diff --git a/CHANGELOG.md b/CHANGELOG.md index ff41a15..245acb9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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/` or `/a/` 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. diff --git a/docs/mcp-oauth.md b/docs/mcp-oauth.md index 47066c9..8ebb8fd 100644 --- a/docs/mcp-oauth.md +++ b/docs/mcp-oauth.md @@ -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/` or `/a/` 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 diff --git a/migrations/0085_mcp_oauth_session_parent.sql b/migrations/0085_mcp_oauth_session_parent.sql new file mode 100644 index 0000000..7ccdc8b --- /dev/null +++ b/migrations/0085_mcp_oauth_session_parent.sql @@ -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. diff --git a/scripts/cloud-import-verify/schema-manifest.json b/scripts/cloud-import-verify/schema-manifest.json index 4b1628e..936ffdb 100644 --- a/scripts/cloud-import-verify/schema-manifest.json +++ b/scripts/cloud-import-verify/schema-manifest.json @@ -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"}}, @@ -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"}}, @@ -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}}, @@ -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}}, @@ -2191,5 +2195,5 @@ "optional":{ }, - "sha256":"4909c8c82aa36e0bc46f1fa88db802d0219ee2d1f6ea91b0e3768774ddd79d91" + "sha256":"31312611794027d498f23bfaff98bdb5c82c06a5b20c19be743251296428ff66" } diff --git a/src/mcp/oauth/protocol.ts b/src/mcp/oauth/protocol.ts index ac133a6..8e08622 100644 --- a/src/mcp/oauth/protocol.ts +++ b/src/mcp/oauth/protocol.ts @@ -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); @@ -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(); diff --git a/src/mcp/oauth/sessions.ts b/src/mcp/oauth/sessions.ts index 8e9d1e3..a9f7b2a 100644 --- a/src/mcp/oauth/sessions.ts +++ b/src/mcp/oauth/sessions.ts @@ -28,6 +28,8 @@ export type McpOAuthSessionRecord = McpOAuthSessionOwner & { sessionId: string; scopes: string[]; grantScopes: string[]; resource: string; clientId: string; revokedAt: Date | null; grantRevokedAt: Date | null; accessTokenExpiresAt: Date; refreshTokenExpiresAt: Date; + /** Root session of a stable-refresh child; null for a root session. */ + parentSessionId: string | null; }; export type McpOAuthAccess = { principal: Principal; @@ -38,7 +40,7 @@ type SessionRow = { id: string; grant_id: string; token_family_id: string; user_id: string; organization_id: string; workspace_id: string; scopes: string[]; grant_scopes: string[]; resource: string; client_id: string; revoked_at: Date | string | null; grant_revoked_at: Date | string | null; - access_token_expires_at: Date | string; refresh_token_expires_at: Date | string; + access_token_expires_at: Date | string; refresh_token_expires_at: Date | string; parent_session_id: string | null; }; function record(row: SessionRow): McpOAuthSessionRecord { @@ -46,7 +48,8 @@ function record(row: SessionRow): McpOAuthSessionRecord { organizationId: row.organization_id, workspaceId: row.workspace_id, scopes: row.scopes, grantScopes: row.grant_scopes, resource: row.resource, clientId: row.client_id, revokedAt: row.revoked_at ? new Date(row.revoked_at) : null, grantRevokedAt: row.grant_revoked_at ? new Date(row.grant_revoked_at) : null, - accessTokenExpiresAt: new Date(row.access_token_expires_at), refreshTokenExpiresAt: new Date(row.refresh_token_expires_at) }; + accessTokenExpiresAt: new Date(row.access_token_expires_at), refreshTokenExpiresAt: new Date(row.refresh_token_expires_at), + parentSessionId: row.parent_session_id ?? null }; } export class McpOAuthSessions { @@ -70,16 +73,22 @@ export class McpOAuthSessions { throw new Error("OAuth session does not match an active consented grant"); } const createdAt = this.now(); + return this.insert(tx, input, scopes, createdAt, new Date(createdAt.getTime()+REFRESH_TTL_MS), null); + } + + /** The only session INSERT. A child row (parentSessionId set) is a stable-refresh access sibling of a root session. */ + private async insert(tx: SqlExecutor, owner: McpOAuthSessionOwner, scopes: string[], createdAt: Date, refreshExpires: Date, + parentSessionId: string | null): Promise { const sessionId = randomUUID(); const accessToken = opaqueToken(MCP_OAUTH_ACCESS_PREFIX), refreshToken = opaqueToken(MCP_OAUTH_REFRESH_PREFIX); - const accessExpires = new Date(createdAt.getTime()+ACCESS_TTL_MS), refreshExpires = new Date(createdAt.getTime()+REFRESH_TTL_MS); + const accessExpires = new Date(createdAt.getTime()+ACCESS_TTL_MS); await tx.query(`INSERT INTO mcp_oauth_sessions (id,grant_id,token_family_id,user_id,organization_id,workspace_id,scopes,access_token_hash,refresh_token_hash, - access_token_expires_at,refresh_token_expires_at,created_at,updated_at) - VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$12)`, - [sessionId,input.grantId,input.tokenFamilyId,input.userId,input.organizationId,input.workspaceId,scopes, - hashSecret(accessToken),hashSecret(refreshToken),accessExpires,refreshExpires,createdAt]); - return { sessionId,tokenFamilyId:input.tokenFamilyId,accessToken,refreshToken, + access_token_expires_at,refresh_token_expires_at,created_at,updated_at,parent_session_id) + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$12,$13)`, + [sessionId,owner.grantId,owner.tokenFamilyId,owner.userId,owner.organizationId,owner.workspaceId,scopes, + hashSecret(accessToken),hashSecret(refreshToken),accessExpires,refreshExpires,createdAt,parentSessionId]); + return { sessionId,tokenFamilyId:owner.tokenFamilyId,accessToken,refreshToken, accessTokenExpiresAt:accessExpires.toISOString(),refreshTokenExpiresAt:refreshExpires.toISOString(),scopes }; } @@ -107,7 +116,7 @@ export class McpOAuthSessions { last_refreshed_at=$6,updated_at=$6,current_pair_used_at=NULL FROM mcp_oauth_grants g,organization_memberships m,workspaces w, (SELECT id,refresh_token_expires_at FROM mcp_oauth_sessions WHERE refresh_token_hash=$1) prior - WHERE s.refresh_token_hash=$1 AND prior.id=s.id AND s.revoked_at IS NULL AND s.refresh_token_expires_at>$6 + WHERE s.refresh_token_hash=$1 AND prior.id=s.id AND s.parent_session_id IS NULL AND s.revoked_at IS NULL AND s.refresh_token_expires_at>$6 AND s.grant_id=$7 AND s.token_family_id=$8 AND s.user_id=$9 AND s.organization_id=$10 AND s.workspace_id=$11 AND g.id=s.grant_id AND g.revoked_at IS NULL AND m.organization_id=s.organization_id AND m.user_id=s.user_id @@ -137,7 +146,8 @@ export class McpOAuthSessions { SET access_token_hash=$2,refresh_token_hash=$3,access_token_expires_at=LEAST($4::timestamptz,s.refresh_token_expires_at), last_refreshed_at=$5,updated_at=$5,current_pair_used_at=NULL FROM mcp_oauth_grants g,organization_memberships m,workspaces w - WHERE s.refresh_token_hash=$1 AND s.revoked_at IS NULL AND s.current_pair_used_at IS NULL AND s.refresh_token_expires_at>$5 + WHERE s.refresh_token_hash=$1 AND s.parent_session_id IS NULL AND s.revoked_at IS NULL AND s.current_pair_used_at IS NULL + AND s.refresh_token_expires_at>$5 AND s.grant_id=$6 AND s.token_family_id=$7 AND s.user_id=$8 AND s.organization_id=$9 AND s.workspace_id=$10 AND g.id=s.grant_id AND g.revoked_at IS NULL AND m.organization_id=s.organization_id AND m.user_id=s.user_id @@ -153,13 +163,45 @@ export class McpOAuthSessions { refreshTokenExpiresAt:new Date(row.refresh_token_expires_at).toISOString(),scopes:row.scopes }; } + /** + * Stable refresh for clients whose callbacks are all Google Connected Apps callbacks: the presented refresh token + * stays on its root session (the anchor), whose refresh expiry is extended; access, refresh hash and + * current_pair_used_at of the anchor are untouched. The new access token is a child row of the anchor whose own + * refresh token is never returned and expires with that access token, so earlier access tokens stay valid until + * their own expiry. The UPDATE is the anchor's row lock and refresh CAS; it applies the same grant, membership, + * workspace and tenancy guards as rotate. Children past expiry are deleted here (nothing else prunes sessions); + * a child is never a code receipt and has no children, so the delete cascades nothing. + */ + async refreshStable(tx: SqlExecutor, refreshToken: string, expected: McpOAuthSessionOwner): Promise { + if (!REFRESH_PATTERN.test(refreshToken)) return null; + const now = this.now(), refreshExpires = new Date(now.getTime()+REFRESH_TTL_MS); + const result = await tx.query<{ id: string; scopes: string[] }>(`UPDATE mcp_oauth_sessions s + SET refresh_token_expires_at=$2,last_refreshed_at=$3,updated_at=$3 + FROM mcp_oauth_grants g,organization_memberships m,workspaces w + WHERE s.refresh_token_hash=$1 AND s.parent_session_id IS NULL AND s.revoked_at IS NULL AND s.refresh_token_expires_at>$3 + AND s.grant_id=$4 AND s.token_family_id=$5 AND s.user_id=$6 AND s.organization_id=$7 AND s.workspace_id=$8 + AND g.id=s.grant_id AND g.revoked_at IS NULL + AND m.organization_id=s.organization_id AND m.user_id=s.user_id + AND w.id=s.workspace_id AND w.organization_id=s.organization_id + AND ($9::text='multi' OR NOT EXISTS (SELECT 1 FROM organizations other WHERE other.id<>s.organization_id)) + RETURNING s.id,s.scopes`,[hashSecret(refreshToken),refreshExpires,now, + expected.grantId,expected.tokenFamilyId,expected.userId,expected.organizationId,expected.workspaceId,this.options.tenancyMode]); + const anchor = result.rows[0]; + if (!anchor) return null; + await tx.query(`DELETE FROM mcp_oauth_sessions s WHERE s.parent_session_id=$1 AND s.refresh_token_expires_at<=$2 + AND NOT EXISTS (SELECT 1 FROM mcp_oauth_authorization_codes c WHERE c.issued_session_id=s.id)`,[anchor.id,now]); + const child = await this.insert(tx, expected, anchor.scopes, now, new Date(now.getTime()+ACCESS_TTL_MS), anchor.id); + return { ...child,refreshToken,refreshTokenExpiresAt:refreshExpires.toISOString() }; + } + async revokeFamily(tx: SqlExecutor, owner: McpOAuthSessionOwner, reason: string): Promise { await revokeMcpOAuthSessionFamily(tx, owner, reason, this.now()); } + /** Ends one root session and its stable-refresh children. */ async revokeSession(tx: SqlExecutor, sessionId: string, owner: McpOAuthSessionOwner, reason: string): Promise { await tx.query(`UPDATE mcp_oauth_sessions SET revoked_at=$7,revoked_reason=$8,updated_at=$7 - WHERE id=$1 AND grant_id=$2 AND token_family_id=$3 AND user_id=$4 AND organization_id=$5 AND workspace_id=$6 AND revoked_at IS NULL`, + WHERE (id=$1 OR parent_session_id=$1) AND grant_id=$2 AND token_family_id=$3 AND user_id=$4 AND organization_id=$5 AND workspace_id=$6 AND revoked_at IS NULL`, [sessionId,owner.grantId,owner.tokenFamilyId,owner.userId,owner.organizationId,owner.workspaceId,this.now(),reason]); } diff --git a/src/mcp/oauth/store.ts b/src/mcp/oauth/store.ts index 96c15a3..db59594 100644 --- a/src/mcp/oauth/store.ts +++ b/src/mcp/oauth/store.ts @@ -8,7 +8,7 @@ import { randomBytes, randomUUID } from "node:crypto"; import type { Database, SqlExecutor } from "../../database.js"; import { hashSecret } from "../../crypto.js"; import { lockOrganization, lockUser, type TenancyMode } from "../../tenancy.js"; -import { isValidCodeVerifier, pkceS256, oidcSectorIdentifierForRedirectUri, +import { isValidCodeVerifier, pkceS256, oidcSectorIdentifierForRedirectUri, usesGoogleConnectedAppsPersistentRefresh, type AuthorizationRequest, type ClientRegistrationInput, type McpAuthorizationScope, type OAuthErrorBody, type createMcpOAuthProtocol } from "./protocol.js"; import { McpOAuthSessions, MCP_OAUTH_REFRESH_PREFIX, type McpOAuthIssuedPair, type McpOAuthSessionOwner } from "./sessions.js"; @@ -45,7 +45,7 @@ export type McpOAuthTokenResponse = { access_token: string; token_type: "Bearer" export type McpOAuthTokenResult = { ok: true; body: McpOAuthTokenResponse } | { ok: false; status: number; error: OAuthErrorBody }; /** One `mcp_oauth_refresh` line per refresh outcome; never a token, hash, user or agent name. */ -export type McpOAuthRefreshLog = { outcome: "rotated" | "reissued_undelivered" | "refused" | "revoked"; +export type McpOAuthRefreshLog = { outcome: "rotated" | "extended" | "reissued_undelivered" | "refused" | "revoked"; grantId?: string; reason?: string; retiredForSeconds?: number }; type RefreshOutcome = [McpOAuthTokenResult, McpOAuthRefreshLog]; type RetiredRow = { grant_id: string; retired_at: Date | string; successor_token_hash: string | null; @@ -68,7 +68,7 @@ function refused(reason: string, grantId?: string, retiredForSeconds?: number): return [reason==="resource_mismatch"?invalidTarget():invalidGrant(),refreshLog("refused",grantId,reason,retiredForSeconds)]; } function logRefresh(entry: McpOAuthRefreshLog): void { - (entry.outcome==="rotated"?console.info:console.warn)("[mcp-oauth] refresh",{ event:"mcp_oauth_refresh",...entry }); + (entry.outcome==="rotated" || entry.outcome==="extended"?console.info:console.warn)("[mcp-oauth] refresh",{ event:"mcp_oauth_refresh",...entry }); } function ownerOf(row: GrantRow): McpOAuthSessionOwner { return { grantId:row.id,tokenFamilyId:row.token_family_id,userId:row.user_id,organizationId:row.organization_id,workspaceId:row.workspace_id }; @@ -233,10 +233,11 @@ export class McpOAuthStore { grant.client_id!==row.client_id || grant.resource!==row.resource)) return invalidGrant(); const previousSessions=grant && !grant.continued_at && resourcePath==="/api/v1/mcp/relay-events" ? (await tx.query(`SELECT id FROM mcp_oauth_sessions WHERE grant_id=$1 AND token_family_id=$2 - AND user_id=$3 AND organization_id=$4 AND workspace_id=$5 LIMIT 2`, + AND user_id=$3 AND organization_id=$4 AND workspace_id=$5 AND parent_session_id IS NULL LIMIT 2`, [grant.id,grant.token_family_id,grant.user_id,grant.organization_id,grant.workspace_id])).rows:[]; if(grant && (grant.continued_at || previousSessions.length===2)) { if(!grant.continued_at) await tx.query("UPDATE mcp_oauth_grants SET continued_at=$2 WHERE id=$1",[grant.id,now]); + // Revokes the continuation's session and its stable-refresh children; the rest of the grant stays live. if(row.issued_session_id) await this.sessions.revokeSession(tx,row.issued_session_id,ownerOf(grant),"authorization_code_replayed"); } else if(grant) await this.revokeRows(tx,grant.id,"authorization_code_replayed"); return invalidGrant("The authorization code was already used."); @@ -341,6 +342,16 @@ export class McpOAuthStore { if(session.revokedAt) return refused("session_revoked",grant.id); if(grant.client_id!==input.clientId) return refused("client_mismatch",grant.id); if(input.resource!==undefined && this.options.protocol.canonicalMcpResourceParam(input.resource)!==grant.resource) return refused("resource_mismatch",grant.id); + // A stable-refresh child's refresh token is never returned to the client; it extends and rotates nothing. + if(session.parentSessionId!==null) return refused("child_session",grant.id); + // Google Connected Apps requires the refresh response to return the presented refresh token with an extended + // expiry. Only clients whose every registered callback is on Google's callback hosts get that weaker lifecycle; + // every other client keeps rotation, reuse detection and undelivered-response recovery. + const client=(await tx.query("SELECT * FROM mcp_oauth_clients WHERE client_id=$1",[grant.client_id])).rows[0]; + if(client && usesGoogleConnectedAppsPersistentRefresh(client.redirect_uris)) { + const extended=await this.sessions.refreshStable(tx,input.refreshToken,session); + return extended?[this.tokenResult(extended),refreshLog("extended",grant.id)]:refused("rotation_lost_race",grant.id); + } const tokens=await this.sessions.rotate(tx,input.refreshToken,session); return tokens?[this.tokenResult(tokens),refreshLog("rotated",grant.id)]:refused("rotation_lost_race",grant.id); } diff --git a/test/mcp-oauth-protocol.test.ts b/test/mcp-oauth-protocol.test.ts index 0947b69..49932bf 100644 --- a/test/mcp-oauth-protocol.test.ts +++ b/test/mcp-oauth-protocol.test.ts @@ -1,8 +1,8 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { - createMcpOAuthProtocol, isAllowedRedirectUri, isValidCodeChallenge, isValidCodeVerifier, - parseClientRegistration, pkceS256, type McpOAuthEndpoint, + createMcpOAuthProtocol, isAllowedRedirectUri, isGoogleConnectedAppsRedirectUri, isValidCodeChallenge, isValidCodeVerifier, + parseClientRegistration, pkceS256, usesGoogleConnectedAppsPersistentRefresh, type McpOAuthEndpoint, } from "../src/mcp/oauth/protocol.js"; const ORIGIN = "https://relay.example.test"; @@ -97,6 +97,23 @@ test("public client registration bounds redirect metadata and accepts no secret } }); +test("stable refresh applies only to exact Google Connected Apps callbacks", () => { + const google = "https://oauth-redirect.googleusercontent.com/r/fake-project"; + for (const uri of [google, "https://oauth-redirect.googleusercontent.com/a/fake-project", + "https://oauth-redirect-sandbox.googleusercontent.com/r/fake-project", "https://oauth-redirect-test.googleusercontent.com/a/fake-project", + "https://OAUTH-REDIRECT.googleusercontent.com/r/fake-project"]) assert.equal(isGoogleConnectedAppsRedirectUri(uri), true, uri); + for (const uri of ["http://oauth-redirect.googleusercontent.com/r/fake-project", `${google}/extra`, + "https://oauth-redirect.googleusercontent.com/r/", "https://oauth-redirect.googleusercontent.com/b/fake-project", + "https://oauth-redirect.googleusercontent.com/r/a/b", `${google}?x=1`, `${google}#x`, + "https://user:secret@oauth-redirect.googleusercontent.com/r/fake-project", + "https://other.googleusercontent.com/r/fake-project", "https://oauth-redirect.googleusercontent.com.attacker.test/r/fake-project", + "https://oauth-redirect.attacker.test/r/fake-project", "not a url"]) assert.equal(isGoogleConnectedAppsRedirectUri(uri), false, uri); + assert.equal(usesGoogleConnectedAppsPersistentRefresh([google]), true); + assert.equal(usesGoogleConnectedAppsPersistentRefresh([google, "https://oauth-redirect-sandbox.googleusercontent.com/r/fake-project"]), true); + assert.equal(usesGoogleConnectedAppsPersistentRefresh([]), false); + assert.equal(usesGoogleConnectedAppsPersistentRefresh([google, REDIRECT]), false); +}); + test("PKCE S256 matches the RFC vector and rejects malformed verifier/challenge lengths", () => { assert.equal(pkceS256("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"), "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"); for (const size of [43, 128]) assert.equal(isValidCodeVerifier("a".repeat(size)), true); diff --git a/test/mcp-oauth-token-flow.test.ts b/test/mcp-oauth-token-flow.test.ts index 8404448..10fab11 100644 --- a/test/mcp-oauth-token-flow.test.ts +++ b/test/mcp-oauth-token-flow.test.ts @@ -19,7 +19,7 @@ function issued(result:McpOAuthTokenResult) { return result.body; } -async function fixture(t:test.TestContext) { +async function fixture(t:test.TestContext,redirectUris=["https://x.ai/callback"]) { const database=new PGliteDatabase(); t.after(()=>database.close()); await migrate(database); const owner={ userId:randomUUID(),organizationId:randomUUID(),workspaceId:randomUUID(),agentName:"fake-agent" }; await database.query("INSERT INTO users(id,email,name) VALUES ($1,'fake@example.test','Fake User')",[owner.userId]); @@ -36,7 +36,7 @@ async function fixture(t:test.TestContext) { issueIdToken:input=>{ if(signerFails) throw new Error("fake signer failure"); signed.push(input); return "fake-id-token"; }, logRefresh:entry=>{ refreshLogs.push(entry); }, }); - const client=await store.registerMcpOAuthClient({ clientName:"fake-client",redirectUris:["https://x.ai/callback"] }); + const client=await store.registerMcpOAuthClient({ clientName:"fake-client",redirectUris }); function authorization(overrides:Record={}) { const result=protocol.validateAuthorizationRequest({ client_id:client.clientId,redirect_uri:client.redirectUris[0]!, response_type:"code",code_challenge:pkceS256(VERIFIER),code_challenge_method:"S256",resource:`${ORIGIN}/cloud${SHARED}`,...overrides },client); @@ -550,3 +550,174 @@ test("organization departure revokes every workspace while preserving session re assert.equal(await f.count("sessions"),3); assert.equal(await f.count("revocations"),2); assert.equal((await f.store.refreshMcpOAuthToken({ refreshToken:first.refresh_token,clientId:f.client.clientId,resource:undefined })).ok,false); }); + +const GOOGLE_CALLBACK="https://oauth-redirect.googleusercontent.com/r/fake-project"; +const MINUTE=60*1000,DAY=24*60*MINUTE; + +/** A delivered pair for a client whose only callback is a Google Connected Apps callback. */ +async function stableRefresh(t:test.TestContext,request:Record={},redirectUris=[GOOGLE_CALLBACK]) { + const f=await fixture(t,redirectUris),code=await f.create(request),first=issued(await f.exchange(code)),id=await f.grantId(code); + const resource=request.resource??`${ORIGIN}/cloud${SHARED}`; + const refresh=(token=first.refresh_token,clientId=f.client.clientId,resourceParam:string|undefined=undefined)=> + f.store.refreshMcpOAuthToken({ refreshToken:token,clientId,resource:resourceParam }); + const resolve=(token:string)=>f.store.sessions.resolveAccessToken(token,resource); + const anchor=async()=>(await f.database.query<{ id:string; access_token_hash:string; refresh_token_hash:string; refresh_token_expires_at:Date }>( + "SELECT id,access_token_hash,refresh_token_hash,refresh_token_expires_at FROM mcp_oauth_sessions WHERE refresh_token_hash=$1", + [hashSecret(first.refresh_token)])).rows[0]!; + const children=async(parent:string)=>(await f.database.query<{ id:string; access_token_hash:string }>( + "SELECT id,access_token_hash FROM mcp_oauth_sessions WHERE parent_session_id=$1 ORDER BY created_at",[parent])).rows; + const retired=async()=>(await f.database.query<{ n:number }>("SELECT count(*)::int AS n FROM mcp_oauth_retired_refresh_tokens")).rows[0]!.n; + return { ...f,code,first,id,resource,refresh,resolve,anchor,children,retired }; +} + +test("a Google Connected Apps client keeps its refresh token, extends its expiry and gets an access sibling per refresh",async t=>{ + const f=await stableRefresh(t),root=await f.anchor(),initialExpiry=root.refresh_token_expires_at.getTime(); + f.advance(10*MINUTE); + const second=issued(await f.refresh()); + assert.equal(second.refresh_token,f.first.refresh_token); assert.notEqual(second.access_token,f.first.access_token); + assert.equal(second.expires_in,3600); assert.equal(second.scope,"relay:mcp"); + const extended=await f.anchor(); + assert.equal(extended.id,root.id); assert.equal(extended.refresh_token_expires_at.getTime(),initialExpiry+10*MINUTE); + assert.equal(extended.access_token_hash,hashSecret(f.first.access_token)); + assert.deepEqual((await f.children(root.id)).map(row=>row.access_token_hash),[hashSecret(second.access_token)]); + const firstAccess=await f.resolve(f.first.access_token),secondAccess=await f.resolve(second.access_token); + assert.equal(firstAccess!.principal.sessionId,root.id); assert.notEqual(secondAccess!.principal.sessionId,root.id); + assert.equal(secondAccess!.grantId,f.id); assert.equal(secondAccess!.principal.tokenFamilyId,firstAccess!.principal.tokenFamilyId); + assert.deepEqual(secondAccess!.principal.scopes,["relay:mcp"]); + // Each access token lives to its own expiry; a later refresh does not end an earlier one. + f.advance(51*MINUTE); + assert.equal(await f.resolve(f.first.access_token),null); + assert.ok(await f.resolve(second.access_token)); + const third=issued(await f.refresh()); + assert.equal(third.refresh_token,f.first.refresh_token); + assert.ok(await f.resolve(second.access_token)); assert.ok(await f.resolve(third.access_token)); + f.advance(10*MINUTE); + assert.equal(await f.resolve(second.access_token),null); assert.ok(await f.resolve(third.access_token)); + // Past the first refresh expiry, still inside 30 days of the last refresh. + f.advance(29*DAY); + assert.ok(await f.resolve(issued(await f.refresh()).access_token)); + f.advance(2*DAY); + assert.ok(initialExpiry({ outcome:"extended",grantId:f.id }))); +}); + +test("stable refresh prunes its expired access siblings and keeps live ones",async t=>{ + const f=await stableRefresh(t),root=(await f.anchor()).id; + f.advance(MINUTE); const first=issued(await f.refresh()); + f.advance(30*MINUTE); const second=issued(await f.refresh()); + assert.equal((await f.children(root)).length,2); + f.advance(45*MINUTE); const third=issued(await f.refresh()); + assert.deepEqual((await f.children(root)).map(row=>row.access_token_hash),[hashSecret(second.access_token),hashSecret(third.access_token)]); + assert.equal(await f.resolve(first.access_token),null); + f.advance(2*60*MINUTE); issued(await f.refresh()); + assert.equal((await f.children(root)).length,1); assert.equal(await f.count("sessions"),2); + assert.ok(await f.anchor()); +}); + +test("a stable refresh token expires 30 days after its last refresh",async t=>{ + const f=await stableRefresh(t); + f.advance(DAY); issued(await f.refresh()); + f.advance(30*DAY+1_000); + const expired=await f.refresh(); + assert.ok(!expired.ok); assert.equal(expired.error.error,"invalid_grant"); + assert.equal(await f.count("revocations"),0); +}); + +test("a stable refresh child's refresh token is refused without extending anything",async t=>{ + const f=await stableRefresh(t),root=await f.anchor(); + f.advance(MINUTE); const second=issued(await f.refresh()); + const childToken=`mcp_rt_${"c".repeat(43)}`,child=(await f.children(root.id))[0]!; + await f.database.query("UPDATE mcp_oauth_sessions SET refresh_token_hash=$2 WHERE id=$1",[child.id,hashSecret(childToken)]); + const before=(await f.anchor()).refresh_token_expires_at.getTime(); + f.advance(MINUTE); + const refused=await f.refresh(childToken); + assert.ok(!refused.ok); assert.equal(refused.error.error,"invalid_grant"); + assert.deepEqual(f.refreshLogs.at(-1),{ outcome:"refused",grantId:f.id,reason:"child_session" }); + assert.equal((await f.anchor()).refresh_token_expires_at.getTime(),before); + assert.equal(await f.count("sessions"),2); assert.equal(await f.count("revocations"),0); + assert.ok(await f.resolve(second.access_token)); +}); + +test("a client with any non-Google callback keeps rotation",async t=>{ + const f=await stableRefresh(t,{},[GOOGLE_CALLBACK,"https://x.ai/callback"]); + const next=issued(await f.refresh()); + assert.notEqual(next.refresh_token,f.first.refresh_token); + assert.equal(await f.retired(),1); assert.equal(await f.count("sessions"),1); + assert.deepEqual(f.refreshLogs.at(-1),{ outcome:"rotated",grantId:f.id }); + assert.equal((await f.refresh()).ok,false); +}); + +test("stable refresh checks client and resource before extending anything",async t=>{ + const f=await stableRefresh(t),before=(await f.anchor()).refresh_token_expires_at.getTime(); + f.advance(MINUTE); + const other=await f.refresh(f.first.refresh_token,"mcpc_fake_other"); + assert.ok(!other.ok); assert.equal(other.error.error,"invalid_grant"); + assert.deepEqual(f.refreshLogs.at(-1),{ outcome:"refused",grantId:f.id,reason:"client_mismatch" }); + const wrongResource=await f.refresh(f.first.refresh_token,f.client.clientId,`${ORIGIN}/mcp`); + assert.ok(!wrongResource.ok); assert.equal(wrongResource.error.error,"invalid_target"); + assert.deepEqual(f.refreshLogs.at(-1),{ outcome:"refused",grantId:f.id,reason:"resource_mismatch" }); + assert.equal((await f.anchor()).refresh_token_expires_at.getTime(),before); + assert.equal(await f.count("sessions"),1); assert.equal(await f.count("revocations"),0); + assert.equal(issued(await f.refresh()).refresh_token,f.first.refresh_token); +}); + +test("revoking a stable refresh token ends the root session and every sibling",async t=>{ + const f=await stableRefresh(t); + f.advance(MINUTE); const second=issued(await f.refresh()); + f.advance(MINUTE); const third=issued(await f.refresh()); + await f.store.revokeMcpOAuthToken({ token:f.first.refresh_token,clientId:f.client.clientId }); + for(const token of [f.first.access_token,second.access_token,third.access_token]) assert.equal(await f.resolve(token),null); + assert.equal((await f.refresh()).ok,false); + assert.equal(await f.store.isOAuthGrantActive(f.id,f.owner),false); + assert.equal((await f.database.query("SELECT reason FROM mcp_oauth_revocations")).rows[0]!.reason,"client_revoked"); +}); + +test("revoking a stable-refresh grant ends its sibling access tokens",async t=>{ + const f=await stableRefresh(t); + f.advance(MINUTE); const second=issued(await f.refresh()); + await f.store.revokeMcpOAuthGrant(f.id,"fake-management-revoke"); + assert.equal(await f.resolve(f.first.access_token),null); assert.equal(await f.resolve(second.access_token),null); + assert.equal(await f.store.hasMcpOAuthGrantForWorkspace(f.owner,f.resource),false); + assert.equal((await f.refresh()).ok,false); +}); + +test("an initial code replay after two stable refreshes revokes the grant; siblings do not count as a continuation",async t=>{ + const requests:Record[]=[{},{ resource:`${ORIGIN}/cloud${EVENTS}`,scope:"relay:events" }]; + for(const request of requests) { + const f=await stableRefresh(t,request); + // Stay inside the 120 s code lifetime: an expired code is refused before the replay action. + f.advance(10_000); const second=issued(await f.refresh()); + f.advance(10_000); const third=issued(await f.refresh()); + assert.equal((await f.exchange(f.code)).ok,false); + for(const token of [f.first.access_token,second.access_token,third.access_token]) assert.equal(await f.resolve(token),null); + assert.equal(await f.store.isOAuthGrantActive(f.id,f.owner),false); + assert.equal((await f.database.query("SELECT continued_at FROM mcp_oauth_grants WHERE id=$1",[f.id])).rows[0]!.continued_at,null); + assert.deepEqual((await f.database.query<{ reason:string }>("SELECT reason FROM mcp_oauth_revocations")).rows.map(row=>row.reason), + ["authorization_code_replayed"]); + assert.equal((await f.refresh()).ok,false); + } +}); + +test("a continuation code replay revokes only the continuation session and its siblings",async t=>{ + const request={ resource:`${ORIGIN}/cloud${EVENTS}`,scope:"relay:events" }; + const f=await stableRefresh(t,request); + f.advance(MINUTE); const initialChild=issued(await f.refresh()); + const nextCode=await f.create({ ...request,scope:"relay:events relay:mcp relay:agents" },f.id),next=issued(await f.exchange(nextCode)); + f.advance(10_000); const nextChild=issued(await f.refresh(next.refresh_token)); + f.advance(10_000); const nextChild2=issued(await f.refresh(next.refresh_token)); + assert.equal(nextChild.refresh_token,next.refresh_token); + assert.deepEqual((await f.resolve(nextChild.access_token))!.principal.scopes,(await f.resolve(next.access_token))!.principal.scopes); + assert.deepEqual((await f.resolve(initialChild.access_token))!.principal.scopes,["relay:events"]); + assert.equal((await f.exchange(nextCode)).ok,false); + for(const token of [next.access_token,nextChild.access_token,nextChild2.access_token]) assert.equal(await f.resolve(token),null); + assert.equal((await f.refresh(next.refresh_token)).ok,false); + assert.ok(await f.resolve(f.first.access_token)); assert.ok(await f.resolve(initialChild.access_token)); + const again=issued(await f.refresh()); + assert.equal(again.refresh_token,f.first.refresh_token); assert.ok(await f.resolve(again.access_token)); + assert.equal(await f.store.isOAuthGrantActive(f.id,f.owner),true); + assert.equal(await f.count("revocations"),0); +});