diff --git a/cmd/mcpproxy/client_binding_cmd.go b/cmd/mcpproxy/client_binding_cmd.go index b67716641..712f17c2a 100644 --- a/cmd/mcpproxy/client_binding_cmd.go +++ b/cmd/mcpproxy/client_binding_cmd.go @@ -27,7 +27,7 @@ const adminKeyDocsURL = "https://docs.mcpproxy.app/configuration/config-file" func addClientBindingCommands(parent *cobra.Command) { parent.AddCommand(newClientSetProfileCmd(), newClientLockCmd(true), newClientLockCmd(false), - newClientAddCmd(), newClientRotateCmd(), newClientUpgradeAdminKeyHoldersCmd(), newClientForgetCmd()) + newClientAddCmd(), newClientRotateCmd(), newClientUpgradeAdminKeyHoldersCmd(), newClientForgetCmd(), newClientRevokeLoginCmd()) } func clientPath(id string) string { return "/api/v1/clients/" + url.PathEscape(id) } diff --git a/cmd/mcpproxy/client_binding_cmd_test.go b/cmd/mcpproxy/client_binding_cmd_test.go index 286169376..2fc064f0e 100644 --- a/cmd/mcpproxy/client_binding_cmd_test.go +++ b/cmd/mcpproxy/client_binding_cmd_test.go @@ -432,7 +432,7 @@ func TestClientForget_DisconnectAndError(t *testing.T) { func TestClientCommands_NoDaemonExit1(t *testing.T) { withNoDaemon(t) - for _, args := range [][]string{{"list"}, {"show", "x"}, {"set-profile", "x", "p"}, {"lock", "x"}, {"add", "x"}, {"rotate", "x"}, {"upgrade-admin-key-holders"}, {"forget", "x"}} { + for _, args := range [][]string{{"list"}, {"show", "x"}, {"set-profile", "x", "p"}, {"lock", "x"}, {"add", "x"}, {"rotate", "x"}, {"upgrade-admin-key-holders"}, {"forget", "x"}, {"revoke-login", "x", "g"}} { _, _, err := runCLI(t, GetClientCommand, "table", args...) require.Error(t, err, args) require.Equal(t, ExitCodeGeneralError, classifyError(err)) diff --git a/cmd/mcpproxy/client_cmd.go b/cmd/mcpproxy/client_cmd.go index b39f5fa71..ca3f0ff6f 100644 --- a/cmd/mcpproxy/client_cmd.go +++ b/cmd/mcpproxy/client_cmd.go @@ -77,7 +77,11 @@ type clientRow struct { ProfileMissing bool `json:"profile_missing"` ExpiresAt *time.Time `json:"expires_at"` RotationPending bool `json:"rotation_pending"` - Sessions []struct { + // Credentials and BrowserLoginDisabled exist only once browser login was + // used (Spec 132). + Credentials []clientCredentialRow `json:"credentials"` + BrowserLoginDisabled *bool `json:"browser_login_disabled"` + Sessions []struct { ID string `json:"id"` WorkSessionID string `json:"work_session_id"` StartedAt time.Time `json:"started_at"` @@ -208,6 +212,9 @@ func runClientShow(_ *cobra.Command, args []string) error { } fmt.Printf("Blocked 24h: %d\n", row.Blocked24h) } + if err := printClientCredentials(row.Credentials, row.BrowserLoginDisabled); err != nil { + return err + } fmt.Printf("Sessions: %d\n", len(row.Sessions)) if len(row.Sessions) > 0 { rows := make([][]string, 0, len(row.Sessions)) diff --git a/cmd/mcpproxy/client_logins_blank_test.go b/cmd/mcpproxy/client_logins_blank_test.go new file mode 100644 index 000000000..9fd796f97 --- /dev/null +++ b/cmd/mcpproxy/client_logins_blank_test.go @@ -0,0 +1,18 @@ +package main + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +// Review: a blank client or grant id must never reach the daemon, where a +// trailing slash could be routed to another handler. +func TestClientRevokeLogin_BlankIDsNeverSendARequest(t *testing.T) { + rec := newRESTRecorder(t, map[string]cannedResponse{}) + for _, args := range [][]string{{"", "g"}, {"cursor", ""}, {"cursor", " "}, {" ", "g"}} { + _, _, err := runCLI(t, GetClientCommand, "table", append([]string{"revoke-login"}, args...)...) + require.Error(t, err, "%q", args) + } + require.Empty(t, rec.requests) +} diff --git a/cmd/mcpproxy/client_logins_cmd.go b/cmd/mcpproxy/client_logins_cmd.go new file mode 100644 index 000000000..336e9f426 --- /dev/null +++ b/cmd/mcpproxy/client_logins_cmd.go @@ -0,0 +1,129 @@ +package main + +// Spec 132 PR-2b: the credentials of a client in `client show`, and +// `client revoke-login`. Both are thin clients of the /clients routes; the +// authorization (administrator only) lives server-side. + +import ( + "encoding/json" + "fmt" + "net/http" + "net/url" + "strings" + "time" + + "github.com/spf13/cobra" +) + +// clientCredentialRow is one entry of a client's `credentials` list. +type clientCredentialRow struct { + Kind string `json:"kind"` + Prefix string `json:"prefix"` + GrantID string `json:"grant_id"` + State string `json:"state"` + ExpiresAt *time.Time `json:"expires_at"` + ApprovedAt *time.Time `json:"approved_at"` + LastUsedAt *time.Time `json:"last_used_at"` + ReportedName string `json:"reported_name"` + RedirectHost string `json:"redirect_host"` + ObservedName string `json:"observed_name"` + NameMismatch bool `json:"name_mismatch"` +} + +func timeCell(t *time.Time) string { + if t == nil { + return "-" + } + return t.Format(time.RFC3339) +} + +// printClientCredentials renders the credentials block of `client show`. It +// prints nothing while the payload has no credentials list, so an install that +// never used browser login shows exactly what it showed before. The reported +// and observed names come from the client, so they are escaped for the +// terminal. +func printClientCredentials(creds []clientCredentialRow, loginDisabled *bool) error { + if creds == nil && loginDisabled == nil { + return nil + } + fmt.Println("Credentials:") + if len(creds) == 0 { + fmt.Println(" none") + } else { + rows := make([][]string, 0, len(creds)) + for _, c := range creds { + id := c.GrantID + if id == "" { + id = c.Prefix + } + detail := "-" + if c.Kind == "browser_login" { + detail = fmt.Sprintf("%s via %s", dashCell(sanitizeCell(c.ReportedName, 40)), dashCell(sanitizeCell(c.RedirectHost, 40))) + } + rows = append(rows, []string{c.Kind, sanitizeCell(id, 40), c.State, timeCell(c.ApprovedAt), timeCell(c.LastUsedAt), detail}) + } + if err := printTable([]string{"KIND", "ID", "STATE", "APPROVED", "LAST USED", "NAME VIA HOST"}, rows); err != nil { + return err + } + } + for _, c := range creds { + if c.Kind == "browser_login" && c.NameMismatch { + fmt.Printf("Warning: login %s reported the name %q but its client introduced itself as %q\n", + sanitizeCell(c.GrantID, 40), sanitizeCell(c.ReportedName, 60), sanitizeCell(c.ObservedName, 60)) + } + } + if loginDisabled != nil && *loginDisabled { + fmt.Println("Browser login: disabled (existing logins are listed; none can sign in)") + } + return nil +} + +func dashCell(s string) string { + if s == "" { + return "-" + } + return s +} + +func newClientRevokeLoginCmd() *cobra.Command { + return &cobra.Command{ + Use: "revoke-login ", + Short: "Revoke one browser login of a client", + Long: `Revoke one browser login (a sign-in a person approved on the consent page). +It stops working on its next request. The client's API key, its other logins and +its profile binding stay. Find the grant id with: mcpproxy client show + +Examples: + mcpproxy client revoke-login cursor 3f9a1c2e7b44`, + Args: argsOrHelpJSON(cobra.ExactArgs(2)), + RunE: func(_ *cobra.Command, args []string) error { + // A blank id would build a path ending in a slash: refuse it here. + if strings.TrimSpace(args[0]) == "" || strings.TrimSpace(args[1]) == "" { + return flagValidationError{fmt.Errorf("both the client id and the grant id are required")} + } + sess, err := newRESTSession("client") + if err != nil { + return err + } + data, ref, err := sess.call(http.MethodDelete, clientPath(args[0])+"/logins/"+url.PathEscape(args[1]), nil) + if e := clientRefusal(ref, err, args[0], ""); e != nil { + return e + } + if structuredOutput() { + return printData(data) + } + var res struct { + Changed bool `json:"changed"` + } + if err := json.Unmarshal(data, &res); err != nil { + return err + } + if res.Changed { + fmt.Printf("Revoked login %s of %s\n", args[1], args[0]) + } else { + fmt.Printf("Login %s of %s was already revoked\n", args[1], args[0]) + } + return nil + }, + } +} diff --git a/cmd/mcpproxy/client_logins_cmd_test.go b/cmd/mcpproxy/client_logins_cmd_test.go new file mode 100644 index 000000000..7a598027d --- /dev/null +++ b/cmd/mcpproxy/client_logins_cmd_test.go @@ -0,0 +1,72 @@ +package main + +import ( + "net/http" + "testing" + + "github.com/stretchr/testify/require" +) + +// Spec 132 PR-2b (T059): `client show` lists credentials and +// `client revoke-login` revokes one browser login. + +const cursorWithLogins = `{"id":"cursor","display_name":"Cursor","kind":"supported","state":"connected_seen","connected":true,"config_path":"/c","display_path":"~/c","active_sessions":0,"calls_24h":0,"blocked_24h":0,"credential_state":"client","token_name":"client-cursor","profile":"dev","profile_mode":"locked","sessions":[],` + + `"credentials":[` + + `{"kind":"api_key","prefix":"mcp_cli_ab12","state":"active","expires_at":"2027-01-01T00:00:00Z","last_used_at":"2026-11-22T10:00:00Z"},` + + `{"kind":"browser_login","grant_id":"grantAAAA","state":"active","approved_at":"2026-11-20T10:00:00Z","last_used_at":"2026-11-22T11:00:00Z","reported_name":"Cursor IDE","redirect_host":"127.0.0.1","observed_name":"cursor-vscode","name_mismatch":true},` + + `{"kind":"browser_login","grant_id":"grantBBBB","state":"lapsed","approved_at":"2026-10-01T10:00:00Z","reported_name":"\u001b[31mEvil","redirect_host":"localhost","name_mismatch":false}` + + `],"browser_login_disabled":true}` + +func TestClientShow_ListsCredentials(t *testing.T) { + newRESTRecorder(t, map[string]cannedResponse{"GET /api/v1/clients/cursor": okResp(cursorWithLogins)}) + out, _, err := runCLI(t, GetClientCommand, "table", "show", "cursor") + require.NoError(t, err) + require.Contains(t, out, "Credentials:") + require.Contains(t, out, "api_key") + require.Contains(t, out, "mcp_cli_ab12") + require.Contains(t, out, "grantAAAA") + require.Contains(t, out, "lapsed") + require.Contains(t, out, "127.0.0.1") + require.Contains(t, out, "Cursor IDE") + require.Contains(t, out, "Browser login: disabled") + require.Contains(t, out, "cursor-vscode", "the mismatch is spelled out") + require.NotContains(t, out, "\x1b", "an untrusted name never reaches the terminal raw") +} + +func TestClientShow_NoCredentialsFieldPrintsNothingNew(t *testing.T) { + newRESTRecorder(t, map[string]cannedResponse{"GET /api/v1/clients/cursor": okResp(cursorRow)}) + out, _, err := runCLI(t, GetClientCommand, "table", "show", "cursor") + require.NoError(t, err) + require.NotContains(t, out, "Credentials:") + require.NotContains(t, out, "Browser login") + assertGolden108(t, "client-show.golden", out) +} + +func TestClientRevokeLogin_DeletesOneLogin(t *testing.T) { + rec := newRESTRecorder(t, map[string]cannedResponse{"DELETE /api/v1/clients/cursor/logins/grantAAAA": okResp(`{"changed":true}`)}) + out, _, err := runCLI(t, GetClientCommand, "table", "revoke-login", "cursor", "grantAAAA") + require.NoError(t, err) + require.Equal(t, http.MethodDelete, rec.only(t).Method) + require.Contains(t, out, "Revoked login grantAAAA") + + newRESTRecorder(t, map[string]cannedResponse{"DELETE /api/v1/clients/cursor/logins/grantAAAA": okResp(`{"changed":false}`)}) + out, _, err = runCLI(t, GetClientCommand, "table", "revoke-login", "cursor", "grantAAAA") + require.NoError(t, err) + require.Contains(t, out, "already revoked") +} + +func TestClientRevokeLogin_UnknownLoginExitsNonZero(t *testing.T) { + newRESTRecorder(t, map[string]cannedResponse{"DELETE /api/v1/clients/cursor/logins/nope": refuse(http.StatusNotFound, `{"success":false,"error":"login not found"}`)}) + _, _, err := runCLI(t, GetClientCommand, "table", "revoke-login", "cursor", "nope") + require.Error(t, err) + require.Equal(t, ExitCodeGeneralError, classifyError(err)) +} + +func TestClientRevokeLogin_NeedsDaemonAndTwoArgs(t *testing.T) { + _, _, err := runCLI(t, GetClientCommand, "table", "revoke-login", "cursor") + require.Error(t, err) + withNoDaemon(t) + _, _, err = runCLI(t, GetClientCommand, "table", "revoke-login", "cursor", "g") + require.Error(t, err) + require.Contains(t, err.Error(), "client requires running daemon") +} diff --git a/docs/api/rest-api.md b/docs/api/rest-api.md index 35703bdb5..c93413b7e 100644 --- a/docs/api/rest-api.md +++ b/docs/api/rest-api.md @@ -1721,7 +1721,10 @@ reference: the Spec 132 contracts. - `GET /api/v1/clients` and `GET /api/v1/clients/{client}` gain `credentials[]` (the API key and each browser login: `kind`, `prefix`, `grant_id`, `state`, times, `reported_name`, `redirect_host`, `observed_name`, `name_mismatch`) and - `browser_login_disabled` once browser login was used. + `browser_login_disabled` once browser login was used. Both reads are + administrator-only (an agent token or client credential gets `403`), so the + reported names and redirect hosts never reach a scoped caller. The strings a + client reported are untrusted text: render them as text. - `DELETE /api/v1/clients/{client}/logins/{grant_id}` revokes one login (also while the feature is off after use); `DELETE /api/v1/clients/{client}/api-key` revokes the API key alone. diff --git a/docs/cli/profile-commands.md b/docs/cli/profile-commands.md index 75d8d8084..4f1de7a5f 100644 --- a/docs/cli/profile-commands.md +++ b/docs/cli/profile-commands.md @@ -74,6 +74,7 @@ A write that would let a client bound to a profile escape it while `require_mcp_ | `client add [--display-name N] [--profile P] [--lock\|--switchable] [--expires-in 90d]` | A custom client (a script, a CI job) with its own credential, printed once with a header snippet | | `client rotate [--yes]` / `--finalize` | Replace a credential without cutting the client off. A supported client previews the config change and asks to confirm (`--yes` for scripts; a non-interactive run without it exits 1); a custom client gets the new secret once and stays pending until `--finalize` or 24 hours | | `client upgrade-admin-key-holders [--profile P\|all] [--lock\|--switchable] [--yes]` | Replace the admin API key in every supported client's config with a per-client credential, after a preview. With `--profile` and `require_mcp_auth` off the guard can refuse: the command prints the preview and the refusal, exits 1 and changes nothing. It ends with the step that remains: rotate the admin API key | +| `client revoke-login ` | Revoke one [browser login](../features/client-oauth-login.md) of a client; its API key, its other logins and its binding stay. Find the grant id in `client show `, which lists the client's credentials (API key and logins, with state, approval and last use, reported name and redirect host, and a note when the initialize name differs) once browser login was used | | `client forget [--disconnect]` | Revoke the credential without touching the client's config; with `--disconnect` also remove the config entry of a supported client | `mcpproxy disconnect ` is the reverse of `connect`: it removes the config entry **and revokes the client's credential** (`client-`), so a secret copied out of the config stops authenticating at once. With a running daemon the command calls `DELETE /api/v1/connect/{client}`; without one it revokes over `config.db`. It prints `Credential: revoked (token client-cursor)`, or `Credential: none to revoke` for a client that had none. If the entry was removed but the revoke failed, the command still exits 0, prints `Credential: NOT revoked (...)` and the fix is `mcpproxy client forget `. Undoing a disconnect restores the config file only; the credential stays revoked and a later `connect` mints a new one. The revoked record keeps the client's prior profile pin and mode, so a `connect` that names no profile re-mints with that binding (a profile-locked client is never silently widened to All servers, and the reconnect preview shows it); pass `--profile` to choose a different one. With `require_mcp_auth` off, a named-profile binding is refused by the bypass guard (`binding_bypassable_without_auth`); enable `require_mcp_auth` or choose `--profile all` explicitly. The credential belongs to the client, so `--name ` for a non-default entry revokes it too. diff --git a/docs/features/client-oauth-login.md b/docs/features/client-oauth-login.md index e7c37f3f2..8ba837ecc 100644 --- a/docs/features/client-oauth-login.md +++ b/docs/features/client-oauth-login.md @@ -11,9 +11,10 @@ keywords: [oauth, browser login, mcp client, pkce, dynamic client registration, MCPProxy can act as a small OAuth 2.1 authorization server so that an MCP client that supports OAuth can sign in instead of carrying an API key in its config file. -It is **off by default** and **experimental**: in this release only the backend and -the administrator REST exist. There is no consent page yet, so an administrator -approves each sign-in through the REST API (see [Approving a sign-in](#approving-a-sign-in)). +It is **off by default** and **experimental**. An administrator approves each sign-in on +a consent page or through the REST API (see [Approving a sign-in](#approving-a-sign-in)) +and manages the logins in the Clients page, the CLI or the `credentials` MCP tool +(see [Managing logins](#managing-logins)). What it gives you: @@ -119,9 +120,39 @@ handed over. Everything the app reports is shown as plain text. - Without the admin API key in this browser the page asks you to open the request from the MCPProxy tray or paste the key, and makes no request until then. -## Seeing and revoking logins +## Managing logins -`GET /api/v1/clients` and `GET /api/v1/clients/` list each login under `credentials` +Everything here is for administrators. An agent token or a client credential cannot see +or revoke a login on any surface. + +**Settings.** One switch, "Browser login for MCP clients", marked Experimental, in +Security & Access (the tray Settings window has the same switch). It takes effect without a +restart. While it is off and was never used, no other page mentions browser login. + +**Clients page.** Expand a client to see its credentials: the API key and every login, each +with its state (`active`, `lapsed` when the refresh token expired, `revoked`), when it was +approved and last used, the name the app reported and the host it returns to. Those names +come from the app, so they are shown as plain text. A login whose client introduces itself +at `initialize` under a different name than the one it registered shows a "name mismatch" +note; it is advice, never a block. "Revoke login" revokes that one login, "Revoke API key" +revokes the key alone (the logins and the profile binding stay); both ask first. While the +switch is off after use, the page says browser login is disabled and still lists the +logins so they can be revoked. + +**CLI.** + +```bash +mcpproxy client show cursor # lists the API key and each login +mcpproxy client revoke-login cursor +``` + +**MCP.** The administrator `credentials` tool lists logins (`list` with `kind=browser_login`, +and they appear under `kind=all`), `get client=` includes them under `logins`, and +`revoke client= grant=` revokes one. `revoke client=` without `grant` +revokes everything under the client. No operation creates a login: only the person on the +consent page can approve one. See [credential lifecycle over MCP](./mcp-credential-lifecycle.md). + +**REST.** `GET /api/v1/clients` and `GET /api/v1/clients/` list each login under `credentials` (`kind: browser_login`, state `active`, `lapsed` or `revoked`, never the token). Revoke one with `DELETE /api/v1/clients//logins/`; the next request on that login, including on an open session, is refused. Forgetting a client removes all its logins. diff --git a/docs/features/mcp-credential-lifecycle.md b/docs/features/mcp-credential-lifecycle.md index df0ec4d74..6f5144dde 100644 --- a/docs/features/mcp-credential-lifecycle.md +++ b/docs/features/mcp-credential-lifecycle.md @@ -46,11 +46,15 @@ Reassigning a worker is the existing `profiles assign client= profile=` adds the client's logins under `logins` when it has any. `revoke client= grant=` revokes that one login (`identity_not_found` for an unknown grant or one that belongs to another client); `grant` needs `client`, and `revoke client=` alone still revokes everything under the client. The tool never creates a login: `create_client` and `create_token` issue API-key credentials only, and a login exists only after a person approves it on the consent page. `reported_name` and the other client-supplied strings are untrusted text. Every credential the tool issues: diff --git a/frontend/src/components/clients/ClientCredentials.vue b/frontend/src/components/clients/ClientCredentials.vue new file mode 100644 index 000000000..4a6ead392 --- /dev/null +++ b/frontend/src/components/clients/ClientCredentials.vue @@ -0,0 +1,122 @@ + + + diff --git a/frontend/src/components/settings/SettingField.vue b/frontend/src/components/settings/SettingField.vue index 7f747d1c1..dc4c12da5 100644 --- a/frontend/src/components/settings/SettingField.vue +++ b/frontend/src/components/settings/SettingField.vue @@ -19,6 +19,7 @@ title="Open documentation" @click.stop >docs ↗ + {{ field.badge }} restart diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.ts index 5362b8c42..29baab3df 100644 --- a/frontend/src/services/api.ts +++ b/frontend/src/services/api.ts @@ -1,5 +1,5 @@ import type { APIResponse, Server, Tool, ToolApproval, SearchResult, StatusUpdate, StatusResponse, SecretRef, MigrationAnalysis, ConfigSecretsResponse, GetToolCallsResponse, GetToolCallDetailResponse, GetServerToolCallsResponse, GetConfigResponse, ValidateConfigResponse, ConfigApplyResult, ServerTokenMetrics, GetRegistriesResponse, SearchRegistryServersResponse, RegistrySummary, CatalogSearchResponse, GetSessionsResponse, GetSessionDetailResponse, InfoResponse, ActivityListResponse, ActivityDetailResponse, ActivityRecord, ActivitySummaryResponse, ImportResponse, AgentTokenInfo, CreateAgentTokenRequest, CreateAgentTokenResponse, RoutingInfo, ConnectStatusResponse, ClientStatus, ConnectResult, ConnectPreview, OnboardingStateResponse, OnboardingMarkRequest, DiagnosticFixResponse, GlobalToolsResponse, UsageAggregateResponse, UsageWindow, UsageSort, UsageStatus, AttentionResponse, ReviewQueueResponse, ServerReviewResponse } from '@/types' -import type { ProfileConfig, ProfileList, ProfileView, ProfileWriteResult, ProfileRenameResult, ProfileDeleteResult, EffectiveToolsResult, TryProfileResponse, AccessExplanation, ExplainSubjectQuery, ClientView, ClientsResponse, BulkAssignResponse, CustomClientResponse, RotateResponse, UpgradePreview, UpgradeApplyResult, ForgetClientResponse, ConnectOptions, OAuthAuthorization, OAuthApprovalBody, OAuthPreview, OAuthDecision, SkillsListResponse, SkillContentResponse, SkillCopy, SkillsResponse } from '@/types/api' +import type { ProfileConfig, ProfileList, ProfileView, ProfileWriteResult, ProfileRenameResult, ProfileDeleteResult, EffectiveToolsResult, TryProfileResponse, AccessExplanation, ExplainSubjectQuery, ClientView, ClientsResponse, BulkAssignResponse, CustomClientResponse, RotateResponse, UpgradePreview, UpgradeApplyResult, ForgetClientResponse, RevokeCredentialResponse, ConnectOptions, OAuthAuthorization, OAuthApprovalBody, OAuthPreview, OAuthDecision, SkillsListResponse, SkillContentResponse, SkillCopy, SkillsResponse } from '@/types/api' import { joinHoldEvidence, type HoldEvidenceSource } from '@/utils/holdEvidence' @@ -1530,6 +1530,16 @@ class APIService { return this.data(`/api/v1/clients/${encodeURIComponent(id)}${queryString({ disconnect: opts.disconnect ? 'true' : undefined })}`, { method: 'DELETE' }) } + // Spec 132: revoke one browser login, or the API key alone (the client's logins + // and binding stay). Administrator only. + revokeClientLogin(id: string, grantId: string): Promise { + return this.data(`/api/v1/clients/${encodeURIComponent(id)}/logins/${encodeURIComponent(grantId)}`, { method: 'DELETE' }) + } + + revokeClientAPIKey(id: string): Promise { + return this.data(`/api/v1/clients/${encodeURIComponent(id)}/api-key`, { method: 'DELETE' }) + } + // Spec 132 sign-in requests (administrator only). All throw an ApiError whose // `status` and `code` the consent page branches on. getOAuthAuthorization(id: string): Promise { diff --git a/frontend/src/types/api.ts b/frontend/src/types/api.ts index a5557b781..eeefd93d2 100644 --- a/frontend/src/types/api.ts +++ b/frontend/src/types/api.ts @@ -1286,7 +1286,27 @@ export interface ClientSessionPresence { id: string; work_session_id?: string; s // Spec 108-f: a Clients row is Spec 109's presence fields plus the credential // and binding fields. The 108 fields are optional here so code written against // the 109 shape (and its fixtures) keeps compiling. +// Spec 132: one credential of a client. A browser login carries what the client +// reported about itself, so every string in it is untrusted text. +export interface ClientCredential { + kind: 'api_key' | 'browser_login' + prefix?: string + grant_id?: string + state: string // api_key: active|expired|revoked; browser_login: active|lapsed|revoked + expires_at?: string | null + approved_at?: string | null + last_used_at?: string | null + reported_name?: string + redirect_host?: string + observed_name?: string + name_mismatch?: boolean +} +export interface RevokeCredentialResponse { changed: boolean } + export type ClientPresence = Omit & { + // Spec 132: present only once browser login was used on this install. + credentials?: ClientCredential[] + browser_login_disabled?: boolean last_seen?: string | null credential_state?: CredentialState blocked_24h?: number diff --git a/frontend/src/views/Clients.vue b/frontend/src/views/Clients.vue index b9520b839..81b227880 100644 --- a/frontend/src/views/Clients.vue +++ b/frontend/src/views/Clients.vue @@ -28,6 +28,7 @@ Tools it sees Usage +

No sessions recorded.

Session {{ session.work_session_id || session.id }} @@ -62,6 +63,7 @@ import { useAuthStore } from '@/stores/auth' import ClientConnectList from '@/components/ClientConnectList.vue' import ProfileChip from '@/components/ProfileChip.vue' import ClientBindingControls from '@/components/ClientBindingControls.vue' +import ClientCredentials from '@/components/clients/ClientCredentials.vue' import GuardRefusal from '@/components/GuardRefusal.vue' import ClientsWarningsBanner from '@/components/clients/ClientsWarningsBanner.vue' import CustomClientDialog from '@/components/clients/CustomClientDialog.vue' diff --git a/frontend/src/views/settings/fields.ts b/frontend/src/views/settings/fields.ts index 86e5385c5..828396abc 100644 --- a/frontend/src/views/settings/fields.ts +++ b/frontend/src/views/settings/fields.ts @@ -76,6 +76,8 @@ export interface SettingField { defaultFor?: (cfg: any, ctx: DefaultContext) => unknown // Set for a textarea that edits a []string key (see ListKind). listKind?: ListKind + // Short label shown beside the field name (e.g. "Experimental"). + badge?: string } export interface SettingsAccordion { @@ -188,6 +190,13 @@ export const SECURITY_FIELDS: SettingField[] = [ help: 'When on, AI clients connecting to the /mcp endpoint must send the API key above (as an "Authorization: Bearer " header). Use “Connect a client” to configure this automatically. When off, any local client can connect without a key.', control: 'toggle', }, + { + key: 'mcp_oauth_enabled', + badge: 'Experimental', + label: 'Browser login for MCP clients', + help: 'Lets an MCP client that supports it sign in through your browser: you approve each request on a consent page in this UI, and the approval can be revoked later. Off by default; turning it on or off needs no restart, and existing logins stay listed either way.', + control: 'toggle', + }, { key: 'quarantine_enabled', defaultValue: true, // *bool, nil = on (Config.IsQuarantineEnabled) diff --git a/frontend/tests/unit/client-credentials.spec.ts b/frontend/tests/unit/client-credentials.spec.ts new file mode 100644 index 000000000..60363e04e --- /dev/null +++ b/frontend/tests/unit/client-credentials.spec.ts @@ -0,0 +1,168 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import ClientCredentials from '@/components/clients/ClientCredentials.vue' +import api from '@/services/api' + +vi.mock('@/services/api', () => ({ + default: { + revokeClientLogin: vi.fn(), + revokeClientAPIKey: vi.fn(), + }, +})) + +const apiKey = { kind: 'api_key', prefix: 'mcp_cli_ab12', state: 'active', expires_at: '2027-01-01T00:00:00Z', last_used_at: '2026-11-22T10:00:00Z' } +const login = (over: Record = {}) => ({ + kind: 'browser_login', grant_id: 'grantAAAA', state: 'active', approved_at: '2026-11-20T10:00:00Z', last_used_at: '2026-11-22T11:00:00Z', + reported_name: 'Cursor IDE', redirect_host: '127.0.0.1', observed_name: 'Cursor IDE', name_mismatch: false, ...over, +}) +const client = (credentials: unknown[] | undefined, disabled?: boolean) => ({ + id: 'cursor', display_name: 'Cursor', kind: 'supported', state: 'connected_seen', active_sessions: 0, last_seen: null, + ...(credentials === undefined ? {} : { credentials }), + ...(disabled === undefined ? {} : { browser_login_disabled: disabled }), +}) +const mountIt = (c: unknown) => mount(ClientCredentials, { props: { client: c as any } }) + +describe('ClientCredentials (Spec 132 T056)', () => { + beforeEach(() => { + vi.clearAllMocks() + ;(api.revokeClientLogin as any).mockResolvedValue({ changed: true }) + ;(api.revokeClientAPIKey as any).mockResolvedValue({ changed: true }) + }) + + it('lists the API key and each login with its state, times, reported name and redirect host', () => { + const w = mountIt(client([apiKey, login(), login({ grant_id: 'grantBBBB', state: 'lapsed' }), login({ grant_id: 'grantCCCC', state: 'revoked' })], false)) + expect(w.find('[data-test="credential-api_key"]').text()).toContain('mcp_cli_ab12') + const rows = w.findAll('[data-test^="credential-login-"]') + expect(rows.map(r => r.attributes('data-test'))).toEqual(['credential-login-grantAAAA', 'credential-login-grantBBBB', 'credential-login-grantCCCC']) + expect(w.get('[data-test="credential-state-grantAAAA"]').text()).toBe('active') + expect(w.get('[data-test="credential-state-grantBBBB"]').text()).toBe('lapsed') + expect(w.get('[data-test="credential-state-grantCCCC"]').text()).toBe('revoked') + const first = rows[0] + expect(first.get('[data-test="credential-reported-name"]').text()).toBe('Cursor IDE') + expect(first.get('[data-test="credential-redirect-host"]').text()).toBe('127.0.0.1') + expect(first.text()).toMatch(/Approved/) + expect(first.text()).toMatch(/Last used/) + expect(w.find('[data-test="browser-login-disabled"]').exists()).toBe(false) + }) + + it('renders client-controlled strings as text inside , never as HTML', () => { + const evil = '‮evil' + const w = mountIt(client([login({ reported_name: evil, redirect_host: 'host', observed_name: '', name_mismatch: true })], false)) + expect(w.find('img').exists()).toBe(false) + expect(w.find('script').exists()).toBe(false) + expect(w.find('b').exists()).toBe(false) + for (const sel of ['credential-reported-name', 'credential-redirect-host', 'credential-observed-name']) { + const el = w.get(`[data-test="${sel}"]`) + expect(el.element.tagName).toBe('BDI') + } + expect(w.get('[data-test="credential-reported-name"]').text()).toBe(evil) + }) + + it('warns, per login, when the name sent at initialize differs from the registered name', () => { + const w = mountIt(client([login({ name_mismatch: true, observed_name: 'cursor-vscode' }), login({ grant_id: 'grantBBBB' })], false)) + expect(w.find('[data-test="credential-mismatch-grantAAAA"]').exists()).toBe(true) + expect(w.get('[data-test="credential-mismatch-grantAAAA"]').text()).toContain('cursor-vscode') + expect(w.find('[data-test="credential-mismatch-grantBBBB"]').exists()).toBe(false) + }) + + it('shows "browser login disabled" and still lists the logins and their revoke buttons', () => { + const w = mountIt(client([login()], true)) + expect(w.get('[data-test="browser-login-disabled"]').text()).toMatch(/disabled/i) + expect(w.find('[data-test="credential-login-grantAAAA"]').exists()).toBe(true) + expect(w.find('[data-test="revoke-login-grantAAAA"]').exists()).toBe(true) + }) + + it('asks before revoking one login, then revokes only that login', async () => { + const w = mountIt(client([apiKey, login(), login({ grant_id: 'grantBBBB' })], false)) + await w.get('[data-test="revoke-login-grantAAAA"]').trigger('click') + expect(api.revokeClientLogin).not.toHaveBeenCalled() + expect(w.get('[data-test="revoke-credential-dialog"]').text()).toContain('Cursor IDE') + await w.get('[data-test="revoke-credential-confirm"]').trigger('click') + await flushPromises() + expect(api.revokeClientLogin).toHaveBeenCalledTimes(1) + expect(api.revokeClientLogin).toHaveBeenCalledWith('cursor', 'grantAAAA') + expect(api.revokeClientAPIKey).not.toHaveBeenCalled() + expect(w.emitted('changed')).toHaveLength(1) + }) + + it('cancelling the confirmation revokes nothing', async () => { + const w = mountIt(client([login()], false)) + await w.get('[data-test="revoke-login-grantAAAA"]').trigger('click') + await w.get('[data-test="revoke-credential-cancel"]').trigger('click') + expect(api.revokeClientLogin).not.toHaveBeenCalled() + expect(w.emitted('changed')).toBeUndefined() + }) + + it('revokes the API key alone and says the logins stay', async () => { + const w = mountIt(client([apiKey, login()], false)) + await w.get('[data-test="revoke-api-key"]').trigger('click') + expect(w.get('[data-test="revoke-credential-dialog"]').text()).toMatch(/logins .* stay/i) + await w.get('[data-test="revoke-credential-confirm"]').trigger('click') + await flushPromises() + expect(api.revokeClientAPIKey).toHaveBeenCalledWith('cursor') + expect(api.revokeClientLogin).not.toHaveBeenCalled() + expect(w.emitted('changed')).toHaveLength(1) + }) + + it('offers no revoke for a login or key that is already revoked', () => { + const w = mountIt(client([{ ...apiKey, state: 'revoked' }, login({ state: 'revoked' })], false)) + expect(w.find('[data-test="revoke-api-key"]').exists()).toBe(false) + expect(w.find('[data-test="revoke-login-grantAAAA"]').exists()).toBe(false) + }) + + it('shows a failed revoke and does not report a change', async () => { + ;(api.revokeClientLogin as any).mockRejectedValue(new Error('login not found')) + const w = mountIt(client([login()], false)) + await w.get('[data-test="revoke-login-grantAAAA"]').trigger('click') + await w.get('[data-test="revoke-credential-confirm"]').trigger('click') + await flushPromises() + expect(w.get('[data-test="revoke-credential-error"]').text()).toContain('login not found') + expect(w.emitted('changed')).toBeUndefined() + }) + + it('cannot be cancelled, closed or confirmed twice while a revoke is in flight', async () => { + let settle!: (v: unknown) => void + ;(api.revokeClientLogin as any).mockReturnValue(new Promise(resolve => { settle = resolve })) + const w = mountIt(client([login(), login({ grant_id: 'grantBBBB' })], false)) + await w.get('[data-test="revoke-login-grantAAAA"]').trigger('click') + await w.get('[data-test="revoke-credential-confirm"]').trigger('click') + await flushPromises() + + expect(w.get('[data-test="revoke-credential-cancel"]').attributes('disabled')).toBeDefined() + await w.get('[data-test="revoke-credential-cancel"]').trigger('click') + await w.findComponent({ name: 'BaseDialog' }).vm.$emit('close') // Escape / backdrop + await w.get('[data-test="revoke-credential-confirm"]').trigger('click') + await w.get('[data-test="revoke-login-grantBBBB"]').trigger('click') // cannot swap the target + expect(w.get('[data-test="revoke-credential-dialog"]').text()).toContain('Revoke') + expect(api.revokeClientLogin).toHaveBeenCalledTimes(1) + + settle({ changed: true }) + await flushPromises() + expect(w.emitted('changed')).toHaveLength(1) + expect(api.revokeClientLogin).toHaveBeenCalledTimes(1) + expect(w.get('[data-test="revoke-credential-dialog"]').text()).not.toContain('Revoke') + }) + + it('a stale completion changes nothing in a newer dialog', async () => { + const settles: Array<(v: unknown, fail?: boolean) => void> = [] + ;(api.revokeClientLogin as any).mockImplementation(() => new Promise((resolve, reject) => { settles.push((v, fail) => (fail ? reject(v) : resolve(v))) })) + const w = mountIt(client([login(), login({ grant_id: 'grantBBBB' })], false)) + await w.get('[data-test="revoke-login-grantAAAA"]').trigger('click') + await w.get('[data-test="revoke-credential-confirm"]').trigger('click') + // Force the stale case the UI guards against: drop the dialog state under the call. + ;(w.vm as any).$.setupState.pending = null + ;(w.vm as any).$.setupState.busy = false + await flushPromises() + await w.get('[data-test="revoke-login-grantBBBB"]').trigger('click') + settles[0](new Error('late failure'), true) + await flushPromises() + expect(w.find('[data-test="revoke-credential-error"]').exists()).toBe(false) + expect(w.emitted('changed')).toBeUndefined() + expect(w.get('[data-test="revoke-credential-dialog"]').text()).toContain('Revoke') + }) + + it('renders nothing while browser login is off and was never used (no new fields in the payload)', () => { + const w = mountIt(client(undefined, undefined)) + expect(w.html()).toBe('') + }) +}) diff --git a/frontend/tests/unit/clients-browser-login-off.spec.ts b/frontend/tests/unit/clients-browser-login-off.spec.ts new file mode 100644 index 000000000..5c0096f88 --- /dev/null +++ b/frontend/tests/unit/clients-browser-login-off.spec.ts @@ -0,0 +1,121 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import { readdirSync, readFileSync, statSync } from 'node:fs' +import { join, relative, resolve } from 'node:path' +import { createPinia, setActivePinia } from 'pinia' +import { createMemoryHistory, createRouter } from 'vue-router' +import Clients from '@/views/Clients.vue' +import api from '@/services/api' +import { useSystemStore } from '@/stores/system' +import { setAvailableFeatures } from '@/composables/useScopeQuery' + +// Spec 132 FR-002 / US1: while browser login is off and was never used, nothing +// but the Settings switch mentions it. The core adds no new field to the +// clients payload then, and the Clients page must read exactly as before. + +vi.mock('@/services/api', () => ({ + default: { + hasAPIKey: vi.fn(() => true), + getClients: vi.fn(), + getRouting: vi.fn(), + getClient: vi.fn(), + revokeClientLogin: vi.fn(), + revokeClientAPIKey: vi.fn(), + }, +})) + +const legacy = { id: 'cursor', display_name: 'Cursor', kind: 'supported', state: 'connected_seen', active_sessions: 0, last_seen: null, credential_state: 'client', token_name: 'client-cursor' } +const used = { + ...legacy, + credentials: [ + { kind: 'api_key', prefix: 'mcp_cli_ab12', state: 'active' }, + { kind: 'browser_login', grant_id: 'grantAAAA', state: 'active', approved_at: '2026-11-20T10:00:00Z', reported_name: 'Cursor IDE', redirect_host: '127.0.0.1', name_mismatch: false }, + ], + browser_login_disabled: true, +} + +function makeRouter() { + return createRouter({ + history: createMemoryHistory(), + routes: [ + { path: '/clients', name: 'clients', component: Clients }, + { path: '/activity', name: 'activity', component: { template: '
' } }, + ], + }) +} + +async function mountPage(row: Record) { + ;(api.getClients as any).mockResolvedValue({ success: true, data: { clients: [row] } }) + ;(api.getClient as any).mockResolvedValue({ success: true, data: { ...row, sessions: [] } }) + const router = makeRouter() + await router.push('/clients') + await router.isReady() + const wrapper = mount(Clients, { global: { plugins: [router], stubs: { ClientConnectList: true, AgentTokens: true, ModeSwitcher: true, ClientBindingControls: true, ProfileChip: true } } }) + await flushPromises() + await wrapper.get('[data-test="client-expand-cursor"]').trigger('click') + await flushPromises() + return wrapper +} + +describe('Clients page with browser login off and never used', () => { + beforeEach(() => { + setActivePinia(createPinia()) + vi.clearAllMocks() + setAvailableFeatures([]) + ;(api.getRouting as any).mockResolvedValue({ success: true, data: { endpoints: { default: '/mcp' }, routing_mode: 'retrieve_tools', available_modes: ['retrieve_tools'] } }) + useSystemStore().$patch({ status: { listen_addr: '127.0.0.1:18081' } as any }) + }) + + it('shows no credentials block and no mention of browser login or sign-in', async () => { + const wrapper = await mountPage(legacy) + expect(wrapper.find('[data-test="client-credentials-cursor"]').exists()).toBe(false) + expect(wrapper.text()).not.toMatch(/browser login|sign.?in|login/i) + }) + + it('shows the credentials of a client once the payload carries them, with the disabled label', async () => { + const wrapper = await mountPage(used) + const block = wrapper.get('[data-test="client-credentials-cursor"]') + expect(block.text()).toContain('mcp_cli_ab12') + expect(block.get('[data-test="credential-reported-name"]').text()).toBe('Cursor IDE') + expect(block.get('[data-test="browser-login-disabled"]').exists()).toBe(true) + }) + + it('refreshes the roster after a login is revoked', async () => { + ;(api.revokeClientLogin as any).mockResolvedValue({ changed: true }) + const wrapper = await mountPage(used) + const before = (api.getClients as any).mock.calls.length + await wrapper.get('[data-test="revoke-login-grantAAAA"]').trigger('click') + await wrapper.get('[data-test="revoke-credential-confirm"]').trigger('click') + await flushPromises() + expect(api.revokeClientLogin).toHaveBeenCalledWith('cursor', 'grantAAAA') + expect((api.getClients as any).mock.calls.length).toBeGreaterThan(before) + }) +}) + +// The one place that guards the rule for every other view: a new mention of +// browser login in the web UI sources has to be added here on purpose. +describe('browser login is mentioned only where the spec allows it', () => { + const root = resolve(__dirname, '../../src') + const allowed = new Set([ + 'components/clients/ClientCredentials.vue', // hidden until the payload carries credentials + 'views/AuthorizeRequest.vue', // the consent page + 'views/settings/fields.ts', // the one Settings switch + 'router/index.ts', // the consent route + 'services/api.ts', + 'types/api.ts', + ]) + function walk(dir: string): string[] { + return readdirSync(dir).flatMap(name => { + const full = join(dir, name) + return statSync(full).isDirectory() ? walk(full) : [full] + }) + } + it('has no other view, component or store that names it', () => { + const hits = walk(root) + .filter(file => /\.(vue|ts)$/.test(file)) + .filter(file => /browser login|browser_login|mcp_oauth/i.test(readFileSync(file, 'utf8'))) + .map(file => relative(root, file)) + .filter(file => !allowed.has(file)) + expect(hits).toEqual([]) + }) +}) diff --git a/frontend/tests/unit/settings-browser-login-switch.spec.ts b/frontend/tests/unit/settings-browser-login-switch.spec.ts new file mode 100644 index 000000000..c46121d36 --- /dev/null +++ b/frontend/tests/unit/settings-browser-login-switch.spec.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from 'vitest' +import { mount } from '@vue/test-utils' +import SettingFieldView from '@/components/settings/SettingField.vue' +import { SECURITY_FIELDS, allCatalogFields } from '../../src/views/settings/fields' + +// Spec 132 FR-001: one Settings switch, off by default, marked "Experimental", +// applied without a restart. + +const KEY = 'mcp_oauth_enabled' + +function field() { + return allCatalogFields().find(f => f.key === KEY) +} + +describe('Settings: browser login switch (Spec 132)', () => { + it('is one toggle in Security & Access, marked Experimental, hot, off by default', () => { + const f = field() + expect(f, `${KEY} must be in the catalogue`).toBeDefined() + expect(SECURITY_FIELDS.some(x => x.key === KEY)).toBe(true) + expect(f!.control).toBe('toggle') + expect(f!.badge).toBe('Experimental') + expect(f!.restart).toBeUndefined() + expect(f!.defaultValue ?? false).toBe(false) + }) + + it('renders the badge beside the label', () => { + const wrapper = mount(SettingFieldView, { props: { field: field()!, modelValue: false } }) + const badge = wrapper.get(`[data-test="setting-badge-${KEY}"]`) + expect(badge.text()).toBe('Experimental') + expect(wrapper.find('input[type="checkbox"]').exists()).toBe(true) + }) + + it('renders no badge for a field without one', () => { + const other = SECURITY_FIELDS.find(f => f.key === 'require_mcp_auth')! + const wrapper = mount(SettingFieldView, { props: { field: other, modelValue: false } }) + expect(wrapper.find('[data-test^="setting-badge-"]').exists()).toBe(false) + }) + + it('says what the switch does in plain words and mentions no other surface', () => { + const help = field()!.help ?? '' + expect(help).toMatch(/browser/i) + expect(help).toMatch(/consent|approve/i) + }) +}) diff --git a/internal/httpapi/oauth_login_test.go b/internal/httpapi/oauth_login_test.go index 718dc5648..13341be21 100644 --- a/internal/httpapi/oauth_login_test.go +++ b/internal/httpapi/oauth_login_test.go @@ -109,6 +109,10 @@ func TestOAuthLoginREST_AdministratorOnly(t *testing.T) { {http.MethodPost, "/api/v1/oauth/authorizations/" + id + "/deny", ``}, {http.MethodDelete, "/api/v1/clients/cursor/logins/whatever", ``}, {http.MethodDelete, "/api/v1/clients/cursor/api-key", ``}, + // Spec 132 PR-2b: the credentials list (logins, reported names, redirect + // hosts) is part of these reads. + {http.MethodGet, "/api/v1/clients", ""}, + {http.MethodGet, "/api/v1/clients/cursor", ""}, } { w := h.call(rt.method, rt.path, rt.body, secret) assert.Equal(t, http.StatusForbidden, w.Code, rt.method+" "+rt.path) @@ -441,3 +445,23 @@ func TestOAuthLoginREST_AccessTokenRefusedOnREST(t *testing.T) { assert.Equal(t, http.StatusUnauthorized, status(off, "Authorization", "Bearer "+oat), "off and never used: unchanged") assert.Equal(t, http.StatusUnauthorized, status(off, "X-API-Key", oat)) } + +// Spec 132 PR-2b review: an empty or blank login id never falls through to a +// client-wide revoke or to the forget-client handler. +func TestOAuthLoginREST_EmptyLoginIDRevokesNothing(t *testing.T) { + h := newOAuthHarness(t, true) + h.mint("cursor", "ro") + for _, path := range []string{ + "/api/v1/clients/cursor/logins/", + "/api/v1/clients/cursor/logins//", + "/api/v1/clients/cursor/logins/%20", + "/api/v1/clients/cursor/logins/%09", + } { + w := h.call(http.MethodDelete, path, "", bindingAdminKey) + assert.GreaterOrEqual(t, w.Code, 400, path) + assert.Less(t, w.Code, 500, path) + } + w := h.call(http.MethodGet, "/api/v1/clients", "", bindingAdminKey) + row := findRowByID(t, w, "cursor") + assert.Equal(t, "client", row["credential_state"], "the client's API key is untouched") +} diff --git a/internal/runtime/credentials_service_oauth.go b/internal/runtime/credentials_service_oauth.go index dc380eb0e..ee3fe2f2f 100644 --- a/internal/runtime/credentials_service_oauth.go +++ b/internal/runtime/credentials_service_oauth.go @@ -121,6 +121,28 @@ func (s *CredentialsService) listOAuth(f CredentialFilter, out []CredentialView, return out, nil } +// ClientLogins returns one client's browser logins, newest approval first; +// nil while the feature was never used or the client has none. +func (s *CredentialsService) ClientLogins(clientID string) ([]CredentialView, error) { + if s == nil || s.clients == nil { + return nil, nil + } + st, err := s.clients.loadOAuthState() + if err != nil || !st.active { + return nil, err + } + var bp *storage.OAuthClientBinding + if b, ok := st.bindings[clientID]; ok { + bp = &b + } + gs := st.grants[clientID] + out := make([]CredentialView, 0, len(gs)) + for i := range gs { + out = append(out, s.grantView(&gs[i], st, bp)) + } + 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) { diff --git a/internal/server/mcp_credentials_logins_test.go b/internal/server/mcp_credentials_logins_test.go new file mode 100644 index 000000000..4359a8e27 --- /dev/null +++ b/internal/server/mcp_credentials_logins_test.go @@ -0,0 +1,159 @@ +package server + +import ( + "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/storage" +) + +// Spec 132 PR-2b (T058): the `credentials` tool lists, inspects and revokes +// browser logins, and never creates one. + +func (f *credentialsToolFixture) seedLogin(client, grant, reg string) { + f.t.Helper() + sm := f.rt.StorageManager() + now := time.Now() + require.NoError(f.t, sm.CreateOAuthRegistration(storage.OAuthRegistration{ + ClientID: reg, 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: grant, RegistrationID: reg, 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-" + grant, AccessHash: "ah-" + grant, AccessExpiresAt: now.Add(time.Hour), RefreshExpiresAt: now.Add(24 * time.Hour), + ApprovedAt: now, DisplayPrefix: "mcp_oat_abcd", ObservedClientName: "cursor-vscode", + }, + Client: client, NewClient: true, Pin: "work-readonly", Mode: auth.ProfileModeLocked, + ExpectedBindingRevision: storage.OAuthBindingAbsent, Now: now, + }) + require.NoError(f.t, err) +} + +func loginsFixture(t *testing.T) *credentialsToolFixture { + if !clientsEdition { + t.Skip("browser login is a personal-edition feature") + } + f := newCredentialsToolFixture(t, nil) + f.seedLogin("cursor", "grantAAAAAAAAAAAAAAAAAA", "reg1") + return f +} + +func loginRows(out map[string]any) []map[string]any { + var rows []map[string]any + for _, r := range out["credentials"].([]any) { + if row := r.(map[string]any); row["kind"] == "browser_login" { + rows = append(rows, row) + } + } + return rows +} + +func TestCredentialsTool_ListShowsBrowserLogins(t *testing.T) { + f := loginsFixture(t) + for _, args := range []map[string]any{ + {"operation": "list"}, + {"operation": "list", "kind": "browser_login"}, + } { + logins := loginRows(f.cok(args)) + require.Len(t, logins, 1, "%v", args) + assert.Equal(t, "grantAAAAAAAAAAAAAAAAAA", logins[0]["id"]) + assert.Equal(t, "cursor", logins[0]["client"]) + assert.Equal(t, "active", logins[0]["state"]) + assert.Equal(t, "Cursor IDE", logins[0]["reported_name"]) + assert.Equal(t, "127.0.0.1", logins[0]["redirect_host"]) + } + assert.Empty(t, loginRows(f.cok(map[string]any{"operation": "list", "kind": "client"}))) + // A lapsed filter is accepted. + f.cok(map[string]any{"operation": "list", "state": "lapsed"}) +} + +func TestCredentialsTool_GetClientIncludesLogins(t *testing.T) { + f := loginsFixture(t) + out := f.cok(map[string]any{"operation": "get", "client": "cursor"}) + logins, ok := out["logins"].([]any) + require.True(t, ok, "get client carries its logins: %v", out) + require.Len(t, logins, 1) + assert.Equal(t, "grantAAAAAAAAAAAAAAAAAA", logins[0].(map[string]any)["id"]) +} + +func TestCredentialsTool_RevokeOneLogin(t *testing.T) { + f := loginsFixture(t) + f.seedLogin("windsurf", "grantBBBBBBBBBBBBBBBBBB", "reg2") + out := f.cok(map[string]any{"operation": "revoke", "client": "cursor", "grant": "grantAAAAAAAAAAAAAAAAAA"}) + assert.Equal(t, true, out["changed"]) + cred := out["credential"].(map[string]any) + assert.Equal(t, "browser_login", cred["kind"]) + assert.Equal(t, "revoked", cred["state"]) + + states := map[string]string{} + for _, row := range loginRows(f.cok(map[string]any{"operation": "list", "kind": "browser_login"})) { + states[row["id"].(string)] = row["state"].(string) + } + assert.Equal(t, map[string]string{"grantAAAAAAAAAAAAAAAAAA": "revoked", "grantBBBBBBBBBBBBBBBBBB": "active"}, states) + + // Revoking it again is not an error and changes nothing. + again := f.cok(map[string]any{"operation": "revoke", "client": "cursor", "grant": "grantAAAAAAAAAAAAAAAAAA"}) + assert.Equal(t, false, again["changed"]) +} + +func TestCredentialsTool_RevokeLoginRefusals(t *testing.T) { + f := loginsFixture(t) + out := f.crefused(map[string]any{"operation": "revoke", "client": "cursor", "grant": "nope"}) + assert.Equal(t, "identity_not_found", out["code"]) + assert.Equal(t, "grant", out["field"]) + + // A grant of another client is not found under this one. + out = f.crefused(map[string]any{"operation": "revoke", "client": "other", "grant": "grantAAAAAAAAAAAAAAAAAA"}) + assert.Equal(t, "identity_not_found", out["code"]) + + // A grant needs a client; get and the create operations do not take one. + out = f.crefused(map[string]any{"operation": "revoke", "token": "t1", "grant": "g"}) + assert.Equal(t, "invalid_argument", out["code"]) + out = f.crefused(map[string]any{"operation": "get", "client": "cursor", "grant": "g"}) + assert.Equal(t, "invalid_argument", out["code"]) + out = f.crefused(map[string]any{"operation": "create_client", "client": "x", "grant": "g"}) + assert.Equal(t, "invalid_argument", out["code"]) + + // The login is untouched by every refusal. + rows := loginRows(f.cok(map[string]any{"operation": "list", "kind": "browser_login"})) + require.Len(t, rows, 1) + assert.Equal(t, "active", rows[0]["state"]) +} + +// An empty or blank grant is a refusal, never the client-wide revoke that +// omitting grant means. +func TestCredentialsTool_BlankGrantIsRefusedNotClientWide(t *testing.T) { + f := loginsFixture(t) + for _, blank := range []string{"", " ", "\t", " \n"} { + out := f.crefused(map[string]any{"operation": "revoke", "client": "cursor", "grant": blank}) + assert.Equal(t, "invalid_argument", out["code"], "%q", blank) + assert.Equal(t, "grant", out["field"], "%q", blank) + } + rows := loginRows(f.cok(map[string]any{"operation": "list", "kind": "browser_login"})) + require.Len(t, rows, 1) + assert.Equal(t, "active", rows[0]["state"], "nothing was revoked") +} + +func TestCredentialsTool_NoOperationCreatesALogin(t *testing.T) { + for _, op := range credentialsOperations { + assert.NotContains(t, op, "login") + } + assert.False(t, credentialsOpArgs["create_client"]["grant"]) + assert.False(t, credentialsOpArgs["create_token"]["grant"]) +} + +func TestCredentialsTool_LoginRevokeHonoursWriteGates(t *testing.T) { + f := loginsFixture(t) + f.proxy.currentConfig().ReadOnlyMode = true + out := f.crefused(map[string]any{"operation": "revoke", "client": "cursor", "grant": "grantAAAAAAAAAAAAAAAAAA"}) + assert.Equal(t, "read_only_mode", out["code"]) + rows := loginRows(f.cok(map[string]any{"operation": "list", "kind": "browser_login"})) + require.Len(t, rows, 1) + assert.Equal(t, "active", rows[0]["state"]) +} diff --git a/internal/server/mcp_credentials_tool.go b/internal/server/mcp_credentials_tool.go index b12dfda0e..730587e73 100644 --- a/internal/server/mcp_credentials_tool.go +++ b/internal/server/mcp_credentials_tool.go @@ -355,11 +355,11 @@ func (p *MCPProxyServer) runCredentialsOperation(ctx context.Context, args map[s kind, _ := str("kind") prof, _ := str("profile") state, _ := str("state") - if kind != "" && kind != "client" && kind != "token" && kind != "all" { - return recorded, nil, nil, &credentialsToolError{profile.CredentialErrorCodeInvalidArgument, `invalid argument "kind": must be client, token or all`, "kind"} + if kind != "" && kind != "client" && kind != "token" && kind != "browser_login" && kind != "all" { + return recorded, nil, nil, &credentialsToolError{profile.CredentialErrorCodeInvalidArgument, `invalid argument "kind": must be client, token, browser_login or all`, "kind"} } - if state != "" && state != "active" && state != "expired" && state != "revoked" && state != "all" { - return recorded, nil, nil, &credentialsToolError{profile.CredentialErrorCodeInvalidArgument, `invalid argument "state": must be active, expired, revoked or all`, "state"} + if state != "" && state != "active" && state != "expired" && state != "lapsed" && state != "revoked" && state != "all" { + return recorded, nil, nil, &credentialsToolError{profile.CredentialErrorCodeInvalidArgument, `invalid argument "state": must be active, expired, lapsed, revoked or all`, "state"} } rows, err := cs.List(runtime.CredentialFilter{Kind: kind, Profile: prof, State: state, ExcludeClients: !clientsSupported}) if err != nil { @@ -375,13 +375,32 @@ func (p *MCPProxyServer) runCredentialsOperation(ctx context.Context, args map[s if client != "" && !clientsSupported { return recorded, nil, nil, unsupported } - ref := runtime.CredentialRef{Client: client, Token: token, EnforceWriteGates: op == "revoke"} + grant, hasGrant := str("grant") + if hasGrant && strings.TrimSpace(grant) == "" { + // A supplied blank grant is never the client-wide revoke that omitting it means. + return recorded, nil, nil, &credentialsToolError{profile.CredentialErrorCodeInvalidArgument, `invalid argument "grant": must not be empty`, "grant"} + } + if grant != "" && client == "" { + return recorded, nil, nil, &credentialsToolError{profile.CredentialErrorCodeInvalidArgument, "revoke: grant requires client", "grant"} + } + ref := runtime.CredentialRef{Client: client, Token: token, Grant: grant, EnforceWriteGates: op == "revoke"} if op == "get" { v, err := cs.Get(ref) if err != nil { return recorded, nil, nil, err } - return recorded, map[string]any{"credential": v, "links": delivery.CredentialUILinks(client, token, v.Profile)}, nil, nil + out := map[string]any{"credential": v, "links": delivery.CredentialUILinks(client, token, v.Profile)} + if client != "" { + // Spec 132: the client's browser logins ride along; none = no key. + logins, lerr := cs.ClientLogins(client) + if lerr != nil { + return recorded, nil, nil, lerr + } + if len(logins) > 0 { + out["logins"] = logins + } + } + return recorded, out, nil, nil } res, err := cs.Revoke(ctx, actor, ref, false) if err != nil { diff --git a/internal/server/mcp_credentials_tool_schema.go b/internal/server/mcp_credentials_tool_schema.go index b7b645cda..ecd416175 100644 --- a/internal/server/mcp_credentials_tool_schema.go +++ b/internal/server/mcp_credentials_tool_schema.go @@ -25,14 +25,15 @@ var credentialsArgs = []struct { }{ {name: "client", desc: "create_client, get, revoke: custom client id (lower-case letters, digits, '-' or '_', at most 56 characters)."}, {name: "token", desc: "get, revoke: agent token name."}, + {name: "grant", desc: "revoke: with client, revoke only this browser login (a login id from list or get). A login is created only by the user on the consent page."}, {name: "name", desc: "create_token: new token name (letters, digits, '_' or '-'; not starting with client-)."}, {name: "display_name", desc: "create_client: display name, at most 64 characters."}, {name: "profile", desc: "create_client, create_token: existing profile to lock or pin to (required, never All servers). list: keep only this profile."}, {name: "mode", enum: []string{"locked", "switchable"}, desc: "create_client: binding mode; omitted = locked."}, {name: "expires_in", desc: "create_client, create_token: required lifetime such as 30m, 4h or 7d; at most 365d. At most 24h is shown as a task lease."}, {name: "purpose", desc: "create_client, create_token: optional task brief and assumptions shown to the user, at most 500 characters; not enforced."}, - {name: "kind", enum: []string{"client", "token", "all"}, desc: "list: credential kind; omitted = all."}, - {name: "state", enum: []string{"active", "expired", "revoked", "all"}, desc: "list: credential state; omitted = all."}, + {name: "kind", enum: []string{"client", "token", "browser_login", "all"}, desc: "list: credential kind; omitted = all."}, + {name: "state", enum: []string{"active", "expired", "lapsed", "revoked", "all"}, desc: "list: credential state (lapsed = browser login past its refresh expiry); omitted = all."}, } // credentialsOpArgs lists the arguments each operation accepts (besides @@ -40,7 +41,7 @@ var credentialsArgs = []struct { var credentialsOpArgs = map[string]map[string]bool{ "list": {"kind": true, "profile": true, "state": true}, "get": {"client": true, "token": true}, - "revoke": {"client": true, "token": true}, + "revoke": {"client": true, "token": true, "grant": true}, "create_client": {"client": true, "profile": true, "expires_in": true, "mode": true, "display_name": true, "purpose": true}, "create_token": {"name": true, "profile": true, "expires_in": true, "purpose": true}, } diff --git a/internal/server/mcp_credentials_tool_test.go b/internal/server/mcp_credentials_tool_test.go index 49ac11f04..62982f7ad 100644 --- a/internal/server/mcp_credentials_tool_test.go +++ b/internal/server/mcp_credentials_tool_test.go @@ -111,7 +111,7 @@ func (f *credentialsToolFixture) internalCalls(n int) []*storage.ActivityRecord func TestCredentialsTool_SchemaAndAnnotations(t *testing.T) { tool := buildCredentialsTool() - want := []string{"client", "display_name", "expires_in", "kind", "mode", "name", "operation", "profile", "purpose", "state", "token"} + want := []string{"client", "display_name", "expires_in", "grant", "kind", "mode", "name", "operation", "profile", "purpose", "state", "token"} assert.Equal(t, want, toolPropertyNames(t, tool)) assert.Equal(t, []string{"operation"}, tool.InputSchema.Required) assert.Equal(t, false, tool.InputSchema.AdditionalProperties) diff --git a/internal/server/testdata/toolslist_goldens/code_execution_mode.json b/internal/server/testdata/toolslist_goldens/code_execution_mode.json index 5f12bdffc..e9f492138 100644 --- a/internal/server/testdata/toolslist_goldens/code_execution_mode.json +++ b/internal/server/testdata/toolslist_goldens/code_execution_mode.json @@ -66,11 +66,16 @@ "description": "create_client, create_token: required lifetime such as 30m, 4h or 7d; at most 365d. At most 24h is shown as a task lease.", "type": "string" }, + "grant": { + "description": "revoke: with client, revoke only this browser login (a login id from list or get). A login is created only by the user on the consent page.", + "type": "string" + }, "kind": { "description": "list: credential kind; omitted = all.", "enum": [ "client", "token", + "browser_login", "all" ], "type": "string" @@ -107,10 +112,11 @@ "type": "string" }, "state": { - "description": "list: credential state; omitted = all.", + "description": "list: credential state (lapsed = browser login past its refresh expiry); omitted = all.", "enum": [ "active", "expired", + "lapsed", "revoked", "all" ], diff --git a/internal/server/testdata/toolslist_goldens/default_server.json b/internal/server/testdata/toolslist_goldens/default_server.json index 163e1b9d6..fb786f11c 100644 --- a/internal/server/testdata/toolslist_goldens/default_server.json +++ b/internal/server/testdata/toolslist_goldens/default_server.json @@ -186,11 +186,16 @@ "description": "create_client, create_token: required lifetime such as 30m, 4h or 7d; at most 365d. At most 24h is shown as a task lease.", "type": "string" }, + "grant": { + "description": "revoke: with client, revoke only this browser login (a login id from list or get). A login is created only by the user on the consent page.", + "type": "string" + }, "kind": { "description": "list: credential kind; omitted = all.", "enum": [ "client", "token", + "browser_login", "all" ], "type": "string" @@ -227,10 +232,11 @@ "type": "string" }, "state": { - "description": "list: credential state; omitted = all.", + "description": "list: credential state (lapsed = browser login past its refresh expiry); omitted = all.", "enum": [ "active", "expired", + "lapsed", "revoked", "all" ], diff --git a/internal/server/testdata/toolslist_goldens/default_server_read_only.json b/internal/server/testdata/toolslist_goldens/default_server_read_only.json index 870b4ac3c..a29a4599a 100644 --- a/internal/server/testdata/toolslist_goldens/default_server_read_only.json +++ b/internal/server/testdata/toolslist_goldens/default_server_read_only.json @@ -186,11 +186,16 @@ "description": "create_client, create_token: required lifetime such as 30m, 4h or 7d; at most 365d. At most 24h is shown as a task lease.", "type": "string" }, + "grant": { + "description": "revoke: with client, revoke only this browser login (a login id from list or get). A login is created only by the user on the consent page.", + "type": "string" + }, "kind": { "description": "list: credential kind; omitted = all.", "enum": [ "client", "token", + "browser_login", "all" ], "type": "string" @@ -227,10 +232,11 @@ "type": "string" }, "state": { - "description": "list: credential state; omitted = all.", + "description": "list: credential state (lapsed = browser login past its refresh expiry); omitted = all.", "enum": [ "active", "expired", + "lapsed", "revoked", "all" ], diff --git a/internal/server/testdata/toolslist_goldens/retrieve_tools_mode.json b/internal/server/testdata/toolslist_goldens/retrieve_tools_mode.json index 98f62903b..ca2ed7391 100644 --- a/internal/server/testdata/toolslist_goldens/retrieve_tools_mode.json +++ b/internal/server/testdata/toolslist_goldens/retrieve_tools_mode.json @@ -186,11 +186,16 @@ "description": "create_client, create_token: required lifetime such as 30m, 4h or 7d; at most 365d. At most 24h is shown as a task lease.", "type": "string" }, + "grant": { + "description": "revoke: with client, revoke only this browser login (a login id from list or get). A login is created only by the user on the consent page.", + "type": "string" + }, "kind": { "description": "list: credential kind; omitted = all.", "enum": [ "client", "token", + "browser_login", "all" ], "type": "string" @@ -227,10 +232,11 @@ "type": "string" }, "state": { - "description": "list: credential state; omitted = all.", + "description": "list: credential state (lapsed = browser login past its refresh expiry); omitted = all.", "enum": [ "active", "expired", + "lapsed", "revoked", "all" ], diff --git a/native/macos/MCPProxy/MCPProxy/Settings/ConfigSettingsView.swift b/native/macos/MCPProxy/MCPProxy/Settings/ConfigSettingsView.swift index 7ff9dbfd6..4561e1df8 100644 --- a/native/macos/MCPProxy/MCPProxy/Settings/ConfigSettingsView.swift +++ b/native/macos/MCPProxy/MCPProxy/Settings/ConfigSettingsView.swift @@ -539,6 +539,11 @@ struct ConfigFieldRow: View { HStack(spacing: 6) { Text(field.label).fontWeight(.medium) if dirty { Circle().fill(Color.orange).frame(width: 6, height: 6) } + if let badge = field.badge { + Text(badge).font(.caption2).padding(.horizontal, 5).padding(.vertical, 1) + .overlay(RoundedRectangle(cornerRadius: 4).stroke(Color.secondary.opacity(0.5))) + .accessibilityIdentifier("setting-badge-\(field.key)") + } if field.restart { Text("restart").font(.caption2).padding(.horizontal, 5).padding(.vertical, 1) .background(Color.orange.opacity(0.25)).cornerRadius(4) diff --git a/native/macos/MCPProxy/MCPProxy/Settings/SettingsCatalog.swift b/native/macos/MCPProxy/MCPProxy/Settings/SettingsCatalog.swift index f5d066890..bfce66c00 100644 --- a/native/macos/MCPProxy/MCPProxy/Settings/SettingsCatalog.swift +++ b/native/macos/MCPProxy/MCPProxy/Settings/SettingsCatalog.swift @@ -31,6 +31,7 @@ struct ConfigField: Identifiable { // never nudged (F13). var step: Double? = nil var restart: Bool = false + var badge: String? = nil // short label beside the name, e.g. "Experimental" var docs: String? = nil // doc path on docs.mcpproxy.app var valueKind: ConfigValueKind? = nil var optional: Bool = false @@ -88,6 +89,13 @@ enum SettingsCatalog { help: "When on, AI clients connecting to the /mcp endpoint must send the API key above (as an \"Authorization: Bearer \" header). Use \u{201C}Connect a client\u{201D} to configure this automatically. When off, any local client can connect without a key.", control: .toggle ), + ConfigField( + key: "mcp_oauth_enabled", + label: "Browser login for MCP clients", + help: "Lets an MCP client that supports it sign in through your browser: you approve each request on a consent page in this UI, and the approval can be revoked later. Off by default; turning it on or off needs no restart, and existing logins stay listed either way.", + control: .toggle, + badge: "Experimental" + ), ConfigField( key: "quarantine_enabled", label: "Quarantine new servers & changed tools",