Skip to content

Make the token refresh code reusable for vMCP and testable - #4117

Merged
jhrozek merged 4 commits into
mainfrom
upstream-refresh/token-service
Mar 12, 2026
Merged

jhrozek merged 4 commits into
mainfrom
upstream-refresh/token-service

Conversation

@jhrozek

@jhrozek jhrozek commented Mar 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR refactors the in-middleware refresh into an UpstreamTokenService that transparently refreshes expired upstream access tokens on behalf of the user, so MCP sessions survive beyond the upstream IDP's token lifespan.

Commits

  1. Add upstreamtoken package for upstream token lifecycle — Introduces a reusable upstreamtoken.Service interface that encapsulates read → validate expiry → refresh → dedup behind a single GetValidTokens call. Designed for reuse by vMCP.

  2. Wire UpstreamTokenService into runner and middleware — Simplifies the MiddlewareRunner interface from two storage-level accessors to a single GetUpstreamTokenService. The upstreamswap middleware now consumes the Service interface directly instead of composing storage and refresher itself.

  3. Simplify runner startup with eager service initialization — Reorders Run() to initialize the embedded auth server before middleware creation, eliminating the lazy accessor with mutex and caching. The service is now a simple field read.

  4. Fail closed when upstream token service is unavailable — When a request carries a tsid claim (meaning it expects upstream token injection), the previous behavior passed it through with the original JWT, leaking the auth server token to the backend. Now returns 503 instead.

Tested end-to-end against a live Okta instance in a kind cluster. The ToolHive proxy was exposed via ngrok to avoid port-forward instability, and VS Code was used as the MCP client to exercise the real-world OAuth flow (dynamic client registration, PKCE, browser login).

After authenticating through Okta, the proxy successfully obtained upstream tokens including a refresh token. The Okta authorization server was configured with a 5-minute access token lifespan. Once the upstream AT expired, the next MCP tool call from VS Code triggered a transparent refresh — the UpstreamTokenService detected the expiry, used singleflight-deduplicated refresh via Okta's token endpoint, stored the new tokens, and injected the fresh AT into the proxied request. The tool call succeeded with no 401 and no re-authentication prompt. Subsequent requests used the refreshed token with a full 5-minute TTL.

Does this introduce a user-facing change?

No. This is transparent to MCP clients — sessions that previously broke after the upstream AT expired now continue working silently.

Special notes for reviewers

  • The upstreamtoken package is intentionally designed as a standalone service (not embedded in middleware) so vMCP can reuse it for the same refresh logic without depending on the middleware layer.

Fixes: #3914
Fixes: #3915
Fixes: #3916
Fixes: #3917

Large PR Justification

  • Large refactoring that must be atomic

jhrozek and others added 4 commits March 12, 2026 09:17
Introduce a reusable upstreamtoken.Service interface that encapsulates
the upstream token lifecycle (read, validate expiry, refresh, dedup)
behind a single GetValidTokens call. This is designed for reuse by
vMCP, which needs the same refresh logic without depending on the
middleware layer.

InProcessService composes UpstreamTokenStorage + UpstreamTokenRefresher
with singleflight deduplication to prevent concurrent refresh attempts
from exhausting single-use refresh tokens.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Simplify the MiddlewareRunner interface from two storage-level accessors
(GetUpstreamTokenStorage, GetUpstreamTokenRefresher) to a single
service-level accessor (GetUpstreamTokenService). The upstreamswap
middleware now consumes the Service interface directly, removing its
responsibility for composing storage and refresher components.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Reorder Run() to initialize the embedded auth server before middleware
creation, eliminating the need for lazy accessor with mutex and caching
in GetUpstreamTokenService(). The service is now created eagerly and
stored as a field, making the accessor a simple field read.

Also deduplicate the createMinimalAuthServerConfig test helper, add
UpstreamTokenRefresher to the go:generate directive, and update the
middleware documentation to reflect the new interface method.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
When a request carries a tsid claim (confirming it expects upstream
token injection), passing through with the original JWT would leak
the auth server token to the backend. Return 503 instead of
forwarding the request when the token service is nil.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@jhrozek
jhrozek requested a review from tgrunnagle March 12, 2026 10:28
@github-actions github-actions Bot added the size/XL Extra large PR: 1000+ lines changed label Mar 12, 2026

@github-actions github-actions 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.

Large PR Detected

This PR exceeds 1000 lines of changes and requires justification before it can be reviewed.

How to unblock this PR:

Add a section to your PR description with the following format:

## Large PR Justification

[Explain why this PR must be large, such as:]
- Generated code that cannot be split
- Large refactoring that must be atomic
- Multiple related changes that would break if separated
- Migration or data transformation

Alternative:

Consider splitting this PR into smaller, focused changes (< 1000 lines each) for easier review and reduced risk.

See our Contributing Guidelines for more details.


This review will be automatically dismissed once you add the justification section.

@codecov

codecov Bot commented Mar 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 77.92208% with 17 lines in your changes missing coverage. Please review.
✅ Project coverage is 68.87%. Comparing base (cf8b6fa) to head (27644a8).
⚠️ Report is 7 commits behind head on main.

Files with missing lines Patch % Lines
pkg/runner/runner.go 16.66% 14 Missing and 1 partial ⚠️
pkg/auth/upstreamtoken/service.go 95.23% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4117      +/-   ##
==========================================
+ Coverage   68.84%   68.87%   +0.02%     
==========================================
  Files         458      459       +1     
  Lines       46274    46267       -7     
==========================================
+ Hits        31859    31866       +7     
+ Misses      11953    11941      -12     
+ Partials     2462     2460       -2     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@jhrozek jhrozek changed the title Upstream refresh/token service Make the token refresh code reusable for vMCP and testable Mar 12, 2026

@tgrunnagle tgrunnagle left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Couple non-blocking comments. Looks great!

Comment thread pkg/auth/upstreamswap/middleware.go Resolved
Comment thread pkg/auth/upstreamtoken/service.go Resolved
@jhrozek
jhrozek dismissed github-actions[bot]’s stale review March 12, 2026 22:37

I added the required paragraph but the nack didn't go away

@jhrozek
jhrozek merged commit 5c68911 into main Mar 12, 2026
52 of 53 checks passed
@jhrozek
jhrozek deleted the upstream-refresh/token-service branch March 12, 2026 22:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/XL Extra large PR: 1000+ lines changed

Projects

None yet

2 participants