authn

package
v0.30.2 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: Apache-2.0 Imports: 26 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 (
	AudienceRun    = "room-broker"  // fixed by SP1 (C2); Kyverno reserves it to namespace agents
	AudienceSystem = "rooms-system" // ruling P3
)

The audiences this broker accepts.

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

ForwardedAccessHeader carries the JWT 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 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.

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

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"`
}

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.

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 the JWT access token in X-Forwarded-Access-Token, same sub. The broker never trusts a header oauth2-proxy merely asserts. maku sends its own access token as a bearer, which oauth2-proxy passes through (phase 6).

func NewHumans

func NewHumans(v *Verifier, projectID, webClientID, roomctlClientID func() string, origin string) *Humans

NewHumans authenticates the humans of one ZITADEL project. The id functions are called on every request; an unreadable id returns "", which refuses.

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 a ZITADEL ID token (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. Machine tokens stay on Verify's one-audience rule (AF). The accepted client is the returned claims' AuthorizedParty.

func (*Humans) VerifyHumanAccess

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

VerifyHumanAccess checks a ZITADEL JWT access token by the same rule, with the client read from client_id: ZITADEL mints access tokens without azp (review C1). The accepted client is the returned claims' ClientID.

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 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 project id a token's aud must hold, as the human path pins it; unset or
	// unreadable, nobody is admitted.
	Audience func() string
}

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

Jump to

Keyboard shortcuts

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