diff --git a/README.md b/README.md index 51947da..40f0e7c 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,16 @@ For API details and option semantics, see the [Go reference](https://pkg.go.dev/ ## Usage +> [!NOTE] +> Component identifiers are represented as [Structured Fields Items](https://www.rfc-editor.org/rfc/rfc9421.html#section-2.5), with quoted component names (for example, `"@method"` or `"content-digest";req`). For convenience, configuration options such as `WithComponents` also accept a simplified form that omits the quotes around the component name. Both forms are equivalent: +> +> ```go +> httpsig.WithComponents(`"@method"`, `"content-digest";req`) // Structured Fields form +> httpsig.WithComponents("@method", "content-digest;req") // simplified form +> ``` +> +> When parsing an `Accept-Signature` header, `httpsig` returns the serialized Structured Fields form in `SignatureRequest.Components`. These values can be passed directly to `WithComponents`. + ### Standalone Signing and Verification The following snippets show two independent flows: signing an outgoing request and verifying a received response. They assume application-provided keys and other values; routine error handling is abbreviated. @@ -205,6 +215,8 @@ nonce := ... // application-generated nonce for this request err = builder.Build(req.Context(), req.Header, httpsig.WithParameter("nonce", nonce)) // error handling goes here + +// send the request ``` This adds an `Accept-Signature` header with a value such as: @@ -216,6 +228,45 @@ Want-Content-Digest: sha-256=2 The `Want-Content-Digest` header is also added because the requested signature covers `content-digest`. +#### Fulfilling a Signature Request + +Use `ParseAcceptSignature` when a peer requests a signature, for example in a `401` response to your request. It takes an `http.Header`, so it works independently of signers and verifiers, and returns one `SignatureRequest` per requested signature: + +```go +requests, err := httpsig.ParseAcceptSignature(resp.Header) +// err reports the members that can't be used; requests holds the usable ones + +msg := httpsig.MessageFromRequest(req) + +for _, request := range requests { + // decide whether the request is acceptable for your application + + signer, err := httpsig.NewSigner( + key, + httpsig.WithLabel(request.Label), + httpsig.WithComponents(request.Components...), + httpsig.WithTag(request.Tag), + ) + // error handling goes here + + var opts []httpsig.SignOption + if request.Nonce != "" { + opts = append(opts, httpsig.WithParameter("nonce", request.Nonce)) + } + + _, err := signer.Sign(msg, opts...) + // error handling goes here + + // ... +} + +req.Header = msg.Header + +// send the request +``` + +`Created` and `Expires` report whether these parameters are requested, as `Accept-Signature` carries no timestamp values. A `Signer` always includes `created`; use `WithTTL` to include `expires`. Parameters not defined by RFC 9421 are available in `Extensions`. If the field as a whole isn't valid Structured Fields, no requests are returned. A malformed member or one with an unsupported component identifier doesn't affect the other members: the usable requests are returned together with a joined error that wraps `ErrMalformedData` for each unusable member. Require `err == nil` if your application must fulfill every request. + #### Requesting Signatures on the Server-Side from the Client On the server side, the `Verifier` can derive `Accept-Signature` requirements from its configured policy. This avoids defining component and parameter requirements separately for verification and negotiation. If a required signature, component, or parameter is missing, `Verify` returns an error wrapping `NoApplicableSignatureError`; use `errors.As` to retrieve it and call `Negotiate` to add the prepared headers to the response. An invalid cryptographic signature is still a verification failure, not a negotiation request. @@ -598,6 +649,7 @@ app.Use(func(c fiber.Ctx) error { * **Coverage:** Require the components your application relies on. For messages with bodies, sign and verify `content-digest` when body integrity matters. * **Key trust:** `KeyResolver` receives unverified message data. Select and validate keys according to your application protocol. +* **Signature requests:** `Accept-Signature` is controlled by the peer. Check the components, key, and parameters of a `SignatureRequest` before signing, so a peer cannot obtain signatures your application did not intend to produce. * **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. @@ -610,7 +662,6 @@ See also [RFC 9421 Security Considerations](https://www.rfc-editor.org/rfc/rfc94 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 diff --git a/accept_signature_builder.go b/accept_signature.go similarity index 51% rename from accept_signature_builder.go rename to accept_signature.go index e105d54..4391a78 100644 --- a/accept_signature_builder.go +++ b/accept_signature.go @@ -2,6 +2,7 @@ package httpsig import ( "context" + "errors" "fmt" "net/http" @@ -142,3 +143,118 @@ func (asb *AcceptSignatureBuilder) setIdentifiers(identifiers []*componentIdenti } } } + +// SignatureRequest describes a single signature requested by a member of an +// Accept-Signature field. All its values are controlled by the peer. The +// application must decide whether a request is acceptable before signing. +type SignatureRequest struct { + // Label is the label of the requested signature. + Label string + + // Components lists the requested component identifiers in their requested + // order, serialized as Structured Fields Items. Each identifier can be + // passed to WithComponents. + Components []string + + // KeyID is the requested keyid parameter. It is empty if not requested. + KeyID string + + // Algorithm is the requested alg parameter. It is empty if not requested. + // It is not checked against the supported signature algorithms. + Algorithm SignatureAlgorithm + + // Tag is the requested tag parameter. It is empty if not requested. + Tag string + + // Nonce is the requested nonce parameter. It is empty if not requested. + Nonce string + + // Created reports whether a created timestamp is requested. + Created bool + + // Expires reports whether an expires timestamp is requested. + Expires bool + + // Extensions contains the requested parameters not defined by RFC 9421. + // It is nil if there are none. Its values are decoded as described for + // SignatureParameters. + Extensions SignatureParameters +} + +// ParseAcceptSignature parses the Accept-Signature fields in header and returns +// the signature requests in the order they appear. It returns an empty result +// if header contains no Accept-Signature field. +// +// If the fields as a whole are not a valid Structured Fields Dictionary, it +// returns no requests and an error wrapping ErrMalformedData. A member that +// cannot be used, for example because it is malformed or names an unsupported +// component, does not affect the other members: the requests of the usable +// members are returned together with a joined error that has an entry wrapping +// ErrMalformedData for each unusable member. RFC 9421 permits ignoring requests +// that cannot be fulfilled, so a non-nil error does not invalidate the returned +// requests. Applications requiring all requests to be usable must check it. +func ParseAcceptSignature(header http.Header) ([]SignatureRequest, error) { + dict, err := httpsfv.UnmarshalDictionary(header.Values(headerAcceptSignature)) + if err != nil { + return nil, fmt.Errorf("%w: %w", ErrMalformedData, err) + } + + labels := dict.Names() + requests := make([]SignatureRequest, 0, len(labels)) + + var errs []error + + for _, label := range labels { + member, _ := dict.Get(label) + + list, ok := member.(httpsfv.InnerList) + if !ok { + errs = append(errs, + fmt.Errorf("%w: unexpected signature request format for label %q", ErrMalformedData, label)) + + continue + } + + request, err := newSignatureRequest(label, list) + if err != nil { + errs = append(errs, fmt.Errorf("%w: label %q: %w", ErrMalformedData, label, err)) + + continue + } + + requests = append(requests, request) + } + + return requests, errors.Join(errs...) +} + +func newSignatureRequest(label string, list httpsfv.InnerList) (SignatureRequest, error) { + var requirements signatureRequirements + + if err := requirements.fromInnerList(list); err != nil { + return SignatureRequest{}, err + } + + components := make([]string, len(requirements.identifiers)) + + for i, identifier := range requirements.identifiers { + component, err := httpsfv.Marshal(identifier.Item) + if err != nil { + return SignatureRequest{}, fmt.Errorf("%w: %w", ErrInvalidComponentIdentifier, err) + } + + components[i] = component + } + + return SignatureRequest{ + Label: label, + Components: components, + KeyID: requirements.keyID, + Algorithm: requirements.alg, + Tag: requirements.tag, + Nonce: requirements.nonce, + Created: requirements.created, + Expires: requirements.expires, + Extensions: requirements.extensions, + }, nil +} diff --git a/accept_signature_builder_test.go b/accept_signature_test.go similarity index 76% rename from accept_signature_builder_test.go rename to accept_signature_test.go index 24d982d..4ac0aef 100644 --- a/accept_signature_builder_test.go +++ b/accept_signature_test.go @@ -6,6 +6,7 @@ import ( "net/http" "testing" + "github.com/dunglas/httpsfv" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -420,3 +421,155 @@ func TestAcceptSignatureBuilderBuild(t *testing.T) { assert.Equal(t, `sig=();created;expires;bytes=:YmVmb3Jl:`, hdr.Get(headerAcceptSignature)) }) } + +func TestNewSignatureRequest(t *testing.T) { + t.Parallel() + + contentDigest := httpsfv.NewItem("content-digest") + contentDigest.Params.Add("req", true) + + queryParam := httpsfv.NewItem("@query-param") + queryParam.Params.Add("name", "a;b") + + params := httpsfv.NewParams() + params.Add(string(Created), true) + params.Add(string(Expires), true) + params.Add(string(KeyID), "test-key") + params.Add(string(Alg), "ed25519") + params.Add(string(Nonce), "abc") + params.Add(string(Tag), "app-123") + params.Add("audience", httpsfv.Token("service-a")) + + for uc, tc := range map[string]struct { + list httpsfv.InnerList + expected SignatureRequest + err error + }{ + "empty request": { + list: httpsfv.InnerList{Params: httpsfv.NewParams()}, + expected: SignatureRequest{Label: "sig", Components: []string{}}, + }, + "serializing component identifiers and copying parameters": { + list: httpsfv.InnerList{ + Items: []httpsfv.Item{httpsfv.NewItem("@method"), contentDigest, queryParam}, + Params: params, + }, + expected: SignatureRequest{ + Label: "sig", + Components: []string{`"@method"`, `"content-digest";req`, `"@query-param";name="a;b"`}, + KeyID: "test-key", + Algorithm: Ed25519, + Tag: "app-123", + Nonce: "abc", + Created: true, + Expires: true, + Extensions: SignatureParameters{"audience": Token("service-a")}, + }, + }, + "invalid component identifier": { + list: httpsfv.InnerList{ + Items: []httpsfv.Item{httpsfv.NewItem("@unsupported")}, + }, + err: ErrUnsupportedComponentIdentifier, + }, + } { + t.Run(uc, func(t *testing.T) { + request, err := newSignatureRequest("sig", tc.list) + if tc.err != nil { + require.ErrorIs(t, err, tc.err) + assert.Equal(t, SignatureRequest{}, request) + + return + } + + require.NoError(t, err) + assert.Equal(t, tc.expected, request) + }) + } +} + +func TestParseAcceptSignature(t *testing.T) { + t.Parallel() + + for uc, tc := range map[string]struct { + values []string + expected []SignatureRequest + err []error + errContains []string + }{ + "no header": { + expected: []SignatureRequest{}, + }, + "single request": { + values: []string{`sig=("@method");tag="app-123"`}, + expected: []SignatureRequest{{Label: "sig", Components: []string{`"@method"`}, Tag: "app-123"}}, + }, + "multiple members keep their order": { + values: []string{`zeta=("@status"), alpha=("@method");tag="a"`}, + expected: []SignatureRequest{ + {Label: "zeta", Components: []string{`"@status"`}}, + {Label: "alpha", Components: []string{`"@method"`}, Tag: "a"}, + }, + }, + "multiple field lines": { + values: []string{`a=("@status")`, `b=("@method")`}, + expected: []SignatureRequest{ + {Label: "a", Components: []string{`"@status"`}}, + {Label: "b", Components: []string{`"@method"`}}, + }, + }, + "invalid structured fields": { + values: []string{`good=("@status"), (`}, + err: []error{ErrMalformedData}, + }, + "member is not an inner list": { + values: []string{`sig="@status"`}, + expected: []SignatureRequest{}, + err: []error{ErrMalformedData}, + }, + "unusable member keeps the usable ones": { + values: []string{`first=("@status"), bad=("@foo"), last=("@method")`}, + expected: []SignatureRequest{ + {Label: "first", Components: []string{`"@status"`}}, + {Label: "last", Components: []string{`"@method"`}}, + }, + err: []error{ErrMalformedData, ErrUnsupportedComponentIdentifier}, + }, + "every unusable member is reported": { + values: []string{`good=("@status"), scalar=1, comp=("@foo"), param=();created=1`}, + expected: []SignatureRequest{{Label: "good", Components: []string{`"@status"`}}}, + err: []error{ + ErrMalformedData, + ErrUnsupportedComponentIdentifier, + ErrMalformedSignatureParameter, + }, + errContains: []string{`"scalar"`, `"comp"`, `"param"`}, + }, + } { + t.Run(uc, func(t *testing.T) { + t.Parallel() + + header := http.Header{} + for _, value := range tc.values { + header.Add(headerAcceptSignature, value) + } + + requests, err := ParseAcceptSignature(header) + assert.Equal(t, tc.expected, requests) + + if len(tc.err) == 0 { + require.NoError(t, err) + + return + } + + for _, expected := range tc.err { + require.ErrorIs(t, err, expected) + } + + for _, expected := range tc.errContains { + require.ErrorContains(t, err, expected) + } + }) + } +} diff --git a/canonicalizer.go b/canonicalizer.go index 98c35d6..1feb41c 100644 --- a/canonicalizer.go +++ b/canonicalizer.go @@ -52,7 +52,7 @@ func assertParameter(name string, params *httpsfv.Params, isRequest bool) error } //nolint:cyclop -func canonicalizerFor(name string) (canonicalizer, error) { +func canonicalizerFor(name string, params *httpsfv.Params) (canonicalizer, error) { switch name { case "@method": return canonicalizerFunc(canonicalizeMethod), nil @@ -69,6 +69,19 @@ func canonicalizerFor(name string) (canonicalizer, error) { case "@query": return canonicalizerFunc(canonicalizeQuery), nil case "@query-param": + if params == nil { + return nil, fmt.Errorf("%w: @query-param requires a 'name' parameter", ErrInvalidComponentIdentifier) + } + + value, present := params.Get("name") + if !present { + return nil, fmt.Errorf("%w: @query-param requires a 'name' parameter", ErrInvalidComponentIdentifier) + } + + if _, ok := value.(string); !ok { + return nil, fmt.Errorf("%w: @query-param 'name' must be a string", ErrInvalidComponentIdentifier) + } + return canonicalizerFunc(canonicalizeQueryParam), nil case "@status": return canonicalizerFunc(canonicalizeStatusCode), nil @@ -174,17 +187,8 @@ func canonicalizeQueryParam(msg *Message, params *httpsfv.Params) ([]string, err return nil, err } - val, ok := params.Get("name") - if !ok { - return nil, fmt.Errorf("%w: %w: @query-param must have a named parameter", - ErrCanonicalization, ErrInvalidComponentIdentifier) - } - - name, ok := val.(string) - if !ok { - return nil, fmt.Errorf("%w: %w: @query-param 'name' must be a string", - ErrCanonicalization, ErrInvalidComponentIdentifier) - } + val, _ := params.Get("name") + name := val.(string) //nolint: forcetypeassert query := msg.queryParams() if !query.Has(name) { diff --git a/canonicalizer_test.go b/canonicalizer_test.go index 87f936e..5df4c8f 100644 --- a/canonicalizer_test.go +++ b/canonicalizer_test.go @@ -14,33 +14,44 @@ import ( func TestCanonicalizerFor(t *testing.T) { t.Parallel() - for _, tc := range []struct { - name string - err bool + queryParams := httpsfv.NewParams() + queryParams.Add("name", "foo") + + nonStringQueryParams := httpsfv.NewParams() + nonStringQueryParams.Add("name", httpsfv.Token("foo")) + + for uc, tc := range map[string]struct { + name string + params *httpsfv.Params + err error }{ - {"@method", false}, - {"@target-uri", false}, - {"@authority", false}, - {"@scheme", false}, - {"@request-target", false}, - {"@path", false}, - {"@query", false}, - {"@query-param", false}, - {"@status", false}, - {"@foo", true}, - {"x-foo-bar", false}, + "@method": {name: "@method"}, + "@target-uri": {name: "@target-uri"}, + "@authority": {name: "@authority"}, + "@scheme": {name: "@scheme"}, + "@request-target": {name: "@request-target"}, + "@path": {name: "@path"}, + "@query": {name: "@query"}, + "@query-param": {name: "@query-param", params: queryParams}, + "@query-param without name": {name: "@query-param", params: httpsfv.NewParams(), err: ErrInvalidComponentIdentifier}, + "@query-param with non-string name": {name: "@query-param", params: nonStringQueryParams, err: ErrInvalidComponentIdentifier}, + "@status": {name: "@status"}, + "@foo": {name: "@foo", err: ErrUnsupportedComponentIdentifier}, + "x-foo-bar": {name: "x-foo-bar"}, } { - t.Run(tc.name, func(t *testing.T) { - c, err := canonicalizerFor(tc.name) + t.Run(uc, func(t *testing.T) { + c, err := canonicalizerFor(tc.name, tc.params) - if tc.err { - require.Error(t, err) - require.ErrorIs(t, err, ErrUnsupportedComponentIdentifier) + if tc.err != nil { + require.ErrorIs(t, err, tc.err) require.ErrorContains(t, err, tc.name) - } else { - require.NoError(t, err) - assert.NotNil(t, c) + assert.Nil(t, c) + + return } + + require.NoError(t, err) + assert.NotNil(t, c) }) } } @@ -469,28 +480,6 @@ func TestCanonicalization(t *testing.T) { require.ErrorContains(t, err, "occurs multiple times") }, }, - "@query-param for request - invalid, without required name parameter": { - identifier: `"@query-param"`, - message: &Message{URL: testURL1, IsRequest: true}, - assert: func(t *testing.T, err error, _ []string) { - t.Helper() - - require.Error(t, err) - require.ErrorIs(t, err, ErrCanonicalization) - require.ErrorContains(t, err, "named parameter") - }, - }, - "@query-param for request - invalid token name parameter": { - identifier: `"@query-param";name=foo`, - message: &Message{URL: testURL1, IsRequest: true}, - assert: func(t *testing.T, err error, _ []string) { - t.Helper() - - require.Error(t, err) - require.ErrorIs(t, err, ErrInvalidComponentIdentifier) - require.ErrorContains(t, err, "must be a string") - }, - }, "@query-param for request - invalid, parameter not present in query": { identifier: `"@query-param";name="moo"`, message: &Message{URL: testURL1, IsRequest: true}, @@ -634,7 +623,7 @@ func TestCanonicalization(t *testing.T) { item, err := httpsfv.UnmarshalItem([]string{tc.identifier}) require.NoError(t, err) - c, err := canonicalizerFor(strings.ToLower(item.Value.(string))) + c, err := canonicalizerFor(strings.ToLower(item.Value.(string)), item.Params) require.NoError(t, err) res, err := c.canonicalize(tc.message, item.Params) diff --git a/component_identifier.go b/component_identifier.go index 70f7a6b..aa7b9e4 100644 --- a/component_identifier.go +++ b/component_identifier.go @@ -1,6 +1,7 @@ package httpsig import ( + "bytes" "fmt" "strings" @@ -64,7 +65,7 @@ func newComponentIdentifier(item httpsfv.Item) (*componentIdentifier, error) { return nil, fmt.Errorf("%w: component name %q must be lowercase", ErrInvalidComponentIdentifier, name) } - canonicalizer, err := canonicalizerFor(name) + canonicalizer, err := canonicalizerFor(name, item.Params) if err != nil { return nil, err } @@ -72,6 +73,25 @@ func newComponentIdentifier(item httpsfv.Item) (*componentIdentifier, error) { return &componentIdentifier{Item: item, c: canonicalizer}, nil } +// equal reports whether two component identifiers have the same name and +// parameters, regardless of parameter order. +func (c *componentIdentifier) equal(other *componentIdentifier) bool { + if c.Value != other.Value || len(c.Params.Names()) != len(other.Params.Names()) { + return false + } + + for _, name := range c.Params.Names() { + actual, present := other.Params.Get(name) + expected, _ := c.Params.Get(name) + + if !present || !equalComponentParameterValues(actual, expected) { + return false + } + } + + return true +} + func (c *componentIdentifier) createComponent(msg *Message) (component, error) { values, err := c.c.canonicalize(msg, c.Params) if err != nil { @@ -80,3 +100,13 @@ func (c *componentIdentifier) createComponent(msg *Message) (component, error) { return component{key: c, value: values}, nil } + +func equalComponentParameterValues(actual, expected any) bool { + if expectedBytes, ok := expected.([]byte); ok { + actualBytes, ok := actual.([]byte) + + return ok && bytes.Equal(actualBytes, expectedBytes) + } + + return actual == expected +} diff --git a/component_identifier_test.go b/component_identifier_test.go index df4e4f3..896e99b 100644 --- a/component_identifier_test.go +++ b/component_identifier_test.go @@ -51,15 +51,6 @@ func TestToComponentIdentifiers(t *testing.T) { require.ErrorIs(t, err, ErrUnsupportedComponentIdentifier) }, }, - "content identifier must be lowercase": { - identifiers: []string{"Content-Digest"}, - assert: func(t *testing.T, ci []*componentIdentifier, err error) { - t.Helper() - - require.ErrorIs(t, err, ErrInvalidComponentIdentifier) - assert.Nil(t, ci) - }, - }, "preserving structured field parameter types": { identifiers: []string{`x-test;string="abc";token=abc;bytes=:AQID:`}, assert: func(t *testing.T, ci []*componentIdentifier, err error) { @@ -79,11 +70,6 @@ func TestToComponentIdentifiers(t *testing.T) { bytesValue, ok := ci[0].Params.Get("bytes") require.True(t, ok) assert.Equal(t, []byte{1, 2, 3}, bytesValue) - - input := newSignatureInput(ci, nil) - marshalled, err := httpsfv.Marshal(input.value) - require.NoError(t, err) - assert.Equal(t, `("x-test";string="abc";token=abc;bytes=:AQID:)`, marshalled) }, }, "valid": { @@ -145,6 +131,15 @@ func TestNewComponentIdentifier(t *testing.T) { require.ErrorIs(t, err, ErrUnsupportedComponentIdentifier) }, }, + "uppercase component name": { + item: httpsfv.NewItem("Content-Type"), + assert: func(t *testing.T, ci *componentIdentifier, err error) { + t.Helper() + + require.ErrorIs(t, err, ErrInvalidComponentIdentifier) + assert.Nil(t, ci) + }, + }, "valid": { item: func() httpsfv.Item { item := httpsfv.NewItem("@method") @@ -172,6 +167,82 @@ func TestNewComponentIdentifier(t *testing.T) { } } +func TestComponentIdentifierEqual(t *testing.T) { + t.Parallel() + + for uc, tc := range map[string]struct { + first string + second string + equal bool + }{ + "same identifier with reordered parameters": { + first: `x-test;key="foo";sf`, + second: `x-test;sf;key="foo"`, + equal: true, + }, + "different names": { + first: `x-first`, + second: `x-second`, + }, + "different parameter names": { + first: `x-test;first="foo"`, + second: `x-test;second="foo"`, + }, + "different parameter counts": { + first: `x-test;req`, + second: `x-test`, + }, + "different parameter values": { + first: `x-test;key="foo"`, + second: `x-test;key="bar"`, + }, + } { + t.Run(uc, func(t *testing.T) { + identifiers, err := toComponentIdentifiers([]string{tc.first, tc.second}) + require.NoError(t, err) + + assert.Equal(t, tc.equal, identifiers[0].equal(identifiers[1])) + }) + } +} + +func TestEqualComponentParameterValues(t *testing.T) { + t.Parallel() + + for uc, tc := range map[string]struct { + actual any + expected any + equal bool + }{ + "equal byte sequences": { + actual: []byte{1, 2, 3}, + expected: []byte{1, 2, 3}, + equal: true, + }, + "different byte sequences": { + actual: []byte{1, 2, 4}, + expected: []byte{1, 2, 3}, + }, + "non-byte value against byte sequence": { + actual: "foo", + expected: []byte{1, 2, 3}, + }, + "equal scalar values": { + actual: int64(42), + expected: int64(42), + equal: true, + }, + "different scalar types": { + actual: httpsfv.Token("foo"), + expected: "foo", + }, + } { + t.Run(uc, func(t *testing.T) { + assert.Equal(t, tc.equal, equalComponentParameterValues(tc.actual, tc.expected)) + }) + } +} + func TestComponentIdentifierCreateComponent(t *testing.T) { t.Parallel() diff --git a/integration_test.go b/integration_test.go new file mode 100644 index 0000000..a897618 --- /dev/null +++ b/integration_test.go @@ -0,0 +1,118 @@ +package httpsig + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "net/http" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestSignAndVerifyParsedSignatureRequest(t *testing.T) { + t.Parallel() + + privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + + requests, err := ParseAcceptSignature(http.Header{headerAcceptSignature: { + `sig1=("@method" "@authority");keyid="key1";nonce="abc";tag="app";created;audience="service-a"`, + }}) + require.NoError(t, err) + require.Len(t, requests, 1) + + request := requests[0] + + signer, err := NewSigner( + Key{Material: privKey, Algorithm: EcdsaP256Sha256}, + WithLabel(request.Label), + WithKeyID(request.KeyID), + WithComponents(request.Components...), + WithTag(request.Tag), + WithParameter("audience", request.Extensions["audience"]), + ) + require.NoError(t, err) + + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "https://example.com/", nil) + require.NoError(t, err) + + header, err := signer.Sign(MessageFromRequest(req), WithParameter(Nonce, request.Nonce)) + require.NoError(t, err) + + req.Header = header + + verifier, err := NewVerifier( + Key{Material: privKey.Public(), Algorithm: EcdsaP256Sha256}, + WithRequiredTag(request.Tag, WithComponents(request.Components...), WithParameter("audience", "service-a")), + ) + require.NoError(t, err) + + verified, err := verifier.Verify(MessageFromRequest(req)) + require.NoError(t, err) + require.Len(t, verified, 1) + + nonce, ok := verified[0].Parameters.Nonce() + require.True(t, ok) + assert.Equal(t, request.Nonce, nonce) + assert.Equal(t, request.Label, verified[0].Label) +} + +func TestParseAcceptSignatureBuilderOutput(t *testing.T) { + t.Parallel() + + builder, err := NewAcceptSignature( + WithLabel("bar"), + WithKeyID("foo"), + WithSignatureAlgorithm(EcdsaP256Sha256), + WithComponents("@status", "content-digest;req", `@query-param;name="Pet"`), + WithTag("awesome-app"), + WithParameter("audience", "service-a"), + WithExpiresTimestamp(false), + ) + require.NoError(t, err) + + header := http.Header{} + require.NoError(t, builder.Build(context.Background(), header, WithParameter(Nonce, "abc"))) + + requests, err := ParseAcceptSignature(header) + + require.NoError(t, err) + assert.Equal(t, []SignatureRequest{{ + Label: "bar", + Components: []string{`"@status"`, `"content-digest";req`, `"@query-param";name="Pet"`}, + KeyID: "foo", + Algorithm: EcdsaP256Sha256, + Tag: "awesome-app", + Nonce: "abc", + Created: true, + Extensions: SignatureParameters{"audience": "service-a"}, + }}, requests) +} + +func TestParsedComponentsRoundTripThroughWithComponents(t *testing.T) { + t.Parallel() + + const field = `sig=("@status" "content-digest";req "@query-param";name="a;b" "a;req" "b\"c" "d\\e");created` + + requests, err := ParseAcceptSignature(http.Header{headerAcceptSignature: {field}}) + require.NoError(t, err) + require.Len(t, requests, 1) + assert.Equal(t, []string{ + `"@status"`, `"content-digest";req`, `"@query-param";name="a;b"`, + `"a;req"`, `"b\"c"`, `"d\\e"`, + }, requests[0].Components) + + builder, err := NewAcceptSignature( + WithComponents(requests[0].Components...), + WithExpiresTimestamp(false), + ) + require.NoError(t, err) + + header := http.Header{} + require.NoError(t, builder.Build(context.Background(), header)) + + assert.Equal(t, field, header.Get(headerAcceptSignature)) +} diff --git a/signature_base.go b/signature_base.go index db60b2f..f4e51ab 100644 --- a/signature_base.go +++ b/signature_base.go @@ -2,6 +2,7 @@ package httpsig import ( "fmt" + "slices" "strings" "github.com/dunglas/httpsfv" @@ -34,7 +35,6 @@ func newSignatureBase(msg *Message, si *signatureInput, prepared []string) (sign entries: make([]serializedComponent, 0, len(si.identifiers)), signatureParams: marshalledSigParams, } - seen := make(map[string]struct{}, len(si.identifiers)) for i, ci := range si.identifiers { var identifier string @@ -47,12 +47,10 @@ func newSignatureBase(msg *Message, si *signatureInput, prepared []string) (sign identifier = prepared[i] } - if _, ok := seen[identifier]; ok { + if slices.ContainsFunc(si.identifiers[:i], ci.equal) { return signatureBase{}, fmt.Errorf("%w: duplicate component identifier %s", ErrMalformedData, identifier) } - seen[identifier] = struct{}{} - comp, err := ci.createComponent(msg) if err != nil { return signatureBase{}, err diff --git a/signature_base_test.go b/signature_base_test.go index dfd1b19..b1af6dc 100644 --- a/signature_base_test.go +++ b/signature_base_test.go @@ -90,6 +90,18 @@ func TestNewSignatureBase(t *testing.T) { require.ErrorContains(t, err, "duplicate component identifier") }, }, + "failing for duplicate component identifier with reordered parameters": { + components: []string{ + `content-digest;key="sha-512";sf`, + `content-digest;sf;key="sha-512"`, + }, + assert: func(t *testing.T, err error, _ signatureBase) { + t.Helper() + + require.ErrorIs(t, err, ErrMalformedData) + require.ErrorContains(t, err, "duplicate component identifier") + }, + }, "failing for unknown component identifier": { components: []string{"@status"}, assert: func(t *testing.T, err error, _ signatureBase) { diff --git a/signature_input.go b/signature_input.go index 24d6568..fd4b6d9 100644 --- a/signature_input.go +++ b/signature_input.go @@ -1,8 +1,8 @@ package httpsig import ( - "bytes" "fmt" + "slices" "time" "github.com/dunglas/httpsfv" @@ -37,30 +37,7 @@ func newSignatureInput( } func (si *signatureInput) hasIdentifier(id *componentIdentifier) bool { - for _, identifier := range si.identifiers { - if identifier.Value != id.Value || len(identifier.Params.Names()) != len(id.Params.Names()) { - continue - } - - matches := true - - for _, name := range id.Params.Names() { - actual, present := identifier.Params.Get(name) - - expected, _ := id.Params.Get(name) - if !present || !equalComponentParameterValues(actual, expected) { - matches = false - - break - } - } - - if matches { - return true - } - } - - return false + return slices.ContainsFunc(si.identifiers, id.equal) } func (si *signatureInput) parameters() SignatureParameters { @@ -73,19 +50,23 @@ func (si *signatureInput) parameters() SignatureParameters { for _, name := range si.value.Params.Names() { value, _ := si.value.Params.Get(name) - switch v := value.(type) { - case httpsfv.Token: - value = Token(v) - case httpsfv.DisplayString: - value = string(v) - } - - result[SignatureParameter(name)] = value + result[SignatureParameter(name)] = decodeParameter(value) } return result } +func decodeParameter(value any) any { + switch v := value.(type) { + case httpsfv.Token: + return Token(v) + case httpsfv.DisplayString: + return string(v) + default: + return value + } +} + func (si *signatureInput) parameter(name SignatureParameter) (any, bool) { if si.value.Params == nil { return nil, false @@ -168,13 +149,3 @@ func validateSignatureInputParameters(params *httpsfv.Params) error { return nil } - -func equalComponentParameterValues(actual, expected any) bool { - if expectedBytes, ok := expected.([]byte); ok { - actualBytes, ok := actual.([]byte) - - return ok && bytes.Equal(actualBytes, expectedBytes) - } - - return actual == expected -} diff --git a/signature_input_test.go b/signature_input_test.go index 19fc778..ac58f81 100644 --- a/signature_input_test.go +++ b/signature_input_test.go @@ -345,15 +345,13 @@ func TestSignatureInputParameters(t *testing.T) { params: func() *httpsfv.Params { params := httpsfv.NewParams() params.Add(string(Created), int64(1577836800)) - params.Add("foo", httpsfv.Token("hello")) - params.Add("bar", httpsfv.DisplayString("hello")) + params.Add("foo", "hello") return params }(), want: SignatureParameters{ Created: int64(1577836800), - "foo": Token("hello"), - "bar": "hello", + "foo": "hello", }, }, } { @@ -365,6 +363,25 @@ func TestSignatureInputParameters(t *testing.T) { } } +func TestDecodeParameter(t *testing.T) { + t.Parallel() + + for uc, tc := range map[string]struct { + value any + want any + }{ + "token": {value: httpsfv.Token("foo"), want: Token("foo")}, + "display string": {value: httpsfv.DisplayString("café"), want: "café"}, + "string": {value: "foo", want: "foo"}, + "integer": {value: int64(42), want: int64(42)}, + "byte sequence": {value: []byte{1, 2, 3}, want: []byte{1, 2, 3}}, + } { + t.Run(uc, func(t *testing.T) { + assert.Equal(t, tc.want, decodeParameter(tc.value)) + }) + } +} + func TestSignatureInputParameter(t *testing.T) { t.Parallel() diff --git a/signature_requirements.go b/signature_requirements.go index a582eaf..e952975 100644 --- a/signature_requirements.go +++ b/signature_requirements.go @@ -2,6 +2,7 @@ package httpsig import ( "fmt" + "slices" "github.com/dunglas/httpsfv" ) @@ -16,6 +17,7 @@ type signatureRequirements struct { keyID string tag string identifiers []*componentIdentifier + extensions SignatureParameters } func newSignatureRequirements( @@ -69,7 +71,7 @@ func newSignatureRequirements( } } -//nolint:funlen, cyclop +//nolint:funlen, cyclop, gocognit func (p *signatureRequirements) fromInnerList(list httpsfv.InnerList) error { for _, item := range list.Items { ci, err := newComponentIdentifier(item) @@ -77,6 +79,10 @@ func (p *signatureRequirements) fromInnerList(list httpsfv.InnerList) error { return err } + if slices.ContainsFunc(p.identifiers, ci.equal) { + return fmt.Errorf("%w: duplicate component identifier %q", ErrMalformedData, ci.Value) + } + p.identifiers = append(p.identifiers, ci) } @@ -86,48 +92,52 @@ func (p *signatureRequirements) fromInnerList(list httpsfv.InnerList) error { switch SignatureParameter(name) { case Created: value, ok := param.(bool) - if !ok { + if !ok || !value { return fmt.Errorf("%w: created", ErrMalformedSignatureParameter) } p.created = value case Expires: value, ok := param.(bool) - if !ok { + if !ok || !value { return fmt.Errorf("%w: expires", ErrMalformedSignatureParameter) } p.expires = value case KeyID: value, ok := param.(string) - if !ok { + if !ok || value == "" { return fmt.Errorf("%w: keyid", ErrMalformedSignatureParameter) } p.keyID = value case Alg: value, ok := param.(string) - if !ok { + if !ok || value == "" { return fmt.Errorf("%w: alg", ErrMalformedSignatureParameter) } p.alg = SignatureAlgorithm(value) case Nonce: value, ok := param.(string) - if !ok { + if !ok || value == "" { return fmt.Errorf("%w: nonce", ErrMalformedSignatureParameter) } p.nonce = value case Tag: value, ok := param.(string) - if !ok { + if !ok || value == "" { return fmt.Errorf("%w: tag", ErrMalformedSignatureParameter) } p.tag = value default: - return fmt.Errorf("%w: %s is unknown", ErrMalformedSignatureParameter, name) + if p.extensions == nil { + p.extensions = make(SignatureParameters) + } + + p.extensions[SignatureParameter(name)] = decodeParameter(param) } } diff --git a/signature_requirements_test.go b/signature_requirements_test.go index ce4fba1..7c610a2 100644 --- a/signature_requirements_test.go +++ b/signature_requirements_test.go @@ -314,6 +314,40 @@ func TestSignatureRequirementsFromInnerList(t *testing.T) { require.ErrorContains(t, err, "expires") }, }, + { + uc: "failing parsing false created parameter", + list: httpsfv.InnerList{ + Params: func() *httpsfv.Params { + params := httpsfv.NewParams() + params.Add(string(Created), false) + + return params + }(), + }, + assert: func(t *testing.T, err error, _ *signatureRequirements) { + t.Helper() + + require.ErrorIs(t, err, ErrMalformedSignatureParameter) + require.ErrorContains(t, err, "created") + }, + }, + { + uc: "failing parsing false expires parameter", + list: httpsfv.InnerList{ + Params: func() *httpsfv.Params { + params := httpsfv.NewParams() + params.Add(string(Expires), false) + + return params + }(), + }, + assert: func(t *testing.T, err error, _ *signatureRequirements) { + t.Helper() + + require.ErrorIs(t, err, ErrMalformedSignatureParameter) + require.ErrorContains(t, err, "expires") + }, + }, { uc: "failing parsing keyid parameter", list: httpsfv.InnerList{ @@ -387,11 +421,62 @@ func TestSignatureRequirementsFromInnerList(t *testing.T) { }, }, { - uc: "failing parsing unknown parameter", + uc: "failing parsing empty keyid parameter", list: httpsfv.InnerList{ Params: func() *httpsfv.Params { params := httpsfv.NewParams() - params.Add("foo", 1) + params.Add(string(KeyID), "") + + return params + }(), + }, + assert: func(t *testing.T, err error, _ *signatureRequirements) { + t.Helper() + + require.ErrorIs(t, err, ErrMalformedSignatureParameter) + require.ErrorContains(t, err, "keyid") + }, + }, + { + uc: "failing parsing empty alg parameter", + list: httpsfv.InnerList{ + Params: func() *httpsfv.Params { + params := httpsfv.NewParams() + params.Add(string(Alg), "") + + return params + }(), + }, + assert: func(t *testing.T, err error, _ *signatureRequirements) { + t.Helper() + + require.ErrorIs(t, err, ErrMalformedSignatureParameter) + require.ErrorContains(t, err, "alg") + }, + }, + { + uc: "failing parsing empty nonce parameter", + list: httpsfv.InnerList{ + Params: func() *httpsfv.Params { + params := httpsfv.NewParams() + params.Add(string(Nonce), "") + + return params + }(), + }, + assert: func(t *testing.T, err error, _ *signatureRequirements) { + t.Helper() + + require.ErrorIs(t, err, ErrMalformedSignatureParameter) + require.ErrorContains(t, err, "nonce") + }, + }, + { + uc: "failing parsing empty tag parameter", + list: httpsfv.InnerList{ + Params: func() *httpsfv.Params { + params := httpsfv.NewParams() + params.Add(string(Tag), "") return params }(), @@ -399,9 +484,60 @@ func TestSignatureRequirementsFromInnerList(t *testing.T) { assert: func(t *testing.T, err error, _ *signatureRequirements) { t.Helper() - require.Error(t, err) require.ErrorIs(t, err, ErrMalformedSignatureParameter) - require.ErrorContains(t, err, "foo is unknown") + require.ErrorContains(t, err, "tag") + }, + }, + { + uc: "duplicate component identifiers", + list: httpsfv.InnerList{ + Items: []httpsfv.Item{httpsfv.NewItem("@method"), httpsfv.NewItem("@method")}, + }, + assert: func(t *testing.T, err error, _ *signatureRequirements) { + t.Helper() + + require.ErrorIs(t, err, ErrMalformedData) + require.ErrorContains(t, err, "duplicate component identifier") + }, + }, + { + uc: "same component with different parameters", + list: httpsfv.InnerList{ + Params: httpsfv.NewParams(), + Items: func() []httpsfv.Item { + first := httpsfv.NewItem("@query-param") + first.Params.Add("name", "foo") + + second := httpsfv.NewItem("@query-param") + second.Params.Add("name", "bar") + + return []httpsfv.Item{first, second} + }(), + }, + assert: func(t *testing.T, err error, params *signatureRequirements) { + t.Helper() + + require.NoError(t, err) + require.Len(t, params.identifiers, 2) + assert.Equal(t, "@query-param", params.identifiers[0].Value) + assert.Equal(t, "@query-param", params.identifiers[1].Value) + }, + }, + { + uc: "collecting extension parameters", + list: httpsfv.InnerList{ + Params: func() *httpsfv.Params { + params := httpsfv.NewParams() + params.Add("foo", "bar") + + return params + }(), + }, + assert: func(t *testing.T, err error, params *signatureRequirements) { + t.Helper() + + require.NoError(t, err) + assert.Equal(t, SignatureParameters{"foo": "bar"}, params.extensions) }, }, { diff --git a/verifier.go b/verifier.go index 35e4d9d..0240044 100644 --- a/verifier.go +++ b/verifier.go @@ -46,6 +46,11 @@ type Verifier interface { Verify(msg *Message, opts ...VerifyOption) (VerificationResult, error) } +type applicableSignature struct { + label string + input *signatureInput +} + // NewVerifier creates a Verifier instance. // Without WithValidateAllSignatures, at least one WithRequiredTag is necessary. // By default, created and expires are required and signatures may be at most @@ -159,7 +164,8 @@ func (v *verifier) Verify(msg *Message, opts ...VerifyOption) (VerificationResul // do the actual verification results := make([]VerifiedSignature, 0, len(applicableSignatures)) - for name, params := range applicableSignatures { + for _, ref := range applicableSignatures { + name, params := ref.label, ref.input tag, _ := params.tag() policy, exists := policiesByTag[tag] @@ -205,27 +211,37 @@ func (v *verifier) policiesForCall(opts []VerifyOption) (map[string]*verificatio return result, nil } -func (v *verifier) applicableSignatures(refs map[string]*signatureInput) (map[string]*signatureInput, error) { - if !v.validateAllSigs { - for name, input := range refs { - tag, present := input.tag() - if !present { - delete(refs, name) +func (v *verifier) applicableSignatures(refs *httpsfv.Dictionary) ([]applicableSignature, error) { + result := make([]applicableSignature, 0, len(refs.Names())) + + for _, label := range refs.Names() { + member, _ := refs.Get(label) + list := member.(httpsfv.InnerList) //nolint:forcetypeassert + if !v.validateAllSigs { + tag, present := signatureTag(list) + if !present { continue } if _, required := v.tagPolicies[tag]; !required { - delete(refs, name) + continue } } + + si, err := parseSignatureInput(list) + if err != nil { + return nil, fmt.Errorf("%w: label %q: %w", ErrMalformedData, label, err) + } + + result = append(result, applicableSignature{label, si}) } - if len(refs) == 0 { + if len(result) == 0 { return nil, &NoApplicableSignatureError{} } - return refs, nil + return result, nil } func (v *verifier) negotiateSignatureParameters(msg *Message, policiesByTag map[string]*verificationPolicy) error { @@ -250,7 +266,7 @@ func (v *verifier) negotiateSignatureParameters(msg *Message, policiesByTag map[ return &NoApplicableSignatureError{headerToAdd: hdr} } -func (v *verifier) hasMissingSignatures(sigRefs map[string]*signatureInput) bool { +func (v *verifier) hasMissingSignatures(sigRefs *httpsfv.Dictionary) bool { for sigTag := range v.tagPolicies { if len(sigTag) == 0 { // empty tag is used for a policy applying to all signatures @@ -260,8 +276,10 @@ func (v *verifier) hasMissingSignatures(sigRefs map[string]*signatureInput) bool var present bool - for _, sigRef := range sigRefs { - tag, tagPresent := sigRef.tag() + for _, label := range sigRefs.Names() { + member, _ := sigRefs.Get(label) + + tag, tagPresent := signatureTag(member.(httpsfv.InnerList)) //nolint:forcetypeassert if tagPresent && tag == sigTag { present = true @@ -328,33 +346,6 @@ func (v *verifier) verifySignature( }, nil } -func getSignatureReferences(values []string) (map[string]*signatureInput, error) { - inputDict, err := httpsfv.UnmarshalDictionary(values) - if err != nil { - return nil, fmt.Errorf("%w: %w", ErrMalformedData, err) - } - - sigRefs := make(map[string]*signatureInput, len(inputDict.Names())) - - for _, label := range inputDict.Names() { - m, _ := inputDict.Get(label) - - sigParams, ok := m.(httpsfv.InnerList) - if !ok { - return nil, fmt.Errorf("%w: unexpected signature parameters format", ErrMalformedData) - } - - si, err := parseSignatureInput(sigParams) - if err != nil { - return nil, fmt.Errorf("%w: %w", ErrMalformedData, err) - } - - sigRefs[label] = si - } - - return sigRefs, nil -} - func (v *verifier) extractSignature(dict *httpsfv.Dictionary, name string) ([]byte, error) { sigItem, ok := dict.Get(name) if !ok { @@ -373,3 +364,36 @@ func (v *verifier) extractSignature(dict *httpsfv.Dictionary, name string) ([]by return signatureBytes, nil } + +func signatureTag(list httpsfv.InnerList) (string, bool) { + if list.Params == nil { + return "", false + } + + value, present := list.Params.Get(string(Tag)) + if !present { + return "", false + } + + tag, ok := value.(string) + + return tag, ok +} + +func getSignatureReferences(values []string) (*httpsfv.Dictionary, error) { + inputDict, err := httpsfv.UnmarshalDictionary(values) + if err != nil { + return nil, fmt.Errorf("%w: %w", ErrMalformedData, err) + } + + // Check member types without converting values that require semantic validation. + for _, label := range inputDict.Names() { + m, _ := inputDict.Get(label) + + if _, ok := m.(httpsfv.InnerList); !ok { + return nil, fmt.Errorf("%w: unexpected signature parameters format", ErrMalformedData) + } + } + + return inputDict, nil +} diff --git a/verifier_test.go b/verifier_test.go index 55989f9..4a05859 100644 --- a/verifier_test.go +++ b/verifier_test.go @@ -1726,6 +1726,34 @@ func TestVerifierVerify(t *testing.T) { assert.Equal(t, map[string]string{"foo": "bar"}, sig.Metadata) }, }, + "unselected invalid component identifier is ignored": { + opts: []VerifierOption{ + WithRequiredTag("foo"), + WithExpiresTimestamp(false), + }, + msg: &Message{Header: http.Header{ + "Signature-Input": { + `valid=();created=1618884473;keyid="test-shared-secret";tag="foo", ` + + `invalid=("@query-param");tag="bar"`, + }, + "Signature": { + `valid=:VhBIZ0nP4o+r4bSKCvC+gc0VI1yVhhN1PECWW8ZF2Dg=:, invalid=:dGVzdA==:`, + }, + }}, + configureResolver: func(t *testing.T, kr *KeyResolverMock) { + t.Helper() + + kr.EXPECT().ResolveKey(mock.Anything, mock.Anything). + Return(KeyInfo{Key: Key{Material: tkMAC, Algorithm: HmacSha256}}, 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, "valid", results[0].Label) + }, + }, "invalid untagged signature fails when validating all": { opts: []VerifierOption{ WithValidateAllSignatures(), @@ -2039,124 +2067,305 @@ func TestVerifierVerify(t *testing.T) { }) } +func TestSignatureTag(t *testing.T) { + t.Parallel() + + withValue := func(name string, value any) httpsfv.InnerList { + params := httpsfv.NewParams() + params.Add(name, value) + + return httpsfv.InnerList{Params: params} + } + + for uc, tc := range map[string]struct { + list httpsfv.InnerList + tag string + present bool + }{ + "nil parameters": {}, + "tag missing": { + list: withValue("other", "test"), + }, + "tag has wrong type": { + list: withValue(string(Tag), true), + }, + "string tag": { + list: withValue(string(Tag), "app"), + tag: "app", present: true, + }, + } { + t.Run(uc, func(t *testing.T) { + tag, present := signatureTag(tc.list) + + assert.Equal(t, tc.tag, tag) + assert.Equal(t, tc.present, present) + }) + } +} + +func TestGetSignatureReferences(t *testing.T) { + t.Parallel() + + for uc, tc := range map[string]struct { + values []string + labels []string + err error + }{ + "no header": {labels: []string{}}, + "valid inner lists": { + values: []string{`first=("@method"), second=("@status")`}, + labels: []string{"first", "second"}, + }, + "invalid structured fields": { + values: []string{`sig=("@method"`}, + err: ErrMalformedData, + }, + "member is not an inner list": { + values: []string{`sig="@method"`}, + err: ErrMalformedData, + }, + } { + t.Run(uc, func(t *testing.T) { + refs, err := getSignatureReferences(tc.values) + if tc.err != nil { + require.ErrorIs(t, err, tc.err) + assert.Nil(t, refs) + + return + } + + require.NoError(t, err) + require.NotNil(t, refs) + assert.Equal(t, tc.labels, refs.Names()) + }) + } +} + +func TestVerifierHasMissingSignatures(t *testing.T) { + t.Parallel() + + withTag := func(tag string) httpsfv.InnerList { + params := httpsfv.NewParams() + params.Add(string(Tag), tag) + + return httpsfv.InnerList{Params: params} + } + + for uc, tc := range map[string]struct { + policies map[string]*verificationPolicy + members map[string]httpsfv.InnerList + missing bool + }{ + "all required tags present": { + policies: map[string]*verificationPolicy{"foo": {}, "bar": {}}, + members: map[string]httpsfv.InnerList{"first": withTag("foo"), "second": withTag("bar")}, + }, + "required tag missing": { + policies: map[string]*verificationPolicy{"foo": {}}, + members: map[string]httpsfv.InnerList{"sig": withTag("other")}, + missing: true, + }, + "global policy does not require a tag": { + policies: map[string]*verificationPolicy{"": {}}, + }, + "non-string tag does not satisfy policy": { + policies: map[string]*verificationPolicy{"foo": {}}, + members: map[string]httpsfv.InnerList{ + "sig": {Params: func() *httpsfv.Params { + params := httpsfv.NewParams() + params.Add(string(Tag), true) + + return params + }()}, + }, + missing: true, + }, + } { + t.Run(uc, func(t *testing.T) { + refs := httpsfv.NewDictionary() + for name, list := range tc.members { + refs.Add(name, list) + } + + v := verifier{tagPolicies: tc.policies} + assert.Equal(t, tc.missing, v.hasMissingSignatures(refs)) + }) + } +} + func TestVerifierApplicableSignatures(t *testing.T) { t.Parallel() - withTag := func(tag string) *signatureInput { + withTag := func(tag string) httpsfv.InnerList { params := httpsfv.NewParams() params.Add(string(Tag), tag) - return newSignatureInput(nil, params) + return newSignatureInput(nil, params).value } for uc, tc := range map[string]struct { verifier verifier - refs map[string]*signatureInput - assert func(t *testing.T, err error, refs map[string]*signatureInput) + refs map[string]httpsfv.InnerList + labels []string + wantErr error }{ "only required signatures are applicable": { verifier: verifier{ tagPolicies: map[string]*verificationPolicy{"foo": {}}, }, - refs: map[string]*signatureInput{ + refs: map[string]httpsfv.InnerList{ "matching": withTag("foo"), "other": withTag("bar"), "empty": withTag(""), - "untagged": newSignatureInput(nil, nil), - }, - assert: func(t *testing.T, err error, refs map[string]*signatureInput) { - t.Helper() - - require.NoError(t, err) - require.Len(t, refs, 1) - assert.Contains(t, refs, "matching") + "untagged": {}, }, + labels: []string{"matching"}, }, "no matching signature": { verifier: verifier{ tagPolicies: map[string]*verificationPolicy{"foo": {}}, }, - refs: map[string]*signatureInput{ + refs: map[string]httpsfv.InnerList{ "other": withTag("bar"), }, - assert: func(t *testing.T, err error, refs map[string]*signatureInput) { - t.Helper() - - require.ErrorIs(t, err, &NoApplicableSignatureError{}) - assert.Nil(t, refs) - }, + wantErr: &NoApplicableSignatureError{}, }, "missing tag": { verifier: verifier{ tagPolicies: map[string]*verificationPolicy{"foo": {}}, }, - refs: map[string]*signatureInput{ - "untagged": newSignatureInput(nil, nil), - }, - assert: func(t *testing.T, err error, refs map[string]*signatureInput) { - t.Helper() - - require.ErrorIs(t, err, &NoApplicableSignatureError{}) - assert.Nil(t, refs) + refs: map[string]httpsfv.InnerList{ + "untagged": {}, }, + wantErr: &NoApplicableSignatureError{}, }, "all signatures are applicable": { verifier: verifier{ validateAllSigs: true, }, - refs: map[string]*signatureInput{ + refs: map[string]httpsfv.InnerList{ "tagged": withTag("foo"), "empty": withTag(""), - "untagged": newSignatureInput(nil, nil), - }, - assert: func(t *testing.T, err error, refs map[string]*signatureInput) { - t.Helper() - - require.NoError(t, err) - assert.Len(t, refs, 3) - assert.Contains(t, refs, "tagged") - assert.Contains(t, refs, "empty") - assert.Contains(t, refs, "untagged") + "untagged": {}, }, + labels: []string{"tagged", "empty", "untagged"}, }, "validate all with required tag": { verifier: verifier{ validateAllSigs: true, tagPolicies: map[string]*verificationPolicy{"foo": {}}, }, - refs: map[string]*signatureInput{ + refs: map[string]httpsfv.InnerList{ "matching": withTag("foo"), "other": withTag("bar"), - "untagged": newSignatureInput(nil, nil), + "untagged": {}, }, - assert: func(t *testing.T, err error, refs map[string]*signatureInput) { - t.Helper() + labels: []string{"matching", "other", "untagged"}, + }, + "unselected invalid component identifier is ignored": { + verifier: verifier{ + tagPolicies: map[string]*verificationPolicy{"foo": {}}, + }, + refs: map[string]httpsfv.InnerList{ + "valid": withTag("foo"), + "invalid": { + Items: []httpsfv.Item{httpsfv.NewItem("@query-param")}, + Params: withTag("bar").Params, + }, + }, + labels: []string{"valid"}, + }, + "unselected invalid signature parameter is ignored": { + verifier: verifier{ + tagPolicies: map[string]*verificationPolicy{"foo": {}}, + }, + refs: map[string]httpsfv.InnerList{ + "valid": withTag("foo"), + "invalid": { + Params: func() *httpsfv.Params { + params := httpsfv.NewParams() + params.Add(string(Tag), "bar") + params.Add(string(Created), false) - require.NoError(t, err) - assert.Len(t, refs, 3) - assert.Contains(t, refs, "matching") - assert.Contains(t, refs, "other") - assert.Contains(t, refs, "untagged") + return params + }(), + }, }, + labels: []string{"valid"}, }, - "no signatures": { + "non-string tag is not selected": { verifier: verifier{ - validateAllSigs: true, + tagPolicies: map[string]*verificationPolicy{"foo": {}}, }, - assert: func(t *testing.T, err error, refs map[string]*signatureInput) { - t.Helper() + refs: map[string]httpsfv.InnerList{ + "valid": withTag("foo"), + "invalid": { + Params: func() *httpsfv.Params { + params := httpsfv.NewParams() + params.Add(string(Tag), true) - require.ErrorIs(t, err, &NoApplicableSignatureError{}) - assert.Nil(t, refs) + return params + }(), + }, }, + labels: []string{"valid"}, + }, + "selected invalid component identifier fails": { + verifier: verifier{ + tagPolicies: map[string]*verificationPolicy{"foo": {}}, + }, + refs: map[string]httpsfv.InnerList{ + "sig": { + Items: []httpsfv.Item{httpsfv.NewItem("@query-param")}, + Params: withTag("foo").Params, + }, + }, + wantErr: ErrInvalidComponentIdentifier, + }, + "validate all rejects invalid signature parameter": { + verifier: verifier{validateAllSigs: true}, + refs: map[string]httpsfv.InnerList{ + "sig": { + Params: func() *httpsfv.Params { + params := httpsfv.NewParams() + params.Add(string(Created), false) + + return params + }(), + }, + }, + wantErr: ErrMalformedSignatureParameter, + }, + "no signatures": { + verifier: verifier{ + validateAllSigs: true, + }, + wantErr: &NoApplicableSignatureError{}, }, } { t.Run(uc, func(t *testing.T) { - v := tc.verifier + dict := httpsfv.NewDictionary() + for name, list := range tc.refs { + dict.Add(name, list) + } + + refs, err := tc.verifier.applicableSignatures(dict) + if tc.wantErr != nil { + require.ErrorIs(t, err, tc.wantErr) + require.Nil(t, refs) + + return + } + + require.NoError(t, err) - refs, err := v.applicableSignatures(tc.refs) + labels := make([]string, 0, len(refs)) + for _, ref := range refs { + require.NotNil(t, ref.input) + labels = append(labels, ref.label) + } - tc.assert(t, err, refs) + assert.ElementsMatch(t, tc.labels, labels) }) } }