Skip to content

fix: make Copilot API token cache per-profile for effective rotation (closes #43658) - #46229

Closed
Br1an67 wants to merge 1 commit into
openclaw:mainfrom
Br1an67:fix/43658
Closed

Br1an67 wants to merge 1 commit into
openclaw:mainfrom
Br1an67:fix/43658

Conversation

@Br1an67

@Br1an67 Br1an67 commented Mar 14, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Problem: All GitHub Copilot auth profiles share one cached API token, making rotation ineffective
  • Why it matters: Rate limit on one profile blocks all profiles
  • What changed: Token cache now keyed per-profile so different PATs get separate tokens
  • What did NOT change: Single-profile usage, token refresh logic

Change Type

  • Bug fix

Scope

  • Auth/Provider

Linked Issue/PR

Security Impact

  • New permissions/capabilities? No
  • Secrets/tokens handling changed? Yes — cache files are now per-profile
  • New/changed network calls? No
  • Command/tool execution surface changed? No
  • Data access scope changed? No

Evidence

  • pnpm build + pnpm check + pnpm test all passing

Compatibility / Migration

  • Backward compatible? Yes — old single cache file is still valid for single-profile
  • Migration needed? No — old cache will be refreshed on next token exchange

Failure Recovery

  • How to revert: revert this commit, delete per-profile cache files

This PR was AI-assisted (fully tested with pnpm build/check/test).

@greptile-apps

greptile-apps Bot commented Mar 14, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes the Copilot API token cache so that each GitHub PAT gets its own cache file (named with a short SHA-256 prefix of the token), preventing one profile's cached token from being served to a different profile and making rate-limit rotation actually effective. An in-file githubTokenHash field is also added as a secondary guard, and backward compatibility with cache files written before this change is preserved via a !cached.githubTokenHash short-circuit.

Key observations:

  • The per-profile filename strategy (github-copilot.token.<hash>.json) is the correct primary fix and is well-implemented.
  • The comment at the hashMatches check (line 114) incorrectly claims the check is skipped for custom cachePath callers; it is actually enforced for all paths when a hash is present. The accompanying test explicitly verifies the stricter behavior, so the comment should be updated to match the code.
  • The 12-character hex truncation (48 bits) is fine for personal use but could cause hash collisions in high-throughput or enterprise scenarios. A modest increase to 16 chars would provide a meaningful safety margin at no practical cost.
  • Old single-profile cache files (github-copilot.token.json) are left on disk unused — this is harmless and intentional per the PR description.
  • Tests cover hash storage on write, cache rejection on mismatch, and hash determinism. No tests exercise the new per-profile filename path directly (they all inject cachePath), but the filename logic is simple enough that this is an acceptable gap.

Confidence Score: 4/5

  • PR is safe to merge; the two flagged items are style/documentation issues and do not affect correctness for typical usage.
  • The core fix (per-profile cache filename) is correct and backward-compatible. The in-file hash guard works as intended despite a misleading comment. The 12-char hash truncation is a minor concern that only matters at fleet scale. No logic errors or security regressions were found.
  • No files require special attention beyond the two style issues already called out in src/providers/github-copilot-token.ts.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/providers/github-copilot-token.ts
Line: 113-117

Comment:
**Comment contradicts actual code behavior**

The comment on line 114 says the hash check is "only enforce[d] for the default (auto-resolved) path", implying it is skipped when a custom `cachePath` is supplied. But the expression on line 116 applies equally to both custom and default paths — if a cached file contains a `githubTokenHash` that does not match the current profile's token, the cache is always rejected, regardless of whether `cachePath` was explicitly provided.

In practice this stricter behavior is arguably more correct (the test "rejects cache when githubTokenHash does not match current profile" explicitly passes a custom `cachePath` and still expects rejection). The comment should be updated to reflect what the code actually does:

```suggestion
  // Accept the cached token only when it belongs to the same profile.  A
  // missing hash (legacy cache written before this change) is treated as a
  // match so that existing single-profile users are not forced to re-fetch.
  const hashMatches = !cached.githubTokenHash || cached.githubTokenHash === tokenHash;
```

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: src/providers/github-copilot-token.ts
Line: 22-24

Comment:
**Short hash increases collision probability**

Only the first 12 hex characters (48 bits) of the SHA-256 digest are kept. Birthday-paradox probability of a collision reaches ~1 % around ~22 million distinct tokens, which is fine for personal use today. However, for fleet-scale or enterprise deployments where hundreds of distinct PATs may be cycled, two profiles could silently share the same cache file and serve each other's tokens.

If the goal is simply a "filesystem-safe" suffix, using 16 or even 20 hex chars (64–80 bits) would still be very short while pushing the collision risk well below practical concern:

```suggestion
  return createHash("sha256").update(githubToken).digest("hex").slice(0, 16);
```

How can I resolve this? If you propose a fix, please make it concise.

Last reviewed commit: 06ccb39

Comment on lines 113 to +117
if (cached && typeof cached.token === "string" && typeof cached.expiresAt === "number") {
if (isTokenUsable(cached)) {
// When a custom cachePath is provided the caller manages isolation, so we
// only enforce the hash check for the default (auto-resolved) path.
const hashMatches = !cached.githubTokenHash || cached.githubTokenHash === tokenHash;
if (hashMatches && isTokenUsable(cached)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment contradicts actual code behavior

The comment on line 114 says the hash check is "only enforce[d] for the default (auto-resolved) path", implying it is skipped when a custom cachePath is supplied. But the expression on line 116 applies equally to both custom and default paths — if a cached file contains a githubTokenHash that does not match the current profile's token, the cache is always rejected, regardless of whether cachePath was explicitly provided.

In practice this stricter behavior is arguably more correct (the test "rejects cache when githubTokenHash does not match current profile" explicitly passes a custom cachePath and still expects rejection). The comment should be updated to reflect what the code actually does:

Suggested change
if (cached && typeof cached.token === "string" && typeof cached.expiresAt === "number") {
if (isTokenUsable(cached)) {
// When a custom cachePath is provided the caller manages isolation, so we
// only enforce the hash check for the default (auto-resolved) path.
const hashMatches = !cached.githubTokenHash || cached.githubTokenHash === tokenHash;
if (hashMatches && isTokenUsable(cached)) {
// Accept the cached token only when it belongs to the same profile. A
// missing hash (legacy cache written before this change) is treated as a
// match so that existing single-profile users are not forced to re-fetch.
const hashMatches = !cached.githubTokenHash || cached.githubTokenHash === tokenHash;
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/providers/github-copilot-token.ts
Line: 113-117

Comment:
**Comment contradicts actual code behavior**

The comment on line 114 says the hash check is "only enforce[d] for the default (auto-resolved) path", implying it is skipped when a custom `cachePath` is supplied. But the expression on line 116 applies equally to both custom and default paths — if a cached file contains a `githubTokenHash` that does not match the current profile's token, the cache is always rejected, regardless of whether `cachePath` was explicitly provided.

In practice this stricter behavior is arguably more correct (the test "rejects cache when githubTokenHash does not match current profile" explicitly passes a custom `cachePath` and still expects rejection). The comment should be updated to reflect what the code actually does:

```suggestion
  // Accept the cached token only when it belongs to the same profile.  A
  // missing hash (legacy cache written before this change) is treated as a
  // match so that existing single-profile users are not forced to re-fetch.
  const hashMatches = !cached.githubTokenHash || cached.githubTokenHash === tokenHash;
```

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines +22 to +24
export function hashGithubToken(githubToken: string): string {
return createHash("sha256").update(githubToken).digest("hex").slice(0, 12);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Short hash increases collision probability

Only the first 12 hex characters (48 bits) of the SHA-256 digest are kept. Birthday-paradox probability of a collision reaches ~1 % around ~22 million distinct tokens, which is fine for personal use today. However, for fleet-scale or enterprise deployments where hundreds of distinct PATs may be cycled, two profiles could silently share the same cache file and serve each other's tokens.

If the goal is simply a "filesystem-safe" suffix, using 16 or even 20 hex chars (64–80 bits) would still be very short while pushing the collision risk well below practical concern:

Suggested change
export function hashGithubToken(githubToken: string): string {
return createHash("sha256").update(githubToken).digest("hex").slice(0, 12);
}
return createHash("sha256").update(githubToken).digest("hex").slice(0, 16);
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/providers/github-copilot-token.ts
Line: 22-24

Comment:
**Short hash increases collision probability**

Only the first 12 hex characters (48 bits) of the SHA-256 digest are kept. Birthday-paradox probability of a collision reaches ~1 % around ~22 million distinct tokens, which is fine for personal use today. However, for fleet-scale or enterprise deployments where hundreds of distinct PATs may be cycled, two profiles could silently share the same cache file and serve each other's tokens.

If the goal is simply a "filesystem-safe" suffix, using 16 or even 20 hex chars (64–80 bits) would still be very short while pushing the collision risk well below practical concern:

```suggestion
  return createHash("sha256").update(githubToken).digest("hex").slice(0, 16);
```

How can I resolve this? If you propose a fix, please make it concise.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 06ccb390b3

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +108 to +109
const cachePath =
params.cachePath?.trim() || resolveCopilotTokenCachePath(params.githubToken, env);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Fall back to legacy Copilot cache file before fetching

resolveCopilotApiToken now resolves only the new hashed cache filename, so upgrades stop reading previously persisted tokens from credentials/github-copilot.token.json. In a common migration case (single-profile user with a still-valid old cache but no network/GitHub outage), this forces a token exchange and fails instead of using the cached token that worked before, which is a functional regression introduced by the new path logic.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 562b6ebb1c

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/providers/github-copilot-token.ts Outdated
Comment on lines +133 to +134
const legacyHashMatches = !legacyCached.githubTokenHash || legacyCached.githubTokenHash === tokenHash;
if (legacyHashMatches && isTokenUsable(legacyCached)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reject unscoped legacy cache during profile migration

When legacyCached.githubTokenHash is missing (the normal pre-migration case), the fallback path treats it as a match for any current PAT and immediately migrates that token into the new per-profile cache. In an upgrade scenario with PAT rotation or multiple Copilot profiles, this copies profile A’s still-valid API token into profile B’s hashed cache, so B keeps using A’s token until expiry and rotation/failover remains ineffective during that window. The migration should avoid reusing unscoped legacy entries across different PATs (for example by marking/locking legacy ownership on first migration or forcing a fetch when scope is unknown).

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f574160761

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/providers/github-copilot-token.ts Outdated
typeof legacyCached.expiresAt === "number"
) {
const legacyHashMatches =
!legacyCached.githubTokenHash || legacyCached.githubTokenHash === tokenHash;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Refuse hashless legacy token during profile migration

The legacy fallback treats a missing githubTokenHash as a match, so an unscoped credentials/github-copilot.token.json entry can be migrated into any new per-profile cache file. After upgrade, if profile A populated the legacy cache and profile B is used next (or PATs were rotated), profile B can incorrectly reuse A’s Copilot API token until expiry, which defeats the per-profile isolation this change is meant to provide and can keep failover/rate-limit recovery broken for that window.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5a9becd70a

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/providers/github-copilot-token.ts Outdated
Comment on lines +141 to +142
const legacyHashMatches = legacyCached.githubTokenHash === tokenHash;
if (legacyHashMatches && isTokenUsable(legacyCached)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Accept hashless legacy cache on first migration

The legacy fallback is currently ineffective for real pre-migration caches because legacyHashMatches requires legacyCached.githubTokenHash === tokenHash, but older github-copilot.token.json entries were written without githubTokenHash. In an upgrade where only the legacy cache exists (especially during GitHub outages/offline runs), this path always skips the cached token and forces a network exchange, regressing previously working cached-auth behavior despite the new "smooth upgrades" fallback.

Useful? React with 👍 / 👎.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: M and removed size: S labels Mar 15, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b79cd4c6a4

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +71 to +74
id === defaultSlotIdForKey("contextEngine") &&
normalizedOwner !== CORE_CONTEXT_ENGINE_OWNER
) {
return { ok: false, existingOwner: CORE_CONTEXT_ENGINE_OWNER };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P0 Badge Allow registering the default context engine

This new ownership guard rejects legacy registrations from any owner except core, but the only public registration path still used by registerLegacyContextEngine() is registerContextEngine(), which hardcodes owner public-sdk; that means ensureContextEnginesInitialized() no longer registers the default engine, and resolveContextEngine() will throw for default contextEngine configs in normal run/compact/subagent flows instead of starting with the legacy engine.

Useful? React with 👍 / 👎.

@Br1an67

Br1an67 commented Mar 17, 2026

Copy link
Copy Markdown
Contributor Author

Closing to manage active PR count. Will reopen when slot is available.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

GitHub Copilot auth profile rotation ineffective — all profiles share single cached API token

1 participant