Skip to content
Merged
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
5 changes: 5 additions & 0 deletions .changeset/20260818112000-clear-mcp-dcr-on-url-change.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@truefoundry/trueforge': patch
---

Clear DCR OAuth tokens and pending authorizations when an MCP server URL changes, since the URL is the token audience.
16 changes: 10 additions & 6 deletions packages/trueforge/src/apis/mcpServers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,14 +247,14 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRou
});

let dcrClientToSave: OAuthClientRecord | undefined;
const urlChanged =
existing !== undefined && existing.manifest.url !== manifest.url && manifest.auth?.type === 'dcr';
if (manifest.auth?.type === 'dcr') {
const existingClient = existing
? await deps.mcpServerStore.getClient({ id: existing.id }, transaction)
: undefined;
// Register when: brand-new server, client was cleared (e.g. invalid_client), or MCP URL changed
// (resource/AS may differ; reuse would keep stale oauth_server/client for the old AS).
// TODO: make manifest URL immutable after create so re-DCR / stale OAuth tokens are not possible via PUT.
const urlChanged = existing && existing.manifest.url !== manifest.url;
const needsDcr = existingClient === undefined || urlChanged;
if (needsDcr) {
dcrClientToSave = await createMcpOAuthClient({
Expand All @@ -275,15 +275,19 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRou
transaction,
);
if (dcrClientToSave !== undefined) {
// New DCR registration (create, missing client, or URL change): replace the shared client only.
// Existing per-user tokens are left in place; resolve/refresh fails them if they no longer
// match the new resource/AS, and users re-authorize from there.
// New DCR registration (create, missing client, or URL change): replace the shared client.
await deps.mcpServerStore.saveClient({ id: saved.id, record: dcrClientToSave }, transaction);
}
if (urlChanged) {
// URL is the OAuth resource/audience — drop every user's tokens and in-flight authorizes.
await deps.tokenStore.deleteTokensForServer({ id: saved.id }, transaction);
await deps.tokenStore.deletePendingAuthorizationsForServer({ id: saved.id }, transaction);
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
return saved;
});

// A re-upsert preserves `id`, so a DCR server may already carry a token from a prior authorize.
// A re-upsert preserves `id`, so a DCR server may already carry a token from a prior authorize
// (unless this PUT changed the URL and cleared all tokens above).
const token =
record.manifest.auth?.type === 'dcr' ? await deps.tokenStore.getToken({ id: record.id, userRef }) : undefined;
return c.json({ data: toConfiguredMcpServer({ record, token }) }, 200);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@ import type { Kysely, Transaction } from 'kysely';
import type { IOAuthTokenStore, OAuthPendingAuthorization, OAuthToken, OAuthTokenKey } from '../../../mcp/auth/types';
import { fromStoredOAuthToken, toStoredOAuthToken } from '../../mcpServerStore';
import type { Database } from '../types';
import { consumePendingAuthorization, savePendingAuthorization } from './queries/pendingAuthorization';
import { deleteToken, getToken, getTokens, saveToken } from './queries/token';
import {
consumePendingAuthorization,
deletePendingAuthorizationsForServer,
savePendingAuthorization,
} from './queries/pendingAuthorization';
import { deleteToken, deleteTokensForServer, getToken, getTokens, saveToken } from './queries/token';

export class PostgresOAuthTokenStore implements IOAuthTokenStore<Transaction<Database>> {
constructor(private readonly db: Kysely<Database>) {}
Expand Down Expand Up @@ -43,4 +47,12 @@ export class PostgresOAuthTokenStore implements IOAuthTokenStore<Transaction<Dat
deleteToken(params: OAuthTokenKey, transaction?: Transaction<Database>): Promise<void> {
return deleteToken(transaction ?? this.db, params);
}

deleteTokensForServer(params: { id: string }, transaction?: Transaction<Database>): Promise<void> {
return deleteTokensForServer(transaction ?? this.db, params);
}

deletePendingAuthorizationsForServer(params: { id: string }, transaction?: Transaction<Database>): Promise<void> {
return deletePendingAuthorizationsForServer(transaction ?? this.db, params);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,10 @@ export async function consumePendingAuthorization(
...fromStoredOAuthPendingAuthorizationData(row.auth_data),
};
}

export async function deletePendingAuthorizationsForServer(
db: Kysely<Database>,
params: { id: string },
): Promise<void> {
await db.deleteFrom('oauth_pending_authorization').where('oauth_server_id', '=', params.id).execute();
}
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,7 @@ export async function deleteToken(db: Kysely<Database>, params: { id: string; us
.where('user_id', '=', params.userRef)
.execute();
}

export async function deleteTokensForServer(db: Kysely<Database>, params: { id: string }): Promise<void> {
await db.deleteFrom('oauth_token').where('oauth_server_id', '=', params.id).execute();
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@ import type { Kysely, Transaction } from 'kysely';
import type { IOAuthTokenStore, OAuthPendingAuthorization, OAuthToken, OAuthTokenKey } from '../../../mcp/auth/types';
import { fromStoredOAuthToken, toStoredOAuthToken } from '../../mcpServerStore';
import type { Database } from '../types';
import { consumePendingAuthorization, savePendingAuthorization } from './queries/pendingAuthorization';
import { deleteToken, getToken, getTokens, saveToken } from './queries/token';
import {
consumePendingAuthorization,
deletePendingAuthorizationsForServer,
savePendingAuthorization,
} from './queries/pendingAuthorization';
import { deleteToken, deleteTokensForServer, getToken, getTokens, saveToken } from './queries/token';

export class SqliteOAuthTokenStore implements IOAuthTokenStore<Transaction<Database>> {
constructor(private readonly db: Kysely<Database>) {}
Expand Down Expand Up @@ -43,4 +47,12 @@ export class SqliteOAuthTokenStore implements IOAuthTokenStore<Transaction<Datab
deleteToken(params: OAuthTokenKey, transaction?: Transaction<Database>): Promise<void> {
return deleteToken(transaction ?? this.db, params);
}

deleteTokensForServer(params: { id: string }, transaction?: Transaction<Database>): Promise<void> {
return deleteTokensForServer(transaction ?? this.db, params);
}

deletePendingAuthorizationsForServer(params: { id: string }, transaction?: Transaction<Database>): Promise<void> {
return deletePendingAuthorizationsForServer(transaction ?? this.db, params);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,10 @@ export async function consumePendingAuthorization(
...fromStoredOAuthPendingAuthorizationData(row.auth_data),
};
}

export async function deletePendingAuthorizationsForServer(
db: Kysely<Database>,
params: { id: string },
): Promise<void> {
await db.deleteFrom('oauth_pending_authorization').where('oauth_server_id', '=', params.id).execute();
}
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,7 @@ export async function deleteToken(db: Kysely<Database>, params: { id: string; us
.where('user_id', '=', params.userRef)
.execute();
}

export async function deleteTokensForServer(db: Kysely<Database>, params: { id: string }): Promise<void> {
await db.deleteFrom('oauth_token').where('oauth_server_id', '=', params.id).execute();
}
17 changes: 17 additions & 0 deletions packages/trueforge/src/mcp/auth/inMemoryStores.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,23 @@ export class InMemoryOAuthTokenStore implements IOAuthTokenStore {
async deleteToken(params: OAuthTokenKey): Promise<void> {
this.tokens.delete(tokenMapKey(params));
}

async deleteTokensForServer(params: { id: string }): Promise<void> {
const prefix = `${params.id}\0`;
for (const key of this.tokens.keys()) {
if (key.startsWith(prefix)) {
this.tokens.delete(key);
}
}
}

async deletePendingAuthorizationsForServer(params: { id: string }): Promise<void> {
for (const [state, entry] of this.pending) {
if (entry.row.id === params.id) {
this.pending.delete(state);
}
}
}
}

/** In-memory OAuth client store for tests and development without a database. */
Expand Down
4 changes: 4 additions & 0 deletions packages/trueforge/src/mcp/auth/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ export interface IOAuthTokenStore<TTransaction = never> {
getToken(params: OAuthTokenKey, transaction?: TTransaction): Promise<OAuthToken | undefined>;
getTokens(params: { ids: string[]; userRef: string }, transaction?: TTransaction): Promise<Map<string, OAuthToken>>;
deleteToken(params: OAuthTokenKey, transaction?: TTransaction): Promise<void>;
/** Deletes every per-user token for one MCP server id (all users). */
deleteTokensForServer(params: { id: string }, transaction?: TTransaction): Promise<void>;
/** Deletes every in-flight authorization for one MCP server id (all users). */
deletePendingAuthorizationsForServer(params: { id: string }, transaction?: TTransaction): Promise<void>;
}

/** Authorization-server endpoints discovered and cached at registration time. */
Expand Down
42 changes: 42 additions & 0 deletions packages/trueforge/tests/db/oauthTokenStoreContractSuite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,22 @@ export function runOAuthTokenStoreContractSuite(getHarness: () => OAuthTokenStor
expect(await h.store.getToken({ id: RESOURCE_ID, userRef: OTHER_USER_REF })).toEqual(forB);
});

it('deleteTokensForServer removes every user token for that resource only', async () => {
const h = getHarness();
await h.seedResource(RESOURCE_ID);
await h.seedResource(OTHER_RESOURCE_ID);
const other = token({ accessToken: 'access-other' });
await h.store.saveToken({ id: RESOURCE_ID, userRef: USER_REF, token: token({ accessToken: 'access-a' }) });
await h.store.saveToken({ id: RESOURCE_ID, userRef: OTHER_USER_REF, token: token({ accessToken: 'access-b' }) });
await h.store.saveToken({ id: OTHER_RESOURCE_ID, userRef: USER_REF, token: other });

await h.store.deleteTokensForServer({ id: RESOURCE_ID });

expect(await h.store.getToken({ id: RESOURCE_ID, userRef: USER_REF })).toBeUndefined();
expect(await h.store.getToken({ id: RESOURCE_ID, userRef: OTHER_USER_REF })).toBeUndefined();
expect(await h.store.getToken({ id: OTHER_RESOURCE_ID, userRef: USER_REF })).toEqual(other);
});

it('savePendingAuthorization + consumePendingAuthorization round-trips, including null fields', async () => {
const h = getHarness();
await h.seedResource(RESOURCE_ID);
Expand Down Expand Up @@ -170,6 +186,32 @@ export function runOAuthTokenStoreContractSuite(getHarness: () => OAuthTokenStor
expect(await h.store.consumePendingAuthorization({ state: 'state-2' })).toEqual(other);
});

it('deletePendingAuthorizationsForServer removes every pending row for that resource only', async () => {
const h = getHarness();
await h.seedResource(RESOURCE_ID);
await h.seedResource(OTHER_RESOURCE_ID);
const otherUser = pending({
state: 'state-other-user',
userRef: OTHER_USER_REF,
codeVerifier: 'verifier-other-user',
});
const otherServer = pending({
state: 'state-other-server',
id: OTHER_RESOURCE_ID,
userRef: USER_REF,
codeVerifier: 'verifier-other-server',
});
await h.store.savePendingAuthorization(pending());
await h.store.savePendingAuthorization(otherUser);
await h.store.savePendingAuthorization(otherServer);

await h.store.deletePendingAuthorizationsForServer({ id: RESOURCE_ID });

expect(await h.store.consumePendingAuthorization({ state: 'state-1' })).toBeUndefined();
expect(await h.store.consumePendingAuthorization({ state: 'state-other-user' })).toBeUndefined();
expect(await h.store.consumePendingAuthorization({ state: 'state-other-server' })).toEqual(otherServer);
});

it('consumePendingAuthorization drops a row past its TTL', async () => {
const h = getHarness();
await h.seedResource(RESOURCE_ID);
Expand Down
30 changes: 23 additions & 7 deletions packages/trueforge/tests/unit/apis/mcpServers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ describe('mcp-servers routers', () => {
await tokenStore.deleteToken({ id: record.id, userRef: LOCAL_USER_CONTEXT.userRef });
});

it('PUT URL change re-registers DCR and keeps existing tokens', async () => {
it('PUT URL change re-registers DCR and clears tokens and pending authorizations', async () => {
const record = await seedDcrServerWithClient();
await tokenStore.saveToken({
id: record.id,
Expand All @@ -318,6 +318,24 @@ describe('mcp-servers routers', () => {
scope: null,
},
});
await tokenStore.saveToken({
id: record.id,
userRef: 'other-user',
token: {
accessToken: 'stale-other-user',
refreshToken: 'stale-other-refresh',
expiresAt: '2099-01-01T00:00:00.000Z',
scope: null,
},
});
await tokenStore.savePendingAuthorization({
state: 'stale-pending-state',
id: record.id,
userRef: LOCAL_USER_CONTEXT.userRef,
mcpServerUrl: putBodyWithDcr.url,
codeVerifier: 'stale-verifier',
redirectUrl: null,
});

const newUrl = 'https://mcp.linear.app/v2/mcp';
const asOrigin = 'https://auth.example.com';
Expand Down Expand Up @@ -373,13 +391,12 @@ describe('mcp-servers routers', () => {
),
);
expect(response.status).toBe(200);
// List/GET auth_status is presence-based; tokens are not cleared on re-DCR.
expect(await response.json()).toEqual({
data: configured({ ...putBodyWithDcr, url: newUrl }, 'authenticated'),
});
expect(await tokenStore.getToken({ id: record.id, userRef: LOCAL_USER_CONTEXT.userRef })).toMatchObject({
accessToken: 'stale-for-old-url',
data: configured({ ...putBodyWithDcr, url: newUrl }, 'auth_required'),
});
expect(await tokenStore.getToken({ id: record.id, userRef: LOCAL_USER_CONTEXT.userRef })).toBeUndefined();
expect(await tokenStore.getToken({ id: record.id, userRef: 'other-user' })).toBeUndefined();
expect(await tokenStore.consumePendingAuthorization({ state: 'stale-pending-state' })).toBeUndefined();
expect(await mcpServerStore.getClient({ id: record.id })).toMatchObject({
client: { clientId: 'new-url-client' },
});
Expand All @@ -405,7 +422,6 @@ describe('mcp-servers routers', () => {
},
},
});
await tokenStore.deleteToken({ id: record.id, userRef: LOCAL_USER_CONTEXT.userRef });
}
});

Expand Down
Loading