🧹 fix: Clean Up MCP OAuth State Mappings on Uninstall + Reject Superseded Callbacks (#14549)

* 🧹 fix: Clean Up MCP OAuth State Mappings on Uninstall + Reject Superseded Callbacks

Disconnecting an OAuth MCP server deleted its mcp_oauth flows but left the
mcp_oauth_state:{state} mappings behind for the full TTL. Because flow ids
are deterministic (userId:serverName) and the CSRF token is HMAC(flowId), a
stale browser tab's callback could resolve its orphaned state to the NEXT
flow for the same server, pass CSRF, burn the fresh flow's one-shot CSRF
cookie, and fail the PKCE exchange, sabotaging the legitimate retry.

- Add MCPOAuthHandler.deleteFlowAndStateMapping: reads the flow's stored
  state and deletes the mapping before the flow (mapping-first so a crash
  between deletes fails closed instead of recreating the orphan)
- Route mcp_oauth deletions in clearStoredMCPOAuthState through the helper
  for both tenant-scoped and legacy flow ids
- Reject callbacks whose state does not match the resolved flow's stored
  state: the only control distinguishing a superseded attempt from the
  current one on a deterministic flow id

Fixes #14534

* fix: gate failFlow on state match in the OAuth error branch (Codex P1)

The provider-error branch failed the resolved flow on CSRF/session alone,
so a superseded error callback resolved through an orphaned mapping could
mark the current flow FAILED. Apply the same stored-state equality gate
before failFlow.

* fix: leave the flow in place when the state-mapping delete fails (Codex P2)

deleteFlow swallows storage errors and returns false, and
deleteStateMapping discarded that result, so a failed mapping delete
followed by a successful flow delete would silently recreate the orphan.
Surface the boolean from deleteStateMapping and throw from
deleteFlowAndStateMapping before touching the flow, so the caller's
allSettled warn branch fires and the next replacement retries both.

* fix: restore the state mapping when the flow delete fails (Codex P2)

The inverse partial failure of the round-3 fix: a successful mapping
delete followed by a silently failed flow delete left a PENDING flow
whose reused authorization URL could never resolve, dead-ending every
callback in invalid_state until the flow went stale. Check deleteFlow's
result, re-store the mapping on failure, and throw so the caller's
allSettled warn branch fires.

* fix: never leave a callback-capable flow behind on uninstall (Codex round 6)

Teardown runs after the server's tokens are deleted, so a preserved
flow+mapping pair (the round-3 early-throw path) let a lingering consent
tab complete the callback and recreate credentials post-uninstall. Now
that both callback branches gate on stored-state equality, an orphaned
mapping is the benign failure mode, so invert the order: delete the flow
first, attempt the mapping delete regardless, and reject when either
reports a storage failure. This supersedes the round-4 mapping restore,
which also preserved a callback-capable pair.

* fix: delete the flow even when its metadata read fails (Codex round 7)

A storage error on the initial getFlowState aborted teardown before any
delete ran, preserving the callback-capable flow after token deletion.
Tolerate the read failure, delete the flow blindly, skip the mapping it
could not identify (the callback gates neutralize the possible orphan),
and reject so the caller's warn branch fires.
This commit is contained in:
Danny Avila 2026-07-31 12:11:36 -04:00 committed by GitHub
parent a67b0c1da8
commit 78ec1940a2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 443 additions and 32 deletions

View file

@ -542,6 +542,159 @@ describe('MCP OAuth Race Condition Fixes', () => {
});
});
describe('deleteFlowAndStateMapping (uninstall teardown)', () => {
const createFlowManager = () => {
const store = new MockKeyv();
return new FlowStateManager<MCPOAuthTokens | null>(store as unknown as Keyv, {
ttl: 30000,
ci: true,
});
};
it('deletes both the flow and its state mapping', async () => {
const flowManager = createFlowManager();
const flowId = 'user1:test-server';
const state = 'random-state-abc123';
await flowManager.initFlow(flowId, 'mcp_oauth', { state });
await MCPOAuthHandler.storeStateMapping(state, flowId, flowManager);
await MCPOAuthHandler.deleteFlowAndStateMapping(flowId, flowManager);
expect(await MCPOAuthHandler.resolveStateToFlowId(state, flowManager)).toBeNull();
expect(await flowManager.getFlowState(flowId, 'mcp_oauth')).toBeFalsy();
});
it('handles tenant-prefixed flow ids', async () => {
const flowManager = createFlowManager();
const flowId = 'tenant:acme:user1:test-server';
const state = 'tenant-state-xyz789';
await flowManager.initFlow(flowId, 'mcp_oauth', { state });
await MCPOAuthHandler.storeStateMapping(state, flowId, flowManager);
await MCPOAuthHandler.deleteFlowAndStateMapping(flowId, flowManager);
expect(await MCPOAuthHandler.resolveStateToFlowId(state, flowManager)).toBeNull();
expect(await flowManager.getFlowState(flowId, 'mcp_oauth')).toBeFalsy();
});
it('is a no-op when the flow is absent and leaves unrelated mappings intact', async () => {
const flowManager = createFlowManager();
const otherFlowId = 'user2:other-server';
const otherState = 'other-state-def456';
await flowManager.initFlow(otherFlowId, 'mcp_oauth', { state: otherState });
await MCPOAuthHandler.storeStateMapping(otherState, otherFlowId, flowManager);
await expect(
MCPOAuthHandler.deleteFlowAndStateMapping('user1:missing-server', flowManager),
).resolves.toBeUndefined();
expect(await MCPOAuthHandler.resolveStateToFlowId(otherState, flowManager)).toBe(otherFlowId);
});
it('deletes the flow before the state mapping', async () => {
const flowManager = createFlowManager();
const flowId = 'user1:test-server';
const state = 'ordered-state-ghi789';
await flowManager.initFlow(flowId, 'mcp_oauth', { state });
await MCPOAuthHandler.storeStateMapping(state, flowId, flowManager);
const calls: string[] = [];
const deleteFlowSpy = jest.spyOn(flowManager, 'deleteFlow');
deleteFlowSpy.mockImplementation(async (id, type) => {
calls.push(`${type}:${id}`);
return true;
});
await MCPOAuthHandler.deleteFlowAndStateMapping(flowId, flowManager);
expect(calls).toEqual([`mcp_oauth:${flowId}`, `mcp_oauth_state:${state}`]);
});
it('still deletes the flow and rejects when the mapping delete hits a storage error', async () => {
const flowManager = createFlowManager();
const flowId = 'user1:test-server';
const state = 'failing-state-jkl012';
await flowManager.initFlow(flowId, 'mcp_oauth', { state });
await MCPOAuthHandler.storeStateMapping(state, flowId, flowManager);
const realDeleteFlow = flowManager.deleteFlow.bind(flowManager);
jest.spyOn(flowManager, 'deleteFlow').mockImplementation(async (id, type) => {
if (type === 'mcp_oauth_state') {
return false;
}
return realDeleteFlow(id, type);
});
await expect(MCPOAuthHandler.deleteFlowAndStateMapping(flowId, flowManager)).rejects.toThrow(
'Failed to fully delete OAuth flow',
);
/** The callback-capable flow must not survive token deletion */
expect(await flowManager.getFlowState(flowId, 'mcp_oauth')).toBeFalsy();
});
it('still deletes the mapping and rejects when the flow delete hits a storage error', async () => {
const flowManager = createFlowManager();
const flowId = 'user1:test-server';
const state = 'restore-state-mno345';
await flowManager.initFlow(flowId, 'mcp_oauth', { state });
await MCPOAuthHandler.storeStateMapping(state, flowId, flowManager);
const realDeleteFlow = flowManager.deleteFlow.bind(flowManager);
jest.spyOn(flowManager, 'deleteFlow').mockImplementation(async (id, type) => {
if (type === 'mcp_oauth') {
return false;
}
return realDeleteFlow(id, type);
});
await expect(MCPOAuthHandler.deleteFlowAndStateMapping(flowId, flowManager)).rejects.toThrow(
'Failed to fully delete OAuth flow',
);
/** The surviving flow must not stay callback-capable: its state no longer resolves */
expect(await MCPOAuthHandler.resolveStateToFlowId(state, flowManager)).toBeNull();
expect(await flowManager.getFlowState(flowId, 'mcp_oauth')).toBeTruthy();
});
it('still deletes the flow and rejects when the metadata read hits a storage error', async () => {
const flowManager = createFlowManager();
const flowId = 'user1:test-server';
const state = 'unreadable-state-pqr678';
await flowManager.initFlow(flowId, 'mcp_oauth', { state });
await MCPOAuthHandler.storeStateMapping(state, flowId, flowManager);
jest
.spyOn(flowManager, 'getFlowState')
.mockRejectedValueOnce(new Error('read connection lost'));
await expect(MCPOAuthHandler.deleteFlowAndStateMapping(flowId, flowManager)).rejects.toThrow(
'Failed to fully delete OAuth flow',
);
/** The callback-capable flow must not survive token deletion */
expect(await flowManager.getFlowState(flowId, 'mcp_oauth')).toBeFalsy();
});
it('still deletes the flow when metadata carries no state', async () => {
const flowManager = createFlowManager();
const flowId = 'user1:stateless-server';
await flowManager.initFlow(flowId, 'mcp_oauth', { serverName: 'stateless-server' });
await MCPOAuthHandler.deleteFlowAndStateMapping(flowId, flowManager);
expect(await flowManager.getFlowState(flowId, 'mcp_oauth')).toBeFalsy();
});
});
describe('Fix 4: ReauthenticationRequiredError for no-refresh-token', () => {
it('should throw ReauthenticationRequiredError when access token expired and no refresh token', async () => {
const expiredDate = new Date(Date.now() - 60000);

View file

@ -1290,12 +1290,51 @@ export class MCPOAuthHandler {
/**
* Deletes an orphaned state mapping when a flow is replaced.
* Prevents old authorization URLs from resolving after a flow restart.
* Returns `false` when the underlying store rejected the delete.
*/
static async deleteStateMapping(
state: string,
flowManager: FlowStateManager<MCPOAuthTokens | null>,
): Promise<boolean> {
return flowManager.deleteFlow(state, this.STATE_MAP_TYPE);
}
/**
* Deletes an OAuth flow together with its state mapping, for teardown paths
* that don't already hold the flow (e.g. server uninstall). The flow is
* deleted first on purpose: it is what makes a provider callback
* completable, and teardown runs after the server's tokens were removed, so
* a surviving callback-capable flow could recreate credentials the user
* just revoked. A failure between the two deletes leaves at worst an
* orphaned mapping, which the callback's stored-state equality gates reduce
* to a clean invalid_state. Both deletes are attempted regardless of the
* other's outcome; any reported storage failure is surfaced as a rejection
* for the caller's best-effort logging.
*/
static async deleteFlowAndStateMapping(
flowId: string,
flowManager: FlowStateManager<MCPOAuthTokens | null>,
): Promise<void> {
await flowManager.deleteFlow(state, this.STATE_MAP_TYPE);
/** A failed metadata read must not abort teardown: the flow is deleted
* blindly and the unidentifiable mapping is left to the callback gates */
let state: string | null = null;
let metadataReadFailed = false;
try {
const flowState = await flowManager.getFlowState(flowId, this.FLOW_TYPE);
const metadata = flowState?.metadata as MCPOAuthFlowMetadata | undefined;
state = typeof metadata?.state === 'string' ? metadata.state : null;
} catch {
metadataReadFailed = true;
}
const flowDeleted = await flowManager.deleteFlow(flowId, this.FLOW_TYPE);
const mappingDeleted = state ? await this.deleteStateMapping(state, flowManager) : true;
if (metadataReadFailed || !flowDeleted || !mappingDeleted) {
throw new Error(
`Failed to fully delete OAuth flow ${flowId} (metadata read ok: ${!metadataReadFailed}, flow deleted: ${flowDeleted}, state mapping deleted: ${mappingDeleted})`,
);
}
}
/**