Skip to content

Cached upstream DCR registration never recovers after the upstream evicts it #6821

Closed

Description

@peppescg

Bug description

When an embedded auth server uses Dynamic Client Registration (DCR) against an upstream that is itself a ToolHive auth server, the downstream keeps its cached registration forever, while the upstream deletes it after 30 days without a token exchange. After that, every authorization the downstream starts is rejected by the upstream with invalid_client, and nothing recovers on its own.

The two sides disagree about the registration's lifetime:

  • Upstream (server side). DCR-issued clients are stored with DefaultDCRClientTTL (30 days, pkg/authserver/storage/config.go). The TTL is renewed only by a successful token exchange or refresh (RenewClientTTL in pkg/authserver/server/handlers/token.go). The registration response still advertises client_secret_expires_at: 0 ("does not expire", pkg/authserver/server/handlers/dcr.go), which is deliberate.
  • Downstream (client side). pkg/auth/dcr persists the resolution and, on a cache hit, returns it without any network I/O. The only invalidation signal is client_secret_expires_at (lookupCachedResolution), which is 0 here. The 90-day dcrStaleAgeThreshold only logs a warning.

So an idle registration is evicted upstream but kept downstream. The same happens if the upstream loses its client storage for any other reason (for example, a Redis/Valkey wipe or a restore).

The browser is the only party that sees the error: /oauth/authorize on the upstream renders it directly. The downstream never sees it, so it can't react, and it presents the same dead client_id on every attempt. The only workaround today is to delete the cached DCR row from the downstream's storage by hand and restart.

Steps to reproduce

  1. Run auth server A (the upstream) with Redis storage and DCR enabled.
  2. Run embedded auth server B (the downstream) with Redis storage and an OAuth2 upstream pointing at A through dcr_config (discovery_url). On boot, B registers on A and caches the client.
  3. Start an authorization through B: A accepts the client and shows its consent page.
  4. Let A's Redis advance past DefaultDCRClientTTL without any token exchange for that client (or delete the client from A's storage).
  5. Restart B against the same Redis and start a new authorization through B.

A self-contained integration test reproduces this with two in-process auth servers and miniredis (FastForward past the TTL). It will be included in the fix PR.

Expected behavior

After the upstream has dropped the registration, the downstream detects it and registers a new client. Authorizations work again without manual intervention.

Actual behavior

B reuses the cached client_id and redirects the browser to A, which answers:

{"error":"invalid_client","error_description":"Client authentication failed (e.g., unknown client, no client authentication included, or unsupported authentication method). The requested OAuth 2.0 Client does not exist."}

This repeats on every attempt and survives restarts of B.

Environment (if relevant)

  • ToolHive version: main at 5220a0a (also present in v0.50.0 – v0.53.0)

Additional context

Proposed fix, client side in pkg/auth/dcr:

  • Validate on cache hit. On a cache hit, send one token-endpoint request with the cached client credentials and a deliberately invalid authorization code. Token endpoints authenticate the client before they validate the grant (RFC 6749 §5.2; fosite's NewAccessRequest does this too), so:
    • invalid_client means the registration is gone;
    • invalid_grant means the registration is alive;
    • anything else (5xx, network error, a non-OAuth error) is inconclusive, and the cached registration is kept so boot is never blocked.
  • Replace the stale row. On invalid_client, re-register and replace the stale row with UpdateDCRCredentialsIfUnchanged (Add compare-and-set update for DCR credentials #6758), so concurrent replicas converge on one registration.

Limitation: the resolver runs only when the auth server is constructed, so this recovers at the next restart, not while the process is running.

Activity

  1. self-assigned this
    on Oct 14, 2026
  2. added
    bug
    on Oct 14, 2026
  3. added
    needs-triage
    on Oct 14, 2026
  4. aron-muon commented on Oct 14, 2026

    @aron-muon
    Contributor

    We hit this in production with a third-party upstream rather than a second
    ToolHive auth server, and it adds two data points to the report.

    Field evidence. Two MCPRemoteProxy deployments (staging and production
    clusters, separate Redis stores) register with the same vendor authorization
    server through dcrConfig.registrationEndpoint. The vendor issues public
    clients only (token_endpoint_auth_methods_supported: ["none"]), so every
    registration response carries client_secret_expires_at: 0 and the only
    invalidation rule in lookupCachedResolution never fires. The vendor purged
    its registered-client store twice in three weeks (once before Sept 24, once
    between Oct 7 and Oct 12). Each time, every proxy start logged
    dcr: cache hit with the dead client_id (dcr_age_days 49 and 12
    respectively) and the browser got the vendor's unknown-client error on
    /authorize; the proxies never saw it. Recovery was the manual path the issue
    describes: delete the dcr: row in Redis and restart the pods. The ages at
    death (about 30 days and under 12 days) show this was not a TTL on the
    vendor's side but a wipe, so no client-side age heuristic alone would have
    predicted it.

    The token-endpoint probe is a false negative for this vendor. Its token
    endpoint validates the grant before the client: redeeming a bogus code with the
    purged client_id, with the live one, and with a made-up one all return
    400 {"error": "invalid_grant", "error_description": "Invalid authorization code"}.
    #6822 would read that as "registration alive" and keep the dead row. With
    token_endpoint_auth_method: none there is nothing for the endpoint to
    authenticate, so this is probably common among public-client-only upstreams.
    Here only the authorization endpoint tells the two apart (302 to the vendor's
    login for a known client, a 400 invalid_request about the redirect URI for an
    unknown one), and that text is vendor-specific.

    A complementary operator-driven knob. Two situations still need a
    deliberate rotation with no Redis surgery:

    1. an upstream like the one above, where the probe cannot tell, and
    2. a rotation the operator wants on request (compromise response, vendor
      asked us to re-register, migration between vendor tenants).

    PR #6825 adds dcrConfig.rotationKey, an optional operator-chosen label that
    is folded into the DCR cache key (DCRKey, redisDCRKey, the memory map key
    and the singleflight key) only when non-empty. Bumping it in the
    MCPExternalAuthConfig makes the next start register a fresh client; the
    previous row is left in place, and existing keys and rows are untouched when
    the field is empty. It does not change the resolve-once-at-startup model
    (#6496) and stays out of the probe's way: both can land independently.

    Possible follow-up for the fix PR. A dcrConfig.maxRegistrationAge
    duration that treats a cached row older than the limit as stale (re-register
    at startup, replace with UpdateDCRCredentialsIfUnchanged so replicas
    converge) would give time-based rotation for upstreams where the probe cannot
    tell. We did not include it here to avoid colliding with the probe work in
    lookupCachedResolution; happy to add it on top of the fix PR if wanted.

    One caveat worth stating in docs for either mechanism: on providers that bind
    refresh tokens to the client (#6508), a new client generation stops refreshing
    the old upstream tokens, so affected users sign in again once.

  5. peppescg commented on Oct 14, 2026

    @peppescg
    ContributorAuthor

    @aron-muon thanks for the field report, it's really useful, and it shows the problem isn't limited to two ToolHive auth servers talking to each other.

    You're right about the probe. It only decides anything when the upstream authenticates the client before it checks the grant. ToolHive's own auth server (fosite) does that for both public and confidential clients, so that case is covered. With an upstream that returns invalid_grant for any client_id, the probe simply can't tell the difference, and the behavior stays exactly as it is today. I've updated the description and the code comments in #6822 to say this explicitly.

    I see #6825 as a good complement and I'm in favour of it, since a deliberate way for operators to rotate the registration is useful even where the probe works. Two small notes on it. The RotationKey doc comment says the rejection "is only visible in the user's browser, so the resolver cannot detect it", which won't hold for every upstream once #6822 is merged, so something like "may not be able to detect it" would age better. The two PRs also conflict in one place, the dcrStaleAgeThreshold comment in store.go, so whichever lands second just needs to merge the two sentences.

    About maxRegistrationAge, I have a few doubts and I'd like to check them with you, since you've run this in production. You mentioned that with #6508 users sign in again once after a new client generation. With a rotation key that happens once, when the operator decides, but with a time threshold wouldn't it happen at every rotation, even when the client is still valid? With more than one replica, wouldn't the first one that restarts after the threshold switch to a new client while the others keep the old one (#6496), so a login could start on one generation and end on the other? How many replicas do your proxies run? Wouldn't each rotation also leave the old registration behind on the vendor side, and does your vendor clean those up or would they pile up? And since you noted that no age heuristic would have predicted the wipes you saw, what would the threshold mainly cover in your case, periodic rotation for its own sake?

    Longer term, Client ID Metadata Documents could be an option, in case your vendor supports them. With CIMD there's no stored registration on the upstream side, so nothing that can be wiped or evicted, and the MCP spec is now deprecating DCR in favour of CIMD anyway.

  6. added a commit that references this issue on Oct 15, 2026
    50d7b9e
  7. aron-muon commented on Oct 15, 2026

    @aron-muon
    Contributor

    Thanks, and agreed on both notes for #6825: "may not be able to detect it" is the better wording, and since #6825 landed first the dcrStaleAgeThreshold comment merge falls to #6822; I'll fix the doc wording in the follow-up below.

    Your questions, from our deployment:

    • Replicas: 2 per proxy, behind a PDB. Karpenter consolidation restarts them several times a day, so "resolve once per process" is in practice "a few times a day".
    • Re-auth per rotation: our vendor does not bind codes or refresh tokens to the client (a code issued to one client_id exchanged fine under another), so a rotation is invisible to users there. On a vendor that binds them, every rotation is one re-auth, and a time threshold would make that periodic. Agreed that this is a real cost.
    • Mixed generations: during a rotation both generations run for the rollout window (about a minute); a login started on the old generation can complete on a pod holding the new one. Fine for our vendor, one failed exchange and a retry on a strict one. Acceptable for a deliberate rotation, not for a timer.
    • Orphans at the vendor: ours wipes its whole client store periodically, so nothing piles up there. It also issues no registration_access_token, so RFC 7592 DELETE is not available for cleanup. On other vendors orphans would accumulate.
    • maxRegistrationAge: you are right, it would mostly buy periodic rotation for its own sake and would not have predicted either wipe. Dropping it.

    What would have caught our case is a check against the authorization endpoint, which I'd like to add as an opt-in second strategy in #6822's framework. RFC 6749 §4.1.2.1: for an unknown client_id or a redirect_uri mismatch the AS MUST NOT redirect and informs the user directly; a known client gets a redirect to login/consent (or to the redirect_uri with an error). Our vendor behaves exactly like that: 302 to its IdP for the live client, direct 400 invalid_request for a purged or made-up one. Classification: 2xx or 3xx = alive; direct 4xx other than 429 = registration not accepted, re-register; 5xx, 429, network errors = inconclusive, keep the cached client. Opt-in per upstream (dcrConfig.registrationProbe: tokenEndpoint | authorizationEndpoint, default tokenEndpoint = #6822's behaviour), because some servers answer direct 4xx on the authorization endpoint for unrelated reasons. I'll open it stacked on #6822 once that merges, together with the doc wording fix.

    On CIMD: agreed as the end state. Our vendor does not advertise client_id_metadata_document_supported yet, and the embedded auth server's upstream path would also need to present a CIMD client_id; happy to look at that once a vendor supports it.

  8. added a commit that references this issue on Oct 15, 2026
    7d2acc6
  9. aron-muon commented on Oct 15, 2026

    @aron-muon
    Contributor

    The authorization-endpoint probe is up as #6834 (dcrConfig.registrationProbe: tokenEndpoint | authorizationEndpoint | none, default unchanged), rebased on #6822 and carrying the rotationKey wording fix.

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

Metadata

Metadata

Assignees

Labels

bugneeds-triage

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions