Skip to content

Add the subject resolver and actor policy packages - #7215

Open
jhrozek wants to merge 5 commits into
mainfrom
as2-subject-packages
Open

jhrozek wants to merge 5 commits into
mainfrom
as2-subject-packages

Conversation

@jhrozek

@jhrozek jhrozek commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Delegated access needs two answers for every delegated token: which local user it acts for, and whether the agent acting for that user is allowed. ID-JAG redemption at the gateway's authorization server, the vMCP's direct route and, later, token exchange all have to reach the same answers for the same token, and embedders need to be able to plug in their own user directory. This PR adds those answers as shared packages. Nothing calls them yet; "Delegated access: subject mapping at ID-JAG redemption" (#6887) is the first caller.

  • pkg/authserver/subject: Ref{Issuer, Claim, Value}, the Resolver interface and its three errors. ErrUnknown refuses the token, ErrAmbiguous is for directory-backed resolvers that find two users, and ErrUnavailable tells callers to answer with a server error so the client can retry. ValidateBindingClaim refuses known mutable claim names (email, preferred_username, upn, unique_name, and profile claims such as name, phone_number, mail and username) and warns on sub for Okta custom authorization servers.
  • pkg/authserver/subjectresolver: the standalone resolver. It maps an issuer to a configured provider and subject claim, reads the provider-identity row, and then loads the user, so a row that outlived its user (Redis deletes the user before cleaning up the rows) resolves to ErrUnknown. New refuses mutable binding claims. It adds no storage method.
  • pkg/authserver/actor: Effective returns the actor from the outermost act (an act without iss takes the token's issuer, as Okta needs), or the client under the client source, with no fallback between the two. DefaultPolicy is bound to one token issuer and allows an actor whose issuer is that issuer or one configured to act through it, so a token from one issuer cannot name an actor issuer allowed only for another. Decisions carry stable reason strings for callers to map to reason codes, and the actor's source for audit. A denial is a Decision; a Policy error means it could not decide, and callers answer with a server error.
  • Generated mocks for Resolver and Policy.

Closes #7157

Type of change

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Dependency update
  • Documentation
  • Other (describe):

Test plan

  • Unit tests (task test)
  • E2E tests (task test-e2e)
  • Linting (task lint-fix)
  • Manual testing (describe below)

Unit tests ran with the race detector on the three new packages at each commit, and golangci-lint and go vet report no issues on them.

Changes

File Change
pkg/authserver/subject/subject.go Ref, Resolver, ErrUnknown, ErrAmbiguous, ErrUnavailable
pkg/authserver/subject/binding_claim.go ValidateBindingClaim
pkg/authserver/subjectresolver/resolver.go Standalone resolver over provider-identity rows and users
pkg/authserver/actor/actor.go Actor, Request, Decision, Policy, Effective
pkg/authserver/actor/policy.go DefaultPolicy and its reason strings
pkg/authserver/{subject,actor}/mocks/ Generated mocks

Does this introduce a user-facing change?

No. The packages have no callers yet.

Special notes for reviewers

  • The issue's "cross-issuer mapping in configuration" item is not here. The resolver already accepts several issuers for one provider, but nothing configures that yet, and its only consumer is "Delegated access: tokens and actors from third-party issuers" (Delegated access: tokens and actors from third-party issuers #7159), which now owns that configuration.
  • subjectresolver.New checks the binding claim but drops the Okta sub warning on purpose. Configuration code that wants to report it calls ValidateBindingClaim itself, so the leaf packages stay free of logging.
  • The issue also asked for a subject allowlist and a CEL expression in the default actor policy. I left both out: neither the subject mapping at redemption nor the third-party issuers work configures them, and a second actor CEL dialect next to the token-exchange actor matcher should come with a consumer. Policy is an interface, so richer rules can be added as another implementation.
  • The actor's issuer is not required to equal the token issuer. A ToolHive authorization server names its agents under their own issuer (for Mecatl, a SPIFFE trust domain), and validateActIssuer even refuses an actor issuer equal to the server's own issuer. Binding each policy to one token issuer gives the same protection.
  • Mapping an issuer to a provider name in subjectresolver.New asserts that the issuer's subject claim values are that provider's stored subjects. Rows are only written by that provider's own sign-in, so nothing mixes unless an operator maps an issuer to it; the docs say a wrong mapping resolves to the wrong user.
  • subject and actor live under pkg/authserver, like pkg/authserver/identity, rather than under pkg/auth, so the authorization server gains no pkg/auth imports. They import nothing else from ToolHive, so the vMCP and embedders can use them without the rest of the server.
  • subject.Ref is {Issuer, Claim, Value}, the shape of the upstream_subject claim. It is the lookup-key part of tokenexchange.UpstreamIdentity ({Issuer, StableClaim, StableValue}, without the raw sub). Both docs now say so. No conversion helper yet; that comes with the redemption wiring, which is the first code that needs one.
  • actor authorizes the act claim of a presented token; tokenexchange.ActorTokenValidator checks the actor's credential before an ID-JAG is issued. The two package docs point at each other.
  • There is no import guard for the two leaf packages. Today they import nothing else from ToolHive, and the Go compiler refuses an import cycle if one ever forms, so a depguard rule added little.
  • About 500 non-test lines, roughly half of them doc comments, which is over the 400-line guidance. They are new packages with no callers and one logical change, so I kept them in one PR.
  • The architecture docs get updated in the PR that wires these packages in, since nothing a client can see changes here.

@jhrozek
jhrozek requested a review from ChrisJBurns as a code owner November 22, 2026 09:38
@github-actions github-actions Bot added the size/XL Extra large PR: 1000+ lines changed label Nov 22, 2026
@codecov

codecov Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.12281% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 81.62%. Comparing base (7da77cd) to head (24cfd3b).

Files with missing lines Patch % Lines
pkg/authserver/subject/binding_claim.go 94.11% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7215      +/-   ##
==========================================
- Coverage   81.64%   81.62%   -0.03%     
==========================================
  Files         898      902       +4     
  Lines       91621    91735     +114     
==========================================
+ Hits        74805    74878      +73     
- Misses      16811    16852      +41     
  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.

@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.

Comment: the code is clean and nothing breaks on upgrade (no callers yet), but several trust-semantics decisions should be settled here, because #6887 will build on these interfaces and they are hard to change afterwards.

Design: Adding leaf packages (pkg/auth/subject, pkg/auth/actor) with depguard rules, and the resolver in pkg/authserver next to storage.UserStorage, is the right placement. The weak spots are where identity is scoped. The actor allowlist and the resolver both treat issuer and subject more loosely than the iss#sub identity implies. There is also now a third act parser and a second actor-authorization dialect (actor.claims here vs claims in ActorMatcher) with no stated plan to converge them.

Findings:

  1. pkg/auth/actor/policy.go:112-119: the issuer and subject allowlists are two independent sets. With issuers {A, B} and subjects {agent-1}, actor B#agent-1 passes even though only A#agent-1 was meant. Subjects are only unique within an issuer. Fix: allow (issuer, subject) pairs (e.g. map[issuer][]subject), or document clearly that the subject list applies to every allowed issuer.

  2. pkg/auth/actor/policy.go:112, actor.go:49-60: Request.TokenIssuer is never used. Effective takes act.iss from the token body, so a token from issuer A carrying act:{iss:"B", sub:"x"} passes whenever B is allowlisted, with no check that A may speak for B. Fix: require act.iss == TokenIssuer unless the operator lists explicit (tokenIssuer, actorIssuer) pairs.

  3. pkg/authserver/subjectresolver/resolver.go:61-79, :92: New accepts two issuers with the same provider Name and the same claim. Both then look up GetProviderIdentity(name, value) in one namespace (the storage key has no issuer component), so issuer B's sub=123 resolves to the local user linked to issuer A's sub=123. Fix: reject shared Name in New unless the claims differ and are known to be in the same value space, or require one issuer per Name.

  4. pkg/auth/subject/subject.go:14, resolver.go:92: Ref.Claim duplicates resolver configuration. The resolver is configured with a claim per issuer and then rejects a Ref whose Claim differs, so callers must know the configured claim and a mismatch silently becomes ErrUnknown. Fix: let the resolver extract the claim itself (Resolve(ctx, issuer, claims)) or expose BindingClaim(issuer); if Ref.Claim stays, drop the equality check.

  5. pkg/auth/subject/binding_claim.go:18: ValidateBindingClaim is a denylist of four names (email, preferred_username, upn, unique_name). mail, name, nickname, username, login, phone_number and namespaced email claims pass, while the package doc promises mutable claims are refused. Fix: extend the list or soften the doc to "known mutable claims".

  6. pkg/auth/actor/policy.go:118-146: a third CEL harness bypassing celcore.Engine (for interrupt support), and actor CEL with different semantics from ActorMatcher. Fix: add interrupt and bool-output options to toolhive-core/cel and use it from all sites, or state in the PR how #6887 and #7159 will reconcile actor_matcher with Policy.

  7. pkg/auth/actor/policy.go:122-132: Evaluate trusts the exported Actor fields. An embedder building an Actor directly can pass Claims containing a nested act, or Source: "client" with claims, so CEL can be driven by a prior actor despite the type docs. Fix: ignore Claims["act"] and ignore Claims for client-sourced actors, or add a constructor.

Test gap: no test exercises a CEL runtime error through a live Policy call site; #6887 needs to know whether it maps to 5xx or refusal.

🤖 Reviewed with Claude Code

jhrozek and others added 5 commits November 22, 2026 22:42
Tokens name a user by a claim from an issuer, and the token exchange,
the vMCP and embedders must all map that claim to the same local user.
Put the lookup key, the Resolver interface and its three failure modes
in a leaf package under pkg/authserver, next to pkg/authserver/identity,
so the authorization server does not depend on pkg/auth and other
callers can import it without pulling in the rest of the server.

ErrUnknown refuses the token, ErrAmbiguous lets directory-backed
resolvers refuse an identity that matches two users, and
ErrUnavailable tells callers to answer with a server error rather
than invalid_grant so the client can retry.

Closes #7157

Co-authored-by: Mecatl <noreply@mecatl.dev>
Delegated-access redemption needs to turn an identity-provider subject
into the local user it belongs to. Add a subject.Resolver for the
standalone authorization server that reads the provider-identity rows
it already keeps (see the "Subject resolver" part of the delegated
access issue).

The resolver is built from a map of issuer to (provider name, subject
claim). An unknown issuer, a claim other than the provider's subject
claim, a missing row, or a row whose user is missing is ErrUnknown;
any other storage error is ErrUnavailable. It never returns an empty
user with a nil error. Rows exist only for the identity-provider
sign-in leg, so later legs never resolve.

A row alone does not prove the user exists: Redis deletes the user
record before it cleans up the user's rows, best effort, so a stale
row can outlive its user. Like the sign-in path, the resolver also
loads the user and treats a missing one as ErrUnknown.

Mapping an issuer to a provider asserts that the issuer's subject
claim values are the subjects that provider's sign-in stores; a wrong
mapping resolves to the wrong user. New accepts several issuers for
one provider, but configuring that belongs to the third-party issuers
work.

Not wired into the server yet.

Closes #7157

Co-authored-by: Mecatl <noreply@mecatl.dev>
The token-exchange handlers, the vMCP and embedders must reach the same
answer on whether the agent named by a delegated token may act. Add the
leaf package pkg/authserver/actor for it, from "Delegated access: subject
resolver and actor policy packages" (#7157).

Effective takes raw claims and returns the outermost act as the actor.
An act without iss takes the token's iss, and a token without act is
refused under the default source. Under the source "client", Effective
names the client as the actor.

Policy and Decision carry stable Reason strings, and Decision records
the actor's source for audit. The default policy is bound to one token
issuer and allows an actor whose issuer is that issuer or one
configured to act through it, so a token from one issuer cannot name
an actor issuer allowed only for another. The actor's issuer need not
equal the token issuer: a ToolHive authorization server names its
agents under their own issuer. A denial is a Decision; a Policy error
means the policy could not decide, and callers answer with a server
error.

The actor's claims are a deep copy of the outermost act without its
nested act, so a Policy that reads them cannot be driven by a prior
actor or by a later change to the caller's claims. An actor with no
issuer or subject is treated as no actor.

Closes #7157

Co-authored-by: Mecatl <noreply@mecatl.dev>
The subject a delegated token maps to must come from a claim that stays
stable for a user. email, preferred_username, upn, unique_name (where
Entra v1 tokens carry the UPN) and the other profile claims such as
name, phone_number, mail and username are mutable, so using them would
let a changed address or display name resolve to a different local
user. Refusing them here, in one exported function, lets the
authorization server and the virtual MCP server share the rule. The
list covers known names only, so a claim that passes is not proven
stable.

Okta custom authorization servers issue sub in access tokens that may not
match the sign-in subject, so sub gets a warning there. The function
returns the warning instead of logging it, so this leaf package stays
free of logging and the caller decides how to report it.

subjectresolver.New runs the same check on each provider's subject
claim, so a resolver cannot be built over a mutable claim. It drops
the Okta warning; callers that want it call ValidateBindingClaim
themselves.

Closes #7157

Co-authored-by: Mecatl <noreply@mecatl.dev>
Callers of the subject and actor packages need to fake the Resolver and
Policy interfaces in their tests. Generate the gomock mocks, with the
go:generate lines that produce them.

Closes #7157

Co-authored-by: Mecatl <noreply@mecatl.dev>
@jhrozek
jhrozek force-pushed the as2-subject-packages branch from 9b293de to 24cfd3b Compare November 22, 2026 21:50
@jhrozek

jhrozek commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, this was useful. Going through them in order:

1, 6 and 7: I dropped the CEL expression and the subject allowlist from DefaultPolicy. Neither the subject mapping at redemption (#6887) nor the third-party issuers work (#7159) configures them, so they were a second actor CEL dialect next to the actor matcher with nobody using it. That removes the independent issuer/subject sets, the separate CEL harness and the "Evaluate trusts Actor.Claims" problem in one go. If someone needs richer actor rules later, they can come back as another Policy implementation on celcore once we know which dialect to standardise on. Policy stays an interface, so embedders can already plug in their own.

2: Agreed that nothing tied the actor issuer to the token issuer. I didn't go with act.iss == TokenIssuer as the default, though, because that breaks every ToolHive AS-1: its act.iss is the agent's issuer (for Mecatl a SPIFFE trust domain), and validateActIssuer even refuses an actor issuer equal to the server's own issuer. Instead a DefaultPolicy is now bound to one token issuer, NewDefaultPolicy(tokenIssuer, actorIssuers), and allows act.iss only from {tokenIssuer} plus the issuers configured to act through it. A request for another token issuer is an error. So it's your pairs model, one policy per token issuer, which is also how #6887 builds it.

3: The storage key is only (upstream name, subject), but the only thing that writes rows under a name is that upstream's own sign-in, and upstream names are unique, so rows from two issuers never mix by accident. Issuer B can only reach A's users if the operator maps B to A's name, and that mapping is exactly the cross-issuer feature: it says "B's claim values are A's stored subjects". Rejecting a repeated (name, claim) pair would block real cases where that holds, like Entra's v1 and v2 issuers for one tenant, which carry the same oid, and requiring different claims wouldn't stop a wrong mapping either. So I left New as is, made the Provider and New docs say plainly what the mapping asserts, and added a test for the Okta uid case. In #6887 the map only ever holds the identity provider's own issuer anyway, because of its startup check.

4: The claim is in Ref on purpose. In #6887 the value doesn't come from the identity provider's token: AS-1 vouches upstream_subject = {iss, claim, value}, so there's no claims map to hand the resolver. And a directory resolver should be able to look up (issuer, claim, value), say Okta uid or Entra oid, without knowing ToolHive's config, which BindingClaim(issuer) would force on it. The caller checks claim against binding_claim and refuses with invalid_assertion before it calls Resolve, so the resolver's check is a backstop. I kept it, because without it a Ref naming email would look up an email address as if it were a stored sub, and added a line to the Resolve doc saying so.

5: Agreed. The list now also has name, nickname, given_name, family_name, phone_number, mail, login and username, and the docs say "known mutable claim names", since a claim that passes isn't proven stable.

Test gap: there's no live call site in this PR, so that one belongs to #6887. What's settled here is the contract: a denial is always a Decision, and a Policy error means it couldn't decide, so callers answer server_error, the same as the resolver's ErrUnavailable. I've put that in #6887's refusal table.

On the third act parser: Effective's doc now says it's the strict parser for decisions, unlike the lenient audit.ParseDelegationChain, which never fails.

A few other changes while I was at it, and a heads-up that I force-pushed with the fixes folded into the original commits. The two packages moved from pkg/auth to pkg/authserver/subject and pkg/authserver/actor, next to pkg/authserver/identity, so the authorization server doesn't pick up new pkg/auth imports. I dropped the depguard rule, because they import nothing else from ToolHive and the compiler catches cycles anyway. Decision now carries the actor's source for audit. And the actor and subject docs now point at tokenexchange.ActorTokenValidator and UpstreamIdentity, so it's clear which step each covers and that Ref is the same lookup key.

@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Nov 22, 2026

@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.

Re-review of 24cfd3b: approve. The earlier findings are resolved or withdrawn, and the new shape is simpler.

  1. Independent issuer/subject allowlists: resolved. The subject allowlist and the CEL expression are gone, so there are no separate sets left to cross-match.
  2. TokenIssuer unused, no tie to act.iss: resolved with a different fix. NewDefaultPolicy(tokenIssuer, actorIssuers) binds one policy to one token issuer and Evaluate rejects any other. Your argument against requiring act.iss == TokenIssuer is right, because agents with their own issuer (e.g. a SPIFFE trust domain) would break.
  3. Shared provider Name across issuers: withdrawn. Rows are only written by that upstream's own sign-in, and Entra v1/v2 issuers sharing one oid is a real case that rejecting repeated names would block. The new docs and the Okta uid test cover it.
  4. Ref.Claim duplicating resolver configuration: withdrawn. AS-1 vouches {iss, claim, value}, so the resolver check is a backstop, and the Resolve doc now says that.
  5. Four-name denylist: resolved. It now has 12 names, matched case-insensitively, and the docs say "known mutable claim names".
  6. Third CEL harness / second actor dialect: resolved. CEL is removed and Policy stays an interface.
  7. Evaluate trusting exported Actor fields: resolved for this PR. Effective deep-copies Claims and DefaultPolicy never reads them.
  8. CEL runtime-error test: withdrawn, as there is no CEL left. The denial-versus-error contract is documented.

Two points to address in this PR or a follow-up. Neither blocks the merge:

  • pkg/authserver/actor/policy.go:62-70: DefaultPolicy is an issuer-only check. For SourceClient the actor issuer is always the token issuer, so it allows every client ID at that issuer. An act with no iss falls back to the token issuer and is allowed for any sub. If that is the intent, state in the DefaultPolicy doc that it does not restrict actors per subject or per client, and that anything finer needs another Policy.
  • Evaluate does not validate Actor.Source, and for SourceClient it does not check Actor.Subject == req.ClientID. Both are cheap to add and would make Evaluate safe for a hand-built Actor too, not only for the output of Effective.

Design: unchanged in shape. The subject resolver, the standalone resolver and the actor Policy with Effective are still the pieces, now under pkg/authserver/{subject,actor} with one policy per token issuer. Nothing outside these packages imports them yet, so there is no upgrade impact.

🤖 Reviewed with Claude Code

This branch has not been deployed

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

Labels

size/XL Extra large PR: 1000+ lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Delegated access: subject resolver and actor policy packages

2 participants