diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d111695..ff41a157 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ assigned at release. ## Unreleased +- 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. - Fixed: MCP repository-filtered session summaries apply the first 200 characters of a repo-only filter in the session directory before pagination, while still accepting a 512-character repo value and verifying the full returned repository URL. This requires a sessions read API whose session directory list applies `projectContains` as a case-insensitive substring of project ID, catalog project key or recorded repository URL (directory migration `20261105034000` or later). Exact verification can still produce a short or empty page with a cursor. Relay agent listings now link an exact roster agent ID to its already-synced Desktop native session when the agent has no validated Relaycast session declaration. The optional session join is failure-open: the roster still returns a null session ID and attribution with `session_unavailable_reason` set to `enrichment_failed` or `ambiguous_sync`; an independently recorded metadata session kind is preserved. No migration. diff --git a/docs/mcp-oauth.md b/docs/mcp-oauth.md index 8443f366..47066c90 100644 --- a/docs/mcp-oauth.md +++ b/docs/mcp-oauth.md @@ -132,9 +132,27 @@ and is refused with `invalid_scope` unless `relay:mcp` is requested with it (see Session reads). Access tokens last one hour; refresh tokens last 30 days. Refresh rotates the -pair and preserves its issued scope limit. Retired refresh tokens are always -refused. Verified reuse within 30 seconds leaves the family live to tolerate -racing refresh requests; verified reuse after that window revokes the grant. +pair and preserves its issued scope limit. A retired refresh token presented +within 30 seconds of its rotation is refused and the connection stays live, to +tolerate racing refresh requests. After that window, if the exact pair it was +rotated into has never been used as a bearer token, the client is assumed to +have lost the refresh response: the server rotates that unused pair again and +returns the new pair on the same connection and approved agent. Recovery is +available for 36 hours after the token's first rotation and never past the +retired token's own expiry. A re-issued pair keeps the refresh expiry it had; +its access expiry never passes it. A retry within 30 seconds of a recovery is +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 +grant ID, a reason and the seconds since retirement; it never logs tokens, +hashes, user IDs or agent names. + +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. 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 diff --git a/migrations/0084_mcp_oauth_undelivered_refresh.sql b/migrations/0084_mcp_oauth_undelivered_refresh.sql new file mode 100644 index 00000000..68526706 --- /dev/null +++ b/migrations/0084_mcp_oauth_undelivered_refresh.sql @@ -0,0 +1,14 @@ +-- MCP OAuth undelivered refresh responses (docs/mcp-oauth.md). +-- current_pair_used_at: first authenticated use of the session's current access +-- token; NULL means the current pair has never been used. Rotation clears it. +ALTER TABLE mcp_oauth_sessions ADD COLUMN IF NOT EXISTS current_pair_used_at timestamptz; + +-- successor_token_hash: the exact refresh-token hash the retiring rotation issued. +-- refresh_token_expires_at: the retired token's own expiry. +ALTER TABLE mcp_oauth_retired_refresh_tokens ADD COLUMN IF NOT EXISTS successor_token_hash text; +ALTER TABLE mcp_oauth_retired_refresh_tokens ADD COLUMN IF NOT EXISTS refresh_token_expires_at timestamptz; +-- reissued_at: the last re-issue from that token; it restarts the race grace window only. +ALTER TABLE mcp_oauth_retired_refresh_tokens ADD COLUMN IF NOT EXISTS reissued_at timestamptz; + +-- Existing rows keep NULL. Retired rows without a successor are never re-issued, +-- so behaviour for pairs rotated before the upgrade is unchanged. diff --git a/scripts/cloud-import-verify/schema-manifest.json b/scripts/cloud-import-verify/schema-manifest.json index 4511dded..4b1628e2 100644 --- a/scripts/cloud-import-verify/schema-manifest.json +++ b/scripts/cloud-import-verify/schema-manifest.json @@ -84,7 +84,8 @@ {"name":"0079_hosted_relay_gate.sql","sha256":"c9b201ff87a00dc9bf06cb304e46673556e47153343a68edf8d557029b988af1"}, {"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":"0083_cloud_bridge.sql","sha256":"5209e515add2701035cee73757ddadc18fe337b47ab443aad82555d5e52de210"}, + {"name":"0084_mcp_oauth_undelivered_refresh.sql","sha256":"858162f963c0b29539c6ef7c3a4a3a7f3e365b8bcedbb48e40e241f8f434fcd4"} ], "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"}}, @@ -714,7 +715,10 @@ {"kind":"column","name":"public.mcp_oauth_grants.workspace_id","definition":{"collation":null,"default":null,"generated":"","identity":"","not_null":true,"position":6,"type":"uuid"}}, {"kind":"column","name":"public.mcp_oauth_retired_refresh_tokens.grant_id","definition":{"collation":null,"default":null,"generated":"","identity":"","not_null":true,"position":2,"type":"uuid"}}, {"kind":"column","name":"public.mcp_oauth_retired_refresh_tokens.organization_id","definition":{"collation":null,"default":null,"generated":"","identity":"","not_null":true,"position":4,"type":"uuid"}}, + {"kind":"column","name":"public.mcp_oauth_retired_refresh_tokens.refresh_token_expires_at","definition":{"collation":null,"default":null,"generated":"","identity":"","not_null":false,"position":8,"type":"timestamp with time zone"}}, + {"kind":"column","name":"public.mcp_oauth_retired_refresh_tokens.reissued_at","definition":{"collation":null,"default":null,"generated":"","identity":"","not_null":false,"position":9,"type":"timestamp with time zone"}}, {"kind":"column","name":"public.mcp_oauth_retired_refresh_tokens.retired_at","definition":{"collation":null,"default":null,"generated":"","identity":"","not_null":true,"position":6,"type":"timestamp with time zone"}}, + {"kind":"column","name":"public.mcp_oauth_retired_refresh_tokens.successor_token_hash","definition":{"collation":"pg_catalog.default","default":null,"generated":"","identity":"","not_null":false,"position":7,"type":"text"}}, {"kind":"column","name":"public.mcp_oauth_retired_refresh_tokens.token_hash","definition":{"collation":"pg_catalog.default","default":null,"generated":"","identity":"","not_null":true,"position":1,"type":"text"}}, {"kind":"column","name":"public.mcp_oauth_retired_refresh_tokens.user_id","definition":{"collation":null,"default":null,"generated":"","identity":"","not_null":true,"position":3,"type":"uuid"}}, {"kind":"column","name":"public.mcp_oauth_retired_refresh_tokens.workspace_id","definition":{"collation":null,"default":null,"generated":"","identity":"","not_null":true,"position":5,"type":"uuid"}}, @@ -737,6 +741,7 @@ {"kind":"column","name":"public.mcp_oauth_sessions.access_token_expires_at","definition":{"collation":null,"default":null,"generated":"","identity":"","not_null":true,"position":10,"type":"timestamp with time zone"}}, {"kind":"column","name":"public.mcp_oauth_sessions.access_token_hash","definition":{"collation":"pg_catalog.default","default":null,"generated":"","identity":"","not_null":true,"position":8,"type":"text"}}, {"kind":"column","name":"public.mcp_oauth_sessions.created_at","definition":{"collation":null,"default":null,"generated":"","identity":"","not_null":true,"position":14,"type":"timestamp with time zone"}}, + {"kind":"column","name":"public.mcp_oauth_sessions.current_pair_used_at","definition":{"collation":null,"default":null,"generated":"","identity":"","not_null":false,"position":17,"type":"timestamp with time zone"}}, {"kind":"column","name":"public.mcp_oauth_sessions.grant_id","definition":{"collation":null,"default":null,"generated":"","identity":"","not_null":true,"position":2,"type":"uuid"}}, {"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"}}, @@ -2186,5 +2191,5 @@ "optional":{ }, - "sha256":"9b8321468fdfb58e2a2b3d3ff820596072eea521a7b4bb43396cbb51ed5772a3" + "sha256":"4909c8c82aa36e0bc46f1fa88db802d0219ee2d1f6ea91b0e3768774ddd79d91" } diff --git a/src/mcp/oauth/sessions.ts b/src/mcp/oauth/sessions.ts index 623f7828..8e9d1e36 100644 --- a/src/mcp/oauth/sessions.ts +++ b/src/mcp/oauth/sessions.ts @@ -93,34 +93,66 @@ export class McpOAuthSessions { return result.rows[0] ? record(result.rows[0]) : null; } - /** Source refresh CAS; the retired hash is committed atomically with rotation. */ + /** + * Source refresh CAS; the retired hash, its successor and its own expiry are committed atomically with rotation. + * `prior` reads the expiry from the statement snapshot; a concurrent rotation changes the hash, so the CAS then misses. + */ async rotate(tx: SqlExecutor, refreshToken: string, expected: McpOAuthSessionOwner): Promise { if (!REFRESH_PATTERN.test(refreshToken)) return null; - const now = this.now(); + const now = this.now(), refreshTokenHash = hashSecret(refreshToken); const accessToken = opaqueToken(MCP_OAUTH_ACCESS_PREFIX), nextRefresh = opaqueToken(MCP_OAUTH_REFRESH_PREFIX); const accessExpires = new Date(now.getTime()+ACCESS_TTL_MS), refreshExpires = new Date(now.getTime()+REFRESH_TTL_MS); - const result = await tx.query<{ id: string; scopes: string[] }>(`UPDATE mcp_oauth_sessions s + const result = await tx.query<{ id: string; scopes: string[]; retired_expires_at: Date | string }>(`UPDATE mcp_oauth_sessions s SET access_token_hash=$2,refresh_token_hash=$3,access_token_expires_at=$4,refresh_token_expires_at=$5, - last_refreshed_at=$6,updated_at=$6 - FROM mcp_oauth_grants g,organization_memberships m,workspaces w - WHERE s.refresh_token_hash=$1 AND s.revoked_at IS NULL AND s.refresh_token_expires_at>$6 + 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 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 AND w.id=s.workspace_id AND w.organization_id=s.organization_id AND ($12::text='multi' OR NOT EXISTS (SELECT 1 FROM organizations other WHERE other.id<>s.organization_id)) - RETURNING s.id,s.scopes`,[hashSecret(refreshToken),hashSecret(accessToken),hashSecret(nextRefresh),accessExpires,refreshExpires,now, + RETURNING s.id,s.scopes,prior.refresh_token_expires_at AS retired_expires_at`,[refreshTokenHash,hashSecret(accessToken), + hashSecret(nextRefresh),accessExpires,refreshExpires,now, expected.grantId,expected.tokenFamilyId,expected.userId,expected.organizationId,expected.workspaceId,this.options.tenancyMode]); const row = result.rows[0]; if (!row) return null; await tx.query(`INSERT INTO mcp_oauth_retired_refresh_tokens - (token_hash,grant_id,user_id,organization_id,workspace_id,retired_at) VALUES ($1,$2,$3,$4,$5,$6) - ON CONFLICT (token_hash) DO NOTHING`,[hashSecret(refreshToken),expected.grantId,expected.userId, - expected.organizationId,expected.workspaceId,now]); + (token_hash,grant_id,user_id,organization_id,workspace_id,retired_at,successor_token_hash,refresh_token_expires_at) + VALUES ($1,$2,$3,$4,$5,$6,$7,$8) ON CONFLICT (token_hash) DO NOTHING`,[refreshTokenHash,expected.grantId,expected.userId, + expected.organizationId,expected.workspaceId,now,hashSecret(nextRefresh),new Date(row.retired_expires_at)]); return { sessionId:row.id,tokenFamilyId:expected.tokenFamilyId,accessToken,refreshToken:nextRefresh, accessTokenExpiresAt:accessExpires.toISOString(),refreshTokenExpiresAt:refreshExpires.toISOString(),scopes:row.scopes }; } + /** + * Re-issue a pair whose refresh response never arrived: keyed by the exact successor hash, only while that + * pair is unused. Keeps the refresh expiry and caps the access expiry by it; the caller writes retired rows. + */ + async reissueUndelivered(tx: SqlExecutor, successorHash: string, expected: McpOAuthSessionOwner, now: Date): Promise { + const accessToken = opaqueToken(MCP_OAUTH_ACCESS_PREFIX), nextRefresh = opaqueToken(MCP_OAUTH_REFRESH_PREFIX); + const result = await tx.query<{ id: string; scopes: string[]; access_token_expires_at: Date | string; refresh_token_expires_at: Date | string }>( + `UPDATE mcp_oauth_sessions s + 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 + 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 + AND w.id=s.workspace_id AND w.organization_id=s.organization_id + AND ($11::text='multi' OR NOT EXISTS (SELECT 1 FROM organizations other WHERE other.id<>s.organization_id)) + RETURNING s.id,s.scopes,s.access_token_expires_at,s.refresh_token_expires_at`,[successorHash,hashSecret(accessToken), + hashSecret(nextRefresh),new Date(now.getTime()+ACCESS_TTL_MS),now, + expected.grantId,expected.tokenFamilyId,expected.userId,expected.organizationId,expected.workspaceId,this.options.tenancyMode]); + const row = result.rows[0]; + if (!row) return null; + return { sessionId:row.id,tokenFamilyId:expected.tokenFamilyId,accessToken,refreshToken:nextRefresh, + accessTokenExpiresAt:new Date(row.access_token_expires_at).toISOString(), + refreshTokenExpiresAt:new Date(row.refresh_token_expires_at).toISOString(),scopes:row.scopes }; + } + async revokeFamily(tx: SqlExecutor, owner: McpOAuthSessionOwner, reason: string): Promise { await revokeMcpOAuthSessionFamily(tx, owner, reason, this.now()); } @@ -140,9 +172,10 @@ export class McpOAuthSessions { const resourcePath = this.options.protocol.parseMcpResource(url.toString()); if (!resourcePath) return null; const resource = this.options.protocol.mcpResourceUrl(resourcePath); + const now = this.now(); const result = await this.database.query(`SELECT s.*,g.scopes AS grant_scopes,g.resource,g.client_id,g.revoked_at AS grant_revoked_at, g.agent_name,g.agent_remote_id,u.email,u.name AS user_name,o.name AS organization_name,w.name AS workspace_name,m.role FROM mcp_oauth_sessions s JOIN mcp_oauth_grants g ON g.id=s.grant_id @@ -152,11 +185,16 @@ export class McpOAuthSessions { WHERE s.access_token_hash=$1 AND s.revoked_at IS NULL AND s.access_token_expires_at>$2 AND g.revoked_at IS NULL AND g.resource=$3 AND ($4::text='multi' OR NOT EXISTS (SELECT 1 FROM organizations other WHERE other.id<>s.organization_id))`, - [hashSecret(token),this.now(),resource,this.options.tenancyMode]); + [hashSecret(token),now,resource,this.options.tenancyMode]); const row = result.rows[0]; if (!row) return null; const scopes=row.scopes.filter(scope=>row.grant_scopes.includes(scope)); if(scopes.length===0) return null; + // First use of this pair, written once. The hash predicate keeps a request racing a rotation off the new pair; + // a pair rotated or re-issued away since the read admits nothing, so an unused pair is never both used and re-issued. + if(row.current_pair_used_at===null && (await this.database.query(`UPDATE mcp_oauth_sessions + SET current_pair_used_at=COALESCE(current_pair_used_at,$3) WHERE id=$1 AND access_token_hash=$2 AND revoked_at IS NULL + RETURNING id`,[row.id,hashSecret(token),now])).rows.length===0) return null; return { principal: { sessionId:row.id,tokenFamilyId:row.token_family_id,userId:row.user_id,email:row.email,name:row.user_name, organizationId:row.organization_id,organizationName:row.organization_name,workspaceId:row.workspace_id, diff --git a/src/mcp/oauth/store.ts b/src/mcp/oauth/store.ts index ee13a713..96c15a3f 100644 --- a/src/mcp/oauth/store.ts +++ b/src/mcp/oauth/store.ts @@ -44,6 +44,16 @@ export type McpOAuthTokenResponse = { access_token: string; token_type: "Bearer" refresh_token: string; scope: string; id_token?: string }; 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"; + grantId?: string; reason?: string; retiredForSeconds?: number }; +type RefreshOutcome = [McpOAuthTokenResult, McpOAuthRefreshLog]; +type RetiredRow = { grant_id: string; retired_at: Date | string; successor_token_hash: string | null; + refresh_token_expires_at: Date | string | null; reissued_at: Date | string | null }; +/** A retired refresh token can recover an undelivered pair for this long after its first retirement. */ +export const MCP_OAUTH_UNDELIVERED_REFRESH_RECOVERY_SECONDS = 60*60*36; +/** A retired token presented this soon after its rotation or its last re-issue is refused without revoking. */ +export const MCP_OAUTH_REFRESH_RACE_MS = 30_000; function invalidGrant(description = "The token or authorization code is invalid, expired, or revoked."): McpOAuthTokenResult { return { ok:false,status:400,error:{ error:"invalid_grant",error_description:description } }; @@ -51,6 +61,15 @@ function invalidGrant(description = "The token or authorization code is invalid, function invalidTarget(): McpOAuthTokenResult { return { ok:false,status:400,error:{ error:"invalid_target",error_description:"resource does not match the grant or authorization request." } }; } +function refreshLog(outcome: McpOAuthRefreshLog["outcome"], grantId?: string, reason?: string, retiredForSeconds?: number): McpOAuthRefreshLog { + return { outcome,...(grantId?{ grantId }:{}),...(reason?{ reason }:{}),...(retiredForSeconds===undefined?{}:{ retiredForSeconds }) }; +} +function refused(reason: string, grantId?: string, retiredForSeconds?: number): RefreshOutcome { + 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 }); +} 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 }; } @@ -77,6 +96,8 @@ export class McpOAuthStore { issueIdToken?(input: { issuer:string; clientId:string; sectorIdentifier:string; userId:string; accessToken:string; nonce:string|null; now:Date }): string; now?: () => Date; + /** Refresh outcome sink; defaults to console info/warn. */ + logRefresh?(entry: McpOAuthRefreshLog): void; }) { this.sessions=new McpOAuthSessions(database,options); } async registerMcpOAuthClient(input: ClientRegistrationInput): Promise { @@ -259,30 +280,69 @@ export class McpOAuthStore { }); } - /** Cloud refresh bindings, rotation and 30-second lost-race/reuse grace. */ + /** + * Cloud refresh bindings, rotation and 30-second lost-race/reuse grace. After the window a retired + * token whose successor pair was never used is a lost response: re-issue on the same grant, not reuse. + */ async refreshMcpOAuthToken(input:{ refreshToken:string; clientId:string; resource:string|undefined }):Promise { if(!input.refreshToken.startsWith(MCP_OAUTH_REFRESH_PREFIX) || input.refreshToken.length>128) return invalidGrant(); - return this.database.transaction(async tx=>{ - const session=await this.sessions.find(tx,"refresh",input.refreshToken); - if(!session) { - const retired=(await tx.query<{ grant_id:string; retired_at:Date|string }>( - "SELECT grant_id,retired_at FROM mcp_oauth_retired_refresh_tokens WHERE token_hash=$1",[hashSecret(input.refreshToken)])).rows[0]; - if(!retired) return invalidGrant(); - const candidate=(await tx.query("SELECT * FROM mcp_oauth_grants WHERE id=$1",[retired.grant_id])).rows[0]; - if(!candidate || !await this.lockWorkspaceAccess(tx,{ userId:candidate.user_id,organizationId:candidate.organization_id,workspaceId:candidate.workspace_id })) return invalidGrant(); - const grant=await this.grant(tx,candidate.id); - if(!grant || grant.revoked_at || grant.client_id!==input.clientId) return invalidGrant(); - if(input.resource!==undefined && this.options.protocol.canonicalMcpResourceParam(input.resource)!==grant.resource) return invalidTarget(); - if(this.now().getTime()-new Date(retired.retired_at).getTime()>=30_000) await this.revokeRows(tx,grant.id,"refresh_token_reused"); - return invalidGrant(); + const [result,entry]=await this.database.transaction(tx=>this.refreshInTransaction(tx,input)); + (this.options.logRefresh??logRefresh)(entry); + return result; + } + + private async refreshInTransaction(tx:SqlExecutor,input:{ refreshToken:string; clientId:string; resource:string|undefined }):Promise { + const session=await this.sessions.find(tx,"refresh",input.refreshToken); + if(!session) { + const tokenHash=hashSecret(input.refreshToken); + const retired=(await tx.query(`SELECT grant_id,retired_at,successor_token_hash,refresh_token_expires_at,reissued_at + FROM mcp_oauth_retired_refresh_tokens WHERE token_hash=$1`,[tokenHash])).rows[0]; + if(!retired) return refused("unknown_token"); + const candidate=(await tx.query("SELECT * FROM mcp_oauth_grants WHERE id=$1",[retired.grant_id])).rows[0]; + if(!candidate || !await this.lockWorkspaceAccess(tx,{ userId:candidate.user_id,organizationId:candidate.organization_id,workspaceId:candidate.workspace_id })) return refused("access_lost",retired.grant_id); + const grant=await this.grant(tx,candidate.id); + if(!grant || grant.revoked_at) return refused("grant_revoked",retired.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); + const now=this.now(),retiredForMs=now.getTime()-new Date(retired.retired_at).getTime(); + const retiredFor=Math.max(0,Math.floor(retiredForMs/1000)); + // The race window restarts at the last re-issue; the recovery window and retiredFor do not. + const graceFrom=Math.max(new Date(retired.retired_at).getTime(),retired.reissued_at===null?0:new Date(retired.reissued_at).getTime()); + if(now.getTime()-graceFromnow.getTime() + && retiredForMs<=MCP_OAUTH_UNDELIVERED_REFRESH_RECOVERY_SECONDS*1000; + if(recoverable) { + const locked=(await tx.query<{ successor_token_hash:string|null; reissued_at:Date|string|null }>(`SELECT successor_token_hash,reissued_at + FROM mcp_oauth_retired_refresh_tokens WHERE token_hash=$1 FOR UPDATE`,[tokenHash])).rows[0]; + const successor=locked?.successor_token_hash??null; + if(successor!==null && successor!==retired.successor_token_hash) return refused("reissue_lost_race",grant.id,retiredFor); + if(successor!==null && locked?.reissued_at!=null + && now.getTime()-new Date(locked.reissued_at).getTime() { await this.database.transaction(async tx=>{ const session=await this.sessions.find(tx,"access",input.token)??await this.sessions.find(tx,"refresh",input.token); - if(!session || (input.clientId!==undefined && input.clientId!==session.clientId)) return; - await lockUser(tx,session.userId); await lockOrganization(tx,session.organizationId); - await this.revokeRows(tx,session.grantId,"client_revoked"); + if(session) { + if(input.clientId!==undefined && input.clientId!==session.clientId) return; + await lockUser(tx,session.userId); await lockOrganization(tx,session.organizationId); + await this.revokeRows(tx,session.grantId,"client_revoked"); + return; + } + // A retired refresh token can still recover an undelivered pair, so revoking it ends its grant. + if(!input.token.startsWith(MCP_OAUTH_REFRESH_PREFIX) || input.token.length>128) return; + const grant=(await tx.query(`SELECT g.* FROM mcp_oauth_retired_refresh_tokens r JOIN mcp_oauth_grants g ON g.id=r.grant_id + WHERE r.token_hash=$1`,[hashSecret(input.token)])).rows[0]; + if(!grant || (input.clientId!==undefined && input.clientId!==grant.client_id)) return; + await lockUser(tx,grant.user_id); await lockOrganization(tx,grant.organization_id); + await this.revokeRows(tx,grant.id,"client_revoked"); }); } diff --git a/test/mcp-oauth-sessions.test.ts b/test/mcp-oauth-sessions.test.ts index dede5b3e..223cd824 100644 --- a/test/mcp-oauth-sessions.test.ts +++ b/test/mcp-oauth-sessions.test.ts @@ -113,6 +113,44 @@ test("refresh CAS has one winner, persists retired hash atomically, and preserve assert.equal(receipt.organization_id,f.owner.organizationId); }); +test("first bearer use of a pair is recorded once and every rotation clears it", async t=>{ + const f=await fixture(t), pair=await f.issue(); + const used=async()=>(await f.database.query<{ current_pair_used_at:Date|null }>("SELECT current_pair_used_at FROM mcp_oauth_sessions")).rows[0]!.current_pair_used_at; + assert.equal(await used(),null); + assert.ok(await f.sessions.resolveAccessToken(pair.accessToken,RESOURCE)); + const first=await used(); assert.ok(first); + f.advance(5_000); + assert.ok(await f.sessions.resolveAccessToken(pair.accessToken,RESOURCE)); + assert.equal((await used())!.getTime(),first.getTime()); + const next=await f.database.transaction(tx=>f.sessions.rotate(tx,pair.refreshToken,f.owner)); + assert.ok(next); + assert.equal(await used(),null); + const retired=(await f.database.query<{ successor_token_hash:string; refresh_token_expires_at:Date }>( + "SELECT successor_token_hash,refresh_token_expires_at FROM mcp_oauth_retired_refresh_tokens")).rows[0]!; + assert.equal(retired.successor_token_hash,hashSecret(next.refreshToken)); + assert.equal(retired.refresh_token_expires_at.toISOString(),pair.refreshTokenExpiresAt); + assert.equal(await f.sessions.resolveAccessToken(pair.accessToken,RESOURCE),null); + assert.equal(await used(),null); +}); + +test("a bearer request that loses to a rotation is refused and does not mark the successor pair used", async t=>{ + const f=await fixture(t), pair=await f.issue(); + let rotated=false; + const racing: Database={ + query: async >(sql:string,params?:unknown[])=>{ + const result=await f.database.query(sql,params); + if(!rotated && sql.includes("WHERE s.access_token_hash=$1")) { + rotated=true; assert.ok(await f.database.transaction(tx=>f.sessions.rotate(tx,pair.refreshToken,f.owner))); + } + return result; + }, + exec: sql=>f.database.exec(sql), transaction: run=>f.database.transaction(run), close: async()=>{}, + }; + assert.equal(await new McpOAuthSessions(racing,f.sessions.options).resolveAccessToken(pair.accessToken,RESOURCE),null); + assert.ok(rotated); + assert.equal((await f.database.query("SELECT current_pair_used_at FROM mcp_oauth_sessions")).rows[0]!.current_pair_used_at,null); +}); + test("rotation rollback keeps the old pair and no retired receipt", async t=>{ const f=await fixture(t), pair=await f.issue(); await assert.rejects(f.database.transaction(async tx=>{ diff --git a/test/mcp-oauth-token-flow.test.ts b/test/mcp-oauth-token-flow.test.ts index 1b72cab6..84044482 100644 --- a/test/mcp-oauth-token-flow.test.ts +++ b/test/mcp-oauth-token-flow.test.ts @@ -6,7 +6,8 @@ import { migrate } from "../src/migrations.js"; import { hashSecret } from "../src/crypto.js"; import { lockUser,lockOrganization } from "../src/tenancy.js"; import { createMcpOAuthProtocol,pkceS256 } from "../src/mcp/oauth/protocol.js"; -import { McpOAuthStore,type McpOAuthTokenResult } from "../src/mcp/oauth/store.js"; +import { McpOAuthStore,MCP_OAUTH_UNDELIVERED_REFRESH_RECOVERY_SECONDS,type McpOAuthRefreshLog,type McpOAuthTokenResult } from "../src/mcp/oauth/store.js"; +import type { Database } from "../src/database.js"; import { PGliteDatabase } from "./support/harness.js"; const ORIGIN="https://relay.example.test",SHARED="/api/v1/mcp/shared-sessions",EVENTS="/api/v1/mcp/relay-events"; @@ -27,12 +28,13 @@ async function fixture(t:test.TestContext) { await database.query(`INSERT INTO workspaces(id,organization_id,name,relaycast_workspace_id,relaycast_api_key_ciphertext) VALUES ($1,$2,'Fake Workspace','fake-relay','fake-envelope')`,[owner.workspaceId,owner.organizationId]); let now=new Date(),signerFails=false; - const signed:Array>=[]; + const signed:Array>=[],refreshLogs:McpOAuthRefreshLog[]=[]; const protocol=createMcpOAuthProtocol({ publicOrigin:ORIGIN,enabledResources:[SHARED,EVENTS,"/mcp"], mountedEndpoints:["authorization","token","jwks"],oidcEnabled:true }); const store=new McpOAuthStore(database,{ protocol,tenancyMode:"multi",now:()=>new Date(now), isGrokRoutine:request=>request.resourcePath===EVENTS && new URL(request.redirectUri).hostname==="x.ai", 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"] }); function authorization(overrides:Record={}) { @@ -48,7 +50,7 @@ async function fixture(t:test.TestContext) { return (await database.query<{ grant_id:string }>("SELECT grant_id FROM mcp_oauth_authorization_codes WHERE code_hash=$1",[hashSecret(code)])).rows[0]!.grant_id; } const count=(table:"grants"|"sessions"|"revocations")=>database.query<{ n:number }>(`SELECT count(*)::int AS n FROM mcp_oauth_${table}`).then(r=>r.rows[0]!.n); - return { database,owner,store,client,create,exchange,grantId,count,signed,authorization, + return { database,owner,store,client,create,exchange,grantId,count,signed,authorization,refreshLogs, advance:(ms:number)=>{ now=new Date(now.getTime()+ms); },signerFailure:(value:boolean)=>{ signerFails=value; } }; } @@ -144,6 +146,280 @@ test("refresh client/resource bindings precede rotation; old-token grace refuses assert.equal(await f.store.sessions.resolveAccessToken(next.access_token,`${ORIGIN}/cloud${SHARED}`),null); assert.ok(await f.store.sessions.resolveAccessToken(unrelated.access_token,`${ORIGIN}/cloud${SHARED}`)); assert.equal((await f.database.query("SELECT reason FROM mcp_oauth_revocations")).rows[0]!.reason,"refresh_token_reused"); + assert.deepEqual(f.refreshLogs.at(-1),{ outcome:"revoked",grantId:await f.grantId(code),reason:"refresh_token_reused",retiredForSeconds:31 }); +}); + +/** One delivered pair, then a rotation whose response the client never received. */ +async function lostRefresh(t:test.TestContext) { + const f=await fixture(t),code=await f.create(),first=issued(await f.exchange(code)),id=await f.grantId(code); + await f.database.query("UPDATE mcp_oauth_grants SET agent_remote_id='fake-immutable-id' WHERE id=$1",[id]); + const resource=`${ORIGIN}/cloud${SHARED}`; + assert.ok(await f.store.sessions.resolveAccessToken(first.access_token,resource)); + const refresh=(token:string,clientId=f.client.clientId)=>f.store.refreshMcpOAuthToken({ refreshToken:token,clientId,resource:undefined }); + const resolve=(token:string)=>f.store.sessions.resolveAccessToken(token,resource); + const lost=issued(await refresh(first.refresh_token)); + const sessionId=(await f.database.query<{ id:string }>("SELECT id FROM mcp_oauth_sessions")).rows[0]!.id; + const reused=async()=>(await f.database.query<{ reason:string }>("SELECT reason FROM mcp_oauth_revocations")).rows.map(row=>row.reason); + const stored=async()=>(await f.database.query<{ refresh_token_hash:string; access_token_expires_at:Date; refresh_token_expires_at:Date }>( + "SELECT refresh_token_hash,access_token_expires_at,refresh_token_expires_at FROM mcp_oauth_sessions WHERE id=$1",[sessionId])).rows[0]!; + return { ...f,first,lost,id,sessionId,refresh,resolve,reused,stored }; +} + +test("re-issues a rotation whose response never reached the client instead of revoking the grant",async t=>{ + const f=await lostRefresh(t); + f.advance(31_000); + const again=issued(await f.refresh(f.first.refresh_token)); + assert.deepEqual(await f.reused(),[]); assert.equal(await f.count("sessions"),1); assert.equal(await f.count("grants"),1); + const grant=(await f.database.query("SELECT * FROM mcp_oauth_grants WHERE id=$1",[f.id])).rows[0]!; + assert.equal(grant.revoked_at,null); assert.equal(grant.agent_name,"fake-agent"); assert.equal(grant.agent_remote_id,"fake-immutable-id"); + assert.equal(await f.resolve(f.lost.access_token),null); + const access=await f.resolve(again.access_token); + assert.equal(access!.grantId,f.id); assert.equal(access!.principal.sessionId,f.sessionId); + assert.equal(again.expires_in,3600); assert.equal(again.scope,"relay:mcp"); + const retired=(await f.database.query("SELECT token_hash,successor_token_hash FROM mcp_oauth_retired_refresh_tokens ORDER BY retired_at")).rows; + assert.deepEqual(retired,[{ token_hash:hashSecret(f.first.refresh_token),successor_token_hash:hashSecret(again.refresh_token) }, + { token_hash:hashSecret(f.lost.refresh_token),successor_token_hash:hashSecret(again.refresh_token) }]); + assert.deepEqual(f.refreshLogs.at(-1),{ outcome:"reissued_undelivered",grantId:f.id,retiredForSeconds:31 }); + const logged=JSON.stringify(f.refreshLogs); + for(const secret of [f.first.refresh_token,f.lost.refresh_token,again.refresh_token,hashSecret(f.first.refresh_token),f.owner.userId,"fake-agent"]) { + assert.ok(!logged.includes(secret)); + } +}); + +test("recovers again when the re-issued response is lost too",async t=>{ + const f=await lostRefresh(t); + f.advance(31_000); const second=issued(await f.refresh(f.first.refresh_token)); + f.advance(31_000); + const third=issued(await f.refresh(f.first.refresh_token)); + assert.equal(await f.resolve(second.access_token),null); + assert.ok(await f.resolve(third.access_token)); + assert.deepEqual(await f.reused(),[]); + // A re-issue restarts only the race window; the recovery window runs from the first retirement. + assert.deepEqual(f.refreshLogs.slice(-2),[{ outcome:"reissued_undelivered",grantId:f.id,retiredForSeconds:31 }, + { outcome:"reissued_undelivered",grantId:f.id,retiredForSeconds:62 }]); +}); + +test("refuses a retry that races a recovery without replacing or revoking the recovered pair",async t=>{ + const f=await lostRefresh(t); + f.advance(31_000); + const recovered=issued(await f.refresh(f.first.refresh_token)); + const presented=(await f.database.query<{ token_hash:string; reissued_at:Date|null }>( + "SELECT token_hash,reissued_at FROM mcp_oauth_retired_refresh_tokens ORDER BY retired_at")).rows; + assert.equal(presented[0]!.token_hash,hashSecret(f.first.refresh_token)); assert.ok(presented[0]!.reissued_at); + assert.equal(presented[1]!.token_hash,hashSecret(f.lost.refresh_token)); assert.equal(presented[1]!.reissued_at,null); + f.advance(5_000); + const duplicate=await f.refresh(f.first.refresh_token); + assert.ok(!duplicate.ok); assert.equal(duplicate.error.error,"invalid_grant"); + assert.deepEqual(await f.reused(),[]); + assert.equal((await f.stored()).refresh_token_hash,hashSecret(recovered.refresh_token)); + assert.deepEqual(f.refreshLogs.at(-1),{ outcome:"refused",grantId:f.id,reason:"refresh_race",retiredForSeconds:36 }); + assert.ok(await f.resolve(recovered.access_token)); + const next=issued(await f.refresh(recovered.refresh_token)); + assert.ok(await f.resolve(next.access_token)); assert.deepEqual(await f.reused(),[]); +}); + +test("a duplicate retry is refused when the recovered pair was used before it arrived",async t=>{ + const f=await lostRefresh(t); + f.advance(31_000); + const recovered=issued(await f.refresh(f.first.refresh_token)); + f.advance(2_000); + assert.ok(await f.resolve(recovered.access_token)); + f.advance(2_000); + const duplicate=await f.refresh(f.first.refresh_token); + assert.ok(!duplicate.ok); assert.equal(duplicate.error.error,"invalid_grant"); + assert.deepEqual(await f.reused(),[]); + assert.deepEqual(f.refreshLogs.at(-1),{ outcome:"refused",grantId:f.id,reason:"refresh_race",retiredForSeconds:35 }); + assert.ok(await f.resolve(recovered.access_token)); + assert.ok(await f.resolve(issued(await f.refresh(recovered.refresh_token)).access_token)); +}); + +test("still revokes when the successor pair has been used",async t=>{ + const f=await lostRefresh(t); + assert.ok(await f.resolve(f.lost.access_token)); + f.advance(31_000); + assert.equal((await f.refresh(f.first.refresh_token)).ok,false); + assert.deepEqual(await f.reused(),["refresh_token_reused"]); + assert.equal(await f.resolve(f.lost.access_token),null); + assert.deepEqual(f.refreshLogs.at(-1),{ outcome:"revoked",grantId:f.id,reason:"refresh_token_reused",retiredForSeconds:31 }); +}); + +test("refuses recovery when the successor authenticates first, even late in the window",async t=>{ + const f=await lostRefresh(t); + f.advance(20_000); + assert.ok(await f.resolve(f.lost.access_token)); + f.advance(11_000); + assert.equal((await f.refresh(f.first.refresh_token)).ok,false); + assert.deepEqual(await f.reused(),["refresh_token_reused"]); +}); + +test("still revokes a token retired before the latest rotation",async t=>{ + const f=await lostRefresh(t); + f.advance(1_000); + const second=issued(await f.refresh(f.lost.refresh_token)); + f.advance(31_000); + assert.equal((await f.refresh(f.first.refresh_token)).ok,false); + assert.deepEqual(await f.reused(),["refresh_token_reused"]); + assert.equal(await f.resolve(second.access_token),null); +}); + +test("revokes when the other holder presents its successor after the re-issued pair was used",async t=>{ + const f=await lostRefresh(t); + f.advance(31_000); + const reissued=issued(await f.refresh(f.first.refresh_token)); + assert.ok(await f.resolve(reissued.access_token)); + f.advance(31_000); + assert.equal((await f.refresh(f.lost.refresh_token)).ok,false); + assert.deepEqual(await f.reused(),["refresh_token_reused"]); + assert.equal(await f.resolve(reissued.access_token),null); +}); + +test("does not re-issue to another client id",async t=>{ + const f=await lostRefresh(t); + f.advance(31_000); + 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(await f.reused(),[]); + assert.equal((await f.database.query("SELECT refresh_token_hash FROM mcp_oauth_sessions")).rows[0]!.refresh_token_hash,hashSecret(f.lost.refresh_token)); + assert.deepEqual(f.refreshLogs.at(-1),{ outcome:"refused",grantId:f.id,reason:"client_mismatch" }); + assert.ok(await f.resolve(f.lost.access_token)); +}); + +test("a retry inside the 30-second window is refused without revoking or re-issuing",async t=>{ + const f=await lostRefresh(t); + f.advance(29_000); + assert.equal((await f.refresh(f.first.refresh_token)).ok,false); + assert.deepEqual(await f.reused(),[]); + assert.equal((await f.database.query("SELECT refresh_token_hash FROM mcp_oauth_sessions")).rows[0]!.refresh_token_hash,hashSecret(f.lost.refresh_token)); + assert.deepEqual(f.refreshLogs.at(-1),{ outcome:"refused",grantId:f.id,reason:"refresh_race",retiredForSeconds:29 }); + assert.ok(await f.resolve(f.lost.access_token)); +}); + +test("a retired row without a successor (rotated before the upgrade) is not recovered",async t=>{ + const f=await lostRefresh(t); + await f.database.query("UPDATE mcp_oauth_retired_refresh_tokens SET successor_token_hash=NULL,refresh_token_expires_at=NULL"); + f.advance(31_000); + assert.equal((await f.refresh(f.first.refresh_token)).ok,false); + assert.deepEqual(await f.reused(),["refresh_token_reused"]); +}); + +test("the old access token, used just before the rotation, does not block recovery",async t=>{ + const f=await lostRefresh(t); + assert.equal(await f.resolve(f.first.access_token),null); + assert.equal((await f.database.query("SELECT current_pair_used_at FROM mcp_oauth_sessions")).rows[0]!.current_pair_used_at,null); + f.advance(31_000); + assert.ok(await f.resolve(issued(await f.refresh(f.first.refresh_token)).access_token)); + assert.deepEqual(await f.reused(),[]); +}); + +test("of two concurrent recoveries of one token only the first wins, without revoking",async t=>{ + // PGlite runs one transaction at a time, so the competing winner is simulated: after this request's unlocked + // read, the successor moves as a concurrent recovery would leave it. + const f=await lostRefresh(t); + const moved=`fake-moved-successor-${randomUUID()}`; + let first=true; + const racing:Database={ query:>(sql:string,params?:unknown[])=>f.database.query(sql,params), + exec:sql=>f.database.exec(sql),close:async()=>{}, + transaction:run=>f.database.transaction(tx=>run({ exec:sql=>tx.exec(sql),query:async >(sql:string,params?:unknown[])=>{ + const result=await tx.query(sql,params); + if(first && sql.includes("FROM mcp_oauth_retired_refresh_tokens WHERE token_hash=$1") && !sql.includes("FOR UPDATE")) { + first=false; await tx.query("UPDATE mcp_oauth_retired_refresh_tokens SET successor_token_hash=$1 WHERE token_hash=$2",[moved,hashSecret(f.first.refresh_token)]); + } + return result; + } })) }; + const store=new McpOAuthStore(racing,f.store.options); + f.advance(31_000); + const lostRace=await store.refreshMcpOAuthToken({ refreshToken:f.first.refresh_token,clientId:f.client.clientId,resource:undefined }); + assert.ok(!lostRace.ok); assert.equal(lostRace.error.error,"invalid_grant"); + assert.deepEqual(await f.reused(),[]); + assert.equal((await f.stored()).refresh_token_hash,hashSecret(f.lost.refresh_token)); + assert.deepEqual(f.refreshLogs.at(-1),{ outcome:"refused",grantId:f.id,reason:"reissue_lost_race",retiredForSeconds:31 }); +}); + +test("a re-issue recorded between the unlocked read and the lock is refused without revoking",async t=>{ + // Simulated: only reissued_at moves after the unlocked read. A real competing re-issue also moves the successor; + // this pins the locked reissued_at check on its own. + const f=await lostRefresh(t); + let first=true; + const racing:Database={ query:>(sql:string,params?:unknown[])=>f.database.query(sql,params), + exec:sql=>f.database.exec(sql),close:async()=>{}, + transaction:run=>f.database.transaction(tx=>run({ exec:sql=>tx.exec(sql),query:async >(sql:string,params?:unknown[])=>{ + const result=await tx.query(sql,params); + if(first && sql.includes("FROM mcp_oauth_retired_refresh_tokens WHERE token_hash=$1") && !sql.includes("FOR UPDATE")) { + first=false; await tx.query("UPDATE mcp_oauth_retired_refresh_tokens SET reissued_at=$1 WHERE token_hash=$2",[f.store.options.now!(),hashSecret(f.first.refresh_token)]); + } + return result; + } })) }; + const store=new McpOAuthStore(racing,f.store.options); + f.advance(31_000); + const lostRace=await store.refreshMcpOAuthToken({ refreshToken:f.first.refresh_token,clientId:f.client.clientId,resource:undefined }); + assert.ok(!lostRace.ok); assert.equal(lostRace.error.error,"invalid_grant"); + assert.deepEqual(await f.reused(),[]); + assert.equal((await f.stored()).refresh_token_hash,hashSecret(f.lost.refresh_token)); + assert.deepEqual(f.refreshLogs.at(-1),{ outcome:"refused",grantId:f.id,reason:"reissue_lost_race",retiredForSeconds:31 }); +}); + +test("on a grant with more than one session only the exact successor session is re-issued",async t=>{ + const f=await fixture(t),request={ resource:`${ORIGIN}/cloud${EVENTS}`,scope:"relay:events" }; + const oldCode=await f.create(request),old=issued(await f.exchange(oldCode)),id=await f.grantId(oldCode); + const next=issued(await f.exchange(await f.create({ ...request,scope:"relay:events relay:mcp relay:agents" },id))); + const refresh=(token:string)=>f.store.refreshMcpOAuthToken({ refreshToken:token,clientId:f.client.clientId,resource:undefined }); + const lost=issued(await refresh(next.refresh_token)); + f.advance(31_000); + const again=issued(await refresh(next.refresh_token)); + assert.equal(await f.count("sessions"),2); assert.equal(await f.count("revocations"),0); + const sessions=(await f.database.query<{ refresh_token_hash:string }>("SELECT refresh_token_hash FROM mcp_oauth_sessions ORDER BY created_at,id")).rows.map(row=>row.refresh_token_hash); + assert.ok(sessions.includes(hashSecret(old.refresh_token))); assert.ok(sessions.includes(hashSecret(again.refresh_token))); + assert.ok(!sessions.includes(hashSecret(lost.refresh_token))); + assert.ok(await f.store.sessions.resolveAccessToken(old.access_token,request.resource)); + assert.ok(await f.store.sessions.resolveAccessToken(again.access_token,request.resource)); +}); + +test("re-issue keeps the session's refresh expiry and caps the access expiry by it",async t=>{ + const f=await lostRefresh(t); + const until=new Date((await f.stored()).access_token_expires_at.getTime()-20*60*1000); + await f.database.query("UPDATE mcp_oauth_sessions SET refresh_token_expires_at=$1",[until]); + f.advance(31_000); + const again=issued(await f.refresh(f.first.refresh_token)),row=await f.stored(); + assert.equal(row.refresh_token_expires_at.getTime(),until.getTime()); + assert.equal(row.access_token_expires_at.getTime(),until.getTime()); + assert.ok(again.expires_in<3600-20*60+1); + assert.equal((await f.database.query<{ refresh_token_expires_at:Date }>("SELECT refresh_token_expires_at FROM mcp_oauth_retired_refresh_tokens WHERE token_hash=$1", + [hashSecret(f.lost.refresh_token)])).rows[0]!.refresh_token_expires_at.getTime(),until.getTime()); +}); + +test("refuses recovery once the presented token's own expiry has passed",async t=>{ + const f=await lostRefresh(t); + await f.database.query(`UPDATE mcp_oauth_retired_refresh_tokens + SET refresh_token_expires_at=retired_at+interval '30 seconds' WHERE token_hash=$1`,[hashSecret(f.first.refresh_token)]); + f.advance(31_000); + assert.equal((await f.refresh(f.first.refresh_token)).ok,false); + assert.deepEqual(await f.reused(),["refresh_token_reused"]); +}); + +test("refuses recovery after the 36-hour window",async t=>{ + const f=await lostRefresh(t); + f.advance(MCP_OAUTH_UNDELIVERED_REFRESH_RECOVERY_SECONDS*1000+1_000); + assert.equal((await f.refresh(f.first.refresh_token)).ok,false); + assert.deepEqual(await f.reused(),["refresh_token_reused"]); +}); + +test("revoking a retired refresh token ends its grant; another client id is ignored",async t=>{ + const f=await lostRefresh(t); + await f.store.revokeMcpOAuthToken({ token:f.first.refresh_token,clientId:"mcpc_fake_other" }); + assert.deepEqual(await f.reused(),[]); + assert.ok(await f.resolve(f.lost.access_token)); + await f.store.revokeMcpOAuthToken({ token:f.first.refresh_token,clientId:f.client.clientId }); + assert.deepEqual(await f.reused(),["client_revoked"]); + assert.equal(await f.resolve(f.lost.access_token),null); + assert.ok((await f.database.query("SELECT revoked_at FROM mcp_oauth_grants WHERE id=$1",[f.id])).rows[0]!.revoked_at); +}); + +test("unknown refresh tokens are refused and logged without a grant id",async t=>{ + const f=await fixture(t); + assert.equal((await f.store.refreshMcpOAuthToken({ refreshToken:`mcp_rt_${"a".repeat(43)}`,clientId:f.client.clientId,resource:undefined })).ok,false); + assert.deepEqual(f.refreshLogs,[{ outcome:"refused",reason:"unknown_token" }]); + assert.equal((await f.store.refreshMcpOAuthToken({ refreshToken:"fake-malformed",clientId:f.client.clientId,resource:undefined })).ok,false); + assert.equal(f.refreshLogs.length,1); }); test("OIDC failure rolls back code/grant/session; nonce and signer inputs are source-bound on retry",async t=>{