diff --git a/.mockery.yaml b/.mockery.yaml index 5554283..0c26451 100644 --- a/.mockery.yaml +++ b/.mockery.yaml @@ -10,3 +10,5 @@ packages: interfaces: NonceGetter: {} KeyResolver: {} + MessageSigner: {} + MessageVerifier: {} diff --git a/README.md b/README.md index c815f63..51947da 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,17 @@ ## Introduction and Scope -`httpsig` is a library for signing and verifying HTTP requests and responses according to [RFC 9421 (HTTP Message Signatures)](https://www.rfc-editor.org/rfc/rfc9421.html). It combines reusable signing and verification policies with support for application-specific signature requirements and signature negotiation using `Accept-Signature`. +`httpsig` is a library for signing and verifying HTTP requests and responses according to [RFC 9421 (HTTP Message Signatures)](https://www.rfc-editor.org/rfc/rfc9421.html). -The `Message` abstraction keeps these capabilities independent of any particular HTTP framework. For API details and option semantics, see the [Go reference](https://pkg.go.dev/github.com/dadrus/httpsig). +Its key features include: + +- **Policy-based signing and verification:** Reusable policies for covered components, signature parameters, tags, and validity constraints. +- **Message integrity:** Automatic generation and verification of `Content-Digest` to protect HTTP message bodies. +- **Signature negotiation:** Support for requesting signatures via `Accept-Signature` and deriving signature requirements from verification policies. +- **Framework independence:** A `Message` abstraction that enables integration with `net/http`, Fiber, other HTTP frameworks, and proxy-based services. +- **Cryptographic agility:** Support for custom signing and verification implementations, allowing applications to use cryptographic algorithms and key management systems (HSMs and KMSs) independently of the library's built-in support (see [Cryptographic Agility](#cryptographic-agility)). + +For API details and option semantics, see the [Go reference](https://pkg.go.dev/github.com/dadrus/httpsig). For known limitations and the current scope of RFC 9421 support, see [Limitations and Compliance](#limitations-and-compliance). ## Usage @@ -264,6 +272,125 @@ For automatic negotiation, the configured `NonceGetter` runs while `Verify` prep A `Signer` or `Verifier` represents a reusable signing or verification policy. Create an instance once per policy and reuse it across messages. This allows most of the configuration work to happen upfront, keeping the per-message overhead low. Message-specific values can be supplied through per-call options. +## Cryptographic Agility + +`httpsig` supports custom signing and verification implementations through the `MessageSigner` and `MessageVerifier` interfaces. This allows applications to use cryptographic algorithms (e.g., PQC) and key management systems (HSMs and KMSs) independently of the library's built-in support. + +The library constructs the [RFC 9421](https://www.rfc-editor.org/rfc/rfc9421.html) signature base and passes it unchanged to the application-provided implementation, which is responsible for the entire cryptographic operation, including hashing and signature encoding. + +### ML-DSA + +The following example demonstrates how to use ML-DSA, available in the Go standard library since Go 1.27, without requiring `httpsig` itself to target that Go version. + +First, define adapters for signing and verification: + +```go +type mlDSASigner mldsa.PrivateKey + +func (s *mlDSASigner) SignMessage(_ context.Context, message []byte) ([]byte, error) { + return (*mldsa.PrivateKey)(s).Sign(nil, message, &mldsa.Options{}) +} + +type mlDSAVerifier mldsa.PublicKey + +func (v *mlDSAVerifier) VerifyMessage(_ context.Context, message, signature []byte) error { + return mldsa.Verify((*mldsa.PublicKey)(v), message, signature, &mldsa.Options{}) +} +``` + +These adapters can then be used directly with the existing signing and verification APIs: + +```go +// Generate an ML-DSA key pair. +privateKey, err := mldsa.GenerateKey(mldsa.MLDSA44()) +// error handling + +// Create a signer. +signer, err := httpsig.NewSigner( + httpsig.Key{ + Material: (*mlDSASigner)(privateKey), + Algorithm: "ml-dsa-44", + }, + httpsig.WithKeyID("demo-ml-dsa-44"), + httpsig.WithAlg(), + httpsig.WithComponents("@method", "@path"), +) +// error handling + +req, err := ... // create the request + +// Sign the request. +req.Header, err = signer.Sign(httpsig.MessageFromRequest(req)) +// error handling + +// Create a verifier. +verifier, err := httpsig.NewVerifier( + httpsig.Key{ + Material: (*mlDSAVerifier)(privateKey.PublicKey()), + Algorithm: "ml-dsa-44", + }, + httpsig.WithValidateAllSignatures(), + httpsig.WithComponents("@method", "@path"), +) +// error handling + +// Verify the request. +result, err := verifier.Verify(httpsig.MessageFromRequest(req)) +// error handling +``` + +### AWS KMS + +The same approach works with external key management systems such as AWS KMS. The application-provided adapter handles the KMS interaction and any required cryptographic processing. + +For example, an ECDSA signer backed by AWS KMS could look like this: + +```go +type awsMessageSigner struct { + client *kms.Client + keyID string +} + +func (s awsMessageSigner) SignMessage(ctx context.Context, message []byte) ([]byte, error) { + digest := sha256.Sum256(message) + + response, err := s.client.Sign(ctx, &kms.SignInput{ + KeyId: &s.keyID, + Message: digest[:], + MessageType: types.MessageTypeDigest, + SigningAlgorithm: types.SigningAlgorithmSpecEcdsaSha256, + }) + if err != nil { + return nil, err + } + + // Convert the ASN.1 DER-encoded ECDSA signature returned by AWS KMS to r || s. + return ecdsaSignatureToRaw(response.Signature) +} +``` + +The adapter can then be passed to `httpsig` like any other signing key: + +```go +client := ... // create the AWS KMS client +keyID := ... // obtain the key ID + +signer, err := httpsig.NewSigner( + httpsig.Key{ + Material: awsMessageSigner{client: client, keyID: keyID}, + Algorithm: httpsig.EcdsaP256Sha256, + }, + httpsig.WithKeyID(keyID), + httpsig.WithComponents("@method", "@path"), +) +// error handling + +req, err := ... // create the request + +req.Header, err = signer.Sign(httpsig.MessageFromRequest(req)) +// error handling +``` + ## Protocols and Profiles ### WIMSE Workload-to-Workload HTTP Signatures @@ -474,4 +601,17 @@ app.Use(func(c fiber.Ctx) error { * **Replay:** Enforce the required nonce checks after successful signature verification. * **Multiple signatures:** Labels are not signed, and `VerificationResult` has no defined order. Choose the required tags or validate all signatures as appropriate. -See [RFC 9421 Security Considerations](https://www.rfc-editor.org/rfc/rfc9421.html#section-7). +See also [RFC 9421 Security Considerations](https://www.rfc-editor.org/rfc/rfc9421.html#section-7). + +## Limitations and Compliance + +### RFC 9421 Compliance + +Following are the known limitations and deviations: + +- **HTTP trailers:** The `;tr` component identifier parameter is not supported. `Signature` and `Signature-Input` fields cannot be processed as trailers. +- **Signature negotiation:** Generating `Accept-Signature` is supported, but parsing received `Accept-Signature` fields is not yet implemented. + +### Other Limitations + +- **Body streaming:** `Content-Digest` generation and verification currently require buffering the complete message body in memory. Streaming digest calculation is not yet supported. \ No newline at end of file diff --git a/httpsig.go b/httpsig.go index 3808efa..c4bff40 100644 --- a/httpsig.go +++ b/httpsig.go @@ -103,9 +103,10 @@ const ( ) // SignatureAlgorithm identifies the concrete cryptographic algorithm used -// to create or verify an HTTP message signature. The supported algorithms -// are the constants below; the selected algorithm must be compatible with -// the supplied Key.Material. +// to create or verify an HTTP message signature. The constants below are +// supported by the built-in implementations. Other algorithms can be used +// with an application-provided MessageSigner or MessageVerifier. The selected +// algorithm must be compatible with the supplied Key.Material. type SignatureAlgorithm string const ( @@ -239,17 +240,36 @@ func (p SignatureParameters) Tag() (string, bool) { // strings when validating profile-specific signature parameters. type Token string +// MessageSigner signs the complete HTTP signature base using an +// application-provided implementation. The implementation is responsible for +// all cryptographic processing and must return signature bytes in the format +// required by the selected HTTP Message Signatures algorithm. +// Context is supplied by the message being signed. +type MessageSigner interface { + SignMessage(ctx context.Context, message []byte) ([]byte, error) +} + +// MessageVerifier verifies the complete HTTP signature base using an +// application-provided implementation. The signature bytes are passed through +// unchanged; the implementation is responsible for the algorithm and encoding. +// Context is supplied by the message being verified. +type MessageVerifier interface { + VerifyMessage(ctx context.Context, message, signature []byte) error +} + // Key combines cryptographic key material with the concrete signature -// algorithm to use. Signing requires private or symmetric key material; -// verification requires public or symmetric key material. +// algorithm to use. Signing requires private or symmetric key material (or +// a signer interface); verification requires public or symmetric key material +// (or a verifier interface). type Key struct { // Algorithm is the signature algorithm to use with Material. // It must be compatible with the supplied key material. Algorithm SignatureAlgorithm // Material is the private, public, or symmetric key material used by the - // chosen algorithm. The currently supported implementations accept the - // corresponding Go crypto key types or []byte for HMAC. + // chosen algorithm. The built-in implementations accept the + // corresponding Go crypto key types or []byte for HMAC. Applications + // may also provide a MessageSigner or MessageVerifier implementation. Material any } diff --git a/mock_message_signer_test.go b/mock_message_signer_test.go new file mode 100644 index 0000000..2f9ff66 --- /dev/null +++ b/mock_message_signer_test.go @@ -0,0 +1,115 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package httpsig + +import ( + "context" + + mock "github.com/stretchr/testify/mock" +) + +// NewMessageSignerMock creates a new instance of MessageSignerMock. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMessageSignerMock(t interface { + mock.TestingT + Cleanup(func()) +}) *MessageSignerMock { + if helper, ok := t.(interface{ Helper() }); ok { + helper.Helper() + } + + mock := &MessageSignerMock{} + mock.Mock.Test(t) + + t.Cleanup(func() { + if helper, ok := t.(interface{ Helper() }); ok { + helper.Helper() + } + mock.AssertExpectations(t) + }) + + return mock +} + +// MessageSignerMock is an autogenerated mock type for the MessageSigner type +type MessageSignerMock struct { + mock.Mock +} + +type MessageSignerMock_Expecter struct { + mock *mock.Mock +} + +func (_m *MessageSignerMock) EXPECT() *MessageSignerMock_Expecter { + return &MessageSignerMock_Expecter{mock: &_m.Mock} +} + +// SignMessage provides a mock function for the type MessageSignerMock +func (_mock *MessageSignerMock) SignMessage(ctx context.Context, message []byte) ([]byte, error) { + ret := _mock.Called(ctx, message) + + if len(ret) == 0 { + panic("no return value specified for SignMessage") + } + + var r0 []byte + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, []byte) ([]byte, error)); ok { + return returnFunc(ctx, message) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, []byte) []byte); ok { + r0 = returnFunc(ctx, message) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]byte) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, []byte) error); ok { + r1 = returnFunc(ctx, message) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// MessageSignerMock_SignMessage_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SignMessage' +type MessageSignerMock_SignMessage_Call struct { + *mock.Call +} + +// SignMessage is a helper method to define mock.On call +// - ctx context.Context +// - message []byte +func (_e *MessageSignerMock_Expecter) SignMessage(ctx any, message any) *MessageSignerMock_SignMessage_Call { + return &MessageSignerMock_SignMessage_Call{Call: _e.mock.On("SignMessage", ctx, message)} +} + +func (_c *MessageSignerMock_SignMessage_Call) Run(run func(ctx context.Context, message []byte)) *MessageSignerMock_SignMessage_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *MessageSignerMock_SignMessage_Call) Return(bytes []byte, err error) *MessageSignerMock_SignMessage_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *MessageSignerMock_SignMessage_Call) RunAndReturn(run func(ctx context.Context, message []byte) ([]byte, error)) *MessageSignerMock_SignMessage_Call { + _c.Call.Return(run) + return _c +} diff --git a/mock_message_verifier_test.go b/mock_message_verifier_test.go new file mode 100644 index 0000000..dce6ebb --- /dev/null +++ b/mock_message_verifier_test.go @@ -0,0 +1,110 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package httpsig + +import ( + "context" + + mock "github.com/stretchr/testify/mock" +) + +// NewMessageVerifierMock creates a new instance of MessageVerifierMock. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMessageVerifierMock(t interface { + mock.TestingT + Cleanup(func()) +}) *MessageVerifierMock { + if helper, ok := t.(interface{ Helper() }); ok { + helper.Helper() + } + + mock := &MessageVerifierMock{} + mock.Mock.Test(t) + + t.Cleanup(func() { + if helper, ok := t.(interface{ Helper() }); ok { + helper.Helper() + } + mock.AssertExpectations(t) + }) + + return mock +} + +// MessageVerifierMock is an autogenerated mock type for the MessageVerifier type +type MessageVerifierMock struct { + mock.Mock +} + +type MessageVerifierMock_Expecter struct { + mock *mock.Mock +} + +func (_m *MessageVerifierMock) EXPECT() *MessageVerifierMock_Expecter { + return &MessageVerifierMock_Expecter{mock: &_m.Mock} +} + +// VerifyMessage provides a mock function for the type MessageVerifierMock +func (_mock *MessageVerifierMock) VerifyMessage(ctx context.Context, message []byte, signature []byte) error { + ret := _mock.Called(ctx, message, signature) + + if len(ret) == 0 { + panic("no return value specified for VerifyMessage") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(context.Context, []byte, []byte) error); ok { + r0 = returnFunc(ctx, message, signature) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// MessageVerifierMock_VerifyMessage_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'VerifyMessage' +type MessageVerifierMock_VerifyMessage_Call struct { + *mock.Call +} + +// VerifyMessage is a helper method to define mock.On call +// - ctx context.Context +// - message []byte +// - signature []byte +func (_e *MessageVerifierMock_Expecter) VerifyMessage(ctx any, message any, signature any) *MessageVerifierMock_VerifyMessage_Call { + return &MessageVerifierMock_VerifyMessage_Call{Call: _e.mock.On("VerifyMessage", ctx, message, signature)} +} + +func (_c *MessageVerifierMock_VerifyMessage_Call) Run(run func(ctx context.Context, message []byte, signature []byte)) *MessageVerifierMock_VerifyMessage_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + var arg2 []byte + if args[2] != nil { + arg2 = args[2].([]byte) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *MessageVerifierMock_VerifyMessage_Call) Return(err error) *MessageVerifierMock_VerifyMessage_Call { + _c.Call.Return(err) + return _c +} + +func (_c *MessageVerifierMock_VerifyMessage_Call) RunAndReturn(run func(ctx context.Context, message []byte, signature []byte) error) *MessageVerifierMock_VerifyMessage_Call { + _c.Call.Return(run) + return _c +} diff --git a/signer.go b/signer.go index 2ef35c8..a4f0300 100644 --- a/signer.go +++ b/signer.go @@ -26,6 +26,8 @@ func newPayloadSigner(signingKey any, alg SignatureAlgorithm) (payloadSigner, er return newECDSASigner(key, alg) case []byte: return newSymmetricSigner(key, alg) + case MessageSigner: + return &messageSignerAdaptor{signer: key}, nil default: return nil, ErrUnsupportedKeyType } @@ -42,7 +44,7 @@ type Signer interface { } // NewSigner creates a Signer using key for cryptographic signing. The key -// must contain private or symmetric material compatible with its algorithm. +// must contain compatible private, symmetric, or application-provided signing material. // By default, signatures use label "sig", include created, and expire // after 30 seconds. The alg, keyid, tag, and nonce parameters are omitted. // When generating Content-Digest, the signer uses both SHA-256 and SHA-512 @@ -73,8 +75,13 @@ func NewSigner(key Key, opts ...SignerOption) (Signer, error) { switch key.Algorithm { case RsaPssSha512, RsaPkcs1v15Sha256, HmacSha256, EcdsaP256Sha256, EcdsaP384Sha384, Ed25519: default: - return nil, fmt.Errorf("%w: %s is not registered for HTTP Message Signatures", - ErrUnsupportedAlgorithm, key.Algorithm) + // Message signers may use algorithms unknown to httpsig. + switch key.Material.(type) { + case MessageSigner: + default: + return nil, fmt.Errorf("%w: %s is not registered for HTTP Message Signatures", + ErrUnsupportedAlgorithm, key.Algorithm) + } } } diff --git a/signer_adaptor.go b/signer_adaptor.go new file mode 100644 index 0000000..b14c334 --- /dev/null +++ b/signer_adaptor.go @@ -0,0 +1,11 @@ +package httpsig + +import "context" + +type messageSignerAdaptor struct { + signer MessageSigner +} + +func (s *messageSignerAdaptor) sign(ctx context.Context, payload []byte) ([]byte, error) { + return s.signer.SignMessage(ctx, payload) +} diff --git a/signer_adaptor_test.go b/signer_adaptor_test.go new file mode 100644 index 0000000..84879db --- /dev/null +++ b/signer_adaptor_test.go @@ -0,0 +1,49 @@ +package httpsig + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestMessageSignerAdaptorSign(t *testing.T) { + t.Parallel() + + message := []byte("signature base") + signingErr := errors.New("signing failed") + + for uc, tc := range map[string]struct { + signature []byte + signErr error + assert func(t *testing.T, signature []byte, err error) + }{ + "returns signature unchanged": { + signature: []byte("signature"), + assert: func(t *testing.T, signature []byte, err error) { + t.Helper() + require.NoError(t, err) + assert.Equal(t, []byte("signature"), signature) + }, + }, + "propagates signing error": { + signErr: signingErr, + assert: func(t *testing.T, signature []byte, err error) { + t.Helper() + require.ErrorIs(t, err, signingErr) + assert.Nil(t, signature) + }, + }, + } { + t.Run(uc, func(t *testing.T) { + mockSigner := NewMessageSignerMock(t) + mockSigner.EXPECT().SignMessage(t.Context(), message). + Return(tc.signature, tc.signErr).Once() + + signer := &messageSignerAdaptor{signer: mockSigner} + signature, err := signer.sign(t.Context(), message) + tc.assert(t, signature, err) + }) + } +} diff --git a/signer_test.go b/signer_test.go index fc3a76d..10c2408 100644 --- a/signer_test.go +++ b/signer_test.go @@ -40,25 +40,25 @@ func TestNewPayloadSigner(t *testing.T) { require.NoError(t, err) require.Equal(t, len(k256), n) - for _, tc := range []struct { - uc string + for uc, tc := range map[string]struct { key any alg SignatureAlgorithm typ any err error }{ - {uc: "unsupported algorithm", key: "foo", err: ErrUnsupportedKeyType}, - {uc: "ed25519 signer", key: ek25519, alg: Ed25519, typ: &ed25519Signer{}}, - {uc: "rsa signer", key: pk2048, alg: RsaPssSha256, typ: &rsaSigner{}}, - {uc: "ecdsa signer", key: pkp256, alg: EcdsaP256Sha256, typ: &ecdsaSigner{}}, - {uc: "hmac signer", key: k256, alg: HmacSha256, typ: &symmetricSigner{}}, + "unsupported key type": {key: "foo", err: ErrUnsupportedKeyType}, + "ed25519 signer": {key: ek25519, alg: Ed25519, typ: &ed25519Signer{}}, + "rsa signer": {key: pk2048, alg: RsaPssSha256, typ: &rsaSigner{}}, + "ecdsa signer": {key: pkp256, alg: EcdsaP256Sha256, typ: &ecdsaSigner{}}, + "hmac signer": {key: k256, alg: HmacSha256, typ: &symmetricSigner{}}, + "message signer": {key: &MessageSignerMock{}, alg: SignatureAlgorithm("custom-alg"), typ: &messageSignerAdaptor{}}, } { - t.Run(tc.uc, func(t *testing.T) { + t.Run(uc, func(t *testing.T) { sig, err := newPayloadSigner(tc.key, tc.alg) if tc.err != nil { - require.Error(t, err) require.ErrorIs(t, err, tc.err) + assert.Nil(t, sig) } else { require.NoError(t, err) require.NotNil(t, sig) @@ -110,6 +110,17 @@ func TestNewSigner(t *testing.T) { require.ErrorIs(t, err, ErrUnsupportedAlgorithm) }, }, + { + uc: "unknown algorithm with message signer", + key: Key{Algorithm: SignatureAlgorithm("custom-alg"), Material: &MessageSignerMock{}}, + opts: []SignerOption{WithAlg()}, + assert: func(t *testing.T, err error, s Signer) { + t.Helper() + + require.NoError(t, err) + assert.NotNil(t, s) + }, + }, { uc: "reserved signature parameter", key: Key{Algorithm: EcdsaP384Sha384, Material: pkp384}, diff --git a/verifier.go b/verifier.go index 2b4aa96..35e4d9d 100644 --- a/verifier.go +++ b/verifier.go @@ -117,6 +117,8 @@ func newPayloadVerifier(verificationKey any, alg SignatureAlgorithm) (payloadVer return newECDSAVerifier(publicKey, alg) case []byte: return newSymmetricSigner(publicKey, alg) + case MessageVerifier: + return &messageVerifierAdaptor{verifier: publicKey}, nil default: return nil, ErrUnsupportedKeyType } diff --git a/verifier_adaptor.go b/verifier_adaptor.go new file mode 100644 index 0000000..cffd6d2 --- /dev/null +++ b/verifier_adaptor.go @@ -0,0 +1,11 @@ +package httpsig + +import "context" + +type messageVerifierAdaptor struct { + verifier MessageVerifier +} + +func (v *messageVerifierAdaptor) verify(ctx context.Context, payload, signature []byte) error { + return v.verifier.VerifyMessage(ctx, payload, signature) +} diff --git a/verifier_adaptor_test.go b/verifier_adaptor_test.go new file mode 100644 index 0000000..dcd9318 --- /dev/null +++ b/verifier_adaptor_test.go @@ -0,0 +1,46 @@ +package httpsig + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestMessageVerifierAdaptorVerify(t *testing.T) { + t.Parallel() + + message := []byte("signature base") + verificationErr := errors.New("verification failed") + + for uc, tc := range map[string]struct { + signature []byte + verifyErr error + assert func(t *testing.T, err error) + }{ + "verifies signature": { + signature: []byte("signature"), + assert: func(t *testing.T, err error) { + t.Helper() + require.NoError(t, err) + }, + }, + "propagates verification error": { + signature: []byte("signature"), + verifyErr: verificationErr, + assert: func(t *testing.T, err error) { + t.Helper() + require.ErrorIs(t, err, verificationErr) + }, + }, + } { + t.Run(uc, func(t *testing.T) { + mockVerifier := NewMessageVerifierMock(t) + mockVerifier.EXPECT().VerifyMessage(t.Context(), message, tc.signature). + Return(tc.verifyErr).Once() + + verifier := &messageVerifierAdaptor{verifier: mockVerifier} + tc.assert(t, verifier.verify(t.Context(), message, tc.signature)) + }) + } +} diff --git a/verifier_test.go b/verifier_test.go index 297619e..55989f9 100644 --- a/verifier_test.go +++ b/verifier_test.go @@ -54,6 +54,7 @@ func TestNewPayloadVerifier(t *testing.T) { "rsa verifier": {key: &pk2048.PublicKey, alg: RsaPssSha256, typ: &rsaVerifier{}}, "ecdsa verifier": {key: &pkp256.PublicKey, alg: EcdsaP256Sha256, typ: &ecdsaVerifier{}}, "hmac verifier": {key: k256, alg: HmacSha256, typ: &symmetricSigner{}}, + "message verifier": {key: &MessageVerifierMock{}, alg: SignatureAlgorithm("custom-alg"), typ: &messageVerifierAdaptor{}}, } { t.Run(uc, func(t *testing.T) { sig, err := newPayloadVerifier(tc.key, tc.alg) @@ -970,6 +971,42 @@ func TestVerifierVerify(t *testing.T) { require.Empty(t, results) }, }, + "unknown algorithm with message verifier": { + opts: []VerifierOption{ + WithValidateAllSignatures(), + WithCreatedTimestamp(false), + WithExpiresTimestamp(false), + }, + msg: &Message{ + Context: context.Background(), + IsRequest: true, + Method: http.MethodGet, + Header: http.Header{ + "Signature-Input": []string{`sig=("@method");alg="custom-alg"`}, + "Signature": []string{"sig=:AQID:"}, + }, + }, + configureResolver: func(t *testing.T, kr *KeyResolverMock) { + t.Helper() + + mockVerifier := NewMessageVerifierMock(t) + mockVerifier.EXPECT().VerifyMessage( + context.Background(), + []byte("\"@method\": GET\n\"@signature-params\": (\"@method\");alg=\"custom-alg\""), + []byte{1, 2, 3}, + ).Return(nil).Once() + + kr.EXPECT().ResolveKey(mock.Anything, mock.Anything). + Return(KeyInfo{Key: Key{Algorithm: SignatureAlgorithm("custom-alg"), Material: mockVerifier}}, nil).Once() + }, + assert: func(t *testing.T, err error, results VerificationResult) { + t.Helper() + + require.NoError(t, err) + require.Len(t, results, 1) + assert.Equal(t, "sig", results[0].Label) + }, + }, "unsupported signature key": { opts: []VerifierOption{ WithRequiredTag("foo"),