Documentation
¶
Index ¶
- Constants
- Variables
- func AuthClientLoader(secrets kdexv1alpha1.Secrets) (map[string]AuthClient, error)
- func DiscoveryHandler(issuer string, registrationEndpoint string) http.HandlerFunc
- func EnrichAuthContext(ac AuthContext, mapper *dmapper.Mapper)
- func FormatADGUID(b []byte) (string, error)
- func JWKSHandler(keyPairs *keys.KeyPairs) http.HandlerFunc
- func LooksLikePAT(token, tokenPrefix string) bool
- func NewHTTPLookup(secret corev1.Secret) (*httpLookup, error)
- func NewLDAPLookup(secret corev1.Secret) *ldapLookup
- func NewRoleProvider(ctx context.Context, c client.Client, focalHost string, ...) (*scopeProvider, error)
- func NewSecretLookup(secrets kdexv1alpha1.Secrets) *secretLookup
- func SetAuthContext(ctx context.Context, ac AuthContext) context.Context
- type AuthClient
- type AuthContext
- func (ac AuthContext) GetAudience() (jwt.ClaimStrings, error)
- func (ac AuthContext) GetAuthMethod() (AuthMethod, error)
- func (ac AuthContext) GetEntitlements() ([]string, error)
- func (ac AuthContext) GetExpirationTime() (*jwt.NumericDate, error)
- func (ac AuthContext) GetIssuedAt() (*jwt.NumericDate, error)
- func (ac AuthContext) GetIssuer() (string, error)
- func (ac AuthContext) GetNotBefore() (*jwt.NumericDate, error)
- func (ac AuthContext) GetRoles() ([]string, error)
- func (ac AuthContext) GetScopes() ([]string, error)
- func (ac AuthContext) GetSubject() (string, error)
- func (ac AuthContext) IsPATBridge() bool
- type AuthMethod
- type AuthorizationChecker
- func (ac *AuthorizationChecker) BindRequirements(reqs entitlements.ParsedRequirements, binding entitlements.Binding) (entitlements.ParsedRequirements, error)
- func (ac *AuthorizationChecker) CalculateRequirements(resource string, resourceName string, ...) ([]kdexv1alpha1.SecurityRequirement, error)
- func (ac *AuthorizationChecker) CheckAccess(ctx context.Context, resource string, resourceName string, ...) (bool, error)
- func (ac *AuthorizationChecker) GetParsedEntitlements(ctx context.Context) entitlements.ParsedEntitlements
- func (ac *AuthorizationChecker) ParseEntitlements(e entitlements.Entitlements) entitlements.ParsedEntitlements
- func (ac *AuthorizationChecker) ParseRequirements(kdexreqs []kdexv1alpha1.SecurityRequirement) (result entitlements.ParsedRequirements)
- func (ac *AuthorizationChecker) VerifyResourceParsedEntitlements(resource string, resourceName string, ...) (bool, error)
- type AuthorizationCodeClaims
- type CompiledMappingRule
- type Config
- func (c *Config) AddAuthentication(mux http.Handler, exchanger *Exchanger) http.Handler
- func (c *Config) IsAuthEnabled() bool
- func (c *Config) IsM2MEnabled() bool
- func (c *Config) IsOIDCEnabled() bool
- func (c *Config) TokenPrefix() string
- func (c *Config) WithAuthentication(exchanger *Exchanger) func(http.Handler) http.Handler
- type ConfigBuilder
- func (cb *ConfigBuilder) Build(auth *kdexv1alpha1.Auth) (*Config, error)
- func (cb *ConfigBuilder) WithAPITokenManagerLoader(apiTokenManagerLoader func() (*apitoken.TokenManager, error)) *ConfigBuilder
- func (cb *ConfigBuilder) WithAudience(audience string) *ConfigBuilder
- func (cb *ConfigBuilder) WithAuthClientLoader(authClientLoader func() (map[string]AuthClient, error)) *ConfigBuilder
- func (cb *ConfigBuilder) WithCacheManager(cacheManager cache.CacheManager) *ConfigBuilder
- func (cb *ConfigBuilder) WithDevMode(devMode bool) *ConfigBuilder
- func (cb *ConfigBuilder) WithFunctions(functions kdexv1alpha1.KDexFunctionList) *ConfigBuilder
- func (cb *ConfigBuilder) WithIssuer(issuer string) *ConfigBuilder
- func (cb *ConfigBuilder) WithKeyLoader(keyLoader func() (*keys.KeyPairs, error)) *ConfigBuilder
- func (cb *ConfigBuilder) WithOIDCClientConfigLoader(oidcClientConfigLoader func() (*OIDCClientConfig, error)) *ConfigBuilder
- func (cb *ConfigBuilder) WithRefreshGraceWindow(d time.Duration) *ConfigBuilder
- type ContextKey
- type DCRConfig
- type Exchanger
- func (e *Exchanger) AuthCodeURL(state string) string
- func (e *Exchanger) CreateAuthorizationCode(ctx context.Context, claims AuthorizationCodeClaims) (string, error)
- func (e *Exchanger) EndSessionURL() (string, error)
- func (e *Exchanger) ExchangeCode(ctx context.Context, code string) (string, error)
- func (e *Exchanger) ExchangeToken(ctx context.Context, rawIDToken string) (string, error)
- func (e *Exchanger) GetClient(clientID string) (AuthClient, bool)
- func (e *Exchanger) GetOIDCClientID() string
- func (e *Exchanger) GetScopesSupported() ([]string, error)
- func (e *Exchanger) GetTokenTTL() time.Duration
- func (e *Exchanger) IsRefreshTokenEnabled() bool
- func (e *Exchanger) LoginClient(ctx context.Context, clientID, clientSecret, scope string) (TokenSet, error)
- func (e *Exchanger) LoginLocal(ctx context.Context, username, password, scope, clientID string, ...) (TokenSet, error)
- func (e *Exchanger) MintResourcePAT(resource, subject, scope string, ttl time.Duration) (string, error)
- func (e *Exchanger) RedeemAuthorizationCode(ctx context.Context, code, clientID, redirectURI, codeVerifier string) (TokenSet, error)
- func (e *Exchanger) RedeemRefreshToken(ctx context.Context, tokenID, clientID string) (TokenSet, error)
- func (e *Exchanger) ResolveInternalRolesAndEntitlements(subject string) ([]string, []string, error)
- func (e *Exchanger) ResolveSubjectClaims(subject string) jwt.MapClaims
- func (e *Exchanger) RevokeRefreshToken(ctx context.Context, tokenID string) error
- type InternalIdentityProvider
- type JWK
- type JWKSet
- type Lookup
- type OAuth2
- type OIDCClientConfig
- type OIDCProviderClaims
- type OpenIDConfiguration
- type RefreshTokenClaims
- type TokenResponse
- type TokenSet
Constants ¶
const ( COOKIE = "cookie" GRANT_TYPE_AUTHORIZATION_CODE = "authorization_code" GRANT_TYPE_REFRESH_TOKEN = "refresh_token" HTTP = "http" HTTPS = "https" PKCE_METHOD_S256 = "S256" TRUE = "true" )
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.
const (
HTTPLookupSecretType = "http-lookup-auth"
)
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.
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 ¶
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. This is an opt-in allowlist, not a fallthrough: RedeemRefreshToken and RedeemAuthorizationCode call out to mintTokensFromCode, LoginLocal and LoginClient, whose infrastructure failures (signer down, identity-provider HTTP lookup down, resolver down) are NOT marked with this and must not have their message echoed — a raw HTTP dial error can carry an internal service URL and pod IP. The token endpoint's classifier (oauthErrorForRedemption) treats anything carrying neither this nor ErrServerError as a grant failure too, but with a fixed generic description rather than its own message: a future error added anywhere in the call graph that forgets to mark itself must disclose nothing. See kdex-tech/host-manager#168.
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.
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.
Functions ¶
func AuthClientLoader ¶
func AuthClientLoader(secrets kdexv1alpha1.Secrets) (map[string]AuthClient, error)
func DiscoveryHandler ¶
func DiscoveryHandler(issuer string, registrationEndpoint string) http.HandlerFunc
DiscoveryHandler creates an HTTP handler that serves the OpenID discovery document.
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 ¶
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
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 NewHTTPLookup ¶ added in v0.2.52
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 NewRoleProvider ¶
func NewSecretLookup ¶
func NewSecretLookup(secrets kdexv1alpha1.Secrets) *secretLookup
func SetAuthContext ¶
func SetAuthContext(ctx context.Context, ac AuthContext) context.Context
SetAuthContext sets the auth context in the context.
Types ¶
type AuthClient ¶
type AuthContext ¶
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
func (ac *AuthorizationChecker) BindRequirements( reqs entitlements.ParsedRequirements, binding entitlements.Binding, ) (entitlements.ParsedRequirements, error)
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 (ac *AuthorizationChecker) ParseEntitlements(e entitlements.Entitlements) entitlements.ParsedEntitlements
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"`
// 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
}
DCR DCRConfig
DCRStore *dcr.Store
MintCapCache cache.Cache
MintTokenEnabled bool
MintTokenTTLCap 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
TokenManager *apitoken.TokenManager
TokenTTL time.Duration
}
func (*Config) AddAuthentication ¶
func (*Config) IsAuthEnabled ¶
func (*Config) IsM2MEnabled ¶
func (*Config) IsOIDCEnabled ¶
func (*Config) TokenPrefix ¶ added in v0.3.0
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) WithAuthentication ¶ added in v0.2.9
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 Exchanger ¶
type Exchanger struct {
// contains filtered or unexported fields
}
func NewExchanger ¶
func NewExchanger( ctx context.Context, cfg Config, cacheManager cache.CacheManager, sp InternalIdentityProvider, ) (*Exchanger, error)
func (*Exchanger) AuthCodeURL ¶
func (*Exchanger) CreateAuthorizationCode ¶
func (*Exchanger) EndSessionURL ¶
func (*Exchanger) ExchangeCode ¶
func (*Exchanger) ExchangeToken ¶
func (*Exchanger) GetOIDCClientID ¶
func (*Exchanger) GetScopesSupported ¶
func (*Exchanger) GetTokenTTL ¶
func (*Exchanger) IsRefreshTokenEnabled ¶
func (*Exchanger) LoginClient ¶
func (*Exchanger) LoginLocal ¶
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, error)
RedeemRefreshToken validates and consumes a refresh token (one-time use / rotation), then returns a fresh TokenSet including a rotated refresh token.
func (*Exchanger) ResolveInternalRolesAndEntitlements ¶ added in v0.2.97
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
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
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 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 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
// 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)
type OIDCClientConfig ¶ added in v0.2.9
func OIDCConfigLoader ¶
func OIDCConfigLoader(secrets kdexv1alpha1.Secrets, devMode bool) (*OIDCClientConfig, error)
type OIDCProviderClaims ¶
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"`
}
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"`
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.