Skip to content

Commit 8d1590f

Browse files
committed
fix(responses): bind OAuth continuation to stable accounts
1 parent 65b5b34 commit 8d1590f

3 files changed

Lines changed: 114 additions & 11 deletions

File tree

‎src/oauth/index.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ import { detectClaudeCodeToken, detectGrokCliToken, hasComparableGrokIdentity, i
2424
import { logOAuthEvent } from "./log";
2525
import { captureConfigGeneration, sweepExpiredOnWrite, type GenerationContext } from "../lib/state-store-sweeper";
2626
import { retainedUtf8Bytes } from "../lib/admission";
27-
import { randomUUID } from "node:crypto";
27+
import { createHash, randomUUID } from "node:crypto";
2828
export {
2929
CODEX_HEALTH_AUTH_FAILED_NOTE,
3030
CODEX_HEALTH_MANAGEMENT_API_UNAVAILABLE_NOTE,
@@ -52,6 +52,8 @@ import { codexAccountNamespaceProviderCollisionError } from "../codex/account-na
5252
const REFRESH_SKEW_MS = 60_000;
5353
export interface OAuthAccessSnapshot {
5454
provider: string;
55+
/** Stable pseudonymous subject for account-bound continuation; absent without an immutable account id. */
56+
credentialSubjectHash?: string;
5557
accountId: string;
5658
generation: string;
5759
accessToken: string;
@@ -299,13 +301,28 @@ export class OAuthLoginRequiredError extends Error {
299301
}
300302

301303
function accessSnapshot(provider: string, accountId: string, cred: OAuthCredentials): OAuthAccessSnapshot {
304+
// Email is not an immutable upstream subject: multiple accounts may share or later reuse it.
305+
// Fail closed unless the provider supplied its stable account id.
306+
const stableCredentialSubject = cred.accountId?.trim()
307+
? ["account-id", cred.accountId.trim()]
308+
: undefined;
302309
const storedKiroRouting = {
303310
...(cred.kiro?.profileArn ? { profileArn: cred.kiro.profileArn } : {}),
304311
...(cred.kiro?.apiRegion ? { apiRegion: cred.kiro.apiRegion } : {}),
305312
...(cred.kiro?.ssoRegion ? { ssoRegion: cred.kiro.ssoRegion } : {}),
306313
};
307314
return {
308315
provider,
316+
...(stableCredentialSubject
317+
? {
318+
credentialSubjectHash: createHash("sha256")
319+
.update("opencodex-oauth-credential-subject\0")
320+
.update(provider)
321+
.update("\0")
322+
.update(JSON.stringify(stableCredentialSubject))
323+
.digest("hex"),
324+
}
325+
: {}),
309326
accountId,
310327
generation: credentialGeneration(cred),
311328
accessToken: cred.access,

‎src/server/responses/core.ts‎

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -305,20 +305,20 @@ function providerContinuationOwnerForRoute(args: {
305305
providerName: string;
306306
provider: OcxProviderConfig;
307307
adapterName: string;
308-
oauthCredentialSnapshot?: Pick<OAuthAccessSnapshot, "accountId" | "generation">;
308+
oauthCredentialSnapshot?: Pick<OAuthAccessSnapshot, "accountId" | "generation" | "credentialSubjectHash">;
309309
codexAuthContext?: CodexAuthContext;
310310
forwardHeaders?: Headers;
311311
}): OcxProviderContinuationOwner | undefined {
312312
const { parsed, providerName, provider, adapterName } = args;
313313
const authMode = provider.authMode ?? "key";
314314
let credentialIdentity: string | undefined;
315315
if (authMode === "oauth") {
316-
const accountId = args.oauthCredentialSnapshot?.accountId?.trim();
317-
if (!accountId) return undefined;
318-
const accountMaterial = JSON.stringify([providerName, accountId]);
316+
const credentialSubjectHash = args.oauthCredentialSnapshot?.credentialSubjectHash?.trim();
317+
if (!credentialSubjectHash) return undefined;
318+
const accountMaterial = JSON.stringify([providerName, credentialSubjectHash]);
319319
// Credential-bearing header overrides are part of the physical identity. Keep them behind
320-
// the existing process-local HMAC; without overrides the non-secret account slot can remain
321-
// restart-stable across ordinary access-token refreshes.
320+
// the existing process-local HMAC. Without overrides, only a verified credential subject is
321+
// restart-stable across ordinary access-token refreshes; a reusable local slot is not identity.
322322
credentialIdentity = reasoningReplayHasCredentialHeaderOverrides(provider.headers)
323323
? reasoningReplayCredentialIdentity("oauth", accountMaterial, provider.headers)
324324
: `oauth-account:${continuationIdentity("provider-continuation-oauth-account", accountMaterial)}`;
@@ -436,7 +436,7 @@ function bindRouteReasoningReplayScope(args: {
436436
providerName: string;
437437
provider: OcxProviderConfig;
438438
adapterName: string;
439-
oauthCredentialSnapshot?: Pick<OAuthAccessSnapshot, "accountId" | "generation">;
439+
oauthCredentialSnapshot?: Pick<OAuthAccessSnapshot, "accountId" | "generation" | "credentialSubjectHash">;
440440
codexAuthContext?: CodexAuthContext;
441441
forwardHeaders?: Headers;
442442
}): void {
@@ -2212,7 +2212,10 @@ async function handleResponsesInner(
22122212
const isOAuth401ReplayProvider = (route.providerName === "xai" || route.providerName === "github-copilot" || route.providerName === "kiro")
22132213
&& route.provider.authMode === "oauth";
22142214
let sentOAuthSnapshot: OAuthAccessSnapshot | undefined;
2215-
let replayOAuthCredentialSnapshot: Pick<OAuthAccessSnapshot, "accountId" | "generation"> | undefined;
2215+
let replayOAuthCredentialSnapshot: Pick<
2216+
OAuthAccessSnapshot,
2217+
"accountId" | "generation" | "credentialSubjectHash"
2218+
> | undefined;
22162219
let anthropicPoolAccountId: string | null = null;
22172220
let anthropicPoolFailovers = 0;
22182221
const anthropicSessionKey = route.providerName === "anthropic" && route.provider.authMode === "oauth"
@@ -2251,6 +2254,9 @@ async function handleResponsesInner(
22512254
replayOAuthCredentialSnapshot = {
22522255
accountId: resolved.accountId,
22532256
generation: resolved.generation,
2257+
...(resolved.credentialSubjectHash
2258+
? { credentialSubjectHash: resolved.credentialSubjectHash }
2259+
: {}),
22542260
};
22552261
if (isOAuth401ReplayProvider) sentOAuthSnapshot = resolved;
22562262
route.provider = { ...route.provider, apiKey: resolved.accessToken };
@@ -3878,6 +3884,9 @@ async function handleResponsesInner(
38783884
replayOAuthCredentialSnapshot = {
38793885
accountId: refreshed.accountId,
38803886
generation: refreshed.generation,
3887+
...(refreshed.credentialSubjectHash
3888+
? { credentialSubjectHash: refreshed.credentialSubjectHash }
3889+
: {}),
38813890
};
38823891
if (route.providerName === "kiro") {
38833892
parsed._kiroAuthContext = { ...(refreshed.kiro ?? {}) };

‎tests/server-combo-failover-e2e.test.ts‎

Lines changed: 79 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
import { getConfigDir, readConfigDiagnostics, saveConfig } from "../src/config";
1313
import type { ProviderAdapter } from "../src/adapters/base";
1414
import { handleManagementAPI } from "../src/server/management-api";
15-
import { saveCredential } from "../src/oauth/store";
15+
import { getAccountSet, saveCredential } from "../src/oauth/store";
1616
import { XAI_OAUTH_DISCOVERY_URL } from "../src/oauth/xai";
1717
import { XAI_GROK_CLI_BASE_URL } from "../src/providers/xai-transport";
1818
import type { AdapterEvent, OcxConfig, OcxProviderConfig, OcxProviderContinuationState } from "../src/types";
@@ -1895,7 +1895,11 @@ describe("server combo failover 030 activation matrix", () => {
18951895

18961896
test("Kiro OAuth continuation follows the account across refresh but not account replacement", async () => {
18971897
const seen: Array<string | undefined> = [];
1898-
const { clearResponseStateForTests, flushResponseState } = await import("../src/responses/state");
1898+
const {
1899+
clearResponseStateForTests,
1900+
clearResponseStateMemoryForTests,
1901+
flushResponseState,
1902+
} = await import("../src/responses/state");
18991903
clearResponseStateForTests();
19001904
customRunTurn = async (parsed, _incoming, emit) => {
19011905
const conversationId = parsed._providerContinuation?.kiro?.conversationId;
@@ -1930,6 +1934,7 @@ describe("server combo failover 030 activation matrix", () => {
19301934
expect(persisted).not.toContain("xai-access-one");
19311935
expect(persisted).not.toContain("xai-refresh-one");
19321936
expect(persisted).not.toContain("acct-xai-a");
1937+
clearResponseStateMemoryForTests();
19331938

19341939
await saveCredential("xai", {
19351940
access: "xai-access-two",
@@ -1975,6 +1980,78 @@ describe("server combo failover 030 activation matrix", () => {
19751980
expect(seen).toEqual([undefined, "kiro-oauth-conversation", undefined, undefined]);
19761981
});
19771982

1983+
test("OAuth credentials without immutable account ids do not inherit provider continuation state", async () => {
1984+
const seen: Array<string | undefined> = [];
1985+
const {
1986+
clearResponseStateForTests,
1987+
clearResponseStateMemoryForTests,
1988+
flushResponseState,
1989+
} = await import("../src/responses/state");
1990+
clearResponseStateForTests();
1991+
customRunTurn = async (parsed, _incoming, emit) => {
1992+
const conversationId = parsed._providerContinuation?.kiro?.conversationId;
1993+
seen.push(conversationId);
1994+
emit({ type: "text_delta", text: "continued" });
1995+
emit({
1996+
type: "done",
1997+
providerState: { kiro: { conversationId: conversationId ?? "identityless-oauth-conversation" } },
1998+
});
1999+
};
2000+
const config = comboConfig({
2001+
xai: provider("openai-chat", "https://api.x.ai/v1", "unused", {
2002+
authMode: "oauth",
2003+
note: "test-kiro-oauth",
2004+
}),
2005+
}, [{ provider: "xai", model: "m1" }]);
2006+
const cases: Array<{ name: string; email?: string }> = [
2007+
{ name: "identityless" },
2008+
{ name: "email-only", email: "[email protected]" },
2009+
];
2010+
for (const testCase of cases) {
2011+
clearResponseStateForTests();
2012+
seen.length = 0;
2013+
await saveCredential("xai", {
2014+
access: `${testCase.name}-access-one`,
2015+
refresh: `${testCase.name}-refresh-one`,
2016+
expires: Date.now() + 3_600_000,
2017+
source: "oauth",
2018+
...(testCase.email ? { email: testCase.email } : {}),
2019+
});
2020+
const firstSlotId = getAccountSet("xai")?.activeAccountId;
2021+
expect(firstSlotId).toBeDefined();
2022+
2023+
const first = await post(config, { store: false, input: "first" });
2024+
expect(first.status).toBe(200);
2025+
const firstJson = await first.json() as { id: string };
2026+
await flushResponseState();
2027+
clearResponseStateMemoryForTests();
2028+
2029+
await saveCredential("xai", {
2030+
access: `${testCase.name}-access-two`,
2031+
refresh: `${testCase.name}-refresh-two`,
2032+
expires: Date.now() + 3_600_000,
2033+
source: "oauth",
2034+
...(testCase.email ? { email: testCase.email } : {}),
2035+
});
2036+
expect(getAccountSet("xai")?.activeAccountId).toBe(firstSlotId);
2037+
const second = await post(config, {
2038+
store: false,
2039+
previous_response_id: firstJson.id,
2040+
input: "second",
2041+
});
2042+
2043+
expect(second.status).toBe(200);
2044+
expect(seen).toEqual([undefined, undefined]);
2045+
await flushResponseState();
2046+
const persisted = readFileSync(join(getConfigDir(), "responses-state.json"), "utf8");
2047+
expect(persisted).not.toContain(`${testCase.name}-access-one`);
2048+
expect(persisted).not.toContain(`${testCase.name}-refresh-one`);
2049+
expect(persisted).not.toContain(`${testCase.name}-access-two`);
2050+
expect(persisted).not.toContain(`${testCase.name}-refresh-two`);
2051+
if (testCase.email) expect(persisted).not.toContain(testCase.email);
2052+
}
2053+
});
2054+
19782055
test("disabled image input rejects an image restored from previous_response_id before dispatch", async () => {
19792056
const { rememberResponseState } = await import("../src/responses/state");
19802057
rememberResponseState(

0 commit comments

Comments
 (0)