From 3caad54c267fa8c2c027c869a8d21a1ddc7e1b9f Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sun, 22 Nov 2026 15:56:57 +0200 Subject: [PATCH 01/15] docs(spec): design for OAuth login of MCP clients (#1971) --- specs/131-client-oauth-login/design.md | 199 +++++++++++++++++++++++++ 1 file changed, 199 insertions(+) create mode 100644 specs/131-client-oauth-login/design.md diff --git a/specs/131-client-oauth-login/design.md b/specs/131-client-oauth-login/design.md new file mode 100644 index 000000000..b7a464817 --- /dev/null +++ b/specs/131-client-oauth-login/design.md @@ -0,0 +1,199 @@ +# Design: OAuth login for MCP clients, next to API keys + +**Issue**: [#1971](https://github.com/smart-mcp-proxy/mcpproxy-go/issues/1971) · **Date**: 2026-11-22 · **Status**: Draft for approval +**Scope**: personal edition. Server edition and the tunnel (Spec 089) reuse the same parts later. + +## Intent + +Today every MCP client needs a credential pasted into its config file. The user wants a second way in: the client is given only a URL, opens the browser, the user approves, and the client is connected. Both ways stay available and the user chooses per client. + +The open question this design answers: **after an OAuth login, how does MCPProxy know which client this is and what it may reach?** + +Answer: MCPProxy suggests, the user confirms. The client's self-reported name only pre-fills the consent page. The identity is the approved registration. Access comes from the profile bound to the client, the same binding API-key clients use. + +## Goals + +- A client configured with `http://127.0.0.1:8080/mcp/oauth` and nothing else can log in through the MCP authorization flow (RFC 9728 discovery, RFC 8414 metadata, RFC 7591 registration, authorization code + PKCE S256, refresh). +- One click on the consent page in the common case. +- An OAuth client is an ordinary row in the Clients hub: same profile binding, same activity attribution, same reassign and revoke. +- A client may hold an API key, OAuth logins, or both. +- Connect offers the choice "API key" or "Sign in with browser" for clients that support OAuth. + +## Non-goals + +- Replacing API keys or agent tokens. Headless clients keep them. +- OAuth on `/mcp`, `/mcp/all`, `/mcp/code`, `/mcp/call`, `/mcp/p/`, `/mcp/s/`. Version 1 serves one OAuth endpoint, `/mcp/oauth`. `/mcp` behaves exactly as today. +- Confidential clients (client secrets), Client ID Metadata Documents, token introspection endpoints. +- Server edition behaviour and the tunnel. The data model leaves room for both (see "Later"). +- Approving a login from the CLI. + +## Anti-goals + +- A client gets access because of the name it reports. Never. +- A login that silently lands on "All servers" while profiles exist. +- A second, parallel notion of "client" with its own profile rules. +- An OAuth client bound to a profile that it can escape by using `/mcp` without a credential. + +## Constraints from the existing code + +- A client credential is an `auth.AgentToken` with `Kind=client`, `ClientID`, `ProfilePin`, `ProfileMode` (`internal/auth/agent_token.go`). The binding lives on that record today. +- The connect registry (`internal/connect/clients.go`) knows each supported client's id and the names it reports (`ClientInfoNames`). +- Client names from the wire are untrusted; `internal/clientidentity` already makes them safe to store and show. +- The personal Web UI has no login. It holds the admin API key in `localStorage` after being opened with `?apikey=` (the tray does this). The `mcpproxy_session` cookie is server edition only. +- With `require_mcp_auth` off, a client bound to a named profile could drop its credential and use `/mcp` unconfined. Every binding change that would allow this is refused with `409 binding_bypassable_without_auth`. +- The `credentials` tool and REST `/clients`, `/tokens` share one issue/revoke path, `runtime.CredentialsService`. +- No new dependencies. + +## Approaches considered + +1. **Automatic by name.** Match `client_name` to the connect registry and assign that client's profile with no question. Rejected: the name is self-asserted, so any local process can call itself "Cursor" and inherit Cursor's access. +2. **User selects everything every time.** Safe. Rejected as the default: tedious, and clients that register again pile up as "Cursor (2)", "Cursor (3)". +3. **Suggest and confirm (chosen).** The server computes a suggestion (which client, which profile, whether this replaces an earlier login). The consent page shows it pre-filled. The user approves with one click or changes it. Chosen by Algis on 2026-11-22. + +## How it works + +### Flow + +1. The client calls `/mcp/oauth` without a token. Answer: `401` with `WWW-Authenticate: Bearer resource_metadata="…"`. +2. The client reads `/.well-known/oauth-protected-resource/mcp/oauth` and `/.well-known/oauth-authorization-server`, then registers at `POST /oauth/register`. +3. The client opens the browser at `GET /oauth/authorize`. The server validates the request (known `client_id`, exact redirect URI match, `code_challenge_method=S256`, `resource` equal to the `/mcp/oauth` URL), stores an **authorization request** (10 minute life) and redirects the browser to `/ui/authorize?request=`. +4. The Web UI consent page loads the request and its suggestion through the REST API, with the admin API key. +5. Approve: the page posts the decision; the answer carries the redirect URL with a single-use code. The page sends the browser there. Deny: redirect with `error=access_denied`. +6. The client exchanges the code at `POST /oauth/token` with its PKCE verifier and gets an access token and a refresh token. + +### The consent page + +``` +"Cursor" wants to connect to MCPProxy +Name reported by the app. MCPProxy cannot verify it. +Returns to: http://127.0.0.1:54321/callback + +Client (•) Cursor (already connected with an API key) + ( ) New client [ Cursor 2 ] +Profile [ dev-readonly ▾ ] locked + Approving gives this app the same access as Cursor. +[x] Replace the previous browser login of Cursor (approved 3 Nov) + + [ Deny ] [ Approve ] +``` + +Rules for the page: + +- The reported name is always labelled as unverified. When an existing client is selected, the page says in words that the app receives that client's access. +- **No admin key in this browser**: the page cannot load the request. It shows "Open this request from the MCPProxy tray, or paste the API key". The core emits an SSE event for a new authorization request; the tray shows a notification and a menu item "Approve sign-in for Cursor…" that opens the same URL with the key, the way it opens the Web UI today. +- **Bypassable binding**: when the chosen profile is a named one and `require_mcp_auth` is off, approval would be refused with `binding_bypassable_without_auth`. The page shows that refusal before the button is pressed, with the fixes the binding guard itself lists (`internal/runtime/binding_guard.go`: turn `require_mcp_auth` on, or set `anonymous_profile`). No exception for OAuth clients. +- The page is never framed (`frame-ancestors 'none'`). Approval is an API-key-authenticated REST call, not a cookie form, so there is no cross-site request to forge. + +### The suggestion + +Computed on the server, returned with the authorization request. First match wins: + +| # | Evidence | Client | Profile | Extra | +|---|---|---|---|---| +| 1 | This `client_id` already has an approved grant | the grant's client | the client's binding | "Signed in before" | +| 2 | An approved grant exists whose registration had the same reported name (normalised) and the same redirect URI set | that grant's client | its binding | "replace previous login" pre-checked | +| 3 | Reported name matches the registry (below), and a Clients row with that id exists | that row | its binding | | +| 4 | Reported name matches the registry, no row yet | new client with the registry id | see below | registry icon and display name | +| 5 | Nothing matches | new custom client, id is a slug of the name, made unique | see below | | + +Registry match: the name a client registers with is not the name it sends at `initialize`, so `ClientInfoNames` alone would rarely match. The registry gains `OAuthClientNames` per client (PR-1, filled from observed registrations and public documentation, best effort like `ClientInfoNames`). A reported name matches a registry client when, after normalisation and case folding, it equals the client's id, display name, a `ClientInfoNames` alias or an `OAuthClientNames` entry. Row 2 is what stops the pile-up for clients the registry does not know: the first approval teaches MCPProxy which client that name and redirect set belong to. + +Profile for a new client: if no profiles are configured, "All servers". If profiles exist, nothing is pre-selected and Approve stays disabled until the user picks one. This is the same rule as `profile_required` in the `credentials` tool. Binding mode defaults to `locked`. + +Consent is shown every time, including row 1. A public client has no secret and loopback redirects match on any port, so a different local process can reuse a known `client_id`. The click is the check. + +### Identity and data + +Three new records, in their own bbolt buckets. They are keyed by client, not by upstream server, so the Spec 116 server purge set does not apply; their cleanup is described under "Revoke and forget". + +- **Registration** (`oauth_registrations`): opaque random `client_id`, reported name (sanitised with `clientidentity`), redirect URIs, optional `software_id` / `software_version`, created time, state `pending | approved | denied`. +- **Grant** (`oauth_grants`): one approved login. Fields: id, `client_id` of the registration, **Clients hub client id**, approved time, approving actor, last used, revoked flag, `user_id` (empty in the personal edition). Holds the hash and 12-character prefix of the current refresh token and the token family id. +- **Authorization request / code**: short-lived, memory only. A restart drops them and the client starts again. + +Tokens: + +- Access token: opaque, prefix `mcp_oat_`, HMAC-SHA256 hashed like agent tokens, 1 hour, accepted only on `/mcp/oauth`. +- Refresh token: opaque, prefix `mcp_ort_`, rotated on every use, 30 days sliding. Reuse of an already rotated refresh token revokes the grant (OAuth 2.1 rule for public clients). + +**One client, several credentials.** A Clients hub row is the identity. Under it: at most one API key (today's `mcp_cli_` record) and any number of OAuth grants. The profile binding belongs to the client, not to a credential. An access token authenticates to the same `AuthContext` a client credential produces: `AuthTypeAgent`-class caller, `Kind=client`, the client's id, the client's binding. Everything downstream (profile resolution, pin boundary, activity `client_id`, `/tools?client=`) is unchanged. + +The invariant for the builder: **one binding per client id, read by both the API-key path and the OAuth path, changed by one writer** (`ClientsService`, which already owns `SetBinding`, `BulkAssign`, `Add` and `Forget`). Today the binding is stored on the API-key record. How to hold it for a client that has only OAuth grants is the builder's call (a credential-less client record, or a small `client_bindings` bucket that both paths read). Reassign, rename, delete-profile (`profile_in_use`, `reassign_to`, dangling means deny-all) and the bypassable-binding check must cover OAuth-only clients exactly as they cover API-key clients. + +Activity rows gain the credential kind `oauth` and the grant id, so two logins of one client can be told apart. Issue, approve, deny, refresh-reuse and revoke are recorded as `profile_change`-family rows through `CredentialsService`, with the actor in context. + +### Canonical address and where OAuth is served + +- The resource and the issuer are built from the **origin of the request**, after the existing host validation (loopback names and `trusted_hosts`). `http://127.0.0.1:8080` and `http://localhost:8080` are two resources; a client stays on the one it was configured with. The metadata documents, the `resource` check at authorize and the audience of a token all use that origin, and a token is refused on any other. +- The consent redirect stays on the same origin. If the browser holds the admin key under another origin, the page takes the "no admin key" path and the tray opens the request on the right origin. +- Version 1 serves `/mcp/oauth`, `/oauth/*` and the metadata only to requests that arrive from a loopback address with a loopback host. Anything else gets 404, so a LAN listen exposes no open registration. The tunnel lifts this later under its own rules. +- `/mcp/oauth` serves the same tool surface as `/mcp` (it follows `routing_mode`). It is registered ahead of the `/mcp/` catch-all. Behaviour change to note in the docs: today `/mcp/oauth` falls into that catch-all and answers like `/mcp`. +- Server edition: the feature answers 404 in version 1 whatever the setting, because consent by admin API key would create grants with no user. + +### Revoke and forget + +- **Revoke a client** (`credentials revoke client=`, REST, CLI): revokes everything under it, the API key and every grant. This keeps today's meaning, "this client loses access". +- **Revoke one credential**: new, for a single grant (by grant id) or for the API key alone. Other credentials of the client keep working. +- **Forget a client** (`DELETE /clients/{client}`, `ClientsService.Forget`): deletes its grants in the same transaction, and each registration left without a grant. +- **Active binding**: the binding guard and `profile_in_use` treat a client's binding as active while it has an API key that is neither revoked nor expired, or at least one grant that is neither revoked nor lapsed. A grant lapses when its refresh token expires (30 days without use). + +### Clients hub + +``` +Cursor profile: dev-readonly (locked) + API key mcp_cli_ab12… last used 2 h ago [Rotate] [Revoke] + Browser login approved 22 Nov last used 5 min ago [Revoke] + Browser login approved 3 Nov revoked +``` + +- Revoking one login stops its access token on the next request and its refresh token at once. Revoking the client revokes everything under it. +- If the name a client sends at `initialize` does not match the name it registered with or the selected client's known names, the row shows an advisory warning. Nothing is blocked. +- `credentials list|get|revoke` (MCP), REST `/clients` and `mcpproxy client …` show and revoke grants. They never issue one: a grant exists only through the consent page. + +### Connect + +The registry gains a flag for clients known to support the MCP authorization flow. For those, Connect (Web UI, CLI `mcpproxy connect --auth oauth|key`) offers both. "Sign in with browser" writes only the `/mcp/oauth` URL into the client's config, no header. The diff preview and backup notice are unchanged. Default stays "API key" in version 1. + +### Limits and abuse + +- `POST /oauth/register`: body at most 16 KiB; rate limited per remote address; at most 50 pending registrations, oldest dropped. A registration never authorised is deleted after 15 minutes; one authorised but never approved, after 24 hours. +- Redirect URIs: `http` on `127.0.0.1`, `[::1]` or `localhost` (any port at authorize time, per RFC 8252), or `https`. Exact match otherwise. Custom schemes are refused in version 1. +- `/oauth/authorize` and `/oauth/token`: rate limited; codes are single-use, 60 seconds, bound to client, redirect URI and PKCE challenge. +- All `/oauth/*` and `/.well-known/*` endpoints are unauthenticated by nature and answer nothing about servers, profiles or existing clients. + +### Configuration + +`mcp_oauth_enabled` (default **on**, env `MCPPROXY_MCP_OAUTH_ENABLED`). Off: `/mcp/oauth`, `/oauth/*` and the metadata documents answer 404 and existing grants stop authenticating until it is on again. + +## Delivery + +1. **PR-1, backend**: metadata, registration, authorize, token, storage, `/mcp/oauth` handler, authentication into the existing client `AuthContext`, the single binding, REST for authorization requests (get with suggestion, approve, deny), activity rows, limits. +2. **PR-2, surfaces**: consent page, macOS tray notification, Clients hub credentials list, `credentials` / REST / CLI list and revoke. **PR-2b**: the same notification in the Go tray (Windows, Linux); until then those users paste the key or open the Web UI from the tray first. +3. **PR-3, Connect and docs**: registry flag, the Connect choice, `docs/features/client-oauth-login.md`, updates to connect-clients, profiles, REST reference. + +Each PR is test-first. End to end: a scripted public client runs the whole flow against a built core (`scripts/test-client-oauth-e2e.sh`), including refresh rotation, reuse detection, revoke on a live session and the bypassable-binding refusal. + +## Calls made here (not decided by Algis) + +- One OAuth endpoint, `/mcp/oauth`, as the issue proposes; tokens are bound to it. +- Feature on by default. +- Consent every time, with no silent re-approval. +- Token lifetimes (1 hour / 30 days sliding) and the numeric limits above. +- Default Connect choice stays "API key". +- No CLI approval, no custom-scheme redirects, no confidential clients in version 1. +- Registry gains `OAuthClientNames`; suggestion row 2 learns from earlier approvals. +- Resource and issuer follow the request origin; OAuth is loopback-only and off in server edition for version 1. +- "Revoke client" revokes the API key and all grants; forgetting a client deletes its grants. +- `/mcp/oauth` follows `routing_mode`; Go tray notification is a follow-up PR. +- Document location: `specs/131-client-oauth-login/design.md`, to become the input of `speckit.specify`. + +## Left to the builder + +- Where the per-client binding is stored (see the invariant). +- Bucket layouts, the exact REST paths and payloads, SSE event name. +- Whether access tokens are separate rows or derived from the grant record. +- Rate-limit implementation, reusing the existing limiter where it fits. + +## Later + +- **Server edition**: the consent page needs the user's session; the grant carries `user_id`; selectable profiles and clients are the user's own. +- **Tunnel (Spec 089)**: same endpoints behind the tunnel origin, consent protected by the proxy-managed credential, tokens bound to the tunnel resource URI. Client ID Metadata Documents would give hosted clients a domain-verified name and can strengthen suggestion row 2. From 51cbfefee28567c4b74b01c5f6c84a375fdae022 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sun, 22 Nov 2026 16:11:46 +0200 Subject: [PATCH 02/15] docs(spec): client OAuth login is opt-in; client fixed by its address (#1971) --- specs/131-client-oauth-login/design.md | 111 +++++++++++++++---------- 1 file changed, 67 insertions(+), 44 deletions(-) diff --git a/specs/131-client-oauth-login/design.md b/specs/131-client-oauth-login/design.md index b7a464817..8aa1866a3 100644 --- a/specs/131-client-oauth-login/design.md +++ b/specs/131-client-oauth-login/design.md @@ -9,11 +9,14 @@ Today every MCP client needs a credential pasted into its config file. The user The open question this design answers: **after an OAuth login, how does MCPProxy know which client this is and what it may reach?** -Answer: MCPProxy suggests, the user confirms. The client's self-reported name only pre-fills the consent page. The identity is the approved registration. Access comes from the profile bound to the client, the same binding API-key clients use. +Answer: the **address** the client was given says which client it is, and the user confirms on the consent page. Connect writes a per-client address (`/mcp/oauth/cursor`), so nothing is guessed from the name the client reports. That name is shown, labelled unverified, and is never used to pick a client. Access comes from the profile bound to the client, the same binding API-key clients use. + +The feature is **off by default** in its first release. With it off, nothing changes for anyone who updates. ## Goals -- A client configured with `http://127.0.0.1:8080/mcp/oauth` and nothing else can log in through the MCP authorization flow (RFC 9728 discovery, RFC 8414 metadata, RFC 7591 registration, authorization code + PKCE S256, refresh). +- With `mcp_oauth_enabled` off (the default), an updated MCPProxy behaves byte for byte as before on every existing path, and asks the user for nothing. +- A client configured with `http://127.0.0.1:8080/mcp/oauth/` (or the generic `/mcp/oauth`) and nothing else can log in through the MCP authorization flow (RFC 9728 discovery, RFC 8414 metadata, RFC 7591 registration, authorization code + PKCE S256, refresh). - One click on the consent page in the common case. - An OAuth client is an ordinary row in the Clients hub: same profile binding, same activity attribution, same reassign and revoke. - A client may hold an API key, OAuth logins, or both. @@ -22,14 +25,16 @@ Answer: MCPProxy suggests, the user confirms. The client's self-reported name on ## Non-goals - Replacing API keys or agent tokens. Headless clients keep them. -- OAuth on `/mcp`, `/mcp/all`, `/mcp/code`, `/mcp/call`, `/mcp/p/`, `/mcp/s/`. Version 1 serves one OAuth endpoint, `/mcp/oauth`. `/mcp` behaves exactly as today. +- OAuth on `/mcp`, `/mcp/all`, `/mcp/code`, `/mcp/call`, `/mcp/p/`, `/mcp/s/`. Version 1 serves OAuth only under `/mcp/oauth`. `/mcp` behaves exactly as today. - Confidential clients (client secrets), Client ID Metadata Documents, token introspection endpoints. - Server edition behaviour and the tunnel. The data model leaves room for both (see "Later"). - Approving a login from the CLI. ## Anti-goals -- A client gets access because of the name it reports. Never. +- A client gets access, or is matched to an existing client, because of the name it reports. Never. +- Matching that works "most of the time". Which client a login belongs to is either determined by the address or chosen by the user. +- An update that changes behaviour or needs an action from a user who did not ask for OAuth. - A login that silently lands on "All servers" while profiles exist. - A second, parallel notion of "client" with its own profile rules. - An OAuth client bound to a profile that it can escape by using `/mcp` without a credential. @@ -48,59 +53,66 @@ Answer: MCPProxy suggests, the user confirms. The client's self-reported name on 1. **Automatic by name.** Match `client_name` to the connect registry and assign that client's profile with no question. Rejected: the name is self-asserted, so any local process can call itself "Cursor" and inherit Cursor's access. 2. **User selects everything every time.** Safe. Rejected as the default: tedious, and clients that register again pile up as "Cursor (2)", "Cursor (3)". -3. **Suggest and confirm (chosen).** The server computes a suggestion (which client, which profile, whether this replaces an earlier login). The consent page shows it pre-filled. The user approves with one click or changes it. Chosen by Algis on 2026-11-22. +3. **Suggest and confirm (chosen).** The consent page arrives pre-filled; the user approves with one click or changes it. Chosen by Algis on 2026-11-22. + +How the page is pre-filled was revised the same day, after Algis asked for it to be reliable: + +- **3a. Guess from the reported name** (registry list of OAuth registration names, plus learning from earlier approvals). Rejected: clients register under names nobody controls, the list needs upkeep, and a wrong guess puts the wrong client on the page. +- **3b. Per-client address (chosen).** Connect already knows which client it is configuring, so it writes that into the URL. The server reads the client from the path. Deterministic, no list to maintain, no secret in the config file. ## How it works ### Flow -1. The client calls `/mcp/oauth` without a token. Answer: `401` with `WWW-Authenticate: Bearer resource_metadata="…"`. -2. The client reads `/.well-known/oauth-protected-resource/mcp/oauth` and `/.well-known/oauth-authorization-server`, then registers at `POST /oauth/register`. -3. The client opens the browser at `GET /oauth/authorize`. The server validates the request (known `client_id`, exact redirect URI match, `code_challenge_method=S256`, `resource` equal to the `/mcp/oauth` URL), stores an **authorization request** (10 minute life) and redirects the browser to `/ui/authorize?request=`. -4. The Web UI consent page loads the request and its suggestion through the REST API, with the admin API key. +1. The client calls `/mcp/oauth/` (or `/mcp/oauth`) without a token. Answer: `401` with `WWW-Authenticate: Bearer resource_metadata="…"`. +2. The client reads the protected-resource metadata for that exact path and `/.well-known/oauth-authorization-server`, then registers at `POST /oauth/register`. +3. The client opens the browser at `GET /oauth/authorize`. The server validates the request (known `client_id`, exact redirect URI match, `code_challenge_method=S256`, `resource` equal to the URL of an OAuth endpoint this instance serves), stores an **authorization request** (10 minute life) and redirects the browser to `/ui/authorize?request=`. +4. The Web UI consent page loads the request and its pre-filled choices through the REST API, with the admin API key. 5. Approve: the page posts the decision; the answer carries the redirect URL with a single-use code. The page sends the browser there. Deny: redirect with `error=access_denied`. 6. The client exchanges the code at `POST /oauth/token` with its PKCE verifier and gets an access token and a refresh token. +### Which client is it + +Two kinds of address, both under `/mcp/oauth`: + +| Address | Who writes it | Client on the consent page | +|---|---|---| +| `/mcp/oauth/` | Connect, or the "Add browser login" action on a Clients row, or the user by hand | **Fixed**: that client. Not selectable | +| `/mcp/oauth` | the user by hand, for a client MCPProxy has never seen | **Chosen by the user**: "New client" (name field pre-filled from the reported name) or an existing client from a list. Nothing is pre-selected among existing clients | + +- `` is the Clients hub id: a connect-registry id (`cursor`, `claude-code`) or a custom client's id. The path is the `resource` the client sends at authorize (RFC 8707), so the server knows the client before the page is shown. +- An id that is neither in the registry nor an existing custom client answers 404 on every step. Clients are not created by typing a new path. +- The address is not a secret and proves nothing. Any local process can use it. That is why consent is shown every time, and why the page says in words whose access is being handed over. +- A token issued for `/mcp/oauth/cursor` is accepted only there, and only while its grant belongs to `cursor`. +- The same registration (`client_id`) coming back is recognised exactly: the page says "Signed in before" and offers to replace that login. +- After login, the name sent at `initialize` is compared with the client's known names. A mismatch is an advisory warning on the Clients row. It blocks nothing. + ### The consent page ``` -"Cursor" wants to connect to MCPProxy -Name reported by the app. MCPProxy cannot verify it. +Sign-in request for Cursor +The app calls itself "Cursor IDE". MCPProxy cannot verify that. Returns to: http://127.0.0.1:54321/callback -Client (•) Cursor (already connected with an API key) - ( ) New client [ Cursor 2 ] -Profile [ dev-readonly ▾ ] locked +Client Cursor (already connected with an API key) +Profile dev-readonly (locked) Approving gives this app the same access as Cursor. -[x] Replace the previous browser login of Cursor (approved 3 Nov) +[x] Replace the previous browser login (approved 3 Nov) [ Deny ] [ Approve ] ``` Rules for the page: -- The reported name is always labelled as unverified. When an existing client is selected, the page says in words that the app receives that client's access. +- **Per-client address**: the client is fixed. If it already has a binding, the profile is shown, not asked. If it is new, the profile rule below applies. +- **Generic address**: the user picks the client first. +- **Profile for a client with no binding yet**: if no profiles are configured, "All servers". If profiles exist, nothing is pre-selected and Approve stays disabled until the user picks one. Same rule as `profile_required` in the `credentials` tool. Binding mode defaults to `locked`. +- **Replace previous login** is pre-checked only when this exact `client_id` already has a grant. Otherwise the new login is added next to the existing ones. - **No admin key in this browser**: the page cannot load the request. It shows "Open this request from the MCPProxy tray, or paste the API key". The core emits an SSE event for a new authorization request; the tray shows a notification and a menu item "Approve sign-in for Cursor…" that opens the same URL with the key, the way it opens the Web UI today. -- **Bypassable binding**: when the chosen profile is a named one and `require_mcp_auth` is off, approval would be refused with `binding_bypassable_without_auth`. The page shows that refusal before the button is pressed, with the fixes the binding guard itself lists (`internal/runtime/binding_guard.go`: turn `require_mcp_auth` on, or set `anonymous_profile`). No exception for OAuth clients. +- **Bypassable binding**: when the profile is a named one and `require_mcp_auth` is off, approval would be refused with `binding_bypassable_without_auth`. The page shows that refusal before the button is pressed, with the fixes the binding guard itself lists (`internal/runtime/binding_guard.go`: turn `require_mcp_auth` on, or set `anonymous_profile`). No exception for OAuth clients. - The page is never framed (`frame-ancestors 'none'`). Approval is an API-key-authenticated REST call, not a cookie form, so there is no cross-site request to forge. -### The suggestion - -Computed on the server, returned with the authorization request. First match wins: - -| # | Evidence | Client | Profile | Extra | -|---|---|---|---|---| -| 1 | This `client_id` already has an approved grant | the grant's client | the client's binding | "Signed in before" | -| 2 | An approved grant exists whose registration had the same reported name (normalised) and the same redirect URI set | that grant's client | its binding | "replace previous login" pre-checked | -| 3 | Reported name matches the registry (below), and a Clients row with that id exists | that row | its binding | | -| 4 | Reported name matches the registry, no row yet | new client with the registry id | see below | registry icon and display name | -| 5 | Nothing matches | new custom client, id is a slug of the name, made unique | see below | | - -Registry match: the name a client registers with is not the name it sends at `initialize`, so `ClientInfoNames` alone would rarely match. The registry gains `OAuthClientNames` per client (PR-1, filled from observed registrations and public documentation, best effort like `ClientInfoNames`). A reported name matches a registry client when, after normalisation and case folding, it equals the client's id, display name, a `ClientInfoNames` alias or an `OAuthClientNames` entry. Row 2 is what stops the pile-up for clients the registry does not know: the first approval teaches MCPProxy which client that name and redirect set belong to. - -Profile for a new client: if no profiles are configured, "All servers". If profiles exist, nothing is pre-selected and Approve stays disabled until the user picks one. This is the same rule as `profile_required` in the `credentials` tool. Binding mode defaults to `locked`. - -Consent is shown every time, including row 1. A public client has no secret and loopback redirects match on any port, so a different local process can reuse a known `client_id`. The click is the check. +Consent is shown every time. A public client has no secret and loopback redirects match on any port, so a different local process can reuse a known `client_id` or address. The click is the check. ### Identity and data @@ -112,7 +124,7 @@ Three new records, in their own bbolt buckets. They are keyed by client, not by Tokens: -- Access token: opaque, prefix `mcp_oat_`, HMAC-SHA256 hashed like agent tokens, 1 hour, accepted only on `/mcp/oauth`. +- Access token: opaque, prefix `mcp_oat_`, HMAC-SHA256 hashed like agent tokens, 1 hour, accepted only on the OAuth address it was issued for. - Refresh token: opaque, prefix `mcp_ort_`, rotated on every use, 30 days sliding. Reuse of an already rotated refresh token revokes the grant (OAuth 2.1 rule for public clients). **One client, several credentials.** A Clients hub row is the identity. Under it: at most one API key (today's `mcp_cli_` record) and any number of OAuth grants. The profile binding belongs to the client, not to a credential. An access token authenticates to the same `AuthContext` a client credential produces: `AuthTypeAgent`-class caller, `Kind=client`, the client's id, the client's binding. Everything downstream (profile resolution, pin boundary, activity `client_id`, `/tools?client=`) is unchanged. @@ -126,7 +138,7 @@ Activity rows gain the credential kind `oauth` and the grant id, so two logins o - The resource and the issuer are built from the **origin of the request**, after the existing host validation (loopback names and `trusted_hosts`). `http://127.0.0.1:8080` and `http://localhost:8080` are two resources; a client stays on the one it was configured with. The metadata documents, the `resource` check at authorize and the audience of a token all use that origin, and a token is refused on any other. - The consent redirect stays on the same origin. If the browser holds the admin key under another origin, the page takes the "no admin key" path and the tray opens the request on the right origin. - Version 1 serves `/mcp/oauth`, `/oauth/*` and the metadata only to requests that arrive from a loopback address with a loopback host. Anything else gets 404, so a LAN listen exposes no open registration. The tunnel lifts this later under its own rules. -- `/mcp/oauth` serves the same tool surface as `/mcp` (it follows `routing_mode`). It is registered ahead of the `/mcp/` catch-all. Behaviour change to note in the docs: today `/mcp/oauth` falls into that catch-all and answers like `/mcp`. +- `/mcp/oauth` and `/mcp/oauth/` serve the same tool surface as `/mcp` (they follow `routing_mode`). While the feature is on they are registered ahead of the `/mcp/` catch-all. While it is off they are not registered at all, so these paths keep falling into the catch-all exactly as today. - Server edition: the feature answers 404 in version 1 whatever the setting, because consent by admin API key would create grants with no user. ### Revoke and forget @@ -151,7 +163,7 @@ Cursor profile: dev-readonly (locked) ### Connect -The registry gains a flag for clients known to support the MCP authorization flow. For those, Connect (Web UI, CLI `mcpproxy connect --auth oauth|key`) offers both. "Sign in with browser" writes only the `/mcp/oauth` URL into the client's config, no header. The diff preview and backup notice are unchanged. Default stays "API key" in version 1. +The registry gains a flag for clients known to support the MCP authorization flow. Only while `mcp_oauth_enabled` is on, Connect (Web UI, CLI `mcpproxy connect --auth oauth|key`) offers both for those clients. "Sign in with browser" writes only the client's own address, `/mcp/oauth/`, into the client's config, no header and no secret. The diff preview and backup notice are unchanged. The default choice stays "API key". With the feature off, Connect looks and behaves as today. ### Limits and abuse @@ -160,27 +172,38 @@ The registry gains a flag for clients known to support the MCP authorization flo - `/oauth/authorize` and `/oauth/token`: rate limited; codes are single-use, 60 seconds, bound to client, redirect URI and PKCE challenge. - All `/oauth/*` and `/.well-known/*` endpoints are unauthenticated by nature and answer nothing about servers, profiles or existing clients. -### Configuration +### Configuration and upgrade -`mcp_oauth_enabled` (default **on**, env `MCPPROXY_MCP_OAUTH_ENABLED`). Off: `/mcp/oauth`, `/oauth/*` and the metadata documents answer 404 and existing grants stop authenticating until it is on again. +`mcp_oauth_enabled`, default **off**, env `MCPPROXY_MCP_OAUTH_ENABLED`, also a switch on the Settings page marked "Experimental". No restart is needed: routes are added and removed on config reload. + +- **Off (default)**: no new route, no metadata document, no new bucket is created, no Connect option, no Clients hub column, no startup notice. Existing API keys, agent tokens, client credentials, `/mcp` and every routing-mode endpoint are untouched. A test pins this: the route table and the answers on `/mcp/oauth*`, `/oauth/*` and `/.well-known/oauth-*` with the feature off equal those of the previous release. +- **On**: everything in this document. API keys keep working next to it. +- **Turned off again**: OAuth addresses stop authenticating at once. Grants and bindings are kept, so turning it on again restores them. A client configured with only an OAuth address is then reported on its Clients row as "browser login disabled". +- **Downgrade** to a binary without the feature: the buckets are ignored, OAuth-only clients fall into the `/mcp/` catch-all as anonymous callers. The docs say to turn `require_mcp_auth` on first, as for pre-108 downgrades. ## Delivery -1. **PR-1, backend**: metadata, registration, authorize, token, storage, `/mcp/oauth` handler, authentication into the existing client `AuthContext`, the single binding, REST for authorization requests (get with suggestion, approve, deny), activity rows, limits. +1. **PR-1, backend**: metadata, registration, authorize, token, storage, `/mcp/oauth` and `/mcp/oauth/` handlers, the off-by-default switch with its unchanged-behaviour test, authentication into the existing client `AuthContext`, the single binding, REST for authorization requests (get with pre-filled choices, approve, deny), activity rows, limits. 2. **PR-2, surfaces**: consent page, macOS tray notification, Clients hub credentials list, `credentials` / REST / CLI list and revoke. **PR-2b**: the same notification in the Go tray (Windows, Linux); until then those users paste the key or open the Web UI from the tray first. 3. **PR-3, Connect and docs**: registry flag, the Connect choice, `docs/features/client-oauth-login.md`, updates to connect-clients, profiles, REST reference. Each PR is test-first. End to end: a scripted public client runs the whole flow against a built core (`scripts/test-client-oauth-e2e.sh`), including refresh rotation, reuse detection, revoke on a live session and the bypassable-binding refusal. +## Decided by Algis + +- OAuth and API keys both stay; the user chooses per client. +- Suggest and confirm on the consent page. +- Which client a login belongs to must be reliable, not guessed from names (2026-11-22). +- Off by default in the first release; an update needs no action and changes nothing for existing users (2026-11-22). + ## Calls made here (not decided by Algis) -- One OAuth endpoint, `/mcp/oauth`, as the issue proposes; tokens are bound to it. -- Feature on by default. +- Readable per-client address (`/mcp/oauth/`) instead of a random one: it carries no authority, so it need not be secret. +- A generic-address login never pre-selects an existing client. - Consent every time, with no silent re-approval. - Token lifetimes (1 hour / 30 days sliding) and the numeric limits above. - Default Connect choice stays "API key". - No CLI approval, no custom-scheme redirects, no confidential clients in version 1. -- Registry gains `OAuthClientNames`; suggestion row 2 learns from earlier approvals. - Resource and issuer follow the request origin; OAuth is loopback-only and off in server edition for version 1. - "Revoke client" revokes the API key and all grants; forgetting a client deletes its grants. - `/mcp/oauth` follows `routing_mode`; Go tray notification is a follow-up PR. @@ -196,4 +219,4 @@ Each PR is test-first. End to end: a scripted public client runs the whole flow ## Later - **Server edition**: the consent page needs the user's session; the grant carries `user_id`; selectable profiles and clients are the user's own. -- **Tunnel (Spec 089)**: same endpoints behind the tunnel origin, consent protected by the proxy-managed credential, tokens bound to the tunnel resource URI. Client ID Metadata Documents would give hosted clients a domain-verified name and can strengthen suggestion row 2. +- **Tunnel (Spec 089)**: same endpoints behind the tunnel origin, consent protected by the proxy-managed credential, tokens bound to the tunnel resource URI. Client ID Metadata Documents would give hosted clients a domain-verified name to show on the consent page. From 2181985237b515c7b687a2f6dea8fb90702e7082 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sun, 22 Nov 2026 16:24:04 +0200 Subject: [PATCH 03/15] docs(spec): address design review round 1 (#1971) --- specs/131-client-oauth-login/design.md | 42 ++++++++++++++++++++------ 1 file changed, 33 insertions(+), 9 deletions(-) diff --git a/specs/131-client-oauth-login/design.md b/specs/131-client-oauth-login/design.md index 8aa1866a3..a1a2a7d35 100644 --- a/specs/131-client-oauth-login/design.md +++ b/specs/131-client-oauth-login/design.md @@ -65,12 +65,24 @@ How the page is pre-filled was revised the same day, after Algis asked for it to ### Flow 1. The client calls `/mcp/oauth/` (or `/mcp/oauth`) without a token. Answer: `401` with `WWW-Authenticate: Bearer resource_metadata="…"`. -2. The client reads the protected-resource metadata for that exact path and `/.well-known/oauth-authorization-server`, then registers at `POST /oauth/register`. -3. The client opens the browser at `GET /oauth/authorize`. The server validates the request (known `client_id`, exact redirect URI match, `code_challenge_method=S256`, `resource` equal to the URL of an OAuth endpoint this instance serves), stores an **authorization request** (10 minute life) and redirects the browser to `/ui/authorize?request=`. +2. The client reads the protected-resource metadata for that exact path and the authorization-server metadata, then registers at `POST /oauth/register`. +3. The client opens the browser at `GET /oauth/authorize`. The server validates the request (known `client_id`, exact redirect URI match, `code_challenge_method=S256`, `resource` equal to the URL of an OAuth endpoint this instance serves on this origin), stores an **authorization request** (10 minute life) with the client's `state`, the full `resource` URI and the issuer, and redirects the browser to `/ui/authorize?request=`. 4. The Web UI consent page loads the request and its pre-filled choices through the REST API, with the admin API key. -5. Approve: the page posts the decision; the answer carries the redirect URL with a single-use code. The page sends the browser there. Deny: redirect with `error=access_denied`. +5. Approve: the page posts the decision; the answer carries the redirect URL with a single-use code. The page sends the browser there. Deny: redirect with `error=access_denied`. Both redirects are built from the stored, already validated redirect URI and return the client's `state` unchanged. 6. The client exchanges the code at `POST /oauth/token` with its PKCE verifier and gets an access token and a refresh token. +**Resource binding.** The approved `resource` and issuer are stored on the authorization request, the code and the grant, and never change. A `resource` sent at code exchange or refresh must equal the stored one, else `invalid_target`. The audience of every access token comes from the grant, never from the Host or parameters of the current request. + +**An authorization request is decided once.** Its state moves `pending → approved | denied | expired | cancelled` in one transaction; at most one code is ever produced, and a second tab gets "already decided". The page carries the revision of what it displayed (client, profile, binding mode). Approval is refused with "this changed, review again" when the client's binding differs from that revision. Forgetting the client or turning the feature off cancels its pending requests. + +**Metadata.** Tested against these exact shapes: + +- `GET /.well-known/oauth-protected-resource/mcp/oauth/cursor` → `resource: "/mcp/oauth/cursor"`, `authorization_servers: [""]`. Each path has its own document; the generic one is `/.well-known/oauth-protected-resource/mcp/oauth`. A document is never reused across paths. +- `GET /.well-known/oauth-authorization-server` → `issuer: ""`, the three endpoints, `response_types_supported: ["code"]`, `grant_types_supported: ["authorization_code","refresh_token"]`, `code_challenge_methods_supported: ["S256"]`, `token_endpoint_auth_methods_supported: ["none"]`. +- The registration answer (RFC 7591) states the effective values, `token_endpoint_auth_method: "none"` and the two grant types, and the registration record stores them. A registration that asks for a secret-based method or another grant type is refused. + +**Plain HTTP on loopback is a known deviation.** RFC 8414 and the MCP authorization spec ask for an HTTPS authorization server; RFC 8252 only exempts loopback redirect URIs. Version 1 serves the issuer on `http://127.0.0.1` as most local MCP servers do, says so in the docs, and claims support only for clients that pass a real-client test (PR-1 gate: Claude Code, Cursor, VS Code, MCP Inspector, each on a per-client path). When local TLS (`internal/tlslocal`) is on, the same endpoints are served over HTTPS and conform. + ### Which client is it Two kinds of address, both under `/mcp/oauth`: @@ -106,7 +118,7 @@ Rules for the page: - **Per-client address**: the client is fixed. If it already has a binding, the profile is shown, not asked. If it is new, the profile rule below applies. - **Generic address**: the user picks the client first. -- **Profile for a client with no binding yet**: if no profiles are configured, "All servers". If profiles exist, nothing is pre-selected and Approve stays disabled until the user picks one. Same rule as `profile_required` in the `credentials` tool. Binding mode defaults to `locked`. +- **Profile for a client with no binding yet**: if no profiles are configured, "All servers", stored the way it is today for a client credential (no pin, `switchable`; a locked credential with an empty profile is invalid under `ValidateTokenInvariants` and stays so). If profiles exist, nothing is pre-selected and Approve stays disabled until the user picks one; a named profile defaults to `locked`. Same rule as `profile_required` in the `credentials` tool. - **Replace previous login** is pre-checked only when this exact `client_id` already has a grant. Otherwise the new login is added next to the existing ones. - **No admin key in this browser**: the page cannot load the request. It shows "Open this request from the MCPProxy tray, or paste the API key". The core emits an SSE event for a new authorization request; the tray shows a notification and a menu item "Approve sign-in for Cursor…" that opens the same URL with the key, the way it opens the Web UI today. - **Bypassable binding**: when the profile is a named one and `require_mcp_auth` is off, approval would be refused with `binding_bypassable_without_auth`. The page shows that refusal before the button is pressed, with the fixes the binding guard itself lists (`internal/runtime/binding_guard.go`: turn `require_mcp_auth` on, or set `anonymous_profile`). No exception for OAuth clients. @@ -119,17 +131,24 @@ Consent is shown every time. A public client has no secret and loopback redirect Three new records, in their own bbolt buckets. They are keyed by client, not by upstream server, so the Spec 116 server purge set does not apply; their cleanup is described under "Revoke and forget". - **Registration** (`oauth_registrations`): opaque random `client_id`, reported name (sanitised with `clientidentity`), redirect URIs, optional `software_id` / `software_version`, created time, state `pending | approved | denied`. -- **Grant** (`oauth_grants`): one approved login. Fields: id, `client_id` of the registration, **Clients hub client id**, approved time, approving actor, last used, revoked flag, `user_id` (empty in the personal edition). Holds the hash and 12-character prefix of the current refresh token and the token family id. +- **Grant** (`oauth_grants`): one approved login. Fields: id, `client_id` of the registration, **Clients hub client id**, the approved `resource` URI and issuer, approved time, approving actor, last used, revoked flag, `user_id` (empty in the personal edition). Holds the hash and 12-character prefix of the current refresh token. - **Authorization request / code**: short-lived, memory only. A restart drops them and the client starts again. Tokens: - Access token: opaque, prefix `mcp_oat_`, HMAC-SHA256 hashed like agent tokens, 1 hour, accepted only on the OAuth address it was issued for. -- Refresh token: opaque, prefix `mcp_ort_`, rotated on every use, 30 days sliding. Reuse of an already rotated refresh token revokes the grant (OAuth 2.1 rule for public clients). +- Refresh token: `mcp_ort__`, rotated on every use, 30 days sliding. The grant id inside the token is what makes replay detectable after any number of rotations and across restarts: a token that names a live grant but whose secret is not the current one is a replay, and the grant is revoked in the same transaction (OAuth 2.1 rule for public clients). Consuming the old secret and storing the new hash is one transaction. The grant id is random, appears only inside tokens and grants nothing by itself. **One client, several credentials.** A Clients hub row is the identity. Under it: at most one API key (today's `mcp_cli_` record) and any number of OAuth grants. The profile binding belongs to the client, not to a credential. An access token authenticates to the same `AuthContext` a client credential produces: `AuthTypeAgent`-class caller, `Kind=client`, the client's id, the client's binding. Everything downstream (profile resolution, pin boundary, activity `client_id`, `/tools?client=`) is unchanged. -The invariant for the builder: **one binding per client id, read by both the API-key path and the OAuth path, changed by one writer** (`ClientsService`, which already owns `SetBinding`, `BulkAssign`, `Add` and `Forget`). Today the binding is stored on the API-key record. How to hold it for a client that has only OAuth grants is the builder's call (a credential-less client record, or a small `client_bindings` bucket that both paths read). Reassign, rename, delete-profile (`profile_in_use`, `reassign_to`, dangling means deny-all) and the bypassable-binding check must cover OAuth-only clients exactly as they cover API-key clients. +The invariant for the builder: **one binding per client id, read by both the API-key path and the OAuth path, changed by one writer** (`ClientsService`, which already owns `SetBinding`, `BulkAssign`, `Add` and `Forget`). Where it is stored is fixed here, because a downgrade must never widen access: + +- A client with an API key keeps its binding on that record (`ProfilePin`, `ProfileMode`), exactly as today. Those fields stay authoritative for the API-key path and are always kept current, so an older binary reads the right profile. +- A client with grants also has the binding in an OAuth-side record (`oauth_client_bindings`), read by the OAuth path. +- `ClientsService` writes both in one transaction when both exist, including on rotation and reconnect. A startup check repairs a mismatch from the API-key record and logs it. +- With the feature off, no bucket is created and nothing is migrated. + +Reassign, rename, delete-profile (`profile_in_use`, `reassign_to`, dangling means deny-all) and the bypassable-binding check must cover OAuth-only clients exactly as they cover API-key clients. Activity rows gain the credential kind `oauth` and the grant id, so two logins of one client can be told apart. Issue, approve, deny, refresh-reuse and revoke are recorded as `profile_change`-family rows through `CredentialsService`, with the actor in context. @@ -178,7 +197,9 @@ The registry gains a flag for clients known to support the MCP authorization flo - **Off (default)**: no new route, no metadata document, no new bucket is created, no Connect option, no Clients hub column, no startup notice. Existing API keys, agent tokens, client credentials, `/mcp` and every routing-mode endpoint are untouched. A test pins this: the route table and the answers on `/mcp/oauth*`, `/oauth/*` and `/.well-known/oauth-*` with the feature off equal those of the previous release. - **On**: everything in this document. API keys keep working next to it. -- **Turned off again**: OAuth addresses stop authenticating at once. Grants and bindings are kept, so turning it on again restores them. A client configured with only an OAuth address is then reported on its Clients row as "browser login disabled". +- **Turned off again**: two cases, told apart by whether any grant was ever stored. + - Never used (no grant record): identical to "off" above, including the legacy catch-all on `/mcp/oauth*`. + - Used: `/mcp/oauth*` answers 404 instead of falling into the `/mcp/` catch-all, so a browser-login client does not quietly continue as an anonymous caller when `require_mcp_auth` is off. `/oauth/*`, the metadata and the consent REST calls answer 404 and pending requests are cancelled. Grants and bindings are kept, so turning it on again restores them. Such a client's row says "browser login disabled". - **Downgrade** to a binary without the feature: the buckets are ignored, OAuth-only clients fall into the `/mcp/` catch-all as anonymous callers. The docs say to turn `require_mcp_auth` on first, as for pre-108 downgrades. ## Delivery @@ -211,11 +232,14 @@ Each PR is test-first. End to end: a scripted public client runs the whole flow ## Left to the builder -- Where the per-client binding is stored (see the invariant). - Bucket layouts, the exact REST paths and payloads, SSE event name. - Whether access tokens are separate rows or derived from the grant record. - Rate-limit implementation, reusing the existing limiter where it fits. +## Review + +Cross-model review, round 1 (opencode `gpt-6.1-sol`, 2026-11-22): nine findings, all accepted. Replay detection through the grant id in the refresh token, resource and issuer stored on request, code and grant, single-decision consent with a binding revision, fail-closed OAuth paths after the feature was used and turned off, the HTTP-issuer deviation, exact metadata shapes, `state`, downgrade-safe binding storage, and the "All servers" representation. + ## Later - **Server edition**: the consent page needs the user's session; the grant carries `user_id`; selectable profiles and clients are the user's own. From 910d6a02b631a96db846f51d63586563cf0de17c Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sun, 22 Nov 2026 16:26:14 +0200 Subject: [PATCH 04/15] docs(spec): address design review round 2 (#1971) --- specs/131-client-oauth-login/design.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/specs/131-client-oauth-login/design.md b/specs/131-client-oauth-login/design.md index a1a2a7d35..7a22b0d6c 100644 --- a/specs/131-client-oauth-login/design.md +++ b/specs/131-client-oauth-login/design.md @@ -137,7 +137,10 @@ Three new records, in their own bbolt buckets. They are keyed by client, not by Tokens: - Access token: opaque, prefix `mcp_oat_`, HMAC-SHA256 hashed like agent tokens, 1 hour, accepted only on the OAuth address it was issued for. -- Refresh token: `mcp_ort__`, rotated on every use, 30 days sliding. The grant id inside the token is what makes replay detectable after any number of rotations and across restarts: a token that names a live grant but whose secret is not the current one is a replay, and the grant is revoked in the same transaction (OAuth 2.1 rule for public clients). Consuming the old secret and storing the new hash is one transaction. The grant id is random, appears only inside tokens and grants nothing by itself. +- Refresh token: `mcp_ort___`, rotated on every use, 30 days sliding. `` is an HMAC over the grant id and the secret with the server's token key (the key agent tokens are hashed with), so the server can tell a token it really issued from a made-up one without storing spent tokens. Order of checks at the token endpoint: + 1. Malformed token, bad MAC, unknown or revoked grant id: `invalid_grant`, identical answer for all, **nothing is written**. Knowing a grant id (it is shown in activity rows and management surfaces) is therefore not enough to disturb a grant. + 2. MAC valid and the secret is the grant's current one: rotate. Consuming the old secret and storing the new hash is one transaction. + 3. MAC valid and the secret is not the current one: an authentic, already used token came back. The grant is revoked in that transaction (OAuth 2.1 rule for public clients). This works after any number of rotations and across restarts. **One client, several credentials.** A Clients hub row is the identity. Under it: at most one API key (today's `mcp_cli_` record) and any number of OAuth grants. The profile binding belongs to the client, not to a credential. An access token authenticates to the same `AuthContext` a client credential produces: `AuthTypeAgent`-class caller, `Kind=client`, the client's id, the client's binding. Everything downstream (profile resolution, pin boundary, activity `client_id`, `/tools?client=`) is unchanged. @@ -197,8 +200,8 @@ The registry gains a flag for clients known to support the MCP authorization flo - **Off (default)**: no new route, no metadata document, no new bucket is created, no Connect option, no Clients hub column, no startup notice. Existing API keys, agent tokens, client credentials, `/mcp` and every routing-mode endpoint are untouched. A test pins this: the route table and the answers on `/mcp/oauth*`, `/oauth/*` and `/.well-known/oauth-*` with the feature off equal those of the previous release. - **On**: everything in this document. API keys keep working next to it. -- **Turned off again**: two cases, told apart by whether any grant was ever stored. - - Never used (no grant record): identical to "off" above, including the legacy catch-all on `/mcp/oauth*`. +- **Turned off again**: two cases, told apart by a persistent marker `oauth_ever_used`. It is written in the transaction that stores the first grant and is never cleared, not by revoke, forget or cleanup, so forgetting the last browser-login client does not bring the catch-all back. + - Never used (marker absent): identical to "off" above, including the legacy catch-all on `/mcp/oauth*`. Storing the marker is the only write the feature makes outside its own buckets. - Used: `/mcp/oauth*` answers 404 instead of falling into the `/mcp/` catch-all, so a browser-login client does not quietly continue as an anonymous caller when `require_mcp_auth` is off. `/oauth/*`, the metadata and the consent REST calls answer 404 and pending requests are cancelled. Grants and bindings are kept, so turning it on again restores them. Such a client's row says "browser login disabled". - **Downgrade** to a binary without the feature: the buckets are ignored, OAuth-only clients fall into the `/mcp/` catch-all as anonymous callers. The docs say to turn `require_mcp_auth` on first, as for pre-108 downgrades. @@ -244,3 +247,5 @@ Cross-model review, round 1 (opencode `gpt-6.1-sol`, 2026-11-22): nine findings, - **Server edition**: the consent page needs the user's session; the grant carries `user_id`; selectable profiles and clients are the user's own. - **Tunnel (Spec 089)**: same endpoints behind the tunnel origin, consent protected by the proxy-managed credential, tokens bound to the tunnel resource URI. Client ID Metadata Documents would give hosted clients a domain-verified name to show on the consent page. + +Round 2 (same reviewer): two findings, both accepted. A refresh token is authenticated by a MAC before the replay rule applies, so a known grant id cannot be used to revoke a grant; "ever used" is a persistent marker, not the presence of grant records. From 9a22e98e5cd4741e58b5d8f6e78ddbf9db266d05 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sun, 22 Nov 2026 16:29:50 +0200 Subject: [PATCH 05/15] docs(spec): spec 131 browser login for MCP clients Related #1971 --- .../checklists/requirements.md | 35 +++ specs/131-client-oauth-login/spec.md | 275 ++++++++++++++++++ 2 files changed, 310 insertions(+) create mode 100644 specs/131-client-oauth-login/checklists/requirements.md create mode 100644 specs/131-client-oauth-login/spec.md diff --git a/specs/131-client-oauth-login/checklists/requirements.md b/specs/131-client-oauth-login/checklists/requirements.md new file mode 100644 index 000000000..07592e9ea --- /dev/null +++ b/specs/131-client-oauth-login/checklists/requirements.md @@ -0,0 +1,35 @@ +# Specification Quality Checklist: Browser login for MCP clients (opt-in OAuth) + +**Purpose**: Validate specification completeness and quality before proceeding to planning +**Created**: 2026-11-22 +**Feature**: [spec.md](../spec.md) + +## Content Quality + +- [x] No implementation details (languages, frameworks, APIs) +- [x] Focused on user value and business needs +- [x] Written for non-technical stakeholders +- [x] All mandatory sections completed + +## Requirement Completeness + +- [x] No [NEEDS CLARIFICATION] markers remain +- [x] Requirements are testable and unambiguous +- [x] Success criteria are measurable +- [x] Success criteria are technology-agnostic (no implementation details) +- [x] All acceptance scenarios are defined +- [x] Edge cases are identified +- [x] Scope is clearly bounded +- [x] Dependencies and assumptions identified + +## Feature Readiness + +- [x] All functional requirements have clear acceptance criteria +- [x] User scenarios cover primary flows +- [x] Feature meets measurable outcomes defined in Success Criteria +- [x] No implementation details leak into specification + +## Notes + +- The spec names `require_mcp_auth`, the `credentials` tool and the Clients hub because they are existing product surfaces the user sees. Protocol shapes, storage and token formats stay in design.md. +- Decisions come from design.md ("Decided by Algis", "Calls made here"), cross-reviewed in three rounds (opencode gpt-6.1-sol, round 3 clean). diff --git a/specs/131-client-oauth-login/spec.md b/specs/131-client-oauth-login/spec.md new file mode 100644 index 000000000..274fac6b6 --- /dev/null +++ b/specs/131-client-oauth-login/spec.md @@ -0,0 +1,275 @@ +# Feature Specification: Browser login for MCP clients (opt-in OAuth), next to API keys + +**Feature Branch**: `claude/oauth-api-key-client-role-eb4179` +**Created**: 2026-11-22 +**Status**: Draft +**Input**: Issue [#1971](https://github.com/smart-mcp-proxy/mcpproxy-go/issues/1971): let MCPProxy act as the OAuth authorization server for its own MCP endpoint so a client needs only a URL. Keep API keys; let the user choose. Decide how a client is identified after login. + +**Related**: [design.md](./design.md) is the approved and cross-reviewed design; it holds the decisions, the rejected alternatives and the protocol detail this spec refers to. [Spec 108](../108-profiles-v3/) (client credentials and bindings), [Spec 115](../115-mcp-credential-lifecycle/) (credential lifecycle), [Spec 089](../089-remote-access-tunnel/spec.md) (tunnel, later reuse). + +## User Scenarios & Testing *(mandatory)* + +### User Story 1 - Updating changes nothing (Priority: P1) + +A user who updates MCPProxy and never asked for browser login sees no difference. Every client keeps working with the credential it has. No prompt, no new screen, no new entry in any menu. + +**Why this priority**: Algis's condition for shipping the first release. The feature must not cost existing users anything. + +**Independent Test**: Run the existing end-to-end suites and a route-table comparison against the previous release with the feature at its default. Everything is identical. + +**Acceptance Scenarios**: + +1. **Given** a default configuration after an update, **When** any existing client connects with its API key, client credential or agent token, **Then** it behaves exactly as before the update. +2. **Given** the default configuration, **When** a request is sent to any browser-login address or discovery document, **Then** the answer is the same as in the previous release. +3. **Given** the default configuration, **When** the user opens Connect, the Clients hub, Settings or the tray, **Then** nothing about browser login is shown except one switch on the Settings page, off and marked "Experimental". +4. **Given** the default configuration, **When** MCPProxy starts, **Then** it creates no new stored data and shows no notice about this feature. + +--- + +### User Story 2 - Sign a known client in with the browser (Priority: P1) + +A user turns browser login on, chooses "Sign in with browser" for Cursor in Connect, and restarts Cursor. The browser opens a page that says "Sign-in request for Cursor". The user clicks Approve. Cursor is connected with Cursor's profile, and no secret was written to Cursor's config file. + +**Why this priority**: This is the feature. It also answers the identity question: Connect gave Cursor its own address, so MCPProxy knows the request is for Cursor without guessing. + +**Independent Test**: With the feature on, configure a scripted client with a per-client address, complete the flow with one approval, call a tool, and confirm the activity row names that client and its profile. + +**Acceptance Scenarios**: + +1. **Given** the feature is on and Cursor already has a profile binding, **When** a sign-in request arrives on Cursor's address, **Then** the consent page shows Cursor as the client, not selectable, with its current profile, and one click on Approve completes the login. +2. **Given** an approved login, **When** the client calls tools, **Then** it reaches exactly what Cursor's profile allows, and activity is attributed to Cursor. +3. **Given** a client that is new to MCPProxy and profiles exist, **When** its sign-in request is shown, **Then** no profile is pre-selected and Approve is disabled until the user picks one. +4. **Given** no profiles are configured, **When** a new client's sign-in request is shown, **Then** "All servers" is the pre-filled access. +5. **Given** a sign-in request, **When** the user clicks Deny, **Then** the client is told access was denied and nothing is stored for it. +6. **Given** the consent page shows a name the app reported about itself, **Then** that name is labelled as unverified and the page states in words whose access is being handed over. + +--- + +### User Story 3 - Manage and revoke logins (Priority: P1) + +The user opens the Clients hub. Cursor's row lists its credentials: an API key and two browser logins. The user revokes one login; the other and the API key keep working. Changing Cursor's profile changes access for all of them. + +**Why this priority**: Without revoke and a single place for access, browser login would be a second, weaker client model. + +**Independent Test**: Create a client with an API key and two logins, revoke one login, reassign the profile, and check each credential's access after each step. + +**Acceptance Scenarios**: + +1. **Given** a client with several credentials, **When** one browser login is revoked, **Then** it stops working on its next request, including on an open session, and the client's other credentials keep working. +2. **Given** a client, **When** the client itself is revoked, **Then** its API key and every browser login stop working. +3. **Given** a client, **When** its profile is changed, **Then** every credential of that client uses the new profile on its next request. +4. **Given** a client is forgotten, **Then** its browser logins are deleted with it. +5. **Given** a browser login unused for 30 days, **Then** it no longer works and the client must sign in again. + +--- + +### User Story 4 - Approve when the browser is not signed in to MCPProxy (Priority: P2) + +The client opens the user's default browser, which has never held MCPProxy's admin key. The page cannot show the request. It tells the user to open the request from the MCPProxy tray or to paste the API key. The tray shows a notification "Approve sign-in for Cursor…" that opens the request ready to approve. + +**Why this priority**: Common on a fresh browser profile. Without it the first login fails with no way forward. + +**Independent Test**: Open a sign-in request in a browser profile with empty storage; confirm the guidance, then approve through the tray entry. + +**Acceptance Scenarios**: + +1. **Given** a browser without the admin key, **When** the consent address opens, **Then** no detail of the request, of clients or of profiles is shown, only the two ways to continue. +2. **Given** a pending sign-in request on macOS, **When** the user picks the tray entry, **Then** the same request opens with the client and profile shown and can be approved. +3. **Given** the user pastes a valid API key, **Then** the request is shown and can be approved. + +--- + +### User Story 5 - A client MCPProxy has never seen (Priority: P2) + +The user types the generic browser-login address into a client that Connect does not know. On the consent page the user chooses "New client", keeps or edits the suggested name, picks a profile, and approves. The client appears in the Clients hub. + +**Why this priority**: Keeps the feature useful beyond the supported-client list, without name guessing. + +**Independent Test**: Run the flow on the generic address with an unknown client name; confirm the new client row, its profile and its activity attribution. + +**Acceptance Scenarios**: + +1. **Given** a sign-in request on the generic address, **Then** the user must choose between "New client" and an existing client; no existing client is pre-selected. +2. **Given** the user picks an existing client, **Then** the page states that the app receives that client's access before Approve is enabled. +3. **Given** an address that names a client id that does not exist, **Then** every step answers "not found" and no client is created. + +--- + +### User Story 6 - Choose the credential type in Connect (Priority: P3) + +With the feature on, Connect offers "API key" (default) and "Sign in with browser" for clients that support it. The preview shows that the browser option writes only an address, no secret. + +**Why this priority**: Convenience. The flow already works when the address is typed by hand. + +**Independent Test**: Connect a supported client with each option and compare the written config with the preview. + +**Acceptance Scenarios**: + +1. **Given** the feature is on and the client supports browser login, **When** the user opens Connect, **Then** both options are offered and "API key" is selected. +2. **Given** "Sign in with browser", **When** the change is applied, **Then** the client's config holds its own address and no credential, and the usual preview and backup notice were shown first. +3. **Given** the feature is off, **Then** Connect shows no choice. + +--- + +### User Story 7 - Turn it off again (Priority: P2) + +The user tried browser login and turns it off. Browser-login clients stop working at once and do not quietly continue as anonymous callers. Turning it on again restores them without a new approval. + +**Why this priority**: An experimental switch must be safe to flip back. + +**Independent Test**: Sign a client in, turn the feature off, confirm its requests are refused, turn it on, confirm it works again. + +**Acceptance Scenarios**: + +1. **Given** the feature was used and is turned off, **When** a browser-login client sends a request to its address, **Then** the request is refused, whatever `require_mcp_auth` is. +2. **Given** the feature was used, the last browser-login client was forgotten, and the feature is turned off, **Then** browser-login addresses are still refused. +3. **Given** the feature is turned on again, **Then** existing logins work without a new approval, and the Clients hub no longer says "browser login disabled". +4. **Given** pending sign-in requests, **When** the feature is turned off, **Then** they are cancelled. + +### Edge Cases + +- Two browser tabs approve the same request: one succeeds, the other is told it was already decided. Approve after Deny is refused. +- The client's profile changes while the consent page is open: approval is refused with "this changed, review again" and the page reloads. +- The chosen profile is a named one while `require_mcp_auth` is off: approval would let the client escape its profile by dropping its credential. The page shows the refusal and the fixes before the button can be pressed. +- A refresh credential that was already used comes back: that login is revoked. A made-up or malformed one changes nothing, even if it names a real login. +- A login approved for one client's address is presented on another address, or on `localhost` instead of `127.0.0.1`: refused. +- Many registrations that are never approved: they are capped and expire. +- A sign-in request left open for more than 10 minutes: expired; the client starts again. +- MCPProxy restarts during a sign-in: the pending request is gone; the client starts again. Approved logins survive. +- The request arrives from another machine on the network, or MCPProxy is the server edition: browser login answers "not found". +- The name a client sends once connected differs from what its row expects: an advisory warning on the row, nothing blocked. +- Downgrade to a release without the feature: API-key clients keep their correct profile; the docs tell the user to turn `require_mcp_auth` on first so browser-login clients do not become anonymous callers. + +## Requirements *(mandatory)* + +### Functional Requirements + +**Default off, nothing changes** + +- **FR-001**: Browser login MUST be off by default and controlled by one setting (config, environment variable, Settings switch marked "Experimental"). Turning it on or off MUST NOT need a restart. +- **FR-002**: While the feature is off and was never used, every address and document it would serve MUST answer as in the previous release, no stored data may be created for it, and no surface other than the Settings switch may mention it. This MUST be pinned by a test that compares against the previous behaviour. +- **FR-003**: API keys, client credentials and agent tokens MUST keep working unchanged whether the feature is on or off. + +**Login flow** + +- **FR-004**: With the feature on, a client given only an address MUST be able to complete the MCP authorization flow: discovery, self-registration, authorization with proof of possession, and renewal without the browser. The protocol shapes are those in design.md "Flow" and "Metadata". +- **FR-005**: Only public clients are accepted. A registration asking for a client secret or another kind of grant MUST be refused. +- **FR-006**: Return addresses MUST be loopback addresses or secure web addresses, matched exactly apart from the loopback port. +- **FR-007**: A login MUST be bound to the exact address and origin it was approved for. It MUST be refused on any other address or origin, and a different target presented at exchange or renewal MUST be refused. +- **FR-008**: The client's own round-trip value MUST be returned unchanged on both the approve and the deny answer. +- **FR-009**: Renewal MUST replace the renewal credential every time. Reuse of a genuine, already used renewal credential MUST revoke that login. A malformed, forged or unknown one MUST get one indistinguishable refusal and MUST change nothing. +- **FR-010**: Version 1 MUST serve browser login only to requests from the same machine, and MUST answer "not found" in the server edition. +- **FR-011**: Registration, authorization and exchange MUST be rate limited and size limited; never-approved registrations MUST be capped and expire (limits in design.md "Limits and abuse"). + +**Which client it is** + +- **FR-012**: A per-client address MUST identify the client. On such a request the consent page MUST show that client as fixed. +- **FR-013**: On the generic address the user MUST choose "New client" or an existing client. No existing client may be pre-selected. +- **FR-014**: The name an app reports about itself MUST be shown as unverified and MUST NOT select a client, a profile or any access. It may pre-fill the name field of a new client. +- **FR-015**: A per-client address whose id is neither a supported client nor an existing custom client MUST answer "not found" at every step. Typing an address MUST NOT create a client. +- **FR-016**: When the same registration signs in again, the page MUST say so and offer to replace its earlier login. Otherwise a new login is added beside existing ones. + +**Consent** + +- **FR-017**: Every login MUST be approved by the administrator on the consent page, every time, including a repeat login. No login may be approved silently or from the command line in version 1. +- **FR-018**: The consent page MUST show: the client, the reported name as unverified, where the browser returns to, the profile, and a sentence stating whose access the app receives. +- **FR-019**: For a client with no binding: with no profiles configured the access is "All servers"; with profiles configured the user MUST pick one and none is pre-selected. A named profile defaults to locked. +- **FR-020**: A sign-in request MUST be decided at most once (approved, denied, expired or cancelled) and MUST yield at most one login. +- **FR-021**: Approval MUST be refused, with a request to review again, when the client's binding differs from what the page displayed. +- **FR-022**: Approval that would create a binding a client can escape while `require_mcp_auth` is off MUST be refused by the existing binding guard, and the page MUST show that refusal and the guard's fixes before the user approves. +- **FR-023**: In a browser without the admin key the page MUST reveal nothing about the request and MUST offer: open from the tray, or paste the API key. The macOS tray MUST announce a pending request and open it. (The Windows/Linux tray follows in a later change.) +- **FR-024**: The consent page MUST NOT be embeddable in another page, and approval MUST NOT be possible by a cross-site request. + +**One client, one binding** + +- **FR-025**: A client MUST be one row in the Clients hub with at most one API key and any number of browser logins. +- **FR-026**: A client MUST have exactly one profile binding, used by all its credentials and changed in one place. Reassign, rename, profile deletion rules and the binding guard MUST treat a client that has only browser logins exactly like one with an API key. +- **FR-027**: A browser-login request MUST be authorized, scoped and attributed exactly like the same client's API-key request, with the credential kind and the login recorded so two logins can be told apart. +- **FR-028**: A downgrade to an earlier release MUST NOT give an API-key client a broader profile than its current one. + +**Manage** + +- **FR-029**: The Clients hub, the REST API, the CLI and the `credentials` administrator tool MUST list a client's browser logins (no secrets) and revoke them. None of them may create a login. +- **FR-030**: Revoking a client MUST revoke its API key and all its logins. Revoking a single credential MUST leave the client's others working. Forgetting a client MUST delete its logins. +- **FR-031**: Revocation MUST take effect on the next request, including on an open session. +- **FR-032**: A login MUST lapse after 30 days without use. +- **FR-033**: Issue, approve, deny, replay-revocation and revoke MUST each produce an activity record naming the acting administrator. + +**Turn off** + +- **FR-034**: Once any login has ever been stored, turning the feature off MUST make browser-login addresses refuse requests instead of serving them as anonymous, MUST cancel pending requests, and MUST keep logins and bindings so that turning it on restores them. "Ever used" MUST survive forgetting every client and restarts. + +**Connect and docs** + +- **FR-035**: While the feature is on, Connect MUST offer "API key" (default) and "Sign in with browser" for clients marked as supporting it, with the existing preview and backup notice. The browser option MUST write only the client's own address. +- **FR-036**: Documentation MUST cover: enabling, the two kinds of address, the consent page, managing logins, turning off, downgrade, and the fact that version 1 serves plain HTTP on the local machine unless local TLS is on, with the list of clients verified to work. + +### Key Entities + +- **Client**: the identity in the Clients hub. Has one profile binding and its credentials. +- **Registration**: what an app declared about itself when it registered: reported name, return addresses, state. +- **Sign-in request**: one pending approval. Short-lived, decided once. +- **Browser login (grant)**: one approved login of one registration for one client and one address. Can be revoked; lapses when unused. +- **Binding**: the profile and mode (locked or switchable) of a client, shared by all its credentials. +- **Ever-used marker**: remembers that browser login has been used on this installation. + +## Success Criteria *(mandatory)* + +### Measurable Outcomes + +- **SC-001**: With the feature at its default, 100% of the existing test suites pass unchanged and the comparison against the previous release shows no difference on any address. +- **SC-002**: A user connects a supported client by browser login in under one minute and with one click on the consent page when the client already has a profile. +- **SC-003**: No secret is written to a client's config file in the browser-login path. +- **SC-004**: In every tested flow the client shown on the consent page is the one named by the address, or the one the user chose. Zero cases depend on the reported name. +- **SC-005**: Each client on the supported list completes the whole flow, including renewal, in a recorded real-client check before that client is offered in Connect: at least Claude Code, Cursor, VS Code and MCP Inspector are attempted, and only those that pass are listed. +- **SC-006**: A revoked login is refused on its next request in 100% of tested cases, including on an open session. +- **SC-007**: After the feature was used and turned off, zero requests to a browser-login address are served. +- **SC-008**: Every abuse case in the edge-case list (double approval, changed binding, replayed renewal, forged renewal, wrong address, wrong origin, remote request) has an automated test that passes. + +## Assumptions + +- Personal edition only. Server edition and the tunnel are later work and reuse these parts. +- The administrator is whoever holds the admin API key in the browser or opens the request from the tray. There is no separate user login in the personal edition. +- Token lifetimes (one hour for access, 30 days sliding for renewal) and the numeric limits are as in design.md and may be tuned during planning without changing this spec. +- MCP clients follow discovery for an address below the MCP root. SC-005 verifies this per client before the client is offered. +- No new dependencies. + +## Out of Scope + +- Replacing or deprecating API keys and agent tokens. +- Browser login on the existing MCP addresses or routing-mode addresses. +- Clients with secrets, hosted client identity documents, approval from the CLI, custom-scheme return addresses. +- Server edition behaviour, the tunnel, the Windows/Linux tray notification (tracked as a follow-up change). + +## Commit Message Conventions *(mandatory)* + +When committing changes for this feature, follow these guidelines: + +### Issue References +- ✅ **Use**: `Related #1971` - Links the commit to the issue without auto-closing +- ❌ **Do NOT use**: `Fixes #1971`, `Closes #1971`, `Resolves #1971` - These auto-close issues on merge + +**Rationale**: Issues should only be closed manually after verification and testing in production, not automatically on merge. + +### Co-Authorship +- ❌ **Do NOT include**: `Co-Authored-By: Claude ` +- ❌ **Do NOT include**: "🤖 Generated with [Claude Code](https://claude.com/claude-code)" + +**Rationale**: Commit authorship should reflect the human contributors, not the AI tools used. + +### Example Commit Message +``` +feat(oauth): browser login for MCP clients, backend (Spec 131 PR-1) + +Related #1971 + +Opt-in authorization server for the MCP endpoint, off by default. + +## Changes +- Discovery, registration, authorization and exchange endpoints +- Per-client and generic browser-login addresses + +## Testing +- Default-off comparison against the previous release +- Scripted public client end to end +``` From e063c092eaea04618f9cf1c5e9e884ed8e9f6e55 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sun, 22 Nov 2026 16:37:33 +0200 Subject: [PATCH 06/15] docs(spec): plan, research, data model and contracts for spec 131 Related #1971 --- .../contracts/oauth-endpoints.md | 100 ++++++++++++ .../contracts/rest-admin.md | 103 ++++++++++++ specs/131-client-oauth-login/data-model.md | 93 +++++++++++ specs/131-client-oauth-login/design.md | 4 +- specs/131-client-oauth-login/plan.md | 150 ++++++++++++++++++ specs/131-client-oauth-login/quickstart.md | 53 +++++++ specs/131-client-oauth-login/research.md | 80 ++++++++++ 7 files changed, 581 insertions(+), 2 deletions(-) create mode 100644 specs/131-client-oauth-login/contracts/oauth-endpoints.md create mode 100644 specs/131-client-oauth-login/contracts/rest-admin.md create mode 100644 specs/131-client-oauth-login/data-model.md create mode 100644 specs/131-client-oauth-login/plan.md create mode 100644 specs/131-client-oauth-login/quickstart.md create mode 100644 specs/131-client-oauth-login/research.md diff --git a/specs/131-client-oauth-login/contracts/oauth-endpoints.md b/specs/131-client-oauth-login/contracts/oauth-endpoints.md new file mode 100644 index 000000000..fbd88614f --- /dev/null +++ b/specs/131-client-oauth-login/contracts/oauth-endpoints.md @@ -0,0 +1,100 @@ +# Contract: public OAuth endpoints + +`` is the scheme and host of the request. All endpoints below answer only when the feature is on, the peer and the Host are loopback, and the build is the personal edition. Otherwise see "Gate". + +## Gate + +| Feature | Ever used | `/mcp/oauth*` | `/oauth/*`, `/.well-known/oauth-*` | +|---|---|---|---| +| off | no | previous behaviour (the `/mcp/` catch-all) | previous behaviour (the root handler) | +| off | yes | `404` | `404` | +| on | any | served | served | + +Non-loopback peer or Host, or server edition, with the feature on: `404`. + +## Protected resource + +`ANY /mcp/oauth` and `ANY /mcp/oauth/{client}` — the MCP endpoint, same surface as `/mcp`. + +- No or invalid bearer token → `401`, `WWW-Authenticate: Bearer resource_metadata="/.well-known/oauth-protected-resource/mcp/oauth[/{client}]"`. +- `{client}` not a known client id → `404` (also on its metadata). +- Accepts only `Authorization: Bearer mcp_oat_…`. `X-API-Key`, `?apikey=`, `mcp_cli_`, `mcp_agt_` and the admin key → `401`. +- Token for another resource or origin → `401`. + +## `GET /.well-known/oauth-protected-resource/mcp/oauth[/{client}]` + +```json +{ + "resource": "/mcp/oauth/cursor", + "authorization_servers": [""], + "bearer_methods_supported": ["header"] +} +``` + +## `GET /.well-known/oauth-authorization-server` + +```json +{ + "issuer": "", + "authorization_endpoint": "/oauth/authorize", + "token_endpoint": "/oauth/token", + "registration_endpoint": "/oauth/register", + "response_types_supported": ["code"], + "grant_types_supported": ["authorization_code", "refresh_token"], + "code_challenge_methods_supported": ["S256"], + "token_endpoint_auth_methods_supported": ["none"] +} +``` + +## `POST /oauth/register` (RFC 7591) + +Request (JSON, at most 16 KiB): `redirect_uris` (required), `client_name`, `software_id`, `software_version`, optional `token_endpoint_auth_method`, `grant_types`, `response_types`. + +- `201`: `client_id`, `client_id_issued_at`, `redirect_uris`, `client_name` (sanitised), `token_endpoint_auth_method: "none"`, `grant_types: ["authorization_code","refresh_token"]`, `response_types: ["code"]`. No `client_secret`. +- `400 invalid_redirect_uri`: not loopback `http` and not `https`, has a fragment, more than 5. +- `400 invalid_client_metadata`: an auth method other than `none`, a grant type or response type outside the lists above. +- `429` with `Retry-After`. + +## `GET /oauth/authorize` + +Query: `response_type=code`, `client_id`, `redirect_uri`, `code_challenge`, `code_challenge_method=S256`, `resource`, `state` (optional), `scope` (ignored). + +- Unknown `client_id` or `redirect_uri` not registered (loopback port ignored) → `400` HTML error page, **no redirect**. +- Other errors → redirect to `redirect_uri` with `error` (`invalid_request`, `unsupported_response_type`, `invalid_target`, `temporarily_unavailable`) and `state`. +- `resource` must be `/mcp/oauth` or `/mcp/oauth/{known client}`, else `invalid_target`. +- Success → `302` to `/ui/authorize?request=`. Headers on every answer: `Cache-Control: no-store`, `Referrer-Policy: no-referrer`. + +After the administrator decides (admin REST), the browser is sent to: + +- approve: `redirect_uri?code=&state=` +- deny: `redirect_uri?error=access_denied&state=` + +## `POST /oauth/token` + +Form-encoded, at most 16 KiB. Answers carry `Cache-Control: no-store`. + +**`grant_type=authorization_code`**: `code`, `redirect_uri`, `client_id`, `code_verifier`, `resource` (optional; if present must equal the approved one). + +**`grant_type=refresh_token`**: `refresh_token`, `client_id`, `resource` (optional, same rule). + +`200`: + +```json +{ "access_token": "mcp_oat_…", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "mcp_ort_…" } +``` + +Errors (`400` JSON `{error, error_description}`): + +| Case | `error` | Side effect | +|---|---|---| +| unknown, expired or already used code; wrong verifier, client or redirect URI | `invalid_grant` | a reused code revokes the grant it produced | +| refresh token malformed, bad MAC, unknown or revoked grant, wrong `client_id` | `invalid_grant` | **none**; all indistinguishable | +| authentic refresh token that is not the current one | `invalid_grant` | grant revoked (`replay`) | +| `resource` differs from the approved one | `invalid_target` | none | +| other grant type | `unsupported_grant_type` | none | +| over the rate limit | `429` + `Retry-After` | none | + +## Token formats + +- Access: `mcp_oat_<43 base64url chars>`; lifetime 3600 s. +- Refresh: `mcp_ort___`; lifetime 30 days from last rotation. diff --git a/specs/131-client-oauth-login/contracts/rest-admin.md b/specs/131-client-oauth-login/contracts/rest-admin.md new file mode 100644 index 000000000..ecad36aac --- /dev/null +++ b/specs/131-client-oauth-login/contracts/rest-admin.md @@ -0,0 +1,103 @@ +# Contract: administrator surfaces + +All REST routes are under `/api/v1`, use the standard `{success, data}` envelope, require administrator credentials (admin API key or tray socket) and answer `403` to agent tokens and client credentials. With the feature off they answer `404 feature_disabled`, except the grant listing fields on `/clients`, which are simply empty. + +## Sign-in requests + +### `GET /oauth/authorizations` + +Pending requests, newest first: `[{id, client_label, created_at, expires_at}]`. Used by the tray and by Home. + +### `GET /oauth/authorizations/{id}` + +```jsonc +{ + "id": "…", + "status": "pending", + "expires_at": "…", + "reported_name": "Cursor IDE", // unverified, sanitised + "redirect_uri": "http://127.0.0.1:54321/callback", + "resource": "http://127.0.0.1:8080/mcp/oauth/cursor", + "address_kind": "client", // "client" | "generic" + "client": { // present when address_kind = client + "id": "cursor", "display_name": "Cursor", "exists": true, + "has_api_key": true, "logins": 1, + "binding": { "profile": "dev-readonly", "mode": "locked", "revision": "b1f3…" } + }, + "existing_clients": [ /* address_kind = generic: {id, display_name, binding} */ ], + "suggested_new_client": { "id": "acme-agent", "display_name": "Acme Agent" }, + "profiles": [ { "name": "dev-readonly" } ], + "profile_required": true, // profiles exist and the client has no binding + "previous_login": { "grant_id": "…", "approved_at": "…" }, // same registration signed in before + "guard": null // or { "code": "binding_bypassable_without_auth", "bindings": [...], "fixes": [...] } +} +``` + +`404` for an unknown, expired, decided or cancelled id (one uniform answer). + +### `POST /oauth/authorizations/{id}/approve` + +```jsonc +{ + "client": { "id": "cursor" }, // generic address: existing id, or + // "client": { "new": { "id": "acme-agent", "display_name": "Acme Agent" } }, + "profile": "dev-readonly", // "" = All servers; ignored when the client has a binding + "mode": "locked", + "binding_revision": "b1f3…", // required when the client has a binding + "replace_grant": "…" // optional: the previous_login grant id +} +``` + +- `200 {redirect_url}`: the page navigates there. +- `409 already_decided`. +- `409 binding_changed`: the binding differs from `binding_revision`; reload. +- `409 binding_bypassable_without_auth`: body as the existing guard refusal. +- `422 profile_required`, `422 client_fixed` (a client other than the one in the address), `422 identity_exists` / `reserved_identity` for a new client id, `404 profile_not_found`. + +### `POST /oauth/authorizations/{id}/deny` + +`200 {redirect_url}` (carries `error=access_denied`). `409 already_decided`. + +## Logins on clients + +- `GET /clients` and `GET /clients/{client}`: each client gains + + ```jsonc + "credentials": [ + { "kind": "api_key", "prefix": "mcp_cli_ab12", "state": "active", "expires_at": "…", "last_used_at": "…" }, + { "kind": "browser_login", "grant_id": "…", "state": "active", // active | lapsed | revoked + "approved_at": "…", "last_used_at": "…", "reported_name": "Cursor IDE", "redirect_host": "127.0.0.1" } + ], + "browser_login_disabled": false + ``` + +- `DELETE /clients/{client}/logins/{grant_id}`: revoke one login. `200 {changed}`; `404` unknown. +- `DELETE /clients/{client}/api-key`: revoke the API key alone; the client's logins and binding stay. `404` when the client has no API key. +- Existing `DELETE /clients/{client}` (forget) and the revoke path: cascade to all logins. +- `PUT /clients/{client}/binding`, `POST /clients/bulk-assign`: work for clients that have only browser logins. + +## SSE (admin-only) + +- `oauth.authorization_pending` `{request_id, client_id, client_label}` +- `oauth.authorization_decided` `{request_id, status}` +- `credentials.changed` (existing) with `kind: "browser_login"`, `change: issue | revoke | replay_revoke` + +## Activity + +`profile_change` rows with `change` = `approve` | `deny` | `revoke` | `replay_revoke`, metadata `client_id`, `grant_id`, `profile`, `actor_kind`, `actor_name`, `surface`. Tool-call rows of a browser login carry `client_id` and `metadata.grant_id`, credential kind `oauth`. + +## MCP `credentials` tool + +- `list` (`kind` gains `browser_login`), `get client=`: include logins with the fields above. +- `revoke client=`: everything under the client. `revoke client= grant=`: one login. +- No operation creates a login. + +## CLI + +- `mcpproxy client show `: lists credentials. +- `mcpproxy client revoke-login `. +- `mcpproxy connect --auth key|oauth` (PR-3); `oauth` is refused with a clear message when the feature is off or the client is not marked as supporting it. + +## Config + +`mcp_oauth_enabled` (bool, default false, hot), env `MCPPROXY_MCP_OAUTH_ENABLED`. diff --git a/specs/131-client-oauth-login/data-model.md b/specs/131-client-oauth-login/data-model.md new file mode 100644 index 000000000..ca71c6bce --- /dev/null +++ b/specs/131-client-oauth-login/data-model.md @@ -0,0 +1,93 @@ +# Data Model: Browser login for MCP clients + +All persistent records live in `config.db` in buckets created on first write. Nothing is created while the feature is off. + +## Registration — bucket `oauth_registrations`, key `client_id` + +| Field | Type | Rule | +|---|---|---| +| `client_id` | string | 22 random base62 chars, server-generated | +| `reported_name` | string | `client_name` after `clientidentity.SanitizeDisplay`, at most 128 bytes; display only | +| `redirect_uris` | []string | 1 to 5; each loopback `http` or `https`; no fragment | +| `software_id`, `software_version` | string | optional, sanitised, display only | +| `token_endpoint_auth_method` | string | always `none` | +| `grant_types` | []string | always `authorization_code`, `refresh_token` | +| `state` | enum | `pending` → `authorized` → `approved`; or `denied` | +| `created_at`, `authorized_at` | time | | + +Lifecycle: `pending` rows are deleted 15 minutes after creation, `authorized` (reached `/oauth/authorize`, never approved) after 24 hours. At most 50 non-approved rows; the oldest is dropped. An `approved` row lives while at least one grant references it. + +## Grant (browser login) — bucket `oauth_grants`, key `grant_id` + +| Field | Type | Rule | +|---|---|---| +| `grant_id` | string | 22 random base62 chars | +| `registration_id` | string | the `client_id` above | +| `client` | string | Clients hub client id; passes `auth.ValidClientID` | +| `resource` | string | full URI approved, immutable | +| `issuer` | string | origin approved, immutable | +| `refresh_hash`, `refresh_prefix` | string | HMAC-SHA256 of the current refresh secret; first 12 chars of the token | +| `access_hash`, `access_expires_at` | string, time | the one live access token | +| `refresh_expires_at` | time | now + 30 days on every rotation | +| `approved_at`, `approved_by` | time, actor | | +| `last_used_at` | time | updated like agent tokens, off the request path | +| `revoked`, `revoked_at`, `revoke_reason` | bool, time, enum | `admin`, `client_revoked`, `replaced`, `replay` | +| `user_id` | string | empty in the personal edition | + +Sub-bucket `by_access_hash`: `access_hash → grant_id`. + +State: `live` (not revoked, `refresh_expires_at` in the future) → `lapsed` (refresh expired) or `revoked`. Neither comes back. A lapsed or revoked grant is kept for display for 30 days, then deleted. + +## Client binding for browser logins — bucket `oauth_client_bindings`, key client id + +| Field | Type | Rule | +|---|---|---| +| `profile_pin` | string | profile name, or empty for All servers | +| `profile_mode` | enum | `locked` requires a non-empty pin; All servers is `switchable` | +| `display_name` | string | for a custom client created at consent, at most 64 runes | +| `updated_at` | time | | + +Invariants: + +- Exists exactly for clients that have at least one grant record. +- If the client also has an API-key record, `profile_pin` and `profile_mode` equal that record's `ProfilePin` and `ProfileMode`. One storage function writes both in one transaction. On startup a mismatch is repaired from the API-key record and logged. +- **Binding revision**: `sha256(client | pin | mode)` truncated, computed on read; the consent page sends back the revision it displayed. + +## Ever-used marker — `MetaBucket` key `oauth_login_ever_used` + +RFC 3339 time of the first stored grant. Written in the same transaction as that grant. Never deleted. + +## Authorization request — memory only + +| Field | Rule | +|---|---| +| `id` | 22 random base62 chars; appears in the consent URL | +| `registration_id`, `redirect_uri`, `state`, `code_challenge` | validated at `/oauth/authorize`; stored verbatim | +| `resource`, `issuer`, `path_client` | `path_client` is the client id from the resource path, empty for the generic address | +| `status` | `pending` → `approved` \| `denied` \| `expired` \| `cancelled`; one transition, compare-and-set | +| `expires_at` | created + 10 minutes | + +At most 20 pending requests; a new one beyond that is refused with `temporarily_unavailable`. + +## Authorization code — memory only + +`code` (32 random bytes, stored hashed), bound to request id, registration, redirect URI, challenge, resource, chosen client and the decision. Single use, 60 seconds. A second use revokes the grant created from the first. + +## Relationships + +```text +Client (Clients hub id) + ├─ 0..1 API key agent_tokens (Kind=client) holds ProfilePin/ProfileMode + ├─ 0..1 binding copy oauth_client_bindings equal to the above when both exist + └─ 0..n Grant oauth_grants ──► Registration oauth_registrations +``` + +## Derived views + +- **Credential list of a client** (Clients hub, REST, `credentials get`): the API key if any, then grants ordered by `approved_at` descending, each with state, prefix, `approved_at`, `last_used_at`, reported name, redirect host. Never a secret or a hash. +- **Active named binding** (guard, `profile_in_use`): a client with a named pin and either a live API key or a live grant. +- **Client state** on the hub gains `browser_login_disabled` when the client has grants and the feature is off. + +## Auth context of a browser-login request + +`Type=agent`, `TokenKind=client`, `ClientID=`, `ProfilePin`, `ProfileMode` from the binding, `CredentialKind=oauth`, `AllowedServers=["*"]`, all three permission tiers. Built by the same helper as the `mcp_cli_` path. diff --git a/specs/131-client-oauth-login/design.md b/specs/131-client-oauth-login/design.md index 7a22b0d6c..e7ec94ff7 100644 --- a/specs/131-client-oauth-login/design.md +++ b/specs/131-client-oauth-login/design.md @@ -160,7 +160,7 @@ Activity rows gain the credential kind `oauth` and the grant id, so two logins o - The resource and the issuer are built from the **origin of the request**, after the existing host validation (loopback names and `trusted_hosts`). `http://127.0.0.1:8080` and `http://localhost:8080` are two resources; a client stays on the one it was configured with. The metadata documents, the `resource` check at authorize and the audience of a token all use that origin, and a token is refused on any other. - The consent redirect stays on the same origin. If the browser holds the admin key under another origin, the page takes the "no admin key" path and the tray opens the request on the right origin. - Version 1 serves `/mcp/oauth`, `/oauth/*` and the metadata only to requests that arrive from a loopback address with a loopback host. Anything else gets 404, so a LAN listen exposes no open registration. The tunnel lifts this later under its own rules. -- `/mcp/oauth` and `/mcp/oauth/` serve the same tool surface as `/mcp` (they follow `routing_mode`). While the feature is on they are registered ahead of the `/mcp/` catch-all. While it is off they are not registered at all, so these paths keep falling into the catch-all exactly as today. +- `/mcp/oauth` and `/mcp/oauth/` serve the same tool surface as `/mcp` (they follow `routing_mode`). The HTTP mux is built once and cannot drop routes, so the new patterns are always registered and decide per request (the pattern `/mcp/s/` and `enable_skills` already use). While the feature is off and was never used, each new pattern hands the request to the handler that answered it before this feature: the `/mcp/` catch-all for `/mcp/oauth*`, the root handler for `/oauth/*` and `/.well-known/oauth-*`. A test compares the answers with those of the unwrapped handlers. - Server edition: the feature answers 404 in version 1 whatever the setting, because consent by admin API key would create grants with no user. ### Revoke and forget @@ -198,7 +198,7 @@ The registry gains a flag for clients known to support the MCP authorization flo `mcp_oauth_enabled`, default **off**, env `MCPPROXY_MCP_OAUTH_ENABLED`, also a switch on the Settings page marked "Experimental". No restart is needed: routes are added and removed on config reload. -- **Off (default)**: no new route, no metadata document, no new bucket is created, no Connect option, no Clients hub column, no startup notice. Existing API keys, agent tokens, client credentials, `/mcp` and every routing-mode endpoint are untouched. A test pins this: the route table and the answers on `/mcp/oauth*`, `/oauth/*` and `/.well-known/oauth-*` with the feature off equal those of the previous release. +- **Off (default)**: no new behaviour on any route, no metadata document, no new bucket is created, no Connect option, no Clients hub column, no startup notice. Existing API keys, agent tokens, client credentials, `/mcp` and every routing-mode endpoint are untouched. A test pins this: the route table and the answers on `/mcp/oauth*`, `/oauth/*` and `/.well-known/oauth-*` with the feature off equal those of the previous release. - **On**: everything in this document. API keys keep working next to it. - **Turned off again**: two cases, told apart by a persistent marker `oauth_ever_used`. It is written in the transaction that stores the first grant and is never cleared, not by revoke, forget or cleanup, so forgetting the last browser-login client does not bring the catch-all back. - Never used (marker absent): identical to "off" above, including the legacy catch-all on `/mcp/oauth*`. Storing the marker is the only write the feature makes outside its own buckets. diff --git a/specs/131-client-oauth-login/plan.md b/specs/131-client-oauth-login/plan.md new file mode 100644 index 000000000..872b7a66b --- /dev/null +++ b/specs/131-client-oauth-login/plan.md @@ -0,0 +1,150 @@ +# Implementation Plan: Browser login for MCP clients (opt-in OAuth) + +**Branch**: `claude/oauth-api-key-client-role-eb4179` (spec) | **Date**: 2026-11-22 | **Spec**: [spec.md](./spec.md) +**Input**: [spec.md](./spec.md) and the approved, cross-reviewed [design.md](./design.md) + +## Summary + +MCPProxy becomes an optional OAuth 2.1 authorization server for its own MCP endpoint. A client given only `/mcp/oauth/` (or the generic `/mcp/oauth`) registers itself, the administrator approves on a consent page, and the client gets short-lived tokens. The address fixes which client it is; nothing is inferred from the reported name. A browser login is one more credential under an existing Clients hub row and uses that client's single profile binding. The feature is off by default and, until first used, leaves every existing answer unchanged. + +Technical approach: one new stdlib-only leaf package for the protocol logic, lazy bbolt buckets in `internal/storage`, one runtime service next to `ClientsService`, HTTP handlers registered once and gated per request, a small extension of `mcpAuthMiddleware`, then the UI and Connect surfaces. + +## Technical Context + +**Language/Version**: Go 1.26 (backend), TypeScript 5.9 / Vue 3.5 (Web UI), Swift 5.9 (macOS tray) +**Primary Dependencies**: standard library only for the new code (`crypto/hmac`, `crypto/sha256`, `crypto/rand`, `net/http`, `net/netip`); existing chi router, bbolt, zap. **No new dependencies.** +**Storage**: bbolt `config.db`. New lazy buckets `oauth_registrations`, `oauth_grants`, `oauth_client_bindings`; marker `oauth_login_ever_used` in `MetaBucket`. Authorization requests and codes are memory only. +**Testing**: `go test -race` unit and integration tests, `scripts/test-client-oauth-e2e.sh`, vitest for the consent page and Clients hub, Playwright sweep for touched views, the macOS tray via `mcpproxy-ui-test`. +**Target Platform**: personal edition on macOS, Windows, Linux. Server edition answers 404. +**Project Type**: web application (Go backend + Vue frontend + native tray) +**Performance Goals**: access-token validation adds one HMAC and one bbolt read per MCP request, the same cost as a client credential today. +**Constraints**: default-off equivalence with the previous release (FR-002); loopback only (FR-010); no secret in client configs (SC-003); downgrade never widens an API-key client (FR-028). +**Scale/Scope**: tens of clients, a few logins each; at most 50 pending registrations. + +## Constitution Check + +| Principle | Status | Note | +|---|---|---| +| I. Performance at Scale | Pass | No change to search, indexing or routing. Token check is O(1). | +| II. Actor-Based Concurrency | Pass with note | Writes go through the existing `bindingWriteMu` that `ClientsService` and `CredentialsService` already share. The in-memory request/code store uses one mutex (short critical sections, no I/O). See Complexity Tracking. | +| III. Configuration-Driven | Pass | One config field, env override, hot reload without restart. | +| IV. Security by Default | Pass | Off by default, loopback only, consent every time, binding guard extended to cover logins, no weakening of API-key auth. | +| V. TDD | Pass | Every task starts with a failing test; default-off equivalence test is written first. | +| VI. Documentation Hygiene | Pass | New feature page, updates to connect, profiles, REST and config references, CLAUDE.md entry written by hand. | + +Re-check after Phase 1: unchanged. + +## Project Structure + +### Documentation (this feature) + +```text +specs/131-client-oauth-login/ +├── design.md # approved design (decisions, alternatives) +├── spec.md +├── plan.md # this file +├── research.md +├── data-model.md +├── quickstart.md +├── contracts/ +│ ├── oauth-endpoints.md # public protocol surface +│ └── rest-admin.md # admin REST, SSE, CLI, MCP tool +├── checklists/requirements.md +└── tasks.md +``` + +### Source Code (repository root) + +```text +internal/mcplogin/ # NEW leaf, stdlib only: pure protocol logic + token.go # mcp_oat_/mcp_ort_ formats, MAC, parse, hash + pkce.go # S256 verify + redirect.go # redirect URI rules (loopback any port, https exact) + metadata.go # RFC 9728 / RFC 8414 documents for an origin + path + registration.go # RFC 7591 request validation, effective values + resource.go # origin + path -> resource URI, client id from path + requests.go # in-memory authorization requests and codes, decided once + limits.go # per-key limiter wrapper (limiter.TokenRates), caps + +internal/storage/ + oauth_login.go # buckets, registration/grant CRUD, rotate-or-revoke tx, + # ever-used marker, forget-client purge + client_credentials.go # UpdateClientCredentialBinding also writes oauth_client_bindings (one tx) + +internal/auth/ + context.go # CredentialKindOAuth + agent_token.go # helper building the client AuthContext from (clientID, pin, mode) + +internal/runtime/ + oauth_login_service.go # OAuthLoginService: suggest, approve, deny, exchange, refresh, revoke, list + clients_service.go # one binding writer covers OAuth-only clients; Forget/Revoke cascade + credentials_service.go # list/get/revoke grants + binding_guard.go # active binding includes clients with live grants + events.go # oauth.authorization_pending + +internal/server/ + oauth_login_routes.go # always-registered, per-request gated handlers + oauth_login_http.go # /oauth/register|authorize|token, /.well-known/* + server.go # mcpAuthMiddleware: mcp_oat_ branch; route registration + profile_binding_guard.go# guard evaluator reads OAuth bindings + +internal/httpapi/ + oauth_login.go # /api/v1/oauth/authorizations*, grants under /clients +internal/config/ # mcp_oauth_enabled: struct, default, env, hot reload, swagger +internal/connect/ # SupportsBrowserLogin flag, URL-only entry +cmd/mcpproxy/ # connect --auth, client logins / revoke-login + +frontend/src/views/AuthorizeRequest.vue # consent page (/ui/authorize) +frontend/src/components/clients/ClientCredentials.vue +frontend/src/views/settings/fields.ts # switch + "Experimental" badge +native/macos/MCPProxy/MCPProxy/ # SSE case, notification, menu item + +scripts/test-client-oauth-e2e.sh +tests/oauthclient/ # scripted public client used by e2e +docs/features/client-oauth-login.md +``` + +**Structure Decision**: follow the existing split. Protocol logic that needs no runtime lives in a leaf package so it can be unit-tested and reused by the tunnel (Spec 089). Everything stateful sits where its neighbours already are: storage in `internal/storage`, the service next to `ClientsService`, HTTP in `internal/server`, admin REST in `internal/httpapi`. + +## Delivery + +Three PRs, each merged before the next starts. + +| PR | Contents | User stories | +|---|---|---| +| **PR-1 backend** | config switch and default-off equivalence; `internal/mcplogin`; storage; service; public endpoints; `mcp_oat_` authentication; single binding and guard; admin REST for requests; activity; limits; e2e script; real-client check | US1, US2 (via REST), US3 (backend), US7 | +| **PR-2 surfaces** | consent page; "no key" path; macOS tray notification; Clients hub credentials; `credentials` tool, REST and CLI list/revoke | US2, US3, US4, US5 | +| **PR-3 Connect and docs** | registry flag; Connect choice (Web UI, CLI); docs; CLAUDE.md entry | US6 | + +PR-2b (Go tray notification for Windows/Linux) is a follow-up outside this plan. + +## Key decisions taken in planning + +Full reasoning is in [research.md](./research.md). + +1. **Routes are always registered and gated per request.** `http.ServeMux` cannot drop a pattern, and the mux is built once (`startCustomHTTPServer`). Each new pattern wraps the handler that answered that path before: the default `mcpHandler` for `/mcp/oauth*`, the root handler for `/oauth/*` and `/.well-known/oauth-*`. Off and never used: delegate. Off and used: 404. On: serve. +2. **Authenticate into the existing client context.** A valid `mcp_oat_` token yields the same `AuthContext` as that client's `mcp_cli_` credential (agent type, `TokenKind=client`, `ClientID`, pin, mode), with `CredentialKind=oauth`. Every `CredentialKind` switch is audited by a test. +3. **Binding storage.** The API-key record keeps `ProfilePin`/`ProfileMode`. `oauth_client_bindings` holds the binding for clients with grants. `storage.UpdateClientCredentialBinding` becomes the one write path and updates both in one bbolt transaction. +4. **Guard.** `BindingGuardActiveBindings` and `ActiveNamedBinding` gain a second source: clients with a live grant and a named binding. +5. **Loopback rule.** New helper `peerIsLoopback(r)` on `r.RemoteAddr`, combined with the existing `httpx.IsLoopbackHost(r.Host)`. Tray socket connections are not loopback TCP and get 404 on the public OAuth endpoints. +6. **Rate limiting.** A private `limiter.TokenRates` instance keyed by endpoint + remote address. No new dependency. +7. **Activity.** New `profile.ChangeKind` values `approve`, `deny`, `replay_revoke`; `issue` and `revoke` are reused. +8. **Settings.** `SettingField` gains an optional `badge` ("Experimental"); mirrored in the macOS settings catalogue. + +## Verification + +- `go test -race ./internal/mcplogin/... ./internal/storage/... ./internal/runtime/... ./internal/server/... ./internal/httpapi/...` with the CI `-skip` regex. +- Both golangci-lint runs (bare and `--build-tags server`). +- `./scripts/test-api-e2e.sh` (unchanged, proves US1) and `./scripts/test-client-oauth-e2e.sh`. +- `make swagger` and `swagger-verify`. +- Web UI: vitest + Playwright sweep report for `/ui/authorize`, `/ui/clients`, `/ui/settings`. +- macOS tray: build, swap, `mcpproxy-ui-test` for the menu item. +- Real-client check (SC-005), recorded in `specs/131-client-oauth-login/verification/`. +- Cross-model review per PR (opencode `gpt-6.1-sol`, at most 10 rounds). + +## Complexity Tracking + +| Deviation | Why needed | Simpler alternative rejected because | +|---|---|---| +| Mutex around the in-memory request/code store | "Decided once" (FR-020) is a compare-and-set on shared state with no I/O | A channel-owned actor adds a goroutine and a request/response type for five map operations; the existing services already use `bindingWriteMu` for the same reason | +| Second binding record (`oauth_client_bindings`) beside the API-key record | A client may have only browser logins, and an older binary must still read the right profile from the API-key record (FR-028) | Moving the binding to one new record breaks downgrade; a credential-less `AgentToken` record fails `ValidateTokenInvariants` on older binaries | diff --git a/specs/131-client-oauth-login/quickstart.md b/specs/131-client-oauth-login/quickstart.md new file mode 100644 index 000000000..6a3a5cc2c --- /dev/null +++ b/specs/131-client-oauth-login/quickstart.md @@ -0,0 +1,53 @@ +# Quickstart: verifying browser login + +Use a scratch data directory and a high port so the installed MCPProxy is untouched. Kill any core using the same data directory first. + +```bash +go build -o mcpproxy ./cmd/mcpproxy +``` + +## 1. Default off: nothing changed + +```bash +./scripts/test-api-e2e.sh +``` + +```bash +go test -race ./internal/server -run 'TestOAuthLogin_DefaultOff' -v +``` + +Expected: both pass; the second compares `/mcp/oauth*`, `/oauth/*` and `/.well-known/oauth-*` with the previous handlers and checks that no new bucket exists. + +## 2. The whole flow, scripted + +```bash +./scripts/test-client-oauth-e2e.sh +``` + +It starts a core with `MCPPROXY_MCP_OAUTH_ENABLED=true`, then with a scripted public client: + +1. `401` challenge and both metadata documents for `/mcp/oauth/cursor`. +2. Registration, authorize, approve through the admin REST, token exchange, `tools/list`. +3. Refresh rotation; replay of the old refresh token revokes the login; a forged token with the real grant id changes nothing. +4. Token used on `/mcp`, on `/mcp/oauth/claude-code` and on `localhost` instead of `127.0.0.1`: refused. +5. Double approve; approve after the binding changed; named profile with `require_mcp_auth` off (guard refusal). +6. Revoke one login on an open session; forget the client. +7. Feature off after use: `/mcp/oauth/cursor` is `404`; on again: the remaining login works. + +## 3. By hand + +```bash +MCPPROXY_MCP_OAUTH_ENABLED=true ./mcpproxy serve --listen 127.0.0.1:18080 --data-dir "$(mktemp -d)" +``` + +Configure a client with `http://127.0.0.1:18080/mcp/oauth/`, start it, approve on the page that opens, then check **Clients** in the Web UI. + +## 4. Real clients (SC-005) + +For Claude Code, Cursor, VS Code and MCP Inspector, record in `verification/real-clients.md`: the name it registered with, redirect URI shape, whether discovery on the per-client path, exchange and refresh worked. Only clients that pass get `SupportsBrowserLogin`. + +## 5. Surfaces (PR-2, PR-3) + +- Web UI: Playwright sweep for `/ui/authorize`, `/ui/clients`, `/ui/settings` per `docs/development/web-ui-verification.md`. +- macOS tray: start a sign-in from a browser profile without the key; the menu shows "Approve sign-in for …". +- Connect: `./mcpproxy connect cursor --auth oauth` writes only the address; the preview shows no header. diff --git a/specs/131-client-oauth-login/research.md b/specs/131-client-oauth-login/research.md new file mode 100644 index 000000000..5b188bdf8 --- /dev/null +++ b/specs/131-client-oauth-login/research.md @@ -0,0 +1,80 @@ +# Research: Browser login for MCP clients + +Code references are from `main` at `dfc3d418f`. Product decisions and their alternatives are in [design.md](./design.md); this file covers what planning had to settle against the code. + +## R1. Turning routes on and off without a restart + +- **Finding**: the outer mux is built once in `(*Server).startCustomHTTPServer` (`internal/server/server.go:3380`, mux at 3431). `http.ServeMux` has no unregister. Existing switchable features decide per request inside an always-registered handler (`/mcp/s/` in `serveSingleServer`, `/debug/pprof/`, `enable_skills` through `RefreshSkillsAvailability`). +- **Decision**: register `/mcp/oauth`, `/mcp/oauth/`, `/oauth/`, `/.well-known/oauth-protected-resource/`, `/.well-known/oauth-authorization-server` once. Each is a gate with three states read per request from config and the ever-used marker (cached, refreshed on `EventTypeConfigReloaded` and on first grant): + - off, never used → call the handler that owned the path before (`mcpHandler` for `/mcp/oauth*`; the root `/` handler for the others); + - off, used → 404; + - on → serve. +- **Rationale**: the only way to get hot reload and FR-002 together. +- **Alternatives**: restart-gated field (rejected: constitution III, and the Settings switch would need a restart); rebuilding the mux (rejected: touches every route for one feature). +- **Test**: for each new pattern and a table of methods/headers, the response of the gate (off, never used) equals the response of the unwrapped previous handler, byte for byte on status, headers of interest and body. + +## R2. Where an access token is authenticated + +- **Finding**: `(*Server).mcpAuthMiddleware` (`server.go:605`) extracts the token (636), handles `mcp_agt_`/`mcp_cli_` at 677 via `storageManager.ValidateAgentToken` and `agentToken.AuthContext()` (723), then the admin key (733). With `require_mcp_auth` off an unknown token falls to the anonymous context (756). +- **Decision**: the OAuth addresses get their own chain `hostValidation → tagMCP → oauthResourceAuth → loggingHandler(streamableServer)`. `oauthResourceAuth` accepts only `Authorization: Bearer mcp_oat_…` whose grant is live, whose resource equals the request's origin + path, and whose client matches the path. Anything else (no token, API key, `mcp_cli_`, wrong audience) → `401` with the `WWW-Authenticate` challenge. It never falls to anonymous. `mcpAuthMiddleware` on the other routes gains one branch: a `mcp_oat_` token is always `401` there (wrong audience), also when `require_mcp_auth` is off, but only while the feature is on or was used, so FR-002 holds. +- **Rationale**: audience binding (FR-007) and "no anonymous fallback" (FR-034) are properties of the OAuth addresses; keeping them out of the shared middleware keeps the default-off path untouched. + +## R3. The auth context of a browser login + +- **Finding**: `(*AgentToken).AuthContext` (`internal/auth/agent_token.go:339`) sets `Type=AuthTypeAgent`, `CredentialKind=agent_token`, `TokenKind`, `ClientID`, `ProfilePin`, `ProfileMode`. `CredentialKind` constants (`internal/auth/context.go:13-30`) have no OAuth kind. +- **Decision**: add `CredentialKindOAuth = "oauth"`. Add `auth.ClientAuthContext(clientID, pin, mode, kind)` used by both the `mcp_cli_` path and the OAuth path, so the two cannot drift. Activity gains `grant_id` in metadata. +- **Risk**: code that switches on `CredentialKind == agent_token` to mean "scoped caller". **Mitigation**: a source test lists every comparison against `CredentialKindAgentToken` and requires each to be classified as "also applies to oauth" or "API-key specific". + +## R4. One binding, two records + +- **Finding**: the binding lives on the `Kind=client` record; `storage.UpdateClientCredentialBinding(clientID, pin, mode)` (`internal/storage/client_credentials.go:233`) is called only from `ClientsService.setBindingLocked` (`internal/runtime/clients_service.go:539`). There is no index by client id (`findClientTokenRecordLocked` scans). `ValidateTokenInvariants` refuses a client record without a secret hash, expiry or with locked + empty pin. +- **Decision**: new bucket `oauth_client_bindings`, key = client id, value `{pin, mode, display_name, updated_at}`. `UpdateClientCredentialBinding` writes the API-key record if present and the OAuth record if present, in one transaction; it fails only if neither exists. `setBindingLocked` drops its "must be `CredentialStateClient`" precondition in favour of "client has an API key or a live grant". Startup check: for a client with both, the API-key record wins and the mismatch is logged at WARN. +- **Alternatives**: single new bucket for all bindings (rejected: downgrade reads the stale API-key record, FR-028); credential-less `AgentToken` (rejected: fails invariants on older binaries and pollutes token lists). + +## R5. The binding guard + +- **Finding**: `ActiveNamedBinding(t, now)` (`internal/runtime/binding_guard.go:114`) and the evaluator in `internal/server/profile_binding_guard.go` (`BindingGuardActiveBindings` at 186, `activeNamedClientBinding` at 76) read `auth.AgentToken` only. Fixes are `require_mcp_auth` and `set_anonymous_profile` (`internal/profile/contract.go:192`). +- **Decision**: the evaluator's set of active bindings becomes the union of (a) today's records and (b) clients in `oauth_client_bindings` with a named pin and at least one grant that is neither revoked nor lapsed. `BindingRef` is unchanged (it names client and profile). Approval calls `CheckBindingGuard` with the candidate binding before any write; the consent REST `GET` returns the guard's verdict and fixes so the page can show them first (FR-022). + +## R6. Refresh tokens + +- **Decision**: `mcp_ort___`; `grantID` 16 random bytes (base62), `secret` 32 random bytes, `mac = HMAC-SHA256(key, "ort|"+grantID+"|"+secret)` truncated to 16 bytes. Key: `auth.GetOrCreateHMACKey(dataDir)` (`agent_token.go:580`), the key agent tokens already use, with a distinct label so the MAC can never collide with a token hash. Stored: `HashToken(secret, key)` and a 12-character prefix. +- **Check order** (FR-009): parse and MAC → load grant → compare secret hash in constant time → rotate or revoke, in one `db.Update`. +- **Access token**: `mcp_oat_`, stored hashed in the grant (`access_hash`, `access_expires_at`); one live access token per grant. A second index bucket is not needed: the lookup key is the hash, kept in `oauth_grants` under a sub-bucket `by_access_hash → grant id`. + +## R7. Loopback only + +- **Finding**: `newHostValidationHandler` (`internal/server/host_validation.go:41`) validates `Host` and `Origin` on loopback connections and passes non-loopback connections through. No helper inspects `r.RemoteAddr`. `httpx.IsLoopbackHost` (`internal/httpx/origin.go:19`) exists. +- **Decision**: `peerIsLoopback(r)` parses `r.RemoteAddr` with `netip.ParseAddrPort` and requires `IsLoopback()`; the gate requires it together with `httpx.IsLoopbackHost(r.Host)` (a `trusted_hosts` name is not enough in version 1). Requests over the tray socket are not TCP loopback and get 404. Server edition: `config.ServerEditionEnabled(cfg)` → 404. +- **Origin**: `scheme://host` from the request (`https` when the listener is TLS), used verbatim as issuer and as the resource prefix. `127.0.0.1` and `localhost` are different origins by design. + +## R8. Rate limits and caps + +- **Finding**: no HTTP rate-limit middleware exists. `limiter.TokenRates` (`internal/upstream/limiter/token_rate.go`) is a per-key token bucket with a clock seam and idle sweep. +- **Decision**: one private `TokenRates` in `internal/mcplogin/limits.go`; keys `register|`, `authorize|`, `token|`. Defaults: register 10/min burst 5, authorize 30/min burst 10, token 60/min burst 20. `http.MaxBytesReader` 16 KiB on register and token. Pending registrations capped at 50 (oldest pending dropped). Over limit → `429` with `Retry-After`. + +## R9. Events and activity + +- **Finding**: events are published through an injected `publish func(Event)`; admin-only types are listed in `adminConfigEventTypes` (`internal/httpapi/sse_scope.go`). `writeChangeRecord` (`clients_service.go:444`) is the single `profile_change` builder; `profile.ChangeKind` has no approve/deny. +- **Decision**: new event `oauth.authorization_pending` `{request_id, client_id, client_label}` (admin-only, no reported name beyond the sanitised label) and reuse of `credentials.changed` for grant create/revoke. New change kinds `approve`, `deny`, `replay_revoke`. The actor comes from `runtime.RequestActor(ctx)`; a replay revocation is recorded with actor kind `system`. + +## R10. Storage laziness + +- **Finding**: `initBuckets` (`internal/storage/bbolt.go:160`) creates a fixed list at open; other buckets (`agent_tokens`, `tpa_bundle_state`, …) are created with `CreateBucketIfNotExists` in the write path and readers treat a nil bucket as empty. Markers live in `MetaBucket` (`markOAuthCompactAdvisedTx`, `oauth_binding.go:110`). +- **Decision**: all three buckets are lazy; nothing is added to `initBuckets`. `oauth_login_ever_used` is written in the transaction that stores the first grant. A test opens a database, runs a default-off server through the e2e route table, and asserts the bucket list is unchanged. +- **Purge**: `ForgetClientCredential` path gains `forgetOAuthClientTx(tx, clientID)`. + +## R11. Config field + +- **Finding**: wiring points for a hot bool: struct field (`internal/config/config.go`), `DefaultConfig`, `Field…`/`envOverride` (`process_overrides.go`, `loader.go`), `DetectConfigChanges` / `undiffedHotConfigFields` (`internal/runtime/config_hotreload.go`), swagger, `frontend/src/views/settings/fields.ts`, `SettingsCatalog.swift`, `docs/configuration/config-file.md`. +- **Decision**: `MCPOAuthEnabled bool json:"mcp_oauth_enabled,omitempty"`, env `MCPPROXY_MCP_OAUTH_ENABLED`, hot. `omitempty` keeps existing config files byte-identical after a save. + +## R12. Connect + +- **Finding**: `buildServerEntry` (`internal/connect/clients.go:566`) and `withAPIKeyHeader` (636) build entries; `baseURL()` returns `http:///mcp`; `ClientDef` has no OAuth flag; Claude Desktop goes through `mcp-remote`. +- **Decision**: `ClientDef.SupportsBrowserLogin bool`, set only for clients that pass the real-client check. `ConnectOptions.Auth` (`key` default, `oauth`). For `oauth` the entry is built with `baseURL()+"/oauth/"+clientID` and no header; the credential minter is not called. The precondition token and preview cover the new option unchanged. + +## R13. Real clients and plain HTTP + +- **Open risk carried from the design**: the issuer is `http://127.0.0.1:`. RFC 8414 and the MCP authorization spec ask for HTTPS. Whether each client accepts it, and whether it follows protected-resource metadata for a path below the MCP root, is an empirical question. +- **Decision**: a PR-1 gate. Run Claude Code, Cursor, VS Code and MCP Inspector against a built core on a per-client path; record for each: discovery, registration name, redirect URI shape, token exchange, refresh. Results go to `verification/real-clients.md` and decide (a) `SupportsBrowserLogin` per client and (b) the docs' supported list. If no client completes the flow over plain HTTP, stop and report before PR-2: the fallback is serving the OAuth endpoints only when local TLS is on. From ebf8aeacb06d41657bba10b6c8804ea363b86140 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sun, 22 Nov 2026 16:38:57 +0200 Subject: [PATCH 07/15] docs(spec): tasks for spec 131 Related #1971 --- ROADMAP.md | 1 + specs/131-client-oauth-login/tasks.md | 163 ++++++++++++++++++++++++++ 2 files changed, 164 insertions(+) create mode 100644 specs/131-client-oauth-login/tasks.md diff --git a/ROADMAP.md b/ROADMAP.md index 247f83830..7bd2fee18 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1444,3 +1444,4 @@ Legend: `shipped` ≥95% checked · `in-flight` 1–94% · `drafted` 0% · `—` | [128-server-list-outcomes](./specs/128-server-list-outcomes/) | — | — | | [129-per-user-upstream-credentials](./specs/129-per-user-upstream-credentials/) | — | — | | [130-skills-review-ux](./specs/130-skills-review-ux/) | `shipped` | 9/9 (100%) | +| [131-client-oauth-login](./specs/131-client-oauth-login/) | `drafted` | 0/71 (0%) | diff --git a/specs/131-client-oauth-login/tasks.md b/specs/131-client-oauth-login/tasks.md new file mode 100644 index 000000000..b34dbc04e --- /dev/null +++ b/specs/131-client-oauth-login/tasks.md @@ -0,0 +1,163 @@ +# Tasks: Browser login for MCP clients (opt-in OAuth) + +**Input**: [plan.md](./plan.md), [spec.md](./spec.md), [research.md](./research.md), [data-model.md](./data-model.md), [contracts/](./contracts/), [design.md](./design.md) + +**Tests**: required (constitution V). Within every group the test tasks come first and must fail before the implementation task starts. + +**Format**: `[ID] [P?] [Story] Description`. `[P]` = different files, no dependency on an unfinished task. Stories: US1 update changes nothing · US2 sign a known client in · US3 manage and revoke · US4 browser without the key · US5 unknown client · US6 Connect choice · US7 turn off again. + +Tasks are grouped by the three delivery PRs. Each PR is merged before the next starts, and each ends with the same gate (see "PR gate"). + +--- + +## PR-1 — Backend + +### Phase 1: Setup + +- [ ] T001 Create package `internal/mcplogin/` with `doc.go` stating its scope (pure protocol logic, stdlib only) and add it to the import-boundary check if one applies (`scripts/` lint config) +- [ ] T002 [P] Create `tests/oauthclient/` with a scripted public client (`client.go`: discovery, register, authorize with a loopback listener, exchange, refresh) used by tests and the e2e script + +### Phase 2: Foundational — switch and default-off equivalence (US1) + +**Goal**: the switch exists, and with it off nothing answers differently. Blocks everything else. + +- [ ] T003 [US1] Test `TestConfig_MCPOAuthEnabled_DefaultOffAndOmitted` in `internal/config/mcp_oauth_test.go`: default false, absent from a saved default config, env `MCPPROXY_MCP_OAUTH_ENABLED` overrides and is not persisted +- [ ] T004 [US1] Add `MCPOAuthEnabled` (`mcp_oauth_enabled,omitempty`) to `internal/config/config.go`, `FieldMCPOAuthEnabled` + `envOverride` in `internal/config/process_overrides.go` and `internal/config/loader.go`, hot field in `internal/runtime/config_hotreload.go` +- [ ] T005 [US1] Test `TestOAuthLogin_DefaultOff_RoutesUnchanged` in `internal/server/oauth_login_default_off_test.go`: for `/mcp/oauth`, `/mcp/oauth/cursor`, `/oauth/register`, `/oauth/authorize`, `/oauth/token`, both `/.well-known/oauth-*` paths, over GET/POST with and without credentials, the gated handler's status, body and auth-relevant headers equal those of the previous handler (`mcpHandler` or the root handler) +- [ ] T006 [US1] Test `TestOAuthLogin_DefaultOff_NoStorage` in `internal/server/oauth_login_default_off_test.go`: after the requests of T005 the bbolt bucket list and `MetaBucket` keys are unchanged +- [ ] T007 [US1] Implement the three-state gate in `internal/server/oauth_login_routes.go` (`oauthLoginGate(prev, served)`: off+never-used → `prev`, off+used → 404, on → `served`; loopback peer + loopback Host + personal edition else 404) and register the five patterns in `startCustomHTTPServer` (`internal/server/server.go`), with `served` a 501 stub for now +- [ ] T008 [P] [US1] Test and implement `peerIsLoopback(r)` in `internal/server/oauth_login_routes.go` (`oauth_login_routes_test.go`: IPv4, IPv6, non-loopback, unix socket, malformed) +- [ ] T009 [US1] Run `make swagger`; add `mcp_oauth_enabled` to `docs/configuration/config-file.md` + +**Checkpoint**: `./scripts/test-api-e2e.sh` and the CI unit matrix pass unchanged. + +### Phase 3: Protocol logic (leaf package, all [P] among themselves) + +- [ ] T010 [P] [US2] Tests then code for token formats in `internal/mcplogin/token.go` (`token_test.go`): generate/parse `mcp_oat_`, `mcp_ort___`, MAC verify with a labelled key, constant-time compare, rejects of every malformed shape +- [ ] T011 [P] [US2] Tests then code for PKCE S256 in `internal/mcplogin/pkce.go` (RFC 7636 vector, wrong verifier, length bounds) +- [ ] T012 [P] [US2] Tests then code for redirect URI rules in `internal/mcplogin/redirect.go`: loopback http any port at match time, https exact, fragment refused, custom scheme refused, at most 5 +- [ ] T013 [P] [US2] Tests then code for resource and origin in `internal/mcplogin/resource.go`: origin from request, `/mcp/oauth` vs `/mcp/oauth/{client}`, client id via `auth.ValidClientID`, `localhost` ≠ `127.0.0.1` +- [ ] T014 [P] [US2] Tests then code for metadata documents in `internal/mcplogin/metadata.go`, golden files in `internal/mcplogin/testdata/` matching `contracts/oauth-endpoints.md` +- [ ] T015 [P] [US2] Tests then code for registration validation in `internal/mcplogin/registration.go`: effective values, refusal of secret-based methods and other grant types, name sanitised with `clientidentity` +- [ ] T016 [P] [US2] Tests then code for the in-memory request and code store in `internal/mcplogin/requests.go`: decided once (race test with two approvers), expiry at 10 min / 60 s with a clock seam, cap of 20, cancel by client and cancel all, code single use +- [ ] T017 [P] [US2] Tests then code for limits in `internal/mcplogin/limits.go`: per-key `limiter.TokenRates`, the three default rates, `Retry-After` + +### Phase 4: Storage + +- [ ] T018 [US2] Tests in `internal/storage/oauth_login_test.go` for registrations: create, get, state moves, expiry sweep (15 min / 24 h), cap of 50 non-approved +- [ ] T019 [US2] Tests in `internal/storage/oauth_login_test.go` for grants: create with first-grant marker in the same tx, lookup by access hash, `RotateOrRevoke` (current secret → rotate; authentic old secret → revoke `replay`; unknown/revoked → no write, asserted by tx id), lapse after 30 days, retention of dead grants +- [ ] T020 [US2] Implement `internal/storage/oauth_login.go` for T018–T019 with lazy buckets `oauth_registrations`, `oauth_grants` (+ `by_access_hash`), marker `oauth_login_ever_used` +- [ ] T021 [US3] Tests in `internal/storage/client_binding_dual_test.go`: `UpdateClientCredentialBinding` writes the API-key record and `oauth_client_bindings` in one tx; works for an OAuth-only client; fails when neither exists; startup repair takes the API-key record +- [ ] T022 [US3] Implement T021 in `internal/storage/client_credentials.go` and `internal/storage/oauth_login.go`; add `forgetOAuthClientTx` to the `ForgetClientCredential` path +- [ ] T023 [P] [US3] Test `TestDowngradeView_APIKeyRecordStaysCurrent` in `internal/storage/client_binding_dual_test.go`: after a reassign of a client with both credentials, the raw `agent_tokens` record carries the new pin and mode (FR-028) + +### Phase 5: Runtime service, binding, guard + +- [ ] T024 [US2] Add `CredentialKindOAuth` to `internal/auth/context.go` and `auth.ClientAuthContext(...)` to `internal/auth/agent_token.go`; make `(*AgentToken).AuthContext` use it; test in `internal/auth/agent_token_identity_test.go` that both paths give equal contexts except the kind +- [ ] T025 [US2] Source test `TestCredentialKindAgentTokenSitesClassified` in `internal/auth/credential_kind_sites_test.go`: every comparison with `CredentialKindAgentToken` in `internal/` is listed as "applies to oauth" or "API-key specific"; fix the sites it finds +- [ ] T026 [US2] Tests in `internal/runtime/oauth_login_service_test.go` for `Describe(requestID)`: fixed client on a per-client address, generic address lists clients with none pre-selected, `profile_required`, `previous_login` only for the same registration, guard verdict included, reported name never selects anything +- [ ] T027 [US2] Tests in `internal/runtime/oauth_login_service_test.go` for `Approve`/`Deny`: creates client binding and grant, `already_decided`, `binding_changed` on a stale revision, `client_fixed`, `profile_required`, new custom client id rules (`identity_exists`, `reserved_identity`), `replace_grant` revokes the old login, activity rows `approve`/`deny` with the request actor +- [ ] T028 [US2] Implement `internal/runtime/oauth_login_service.go` (`OAuthLoginService`: `Describe`, `Approve`, `Deny`, `Exchange`, `Refresh`, `Authenticate`, `ListGrants`, `RevokeGrant`) under `bindingWriteMu`; wire in `internal/runtime/runtime.go`; add `approve`, `deny`, `replay_revoke` to `internal/profile/contract.go`; add events to `internal/runtime/events.go` and to `adminConfigEventTypes` in `internal/httpapi/sse_scope.go` +- [ ] T029 [US3] Tests in `internal/runtime/clients_service_test.go`: `SetBinding` and `BulkAssign` on an OAuth-only client; `Forget` deletes grants; client revoke revokes key and all grants; profile delete reports an OAuth-only client in `profile_in_use`; rename moves its pin +- [ ] T030 [US3] Implement T029 in `internal/runtime/clients_service.go` and `internal/runtime/credentials_service.go` (revoke cascade, single-grant revoke, API-key-only revoke, grants in `List`/`Get`) +- [ ] T031 [US2] Tests in `internal/runtime/binding_guard_strict_test.go` and `internal/server/profile_binding_guard_test.go`: an OAuth-only client with a named pin and a live grant is an active binding; lapsed or revoked grants are not; approval with `require_mcp_auth` off returns `binding_bypassable_without_auth` with the guard's fixes +- [ ] T032 [US2] Implement T031 in `internal/runtime/binding_guard.go` and `internal/server/profile_binding_guard.go` + +### Phase 6: HTTP endpoints and authentication + +- [ ] T033 [US2] Tests in `internal/server/oauth_login_http_test.go` for metadata and the `401` challenge on `/mcp/oauth` and `/mcp/oauth/{client}`, unknown client id → 404 everywhere +- [ ] T034 [US2] Tests in `internal/server/oauth_login_http_test.go` for `/oauth/register`, `/oauth/authorize` (no redirect on bad client/redirect URI, `invalid_target`, `state` round trip, `no-store`, `Referrer-Policy`) and `/oauth/token` (every row of the error table in `contracts/oauth-endpoints.md`, `resource` substitution, size and rate limits) +- [ ] T035 [US2] Implement `internal/server/oauth_login_http.go` and replace the 501 stub from T007 +- [ ] T036 [US2] Tests in `internal/server/oauth_login_auth_test.go`: `mcp_oat_` accepted only on its own resource and origin; API key, `mcp_cli_`, `mcp_agt_`, no token → 401 on OAuth addresses even with `require_mcp_auth` off; `mcp_oat_` on `/mcp` and routing-mode routes → 401 while the feature is on or was used, unchanged anonymous behaviour while off and never used; revoked or lapsed grant → 401 on the next request of an open session; profile scope and activity attribution equal the same client's `mcp_cli_` request +- [ ] T037 [US2] Implement `oauthResourceAuth` and the `mcp_oat_` branch of `mcpAuthMiddleware` in `internal/server/server.go`; record `grant_id` and credential kind on activity rows +- [ ] T038 [US7] Tests in `internal/server/oauth_login_toggle_test.go`: on → off after use gives 404 on all OAuth paths and cancels pending requests; forgetting the last client keeps 404; off → on restores logins; toggling needs no restart (config reload event) +- [ ] T039 [US7] Implement the toggle handling: cached gate state refreshed on `EventTypeConfigReloaded` and on first grant in `internal/server/oauth_login_routes.go` + +### Phase 7: Admin REST + +- [ ] T040 [US2] Tests in `internal/httpapi/oauth_login_test.go` for `GET /oauth/authorizations`, `GET /oauth/authorizations/{id}`, `POST …/approve`, `POST …/deny`: payloads and error codes of `contracts/rest-admin.md`, uniform 404, `403` for agent tokens and client credentials, `404 feature_disabled` when off +- [ ] T041 [US2] Implement `internal/httpapi/oauth_login.go`, register under `/api/v1` in `internal/httpapi/server.go`, classify the GETs for `scope_route_table_guard_test.go`, run `make swagger` +- [ ] T042 [US3] Tests then code in `internal/httpapi/clients.go` and `internal/httpapi/client_bindings.go`: `credentials[]` and `browser_login_disabled` on client payloads, `DELETE /clients/{client}/logins/{grant_id}`, `DELETE /clients/{client}/api-key` (tests in `internal/httpapi/clients_routes_test.go`); update `internal/contracts` types and regenerate frontend types + +### Phase 8: End to end and real clients + +- [ ] T043 [US2] Write `scripts/test-client-oauth-e2e.sh` following `scripts/test-oauth-token-encryption-e2e.sh`, covering the seven numbered steps of `quickstart.md` §2 with `tests/oauthclient` +- [ ] T044 [US2] Run the real-client check of `research.md` R13 for Claude Code, Cursor, VS Code and MCP Inspector; record `specs/131-client-oauth-login/verification/real-clients.md`. **If none completes the flow over plain HTTP, stop and report before PR-2.** +- [ ] T045 Write `docs/features/client-oauth-login.md` (backend scope: enabling, addresses, tokens, turning off, downgrade, the HTTP note, REST) and add it to the docs sidebar/allowlist; add the CLAUDE.md "Recent Changes" entry by hand +- [ ] T046 PR gate for PR-1 (see below) + +--- + +## PR-2 — Surfaces + +### Phase 9: Consent page (US2, US5, US4) + +- [ ] T047 [P] [US2] Add API methods and types for authorizations and client credentials in `frontend/src/services/api.ts` and `frontend/src/types/` +- [ ] T048 [US2] Vitest `frontend/tests/unit/authorize-request.spec.ts`: fixed client view, unverified-name label, access sentence, profile shown not asked when bound, Approve disabled until a profile is chosen when `profile_required`, replace-login checkbox only with `previous_login`, guard refusal with fixes shown before approval, `already_decided` and `binding_changed` handling, navigation to `redirect_url` +- [ ] T049 [US2] Implement `frontend/src/views/AuthorizeRequest.vue` and the `/authorize` route in `frontend/src/router/index.ts`, reusing `GuardRefusal.vue`, `ProfileChip.vue` +- [ ] T050 [US5] Vitest in `frontend/tests/unit/authorize-request.spec.ts` for the generic address: nothing pre-selected, "New client" with editable id and name, existing-client choice shows the access sentence, `identity_exists` / `reserved_identity` errors +- [ ] T051 [US5] Implement the generic-address branch in `frontend/src/views/AuthorizeRequest.vue` +- [ ] T052 [US4] Vitest then code: with no API key in storage `AuthorizeRequest.vue` shows only "Open from the tray or paste the API key", makes no request-detail call, and continues after a pasted key (`frontend/tests/unit/authorize-request-nokey.spec.ts`) +- [ ] T053 [US4] Test then code: `frame-ancestors 'none'` (and `X-Frame-Options: DENY`) on `/ui/authorize` in `internal/server/server.go` (`internal/server/oauth_login_http_test.go`) + +### Phase 10: Tray (US4) + +- [ ] T054 [US4] macOS tray: handle `oauth.authorization_pending` / `oauth.authorization_decided` in `native/macos/MCPProxy/MCPProxy/Core/CoreProcessManager.swift`, keep pending requests in `State/AppState.swift`, add menu items "Approve sign-in for …" in `MCPProxyApp.swift` opening `/authorize?request=` through `WebUILink`, add `sendSignInRequest` to `Services/NotificationService.swift`; Swift unit tests for the state reducer +- [ ] T055 [US4] Verify T054 with `mcpproxy-ui-test` (menu item appears, opens the request) per `docs/development/macos-tray.md`; screenshot into `verification/` + +### Phase 11: Clients hub and management (US3) + +- [ ] T056 [US3] Vitest `frontend/tests/unit/client-credentials.spec.ts`: credential list per client (API key, logins with state), revoke one login, revoke API key only, "browser login disabled" label, initialize-name mismatch warning +- [ ] T057 [US3] Implement `frontend/src/components/clients/ClientCredentials.vue` and use it in `frontend/src/views/Clients.vue` +- [ ] T058 [P] [US3] Tests then code: `credentials` MCP tool lists logins and revokes one (`grant=`), never creates one — `internal/server/mcp_credentials*.go` and its tests +- [ ] T059 [P] [US3] Tests then code: CLI `mcpproxy client show` lists credentials and `mcpproxy client revoke-login ` in `cmd/mcpproxy/client_cmd.go`, `cmd/mcpproxy/client_binding_cmd.go` +- [ ] T060 [P] [US1] Settings switch: optional `badge` on `SettingField`, entry for `mcp_oauth_enabled` in `frontend/src/views/settings/fields.ts`, rendering in `frontend/src/views/Settings.vue`, mirror in `native/macos/MCPProxy/MCPProxy/Settings/SettingsCatalog.swift`; vitest that no other view mentions browser login while off +- [ ] T061 [US3] Playwright sweep for `/ui/authorize`, `/ui/clients`, `/ui/settings` with HTML report per `docs/development/web-ui-verification.md`; extend `scripts/test-client-oauth-e2e.sh` with approval through the page +- [ ] T062 Update `docs/features/client-oauth-login.md` (consent page, tray, managing logins), `docs/features/mcp-credential-lifecycle.md`, `docs/cli/profile-commands.md`, `docs/api/rest-api.md` +- [ ] T063 PR gate for PR-2 + +--- + +## PR-3 — Connect and docs + +### Phase 12: Connect choice (US6) + +- [ ] T064 [US6] Tests in `internal/connect/clients_test.go` and `internal/connect/connect_test.go`: `SupportsBrowserLogin` set only for clients that passed T044; `ConnectOptions.Auth=oauth` builds `…/mcp/oauth/` with no header for each config format; the minter is not called; preview masks nothing and shows no credential; refused when the feature is off or the client is unsupported +- [ ] T065 [US6] Implement T064 in `internal/connect/clients.go`, `internal/connect/connect.go`, `internal/connect/preview.go`; expose `supports_browser_login` on the connect payload (`internal/contracts`, `make swagger`) +- [ ] T066 [P] [US6] CLI `mcpproxy connect --auth key|oauth` in `cmd/mcpproxy/connect_cmd.go` and `cmd/mcpproxy/connect_credential.go`, with tests +- [ ] T067 [P] [US6] Web UI choice in `frontend/src/components/ClientConnectList.vue` (shown only when the feature is on and the client supports it; "API key" default), vitest `frontend/tests/unit/connect-auth-choice.spec.ts` +- [ ] T068 [P] [US6] macOS Connect view choice in `native/macos/MCPProxy/MCPProxy/Views/ConnectClientView.swift` and `ConnectClientModel.swift` +- [ ] T069 [US6] Extend `scripts/test-client-oauth-e2e.sh`: `connect --auth oauth` writes only the address; Playwright sweep for the Connect screen +- [ ] T070 Finish docs: `docs/features/client-oauth-login.md` (Connect, verified clients list), `docs/features/connect-clients.md`, `docs/features/profiles.md` (credentials of a client), `docs/features/agent-tokens.md` cross-link; CLAUDE.md entry +- [ ] T071 PR gate for PR-3; comment on issue #1971 with what shipped and how to enable it + +--- + +## PR gate (T046, T063, T071) + +1. `go test -race` for the touched packages with the CI `-skip` regex, plus `-tags server` for `internal/server`, `internal/httpapi`, `internal/storage`. +2. Both `golangci-lint` runs (`.github/.golangci.yml`, bare and `--build-tags server`). +3. `./scripts/test-api-e2e.sh` (run alone) and `./scripts/test-client-oauth-e2e.sh`. +4. `make swagger` clean; frontend `npm run test:unit` and build when `frontend/` changed. +5. Cross-model review (opencode `github-copilot/gpt-6.1-sol`, chunked by file, at most 10 rounds); security-sensitive PR-1 also gets one Opus subagent review. +6. PR title `feat(oauth): … (Spec 131 PR-n)`, body via `--body-file`, `Related #1971`, no QA report in the body. + +## Dependencies + +- Phase 2 blocks everything. Phase 3 tasks are mutually parallel. Phase 4 needs T010. Phase 5 needs Phases 3–4. Phase 6 needs Phase 5. Phase 7 needs T028 and T030. Phase 8 needs Phases 6–7. +- PR-2 needs PR-1 merged. Phase 10 needs T028 (events). Phase 11 needs T042. +- PR-3 needs T044 (which clients qualify) and PR-2 merged. +- Story order: US1 (Phase 2) → US2 backend (3–7) with US3 backend and US7 alongside → US2/US5/US4 surfaces → US3 surfaces → US6. + +## Parallel opportunities + +- T010–T017 (eight files in `internal/mcplogin`). +- T002 with Phase 2. +- T058, T059, T060 with the Clients hub work. +- T066, T067, T068 after T065. + +## Implementation strategy + +- **MVP = PR-1.** It is usable with the scripted client and the admin REST, proves the default-off promise and settles the real-client question (T044) before any UI is built. +- Stop points: after T009 (switch only, safe to merge alone if PR-1 grows too large), after T044 (go/no-go for PR-2). +- Counts: 71 tasks. PR-1 46 (US1 7, US2 27, US3 7, US7 2, shared 3), PR-2 17, PR-3 8. From a2a121b8d6b1e190f80f03dc73eab6052308f054 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sun, 22 Nov 2026 17:00:37 +0200 Subject: [PATCH 08/15] docs(spec): address plan review round 1 for spec 131 Related #1971 --- .../contracts/oauth-endpoints.md | 13 +++++++---- .../contracts/rest-admin.md | 7 +++--- specs/131-client-oauth-login/data-model.md | 9 +++++--- specs/131-client-oauth-login/plan.md | 12 ++++++---- specs/131-client-oauth-login/research.md | 23 +++++++++++++------ 5 files changed, 42 insertions(+), 22 deletions(-) diff --git a/specs/131-client-oauth-login/contracts/oauth-endpoints.md b/specs/131-client-oauth-login/contracts/oauth-endpoints.md index fbd88614f..7b19b5daf 100644 --- a/specs/131-client-oauth-login/contracts/oauth-endpoints.md +++ b/specs/131-client-oauth-login/contracts/oauth-endpoints.md @@ -60,14 +60,17 @@ Request (JSON, at most 16 KiB): `redirect_uris` (required), `client_name`, `soft Query: `response_type=code`, `client_id`, `redirect_uri`, `code_challenge`, `code_challenge_method=S256`, `resource`, `state` (optional), `scope` (ignored). - Unknown `client_id` or `redirect_uri` not registered (loopback port ignored) → `400` HTML error page, **no redirect**. +- `resource` is `/mcp/oauth/{client}` with a client id that does not exist → `404` HTML page, **no redirect** (FR-015). Checked before the general `resource` rule. - Other errors → redirect to `redirect_uri` with `error` (`invalid_request`, `unsupported_response_type`, `invalid_target`, `temporarily_unavailable`) and `state`. -- `resource` must be `/mcp/oauth` or `/mcp/oauth/{known client}`, else `invalid_target`. +- Any other `resource` that is not `/mcp/oauth` or `/mcp/oauth/{known client}` → `invalid_target`. - Success → `302` to `/ui/authorize?request=`. Headers on every answer: `Cache-Control: no-store`, `Referrer-Policy: no-referrer`. After the administrator decides (admin REST), the browser is sent to: -- approve: `redirect_uri?code=&state=` -- deny: `redirect_uri?error=access_denied&state=` +- approve: the stored redirect URI with `code` added +- deny: the stored redirect URI with `error=access_denied` added + +Every redirect (these two and the error redirects above) is built by parsing the stored redirect URI, keeping its existing query, and appending percent-encoded parameters. `state` is added only if the client sent one, with its value unchanged. ## `POST /oauth/token` @@ -87,8 +90,8 @@ Errors (`400` JSON `{error, error_description}`): | Case | `error` | Side effect | |---|---|---| -| unknown, expired or already used code; wrong verifier, client or redirect URI | `invalid_grant` | a reused code revokes the grant it produced | -| refresh token malformed, bad MAC, unknown or revoked grant, wrong `client_id` | `invalid_grant` | **none**; all indistinguishable | +| unknown, expired or already used code; wrong verifier, client or redirect URI | `invalid_grant` | a code reused within 10 minutes revokes the grant it produced | +| refresh token malformed, bad MAC, unknown, revoked or expired grant, wrong `client_id` | `invalid_grant` | **none**; all indistinguishable; an expired login is never extended | | authentic refresh token that is not the current one | `invalid_grant` | grant revoked (`replay`) | | `resource` differs from the approved one | `invalid_target` | none | | other grant type | `unsupported_grant_type` | none | diff --git a/specs/131-client-oauth-login/contracts/rest-admin.md b/specs/131-client-oauth-login/contracts/rest-admin.md index ecad36aac..339e1d9e5 100644 --- a/specs/131-client-oauth-login/contracts/rest-admin.md +++ b/specs/131-client-oauth-login/contracts/rest-admin.md @@ -1,6 +1,6 @@ # Contract: administrator surfaces -All REST routes are under `/api/v1`, use the standard `{success, data}` envelope, require administrator credentials (admin API key or tray socket) and answer `403` to agent tokens and client credentials. With the feature off they answer `404 feature_disabled`, except the grant listing fields on `/clients`, which are simply empty. +All REST routes are under `/api/v1`, use the standard `{success, data}` envelope, require administrator credentials (admin API key or tray socket) and answer `403` to agent tokens and client credentials. With the feature off the sign-in request routes answer `404 feature_disabled`. Client payloads depend on whether the feature was ever used: never used → exactly today's payload, no new fields; used → logins are still listed and `browser_login_disabled` is `true`. Revoking a login works in both on and off-after-use states. ## Sign-in requests @@ -66,7 +66,8 @@ Pending requests, newest first: `[{id, client_label, created_at, expires_at}]`. "credentials": [ { "kind": "api_key", "prefix": "mcp_cli_ab12", "state": "active", "expires_at": "…", "last_used_at": "…" }, { "kind": "browser_login", "grant_id": "…", "state": "active", // active | lapsed | revoked - "approved_at": "…", "last_used_at": "…", "reported_name": "Cursor IDE", "redirect_host": "127.0.0.1" } + "approved_at": "…", "last_used_at": "…", "reported_name": "Cursor IDE", "redirect_host": "127.0.0.1", + "observed_name": "cursor-vscode", "name_mismatch": false } ], "browser_login_disabled": false ``` @@ -84,7 +85,7 @@ Pending requests, newest first: `[{id, client_label, created_at, expires_at}]`. ## Activity -`profile_change` rows with `change` = `approve` | `deny` | `revoke` | `replay_revoke`, metadata `client_id`, `grant_id`, `profile`, `actor_kind`, `actor_name`, `surface`. Tool-call rows of a browser login carry `client_id` and `metadata.grant_id`, credential kind `oauth`. +`profile_change` rows with `change` = `approve` | `deny` | `issue` | `revoke` | `replay_revoke`, metadata `client_id`, `grant_id`, `profile`, `actor_kind`, `actor_name`, `surface`. `approve`, `deny` and `revoke` name the administrator who made the request. `issue` (first token exchange) and `replay_revoke` happen on the public token endpoint: they name the administrator who approved the login (`approved_by`) and add `trigger: "client"`. Tool-call rows of a browser login carry `client_id` and `metadata.grant_id`, credential kind `oauth`. ## MCP `credentials` tool diff --git a/specs/131-client-oauth-login/data-model.md b/specs/131-client-oauth-login/data-model.md index ca71c6bce..ee68d3cdf 100644 --- a/specs/131-client-oauth-login/data-model.md +++ b/specs/131-client-oauth-login/data-model.md @@ -31,6 +31,8 @@ Lifecycle: `pending` rows are deleted 15 minutes after creation, `authorized` (r | `refresh_expires_at` | time | now + 30 days on every rotation | | `approved_at`, `approved_by` | time, actor | | | `last_used_at` | time | updated like agent tokens, off the request path | +| `observed_client_name`, `observed_at` | string, time | name sent at `initialize` on this login, sanitised; for the advisory mismatch warning only | +| `display_prefix` | string | 12 chars shown in lists and used as the context's token prefix | | `revoked`, `revoked_at`, `revoke_reason` | bool, time, enum | `admin`, `client_revoked`, `replaced`, `replay` | | `user_id` | string | empty in the personal edition | @@ -71,7 +73,7 @@ At most 20 pending requests; a new one beyond that is refused with `temporarily_ ## Authorization code — memory only -`code` (32 random bytes, stored hashed), bound to request id, registration, redirect URI, challenge, resource, chosen client and the decision. Single use, 60 seconds. A second use revokes the grant created from the first. +`code` (32 random bytes, stored hashed), bound to request id, registration, redirect URI, challenge, resource, issuer, chosen client and the decision. Single use, 60 seconds. Consuming it and storing the grant is one step; the entry then stays as a tombstone `{consumed_at, grant_id}` for 10 minutes. A second presentation within that time revokes that grant (`replay`); after it, the code is simply unknown. ## Relationships @@ -86,8 +88,9 @@ Client (Clients hub id) - **Credential list of a client** (Clients hub, REST, `credentials get`): the API key if any, then grants ordered by `approved_at` descending, each with state, prefix, `approved_at`, `last_used_at`, reported name, redirect host. Never a secret or a hash. - **Active named binding** (guard, `profile_in_use`): a client with a named pin and either a live API key or a live grant. -- **Client state** on the hub gains `browser_login_disabled` when the client has grants and the feature is off. +- **Client state** on the hub gains `browser_login_disabled` when the client has grants and the feature is off. The logins stay listed. +- **Name mismatch** per login: derived from `observed_client_name` (research R14). ## Auth context of a browser-login request -`Type=agent`, `TokenKind=client`, `ClientID=`, `ProfilePin`, `ProfileMode` from the binding, `CredentialKind=oauth`, `AllowedServers=["*"]`, all three permission tiers. Built by the same helper as the `mcp_cli_` path. +`Type=agent`, `TokenKind=client`, `ClientID=`, `AgentName=client-`, `ProfilePin`, `ProfileMode` from the binding, `CredentialKind=oauth`, `GrantID`, `TokenPrefix=`, `TokenGeneration=`, the client rate limit, `AllowedServers=["*"]`, all three permission tiers. Built by the same helper as the `mcp_cli_` path. The grant id is also kept on the MCP session record. diff --git a/specs/131-client-oauth-login/plan.md b/specs/131-client-oauth-login/plan.md index 872b7a66b..3dcd8659b 100644 --- a/specs/131-client-oauth-login/plan.md +++ b/specs/131-client-oauth-login/plan.md @@ -122,13 +122,13 @@ PR-2b (Go tray notification for Windows/Linux) is a follow-up outside this plan. Full reasoning is in [research.md](./research.md). -1. **Routes are always registered and gated per request.** `http.ServeMux` cannot drop a pattern, and the mux is built once (`startCustomHTTPServer`). Each new pattern wraps the handler that answered that path before: the default `mcpHandler` for `/mcp/oauth*`, the root handler for `/oauth/*` and `/.well-known/oauth-*`. Off and never used: delegate. Off and used: 404. On: serve. +1. **Routes are always registered and gated per request.** `http.ServeMux` cannot drop a pattern, and the mux is built once (`startCustomHTTPServer`). Only exact paths are registered (`/oauth/register`, `/oauth/authorize`, `/oauth/token`, `/.well-known/oauth-authorization-server`, `/mcp/oauth`, `/.well-known/oauth-protected-resource/mcp/oauth`) plus the two subtrees `/mcp/oauth/` and `/.well-known/oauth-protected-resource/mcp/oauth/`, each with its exact no-slash companion already in the list, so the mux never issues a trailing-slash redirect that did not exist before. Each new pattern wraps the handler that answered that path before: the default `mcpHandler` for `/mcp/oauth*`, the root handler for `/oauth/*` and `/.well-known/oauth-*`. Off and never used: delegate. Off and used: 404. On: serve. 2. **Authenticate into the existing client context.** A valid `mcp_oat_` token yields the same `AuthContext` as that client's `mcp_cli_` credential (agent type, `TokenKind=client`, `ClientID`, pin, mode), with `CredentialKind=oauth`. Every `CredentialKind` switch is audited by a test. -3. **Binding storage.** The API-key record keeps `ProfilePin`/`ProfileMode`. `oauth_client_bindings` holds the binding for clients with grants. `storage.UpdateClientCredentialBinding` becomes the one write path and updates both in one bbolt transaction. -4. **Guard.** `BindingGuardActiveBindings` and `ActiveNamedBinding` gain a second source: clients with a live grant and a named binding. +3. **Binding storage.** The API-key record keeps `ProfilePin`/`ProfileMode`. `oauth_client_bindings` holds the binding for clients with grants. One transaction-local helper, `writeClientBindingTx`, is the only code that writes a client's pin or mode, and every writer calls it inside its own transaction: binding update, mint and reconnect, connect rollback, profile repin and restore (`RepinProfile`, `RestorePins`). A source test forbids any other assignment to those fields in `internal/storage`. +4. **Guard.** `GuardState` gains `OAuthBindings` (client, pin, mode, live). Every producer of a current or candidate state fills it, an approval adds its not-yet-stored binding to the candidate, and the delta, fixes, conservative and offline evaluators read both sources, deduplicated by client. A storage error while building a state refuses the change. 5. **Loopback rule.** New helper `peerIsLoopback(r)` on `r.RemoteAddr`, combined with the existing `httpx.IsLoopbackHost(r.Host)`. Tray socket connections are not loopback TCP and get 404 on the public OAuth endpoints. 6. **Rate limiting.** A private `limiter.TokenRates` instance keyed by endpoint + remote address. No new dependency. -7. **Activity.** New `profile.ChangeKind` values `approve`, `deny`, `replay_revoke`; `issue` and `revoke` are reused. +7. **Activity.** New `profile.ChangeKind` values `approve`, `deny`, `replay_revoke`; `issue` (first token exchange of a grant) and `revoke` are reused. Rows written on the public token endpoint (`issue`, `replay_revoke`) take the administrator from the grant's `approved_by` and add `trigger: client`. 8. **Settings.** `SettingField` gains an optional `badge` ("Experimental"); mirrored in the macOS settings catalogue. ## Verification @@ -148,3 +148,7 @@ Full reasoning is in [research.md](./research.md). |---|---|---| | Mutex around the in-memory request/code store | "Decided once" (FR-020) is a compare-and-set on shared state with no I/O | A channel-owned actor adds a goroutine and a request/response type for five map operations; the existing services already use `bindingWriteMu` for the same reason | | Second binding record (`oauth_client_bindings`) beside the API-key record | A client may have only browser logins, and an older binary must still read the right profile from the API-key record (FR-028) | Moving the binding to one new record breaks downgrade; a credential-less `AgentToken` record fails `ValidateTokenInvariants` on older binaries | + +## Review + +Cross-model review of plan, research, data model, contracts and tasks, round 1 (opencode `gpt-6.1-sol`, 2026-11-22): 15 findings, all accepted. Every binding writer goes through one helper; the guard state carries OAuth bindings including the candidate; forget, revoke-client, revoke-key and connect rollback are separate storage operations; exact route patterns avoid new trailing-slash redirects; the full client auth context and grant id are specified; codes carry issuer and a consumed tombstone; the initialize-name warning has storage and a hook; refresh expiry is checked before rotation; profile delete/rename files are in scope; listings after turn-off keep logins; redirect construction, unknown-client 404 at authorize, activity coverage, task order and the package boundary are corrected. diff --git a/specs/131-client-oauth-login/research.md b/specs/131-client-oauth-login/research.md index 5b188bdf8..e32d9675b 100644 --- a/specs/131-client-oauth-login/research.md +++ b/specs/131-client-oauth-login/research.md @@ -5,13 +5,13 @@ Code references are from `main` at `dfc3d418f`. Product decisions and their alte ## R1. Turning routes on and off without a restart - **Finding**: the outer mux is built once in `(*Server).startCustomHTTPServer` (`internal/server/server.go:3380`, mux at 3431). `http.ServeMux` has no unregister. Existing switchable features decide per request inside an always-registered handler (`/mcp/s/` in `serveSingleServer`, `/debug/pprof/`, `enable_skills` through `RefreshSkillsAvailability`). -- **Decision**: register `/mcp/oauth`, `/mcp/oauth/`, `/oauth/`, `/.well-known/oauth-protected-resource/`, `/.well-known/oauth-authorization-server` once. Each is a gate with three states read per request from config and the ever-used marker (cached, refreshed on `EventTypeConfigReloaded` and on first grant): +- **Decision**: register only exact paths plus two subtrees whose no-slash form is also registered: `/mcp/oauth`, `/mcp/oauth/`, `/oauth/register`, `/oauth/authorize`, `/oauth/token`, `/.well-known/oauth-authorization-server`, `/.well-known/oauth-protected-resource/mcp/oauth`, `/.well-known/oauth-protected-resource/mcp/oauth/`. A subtree pattern such as `/oauth/` is not used: `ServeMux` would answer `/oauth` with a redirect before any gate runs, which differs from today's 404. Each is a gate with three states read per request from config and the ever-used marker (cached, refreshed on `EventTypeConfigReloaded` and on first grant): - off, never used → call the handler that owned the path before (`mcpHandler` for `/mcp/oauth*`; the root `/` handler for the others); - off, used → 404; - on → serve. - **Rationale**: the only way to get hot reload and FR-002 together. - **Alternatives**: restart-gated field (rejected: constitution III, and the Settings switch would need a restart); rebuilding the mux (rejected: touches every route for one feature). -- **Test**: for each new pattern and a table of methods/headers, the response of the gate (off, never used) equals the response of the unwrapped previous handler, byte for byte on status, headers of interest and body. +- **Test**: build the complete mux twice, with and without the new registrations, and compare answers for a table of paths (the registered ones, their slash and no-slash variants, `/oauth`, `/oauth/`, `/oauth/x`, `/.well-known/oauth-protected-resource`, `/.well-known/x`), methods and credentials, in all three gate states where the legacy mux is the reference for "off, never used". ## R2. Where an access token is authenticated @@ -22,24 +22,27 @@ Code references are from `main` at `dfc3d418f`. Product decisions and their alte ## R3. The auth context of a browser login - **Finding**: `(*AgentToken).AuthContext` (`internal/auth/agent_token.go:339`) sets `Type=AuthTypeAgent`, `CredentialKind=agent_token`, `TokenKind`, `ClientID`, `ProfilePin`, `ProfileMode`. `CredentialKind` constants (`internal/auth/context.go:13-30`) have no OAuth kind. -- **Decision**: add `CredentialKindOAuth = "oauth"`. Add `auth.ClientAuthContext(clientID, pin, mode, kind)` used by both the `mcp_cli_` path and the OAuth path, so the two cannot drift. Activity gains `grant_id` in metadata. +- **Finding (review)**: `AuthContext()` also sets `AgentName`, `TokenPrefix`, `TokenGeneration` and `RateLimit` (`agent_token.go:343-358`); work-session grouping (`workspace.go:158-190`) and activity attribution (`mcp_activity_attribution.go:62-71`) read them. +- **Decision**: add `CredentialKindOAuth = "oauth"` and `AuthContext.GrantID`. One builder, `auth.ClientAuthContext(ClientIdentity)`, is used by both paths. For a browser login: `AgentName = ClientTokenName(clientID)` (the same `client-` an API key has, so activity and filters match), `TokenPrefix` = the grant's display prefix, `TokenGeneration` = grant id (so each login is its own work session and a revoked login never merges with a new one), `RateLimit` = the client rate limit configuration an API key gets. The MCP session record stores the grant id at `initialize`, so session-backed activity emitted without a request context still carries it. - **Risk**: code that switches on `CredentialKind == agent_token` to mean "scoped caller". **Mitigation**: a source test lists every comparison against `CredentialKindAgentToken` and requires each to be classified as "also applies to oauth" or "API-key specific". ## R4. One binding, two records - **Finding**: the binding lives on the `Kind=client` record; `storage.UpdateClientCredentialBinding(clientID, pin, mode)` (`internal/storage/client_credentials.go:233`) is called only from `ClientsService.setBindingLocked` (`internal/runtime/clients_service.go:539`). There is no index by client id (`findClientTokenRecordLocked` scans). `ValidateTokenInvariants` refuses a client record without a secret hash, expiry or with locked + empty pin. -- **Decision**: new bucket `oauth_client_bindings`, key = client id, value `{pin, mode, display_name, updated_at}`. `UpdateClientCredentialBinding` writes the API-key record if present and the OAuth record if present, in one transaction; it fails only if neither exists. `setBindingLocked` drops its "must be `CredentialStateClient`" precondition in favour of "client has an API key or a live grant". Startup check: for a client with both, the API-key record wins and the mismatch is logged at WARN. +- **Finding (review)**: the binding is also written by connect rollback (`clients_service_connect.go:355`), by mint and replacement mint (`client_credentials.go:156-219`) and by profile rename/reassign through `RepinProfile` / `RestorePins` (`internal/storage/agent_token_repin.go`, called from `internal/runtime/config_funnel.go:126-143`). Profile users are found through `ListAgentTokens()` in `internal/runtime/profiles_service.go`. +- **Decision**: new bucket `oauth_client_bindings`, key = client id, value `{pin, mode, display_name, updated_at}`. A transaction-local helper `writeClientBindingTx(tx, clientID, pin, mode)` writes the API-key record if present and the OAuth record if present; it fails only if neither exists. Update, mint, reconnect, rollback, repin and restore all call it inside their own transaction. Minting an API key for a client that has only browser logins writes the binding the caller asked for to both records. `profiles_service.go` gets a `ListClientBindings()` view that includes OAuth-only clients. `setBindingLocked` drops its "must be `CredentialStateClient`" precondition in favour of "client has an API key or a live grant". Startup check: for a client with both, the API-key record wins and the mismatch is logged at WARN. - **Alternatives**: single new bucket for all bindings (rejected: downgrade reads the stale API-key record, FR-028); credential-less `AgentToken` (rejected: fails invariants on older binaries and pollutes token lists). ## R5. The binding guard - **Finding**: `ActiveNamedBinding(t, now)` (`internal/runtime/binding_guard.go:114`) and the evaluator in `internal/server/profile_binding_guard.go` (`BindingGuardActiveBindings` at 186, `activeNamedClientBinding` at 76) read `auth.AgentToken` only. Fixes are `require_mcp_auth` and `set_anonymous_profile` (`internal/profile/contract.go:192`). -- **Decision**: the evaluator's set of active bindings becomes the union of (a) today's records and (b) clients in `oauth_client_bindings` with a named pin and at least one grant that is neither revoked nor lapsed. `BindingRef` is unchanged (it names client and profile). Approval calls `CheckBindingGuard` with the candidate binding before any write; the consent REST `GET` returns the guard's verdict and fixes so the page can show them first (FR-022). +- **Finding (review)**: `GuardState` holds only `Tokens []auth.AgentToken` (`binding_guard.go:44-47`); `BindingGuardDelta` and `BindingGuardFixes` evaluate explicit current and candidate snapshots (`profile_binding_guard.go:118-180`), and config changes build token-only candidates (`config_funnel.go:102-112`, `218-224`). +- **Decision**: `GuardState` gains `OAuthBindings []OAuthBinding{ClientID, Pin, Mode, Live}`. Every snapshot producer (clients service, credentials service, config funnel, offline CLI, anonymous-profile check) fills it from storage; a read error refuses the change. An approval builds the candidate by adding or replacing its own client's entry with `Live: true` before anything is stored. Delta, fixes, `ConservativeBindingGuard` and `StrictOfflineBindingGuard` treat an entry with a named pin and `Live` as an active binding, deduplicated with the API-key record of the same client. `BindingRef` is unchanged (it names client and profile). Approval calls `CheckBindingGuard` with the candidate binding before any write; the consent REST `GET` returns the guard's verdict and fixes so the page can show them first (FR-022). ## R6. Refresh tokens - **Decision**: `mcp_ort___`; `grantID` 16 random bytes (base62), `secret` 32 random bytes, `mac = HMAC-SHA256(key, "ort|"+grantID+"|"+secret)` truncated to 16 bytes. Key: `auth.GetOrCreateHMACKey(dataDir)` (`agent_token.go:580`), the key agent tokens already use, with a distinct label so the MAC can never collide with a token hash. Stored: `HashToken(secret, key)` and a 12-character prefix. -- **Check order** (FR-009): parse and MAC → load grant → compare secret hash in constant time → rotate or revoke, in one `db.Update`. +- **Check order** (FR-009, FR-032): parse and MAC → load grant → revoked or `refresh_expires_at` passed → `invalid_grant`, no write, lifetime not extended → compare secret hash in constant time → rotate or revoke, in one `db.Update`. - **Access token**: `mcp_oat_`, stored hashed in the grant (`access_hash`, `access_expires_at`); one live access token per grant. A second index bucket is not needed: the lookup key is the hash, kept in `oauth_grants` under a sub-bucket `by_access_hash → grant id`. ## R7. Loopback only @@ -62,7 +65,8 @@ Code references are from `main` at `dfc3d418f`. Product decisions and their alte - **Finding**: `initBuckets` (`internal/storage/bbolt.go:160`) creates a fixed list at open; other buckets (`agent_tokens`, `tpa_bundle_state`, …) are created with `CreateBucketIfNotExists` in the write path and readers treat a nil bucket as empty. Markers live in `MetaBucket` (`markOAuthCompactAdvisedTx`, `oauth_binding.go:110`). - **Decision**: all three buckets are lazy; nothing is added to `initBuckets`. `oauth_login_ever_used` is written in the transaction that stores the first grant. A test opens a database, runs a default-off server through the e2e route table, and asserts the bucket list is unchanged. -- **Purge**: `ForgetClientCredential` path gains `forgetOAuthClientTx(tx, clientID)`. +- **Finding (review)**: `ForgetClientCredential` is shared by client forget and client revoke (`clients_service.go:695-724`), and its restoring variant aborts a failed connect (`clients_service_connect.go:393-399`). +- **Decision**: four distinct storage operations. `ForgetClient` deletes the API-key record, all grants, the OAuth binding and registrations left without a grant. `RevokeClient` marks the API key and every grant revoked and keeps them for display. `RevokeClientAPIKey` touches the API-key record only. Connect rollback (`ForgetClientCredentialRestoringPrior`) touches the API-key record only and restores the binding through `writeClientBindingTx`. ## R11. Config field @@ -78,3 +82,8 @@ Code references are from `main` at `dfc3d418f`. Product decisions and their alte - **Open risk carried from the design**: the issuer is `http://127.0.0.1:`. RFC 8414 and the MCP authorization spec ask for HTTPS. Whether each client accepts it, and whether it follows protected-resource metadata for a path below the MCP root, is an empirical question. - **Decision**: a PR-1 gate. Run Claude Code, Cursor, VS Code and MCP Inspector against a built core on a per-client path; record for each: discovery, registration name, redirect URI shape, token exchange, refresh. Results go to `verification/real-clients.md` and decide (a) `SupportsBrowserLogin` per client and (b) the docs' supported list. If no client completes the flow over plain HTTP, stop and report before PR-2: the fallback is serving the OAuth endpoints only when local TLS is on. + +## R14. The initialize-name warning + +- **Finding**: the name a client sends at `initialize` is already recorded for presence (`clientidentity`, `ClientInfoNames` matching in `internal/connect/clients.go`). +- **Decision**: at `initialize` on an OAuth address, store the sanitised name on the grant (`observed_client_name`, `observed_at`), off the request path like last-used. The mismatch is derived on read: the observed name, normalised, is neither the registration's reported name nor, for a registry client, one of its id, display name or `ClientInfoNames`. It is advisory, shown per login, and takes no part in selection or authorization. From 001c805c3e4bd73a45003394d633078c516f63b4 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sun, 22 Nov 2026 17:01:01 +0200 Subject: [PATCH 09/15] docs(spec): address plan review round 1 in tasks for spec 131 Related #1971 --- specs/131-client-oauth-login/tasks.md | 34 +++++++++++++-------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/specs/131-client-oauth-login/tasks.md b/specs/131-client-oauth-login/tasks.md index b34dbc04e..d5f681d0a 100644 --- a/specs/131-client-oauth-login/tasks.md +++ b/specs/131-client-oauth-login/tasks.md @@ -14,7 +14,7 @@ Tasks are grouped by the three delivery PRs. Each PR is merged before the next s ### Phase 1: Setup -- [ ] T001 Create package `internal/mcplogin/` with `doc.go` stating its scope (pure protocol logic, stdlib only) and add it to the import-boundary check if one applies (`scripts/` lint config) +- [ ] T001 Create package `internal/mcplogin/` with `doc.go` stating its scope (pure protocol logic; no new external dependencies; may import only `internal/auth`, `internal/clientidentity` and `internal/upstream/limiter` from this repo) and add it to the import-boundary check if one applies (`scripts/` lint config) - [ ] T002 [P] Create `tests/oauthclient/` with a scripted public client (`client.go`: discovery, register, authorize with a loopback listener, exchange, refresh) used by tests and the e2e script ### Phase 2: Foundational — switch and default-off equivalence (US1) @@ -23,9 +23,9 @@ Tasks are grouped by the three delivery PRs. Each PR is merged before the next s - [ ] T003 [US1] Test `TestConfig_MCPOAuthEnabled_DefaultOffAndOmitted` in `internal/config/mcp_oauth_test.go`: default false, absent from a saved default config, env `MCPPROXY_MCP_OAUTH_ENABLED` overrides and is not persisted - [ ] T004 [US1] Add `MCPOAuthEnabled` (`mcp_oauth_enabled,omitempty`) to `internal/config/config.go`, `FieldMCPOAuthEnabled` + `envOverride` in `internal/config/process_overrides.go` and `internal/config/loader.go`, hot field in `internal/runtime/config_hotreload.go` -- [ ] T005 [US1] Test `TestOAuthLogin_DefaultOff_RoutesUnchanged` in `internal/server/oauth_login_default_off_test.go`: for `/mcp/oauth`, `/mcp/oauth/cursor`, `/oauth/register`, `/oauth/authorize`, `/oauth/token`, both `/.well-known/oauth-*` paths, over GET/POST with and without credentials, the gated handler's status, body and auth-relevant headers equal those of the previous handler (`mcpHandler` or the root handler) +- [ ] T005 [US1] Test `TestOAuthLogin_DefaultOff_RoutesUnchanged` in `internal/server/oauth_login_default_off_test.go`: for `/mcp/oauth`, `/mcp/oauth/`, `/mcp/oauth/cursor`, `/oauth/register`, `/oauth/authorize`, `/oauth/token`, both `/.well-known/oauth-*` paths, over GET/POST with and without credentials, the complete mux with the new registrations answers exactly like the mux without them (status, body, `Location`, auth-relevant headers), including `/oauth`, `/oauth/`, `/oauth/x`, `/.well-known/oauth-protected-resource` and slash/no-slash variants - [ ] T006 [US1] Test `TestOAuthLogin_DefaultOff_NoStorage` in `internal/server/oauth_login_default_off_test.go`: after the requests of T005 the bbolt bucket list and `MetaBucket` keys are unchanged -- [ ] T007 [US1] Implement the three-state gate in `internal/server/oauth_login_routes.go` (`oauthLoginGate(prev, served)`: off+never-used → `prev`, off+used → 404, on → `served`; loopback peer + loopback Host + personal edition else 404) and register the five patterns in `startCustomHTTPServer` (`internal/server/server.go`), with `served` a 501 stub for now +- [ ] T007 [US1] Implement the three-state gate in `internal/server/oauth_login_routes.go` (`oauthLoginGate(prev, served)`: off+never-used → `prev`, off+used → 404, on → `served`; loopback peer + loopback Host + personal edition else 404) and register the exact patterns and two subtrees listed in research R1 (no `/oauth/` subtree) in `startCustomHTTPServer` (`internal/server/server.go`), with `served` a 501 stub for now - [ ] T008 [P] [US1] Test and implement `peerIsLoopback(r)` in `internal/server/oauth_login_routes.go` (`oauth_login_routes_test.go`: IPv4, IPv6, non-loopback, unix socket, malformed) - [ ] T009 [US1] Run `make swagger`; add `mcp_oauth_enabled` to `docs/configuration/config-file.md` @@ -45,30 +45,30 @@ Tasks are grouped by the three delivery PRs. Each PR is merged before the next s ### Phase 4: Storage - [ ] T018 [US2] Tests in `internal/storage/oauth_login_test.go` for registrations: create, get, state moves, expiry sweep (15 min / 24 h), cap of 50 non-approved -- [ ] T019 [US2] Tests in `internal/storage/oauth_login_test.go` for grants: create with first-grant marker in the same tx, lookup by access hash, `RotateOrRevoke` (current secret → rotate; authentic old secret → revoke `replay`; unknown/revoked → no write, asserted by tx id), lapse after 30 days, retention of dead grants +- [ ] T019 [US2] Tests in `internal/storage/oauth_login_test.go` for grants: create with first-grant marker in the same tx, lookup by access hash, `RotateOrRevoke` (current secret → rotate; authentic old secret → revoke `replay`; unknown, revoked or expired → no write and no lifetime extension, asserted by tx id), lapse after 30 days, retention of dead grants - [ ] T020 [US2] Implement `internal/storage/oauth_login.go` for T018–T019 with lazy buckets `oauth_registrations`, `oauth_grants` (+ `by_access_hash`), marker `oauth_login_ever_used` -- [ ] T021 [US3] Tests in `internal/storage/client_binding_dual_test.go`: `UpdateClientCredentialBinding` writes the API-key record and `oauth_client_bindings` in one tx; works for an OAuth-only client; fails when neither exists; startup repair takes the API-key record -- [ ] T022 [US3] Implement T021 in `internal/storage/client_credentials.go` and `internal/storage/oauth_login.go`; add `forgetOAuthClientTx` to the `ForgetClientCredential` path -- [ ] T023 [P] [US3] Test `TestDowngradeView_APIKeyRecordStaysCurrent` in `internal/storage/client_binding_dual_test.go`: after a reassign of a client with both credentials, the raw `agent_tokens` record carries the new pin and mode (FR-028) +- [ ] T021 [US3] Tests in `internal/storage/client_binding_dual_test.go`: `writeClientBindingTx` writes the API-key record and `oauth_client_bindings` in one tx for every writer (update, mint for an OAuth-only client, reconnect, connect rollback, `RepinProfile`, `RestorePins`); works for an OAuth-only client; fails when neither exists; startup repair takes the API-key record; source test that no other code in `internal/storage` assigns `ProfilePin`/`ProfileMode` of a client record +- [ ] T022 [US3] Test `TestDowngradeView_APIKeyRecordStaysCurrent` in `internal/storage/client_binding_dual_test.go`: after a reassign, a rename and a reconnect of a client with both credentials, the raw `agent_tokens` record carries the current pin and mode (FR-028) +- [ ] T023 [US3] Tests in `internal/storage/oauth_login_client_ops_test.go` then code in `internal/storage/oauth_login.go`, `internal/storage/client_credentials.go`, `internal/storage/agent_token_repin.go`: implement `writeClientBindingTx` for T021–T022 and the four separate operations `ForgetClient` (deletes grants, OAuth binding, orphan registrations), `RevokeClient` (marks key and all grants revoked, keeps them), `RevokeClientAPIKey`, and connect rollback that leaves grants untouched ### Phase 5: Runtime service, binding, guard -- [ ] T024 [US2] Add `CredentialKindOAuth` to `internal/auth/context.go` and `auth.ClientAuthContext(...)` to `internal/auth/agent_token.go`; make `(*AgentToken).AuthContext` use it; test in `internal/auth/agent_token_identity_test.go` that both paths give equal contexts except the kind +- [ ] T024 [US2] Test first in `internal/auth/agent_token_identity_test.go`, then add `CredentialKindOAuth` and `AuthContext.GrantID` to `internal/auth/context.go` and `auth.ClientAuthContext(ClientIdentity)` to `internal/auth/agent_token.go`; `(*AgentToken).AuthContext` uses it; both paths give equal contexts except kind, grant id, prefix and generation (research R3); tests in `internal/server` that work-session grouping separates two logins of one client and that session-backed activity carries the grant id - [ ] T025 [US2] Source test `TestCredentialKindAgentTokenSitesClassified` in `internal/auth/credential_kind_sites_test.go`: every comparison with `CredentialKindAgentToken` in `internal/` is listed as "applies to oauth" or "API-key specific"; fix the sites it finds - [ ] T026 [US2] Tests in `internal/runtime/oauth_login_service_test.go` for `Describe(requestID)`: fixed client on a per-client address, generic address lists clients with none pre-selected, `profile_required`, `previous_login` only for the same registration, guard verdict included, reported name never selects anything -- [ ] T027 [US2] Tests in `internal/runtime/oauth_login_service_test.go` for `Approve`/`Deny`: creates client binding and grant, `already_decided`, `binding_changed` on a stale revision, `client_fixed`, `profile_required`, new custom client id rules (`identity_exists`, `reserved_identity`), `replace_grant` revokes the old login, activity rows `approve`/`deny` with the request actor +- [ ] T027 [US2] Tests in `internal/runtime/oauth_login_service_test.go` for `Approve`/`Deny`: creates client binding and grant, `already_decided`, `binding_changed` on a stale revision, `client_fixed`, `profile_required`, new custom client id rules (`identity_exists`, `reserved_identity`), `replace_grant` revokes the old login, activity rows `approve`/`deny` with the request actor; and for `Exchange`/`Refresh`: PKCE, client and redirect binding, resource and issuer substitution, code expiry and reuse within the tombstone window, refresh expiry without extension, rotation, authentic replay, forged token with a real grant id; activity rows `issue` and `replay_revoke` naming `approved_by` with `trigger: client`; `revoke` naming the request actor - [ ] T028 [US2] Implement `internal/runtime/oauth_login_service.go` (`OAuthLoginService`: `Describe`, `Approve`, `Deny`, `Exchange`, `Refresh`, `Authenticate`, `ListGrants`, `RevokeGrant`) under `bindingWriteMu`; wire in `internal/runtime/runtime.go`; add `approve`, `deny`, `replay_revoke` to `internal/profile/contract.go`; add events to `internal/runtime/events.go` and to `adminConfigEventTypes` in `internal/httpapi/sse_scope.go` -- [ ] T029 [US3] Tests in `internal/runtime/clients_service_test.go`: `SetBinding` and `BulkAssign` on an OAuth-only client; `Forget` deletes grants; client revoke revokes key and all grants; profile delete reports an OAuth-only client in `profile_in_use`; rename moves its pin -- [ ] T030 [US3] Implement T029 in `internal/runtime/clients_service.go` and `internal/runtime/credentials_service.go` (revoke cascade, single-grant revoke, API-key-only revoke, grants in `List`/`Get`) -- [ ] T031 [US2] Tests in `internal/runtime/binding_guard_strict_test.go` and `internal/server/profile_binding_guard_test.go`: an OAuth-only client with a named pin and a live grant is an active binding; lapsed or revoked grants are not; approval with `require_mcp_auth` off returns `binding_bypassable_without_auth` with the guard's fixes -- [ ] T032 [US2] Implement T031 in `internal/runtime/binding_guard.go` and `internal/server/profile_binding_guard.go` +- [ ] T029 [US3] Tests in `internal/runtime/clients_service_test.go`, `internal/runtime/profiles_service_test.go` and the config-funnel tests (`internal/runtime/config_funnel_test.go`): `SetBinding` and `BulkAssign` on an OAuth-only client; `Forget` deletes grants; client revoke revokes key and all grants; profile delete reports an OAuth-only client in `profile_in_use`, `reassign_to` moves it, a failed funnel commit restores it; rename moves its pin in both records; minting an API key for an OAuth-only client keeps one binding +- [ ] T030 [US3] Implement T029 in `internal/runtime/clients_service.go`, `internal/runtime/clients_service_connect.go`, `internal/runtime/credentials_service.go`, `internal/runtime/profiles_service.go` and `internal/runtime/config_funnel.go` (revoke cascade, single-grant revoke, API-key-only revoke, grants in `List`/`Get`) +- [ ] T031 [US2] Tests in `internal/runtime/binding_guard_strict_test.go` and `internal/server/profile_binding_guard_test.go`: `GuardState.OAuthBindings` is filled by every snapshot producer (clients service, credentials service, config funnel, offline CLI, anonymous-profile change); an OAuth-only client with a named pin and a live grant is an active binding in delta, fixes, conservative and strict-offline guards; lapsed or revoked grants are not; a first approval is evaluated through its candidate entry before anything is stored; a client with both credentials counts once; a storage read error refuses the change; approval with `require_mcp_auth` off returns `binding_bypassable_without_auth` with the guard's fixes +- [ ] T032 [US2] Implement T031 in `internal/runtime/binding_guard.go`, `internal/server/profile_binding_guard.go`, `internal/runtime/config_funnel.go` and the offline guard wiring in `cmd/mcpproxy` ### Phase 6: HTTP endpoints and authentication - [ ] T033 [US2] Tests in `internal/server/oauth_login_http_test.go` for metadata and the `401` challenge on `/mcp/oauth` and `/mcp/oauth/{client}`, unknown client id → 404 everywhere -- [ ] T034 [US2] Tests in `internal/server/oauth_login_http_test.go` for `/oauth/register`, `/oauth/authorize` (no redirect on bad client/redirect URI, `invalid_target`, `state` round trip, `no-store`, `Referrer-Policy`) and `/oauth/token` (every row of the error table in `contracts/oauth-endpoints.md`, `resource` substitution, size and rate limits) +- [ ] T034 [US2] Tests in `internal/server/oauth_login_http_test.go` for `/oauth/register`, `/oauth/authorize` (no redirect on bad client/redirect URI, `404` without redirect for an unknown per-client resource, `invalid_target`, redirects that keep an existing callback query and return `state` only when sent and unchanged including reserved characters, `no-store`, `Referrer-Policy`) and `/oauth/token` (every row of the error table in `contracts/oauth-endpoints.md`, a current refresh token after 30 days, `resource` substitution, size and rate limits) - [ ] T035 [US2] Implement `internal/server/oauth_login_http.go` and replace the 501 stub from T007 -- [ ] T036 [US2] Tests in `internal/server/oauth_login_auth_test.go`: `mcp_oat_` accepted only on its own resource and origin; API key, `mcp_cli_`, `mcp_agt_`, no token → 401 on OAuth addresses even with `require_mcp_auth` off; `mcp_oat_` on `/mcp` and routing-mode routes → 401 while the feature is on or was used, unchanged anonymous behaviour while off and never used; revoked or lapsed grant → 401 on the next request of an open session; profile scope and activity attribution equal the same client's `mcp_cli_` request +- [ ] T036 [US2] Tests in `internal/server/oauth_login_auth_test.go`: `mcp_oat_` accepted only on its own resource and origin; API key, `mcp_cli_`, `mcp_agt_`, no token → 401 on OAuth addresses even with `require_mcp_auth` off; `mcp_oat_` on `/mcp` and routing-mode routes → 401 while the feature is on or was used, unchanged anonymous behaviour while off and never used; revoked or lapsed grant → 401 on the next request of an open session; the name sent at `initialize` is stored on the grant and the mismatch flag is derived as in research R14; profile scope and activity attribution equal the same client's `mcp_cli_` request - [ ] T037 [US2] Implement `oauthResourceAuth` and the `mcp_oat_` branch of `mcpAuthMiddleware` in `internal/server/server.go`; record `grant_id` and credential kind on activity rows - [ ] T038 [US7] Tests in `internal/server/oauth_login_toggle_test.go`: on → off after use gives 404 on all OAuth paths and cancels pending requests; forgetting the last client keeps 404; off → on restores logins; toggling needs no restart (config reload event) - [ ] T039 [US7] Implement the toggle handling: cached gate state refreshed on `EventTypeConfigReloaded` and on first grant in `internal/server/oauth_login_routes.go` @@ -77,7 +77,7 @@ Tasks are grouped by the three delivery PRs. Each PR is merged before the next s - [ ] T040 [US2] Tests in `internal/httpapi/oauth_login_test.go` for `GET /oauth/authorizations`, `GET /oauth/authorizations/{id}`, `POST …/approve`, `POST …/deny`: payloads and error codes of `contracts/rest-admin.md`, uniform 404, `403` for agent tokens and client credentials, `404 feature_disabled` when off - [ ] T041 [US2] Implement `internal/httpapi/oauth_login.go`, register under `/api/v1` in `internal/httpapi/server.go`, classify the GETs for `scope_route_table_guard_test.go`, run `make swagger` -- [ ] T042 [US3] Tests then code in `internal/httpapi/clients.go` and `internal/httpapi/client_bindings.go`: `credentials[]` and `browser_login_disabled` on client payloads, `DELETE /clients/{client}/logins/{grant_id}`, `DELETE /clients/{client}/api-key` (tests in `internal/httpapi/clients_routes_test.go`); update `internal/contracts` types and regenerate frontend types +- [ ] T042 [US3] Tests then code in `internal/httpapi/clients.go` and `internal/httpapi/client_bindings.go`: `credentials[]` (with `observed_name`, `name_mismatch`) and `browser_login_disabled` on client payloads in the three states (off never used: payload unchanged; on; off after use: logins listed, disabled true), `DELETE /clients/{client}/logins/{grant_id}`, `DELETE /clients/{client}/api-key` (tests in `internal/httpapi/clients_routes_test.go`); update `internal/contracts` types and regenerate frontend types ### Phase 8: End to end and real clients @@ -107,7 +107,7 @@ Tasks are grouped by the three delivery PRs. Each PR is merged before the next s ### Phase 11: Clients hub and management (US3) -- [ ] T056 [US3] Vitest `frontend/tests/unit/client-credentials.spec.ts`: credential list per client (API key, logins with state), revoke one login, revoke API key only, "browser login disabled" label, initialize-name mismatch warning +- [ ] T056 [US3] Vitest `frontend/tests/unit/client-credentials.spec.ts`: credential list per client (API key, logins with state), revoke one login, revoke API key only, "browser login disabled" label with logins still listed, initialize-name mismatch warning per login - [ ] T057 [US3] Implement `frontend/src/components/clients/ClientCredentials.vue` and use it in `frontend/src/views/Clients.vue` - [ ] T058 [P] [US3] Tests then code: `credentials` MCP tool lists logins and revokes one (`grant=`), never creates one — `internal/server/mcp_credentials*.go` and its tests - [ ] T059 [P] [US3] Tests then code: CLI `mcpproxy client show` lists credentials and `mcpproxy client revoke-login ` in `cmd/mcpproxy/client_cmd.go`, `cmd/mcpproxy/client_binding_cmd.go` From 8dccf7df92d53295f9b10fc87975f97a4a31a575 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sun, 22 Nov 2026 17:04:00 +0200 Subject: [PATCH 10/15] docs(spec): address plan review round 2 for spec 131 Related #1971 --- .../contracts/oauth-endpoints.md | 6 ++++++ .../contracts/rest-admin.md | 18 ++++++++++++++++-- specs/131-client-oauth-login/data-model.md | 8 ++++++-- specs/131-client-oauth-login/plan.md | 2 ++ specs/131-client-oauth-login/research.md | 17 ++++++++++++++--- specs/131-client-oauth-login/tasks.md | 14 +++++++------- 6 files changed, 51 insertions(+), 14 deletions(-) diff --git a/specs/131-client-oauth-login/contracts/oauth-endpoints.md b/specs/131-client-oauth-login/contracts/oauth-endpoints.md index 7b19b5daf..e531cb510 100644 --- a/specs/131-client-oauth-login/contracts/oauth-endpoints.md +++ b/specs/131-client-oauth-login/contracts/oauth-endpoints.md @@ -76,6 +76,10 @@ Every redirect (these two and the error redirects above) is built by parsing the Form-encoded, at most 16 KiB. Answers carry `Cache-Control: no-store`. +The origin of the token request must equal the issuer stored with the code or the grant. This is checked first, for both grant types: on a mismatch the answer is `invalid_grant` and nothing is consumed, rotated or revoked. + +The authorization-code exchange is where the login is stored (data-model, research R15). If the client's binding changed since approval, or the binding guard now refuses it, the answer is `invalid_grant` and nothing is stored. + **`grant_type=authorization_code`**: `code`, `redirect_uri`, `client_id`, `code_verifier`, `resource` (optional; if present must equal the approved one). **`grant_type=refresh_token`**: `refresh_token`, `client_id`, `resource` (optional, same rule). @@ -91,6 +95,8 @@ Errors (`400` JSON `{error, error_description}`): | Case | `error` | Side effect | |---|---|---| | unknown, expired or already used code; wrong verifier, client or redirect URI | `invalid_grant` | a code reused within 10 minutes revokes the grant it produced | +| request origin differs from the stored issuer | `invalid_grant` | none | +| binding changed or guard refuses at exchange | `invalid_grant` | none; `deny` activity row | | refresh token malformed, bad MAC, unknown, revoked or expired grant, wrong `client_id` | `invalid_grant` | **none**; all indistinguishable; an expired login is never extended | | authentic refresh token that is not the current one | `invalid_grant` | grant revoked (`replay`) | | `resource` differs from the approved one | `invalid_target` | none | diff --git a/specs/131-client-oauth-login/contracts/rest-admin.md b/specs/131-client-oauth-login/contracts/rest-admin.md index 339e1d9e5..f0c78fc19 100644 --- a/specs/131-client-oauth-login/contracts/rest-admin.md +++ b/specs/131-client-oauth-login/contracts/rest-admin.md @@ -1,6 +1,6 @@ # Contract: administrator surfaces -All REST routes are under `/api/v1`, use the standard `{success, data}` envelope, require administrator credentials (admin API key or tray socket) and answer `403` to agent tokens and client credentials. With the feature off the sign-in request routes answer `404 feature_disabled`. Client payloads depend on whether the feature was ever used: never used → exactly today's payload, no new fields; used → logins are still listed and `browser_login_disabled` is `true`. Revoking a login works in both on and off-after-use states. +All REST routes are under `/api/v1`, use the standard `{success, data}` envelope, require administrator credentials (admin API key or tray socket) and answer `403` to agent tokens and client credentials. With the feature off the sign-in request routes answer `404 feature_disabled`. Client payloads depend on whether the feature was ever used: never used → exactly today's payload, no new fields; used → the new fields are present and logins are listed. `browser_login_disabled` reflects only whether the feature is off right now: `false` while on, `true` while off after use. Revoking a login works in both on and off-after-use states. ## Sign-in requests @@ -29,14 +29,28 @@ Pending requests, newest first: `[{id, client_label, created_at, expires_at}]`. "profiles": [ { "name": "dev-readonly" } ], "profile_required": true, // profiles exist and the client has no binding "previous_login": { "grant_id": "…", "approved_at": "…" }, // same registration signed in before - "guard": null // or { "code": "binding_bypassable_without_auth", "bindings": [...], "fixes": [...] } + "guard": null // only when the address fixes a client that has a binding; else absent, use preview } ``` `404` for an unknown, expired, decided or cancelled id (one uniform answer). +### `POST /oauth/authorizations/{id}/preview` + +Read-only. Body: the same `client`, `profile`, `mode` as approve. Answer: + +```jsonc +{ "complete": true, + "access": { "client": "cursor", "profile": "dev-readonly", "mode": "locked", "same_access_as_existing_client": true }, + "guard": null } // or { "code": "binding_bypassable_without_auth", "bindings": [...], "fixes": [...] } +``` + +`complete: false` (and no verdict) while a required choice is missing. Same `422` codes as approve for an invalid choice. Writes nothing. + ### `POST /oauth/authorizations/{id}/approve` +Records the decision and issues the code. The login itself is stored when the client exchanges the code. + ```jsonc { "client": { "id": "cursor" }, // generic address: existing id, or diff --git a/specs/131-client-oauth-login/data-model.md b/specs/131-client-oauth-login/data-model.md index ee68d3cdf..c748df332 100644 --- a/specs/131-client-oauth-login/data-model.md +++ b/specs/131-client-oauth-login/data-model.md @@ -24,6 +24,7 @@ Lifecycle: `pending` rows are deleted 15 minutes after creation, `authorized` (r | `grant_id` | string | 22 random base62 chars | | `registration_id` | string | the `client_id` above | | `client` | string | Clients hub client id; passes `auth.ValidClientID` | +| `redirect_uri` | string | the registered redirect URI actually used; `redirect_host` in listings comes from it | | `resource` | string | full URI approved, immutable | | `issuer` | string | origin approved, immutable | | `refresh_hash`, `refresh_prefix` | string | HMAC-SHA256 of the current refresh secret; first 12 chars of the token | @@ -38,6 +39,8 @@ Lifecycle: `pending` rows are deleted 15 minutes after creation, `authorized` (r Sub-bucket `by_access_hash`: `access_hash → grant_id`. +A grant is created at the token exchange, not at approval (research R15). + State: `live` (not revoked, `refresh_expires_at` in the future) → `lapsed` (refresh expired) or `revoked`. Neither comes back. A lapsed or revoked grant is kept for display for 30 days, then deleted. ## Client binding for browser logins — bucket `oauth_client_bindings`, key client id @@ -51,7 +54,7 @@ State: `live` (not revoked, `refresh_expires_at` in the future) → `lapsed` (re Invariants: -- Exists exactly for clients that have at least one grant record. +- Exists exactly for clients that have at least one grant record; it is created in the transaction that stores the client's first grant. - If the client also has an API-key record, `profile_pin` and `profile_mode` equal that record's `ProfilePin` and `ProfileMode`. One storage function writes both in one transaction. On startup a mismatch is repaired from the API-key record and logged. - **Binding revision**: `sha256(client | pin | mode)` truncated, computed on read; the consent page sends back the revision it displayed. @@ -67,13 +70,14 @@ RFC 3339 time of the first stored grant. Written in the same transaction as that | `registration_id`, `redirect_uri`, `state`, `code_challenge` | validated at `/oauth/authorize`; stored verbatim | | `resource`, `issuer`, `path_client` | `path_client` is the client id from the resource path, empty for the generic address | | `status` | `pending` → `approved` \| `denied` \| `expired` \| `cancelled`; one transition, compare-and-set | +| `decision` | set on approval: client (existing or new), profile, mode, binding revision seen, replace choice, approving actor | | `expires_at` | created + 10 minutes | At most 20 pending requests; a new one beyond that is refused with `temporarily_unavailable`. ## Authorization code — memory only -`code` (32 random bytes, stored hashed), bound to request id, registration, redirect URI, challenge, resource, issuer, chosen client and the decision. Single use, 60 seconds. Consuming it and storing the grant is one step; the entry then stays as a tombstone `{consumed_at, grant_id}` for 10 minutes. A second presentation within that time revokes that grant (`replay`); after it, the code is simply unknown. +`code` (32 random bytes, stored hashed), bound to request id, registration, redirect URI, challenge, resource, issuer, chosen client and the decision. Single use, 60 seconds. Consuming it, re-checking revision and guard, and storing the grant and any new binding is one step (research R15); the entry then stays as a tombstone `{consumed_at, grant_id}` for 10 minutes. A second presentation within that time revokes that grant (`replay`); after it, the code is simply unknown. ## Relationships diff --git a/specs/131-client-oauth-login/plan.md b/specs/131-client-oauth-login/plan.md index 3dcd8659b..615e7509f 100644 --- a/specs/131-client-oauth-login/plan.md +++ b/specs/131-client-oauth-login/plan.md @@ -152,3 +152,5 @@ Full reasoning is in [research.md](./research.md). ## Review Cross-model review of plan, research, data model, contracts and tasks, round 1 (opencode `gpt-6.1-sol`, 2026-11-22): 15 findings, all accepted. Every binding writer goes through one helper; the guard state carries OAuth bindings including the candidate; forget, revoke-client, revoke-key and connect rollback are separate storage operations; exact route patterns avoid new trailing-slash redirects; the full client auth context and grant id are specified; codes carry issuer and a consumed tombstone; the initialize-name warning has storage and a hook; refresh expiry is checked before rotation; profile delete/rename files are in scope; listings after turn-off keep logins; redirect construction, unknown-client 404 at authorize, activity coverage, task order and the package boundary are corrected. + +Round 2 (same reviewer): eight findings, all accepted. A connect on a client with only browser logins snapshots and restores its binding; the login is stored at the token exchange, with revision and guard re-checked there (research R15); the consent page gets a read-only preview call for the guard verdict (R16); the grant keeps the redirect URI used; the token endpoint checks the request origin against the stored issuer first; replay rows name the approving administrator; `browser_login_disabled` reflects current state only; the registration cap covers all non-approved rows. diff --git a/specs/131-client-oauth-login/research.md b/specs/131-client-oauth-login/research.md index e32d9675b..41e65c395 100644 --- a/specs/131-client-oauth-login/research.md +++ b/specs/131-client-oauth-login/research.md @@ -30,7 +30,7 @@ Code references are from `main` at `dfc3d418f`. Product decisions and their alte - **Finding**: the binding lives on the `Kind=client` record; `storage.UpdateClientCredentialBinding(clientID, pin, mode)` (`internal/storage/client_credentials.go:233`) is called only from `ClientsService.setBindingLocked` (`internal/runtime/clients_service.go:539`). There is no index by client id (`findClientTokenRecordLocked` scans). `ValidateTokenInvariants` refuses a client record without a secret hash, expiry or with locked + empty pin. - **Finding (review)**: the binding is also written by connect rollback (`clients_service_connect.go:355`), by mint and replacement mint (`client_credentials.go:156-219`) and by profile rename/reassign through `RepinProfile` / `RestorePins` (`internal/storage/agent_token_repin.go`, called from `internal/runtime/config_funnel.go:126-143`). Profile users are found through `ListAgentTokens()` in `internal/runtime/profiles_service.go`. -- **Decision**: new bucket `oauth_client_bindings`, key = client id, value `{pin, mode, display_name, updated_at}`. A transaction-local helper `writeClientBindingTx(tx, clientID, pin, mode)` writes the API-key record if present and the OAuth record if present; it fails only if neither exists. Update, mint, reconnect, rollback, repin and restore all call it inside their own transaction. Minting an API key for a client that has only browser logins writes the binding the caller asked for to both records. `profiles_service.go` gets a `ListClientBindings()` view that includes OAuth-only clients. `setBindingLocked` drops its "must be `CredentialStateClient`" precondition in favour of "client has an API key or a live grant". Startup check: for a client with both, the API-key record wins and the mismatch is logged at WARN. +- **Decision**: new bucket `oauth_client_bindings`, key = client id, value `{pin, mode, display_name, updated_at}`. A transaction-local helper `writeClientBindingTx(tx, clientID, pin, mode)` writes the API-key record if present and the OAuth record if present; it fails only if neither exists. Update, mint, reconnect, rollback, repin and restore all call it inside their own transaction. Minting an API key for a client that has only browser logins writes the binding the caller asked for to both records, and first copies the client's OAuth binding into the new record's `PriorProfilePin`/`PriorProfileMode` (today these are captured only from an earlier API-key record, `client_credentials.go:186-200`). An aborted or undone connect restores that snapshot to the OAuth record through `writeClientBindingTx`, so a wider binding from a connect that never took effect cannot stay on the existing logins. `profiles_service.go` gets a `ListClientBindings()` view that includes OAuth-only clients. `setBindingLocked` drops its "must be `CredentialStateClient`" precondition in favour of "client has an API key or a live grant". Startup check: for a client with both, the API-key record wins and the mismatch is logged at WARN. - **Alternatives**: single new bucket for all bindings (rejected: downgrade reads the stale API-key record, FR-028); credential-less `AgentToken` (rejected: fails invariants on older binaries and pollutes token lists). ## R5. The binding guard @@ -54,12 +54,12 @@ Code references are from `main` at `dfc3d418f`. Product decisions and their alte ## R8. Rate limits and caps - **Finding**: no HTTP rate-limit middleware exists. `limiter.TokenRates` (`internal/upstream/limiter/token_rate.go`) is a per-key token bucket with a clock seam and idle sweep. -- **Decision**: one private `TokenRates` in `internal/mcplogin/limits.go`; keys `register|`, `authorize|`, `token|`. Defaults: register 10/min burst 5, authorize 30/min burst 10, token 60/min burst 20. `http.MaxBytesReader` 16 KiB on register and token. Pending registrations capped at 50 (oldest pending dropped). Over limit → `429` with `Retry-After`. +- **Decision**: one private `TokenRates` in `internal/mcplogin/limits.go`; keys `register|`, `authorize|`, `token|`. Defaults: register 10/min burst 5, authorize 30/min burst 10, token 60/min burst 20. `http.MaxBytesReader` 16 KiB on register and token. Registrations that are not approved (`pending` and `authorized`) are capped at 50 together; the oldest of them is dropped. Over limit → `429` with `Retry-After`. ## R9. Events and activity - **Finding**: events are published through an injected `publish func(Event)`; admin-only types are listed in `adminConfigEventTypes` (`internal/httpapi/sse_scope.go`). `writeChangeRecord` (`clients_service.go:444`) is the single `profile_change` builder; `profile.ChangeKind` has no approve/deny. -- **Decision**: new event `oauth.authorization_pending` `{request_id, client_id, client_label}` (admin-only, no reported name beyond the sanitised label) and reuse of `credentials.changed` for grant create/revoke. New change kinds `approve`, `deny`, `replay_revoke`. The actor comes from `runtime.RequestActor(ctx)`; a replay revocation is recorded with actor kind `system`. +- **Decision**: new event `oauth.authorization_pending` `{request_id, client_id, client_label}` (admin-only, no reported name beyond the sanitised label) and reuse of `credentials.changed` for grant create/revoke. New change kinds `approve`, `deny`, `replay_revoke`. `approve`, `deny` and `revoke` take the actor from `runtime.RequestActor(ctx)`. `issue` and `replay_revoke` happen on the public token endpoint: they name the administrator stored in the grant's `approved_by` and add `trigger: client`. ## R10. Storage laziness @@ -87,3 +87,14 @@ Code references are from `main` at `dfc3d418f`. Product decisions and their alte - **Finding**: the name a client sends at `initialize` is already recorded for presence (`clientidentity`, `ClientInfoNames` matching in `internal/connect/clients.go`). - **Decision**: at `initialize` on an OAuth address, store the sanitised name on the grant (`observed_client_name`, `observed_at`), off the request path like last-used. The mismatch is derived on read: the observed name, normalised, is neither the registration's reported name nor, for a registry client, one of its id, display name or `ClientInfoNames`. It is advisory, shown per login, and takes no part in selection or authorization. + +## R15. When a login is stored + +- **Decision**: approval stores nothing in `config.db`. It records the decision (client, profile, mode, replace choice, approving actor) on the in-memory request, writes the `approve` activity row and issues the code. The **token exchange** is the commit: in one transaction it re-checks the binding revision and the guard with the decided candidate, creates the client binding if the client is new, stores the grant (with the redirect URI used, resource, issuer, `approved_by`), revokes the replaced login if asked, and sets the ever-used marker; then it writes the `issue` row. If the re-check fails the exchange answers `invalid_grant`, nothing is stored and a `deny` row with reason `binding_changed` or `guard` is written. +- **Rationale**: an approval the client never completes leaves no login, no client row and no marker. One point of commit also removes the question of what a code refers to. +- **Consequence**: a restart between approval and exchange drops the code; the client starts again. + +## R16. Guard verdict on the consent page + +- **Finding (review)**: on the generic address the client, profile and mode are not known when the page loads, so one `guard` field on the request cannot describe the user's choice. +- **Decision**: `POST /api/v1/oauth/authorizations/{id}/preview` (read-only, admin) takes the proposed client (existing or new), profile and mode and returns the guard verdict, its fixes and the access sentence. The page calls it whenever the selection becomes complete or changes, and enables Approve only on a clean verdict. `GET` returns a verdict only when the address fixes a client that already has a binding. diff --git a/specs/131-client-oauth-login/tasks.md b/specs/131-client-oauth-login/tasks.md index d5f681d0a..83ea7e446 100644 --- a/specs/131-client-oauth-login/tasks.md +++ b/specs/131-client-oauth-login/tasks.md @@ -44,10 +44,10 @@ Tasks are grouped by the three delivery PRs. Each PR is merged before the next s ### Phase 4: Storage -- [ ] T018 [US2] Tests in `internal/storage/oauth_login_test.go` for registrations: create, get, state moves, expiry sweep (15 min / 24 h), cap of 50 non-approved -- [ ] T019 [US2] Tests in `internal/storage/oauth_login_test.go` for grants: create with first-grant marker in the same tx, lookup by access hash, `RotateOrRevoke` (current secret → rotate; authentic old secret → revoke `replay`; unknown, revoked or expired → no write and no lifetime extension, asserted by tx id), lapse after 30 days, retention of dead grants +- [ ] T018 [US2] Tests in `internal/storage/oauth_login_test.go` for registrations: create, get, state moves, expiry sweep (15 min / 24 h), cap of 50 over `pending` and `authorized` rows together with the oldest dropped +- [ ] T019 [US2] Tests in `internal/storage/oauth_login_test.go` for grants: `CommitLogin` stores the grant (with `redirect_uri`), a new client's binding, the replaced login's revocation and the first-grant marker in one tx and writes nothing when its revision check fails, lookup by access hash, `RotateOrRevoke` (current secret → rotate; authentic old secret → revoke `replay`; unknown, revoked or expired → no write and no lifetime extension, asserted by tx id), lapse after 30 days, retention of dead grants - [ ] T020 [US2] Implement `internal/storage/oauth_login.go` for T018–T019 with lazy buckets `oauth_registrations`, `oauth_grants` (+ `by_access_hash`), marker `oauth_login_ever_used` -- [ ] T021 [US3] Tests in `internal/storage/client_binding_dual_test.go`: `writeClientBindingTx` writes the API-key record and `oauth_client_bindings` in one tx for every writer (update, mint for an OAuth-only client, reconnect, connect rollback, `RepinProfile`, `RestorePins`); works for an OAuth-only client; fails when neither exists; startup repair takes the API-key record; source test that no other code in `internal/storage` assigns `ProfilePin`/`ProfileMode` of a client record +- [ ] T021 [US3] Tests in `internal/storage/client_binding_dual_test.go`: `writeClientBindingTx` writes the API-key record and `oauth_client_bindings` in one tx for every writer (update, mint for an OAuth-only client, reconnect, connect rollback, `RepinProfile`, `RestorePins`); a mint for an OAuth-only client snapshots its binding into `PriorProfilePin`/`PriorProfileMode`, and abort or undo restores it to the OAuth record without touching grants; works for an OAuth-only client; fails when neither exists; startup repair takes the API-key record; source test that no other code in `internal/storage` assigns `ProfilePin`/`ProfileMode` of a client record - [ ] T022 [US3] Test `TestDowngradeView_APIKeyRecordStaysCurrent` in `internal/storage/client_binding_dual_test.go`: after a reassign, a rename and a reconnect of a client with both credentials, the raw `agent_tokens` record carries the current pin and mode (FR-028) - [ ] T023 [US3] Tests in `internal/storage/oauth_login_client_ops_test.go` then code in `internal/storage/oauth_login.go`, `internal/storage/client_credentials.go`, `internal/storage/agent_token_repin.go`: implement `writeClientBindingTx` for T021–T022 and the four separate operations `ForgetClient` (deletes grants, OAuth binding, orphan registrations), `RevokeClient` (marks key and all grants revoked, keeps them), `RevokeClientAPIKey`, and connect rollback that leaves grants untouched @@ -56,8 +56,8 @@ Tasks are grouped by the three delivery PRs. Each PR is merged before the next s - [ ] T024 [US2] Test first in `internal/auth/agent_token_identity_test.go`, then add `CredentialKindOAuth` and `AuthContext.GrantID` to `internal/auth/context.go` and `auth.ClientAuthContext(ClientIdentity)` to `internal/auth/agent_token.go`; `(*AgentToken).AuthContext` uses it; both paths give equal contexts except kind, grant id, prefix and generation (research R3); tests in `internal/server` that work-session grouping separates two logins of one client and that session-backed activity carries the grant id - [ ] T025 [US2] Source test `TestCredentialKindAgentTokenSitesClassified` in `internal/auth/credential_kind_sites_test.go`: every comparison with `CredentialKindAgentToken` in `internal/` is listed as "applies to oauth" or "API-key specific"; fix the sites it finds - [ ] T026 [US2] Tests in `internal/runtime/oauth_login_service_test.go` for `Describe(requestID)`: fixed client on a per-client address, generic address lists clients with none pre-selected, `profile_required`, `previous_login` only for the same registration, guard verdict included, reported name never selects anything -- [ ] T027 [US2] Tests in `internal/runtime/oauth_login_service_test.go` for `Approve`/`Deny`: creates client binding and grant, `already_decided`, `binding_changed` on a stale revision, `client_fixed`, `profile_required`, new custom client id rules (`identity_exists`, `reserved_identity`), `replace_grant` revokes the old login, activity rows `approve`/`deny` with the request actor; and for `Exchange`/`Refresh`: PKCE, client and redirect binding, resource and issuer substitution, code expiry and reuse within the tombstone window, refresh expiry without extension, rotation, authentic replay, forged token with a real grant id; activity rows `issue` and `replay_revoke` naming `approved_by` with `trigger: client`; `revoke` naming the request actor -- [ ] T028 [US2] Implement `internal/runtime/oauth_login_service.go` (`OAuthLoginService`: `Describe`, `Approve`, `Deny`, `Exchange`, `Refresh`, `Authenticate`, `ListGrants`, `RevokeGrant`) under `bindingWriteMu`; wire in `internal/runtime/runtime.go`; add `approve`, `deny`, `replay_revoke` to `internal/profile/contract.go`; add events to `internal/runtime/events.go` and to `adminConfigEventTypes` in `internal/httpapi/sse_scope.go` +- [ ] T027 [US2] Tests in `internal/runtime/oauth_login_service_test.go` for `Preview` (guard verdict and access sentence for a proposed client, profile and mode; `complete: false` while a choice is missing; writes nothing) and `Approve`/`Deny`: approval stores nothing in the database and records the decision on the request; the exchange commits binding and grant after re-checking revision and guard, and answers `invalid_grant` with a `deny` row when either fails; `already_decided`, `binding_changed` on a stale revision, `client_fixed`, `profile_required`, new custom client id rules (`identity_exists`, `reserved_identity`), `replace_grant` revokes the old login, activity rows `approve`/`deny` with the request actor; and for `Exchange`/`Refresh`: PKCE, client and redirect binding, resource substitution, a token request whose origin differs from the stored issuer (refused first, nothing consumed), code expiry and reuse within the tombstone window, refresh expiry without extension, rotation, authentic replay, forged token with a real grant id; activity rows `issue` and `replay_revoke` naming `approved_by` with `trigger: client`; `revoke` naming the request actor +- [ ] T028 [US2] Implement `internal/runtime/oauth_login_service.go` (`OAuthLoginService`: `Describe`, `Preview`, `Approve`, `Deny`, `Exchange`, `Refresh`, `Authenticate`, `ListGrants`, `RevokeGrant`) under `bindingWriteMu`; wire in `internal/runtime/runtime.go`; add `approve`, `deny`, `replay_revoke` to `internal/profile/contract.go`; add events to `internal/runtime/events.go` and to `adminConfigEventTypes` in `internal/httpapi/sse_scope.go` - [ ] T029 [US3] Tests in `internal/runtime/clients_service_test.go`, `internal/runtime/profiles_service_test.go` and the config-funnel tests (`internal/runtime/config_funnel_test.go`): `SetBinding` and `BulkAssign` on an OAuth-only client; `Forget` deletes grants; client revoke revokes key and all grants; profile delete reports an OAuth-only client in `profile_in_use`, `reassign_to` moves it, a failed funnel commit restores it; rename moves its pin in both records; minting an API key for an OAuth-only client keeps one binding - [ ] T030 [US3] Implement T029 in `internal/runtime/clients_service.go`, `internal/runtime/clients_service_connect.go`, `internal/runtime/credentials_service.go`, `internal/runtime/profiles_service.go` and `internal/runtime/config_funnel.go` (revoke cascade, single-grant revoke, API-key-only revoke, grants in `List`/`Get`) - [ ] T031 [US2] Tests in `internal/runtime/binding_guard_strict_test.go` and `internal/server/profile_binding_guard_test.go`: `GuardState.OAuthBindings` is filled by every snapshot producer (clients service, credentials service, config funnel, offline CLI, anonymous-profile change); an OAuth-only client with a named pin and a live grant is an active binding in delta, fixes, conservative and strict-offline guards; lapsed or revoked grants are not; a first approval is evaluated through its candidate entry before anything is stored; a client with both credentials counts once; a storage read error refuses the change; approval with `require_mcp_auth` off returns `binding_bypassable_without_auth` with the guard's fixes @@ -75,7 +75,7 @@ Tasks are grouped by the three delivery PRs. Each PR is merged before the next s ### Phase 7: Admin REST -- [ ] T040 [US2] Tests in `internal/httpapi/oauth_login_test.go` for `GET /oauth/authorizations`, `GET /oauth/authorizations/{id}`, `POST …/approve`, `POST …/deny`: payloads and error codes of `contracts/rest-admin.md`, uniform 404, `403` for agent tokens and client credentials, `404 feature_disabled` when off +- [ ] T040 [US2] Tests in `internal/httpapi/oauth_login_test.go` for `GET /oauth/authorizations`, `GET /oauth/authorizations/{id}`, `POST …/preview`, `POST …/approve`, `POST …/deny`: payloads and error codes of `contracts/rest-admin.md`, uniform 404, `403` for agent tokens and client credentials, `404 feature_disabled` when off - [ ] T041 [US2] Implement `internal/httpapi/oauth_login.go`, register under `/api/v1` in `internal/httpapi/server.go`, classify the GETs for `scope_route_table_guard_test.go`, run `make swagger` - [ ] T042 [US3] Tests then code in `internal/httpapi/clients.go` and `internal/httpapi/client_bindings.go`: `credentials[]` (with `observed_name`, `name_mismatch`) and `browser_login_disabled` on client payloads in the three states (off never used: payload unchanged; on; off after use: logins listed, disabled true), `DELETE /clients/{client}/logins/{grant_id}`, `DELETE /clients/{client}/api-key` (tests in `internal/httpapi/clients_routes_test.go`); update `internal/contracts` types and regenerate frontend types @@ -93,7 +93,7 @@ Tasks are grouped by the three delivery PRs. Each PR is merged before the next s ### Phase 9: Consent page (US2, US5, US4) - [ ] T047 [P] [US2] Add API methods and types for authorizations and client credentials in `frontend/src/services/api.ts` and `frontend/src/types/` -- [ ] T048 [US2] Vitest `frontend/tests/unit/authorize-request.spec.ts`: fixed client view, unverified-name label, access sentence, profile shown not asked when bound, Approve disabled until a profile is chosen when `profile_required`, replace-login checkbox only with `previous_login`, guard refusal with fixes shown before approval, `already_decided` and `binding_changed` handling, navigation to `redirect_url` +- [ ] T048 [US2] Vitest `frontend/tests/unit/authorize-request.spec.ts`: fixed client view, unverified-name label, access sentence, profile shown not asked when bound, Approve disabled until a profile is chosen when `profile_required`, replace-login checkbox only with `previous_login`, guard verdict fetched through the preview call whenever the selection is complete or changes, refusal with fixes shown and Approve disabled until it is clean, `already_decided` and `binding_changed` handling, navigation to `redirect_url` - [ ] T049 [US2] Implement `frontend/src/views/AuthorizeRequest.vue` and the `/authorize` route in `frontend/src/router/index.ts`, reusing `GuardRefusal.vue`, `ProfileChip.vue` - [ ] T050 [US5] Vitest in `frontend/tests/unit/authorize-request.spec.ts` for the generic address: nothing pre-selected, "New client" with editable id and name, existing-client choice shows the access sentence, `identity_exists` / `reserved_identity` errors - [ ] T051 [US5] Implement the generic-address branch in `frontend/src/views/AuthorizeRequest.vue` From 5d23d1df6942fd8331dddb09a6333cddd0eac97d Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sun, 22 Nov 2026 17:06:30 +0200 Subject: [PATCH 11/15] docs(spec): address plan review round 3 for spec 131 Related #1971 --- specs/131-client-oauth-login/contracts/oauth-endpoints.md | 1 + specs/131-client-oauth-login/contracts/rest-admin.md | 2 +- specs/131-client-oauth-login/data-model.md | 8 ++++---- specs/131-client-oauth-login/plan.md | 2 ++ specs/131-client-oauth-login/research.md | 3 ++- specs/131-client-oauth-login/tasks.md | 8 ++++---- 6 files changed, 14 insertions(+), 10 deletions(-) diff --git a/specs/131-client-oauth-login/contracts/oauth-endpoints.md b/specs/131-client-oauth-login/contracts/oauth-endpoints.md index e531cb510..3c12b50b3 100644 --- a/specs/131-client-oauth-login/contracts/oauth-endpoints.md +++ b/specs/131-client-oauth-login/contracts/oauth-endpoints.md @@ -97,6 +97,7 @@ Errors (`400` JSON `{error, error_description}`): | unknown, expired or already used code; wrong verifier, client or redirect URI | `invalid_grant` | a code reused within 10 minutes revokes the grant it produced | | request origin differs from the stored issuer | `invalid_grant` | none | | binding changed or guard refuses at exchange | `invalid_grant` | none; `deny` activity row | +| request cancelled after approval (client revoked or forgotten, feature turned off) | `invalid_grant` | none | | refresh token malformed, bad MAC, unknown, revoked or expired grant, wrong `client_id` | `invalid_grant` | **none**; all indistinguishable; an expired login is never extended | | authentic refresh token that is not the current one | `invalid_grant` | grant revoked (`replay`) | | `resource` differs from the approved one | `invalid_target` | none | diff --git a/specs/131-client-oauth-login/contracts/rest-admin.md b/specs/131-client-oauth-login/contracts/rest-admin.md index f0c78fc19..40fc29b90 100644 --- a/specs/131-client-oauth-login/contracts/rest-admin.md +++ b/specs/131-client-oauth-login/contracts/rest-admin.md @@ -99,7 +99,7 @@ Records the decision and issues the code. The login itself is stored when the cl ## Activity -`profile_change` rows with `change` = `approve` | `deny` | `issue` | `revoke` | `replay_revoke`, metadata `client_id`, `grant_id`, `profile`, `actor_kind`, `actor_name`, `surface`. `approve`, `deny` and `revoke` name the administrator who made the request. `issue` (first token exchange) and `replay_revoke` happen on the public token endpoint: they name the administrator who approved the login (`approved_by`) and add `trigger: "client"`. Tool-call rows of a browser login carry `client_id` and `metadata.grant_id`, credential kind `oauth`. +`profile_change` rows with `change` = `approve` | `deny` | `issue` | `revoke` | `replay_revoke`, metadata `client_id`, `request_id` (rows written before a login exists: `approve`, `deny`), `grant_id` (rows about a stored login: `issue`, `revoke`, `replay_revoke`), `profile`, `actor_kind`, `actor_name`, `surface`. `approve`, `revoke` and a `deny` clicked on the page name the administrator who made the request. Rows written on the public token endpoint (`issue`, `replay_revoke`, and a `deny` caused by the re-check at exchange) name the administrator who approved (`approved_by`) and add `trigger: "client"`. Tool-call rows of a browser login carry `client_id` and `metadata.grant_id`, credential kind `oauth`. ## MCP `credentials` tool diff --git a/specs/131-client-oauth-login/data-model.md b/specs/131-client-oauth-login/data-model.md index c748df332..2d2abee4e 100644 --- a/specs/131-client-oauth-login/data-model.md +++ b/specs/131-client-oauth-login/data-model.md @@ -12,10 +12,10 @@ All persistent records live in `config.db` in buckets created on first write. No | `software_id`, `software_version` | string | optional, sanitised, display only | | `token_endpoint_auth_method` | string | always `none` | | `grant_types` | []string | always `authorization_code`, `refresh_token` | -| `state` | enum | `pending` → `authorized` → `approved`; or `denied` | +| `state` | enum | `pending` → `authorized` → `approved` | | `created_at`, `authorized_at` | time | | -Lifecycle: `pending` rows are deleted 15 minutes after creation, `authorized` (reached `/oauth/authorize`, never approved) after 24 hours. At most 50 non-approved rows; the oldest is dropped. An `approved` row lives while at least one grant references it. +Lifecycle: `pending` rows are deleted 15 minutes after creation, `authorized` (reached `/oauth/authorize`, no login stored yet, whether the request was denied, abandoned or is still open) 24 hours after `authorized_at`. At most 50 rows that are not `approved`; the oldest is dropped. A row becomes `approved` in the transaction that stores its first grant, lives while at least one grant record references it, and is deleted with its last grant record. A denial is not a registration state. ## Grant (browser login) — bucket `oauth_grants`, key `grant_id` @@ -54,7 +54,7 @@ State: `live` (not revoked, `refresh_expires_at` in the future) → `lapsed` (re Invariants: -- Exists exactly for clients that have at least one grant record; it is created in the transaction that stores the client's first grant. +- Exists exactly for clients that have at least one grant record; it is created in the transaction that stores the client's first grant, for a new client and for an existing API-key client alike, from the client's current binding. - If the client also has an API-key record, `profile_pin` and `profile_mode` equal that record's `ProfilePin` and `ProfileMode`. One storage function writes both in one transaction. On startup a mismatch is repaired from the API-key record and logged. - **Binding revision**: `sha256(client | pin | mode)` truncated, computed on read; the consent page sends back the revision it displayed. @@ -69,7 +69,7 @@ RFC 3339 time of the first stored grant. Written in the same transaction as that | `id` | 22 random base62 chars; appears in the consent URL | | `registration_id`, `redirect_uri`, `state`, `code_challenge` | validated at `/oauth/authorize`; stored verbatim | | `resource`, `issuer`, `path_client` | `path_client` is the client id from the resource path, empty for the generic address | -| `status` | `pending` → `approved` \| `denied` \| `expired` \| `cancelled`; one transition, compare-and-set | +| `status` | `pending` → `approved` \| `denied` \| `expired` \| `cancelled`; one decision, compare-and-set. An `approved` request can still become `cancelled` until its code is consumed (client revoked or forgotten, feature turned off) | | `decision` | set on approval: client (existing or new), profile, mode, binding revision seen, replace choice, approving actor | | `expires_at` | created + 10 minutes | diff --git a/specs/131-client-oauth-login/plan.md b/specs/131-client-oauth-login/plan.md index 615e7509f..63d2c72a8 100644 --- a/specs/131-client-oauth-login/plan.md +++ b/specs/131-client-oauth-login/plan.md @@ -154,3 +154,5 @@ Full reasoning is in [research.md](./research.md). Cross-model review of plan, research, data model, contracts and tasks, round 1 (opencode `gpt-6.1-sol`, 2026-11-22): 15 findings, all accepted. Every binding writer goes through one helper; the guard state carries OAuth bindings including the candidate; forget, revoke-client, revoke-key and connect rollback are separate storage operations; exact route patterns avoid new trailing-slash redirects; the full client auth context and grant id are specified; codes carry issuer and a consumed tombstone; the initialize-name warning has storage and a hook; refresh expiry is checked before rotation; profile delete/rename files are in scope; listings after turn-off keep logins; redirect construction, unknown-client 404 at authorize, activity coverage, task order and the package boundary are corrected. Round 2 (same reviewer): eight findings, all accepted. A connect on a client with only browser logins snapshots and restores its binding; the login is stored at the token exchange, with revision and guard re-checked there (research R15); the consent page gets a read-only preview call for the guard verdict (R16); the grant keeps the redirect URI used; the token endpoint checks the request origin against the stored issuer first; replay rows name the approving administrator; `browser_login_disabled` reflects current state only; the registration cap covers all non-approved rows. + +Round 3: four findings, all accepted. Revoke, forget and turn-off cancel approved requests and unconsumed codes under the same lock as the commit; the commit creates the OAuth-side binding whenever it is absent; the registration is promoted in the commit and has no `denied` state; activity rows before a login carry `request_id`, and a refusal at exchange names the approving administrator. diff --git a/specs/131-client-oauth-login/research.md b/specs/131-client-oauth-login/research.md index 41e65c395..2a677d445 100644 --- a/specs/131-client-oauth-login/research.md +++ b/specs/131-client-oauth-login/research.md @@ -90,7 +90,8 @@ Code references are from `main` at `dfc3d418f`. Product decisions and their alte ## R15. When a login is stored -- **Decision**: approval stores nothing in `config.db`. It records the decision (client, profile, mode, replace choice, approving actor) on the in-memory request, writes the `approve` activity row and issues the code. The **token exchange** is the commit: in one transaction it re-checks the binding revision and the guard with the decided candidate, creates the client binding if the client is new, stores the grant (with the redirect URI used, resource, issuer, `approved_by`), revokes the replaced login if asked, and sets the ever-used marker; then it writes the `issue` row. If the re-check fails the exchange answers `invalid_grant`, nothing is stored and a `deny` row with reason `binding_changed` or `guard` is written. +- **Decision**: approval writes no registration, login, binding or marker. It records the decision (client, profile, mode, replace choice, approving actor) on the in-memory request, writes the `approve` activity row (activity is the one thing it persists) and issues the code. The **token exchange** is the commit: under `bindingWriteMu` it confirms the request is still `approved`, then in one transaction re-checks the binding revision and the guard with the decided candidate, creates the OAuth-side binding whenever the client has none (a new client, and also an existing API-key client getting its first login, from that client's current binding), promotes the registration to `approved`, stores the grant (with the redirect URI used, resource, issuer, `approved_by`), revokes the replaced login if asked, and sets the ever-used marker; then it writes the `issue` row. If the re-check fails the exchange answers `invalid_grant`, nothing is stored and a `deny` row with reason `binding_changed` or `guard` is written, naming the decision's approving administrator with `trigger: client`. +- **Cancellation**: revoking a client, forgetting a client and turning the feature off cancel every request that targets that client (by address or by decision), pending or approved, and with it any unconsumed code. They run under the same `bindingWriteMu` as the commit, so an exchange either completes before them (and its grant is then revoked or deleted by them) or finds its request cancelled. The binding revision alone would not catch a revoke, which changes neither pin nor mode. - **Rationale**: an approval the client never completes leaves no login, no client row and no marker. One point of commit also removes the question of what a code refers to. - **Consequence**: a restart between approval and exchange drops the code; the client starts again. diff --git a/specs/131-client-oauth-login/tasks.md b/specs/131-client-oauth-login/tasks.md index 83ea7e446..f8e5d0062 100644 --- a/specs/131-client-oauth-login/tasks.md +++ b/specs/131-client-oauth-login/tasks.md @@ -44,8 +44,8 @@ Tasks are grouped by the three delivery PRs. Each PR is merged before the next s ### Phase 4: Storage -- [ ] T018 [US2] Tests in `internal/storage/oauth_login_test.go` for registrations: create, get, state moves, expiry sweep (15 min / 24 h), cap of 50 over `pending` and `authorized` rows together with the oldest dropped -- [ ] T019 [US2] Tests in `internal/storage/oauth_login_test.go` for grants: `CommitLogin` stores the grant (with `redirect_uri`), a new client's binding, the replaced login's revocation and the first-grant marker in one tx and writes nothing when its revision check fails, lookup by access hash, `RotateOrRevoke` (current secret → rotate; authentic old secret → revoke `replay`; unknown, revoked or expired → no write and no lifetime extension, asserted by tx id), lapse after 30 days, retention of dead grants +- [ ] T018 [US2] Tests in `internal/storage/oauth_login_test.go` for registrations: create, get, state moves, expiry sweep (15 min / 24 h), cap of 50 over `pending` and `authorized` rows together with the oldest dropped; a registration is deleted with its last grant record; there is no `denied` state +- [ ] T019 [US2] Tests in `internal/storage/oauth_login_test.go` for grants: `CommitLogin` stores the grant (with `redirect_uri`), promotes the registration to `approved`, creates the OAuth-side binding whenever the client has none (new client, and API-key-only client getting its first login, with both records equal afterwards), the replaced login's revocation and the first-grant marker in one tx and writes nothing when its revision check fails, lookup by access hash, `RotateOrRevoke` (current secret → rotate; authentic old secret → revoke `replay`; unknown, revoked or expired → no write and no lifetime extension, asserted by tx id), lapse after 30 days, retention of dead grants - [ ] T020 [US2] Implement `internal/storage/oauth_login.go` for T018–T019 with lazy buckets `oauth_registrations`, `oauth_grants` (+ `by_access_hash`), marker `oauth_login_ever_used` - [ ] T021 [US3] Tests in `internal/storage/client_binding_dual_test.go`: `writeClientBindingTx` writes the API-key record and `oauth_client_bindings` in one tx for every writer (update, mint for an OAuth-only client, reconnect, connect rollback, `RepinProfile`, `RestorePins`); a mint for an OAuth-only client snapshots its binding into `PriorProfilePin`/`PriorProfileMode`, and abort or undo restores it to the OAuth record without touching grants; works for an OAuth-only client; fails when neither exists; startup repair takes the API-key record; source test that no other code in `internal/storage` assigns `ProfilePin`/`ProfileMode` of a client record - [ ] T022 [US3] Test `TestDowngradeView_APIKeyRecordStaysCurrent` in `internal/storage/client_binding_dual_test.go`: after a reassign, a rename and a reconnect of a client with both credentials, the raw `agent_tokens` record carries the current pin and mode (FR-028) @@ -56,7 +56,7 @@ Tasks are grouped by the three delivery PRs. Each PR is merged before the next s - [ ] T024 [US2] Test first in `internal/auth/agent_token_identity_test.go`, then add `CredentialKindOAuth` and `AuthContext.GrantID` to `internal/auth/context.go` and `auth.ClientAuthContext(ClientIdentity)` to `internal/auth/agent_token.go`; `(*AgentToken).AuthContext` uses it; both paths give equal contexts except kind, grant id, prefix and generation (research R3); tests in `internal/server` that work-session grouping separates two logins of one client and that session-backed activity carries the grant id - [ ] T025 [US2] Source test `TestCredentialKindAgentTokenSitesClassified` in `internal/auth/credential_kind_sites_test.go`: every comparison with `CredentialKindAgentToken` in `internal/` is listed as "applies to oauth" or "API-key specific"; fix the sites it finds - [ ] T026 [US2] Tests in `internal/runtime/oauth_login_service_test.go` for `Describe(requestID)`: fixed client on a per-client address, generic address lists clients with none pre-selected, `profile_required`, `previous_login` only for the same registration, guard verdict included, reported name never selects anything -- [ ] T027 [US2] Tests in `internal/runtime/oauth_login_service_test.go` for `Preview` (guard verdict and access sentence for a proposed client, profile and mode; `complete: false` while a choice is missing; writes nothing) and `Approve`/`Deny`: approval stores nothing in the database and records the decision on the request; the exchange commits binding and grant after re-checking revision and guard, and answers `invalid_grant` with a `deny` row when either fails; `already_decided`, `binding_changed` on a stale revision, `client_fixed`, `profile_required`, new custom client id rules (`identity_exists`, `reserved_identity`), `replace_grant` revokes the old login, activity rows `approve`/`deny` with the request actor; and for `Exchange`/`Refresh`: PKCE, client and redirect binding, resource substitution, a token request whose origin differs from the stored issuer (refused first, nothing consumed), code expiry and reuse within the tombstone window, refresh expiry without extension, rotation, authentic replay, forged token with a real grant id; activity rows `issue` and `replay_revoke` naming `approved_by` with `trigger: client`; `revoke` naming the request actor +- [ ] T027 [US2] Tests in `internal/runtime/oauth_login_service_test.go` for `Preview` (guard verdict and access sentence for a proposed client, profile and mode; `complete: false` while a choice is missing; writes nothing) and `Approve`/`Deny`: approval stores nothing in the database and records the decision on the request; the exchange commits binding and grant after re-checking revision and guard, and answers `invalid_grant` with a `deny` row (approving administrator, `trigger: client`) when either fails; approve → revoke client → exchange, approve → forget and recreate client → exchange, and approve → feature off → on → exchange all answer `invalid_grant` and store nothing; `approve`/`deny` rows carry `request_id`; `already_decided`, `binding_changed` on a stale revision, `client_fixed`, `profile_required`, new custom client id rules (`identity_exists`, `reserved_identity`), `replace_grant` revokes the old login, activity rows `approve`/`deny` with the request actor; and for `Exchange`/`Refresh`: PKCE, client and redirect binding, resource substitution, a token request whose origin differs from the stored issuer (refused first, nothing consumed), code expiry and reuse within the tombstone window, refresh expiry without extension, rotation, authentic replay, forged token with a real grant id; activity rows `issue` and `replay_revoke` naming `approved_by` with `trigger: client`; `revoke` naming the request actor - [ ] T028 [US2] Implement `internal/runtime/oauth_login_service.go` (`OAuthLoginService`: `Describe`, `Preview`, `Approve`, `Deny`, `Exchange`, `Refresh`, `Authenticate`, `ListGrants`, `RevokeGrant`) under `bindingWriteMu`; wire in `internal/runtime/runtime.go`; add `approve`, `deny`, `replay_revoke` to `internal/profile/contract.go`; add events to `internal/runtime/events.go` and to `adminConfigEventTypes` in `internal/httpapi/sse_scope.go` - [ ] T029 [US3] Tests in `internal/runtime/clients_service_test.go`, `internal/runtime/profiles_service_test.go` and the config-funnel tests (`internal/runtime/config_funnel_test.go`): `SetBinding` and `BulkAssign` on an OAuth-only client; `Forget` deletes grants; client revoke revokes key and all grants; profile delete reports an OAuth-only client in `profile_in_use`, `reassign_to` moves it, a failed funnel commit restores it; rename moves its pin in both records; minting an API key for an OAuth-only client keeps one binding - [ ] T030 [US3] Implement T029 in `internal/runtime/clients_service.go`, `internal/runtime/clients_service_connect.go`, `internal/runtime/credentials_service.go`, `internal/runtime/profiles_service.go` and `internal/runtime/config_funnel.go` (revoke cascade, single-grant revoke, API-key-only revoke, grants in `List`/`Get`) @@ -70,7 +70,7 @@ Tasks are grouped by the three delivery PRs. Each PR is merged before the next s - [ ] T035 [US2] Implement `internal/server/oauth_login_http.go` and replace the 501 stub from T007 - [ ] T036 [US2] Tests in `internal/server/oauth_login_auth_test.go`: `mcp_oat_` accepted only on its own resource and origin; API key, `mcp_cli_`, `mcp_agt_`, no token → 401 on OAuth addresses even with `require_mcp_auth` off; `mcp_oat_` on `/mcp` and routing-mode routes → 401 while the feature is on or was used, unchanged anonymous behaviour while off and never used; revoked or lapsed grant → 401 on the next request of an open session; the name sent at `initialize` is stored on the grant and the mismatch flag is derived as in research R14; profile scope and activity attribution equal the same client's `mcp_cli_` request - [ ] T037 [US2] Implement `oauthResourceAuth` and the `mcp_oat_` branch of `mcpAuthMiddleware` in `internal/server/server.go`; record `grant_id` and credential kind on activity rows -- [ ] T038 [US7] Tests in `internal/server/oauth_login_toggle_test.go`: on → off after use gives 404 on all OAuth paths and cancels pending requests; forgetting the last client keeps 404; off → on restores logins; toggling needs no restart (config reload event) +- [ ] T038 [US7] Tests in `internal/server/oauth_login_toggle_test.go`: on → off after use gives 404 on all OAuth paths and cancels pending and approved requests with their unconsumed codes; forgetting the last client keeps 404; off → on restores logins; toggling needs no restart (config reload event) - [ ] T039 [US7] Implement the toggle handling: cached gate state refreshed on `EventTypeConfigReloaded` and on first grant in `internal/server/oauth_login_routes.go` ### Phase 7: Admin REST From 5316b391715ba33cffb9ca02e98eaa9e2f1b7597 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sun, 22 Nov 2026 17:08:47 +0200 Subject: [PATCH 12/15] docs(spec): address plan review round 4 for spec 131 Related #1971 --- specs/131-client-oauth-login/contracts/oauth-endpoints.md | 1 + specs/131-client-oauth-login/data-model.md | 2 +- specs/131-client-oauth-login/plan.md | 2 ++ specs/131-client-oauth-login/research.md | 4 +++- specs/131-client-oauth-login/tasks.md | 8 ++++---- 5 files changed, 11 insertions(+), 6 deletions(-) diff --git a/specs/131-client-oauth-login/contracts/oauth-endpoints.md b/specs/131-client-oauth-login/contracts/oauth-endpoints.md index 3c12b50b3..364e81243 100644 --- a/specs/131-client-oauth-login/contracts/oauth-endpoints.md +++ b/specs/131-client-oauth-login/contracts/oauth-endpoints.md @@ -98,6 +98,7 @@ Errors (`400` JSON `{error, error_description}`): | request origin differs from the stored issuer | `invalid_grant` | none | | binding changed or guard refuses at exchange | `invalid_grant` | none; `deny` activity row | | request cancelled after approval (client revoked or forgotten, feature turned off) | `invalid_grant` | none | +| registration no longer exists, or the new client id chosen at approval now exists | `invalid_grant` | none | | refresh token malformed, bad MAC, unknown, revoked or expired grant, wrong `client_id` | `invalid_grant` | **none**; all indistinguishable; an expired login is never extended | | authentic refresh token that is not the current one | `invalid_grant` | grant revoked (`replay`) | | `resource` differs from the approved one | `invalid_target` | none | diff --git a/specs/131-client-oauth-login/data-model.md b/specs/131-client-oauth-login/data-model.md index 2d2abee4e..e70af91c1 100644 --- a/specs/131-client-oauth-login/data-model.md +++ b/specs/131-client-oauth-login/data-model.md @@ -56,7 +56,7 @@ Invariants: - Exists exactly for clients that have at least one grant record; it is created in the transaction that stores the client's first grant, for a new client and for an existing API-key client alike, from the client's current binding. - If the client also has an API-key record, `profile_pin` and `profile_mode` equal that record's `ProfilePin` and `ProfileMode`. One storage function writes both in one transaction. On startup a mismatch is repaired from the API-key record and logged. -- **Binding revision**: `sha256(client | pin | mode)` truncated, computed on read; the consent page sends back the revision it displayed. +- **Binding revision**: `sha256(client | pin | mode)` truncated, computed on read; a client that does not exist yet has the fixed revision `absent`. The consent page sends back the revision it displayed. ## Ever-used marker — `MetaBucket` key `oauth_login_ever_used` diff --git a/specs/131-client-oauth-login/plan.md b/specs/131-client-oauth-login/plan.md index 63d2c72a8..cb14cc89e 100644 --- a/specs/131-client-oauth-login/plan.md +++ b/specs/131-client-oauth-login/plan.md @@ -156,3 +156,5 @@ Cross-model review of plan, research, data model, contracts and tasks, round 1 ( Round 2 (same reviewer): eight findings, all accepted. A connect on a client with only browser logins snapshots and restores its binding; the login is stored at the token exchange, with revision and guard re-checked there (research R15); the consent page gets a read-only preview call for the guard verdict (R16); the grant keeps the redirect URI used; the token endpoint checks the request origin against the stored issuer first; replay rows name the approving administrator; `browser_login_disabled` reflects current state only; the registration cap covers all non-approved rows. Round 3: four findings, all accepted. Revoke, forget and turn-off cancel approved requests and unconsumed codes under the same lock as the commit; the commit creates the OAuth-side binding whenever it is absent; the registration is promoted in the commit and has no `denied` state; activity rows before a login carry `request_id`, and a refusal at exchange names the approving administrator. + +Round 4: three findings, all accepted. Turn-off cancels requests synchronously while the config is applied, not from an event; the commit re-checks that a new client id is still absent and that the registration still exists. diff --git a/specs/131-client-oauth-login/research.md b/specs/131-client-oauth-login/research.md index 2a677d445..7d11fdb86 100644 --- a/specs/131-client-oauth-login/research.md +++ b/specs/131-client-oauth-login/research.md @@ -5,6 +5,7 @@ Code references are from `main` at `dfc3d418f`. Product decisions and their alte ## R1. Turning routes on and off without a restart - **Finding**: the outer mux is built once in `(*Server).startCustomHTTPServer` (`internal/server/server.go:3380`, mux at 3431). `http.ServeMux` has no unregister. Existing switchable features decide per request inside an always-registered handler (`/mcp/s/` in `serveSingleServer`, `/debug/pprof/`, `enable_skills` through `RefreshSkillsAvailability`). +- **Gate state**: read from the live config and the marker on each request; nothing about the decision is cached across a config change. - **Decision**: register only exact paths plus two subtrees whose no-slash form is also registered: `/mcp/oauth`, `/mcp/oauth/`, `/oauth/register`, `/oauth/authorize`, `/oauth/token`, `/.well-known/oauth-authorization-server`, `/.well-known/oauth-protected-resource/mcp/oauth`, `/.well-known/oauth-protected-resource/mcp/oauth/`. A subtree pattern such as `/oauth/` is not used: `ServeMux` would answer `/oauth` with a redirect before any gate runs, which differs from today's 404. Each is a gate with three states read per request from config and the ever-used marker (cached, refreshed on `EventTypeConfigReloaded` and on first grant): - off, never used → call the handler that owned the path before (`mcpHandler` for `/mcp/oauth*`; the root `/` handler for the others); - off, used → 404; @@ -91,7 +92,8 @@ Code references are from `main` at `dfc3d418f`. Product decisions and their alte ## R15. When a login is stored - **Decision**: approval writes no registration, login, binding or marker. It records the decision (client, profile, mode, replace choice, approving actor) on the in-memory request, writes the `approve` activity row (activity is the one thing it persists) and issues the code. The **token exchange** is the commit: under `bindingWriteMu` it confirms the request is still `approved`, then in one transaction re-checks the binding revision and the guard with the decided candidate, creates the OAuth-side binding whenever the client has none (a new client, and also an existing API-key client getting its first login, from that client's current binding), promotes the registration to `approved`, stores the grant (with the redirect URI used, resource, issuer, `approved_by`), revokes the replaced login if asked, and sets the ever-used marker; then it writes the `issue` row. If the re-check fails the exchange answers `invalid_grant`, nothing is stored and a `deny` row with reason `binding_changed` or `guard` is written, naming the decision's approving administrator with `trigger: client`. -- **Cancellation**: revoking a client, forgetting a client and turning the feature off cancel every request that targets that client (by address or by decision), pending or approved, and with it any unconsumed code. They run under the same `bindingWriteMu` as the commit, so an exchange either completes before them (and its grant is then revoked or deleted by them) or finds its request cancelled. The binding revision alone would not catch a revoke, which changes neither pin nor mode. +- **Cancellation**: revoking a client, forgetting a client and turning the feature off cancel every request that targets that client (by address or by decision), pending or approved, and with it any unconsumed code. They run under the same `bindingWriteMu` as the commit, so an exchange either completes before them (and its grant is then revoked or deleted by them) or finds its request cancelled. The binding revision alone would not catch a revoke, which changes neither pin nor mode. For turn-off the cancellation is a synchronous step of applying a config in which `mcp_oauth_enabled` goes from true to false, on both the API update path and the file-reload path, before the new config becomes visible; it does not depend on `EventTypeConfigReloaded`, which is asynchronous and may be dropped (`event_bus.go:206-219`). Events only refresh caches and notify surfaces. The gates read the live config on every request. +- **Re-checks inside the commit transaction**, each failing with `invalid_grant` and no write: the registration still exists (it may have been evicted or deleted with its last grant; it is never recreated from the code); a decision that creates a new client still finds that id absent and not reserved (two approved requests for the same new id: the second fails, it is not turned into "existing client"); the binding revision, where the revision of an absent client is a fixed sentinel; the guard. - **Rationale**: an approval the client never completes leaves no login, no client row and no marker. One point of commit also removes the question of what a code refers to. - **Consequence**: a restart between approval and exchange drops the code; the client starts again. diff --git a/specs/131-client-oauth-login/tasks.md b/specs/131-client-oauth-login/tasks.md index f8e5d0062..d0b5488ab 100644 --- a/specs/131-client-oauth-login/tasks.md +++ b/specs/131-client-oauth-login/tasks.md @@ -45,7 +45,7 @@ Tasks are grouped by the three delivery PRs. Each PR is merged before the next s ### Phase 4: Storage - [ ] T018 [US2] Tests in `internal/storage/oauth_login_test.go` for registrations: create, get, state moves, expiry sweep (15 min / 24 h), cap of 50 over `pending` and `authorized` rows together with the oldest dropped; a registration is deleted with its last grant record; there is no `denied` state -- [ ] T019 [US2] Tests in `internal/storage/oauth_login_test.go` for grants: `CommitLogin` stores the grant (with `redirect_uri`), promotes the registration to `approved`, creates the OAuth-side binding whenever the client has none (new client, and API-key-only client getting its first login, with both records equal afterwards), the replaced login's revocation and the first-grant marker in one tx and writes nothing when its revision check fails, lookup by access hash, `RotateOrRevoke` (current secret → rotate; authentic old secret → revoke `replay`; unknown, revoked or expired → no write and no lifetime extension, asserted by tx id), lapse after 30 days, retention of dead grants +- [ ] T019 [US2] Tests in `internal/storage/oauth_login_test.go` for grants: `CommitLogin` stores the grant (with `redirect_uri`), promotes the registration to `approved`, creates the OAuth-side binding whenever the client has none (new client, and API-key-only client getting its first login, with both records equal afterwards), the replaced login's revocation and the first-grant marker in one tx and writes nothing when its revision check fails, when the registration is gone, or when a new-client decision finds the id present, lookup by access hash, `RotateOrRevoke` (current secret → rotate; authentic old secret → revoke `replay`; unknown, revoked or expired → no write and no lifetime extension, asserted by tx id), lapse after 30 days, retention of dead grants - [ ] T020 [US2] Implement `internal/storage/oauth_login.go` for T018–T019 with lazy buckets `oauth_registrations`, `oauth_grants` (+ `by_access_hash`), marker `oauth_login_ever_used` - [ ] T021 [US3] Tests in `internal/storage/client_binding_dual_test.go`: `writeClientBindingTx` writes the API-key record and `oauth_client_bindings` in one tx for every writer (update, mint for an OAuth-only client, reconnect, connect rollback, `RepinProfile`, `RestorePins`); a mint for an OAuth-only client snapshots its binding into `PriorProfilePin`/`PriorProfileMode`, and abort or undo restores it to the OAuth record without touching grants; works for an OAuth-only client; fails when neither exists; startup repair takes the API-key record; source test that no other code in `internal/storage` assigns `ProfilePin`/`ProfileMode` of a client record - [ ] T022 [US3] Test `TestDowngradeView_APIKeyRecordStaysCurrent` in `internal/storage/client_binding_dual_test.go`: after a reassign, a rename and a reconnect of a client with both credentials, the raw `agent_tokens` record carries the current pin and mode (FR-028) @@ -56,7 +56,7 @@ Tasks are grouped by the three delivery PRs. Each PR is merged before the next s - [ ] T024 [US2] Test first in `internal/auth/agent_token_identity_test.go`, then add `CredentialKindOAuth` and `AuthContext.GrantID` to `internal/auth/context.go` and `auth.ClientAuthContext(ClientIdentity)` to `internal/auth/agent_token.go`; `(*AgentToken).AuthContext` uses it; both paths give equal contexts except kind, grant id, prefix and generation (research R3); tests in `internal/server` that work-session grouping separates two logins of one client and that session-backed activity carries the grant id - [ ] T025 [US2] Source test `TestCredentialKindAgentTokenSitesClassified` in `internal/auth/credential_kind_sites_test.go`: every comparison with `CredentialKindAgentToken` in `internal/` is listed as "applies to oauth" or "API-key specific"; fix the sites it finds - [ ] T026 [US2] Tests in `internal/runtime/oauth_login_service_test.go` for `Describe(requestID)`: fixed client on a per-client address, generic address lists clients with none pre-selected, `profile_required`, `previous_login` only for the same registration, guard verdict included, reported name never selects anything -- [ ] T027 [US2] Tests in `internal/runtime/oauth_login_service_test.go` for `Preview` (guard verdict and access sentence for a proposed client, profile and mode; `complete: false` while a choice is missing; writes nothing) and `Approve`/`Deny`: approval stores nothing in the database and records the decision on the request; the exchange commits binding and grant after re-checking revision and guard, and answers `invalid_grant` with a `deny` row (approving administrator, `trigger: client`) when either fails; approve → revoke client → exchange, approve → forget and recreate client → exchange, and approve → feature off → on → exchange all answer `invalid_grant` and store nothing; `approve`/`deny` rows carry `request_id`; `already_decided`, `binding_changed` on a stale revision, `client_fixed`, `profile_required`, new custom client id rules (`identity_exists`, `reserved_identity`), `replace_grant` revokes the old login, activity rows `approve`/`deny` with the request actor; and for `Exchange`/`Refresh`: PKCE, client and redirect binding, resource substitution, a token request whose origin differs from the stored issuer (refused first, nothing consumed), code expiry and reuse within the tombstone window, refresh expiry without extension, rotation, authentic replay, forged token with a real grant id; activity rows `issue` and `replay_revoke` naming `approved_by` with `trigger: client`; `revoke` naming the request actor +- [ ] T027 [US2] Tests in `internal/runtime/oauth_login_service_test.go` for `Preview` (guard verdict and access sentence for a proposed client, profile and mode; `complete: false` while a choice is missing; writes nothing) and `Approve`/`Deny`: approval stores nothing in the database and records the decision on the request; the exchange commits binding and grant after re-checking revision and guard, and answers `invalid_grant` with a `deny` row (approving administrator, `trigger: client`) when either fails; approve → revoke client → exchange, approve → forget and recreate client → exchange, and approve → feature off → on → exchange all answer `invalid_grant` and store nothing; so do two approved new-client requests with the same id (the second), and an exchange whose registration was evicted or deleted after approval; `approve`/`deny` rows carry `request_id`; `already_decided`, `binding_changed` on a stale revision, `client_fixed`, `profile_required`, new custom client id rules (`identity_exists`, `reserved_identity`), `replace_grant` revokes the old login, activity rows `approve`/`deny` with the request actor; and for `Exchange`/`Refresh`: PKCE, client and redirect binding, resource substitution, a token request whose origin differs from the stored issuer (refused first, nothing consumed), code expiry and reuse within the tombstone window, refresh expiry without extension, rotation, authentic replay, forged token with a real grant id; activity rows `issue` and `replay_revoke` naming `approved_by` with `trigger: client`; `revoke` naming the request actor - [ ] T028 [US2] Implement `internal/runtime/oauth_login_service.go` (`OAuthLoginService`: `Describe`, `Preview`, `Approve`, `Deny`, `Exchange`, `Refresh`, `Authenticate`, `ListGrants`, `RevokeGrant`) under `bindingWriteMu`; wire in `internal/runtime/runtime.go`; add `approve`, `deny`, `replay_revoke` to `internal/profile/contract.go`; add events to `internal/runtime/events.go` and to `adminConfigEventTypes` in `internal/httpapi/sse_scope.go` - [ ] T029 [US3] Tests in `internal/runtime/clients_service_test.go`, `internal/runtime/profiles_service_test.go` and the config-funnel tests (`internal/runtime/config_funnel_test.go`): `SetBinding` and `BulkAssign` on an OAuth-only client; `Forget` deletes grants; client revoke revokes key and all grants; profile delete reports an OAuth-only client in `profile_in_use`, `reassign_to` moves it, a failed funnel commit restores it; rename moves its pin in both records; minting an API key for an OAuth-only client keeps one binding - [ ] T030 [US3] Implement T029 in `internal/runtime/clients_service.go`, `internal/runtime/clients_service_connect.go`, `internal/runtime/credentials_service.go`, `internal/runtime/profiles_service.go` and `internal/runtime/config_funnel.go` (revoke cascade, single-grant revoke, API-key-only revoke, grants in `List`/`Get`) @@ -70,8 +70,8 @@ Tasks are grouped by the three delivery PRs. Each PR is merged before the next s - [ ] T035 [US2] Implement `internal/server/oauth_login_http.go` and replace the 501 stub from T007 - [ ] T036 [US2] Tests in `internal/server/oauth_login_auth_test.go`: `mcp_oat_` accepted only on its own resource and origin; API key, `mcp_cli_`, `mcp_agt_`, no token → 401 on OAuth addresses even with `require_mcp_auth` off; `mcp_oat_` on `/mcp` and routing-mode routes → 401 while the feature is on or was used, unchanged anonymous behaviour while off and never used; revoked or lapsed grant → 401 on the next request of an open session; the name sent at `initialize` is stored on the grant and the mismatch flag is derived as in research R14; profile scope and activity attribution equal the same client's `mcp_cli_` request - [ ] T037 [US2] Implement `oauthResourceAuth` and the `mcp_oat_` branch of `mcpAuthMiddleware` in `internal/server/server.go`; record `grant_id` and credential kind on activity rows -- [ ] T038 [US7] Tests in `internal/server/oauth_login_toggle_test.go`: on → off after use gives 404 on all OAuth paths and cancels pending and approved requests with their unconsumed codes; forgetting the last client keeps 404; off → on restores logins; toggling needs no restart (config reload event) -- [ ] T039 [US7] Implement the toggle handling: cached gate state refreshed on `EventTypeConfigReloaded` and on first grant in `internal/server/oauth_login_routes.go` +- [ ] T038 [US7] Tests in `internal/server/oauth_login_toggle_test.go`: on → off after use gives 404 on all OAuth paths and cancels pending and approved requests with their unconsumed codes; forgetting the last client keeps 404; off → on restores logins; toggling needs no restart; cancellation happens while the config is applied on both the API update and the file-reload path and still holds when `EventTypeConfigReloaded` is delayed or dropped; a quick off → on leaves no approved request usable +- [ ] T039 [US7] Implement the toggle handling: gates read live config and the marker per request in `internal/server/oauth_login_routes.go`; a synchronous cancel-all hook under `bindingWriteMu` in the config apply path (`internal/runtime/config_hotreload.go` and the commit path in `internal/runtime/commit.go`) when `mcp_oauth_enabled` goes true → false ### Phase 7: Admin REST From a60ef27ed246f2baad88d3ee510bf8e45fab40d6 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sun, 22 Nov 2026 19:38:06 +0200 Subject: [PATCH 13/15] docs(spec): record storage decisions from PR-1c review (spec 132) Related #1971 --- specs/132-client-oauth-login/data-model.md | 3 ++- specs/132-client-oauth-login/research.md | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/specs/132-client-oauth-login/data-model.md b/specs/132-client-oauth-login/data-model.md index e70af91c1..687d95b8a 100644 --- a/specs/132-client-oauth-login/data-model.md +++ b/specs/132-client-oauth-login/data-model.md @@ -37,7 +37,7 @@ Lifecycle: `pending` rows are deleted 15 minutes after creation, `authorized` (r | `revoked`, `revoked_at`, `revoke_reason` | bool, time, enum | `admin`, `client_revoked`, `replaced`, `replay` | | `user_id` | string | empty in the personal edition | -Sub-bucket `by_access_hash`: `access_hash → grant_id`. +Index bucket `oauth_grant_access_index` (a sibling bucket, so iterating `oauth_grants` never meets a nested bucket): `access_hash → grant_id`. Authentication goes through one storage call that also requires the grant not revoked and both the access and the refresh expiry in the future. A grant is created at the token exchange, not at approval (research R15). @@ -51,6 +51,7 @@ State: `live` (not revoked, `refresh_expires_at` in the future) → `lapsed` (re | `profile_mode` | enum | `locked` requires a non-empty pin; All servers is `switchable` | | `display_name` | string | for a custom client created at consent, at most 64 runes | | `updated_at` | time | | +| `write_id` | string | random, renewed on every write of the entry; lets a profile-rename rollback tell "still the binding I wrote" from a re-created or reassigned one with the same values. Storage-internal, not part of the binding revision | Invariants: diff --git a/specs/132-client-oauth-login/research.md b/specs/132-client-oauth-login/research.md index 7d11fdb86..49a4ea83d 100644 --- a/specs/132-client-oauth-login/research.md +++ b/specs/132-client-oauth-login/research.md @@ -31,7 +31,7 @@ Code references are from `main` at `dfc3d418f`. Product decisions and their alte - **Finding**: the binding lives on the `Kind=client` record; `storage.UpdateClientCredentialBinding(clientID, pin, mode)` (`internal/storage/client_credentials.go:233`) is called only from `ClientsService.setBindingLocked` (`internal/runtime/clients_service.go:539`). There is no index by client id (`findClientTokenRecordLocked` scans). `ValidateTokenInvariants` refuses a client record without a secret hash, expiry or with locked + empty pin. - **Finding (review)**: the binding is also written by connect rollback (`clients_service_connect.go:355`), by mint and replacement mint (`client_credentials.go:156-219`) and by profile rename/reassign through `RepinProfile` / `RestorePins` (`internal/storage/agent_token_repin.go`, called from `internal/runtime/config_funnel.go:126-143`). Profile users are found through `ListAgentTokens()` in `internal/runtime/profiles_service.go`. -- **Decision**: new bucket `oauth_client_bindings`, key = client id, value `{pin, mode, display_name, updated_at}`. A transaction-local helper `writeClientBindingTx(tx, clientID, pin, mode)` writes the API-key record if present and the OAuth record if present; it fails only if neither exists. Update, mint, reconnect, rollback, repin and restore all call it inside their own transaction. Minting an API key for a client that has only browser logins writes the binding the caller asked for to both records, and first copies the client's OAuth binding into the new record's `PriorProfilePin`/`PriorProfileMode` (today these are captured only from an earlier API-key record, `client_credentials.go:186-200`). An aborted or undone connect restores that snapshot to the OAuth record through `writeClientBindingTx`, so a wider binding from a connect that never took effect cannot stay on the existing logins. `profiles_service.go` gets a `ListClientBindings()` view that includes OAuth-only clients. `setBindingLocked` drops its "must be `CredentialStateClient`" precondition in favour of "client has an API key or a live grant". Startup check: for a client with both, the API-key record wins and the mismatch is logged at WARN. +- **Decision**: new bucket `oauth_client_bindings`, key = client id, value `{pin, mode, display_name, updated_at}`. A transaction-local helper `writeClientBindingTx(tx, clientID, pin, mode)` writes the API-key record if present and the OAuth record if present; it fails only if neither exists. Update, mint, reconnect, rollback, repin and restore all call it inside their own transaction. Minting an API key for a client that has only browser logins writes the binding the caller asked for to both records, and first copies the client's OAuth binding into the new record's `PriorProfilePin`/`PriorProfileMode` (today these are captured only from an earlier API-key record, `client_credentials.go:186-200`). An aborted or undone connect restores that snapshot to the OAuth record through `writeClientBindingTx`, so a wider binding from a connect that never took effect cannot stay on the existing logins. `profiles_service.go` gets a `ListClientBindings()` view that includes OAuth-only clients. `setBindingLocked` drops its "must be `CredentialStateClient`" precondition in favour of "client has an API key or a live grant". Startup check: for a client with both, the API-key record wins and the mismatch is logged at WARN. The browser-login request path reads the binding with the same rule (`CurrentClientBinding`), never the OAuth entry alone, so a change made by an older binary is honoured even before the repair runs. The writer validates a binding only when an OAuth copy exists; API-key-only writes stay exactly as before. A profile-rename rollback (`RestorePins`) decides once per client, by the entry's `write_id`, and restores both copies or neither; it does not touch the connect snapshot (`PriorProfile*`), so undoing a connect returns a client to its pre-connect binding as it does for API keys today. - **Alternatives**: single new bucket for all bindings (rejected: downgrade reads the stale API-key record, FR-028); credential-less `AgentToken` (rejected: fails invariants on older binaries and pollutes token lists). ## R5. The binding guard @@ -67,7 +67,7 @@ Code references are from `main` at `dfc3d418f`. Product decisions and their alte - **Finding**: `initBuckets` (`internal/storage/bbolt.go:160`) creates a fixed list at open; other buckets (`agent_tokens`, `tpa_bundle_state`, …) are created with `CreateBucketIfNotExists` in the write path and readers treat a nil bucket as empty. Markers live in `MetaBucket` (`markOAuthCompactAdvisedTx`, `oauth_binding.go:110`). - **Decision**: all three buckets are lazy; nothing is added to `initBuckets`. `oauth_login_ever_used` is written in the transaction that stores the first grant. A test opens a database, runs a default-off server through the e2e route table, and asserts the bucket list is unchanged. - **Finding (review)**: `ForgetClientCredential` is shared by client forget and client revoke (`clients_service.go:695-724`), and its restoring variant aborts a failed connect (`clients_service_connect.go:393-399`). -- **Decision**: four distinct storage operations. `ForgetClient` deletes the API-key record, all grants, the OAuth binding and registrations left without a grant. `RevokeClient` marks the API key and every grant revoked and keeps them for display. `RevokeClientAPIKey` touches the API-key record only. Connect rollback (`ForgetClientCredentialRestoringPrior`) touches the API-key record only and restores the binding through `writeClientBindingTx`. +- **Decision**: four distinct storage operations. `ForgetClient` revokes the API-key record exactly as today's forget does (the tombstone keeps the name reserved) and deletes all grants, the OAuth binding and registrations left without a grant. `RevokeClient` marks the API key and every grant revoked and keeps them for display. `RevokeClientAPIKey` touches the API-key record only. Connect rollback (`ForgetClientCredentialRestoringPrior`) touches the API-key record only and restores the binding through `writeClientBindingTx`. ## R11. Config field From 4c5c733b8551f27b3f9bae9ecfabb3a3775f03f3 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 23 Nov 2026 12:58:15 +0200 Subject: [PATCH 14/15] docs(spec): name suggestion on the generic address (spec 132) The issue author asked for the consent page to be pre-filled from the client name with the user able to override it; approved by the maintainer. The reported name may pre-select one client on the generic address when it matches exactly one known client. It decides nothing by itself. Related #1971 --- ROADMAP.md | 2 +- .../132-client-oauth-login/contracts/rest-admin.md | 3 +++ specs/132-client-oauth-login/design.md | 11 +++++++---- specs/132-client-oauth-login/spec.md | 14 ++++++++------ specs/132-client-oauth-login/tasks.md | 3 ++- 5 files changed, 21 insertions(+), 12 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 82c33ddd5..138aed6b1 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1445,4 +1445,4 @@ Legend: `shipped` ≥95% checked · `in-flight` 1–94% · `drafted` 0% · `—` | [129-per-user-upstream-credentials](./specs/129-per-user-upstream-credentials/) | — | — | | [130-skills-review-ux](./specs/130-skills-review-ux/) | `shipped` | 9/9 (100%) | | [131-skills-card-ux](./specs/131-skills-card-ux/) | `shipped` | 7/7 (100%) | -| [132-client-oauth-login](./specs/132-client-oauth-login/) | `drafted` | 0/71 (0%) | +| [132-client-oauth-login](./specs/132-client-oauth-login/) | `drafted` | 0/72 (0%) | diff --git a/specs/132-client-oauth-login/contracts/rest-admin.md b/specs/132-client-oauth-login/contracts/rest-admin.md index 40fc29b90..c91e03273 100644 --- a/specs/132-client-oauth-login/contracts/rest-admin.md +++ b/specs/132-client-oauth-login/contracts/rest-admin.md @@ -26,6 +26,7 @@ Pending requests, newest first: `[{id, client_label, created_at, expires_at}]`. }, "existing_clients": [ /* address_kind = generic: {id, display_name, binding} */ ], "suggested_new_client": { "id": "acme-agent", "display_name": "Acme Agent" }, + "suggested_client": { "id": "cursor", "matched": "display_name" }, // generic only; present when the reported name equals exactly one entry of existing_clients (matched: id | display_name | known_name); absent otherwise "profiles": [ { "name": "dev-readonly" } ], "profile_required": true, // profiles exist and the client has no binding "previous_login": { "grant_id": "…", "approved_at": "…" }, // same registration signed in before @@ -35,6 +36,8 @@ Pending requests, newest first: `[{id, client_label, created_at, expires_at}]`. `404` for an unknown, expired, decided or cancelled id (one uniform answer). +`suggested_client` is advice for the page only. It is computed on read from the sanitised reported name (trimmed, compared without regard to case) against each entry of `existing_clients`: its id, its display name and, for a connect-registry client, its known client names. No match or more than one match → absent. Preview and approve take the client from their own body and never fall back to the suggestion. + ### `POST /oauth/authorizations/{id}/preview` Read-only. Body: the same `client`, `profile`, `mode` as approve. Answer: diff --git a/specs/132-client-oauth-login/design.md b/specs/132-client-oauth-login/design.md index cd4fbd5bb..41bd799d7 100644 --- a/specs/132-client-oauth-login/design.md +++ b/specs/132-client-oauth-login/design.md @@ -57,8 +57,9 @@ The feature is **off by default** in its first release. With it off, nothing cha How the page is pre-filled was revised the same day, after Algis asked for it to be reliable: -- **3a. Guess from the reported name** (registry list of OAuth registration names, plus learning from earlier approvals). Rejected: clients register under names nobody controls, the list needs upkeep, and a wrong guess puts the wrong client on the page. +- **3a. Guess from the reported name** (registry list of OAuth registration names, plus learning from earlier approvals). Rejected as the way to decide which client a login belongs to: clients register under names nobody controls, the list needs upkeep, and a wrong guess puts the wrong client on the page. - **3b. Per-client address (chosen).** Connect already knows which client it is configuring, so it writes that into the URL. The server reads the client from the path. Deterministic, no list to maintain, no secret in the config file. +- **3c. Name suggestion on the generic address (added 2026-11-23).** The issue author asked for the consent page to be pre-filled from the client name, with the user able to change it. Algis approved. It applies only where the user has to choose anyway (the generic address): the reported name may pre-select one client on the page. It decides nothing by itself. See "Name suggestion" below. ## How it works @@ -90,7 +91,7 @@ Two kinds of address, both under `/mcp/oauth`: | Address | Who writes it | Client on the consent page | |---|---|---| | `/mcp/oauth/` | Connect, or the "Add browser login" action on a Clients row, or the user by hand | **Fixed**: that client. Not selectable | -| `/mcp/oauth` | the user by hand, for a client MCPProxy has never seen | **Chosen by the user**: "New client" (name field pre-filled from the reported name) or an existing client from a list. Nothing is pre-selected among existing clients | +| `/mcp/oauth` | the user by hand, for a client MCPProxy has never seen | **Chosen by the user**: "New client" (name field pre-filled from the reported name) or an existing client from a list. An existing client is pre-selected only by the name suggestion below; otherwise "New client" is | - `` is the Clients hub id: a connect-registry id (`cursor`, `claude-code`) or a custom client's id. The path is the `resource` the client sends at authorize (RFC 8707), so the server knows the client before the page is shown. - An id that is neither in the registry nor an existing custom client answers 404 on every step. Clients are not created by typing a new path. @@ -117,7 +118,8 @@ Profile dev-readonly (locked) Rules for the page: - **Per-client address**: the client is fixed. If it already has a binding, the profile is shown, not asked. If it is new, the profile rule below applies. -- **Generic address**: the user picks the client first. +- **Generic address**: the page opens with a client already selected, and the user can change it before approving. +- **Name suggestion** (generic address only): the sanitised reported name is compared, case-insensitively and after trimming, with the id, the display name and the known client names (connect registry) of every client the page offers. Exactly one match pre-selects that client, and the page says why: `Suggested because the app calls itself "Cursor". MCPProxy cannot verify that.` No match, or more than one, pre-selects "New client" with the name field filled from the reported name. The profile then follows from the selected client exactly as it does without a suggestion: a bound client shows its profile; an unbound one follows the profile rule below. The server never applies a suggestion: approval carries the client the page sent, and a request without one is refused as before. A per-client address ignores the reported name for selection. - **Profile for a client with no binding yet**: if no profiles are configured, "All servers", stored the way it is today for a client credential (no pin, `switchable`; a locked credential with an empty profile is invalid under `ValidateTokenInvariants` and stays so). If profiles exist, nothing is pre-selected and Approve stays disabled until the user picks one; a named profile defaults to `locked`. Same rule as `profile_required` in the `credentials` tool. - **Replace previous login** is pre-checked only when this exact `client_id` already has a grant. Otherwise the new login is added next to the existing ones. - **No admin key in this browser**: the page cannot load the request. It shows "Open this request from the MCPProxy tray, or paste the API key". The core emits an SSE event for a new authorization request; the tray shows a notification and a menu item "Approve sign-in for Cursor…" that opens the same URL with the key, the way it opens the Web UI today. @@ -217,13 +219,14 @@ Each PR is test-first. End to end: a scripted public client runs the whole flow - OAuth and API keys both stay; the user chooses per client. - Suggest and confirm on the consent page. +- On the generic address the reported name may pre-select a client; the user confirms or changes it (2026-11-23, after the issue author's reply on #1971). - Which client a login belongs to must be reliable, not guessed from names (2026-11-22). - Off by default in the first release; an update needs no action and changes nothing for existing users (2026-11-22). ## Calls made here (not decided by Algis) - Readable per-client address (`/mcp/oauth/`) instead of a random one: it carries no authority, so it need not be secret. -- A generic-address login never pre-selects an existing client. +- The name suggestion needs exactly one match and is limited to the generic address; a bound client's profile is still shown, not asked, on the consent page (it is changed in the Clients hub, because it also governs that client's API key). - Consent every time, with no silent re-approval. - Token lifetimes (1 hour / 30 days sliding) and the numeric limits above. - Default Connect choice stays "API key". diff --git a/specs/132-client-oauth-login/spec.md b/specs/132-client-oauth-login/spec.md index cb2945df6..aa5515fe2 100644 --- a/specs/132-client-oauth-login/spec.md +++ b/specs/132-client-oauth-login/spec.md @@ -81,15 +81,17 @@ The client opens the user's default browser, which has never held MCPProxy's adm ### User Story 5 - A client MCPProxy has never seen (Priority: P2) -The user types the generic browser-login address into a client that Connect does not know. On the consent page the user chooses "New client", keeps or edits the suggested name, picks a profile, and approves. The client appears in the Clients hub. +The user types the generic browser-login address into a client that Connect does not know. The consent page opens with "New client" selected and the name filled in; the user keeps or edits the name, picks a profile, and approves. When the name the app reports matches exactly one client MCPProxy already knows, that client is selected instead and the user confirms or changes it. The client appears in the Clients hub. -**Why this priority**: Keeps the feature useful beyond the supported-client list, without name guessing. +**Why this priority**: Keeps the feature useful beyond the supported-client list, while the reported name only suggests and never decides. **Independent Test**: Run the flow on the generic address with an unknown client name; confirm the new client row, its profile and its activity attribution. **Acceptance Scenarios**: -1. **Given** a sign-in request on the generic address, **Then** the user must choose between "New client" and an existing client; no existing client is pre-selected. +1. **Given** a sign-in request on the generic address whose reported name matches no known client, or more than one, **Then** "New client" is selected with the name filled from the reported name, and the user can pick an existing client instead. +4. **Given** a sign-in request on the generic address whose reported name matches exactly one known client, **Then** that client is selected, the page says the selection comes from an unverified name, and the user can change it before approving. +5. **Given** a suggested client that has a profile, **When** the user approves without changing anything, **Then** the login belongs to that client; **When** the user picks another client first, **Then** the login belongs to the client the user picked. 2. **Given** the user picks an existing client, **Then** the page states that the app receives that client's access before Approve is enabled. 3. **Given** an address that names a client id that does not exist, **Then** every step answers "not found" and no client is created. @@ -164,8 +166,8 @@ The user tried browser login and turns it off. Browser-login clients stop workin **Which client it is** - **FR-012**: A per-client address MUST identify the client. On such a request the consent page MUST show that client as fixed. -- **FR-013**: On the generic address the user MUST choose "New client" or an existing client. No existing client may be pre-selected. -- **FR-014**: The name an app reports about itself MUST be shown as unverified and MUST NOT select a client, a profile or any access. It may pre-fill the name field of a new client. +- **FR-013**: On the generic address the page MUST offer "New client" and every existing client, and the user MUST be able to change the selection before approving. An existing client may be pre-selected only when the reported name matches exactly one known client (id, display name or known client name, compared without regard to case); the page MUST then say that the selection comes from an unverified name. Otherwise "New client" is selected. +- **FR-014**: The name an app reports about itself MUST be shown as unverified and MUST NOT grant a client, a profile or any access by itself: a login is stored only for the client the administrator approved. It may pre-fill the name field of a new client and, on the generic address, pre-select a client under FR-013. On a per-client address it MUST NOT affect the selection. - **FR-015**: A per-client address whose id is neither a supported client nor an existing custom client MUST answer "not found" at every step. Typing an address MUST NOT create a client. - **FR-016**: When the same registration signs in again, the page MUST say so and offer to replace its earlier login. Otherwise a new login is added beside existing ones. @@ -220,7 +222,7 @@ The user tried browser login and turns it off. Browser-login clients stop workin - **SC-001**: With the feature at its default, 100% of the existing test suites pass unchanged and the comparison against the previous release shows no difference on any address. - **SC-002**: A user connects a supported client by browser login in under one minute and with one click on the consent page when the client already has a profile. - **SC-003**: No secret is written to a client's config file in the browser-login path. -- **SC-004**: In every tested flow the client shown on the consent page is the one named by the address, or the one the user chose. Zero cases depend on the reported name. +- **SC-004**: In every tested flow the client shown on the consent page is the one named by the address, or the one selected on the page when the user approved. On a per-client address zero cases depend on the reported name; on the generic address the reported name changes only what is pre-selected, never the stored result of an approval. - **SC-005**: Each client on the supported list completes the whole flow, including renewal, in a recorded real-client check before that client is offered in Connect: at least Claude Code, Cursor, VS Code and MCP Inspector are attempted, and only those that pass are listed. - **SC-006**: A revoked login is refused on its next request in 100% of tested cases, including on an open session. - **SC-007**: After the feature was used and turned off, zero requests to a browser-login address are served. diff --git a/specs/132-client-oauth-login/tasks.md b/specs/132-client-oauth-login/tasks.md index 6c24c30d3..fa4d23a49 100644 --- a/specs/132-client-oauth-login/tasks.md +++ b/specs/132-client-oauth-login/tasks.md @@ -95,7 +95,8 @@ Tasks are grouped by the three delivery PRs. Each PR is merged before the next s - [ ] T047 [P] [US2] Add API methods and types for authorizations and client credentials in `frontend/src/services/api.ts` and `frontend/src/types/` - [ ] T048 [US2] Vitest `frontend/tests/unit/authorize-request.spec.ts`: fixed client view, unverified-name label, access sentence, profile shown not asked when bound, Approve disabled until a profile is chosen when `profile_required`, replace-login checkbox only with `previous_login`, guard verdict fetched through the preview call whenever the selection is complete or changes, refusal with fixes shown and Approve disabled until it is clean, `already_decided` and `binding_changed` handling, navigation to `redirect_url` - [ ] T049 [US2] Implement `frontend/src/views/AuthorizeRequest.vue` and the `/authorize` route in `frontend/src/router/index.ts`, reusing `GuardRefusal.vue`, `ProfileChip.vue` -- [ ] T050 [US5] Vitest in `frontend/tests/unit/authorize-request.spec.ts` for the generic address: nothing pre-selected, "New client" with editable id and name, existing-client choice shows the access sentence, `identity_exists` / `reserved_identity` errors +- [ ] T049a [US5] Tests then code: `suggested_client` on the sign-in request payload (`internal/runtime/oauth_login_consent.go`, `internal/httpapi/oauth_login.go`, `internal/contracts`, `make swagger`): exactly one case-insensitive match on id, display name or known client name → present with `matched`; none or several → absent; never on a per-client address; approve and preview without a client are still refused +- [ ] T050 [US5] Vitest in `frontend/tests/unit/authorize-request.spec.ts` for the generic address: "New client" selected when there is no `suggested_client`, the suggested client selected with the unverified-name notice when there is one, changing the selection sends the changed client, "New client" with editable id and name, existing-client choice shows the access sentence, `identity_exists` / `reserved_identity` errors - [ ] T051 [US5] Implement the generic-address branch in `frontend/src/views/AuthorizeRequest.vue` - [ ] T052 [US4] Vitest then code: with no API key in storage `AuthorizeRequest.vue` shows only "Open from the tray or paste the API key", makes no request-detail call, and continues after a pasted key (`frontend/tests/unit/authorize-request-nokey.spec.ts`) - [ ] T053 [US4] Test then code: `frame-ancestors 'none'` (and `X-Frame-Options: DENY`) on `/ui/authorize` in `internal/server/server.go` (`internal/server/oauth_login_http_test.go`) From fc5e11d3db5bf7984b518026d07de4bf44cb3099 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 23 Nov 2026 13:00:50 +0200 Subject: [PATCH 15/15] docs(spec): address review of the name suggestion (spec 132) Related #1971 --- specs/132-client-oauth-login/contracts/rest-admin.md | 4 ++-- specs/132-client-oauth-login/data-model.md | 2 +- specs/132-client-oauth-login/design.md | 6 +++--- specs/132-client-oauth-login/plan.md | 2 +- specs/132-client-oauth-login/spec.md | 10 ++++++---- specs/132-client-oauth-login/tasks.md | 4 ++-- 6 files changed, 15 insertions(+), 13 deletions(-) diff --git a/specs/132-client-oauth-login/contracts/rest-admin.md b/specs/132-client-oauth-login/contracts/rest-admin.md index c91e03273..51c31e6fd 100644 --- a/specs/132-client-oauth-login/contracts/rest-admin.md +++ b/specs/132-client-oauth-login/contracts/rest-admin.md @@ -36,7 +36,7 @@ Pending requests, newest first: `[{id, client_label, created_at, expires_at}]`. `404` for an unknown, expired, decided or cancelled id (one uniform answer). -`suggested_client` is advice for the page only. It is computed on read from the sanitised reported name (trimmed, compared without regard to case) against each entry of `existing_clients`: its id, its display name and, for a connect-registry client, its known client names. No match or more than one match → absent. Preview and approve take the client from their own body and never fall back to the suggestion. +`suggested_client` is advice for the page only. It is computed on read from the sanitised reported name (trimmed, compared without regard to case) against each entry of `existing_clients`: its id, its display name and, for a connect-registry client, its known client names. The whole name is tried and, when it ends with a parenthesised suffix, also the part before it. Matches are collected over all fields and counted by distinct client id; exactly one distinct client → present, none or several → absent. `matched` names the first field that matched in the order `id`, `display_name`, `known_name`. Preview and approve take the client from their own body and never fall back to the suggestion: on the generic address, preview without a client answers `200 {"complete": false}` with no `access` and no `guard`, and approve without a client answers `422 client_required`. ### `POST /oauth/authorizations/{id}/preview` @@ -69,7 +69,7 @@ Records the decision and issues the code. The login itself is stored when the cl - `409 already_decided`. - `409 binding_changed`: the binding differs from `binding_revision`; reload. - `409 binding_bypassable_without_auth`: body as the existing guard refusal. -- `422 profile_required`, `422 client_fixed` (a client other than the one in the address), `422 identity_exists` / `reserved_identity` for a new client id, `404 profile_not_found`. +- `422 client_required` (generic address, no client in the body), `422 profile_required`, `422 client_fixed` (a client other than the one in the address), `422 identity_exists` / `reserved_identity` for a new client id, `404 profile_not_found`. ### `POST /oauth/authorizations/{id}/deny` diff --git a/specs/132-client-oauth-login/data-model.md b/specs/132-client-oauth-login/data-model.md index 687d95b8a..5e4bf7f10 100644 --- a/specs/132-client-oauth-login/data-model.md +++ b/specs/132-client-oauth-login/data-model.md @@ -7,7 +7,7 @@ All persistent records live in `config.db` in buckets created on first write. No | Field | Type | Rule | |---|---|---| | `client_id` | string | 22 random base62 chars, server-generated | -| `reported_name` | string | `client_name` after `clientidentity.SanitizeDisplay`, at most 128 bytes; display only | +| `reported_name` | string | `client_name` after `clientidentity.SanitizeDisplay`, at most 128 bytes; display, plus the generic-address suggestion (`suggested_client`, computed on read, never stored) | | `redirect_uris` | []string | 1 to 5; each loopback `http` or `https`; no fragment | | `software_id`, `software_version` | string | optional, sanitised, display only | | `token_endpoint_auth_method` | string | always `none` | diff --git a/specs/132-client-oauth-login/design.md b/specs/132-client-oauth-login/design.md index 41bd799d7..a747c4485 100644 --- a/specs/132-client-oauth-login/design.md +++ b/specs/132-client-oauth-login/design.md @@ -9,7 +9,7 @@ Today every MCP client needs a credential pasted into its config file. The user The open question this design answers: **after an OAuth login, how does MCPProxy know which client this is and what it may reach?** -Answer: the **address** the client was given says which client it is, and the user confirms on the consent page. Connect writes a per-client address (`/mcp/oauth/cursor`), so nothing is guessed from the name the client reports. That name is shown, labelled unverified, and is never used to pick a client. Access comes from the profile bound to the client, the same binding API-key clients use. +Answer: the **address** the client was given says which client it is, and the user confirms on the consent page. Connect writes a per-client address (`/mcp/oauth/cursor`), so nothing is guessed from the name the client reports. That name is shown, labelled unverified, and never decides which client a login belongs to: on the generic address it may pre-select a client on the page, and the user confirms or changes it. Access comes from the profile bound to the client, the same binding API-key clients use. The feature is **off by default** in its first release. With it off, nothing changes for anyone who updates. @@ -32,7 +32,7 @@ The feature is **off by default** in its first release. With it off, nothing cha ## Anti-goals -- A client gets access, or is matched to an existing client, because of the name it reports. Never. +- A client gets access, or a login is stored under an existing client, because of the name it reports. Never. (A name may pre-select a client on the generic-address consent page; only the administrator's approval of the client the page sent stores anything.) - Matching that works "most of the time". Which client a login belongs to is either determined by the address or chosen by the user. - An update that changes behaviour or needs an action from a user who did not ask for OAuth. - A login that silently lands on "All servers" while profiles exist. @@ -119,7 +119,7 @@ Rules for the page: - **Per-client address**: the client is fixed. If it already has a binding, the profile is shown, not asked. If it is new, the profile rule below applies. - **Generic address**: the page opens with a client already selected, and the user can change it before approving. -- **Name suggestion** (generic address only): the sanitised reported name is compared, case-insensitively and after trimming, with the id, the display name and the known client names (connect registry) of every client the page offers. Exactly one match pre-selects that client, and the page says why: `Suggested because the app calls itself "Cursor". MCPProxy cannot verify that.` No match, or more than one, pre-selects "New client" with the name field filled from the reported name. The profile then follows from the selected client exactly as it does without a suggestion: a bound client shows its profile; an unbound one follows the profile rule below. The server never applies a suggestion: approval carries the client the page sent, and a request without one is refused as before. A per-client address ignores the reported name for selection. +- **Name suggestion** (generic address only): the sanitised reported name is compared, case-insensitively and after trimming, with the id, the display name and the known client names (connect registry `ClientInfoNames`) of every client the page offers. Two forms of the reported name are tried: the whole name and, when it ends with a parenthesised suffix, the part before it (Claude Code registers as `Claude Code ()`). Matches are collected over all fields and both forms and counted by distinct client id, so one client matching on several fields is one match, and a name that equals one client's id and another client's display name is two. Exactly one matching client pre-selects that client, and the page says why: `Suggested because the app calls itself "Cursor". MCPProxy cannot verify that.` No match, or more than one, pre-selects "New client" with the name field filled from the reported name. The profile then follows from the selected client exactly as it does without a suggestion: a bound client shows its profile; an unbound one follows the profile rule below. The server never applies a suggestion: approval carries the client the page sent, and a request without one is refused as before. A per-client address ignores the reported name for selection. - **Profile for a client with no binding yet**: if no profiles are configured, "All servers", stored the way it is today for a client credential (no pin, `switchable`; a locked credential with an empty profile is invalid under `ValidateTokenInvariants` and stays so). If profiles exist, nothing is pre-selected and Approve stays disabled until the user picks one; a named profile defaults to `locked`. Same rule as `profile_required` in the `credentials` tool. - **Replace previous login** is pre-checked only when this exact `client_id` already has a grant. Otherwise the new login is added next to the existing ones. - **No admin key in this browser**: the page cannot load the request. It shows "Open this request from the MCPProxy tray, or paste the API key". The core emits an SSE event for a new authorization request; the tray shows a notification and a menu item "Approve sign-in for Cursor…" that opens the same URL with the key, the way it opens the Web UI today. diff --git a/specs/132-client-oauth-login/plan.md b/specs/132-client-oauth-login/plan.md index b7d2f1099..8ac36d7d0 100644 --- a/specs/132-client-oauth-login/plan.md +++ b/specs/132-client-oauth-login/plan.md @@ -5,7 +5,7 @@ ## Summary -MCPProxy becomes an optional OAuth 2.1 authorization server for its own MCP endpoint. A client given only `/mcp/oauth/` (or the generic `/mcp/oauth`) registers itself, the administrator approves on a consent page, and the client gets short-lived tokens. The address fixes which client it is; nothing is inferred from the reported name. A browser login is one more credential under an existing Clients hub row and uses that client's single profile binding. The feature is off by default and, until first used, leaves every existing answer unchanged. +MCPProxy becomes an optional OAuth 2.1 authorization server for its own MCP endpoint. A client given only `/mcp/oauth/` (or the generic `/mcp/oauth`) registers itself, the administrator approves on a consent page, and the client gets short-lived tokens. The address fixes which client it is; the reported name decides nothing (on the generic address it may pre-select a client on the consent page, which the administrator confirms or changes). A browser login is one more credential under an existing Clients hub row and uses that client's single profile binding. The feature is off by default and, until first used, leaves every existing answer unchanged. Technical approach: one new stdlib-only leaf package for the protocol logic, lazy bbolt buckets in `internal/storage`, one runtime service next to `ClientsService`, HTTP handlers registered once and gated per request, a small extension of `mcpAuthMiddleware`, then the UI and Connect surfaces. diff --git a/specs/132-client-oauth-login/spec.md b/specs/132-client-oauth-login/spec.md index aa5515fe2..0ef71bfa8 100644 --- a/specs/132-client-oauth-login/spec.md +++ b/specs/132-client-oauth-login/spec.md @@ -90,10 +90,12 @@ The user types the generic browser-login address into a client that Connect does **Acceptance Scenarios**: 1. **Given** a sign-in request on the generic address whose reported name matches no known client, or more than one, **Then** "New client" is selected with the name filled from the reported name, and the user can pick an existing client instead. -4. **Given** a sign-in request on the generic address whose reported name matches exactly one known client, **Then** that client is selected, the page says the selection comes from an unverified name, and the user can change it before approving. -5. **Given** a suggested client that has a profile, **When** the user approves without changing anything, **Then** the login belongs to that client; **When** the user picks another client first, **Then** the login belongs to the client the user picked. -2. **Given** the user picks an existing client, **Then** the page states that the app receives that client's access before Approve is enabled. -3. **Given** an address that names a client id that does not exist, **Then** every step answers "not found" and no client is created. +2. **Given** a sign-in request on the generic address whose reported name matches exactly one known client, **Then** that client is selected, the page says the selection comes from an unverified name, and the user can change it before approving. +3. **Given** a suggested client that has a profile, **When** the user approves without changing anything and the app completes the sign-in, **Then** the stored login belongs to the suggested client with that client's profile. +4. **Given** a suggested client, **When** the user picks another existing client, approves, and the app completes the sign-in, **Then** the stored login belongs to the client the user picked. +5. **Given** a suggested client, **When** the user picks "New client", approves, and the app completes the sign-in, **Then** a new client is created and the suggested client is unchanged. +6. **Given** an existing client is selected, by suggestion or by the user, **Then** the page states that the app receives that client's access before Approve is enabled. +7. **Given** an address that names a client id that does not exist, **Then** every step answers "not found" and no client is created. --- diff --git a/specs/132-client-oauth-login/tasks.md b/specs/132-client-oauth-login/tasks.md index fa4d23a49..b2eb6f79e 100644 --- a/specs/132-client-oauth-login/tasks.md +++ b/specs/132-client-oauth-login/tasks.md @@ -55,7 +55,7 @@ Tasks are grouped by the three delivery PRs. Each PR is merged before the next s - [ ] T024 [US2] Test first in `internal/auth/agent_token_identity_test.go`, then add `CredentialKindOAuth` and `AuthContext.GrantID` to `internal/auth/context.go` and `auth.ClientAuthContext(ClientIdentity)` to `internal/auth/agent_token.go`; `(*AgentToken).AuthContext` uses it; both paths give equal contexts except kind, grant id, prefix and generation (research R3); tests in `internal/server` that work-session grouping separates two logins of one client and that session-backed activity carries the grant id - [ ] T025 [US2] Source test `TestCredentialKindAgentTokenSitesClassified` in `internal/auth/credential_kind_sites_test.go`: every comparison with `CredentialKindAgentToken` in `internal/` is listed as "applies to oauth" or "API-key specific"; fix the sites it finds -- [ ] T026 [US2] Tests in `internal/runtime/oauth_login_service_test.go` for `Describe(requestID)`: fixed client on a per-client address, generic address lists clients with none pre-selected, `profile_required`, `previous_login` only for the same registration, guard verdict included, reported name never selects anything +- [ ] T026 [US2] Tests in `internal/runtime/oauth_login_service_test.go` for `Describe(requestID)`: fixed client on a per-client address, generic address lists clients, `profile_required`, `previous_login` only for the same registration, guard verdict included, reported name never changes the client on a per-client address (the generic-address suggestion is T049a, PR-2) - [ ] T027 [US2] Tests in `internal/runtime/oauth_login_service_test.go` for `Preview` (guard verdict and access sentence for a proposed client, profile and mode; `complete: false` while a choice is missing; writes nothing) and `Approve`/`Deny`: approval stores nothing in the database and records the decision on the request; the exchange commits binding and grant after re-checking revision and guard, and answers `invalid_grant` with a `deny` row (approving administrator, `trigger: client`) when either fails; approve → revoke client → exchange, approve → forget and recreate client → exchange, and approve → feature off → on → exchange all answer `invalid_grant` and store nothing; so do two approved new-client requests with the same id (the second), and an exchange whose registration was evicted or deleted after approval; `approve`/`deny` rows carry `request_id`; `already_decided`, `binding_changed` on a stale revision, `client_fixed`, `profile_required`, new custom client id rules (`identity_exists`, `reserved_identity`), `replace_grant` revokes the old login, activity rows `approve`/`deny` with the request actor; and for `Exchange`/`Refresh`: PKCE, client and redirect binding, resource substitution, a token request whose origin differs from the stored issuer (refused first, nothing consumed), code expiry and reuse within the tombstone window, refresh expiry without extension, rotation, authentic replay, forged token with a real grant id; activity rows `issue` and `replay_revoke` naming `approved_by` with `trigger: client`; `revoke` naming the request actor - [ ] T028 [US2] Implement `internal/runtime/oauth_login_service.go` (`OAuthLoginService`: `Describe`, `Preview`, `Approve`, `Deny`, `Exchange`, `Refresh`, `Authenticate`, `ListGrants`, `RevokeGrant`) under `bindingWriteMu`; wire in `internal/runtime/runtime.go`; add `approve`, `deny`, `replay_revoke` to `internal/profile/contract.go`; add events to `internal/runtime/events.go` and to `adminConfigEventTypes` in `internal/httpapi/sse_scope.go` - [ ] T029 [US3] Tests in `internal/runtime/clients_service_test.go`, `internal/runtime/profiles_service_test.go` and the config-funnel tests (`internal/runtime/config_funnel_test.go`): `SetBinding` and `BulkAssign` on an OAuth-only client; `Forget` deletes grants; client revoke revokes key and all grants; profile delete reports an OAuth-only client in `profile_in_use`, `reassign_to` moves it, a failed funnel commit restores it; rename moves its pin in both records; minting an API key for an OAuth-only client keeps one binding @@ -95,7 +95,7 @@ Tasks are grouped by the three delivery PRs. Each PR is merged before the next s - [ ] T047 [P] [US2] Add API methods and types for authorizations and client credentials in `frontend/src/services/api.ts` and `frontend/src/types/` - [ ] T048 [US2] Vitest `frontend/tests/unit/authorize-request.spec.ts`: fixed client view, unverified-name label, access sentence, profile shown not asked when bound, Approve disabled until a profile is chosen when `profile_required`, replace-login checkbox only with `previous_login`, guard verdict fetched through the preview call whenever the selection is complete or changes, refusal with fixes shown and Approve disabled until it is clean, `already_decided` and `binding_changed` handling, navigation to `redirect_url` - [ ] T049 [US2] Implement `frontend/src/views/AuthorizeRequest.vue` and the `/authorize` route in `frontend/src/router/index.ts`, reusing `GuardRefusal.vue`, `ProfileChip.vue` -- [ ] T049a [US5] Tests then code: `suggested_client` on the sign-in request payload (`internal/runtime/oauth_login_consent.go`, `internal/httpapi/oauth_login.go`, `internal/contracts`, `make swagger`): exactly one case-insensitive match on id, display name or known client name → present with `matched`; none or several → absent; never on a per-client address; approve and preview without a client are still refused +- [ ] T049a [US5] Tests then code: `suggested_client` on the sign-in request payload (`internal/runtime/oauth_login_consent.go`, `internal/httpapi/oauth_login.go`, `internal/contracts`, `make swagger`): exactly one case-insensitive match on id, display name or known client name → present with `matched`; none or several → absent; one client matching on several fields is one match (`matched` precedence `id`, `display_name`, `known_name`); a name equal to one client's id and another's display name → absent; a trailing parenthesised suffix is also tried without it; never on a per-client address; with a suggestion present, preview without a client answers `200 {complete:false}` with no access and no guard, and approve without a client answers `422 client_required` and writes nothing - [ ] T050 [US5] Vitest in `frontend/tests/unit/authorize-request.spec.ts` for the generic address: "New client" selected when there is no `suggested_client`, the suggested client selected with the unverified-name notice when there is one, changing the selection sends the changed client, "New client" with editable id and name, existing-client choice shows the access sentence, `identity_exists` / `reserved_identity` errors - [ ] T051 [US5] Implement the generic-address branch in `frontend/src/views/AuthorizeRequest.vue` - [ ] T052 [US4] Vitest then code: with no API key in storage `AuthorizeRequest.vue` shows only "Open from the tray or paste the API key", makes no request-detail call, and continues after a pasted key (`frontend/tests/unit/authorize-request-nokey.spec.ts`)