Documentation
¶
Overview ¶
Package authhandlers provides shared types and utilities for the server's authentication handler cluster: login, TOTP, WebAuthn, OIDC, admin user management, and security management (password change, API keys, passkeys).
Index ¶
- Constants
- func Audit(r *http.Request, level slog.Level, event AuditEvent, success bool, user string, ...)
- func Base64URLEncode(data []byte) string
- func ClientIP(r *http.Request) string
- func GenerateCeremonyToken() (string, error)
- func ValidateAndHashPassword(ctx context.Context, password, username string, passwordOnly, checkBreach bool, ...) (hash, userMsg string, err error)
- type AuditEvent
- type AuthAdminStore
- type AuthConfig
- type AuthHandlerStore
- type CeremonyStore
- type Handler
- func (h *Handler) HandleAuthMe(w http.ResponseWriter, r *http.Request)
- func (h *Handler) HandleChangePassword(w http.ResponseWriter, r *http.Request)
- func (h *Handler) HandleCreateUser(w http.ResponseWriter, r *http.Request)
- func (h *Handler) HandleDeletePasskey(w http.ResponseWriter, r *http.Request)
- func (h *Handler) HandleDeleteUser(w http.ResponseWriter, r *http.Request)
- func (h *Handler) HandleGenerateAPIKey(w http.ResponseWriter, r *http.Request)
- func (h *Handler) HandleListAPIKeys(w http.ResponseWriter, r *http.Request)
- func (h *Handler) HandleListPasskeys(w http.ResponseWriter, r *http.Request)
- func (h *Handler) HandleListUsers(w http.ResponseWriter, r *http.Request)
- func (h *Handler) HandleLogin(w http.ResponseWriter, r *http.Request)
- func (h *Handler) HandleLogout(w http.ResponseWriter, r *http.Request)
- func (h *Handler) HandleOIDCCallback(w http.ResponseWriter, r *http.Request)
- func (h *Handler) HandleOIDCLink(w http.ResponseWriter, r *http.Request)
- func (h *Handler) HandleOIDCRedirect(w http.ResponseWriter, r *http.Request)
- func (h *Handler) HandleOIDCUnlink(w http.ResponseWriter, r *http.Request)
- func (h *Handler) HandleRenamePasskey(w http.ResponseWriter, r *http.Request)
- func (h *Handler) HandleRevokeAPIKey(w http.ResponseWriter, r *http.Request)
- func (h *Handler) HandleSetupCreate(w http.ResponseWriter, r *http.Request)
- func (h *Handler) HandleSetupStatus(w http.ResponseWriter, r *http.Request)
- func (h *Handler) HandleWebAuthnLoginBegin(w http.ResponseWriter, r *http.Request)
- func (h *Handler) HandleWebAuthnLoginFinish(w http.ResponseWriter, r *http.Request)
- func (h *Handler) HandleWebAuthnRegisterBegin(w http.ResponseWriter, r *http.Request)
- func (h *Handler) HandleWebAuthnRegisterFinish(w http.ResponseWriter, r *http.Request)
- func (h *Handler) HandleWebAuthnSignalData(w http.ResponseWriter, r *http.Request)
- type OIDCStore
- type PendingLink
- type SecurityStore
- type ShardedCeremonyMap
- type WebAuthnLoginBeginResponse
- type WebAuthnRegisterBeginResponse
- type WebAuthnSession
Constants ¶
const ( // CeremonyTTL is the maximum age for pending TOTP and WebAuthn sessions. CeremonyTTL = auth.CeremonyTimeout // MaxCeremonySessions caps the in-memory ceremony maps to prevent OOM // from unauthenticated flooding of /api/auth/login or /api/auth/webauthn/login/begin. MaxCeremonySessions = 10000 // CeremonyShards is the number of shards for ceremony maps. CeremonyShards = 16 // HeaderWebAuthnSession is the HTTP header carrying the WebAuthn session token. HeaderWebAuthnSession = "X-WebAuthn-Session" )
const AuditEventKind = "auth"
AuditEventKind is the fixed attribute value used to mark auth audit records. Filter on `event_kind="auth"` in log queries.
Variables ¶
This section is empty.
Functions ¶
func Audit ¶
func Audit(r *http.Request, level slog.Level, event AuditEvent, success bool, user string, kvs ...any)
Audit emits a structured auth audit record at the specified slog level. Failures should emit at WARN; successes at INFO (so operator dashboards still see failures distinct from routine success traffic while auditors filter the full trail by event_kind).
`user` is the username when known; pass "" for failures on unknown usernames (still useful as the audit record will carry the IP and the failure reason).
Extra attributes are appended verbatim. Use `slog.String("reason", "invalid_password")` or `slog.String("key_id", id)` to keep the structured shape consistent.
func Base64URLEncode ¶
Base64URLEncode encodes bytes as base64url without padding.
func GenerateCeremonyToken ¶
GenerateCeremonyToken generates a random hex token for ephemeral ceremony state.
func ValidateAndHashPassword ¶
func ValidateAndHashPassword(ctx context.Context, password, username string, passwordOnly, checkBreach bool, client *http.Client) (hash, userMsg string, err error)
ValidateAndHashPassword validates password length and context (rejecting passwords that contain the username or app name), checks against breach databases (if checkBreach is true), and returns the Argon2id hash.
Types ¶
type AuditEvent ¶
type AuditEvent string
AuditEvent enumerates the security-relevant events captured in the audit trail. Add new events here when introducing new auth flows.
const ( AuditLoginSuccess AuditEvent = "login.success" AuditLoginFailure AuditEvent = "login.failure" AuditLoginRateLimited AuditEvent = "login.rate_limited" AuditLogout AuditEvent = "logout" AuditPasswordChange AuditEvent = "password.change" AuditPasskeyAdd AuditEvent = "passkey.add" AuditPasskeyDelete AuditEvent = "passkey.delete" AuditPasskeyRename AuditEvent = "passkey.rename" AuditAPIKeyCreate AuditEvent = "apikey.create" AuditAPIKeyRevoke AuditEvent = "apikey.revoke" AuditOIDCCallback AuditEvent = "oidc.callback" )
type AuthAdminStore ¶
type AuthAdminStore interface {
ListUsers(ctx context.Context) ([]api.User, error)
CreateUser(ctx context.Context, user *api.User) error
DeleteUser(ctx context.Context, id int64) error
}
AuthAdminStore is the narrow interface consumed by admin user management handlers.
type AuthConfig ¶
type AuthConfig interface {
BasicAuthEnabled() bool
CheckBreachedPasswords() bool
OIDCEnabled() bool
}
AuthConfig is the narrow interface consumed by auth handlers for configuration access. Mirrors the auth-related subset of api.ConfigProvider.
type AuthHandlerStore ¶
type AuthHandlerStore interface {
GetUserByUsername(ctx context.Context, username string) (*api.User, error)
GetUserByID(ctx context.Context, id int64) (*api.User, error)
UpdateUser(ctx context.Context, user *api.User) error
UserCount(ctx context.Context) (int, error)
CreateUser(ctx context.Context, user *api.User) error
CreateSession(ctx context.Context, sess *api.Session) error
DeleteSession(ctx context.Context, tokenHash string) error
PasskeyCountForUser(ctx context.Context, userID int64) (int, error)
}
AuthHandlerStore is the narrow interface consumed by login, registration, and session creation flows. Documented for discoverability; the Handler struct uses the full authstore.AuthStore directly.
type CeremonyStore ¶
type CeremonyStore struct {
WebAuthn *ShardedCeremonyMap[*WebAuthnSession]
Link *ShardedCeremonyMap[*PendingLink]
}
CeremonyStore holds ephemeral ceremony state for auth flows. Owned by the Server struct to enable per-instance isolation in tests.
func NewCeremonyStore ¶
func NewCeremonyStore() *CeremonyStore
NewCeremonyStore creates a new ceremony store.
func (*CeremonyStore) Cleanup ¶
func (cs *CeremonyStore) Cleanup()
Cleanup removes expired pending TOTP and WebAuthn sessions. Called periodically by the server.
func (*CeremonyStore) ConsumeWebAuthnSession ¶
func (cs *CeremonyStore) ConsumeWebAuthnSession(token string) *webauthn.SessionData
ConsumeWebAuthnSession atomically retrieves and removes a WebAuthn session. Returns nil if the session is missing or expired.
type Handler ¶
type Handler struct {
Store authstore.AuthStore
AdminDB AuthAdminStore
SecDB SecurityStore
OidcDB OIDCStore
RateLimiter ratelimit.Checker
WebAuthn *webauthn.WebAuthn // may be nil
OIDCResolver func() *auth.OIDCProvider
Ceremonies *CeremonyStore
Config func() AuthConfig // returns current config (hot-reloadable)
Configured func() bool // returns whether server has valid config
HTTPClient *http.Client // shared client for outbound requests (HIBP, etc.)
// contains filtered or unexported fields
}
Handler holds all dependencies for the auth handler family. Constructed by the server package and stored on the Server struct.
func (*Handler) HandleAuthMe ¶
func (h *Handler) HandleAuthMe(w http.ResponseWriter, r *http.Request)
func (*Handler) HandleChangePassword ¶
func (h *Handler) HandleChangePassword(w http.ResponseWriter, r *http.Request)
func (*Handler) HandleCreateUser ¶
func (h *Handler) HandleCreateUser(w http.ResponseWriter, r *http.Request)
func (*Handler) HandleDeletePasskey ¶
func (h *Handler) HandleDeletePasskey(w http.ResponseWriter, r *http.Request)
func (*Handler) HandleDeleteUser ¶
func (h *Handler) HandleDeleteUser(w http.ResponseWriter, r *http.Request)
func (*Handler) HandleGenerateAPIKey ¶
func (h *Handler) HandleGenerateAPIKey(w http.ResponseWriter, r *http.Request)
func (*Handler) HandleListAPIKeys ¶
func (h *Handler) HandleListAPIKeys(w http.ResponseWriter, r *http.Request)
func (*Handler) HandleListPasskeys ¶
func (h *Handler) HandleListPasskeys(w http.ResponseWriter, r *http.Request)
func (*Handler) HandleListUsers ¶
func (h *Handler) HandleListUsers(w http.ResponseWriter, r *http.Request)
func (*Handler) HandleLogin ¶
func (h *Handler) HandleLogin(w http.ResponseWriter, r *http.Request)
func (*Handler) HandleLogout ¶
func (h *Handler) HandleLogout(w http.ResponseWriter, r *http.Request)
func (*Handler) HandleOIDCCallback ¶
func (h *Handler) HandleOIDCCallback(w http.ResponseWriter, r *http.Request)
func (*Handler) HandleOIDCLink ¶
func (h *Handler) HandleOIDCLink(w http.ResponseWriter, r *http.Request)
HandleOIDCLink completes link-on-login: the user proves ownership of the existing local account by password, and the pending OIDC identity is linked to it. The link token is single-use and TTL-bounded.
func (*Handler) HandleOIDCRedirect ¶
func (h *Handler) HandleOIDCRedirect(w http.ResponseWriter, r *http.Request)
func (*Handler) HandleOIDCUnlink ¶
func (h *Handler) HandleOIDCUnlink(w http.ResponseWriter, r *http.Request)
HandleOIDCUnlink removes the OIDC binding from the current user's account. It refuses if doing so would leave the account with no way to log in (no password and no passkey), mirroring the disable-password lockout guard.
func (*Handler) HandleRenamePasskey ¶
func (h *Handler) HandleRenamePasskey(w http.ResponseWriter, r *http.Request)
func (*Handler) HandleRevokeAPIKey ¶
func (h *Handler) HandleRevokeAPIKey(w http.ResponseWriter, r *http.Request)
func (*Handler) HandleSetupCreate ¶
func (h *Handler) HandleSetupCreate(w http.ResponseWriter, r *http.Request)
func (*Handler) HandleSetupStatus ¶
func (h *Handler) HandleSetupStatus(w http.ResponseWriter, r *http.Request)
func (*Handler) HandleWebAuthnLoginBegin ¶
func (h *Handler) HandleWebAuthnLoginBegin(w http.ResponseWriter, r *http.Request)
func (*Handler) HandleWebAuthnLoginFinish ¶
func (h *Handler) HandleWebAuthnLoginFinish(w http.ResponseWriter, r *http.Request)
func (*Handler) HandleWebAuthnRegisterBegin ¶
func (h *Handler) HandleWebAuthnRegisterBegin(w http.ResponseWriter, r *http.Request)
func (*Handler) HandleWebAuthnRegisterFinish ¶
func (h *Handler) HandleWebAuthnRegisterFinish(w http.ResponseWriter, r *http.Request)
func (*Handler) HandleWebAuthnSignalData ¶
func (h *Handler) HandleWebAuthnSignalData(w http.ResponseWriter, r *http.Request)
type OIDCStore ¶
type OIDCStore interface {
CreateOIDCState(ctx context.Context, state, nonce, codeVerifier, redirectURI string) error
ConsumeOIDCState(ctx context.Context, state string) (nonce, codeVerifier, redirectURI string, err error)
GetUserByOIDCSub(ctx context.Context, issuer, sub string) (*api.User, error)
GetUserByEmail(ctx context.Context, email string) (*api.User, error)
GetUserByUsername(ctx context.Context, username string) (*api.User, error)
CreateUser(ctx context.Context, user *api.User) error
UpdateUser(ctx context.Context, user *api.User) error
}
OIDCStore is the narrow interface consumed by OIDC authentication handlers.
type PendingLink ¶
PendingLink holds state for an OIDC login that matched an existing local account by username but not by (issuer, sub). The user must prove ownership of the local account with its password before the OIDC identity is linked (link-on-login). Stored under a random token, single-use, TTL-bounded.
type SecurityStore ¶
type SecurityStore interface {
UpdateUser(ctx context.Context, user *api.User) error
DeleteUserSessions(ctx context.Context, userID int64, exceptHash string) error
PasskeyCountForUser(ctx context.Context, userID int64) (int, error)
GetPasskeysByUserID(ctx context.Context, userID int64) ([]api.PasskeyCredential, error)
CreatePasskey(ctx context.Context, cred *api.PasskeyCredential) error
DeletePasskey(ctx context.Context, id, userID int64) error
RenamePasskey(ctx context.Context, id, userID int64, name string) error
CreateAPIKey(ctx context.Context, key *api.Key) error
DeleteAPIKey(ctx context.Context, id, userID int64) error
ListAPIKeysByUserID(ctx context.Context, userID int64) ([]api.Key, error)
}
SecurityStore is the narrow interface consumed by security management handlers.
type ShardedCeremonyMap ¶
type ShardedCeremonyMap[V any] struct { // contains filtered or unexported fields }
ShardedCeremonyMap is a sharded map for ephemeral ceremony state. Sharding reduces lock contention under concurrent auth requests.
func NewShardedCeremonyMap ¶
func NewShardedCeremonyMap[V any]() *ShardedCeremonyMap[V]
NewShardedCeremonyMap creates a new sharded ceremony map.
func (*ShardedCeremonyMap[V]) Cleanup ¶
func (sm *ShardedCeremonyMap[V]) Cleanup(isExpired func(V) bool)
Cleanup removes entries matching the isExpired predicate.
func (*ShardedCeremonyMap[V]) Load ¶
func (sm *ShardedCeremonyMap[V]) Load(key string) (V, bool)
Load retrieves a value from the sharded ceremony map by key without removing it.
func (*ShardedCeremonyMap[V]) LoadAndDelete ¶
func (sm *ShardedCeremonyMap[V]) LoadAndDelete(key string) (V, bool)
LoadAndDelete atomically retrieves and removes a value from the map.
func (*ShardedCeremonyMap[V]) Store ¶
func (sm *ShardedCeremonyMap[V]) Store(key string, val V) bool
Store adds a value to the map. Returns false if the session limit is reached.
type WebAuthnLoginBeginResponse ¶
type WebAuthnLoginBeginResponse struct {
PublicKey *protocol.CredentialAssertion `json:"publicKey"`
SessionToken string `json:"session_token"`
}
WebAuthnLoginBeginResponse wraps WebAuthn assertion options with a session token. Used for login ceremonies.
type WebAuthnRegisterBeginResponse ¶
type WebAuthnRegisterBeginResponse struct {
PublicKey *protocol.CredentialCreation `json:"publicKey"`
SessionToken string `json:"session_token"`
}
WebAuthnRegisterBeginResponse wraps WebAuthn creation options with a session token. Used for passkey registration ceremonies.
type WebAuthnSession ¶
type WebAuthnSession struct {
Data *webauthn.SessionData
CreatedAt time.Time
}
WebAuthnSession holds ephemeral WebAuthn ceremony data.