diff --git a/cmd/generate-types/main.go b/cmd/generate-types/main.go index a1083fd19..d9c8f363f 100644 --- a/cmd/generate-types/main.go +++ b/cmd/generate-types/main.go @@ -923,6 +923,9 @@ export const ProfileChangeRotate = 'rotate' as const; export const ProfileChangeAnonymous = 'anonymous' as const; export const ProfileChangeIssue = 'issue' as const; export const ProfileChangeRevoke = 'revoke' as const; +export const ProfileChangeApprove = 'approve' as const; +export const ProfileChangeDeny = 'deny' as const; +export const ProfileChangeReplayRevoke = 'replay_revoke' as const; export type ProfileChangeKind = | typeof ProfileChangeCreate | typeof ProfileChangeUpdate @@ -936,7 +939,10 @@ export type ProfileChangeKind = | typeof ProfileChangeRotate | typeof ProfileChangeAnonymous | typeof ProfileChangeIssue - | typeof ProfileChangeRevoke; + | typeof ProfileChangeRevoke + | typeof ProfileChangeApprove + | typeof ProfileChangeDeny + | typeof ProfileChangeReplayRevoke; export const RotationFinalized = 'finalized' as const; export const RotationRolledBack = 'rolled_back' as const; diff --git a/frontend/src/types/contracts.ts b/frontend/src/types/contracts.ts index 3e6a44f99..aed26e6f9 100644 --- a/frontend/src/types/contracts.ts +++ b/frontend/src/types/contracts.ts @@ -868,6 +868,9 @@ export const ProfileChangeRotate = 'rotate' as const; export const ProfileChangeAnonymous = 'anonymous' as const; export const ProfileChangeIssue = 'issue' as const; export const ProfileChangeRevoke = 'revoke' as const; +export const ProfileChangeApprove = 'approve' as const; +export const ProfileChangeDeny = 'deny' as const; +export const ProfileChangeReplayRevoke = 'replay_revoke' as const; export type ProfileChangeKind = | typeof ProfileChangeCreate | typeof ProfileChangeUpdate @@ -881,7 +884,10 @@ export type ProfileChangeKind = | typeof ProfileChangeRotate | typeof ProfileChangeAnonymous | typeof ProfileChangeIssue - | typeof ProfileChangeRevoke; + | typeof ProfileChangeRevoke + | typeof ProfileChangeApprove + | typeof ProfileChangeDeny + | typeof ProfileChangeReplayRevoke; export const RotationFinalized = 'finalized' as const; export const RotationRolledBack = 'rolled_back' as const; diff --git a/internal/auth/agent_token.go b/internal/auth/agent_token.go index fd8614d44..9bb9b8f00 100644 --- a/internal/auth/agent_token.go +++ b/internal/auth/agent_token.go @@ -7,8 +7,6 @@ import ( "encoding/hex" "errors" "fmt" - "os" - "path/filepath" "regexp" "strconv" "strings" @@ -340,29 +338,96 @@ func (t *AgentToken) AuthContext() *AuthContext { if t == nil { return nil } - return &AuthContext{ - Type: AuthTypeAgent, + return ClientAuthContext(ClientIdentity{ AgentName: t.Name, + TokenKind: normalizeKind(t.Kind), + ClientID: t.ClientID, + ProfilePin: t.ProfilePin, + ProfileMode: t.ProfileMode, + CredentialKind: CredentialKindAgentToken, TokenPrefix: t.authenticatedPrefix(), TokenGeneration: t.MatchedGeneration, AllowedServers: t.AllowedServers, Permissions: t.Permissions, - ProfilePin: t.ProfilePin, - Email: t.OwnerEmail, - Provider: t.OwnerProvider, - Role: t.OwnerRole, - CredentialKind: CredentialKindAgentToken, - TokenKind: normalizeKind(t.Kind), - ClientID: t.ClientID, - ProfileMode: t.ProfileMode, - RateLimit: t.RateLimit.clone(), + RateLimit: t.RateLimit, // UserID carries the owning tenant (server edition). Without it an // agent-token request had no tenant identity at all, so its activity // could not be attributed or scoped. It does NOT confer the user tier: // Type stays AuthTypeAgent, so IsUser()/IsAdmin() remain false, and // every per-user surface must gate on IsUser() rather than on a // non-empty UserID. - UserID: t.UserID, + UserID: t.UserID, + Email: t.OwnerEmail, + Provider: t.OwnerProvider, + Role: t.OwnerRole, + }) +} + +// ClientIdentity is everything the one AuthContext builder needs. Both the +// stored-token path ((*AgentToken).AuthContext) and a browser login (Spec 132) +// fill it, so no path can silently drop a field. +type ClientIdentity struct { + // AgentName is the context's AgentName. Empty means ClientTokenName(ClientID) + // (what a client credential's record is named, so activity and filters match). + AgentName string + // TokenKind is KindAgent or KindClient. Empty means KindClient. + TokenKind string + // ClientID, ProfilePin and ProfileMode are the client binding. + ClientID, ProfilePin, ProfileMode string + // CredentialKind is the source credential (agent_token or oauth). + CredentialKind CredentialKind + // GrantID is the browser-login grant id (oauth only). + GrantID string + // TokenPrefix is the display prefix; TokenGeneration identifies the + // authenticated secret (a browser login uses its grant id). + TokenPrefix, TokenGeneration string + // AllowedServers and Permissions are the token's own scope. For a browser + // login (CredentialKindOAuth) nil means "*" and all three tiers: its + // reach comes from the client's profile binding only. + AllowedServers, Permissions []string + // RateLimit is the credential's own call budget (copied, never aliased). + RateLimit *TokenRateLimit + // UserID, Email, Provider and Role are the owning tenant (server edition). + UserID, Email, Provider, Role string +} + +// ClientAuthContext is the single builder of the agent-tier AuthContext. +func ClientAuthContext(id ClientIdentity) *AuthContext { + kind := id.TokenKind + if kind == "" { + kind = KindClient + } + name := id.AgentName + if name == "" && id.ClientID != "" { + name = ClientTokenName(id.ClientID) + } + servers, perms := id.AllowedServers, id.Permissions + if id.CredentialKind == CredentialKindOAuth { + if servers == nil { + servers = []string{"*"} + } + if perms == nil { + perms = []string{PermRead, PermWrite, PermDestructive} + } + } + return &AuthContext{ + Type: AuthTypeAgent, + AgentName: name, + TokenPrefix: id.TokenPrefix, + TokenGeneration: id.TokenGeneration, + AllowedServers: servers, + Permissions: perms, + ProfilePin: id.ProfilePin, + Email: id.Email, + Provider: id.Provider, + Role: id.Role, + CredentialKind: id.CredentialKind, + GrantID: id.GrantID, + TokenKind: kind, + ClientID: id.ClientID, + ProfileMode: id.ProfileMode, + RateLimit: id.RateLimit.clone(), + UserID: id.UserID, } } @@ -574,37 +639,6 @@ func TokenPrefix(token string) string { // hmacKeyFile is the filename for the persisted HMAC key. const hmacKeyFile = ".token_key" -// GetOrCreateHMACKey reads the HMAC key from /.token_key. -// If the file does not exist, it generates a 32-byte random key, -// writes it with 0600 permissions, and returns it. -func GetOrCreateHMACKey(dataDir string) ([]byte, error) { - keyPath := filepath.Join(dataDir, hmacKeyFile) - - // Try to read existing key - data, err := os.ReadFile(keyPath) - if err == nil && len(data) == 32 { - return data, nil - } - - // Generate new key - key := make([]byte, 32) - if _, err := rand.Read(key); err != nil { - return nil, fmt.Errorf("failed to generate HMAC key: %w", err) - } - - // Ensure directory exists - if err := os.MkdirAll(dataDir, 0700); err != nil { - return nil, fmt.Errorf("failed to create data directory: %w", err) - } - - // Write key file with restrictive permissions - if err := os.WriteFile(keyPath, key, 0600); err != nil { - return nil, fmt.Errorf("failed to write HMAC key file: %w", err) - } - - return key, nil -} - // ValidatePermissions checks that the given permissions list is valid. // It must contain "read" and only contain valid permission values. func ValidatePermissions(perms []string) error { diff --git a/internal/auth/client_auth_context_test.go b/internal/auth/client_auth_context_test.go new file mode 100644 index 000000000..ec8e24b39 --- /dev/null +++ b/internal/auth/client_auth_context_test.go @@ -0,0 +1,80 @@ +package auth + +import ( + "reflect" + "testing" + "time" +) + +// TestAgentTokenAuthContext_PinnedStructs pins EVERY field of the context a +// client credential and a regular agent token produce, so moving +// (*AgentToken).AuthContext onto ClientAuthContext (Spec 132 R3) cannot change +// what the mcp_cli_ and mcp_agt_ paths have always produced. +func TestAgentTokenAuthContext_PinnedStructs(t *testing.T) { + rl := &TokenRateLimit{PerMinute: 30, Burst: 5} + client := &AgentToken{ + Name: ClientTokenName("cursor"), TokenPrefix: "mcp_cli_old1", MatchedPrefix: "mcp_cli_new2", + MatchedGeneration: "gen-abc", AllowedServers: []string{"*"}, + Permissions: []string{PermRead, PermWrite, PermDestructive}, + Kind: KindClient, ClientID: "cursor", ProfilePin: "dev", ProfileMode: ProfileModeLocked, + RateLimit: rl, ExpiresAt: time.Now().Add(time.Hour), + } + want := &AuthContext{ + Type: AuthTypeAgent, AgentName: "client-cursor", TokenPrefix: "mcp_cli_new2", TokenGeneration: "gen-abc", + AllowedServers: []string{"*"}, Permissions: []string{PermRead, PermWrite, PermDestructive}, + ProfilePin: "dev", TokenKind: KindClient, ClientID: "cursor", ProfileMode: ProfileModeLocked, + RateLimit: &TokenRateLimit{PerMinute: 30, Burst: 5}, CredentialKind: CredentialKindAgentToken, + } + if got := client.AuthContext(); !reflect.DeepEqual(got, want) { + t.Fatalf("client credential context drifted:\n got %+v\nwant %+v", got, want) + } + + regular := &AgentToken{ + Name: "ci", TokenPrefix: "mcp_agt_abcd", AllowedServers: []string{"srv"}, Permissions: []string{PermRead}, + ProfilePin: "p", UserID: "u1", OwnerEmail: "a@b.c", OwnerProvider: "github", OwnerRole: "user", + } + wantReg := &AuthContext{ + Type: AuthTypeAgent, AgentName: "ci", TokenPrefix: "mcp_agt_abcd", AllowedServers: []string{"srv"}, + Permissions: []string{PermRead}, ProfilePin: "p", Email: "a@b.c", Provider: "github", Role: "user", + UserID: "u1", TokenKind: KindAgent, CredentialKind: CredentialKindAgentToken, + } + if got := regular.AuthContext(); !reflect.DeepEqual(got, wantReg) { + t.Fatalf("agent token context drifted:\n got %+v\nwant %+v", got, wantReg) + } + if got := client.AuthContext(); got.RateLimit == rl { + t.Fatal("the context must not alias the record's rate limit") + } +} + +// TestClientAuthContext_BrowserLogin: a browser login is the same caller a +// client credential is, apart from kind, grant id, prefix and generation. +func TestClientAuthContext_BrowserLogin(t *testing.T) { + ac := ClientAuthContext(ClientIdentity{ + ClientID: "cursor", ProfilePin: "dev", ProfileMode: ProfileModeSwitchable, + CredentialKind: CredentialKindOAuth, GrantID: "G1", TokenPrefix: "mcp_oat_abcd", TokenGeneration: "G1", + }) + want := &AuthContext{ + Type: AuthTypeAgent, AgentName: "client-cursor", TokenPrefix: "mcp_oat_abcd", TokenGeneration: "G1", + AllowedServers: []string{"*"}, Permissions: []string{PermRead, PermWrite, PermDestructive}, + ProfilePin: "dev", TokenKind: KindClient, ClientID: "cursor", ProfileMode: ProfileModeSwitchable, + CredentialKind: CredentialKindOAuth, GrantID: "G1", + } + if !reflect.DeepEqual(ac, want) { + t.Fatalf("browser-login context:\n got %+v\nwant %+v", ac, want) + } + if !ac.IsClientCredential() || ac.IsAdmin() || ac.IsUser() { + t.Fatal("a browser login is a client credential and nothing more") + } +} + +func TestCredentialKind_IsScopedClientCredential(t *testing.T) { + for k, want := range map[CredentialKind]bool{ + CredentialKindAgentToken: true, CredentialKindOAuth: true, CredentialKindAPIKey: false, + CredentialKindSocket: false, CredentialKindCookie: false, CredentialKindBearerJWT: false, + CredentialKindAnonymous: false, "": false, + } { + if got := k.IsScopedClientCredential(); got != want { + t.Errorf("%q.IsScopedClientCredential() = %v, want %v", k, got, want) + } + } +} diff --git a/internal/auth/context.go b/internal/auth/context.go index 63ee01bb5..86dfbdcd5 100644 --- a/internal/auth/context.go +++ b/internal/auth/context.go @@ -26,10 +26,21 @@ const ( CredentialKindAPIKey CredentialKind = "api_key" // the global API key (header, bearer or ?apikey=) CredentialKindBearerJWT CredentialKind = "bearer_jwt" // a user JWT minted by POST /auth/token CredentialKindAgentToken CredentialKind = "agent_token" // an mcp_agt_ agent token + CredentialKindOAuth CredentialKind = "oauth" // an mcp_oat_ browser-login access token (Spec 132) CredentialKindCookie CredentialKind = "cookie" // the mcpproxy_session cookie CredentialKindAnonymous CredentialKind = "anonymous" // no credential (require_mcp_auth: false back-compat) ) +// IsScopedClientCredential reports whether the kind is a credential scoped by +// an agent-token style binding: an mcp_agt_/mcp_cli_ token or a browser-login +// access token. Every "scoped caller, not an administrator" decision that +// would compare against CredentialKindAgentToken goes through it, so a browser +// login is treated exactly like the same client's mcp_cli_ credential (Spec 132 +// R3). +func (k CredentialKind) IsScopedClientCredential() bool { + return k == CredentialKindAgentToken || k == CredentialKindOAuth +} + // AuthContext carries authentication identity through request context. type AuthContext struct { Type string // "admin", "agent", "user", or "admin_user" @@ -39,9 +50,13 @@ type AuthContext struct { // its hash). Internal: it keys a work session on the credential's // generation (Spec 124 FR-009) and is never returned or logged. TokenGeneration string - AllowedServers []string // Servers this token can access (nil = all for admin) - Permissions []string // Permission tiers (nil = all for admin) - ProfilePin string // Profile this agent token is pinned to (Profiles v2 T3; empty if unpinned) + // GrantID is the browser-login grant that authenticated this request + // (Spec 132; empty for every other credential). Activity rows carry it so + // two logins of one client can be told apart. + GrantID string + AllowedServers []string // Servers this token can access (nil = all for admin) + Permissions []string // Permission tiers (nil = all for admin) + ProfilePin string // Profile this agent token is pinned to (Profiles v2 T3; empty if unpinned) // TokenKind, ClientID and ProfileMode are the Spec 108-c client- // credential identity, copied from AgentToken at authentication diff --git a/internal/auth/credential_kind_sites_test.go b/internal/auth/credential_kind_sites_test.go new file mode 100644 index 000000000..699003f1d --- /dev/null +++ b/internal/auth/credential_kind_sites_test.go @@ -0,0 +1,100 @@ +package auth + +import ( + "go/ast" + "go/parser" + "go/token" + "io/fs" + "path/filepath" + "sort" + "strings" + "testing" +) + +// credentialKindAgentTokenSites classifies every use of CredentialKindAgentToken +// in non-test Go code under internal/ and cmd/ (Spec 132 R3, T025). A browser +// login carries CredentialKindOAuth, so any code that asked "is this the agent +// token kind?" to mean "scoped caller" would silently treat a login as +// something else. Each site is therefore either: +// +// - also_oauth: the decision must also hold for CredentialKindOAuth. The code +// goes through CredentialKind.IsScopedClientCredential (or an equivalent +// that includes oauth) instead of comparing with the constant. +// - api_key_only: the site is specific to a stored mcp_agt_/mcp_cli_ token. +// +// Key: "#". +var credentialKindAgentTokenSites = map[string]struct{ class, reason string }{ + "internal/auth/context.go#IsScopedClientCredential": {"also_oauth", + "the helper every scoped-caller decision goes through; it matches agent_token AND oauth"}, + "internal/auth/agent_token.go#AuthContext": {"api_key_only", + "builds the context of a STORED token; a browser login is built by ClientAuthContext with CredentialKindOAuth"}, + "internal/runtime/clients_service.go#ActorFromContext": {"api_key_only", + "fallback label for a REST context that never stamped a credential kind; the browser-login context always stamps oauth, so this branch is unreachable for it"}, +} + +func TestCredentialKindAgentTokenSitesClassified(t *testing.T) { + root, err := filepath.Abs("../..") + if err != nil { + t.Fatal(err) + } + found := map[string]bool{} + fset := token.NewFileSet() + for _, top := range []string{"internal", "cmd"} { + _ = filepath.WalkDir(filepath.Join(root, top), func(path string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") { + return nil + } + file, perr := parser.ParseFile(fset, path, nil, 0) + if perr != nil { + t.Errorf("parse %s: %v", path, perr) + return nil + } + rel, _ := filepath.Rel(root, path) + rel = filepath.ToSlash(rel) + for _, decl := range file.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + ast.Inspect(fn.Body, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.SelectorExpr: + if x.Sel.Name == "CredentialKindAgentToken" { + found[rel+"#"+fn.Name.Name] = true + } + case *ast.Ident: + if x.Name == "CredentialKindAgentToken" { + found[rel+"#"+fn.Name.Name] = true + } + } + return true + }) + } + return nil + }) + } + + var keys []string + for k := range found { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + entry, ok := credentialKindAgentTokenSites[k] + if !ok { + t.Errorf("unclassified use of CredentialKindAgentToken at %s: classify it in credentialKindAgentTokenSites as also_oauth or api_key_only", k) + continue + } + if entry.class != "also_oauth" && entry.class != "api_key_only" { + t.Errorf("%s: class %q must be also_oauth or api_key_only", k, entry.class) + } + if strings.TrimSpace(entry.reason) == "" { + t.Errorf("%s: a classification needs a one-line reason", k) + } + } + for k := range credentialKindAgentTokenSites { + if !found[k] { + t.Errorf("stale entry %s: the site no longer uses CredentialKindAgentToken", k) + } + } +} diff --git a/internal/auth/hmac_key.go b/internal/auth/hmac_key.go new file mode 100644 index 000000000..92d8d173c --- /dev/null +++ b/internal/auth/hmac_key.go @@ -0,0 +1,104 @@ +package auth + +import ( + "crypto/rand" + "errors" + "fmt" + "os" + "path/filepath" + "sync" +) + +// hmacKeyMu serialises in-process creators. Disk exclusivity (below) covers +// other processes and every caller that bypasses this package-level lock. +var hmacKeyMu sync.Mutex + +// linkFile publishes the temp file without replacing a target; a variable so a +// test can simulate a filesystem without hard links. +var linkFile = os.Link + +// readValidHMACKey returns the key at path when it is a 32-byte file. +func readValidHMACKey(path string) ([]byte, bool) { + data, err := os.ReadFile(path) + if err == nil && len(data) == 32 { + return data, true + } + return nil, false +} + +// GetOrCreateHMACKey reads the HMAC key from /.token_key. +// If the file does not exist, it generates a 32-byte random key, +// writes it with 0600 permissions, and returns it. +// +// Creation is atomic for every caller: in-process callers are serialised by a +// package-level mutex, and the key reaches the final name only through a hard +// link (or, where links are unsupported, an atomic rename) of a fully written +// 0600 temporary file in the same directory, so a crash never leaves a partial +// key and two first-time callers can never each generate a key and overwrite +// the other's. A caller that loses the race returns the winner's key; after any +// write the on-disk bytes are re-read and returned. A file of the wrong size +// (empty included) is replaced, as it always was. +// +// Single-process assumption: replacing an INVALID file is not guarded across +// processes. That is safe because one data dir has one core process (the bbolt +// lock on config.db, exit code 3) and every caller runs only after its process +// holds that lock. +func GetOrCreateHMACKey(dataDir string) ([]byte, error) { + keyPath := filepath.Join(dataDir, hmacKeyFile) + + hmacKeyMu.Lock() + defer hmacKeyMu.Unlock() + + // Try to read existing key + if key, ok := readValidHMACKey(keyPath); ok { + return key, nil + } + + // Generate new key + key := make([]byte, 32) + if _, err := rand.Read(key); err != nil { + return nil, fmt.Errorf("failed to generate HMAC key: %w", err) + } + + // Ensure directory exists + if err := os.MkdirAll(dataDir, 0700); err != nil { + return nil, fmt.Errorf("failed to create data directory: %w", err) + } + + tmp, err := os.CreateTemp(dataDir, ".token_key.tmp-*") // created 0600 + if err != nil { + return nil, fmt.Errorf("failed to write HMAC key file: %w", err) + } + tmpPath := tmp.Name() + defer func() { _ = os.Remove(tmpPath) }() + if err := tmp.Chmod(0600); err != nil { + _ = tmp.Close() + return nil, fmt.Errorf("failed to write HMAC key file: %w", err) + } + if _, err := tmp.Write(key); err != nil { + _ = tmp.Close() + return nil, fmt.Errorf("failed to write HMAC key file: %w", err) + } + if err := tmp.Close(); err != nil { + return nil, fmt.Errorf("failed to write HMAC key file: %w", err) + } + + // Publish the complete temp file. A hard link never replaces an existing + // target; when it fails (the target exists, or the filesystem has no hard + // links) a valid existing key wins, and otherwise the complete temp file is + // renamed into place, which is atomic and works on every filesystem and also + // recovers an empty or wrong-size target. + if err := linkFile(tmpPath, keyPath); err != nil { + if existing, ok := readValidHMACKey(keyPath); ok { + return existing, nil + } + if err := os.Rename(tmpPath, keyPath); err != nil { + return nil, fmt.Errorf("failed to write HMAC key file: %w", err) + } + } + // Whatever happened above, return what is on disk now. + if onDisk, ok := readValidHMACKey(keyPath); ok { + return onDisk, nil + } + return nil, errors.New("failed to write HMAC key file: the key file is unreadable after writing") +} diff --git a/internal/auth/hmac_key_atomic_test.go b/internal/auth/hmac_key_atomic_test.go new file mode 100644 index 000000000..499fbcdad --- /dev/null +++ b/internal/auth/hmac_key_atomic_test.go @@ -0,0 +1,85 @@ +package auth + +import ( + "bytes" + "os" + "path/filepath" + "runtime" + "sync" + "testing" +) + +// Two first-time callers must never end up with different keys: every caller of +// GetOrCreateHMACKey on an empty directory gets the one key the file holds. +func TestGetOrCreateHMACKey_ConcurrentFirstCallersAgree(t *testing.T) { + dir := t.TempDir() + const n = 32 + keys := make([][]byte, n) + errs := make([]error, n) + var wg sync.WaitGroup + start := make(chan struct{}) + for i := 0; i < n; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + <-start + keys[i], errs[i] = GetOrCreateHMACKey(dir) + }(i) + } + close(start) + wg.Wait() + + onDisk, err := os.ReadFile(filepath.Join(dir, hmacKeyFile)) + if err != nil || len(onDisk) != 32 { + t.Fatalf("key file: %v len=%d", err, len(onDisk)) + } + for i := range keys { + if errs[i] != nil { + t.Fatalf("caller %d: %v", i, errs[i]) + } + if !bytes.Equal(keys[i], onDisk) { + t.Fatalf("caller %d got a key that is not the one on disk", i) + } + } + info, _ := os.Stat(filepath.Join(dir, hmacKeyFile)) + // Windows reports 0666 for any writable file; the mode bits mean nothing there. + if runtime.GOOS != "windows" && info.Mode().Perm() != 0o600 { + t.Fatalf("permissions %v", info.Mode().Perm()) + } + entries, _ := os.ReadDir(dir) + if len(entries) != 1 { + t.Fatalf("temporary files were left behind: %v", entries) + } +} + +func TestGetOrCreateHMACKey_ExistingKeyIsReturnedUnchanged(t *testing.T) { + dir := t.TempDir() + want := bytes.Repeat([]byte{7}, 32) + if err := os.WriteFile(filepath.Join(dir, hmacKeyFile), want, 0o600); err != nil { + t.Fatal(err) + } + got, err := GetOrCreateHMACKey(dir) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("got %x err %v", got, err) + } + onDisk, _ := os.ReadFile(filepath.Join(dir, hmacKeyFile)) + if !bytes.Equal(onDisk, want) { + t.Fatal("an existing key file was rewritten") + } +} + +// A file of the wrong size is replaced, as it always was. +func TestGetOrCreateHMACKey_WrongSizeFileIsReplaced(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, hmacKeyFile), []byte("short"), 0o600); err != nil { + t.Fatal(err) + } + got, err := GetOrCreateHMACKey(dir) + if err != nil || len(got) != 32 { + t.Fatalf("got %d bytes, err %v", len(got), err) + } + onDisk, _ := os.ReadFile(filepath.Join(dir, hmacKeyFile)) + if !bytes.Equal(onDisk, got) { + t.Fatal("the replacement is not on disk") + } +} diff --git a/internal/auth/hmac_key_fallback_test.go b/internal/auth/hmac_key_fallback_test.go new file mode 100644 index 000000000..c1533a227 --- /dev/null +++ b/internal/auth/hmac_key_fallback_test.go @@ -0,0 +1,68 @@ +package auth + +import ( + "bytes" + "errors" + "os" + "path/filepath" + "runtime" + "testing" +) + +func noLinks(t *testing.T) { + t.Helper() + orig := linkFile + linkFile = func(string, string) error { return errors.New("hard links are not supported") } + t.Cleanup(func() { linkFile = orig }) +} + +// Without hard links the fallback publishes the COMPLETE temp file by rename: the +// key file is never visible empty, and the bytes on disk are what is returned. +func TestGetOrCreateHMACKey_NoHardLinkFallbackPublishesACompleteFile(t *testing.T) { + noLinks(t) + dir := t.TempDir() + got, err := GetOrCreateHMACKey(dir) + if err != nil || len(got) != 32 { + t.Fatalf("got %d bytes err %v", len(got), err) + } + onDisk, _ := os.ReadFile(filepath.Join(dir, hmacKeyFile)) + if !bytes.Equal(onDisk, got) { + t.Fatal("the returned key is not the one on disk") + } + info, _ := os.Stat(filepath.Join(dir, hmacKeyFile)) + // Windows reports 0666 for any writable file; the mode bits mean nothing there. + if runtime.GOOS != "windows" && info.Mode().Perm() != 0o600 { + t.Fatalf("permissions %v", info.Mode().Perm()) + } + if entries, _ := os.ReadDir(dir); len(entries) != 1 { + t.Fatalf("temp files left behind: %v", entries) + } + // A second call reads the same key. + again, _ := GetOrCreateHMACKey(dir) + if !bytes.Equal(again, got) { + t.Fatal("second call returned another key") + } +} + +// An empty or wrong-size target is recovered on every filesystem. +func TestGetOrCreateHMACKey_EmptyTargetIsRecovered(t *testing.T) { + for name, withLinks := range map[string]bool{"links": true, "no links": false} { + t.Run(name, func(t *testing.T) { + if !withLinks { + noLinks(t) + } + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, hmacKeyFile), nil, 0o600); err != nil { + t.Fatal(err) + } + got, err := GetOrCreateHMACKey(dir) + if err != nil || len(got) != 32 { + t.Fatalf("got %d bytes err %v", len(got), err) + } + onDisk, _ := os.ReadFile(filepath.Join(dir, hmacKeyFile)) + if !bytes.Equal(onDisk, got) { + t.Fatal("not repaired on disk") + } + }) + } +} diff --git a/internal/httpapi/oauth_login_event_scope_test.go b/internal/httpapi/oauth_login_event_scope_test.go new file mode 100644 index 000000000..4f0f162b3 --- /dev/null +++ b/internal/httpapi/oauth_login_event_scope_test.go @@ -0,0 +1,30 @@ +package httpapi + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + internalRuntime "github.com/smart-mcp-proxy/mcpproxy-go/internal/runtime" +) + +// Spec 132: a sign-in request names a client and the label it reported, and +// its decision tells which request was approved. Only an administrator sees +// either; a scoped caller never does. +func TestSSE_OAuthLoginEventsAreAdminOnly(t *testing.T) { + scoped := auth.WithAuthContext(context.Background(), &auth.AuthContext{ + Type: auth.AuthTypeAgent, AgentName: "bot", AllowedServers: []string{"alpha"}, Permissions: []string{auth.PermRead}, + }) + admin := auth.WithAuthContext(context.Background(), &auth.AuthContext{Type: auth.AuthTypeAdmin}) + for _, evt := range []internalRuntime.Event{ + {Type: internalRuntime.EventTypeOAuthAuthorizationPending, + Payload: map[string]any{"request_id": "r1", "client_id": "cursor", "client_label": "Cursor IDE"}}, + {Type: internalRuntime.EventTypeOAuthAuthorizationDecided, + Payload: map[string]any{"request_id": "r1", "status": "approved"}}, + } { + require.False(t, eventVisibleToCaller(scoped, evt), "%s must be dropped for a scoped caller", evt.Type) + require.True(t, eventVisibleToCaller(admin, evt), "%s reaches an administrator", evt.Type) + } +} diff --git a/internal/httpapi/sse_scope.go b/internal/httpapi/sse_scope.go index 1ae1d9cf6..581b45e3e 100644 --- a/internal/httpapi/sse_scope.go +++ b/internal/httpapi/sse_scope.go @@ -178,6 +178,10 @@ var adminConfigEventTypes = map[internalRuntime.EventType]struct{}{ // A credential lifecycle invalidation names identities and their // profiles (Spec 115 FR-024): administrator-only, like the binding event. internalRuntime.EventTypeCredentialsChanged: {}, + // A browser sign-in request names a client and the label it reported + // (Spec 132): administrator-only, like the credential invalidation. + internalRuntime.EventTypeOAuthAuthorizationPending: {}, + internalRuntime.EventTypeOAuthAuthorizationDecided: {}, // A skills catalog change carries per-state counts of every skill of a // server, available or not (Spec 125 FR-019a): until agents are offered // skills it is an administrator-only invalidation. diff --git a/internal/httpapi/sse_scope_reveal_test.go b/internal/httpapi/sse_scope_reveal_test.go index 734310fa5..2eed30c5b 100644 --- a/internal/httpapi/sse_scope_reveal_test.go +++ b/internal/httpapi/sse_scope_reveal_test.go @@ -598,6 +598,8 @@ func TestSSE_EveryRuntimeEventTypeIsClassified(t *testing.T) { "client.binding_changed": "administrator-only client -> profile binding change (Spec 108 FR-026); dropped for scoped callers", "profiles.changed": "administrator-only profile change invalidation (Spec 108-f FR-038): names profiles a scoped caller may not reach; dropped for scoped callers", "credentials.changed": "administrator-only credential lifecycle invalidation (Spec 115 FR-024): names identities and profiles; dropped for scoped callers", + "oauth.authorization_pending": "administrator-only browser-login request (Spec 132): names a client and its sanitised label; dropped for scoped callers", + "oauth.authorization_decided": "administrator-only browser-login decision (Spec 132): request id and status; dropped for scoped callers", "skills.changed": "administrator-only skills catalog invalidation (Spec 125 FR-019a): carries per-state skill counts; dropped for scoped callers", "activity.skill_quarantine_change": "administrator-only skill approval row (Spec 125 FR-019a): names skills that may be unapproved, even on a visible server; dropped for scoped callers", "activity.skill_access": "administrator-only skill access row (Spec 125 FR-019a): names the id its caller asked for, which may be a held skill on a visible server; dropped for scoped callers", diff --git a/internal/mcplogin/cancel_report.go b/internal/mcplogin/cancel_report.go new file mode 100644 index 000000000..7619d5328 --- /dev/null +++ b/internal/mcplogin/cancel_report.go @@ -0,0 +1,19 @@ +package mcplogin + +import "sort" + +// CancelAllReport cancels every pending and approved-but-unconsumed request in +// ONE critical section and returns the ids of the requests that were still +// pending, so a caller can announce them without a race between listing and +// cancelling. +func (s *Store) CancelAllReport() (pendingIDs []string, cancelled int) { + s.mu.Lock() + defer s.mu.Unlock() + for id := range s.reqs { + if r := s.live(id); r != nil && r.Status == StatusPending { + pendingIDs = append(pendingIDs, id) + } + } + sort.Strings(pendingIDs) + return pendingIDs, s.cancelWhere(func(*Request) bool { return true }) +} diff --git a/internal/mcplogin/origin_test.go b/internal/mcplogin/origin_test.go new file mode 100644 index 000000000..b93bd8c4b --- /dev/null +++ b/internal/mcplogin/origin_test.go @@ -0,0 +1,46 @@ +package mcplogin + +import ( + "errors" + "testing" +) + +// The issuer rides on the code for its whole life: a replay on another origin +// is refused before replay handling (no grant id comes back to revoke). +func TestConsumeAt_OriginIsCheckedBeforeConsumptionAndReplay(t *testing.T) { + s, _ := newTestStore() + r := mustCreate(t, s, "cursor") + code, err := s.Approve(r.ID, Decision{ClientID: "cursor"}) + if err != nil { + t.Fatal(err) + } + if _, _, err := s.ConsumeAt(code, "http://localhost:8080", func(Request) (string, error) { return "g", nil }); !errors.Is(err, ErrCodeOriginMismatch) { + t.Fatalf("wrong origin on a live code: %v", err) + } + if _, g, err := s.ConsumeAt(code, r.Issuer, func(Request) (string, error) { return "g1", nil }); err != nil || g != "g1" { + t.Fatalf("the code is still usable on its own origin: %v %q", err, g) + } + // Replay: the right origin reports the grant, another origin learns nothing. + if _, g, err := s.ConsumeAt(code, "http://localhost:8080", nil); !errors.Is(err, ErrCodeOriginMismatch) || g != "" { + t.Fatalf("replay on another origin: %v %q", err, g) + } + if _, g, err := s.ConsumeAt(code, r.Issuer, nil); !errors.Is(err, ErrCodeReused) || g != "g1" { + t.Fatalf("replay on the same origin: %v %q", err, g) + } +} + +func TestCancelAllReport(t *testing.T) { + s, _ := newTestStore() + a := mustCreate(t, s, "") + b := mustCreate(t, s, "") + if _, err := s.Approve(b.ID, Decision{ClientID: "c"}); err != nil { + t.Fatal(err) + } + ids, n := s.CancelAllReport() + if n != 2 || len(ids) != 1 || ids[0] != a.ID { + t.Fatalf("ids=%v n=%d", ids, n) + } + if ids, n = s.CancelAllReport(); n != 0 || len(ids) != 0 { + t.Fatal("second call finds nothing") + } +} diff --git a/internal/mcplogin/peek.go b/internal/mcplogin/peek.go new file mode 100644 index 000000000..cfe171842 --- /dev/null +++ b/internal/mcplogin/peek.go @@ -0,0 +1,22 @@ +package mcplogin + +// PeekCode returns a copy of the request an unconsumed, unexpired code belongs +// to, while that request is still approved. It consumes nothing and changes +// nothing: the token endpoint uses it to compare the request's origin with the +// stored issuer BEFORE the code's single use is spent (a mismatch must leave +// the code usable). ok is false for an unknown, expired, consumed or cancelled +// code, with nothing to tell the cases apart. +func (s *Store) PeekCode(code string) (Request, bool) { + h := HashSecret(s.key, KindCode, code) + s.mu.Lock() + defer s.mu.Unlock() + e := s.codes[h] + if e == nil || e.consumed || !s.now().Before(e.expiresAt) { + return Request{}, false + } + r := s.live(e.requestID) + if r == nil || r.Status != StatusApproved { + return Request{}, false + } + return *r, true +} diff --git a/internal/mcplogin/peek_test.go b/internal/mcplogin/peek_test.go new file mode 100644 index 000000000..9099fd6d2 --- /dev/null +++ b/internal/mcplogin/peek_test.go @@ -0,0 +1,44 @@ +package mcplogin + +import "testing" + +// PeekCode lets the token endpoint compare the request's origin with the +// stored issuer BEFORE the single-use code is consumed (Spec 132): a mismatch +// must leave the code usable. +func TestPeekCode(t *testing.T) { + s, clk := newTestStore() + r := mustCreate(t, s, "cursor") + code, err := s.Approve(r.ID, Decision{ClientID: "cursor"}) + if err != nil { + t.Fatal(err) + } + + got, ok := s.PeekCode(code) + if !ok || got.ID != r.ID || got.Issuer != r.Issuer || got.Status != StatusApproved { + t.Fatalf("peek of a live code: %+v ok=%v", got, ok) + } + if _, ok := s.PeekCode("nope"); ok { + t.Fatal("an unknown code must not peek") + } + // Peeking consumes nothing. + if _, _, err := s.Consume(code, func(Request) (string, error) { return "g1", nil }); err != nil { + t.Fatalf("consume after peek: %v", err) + } + if _, ok := s.PeekCode(code); ok { + t.Fatal("a consumed code must not peek") + } + + r2 := mustCreate(t, s, "") + code2, _ := s.Approve(r2.ID, Decision{ClientID: "c"}) + clk.advance(CodeLifetime) + if _, ok := s.PeekCode(code2); ok { + t.Fatal("an expired code must not peek") + } + + r3 := mustCreate(t, s, "") + code3, _ := s.Approve(r3.ID, Decision{ClientID: "c"}) + s.CancelAll() + if _, ok := s.PeekCode(code3); ok { + t.Fatal("a cancelled request's code must not peek") + } +} diff --git a/internal/mcplogin/requests.go b/internal/mcplogin/requests.go index 5c4768035..2fe687ff1 100644 --- a/internal/mcplogin/requests.go +++ b/internal/mcplogin/requests.go @@ -31,6 +31,9 @@ var ( // 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") + // ErrCodeOriginMismatch means the code was presented on another origin than + // the one it was issued for. Nothing is consumed and nothing is revoked. + ErrCodeOriginMismatch = errors.New("mcplogin: authorization code presented on another origin") ) // Status is the state of an authorization request. @@ -99,6 +102,10 @@ type codeEntry struct { consumed bool consumedAt time.Time grantID string // empty when the commit failed + // issuer is the origin the request was made on. It stays on the entry (and + // so on the tombstone) for its whole life, so a replay on another origin is + // refused before replay handling. + issuer string } // Store holds authorization requests and their codes. It is safe for @@ -223,7 +230,7 @@ func (s *Store) Approve(id string, d Decision) (string, error) { // 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)} + s.codes[HashSecret(s.key, KindCode, code)] = &codeEntry{requestID: id, expiresAt: now.Add(CodeLifetime), issuer: r.Issuer} return code, nil } @@ -284,6 +291,18 @@ func (s *Store) CancelAll() int { // 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) { + return s.consume(code, "", false, commit) +} + +// ConsumeAt is Consume that first requires the code to have been issued for +// origin. The comparison happens inside the store, BEFORE consumption and +// BEFORE replay handling, and also for an already consumed code: a mismatch is +// ErrCodeOriginMismatch with nothing consumed and no grant id returned. +func (s *Store) ConsumeAt(code, origin string, commit func(Request) (grantID string, err error)) (Request, string, error) { + return s.consume(code, origin, true, commit) +} + +func (s *Store) consume(code, origin string, checkOrigin bool, commit func(Request) (string, error)) (Request, string, error) { h := HashSecret(s.key, KindCode, code) s.mu.Lock() defer s.mu.Unlock() @@ -293,6 +312,9 @@ func (s *Store) Consume(code string, commit func(Request) (grantID string, err e if e == nil { return Request{}, "", ErrCodeUnknown } + if checkOrigin && e.issuer != origin { + return Request{}, "", ErrCodeOriginMismatch + } if e.consumed { if now.Before(e.consumedAt.Add(TombstoneLifetime)) { return Request{}, e.grantID, ErrCodeReused diff --git a/internal/profile/contract.go b/internal/profile/contract.go index 0788c810c..d3434e04d 100644 --- a/internal/profile/contract.go +++ b/internal/profile/contract.go @@ -216,6 +216,13 @@ const ( // page's Forget action. ChangeIssue ChangeKind = "issue" ChangeRevoke ChangeKind = "revoke" + // ChangeApprove, ChangeDeny and ChangeReplayRevoke are the Spec 132 browser + // login records: an administrator approved or denied a sign-in request + // (before any login exists), and an authentic refresh token that was + // already spent came back, so its login was revoked (reason replay). + ChangeApprove ChangeKind = "approve" + ChangeDeny ChangeKind = "deny" + ChangeReplayRevoke ChangeKind = "replay_revoke" ) // Credential error codes of the `credentials` admin MCP tool (Spec 115, diff --git a/internal/profile/contract_enums_golden_test.go b/internal/profile/contract_enums_golden_test.go index 195743285..c5d1a398d 100644 --- a/internal/profile/contract_enums_golden_test.go +++ b/internal/profile/contract_enums_golden_test.go @@ -57,7 +57,8 @@ func enumFamilies() map[string][]string { "explain_verdict": strs(ExplainVerdictAllowed, ExplainVerdictBlocked, ExplainVerdictHidden), "change_kind": strs(ChangeCreate, ChangeUpdate, ChangeDelete, ChangeRename, ChangeClassify, ChangeAssign, ChangeLock, ChangeUnlock, ChangeForget, - ChangeRotate, ChangeAnonymous, ChangeIssue, ChangeRevoke), + ChangeRotate, ChangeAnonymous, ChangeIssue, ChangeRevoke, ChangeApprove, + ChangeDeny, ChangeReplayRevoke), "rotation_state": {RotationFinalized, RotationRolledBack, RotationPending}, "surface": strs(SurfaceWeb, SurfaceMacOS, SurfaceCLI, SurfaceMCP, SurfaceAPI), "warning_code": strs(WarningAnonymousDeniedByBindingGuard, WarningClientHoldsAdminKey, diff --git a/internal/profile/testdata/contract/enums.json b/internal/profile/testdata/contract/enums.json index f68e2f0bf..8a74d9772 100644 --- a/internal/profile/testdata/contract/enums.json +++ b/internal/profile/testdata/contract/enums.json @@ -37,7 +37,10 @@ "rotate", "anonymous", "issue", - "revoke" + "revoke", + "approve", + "deny", + "replay_revoke" ], "credential_error_code": [ "secret_in_argument", diff --git a/internal/runtime/activity_attribution.go b/internal/runtime/activity_attribution.go index 0dc946e06..0409c9364 100644 --- a/internal/runtime/activity_attribution.go +++ b/internal/runtime/activity_attribution.go @@ -35,6 +35,10 @@ type ActivityAttribution struct { // scoped caller recognises its own policy_decision and prompt_get rows), // never in any API shape, export or SSE frame for another caller. TokenPrefix string + // GrantID is the browser-login grant that authenticated the request (Spec + // 132): it lands as metadata.grant_id so two logins of one client can be + // told apart. Not a secret. + GrantID string // WorkSessionID is the work session of the request (Spec 124 D1). It is // resolved at the emit site because only the request knows the credential, @@ -85,6 +89,7 @@ func (a ActivityAttribution) payload() map[string]any { set("client_version", a.ClientVersion) set("token_name", a.TokenName) set("_token_prefix", a.TokenPrefix) + set("grant_id", a.GrantID) set("_work_session_id", a.WorkSessionID) set("_user_id", a.UserID) set("run_name", a.RunName) @@ -114,6 +119,7 @@ func attributionFromPayload(payload map[string]any) ActivityAttribution { ClientVersion: getStringPayload(m, "client_version"), TokenName: getStringPayload(m, "token_name"), TokenPrefix: getStringPayload(m, "_token_prefix"), + GrantID: getStringPayload(m, "grant_id"), WorkSessionID: getStringPayload(m, "_work_session_id"), UserID: getStringPayload(m, "_user_id"), RunName: getStringPayload(m, "run_name"), @@ -175,6 +181,7 @@ func applyAttribution(rec *storage.ActivityRecord, a ActivityAttribution) { } setMetadataIfAbsent("client_name", a.ClientName) setMetadataIfAbsent("client_version", a.ClientVersion) + setMetadataIfAbsent("grant_id", a.GrantID) } // NewUsageAggregate returns an empty aggregate at the current admission diff --git a/internal/runtime/activity_attribution_grant_test.go b/internal/runtime/activity_attribution_grant_test.go new file mode 100644 index 000000000..5f0765588 --- /dev/null +++ b/internal/runtime/activity_attribution_grant_test.go @@ -0,0 +1,33 @@ +package runtime + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" +) + +// A browser login's grant id rides on the attribution and lands as +// metadata.grant_id on the record (Spec 132 R3): two logins of one client can +// be told apart in the log. The grant id is not a secret. +func TestActivityAttribution_GrantIDRoundTripsToMetadata(t *testing.T) { + a := testAttribution() + a.GrantID = "grantAAAAAAAAAAAAAAAAAA" + assert.Equal(t, "grantAAAAAAAAAAAAAAAAAA", attributionFromPayload(map[string]any{attributionPayloadKey: a.payload()}).GrantID) + assert.NotContains(t, ActivityAttribution{Profile: "p"}.payload(), "grant_id", "no grant, no key") + + store, cleanup := setupTestStorage(t) + defer cleanup() + svc := NewActivityService(store, zap.NewNop()) + svc.handleEvent(Event{ + Type: EventTypeActivityToolCallCompleted, Timestamp: time.Now().UTC(), + Payload: map[string]any{ + "server_name": "github", "tool_name": "list_issues", "session_id": "s1", "request_id": "r1", + "source": "mcp", "status": "success", "duration_ms": int64(5), "attribution": a.payload(), + }, + }) + rec := onlyRecord(t, store) + require.Equal(t, "grantAAAAAAAAAAAAAAAAAA", rec.Metadata["grant_id"]) +} diff --git a/internal/runtime/binding_guard.go b/internal/runtime/binding_guard.go index 319335c2f..2c0cc8fe8 100644 --- a/internal/runtime/binding_guard.go +++ b/internal/runtime/binding_guard.go @@ -44,6 +44,11 @@ type GuardFix struct { type GuardState struct { Config *config.Config Tokens []auth.AgentToken + // OAuthBindings are the browser-login binding entries (Spec 132 R5), each + // with its liveness. Every producer of a current or candidate state fills + // it from storage; a storage read error refuses the change. The evaluators + // read the combined view through EffectiveTokens. + OAuthBindings []OAuthBinding } // BindingGuard evaluates FR-008a. Implementations must be safe for concurrent @@ -155,15 +160,17 @@ func BindingRefOf(t *auth.AgentToken) BindingRef { func (ConservativeBindingGuard) BindingGuardDelta(current, candidate GuardState) []BindingRef { now := time.Now() already := make(map[string]bool) - for i := range current.Tokens { - t := ¤t.Tokens[i] + currentTokens := current.EffectiveTokens(now) + for i := range currentTokens { + t := ¤tTokens[i] if conservativeBypassable(current, t, now) { already[t.Name] = true } } var out []BindingRef - for i := range candidate.Tokens { - t := &candidate.Tokens[i] + candidateTokens := candidate.EffectiveTokens(now) + for i := range candidateTokens { + t := &candidateTokens[i] if conservativeBypassable(candidate, t, now) && !already[t.Name] { out = append(out, BindingRefOf(t)) } @@ -197,15 +204,17 @@ type bindingIdentity struct{ name, pin, mode string } func (StrictOfflineBindingGuard) BindingGuardDelta(current, candidate GuardState) []BindingRef { now := time.Now() already := make(map[bindingIdentity]bool) - for i := range current.Tokens { - t := ¤t.Tokens[i] + currentTokens := current.EffectiveTokens(now) + for i := range currentTokens { + t := ¤tTokens[i] if conservativeBypassable(current, t, now) { already[bindingIdentity{t.Name, t.ProfilePin, t.ProfileMode}] = true } } var out []BindingRef - for i := range candidate.Tokens { - t := &candidate.Tokens[i] + candidateTokens := candidate.EffectiveTokens(now) + for i := range candidateTokens { + t := &candidateTokens[i] if conservativeBypassable(candidate, t, now) && !already[bindingIdentity{t.Name, t.ProfilePin, t.ProfileMode}] { out = append(out, BindingRefOf(t)) } diff --git a/internal/runtime/binding_guard_oauth.go b/internal/runtime/binding_guard_oauth.go new file mode 100644 index 000000000..fd0aea3cd --- /dev/null +++ b/internal/runtime/binding_guard_oauth.go @@ -0,0 +1,156 @@ +package runtime + +import ( + "fmt" + "sort" + "time" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// Spec 132 R5: a client that holds browser logins but no API key has no token +// record, so the binding guard (which reads auth.AgentToken only) would not see +// its binding. GuardState therefore carries the OAuth-side bindings next to the +// token records, and every guard treats a live named one as an active binding. + +// OAuthBinding is one browser-login binding entry as the guard sees it. Live is +// true while the client has at least one grant that is not revoked and whose +// refresh token has not expired. +type OAuthBinding struct { + ClientID string `json:"client_id"` + Pin string `json:"pin"` + Mode string `json:"mode"` + Live bool `json:"live"` +} + +// OAuthBindingSource is the browser-login storage surface the guard producers +// read; *storage.Manager implements it. A store that does not (a test fake, an +// older store) contributes no OAuth bindings. +type OAuthBindingSource interface { + ListOAuthClientBindings() (map[string]storage.OAuthClientBinding, error) + ListOAuthGrants() ([]storage.OAuthGrant, error) +} + +// LoadOAuthBindings reads every browser-login binding with its liveness, sorted +// by client id. src is any value; one that does not implement +// OAuthBindingSource yields nil. A read error is returned and the caller MUST +// refuse the change (fail closed): it must never be read as "no bindings". +// On a database that never used browser login this is two read transactions +// over absent buckets and no write. +func LoadOAuthBindings(src any, now time.Time) ([]OAuthBinding, error) { + s, ok := src.(OAuthBindingSource) + if !ok || s == nil { + return nil, nil + } + bindings, err := s.ListOAuthClientBindings() + if err != nil { + return nil, fmt.Errorf("cannot read browser-login bindings: %w", err) + } + if len(bindings) == 0 { + return nil, nil + } + grants, err := s.ListOAuthGrants() + if err != nil { + return nil, fmt.Errorf("cannot read browser-login grants: %w", err) + } + live := map[string]bool{} + for i := range grants { + g := &grants[i] + if !g.Revoked && g.RefreshExpiresAt.After(now) { + live[g.Client] = true + } + } + out := make([]OAuthBinding, 0, len(bindings)) + for id, b := range bindings { + out = append(out, OAuthBinding{ClientID: id, Pin: b.ProfilePin, Mode: b.ProfileMode, Live: live[id]}) + } + sort.Slice(out, func(i, j int) bool { return out[i].ClientID < out[j].ClientID }) + return out, nil +} + +// ActiveOAuthBinding reports whether b counts as an active named binding: a +// live entry with a named pin and a binding mode. +func ActiveOAuthBinding(b OAuthBinding) bool { + return b.Live && b.Pin != "" && + (b.Mode == auth.ProfileModeLocked || b.Mode == auth.ProfileModeSwitchable) +} + +// EffectiveTokens returns the guarded records the evaluators walk: Tokens, plus +// one synthetic client record for every live named OAuth binding whose client +// has no ACTIVE guarded token (a client with both credentials counts once, as +// its API-key record). The binding of a client that has an API-key record, in +// any state, is that record's: it is the truth for the request path +// (storage.CurrentClientBinding), so a stale entry never decides. With no OAuth +// bindings the result is Tokens itself, unchanged. +func (s GuardState) EffectiveTokens(now time.Time) []auth.AgentToken { + if len(s.OAuthBindings) == 0 { + return s.Tokens + } + byName := make(map[string]*auth.AgentToken, len(s.Tokens)) + for i := range s.Tokens { + byName[s.Tokens[i].Name] = &s.Tokens[i] + } + var extra []auth.AgentToken + for _, b := range s.OAuthBindings { + if !b.Live { + continue + } + name := auth.ClientTokenName(b.ClientID) + pin, mode := b.Pin, b.Mode + if rec := byName[name]; rec != nil && rec.Kind == auth.KindClient { + if ActiveGuardedBinding(rec, now) { + continue // counted once, as the API-key record + } + pin, mode = rec.ProfilePin, rec.ProfileMode + } + if !ActiveOAuthBinding(OAuthBinding{ClientID: b.ClientID, Pin: pin, Mode: mode, Live: true}) { + continue + } + extra = append(extra, auth.AgentToken{ + Name: name, Kind: auth.KindClient, ClientID: b.ClientID, + ProfilePin: pin, ProfileMode: mode, ExpiresAt: now.AddDate(100, 0, 0), + }) + } + if len(extra) == 0 { + return s.Tokens + } + out := make([]auth.AgentToken, 0, len(s.Tokens)+len(extra)) + out = append(out, s.Tokens...) + return append(out, extra...) +} + +// withOAuthClient returns bindings with client's entry added or replaced by e +// (a first approval's candidate entry, Live: true). +func withOAuthClient(bindings []OAuthBinding, e OAuthBinding) []OAuthBinding { + out := make([]OAuthBinding, 0, len(bindings)+1) + replaced := false + for _, b := range bindings { + if b.ClientID == e.ClientID { + out = append(out, e) + replaced = true + continue + } + out = append(out, b) + } + if !replaced { + out = append(out, e) + } + return out +} + +// repinOAuthBindings returns bindings with every pin naming from moved to to +// (a profile rename or reassign rewrites both copies). +func repinOAuthBindings(bindings []OAuthBinding, from, to string) []OAuthBinding { + if len(bindings) == 0 { + return bindings + } + out := make([]OAuthBinding, len(bindings)) + copy(out, bindings) + for i := range out { + if out[i].Pin == from { + out[i].Pin = to + } + } + return out +} diff --git a/internal/runtime/binding_guard_oauth_test.go b/internal/runtime/binding_guard_oauth_test.go new file mode 100644 index 000000000..55b6f64cc --- /dev/null +++ b/internal/runtime/binding_guard_oauth_test.go @@ -0,0 +1,157 @@ +package runtime + +import ( + "errors" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +func oauthB(client, pin, mode string, live bool) OAuthBinding { + return OAuthBinding{ClientID: client, Pin: pin, Mode: mode, Live: live} +} + +func authOff() *config.Config { return &config.Config{} } + +// With no OAuth bindings the effective token list IS the token list. +func TestGuardState_EffectiveTokensWithoutOAuthIsIdentical(t *testing.T) { + toks := []auth.AgentToken{strictTok("cursor", "ro", auth.ProfileModeLocked)} + st := GuardState{Config: authOff(), Tokens: toks} + got := st.EffectiveTokens(time.Now()) + require.Equal(t, toks, got) + if len(got) > 0 { + require.Same(t, &toks[0], &got[0], "no copy when there is nothing to add") + } +} + +func TestBindingGuard_OAuthOnlyClientIsAnActiveNamedBinding(t *testing.T) { + cur := GuardState{Config: authOff()} + live := GuardState{Config: authOff(), OAuthBindings: []OAuthBinding{oauthB("cursor", "ro", auth.ProfileModeLocked, true)}} + + for name, g := range map[string]BindingGuard{"conservative": ConservativeBindingGuard{}, "strict": StrictOfflineBindingGuard{}} { + t.Run(name, func(t *testing.T) { + // A first approval: the candidate adds the entry with Live: true. + delta := g.BindingGuardDelta(cur, live) + require.Len(t, delta, 1) + require.Equal(t, BindingRef{ClientID: "cursor", TokenName: "client-cursor", Profile: "ro", Mode: auth.ProfileModeLocked}, delta[0]) + + // Lapsed or revoked: not a binding. + lapsed := GuardState{Config: authOff(), OAuthBindings: []OAuthBinding{oauthB("cursor", "ro", auth.ProfileModeLocked, false)}} + require.Empty(t, g.BindingGuardDelta(cur, lapsed)) + // All servers (no pin) is not a named binding. + open := GuardState{Config: authOff(), OAuthBindings: []OAuthBinding{oauthB("cursor", "", auth.ProfileModeSwitchable, true)}} + require.Empty(t, g.BindingGuardDelta(cur, open)) + // require_mcp_auth on never refuses. + authOn := GuardState{Config: &config.Config{RequireMCPAuth: true}, OAuthBindings: live.OAuthBindings} + require.Empty(t, g.BindingGuardDelta(cur, authOn)) + // An unchanged live binding is not NEW. + require.Empty(t, g.BindingGuardDelta(live, live)) + }) + } +} + +// A client with both credentials counts once, and the API-key record decides +// the binding (it is the truth for the request path too). +func TestBindingGuard_ClientWithBothCredentialsCountsOnce(t *testing.T) { + g := ConservativeBindingGuard{} + api := strictTok("cursor", "ro", auth.ProfileModeLocked) + cur := GuardState{Config: authOff()} + both := GuardState{ + Config: authOff(), Tokens: []auth.AgentToken{api}, + OAuthBindings: []OAuthBinding{oauthB("cursor", "ro", auth.ProfileModeLocked, true)}, + } + delta := g.BindingGuardDelta(cur, both) + require.Len(t, delta, 1, "one client, one ref") + + // The record wins over a stale entry. + stale := GuardState{ + Config: authOff(), Tokens: []auth.AgentToken{api}, + OAuthBindings: []OAuthBinding{oauthB("cursor", "other", auth.ProfileModeSwitchable, true)}, + } + delta = g.BindingGuardDelta(cur, stale) + require.Len(t, delta, 1) + require.Equal(t, "ro", delta[0].Profile) + + // A revoked API record leaves the live login binding in force. + revoked := api + revoked.Revoked = true + login := GuardState{ + Config: authOff(), Tokens: []auth.AgentToken{revoked}, + OAuthBindings: []OAuthBinding{oauthB("cursor", "ro", auth.ProfileModeLocked, true)}, + } + require.Len(t, g.BindingGuardDelta(cur, login), 1) +} + +func TestBindingGuard_NoOAuthBindingsKeepsTodaysResult(t *testing.T) { + cur := GuardState{Config: authOff(), Tokens: []auth.AgentToken{strictTok("cursor", "ro", auth.ProfileModeLocked)}} + cand := GuardState{Config: authOff(), Tokens: []auth.AgentToken{strictTok("cursor", "ro", auth.ProfileModeLocked), strictTok("codex", "ro", auth.ProfileModeLocked)}} + for _, g := range []BindingGuard{ConservativeBindingGuard{}, StrictOfflineBindingGuard{}} { + require.Len(t, g.BindingGuardDelta(cur, cand), 1) + } +} + +type fakeOAuthSource struct { + bindings map[string]storage.OAuthClientBinding + grants []storage.OAuthGrant + err error +} + +func (f fakeOAuthSource) ListOAuthClientBindings() (map[string]storage.OAuthClientBinding, error) { + return f.bindings, f.err +} +func (f fakeOAuthSource) ListOAuthGrants() ([]storage.OAuthGrant, error) { return f.grants, f.err } + +func TestLoadOAuthBindings_LiveMeansAGrantNotRevokedAndNotLapsed(t *testing.T) { + now := time.Now() + src := fakeOAuthSource{ + bindings: map[string]storage.OAuthClientBinding{ + "live": {ProfilePin: "p", ProfileMode: auth.ProfileModeLocked}, + "dead": {ProfilePin: "p", ProfileMode: auth.ProfileModeLocked}, + "lap": {ProfilePin: "p", ProfileMode: auth.ProfileModeLocked}, + "none": {ProfilePin: "p", ProfileMode: auth.ProfileModeLocked}, + }, + grants: []storage.OAuthGrant{ + {GrantID: "g1", Client: "live", RefreshExpiresAt: now.Add(time.Hour)}, + {GrantID: "g2", Client: "dead", RefreshExpiresAt: now.Add(time.Hour), Revoked: true}, + {GrantID: "g3", Client: "lap", RefreshExpiresAt: now.Add(-time.Hour)}, + {GrantID: "g4", Client: "dead", RefreshExpiresAt: now.Add(time.Hour), Revoked: true}, + {GrantID: "g5", Client: "live", RefreshExpiresAt: now.Add(-time.Hour)}, + }, + } + got, err := LoadOAuthBindings(src, now) + require.NoError(t, err) + require.Equal(t, []OAuthBinding{ + {ClientID: "dead", Pin: "p", Mode: auth.ProfileModeLocked}, + {ClientID: "lap", Pin: "p", Mode: auth.ProfileModeLocked}, + {ClientID: "live", Pin: "p", Mode: auth.ProfileModeLocked, Live: true}, + {ClientID: "none", Pin: "p", Mode: auth.ProfileModeLocked}, + }, got) +} + +// A storage read error refuses the change instead of guessing (fail closed), +// and a store that has no browser-login storage contributes nothing. +func TestLoadOAuthBindings_ErrorIsReturnedAndNonStoreIsNil(t *testing.T) { + _, err := LoadOAuthBindings(fakeOAuthSource{err: errors.New("boom")}, time.Now()) + require.Error(t, err) + got, err := LoadOAuthBindings(struct{}{}, time.Now()) + require.NoError(t, err) + require.Nil(t, got) + got, err = LoadOAuthBindings(nil, time.Now()) + require.NoError(t, err) + require.Nil(t, got) +} + +// On a database that never used browser login the read is empty and writes +// nothing (no bucket is created by the read path). +func TestLoadOAuthBindings_NeverUsedDatabaseIsEmpty(t *testing.T) { + store, cleanup := setupTestStorage(t) + defer cleanup() + got, err := LoadOAuthBindings(store, time.Now()) + require.NoError(t, err) + require.Empty(t, got) +} diff --git a/internal/runtime/binding_guard_wiring.go b/internal/runtime/binding_guard_wiring.go index dbe1b0e8b..78b016768 100644 --- a/internal/runtime/binding_guard_wiring.go +++ b/internal/runtime/binding_guard_wiring.go @@ -1,6 +1,8 @@ package runtime import ( + "time" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" ) @@ -53,3 +55,14 @@ func (r *Runtime) guardedBindingSnapshot() ([]auth.AgentToken, error) { } return guardedOnly(all), nil } + +// oauthBindingSnapshot returns the browser-login bindings every FR-008a path +// evaluates next to the token records (Spec 132 R5). A read error is returned, +// never swallowed: the guard fails closed. +func (r *Runtime) oauthBindingSnapshot() ([]OAuthBinding, error) { + sm := r.StorageManager() + if sm == nil { + return nil, nil + } + return LoadOAuthBindings(sm, time.Now()) +} diff --git a/internal/runtime/clients_service.go b/internal/runtime/clients_service.go index a5b259b5c..69483588e 100644 --- a/internal/runtime/clients_service.go +++ b/internal/runtime/clients_service.go @@ -43,6 +43,10 @@ type ClientsService struct { notifier BindingNotifier reader ClientConfigReader + // cancelLogins cancels a client's pending and approved browser sign-in + // requests (Spec 132). Called under mu after a revoke or forget. + cancelLogins func(clientID string) + // upgrade is the connect port behind the admin-key upgrade, observe the // sink for on-demand credential classifications (Spec 108-f). upgrade AdminKeyUpgradePort @@ -139,6 +143,10 @@ type ClientCredentialView struct { ExpiresAt *time.Time `json:"expires_at,omitempty"` ConnectedAt *time.Time `json:"connected_at,omitempty"` RotationPending bool `json:"rotation_pending,omitempty"` + // Credentials and BrowserLoginDisabled exist only once browser login was + // used (Spec 132); until then a view is exactly what it always was. + Credentials []ClientCredentialEntry `json:"credentials,omitempty"` + BrowserLoginDisabled *bool `json:"browser_login_disabled,omitempty"` } // ValidationError is a 400 {error, field} refusal. @@ -385,8 +393,18 @@ func guardedOnly(all []auth.AgentToken) []auth.AgentToken { func (s *ClientsService) checkGuard(all []auth.AgentToken, clientID string, next *auth.AgentToken) error { cfg := s.cfg() - current := GuardState{Config: cfg, Tokens: guardedOnly(all)} - candidate := GuardState{Config: cfg, Tokens: candidateTokens(all, clientID, next)} + // Spec 132 R5: the browser-login bindings are part of both states. A read + // error refuses the change (fail closed). + oauth, err := s.loadOAuthBindings() + if err != nil { + return err + } + candOAuth := oauth + if next != nil { + candOAuth = repinOAuthClient(oauth, clientID, next.ProfilePin, next.ProfileMode) + } + current := GuardState{Config: cfg, Tokens: guardedOnly(all), OAuthBindings: oauth} + candidate := GuardState{Config: cfg, Tokens: candidateTokens(all, clientID, next), OAuthBindings: candOAuth} return CheckBindingGuard(s.guard(), current, candidate) } @@ -421,6 +439,10 @@ type changeRecord struct { clientID string tokenName string diff map[string]interface{} + // meta is merged into the record's metadata after the fixed keys (it never + // replaces one): the Spec 132 rows carry request_id, grant_id, trigger and + // approved_by this way. + meta map[string]interface{} } func surfaceSource(s profile.Surface) storage.ActivitySource { @@ -458,6 +480,11 @@ func writeChangeRecord(ctx context.Context, activity func(*storage.ActivityRecor if len(c.diff) > 0 { meta["diff"] = c.diff } + for k, v := range c.meta { + if _, fixed := meta[k]; !fixed { + meta[k] = v + } + } rec := &storage.ActivityRecord{ Type: storage.ActivityTypeProfileChange, Source: surfaceSource(a.Surface), @@ -545,6 +572,11 @@ func (s *ClientsService) setBindingLocked(ctx context.Context, a Actor, clientID // The credential precondition (409) comes before request validation (400) // so a client without an active credential always gets no_client_credential. if state := s.stateOf(rec); state != profile.CredentialStateClient { + // Spec 132: a client with browser logins and no active API key is + // still a client; its binding changes through the one binding writer. + if v, handled, err := s.setOAuthBindingLocked(ctx, a, all, rec, clientID, profileName, modeArg); handled { + return v, err + } return nil, &NoClientCredentialError{ClientID: clientID, State: state} } if profileName != "" && !s.profileExists(s.cfg(), profileName) { @@ -604,6 +636,7 @@ func (s *ClientsService) BulkAssign(ctx context.Context, a Actor, from, to strin ids = append(ids, t.ClientID) } } + ids = append(ids, s.oauthOnlyBindingClients(all, from)...) sort.Strings(ids) for _, id := range ids { if s.connectInFlight(id) { @@ -644,12 +677,26 @@ func (s *ClientsService) List() ([]ClientCredentialView, error) { if err != nil { return nil, err } + st, err := s.loadOAuthState() + if err != nil { + return nil, err + } var out []ClientCredentialView for i := range all { if all[i].Kind == auth.KindClient { - out = append(out, *s.view(&all[i])) + v := s.view(&all[i]) + st.decorate(v, &all[i], s.now()) + out = append(out, *v) } } + for id, b := range st.bindings { + if rec := clientRecord(all, id); rec != nil && rec.Kind == auth.KindClient { + continue + } + v := s.oauthOnlyView(id, b) + st.decorate(v, nil, s.now()) + out = append(out, *v) + } sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID }) return out, nil } @@ -661,10 +708,21 @@ func (s *ClientsService) Get(clientID string) (*ClientCredentialView, error) { return nil, err } rec := clientRecord(all, clientID) + st, err := s.loadOAuthState() + if err != nil { + return nil, err + } if rec == nil || rec.Kind != auth.KindClient { + if b, ok := st.bindings[clientID]; ok { + v := s.oauthOnlyView(clientID, b) + st.decorate(v, nil, s.now()) + return v, nil + } return nil, nil } - return s.view(rec), nil + v := s.view(rec) + st.decorate(v, rec, s.now()) + return v, nil } // Forget revokes a client's credential (change=forget). disconnected records @@ -707,9 +765,34 @@ func (s *ClientsService) forgetLockedChange(ctx context.Context, a Actor, client // forgetRecordLocked is forgetLockedChange returning the committed revoked // record, so the credentials service projects its view without a re-read. func (s *ClientsService) forgetRecordLocked(ctx context.Context, a Actor, clientID string, diff map[string]interface{}, restorePrior bool, change profile.ChangeKind) (*auth.AgentToken, error) { + // Cancel the client's pending and approved sign-in requests FIRST, under the + // mutex the token exchange commits under, and whatever the storage call + // below answers: a client with nothing stored yet (no_client_credential) + // must not keep an approved first login alive (Spec 132 R15). + s.cancelLoginRequests(clientID) forget := s.store.ForgetClientCredential if restorePrior { forget = s.store.ForgetClientCredentialRestoringPrior + // A connect undone for a client with live logins must not restore a + // binding the guard now refuses: revoke the key only and say so. + if reason := s.restoreSkipReason(clientID); reason != "" { + forget = s.revokeKeyKeepingBinding + nd := map[string]interface{}{"restore_skipped": reason} + for k, v := range diff { + nd[k] = v + } + diff = nd + } + } else if o := s.oauthStore(); o != nil { + hasLogins, herr := s.hasLoginRecords(o, clientID) + if herr != nil { + return nil, herr // fail closed: never leave live logins behind + } + if hasLogins { + // Spec 132: forget deletes the client's browser logins, revoke + // marks them revoked; both cover the API key exactly as before. + forget = s.oauthForgetFunc(o, change) + } } // The restore path rewrites the revoked record's binding, so capture the // binding it held when revoked for the audit record. @@ -735,6 +818,8 @@ func (s *ClientsService) forgetRecordLocked(ctx context.Context, a Actor, client change: change, profile: heldPin, previousProfile: heldPin, clientID: clientID, tokenName: revoked.Name, diff: diff, }) + // Live MCP sessions and streams are not terminated here: a revoked login is + // refused on its next request, which the HTTP layer enforces per request. if s.publish != nil { s.publish(newEvent(EventTypeCredentialsChanged, map[string]any{ "kind": CredentialKindClient, "id": clientID, "token_name": revoked.Name, diff --git a/internal/runtime/clients_service_connect.go b/internal/runtime/clients_service_connect.go index e0ca39ab5..447b7fd28 100644 --- a/internal/runtime/clients_service_connect.go +++ b/internal/runtime/clients_service_connect.go @@ -116,7 +116,30 @@ func (s *ClientsService) releaseConnect(clientID, token string) { // instead of silently widening a profile-locked client to All servers. A // tombstone with no binding (or no record) starts from the defaults, and an // explicit profile always wins. -func (s *ClientsService) resolveBindingLocked(rec *auth.AgentToken, profilePtr, modePtr *string) (pin, mode string, err error) { +func (s *ClientsService) resolveBindingLocked(clientID string, rec *auth.AgentToken, profilePtr, modePtr *string) (pin, mode string, err error) { + // Spec 132: a client with browser logins and no API-key record keeps the + // binding of its logins when the connect names no profile, exactly as a + // reconnect keeps a record's. A read error refuses (fail closed); explicit + // arguments override and still go through the guard. + if rec == nil && profilePtr == nil { + if o := s.oauthStore(); o != nil { + entry, gerr := o.GetOAuthClientBinding(clientID) + if gerr != nil { + return "", "", fmt.Errorf("cannot read browser-login bindings: %w", gerr) + } + if entry != nil { + pin = entry.ProfilePin + mode, err = resolveMode(pin, modePtr, entry.ProfileMode) + if err != nil { + return "", "", err + } + if pin != "" && !s.profileExists(s.cfg(), pin) { + return "", "", &ValidationError{Field: "profile", Message: fmt.Sprintf("unknown profile %q", pin)} + } + return pin, mode, nil + } + } + } keepBinding := rec != nil && profilePtr == nil && (s.stateOf(rec) == profile.CredentialStateClient || s.stateOf(rec) == profile.CredentialStateExpired || s.stateOf(rec) == profile.CredentialStateRevoked) @@ -161,7 +184,7 @@ func (s *ClientsService) issueLockedRecord(clientID string, profilePtr, modePtr return nil, nil, &ValidationError{Field: "id", Message: fmt.Sprintf("client %s already has an active credential; rotate it instead", clientID)} } - pin, mode, err := s.resolveBindingLocked(rec, profilePtr, modePtr) + pin, mode, err := s.resolveBindingLocked(clientID, rec, profilePtr, modePtr) if err != nil { return nil, nil, err } @@ -254,7 +277,7 @@ func (m connectMinter) PreviewBinding(clientID string, intent connect.Credential if rec != nil && rec.Kind != auth.KindClient { return "", "", storage.ErrClientCredentialConflict } - return s.resolveBindingLocked(rec, intent.Profile, intent.Mode) + return s.resolveBindingLocked(clientID, rec, intent.Profile, intent.Mode) } // Release implements connect.CredentialMinter: it ends the in-flight claim @@ -395,6 +418,18 @@ func (m connectMinter) Abort(clientID string, intent connect.CredentialIntent, i } // A fresh mint whose config write failed: revoke it and write no record // (from the operator's view nothing happened, plan D13). + if reason := s.restoreSkipReason(clientID); reason != "" { + revoked, rerr := s.revokeKeyKeepingBinding(clientID) + if rerr != nil { + return rerr + } + s.writeChange(context.Background(), actorOf(intent), changeRecord{ + change: profile.ChangeForget, profile: revoked.ProfilePin, previousProfile: revoked.ProfilePin, + clientID: clientID, tokenName: revoked.Name, + diff: map[string]interface{}{"reason": "rollback", "restore_skipped": reason}, + }) + return nil + } _, err := s.store.ForgetClientCredentialRestoringPrior(clientID) return err } diff --git a/internal/runtime/clients_service_oauth.go b/internal/runtime/clients_service_oauth.go new file mode 100644 index 000000000..a0b14c37d --- /dev/null +++ b/internal/runtime/clients_service_oauth.go @@ -0,0 +1,453 @@ +package runtime + +import ( + "context" + "errors" + "fmt" + "sort" + "time" + + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/profile" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// Spec 132: a client holds an API key, browser logins, or both. The binding is +// one per client; this file is where ClientsService learns about the OAuth side +// without changing a byte of what it does for a client that never used it: every +// entry point first asks whether the store has browser-login storage AND whether +// the client (or the install) has any. + +// oauthClientStore is the browser-login storage surface ClientsService uses +// beyond ClientCredentialStore; *storage.Manager implements it. A store that +// does not (a test fake) keeps every behaviour exactly as it was. +type oauthClientStore interface { + OAuthBindingSource + GetOAuthClientBinding(clientID string) (*storage.OAuthClientBinding, error) + ListOAuthRegistrations() ([]storage.OAuthRegistration, error) + OAuthLoginEverUsed() (bool, error) + ForgetClient(clientID string) (*auth.AgentToken, error) + RevokeClient(clientID string, now time.Time) (*auth.AgentToken, error) + RevokeClientAPIKey(clientID string) (*auth.AgentToken, error) + UpdateOAuthClientBinding(clientID, pin, mode string) (beforePin, beforeMode string, err error) + RepairOAuthClientBindings() (repaired, skipped []string, err error) +} + +func (s *ClientsService) oauthStore() oauthClientStore { + o, _ := s.store.(oauthClientStore) + return o +} + +// SetLoginCanceler installs the hook that cancels a client's pending and +// approved sign-in requests; it runs under the service's mutex (the same one +// the token exchange commits under) after a revoke or forget. +func (s *ClientsService) SetLoginCanceler(fn func(clientID string)) { + s.cancelLogins = func(id string) { + if fn != nil { + fn(id) + } + } +} + +func (s *ClientsService) cancelLoginRequests(clientID string) { + if s.cancelLogins != nil { + s.cancelLogins(clientID) + } +} + +// hasLoginRecords reports whether the client has browser-login storage. +func (s *ClientsService) hasLoginRecords(o oauthClientStore, clientID string) (bool, error) { + if o == nil { + return false, nil + } + b, err := o.GetOAuthClientBinding(clientID) + if err != nil { + return false, fmt.Errorf("cannot read browser-login bindings: %w", err) + } + return b != nil, nil +} + +// loadOAuthBindings reads the OAuth side of a guard state (fail closed: an error +// refuses the change). +func (s *ClientsService) loadOAuthBindings() ([]OAuthBinding, error) { + return LoadOAuthBindings(s.store, s.now()) +} + +// oauthBindingsBestEffort is loadOAuthBindings for an advisory view (the +// warnings list): an unreadable store yields no bindings instead of an error, +// because nothing is being refused. +func (s *ClientsService) oauthBindingsBestEffort() []OAuthBinding { + b, err := s.loadOAuthBindings() + if err != nil { + s.logger.Warn("cannot read browser-login bindings for the warnings", zap.Error(err)) + return nil + } + return b +} + +// repinOAuthClient returns bindings with the client's entry set to (pin, mode). +func repinOAuthClient(bindings []OAuthBinding, clientID, pin, mode string) []OAuthBinding { + if len(bindings) == 0 { + return bindings + } + out := make([]OAuthBinding, len(bindings)) + copy(out, bindings) + for i := range out { + if out[i].ClientID == clientID { + out[i].Pin, out[i].Mode = pin, mode + } + } + return out +} + +// --- views ---------------------------------------------------------------------- + +// ClientCredentialEntry is one credential of a client in the Clients views +// (contracts/rest-admin.md): the API key or a browser login. A secret, a hash or +// a token never appears here. +type ClientCredentialEntry struct { + // Kind is api_key or browser_login. + Kind string `json:"kind"` + Prefix string `json:"prefix,omitempty"` + // GrantID names a browser login. + GrantID string `json:"grant_id,omitempty"` + // State is active|expired|revoked for an API key and active|lapsed|revoked + // for a login. + State string `json:"state"` + ExpiresAt *time.Time `json:"expires_at,omitempty"` + ApprovedAt *time.Time `json:"approved_at,omitempty"` + LastUsedAt *time.Time `json:"last_used_at,omitempty"` + ReportedName string `json:"reported_name,omitempty"` + RedirectHost string `json:"redirect_host,omitempty"` + ObservedName string `json:"observed_name,omitempty"` + NameMismatch *bool `json:"name_mismatch,omitempty"` +} + +// Browser-login states of a grant. +const ( + GrantStateActive = "active" + GrantStateLapsed = "lapsed" + GrantStateRevoked = "revoked" +) + +// GrantStateOf classifies a grant: revoked over lapsed over active. +func GrantStateOf(g *storage.OAuthGrant, now time.Time) string { + switch { + case g.Revoked: + return GrantStateRevoked + case !g.RefreshExpiresAt.After(now): + return GrantStateLapsed + default: + return GrantStateActive + } +} + +// oauthClientsState is what the views need from the browser-login storage. It +// is inactive (the zero value) for an install that never used the feature, and +// then every view is exactly what it was before Spec 132. +type oauthClientsState struct { + active bool + disabled bool + bindings map[string]storage.OAuthClientBinding + grants map[string][]storage.OAuthGrant + reported map[string]string // registration id -> reported name +} + +func (s *ClientsService) loadOAuthState() (oauthClientsState, error) { + o := s.oauthStore() + if o == nil { + return oauthClientsState{}, nil + } + bindings, err := o.ListOAuthClientBindings() + if err != nil { + return oauthClientsState{}, fmt.Errorf("cannot read browser-login bindings: %w", err) + } + used := len(bindings) > 0 + if !used { + if used, err = o.OAuthLoginEverUsed(); err != nil { + return oauthClientsState{}, fmt.Errorf("cannot read the browser-login marker: %w", err) + } + } + if !used { + return oauthClientsState{}, nil + } + grants, err := o.ListOAuthGrants() + if err != nil { + return oauthClientsState{}, fmt.Errorf("cannot read browser logins: %w", err) + } + regs, err := o.ListOAuthRegistrations() + if err != nil { + return oauthClientsState{}, fmt.Errorf("cannot read browser-login registrations: %w", err) + } + st := oauthClientsState{active: true, bindings: bindings, grants: map[string][]storage.OAuthGrant{}, reported: map[string]string{}} + if c := s.cfg(); c == nil || !c.MCPOAuthEnabled { + st.disabled = true + } + for i := range regs { + st.reported[regs[i].ClientID] = regs[i].ReportedName + } + sort.SliceStable(grants, func(i, j int) bool { return grants[i].ApprovedAt.After(grants[j].ApprovedAt) }) + for i := range grants { + st.grants[grants[i].Client] = append(st.grants[grants[i].Client], grants[i]) + } + return st, nil +} + +// decorate adds the credentials list and browser_login_disabled to a view. It +// is a no-op while the feature was never used. +func (st oauthClientsState) decorate(v *ClientCredentialView, rec *auth.AgentToken, now time.Time) { + if !st.active { + return + } + creds := []ClientCredentialEntry{} + if rec != nil && rec.Kind == auth.KindClient { + e := ClientCredentialEntry{Kind: "api_key", Prefix: rec.TokenPrefix, State: CredentialStateOf(rec, now), LastUsedAt: rec.LastUsedAt} + if !rec.ExpiresAt.IsZero() { + exp := rec.ExpiresAt + e.ExpiresAt = &exp + } + creds = append(creds, e) + } + grants := st.grants[v.ID] + for i := range grants { + g := &grants[i] + mismatch := OAuthNameMismatch(g.ObservedClientName, st.reported[g.RegistrationID], g.Client) + approved := g.ApprovedAt + exp := g.RefreshExpiresAt + creds = append(creds, ClientCredentialEntry{ + Kind: CredentialKindBrowserLogin, GrantID: g.GrantID, State: GrantStateOf(g, now), + Prefix: g.DisplayPrefix, ExpiresAt: &exp, ApprovedAt: &approved, LastUsedAt: g.LastUsedAt, + ReportedName: st.reported[g.RegistrationID], RedirectHost: redirectHost(g.RedirectURI), + ObservedName: g.ObservedClientName, NameMismatch: &mismatch, + }) + } + v.Credentials = creds + disabled := st.disabled && len(grants) > 0 + v.BrowserLoginDisabled = &disabled +} + +// oauthOnlyView is the view of a client that has browser logins and no API-key +// record. +func (s *ClientsService) oauthOnlyView(id string, b storage.OAuthClientBinding) *ClientCredentialView { + return &ClientCredentialView{ + ID: id, DisplayName: b.DisplayName, TokenName: auth.ClientTokenName(id), + Profile: b.ProfilePin, Mode: b.ProfileMode, CredentialState: profile.CredentialStateNone, + } +} + +// --- binding change --------------------------------------------------------------- + +// setOAuthBindingLocked is setBindingLocked for a client without an ACTIVE API +// key that has browser-login storage (s.mu held). handled is false when the +// client has none, and the caller answers no_client_credential as before. The +// one binding writer keeps an existing API-key record equal. +func (s *ClientsService) setOAuthBindingLocked(ctx context.Context, a Actor, all []auth.AgentToken, rec *auth.AgentToken, clientID, profileName string, modeArg *string) (view *ClientCredentialView, handled bool, err error) { + o := s.oauthStore() + if o == nil { + return nil, false, nil + } + entry, err := o.GetOAuthClientBinding(clientID) + if err != nil { + return nil, true, err + } + if entry == nil { + return nil, false, nil + } + curPin, curMode := entry.ProfilePin, entry.ProfileMode + if rec != nil && rec.Kind == auth.KindClient { + curPin, curMode = rec.ProfilePin, rec.ProfileMode // the record wins + } + if profileName != "" && !s.profileExists(s.cfg(), profileName) { + return nil, true, &ValidationError{Field: "profile", Message: fmt.Sprintf("unknown profile %q", profileName)} + } + mode, err := resolveMode(profileName, modeArg, curMode) + if err != nil { + return nil, true, err + } + state, err := s.loadOAuthState() + if err != nil { + return nil, true, err + } + if curPin == profileName && curMode == mode { + v := s.oauthOnlyView(clientID, *entry) + v.Profile, v.Mode = curPin, curMode + state.decorate(v, rec, s.now()) + return v, true, nil + } + // The guard judges the whole candidate: the API-key record (when there is + // one, whatever its state) and the browser-login entry both move. + oauth, err := s.loadOAuthBindings() + if err != nil { + return nil, true, err + } + cfg := s.cfg() + tokens := guardedOnly(all) + candTokens := tokens + if rec != nil && rec.Kind == auth.KindClient { + next := *rec + next.ProfilePin, next.ProfileMode = profileName, mode + candTokens = candidateTokens(all, clientID, &next) + } + if err := CheckBindingGuard(s.guard(), + GuardState{Config: cfg, Tokens: tokens, OAuthBindings: oauth}, + GuardState{Config: cfg, Tokens: candTokens, OAuthBindings: repinOAuthClient(oauth, clientID, profileName, mode)}); err != nil { + return nil, true, err + } + if _, _, err := o.UpdateOAuthClientBinding(clientID, profileName, mode); err != nil { + if errors.Is(err, storage.ErrClientCredentialNotFound) { + return nil, false, nil + } + return nil, true, err + } + before := &auth.AgentToken{Name: auth.ClientTokenName(clientID), Kind: auth.KindClient, ClientID: clientID, ProfilePin: curPin, ProfileMode: curMode} + after := &auth.AgentToken{Name: auth.ClientTokenName(clientID), Kind: auth.KindClient, ClientID: clientID, ProfilePin: profileName, ProfileMode: mode} + change, diff := bindingChange(before, after) + s.writeChange(ctx, a, changeRecord{ + change: change, profile: profileName, previousProfile: curPin, + clientID: clientID, tokenName: after.Name, diff: diff, + }) + s.announce(before, after) + v := s.oauthOnlyView(clientID, *entry) + v.Profile, v.Mode = profileName, mode + state, _ = s.loadOAuthState() + state.decorate(v, rec, s.now()) + return v, true, nil +} + +// oauthOnlyBindingClients returns the ids of clients with a browser-login entry +// but no kind=client API-key record whose binding pin is from, sorted. +func (s *ClientsService) oauthOnlyBindingClients(all []auth.AgentToken, from string) []string { + o := s.oauthStore() + if o == nil { + return nil + } + bindings, err := o.ListOAuthClientBindings() + if err != nil || len(bindings) == 0 { + return nil + } + var ids []string + for id, b := range bindings { + if rec := clientRecord(all, id); rec != nil && rec.Kind == auth.KindClient { + continue // listed through its record + } + if b.ProfilePin == from { + ids = append(ids, id) + } + } + sort.Strings(ids) + return ids +} + +// --- forget and revoke -------------------------------------------------------------- + +// oauthForgetFunc is the store call a forget or revoke makes for a client that +// has browser-login storage: ForgetClient deletes grants and the entry, +// RevokeClient marks the key and every grant revoked and keeps them for +// display. It returns the API-key record, or a revoked stand-in carrying the +// binding for a client that has none (so the surfaces and the audit record read +// the same). +func (s *ClientsService) oauthForgetFunc(o oauthClientStore, change profile.ChangeKind) func(string) (*auth.AgentToken, error) { + return func(clientID string) (*auth.AgentToken, error) { + entry, _ := o.GetOAuthClientBinding(clientID) + var rec *auth.AgentToken + var err error + if change == profile.ChangeRevoke { + rec, err = o.RevokeClient(clientID, s.now().UTC()) + } else { + rec, err = o.ForgetClient(clientID) + } + if err != nil { + return nil, err + } + if rec == nil { + standIn := &auth.AgentToken{ + Name: auth.ClientTokenName(clientID), Kind: auth.KindClient, ClientID: clientID, + Revoked: true, ExpiresAt: time.Time{}, + } + if entry != nil { + standIn.ProfilePin, standIn.ProfileMode, standIn.DisplayName = entry.ProfilePin, entry.ProfileMode, entry.DisplayName + } + rec = standIn + } + return rec, nil + } +} + +// RevokeAPIKey revokes the client's API key alone: its browser logins and its +// binding stay (Spec 132). It writes a `revoke` record and emits +// credentials.changed. A client with no active API key is +// *NoClientCredentialError. +func (s *ClientsService) RevokeAPIKey(ctx context.Context, a Actor, clientID string) (*ClientCredentialView, error) { + if !auth.ValidClientID(clientID) { + return nil, &ValidationError{Field: "id", Message: fmt.Sprintf("invalid client id %q", clientID)} + } + s.mu.Lock() + defer s.mu.Unlock() + all, err := s.records() + if err != nil { + return nil, err + } + rec := clientRecord(all, clientID) + if state := s.stateOf(rec); rec == nil || rec.Kind != auth.KindClient || rec.Revoked { + return nil, &NoClientCredentialError{ClientID: clientID, State: state} + } + var revoked *auth.AgentToken + if o := s.oauthStore(); o != nil { + revoked, err = o.RevokeClientAPIKey(clientID) + } else { + revoked, err = s.store.ForgetClientCredential(clientID) + } + if err != nil { + if errors.Is(err, storage.ErrClientCredentialNotFound) { + return nil, &NoClientCredentialError{ClientID: clientID, State: profile.CredentialStateNone} + } + return nil, err + } + s.writeChange(ctx, a, changeRecord{ + change: profile.ChangeRevoke, profile: revoked.ProfilePin, previousProfile: revoked.ProfilePin, + clientID: clientID, tokenName: revoked.Name, + diff: map[string]interface{}{"credential_kind": "api_key", "via": viaOf(a), "changed": true}, + }) + if s.publish != nil { + s.publish(newEvent(EventTypeCredentialsChanged, map[string]any{ + "kind": CredentialKindClient, "id": clientID, "token_name": revoked.Name, + "change": string(profile.ChangeRevoke), "profile": revoked.ProfilePin, + })) + } + if s.notifier != nil { + s.notifier.NotifyBindingChanged(revoked.Name) + } + v := s.view(revoked) + if st, lerr := s.loadOAuthState(); lerr == nil { + st.decorate(v, revoked, s.now()) + } + return v, nil +} + +// --- startup --------------------------------------------------------------------------- + +// repairOAuthBindings makes every client that has both an API-key record and a +// browser-login entry agree (the record is the truth) and logs what it did at +// WARN. It runs once at startup, before serving. On a database that never used +// browser login it opens no write transaction. +func (r *Runtime) repairOAuthBindings() { + sm := r.storageManager + if sm == nil { + return + } + repaired, skipped, err := sm.RepairOAuthClientBindings() + if err != nil { + r.logger.Warn("browser login: cannot check client bindings at startup", zap.Error(err)) + return + } + if len(repaired) > 0 { + r.logger.Warn("browser login: repaired client bindings that differed from the API-key record", + zap.Strings("clients", repaired)) + } + if len(skipped) > 0 { + r.logger.Warn("browser login: left client bindings alone because the API-key binding is invalid", + zap.Strings("clients", skipped)) + } +} diff --git a/internal/runtime/clients_service_reconcile.go b/internal/runtime/clients_service_reconcile.go index 6d0f27b27..6138b92cc 100644 --- a/internal/runtime/clients_service_reconcile.go +++ b/internal/runtime/clients_service_reconcile.go @@ -155,7 +155,7 @@ func (s *ClientsService) Warnings(states map[string]profile.CredentialState) []W Message: fmt.Sprintf("anonymous callers are denied while %s could be bypassed without auth", strings.Join(names, ", ")), Action: &WarningAction{Kind: string(profile.FixChangeSetting), Target: "require_mcp_auth"}, Bindings: active, - Fixes: g.BindingGuardFixes(GuardState{Config: cfg, Tokens: guardedOnly(all)}, active), + Fixes: g.BindingGuardFixes(GuardState{Config: cfg, Tokens: guardedOnly(all), OAuthBindings: s.oauthBindingsBestEffort()}, active), }) } now := s.now() diff --git a/internal/runtime/clients_service_restore_reason.go b/internal/runtime/clients_service_restore_reason.go new file mode 100644 index 000000000..fa2f616d4 --- /dev/null +++ b/internal/runtime/clients_service_restore_reason.go @@ -0,0 +1,27 @@ +package runtime + +import "go.uber.org/zap" + +// Reasons a connect rollback does not restore the prior binding. +const ( + restoreSkippedGuard = "guard" + restoreSkippedInspectError = "inspect_error" +) + +// restoreSkipReason answers whether the rollback of a connect for clientID must +// skip restoring the prior binding: "" restores as before, "guard" when the +// guard now refuses the restored state, "inspect_error" when that could not be +// evaluated. The revocation of the fresh API key never depends on this: an +// inspection failure only costs the optional restore, and is logged (s.mu held). +func (s *ClientsService) restoreSkipReason(clientID string) string { + refused, err := s.restoreRefusedInner(clientID) + switch { + case err != nil: + s.logger.Warn("connect rollback: cannot evaluate the binding restore; revoking the key without restoring", + zap.String("client_id", clientID), zap.Error(err)) + return restoreSkippedInspectError + case refused: + return restoreSkippedGuard + } + return "" +} diff --git a/internal/runtime/clients_service_rollback.go b/internal/runtime/clients_service_rollback.go new file mode 100644 index 000000000..20b4288ed --- /dev/null +++ b/internal/runtime/clients_service_rollback.go @@ -0,0 +1,68 @@ +package runtime + +import ( + "errors" + "fmt" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +// restoreRefusedInner reports whether undoing a connect (restoring the binding +// the revoked record replaced) would create a binding the guard now refuses +// (s.mu held). It only matters for a client that has LIVE browser logins: the +// restore also rewrites their binding, and the configuration may have changed +// since the connect. The candidate is the API key revoked with the prior +// binding plus the surviving live logins bound to it. A client without live +// logins, or without a prior binding to restore, answers false: the rollback +// behaves exactly as before. A read error is returned (fail closed). +func (s *ClientsService) restoreRefusedInner(clientID string) (bool, error) { + o := s.oauthStore() + has, err := s.hasLoginRecords(o, clientID) + if err != nil || !has { + return false, err + } + grants, err := o.ListOAuthGrants() + if err != nil { + return false, fmt.Errorf("cannot read browser logins: %w", err) + } + live := false + for i := range grants { + if grants[i].Client == clientID && GrantStateOf(&grants[i], s.now()) == GrantStateActive { + live = true + } + } + if !live { + return false, nil + } + all, err := s.records() + if err != nil { + return false, err + } + rec := clientRecord(all, clientID) + if rec == nil || rec.Kind != auth.KindClient || rec.PriorProfileMode == "" { + return false, nil + } + oauth, err := s.loadOAuthBindings() + if err != nil { + return false, err + } + next := *rec + next.Revoked = true + next.ProfilePin, next.ProfileMode = rec.PriorProfilePin, rec.PriorProfileMode + cfg := s.cfg() + gerr := CheckBindingGuard(s.guard(), + GuardState{Config: cfg, Tokens: guardedOnly(all), OAuthBindings: oauth}, + GuardState{Config: cfg, Tokens: candidateTokens(all, clientID, &next), + OAuthBindings: repinOAuthClient(oauth, clientID, next.ProfilePin, next.ProfileMode)}) + var ge *BindingGuardError + if errors.As(gerr, &ge) { + return true, nil + } + return false, gerr +} + +// revokeKeyKeepingBinding revokes the API key alone and leaves the binding of +// the client's logins as it is (storage.RevokeClientAPIKey, the one writer). +func (s *ClientsService) revokeKeyKeepingBinding(clientID string) (*auth.AgentToken, error) { + return s.oauthStore().RevokeClientAPIKey(clientID) +} diff --git a/internal/runtime/clients_service_upgrade.go b/internal/runtime/clients_service_upgrade.go index ec04ccf22..6f14e674b 100644 --- a/internal/runtime/clients_service_upgrade.go +++ b/internal/runtime/clients_service_upgrade.go @@ -260,8 +260,13 @@ func (s *ClientsService) upgradeGuard(rows []UpgradeRow, req UpgradeRequest) err return err } cfg := s.cfg() - current := GuardState{Config: cfg, Tokens: guardedOnly(all)} + oauth, err := s.loadOAuthBindings() + if err != nil { + return err + } + current := GuardState{Config: cfg, Tokens: guardedOnly(all), OAuthBindings: oauth} tokens := guardedOnly(all) + candOAuth := oauth now := s.now().UTC() for _, r := range rows { next := auth.AgentToken{ @@ -269,8 +274,9 @@ func (s *ClientsService) upgradeGuard(rows []UpgradeRow, req UpgradeRequest) err ProfilePin: *req.Profile, ProfileMode: mode, CreatedAt: now, ExpiresAt: now.Add(clientCredentialTTL), } tokens = candidateTokens(tokens, r.ClientID, &next) + candOAuth = repinOAuthClient(candOAuth, r.ClientID, next.ProfilePin, next.ProfileMode) } - return CheckBindingGuard(s.guard(), current, GuardState{Config: cfg, Tokens: tokens}) + return CheckBindingGuard(s.guard(), current, GuardState{Config: cfg, Tokens: tokens, OAuthBindings: candOAuth}) } // PreviewAdminKeyUpgrade classifies every supported client that holds the admin diff --git a/internal/runtime/commit.go b/internal/runtime/commit.go index a392cf4cc..6877b4070 100644 --- a/internal/runtime/commit.go +++ b/internal/runtime/commit.go @@ -956,6 +956,18 @@ func (r *Runtime) commitLocked(reason string, fn func(tx *CommitTx) error) (*Com h(reason) } + // Spec 132 R15: a commit in which browser login goes from on to off cancels + // every pending and approved sign-in request BEFORE the new configuration + // becomes visible, on the API update path and the file-reload path alike + // (both end here). It does not depend on config.reloaded, which is + // asynchronous and may be dropped. The lifecycle lock taken here is held until + // the function returns, that is, past the publish below and the r.cfg swap, so + // a BeginAuthorization either created its request before this ran or sees the + // switch off. See the lock-order note on OAuthLoginService. + if base.Config != nil && base.Config.MCPOAuthEnabled && !tx.next.MCPOAuthEnabled && r.oauthLoginService != nil { + defer r.oauthLoginService.beginDisable("feature_disabled")() + } + // Step 8: publish. snap, perr := r.configSvc.Publish(prepared) if perr != nil { diff --git a/internal/runtime/config_funnel.go b/internal/runtime/config_funnel.go index b768f38df..55a9cd6eb 100644 --- a/internal/runtime/config_funnel.go +++ b/internal/runtime/config_funnel.go @@ -103,13 +103,21 @@ func (r *Runtime) MutateConfig( if err != nil { return fail(fmt.Errorf("cannot inspect client bindings: %w", err)) } + oauthCurrent, err := r.oauthBindingSnapshot() + if err != nil { + return fail(fmt.Errorf("cannot inspect browser-login bindings: %w", err)) + } + oauthCandidate := oauthCurrent + if tokens.active() { + oauthCandidate = repinOAuthBindings(oauthCurrent, tokens.From, tokens.To) + } candidateTokens := current if tokens.active() { candidateTokens = rewriteClientPins(current, tokens.From, tokens.To) } if err := CheckBindingGuard(r.BindingGuard(), - GuardState{Config: r.Config(), Tokens: current}, - GuardState{Config: desired, Tokens: candidateTokens}); err != nil { + GuardState{Config: r.Config(), Tokens: current, OAuthBindings: oauthCurrent}, + GuardState{Config: desired, Tokens: candidateTokens, OAuthBindings: oauthCandidate}); err != nil { return fail(err) } @@ -219,8 +227,12 @@ func (r *Runtime) GuardedApplyConfig(newCfg *config.Config, cfgPath string) (*Co if err != nil { return nil, fmt.Errorf("cannot inspect client bindings: %w", err) } - current := GuardState{Config: r.Config(), Tokens: tokens} - candidate := GuardState{Config: newCfg, Tokens: tokens} + oauth, err := r.oauthBindingSnapshot() + if err != nil { + return nil, fmt.Errorf("cannot inspect browser-login bindings: %w", err) + } + current := GuardState{Config: r.Config(), Tokens: tokens, OAuthBindings: oauth} + candidate := GuardState{Config: newCfg, Tokens: tokens, OAuthBindings: oauth} if err := CheckBindingGuard(r.BindingGuard(), current, candidate); err != nil { return nil, err } diff --git a/internal/runtime/credential_input_screen.go b/internal/runtime/credential_input_screen.go index 29d6911bb..00001e754 100644 --- a/internal/runtime/credential_input_screen.go +++ b/internal/runtime/credential_input_screen.go @@ -10,6 +10,7 @@ import ( "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" "github.com/smart-mcp-proxy/mcpproxy-go/internal/profile" "github.com/smart-mcp-proxy/mcpproxy-go/internal/security" ) @@ -117,7 +118,8 @@ func (c *CredentialScreen) SecretShaped(s string) bool { return false } lower := strings.ToLower(s) - if strings.Contains(lower, auth.TokenPrefixStr) || strings.Contains(lower, auth.ClientTokenPrefixStr) { + if strings.Contains(lower, auth.TokenPrefixStr) || strings.Contains(lower, auth.ClientTokenPrefixStr) || + strings.Contains(lower, mcplogin.AccessTokenPrefix) || strings.Contains(lower, mcplogin.RefreshTokenPrefix) { return true } // Every nonempty configured key is compared, whatever its length (A24): diff --git a/internal/runtime/credentials_service.go b/internal/runtime/credentials_service.go index 93439d2a7..632ecd9d6 100644 --- a/internal/runtime/credentials_service.go +++ b/internal/runtime/credentials_service.go @@ -44,6 +44,8 @@ type CredentialsService struct { mu *sync.Mutex logger *zap.Logger generate func() (string, error) + // oauth revokes one browser login (Spec 132). Nil in tests that do not wire it. + oauth *OAuthLoginService } // CredentialTokenStore is the token-store surface the service needs. Every @@ -180,6 +182,15 @@ type CredentialView struct { // RateLimit is the token's own call budget (issue #1699), set at issue // time. Absent when the token has none and follows agent_token_rate_limit. RateLimit *auth.TokenRateLimit `json:"rate_limit,omitempty"` + + // The fields below describe a browser login (kind browser_login, Spec 132); + // they are empty for every other kind. ID is the grant id and Client the + // Clients hub id. + Client string `json:"client,omitempty"` + ReportedName string `json:"reported_name,omitempty"` + RedirectHost string `json:"redirect_host,omitempty"` + ObservedName string `json:"observed_name,omitempty"` + NameMismatch *bool `json:"name_mismatch,omitempty"` } // CredentialStateOf classifies a record: revoked over expired over active. @@ -339,6 +350,8 @@ type IssueTokenRequest struct { // token name (the OWNERLESS namespace only, data-model §9). type CredentialRef struct { Client, Token string + // Grant, with Client, names ONE browser login of the client (Spec 132). + Grant string // EnforceWriteGates (MCP) re-checks read_only_mode and disable_management // under bindingWriteMu, so a mutation queued behind a config write that // turns a gate on is refused (the handler's check alone is a TOCTOU). @@ -712,7 +725,11 @@ func (s *CredentialsService) IssueToken(ctx context.Context, a Actor, req IssueT if req.EnforceGuard { current := guardedOnly(all) next := append(append([]auth.AgentToken(nil), current...), candidate) - if err := CheckBindingGuard(s.guard(), GuardState{Config: cfg, Tokens: current}, GuardState{Config: cfg, Tokens: next}); err != nil { + oauth, err := LoadOAuthBindings(s.tokens, s.now()) + if err != nil { + return nil, err // fail closed: an unreadable browser-login store refuses the issue + } + if err := CheckBindingGuard(s.guard(), GuardState{Config: cfg, Tokens: current, OAuthBindings: oauth}, GuardState{Config: cfg, Tokens: next, OAuthBindings: oauth}); err != nil { return nil, err } } @@ -941,6 +958,16 @@ func (s *CredentialsService) issueClientMCP(ctx context.Context, a Actor, req Is Msg: fmt.Sprintf("client %s already exists (%s); choose a new id", req.ID, state)} } } + // 8. A client that has browser logins but no record exists too: create_client + // must not "create" it and rebind it (Spec 132). + hasLogins, herr := s.clients.hasLoginRecords(s.clients.oauthStore(), req.ID) + if herr != nil { + return nil, herr + } + if hasLogins { + return nil, &CredentialError{ErrCode: profile.CredentialErrorCodeIdentityExists, Field: "client", State: "browser_login", Status: 409, + Msg: fmt.Sprintf("client %s already exists (browser_login); choose a new id", req.ID)} + } profileArg := req.Profile return s.mintClientLocked(ctx, a, req, &profileArg, &mode, expiresAt) } @@ -986,11 +1013,19 @@ func (s *CredentialsService) Revoke(ctx context.Context, a Actor, ref Credential if (ref.Client == "") == (ref.Token == "") { return nil, credErr(profile.CredentialErrorCodeInvalidArgument, "client", "exactly one of client or token is required", 400) } + if ref.Grant != "" && ref.Client == "" { + return nil, credErr(profile.CredentialErrorCodeInvalidArgument, "grant", "a grant is revoked together with its client", 400) + } s.mu.Lock() defer s.mu.Unlock() if err := s.writeGateError(ref.EnforceWriteGates); err != nil { return nil, err } + if ref.Grant != "" { + // The login service reads the actor from the context: stamp the one this + // call was given, as every other branch uses it. + return s.revokeGrantLocked(ContextWithActor(ctx, a), ref.Client, ref.Grant) + } if ref.Client != "" { return s.revokeClientLocked(ctx, a, ref.Client) } @@ -1011,6 +1046,30 @@ func (s *CredentialsService) Revoke(ctx context.Context, a Actor, ref Credential return nil, credErr(profile.CredentialErrorCodeReservedIdentity, "token", fmt.Sprintf("token %s is a client credential; revoke it with client=%s", ref.Token, before.ClientID), 400) } + if before.Kind == auth.KindClient { + // The legacy token-name door (DELETE /tokens/client-) used to cut a client + // off completely. It still does: a client that has browser logins goes + // through the client revoke (key, every login, request cancellation). One + // without logins keeps exactly the old result, row and events; its pending + // requests are cancelled either way. + // + // A service built without a clients service (a supported construction, + // also the HTTP token-service fallback) has nothing to cancel; whether the + // client has logins is read through the storage interface it does have. + if s.clients != nil { + s.clients.cancelLoginRequests(before.ClientID) + } + hasLogins, herr := s.hasLoginRecordsFor(before.ClientID) + if herr != nil { + return nil, herr + } + if hasLogins { + if s.clients == nil { + return nil, ErrCredentialsUnavailable // cannot cascade: refuse, nothing half-done + } + return s.revokeClientLocked(ctx, a, before.ClientID) + } + } cfg := s.cfg() if before.Revoked { return &RevokeResult{View: ViewOf(before, cfg, s.now())}, nil @@ -1112,20 +1171,48 @@ func (s *CredentialsService) revokeClientLocked(ctx context.Context, a Actor, cl return nil, credErr(profile.CredentialErrorCodeInvalidArgument, "client", `invalid argument "client": must be lower-case letters, digits, '-' or '_', at most 56 characters`, 400) } + // Cancel the client's pending AND approved sign-in requests before any + // idempotent early return: a revoke that changes nothing stored must still + // kill a login that was approved but not yet exchanged (Spec 132 R15). + s.clients.cancelLoginRequests(clientID) all, err := s.clients.records() if err != nil { return nil, err } rec := clientRecord(all, clientID) - if rec == nil || rec.Kind != auth.KindClient { + hasKey := rec != nil && rec.Kind == auth.KindClient + // Spec 132: a client with browser logins is a client even without an API + // key, and revoking it revokes every login too. + hasLogins, err := s.clients.hasLoginRecords(s.clients.oauthStore(), clientID) + if err != nil { + return nil, err + } + if !hasKey && !hasLogins { return nil, s.notFound("client", clientID) } cfg := s.cfg() - if rec.Revoked { - return &RevokeResult{View: ViewOf(rec, cfg, s.now()), ClientConfigUntouched: true}, nil + if hasKey && rec.Revoked { + live := false + if hasLogins { + if live, err = s.hasLiveGrant(clientID, s.now()); err != nil { + return nil, err // fail closed: an unreadable list is not "nothing live" + } + } + if !live { + return &RevokeResult{View: ViewOf(rec, cfg, s.now()), ClientConfigUntouched: true}, nil + } + } + var view CredentialView + if hasKey { + view = ViewOf(rec, cfg, s.now()) + } else { + st, err := s.clients.loadOAuthState() + if err != nil { + return nil, err + } + view = s.oauthOnlyCredentialView(clientID, st.bindings[clientID], st.grants[clientID]) } diff := map[string]interface{}{"via": viaOf(a), "changed": true, "client_config_untouched": true} - view := ViewOf(rec, cfg, s.now()) for k, v := range lifecycleDiff(view, a) { if _, set := diff[k]; !set { diff[k] = v @@ -1171,6 +1258,16 @@ func (s *CredentialsService) List(f CredentialFilter) ([]CredentialView, error) } out = append(out, v) } + haveClient := map[string]bool{} // from the UNFILTERED records + for _, t := range ownerlessTokens(all) { + if t.Kind == auth.KindClient { + haveClient[t.ClientID] = true + } + } + out, err = s.listOAuth(f, out, haveClient) + if err != nil { + return nil, err + } sort.Slice(out, func(i, j int) bool { if out[i].Kind != out[j].Kind { return out[i].Kind < out[j].Kind @@ -1204,6 +1301,11 @@ func (s *CredentialsService) Get(ref CredentialRef) (*CredentialView, error) { return nil, fmt.Errorf("cannot read credentials: %w", err) } if rec == nil || (kind == "client") != (rec.Kind == auth.KindClient) { + if kind == "client" { + if v, err := s.getOAuthOnlyClient(ref.Client); err != nil || v != nil { + return v, err + } + } label := ref.Token if kind == "client" { label = ref.Client diff --git a/internal/runtime/credentials_service_nilsafe.go b/internal/runtime/credentials_service_nilsafe.go new file mode 100644 index 000000000..b864c3ddd --- /dev/null +++ b/internal/runtime/credentials_service_nilsafe.go @@ -0,0 +1,22 @@ +package runtime + +// hasLoginRecordsFor reports whether the client has browser-login storage, +// through whichever storage interface this service has: the clients service's +// store when there is one, else the token store itself. A store without +// browser-login storage answers false. A read error is returned (fail closed). +func (s *CredentialsService) hasLoginRecordsFor(clientID string) (bool, error) { + var o oauthClientStore + if s.clients != nil { + o = s.clients.oauthStore() + } else if st, ok := s.tokens.(oauthClientStore); ok { + o = st + } + if o == nil { + return false, nil + } + b, err := o.GetOAuthClientBinding(clientID) + if err != nil { + return false, err + } + return b != nil, nil +} diff --git a/internal/runtime/credentials_service_oauth.go b/internal/runtime/credentials_service_oauth.go new file mode 100644 index 000000000..dc380eb0e --- /dev/null +++ b/internal/runtime/credentials_service_oauth.go @@ -0,0 +1,189 @@ +package runtime + +import ( + "context" + "errors" + "fmt" + "sort" + "time" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/profile" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// Spec 132: the credentials service lists and revokes browser logins next to +// the API keys and tokens it already owns. It never issues one: a login exists +// only through the consent page. + +// CredentialStateLapsed is the state of a browser login whose refresh token +// expired. +const CredentialStateLapsed = "lapsed" + +// SetOAuthLogin installs the browser-login service used to revoke one login. +func (s *CredentialsService) SetOAuthLogin(o *OAuthLoginService) { s.oauth = o } + +// grantView projects a grant to its safe view: no token, no hash. +func (s *CredentialsService) grantView(g *storage.OAuthGrant, st oauthClientsState, binding *storage.OAuthClientBinding) CredentialView { + now := s.now() + exp := g.RefreshExpiresAt + mismatch := OAuthNameMismatch(g.ObservedClientName, st.reported[g.RegistrationID], g.Client) + v := CredentialView{ + Kind: CredentialKindBrowserLogin, ID: g.GrantID, Client: g.Client, TokenName: auth.ClientTokenName(g.Client), + State: GrantStateOf(g, now), CreatedAt: g.ApprovedAt, ExpiresAt: &exp, RevokedAt: g.RevokedAt, + LastUsedAt: g.LastUsedAt, TokenPrefix: g.DisplayPrefix, ReportedName: st.reported[g.RegistrationID], + RedirectHost: redirectHost(g.RedirectURI), ObservedName: g.ObservedClientName, NameMismatch: &mismatch, + } + if binding != nil { + v.Profile, v.Binding, v.ProfileState = binding.ProfilePin, binding.ProfileMode, ProfileStateOf(binding.ProfilePin, s.cfg()) + } else { + v.ProfileState = ProfileStateNone + } + return v +} + +// oauthOnlyCredentialView is the view of a client that has browser logins and +// no API-key record: its state is the best state of its logins. +func (s *CredentialsService) oauthOnlyCredentialView(id string, b storage.OAuthClientBinding, grants []storage.OAuthGrant) CredentialView { + now := s.now() + v := CredentialView{ + Kind: CredentialKindClient, ID: id, TokenName: auth.ClientTokenName(id), DisplayName: b.DisplayName, + Profile: b.ProfilePin, Binding: b.ProfileMode, ProfileState: ProfileStateOf(b.ProfilePin, s.cfg()), + State: CredentialStateRevoked, CreatedAt: b.UpdatedAt, + } + sawExpired := false + for i := range grants { + g := &grants[i] + if v.CreatedAt.IsZero() || g.ApprovedAt.Before(v.CreatedAt) { + v.CreatedAt = g.ApprovedAt + } + if g.LastUsedAt != nil && (v.LastUsedAt == nil || g.LastUsedAt.After(*v.LastUsedAt)) { + t := *g.LastUsedAt + v.LastUsedAt = &t + } + switch GrantStateOf(g, now) { + case GrantStateActive: + v.State = CredentialStateActive + case GrantStateLapsed: + sawExpired = true + } + } + if v.State != CredentialStateActive && sawExpired { + v.State = CredentialStateExpired + } + return v +} + +// listOAuth adds the browser logins (and the clients that have only logins) to +// a List result. It adds nothing while the feature was never used. +func (s *CredentialsService) listOAuth(f CredentialFilter, out []CredentialView, have map[string]bool) ([]CredentialView, error) { + if s.clients == nil { + return out, nil + } + st, err := s.clients.loadOAuthState() + if err != nil { + return nil, err + } + if !st.active { + return out, nil + } + add := func(v CredentialView) { + if f.Kind != "" && f.Kind != "all" && f.Kind != v.Kind { + return + } + if f.Profile != "" && f.Profile != v.Profile { + return + } + if f.State != "" && f.State != "all" && f.State != v.State { + return + } + out = append(out, v) + } + if !f.ExcludeClients { + for id, b := range st.bindings { + if !have[id] { + add(s.oauthOnlyCredentialView(id, b, st.grants[id])) + } + } + for id, gs := range st.grants { + b := st.bindings[id] + for i := range gs { + add(s.grantView(&gs[i], st, &b)) + } + } + } + sort.Slice(out, func(i, j int) bool { + if out[i].Kind != out[j].Kind { + return out[i].Kind < out[j].Kind + } + return out[i].ID < out[j].ID + }) + return out, nil +} + +// getOAuthOnlyClient answers Get(client) for a client with browser logins and +// no API-key record; nil when it has none. +func (s *CredentialsService) getOAuthOnlyClient(clientID string) (*CredentialView, error) { + if s.clients == nil { + return nil, nil + } + st, err := s.clients.loadOAuthState() + if err != nil { + return nil, err + } + b, ok := st.bindings[clientID] + if !ok { + return nil, nil + } + v := s.oauthOnlyCredentialView(clientID, b, st.grants[clientID]) + return &v, nil +} + +// revokeGrantLocked revokes one browser login (s.mu held): the login service +// writes the `revoke` record and the credentials.changed event itself. +func (s *CredentialsService) revokeGrantLocked(ctx context.Context, clientID, grantID string) (*RevokeResult, error) { + if s.oauth == nil || s.clients == nil { + return nil, ErrCredentialsUnavailable + } + if !auth.ValidClientID(clientID) { + return nil, credErr(profile.CredentialErrorCodeInvalidArgument, "client", + `invalid argument "client": must be lower-case letters, digits, '-' or '_', at most 56 characters`, 400) + } + changed, err := s.oauth.revokeGrantLocked(ctx, clientID, grantID) + if err != nil { + if errors.Is(err, ErrOAuthGrantNotFound) { + return nil, credErr(profile.CredentialErrorCodeIdentityNotFound, "grant", "browser login not found", 404) + } + return nil, err + } + st, err := s.clients.loadOAuthState() + if err != nil { + return nil, err + } + b := st.bindings[clientID] + for i := range st.grants[clientID] { + if g := &st.grants[clientID][i]; g.GrantID == grantID { + return &RevokeResult{View: s.grantView(g, st, &b), Changed: changed, ClientConfigUntouched: true}, nil + } + } + return nil, credErr(profile.CredentialErrorCodeIdentityNotFound, "grant", "browser login not found", 404) +} + +// hasLiveGrant reports whether the client has a browser login that is neither +// revoked nor lapsed. +func (s *CredentialsService) hasLiveGrant(clientID string, now time.Time) (bool, error) { + o := s.clients.oauthStore() + if o == nil { + return false, nil + } + gs, err := o.ListOAuthGrants() + if err != nil { + return false, fmt.Errorf("cannot read browser logins: %w", err) // fail closed + } + for i := range gs { + if gs[i].Client == clientID && GrantStateOf(&gs[i], now) == GrantStateActive { + return true, nil + } + } + return false, nil +} diff --git a/internal/runtime/events.go b/internal/runtime/events.go index 86ff2eea3..8f3fd6ead 100644 --- a/internal/runtime/events.go +++ b/internal/runtime/events.go @@ -54,6 +54,15 @@ const ( // prefix, purpose or expiry: subscribers refetch. It names identities and // profiles, so it is administrator-only on SSE. EventTypeCredentialsChanged EventType = "credentials.changed" + // EventTypeOAuthAuthorizationPending is emitted (Spec 132) when a browser + // sign-in request waits for an administrator. Payload: {request_id, + // client_id, client_label}; the label is the sanitised, unverified name the + // client reported. It names a client, so it is administrator-only on SSE. + EventTypeOAuthAuthorizationPending EventType = "oauth.authorization_pending" + // EventTypeOAuthAuthorizationDecided is emitted (Spec 132) when a sign-in + // request leaves the pending state. Payload: {request_id, status} with + // status approved, denied or cancelled. Administrator-only on SSE. + EventTypeOAuthAuthorizationDecided EventType = "oauth.authorization_decided" // Activity logging events (RFC-003) // EventTypeActivityToolCallStarted is emitted when a tool execution begins. diff --git a/internal/runtime/oauth_login_clients_test.go b/internal/runtime/oauth_login_clients_test.go new file mode 100644 index 000000000..0ee4d95c5 --- /dev/null +++ b/internal/runtime/oauth_login_clients_test.go @@ -0,0 +1,535 @@ +package runtime + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/profile" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// commitOAuthOnlyClient stores a client that has only a browser login. +func commitOAuthOnlyClient(t *testing.T, sm *storage.Manager, regID, grantID, client, pin, mode string) { + t.Helper() + now := time.Now().UTC() + require.NoError(t, sm.CreateOAuthRegistration(storage.OAuthRegistration{ + ClientID: regID, ReportedName: "App", RedirectURIs: []string{"http://127.0.0.1:9/cb"}, + TokenEndpointAuthMethod: "none", GrantTypes: []string{"authorization_code", "refresh_token"}, CreatedAt: now, + })) + _, err := sm.CommitOAuthLogin(storage.CommitLoginInput{ + Grant: storage.OAuthGrant{ + GrantID: grantID, RegistrationID: regID, Client: client, RedirectURI: "http://127.0.0.1:9/cb", + Resource: "http://127.0.0.1:8080/mcp/oauth/" + client, Issuer: "http://127.0.0.1:8080", + RefreshHash: "rh-" + grantID, AccessHash: "ah-" + grantID, + AccessExpiresAt: now.Add(time.Hour), RefreshExpiresAt: now.Add(24 * time.Hour), + ApprovedAt: now, DisplayPrefix: "mcp_oat_" + grantID[:4], + }, + Client: client, NewClient: true, Pin: pin, Mode: mode, ExpectedBindingRevision: storage.OAuthBindingAbsent, Now: now, + }) + require.NoError(t, err) +} + +// --- views ------------------------------------------------------------------------------------------ + +// While browser login was never used a view is EXACTLY what it was: no new +// field is set, so the JSON carries no new key. +func TestClientViews_UnchangedWhenNeverUsed(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + + list, err := fx.clients.List() + require.NoError(t, err) + require.Len(t, list, 1) + got, err := fx.clients.Get("codex") + require.NoError(t, err) + require.NotNil(t, got) + for _, v := range []ClientCredentialView{list[0], *got} { + assert.Nil(t, v.Credentials) + assert.Nil(t, v.BrowserLoginDisabled) + raw, err := json.Marshal(v) + require.NoError(t, err) + assert.NotContains(t, string(raw), "credentials") + assert.NotContains(t, string(raw), "browser_login_disabled") + } + + cl, err := fx.creds.List(CredentialFilter{}) + require.NoError(t, err) + require.Len(t, cl, 1) + assert.Equal(t, CredentialKindClient, cl[0].Kind) + raw, _ := json.Marshal(cl[0]) + assert.NotContains(t, string(raw), "reported_name") + + ghost, err := fx.clients.Get("ghost") + require.NoError(t, err) + assert.Nil(t, ghost) + used, _ := fx.sm.OAuthLoginEverUsed() + assert.False(t, used) +} + +func TestClientViews_ListCredentialsOnceUsed(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + fx.loginNew("cursor", "rw") + gid := fx.grants()[0].GrantID + require.NoError(t, fx.sm.TouchOAuthGrant(gid, fx.clock.Now(), "totally-other-app")) + + list, err := fx.clients.List() + require.NoError(t, err) + require.Len(t, list, 2) + byID := map[string]ClientCredentialView{} + for _, v := range list { + byID[v.ID] = v + } + // An API-key-only client carries its api_key entry and the flag, no logins. + codex := byID["codex"] + require.Len(t, codex.Credentials, 1) + assert.Equal(t, "api_key", codex.Credentials[0].Kind) + assert.Equal(t, "active", codex.Credentials[0].State) + require.NotNil(t, codex.BrowserLoginDisabled) + assert.False(t, *codex.BrowserLoginDisabled) + + // The OAuth-only client is a row of the hub. + cur := byID["cursor"] + assert.Equal(t, "rw", cur.Profile) + assert.Equal(t, auth.ProfileModeLocked, cur.Mode) + assert.Equal(t, profile.CredentialStateNone, cur.CredentialState, "it has no API key") + assert.Equal(t, "client-cursor", cur.TokenName) + require.Len(t, cur.Credentials, 1) + e := cur.Credentials[0] + assert.Equal(t, "browser_login", e.Kind) + assert.Equal(t, gid, e.GrantID) + assert.Equal(t, "active", e.State) + assert.Equal(t, "cursor ide", e.ReportedName) + assert.Equal(t, "127.0.0.1", e.RedirectHost) + assert.Equal(t, "totally-other-app", e.ObservedName) + require.NotNil(t, e.NameMismatch) + assert.True(t, *e.NameMismatch, "advisory only") + assert.NotNil(t, e.ApprovedAt) + + // The matching name clears the warning. + require.NoError(t, fx.sm.TouchOAuthGrant(gid, fx.clock.Now(), "cursor")) + got, err := fx.clients.Get("cursor") + require.NoError(t, err) + require.NotNil(t, got) + assert.False(t, *got.Credentials[0].NameMismatch) + assert.False(t, *got.BrowserLoginDisabled) + + // The switch off after use: logins stay listed, flagged. + fx.cfg.MCPOAuthEnabled = false + got, err = fx.clients.Get("cursor") + require.NoError(t, err) + assert.True(t, *got.BrowserLoginDisabled) + codex2, _ := fx.clients.Get("codex") + assert.False(t, *codex2.BrowserLoginDisabled, "only a client that has logins is flagged") + + // A lapsed login says so. + fx.clock.Advance(OAuthRefreshTokenTTL + time.Hour) + got, _ = fx.clients.Get("cursor") + assert.Equal(t, "lapsed", got.Credentials[0].State) +} + +func TestCredentialsService_ListsAndGetsBrowserLogins(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + fx.loginNew("cursor", "rw") + gid := fx.grants()[0].GrantID + + all, err := fx.creds.List(CredentialFilter{}) + require.NoError(t, err) + kinds := map[string]CredentialView{} + for _, v := range all { + kinds[v.Kind+"/"+v.ID] = v + } + login := kinds["browser_login/"+gid] + assert.Equal(t, "cursor", login.Client) + assert.Equal(t, "active", login.State) + assert.Equal(t, "rw", login.Profile) + assert.Contains(t, kinds, "client/codex") + assert.Equal(t, "active", kinds["client/cursor"].State, "an OAuth-only client is a client") + + only, err := fx.creds.List(CredentialFilter{Kind: "browser_login"}) + require.NoError(t, err) + require.Len(t, only, 1) + none, err := fx.creds.List(CredentialFilter{ExcludeClients: true}) + require.NoError(t, err) + assert.Empty(t, none, "the server edition has no client credentials and no logins") + + v, err := fx.creds.Get(CredentialRef{Client: "cursor"}) + require.NoError(t, err) + assert.Equal(t, "rw", v.Profile) + _, err = fx.creds.Get(CredentialRef{Client: "ghost"}) + require.Error(t, err) +} + +// --- binding for a client that has only logins --------------------------------------------------------- + +func TestSetBinding_OAuthOnlyClient(t *testing.T) { + fx := newOAuthFx(t) + fx.loginNew("cursor", "ro") + + v, err := fx.clients.SetBinding(fx.ctx(), fx.actor(), "cursor", "rw", nil) + require.NoError(t, err) + assert.Equal(t, "rw", v.Profile) + pin, mode, found, err := fx.sm.CurrentClientBinding("cursor") + require.NoError(t, err) + require.True(t, found) + assert.Equal(t, "rw", pin) + assert.Equal(t, auth.ProfileModeLocked, mode) + rows := fx.changeRows("assign") + require.Len(t, rows, 1) + assert.Equal(t, "cursor", rows[0]["client_id"]) + assert.Equal(t, "rw", rows[0]["profile"]) + assert.Equal(t, "ro", rows[0]["previous_profile"]) + assert.NotEmpty(t, fx.eventsOf(EventTypeClientBindingChanged)) + + sw := auth.ProfileModeSwitchable + _, err = fx.clients.SetBinding(fx.ctx(), fx.actor(), "cursor", "rw", &sw) + require.NoError(t, err) + assert.Len(t, fx.changeRows("unlock"), 1) + + _, err = fx.clients.SetBinding(fx.ctx(), fx.actor(), "cursor", "ghost", nil) + var ve *ValidationError + require.True(t, errors.As(err, &ve)) + // A client with nothing at all is still no_client_credential. + _, err = fx.clients.SetBinding(fx.ctx(), fx.actor(), "ghost", "rw", nil) + var nc *NoClientCredentialError + require.True(t, errors.As(err, &nc)) +} + +func TestSetBinding_OAuthOnlyClientIsJudgedByTheGuard(t *testing.T) { + fx := newOAuthFx(t) + fx.loginNew("cursor", "ro") + fx.guard = StrictOfflineBindingGuard{} + fx.cfg.RequireMCPAuth = false + + _, err := fx.clients.SetBinding(fx.ctx(), fx.actor(), "cursor", "rw", nil) + var ge *BindingGuardError + require.ErrorAs(t, err, &ge, "the live login is an active named binding for the guard") + pin, _, _, _ := fx.sm.CurrentClientBinding("cursor") + assert.Equal(t, "ro", pin, "a refused change writes nothing") + assert.Empty(t, fx.changeRows("assign")) +} + +func TestBulkAssign_MovesOAuthOnlyClients(t *testing.T) { + fx := newOAuthFx(t) + fx.loginNew("cursor", "ro") + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + + moved, skipped, err := fx.clients.BulkAssign(fx.ctx(), fx.actor(), "ro", "rw", nil) + require.NoError(t, err) + assert.Empty(t, skipped) + assert.Equal(t, []string{"codex", "cursor"}, moved) + pin, _, _, _ := fx.sm.CurrentClientBinding("cursor") + assert.Equal(t, "rw", pin) +} + +func TestMintingAnAPIKeyForAnOAuthOnlyClientKeepsOneBinding(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + code := fx.approvedCode(reg, "", ApprovalChoice{Client: ClientChoice{New: &NewClientChoice{ID: "acme"}}, Profile: oauthStrp("ro")}) + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + require.Nil(t, terr) + + _, secret, err := fx.clients.Add(fx.ctx(), fx.actor(), AddRequest{ID: "acme", Profile: "rw"}) + require.NoError(t, err) + assert.NotEmpty(t, secret) + pin, _, _, err := fx.sm.CurrentClientBinding("acme") + require.NoError(t, err) + assert.Equal(t, "rw", pin) + b, err := fx.sm.GetOAuthClientBinding("acme") + require.NoError(t, err) + assert.Equal(t, "rw", b.ProfilePin, "both copies carry the binding the caller asked for") +} + +// --- forget, revoke --------------------------------------------------------------------------------------- + +func TestForgetClient_DeletesTheLoginsAndTheBinding(t *testing.T) { + fx := newOAuthFx(t) + fx.loginNew("cursor", "ro") + _, err := fx.clients.Forget(fx.ctx(), fx.actor(), "cursor", false) + require.NoError(t, err) + assert.Empty(t, fx.grants()) + b, _ := fx.sm.GetOAuthClientBinding("cursor") + assert.Nil(t, b) + got, _ := fx.clients.Get("cursor") + assert.Nil(t, got) + assert.Len(t, fx.changeRows("forget"), 1) + // Forgetting something that has nothing is still the old refusal. + _, err = fx.clients.Forget(fx.ctx(), fx.actor(), "cursor", false) + var nc *NoClientCredentialError + require.True(t, errors.As(err, &nc)) +} + +func TestRevokeClient_RevokesTheKeyAndEveryLoginAndKeepsThemForDisplay(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + res, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + require.Nil(t, terr) + + r, err := fx.creds.Revoke(fx.ctx(), fx.actor(), CredentialRef{Client: "codex"}, false) + require.NoError(t, err) + assert.True(t, r.Changed) + tok, _ := fx.sm.GetAgentTokenByName("client-codex") + assert.True(t, tok.Revoked) + gs := fx.grants() + require.Len(t, gs, 1) + assert.True(t, gs[0].Revoked) + assert.Equal(t, storage.OAuthRevokeClientRevoked, gs[0].RevokeReason) + _, _, aerr := fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth/codex", fx.clock.Now()) + assert.ErrorIs(t, aerr, ErrOAuthUnauthorized, "a live session's next request is refused") + assert.Len(t, fx.changeRows("revoke"), 1) + + // An API key that is already revoked with a live login still revokes the login. + fx.mintClient("zed", "ro", auth.ProfileModeLocked) + regZ := fx.register() + idZ := fx.authorize(regZ, "zed") + revZ, _ := fx.sm.ClientBindingRevision("zed") + redirectZ, err := fx.svc.Approve(fx.ctx(), idZ, ApprovalChoice{BindingRevision: revZ}) + require.NoError(t, err) + _, terr = fx.svc.Exchange(fx.tokenInput(regZ, oauthCodeOf(t, redirectZ))) + require.Nil(t, terr) + _, err = fx.clients.RevokeAPIKey(fx.ctx(), fx.actor(), "zed") + require.NoError(t, err) + r, err = fx.creds.Revoke(fx.ctx(), fx.actor(), CredentialRef{Client: "zed"}, false) + require.NoError(t, err) + assert.True(t, r.Changed, "the revoked key does not hide a live login") + for _, g := range fx.grants() { + assert.True(t, g.Revoked, g.Client) + } +} + +func TestRevokeClient_OAuthOnlyClient(t *testing.T) { + fx := newOAuthFx(t) + fx.loginNew("cursor", "ro") + r, err := fx.creds.Revoke(fx.ctx(), fx.actor(), CredentialRef{Client: "cursor"}, false) + require.NoError(t, err) + assert.True(t, r.Changed) + assert.Equal(t, CredentialStateRevoked, r.View.State) + require.Len(t, fx.grants(), 1) + assert.True(t, fx.grants()[0].Revoked) + b, _ := fx.sm.GetOAuthClientBinding("cursor") + assert.NotNil(t, b, "kept for display") + evs := fx.eventsOf(EventTypeCredentialsChanged) + assert.Equal(t, "revoke", evs[len(evs)-1].Payload["change"]) +} + +func TestRevokeAPIKey_LeavesTheLoginsAndTheBinding(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + res, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + require.Nil(t, terr) + + v, err := fx.clients.RevokeAPIKey(fx.ctx(), fx.actor(), "codex") + require.NoError(t, err) + assert.Equal(t, profile.CredentialStateRevoked, v.CredentialState) + _, _, aerr := fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth/codex", fx.clock.Now()) + assert.NoError(t, aerr, "the login keeps working") + pin, _, _, _ := fx.sm.CurrentClientBinding("codex") + assert.Equal(t, "ro", pin) + assert.False(t, fx.grants()[0].Revoked) + + _, err = fx.clients.RevokeAPIKey(fx.ctx(), fx.actor(), "codex") + var nc *NoClientCredentialError + require.True(t, errors.As(err, &nc), "no API key left") + _, err = fx.clients.RevokeAPIKey(fx.ctx(), fx.actor(), "ghost") + require.True(t, errors.As(err, &nc)) +} + +func TestCredentialsRevoke_OneGrant(t *testing.T) { + fx := newOAuthFx(t) + _, res := fx.loginNew("cursor", "ro") + gid := fx.grants()[0].GrantID + r, err := fx.creds.Revoke(fx.ctx(), fx.actor(), CredentialRef{Client: "cursor", Grant: gid}, false) + require.NoError(t, err) + assert.True(t, r.Changed) + assert.Equal(t, "browser_login", r.View.Kind) + assert.Equal(t, "revoked", r.View.State) + _, _, aerr := fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth/cursor", fx.clock.Now()) + assert.ErrorIs(t, aerr, ErrOAuthUnauthorized) + + _, err = fx.creds.Revoke(fx.ctx(), fx.actor(), CredentialRef{Client: "cursor", Grant: "nope"}, false) + var ce *CredentialError + require.True(t, errors.As(err, &ce)) + assert.Equal(t, 404, ce.Status) + _, err = fx.creds.Revoke(fx.ctx(), fx.actor(), CredentialRef{Token: "x", Grant: gid}, false) + require.Error(t, err) +} + +// --- profiles and the funnel --------------------------------------------------------------------------------- + +func TestProfilesService_OAuthOnlyClientIsAUserOfItsProfile(t *testing.T) { + h := newProfilesHarness(t) + ctx := context.Background() + commitOAuthOnlyClient(t, h.rt.StorageManager(), "reg1", "grantAAAAAAAAAAAAAAAAAA", "acme", "ro", auth.ProfileModeLocked) + + u, err := h.svc.UsedBy("ro") + require.NoError(t, err) + require.Len(t, u.Clients, 1) + assert.Equal(t, "acme", u.Clients[0].ID) + + // Delete is refused while it points at the profile. + _, err = h.svc.Delete(ctx, h.actor(), "ro", "", false) + var inUse *ProfileInUseError + require.True(t, errors.As(err, &inUse)) + require.Len(t, inUse.UsedBy.Clients, 1) + + // A revoked login no longer counts. + _, err = h.rt.StorageManager().RevokeOAuthGrant("grantAAAAAAAAAAAAAAAAAA", storage.OAuthRevokeAdmin, time.Now()) + require.NoError(t, err) + u, err = h.svc.UsedBy("ro") + require.NoError(t, err) + assert.Empty(t, u.Clients) +} + +func TestProfilesService_ReassignAndRenameMoveTheOAuthOnlyClient(t *testing.T) { + h := newProfilesHarness(t) + ctx := context.Background() + sm := h.rt.StorageManager() + commitOAuthOnlyClient(t, sm, "reg1", "grantAAAAAAAAAAAAAAAAAA", "acme", "ro", auth.ProfileModeLocked) + + _, err := h.svc.Rename(ctx, h.actor(), "ro", "ro2") + require.NoError(t, err) + pin, _, _, _ := sm.CurrentClientBinding("acme") + assert.Equal(t, "ro2", pin, "rename moves its pin") + + _, err = h.svc.Delete(ctx, h.actor(), "ro2", "full", false) + require.NoError(t, err) + pin, _, _, _ = sm.CurrentClientBinding("acme") + assert.Equal(t, "full", pin, "reassign_to moves it") +} + +func TestMutateConfig_FailedApplyRestoresAnOAuthOnlyClient(t *testing.T) { + rt := newFunnelRuntime(t) + sm := rt.StorageManager() + commitOAuthOnlyClient(t, sm, "reg1", "grantAAAAAAAAAAAAAAAAAA", "acme", "ro", auth.ProfileModeLocked) + + blocker := filepath.Join(t.TempDir(), "blocker") + require.NoError(t, os.WriteFile(blocker, []byte("x"), 0o600)) + rt.configSvc.UpdatePath(filepath.Join(blocker, "mcp_config.json")) + + _, _, err := rt.MutateConfig(context.Background(), funnelActor(), func(d *config.Config) (ChangeHint, error) { + d.Profiles[0].Name = "ro2" + return ChangeHint{Kind: profile.ChangeRename, Profile: "ro2", PreviousProfile: "ro"}, nil + }, TokenRewrite{From: "ro", To: "ro2"}) + require.Error(t, err) + pin, _, _, _ := sm.CurrentClientBinding("acme") + assert.Equal(t, "ro", pin, "the failed commit restores the browser-login client") + b, _ := sm.GetOAuthClientBinding("acme") + assert.Equal(t, "ro", b.ProfilePin) +} + +// The funnel judges the whole candidate, browser logins included: a config +// that turns auth off while a live login holds a named binding is refused. +func TestMutateConfig_GuardSeesAnOAuthOnlyBinding(t *testing.T) { + rt := newFunnelRuntime(t) + sm := rt.StorageManager() + commitOAuthOnlyClient(t, sm, "reg1", "grantAAAAAAAAAAAAAAAAAA", "acme", "ro", auth.ProfileModeLocked) + rt.SetBindingGuard(ConservativeBindingGuard{}) + + _, _, err := rt.MutateConfig(context.Background(), funnelActor(), func(d *config.Config) (ChangeHint, error) { + d.RequireMCPAuth = false + return ChangeHint{}, nil + }, TokenRewrite{}) + var ge *BindingGuardError + require.ErrorAs(t, err, &ge) + require.NotEmpty(t, ge.Bindings) + assert.Equal(t, "acme", ge.Bindings[0].ClientID) + + // Once the login is revoked nothing is bound. + _, err = sm.RevokeOAuthGrant("grantAAAAAAAAAAAAAAAAAA", storage.OAuthRevokeAdmin, time.Now()) + require.NoError(t, err) + _, _, err = rt.MutateConfig(context.Background(), funnelActor(), func(d *config.Config) (ChangeHint, error) { + d.RequireMCPAuth = false + return ChangeHint{}, nil + }, TokenRewrite{}) + require.NoError(t, err) +} + +// --- the switch --------------------------------------------------------------------------------------------------- + +// Applying a config in which the switch goes off cancels every pending and +// approved request BEFORE the new config is visible, on the commit path both +// the API update and the file reload end in, with no event delivered. +func TestCommit_TurningTheSwitchOffCancelsSignInRequests(t *testing.T) { + rt := newFunnelRuntime(t) + _, err := rt.Commit("test_on", func(tx *CommitTx) error { + return tx.MutateGlobal(func(c *config.Config) error { c.MCPOAuthEnabled = true; return nil }) + }) + require.NoError(t, err) + svc := rt.OAuthLoginService() + require.True(t, svc.Enabled()) + + reg, rerr, err := svc.Register(mcpRegistration()) + require.NoError(t, err) + require.Nil(t, rerr) + regID := reg["client_id"].(string) + id, aerr := svc.BeginAuthorization(AuthorizeInput{ + Origin: oauthTestOrigin, ClientID: regID, RedirectURI: oauthTestRedirect, State: "s", + CodeChallenge: oauthTestChallenge(), Method: "S256", Resource: oauthTestOrigin + "/mcp/oauth/cursor", ResponseType: "code", + }) + require.Nil(t, aerr) + redirect, err := svc.Approve(context.Background(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + require.NoError(t, err) + code := oauthCodeOf(t, redirect) + pendingID, aerr := svc.BeginAuthorization(AuthorizeInput{ + Origin: oauthTestOrigin, ClientID: regID, RedirectURI: oauthTestRedirect, State: "s", + CodeChallenge: oauthTestChallenge(), Method: "S256", Resource: oauthTestOrigin + "/mcp/oauth", ResponseType: "code", + }) + require.Nil(t, aerr) + + _, err = rt.Commit("test_off", func(tx *CommitTx) error { + return tx.MutateGlobal(func(c *config.Config) error { c.MCPOAuthEnabled = false; return nil }) + }) + require.NoError(t, err) + _, err = rt.Commit("test_on_again", func(tx *CommitTx) error { + return tx.MutateGlobal(func(c *config.Config) error { c.MCPOAuthEnabled = true; return nil }) + }) + require.NoError(t, err) + + _, terr := svc.Exchange(TokenInput{Origin: oauthTestOrigin, Code: code, RedirectURI: oauthTestRedirect, ClientID: regID, CodeVerifier: oauthTestVerifier}) + requireInvalidGrant(t, terr) + _, err = svc.Approve(context.Background(), pendingID, ApprovalChoice{Client: ClientChoice{ID: "x"}}) + assert.ErrorIs(t, err, ErrOAuthRequestNotFound) + used, _ := rt.StorageManager().OAuthLoginEverUsed() + assert.False(t, used) +} + +func mcpRegistration() mcplogin.RegistrationRequest { + return mcplogin.RegistrationRequest{RedirectURIs: []string{oauthTestRedirect}, ClientName: "Cursor"} +} + +// --- startup ------------------------------------------------------------------------------------------------------ + +// RepairOAuthClientBindings runs once at startup; on a database that never +// used browser login it opens no write transaction (the runtime is built in +// every funnel test: a never-used database stays free of the OAuth buckets). +func TestStartup_RepairIsANoOpWithoutBrowserLogin(t *testing.T) { + rt := newFunnelRuntime(t) + rt.repairOAuthBindings() // a second run changes nothing and does not panic + b, err := rt.StorageManager().ListOAuthClientBindings() + require.NoError(t, err) + assert.Empty(t, b) + used, _ := rt.StorageManager().OAuthLoginEverUsed() + assert.False(t, used) +} diff --git a/internal/runtime/oauth_login_consent.go b/internal/runtime/oauth_login_consent.go new file mode 100644 index 000000000..1a7e81c5e --- /dev/null +++ b/internal/runtime/oauth_login_consent.go @@ -0,0 +1,855 @@ +package runtime + +import ( + "context" + "errors" + "fmt" + "net/http" + "sort" + "strings" + "time" + "unicode/utf8" + + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/connect" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/profile" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// --- GET /oauth/authorize ---------------------------------------------------------- + +// AuthorizeInput is the query of GET /oauth/authorize. Origin is the origin of +// this request (mcplogin.Origin). +type AuthorizeInput struct { + Origin, ClientID, RedirectURI, State, CodeChallenge, Method, Resource, ResponseType string +} + +// AuthorizeErrorKind says what the HTTP layer does with a refusal. +type AuthorizeErrorKind int + +const ( + // AuthorizeNoRedirect: an HTML error page (400), never a redirect: the + // client id or redirect URI cannot be trusted. + AuthorizeNoRedirect AuthorizeErrorKind = iota + // AuthorizeNotFound: an HTML 404 page, no redirect (the per-client resource + // names a client that does not exist). + AuthorizeNotFound + // AuthorizeRedirect: redirect to the registered redirect URI with error. + AuthorizeRedirect +) + +// AuthorizeError is a refusal of BeginAuthorization. +type AuthorizeError struct { + Kind AuthorizeErrorKind + Code string // OAuth error code (redirect kind) + Description string + // RedirectURI and State are set for AuthorizeRedirect. + RedirectURI string + State string +} + +func (e *AuthorizeError) Error() string { return e.Code + ": " + e.Description } + +// RedirectURL builds the error redirect from the registered redirect URI, +// keeping its query and appending percent-encoded parameters; state only when +// the client sent one. +func (e *AuthorizeError) RedirectURL() (string, error) { + params := map[string]string{"error": e.Code, "error_description": e.Description} + if e.State != "" { + params["state"] = e.State + } + return mcplogin.BuildRedirect(e.RedirectURI, params) +} + +func authzNoRedirect(desc string) *AuthorizeError { + return &AuthorizeError{Kind: AuthorizeNoRedirect, Code: "invalid_request", Description: desc} +} + +// BeginAuthorization validates an authorization request in the order of +// contracts/oauth-endpoints.md, stores it (10 minutes), marks the registration +// authorized and publishes oauth.authorization_pending. It returns the request +// id the consent URL carries. +func (s *OAuthLoginService) BeginAuthorization(in AuthorizeInput) (string, *AuthorizeError) { + if !s.Enabled() { + return "", &AuthorizeError{Kind: AuthorizeNotFound, Code: "not_found", Description: "not found"} + } + // 1. Unknown client_id, or a redirect URI the registration does not hold: + // no redirect, because neither can be trusted. + reg, err := s.store.GetOAuthRegistration(in.ClientID) + if err != nil || reg == nil { + return "", authzNoRedirect("unknown client_id") + } + redirect, ok := mcplogin.MatchRedirect(reg.RedirectURIs, in.RedirectURI) + if !ok { + return "", authzNoRedirect("redirect_uri is not registered") + } + fail := func(code, desc string) *AuthorizeError { + return &AuthorizeError{Kind: AuthorizeRedirect, Code: code, Description: desc, RedirectURI: redirect, State: in.State} + } + // 2. A per-client resource naming a client that does not exist: 404, no + // redirect, checked before the general resource rule (FR-015). + pathClient, generic, resourceOK := mcplogin.ParseResource(in.Origin, in.Resource) + if resourceOK && !generic && !s.clientExists(pathClient) { + return "", &AuthorizeError{Kind: AuthorizeNotFound, Code: "not_found", Description: "unknown client"} + } + // 3. The rest are redirectable. + if in.ResponseType != "code" { + return "", fail("unsupported_response_type", "only response_type=code is supported") + } + if in.Method != "S256" || !mcplogin.ValidChallenge(in.CodeChallenge) { + return "", fail("invalid_request", "a PKCE S256 code_challenge is required") + } + if !resourceOK { + return "", fail("invalid_target", "resource must be an MCPProxy browser-login address on this origin") + } + reqs, err := s.requests() + if err != nil { + s.logger.Error("browser login: cannot build the request store", zap.Error(err)) + return "", fail("temporarily_unavailable", "try again") + } + // "enabled check -> Create" is one boundary shared with the switch-off + // (lifecycleMu): a request admitted here is either created before CancelAll + // runs, and cancelled by it, or refused because the switch is already off. + // Nothing but those two steps happens under the lock. + s.lifecycleMu.Lock() + if !s.Enabled() { + s.lifecycleMu.Unlock() + return "", &AuthorizeError{Kind: AuthorizeNotFound, Code: "not_found", Description: "not found"} + } + if h := s.testHookBeginAfterEnabled; h != nil { + h() + } + req, err := reqs.Create(mcplogin.Request{ + RegistrationID: reg.ClientID, RedirectURI: redirect, State: in.State, CodeChallenge: in.CodeChallenge, + Resource: in.Origin + mcplogin.ResourcePath(pathClient), Issuer: in.Origin, PathClient: pathClient, + }) + s.lifecycleMu.Unlock() + if err != nil { + if errors.Is(err, mcplogin.ErrTooManyPending) { + return "", fail("temporarily_unavailable", "too many sign-in requests are waiting") + } + s.logger.Error("browser login: cannot store the request", zap.Error(err)) + return "", fail("temporarily_unavailable", "try again") + } + if err := s.store.MarkOAuthRegistrationAuthorized(reg.ClientID, s.now()); err != nil { + s.logger.Warn("browser login: cannot mark the registration authorized", zap.Error(err)) + } + if s.publish != nil { + s.publish(newEvent(EventTypeOAuthAuthorizationPending, map[string]any{ + "request_id": req.ID, "client_id": pathClient, "client_label": clientLabel(reg.ReportedName), + })) + } + return req.ID, nil +} + +func clientLabel(reported string) string { + if strings.TrimSpace(reported) == "" { + return "an application" + } + return reported +} + +// --- client lookups ------------------------------------------------------------------ + +// clientExists: a connect-registry id (supported or not), or an existing client +// record (API key in any state) or browser-login binding. +func (s *OAuthLoginService) clientExists(clientID string) bool { + if connect.FindClient(clientID) != nil { + return true + } + return s.hasClientRecords(clientID) +} + +// hasClientRecords: the client has an API-key record or a browser-login entry +// (a registry id alone does not count). +func (s *OAuthLoginService) hasClientRecords(clientID string) bool { + rec, err := s.store.GetAgentTokenByName(auth.ClientTokenName(clientID)) + if err == nil && rec != nil { + return true + } + b, err := s.store.GetOAuthClientBinding(clientID) + return err == nil && b != nil +} + +// --- views --------------------------------------------------------------------------- + +// BindingView is a client's binding and its revision. +type BindingView struct { + Profile string `json:"profile"` + Mode string `json:"mode"` + Revision string `json:"revision"` +} + +// AuthorizationClientView is the fixed client of a per-client address. +type AuthorizationClientView struct { + ID string `json:"id"` + DisplayName string `json:"display_name"` + Exists bool `json:"exists"` + HasAPIKey bool `json:"has_api_key"` + Logins int `json:"logins"` + Binding *BindingView `json:"binding,omitempty"` +} + +// ExistingClientView is one choice of the generic address. +type ExistingClientView struct { + ID string `json:"id"` + DisplayName string `json:"display_name"` + Binding *BindingView `json:"binding,omitempty"` +} + +// SuggestedClient is the new-client suggestion derived from the reported name. +type SuggestedClient struct { + ID string `json:"id"` + DisplayName string `json:"display_name"` +} + +// ProfileChoice names a profile the page may offer. +type ProfileChoice struct { + Name string `json:"name"` +} + +// PreviousLogin is a live login of THIS registration. +type PreviousLogin struct { + GrantID string `json:"grant_id"` + ApprovedAt time.Time `json:"approved_at"` +} + +// GuardVerdict is the binding guard's refusal as the page shows it. +type GuardVerdict struct { + Code string `json:"code"` + Bindings []BindingRef `json:"bindings"` + Fixes []GuardFix `json:"fixes"` +} + +// AuthorizationSummary is one row of the pending list. +type AuthorizationSummary struct { + ID string `json:"id"` + ClientLabel string `json:"client_label"` + CreatedAt time.Time `json:"created_at"` + ExpiresAt time.Time `json:"expires_at"` +} + +// AuthorizationView is GET /oauth/authorizations/{id} (contracts/rest-admin.md). +type AuthorizationView struct { + ID string `json:"id"` + Status string `json:"status"` + ExpiresAt time.Time `json:"expires_at"` + ReportedName string `json:"reported_name"` + RedirectURI string `json:"redirect_uri"` + Resource string `json:"resource"` + AddressKind string `json:"address_kind"` + Client *AuthorizationClientView `json:"client,omitempty"` + ExistingClients []ExistingClientView `json:"existing_clients,omitempty"` + SuggestedNewClient *SuggestedClient `json:"suggested_new_client,omitempty"` + Profiles []ProfileChoice `json:"profiles"` + ProfileRequired bool `json:"profile_required"` + PreviousLogin *PreviousLogin `json:"previous_login,omitempty"` + Guard *GuardVerdict `json:"guard"` +} + +// PreviewAccess is the access sentence of a proposed choice. +type PreviewAccess struct { + Client string `json:"client"` + Profile string `json:"profile"` + Mode string `json:"mode"` + SameAccessAsExistingClient bool `json:"same_access_as_existing_client"` +} + +// PreviewView is POST /oauth/authorizations/{id}/preview. +type PreviewView struct { + Complete bool `json:"complete"` + Access *PreviewAccess `json:"access,omitempty"` + Guard *GuardVerdict `json:"guard"` +} + +// ListPending returns the pending requests, newest first. +func (s *OAuthLoginService) ListPending() []AuthorizationSummary { + reqs := s.existingRequests() + out := []AuthorizationSummary{} + if reqs == nil || !s.Enabled() { + return out + } + for _, r := range reqs.ListPending() { + label := "an application" + if reg, err := s.store.GetOAuthRegistration(r.RegistrationID); err == nil && reg != nil { + label = clientLabel(reg.ReportedName) + } + out = append(out, AuthorizationSummary{ID: r.ID, ClientLabel: label, CreatedAt: r.CreatedAt, ExpiresAt: r.ExpiresAt}) + } + sort.Slice(out, func(i, j int) bool { return out[i].CreatedAt.After(out[j].CreatedAt) }) + return out +} + +// pendingRequest returns the request when it is still pending. +func (s *OAuthLoginService) pendingRequest(id string) (mcplogin.Request, *mcplogin.Store, error) { + reqs := s.existingRequests() + if reqs == nil || !s.Enabled() { + return mcplogin.Request{}, nil, ErrOAuthRequestNotFound + } + req, ok := reqs.Get(id) + if !ok || req.Status != mcplogin.StatusPending { + return mcplogin.Request{}, nil, ErrOAuthRequestNotFound + } + return req, reqs, nil +} + +// Describe returns the consent page's view of a pending request. The reported +// name is shown and NEVER selects anything. +func (s *OAuthLoginService) Describe(ctx context.Context, requestID string) (*AuthorizationView, error) { + req, _, err := s.pendingRequest(requestID) + if err != nil { + return nil, err + } + reg, err := s.store.GetOAuthRegistration(req.RegistrationID) + if err != nil || reg == nil { + return nil, ErrOAuthRequestNotFound + } + cfg := s.cfg() + all, err := s.store.ListAgentTokens() + if err != nil { + return nil, fmt.Errorf("cannot read client credentials: %w", err) + } + grants, err := s.store.ListOAuthGrants() + if err != nil { + return nil, fmt.Errorf("cannot read browser logins: %w", err) + } + bindings, err := s.store.ListOAuthClientBindings() + if err != nil { + return nil, fmt.Errorf("cannot read browser-login bindings: %w", err) + } + now := s.now() + v := &AuthorizationView{ + ID: req.ID, Status: string(req.Status), ExpiresAt: req.ExpiresAt, ReportedName: reg.ReportedName, + RedirectURI: req.RedirectURI, Resource: req.Resource, Profiles: profileChoices(cfg), + } + liveByClient := map[string]int{} + for i := range grants { + g := &grants[i] + if !g.Revoked && g.RefreshExpiresAt.After(now) { + liveByClient[g.Client]++ + if g.RegistrationID == reg.ClientID && (req.PathClient == "" || g.Client == req.PathClient) && + (v.PreviousLogin == nil || g.ApprovedAt.After(v.PreviousLogin.ApprovedAt)) { + v.PreviousLogin = &PreviousLogin{GrantID: g.GrantID, ApprovedAt: g.ApprovedAt} + } + } + } + bindingOf := func(id string) (*BindingView, bool) { + pin, mode, found, err := s.store.CurrentClientBinding(id) + if err != nil || !found { + return nil, false + } + rev, err := s.store.ClientBindingRevision(id) + if err != nil { + return nil, false + } + return &BindingView{Profile: pin, Mode: mode, Revision: rev}, true + } + + if req.PathClient != "" { + v.AddressKind = "client" + cv := &AuthorizationClientView{ID: req.PathClient, DisplayName: s.displayNameOf(req.PathClient, all, bindings), + Logins: liveByClient[req.PathClient]} + rec := clientRecord(all, req.PathClient) + cv.HasAPIKey = rec != nil && rec.Kind == auth.KindClient + _, hasEntry := bindings[req.PathClient] + cv.Exists = cv.HasAPIKey || hasEntry + if b, ok := bindingOf(req.PathClient); ok && cv.Exists { + cv.Binding = b + } + v.Client = cv + v.ProfileRequired = len(v.Profiles) > 0 && cv.Binding == nil + if cv.Binding != nil { + if perr := s.checkCandidateGuard(cv.ID, cv.Binding.Profile, cv.Binding.Mode); perr != nil { + var ge *BindingGuardError + if errors.As(perr, &ge) { + v.Guard = verdictOf(ge) + } + } + } + } else { + v.AddressKind = "generic" + ids := map[string]bool{} + for i := range all { + if all[i].Kind == auth.KindClient && all[i].UserID == "" { + ids[all[i].ClientID] = true + } + } + for id := range bindings { + ids[id] = true + } + sorted := make([]string, 0, len(ids)) + for id := range ids { + sorted = append(sorted, id) + } + sort.Strings(sorted) + v.ExistingClients = []ExistingClientView{} + for _, id := range sorted { + ev := ExistingClientView{ID: id, DisplayName: s.displayNameOf(id, all, bindings)} + if b, ok := bindingOf(id); ok { + ev.Binding = b + } + v.ExistingClients = append(v.ExistingClients, ev) + } + v.ProfileRequired = len(v.Profiles) > 0 + v.SuggestedNewClient = s.suggestNewClient(reg.ReportedName, ids) + } + return v, nil +} + +func profileChoices(cfg *config.Config) []ProfileChoice { + out := []ProfileChoice{} + if cfg != nil { + for i := range cfg.Profiles { + out = append(out, ProfileChoice{Name: cfg.Profiles[i].Name}) + } + } + return out +} + +func verdictOf(ge *BindingGuardError) *GuardVerdict { + return &GuardVerdict{Code: ge.Code(), Bindings: ge.Bindings, Fixes: ge.Fixes} +} + +// displayNameOf is the registry name, else the record's display name, else the id. +func (s *OAuthLoginService) displayNameOf(id string, all []auth.AgentToken, bindings map[string]storage.OAuthClientBinding) string { + if def := connect.FindClient(id); def != nil && def.Name != "" { + return def.Name + } + if rec := clientRecord(all, id); rec != nil && rec.DisplayName != "" { + return rec.DisplayName + } + if b, ok := bindings[id]; ok && b.DisplayName != "" { + return b.DisplayName + } + return id +} + +// suggestNewClient derives an id from the reported name: lower-case slug of +// letters, digits, '-' and '_', at most 56 characters, made unique against the +// registry and the existing clients ("-2", "-3", ...). It only SUGGESTS: the +// page shows it in an editable field and the administrator submits what they +// want. The suggested display name is the reported name. +func (s *OAuthLoginService) suggestNewClient(reported string, existing map[string]bool) *SuggestedClient { + var b strings.Builder + dash := false + for _, r := range strings.ToLower(reported) { + switch { + case r >= 'a' && r <= 'z', r >= '0' && r <= '9': + b.WriteRune(r) + dash = false + case r == '_' || r == '-': + if b.Len() > 0 && !dash { + b.WriteRune('-') + dash = true + } + default: + if b.Len() > 0 && !dash { + b.WriteRune('-') + dash = true + } + } + } + base := strings.Trim(b.String(), "-_") + if base == "" { + base = "client" + } + if len(base) > 50 { + base = strings.Trim(base[:50], "-_") + } + taken := func(id string) bool { + return existing[id] || connect.FindClient(id) != nil || s.hasClientRecords(id) + } + id := base + for n := 2; taken(id); n++ { + id = fmt.Sprintf("%s-%d", base, n) + } + name := strings.TrimSpace(reported) + if name == "" { + name = id + } + if utf8.RuneCountInString(name) > auth.MaxClientDisplayName { + name = string([]rune(name)[:auth.MaxClientDisplayName]) + } + return &SuggestedClient{ID: id, DisplayName: name} +} + +// --- choice ------------------------------------------------------------------------------ + +// NewClientChoice is a client the approval creates. +type NewClientChoice struct { + ID string `json:"id"` + DisplayName string `json:"display_name,omitempty"` +} + +// ClientChoice is the client of an approval: an existing id, or a new one. +type ClientChoice struct { + ID string `json:"id,omitempty"` + New *NewClientChoice `json:"new,omitempty"` +} + +// ApprovalChoice is the body of preview and approve. Profile nil means "not +// chosen" (an empty string is the explicit choice All servers). +type ApprovalChoice struct { + Client ClientChoice `json:"client"` + Profile *string `json:"profile,omitempty"` + Mode string `json:"mode,omitempty"` + BindingRevision string `json:"binding_revision,omitempty"` + ReplaceGrant string `json:"replace_grant,omitempty"` +} + +// Typed refusals of Preview, Approve and Deny. The REST layer maps them with +// OAuthErrorStatus. +var ( + ErrOAuthRequestNotFound = errors.New("authorization request not found") + ErrOAuthAlreadyDecided = errors.New("authorization request already decided") + ErrOAuthBindingChanged = errors.New("the client's binding changed since it was displayed") + ErrOAuthClientFixed = errors.New("this address fixes the client") + ErrOAuthClientRequired = errors.New("choose a client") + ErrOAuthClientUnknown = errors.New("unknown client") + ErrOAuthProfileRequired = errors.New("choose a profile") + ErrOAuthProfileNotFound = errors.New("unknown profile") + ErrOAuthIdentityExists = errors.New("a client with this id already exists") + ErrOAuthReservedIdentity = errors.New("this id belongs to a supported client") +) + +// OAuthErrorStatus maps a refusal to its wire code and HTTP status +// (contracts/rest-admin.md). ok is false for an error that is not one of them. +func OAuthErrorStatus(err error) (code string, status int, ok bool) { + var ge *BindingGuardError + var ve *ValidationError + switch { + case errors.Is(err, ErrOAuthRequestNotFound): + return "request_not_found", http.StatusNotFound, true + case errors.Is(err, ErrOAuthAlreadyDecided): + return "already_decided", http.StatusConflict, true + case errors.Is(err, ErrOAuthBindingChanged): + return "binding_changed", http.StatusConflict, true + case errors.As(err, &ge): + return ge.Code(), http.StatusConflict, true + case errors.Is(err, ErrOAuthClientFixed): + return "client_fixed", http.StatusUnprocessableEntity, true + case errors.Is(err, ErrOAuthClientRequired): + return "client_required", http.StatusUnprocessableEntity, true + case errors.Is(err, ErrOAuthClientUnknown): + return "client_not_found", http.StatusNotFound, true + case errors.Is(err, ErrOAuthProfileRequired): + return "profile_required", http.StatusUnprocessableEntity, true + case errors.Is(err, ErrOAuthProfileNotFound): + return "profile_not_found", http.StatusNotFound, true + case errors.Is(err, ErrOAuthIdentityExists): + return "identity_exists", http.StatusUnprocessableEntity, true + case errors.Is(err, ErrOAuthReservedIdentity): + return "reserved_identity", http.StatusUnprocessableEntity, true + case errors.As(err, &ve): + return "invalid_" + ve.Field, http.StatusUnprocessableEntity, true + } + return "", 0, false +} + +// resolvedChoice is a validated choice. +type resolvedChoice struct { + clientID string + newClient bool + display string + pin, mode string + revision string // expected binding revision at commit + hasBinding bool + replace string + complete bool +} + +// resolveChoice validates a choice against the request and the stored state. +// An incomplete choice (a required selection is missing) is not an error: it is +// reported as complete=false so a preview can say so. Invalid values are +// errors in both cases. +func (s *OAuthLoginService) resolveChoice(req mcplogin.Request, c ApprovalChoice) (*resolvedChoice, error) { + cfg := s.cfg() + rc := &resolvedChoice{complete: true} + + // 1. Which client. + switch { + case req.PathClient != "": + if c.Client.New != nil || (c.Client.ID != "" && c.Client.ID != req.PathClient) { + return nil, ErrOAuthClientFixed + } + rc.clientID = req.PathClient + if !s.hasClientRecords(rc.clientID) { + def := connect.FindClient(rc.clientID) + if def == nil { + return nil, ErrOAuthClientUnknown // the client vanished since authorize + } + rc.newClient, rc.display = true, def.Name + } + case c.Client.New != nil: + if c.Client.ID != "" { + return nil, &ValidationError{Field: "client", Message: "choose an existing client or a new one, not both"} + } + n := c.Client.New + if !auth.ValidClientID(n.ID) { + return nil, &ValidationError{Field: "client_new_id", Message: fmt.Sprintf( + "invalid client id %q: must be lower-case letters, digits, '-' or '_', start with a letter or digit, and be at most 56 characters", n.ID)} + } + if connect.FindClient(n.ID) != nil { + return nil, ErrOAuthReservedIdentity + } + if s.hasClientRecords(n.ID) { + return nil, ErrOAuthIdentityExists + } + if utf8.RuneCountInString(n.DisplayName) > auth.MaxClientDisplayName { + return nil, &ValidationError{Field: "client_new_display_name", Message: "display name is too long"} + } + rc.clientID, rc.newClient, rc.display = n.ID, true, n.DisplayName + case c.Client.ID != "": + if !s.hasClientRecords(c.Client.ID) { + return nil, ErrOAuthClientUnknown + } + rc.clientID = c.Client.ID + default: + rc.complete = false + } + if !rc.complete { + return rc, nil + } + + // 2. The binding: kept for a client that has one, chosen for a new one. + if !rc.newClient { + pin, mode, found, err := s.store.CurrentClientBinding(rc.clientID) + if err != nil { + return nil, err + } + if !found { + return nil, ErrOAuthClientUnknown + } + rev, err := s.store.ClientBindingRevision(rc.clientID) + if err != nil { + return nil, err + } + if c.BindingRevision != rev { + return nil, ErrOAuthBindingChanged + } + rc.pin, rc.mode, rc.revision, rc.hasBinding = pin, mode, rev, true + } else { + rc.revision = storage.OAuthBindingAbsent + if c.Profile == nil { + if cfg != nil && len(cfg.Profiles) > 0 { + rc.complete = false // profiles exist: nothing is pre-selected + return rc, nil + } + c.Profile = new(string) + } + pin := *c.Profile + if pin != "" && !profileConfigured(cfg, pin) { + return nil, ErrOAuthProfileNotFound + } + var modeArg *string + if c.Mode != "" { + m := c.Mode + modeArg = &m + } + mode, err := resolveMode(pin, modeArg, "") + if err != nil { + return nil, err + } + rc.pin, rc.mode = pin, mode + } + + // 3. Replace the previous login: only a live login of THIS registration + // and of this client; anything else is ignored, never revoked. + if c.ReplaceGrant != "" { + if g, err := s.store.GetOAuthGrant(c.ReplaceGrant); err == nil && g != nil && g.Client == rc.clientID && + !g.Revoked && g.RefreshExpiresAt.After(s.now()) && g.RegistrationID == req.RegistrationID { + rc.replace = g.GrantID + } + } + return rc, nil +} + +func profileConfigured(cfg *config.Config, name string) bool { + if cfg == nil { + return false + } + for i := range cfg.Profiles { + if cfg.Profiles[i].Name == name { + return true + } + } + return false +} + +// checkCandidateGuard runs the binding guard over the state this client's login +// would create (its entry added or replaced with Live true). +func (s *OAuthLoginService) checkCandidateGuard(clientID, pin, mode string) error { + cur, cand, err := s.guardStatesFor(s.cfg(), clientID, pin, mode) + if err != nil { + return err + } + return CheckBindingGuard(s.guard(), cur, cand) +} + +// Preview is the read-only verdict of a proposed choice. It writes nothing. +// A guard refusal is part of the answer, not an error. +func (s *OAuthLoginService) Preview(ctx context.Context, requestID string, c ApprovalChoice) (*PreviewView, error) { + req, _, err := s.pendingRequest(requestID) + if err != nil { + return nil, err + } + rc, err := s.resolveChoice(req, c) + if err != nil { + return nil, err + } + out := &PreviewView{Complete: rc.complete} + if !rc.complete { + return out, nil + } + out.Access = &PreviewAccess{Client: rc.clientID, Profile: rc.pin, Mode: rc.mode, SameAccessAsExistingClient: rc.hasBinding} + if gerr := s.checkCandidateGuard(rc.clientID, rc.pin, rc.mode); gerr != nil { + var ge *BindingGuardError + if errors.As(gerr, &ge) { + out.Guard = verdictOf(ge) + return out, nil + } + return nil, gerr + } + return out, nil +} + +// --- approve and deny ---------------------------------------------------------------------- + +// Approve records the administrator's decision on the in-memory request and +// returns the redirect carrying the single-use code. It stores NO registration, +// login, binding or marker: the login is stored by the token exchange. It +// writes the `approve` activity row (the one thing it persists), naming the +// request's actor with the request id, and publishes +// oauth.authorization_decided. It runs under bindingWriteMu, so no binding +// write interleaves between the revision check and the decision. +func (s *OAuthLoginService) Approve(ctx context.Context, requestID string, c ApprovalChoice) (string, error) { + s.mu.Lock() + defer s.mu.Unlock() + req, reqs, err := s.pendingRequestForDecision(requestID) + if err != nil { + return "", err + } + rc, err := s.resolveChoice(req, c) + if err != nil { + return "", err + } + if !rc.complete { + if rc.clientID == "" { + return "", ErrOAuthClientRequired + } + return "", ErrOAuthProfileRequired + } + if gerr := s.checkCandidateGuard(rc.clientID, rc.pin, rc.mode); gerr != nil { + return "", gerr + } + actor, _ := RequestActor(ctx) + if actor.Surface == "" { + actor.Surface = profile.SurfaceAPI + } + code, err := reqs.Approve(requestID, mcplogin.Decision{ + ClientID: rc.clientID, NewClient: rc.newClient, DisplayName: rc.display, Profile: rc.pin, Mode: rc.mode, + BindingRevision: rc.revision, ReplaceGrantID: rc.replace, ActorKind: actor.Kind, ActorName: actor.Name, + }) + if err != nil { + return "", mapRequestStoreError(err) + } + if h := s.testHookApproveAfterStore; h != nil { + h() + } + // A switch-off cancels without bindingWriteMu, so the approval may have lost + // a race after Store.Approve: re-read the request and write nothing, publish + // nothing and hand out no redirect if it is no longer approved. + // + // The rest runs under lifecycleMu (after bindingWriteMu, the documented + // order), released by the defer at return: final status check, activity row, + // event and redirect are one step, so a switch-off either ran before it + // (refusal, no row) or runs after it (the code is cancelled and the client's + // exchange fails, which is expected). + s.lifecycleMu.Lock() + defer s.lifecycleMu.Unlock() + if h := s.testHookApproveFinalising; h != nil { + h() + } + if cur, ok := reqs.Get(requestID); !ok || cur.Status != mcplogin.StatusApproved { + return "", ErrOAuthRequestNotFound + } + writeChangeRecord(ctx, s.activity, s.logger, s.now(), actor, changeRecord{ + change: profile.ChangeApprove, profile: rc.pin, clientID: rc.clientID, tokenName: auth.ClientTokenName(rc.clientID), + meta: map[string]interface{}{"request_id": requestID}, + }) + s.publishDecided(requestID, string(mcplogin.StatusApproved)) + params := map[string]string{"code": code} + if req.State != "" { + params["state"] = req.State + } + return mcplogin.BuildRedirect(req.RedirectURI, params) +} + +// Deny refuses the request: the redirect carries error=access_denied. +func (s *OAuthLoginService) Deny(ctx context.Context, requestID string) (string, error) { + s.mu.Lock() + defer s.mu.Unlock() + req, reqs, err := s.pendingRequestForDecision(requestID) + if err != nil { + return "", err + } + if err := reqs.Deny(requestID); err != nil { + return "", mapRequestStoreError(err) + } + actor, _ := RequestActor(ctx) + if actor.Surface == "" { + actor.Surface = profile.SurfaceAPI + } + writeChangeRecord(ctx, s.activity, s.logger, s.now(), actor, changeRecord{ + change: profile.ChangeDeny, clientID: req.PathClient, tokenName: authTokenNameOrEmpty(req.PathClient), + meta: map[string]interface{}{"request_id": requestID}, + }) + s.publishDecided(requestID, string(mcplogin.StatusDenied)) + params := map[string]string{"error": "access_denied", "error_description": "the administrator denied the request"} + if req.State != "" { + params["state"] = req.State + } + return mcplogin.BuildRedirect(req.RedirectURI, params) +} + +func authTokenNameOrEmpty(clientID string) string { + if clientID == "" { + return "" + } + return auth.ClientTokenName(clientID) +} + +// pendingRequestForDecision is pendingRequest, but a request that was decided +// already answers ErrOAuthAlreadyDecided instead of not-found. +func (s *OAuthLoginService) pendingRequestForDecision(id string) (mcplogin.Request, *mcplogin.Store, error) { + reqs := s.existingRequests() + if reqs == nil || !s.Enabled() { + return mcplogin.Request{}, nil, ErrOAuthRequestNotFound + } + req, ok := reqs.Get(id) + if !ok { + return mcplogin.Request{}, nil, ErrOAuthRequestNotFound + } + switch req.Status { + case mcplogin.StatusPending: + return req, reqs, nil + case mcplogin.StatusCancelled: + return mcplogin.Request{}, nil, ErrOAuthRequestNotFound + default: + return mcplogin.Request{}, nil, ErrOAuthAlreadyDecided + } +} + +func mapRequestStoreError(err error) error { + switch { + case errors.Is(err, mcplogin.ErrAlreadyDecided): + return ErrOAuthAlreadyDecided + case errors.Is(err, mcplogin.ErrRequestNotFound): + return ErrOAuthRequestNotFound + } + return err +} diff --git a/internal/runtime/oauth_login_exchange_test.go b/internal/runtime/oauth_login_exchange_test.go new file mode 100644 index 000000000..31879d714 --- /dev/null +++ b/internal/runtime/oauth_login_exchange_test.go @@ -0,0 +1,649 @@ +package runtime + +import ( + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/profile" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// approvedCode runs authorize + approve for a fixed client and returns the code. +func (fx *oauthFx) approvedCode(reg, client string, choice ApprovalChoice) string { + fx.t.Helper() + id := fx.authorize(reg, client) + redirect, err := fx.svc.Approve(fx.ctx(), id, choice) + require.NoError(fx.t, err) + return oauthCodeOf(fx.t, redirect) +} + +func requireInvalidGrant(t *testing.T, terr *TokenError) { + t.Helper() + require.NotNil(t, terr) + assert.Equal(t, TokenErrInvalidGrant, terr.Code) +} + +// --- the exchange is the commit --------------------------------------------------------- + +func TestExchange_StoresTheLoginAndWritesTheIssueRow(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + fx.nothingStored() + + res, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + require.Nil(t, terr) + assert.True(t, strings.HasPrefix(res.AccessToken, mcplogin.AccessTokenPrefix)) + assert.True(t, strings.HasPrefix(res.RefreshToken, mcplogin.RefreshTokenPrefix)) + assert.Equal(t, "Bearer", res.TokenType) + assert.Equal(t, 3600, res.ExpiresIn) + + gs := fx.grants() + require.Len(t, gs, 1) + g := gs[0] + assert.Equal(t, "cursor", g.Client) + assert.Equal(t, reg, g.RegistrationID) + assert.Equal(t, oauthTestOrigin+"/mcp/oauth/cursor", g.Resource) + assert.Equal(t, oauthTestOrigin, g.Issuer) + assert.Equal(t, oauthTestRedirect, g.RedirectURI) + assert.Equal(t, "admin", g.ApprovedBy.Name) + assert.NotContains(t, g.AccessHash, res.AccessToken, "only hashes are stored") + pin, mode, found, err := fx.sm.CurrentClientBinding("cursor") + require.NoError(t, err) + require.True(t, found) + assert.Equal(t, "ro", pin) + assert.Equal(t, auth.ProfileModeLocked, mode) + used, _ := fx.sm.OAuthLoginEverUsed() + assert.True(t, used) + + rows := fx.changeRows("issue") + require.Len(t, rows, 1) + assert.Equal(t, g.GrantID, rows[0]["grant_id"]) + assert.Equal(t, "client", rows[0]["trigger"]) + assert.Equal(t, "admin", rows[0]["actor_name"], "the approving administrator, not the client") + assert.Equal(t, map[string]interface{}{"kind": "api_key", "name": "admin"}, rows[0]["approved_by"]) + ev := fx.eventsOf(EventTypeCredentialsChanged) + require.NotEmpty(t, ev) + last := ev[len(ev)-1].Payload + assert.Equal(t, "browser_login", last["kind"]) + assert.Equal(t, "issue", last["change"]) + assert.Equal(t, g.GrantID, last["id"]) + + // The access token authenticates exactly where it was approved. + ac, grant, aerr := fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth/cursor", fx.clock.Now()) + require.NoError(t, aerr) + assert.Equal(t, g.GrantID, grant.GrantID) + assert.Equal(t, auth.CredentialKindOAuth, ac.CredentialKind) + assert.Equal(t, g.GrantID, ac.GrantID) + assert.Equal(t, g.GrantID, ac.TokenGeneration) + assert.Equal(t, "cursor", ac.ClientID) + assert.Equal(t, "client-cursor", ac.AgentName) + assert.Equal(t, "ro", ac.ProfilePin) + assert.Equal(t, auth.ProfileModeLocked, ac.ProfileMode) + assert.True(t, ac.IsClientCredential()) +} + +func TestExchange_ExistingAPIKeyClientGetsItsFirstLoginFromItsCurrentBinding(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + _, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + require.Nil(t, terr) + b, err := fx.sm.GetOAuthClientBinding("codex") + require.NoError(t, err) + require.NotNil(t, b) + assert.Equal(t, "ro", b.ProfilePin) +} + +func TestExchange_FirstApprovalIsJudgedByTheGuardAtExchange(t *testing.T) { + fx := newOAuthFx(t) + fx.guard = ConservativeBindingGuard{} + reg := fx.register() + code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) // auth on: allowed + fx.cfg.RequireMCPAuth = false // ...then auth goes off + + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + fx.nothingStored() + rows := fx.changeRows("deny") + require.Len(t, rows, 1) + assert.Equal(t, "guard", rows[0]["reason"]) + assert.Equal(t, "client", rows[0]["trigger"]) + assert.Equal(t, "admin", rows[0]["actor_name"], "the approving administrator") +} + +func TestExchange_RefusalsAreInvalidGrantAndBurnTheCode(t *testing.T) { + cases := map[string]func(in *TokenInput){ + "wrong verifier": func(in *TokenInput) { in.CodeVerifier = strings.Repeat("w", 43) }, + "wrong client": func(in *TokenInput) { in.ClientID = "someoneelse" }, + "wrong redirect uri": func(in *TokenInput) { in.RedirectURI = "http://127.0.0.1:5556/cb" }, + } + for name, mut := range cases { + t.Run(name, func(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + in := fx.tokenInput(reg, code) + mut(&in) + _, terr := fx.svc.Exchange(in) + requireInvalidGrant(t, terr) + fx.nothingStored() + // Single use: even the right request now fails. + _, terr = fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + fx.nothingStored() + }) + } +} + +func TestExchange_ResourceMustEqualTheApprovedOne(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + in := fx.tokenInput(reg, code) + in.Resource = oauthTestOrigin + "/mcp/oauth/codex" + _, terr := fx.svc.Exchange(in) + require.NotNil(t, terr) + assert.Equal(t, TokenErrInvalidTarget, terr.Code) + fx.nothingStored() + + // The same resource, and an absent one, are fine. + code = fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + in = fx.tokenInput(reg, code) + in.Resource = oauthTestOrigin + "/mcp/oauth/cursor" + _, terr = fx.svc.Exchange(in) + require.Nil(t, terr) +} + +func TestExchange_OriginMismatchIsRefusedFirstAndConsumesNothing(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + in := fx.tokenInput(reg, code) + in.Origin = "http://localhost:8080" + _, terr := fx.svc.Exchange(in) + requireInvalidGrant(t, terr) + fx.nothingStored() + _, terr = fx.svc.Exchange(fx.tokenInput(reg, code)) + require.Nil(t, terr, "the code is still usable on the right origin") +} + +func TestExchange_CodeExpiryAndReuse(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + + code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + fx.clock.Advance(mcplogin.CodeLifetime) + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + fx.nothingStored() + + // Reuse inside the tombstone window revokes the login it produced. + code = fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + res, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + require.Nil(t, terr) + _, terr = fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + gs := fx.grants() + require.Len(t, gs, 1) + assert.True(t, gs[0].Revoked) + assert.Equal(t, storage.OAuthRevokeReplay, gs[0].RevokeReason) + rows := fx.changeRows("replay_revoke") + require.Len(t, rows, 1) + assert.Equal(t, gs[0].GrantID, rows[0]["grant_id"]) + assert.Equal(t, "client", rows[0]["trigger"]) + assert.Equal(t, "admin", rows[0]["actor_name"]) + _, _, aerr := fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth/cursor", fx.clock.Now()) + assert.ErrorIs(t, aerr, ErrOAuthUnauthorized, "a revoked login stops authenticating") + + // After the window the code is simply unknown: nothing more is revoked. + fx.clock.Advance(mcplogin.TombstoneLifetime + time.Second) + _, terr = fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + assert.Len(t, fx.changeRows("replay_revoke"), 1) +} + +func TestExchange_ReuseOfACodeWhoseCommitFailedRevokesNothing(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + code := oauthCodeOf(t, redirect) + _, _, err = fx.clients.SetBindingForTest(fx, "rw") + require.NoError(t, err) + + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + _, terr = fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + assert.Empty(t, fx.changeRows("replay_revoke"), "an empty grant id means there is nothing to revoke") +} + +// SetBindingForTest changes codex's binding through the real clients service. +func (s *ClientsService) SetBindingForTest(fx *oauthFx, pin string) (*ClientCredentialView, struct{}, error) { + v, err := s.SetBinding(fx.ctx(), fx.actor(), "codex", pin, nil) + return v, struct{}{}, err +} + +func TestExchange_BindingChangedAfterApprovalStoresNothing(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + _, _, err = fx.clients.SetBindingForTest(fx, "rw") + require.NoError(t, err) + + _, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + requireInvalidGrant(t, terr) + assert.Empty(t, fx.grants()) + rows := fx.changeRows("deny") + require.Len(t, rows, 1) + assert.Equal(t, "binding_changed", rows[0]["reason"]) + assert.Equal(t, "client", rows[0]["trigger"]) + assert.Equal(t, "admin", rows[0]["actor_name"]) +} + +func TestExchange_ReplaceGrantRevokesTheOldLogin(t *testing.T) { + fx := newOAuthFx(t) + reg, first := fx.loginNew("cursor", "ro") + old := fx.grants()[0] + + id := fx.authorize(reg, "cursor") + rev, _ := fx.sm.ClientBindingRevision("cursor") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev, ReplaceGrant: old.GrantID}) + require.NoError(t, err) + second, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + require.Nil(t, terr) + + _, _, aerr := fx.svc.Authenticate(first.AccessToken, oauthTestOrigin, "/mcp/oauth/cursor", fx.clock.Now()) + assert.ErrorIs(t, aerr, ErrOAuthUnauthorized) + _, _, aerr = fx.svc.Authenticate(second.AccessToken, oauthTestOrigin, "/mcp/oauth/cursor", fx.clock.Now()) + assert.NoError(t, aerr) + for _, g := range fx.grants() { + if g.GrantID == old.GrantID { + assert.True(t, g.Revoked) + assert.Equal(t, storage.OAuthRevokeReplaced, g.RevokeReason) + } + } + + // A replace_grant of someone else's login is ignored, never revoked. + other := fx.register() + id = fx.authorize(other, "cursor") + rev, _ = fx.sm.ClientBindingRevision("cursor") + live := "" + for _, g := range fx.grants() { + if !g.Revoked { + live = g.GrantID + } + } + redirect, err = fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev, ReplaceGrant: live}) + require.NoError(t, err) + _, terr = fx.svc.Exchange(fx.tokenInput(other, oauthCodeOf(t, redirect))) + require.Nil(t, terr) + _, _, aerr = fx.svc.Authenticate(second.AccessToken, oauthTestOrigin, "/mcp/oauth/cursor", fx.clock.Now()) + assert.NoError(t, aerr, "another registration's login is not replaced") +} + +// --- cancellation after approval ------------------------------------------------------------ + +func TestExchange_AfterApprovalRevokeClientFails(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + + _, err = fx.creds.Revoke(fx.ctx(), fx.actor(), CredentialRef{Client: "codex"}, false) + require.NoError(t, err) + _, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + requireInvalidGrant(t, terr) + assert.Empty(t, fx.grants(), "a revoke changes neither pin nor mode: only the cancellation catches it") +} + +func TestExchange_AfterApprovalForgetAndRecreateFails(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + + _, err = fx.clients.Forget(fx.ctx(), fx.actor(), "codex", false) + require.NoError(t, err) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) // recreated with the very same binding + _, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + requireInvalidGrant(t, terr) + assert.Empty(t, fx.grants()) +} + +func TestExchange_AfterApprovalFeatureOffThenOnFailsEvenWithoutAnEvent(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + pendingID := fx.authorize(reg, "cursor") + + // The synchronous step of applying a config in which the switch goes off. + assert.Equal(t, 2, fx.svc.CancelAll("feature_disabled")) + fx.cfg.MCPOAuthEnabled = false + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + fx.cfg.MCPOAuthEnabled = true // on again: the code is still dead + _, terr = fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + fx.nothingStored() + _, err := fx.svc.Approve(fx.ctx(), pendingID, ApprovalChoice{Profile: oauthStrp("ro")}) + assert.ErrorIs(t, err, ErrOAuthRequestNotFound, "a cancelled pending request cannot be approved") + assert.NotEmpty(t, fx.eventsOf(EventTypeOAuthAuthorizationDecided)) +} + +func TestExchange_TwoApprovedNewClientRequestsWithTheSameID(t *testing.T) { + fx := newOAuthFx(t) + choice := ApprovalChoice{Client: ClientChoice{New: &NewClientChoice{ID: "acme"}}, Profile: oauthStrp("ro")} + regA, regB := fx.register(), fx.register() + codeA := fx.approvedCode(regA, "", choice) + codeB := fx.approvedCode(regB, "", choice) + + _, terr := fx.svc.Exchange(fx.tokenInput(regA, codeA)) + require.Nil(t, terr) + _, terr = fx.svc.Exchange(fx.tokenInput(regB, codeB)) + requireInvalidGrant(t, terr) + gs := fx.grants() + require.Len(t, gs, 1, "the second is not turned into an existing-client login") + assert.Equal(t, regA, gs[0].RegistrationID) + rows := fx.changeRows("deny") + require.Len(t, rows, 1) + assert.Equal(t, "client_exists", rows[0]["reason"]) +} + +func TestExchange_RegistrationEvictedAfterApproval(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + n, err := fx.sm.SweepOAuthRegistrations(fx.clock.Now().Add(48 * time.Hour)) + require.NoError(t, err) + require.Equal(t, 1, n) + + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + fx.nothingStored() + _, err = fx.sm.GetOAuthRegistration(reg) + assert.ErrorIs(t, err, storage.ErrOAuthRegistrationGone, "it is never recreated from the code") +} + +func TestExchange_FeatureOffRefusesEverything(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + fx.cfg.MCPOAuthEnabled = false + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + _, terr = fx.svc.Refresh(TokenInput{Origin: oauthTestOrigin, RefreshToken: "x", ClientID: reg}) + requireInvalidGrant(t, terr) + _, _, aerr := fx.svc.Authenticate("mcp_oat_x", oauthTestOrigin, "/mcp/oauth", fx.clock.Now()) + assert.ErrorIs(t, aerr, ErrOAuthUnauthorized) +} + +// --- authentication ------------------------------------------------------------------------------ + +func TestAuthenticate_AudienceBinding(t *testing.T) { + fx := newOAuthFx(t) + _, res := fx.loginNew("cursor", "ro") + now := fx.clock.Now() + + _, _, err := fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth/cursor", now) + assert.NoError(t, err) + _, _, err = fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth/cursor/", now) + assert.NoError(t, err, "a trailing slash names the same resource path") + for name, c := range map[string]struct{ origin, path string }{ + "another client's address": {oauthTestOrigin, "/mcp/oauth/codex"}, + "the generic address": {oauthTestOrigin, "/mcp/oauth"}, + "another origin": {"http://localhost:8080", "/mcp/oauth/cursor"}, + "the plain MCP endpoint": {oauthTestOrigin, "/mcp"}, + } { + _, _, err := fx.svc.Authenticate(res.AccessToken, c.origin, c.path, now) + assert.ErrorIs(t, err, ErrOAuthUnauthorized, name) + } + _, _, err = fx.svc.Authenticate("mcp_oat_notatoken", oauthTestOrigin, "/mcp/oauth/cursor", now) + assert.ErrorIs(t, err, ErrOAuthUnauthorized) + _, _, err = fx.svc.Authenticate("mcp_cli_something", oauthTestOrigin, "/mcp/oauth/cursor", now) + assert.ErrorIs(t, err, ErrOAuthUnauthorized) + _, _, err = fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth/cursor", now.Add(time.Hour)) + assert.ErrorIs(t, err, ErrOAuthUnauthorized, "the access token lives one hour") +} + +func TestAuthenticate_GenericResourceGrantOnlyOnTheGenericAddress(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + code := fx.approvedCode(reg, "", ApprovalChoice{Client: ClientChoice{New: &NewClientChoice{ID: "acme"}}, Profile: oauthStrp("ro")}) + res, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + require.Nil(t, terr) + _, _, err := fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth", fx.clock.Now()) + assert.NoError(t, err) + _, _, err = fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth/acme", fx.clock.Now()) + assert.ErrorIs(t, err, ErrOAuthUnauthorized) +} + +func TestAuthenticate_BindingIsReadThroughTheAPIKeyRecord(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + res, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + require.Nil(t, terr) + + ac, _, aerr := fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth/codex", fx.clock.Now()) + require.NoError(t, aerr) + assert.Equal(t, "ro", ac.ProfilePin) + // An older binary moved the API-key record only; the entry is stale. + _, _, uerr := fx.sm.UpdateClientCredentialBinding("codex", "rw", auth.ProfileModeLocked) + require.NoError(t, uerr) + ac, _, aerr = fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth/codex", fx.clock.Now()) + require.NoError(t, aerr) + assert.Equal(t, "rw", ac.ProfilePin) +} + +// --- refresh ------------------------------------------------------------------------------------------ + +func (fx *oauthFx) refresh(reg, token string) (TokenResult, *TokenError) { + return fx.svc.Refresh(TokenInput{Origin: oauthTestOrigin, RefreshToken: token, ClientID: reg}) +} + +func TestRefresh_RotatesAndNeverExtendsAnExpiredLogin(t *testing.T) { + fx := newOAuthFx(t) + reg, first := fx.loginNew("cursor", "ro") + gid := fx.grants()[0].GrantID + + fx.clock.Advance(10 * 24 * time.Hour) + second, terr := fx.refresh(reg, first.RefreshToken) + require.Nil(t, terr) + assert.NotEqual(t, first.RefreshToken, second.RefreshToken) + assert.NotEqual(t, first.AccessToken, second.AccessToken) + g, _ := fx.sm.GetOAuthGrant(gid) + assert.True(t, g.RefreshExpiresAt.Equal(fx.clock.Now().Add(OAuthRefreshTokenTTL)), "30 days from the last rotation") + _, _, aerr := fx.svc.Authenticate(first.AccessToken, oauthTestOrigin, "/mcp/oauth/cursor", fx.clock.Now()) + assert.ErrorIs(t, aerr, ErrOAuthUnauthorized, "the previous access token is replaced") + _, _, aerr = fx.svc.Authenticate(second.AccessToken, oauthTestOrigin, "/mcp/oauth/cursor", fx.clock.Now()) + assert.NoError(t, aerr) + + // Expiry: 31 days of silence. Refused, not extended, nothing written. + before, _ := fx.sm.GetOAuthGrant(gid) + fx.clock.Advance(31 * 24 * time.Hour) + _, terr = fx.refresh(reg, second.RefreshToken) + requireInvalidGrant(t, terr) + after, _ := fx.sm.GetOAuthGrant(gid) + assert.Equal(t, before.RefreshExpiresAt, after.RefreshExpiresAt) + assert.False(t, after.Revoked) +} + +func TestRefresh_AuthenticReplayRevokesAndForgeryDoesNot(t *testing.T) { + fx := newOAuthFx(t) + reg, first := fx.loginNew("cursor", "ro") + gid := fx.grants()[0].GrantID + second, terr := fx.refresh(reg, first.RefreshToken) + require.Nil(t, terr) + + // A made-up token for a real grant id: bad MAC, nothing written. + forged := first.RefreshToken[:len(first.RefreshToken)-3] + "AAA" + _, terr = fx.refresh(reg, forged) + requireInvalidGrant(t, terr) + g, _ := fx.sm.GetOAuthGrant(gid) + assert.False(t, g.Revoked, "knowing a grant id is not enough to disturb a grant") + _, terr = fx.refresh(reg, "mcp_ort_"+gid+"_"+strings.Repeat("A", 43)+"_"+strings.Repeat("B", 22)) + requireInvalidGrant(t, terr) + g, _ = fx.sm.GetOAuthGrant(gid) + assert.False(t, g.Revoked) + + // The authentic, already-spent token comes back: the login is revoked. + _, terr = fx.refresh(reg, first.RefreshToken) + requireInvalidGrant(t, terr) + g, _ = fx.sm.GetOAuthGrant(gid) + assert.True(t, g.Revoked) + assert.Equal(t, storage.OAuthRevokeReplay, g.RevokeReason) + rows := fx.changeRows("replay_revoke") + require.Len(t, rows, 1) + assert.Equal(t, gid, rows[0]["grant_id"]) + assert.Equal(t, "client", rows[0]["trigger"]) + evs := fx.eventsOf(EventTypeCredentialsChanged) + assert.Equal(t, "replay_revoke", evs[len(evs)-1].Payload["change"]) + // The current token is dead too now. + _, terr = fx.refresh(reg, second.RefreshToken) + requireInvalidGrant(t, terr) +} + +func TestRefresh_ClientOriginAndResourceChecks(t *testing.T) { + fx := newOAuthFx(t) + reg, first := fx.loginNew("cursor", "ro") + gid := fx.grants()[0].GrantID + + _, terr := fx.refresh("someoneelse", first.RefreshToken) + requireInvalidGrant(t, terr) + _, terr = fx.svc.Refresh(TokenInput{Origin: "http://localhost:8080", RefreshToken: first.RefreshToken, ClientID: reg}) + requireInvalidGrant(t, terr) + _, terr = fx.svc.Refresh(TokenInput{Origin: oauthTestOrigin, RefreshToken: first.RefreshToken, ClientID: reg, Resource: oauthTestOrigin + "/mcp/oauth"}) + require.NotNil(t, terr) + assert.Equal(t, TokenErrInvalidTarget, terr.Code) + g, _ := fx.sm.GetOAuthGrant(gid) + assert.False(t, g.Revoked, "none of these wrote anything") + + _, terr = fx.svc.Refresh(TokenInput{Origin: oauthTestOrigin, RefreshToken: first.RefreshToken, ClientID: reg, Resource: oauthTestOrigin + "/mcp/oauth/cursor"}) + require.Nil(t, terr, "the same resource is accepted") +} + +// --- admin revoke ------------------------------------------------------------------------------------------ + +func TestRevokeGrant_NamesTheRequestActorAndStopsTheToken(t *testing.T) { + fx := newOAuthFx(t) + _, res := fx.loginNew("cursor", "ro") + gid := fx.grants()[0].GrantID + n := &countingNotifier{} + fx.svc.SetNotifier(n) + + changed, err := fx.svc.RevokeGrant(fx.ctx(), "cursor", gid) + require.NoError(t, err) + assert.True(t, changed) + rows := fx.changeRows("revoke") + require.Len(t, rows, 1) + assert.Equal(t, gid, rows[0]["grant_id"]) + assert.Equal(t, "admin", rows[0]["actor_name"]) + assert.NotContains(t, rows[0], "trigger", "an administrator's action, not the client's") + assert.Equal(t, 1, int(n.calls.Load())) + evs := fx.eventsOf(EventTypeCredentialsChanged) + assert.Equal(t, "revoke", evs[len(evs)-1].Payload["change"]) + _, _, aerr := fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth/cursor", fx.clock.Now()) + assert.ErrorIs(t, aerr, ErrOAuthUnauthorized, "the next request is refused") + + changed, err = fx.svc.RevokeGrant(fx.ctx(), "cursor", gid) + require.NoError(t, err) + assert.False(t, changed, "already revoked") + _, err = fx.svc.RevokeGrant(fx.ctx(), "codex", gid) + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) + _, err = fx.svc.RevokeGrant(fx.ctx(), "cursor", "nope") + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) +} + +type countingNotifier struct{ calls atomic.Int32 } + +func (c *countingNotifier) NotifyBindingChanged(string) { c.calls.Add(1) } + +// --- the lock order -------------------------------------------------------------------------------------------- + +// Exchange takes bindingWriteMu before the request store, and revoke/forget take +// it before CancelForClient: one order, so hammering both finishes. Run under +// -race. +func TestExchangeAgainstRevokeClientDoesNotDeadlockOrRace(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + const n = 12 + type pending struct{ reg, code string } + var ps []pending + for i := 0; i < n; i++ { + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + ps = append(ps, pending{reg, oauthCodeOf(t, redirect)}) + } + + done := make(chan struct{}) + go func() { + defer close(done) + var wg sync.WaitGroup + for _, p := range ps { + p := p + wg.Add(1) + go func() { + defer wg.Done() + _, _ = fx.svc.Exchange(fx.tokenInput(p.reg, p.code)) + }() + } + for i := 0; i < 4; i++ { + wg.Add(2) + go func() { + defer wg.Done() + _, _ = fx.creds.Revoke(fx.ctx(), fx.actor(), CredentialRef{Client: "codex"}, false) + }() + go func() { + defer wg.Done() + fx.svc.CancelForClient("codex") + fx.svc.CancelAll("race") + }() + } + wg.Wait() + }() + select { + case <-done: + case <-time.After(60 * time.Second): + t.Fatal("deadlock: Exchange and revoke/cancel never finished") + } + // Whatever won, no login is left live for a revoked client. + for _, g := range fx.grants() { + assert.True(t, g.Revoked, "a login that slipped in before the revoke is revoked by it") + } +} + +var _ = profile.ChangeApprove diff --git a/internal/runtime/oauth_login_failclosed_test.go b/internal/runtime/oauth_login_failclosed_test.go new file mode 100644 index 000000000..6cf792d0d --- /dev/null +++ b/internal/runtime/oauth_login_failclosed_test.go @@ -0,0 +1,77 @@ +package runtime + +import ( + "errors" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// brokenOAuthStore is a real store whose browser-login bindings cannot be read. +type brokenOAuthStore struct{ *storage.Manager } + +func (brokenOAuthStore) ListOAuthClientBindings() (map[string]storage.OAuthClientBinding, error) { + return nil, errors.New("disk on fire") +} + +// A storage read error REFUSES the change instead of being read as "no +// bindings" (research R5): the producers of a guard state fail closed. +func TestGuardProducersFailClosedOnAnOAuthStoreReadError(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + broken := brokenOAuthStore{fx.sm} + var shared = fx.clients.mu + clients := NewClientsService(ClientsServiceDeps{ + Store: broken, HMACKey: func() ([]byte, error) { return oauthTestKey, nil }, + Config: func() *config.Config { return fx.cfg }, Guard: func() BindingGuard { return stubGuard{} }, + Now: fx.clock.Now, Mu: shared, + }) + + _, err := clients.SetBinding(fx.ctx(), fx.actor(), "codex", "rw", nil) + require.Error(t, err) + assert.Contains(t, err.Error(), "browser-login") + pin, _, _, _ := fx.sm.CurrentClientBinding("codex") + assert.Equal(t, "ro", pin, "nothing was written") + + // The views refuse too, rather than silently dropping the logins. + _, err = clients.List() + require.Error(t, err) +} + +func TestOAuthNameMismatch(t *testing.T) { + cases := []struct { + observed, reported, client string + want bool + }{ + {"", "anything", "cursor", false}, + {"cursor", "other", "cursor", false}, // a registry id + {"Cursor", "other", "cursor", false}, // the registry display name + {"totally-other", "cursor ide", "cursor", true}, // neither + {"cursor ide", "cursor ide", "acme", false}, // the registered name + {"cursor ide", "something else", "acme", true}, // a custom client knows only its registered name + {"claude-code (via mcp-remote 0.1.2)", "x", "claude-code", false}, + } + for _, c := range cases { + assert.Equal(t, c.want, OAuthNameMismatch(c.observed, c.reported, c.client), "%+v", c) + } +} + +func TestTouch_StampsLastUseAndObservedNameOffTheRequestPath(t *testing.T) { + fx := newOAuthFx(t) + fx.loginNew("cursor", "ro") + gid := fx.grants()[0].GrantID + fx.svc.Touch(gid, "Cursor-VSCode") + require.Eventually(t, func() bool { + g, _ := fx.sm.GetOAuthGrant(gid) + return g != nil && g.LastUsedAt != nil && g.ObservedClientName != "" + }, 2*time.Second, 10*time.Millisecond) + g, _ := fx.sm.GetOAuthGrant(gid) + assert.Equal(t, "cursor-vscode", g.ObservedClientName, "sanitised before it is stored") + fx.svc.Touch("", "x") // no grant: nothing happens +} diff --git a/internal/runtime/oauth_login_fixture_test.go b/internal/runtime/oauth_login_fixture_test.go new file mode 100644 index 000000000..935553b03 --- /dev/null +++ b/internal/runtime/oauth_login_fixture_test.go @@ -0,0 +1,230 @@ +package runtime + +import ( + "context" + "crypto/sha256" + "encoding/base64" + "net/url" + "os" + "strings" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/require" + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/profile" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +const ( + oauthTestOrigin = "http://127.0.0.1:8080" + oauthTestRedirect = "http://127.0.0.1:5555/cb" +) + +var oauthTestKey = []byte("oauth-login-test-key-0123456789ab") + +type oauthTestClock struct { + mu sync.Mutex + t time.Time +} + +func (c *oauthTestClock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.t +} + +func (c *oauthTestClock) Advance(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.t = c.t.Add(d) +} + +// oauthFx is the browser-login services over a real storage manager. +type oauthFx struct { + t *testing.T + sm *storage.Manager + cfg *config.Config + clock *oauthTestClock + svc *OAuthLoginService + clients *ClientsService + creds *CredentialsService + reqs *mcplogin.Store + guard BindingGuard + + mu sync.Mutex + rows []*storage.ActivityRecord + events []Event +} + +func newOAuthFx(t *testing.T) *oauthFx { + t.Helper() + dir, err := os.MkdirTemp("", "oauth-login-svc-*") + require.NoError(t, err) + sm, err := storage.NewManager(dir, zap.NewNop().Sugar()) + require.NoError(t, err) + t.Cleanup(func() { _ = sm.Close(); _ = os.RemoveAll(dir) }) + + fx := &oauthFx{t: t, sm: sm, clock: &oauthTestClock{t: time.Date(2026, 11, 22, 12, 0, 0, 0, time.UTC)}, guard: stubGuard{}} + fx.cfg = &config.Config{ + MCPOAuthEnabled: true, RequireMCPAuth: true, + Profiles: []config.ProfileConfig{{Name: "ro", Servers: []string{"a"}}, {Name: "rw", Servers: []string{"a"}}}, + } + fx.reqs = mcplogin.NewStore(oauthTestKey, fx.clock.Now) + var shared sync.Mutex + keyf := func() ([]byte, error) { return oauthTestKey, nil } + cfgf := func() *config.Config { return fx.cfg } + guardf := func() BindingGuard { return fx.guard } + act := func(r *storage.ActivityRecord) error { + fx.mu.Lock() + defer fx.mu.Unlock() + fx.rows = append(fx.rows, r) + return nil + } + pub := func(e Event) { + fx.mu.Lock() + defer fx.mu.Unlock() + fx.events = append(fx.events, e) + } + fx.svc = NewOAuthLoginService(OAuthLoginDeps{ + Store: sm, HMACKey: keyf, Config: cfgf, Guard: guardf, Activity: act, Publish: pub, + Now: fx.clock.Now, Mu: &shared, Requests: fx.reqs, + }) + fx.clients = NewClientsService(ClientsServiceDeps{ + Store: sm, HMACKey: keyf, Config: cfgf, Guard: guardf, Activity: act, Publish: pub, + Now: fx.clock.Now, Mu: &shared, + }) + fx.clients.SetLoginCanceler(func(id string) { fx.svc.CancelForClient(id) }) + fx.creds = fx.clients.CredentialsServiceOver(sm) + fx.creds.SetOAuthLogin(fx.svc) + return fx +} + +// stubGuard never refuses (the same shape config_funnel_test uses); tests that +// need the real conservative evaluator set fx.guard. +func (fx *oauthFx) ctx() context.Context { + return ContextWithActor(context.Background(), Actor{Kind: "api_key", Name: "admin", Surface: profile.SurfaceAPI}) +} + +func (fx *oauthFx) actor() Actor { + return Actor{Kind: "api_key", Name: "admin", Surface: profile.SurfaceAPI} +} + +// mintClient creates an API-key client with a binding. +func (fx *oauthFx) mintClient(id, pin, mode string) { + fx.t.Helper() + _, err := fx.sm.MintClientCredential(id, "mcp_cli_"+id+"_oauth_test_secret_000000", oauthTestKey, mode, pin, time.Now().Add(300*24*time.Hour)) // storage validates against the real clock + require.NoError(fx.t, err) +} + +func (fx *oauthFx) register() string { + fx.t.Helper() + resp, rerr, err := fx.svc.Register(mcplogin.RegistrationRequest{ + RedirectURIs: []string{oauthTestRedirect}, ClientName: "Cursor IDE", + }) + require.NoError(fx.t, err) + require.Nil(fx.t, rerr) + return resp["client_id"].(string) +} + +var oauthTestVerifier = strings.Repeat("v", 43) + +func oauthTestChallenge() string { + sum := sha256.Sum256([]byte(oauthTestVerifier)) + return base64.RawURLEncoding.EncodeToString(sum[:]) +} + +func (fx *oauthFx) authInput(reg, resource string) AuthorizeInput { + return AuthorizeInput{ + Origin: oauthTestOrigin, ClientID: reg, RedirectURI: oauthTestRedirect, State: "st-1", + CodeChallenge: oauthTestChallenge(), Method: "S256", Resource: resource, ResponseType: "code", + } +} + +// authorize registers nothing: it begins an authorization for reg at the +// per-client resource of client ("" = the generic address). +func (fx *oauthFx) authorize(reg, client string) string { + fx.t.Helper() + id, aerr := fx.svc.BeginAuthorization(fx.authInput(reg, oauthTestOrigin+mcplogin.ResourcePath(client))) + require.Nil(fx.t, aerr) + require.NotEmpty(fx.t, id) + return id +} + +func oauthCodeOf(t *testing.T, redirect string) string { + t.Helper() + u, err := url.Parse(redirect) + require.NoError(t, err) + code := u.Query().Get("code") + require.NotEmpty(t, code, redirect) + return code +} + +func (fx *oauthFx) tokenInput(reg, code string) TokenInput { + return TokenInput{Origin: oauthTestOrigin, Code: code, RedirectURI: oauthTestRedirect, ClientID: reg, CodeVerifier: oauthTestVerifier} +} + +func oauthStrp(s string) *string { return &s } + +// login runs register -> authorize -> approve -> exchange for a new client. +func (fx *oauthFx) loginNew(client, profileName string) (reg string, res TokenResult) { + fx.t.Helper() + reg = fx.register() + id := fx.authorize(reg, client) + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Client: ClientChoice{ID: client}, Profile: oauthStrp(profileName)}) + require.NoError(fx.t, err) + var terr *TokenError + res, terr = fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(fx.t, redirect))) + require.Nil(fx.t, terr) + return reg, res +} + +func (fx *oauthFx) changeRows(change string) []map[string]interface{} { + fx.mu.Lock() + defer fx.mu.Unlock() + var out []map[string]interface{} + for _, r := range fx.rows { + if r.Type == storage.ActivityTypeProfileChange && r.Metadata["change"] == change { + out = append(out, r.Metadata) + } + } + return out +} + +func (fx *oauthFx) eventsOf(typ EventType) []Event { + fx.mu.Lock() + defer fx.mu.Unlock() + var out []Event + for _, e := range fx.events { + if e.Type == typ { + out = append(out, e) + } + } + return out +} + +func (fx *oauthFx) grants() []storage.OAuthGrant { + fx.t.Helper() + gs, err := fx.sm.ListOAuthGrants() + require.NoError(fx.t, err) + return gs +} + +// nothingStored asserts that no login, binding or marker exists. +func (fx *oauthFx) nothingStored() { + fx.t.Helper() + require.Empty(fx.t, fx.grants()) + b, err := fx.sm.ListOAuthClientBindings() + require.NoError(fx.t, err) + require.Empty(fx.t, b) + used, err := fx.sm.OAuthLoginEverUsed() + require.NoError(fx.t, err) + require.False(fx.t, used) +} + +var _ = auth.KindClient diff --git a/internal/runtime/oauth_login_refresh_fence.go b/internal/runtime/oauth_login_refresh_fence.go new file mode 100644 index 000000000..240f97294 --- /dev/null +++ b/internal/runtime/oauth_login_refresh_fence.go @@ -0,0 +1,42 @@ +package runtime + +import ( + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// rotateFenced runs storage.RotateOAuthRefresh inside the config fence: it takes +// the same ConfigCommitLock as the exchange (the lock every config publication +// holds, including the one that switches browser login off), reads ONE config +// snapshot, re-checks MCPOAuthEnabled on it and holds the lock through the +// rotation. A refresh that passed the early Enabled() check therefore cannot +// rotate secrets or extend an expiry after a commit disabled the feature: the +// commit either completed first (uniform refusal, nothing written) or starts +// after the rotation. Refresh does not take bindingWriteMu, so the order is +// configCommitMu -> storage. Key I/O and token generation happened before; the +// replay row, event and notifier run after the lock is released (by the caller). +func (s *OAuthLoginService) rotateFenced(grantID, presentedHash string, ts *tokenSet) (storage.RefreshOutcome, storage.OAuthGrant, *TokenError) { + if h := s.testHookBeforeRotateLock; h != nil { + h() + } + if s.commitLock != nil { + s.commitLock.Lock() + defer s.commitLock.Unlock() + } + cfg := s.cfg() + if cfg == nil || !cfg.MCPOAuthEnabled { + return storage.RefreshInvalid, storage.OAuthGrant{}, errInvalidGrant + } + if h := s.testHookInRotate; h != nil { + h() + } + now := s.now().UTC() + outcome, after, err := s.store.RotateOAuthRefresh(grantID, presentedHash, + ts.refreshHash, ts.refreshPrefix, ts.accessHash, now, OAuthAccessTokenTTL, OAuthRefreshTokenTTL) + if err != nil { + s.logger.Error("browser login: refresh rotation failed", zap.Error(err)) + return storage.RefreshInvalid, storage.OAuthGrant{}, errTokenServer + } + return outcome, after, nil +} diff --git a/internal/runtime/oauth_login_review_test.go b/internal/runtime/oauth_login_review_test.go new file mode 100644 index 000000000..116f4cb47 --- /dev/null +++ b/internal/runtime/oauth_login_review_test.go @@ -0,0 +1,437 @@ +package runtime + +import ( + "errors" + "strings" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/connect" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// --- A1: cancellation before any idempotent early return ----------------------------------- + +func TestRevokeClient_AlreadyRevokedKeyStillCancelsApprovedRequests(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + _, err := fx.clients.RevokeAPIKey(fx.ctx(), fx.actor(), "codex") + require.NoError(t, err) + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + + r, err := fx.creds.Revoke(fx.ctx(), fx.actor(), CredentialRef{Client: "codex"}, false) + require.NoError(t, err) + assert.False(t, r.Changed, "nothing live: the revoke itself is a no-op") + _, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + requireInvalidGrant(t, terr) + assert.Empty(t, fx.grants()) +} + +func TestForgetClient_WithNothingStoredStillCancelsApprovedRequests(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + pending := fx.authorize(reg, "cursor") + + _, err := fx.clients.Forget(fx.ctx(), fx.actor(), "cursor", false) + var nc *NoClientCredentialError + require.True(t, errors.As(err, &nc), "the returned error is unchanged") + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + _, err = fx.svc.Approve(fx.ctx(), pending, ApprovalChoice{Profile: oauthStrp("ro")}) + assert.ErrorIs(t, err, ErrOAuthRequestNotFound) + fx.nothingStored() +} + +// --- A2: hasLiveGrant fails closed -------------------------------------------------------------- + +type failingGrantsStore struct{ *storage.Manager } + +func (failingGrantsStore) ListOAuthGrants() ([]storage.OAuthGrant, error) { + return nil, errors.New("disk on fire") +} + +func TestRevokeClient_UnreadableGrantsRefuseInsteadOfSkipping(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + _, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + require.Nil(t, terr) + _, err = fx.clients.RevokeAPIKey(fx.ctx(), fx.actor(), "codex") + require.NoError(t, err) + + broken := failingGrantsStore{fx.sm} + cs := NewClientsService(ClientsServiceDeps{ + Store: broken, HMACKey: func() ([]byte, error) { return oauthTestKey, nil }, + Config: func() *config.Config { return fx.cfg }, Guard: func() BindingGuard { return stubGuard{} }, + Now: fx.clock.Now, Mu: fx.clients.mu, + }) + _, err = cs.CredentialsServiceOver(broken).Revoke(fx.ctx(), fx.actor(), CredentialRef{Client: "codex"}, false) + require.Error(t, err, "an unreadable grant list must not look like 'nothing live'") + assert.False(t, fx.grants()[0].Revoked) +} + +// --- A3: the legacy token-name door cascades ------------------------------------------------- + +func TestRevokeByTokenName_ClientWithLoginsCascades(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + code := oauthCodeOf(t, redirect) + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + require.Nil(t, terr) + pending := fx.approvedCode(fx.register(), "codex", ApprovalChoice{BindingRevision: rev}) + + _, err = fx.creds.Revoke(fx.ctx(), fx.actor(), CredentialRef{Token: "client-codex"}, true) + require.NoError(t, err) + tok, _ := fx.sm.GetAgentTokenByName("client-codex") + assert.True(t, tok.Revoked) + for _, g := range fx.grants() { + assert.True(t, g.Revoked, "the door cut a client off completely before, and still does") + } + _, terr = fx.svc.Exchange(fx.tokenInput(reg, pending)) + requireInvalidGrant(t, terr) +} + +func TestRevokeByTokenName_ClientWithoutLoginsIsExactlyTheOldDoor(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + r, err := fx.creds.Revoke(fx.ctx(), fx.actor(), CredentialRef{Token: "client-codex"}, true) + require.NoError(t, err) + assert.True(t, r.Changed) + assert.False(t, r.ClientConfigUntouched, "the token door never said this") + rows := fx.changeRows("revoke") + require.Len(t, rows, 1) + diff, _ := rows[0]["diff"].(map[string]interface{}) + assert.Equal(t, true, diff["changed"]) + assert.NotContains(t, diff, "client_config_untouched", "the client-revoke diff is not used") + evs := fx.eventsOf(EventTypeCredentialsChanged) + require.Len(t, evs, 1) + assert.Equal(t, CredentialKindClient, evs[0].Payload["kind"]) +} + +// --- A4: the switch-off boundary ----------------------------------------------------------------- + +func TestBeginAuthorization_RequestAdmittedBeforeSwitchOffIsCancelledByIt(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + done := make(chan struct{}) + var once sync.Once + fx.svc.testHookBeginAfterEnabled = func() { + once.Do(func() { + go func() { + release := fx.svc.beginDisable("test") // blocks until Begin leaves the lifecycle section + fx.cfg.MCPOAuthEnabled = false + release() + close(done) + }() + time.Sleep(50 * time.Millisecond) // let it queue on the lifecycle lock + }) + } + id, aerr := fx.svc.BeginAuthorization(fx.authInput(reg, oauthTestOrigin+"/mcp/oauth/cursor")) + require.Nil(t, aerr, "admitted: the enabled check and the create share one boundary") + <-done + _, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + assert.ErrorIs(t, err, ErrOAuthRequestNotFound, "the switch-off cancelled it") + + // During the off window nothing is admitted, and after off -> on nothing from + // the window is approvable. + _, aerr = fx.svc.BeginAuthorization(fx.authInput(reg, oauthTestOrigin+"/mcp/oauth/cursor")) + require.NotNil(t, aerr) + fx.cfg.MCPOAuthEnabled = true + _, err = fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + assert.ErrorIs(t, err, ErrOAuthRequestNotFound) + assert.Empty(t, fx.svc.ListPending()) +} + +func TestApprove_LosingToACancelWritesNoRowAndNoRedirect(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + id := fx.authorize(reg, "cursor") + fx.svc.testHookApproveAfterStore = func() { fx.svc.CancelAll("race") } + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + assert.ErrorIs(t, err, ErrOAuthRequestNotFound) + assert.Empty(t, redirect) + assert.Empty(t, fx.changeRows("approve")) + for _, e := range fx.eventsOf(EventTypeOAuthAuthorizationDecided) { + assert.NotEqual(t, "approved", e.Payload["status"]) + } +} + +// --- B5: wrong-origin replay ----------------------------------------------------------------------- + +func TestExchange_ReplayOnAnotherOriginDoesNotRevokeTheLogin(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + require.Nil(t, terr) + + in := fx.tokenInput(reg, code) + in.Origin = "http://localhost:8080" + _, terr = fx.svc.Exchange(in) + requireInvalidGrant(t, terr) + gs := fx.grants() + require.Len(t, gs, 1) + assert.False(t, gs[0].Revoked, "a foreign-origin replay revokes nothing") + assert.Empty(t, fx.changeRows("replay_revoke")) + // The same-origin replay still does. + _, terr = fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + assert.True(t, fx.grants()[0].Revoked) +} + +// --- B6: a dead grant never answers invalid_target --------------------------------------------------- + +func TestRefresh_DeadGrantAnswersInvalidGrantEvenWithAWrongResource(t *testing.T) { + fx := newOAuthFx(t) + reg, first := fx.loginNew("cursor", "ro") + gid := fx.grants()[0].GrantID + wrong := func(tok string) *TokenError { + _, terr := fx.svc.Refresh(TokenInput{Origin: oauthTestOrigin, RefreshToken: tok, ClientID: reg, Resource: oauthTestOrigin + "/mcp/oauth/other"}) + return terr + } + live := wrong(first.RefreshToken) + require.NotNil(t, live) + assert.Equal(t, TokenErrInvalidTarget, live.Code, "a live grant: the resource check applies") + + key := oauthTestKey + unknownTok, _, err := mcplogin.NewRefreshToken(key, strings.Repeat("A", mcplogin.GrantIDLen)) + require.NoError(t, err) + unknown := wrong(unknownTok) + + _, err = fx.sm.RevokeOAuthGrant(gid, storage.OAuthRevokeAdmin, fx.clock.Now()) + require.NoError(t, err) + revoked := wrong(first.RefreshToken) + + fx2 := newOAuthFx(t) + reg2, first2 := fx2.loginNew("cursor", "ro") + fx2.clock.Advance(OAuthRefreshTokenTTL + time.Hour) + _, expired := fx2.svc.Refresh(TokenInput{Origin: oauthTestOrigin, RefreshToken: first2.RefreshToken, ClientID: reg2, Resource: oauthTestOrigin + "/mcp/oauth/other"}) + + for name, e := range map[string]*TokenError{"unknown": unknown, "revoked": revoked, "expired": expired} { + require.NotNil(t, e, name) + assert.Equal(t, errInvalidGrant, e, name+": the one uniform answer") + } +} + +// --- B7: one resource identity -------------------------------------------------------------------------- + +func TestResource_SlashFormIsCanonicalisedEndToEnd(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + id, aerr := fx.svc.BeginAuthorization(fx.authInput(reg, oauthTestOrigin+"/mcp/oauth/cursor/")) + require.Nil(t, aerr) + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + require.NoError(t, err) + in := fx.tokenInput(reg, oauthCodeOf(t, redirect)) + in.Resource = oauthTestOrigin + "/mcp/oauth/cursor/" // the form the client sent + res, terr := fx.svc.Exchange(in) + require.Nil(t, terr) + assert.Equal(t, oauthTestOrigin+"/mcp/oauth/cursor", fx.grants()[0].Resource, "stored canonical") + + now := fx.clock.Now() + for _, p := range []string{"/mcp/oauth/cursor", "/mcp/oauth/cursor/"} { + _, _, aerr := fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, p, now) + assert.NoError(t, aerr, p) + } + _, terr = fx.svc.Refresh(TokenInput{Origin: oauthTestOrigin, RefreshToken: res.RefreshToken, ClientID: reg, Resource: oauthTestOrigin + "/mcp/oauth/cursor/"}) + require.Nil(t, terr, "the slash form the client sent still refreshes") +} + +func TestResource_RefreshAcceptsEitherFormAndGenericAddress(t *testing.T) { + fx := newOAuthFx(t) + reg, res := fx.loginNew("cursor", "ro") + r1, terr := fx.svc.Refresh(TokenInput{Origin: oauthTestOrigin, RefreshToken: res.RefreshToken, ClientID: reg, Resource: oauthTestOrigin + "/mcp/oauth/cursor/"}) + require.Nil(t, terr) + _, terr = fx.svc.Refresh(TokenInput{Origin: oauthTestOrigin, RefreshToken: r1.RefreshToken, ClientID: reg, Resource: oauthTestOrigin + "/mcp/oauth/cursor"}) + require.Nil(t, terr) + _, terr = fx.svc.Refresh(TokenInput{Origin: oauthTestOrigin, RefreshToken: "x", ClientID: reg, Resource: oauthTestOrigin + "/mcp/oauth/codex/"}) + require.NotNil(t, terr) + + // the generic address, with and without the slash + reg2 := fx.register() + id, aerr := fx.svc.BeginAuthorization(fx.authInput(reg2, oauthTestOrigin+"/mcp/oauth/")) + require.Nil(t, aerr) + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Client: ClientChoice{New: &NewClientChoice{ID: "acme"}}, Profile: oauthStrp("ro")}) + require.NoError(t, err) + res2, terr := fx.svc.Exchange(fx.tokenInput(reg2, oauthCodeOf(t, redirect))) + require.Nil(t, terr) + _, _, aerr2 := fx.svc.Authenticate(res2.AccessToken, oauthTestOrigin, "/mcp/oauth", fx.clock.Now()) + assert.NoError(t, aerr2) + _, _, aerr2 = fx.svc.Authenticate(res2.AccessToken, oauthTestOrigin, "/mcp/oauth/", fx.clock.Now()) + assert.NoError(t, aerr2) +} + +// --- B8: the profile must still exist --------------------------------------------------------------------- + +func TestExchange_NewClientProfileGoneAtExchange(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + fx.cfg.Profiles = fx.cfg.Profiles[1:] // "ro" deleted + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + fx.nothingStored() + rows := fx.changeRows("deny") + require.Len(t, rows, 1) + assert.Equal(t, "profile_gone", rows[0]["reason"]) +} + +// --- B9: Register is gated -------------------------------------------------------------------------------- + +func TestRegister_DisabledRefusesAndWritesNothing(t *testing.T) { + fx := newOAuthFx(t) + fx.cfg.MCPOAuthEnabled = false + _, rerr, err := fx.svc.Register(mcplogin.RegistrationRequest{RedirectURIs: []string{oauthTestRedirect}, ClientName: "x"}) + assert.ErrorIs(t, err, ErrOAuthFeatureDisabled) + assert.Nil(t, rerr) + regs, lerr := fx.sm.ListOAuthRegistrations() + require.NoError(t, lerr) + assert.Empty(t, regs) +} + +// --- C10: connect on a browser-only client ---------------------------------------------------------------- + +func TestConnect_BrowserOnlyClientKeepsItsBindingWhenNoProfileIsGiven(t *testing.T) { + fx := newOAuthFx(t) + fx.loginNew("cursor", "ro") + m := fx.clients.ConnectMinter() + + pin, mode, err := m.PreviewBinding("cursor", connect.CredentialIntent{}) + require.NoError(t, err) + assert.Equal(t, "ro", pin) + assert.Equal(t, auth.ProfileModeLocked, mode) + + issued, err := m.Issue("cursor", connect.CredentialIntent{}) + require.NoError(t, err) + assert.Equal(t, "ro", issued.Profile) + assert.Equal(t, auth.ProfileModeLocked, issued.Mode) + tok, _ := fx.sm.GetAgentTokenByName("client-cursor") + assert.Equal(t, "ro", tok.ProfilePin) + b, _ := fx.sm.GetOAuthClientBinding("cursor") + assert.Equal(t, "ro", b.ProfilePin) + assert.False(t, fx.grants()[0].Revoked, "logins unchanged") + require.NoError(t, m.Abort("cursor", connect.CredentialIntent{}, issued)) + + // An explicit profile still wins. + rw := "rw" + pin, _, err = m.PreviewBinding("cursor", connect.CredentialIntent{Profile: &rw}) + require.NoError(t, err) + assert.Equal(t, "rw", pin) +} + +// --- C11: create_client must not rebind an OAuth-only client ----------------------------------------------- + +func TestIssueClientMCP_RefusesAClientThatHasBrowserLogins(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + code := fx.approvedCode(reg, "", ApprovalChoice{Client: ClientChoice{New: &NewClientChoice{ID: "acme"}}, Profile: oauthStrp("ro")}) + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + require.Nil(t, terr) + + _, err := fx.creds.IssueClient(fx.ctx(), fx.actor(), IssueClientRequest{ + ID: "acme", Profile: "rw", ProfilePresent: true, ExpiresIn: "7d", RequireProfile: true, RefuseExistingRecord: true, + }) + var ce *CredentialError + require.True(t, errors.As(err, &ce)) + assert.Equal(t, "identity_exists", ce.Code()) + pin, _, _, _ := fx.sm.CurrentClientBinding("acme") + assert.Equal(t, "ro", pin, "nothing was rebound") +} + +// --- C12: list filters apply after the unfiltered record check ------------------------------------------------ + +func TestCredentialsList_ActiveFilterDoesNotFabricateAnOAuthOnlyRow(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + _, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + require.Nil(t, terr) + _, err = fx.clients.RevokeAPIKey(fx.ctx(), fx.actor(), "codex") + require.NoError(t, err) + + got, err := fx.creds.List(CredentialFilter{State: "active", Kind: "client"}) + require.NoError(t, err) + assert.Empty(t, got, "the client has an API-key record (revoked): no OAuth-only stand-in under an active filter") + got, err = fx.creds.List(CredentialFilter{State: "active"}) + require.NoError(t, err) + require.Len(t, got, 1) + assert.Equal(t, "browser_login", got[0].Kind) +} + +// --- C13: the explicit actor reaches the single-grant revoke ----------------------------------------------------- + +func TestCredentialsRevoke_OneGrantUsesTheSuppliedActor(t *testing.T) { + fx := newOAuthFx(t) + fx.loginNew("cursor", "ro") + gid := fx.grants()[0].GrantID + other := Actor{Kind: "agent_token", Name: "ops-bot", Surface: "mcp"} + _, err := fx.creds.Revoke(fx.ctx(), other, CredentialRef{Client: "cursor", Grant: gid}, false) + require.NoError(t, err) + rows := fx.changeRows("revoke") + require.Len(t, rows, 1) + assert.Equal(t, "ops-bot", rows[0]["actor_name"]) + assert.Equal(t, "agent_token", rows[0]["actor_kind"]) + assert.Equal(t, "mcp", rows[0]["surface"]) +} + +// --- C14: profile users take the pin from the API-key record --------------------------------------------------------- + +// A binary that knew nothing of browser logins moved only the API-key record: +// the record is the truth (storage.CurrentClientBinding), the entry is stale. +func TestProfilesService_UsedByTakesTheAPIKeyRecordPinOverADivergentEntry(t *testing.T) { + h := newProfilesHarness(t) + commitOAuthOnlyClient(t, h.rt.StorageManager(), "reg1", "grantAAAAAAAAAAAAAAAAAA", "acme", "ro", auth.ProfileModeLocked) + tokens := []auth.AgentToken{{ + Name: auth.ClientTokenName("acme"), Kind: auth.KindClient, ClientID: "acme", + ProfilePin: "full", ProfileMode: auth.ProfileModeSwitchable, Revoked: true, + }} + collect := func(pin string) *UsedBy { + u := &UsedBy{} + require.NoError(t, h.svc.addOAuthUsers(tokens, func(p string) *UsedBy { + if p == pin { + return u + } + return nil + })) + return u + } + assert.Empty(t, collect("ro").Clients, "the stale entry pin does not decide") + full := collect("full") + require.Len(t, full.Clients, 1) + assert.Equal(t, "acme", full.Clients[0].ID) + assert.Equal(t, auth.ProfileModeSwitchable, full.Clients[0].Mode) +} + +// --- C15: issued-credential prefixes ------------------------------------------------------------------------------------- + +func TestSecretShaped_RecognisesBrowserLoginTokens(t *testing.T) { + c := NewCredentialScreen(nil) + assert.True(t, c.SecretShaped("here: mcp_oat_abcdef")) + assert.True(t, c.SecretShaped("MCP_ORT_whatever")) + assert.False(t, c.SecretShaped("an ordinary sentence")) +} diff --git a/internal/runtime/oauth_login_round2_test.go b/internal/runtime/oauth_login_round2_test.go new file mode 100644 index 000000000..6ab8a6d10 --- /dev/null +++ b/internal/runtime/oauth_login_round2_test.go @@ -0,0 +1,179 @@ +package runtime + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/connect" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// --- 2: Approve finalisation cannot interleave with a cancel --------------------------------- + +func TestApprove_FinalisationIsAtomicAgainstASwitchOff(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + id := fx.authorize(reg, "cursor") + cancelDone := make(chan struct{}) + var once sync.Once + fx.svc.testHookApproveFinalising = func() { + once.Do(func() { + go func() { fx.svc.CancelAll("race"); close(cancelDone) }() + select { + case <-cancelDone: + t.Error("a cancel completed while Approve was finalising") + case <-time.After(100 * time.Millisecond): // it is blocked on lifecycleMu + } + }) + } + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + require.NoError(t, err, "the cancel came after finalisation") + code := oauthCodeOf(t, redirect) + <-cancelDone + require.Len(t, fx.changeRows("approve"), 1) + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) // the code was cancelled: fine and expected + fx.nothingStored() +} + +// --- 3: key I/O never blocks the switch-off ------------------------------------------------------ + +func TestSwitchOffDoesNotWaitOnLazyKeyInitialisation(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + release := make(chan struct{}) + entered := make(chan struct{}, 1) + svc := NewOAuthLoginService(OAuthLoginDeps{ + Store: fx.sm, Config: func() *config.Config { return fx.cfg }, Now: fx.clock.Now, + HMACKey: func() ([]byte, error) { + select { + case entered <- struct{}{}: + default: + } + <-release + return oauthTestKey, nil + }, + }) + go func() { _, _ = svc.BeginAuthorization(fx.authInput(reg, oauthTestOrigin+"/mcp/oauth/cursor")) }() + <-entered // key initialisation is now stalled + + done := make(chan struct{}) + go func() { + svc.CancelAll("switch_off") + unlock := svc.beginDisable("switch_off") + unlock() + close(done) + }() + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("the switch-off waited on key I/O") + } + close(release) +} + +// --- 4: connect rollback never restores a binding the guard refuses --------------------------------- + +func rollbackFixture(t *testing.T) (*oauthFx, connect.CredentialMinter, *connect.IssuedCredential) { + fx := newOAuthFx(t) + fx.loginNew("cursor", "ro") // browser-only client bound to ro (locked) + m := fx.clients.ConnectMinter() + rw := "rw" + issued, err := m.Issue("cursor", connect.CredentialIntent{Profile: &rw}) + require.NoError(t, err) + b, _ := fx.sm.GetOAuthClientBinding("cursor") + require.Equal(t, "rw", b.ProfilePin, "the connect moved both copies") + return fx, m, issued +} + +func TestConnectRollback_RestoresThePriorBindingWhenTheGuardAllowsIt(t *testing.T) { + fx, m, issued := rollbackFixture(t) + require.NoError(t, m.Abort("cursor", connect.CredentialIntent{}, issued)) + b, _ := fx.sm.GetOAuthClientBinding("cursor") + assert.Equal(t, "ro", b.ProfilePin, "as before: the aborted connect is undone") + tok, _ := fx.sm.GetAgentTokenByName("client-cursor") + assert.True(t, tok.Revoked) +} + +func TestConnectRollback_SkipsTheRestoreWhenTheGuardNowRefusesIt(t *testing.T) { + fx, m, issued := rollbackFixture(t) + fx.guard = StrictOfflineBindingGuard{} + fx.cfg.RequireMCPAuth = false // the config changed since the connect + + require.NoError(t, m.Abort("cursor", connect.CredentialIntent{}, issued)) + tok, _ := fx.sm.GetAgentTokenByName("client-cursor") + assert.True(t, tok.Revoked, "the API key is still revoked") + b, _ := fx.sm.GetOAuthClientBinding("cursor") + assert.Equal(t, "rw", b.ProfilePin, "the logins keep the binding the guard already accepts") + assert.False(t, fx.grants()[0].Revoked) + rows := fx.changeRows("forget") + require.Len(t, rows, 1) + diff, _ := rows[0]["diff"].(map[string]interface{}) + assert.Equal(t, "guard", diff["restore_skipped"]) +} + +func TestConnectRollback_APIKeyOnlyClientIsUnchanged(t *testing.T) { + fx := newOAuthFx(t) + m := fx.clients.ConnectMinter() + rw := "rw" + issued, err := m.Issue("cursor", connect.CredentialIntent{Profile: &rw}) + require.NoError(t, err) + fx.guard = StrictOfflineBindingGuard{} + fx.cfg.RequireMCPAuth = false + require.NoError(t, m.Abort("cursor", connect.CredentialIntent{}, issued)) + assert.Empty(t, fx.changeRows("forget"), "no row, exactly as before") +} + +// --- 5: a CredentialsService without a clients service ----------------------------------------------- + +func newClientlessCreds(fx *oauthFx) *CredentialsService { + return NewCredentialsService(CredentialsServiceDeps{ + Tokens: fx.sm, HMACKey: func() ([]byte, error) { return oauthTestKey, nil }, + Config: func() *config.Config { return fx.cfg }, Activity: func(*storage.ActivityRecord) error { return nil }, + Now: fx.clock.Now, + }) +} + +func TestRevokeByTokenName_WithoutAClientsService(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + cs := newClientlessCreds(fx) + + r, err := cs.Revoke(context.Background(), fx.actor(), CredentialRef{Token: "client-codex"}, true) + require.NoError(t, err, "no panic, the original token-revoke path") + assert.True(t, r.Changed) + r, err = cs.Revoke(context.Background(), fx.actor(), CredentialRef{Token: "client-codex"}, true) + require.NoError(t, err) + assert.False(t, r.Changed, "already revoked") +} + +func TestRevokeByTokenName_WithoutAClientsServiceButWithLogins(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + _, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + require.Nil(t, terr) + + cs := newClientlessCreds(fx) + _, err = cs.Revoke(context.Background(), fx.actor(), CredentialRef{Token: "client-codex"}, true) + var ce *CredentialError + require.True(t, errors.As(err, &ce), "a controlled error, not a panic") + tok, _ := fx.sm.GetAgentTokenByName("client-codex") + assert.False(t, tok.Revoked, "nothing half-done") + assert.False(t, fx.grants()[0].Revoked) +} + +var _ = mcplogin.AccessTokenPrefix diff --git a/internal/runtime/oauth_login_round3_test.go b/internal/runtime/oauth_login_round3_test.go new file mode 100644 index 000000000..334ec5107 --- /dev/null +++ b/internal/runtime/oauth_login_round3_test.go @@ -0,0 +1,296 @@ +package runtime + +import ( + "context" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/connect" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// --- the exchange is fenced against config publication (real runtime) ----------------------------- + +func enabledFunnelRuntime(t *testing.T) *Runtime { + t.Helper() + rt := newFunnelRuntime(t) + _, err := rt.Commit("test_on", func(tx *CommitTx) error { + return tx.MutateGlobal(func(c *config.Config) error { c.MCPOAuthEnabled = true; return nil }) + }) + require.NoError(t, err) + return rt +} + +func rtActor() context.Context { + return ContextWithActor(context.Background(), Actor{Kind: "api_key", Name: "admin", Surface: "api"}) +} + +// rtApprovedNewClient registers, authorizes at the generic address and approves a +// NEW client bound to profile pin; it returns the registration and the code. +func rtApprovedNewClient(t *testing.T, rt *Runtime, client, pin string) (reg, code string) { + t.Helper() + svc := rt.OAuthLoginService() + resp, rerr, err := svc.Register(mcplogin.RegistrationRequest{RedirectURIs: []string{oauthTestRedirect}, ClientName: "App"}) + require.NoError(t, err) + require.Nil(t, rerr) + reg = resp["client_id"].(string) + id, aerr := svc.BeginAuthorization(AuthorizeInput{ + Origin: oauthTestOrigin, ClientID: reg, RedirectURI: oauthTestRedirect, State: "s", + CodeChallenge: oauthTestChallenge(), Method: "S256", Resource: oauthTestOrigin + "/mcp/oauth", ResponseType: "code", + }) + require.Nil(t, aerr) + redirect, err := svc.Approve(rtActor(), id, ApprovalChoice{Client: ClientChoice{New: &NewClientChoice{ID: client}}, Profile: oauthStrp(pin)}) + require.NoError(t, err) + return reg, oauthCodeOf(t, redirect) +} + +func rtToken(reg, code string) TokenInput { + return TokenInput{Origin: oauthTestOrigin, Code: code, RedirectURI: oauthTestRedirect, ClientID: reg, CodeVerifier: oauthTestVerifier} +} + +func deleteProfileRO(c *config.Config) error { + kept := c.Profiles[:0:0] + for _, p := range c.Profiles { + if p.Name != "ro" { + kept = append(kept, p) + } + } + c.Profiles = kept + return nil +} + +// A config publication attempted DURING the exchange (the file-reload entry point +// and the API funnel) waits for it, then succeeds over the stored login. +func TestExchange_ConfigPublicationWaitsForTheExchange(t *testing.T) { + rt := enabledFunnelRuntime(t) + reg, code := rtApprovedNewClient(t, rt, "acme", "ro") + svc := rt.OAuthLoginService() + + reloadDone := make(chan error, 1) + funnelDone := make(chan error, 1) + var reloadFinished, funnelFinished atomic.Bool + var once sync.Once + svc.testHookBeforeCommit = func() { + once.Do(func() { + go func() { + _, err := rt.Commit(commitReasonFileReload, func(tx *CommitTx) error { return tx.MutateGlobal(deleteProfileRO) }) + reloadFinished.Store(true) + reloadDone <- err + }() + go func() { + _, _, err := rt.MutateConfig(context.Background(), funnelActor(), func(d *config.Config) (ChangeHint, error) { + d.AnonymousProfile = "" + return ChangeHint{}, nil + }, TokenRewrite{}) + funnelFinished.Store(true) + funnelDone <- err + }() + time.Sleep(150 * time.Millisecond) + if reloadFinished.Load() { + t.Error("a config publication completed while the exchange held the fence") + } + if funnelFinished.Load() { + t.Error("a funnel write completed while the exchange held the fence") + } + }) + } + + res, terr := svc.Exchange(rtToken(reg, code)) + require.Nil(t, terr, "the exchange saw the config as it was when it started") + require.NotEmpty(t, res.AccessToken) + require.NoError(t, <-reloadDone) + require.NoError(t, <-funnelDone) + + gs, err := rt.StorageManager().ListOAuthGrants() + require.NoError(t, err) + require.Len(t, gs, 1) + assert.False(t, gs[0].Revoked, "the login is handled by the ordinary config path afterwards") + pin, _, found, _ := rt.StorageManager().CurrentClientBinding("acme") + require.True(t, found) + assert.Equal(t, "ro", pin, "a now-dangling pin is deny-all, never wider") +} + +// A reload that completed just before: the exchange sees it and refuses. +func TestExchange_ReloadCompletedBeforeIsSeenAndRefused(t *testing.T) { + rt := enabledFunnelRuntime(t) + reg, code := rtApprovedNewClient(t, rt, "acme", "ro") + _, err := rt.Commit(commitReasonFileReload, func(tx *CommitTx) error { return tx.MutateGlobal(deleteProfileRO) }) + require.NoError(t, err) + + _, terr := rt.OAuthLoginService().Exchange(rtToken(reg, code)) + requireInvalidGrant(t, terr) + gs, _ := rt.StorageManager().ListOAuthGrants() + assert.Empty(t, gs) + reasons := []interface{}{} + for _, m := range profileChanges(t, rt) { + if m["change"] == "deny" { + reasons = append(reasons, m["reason"]) + } + } + assert.Equal(t, []interface{}{"profile_gone"}, reasons) +} + +// The replacement scenario: the reload that turned auth off came earlier, the +// binding was already bypassable. The pre-commit guard decides, once: the +// replacement succeeds and the client is never left with no live login. +func TestExchange_ReplacementOfAnAlreadyBypassableBindingSucceeds(t *testing.T) { + fx := newOAuthFx(t) + fx.guard = ConservativeBindingGuard{} + reg, _ := fx.loginNew("cursor", "ro") // auth on at the time + old := fx.grants()[0] + fx.cfg.RequireMCPAuth = false // a reload turned auth off earlier + + id := fx.authorize(reg, "cursor") + rev, _ := fx.sm.ClientBindingRevision("cursor") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev, ReplaceGrant: old.GrantID}) + require.NoError(t, err, "no new bypassable binding: the guard has nothing to add") + res, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + require.Nil(t, terr) + + live := 0 + for _, g := range fx.grants() { + if !g.Revoked { + live++ + } + } + assert.Equal(t, 1, live, "exactly the replacement is live") + _, _, aerr := fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth/cursor", fx.clock.Now()) + assert.NoError(t, aerr) +} + +// --- the lock-order hammer, with config commits ------------------------------------------------------------ + +func TestExchangeAgainstConfigCommitsRevokeAndReloadDoesNotDeadlockOrRace(t *testing.T) { + rt := enabledFunnelRuntime(t) + const n = 8 + type pending struct{ reg, code string } + var ps []pending + for i := 0; i < n; i++ { + reg, code := rtApprovedNewClient(t, rt, "app"+string(rune('a'+i)), "ro") + ps = append(ps, pending{reg, code}) + } + svc := rt.OAuthLoginService() + + done := make(chan struct{}) + go func() { + defer close(done) + var wg sync.WaitGroup + for _, p := range ps { + p := p + wg.Add(1) + go func() { defer wg.Done(); _, _ = svc.Exchange(rtToken(p.reg, p.code)) }() + } + for i := 0; i < 4; i++ { + wg.Add(4) + go func() { // the API commit path + defer wg.Done() + _, _ = rt.Commit("test", func(tx *CommitTx) error { + return tx.MutateGlobal(func(c *config.Config) error { c.ToolsLimit++; return nil }) + }) + }() + go func() { // the file-reload entry point + defer wg.Done() + _ = rt.ReloadConfiguration() + }() + go func() { // the funnel + defer wg.Done() + _, _, _ = rt.MutateConfig(context.Background(), funnelActor(), func(d *config.Config) (ChangeHint, error) { + return ChangeHint{}, nil + }, TokenRewrite{}) + }() + go func() { + defer wg.Done() + _, _ = rt.CredentialsService().Revoke(rtActor(), funnelActor(), CredentialRef{Client: "appa"}, false) + svc.CancelForClient("appb") + }() + } + wg.Wait() + }() + select { + case <-done: + case <-time.After(120 * time.Second): + t.Fatal("deadlock between the exchange and config commits") + } +} + +// --- connect rollback when the guard inspection itself fails --------------------------------------------- + +type armedFailStore struct { + *storage.Manager + armed *atomic.Bool +} + +func (a armedFailStore) ListOAuthGrants() ([]storage.OAuthGrant, error) { + if a.armed.Load() { + return nil, assert.AnError + } + return a.Manager.ListOAuthGrants() +} + +func failingRollbackFixture(t *testing.T) (*oauthFx, *ClientsService, *atomic.Bool) { + fx := newOAuthFx(t) + fx.loginNew("cursor", "ro") + armed := &atomic.Bool{} + cs := NewClientsService(ClientsServiceDeps{ + Store: armedFailStore{fx.sm, armed}, HMACKey: func() ([]byte, error) { return oauthTestKey, nil }, + Config: func() *config.Config { return fx.cfg }, Guard: func() BindingGuard { return stubGuard{} }, + Activity: func(r *storage.ActivityRecord) error { + fx.mu.Lock() + defer fx.mu.Unlock() + fx.rows = append(fx.rows, r) + return nil + }, + Now: fx.clock.Now, Mu: fx.clients.mu, + }) + return fx, cs, armed +} + +func TestConnectAbort_InspectionFailureStillRevokesTheFreshKey(t *testing.T) { + fx, cs, armed := failingRollbackFixture(t) + m := cs.ConnectMinter() + rw := "rw" + issued, err := m.Issue("cursor", connect.CredentialIntent{Profile: &rw}) + require.NoError(t, err) + armed.Store(true) + + require.NoError(t, m.Abort("cursor", connect.CredentialIntent{}, issued)) + tok, _ := fx.sm.GetAgentTokenByName("client-cursor") + assert.True(t, tok.Revoked, "the aborted connect's key is revoked whatever the inspection said") + b, _ := fx.sm.GetOAuthClientBinding("cursor") + assert.Equal(t, "rw", b.ProfilePin, "the prior binding is not restored") + rows := fx.changeRows("forget") + require.Len(t, rows, 1) + diff, _ := rows[0]["diff"].(map[string]interface{}) + assert.Equal(t, "inspect_error", diff["restore_skipped"]) +} + +func TestConnectUndo_InspectionFailureStillRevokesTheFreshKey(t *testing.T) { + fx, cs, armed := failingRollbackFixture(t) + m := cs.ConnectMinter() + rw := "rw" + _, err := m.Issue("cursor", connect.CredentialIntent{Profile: &rw}) + require.NoError(t, err) + armed.Store(true) + + name, err := m.ForgetUnheld("cursor", "", connect.CredentialIntent{}) + require.NoError(t, err) + assert.Equal(t, "client-cursor", name) + tok, _ := fx.sm.GetAgentTokenByName("client-cursor") + assert.True(t, tok.Revoked) + b, _ := fx.sm.GetOAuthClientBinding("cursor") + assert.Equal(t, "rw", b.ProfilePin) + rows := fx.changeRows("forget") + require.Len(t, rows, 1) + diff, _ := rows[0]["diff"].(map[string]interface{}) + assert.Equal(t, "inspect_error", diff["restore_skipped"]) +} + +var _ = auth.KindClient diff --git a/internal/runtime/oauth_login_round4_test.go b/internal/runtime/oauth_login_round4_test.go new file mode 100644 index 000000000..177600104 --- /dev/null +++ b/internal/runtime/oauth_login_round4_test.go @@ -0,0 +1,119 @@ +package runtime + +import ( + "context" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" +) + +func switchBrowserLogin(rt *Runtime, on bool) error { + _, err := rt.Commit("test_switch", func(tx *CommitTx) error { + return tx.MutateGlobal(func(c *config.Config) error { c.MCPOAuthEnabled = on; return nil }) + }) + return err +} + +func rtLogin(t *testing.T, rt *Runtime, client string) (reg string, res TokenResult) { + t.Helper() + reg, code := rtApprovedNewClient(t, rt, client, "ro") + res, terr := rt.OAuthLoginService().Exchange(rtToken(reg, code)) + require.Nil(t, terr) + return reg, res +} + +// A switch-off commit started during a refresh waits for the rotation. +func TestRefresh_SwitchOffCommitWaitsForTheRotation(t *testing.T) { + rt := enabledFunnelRuntime(t) + reg, res := rtLogin(t, rt, "acme") + svc := rt.OAuthLoginService() + + var finished atomic.Bool + done := make(chan error, 1) + var once sync.Once + svc.testHookInRotate = func() { + once.Do(func() { + go func() { + err := switchBrowserLogin(rt, false) + finished.Store(true) + done <- err + }() + time.Sleep(150 * time.Millisecond) + if finished.Load() { + t.Error("the switch-off completed while the refresh held the fence") + } + }) + } + _, terr := svc.Refresh(TokenInput{Origin: oauthTestOrigin, RefreshToken: res.RefreshToken, ClientID: reg}) + require.Nil(t, terr, "the refresh started before the switch-off") + require.NoError(t, <-done) + assert.False(t, svc.Enabled()) +} + +// A refresh that passed the early check but meets the switch-off at the fence is +// refused uniformly and the stored grant is byte-for-byte unchanged. +func TestRefresh_AfterSwitchOffLeavesTheGrantUntouched(t *testing.T) { + fx := newOAuthFx(t) + reg, res := fx.loginNew("cursor", "ro") + before, _ := fx.sm.GetOAuthGrant(fx.grants()[0].GrantID) + fx.svc.testHookBeforeRotateLock = func() { fx.cfg.MCPOAuthEnabled = false } + + fx.clock.Advance(time.Hour) + _, terr := fx.svc.Refresh(TokenInput{Origin: oauthTestOrigin, RefreshToken: res.RefreshToken, ClientID: reg}) + requireInvalidGrant(t, terr) + after, _ := fx.sm.GetOAuthGrant(before.GrantID) + assert.Equal(t, before.RefreshHash, after.RefreshHash, "secrets not rotated") + assert.Equal(t, before.AccessHash, after.AccessHash) + assert.True(t, before.RefreshExpiresAt.Equal(after.RefreshExpiresAt), "expiry not extended") + assert.False(t, after.Revoked) +} + +// Concurrent refreshes, exchanges, switch-offs and other config commits finish. +func TestRefreshExchangeAndSwitchOffHammerDoesNotDeadlockOrRace(t *testing.T) { + rt := enabledFunnelRuntime(t) + svc := rt.OAuthLoginService() + type login struct{ reg, refresh string } + var logins []login + for _, c := range []string{"appa", "appb", "appc", "appd"} { + reg, res := rtLogin(t, rt, c) + logins = append(logins, login{reg, res.RefreshToken}) + } + done := make(chan struct{}) + go func() { + defer close(done) + var wg sync.WaitGroup + for _, l := range logins { + l := l + for i := 0; i < 3; i++ { + wg.Add(1) + go func() { + defer wg.Done() + _, _ = svc.Refresh(TokenInput{Origin: oauthTestOrigin, RefreshToken: l.refresh, ClientID: l.reg}) + }() + } + } + for i := 0; i < 4; i++ { + wg.Add(3) + go func() { defer wg.Done(); _ = switchBrowserLogin(rt, false); _ = switchBrowserLogin(rt, true) }() + go func() { defer wg.Done(); _ = rt.ReloadConfiguration() }() + go func() { + defer wg.Done() + _, _, _ = rt.MutateConfig(context.Background(), funnelActor(), func(d *config.Config) (ChangeHint, error) { + return ChangeHint{}, nil + }, TokenRewrite{}) + }() + } + wg.Wait() + }() + select { + case <-done: + case <-time.After(120 * time.Second): + t.Fatal("deadlock between refresh and config commits") + } +} diff --git a/internal/runtime/oauth_login_service.go b/internal/runtime/oauth_login_service.go new file mode 100644 index 000000000..6115d6cab --- /dev/null +++ b/internal/runtime/oauth_login_service.go @@ -0,0 +1,594 @@ +package runtime + +import ( + "errors" + "sync" + "time" + + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/profile" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// OAuthLoginService is the runtime half of the browser login for MCP clients +// (Spec 132): registration, the authorization request and its consent +// decision, the token endpoint's exchange and refresh, access-token +// authentication, and the admin revoke of one login. +// +// LOCK ORDER (one rule, no cycles). Every path that pairs a storage write with +// the in-memory request store takes the runtime's bindingWriteMu FIRST and the +// request store's own mutex second: +// +// bindingWriteMu -> configCommitMu (Exchange only) -> mcplogin.Store.mu -> storage.Manager.mu +// +// - Exchange takes bindingWriteMu BEFORE calling Store.Consume, and its commit +// callback (which Consume runs under Store.mu) does NOT take bindingWriteMu +// again. That is why the callback may do the guard check and the storage +// commit: the lock above it is already held. +// - Revoke-client, forget-client and RevokeGrant hold bindingWriteMu (their +// own services take it) and then call Store.CancelForClient, the same order. +// - Approve holds bindingWriteMu while it validates the choice and calls +// Store.Approve, the same order. +// - The turn-off cancellation (beginDisable from the config commit) takes +// lifecycleMu and then Store.mu. It needs no bindingWriteMu: it is one +// in-memory step, atomic with Consume through Store.mu, and may run while the +// caller already holds bindingWriteMu (MutateConfig) or does not (reload). +// - Nothing holding Store.mu ever acquires bindingWriteMu (the commit callback +// never does), so the two cannot be taken in opposite orders. +// +// The switch-off boundary adds one lock, lifecycleMu, with the full order +// +// bindingWriteMu -> configCommitMu -> lifecycleMu -> {Runtime.mu | Store.mu} +// +// BeginAuthorization holds lifecycleMu only across "Enabled() -> Store.Create" +// (Enabled reads Runtime.mu, Create takes Store.mu: both are leaves below it) +// and never takes bindingWriteMu, configCommitMu, storage or any disk I/O under +// it. The commit holds it from CancelAll until the new config is published, so +// a request admitted before the switch-off is created before CancelAll runs +// (and cancelled by it), and one admitted after sees the switch off. Exchange's +// commit callback holds Store.mu and reads Runtime.mu through the guard, but no +// path holds Runtime.mu and then waits for Store.mu or lifecycleMu. +// +// Approve's finalisation (final status check, activity row, event, redirect) +// runs under lifecycleMu taken AFTER bindingWriteMu, so a switch-off cannot +// interleave with it; it does one storage write (the activity row) under it, and +// the switch-off commit only waits for that. The lazy token key is created before +// reqMu is taken (auth.GetOrCreateHMACKey is atomic): reqMu is never held across +// I/O, so existingRequests (and the switch-off) never wait on it. +// +// THE EXCHANGE FENCE. A file reload commits without bindingWriteMu, so Exchange +// takes bindingWriteMu, then configCommitMu (the lock every config publication +// holds), then Store.mu and storage, reads ONE config snapshot inside that +// section and uses it for every check. Publication is thereby fenced: a config +// change completes before the exchange starts (its checks refuse) or starts after +// the grant is stored (an ordinary change over an existing login). It is safe +// because no path holding configCommitMu waits for bindingWriteMu (MutateConfig +// and GuardedApplyConfig take bindingWriteMu BEFORE the commit; no commit hook, +// publish hook or callback calls a service that takes it), and the commit path +// never calls Exchange or Store.Consume. Key creation, token minting, events and +// notifier callbacks stay outside the fence. +type OAuthLoginService struct { + store OAuthLoginStore + hmacKey func() ([]byte, error) + cfg func() *config.Config + guard func() BindingGuard + // activity writes a profile_change row; publish emits an SSE event. + activity func(*storage.ActivityRecord) error + publish func(Event) + now func() time.Time + mu *sync.Mutex + logger *zap.Logger + // commitLock is the lock every config publication holds (the runtime's + // configCommitMu); nil in tests that build the service without a runtime. + commitLock sync.Locker + + notifier BindingNotifier + + // reqs is built on first use, because building it needs the token key and + // creating that key writes a file: a default-off install must not. + reqMu sync.Mutex + reqs *mcplogin.Store + + // lifecycleMu is the switch-off boundary (see the lock-order note): held + // across "enabled check -> Store.Create" in BeginAuthorization and across + // "CancelAll -> config published" in the commit. + lifecycleMu sync.Mutex + // test hooks, nil in production. + testHookBeginAfterEnabled func() + testHookApproveAfterStore func() + testHookApproveFinalising func() + testHookBeforeCommit func() + testHookBeforeRotateLock func() + testHookInRotate func() + + everUsed bool // positive results only + everMu sync.Mutex + touchMu sync.Mutex + lastTouch map[string]time.Time +} + +// OAuthLoginStore is the storage surface the service needs; *storage.Manager +// implements it. +type OAuthLoginStore interface { + ListAgentTokens() ([]auth.AgentToken, error) + GetAgentTokenByName(name string) (*auth.AgentToken, error) + CreateOAuthRegistration(reg storage.OAuthRegistration) error + GetOAuthRegistration(id string) (*storage.OAuthRegistration, error) + MarkOAuthRegistrationAuthorized(id string, at time.Time) error + CommitOAuthLogin(in storage.CommitLoginInput) (storage.OAuthGrant, error) + GetOAuthGrant(id string) (*storage.OAuthGrant, error) + ListOAuthGrants() ([]storage.OAuthGrant, error) + ListOAuthGrantsForClient(clientID string) ([]storage.OAuthGrant, error) + AuthenticateOAuthAccess(accessHash string, now time.Time) (*storage.OAuthGrant, error) + RotateOAuthRefresh(grantID, presentedSecretHash, newRefreshHash, newRefreshPrefix, newAccessHash string, now time.Time, accessTTL, refreshTTL time.Duration) (storage.RefreshOutcome, storage.OAuthGrant, error) + RevokeOAuthGrant(id, reason string, now time.Time) (bool, error) + TouchOAuthGrant(id string, lastUsedAt time.Time, observedName string) error + GetOAuthClientBinding(clientID string) (*storage.OAuthClientBinding, error) + ListOAuthClientBindings() (map[string]storage.OAuthClientBinding, error) + CurrentClientBinding(clientID string) (pin, mode string, found bool, err error) + ClientBindingRevision(clientID string) (string, error) + OAuthLoginEverUsed() (bool, error) +} + +// Token lifetimes of a browser login (research R6). +const ( + OAuthAccessTokenTTL = time.Hour + OAuthRefreshTokenTTL = 30 * 24 * time.Hour +) + +// OAuthLoginDeps wires an OAuthLoginService. Zero values are safe in tests: +// Now defaults to time.Now, Mu to a private mutex, Guard to the conservative +// evaluator, Logger to a no-op, Requests to a store built on first use. +type OAuthLoginDeps struct { + Store OAuthLoginStore + HMACKey func() ([]byte, error) + Config func() *config.Config + Guard func() BindingGuard + Activity func(*storage.ActivityRecord) error + Publish func(Event) + Now func() time.Time + Mu *sync.Mutex + Logger *zap.Logger + // Requests is the in-memory request and code store (tests inject one with + // a fake clock). + Requests *mcplogin.Store + // ConfigCommitLock fences the token exchange against config publication + // (see exchangeFenced). Nil is allowed. + ConfigCommitLock sync.Locker +} + +// NewOAuthLoginService builds the service. +func NewOAuthLoginService(d OAuthLoginDeps) *OAuthLoginService { + s := &OAuthLoginService{ + store: d.Store, hmacKey: d.HMACKey, cfg: d.Config, guard: d.Guard, activity: d.Activity, + publish: d.Publish, now: d.Now, mu: d.Mu, logger: d.Logger, reqs: d.Requests, commitLock: d.ConfigCommitLock, + lastTouch: map[string]time.Time{}, + } + if s.now == nil { + s.now = time.Now + } + if s.mu == nil { + s.mu = &sync.Mutex{} + } + if s.guard == nil { + s.guard = func() BindingGuard { return ConservativeBindingGuard{} } + } + if s.logger == nil { + s.logger = zap.NewNop() + } + if s.cfg == nil { + s.cfg = func() *config.Config { return nil } + } + return s +} + +// OAuthLoginService returns the runtime's browser-login service (Spec 132). +func (r *Runtime) OAuthLoginService() *OAuthLoginService { return r.oauthLoginService } + +// SetNotifier installs the live-session notifier (the server). +func (s *OAuthLoginService) SetNotifier(n BindingNotifier) { s.notifier = n } + +// Enabled reports whether the feature is on in the live configuration. +func (s *OAuthLoginService) Enabled() bool { + c := s.cfg() + return c != nil && c.MCPOAuthEnabled +} + +// EverUsed reports whether a browser login was ever stored. Only a positive +// answer is cached: the marker is never cleared, a negative one can change. +func (s *OAuthLoginService) EverUsed() bool { + s.everMu.Lock() + defer s.everMu.Unlock() + if s.everUsed { + return true + } + used, err := s.store.OAuthLoginEverUsed() + if err != nil { + s.logger.Warn("cannot read the browser-login marker", zap.Error(err)) + return false + } + s.everUsed = used + return used +} + +// requests returns the request store, building it on first use. +func (s *OAuthLoginService) requests() (*mcplogin.Store, error) { + if st := s.existingRequests(); st != nil { + return st, nil + } + // The key may be created on disk (atomically, see auth.GetOrCreateHMACKey): + // do that OUTSIDE reqMu, so existingRequests, and with it the switch-off + // path, never waits on key I/O. Then install the store under reqMu, + // double-checked: two racing builders hold the same key. + key, err := s.hmacKey() + if err != nil { + return nil, err + } + s.reqMu.Lock() + defer s.reqMu.Unlock() + if s.reqs == nil { + s.reqs = mcplogin.NewStore(key, s.now) + } + return s.reqs, nil +} + +// existingRequests returns the request store when one was ever built. +func (s *OAuthLoginService) existingRequests() *mcplogin.Store { + s.reqMu.Lock() + defer s.reqMu.Unlock() + return s.reqs +} + +// --- cancellation ------------------------------------------------------------ + +// CancelAll cancels every pending and approved-but-unconsumed request (the +// feature is being turned off). It takes the request store's mutex only (see +// the lock-order note): it may run under bindingWriteMu or without it. +func (s *OAuthLoginService) CancelAll(reason string) int { + s.lifecycleMu.Lock() + defer s.lifecycleMu.Unlock() + return s.cancelAllLocked(reason) +} + +// beginDisable is the switch-off boundary: it takes the lifecycle lock, cancels +// every request and returns the release the caller runs AFTER the new config +// is visible. A BeginAuthorization either created its request before this ran +// (and it is cancelled here) or waits and then sees the switch off. +func (s *OAuthLoginService) beginDisable(reason string) (release func()) { + s.lifecycleMu.Lock() + s.cancelAllLocked(reason) + return s.lifecycleMu.Unlock +} + +// cancelAllLocked snapshots the pending ids and cancels everything in one +// request-store critical section (s.lifecycleMu held). +func (s *OAuthLoginService) cancelAllLocked(reason string) int { + reqs := s.existingRequests() + if reqs == nil { + return 0 + } + pending, n := reqs.CancelAllReport() + for _, id := range pending { + s.publishDecided(id, string(mcplogin.StatusCancelled)) + } + if n > 0 { + s.logger.Info("cancelled browser sign-in requests", zap.Int("count", n), zap.String("reason", reason)) + } + return n +} + +// CancelForClient cancels the pending and approved requests that target the +// client, by address or by decision. Callers hold bindingWriteMu (revoke and +// forget run under it), so an exchange either completed before them or finds +// its request cancelled. +func (s *OAuthLoginService) CancelForClient(clientID string) int { + reqs := s.existingRequests() + if reqs == nil { + return 0 + } + var ids []string + for _, p := range reqs.ListPending() { + if p.PathClient == clientID { + ids = append(ids, p.ID) + } + } + n := reqs.CancelForClient(clientID) + for _, id := range ids { + s.publishDecided(id, string(mcplogin.StatusCancelled)) + } + return n +} + +func (s *OAuthLoginService) publishDecided(requestID, status string) { + if s.publish != nil { + s.publish(newEvent(EventTypeOAuthAuthorizationDecided, map[string]any{"request_id": requestID, "status": status})) + } +} + +// --- registration -------------------------------------------------------------- + +// ErrOAuthFeatureDisabled is the refusal of a public entry point while browser +// login is off. The HTTP layer maps it to 404. +var ErrOAuthFeatureDisabled = errors.New("browser login is disabled") + +// canonicalResource is THE resource identity: a resource that parses as an +// OAuth address on origin becomes origin + mcplogin.ResourcePath(client) (no +// trailing slash); anything else is returned unchanged, so it matches nothing. +// Stored and compared in this form everywhere. +func canonicalResource(origin, resource string) string { + if clientID, _, ok := mcplogin.ParseResource(origin, resource); ok { + return origin + mcplogin.ResourcePath(clientID) + } + return resource +} + +// Register validates an RFC 7591 request and stores a pending registration. +// The first return is the 201 body; the second a refusal shaped for the +// client; the third an internal failure. +func (s *OAuthLoginService) Register(req mcplogin.RegistrationRequest) (map[string]any, *mcplogin.RegError, error) { + if !s.Enabled() { + return nil, nil, ErrOAuthFeatureDisabled // the HTTP layer answers 404; nothing is written + } + reg, regErr := mcplogin.ValidateRegistration(req) + if regErr != nil { + return nil, regErr, nil + } + id, err := mcplogin.NewClientID() + if err != nil { + return nil, nil, err + } + reg.ClientID = id + now := s.now().UTC() + if err := s.store.CreateOAuthRegistration(storage.OAuthRegistration{ + ClientID: id, ReportedName: reg.ClientName, RedirectURIs: reg.RedirectURIs, + SoftwareID: reg.SoftwareID, SoftwareVersion: reg.SoftwareVersion, + TokenEndpointAuthMethod: reg.TokenEndpointAuthMethod, GrantTypes: reg.GrantTypes, CreatedAt: now, + }); err != nil { + return nil, nil, err + } + return reg.Response(now), nil, nil +} + +// --- tokens ---------------------------------------------------------------------- + +// TokenInput is a token request, after the HTTP layer parsed the form. Origin +// is the origin of THIS request (mcplogin.Origin). +type TokenInput struct { + Origin string + Code string + RedirectURI string + ClientID string // the registration's client_id + CodeVerifier string + RefreshToken string + Resource string +} + +// TokenResult is a successful token answer. +type TokenResult struct { + AccessToken string `json:"access_token"` + TokenType string `json:"token_type"` + ExpiresIn int `json:"expires_in"` + RefreshToken string `json:"refresh_token"` +} + +// Token error codes (contracts/oauth-endpoints.md). +const ( + TokenErrInvalidGrant = "invalid_grant" + TokenErrInvalidTarget = "invalid_target" + TokenErrServer = "server_error" +) + +// TokenError is a refusal of the token endpoint: always 400 except +// server_error. Descriptions are deliberately uniform: they never tell which +// check failed. +type TokenError struct { + Code string + Description string +} + +func (e *TokenError) Error() string { return e.Code + ": " + e.Description } + +var ( + errInvalidGrant = &TokenError{Code: TokenErrInvalidGrant, Description: "the grant is invalid, expired or revoked"} + errInvalidTarget = &TokenError{Code: TokenErrInvalidTarget, Description: "the resource does not match the approved one"} + errTokenServer = &TokenError{Code: TokenErrServer, Description: "the server could not complete the request"} +) + +// errExchangeRefused is how an exchange re-check says "invalid_grant". +var errExchangeRefused = errors.New("oauth exchange refused") + +// newTokenSet mints the access and refresh tokens of a grant. +type tokenSet struct { + access, refresh string + accessHash, refreshHash, refreshPrefix string + displayPrefix string +} + +func newTokenSet(key []byte, grantID string) (*tokenSet, error) { + access, err := mcplogin.NewAccessToken() + if err != nil { + return nil, err + } + refresh, secret, err := mcplogin.NewRefreshToken(key, grantID) + if err != nil { + return nil, err + } + return &tokenSet{ + access: access, refresh: refresh, + accessHash: mcplogin.HashSecret(key, mcplogin.KindAccess, access), + refreshHash: mcplogin.HashSecret(key, mcplogin.KindRefresh, secret), + refreshPrefix: mcplogin.DisplayPrefix(refresh), + displayPrefix: mcplogin.DisplayPrefix(access), + }, nil +} + +func (t *tokenSet) result() TokenResult { + return TokenResult{ + AccessToken: t.access, TokenType: "Bearer", ExpiresIn: int(OAuthAccessTokenTTL / time.Second), + RefreshToken: t.refresh, + } +} + +// Exchange is the authorization-code grant. It is where the login is STORED +// (research R15): the request's origin is compared with the stored issuer +// first (a mismatch consumes nothing), then, under bindingWriteMu and the +// request store's single-use boundary, the PKCE verifier, client, redirect URI +// and resource are checked, the guard is re-run over the decided candidate and +// storage.CommitOAuthLogin re-checks the registration, the new-client id and +// the binding revision in one transaction. Any failed check answers +// invalid_grant (invalid_target for a resource mismatch) with nothing stored. +func (s *OAuthLoginService) Exchange(in TokenInput) (TokenResult, *TokenError) { + // Advisory early exit: a disabled install must not create a key file. The + // authoritative check is made on the one config snapshot taken below. + if !s.Enabled() { + return TokenResult{}, errInvalidGrant + } + // Everything that may touch the key file or mint secrets happens BEFORE the + // config-commit lock is taken. + reqs, err := s.requests() + if err != nil { + s.logger.Error("browser login: cannot build the request store", zap.Error(err)) + return TokenResult{}, errTokenServer + } + key, err := s.hmacKey() + if err != nil { + s.logger.Error("browser login: cannot read the token key", zap.Error(err)) + return TokenResult{}, errTokenServer + } + grantID, err := mcplogin.NewGrantID() + if err != nil { + return TokenResult{}, errTokenServer + } + ts, err := newTokenSet(key, grantID) + if err != nil { + return TokenResult{}, errTokenServer + } + // Events and notifier callbacks run after every lock is released. + var after []func() + res, terr := s.exchangeFenced(in, reqs, ts, grantID, &after) + for _, f := range after { + f() + } + return res, terr +} + +// exchangeFenced is the part of Exchange that runs inside the fence: +// bindingWriteMu, then configCommitMu (the lock every config publication, +// including a file reload, holds), then the request store and storage. With +// publication fenced a config change either completed before the exchange +// started (its checks see it and refuse) or starts after the grant is stored (an +// ordinary config change over an existing login, covered by the funnel's guard +// and repin logic). ONE config snapshot is read inside the fence and used for +// every check of this exchange. +func (s *OAuthLoginService) exchangeFenced(in TokenInput, reqs *mcplogin.Store, ts *tokenSet, grantID string, after *[]func()) (TokenResult, *TokenError) { + s.mu.Lock() + defer s.mu.Unlock() + if s.commitLock != nil { + s.commitLock.Lock() + defer s.commitLock.Unlock() + } + cfg := s.cfg() + if cfg == nil || !cfg.MCPOAuthEnabled { + return TokenResult{}, errInvalidGrant + } + + var ( + grant storage.OAuthGrant + decided mcplogin.Decision + target bool + ) + commit := func(req mcplogin.Request) (string, error) { + decided = req.Decision + // (the origin was already compared inside the store, before consumption) + if !mcplogin.VerifyS256(in.CodeVerifier, req.CodeChallenge) || + in.ClientID != req.RegistrationID || in.RedirectURI != req.RedirectURI { + return "", errExchangeRefused + } + if in.Resource != "" && canonicalResource(in.Origin, in.Resource) != req.Resource { + target = true + return "", errExchangeRefused + } + now := s.now().UTC() + // A new client's profile must still exist: a later profile of the same + // name must never apply silently to a decision made about another one. + if req.Decision.NewClient && req.Decision.Profile != "" && !profileConfigured(cfg, req.Decision.Profile) { + s.writeDecisionRow(profile.ChangeDeny, req, "profile_gone", now) + return "", errExchangeRefused + } + if err := s.recheckGuard(cfg, req.Decision); err != nil { + s.writeDecisionRow(profile.ChangeDeny, req, "guard", now) + return "", errExchangeRefused + } + if h := s.testHookBeforeCommit; h != nil { + h() + } + stored, err := s.store.CommitOAuthLogin(storage.CommitLoginInput{ + Grant: storage.OAuthGrant{ + GrantID: grantID, RegistrationID: req.RegistrationID, Client: req.Decision.ClientID, + RedirectURI: req.RedirectURI, Resource: req.Resource, Issuer: req.Issuer, + RefreshHash: ts.refreshHash, RefreshPrefix: ts.refreshPrefix, AccessHash: ts.accessHash, + AccessExpiresAt: now.Add(OAuthAccessTokenTTL), RefreshExpiresAt: now.Add(OAuthRefreshTokenTTL), + ApprovedAt: now, ApprovedBy: storage.OAuthActor{Kind: req.Decision.ActorKind, Name: req.Decision.ActorName}, + DisplayPrefix: ts.displayPrefix, + }, + Client: req.Decision.ClientID, NewClient: req.Decision.NewClient, + Pin: req.Decision.Profile, Mode: req.Decision.Mode, DisplayName: req.Decision.DisplayName, + ExpectedBindingRevision: req.Decision.BindingRevision, ReplaceGrantID: req.Decision.ReplaceGrantID, Now: now, + }) + if err != nil { + reason := "" + switch { + case errors.Is(err, storage.ErrOAuthBindingChanged): + reason = "binding_changed" + case errors.Is(err, storage.ErrOAuthClientExists): + reason = "client_exists" + case errors.Is(err, storage.ErrOAuthRegistrationGone): + reason = "registration_gone" + } + if reason == "" { + return "", err // a storage failure: not a refusal + } + s.writeDecisionRow(profile.ChangeDeny, req, reason, now) + return "", errExchangeRefused + } + grant = stored + return grantID, nil + } + + // The store compares the origin with the issuer kept on the code (also on + // its tombstone) BEFORE consumption and replay handling. + req, replayedGrant, err := reqs.ConsumeAt(in.Code, in.Origin, commit) + switch { + case err == nil: + case errors.Is(err, mcplogin.ErrCodeOriginMismatch): + return TokenResult{}, errInvalidGrant + case errors.Is(err, mcplogin.ErrCodeReused): + // A code presented again inside the tombstone window revokes the login + // it produced. An empty grant id means the first presentation stored + // nothing: there is nothing to revoke. + *after = append(*after, s.revokeReplayedCode(replayedGrant)...) + return TokenResult{}, errInvalidGrant + default: + if target { + return TokenResult{}, errInvalidTarget + } + if errors.Is(err, errExchangeRefused) || errors.Is(err, mcplogin.ErrCodeUnknown) { + return TokenResult{}, errInvalidGrant + } + s.logger.Error("browser login: token exchange failed", zap.Error(err)) + return TokenResult{}, errTokenServer + } + + s.writeGrantRow(profile.ChangeIssue, grant, decided, "") + *after = append(*after, func() { + s.publishGrantChanged(grant, profile.ChangeIssue, req.Decision.Profile) + if s.notifier != nil && decided.ReplaceGrantID != "" { + s.notifier.NotifyBindingChanged(auth.ClientTokenName(grant.Client)) + } + }) + return ts.result(), nil +} diff --git a/internal/runtime/oauth_login_service_test.go b/internal/runtime/oauth_login_service_test.go new file mode 100644 index 000000000..7c3c3229d --- /dev/null +++ b/internal/runtime/oauth_login_service_test.go @@ -0,0 +1,456 @@ +package runtime + +import ( + "net/url" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/profile" +) + +// --- BeginAuthorization --------------------------------------------------------- + +func TestBeginAuthorization_OrderOfChecks(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + + in := func(mut func(*AuthorizeInput)) *AuthorizeError { + a := fx.authInput(reg, oauthTestOrigin+"/mcp/oauth/codex") + mut(&a) + _, err := fx.svc.BeginAuthorization(a) + return err + } + // 1. unknown client or unregistered redirect: no redirect, whatever else is wrong. + e := in(func(a *AuthorizeInput) { a.ClientID = "nope"; a.ResponseType = "token" }) + require.NotNil(t, e) + assert.Equal(t, AuthorizeNoRedirect, e.Kind) + e = in(func(a *AuthorizeInput) { a.RedirectURI = "http://127.0.0.1:5555/other" }) + require.NotNil(t, e) + assert.Equal(t, AuthorizeNoRedirect, e.Kind) + // 2. a per-client resource of a client that does not exist: 404, no redirect, before the rest. + e = in(func(a *AuthorizeInput) { a.Resource = oauthTestOrigin + "/mcp/oauth/ghost"; a.ResponseType = "token" }) + require.NotNil(t, e) + assert.Equal(t, AuthorizeNotFound, e.Kind) + // A registry id without a record exists. + e = in(func(a *AuthorizeInput) { a.Resource = oauthTestOrigin + "/mcp/oauth/cursor" }) + assert.Nil(t, e) + // 3. redirectable errors. + e = in(func(a *AuthorizeInput) { a.ResponseType = "token" }) + require.NotNil(t, e) + assert.Equal(t, AuthorizeRedirect, e.Kind) + assert.Equal(t, "unsupported_response_type", e.Code) + e = in(func(a *AuthorizeInput) { a.Method = "plain" }) + assert.Equal(t, "invalid_request", e.Code) + e = in(func(a *AuthorizeInput) { a.CodeChallenge = "short" }) + assert.Equal(t, "invalid_request", e.Code) + e = in(func(a *AuthorizeInput) { a.Resource = oauthTestOrigin + "/mcp" }) + assert.Equal(t, "invalid_target", e.Code) + e = in(func(a *AuthorizeInput) { a.Resource = "http://localhost:8080/mcp/oauth/codex" }) + assert.Equal(t, "invalid_target", e.Code, "another origin is another resource") + + u, err := e.RedirectURL() + require.NoError(t, err) + pu, _ := url.Parse(u) + assert.Equal(t, "invalid_target", pu.Query().Get("error")) + assert.Equal(t, "st-1", pu.Query().Get("state")) +} + +func TestBeginAuthorization_PublishesPendingAndMarksAuthorized(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + id := fx.authorize(reg, "cursor") + ev := fx.eventsOf(EventTypeOAuthAuthorizationPending) + require.Len(t, ev, 1) + assert.Equal(t, map[string]any{"request_id": id, "client_id": "cursor", "client_label": "cursor ide"}, ev[0].Payload) + got, err := fx.sm.GetOAuthRegistration(reg) + require.NoError(t, err) + assert.Equal(t, "authorized", got.State) + pend := fx.svc.ListPending() + require.Len(t, pend, 1) + assert.Equal(t, id, pend[0].ID) + assert.Equal(t, "cursor ide", pend[0].ClientLabel) + + // The generic address names no client in the event. + id2 := fx.authorize(reg, "") + ev = fx.eventsOf(EventTypeOAuthAuthorizationPending) + require.Len(t, ev, 2) + assert.Equal(t, id2, ev[1].Payload["request_id"]) + assert.Equal(t, "", ev[1].Payload["client_id"]) +} + +// --- Describe ----------------------------------------------------------------------- + +func TestDescribe_FixedClientOnPerClientAddress(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "codex") + + v, err := fx.svc.Describe(fx.ctx(), id) + require.NoError(t, err) + assert.Equal(t, "client", v.AddressKind) + require.NotNil(t, v.Client) + assert.Equal(t, "codex", v.Client.ID) + assert.True(t, v.Client.Exists) + assert.True(t, v.Client.HasAPIKey) + require.NotNil(t, v.Client.Binding) + assert.Equal(t, "ro", v.Client.Binding.Profile) + rev, err := fx.sm.ClientBindingRevision("codex") + require.NoError(t, err) + assert.Equal(t, rev, v.Client.Binding.Revision) + assert.False(t, v.ProfileRequired, "the client already has a binding") + assert.Empty(t, v.ExistingClients) + assert.Nil(t, v.PreviousLogin) + assert.Nil(t, v.Guard, "auth is on: nothing to refuse") + assert.Equal(t, "cursor ide", v.ReportedName, "shown, unverified") + assert.Len(t, v.Profiles, 2) +} + +func TestDescribe_GenericAddressListsClientsNothingPreselected(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + fx.mintClient("zed", "rw", auth.ProfileModeSwitchable) + reg := fx.register() // reports itself as "Cursor IDE" + id := fx.authorize(reg, "") + + v, err := fx.svc.Describe(fx.ctx(), id) + require.NoError(t, err) + assert.Equal(t, "generic", v.AddressKind) + assert.Nil(t, v.Client, "the generic address fixes nothing") + require.Len(t, v.ExistingClients, 2) + assert.Equal(t, "codex", v.ExistingClients[0].ID) + assert.Equal(t, "zed", v.ExistingClients[1].ID) + assert.True(t, v.ProfileRequired) + require.NotNil(t, v.SuggestedNewClient) + assert.Equal(t, "cursor-ide", v.SuggestedNewClient.ID) + + // The reported name never selects: an empty choice stays incomplete even + // though the app calls itself after an existing client. + pv, err := fx.svc.Preview(fx.ctx(), id, ApprovalChoice{}) + require.NoError(t, err) + assert.False(t, pv.Complete) + assert.Nil(t, pv.Access) +} + +func TestDescribe_SuggestedIDIsUniqueAndNeverARegistryID(t *testing.T) { + fx := newOAuthFx(t) + resp, _, err := fx.svc.Register(mcplogin.RegistrationRequest{RedirectURIs: []string{oauthTestRedirect}, ClientName: "Cursor"}) + require.NoError(t, err) + id := fx.authorize(resp["client_id"].(string), "") + v, err := fx.svc.Describe(fx.ctx(), id) + require.NoError(t, err) + assert.Equal(t, "cursor-2", v.SuggestedNewClient.ID, "cursor is a supported client's id") + assert.Equal(t, "cursor", v.SuggestedNewClient.DisplayName) +} + +func TestDescribe_ProfileRequiredOnlyWhenProfilesExistAndNoBinding(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + id := fx.authorize(reg, "cursor") // a registry client with no record yet + v, err := fx.svc.Describe(fx.ctx(), id) + require.NoError(t, err) + require.NotNil(t, v.Client) + assert.False(t, v.Client.Exists) + assert.Nil(t, v.Client.Binding) + assert.True(t, v.ProfileRequired) + + fx.cfg.Profiles = nil + v, err = fx.svc.Describe(fx.ctx(), id) + require.NoError(t, err) + assert.False(t, v.ProfileRequired, "no profiles are configured: All servers") +} + +func TestDescribe_PreviousLoginOnlyForTheSameRegistration(t *testing.T) { + fx := newOAuthFx(t) + reg, _ := fx.loginNew("cursor", "ro") + grants := fx.grants() + require.Len(t, grants, 1) + + id := fx.authorize(reg, "cursor") + v, err := fx.svc.Describe(fx.ctx(), id) + require.NoError(t, err) + require.NotNil(t, v.PreviousLogin) + assert.Equal(t, grants[0].GrantID, v.PreviousLogin.GrantID) + assert.Equal(t, 1, v.Client.Logins) + + // Another registration of the same client: signed in before? No: this + // registration never was. + other := fx.register() + id2 := fx.authorize(other, "cursor") + v2, err := fx.svc.Describe(fx.ctx(), id2) + require.NoError(t, err) + assert.Nil(t, v2.PreviousLogin) + + // A revoked login is not a previous login. + _, err = fx.svc.RevokeGrant(fx.ctx(), "cursor", grants[0].GrantID) + require.NoError(t, err) + v, err = fx.svc.Describe(fx.ctx(), id) + require.NoError(t, err) + assert.Nil(t, v.PreviousLogin) +} + +func TestDescribe_GuardVerdictForAFixedClientThatHasABinding(t *testing.T) { + fx := newOAuthFx(t) + fx.guard = ConservativeBindingGuard{} + reg, _ := fx.loginNew("cursor", "ro") // auth on: allowed + gs := fx.grants() + _, err := fx.svc.RevokeGrant(fx.ctx(), "cursor", gs[0].GrantID) + require.NoError(t, err) + fx.cfg.RequireMCPAuth = false + + id := fx.authorize(reg, "cursor") + v, err := fx.svc.Describe(fx.ctx(), id) + require.NoError(t, err) + require.NotNil(t, v.Guard, "a new live login on a named binding with auth off is refused") + assert.Equal(t, profile.ErrorCodeBindingBypassable, v.Guard.Code) + require.NotEmpty(t, v.Guard.Fixes) + assert.Equal(t, profile.GuardFixRequireMCPAuth, v.Guard.Fixes[0].Kind) +} + +func TestDescribe_DecidedOrUnknownRequestIsNotFound(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + id := fx.authorize(reg, "cursor") + _, err := fx.svc.Describe(fx.ctx(), "nope") + assert.ErrorIs(t, err, ErrOAuthRequestNotFound) + _, err = fx.svc.Deny(fx.ctx(), id) + require.NoError(t, err) + _, err = fx.svc.Describe(fx.ctx(), id) + assert.ErrorIs(t, err, ErrOAuthRequestNotFound, "decided: one uniform answer") +} + +// --- Preview ---------------------------------------------------------------------------- + +func TestPreview_CompleteVerdictAndWritesNothing(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + id := fx.authorize(reg, "cursor") + + // Profiles exist and none is chosen: incomplete, no verdict. + pv, err := fx.svc.Preview(fx.ctx(), id, ApprovalChoice{}) + require.NoError(t, err) + assert.False(t, pv.Complete) + assert.Nil(t, pv.Guard) + + pv, err = fx.svc.Preview(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + require.NoError(t, err) + assert.True(t, pv.Complete) + require.NotNil(t, pv.Access) + assert.Equal(t, PreviewAccess{Client: "cursor", Profile: "ro", Mode: auth.ProfileModeLocked, SameAccessAsExistingClient: false}, *pv.Access) + assert.Nil(t, pv.Guard) + + // auth off: the guard's verdict is part of the answer, not an error. + fx.guard = ConservativeBindingGuard{} + fx.cfg.RequireMCPAuth = false + pv, err = fx.svc.Preview(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + require.NoError(t, err) + require.NotNil(t, pv.Guard) + assert.Equal(t, profile.ErrorCodeBindingBypassable, pv.Guard.Code) + + // Invalid choices are the same errors approve answers. + _, err = fx.svc.Preview(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ghost")}) + assert.ErrorIs(t, err, ErrOAuthProfileNotFound) + + fx.nothingStored() + toks, lerr := fx.sm.ListAgentTokens() + require.NoError(t, lerr) + assert.Empty(t, toks, "a preview mints and writes nothing") + assert.Empty(t, fx.changeRows("approve")) + _, ok := fx.reqs.Get(id) + assert.True(t, ok) + r, _ := fx.reqs.Get(id) + assert.Equal(t, mcplogin.StatusPending, r.Status) +} + +func TestPreview_ExistingClientIsTheSameAccess(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "") + rev, err := fx.sm.ClientBindingRevision("codex") + require.NoError(t, err) + pv, err := fx.svc.Preview(fx.ctx(), id, ApprovalChoice{Client: ClientChoice{ID: "codex"}, BindingRevision: rev}) + require.NoError(t, err) + require.True(t, pv.Complete) + assert.True(t, pv.Access.SameAccessAsExistingClient) + assert.Equal(t, "ro", pv.Access.Profile) +} + +// --- Approve and Deny ---------------------------------------------------------------------- + +func TestApprove_StoresNothingAndRecordsTheDecision(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + id := fx.authorize(reg, "cursor") + + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + require.NoError(t, err) + u, err := url.Parse(redirect) + require.NoError(t, err) + assert.NotEmpty(t, u.Query().Get("code")) + assert.Equal(t, "st-1", u.Query().Get("state")) + assert.Equal(t, "127.0.0.1:5555", u.Host) + + fx.nothingStored() + toks, lerr := fx.sm.ListAgentTokens() + require.NoError(t, lerr) + assert.Empty(t, toks) + r, ok := fx.reqs.Get(id) + require.True(t, ok) + assert.Equal(t, mcplogin.StatusApproved, r.Status) + assert.Equal(t, "cursor", r.Decision.ClientID) + assert.True(t, r.Decision.NewClient) + assert.Equal(t, "ro", r.Decision.Profile) + assert.Equal(t, auth.ProfileModeLocked, r.Decision.Mode) + assert.Equal(t, "admin", r.Decision.ActorName) + + rows := fx.changeRows("approve") + require.Len(t, rows, 1) + assert.Equal(t, id, rows[0]["request_id"]) + assert.Equal(t, "api_key", rows[0]["actor_kind"]) + assert.Equal(t, "admin", rows[0]["actor_name"]) + assert.Equal(t, "cursor", rows[0]["client_id"]) + decided := fx.eventsOf(EventTypeOAuthAuthorizationDecided) + require.Len(t, decided, 1) + assert.Equal(t, "approved", decided[0].Payload["status"]) +} + +func TestApprove_NoStateInTheRedirectWhenTheClientSentNone(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + in := fx.authInput(reg, oauthTestOrigin+"/mcp/oauth/cursor") + in.State = "" + id, aerr := fx.svc.BeginAuthorization(in) + require.Nil(t, aerr) + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + require.NoError(t, err) + u, _ := url.Parse(redirect) + assert.False(t, u.Query().Has("state")) +} + +func TestDeny_RedirectsWithAccessDeniedAndWritesARow(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + id := fx.authorize(reg, "cursor") + redirect, err := fx.svc.Deny(fx.ctx(), id) + require.NoError(t, err) + u, _ := url.Parse(redirect) + assert.Equal(t, "access_denied", u.Query().Get("error")) + assert.Equal(t, "st-1", u.Query().Get("state")) + assert.Empty(t, u.Query().Get("code")) + rows := fx.changeRows("deny") + require.Len(t, rows, 1) + assert.Equal(t, id, rows[0]["request_id"]) + assert.Equal(t, "admin", rows[0]["actor_name"]) + fx.nothingStored() + _, err = fx.svc.Deny(fx.ctx(), id) + assert.ErrorIs(t, err, ErrOAuthAlreadyDecided) +} + +func TestApprove_Refusals(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + fx.mintClient("acme", "ro", auth.ProfileModeLocked) + reg := fx.register() + + t.Run("already decided", func(t *testing.T) { + id := fx.authorize(reg, "cursor") + _, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + require.NoError(t, err) + _, err = fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + assert.ErrorIs(t, err, ErrOAuthAlreadyDecided) + code, status, ok := OAuthErrorStatus(err) + assert.True(t, ok) + assert.Equal(t, "already_decided", code) + assert.Equal(t, 409, status) + }) + t.Run("client_fixed", func(t *testing.T) { + id := fx.authorize(reg, "cursor") + _, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Client: ClientChoice{ID: "codex"}, Profile: oauthStrp("ro")}) + assert.ErrorIs(t, err, ErrOAuthClientFixed) + _, err = fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Client: ClientChoice{New: &NewClientChoice{ID: "x"}}, Profile: oauthStrp("ro")}) + assert.ErrorIs(t, err, ErrOAuthClientFixed) + }) + t.Run("profile_required", func(t *testing.T) { + id := fx.authorize(reg, "cursor") + _, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{}) + assert.ErrorIs(t, err, ErrOAuthProfileRequired) + }) + t.Run("client_required on the generic address", func(t *testing.T) { + id := fx.authorize(reg, "") + _, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + assert.ErrorIs(t, err, ErrOAuthClientRequired) + }) + t.Run("profile_not_found", func(t *testing.T) { + id := fx.authorize(reg, "cursor") + _, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ghost")}) + assert.ErrorIs(t, err, ErrOAuthProfileNotFound) + }) + t.Run("identity_exists", func(t *testing.T) { + id := fx.authorize(reg, "") + _, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Client: ClientChoice{New: &NewClientChoice{ID: "acme"}}, Profile: oauthStrp("ro")}) + assert.ErrorIs(t, err, ErrOAuthIdentityExists) + }) + t.Run("reserved_identity", func(t *testing.T) { + id := fx.authorize(reg, "") + _, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Client: ClientChoice{New: &NewClientChoice{ID: "cursor"}}, Profile: oauthStrp("ro")}) + assert.ErrorIs(t, err, ErrOAuthReservedIdentity) + _, err = fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Client: ClientChoice{New: &NewClientChoice{ID: "Bad Id"}}, Profile: oauthStrp("ro")}) + var ve *ValidationError + assert.ErrorAs(t, err, &ve) + }) + t.Run("binding_changed on a stale or missing revision", func(t *testing.T) { + id := fx.authorize(reg, "codex") + _, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: "stale"}) + assert.ErrorIs(t, err, ErrOAuthBindingChanged) + _, err = fx.svc.Approve(fx.ctx(), id, ApprovalChoice{}) + assert.ErrorIs(t, err, ErrOAuthBindingChanged, "an existing client needs the revision the page displayed") + rev, _ := fx.sm.ClientBindingRevision("codex") + _, err = fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev, Profile: oauthStrp("rw")}) + assert.NoError(t, err, "the profile of an existing client is ignored") + }) + fx.nothingStored() +} + +func TestApprove_GuardRefusalCarriesTheFixesAndLeavesTheRequestPending(t *testing.T) { + fx := newOAuthFx(t) + fx.guard = ConservativeBindingGuard{} + fx.cfg.RequireMCPAuth = false + reg := fx.register() + id := fx.authorize(reg, "cursor") + _, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + var ge *BindingGuardError + require.ErrorAs(t, err, &ge, "a first approval is judged through its candidate entry") + require.NotEmpty(t, ge.Fixes) + assert.Equal(t, profile.GuardFixRequireMCPAuth, ge.Fixes[0].Kind) + code, status, _ := OAuthErrorStatus(err) + assert.Equal(t, profile.ErrorCodeBindingBypassable, code) + assert.Equal(t, 409, status) + r, _ := fx.reqs.Get(id) + assert.Equal(t, mcplogin.StatusPending, r.Status) + + // All servers (no pin) is not a named binding. + fx.cfg.Profiles = nil + _, err = fx.svc.Approve(fx.ctx(), id, ApprovalChoice{}) + assert.NoError(t, err) +} + +func TestApprove_NewCustomClientOnTheGenericAddress(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + id := fx.authorize(reg, "") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{ + Client: ClientChoice{New: &NewClientChoice{ID: "acme-agent", DisplayName: "Acme Agent"}}, Profile: oauthStrp("rw"), Mode: auth.ProfileModeSwitchable, + }) + require.NoError(t, err) + r, _ := fx.reqs.Get(id) + assert.Equal(t, "acme-agent", r.Decision.ClientID) + assert.Equal(t, "Acme Agent", r.Decision.DisplayName) + assert.Equal(t, auth.ProfileModeSwitchable, r.Decision.Mode) + assert.NotEmpty(t, oauthCodeOf(t, redirect)) +} diff --git a/internal/runtime/oauth_login_tokens.go b/internal/runtime/oauth_login_tokens.go new file mode 100644 index 000000000..50857cf1f --- /dev/null +++ b/internal/runtime/oauth_login_tokens.go @@ -0,0 +1,367 @@ +package runtime + +import ( + "context" + "errors" + "fmt" + "net/url" + "strings" + "time" + + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/clientidentity" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/connect" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/profile" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// --- refresh ---------------------------------------------------------------------- + +// Refresh is the refresh-token grant. Every refusal is the one indistinguishable +// invalid_grant, and none of them writes anything or extends a lifetime, except +// an authentic refresh token that is not the current one: that revokes the +// login (reason replay) and writes a replay_revoke row. +// +// Check order (FR-009, FR-032): origin, then parse and MAC, then the grant, +// then client and resource, then storage.RotateOAuthRefresh. +func (s *OAuthLoginService) Refresh(in TokenInput) (TokenResult, *TokenError) { + if !s.Enabled() { + return TokenResult{}, errInvalidGrant + } + key, err := s.hmacKey() + if err != nil { + s.logger.Error("browser login: cannot read the token key", zap.Error(err)) + return TokenResult{}, errTokenServer + } + grantID, secret, ok := mcplogin.ParseRefreshToken(key, in.RefreshToken) + if !ok { + return TokenResult{}, errInvalidGrant + } + grant, err := s.store.GetOAuthGrant(grantID) + if err != nil || grant == nil { + if err != nil && !errors.Is(err, storage.ErrOAuthGrantNotFound) { + s.logger.Warn("browser login: cannot read a grant", zap.Error(err)) + } + return TokenResult{}, errInvalidGrant + } + if grant.Issuer != in.Origin || grant.RegistrationID != in.ClientID { + return TokenResult{}, errInvalidGrant + } + // A dead grant answers the uniform invalid_grant BEFORE the resource check, + // so it never reveals its resource. (The rotation re-checks liveness inside + // its own transaction.) + if grant.Revoked || !grant.RefreshExpiresAt.After(s.now()) { + return TokenResult{}, errInvalidGrant + } + if in.Resource != "" && canonicalResource(in.Origin, in.Resource) != grant.Resource { + return TokenResult{}, errInvalidTarget + } + ts, err := newTokenSet(key, grantID) + if err != nil { + s.logger.Error("browser login: cannot mint tokens", zap.Error(err)) + return TokenResult{}, errTokenServer + } + outcome, after, rerr := s.rotateFenced(grantID, mcplogin.HashSecret(key, mcplogin.KindRefresh, secret), ts) + if rerr != nil { + return TokenResult{}, rerr + } + switch outcome { + case storage.RefreshRotated: + return ts.result(), nil + case storage.RefreshReplay: + s.writeGrantRow(profile.ChangeReplayRevoke, after, mcplogin.Decision{}, "refresh_replay") + s.publishGrantChanged(after, profile.ChangeReplayRevoke, "") + s.notifyGrantRevoked(after) + } + return TokenResult{}, errInvalidGrant +} + +// revokeReplayedCode revokes the login an authorization code produced when the +// code is presented again inside the tombstone window. The revoke and its +// activity row happen now (under the caller's locks); the event and the +// notifier callback are returned to run after they are released. +func (s *OAuthLoginService) revokeReplayedCode(grantID string) []func() { + if grantID == "" { + return nil + } + now := s.now().UTC() + changed, err := s.store.RevokeOAuthGrant(grantID, storage.OAuthRevokeReplay, now) + if err != nil { + if !errors.Is(err, storage.ErrOAuthGrantNotFound) { + s.logger.Error("browser login: cannot revoke a replayed login", zap.Error(err)) + } + return nil + } + if !changed { + return nil + } + g, err := s.store.GetOAuthGrant(grantID) + if err != nil || g == nil { + return nil + } + s.writeGrantRow(profile.ChangeReplayRevoke, *g, mcplogin.Decision{}, "code_replay") + return []func(){func() { + s.publishGrantChanged(*g, profile.ChangeReplayRevoke, "") + s.notifyGrantRevoked(*g) + }} +} + +// --- authentication ------------------------------------------------------------------ + +// ErrOAuthUnauthorized is the one answer for every failed access-token check. +var ErrOAuthUnauthorized = errors.New("oauth access token not accepted") + +// Authenticate resolves an mcp_oat_ access token presented at origin+path. The +// grant must be live, its resource must be exactly this origin and path, and +// (on a per-client address) its client must be the path's client. The binding +// is read through storage.CurrentClientBinding, so the API-key record wins. The +// context comes from auth.ClientAuthContext, the builder the mcp_cli_ path +// uses. Every failure is the same ErrOAuthUnauthorized. +func (s *OAuthLoginService) Authenticate(accessToken, origin, path string, now time.Time) (*auth.AuthContext, *storage.OAuthGrant, error) { + if !s.Enabled() || !mcplogin.IsAccessToken(accessToken) { + return nil, nil, ErrOAuthUnauthorized + } + clientID, _, ok := mcplogin.ParseResourcePath(path) + if !ok { + return nil, nil, ErrOAuthUnauthorized + } + key, err := s.hmacKey() + if err != nil { + return nil, nil, ErrOAuthUnauthorized + } + grant, err := s.store.AuthenticateOAuthAccess(mcplogin.HashSecret(key, mcplogin.KindAccess, accessToken), now) + if err != nil { + if !errors.Is(err, storage.ErrOAuthGrantNotFound) { + s.logger.Warn("browser login: access-token lookup failed", zap.Error(err)) + } + return nil, nil, ErrOAuthUnauthorized + } + if grant.Issuer != origin || grant.Resource != origin+mcplogin.ResourcePath(clientID) || + (clientID != "" && grant.Client != clientID) { + return nil, nil, ErrOAuthUnauthorized + } + pin, mode, found, err := s.store.CurrentClientBinding(grant.Client) + if err != nil || !found { + return nil, nil, ErrOAuthUnauthorized + } + ac := auth.ClientAuthContext(auth.ClientIdentity{ + ClientID: grant.Client, ProfilePin: pin, ProfileMode: mode, + CredentialKind: auth.CredentialKindOAuth, GrantID: grant.GrantID, + TokenPrefix: grant.DisplayPrefix, TokenGeneration: grant.GrantID, + }) + return ac, grant, nil +} + +// touchInterval bounds how often a grant's last-used stamp is rewritten. +const touchInterval = time.Minute + +// Touch stamps the grant's last use and, when non-empty, the name the client +// sent at initialize. It is best effort and off the request path, like the +// agent-token stamp: one write per grant per minute, a new observed name +// always. +func (s *OAuthLoginService) Touch(grantID, observedName string) { + if grantID == "" { + return + } + observed := clientidentity.SanitizeDisplay(observedName) + now := s.now() + s.touchMu.Lock() + last, seen := s.lastTouch[grantID] + if seen && observed == "" && now.Sub(last) < touchInterval { + s.touchMu.Unlock() + return + } + if len(s.lastTouch) > 4096 { + s.lastTouch = map[string]time.Time{} + } + s.lastTouch[grantID] = now + s.touchMu.Unlock() + go func() { + if err := s.store.TouchOAuthGrant(grantID, now, observed); err != nil && !errors.Is(err, storage.ErrOAuthGrantNotFound) { + s.logger.Debug("browser login: cannot stamp last use", zap.Error(err)) + } + }() +} + +// --- admin: list and revoke ------------------------------------------------------------ + +// ListGrants returns the client's browser logins, newest approval first. +func (s *OAuthLoginService) ListGrants(clientID string) ([]storage.OAuthGrant, error) { + return s.store.ListOAuthGrantsForClient(clientID) +} + +// ErrOAuthGrantNotFound is RevokeGrant's answer for a grant that is not the +// client's. +var ErrOAuthGrantNotFound = errors.New("browser login not found") + +// RevokeGrant revokes one login of a client (reason admin) under +// bindingWriteMu, writes a `revoke` row naming the request's actor, emits +// credentials.changed and tells live sessions so they drop on their next +// request. It reports whether the login changed (an already revoked login is +// not an error). +func (s *OAuthLoginService) RevokeGrant(ctx context.Context, clientID, grantID string) (bool, error) { + s.mu.Lock() + defer s.mu.Unlock() + return s.revokeGrantLocked(ctx, clientID, grantID) +} + +func (s *OAuthLoginService) revokeGrantLocked(ctx context.Context, clientID, grantID string) (bool, error) { + g, err := s.store.GetOAuthGrant(grantID) + if err != nil || g == nil || g.Client != clientID { + if err != nil && !errors.Is(err, storage.ErrOAuthGrantNotFound) { + return false, err + } + return false, ErrOAuthGrantNotFound + } + changed, err := s.store.RevokeOAuthGrant(grantID, storage.OAuthRevokeAdmin, s.now().UTC()) + if err != nil { + if errors.Is(err, storage.ErrOAuthGrantNotFound) { + return false, ErrOAuthGrantNotFound + } + return false, err + } + if !changed { + return false, nil + } + actor, _ := RequestActor(ctx) + if actor.Surface == "" { + actor.Surface = profile.SurfaceAPI + } + pin, _, _, _ := s.store.CurrentClientBinding(clientID) + writeChangeRecord(ctx, s.activity, s.logger, s.now(), actor, changeRecord{ + change: profile.ChangeRevoke, profile: pin, previousProfile: pin, + clientID: clientID, tokenName: auth.ClientTokenName(clientID), + meta: map[string]interface{}{"grant_id": grantID, "credential_kind": CredentialKindBrowserLogin}, + }) + // Terminating live MCP sessions or streams is NOT done here: a revoked login is + // refused on its NEXT request (storage no longer authenticates it), which the + // HTTP layer enforces per request. + s.publishGrantChanged(*g, profile.ChangeRevoke, pin) + s.notifyGrantRevoked(*g) + return true, nil +} + +// notifyGrantRevoked tells the sessions of the client's name that their +// binding state changed so they re-list. A revoked access token already stops +// authenticating on the next request (storage refuses it). +func (s *OAuthLoginService) notifyGrantRevoked(g storage.OAuthGrant) { + if s.notifier != nil { + s.notifier.NotifyBindingChanged(auth.ClientTokenName(g.Client)) + } +} + +// --- rows and events --------------------------------------------------------------------- + +// CredentialKindBrowserLogin is the credentials vocabulary's name for a grant. +const CredentialKindBrowserLogin = "browser_login" + +func (s *OAuthLoginService) publishGrantChanged(g storage.OAuthGrant, change profile.ChangeKind, pin string) { + if s.publish == nil { + return + } + s.publish(newEvent(EventTypeCredentialsChanged, map[string]any{ + "kind": CredentialKindBrowserLogin, "id": g.GrantID, "client": g.Client, + "token_name": auth.ClientTokenName(g.Client), "change": string(change), "profile": pin, + })) +} + +// writeGrantRow writes a row about a STORED login on the public token endpoint +// (issue, replay_revoke): it names the administrator who approved the login and +// says the trigger was the client. +func (s *OAuthLoginService) writeGrantRow(change profile.ChangeKind, g storage.OAuthGrant, d mcplogin.Decision, reason string) { + actor := Actor{Kind: g.ApprovedBy.Kind, Name: g.ApprovedBy.Name, Surface: profile.SurfaceAPI} + pin, _, _, _ := s.store.CurrentClientBinding(g.Client) + meta := map[string]interface{}{ + "grant_id": g.GrantID, "trigger": "client", "credential_kind": CredentialKindBrowserLogin, + "approved_by": map[string]interface{}{"kind": g.ApprovedBy.Kind, "name": g.ApprovedBy.Name}, + } + if reason != "" { + meta["reason"] = reason + } + if d.ReplaceGrantID != "" { + meta["replaced_grant"] = d.ReplaceGrantID + } + writeChangeRecord(context.Background(), s.activity, s.logger, s.now(), actor, changeRecord{ + change: change, profile: pin, previousProfile: pin, + clientID: g.Client, tokenName: auth.ClientTokenName(g.Client), meta: meta, + }) +} + +// writeDecisionRow writes the `deny` row of an exchange that was refused after +// approval: it names the approving administrator with trigger client. +func (s *OAuthLoginService) writeDecisionRow(change profile.ChangeKind, req mcplogin.Request, reason string, now time.Time) { + actor := Actor{Kind: req.Decision.ActorKind, Name: req.Decision.ActorName, Surface: profile.SurfaceAPI} + writeChangeRecord(context.Background(), s.activity, s.logger, now, actor, changeRecord{ + change: change, profile: req.Decision.Profile, + clientID: req.Decision.ClientID, tokenName: auth.ClientTokenName(req.Decision.ClientID), + meta: map[string]interface{}{"request_id": req.ID, "trigger": "client", "reason": reason}, + }) +} + +// --- guard ------------------------------------------------------------------------------- + +// guardStatesFor builds the current state and the candidate state a login of +// clientID with (pin, mode) would create: the candidate adds or replaces the +// client's own browser-login entry with Live true, before anything is stored. +// A storage read error is returned and the caller must refuse (fail closed). +func (s *OAuthLoginService) guardStatesFor(cfg *config.Config, clientID, pin, mode string) (current, candidate GuardState, err error) { + all, err := s.store.ListAgentTokens() + if err != nil { + return current, candidate, fmt.Errorf("cannot inspect client bindings: %w", err) + } + oauth, err := LoadOAuthBindings(s.store, s.now()) + if err != nil { + return current, candidate, err + } + tokens := guardedOnly(all) + current = GuardState{Config: cfg, Tokens: tokens, OAuthBindings: oauth} + candidate = GuardState{Config: cfg, Tokens: tokens, + OAuthBindings: withOAuthClient(oauth, OAuthBinding{ClientID: clientID, Pin: pin, Mode: mode, Live: true})} + return current, candidate, nil +} + +func (s *OAuthLoginService) recheckGuard(cfg *config.Config, d mcplogin.Decision) error { + cur, cand, err := s.guardStatesFor(cfg, d.ClientID, d.Profile, d.Mode) + if err != nil { + return err + } + return CheckBindingGuard(s.guard(), cur, cand) +} + +// --- name mismatch (research R14) ------------------------------------------------------- + +// OAuthNameMismatch derives the advisory warning of a login: the name the +// client sent at initialize is neither the name it registered with nor, for a +// registry client, one of its id, display name or ClientInfoNames. An empty +// observed name never mismatches. It takes no part in selection or +// authorization. +func OAuthNameMismatch(observed, reportedName, clientID string) bool { + norm := clientidentity.NormalizeRaw(observed) + if norm == "" { + return false + } + known := []string{reportedName} + if def := connect.FindClient(clientID); def != nil { + known = append(known, def.ID, def.Name) + known = append(known, def.ClientInfoNames...) + } + for _, k := range known { + if k != "" && (norm == clientidentity.NormalizeRaw(k) || clientidentity.AliasCandidate(observed) == clientidentity.NormalizeRaw(k)) { + return false + } + } + return true +} + +// redirectHost is the host part of a stored redirect URI, for listings. +func redirectHost(raw string) string { + u, err := url.Parse(raw) + if err != nil { + return "" + } + return strings.ToLower(u.Hostname()) +} diff --git a/internal/runtime/profiles_service.go b/internal/runtime/profiles_service.go index 5ca4784fb..0fbd6a0ec 100644 --- a/internal/runtime/profiles_service.go +++ b/internal/runtime/profiles_service.go @@ -240,6 +240,9 @@ func (s *ProfilesService) usedByAll(cfg *config.Config) (map[string]*UsedBy, err u.Tokens = append(u.Tokens, t.Name) } } + if err := s.addOAuthUsers(tokens, func(pin string) *UsedBy { return out[pin] }); err != nil { + return nil, err + } for _, u := range out { sortUsedBy(u) } @@ -281,6 +284,14 @@ func (s *ProfilesService) UsedBy(name string) (UsedBy, error) { u.Tokens = append(u.Tokens, t.Name) } } + if err := s.addOAuthUsers(tokens, func(pin string) *UsedBy { + if pin == name { + return &u + } + return nil + }); err != nil { + return u, err + } sortUsedBy(&u) if cfg := s.rt.Config(); cfg != nil { u.AnonymousProfile = cfg.AnonymousProfile == name diff --git a/internal/runtime/profiles_service_oauth.go b/internal/runtime/profiles_service_oauth.go new file mode 100644 index 000000000..0036aedf8 --- /dev/null +++ b/internal/runtime/profiles_service_oauth.go @@ -0,0 +1,62 @@ +package runtime + +import ( + "fmt" + "time" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +// addOAuthUsers adds the clients that are bound to a profile only through +// browser logins (Spec 132): a client with a live login and a named pin is a +// user of that profile exactly like one with an API key, so a profile delete +// reports it in profile_in_use and a reassign moves it. A client that has an +// active API-key record is already listed through the record and is not +// counted twice. target returns the used-by list for a pin, or nil when the +// pin is not one the caller collects. A read error fails the call (fail +// closed): an unreadable store must not look like "nobody uses it". +func (s *ProfilesService) addOAuthUsers(tokens []auth.AgentToken, target func(pin string) *UsedBy) error { + sm := s.rt.StorageManager() + if sm == nil { + return nil + } + now := time.Now() + bindings, err := LoadOAuthBindings(sm, now) + if err != nil { + return fmt.Errorf("cannot read browser-login bindings: %w", err) + } + if len(bindings) == 0 { + return nil + } + active := map[string]bool{} + recs := map[string]*auth.AgentToken{} + for i := range tokens { + t := &tokens[i] + if t.Kind != auth.KindClient || t.UserID != "" { + continue + } + recs[t.ClientID] = t + if !t.Revoked && t.ExpiresAt.After(now) { + active[t.ClientID] = true + } + } + for _, b := range bindings { + if !b.Live || active[b.ClientID] { + continue + } + // The API-key record, in any state, decides the binding (as + // EffectiveTokens and CurrentClientBinding do); the entry only when there + // is no record. + pin, mode := b.Pin, b.Mode + if rec := recs[b.ClientID]; rec != nil { + pin, mode = rec.ProfilePin, rec.ProfileMode + } + if pin == "" { + continue + } + if u := target(pin); u != nil { + u.Clients = append(u.Clients, UsedByClient{ID: b.ClientID, Mode: mode}) + } + } + return nil +} diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index 5416bc339..297ea6d31 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -448,6 +448,9 @@ type Runtime struct { // credentialsService is Spec 115's issuance/revocation facade over both // credential kinds; it shares bindingWriteMu with clientsService. credentialsService *CredentialsService + // oauthLoginService is Spec 132's browser-login service; it shares + // bindingWriteMu with the two services above. + oauthLoginService *OAuthLoginService // profilesService is Spec 108-f's single profiles service; the evaluator // and session hook are installed by the server. profilesService *ProfilesService @@ -776,6 +779,27 @@ func New(cfg *config.Config, cfgPath string, logger *zap.Logger) (*Runtime, erro Logger: logger, }) + // Spec 132: the browser-login service. Same mutex as the two services + // above (the one lock order is documented on OAuthLoginService); revoking + // or forgetting a client cancels that client's pending sign-in requests + // through it. + rt.oauthLoginService = NewOAuthLoginService(OAuthLoginDeps{ + Store: storageManager, + HMACKey: func() ([]byte, error) { + return auth.GetOrCreateHMACKey(rt.Config().DataDir) + }, + Config: rt.Config, + Guard: rt.BindingGuard, + Activity: storageManager.SaveActivity, + Publish: rt.publishEvent, + Mu: &rt.bindingWriteMu, + Logger: logger, + ConfigCommitLock: &rt.configCommitMu, + }) + rt.clientsService.SetLoginCanceler(func(clientID string) { rt.oauthLoginService.CancelForClient(clientID) }) + rt.credentialsService.SetOAuthLogin(rt.oauthLoginService) + rt.repairOAuthBindings() + rt.profilesService = newProfilesService(rt) // Spec 047: drainer goroutine that publishes coalesced servers.changed diff --git a/internal/server/mcp.go b/internal/server/mcp.go index ff7ae640c..5e4f997ee 100644 --- a/internal/server/mcp.go +++ b/internal/server/mcp.go @@ -818,6 +818,9 @@ func NewMCPProxyServer( if ac := auth.AuthContextFromContext(ctx); ac != nil && ac.AgentName != "" { sessionStore.SetSessionIdentity(sessionID, ac.AgentName, ac.ClientID) sessionStore.SetSessionTokenPrefix(sessionID, ac.TokenPrefix) + if ac.GrantID != "" { + sessionStore.SetSessionGrantID(sessionID, ac.GrantID) + } } sessionStore.SetSessionServer(sessionID, mcpserver.ServerFromContext(ctx)) // Spec 108-f F10: a session that presented no credential has diff --git a/internal/server/mcp_activity_attribution.go b/internal/server/mcp_activity_attribution.go index 09e3da93e..ec9e59841 100644 --- a/internal/server/mcp_activity_attribution.go +++ b/internal/server/mcp_activity_attribution.go @@ -69,6 +69,9 @@ func (p *MCPProxyServer) activityAttribution(ctx context.Context, sessionID stri if attr.ClientID == "" && ac.IsClientCredential() { attr.ClientID = ac.ClientID } + if attr.GrantID == "" { + attr.GrantID = ac.GrantID + } } if sessionID == "" { @@ -99,6 +102,9 @@ func (p *MCPProxyServer) activityAttribution(ctx context.Context, sessionID stri if attr.ClientID == "" && sessionCredential { attr.ClientID = info.ClientID } + if attr.GrantID == "" && sessionCredential { + attr.GrantID = info.GrantID + } if attr.ProfileSource == "" { attr.Profile = info.Profile attr.ProfileSource = info.ProfileSource diff --git a/internal/server/oauth_login_attribution_test.go b/internal/server/oauth_login_attribution_test.go new file mode 100644 index 000000000..30cc62848 --- /dev/null +++ b/internal/server/oauth_login_attribution_test.go @@ -0,0 +1,42 @@ +package server + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +func browserLoginContext(grant string) context.Context { + return auth.WithAuthContext(context.Background(), auth.ClientAuthContext(auth.ClientIdentity{ + ClientID: "cursor", ProfilePin: "dev", ProfileMode: auth.ProfileModeLocked, + CredentialKind: auth.CredentialKindOAuth, GrantID: grant, TokenPrefix: "mcp_oat_" + grant[:4], TokenGeneration: grant, + })) +} + +// Spec 132 R3: two logins of one client are two work sessions (the grant id is +// the credential generation), and a revoked login never merges with a new one. +func TestPrincipalFromContext_BrowserLoginsOfOneClientAreSeparate(t *testing.T) { + a, b := browserLoginContext("grantAAAAAAAAAAAAAAAAAA"), browserLoginContext("grantBBBBBBBBBBBBBBBBBB") + assert.NotEqual(t, principalFromContext(a), principalFromContext(b)) + assert.Contains(t, principalFromContext(a), "agent:client-cursor:") +} + +// Session-backed and request-backed activity both carry the grant id. +func TestActivityAttribution_BrowserLoginCarriesGrantID(t *testing.T) { + f := newProfilesV3RESTFixture(t, nil) + ctx := browserLoginContext("grantAAAAAAAAAAAAAAAAAA") + attr := f.proxy.activityAttribution(ctx, "") + assert.Equal(t, "grantAAAAAAAAAAAAAAAAAA", attr.GrantID) + assert.Equal(t, "cursor", attr.ClientID, "attributed to the client exactly like its mcp_cli_ credential") + assert.Equal(t, "client-cursor", attr.TokenName) + + // A ctx-less internal emitter reads the grant back from the session. + f.proxy.sessionStore.SetSession("s-oauth", "Cursor", "1.0", false, false, nil) + f.proxy.sessionStore.SetSessionIdentity("s-oauth", "client-cursor", "cursor") + f.proxy.sessionStore.SetSessionGrantID("s-oauth", "grantAAAAAAAAAAAAAAAAAA") + attr = f.proxy.activityAttribution(context.Background(), "s-oauth") + assert.Equal(t, "grantAAAAAAAAAAAAAAAAAA", attr.GrantID) +} diff --git a/internal/server/profile_binding_guard.go b/internal/server/profile_binding_guard.go index 529b9fa11..56990c033 100644 --- a/internal/server/profile_binding_guard.go +++ b/internal/server/profile_binding_guard.go @@ -41,6 +41,14 @@ func (p *MCPProxyServer) bindingGuardActive(idx *profileIndex) bool { } return true } + oauthBindings, err := runtime.LoadOAuthBindings(p.storage, time.Now()) + if err != nil { + if p.logger != nil { + p.logger.Error("cannot inspect browser-login bindings for anonymous profile guard", zap.Error(err)) + } + return true + } + tokens = runtime.GuardState{Tokens: tokens, OAuthBindings: oauthBindings}.EffectiveTokens(time.Now()) if cfg == nil || idx == nil || idx.cfg == nil { // During a publication gap the guard cannot compare reachability. Any // live named client binding therefore denies anonymous access until a @@ -123,15 +131,17 @@ func (p *MCPProxyServer) BindingGuardDelta(current, candidate runtime.GuardState curIdx := newProfileIndex(current.Config) candIdx := newProfileIndex(candidate.Config) already := make(map[string]bool) - for i := range current.Tokens { - t := ¤t.Tokens[i] + currentTokens := current.EffectiveTokens(e.now) + for i := range currentTokens { + t := ¤tTokens[i] if e.bypassable(current.Config, curIdx, t) { already[t.Name] = true } } var out []runtime.BindingRef - for i := range candidate.Tokens { - t := &candidate.Tokens[i] + candidateTokens := candidate.EffectiveTokens(e.now) + for i := range candidateTokens { + t := &candidateTokens[i] if !already[t.Name] && e.bypassable(candidate.Config, candIdx, t) { out = append(out, runtime.BindingRefOf(t)) } @@ -167,8 +177,9 @@ func (p *MCPProxyServer) BindingGuardFixes(candidate runtime.GuardState, delta [ altIdx := newProfileIndex(&alt) e := p.newGuardEvaluation() qualifies := true - for i := range candidate.Tokens { - t := &candidate.Tokens[i] + fixTokens := candidate.EffectiveTokens(e.now) + for i := range fixTokens { + t := &fixTokens[i] if e.bypassable(&alt, altIdx, t) { qualifies = false break @@ -195,8 +206,16 @@ func (p *MCPProxyServer) BindingGuardActiveBindings() []runtime.BindingRef { } return nil } + oauthBindings, err := runtime.LoadOAuthBindings(p.storage, time.Now()) + if err != nil { + if p.logger != nil { + p.logger.Error("cannot inspect browser-login bindings for the binding guard", zap.Error(err)) + } + return nil + } idx := p.profileIndexFor(cfg) e := p.newGuardEvaluation() + tokens = runtime.GuardState{Tokens: tokens, OAuthBindings: oauthBindings}.EffectiveTokens(e.now) var out []runtime.BindingRef for i := range tokens { if e.bypassable(cfg, idx, &tokens[i]) { diff --git a/internal/server/profile_binding_guard_oauth_test.go b/internal/server/profile_binding_guard_oauth_test.go new file mode 100644 index 000000000..b8732a085 --- /dev/null +++ b/internal/server/profile_binding_guard_oauth_test.go @@ -0,0 +1,86 @@ +package server + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/profile" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/runtime" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// oauthOnlyGuardProxy builds a proxy whose only binding is a browser login: +// client "cursor", no API key, a live grant, bound to profile P (locked). +func oauthOnlyGuardProxy(t *testing.T, anonymousProfile string) (*MCPProxyServer, *profileIndex) { + t.Helper() + proxy, rt := createTestProxyWithRuntimeCfg(t, []*config.ServerConfig{{Name: "a", Enabled: true}}, func(cfg *config.Config) { + cfg.RequireMCPAuth = false + cfg.AnonymousProfile = anonymousProfile + cfg.Profiles = []config.ProfileConfig{{Name: "P", Servers: []string{"a"}}} + }) + sm := rt.StorageManager() + now := time.Now() + require.NoError(t, sm.CreateOAuthRegistration(storage.OAuthRegistration{ + ClientID: "reg1", ReportedName: "Cursor IDE", RedirectURIs: []string{"http://127.0.0.1:9/cb"}, + TokenEndpointAuthMethod: "none", GrantTypes: []string{"authorization_code", "refresh_token"}, CreatedAt: now, + })) + _, err := sm.CommitOAuthLogin(storage.CommitLoginInput{ + Grant: storage.OAuthGrant{ + GrantID: "grantAAAAAAAAAAAAAAAAAA", RegistrationID: "reg1", Client: "cursor", + RedirectURI: "http://127.0.0.1:9/cb", Resource: "http://127.0.0.1:8080/mcp/oauth/cursor", Issuer: "http://127.0.0.1:8080", + RefreshHash: "rh", AccessHash: "ah", AccessExpiresAt: now.Add(time.Hour), RefreshExpiresAt: now.Add(24 * time.Hour), + ApprovedAt: now, DisplayPrefix: "mcp_oat_abcd", + }, + Client: "cursor", NewClient: true, Pin: "P", Mode: auth.ProfileModeLocked, + ExpectedBindingRevision: storage.OAuthBindingAbsent, Now: now, + }) + require.NoError(t, err) + return proxy, proxy.profileIndexFor(proxy.currentConfig()) +} + +// Spec 132 R5: an OAuth-only client with a named pin and a live grant is an +// active binding, so an anonymous caller that could escape it is denied. +func TestBindingGuard_OAuthOnlyClientGuardsAnonymous(t *testing.T) { + proxy, idx := oauthOnlyGuardProxy(t, "") + got := proxy.ResolveProfileV3(context.Background(), idx) + require.Equal(t, string(profile.SourceAnonymous), got.Source) + require.True(t, got.BindingGuarded, "a live browser login bound to P is a binding anonymous could escape") + + active := proxy.BindingGuardActiveBindings() + require.Len(t, active, 1) + require.Equal(t, "cursor", active[0].ClientID) + require.Equal(t, "P", active[0].Profile) + + // Revoking the login ends the binding. + _, err := proxy.storage.RevokeOAuthGrant("grantAAAAAAAAAAAAAAAAAA", storage.OAuthRevokeAdmin, time.Now()) + require.NoError(t, err) + got = proxy.ResolveProfileV3(context.Background(), idx) + require.False(t, got.BindingGuarded, "a revoked login binds nothing") + require.Empty(t, proxy.BindingGuardActiveBindings()) +} + +func TestBindingGuard_OAuthEntryIsEvaluatedThroughItsCandidate(t *testing.T) { + proxy, _ := bindingGuardTestProxy(t, "", []config.ProfileConfig{{Name: "P", Servers: []string{"a"}}}, auth.ProfileModeLocked, "P") + cfg := proxy.currentConfig() + cur := runtime.GuardState{Config: cfg} + cand := runtime.GuardState{Config: cfg, OAuthBindings: []runtime.OAuthBinding{ + {ClientID: "cursor2", Pin: "P", Mode: auth.ProfileModeLocked, Live: true}, + }} + delta := proxy.BindingGuardDelta(cur, cand) + require.Len(t, delta, 1, "a first approval is judged through its candidate entry before anything is stored") + require.Equal(t, "cursor2", delta[0].ClientID) + fixes := proxy.BindingGuardFixes(cand, delta) + require.NotEmpty(t, fixes) + require.Equal(t, profile.GuardFixRequireMCPAuth, fixes[0].Kind) + + // Not live: no binding. Unchanged: nothing new. + cand.OAuthBindings[0].Live = false + require.Empty(t, proxy.BindingGuardDelta(cur, cand)) + cand.OAuthBindings[0].Live = true + require.Empty(t, proxy.BindingGuardDelta(cand, cand)) +} diff --git a/internal/server/session_store.go b/internal/server/session_store.go index 807be5854..d4eabe321 100644 --- a/internal/server/session_store.go +++ b/internal/server/session_store.go @@ -90,6 +90,10 @@ type SessionInfo struct { // no request context read it back so an event carries the same ownership // proof the SSE renderer checks (name AND prefix). TokenPrefix string + // GrantID is the browser-login grant that authenticated the session (Spec + // 132), set once at initialize like TokenName; empty for every other + // credential. INTERNAL: it only feeds activity attribution. + GrantID string // Anonymous marks a session that presented no credential (Spec 108-f F10): // its base is the snapshot's anonymous_profile, read at notify time. Memory diff --git a/internal/server/session_store_grant.go b/internal/server/session_store_grant.go new file mode 100644 index 000000000..0a55e87f7 --- /dev/null +++ b/internal/server/session_store_grant.go @@ -0,0 +1,15 @@ +package server + +// SetSessionGrantID records the browser-login grant that authenticated a +// session (Spec 132 R3), next to SetSessionTokenPrefix, so session-backed +// activity emitted without a request context still carries it. +func (s *SessionStore) SetSessionGrantID(sessionID, grantID string) { + if sessionID == "" { + return + } + s.mu.Lock() + defer s.mu.Unlock() + if info, ok := s.sessions[sessionID]; ok { + info.GrantID = grantID + } +} diff --git a/internal/storage/client_binding_hardening_test.go b/internal/storage/client_binding_hardening_test.go index 9105955fc..7487d0fdc 100644 --- a/internal/storage/client_binding_hardening_test.go +++ b/internal/storage/client_binding_hardening_test.go @@ -101,32 +101,21 @@ func TestUpdateClientCredentialBinding_ErrorTextUnchangedForAPIKeyOnly(t *testin // in ONE list in bbolt key order, whether regular token or client, so `before` // and the hook order are what they were before Spec 132. func TestRepinProfile_KeepsKeyOrderForRecordsAndHooks(t *testing.T) { - m, cleanup := setupTestStorageForAgentTokens(t) - defer cleanup() - mintTestClient(t, m, "cursor", auth.ProfileModeLocked, "p") - - keyOrder := func() []string { - var names []string - require.NoError(t, m.db.db.View(func(tx *bbolt.Tx) error { - return tx.Bucket([]byte(AgentTokensBucket)).ForEach(func(_, v []byte) error { - var tk auth.AgentToken - require.NoError(t, jsonUnmarshal(v, &tk)) - names = append(names, tk.Name) - return nil - }) - })) - return names - } - // Add agent tokens pinned to p until the client record sits in the middle. - for i := 0; i < 30; i++ { - tok, raw := makeTestToken("agent-" + string(rune('a'+i))) - tok.ProfilePin = "p" - require.NoError(t, m.CreateAgentToken(tok, raw, testHMACKey)) - names := keyOrder() - if len(names) >= 3 && names[0] != "client-cursor" && names[len(names)-1] != "client-cursor" { + // Keys are token hashes, so where the client record lands among the tokens + // is random, and the token count is capped. A store that leaves the client + // first or last (a few percent of runs) is thrown away and rebuilt. + var m *Manager + var keyOrder func() []string + for attempt := 0; attempt < 50; attempt++ { + mgr, cleanup := setupTestStorageForAgentTokens(t) + t.Cleanup(cleanup) + order, ok := repinOrderFixture(t, mgr) + if ok { + m, keyOrder = mgr, order break } } + require.NotNil(t, m, "no store put the client record between two tokens") want := keyOrder() require.NotEqual(t, "client-cursor", want[0]) require.NotEqual(t, "client-cursor", want[len(want)-1]) @@ -264,3 +253,34 @@ func TestRepinProfile_FailureKeepsErrorTextAndRollsBack(t *testing.T) { pin, _, _, _, _, _ := bindings(t, m, "cursor") assert.Equal(t, "p", pin) } + +// repinOrderFixture mints one client and agent tokens pinned to p until the +// client record sits between two tokens in bbolt key order. ok is false when +// it never does. +func repinOrderFixture(t *testing.T, m *Manager) (keyOrder func() []string, ok bool) { + t.Helper() + mintTestClient(t, m, "cursor", auth.ProfileModeLocked, "p") + + keyOrder = func() []string { + var names []string + require.NoError(t, m.db.db.View(func(tx *bbolt.Tx) error { + return tx.Bucket([]byte(AgentTokensBucket)).ForEach(func(_, v []byte) error { + var tk auth.AgentToken + require.NoError(t, jsonUnmarshal(v, &tk)) + names = append(names, tk.Name) + return nil + }) + })) + return names + } + for i := 0; i < 30; i++ { + tok, raw := makeTestToken("agent-" + string(rune('a'+i))) + tok.ProfilePin = "p" + require.NoError(t, m.CreateAgentToken(tok, raw, testHMACKey)) + names := keyOrder() + if len(names) >= 3 && names[0] != "client-cursor" && names[len(names)-1] != "client-cursor" { + return keyOrder, true + } + } + return keyOrder, false +} diff --git a/internal/storage/client_binding_update.go b/internal/storage/client_binding_update.go new file mode 100644 index 000000000..ceafb1530 --- /dev/null +++ b/internal/storage/client_binding_update.go @@ -0,0 +1,46 @@ +package storage + +import ( + "fmt" + + "go.etcd.io/bbolt" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +// UpdateOAuthClientBinding rewrites the binding of a client that has a +// browser-login entry, whether or not its API-key record is active (an +// UpdateClientCredentialBinding of a revoked or absent API key refuses). It +// goes through the one binding writer, so an API-key record that exists is kept +// equal. It returns the binding the client held before (the API-key record +// wins, as everywhere on the request path). ErrClientCredentialNotFound means +// the client has no browser-login entry. +func (m *Manager) UpdateOAuthClientBinding(clientID, pin, mode string) (beforePin, beforeMode string, err error) { + if !auth.ValidClientID(clientID) { + return "", "", fmt.Errorf("invalid client id %q", clientID) + } + if err := validateClientBinding(pin, mode); err != nil { + return "", "", err + } + m.mu.Lock() + defer m.mu.Unlock() + err = m.db.db.Update(func(tx *bbolt.Tx) error { + b, err := getOAuthBindingTx(tx, clientID) + if err != nil { + return err + } + if b == nil { + return ErrClientCredentialNotFound + } + var exists bool + beforePin, beforeMode, exists, err = currentClientBindingTx(tx, clientID) + if err != nil { + return err + } + if !exists { + return ErrClientCredentialNotFound + } + return writeClientBindingOptsTx(tx, clientID, pin, mode, true) + }) + return beforePin, beforeMode, err +} diff --git a/internal/storage/client_binding_update_test.go b/internal/storage/client_binding_update_test.go new file mode 100644 index 000000000..4911521cb --- /dev/null +++ b/internal/storage/client_binding_update_test.go @@ -0,0 +1,49 @@ +package storage + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +func TestUpdateOAuthClientBinding_OAuthOnlyClient(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + commitNew(t, m, "r", "g1", "webonly", "ro", auth.ProfileModeLocked, time.Now().UTC()) + + pin, mode, err := m.UpdateOAuthClientBinding("webonly", "", auth.ProfileModeSwitchable) + require.NoError(t, err) + assert.Equal(t, "ro", pin) + assert.Equal(t, auth.ProfileModeLocked, mode) + p, md, found, err := m.CurrentClientBinding("webonly") + require.NoError(t, err) + require.True(t, found) + assert.Equal(t, "", p) + assert.Equal(t, auth.ProfileModeSwitchable, md) + + // Invalid: locked needs a pin; nothing changes. + _, _, err = m.UpdateOAuthClientBinding("webonly", "", auth.ProfileModeLocked) + require.Error(t, err) + _, md, _, _ = m.CurrentClientBinding("webonly") + assert.Equal(t, auth.ProfileModeSwitchable, md) + + // A client with no browser-login entry is NotFound. + _, _, err = m.UpdateOAuthClientBinding("ghost", "ro", auth.ProfileModeLocked) + assert.ErrorIs(t, err, ErrClientCredentialNotFound) +} + +func TestUpdateOAuthClientBinding_KeepsBothCopiesEqualEvenWhenKeyIsRevoked(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + twoLoginClient(t, m) + _, err := m.RevokeClientAPIKey("cursor") + require.NoError(t, err) + + _, _, err = m.UpdateOAuthClientBinding("cursor", "rw", auth.ProfileModeSwitchable) + require.NoError(t, err, "a revoked API key does not block a binding change of a client with live logins") + assertEqualBindings(t, m, "cursor", "rw", auth.ProfileModeSwitchable) +}