Repository navigation
Read delegated credentials in upstream_inject - #7355
Conversation
Resolve delegated upstream access tokens by platform user and provider so sessionless identities can authenticate without a token map. Fail closed on unavailable credentials, preserve reconnect and caller cancellation errors, and leave non-delegated requests and health checks unchanged. Co-authored-by: Mecatl <[email protected]>
Pin upstream_inject behavior in process on Legacy and Modern, including the foreign-issuer guard. Distinguish tools omitted during discovery from tools still advertised when their credential becomes unusable, and document how embedders enable the reader. Before: missing delegated credentials were classified as ErrAuthenticationFailed at backend authentication. After: a call that reaches delegated upstream authentication returns a provider-named isError result when authorization is required, or JSON-RPC -32603 when the credential is unavailable. An undiscovered tool does not reach that path. Co-authored-by: Mecatl <[email protected]>
Previously, a delegated request reaching an outgoing auth strategy without a configured UserCredentialReader logged only at DEBUG before failing closed with ErrDelegatedCredentialUnavailable, leaving misconfigured embedders silent at default log levels. Emit one WARN per strategy instance on the first delegated lookup with a nil reader and log subsequent misses at DEBUG so callers cannot drive WARN volume at request rate. Initialize upstreamCredentials in place via pointer receivers so the atomic warning guard is never copied. Co-authored-by: Mecatl <[email protected]>
The reader contract says error text can carry provider-supplied detail, but the delegated read logged the raw error at WARN. Log a fixed reason instead, drop per-user conditions that repeat on every request to DEBUG, and remove a nil-identity check that could never fire. Co-authored-by: Mecatl <[email protected]>
Authenticate's doc comment still described only the identity-map lookup. A missing refresh token persists for the user like the other conditions already logged at DEBUG, so stop repeating it at WARN on every request. Co-authored-by: Mecatl <[email protected]>
A typed-nil reader passed the missing-reader guard and panicked on the first delegated read; treat it as no reader so the request fails closed. The discovery test accepted a JSON-RPC error as partial discovery, and the fixture reused request IDs and sent null arguments. The docs now say when discovery omits a backend, that the stock vmcp serve passes no reader yet, and how Legacy sessions pick up newly visible tools. Co-authored-by: Mecatl <[email protected]>
The UserCredentialReader contract tells callers to log a failure category because error text can carry provider-supplied detail, yet the reader's own ID-token refresh warnings logged the raw error. Log a fixed reason instead, and drop the session key, which is derived from the user ID on the per-user path, from the matching debug line. Co-authored-by: Mecatl <[email protected]>
rdimitrov
left a comment
There was a problem hiding this comment.
Reviewed against Part C of #6407, #7188 and #7189. The strategy side looks right to me, apart from one gap from the design. Details below.
What I checked
- Identity trust.
AdmissionRouteis set only by the token validator's route classification.PlatformUserIDis the validatedsub. Neither can be reached from headers, the request body or tool arguments. A foreign issuer's marker gets no route, and a token with bothtsidand the marker is refused with a 401. - Error mapping matches the Part C table:
- No row, an expired row with no refresh token, or
invalid_grant: the named error. - Storage failure, transient refresh failure, another user's row, or no canonical user:
upstream credential unavailable. - Caller's context ended: the caller's own context error.
- No row, an expired row with no refresh token, or
- Existing
upstream_injectusers. Interactive and unspecified routes take the same path as before.NewUpstreamInjectStrategy(opts ...Option)is source-compatible. - Cross-user isolation, run locally. I wrote a throwaway test on top of this PR's harness: two delegated users on one vMCP, with a real embedded validator and a user-keyed reader. Alice connected providers A and B; Bob connected only B. On 2025-11-25 and 2026-07-28, in both discovery orders, with 20 concurrent calls and three repeat runs:
- Each backend request carried only that user's token.
- Bob's tool list never included Alice's tool.
- Bob's call to provider A got "unknown tool" and never reached A's backend.
- Test suites.
go test -racepasses on./pkg/vmcp/...,./pkg/auth/...,./pkg/authserver/...and./cmd/vmcp/....
One gap: a reader over storage that is not user-keyed reports "requires authorization"
WithUserCredentialReader accepts any reader, and GetValidTokensForUser always reads the row user:<id>. Over session-keyed storage that row never exists. So a user who has connected the provider gets DelegatedAuthRequiredError, and the strategy logs nothing, because the needs-authorization branch doesn't log.
I reproduced this with upstreamtoken.NewInProcessService over a plain MemoryStorage, holding a live row stored under the user's tsid. UserKeyed() reports false, and Authenticate returns provider "github" requires upstream authorization.
Why it matters:
- Today: discovery drops every
upstream_injectbackend for every delegated user, with no WARN. The misconfiguration doesn't show up anywhere. - Once #7188 lands: the user is sent to connect, the connection is written the session-keyed way, and the next call asks again. That loops forever.
- Design: Part C says the delegated route reads only from user-keyed storage or the embedder's own reader, and otherwise "fails closed per request with an infrastructure error."
The embedders this PR is for are exactly where this can happen, and the serve.go guard from the follow-up won't cover them. There's a precedent in validateUserKeyedReader (pkg/auth/token.go). Something along these lines would close it:
- Treat a reader that implements
upstreamtoken.UserKeyedReaderwithUserKeyed() == falseas no reader, either inWithUserCredentialReaderor inreadDelegatedCredential. It then fails closed withErrDelegatedCredentialUnavailableand hits the existing warn-once. - Say in
vmcp-library.mdthat the reader must read user-keyed storage. Today the doc only says "when using … over user-keyed storage".
A reader the embedder writes itself won't implement the interface and stays the embedder's responsibility. That matches the design.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #7355 +/- ##
=======================================
Coverage 82.64% 82.64%
=======================================
Files 944 945 +1
Lines 97034 97106 +72
=======================================
+ Hits 80190 80251 +61
- Misses 16839 16850 +11
Partials 5 5 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
The in-process reader reads the row user:<id>, which never exists in storage that is not keyed by user. Handed such a reader, the strategy told users who had connected the provider that they must authorize it, and logged nothing. Refuse a UserKeyedReader that reports false, so delegated requests fail closed as unavailable with a warning that names the cause, and say in the docs that the reader must read user-keyed storage. Co-authored-by: Mecatl <[email protected]>
|
Thanks, good catch, and thanks for running the two-user check. Fixed in 390c947. |
rdimitrov
left a comment
There was a problem hiding this comment.
Thanks for 390c947. The production change is right:
- My repro (the in-process reader over plain
MemoryStorage, with the user's row stored under thetsid) now getsupstream credential unavailable, logs one WARN, and injects nothing. isNilReaderruns before theUserKeyed()call, so a typed-nil reader can't panic.- A reader that wraps
InProcessServicewithout implementingUserKeyedReaderis accepted as given. That matches what the docs now say.
It does break one test in this PR, though. CI's "Test Go Code" job fails on TestDelegatedCredentialRead/{2025-11-25,2026-07-28}/no_canonical_user, and I reproduced it locally.
That case builds the outgoing reader over storagemocks.NewMockUpstreamTokenStorage, which forwards reads to the real user-keyed storage. The mock has no Unwrap(), so storage.IsUserKeyed reports false and the new guard refuses the reader. Discovery then drops tool-a, and the test fails at warm with "discovery must advertise the tool".
The guard is doing its job; the fixture needs to be a decorator that IsUserKeyed can see through. This passes TestDelegatedCredential* three runs in a row under -race:
fault := &canonicalUserFault{UpstreamTokenStorage: stor, provider: credentialProvider, on: &missingCanonicalUser}
outgoingReader = upstreamtoken.NewInProcessService(fault, as.UpstreamTokenRefresher())
// canonicalUserFault decorates the user-keyed storage, so the reader built on
// it still reports UserKeyed, and fails reads for one provider on demand.
type canonicalUserFault struct {
storage.UpstreamTokenStorage
provider string
on *atomic.Bool
}
func (f *canonicalUserFault) Unwrap() storage.UpstreamTokenStorage { return f.UpstreamTokenStorage }
func (f *canonicalUserFault) GetUpstreamTokens(ctx context.Context, sid, provider string) (*storage.UpstreamTokens, error) {
if provider == f.provider && f.on.Load() {
return nil, fmt.Errorf("private storage detail: %w", storage.ErrNoCanonicalUser)
}
return f.UpstreamTokenStorage.GetUpstreamTokens(ctx, sid, provider)
}With that change, the two-user isolation check from my earlier review still passes on the new head. I'll approve once CI is green.
The no_canonical_user case built its reader over a gomock storage mock, which has no Unwrap, so the new guard refused it as not user-keyed and discovery dropped the tool before the case ran. Inject the fault with a decorator that unwraps to the user-keyed storage instead. Co-authored-by: Mecatl <[email protected]>
|
Thanks, that was my miss, I only reran the strategies package after the guard went in. Took your decorator as is in 0c2e0cc, and the server, strategies, client and upstreamtoken packages pass under -race. |
rdimitrov
left a comment
There was a problem hiding this comment.
Approving on 0c2e0cc.
- The non-user-keyed reader guard from 390c947 now fails closed with one WARN, instead of telling the client the provider needs authorization. That fixes the issue from my first review.
- The
no_canonical_userfixture is now a decorator that unwraps to the user-keyed storage. That case runs again and still exercisesErrNoCanonicalUser→ -32603. - Locally,
pkg/vmcp/server,pkg/vmcp/auth/strategiesandpkg/auth/upstreamtokenpass with-race -count=2, and CI is green.
Summary
#7353 taught vMCP to render a delegated credential failure as "connect provider X" or a fixed "credential unavailable", but nothing produced those errors yet. A caller admitted on the delegated route carries no session ID, so
Identity.UpstreamTokensis always empty for it, and anupstream_injectbackend could never authenticate that caller. This PR makesupstream_injectread the user's credential directly.AdmissionRouteDelegated,upstream_injectreads the backend's provider credential forIdentity.PlatformUserIDthrough anupstreamtoken.UserCredentialReader, passed in with the newstrategies.WithUserCredentialReaderoption. It never falls back toIdentity.UpstreamTokensor the incoming bearer. Interactive and unspecified routes, and health checks, are unchanged.DelegatedAuthRequiredError; anything else producesErrDelegatedCredentialUnavailable. If the caller's context ended, the caller's own context error is returned. A nil or typed-nil reader counts as no reader, so the request fails closed instead of panicking.reason, never the reader's error text, since that can carry provider-supplied detail. Failures that persist for a user (no user, no canonical user, no refresh token) log at DEBUG so they don't repeat at WARN on every request. A missing reader is warned about once per strategy.vmcp-library.md, the delegated route in the architecture docs, and the wire responses, discovery and cache behaviour indocs/error-handling.md.Part of #6407
Type of change
Test plan
pkg/vmcp/auth/strategies,pkg/vmcp/server,pkg/vmcp/client,pkg/auth/upstreamtoken, with-race)The new server test drives Legacy and Modern sessions through a real embedded validator and a user-keyed in-process reader. It covers success, needs-authorization, unavailable, discovery leaving out a backend whose credential is missing, and the foreign-issuer guard.
Changes
pkg/vmcp/auth/strategies/delegated.gopkg/vmcp/auth/strategies/upstream_inject.gopkg/auth/upstreamtoken/service.godocs/arch/*.md,docs/error-handling.md*_test.goDoes this introduce a user-facing change?
Yes, for callers admitted on the delegated route (a token minted by the embedded authorization server with the delegated-access marker and no session ID) when they reach an
upstream_injectbackend.Before: these calls always failed as
ErrAuthenticationFailed("... for backend (upstream token missing): ..."). Legacytools/callreturned anisErrortool result with that text. Moderntools/call,resources/readandprompts/getreturned JSON-RPC -32603 with the same text.After: vMCP reads the user's credential for the configured provider through the reader the embedder passes, and injects it as before.
tools/callreturns anisErrortool result naming only the provider (provider "github" requires upstream authorization), on both Legacy and Modern.upstream credential unavailable. This applies totools/callon Legacy and Modern, and toresources/readandprompts/get. The backend ID and the reader's error text no longer reach the client.upstream_injectbackend still fails, now with the fixed -32603.Interactive and other non-delegated callers, and health checks, behave as before.
Special notes for reviewers
thv vmcp servedoesn't pass a reader yet:factory.NewOutgoingAuthRegistrybuildsupstream_injectwithout one, so delegated requests there keep failing closed (now with the fixed -32603). This PR is for embedders that build their own registry, such as mecatl. Wiringserve.goonly when storage is user-keyed, and a factory option, come in a follow-up.vmcp-library.mdsays so.upstream_injectreads delegated credentials in this PR.token_exchange,oboandaws_stswith a subject provider, andxaa, still readIdentity.UpstreamTokensand fail as before for delegated callers. Moving them onto the shared lookup is the next PR.Optionis package-wide for that reason.service.gostill log the raw error. The drive-by covers only the per-user ID-token path that this PR makes reachable.