Repository navigation
Description
Overview
This epic tracks the implementation of RFC-0052: adding multi-upstream Identity Provider (IDP) support to the embedded OAuth authorization server (pkg/authserver/). The auth server currently hard-rejects more than one upstream provider configuration; this feature lifts that restriction by adding a providerName dimension to the storage layer and introducing a sequential authorization chain so a single auth server instance can acquire tokens from multiple upstream IDPs in one flow.
Background
Multi-upstream IDP support is a prerequisite for the full vMCP auth story. Without it, backends requiring credentials from different IDPs (e.g., a corporate SSO token for internal services and a GitHub token for public APIs) cannot be served by a single auth server instance. The RFC specifies a server-driven sequential authorization chain, eager token loading into Identity.UpstreamTokens at middleware time, and full backward compatibility for existing single-upstream deployments.
Task Breakdown
| Task ID | Title | Depends On | GitHub Issue # |
|---|---|---|---|
| TASK-001 | Phase 1: Storage Layer | — | #4136 |
| TASK-002 | Phase 2: Handler and Server Layer | TASK-001 | #4137 |
| TASK-003 | Phase 3: Config and Operator | TASK-001 | #4138 |
| TASK-004 | Phase 4: Identity Enrichment and upstreamswap Middleware | TASK-001 | #4139 |
Acceptance Criteria
- A single auth server instance accepts and validates configuration with multiple upstream OAuth2/OIDC providers
- Sequential authorization chain drives the user through each configured upstream in turn; the client makes one
GET /oauth/authorizeand receives one authorization code - All upstream tokens are eagerly loaded into
Identity.UpstreamTokensat auth middleware time -
upstreamswapmiddleware reads upstream tokens fromIdentity.UpstreamTokenswith no hidden storage calls - Single-upstream deployments continue to work with no configuration changes required
- Redis breaking change (key pattern) and
ProviderIdentitybreaking change documented in migration guide - All linked task issues completed
References
- RFC-0052: https://github.com/stacklok/toolhive-rfcs/blob/main/rfcs/THV-0052-multi-upstream-idp-authserver.md
- Related stacklok-epics issue: https://github.com/stacklok/stacklok-epics/issues/251
Activity
[-]Authserver: multi-upstream provider support with scope-based routing[/-][+]Authserver: multi-upstream provider support[/+][-]Authserver: multi-upstream provider support[/-][+]Auth Server: multi-upstream provider support[/+]tgrunnagle commentedon Mar 13, 2026
Intake: RFC-0052 Multi-Upstream IDP Support in the Embedded Auth Server
Original Requirements
Implement RFC-0052: Multi-Upstream IDP Support in the Embedded Auth Server. The auth server (
pkg/authserver/) currently hard-rejects configuration with more than one upstream Identity Provider (IDP). This RFC lifts that restriction by:providerNamedimension to theUpstreamTokenStorageinterface so multiple providers' tokens can coexist per session without overwriting each other.Identity.UpstreamTokensat the auth middleware layer so downstream components (upstreamswapmiddleware, outgoing auth strategies) receive tokens as explicit struct fields — no context extraction, no hidden storage calls.A placeholder epic issue already exists at #3924. One sub-issue must be created per implementation phase (4 total).
Existing Documentation
/Users/trey/Documents/GitHub/toolhive/docs/proposals/THV-0052-multi-upstream-idp-authserver.md— Primary design document. Covers problem statement, proposed solution (high-level and detailed design), API changes, data model changes, sequential authorization chain flow, security considerations, compatibility notes, 4-phase implementation plan, detailed testing strategy, and documentation requirements.Clarifying Questions & Answers
Issue Style
Repository & Project
stacklok/toolhive(primary — issues created here):/Users/trey/Documents/GitHub/toolhive— Main ToolHive service; all code changes for this RFC land here (pkg/authserver/,pkg/auth/,pkg/runner/,cmd/thv-operator/)Scope & Boundaries
/oauth/authorizeflow the server drives sequential upstream redirects transparently; after all providers are satisfied the authorization code is issued. On each subsequent MCP request, the auth middleware populatesIdentity.UpstreamTokens(keyed by provider name) soupstreamswapand outgoing auth strategies can inject the correct upstream token for each backend.UpstreamTokenStorageinterface: addproviderNametoStoreUpstreamTokensandGetUpstreamTokens; addGetAllUpstreamTokensbulk-read method; updateDeleteUpstreamTokensto remain session-scopedsessionID → providerName → entry); implementGetAllUpstreamTokens; update eviction TTL tomax(accessToken.ExpiresAt, refreshToken.ExpiresAt){prefix}upstream:{sessionID}:{providerName}; session index SET at{prefix}upstream:idx:{sessionID}; Lua scripts for atomic store and delete; SMEMBERS+MGET forGetAllUpstreamTokensPendingAuthorization: addUpstreamProviderNameandSessionIDfieldsupstreamfield withupstreams map[string]upstream.OAuth2Provider+upstreamOrder []string; implement sequential chain in authorize and callback handlers;nextMissingUpstreamhelperpkg/authserver/config.go: removelen > 1rejection; add name-uniqueness and explicit-name requirements for multi-upstreampkg/runner/): addlen > 1upstream rejection to preserve single-upstream invariant for CLI proxy runnerMCPServer,MCPRemoteProxy): movelen > 1restriction fromMCPExternalAuthConfigCRD-level validation to workload-specific webhooks, soVirtualMCPServercan reference multi-upstream auth configsIdentitystruct: addUpstreamTokens map[string]string; add to redaction logicGetAllUpstreamTokensafter JWT validation; populateIdentity.UpstreamTokensupstreamswapmiddleware: addProviderNameconfig field; read fromIdentity.UpstreamTokensinstead of calling storage; removeStorageGetterdependencypkg/runner/middleware.go(addUpstreamSwapMiddleware): deriveProviderNamefromUpstreams[0].Name, falling back to"default"mockgenthv proxy) and corresponding K8s workload types (MCPServer,MCPRemoteProxy)Technical Context
pkg/authserver/storage/—UpstreamTokenStorageinterface, in-memory backend, Redis backend,PendingAuthorizationtypes, storage mockspkg/authserver/server/handlers/—Handlerstruct, authorize handler, callback handler,nextMissingUpstreamlogicpkg/authserver/server_impl.go— upstream map/slice construction from configpkg/authserver/config.go— validation changespkg/auth/—Identitystruct, auth middleware enrichmentpkg/auth/upstreamswap/—Config, middleware handlerpkg/runner/— proxy runner config validation,addUpstreamSwapMiddlewarecmd/thv-operator/api/v1alpha1/—MCPExternalAuthConfigand workload webhook admission validationSessionIDmust be generated server-side only; never accepted from client input (security invariant)PendingAuthorizationleg must use a freshInternalStatefor CSRF protectionhandleCallbackto the primary to avoid replication-lag false restarts (existing go-redis default behavior; do not enableReadOnlyrouting)ProviderIdentityrecords stored withproviderID = "oauth2"will not match after upgrade — documented breaking changeDependencies & Integration
upstreamswapmiddleware — readsIdentity.UpstreamTokensafter this change instead of calling storage directlyIdentity.UpstreamTokensAcceptance & Verification
Identity.UpstreamTokensis populated for all upstream providers on every authenticated MCP requestupstreamswapmiddleware injects the correct upstream token without calling storage directlyMCPServer/MCPRemoteProxyoperator webhooks continue to reject multi-upstream configurationsVirtualMCPServeroperator resource can reference an auth config with multiple upstreamsGetAllUpstreamTokensreturns all (including expired) and empty map for unknown session, eviction TTL usesmax(access.ExpiresAt, refresh.ExpiresAt)SessionIDgenerated and threaded through legs,nextMissingUpstreamreturns correct next, all-satisfied path issues auth code, freshInternalStateper leg, full sequential chain integration test (authorize → leg 1 callback → leg 2 callback → auth code → both tokens present)len > 1no longer rejected at auth server level; name uniqueness enforced; proxy runner rejectslen > 1; operator webhooks forMCPServer/MCPRemoteProxyrejectlen > 1butVirtualMCPServerdoes notGetAllUpstreamTokenscalled whentsidclaim present; expired tokens included; empty map when notsidupstreamswap: reads fromIdentity.UpstreamTokens; returns 401 when token absent;StorageGetterno longer injectedstateparameter rejected;SessionIDnot read from client query paramsDry Run Mode
Additional Notes
Phase Breakdown
The RFC defines 4 implementation phases with explicit ordering constraints:
Phase 1: Storage Layer — Foundation phase. Must land first. Changes
UpstreamTokenStorageinterface, updates both storage backends (memory + Redis), addsPendingAuthorizationfields, regenerates mocks, updates all existing call sites withinpkg/authserver/. All subsequent phases depend on the new interface signatures.Phase 2: Handler and Server Layer — Depends on Phase 1 (new storage interface). Replaces single-upstream handler with multi-upstream map + sequential chain logic. Includes full integration test of the end-to-end chain.
Phase 3: Config and Operator — Depends on Phase 1 (storage interface must already accept multiple providers for config to allow them). Updates config validation to lift the
len > 1authserver-library restriction, moves the restriction to proxy runner and operator webhooks.Phase 4: Identity Enrichment and
upstreamswapMiddleware — Depends on Phase 1 (GetAllUpstreamTokensmust exist). EnrichesIdentitystruct, updates auth middleware andupstreamswapmiddleware. Can be developed in parallel with Phases 2 and 3 after Phase 1 lands, though sequential ordering is recommended for clarity.Issue Framing
Each sub-issue should:
docs/proposals/THV-0052-multi-upstream-idp-authserver.mdBreaking Changes
Two documented breaking changes exist and must be called out in each relevant phase issue:
{prefix}upstream:{sessionID}become unreachable; sessions require re-authentication after upgrade.ProviderIdentityrecords stored withproviderID = "oauth2"will not match post-upgrade; affected users get freshUserrecords.tgrunnagle commentedon Mar 13, 2026
Research: RFC-0052 Multi-Upstream IDP Support in the Embedded Auth Server
Local Repository Clones
/Users/trey/Documents/GitHub/toolhive— stacklok/toolhive (primary); all code changes for this RFC land hereReference Documentation
In Repository
docs/proposals/THV-0052-multi-upstream-idp-authserver.md— Primary RFC. Full problem statement, high-level and detailed design, API changes, data model changes, sequential authorization chain pseudocode, security considerations, compatibility notes, 4-phase implementation plan with file-level change lists, detailed testing strategy table, and documentation requirements.docs/arch/11-auth-server-storage.md— Architecture doc for auth server storage. Documents current storage design, Redis Sentinel model, key design (includingDeriveKeyPrefixhash-tag format), consistency model (Lua scripts vs. pipelines vs. best-effort commands), TTL table, and CRD configuration shape.CONTRIBUTING.md— Contribution guidelines: DCO/Signed-off-by requirement, squash-merge policy, review requirements, testing requirements, PR size limits (~1000 lines).CLAUDE.md— Engineering conventions: SPDX license headers, mock generation viago.uber.org/mock(mockgen), business logic inpkg/, CLI as thin wrappers, table-driven tests preferred,lint-fixoverlint, conventional commits NOT used, PR titles under 70 chars imperative mood.cmd/thv-operator/CLAUDE.md— Operator-specific: after CRD modifications runtask operator-generate,task operator-manifests,task crdref-gen(from insidecmd/thv-operator/).docs/arch/09-operator-architecture.md— Operator architecture (CRD and controller design).docs/arch/10-virtual-mcp-architecture.md— vMCP architecture (primary consumer of multi-upstream feature).External URLs
fosite.OAuth2Provider, storage interfaces (AuthorizeCodeStorage,AccessTokenStorage, etc.), andcomposebuilder used by the auth server.PendingAuthorization.UpstreamPKCEVerifier/Challenge.AllowedAudiencesvalidation for MCP compliance.ClientRegistryinterface.Organizational Standards
Coding Conventions
task license-fixto add them automatically;task license-checkto verify.CLAUDE.mdexample).fmt.Errorfwith%wto preserve error chains; useerrors.Is()/errors.As()for inspection.slogfor structured logging; silent success principle (no INFO logging on happy paths).Review Process
Signed-off-bytrailer (DCO).feat:,fix:, etc.).Documentation Standards
docs/arch/; update when adding or changing components, transports, middleware, CRDs, or RunConfig schema.cmd/thv-operator/api/v1alpha1/: runtask operator-generate,task operator-manifests,task crdref-gen(from insidecmd/thv-operator/).task docs.Testing Requirements
*_test.go); prefer table-driven tests.go.uber.org/mock(mockgen); place inmocks/subdirectory; regenerate withmockgen.//go:build integrationbuild tag;task testexcludes them by default.require.NoError(t, err)(testify) overt.Fatal.t.TempDir()+filepath.EvalSymlinks()on macOS to resolve symlinks).math.MaxInt16) in tests to avoid collisions.test/e2e/test the compiled binary; they are the primary testing strategy for CLI commands.Architecture & Design
System Architecture
The embedded OAuth authorization server (
pkg/authserver/) is a full OAuth2/OIDC AS built on the Fosite framework. It sits in front of upstream Identity Providers and issues its own JWTs (TH-JWTs) that include atsid(token session ID) claim linking the JWT to stored upstream tokens.Current single-upstream flow:
GET /oauth/authorize.PendingAuthorization(withInternalStatefor CSRF andUpstreamPKCEVerifier/UpstreamNonce), redirects user to the single configured upstream IDP.GET /oauth/callbackwith a code.UpstreamTokenskeyed bysessionID, resolves/creates the internalUser, issues fosite authorization code, redirects to client'sredirect_uri.tsidclaim) viaPOST /oauth/token.upstreamswapmiddleware usestsidto callInProcessService.GetValidTokens(ctx, sessionID)(storage lookup with transparent refresh viaUpstreamTokenRefresher), injects upstream access token into outgoing request.RFC-0052 change — sequential multi-upstream chain:
GET /oauth/authorize(same as before — single request).SessionID(the TSID for this chain), redirects toupstreamOrder[0].pending.UpstreamProviderName, callsGetAllUpstreamTokens(ctx, sessionID)to determinenextMissingUpstream, either redirects to the next upstream or issues the authorization code.GET /oauth/authorizeand receives exactly one authorization code; all intermediate upstream redirects are transparent.GetAllUpstreamTokensonce (bulk read) and populatesIdentity.UpstreamTokens map[string]string(providerName → access token).upstreamswapreadsidentity.UpstreamTokens[cfg.ProviderName]directly — no storage call, no context extraction.Established Patterns
AuthorizeCodeStorage,AccessTokenStorage,RefreshTokenStorage,TokenRevocationStorage,PKCERequestStorage; ToolHive addsUpstreamTokenStorage,PendingAuthorizationStorage,ClientRegistry,UserStorage. The compositeStorageinterface embeds all of them (pkg/authserver/storage/types.go).pkg/runner/middleware.go:GetSupportedMiddlewareFactories()with string-keyed map; each factory receives*types.MiddlewareConfig+types.MiddlewareRunner.UpstreamTokenscopies inmemory.go:StoreUpstreamTokensandGetUpstreamTokens).MULTI/EXEC) for batched non-atomic operations. Individual commands with best-effort cleanup for revocation.storage.ErrNotFound,storage.ErrExpired,storage.ErrAlreadyExists,storage.ErrInvalidBinding— always check witherrors.Is().pkg/runner.RunConfigpattern.+kubebuilder:validation:XValidation) as the admission-time layer, plusValidate()methods on the types for runtime defense-in-depth.MCPExternalAuthConfigis the exemplar of this pattern (seecmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.go).Prior Decisions
tsidclaim name: Uses"tsid"instead of"sid"to avoid confusion with OIDC Session Management spec (pkg/auth/upstreamtoken/types.go:TokenSessionIDClaimKey).{ns:name}in key prefix ensures slot co-location if ever migrated to Cluster, but has no functional effect in Sentinel mode.requirepassnot supported. Redis ACL users (Redis 6+) provide fine-grained access control.types.gointerface:mockgen -source=types.gogeneratespkg/authserver/storage/mocks/mock_storage.go. Must regenerate whenever theStorageinterface or any sub-interface changes.pkg/authserver/config.go:validateUpstreams()withif len(c.Upstreams) > 1and (2)cmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.go:787-788insidevalidateEmbeddedAuthServer(). RFC-0052 removes (1) from the library layer and moves the restriction to the consumer layers (proxy runner and operator workload types).InProcessServicewithsingleflight: Token refresh operations are deduplicated viagolang.org/x/sync/singleflightto prevent concurrent refresh races for the same session. Refresh timeout is 30s, detached from the triggering request context (pkg/auth/upstreamtoken/service.go).tokens.ExpiresAt + DefaultRefreshTokenTTL. RFC-0052 changes this tomax(accessToken.ExpiresAt, refreshToken.ExpiresAt)to prevent premature eviction of tokens that still have a valid refresh token.API Contracts (Interfaces Affected by RFC-0052)
Current
UpstreamTokenStorageinterface (pkg/authserver/storage/types.go):Post-RFC-0052
UpstreamTokenStorageinterface (from RFC):Current
PendingAuthorizationstruct (relevant fields):ClientID,RedirectURI,State,PKCEChallenge,PKCEMethod,Scopes,InternalState,UpstreamPKCEVerifier,UpstreamNonce,CreatedAt.New fields:
UpstreamProviderName stringandSessionID string.Identitystruct (pkg/auth/identity.go) — new field to add:UpstreamTokens map[string]string(providerName → access token). Must also be added toMarshalJSON()redaction logic (token values must be redacted, though provider names are safe to log).upstreamswap.Config(pkg/auth/upstreamswap/middleware.go) — new field:ProviderName string. TheServiceGettertype and its use inCreateMiddlewareandcreateMiddlewareFuncwill be removed.Known Constraints
SessionIDinPendingAuthorizationis generated server-side by the authorize handler and stored only server-side. It must never be accepted from any client-supplied query parameter or form field.InternalStatefor the upstreamstateparameter (independent CSRF protection per redirect). The usedPendingAuthorizationmust be deleted before creating the next leg's pending entry.handleCallbackreads (GetAllUpstreamTokensfornextMissingUpstream) must go to the primary — do not enableReadOnlyrouting on the go-redis client. Standard go-redis failover client routes reads to master by default; this must not be changed.providerNameis non-empty at entry points.pkg/authserver/config.go) to the consumer layer (pkg/runner/).Codebase Analysis
Relevant Directories
pkg/authserver/storage/—UpstreamTokenStorageinterface (types.go), in-memory backend (memory.go), Redis backend (redis.go), Redis key helpers (redis_keys.go), storage config (config.go), mocks (mocks/mock_storage.go).pkg/authserver/server/handlers/—Handlerstruct (handler.go),AuthorizeHandler(authorize.go),CallbackHandler(callback.go),TokenHandler(token.go),UserResolver(user.go), discovery/JWKS (discovery.go).pkg/authserver/server/—AuthorizationServerConfig(provider.go);session/— fosite session type.pkg/authserver/—Config/RunConfig/UpstreamRunConfigstructs andvalidateUpstreams()(config.go);server_impl.go—newServer()andcreateProvider();server.go—Serverinterface.pkg/authserver/upstream/—OAuth2Providerinterface and implementations (OIDCProviderImpl,BaseOAuth2Provider).pkg/auth/—Identitystruct (identity.go);TokenValidator.MiddlewareandclaimsToIdentity(token.go);GetAuthenticationMiddleware(utils.go);context.go(context helpersWithIdentity/IdentityFromContext).pkg/auth/upstreamswap/—Middleware,Config,ServiceGetter,createMiddlewareFunc(middleware.go).pkg/auth/upstreamtoken/—Serviceinterface andTokenSessionIDClaimKey(types.go);InProcessService.GetValidTokenswith singleflight refresh (service.go); sentinel errors (errors.go).pkg/runner/—GetSupportedMiddlewareFactories()andPopulateMiddlewareConfigs()(middleware.go);Runner.GetUpstreamTokenService()and embedded auth server wiring (runner.go);RunConfigstruct (includesEmbeddedAuthServerConfig,UpstreamSwapConfig).pkg/transport/types/—MiddlewareRunnerinterface (includesGetUpstreamTokenService()) (transport.go); mocks (mocks/mock_transport.go).cmd/thv-operator/api/v1alpha1/—MCPExternalAuthConfigCRD types includingEmbeddedAuthServerConfig,UpstreamProviderConfig,AuthServerStorageConfig(mcpexternalauthconfig_types.go);MCPServertypes withExternalAuthConfigRef(mcpserver_types.go);MCPRemoteProxytypes withExternalAuthConfigRef(mcpremoteproxy_types.go).cmd/thv-operator/pkg/controllerutil/—authserver.go(converts CRDEmbeddedAuthServerConfigtoauthserver.RunConfig; callsvalidateUpstreamProviders— this is the controller-side validation entry point).Similar Implementations (Reference Patterns)
pkg/authserver/storage/memory.golines 685–777 — CurrentStoreUpstreamTokens,GetUpstreamTokens,DeleteUpstreamTokens. Shows defensive copy pattern,timedEntrywrapper, eviction TTL calculation, and error wrapping pattern. Phase 1 will transformupstreamTokens map[string]*timedEntry[*UpstreamTokens]to a nested mapmap[string]map[string]*timedEntry[*UpstreamTokens].pkg/authserver/storage/redis.go— Lua script patterns, SADD/SMEMBERS set-index pattern, JSON serialization,nullMarkerfor nil values,warnOnCleanupErrfor best-effort secondary index cleanup.pkg/authserver/storage/redis_keys.go— Key generation helpersredisKey,redisProviderKey,redisSetKey. Phase 1 addsredisUpstreamKey(prefix, sessionID, providerName string).cmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.go—validateEmbeddedAuthServer()andvalidateUpstreamProvider()are the exemplar pattern for CRD-levelValidate()methods. Phase 3 adds aValidate()method (or a validation helper) onMCPServerandMCPRemoteProxytypes following this same pattern.pkg/auth/upstreamswap/middleware.go— CurrentcreateMiddlewareFuncpattern: extractstsidfromidentity.Claims, callsserviceGetter()at request time, callssvc.GetValidTokens(ctx, tsid). Phase 4 replaces this with a directidentity.UpstreamTokens[cfg.ProviderName]read.Key Call Sites for Phase 4 (Identity Enrichment)
JWT validation + Identity construction —
pkg/auth/token.go,TokenValidator.Middlewaremethod (around line 1067):The
GetAllUpstreamTokenscall must be inserted betweenclaimsToIdentity(line ~1087) andWithIdentity(line ~1096). TheTokenValidatorstruct will need access tostorage.UpstreamTokenStorage— this requires either adding a field toTokenValidatoror threading storage throughGetAuthenticationMiddlewareinpkg/auth/utils.go.GetAuthenticationMiddlewarewiring —pkg/auth/utils.goline 64: createsNewTokenValidator(ctx, *oidcConfig)and returnsjwtValidator.Middleware. TheUpstreamTokenStoragedependency for enrichment needs to be threaded through here.CreateMiddleware(auth factory) —pkg/auth/middleware.goline 48: called fromPopulateMiddlewareConfigsinpkg/runner/middleware.go. Receivestypes.MiddlewareRunner; the runner has access toIDPTokenStorage()viar.embeddedAuthServer.IDPTokenStorage().GetUpstreamTokenService()removal fromupstreamswap—pkg/transport/types/transport.goline 86:GetUpstreamTokenService() func() upstreamtoken.Serviceis on theMiddlewareRunnerinterface. After Phase 4, this method may no longer be needed byupstreamswap. Assess whether it is still needed by any other middleware before removing.Test Patterns
pkg/authserver/storage/memory_test.go— Unit tests for memory storage; test helpers useNewMemoryStorage(). Pattern: call storage methods directly, check return values and errors.pkg/authserver/storage/redis_test.go— Unit tests usingminiredis(in-process Redis mock);redis_integration_test.gouses//go:build integrationwith real Redis via testcontainers.pkg/authserver/server/handlers/helpers_test.go— Shared test fixtures for handler tests:testStorageState, mock upstream provider implementations, test token helpers.pkg/authserver/integration_test.go— Full end-to-end integration test of the auth server (authorize → callback → token → validation). Phase 2 adds a multi-upstream sequential chain test here.pkg/auth/upstreamswap/middleware_test.go— TestsCreateMiddlewarefactory andcreateMiddlewareFunc; usesMockMiddlewareRunnerfrompkg/transport/types/mocks/.File Naming Conventions
pkg/authserver/storage/mocks/mock_storage.go— regenerated viamockgen -destination=mocks/mock_storage.go -package=mocks -source=types.go [interface names]pkg/transport/types/mocks/mock_transport.gocmd/thv-operator/api/v1alpha1/follow<resourcename>_types.goconvention.Related Work
Open Issues
Known Tech Debt
pkg/authserver/storage/redis.go:warnOnCleanupErr.TokenValidatorcurrently has no access toUpstreamTokenStorage; threading this dependency for Phase 4 requires a small refactor ofTokenValidator,GetAuthenticationMiddleware, and theauth.CreateMiddlewarefactory.GetUpstreamTokenService()onMiddlewareRunnerinterface exists solely forupstreamswap. After Phase 4 this dependency is removed fromupstreamswap; assess whether the interface method should be retained or removed (requires updating the mock).Gaps & Open Questions
TokenValidatorstorage dependency (Phase 4): TheTokenValidatorstruct inpkg/auth/token.gocurrently takes no storage dependency. To callGetAllUpstreamTokensafter JWT validation, either: (a) addUpstreamTokenStorageas an optional field onTokenValidator(nil = no enrichment, consistent with non-embedded-auth-server deployments), or (b) add a post-validation enrichment hook. The RFC does not prescribe the exact wiring; this is an implementation decision for the Phase 4 planner. Option (a) is preferred given the existing patterns in the codebase.GetUpstreamTokenService()interface retention (Phase 4): Afterupstreamswapno longer calls storage directly,GetUpstreamTokenService()onMiddlewareRunnermay have no remaining callers. If removed,pkg/transport/types/transport.gointerface andpkg/transport/types/mocks/mock_transport.gomust be updated. Confirm no other middleware depends on it before removing.Operator workload-type
Validate()methods (Phase 3): NeitherMCPServernorMCPRemoteProxycurrently has aValidate()method in their*_types.gofiles. Phase 3 must add validation to both types (following theMCPExternalAuthConfig.Validate()pattern) that rejectsembeddedAuthServerauth configs referencing more than one upstream provider. The validation needs to resolve the referencedMCPExternalAuthConfig— clarify whether this validation lives in the CRDValidate()method (without cluster access) or in the controller's reconcile loop (with cluster access to fetch the referenced config). Given thatMCPExternalAuthConfig.Validate()validates the config itself and theMCPServer/MCPRemoteProxyonly hold a reference, the controller's reconcile logic (similar to how it checksConditionTypeExternalAuthConfigValidated) is the more practical location.ProviderIdentityprovider ID after RFC-0052: Currently the callback storesproviderID = string(h.upstream.Type())which resolves to"oidc"or"oauth2". After RFC-0052, it should storeproviderID = pending.UpstreamProviderName(the configured name, e.g.,"github","corporate-idp"). This is a documented breaking change for existing Redis deployments. The Phase 2 handler implementation must usepending.UpstreamProviderNamenotupstream.Type()as the providerID inh.userResolver.ResolveUser.tgrunnagle commentedon Mar 13, 2026
Architecture: RFC-0052 Multi-Upstream IDP Support in the Embedded Auth Server
Overview
Extend the embedded OAuth authorization server (
pkg/authserver/) to support multiple upstream IDPs in a single instance by adding aproviderNamedimension to the storage layer, driving a server-side sequential authorization chain across all configured upstreams, and eagerly loading all upstream tokens intoIdentity.UpstreamTokensat auth middleware time. Single-upstream deployments are fully backward compatible.Implementation Phases
Phases must land in dependency order. Phases 2 and 3 may be developed in parallel after Phase 1.
upstreamswapMiddlewareCode Structure
Key Files to Modify
Phase 1 — Storage Layer
pkg/authserver/storage/types.go—UpstreamTokenStorageinterface new signatures;PendingAuthorizationtwo new fieldspkg/authserver/storage/memory.go— nested mapmap[string]map[string]*timedEntry;GetAllUpstreamTokens; TTL fixpkg/authserver/storage/redis.go— new key pattern; session index SET; Lua scripts;GetAllUpstreamTokenspkg/authserver/storage/redis_keys.go— addredisUpstreamKeyhelperpkg/authserver/storage/mocks/mock_storage.go— regenerate viamockgenPhase 2 — Handler and Server Layer
pkg/authserver/server/handlers/handler.go— replaceupstreamfield withupstreams map+upstreamOrder; updateNewHandlerpkg/authserver/server/handlers/authorize.go— chain start: generateSessionID, redirect toupstreamOrder[0]pkg/authserver/server/handlers/callback.go—nextMissingUpstream; chain continuation or auth code issuance; usepending.UpstreamProviderNameasproviderIDinResolveUserpkg/authserver/server_impl.go— build upstream map and ordered slice from configPhase 3 — Config and Operator
pkg/authserver/config.go— removelen > 1guard; add explicit-name rule; removeGetUpstream()pkg/runner/(config validation) — addlen > 1upstream rejection for proxy runnercmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.go— removelen > 1fromvalidateEmbeddedAuthServer()cmd/thv-operator/(reconciler forMCPServerandMCPRemoteProxy) — addlen > 1upstream rejection in controller reconcile logic (not in CRDValidate(); controller has cluster access to fetch referencedMCPExternalAuthConfig)Phase 4 — Identity Enrichment and
upstreamswappkg/auth/identity.go— addUpstreamTokens map[string]string; updateMarshalJSONredactionpkg/auth/token.go— insertGetAllUpstreamTokenscall betweenclaimsToIdentity(~line 1087) andWithIdentity(~line 1096); add optionalUpstreamTokenStoragefield toTokenValidatorpkg/auth/utils.go— threadUpstreamTokenStoragethroughGetAuthenticationMiddleware; wire from runnerpkg/auth/middleware.go—CreateMiddlewarereceives storage dependency via runnerpkg/auth/upstreamswap/middleware.go— addProviderNametoConfig; removeStorageGetterandserviceGetter; readidentity.UpstreamTokens[cfg.ProviderName]directlypkg/runner/middleware.go—addUpstreamSwapMiddlewarederivesProviderNamefromUpstreams[0].Name(fallback"default")pkg/transport/types/transport.go— assess whetherGetUpstreamTokenService()onMiddlewareRunnercan be removed after Phase 4; update mock if removedReference Implementations
pkg/authserver/storage/memory.golines 685–777 — defensive copy pattern,timedEntrywrapper, eviction logicpkg/authserver/storage/redis.go— Lua script atomicity, SADD/SMEMBERS set-index,nullMarker,warnOnCleanupErrpkg/authserver/storage/redis_keys.go—redisKey,redisProviderKey,redisSetKeyconventionscmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.go—validateEmbeddedAuthServer()/validateUpstreamProvider()pattern for CRDValidate()methodspkg/auth/upstreamswap/middleware_test.go— pattern for testing middleware factory andcreateMiddlewareFuncpkg/authserver/integration_test.go— full end-to-end auth server chain test; Phase 2 adds multi-upstream case hereAPI Contracts
UpstreamTokenStorageInterface (Phase 1 — all other phases depend on this)All callers of
StoreUpstreamTokensandGetUpstreamTokenswithinpkg/authserver/must be updated when this lands.PendingAuthorizationNew Fields (Phase 1)HandlerStruct and Constructor (Phase 2)nextMissingUpstreamHelper (Phase 2 — internal tohandlerspackage)IdentityNew Field (Phase 4)Provider names are safe to log; token values must be redacted in
MarshalJSON.upstreamswap.ConfigChange (Phase 4)Integration Points
Storage Backends
pkg/authserver/storage/memory.go):upstreamTokenschanges frommap[string]*timedEntrytomap[string]map[string]*timedEntry(outer key = sessionID, inner key = providerName). Eviction TTL changes tomax(accessToken.ExpiresAt, refreshToken.ExpiresAt).pkg/authserver/storage/redis.go): New key pattern{prefix}upstream:{sessionID}:{providerName}; session index SET at{prefix}upstream:idx:{sessionID}.StoreUpstreamTokensuses Lua script for atomic key + SADD.DeleteUpstreamTokensuses Lua for atomic SMEMBERS + DEL all keys + DEL index.GetAllUpstreamTokensuses SMEMBERS + MGET (two round-trips).Auth Middleware Enrichment (Phase 4)
Insertion point in
pkg/auth/token.go(TokenValidator.Middleware):TokenValidatorgains an optional fieldupstreamStorage storage.UpstreamTokenStorage(nil = no enrichment, for non-embedded-AS deployments). Threading path:CreateMiddlewareinpkg/auth/middleware.go→GetAuthenticationMiddlewareinpkg/auth/utils.go→NewTokenValidator.The runner provides storage via
r.embeddedAuthServer.IDPTokenStorage()(already accessible viarunner.go).Operator Restriction Migration (Phase 3)
Current location of
len > 1guard:cmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.go:787invalidateEmbeddedAuthServer()Target after Phase 3:
MCPExternalAuthConfig.Validate()— the config resource itself becomes multi-upstream capableMCPServerandMCPRemoteProxy(has cluster access to fetch and inspect the referencedMCPExternalAuthConfig; mirrors existingConditionTypeExternalAuthConfigValidatedpattern)VirtualMCPServeris intentionally exempt — it is the primary consumer of multi-upstreamSequential Authorization Chain Flow
sequenceDiagram participant C as OAuth Client participant AS as Auth Server participant S as UpstreamTokenStorage participant P1 as Upstream Provider 1 participant P2 as Upstream Provider 2 C->>AS: GET /oauth/authorize AS->>AS: generate SessionID, pending for upstreamOrder[0] AS->>C: 302 → Provider 1 /authorize C->>P1: authorize P1->>AS: GET /oauth/callback?code=…&state=internalState1 AS->>S: StoreUpstreamTokens(sessionID, "provider-1", tokens) AS->>S: GetAllUpstreamTokens(sessionID) → nextMissingUpstream = "provider-2" AS->>AS: create next PendingAuthorization (same SessionID, fresh InternalState) AS->>C: 302 → Provider 2 /authorize C->>P2: authorize P2->>AS: GET /oauth/callback?code=…&state=internalState2 AS->>S: StoreUpstreamTokens(sessionID, "provider-2", tokens) AS->>S: GetAllUpstreamTokens(sessionID) → nextMissingUpstream = "" (all satisfied) AS->>C: 302 → redirect_uri?code=authCode C->>AS: POST /oauth/token (exchange authCode) AS->>C: TH-JWT (tsid=SessionID) Note over C,P2: Subsequent MCP requests C->>AS: MCP request + TH-JWT AS->>S: GetAllUpstreamTokens(SessionID) AS->>AS: identity.UpstreamTokens populated AS->>AS: upstreamswap reads identity.UpstreamTokens["provider-1"]Core Principles
Phase 1 is the foundation: All other phases break at compile time without the new
UpstreamTokenStoragesignatures. Land Phase 1 first; update every call site inpkg/authserver/before merging.SessionIDis server-side only: Generated by the authorize handler usingrand.Text(); stored only inPendingAuthorization; never read from any client-supplied request field. Enforce this invariant in code review.Fresh
InternalStateper chain leg: The usedPendingAuthorizationmust be deleted withDeletePendingAuthorizationbefore the next leg's entry is created. This prevents CSRF replay across legs.Enrichment is non-fatal: If
GetAllUpstreamTokensfails in the auth middleware, log at WARN and continue with an emptyUpstreamTokensmap. The downstream backend will report its own error. Do not fail the entire request.No token values in logs or errors:
Identity.UpstreamTokensvalues,UpstreamTokens.AccessToken,RefreshToken, andIDTokenmust never appear in log fields, error messages, or HTTP responses. Provider names are safe to log.Read primary in Redis callbacks:
handleCallbackmust use a Redis client that routes reads to the primary (default go-redis failover behavior). Do not enableReadOnlyrouting; replication lag would cause false chain restarts.Defensive copies: Both memory and Redis backends must make defensive copies on read and write (existing pattern in
memory.go:StoreUpstreamTokens). Preserve this when adding the nested map.Validate
providerNameat storage entry points: BothStoreUpstreamTokensandGetUpstreamTokensmust reject emptyproviderNamewith a clear error before touching storage.Constraints
thv proxyand K8s workload typesMCPServer/MCPRemoteProxycontinue to enforce exactly one upstream. This invariant moves from the library layer (pkg/authserver/config.go) to the consumer layer (pkg/runner/and operator reconciler).{prefix}upstream:{sessionID}(old pattern) are unreachable after upgrade. Sessions require re-authentication. Document in Phase 1 PR.ProviderIdentitybreaking change: Records stored withproviderID = "oauth2"(fromupstream.Type()) will not match after Phase 2 switches topending.UpstreamProviderName. Affected users get newUserrecords. Document in Phase 2 PR.GetUpstreamTokenService()onMiddlewareRunner: After Phase 4,upstreamswapno longer calls this. Assess before removing the interface method — if no other middleware uses it, remove frompkg/transport/types/transport.goand regeneratepkg/transport/types/mocks/mock_transport.go.singleflightinInProcessServiceremains; multi-provider refresh races are out of scope.Identity.UpstreamTokensas-is. Backends that receive an expired token will fail with their own error. Refresh is deferred to a later RFC.Out of Scope
MCPServer/MCPRemoteProxyK8s workload types