Skip to content

Commit 15f6cbd

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 2d41d74 commit 15f6cbd

6 files changed

Lines changed: 554 additions & 16 deletions

File tree

‎README.md‎

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

114+
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.
115+
116+
```go
117+
verifier, err := httpsig.NewVerifier(
118+
keyResolver,
119+
httpsig.WithSignatureSelection(),
120+
httpsig.WithComponents("@method", "@target-uri"),
121+
)
122+
// error handling goes here
123+
124+
verified, err := verifier.Verify(msg, httpsig.WithLabel("sig1"))
125+
// error handling goes here
126+
```
127+
128+
`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.
129+
114130
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.
115131

116132
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 {
@@ -428,6 +448,20 @@ func WithValidateAllSignatures() VerifierOption {
428448
})
429449
}
430450

451+
// WithSignatureSelection makes every Verify call check only the one signature
452+
// chosen through WithLabel, which is then required on each call. The verifier's
453+
// requirements apply to that signature and other signatures do not affect the
454+
// result, except that the Signature-Input and Signature fields as a whole must
455+
// be valid Structured Fields. It cannot be combined with WithValidateAllSignatures,
456+
// WithRequiredTag, or WithSignatureNegotiation.
457+
func WithSignatureSelection() VerifierOption {
458+
return verifierOptionFunc(func(v *verifier, _ *verificationPolicy, _ bool) error {
459+
v.signatureSelection = true
460+
461+
return nil
462+
})
463+
}
464+
431465
// WithCreatedTimestamp specifies whether the created parameter is required
432466
// during verification or requested in Accept-Signature. False makes it
433467
// 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
@@ -785,6 +785,78 @@ func TestWithValidateAllSignatures(t *testing.T) {
785785
assert.True(t, v.validateAllSigs)
786786
}
787787

788+
func TestWithSignatureSelection(t *testing.T) {
789+
t.Parallel()
790+
791+
v := &verifier{}
792+
793+
err := WithSignatureSelection().applyVerifierOption(v, &verificationPolicy{}, false)
794+
795+
require.NoError(t, err)
796+
assert.True(t, v.signatureSelection)
797+
assert.False(t, v.validateAllSigs)
798+
}
799+
800+
func TestWithLabelForVerify(t *testing.T) {
801+
t.Parallel()
802+
803+
for uc, tc := range map[string]struct {
804+
policy verificationPolicy
805+
label string
806+
assert func(t *testing.T, err error, policy *verificationPolicy)
807+
}{
808+
"selects label": {
809+
policy: verificationPolicy{labelSelection: true},
810+
label: "sig1",
811+
assert: func(t *testing.T, err error, policy *verificationPolicy) {
812+
t.Helper()
813+
814+
require.NoError(t, err)
815+
assert.Equal(t, "sig1", policy.selectedLabel)
816+
},
817+
},
818+
"rejects empty label": {
819+
policy: verificationPolicy{labelSelection: true},
820+
assert: func(t *testing.T, err error, _ *verificationPolicy) {
821+
t.Helper()
822+
823+
require.ErrorIs(t, err, ErrParameter)
824+
require.ErrorContains(t, err, "must not be empty")
825+
},
826+
},
827+
"rejects repeated label": {
828+
policy: verificationPolicy{labelSelection: true, selectedLabel: "sig1"},
829+
label: "sig1",
830+
assert: func(t *testing.T, err error, _ *verificationPolicy) {
831+
t.Helper()
832+
833+
require.ErrorIs(t, err, ErrParameter)
834+
require.ErrorContains(t, err, "more than once")
835+
},
836+
},
837+
"rejects verifier without signature selection": {
838+
label: "sig1",
839+
assert: func(t *testing.T, err error, policy *verificationPolicy) {
840+
t.Helper()
841+
842+
require.ErrorIs(t, err, ErrParameter)
843+
require.ErrorContains(t, err, "WithSignatureSelection")
844+
assert.Empty(t, policy.selectedLabel)
845+
},
846+
},
847+
} {
848+
t.Run(uc, func(t *testing.T) {
849+
t.Parallel()
850+
851+
policy := tc.policy
852+
853+
err := WithLabel(tc.label).applyVerifyOption(&policy)
854+
855+
tc.assert(t, err, &policy)
856+
})
857+
}
858+
}
859+
788860
func TestWithCreatedTimestampForVerifier(t *testing.T) {
789861
t.Parallel()
790862

‎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: 76 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -47,11 +47,14 @@ type Verifier interface {
4747
}
4848

4949
// NewVerifier creates a Verifier instance.
50-
// Without WithValidateAllSignatures, at least one WithRequiredTag is necessary.
50+
// Signatures must be selected through WithValidateAllSignatures, at least one
51+
// WithRequiredTag, or WithSignatureSelection. The first two may be combined,
52+
// while WithSignatureSelection excludes both.
5153
// By default, created and expires are required and signatures may be at most
5254
// 30 seconds old. Optional created or expires parameters are still checked
5355
// when present. Global WithSignatureNegotiation cannot be combined with
54-
// WithValidateAllSignatures. More specific requirements can be set through opts.
56+
// WithValidateAllSignatures or WithSignatureSelection. More specific requirements
57+
// can be set through opts.
5558
//
5659
//nolint:cyclop
5760
func NewVerifier(resolver KeyResolver, opts ...VerifierOption) (Verifier, error) {
@@ -76,7 +79,14 @@ func NewVerifier(resolver KeyResolver, opts ...VerifierOption) (Verifier, error)
7679
}
7780
}
7881

79-
if !ver.validateAllSigs && len(ver.tagPolicies) == 0 {
82+
if ver.signatureSelection {
83+
if ver.validateAllSigs || len(ver.tagPolicies) != 0 || globalPolicy.asb != nil {
84+
return nil, fmt.Errorf("%w: signature selection cannot be combined with "+
85+
"validation of all signatures, required tags, or signature negotiation", ErrVerifierCreation)
86+
}
87+
88+
globalPolicy.labelSelection = true
89+
} else if !ver.validateAllSigs && len(ver.tagPolicies) == 0 {
8090
return nil, fmt.Errorf("%w: validation of all signatures disabled, but no signature tags specified",
8191
ErrVerifierCreation)
8292
}
@@ -92,7 +102,7 @@ func NewVerifier(resolver KeyResolver, opts ...VerifierOption) (Verifier, error)
92102
}
93103
}
94104

95-
if ver.validateAllSigs {
105+
if ver.validateAllSigs || ver.signatureSelection {
96106
if err := globalPolicy.prepare(""); err != nil {
97107
return nil, fmt.Errorf("%w: %w", ErrVerifierCreation, err)
98108
}
@@ -123,9 +133,10 @@ func newPayloadVerifier(verificationKey any, alg SignatureAlgorithm) (payloadVer
123133
}
124134

125135
type verifier struct {
126-
keyResolver KeyResolver
127-
tagPolicies map[string]*verificationPolicy
128-
validateAllSigs bool
136+
keyResolver KeyResolver
137+
tagPolicies map[string]*verificationPolicy
138+
validateAllSigs bool
139+
signatureSelection bool
129140
}
130141

131142
func (v *verifier) Verify(msg *Message, opts ...VerifyOption) (VerificationResult, error) {
@@ -134,7 +145,7 @@ func (v *verifier) Verify(msg *Message, opts ...VerifyOption) (VerificationResul
134145
return nil, fmt.Errorf("%w: %w", ErrVerificationFailed, err)
135146
}
136147

137-
sigRefs, err := getSignatureReferences(msg.Header.Values(headerSignatureInput))
148+
sigRefs, err := v.signatureReferences(msg, policiesByTag)
138149
if err != nil {
139150
return nil, fmt.Errorf("%w: %w", ErrVerificationFailed, err)
140151
}
@@ -203,8 +214,29 @@ func (v *verifier) policiesForCall(opts []VerifyOption) (map[string]*verificatio
203214
return result, nil
204215
}
205216

217+
// signatureReferences returns the parsed signature inputs to consider. With
218+
// signature selection, only the selected member is parsed, so a member the
219+
// caller did not select cannot fail the call. Its absence yields an empty result.
220+
func (v *verifier) signatureReferences(
221+
msg *Message,
222+
policiesByTag map[string]*verificationPolicy,
223+
) (map[string]*signatureInput, error) {
224+
values := msg.Header.Values(headerSignatureInput)
225+
226+
if !v.signatureSelection {
227+
return getSignatureReferences(values)
228+
}
229+
230+
label := policiesByTag[""].selectedLabel
231+
if len(label) == 0 {
232+
return nil, fmt.Errorf("%w: signature selection requires a label", ErrParameter)
233+
}
234+
235+
return getSignatureReference(values, label)
236+
}
237+
206238
func (v *verifier) applicableSignatures(refs map[string]*signatureInput) (map[string]*signatureInput, error) {
207-
if !v.validateAllSigs {
239+
if !v.validateAllSigs && !v.signatureSelection {
208240
for name, input := range refs {
209241
tag, present := input.tag()
210242
if !present {
@@ -337,14 +369,9 @@ func getSignatureReferences(values []string) (map[string]*signatureInput, error)
337369
for _, label := range inputDict.Names() {
338370
m, _ := inputDict.Get(label)
339371

340-
sigParams, ok := m.(httpsfv.InnerList)
341-
if !ok {
342-
return nil, fmt.Errorf("%w: unexpected signature parameters format", ErrMalformedData)
343-
}
344-
345-
si, err := parseSignatureInput(sigParams)
372+
si, err := parseSignatureReference(m)
346373
if err != nil {
347-
return nil, fmt.Errorf("%w: %w", ErrMalformedData, err)
374+
return nil, err
348375
}
349376

350377
sigRefs[label] = si
@@ -353,6 +380,39 @@ func getSignatureReferences(values []string) (map[string]*signatureInput, error)
353380
return sigRefs, nil
354381
}
355382

383+
func getSignatureReference(values []string, label string) (map[string]*signatureInput, error) {
384+
inputDict, err := httpsfv.UnmarshalDictionary(values)
385+
if err != nil {
386+
return nil, fmt.Errorf("%w: %w", ErrMalformedData, err)
387+
}
388+
389+
m, present := inputDict.Get(label)
390+
if !present {
391+
return map[string]*signatureInput{}, nil
392+
}
393+
394+
si, err := parseSignatureReference(m)
395+
if err != nil {
396+
return nil, err
397+
}
398+
399+
return map[string]*signatureInput{label: si}, nil
400+
}
401+
402+
func parseSignatureReference(member httpsfv.Member) (*signatureInput, error) {
403+
sigParams, ok := member.(httpsfv.InnerList)
404+
if !ok {
405+
return nil, fmt.Errorf("%w: unexpected signature parameters format", ErrMalformedData)
406+
}
407+
408+
si, err := parseSignatureInput(sigParams)
409+
if err != nil {
410+
return nil, fmt.Errorf("%w: %w", ErrMalformedData, err)
411+
}
412+
413+
return si, nil
414+
}
415+
356416
func (v *verifier) extractSignature(dict *httpsfv.Dictionary, name string) ([]byte, error) {
357417
sigItem, ok := dict.Get(name)
358418
if !ok {

0 commit comments

Comments
 (0)