Skip to content

fix(auth): avoid refreshing short-lived access tokens on every call - #1450

Merged
DaleSeo merged 5 commits into
modelcontextprotocol:mainfrom
figitaki:monad/fix-short-lived-token-refresh
Nov 17, 2026
Merged

DaleSeo merged 5 commits into
modelcontextprotocol:mainfrom
figitaki:monad/fix-short-lived-token-refresh

Conversation

@figitaki

@figitaki figitaki commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1442

Problem

get_access_token refreshes whenever remaining < 30s. Tokens with expires_in <= 30s are always inside the window, so every call triggers a refresh (and a rotated refresh token each time).

Change

  • Buffer is now min(REFRESH_BUFFER_SECS, expires_in / 2), as agreed in the issue.
  • Added remaining == 0 so expired tokens with expires_in <= 1 (buffer 0) still refresh/re-auth instead of being returned forever.

Tests (all in auth::tests)

  • 20s token received now: returned without refresh.
  • 20s token, age 11s (unexpired, inside the half-lifetime buffer): re-auth/refresh attempted.
  • 20s token received 25s ago: requires_reauth.
  • 1s token received 5s ago: requires_reauth (covers the remaining == 0 clause).
  • axum mock /token endpoint issuing 20s tokens with a hit counter: two get_access_token calls result in exactly one token request. Also covers the 1s zero-buffer case.

Existing long-lived token tests are unchanged.

