Skip to content

vMCP: add embedded authorization server #4120

Closed
5 of 5 issues completed
Closed

Description

@tgrunnagle

Overview

Add an optional embedded OAuth authorization server (AS) to vMCP. When enabled, the AS acts as the OIDC issuer for incoming clients: it drives users through one or more upstream IDPs, accumulates their tokens, and issues a ToolHive JWT. The OIDC middleware validates that TH-JWT via a self-referencing loopback and eagerly loads the upstream tokens into `identity.UpstreamTokens`. Existing behavior when no AS is configured (Mode A) is byte-for-byte unchanged.

Background

vMCP today requires clients to obtain upstream IDP tokens externally before connecting — there is no mechanism for vMCP to orchestrate the auth flow itself. Additionally, upstream tokens accumulated during login have no unified path into the outgoing auth layer; the `upstream_inject` strategy (which would inject an upstream provider token into backend requests) has no source to draw from.

This RFC adds Mode B, where vMCP hosts the auth server at the same origin, handles OAuth/OIDC discovery as a loopback, and makes upstream tokens available to outgoing auth strategies via `identity.UpstreamTokens`.

RFC: stacklok/rfcs#53
Depends on: #3924 (RFC-0052 multi-upstream IDP support) for full end-to-end token flow

Task Breakdown

Task GitHub Issue Title Depends On
Phase 1 #4140 Foundation — add AuthServerConfig model, CRD field, and structural validation —
Phase 2 #4141 Server wiring — mount embedded auth server routes on vMCP mux #4140
Phase 3 #4142 Startup validation (V-01..V-07) — upstream_inject types and validateAuthServerIntegration #4140
Phase 4 #4143 Operator reconciler, HTTP handler unit tests, and E2E test coverage #4141, #4142
#4140 (Phase 1: Foundation)
    |
    +---> #4141 (Phase 2: Server wiring)      \
    |                                          +---> #4143 (Phase 4: Operator + E2E)
    +---> #4142 (Phase 3: Startup validation) /

Phase 1 is the root; Phases 2 and 3 can be developed in parallel; Phase 4 is the integration phase.

Acceptance Criteria

Sub-issues

Sub-issues

5 of 5 Issues completed
Loading 5 sub-issues

Activity

  1. added
    enhancement
    go
    vmcp
    on Mar 12, 2026
  2. self-assigned this
    on Mar 12, 2026
  3. tgrunnagle commented on Mar 13, 2026

    @tgrunnagle
    CollaboratorAuthor

    Planning Artifact: Intake

    Intake: vMCP — Add Embedded Authorization Server (RFC-0053)

    Original Requirements

    Implement RFC-0053 (Embedded Auth Server in vMCP) as tracked by the placeholder epic issue
    #4120. The RFC adds an optional embedded OAuth
    authorization server to vMCP. When enabled, the AS acts as the OIDC issuer for incoming
    clients: it drives users through one or more upstream IDPs, accumulates their tokens, and
    issues a ToolHive JWT. Existing behavior for an external OIDC issuer is unchanged (byte-for-byte
    backward compatibility).

    Create exactly one GitHub issue per RFC implementation phase (4 phases total), linked as
    sub-issues of #4120.

    RFC document: /Users/trey/Documents/GitHub/toolhive/docs/proposals/THV-0053-vmcp-embedded-authserver.md

    Existing Documentation

    • RFC-0053: Embedded Auth Server in vMCP — /Users/trey/Documents/GitHub/toolhive/docs/proposals/THV-0053-vmcp-embedded-authserver.md — Full design: problem statement, high-level design (Mode A / Mode B), detailed config model changes, CRD changes, operator reconciler changes, HTTP route mounting, validation rules V-01..V-07, security considerations, testing strategy, and 4-phase implementation plan.
    • RFC-0052 tracking issue — Auth Server: multi-upstream provider support #3924 — "Auth Server: multi-upstream provider support". Phases that depend on RFC-0052 (specifically identity.UpstreamTokens population by the OIDC auth middleware) should link to this issue.
    • Epic placeholder issue — vMCP: add embedded authorization server #4120 — "vMCP: add embedded authorization server". All 4 phase issues are sub-issues of this epic.

    Clarifying Questions & Answers

    Issue Style

    • Format: Task-based engineering tickets
    • Rationale: Each phase maps 1:1 to a concrete set of file changes described in the RFC. Task-based framing (naming the files and actions) is more actionable than user-story framing for implementation work.

    Repository & Project

    Scope & Boundaries

    • Expected Outcome: vMCP can optionally embed an OAuth authorization server that acts as the OIDC issuer for incoming clients, with full CRD support in the Kubernetes operator and startup validation for misconfigured auth wiring.
    • In Scope:
      • Moving ExternalAuthConfigRef to its canonical location in mcpexternalauthconfig_types.go
      • Adding AuthServerConfigRef *ExternalAuthConfigRef to VirtualMCPServerSpec
      • Adding AuthServer *AuthServerConfig to pkg/vmcp/config/config.go
      • Regenerating zz_generated.deepcopy.go
      • Conditional AS creation and HTTP route mounting in cmd/vmcp/app/commands.go and pkg/vmcp/server/server.go
      • Replacing the /.well-known/ catch-all handler with explicit path registrations
      • Adding validateAuthServerIntegration with validation rules V-01 through V-07
      • Operator reconciler: resolving authServerConfigRef, cross-resource validation (type check, V-04, V-07), new AuthServerConfigValid status condition
      • CRD-to-config converter updates in cmd/thv-operator/pkg/vmcpconfig/converter.go
      • Unit tests (table-driven Ginkgo) for all validation rules
      • E2E tests for Mode A and Mode B behavior and negative validation cases
      • Documentation updates (docs/arch/09-operator-architecture.md, docs/arch/02-core-concepts.md, new vMCP auth server guide)
    • Out of Scope:
      • upstream_inject outgoing auth strategy (deferred to a follow-up RFC)
      • Hot-reload of AS configuration
      • Multi-upstream IDP support (defined by RFC-0052, depended on but not re-specified here)
      • CLI-path upstream token swap (pkg/auth/upstreamswap middleware)
      • Step-up auth signaling
    • Type: New feature (Mode B); non-breaking enhancement (Mode A preserved)

    Technical Context

    • Affected Components:
      • pkg/vmcp/config/config.go — new AuthServer *AuthServerConfig field and AuthServerConfig struct
      • pkg/vmcp/config/validator.go — new validateAuthServerIntegration method and helper functions
      • pkg/vmcp/config/zz_generated.deepcopy.go — regenerated
      • pkg/authserver/runner/embeddedauthserver.go — new RegisterHandlers(mux *http.ServeMux) method
      • cmd/vmcp/app/commands.go — conditional AS creation; pass AuthServer to server config
      • pkg/vmcp/server/server.go — add AuthServer to server Config; mount AS routes; replace /.well-known/ catch-all
      • cmd/thv-operator/api/v1alpha1/mcpserver_types.go — remove ExternalAuthConfigRef struct definition (moved)
      • cmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.go — add ExternalAuthConfigRef struct definition (moved from mcpserver_types.go)
      • cmd/thv-operator/api/v1alpha1/virtualmcpserver_types.go — add AuthServerConfigRef field; add validateAuthServerConfig method
      • cmd/thv-operator/pkg/vmcpconfig/converter.go — resolve authServerConfigRef to AuthServerConfig.RunConfig
      • cmd/thv-operator/controllers/virtualmcpserver_controller.go — cross-resource validation, new status condition
    • Known Constraints:
      • pkg/authserver/runner.EmbeddedAuthServer is already implemented; no new AS implementation work needed in this RFC
      • The /.well-known/ catch-all change is behavioral but non-breaking: the catch-all currently only serves oauth-protected-resource; all other paths return 404 in both old and new code
      • allowedAudiences is derived by the operator converter from the referencing VirtualMCPServer's incoming auth audience — it is NOT an explicit field on MCPExternalAuthConfig in the CRD
      • V-07 is an active startup check only on the YAML path; on the Kubernetes path it is satisfied by construction (converter derives the value)
      • Mode A (no AS) behavior must remain byte-for-byte identical; all new code paths are gated on cfg.AuthServer != nil
    • Target Milestone: None specified

    Dependencies & Integration

    • Depends On:
      • RFC-0052 (multi-upstream IDP support) — Auth Server: multi-upstream provider support #3924 — Required for identity.UpstreamTokens population by the OIDC auth middleware. Phases 1–2 can be developed in parallel; full integration testing of the end-to-end flow requires RFC-0052 to be merged.
    • Downstream Consumers:
      • upstream_inject outgoing auth strategy (deferred to a follow-up RFC) — will consume identity.UpstreamTokens populated by this RFC's auth middleware wiring
      • Cedar authorization policies — identity sub and claims will be derived from the first configured upstream IDP when Mode B is active
    • External Integrations:
      • Upstream OIDC/OAuth IDPs configured by the operator (e.g., corporate SSO, GitHub)
      • Redis (optional AS session storage backend for production deployments)

    Acceptance & Verification

    • Success Criteria:
      • Mode A (no AS config): zero behavior change; all existing tests pass
      • Mode B (AS config present): /.well-known/openid-configuration returns a valid OIDC discovery document with the correct issuer and non-empty jwks_uri
      • Mode B: unauthenticated requests to the MCP endpoint return 401 (auth middleware remains active)
      • Validation rules V-01..V-07 fail fast at startup (YAML path) or at operator reconciliation (Kubernetes path) with descriptive error messages
      • Operator reconciler surfaces AuthServerConfigValid status condition on VirtualMCPServer
      • Invalid configurations produce a Failed phase with a descriptive condition message, preventing deployment until corrected
    • Test Scenarios:
      • Unit (Ginkgo DescribeTable): one Entry per validation rule V-01..V-07, plus nil AuthServer (Mode A passes all checks) and a valid Mode B config
      • Unit: CRD validateAuthServerConfig — empty name rejection and nil-pointer safety
      • Unit: HTTP handler tests (Mode A: AS routes return 404; Mode B: AS routes served; oauth-protected-resource served in both modes)
      • E2E (test/e2e/vmcp_authserver_test.go): Mode B startup, OIDC discovery response, 401 on unauthenticated MCP request, Mode A 404 on discovery
      • E2E negative: issuer mismatch exits non-zero with V-04 error; upstream_inject with no AS exits with V-01 error; unknown provider exits with V-02 error
      • Operator E2E (Ginkgo/Gomega + Eventually): create MCPExternalAuthConfig + VirtualMCPServer, verify deployment and AuthServerConfigValid condition
    • Stakeholders: tgrunnagle (RFC author, epic assignee)

    Dry Run Mode

    • Enabled: false — create issues directly in GitHub

    Issue Labels

    All phase issues inherit the epic's labels: authentication, authorization, enhancement, go, vmcp

    Issue Linking

    Each phase issue is linked to epic #4120 as a GitHub sub-issue using the gh sub-issue extension.

    Assignees

    Leave all phase issues unassigned.

    Phase Breakdown

    The RFC defines exactly 4 implementation phases. Each becomes one GitHub issue.

    Phase 1: Foundation (no runtime behavior change)

    Summary: Structural changes only — no runtime behavior changes. Move ExternalAuthConfigRef,
    add new CRD and config fields, add structural validation, regenerate deepcopy.

    File changes:

    • cmd/thv-operator/api/v1alpha1/mcpserver_types.go — remove ExternalAuthConfigRef struct (moved)
    • cmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.go — add ExternalAuthConfigRef struct (moved from mcpserver_types.go); all existing callers are unaffected (same package)
    • cmd/thv-operator/api/v1alpha1/virtualmcpserver_types.go — add AuthServerConfigRef *ExternalAuthConfigRef to VirtualMCPServerSpec; add validateAuthServerConfig() structural validation (name non-empty check)
    • pkg/vmcp/config/config.go — add AuthServer *AuthServerConfig to Config; add AuthServerConfig struct wrapping authserver.RunConfig
    • pkg/vmcp/config/zz_generated.deepcopy.go — regenerate

    Acceptance: All existing tests pass. The new fields are optional and unused; no server behavior changes.

    Dependencies: None (can start immediately)


    Phase 2: Server wiring

    Summary: Conditional AS creation at startup and HTTP route mounting. This is the first phase
    that changes runtime behavior (when authServer is configured in the YAML).

    File changes:

    • pkg/authserver/runner/embeddedauthserver.go — add RegisterHandlers(mux *http.ServeMux) method mounting /oauth/, /.well-known/openid-configuration, /.well-known/oauth-authorization-server, /.well-known/jwks.json
    • cmd/vmcp/app/commands.go — conditional AS creation (if cfg.AuthServer != nil); pass AuthServer to server config; hard failure on AS creation error (no silent fallback to Mode A)
    • pkg/vmcp/server/server.go — add AuthServer *runner.EmbeddedAuthServer to server Config; call RegisterHandlers conditionally; replace mux.Handle("/.well-known/", ...) catch-all with explicit /.well-known/oauth-protected-resource registration

    Smoke test: Start vMCP with a Mode B config; confirm /.well-known/openid-configuration returns AS metadata. Confirm Mode A behavior is unchanged.

    Dependencies: Phase 1 must be merged. Can be developed in parallel with RFC-0052 (#3924), but full end-to-end auth flow requires RFC-0052.


    Phase 3: Startup validation

    Summary: Add validateAuthServerIntegration to the config validator, covering all V-01..V-07
    rules, plus unit tests.

    File changes:

    • pkg/vmcp/config/validator.go — add validateAuthServerIntegration(cfg *Config) error called from Validate(); add helpers collectAllBackendStrategies, hasUpstreamProvider, containsString; extend validateBackendAuthStrategy for upstream_inject V-01/V-06

    Tests:

    • pkg/vmcp/config/validator_test.go — table-driven Ginkgo DescribeTable with one Entry per rule: V-01 (upstream_inject, no AS), V-02 (unknown provider), V-03 (token_exchange warning), V-04 (issuer mismatch), V-05 (AS internal validation failure), V-06 (empty provider name), V-07 (audience not in allowedAudiences); plus Mode A pass-through and valid Mode B config
    • cmd/thv-operator/api/v1alpha1/virtualmcpserver_types_test.go — validateAuthServerConfig covering empty name rejection and nil-pointer safety

    Dependencies: Phase 1 must be merged. Independent of Phase 2 (can be developed in parallel).


    Phase 4: Operator reconciler

    Summary: Kubernetes operator support — resolve authServerConfigRef, cross-resource
    validation, new status condition, CRD converter updates, and E2E tests.

    File changes:

    • cmd/thv-operator/controllers/virtualmcpserver_controller.go — resolve spec.authServerConfigRef ref; verify type is embeddedAuthServer; verify issuer consistency (V-04); verify audience non-empty (defense-in-depth); surface AuthServerConfigValid status condition; invalid config produces Failed phase with descriptive message
    • cmd/thv-operator/pkg/vmcpconfig/converter.go — resolve spec.authServerConfigRef → AuthServerConfig.RunConfig; derive allowedAudiences from spec.incomingAuth.oidcConfig.inline.audience

    Tests:

    • pkg/vmcp/server/server.go HTTP handler unit tests — Mode A: AS routes return 404, oauth-protected-resource returns RFC 9728 response; Mode B: AS routes served, oauth-protected-resource served, unauthenticated MCP catch-all returns 401
    • test/e2e/vmcp_authserver_test.go — positive: Mode B OIDC discovery returns valid document; Mode B unauthenticated MCP returns 401; Mode A discovery returns 404
    • test/e2e/vmcp_authserver_test.go — negative: issuer mismatch → non-zero exit + V-04 stderr; upstream_inject no AS → V-01 stderr; unknown provider → V-02 stderr
    • Operator E2E (Ginkgo/Gomega, test/e2e/chainsaw/operator/ or test/e2e/): create MCPExternalAuthConfig + VirtualMCPServer; verify deployment; verify AuthServerConfigValid condition via Eventually

    Documentation updates:

    • docs/arch/09-operator-architecture.md — new VirtualMCPServerSpec.AuthServerConfigRef field and reconciliation steps
    • docs/arch/02-core-concepts.md — Mode A / Mode B distinction for vMCP auth
    • docs/ — new vMCP auth server guide (config walkthrough, example YAML, troubleshooting self-referencing OIDC discovery)
    • Run task docs to regenerate CRD documentation

    Dependencies: Phases 1, 2, and 3 must be merged. RFC-0052 (#3924) is required for full integration test of the end-to-end auth flow (upstream token population).

    Additional Notes

    • The EmbeddedAuthServer implementation in pkg/authserver/runner/ already exists and is used by the proxy runner. No new AS implementation is needed for this RFC — only the RegisterHandlers method is new.
    • The self-referencing OIDC discovery loopback works because TokenValidator uses lazy OIDC discovery (deferred to first token validation) with exponential backoff retry. jwksAllowPrivateIP: true must be set in the incoming auth config for in-cluster deployments.
    • V-07 (audience consistency) is checked only on the YAML path. On the Kubernetes path it is satisfied by construction: the converter derives allowedAudiences from the referencing VirtualMCPServer's incoming auth audience, so they are always consistent. The reconciler still checks post-conversion for defense-in-depth (empty audience guard).
    • The ExternalAuthConfigRef move (Phase 1) is a struct definition move within the same Go package (v1alpha1). All existing callers using v1alpha1.ExternalAuthConfigRef are unaffected — no API surface changes.
  4. tgrunnagle commented on Mar 13, 2026

    @tgrunnagle
    CollaboratorAuthor

    Planning Artifact: Research

    Research: vMCP — Add Embedded Authorization Server (RFC-0053)

    Local Repository Clones

    • /Users/trey/Documents/GitHub/toolhive — stacklok/toolhive (primary): main service being changed; contains all affected packages (pkg/vmcp/, pkg/authserver/, cmd/vmcp/, cmd/thv-operator/)

    Reference Documentation

    Key documents discovered during research. Include retrieval paths for sub-agents.

    In Repository

    • /Users/trey/Documents/GitHub/toolhive/docs/proposals/THV-0053-vmcp-embedded-authserver.md — Full RFC-0053 design document: problem statement, Mode A/B design, detailed config model changes, CRD changes, operator reconciler changes, HTTP route mounting, validation rules V-01..V-07, security considerations, alternatives considered, and 4-phase implementation plan
    • /Users/trey/Documents/GitHub/toolhive/docs/proposals/THV-0052-multi-upstream-idp-authserver.md — RFC-0052 (multi-upstream IDP support): dependency of RFC-0053; defines identity.UpstreamTokens population by the OIDC auth middleware
    • /Users/trey/Documents/GitHub/toolhive/CONTRIBUTING.md — Contribution guidelines: DCO sign-off requirement, PR process, commit message guidelines
    • /Users/trey/Documents/GitHub/toolhive/CLAUDE.md — Project-specific AI guidance: subagent list, build commands, architecture overview, testing strategy, coding conventions, commit/PR standards
    • /Users/trey/Documents/GitHub/toolhive/docs/arch/09-operator-architecture.md — Kubernetes operator architecture: CRD hierarchy, reconciler design, VirtualMCPServer lifecycle; must be updated in Phase 4
    • /Users/trey/Documents/GitHub/toolhive/docs/arch/02-core-concepts.md — Core concepts: workloads, transports, security model; must be updated in Phase 4 for Mode A/B distinction
    • /Users/trey/Documents/GitHub/toolhive/docs/cli-best-practices.md — CLI development patterns: thin-wrapper principle, flag naming, output formatting, testing philosophy
    • /Users/trey/Documents/GitHub/toolhive/docs/error-handling.md — Error handling guidelines: wrap with %w, no sensitive data in errors, errors.Is/errors.As for inspection
    • /Users/trey/Documents/GitHub/toolhive/docs/logging.md — Logging guidelines: silent success, DEBUG for diagnostics, no sensitive data

    External URLs


    Organizational Standards

    Coding Conventions

    • All Go files require SPDX headers at top:
      // SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc.
      // SPDX-License-Identifier: Apache-2.0
    • Use go.uber.org/mock (gomock) for all mocks; generate with mockgen; place mocks in mocks/ subdirectories
    • Public methods in the top half of each Go file; private methods in the bottom half
    • Prefer immutable variable assignment with immediately-invoked anonymous functions over mutable branching (see CLAUDE.md)
    • Use fmt.Errorf with %w for error wrapping; never silently swallow errors
    • errors.Is() / errors.As() for all error inspection
    • No sensitive data (tokens, secrets, keys) in error messages or log output
    • require.NoError(t, err) preferred over t.Fatal in tests
    • slog.Debug for diagnostics; slog.Info sparingly (long-running ops only); slog.Warn for non-fatal fallbacks
    • Silent success: no log output at INFO or above for successful operations

    Review Process

    • PRs must follow .github/pull_request_template.md exactly — no placeholder text left in required sections
    • PR title: under 70 characters, imperative mood, no trailing period, no conventional-commit prefixes (feat:, fix:, chore:, etc.)
    • PR summary must explain the "why" first, then the "what"
    • Must check at least one item in the test plan section
    • All commits must include a Signed-off-by trailer (DCO)
    • PR size limit: 400 lines of code changes (excluding tests, generated code, docs) and 10 files changed

    Documentation Standards

    • Architecture docs in docs/arch/ must be updated when components change (see CLAUDE.md table)
    • Include code references using file_path format (without line numbers, since they change)
    • Cross-reference related documentation; keep terminology consistent with docs/arch/02-core-concepts.md
    • CRD documentation regenerated with task docs after any CRD changes

    Testing Requirements

    • Unit tests alongside source files (*_test.go); pkg/ packages require thorough coverage
    • CLI layer (cmd/thv/app/) tested primarily with E2E tests; only output formatting/flag validation get unit tests
    • Tests that touch disk state use isolated temp directories: t.TempDir() then filepath.EvalSymlinks(dir) on macOS (symlink resolution for path validators)
    • Tests that set env vars must be isolated from other tests that set the same vars
    • Table-driven (declarative) tests preferred over imperative tests
    • Avoid redundant test cases that exercise identical code paths
    • Use large port numbers in tests (near math.MaxInt16) to avoid port conflicts

    Architecture & Design

    System Architecture

    • vMCP is the Virtual MCP Server that aggregates multiple backend MCP servers into a single unified endpoint. It runs as a standalone binary (cmd/vmcp/) or as a Kubernetes Deployment managed by thv-operator.
    • The operator pattern: thv-operator watches CRDs, reconciles Kubernetes resources (Deployment, Service, ConfigMap, ServiceAccount, RBAC). The CRD-to-Config converter (cmd/thv-operator/pkg/vmcpconfig/converter.go) translates the CRD spec into a platform-agnostic pkg/vmcp/config.Config YAML that vMCP reads at startup.
    • The pkg/vmcp/config.Config struct is the central configuration model shared by both the CLI YAML path and the Kubernetes path.
    • Authentication boundaries: incoming (clients → vMCP, configured via IncomingAuth) and outgoing (vMCP → backends, configured via OutgoingAuth). These are intentionally independent config sections.

    Established Patterns

    • Factory Pattern: pkg/vmcp/auth/factory/ creates auth middleware from config. NewIncomingAuthMiddleware(ctx, cfg.IncomingAuth) returns (authMw, authzMw, authInfoHandler, err). New AS creation follows the same conditional creation pattern already used for other components.
    • Converter pattern: cmd/thv-operator/pkg/vmcpconfig/converter.go Convert() starts with config := vmcp.Spec.Config.DeepCopy() then conditionally overrides each section. New authServerConfigRef resolution follows the same pattern as existing convertIncomingAuth.
    • Status conditions: cmd/thv-operator/controllers/virtualmcpserver_controller.go uses metav1.Condition slices and AuthConfigError type to surface per-resource validation failures. New AuthServerConfigValid condition follows this established pattern.
    • +kubebuilder:object:generate=true annotation: Used on structs that need deepcopy generated. Adding to AuthServerConfig triggers regeneration of zz_generated.deepcopy.go.
    • omitempty for optional fields: All optional config fields use json:"fieldName,omitempty" yaml:"fieldName,omitempty" tags.
    • Nil-guard gating: All new code paths for Mode B are gated on cfg.AuthServer != nil (YAML path) or s.config.AuthServer != nil (server path), ensuring byte-for-byte Mode A compatibility.

    Prior Decisions

    • ExternalAuthConfigRef reuse for vMCP auth server reference: Rather than embedding EmbeddedAuthServerConfig directly in VirtualMCPServerSpec or creating a new CRD, RFC-0053 reuses the existing MCPExternalAuthConfig pattern. This is consistent with how MCPServer.spec.externalAuthConfigRef works and allows sharing config across multiple VirtualMCPServer resources. See Alternatives Considered section of RFC-0053.
    • allowedAudiences derived by converter, not stored in CRD: The MCPExternalAuthConfig.embeddedAuthServer spec intentionally omits allowedAudiences because its correct value depends on the referencing VirtualMCPServer. The converter derives it from spec.incomingAuth.oidcConfig.inline.audience.
    • Issuer must be set explicitly (not auto-derived): The operator requires the issuer to be set explicitly in MCPExternalAuthConfig.embeddedAuthServer.issuer. No auto-derivation from service name. (RFC-0053, Decisions section.)
    • Redis TLS via service mesh only: RedisStorageConfig does not expose TLS fields in the CRD; encryption in transit is the responsibility of the cluster service mesh.
    • Self-referencing OIDC discovery works via lazy discovery: TokenValidator uses lazy OIDC discovery with exponential backoff retry (deferred to first token validation, not server startup). This means the loopback to the embedded AS works because the AS is serving before the first client token arrives.

    API Contracts

    • pkg/authserver/runner.EmbeddedAuthServer: Already implemented. Public interface: NewEmbeddedAuthServer(ctx, *authserver.RunConfig) (*EmbeddedAuthServer, error), Handler() http.Handler, Close() error, IDPTokenStorage() storage.UpstreamTokenStorage, UpstreamTokenRefresher() storage.UpstreamTokenRefresher. The new method RegisterHandlers(mux *http.ServeMux) is additive.
    • pkg/vmcp/server.Config: Existing fields include AuthMiddleware, AuthzMiddleware, AuthInfoHandler http.Handler. New field AuthServer *runner.EmbeddedAuthServer is additive.
    • pkg/vmcp/config.Config: Existing fields include IncomingAuth, OutgoingAuth, Aggregation, etc. New field AuthServer *AuthServerConfig is additive with omitempty.
    • pkg/vmcp/auth/types: Existing constants: StrategyTypeUnauthenticated, StrategyTypeHeaderInjection, StrategyTypeTokenExchange. New constant StrategyTypeUpstreamInject = "upstream_inject" must be added (Phase 3).

    Known Constraints

    • /.well-known/ catch-all replacement is behavioral but non-breaking: Currently mux.Handle("/.well-known/", wellKnownHandler) at line 485 of pkg/vmcp/server/server.go serves only /.well-known/oauth-protected-resource; all other /.well-known/ paths return 404. Replacing with explicit path registration preserves this behavior while allowing the AS to register its own well-known paths.
    • Mode A byte-for-byte compatibility: All new code paths are gated on cfg.AuthServer != nil. Existing configs that omit authServer are unaffected.
    • ExternalAuthConfigRef move is within the same package: Moving the struct definition from mcpserver_types.go to mcpexternalauthconfig_types.go is within package v1alpha1. All existing callers using v1alpha1.ExternalAuthConfigRef are unaffected — no API surface changes.
    • V-07 is YAML-path-only: On the Kubernetes path, allowedAudiences is derived by the converter from the referencing VirtualMCPServer's incoming auth audience, making the check structurally satisfied. The reconciler checks post-conversion only as a defense-in-depth empty-audience guard.
    • jwksAllowPrivateIP is a gap: The RFC example YAML uses jwksAllowPrivateIP: true in IncomingAuth.OIDCConfig. The current pkg/vmcp/config.OIDCConfig struct does not have this field. The underlying pkg/auth.TokenValidatorConfig.AllowPrivateIP exists, and the current ProtectedResourceAllowPrivateIP field already maps to it. Phase 1 or 2 must add a dedicated JwksAllowPrivateIP bool field to config.OIDCConfig and wire it through pkg/vmcp/auth/factory/incoming.go's newOIDCAuthMiddleware, so in-cluster loopback OIDC discovery works for Mode B.
    • StrategyTypeUpstreamInject does not yet exist: The constant and corresponding BackendAuthStrategy field (UpstreamInject *UpstreamInjectConfig) must be added to pkg/vmcp/auth/types/types.go in Phase 3, alongside the validateBackendAuthStrategy extension.
    • deepcopy regeneration required: After adding AuthServerConfig (with +kubebuilder:object:generate=true) to pkg/vmcp/config/config.go, zz_generated.deepcopy.go must be regenerated. In cmd/thv-operator/: after any CRD type changes, task operator-generate, task operator-manifests, and task crdref-gen must be run.

    Codebase Analysis

    Relevant Directories

    • /Users/trey/Documents/GitHub/toolhive/pkg/vmcp/config/ — Platform-agnostic vMCP config model: Config struct, IncomingAuthConfig, OIDCConfig, OutgoingAuthConfig, DefaultValidator, zz_generated.deepcopy.go. Primary location for Phase 1 and Phase 3 changes.
    • /Users/trey/Documents/GitHub/toolhive/pkg/vmcp/server/ — HTTP server implementation: Config struct, Handler() method with mux registration, middleware chain. Phase 2 changes here.
    • /Users/trey/Documents/GitHub/toolhive/pkg/authserver/runner/ — EmbeddedAuthServer wrapper: NewEmbeddedAuthServer, Handler(), Close(). New RegisterHandlers method added in Phase 2.
    • /Users/trey/Documents/GitHub/toolhive/pkg/vmcp/auth/ — vMCP auth layer: factory/incoming.go creates incoming middleware from config; factory/outgoing.go creates outgoing registry; types/types.go defines strategy type constants and BackendAuthStrategy struct.
    • /Users/trey/Documents/GitHub/toolhive/cmd/vmcp/app/ — vMCP CLI entry point: commands.go contains runServe, loadAndValidateConfig, discoverBackends. Phase 2 inserts conditional AS creation and wires it to serverCfg.AuthServer.
    • /Users/trey/Documents/GitHub/toolhive/cmd/thv-operator/api/v1alpha1/ — CRD type definitions: mcpserver_types.go (contains ExternalAuthConfigRef to move), mcpexternalauthconfig_types.go (receives ExternalAuthConfigRef, already has EmbeddedAuthServerConfig), virtualmcpserver_types.go (receives AuthServerConfigRef field). Phase 1 and Phase 4 changes.
    • /Users/trey/Documents/GitHub/toolhive/cmd/thv-operator/pkg/vmcpconfig/ — CRD-to-Config converter: converter.go Convert() method. Phase 4 adds authServerConfigRef resolution step.
    • /Users/trey/Documents/GitHub/toolhive/cmd/thv-operator/controllers/ — Operator reconcilers: virtualmcpserver_controller.go handles the VirtualMCPServer reconciliation loop. Phase 4 adds cross-resource validation and AuthServerConfigValid status condition.
    • /Users/trey/Documents/GitHub/toolhive/test/e2e/ — E2E tests: Ginkgo v2 + Gomega, package e2e_test. New file vmcp_authserver_test.go goes here (Phase 4).

    Key File Details

    /Users/trey/Documents/GitHub/toolhive/pkg/vmcp/config/config.go

    • Config struct: lines 89–159. Has IncomingAuth *IncomingAuthConfig, OutgoingAuth *OutgoingAuthConfig, etc. Add AuthServer *AuthServerConfig here with omitempty JSON/YAML tags and a +optional kubebuilder comment.
    • IncomingAuthConfig struct: lines 172–181. Contains Type string, OIDC *OIDCConfig, Authz *AuthzConfig.
    • OIDCConfig struct: lines 186–218. Has Issuer, ClientID, Audience, ProtectedResourceAllowPrivateIP, InsecureAllowHTTP. Needs a new JwksAllowPrivateIP bool field for Mode B loopback OIDC discovery.
    • New structs to add: AuthServerConfig (wraps authserver.RunConfig) with +kubebuilder:object:generate=true.

    /Users/trey/Documents/GitHub/toolhive/pkg/vmcp/config/validator.go

    • DefaultValidator.Validate(): lines 31–81. Calls a series of sub-validators and accumulates errors. New validateAuthServerIntegration(cfg) call is added here.
    • validateBackendAuthStrategy(): lines 182–223. Currently allows unauthenticated, header_injection, token_exchange. Must add upstream_inject to validTypes and add a case in the switch for V-01/V-02/V-06.
    • Existing helper contains(slice []string, item string) bool at line 441 can be aliased as containsString.

    /Users/trey/Documents/GitHub/toolhive/pkg/vmcp/server/server.go

    • Config struct: lines 84–~160. Has AuthMiddleware, AuthzMiddleware, AuthInfoHandler. Add AuthServer *runner.EmbeddedAuthServer here.
    • Handler() method: line 444. The /.well-known/ catch-all is at line 485. Replace with explicit /.well-known/oauth-protected-resource registration. Add conditional AS route mounting after (or before) the well-known block.

    /Users/trey/Documents/GitHub/toolhive/pkg/authserver/runner/embeddedauthserver.go

    • EmbeddedAuthServer struct: lines 39–43.
    • Handler() method: lines 115–117. Returns the underlying server's HTTP handler, which serves all /oauth/* and /.well-known/* paths. RegisterHandlers will call e.Handler() once and register it on the provided mux at specific paths.

    /Users/trey/Documents/GitHub/toolhive/cmd/vmcp/app/commands.go

    • runServe(): lines 345–576. After cfg, err := loadAndValidateConfig(configPath) and before building serverCfg, insert: conditional runner.NewEmbeddedAuthServer(ctx, cfg.AuthServer.RunConfig) with hard failure on error, and set serverCfg.AuthServer = authServer.
    • loadAndValidateConfig(): lines 203–229. Calls config.NewValidator().Validate(cfg). No changes needed here; V-01..V-07 are invoked via Validate().

    /Users/trey/Documents/GitHub/toolhive/cmd/thv-operator/api/v1alpha1/mcpserver_types.go

    • ExternalAuthConfigRef struct: lines 632–638. Definition to be moved to mcpexternalauthconfig_types.go.

    /Users/trey/Documents/GitHub/toolhive/cmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.go

    • EmbeddedAuthServerConfig struct: lines 152–200. Defines Issuer, SigningKeySecretRefs, HMACSecretRefs, TokenLifespans, UpstreamProviders, Storage. Note: AllowedAudiences field is intentionally absent (derived by converter). Receives the moved ExternalAuthConfigRef struct.
    • MCPExternalAuthConfig.Validate(): lines 714–736. Already handles ExternalAuthTypeEmbeddedAuthServer case.

    /Users/trey/Documents/GitHub/toolhive/cmd/thv-operator/api/v1alpha1/virtualmcpserver_types.go

    • VirtualMCPServerSpec: lines 17–76. Has IncomingAuth, OutgoingAuth, Config, EmbeddingServerRef. Add AuthServerConfigRef *ExternalAuthConfigRef here with +optional marker.
    • VirtualMCPServer.Validate(): lines 364–398. Add call to r.validateAuthServerConfig() at the end (before return r.validateEmbeddingServer()).
    • Condition type constants: lines 210–228. Add ConditionTypeAuthServerConfigValid = "AuthServerConfigValid" here.

    /Users/trey/Documents/GitHub/toolhive/cmd/thv-operator/pkg/vmcpconfig/converter.go

    • Convert(): lines 68–150. After existing conversions, add a new resolution step: if vmcp.Spec.AuthServerConfigRef != nil, fetch the MCPExternalAuthConfig, verify type is embeddedAuthServer, call a new helper to convert EmbeddedAuthServerConfig → authserver.RunConfig, derive allowedAudiences from vmcp.Spec.IncomingAuth.OIDCConfig.Inline.Audience, and set config.AuthServer.

    /Users/trey/Documents/GitHub/toolhive/cmd/thv-operator/controllers/virtualmcpserver_controller.go

    • VirtualMCPServerReconciler.Reconcile(): line 114. Phase 4 adds a new reconciliation step to resolve authServerConfigRef, verify type and issuer consistency, surface AuthServerConfigValid status condition, and produce Failed phase with descriptive message on invalid config.

    /Users/trey/Documents/GitHub/toolhive/pkg/vmcp/config/zz_generated.deepcopy.go

    • Generated file. Pattern: each struct gets DeepCopyInto and DeepCopy functions. After adding AuthServerConfig with +kubebuilder:object:generate=true, regenerate with task gen or controller-gen.

    Similar Implementations

    • /Users/trey/Documents/GitHub/toolhive/pkg/vmcp/auth/factory/incoming.go — Pattern for conditionally creating a component from config (OIDC vs. local vs. anonymous). The AS creation in commands.go follows the same "check config, construct component, hard-fail on error" pattern.
    • /Users/trey/Documents/GitHub/toolhive/cmd/thv-operator/pkg/vmcpconfig/converter.go convertIncomingAuth() — Pattern for resolving a CRD reference (OIDC resolver) and mapping it to a pkg/vmcp/config type. The authServerConfigRef resolution follows this exact structure.
    • /Users/trey/Documents/GitHub/toolhive/cmd/thv-operator/controllers/virtualmcpserver_controller.go — AuthConfigError struct and status condition surfacing — template for the new AuthServerConfigValid condition.

    Test Patterns

    • /Users/trey/Documents/GitHub/toolhive/pkg/vmcp/config/validator_test.go — Current pattern for validator tests: standard Go testing package with table-driven []struct{name, cfg, wantErr, errMsg}. The RFC calls for Ginkgo DescribeTable for the new V-01..V-07 entries. Implementers can either add a separate _test.go file using Ginkgo (consistent with RFC spec) or add Go-native table-driven tests to the existing file (consistent with the current file style). If using Ginkgo, a Ginkgo test suite bootstrap is needed for the config package.
    • /Users/trey/Documents/GitHub/toolhive/test/e2e/e2e_suite_test.go — E2E suite setup: TestE2e(t) registers Ginkgo, BeforeSuite/AfterSuite manage shared config dir. New vmcp_authserver_test.go joins the existing suite automatically.
    • /Users/trey/Documents/GitHub/toolhive/test/e2e/proxy_oauth_test.go — Best reference for vMCP auth E2E tests: starts a mock OIDC server, runs a process, makes HTTP requests, uses By() for test narration, uses Eventually() for async assertions.
    • /Users/trey/Documents/GitHub/toolhive/test/e2e/oidc_mock.go — OIDCMockServer helper: reusable mock OIDC server backed by Ory Fosite. Mode B E2E tests can reuse this as an upstream IDP.

    File Naming Conventions

    • CRD type files: {resource}_types.go (e.g., mcpserver_types.go, virtualmcpserver_types.go)
    • Controller files: {resource}_controller.go
    • Converter files: converter.go (within a purpose-named package like vmcpconfig)
    • Test files: {source_file}_test.go alongside the source, or {feature}_test.go in test/e2e/
    • Generated deepcopy: zz_generated.deepcopy.go

    Related Work

    Open Issues

    • #4120 — "vMCP: add embedded authorization server" — parent epic; all 4 phase issues are sub-issues of this
    • #3924 — "Auth Server: multi-upstream provider support" (RFC-0052) — dependency; required for identity.UpstreamTokens population by the OIDC auth middleware; Phases 1–2 can be developed in parallel, full E2E requires RFC-0052 merged

    Recent PRs

    • #4125 — "Add swagger dependency parsing for external types" — recent tooling change; no conflict
    • #4129 — "Inject tool annotations into context during list filtering" — vMCP router change; no conflict with auth server work

    Known Tech Debt

    • validateBackendAuthStrategy has a TODO comment at line 191–192 of validator.go noting strategies to add later: "pass_through", "client_credentials", "oauth_proxy". Phase 3 adds upstream_inject to this list.
    • The OIDCConfig struct currently reuses ProtectedResourceAllowPrivateIP for both the protected resource metadata endpoint and JWKS/OIDC discovery endpoint. For Mode B, a distinct JwksAllowPrivateIP field is needed to allow the loopback self-referencing OIDC discovery without also enabling private IPs for the protected resource endpoint.

    Gaps & Open Questions

    1. jwksAllowPrivateIP field missing from config.OIDCConfig: The RFC's example YAML uses jwksAllowPrivateIP: true. The current config.OIDCConfig struct in pkg/vmcp/config/config.go only has ProtectedResourceAllowPrivateIP (which maps to auth.TokenValidatorConfig.AllowPrivateIP). A new dedicated JwksAllowPrivateIP bool field must be added to OIDCConfig and wired through pkg/vmcp/auth/factory/incoming.go. This should be treated as a Phase 1 or Phase 2 task.

    2. StrategyTypeUpstreamInject and UpstreamInjectConfig not yet in pkg/vmcp/auth/types/types.go: The constant and struct must be added in Phase 3 alongside the validateBackendAuthStrategy extension. The BackendAuthStrategy struct will need an UpstreamInject *UpstreamInjectConfig field. UpstreamInjectConfig needs at minimum a ProviderName string field (referenced in RFC V-02 and V-06 checks).

    3. Ginkgo suite bootstrap for pkg/vmcp/config/ package: The current validator_test.go uses standard testing, not Ginkgo. If the RFC's Ginkgo DescribeTable style is followed for V-01..V-07 tests, a Ginkgo suite bootstrap (_suite_test.go with RunSpecs) must be added to the config package. Alternatively, the new tests can follow the existing testing table-driven style — this is a style decision for the planner to resolve.

    4. OIDCConfigRef.Inline field access in converter: The converter derives allowedAudiences from vmcp.Spec.IncomingAuth.OIDCConfig.Inline.Audience. The OIDCConfigRef type in virtualmcpserver_types.go needs verification that .Inline exists and has an Audience field (this is the CRD-side type, distinct from config.OIDCConfig).

    5. Operator RBAC for MCPExternalAuthConfig get: The reconciler already has // +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=mcpexternalauthconfigs,verbs=get;list;watch at line 98 of virtualmcpserver_controller.go. No new RBAC markers needed.

    6. Phase 4 E2E test location for operator tests: The intake lists both test/e2e/chainsaw/operator/ and test/e2e/ as potential locations for the operator E2E test. The planner should clarify which location to use based on the team's current operator testing approach.

  5. tgrunnagle commented on Mar 13, 2026

    @tgrunnagle
    CollaboratorAuthor

    Planning Artifact: Architecture

    Architecture: vMCP — Add Embedded Authorization Server (RFC-0053)

    Overview

    Add an optional embedded OAuth authorization server to vMCP. When Config.AuthServer is nil
    (Mode A), behavior is byte-for-byte identical to today. When set (Mode B), the AS mounts
    OAuth/OIDC endpoints on the same mux as vMCP, drives clients through upstream IDPs, issues
    TH-JWTs, and populates identity.UpstreamTokens for downstream auth strategies.


    Mode A / Mode B

    Aspect Mode A (no AS) Mode B (with AS)
    Config.AuthServer nil *AuthServerConfig
    AS HTTP routes not mounted /oauth/, 3 /.well-known/ paths
    identity.Token external IDP JWT TH-JWT (AS-issued)
    identity.UpstreamTokens nil map keyed by provider name (RFC-0052)
    identity.Claims["tsid"] absent present (session ID)

    Invariant: all new Mode B code paths are gated on cfg.AuthServer != nil (config/validation
    layer) or s.config.AuthServer != nil (server layer). Mode A executes zero new lines.


    Code Structure

    New Code Locations

    • pkg/vmcp/config/config.go — AuthServerConfig struct; AuthServer *AuthServerConfig field on Config
    • pkg/vmcp/config/validator.go — validateAuthServerIntegration; helpers collectAllBackendStrategies, hasUpstreamProvider
    • pkg/vmcp/auth/types/types.go — StrategyTypeUpstreamInject constant; UpstreamInjectConfig struct; UpstreamInject field on BackendAuthStrategy
    • pkg/authserver/runner/embeddedauthserver.go — RegisterHandlers(mux *http.ServeMux) method (additive)
    • test/e2e/thv-operator/virtualmcp/virtualmcp_authserver_test.go — operator E2E tests (Phase 4)
    • test/e2e/vmcp_authserver_test.go — CLI/YAML-path E2E tests (Phase 4)

    Key Files to Modify

    • pkg/vmcp/config/config.go — add AuthServer *AuthServerConfig to Config; add JwksAllowPrivateIP bool to OIDCConfig
    • pkg/vmcp/config/zz_generated.deepcopy.go — regenerate after adding AuthServerConfig
    • pkg/vmcp/server/server.go — add AuthServer *runner.EmbeddedAuthServer to server Config; call RegisterHandlers conditionally; replace mux.Handle("/.well-known/", ...) catch-all (line ~485) with explicit /.well-known/oauth-protected-resource registration
    • cmd/vmcp/app/commands.go — conditional AS creation in runServe() after loadAndValidateConfig; pass authServer to serverCfg.AuthServer
    • cmd/thv-operator/api/v1alpha1/mcpserver_types.go — remove ExternalAuthConfigRef struct definition (moved)
    • cmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.go — add ExternalAuthConfigRef struct (received from above)
    • cmd/thv-operator/api/v1alpha1/virtualmcpserver_types.go — add AuthServerConfigRef *ExternalAuthConfigRef to VirtualMCPServerSpec; add ConditionTypeAuthServerConfigValid; add validateAuthServerConfig() method
    • cmd/thv-operator/pkg/vmcpconfig/converter.go — add authServerConfigRef resolution step in Convert()
    • cmd/thv-operator/controllers/virtualmcpserver_controller.go — add cross-resource validation (type check, V-04, audience guard); surface AuthServerConfigValid status condition

    Reference Implementations

    • pkg/vmcp/auth/factory/incoming.go — pattern for conditional component creation from config (check → construct → hard-fail)
    • cmd/thv-operator/pkg/vmcpconfig/converter.go convertIncomingAuth() — pattern for resolving a CRD reference to a pkg/vmcp/config type
    • cmd/thv-operator/controllers/virtualmcpserver_controller.go validateSpec() — pattern for surfacing a status condition on validation failure
    • test/e2e/thv-operator/virtualmcp/virtualmcp_external_auth_test.go — closest analog for operator auth E2E tests
    • test/e2e/proxy_oauth_test.go — pattern for vMCP auth E2E tests (mock OIDC, process start, HTTP assertions, Eventually)
    • test/e2e/oidc_mock.go — reusable OIDCMockServer for Mode B E2E upstream IDP

    API Contracts

    AuthServerConfig (new — Phase 1)

    Added to pkg/vmcp/config/config.go. Shared between the YAML config model, the server
    Config, and the operator converter.

    // AuthServerConfig wraps the auth server's RunConfig for vMCP.
    // +kubebuilder:object:generate=true
    type AuthServerConfig struct {
        RunConfig *authserver.RunConfig `json:"runConfig" yaml:"runConfig"`
    }

    Added to Config:

    // AuthServer configures the embedded OAuth authorization server.
    // nil = Mode A (no AS). non-nil = Mode B.
    // +optional
    AuthServer *AuthServerConfig `json:"authServer,omitempty" yaml:"authServer,omitempty"`

    Added to server Config in pkg/vmcp/server/server.go:

    // AuthServer is the embedded auth server. nil in Mode A.
    AuthServer *runner.EmbeddedAuthServer

    RegisterHandlers (new — Phase 2)

    New method on EmbeddedAuthServer in pkg/authserver/runner/embeddedauthserver.go.
    Consumed by pkg/vmcp/server/server.go.

    // RegisterHandlers mounts AS OAuth/OIDC endpoints on mux as unauthenticated routes.
    func (e *EmbeddedAuthServer) RegisterHandlers(mux *http.ServeMux) {
        h := e.Handler()
        mux.Handle("/oauth/", h)
        mux.Handle("/.well-known/openid-configuration", h)
        mux.Handle("/.well-known/oauth-authorization-server", h)
        mux.Handle("/.well-known/jwks.json", h)
    }

    StrategyTypeUpstreamInject + UpstreamInjectConfig (new — Phase 3)

    Added to pkg/vmcp/auth/types/types.go. Consumed by validator V-01/V-02/V-06 checks.
    Note: the upstream_inject outgoing strategy implementation is deferred to a follow-up RFC;
    only the constant, config struct, and validation are added here.

    const StrategyTypeUpstreamInject = "upstream_inject"
    
    // UpstreamInjectConfig configures the upstream inject auth strategy.
    // +kubebuilder:object:generate=true
    type UpstreamInjectConfig struct {
        // ProviderName is the upstream provider whose token is injected as Bearer.
        // Must match a provider name in authServer.runConfig.upstreams.
        ProviderName string `json:"providerName" yaml:"providerName"`
    }

    BackendAuthStrategy gains:

    // UpstreamInject contains configuration for upstream inject auth strategy.
    // Used when Type = "upstream_inject".
    UpstreamInject *UpstreamInjectConfig `json:"upstreamInject,omitempty" yaml:"upstreamInject,omitempty"`

    JwksAllowPrivateIP on OIDCConfig (new — Phase 1 or 2)

    Added to pkg/vmcp/config/config.go OIDCConfig struct. Required for Mode B in-cluster
    loopback OIDC discovery. Must be wired through pkg/vmcp/auth/factory/incoming.go
    newOIDCAuthMiddleware to auth.TokenValidatorConfig.AllowPrivateIP.

    // JwksAllowPrivateIP allows OIDC discovery and JWKS fetches to private IPs.
    // Required when IncomingAuth.OIDC.Issuer points to an in-cluster service (Mode B).
    // Default: false (private IPs rejected).
    JwksAllowPrivateIP bool `json:"jwksAllowPrivateIP,omitempty" yaml:"jwksAllowPrivateIP,omitempty"`

    Validation Rules (Phase 3)

    New function validateAuthServerIntegration(cfg *Config) error called at the end of
    DefaultValidator.Validate() in pkg/vmcp/config/validator.go.

    ID Condition Severity Path
    V-01 upstream_inject used but AuthServer == nil error YAML startup + operator
    V-02 upstream_inject ProviderName not in AuthServer.RunConfig.Upstreams error YAML startup + operator
    V-03 token_exchange used when AS is incoming auth provider warning (slog.Warn) YAML startup only
    V-04 AuthServer.RunConfig.Issuer ≠ IncomingAuth.OIDC.Issuer error YAML startup + operator
    V-05 NewEmbeddedAuthServer internal config validation fails error YAML startup
    V-06 upstream_inject ProviderName is empty string error YAML startup + operator
    V-07 IncomingAuth.OIDC.Audience not in AuthServer.RunConfig.AllowedAudiences error YAML startup only (K8s: by construction)

    K8s path note for V-07: The converter derives allowedAudiences from
    spec.incomingAuth.oidcConfig.inline.audience, making V-07 structurally satisfied. The
    reconciler checks post-conversion only as a defense-in-depth empty-audience guard.


    Integration Points

    pkg/authserver/runner.EmbeddedAuthServer

    Already implemented. Existing public API:

    • NewEmbeddedAuthServer(ctx, *authserver.RunConfig) (*EmbeddedAuthServer, error)
    • Handler() http.Handler
    • Close() error
    • IDPTokenStorage() storage.UpstreamTokenStorage
    • UpstreamTokenRefresher() storage.UpstreamTokenRefresher

    The new RegisterHandlers method is purely additive. No existing callers are affected.

    pkg/authserver.RunConfig

    The YAML-path serializable config consumed by EmbeddedAuthServer. Key fields relevant to
    validation: Issuer string, AllowedAudiences []string, Upstreams []UpstreamRunConfig
    (each has Name string).

    Operator Converter (cmd/thv-operator/pkg/vmcpconfig/converter.go)

    Convert() starts with config := vmcp.Spec.Config.DeepCopy() and then applies explicit
    overrides. The new step follows the existing convertIncomingAuth pattern:

    1. If vmcp.Spec.AuthServerConfigRef != nil, fetch the MCPExternalAuthConfig by name.
    2. Verify spec.type == "embeddedAuthServer".
    3. Convert EmbeddedAuthServerConfig → authserver.RunConfig.
    4. Derive allowedAudiences from vmcp.Spec.IncomingAuth.OIDCConfig.Inline.Audience.
    5. Set config.AuthServer = &vmcpconfig.AuthServerConfig{RunConfig: runConfig}.

    Operator Reconciler (cmd/thv-operator/controllers/virtualmcpserver_controller.go)

    Validation is performed inside runValidations() before ensureAllResources(). The new
    AuthServerConfigValid condition follows the existing AuthConfigError / validateSpec
    pattern using statusManager.SetCondition(...). Invalid config produces Failed phase with
    a descriptive message; reconciliation does not proceed to resource creation.

    identity.UpstreamTokens (RFC-0052 dependency)

    identity.UpstreamTokens population — extracting tsid from TH-JWT and loading upstream
    tokens from AS storage — is defined and implemented by RFC-0052 (#3924). Phases 1–2 can be
    developed in parallel with RFC-0052; full E2E integration test of the auth flow requires
    RFC-0052 to be merged.


    HTTP Route Table (after Phase 2)

    Unauthenticated (mounted directly on mux):
      /health, /ping, /readyz, /status, /api/backends/health   (unchanged)
      /metrics                                                  (unchanged, if telemetry)
      /.well-known/oauth-protected-resource                     (explicit — replaces catch-all)
      /.well-known/openid-configuration                         (Mode B only)
      /.well-known/oauth-authorization-server                   (Mode B only)
      /.well-known/jwks.json                                    (Mode B only)
      /oauth/                                                   (Mode B only)
    
    Authenticated (auth middleware wraps):
      / (catch-all)                                             (MCP endpoint, unchanged)
    

    The /.well-known/ catch-all at server.go:485 is replaced with an explicit
    /.well-known/oauth-protected-resource registration. Behavioral impact: none — the old
    catch-all only served that single path; all other /.well-known/ paths already returned 404.


    CRD Changes (Phase 1 + 4)

    ExternalAuthConfigRef move

    Struct definition moves from mcpserver_types.go:632 to mcpexternalauthconfig_types.go.
    Same v1alpha1 package — all existing callers (v1alpha1.ExternalAuthConfigRef) are
    unaffected. No API surface change.

    VirtualMCPServerSpec new field

    // AuthServerConfigRef references an MCPExternalAuthConfig of type "embeddedAuthServer".
    // Must exist in the same namespace. nil = Mode A.
    // +optional
    AuthServerConfigRef *ExternalAuthConfigRef `json:"authServerConfigRef,omitempty"`

    New status condition type

    const ConditionTypeAuthServerConfigValid = "AuthServerConfigValid"

    After CRD changes, run:

    task operator-generate   # regenerates zz_generated.deepcopy.go
    task operator-manifests  # regenerates CRD YAML
    task crdref-gen          # regenerates CRD docs
    

    Core Principles

    1. Mode A nil-gate: Every Mode B code path must start with if cfg.AuthServer != nil or
      if s.config.AuthServer != nil. Mode A must pass all existing tests unchanged.
      (see pkg/vmcp/auth/factory/incoming.go for the creation pattern)

    2. Hard fail, no silent fallback: If NewEmbeddedAuthServer returns an error in Mode B,
      the process must exit with that error. Never silently fall back to Mode A.
      (see cmd/vmcp/app/commands.go runServe() pattern)

    3. Converter derives, validator checks: In the K8s path, allowedAudiences is derived
      by the converter (never stored in the CRD). In the YAML path, it is explicit and validated
      by V-07. Do not add allowedAudiences as a field on EmbeddedAuthServerConfig in the CRD.

    4. Additive only: AuthServerConfig, RegisterHandlers, UpstreamInjectConfig are all
      additive — no existing struct fields are removed or renamed, no existing method signatures
      change.

    5. omitempty on all optional fields: AuthServer, AuthServerConfigRef, and
      JwksAllowPrivateIP all use omitempty so existing configs round-trip without changes.


    Constraints

    • RFC-0052 dependency: identity.UpstreamTokens population requires RFC-0052 (Auth Server: multi-upstream provider support #3924).
      Phase 4 E2E tests that verify the full token flow must wait for RFC-0052 to land.
    • jwksAllowPrivateIP gap: OIDCConfig currently lacks this field. It must be added in
      Phase 1 or 2 and wired through pkg/vmcp/auth/factory/incoming.go before Mode B in-cluster
      OIDC loopback works.
    • StrategyTypeUpstreamInject gap: The constant and UpstreamInjectConfig do not yet
      exist in pkg/vmcp/auth/types/types.go. They must be added in Phase 3 alongside validator
      changes; the actual outgoing strategy implementation is deferred to a follow-up RFC.
    • Ginkgo vs. testing in pkg/vmcp/config/: Current validator_test.go uses standard
      testing. If Phase 3 adds Ginkgo DescribeTable tests, a Ginkgo suite bootstrap
      (_suite_test.go with RunSpecs) must also be added to the config package. Alternatively,
      use the existing testing table-driven style to avoid the bootstrap.
    • Issuer string exact match: V-04 and V-07 use exact string comparison. No URL
      normalization is applied. Operators must use the identical string in both the AS config and
      the incoming auth config.
    • Redis TLS is service-mesh-only: RedisStorageConfig does not expose TLS fields in the
      CRD. TLS in transit is the cluster service mesh's responsibility.

    Out of Scope

    • upstream_inject outgoing strategy implementation (deferred to follow-up RFC)
    • Hot-reload of AS configuration (requires pod restart)
    • Multi-upstream IDP support (defined by RFC-0052, depended on but not re-specified here)
    • Step-up auth signaling
    • CLI-path upstream token swap (pkg/auth/upstreamswap)
  6. jhrozek commented on Mar 27, 2026

    @jhrozek
    Contributor

    subtasks done, closing

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

Metadata

Metadata

Assignees

Labels

authenticationauthorizationenhancementgovmcp

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions