Skip to content

Commit 64b4358

Browse files
fix(agents): keep session auth rotation on one provider route
Session auth-profile rotation (compaction round-robin, cooldown replacement) rotated over the provider's full configured order, route-blind. On OpenAI dual-route models an API-key session could rotate onto an OAuth profile and silently switch to the ChatGPT subscription route. Rotation now consults the provider-owned route dispatcher and constrains itself to the current pin's route only when the model resolves multiple routes; routeless providers keep mixed-mode rotation (Anthropic api-key -> claude-cli OAuth fallback preserved). New resolveSessionAuthSelection facade owns provider expansion, rotation, provenance, configured-profile precedence, and route requirement; all four callers migrate to it and inference-runtime drops its duplicate credential-mode re-derivation. Replaces #123894. Co-authored-by: fuller-stack-dev <[email protected]>
1 parent a132518 commit 64b4358

20 files changed

Lines changed: 598 additions & 315 deletions
Lines changed: 283 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,283 @@
1+
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
import type { SessionEntry } from "../../config/sessions/types.js";
3+
import type { OpenClawConfig } from "../../config/types.openclaw.js";
4+
import { resolveSessionAuthSelection } from "./session-override.js";
5+
import type { AuthProfileStore } from "./types.js";
6+
7+
const API_PRIMARY = "openai:api-primary";
8+
const API_BACKUP = "openai:api-backup";
9+
const OAUTH = "openai:subscription";
10+
const TOKEN = "openai:token-backup";
11+
const ANTHROPIC_API = "anthropic:api";
12+
const ANTHROPIC_CLI = "anthropic:claude-cli";
13+
const SESSION_KEY = "agent:main:main";
14+
const OPENAI_MODEL = "gpt-5.6-luna";
15+
16+
const authStoreMocks = vi.hoisted(() => {
17+
const state: { store: AuthProfileStore } = {
18+
store: { version: 1, profiles: {} },
19+
};
20+
return {
21+
state,
22+
isProfileInCooldown: vi.fn((_store: AuthProfileStore, _profileId: string) => false),
23+
};
24+
});
25+
26+
vi.mock("./store.js", () => ({
27+
ensureAuthProfileStore: () => authStoreMocks.state.store,
28+
hasAnyAuthProfileStoreSource: () => true,
29+
}));
30+
31+
vi.mock("./order.js", () => ({
32+
isStoredCredentialCompatibleWithAuthProvider: ({
33+
provider,
34+
credential,
35+
}: {
36+
provider: string;
37+
credential: { provider: string };
38+
}) => credential.provider === provider,
39+
isConfiguredAwsSdkAuthProfileForProvider: () => false,
40+
resolveAuthProfileOrder: ({ store, provider }: { store: AuthProfileStore; provider: string }) =>
41+
store.order?.[provider] ?? [],
42+
}));
43+
44+
vi.mock("./usage.js", () => ({
45+
isProfileInCooldown: authStoreMocks.isProfileInCooldown,
46+
}));
47+
48+
function configureOpenAI(order: string[]): void {
49+
authStoreMocks.state.store = {
50+
version: 1,
51+
profiles: {
52+
[API_PRIMARY]: { type: "api_key", provider: "openai", key: "sk-primary" },
53+
[API_BACKUP]: { type: "api_key", provider: "openai", key: "sk-backup" },
54+
[OAUTH]: {
55+
type: "oauth",
56+
provider: "openai",
57+
access: "test-access",
58+
refresh: "test-refresh",
59+
expires: Date.now() + 60_000,
60+
},
61+
[TOKEN]: { type: "token", provider: "openai", token: "test-token" },
62+
},
63+
order: { openai: order },
64+
};
65+
}
66+
67+
function configureAnthropic(): void {
68+
authStoreMocks.state.store = {
69+
version: 1,
70+
profiles: {
71+
[ANTHROPIC_API]: { type: "api_key", provider: "anthropic", key: "sk-anthropic" },
72+
[ANTHROPIC_CLI]: {
73+
type: "oauth",
74+
provider: "anthropic",
75+
access: "test-access",
76+
refresh: "test-refresh",
77+
expires: Date.now() + 60_000,
78+
},
79+
},
80+
order: { anthropic: [ANTHROPIC_API, ANTHROPIC_CLI] },
81+
};
82+
}
83+
84+
function automaticEntry(profileId: string, overrides: Partial<SessionEntry> = {}): SessionEntry {
85+
return {
86+
sessionId: "s1",
87+
updatedAt: 1,
88+
compactionCount: 1,
89+
authProfileOverride: profileId,
90+
authProfileOverrideSource: "auto",
91+
authProfileOverrideCompactionCount: 0,
92+
...overrides,
93+
};
94+
}
95+
96+
async function resolveSelection(params: {
97+
provider: string;
98+
modelId: string;
99+
configuredProfileId?: string;
100+
sessionEntry: SessionEntry;
101+
}) {
102+
return await resolveSessionAuthSelection({
103+
cfg: {} as OpenClawConfig,
104+
provider: params.provider,
105+
modelId: params.modelId,
106+
...(params.configuredProfileId ? { configuredProfileId: params.configuredProfileId } : {}),
107+
agentDir: "/tmp/openclaw-session-auth-rotation",
108+
sessionEntry: params.sessionEntry,
109+
sessionStore: { [SESSION_KEY]: params.sessionEntry },
110+
sessionKey: SESSION_KEY,
111+
isNewSession: false,
112+
});
113+
}
114+
115+
describe("session auth-profile route rotation", () => {
116+
beforeEach(() => {
117+
authStoreMocks.state.store = { version: 1, profiles: {} };
118+
authStoreMocks.isProfileInCooldown.mockReset();
119+
authStoreMocks.isProfileInCooldown.mockReturnValue(false);
120+
});
121+
122+
it("rotates OpenAI API-key sessions only to an API-key backup", async () => {
123+
configureOpenAI([API_PRIMARY, OAUTH, API_BACKUP]);
124+
const sessionEntry = automaticEntry(API_PRIMARY);
125+
126+
const selection = await resolveSelection({
127+
provider: "openai",
128+
modelId: OPENAI_MODEL,
129+
sessionEntry,
130+
});
131+
132+
expect(selection).toEqual({
133+
profileId: API_BACKUP,
134+
source: "auto",
135+
routeRequirement: "api-key",
136+
});
137+
expect(sessionEntry.authProfileOverride).toBe(API_BACKUP);
138+
expect(sessionEntry.authProfileOverrideCompactionCount).toBe(1);
139+
});
140+
141+
it("rotates OpenAI subscription sessions to a token backup", async () => {
142+
configureOpenAI([OAUTH, API_PRIMARY, TOKEN]);
143+
const sessionEntry = automaticEntry(OAUTH);
144+
145+
const selection = await resolveSelection({
146+
provider: "openai",
147+
modelId: OPENAI_MODEL,
148+
sessionEntry,
149+
});
150+
151+
expect(selection?.profileId).toBe(TOKEN);
152+
expect(selection?.routeRequirement).toBe("subscription");
153+
});
154+
155+
it("keeps the current OpenAI route when it has no backup profile", async () => {
156+
configureOpenAI([API_PRIMARY, OAUTH]);
157+
const sessionEntry = automaticEntry(API_PRIMARY);
158+
159+
const selection = await resolveSelection({
160+
provider: "openai",
161+
modelId: OPENAI_MODEL,
162+
sessionEntry,
163+
});
164+
165+
expect(selection?.profileId).toBe(API_PRIMARY);
166+
expect(sessionEntry.authProfileOverrideCompactionCount).toBe(1);
167+
});
168+
169+
it("replaces a cooled-down OpenAI profile only within its current route", async () => {
170+
configureOpenAI([API_PRIMARY, OAUTH, API_BACKUP]);
171+
authStoreMocks.isProfileInCooldown.mockImplementation(
172+
(_store: AuthProfileStore, profileId: string) => profileId === API_PRIMARY,
173+
);
174+
const sessionEntry = automaticEntry(API_PRIMARY, {
175+
compactionCount: 0,
176+
authProfileOverrideCompactionCount: 0,
177+
});
178+
179+
const selection = await resolveSelection({
180+
provider: "openai",
181+
modelId: OPENAI_MODEL,
182+
sessionEntry,
183+
});
184+
185+
expect(selection?.profileId).toBe(API_BACKUP);
186+
expect(sessionEntry.authProfileOverride).toBe(API_BACKUP);
187+
});
188+
189+
it.each(["compaction", "cooldown"] as const)(
190+
"keeps Anthropic API-key to CLI OAuth fallback across %s",
191+
async (trigger) => {
192+
configureAnthropic();
193+
if (trigger === "cooldown") {
194+
authStoreMocks.isProfileInCooldown.mockImplementation(
195+
(_store: AuthProfileStore, profileId: string) => profileId === ANTHROPIC_API,
196+
);
197+
}
198+
const sessionEntry = automaticEntry(
199+
ANTHROPIC_API,
200+
trigger === "cooldown" ? { compactionCount: 0, authProfileOverrideCompactionCount: 0 } : {},
201+
);
202+
203+
const selection = await resolveSelection({
204+
provider: "anthropic",
205+
modelId: "sonnet-4.6",
206+
sessionEntry,
207+
});
208+
209+
expect(selection?.profileId).toBe(ANTHROPIC_CLI);
210+
expect(selection?.routeRequirement).toBe("subscription");
211+
},
212+
);
213+
214+
it("returns prepared route facts for an explicit user pin", async () => {
215+
configureOpenAI([API_PRIMARY, API_BACKUP]);
216+
const sessionEntry: SessionEntry = {
217+
sessionId: "s1",
218+
updatedAt: 1,
219+
authProfileOverride: API_PRIMARY,
220+
authProfileOverrideSource: "user",
221+
};
222+
223+
await expect(
224+
resolveSelection({ provider: "openai", modelId: OPENAI_MODEL, sessionEntry }),
225+
).resolves.toEqual({
226+
profileId: API_PRIMARY,
227+
source: "user",
228+
routeRequirement: "api-key",
229+
});
230+
});
231+
232+
it("uses only the explicit configured profile for default-profile precedence", async () => {
233+
configureOpenAI([API_PRIMARY, OAUTH]);
234+
const sessionEntry = automaticEntry(API_PRIMARY, {
235+
compactionCount: 0,
236+
authProfileOverrideCompactionCount: 0,
237+
});
238+
239+
await expect(
240+
resolveSelection({
241+
provider: "openai",
242+
modelId: `${OPENAI_MODEL}@${OAUTH}`,
243+
sessionEntry,
244+
}),
245+
).resolves.toMatchObject({ profileId: API_PRIMARY, source: "auto" });
246+
await expect(
247+
resolveSelection({
248+
provider: "openai",
249+
modelId: OPENAI_MODEL,
250+
configuredProfileId: OAUTH,
251+
sessionEntry,
252+
}),
253+
).resolves.toEqual({
254+
profileId: OAUTH,
255+
source: "user",
256+
routeRequirement: "subscription",
257+
});
258+
});
259+
260+
it("keeps an automatic override after its cooldown expires", async () => {
261+
configureOpenAI([API_PRIMARY]);
262+
authStoreMocks.state.store.usageStats = {
263+
[API_PRIMARY]: { cooldownUntil: Date.now() - 1 },
264+
};
265+
authStoreMocks.isProfileInCooldown.mockImplementation(
266+
(store: AuthProfileStore, profileId: string) =>
267+
(store.usageStats?.[profileId]?.cooldownUntil ?? 0) > Date.now(),
268+
);
269+
const sessionEntry = automaticEntry(API_PRIMARY, {
270+
compactionCount: 0,
271+
authProfileOverrideCompactionCount: 0,
272+
});
273+
274+
const selection = await resolveSelection({
275+
provider: "openai",
276+
modelId: OPENAI_MODEL,
277+
sessionEntry,
278+
});
279+
280+
expect(selection?.profileId).toBe(API_PRIMARY);
281+
expect(sessionEntry.updatedAt).toBe(1);
282+
});
283+
});

0 commit comments

Comments
 (0)