From 5359b64e68a6233eaaf7d0d64b64fafcf18a6e7d Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Tue, 17 Nov 2026 12:56:08 +0100 Subject: [PATCH 1/5] Add subject resolver types 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 --- pkg/authserver/subject/subject.go | 51 +++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 pkg/authserver/subject/subject.go diff --git a/pkg/authserver/subject/subject.go b/pkg/authserver/subject/subject.go new file mode 100644 index 0000000000..1e4c845390 --- /dev/null +++ b/pkg/authserver/subject/subject.go @@ -0,0 +1,51 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +// Package subject maps a user's identity at an issuer, one claim and its +// value, to the local user it belongs to. Callers build the key from the token +// they hold: the upstream_subject claim of an ID-JAG from a ToolHive +// authorization server, or the configured binding claim of a token that an +// identity provider issued directly. +package subject + +import ( + "context" + "errors" +) + +// Ref is a lookup key for a subject: one claim, with its value, from one issuer. +// +// It has the shape of the https://toolhive.dev/upstream_subject claim +// ({iss, claim, value}). From ToolHive's own record of an upstream login +// (session.UpstreamSubject, tokenexchange.UpstreamIdentity) it is +// {Issuer, StableClaim, StableValue}; the raw sub is not part of the key. +type Ref struct { + // Issuer is the issuer the claim belongs to. For an upstream_subject claim + // that is the identity provider, not the server that signed the token. + Issuer string + // Claim is the name of the claim, such as "sub". + Claim string + // Value is the claim's value. + Value string +} + +// Resolver maps a Ref to the canonical local user ID. +// +// A nil error always comes with a non-empty user ID. Resolvers never create +// users; a Ref with no local user returns ErrUnknown. Callers log the errors +// an implementation returns, so they must not include the Ref's values. +type Resolver interface { + Resolve(ctx context.Context, ref Ref) (string, error) +} + +var ( + // ErrUnknown means no local user matches the Ref. Callers refuse the token. + ErrUnknown = errors.New("unknown subject") + // ErrAmbiguous means more than one local user matches the Ref. Callers + // refuse the token. Directory-backed resolvers return it; the standalone + // resolver never does. + ErrAmbiguous = errors.New("ambiguous subject") + // ErrUnavailable means the resolver could not answer. Callers report a + // server error, not invalid_grant, so the client may retry. + ErrUnavailable = errors.New("subject resolver unavailable") +) From a9d9f5ee47f35b680c8c7c75b38b023c0e8fab3a Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Tue, 17 Nov 2026 12:57:57 +0100 Subject: [PATCH 2/5] Add standalone subject resolver 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 --- pkg/authserver/subjectresolver/resolver.go | 114 +++++++++ .../subjectresolver/resolver_test.go | 218 ++++++++++++++++++ 2 files changed, 332 insertions(+) create mode 100644 pkg/authserver/subjectresolver/resolver.go create mode 100644 pkg/authserver/subjectresolver/resolver_test.go diff --git a/pkg/authserver/subjectresolver/resolver.go b/pkg/authserver/subjectresolver/resolver.go new file mode 100644 index 0000000000..a007dd37aa --- /dev/null +++ b/pkg/authserver/subjectresolver/resolver.go @@ -0,0 +1,114 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +// Package subjectresolver implements subject.Resolver for the standalone +// authorization server, using the provider-identity rows it keeps for users. +// +// Provider-identity rows are written only on the identity-provider sign-in +// leg. A subject from a later leg (for example GitHub) therefore never +// resolves. The resolver knows only found or not found: it has no notion of +// deactivated users and never returns subject.ErrAmbiguous. +// +// A provider-identity row alone does not prove the user exists. Deleting a user +// in the Redis storage removes the user record first and cleans up the provider +// links on a best-effort basis, so a stale link can outlive its user. The +// resolver therefore also loads the user record, as the sign-in path does. +package subjectresolver + +import ( + "context" + "errors" + "fmt" + + "github.com/stacklok/toolhive/pkg/authserver/storage" + "github.com/stacklok/toolhive/pkg/authserver/subject" +) + +// IdentityStore is the part of storage.UserStorage the resolver reads. +type IdentityStore interface { + GetUser(ctx context.Context, id string) (*storage.User, error) + GetProviderIdentity(ctx context.Context, providerID, providerSubject string) (*storage.ProviderIdentity, error) +} + +// Provider names an identity provider and the claim that carries its subject. +// +// Mapping an issuer to a Provider asserts that the values of that issuer's +// SubjectClaim are the subjects Name's upstream stores for its users. Rows are +// written only by that upstream's own sign-in and are keyed by upstream name +// and subject, so nothing mixes unless an operator maps an issuer to it. A +// wrong mapping resolves to the wrong user. +type Provider struct { + // Name is the provider ID under which the provider's identities are stored. + Name string + // SubjectClaim is the claim whose value is the provider's subject, such as "sub". + SubjectClaim string +} + +// Resolver resolves a subject.Ref to a local user ID. +type Resolver struct { + providers map[string]Provider + store IdentityStore +} + +var _ subject.Resolver = (*Resolver)(nil) + +// New returns a Resolver for the given identity providers, keyed by issuer. +// Each entry asserts what Provider documents: that the issuer's SubjectClaim +// values are the subjects the named upstream stores. New accepts several +// issuers for the same provider name with different subject claims (an Okta +// custom authorization server carries the sign-in subject in uid), but nothing +// configures that yet; it belongs to the third-party issuers work. +// It returns an error if the store is nil, no providers are given, or an +// entry has an empty issuer, name or subject claim. +func New(providers map[string]Provider, store IdentityStore) (*Resolver, error) { + if store == nil { + return nil, errors.New("subjectresolver: store is required") + } + if len(providers) == 0 { + return nil, errors.New("subjectresolver: at least one provider is required") + } + copied := make(map[string]Provider, len(providers)) + for issuer, p := range providers { + if issuer == "" || p.Name == "" || p.SubjectClaim == "" { + return nil, errors.New("subjectresolver: provider entries need an issuer, a name and a subject claim") + } + copied[issuer] = p + } + return &Resolver{providers: copied, store: store}, nil +} + +// Resolve returns the local user ID for ref. Callers check Ref.Claim against +// their own configuration first so they can return a precise error. A claim +// that is not the provider's subject claim is ErrUnknown here by design, so a +// value from another claim is never looked up as a stored subject. +// +// It returns subject.ErrUnknown when the issuer or claim is not configured, no +// provider identity matches, or the identity points at a user that no longer +// exists, and subject.ErrUnavailable when the store cannot answer. +func (r *Resolver) Resolve(ctx context.Context, ref subject.Ref) (string, error) { + p, ok := r.providers[ref.Issuer] + if !ok || ref.Claim != p.SubjectClaim { + return "", subject.ErrUnknown + } + identity, err := r.store.GetProviderIdentity(ctx, p.Name, ref.Value) + if err != nil { + if errors.Is(err, storage.ErrNotFound) { + return "", subject.ErrUnknown + } + return "", fmt.Errorf("%w: %w", subject.ErrUnavailable, err) + } + if identity == nil || identity.UserID == "" { + return "", subject.ErrUnknown + } + user, err := r.store.GetUser(ctx, identity.UserID) + if err != nil { + if errors.Is(err, storage.ErrNotFound) { + return "", subject.ErrUnknown + } + return "", fmt.Errorf("%w: %w", subject.ErrUnavailable, err) + } + if user == nil || user.ID == "" { + return "", subject.ErrUnknown + } + return user.ID, nil +} diff --git a/pkg/authserver/subjectresolver/resolver_test.go b/pkg/authserver/subjectresolver/resolver_test.go new file mode 100644 index 0000000000..0a94d7791e --- /dev/null +++ b/pkg/authserver/subjectresolver/resolver_test.go @@ -0,0 +1,218 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package subjectresolver_test + +import ( + "context" + "errors" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/mock/gomock" + + "github.com/stacklok/toolhive/pkg/authserver/storage" + "github.com/stacklok/toolhive/pkg/authserver/storage/mocks" + "github.com/stacklok/toolhive/pkg/authserver/subject" + "github.com/stacklok/toolhive/pkg/authserver/subjectresolver" +) + +const ( + idpIssuer = "https://idp.example.com" + entraIssuer = "https://entra.example.com" + // oktaCustomIssuer is a custom authorization server whose tokens carry the + // sign-in subject in uid and are mapped to the same provider as idpIssuer. + oktaCustomIssuer = "https://okta.example.com/oauth2/default" +) + +func TestResolve(t *testing.T) { + t.Parallel() + storeErr := errors.New("boom") + + tests := []struct { + name string + ref subject.Ref + lookup func(*mocks.MockUserStorage) + want string + wantErr error + wantCause error + }{ + { + name: "found", + ref: subject.Ref{Issuer: idpIssuer, Claim: "sub", Value: "abc"}, + lookup: func(m *mocks.MockUserStorage) { + m.EXPECT().GetProviderIdentity(gomock.Any(), "okta", "abc"). + Return(&storage.ProviderIdentity{UserID: "user-1"}, nil) + m.EXPECT().GetUser(gomock.Any(), "user-1").Return(&storage.User{ID: "user-1"}, nil) + }, + want: "user-1", + }, + { + name: "second issuer queries its own provider", + ref: subject.Ref{Issuer: entraIssuer, Claim: "oid", Value: "abc"}, + lookup: func(m *mocks.MockUserStorage) { + m.EXPECT().GetProviderIdentity(gomock.Any(), "entra", "abc"). + Return(&storage.ProviderIdentity{UserID: "user-2"}, nil) + m.EXPECT().GetUser(gomock.Any(), "user-2").Return(&storage.User{ID: "user-2"}, nil) + }, + want: "user-2", + }, + { + name: "second issuer for the same provider uses its own subject claim", + ref: subject.Ref{Issuer: oktaCustomIssuer, Claim: "uid", Value: "abc"}, + lookup: func(m *mocks.MockUserStorage) { + m.EXPECT().GetProviderIdentity(gomock.Any(), "okta", "abc"). + Return(&storage.ProviderIdentity{UserID: "user-1"}, nil) + m.EXPECT().GetUser(gomock.Any(), "user-1").Return(&storage.User{ID: "user-1"}, nil) + }, + want: "user-1", + }, + { + name: "second issuer with the claim of another issuer", + ref: subject.Ref{Issuer: oktaCustomIssuer, Claim: "sub", Value: "abc"}, + wantErr: subject.ErrUnknown, + }, + { + name: "no row", + ref: subject.Ref{Issuer: idpIssuer, Claim: "sub", Value: "abc"}, + lookup: func(m *mocks.MockUserStorage) { + m.EXPECT().GetProviderIdentity(gomock.Any(), "okta", "abc").Return(nil, storage.ErrNotFound) + }, + wantErr: subject.ErrUnknown, + }, + { + name: "storage error", + ref: subject.Ref{Issuer: idpIssuer, Claim: "sub", Value: "abc"}, + lookup: func(m *mocks.MockUserStorage) { + m.EXPECT().GetProviderIdentity(gomock.Any(), "okta", "abc").Return(nil, storeErr) + }, + wantErr: subject.ErrUnavailable, + wantCause: storeErr, + }, + { + name: "issuer without provider", + ref: subject.Ref{Issuer: "https://other.example.com", Claim: "sub", Value: "abc"}, + wantErr: subject.ErrUnknown, + }, + { + name: "claim is not the subject claim", + ref: subject.Ref{Issuer: idpIssuer, Claim: "email", Value: "abc"}, + wantErr: subject.ErrUnknown, + }, + { + name: "nil row", + ref: subject.Ref{Issuer: idpIssuer, Claim: "sub", Value: "abc"}, + lookup: func(m *mocks.MockUserStorage) { + m.EXPECT().GetProviderIdentity(gomock.Any(), "okta", "abc").Return(nil, nil) + }, + wantErr: subject.ErrUnknown, + }, + { + name: "row with empty user ID", + ref: subject.Ref{Issuer: idpIssuer, Claim: "sub", Value: "abc"}, + lookup: func(m *mocks.MockUserStorage) { + m.EXPECT().GetProviderIdentity(gomock.Any(), "okta", "abc"). + Return(&storage.ProviderIdentity{}, nil) + }, + wantErr: subject.ErrUnknown, + }, + { + name: "link without user", + ref: subject.Ref{Issuer: idpIssuer, Claim: "sub", Value: "abc"}, + lookup: func(m *mocks.MockUserStorage) { + m.EXPECT().GetProviderIdentity(gomock.Any(), "okta", "abc"). + Return(&storage.ProviderIdentity{UserID: "user-1"}, nil) + m.EXPECT().GetUser(gomock.Any(), "user-1").Return(nil, storage.ErrNotFound) + }, + wantErr: subject.ErrUnknown, + }, + { + name: "user lookup storage error", + ref: subject.Ref{Issuer: idpIssuer, Claim: "sub", Value: "abc"}, + lookup: func(m *mocks.MockUserStorage) { + m.EXPECT().GetProviderIdentity(gomock.Any(), "okta", "abc"). + Return(&storage.ProviderIdentity{UserID: "user-1"}, nil) + m.EXPECT().GetUser(gomock.Any(), "user-1").Return(nil, storeErr) + }, + wantErr: subject.ErrUnavailable, + wantCause: storeErr, + }, + { + name: "nil user", + ref: subject.Ref{Issuer: idpIssuer, Claim: "sub", Value: "abc"}, + lookup: func(m *mocks.MockUserStorage) { + m.EXPECT().GetProviderIdentity(gomock.Any(), "okta", "abc"). + Return(&storage.ProviderIdentity{UserID: "user-1"}, nil) + m.EXPECT().GetUser(gomock.Any(), "user-1").Return(nil, nil) + }, + wantErr: subject.ErrUnknown, + }, + { + name: "user with empty ID", + ref: subject.Ref{Issuer: idpIssuer, Claim: "sub", Value: "abc"}, + lookup: func(m *mocks.MockUserStorage) { + m.EXPECT().GetProviderIdentity(gomock.Any(), "okta", "abc"). + Return(&storage.ProviderIdentity{UserID: "user-1"}, nil) + m.EXPECT().GetUser(gomock.Any(), "user-1").Return(&storage.User{}, nil) + }, + wantErr: subject.ErrUnknown, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + store := mocks.NewMockUserStorage(gomock.NewController(t)) + if tt.lookup != nil { + tt.lookup(store) + } + r, err := subjectresolver.New(map[string]subjectresolver.Provider{ + idpIssuer: {Name: "okta", SubjectClaim: "sub"}, + entraIssuer: {Name: "entra", SubjectClaim: "oid"}, + oktaCustomIssuer: {Name: "okta", SubjectClaim: "uid"}, + }, store) + require.NoError(t, err) + + got, err := r.Resolve(context.Background(), tt.ref) + if err == nil { + require.NotEmpty(t, got) + } + if tt.wantErr != nil { + require.ErrorIs(t, err, tt.wantErr) + assert.Empty(t, got) + if tt.wantCause != nil { + assert.ErrorIs(t, err, tt.wantCause) + } + return + } + require.NoError(t, err) + assert.Equal(t, tt.want, got) + }) + } +} + +func TestNewRefusesInvalidInput(t *testing.T) { + t.Parallel() + store := mocks.NewMockUserStorage(gomock.NewController(t)) + valid := subjectresolver.Provider{Name: "okta", SubjectClaim: "sub"} + + tests := []struct { + name string + providers map[string]subjectresolver.Provider + store subjectresolver.IdentityStore + }{ + {"nil store", map[string]subjectresolver.Provider{idpIssuer: valid}, nil}, + {"no providers", nil, store}, + {"empty issuer", map[string]subjectresolver.Provider{"": valid}, store}, + {"empty name", map[string]subjectresolver.Provider{idpIssuer: {SubjectClaim: "sub"}}, store}, + {"empty subject claim", map[string]subjectresolver.Provider{idpIssuer: {Name: "okta"}}, store}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + r, err := subjectresolver.New(tt.providers, tt.store) + require.Error(t, err) + assert.Nil(t, r) + }) + } +} From 0140f9637fdd320aff9e4b74b716acd2d2046c64 Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Tue, 17 Nov 2026 13:02:17 +0100 Subject: [PATCH 3/5] Add actor policy package 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 --- pkg/authserver/actor/actor.go | 160 +++++++++++ pkg/authserver/actor/actor_test.go | 262 ++++++++++++++++++ pkg/authserver/actor/policy.go | 85 ++++++ .../server/tokenexchange/actor_validator.go | 13 +- 4 files changed, 515 insertions(+), 5 deletions(-) create mode 100644 pkg/authserver/actor/actor.go create mode 100644 pkg/authserver/actor/actor_test.go create mode 100644 pkg/authserver/actor/policy.go diff --git a/pkg/authserver/actor/actor.go b/pkg/authserver/actor/actor.go new file mode 100644 index 0000000000..1abfc3204d --- /dev/null +++ b/pkg/authserver/actor/actor.go @@ -0,0 +1,160 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +// Package actor decides whether the agent acting on a user's behalf, named by +// a delegated token, is allowed. +// +// It authorizes the actor a token already names, when the token is presented: +// the outermost act claim, or the client under SourceClient. Checking an +// actor's credential before ToolHive issues a token, and so deciding what goes +// into act, is tokenexchange.ActorTokenValidator. +package actor + +import ( + "context" + "errors" + "fmt" +) + +// Where an identity provider names the actor. +const ( + // SourceAct takes the actor from the token's outermost act claim. It is + // the default. + SourceAct = "act" + // SourceClient takes the actor from the client the token was issued to, + // for providers that never emit act. There is no fallback between sources. + SourceClient = "client" +) + +var ( + // ErrNoActor means the source is "act" and the token has no act claim. + ErrNoActor = errors.New("token has no actor") + // ErrMalformedActor means the act claim, or the input that stands in for + // it, cannot name an actor. + ErrMalformedActor = errors.New("malformed actor") +) + +// Actor is the agent a token names as acting on the user's behalf. +type Actor struct { + // Source is where the identity provider names the actor. + Source string + // Issuer is act.iss, or the token's issuer when act has none. + Issuer string + // Subject is act.sub, or the client ID when Source is SourceClient. + Subject string + // Claims is a copy of the outermost act object without its nested act + // member, so a prior actor cannot drive a decision. It is nil when Source + // is SourceClient. DefaultPolicy does not read it; it is there for Policy + // implementations that do. + Claims map[string]any +} + +// Request is what a Policy decides on. +type Request struct { + TokenIssuer string + // ClientID is a separate input. It is never the actor, except when the + // issuer's source is SourceClient. + ClientID string + // Actor is nil when the token has no actor. + Actor *Actor + User string + Resource string +} + +// Decision is a Policy's answer. +type Decision struct { + Allow bool + // Reason is a stable string callers map to a reason code. + Reason string + // Principal is the actor identity for session binding and audit. + Principal string + // Source is where the actor came from, SourceAct or SourceClient, copied + // from the Actor for audit. It is empty when there was no actor. + Source string +} + +// Policy decides whether an actor may act for a user. A Decision that does not +// allow is a denial. A non-nil error means the policy could not decide (for +// example a directory-backed policy that is unavailable, or a request for +// another token issuer): the Decision does not allow, and callers answer with a +// server error rather than a denial, like subject.ErrUnavailable. +type Policy interface { + Evaluate(ctx context.Context, req Request) (Decision, error) +} + +// Effective returns the actor a token names. Only the outermost act counts +// (RFC 8693 section 4.1): Claims is a deep copy of it with the nested act +// removed, and does not alias the caller's map or any map[string]any or []any +// inside it (the shapes JSON decoding produces). An act without iss takes +// tokenIssuer, so providers that omit it (Okta) work. +// +// For SourceClient the actor is the client, with tokenIssuer as its issuer. +// An empty source means SourceAct. +// +// Effective is the strict parser for authorization decisions: it fails closed, +// unlike the lenient audit parser audit.ParseDelegationChain (toolhive-core), +// which never fails. +func Effective(source string, claims map[string]any, tokenIssuer, clientID string) (*Actor, error) { + switch source { + case SourceClient: + if tokenIssuer == "" || clientID == "" { + return nil, fmt.Errorf("%w: client source needs an issuer and a client ID", ErrMalformedActor) + } + return &Actor{Source: SourceClient, Issuer: tokenIssuer, Subject: clientID}, nil + case SourceAct, "": + default: + return nil, fmt.Errorf("unknown actor source %q", source) + } + + raw, ok := claims["act"] + if !ok || raw == nil { + return nil, ErrNoActor + } + act, ok := raw.(map[string]any) + if !ok { + return nil, fmt.Errorf("%w: act is not an object", ErrMalformedActor) + } + sub, _ := act["sub"].(string) + if sub == "" { + return nil, fmt.Errorf("%w: act has no sub", ErrMalformedActor) + } + iss := tokenIssuer + if v, present := act["iss"]; present { + s, isString := v.(string) + if !isString || s == "" { + return nil, fmt.Errorf("%w: act.iss is not a non-empty string", ErrMalformedActor) + } + iss = s + } + if iss == "" { + return nil, fmt.Errorf("%w: act has no iss and the token has none", ErrMalformedActor) + } + actClaims := make(map[string]any, len(act)) + for k, v := range act { + if k != "act" { + actClaims[k] = deepCopy(v) + } + } + return &Actor{Source: SourceAct, Issuer: iss, Subject: sub, Claims: actClaims}, nil +} + +// deepCopy copies the JSON-shaped containers (map[string]any and []any) +// recursively and returns every other value as is. +func deepCopy(v any) any { + switch t := v.(type) { + case map[string]any: + out := make(map[string]any, len(t)) + for k, e := range t { + out[k] = deepCopy(e) + } + return out + case []any: + out := make([]any, len(t)) + for i, e := range t { + out[i] = deepCopy(e) + } + return out + default: + return v + } +} diff --git a/pkg/authserver/actor/actor_test.go b/pkg/authserver/actor/actor_test.go new file mode 100644 index 0000000000..835370e879 --- /dev/null +++ b/pkg/authserver/actor/actor_test.go @@ -0,0 +1,262 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package actor + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestEffective(t *testing.T) { + t.Parallel() + tests := []struct { + name string + source string + claims map[string]any + client string + want *Actor + // wantClaims, when set, is the exact Claims the actor must carry. + wantClaims map[string]any + wantErr error + // wantFail is for errors that carry no sentinel. + wantFail bool + noIssuer bool + }{ + { + name: "outermost act wins over a nested one", + claims: map[string]any{"act": map[string]any{ + "iss": "https://platform", "sub": "agent-1", + "act": map[string]any{"iss": "https://other", "sub": "agent-0"}, + }}, + want: &Actor{Source: SourceAct, Issuer: "https://platform", Subject: "agent-1"}, + wantClaims: map[string]any{"iss": "https://platform", "sub": "agent-1"}, + }, + { + name: "act without iss takes the token issuer", + claims: map[string]any{"act": map[string]any{"sub": "agent-1"}}, + want: &Actor{Source: SourceAct, Issuer: "https://token-iss", Subject: "agent-1"}, + }, + { + name: "explicit act source", + source: SourceAct, + claims: map[string]any{"act": map[string]any{"iss": "https://platform", "sub": "agent-1"}}, + want: &Actor{Source: SourceAct, Issuer: "https://platform", Subject: "agent-1"}, + }, + {name: "act that is nil", claims: map[string]any{"act": nil}, wantErr: ErrNoActor}, + { + name: "act.iss that is empty", + claims: map[string]any{"act": map[string]any{"iss": "", "sub": "agent-1"}}, + wantErr: ErrMalformedActor, + }, + { + name: "client source without a token issuer", + source: SourceClient, + client: "client-1", + noIssuer: true, + wantErr: ErrMalformedActor, + }, + {name: "no act is refused", claims: map[string]any{"sub": "u"}, wantErr: ErrNoActor}, + {name: "act that is not an object", claims: map[string]any{"act": "agent-1"}, wantErr: ErrMalformedActor}, + {name: "act without sub", claims: map[string]any{"act": map[string]any{"iss": "https://platform"}}, wantErr: ErrMalformedActor}, + { + name: "client source ignores act and names the client", + source: SourceClient, + claims: map[string]any{"act": map[string]any{"sub": "agent-1"}}, + client: "client-1", + want: &Actor{Source: SourceClient, Issuer: "https://token-iss", Subject: "client-1"}, + }, + {name: "client source without a client ID", source: SourceClient, wantErr: ErrMalformedActor}, + {name: "unknown source", source: "bogus", wantFail: true}, + { + name: "act.iss that is not a string", + claims: map[string]any{"act": map[string]any{"iss": 42, "sub": "agent-1"}}, + wantErr: ErrMalformedActor, + }, + { + name: "no iss in act or on the token", + claims: map[string]any{"act": map[string]any{"sub": "agent-1"}}, + noIssuer: true, + wantErr: ErrMalformedActor, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + tokenIssuer := "https://token-iss" + if tt.noIssuer { + tokenIssuer = "" + } + got, err := Effective(tt.source, tt.claims, tokenIssuer, tt.client) + if tt.wantErr != nil || tt.wantFail { + require.Error(t, err) + if tt.wantErr != nil { + require.ErrorIs(t, err, tt.wantErr) + } + assert.Nil(t, got) + return + } + require.NoError(t, err) + assert.Equal(t, tt.want.Source, got.Source) + assert.Equal(t, tt.want.Issuer, got.Issuer) + assert.Equal(t, tt.want.Subject, got.Subject) + if tt.wantClaims != nil { + assert.Equal(t, tt.wantClaims, got.Claims) + } + if tt.want.Source == SourceAct { + assert.NotContains(t, got.Claims, "act") + } + }) + } +} + +func TestNewDefaultPolicy_Refusals(t *testing.T) { + t.Parallel() + tests := []struct { + name string + tokenIssuer string + actorIssuers []string + }{ + {name: "empty token issuer", actorIssuers: []string{"spiffe://td"}}, + {name: "empty actor issuer", tokenIssuer: "https://as", actorIssuers: []string{""}}, + {name: "token issuer with #", tokenIssuer: "https://as#frag"}, + {name: "actor issuer with #", tokenIssuer: "https://as", actorIssuers: []string{"spiffe://td#frag"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + p, err := NewDefaultPolicy(tt.tokenIssuer, tt.actorIssuers) + require.Error(t, err) + assert.Nil(t, p) + }) + } +} + +func TestEffective_ClaimsDoNotAliasInput(t *testing.T) { + t.Parallel() + nested := map[string]any{"sub": "agent-0"} + inner := map[string]any{"level": "high"} + list := []any{"a", map[string]any{"k": "v"}} + act := map[string]any{"iss": "https://platform", "sub": "agent-1", "act": nested, "meta": inner, "roles": list} + claims := map[string]any{"act": act} + + got, err := Effective(SourceAct, claims, "https://token-iss", "") + require.NoError(t, err) + want := map[string]any{"iss": "https://platform", "sub": "agent-1", "meta": map[string]any{"level": "high"}, + "roles": []any{"a", map[string]any{"k": "v"}}} + require.Equal(t, want, got.Claims) + + inner["level"] = "tampered" + list[0] = "tampered" + list[1].(map[string]any)["k"] = "tampered" + + assert.Equal(t, want, got.Claims) + + got.Claims["sub"] = "tampered" + got.Claims["extra"] = true + assert.Equal(t, "agent-1", act["sub"]) + assert.NotContains(t, act, "extra") +} + +func TestDefaultPolicy_Evaluate(t *testing.T) { + t.Parallel() + const ( + tokenIss = "https://as" + spiffe = "spiffe://td" + ) + tests := []struct { + name string + tokenIssuer string + actor *Actor + wantErr bool + wantAllow bool + wantReason string + wantPrinc string + wantSource string + }{ + { + name: "actor issuer is the token issuer", + tokenIssuer: tokenIss, + actor: &Actor{Issuer: tokenIss, Subject: "agent-1", Source: SourceAct}, + wantAllow: true, + wantReason: ReasonAllowed, + wantPrinc: tokenIss + "#agent-1", + wantSource: SourceAct, + }, + { + name: "actor from the client", + tokenIssuer: tokenIss, + actor: &Actor{Issuer: tokenIss, Subject: "client-1", Source: SourceClient}, + wantAllow: true, + wantReason: ReasonAllowed, + wantPrinc: tokenIss + "#client-1", + wantSource: SourceClient, + }, + { + name: "actor issuer is a configured actor issuer", + tokenIssuer: tokenIss, + actor: &Actor{Issuer: spiffe, Subject: "ns/agent"}, + wantAllow: true, + wantReason: ReasonAllowed, + wantPrinc: spiffe + "#ns/agent", + }, + { + name: "actor issuer not allowed", + tokenIssuer: tokenIss, + actor: &Actor{Issuer: "https://evil", Subject: "agent-1", Source: SourceAct}, + wantReason: ReasonIssuerNotAllowed, + wantSource: SourceAct, + }, + {name: "no actor", tokenIssuer: tokenIss, wantReason: ReasonNoActor}, + { + name: "actor without subject", + tokenIssuer: tokenIss, + actor: &Actor{Issuer: spiffe}, + wantReason: ReasonNoActor, + }, + { + name: "actor without issuer", + tokenIssuer: tokenIss, + actor: &Actor{Subject: "agent-1"}, + wantReason: ReasonNoActor, + }, + { + name: "request for another token issuer", + tokenIssuer: "https://other-as", + actor: &Actor{Issuer: spiffe, Subject: "ns/agent"}, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + p, err := NewDefaultPolicy(tokenIss, []string{spiffe}) + require.NoError(t, err) + got, err := p.Evaluate(context.Background(), Request{TokenIssuer: tt.tokenIssuer, Actor: tt.actor}) + if tt.wantErr { + require.Error(t, err) + assert.NotContains(t, err.Error(), tt.tokenIssuer) + assert.Contains(t, err.Error(), tokenIss) + assert.False(t, got.Allow) + return + } + require.NoError(t, err) + assert.Equal(t, Decision{Allow: tt.wantAllow, Reason: tt.wantReason, Principal: tt.wantPrinc, Source: tt.wantSource}, got) + }) + } +} + +func TestReasons(t *testing.T) { + t.Parallel() + tests := map[string]string{ + ReasonAllowed: "allowed", + ReasonNoActor: "no_actor", + ReasonIssuerNotAllowed: "actor_issuer_not_allowed", + } + for got, want := range tests { + assert.Equal(t, want, got) + } +} diff --git a/pkg/authserver/actor/policy.go b/pkg/authserver/actor/policy.go new file mode 100644 index 0000000000..1960092c2f --- /dev/null +++ b/pkg/authserver/actor/policy.go @@ -0,0 +1,85 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package actor + +import ( + "context" + "errors" + "fmt" + "strings" +) + +// Stable reasons in Decision.Reason. +const ( + ReasonAllowed = "allowed" + ReasonNoActor = "no_actor" + ReasonIssuerNotAllowed = "actor_issuer_not_allowed" +) + +// DefaultPolicy allows an actor whose issuer is the token issuer or one of the +// issuers configured to act through it. There is one policy per token issuer. +type DefaultPolicy struct { + tokenIssuer string + issuers map[string]struct{} +} + +var _ Policy = (*DefaultPolicy)(nil) + +// NewDefaultPolicy returns a DefaultPolicy for tokens issued by tokenIssuer. +// The actor's issuer must be tokenIssuer or one of actorIssuers, which may be +// empty. +// +// act.iss is not required to equal the token issuer: a ToolHive authorization +// server names its agents under a different issuer (for example a SPIFFE trust +// domain), and the server refuses an actor issuer equal to its own issuer. +// +// tokenIssuer must be non-empty. Empty issuers are refused, and so is any +// issuer containing #, because Principal is issuer#subject and splitting on the +// first # must recover both parts. +func NewDefaultPolicy(tokenIssuer string, actorIssuers []string) (*DefaultPolicy, error) { + if tokenIssuer == "" { + return nil, errors.New("actor policy: token issuer is empty") + } + p := &DefaultPolicy{ + tokenIssuer: tokenIssuer, + issuers: make(map[string]struct{}, len(actorIssuers)+1), + } + if strings.Contains(tokenIssuer, "#") { + return nil, fmt.Errorf("actor policy: token issuer %q contains #", tokenIssuer) + } + p.issuers[tokenIssuer] = struct{}{} + for _, iss := range actorIssuers { + if iss == "" { + return nil, errors.New("actor policy: allowed actor issuer is empty") + } + if strings.Contains(iss, "#") { + return nil, fmt.Errorf("actor policy: allowed actor issuer %q contains #", iss) + } + p.issuers[iss] = struct{}{} + } + return p, nil +} + +// Evaluate implements Policy. An Actor without an issuer or a subject counts as +// no actor. A request whose TokenIssuer is not the policy's returns an error, +// because the policy cannot decide for another issuer. +func (p *DefaultPolicy) Evaluate(_ context.Context, req Request) (Decision, error) { + if req.TokenIssuer != p.tokenIssuer { + return Decision{}, fmt.Errorf("actor policy: request is for another token issuer; this policy is for %q", + p.tokenIssuer) + } + a := req.Actor + if a == nil || a.Issuer == "" || a.Subject == "" { + return Decision{Reason: ReasonNoActor}, nil + } + if _, ok := p.issuers[a.Issuer]; !ok { + return Decision{Reason: ReasonIssuerNotAllowed, Source: a.Source}, nil + } + return Decision{ + Allow: true, + Reason: ReasonAllowed, + Principal: a.Issuer + "#" + a.Subject, + Source: a.Source, + }, nil +} diff --git a/pkg/authserver/server/tokenexchange/actor_validator.go b/pkg/authserver/server/tokenexchange/actor_validator.go index 062cb3c81b..c3d74feb6d 100644 --- a/pkg/authserver/server/tokenexchange/actor_validator.go +++ b/pkg/authserver/server/tokenexchange/actor_validator.go @@ -76,7 +76,8 @@ type ActorProfile struct { // ActorTokenValidator checks the actor token that a client presents during ID-JAG // issuance and reports which agent it belongs to. How a validator is registered and -// selected is not part of this interface. +// selected is not part of this interface. Authorizing the act claim of a token +// presented to ToolHive is pkg/authserver/actor. // // ValidateActor is called once per issuance, after the grant checks and before the // ID-JAG is signed. ToolHive builds the act claim from the answer: sub is AgentID, and @@ -126,10 +127,12 @@ type ActorProfile struct { // It holds the configured target, not text from the request. // - Find the user by ActorRequest.Grant.Upstream when the validator binds // users by a per-issuer claim. Check that StableClaim is the claim the validator -// expects for that Issuer, then look the user up by StableValue. A mismatch, or an -// issuer the validator does not know, is a configuration fault. Return a plain -// error for it, not a denial, because a denial is final for the client and would -// hide the fault from operators. +// expects for that Issuer, then look the user up by StableValue. Issuer, +// StableClaim and StableValue are the same key as subject.Ref in +// pkg/authserver/subject. A mismatch, or an issuer the validator does not +// know, is a configuration fault. Return a plain error for it, not a denial, +// because a denial is final for the client and would hide the fault from +// operators. // - The whole validation, including the validator's own calls to remote services, // has a budget of currently 5 seconds; ToolHive may raise it but will not lower // it. The budget also covers any time the call waits for a free slot when many From f00332ef0e38c2a4dd03e2c61d8802f4cdd25365 Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Tue, 17 Nov 2026 13:07:16 +0100 Subject: [PATCH 4/5] Validate the binding claim for delegated access 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 --- pkg/authserver/subject/binding_claim.go | 68 +++++++++++++++++++ pkg/authserver/subject/binding_claim_test.go | 66 ++++++++++++++++++ pkg/authserver/subjectresolver/resolver.go | 11 ++- .../subjectresolver/resolver_test.go | 24 +++++-- 4 files changed, 162 insertions(+), 7 deletions(-) create mode 100644 pkg/authserver/subject/binding_claim.go create mode 100644 pkg/authserver/subject/binding_claim_test.go diff --git a/pkg/authserver/subject/binding_claim.go b/pkg/authserver/subject/binding_claim.go new file mode 100644 index 0000000000..91d57f48cc --- /dev/null +++ b/pkg/authserver/subject/binding_claim.go @@ -0,0 +1,68 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package subject + +import ( + "errors" + "fmt" + "net/url" + "slices" + "strings" +) + +// ErrInvalidBindingClaim means a configured binding claim cannot identify a +// local user. +var ErrInvalidBindingClaim = errors.New("invalid binding claim") + +// oktaDomainSuffixes are the host suffixes of Okta's hosted domains. +var oktaDomainSuffixes = []string{".okta.com", ".oktapreview.com", ".okta-emea.com"} + +// mutableClaims are known claim names that users or their administrators can +// change. The list is not exhaustive. unique_name is where Entra v1 tokens +// carry the UPN. +var mutableClaims = []string{ + "email", "preferred_username", "upn", "unique_name", + "name", "nickname", "given_name", "family_name", "phone_number", + "mail", "login", "username", +} + +// ValidateBindingClaim checks the claim that maps a token's subject to a local +// user, for the token issuer named by issuer. A known mutable claim name (such +// as email, preferred_username, upn, unique_name or name, in any letter case), +// an empty claim, or a claim with surrounding whitespace is refused. A claim +// that passes is not proven stable: prefer sub, oid or uid. A non-empty +// warning means the claim is sub on an Okta custom authorization server; the +// caller decides how to report it. +func ValidateBindingClaim(issuer, claim string) (warning string, err error) { + if claim == "" { + return "", fmt.Errorf("%w: the claim name is empty", ErrInvalidBindingClaim) + } + if strings.TrimSpace(claim) != claim { + return "", fmt.Errorf("%w: %q has leading or trailing whitespace", ErrInvalidBindingClaim, claim) + } + if slices.ContainsFunc(mutableClaims, func(m string) bool { return strings.EqualFold(m, claim) }) { + return "", fmt.Errorf("%w: %q is a known mutable claim name; use a stable claim such as sub, oid or uid", + ErrInvalidBindingClaim, claim) + } + if claim == "sub" && isOktaCustomAuthorizationServer(issuer) { + return "sub on an Okta custom authorization server may not match the sign-in subject; consider uid", nil + } + return "", nil +} + +// isOktaCustomAuthorizationServer reports whether issuer has the shape of an +// Okta custom authorization server (https:///oauth2/) on an Okta +// hosted domain. Okta custom domains cannot be recognised and return false. +func isOktaCustomAuthorizationServer(issuer string) bool { + u, err := url.Parse(issuer) + if err != nil { + return false + } + if !strings.HasPrefix(u.Path, "/oauth2/") { + return false + } + return slices.ContainsFunc(oktaDomainSuffixes, func(suffix string) bool { + return strings.HasSuffix(strings.ToLower(u.Hostname()), suffix) + }) +} diff --git a/pkg/authserver/subject/binding_claim_test.go b/pkg/authserver/subject/binding_claim_test.go new file mode 100644 index 0000000000..72220e93d7 --- /dev/null +++ b/pkg/authserver/subject/binding_claim_test.go @@ -0,0 +1,66 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package subject + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestValidateBindingClaim(t *testing.T) { + t.Parallel() + + const ( + genericIssuer = "https://login.example.com" + oktaCustomIssuer = "https://dev-123456.okta.com/oauth2/default" + oktaOrgIssuer = "https://dev-1.okta.com" + oktaUpperIssuer = "https://DEV-1.OKTA.COM/oauth2/default" + ) + + tests := []struct { + name string + issuer string + claim string + wantErr bool + wantWarning bool + }{ + {name: "email is refused", issuer: genericIssuer, claim: "email", wantErr: true}, + {name: "preferred_username is refused", issuer: genericIssuer, claim: "preferred_username", wantErr: true}, + {name: "upn is refused", issuer: genericIssuer, claim: "upn", wantErr: true}, + {name: "unique_name is refused", issuer: genericIssuer, claim: "unique_name", wantErr: true}, + {name: "name is refused", issuer: genericIssuer, claim: "name", wantErr: true}, + {name: "mail is refused", issuer: genericIssuer, claim: "mail", wantErr: true}, + {name: "username is refused", issuer: genericIssuer, claim: "username", wantErr: true}, + {name: "phone_number is refused", issuer: genericIssuer, claim: "phone_number", wantErr: true}, + {name: "Given_Name is refused", issuer: genericIssuer, claim: "Given_Name", wantErr: true}, + {name: "Email is refused", issuer: genericIssuer, claim: "Email", wantErr: true}, + {name: "leading space is refused", issuer: genericIssuer, claim: " email", wantErr: true}, + {name: "trailing space is refused", issuer: genericIssuer, claim: "email ", wantErr: true}, + {name: "empty claim is refused", issuer: genericIssuer, claim: "", wantErr: true}, + {name: "oid is allowed", issuer: genericIssuer, claim: "oid"}, + {name: "sub on Okta custom authorization server warns", issuer: oktaCustomIssuer, claim: "sub", wantWarning: true}, + {name: "sub on Okta custom authorization server with uppercase host warns", issuer: oktaUpperIssuer, claim: "sub", wantWarning: true}, + {name: "sub on the Okta org authorization server is allowed without warning", issuer: oktaOrgIssuer, claim: "sub"}, + {name: "sub on another issuer is allowed without warning", issuer: genericIssuer, claim: "sub"}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + warning, err := ValidateBindingClaim(tc.issuer, tc.claim) + if tc.wantErr { + require.ErrorIs(t, err, ErrInvalidBindingClaim) + } else { + require.NoError(t, err) + } + if tc.wantWarning { + require.NotEmpty(t, warning) + } else { + require.Empty(t, warning) + } + }) + } +} diff --git a/pkg/authserver/subjectresolver/resolver.go b/pkg/authserver/subjectresolver/resolver.go index a007dd37aa..03c2b7f1ce 100644 --- a/pkg/authserver/subjectresolver/resolver.go +++ b/pkg/authserver/subjectresolver/resolver.go @@ -58,8 +58,12 @@ var _ subject.Resolver = (*Resolver)(nil) // issuers for the same provider name with different subject claims (an Okta // custom authorization server carries the sign-in subject in uid), but nothing // configures that yet; it belongs to the third-party issuers work. -// It returns an error if the store is nil, no providers are given, or an -// entry has an empty issuer, name or subject claim. +// It returns an error if the store is nil, no providers are given, an entry has +// an empty issuer, name or subject claim, or subject.ValidateBindingClaim +// refuses an entry's claim (the error wraps subject.ErrInvalidBindingClaim). +// The warning ValidateBindingClaim can return, for sub on an Okta custom +// authorization server, is ignored here; callers who want it call +// ValidateBindingClaim themselves. func New(providers map[string]Provider, store IdentityStore) (*Resolver, error) { if store == nil { return nil, errors.New("subjectresolver: store is required") @@ -72,6 +76,9 @@ func New(providers map[string]Provider, store IdentityStore) (*Resolver, error) if issuer == "" || p.Name == "" || p.SubjectClaim == "" { return nil, errors.New("subjectresolver: provider entries need an issuer, a name and a subject claim") } + if _, err := subject.ValidateBindingClaim(issuer, p.SubjectClaim); err != nil { + return nil, fmt.Errorf("subjectresolver: provider %q: %w", p.Name, err) + } copied[issuer] = p } return &Resolver{providers: copied, store: store}, nil diff --git a/pkg/authserver/subjectresolver/resolver_test.go b/pkg/authserver/subjectresolver/resolver_test.go index 0a94d7791e..0c5be621ca 100644 --- a/pkg/authserver/subjectresolver/resolver_test.go +++ b/pkg/authserver/subjectresolver/resolver_test.go @@ -200,12 +200,23 @@ func TestNewRefusesInvalidInput(t *testing.T) { name string providers map[string]subjectresolver.Provider store subjectresolver.IdentityStore + wantErr error }{ - {"nil store", map[string]subjectresolver.Provider{idpIssuer: valid}, nil}, - {"no providers", nil, store}, - {"empty issuer", map[string]subjectresolver.Provider{"": valid}, store}, - {"empty name", map[string]subjectresolver.Provider{idpIssuer: {SubjectClaim: "sub"}}, store}, - {"empty subject claim", map[string]subjectresolver.Provider{idpIssuer: {Name: "okta"}}, store}, + {"nil store", map[string]subjectresolver.Provider{idpIssuer: valid}, nil, nil}, + {"no providers", nil, store, nil}, + {"empty issuer", map[string]subjectresolver.Provider{"": valid}, store, nil}, + {"empty name", map[string]subjectresolver.Provider{idpIssuer: {SubjectClaim: "sub"}}, store, nil}, + {"empty subject claim", map[string]subjectresolver.Provider{idpIssuer: {Name: "okta"}}, store, nil}, + { + "mutable email claim", + map[string]subjectresolver.Provider{idpIssuer: {Name: "okta", SubjectClaim: "email"}}, + store, subject.ErrInvalidBindingClaim, + }, + { + "mutable preferred_username claim", + map[string]subjectresolver.Provider{idpIssuer: {Name: "okta", SubjectClaim: "preferred_username"}}, + store, subject.ErrInvalidBindingClaim, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -213,6 +224,9 @@ func TestNewRefusesInvalidInput(t *testing.T) { r, err := subjectresolver.New(tt.providers, tt.store) require.Error(t, err) assert.Nil(t, r) + if tt.wantErr != nil { + assert.ErrorIs(t, err, tt.wantErr) + } }) } } From 24cfd3b9fee28ab4ec9cc584e872863dfc1366d2 Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Sat, 21 Nov 2026 21:38:40 +0100 Subject: [PATCH 5/5] Add mocks for the resolver and actor policy 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 --- pkg/authserver/actor/actor.go | 2 + pkg/authserver/actor/mocks/mock_policy.go | 57 +++++++++++++++++++ pkg/authserver/subject/mocks/mock_resolver.go | 57 +++++++++++++++++++ pkg/authserver/subject/subject.go | 2 + 4 files changed, 118 insertions(+) create mode 100644 pkg/authserver/actor/mocks/mock_policy.go create mode 100644 pkg/authserver/subject/mocks/mock_resolver.go diff --git a/pkg/authserver/actor/actor.go b/pkg/authserver/actor/actor.go index 1abfc3204d..f153972c32 100644 --- a/pkg/authserver/actor/actor.go +++ b/pkg/authserver/actor/actor.go @@ -73,6 +73,8 @@ type Decision struct { Source string } +//go:generate mockgen -destination=mocks/mock_policy.go -package=mocks -source=actor.go Policy + // Policy decides whether an actor may act for a user. A Decision that does not // allow is a denial. A non-nil error means the policy could not decide (for // example a directory-backed policy that is unavailable, or a request for diff --git a/pkg/authserver/actor/mocks/mock_policy.go b/pkg/authserver/actor/mocks/mock_policy.go new file mode 100644 index 0000000000..ad16746308 --- /dev/null +++ b/pkg/authserver/actor/mocks/mock_policy.go @@ -0,0 +1,57 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: actor.go +// +// Generated by this command: +// +// mockgen -destination=mocks/mock_policy.go -package=mocks -source=actor.go Policy +// + +// Package mocks is a generated GoMock package. +package mocks + +import ( + context "context" + reflect "reflect" + + actor "github.com/stacklok/toolhive/pkg/authserver/actor" + gomock "go.uber.org/mock/gomock" +) + +// MockPolicy is a mock of Policy interface. +type MockPolicy struct { + ctrl *gomock.Controller + recorder *MockPolicyMockRecorder + isgomock struct{} +} + +// MockPolicyMockRecorder is the mock recorder for MockPolicy. +type MockPolicyMockRecorder struct { + mock *MockPolicy +} + +// NewMockPolicy creates a new mock instance. +func NewMockPolicy(ctrl *gomock.Controller) *MockPolicy { + mock := &MockPolicy{ctrl: ctrl} + mock.recorder = &MockPolicyMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockPolicy) EXPECT() *MockPolicyMockRecorder { + return m.recorder +} + +// Evaluate mocks base method. +func (m *MockPolicy) Evaluate(ctx context.Context, req actor.Request) (actor.Decision, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Evaluate", ctx, req) + ret0, _ := ret[0].(actor.Decision) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Evaluate indicates an expected call of Evaluate. +func (mr *MockPolicyMockRecorder) Evaluate(ctx, req any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Evaluate", reflect.TypeOf((*MockPolicy)(nil).Evaluate), ctx, req) +} diff --git a/pkg/authserver/subject/mocks/mock_resolver.go b/pkg/authserver/subject/mocks/mock_resolver.go new file mode 100644 index 0000000000..ac76176c1c --- /dev/null +++ b/pkg/authserver/subject/mocks/mock_resolver.go @@ -0,0 +1,57 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: subject.go +// +// Generated by this command: +// +// mockgen -destination=mocks/mock_resolver.go -package=mocks -source=subject.go Resolver +// + +// Package mocks is a generated GoMock package. +package mocks + +import ( + context "context" + reflect "reflect" + + subject "github.com/stacklok/toolhive/pkg/authserver/subject" + gomock "go.uber.org/mock/gomock" +) + +// MockResolver is a mock of Resolver interface. +type MockResolver struct { + ctrl *gomock.Controller + recorder *MockResolverMockRecorder + isgomock struct{} +} + +// MockResolverMockRecorder is the mock recorder for MockResolver. +type MockResolverMockRecorder struct { + mock *MockResolver +} + +// NewMockResolver creates a new mock instance. +func NewMockResolver(ctrl *gomock.Controller) *MockResolver { + mock := &MockResolver{ctrl: ctrl} + mock.recorder = &MockResolverMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockResolver) EXPECT() *MockResolverMockRecorder { + return m.recorder +} + +// Resolve mocks base method. +func (m *MockResolver) Resolve(ctx context.Context, ref subject.Ref) (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Resolve", ctx, ref) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Resolve indicates an expected call of Resolve. +func (mr *MockResolverMockRecorder) Resolve(ctx, ref any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Resolve", reflect.TypeOf((*MockResolver)(nil).Resolve), ctx, ref) +} diff --git a/pkg/authserver/subject/subject.go b/pkg/authserver/subject/subject.go index 1e4c845390..06bf91cdd4 100644 --- a/pkg/authserver/subject/subject.go +++ b/pkg/authserver/subject/subject.go @@ -29,6 +29,8 @@ type Ref struct { Value string } +//go:generate mockgen -destination=mocks/mock_resolver.go -package=mocks -source=subject.go Resolver + // Resolver maps a Ref to the canonical local user ID. // // A nil error always comes with a non-empty user ID. Resolvers never create