Skip to content

Commit 9e38cc1

Browse files
committed
fix(auth): keep OAuth refresh policy provider-owned
1 parent f512990 commit 9e38cc1

7 files changed

Lines changed: 42 additions & 96 deletions

File tree

‎src/agents/auth-profiles/oauth-manager.test.ts‎

Lines changed: 0 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -252,41 +252,6 @@ describe("OAuthManagerRefreshError", () => {
252252
});
253253

254254
describe("createOAuthManager", () => {
255-
it("accepts an unchanged expired credential as provider-owned refresh policy", async () => {
256-
await withOAuthTempRoot("oauth-manager-unchanged-refresh-", async (tempRoot) => {
257-
const agentDir = path.join(tempRoot, "agents", "main", "agent");
258-
await fs.mkdir(agentDir, { recursive: true });
259-
const profileId = "github-copilot:default";
260-
const credential = createCredential({
261-
provider: "github-copilot",
262-
access: "expired-copilot-access",
263-
refresh: "durable-github-token",
264-
expires: 1,
265-
});
266-
const refreshCredential = vi.fn(async () => credential);
267-
const manager = createOAuthManager({
268-
buildApiKey: async (_provider, value) => value.refresh,
269-
refreshCredential,
270-
readBootstrapCredential: () => null,
271-
isRefreshTokenReusedError: () => false,
272-
});
273-
const persistedStore: AuthProfileStore = {
274-
version: 1,
275-
profiles: { [profileId]: credential },
276-
};
277-
saveAuthProfileStore(persistedStore, agentDir, { filterExternalAuthProfiles: false });
278-
const store = ensureAuthProfileStoreWithoutExternalProfiles(agentDir, {
279-
allowKeychainPrompt: false,
280-
});
281-
282-
await expect(
283-
manager.resolveOAuthAccess({ store, profileId, credential, agentDir }),
284-
).resolves.toEqual({ apiKey: "durable-github-token", credential });
285-
expect(refreshCredential).toHaveBeenCalledOnce();
286-
expect(store.profiles[profileId]).toEqual(credential);
287-
});
288-
});
289-
290255
it("passes active config to OAuth API-key formatting", async () => {
291256
const profileId = "openai:oauth";
292257
const credential = createCredential({ expires: Date.now() + 10 * 60_000 });

‎src/agents/auth-profiles/oauth-manager.ts‎

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import { isDeepStrictEqual } from "node:util";
21
/**
32
* OAuth credential manager.
43
* Resolves usable access tokens, refreshes expired credentials under global
@@ -622,18 +621,6 @@ export function createOAuthManager(adapter: OAuthManagerAdapter) {
622621
if (!refreshedCredentials) {
623622
return null;
624623
}
625-
if (isDeepStrictEqual(refreshedCredentials, credentialToRefresh)) {
626-
// Providers may declare legacy access expiry irrelevant by returning
627-
// the same bundle. Use their formatted credential without rewriting
628-
// unchanged state or requiring a refreshable account identity.
629-
return {
630-
apiKey: await adapter.buildApiKey(cred.provider, refreshedCredentials, {
631-
cfg: params.cfg,
632-
agentDir: params.agentDir,
633-
}),
634-
credential: refreshedCredentials,
635-
};
636-
}
637624
store.profiles[params.profileId] = refreshedCredentials;
638625
const persisted = await saveOAuthCredentialWithStoreLock({
639626
agentDir: ownerAgentDir,

‎src/agents/auth-profiles/oauth.openai-codex-refresh-fallback.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,27 @@ describe("resolveApiKeyForProfile openai refresh fallback", () => {
223223
expect(refreshProviderOAuthCredentialWithPluginMock).toHaveBeenCalledTimes(1);
224224
});
225225

226+
it("fails closed when provider refresh returns an unchanged expired credential", async () => {
227+
const profileId = "openai:default";
228+
saveAuthProfileStore(
229+
createExpiredOauthStore({
230+
profileId,
231+
provider: "openai",
232+
}),
233+
agentDir,
234+
{ filterExternalAuthProfiles: false, syncExternalCli: false },
235+
);
236+
refreshProviderOAuthCredentialWithPluginMock.mockImplementationOnce(async (params) =>
237+
requireOAuthContext(params?.context),
238+
);
239+
240+
await expect(resolveOpenAICodexProfile({ profileId, agentDir })).rejects.toThrow(
241+
/OAuth token refresh failed for openai/,
242+
);
243+
expect(refreshProviderOAuthCredentialWithPluginMock).toHaveBeenCalledTimes(1);
244+
expect(getOAuthApiKeyMock).not.toHaveBeenCalled();
245+
});
246+
226247
it("surfaces refresh contention once without local lock details", async () => {
227248
const profileId = "openai:default";
228249
saveAuthProfileStore(createExpiredOauthStore({ profileId, provider: "openai" }), agentDir, {

‎src/agents/sessions/auth-storage.test.ts‎

Lines changed: 0 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -132,41 +132,6 @@ describe("SQLite auth storage", () => {
132132
expect(readPersistedAuthProfileStoreRaw(agentDir)).toEqual(unreadableStore);
133133
});
134134

135-
it("uses a provider-owned unchanged refresh result without rewriting the profile", async () => {
136-
const agentDir = makeAgentDir();
137-
const credential = {
138-
type: "oauth" as const,
139-
provider: "test-oauth",
140-
access: "expired-access",
141-
refresh: "durable-source-token",
142-
expires: 1,
143-
};
144-
writePersistedAuthProfileStoreRaw(
145-
{ version: 1, profiles: { "test-oauth:default": credential } },
146-
agentDir,
147-
);
148-
const storage = AuthStorage.forAgent(agentDir);
149-
getAuthStorageOAuthProviderRegistry(storage).register({
150-
id: "test-oauth",
151-
name: "Test OAuth",
152-
async login() {
153-
throw new Error("not used");
154-
},
155-
async refreshToken(credentials) {
156-
return credentials;
157-
},
158-
getApiKey(credentials) {
159-
return credentials.refresh;
160-
},
161-
});
162-
163-
await expect(storage.getApiKey("test-oauth")).resolves.toBe("durable-source-token");
164-
expect(readPersistedAuthProfileStoreRaw(agentDir)).toEqual({
165-
version: 1,
166-
profiles: { "test-oauth:default": credential },
167-
});
168-
});
169-
170135
it("does not commit a refresh when a legacy source appears during the provider call", async () => {
171136
const agentDir = makeAgentDir();
172137
writePersistedAuthProfileStoreRaw(

‎src/agents/sessions/auth-storage.ts‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -736,12 +736,6 @@ export class AuthStorage {
736736
type: "oauth",
737737
...refreshed.newCredentials,
738738
};
739-
if (isDeepStrictEqual(cred, refreshedCredential)) {
740-
// A provider can keep a durable source credential even when a legacy
741-
// access token expired. Avoid rewriting an intentionally unchanged
742-
// profile while still returning the provider-formatted API key.
743-
return { result: refreshed };
744-
}
745739
const merged: AuthStorageData = {
746740
...currentData,
747741
[providerId]: refreshedCredential,

‎src/llm/utils/oauth/github-copilot.test.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// GitHub Copilot OAuth tests cover device flow polling and timeout behavior.
22
import { getEventListeners } from "node:events";
3+
import { MAX_DATE_TIMESTAMP_MS } from "@openclaw/normalization-core/number-coercion";
34
import { afterEach, describe, expect, it, vi } from "vitest";
45
import type { Model } from "../../types.js";
56
import { githubCopilotOAuthProvider } from "./github-copilot.js";
@@ -301,12 +302,17 @@ describe("GitHub Copilot OAuth model routing", () => {
301302
expect(githubCopilotOAuthProvider.getApiKey(credential({}))).toBe("refresh-token");
302303
});
303304

304-
it("does not exchange an expired legacy access token during runtime resolution", async () => {
305+
it("normalizes an expired legacy access token without exchanging it", async () => {
305306
const expired = credential({ expires: 1 });
306307
const fetchMock = vi.fn();
307308
vi.stubGlobal("fetch", fetchMock);
308309

309-
await expect(githubCopilotOAuthProvider.refreshToken(expired)).resolves.toBe(expired);
310+
await expect(githubCopilotOAuthProvider.refreshToken(expired)).resolves.toEqual({
311+
...expired,
312+
access: "refresh-token",
313+
expires: MAX_DATE_TIMESTAMP_MS,
314+
});
315+
expect(expired).toMatchObject({ access: "access-token", expires: 1 });
310316
expect(fetchMock).not.toHaveBeenCalled();
311317
});
312318

‎src/llm/utils/oauth/github-copilot.ts‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@
22
* GitHub Copilot OAuth flow
33
*/
44

5-
import { resolveTimerTimeoutMs } from "@openclaw/normalization-core/number-coercion";
5+
import {
6+
MAX_DATE_TIMESTAMP_MS,
7+
resolveTimerTimeoutMs,
8+
} from "@openclaw/normalization-core/number-coercion";
69
import {
710
assertOkOrThrowProviderError,
811
readProviderJsonResponse,
@@ -45,6 +48,7 @@ const INITIAL_POLL_INTERVAL_MULTIPLIER = 1.2;
4548
const SLOW_DOWN_POLL_INTERVAL_MULTIPLIER = 1.4;
4649
const COPILOT_ROUTER_ID_PREFIX = "accounts/";
4750
const COPILOT_REQUEST_TIMEOUT_MS = 30_000;
51+
const COPILOT_SOURCE_CREDENTIAL_EXPIRES_AT_MS = MAX_DATE_TIMESTAMP_MS;
4852

4953
function resolveExpiresAtFromDurationSeconds(value: unknown): number | undefined {
5054
return resolveExpiresAtMsFromDurationSeconds(value);
@@ -566,10 +570,14 @@ export const githubCopilotOAuthProvider: OAuthProviderInterface = {
566570
},
567571

568572
async refreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {
569-
// `expires` belongs to the legacy exchanged Copilot token. Runtime auth now
570-
// validates and sends the durable GitHub credential, so expiry must not
571-
// force upgraded profiles back through the retired exchange.
572-
return credentials;
573+
// Legacy profiles expire the retired exchanged token, not the durable
574+
// GitHub credential. Normalize once so generic OAuth persistence records
575+
// the source token as active and never infers a successful no-op refresh.
576+
return {
577+
...credentials,
578+
access: credentials.refresh,
579+
expires: COPILOT_SOURCE_CREDENTIAL_EXPIRES_AT_MS,
580+
};
573581
},
574582

575583
getApiKey(credentials: OAuthCredentials): string {

0 commit comments

Comments
 (0)