Skip to content

Read delegated credentials in upstream_inject - #7355

Merged
jhrozek merged 9 commits into
stacklok:mainfrom
jhrozek:credential-read-4-upstream-inject
Nov 27, 2026
Merged

jhrozek merged 9 commits into
stacklok:mainfrom
jhrozek:credential-read-4-upstream-inject

Conversation

@jhrozek

@jhrozek jhrozek commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

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.UpstreamTokens is always empty for it, and an upstream_inject backend could never authenticate that caller. This PR makes upstream_inject read the user's credential directly.

  • On AdmissionRouteDelegated, upstream_inject reads the backend's provider credential for Identity.PlatformUserID through an upstreamtoken.UserCredentialReader, passed in with the new strategies.WithUserCredentialReader option. It never falls back to Identity.UpstreamTokens or the incoming bearer. Interactive and unspecified routes, and health checks, are unchanged.
  • It fails closed when there is no reader, no platform user ID, or no provider, or when the read fails. A reader that wants the user to reconnect produces DelegatedAuthRequiredError; anything else produces ErrDelegatedCredentialUnavailable. 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.
  • Reader failures are logged as a fixed 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.
  • Drive-by: the in-process reader's own ID-token refresh warnings also logged the raw refresh error. They now log a fixed reason too, and the debug line next to them no longer logs the user-derived row key.
  • Docs: embedder wiring in vmcp-library.md, the delegated route in the architecture docs, and the wire responses, discovery and cache behaviour in docs/error-handling.md.

Part of #6407

Type of change

  • New feature

Test plan

  • Unit tests (pkg/vmcp/auth/strategies, pkg/vmcp/server, pkg/vmcp/client, pkg/auth/upstreamtoken, with -race)
  • Linting (golangci-lint on the same packages)

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

File Change
pkg/vmcp/auth/strategies/delegated.go New: route-aware credential lookup, reader option, failure logging
pkg/vmcp/auth/strategies/upstream_inject.go Uses the shared lookup; takes options
pkg/auth/upstreamtoken/service.go Drive-by: log refresh failures by reason
docs/arch/*.md, docs/error-handling.md Delegated reads, embedder wiring, wire responses
*_test.go Strategy, reader and in-process server tests

Does 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_inject backend.

Before: these calls always failed as ErrAuthenticationFailed ("... for backend (upstream token missing): ..."). Legacy tools/call returned an isError tool result with that text. Modern tools/call, resources/read and prompts/get returned 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.

  • When the user must connect the provider again, tools/call returns an isError tool result naming only the provider (provider "github" requires upstream authorization), on both Legacy and Modern.
  • When the credential can't be read (no reader configured, storage failure, refresh failure, invalid binding), the response is JSON-RPC -32603 with the fixed message upstream credential unavailable. This applies to tools/call on Legacy and Modern, and to resources/read and prompts/get. The backend ID and the reader's error text no longer reach the client.
  • Without a reader, a delegated call to an upstream_inject backend still fails, now with the fixed -32603.

Interactive and other non-delegated callers, and health checks, behave as before.

Special notes for reviewers

  • The stock thv vmcp serve doesn't pass a reader yet: factory.NewOutgoingAuthRegistry builds upstream_inject without 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. Wiring serve.go only when storage is user-keyed, and a factory option, come in a follow-up. vmcp-library.md says so.
  • Only upstream_inject reads delegated credentials in this PR. token_exchange, obo and aws_sts with a subject provider, and xaa, still read Identity.UpstreamTokens and fail as before for delegated callers. Moving them onto the shared lookup is the next PR. Option is package-wide for that reason.
  • The session-path refresh warnings in service.go still log the raw error. The drive-by covers only the per-user ID-token path that this PR makes reachable.

jhrozek and others added 7 commits November 27, 2026 15:18
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]>
@jhrozek
jhrozek requested a review from ChrisJBurns as a code owner November 27, 2026 14:22

@rdimitrov rdimitrov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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. AdmissionRoute is set only by the token validator's route classification. PlatformUserID is the validated sub. Neither can be reached from headers, the request body or tool arguments. A foreign issuer's marker gets no route, and a token with both tsid and 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.
  • Existing upstream_inject users. 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 -race passes 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_inject backend 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.UserKeyedReader with UserKeyed() == false as no reader, either in WithUserCredentialReader or in readDelegatedCredential. It then fails closed with ErrDelegatedCredentialUnavailable and hits the existing warn-once.
  • Say in vmcp-library.md that 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

codecov Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 82.64%. Comparing base (cfebc3d) to head (0c2e0cc).
⚠️ Report is 2 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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]>
@jhrozek

jhrozek commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, good catch, and thanks for running the two-user check. Fixed in 390c947. WithUserCredentialReader now refuses a reader that implements upstreamtoken.UserKeyedReader and reports UserKeyed() == false, same check as validateUserKeyedReader. Delegated requests then fail closed with upstream credential unavailable, and there's a one-time WARN saying the reader doesn't read user-keyed storage. A reader the embedder writes itself is still taken as given. There's a test with NewInProcessService over plain MemoryStorage that now gets unavailable instead of requires-authorization, and vmcp-library.md says the reader has to read user-keyed storage.

@rdimitrov rdimitrov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for 390c947. The production change is right:

  • My repro (the in-process reader over plain MemoryStorage, with the user's row stored under the tsid) now gets upstream credential unavailable, logs one WARN, and injects nothing.
  • isNilReader runs before the UserKeyed() call, so a typed-nil reader can't panic.
  • A reader that wraps InProcessService without implementing UserKeyedReader is 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.

ChrisJBurns
ChrisJBurns previously approved these changes Nov 27, 2026
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]>
@jhrozek

jhrozek commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

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 rdimitrov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_user fixture is now a decorator that unwraps to the user-keyed storage. That case runs again and still exercises ErrNoCanonicalUser → -32603.
  • Locally, pkg/vmcp/server, pkg/vmcp/auth/strategies and pkg/auth/upstreamtoken pass with -race -count=2, and CI is green.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants