auth

package
v0.21.1 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: Apache-2.0 Imports: 51 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

Index

Constants

View Source
const (
	COOKIE                        = "cookie"
	GRANT_TYPE_AUTHORIZATION_CODE = "authorization_code"
	GRANT_TYPE_REFRESH_TOKEN      = "refresh_token"
	GRANT_TYPE_TOKEN_EXCHANGE     = "urn:ietf:params:oauth:grant-type:token-exchange"
	HTTP                          = "http"
	HTTPS                         = "https"
	LookupTypeSecret              = "secret"
	PKCE_METHOD_S256              = "S256"
	TRUE                          = "true"
)
View Source
const CapUsesClaim = "kdx_cap"

CapUsesClaim marks a JWT as a bounded-use capability minted by mint_token (internal/host/mint_token.go). The inbound middleware decrements the jti-keyed use counter only for tokens carrying this claim; ordinary session/FAT tokens never carry it. Exported so both the minting side (internal/host) and the enforcing side (this package) share one source of truth for the marker's name.

View Source
const (
	HTTPEventHookSecretType = "http-event-hook"
)
View Source
const (
	HTTPLookupSecretType = "http-lookup-auth"
)
View Source
const MaxRefreshGraceWindow = 60 * time.Second

MaxRefreshGraceWindow is the hard ceiling on Config.RefreshGraceWindow. The window exists to absorb the few hundred milliseconds a real client's parallel refreshes span (RFC 9700 4.14); anything on that order is covered well inside a minute. Past it the knob stops being a race absorber and becomes a replay window: a consumed refresh token keeps returning a live access/ID/refresh set for its whole duration, and the minted set sits at rest in the cache for just as long. A misconfigured `--refresh-grace-window=24h` would silently convert single-use rotation into 24h replay, so NewExchanger clamps to this and says so.

View Source
const OAuthCallbackPath = "/-/oauth/callback"

OAuthCallbackPath is the path this host serves the OIDC authorization-code callback on, and the path component of the redirect_uri sent to the provider.

It is one constant rather than two literals deliberately: the value is registered by hand with the identity provider, which compares it exactly, so a drift between the path we advertise and the path we serve would present as an authorization failure with no local symptom to trace it by. The handler registration in internal/host reads this same constant.

View Source
const (

	// PATBridgeClaim is the auth-context claim set ONLY by the proxy PAT
	// bridge (internal/host/proxy.go) when it authenticates an
	// audience-bound PASETO PAT and resolves the subject's role-derived
	// entitlements. A PAT minted through the authorization-code (oauth2)
	// flow is semantically an oauth2 authentication, so callers carrying
	// this marker have their role-resolved entitlements mirrored into the
	// "oauth2" scheme bucket (in addition to "bearer") by
	// GetParsedEntitlements — letting them satisfy oauth2-only operation
	// requirements. This marker is intentionally distinct from
	// auth_method=="oauth2": an ordinary JWT-cookie user who logged in via
	// the oauth2 flow also carries auth_method=="oauth2" but must NOT have
	// their bearer entitlements satisfy oauth2 requirements. Only the PAT
	// bridge sets this claim. See kdex-tech/host-manager §4.
	PATBridgeClaim = "pat_bridge"
)

Variables

View Source
var ErrGrantFailure = errors.New("grant failure")

ErrGrantFailure marks a rejection that is genuinely ABOUT the grant the caller presented — not found, expired, mismatched, already consumed — and is therefore safe to describe back to an unauthenticated caller. Marking is an opt-in allowlist: an unmarked error is still treated as a grant failure but gets a fixed generic description instead of its own message. Why that default points the way it does is documented once, on oauthErrorForRedemption.

Errors are classified against this sentinel via errors.Is, but are never built by wrapping it with fmt.Errorf("%w: ...", ErrGrantFailure) — doing so would put ErrGrantFailure's own "grant failure" text on the wire ahead of the actual message (e.g. "grant failure: refresh token not found or expired" instead of the exact string #168's reporter is matching on). Build grant-failure errors with grantFailuref instead: it classifies against this sentinel via the errors.Is opt-in Is(error) bool hook, with the message left untouched.

View Source
var ErrLoginHookDenied = errors.New("login denied by event hook")

ErrLoginHookDenied is returned by GateLogin when an enforcing login hook denies the login (ok=false, or a fail-closed transport failure).

View Source
var ErrLookupUnavailable = errors.New("lookup unavailable")

ErrLookupUnavailable marks a Lookup failure as "this backend could not give us an answer" — a dial failure, a timeout, a 5xx, an undecodable response, a broken service account — as distinct from "this backend answered, and the credential is bad".

The interface's (bool, claims, error) shape looks like it separates those already, but it does not: `ok=false` means only "this subject is not present in this lookup", and every implementation returns a wrong password as an `error`. Without this marker a credential backend outage is indistinguishable from a bad password, so the token endpoint answers 400 invalid_grant during an outage and clients discard working refresh tokens and force users to re-authenticate. See kdex-tech/host-manager#171.

View Source
var ErrServerError = errors.New("server error")

ErrServerError marks a failure of OUR infrastructure — a cache read, a signing operation, a stored-record unmarshal — as distinct from a failure of the client's grant. The token endpoint maps it to RFC 6749 5.2's server_error (500) rather than invalid_grant (400), because telling a client its credential is dead during a transient outage makes it discard a working refresh token and re-authorize for no reason. See kdex-tech/host-manager#168.

View Source
var SupportedScopes = []string{"openid", "email", "profile", "entitlements", "roles"}

DiscoveryHandler creates an HTTP handler that serves the OpenID discovery document. SupportedScopes is the authorization server's scope vocabulary: the complete set of `scope` values a client may be granted.

RFC 6749 3.3 makes the vocabulary the AS's to define, and RFC 8414 2 makes scopes_supported the way it is published. This variable is therefore the single source for BOTH -- the discovery document advertises it and applyScopeFilter grants nothing outside it. They were previously two hardcoded lists that could drift, so a scope could be advertised but ungrantable, or grantable but unadvertised.

Order is the grant order applyScopeFilter emits; discovery order is not significant.

Functions

func AuthClientLoader

func AuthClientLoader(secrets kdexv1alpha1.Secrets) (map[string]AuthClient, error)

func CheckedResourceMetadata added in v0.8.0

func CheckedResourceMetadata(ctx context.Context, raw string) string

CheckedResourceMetadata returns raw when it may be emitted inside an RFC 9728 resource_metadata auth-param, and "" when it may not. It is the ONE gate every emitter of that parameter goes through: internal/auth/denial.Write (the denial contract's 401/403 challenges) and bearerChallenge (the invalid/expired-token 401 raised by WithAuthentication).

It lives HERE, in internal/auth, rather than in internal/auth/denial, because the dependency only runs one way: internal/auth/denial imports internal/auth, so internal/auth cannot import it back. Two emitters, one implementation -- the alternative was a second copy of the rule in the more reachable of the two paths, which is how the two halves came to disagree in the first place.

Why the value needs checking at all

The value both emitters carry is <issuer> + protectedResourcePath + basePath. The issuer half is hostname-validated; basePath is NOT. Its CRD pattern is `^/\w+/\w+`, which is START-ANCHORED ONLY, so `/a/b",resource_metadata="https://attacker.example/x` is a valid spec.api.basePath. Emitting it raw would put a SECOND resource_metadata parameter in the challenge and let an RFC 9728 client be steered to an attacker-run authorization server. Go rewrites only CR/LF on write, so this cannot split a response -- but it fully controls this header's auth-params, which is enough.

Anchoring the CRD pattern with `$` and giving it a MaxLength is the upstream fix and lives in kdex-crds; this consumer-side check is the defence in depth that holds whichever CRD version happens to be installed.

Omit, never clean

A rejected value yields "", and the CALLER drops the parameter while keeping the rest of its challenge. Emitting a sanitized value would hand an RFC 9728 client a URL nobody authored; omitting the pointer costs it discovery and nothing else.

The rejection is logged at V(0): an operator has authored a basePath that cannot be expressed in this header, and the only other symptom is an OAuth2/MCP client with no discovery pointer. That is worth seeing at the default verbosity. An empty raw is the ordinary "this resource is not oauth2-protected" case and is not logged.

func DiscoveryHandler

func DiscoveryHandler(issuer string, registrationEndpoint string) http.HandlerFunc

func EnrichAuthContext added in v0.4.17

func EnrichAuthContext(ac AuthContext, mapper *dmapper.Mapper)

EnrichAuthContext applies mapper (compiled ClaimMappings) to the auth context IN PLACE, so any enrichment a mapping performs (e.g. folding a backend-supplied source claim into entitlements) is reflected BEFORE the context is used to derive `held`, the identity gate, or a downstream token. It is the single authContext-enrichment primitive; callers MUST pass the SAME mapper the token or FAT signer uses for that context — host ClaimMappings for a session token, host + fn.Spec.ClaimMappings for a function's proxy path — so the enriched context and the token it yields never disagree. Idempotent for an already-enriched context (no raw source claims remain to re-fold); attenuation-safe (only ADDS mapped output, never removes a claim, and a downscoped capability token carries no source claims to re-expand); fail-safe (a mapping error leaves the context unchanged). No claim name is special-cased — ClaimMappings are the generic enrichment mechanism.

func FormatADGUID

func FormatADGUID(b []byte) (string, error)

FormatADGUID converts the raw binary objectGUID from AD into a standard UUID string. AD uses a little-endian format for the first three components.

func JWKSHandler

func JWKSHandler(keyPairs *keys.KeyPairs) http.HandlerFunc

JWKSHandler creates an HTTP handler that serves the JWKS endpoint. This endpoint exposes the public key(s) used to verify JWT signatures.

func LooksLikePAT added in v0.3.0

func LooksLikePAT(token, tokenPrefix string) bool

LooksLikePAT is the exported wrapper around looksLikePAT so other packages (e.g. the host proxy bridge) can recognize a PASETO PAT presented on the Authorization: Bearer header.

func NewHTTPEventHook added in v0.14.0

func NewHTTPEventHook(secret corev1.Secret) (*httpEventHook, error)

func NewHTTPLookup added in v0.2.52

func NewHTTPLookup(secret corev1.Secret) (*httpLookup, error)

NewHTTPLookup constructs a Lookup that POSTs credentials to an external HTTP endpoint identified by the Secret's data.url field, signing requests with HMAC-SHA256 using data.shared-secret as the key.

func NewLDAPLookup

func NewLDAPLookup(secret corev1.Secret) *ldapLookup

func NewRoleProvider

func NewRoleProvider(
	ctx context.Context,
	c client.Client,
	focalHost string,
	controllerNamespace string,
	lookups []Lookup,
) (*scopeProvider, error)

func NewSecretLookup

func NewSecretLookup(secrets kdexv1alpha1.Secrets) *secretLookup

func PreserveHeader added in v0.8.0

func PreserveHeader(w http.ResponseWriter, name, value string)

PreserveHeader sets a response header AND, when w can record provenance, marks it as authored by this process so it survives a header wipe.

Use it for any header that describes the REJECTION rather than the body -- a WWW-Authenticate challenge above all. Never for a header copied from an upstream response: a backend's challenge reaching a browser on the host's origin is a phishing primitive, not a contract.

func SetAuthContext

func SetAuthContext(ctx context.Context, ac AuthContext) context.Context

SetAuthContext sets the auth context in the context.

Types

type AuthClient

type AuthClient struct {
	AllowedGrantTypes []string
	AllowedScopes     []string
	AllowedResources  []string
	ClientID          string
	ClientSecret      string
	Description       string
	Name              string
	Public            bool
	RedirectURIs      []string
	RequirePKCE       bool
}

type AuthContext

type AuthContext jwt.MapClaims

func GetAuthContext

func GetAuthContext(ctx context.Context) (AuthContext, bool)

GetAuthContext retrieves the claims from the context.

func (AuthContext) GetAudience

func (ac AuthContext) GetAudience() (jwt.ClaimStrings, error)

GetAudience implements the Claims interface.

func (AuthContext) GetAuthMethod

func (ac AuthContext) GetAuthMethod() (AuthMethod, error)

func (AuthContext) GetEntitlements

func (ac AuthContext) GetEntitlements() ([]string, error)

func (AuthContext) GetExpirationTime

func (ac AuthContext) GetExpirationTime() (*jwt.NumericDate, error)

GetExpirationTime implements the Claims interface.

func (AuthContext) GetIssuedAt

func (ac AuthContext) GetIssuedAt() (*jwt.NumericDate, error)

GetIssuedAt implements the Claims interface.

func (AuthContext) GetIssuer

func (ac AuthContext) GetIssuer() (string, error)

GetIssuer implements the Claims interface.

func (AuthContext) GetNotBefore

func (ac AuthContext) GetNotBefore() (*jwt.NumericDate, error)

GetNotBefore implements the Claims interface.

func (AuthContext) GetRoles

func (ac AuthContext) GetRoles() ([]string, error)

func (AuthContext) GetScopes

func (ac AuthContext) GetScopes() ([]string, error)

func (AuthContext) GetSubject

func (ac AuthContext) GetSubject() (string, error)

GetSubject implements the Claims interface.

func (AuthContext) IsPATBridge added in v0.3.0

func (ac AuthContext) IsPATBridge() bool

IsPATBridge reports whether this auth context was produced by the proxy PAT bridge. See PATBridgeClaim.

type AuthMethod

type AuthMethod string
const (
	AuthMethodLocal  AuthMethod = "local"
	AuthMethodOIDC   AuthMethod = "oidc"
	AuthMethodOAuth2 AuthMethod = "oauth2"
)

type AuthorizationChecker

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

AuthorizationChecker validates whether a user has the required permissions.

func NewAuthorizationChecker

func NewAuthorizationChecker(anonymousEntitlements []string, log logr.Logger) *AuthorizationChecker

NewAuthorizationChecker creates a new authorization checker.

func (*AuthorizationChecker) BindRequirements added in v0.4.18

BindRequirements substitutes each {placeholder} resourceName in reqs with its bound value. Delegates to the entitlements checker; see its doc comment for the error contract (ErrUnboundPlaceholder / ErrInvalidBoundValue / ErrWildcardRequirement).

func (*AuthorizationChecker) CalculateRequirements

func (ac *AuthorizationChecker) CalculateRequirements(
	resource string,
	resourceName string,
	kdexreqs []kdexv1alpha1.SecurityRequirement,
	verbs ...string,
) ([]kdexv1alpha1.SecurityRequirement, error)

func (*AuthorizationChecker) CheckAccess

func (ac *AuthorizationChecker) CheckAccess(
	ctx context.Context,
	resource string,
	resourceName string,
	kdexreqs []kdexv1alpha1.SecurityRequirement,
	verbs ...string,
) (bool, error)

func (*AuthorizationChecker) GetParsedEntitlements added in v0.2.9

func (ac *AuthorizationChecker) GetParsedEntitlements(ctx context.Context) entitlements.ParsedEntitlements

func (*AuthorizationChecker) ParseEntitlements added in v0.2.9

func (*AuthorizationChecker) ParseRequirements added in v0.2.9

func (ac *AuthorizationChecker) ParseRequirements(kdexreqs []kdexv1alpha1.SecurityRequirement) (result entitlements.ParsedRequirements)

func (*AuthorizationChecker) VerifyResourceParsedEntitlements added in v0.2.9

func (ac *AuthorizationChecker) VerifyResourceParsedEntitlements(
	resource string,
	resourceName string,
	parsedEntitlements entitlements.ParsedEntitlements,
	parsedRequirements entitlements.ParsedRequirements,
	verbs ...string,
) (bool, error)

type AuthorizationCodeClaims

type AuthorizationCodeClaims struct {
	AuthMethod          AuthMethod `json:"auth_method"`
	ClientID            string     `json:"cid"`
	CodeChallenge       string     `json:"challenge,omitempty"`
	CodeChallengeMethod string     `json:"challenge_method,omitempty"`
	Exp                 int64      `json:"exp"`
	// IDPClaims is the non-reserved claim snapshot the IdP asserted at login,
	// mirroring RefreshTokenClaims.IDPClaims. It is carried so the code-redemption
	// mint can compute the role-binding key (e.g. email) the same way the login and
	// refresh paths do, without a fresh IdP round-trip. omitempty keeps codes for
	// non-OIDC grants unchanged.
	IDPClaims jwt.MapClaims `json:"idpc,omitempty"`
	// JTI is the random per-code identifier used to enforce single-use
	// semantics. Set on mint, looked up + deleted on redeem. See
	// kdex-tech/host-manager#65.
	JTI         string `json:"jti,omitempty"`
	RedirectURI string `json:"uri"`
	// Resource is the RFC 8707 resource indicator supplied by the client
	// during the authorization request. It is encrypted inside the auth
	// code JWE and can be inspected by the token endpoint if needed.
	Resource string `json:"resource,omitempty"`
	Scope    string `json:"scp"`
	Subject  string `json:"sub"`
}

type CompiledMappingRule

type CompiledMappingRule struct {
	dmapper.MappingRule
	Program cel.Program
}

type Config

type Config struct {
	ActivePair            *keys.KeyPair
	AnonymousEntitlements []string
	Audience              string
	AutoExtendSession     bool
	Clients               map[string]AuthClient
	CookieName            string
	FunctionURLs          []string
	Issuer                string
	KeyPairs              *keys.KeyPairs
	MaxSessionAge         time.Duration
	OIDC                  struct {
		BlockKey             string
		ClientID             string
		ClientSecret         string
		IDTokenStore         idtoken.IDTokenStore
		Name                 string
		ProviderURL          string
		RedirectURL          string
		Scopes               []string
		RoleBindingClaim     string
		RequireEmailVerified bool
	}
	DCR      DCRConfig
	DCRStore *dcr.Store
	// OAuth2ResourceMetadata maps an oauth2-protected resource's basePath to
	// that resource's RFC 9728 metadata URL. It exists so the 401 this
	// middleware returns for an invalid bearer can carry the same
	// resource_metadata challenge the proxy's oauth2 gate emits for an
	// anonymous caller (#180) — the middleware wraps the whole mux and has no
	// other way to know which function a path belongs to.
	//
	// A read-only snapshot of internal/host.oauth2ProtectedResources(),
	// installed by SetHost whenever the host's functions change. Nil is fine:
	// the challenge then omits resource_metadata and is still RFC 6750
	// conformant.
	OAuth2ResourceMetadata    map[string]string
	MintCapCache              cache.Cache
	MintTokenEnabled          bool
	MintTokenTTLCap           time.Duration
	MintTokenCapabilityTTLCap time.Duration
	MintTokenUsesCap          int
	MintTokenDestructiveVerbs []string
	MintTokenURLDelivery      bool
	RefreshTokenTTL           time.Duration
	// RefreshGraceWindow keeps a rotated refresh token's RESULT replayable
	// for a short period so concurrent refreshes from one client do not
	// race (RFC 9700 4.14; kdex-tech/host-manager#169). Zero disables it,
	// restoring strict single-winner rotation.
	//
	// Deliberately NOT a KDexHost.spec.auth field: a CRD change would force
	// a paired nexus-manager release. Per-host override goes through
	// KDexHost.spec.helm.hostManager.values instead.
	RefreshGraceWindow time.Duration
	Signer             sign.Signer
	// ClaimMappings are the host's spec.auth.claimMappings rules. They shape
	// EVERY token the host issues: the session Signer above bakes them in, and
	// the per-function FAT signer (proxy.go) prepends them to its own
	// fn.Spec.ClaimMappings — so a rule authored once on the host applies
	// uniformly. See #138.
	ClaimMappings []dmapper.MappingRule

	// ClaimMapper is ClaimMappings compiled once, retained so any reader of an
	// auth context can apply the SAME enrichment the session-token signer does.
	// Without it the only compiled host mapper lived inside Build's local scope
	// and was handed to the Signer alone, so a context assembled OUTSIDE the
	// mint path -- a host-audience PAT identity (#175) -- carried its
	// data-driven source claims unfolded, and every non-proxied reader
	// evaluated a smaller entitlement set than the proxy gate enforced.
	// See kdex-tech/host-manager#192.
	ClaimMapper  *dmapper.Mapper
	TokenManager *apitoken.TokenManager
	TokenTTL     time.Duration
}

func (*Config) AddAuthentication

func (c *Config) AddAuthentication(mux http.Handler, exchanger *Exchanger) http.Handler

func (*Config) IsAuthEnabled

func (c *Config) IsAuthEnabled() bool

func (*Config) IsM2MEnabled

func (c *Config) IsM2MEnabled() bool

func (*Config) IsOIDCEnabled

func (c *Config) IsOIDCEnabled() bool

func (*Config) TokenPrefix added in v0.3.0

func (c *Config) TokenPrefix() string

TokenPrefix returns this host's white-label API token prefix (empty when no TokenManager is configured or prefixing is off). Used by the Bearer auth path (both the WithAuthentication middleware and the proxy PAT bridge) to recognize a brand-prefixed PAT.

func (*Config) WithAPITokenIdentity added in v0.5.1

func (c *Config) WithAPITokenIdentity(exchanger *Exchanger) func(http.Handler) http.Handler

WithAPITokenIdentity is OPT-IN: it authenticates a host-audience PASETO PAT into an identity for the single route it wraps. Apply it only to endpoints that should treat an API key as the caller, and never to the mux as a whole — see the PAT block in WithAuthentication for what happens when a PAT identity leaks into the proxy bridge or into /-/oauth/authorize.

It composes AFTER WithAuthentication: a request already carrying an identity (JWT or cookie) is left alone, so this only ever fills the gap the PAT passthrough leaves.

func (*Config) WithAuthentication added in v0.2.9

func (c *Config) WithAuthentication(exchanger *Exchanger) func(http.Handler) http.Handler

WithAuthentication creates a middleware that validates JWT tokens from the Authorization header. It injects the claims into the request context if the token is valid. If the Header is present but invalid, it returns 401 Unauthorized. If the Header is missing, it proceeds without claims (anonymous access).

type ConfigBuilder added in v0.2.9

type ConfigBuilder struct {
	APITokenManagerLoader  func() (*apitoken.TokenManager, error)
	Audience               string
	AuthClientLoader       func() (map[string]AuthClient, error)
	CacheManager           cache.CacheManager
	DevMode                bool
	Functions              kdexv1alpha1.KDexFunctionList
	Issuer                 string
	KeyLoader              func() (*keys.KeyPairs, error)
	OIDCClientConfigLoader func() (*OIDCClientConfig, error)
	RefreshGraceWindow     time.Duration
}

func NewConfigBuilder added in v0.2.9

func NewConfigBuilder() *ConfigBuilder

func (*ConfigBuilder) Build added in v0.2.9

func (cb *ConfigBuilder) Build(auth *kdexv1alpha1.Auth) (*Config, error)

func (*ConfigBuilder) WithAPITokenManagerLoader added in v0.2.9

func (cb *ConfigBuilder) WithAPITokenManagerLoader(apiTokenManagerLoader func() (*apitoken.TokenManager, error)) *ConfigBuilder

func (*ConfigBuilder) WithAudience added in v0.2.9

func (cb *ConfigBuilder) WithAudience(audience string) *ConfigBuilder

func (*ConfigBuilder) WithAuthClientLoader added in v0.2.9

func (cb *ConfigBuilder) WithAuthClientLoader(authClientLoader func() (map[string]AuthClient, error)) *ConfigBuilder

func (*ConfigBuilder) WithCacheManager added in v0.2.9

func (cb *ConfigBuilder) WithCacheManager(cacheManager cache.CacheManager) *ConfigBuilder

func (*ConfigBuilder) WithDevMode added in v0.2.9

func (cb *ConfigBuilder) WithDevMode(devMode bool) *ConfigBuilder

func (*ConfigBuilder) WithFunctions added in v0.2.9

func (cb *ConfigBuilder) WithFunctions(functions kdexv1alpha1.KDexFunctionList) *ConfigBuilder

func (*ConfigBuilder) WithIssuer added in v0.2.9

func (cb *ConfigBuilder) WithIssuer(issuer string) *ConfigBuilder

func (*ConfigBuilder) WithKeyLoader added in v0.2.9

func (cb *ConfigBuilder) WithKeyLoader(keyLoader func() (*keys.KeyPairs, error)) *ConfigBuilder

func (*ConfigBuilder) WithOIDCClientConfigLoader added in v0.2.9

func (cb *ConfigBuilder) WithOIDCClientConfigLoader(oidcClientConfigLoader func() (*OIDCClientConfig, error)) *ConfigBuilder

func (*ConfigBuilder) WithRefreshGraceWindow added in v0.5.0

func (cb *ConfigBuilder) WithRefreshGraceWindow(d time.Duration) *ConfigBuilder

type ContextKey

type ContextKey string

ContextKey is a custom type for context keys to avoid collisions.

type DCRConfig added in v0.3.0

type DCRConfig struct {
	Enabled                bool
	ClientTTL              time.Duration
	MaxClients             int32
	AllowedRedirectSchemes []string
}

DCRConfig is the resolved per-host Dynamic Client Registration config.

type EventDispatcher added in v0.14.0

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

EventDispatcher owns the parsed hooks for one host and emits lifecycle events. A nil *EventDispatcher is valid: every method is a no-op (GateLogin allows).

func NewEventDispatcher added in v0.14.0

func NewEventDispatcher(host string, hooks []*httpEventHook, log logr.Logger) *EventDispatcher

func NewEventDispatcherFromSecrets added in v0.14.0

func NewEventDispatcherFromSecrets(host string, secrets []corev1.Secret, log logr.Logger) (*EventDispatcher, error)

NewEventDispatcherFromSecrets filters secrets down to the active http-event-hook Secrets (kdex.dev/secret-type == HTTPEventHookSecretType and kdex.dev/active-key == "true"), parses each into an httpEventHook, and wraps the result in an EventDispatcher. Returns the first parse error encountered, if any. httpEventHook is unexported, so this is the only way a caller outside the auth package can build a dispatcher from Secrets.

func (*EventDispatcher) GateLogin added in v0.14.0

func (d *EventDispatcher) GateLogin(ctx context.Context, p EventPayload) error

GateLogin runs the enforcing login hooks in name order and denies on the first ok=false (or, per failure-mode, a transport error). Nil-safe.

func (*EventDispatcher) HasEnforcingLogin added in v0.14.1

func (d *EventDispatcher) HasEnforcingLogin() bool

HasEnforcingLogin reports whether any configured hook is an enforcing gate for the login event. It is the trigger for the #206 post-gate enrichment: only a deployment that actually runs an enforcing login gate can provision a subject during login, so this keeps the enrichment (and its extra backend resolve) off the mint path for every other deployment. Nil-safe (a nil dispatcher enforces nothing).

func (*EventDispatcher) Logout added in v0.14.0

func (d *EventDispatcher) Logout(ctx context.Context, p EventPayload)

Logout runs enforcing-logout hooks as sequential barriers (blocking up to each hook's timeout) but NEVER refuses the logout, then fires advisory-logout hooks async. Nil-safe.

func (*EventDispatcher) NoteGateExempt added in v0.18.0

func (d *EventDispatcher) NoteGateExempt(p EventPayload, why string)

NoteGateExempt records a login that bypassed the enforcing login hooks (`why` names the exemption) at default verbosity: a break-glass login is an audit event. Silent when no enforcing login hook is configured, since there was no gate to bypass. Nil-safe. See kdex-tech/host-manager#226.

func (*EventDispatcher) NotifyLoginFailed added in v0.14.0

func (d *EventDispatcher) NotifyLoginFailed(ctx context.Context, p EventPayload)

func (*EventDispatcher) NotifyLoginSuccess added in v0.14.0

func (d *EventDispatcher) NotifyLoginSuccess(ctx context.Context, p EventPayload)

func (*EventDispatcher) NotifySessionRefresh added in v0.14.0

func (d *EventDispatcher) NotifySessionRefresh(ctx context.Context, p EventPayload)

type EventPayload added in v0.14.0

type EventPayload struct {
	Event        EventType      `json:"event"`
	Timestamp    int64          `json:"timestamp"`
	Host         string         `json:"host"`
	Subject      string         `json:"subject"`
	AuthMethod   string         `json:"auth_method,omitempty"`
	ClientID     string         `json:"client_id,omitempty"`
	Scope        string         `json:"scope,omitempty"`
	Claims       map[string]any `json:"claims,omitempty"`
	Roles        []string       `json:"roles,omitempty"`
	Entitlements []string       `json:"entitlements,omitempty"`
	SessionID    string         `json:"session_id,omitempty"`
	Reason       string         `json:"reason,omitempty"`
}

EventPayload is the JSON envelope POSTed to a hook. Field presence varies by event (see the design spec); omitempty keeps absent context out of the body.

type EventType added in v0.14.0

type EventType string
const (
	EventLogin          EventType = "login"
	EventLogout         EventType = "logout"
	EventLoginFailed    EventType = "login-failed"
	EventSessionRefresh EventType = "session-refresh"
)

type Exchanger

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

func NewExchanger

func NewExchanger(
	ctx context.Context,
	cfg Config,
	cacheManager cache.CacheManager,
	sp InternalIdentityProvider,
	dispatcher *EventDispatcher,
) (*Exchanger, error)

func (*Exchanger) AuthCodeURL

func (e *Exchanger) AuthCodeURL(state string) string

func (*Exchanger) BumpGrantGeneration added in v0.10.0

func (e *Exchanger) BumpGrantGeneration(ctx context.Context)

BumpGrantGeneration advances the shared grant generation so every cached browser-session grant becomes stale and is re-resolved on the next request. Called from the proxy when a membership mutation succeeds (#203).

The token is a per-process random nonce plus a monotonic counter, NOT a wall-clock stamp: the value is used as an equality/cache-key token and must be unique across the 60s TTL window regardless of clock behaviour, so a backward clock step can never reproduce a still-cached generation value (DI-F2/SEC-S4).

func (*Exchanger) CreateAuthorizationCode

func (e *Exchanger) CreateAuthorizationCode(ctx context.Context, claims AuthorizationCodeClaims) (string, error)

func (*Exchanger) EmitLogout added in v0.14.0

func (e *Exchanger) EmitLogout(ctx context.Context, refreshTokenID, _ string)

EmitLogout dispatches the logout event to any configured event hooks. When refreshTokenID names a still-cached refresh token, its RefreshTokenClaims are read (without consuming the record -- the caller typically still needs it for its own RevokeRefreshToken call) and used to populate Subject/ClientID/Scope/AuthMethod/SessionID on the payload. Logout STILL fires, with an empty Subject, when refreshTokenID is empty, unknown, or its record fails to parse -- a hook must see every logout, not only the ones with a resolvable identity.

idToken is currently unused; the parameter is reserved for future OIDC end-session correlation.

Nil-safe (both e and e.eventDispatcher). This is a barrier: it may block the caller up to the slowest enforcing-logout hook's timeout.

func (*Exchanger) EndSessionURL

func (e *Exchanger) EndSessionURL() (string, error)

func (*Exchanger) ExchangeCode

func (e *Exchanger) ExchangeCode(ctx context.Context, code string) (OIDCExchange, error)

func (*Exchanger) ExchangeSubjectToken added in v0.11.0

func (e *Exchanger) ExchangeSubjectToken(subjectToken, targetAudience string) (TokenSet, error)

ExchangeSubjectToken performs an RFC 8693 token exchange: it verifies a host-issued subject_token (a FAT), re-resolves the subject's entitlements, and mints a fresh JWT addressed to targetAudience. The subject_token's audience is intentionally NOT checked -- a FAT's aud is a function, not the host -- but its signature, issuer and expiry are. The minted token carries the subject's re-resolved entitlements (never the subject_token's), so the target function's own entitlement checks remain authoritative. An `act` claim records the calling function (the subject_token's audience) for audit.

func (*Exchanger) ExchangeToken

func (e *Exchanger) ExchangeToken(ctx context.Context, oidcTokens OIDCExchange) (TokenSet, error)

func (*Exchanger) GetClient

func (e *Exchanger) GetClient(clientID string) (AuthClient, bool)

func (*Exchanger) GetOIDCClientID

func (e *Exchanger) GetOIDCClientID() string

func (*Exchanger) GetScopesSupported

func (e *Exchanger) GetScopesSupported() ([]string, error)

func (*Exchanger) GetTokenTTL

func (e *Exchanger) GetTokenTTL() time.Duration

func (*Exchanger) IsRefreshTokenEnabled

func (e *Exchanger) IsRefreshTokenEnabled() bool

func (*Exchanger) LoginClient

func (e *Exchanger) LoginClient(ctx context.Context, clientID, clientSecret, scope string) (TokenSet, error)

func (*Exchanger) LoginClientResource added in v0.16.0

func (e *Exchanger) LoginClientResource(ctx context.Context, clientID, clientSecret, scope, targetAudience string) (TokenSet, error)

LoginClientResource is LoginClient signed for a peer resource's audience instead of the host: the SAME authenticated client identity + re-resolved authority (buildClientSigningContext), addressed to targetAudience so a confidential client can call a peer function without an RFC 8693 exchange. The caller (token handler) has already checked the resource against the client's AllowedResources gate and resolved targetAudience solely from ExchangeTargets[resource] -- AllowedResources authorizes the request, it plays no part in resolving the audience. No `act` -- the client is itself the subject.

func (*Exchanger) LoginLocal

func (e *Exchanger) LoginLocal(ctx context.Context, username, password, scope, clientID string, authMethod AuthMethod) (TokenSet, error)

func (*Exchanger) MintResourcePAT added in v0.3.0

func (e *Exchanger) MintResourcePAT(resource, subject, scope string, ttl time.Duration) (string, error)

MintResourcePAT mints an audience-bound PASETO PAT for an oauth2 protected resource. The PAT's aud is the resource URI (RFC 8707); the subject's entitlements are NOT baked in — the proxy re-resolves them from the subject's KDexRoleBindings at request time.

func (*Exchanger) RedeemAuthorizationCode

func (e *Exchanger) RedeemAuthorizationCode(ctx context.Context, code, clientID, redirectURI, codeVerifier string) (TokenSet, error)

RedeemAuthorizationCode validates and exchanges an authorization code for a TokenSet.

func (*Exchanger) RedeemRefreshToken

func (e *Exchanger) RedeemRefreshToken(ctx context.Context, tokenID, clientID string) (_ TokenSet, err error)

RedeemRefreshToken validates and consumes a refresh token (one-time use / rotation), then returns a fresh TokenSet including a rotated refresh token. The results are NAMED so the #172 compensating restore can inspect the error this call is actually returning. Nothing else depends on the names.

func (*Exchanger) ResolveInternalRolesAndEntitlements added in v0.2.97

func (e *Exchanger) ResolveInternalRolesAndEntitlements(subject string) ([]string, []string, error)

ResolveInternalRolesAndEntitlements maps a subject (e.g. the `sub` of a validated PASETO API token) to its internal roles and entitlements using the same KDexRole/KDexRoleBinding resolution the JWT login path uses (scopeProvider.FindInternalRolesAndEntitlements). It exists so the proxy's PASETO->authContext bridge can derive a structured authorization context for API-token callers without duplicating role resolution. Returns empty slices (fail-closed) when no identity provider is wired. See kdex-tech/host-manager#103.

func (*Exchanger) ResolveSubjectClaims added in v0.4.11

func (e *Exchanger) ResolveSubjectClaims(subject string) jwt.MapClaims

ResolveSubjectClaims resolves a subject's data-driven backend claims (e.g. a backend claim) FRESH and password-lessly for the token bridge, memoized for a short window to bound backend load. Returns nil when the identity provider can't resolve them (e.g. no http-lookup resolve endpoint wired), so the bridge degrades to role-only entitlements. See kdex-tech/host-manager#138.

func (*Exchanger) RevokeRefreshToken added in v0.2.92

func (e *Exchanger) RevokeRefreshToken(ctx context.Context, tokenID string) error

RevokeRefreshToken deletes the refresh-token entry identified by tokenID from the cache. Idempotent — returns nil if no entry exists. Called from logout flows so a stolen `_refresh` cookie value cannot be replayed after the user logs out. See kdex-tech/host-manager#84.

It also tears down the #169 grace records that can still replay this session, which deleting the refresh token alone does not cover. A grace record is keyed by the CONSUMED token id, so after a T1->T2 rotation the live record sits under T1 while the cookie holds T2: revoking T2 left anyone presenting T1 with the winner's access and ID tokens for the rest of the window. T2 is dead so no lineage continues, but logout had gained a replay window it did not have before the grace window existed. Both keys are therefore removed:

  • tokenID itself, for a logout that presents an already-consumed token (a stale cookie, or a client that raced its own rotation), and
  • claims.PredecessorID, the key under which THIS token was published -- the T1 above.

Grace deletion is best-effort: a failure there must not stop the actual revocation, which is what bounds the exposure to the grace window rather than the refresh-token TTL.

type FailureMode added in v0.14.0

type FailureMode string
const (
	FailOpen   FailureMode = "fail-open"
	FailClosed FailureMode = "fail-closed"
)

type HeaderPreserver added in v0.8.0

type HeaderPreserver interface {
	PreserveHeader(name, value string)
}

HeaderPreserver is a http.ResponseWriter that can be told which response headers THIS PROCESS authored, so a downstream re-render can restore them after wiping everything a proxied backend left behind.

Implemented by internal/host's errorResponseWriter, which buffers every >= 400 response and (for an HTML-accepting caller) re-renders it through the error utility page. That re-render deletes the whole header map, because a suppressed proxy body leaves a Content-Length describing bytes the client will never receive. Recording provenance is what lets the wipe stay total while a challenge this process wrote still reaches the client.

Declared here rather than in internal/host because internal/host imports internal/auth, so the dependency cannot run the other way.

type HookMode added in v0.14.0

type HookMode string
const (
	ModeAdvisory  HookMode = "advisory"
	ModeEnforcing HookMode = "enforcing"
)

type InternalIdentityProvider

type InternalIdentityProvider interface {
	FindInternal(subject string, password string) (jwt.MapClaims, error)
	FindInternalRolesAndEntitlements(subject string) ([]string, []string, error)
}

type JWK

type JWK struct {
	Alg string `json:"alg"`
	Kid string `json:"kid"`
	Kty string `json:"kty"`
	Use string `json:"use"`
	// RSA fields
	E string `json:"e,omitempty"`
	N string `json:"n,omitempty"`
	// ECDSA fields
	Crv string `json:"crv,omitempty"`
	X   string `json:"x,omitempty"`
	Y   string `json:"y,omitempty"`
}

JWK represents a JSON Web Key.

type JWKSet

type JWKSet struct {
	Keys []JWK `json:"keys"`
}

JWKSet represents a JSON Web Key Set.

type Lookup

type Lookup interface {
	FindInternal(subject string, password string) (bool, jwt.MapClaims, error)
	// ResolveClaims returns a subject's backend claims
	// WITHOUT a credential check — a password-less lookup the token bridge uses
	// to re-resolve data-driven grants fresh at request time. Returns
	// (nil, nil) when this lookup supplies no such claims. See
	// kdex-tech/host-manager#138.
	ResolveClaims(subject string) (jwt.MapClaims, error)
	Type() string
}

type OAuth2

type OAuth2 struct {
	AuthConfig    *Config
	AuthExchanger *Exchanger
	// ResourceAudiences is the set of oauth2-protected resource identifiers
	// for this host (both the basePath and the full resource URI forms, per
	// RFC 8707). When a token request carries a `resource` value present in
	// this set, the authorization_code grant mints an audience-bound PASETO
	// PAT as the access_token instead of the standard JWT.
	ResourceAudiences map[string]bool
	// ExchangeTargets maps a token-exchange `resource` value (basePath or
	// issuer+basePath) to the target function's audience. Includes internal
	// functions. Snapshot handed in by the host, same pattern as
	// ResourceAudiences.
	ExchangeTargets map[string]string
	// AccessTokenTTL is the lifetime applied to a minted resource PAT.
	AccessTokenTTL time.Duration
}

func (*OAuth2) AuthorizeHandler

func (o *OAuth2) AuthorizeHandler(w http.ResponseWriter, r *http.Request)

func (*OAuth2) OAuth2TokenHandler

func (o *OAuth2) OAuth2TokenHandler(w http.ResponseWriter, r *http.Request)

func (*OAuth2) OAuthGet

func (o *OAuth2) OAuthGet(w http.ResponseWriter, r *http.Request)

type OIDCClientConfig added in v0.2.9

type OIDCClientConfig struct {
	ClientID     string
	ClientSecret string
	BlockKey     string
	Name         string
}

func OIDCConfigLoader

func OIDCConfigLoader(secrets kdexv1alpha1.Secrets, devMode bool) (*OIDCClientConfig, error)

type OIDCExchange added in v0.7.0

type OIDCExchange struct {
	RawIDToken           string
	UpstreamRefreshToken string
}

OIDCExchange is what an authorization-code exchange with the upstream IdP yielded. UpstreamRefreshToken is empty unless offline access was requested AND the provider issued one -- it was previously discarded outright, which is the second half of kdex-tech/host-manager#190.

type OIDCProviderClaims

type OIDCProviderClaims struct {
	EndSessionURL   string   `json:"end_session_endpoint"`
	ScopesSupported []string `json:"scopes_supported"`
}

type OpenIDConfiguration

type OpenIDConfiguration struct {
	AuthorizationEndpoint            string   `json:"authorization_endpoint,omitempty"`
	ClaimsSupported                  []string `json:"claims_supported,omitempty"`
	CodeChallengeMethodsSupported    []string `json:"code_challenge_methods_supported,omitempty"`
	GrantTypesSupported              []string `json:"grant_types_supported,omitempty"`
	IDTokenSigningAlgValuesSupported []string `json:"id_token_signing_alg_values_supported"`
	Issuer                           string   `json:"issuer"`
	JwksURI                          string   `json:"jwks_uri"`
	RegistrationEndpoint             string   `json:"registration_endpoint,omitempty"`
	ResponseTypesSupported           []string `json:"response_types_supported"`
	ScopesSupported                  []string `json:"scopes_supported,omitempty"`
	SubjectTypesSupported            []string `json:"subject_types_supported"`
	TokenEndpoint                    string   `json:"token_endpoint,omitempty"`
}

OpenIDConfiguration represents the OIDC discovery document.

type RefreshTokenClaims

type RefreshTokenClaims struct {
	AuthMethod       AuthMethod `json:"auth_method"`
	ClientID         string     `json:"cid"`
	ExpiresAt        int64      `json:"exp"`
	IssuedAt         int64      `json:"iat"`
	OriginalIssuedAt int64      `json:"oiat"`
	// PredecessorID is the id of the refresh token this one ROTATED FROM,
	// set only by RedeemRefreshToken. It is the key the #169 grace record
	// for that rotation lives under, and exists so RevokeRefreshToken can
	// tear the record down at logout -- the grace record is keyed by the
	// CONSUMED token, which is not the value the cookie holds afterwards,
	// so revocation has no other way to find it. Empty on a freshly minted
	// (non-rotated) token and on records written before this field
	// existed; omitempty keeps those round-tripping unchanged.
	PredecessorID string `json:"pid,omitempty"`
	Scope         string `json:"scp"`
	Subject       string `json:"sub"`
	// IDPClaims is the claim set the upstream IdP asserted at login, minus
	// reservedMintClaims. Rotation re-mints through mintTokensFromSubject,
	// which knows only what FindInternalRolesAndEntitlements returns -- so
	// without this every IdP-supplied claim (email, profile, and any custom
	// claim a host's ClaimMappings reads as an INPUT) would vanish at the
	// first rotation, an hour into the session. Empty for non-OIDC grants
	// and for records written before this field existed; omitempty keeps
	// those round-tripping unchanged.
	//
	// Deliberately NOT allowlisted down to the claims the signer projects: a
	// host's ClaimMappings is CEL over the WHOLE signing context, so any claim
	// can be a mapper INPUT, and a fixed allowlist is exactly what would drop
	// the custom one some tenant depends on. The cost is that identity claims
	// (email, name, ...) now sit in the refresh-token cache beside the `sub`
	// already there -- same store, same trust boundary, more PII at rest.
	// See kdex-tech/host-manager#189.
	IDPClaims jwt.MapClaims `json:"idpc,omitempty"`
	// UpstreamRefreshToken is the refresh token the IdP issued for this
	// session, held so a rotation can re-derive the user from the IdP instead
	// of replaying IDPClaims. Empty unless offline access was requested and
	// the provider issued one.
	//
	// This is a long-lived THIRD-PARTY credential living in the same cache as
	// this host's own refresh tokens -- the trust boundary is unchanged, but
	// the value of the store is not. See kdex-tech/host-manager#190.
	UpstreamRefreshToken string `json:"urt,omitempty"`
}

RefreshTokenClaims holds the data stored inside a refresh token entry in the cache.

type TokenResponse

type TokenResponse struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"`
	IDToken     string `json:"id_token,omitempty"`
	// IssuedTokenType is RFC 8693 2.2.1's required field on a token-exchange
	// response, naming the type of the issued access_token. Empty (and thus
	// omitted) for every other grant this endpoint serves.
	IssuedTokenType string `json:"issued_token_type,omitempty"`
	RefreshToken    string `json:"refresh_token,omitempty"`
	Scope           string `json:"scope,omitempty"`
	TokenType       string `json:"token_type"`
}

TokenResponse represents the OAuth2 token response.

type TokenSet

type TokenSet struct {
	AccessToken  string
	IDToken      string
	RefreshToken string
	Scope        string
	Subject      string
}

TokenSet is the result of a token minting operation.

On success every field is populated as the grant allows. On failure the zero value is returned EXCEPT for Subject, which is set whenever the failing operation had already established a server-vouched subject -- decrypted authorization-code claims, a stored refresh-token record, a credential-store hit, or an authenticated client. This lets the token endpoint attribute a rejected exchange to an identity instead of logging `"subject": ""`. See kdex-tech/host-manager#158.

Callers must still gate on the returned error: a non-empty Subject says who the request was about, never that it succeeded.

Directories

Path Synopsis
Package denial implements host-manager's single denial contract.
Package denial implements host-manager's single denial contract.

Jump to

Keyboard shortcuts

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