diff --git a/canonicalizer.go b/canonicalizer.go index 651e630..7f39ebb 100644 --- a/canonicalizer.go +++ b/canonicalizer.go @@ -2,7 +2,6 @@ package httpsig import ( "fmt" - "net" "net/http" "net/url" "slices" @@ -150,25 +149,35 @@ func newAuthorityCanonicalizer(params *httpsfv.Params) (canonicalizer, error) { 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 + host, port, valid := splitHostPort(msg.Authority) + if !valid { + return nil, fmt.Errorf("%w: invalid authority %q", ErrCanonicalization, msg.Authority) } - // 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 + host = normalizeHost(host) + if port == "" { + return []string{host}, nil + } + + port = strings.TrimLeft(port, "0") + if port == "" { + port = "0" + } + + if msg.URL != nil { + switch strings.ToLower(msg.URL.Scheme) { + case "http": + if port == "80" { + return []string{host}, nil + } + case "https": + if port == "443" { + return []string{host}, nil + } } } - return []string{strings.ToLower(msg.Authority)}, nil + return []string{host + ":" + port}, nil }), nil } diff --git a/canonicalizer_test.go b/canonicalizer_test.go index a88fbc4..13effd9 100644 --- a/canonicalizer_test.go +++ b/canonicalizer_test.go @@ -510,14 +510,9 @@ func TestCanonicalizeAuthority(t *testing.T) { want []string errContains string }{ - "@authority for request - valid http without port": { + "@authority for request - without port": { identifier: `"@authority"`, - message: &Message{Authority: "example.com", URL: &url.URL{Scheme: "http"}, IsRequest: true}, - 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}, + message: &Message{Authority: "ExAmPlE.COM", URL: &url.URL{Scheme: "http"}, IsRequest: true}, want: []string{"example.com"}, }, "@authority for request - valid http with default port": { @@ -530,16 +525,56 @@ func TestCanonicalizeAuthority(t *testing.T) { message: &Message{Authority: "example.com:443", URL: &url.URL{Scheme: "https"}, IsRequest: true}, 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}, - 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}, want: []string{"example.com:8443"}, }, + "@authority for request - ipv6 default port": { + identifier: `"@authority"`, + message: &Message{Authority: "[2001:DB8::1]:443", URL: &url.URL{Scheme: "https"}, IsRequest: true}, + want: []string{"[2001:db8::1]"}, + }, + "@authority for request - percent-encoded letter": { + identifier: `"@authority"`, + message: &Message{Authority: "EXA%6Dple.COM", URL: &url.URL{Scheme: "https"}, IsRequest: true}, + want: []string{"example.com"}, + }, + "@authority for request - padded default port": { + identifier: `"@authority"`, + message: &Message{Authority: "EXAMPLE.com:0443", URL: &url.URL{Scheme: "HTTPS"}, IsRequest: true}, + want: []string{"example.com"}, + }, + "@authority for request - padded non-default port": { + identifier: `"@authority"`, + message: &Message{Authority: "EXAMPLE.com:008443", URL: &url.URL{Scheme: "https"}, IsRequest: true}, + want: []string{"example.com:8443"}, + }, + "@authority for request - empty port": { + identifier: `"@authority"`, + message: &Message{Authority: "EXAMPLE.com:", URL: &url.URL{Scheme: "https"}, IsRequest: true}, + want: []string{"example.com"}, + }, + "@authority for request - zero port": { + identifier: `"@authority"`, + message: &Message{Authority: "example.com:0000", URL: &url.URL{Scheme: "https"}, IsRequest: true}, + want: []string{"example.com:0"}, + }, + "@authority for request - no default-port removal for other scheme": { + identifier: `"@authority"`, + message: &Message{Authority: "EXAMPLE.com:443", URL: &url.URL{Scheme: "http"}, IsRequest: true}, + want: []string{"example.com:443"}, + }, + "@authority for request - no default-port removal without scheme": { + identifier: `"@authority"`, + message: &Message{Authority: "EXAMPLE.com:80", URL: &url.URL{}, IsRequest: true}, + want: []string{"example.com:80"}, + }, + "@authority for request - invalid non-numeric port": { + identifier: `"@authority"`, + message: &Message{Authority: "example.com:abc", URL: &url.URL{Scheme: "https"}, IsRequest: true}, + errContains: "invalid authority", + }, "@authority for request - invalid": { identifier: `"@authority";req`, message: &Message{Authority: "example.com", URL: &url.URL{Scheme: "http"}, IsRequest: true}, diff --git a/net.go b/net.go new file mode 100644 index 0000000..4259a08 --- /dev/null +++ b/net.go @@ -0,0 +1,189 @@ +package httpsig + +import ( + "net/netip" + "strings" +) + +// splitHostPort splits an HTTP authority into a validated host (including +// IP-literal brackets) and an optional port. Userinfo, paths, queries, and +// fragments are not permitted. +// +//nolint:cyclop +func splitHostPort(authority string) (string, string, bool) { + if authority == "" { + return "", "", false + } + + var ( + host string + port string + ) + + if authority[0] == '[' { //nolint:nestif + end := strings.IndexByte(authority, ']') + if end == -1 { + return "", "", false + } + + if !validIPLiteral(authority[1:end]) { + return "", "", false + } + + host = authority[:end+1] + if end+1 < len(authority) { + if authority[end+1] != ':' { + return "", "", false + } + + port = authority[end+2:] + } + } else { + if before, after, ok := strings.Cut(authority, ":"); ok { + host, port = before, after + } else { + host = authority + } + + if !validAuthorityRegName(host) { + return "", "", false + } + } + + for i := range len(port) { + if port[i] < '0' || port[i] > '9' { + return "", "", false + } + } + + return host, port, true +} + +// normalizeHost applies HTTP URI case and percent-encoding +// normalization to a host already validated by splitHostPort. +// +//nolint:cyclop +func normalizeHost(host string) string { + if strings.HasPrefix(host, "[") || !strings.Contains(host, "%") { + return strings.ToLower(host) + } + + const upperHex = "0123456789ABCDEF" + + var normalized strings.Builder + normalized.Grow(len(host)) + + for i := 0; i < len(host); i++ { + ch := host[i] + if ch == '%' { + decoded := hexValue(host[i+1])<<4 | hexValue(host[i+2]) //nolint:mnd + if (decoded >= 'a' && decoded <= 'z') || + (decoded >= 'A' && decoded <= 'Z') || + (decoded >= '0' && decoded <= '9') || + decoded == '-' || decoded == '.' || decoded == '_' || decoded == '~' { + ch = decoded + } else { + normalized.WriteByte('%') + normalized.WriteByte(upperHex[decoded>>4]) + normalized.WriteByte(upperHex[decoded&0x0f]) + + i += 2 + + continue + } + + i += 2 + } + + if ch >= 'A' && ch <= 'Z' { + ch += 'a' - 'A' + } + + normalized.WriteByte(ch) + } + + return normalized.String() +} + +// hexValue converts a validated ASCII hex digit to its numeric value. +func hexValue(ch byte) byte { + switch { + case ch >= '0' && ch <= '9': + return ch - '0' + case ch >= 'A' && ch <= 'F': + return ch - 'A' + 10 //nolint:mnd + default: + return ch - 'a' + 10 //nolint:mnd + } +} + +func validIPLiteral(literal string) bool { + ip, err := netip.ParseAddr(literal) + if err == nil { + return ip.Is6() && ip.Zone() == "" + } + + return validIPvFuture(literal) +} + +func validAuthorityRegName(name string) bool { + if name == "" { + return false + } + + for i := 0; i < len(name); i++ { + ch := name[i] + if isRegNameChar(ch) { + continue + } + + if ch != '%' || i+2 >= len(name) || !isHexDigit(name[i+1]) || !isHexDigit(name[i+2]) { + return false + } + + i += 2 + } + + return true +} + +//nolint:cyclop +func validIPvFuture(literal string) bool { + if len(literal) < 4 || (literal[0] != 'v' && literal[0] != 'V') { + return false + } + + i := 1 + for i < len(literal) && isHexDigit(literal[i]) { + i++ + } + + if i == 1 || i >= len(literal)-1 || literal[i] != '.' { + return false + } + + for i++; i < len(literal); i++ { + if !isRegNameChar(literal[i]) && literal[i] != ':' { + return false + } + } + + return true +} + +func isRegNameChar(ch byte) bool { + if (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') { + return true + } + + switch ch { + case '-', '.', '_', '~', '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=': + return true + } + + return false +} + +func isHexDigit(ch byte) bool { + return (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') +} diff --git a/net_test.go b/net_test.go new file mode 100644 index 0000000..73430fe --- /dev/null +++ b/net_test.go @@ -0,0 +1,72 @@ +package httpsig + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestSplitHostPort(t *testing.T) { + t.Parallel() + + for name, tc := range map[string]struct { + input string + host string + port string + valid bool + }{ + "domain without port": {input: "EXAMPLE.com", host: "EXAMPLE.com", valid: true}, + "domain with port": {input: "EXAMPLE.com:0443", host: "EXAMPLE.com", port: "0443", valid: true}, + "domain with empty port": {input: "EXAMPLE.com:", host: "EXAMPLE.com", valid: true}, + "ipv6 without port": {input: "[2001:DB8::1]", host: "[2001:DB8::1]", valid: true}, + "ipv6 with port": {input: "[2001:DB8::1]:443", host: "[2001:DB8::1]", port: "443", valid: true}, + "ipv6 with empty port": {input: "[2001:DB8::1]:", host: "[2001:DB8::1]", valid: true}, + "invalid ipv6 encoded zone": {input: "[fe80::1%25eth0]"}, + "invalid ipv6 encoded zone case": {input: "[fe80::1%25ETH0]"}, + "ipvfuture": {input: "[v1.a:2]", host: "[v1.a:2]", valid: true}, + "percent-encoded reg-name": {input: "exa%6Dple.com", host: "exa%6Dple.com", valid: true}, + "invalid empty authority": {input: ""}, + "invalid empty hostname": {input: ":80"}, + "invalid alpha port": {input: "example.com:abc"}, + "invalid signed port": {input: "example.com:+80"}, + "invalid unbracketed ipv6": {input: "2001:db8::1"}, + "invalid ipv6": {input: "[not-ipv6]"}, + "invalid missing bracket": {input: "[2001:db8::1"}, + "invalid ipvfuture": {input: "[v.no]"}, + "invalid zone encoding": {input: "[fe80::1%eth0]"}, + "invalid userinfo": {input: "user@example.com"}, + "invalid path": {input: "example.com/path"}, + "invalid percent escape": {input: "exa%GGmple.com"}, + "invalid non-ASCII": {input: "exämple.com"}, + } { + t.Run(name, func(t *testing.T) { + host, port, valid := splitHostPort(tc.input) + assert.Equal(t, tc.valid, valid) + assert.Equal(t, tc.host, host) + assert.Equal(t, tc.port, port) + }) + } +} + +func TestNormalizeHost(t *testing.T) { + t.Parallel() + + for name, tc := range map[string]struct { + input string + want string + }{ + "plain lowercase": {input: "example.com", want: "example.com"}, + "mixed case": {input: "EXAMPLE.COM", want: "example.com"}, + "percent-encoded letter": {input: "EXA%6Dple.COM", want: "example.com"}, + "percent-encoded capital": {input: "EX%41MPLE.COM", want: "example.com"}, + "percent-encoded tilde": {input: "EXA%7Emple.COM", want: "exa~mple.com"}, + "percent-encoded dot": {input: "EXAMPLE%2eCOM", want: "example.com"}, + "percent-encoded reserved": {input: "EXAMPLE%2f.COM", want: "example%2F.com"}, + "percent-encoded non-ASCII": {input: "EXAMPLE%C3%a4.COM", want: "example%C3%A4.com"}, + "do not double-decode percent": {input: "EXAMPLE%256d.COM", want: "example%256d.com"}, + } { + t.Run(name, func(t *testing.T) { + assert.Equal(t, tc.want, normalizeHost(tc.input)) + }) + } +}