authn

package
v0.53.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2026 License: Apache-2.0 Imports: 27 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package authn authenticates every caller offline (programme C2 r5): an audience-bound JWT, checked against an allowlisted issuer's JWKS. No TokenReview: liveness comes from the AgentRun itself (runwatch).

Every refusal wraps ErrUnauthenticated; the finer sentinels (ErrTokenExpired, ErrWrongAudience, ...) say why. Neither a token nor its claims ever reach a log line or an error message.

Index

Constants

View Source
const (
	// TokenUseAccess is the ID-plus-access pair for the web, and maku's access token as a bearer:
	// the zitadel preset, and any IdP that issues JWT access tokens with an audience.
	TokenUseAccess = "access"
	// TokenUseID makes the ID token the credential: its aud names the web or the CLI client. The
	// web session's access token is never parsed, and may be opaque.
	TokenUseID = "id"
)

What a human presents as the credential (PR3).

View Source
const (
	AudienceRun    = "room-broker"  // fixed by SP1 (C2); Kyverno reserves it to namespace agents
	AudienceSystem = "rooms-system" // ruling P3
	// AudienceRoomTools is a run's :8090 token in roomTools.auth tokenreview. It is apart from
	// AudienceRun: the harness, where the model's commands run, holds it, and it must not open :8443.
	AudienceRoomTools = "room-tools"
)

The audiences this broker accepts.

View Source
const (
	RolesClaimMissing = "missing" // the claim, or a step of its pointer, is absent
	RolesClaimType    = "type"    // neither an array of strings, an object nor a string
	RolesClaimBounds  = "bounds"  // over maxRoleNames names, or a name over maxRoleNameSize bytes
)

Why a roles claim gave no group: a closed set, the label of rooms_human_roles_claim_refused_total.

View Source
const ForwardedAccessHeader = "X-Forwarded-Access-Token"

ForwardedAccessHeader carries the access token oauth2-proxy forwards beside the ID token. Not named ...TokenHeader: gosec G101 reads that as a credential.

View Source
const LocalClientID = "local"

LocalClientID is the local user's rooms client. Every client of the loopback listener is the one human, so the web UI/CLI split (P18) does not apply: the broker's WebClient is this id too.

View Source
const LocalPrincipal = "human:local"

LocalPrincipal is the one human of a local-mode broker (adoption 3b): whoever reaches the loopback listener through kubectl port-forward, which only a cluster user can open.

Variables

View Source
var (
	// ErrUnauthenticated is every refusal of a credential: missing, malformed or
	// invalid. APIs map it to 401.
	ErrUnauthenticated = errors.New("unauthenticated")
	// ErrForbidden is a valid credential for a principal outside the allowlist. APIs map it to 403.
	ErrForbidden = errors.New("forbidden")

	// ErrTokenExpired is a token past exp plus the allowed skew.
	ErrTokenExpired = fmt.Errorf("%w: token expired", ErrUnauthenticated)
	// ErrTokenNotYetValid is a token before nbf or iat, minus the allowed skew.
	ErrTokenNotYetValid = fmt.Errorf("%w: token not yet valid", ErrUnauthenticated)
	// ErrWrongIssuer is a token from an issuer this Verifier does not trust.
	ErrWrongIssuer = fmt.Errorf("%w: wrong issuer", ErrUnauthenticated)
	// ErrWrongAudience is a token minted for another audience.
	ErrWrongAudience = fmt.Errorf("%w: wrong audience", ErrUnauthenticated)
	// ErrUnknownKey is a token whose kid the issuer's JWKS does not publish.
	ErrUnknownKey = fmt.Errorf("%w: unknown signing key", ErrUnauthenticated)
	// ErrKeysStale is a token whose key was last confirmed by the issuer longer
	// ago than the stale cap: an outage long enough that a rotated-out key could
	// still be in our hands.
	ErrKeysStale = fmt.Errorf("%w: issuer keys past the stale cap", ErrUnauthenticated)
)
View Source
var ErrIssuerMismatch = errors.New("discovery: the document's issuer is not the configured one (OIDC Discovery §4.3)")

