Skip to content

Commit a81ded1

Browse files
fix: bind copilot token cache to github profile fingerprint (#43658)
Port the fix from PR #43659 to the correct active file paths. The original PR targeted src/providers/github-copilot-token.ts which no longer exists in current main. Changes: - extensions/github-copilot/token.ts: add githubTokenFingerprint field to CachedCopilotToken, export fingerprintGithubToken() helper, require fingerprint match on cache hit so profile rotation forces a fresh exchange - src/agents/github-copilot-token.ts: identical fix for the legacy agent path - extensions/github-copilot/models.test.ts: update cache-hit test to include fingerprint; add two regression tests (different profile bypasses cache, legacy entry without fingerprint treated as miss) Closes #43658 Co-authored-by: Copilot <[email protected]>
1 parent 7719257 commit a81ded1

3 files changed

Lines changed: 108 additions & 3 deletions

File tree

‎extensions/github-copilot/models.test.ts‎

Lines changed: 74 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ import { resolveCopilotForwardCompatModel } from "./models.js";
4040

4141
let deriveCopilotApiBaseUrlFromToken: typeof import("./token.js").deriveCopilotApiBaseUrlFromToken;
4242
let resolveCopilotApiToken: typeof import("./token.js").resolveCopilotApiToken;
43+
let fingerprintGithubToken: typeof import("./token.js").fingerprintGithubToken;
4344

4445
function createMockCtx(
4546
modelId: string,
@@ -305,7 +306,7 @@ describe("github-copilot token", () => {
305306
vi.resetModules();
306307
loadJsonFile.mockClear();
307308
saveJsonFile.mockClear();
308-
({ deriveCopilotApiBaseUrlFromToken, resolveCopilotApiToken } = await import("./token.js"));
309+
({ deriveCopilotApiBaseUrlFromToken, resolveCopilotApiToken, fingerprintGithubToken } = await import("./token.js"));
309310
});
310311

311312
it("derives baseUrl from token", async () => {
@@ -323,6 +324,7 @@ describe("github-copilot token", () => {
323324
token: "cached;proxy-ep=proxy.example.com;",
324325
expiresAt: now + 60 * 60 * 1000,
325326
updatedAt: now,
327+
githubTokenFingerprint: fingerprintGithubToken("gh"),
326328
});
327329

328330
const fetchImpl = vi.fn();
@@ -363,5 +365,76 @@ describe("github-copilot token", () => {
363365
expect(res.token).toBe("fresh;proxy-ep=https://proxy.contoso.test;");
364366
expect(res.baseUrl).toBe("https://api.contoso.test");
365367
expect(saveJsonFile).toHaveBeenCalledTimes(1);
368+
// New cache entry must carry the fingerprint
369+
const savedPayload = saveJsonFile.mock.calls[0][1];
370+
expect(savedPayload.githubTokenFingerprint).toBe(fingerprintGithubToken("gh"));
371+
});
372+
373+
it("bypasses cache when a different github token (profile) is used", async () => {
374+
const now = Date.now();
375+
// Cache was written by profile "gh-user-a"
376+
loadJsonFile.mockReturnValue({
377+
token: "cached-a;proxy-ep=proxy.example.com;",
378+
expiresAt: now + 60 * 60 * 1000,
379+
updatedAt: now,
380+
githubTokenFingerprint: fingerprintGithubToken("gh-user-a"),
381+
});
382+
383+
const fetchImpl = vi.fn().mockResolvedValue({
384+
ok: true,
385+
status: 200,
386+
json: async () => ({
387+
token: "fresh-b;proxy-ep=https://proxy.example.com;",
388+
expires_at: Math.floor(Date.now() / 1000) + 3600,
389+
}),
390+
});
391+
392+
// Request with a different profile token "gh-user-b"
393+
const res = await resolveCopilotApiToken({
394+
githubToken: "gh-user-b",
395+
cachePath,
396+
loadJsonFileImpl: loadJsonFile,
397+
saveJsonFileImpl: saveJsonFile,
398+
fetchImpl: fetchImpl as unknown as typeof fetch,
399+
});
400+
401+
// Must NOT return the cached token from profile A
402+
expect(res.token).toBe("fresh-b;proxy-ep=https://proxy.example.com;");
403+
expect(fetchImpl).toHaveBeenCalledTimes(1);
404+
expect(saveJsonFile).toHaveBeenCalledTimes(1);
405+
// New cache entry should carry profile B's fingerprint
406+
const savedPayload = saveJsonFile.mock.calls[0][1];
407+
expect(savedPayload.githubTokenFingerprint).toBe(fingerprintGithubToken("gh-user-b"));
408+
});
409+
410+
it("bypasses cache when cached entry has no fingerprint (legacy)", async () => {
411+
const now = Date.now();
412+
// Legacy cache without githubTokenFingerprint
413+
loadJsonFile.mockReturnValue({
414+
token: "old-cached;proxy-ep=proxy.example.com;",
415+
expiresAt: now + 60 * 60 * 1000,
416+
updatedAt: now,
417+
});
418+
419+
const fetchImpl = vi.fn().mockResolvedValue({
420+
ok: true,
421+
status: 200,
422+
json: async () => ({
423+
token: "fresh;proxy-ep=https://proxy.contoso.test;",
424+
expires_at: Math.floor(Date.now() / 1000) + 3600,
425+
}),
426+
});
427+
428+
const res = await resolveCopilotApiToken({
429+
githubToken: "gh",
430+
cachePath,
431+
loadJsonFileImpl: loadJsonFile,
432+
saveJsonFileImpl: saveJsonFile,
433+
fetchImpl: fetchImpl as unknown as typeof fetch,
434+
});
435+
436+
// Legacy cache without fingerprint must be treated as a miss
437+
expect(res.token).toBe("fresh;proxy-ep=https://proxy.contoso.test;");
438+
expect(fetchImpl).toHaveBeenCalledTimes(1);
366439
});
367440
});

‎extensions/github-copilot/token.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { createHash } from "node:crypto";
12
import path from "node:path";
23
import { loadJsonFile, saveJsonFile } from "openclaw/plugin-sdk/json-store";
34
import { resolveProviderEndpoint } from "openclaw/plugin-sdk/provider-model-shared";
@@ -16,8 +17,17 @@ export type CachedCopilotToken = {
1617
token: string;
1718
expiresAt: number;
1819
updatedAt: number;
20+
/** SHA-256 fingerprint of the GitHub token used for the exchange.
21+
* When a different profile is selected the fingerprint won't match,
22+
* forcing a fresh token exchange instead of reusing the cached token. */
23+
githubTokenFingerprint?: string;
1924
};
2025

26+
/** Short SHA-256 prefix — enough to detect a different GitHub PAT. */
27+
export function fingerprintGithubToken(githubToken: string): string {
28+
return createHash("sha256").update(githubToken).digest("hex").slice(0, 16);
29+
}
30+
2131
function buildCopilotIdeHeaders(
2232
params: {
2333
includeApiVersion?: boolean;
@@ -127,8 +137,13 @@ export async function resolveCopilotApiToken(params: {
127137
const loadJsonFileFn = params.loadJsonFileImpl ?? loadJsonFile;
128138
const saveJsonFileFn = params.saveJsonFileImpl ?? saveJsonFile;
129139
const cached = loadJsonFileFn(cachePath) as CachedCopilotToken | undefined;
140+
const fingerprint = fingerprintGithubToken(params.githubToken);
130141
if (cached && typeof cached.token === "string" && typeof cached.expiresAt === "number") {
131-
if (isTokenUsable(cached)) {
142+
// Only reuse the cached token when it belongs to the same GitHub account.
143+
// Without this check, profile rotation after a rate-limit would keep
144+
// returning the rate-limited profile's Copilot API token.
145+
const fingerprintMatch = cached.githubTokenFingerprint === fingerprint;
146+
if (fingerprintMatch && isTokenUsable(cached)) {
132147
return {
133148
token: cached.token,
134149
expiresAt: cached.expiresAt,
@@ -157,6 +172,7 @@ export async function resolveCopilotApiToken(params: {
157172
token: json.token,
158173
expiresAt: json.expiresAt,
159174
updatedAt: Date.now(),
175+
githubTokenFingerprint: fingerprint,
160176
};
161177
saveJsonFileFn(cachePath, payload);
162178

‎src/agents/github-copilot-token.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { createHash } from "node:crypto";
12
import path from "node:path";
23
import { resolveStateDir } from "../config/paths.js";
34
import { loadJsonFile, saveJsonFile } from "../infra/json-file.js";
@@ -13,8 +14,17 @@ export type CachedCopilotToken = {
1314
expiresAt: number;
1415
/** milliseconds since epoch */
1516
updatedAt: number;
17+
/** SHA-256 fingerprint of the GitHub token used for the exchange.
18+
* When a different profile is selected the fingerprint won't match,
19+
* forcing a fresh token exchange instead of reusing the cached token. */
20+
githubTokenFingerprint?: string;
1621
};
1722

23+
/** Short SHA-256 prefix — enough to detect a different GitHub PAT. */
24+
export function fingerprintGithubToken(githubToken: string): string {
25+
return createHash("sha256").update(githubToken).digest("hex").slice(0, 16);
26+
}
27+
1828
function resolveCopilotTokenCachePath(env: NodeJS.ProcessEnv = process.env) {
1929
return path.join(resolveStateDir(env), "credentials", "github-copilot.token.json");
2030
}
@@ -120,8 +130,13 @@ export async function resolveCopilotApiToken(params: {
120130
const loadJsonFileFn = params.loadJsonFileImpl ?? loadJsonFile;
121131
const saveJsonFileFn = params.saveJsonFileImpl ?? saveJsonFile;
122132
const cached = loadJsonFileFn(cachePath) as CachedCopilotToken | undefined;
133+
const fingerprint = fingerprintGithubToken(params.githubToken);
123134
if (cached && typeof cached.token === "string" && typeof cached.expiresAt === "number") {
124-
if (isTokenUsable(cached)) {
135+
// Only reuse the cached token when it belongs to the same GitHub account.
136+
// Without this check, profile rotation after a rate-limit would keep
137+
// returning the rate-limited profile's Copilot API token.
138+
const fingerprintMatch = cached.githubTokenFingerprint === fingerprint;
139+
if (fingerprintMatch && isTokenUsable(cached)) {
125140
return {
126141
token: cached.token,
127142
expiresAt: cached.expiresAt,
@@ -150,6 +165,7 @@ export async function resolveCopilotApiToken(params: {
150165
token: json.token,
151166
expiresAt: json.expiresAt,
152167
updatedAt: Date.now(),
168+
githubTokenFingerprint: fingerprint,
153169
};
154170
saveJsonFileFn(cachePath, payload);
155171

0 commit comments

Comments
 (0)