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

Filter by extension

Filter by extension

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

## Unreleased

- Fixed: 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.
Expand Down
24 changes: 21 additions & 3 deletions docs/mcp-oauth.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 14 additions & 0 deletions migrations/0084_mcp_oauth_undelivered_refresh.sql
Original file line number Diff line number Diff line change
@@ -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.
9 changes: 7 additions & 2 deletions scripts/cloud-import-verify/schema-manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"}},
Expand Down Expand Up @@ -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"}},
Expand All @@ -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"}},
Expand Down Expand Up @@ -2186,5 +2191,5 @@
"optional":{

},
"sha256":"9b8321468fdfb58e2a2b3d3ff820596072eea521a7b4bb43396cbb51ed5772a3"
"sha256":"4909c8c82aa36e0bc46f1fa88db802d0219ee2d1f6ea91b0e3768774ddd79d91"
}
62 changes: 50 additions & 12 deletions src/mcp/oauth/sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<McpOAuthIssuedPair | null> {
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<McpOAuthIssuedPair | null> {
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<void> {
await revokeMcpOAuthSessionFamily(tx, owner, reason, this.now());
}
Expand All @@ -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<SessionRow & {
email: string; user_name: string; organization_name: string; workspace_name: string; role: Principal["role"];
agent_name: string; agent_remote_id: string | null;
agent_name: string; agent_remote_id: string | null; current_pair_used_at: Date | string | null;
}>(`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
Expand All @@ -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,
Expand Down
Loading
Loading