Validation

  • Local (rustc 1.96): cargo test -p rmcp --lib --all-features -- auth:: gives 306 passed, 0 failed; just fix and cargo clippy --all-targets --all-features -- -D warnings are clean.
  • Red/green: against the original condition the new tests fail (2 failures: 2 token hits instead of 1, and AuthorizationRequired for a fresh short-lived token); with only the capped buffer and no remaining == 0 clause the 1s guard tests fail.
  • Remote: upstream workflows await first-time-contributor approval, so CI was run on a fork PR at head 2a91f92: CI and Conformance green (CI validation for upstream #1450 figitaki/rmcp#1).

@github-actions github-actions Bot added T-core Core library changes T-transport Transport layer changes labels Nov 13, 2026
@github-actions
github-actions Bot requested a review from jokemanfire November 13, 2026 08:44
@github-actions

Copy link
Copy Markdown
Contributor

@jokemanfire is on triage rotation this week and is the reviewer for this one.

Labels come from the PR labeler. Please review the change.

Automated triage. Labels are a first pass and the assigned maintainer has the final say.

@figitaki
figitaki marked this pull request as ready for review November 13, 2026 08:51
@figitaki
figitaki requested a review from a team as a code owner November 13, 2026 08:51
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-16T03:11:48.285034Z 5d7016f New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@figitaki
figitaki marked this pull request as draft November 13, 2026 08:52
@figitaki
figitaki marked this pull request as ready for review November 13, 2026 09:01

@ratomirjovanovic ratomirjovanovic left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Matches what we settled on in #1442, and the remaining == 0 clause covers the 1s case. I checked the counting /token test against refresh_token(), which saves token_received_at as now, so the second call sees a fresh 20s token and skips the refresh as expected. One small non-blocking thing: the doc on REFRESH_BUFFER_SECS still says tokens are refreshed this many seconds before they expire, which is now only the upper bound.

@jokemanfire jokemanfire left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Independently checked at 2a91f92 (not by reading the description): cargo test -p rmcp --lib --features "auth client reqwest" -- auth::tests::get_access_token -> 13 passed, 0 failed, including the mock /token counter test (hits == 1 after two calls) and both 1s-token cases.

The arithmetic holds for every band I tried:

  • expires_in = 20: buffer 10, token age 0..9 -> returned, age 10 -> remaining == buffer -> still returned (strict <), age 11+ -> refresh/reauth.
  • expires_in = 1: buffer 0, so the remaining == 0 clause is what prevents an expired token from being returned forever - that clause is load-bearing, not redundant.
  • expires_in >= 60: buffer stays 30, so long-lived behaviour is unchanged.

Two small things, neither blocking:

  1. remaining < buffer || remaining == 0 is exactly remaining < buffer.max(1). Using that form makes the "buffer can be zero" case self-evident and removes the double condition; the comment above it already explains why half the lifetime is the cap.

  2. The equality boundary is untested. remaining == buffer must not refresh, and that strict comparison is the same off-by-one family as the original bug. The four new tests sit at 0, 11 and 25 seconds (and 0/1 for the 1s token), so a future <= would keep them all green. One extra case - 20s token, age 10 (remaining == buffer) -> returned without refresh - pins it. expires_in = 2 (buffer 1) would additionally cover the truncating division, if you want the full matrix.

@figitaki

Copy link
Copy Markdown
Contributor Author

Thanks both. Pushed 8727294:

  • switched to remaining < buffer.max(1) (equivalent to the || remaining == 0 form for u64, and simpler)
  • updated the REFRESH_BUFFER_SECS doc to describe it as the upper bound
  • added the equality-boundary case (20s token at age 10 is not refreshed) and an expires_in = 2 case, covering ages 0, 1, and 2

@ratomirjovanovic thanks for the diagnosis and the fix direction in #1442. This is your approach plus @jokemanfire's zero-buffer clause.

Upstream CI is waiting on workflow approval for a first-time contributor, whenever someone has a moment.

(Changes drafted with AI assistance; tests run locally: 275 auth library tests passed, and clippy was clean.)

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

Copy link
Copy Markdown

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: 8727294636

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".


#[tokio::test]
async fn get_access_token_returns_short_lived_token_at_half_lifetime_boundary() {
let manager = short_lived_token_manager(20, 10).await;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Decouple boundary tests from the wall clock

When the wall clock crosses an epoch-second boundary after short_lived_token_manager(20, 10) records now - 10 but before get_access_token samples now, the token's computed age becomes 11 and this assertion gets AuthorizationRequired instead of the token. The age-1 branch of the two-second test below has the same race, so busy CI can fail nondeterministically; freeze or inject the clock, or exercise the boundary calculation without elapsed real time.

Useful? React with 👍 / 👎.

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

Copy link
Copy Markdown

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: 0f839cda9e

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread crates/rmcp/src/transport/auth.rs Outdated
/// Transient refresh failures return [`AuthError::TokenRefreshFailed`] so the
/// caller can retry; other errors are propagated as-is.
pub async fn get_access_token(&self) -> Result<String, AuthError> {
self.get_access_token_at(Self::now_epoch_secs()).await

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Sample the clock after loading credentials

When an async credential backend is delayed, this snapshots now before get_access_token_at awaits credential_store.load(), so the token can cross its refresh or expiration boundary during that await while the calculation still uses the stale timestamp. For a 1- or 2-second token, or a slow keychain/database store, this can return an already expired bearer token instead of refreshing it; keep the production clock read after the load and inject only the expiry calculation for tests.

Useful? React with 👍 / 👎.

@jokemanfire

Copy link
Copy Markdown
Member

just fix the lint

@figitaki
figitaki force-pushed the monad/fix-short-lived-token-refresh branch 2 times, most recently from 6a6d7b9 to bb59d1c Compare November 15, 2026 23:40
figitaki and others added 4 commits November 15, 2026 15:46
Co-authored-by: Turnkey <noreply@turnkey.com>
Co-authored-by: Claude <noreply@anthropic.com>
…short-lived tokens

Co-authored-by: Turnkey <noreply@turnkey.com>
Co-authored-by: Claude <noreply@anthropic.com>
…undaries

Document REFRESH_BUFFER_SECS as an upper bound on the proactive refresh
buffer, express the refresh condition as remaining < buffer.max(1), and
add tests for the half-lifetime boundary and a two-second token at ages
0, 1, and 2.

Co-authored-by: Turnkey <noreply@turnkey.com>
Co-authored-by: Claude <noreply@anthropic.com>
…an injected clock

Co-authored-by: Turnkey <noreply@turnkey.com>
Co-authored-by: Claude <noreply@anthropic.com>
@figitaki
figitaki force-pushed the monad/fix-short-lived-token-refresh branch from bb59d1c to 505490a Compare November 15, 2026 23:46
@figitaki

Copy link
Copy Markdown
Contributor Author

@jokemanfire fixed: the lint failure was commitlint's 100-character limit on commit-body lines, hit by one commit message. I rewrapped that message (no code changes) and re-signed the branch; the head is now 505490a. The workflows may need approval to run again.

Defer clock evaluation until credential loading completes so a slow store
cannot return a short-lived token that crossed its refresh boundary.
Cover expiry and half-lifetime boundaries with a deterministic advancing clock.

Co-authored-by: Turnkey <noreply@turnkey.com>
Co-authored-by: Claude <noreply@anthropic.com>

@jokemanfire jokemanfire left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verified at 5d7016f, by running the code rather than reading the description.

What I ran

cargo test -p rmcp --lib --features "auth client reqwest" -- auth::tests
  -> 260 passed, 0 failed
cargo test ... -- auth::tests::get_access_token
  -> 16 passed, 0 failed (includes the new `get_access_token_samples_clock_after_credential_load`)
cargo fmt --check -p rmcp  -> clean

Note: no CI ran on this PR (the only check is Assign labels), so everything here is local evidence at the head SHA.

Mutation, to show the new test bites

Sampled the clock at function entry and reused it for the age calculation (i.e. reverted to the pre-5d7016f behaviour):

let sampled_at_entry = now_epoch_secs();
let stored = self.credential_store.load().await?;
...
let elapsed = sampled_at_entry.saturating_sub(received_at);

get_access_token_samples_clock_after_credential_load FAILED with

lifetime=1, age before=0, age after=1: Ok("short-lived")

That is the exact bug the commit claims to fix: a 1s token that expired while the store was loading was returned as a valid bearer. Restored the file, suite green again (260 passed).

What else I checked by hand

  • now_epoch_secs is now impl FnOnce() -> u64 + Send and is consumed after credential_store.load(), inside the if let (Some(expires_in), Some(received_at)) arm — so the clock is only sampled when it is actually used, and a store that errors never runs it.
  • get_access_token_at was private and is now #[cfg(test)]; no public API surface changed (cargo test and the crate's own Public API Check job would have caught that if it had run).
  • remaining < buffer.max(1) is unchanged, so the 1s-token case from #1442 still behaves as agreed (returned at age 0, refreshed at age 1).
  • Both earlier Codex findings are addressed: the wall-clock flakiness one by moving the boundary tests to get_access_token_at(SHORT_LIVED_NOW), and the stale-clock one by this commit.

One non-blocking nit

ClockAdvancingStore::save / clear use unreachable!(). If a later change made the refresh path reachable from this test, the failure would surface as a worker-task panic rather than a readable assertion. panic!("these credentials have no refresh token") says what happened; optional.

@DaleSeo
DaleSeo merged commit 33ca325 into modelcontextprotocol:main Nov 17, 2026
24 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

T-core Core library changes T-transport Transport layer changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

auth: tokens that live 30s or less are refreshed on every request

4 participants