Skip to content

Commit

Permalink
Fix jws.Verify not respecting the b64 header in the protected headers (
Browse files Browse the repository at this point in the history
…#683)

* Add failing test

* Apply fix from #681
  • Loading branch information
lestrrat committed Apr 8, 2022
1 parent b66a2cb commit e831228
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 10 deletions.
24 changes: 14 additions & 10 deletions jws/jws.go
Expand Up @@ -476,16 +476,6 @@ func (ctx *verifyCtx) verifyCompact(signed []byte) ([]byte, error) {
return nil, errors.Wrap(err, `failed extract from compact serialization format`)
}

verifyBuf := pool.GetBytesBuffer()
defer pool.ReleaseBytesBuffer(verifyBuf)

verifyBuf.Write(protected)
verifyBuf.WriteByte('.')
if len(payload) == 0 && ctx.detachedPayload != nil {
payload = ctx.detachedPayload
}
verifyBuf.Write(payload)

decodedSignature, err := base64.Decode(signature)
if err != nil {
return nil, errors.Wrap(err, `failed to decode signature`)
Expand All @@ -501,6 +491,20 @@ func (ctx *verifyCtx) verifyCompact(signed []byte) ([]byte, error) {
return nil, errors.Wrap(err, `failed to decode headers`)
}

verifyBuf := pool.GetBytesBuffer()
defer pool.ReleaseBytesBuffer(verifyBuf)

verifyBuf.Write(protected)
verifyBuf.WriteByte('.')
if len(payload) == 0 && ctx.detachedPayload != nil {
if getB64Value(hdr) {
payload = base64.Encode(ctx.detachedPayload)
} else {
payload = ctx.detachedPayload
}
}
verifyBuf.Write(payload)

if !ctx.useJKU {
if hdr.KeyID() != "" {
if jwkKey, ok := ctx.key.(jwk.Key); ok {
Expand Down
17 changes: 17 additions & 0 deletions jws/jws_test.go
Expand Up @@ -1778,3 +1778,20 @@ func TestJKU(t *testing.T) {
}
})
}

func TestGH681(t *testing.T) {
privkey, err := jwxtest.GenerateRsaKey()
if !assert.NoError(t, err, "failed to create private key") {
return
}

buf, err := jws.Sign(nil, jwa.RS256, privkey, jws.WithDetachedPayload([]byte("Lorem ipsum")))
if !assert.NoError(t, err, "failed to sign payload") {
return
}

_, err = jws.Verify(buf, jwa.RS256, &privkey.PublicKey, jws.WithDetachedPayload([]byte("Lorem ipsum")))
if !assert.NoError(t, err, "failed to verify JWS message") {
return
}
}

0 comments on commit e831228

Please sign in to comment.