ErrIssuerMismatch is a discovery document whose issuer is not the configured one, byte for byte.

View Source
var ErrReviewUnavailable = fmt.Errorf("%w: token review unavailable", ErrUnauthenticated)

ErrReviewUnavailable is a TokenReview call that failed (RBAC, a missing auth-delegator binding, an apiserver blip): no verdict on the token. It wraps ErrUnauthenticated, so the caller refuses; the broker logs it apart from a bad credential.

View Source
var ErrRolesClaim = errors.New("roles claim refused")

ErrRolesClaim is every refusal of a token's roles claim. The token is still valid: its principal holds no group, which the policy refuses as "not in an agents group".

Functions

func Bearer

func Bearer(r *http.Request) (string, error)

Bearer returns the request's bearer token. The scheme is case-insensitive (RFC 9110).

func DiscoveryURL added in v0.47.0

func DiscoveryURL(issuer string) string

DiscoveryURL is issuer's OpenID Provider Configuration URL (OIDC Discovery §4): a trailing slash on the issuer is not doubled.

func HTTPSEndpoint added in v0.47.0

func HTTPSEndpoint(raw string) bool

HTTPSEndpoint reports whether raw is an absolute https:// URL with no userinfo: what a client checks again before it sends a credential to an endpoint it read or stored.

func LoopbackOrigins

func LoopbackOrigins(publicURL string) []string

LoopbackOrigins is every origin a local broker answers as itself: publicURL first, then its port under each loopback name. kubectl port-forward listens on 127.0.0.1 and [::1] and keeps the Host the client sent, so these three names on that port are the listener's own; a DNS-rebound page keeps a Host of its own and matches none. A publicURL that is not http://host:port gives itself.

func ValidClientClaim added in v0.47.0

func ValidClientClaim(claim string) bool

ValidClientClaim reports whether claim may name a sponsored token's client.

func ValidRolesClaim added in v0.47.0

func ValidRolesClaim(claim string) bool

ValidRolesClaim reports whether claim is a claim name, or a well-formed RFC 6901 pointer.

Types

type Claims

type Claims struct {
	jwt.RegisteredClaims
	Groups          []string `json:"groups,omitempty"`
	AuthorizedParty string   `json:"azp,omitempty"`
	// ClientID is where ZITADEL names the client in a JWT access token, which has no azp.
	ClientID string `json:"client_id,omitempty"`
	// ProjectRoles is the roles claim ZITADEL asserts natively: role name to granting orgs.
	ProjectRoles map[string]json.RawMessage `json:"urn:zitadel:iam:org:project:roles,omitempty"`
	// contains filtered or unexported fields
}

Claims is what a verified token asserts.

func (*Claims) GroupNames

func (c *Claims) GroupNames() []string

GroupNames is the groups claim our ZITADEL action sets on ID tokens, else the project role names ZITADEL asserts natively, which is what a maku access token may carry instead (accessTokenRoleAssertion). Sorted, never nil.

func (*Claims) RoleNames added in v0.47.0

func (c *Claims) RoleNames(claim string) ([]string, error)

RoleNames is the group names the roles claim holds. claim is a claim name, or an RFC 6901 pointer into the claim set when it starts with "/"; "" is GroupNames, the zitadel preset's rule. The value may be an array of strings, an object (its keys, sorted) or one string. A missing claim, another shape, or one over the bounds is a *RolesClaimError and no names. The bounds apply to a configured claim only: the zitadel rule keeps today's behaviour.

func (*Claims) UnmarshalJSON added in v0.47.0

func (c *Claims) UnmarshalJSON(b []byte) error

UnmarshalJSON keeps the raw claim set beside the typed fields, so a configured roles claim can be read by name or pointer. groups and the ZITADEL roles claim decode leniently: a token whose groups is a string (Authentik) must still verify, and RoleNames judges the shape.

type Discovery added in v0.47.0

