authhandlers

package
v0.9.0-dev.7 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2026 License: AGPL-3.0 Imports: 25 Imported by: 0

Documentation

Overview

Package authhandlers provides shared types and utilities for the server's authentication handler cluster: login, WebAuthn, OIDC, admin user management, and security management (password change, API keys, passkeys).

Index

Constants

View Source
const CookieNameHTTP = "sfx_session"

CookieNameHTTP is the session cookie's base name, sent as is over plain HTTP; over HTTPS the auth library sends it with the __Host- prefix.

Variables

View Source
var SessionCookie = auth.CookieConfig{
	Posture:               auth.PosturePerRequest,
	Name:                  CookieNameHTTP,
	TrustForwardedHeaders: true,
}

SessionCookie is subflux's session-cookie configuration. Subflux serves both HTTP (LAN, ip:port) and HTTPS (behind a reverse proxy) from a single instance, so PosturePerRequest selects the __Host- name with the Secure flag over HTTPS and CookieNameHTTP without it over plain HTTP, per request. TrustForwardedHeaders honors X-Forwarded-Proto for the HTTPS decision; it is safe only because SanitizeForwardedProto strips that header from any request whose direct peer is not a configured trusted proxy.

Functions

func ClientIP

func ClientIP(r *http.Request) string

ClientIP extracts the client IP address from the request using the current trusted-proxy set. With no trusted proxies configured it returns the unspoofable socket-peer host and ignores X-Forwarded-For; when the direct peer is a trusted proxy it resolves the real client from a trusted X-Forwarded-For chain (spoof-safe, walked right-to-left). It delegates to webhttp.ClientIP, the shared spoof-aware resolver — passing no trusted ranges is byte-identical to the previous unconfigured behavior.

func GenerateCeremonyToken

func GenerateCeremonyToken() (string, error)

GenerateCeremonyToken generates a random hex token for ephemeral ceremony state.

func NewSessionHashContext added in v0.4.0

func NewSessionHashContext(ctx context.Context, sessHash string) context.Context

NewSessionHashContext returns a new context carrying the session token hash for the current request. Only requireAuth populates this; API-key callers have an empty session hash.

func NewUserContext added in v0.4.0

func NewUserContext(ctx context.Context, u *auth.User) context.Context

NewUserContext returns a new context with the given user stored in it.

func SanitizeForwardedProto added in v0.1.148

func SanitizeForwardedProto(next http.Handler) http.Handler

SanitizeForwardedProto strips the X-Forwarded-Proto header from any request whose direct peer is not in the configured trusted-proxy set (the same hot-reloadable set ClientIP consults). A trusted reverse proxy always overwrites the header for the requests it forwards, so the only surviving spoofing path is a direct connection — and for those the header must not influence the per-request cookie posture (a forged "https" over plain LAN HTTP would flip the session cookie to the __Host-/Secure form the browser then refuses to store or send). With no trusted proxies configured the header is stripped from every request: scheme detection falls back to the unspoofable r.TLS, and HTTPS-terminating deployments declare their proxy via trusted_proxies exactly as they already must for client-IP resolution.

func SetTrustedProxies added in v0.1.92

func SetTrustedProxies(nets []*net.IPNet)

SetTrustedProxies replaces the trusted reverse-proxy CIDR set used by ClientIP. Passing nil or an empty slice restores the trust-nothing default. It is safe for concurrent use and the new set takes effect on the next request, so a config hot-reload updates client-IP resolution without a restart.

func UnauthorizedResponse added in v0.1.148

func UnauthorizedResponse(w http.ResponseWriter, r *http.Request)

UnauthorizedResponse writes subflux's unauthorized response: a 302 to /login for browsers and subflux's typed 401 JSON envelope otherwise. Installed on the library Authenticator via auth.WithUnauthorizedResponse so RequireAuth speaks subflux's error vocabulary.

func UserFromContext added in v0.4.0

func UserFromContext(ctx context.Context) *auth.User

UserFromContext extracts the authenticated user from the request context. Returns nil if no user is present.

Types

type APIKeyInfo added in v0.1.148

type APIKeyInfo struct {
	CreatedAt time.Time `json:"created_at"`
	KeyPrefix string    `json:"key_prefix"`
	KeySuffix string    `json:"key_suffix"`
	Label     string    `json:"label"`
	ID        int64     `json:"id"`
}

APIKeyInfo is one entry of the GET /api/auth/apikeys response.

type AccountStore added in v0.4.0

