Skip to content

Embedded auth server rejects DCR from confidential MCP clients (token_endpoint_auth_method hardcoded to none) #5321

Done

Description

@nuclon

Summary

The embedded authorization server's DCR endpoint hardcodes token_endpoint_auth_method to none and refuses any client that registers with a different method or that expects a client_secret returned in the DCR response. This blocks any MCP client that implements OAuth as a confidential client.

Currently failing in production: Perplexity's MCP integration. ChatGPT's MCP support appears to follow the same confidential-client pattern (unverified in our setup — flagging as likely affected based on its public OAuth UX, would be good to confirm).

Working fine with the current implementation: Claude Code, Claude Desktop, Cursor, MCP Inspector (all public-client + PKCE).

Reproduction

  1. Deploy ToolHive operator v0.27.2 with a VirtualMCPServer that uses authServerConfig (embedded AS, any upstream — e.g. AWS Cognito or Google via OIDC upstream provider).
  2. In Perplexity's MCP server configuration, add the vMCP URL (e.g. https://mcp.example.com/).

First failure (already addressed by adding offline_access to advertised scopes — separate concern, calling out for completeness):

[API_CLIENTS_ERROR] {"error":"invalid_client_metadata","error_description":"default scope not supported by server: offline_access"}

After adding offline_access to incomingAuth.oidcConfigRef.scopes, second failure:

[API_CLIENTS_ERROR] Dynamic client registration did not return a client_secret

Server-side, the AS logs failed to create access request with error: "invalid_client" once Perplexity attempts the token exchange with a client_secret it expected but never received.

Root cause

pkg/authserver/server/registration/dcr.go:219-229 at tag v0.27.2:

// 5. Validate/default token_endpoint_auth_method
authMethod := req.TokenEndpointAuthMethod
if authMethod == "" {
    authMethod = "none"
}
if authMethod != "none" {
    return nil, &DCRError{
        Error:            DCRErrorInvalidClientMetadata,
        ErrorDescription: "token_endpoint_auth_method must be 'none' for public clients",
    }
}

This is reinforced by /.well-known/openid-configuration, which advertises:

"token_endpoint_auth_methods_supported": ["none"]

The intent is clearly to enforce the OAuth 2.1 / RFC 7591 best practice for native clients (no shared secrets in distributed apps), which is correct for many MCP clients. However, some commercial MCP clients (Perplexity, likely ChatGPT) implement their MCP integration as a server-side confidential client and require a client_secret to be issued at DCR time. For those clients, there is no workaround on the client side; the AS must support client_secret_basic or client_secret_post.

Impact

Client Behaviour
Claude Code, Claude Desktop, Cursor, MCP Inspector ✅ Work (public client + PKCE)
Perplexity ❌ Fail at DCR — needs client_secret returned
ChatGPT Likely ❌ — uses confidential-client OAuth in its other integrations
VS Code ✅ (per #2585)
WindSurf Untested per #2585

Without confidential-client support, the embedded AS cannot serve as the auth surface for the full set of MCP-capable clients an enterprise may want to support.

Proposed solution

Add an opt-in flag on EmbeddedAuthServerConfig (e.g. allowConfidentialClients: bool) that, when set:

  1. Accepts token_endpoint_auth_method values of client_secret_basic and client_secret_post (in addition to none) at /oauth/register.
  2. Returns a freshly generated client_secret in the DCR response when the registered method requires one (RFC 7591 §3.2.1).
  3. Stores the secret hashed in the credential store (the work in Persistent DCRCredentialStore backends (memory + Redis) #4979 / Persistent DCRCredentialStore: wire into EmbeddedAuthServer #5185 already provides the persistence layer).
  4. Validates client_secret_basic / client_secret_post at /oauth/token.
  5. Advertises the additional methods in token_endpoint_auth_methods_supported only when the flag is set.

This keeps the safe default (PKCE-only public clients) while letting operators opt into confidential clients when they need to support clients like Perplexity. The field documentation should mention that operators are accepting the risk of leaked secrets in distributed clients.

Alternative: support Client ID Metadata Document (CIMD) as a third path — but CIMD doesn't issue client_secret either, so it doesn't directly help Perplexity unless Perplexity adds CIMD support too.

Workarounds

For users hitting this today:

  • Skip Perplexity — use only public-client MCP clients (Claude Code, Cursor, etc.).
  • Use a different IdP that supports both public and confidential DCR — Keycloak, Authentik, ZITADEL, Auth0 — and point MCPOIDCConfig directly at it without the embedded AS. Adds infra weight and isn't a great fit if Cognito/Google is already the source of truth.

References

Activity

  1. added
    needs-triage
    on Jun 24, 2026
  2. jerm-dro commented on Jun 26, 2026

    @jerm-dro
    Collaborator

    Thanks for the report, @nuclon, and for the unusually thorough write-up. The root-cause pointer, the client-by-client breakdown, and the RFC references all made this easy to understand.

    This is something we would like to see supported. It is involved work, though, and it is not on our near-term roadmap: it touches the DCR endpoint and the token endpoint, requires issuing and securely storing client_secrets in the embedded AS, and updating the well-known metadata advertisement, all while keeping the safe public-client + PKCE default intact.

    We have labelled this good-tenth-issue to signal that we would welcome a community PR. Given the security surface, anyone picking it up should open a short design discussion or a draft PR first so we can align on approach before going deep. cc @jhrozek, who can review any proposed changes here. Thanks again for raising it.

  3. added
    good-tenth-issue
    and removed
    needs-triage
    on Jun 26, 2026
  4. Sanskarzz commented on Jul 3, 2026

    @Sanskarzz
    Collaborator

    @jerm-dro , I am interested in giving this a try. Please assign me. Thanks

  5. ChrisJBurns commented on Jul 30, 2026

    @ChrisJBurns
    Collaborator

    @Sanskarzz apologies for the silence, you asked 27 days ago and should not have had to wait. Assigning this to you.

    Before going deep, please post a short design outline in this issue, as @jerm-dro asked. The security surface is the reason: this means issuing and storing client_secrets in the embedded AS, changing the token endpoint's client authentication, and updating the advertised token_endpoint_auth_methods_supported, all while keeping public-client plus PKCE as the default and not weakening it for the clients that work today. Worth covering how secrets are generated and stored, what a confidential client's DCR response looks like, and how an operator opts in.

    Your work on #5377 for client-secret expiry and renewal is the closest thing in the tree, so some of that groundwork should carry over.

    One clarification for anyone reading this later: the hardcoded rejection is still present on main, at pkg/authserver/server/registration/dcr.go. #5866 has a similar-sounding title but addresses the opposite direction, our AS acting as an OAuth2 client to an upstream IdP, so it does not cover this.

    @nuclon, thanks for the original write-up. This has not moved as fast as it should have, and the report is still accurate.

  6. jhrozek commented on Aug 5, 2026

    @jhrozek
    Contributor

    @Sanskarzz — here's the design outline @jerm-dro and @ChrisJBurns asked for, written up as a full implementation plan so you have something concrete to build against or push back on. I went through the auth server code, checked how Ory Hydra (same fosite version we're on) and agentgateway handle this, and read it against RFC 7591/6749, OAuth 2.1 and the MCP authorization spec. Please treat it as a proposal, not a spec handed down — if you disagree with any of it, say so on the issue before writing code.

    The short version of what changed relative to the issue description:

    • Don't use bcrypt for the generated secret. /oauth/register is unauthenticated, so a cost-10 bcrypt on registration — and worse, on every wrong-secret attempt at /oauth/token — is a CPU amplifier against a process that also carries MCP traffic. Since the secret is 32 bytes of CSPRNG output and never client-chosen, SHA-256 + a constant-time compare via fosite.Config.ClientSecretsHasher is both correct and cheaper. Hydra moved off bcrypt for exactly this reason. This is free to do now and awkward later, since no client secrets exist yet.
    • client_secret_expires_at should be client_id_issued_at + 30d, not 0. Registrations already carry a 30-day idle TTL, so claiming "never expires" would be false, and without RFC 7592 a client has no way to recover except by hitting invalid_client. Advertising the real expiry makes re-registration the documented recovery path. Bonus: because the value is never zero, the existing omitempty field works unchanged.
    • Three upgrade hazards worth knowing before you start, all in the storage layer: rows written today have no token_endpoint_auth_method, and defaulting them to none would silently turn an existing confidential client public; public and the auth method are two sources of truth that must not be allowed to disagree (if they do, fosite returns early and never verifies the secret at all); and applying the DCR TTL by IsPublic() would attach a 30-day expiry to pre-provisioned confidential clients on their next token request. Commit 1 handles all three, and it needs to land first.
    • fosite pins the registered auth method in both directions — a client_secret_basic client sending credentials in the body is rejected too. That's worth knowing because OAuth 2.1 §2.4 actively recommends body credentials, so it's a plausible Perplexity failure mode. If it bites, the fix is a custom ClientAuthenticationStrategy, not looser secret handling.

    Two things I could not settle from the code and would like an answer to before commit 4 is written: does Perplexity send its client_secret_basic credentials in the header or the request body? The whole feature hinges on that matching fosite's pin. If you can capture the DCR request and the token request from a real attempt, that would settle it. Second, someone should confirm fosite's GetSecretsHasher is used only for client secrets in v0.49.0 before the hasher swap lands.

    Each commit below has a deliverable and acceptance criteria, so it should be reasonably mechanical to work through, and there's a kind e2e in there that reuses the existing Dex-based headless PKCE harness rather than needing a browser. Happy to review as you go.

    Full implementation plan (11 commits, with deliverables and acceptance criteria)

    Issue #5321 — Confidential-client DCR in the embedded auth server

    Context

    The embedded AS hardcodes token_endpoint_auth_method to none
    (pkg/authserver/server/registration/dcr.go:157-167) and advertises only ["none"] in
    discovery (handlers/discovery.go:116). Any MCP client implementing OAuth as a confidential
    client — Perplexity today, probably ChatGPT — fails DCR with "Dynamic client registration did
    not return a client_secret"
    , with no client-side workaround. Add an opt-in flag that accepts
    client_secret_basic / client_secret_post, mints a secret at registration, and keeps
    public-client + PKCE as the untouched default.

    One branch, commits in the order below. The issue is assigned to a community contributor
    (Sanskarzz) who was asked for a design outline first — post the design comment (last section)
    before or alongside implementing, and coordinate on the issue.

    MCP 2025-11-25 requires OAuth 2.1 "with appropriate security measures for both confidential
    and public clients
    ", so this moves the AS toward the spec rather than merely permitting
    something exotic. Worth saying in the issue comment.

    What already exists — reuse, don't rebuild

    Piece Where
    Confidential-client construction + empty-secret guard registration/client.go:156-182; 3 live callers (integration_test.go:699, integration_delegation_audit_test.go:161,261) all using client_secret_post and working end to end
    client_secret / client_secret_expires_at response fields pkg/oauthproto/dcr.go:122,126
    Auth-method constants pkg/oauthproto/constants.go:41-51 (imported as sharedobauth in discovery.go)
    Hashed-secret column in Redis storedClient.Secret — storage/redis.go:169
    Client auth at /oauth/token fosite NewAccessRequest; verified against Hydra's token handler — no hand-written client-auth code needed
    RenewClientTTL on every successful token response incl. refresh handlers/token.go:100-113
    Rate limiter dependency golang.org/x/time/rate — already a direct dep (go.mod:73)
    Flat-bool flag plumbed CRD→RunConfig→…→handlers InsecureAllowHTTP (not CIMDEnabled, which is a nested pointer struct)
    Headless PKCE flow in kind against the embedded AS getEmbeddedASToken + deployDex + registerOAuthClient — test/e2e/thv-operator/virtualmcp/helpers.go:1539,1682,1871

    Panel findings folded in

    Reviewed by five panelists: Ory Hydra (same fosite v0.49.0), agentgateway, oauth-expert,
    toolhive-expert, kubernetes-expert.

    Security, adopted as in-scope work:

    • bcrypt is a CPU-amplification DoS here. Cost-10 bcrypt on unauthenticated
      /oauth/register, and worse on /oauth/token — register once, then hammer with a wrong
      secret and force one bcrypt verify per attempt. The AS is in-process with the proxy data
      path, so this starves MCP traffic. The secret is 256 bits of CSPRNG output; a
      password-stretching KDF protects nothing. Swap to SHA-256 + subtle.ConstantTimeCompare via
      fosite.Config.ClientSecretsHasher. Free only until this ships — zero bcrypt client rows
      exist today because registration.New's only production caller passes Public: true.
    • Global rate limit on /oauth/register (rate.NewLimiter(1, 5), global not per-IP — per-IP is
      evadable and the map is itself unbounded).
    • Confidential clients get https-only redirect URIs. A client on http://localhost or
      cursor:// is by construction a public client (OAuth 2.1 §2.1); minting it a secret ships
      that secret inside a distributed binary. Costs nothing for Perplexity/ChatGPT, which register
      https. Also: do not wrap confidential clients in LoopbackClient — no dynamic-port matching
      for a secret holder.
    • Turning the flag off does not revoke already-minted secrets. Must be documented.

    Correctness / upgrade hazards:

    • Write-path/read-path composition can make a confidential client read back public, and
      fosite then returns at client_authentication.go:215 without ever calling
      checkClientSecret
      . The precise trigger is the stored client not satisfying
      fosite.OpenIDConnectClient — today's redisClient never does, which is why the bug is
      latent rather than live. Fail closed in both directions (commit 1).
    • Legacy Redis rows have no method (""). A blanket "" → none default turns an existing
      confidential row into a public one. Three-way read logic required.
    • registration.New must reject an empty/unknown method rather than defaulting — silently
      defaulting is the same public-ification bug one layer up. The three existing confidential
      test clients must be migrated to an explicit client_secret_post.
    • "mirror CIMDEnabled" was wrong: CIMDEnabled doesn't exist on RunConfig (it's a nested
      CIMDRunConfig pointer). Template is InsecureAllowHTTP.
    • vmcpconfig/converter.go:469 was the wrong file — that's the incoming-OIDC-middleware config.
      The vMCP path already delegates to controllerutil.BuildAuthServerRunConfig
      (converter.go:535), so controllerutil/authserver.go:590 is the only mapping site.
    • task docs is CLI docs. CRD API docs come from task crdref-gen, run from the repo root.
    • Commit-6 TTL as originally written would have applied a 30-day expiry to pre-provisioned
      confidential clients — and Redis EXPIRE on a key with no TTL creates one, so an existing
      permanent client would acquire an expiry on its first token request after upgrade.
    • My earlier "Redis round-trip breaks RFC 8252 port matching" claim was wrong:
      MatchRedirectURI has no callers in fosite's matching path (authorize_helper.go:66 reads
      only GetRedirectURIs()). The wrapper's only live effect is exposing
      GetTokenEndpointAuthMethod. Its doc comment is already misleading and must be corrected.
    • base64.RawURLEncoding is load-bearing: fosite url.QueryUnescapes both Basic components
      (client_authentication.go:308-311), so +///% in a secret would corrupt or error.
    • fosite pins the negotiated method in both directions — a client_secret_basic client
      sending body credentials is rejected too (:207-208), not just the reverse. OAuth 2.1 §2.4
      makes body credentials the MUST and calls the Basic encoding rule an interop hazard, so this
      pin is a deliberate deviation worth recording: if real-client testing hits it, the fix is a
      custom ClientAuthenticationStrategy, not loosening secret handling.
    • "none"-first in discovery is not a control — RFC 8414 defines no ordering semantics.
      Keep it (harmless), but don't present it as a mitigation. Real blast radius is narrower than
      first thought: an existing none client can't break (it has no secret to send); what changes
      is that new registrations from negotiating clients will ask for client_secret_basic.

    Refuted, so nobody "fixes" them: the flag does not widen the AS's exposure to upstream IdP
    tokens — a confidential refresh grant is strictly stronger than today's public one, since it
    requires the secret in addition to the refresh token; multi-tenancy is
    unaffected (per-instance AS, per-{ns}:{name} Redis prefix); no audit/OTel/access-log
    middleware exists on the AS chain, so no secret leaks there — but that is now a load-bearing
    invariant, so don't add request logging to this chain later; task gen is not needed (no
    interface signature changes); CIMD is unaffected (cimd_decorator.go:139 rejects non-none
    documents — leave it, do not "consistency-fix" it to follow the flag).

    Settled decisions

    • Opt-in allow_confidential_clients / allowConfidentialClients, default false ⇒ byte-identical
      server behaviour to today.
    • Accepted when on: none (still the default on omission), client_secret_basic,
      client_secret_post. Nothing else (fosite rejects client_secret_jwt outright;
      private_key_jwt is the RFC 9700-preferred long-term answer and pairs with CIMD — out of scope,
      say so in the design comment since MCP allows CIMD clients to use it).
    • Secret: 32 bytes crypto/rand → base64.RawURLEncoding (43 chars), returned once, hashed
      with SHA-256 at rest, never logged.
    • client_secret_expires_at = client_id_issued_at + DefaultDCRClientTTL (30 days) — truthful
      at issuance and it makes re-registration the documented recovery path, so RFC 7592 stays out
      of scope legitimately. Because that value is never 0, the existing int64 + omitempty
      field works as-is
      (public registrations omit the key; confidential ones emit it). No
      pointer change, no ripple into pkg/auth/dcr. Leave a comment: if anyone ever changes this
      to 0, omitempty silently drops the RFC-required key — the raw-JSON test is the guard.
    • Redirect-URI policy for existing public clients is unchanged (decided) — today's
      RedirectURIPolicyAllowPrivateSchemes (any https host, loopback http, private schemes) stays
      exactly as-is for none clients. The new confidential path is https-only-non-loopback with
      no LoopbackClient wrapper: that restricts new functionality rather than changing existing
      behaviour, so it carries no upgrade risk.
    • allow_confidential_clients + insecure_allow_http is a loud warning, not a hard gate
      (decided): WARN at AS startup naming the consequence, plus an operator condition
      reason. A hard gate would make the flag-on path untestable in kind — every embedded-AS e2e
      runs an in-cluster http:// issuer — and would break the in-cluster-HTTP posture the
      InsecureAllowHTTP doc comment already blesses.
    • PKCE stays enforced for everyone (OAuth 2.1 §4.1.1 + MCP). No per-client bypass — that would
      be a downgrade lever reachable from unauthenticated DCR. Make the rejection text name PKCE and
      code_challenge_methods_supported, because the first person to hit it will otherwise "fix" it
      by disabling EnforcePKCE.

    Commits

    1. Fail-closed client persistence in Redis

    Deliverable: pkg/authserver/storage/redis.go + redis_test.go. storedClient gains
    TokenEndpointAuthMethod string \json:"token_endpoint_auth_method,omitempty"`; the redisClienttype is deleted;GetClientrebuilds a*fosite.DefaultOpenIDConnectClient`.
    Three-way read logic, so drift in either column can only add secret verification:

    method := stored.TokenEndpointAuthMethod
    if method == "" {
        // Row predates confidential-client support. A public row was "none". A
        // confidential row had no method and fosite skipped method enforcement for
        // it — return a non-OIDC client so that stays true and the upgrade is a no-op.
        if !stored.Public {
            return &fosite.DefaultClient{ /* … */ }, nil
        }
        method = oauthproto.TokenEndpointAuthMethodNone
    }
    public := stored.Public && method == oauthproto.TokenEndpointAuthMethodNone

    Write path: populate from a fosite.OpenIDConnectClient assertion; on failure leave the field
    empty (no none fallback) and let Public carry the meaning it already carries. Don't
    route through registration.New — it would re-hash an already-hashed secret. Correct
    NewLoopbackClient's doc comment (the RFC 8252 claim is false as a fosite hook).

    Acceptance:

    1. An OIDC client with client_secret_basic round-trips with that method and IsPublic() == false.
    2. Legacy public row ("public": true, no method key) → IsPublic() == true, method none,
      and still completes a code flow.
    3. Legacy confidential row ("public": false, no method key) → IsPublic() == false and does
      not satisfy fosite.OpenIDConnectClient (assert by type assertion). Upgrade-safety pin.
    4. Drift row ("public": true + client_secret_basic) → IsPublic() == false.
    5. mockClient (non-OIDC, public: false) round-trips as non-public — the exploitable hole closed.
    6. GetHashedSecret() after round-trip is byte-identical to what was stored (no re-hash).
    7. The value returned by GetClient for a modern row satisfies fosite.OpenIDConnectClient —
      that assertion, not the Public field, is what activates fosite's method enforcement.

    2. SHA-256 client-secret hasher

    Deliverable: a fosite.Hasher implementation (SHA-256 + subtle.ConstantTimeCompare, ~15
    lines) wired via fosite.Config.ClientSecretsHasher in NewAuthorizationServerConfig
    (server/provider.go:~240), with registration.New hashing identically. Replaces
    bcrypt.GenerateFromPassword at registration/client.go:163. Comment states why: the secret is
    32 bytes of CSPRNG output, never client-chosen (the DCR request struct has no client_secret
    field — keep it that way), so there is nothing for a KDF to protect, and bcrypt on an
    unauthenticated endpoint is a CPU amplifier.

    Verify during implementation: that fosite's GetSecretsHasher is used only for client
    secrets in v0.49.0 and nothing else depends on the bcrypt shape.

    Acceptance:

    1. The three existing confidential token-exchange integration tests pass unchanged in behaviour.
    2. Unit test: Compare accepts the correct secret, rejects a wrong one, and rejects a truncated
      one; the comparison is subtle.ConstantTimeCompare by construction (assert on the code path,
      not by timing).
    3. 100 wrong-secret /oauth/token calls complete within a bound consistent with SHA-256
      (single-digit ms total) — proves no per-attempt KDF.
    4. grep -rn bcrypt pkg/authserver returns no hits.

    3. Flag plumbing

    Deliverable: the flag threaded through all seven hops, template InsecureAllowHTTP:
    RunConfig (config.go:36-120, //nolint:lll on the tags) → runner/embeddedauthserver.go:227-244
    literal → authserver.Config (next to InsecureAllowHTTP, ~:688) → server_impl.go:130-144
    params literal → AuthorizationServerParams field (provider.go:~110) → the
    NewAuthorizationServerConfig return literal (provider.go:265-274) — a distinct hop, and the
    one that silently drops the flag if missed
    → AuthorizationServerConfig field (provider.go:~72).
    Plus handlers_test.go's local testSetupOptions struct (:41), without which no discovery
    test can be written. Plus the startup WARN when combined with InsecureAllowHTTP, and an Info
    log when enabled that names the consequence ("this server issues client secrets over
    unauthenticated dynamic registration"), not just the flag name — precedent for Info here is
    provider.go:194. Regenerate docs/server/* (authserver.RunConfig is an exposed swagger
    model via pkg/runner/config.go:303).

    No change needed to: Validate/applyDefaults (plain bool), deepcopy, pkg/vmcp/cli/serve.go
    (tag-driven unmarshal), pkg/vmcp/config/validator.go, mocks.

    Acceptance:

    1. A test asserts the flag survives RunConfig → handlers.Handler.config (via
      buildOAuthMetadata). A gap at any of the seven hops fails it.
    2. Starting with both allow_confidential_clients and insecure_allow_http set emits exactly
      one WARN naming both fields and the cleartext-credential consequence; startup still succeeds.
    3. git status clean after task docs; grep allow_confidential_clients docs/server/swagger.yaml hits.
    4. Full task test green with no test changes outside handlers_test.go's struct.

    4. Accept confidential registrations and mint the secret

    Deliverable:

    • registration/client.go: Config.Public bool → Config.TokenEndpointAuthMethod string;
      Public derived; explicit enum validation in the constructor (reject "" and unknown
      values per .claude/rules/go-style.md "don't fall back silently to a default the caller
      didn't request"); LoopbackClient wrapper only when public. New
      registration.GenerateClientSecret() (string, error) lives here, next to the hashing it
      feeds, so handlers/dcr.go stays transport-only. A marker interface (registration.DCRIssued
      with an unexported method, satisfied by both the public and confidential return types) so
      storage can tell DCR-issued clients from pre-provisioned ones — needed by commit 6.
    • registration/dcr.go: ValidateDCRRequest(req, allowConfidential bool). Empty method still
      defaults to none; flag-off keeps today's byte-identical error string. Flag-on allows the two
      client_secret_* constants; confidential registrations additionally require https
      non-loopback redirect URIs
      (invalid_redirect_uri). Replace the hardcoded "none" literals
      at :160,162 and client.go:177 with oauthproto.TokenEndpointAuthMethodNone.
    • handlers/dcr.go: mint on non-none, set ClientSecret and
      ClientSecretExpiresAt = issuedAt + int64(storage.DefaultDCRClientTTL.Seconds()).
    • Migrate the three confidential test call sites to explicit client_secret_post, and update
      the server/doc.go:60 example (comment-sync rule).

    Acceptance:

    1. registration.New returns an error for TokenEndpointAuthMethod: "" and for any
      unrecognized value.
    2. Flag off: client_secret_basic DCR → 400 invalid_client_metadata, today's exact error
      string (assert the literal), no client_secret key in the body.
    3. Flag on, method omitted: no client_secret and no client_secret_expires_at key; method
      echoes none.
    4. Flag on, client_secret_basic: 201, Cache-Control: no-store, secret matching
      ^[A-Za-z0-9_-]{43}$, and the raw JSON literally contains client_secret_expires_at equal
      to client_id_issued_at + 2592000. Assert on raw bytes, not the unmarshalled struct —
      this is the assertion that catches an omitempty drop.
    5. Two consecutive registrations return different secrets.
    6. A request carrying a client_secret field has it ignored (response secret differs).
    7. Flag on: client_secret_basic with http://localhost:1234/cb, http://127.0.0.1/cb, or
      cursor://cb → 400 invalid_redirect_uri; the same URIs with none still succeed.
    8. A confidential client registered https://app.example/cb does not match
      https://app.example:9999/cb at /oauth/authorize (no loopback wrapper).
    9. client_secret_jwt, private_key_jwt, tls_client_auth, and garbage → 400
      invalid_client_metadata, flag on or off.
    10. Full flow on memory and miniredis: register client_secret_basic → authorize → redeem
      with Basic auth → 200. Also with client_id/secret percent-encoded before base64 (RFC 6749
      §2.3.1 form) — byte-identical for this charset, so both must pass.
    11. Wrong secret → 401 invalid_client with no error_debug field and no substring of
      either secret. Unknown client_id → an indistinguishable response body.
    12. Method pinning, both directions: client_secret_post client via Basic → invalid_client;
      client_secret_basic client via body creds → invalid_client.
    13. A confidential client presenting no credentials → invalid_client (not a silent success
      via the IsPublic() early return).
    14. A confidential authorize request omitting code_challenge → 400, error text naming PKCE and
      code_challenge_methods_supported.
    15. The minted secret appears in zero log records at any level across registration,
      authorize, and token paths including failures (assert over an slog capture handler).
    16. A token issued to a confidential client carries the same aud/resource restriction as one
      issued to a public client with identical AllowedAudiences (guards against the
      registration.Config rewrite dropping Audience).
    17. All three pre-existing token-exchange integration tests pass with only their Config
      literal changed.

    5. Advertise the extra methods

    Deliverable: handlers/discovery.go:116 built from config (none first). One edit covers
    both well-known endpoints (buildOAuthMetadata feeds both). Upgrade
    handlers_test.go:191,252 from assert.Contains(…, "none") — which cannot fail — to exact-slice
    assertions.

    Acceptance:

    1. Flag off: token_endpoint_auth_methods_supported equals ["none"] on both
      /.well-known/oauth-authorization-server and /.well-known/openid-configuration.
    2. Flag on: equals ["none","client_secret_basic","client_secret_post"], none at index 0.
    3. Every advertised method is accepted at /oauth/register in the same test process — no
      advertise/reject skew.
    4. Note in the docs that discovery is cached public, max-age=3600
      (discovery.go:143,174), so a flag flip is invisible for up to an hour to caching clients.

    6. TTL DCR-issued registrations, including confidential ones

    Deliverable: storage/redis.go — gate the TTL on the registration.DCRIssued marker in
    both RegisterClient (:212-220) and RenewClientTTL (:243-260), not on IsPublic().
    Rename DefaultPublicClientTTL → DefaultDCRClientTTL (5 sites) — a constant named Public
    governing confidential clients is exactly the name drift the style rules prohibit. Rewrite three
    doc comments (storage/config.go:40-42 — "confidential clients don't expire" becomes false;
    redis.go:213-215; redis.go:243-256, whose whole security argument is phrased public-vs-confidential).

    Acceptance:

    1. A DCR-registered client_secret_basic client carries a positive Redis TTL after registration.
    2. Its TTL is renewed to ~DefaultDCRClientTTL after a successful authorization_code and
      refresh_token response (miniredis FastForward + TTL).
    3. A confidential client registered directly via RegisterClient (not DCR-issued, e.g. the
      token-exchange agent pattern) has TTL 0 both after registration and after
      RenewClientTTL — anti-regression pin for pre-provisioned clients.
    4. After the row is evicted, /oauth/token with correct credentials returns 401
      invalid_client — the documented re-registration signal.
    5. grep -rn DefaultPublicClientTTL returns zero hits; no comment in pkg/authserver/storage/
      still claims confidential clients never expire.

    7. Rate-limit /oauth/register

    Deliverable: a global rate.NewLimiter(1, 5) gate returning 429 with Retry-After, applied
    to the registration route only. Global, not per-IP. Also demote
    handlers/token.go:30-32 and :94-96 from slog.Error to Debug: RFC6749Error.Error()
    returns only the error code, so the line is content-free, and it is now
    unauthenticated-triggerable at arbitrary rate (log-ingestion DoS that drowns real errors).

    Acceptance:

    1. 20 rapid POST /oauth/register calls: at least one returns 429 with Retry-After.
    2. A single registration in an idle server always succeeds (the limiter's burst doesn't break
      normal use).
    3. 100 wrong-secret token requests produce no ERROR-level log records.

    8. Bound the in-memory client map (splittable — pre-existing gap)

    Deliverable: MemoryStorage (the default backend, config.go:97-99) has no TTL, no cap,
    and a no-op RenewClientTTL (memory.go:342-354), so /oauth/register is an unbounded memory
    leak in the same process as the proxy. Pre-existing for public clients, but the flag raises the
    value of each entry, and it invalidates the "the TTL bounds keyspace" argument for the default
    configuration. Add a bounded map with oldest-first eviction (a cap, not a rejection — rejecting
    converts a memory DoS into a lockout DoS).

    If a reviewer wants this out of the PR, split it and reference the issue from the flag's doc
    comment — but do not leave the plan's Redis-only keyspace claim standing unqualified.

    Acceptance: N+1 registrations on the memory backend evict the oldest rather than growing
    unbounded; the surviving N still authenticate.

    9. Operator surface

    Deliverable: AllowConfidentialClients bool on EmbeddedAuthServerConfig
    (cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go:~485, by BaselineClientScopes),
    +kubebuilder:default=false, +optional. No CEL rule (user decision: warning, not hard
    gate) — instead extend validateAuthServerConfig (virtualmcpserver_controller.go:491-575,
    which already mirrors the InsecureAllowHTTP/http-issuer rule at :510) to surface the insecure
    combination in the AuthServerConfigValidated condition reason. No new condition type; no
    status-parity work for MCPServer/MCPRemoteProxy, which already defer to pod-startup validation.

    Doc comment in the InsecureAllowHTTP two-paragraph style, stating: unauthenticated
    /oauth/register now mints shared secrets (rate-limited, not authenticated); registrations idle

    30 days are evicted and must re-register; disabling the flag does not revoke already-minted
    secrets
    (memory: restart; Redis: ≤30-day idle eviction or a flush); advertising
    client_secret_basic may make a currently-public negotiating client upgrade to it; none
    remains the default on omission.

    Mapping: controllerutil/authserver.go:590 only — the vMCP path delegates via
    vmcpconfig/converter.go:535. v1beta1 is correct and needs no conversion function because
    v1alpha1 aliases the v1beta1 spec types (api/v1alpha1/types.go:57), so the field appears in
    both served versions automatically.

    Regenerate — note the third command runs from the repo root:

    task -d cmd/thv-operator operator-generate
    task -d cmd/thv-operator operator-manifests
    task crdref-gen
    

    Committed artifacts: four CRD YAMLs (files/crds/ + templates/ × mcpexternalauthconfigs +
    virtualmcpservers), each with two insertions because v1alpha1 aliases the same schema, plus
    docs/operator/crd-api.md. The diff will look ~4× larger than expected; that's correct.

    Acceptance:

    1. git status clean after all three commands — i.e. the Generate CRDs and Generate CRD Docs
      jobs in operator-ci.yml pass.
    2. grep -c allowConfidentialClients …_virtualmcpservers.yaml ≥ 2.
    3. Operator unit test: CRD true → RunConfig.AllowConfidentialClients == true; unset → false.
    4. A VirtualMCPServer with allowConfidentialClients: true + insecureAllowHTTP: true
      reconciles successfully and its AuthServerConfigValidated condition reason names the
      insecure combination.
    5. zz_generated.deepcopy.go diff is empty.
    6. No new field in vmcpconfig/converter.go.
    7. The chainsaw test referencing EmbeddedAuthServerConfig still passes with the
      API-server-defaulted field present.

    10. Kubernetes e2e in a kind cluster

    Deliverable: new test/e2e/thv-operator/virtualmcp/virtualmcp_authserver_confidential_dcr_test.go
    — one Ordered Describe, modelled on virtualmcp_redis_session_test.go:730-1140 (minus Redis
    and the 2-replica bits), which is the working reference for standing up Dex + signing-key/HMAC
    secrets + an EmbeddedAuthServerConfig on a VirtualMCPServer and driving a full PKCE flow.

    BeforeAll: RSA signing-key + HMAC + Dex client secrets; CreateMCPGroupAndWait; one
    lightweight backend MCPServer (images.GofetchServerImage); deployDex(...) (the
    mockCallback connector auto-approves, so the authorize step is fully headless — no browser,
    no Keycloak
    , and ghcr.io/dexidp/dex:v2.42.0 is already pre-pulled and kind loaded by the
    workflow); an inline MCPOIDCConfig; then two VirtualMCPServers with identical auth-server
    config except AllowConfidentialClients: true / field absent. One Dex serves both — only the
    flag-on vMCP runs a browser flow. Timestamp-suffix every resource name (--procs=8, shared
    default namespace). Reach the AS with portForwardToService(VMCPServiceName(name), 4483)
    inside each It, never shared across specs.

    Two small helper changes in helpers.go: registerOAuthClient gains a
    tokenEndpointAuthMethod param (existing call site passes "", behaviour byte-identical), and
    getEmbeddedASToken switches /oauth/token from the client_secret form field (:1846-1850,
    i.e. client_secret_post) to req.SetBasicAuth when the client registered client_secret_basic.

    The CRD-level assertion goes in virtualmcp_authserver_config_test.go, not chainsaw:
    test/e2e/chainsaw/operator/validation/ is executed by neither operator-ci.yml (lines 219-224)
    nor task operator-e2e-test — a test added there would be dead on arrival. File a separate
    issue to wire that directory into CI; three existing CEL tests there have apparently never run.

    Local loop: task -d cmd/thv-operator kind-setup-e2e → operator-install-crds →
    operator-deploy-local → thv-operator-e2e-test-run (re-runnable), focus with
    ginkgo --focus "Confidential DCR". CI: .github/workflows/test-e2e-lifecycle.yml (the only job
    running the Ginkgo suite), kind v1.33.7/v1.34.3/v1.35.1, 30-min budget. Expected +3-5 min wall
    clock. --fail-fast is on, so any flake here kills the whole suite — the port-forward subprocess
    and Dex's bounded redirect chain are the two live flake risks. Do not assert on log contents
    here (that's a unit assertion).

    Acceptance:

    1. task -d cmd/thv-operator thv-operator-e2e-test passes on a clean kind cluster, and
      --focus "Confidential DCR" passes 3 consecutive times on a provisioned cluster.
    2. Flag-on vMCP discovery returns exactly ["none","client_secret_basic","client_secret_post"].
    3. Flag-absent vMCP returns exactly ["none"].
    4. client_secret_basic DCR on the flag-on vMCP: 201, non-empty client_secret, method echoed,
      and client_secret_expires_at present in the raw JSON (decode to map[string]any, not a
      struct).
    5. The identical POST against the flag-absent vMCP: 400 invalid_client_metadata.
    6. A client_secret_basic client completes the Dex PKCE flow and redeems via
      Authorization: Basic, getting a non-empty access_token; a mutated secret → 401
      invalid_client.
    7. Reverting only commit 5 fails criterion 2 and nothing else; reverting only commit 4 fails
      criteria 4 and 6.
      If a commit can be reverted with the e2e still green, the e2e isn't
      testing it.
    8. The E2E Tests Lifecycle job stays under 30 minutes on all three kind versions.

    11. Docs

    Deliverable: the embedded-AS section of docs/arch/ covering the flag, the default-off
    invariant, the none-first ordering and why it is not a control, the both-directions method
    pinning (and that the fix for a real-client mismatch is a custom ClientAuthenticationStrategy,
    never looser secret handling), 30-day idle eviction and re-registration as the recovery path,
    that disabling the flag revokes nothing, the one-hour discovery cache, and the explicit
    non-goals with issue links. The docs-website change is a separate repo/PR.

    Acceptance:

    1. Every file path and line-anchored claim resolves against the merged tree.
    2. Each out-of-scope item below has a filed issue referenced by number — otherwise "worth its
      own issue" is a promise with no owner.

    Out of scope (file issues, don't build)

    • RFC 7592 client management — re-registration is the recovery path, and Hydra blanks the
      secret on re-read anyway.
    • private_key_jwt / mTLS — RFC 9700's preferred direction and permitted for CIMD clients by
      MCP, but the failing real clients implement client_secret_* only.
    • CORS on /oauth/register and /.well-known/* — none today (grepped: zero hits).
      Irrelevant for server-side clients like Perplexity; a blocker for browser-side MCP clients.
      agentgateway's entire registration_endpoint rewrite exists because IdPs omit CORS there.
    • Secret rotation (fosite.ClientWithSecretRotation) — nothing in the tree implements it;
      Hydra doesn't either.
    • Wiring test/e2e/chainsaw/operator/validation/ into CI — three CEL tests there are dead.

    Two things to settle before writing code

    1. Does Perplexity send client_secret_basic credentials in the header or the body? fosite
      pins the registered method in both directions, and OAuth 2.1 §2.4 actively recommends the
      body. Commit 4's whole value proposition depends on the pin matching Perplexity's real
      behaviour, and the plan otherwise defers that to the very last verification step. If a real
      endpoint isn't reachable, capture it from the DCR request Perplexity sends.
    2. Confirm fosite GetSecretsHasher is client-secret-only in v0.49.0 before commit 2 lands.

    Verification

    1. task test for the touched packages; task lint-fix.
    2. Default-off regression: client_secret_basic still rejected with the byte-identical error;
      discovery still exactly ["none"]; no bcrypt/SHA change visible to existing clients.
    3. Upgrade regression: a Redis row written by current code still authenticates — public and
      confidential variants. This is the one that breaks live deployments if wrong.
    4. Flag-on integration tests: full confidential flow on memory and miniredis, plus wrong-secret,
      wrong-method (both directions), no-credentials, and missing-PKCE failures.
    5. task -d cmd/thv-operator thv-operator-e2e-test — the kind e2e above, including the
      revert-a-commit-and-watch-it-fail check.
    6. Manual via the vMCP CLI path (pkg/vmcp/cli/serve.go:591-610 loads a sibling
      authserver-config.yaml): curl discovery → curl -X POST /oauth/register with
      client_secret_basic → browser flow → curl -u id:secret at /oauth/token; then remove the
      flag and confirm rejection (allowing for the one-hour discovery cache).
    7. Real-client check: point Perplexity's MCP config at a flag-on vMCP on a public HTTPS endpoint
      (the setup-ngrok-gateway skill covers this). This is the only test that closes the issue;
      everything above proves we built what we think Perplexity wants.
  7. jhrozek commented on Aug 5, 2026

    @jhrozek
    Contributor

    Sorry about the wall of text @Sanskarzz. What I tried to say and failed with the help of Claude :-) was that this issue has bubbled up in terms of priority. Above is a proposed plan - let me know if you already started, otherwise I'd be happy to take over.

  8. Sanskarzz commented on Aug 5, 2026

    @Sanskarzz
    Collaborator

    @jhrozek Thanks for putting together the detailed implementation plan. I haven’t started the implementation yet, but I’d like to continue working on this issue.

    I’ll go through the proposed plan carefully, understand the changes and security considerations, and then start the implementation. I’ll share any questions or concerns on the issue before proceeding with the relevant changes.

  9. jhrozek commented on Aug 5, 2026

    @jhrozek
    Contributor

    @jhrozek Thanks for putting together the detailed implementation plan. I haven’t started the implementation yet, but I’d like to continue working on this issue.

    I’ll go through the proposed plan carefully, understand the changes and security considerations, and then start the implementation. I’ll share any questions or concerns on the issue before proceeding with the relevant changes.

    The issue is kinda blocking me though on 2 fronts (XAA testing and finishing token delegation work) any chance you'd accept a different issue instead since you haven't started the implementation?

  10. Sanskarzz commented on Aug 6, 2026

    @Sanskarzz
    Collaborator

    @jhrozek Yes, it looks like this issue has become a priority, so please feel free to take it up.

    I’m currently focused on addressing the review comments on PR #5800 , so I can pick up a different issue once that work is complete. Thanks for checking.

  11. jhrozek commented on Aug 6, 2026

    @jhrozek
    Contributor

    @jhrozek Yes, it looks like this issue has become a priority, so please feel free to take it up.

    I’m currently focused on addressing the review comments on PR #5800 , so I can pick up a different issue once that work is complete. Thanks for checking.

    Thank you @Sanskarzz !

  12. assigned and unassigned on Aug 6, 2026
  13. jhrozek commented on Nov 24, 2026

    @jhrozek
    Contributor

    Closing this as fixed. Confidential clients can now register through DCR in the embedded authorization server, with a client secret issued at registration. The change is in #6252, which is merged.

    The feature is opt-in: it is turned on with AllowConfidentialClientRegistration in the auth server config (the operator field is on MCPExternalAuthConfig). With the flag off, the server still rejects confidential registration, as before.

    If the fix doesn't work for your setup, or if you think the default should be on, please reopen this issue with the server config (secrets redacted) and the registration request and response.

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

Metadata

Metadata

Assignees

Labels

authenticationenhancementgood-tenth-issueoauth

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions