Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ assigned at release.

## Unreleased

- Fixed: MCP OAuth clients whose every redirect URI is a Google Connected Apps callback (`oauth-redirect`, `oauth-redirect-sandbox` or `oauth-redirect-test` on `googleusercontent.com`, single `/r/<id>` or `/a/<id>` segment) get the stable refresh token Google requires: refresh returns the presented refresh token, extends its expiry to 30 days after that refresh and issues the new access token as a linked session row, so earlier access tokens stay valid until their own expiry. Expired linked rows are deleted on the next refresh, and their tokens never refresh. Revoking the refresh token or the grant ends every linked access token; a replayed continuation code revokes its session and its linked rows, and continuation detection counts only code-issued sessions. Every other client keeps rotation. Each such refresh logs outcome `extended` (migration 0085 `mcp_oauth_sessions.parent_session_id`; docs/mcp-oauth.md).
- Fixed: an MCP OAuth refresh whose response never reached the client no longer revokes the connection when the client retries with its retired refresh token more than 30 seconds later. While the exact pair that token was rotated into has never been used as a bearer token, the server rotates that pair again and returns the new pair on the same grant and approved agent, for up to 36 hours after the first rotation and never past the retired token's own expiry; the re-issued pair keeps its refresh expiry. A retry within 30 seconds of a recovery is refused without revoking, like a retry within 30 seconds of the rotation. Reuse after the successor pair was used still revokes the grant. Bearer admission records first use of each pair (`mcp_oauth_sessions.current_pair_used_at`) and each rotation records its successor on the retired token. Revoking a retired refresh token at the revocation endpoint now ends its grant. Rotations made before the upgrade are not recoverable. Each refresh logs one `mcp_oauth_refresh` line with outcome, grant ID, reason and seconds since retirement, never a token, hash, user ID or agent name (migration 0084; docs/mcp-oauth.md).
- Added: optional `SELFHOST_ROUTED_SITE_URL` (an https origin) for a deployment reached through an edge router on another site origin. When a request carries exactly one `x-original-host` header naming that origin's host, the Desktop/CLI sign-in answers (browser handoff `api_url`, desktop session, workspace switch, device start `verification_uri`, device and enrollment token `api_url`, and refresh `apiUrl`) name it instead of the Host-selected origin, so a Desktop that signed in through that site accepts them. The header only selects the configured value and is never echoed; emailed links, OIDC redirect URIs, the MCP endpoint URL, cookies and browser origin checks are unchanged. The router must overwrite `x-original-host`. Unset: unchanged. No migration.
- Added: a session bridge for organizations moved from Agent Relay Cloud (migration 0083; docs/identity.md). Off by default (`SELFHOST_CLOUD_BRIDGE_ENABLED`); while off its routes answer 404. Cloud signs a short-lived, single-use Ed25519 assertion for a browser with a live Cloud session and posts it to `/cloud/api/v1/auth/cloud-bridge/consume`; this deployment verifies it against `SELFHOST_CLOUD_BRIDGE_PUBLIC_KEYS` and issues its own browser session for the existing user (matched by id, never email) in an organization the operator listed with a time-boxed window (`/api/v1/installation/cloud-bridge/organizations`, bootstrap bearer only). It creates nothing, accepts no Cloud token, and is refused after the person signs out here.
Expand Down
33 changes: 32 additions & 1 deletion docs/mcp-oauth.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,15 +145,46 @@ refused without revoking, like a retry within 30 seconds of the rotation.
Otherwise the retired token counts as reuse
and revokes the grant. Revoking a retired refresh token at the revocation
endpoint ends the grant. Each refresh logs one `mcp_oauth_refresh` line with
`outcome` (`rotated`, `reissued_undelivered`, `refused` or `revoked`), the
`outcome` (`rotated`, `extended`, `reissued_undelivered`, `refused` or
`revoked`), the
grant ID, a reason and the seconds since retirement; it never logs tokens,
hashes, user IDs or agent names.

Google Connected Apps requires a refresh to return the refresh token it was
given. A client whose every registered redirect URI is a Google Connected Apps
callback (`https://oauth-redirect.googleusercontent.com`, or its `-sandbox`
and `-test` hosts, with a single `/r/<id>` or `/a/<id>` path segment and no
query, fragment or userinfo) therefore gets stable refresh instead of
rotation: the refresh response returns the presented refresh token, its
expiry moves to 30 days after that refresh, and the new access token is
issued as a separate session row linked to the code-issued session. Earlier
access tokens stay valid until their own one-hour expiry. A linked row's own
refresh token is never returned and is refused if presented; expired linked
rows are deleted at the next refresh. This is a weaker bearer lifecycle than
rotation: a copied refresh token keeps working until it expires or is
revoked, with no reuse detection or undelivered-response recovery, so it is
limited to that callback set. A client with any other redirect URI keeps
rotation. Revoking the refresh token or the grant ends every access token it
issued. A replayed authorization code that continued an existing connection
revokes only the session that code issued and the access tokens refreshed
from it; continuation detection does not count those refreshed rows.

Upgrading to migration 0084: rotations made before the upgrade are not
recoverable, so their reuse revokes the grant as before. During a rolling
upgrade a server still on the previous version neither records first use nor
writes the successor link.

Upgrading to migration 0085 (`mcp_oauth_sessions.parent_session_id`): apply it
before the new version serves traffic, because new sessions write that
column. During a rolling upgrade a server still on the previous version
rotates the refresh token of a Google callback client as before and counts
its refreshed rows in continuation detection, and its code-replay
revocation of a continuation session leaves that session's linked rows live
until their one-hour expiry. A Google callback connection whose refresh
token a previous version already rotated is not repaired by the upgrade: a
client that kept the earlier token presents a retired token, which follows
the reuse rules above, and the connector must be reconnected once.

Each connection acts only as its approved relay agent. First use pins the
agent's immutable ID. A rename follows that same ID; a replacement holding
its previous name cannot take over the connection. MCP session IDs identify
Expand Down
13 changes: 13 additions & 0 deletions migrations/0085_mcp_oauth_session_parent.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
-- MCP OAuth stable refresh for Google Connected Apps clients (docs/mcp-oauth.md).
-- parent_session_id: the root session (issued by an authorization code) of a
-- refreshed access session. The refresh token stays on the root; each refresh
-- adds one child row whose own refresh token is never returned. A code replay
-- of a continued grant revokes the root and its children, and continuation
-- detection counts root sessions only. NULL for every root session.
ALTER TABLE mcp_oauth_sessions ADD COLUMN IF NOT EXISTS parent_session_id uuid
REFERENCES mcp_oauth_sessions(id) ON DELETE CASCADE;
-- Child rows only: the revoke and prune lookups never search for NULL.
CREATE INDEX IF NOT EXISTS mcp_oauth_sessions_parent_idx ON mcp_oauth_sessions (parent_session_id)
WHERE parent_session_id IS NOT NULL;

-- Existing rows keep NULL: they are all root sessions.
8 changes: 6 additions & 2 deletions scripts/cloud-import-verify/schema-manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,8 @@
{"name":"0080_staff_read_grants_year_cap.sql","sha256":"86d678003039015d447a4d3461830082d0a3bf03a578ece20526ccf763e4f562"},
{"name":"0081_cursor_cloud_identity.sql","sha256":"4b8bd4a7e758708db798f953fe50b0f225ca1db17e841a490ce363940c4a949c"},
{"name":"0083_cloud_bridge.sql","sha256":"5209e515add2701035cee73757ddadc18fe337b47ab443aad82555d5e52de210"},
{"name":"0084_mcp_oauth_undelivered_refresh.sql","sha256":"858162f963c0b29539c6ef7c3a4a3a7f3e365b8bcedbb48e40e241f8f434fcd4"}
{"name":"0084_mcp_oauth_undelivered_refresh.sql","sha256":"858162f963c0b29539c6ef7c3a4a3a7f3e365b8bcedbb48e40e241f8f434fcd4"},
{"name":"0085_mcp_oauth_session_parent.sql","sha256":"a2f709681bb844df11f81fe2ca3c6b8e1a7ac7d6bf53892663efcb4014cf29a3"}
],
"required":[
{"kind":"column","name":"public.admin_audit_events.action","definition":{"collation":"pg_catalog.default","default":null,"generated":"","identity":"","not_null":true,"position":6,"type":"text"}},
Expand Down Expand Up @@ -746,6 +747,7 @@
{"kind":"column","name":"public.mcp_oauth_sessions.id","definition":{"collation":null,"default":null,"generated":"","identity":"","not_null":true,"position":1,"type":"uuid"}},
{"kind":"column","name":"public.mcp_oauth_sessions.last_refreshed_at","definition":{"collation":null,"default":null,"generated":"","identity":"","not_null":false,"position":16,"type":"timestamp with time zone"}},
{"kind":"column","name":"public.mcp_oauth_sessions.organization_id","definition":{"collation":null,"default":null,"generated":"","identity":"","not_null":true,"position":5,"type":"uuid"}},
{"kind":"column","name":"public.mcp_oauth_sessions.parent_session_id","definition":{"collation":null,"default":null,"generated":"","identity":"","not_null":false,"position":18,"type":"uuid"}},
{"kind":"column","name":"public.mcp_oauth_sessions.refresh_token_expires_at","definition":{"collation":null,"default":null,"generated":"","identity":"","not_null":true,"position":11,"type":"timestamp with time zone"}},
{"kind":"column","name":"public.mcp_oauth_sessions.refresh_token_hash","definition":{"collation":"pg_catalog.default","default":null,"generated":"","identity":"","not_null":true,"position":9,"type":"text"}},
{"kind":"column","name":"public.mcp_oauth_sessions.revoked_at","definition":{"collation":null,"default":null,"generated":"","identity":"","not_null":false,"position":12,"type":"timestamp with time zone"}},
Expand Down Expand Up @@ -1564,6 +1566,7 @@
{"kind":"constraint","name":"public.mcp_oauth_sessions.mcp_oauth_sessions_access_token_hash_key","definition":{"deferrable":false,"deferred":false,"definition":"UNIQUE (access_token_hash)","no_inherit":true,"triggers":[],"type":"u","validated":true}},
{"kind":"constraint","name":"public.mcp_oauth_sessions.mcp_oauth_sessions_grant_id_organization_id_works_fkey","definition":{"deferrable":false,"deferred":false,"definition":"FOREIGN KEY (grant_id, organization_id, workspace_id, user_id) REFERENCES mcp_oauth_grants(id, organization_id, workspace_id, user_id) ON DELETE CASCADE","no_inherit":true,"triggers":[{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_cascade_del","table":"public.mcp_oauth_grants","type":9},{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_noaction_upd","table":"public.mcp_oauth_grants","type":17},{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_check_ins","table":"public.mcp_oauth_sessions","type":5},{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_check_upd","table":"public.mcp_oauth_sessions","type":17}],"type":"f","validated":true}},
{"kind":"constraint","name":"public.mcp_oauth_sessions.mcp_oauth_sessions_grant_id_token_family_id_fkey","definition":{"deferrable":false,"deferred":false,"definition":"FOREIGN KEY (grant_id, token_family_id) REFERENCES mcp_oauth_grants(id, token_family_id) ON DELETE CASCADE","no_inherit":true,"triggers":[{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_cascade_del","table":"public.mcp_oauth_grants","type":9},{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_noaction_upd","table":"public.mcp_oauth_grants","type":17},{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_check_ins","table":"public.mcp_oauth_sessions","type":5},{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_check_upd","table":"public.mcp_oauth_sessions","type":17}],"type":"f","validated":true}},
{"kind":"constraint","name":"public.mcp_oauth_sessions.mcp_oauth_sessions_parent_session_id_fkey","definition":{"deferrable":false,"deferred":false,"definition":"FOREIGN KEY (parent_session_id) REFERENCES mcp_oauth_sessions(id) ON DELETE CASCADE","no_inherit":true,"triggers":[{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_check_ins","table":"public.mcp_oauth_sessions","type":5},{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_cascade_del","table":"public.mcp_oauth_sessions","type":9},{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_check_upd","table":"public.mcp_oauth_sessions","type":17},{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_noaction_upd","table":"public.mcp_oauth_sessions","type":17}],"type":"f","validated":true}},
{"kind":"constraint","name":"public.mcp_oauth_sessions.mcp_oauth_sessions_pkey","definition":{"deferrable":false,"deferred":false,"definition":"PRIMARY KEY (id)","no_inherit":true,"triggers":[],"type":"p","validated":true}},
{"kind":"constraint","name":"public.mcp_oauth_sessions.mcp_oauth_sessions_refresh_token_hash_check","definition":{"deferrable":false,"deferred":false,"definition":"CHECK ((refresh_token_hash ~ '^[0-9a-f]{64}$'::text))","no_inherit":false,"triggers":[],"type":"c","validated":true}},
{"kind":"constraint","name":"public.mcp_oauth_sessions.mcp_oauth_sessions_refresh_token_hash_key","definition":{"deferrable":false,"deferred":false,"definition":"UNIQUE (refresh_token_hash)","no_inherit":true,"triggers":[],"type":"u","validated":true}},
Expand Down Expand Up @@ -1950,6 +1953,7 @@
{"kind":"index","name":"public.mcp_oauth_sessions.mcp_oauth_session_receipt_owner","definition":{"definition":"CREATE UNIQUE INDEX mcp_oauth_session_receipt_owner ON public.mcp_oauth_sessions USING btree (id, grant_id, organization_id, workspace_id, user_id)","live":true,"nulls_not_distinct":false,"primary":false,"ready":true,"unique":true,"valid":true}},
{"kind":"index","name":"public.mcp_oauth_sessions.mcp_oauth_sessions_access_token_hash_key","definition":{"definition":"CREATE UNIQUE INDEX mcp_oauth_sessions_access_token_hash_key ON public.mcp_oauth_sessions USING btree (access_token_hash)","live":true,"nulls_not_distinct":false,"primary":false,"ready":true,"unique":true,"valid":true}},
{"kind":"index","name":"public.mcp_oauth_sessions.mcp_oauth_sessions_family_idx","definition":{"definition":"CREATE INDEX mcp_oauth_sessions_family_idx ON public.mcp_oauth_sessions USING btree (token_family_id)","live":true,"nulls_not_distinct":false,"primary":false,"ready":true,"unique":false,"valid":true}},
{"kind":"index","name":"public.mcp_oauth_sessions.mcp_oauth_sessions_parent_idx","definition":{"definition":"CREATE INDEX mcp_oauth_sessions_parent_idx ON public.mcp_oauth_sessions USING btree (parent_session_id) WHERE (parent_session_id IS NOT NULL)","live":true,"nulls_not_distinct":false,"primary":false,"ready":true,"unique":false,"valid":true}},
{"kind":"index","name":"public.mcp_oauth_sessions.mcp_oauth_sessions_pkey","definition":{"definition":"CREATE UNIQUE INDEX mcp_oauth_sessions_pkey ON public.mcp_oauth_sessions USING btree (id)","live":true,"nulls_not_distinct":false,"primary":true,"ready":true,"unique":true,"valid":true}},
{"kind":"index","name":"public.mcp_oauth_sessions.mcp_oauth_sessions_refresh_token_hash_key","definition":{"definition":"CREATE UNIQUE INDEX mcp_oauth_sessions_refresh_token_hash_key ON public.mcp_oauth_sessions USING btree (refresh_token_hash)","live":true,"nulls_not_distinct":false,"primary":false,"ready":true,"unique":true,"valid":true}},
{"kind":"index","name":"public.organization_domains.organization_domains_org_idx","definition":{"definition":"CREATE INDEX organization_domains_org_idx ON public.organization_domains USING btree (organization_id)","live":true,"nulls_not_distinct":false,"primary":false,"ready":true,"unique":false,"valid":true}},
Expand Down Expand Up @@ -2191,5 +2195,5 @@
"optional":{

},
"sha256":"4909c8c82aa36e0bc46f1fa88db802d0219ee2d1f6ea91b0e3768774ddd79d91"
"sha256":"31312611794027d498f23bfaff98bdb5c82c06a5b20c19be743251296428ff66"
}
23 changes: 23 additions & 0 deletions src/mcp/oauth/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@ const MAX_STATE_LENGTH = 4 * 1024;
const MAX_NONCE_LENGTH = 1024;
// WHATWG URL keeps IPv6 brackets in `hostname`; the bare form is accepted defensively.
const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
const GOOGLE_CONNECTED_APPS_REDIRECT_HOSTS = new Set([
"oauth-redirect.googleusercontent.com",
"oauth-redirect-sandbox.googleusercontent.com",
"oauth-redirect-test.googleusercontent.com",
]);

export function isValidCodeChallenge(value: string): boolean {
return CODE_CHALLENGE_PATTERN.test(value);
Expand Down Expand Up @@ -91,6 +96,24 @@ export function isAllowedRedirectUri(raw: string): boolean {
return parseSafeOAuthUrl(raw) !== null;
}

/** Google Connected Apps callback families that require stable refresh tokens. */
export function isGoogleConnectedAppsRedirectUri(raw: string): boolean {
try {
const url = new URL(raw);
return url.protocol === "https:" &&
GOOGLE_CONNECTED_APPS_REDIRECT_HOSTS.has(url.hostname.toLowerCase()) &&
(/^\/r\/[^/]+$/u.test(url.pathname) || /^\/a\/[^/]+$/u.test(url.pathname)) &&
!url.search && !url.hash && !url.username && !url.password;
} catch {
return false;
}
}

/** True only when every registered callback is a Google Connected Apps callback. */
export function usesGoogleConnectedAppsPersistentRefresh(redirectUris: readonly string[]): boolean {
return redirectUris.length > 0 && redirectUris.every(isGoogleConnectedAppsRedirectUri);
}

/** OIDC pairwise-subject sector when no sector_identifier_uri is registered. */
export function oidcSectorIdentifierForRedirectUri(raw: string): string {
return new URL(raw).hostname.toLowerCase();
Expand Down
Loading
Loading