Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,22 @@ verified, err := verifier.Verify(msg)
// error handling goes here
```

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.

```go
verifier, err := httpsig.NewVerifier(
keyResolver,
httpsig.WithSignatureSelection(),
httpsig.WithComponents("@method", "@target-uri"),
)
// error handling goes here

verified, err := verifier.Verify(msg, httpsig.WithLabel("sig1"))
// error handling goes here
```

`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.

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.

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:
Expand Down
34 changes: 34 additions & 0 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ func (f verifierOptionFunc) applyVerifierOption(v *verifier, e *verificationPoli

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

func (o labelOption) applyVerifyOption(policy *verificationPolicy) error {
if !policy.labelSelection {
return fmt.Errorf("%w: selecting a signature by label requires WithSignatureSelection", ErrParameter)
}

if len(o) == 0 {
return fmt.Errorf("%w: signature label must not be empty", ErrParameter)
}

if len(policy.selectedLabel) != 0 {
return fmt.Errorf("%w: signature label specified more than once", ErrParameter)
}

policy.selectedLabel = string(o)

return nil
}

// WithTTL specifies the interval between the created and expires signature
// parameters. A non-positive duration omits expires.
func WithTTL(ttl time.Duration) SignerOption {
Expand Down Expand Up @@ -445,6 +465,20 @@ func WithValidateAllSignatures() VerifierOption {
})
}

// WithSignatureSelection makes every Verify call check only the one signature
// chosen through WithLabel, which is then required on each call. The verifier's
// requirements apply to that signature and other signatures do not affect the
// result, except that the Signature-Input and Signature fields as a whole must
// be valid Structured Fields. It cannot be combined with WithValidateAllSignatures,
// WithRequiredTag, or WithSignatureNegotiation.
func WithSignatureSelection() VerifierOption {
return verifierOptionFunc(func(v *verifier, _ *verificationPolicy, _ bool) error {
v.signatureSelection = true

return nil
})
}

// WithCreatedTimestamp specifies whether the created parameter is required
// during verification or requested in Accept-Signature. False makes it
// optional during verification and omits it from Accept-Signature.
Expand Down
72 changes: 72 additions & 0 deletions options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -830,6 +830,78 @@ func TestWithValidateAllSignatures(t *testing.T) {
assert.True(t, v.validateAllSigs)
}

func TestWithSignatureSelection(t *testing.T) {
t.Parallel()

v := &verifier{}

err := WithSignatureSelection().applyVerifierOption(v, &verificationPolicy{}, false)

require.NoError(t, err)
assert.True(t, v.signatureSelection)
assert.False(t, v.validateAllSigs)
}

func TestWithLabelForVerify(t *testing.T) {
t.Parallel()

for uc, tc := range map[string]struct {
policy verificationPolicy
label string
assert func(t *testing.T, err error, policy *verificationPolicy)
}{
"selects label": {
policy: verificationPolicy{labelSelection: true},
label: "sig1",
assert: func(t *testing.T, err error, policy *verificationPolicy) {
t.Helper()

require.NoError(t, err)
assert.Equal(t, "sig1", policy.selectedLabel)
},
},
"rejects empty label": {
policy: verificationPolicy{labelSelection: true},
assert: func(t *testing.T, err error, _ *verificationPolicy) {
t.Helper()

require.ErrorIs(t, err, ErrParameter)
require.ErrorContains(t, err, "must not be empty")
},
},
"rejects repeated label": {
policy: verificationPolicy{labelSelection: true, selectedLabel: "sig1"},
label: "sig1",
assert: func(t *testing.T, err error, _ *verificationPolicy) {
t.Helper()

require.ErrorIs(t, err, ErrParameter)
require.ErrorContains(t, err, "more than once")
},
},
"rejects verifier without signature selection": {
label: "sig1",
assert: func(t *testing.T, err error, policy *verificationPolicy) {
t.Helper()

require.ErrorIs(t, err, ErrParameter)
require.ErrorContains(t, err, "WithSignatureSelection")
assert.Empty(t, policy.selectedLabel)
},
},
} {
t.Run(uc, func(t *testing.T) {
t.Parallel()

policy := tc.policy

err := WithLabel(tc.label).applyVerifyOption(&policy)

tc.assert(t, err, &policy)
})
}
}

func TestWithCreatedTimestampForVerifier(t *testing.T) {
t.Parallel()

Expand Down
2 changes: 2 additions & 0 deletions verification_policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ type verificationPolicy struct {
requiredParameters []SignatureParameter
forbiddenParameters []SignatureParameter
expectedParameters []parameterOption
labelSelection bool
selectedLabel string
}

// clone copies the parameter slices for per-call options. Other fields are
Expand Down
64 changes: 55 additions & 9 deletions verifier.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,14 @@ type applicableSignature struct {
}

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

if !ver.validateAllSigs && len(ver.tagPolicies) == 0 {
if ver.signatureSelection {
if ver.validateAllSigs || len(ver.tagPolicies) != 0 || globalPolicy.asb != nil {
return nil, fmt.Errorf("%w: signature selection cannot be combined with "+
"validation of all signatures, required tags, or signature negotiation", ErrVerifierCreation)
}

globalPolicy.labelSelection = true
} else if !ver.validateAllSigs && len(ver.tagPolicies) == 0 {
return nil, fmt.Errorf("%w: validation of all signatures disabled, but no signature tags specified",
ErrVerifierCreation)
}
Expand All @@ -97,7 +107,7 @@ func NewVerifier(resolver KeyResolver, opts ...VerifierOption) (Verifier, error)
}
}

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

type verifier struct {
keyResolver KeyResolver
tagPolicies map[string]*verificationPolicy
validateAllSigs bool
keyResolver KeyResolver
tagPolicies map[string]*verificationPolicy
validateAllSigs bool
signatureSelection bool
}

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

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

// signatureReferences returns the Signature-Input members to consider. With
// signature selection, only the selected member is kept, so a member the
// caller did not select cannot fail the call. Its absence yields an empty result.
func (v *verifier) signatureReferences(
msg *Message,
policiesByTag map[string]*verificationPolicy,
) (*httpsfv.Dictionary, error) {
values := msg.Header.Values(headerSignatureInput)

if !v.signatureSelection {
return getSignatureReferences(values)
}

label := policiesByTag[""].selectedLabel
if len(label) == 0 {
return nil, fmt.Errorf("%w: signature selection requires a label", ErrParameter)
}

inputDict, err := httpsfv.UnmarshalDictionary(values)
if err != nil {
return nil, fmt.Errorf("%w: %w", ErrMalformedData, err)
}

selected := httpsfv.NewDictionary()
if member, present := inputDict.Get(label); present {
selected.Add(label, member)
}

return checkSignatureReferences(selected)
}

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 {
if !v.validateAllSigs && !v.signatureSelection {
tag, present := signatureTag(list)
if !present {
continue
Expand Down Expand Up @@ -386,6 +428,10 @@ func getSignatureReferences(values []string) (*httpsfv.Dictionary, error) {
return nil, fmt.Errorf("%w: %w", ErrMalformedData, err)
}

return checkSignatureReferences(inputDict)
}

func checkSignatureReferences(inputDict *httpsfv.Dictionary) (*httpsfv.Dictionary, error) {
// Check member types without converting values that require semantic validation.
for _, label := range inputDict.Names() {
m, _ := inputDict.Get(label)
Expand Down
Loading
Loading