Skip to content

Commit 36ff8e1

Browse files
committed
feat: Supporting verification of a signature selected by label
WithSignatureSelection makes Verify check only the signature named by WithLabel, so other signatures on the message don't affect the result.
1 parent a572b10 commit 36ff8e1

6 files changed

Lines changed: 538 additions & 9 deletions

File tree

‎README.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,22 @@ verified, err := verifier.Verify(msg)
129129
// error handling goes here
130130
```
131131

132+
If your application picks the signature to check itself, for example because its protocol doesn't use tags, declare `WithSignatureSelection` and name the signature on each call with `WithLabel`. Only that signature is verified and the verifier's requirements apply to it. Other signatures don't affect the result, unless a `Signature-Input` or `Signature` field as a whole isn't valid Structured Fields.
133+
134+
```go
135+
verifier, err := httpsig.NewVerifier(
136+
keyResolver,
137+
httpsig.WithSignatureSelection(),
138+
httpsig.WithComponents("@method", "@target-uri"),
139+
)
140+
// error handling goes here
141+
142+
verified, err := verifier.Verify(msg, httpsig.WithLabel("sig1"))
143+
// error handling goes here
144+
```
145+
146+
`WithSignatureSelection` can't be combined with `WithValidateAllSignatures`, `WithRequiredTag`, or `WithSignatureNegotiation`. If the message has no signature with that label, `Verify` returns an error wrapping `NoApplicableSignatureError`. If `WithLabel` is missing, empty, or given more than once, or is used on a verifier without `WithSignatureSelection`, `Verify` returns an error wrapping `ErrParameter`. Labels aren't signed, so a label only chooses what to check and must not be treated as an identity or authorization claim.
147+
132148
Global verifier options act as defaults for required tags. Tag-specific options take precedence (for example, `WithComponents` replaces the global component list), while required, forbidden, and expected signature-parameter constraints are additive. Automatic signature negotiation uses these effective per-tag requirements.
133149

134150
The same APIs also verify incoming requests and sign outgoing responses. Both `Signer.Sign` and `Verifier.Verify` operate on a `Message`, created for the corresponding HTTP direction:

‎options.go‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,8 @@ func (f verifierOptionFunc) applyVerifierOption(v *verifier, e *verificationPoli
7878

7979
// WithLabel specifies the technical label for a signature or an
8080
// Accept-Signature request. An empty label leaves the current label unchanged.
81+
// For Verify, it selects the signature to check; see WithSignatureSelection.
82+
// There, an empty label is rejected.
8183
func WithLabel(label string) labelOption {
8284
return labelOption(label)
8385
}
@@ -112,6 +114,24 @@ func (o labelOption) applySignatureNegotiationOption(opts *sigNegotiationOptions
112114
opts.opts = append(opts.opts, o)
113115
}
114116

117+
func (o labelOption) applyVerifyOption(policy *verificationPolicy) error {
118+
if !policy.labelSelection {
119+
return fmt.Errorf("%w: selecting a signature by label requires WithSignatureSelection", ErrParameter)
120+
}
121+
122+
if len(o) == 0 {
123+
return fmt.Errorf("%w: signature label must not be empty", ErrParameter)
124+
}
125+
126+
if len(policy.selectedLabel) != 0 {
127+
return fmt.Errorf("%w: signature label specified more than once", ErrParameter)
128+
}
129+
130+
policy.selectedLabel = string(o)
131+
132+
return nil
133+
}
134+
115135
// WithTTL specifies the interval between the created and expires signature
116136
// parameters. A non-positive duration omits expires.
117137
func WithTTL(ttl time.Duration) SignerOption {
@@ -445,6 +465,20 @@ func WithValidateAllSignatures() VerifierOption {
445465
})
446466
}
447467

468+
// WithSignatureSelection makes every Verify call check only the one signature
469+
// chosen through WithLabel, which is then required on each call. The verifier's
470+
// requirements apply to that signature and other signatures do not affect the
471+
// result, except that the Signature-Input and Signature fields as a whole must
472+
// be valid Structured Fields. It cannot be combined with WithValidateAllSignatures,
473+
// WithRequiredTag, or WithSignatureNegotiation.
474+
func WithSignatureSelection() VerifierOption {
475+
return verifierOptionFunc(func(v *verifier, _ *verificationPolicy, _ bool) error {
476+
v.signatureSelection = true
477+
478+
return nil
479+
})
480+
}
481+
448482
// WithCreatedTimestamp specifies whether the created parameter is required
449483
// during verification or requested in Accept-Signature. False makes it
450484
// optional during verification and omits it from Accept-Signature.

‎options_test.go‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -830,6 +830,78 @@ func TestWithValidateAllSignatures(t *testing.T) {
830830
assert.True(t, v.validateAllSigs)
831831
}
832832

833+
func TestWithSignatureSelection(t *testing.T) {
834+
t.Parallel()
835+
836+
v := &verifier{}
837+
838+
err := WithSignatureSelection().applyVerifierOption(v, &verificationPolicy{}, false)
839+
840+
require.NoError(t, err)
841+
assert.True(t, v.signatureSelection)
842+
assert.False(t, v.validateAllSigs)
843+
}
844+
845+
func TestWithLabelForVerify(t *testing.T) {
846+
t.Parallel()
847+
848+
for uc, tc := range map[string]struct {
849+
policy verificationPolicy
850+
label string
851+
assert func(t *testing.T, err error, policy *verificationPolicy)
852+
}{
853+
"selects label": {
854+
policy: verificationPolicy{labelSelection: true},
855+
label: "sig1",
856+
assert: func(t *testing.T, err error, policy *verificationPolicy) {
857+
t.Helper()
858+
859+
require.NoError(t, err)
860+
assert.Equal(t, "sig1", policy.selectedLabel)
861+
},
862+
},
863+
"rejects empty label": {
864+
policy: verificationPolicy{labelSelection: true},
865+
assert: func(t *testing.T, err error, _ *verificationPolicy) {
866+
t.Helper()
867+
868+
require.ErrorIs(t, err, ErrParameter)
869+
require.ErrorContains(t, err, "must not be empty")
870+
},
871+
},
872+
"rejects repeated label": {
873+
policy: verificationPolicy{labelSelection: true, selectedLabel: "sig1"},
874+
label: "sig1",
875+
assert: func(t *testing.T, err error, _ *verificationPolicy) {
876+
t.Helper()
877+
878+
require.ErrorIs(t, err, ErrParameter)
879+
require.ErrorContains(t, err, "more than once")
880+
},
881+
},
882+
"rejects verifier without signature selection": {
883+
label: "sig1",
884+
assert: func(t *testing.T, err error, policy *verificationPolicy) {
885+
t.Helper()
886+
887+
require.ErrorIs(t, err, ErrParameter)
888+
require.ErrorContains(t, err, "WithSignatureSelection")
889+
assert.Empty(t, policy.selectedLabel)
890+
},
891+
},
892+
} {
893+
t.Run(uc, func(t *testing.T) {
894+
t.Parallel()
895+
896+
policy := tc.policy
897+
898+
err := WithLabel(tc.label).applyVerifyOption(&policy)
899+
900+
tc.assert(t, err, &policy)
901+
})
902+
}
903+
}
904+
833905
func TestWithCreatedTimestampForVerifier(t *testing.T) {
834906
t.Parallel()
835907

‎verification_policy.go‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ type verificationPolicy struct {
2121
requiredParameters []SignatureParameter
2222
forbiddenParameters []SignatureParameter
2323
expectedParameters []parameterOption
24+
labelSelection bool
25+
selectedLabel string
2426
}
2527

2628
// clone copies the parameter slices for per-call options. Other fields are

‎verifier.go‎

Lines changed: 55 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -52,11 +52,14 @@ type applicableSignature struct {
5252
}
5353

5454
// NewVerifier creates a Verifier instance.
55-
// Without WithValidateAllSignatures, at least one WithRequiredTag is necessary.
55+
// Signatures must be selected through WithValidateAllSignatures, at least one
56+
// WithRequiredTag, or WithSignatureSelection. The first two may be combined,
57+
// while WithSignatureSelection excludes both.
5658
// By default, created and expires are required and signatures may be at most
5759
// 30 seconds old. Optional created or expires parameters are still checked
5860
// when present. Global WithSignatureNegotiation cannot be combined with
59-
// WithValidateAllSignatures. More specific requirements can be set through opts.
61+
// WithValidateAllSignatures or WithSignatureSelection. More specific requirements
62+
// can be set through opts.
6063
//
6164
//nolint:cyclop
6265
func NewVerifier(resolver KeyResolver, opts ...VerifierOption) (Verifier, error) {
@@ -81,7 +84,14 @@ func NewVerifier(resolver KeyResolver, opts ...VerifierOption) (Verifier, error)
8184
}
8285
}
8386

84-
if !ver.validateAllSigs && len(ver.tagPolicies) == 0 {
87+
if ver.signatureSelection {
88+
if ver.validateAllSigs || len(ver.tagPolicies) != 0 || globalPolicy.asb != nil {
89+
return nil, fmt.Errorf("%w: signature selection cannot be combined with "+
90+
"validation of all signatures, required tags, or signature negotiation", ErrVerifierCreation)
91+
}
92+
93+
globalPolicy.labelSelection = true
94+
} else if !ver.validateAllSigs && len(ver.tagPolicies) == 0 {
8595
return nil, fmt.Errorf("%w: validation of all signatures disabled, but no signature tags specified",
8696
ErrVerifierCreation)
8797
}
@@ -97,7 +107,7 @@ func NewVerifier(resolver KeyResolver, opts ...VerifierOption) (Verifier, error)
97107
}
98108
}
99109

100-
if ver.validateAllSigs {
110+
if ver.validateAllSigs || ver.signatureSelection {
101111
if err := globalPolicy.prepare(""); err != nil {
102112
return nil, fmt.Errorf("%w: %w", ErrVerifierCreation, err)
103113
}
@@ -130,9 +140,10 @@ func newPayloadVerifier(verificationKey any, alg SignatureAlgorithm) (payloadVer
130140
}
131141

132142
type verifier struct {
133-
keyResolver KeyResolver
134-
tagPolicies map[string]*verificationPolicy
135-
validateAllSigs bool
143+
keyResolver KeyResolver
144+
tagPolicies map[string]*verificationPolicy
145+
validateAllSigs bool
146+
signatureSelection bool
136147
}
137148

138149
func (v *verifier) Verify(msg *Message, opts ...VerifyOption) (VerificationResult, error) {
@@ -141,7 +152,7 @@ func (v *verifier) Verify(msg *Message, opts ...VerifyOption) (VerificationResul
141152
return nil, fmt.Errorf("%w: %w", ErrVerificationFailed, err)
142153
}
143154

144-
sigRefs, err := getSignatureReferences(msg.Header.Values(headerSignatureInput))
155+
sigRefs, err := v.signatureReferences(msg, policiesByTag)
145156
if err != nil {
146157
return nil, fmt.Errorf("%w: %w", ErrVerificationFailed, err)
147158
}
@@ -211,14 +222,45 @@ func (v *verifier) policiesForCall(opts []VerifyOption) (map[string]*verificatio
211222
return result, nil
212223
}
213224

225+
// signatureReferences returns the Signature-Input members to consider. With
226+
// signature selection, only the selected member is kept, so a member the
227+
// caller did not select cannot fail the call. Its absence yields an empty result.
228+
func (v *verifier) signatureReferences(
229+
msg *Message,
230+
policiesByTag map[string]*verificationPolicy,
231+
) (*httpsfv.Dictionary, error) {
232+
values := msg.Header.Values(headerSignatureInput)
233+
234+
if !v.signatureSelection {
235+
return getSignatureReferences(values)
236+
}
237+
238+
label := policiesByTag[""].selectedLabel
239+
if len(label) == 0 {
240+
return nil, fmt.Errorf("%w: signature selection requires a label", ErrParameter)
241+
}
242+
243+
inputDict, err := httpsfv.UnmarshalDictionary(values)
244+
if err != nil {
245+
return nil, fmt.Errorf("%w: %w", ErrMalformedData, err)
246+
}
247+
248+
selected := httpsfv.NewDictionary()
249+
if member, present := inputDict.Get(label); present {
250+
selected.Add(label, member)
251+
}
252+
253+
return checkSignatureReferences(selected)
254+
}
255+
214256
func (v *verifier) applicableSignatures(refs *httpsfv.Dictionary) ([]applicableSignature, error) {
215257
result := make([]applicableSignature, 0, len(refs.Names()))
216258

217259
for _, label := range refs.Names() {
218260
member, _ := refs.Get(label)
219261

220262
list := member.(httpsfv.InnerList) //nolint:forcetypeassert
221-
if !v.validateAllSigs {
263+
if !v.validateAllSigs && !v.signatureSelection {
222264
tag, present := signatureTag(list)
223265
if !present {
224266
continue
@@ -386,6 +428,10 @@ func getSignatureReferences(values []string) (*httpsfv.Dictionary, error) {
386428
return nil, fmt.Errorf("%w: %w", ErrMalformedData, err)
387429
}
388430

431+
return checkSignatureReferences(inputDict)
432+
}
433+
434+
func checkSignatureReferences(inputDict *httpsfv.Dictionary) (*httpsfv.Dictionary, error) {
389435
// Check member types without converting values that require semantic validation.
390436
for _, label := range inputDict.Names() {
391437
m, _ := inputDict.Get(label)

0 commit comments

Comments
 (0)