From 45eee1b07c7bdb9b13d804668d1d6fd23389dae2 Mon Sep 17 00:00:00 2001 From: Dimitrij Drus Date: Sun, 18 Oct 2026 18:20:29 +0200 Subject: [PATCH 1/2] refactor: Made signature base explicit --- component.go | 26 +-- component_test.go | 31 ---- signature_base.go | 95 ++++++++++ signature_base_test.go | 330 +++++++++++++++++++++++++++++++++++ signature_parameters.go | 42 ----- signature_parameters_test.go | 129 -------------- signer.go | 13 +- verifier.go | 9 +- 8 files changed, 444 insertions(+), 231 deletions(-) delete mode 100644 component_test.go create mode 100644 signature_base.go create mode 100644 signature_base_test.go diff --git a/component.go b/component.go index 07bb2f9..dcb669e 100644 --- a/component.go +++ b/component.go @@ -1,32 +1,12 @@ package httpsig -import ( - "strings" - - "github.com/dunglas/httpsfv" -) +import "strings" type component struct { key *componentIdentifier value []string } -type componentList []component - -func (s componentList) marshal() (string, error) { - var builder strings.Builder - - for _, item := range s { - marshalledKey, err := httpsfv.Marshal(item.key) - if err != nil { - return "", err - } - - _, err = builder.WriteString(marshalledKey + ": " + strings.Join(item.value, ", ") + "\n") - if err != nil { - return "", err - } - } - - return strings.TrimRight(builder.String(), "\n"), nil +func (c component) canonicalValue() string { + return strings.Join(c.value, ", ") } diff --git a/component_test.go b/component_test.go deleted file mode 100644 index 57eace2..0000000 --- a/component_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package httpsig - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestComponentListMarshal(t *testing.T) { - t.Parallel() - - msg := &Message{Method: "GET", Authority: "foo.bar", IsRequest: true} - - ci, err := toComponentIdentifiers([]string{"@authority", "@method"}) - require.NoError(t, err) - - list := make(componentList, len(ci)) - - for i, id := range ci { - c, err := id.createComponent(msg) - require.NoError(t, err) - - list[i] = c - } - - res, err := list.marshal() - require.NoError(t, err) - - assert.Equal(t, "\"@authority\": foo.bar\n\"@method\": GET", res) -} diff --git a/signature_base.go b/signature_base.go new file mode 100644 index 0000000..9ebf3bb --- /dev/null +++ b/signature_base.go @@ -0,0 +1,95 @@ +package httpsig + +import ( + "bytes" + "fmt" + "strings" + + "github.com/dunglas/httpsfv" +) + +type signatureBase []component + +func newSignatureBase(params *signatureParameters, msg *Message) (signatureBase, error) { + marshalledSigParams, err := httpsfv.Marshal(params.InnerList) + if err != nil { + return nil, err + } + + sigBase := make(signatureBase, 0, len(params.identifiers)+1) + seen := make(map[string]struct{}, len(params.identifiers)) + + for _, ci := range params.identifiers { + identifier, err := httpsfv.Marshal(ci.Item) + if err != nil { + return nil, err + } + + if _, ok := seen[identifier]; ok { + return nil, fmt.Errorf("%w: duplicate component identifier %s", ErrMalformedData, identifier) + } + + seen[identifier] = struct{}{} + + comp, err := ci.createComponent(msg) + if err != nil { + return nil, err + } + + sigBase = append(sigBase, comp) + } + + sigBase = append(sigBase, component{ + key: &componentIdentifier{Item: httpsfv.NewItem("@signature-params")}, + value: []string{marshalledSigParams}, + }) + + return sigBase, nil +} + +func (s signatureBase) marshal() ([]byte, error) { + var buf bytes.Buffer + + for i, item := range s { + marshalledKey, err := httpsfv.Marshal(item.key.Item) + if err != nil { + return nil, err + } + + if i > 0 { + buf.WriteByte('\n') + } + + buf.WriteString(marshalledKey) + buf.WriteString(": ") + buf.WriteString(item.canonicalValue()) + } + + return buf.Bytes(), nil +} + +func (s signatureBase) components() (map[string]string, error) { + result := make(map[string]string, len(s)) + + for _, component := range s { + name := component.key.Value.(string) + + if name == "@signature-params" { + continue + } + + identifier, err := httpsfv.Marshal(component.key.Item) + if err != nil { + return nil, err + } + + // Remove quotes around the component name, + // preserving identifier parameters. + prefix := `"` + name + `"` + key := name + strings.TrimPrefix(identifier, prefix) + + result[key] = component.canonicalValue() + } + + return result, nil +} diff --git a/signature_base_test.go b/signature_base_test.go new file mode 100644 index 0000000..a668623 --- /dev/null +++ b/signature_base_test.go @@ -0,0 +1,330 @@ +package httpsig + +import ( + "net/http" + "net/url" + "testing" + "time" + + "github.com/dunglas/httpsfv" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestNewSignatureBase(t *testing.T) { + t.Parallel() + + // test is based on the non-normative example from + // https://www.rfc-editor.org/rfc/rfc9421.html#name-creating-the-signature-base + + reqURL, err := url.Parse("http://example.com/foo?param=Value&Pet=dog&Cat=meow") + require.NoError(t, err) + + msg := &Message{ + Method: "POST", + Authority: "example.com", + URL: reqURL, + Header: http.Header{ + "Host": []string{"example.com"}, + "Date": []string{"Tue, 20 Apr 2021 02:07:55 GMT"}, + "Content-Type": []string{"application/json"}, + "Content-Digest": []string{"sha-512=:WZDPaVn/7XgHaAy8pmojAkGWoRx2UFChF41A2svX+TaPm+AbwAgBWnrIiYllu7BNNyealdVLvRwEmTHWXvJwew==:"}, + "Content-Length": []string{"18"}, + }, + StatusCode: 0, + IsRequest: true, + } + + keyID := "test-key-rsa-pss" + created, err := time.Parse(time.RFC1123, "Tue, 20 Apr 2021 02:07:53 GMT") + require.NoError(t, err) + + for _, tc := range []struct { + uc string + components []string + assert func(t *testing.T, err error, base signatureBase) + }{ + { + uc: "successful signature base creation", + components: []string{ + "@method", "@authority", "@path", "content-digest", "content-length", "content-type", + }, + assert: func(t *testing.T, err error, base signatureBase) { + t.Helper() + + require.NoError(t, err) + + expected := `"@method": POST +"@authority": example.com +"@path": /foo +"content-digest": sha-512=:WZDPaVn/7XgHaAy8pmojAkGWoRx2UFChF41A2svX+TaPm+AbwAgBWnrIiYllu7BNNyealdVLvRwEmTHWXvJwew==: +"content-length": 18 +"content-type": application/json +"@signature-params": ("@method" "@authority" "@path" "content-digest" "content-length" "content-type");created=1618884473;keyid="test-key-rsa-pss"` + + sigBase, err := base.marshal() + require.NoError(t, err) + + assert.Equal(t, expected, string(sigBase)) + }, + }, + { + uc: "failing for duplicate component identifier", + components: []string{ + "@method", "@method", + }, + assert: func(t *testing.T, err error, _ signatureBase) { + t.Helper() + + require.Error(t, err) + require.ErrorIs(t, err, ErrMalformedData) + require.ErrorContains(t, err, "duplicate component identifier") + }, + }, + { + uc: "failing for duplicate parameterized component identifier", + components: []string{ + `@query-param;name="Pet"`, + `@query-param;name="Pet"`, + }, + assert: func(t *testing.T, err error, _ signatureBase) { + t.Helper() + + require.Error(t, err) + require.ErrorIs(t, err, ErrMalformedData) + require.ErrorContains(t, err, "duplicate component identifier") + }, + }, + { + uc: "failing for unknown component identifier", + components: []string{"@status"}, + assert: func(t *testing.T, err error, _ signatureBase) { + t.Helper() + + require.Error(t, err) + require.ErrorIs(t, err, ErrCanonicalization) + require.ErrorContains(t, err, "@status") + }, + }, + { + uc: "allowing same component identifier with different parameters", + components: []string{ + `@query-param;name="Pet"`, + `@query-param;name="Cat"`, + }, + assert: func(t *testing.T, err error, base signatureBase) { + t.Helper() + + require.NoError(t, err) + + expected := `"@query-param";name="Pet": dog +"@query-param";name="Cat": meow +"@signature-params": ("@query-param";name="Pet" "@query-param";name="Cat");created=1618884473;keyid="test-key-rsa-pss"` + + sigBase, err := base.marshal() + require.NoError(t, err) + + assert.Equal(t, expected, string(sigBase)) + }, + }, + } { + t.Run(tc.uc, func(t *testing.T) { + identifiers, err := toComponentIdentifiers(tc.components) + require.NoError(t, err) + + params := newSignatureParameters(created, time.Time{}, "", keyID, "", "", identifiers) + + sigBase, err := newSignatureBase(params, msg) + + tc.assert(t, err, sigBase) + }) + } +} + +func TestSignatureBaseMarshal(t *testing.T) { + t.Parallel() + + msg := &Message{Method: "GET", Authority: "foo.bar", IsRequest: true} + + ci, err := toComponentIdentifiers([]string{"@authority", "@method"}) + require.NoError(t, err) + + list := make(signatureBase, len(ci)) + + for i, id := range ci { + c, err := id.createComponent(msg) + require.NoError(t, err) + + list[i] = c + } + + res, err := list.marshal() + require.NoError(t, err) + + assert.Equal(t, "\"@authority\": foo.bar\n\"@method\": GET", string(res)) +} + +func TestSignatureBaseComponents(t *testing.T) { + t.Parallel() + + petParams := httpsfv.NewParams() + petParams.Add("name", "Pet") + + catParams := httpsfv.NewParams() + catParams.Add("name", "Cat") + + agentParams := httpsfv.NewParams() + agentParams.Add("key", "sig1") + + sfParams := httpsfv.NewParams() + sfParams.Add("sf", true) + + for uc, tc := range map[string]struct { + base signatureBase + expected map[string]string + }{ + "empty signature base": { + base: signatureBase{}, + expected: map[string]string{}, + }, + "excluding signature parameters": { + base: signatureBase{ + { + key: &componentIdentifier{ + Item: httpsfv.NewItem("@signature-params"), + }, + value: []string{`("@method");created=123`}, + }, + }, + expected: map[string]string{}, + }, + "simple component identifiers": { + base: signatureBase{ + { + key: &componentIdentifier{ + Item: httpsfv.NewItem("@method"), + }, + value: []string{"GET"}, + }, + { + key: &componentIdentifier{ + Item: httpsfv.NewItem("@authority"), + }, + value: []string{"example.com"}, + }, + { + key: &componentIdentifier{ + Item: httpsfv.NewItem("user-agent"), + }, + value: []string{"ExampleBot/1.0"}, + }, + { + key: &componentIdentifier{ + Item: httpsfv.NewItem("@signature-params"), + }, + value: []string{ + `("@method" "@authority" "user-agent")`, + }, + }, + }, + expected: map[string]string{ + "@method": "GET", + "@authority": "example.com", + "user-agent": "ExampleBot/1.0", + }, + }, + "parameterized component identifiers": { + base: signatureBase{ + { + key: &componentIdentifier{ + Item: httpsfv.Item{ + Value: "@query-param", + Params: petParams, + }, + }, + value: []string{"dog"}, + }, + { + key: &componentIdentifier{ + Item: httpsfv.Item{ + Value: "@query-param", + Params: catParams, + }, + }, + value: []string{"meow"}, + }, + { + key: &componentIdentifier{ + Item: httpsfv.Item{ + Value: "signature-agent", + Params: agentParams, + }, + }, + value: []string{ + `"https://bots.example.com";type=cimd`, + }, + }, + }, + expected: map[string]string{ + `@query-param;name="Pet"`: "dog", + `@query-param;name="Cat"`: "meow", + `signature-agent;key="sig1"`: `"https://bots.example.com";type=cimd`, + }, + }, + "boolean identifier parameter": { + base: signatureBase{ + { + key: &componentIdentifier{ + Item: httpsfv.Item{ + Value: "content-type", + Params: sfParams, + }, + }, + value: []string{"application/json"}, + }, + }, + expected: map[string]string{ + "content-type;sf": "application/json", + }, + }, + "multiple canonicalized values": { + base: signatureBase{ + { + key: &componentIdentifier{ + Item: httpsfv.NewItem("x-example"), + }, + value: []string{ + "first", + "second", + "third", + }, + }, + }, + expected: map[string]string{ + "x-example": "first, second, third", + }, + }, + "empty canonicalized value": { + base: signatureBase{ + { + key: &componentIdentifier{ + Item: httpsfv.NewItem("x-empty"), + }, + value: []string{""}, + }, + }, + expected: map[string]string{ + "x-empty": "", + }, + }, + } { + t.Run(uc, func(t *testing.T) { + t.Parallel() + + components, err := tc.base.components() + require.NoError(t, err) + + assert.Equal(t, tc.expected, components) + }) + } +} diff --git a/signature_parameters.go b/signature_parameters.go index a429243..2198f9b 100644 --- a/signature_parameters.go +++ b/signature_parameters.go @@ -138,48 +138,6 @@ func (p *signatureParameters) fromInnerList(list httpsfv.InnerList) error { return nil } -func (p *signatureParameters) toSignatureBase(msg *Message) ([]byte, error) { - marshalledSigParams, err := httpsfv.Marshal(p.InnerList) - if err != nil { - return nil, err - } - - sigBase := make(componentList, 0, len(p.identifiers)) - seen := make(map[string]struct{}, len(p.identifiers)) - - for _, ci := range p.identifiers { - identifier, err := httpsfv.Marshal(ci.Item) - if err != nil { - return nil, err - } - - if _, ok := seen[identifier]; ok { - return nil, fmt.Errorf("%w: duplicate component identifier %s", ErrMalformedData, identifier) - } - - seen[identifier] = struct{}{} - - comp, err := ci.createComponent(msg) - if err != nil { - return nil, err - } - - sigBase = append(sigBase, comp) - } - - sigBase = append(sigBase, component{ - key: &componentIdentifier{Item: httpsfv.NewItem("@signature-params")}, - value: []string{marshalledSigParams}, - }) - - base, err := sigBase.marshal() - if err != nil { - return nil, err - } - - return []byte(base), nil -} - func (p *signatureParameters) hasIdentifier(id *componentIdentifier) bool { for _, identifier := range p.identifiers { if identifier.Value == id.Value && slices.Equal(identifier.Params.Names(), id.Params.Names()) { diff --git a/signature_parameters_test.go b/signature_parameters_test.go index 46c2a8f..0b36da2 100644 --- a/signature_parameters_test.go +++ b/signature_parameters_test.go @@ -1,8 +1,6 @@ package httpsig import ( - "net/http" - "net/url" "testing" "time" @@ -483,130 +481,3 @@ func TestSignatureParametersFromInnerList(t *testing.T) { }) } } - -func TestSignatureParametersToSignatureBase(t *testing.T) { - t.Parallel() - - // test is based on the non-normative example from - // https://www.rfc-editor.org/rfc/rfc9421.html#name-creating-the-signature-base - - reqURL, err := url.Parse("http://example.com/foo?param=Value&Pet=dog&Cat=meow") - require.NoError(t, err) - - msg := &Message{ - Method: "POST", - Authority: "example.com", - URL: reqURL, - Header: http.Header{ - "Host": []string{"example.com"}, - "Date": []string{"Tue, 20 Apr 2021 02:07:55 GMT"}, - "Content-Type": []string{"application/json"}, - "Content-Digest": []string{"sha-512=:WZDPaVn/7XgHaAy8pmojAkGWoRx2UFChF41A2svX+TaPm+AbwAgBWnrIiYllu7BNNyealdVLvRwEmTHWXvJwew==:"}, - "Content-Length": []string{"18"}, - }, - StatusCode: 0, - IsRequest: true, - } - - keyID := "test-key-rsa-pss" - created, err := time.Parse(time.RFC1123, "Tue, 20 Apr 2021 02:07:53 GMT") - require.NoError(t, err) - - for _, tc := range []struct { - uc string - components []string - assert func(t *testing.T, err error, sigBase []byte) - }{ - { - uc: "successful signature base creation", - components: []string{ - "@method", "@authority", "@path", "content-digest", "content-length", "content-type", - }, - assert: func(t *testing.T, err error, sigBase []byte) { - t.Helper() - - require.NoError(t, err) - - expected := `"@method": POST -"@authority": example.com -"@path": /foo -"content-digest": sha-512=:WZDPaVn/7XgHaAy8pmojAkGWoRx2UFChF41A2svX+TaPm+AbwAgBWnrIiYllu7BNNyealdVLvRwEmTHWXvJwew==: -"content-length": 18 -"content-type": application/json -"@signature-params": ("@method" "@authority" "@path" "content-digest" "content-length" "content-type");created=1618884473;keyid="test-key-rsa-pss"` - - assert.Equal(t, expected, string(sigBase)) - }, - }, - { - uc: "failing for duplicate component identifier", - components: []string{ - "@method", "@method", - }, - assert: func(t *testing.T, err error, sigBase []byte) { - t.Helper() - - require.Error(t, err) - require.ErrorIs(t, err, ErrMalformedData) - require.ErrorContains(t, err, "duplicate component identifier") - assert.Nil(t, sigBase) - }, - }, - { - uc: "failing for duplicate parameterized component identifier", - components: []string{ - `@query-param;name="Pet"`, - `@query-param;name="Pet"`, - }, - assert: func(t *testing.T, err error, sigBase []byte) { - t.Helper() - - require.Error(t, err) - require.ErrorIs(t, err, ErrMalformedData) - require.ErrorContains(t, err, "duplicate component identifier") - assert.Nil(t, sigBase) - }, - }, - { - uc: "failing for unknown component identifier", - components: []string{"@status"}, - assert: func(t *testing.T, err error, sigBase []byte) { - t.Helper() - - require.Error(t, err) - require.ErrorIs(t, err, ErrCanonicalization) - require.ErrorContains(t, err, "@status") - assert.Nil(t, sigBase) - }, - }, - { - uc: "allowing same component identifier with different parameters", - components: []string{ - `@query-param;name="Pet"`, - `@query-param;name="Cat"`, - }, - assert: func(t *testing.T, err error, sigBase []byte) { - t.Helper() - - require.NoError(t, err) - - expected := `"@query-param";name="Pet": dog -"@query-param";name="Cat": meow -"@signature-params": ("@query-param";name="Pet" "@query-param";name="Cat");created=1618884473;keyid="test-key-rsa-pss"` - - assert.Equal(t, expected, string(sigBase)) - }, - }, - } { - t.Run(tc.uc, func(t *testing.T) { - identifiers, err := toComponentIdentifiers(tc.components) - require.NoError(t, err) - - params := newSignatureParameters(created, time.Time{}, "", keyID, "", "", identifiers) - - sigBase, err := params.toSignatureBase(msg) - - tc.assert(t, err, sigBase) - }) - } -} diff --git a/signer.go b/signer.go index 4bc115b..381730b 100644 --- a/signer.go +++ b/signer.go @@ -149,7 +149,7 @@ type signer struct { } func (s *signer) Sign(msg *Message) (http.Header, error) { - sp, err := s.signatureParameters(msg.Context) + params, err := s.signatureParameters(msg.Context) if err != nil { return nil, err } @@ -158,17 +158,22 @@ func (s *signer) Sign(msg *Message) (http.Header, error) { return nil, err } - base, err := sp.toSignatureBase(msg) + base, err := newSignatureBase(params, msg) if err != nil { return nil, err } - signature, err := s.ps.signPayload(base) + sb, err := base.marshal() if err != nil { return nil, err } - return msg.addSignature(s.label, signature, sp.InnerList) + signature, err := s.ps.signPayload(sb) + if err != nil { + return nil, err + } + + return msg.addSignature(s.label, signature, params.InnerList) } func (s *signer) signatureParameters(ctx context.Context) (*signatureParameters, error) { diff --git a/verifier.go b/verifier.go index 18aae71..9a1560f 100644 --- a/verifier.go +++ b/verifier.go @@ -478,7 +478,7 @@ func (v *verifier) verifySignature( params *signatureParameters, exp *expectations, ) error { - base, err := params.toSignatureBase(msg) + base, err := newSignatureBase(params, msg) if err != nil { return err } @@ -497,7 +497,12 @@ func (v *verifier) verifySignature( return err } - return verifier.verifyPayload(base, signature) + sb, err := base.marshal() + if err != nil { + return err + } + + return verifier.verifyPayload(sb, signature) } func getSignatureReferences(values []string) (map[string]*signatureParameters, error) { From 463d8dae80e05c51592f0b8714d1efe79f536517 Mon Sep 17 00:00:00 2001 From: Dimitrij Drus Date: Sun, 18 Oct 2026 18:25:08 +0200 Subject: [PATCH 2/2] linter warning resolved --- signature_base.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/signature_base.go b/signature_base.go index 9ebf3bb..b6271e7 100644 --- a/signature_base.go +++ b/signature_base.go @@ -72,7 +72,7 @@ func (s signatureBase) components() (map[string]string, error) { result := make(map[string]string, len(s)) for _, component := range s { - name := component.key.Value.(string) + name := component.key.Value.(string) // nolint: forcetypeassert if name == "@signature-params" { continue