type Discovery struct {
	Issuer                      string `json:"issuer"`
	JWKSURI                     string `json:"jwks_uri"`
	AuthorizationEndpoint       string `json:"authorization_endpoint,omitempty"`
	TokenEndpoint               string `json:"token_endpoint,omitempty"`
	DeviceAuthorizationEndpoint string `json:"device_authorization_endpoint,omitempty"`
}

Discovery is what Maku reads from an issuer's OpenID Provider Configuration.

func Discover added in v0.47.0

func Discover(ctx context.Context, hc *http.Client, issuer string) (Discovery, error)

Discover fetches issuer's OpenID Provider Configuration through hc. The document's issuer must equal issuer exactly (OIDC Discovery §4.3), and its jwks_uri be an absolute https:// URL. An error names the HTTP status, never the body.

type HumanOptions added in v0.47.0

type HumanOptions struct {
	// TokenUse is TokenUseAccess ("" too) or TokenUseID.
	TokenUse string
	// ZITADEL keeps the zitadel preset's rules (Ruling AS): every token's aud holds Audience (the
	// project id) and its client, which is azp on an ID token and client_id on an access token.
	// Otherwise an ID token's aud holds its client (OIDC Core), and an access token's aud holds
	// Audience, its client in azp or client_id.
	ZITADEL bool
	// Audience is the aud value every access token must hold. Unread under TokenUseID.
	Audience func() string
	// RolesClaim names the claim holding the groups, or an RFC 6901 pointer to it; "" is the
	// zitadel preset's GroupNames.
	RolesClaim string
	// Web and CLI are the rooms clients: oauth2-proxy's, and maku's ("" until it has one).
	Web, CLI func() string
	// Origin is the only Origin a browser request may carry (T9).
	Origin string
	// RolesRefused counts a roles claim that gave no group, by a RolesClaim* reason. Optional.
	RolesRefused func(ctx context.Context, reason string)
}

HumanOptions configures Humans over one OIDC issuer. The id functions are called on every request; an unreadable id returns "", which refuses.

type Humans

type Humans struct {
	// contains filtered or unexported fields
}

Humans re-validates what oauth2-proxy forwards (§3, S5): the ID token in Authorization and, beside it, the access token in X-Forwarded-Access-Token. The broker never trusts a header oauth2-proxy merely asserts. maku sends its own token as a bearer, which oauth2-proxy passes through (phase 6).

func NewHumansWith added in v0.47.0

func NewHumansWith(v *Verifier, o HumanOptions) *Humans

NewHumansWith authenticates the humans of one OIDC issuer, by o's token use and rules.

func (*Humans) Authenticate

func (h *Humans) Authenticate(r *http.Request) (Principal, error)

Authenticate maps a viewer's request to a human principal. A foreign Origin is ErrForbidden; every other refusal wraps ErrUnauthenticated. ClientID says which client the session came through, so callers can tell the web UI from maku (ruling P18).

func (*Humans) VerifyHuman

func (h *Humans) VerifyHuman(ctx context.Context, raw string) (*Claims, error)

VerifyHuman checks an ID token. Under the zitadel preset (Ruling AS) its aud holds the project id and an allowlisted rooms client, and azp names that client: ZITADEL lists every app of the project in aud, so only azp says which app the token was issued to. Otherwise its aud holds the client it was issued to (azp, else client_id, else its one aud). Machine tokens stay on Verify's one-audience rule (AF).

func (*Humans) VerifyHumanAccess

func (h *Humans) VerifyHumanAccess(ctx context.Context, raw string) (*Claims, error)

VerifyHumanAccess checks a JWT access token. Under the zitadel preset its aud holds the project id and its client, read from client_id: ZITADEL mints access tokens without azp (review C1). Otherwise its aud holds the configured audience, and azp or client_id names an allowlisted client. Under token use id no access token is verified.

type Local

type Local struct {
	// contains filtered or unexported fields
}

Local authenticates every request as LocalPrincipal. Reaching the loopback listener is the only credential, so two checks stand in for the token: T9's Origin (a page from another origin must not act through the user's port-forward) and the Host (one of publicURL's loopback names on its port: a DNS-rebound page keeps its own Host, which kubectl port-forward preserves).

func NewLocal

func NewLocal(publicURL string, groups []string) *Local

NewLocal accepts requests from publicURL's loopback origins (or with no Origin, as non-browser clients send), and only with a Host those origins name.

func NewLocalWithClock

func NewLocalWithClock(publicURL string, groups []string, now func() time.Time) *Local

NewLocalWithClock is NewLocal with the clock a session's expiry is measured on: the one-hour life is what humanapi caps a connection at, so a test pins it rather than racing the wall clock.

func (*Local) Authenticate

func (l *Local) Authenticate(r *http.Request) (Principal, error)

Authenticate returns LocalPrincipal, in every group the broker knows.

type Option

type Option func(*options)

Option configures a Verifier.

func WithCacheTTL

func WithCacheTTL(d time.Duration) Option

WithCacheTTL sets how long a fetched JWKS is trusted before a refetch (default 1 h).

func WithClock

func WithClock(now func() time.Time) Option

WithClock replaces time.Now for token expiry and the JWKS cache.

func WithHTTPClient

func WithHTTPClient(c *http.Client) Option

WithHTTPClient replaces the JWKS client; pass an httpx client, for example one trusting a private CA. The default is httpx.New with the system pool.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets where JWKS refreshes are reported. The default discards.

func WithMaxStale

func WithMaxStale(d time.Duration) Option

WithMaxStale sets how long held keys keep verifying after the last successful fetch while the issuer is unreachable (default 24 h).

func WithMinRefreshInterval

func WithMinRefreshInterval(d time.Duration) Option

WithMinRefreshInterval sets the least time between two JWKS fetches (default 1 min), so a flood of unknown kids cannot hammer the issuer.

type Principal

type Principal struct {
	Kind        envelope.ActorKind
	ID          string // agent:<runId> | human:<sub> | system:<component>
	RunID       string
	Sub         string
	Groups      []string
	ClientID    string    // humans: the rooms client, the ID token's azp or maku's client_id (ruling P18)
	Expiry      time.Time // a connection lives min(exp, 1 h)
	AccessToken string    // humans and sponsored principals; forwarded to the factory (C4), never logged
	// Sponsored marks a sponsored principal's token (factory interfaces F4): a service account's,
	// which may start api tasks and read its own tasks' rooms, and nothing a human may do.
	Sponsored bool
	// Internal marks an internal principal (RunLore agent-to-agent RA2): a sponsored principal
	// allowed internal data. It is always set with Sponsored, never alone.
	Internal bool
}

Principal is who is calling, in the C2 canonical form.

func (Principal) GoString

func (p Principal) GoString() string

GoString keeps AccessToken out of %#v.

func (Principal) LogValue

func (p Principal) LogValue() slog.Value

LogValue keeps AccessToken out of every log line that carries a Principal.

func (Principal) String

func (p Principal) String() string

String is the principal's id, so %v and %+v never print AccessToken.

type RolesClaimError added in v0.47.0

type RolesClaimError struct{ Reason string }

RolesClaimError says why a roles claim gave no group. It never carries the claim's value.

func (*RolesClaimError) Error added in v0.47.0

func (e *RolesClaimError) Error() string

func (*RolesClaimError) Is added in v0.47.0

func (e *RolesClaimError) Is(target error) bool

Is makes every RolesClaimError an ErrRolesClaim.

type RunIssuer

type RunIssuer struct {
	Verifier   RunVerifier
	SubPattern *regexp.Regexp // one capture group: the runId; must match the whole subject
}

RunIssuer is one allowlisted issuer and how its subject names a run. Today the only issuer is the cluster's (sub system:serviceaccount:<runs.namespace>:<runs.namePrefix><runId>); a runtime minting its own workload JWTs is one more entry, not a new path (C2 r5).

type RunVerifier

type RunVerifier interface {
	Verify(ctx context.Context, raw, audience string) (*Claims, error)
}

RunVerifier checks a run's token for audience: a JWKS Verifier, or the cluster's TokenReview where no issuer URL is reachable (kind, adoption 3b).

type Runs

type Runs struct {
	// contains filtered or unexported fields
}

Runs authenticates run bridges against the allowlisted issuers.

func NewRuns

func NewRuns(issuers ...RunIssuer) (*Runs, error)

NewRuns allowlists issuers, tried in order. Each needs a Verifier and a SubPattern with exactly one capture group.

func (*Runs) Authenticate

func (r *Runs) Authenticate(req *http.Request) (Principal, error)

Authenticate maps a bridge's token to agent:<runId>. It does NOT check that the run is live: the caller does, against the AgentRun watch.

type Sponsored struct {
	V       *Verifier
	Clients []SponsoredClient
	Exclude func() []string
	// Audience is the value a token's aud must hold: the project id under the zitadel preset, as
	// the human path pins it, else the configured audience. Unset or unreadable, nobody is admitted.
	Audience func() string
	// ClientClaim names the string claim holding the client id, for an IdP that puts it elsewhere
	// (Okta's cid): one of ValidClientClaim's, else nobody is admitted. azp or client_id naming
	// another client still refuses. "" reads azp, else client_id.
	ClientClaim string
	// Generic is the generic preset: the roles claim is not judged here, and with no ClientClaim
	// a one-element aud may name the client. Unset is the zitadel preset, byte for byte.
	Generic bool
}

Sponsored authenticates a sponsored principal (factory interfaces F4, R2): a ZITADEL service account's access token, issued to one of Clients through client credentials. The client id is the claim ZITADEL sets from the authenticated client; nothing else in the token names the principal. Exclude lists the human clients' ids: a principal whose id equals one never matches. Every error fails closed: no verifier, an unreadable id, or two principals resolving to the same id (the runtime twin of the config's duplicate-file check) admit nobody on that id.

func (*Sponsored) Authenticate

func (s *Sponsored) Authenticate(ctx context.Context, raw string) (Principal, error)

Authenticate maps raw to its sponsored principal, or ErrUnauthenticated.

type SponsoredClient

type SponsoredClient struct {
	Name     string
	ClientID func() string
	// Internal marks an internal principal's client (RunLore agent-to-agent RA2): the principal it
	// yields is a sponsored one that may also ask for internal data.
	Internal bool
}

SponsoredClient is one sponsored principal's ZITADEL client, its id read at use (Ruling AS-a).

type Systems

type Systems struct {
	// contains filtered or unexported fields
}

Systems authenticates system:* callers of the :8443 API (SP3's factory). The allowlist maps a ServiceAccount subject to its canonical principal.

func NewSystems

func NewSystems(v RunVerifier, allow map[string]string) *Systems

NewSystems allowlists subjects: allow maps a token's sub to a system:<component> id. A nil v is the intentional never-authenticating path, so a broker without a system issuer still answers 401 on the system routes rather than 404.

func (*Systems) Authenticate

func (s *Systems) Authenticate(req *http.Request) (Principal, error)

Authenticate maps a system caller's token to its principal. A valid token for an unlisted subject is ErrForbidden, not ErrUnauthenticated.

type TokenReview

type TokenReview struct {
	// contains filtered or unexported fields
}

TokenReview asks the apiserver about each token, and caches the answers it accepts.

func NewTokenReview

func NewTokenReview(c TokenReviewer, now func() time.Time) *TokenReview

NewTokenReview reviews tokens through c.

func (*TokenReview) Verify

func (t *TokenReview) Verify(ctx context.Context, raw, audience string) (*Claims, error)

Verify returns the token's subject when the apiserver authenticates it for exactly audience. An unauthenticated answer is ErrWrongIssuer, so a JWKS issuer listed after it may still try. A token whose own exp has passed is ErrTokenExpired: the unverified claim can refuse, never accept. The claims carry the token's own exp, or a zero one a stream reads as no deadline; the cache's shorter lifetime is the verifier's business alone.

type TokenReviewer

type TokenReviewer interface {
	Create(ctx context.Context, tr *authv1.TokenReview, opts metav1.CreateOptions) (*authv1.TokenReview, error)
}

TokenReviewer is client-go's TokenReviewInterface, narrowed for tests.

type Verifier

type Verifier struct {
	// contains filtered or unexported fields
}

Verifier checks tokens from one issuer: signature, algorithm, iss, aud, exp, nbf and iat, with a bounded skew. It is safe for concurrent use.

func NewDiscoveringVerifier added in v0.47.0

func NewDiscoveringVerifier(issuer string, opts ...Option) (*Verifier, error)

NewDiscoveringVerifier is NewLazyVerifier with the JWKS URL read from the issuer's discovery document, at each fetch: nothing is fetched at construction, so an IdP that is down does not stop the process, and until it answers every token is refused.

func NewLazyVerifier

func NewLazyVerifier(issuer, jwksURL string, opts ...Option) (*Verifier, error)

NewLazyVerifier is NewVerifier without the fetch at construction: the first token or Refresh fetches the keys, and until then every token is refused. It suits an issuer the process must start without, such as the humans' IdP.

func NewVerifier

func NewVerifier(ctx context.Context, issuer, jwksURL string, opts ...Option) (*Verifier, error)

NewVerifier fetches the issuer's JWKS now, through the audited egress client, and refetches it on use once it is older than the cache TTL or when a token names an unknown kid, never more often than the minimum refresh interval. Held keys stop verifying once the last successful fetch is older than the stale cap. A JWKS that cannot be fetched or holds no usable key fails construction.

func NewVerifierWithKeyfunc

func NewVerifierWithKeyfunc(issuer string, kf jwt.Keyfunc, opts ...Option) *Verifier

NewVerifierWithKeyfunc builds a Verifier on a caller's key function, for tests and for issuers whose keys are not a JWKS. Only WithClock applies.

func (*Verifier) LastRefresh

func (v *Verifier) LastRefresh() time.Time

LastRefresh is when the issuer's keys were last fetched successfully; zero for a Verifier built on a key function. The metrics set gauges its age.

func (*Verifier) Refresh

func (v *Verifier) Refresh(ctx context.Context) error

Refresh fetches the issuer's JWKS now, unless a fetch started within the minimum refresh interval, which is no error (Ruling AQ: the broker calls it on a timer, so an idle broker's keys and LastRefresh stay fresh). It waits for a fetch already in flight. A failed fetch keeps the held keys, up to the stale cap, and leaves LastRefresh where it was. A Verifier on a key function has nothing to refresh.

func (*Verifier) Verify

func (v *Verifier) Verify(ctx context.Context, raw, audience string) (*Claims, error)

Verify checks raw for audience and returns its claims. A refusal wraps ErrUnauthenticated and, where one applies, a finer sentinel.

func (*Verifier) VerifyAuthorizedParty

func (v *Verifier) VerifyAuthorizedParty(ctx context.Context, raw, clientID string) (*Claims, error)

VerifyAuthorizedParty checks raw, a token issued to the named client: its azp, or its client_id when it has no azp. aud lists every app of the project, so only those claims say which app a ZITADEL token was issued to, and aud goes unchecked here (the rule Humans.verify states, applied to one client). A refusal wraps ErrUnauthenticated.

func (*Verifier) VerifyClient added in v0.47.0

func (v *Verifier) VerifyClient(ctx context.Context, raw, clientID string) (*Claims, error)

VerifyClient is VerifyAuthorizedParty under the generic preset: the client is azp, else client_id, else a one-element aud, and the roles claim is judged by RoleNames rather than by the decoder.

func (*Verifier) VerifyIDToken added in v0.47.0

func (v *Verifier) VerifyIDToken(ctx context.Context, raw, clientID string) (*Claims, error)

VerifyIDToken checks raw, an ID token issued to clientID (token use id): its aud holds the client (OIDC Core), and it is not an RFC 9068 access token, whose aud may also be the client (Dex's is).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL