diff --git a/.gitattributes b/.gitattributes index effd180bc..d5f3d6172 100644 --- a/.gitattributes +++ b/.gitattributes @@ -62,3 +62,7 @@ internal/security/bundlesig/testdata/* -text # leave a \r on the shebang and every command line, so pin the CI shell # scripts to LF. scripts/*.sh text eol=lf + +# Spec 132 OAuth metadata goldens are byte-compared against LF-only +# MarshalIndent output; pin LF so a Windows checkout does not yield CRLF. +internal/mcplogin/testdata/*.json text eol=lf diff --git a/internal/mcplogin/limits.go b/internal/mcplogin/limits.go new file mode 100644 index 000000000..9c267a669 --- /dev/null +++ b/internal/mcplogin/limits.go @@ -0,0 +1,114 @@ +package mcplogin + +import ( + "math" + "sync" + "time" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/upstream/limiter" +) + +const ( + // MaxBodyBytes is the largest request body register and token accept. + MaxBodyBytes = 16 << 10 + // MaxPendingRegistrations caps registrations that are not yet approved. + MaxPendingRegistrations = 50 + // MaxPendingRequests caps pending authorization requests. + MaxPendingRequests = 20 +) + +// Endpoint names the rate-limited public endpoints. +const ( + // EndpointRegister is POST /oauth/register. + EndpointRegister = "register" + // EndpointAuthorize is GET /oauth/authorize. + EndpointAuthorize = "authorize" + // EndpointToken is POST /oauth/token. + EndpointToken = "token" +) + +// rateFor returns the default budget of an endpoint. +func rateFor(endpoint string) (limiter.RateSpec, bool) { + switch endpoint { + case EndpointRegister: + return limiter.RateSpec{PerMinute: 10, Burst: 5}, true + case EndpointAuthorize: + return limiter.RateSpec{PerMinute: 30, Burst: 10}, true + case EndpointToken: + return limiter.RateSpec{PerMinute: 60, Burst: 20}, true + } + return limiter.RateSpec{}, false +} + +const ( + // MaxTrackedKeys caps the distinct endpoint|address keys the Limiter keeps. + MaxTrackedKeys = 4096 + // idleAfter is how long a key must be unseen before it may be dropped. It + // exceeds the time any bucket needs to refill completely, so dropping an + // idle key never hands a caller extra budget. + idleAfter = time.Minute +) + +// Limiter rate limits the public OAuth endpoints per endpoint and remote +// address, over at most MaxTrackedKeys keys. It is safe for concurrent use. +type Limiter struct { + rates *limiter.TokenRates + now func() time.Time + mu sync.Mutex + seen map[string]time.Time +} + +// NewLimiter returns a Limiter with the default rates. now is the clock; nil +// means time.Now. +func NewLimiter(now func() time.Time) *Limiter { + if now == nil { + now = time.Now + } + return &Limiter{rates: limiter.NewTokenRates(now), now: now, seen: map[string]time.Time{}} +} + +// admit records key as seen now. For an unseen key at the cap it prunes idle +// keys first and, if the limiter is still full, refuses with the seconds until +// the oldest key becomes idle. Active keys are never evicted. +func (l *Limiter) admitLocked(key string) (bool, int) { + now := l.now() + if _, known := l.seen[key]; !known && len(l.seen) >= MaxTrackedKeys { + oldest := now + for k, t := range l.seen { + if now.Sub(t) >= idleAfter { + delete(l.seen, k) + } else if t.Before(oldest) { + oldest = t + } + } + if len(l.seen) >= MaxTrackedKeys { + wait := idleAfter - now.Sub(oldest) + return false, max(1, int(math.Ceil(wait.Seconds()))) + } + } + l.seen[key] = now + return true, 0 +} + +// Allow charges one call of endpoint from remoteIP. When refused, +// retryAfterSeconds is at least 1. An unknown endpoint is not limited. A new +// address is refused while the limiter is full of active ones. +func (l *Limiter) Allow(endpoint, remoteIP string) (ok bool, retryAfterSeconds int) { + spec, known := rateFor(endpoint) + if !known { + return true, 0 + } + key := endpoint + "|" + remoteIP + // One lock spans admission and the bucket charge, so a key cannot be + // pruned between the two and leave a bucket that seen does not know. + l.mu.Lock() + defer l.mu.Unlock() + if ok, retry := l.admitLocked(key); !ok { + return false, retry + } + d := l.rates.Allow(key, &spec) + if d.Allowed { + return true, 0 + } + return false, max(1, int(math.Ceil(d.RetryAfter.Seconds()))) +} diff --git a/internal/mcplogin/limits_test.go b/internal/mcplogin/limits_test.go new file mode 100644 index 000000000..19086b867 --- /dev/null +++ b/internal/mcplogin/limits_test.go @@ -0,0 +1,75 @@ +package mcplogin + +import ( + "sync" + "testing" + "time" +) + +type fakeClock struct { + mu sync.Mutex + t time.Time +} + +func (c *fakeClock) now() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.t } +func (c *fakeClock) advance(d time.Duration) { + c.mu.Lock() + c.t = c.t.Add(d) + c.mu.Unlock() +} + +func TestLimiterBurstRefillRetryAfter(t *testing.T) { + clk := &fakeClock{t: time.Unix(1000, 0)} + l := NewLimiter(clk.now) + for i := 0; i < 5; i++ { + if ok, _ := l.Allow(EndpointRegister, "1.2.3.4"); !ok { + t.Fatalf("burst call %d refused", i) + } + } + ok, retry := l.Allow(EndpointRegister, "1.2.3.4") + if ok || retry < 1 { + t.Fatalf("expected refusal with retry>=1, got %v %d", ok, retry) + } + if ok, _ := l.Allow(EndpointRegister, "5.6.7.8"); !ok { + t.Fatal("other ip shares bucket") + } + if ok, _ := l.Allow(EndpointAuthorize, "1.2.3.4"); !ok { + t.Fatal("other endpoint shares bucket") + } + clk.advance(6 * time.Second) // 10/min -> 1 per 6 s + if ok, _ := l.Allow(EndpointRegister, "1.2.3.4"); !ok { + t.Fatal("refill failed") + } + if ok, _ := l.Allow(EndpointRegister, "1.2.3.4"); ok { + t.Fatal("only one token should have refilled") + } +} + +func TestLimiterDefaults(t *testing.T) { + clk := &fakeClock{t: time.Unix(1000, 0)} + l := NewLimiter(clk.now) + count := func(ep string) int { + n := 0 + for { + if ok, _ := l.Allow(ep, "9.9.9.9"); !ok { + return n + } + n++ + } + } + if got := count(EndpointAuthorize); got != 10 { + t.Errorf("authorize burst %d", got) + } + if got := count(EndpointToken); got != 20 { + t.Errorf("token burst %d", got) + } + if ok, _ := l.Allow("unknown", "1.1.1.1"); !ok { + t.Error("unknown endpoint must not be limited") + } +} + +func TestLimitConstants(t *testing.T) { + if MaxBodyBytes != 16<<10 || MaxPendingRegistrations != 50 || MaxPendingRequests != 20 { + t.Fatal("constants") + } +} diff --git a/internal/mcplogin/metadata.go b/internal/mcplogin/metadata.go new file mode 100644 index 000000000..d1a7168c4 --- /dev/null +++ b/internal/mcplogin/metadata.go @@ -0,0 +1,31 @@ +package mcplogin + +// ProtectedResourceMetadata is the RFC 9728 document for one OAuth resource +// path: the generic address when clientID is empty, else that client's. +func ProtectedResourceMetadata(origin, clientID string) map[string]any { + return map[string]any{ + "resource": origin + ResourcePath(clientID), + "authorization_servers": []string{origin}, + "bearer_methods_supported": []string{"header"}, + } +} + +// AuthorizationServerMetadata is the RFC 8414 document for this instance. +func AuthorizationServerMetadata(origin string) map[string]any { + return map[string]any{ + "issuer": origin, + "authorization_endpoint": origin + "/oauth/authorize", + "token_endpoint": origin + "/oauth/token", + "registration_endpoint": origin + "/oauth/register", + "response_types_supported": []string{"code"}, + "grant_types_supported": []string{"authorization_code", "refresh_token"}, + "code_challenge_methods_supported": []string{"S256"}, + "token_endpoint_auth_methods_supported": []string{"none"}, + } +} + +// Challenge is the WWW-Authenticate value that points an unauthenticated +// client at the protected-resource metadata of its address. +func Challenge(origin, clientID string) string { + return `Bearer resource_metadata="` + origin + "/.well-known/oauth-protected-resource" + ResourcePath(clientID) + `"` +} diff --git a/internal/mcplogin/metadata_test.go b/internal/mcplogin/metadata_test.go new file mode 100644 index 000000000..d9b52b219 --- /dev/null +++ b/internal/mcplogin/metadata_test.go @@ -0,0 +1,43 @@ +package mcplogin + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" +) + +func golden(t *testing.T, name string, v any) { + t.Helper() + got, err := json.MarshalIndent(v, "", " ") // maps marshal with sorted keys + if err != nil { + t.Fatal(err) + } + want, err := os.ReadFile(filepath.Join("testdata", name)) + if err != nil { + t.Fatal(err) + } + if string(got)+"\n" != string(want) { + t.Fatalf("%s mismatch:\n%s\nwant:\n%s", name, got, want) + } +} + +func TestProtectedResourceMetadataGolden(t *testing.T) { + golden(t, "protected_resource_client.json", ProtectedResourceMetadata("http://127.0.0.1:8080", "cursor")) + golden(t, "protected_resource_generic.json", ProtectedResourceMetadata("http://127.0.0.1:8080", "")) +} + +func TestAuthorizationServerMetadataGolden(t *testing.T) { + golden(t, "authorization_server.json", AuthorizationServerMetadata("http://127.0.0.1:8080")) +} + +func TestChallenge(t *testing.T) { + if got := Challenge("http://127.0.0.1:8080", "cursor"); got != + `Bearer resource_metadata="http://127.0.0.1:8080/.well-known/oauth-protected-resource/mcp/oauth/cursor"` { + t.Fatal(got) + } + if got := Challenge("http://127.0.0.1:8080", ""); got != + `Bearer resource_metadata="http://127.0.0.1:8080/.well-known/oauth-protected-resource/mcp/oauth"` { + t.Fatal(got) + } +} diff --git a/internal/mcplogin/pkce.go b/internal/mcplogin/pkce.go new file mode 100644 index 000000000..f4c3d7d8a --- /dev/null +++ b/internal/mcplogin/pkce.go @@ -0,0 +1,35 @@ +package mcplogin + +import ( + "crypto/sha256" + "crypto/subtle" + "encoding/base64" +) + +// VerifyS256 reports whether challenge is the S256 transform of verifier +// (RFC 7636): the verifier is 43 to 128 characters of the unreserved set and +// the challenge is base64url(sha256(verifier)) without padding. +func VerifyS256(verifier, challenge string) bool { + if len(verifier) < 43 || len(verifier) > 128 { + return false + } + for i := 0; i < len(verifier); i++ { + c := verifier[i] + switch { + case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9', + c == '-', c == '.', c == '_', c == '~': + default: + return false + } + } + if !ValidChallenge(challenge) { + return false + } + sum := sha256.Sum256([]byte(verifier)) + want := base64.RawURLEncoding.EncodeToString(sum[:]) + return subtle.ConstantTimeCompare([]byte(want), []byte(challenge)) == 1 +} + +// ValidChallenge reports whether s is shaped like an S256 challenge: 43 +// base64url characters. +func ValidChallenge(s string) bool { return validBase64URL(s, 43) } diff --git a/internal/mcplogin/pkce_test.go b/internal/mcplogin/pkce_test.go new file mode 100644 index 000000000..15a53d86b --- /dev/null +++ b/internal/mcplogin/pkce_test.go @@ -0,0 +1,70 @@ +package mcplogin + +import ( + "crypto/sha256" + "encoding/base64" + "strings" + "testing" +) + +func challengeOf(v string) string { + sum := sha256.Sum256([]byte(v)) + return base64.RawURLEncoding.EncodeToString(sum[:]) +} + +func TestVerifyS256RFCVector(t *testing.T) { + v := "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk" + c := "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" + if !VerifyS256(v, c) { + t.Fatal("RFC vector must verify") + } + if !ValidChallenge(c) { + t.Fatal("challenge must be valid") + } +} + +func TestVerifyS256Rejects(t *testing.T) { + v := "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk" + c := "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" + if VerifyS256(v+"x", c) { + t.Error("wrong verifier") + } + if VerifyS256(v, c[:42]+"A") { + t.Error("wrong challenge") + } + if VerifyS256(strings.Repeat("a", 42), challengeOf(strings.Repeat("a", 42))) || + VerifyS256(strings.Repeat("a", 129), challengeOf(strings.Repeat("a", 129))) { + t.Error("length bounds") + } + if VerifyS256(v[:42]+"!", challengeOf(v[:42]+"!")) || VerifyS256(v[:42]+" ", challengeOf(v[:42]+" ")) { + t.Error("bad chars") + } + if VerifyS256("", "") { + t.Error("empty") + } +} + +func TestVerifyS256Bounds(t *testing.T) { + for _, n := range []int{43, 128} { + v := strings.Repeat("a", n) + if !VerifyS256(v, challengeOf(v)) { + t.Errorf("length %d should be valid", n) + } + } + v := "a-._~" + strings.Repeat("Z", 40) + if !VerifyS256(v, challengeOf(v)) { + t.Error("unreserved set") + } +} + +func TestValidChallenge(t *testing.T) { + good := strings.Repeat("A", 43) + if !ValidChallenge(good) { + t.Error("good") + } + for _, bad := range []string{"", good[:42], good + "A", good[:42] + "=", good[:42] + "+", good[:42] + "/"} { + if ValidChallenge(bad) { + t.Errorf("%q accepted", bad) + } + } +} diff --git a/internal/mcplogin/redirect.go b/internal/mcplogin/redirect.go new file mode 100644 index 000000000..8bf3fbc07 --- /dev/null +++ b/internal/mcplogin/redirect.go @@ -0,0 +1,172 @@ +package mcplogin + +import ( + "errors" + "fmt" + "net/url" + "sort" + "strings" +) + +// MaxRedirectURIs is the most redirect URIs one registration may carry. +const MaxRedirectURIs = 5 + +// ErrRedirectCount is returned when there are no redirect URIs or too many. +var ErrRedirectCount = errors.New("mcplogin: redirect_uris must hold 1 to 5 entries") + +func isLoopbackHost(h string) bool { + return h == "127.0.0.1" || h == "[::1]" || h == "localhost" +} + +// parseRedirect parses one redirect URI and enforces the shape rules shared +// by registration and matching. +func parseRedirect(raw string) (*url.URL, error) { + u, err := url.Parse(raw) + if err != nil { + return nil, fmt.Errorf("redirect uri is not a valid URL") + } + if !u.IsAbs() || u.Opaque != "" { + return nil, fmt.Errorf("redirect uri must be an absolute URL") + } + if u.Fragment != "" || strings.Contains(raw, "#") { + return nil, fmt.Errorf("redirect uri must not have a fragment") + } + if u.User != nil { + return nil, fmt.Errorf("redirect uri must not carry credentials") + } + switch u.Scheme { + case "http": + if !isLoopbackHost(u.Host[:hostEnd(u.Host)]) { + return nil, fmt.Errorf("http redirect uri must use 127.0.0.1, [::1] or localhost") + } + case "https": + if u.Hostname() == "" { + return nil, fmt.Errorf("https redirect uri needs a host") + } + default: + return nil, fmt.Errorf("redirect uri scheme %q is not allowed", u.Scheme) + } + return u, nil +} + +// hostEnd returns the index where the port starts in a host[:port] string +// (len(h) when there is none), understanding bracketed IPv6. +func hostEnd(h string) int { + if strings.HasPrefix(h, "[") { + if i := strings.Index(h, "]"); i >= 0 { + return i + 1 + } + return len(h) + } + if i := strings.LastIndex(h, ":"); i >= 0 { + return i + } + return len(h) +} + +func isLoopbackURL(u *url.URL) bool { + return u.Scheme == "http" && isLoopbackHost(u.Host[:hostEnd(u.Host)]) +} + +// stripPort removes the port from the authority of an already validated URI +// string and leaves every other byte alone, so two loopback URIs compare equal +// only when they differ by port at most. +func stripPort(raw string) string { + i := strings.Index(raw, "://") + if i < 0 { + return raw + } + start := i + 3 + end := len(raw) + if j := strings.IndexAny(raw[start:], "/?#"); j >= 0 { + end = start + j + } + auth := raw[start:end] + return raw[:start] + auth[:hostEnd(auth)] + raw[end:] +} + +// ValidateRegisteredRedirects checks the redirect URIs of a registration: 1 to +// 5 entries, each an absolute URL without fragment or user info, either http +// on 127.0.0.1, [::1] or localhost, or https with a host. Custom schemes are +// refused. +func ValidateRegisteredRedirects(uris []string) error { + if len(uris) < 1 || len(uris) > MaxRedirectURIs { + return ErrRedirectCount + } + for _, raw := range uris { + if _, err := parseRedirect(raw); err != nil { + return err + } + } + return nil +} + +// MatchRedirect finds the registered URI that the presented redirect URI +// stands for. https must match exactly; loopback http matches on scheme, host, +// path and query with the port ignored (RFC 8252 section 7.3). For loopback the +// presented URI is returned, since it names the port the client listens on. +func MatchRedirect(registered []string, presented string) (matched string, ok bool) { + p, err := parseRedirect(presented) + if err != nil { + return "", false + } + for _, reg := range registered { + if p.Scheme == "https" { + if reg == presented { + return presented, true + } + continue + } + r, err := parseRedirect(reg) + if err != nil || !isLoopbackURL(r) { + continue + } + if isLoopbackURL(p) && stripPort(reg) == stripPort(presented) { + return presented, true + } + } + return "", false +} + +// BuildRedirect parses base, keeps its existing query and appends params +// percent-encoded. The order is deterministic: code, error, error_description +// and iss first, then state, then any other key alphabetically. Which keys are +// present is decided entirely by the map. +func BuildRedirect(base string, params map[string]string) (string, error) { + u, err := url.Parse(base) + if err != nil || !u.IsAbs() { + return "", errors.New("mcplogin: invalid redirect base") + } + order := []string{"code", "error", "error_description", "iss"} + var keys []string + seen := map[string]bool{} + for _, k := range order { + if _, ok := params[k]; ok { + keys = append(keys, k) + seen[k] = true + } + } + var rest []string + for k := range params { + if !seen[k] && k != "state" { + rest = append(rest, k) + } + } + sort.Strings(rest) + keys = append(keys, rest...) + if _, ok := params["state"]; ok { + keys = append(keys, "state") + } + var b strings.Builder + b.WriteString(u.RawQuery) + for _, k := range keys { + if b.Len() > 0 { + b.WriteByte('&') + } + b.WriteString(url.QueryEscape(k)) + b.WriteByte('=') + b.WriteString(url.QueryEscape(params[k])) + } + u.RawQuery = b.String() + return u.String(), nil +} diff --git a/internal/mcplogin/redirect_test.go b/internal/mcplogin/redirect_test.go new file mode 100644 index 000000000..618546a94 --- /dev/null +++ b/internal/mcplogin/redirect_test.go @@ -0,0 +1,105 @@ +package mcplogin + +import ( + "strings" + "testing" +) + +func TestValidateRegisteredRedirects(t *testing.T) { + ok := [][]string{ + {"http://127.0.0.1/cb"}, + {"http://127.0.0.1:8123/cb?x=1"}, + {"http://[::1]:9/cb"}, + {"http://localhost:1/cb"}, + {"https://example.com/cb"}, + {"http://127.0.0.1/a", "https://example.com/b"}, + {"https://a/1", "https://a/2", "https://a/3", "https://a/4", "https://a/5"}, + } + for _, c := range ok { + if err := ValidateRegisteredRedirects(c); err != nil { + t.Errorf("%v: %v", c, err) + } + } + bad := [][]string{ + nil, + {}, + {"https://a/1", "https://a/2", "https://a/3", "https://a/4", "https://a/5", "https://a/6"}, + {"http://example.com/cb"}, + {"http://127.0.0.2/cb"}, + {"http://localhost.evil.com/cb"}, + {"cursor://callback"}, + {"vscode://x/y"}, + {"https://example.com/cb#frag"}, + {"http://127.0.0.1/cb#"}, + {"https://user:pw@example.com/cb"}, + {"https:///cb"}, + {"/relative"}, + {""}, + {"https://example.com/cb", "bad"}, + } + for _, c := range bad { + if err := ValidateRegisteredRedirects(c); err == nil { + t.Errorf("%v accepted", c) + } + } +} + +func TestMatchRedirect(t *testing.T) { + reg := []string{"http://127.0.0.1/cb", "https://app.example.com/cb", "http://localhost/x?y=1", "http://[::1]/v6"} + cases := []struct { + in, want string + ok bool + }{ + {"http://127.0.0.1:54321/cb", "http://127.0.0.1:54321/cb", true}, + {"http://127.0.0.1/cb", "http://127.0.0.1/cb", true}, + {"http://127.0.0.1:54321/other", "", false}, + {"http://localhost:1/x?y=1", "http://localhost:1/x?y=1", true}, + {"http://localhost:1/x?y=2", "", false}, + {"http://localhost:1/x", "", false}, + {"http://[::1]:7/v6", "http://[::1]:7/v6", true}, + {"http://127.0.0.1:1/cb#f", "", false}, + {"https://app.example.com/cb", "https://app.example.com/cb", true}, + {"https://app.example.com:444/cb", "", false}, + {"https://app.example.com/cb/", "", false}, + {"http://app.example.com/cb", "", false}, + {"https://127.0.0.1/cb", "", false}, + {"http://localhost:1/cb", "", false}, + {"", "", false}, + {"garbage", "", false}, + } + for _, c := range cases { + got, ok := MatchRedirect(reg, c.in) + if ok != c.ok || got != c.want { + t.Errorf("%q: got %q %v", c.in, got, ok) + } + } +} + +func TestBuildRedirect(t *testing.T) { + got, err := BuildRedirect("http://127.0.0.1:5/cb?keep=1", map[string]string{"code": "abc", "state": "a b&c=d/é"}) + if err != nil { + t.Fatal(err) + } + want := "http://127.0.0.1:5/cb?keep=1&code=abc&state=a+b%26c%3Dd%2F%C3%A9" + if got != want { + t.Fatalf("got %s want %s", got, want) + } + got, _ = BuildRedirect("https://a/cb", map[string]string{"state": "s", "error": "access_denied"}) + if got != "https://a/cb?error=access_denied&state=s" { + t.Fatalf("order: %s", got) + } + got, _ = BuildRedirect("https://a/cb", map[string]string{"code": "c"}) + if got != "https://a/cb?code=c" { + t.Fatalf("no state: %s", got) + } + got, _ = BuildRedirect("https://a/cb", map[string]string{"code": "c", "state": ""}) + if got != "https://a/cb?code=c&state=" { + t.Fatalf("empty passed key kept: %s", got) + } + if _, err := BuildRedirect("::bad", nil); err == nil { + t.Fatal("bad base") + } + if got, _ := BuildRedirect("https://a/cb", nil); !strings.HasPrefix(got, "https://a/cb") { + t.Fatal(got) + } +} diff --git a/internal/mcplogin/registration.go b/internal/mcplogin/registration.go new file mode 100644 index 000000000..9936c6ac3 --- /dev/null +++ b/internal/mcplogin/registration.go @@ -0,0 +1,130 @@ +package mcplogin + +import ( + "time" + "unicode/utf8" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/clientidentity" +) + +// RFC 7591 error codes used by registration. +const ( + // ErrCodeInvalidRedirectURI is the error code for a refused redirect URI. + ErrCodeInvalidRedirectURI = "invalid_redirect_uri" + // ErrCodeInvalidClientMetadata is the error code for other refused metadata. + ErrCodeInvalidClientMetadata = "invalid_client_metadata" +) + +const ( + maxNameBytes = 128 + maxSoftwareBytes = 64 +) + +// RegistrationRequest is the JSON body of POST /oauth/register. +type RegistrationRequest struct { + RedirectURIs []string `json:"redirect_uris"` + ClientName string `json:"client_name"` + SoftwareID string `json:"software_id"` + SoftwareVersion string `json:"software_version"` + TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"` + GrantTypes []string `json:"grant_types"` + ResponseTypes []string `json:"response_types"` +} + +// Registration is a validated registration with its effective values. The +// caller assigns ClientID (see NewClientID) before storing or answering. +type Registration struct { + ClientID string + RedirectURIs []string + ClientName string + SoftwareID string + SoftwareVersion string + TokenEndpointAuthMethod string + GrantTypes []string + ResponseTypes []string +} + +// RegError is a registration refusal, shaped for an RFC 7591 error answer. +type RegError struct { + // Code is ErrCodeInvalidRedirectURI or ErrCodeInvalidClientMetadata. + Code string + // Description is a human-readable reason. + Description string +} + +// Error implements error. +func (e *RegError) Error() string { return e.Code + ": " + e.Description } + +// truncateUTF8 cuts s to at most max bytes without splitting a character. +func truncateUTF8(s string, max int) string { + if len(s) <= max { + return s + } + s = s[:max] + for len(s) > 0 && !utf8.ValidString(s) { + s = s[:len(s)-1] + } + return s +} + +func sanitize(s string, max int) string { + return truncateUTF8(clientidentity.SanitizeDisplay(s), max) +} + +// ValidateRegistration checks a request and returns the registration with the +// effective values: method "none", grants authorization_code and +// refresh_token, response type code. A request that asks for anything else is +// refused rather than silently changed. +func ValidateRegistration(req RegistrationRequest) (Registration, *RegError) { + if err := ValidateRegisteredRedirects(req.RedirectURIs); err != nil { + return Registration{}, &RegError{Code: ErrCodeInvalidRedirectURI, Description: err.Error()} + } + if m := req.TokenEndpointAuthMethod; m != "" && m != "none" { + return Registration{}, &RegError{Code: ErrCodeInvalidClientMetadata, + Description: "only token_endpoint_auth_method \"none\" is supported"} + } + for _, g := range req.GrantTypes { + if g != "authorization_code" && g != "refresh_token" { + return Registration{}, &RegError{Code: ErrCodeInvalidClientMetadata, + Description: "only the authorization_code and refresh_token grant types are supported"} + } + } + for _, r := range req.ResponseTypes { + if r != "code" { + return Registration{}, &RegError{Code: ErrCodeInvalidClientMetadata, + Description: "only the code response type is supported"} + } + } + return Registration{ + RedirectURIs: append([]string(nil), req.RedirectURIs...), + ClientName: sanitize(req.ClientName, maxNameBytes), + SoftwareID: sanitize(req.SoftwareID, maxSoftwareBytes), + SoftwareVersion: sanitize(req.SoftwareVersion, maxSoftwareBytes), + TokenEndpointAuthMethod: "none", + GrantTypes: []string{"authorization_code", "refresh_token"}, + ResponseTypes: []string{"code"}, + }, nil +} + +// NewClientID returns a fresh registration client id: 22 base62 characters. +func NewClientID() (string, error) { return randomBase62(22) } + +// Response is the RFC 7591 201 body. It never carries a client_secret. +func (r Registration) Response(issuedAt time.Time) map[string]any { + m := map[string]any{ + "client_id": r.ClientID, + "client_id_issued_at": issuedAt.Unix(), + "redirect_uris": r.RedirectURIs, + "client_name": r.ClientName, + "token_endpoint_auth_method": r.TokenEndpointAuthMethod, + "grant_types": r.GrantTypes, + "response_types": r.ResponseTypes, + } + if r.SoftwareID != "" { + m["software_id"] = r.SoftwareID + } + if r.SoftwareVersion != "" { + m["software_version"] = r.SoftwareVersion + } + return m +} diff --git a/internal/mcplogin/registration_test.go b/internal/mcplogin/registration_test.go new file mode 100644 index 000000000..9740fdc9c --- /dev/null +++ b/internal/mcplogin/registration_test.go @@ -0,0 +1,110 @@ +package mcplogin + +import ( + "strings" + "testing" + "time" +) + +func TestValidateRegistrationOK(t *testing.T) { + reg, rerr := ValidateRegistration(RegistrationRequest{ + RedirectURIs: []string{"http://127.0.0.1:1/cb"}, + ClientName: " My\x07 Client ", + SoftwareID: "sw", SoftwareVersion: "1.0", + TokenEndpointAuthMethod: "none", + GrantTypes: []string{"refresh_token", "authorization_code"}, + ResponseTypes: []string{"code"}, + }) + if rerr != nil { + t.Fatal(rerr) + } + if reg.ClientName != "my client" || reg.TokenEndpointAuthMethod != "none" || + len(reg.GrantTypes) != 2 || reg.GrantTypes[0] != "authorization_code" || + len(reg.ResponseTypes) != 1 || reg.ResponseTypes[0] != "code" { + t.Fatalf("%+v", reg) + } + if _, rerr := ValidateRegistration(RegistrationRequest{RedirectURIs: []string{"https://a/cb"}}); rerr != nil { + t.Fatal(rerr) + } +} + +func TestValidateRegistrationRefusals(t *testing.T) { + base := func() RegistrationRequest { return RegistrationRequest{RedirectURIs: []string{"https://a/cb"}} } + type tc struct { + mod func(*RegistrationRequest) + code string + } + cases := map[string]tc{ + "no redirects": {func(r *RegistrationRequest) { r.RedirectURIs = nil }, ErrCodeInvalidRedirectURI}, + "fragment": {func(r *RegistrationRequest) { r.RedirectURIs = []string{"https://a/cb#x"} }, ErrCodeInvalidRedirectURI}, + "http non-loop": {func(r *RegistrationRequest) { r.RedirectURIs = []string{"http://a/cb"} }, ErrCodeInvalidRedirectURI}, + "custom scheme": {func(r *RegistrationRequest) { r.RedirectURIs = []string{"x://cb"} }, ErrCodeInvalidRedirectURI}, + "secret basic": {func(r *RegistrationRequest) { r.TokenEndpointAuthMethod = "client_secret_basic" }, ErrCodeInvalidClientMetadata}, + "secret post": {func(r *RegistrationRequest) { r.TokenEndpointAuthMethod = "client_secret_post" }, ErrCodeInvalidClientMetadata}, + "implicit grant": {func(r *RegistrationRequest) { r.GrantTypes = []string{"implicit"} }, ErrCodeInvalidClientMetadata}, + "client creds": {func(r *RegistrationRequest) { + r.GrantTypes = []string{"authorization_code", "client_credentials"} + }, ErrCodeInvalidClientMetadata}, + "token response": {func(r *RegistrationRequest) { r.ResponseTypes = []string{"token"} }, ErrCodeInvalidClientMetadata}, + "code+token": {func(r *RegistrationRequest) { r.ResponseTypes = []string{"code", "token"} }, ErrCodeInvalidClientMetadata}, + } + for name, c := range cases { + r := base() + c.mod(&r) + _, rerr := ValidateRegistration(r) + if rerr == nil || rerr.Code != c.code || rerr.Description == "" { + t.Errorf("%s: %+v", name, rerr) + } + } +} + +func TestValidateRegistrationCaps(t *testing.T) { + r := RegistrationRequest{ + RedirectURIs: []string{"https://a/cb"}, ClientName: strings.Repeat("é", 200), + SoftwareID: strings.Repeat("s", 200), SoftwareVersion: strings.Repeat("v", 200), + } + reg, rerr := ValidateRegistration(r) + if rerr != nil { + t.Fatal(rerr) + } + if len(reg.ClientName) > 128 || len(reg.SoftwareID) > 64 || len(reg.SoftwareVersion) > 64 { + t.Fatalf("caps: %d %d %d", len(reg.ClientName), len(reg.SoftwareID), len(reg.SoftwareVersion)) + } + if !strings.HasPrefix(reg.ClientName, "é") || strings.ContainsRune(reg.ClientName, '\uFFFD') { + t.Fatal("truncation must keep valid utf-8") + } +} + +func TestNewClientID(t *testing.T) { + a, err := NewClientID() + if err != nil || len(a) != 22 { + t.Fatalf("%q %v", a, err) + } + b, _ := NewClientID() + if a == b { + t.Fatal("same id") + } +} + +func TestRegistrationResponse(t *testing.T) { + reg, _ := ValidateRegistration(RegistrationRequest{RedirectURIs: []string{"https://a/cb"}, ClientName: "X", SoftwareID: " SW\x07", SoftwareVersion: "1.0"}) + reg.ClientID = "abc" + m := reg.Response(time.Unix(1700000000, 0)) + if m["client_id"] != "abc" || m["client_id_issued_at"] != int64(1700000000) || + m["token_endpoint_auth_method"] != "none" || m["client_name"] != "x" { + t.Fatalf("%v", m) + } + if m["software_id"] != "sw" || m["software_version"] != "1.0" { + t.Fatalf("software fields: %v", m) + } + bare, _ := ValidateRegistration(RegistrationRequest{RedirectURIs: []string{"https://a/cb"}}) + if _, has := bare.Response(time.Unix(1, 0))["software_id"]; has { + t.Fatal("empty software_id must be omitted") + } + if _, has := m["client_secret"]; has { + t.Fatal("client_secret present") + } + if uris, _ := m["redirect_uris"].([]string); len(uris) != 1 { + t.Fatalf("%v", m["redirect_uris"]) + } +} diff --git a/internal/mcplogin/requests.go b/internal/mcplogin/requests.go new file mode 100644 index 000000000..5c4768035 --- /dev/null +++ b/internal/mcplogin/requests.go @@ -0,0 +1,349 @@ +package mcplogin + +import ( + "errors" + "sort" + "sync" + "time" +) + +// Lifetimes of the in-memory login state. +const ( + // RequestLifetime is how long an authorization request lives. + RequestLifetime = 10 * time.Minute + // CodeLifetime is how long an authorization code is usable. + CodeLifetime = 60 * time.Second + // TombstoneLifetime is how long a consumed code is remembered so that a + // second presentation can be told from an unknown code. + TombstoneLifetime = 10 * time.Minute +) + +// Errors returned by Store. +var ( + // ErrTooManyPending means MaxPendingRequests requests are already pending. + ErrTooManyPending = errors.New("mcplogin: too many pending authorization requests") + // ErrRequestNotFound means the request does not exist or has expired. + ErrRequestNotFound = errors.New("mcplogin: authorization request not found") + // ErrAlreadyDecided means the request left the pending state already. + ErrAlreadyDecided = errors.New("mcplogin: authorization request already decided") + // ErrCodeUnknown means the code is unknown, expired, cancelled or burned. + ErrCodeUnknown = errors.New("mcplogin: authorization code unknown") + // ErrCodeReused means a consumed code was presented again inside the + // tombstone window. Consume returns the grant id it produced. + ErrCodeReused = errors.New("mcplogin: authorization code already used") +) + +// Status is the state of an authorization request. +type Status string + +// Request states. A request is decided once: pending moves to approved or +// denied, and an approved request can still become cancelled until its code is +// consumed. Consumed is the final state of a request whose code was exchanged. +const ( + // StatusPending awaits the administrator's decision. + StatusPending Status = "pending" + // StatusApproved has a code issued and not yet exchanged. + StatusApproved Status = "approved" + // StatusDenied was refused by the administrator. + StatusDenied Status = "denied" + // StatusExpired ran out of time. + StatusExpired Status = "expired" + // StatusCancelled was withdrawn (client revoked or forgotten, feature off). + StatusCancelled Status = "cancelled" + // StatusConsumed had its code exchanged. + StatusConsumed Status = "consumed" +) + +// Decision is what the administrator chose when approving a request. +type Decision struct { + // ClientID is the client hub id the login is for. + ClientID string + // NewClient is true when approval creates the client. + NewClient bool + // DisplayName is the display name of a new client. + DisplayName string + // Profile is the profile the client is bound to. + Profile string + // Mode is the binding mode. + Mode string + // BindingRevision is the binding revision the consent page displayed. + BindingRevision string + // ReplaceGrantID is the earlier login to revoke on success, if any. + ReplaceGrantID string + // ActorKind and ActorName identify the approving administrator. + ActorKind string + ActorName string +} + +// Request is one authorization request, kept in memory only. +type Request struct { + ID string + RegistrationID string + RedirectURI string + State string + CodeChallenge string + Resource string + Issuer string + // PathClient is the client id from the resource path, empty for the + // generic address. + PathClient string + Status Status + Decision Decision + CreatedAt time.Time + ExpiresAt time.Time +} + +type codeEntry struct { + requestID string + expiresAt time.Time + consumed bool + consumedAt time.Time + grantID string // empty when the commit failed +} + +// Store holds authorization requests and their codes. It is safe for +// concurrent use; one mutex guards everything and nothing blocks under it +// except the commit callback of Consume, which is its single-use boundary. +type Store struct { + key []byte + now func() time.Time + mu sync.Mutex + reqs map[string]*Request + codes map[string]*codeEntry // keyed by HashSecret(kind code) +} + +// NewStore returns an empty Store. key hashes codes; now is the clock (nil +// means time.Now). +func NewStore(key []byte, now func() time.Time) *Store { + if now == nil { + now = time.Now + } + return &Store{key: key, now: now, reqs: map[string]*Request{}, codes: map[string]*codeEntry{}} +} + +// live returns the request with lazy expiry applied. Caller holds s.mu. +func (s *Store) live(id string) *Request { + r := s.reqs[id] + if r == nil { + return nil + } + if (r.Status == StatusPending || r.Status == StatusApproved) && !s.now().Before(r.ExpiresAt) { + r.Status = StatusExpired + } + if r.Status == StatusExpired { + return nil + } + return r +} + +func (s *Store) pendingCountLocked() int { + n := 0 + for id := range s.reqs { + if r := s.live(id); r != nil && r.Status == StatusPending { + n++ + } + } + return n +} + +// Create stores a new pending request built from req (ID, Status, CreatedAt +// and ExpiresAt are assigned here). It fails with ErrTooManyPending at the cap. +func (s *Store) Create(req Request) (Request, error) { + id, err := randomBase62(22) + if err != nil { + return Request{}, err + } + s.mu.Lock() + defer s.mu.Unlock() + s.sweepLocked() + if s.pendingCountLocked() >= MaxPendingRequests { + return Request{}, ErrTooManyPending + } + now := s.now() + req.ID = id + req.Status = StatusPending + req.Decision = Decision{} + req.CreatedAt = now + req.ExpiresAt = now.Add(RequestLifetime) + s.reqs[id] = &req + return req, nil +} + +// Get returns a copy of the request. An expired request reads as not found. +func (s *Store) Get(id string) (Request, bool) { + s.mu.Lock() + defer s.mu.Unlock() + r := s.live(id) + if r == nil { + return Request{}, false + } + return *r, true +} + +// ListPending returns the pending requests, oldest first. +func (s *Store) ListPending() []Request { + s.mu.Lock() + defer s.mu.Unlock() + var out []Request + for id := range s.reqs { + if r := s.live(id); r != nil && r.Status == StatusPending { + out = append(out, *r) + } + } + sort.Slice(out, func(i, j int) bool { + if out[i].CreatedAt.Equal(out[j].CreatedAt) { + return out[i].ID < out[j].ID + } + return out[i].CreatedAt.Before(out[j].CreatedAt) + }) + return out +} + +// Approve moves a pending request to approved, records the decision and +// returns the single-use code (valid CodeLifetime). A request that is no +// longer pending gives ErrAlreadyDecided. +func (s *Store) Approve(id string, d Decision) (string, error) { + code, err := randomSecret() + if err != nil { + return "", err + } + s.mu.Lock() + defer s.mu.Unlock() + s.sweepLocked() + r := s.live(id) + if r == nil { + return "", ErrRequestNotFound + } + if r.Status != StatusPending { + return "", ErrAlreadyDecided + } + now := s.now() + r.Status = StatusApproved + r.Decision = d + // Pending expiry and approved-code expiry are separate: an approved + // request lives exactly as long as its code. + r.ExpiresAt = now.Add(CodeLifetime) + s.codes[HashSecret(s.key, KindCode, code)] = &codeEntry{requestID: id, expiresAt: now.Add(CodeLifetime)} + return code, nil +} + +// Deny moves a pending request to denied. +func (s *Store) Deny(id string) error { + s.mu.Lock() + defer s.mu.Unlock() + r := s.live(id) + if r == nil { + return ErrRequestNotFound + } + if r.Status != StatusPending { + return ErrAlreadyDecided + } + r.Status = StatusDenied + return nil +} + +func (s *Store) cancelWhere(match func(*Request) bool) int { + n := 0 + for id := range s.reqs { + r := s.live(id) + if r == nil || (r.Status != StatusPending && r.Status != StatusApproved) { + continue + } + if match(r) { + r.Status = StatusCancelled + n++ + } + } + return n +} + +// CancelForClient cancels the pending and approved-but-unconsumed requests +// whose path client or decided client is clientID. Their codes become unusable. +func (s *Store) CancelForClient(clientID string) int { + s.mu.Lock() + defer s.mu.Unlock() + return s.cancelWhere(func(r *Request) bool { + return r.PathClient == clientID || (r.Status == StatusApproved && r.Decision.ClientID == clientID) + }) +} + +// CancelAll cancels every pending and approved-but-unconsumed request. +func (s *Store) CancelAll() int { + s.mu.Lock() + defer s.mu.Unlock() + return s.cancelWhere(func(*Request) bool { return true }) +} + +// Consume exchanges a code. Under the store lock it checks that the code is +// known, unexpired, unconsumed and that its request is still approved, then +// calls commit with a copy of the request. On success the request is consumed +// and a tombstone {consumed_at, grant_id} is kept for TombstoneLifetime. If +// commit fails the code is burned too (single use) and the error is returned. +// Presenting a consumed code again inside the tombstone window returns +// ErrCodeReused together with the grant id it produced; afterwards the code is +// unknown. This holds for a code whose commit failed as well, with an empty +// grant id: callers must treat an empty grant id as "nothing to revoke". +func (s *Store) Consume(code string, commit func(Request) (grantID string, err error)) (Request, string, error) { + h := HashSecret(s.key, KindCode, code) + s.mu.Lock() + defer s.mu.Unlock() + s.sweepLocked() + now := s.now() + e := s.codes[h] + if e == nil { + return Request{}, "", ErrCodeUnknown + } + if e.consumed { + if now.Before(e.consumedAt.Add(TombstoneLifetime)) { + return Request{}, e.grantID, ErrCodeReused + } + delete(s.codes, h) + return Request{}, "", ErrCodeUnknown + } + if !now.Before(e.expiresAt) { + delete(s.codes, h) + return Request{}, "", ErrCodeUnknown + } + r := s.live(e.requestID) + if r == nil || r.Status != StatusApproved { + delete(s.codes, h) + return Request{}, "", ErrCodeUnknown + } + e.consumed = true + e.consumedAt = now + r.Status = StatusConsumed + grantID, err := commit(*r) + if err != nil { + return Request{}, "", err + } + e.grantID = grantID + return *r, grantID, nil +} + +// Sweep removes expired requests and codes and tombstones past their window. +func (s *Store) Sweep() { + s.mu.Lock() + defer s.mu.Unlock() + s.sweepLocked() +} + +// sweepLocked drops dead entries. Create, Approve and Consume call it, so the +// maps stay bounded by what is live (at most MaxPendingRequests pending plus +// ten minutes of decided state) without an external janitor. Caller holds s.mu. +func (s *Store) sweepLocked() { + now := s.now() + for id, r := range s.reqs { + if !now.Before(r.ExpiresAt) { + delete(s.reqs, id) + } + } + for h, e := range s.codes { + if e.consumed { + if !now.Before(e.consumedAt.Add(TombstoneLifetime)) { + delete(s.codes, h) + } + } else if !now.Before(e.expiresAt) { + delete(s.codes, h) + } + } +} diff --git a/internal/mcplogin/requests_test.go b/internal/mcplogin/requests_test.go new file mode 100644 index 000000000..efb2d5471 --- /dev/null +++ b/internal/mcplogin/requests_test.go @@ -0,0 +1,253 @@ +package mcplogin + +import ( + "errors" + "sync" + "sync/atomic" + "testing" + "time" +) + +func newTestStore() (*Store, *fakeClock) { + clk := &fakeClock{t: time.Unix(1000, 0)} + return NewStore(testKey, clk.now), clk +} + +func mkReq(pathClient string) Request { + return Request{RegistrationID: "reg1", RedirectURI: "http://127.0.0.1:1/cb", State: "st", + CodeChallenge: "ch", Resource: "http://127.0.0.1:8080/mcp/oauth", Issuer: "http://127.0.0.1:8080", PathClient: pathClient} +} + +func mustCreate(t *testing.T, s *Store, pc string) Request { + t.Helper() + r, err := s.Create(mkReq(pc)) + if err != nil { + t.Fatal(err) + } + return r +} + +func TestCreateGetList(t *testing.T) { + s, clk := newTestStore() + r := mustCreate(t, s, "") + if len(r.ID) != 22 || r.Status != StatusPending || !r.ExpiresAt.Equal(clk.now().Add(RequestLifetime)) { + t.Fatalf("%+v", r) + } + g, ok := s.Get(r.ID) + if !ok || g.ID != r.ID { + t.Fatal("get") + } + if len(s.ListPending()) != 1 { + t.Fatal("list") + } + clk.advance(RequestLifetime) + if _, ok := s.Get(r.ID); ok { + t.Fatal("expired must read as not found") + } + if len(s.ListPending()) != 0 { + t.Fatal("expired listed") + } + if _, err := s.Approve(r.ID, Decision{ClientID: "c"}); !errors.Is(err, ErrRequestNotFound) { + t.Fatalf("approve expired: %v", err) + } +} + +func TestCap(t *testing.T) { + s, _ := newTestStore() + for i := 0; i < MaxPendingRequests; i++ { + mustCreate(t, s, "") + } + if _, err := s.Create(mkReq("")); !errors.Is(err, ErrTooManyPending) { + t.Fatalf("%v", err) + } +} + +func TestCapIgnoresDecided(t *testing.T) { + s, _ := newTestStore() + var first Request + for i := 0; i < MaxPendingRequests; i++ { + r := mustCreate(t, s, "") + if i == 0 { + first = r + } + } + if err := s.Deny(first.ID); err != nil { + t.Fatal(err) + } + if _, err := s.Create(mkReq("")); err != nil { + t.Fatalf("slot should be free: %v", err) + } +} + +func TestDecidedOnceRace(t *testing.T) { + s, _ := newTestStore() + r := mustCreate(t, s, "") + var wins, losses int32 + var wg sync.WaitGroup + for i := 0; i < 16; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + var err error + if i%2 == 0 { + _, err = s.Approve(r.ID, Decision{ClientID: "c"}) + } else { + err = s.Deny(r.ID) + } + if err == nil { + atomic.AddInt32(&wins, 1) + } else if errors.Is(err, ErrAlreadyDecided) { + atomic.AddInt32(&losses, 1) + } else { + t.Errorf("unexpected %v", err) + } + }(i) + } + wg.Wait() + if wins != 1 || losses != 15 { + t.Fatalf("wins %d losses %d", wins, losses) + } +} + +func TestApproveConsumeHappyPath(t *testing.T) { + s, _ := newTestStore() + r := mustCreate(t, s, "cursor") + code, err := s.Approve(r.ID, Decision{ClientID: "cursor", ActorKind: "admin", ActorName: "a"}) + if err != nil || code == "" { + t.Fatal(err) + } + g, _ := s.Get(r.ID) + if g.Status != StatusApproved || g.Decision.ClientID != "cursor" { + t.Fatalf("%+v", g) + } + if _, err := s.Approve(r.ID, Decision{}); !errors.Is(err, ErrAlreadyDecided) { + t.Fatal(err) + } + if err := s.Deny(r.ID); !errors.Is(err, ErrAlreadyDecided) { + t.Fatal(err) + } + var seen Request + got, gid, err := s.Consume(code, func(q Request) (string, error) { seen = q; return "grant1", nil }) + if err != nil || gid != "grant1" || got.ID != r.ID || seen.Decision.ClientID != "cursor" { + t.Fatalf("%+v %q %v", got, gid, err) + } + if g, _ := s.Get(r.ID); g.Status != StatusConsumed { + t.Fatalf("status %s", g.Status) + } +} + +func TestConsumeReuse(t *testing.T) { + s, clk := newTestStore() + r := mustCreate(t, s, "") + code, _ := s.Approve(r.ID, Decision{ClientID: "c"}) + calls := 0 + commit := func(Request) (string, error) { calls++; return "g1", nil } + if _, _, err := s.Consume(code, commit); err != nil { + t.Fatal(err) + } + clk.advance(5 * time.Minute) + _, gid, err := s.Consume(code, commit) + if !errors.Is(err, ErrCodeReused) || gid != "g1" || calls != 1 { + t.Fatalf("%v %q %d", err, gid, calls) + } + clk.advance(6 * time.Minute) + if _, gid, err := s.Consume(code, commit); !errors.Is(err, ErrCodeUnknown) || gid != "" { + t.Fatalf("%v %q", err, gid) + } +} + +func TestConsumeExpiryAndUnknown(t *testing.T) { + s, clk := newTestStore() + r := mustCreate(t, s, "") + code, _ := s.Approve(r.ID, Decision{ClientID: "c"}) + if _, _, err := s.Consume("nope", nil); !errors.Is(err, ErrCodeUnknown) { + t.Fatal(err) + } + clk.advance(CodeLifetime) + called := false + if _, _, err := s.Consume(code, func(Request) (string, error) { called = true; return "g", nil }); !errors.Is(err, ErrCodeUnknown) || called { + t.Fatalf("%v %v", err, called) + } +} + +func TestConsumeCommitErrorBurnsCode(t *testing.T) { + s, _ := newTestStore() + r := mustCreate(t, s, "") + code, _ := s.Approve(r.ID, Decision{ClientID: "c"}) + boom := errors.New("boom") + if _, _, err := s.Consume(code, func(Request) (string, error) { return "", boom }); !errors.Is(err, boom) { + t.Fatal(err) + } + called := false + _, gid, err := s.Consume(code, func(Request) (string, error) { called = true; return "g", nil }) + if called || gid != "" || !errors.Is(err, ErrCodeReused) { + t.Fatalf("code reusable after failed commit: %v %q %v", err, gid, called) + } +} + +func TestCancelForClient(t *testing.T) { + s, _ := newTestStore() + pathReq := mustCreate(t, s, "cursor") + decided := mustCreate(t, s, "") + code, _ := s.Approve(decided.ID, Decision{ClientID: "cursor"}) + other := mustCreate(t, s, "other") + if n := s.CancelForClient("cursor"); n != 2 { + t.Fatalf("cancelled %d", n) + } + if g, _ := s.Get(pathReq.ID); g.Status != StatusCancelled { + t.Fatal("path req") + } + if g, _ := s.Get(decided.ID); g.Status != StatusCancelled { + t.Fatal("decided req") + } + if g, _ := s.Get(other.ID); g.Status != StatusPending { + t.Fatal("other touched") + } + called := false + if _, _, err := s.Consume(code, func(Request) (string, error) { called = true; return "g", nil }); !errors.Is(err, ErrCodeUnknown) || called { + t.Fatalf("cancelled code usable: %v", err) + } + if _, err := s.Approve(pathReq.ID, Decision{ClientID: "x"}); !errors.Is(err, ErrAlreadyDecided) { + t.Fatalf("approve cancelled: %v", err) + } +} + +func TestCancelAllAndAfterConsume(t *testing.T) { + s, _ := newTestStore() + a := mustCreate(t, s, "") + b := mustCreate(t, s, "x") + code, _ := s.Approve(b.ID, Decision{ClientID: "x"}) + consumedReq := mustCreate(t, s, "") + c2, _ := s.Approve(consumedReq.ID, Decision{ClientID: "y"}) + if _, _, err := s.Consume(c2, func(Request) (string, error) { return "g", nil }); err != nil { + t.Fatal(err) + } + if n := s.CancelAll(); n != 2 { + t.Fatalf("cancelled %d", n) + } + if g, _ := s.Get(a.ID); g.Status != StatusCancelled { + t.Fatal("a") + } + if _, _, err := s.Consume(code, func(Request) (string, error) { return "g", nil }); !errors.Is(err, ErrCodeUnknown) { + t.Fatal(err) + } + if _, gid, err := s.Consume(c2, nil); !errors.Is(err, ErrCodeReused) || gid != "g" { + t.Fatalf("%v %q", err, gid) + } + if n := s.CancelForClient("y"); n != 0 { + t.Fatalf("consumed request must not be cancelled: %d", n) + } +} + +func TestSweep(t *testing.T) { + s, clk := newTestStore() + mustCreate(t, s, "") + r := mustCreate(t, s, "") + code, _ := s.Approve(r.ID, Decision{ClientID: "c"}) + _, _, _ = s.Consume(code, func(Request) (string, error) { return "g", nil }) + clk.advance(RequestLifetime + TombstoneLifetime) + s.Sweep() + if n := s.size(); n != 0 { + t.Fatalf("left %d entries", n) + } +} diff --git a/internal/mcplogin/resource.go b/internal/mcplogin/resource.go new file mode 100644 index 000000000..d10ae2bb7 --- /dev/null +++ b/internal/mcplogin/resource.go @@ -0,0 +1,65 @@ +package mcplogin + +import ( + "net/http" + "net/url" + "strings" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +// resourceBase is the path of the generic OAuth-protected MCP endpoint. +const resourceBase = "/mcp/oauth" + +// Origin returns "scheme://host" for the request: https when the connection is +// TLS, else http; the host is r.Host lowercased and otherwise verbatim. It is +// used as the issuer and as the resource prefix, so "localhost" and +// "127.0.0.1" are different origins by design. +func Origin(r *http.Request) string { + scheme := "http" + if r.TLS != nil { + scheme = "https" + } + return scheme + "://" + strings.ToLower(r.Host) +} + +// ResourcePath returns "/mcp/oauth" for an empty client id, else +// "/mcp/oauth/". +func ResourcePath(clientID string) string { + if clientID == "" { + return resourceBase + } + return resourceBase + "/" + clientID +} + +// ParseResourcePath accepts exactly /mcp/oauth, /mcp/oauth/, /mcp/oauth/ +// and /mcp/oauth// where id passes auth.ValidClientID. Nothing deeper. +func ParseResourcePath(path string) (clientID string, generic, ok bool) { + if path == resourceBase || path == resourceBase+"/" { + return "", true, true + } + rest, found := strings.CutPrefix(path, resourceBase+"/") + if !found { + return "", false, false + } + rest = strings.TrimSuffix(rest, "/") + if !auth.ValidClientID(rest) { + return "", false, false + } + return rest, false, true +} + +// ParseResource checks that resource is a URL on exactly the given origin with +// an OAuth resource path, no query and no fragment. +func ParseResource(origin, resource string) (clientID string, generic, ok bool) { + rest, found := strings.CutPrefix(resource, origin) + if !found || !strings.HasPrefix(rest, "/") { + return "", false, false + } + u, err := url.Parse(resource) + if err != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || + strings.ContainsAny(resource, "?#") || u.User != nil { + return "", false, false + } + return ParseResourcePath(rest) +} diff --git a/internal/mcplogin/resource_test.go b/internal/mcplogin/resource_test.go new file mode 100644 index 000000000..7e8a342fe --- /dev/null +++ b/internal/mcplogin/resource_test.go @@ -0,0 +1,84 @@ +package mcplogin + +import ( + "crypto/tls" + "net/http" + "net/http/httptest" + "testing" +) + +type resCase struct { + id string + generic bool + ok bool +} + +func TestOrigin(t *testing.T) { + r := httptest.NewRequest("GET", "/x", nil) + r.Host = "127.0.0.1:8080" + if Origin(r) != "http://127.0.0.1:8080" { + t.Fatal(Origin(r)) + } + r.TLS = &tls.ConnectionState{} + r.Host = "LocalHost:8443" + if Origin(r) != "https://localhost:8443" { + t.Fatal(Origin(r)) + } + if Origin(&http.Request{Host: "a"}) != "http://a" { + t.Fatal("plain request") + } +} + +func TestResourcePath(t *testing.T) { + if ResourcePath("") != "/mcp/oauth" || ResourcePath("cursor") != "/mcp/oauth/cursor" { + t.Fatal("ResourcePath") + } +} + +func TestParseResourcePath(t *testing.T) { + cases := map[string]resCase{ + "/mcp/oauth": {"", true, true}, + "/mcp/oauth/": {"", true, true}, + "/mcp/oauth/cursor": {"cursor", false, true}, + "/mcp/oauth/cursor/": {"cursor", false, true}, + "/mcp/oauth/cursor/x": {}, + "/mcp/oauth//": {}, + "/mcp/oauth/Bad": {}, + "/mcp/oauth/-x": {}, + "/mcp/oauthx": {}, + "/mcp": {}, + "/mcp/oauth/a/b/c": {}, + "": {}, + } + for p, want := range cases { + id, gen, ok := ParseResourcePath(p) + if (resCase{id, gen, ok}) != want { + t.Errorf("%q: got %q %v %v", p, id, gen, ok) + } + } +} + +func TestParseResource(t *testing.T) { + o := "http://127.0.0.1:8080" + cases := map[string]resCase{ + o + "/mcp/oauth": {"", true, true}, + o + "/mcp/oauth/cursor": {"cursor", false, true}, + o + "/mcp/oauth/cursor/": {"cursor", false, true}, + "http://localhost:8080/mcp/oauth": {}, + "https://127.0.0.1:8080/mcp/oauth": {}, + o + "/mcp/oauth?x=1": {}, + o + "/mcp/oauth?": {}, + o + "/mcp/oauth#f": {}, + o + "/mcp/oauth/cursor/x": {}, + o + "/mcp": {}, + "/mcp/oauth": {}, + "::bad": {}, + "": {}, + } + for in, want := range cases { + id, gen, ok := ParseResource(o, in) + if (resCase{id, gen, ok}) != want { + t.Errorf("%q: got %q %v %v", in, id, gen, ok) + } + } +} diff --git a/internal/mcplogin/review_fixes_test.go b/internal/mcplogin/review_fixes_test.go new file mode 100644 index 000000000..6cfd39681 --- /dev/null +++ b/internal/mcplogin/review_fixes_test.go @@ -0,0 +1,139 @@ +package mcplogin + +import ( + "errors" + "fmt" + "sync" + "testing" + "time" +) + +func (s *Store) size() int { + s.mu.Lock() + defer s.mu.Unlock() + return len(s.reqs) + len(s.codes) +} + +func (l *Limiter) tracked() int { + l.mu.Lock() + defer l.mu.Unlock() + return len(l.seen) +} + +func TestMatchRedirectDiffersByPortOnly(t *testing.T) { + reg := []string{"http://localhost/cb"} + for _, in := range []string{ + "http://localhost:54321/cb?", + "HTTP://localhost:54321/cb", + "http://LOCALHOST:54321/cb", + "http://localhost:54321/CB", + } { + if got, ok := MatchRedirect(reg, in); ok { + t.Errorf("%q matched as %q", in, got) + } + } + if _, ok := MatchRedirect([]string{"http://localhost:1/cb"}, "http://localhost:54321/cb"); !ok { + t.Error("registered port must be ignored too") + } + if _, ok := MatchRedirect([]string{"http://[::1]/cb"}, "http://[::1]:5/cb"); !ok { + t.Error("ipv6 port") + } +} + +func TestStoreStaysBounded(t *testing.T) { + s, clk := newTestStore() + for round := 0; round < 5; round++ { + for i := 0; i < MaxPendingRequests; i++ { + mustCreate(t, s, "") + } + clk.advance(RequestLifetime + time.Second) + } + if n := s.size(); n > MaxPendingRequests { + t.Fatalf("store grew to %d entries", n) + } +} + +func TestStoreCodesStayBounded(t *testing.T) { + s, clk := newTestStore() + for round := 0; round < 5; round++ { + r := mustCreate(t, s, "") + code, _ := s.Approve(r.ID, Decision{ClientID: "c"}) + clk.advance(RequestLifetime + TombstoneLifetime) + _, _, _ = s.Consume(code, nil) + } + mustCreate(t, s, "") + if n := s.size(); n > 3 { + t.Fatalf("store grew to %d entries", n) + } +} + +func TestLimiterBoundedKeys(t *testing.T) { + clk := &fakeClock{t: time.Unix(1000, 0)} + l := NewLimiter(clk.now) + for i := 0; i < MaxTrackedKeys; i++ { + if ok, _ := l.Allow(EndpointToken, fmt.Sprintf("ip-%d", i)); !ok { + t.Fatalf("key %d refused", i) + } + } + ok, retry := l.Allow(EndpointToken, "newcomer") + if ok || retry < 1 { + t.Fatalf("full limiter must refuse new key: %v %d", ok, retry) + } + if ok, _ := l.Allow(EndpointToken, "ip-0"); !ok { + t.Fatal("known key must still be served") + } + clk.advance(2 * time.Minute) + if ok, _ := l.Allow(EndpointToken, "newcomer"); !ok { + t.Fatal("idle keys should have been pruned") + } + if n := l.tracked(); n > 2 { + t.Fatalf("tracked %d", n) + } +} + +func TestApprovedCodeLivesFullLifetime(t *testing.T) { + s, clk := newTestStore() + r := mustCreate(t, s, "") + clk.advance(RequestLifetime - 10*time.Second) + code, err := s.Approve(r.ID, Decision{ClientID: "c"}) + if err != nil { + t.Fatal(err) + } + clk.advance(50 * time.Second) + if _, _, err := s.Consume(code, func(Request) (string, error) { return "g", nil }); err != nil { + t.Fatalf("code died early: %v", err) + } + r2 := mustCreate(t, s, "") + code2, _ := s.Approve(r2.ID, Decision{ClientID: "c"}) + clk.advance(CodeLifetime + time.Second) + if _, _, err := s.Consume(code2, func(Request) (string, error) { return "g", nil }); !errors.Is(err, ErrCodeUnknown) { + t.Fatalf("expired code: %v", err) + } +} + +func TestLimiterBucketsStayBoundedConcurrently(t *testing.T) { + clk := &fakeClock{t: time.Unix(1000, 0)} + l := NewLimiter(clk.now) + var wg sync.WaitGroup + for g := 0; g < 8; g++ { + wg.Add(1) + go func(g int) { + defer wg.Done() + for i := 0; i < MaxTrackedKeys; i++ { + l.Allow(EndpointToken, fmt.Sprintf("ip-%d-%d", g, i)) + if i%500 == 0 { + clk.advance(30 * time.Second) + } + } + }(g) + } + wg.Wait() + l.mu.Lock() + defer l.mu.Unlock() + if len(l.seen) > MaxTrackedKeys || l.rates.Len() > MaxTrackedKeys { + t.Fatalf("seen %d buckets %d", len(l.seen), l.rates.Len()) + } + if l.rates.Len() > len(l.seen) { + t.Fatalf("bucket without seen entry: seen %d buckets %d", len(l.seen), l.rates.Len()) + } +} diff --git a/internal/mcplogin/testdata/authorization_server.json b/internal/mcplogin/testdata/authorization_server.json new file mode 100644 index 000000000..0d7159f69 --- /dev/null +++ b/internal/mcplogin/testdata/authorization_server.json @@ -0,0 +1,19 @@ +{ + "authorization_endpoint": "http://127.0.0.1:8080/oauth/authorize", + "code_challenge_methods_supported": [ + "S256" + ], + "grant_types_supported": [ + "authorization_code", + "refresh_token" + ], + "issuer": "http://127.0.0.1:8080", + "registration_endpoint": "http://127.0.0.1:8080/oauth/register", + "response_types_supported": [ + "code" + ], + "token_endpoint": "http://127.0.0.1:8080/oauth/token", + "token_endpoint_auth_methods_supported": [ + "none" + ] +} diff --git a/internal/mcplogin/testdata/protected_resource_client.json b/internal/mcplogin/testdata/protected_resource_client.json new file mode 100644 index 000000000..85aa69f6f --- /dev/null +++ b/internal/mcplogin/testdata/protected_resource_client.json @@ -0,0 +1,9 @@ +{ + "authorization_servers": [ + "http://127.0.0.1:8080" + ], + "bearer_methods_supported": [ + "header" + ], + "resource": "http://127.0.0.1:8080/mcp/oauth/cursor" +} diff --git a/internal/mcplogin/testdata/protected_resource_generic.json b/internal/mcplogin/testdata/protected_resource_generic.json new file mode 100644 index 000000000..c951da24d --- /dev/null +++ b/internal/mcplogin/testdata/protected_resource_generic.json @@ -0,0 +1,9 @@ +{ + "authorization_servers": [ + "http://127.0.0.1:8080" + ], + "bearer_methods_supported": [ + "header" + ], + "resource": "http://127.0.0.1:8080/mcp/oauth" +} diff --git a/internal/mcplogin/token.go b/internal/mcplogin/token.go new file mode 100644 index 000000000..dca8dbbc3 --- /dev/null +++ b/internal/mcplogin/token.go @@ -0,0 +1,200 @@ +package mcplogin + +import ( + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/base64" + "encoding/hex" + "errors" + "strings" +) + +const ( + // AccessTokenPrefix starts every browser-login access token. + AccessTokenPrefix = "mcp_oat_" + // RefreshTokenPrefix starts every browser-login refresh token. + RefreshTokenPrefix = "mcp_ort_" + + // GrantIDLen is the length of a grant id (base62 characters). + GrantIDLen = 22 + + secretLen = 43 // 32 random bytes, base64url without padding + macLen = 22 // 16 bytes, base64url without padding + macBytes = 16 + prefixShow = 12 + + base62Alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" +) + +// Hash kinds for HashSecret. Each has its own label, so a hash made for one +// kind can never equal a hash made for another. +const ( + // KindAccess labels hashes of access tokens. + KindAccess = "access" + // KindRefresh labels hashes of refresh-token secrets. + KindRefresh = "refresh" + // KindCode labels hashes of authorization codes. + KindCode = "code" +) + +// ErrBadKey is returned when a token key is empty. +var ErrBadKey = errors.New("mcplogin: token key is empty") + +// ErrBadGrantID is returned when a grant id is not GrantIDLen base62 characters. +var ErrBadGrantID = errors.New("mcplogin: malformed grant id") + +// randomBytes reads n bytes from crypto/rand. +func randomBytes(n int) ([]byte, error) { + b := make([]byte, n) + if _, err := rand.Read(b); err != nil { + return nil, err + } + return b, nil +} + +// randomBase62 returns n unbiased random base62 characters. Bytes at or above +// 248 (the largest multiple of 62 that fits in a byte) are rejected. +func randomBase62(n int) (string, error) { + out := make([]byte, 0, n) + buf := make([]byte, n+n/2+8) + for len(out) < n { + if _, err := rand.Read(buf); err != nil { + return "", err + } + for _, c := range buf { + if c >= 248 { + continue + } + out = append(out, base62Alphabet[int(c)%62]) + if len(out) == n { + break + } + } + } + return string(out), nil +} + +func randomSecret() (string, error) { + b, err := randomBytes(32) + if err != nil { + return "", err + } + return base64.RawURLEncoding.EncodeToString(b), nil +} + +// NewAccessToken returns a fresh access token: "mcp_oat_" plus 43 base64url +// characters (32 random bytes). +func NewAccessToken() (string, error) { + s, err := randomSecret() + if err != nil { + return "", err + } + return AccessTokenPrefix + s, nil +} + +// NewGrantID returns a fresh grant id of GrantIDLen base62 characters. +func NewGrantID() (string, error) { return randomBase62(GrantIDLen) } + +func validBase62(s string, n int) bool { + if len(s) != n { + return false + } + for i := 0; i < len(s); i++ { + if strings.IndexByte(base62Alphabet, s[i]) < 0 { + return false + } + } + return true +} + +func validBase64URL(s string, n int) bool { + if len(s) != n { + return false + } + for i := 0; i < len(s); i++ { + c := s[i] + switch { + case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9', c == '-', c == '_': + default: + return false + } + } + return true +} + +func refreshMAC(key []byte, grantID, secret string) string { + m := hmac.New(sha256.New, key) + m.Write([]byte("mcplogin|ort|v1|" + grantID + "|" + secret)) + return base64.RawURLEncoding.EncodeToString(m.Sum(nil)[:macBytes]) +} + +// NewRefreshToken issues "mcp_ort___" for a grant. It +// returns the whole token and the secret part, which the caller stores hashed. +func NewRefreshToken(key []byte, grantID string) (token, secret string, err error) { + if len(key) == 0 { + return "", "", ErrBadKey + } + if !validBase62(grantID, GrantIDLen) { + return "", "", ErrBadGrantID + } + secret, err = randomSecret() + if err != nil { + return "", "", err + } + return RefreshTokenPrefix + grantID + "_" + secret + "_" + refreshMAC(key, grantID, secret), secret, nil +} + +// ParseRefreshToken splits a refresh token by fixed field lengths (the secret +// and the MAC may themselves contain '_') and verifies the MAC in constant +// time. ok is false for every malformed token and for a bad MAC, with nothing +// to tell the two apart. +func ParseRefreshToken(key []byte, token string) (grantID, secret string, ok bool) { + if len(key) == 0 || !strings.HasPrefix(token, RefreshTokenPrefix) { + return "", "", false + } + rest := token[len(RefreshTokenPrefix):] + if len(rest) != GrantIDLen+1+secretLen+1+macLen { + return "", "", false + } + grantID = rest[:GrantIDLen] + secret = rest[GrantIDLen+1 : GrantIDLen+1+secretLen] + mac := rest[GrantIDLen+1+secretLen+1:] + if rest[GrantIDLen] != '_' || rest[GrantIDLen+1+secretLen] != '_' || + !validBase62(grantID, GrantIDLen) || !validBase64URL(secret, secretLen) || !validBase64URL(mac, macLen) { + return "", "", false + } + if !hmac.Equal([]byte(mac), []byte(refreshMAC(key, grantID, secret))) { + return "", "", false + } + return grantID, secret, true +} + +// HashSecret returns the hex HMAC-SHA256 of secret under key, labelled by +// kind (KindAccess, KindRefresh, KindCode), so hashes of different kinds, and +// agent-token hashes, never collide. +func HashSecret(key []byte, kind, secret string) string { + m := hmac.New(sha256.New, key) + m.Write([]byte("mcplogin|hash|v1|" + kind + "|" + secret)) + return hex.EncodeToString(m.Sum(nil)) +} + +// SecretEqual compares two strings in constant time. +func SecretEqual(a, b string) bool { + return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1 +} + +// DisplayPrefix returns the first 12 characters of a token, safe to show. +func DisplayPrefix(token string) string { + if len(token) <= prefixShow { + return token + } + return token[:prefixShow] +} + +// IsAccessToken reports whether s carries the access-token prefix. +func IsAccessToken(s string) bool { return strings.HasPrefix(s, AccessTokenPrefix) } + +// IsRefreshToken reports whether s carries the refresh-token prefix. +func IsRefreshToken(s string) bool { return strings.HasPrefix(s, RefreshTokenPrefix) } diff --git a/internal/mcplogin/token_test.go b/internal/mcplogin/token_test.go new file mode 100644 index 000000000..ce7f81cd2 --- /dev/null +++ b/internal/mcplogin/token_test.go @@ -0,0 +1,131 @@ +package mcplogin + +import ( + "strings" + "testing" +) + +var testKey = []byte("0123456789abcdef0123456789abcdef") + +func TestAccessToken(t *testing.T) { + a, err := NewAccessToken() + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(a, AccessTokenPrefix) || len(a) != len(AccessTokenPrefix)+43 { + t.Fatalf("bad access token %q", a) + } + if !IsAccessToken(a) || IsRefreshToken(a) { + t.Fatal("prefix checks wrong") + } + b, _ := NewAccessToken() + if a == b { + t.Fatal("tokens must differ") + } +} + +func TestGrantID(t *testing.T) { + g, err := NewGrantID() + if err != nil || len(g) != 22 { + t.Fatalf("grant id %q %v", g, err) + } + for _, c := range g { + if !strings.ContainsRune(base62Alphabet, c) { + t.Fatalf("non base62 %q", g) + } + } +} + +func TestRefreshTokenRoundTrip(t *testing.T) { + g, _ := NewGrantID() + tok, secret, err := NewRefreshToken(testKey, g) + if err != nil { + t.Fatal(err) + } + if !IsRefreshToken(tok) || IsAccessToken(tok) { + t.Fatal("prefix checks wrong") + } + if len(tok) != len(RefreshTokenPrefix)+22+1+43+1+22 { + t.Fatalf("length %d", len(tok)) + } + gid, sec, ok := ParseRefreshToken(testKey, tok) + if !ok || gid != g || sec != secret { + t.Fatalf("round trip failed: %v %q %q", ok, gid, sec) + } + tok2, secret2, _ := NewRefreshToken(testKey, g) + if tok2 == tok || secret2 == secret { + t.Fatal("two tokens of one grant must differ") + } +} + +func TestNewRefreshTokenRejectsBadGrantID(t *testing.T) { + if _, _, err := NewRefreshToken(testKey, "short"); err == nil { + t.Fatal("bad grant id accepted") + } + if _, _, err := NewRefreshToken(nil, strings.Repeat("a", 22)); err == nil { + t.Fatal("empty key accepted") + } +} + +func TestParseRefreshTokenRejects(t *testing.T) { + g, _ := NewGrantID() + tok, _, _ := NewRefreshToken(testKey, g) + other := []byte("ffffffffffffffffffffffffffffffff") + otherTok, _, _ := NewRefreshToken(other, g) + flip := func(s string, i int) string { + b := []byte(s) + if b[i] == 'A' { + b[i] = 'B' + } else { + b[i] = 'A' + } + return string(b) + } + p := len(RefreshTokenPrefix) + cases := map[string]string{ + "empty": "", + "wrong prefix": "mcp_oat_" + tok[p:], + "short": tok[:len(tok)-1], + "long": tok + "A", + "grant": flip(tok, p+3), + "secret": flip(tok, p+22+1+5), + "mac": flip(tok, len(tok)-3), + "other key": otherTok, + "no seps": strings.ReplaceAll(tok, "_", "-"), + } + for name, c := range cases { + if _, _, ok := ParseRefreshToken(testKey, c); ok { + t.Errorf("%s: accepted", name) + } + } + if _, _, ok := ParseRefreshToken(nil, tok); ok { + t.Error("nil key accepted") + } +} + +func TestHashSecretKinds(t *testing.T) { + s := "secret" + hs := map[string]bool{} + for _, k := range []string{"access", "refresh", "code"} { + h := HashSecret(testKey, k, s) + if len(h) != 64 || hs[h] { + t.Fatalf("kind %s: bad or colliding hash", k) + } + hs[h] = true + if h != HashSecret(testKey, k, s) { + t.Fatal("not deterministic") + } + } + if HashSecret(testKey, "access", s) == HashSecret(testKey, "access", s+"x") { + t.Fatal("collision") + } +} + +func TestSecretEqualAndPrefix(t *testing.T) { + if !SecretEqual("a", "a") || SecretEqual("a", "b") || SecretEqual("a", "ab") { + t.Fatal("SecretEqual wrong") + } + if DisplayPrefix("mcp_oat_abcdefgh") != "mcp_oat_abcd" || DisplayPrefix("abc") != "abc" { + t.Fatal("DisplayPrefix wrong") + } +}