Skip to content

[vMCP] identityPropagatingRoundTripper captures stale identity, bypassing per-request upstream token refresh #5323

Closed

Description

@tgrunnagle

Summary

identityPropagatingRoundTripper in pkg/vmcp/client/client.go captures the request *auth.Identity once at backend client creation time and re-injects that snapshot on every outgoing backend HTTP request, overriding the fresh identity placed onto the request context by TokenValidator.Middleware moments earlier. This bypasses the transparent upstream-token refresh performed in GetAllValidTokens and results in stale upstream access tokens being injected by UpstreamInjectStrategy / TokenExchangeStrategy for the entire lifetime of the backend client.

Users are observing a forced re-auth roughly every 24 hours. This matches the access-token lifespan of common upstream providers and is consistent with the captured-identity bug rather than with any embedded-auth-server refresh-token expiry (which is configurable up to 30 days and validated to be ≥1h in pkg/authserver/server/provider.go).

Root cause

The bug is a two-path identity flow that doesn't reconnect:

Path A — per-request refresh, works correctly

pkg/auth/token.go:1203 TokenValidator.Middleware runs on every incoming request, including tool calls. It calls loadUpstreamTokens → InProcessService.GetAllValidTokens (pkg/auth/upstreamtoken/service.go:86) which transparently refreshes any expired upstream access tokens via the configured UpstreamTokenRefresher and writes the fresh map into identity.UpstreamTokens. The fresh identity is then attached to the request context via auth.WithIdentity at pkg/auth/token.go:1245.

Path B — captured at session-init, becomes stale

defaultClientFactory in pkg/vmcp/client/client.go:271 constructs the backend client's transport chain at SessionFactory.MakeSession() time. At pkg/vmcp/client/client.go:319-324, the identity is snapshotted once:

identity, _ := auth.IdentityFromContext(ctx)
baseTransport = &identityPropagatingRoundTripper{
    base:          baseTransport,
    identity:      identity,        // captured here, held for session lifetime
    isHealthCheck: healthcontext.IsHealthCheck(ctx),
}

On every subsequent outgoing request, identityPropagatingRoundTripper.RoundTrip at pkg/vmcp/client/client.go:195-207 overrides whatever identity is on the request context with the captured one:

func (i *identityPropagatingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
    ctx := req.Context()
    if i.identity != nil {
        ctx = auth.WithIdentity(ctx, i.identity)   // discards fresh identity from Path A
    }
    ...
}

The downstream auth strategies read identity from the (now overridden) context and inject the captured stale token:

  • pkg/vmcp/auth/strategies/upstream_inject.go:80 — token := identity.UpstreamTokens[providerName]
  • pkg/vmcp/auth/strategies/tokenexchange.go:124 — subjectToken = identity.UpstreamTokens[config.SubjectProviderName]
  • pkg/vmcp/auth/strategies/aws_sts.go:136 — bearerToken = identity.UpstreamTokens[cfg.SubjectProviderName]

So tokens are refreshed at the vMCP edge on every tool call (Path A), then immediately discarded by the backend roundtripper (Path B) before they can be used.

Observed user-facing behavior

  • vMCP session opens; tool calls succeed.
  • Tool calls continue to succeed for ~the upstream provider's access-token lifespan, even though the captured token is never refreshed at the backend layer.
  • Once the captured access token passes its upstream-side expiry, every tool call to that backend starts returning 401 from the upstream API.
  • Users perceive this as needing to re-authenticate. The cadence (~24h) tracks the shortest-lived upstream AT in the session's backend set, not anything ToolHive-configurable.

Why the existing safety nets don't catch this today

This issue is filed separately from #3877 to flag that the Part 1 fix has a concrete user-visible impact (daily forced re-auth) and is worth landing on its own ahead of the rest of #3877's scope.

Suggested fix

Make identityPropagatingRoundTripper source identity from the live request context instead of from a captured field. Sketch:

type identityPropagatingRoundTripper struct {
    base          http.RoundTripper
    isHealthCheck bool
    // identity field removed
}

func (i *identityPropagatingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
    ctx := req.Context()
    // If mcp-go reconstructed this request with context.Background() (as it does
    // for streamable-HTTP Close()), there will be no identity on ctx. In that
    // case we can't recover one — health-check requests don't need it; for
    // session-bound requests the caller is responsible for propagating context.
    if i.isHealthCheck {
        ctx = healthcontext.WithHealthCheckMarker(ctx)
        req = req.Clone(ctx)
    }
    return i.base.RoundTrip(req)
}

Constructor at pkg/vmcp/client/client.go:319-324 drops the identity capture:

baseTransport = &identityPropagatingRoundTripper{
    base:          baseTransport,
    isHealthCheck: healthcontext.IsHealthCheck(ctx),
}

Open question for implementation: the existing comment at pkg/vmcp/client/client.go:314-318 documents that mcp-go's Close() issues a DELETE built from context.Background() which loses identity. The current capture-at-construction behavior was intentional for that path. With the fix, that DELETE will arrive without identity. Two options:

  1. Skip identity injection for the streamable-HTTP DELETE (it's a session-teardown request; upstream auth on a DELETE may not be needed).
  2. Capture only what is strictly needed for teardown (e.g., a token specifically for the DELETE) and inject it only on requests where req.Context() carries no identity. This preserves teardown while letting normal requests use the fresh per-request identity.

Whichever path is chosen, the invariant must be: a non-nil identity in req.Context() is never silently overridden by a captured one.

Reproduction

  1. Configure a vMCP with one or more MCPServerEntry backends using upstreamInject outgoing auth, against an upstream IDP whose access tokens expire in less than 24 hours (most providers default to 1h–24h).
  2. Authenticate through vMCP from an MCP client and exercise a tool against the upstream backend (succeeds).
  3. Keep the session open and idle past the upstream's access-token lifespan. Do not restart the client or close the session.
  4. Make another tool call to the same backend. Expected: vMCP refreshes the upstream token transparently and the call succeeds. Actual: the captured AT is used; the upstream returns 401; the call fails.

A targeted unit test on identityPropagatingRoundTripper.RoundTrip should assert that an identity placed on req.Context() is preserved into the outgoing request and is not replaced by a different identity captured at construction time.

Acceptance criteria

  • identityPropagatingRoundTripper no longer holds a captured *auth.Identity field, OR if it does, that field is never used to override an identity already present on req.Context().
  • A fresh identity placed on req.Context() by TokenValidator.Middleware reaches UpstreamInjectStrategy.Authenticate / TokenExchangeStrategy.Authenticate / AWSSTSStrategy.Authenticate unchanged.
  • The streamable-HTTP Close()/DELETE path (where mcp-go uses context.Background()) continues to function without panicking or erroring on missing identity.
  • Unit tests cover: (a) identity present in req.Context() is propagated, (b) identity absent in req.Context() is handled gracefully for the DELETE/teardown path, (c) isHealthCheck marker behavior is preserved.
  • Integration test that idles a vMCP session past the upstream AT lifespan and asserts the next tool call succeeds via transparent refresh.

Related

Metadata

Metadata

Assignees

Labels

authenticationbuggovmcp

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions