diff --git a/canonicalizer.go b/canonicalizer.go index 1feb41c..651e630 100644 --- a/canonicalizer.go +++ b/canonicalizer.go @@ -5,6 +5,7 @@ import ( "net" "net/http" "net/url" + "slices" "strconv" "strings" @@ -34,18 +35,45 @@ func assertRequestOnly(name string, params *httpsfv.Params, isRequest bool) erro return nil } -func assertResponseOnly(name string, params *httpsfv.Params, isRequest bool) error { - if _, isReq := params.Get("req"); isRequest || isReq { - return fmt.Errorf("%w: %s not valid for requests", ErrCanonicalization, name) +// assertParameters checks whether parameters are applicable to a +// component and have the required RFC 9421 types and values. +// +//nolint:cyclop +func assertParameters(name string, params *httpsfv.Params, allowed ...string) error { + if params == nil { + return nil } - return nil -} + for _, param := range params.Names() { + if !slices.Contains(allowed, param) { + return fmt.Errorf("%w: parameter %q is not applicable to %s", + ErrInvalidComponentIdentifier, param, name) + } -func assertParameter(name string, params *httpsfv.Params, isRequest bool) error { - if _, forReq := params.Get("req"); forReq && isRequest { - return fmt.Errorf("%w: 'req' parameter in %s is not valid for requests", - ErrCanonicalization, name) + value, _ := params.Get(param) + + switch param { + case "sf", "bs", "tr", "req": + enabled, ok := value.(bool) + if !ok || !enabled { + return fmt.Errorf("%w: %s parameter %q must be true", + ErrInvalidComponentIdentifier, name, param) + } + case "key": + key, ok := value.(string) + if !ok || key == "" { + return fmt.Errorf("%w: %s parameter %q must be a non-empty string", + ErrInvalidComponentIdentifier, name, param) + } + case "name": + if _, ok := value.(string); !ok { + return fmt.Errorf("%w: %s parameter %q must be a string", + ErrInvalidComponentIdentifier, name, param) + } + default: + return fmt.Errorf("%w: %s has unsupported parameter %q", + ErrInvalidComponentIdentifier, name, param) + } } return nil @@ -55,165 +83,235 @@ func assertParameter(name string, params *httpsfv.Params, isRequest bool) error func canonicalizerFor(name string, params *httpsfv.Params) (canonicalizer, error) { switch name { case "@method": - return canonicalizerFunc(canonicalizeMethod), nil + return newMethodCanonicalizer(params) case "@target-uri": - return canonicalizerFunc(canonicalizeTargetURI), nil + return newTargetURICanonicalizer(params) case "@authority": - return canonicalizerFunc(canonicalizeAuthority), nil + return newAuthorityCanonicalizer(params) case "@scheme": - return canonicalizerFunc(canonicalizeScheme), nil + return newSchemeCanonicalizer(params) case "@request-target": - return canonicalizerFunc(canonicalizeRequestTarget), nil + return newRequestTargetCanonicalizer(params) case "@path": - return canonicalizerFunc(canonicalizePath), nil + return newPathCanonicalizer(params) case "@query": - return canonicalizerFunc(canonicalizeQuery), nil + return newQueryCanonicalizer(params) case "@query-param": - if params == nil { - return nil, fmt.Errorf("%w: @query-param requires a 'name' parameter", ErrInvalidComponentIdentifier) - } - - value, present := params.Get("name") - if !present { - return nil, fmt.Errorf("%w: @query-param requires a 'name' parameter", ErrInvalidComponentIdentifier) - } - - if _, ok := value.(string); !ok { - return nil, fmt.Errorf("%w: @query-param 'name' must be a string", ErrInvalidComponentIdentifier) - } - - return canonicalizerFunc(canonicalizeQueryParam), nil + return newQueryParamCanonicalizer(params) case "@status": - return canonicalizerFunc(canonicalizeStatusCode), nil + return newStatusCodeCanonicalizer(params) default: if strings.HasPrefix(name, "@") { return nil, fmt.Errorf("%w: %s", ErrUnsupportedComponentIdentifier, name) } - return headerCanonicalizer(name), nil + return newHeaderCanonicalizer(name, params) } } -func canonicalizeMethod(msg *Message, params *httpsfv.Params) ([]string, error) { - // https://www.rfc-editor.org/rfc/rfc9421.html#content-request-method (Section 2.2.1) - if err := assertRequestOnly("@method", params, msg.IsRequest); err != nil { +func newMethodCanonicalizer(params *httpsfv.Params) (canonicalizer, error) { + if err := assertParameters("@method", params, "req"); err != nil { return nil, err } - return []string{msg.Method}, nil + return canonicalizerFunc(func(msg *Message, params *httpsfv.Params) ([]string, error) { + // https://www.rfc-editor.org/rfc/rfc9421.html#content-request-method (Section 2.2.1) + if err := assertRequestOnly("@method", params, msg.IsRequest); err != nil { + return nil, err + } + + return []string{msg.Method}, nil + }), nil } -func canonicalizeTargetURI(msg *Message, params *httpsfv.Params) ([]string, error) { - // https://www.rfc-editor.org/rfc/rfc9421.html#name-target-uri (Section 2.2.2) - if err := assertRequestOnly("@target-uri", params, msg.IsRequest); err != nil { +func newTargetURICanonicalizer(params *httpsfv.Params) (canonicalizer, error) { + if err := assertParameters("@target-uri", params, "req"); err != nil { return nil, err } - return []string{msg.URL.String()}, nil + return canonicalizerFunc(func(msg *Message, params *httpsfv.Params) ([]string, error) { + // https://www.rfc-editor.org/rfc/rfc9421.html#name-target-uri (Section 2.2.2) + if err := assertRequestOnly("@target-uri", params, msg.IsRequest); err != nil { + return nil, err + } + + return []string{msg.URL.String()}, nil + }), nil } -func canonicalizeAuthority(msg *Message, params *httpsfv.Params) ([]string, error) { - // https://www.rfc-editor.org/rfc/rfc9421.html#name-authority (Section 2.2.3) - if err := assertRequestOnly("@authority", params, msg.IsRequest); err != nil { +func newAuthorityCanonicalizer(params *httpsfv.Params) (canonicalizer, error) { + if err := assertParameters("@authority", params, "req"); err != nil { return nil, err } - host, port, err := net.SplitHostPort(msg.Authority) - if err != nil { - // no port, just use the whole thing - return []string{strings.ToLower(msg.Authority)}, nil //nolint:nilerr - } + return canonicalizerFunc(func(msg *Message, params *httpsfv.Params) ([]string, error) { + // https://www.rfc-editor.org/rfc/rfc9421.html#name-authority (Section 2.2.3) + if err := assertRequestOnly("@authority", params, msg.IsRequest); err != nil { + return nil, err + } - // default ports shall be omitted - switch strings.ToLower(msg.URL.Scheme) { - case "http": - if port == "80" { - return []string{strings.ToLower(host)}, nil + host, port, err := net.SplitHostPort(msg.Authority) + if err != nil { + // no port, just use the whole thing + return []string{strings.ToLower(msg.Authority)}, nil //nolint:nilerr } - case "https": - if port == "443" { - return []string{strings.ToLower(host)}, nil + + // default ports shall be omitted + switch strings.ToLower(msg.URL.Scheme) { + case "http": + if port == "80" { + return []string{strings.ToLower(host)}, nil + } + case "https": + if port == "443" { + return []string{strings.ToLower(host)}, nil + } } - } - return []string{strings.ToLower(msg.Authority)}, nil + return []string{strings.ToLower(msg.Authority)}, nil + }), nil } -func canonicalizeScheme(msg *Message, params *httpsfv.Params) ([]string, error) { - // https://www.rfc-editor.org/rfc/rfc9421.html#name-scheme (Section 2.2.4) - if err := assertRequestOnly("@scheme", params, msg.IsRequest); err != nil { +func newSchemeCanonicalizer(params *httpsfv.Params) (canonicalizer, error) { + if err := assertParameters("@scheme", params, "req"); err != nil { return nil, err } - return []string{strings.ToLower(msg.URL.Scheme)}, nil + return canonicalizerFunc(func(msg *Message, params *httpsfv.Params) ([]string, error) { + // https://www.rfc-editor.org/rfc/rfc9421.html#name-scheme (Section 2.2.4) + if err := assertRequestOnly("@scheme", params, msg.IsRequest); err != nil { + return nil, err + } + + return []string{strings.ToLower(msg.URL.Scheme)}, nil + }), nil } -func canonicalizeRequestTarget(msg *Message, params *httpsfv.Params) ([]string, error) { - // https://www.rfc-editor.org/rfc/rfc9421.html#name-request-target (Section 2.2.5) - if err := assertRequestOnly("@request-target", params, msg.IsRequest); err != nil { +func newRequestTargetCanonicalizer(params *httpsfv.Params) (canonicalizer, error) { + if err := assertParameters("@request-target", params, "req"); err != nil { return nil, err } - return []string{msg.URL.RequestURI()}, nil + return canonicalizerFunc(func(msg *Message, params *httpsfv.Params) ([]string, error) { + // https://www.rfc-editor.org/rfc/rfc9421.html#name-request-target (Section 2.2.5) + if err := assertRequestOnly("@request-target", params, msg.IsRequest); err != nil { + return nil, err + } + + return []string{msg.URL.RequestURI()}, nil + }), nil } -func canonicalizePath(msg *Message, params *httpsfv.Params) ([]string, error) { - // https://www.rfc-editor.org/rfc/rfc9421.html#name-path (Section 2.2.6) - if err := assertRequestOnly("@path", params, msg.IsRequest); err != nil { +func newPathCanonicalizer(params *httpsfv.Params) (canonicalizer, error) { + if err := assertParameters("@path", params, "req"); err != nil { return nil, err } - path := msg.URL.EscapedPath() - if len(path) == 0 || path[0] != '/' { - path = "/" + path - } + return canonicalizerFunc(func(msg *Message, params *httpsfv.Params) ([]string, error) { + // https://www.rfc-editor.org/rfc/rfc9421.html#name-path (Section 2.2.6) + if err := assertRequestOnly("@path", params, msg.IsRequest); err != nil { + return nil, err + } + + path := msg.URL.EscapedPath() + if len(path) == 0 || path[0] != '/' { + path = "/" + path + } - return []string{path}, nil + return []string{path}, nil + }), nil } -func canonicalizeQuery(msg *Message, params *httpsfv.Params) ([]string, error) { - // https://www.rfc-editor.org/rfc/rfc9421.html#name-query (Section 2.2.7) - if err := assertRequestOnly("@query", params, msg.IsRequest); err != nil { +func newQueryCanonicalizer(params *httpsfv.Params) (canonicalizer, error) { + if err := assertParameters("@query", params, "req"); err != nil { return nil, err } - // absent query params means use `?` - return []string{"?" + msg.URL.RawQuery}, nil + return canonicalizerFunc(func(msg *Message, params *httpsfv.Params) ([]string, error) { + // https://www.rfc-editor.org/rfc/rfc9421.html#name-query (Section 2.2.7) + if err := assertRequestOnly("@query", params, msg.IsRequest); err != nil { + return nil, err + } + + // absent query params means use `?` + return []string{"?" + msg.URL.RawQuery}, nil + }), nil } -func canonicalizeQueryParam(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 { +func newQueryParamCanonicalizer(params *httpsfv.Params) (canonicalizer, error) { + if err := assertParameters("@query-param", params, "req", "name"); err != nil { return nil, err } - val, _ := params.Get("name") - name := val.(string) //nolint: forcetypeassert - - query := msg.queryParams() - if !query.Has(name) { - return nil, fmt.Errorf("%w: expected query parameter '%s' not found", ErrCanonicalization, name) + hasName := false + if params != nil { + _, hasName = params.Get("name") } - unescaped := query[name] - if len(unescaped) > 1 { - return nil, fmt.Errorf("%w: query parameter '%s' occurs multiple times", ErrCanonicalization, name) + if !hasName { + return nil, fmt.Errorf("%w: @query-param requires a 'name' parameter", ErrInvalidComponentIdentifier) } - return []string{url.PathEscape(unescaped[0])}, nil + 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) { + return nil, fmt.Errorf("%w: expected query parameter '%s' not found", ErrCanonicalization, name) + } + + unescaped := query[name] + if len(unescaped) > 1 { + return nil, fmt.Errorf("%w: query parameter '%s' occurs multiple times", ErrCanonicalization, name) + } + + return []string{url.PathEscape(unescaped[0])}, nil + }), nil } -func canonicalizeStatusCode(msg *Message, params *httpsfv.Params) ([]string, error) { - // https://www.rfc-editor.org/rfc/rfc9421.html#name-status-code (Section 2.2.9) - if err := assertResponseOnly("@status", params, msg.IsRequest); err != nil { +func newStatusCodeCanonicalizer(params *httpsfv.Params) (canonicalizer, error) { + if err := assertParameters("@status", params); err != nil { return nil, err } - return []string{strconv.Itoa(msg.StatusCode)}, nil + return canonicalizerFunc(func(msg *Message, _ *httpsfv.Params) ([]string, error) { + // https://www.rfc-editor.org/rfc/rfc9421.html#name-status-code (Section 2.2.9) + if msg.IsRequest { + return nil, fmt.Errorf("%w: @status not valid for requests", ErrCanonicalization) + } + + return []string{strconv.Itoa(msg.StatusCode)}, nil + }), nil } -func headerCanonicalizer(header string) canonicalizerFunc { - return func(msg *Message, params *httpsfv.Params) ([]string, error) { +//nolint:cyclop +func newHeaderCanonicalizer(header string, params *httpsfv.Params) (canonicalizer, error) { + if err := assertParameters(header, params, "sf", "key", "bs", "tr", "req"); err != nil { + return nil, err + } + + if params != nil { + if _, present := params.Get("tr"); present { + return nil, fmt.Errorf("%w: trailer fields are not supported", ErrInvalidComponentIdentifier) + } + + _, bs := params.Get("bs") + _, sf := params.Get("sf") + + _, key := params.Get("key") + if bs && (sf || key) { + return nil, fmt.Errorf("%w: cannot combine 'bs' with 'sf' or 'key' on %s", + ErrInvalidComponentIdentifier, header) + } + } + + return canonicalizerFunc(func(msg *Message, params *httpsfv.Params) ([]string, error) { serializer, err := newSerializer(params, msg.IsRequest) if err != nil { return nil, fmt.Errorf("%w: %s: %w", ErrCanonicalization, header, err) @@ -221,10 +319,6 @@ func headerCanonicalizer(header string) canonicalizerFunc { var hdr http.Header - if err := assertParameter(header, params, msg.IsRequest); err != nil { - return nil, err - } - if _, isReq := params.Get("req"); !msg.IsRequest && isReq { hdr = msg.RequestHeader } else { @@ -247,5 +341,5 @@ func headerCanonicalizer(header string) canonicalizerFunc { } return result, nil - } + }), nil } diff --git a/canonicalizer_test.go b/canonicalizer_test.go index 5df4c8f..a88fbc4 100644 --- a/canonicalizer_test.go +++ b/canonicalizer_test.go @@ -11,40 +11,85 @@ import ( "github.com/stretchr/testify/require" ) -func TestCanonicalizerFor(t *testing.T) { +func TestAssertParameters(t *testing.T) { t.Parallel() - queryParams := httpsfv.NewParams() - queryParams.Add("name", "foo") + allowed := []string{"sf", "bs", "tr", "req", "key", "name"} + for uc, tc := range map[string]struct { + parameter string + value any + allowed []string + invalid bool + }{ + "no parameters": {}, + "true sf flag": {parameter: "sf", value: true, allowed: allowed}, + "false sf flag": {parameter: "sf", value: false, allowed: allowed, invalid: true}, + "false bs flag": {parameter: "bs", value: false, allowed: allowed, invalid: true}, + "false req flag": {parameter: "req", value: false, allowed: allowed, invalid: true}, + "false tr flag": {parameter: "tr", value: false, allowed: allowed, invalid: true}, + "non-boolean sf flag": {parameter: "sf", value: int64(1), allowed: allowed, invalid: true}, + "non-boolean bs flag": {parameter: "bs", value: "true", allowed: allowed, invalid: true}, + "string key": {parameter: "key", value: "foo", allowed: allowed}, + "empty key": {parameter: "key", value: "", allowed: allowed, invalid: true}, + "non-string key": {parameter: "key", value: httpsfv.Token("foo"), allowed: allowed, invalid: true}, + "string name": {parameter: "name", value: "foo", allowed: allowed}, + "empty name": {parameter: "name", value: "", allowed: allowed}, + "non-string name": {parameter: "name", value: httpsfv.Token("foo"), allowed: allowed, invalid: true}, + "unknown parameter": {parameter: "unknown", value: true, allowed: allowed, invalid: true}, + "allowed parameter": {parameter: "req", value: true, allowed: []string{"req", "name"}}, + "disallowed parameter": {parameter: "sf", value: true, allowed: []string{"req"}, invalid: true}, + "no allowed parameters": {parameter: "req", value: true, invalid: true}, + } { + t.Run(uc, func(t *testing.T) { + var params *httpsfv.Params + if tc.parameter != "" { + params = httpsfv.NewParams() + params.Add(tc.parameter, tc.value) + } - nonStringQueryParams := httpsfv.NewParams() - nonStringQueryParams.Add("name", httpsfv.Token("foo")) + err := assertParameters("x-test", params, tc.allowed...) + if tc.invalid { + require.ErrorIs(t, err, ErrInvalidComponentIdentifier) + require.ErrorContains(t, err, tc.parameter) + } else { + require.NoError(t, err) + } + }) + } +} + +func TestCanonicalizerFor(t *testing.T) { + t.Parallel() for uc, tc := range map[string]struct { name string - params *httpsfv.Params + params map[string]any err error }{ - "@method": {name: "@method"}, - "@target-uri": {name: "@target-uri"}, - "@authority": {name: "@authority"}, - "@scheme": {name: "@scheme"}, - "@request-target": {name: "@request-target"}, - "@path": {name: "@path"}, - "@query": {name: "@query"}, - "@query-param": {name: "@query-param", params: queryParams}, - "@query-param without name": {name: "@query-param", params: httpsfv.NewParams(), err: ErrInvalidComponentIdentifier}, - "@query-param with non-string name": {name: "@query-param", params: nonStringQueryParams, err: ErrInvalidComponentIdentifier}, - "@status": {name: "@status"}, - "@foo": {name: "@foo", err: ErrUnsupportedComponentIdentifier}, - "x-foo-bar": {name: "x-foo-bar"}, + "@method": {name: "@method"}, + "@target-uri": {name: "@target-uri"}, + "@authority": {name: "@authority"}, + "@scheme": {name: "@scheme"}, + "@request-target": {name: "@request-target"}, + "@path": {name: "@path"}, + "@query": {name: "@query"}, + "@query-param": {name: "@query-param", params: map[string]any{"name": "foo"}}, + "@status": {name: "@status"}, + "@foo": {name: "@foo", err: ErrUnsupportedComponentIdentifier}, + "x-foo-bar": {name: "x-foo-bar"}, } { t.Run(uc, func(t *testing.T) { - c, err := canonicalizerFor(tc.name, tc.params) + var params *httpsfv.Params + if tc.params != nil { + params = httpsfv.NewParams() + for name, value := range tc.params { + params.Add(name, value) + } + } + c, err := canonicalizerFor(tc.name, params) if tc.err != nil { require.ErrorIs(t, err, tc.err) - require.ErrorContains(t, err, tc.name) assert.Nil(t, c) return @@ -56,579 +101,866 @@ func TestCanonicalizerFor(t *testing.T) { } } -func TestCanonicalization(t *testing.T) { +func TestNewMethodCanonicalizer(t *testing.T) { t.Parallel() - url1 := "https://example.com/foo%2Fbaz/bar%5Bid%5D?foo=bar&bar=%5Bid%5D" - testURL1, err := url.Parse(url1) - require.NoError(t, err) + for uc, tc := range map[string]struct { + params map[string]any + invalid bool + }{ + "with req": {params: map[string]any{"req": true}}, + "with req and sf": {params: map[string]any{"req": true, "sf": true}, invalid: true}, + } { + t.Run(uc, func(t *testing.T) { + params := httpsfv.NewParams() + for name, value := range tc.params { + params.Add(name, value) + } + + c, err := newMethodCanonicalizer(params) + if tc.invalid { + require.ErrorIs(t, err, ErrInvalidComponentIdentifier) + assert.Nil(t, c) + } else { + require.NoError(t, err) + assert.NotNil(t, c) + } + }) + } +} + +func TestNewTargetURICanonicalizer(t *testing.T) { + t.Parallel() + + for uc, tc := range map[string]struct { + params map[string]any + invalid bool + }{ + "with req": {params: map[string]any{"req": true}}, + "with req and sf": {params: map[string]any{"req": true, "sf": true}, invalid: true}, + } { + t.Run(uc, func(t *testing.T) { + params := httpsfv.NewParams() + for name, value := range tc.params { + params.Add(name, value) + } + + c, err := newTargetURICanonicalizer(params) + if tc.invalid { + require.ErrorIs(t, err, ErrInvalidComponentIdentifier) + assert.Nil(t, c) + } else { + require.NoError(t, err) + assert.NotNil(t, c) + } + }) + } +} + +func TestNewAuthorityCanonicalizer(t *testing.T) { + t.Parallel() + + for uc, tc := range map[string]struct { + params map[string]any + invalid bool + }{ + "with req": {params: map[string]any{"req": true}}, + "with req and sf": {params: map[string]any{"req": true, "sf": true}, invalid: true}, + } { + t.Run(uc, func(t *testing.T) { + params := httpsfv.NewParams() + for name, value := range tc.params { + params.Add(name, value) + } + + c, err := newAuthorityCanonicalizer(params) + if tc.invalid { + require.ErrorIs(t, err, ErrInvalidComponentIdentifier) + assert.Nil(t, c) + } else { + require.NoError(t, err) + assert.NotNil(t, c) + } + }) + } +} + +func TestNewSchemeCanonicalizer(t *testing.T) { + t.Parallel() + + for uc, tc := range map[string]struct { + params map[string]any + invalid bool + }{ + "with req": {params: map[string]any{"req": true}}, + "with req and sf": {params: map[string]any{"req": true, "sf": true}, invalid: true}, + } { + t.Run(uc, func(t *testing.T) { + params := httpsfv.NewParams() + for name, value := range tc.params { + params.Add(name, value) + } + + c, err := newSchemeCanonicalizer(params) + if tc.invalid { + require.ErrorIs(t, err, ErrInvalidComponentIdentifier) + assert.Nil(t, c) + } else { + require.NoError(t, err) + assert.NotNil(t, c) + } + }) + } +} + +func TestNewRequestTargetCanonicalizer(t *testing.T) { + t.Parallel() + + for uc, tc := range map[string]struct { + params map[string]any + invalid bool + }{ + "with req": {params: map[string]any{"req": true}}, + "with req and sf": {params: map[string]any{"req": true, "sf": true}, invalid: true}, + } { + t.Run(uc, func(t *testing.T) { + params := httpsfv.NewParams() + for name, value := range tc.params { + params.Add(name, value) + } + + c, err := newRequestTargetCanonicalizer(params) + if tc.invalid { + require.ErrorIs(t, err, ErrInvalidComponentIdentifier) + assert.Nil(t, c) + } else { + require.NoError(t, err) + assert.NotNil(t, c) + } + }) + } +} + +func TestNewPathCanonicalizer(t *testing.T) { + t.Parallel() + + for uc, tc := range map[string]struct { + params map[string]any + invalid bool + }{ + "with req": {params: map[string]any{"req": true}}, + "with req and sf": {params: map[string]any{"req": true, "sf": true}, invalid: true}, + } { + t.Run(uc, func(t *testing.T) { + params := httpsfv.NewParams() + for name, value := range tc.params { + params.Add(name, value) + } + + c, err := newPathCanonicalizer(params) + if tc.invalid { + require.ErrorIs(t, err, ErrInvalidComponentIdentifier) + assert.Nil(t, c) + } else { + require.NoError(t, err) + assert.NotNil(t, c) + } + }) + } +} + +func TestNewQueryCanonicalizer(t *testing.T) { + t.Parallel() for uc, tc := range map[string]struct { - identifier string - message *Message - assert func(t *testing.T, err error, value []string) + params map[string]any + invalid bool + }{ + "with req": {params: map[string]any{"req": true}}, + "with req and sf": {params: map[string]any{"req": true, "sf": true}, invalid: true}, + } { + t.Run(uc, func(t *testing.T) { + params := httpsfv.NewParams() + for name, value := range tc.params { + params.Add(name, value) + } + + c, err := newQueryCanonicalizer(params) + if tc.invalid { + require.ErrorIs(t, err, ErrInvalidComponentIdentifier) + assert.Nil(t, c) + } else { + require.NoError(t, err) + assert.NotNil(t, c) + } + }) + } +} + +func TestNewQueryParamCanonicalizer(t *testing.T) { + t.Parallel() + + for uc, tc := range map[string]struct { + 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}}, + } { + t.Run(uc, func(t *testing.T) { + var params *httpsfv.Params + if tc.params != nil { + params = httpsfv.NewParams() + for name, value := range tc.params { + params.Add(name, value) + } + } + + c, err := newQueryParamCanonicalizer(params) + if tc.valid { + require.NoError(t, err) + assert.NotNil(t, c) + } else { + require.ErrorIs(t, err, ErrInvalidComponentIdentifier) + assert.Nil(t, c) + } + }) + } +} + +func TestNewStatusCodeCanonicalizer(t *testing.T) { + t.Parallel() + + for uc, tc := range map[string]struct { + params map[string]any + invalid bool + }{ + "without parameters": {}, + "with req": {params: map[string]any{"req": true}, invalid: true}, + } { + t.Run(uc, func(t *testing.T) { + var params *httpsfv.Params + if tc.params != nil { + params = httpsfv.NewParams() + for name, value := range tc.params { + params.Add(name, value) + } + } + + c, err := newStatusCodeCanonicalizer(params) + if tc.invalid { + require.ErrorIs(t, err, ErrInvalidComponentIdentifier) + assert.Nil(t, c) + } else { + require.NoError(t, err) + assert.NotNil(t, c) + } + }) + } +} + +func TestNewHeaderCanonicalizer(t *testing.T) { + t.Parallel() + + for uc, tc := range map[string]struct { + params map[string]any + valid bool + }{ + "without parameters": {valid: true}, + "with req": {params: map[string]any{"req": true}, valid: true}, + "with sf and key": {params: map[string]any{"sf": true, "key": "foo"}, valid: true}, + "with bs": {params: map[string]any{"bs": true}, valid: true}, + "with sf and bs": {params: map[string]any{"sf": true, "bs": true}}, + "with key and bs": {params: map[string]any{"key": "foo", "bs": true}}, + "with tr": {params: map[string]any{"tr": true}}, + "with name": {params: map[string]any{"name": "foo"}}, + } { + t.Run(uc, func(t *testing.T) { + var params *httpsfv.Params + if tc.params != nil { + params = httpsfv.NewParams() + for name, value := range tc.params { + params.Add(name, value) + } + } + + c, err := newHeaderCanonicalizer("x-foo-bar", params) + if tc.valid { + require.NoError(t, err) + assert.NotNil(t, c) + } else { + require.ErrorIs(t, err, ErrInvalidComponentIdentifier) + assert.Nil(t, c) + } + }) + } +} + +func TestCanonicalizeMethod(t *testing.T) { + t.Parallel() + + for uc, tc := range map[string]struct { + identifier string + message *Message + want []string + errContains string }{ "@method for request - valid": { identifier: `"@method"`, message: &Message{Method: http.MethodGet, IsRequest: true}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - assert.Equal(t, []string{http.MethodGet}, value) - }, + want: []string{http.MethodGet}, }, "@method for request - invalid": { - identifier: `"@method";req`, - message: &Message{Method: http.MethodGet, IsRequest: true}, - assert: func(t *testing.T, err error, _ []string) { - t.Helper() - - require.Error(t, err) - require.ErrorIs(t, err, ErrCanonicalization) - require.ErrorContains(t, err, "is not valid for requests") - }, + identifier: `"@method";req`, + message: &Message{Method: http.MethodGet, IsRequest: true}, + errContains: "is not valid for requests", }, "@method for response - valid": { identifier: `"@method";req`, message: &Message{Method: http.MethodPost, IsRequest: false}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - assert.Equal(t, []string{http.MethodPost}, value) - }, + want: []string{http.MethodPost}, }, "@method for response - invalid": { - identifier: `"@method"`, - message: &Message{Method: http.MethodGet, IsRequest: false}, - assert: func(t *testing.T, err error, _ []string) { - t.Helper() + identifier: `"@method"`, + message: &Message{Method: http.MethodGet, IsRequest: false}, + errContains: "@method not valid for responses", + }, + } { + t.Run(uc, func(t *testing.T) { + item, err := httpsfv.UnmarshalItem([]string{tc.identifier}) + require.NoError(t, err) + + c, err := newMethodCanonicalizer(item.Params) + require.NoError(t, err) - require.Error(t, err) + value, err := c.canonicalize(tc.message, item.Params) + if tc.errContains != "" { require.ErrorIs(t, err, ErrCanonicalization) - require.ErrorContains(t, err, "@method not valid for responses") - }, - }, + require.ErrorContains(t, err, tc.errContains) + } else { + require.NoError(t, err) + assert.Equal(t, tc.want, value) + } + }) + } +} + +func TestCanonicalizeTargetURI(t *testing.T) { + t.Parallel() + + url1 := "https://example.com/foo%2Fbaz/bar%5Bid%5D?foo=bar&bar=%5Bid%5D" + testURL1, err := url.Parse(url1) + require.NoError(t, err) + + for uc, tc := range map[string]struct { + identifier string + message *Message + want []string + errContains string + }{ "@target-uri for request - valid": { identifier: `"@target-uri"`, message: &Message{URL: testURL1, IsRequest: true}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - require.Equal(t, []string{url1}, value) - }, + want: []string{url1}, }, "@target-uri for request - invalid": { - identifier: `"@target-uri";req`, - message: &Message{Method: http.MethodGet, IsRequest: true}, - assert: func(t *testing.T, err error, _ []string) { - t.Helper() - - require.Error(t, err) - require.ErrorIs(t, err, ErrCanonicalization) - require.ErrorContains(t, err, "is not valid for requests") - }, + identifier: `"@target-uri";req`, + message: &Message{Method: http.MethodGet, IsRequest: true}, + errContains: "is not valid for requests", }, "@target-uri for response - valid": { identifier: `"@target-uri";req`, message: &Message{URL: testURL1, IsRequest: false}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - require.Equal(t, []string{url1}, value) - }, + want: []string{url1}, }, "@target-uri for response - invalid": { - identifier: `"@target-uri"`, - message: &Message{URL: testURL1, IsRequest: false}, - assert: func(t *testing.T, err error, _ []string) { - t.Helper() + identifier: `"@target-uri"`, + message: &Message{URL: testURL1, IsRequest: false}, + errContains: "@target-uri not valid for responses", + }, + } { + t.Run(uc, func(t *testing.T) { + item, err := httpsfv.UnmarshalItem([]string{tc.identifier}) + require.NoError(t, err) + + c, err := newTargetURICanonicalizer(item.Params) + require.NoError(t, err) - require.Error(t, err) + value, err := c.canonicalize(tc.message, item.Params) + if tc.errContains != "" { require.ErrorIs(t, err, ErrCanonicalization) - require.ErrorContains(t, err, "@target-uri not valid for responses") - }, - }, + require.ErrorContains(t, err, tc.errContains) + } else { + require.NoError(t, err) + assert.Equal(t, tc.want, value) + } + }) + } +} + +func TestCanonicalizeAuthority(t *testing.T) { + t.Parallel() + + for uc, tc := range map[string]struct { + identifier string + message *Message + want []string + errContains string + }{ "@authority for request - valid http without port": { identifier: `"@authority"`, message: &Message{Authority: "example.com", URL: &url.URL{Scheme: "http"}, IsRequest: true}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - require.Equal(t, []string{"example.com"}, value) - }, + want: []string{"example.com"}, }, "@authority for request - valid https without port": { identifier: `"@authority"`, message: &Message{Authority: "example.com", URL: &url.URL{Scheme: "https"}, IsRequest: true}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - require.Equal(t, []string{"example.com"}, value) - }, + want: []string{"example.com"}, }, "@authority for request - valid http with default port": { identifier: `"@authority"`, message: &Message{Authority: "example.com:80", URL: &url.URL{Scheme: "http"}, IsRequest: true}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - require.Equal(t, []string{"example.com"}, value) - }, + want: []string{"example.com"}, }, "@authority for request - valid https with default port": { identifier: `"@authority"`, message: &Message{Authority: "example.com:443", URL: &url.URL{Scheme: "https"}, IsRequest: true}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - require.Equal(t, []string{"example.com"}, value) - }, + want: []string{"example.com"}, }, "@authority for request - valid http with custom port": { identifier: `"@authority"`, message: &Message{Authority: "example.com:8080", URL: &url.URL{Scheme: "http"}, IsRequest: true}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - require.Equal(t, []string{"example.com:8080"}, value) - }, + want: []string{"example.com:8080"}, }, "@authority for request - valid https with custom port": { identifier: `"@authority"`, message: &Message{Authority: "example.com:8443", URL: &url.URL{Scheme: "https"}, IsRequest: true}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - require.Equal(t, []string{"example.com:8443"}, value) - }, + want: []string{"example.com:8443"}, }, "@authority for request - invalid": { - identifier: `"@authority";req`, - message: &Message{Authority: "example.com", URL: &url.URL{Scheme: "http"}, IsRequest: true}, - assert: func(t *testing.T, err error, _ []string) { - t.Helper() - - require.Error(t, err) - require.ErrorIs(t, err, ErrCanonicalization) - require.ErrorContains(t, err, "is not valid for requests") - }, + identifier: `"@authority";req`, + message: &Message{Authority: "example.com", URL: &url.URL{Scheme: "http"}, IsRequest: true}, + errContains: "is not valid for requests", }, "@authority for response - valid": { identifier: `"@authority";req`, message: &Message{Authority: "example.com", URL: &url.URL{Scheme: "http"}, IsRequest: false}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - require.Equal(t, []string{"example.com"}, value) - }, + want: []string{"example.com"}, }, "@authority for response - invalid": { - identifier: `"@authority"`, - message: &Message{Authority: "example.com", URL: &url.URL{Scheme: "http"}, IsRequest: false}, - assert: func(t *testing.T, err error, _ []string) { - t.Helper() - - require.Error(t, err) - }, + identifier: `"@authority"`, + message: &Message{Authority: "example.com", URL: &url.URL{Scheme: "http"}, IsRequest: false}, + errContains: "not valid for responses", }, + } { + t.Run(uc, func(t *testing.T) { + item, err := httpsfv.UnmarshalItem([]string{tc.identifier}) + require.NoError(t, err) + + c, err := newAuthorityCanonicalizer(item.Params) + require.NoError(t, err) + + value, err := c.canonicalize(tc.message, item.Params) + if tc.errContains != "" { + require.ErrorIs(t, err, ErrCanonicalization) + require.ErrorContains(t, err, tc.errContains) + } else { + require.NoError(t, err) + assert.Equal(t, tc.want, value) + } + }) + } +} + +func TestCanonicalizeScheme(t *testing.T) { + t.Parallel() + + for uc, tc := range map[string]struct { + identifier string + message *Message + want []string + errContains string + }{ "@scheme for request - valid": { identifier: `"@scheme"`, message: &Message{URL: &url.URL{Scheme: "http"}, IsRequest: true}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - assert.Equal(t, []string{"http"}, value) - }, + want: []string{"http"}, }, "@scheme for request - invalid": { - identifier: `"@scheme";req`, - message: &Message{URL: &url.URL{Scheme: "http"}, IsRequest: true}, - assert: func(t *testing.T, err error, _ []string) { - t.Helper() - - require.Error(t, err) - require.ErrorIs(t, err, ErrCanonicalization) - require.ErrorContains(t, err, "is not valid for requests") - }, + identifier: `"@scheme";req`, + message: &Message{URL: &url.URL{Scheme: "http"}, IsRequest: true}, + errContains: "is not valid for requests", }, "@scheme for response - valid": { identifier: `"@scheme";req`, message: &Message{URL: &url.URL{Scheme: "https"}, IsRequest: false}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - assert.Equal(t, []string{"https"}, value) - }, + want: []string{"https"}, }, "@scheme for response - invalid": { - identifier: `"@scheme"`, - message: &Message{URL: &url.URL{Scheme: "https"}, IsRequest: false}, - assert: func(t *testing.T, err error, _ []string) { - t.Helper() + identifier: `"@scheme"`, + message: &Message{URL: &url.URL{Scheme: "https"}, IsRequest: false}, + errContains: "@scheme not valid for responses", + }, + } { + t.Run(uc, func(t *testing.T) { + item, err := httpsfv.UnmarshalItem([]string{tc.identifier}) + require.NoError(t, err) - require.Error(t, err) + c, err := newSchemeCanonicalizer(item.Params) + require.NoError(t, err) + + value, err := c.canonicalize(tc.message, item.Params) + if tc.errContains != "" { require.ErrorIs(t, err, ErrCanonicalization) - require.ErrorContains(t, err, "@scheme not valid for responses") - }, - }, + require.ErrorContains(t, err, tc.errContains) + } else { + require.NoError(t, err) + assert.Equal(t, tc.want, value) + } + }) + } +} + +func TestCanonicalizeRequestTarget(t *testing.T) { + t.Parallel() + + url1 := "https://example.com/foo%2Fbaz/bar%5Bid%5D?foo=bar&bar=%5Bid%5D" + testURL1, err := url.Parse(url1) + require.NoError(t, err) + + for uc, tc := range map[string]struct { + identifier string + message *Message + want []string + errContains string + }{ "@request-target for request - valid": { identifier: `"@request-target"`, message: &Message{URL: testURL1, IsRequest: true}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - assert.Equal(t, []string{"/foo%2Fbaz/bar%5Bid%5D?foo=bar&bar=%5Bid%5D"}, value) - }, + want: []string{"/foo%2Fbaz/bar%5Bid%5D?foo=bar&bar=%5Bid%5D"}, }, "@request-target for request - invalid": { - identifier: `"@request-target";req`, - message: &Message{URL: testURL1, IsRequest: true}, - assert: func(t *testing.T, err error, _ []string) { - t.Helper() - - require.Error(t, err) - require.ErrorIs(t, err, ErrCanonicalization) - require.ErrorContains(t, err, "is not valid for requests") - }, + identifier: `"@request-target";req`, + message: &Message{URL: testURL1, IsRequest: true}, + errContains: "is not valid for requests", }, "@request-target for response - valid": { identifier: `"@request-target";req`, message: &Message{URL: testURL1, IsRequest: false}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - assert.Equal(t, []string{"/foo%2Fbaz/bar%5Bid%5D?foo=bar&bar=%5Bid%5D"}, value) - }, + want: []string{"/foo%2Fbaz/bar%5Bid%5D?foo=bar&bar=%5Bid%5D"}, }, "@request-target for response - invalid": { - identifier: `"@request-target"`, - message: &Message{URL: testURL1, IsRequest: false}, - assert: func(t *testing.T, err error, _ []string) { - t.Helper() + identifier: `"@request-target"`, + message: &Message{URL: testURL1, IsRequest: false}, + errContains: "@request-target not valid for responses", + }, + } { + t.Run(uc, func(t *testing.T) { + item, err := httpsfv.UnmarshalItem([]string{tc.identifier}) + require.NoError(t, err) + + c, err := newRequestTargetCanonicalizer(item.Params) + require.NoError(t, err) - require.Error(t, err) + value, err := c.canonicalize(tc.message, item.Params) + if tc.errContains != "" { require.ErrorIs(t, err, ErrCanonicalization) - require.ErrorContains(t, err, "@request-target not valid for responses") - }, - }, + require.ErrorContains(t, err, tc.errContains) + } else { + require.NoError(t, err) + assert.Equal(t, tc.want, value) + } + }) + } +} + +func TestCanonicalizePath(t *testing.T) { + t.Parallel() + + for uc, tc := range map[string]struct { + identifier string + message *Message + want []string + errContains string + }{ "@path for request - valid without leading slash": { identifier: `"@path"`, message: &Message{URL: &url.URL{Path: "foo"}, IsRequest: true}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - assert.Equal(t, []string{"/foo"}, value) - }, + want: []string{"/foo"}, }, "@path for request - valid with leading slash": { identifier: `"@path"`, message: &Message{URL: &url.URL{Path: "/foo"}, IsRequest: true}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - assert.Equal(t, []string{"/foo"}, value) - }, + want: []string{"/foo"}, }, "@path for request - invalid": { - identifier: `"@path";req`, - message: &Message{URL: &url.URL{Path: "/foo"}, IsRequest: true}, - assert: func(t *testing.T, err error, _ []string) { - t.Helper() - - require.Error(t, err) - require.ErrorIs(t, err, ErrCanonicalization) - require.ErrorContains(t, err, "is not valid for requests") - }, + identifier: `"@path";req`, + message: &Message{URL: &url.URL{Path: "/foo"}, IsRequest: true}, + errContains: "is not valid for requests", }, "@path for response - valid": { identifier: `"@path";req`, message: &Message{URL: &url.URL{Path: "/bar"}, IsRequest: false}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - assert.Equal(t, []string{"/bar"}, value) - }, + want: []string{"/bar"}, }, "@path for response - invalid": { - identifier: `"@path"`, - message: &Message{URL: &url.URL{Path: "/bar"}, IsRequest: false}, - assert: func(t *testing.T, err error, _ []string) { - t.Helper() + identifier: `"@path"`, + message: &Message{URL: &url.URL{Path: "/bar"}, IsRequest: false}, + errContains: "@path not valid for responses", + }, + } { + t.Run(uc, func(t *testing.T) { + item, err := httpsfv.UnmarshalItem([]string{tc.identifier}) + require.NoError(t, err) + + c, err := newPathCanonicalizer(item.Params) + require.NoError(t, err) - require.Error(t, err) + value, err := c.canonicalize(tc.message, item.Params) + if tc.errContains != "" { require.ErrorIs(t, err, ErrCanonicalization) - require.ErrorContains(t, err, "@path not valid for responses") - }, - }, + require.ErrorContains(t, err, tc.errContains) + } else { + require.NoError(t, err) + assert.Equal(t, tc.want, value) + } + }) + } +} + +func TestCanonicalizeQuery(t *testing.T) { + t.Parallel() + + url1 := "https://example.com/foo%2Fbaz/bar%5Bid%5D?foo=bar&bar=%5Bid%5D" + testURL1, err := url.Parse(url1) + require.NoError(t, err) + + for uc, tc := range map[string]struct { + identifier string + message *Message + want []string + errContains string + }{ "@query for request - valid with query present": { identifier: `"@query"`, message: &Message{URL: testURL1, IsRequest: true}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - assert.Equal(t, []string{"?foo=bar&bar=%5Bid%5D"}, value) - }, + want: []string{"?foo=bar&bar=%5Bid%5D"}, }, "@query for request - valid without query": { identifier: `"@query"`, message: &Message{URL: &url.URL{}, IsRequest: true}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - assert.Equal(t, []string{"?"}, value) - }, + want: []string{"?"}, }, "@query for request - invalid": { - identifier: `"@query";req`, - message: &Message{URL: &url.URL{}, IsRequest: true}, - assert: func(t *testing.T, err error, _ []string) { - t.Helper() - - require.Error(t, err) - require.ErrorIs(t, err, ErrCanonicalization) - require.ErrorContains(t, err, "is not valid for requests") - }, + identifier: `"@query";req`, + message: &Message{URL: &url.URL{}, IsRequest: true}, + errContains: "is not valid for requests", }, "@query for response - valid": { identifier: `"@query";req`, message: &Message{URL: &url.URL{}, IsRequest: false}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - assert.Equal(t, []string{"?"}, value) - }, + want: []string{"?"}, }, "@query for response - invalid": { - identifier: `"@query"`, - message: &Message{URL: &url.URL{}, IsRequest: false}, - assert: func(t *testing.T, err error, _ []string) { - t.Helper() + identifier: `"@query"`, + message: &Message{URL: &url.URL{}, IsRequest: false}, + errContains: "@query not valid for responses", + }, + } { + t.Run(uc, func(t *testing.T) { + item, err := httpsfv.UnmarshalItem([]string{tc.identifier}) + require.NoError(t, err) + + c, err := newQueryCanonicalizer(item.Params) + require.NoError(t, err) - require.Error(t, err) + value, err := c.canonicalize(tc.message, item.Params) + if tc.errContains != "" { require.ErrorIs(t, err, ErrCanonicalization) - require.ErrorContains(t, err, "@query not valid for responses") - }, - }, + require.ErrorContains(t, err, tc.errContains) + } else { + require.NoError(t, err) + assert.Equal(t, tc.want, value) + } + }) + } +} + +func TestCanonicalizeQueryParam(t *testing.T) { + t.Parallel() + + url1 := "https://example.com/foo%2Fbaz/bar%5Bid%5D?foo=bar&bar=%5Bid%5D" + testURL1, err := url.Parse(url1) + require.NoError(t, err) + + for uc, tc := range map[string]struct { + identifier string + message *Message + want []string + errContains string + }{ "@query-param for request - valid": { identifier: `"@query-param";name="bar"`, message: &Message{URL: testURL1, IsRequest: true}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - assert.Equal(t, []string{"%5Bid%5D"}, value) - }, + want: []string{"%5Bid%5D"}, }, "@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}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - assert.Equal(t, []string{"bar"}, value) - }, + want: []string{"bar"}, }, "@query-param for request - invalid, duplicate parameter": { - identifier: `"@query-param";name="foo"`, - message: &Message{URL: &url.URL{RawQuery: "foo=one&foo=two"}, IsRequest: true}, - assert: func(t *testing.T, err error, _ []string) { - t.Helper() - - require.ErrorIs(t, err, ErrCanonicalization) - require.ErrorContains(t, err, "occurs multiple times") - }, + identifier: `"@query-param";name="foo"`, + message: &Message{URL: &url.URL{RawQuery: "foo=one&foo=two"}, IsRequest: true}, + errContains: "occurs multiple times", }, "@query-param for request - invalid, duplicate encoded parameter": { - identifier: `"@query-param";name="foo"`, - message: &Message{URL: &url.URL{RawQuery: "foo=one&%66oo=two"}, IsRequest: true}, - assert: func(t *testing.T, err error, _ []string) { - t.Helper() - - require.ErrorIs(t, err, ErrCanonicalization) - require.ErrorContains(t, err, "occurs multiple times") - }, + identifier: `"@query-param";name="foo"`, + 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}, - assert: func(t *testing.T, err error, _ []string) { - t.Helper() - - require.ErrorIs(t, err, ErrCanonicalization) - require.ErrorContains(t, err, "occurs multiple times") - }, + 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}, - assert: func(t *testing.T, err error, _ []string) { - t.Helper() - - require.Error(t, err) - require.ErrorIs(t, err, ErrCanonicalization) - require.ErrorContains(t, err, "not found") - }, + identifier: `"@query-param";name="moo"`, + message: &Message{URL: testURL1, IsRequest: true}, + errContains: "not found", }, "@query-param for response - valid": { identifier: `"@query-param";name="foo";req`, message: &Message{URL: testURL1, IsRequest: false}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - assert.Equal(t, []string{"bar"}, value) - }, + want: []string{"bar"}, }, "@query-param for response - invalid": { - identifier: `"@query-param";name="foo"`, - message: &Message{URL: testURL1, IsRequest: false}, - assert: func(t *testing.T, err error, _ []string) { - t.Helper() + identifier: `"@query-param";name="foo"`, + message: &Message{URL: testURL1, IsRequest: false}, + errContains: "not valid for responses", + }, + } { + t.Run(uc, func(t *testing.T) { + item, err := httpsfv.UnmarshalItem([]string{tc.identifier}) + require.NoError(t, err) - require.Error(t, err) + c, err := newQueryParamCanonicalizer(item.Params) + require.NoError(t, err) + + value, err := c.canonicalize(tc.message, item.Params) + if tc.errContains != "" { require.ErrorIs(t, err, ErrCanonicalization) - require.ErrorContains(t, err, "not valid for responses") - }, - }, + require.ErrorContains(t, err, tc.errContains) + } else { + require.NoError(t, err) + assert.Equal(t, tc.want, value) + } + }) + } +} + +func TestCanonicalizeStatusCode(t *testing.T) { + t.Parallel() + + for uc, tc := range map[string]struct { + identifier string + message *Message + want []string + errContains string + }{ "@status for response - valid": { identifier: `"@status"`, message: &Message{StatusCode: http.StatusNotFound, IsRequest: false}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - assert.Equal(t, []string{"404"}, value) - }, - }, - "@status for response - invalid": { - identifier: `"@status";req`, - message: &Message{StatusCode: http.StatusNotFound, IsRequest: false}, - assert: func(t *testing.T, err error, _ []string) { - t.Helper() - - require.Error(t, err) - require.ErrorIs(t, err, ErrCanonicalization) - require.ErrorContains(t, err, "not valid for requests") - }, + want: []string{"404"}, }, "@status for request - invalid": { - identifier: `"@status"`, - message: &Message{StatusCode: http.StatusNotFound, IsRequest: true}, - assert: func(t *testing.T, err error, _ []string) { - t.Helper() - - require.Error(t, err) - require.ErrorIs(t, err, ErrCanonicalization) - require.ErrorContains(t, err, "not valid for requests") - }, + identifier: `"@status"`, + message: &Message{StatusCode: http.StatusNotFound, IsRequest: true}, + errContains: "not valid for requests", }, - "header component for request - invalid, no header present": { - identifier: `"X-Foo-Bar"`, - message: &Message{IsRequest: true}, - assert: func(t *testing.T, err error, _ []string) { - t.Helper() + } { + t.Run(uc, func(t *testing.T) { + item, err := httpsfv.UnmarshalItem([]string{tc.identifier}) + require.NoError(t, err) - require.Error(t, err) + c, err := newStatusCodeCanonicalizer(item.Params) + require.NoError(t, err) + + value, err := c.canonicalize(tc.message, item.Params) + if tc.errContains != "" { require.ErrorIs(t, err, ErrCanonicalization) - require.ErrorContains(t, err, "x-foo-bar not present in message") - }, + require.ErrorContains(t, err, tc.errContains) + } else { + require.NoError(t, err) + assert.Equal(t, tc.want, value) + } + }) + } +} + +func TestCanonicalizeHeader(t *testing.T) { + t.Parallel() + + for uc, tc := range map[string]struct { + identifier string + message *Message + want []string + errContains string + }{ + "header component for request - invalid, no header present": { + identifier: `"X-Foo-Bar"`, + message: &Message{IsRequest: true}, + errContains: "x-foo-bar not present in message", }, "header component for request - invalid, specified header not present": { - identifier: `"X-Foo-Bar"`, - message: &Message{Header: http.Header{"Accept": []string{"application/json"}}, IsRequest: true}, - assert: func(t *testing.T, err error, _ []string) { - t.Helper() - - require.Error(t, err) - require.ErrorIs(t, err, ErrCanonicalization) - require.ErrorContains(t, err, "x-foo-bar not present in message") - }, + identifier: `"X-Foo-Bar"`, + message: &Message{Header: http.Header{"Accept": []string{"application/json"}}, IsRequest: true}, + errContains: "x-foo-bar not present in message", }, - "header component for request - invalid, bad serialization settings": { - identifier: `"X-Foo-Bar";bs;sf`, - message: &Message{Header: http.Header{"X-Foo-Bar": []string{"baz"}}, IsRequest: true}, - assert: func(t *testing.T, err error, _ []string) { - t.Helper() - - require.Error(t, err) - require.ErrorIs(t, err, ErrCanonicalization) - require.ErrorContains(t, err, "cannot have both") - }, + "header component for request - invalid, req parameter": { + identifier: `"X-Foo-Bar";req`, + message: &Message{Header: http.Header{"X-Foo-Bar": []string{"baz"}}, IsRequest: true}, + errContains: "'req' parameter not valid for requests", }, "header component for request - invalid, serialization error": { - identifier: `"X-Foo-Bar";sf;key="foo"`, - message: &Message{Header: http.Header{"X-Foo-Bar": []string{"baz"}}, IsRequest: true}, - assert: func(t *testing.T, err error, _ []string) { - t.Helper() - - require.Error(t, err) - require.ErrorIs(t, err, ErrCanonicalization) - require.ErrorContains(t, err, "unable to parse") - }, + identifier: `"X-Foo-Bar";sf;key="foo"`, + message: &Message{Header: http.Header{"X-Foo-Bar": []string{"baz"}}, IsRequest: true}, + errContains: "unable to parse", }, "header component for request - valid": { identifier: `"X-Foo-Bar"`, message: &Message{Header: http.Header{"X-Foo-Bar": []string{"baz"}}, IsRequest: true}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - assert.Equal(t, []string{"baz"}, value) - }, + want: []string{"baz"}, }, "header component for response - valid": { identifier: `"X-Foo-Bar"`, message: &Message{Header: http.Header{"X-Foo-Bar": []string{"baz"}}, IsRequest: false}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - assert.Equal(t, []string{"baz"}, value) - }, + want: []string{"baz"}, }, "header component for response from request - valid": { identifier: `"X-Foo-Bar";req`, message: &Message{RequestHeader: http.Header{"X-Foo-Bar": []string{"baz"}}, IsRequest: false}, - assert: func(t *testing.T, err error, value []string) { - t.Helper() - - require.NoError(t, err) - assert.Equal(t, []string{"baz"}, value) - }, + want: []string{"baz"}, }, } { t.Run(uc, func(t *testing.T) { item, err := httpsfv.UnmarshalItem([]string{tc.identifier}) require.NoError(t, err) - c, err := canonicalizerFor(strings.ToLower(item.Value.(string)), item.Params) + c, err := newHeaderCanonicalizer(strings.ToLower(item.Value.(string)), item.Params) require.NoError(t, err) - res, err := c.canonicalize(tc.message, item.Params) - - tc.assert(t, err, res) + value, err := c.canonicalize(tc.message, item.Params) + if tc.errContains != "" { + require.ErrorIs(t, err, ErrCanonicalization) + require.ErrorContains(t, err, tc.errContains) + } else { + require.NoError(t, err) + assert.Equal(t, tc.want, value) + } }) } } diff --git a/component_identifier_test.go b/component_identifier_test.go index 3ff399f..9a68b55 100644 --- a/component_identifier_test.go +++ b/component_identifier_test.go @@ -51,29 +51,29 @@ func TestToComponentIdentifiers(t *testing.T) { require.ErrorIs(t, err, ErrUnsupportedComponentIdentifier) }, }, - "preserving structured field parameter types": { - identifiers: []string{`x-test;string="abc";token=abc;bytes=:AQID:`}, + "preserving supported parameter types": { + identifiers: []string{`x-test;key="abc";sf;req`}, assert: func(t *testing.T, ci []*componentIdentifier, err error) { t.Helper() require.NoError(t, err) require.Len(t, ci, 1) - stringValue, ok := ci[0].Params.Get("string") - require.True(t, ok) - assert.Equal(t, "abc", stringValue) + key, present := ci[0].Params.Get("key") + require.True(t, present) + assert.Equal(t, "abc", key) - tokenValue, ok := ci[0].Params.Get("token") - require.True(t, ok) - assert.Equal(t, httpsfv.Token("abc"), tokenValue) + sf, present := ci[0].Params.Get("sf") + require.True(t, present) + assert.Equal(t, true, sf) - bytesValue, ok := ci[0].Params.Get("bytes") - require.True(t, ok) - assert.Equal(t, []byte{1, 2, 3}, bytesValue) + req, present := ci[0].Params.Get("req") + require.True(t, present) + assert.Equal(t, true, req) }, }, "valid": { - identifiers: []string{"@method;foo=bar", "@status", `@query-param;name="Pet"`}, + identifiers: []string{"@method;req", "@status", `@query-param;name="Pet"`}, assert: func(t *testing.T, ci []*componentIdentifier, err error) { t.Helper() @@ -81,9 +81,9 @@ func TestToComponentIdentifiers(t *testing.T) { require.Len(t, ci, 3) assert.Equal(t, "@method", ci[0].Value.(string)) - res, ok := ci[0].Params.Get("foo") + res, ok := ci[0].Params.Get("req") require.True(t, ok) - require.Equal(t, httpsfv.Token("bar"), res) + require.Equal(t, true, res) assert.NotNil(t, ci[0].c) assert.Equal(t, "@status", ci[1].Value.(string)) @@ -185,7 +185,7 @@ func TestNewComponentIdentifier(t *testing.T) { "valid": { item: func() httpsfv.Item { item := httpsfv.NewItem("@method") - item.Params.Add("foo", []byte("bar")) + item.Params.Add("req", true) return item }(), @@ -195,9 +195,9 @@ func TestNewComponentIdentifier(t *testing.T) { require.NoError(t, err) assert.NotNil(t, ci.c) - val, ok := ci.Params.Get("foo") + val, ok := ci.Params.Get("req") require.True(t, ok) - assert.Equal(t, []byte("bar"), val) + assert.Equal(t, true, val) }, }, } { @@ -227,8 +227,8 @@ func TestComponentIdentifierEqual(t *testing.T) { second: `x-second`, }, "different parameter names": { - first: `x-test;first="foo"`, - second: `x-test;second="foo"`, + first: `x-test;sf`, + second: `x-test;bs`, }, "different parameter counts": { first: `x-test;req`, diff --git a/options_test.go b/options_test.go index 3a025e4..e5f2bb0 100644 --- a/options_test.go +++ b/options_test.go @@ -98,7 +98,7 @@ func TestWithComponentsForSigner(t *testing.T) { identifiers []string err error }{ - "multiple valid identifier": {identifiers: []string{"@status;req", "@method"}}, + "multiple valid identifier": {identifiers: []string{"@method;req", "@status"}}, "invalid identifier": {identifiers: []string{"@foo"}, err: ErrUnsupportedComponentIdentifier}, } { t.Run(uc, func(t *testing.T) { @@ -129,7 +129,7 @@ func TestWithComponentsForVerifier(t *testing.T) { identifiers []string err error }{ - "multiple valid identifier": {identifiers: []string{"@status;req", "@method"}}, + "multiple valid identifier": {identifiers: []string{"@method;req", "@status"}}, "invalid identifier": {identifiers: []string{"@foo"}, err: ErrUnsupportedComponentIdentifier}, } { t.Run(uc, func(t *testing.T) { diff --git a/serializer.go b/serializer.go index fb224e7..f01282b 100644 --- a/serializer.go +++ b/serializer.go @@ -18,13 +18,7 @@ type serializer interface { serialize(v []string) ([]string, error) } -//nolint:cyclop func newSerializer(params *httpsfv.Params, isRequest bool) (serializer, error) { - var ( - key string - ok bool - ) - if _, hasReqParam := params.Get("req"); hasReqParam && isRequest { return nil, fmt.Errorf("%w: 'req' parameter not valid for requests", errSerialization) @@ -32,23 +26,8 @@ func newSerializer(params *httpsfv.Params, isRequest bool) (serializer, error) { _, isBs := params.Get("bs") _, isSf := params.Get("sf") - _, isTr := params.Get("tr") keyParam, isKey := params.Get("key") - - if isTr { - return nil, fmt.Errorf("%w: message trailers are not supported", errSerialization) - } - - if isBs && (isSf || isKey) { - return nil, fmt.Errorf("%w: cannot have both 'bs' and 'sf'/'key' parameters", - errSerialization) - } - - if isKey { - if key, ok = keyParam.(string); !ok { - return nil, fmt.Errorf("%w: key parameter must be a string", errSerialization) - } - } + key, _ := keyParam.(string) // validated by canonicalizerFor switch { case isSf || isKey: diff --git a/serializer_test.go b/serializer_test.go index 158db7b..85af7a3 100644 --- a/serializer_test.go +++ b/serializer_test.go @@ -34,72 +34,6 @@ func TestNewSerializer(t *testing.T) { require.ErrorContains(t, err, "'req' parameter") }, }, - { - uc: "message trailers are not supported", - params: func() *httpsfv.Params { - params := httpsfv.NewParams() - params.Add("tr", true) - - return params - }(), - assert: func(t *testing.T, _ serializer, err error) { - t.Helper() - - require.Error(t, err) - require.ErrorIs(t, err, errSerialization) - require.ErrorContains(t, err, "message trailers are not supported") - }, - }, - { - uc: "sf and bs serialization are mutually exclusive", - params: func() *httpsfv.Params { - params := httpsfv.NewParams() - params.Add("bs", true) - params.Add("sf", true) - - return params - }(), - assert: func(t *testing.T, _ serializer, err error) { - t.Helper() - - require.Error(t, err) - require.ErrorIs(t, err, errSerialization) - require.ErrorContains(t, err, "cannot have both") - }, - }, - { - uc: "key and bs serialization are mutually exclusive", - params: func() *httpsfv.Params { - params := httpsfv.NewParams() - params.Add("bs", true) - params.Add("key", true) - - return params - }(), - assert: func(t *testing.T, _ serializer, err error) { - t.Helper() - - require.Error(t, err) - require.ErrorIs(t, err, errSerialization) - require.ErrorContains(t, err, "cannot have both") - }, - }, - { - uc: "dictionary structured field key must be a string", - params: func() *httpsfv.Params { - params := httpsfv.NewParams() - params.Add("key", 1) - - return params - }(), - assert: func(t *testing.T, _ serializer, err error) { - t.Helper() - - require.Error(t, err) - require.ErrorIs(t, err, errSerialization) - require.ErrorContains(t, err, "must be a string") - }, - }, { uc: "strict encoding serializer", params: func() *httpsfv.Params { diff --git a/signature_input_test.go b/signature_input_test.go index ac58f81..ee7e987 100644 --- a/signature_input_test.go +++ b/signature_input_test.go @@ -823,23 +823,6 @@ func TestSignatureInputHasIdentifier(t *testing.T) { given: []string{`@query-param;name="bar"`}, identifier: `@query-param;name="foo"`, }, - "different parameter type": { - given: []string{`x-test;value=1`}, - identifier: `x-test;value="1"`, - }, - "matching byte sequence parameter": { - given: []string{`x-test;custom=:AQID:`}, - identifier: `x-test;custom=:AQID:`, - expected: true, - }, - "different byte sequence parameter": { - given: []string{`x-test;custom=:AQID:`}, - identifier: `x-test;custom=:AQIE:`, - }, - "different flag value": { - given: []string{`x-test;sf=?0`}, - identifier: `x-test;sf`, - }, "different parameter name": { given: []string{`x-test;sf`}, identifier: `x-test;req`,