contract

package
v0.0.0-...-4ff1bda Latest Latest
Warning

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

Go to latest
Published: Aug 14, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package contract holds the cross-cutting types and interfaces shared between the base auth package and the plugin packages.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidCredentials is returned when the supplied username/password is wrong.
	ErrInvalidCredentials = errors.New("invalid credentials")
	// ErrUserAlreadyExists is returned by Registerer.Register when the account is taken.
	ErrUserAlreadyExists = errors.New("user already exists")
	// ErrUserNotFound is returned by UserProvider.GetUser when the user ID is unknown.
	ErrUserNotFound = errors.New("user not found")
)

Functions

This section is empty.

Types

type ACRLevelConfig

type ACRLevelConfig struct {
	Value       string   `mapstructure:"value"        validate:"required"` // acr string, e.g. "loa1"
	Level       int      `mapstructure:"level"        validate:"required"` // ordinal rank; higher = stronger
	AuthMethods []string `mapstructure:"auth_methods"`                     // permitted primary methods (empty = any)
	RequireMFA  bool     `mapstructure:"require_mfa"`                      // session must have passed MFA
	MFAMethods  []string `mapstructure:"mfa_methods"`                      // permitted MFA methods (empty = any enrolled)
	// MFASatisfiedByAMR lists amr values that, if already present from the PRIMARY method,
	// satisfy RequireMFA without prompting a separate factor.
	MFASatisfiedByAMR []string `mapstructure:"mfa_satisfied_by_amr"`
	AMR               []string `mapstructure:"amr"` // amr values recorded when satisfied (optional)
}

ACRLevelConfig defines one authentication context class (Level of Assurance). Levels form an ordered ladder via Level: satisfying a higher level also satisfies every lower one.

type AuthenticatorConfig

type AuthenticatorConfig struct {
	Name        string            `mapstructure:"name"`   // method name used in URLs: /authn/{name}/* and in AMR
	Driver      string            `mapstructure:"driver"` // registered authenticator driver, e.g. "passkey"
	Config      map[string]string `mapstructure:"config"` // driver-specific options
	ClaimMapper ClaimMapper       `mapstructure:"-"`      // optional per-method override; set in code
}

AuthenticatorConfig configures one passwordless primary-auth driver instance (passkey, magic-link, …). Resolved dynamically per request against the live slice, like Providers.

type ClaimMapper

type ClaimMapper interface {
	MapClaims(ctx context.Context, name string, raw map[string]any) (UserInfo, error)
}

ClaimMapper turns the raw claims returned by an external IdP or a passwordless authenticator into a UserInfo.

type ClaimMapperFunc

type ClaimMapperFunc func(ctx context.Context, name string, raw map[string]any) (UserInfo, error)

ClaimMapperFunc adapts a plain function to the ClaimMapper interface.

func (ClaimMapperFunc) MapClaims

func (f ClaimMapperFunc) MapClaims(ctx context.Context, name string, raw map[string]any) (UserInfo, error)

MapClaims implements ClaimMapper.

type Configuration

type Configuration struct {
	Secret string `mapstructure:"secret" validate:"required,min=32"`
	// FallbackSecrets holds previous PASETO local secrets, kept for decryption/verification only,
	// enabling zero-downtime rotation of Secret. New tokens are always sealed with Secret;
	// decryption falls back to this.
	FallbackSecrets []string `mapstructure:"fallback_secrets"`
	// Secure pins the cookie Secure flag, defaults to secure.
	Secure *bool `mapstructure:"secure"`
	// SameSite pins the cookie SameSite mode, defaults to strict.
	SameSite   string `mapstructure:"same_site" validate:"omitempty,oneof=strict lax none"`
	CookieName string `mapstructure:"cookie_name"` // default: "__session"
	CookiePath string `mapstructure:"cookie_path"` // default: base path + auth mount prefix (see CookieCtx.PathFor)
	// LogoutInvalidatesCookie makes logout authoritative server-side (session + JTI revoked).
	// Default true; only disable if a shared cookie must survive a single app's logout.
	LogoutInvalidatesCookie bool          `mapstructure:"logout_invalidates_cookie"`
	AccessTokenTTL          time.Duration `mapstructure:"access_token_ttl" validate:"required"` // default: 20m
	SessionTTL              time.Duration `mapstructure:"session_ttl"      validate:"required"` // default: 8h
	CodeTTL                 time.Duration `mapstructure:"code_ttl"`                             // authorization-code lifetime; default: 60s
	// BaseURL pins the public base URL used to resolve the issuer and the default cookie
	// path instead of deriving them from the incoming request (proxies, split origin).
	BaseURL string `mapstructure:"base_url" validate:"omitempty,url"`
	// Issuer is the OIDC issuer identifier (iss claim, discovery document base).
	Issuer string `mapstructure:"issuer" validate:"omitempty,url"`
	// Keys is the JWT/JWKS signing key set. Nil = introspect-only mode (no JWKS endpoint,
	// no id_token issuance); supply it (or the KeyProvider() option) to enable JWT tokens.
	Keys           *KeySetConfig            `mapstructure:"keys"           validate:"omitempty"`
	Providers      []ExternalProviderConfig `mapstructure:"providers"      validate:"omitempty,dive"`
	Authenticators []AuthenticatorConfig    `mapstructure:"authenticators" validate:"omitempty,dive"` // passwordless primary methods
	ACRLevels      []ACRLevelConfig         `mapstructure:"acr_levels"     validate:"omitempty,dive"` // trust ladder
	Throttle       ThrottleConfig           `mapstructure:"throttle"`                                 // brute-force / lockout tuning
}

Configuration is the authentication configuration section.

func (*Configuration) Bind

func (c *Configuration) Bind(prefix string, v *viper.Viper)

Bind registers defaults and environment variable bindings for the auth configuration section under the given prefix.

func (*Configuration) Validate

func (c *Configuration) Validate(valid *validation.Validate) error

Validate validates the authentication configuration section.

type ExternalProviderConfig

type ExternalProviderConfig struct {
	Name         string `mapstructure:"name"`   // identifier used in URLs: /external/{name}/*
	Driver       string `mapstructure:"driver"` // registered driver name, e.g. "azure"
	ClientID     string `mapstructure:"client_id"      validate:"required"`
	ClientSecret string `mapstructure:"client_secret"` // loaded via LoadRemoteSecret
	RedirectURL  string `mapstructure:"redirect_url"   validate:"required,url"`
	Scopes       []string
	// LogoutAfterAuth is the "no-SSO" mode: RP-initiate logout at the IdP immediately after a
	// successful login and finalize the local session only on the logout callback.
	LogoutAfterAuth bool              `mapstructure:"logout_after_auth"`
	Config          map[string]string `mapstructure:"config"` // driver-specific extra options
}

ExternalProviderConfig configures one external IdP driver instance.

type ExternalUserProvider

type ExternalUserProvider interface {
	FindOrCreateUser(ctx context.Context, method string, info UserInfo) (UserInfo, error)
}

ExternalUserProvider is an optional extension of UserProvider, the shared identity-resolution hook for BOTH external IdP logins AND passwordless authenticators.

type KeyConfig

type KeyConfig struct {
	// ID is the key ID (kid) included in issued JWTs and the JWKS document; unique per set.
	// Defaults to the RFC 7638 JWK Thumbprint of the public key when unset.
	ID string `mapstructure:"id"`
	// Algorithm is RS256, RS384, RS512, ES256, ES384 or ES512.
	Algorithm string `mapstructure:"algorithm" validate:"omitempty,oneof=RS256 RS384 RS512 ES256 ES384 ES512"`
	// PrivateKey is a PEM-encoded private key.
	PrivateKey string `mapstructure:"private_key"`
	// PublicKey is a PEM-encoded public key or certificate.
	PublicKey string `mapstructure:"public_key"`
}

KeyConfig describes one asymmetric key pair or certificate.

type KeySetConfig

type KeySetConfig struct {
	Primary   KeyConfig   `mapstructure:"primary"   validate:"required"`
	Signing   []KeyConfig `mapstructure:"signing"   validate:"omitempty,dive"`
	Secondary []KeyConfig `mapstructure:"secondary" validate:"omitempty,dive"`
}

KeySetConfig holds the signing key set for JWT/JWKS operations. Primary is the default signing key; Signing keys offer alternative algorithms (one key per algorithm) for clients that register a different id_token_signed_response_alg; Secondary keys verify only (in order).

type PasswordChanger

type PasswordChanger interface {
	// ChangePassword changes the authenticated user's password after verifying currentPassword.
	// Used by the self-service flow on an active session.
	ChangePassword(ctx context.Context, userID, currentPassword, newPassword string) error
	// SetPassword sets a new password WITHOUT verifying a current one. It is called only to
	// complete a pending_password_change session.
	SetPassword(ctx context.Context, userID, newPassword string) error
}

PasswordChanger is an optional UserProvider extension for changing a user's password.

type PasswordResetter

type PasswordResetter interface {
	// RequestPasswordReset initiates a reset flow (e.g. sends an email with a token).
	RequestPasswordReset(ctx context.Context, identifier string) error
	// ResetPassword sets a new password using a verified reset token (no old password needed).
	ResetPassword(ctx context.Context, token, newPassword string) error
}

PasswordResetter is an optional UserProvider extension for reseting forgotten password.

type ProfileManager

type ProfileManager interface {
	// GetProfile returns display/profile data for the authenticated user.
	GetProfile(ctx context.Context, userID string) (map[string]any, error)
	// UpdateProfile updates display/profile data for the authenticated user.
	UpdateProfile(ctx context.Context, userID string, data map[string]any) error
}

ProfileManager is an optional UserProvider extension for user profile.

type Registerer

type Registerer interface {
	// Register creates a new user account. Returns ErrUserAlreadyExists if taken.
	Register(ctx context.Context, req RegistrationRequest) (UserInfo, error)
}

Registerer is an optional UserProvider for registering new user accounts.

type RegistrationRequest

type RegistrationRequest struct {
	Username string
	Email    string
	Password string
	Extra    map[string]any // custom data needed for registration
}

RegistrationRequest carries the data for a new user registration.

type ThrottleConfig

type ThrottleConfig struct {
	Enabled bool `mapstructure:"enabled"` // default: true
	// MaxAttempts/Window/LockoutTTL are required (non-zero) only when Enabled is set.
	MaxAttempts int           `mapstructure:"max_attempts" validate:"required_with=Enabled"` // default: 5
	Window      time.Duration `mapstructure:"window"       validate:"required_with=Enabled"` // default: 15m
	LockoutTTL  time.Duration `mapstructure:"lockout_ttl"  validate:"required_with=Enabled"` // default: 15m
	// MFA code resend (POST /mfa/resend), enforced independently of the verify lockout.
	MFAResendCooldown time.Duration `mapstructure:"mfa_resend_cooldown"` // default: 60s
	MFAMaxResends     int           `mapstructure:"mfa_max_resends"`     // default: 3
}

ThrottleConfig tunes the default cache-backed lockout guard applied to credential endpoints.

type UserInfo

type UserInfo struct {
	ID    string
	Name  string
	Email string
	// Scope is the user's maximal, space-separated scope: both the OIDC scope values
	// (openid, profile, email, ...) and any application-defined authorization scopes
	// (admin, items:write, ...).
	Scope                  string
	Claims                 map[string]any
	RequiresPasswordChange bool
	// AMR lets a claim mapper / external login / authenticator ASSERT the authentication
	// methods of this login - RFC 8176 values, e.g. ["mfa","hwk"].
	AMR []string
}

UserInfo is returned by UserProvider. All fields are optional except ID.

func (UserInfo) ToUser

func (info UserInfo) ToUser() *user.Basic

ToUser returns user identity.

type UserProvider

type UserProvider interface {
	// Authenticate returns a UserInfo on success or an error ErrInvalidCredentials.
	Authenticate(ctx context.Context, username, password string) (UserInfo, error)
	// GetUser returns the current state of a user by ID.
	GetUser(ctx context.Context, userID string) (UserInfo, error)
}

UserProvider validates credentials and loads user data.

Jump to

Keyboard shortcuts

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