Skip to content
Merged
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
53 changes: 52 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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:
Expand All @@ -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.
Expand Down Expand Up @@ -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.

Expand All @@ -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

Expand Down
116 changes: 116 additions & 0 deletions accept_signature_builder.go → accept_signature.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package httpsig

import (
"context"
"errors"
"fmt"
"net/http"

Expand Down Expand Up @@ -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
}
153 changes: 153 additions & 0 deletions accept_signature_builder_test.go → accept_signature_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"net/http"
"testing"

"github.com/dunglas/httpsfv"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
Expand Down Expand Up @@ -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)
}
})
}
}
Loading
Loading