Skip to content

fix(portal): token refresh races with mcp-remote and reports a misleading invalid_grant #199

Closed

Description

@KooshaPari

Summary

scripts/refresh-portal-token.py performs a read → exchange → write cycle on the token cache with no mutual exclusion. Because the Portal authorization server issues single-use, rotating refresh tokens, two concurrent refreshes of the same cache race, and the loser reports a misleading failure.

mcp-remote also refreshes on launch, so the race is reachable in normal use, not just from a manual rerun.

Failure modes

  1. Misleading failure. The loser gets 400 invalid_grant and prints "the cached refresh token was already spent; re-run the consent flow to mint a new one" — which tells the operator to re-consent for what is really a local concurrency bug.
  2. Spent-token cache. If a process read the pair before another rotated it, a later write can leave a spent refresh token on disk while the access token still looks valid. That is exactly the state observed in the cache at the start of the 2026-10-19 session: a spent refresh token paired with a live access token.

Reproduction (controlled, mock rotation server)

A local mock endpoint implementing single-use rotation with a 200 ms window, seeded with an expired access token and RT-1. Four concurrent invocations of the current helper:

Run Result
1 OK: refreshed
2 OK: refreshed
3 FAIL: HTTP 400 (invalid_grant)
4 FAIL: HTTP 400 (invalid_grant)

Half the runs reported the misleading "already spent, re-run the consent flow" message.

Proposed fix

  • Serialise the read/exchange/write cycle with an advisory exclusive flock on <token-path>.lock.
  • Re-read the cache inside the lock, since another process may have rotated it between the first read and lock acquisition.
  • Add --refresh-if-expiring SECONDS so a scheduled or opportunistic caller is a no-op unless the token is actually near expiry. Every refresh consumes a rotation, so unconditional refreshes needlessly widen the race window.

Acceptance

With the same 4-way concurrency against the same mock:

Mode Result
--refresh-if-expiring 600 1 rotation, 3 no-ops, 0 failures
unconditional (worst case) 4 sequential rotations, 0 failures

Activity

  1. added
    kilo-triaged
    on Oct 27, 2026
  2. added a commit that references this issue on Oct 27, 2026
    9d09966
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    kilo-triaged

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions