Documentation
¶
Index ¶
- func ClaimString(claims map[string]interface{}, key string) string
- func ClaimStringSlice(claims map[string]interface{}, key string) []string
- func ContextWithUserInfo(ctx context.Context, info *UserInfo) context.Context
- func GenerateKey() (string, error)
- func NewMiddleware(cfg MiddlewareConfig) func(http.Handler) http.Handler
- type AuditLogger
- type AuthMetrics
- type AuthProvider
- type CompositeProvider
- type GitHubProvider
- type GitHubProviderConfig
- type MiddlewareConfig
- type OIDCProvider
- type OIDCProviderConfig
- type SessionClaims
- type SessionConfig
- type SessionManager
- type TokenCache
- type TokenReviewProvider
- type UserInfo
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ClaimString ¶ added in v0.7.0
ClaimString extracts a string claim from the raw claims map.
func ClaimStringSlice ¶ added in v0.7.0
ClaimStringSlice extracts a string slice claim from the raw claims map. Handles three formats:
- []string (standard OIDC)
- []interface{} (JSON-decoded array)
- map[string]interface{} (Zitadel project roles, where keys are role names)
func ContextWithUserInfo ¶
ContextWithUserInfo returns a new context with the user's identity attached.
func GenerateKey ¶ added in v0.7.0
GenerateKey generates a cryptographically random 32-byte key suitable for use as a session signing key. Returns the key as base64-encoded string.
func NewMiddleware ¶
func NewMiddleware(cfg MiddlewareConfig) func(http.Handler) http.Handler
NewMiddleware creates net/http middleware that authenticates requests via Kubernetes TokenReview with LRU caching.
Types ¶
type AuditLogger ¶
type AuthMetrics ¶
type AuthMetrics struct {
Latency *prometheus.HistogramVec // provider, result
CacheHits prometheus.Counter
CacheMisses prometheus.Counter
Attempts *prometheus.CounterVec // provider, result
}
AuthMetrics holds Prometheus metrics for the auth middleware.
type AuthProvider ¶
AuthProvider authenticates a bearer token and returns user identity.
type CompositeProvider ¶ added in v0.7.0
type CompositeProvider struct {
// contains filtered or unexported fields
}
CompositeProvider tries multiple AuthProviders in order, returning on the first successful authentication. This allows coexistence of OIDC sessions, GitHub sessions, and Kubernetes ServiceAccount tokens.
func NewCompositeProvider ¶ added in v0.7.0
func NewCompositeProvider(logger *slog.Logger) *CompositeProvider
NewCompositeProvider creates a composite provider that tries providers in order. The first provider to successfully authenticate wins. All providers must fail for the authentication to be rejected.
func (*CompositeProvider) Add ¶ added in v0.7.0
func (cp *CompositeProvider) Add(name string, provider AuthProvider)
Add registers a named auth provider. Providers are tried in registration order.
func (*CompositeProvider) Authenticate ¶ added in v0.7.0
Authenticate tries each registered provider in order. Returns the first successful result. If all providers fail, returns a combined error.
type GitHubProvider ¶ added in v0.7.0
type GitHubProvider struct {
// contains filtered or unexported fields
}
GitHubProvider authenticates users via GitHub OAuth2 access tokens. It fetches the user's profile and team memberships to build UserInfo.
func NewGitHubProvider ¶ added in v0.7.0
func NewGitHubProvider(cfg GitHubProviderConfig, session *SessionManager, logger *slog.Logger) *GitHubProvider
NewGitHubProvider creates a new GitHub authentication provider.
func (*GitHubProvider) Authenticate ¶ added in v0.7.0
Authenticate verifies the token as either a Diverge session JWT or a GitHub personal access token. Returns UserInfo on success.
type GitHubProviderConfig ¶ added in v0.7.0
type GitHubProviderConfig struct {
// AllowedOrgs restricts access to members of these GitHub organizations.
// Empty list means all authenticated GitHub users are allowed.
AllowedOrgs []string
// AllowedGroups restricts access to users in these groups (org:team format).
// Applied after session JWT verification.
AllowedGroups []string
}
GitHubProviderConfig configures the GitHub OAuth authentication provider.
type MiddlewareConfig ¶
type MiddlewareConfig struct {
Provider AuthProvider
Cache *TokenCache
Logger *slog.Logger
AuditLogger AuditLogger
Metrics *AuthMetrics
ExemptPaths []string
ExemptPrefixes []string
// LoginURL, when set, is where an unauthenticated BROWSER NAVIGATION is
// redirected instead of receiving the raw 401 below. A signed-out human
// loading the dashboard is the routine case — every session expires — and
// "missing or invalid authorization header" as a bare page is an error
// message for a state that is not an error. API callers, and anything not
// asking for text/html, keep the 401 they can act on.
LoginURL string
}
MiddlewareConfig configures the auth middleware.
type OIDCProvider ¶ added in v0.7.0
type OIDCProvider struct {
// contains filtered or unexported fields
}
OIDCProvider authenticates users by verifying OIDC ID tokens (JWTs). It supports both direct OIDC tokens and Diverge session JWTs.
func NewOIDCProvider ¶ added in v0.7.0
func NewOIDCProvider(ctx context.Context, cfg OIDCProviderConfig, session *SessionManager, logger *slog.Logger) (*OIDCProvider, error)
NewOIDCProvider creates a new OIDC authentication provider. It performs OpenID Connect discovery on the issuer URL to fetch the JWKS keys.
func (*OIDCProvider) Authenticate ¶ added in v0.7.0
Authenticate verifies the token as either a Diverge session JWT or an OIDC ID token. Returns UserInfo on success.
type OIDCProviderConfig ¶ added in v0.7.0
type OIDCProviderConfig struct {
// IssuerURL is the OIDC provider's issuer URL (used for discovery).
IssuerURL string
// ClientID is the OIDC client ID for token audience validation.
ClientID string
// UsernameClaim is the JWT claim used for the username. Defaults to "preferred_username".
UsernameClaim string
// GroupsClaim is the JWT claim used for group membership. Defaults to "groups".
GroupsClaim string
// AllowedGroups restricts access to users whose groups intersect this list.
// Empty list means all authenticated users are allowed.
AllowedGroups []string
}
OIDCProviderConfig configures the OIDC authentication provider.
type SessionClaims ¶ added in v0.7.0
type SessionClaims struct {
Subject string `json:"sub"`
Email string `json:"email,omitempty"`
Groups []string `json:"groups,omitempty"`
Issuer string `json:"iss"`
IssuedAt int64 `json:"iat"`
Expiry int64 `json:"exp"`
// Provider tracks which auth method created this session (e.g. "oidc", "github").
Provider string `json:"provider,omitempty"`
}
SessionClaims represents the claims in a Diverge session JWT.
type SessionConfig ¶ added in v0.7.0
type SessionConfig struct {
// SigningKey is the HMAC-SHA256 key for signing session JWTs.
SigningKey []byte
// MaxAge is the session duration. Defaults to 24 hours.
MaxAge time.Duration
// Issuer is the JWT issuer claim. Defaults to "diverge-server".
Issuer string
}
SessionConfig configures session JWT creation and verification.
type SessionManager ¶ added in v0.7.0
type SessionManager struct {
// contains filtered or unexported fields
}
SessionManager handles creation and verification of signed session JWTs.
func NewSessionManager ¶ added in v0.7.0
func NewSessionManager(cfg SessionConfig) (*SessionManager, error)
NewSessionManager creates a new session manager with the given config. If SigningKey is empty, a random 32-byte key is generated (sessions won't survive server restarts).
func (*SessionManager) Mint ¶ added in v0.7.0
func (sm *SessionManager) Mint(subject, email, provider string, groups []string) (string, error)
Mint creates a signed session JWT for the given user identity.
func (*SessionManager) Verify ¶ added in v0.7.0
func (sm *SessionManager) Verify(token string) (*SessionClaims, error)
Verify validates a session token and returns the claims.
type TokenCache ¶
type TokenCache struct {
// contains filtered or unexported fields
}
TokenCache is a bounded LRU cache for authenticated TokenReview results. Keys are SHA-256 hashes of tokens — raw tokens are never stored.
func NewTokenCache ¶
func NewTokenCache(maxSize int, ttl time.Duration) *TokenCache
NewTokenCache creates a cache with the given maximum size and entry TTL. A maxSize <= 0 creates a no-op cache that never stores entries.
func (*TokenCache) Get ¶
func (c *TokenCache) Get(token string) *UserInfo
Get looks up a cached user identity by token. Returns nil if not found or expired. Promotes the entry to newest on hit (LRU).
func (*TokenCache) Set ¶
func (c *TokenCache) Set(token string, user *UserInfo)
Set stores an authenticated user identity keyed by token hash. Only cache successful authentications — never cache failures. If the key already exists, it is updated in-place without eviction.
type TokenReviewProvider ¶
type TokenReviewProvider struct {
// contains filtered or unexported fields
}
TokenReviewProvider authenticates tokens via the Kubernetes TokenReview API.
func NewTokenReviewProvider ¶
func NewTokenReviewProvider(client kubernetes.Interface, audiences []string) *TokenReviewProvider
NewTokenReviewProvider creates a provider that validates tokens against the kube-apiserver.
func (*TokenReviewProvider) Authenticate ¶
type UserInfo ¶
type UserInfo struct {
Username string
UID string
Email string
Groups []string
Extra map[string]authorizationv1.ExtraValue
}
UserInfo represents the authenticated user's identity.
func UserInfoFromContext ¶
UserInfoFromContext extracts the authenticated user's identity from the context.