nexusauth

package
v0.31.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Overview

Package nexusauth verifies a credential minted elsewhere and turns an inbound HTTP request into a Principal.

It deliberately knows nothing about the session broker or about any plugin. cmd/nexus-broker is package main and therefore importable by nothing, while nexus.io.agui is a plugin — the only place code both can share is a neutral pkg/ package, which is why this one exists.

The moving parts:

  • Principal — the verified identity. ID is the only field authorization compares; Tenant, Scopes and Claims are carried for policy and audit.
  • Validator — the single extension point. Four implementations ship here: static (a token → Principal table), jwks (an OIDC JWS verified against the issuer's published key set), introspect (an opaque token verified by asking the issuer, per RFC 7662) and proxy_headers (an identity a fronting reverse proxy already established, honoured only for peers inside a configured CIDR allowlist).
  • Chain — an ordered set of named validators. The first success wins. When every validator denies, the aggregate *DeniedError names each validator and its reason so an operator can diagnose the rejection from a single slog record.
  • Kind and Error — four denial kinds a caller maps onto transport status codes: KindNoCredential and KindInvalidCredential are 401, KindInsufficientScope is 403, and KindUnavailable is 503 (we could not find out — retry, do not re-authenticate). Use KindOf, or errors.Is against the package sentinels; never match on error strings.

A chain built from an empty validator list is *disabled*, not permissive: Validate always returns ErrAuthDisabled and never a Principal. Callers decide what an unconfigured chain means — the broker treats it as auth-off plus a loud warning — but the package itself will never silently allow a request.

Config arrives as a map[string]any so the same code path serves broker.yaml (decoded by gopkg.in/yaml.v3) and a plugin's ctx.Config block. See ParseConfig and BuildChain.

The package is stdlib-only apart from github.com/golang-jwt/jwt/v5, which the jwks validator uses for signature and standard-claim verification (the introspect validator is plain net/http and encoding/json). That is a deliberate, single exception: hand-rolling JWS verification is exactly the kind of code that fails silently and open. Everything around it — the JWKS fetch, the JWK-to-public-key reconstruction, the key cache and its rotation behaviour — is written here against stdlib crypto rather than pulling in a JOSE library. This is the shared trust boundary for two very different hosts and must not drag dependencies into either.

Index

Constants

View Source
const (
	// ClientAuthBasic sends the client credentials in an HTTP Basic header. It
	// is the default because RFC 6749 §2.3.1 requires every authorization
	// server to support it, and because it keeps the secret out of the request
	// body (and therefore out of anything that logs bodies).
	ClientAuthBasic = "basic"

	// ClientAuthPost sends client_id/client_secret as form parameters, for the
	// providers that only accept `client_secret_post`.
	ClientAuthPost = "post"
)

Client authentication methods an `introspect` entry may use when it calls the introspection endpoint. RFC 7662 §2.1 requires the endpoint to authorize its callers but does not fix how; these are the two ways OAuth 2.0 clients actually do it (RFC 6749 §2.3.1).

View Source
const ValidatorTypeIntrospect = "introspect"

ValidatorTypeIntrospect is the config `type:` that selects IntrospectValidator.

View Source
const ValidatorTypeJWKS = "jwks"

ValidatorTypeJWKS is the config `type:` that selects JWKSValidator.

View Source
const ValidatorTypeProxyHeaders = "proxy_headers"

ValidatorTypeProxyHeaders is the config `type:` that selects ProxyHeadersValidator.

View Source
const ValidatorTypeStatic = "static"

ValidatorTypeStatic is the config `type:` that selects StaticValidator.

Variables

View Source
var (
	// ErrNoCredential matches any denial of kind KindNoCredential.
	ErrNoCredential = errors.New("nexusauth: no credential presented")

	// ErrInvalidCredential matches any denial of kind KindInvalidCredential.
	ErrInvalidCredential = errors.New("nexusauth: credential rejected")

	// ErrInsufficientScope matches any denial of kind KindInsufficientScope.
	ErrInsufficientScope = errors.New("nexusauth: insufficient scope")

	// ErrUnavailable matches any denial of kind KindUnavailable.
	ErrUnavailable = errors.New("nexusauth: authentication authority unavailable")

	// ErrAuthDisabled is returned by a Chain with no validators. It is
	// deliberately not one of the three kinds: an unconfigured chain is a
	// deployment state, not a verdict on the request. The caller decides what
	// it means — refuse to start, warn and allow, or fail closed — but Validate
	// never returns a Principal for it.
	ErrAuthDisabled = errors.New("nexusauth: authentication is not configured")
)

Sentinel errors for errors.Is. Both *Error and *DeniedError report themselves as matching the sentinel for their kind, so a caller can branch on errors.Is(err, ErrNoCredential) without knowing which concrete type it holds.

Functions

func BearerToken

func BearerToken(r *http.Request) string

BearerToken extracts the token from an RFC 6750 "Authorization: Bearer <token>" header. It returns "" when the header is absent, uses a different scheme, or carries an empty token. The scheme is matched case-insensitively because RFC 7235 defines auth schemes as case-insensitive, and real clients send "bearer".

It lives here rather than inside the static validator because every token-bearing validator needs exactly this extraction.

func ParseScopes

func ParseScopes(v any) ([]string, error)

ParseScopes normalizes a scope set into individual scopes. It accepts the two shapes real credentials and configs use:

  • a space-delimited string, per OAuth 2.0's "scope" parameter ("leases.read leases.write")
  • an array of strings, as JSON- or YAML-decoded ([]any of string)

nil yields nil. Blank entries are dropped so trailing separators and empty YAML list items do not produce phantom scopes.

Types

type Attempt

type Attempt struct {
	// Validator is the chain-assigned name of the validator that denied.
	Validator string

	// Kind is the denial classification that validator reported.
	Kind Kind

	// Reason is that validator's operator-facing explanation.
	Reason string

	// Err is the error the validator returned, verbatim.
	Err error
}

Attempt records one validator's verdict inside a DeniedError.

func (Attempt) String

func (a Attempt) String() string

String renders one attempt as "<validator>: <kind>: <reason>".

type Chain

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

Chain tries validators in configured order and returns the first success. It is immutable after construction and therefore safe for concurrent use.

Chain itself satisfies Validator, so a chain can nest inside another chain.

func BuildChain

func BuildChain(cfg Config) (*Chain, error)

BuildChain instantiates every configured validator and assembles them into a Chain, preserving config order. A Config with no validators yields a disabled Chain and no error: refusing to boot is the caller's call to make, not this package's.

func ChainFromMap

func ChainFromMap(raw map[string]any) (*Chain, error)

ChainFromMap is the one call a host needs: parse an `auth:` block and build the chain from it.

func NewChain

func NewChain(validators ...NamedValidator) *Chain

NewChain builds a Chain over validators, in the order given. Order is significant: it is the operator's cheap-to-expensive ordering (a static token table before a network round-trip), and the first success short-circuits the rest.

A Chain over zero validators is disabled — see Enabled and ErrAuthDisabled.

func (*Chain) Enabled

func (c *Chain) Enabled() bool

Enabled reports whether the chain has any validators. A caller checks this once at startup to decide what an unconfigured chain means for it; the package takes no position beyond refusing to authenticate.

func (*Chain) Names

func (c *Chain) Names() []string

Names returns the validator names in chain order, for a startup log line that tells an operator exactly which validators are live and in what order.

func (*Chain) Validate

func (c *Chain) Validate(ctx context.Context, r *http.Request) (Principal, error)

Validate tries each validator in order and returns the first Principal that verifies. If every validator denies, it returns a *DeniedError carrying one Attempt per validator so a single log record explains the whole refusal.

A disabled chain (no validators, including a nil *Chain) returns ErrAuthDisabled and never a Principal: "not configured" must be distinguishable from both "allowed" and "denied", and it is the caller's job to decide the policy.

type ClaimMapping

type ClaimMapping struct {
	// PrincipalClaim is the claim whose value becomes Principal.ID.
	PrincipalClaim string

	// TenantClaim is the claim whose value becomes Principal.Tenant. Optional.
	TenantClaim string

	// ScopesClaim is the claim whose value becomes Principal.Scopes. Its value
	// may be either a space-delimited string (the OAuth 2.0 "scope" convention)
	// or an array of strings — see ParseScopes.
	ScopesClaim string
}

ClaimMapping names the claims a token-based validator reads to build a Principal. Nexus targets generic OIDC and ships no provider-specific defaults: an operator states which claim carries the principal id, which carries the tenant, and which carries the scopes. An empty field means "not configured", and the consuming validator decides whether that is fatal or simply means the resulting Principal field stays empty.

The mapping is parsed and carried for every validator entry even though only the claim-bearing validators consume it, so the config surface is uniform.

func (ClaimMapping) IsZero

func (m ClaimMapping) IsZero() bool

IsZero reports whether no claim names are configured at all.

func (ClaimMapping) Principal

func (m ClaimMapping) Principal(claims map[string]any) (Principal, error)

Principal projects a verified claim set onto a Principal using the mapping. The full claim set is carried on Principal.Claims for audit regardless of which claims the mapping names.

It returns an *Error of kind KindInvalidCredential when the credential itself is at fault (the principal claim is missing, empty, or not a scalar), and a plain error when the mapping is unusable (no principal claim configured) — those are an operator's bug, not a caller's.

type Config

type Config struct {
	// Validators are the configured validators, in the order the operator listed
	// them. Empty means auth is not configured — BuildChain returns a disabled
	// Chain, not a permissive one.
	Validators []ValidatorConfig
}

Config is the parsed form of an `auth:` block. It is decoder-agnostic on purpose: ParseConfig takes a map[string]any, which is what both gopkg.in/yaml.v3 (broker.yaml) and a plugin's ctx.Config hand over, so the two hosts share one code path and one set of error messages.

func ParseConfig

func ParseConfig(raw map[string]any) (Config, error)

ParseConfig parses an `auth:` block. A nil or empty map is valid and yields a Config with no validators — "absent" is a legitimate deployment state that BuildChain turns into a disabled Chain.

Unknown keys are rejected at every level, matching the repo's additionalProperties:false convention for config schemas: a misspelled auth key that is silently ignored is a security bug, not a cosmetic one.

type DeniedError

type DeniedError struct {
	// Attempts holds one entry per validator the chain tried, in chain order.
	Attempts []Attempt
}

DeniedError aggregates every validator's refusal for one request. Aggregation is an operability requirement, not a nicety: when a caller is denied by a multi-validator chain the operator has to learn from a single log record which validator rejected the request and why. Both Error and LogValue therefore render every attempt.

func (*DeniedError) Error

func (d *DeniedError) Error() string

Error implements error, rendering every attempt on one line.

func (*DeniedError) Is

func (d *DeniedError) Is(target error) bool

Is reports a match against the sentinel for the aggregate kind.

func (*DeniedError) Kind

func (d *DeniedError) Kind() Kind

Kind collapses the attempts into the kind the caller should act on, in severity order.

The order encodes how much each verdict actually knows. An insufficient-scope refusal is highest because some validator *did* verify the credential, so 403 is the honest answer. KindUnavailable comes next, above a flat rejection: consider a chain of [static, introspect] presented with a real identity-provider token — the static table rejects it (it is not in the table) while introspect could not reach its endpoint. Collapsing that to "credential rejected" would tell the client to re-authenticate against the provider that is already down, which is exactly the re-auth storm KindUnavailable exists to prevent. A rejection in turn outranks a missing credential.

An empty DeniedError fails closed as KindInvalidCredential rather than reporting no kind at all.

func (*DeniedError) LogValue

func (d *DeniedError) LogValue() slog.Value

LogValue renders the aggregate as a group carrying the effective kind plus one string per attempt, which keeps a full denial diagnosis inside one slog record.

type Error

type Error struct {
	// Kind is the denial classification. See Kind for the status mapping.
	Kind Kind

	// Reason explains the denial in one short clause, e.g. "token expired".
	Reason string

	// Err is an optional underlying cause, exposed through Unwrap.
	Err error
}

Error is a single classified denial, returned by a Validator. Reason is operator-facing prose: it is logged and may be echoed to the caller, so it must never contain the credential itself.

func NewError

func NewError(kind Kind, reason string, cause error) *Error

NewError builds a denial. cause may be nil.

func (*Error) Error

func (e *Error) Error() string

Error implements error.

func (*Error) Is

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

Is reports a match against the sentinel for this error's kind, so callers can use errors.Is instead of a type assertion.

func (*Error) LogValue

func (e *Error) LogValue() slog.Value

LogValue renders the denial as a structured slog group rather than a flat string, so a caller can log it with slog.Any and still filter on kind.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap exposes the underlying cause, if any.

type IntrospectValidator

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

IntrospectValidator authenticates a bearer token by asking the issuer about it, per RFC 7662 (OAuth 2.0 Token Introspection).

It exists because not every identity provider issues JWTs. An opaque token carries no claims and no signature to check, so the only thing that can say whether it is live is the authority that minted it. The validator POSTs the token to the configured introspection endpoint using its own client credentials, reads the `active` verdict and the returned claims, and maps those claims onto a Principal with the same ClaimMapping the `jwks` validator uses.

The response cache is not an optimization. This sits on POST /claim and on the WebSocket connect path, so an uncached implementation would put the identity provider's latency in front of every session and its request rate in proportion to Nexus traffic.

It is immutable after construction apart from the cache, which is internally synchronized, so one instance serves every request.

func (*IntrospectValidator) Validate

func (v *IntrospectValidator) Validate(ctx context.Context, r *http.Request) (Principal, error)

Validate implements Validator.

type JWKSValidator

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

JWKSValidator verifies a JWS bearer token against the signature keys an OIDC issuer publishes at its JWKS endpoint, then maps the verified claims onto a Principal.

It is generic OIDC: there are no provider-specific claim defaults, and the operator states the issuer, the audience, the allowed algorithms and which claim becomes the principal id.

It is immutable after construction apart from the key cache, which is internally synchronized, so one instance serves every request.

func (*JWKSValidator) Validate

func (v *JWKSValidator) Validate(ctx context.Context, r *http.Request) (Principal, error)

Validate implements Validator.

type Kind

type Kind string

Kind classifies a denial. It exists so a caller can map a denial onto a transport status code without matching on error strings:

KindNoCredential      → 401 (nothing presented; challenge the caller)
KindInvalidCredential → 401 (presented and rejected; include the reason)
KindInsufficientScope → 403 (identity is good, authority is not)
KindUnavailable       → 503 (we could not find out; retry, do not re-auth)
const (
	// KindNoCredential means the request carried no credential at all.
	KindNoCredential Kind = "no_credential"

	// KindInvalidCredential means a credential was presented but did not
	// verify — wrong token, bad signature, expired, wrong audience.
	KindInvalidCredential Kind = "invalid_credential"

	// KindInsufficientScope means the credential verified but does not grant
	// the authority the operation requires.
	KindInsufficientScope Kind = "insufficient_scope"

	// KindUnavailable means the validator could not reach a verdict because the
	// authority it depends on did not answer — an introspection endpoint that
	// timed out, refused the broker's own client credentials, or returned a
	// server error.
	//
	// It is still a denial: no Principal is produced and the request is refused.
	// What it changes is the *story told to the client*. A validator that must
	// ask a remote authority on every cold credential (see IntrospectValidator)
	// has no cache to fall back on, so an identity-provider outage would
	// otherwise become a wall of 401s. A 401 reads to a client as "your token is
	// bad, go re-authenticate", and every client doing that at once aims a
	// re-auth storm at the identity provider that is already struggling. A 503
	// with a Retry-After says the honest thing — "ask again shortly" — and lets
	// the outage recover.
	//
	// It is deliberately NOT used for a verdict the authority actually gave. An
	// RFC 7662 endpoint reports "this token is no good" as 200 with
	// active:false, never as an error status, so a non-2xx from it is never a
	// statement about the caller's credential.
	KindUnavailable Kind = "unavailable"
)

func KindOf

func KindOf(err error) Kind

KindOf extracts the denial kind from err, handling a single *Error, an aggregate *DeniedError, and a bare sentinel alike. It returns the empty Kind when err is nil or is not an authentication denial (ErrAuthDisabled included — that is a deployment state, not a verdict).

type NamedValidator

type NamedValidator struct {
	// Name identifies the validator in logs and DeniedError attempts, e.g.
	// "static" or "jwks#2".
	Name string

	// Validator is the implementation.
	Validator Validator
}

NamedValidator pairs a Validator with the operator-facing name a Chain uses in its denial records. The name is not part of the Validator interface on purpose: a validator does not know what an operator called it, and keeping the interface to one method keeps implementations trivial.

type Principal

type Principal struct {
	// ID is the stable identifier of the caller. It must be non-empty for a
	// validation to count as a success; the Chain rejects an empty ID rather
	// than pass an anonymous principal upstream.
	ID string

	// Tenant is an optional organization/workspace identifier. Empty when the
	// credential carries no tenant notion.
	Tenant string

	// Scopes are the granted scopes, already split into individual tokens. Nil
	// when the credential carries none.
	Scopes []string

	// Claims is the raw claim set the identity was derived from, kept for audit
	// and for policy that needs a claim the Principal does not model. Nil for
	// credentials with no claim structure (e.g. a static token).
	Claims map[string]any
}

Principal is a verified caller identity. It is a value type: validators hand back a fully populated copy, so a caller can stash or mutate it without touching the validator's own configuration.

ID is the only field authorization ever compares — lease ownership is principal-id equality and nothing else. Tenant, Scopes and Claims exist for policy decisions layered on top (a scope check, a tenant-scoped listing) and for audit records; nothing in the package keys on them.

func (Principal) Clone

func (p Principal) Clone() Principal

Clone deep-copies the reference-typed fields so a validator can return a Principal derived from its own long-lived configuration without handing the caller a slice or map it could mutate under a concurrent request.

It is EXPORTED because the same discipline is needed outside this package: cmd/nexus-broker stamps a Principal onto a lease and hands copies back out of its registry, and being `package main` it cannot reach an unexported method. It previously carried a hand-maintained duplicate with a "keep in sync" comment — one deep-copy definition per type is the only version of that which cannot drift.

func (Principal) HasScope

func (p Principal) HasScope(s string) bool

HasScope reports whether the principal was granted the exact scope s. The comparison is case-sensitive: scopes are opaque identifiers, and folding case would make "Admin" silently equivalent to "admin".

type ProxyHeadersValidator

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

ProxyHeadersValidator trusts an identity a fronting reverse proxy has already established and passed down in request headers — oauth2-proxy, an OIDC-aware ingress, a service-mesh sidecar.

It is the most dangerous validator in this package, because a header is not a credential: anyone who can open a socket to the broker can send any header they like. The single thing that makes it safe is the network check. Headers are read ONLY when the request's own peer address falls inside a configured CIDR allowlist, i.e. only when the connection demonstrably came from the proxy. Every other request is denied without the headers being consulted at all.

Three deliberate non-negotiables follow from that:

  • The allowlist may not be empty. An absent allowlist is a boot error, never an implicit allow-everything — failing open here converts the broker into an open door with no signal that anything is wrong.
  • X-Forwarded-For is never consulted. It is written by whoever is talking to us and can name any address; using it for the trust decision would hand the allowlist to the attacker. Only r.RemoteAddr, which is the kernel's view of the peer, is used.
  • A peer address that cannot be parsed (unset, malformed, or a Unix socket, which has no IP at all) is denied. There is no "probably local" fallback.

It composes with the other validators through a Chain: a deployment can accept proxy headers from its ingress network and JWTs from anywhere, in the order the operator listed them.

It is immutable after construction and safe for concurrent use.

func (*ProxyHeadersValidator) TrustedCIDRs

func (v *ProxyHeadersValidator) TrustedCIDRs() []string

TrustedCIDRs returns the allowlist in configured order, for a startup log line that lets an operator confirm what the broker will actually trust.

func (*ProxyHeadersValidator) Validate

Validate implements Validator.

The order of the checks is load-bearing: the peer address is settled before a single header is read, so there is no code path on which a header from an untrusted peer can influence anything.

type StaticToken

type StaticToken struct {
	// Token is the bearer token value, compared in constant time.
	Token string

	// Principal is the identity a request presenting Token acts as.
	Principal Principal
}

StaticToken binds one shared secret to the identity it stands for.

type StaticValidator

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

StaticValidator authenticates a bearer token against a fixed table of operator-configured tokens. It is the escape hatch that keeps the broker usable without an identity provider — service accounts, CI, a local operator CLI — and it makes the whole package testable with no network.

It is immutable after construction and safe for concurrent use.

func NewStaticValidator

func NewStaticValidator(tokens []StaticToken) (*StaticValidator, error)

NewStaticValidator builds a validator over tokens. It rejects a table that could never authenticate anything (no tokens), entries missing a token or a principal id, and duplicate token values — a duplicate is always an operator mistake, and resolving it silently would pin the identity to whichever entry happened to be listed last.

func (*StaticValidator) Validate

func (v *StaticValidator) Validate(_ context.Context, r *http.Request) (Principal, error)

Validate implements Validator.

type Validator

type Validator interface {
	Validate(ctx context.Context, r *http.Request) (Principal, error)
}

Validator verifies the credential on an inbound request. It is the single extension point of this package: everything else — the chain, the errors, the config parser — is shared plumbing around implementations of this one method.

A Validator returns a Principal with a non-empty ID on success. On failure it returns a classified *Error (see NewError) so the chain can aggregate the reason and the caller can map it to a status code. Implementations must be safe for concurrent use: one instance serves every request.

type ValidatorConfig

type ValidatorConfig struct {
	// Type selects the implementation, e.g. ValidatorTypeStatic.
	Type string

	// Name is the label the Chain reports in denial records. ParseConfig derives
	// it from Type, disambiguating repeats as "type#2", "type#3", …, so an
	// operator with two issuers can tell the two apart in one log line without
	// having to name them.
	Name string

	// ClaimMapping is the shared claim-name mapping. It is parsed for every
	// entry even though only claim-bearing validators consume it.
	ClaimMapping ClaimMapping

	// Options holds the remaining, type-specific keys verbatim. The per-type
	// builder consumes them and rejects anything it does not recognize, so a
	// typo fails loudly instead of being silently ignored.
	Options map[string]any
}

ValidatorConfig is one entry of the `validators:` list.

Jump to

Keyboard shortcuts

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