Repository navigation
Description
Overview
This epic implements the upstream_inject outgoing auth strategy for vMCP (RFC-0054). The strategy reads upstream IDP access tokens from identity.UpstreamTokens (a map[string]string populated by the embedded authorization server in Mode B) and injects them as Authorization: Bearer headers on outgoing backend requests. It also extends token_exchange with an optional SubjectProviderName field for RFC 8693 subject resolution from upstream provider tokens.
Background
RFC-0052 extended the auth middleware to populate identity.UpstreamTokens after TH-JWT validation, and RFC-0053 wired the embedded AS into vMCP. However, no outgoing auth strategy currently consumes those upstream tokens — backends requiring upstream provider credentials (e.g., a GitHub MCP server needing a GitHub access token) cannot receive them. This epic completes the pipeline by adding the upstream_inject strategy and the startup validation rules V-01, V-02, and V-06 that guard against misconfiguration.
Task Breakdown
| Task ID | Title | Depends On | GitHub Issue # |
|---|---|---|---|
| TASK-001 | Phase 1: Core types and sentinel | — | #4144 |
| TASK-002 | Phase 2: Strategy implementations | TASK-001 | #4145 |
| TASK-003 | Phase 3: Startup validation | TASK-001 | #4147 |
| TASK-004 | Phase 4: CRD and converter | TASK-001 | #4146 |
Acceptance Criteria
-
upstream_injectstrategy readsidentity.UpstreamTokens[providerName]and injectsAuthorization: Beareron outgoing backend requests -
ErrUpstreamTokenNotFoundsentinel is defined and returned (wrapped with%w) when the provider's token is absent -
TokenExchangeStrategyuses the upstream provider token as subject whenSubjectProviderNameis set - Startup validation V-01 (no AS present), V-02 (provider not in AS upstream list), and V-06 (empty providerName) fail fast with descriptive errors
- Kubernetes CRD supports
type: upstreamInjectwithUpstreamInjectSpec.providerName - CRD
TokenExchangeConfigsupportssubjectProviderNamefield -
UpstreamInjectConverterconverts CRD resources toBackendAuthStrategy - All new types have SPDX headers, kubebuilder markers, and deepcopy regenerated
- All linked task issues completed
References
- RFC-0054: https://github.com/stacklok/toolhive-rfcs/blob/main/rfcs/THV-0054-vmcp-upstream-inject-strategy.md
- RFC-0052 (multi-upstream IDP support): Auth Server: multi-upstream provider support #3924
- RFC-0053 (embedded AS in vMCP): vMCP: add embedded authorization server #4120
Activity
[-]vMCP: implement embeddedAuthServer outgoing auth strategy[/-][+]vMCP: implement upstream_inject outgoing auth strategy[/+]tgrunnagle commentedon Mar 13, 2026
Intake: vMCP Upstream Inject Outgoing Auth Strategy (RFC-0054)
Original Requirements
Implement RFC-0054: vMCP Upstream Inject Outgoing Auth Strategy. This RFC implements the
upstream_injectoutgoing auth strategy for the vMCP component. The strategy reads a named upstream provider's access token fromidentity.UpstreamTokens(populated by the auth middleware after TH-JWT validation in Mode B) and injects it as anAuthorization: Bearerheader on outgoing backend requests. It also adds an optionalsubjectProviderNameenhancement totoken_exchangefor RFC 8693 subject resolution from upstream tokens.The implementation is broken into 4 phases:
A placeholder epic issue exists at #3925. One GitHub issue should be created per phase, linked as sub-issues of #3925.
Existing Documentation
RFC-0054: vMCP Upstream Inject Outgoing Auth Strategy—/Users/trey/Documents/GitHub/toolhive/docs/proposals/THV-0054-vmcp-upstream-inject-strategy.md— Full RFC covering problem statement, detailed design (type changes, new strategy, factory changes, startup validation rules, CRD changes, converters), security considerations, testing strategy, and implementation plan. Status: Draft.RFC-0052(multi-upstream IDP support) — referenced by RFC-0054 as a prerequisite; definesidentity.UpstreamTokens map[string]stringpopulated by auth middleware after TH-JWT validation.RFC-0053(embedded AS in vMCP) — referenced by RFC-0054 as a prerequisite; wires the embedded authorization server into vMCP so upstream tokens are acquired during the OAuth flow. Declares validation rules V-01 through V-07 and scaffoldsvalidateAuthServerIntegration. Proposed docs at/Users/trey/Documents/GitHub/toolhive/docs/proposals/THV-0053-vmcp-embedded-authserver.md.Clarifying Questions & Answers
Issue Style
Repository & Project
stacklok/toolhive(primary — issues created here):/Users/trey/Documents/GitHub/toolhive— main ToolHive repository; contains all source code affected by this RFC (pkg/vmcp/, cmd/thv-operator/, etc.)Scope & Boundaries
upstream_injectoutgoing auth strategy is fully implemented, tested, and wired end-to-end — from the Go types layer through the Kubernetes CRD converter — enabling vMCP operators to configure backends that receive upstream IDP access tokens as Bearer authorization headers on outgoing requests.StrategyTypeUpstreamInjectconstant,UpstreamInjectConfigstruct,UpstreamInjectfield onBackendAuthStrategy, andErrUpstreamTokenNotFoundsentinel topkg/vmcp/auth/types/types.goSubjectProviderNamefield toTokenExchangeConfiginpkg/vmcp/auth/types/types.gozz_generated.deepcopy.goUpstreamInjectStrategyinpkg/vmcp/auth/strategies/upstream_inject.goTokenExchangeStrategy.Authenticate()and internaltokenExchangeConfigforSubjectProviderNameinpkg/vmcp/auth/strategies/tokenexchange.goupstream_injectinpkg/vmcp/auth/factory/outgoing.gopkg/vmcp/config/validator.goExternalAuthTypeUpstreamInject,UpstreamInjectSpec, and CRD validation tocmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.goSubjectProviderNameto the CRD'sTokenExchangeConfigstructUpstreamInjectConverterinpkg/vmcp/auth/converters/upstream_inject.goTokenExchangeConverter.ConvertToStrategy()to populateSubjectProviderNameUpstreamInjectConverterinNewRegistry()ErrUpstreamTokenNotFoundsentinel is defined here but the intercept/redirect flow is a separate RFCdocs/arch/02-core-concepts.md,docs/vmcp-auth.md) — these are documentation tasks and not included in the 4 phase issuesTechnical Context
pkg/vmcp/auth/types/— type definitions and sentinel errorpkg/vmcp/auth/strategies/—upstream_inject.go(new),tokenexchange.go(modified)pkg/vmcp/auth/factory/— outgoing auth registry registrationpkg/vmcp/config/— startup validation rules V-01, V-02, V-06cmd/thv-operator/api/v1alpha1/— CRD types (mcpexternalauthconfig_types.go)pkg/vmcp/auth/converters/—upstream_inject.go(new),tokenexchange.go(modified)zz_generated.deepcopy.go— regenerated after type changes in Phase 1upstream_injectis Bearer-only; non-Bearer formats useheader_injectionidentity.UpstreamTokensin contextgo.uber.org/mock(gomock) for any mocks; mock files go inmocks/subdirectories// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc./// SPDX-License-Identifier: Apache-2.0)+kubebuilder:object:generate=trueand+gendocmarkers required on new types for codegenDependencies & Integration
identity.UpstreamTokensto be defined and populatedidentity.UpstreamTokensis populated at request time; also definescfg.AuthServer.RunConfigreferenced in V-01/V-02 validationerrors.Is(err, ErrUpstreamTokenNotFound)to trigger step-up flows; defined in a future RFCtoken_exchangestrategy;SubjectProviderNameenhancement uses upstream tokens as the RFC 8693 subjectAcceptance & Verification
upstream_injectstrategy correctly readsidentity.UpstreamTokens[providerName]and injects asAuthorization: Beareron outgoing requestsErrUpstreamTokenNotFoundreturned (and wrappable viaerrors.Is()) when the token is absent or emptytoken_exchangewithSubjectProviderNameuses the upstream token as RFC 8693 subject instead ofidentity.Tokentype: upstreamInjectwithUpstreamInjectSpec.providerName;MCPExternalAuthConfigTokenExchangeConfigCRD struct exposessubjectProviderNameupstream_inject_test.go: 9 cases (happy path, token not found, empty token, health check bypass, nil strategy/config, Validate cases)tokenexchange_test.go: 3 additions (SubjectProviderName used, SubjectProviderName missing provider, regression for existing behavior)validator_test.go: 4 additions (V-01 negative, V-02 negative, V-06 negative, positive)upstream_inject_converter_test.go: 3 cases (ConvertToStrategy valid/nil, ResolveSecrets pass-through)Dry Run Mode
Issue Labels
authentication,authorization,enhancement,go,vmcpPhase Issue Definitions
Phase 1: Core types and sentinel (no behavior change)
Files changed:
pkg/vmcp/auth/types/types.go— addStrategyTypeUpstreamInjectconstant,UpstreamInjectConfigstruct,UpstreamInject *UpstreamInjectConfigfield onBackendAuthStrategy,ErrUpstreamTokenNotFoundsentinel,SubjectProviderName stringfield onTokenExchangeConfigzz_generated.deepcopy.go— regenerate after type additions (task gen)Acceptance criteria:
zz_generated.deepcopy.gois regenerated and consistent with the new typesPhase 2: Strategy implementations
Files changed:
pkg/vmcp/auth/strategies/upstream_inject.go— new file implementingUpstreamInjectStrategy(stateless, Bearer-only,ErrUpstreamTokenNotFoundpropagation, health check bypass,Validate())pkg/vmcp/auth/strategies/tokenexchange.go— updateAuthenticate()and internaltokenExchangeConfigstruct forSubjectProviderNamepkg/vmcp/auth/factory/outgoing.go— registerStrategyTypeUpstreamInject/NewUpstreamInjectStrategy()pkg/vmcp/auth/strategies/upstream_inject_test.go— new test file, 9 table-driven casespkg/vmcp/auth/strategies/tokenexchange_test.go— 3 new table entriesAcceptance criteria:
UpstreamInjectStrategy.Authenticate()setsAuthorization: Bearer <token>when token found inidentity.UpstreamTokensErrUpstreamTokenNotFound(wrapped with%w) when provider absent or token emptyTokenExchangeStrategy.Authenticate()usesidentity.UpstreamTokens[SubjectProviderName]as subject whenSubjectProviderNameis set; falls back toidentity.Tokenwhen unset (no regression)upstream_injectregistered in outgoing auth registryPhase 3: Startup validation
Files changed:
pkg/vmcp/config/validator.go— addupstream_injectcase tovalidateAuthServerIntegrationimplementing V-01 (no AS configured), V-02 (providerName not in AS upstream list), V-06 (empty providerName)pkg/vmcp/config/validator_test.go— 4 new table-driven entries (V-01 negative, V-02 negative, V-06 negative, positive case)Acceptance criteria:
upstream_injectbackend configured butAuthServer == nil; error message references "no authServer configured"providerNameis not in the AS upstream list; error message references the unknown provider nameproviderNameis empty; error message references "non-empty providerName"upstream_injectbackend with valid AS and matching provider returnsnilPhase 4: CRD and converter
Files changed:
cmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.go— addExternalAuthTypeUpstreamInjectconstant,UpstreamInjectSpecstruct,UpstreamInject *UpstreamInjectSpecfield onMCPExternalAuthConfigSpec, CRD validation (spec/type equivalence check, per-type validation for non-emptyproviderName); addSubjectProviderName stringto the CRD'sTokenExchangeConfigstructpkg/vmcp/auth/converters/upstream_inject.go— new file implementingUpstreamInjectConverter(stateless, no secrets,ConvertToStrategy,ResolveSecretspass-through)pkg/vmcp/auth/converters/tokenexchange.go(or equivalent converter file) — updateConvertToStrategy()to populateSubjectProviderNameNewRegistry()— registerUpstreamInjectConverterpkg/vmcp/auth/converters/upstream_inject_test.go— new test file, 3 casespkg/vmcp/auth/converters/tokenexchange_test.go— regression tests for updatedTokenExchangeConverterAcceptance criteria:
MCPExternalAuthConfigCRD acceptstype: upstreamInjectwithupstreamInject.providerNameupstreamInjectspec relative to typeUpstreamInjectConverter.ConvertToStrategy()producesBackendAuthStrategy{Type: "upstream_inject", UpstreamInject: {ProviderName: ...}}UpstreamInjectConverter.ResolveSecrets()returns the strategy unchangedTokenExchangeConverter.ConvertToStrategy()populatesSubjectProviderNamefrom the CRD fieldAdditional Notes
tgrunnagle commentedon Mar 13, 2026
Research: vMCP Upstream Inject Outgoing Auth Strategy (RFC-0054)
Overview
This document captures existing architectural context, coding standards, and design documentation
relevant to the RFC-0054 implementation epic. It is intended for use by downstream planning agents
to produce well-grounded phase issues.
Local Repository Clones
/Users/trey/Documents/GitHub/toolhiveOrganizational Coding Standards
Sources:
CLAUDE.md,CONTRIBUTING.md,docs/cli-best-practices.mdSPDX License Headers
All Go files must have SPDX headers at the top:
Use
task license-checkto verify;task license-fixto add automatically. CI enforces this onall PRs (ignores generated files: mocks, testdata, vendor,
*.pb.go,zz_generated*.go).Commit and PR Style
feat:,fix:,chore:, etc.).github/pull_request_template.md(Summary / Type of change / Test plan)Codegen Markers on New Types
New structs that participate in deep-copy generation (typically those in
pkg/vmcp/auth/types/and operator API types) need both:
After adding or modifying types in
pkg/vmcp/auth/types/, run:This regenerates
pkg/vmcp/auth/types/zz_generated.deepcopy.go.After modifying CRD types in
cmd/thv-operator/api/v1alpha1/, run:task operator-generate task operator-manifests # inside cmd/thv-operator/: task crdref-genTesting Requirements
*_test.go)go.uber.org/mock(gomock) for mocks; mock files go inmocks/subdirectories; generatewith
mockgenrequire.NoError(t, err)(fromgithub.com/stretchr/testify) rather thant.Fatalt.TempDir()paths; on macOS, resolvesymlinks with
filepath.EvalSymlinks(dir)when validators reject symlinked pathsmath.MaxInt16) in tests to avoid port conflictspkg/business logicGo Coding Style
mutation across multiple
ifbranchesfmt.Errorfwith%wto preserve error chains; useerrors.Is()/errors.As()forerror inspection
Existing Architecture Documentation
vMCP Auth Architecture
Strategy Interface
Defined in
pkg/vmcp/auth/auth.go:DefaultOutgoingAuthRegistry(inpkg/vmcp/auth/outgoing_registry.go) enforces thatRegisterStrategy(name, strategy)requiresname == strategy.Name(), ensuring all registeredstrategies are self-describing.
Existing Strategy Constants and Types
File:
pkg/vmcp/auth/types/types.goCurrent strategy type constants:
BackendAuthStrategyis the union-discriminated config struct:TokenExchangeConfig(abridged):zz_generated.deepcopy.go(also inpkg/vmcp/auth/types/) currently coversBackendAuthStrategy,HeaderInjectionConfig, andTokenExchangeConfig. After Phase 1 addsUpstreamInjectConfig,task genmust be re-run to regenerate this file.Existing Strategy Implementations
All strategies are in
pkg/vmcp/auth/strategies/:unauthenticated.go— no-op, always returns nil; health check: always passesheader_injection.go— injects static header fromBackendAuthStrategy.HeaderInjection; appliesto all requests including health checks; validates with CRLF-injection prevention
tokenexchange.go— RFC 8693 token exchange; cachesExchangeConfigper backend config (notper user); health check path uses client credentials grant if
ClientID/ClientSecretare set,otherwise skips auth; uses
auth.IdentityFromContext(ctx)to obtainidentity.TokenThe new
upstream_inject.gostrategy (Phase 2) will mirrorunauthenticated.goinstructurally stateless design but read from
identity.UpstreamTokens[providerName].Factory Registration
File:
pkg/vmcp/auth/factory/outgoing.goPhase 2 adds one more
registry.RegisterStrategy(authtypes.StrategyTypeUpstreamInject, strategies.NewUpstreamInjectStrategy())call here. No signature changes.Startup Validator
File:
pkg/vmcp/config/validator.goDefaultValidator.Validate(cfg *Config)orchestrates all validation. The methodvalidateBackendAuthStrategycurrently validatestoken_exchangeandheader_injectiontype-specific requirements and lists allowed strategy types:
Phase 3 of this RFC adds
authtypes.StrategyTypeUpstreamInjectto this list and implements V-01,V-02, and V-06 in a new
validateAuthServerIntegrationcase. The validator is called at processstartup (YAML path) and by the operator reconciler (Kubernetes path).
CRD Auth Types
File:
cmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.goCurrent
ExternalAuthTypeconstants:MCPExternalAuthConfigSpecholds optional typed spec fields for each auth type (one field pertype, keyed by
Type). Phase 4 addsExternalAuthTypeUpstreamInjectandUpstreamInject *UpstreamInjectSpec.The CEL admission rules use the pattern:
Phase 4 adds a matching CEL rule for
upstreamInject. The GoValidate()method onMCPExternalAuthConfigmirrors this with a nil-equality check:The CRD's
TokenExchangeConfigstruct (distinct frompkg/vmcp/auth/types/TokenExchangeConfig)also needs
SubjectProviderName stringadded in Phase 4.Converter Registry
File:
pkg/vmcp/auth/converters/interface.goStrategyConverterinterface:NewRegistry()currently registers:Phase 4 adds
r.Register(mcpv1alpha1.ExternalAuthTypeUpstreamInject, &UpstreamInjectConverter{}).The
TokenExchangeConverter.ConvertToStrategy()currently does not populateSubjectProviderNamebecause that field does not exist yet in either the CRD or the types package. Phase 4 updates it
to pass
tokenExchange.SubjectProviderNamethrough.Identity and UpstreamTokens (RFC-0052 Prerequisite)
File:
pkg/auth/identity.goIdentityis the primary authenticated-principal struct. As of the current codebase, it has:RFC-0052 will add
UpstreamTokens map[string]stringto this struct (keyed by upstream providername, populated by the auth middleware from
GetAllUpstreamTokens(tsid)in session storage). Thisfield is the direct dependency of
UpstreamInjectStrategy.Authenticate(). Until RFC-0052 merges,the strategy cannot be tested end-to-end but the types and factory wiring can be implemented.
auth.IdentityFromContext(ctx)is defined inpkg/auth/context.goand is already used byTokenExchangeStrategy—UpstreamInjectStrategywill use the same pattern.Health Check Detection
File:
pkg/vmcp/health/monitor.goAll strategies call
health.IsHealthCheck(ctx)at the top ofAuthenticate()to bypassper-user auth for health probes.
UpstreamInjectStrategyreturnsnilon health check (noheader set), consistent with all other strategies.
Design Documentation
RFC-0054 (Primary RFC for this Epic)
Location:
docs/proposals/THV-0054-vmcp-upstream-inject-strategy.mdStatus: Draft (2026-03-10). Contains the complete design including:
pkg/vmcp/auth/types/types.goUpstreamInjectStrategyincluding health check bypass and error wrappingTokenExchangeStrategy.Authenticate()forSubjectProviderNamepkg/vmcp/auth/factory/outgoing.gocmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.goUpstreamInjectConverterimplementationRFC-0052 (Prerequisite — Multi-Upstream IDP Support)
Location:
docs/proposals/THV-0052-multi-upstream-idp-authserver.mdStatus: Draft (2026-03-09). Defines:
Identity.UpstreamTokens map[string]string— the field RFC-0054 reads at request timeGetAllUpstreamTokens(sessionID)bulk-read onUpstreamTokenStorageIdentity.UpstreamTokensfrom session storage after TH-JWT validationRFC-0054 Phase 1 can be implemented while RFC-0052 is pending (type additions are independent).
Phase 2 will compile but cannot be fully tested end-to-end until RFC-0052 merges and
identity.UpstreamTokensis populated in the middleware.RFC-0053 (Prerequisite — Embedded AS in vMCP)
Location:
docs/proposals/THV-0053-vmcp-embedded-authserver.mdStatus: Draft (2026-03-10). Defines:
validateAuthServerIntegrationscaffold inpkg/vmcp/config/validator.go— RFC-0054 Phase 3 fills in theupstream_injectcasecfg.AuthServer.RunConfigfield (referenced by V-01/V-02 validation)#4142) createsvalidateAuthServerIntegrationthat RFC-0054 Phase 3 adds toKey Code Pointers by Phase
Phase 1 — Core Types and Sentinel
StrategyTypeUpstreamInject = "upstream_inject"constantpkg/vmcp/auth/types/types.goUpstreamInjectConfigstruct (withProviderName string)pkg/vmcp/auth/types/types.goUpstreamInject *UpstreamInjectConfigfield toBackendAuthStrategypkg/vmcp/auth/types/types.goErrUpstreamTokenNotFound = errors.New(...)sentinel varpkg/vmcp/auth/types/types.goSubjectProviderName stringfield toTokenExchangeConfigpkg/vmcp/auth/types/types.gopkg/vmcp/auth/types/zz_generated.deepcopy.goNew struct needs
// +kubebuilder:object:generate=trueand// +gendocmarkers.zz_generated.deepcopy.gocurrently coversBackendAuthStrategy,HeaderInjectionConfig, andTokenExchangeConfig. After addingUpstreamInjectConfig(which only has scalar fields, so itsDeepCopyIntowill be a trivial*out = *in), and theUpstreamInject *UpstreamInjectConfigpointer field on
BackendAuthStrategy, the generated file will also includeUpstreamInjectConfigdeep-copy functions and a nil-check pointer copy for the new field.
Phase 2 — Strategy Implementations
UpstreamInjectStrategystruct implementingauth.Strategypkg/vmcp/auth/strategies/upstream_inject.go(new)TokenExchangeStrategy.Authenticate()andtokenExchangeConfigforSubjectProviderNamepkg/vmcp/auth/strategies/tokenexchange.goStrategyTypeUpstreamInjectin outgoing auth registrypkg/vmcp/auth/factory/outgoing.gopkg/vmcp/auth/strategies/upstream_inject_test.go(new)pkg/vmcp/auth/strategies/tokenexchange_test.goKey implementation note for
UpstreamInjectStrategy.Authenticate():health.IsHealthCheck(ctx)frompkg/vmcp/health/monitor.goat the topauth.IdentityFromContext(ctx)frompkg/auth/context.goto get the identityidentity.UpstreamTokens[providerName]— both missing key and empty value →ErrUpstreamTokenNotFoundfmt.Errorf("upstream_inject provider %q: %w", providerName, authtypes.ErrUpstreamTokenNotFound)req.Header.Set("Authorization", "Bearer "+token)on successTokenExchangeStrategychanges: the internaltokenExchangeConfigstruct gainsSubjectProviderName string.In
parseTokenExchangeConfig, populate it fromstrategy.TokenExchange.SubjectProviderName.In
Authenticate(), resolvesubjectTokenfromidentity.UpstreamTokens[config.SubjectProviderName]when
SubjectProviderName != "", then passsubjectTokentocreateUserConfig.buildCacheKeydoes NOT include
SubjectProviderName(the server-level cache template is subject-agnostic).Phase 3 — Startup Validation
upstream_injectcase tovalidateAuthServerIntegration(V-01, V-02, V-06)pkg/vmcp/config/validator.goStrategyTypeUpstreamInjectto thevalidTypesslice invalidateBackendAuthStrategypkg/vmcp/config/validator.gopkg/vmcp/config/validator_test.goValidation rules:
upstream_injectbackend present butcfg.AuthServer == nil→ error referencing "no authServer configured"strategy.UpstreamInject.ProviderNamenot in AS upstream provider list → error referencing the unknown provider namestrategy.UpstreamInject.ProviderName == ""→ error referencing "non-empty providerName"RFC-0053 Phase 3 (#4142) scaffolds
validateAuthServerIntegration; RFC-0054 Phase 3 adds theupstream_injectcase to that function's switch statement.Phase 4 — CRD and Converter
ExternalAuthTypeUpstreamInject ExternalAuthType = "upstreamInject"constantcmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.goUpstreamInjectSpecstruct withProviderName stringcmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.goUpstreamInject *UpstreamInjectSpecfield toMCPExternalAuthConfigSpeccmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.goupstreamInjecttype equivalencecmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.goupstreamInjectto+kubebuilder:validation:EnumonTypefieldcmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.goproviderNametoValidate()cmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.goSubjectProviderName stringto CRDTokenExchangeConfigstructcmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.goUpstreamInjectConverter(stateless, no secrets)pkg/vmcp/auth/converters/upstream_inject.go(new)TokenExchangeConverter.ConvertToStrategy()to populateSubjectProviderNamepkg/vmcp/auth/converters/token_exchange.goUpstreamInjectConverterinNewRegistry()pkg/vmcp/auth/converters/interface.gopkg/vmcp/auth/converters/upstream_inject_test.go(new)TokenExchangeConverterpkg/vmcp/auth/converters/token_exchange_test.goAfter CRD type changes run operator codegen:
task operator-generate task operator-manifests # inside cmd/thv-operator/: task crdref-genKey Conventions to Follow
Error Wrapping Pattern
All strategies wrap sentinel errors with
%wforerrors.Is()compatibility:Health Check Pattern
Every
Authenticate()implementation begins with a health check guard:UpstreamInjectStrategyreturnsnilwith no header set (no upstream token at probe time).No Token Values in Output
Hard security requirement throughout all phases:
ErrUpstreamTokenNotFound(provider name and backend name only)Strategy Self-Registration Pattern
DefaultOutgoingAuthRegistry.RegisterStrategy(name, strategy)enforcesname == strategy.Name().New strategies must return their constant from
Name():Type Discriminated Structs Pattern
BackendAuthStrategyfollows a discriminated union pattern: theTypestring selects whichoptional config pointer is populated. Startup validation and strategy
Validate()check that theexpected pointer is non-nil. CRD CEL rules enforce spec/type equivalence at admission time.
Issue Style Guidelines
Based on the intake document and review of existing issues:
Phase N: <short imperative description> (RFC-0054)authentication,authorization,enhancement,go,vmcpDependency Order
Phase 4 can proceed immediately after Phase 1 lands, since it only depends on the types package.
It does not require RFC-0052 or RFC-0053 to compile or unit-test.
Gaps and Notes
identity.UpstreamTokensdoes not yet exist inpkg/auth/identity.go— it is added by RFC-0052.Phase 1 and Phase 4 can be implemented and unit-tested without it; Phase 2 unit tests can
populate a mock identity struct directly once the field exists.
validateAuthServerIntegrationdoes not yet exist inpkg/vmcp/config/validator.go— it isscaffolded by RFC-0053 Phase 3. Phase 3 of this RFC adds the
upstream_injectcase to it.RFC-0053's test specification.
docs/arch/02-core-concepts.md,docs/vmcp-auth.md) areexplicitly out of scope per the intake document and should not be included in phase issues.
tgrunnagle commentedon Mar 13, 2026
Architecture: vMCP Upstream Inject Outgoing Auth Strategy (RFC-0054)
Overview
This epic adds the
upstream_injectoutgoing auth strategy to vMCP. The strategy reads a namedupstream provider's access token from
identity.UpstreamTokens(populated by RFC-0052's authmiddleware) and injects it as
Authorization: Beareron outgoing backend requests. It also addsan optional
subjectProviderNamefield totoken_exchangefor RFC 8693 subject resolution fromupstream tokens. Implementation spans four ordered phases: types, strategy, validation, CRD/converter.
Code Structure
New Files
pkg/vmcp/auth/strategies/upstream_inject.go—UpstreamInjectStrategyimplementation (Phase 2)pkg/vmcp/auth/strategies/upstream_inject_test.go— 9 table-driven test cases (Phase 2)pkg/vmcp/auth/converters/upstream_inject.go—UpstreamInjectConverterimplementation (Phase 4)pkg/vmcp/auth/converters/upstream_inject_test.go— 3 test cases (Phase 4)Modified Files
pkg/vmcp/auth/types/types.go— add constant, struct, sentinel, two fields (Phase 1)pkg/vmcp/auth/types/zz_generated.deepcopy.go— regenerated viatask gen(Phase 1)pkg/vmcp/auth/strategies/tokenexchange.go— addSubjectProviderNamepath toAuthenticate()andtokenExchangeConfig(Phase 2)pkg/vmcp/auth/strategies/tokenexchange_test.go— 3 new table entries (Phase 2)pkg/vmcp/auth/factory/outgoing.go— registerupstream_injectstrategy (Phase 2)pkg/vmcp/config/validator.go— addupstream_injecttovalidTypes, implement V-01/V-02/V-06 (Phase 3)pkg/vmcp/config/validator_test.go— 4 new table entries (Phase 3)cmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.go— new constant, struct, spec field, CEL rule, enum value,SubjectProviderNameon CRDTokenExchangeConfig(Phase 4)pkg/vmcp/auth/converters/token_exchange.go— populateSubjectProviderNameinConvertToStrategy()(Phase 4)pkg/vmcp/auth/converters/token_exchange_test.go— regression entries (Phase 4)pkg/vmcp/auth/converters/interface.go— registerUpstreamInjectConverterinNewRegistry()(Phase 4)Reference Implementations
pkg/vmcp/auth/strategies/unauthenticated.go— structural model for the stateless strategy patternpkg/vmcp/auth/strategies/tokenexchange.go— model for howAuthenticate()accesses identity via contextpkg/vmcp/auth/converters/token_exchange.go— model forConvertToStrategy/ResolveSecretspatterncmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.go— model for CEL rules, type enum,validateTypeConfigConsistencypatternAPI Contracts
Phase 1 Type Additions (
pkg/vmcp/auth/types/types.go)All downstream phases depend on these types. They must land before Phases 2, 3, and 4.
Phase 2 Strategy Interface (
pkg/vmcp/auth)UpstreamInjectStrategymust satisfy the existingauth.Strategyinterface:Constructor signature for factory registration:
DefaultOutgoingAuthRegistry.RegisterStrategyenforcesname == strategy.Name(), soName()must return exactly
authtypes.StrategyTypeUpstreamInject.Phase 4 Converter Interface (
pkg/vmcp/auth/converters/interface.go)UpstreamInjectConvertermust satisfy the existingStrategyConverterinterface (no changes):UpstreamInjectConverter.ResolveSecretsis a no-op pass-through (no static secrets to resolve).Integration Points
identity.UpstreamTokens(RFC-0052 prerequisite)pkg/auth/identity.go—Identitystruct does not yet haveUpstreamTokensIdentity.UpstreamTokens map[string]stringkeyed by provider nameauth.IdentityFromContext(ctx)(frompkg/auth/context.go) retrieves the identity; strategy readsidentity.UpstreamTokens[providerName]validateAuthServerIntegration(RFC-0053 Phase 3 prerequisite)pkg/vmcp/config/validator.go—validateAuthServerIntegrationdoes not yet existcase authtypes.StrategyTypeUpstreamInject:block implementing V-01, V-02, V-06authtypes.StrategyTypeUpstreamInjectto thevalidTypesslice invalidateBackendAuthStrategyHealth Check Bypass (
pkg/vmcp/health/monitor.go)Outgoing Auth Factory (
pkg/vmcp/auth/factory/outgoing.go)Unconditional registration — no signature changes to
NewOutgoingAuthRegistry:CRD Converter Registry (
pkg/vmcp/auth/converters/interface.go)One additional
r.Registercall inNewRegistry():CRD Admission (
cmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.go)Two changes follow existing patterns:
MCPExternalAuthConfigSpeckubebuilder markers:validateTypeConfigConsistency()gains a nil-equality check mirroring all other types:upstreamInjectadded to+kubebuilder:validation:Enumon theTypefieldPhase Dependency Diagram
graph TD P1["Phase 1: Types & sentinel<br/>(pkg/vmcp/auth/types/types.go)"] P2["Phase 2: Strategy impl<br/>(strategies/upstream_inject.go,<br/>factory/outgoing.go)"] P3["Phase 3: Startup validation<br/>(config/validator.go)"] P4["Phase 4: CRD & converter<br/>(v1alpha1 types,<br/>converters/upstream_inject.go)"] RFC052["RFC-0052<br/>identity.UpstreamTokens"] RFC053P3["RFC-0053 Phase 3 (#4142)<br/>validateAuthServerIntegration scaffold"] P1 --> P2 P2 --> P3 P1 --> P4 RFC052 -.->|"required for full e2e test"| P2 RFC053P3 -.->|"required for Phase 3"| P3Phase 4 can be worked in parallel with Phases 2 and 3 once Phase 1 lands.
Core Principles
Stateless strategy:
UpstreamInjectStrategyhas no fields, no cache, no mutexes; all state comes fromidentity.UpstreamTokensin context (seepkg/vmcp/auth/strategies/unauthenticated.goas structural model)Error wrapping for sentinel propagation: Always wrap
ErrUpstreamTokenNotFoundwith%wsoerrors.Is()works at any depth:No token values in any output: Error messages, log lines, and validation errors include provider names and backend names only — never token values (hard security requirement for all phases)
Health check guard first: Every
Authenticate()begins withhealth.IsHealthCheck(ctx)check;upstream_injectreturnsnilwith no header set on health probesDiscriminated union pattern:
BackendAuthStrategy.Typeselects which config pointer is populated;Validate()and startup validation enforce the pointer is non-nil; CRD CEL rules enforce spec/type equivalence at admission timeAdditive-only changes: All changes are additive; no existing behavior is altered for configs without the new fields
Constraints
upstream_injectalways injectsAuthorization: Bearer <token>; non-Bearer upstream token injection must useheader_injectionvalidateAuthServerIntegrationidentity.UpstreamTokensfield does not exist until RFC-0052 merges; Phases 1 and 4 can proceed without it; Phase 2 compiles against the field and requires RFC-0052 to be merged firsttask genafter Phase 1 to regeneratepkg/vmcp/auth/types/zz_generated.deepcopy.gotask operator-generate,task operator-manifests, andtask crdref-gen(fromcmd/thv-operator/) after Phase 4 CRD changesSubjectProviderNamenot inbuildCacheKey: The server-levelExchangeConfigcache inTokenExchangeStrategyis keyed on server config, not per-user subject;SubjectProviderNameis resolved per-request inAuthenticate()after the cache lookupOut of Scope
ErrUpstreamTokenNotFoundsentinel is defined here but the intercept/redirect flow is a separate RFCActorProviderNameparallel field not in scopeupstream_inject— expired tokens are injected as-isdocs/arch/02-core-concepts.md,docs/vmcp-auth.md) — explicitly out of scope per intake