type AccountStore interface {
	CreateSession(ctx context.Context, sess *auth.Session) error
	SessionByHash(ctx context.Context, tokenHash string) (sess *auth.Session, found bool, err error)
	DeleteSession(ctx context.Context, tokenHash string) error
	CreateUser(ctx context.Context, user *auth.User) error
	UserByID(ctx context.Context, id int64) (user *auth.User, found bool, err error)
	UserByUsername(ctx context.Context, username string) (user *auth.User, found bool, err error)
	// UserByWebAuthnHandle resolves the asserting account during a
	// discoverable login: the assertion carries a user handle, not a username.
	UserByWebAuthnHandle(ctx context.Context, handle []byte) (user *auth.User, found bool, err error)
	UpdateUser(ctx context.Context, user *auth.User) error
	ListUsers(ctx context.Context) ([]auth.User, error)
	UserCount(ctx context.Context) (int, error)
	PasskeysByUserID(ctx context.Context, userID int64) ([]auth.PasskeyCredential, error)
	PasskeyCountForUser(ctx context.Context, userID int64) (int, error)
	// AnyPasskeyForDiscoverableLogin reports whether any stored credential
	// could answer a discoverable login for rpID. An unreported
	// discoverability and an unrecorded RP ID both count as usable: nil is
	// what every credential stored before the client forwarded credProps
	// carries.
	AnyPasskeyForDiscoverableLogin(ctx context.Context, rpID string) (bool, error)
	DeletePasskey(ctx context.Context, ref auth.PasskeyRef) error
	// UpdatePasskeyAfterLogin is the post-login credential-custody write the
	// library's CompleteLogin performs through this store.
	UpdatePasskeyAfterLogin(ctx context.Context, credID []byte, signCount uint32, flags auth.PasskeyFlags) error
}

AccountStore is the narrow interface consumed by the account handlers on Handler.Store: the session, user, and passkey-inspection surface the self-service account flows (login, logout, me, password change, OIDC link/unlink) reach for. It is wider than the three role interfaces below because those flows span all three domains; it is still only the methods those flows call.

type AuthAdminStore

type AuthAdminStore interface {
	ListUsers(ctx context.Context) ([]auth.User, error)
	CreateUser(ctx context.Context, user *auth.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
	WebAuthnRPID() string
}

AuthConfig is the authentication half of the configuration, and the only part these handlers read: whether password login is on at all, whether a new password must be checked against the breach corpus, whether OIDC is available as an alternative factor, and the configured relying-party ID the availability probe reports. 4 of the 37 values the config offers.

Exported because the composition root names it: the Config resolver below is how the handlers see a hot-reloaded config, and the root has to write that function's type.

type CeremonyStore

type CeremonyStore struct {
	WebAuthn *shardedCeremonyMap[authwebauthn.Ceremony]
	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 WebAuthn ceremonies and OIDC links. Called periodically by the server.

func (*CeremonyStore) ConsumeWebAuthnSession

func (cs *CeremonyStore) ConsumeWebAuthnSession(token string) (ceremony authwebauthn.Ceremony, found bool)

ConsumeWebAuthnSession atomically retrieves and removes a WebAuthn ceremony. found is false when the token is unknown, already spent, or the ceremony's own deadline has passed.

type Handler

type Handler struct {
	Store       AccountStore
	AdminDB     AuthAdminStore
	SecDB       SecurityStore
	OidcDB      OIDCStore
	RateLimiter ratelimit.Checker
	// WebAuthnResolver resolves the current relying party from the live
	// snapshot per request (may resolve nil: RP ID unset or construction
	// degraded). A direct field would freeze the boot-time instance across
	// hot config edits; the resolver is the same seam OIDCResolver and
	// Config already use.
	WebAuthnResolver func() *authwebauthn.RelyingParty
	OIDCResolver     func() *authoidc.Provider
	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)

HandleAuthMe handles GET /api/auth/me — returns profile information for the current user.

func (*Handler) HandleChangePassword

func (h *Handler) HandleChangePassword(w http.ResponseWriter, r *http.Request)

HandleChangePassword handles PUT /api/auth/password — changes the current user's password after verifying the existing one, then invalidates all other sessions.

func (*Handler) HandleCreateUser

func (h *Handler) HandleCreateUser(w http.ResponseWriter, r *http.Request)

HandleCreateUser handles POST /api/auth/users — creates a new user account.

func (*Handler) HandleDeletePasskey

func (h *Handler) HandleDeletePasskey(w http.ResponseWriter, r *http.Request)

HandleDeletePasskey handles DELETE /api/auth/passkeys/{id} — removes a passkey. Refuses when deleting would leave the account with no authentication method.

func (*Handler) HandleDeleteUser

func (h *Handler) HandleDeleteUser(w http.ResponseWriter, r *http.Request)

HandleDeleteUser handles DELETE /api/auth/users/{id} — deletes a user account. Refuses to delete the caller's own account or the last admin.

func (*Handler) HandleGenerateAPIKey

func (h *Handler) HandleGenerateAPIKey(w http.ResponseWriter, r *http.Request)

HandleGenerateAPIKey handles POST /api/auth/apikeys — generates a new API key for the current user.

func (*Handler) HandleListAPIKeys

func (h *Handler) HandleListAPIKeys(w http.ResponseWriter, r *http.Request)

HandleListAPIKeys handles GET /api/auth/apikeys — lists API keys for the current user.

func (*Handler) HandleListPasskeys

func (h *Handler) HandleListPasskeys(w http.ResponseWriter, r *http.Request)

HandleListPasskeys handles GET /api/auth/passkeys — lists passkeys for the current user.

func (*Handler) HandleListUsers

func (h *Handler) HandleListUsers(w http.ResponseWriter, r *http.Request)

HandleListUsers handles GET /api/auth/users — lists all user accounts.

func (*Handler) HandleLogin

func (h *Handler) HandleLogin(w http.ResponseWriter, r *http.Request)

HandleLogin handles POST /api/auth/login — authenticates with username and password.

func (*Handler) HandleLogout

func (h *Handler) HandleLogout(w http.ResponseWriter, r *http.Request)

HandleLogout handles POST /api/auth/logout — invalidates the current session cookie.

func (*Handler) HandleOIDCCallback

func (h *Handler) HandleOIDCCallback(w http.ResponseWriter, r *http.Request)

HandleOIDCCallback handles GET /api/auth/oidc/callback — completes the OIDC authorization code exchange, resolves or JIT-provisions the user, and creates a session. Redirects to /login.html when a link ceremony is required.

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)

HandleOIDCRedirect handles GET /api/auth/oidc — initiates the OIDC authorization code flow by generating state, nonce, and PKCE and redirecting to the provider.

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)

