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
2 changes: 2 additions & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ linters:
- m map[string]int
- w http.ResponseWriter
- r *http.Request
- c char
- b byte
exclusions:
generated: lax
presets:
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -662,6 +662,7 @@ 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.
- **Query parameter parsing:** `@query-param` uses Go's `url.URL.Query()` to parse form parameters. Its handling of malformed percent escapes, raw semicolons, and invalid UTF-8 differs from WHATWG form parsing. For ambiguous or repeated parameters, cover the entire query with `@query` instead. The `@query-param` component uses `%20` for spaces, following the RFC 9421 examples and other HMS implementations.

### Other Limitations

Expand Down
4 changes: 2 additions & 2 deletions accept_signature_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,7 @@ func TestNewSignatureRequest(t *testing.T) {
contentDigest.Params.Add("req", true)

queryParam := httpsfv.NewItem("@query-param")
queryParam.Params.Add("name", "a;b")
queryParam.Params.Add("name", "a%3Bb")

params := httpsfv.NewParams()
params.Add(string(Created), true)
Expand All @@ -456,7 +456,7 @@ func TestNewSignatureRequest(t *testing.T) {
},
expected: SignatureRequest{
Label: "sig",
Components: []string{`"@method"`, `"content-digest";req`, `"@query-param";name="a;b"`},
Components: []string{`"@method"`, `"content-digest";req`, `"@query-param";name="a%3Bb"`},
KeyID: "test-key",
Algorithm: Ed25519,
Tag: "app-123",
Expand Down
65 changes: 56 additions & 9 deletions canonicalizer.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"slices"
"strconv"
"strings"
"unicode/utf8"

"github.com/dunglas/httpsfv"
)
Expand Down Expand Up @@ -252,35 +253,43 @@ func newQueryParamCanonicalizer(params *httpsfv.Params) (canonicalizer, error) {
return nil, err
}

hasName := false
if params != nil {
_, hasName = params.Get("name")
if params == nil {
return nil, fmt.Errorf("%w: @query-param requires a 'name' parameter", ErrInvalidComponentIdentifier)
}

val, hasName := params.Get("name")
if !hasName {
return nil, fmt.Errorf("%w: @query-param requires a 'name' parameter", ErrInvalidComponentIdentifier)
}

name := val.(string) //nolint: forcetypeassert

decodedName, err := url.PathUnescape(name)
if err != nil {
return nil, fmt.Errorf("%w: invalid @query-param name %q: %w", ErrInvalidComponentIdentifier, name, err)
}

if !utf8.ValidString(decodedName) || encodeQueryParam(decodedName) != name {
return nil, fmt.Errorf("%w: @query-param name %q is not canonically encoded", ErrInvalidComponentIdentifier, name)
}

return canonicalizerFunc(func(msg *Message, params *httpsfv.Params) ([]string, error) {
// https://www.rfc-editor.org/rfc/rfc9421.html#name-query-parameters (Section 2.2.8)
if err := assertRequestOnly("@query-param", params, msg.IsRequest); err != nil {
return nil, err
}

val, _ := params.Get("name")
name := val.(string) //nolint: forcetypeassert

query := msg.queryParams()
if !query.Has(name) {
if !query.Has(decodedName) {
return nil, fmt.Errorf("%w: expected query parameter '%s' not found", ErrCanonicalization, name)
}

unescaped := query[name]
unescaped := query[decodedName]
if len(unescaped) > 1 {
return nil, fmt.Errorf("%w: query parameter '%s' occurs multiple times", ErrCanonicalization, name)
}

return []string{url.PathEscape(unescaped[0])}, nil
return []string{encodeQueryParam(unescaped[0])}, nil
}), nil
}

Expand Down Expand Up @@ -352,3 +361,41 @@ func newHeaderCanonicalizer(header string, params *httpsfv.Params) (canonicalize
return result, nil
}), nil
}

// encodeQueryParam uses the HTML form percent-encode set with spaces encoded
// as %20, as in RFC 9421 section 2.2.8's examples.
func encodeQueryParam(value string) string {
const hex = "0123456789ABCDEF"

for i := 0; i < len(value); i++ {
if queryParamUnescaped(value[i]) {
continue
}

var encoded strings.Builder
encoded.Grow(len(value) + 2) //nolint:mnd
encoded.WriteString(value[:i])

for ; i < len(value); i++ {
b := value[i]
if queryParamUnescaped(b) {
encoded.WriteByte(b)

continue
}

encoded.WriteByte('%')
encoded.WriteByte(hex[b>>4])
encoded.WriteByte(hex[b&0x0F])
}

return encoded.String()
}

return value
}

func queryParamUnescaped(c byte) bool {
return 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' ||
c == '*' || c == '-' || c == '.' || c == '_'
}
57 changes: 47 additions & 10 deletions canonicalizer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -304,11 +304,17 @@ func TestNewQueryParamCanonicalizer(t *testing.T) {
params map[string]any
valid bool
}{
"without params": {},
"without name": {params: map[string]any{"req": true}},
"with name": {params: map[string]any{"name": "foo"}, valid: true},
"with name and req": {params: map[string]any{"name": "foo", "req": true}, valid: true},
"with disallowed sf": {params: map[string]any{"name": "foo", "sf": true}},
"without params": {},
"without name": {params: map[string]any{"req": true}},
"with name": {params: map[string]any{"name": "foo"}, valid: true},
"with name and req": {params: map[string]any{"name": "foo", "req": true}, valid: true},
"with encoded name": {params: map[string]any{"name": "x%2By"}, valid: true},
"with invalid escape": {params: map[string]any{"name": "x%GG"}},
"with literal plus": {params: map[string]any{"name": "x+y"}},
"with lowercase escape": {params: map[string]any{"name": "x%2by"}},
"with escaped unreserved": {params: map[string]any{"name": "f%6Fo"}},
"with invalid UTF-8": {params: map[string]any{"name": "%FF"}},
"with disallowed sf": {params: map[string]any{"name": "foo", "sf": true}},
} {
t.Run(uc, func(t *testing.T) {
var params *httpsfv.Params
Expand Down Expand Up @@ -842,6 +848,21 @@ func TestCanonicalizeQueryParam(t *testing.T) {
message: &Message{URL: testURL1, IsRequest: true},
want: []string{"%5Bid%5D"},
},
"@query-param for request - percent-encoded plus in name": {
identifier: `"@query-param";name="x%2By"`,
message: &Message{URL: &url.URL{RawQuery: "x%2By=ok"}, IsRequest: true},
want: []string{"ok"},
},
"@query-param for request - percent-encoded space in name": {
identifier: `"@query-param";name="x%20y"`,
message: &Message{URL: &url.URL{RawQuery: "x+y=ok"}, IsRequest: true},
want: []string{"ok"},
},
"@query-param for request - empty value": {
identifier: `"@query-param";name="x"`,
message: &Message{URL: &url.URL{RawQuery: "x="}, IsRequest: true},
want: []string{""},
},
"@query-param for request - valid with duplicate unrelated parameter": {
identifier: `"@query-param";name="foo"`,
message: &Message{URL: &url.URL{RawQuery: "foo=bar&other=one&other=two"}, IsRequest: true},
Expand All @@ -857,11 +878,6 @@ func TestCanonicalizeQueryParam(t *testing.T) {
message: &Message{URL: &url.URL{RawQuery: "foo=one&%66oo=two"}, IsRequest: true},
errContains: "occurs multiple times",
},
"@query-param for response - invalid, duplicate request parameter": {
identifier: `"@query-param";name="foo";req`,
message: &Message{URL: &url.URL{RawQuery: "foo=one&foo=two"}, IsRequest: false},
errContains: "occurs multiple times",
},
"@query-param for request - invalid, parameter not present in query": {
identifier: `"@query-param";name="moo"`,
message: &Message{URL: testURL1, IsRequest: true},
Expand Down Expand Up @@ -999,3 +1015,24 @@ func TestCanonicalizeHeader(t *testing.T) {
})
}
}

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

for uc, tc := range map[string]struct {
value string
want string
}{
"empty value": {},
"unescaped ASCII": {value: "AZaz09*-._", want: "AZaz09*-._"},
"literal plus": {value: "a+b", want: "a%2Bb"},
"space": {value: "a b", want: "a%20b"},
"form special characters": {value: "a*b~c&d/e", want: "a*b%7Ec%26d%2Fe"},
"non-ASCII and newline": {value: "café\n", want: "caf%C3%A9%0A"},
"percent sign": {value: "a%b", want: "a%25b"},
} {
t.Run(uc, func(t *testing.T) {
assert.Equal(t, tc.want, encodeQueryParam(tc.value))
})
}
}
6 changes: 3 additions & 3 deletions integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,14 +95,14 @@ func TestParseAcceptSignatureBuilderOutput(t *testing.T) {
func TestParsedComponentsRoundTripThroughWithComponents(t *testing.T) {
t.Parallel()

const field = `sig=("@status" "content-digest";req "@query-param";name="a;b" "@query-param";name="b\"c" "@query-param";name="d\\e" "x_test");created`
const field = `sig=("@status" "content-digest";req "@query-param";name="a%3Bb" "@query-param";name="b%22c" "@query-param";name="d%5Ce" "x_test");created`

requests, err := ParseAcceptSignature(http.Header{headerAcceptSignature: {field}})
require.NoError(t, err)
require.Len(t, requests, 1)
assert.Equal(t, []string{
`"@status"`, `"content-digest";req`, `"@query-param";name="a;b"`,
`"@query-param";name="b\"c"`, `"@query-param";name="d\\e"`, `"x_test"`,
`"@status"`, `"content-digest";req`, `"@query-param";name="a%3Bb"`,
`"@query-param";name="b%22c"`, `"@query-param";name="d%5Ce"`, `"x_test"`,
}, requests[0].Components)

builder, err := NewAcceptSignature(
Expand Down
4 changes: 4 additions & 0 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,10 @@ func WithTTL(ttl time.Duration) SignerOption {

// WithComponents specifies component identifiers to cover when signing,
// require during verification, or request in Accept-Signature.
// For `@query-param`, the `name` component parameter must contain the
// canonical percent-encoded parameter name. For example, use
// `"@query-param";name="x%2By"` for a query parameter named `x+y`; a literal
// `+` in `name` is rejected.
func WithComponents(identifiers ...string) componentsOption {
return componentsOption{identifiers: identifiers}
}
Expand Down
Loading