HandleRenamePasskey handles PUT /api/auth/passkeys/{id} — renames a passkey.

func (*Handler) HandleRevokeAPIKey

func (h *Handler) HandleRevokeAPIKey(w http.ResponseWriter, r *http.Request)

HandleRevokeAPIKey handles DELETE /api/auth/apikeys/{id} — revokes an API key owned by the current user.

func (*Handler) HandleSetupCreate

func (h *Handler) HandleSetupCreate(w http.ResponseWriter, r *http.Request)

HandleSetupCreate handles POST /api/auth/setup — creates the initial admin account. Only succeeds when no users exist; subsequent calls return 409.

func (*Handler) HandleSetupStatus

func (h *Handler) HandleSetupStatus(w http.ResponseWriter, r *http.Request)

HandleSetupStatus handles GET /api/auth/setup — returns whether initial setup is required, and whether a passkey login could succeed here.

func (*Handler) HandleUpdateProfile added in v0.4.35

func (h *Handler) HandleUpdateProfile(w http.ResponseWriter, r *http.Request)

HandleUpdateProfile handles PUT /api/auth/profile — sets the current user's display name.

An empty value clears it, which makes the username the label again. The username itself is deliberately not editable here: it is the login identifier, and every session, passkey and API key is keyed to the account rather than to the name.

The client sends the WebAuthn current-user-details signal after a successful save, so a stored passkey's label follows the account instead of keeping the name it was registered under.

func (*Handler) HandleWebAuthnAvailability added in v0.6.0

func (h *Handler) HandleWebAuthnAvailability(w http.ResponseWriter, r *http.Request)

HandleWebAuthnAvailability handles GET /api/auth/webauthn/availability — reports whether a passkey ceremony could be conducted from the origin named by the required ?origin= parameter. A GET carries no Origin header, and r.Host is wrong behind a Host-rewriting proxy, so the page states its own. The answer is advisory: the authoritative check is at Begin.

func (*Handler) HandleWebAuthnLoginBegin

func (h *Handler) HandleWebAuthnLoginBegin(w http.ResponseWriter, r *http.Request)

HandleWebAuthnLoginBegin handles POST /api/auth/webauthn/login/begin — issues a WebAuthn assertion challenge bound to the request's origin. Supports both standard and conditional (passkey autofill) mediation modes.

func (*Handler) HandleWebAuthnLoginFinish

func (h *Handler) HandleWebAuthnLoginFinish(w http.ResponseWriter, r *http.Request)

HandleWebAuthnLoginFinish handles POST /api/auth/webauthn/login/finish — verifies the assertion response, updates the credential sign count, and creates a session for the authenticated user.

func (*Handler) HandleWebAuthnRegisterBegin

func (h *Handler) HandleWebAuthnRegisterBegin(w http.ResponseWriter, r *http.Request)

HandleWebAuthnRegisterBegin handles POST /api/auth/webauthn/register/begin — initiates passkey registration. Requires password verification before issuing the creation challenge to prevent unauthorized credential provisioning.

func (*Handler) HandleWebAuthnRegisterFinish

func (h *Handler) HandleWebAuthnRegisterFinish(w http.ResponseWriter, r *http.Request)

HandleWebAuthnRegisterFinish handles POST /api/auth/webauthn/register/finish — completes passkey registration, stores the new credential, and emits an audit record.

func (*Handler) HandleWebAuthnSignalData

func (h *Handler) HandleWebAuthnSignalData(w http.ResponseWriter, r *http.Request)

HandleWebAuthnSignalData handles GET /api/auth/webauthn/signal-data — returns the WebAuthn signal data needed by the browser for credential management.

type OIDCStore

type OIDCStore interface {
	CreateOIDCState(ctx context.Context, state auth.OIDCState, nonce auth.OIDCNonce, codeVerifier auth.OIDCCodeVerifier, redirectURI string) error
	ConsumeOIDCState(ctx context.Context, state auth.OIDCState) (nonce auth.OIDCNonce, codeVerifier auth.OIDCCodeVerifier, redirectURI string, err error)
	UserByOIDCSub(ctx context.Context, issuer, sub string) (user *auth.User, found bool, err error)
	UserByUsername(ctx context.Context, username string) (user *auth.User, found bool, err error)
	CreateUser(ctx context.Context, user *auth.User) error
}

OIDCStore is the narrow interface consumed by OIDC authentication handlers: the login/callback leg (state custody plus the identity lookups that resolve or create the user). The link/unlink leg needs the wider account surface (UserByID, ListUsers, passkey inspection) and goes through Handler.Store.

type PasskeyInfo added in v0.1.148

type PasskeyInfo struct {
	CreatedAt      time.Time `json:"created_at"`
	Name           string    `json:"name"`
	Transport      string    `json:"transport,omitempty"`
	ID             int64     `json:"id"`
	BackupEligible bool      `json:"backup_eligible"`
}

PasskeyInfo is one entry of the GET /api/auth/passkeys response.

type PendingLink struct {
	CreatedAt  time.Time
	OIDCSub    string
	OIDCIssuer string
	UserID     int64
}

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 *auth.User) error
	DeleteUserSessions(ctx context.Context, userID int64, exceptHash string) error
	PasskeyCountForUser(ctx context.Context, userID int64) (int, error)
	PasskeysByUserID(ctx context.Context, userID int64) ([]auth.PasskeyCredential, error)
	CreatePasskey(ctx context.Context, cred *auth.PasskeyCredential) error
	DeletePasskey(ctx context.Context, ref auth.PasskeyRef) error
	RenamePasskey(ctx context.Context, ref auth.PasskeyRef, name string) error
	CreateAPIKey(ctx context.Context, key *auth.Key) error
	DeleteAPIKey(ctx context.Context, ref auth.KeyRef) error
	ListAPIKeysByUserID(ctx context.Context, userID int64) ([]auth.Key, error)
}

SecurityStore is the narrow interface consumed by security management handlers.

type UserInfo added in v0.1.148

type UserInfo struct {
	CreatedAt time.Time `json:"created_at"`
	Username  string    `json:"username"`
	Email     string    `json:"email"`
	Role      auth.Role `json:"role"`
	ID        int64     `json:"id"`
	Enabled   bool      `json:"enabled"`
}

UserInfo is one entry of the GET /api/auth/users response.

type WebAuthnLoginBeginResponse

type WebAuthnLoginBeginResponse struct {
	PublicKey    *authwebauthn.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    *authwebauthn.CredentialCreation `json:"publicKey"`
	SessionToken string                           `json:"session_token"`
}

WebAuthnRegisterBeginResponse wraps WebAuthn creation options with a session token. Used for passkey registration ceremonies.

Jump to

Keyboard shortcuts

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