auth

package module
v5.0.9 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2026 License: Apache-2.0 Imports: 23 Imported by: 0

README

auth

Go Reference Go version Test coverage Mutation OpenSSF Best Practices OpenSSF Scorecard

Go authentication library: Argon2id passwords, WebAuthn/passkeys, OIDC, sessions, API keys, and RBAC.

A standalone Go authentication library providing password hashing (Argon2id with OWASP parameters), WebAuthn/FIDO2 passkey ceremonies, OIDC provider integration with PKCE, session management with idle/absolute timeouts, API key generation and verification, CSRF token helpers, password-reset/email-verification token primitives, and role-based access control helpers.

Dependencies: golang.org/x/crypto, golang.org/x/oauth2, golang.org/x/text, github.com/go-webauthn/webauthn, github.com/coreos/go-oidc/v3.

Note: HTTP handlers are app-specific and intentionally not included. Build your own HTTP layer on the exported primitives.

Install

go get github.com/cplieger/auth/v5@latest

Usage

package main

import (
	"log"
	"net/http"
	"time"

	"github.com/cplieger/auth/v5"
)

func main() {
	// Hash a password (package-level with OWASP defaults)
	hash := auth.HashPassword("my-secure-password")

	// Verify
	ok, _ := auth.VerifyPassword("my-secure-password", hash)
	_ = ok

	// Or use a configurable Hasher with custom params and optional pepper
	hasher, _ := auth.NewHasher(auth.Argon2Params{
		Memory: 65536, Iterations: 3, Parallelism: 2,
		SaltLength: 16, KeyLength: 32,
	}, auth.WithPepper([]byte("my-secret-pepper")))
	hash2 := hasher.Hash("my-secure-password")
	ok2, _ := hasher.Verify("my-secure-password", hash2)
	_, _ = hash2, ok2

	// Set up authenticator with your store implementation (functional options).
	// auth.New returns an error if the configuration is unusable (e.g. a
	// __Host- cookie posture combined with a Domain or a non-root Path).
	authenticator, err := auth.New(
		myStore, // implements auth.AuthenticatorStore
		auth.WithIdleTimeout(1*time.Hour),
		auth.WithAbsTimeout(24*time.Hour),
		auth.WithLoginPath("/login"),
		auth.WithCookie(auth.DefaultCookieConfig()),
	)
	if err != nil {
		log.Fatalf("auth: %v", err)
	}

	// Use in HTTP handler
	http.HandleFunc("/api/protected", func(w http.ResponseWriter, r *http.Request) {
		user, _, ok := authenticator.RequireAuth(w, r)
		if !ok {
			return
		}
		_ = user
	})
}

Configuration

All configuration is via functional options and function parameters. The library has no import-time side effects, no environment reads, and no global state.

  • WithLogger(l): optional *slog.Logger; if nil, uses slog.Default()
  • WithLoginPath(path): redirect path for unauthenticated browser requests (default: "/login")
  • WithCookie(cfg): configurable cookie Name, Posture, Path, SameSite, Domain, TrustForwardedHeaders (see CookieConfig)
  • WithIdleTimeout(d): session idle timeout (default: 1h)
  • WithAbsTimeout(d): session absolute timeout (default: 24h)
  • WithBypass(fn): development bypass hook (synthetic admin user); a production-safety warning fires once, on the first request the hook actually grants
  • WithVerifiers(vs []CredentialVerifier): replace the default verifier chain (SessionVerifier + APIKeyVerifier) with your own
  • WithActivityThrottle(d time.Duration): call UpdateSessionActivity at most once per d per session instead of on every request (default 0: write on every request). d must be less than the idle timeout or construction returns an error, since the persisted last-activity lags by up to d.
  • WithUnauthorizedResponse(fn): replace RequireAuth's default unauthorized response (302 to the login path for browsers, 401 JSON otherwise) with your own writer. The hook owns both branches; call IsBrowserRequest inside it to keep a redirect path.
  • WithTimeoutSource(fn): resolve the idle/absolute session timeouts per verification from a callback (for hot-reloadable config). Non-positive callback values fall back to the static options; the activity throttle is clamped to half the resolved idle timeout so a shrunken idle cannot expire active sessions.
  • NewHasher(params, ...HasherOption): configurable Argon2id parameters; use WithPepper([]byte) for HMAC peppering
  • GenerateAPIKey(prefix): pass your key prefix (e.g. "ak_")
  • ValidatePasswordContext(password, PasswordContext{Username, ForbiddenWords}): pass app-specific forbidden words
cfg := auth.CookieConfig{
    Name:     "my_session",          // base name (default: "auth_session")
    Posture:  auth.PostureSecure,    // __Host- + Secure (default); see CookiePosture table below
    Path:     "/",                   // cookie path (default: "/")
    Domain:   "",                    // cookie domain (default: unset; must stay unset under a __Host- posture)
    SameSite: http.SameSiteLaxMode,  // (default: Lax)
    // TrustForwardedHeaders: true,  // only behind a proxy that always sets X-Forwarded-Proto
}
authenticator, err := auth.New(myStore, auth.WithCookie(cfg))
if err != nil {
    log.Fatalf("auth: %v", err) // cfg rejected: see CookieConfig.Validate
}
CookiePosture

CookiePosture controls the cookie name prefix and Secure flag strategy:

Value Behavior
(default) Static __Host- prefix when Secure is true/auto-HTTPS
PosturePerRequest Selects the cookie name and Secure flag at request time: HTTPS requests get __Host-+base+Secure; plain HTTP gets the bare base name without the Secure flag. Respects TrustForwardedHeaders for X-Forwarded-Proto detection.

PosturePerRequest suits services that accept both HTTP and HTTPS traffic, such as a load balancer that terminates TLS for some paths but not others.

API

Grouped summary of the exported surface. Signatures and full semantics live in the Go Reference.

  • Password hashing: HashPassword / VerifyPassword / NeedsRehash (Argon2id PHC strings, OWASP defaults; HashPassword and Hasher.Hash return no error), DummyHash (constant-time timing equalization for unknown-user logins), DefaultArgon2Params, NewHasher + WithPepper (custom parameters, HMAC pepper), Hasher.Hash / Hasher.Verify / Hasher.NeedsRehash, ValidateMultiFactorPasswordLength / ValidateSoloPasswordLength (NIST, max 128; the solo variant applies the stricter minimum for accounts where password login is the sole factor), ValidatePasswordContext, CheckBreachedPassword (HIBP k-anonymity).
  • Username identity: NormalizeUsername decides whether two logins are the same account, using the UsernameCaseMapped profile of the PRECIS IdentifierClass (RFC 8265). It folds case across the whole of Unicode rather than ASCII only, does not transliterate (straße and strasse stay distinct), and rejects a username containing a space. Apply it on both sides of the comparison: to the unique-index key, and to the login input before the lookup.
  • Sessions and tokens: GenerateSessionToken (256-bit; returns no error, like RotateSessionToken, GenerateAPIKey, GenerateOpaqueToken, oidc.GenerateState and oidc.GeneratePKCE), RotateSessionToken, ValidateSession (takes a SessionTimeouts{Idle, Absolute} pair), SessionHash, HexSHA256, CSRFToken / VerifyCSRFToken (bound to the session hash), GenerateOpaqueToken / VerifyOpaqueToken (password reset, email verification).
  • Cookies: DefaultCookieConfig, then CookieConfig.CookieName / SetCookie / ReadCookie / ClearCookie. Declare the config your deployment needs rather than relying on a package default, so the posture is visible at the call site.
  • API keys: GenerateAPIKey, VerifyAPIKey (constant-time hash equality plus expiry check), APIKeyHash.
  • Middleware and guards: New and NewSessionVerifier (both return an error on an unusable config; see CookieConfig.Validate), NewAPIKeyVerifier (reads the X-Api-Key header only, never a URL query parameter, per CWE-598), Authenticator.Authenticate / Authenticator.RequireAuth, HasRole (flat RBAC), ValidateRedirectURI (relative paths only), CanDisableMethod (takes a MethodAvailability struct), IsBrowserRequest. The WithVerifiers / WithActivityThrottle / WithUnauthorizedResponse / WithTimeoutSource options are described under Configuration.
  • Interfaces: CredentialVerifier (pluggable credential verification), AuthenticatorStore (the composed read surface New takes: session, user and API-key lookup), webauthn.Store (consumer-implemented storage), and the persistence-SPI role interfaces UserStore / SessionPersister / PasskeyStore / KeyStore / OIDCStateStore. Implement the roles your handler layer needs. A by-key lookup returns a value the caller owns, so an in-memory or caching store must return a copy; a SQL-backed store satisfies this for free.
    • Two lookups carry rules a store must follow, both stated in store_contract.go: UserByUsername is keyed on NormalizeUsername applied to BOTH the index and the login input, and UserByWebAuthnHandle resolves the opaque handle a discoverable login arrives with, answering the same way for an unknown handle and a malformed one so it cannot be used to probe which accounts exist.
  • WebAuthn (github.com/cplieger/auth/v5/webauthn): no go-webauthn type appears on this package's exported surface, so a consumer runs a ceremony without importing it. New takes an RPConfig{ID, DisplayName, Origins} and returns a *RelyingParty (ID() reports the relying-party identifier); NewUser; BeginRegistration / FinishRegistration / BeginLogin / BeginConditionalLogin (conditional mediation, autofill UI) / CompleteLogin (store-backed login completion; the caller keeps account-status policy and session creation).
    • The Begin* calls return a Ceremony, an opaque handle a consumer holds between the two halves of a ceremony and evicts on Ceremony.Expires(), plus first-party CredentialCreation / CredentialAssertion options that restate the WebAuthn §5.4 and §5.5 dictionaries and serialize exactly as the browser expects.
    • FinishRegistration returns an auth.PasskeyCredential ready to store; set its Name from PasskeyFriendlyName first, which derives a name from the AAGUID against the user's existing passkey names.
    • Registration requires a discoverable credential with user verification, and offers the ML-DSA post-quantum algorithms ahead of EdDSA, ES256 and RS256, so an authenticator that implements one produces a post-quantum credential. ErrNotDiscoverable reports a credential the client says is not discoverable, because only a discoverable credential can complete BeginLogin; ErrUnknownCredential reports a login by a passkey deleted server-side, translated rather than wrapped so the upstream error type is not reachable.
    • NewSignals(rpID, user) derives the WebAuthn Signal API payloads a client sends to keep a credential manager's passkey list in step with the server. An empty accepted-credential list is meaningful — it tells the credential manager to remove every passkey for the account — so it always serializes as [].
  • OIDC (github.com/cplieger/auth/v5/oidc): NewProvider and ValidateConfig (both take an oidc.Config), GenerateState, GeneratePKCE (S256; both mint their results as the distinct types below), Provider.AuthorizationURL and Provider.Exchange (distinct State / Nonce / CodeChallenge / Code / CodeVerifier string types keep the opaque randoms from being transposed; State, Nonce, and CodeVerifier are aliases of the root auth.OIDCState / auth.OIDCNonce / auth.OIDCCodeVerifier types used by the OIDCStateStore SPI. AuthorizationURL rejects an empty state or code challenge and Exchange rejects an empty or mismatched nonce, both failing closed with descriptive errors, and a nonce mismatch reports ErrNonceMismatch), ResolveUser (maps an OIDC identity by issuer and subject to a user; ErrNoUsername when the token carries neither preferred_username nor email).

Subpackages

auth/ratelimit

Dual sliding-window per-IP + per-account authentication brute-force rate limiter (OWASP ASVS 2.2.1). Standard library only (context, log/slog, sync, time). The two dimension keys are distinct types (ratelimit.ClientIP, ratelimit.Username) so they cannot be transposed silently.

rl := ratelimit.New(ctx, ratelimit.DefaultConfig())
defer func() {
    // Bound the wait so a wedged prune goroutine surfaces as an error
    // instead of hanging process shutdown.
    sctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    if err := rl.Shutdown(sctx); err != nil {
        log.Printf("ratelimit shutdown: %v", err)
    }
}()
ip, user := ratelimit.ClientIP(clientIP), ratelimit.Username(username)
if allowed, retryAfter := rl.Allow(ip, user); !allowed {
    // reject; retry after retryAfter
}
// On each FAILED login attempt, record it so it counts toward the limit:
rl.Record(ip, user)
// On successful login, clear the failure counters:
rl.Reset(ip, user)
auth/authtest

Exported in-memory AuthenticatorStore implementation for consumer tests. Every read returns a fresh copy.

store := authtest.NewMemStore()
store.AddUser(&auth.User{Username: "test", Role: auth.RoleUser, Enabled: true})

Unsupported by Design

The following features are intentionally out of scope.

Feature Rationale
Full OIDC token-refresh orchestration Library handles authentication, not long-lived API access. Consumer uses oauth2.TokenSource.
Multi-provider OIDC registry Consumer instantiates multiple OIDCProvider instances.
WebAuthn MDS verification Not supported: the ceremony functions own the RP configuration. See the note below.
OIDC back-channel logout Enterprise SSO feature beyond scope of auth-primitive library.
Hierarchical RBAC / permission sets Library provides HasRole for flat role check. Use casbin/ory-keto for complex RBAC.
Cookie encryption/signing Opaque-token architecture; cookie value is a random token, not sensitive data.
OIDC userinfo endpoint ID token claims sufficient for authentication. Consumer can call provider.UserInfo().
WebAuthn attestation conveyance Default none is correct for most RPs per FIDO Alliance guidance.
WebAuthn credential filtering (AAGUID) Not supported: the ceremony functions own the RP configuration. See the note below.
Passkey well-known endpoints Browser/credential-manager concern, not server-auth-library concern.
CSRF middleware (full HTTP layer) Library provides CSRFToken/VerifyCSRFToken primitives; full middleware is HTTP-framework-specific.

On the two WebAuthn authenticator-policy rows. Both are enforceable only where this library is the relying party, and a deployment that wants either one runs an identity provider — which then becomes the relying party and applies the policy itself, needing nothing from here. So there is no injection path and no plan for one: New owns the relying-party configuration deliberately, because a hole there is a hole in the type boundary the WebAuthn API section describes.

Nothing is lost that a later release cannot supply. The credential record persists the raw attestation and the AAGUID, so if a consumer ever is the sole identity authority for an organisation with an authenticator mandate, the answer is first-party RPConfig fields plus attestation conveyance — additive, and decided then. Note that AAGUID filtering also needs that conveyance to work at all: the AAGUID arrives unaltered only under direct or enterprise, and is stripped under the none default above.

Contributing

Issues and PRs are welcome. See CONTRIBUTING.md for the conventions and how to run the checks locally.

Disclaimer

This project is built with care and follows security best practices, but it is intended for personal / self-hosted use. No guarantees of fitness for production environments. Use at your own risk.

This project was built with AI-assisted tooling using Claude, GPT, and Kiro. The human maintainer defines architecture, supervises implementation, and makes all final decisions.

License

Apache-2.0. See LICENSE.

Documentation

Overview

Package auth implements authentication primitives: password hashing (Argon2id in PHC string format), WebAuthn/FIDO2 passkey ceremonies, OIDC provider integration with PKCE, session management with idle/absolute timeouts, API key generation and verification, and role-based access control helpers.

Index

Examples

Constants

View Source
const (
	DefaultIdleTimeout = 1 * time.Hour
	DefaultAbsTimeout  = 24 * time.Hour
)

Default session timeout values matching the pre-refactor struct-field defaults.

View Source
const HeaderXAPIKey = "X-Api-Key" //nolint:gosec // G101 false positive: header name, not a credential

HeaderXAPIKey is the HTTP header carrying the API key. Keys are accepted only via this header, never a URL query parameter; a query-string key leaks into access logs, browser history, and the Referer header (CWE-598).

View Source
const PasswordMaxLength = 128

PasswordMaxLength is the maximum password length to prevent DoS via extremely long inputs to Argon2id (OWASP recommendation).

View Source
const PasswordMinLengthMultiFactor = 8

PasswordMinLengthMultiFactor is the minimum password length when password login is not the sole sufficient factor.

View Source
const PasswordMinLengthSolo = 15

PasswordMinLengthSolo is the minimum password length when password login is enabled and thus a sole sufficient factor.

View Source
const WebAuthnHandleSize = 64

WebAuthnHandleSize is the length of a generated user handle. WebAuthn caps a user handle at 64 bytes and §14.6.1 recommends using all of them, randomly.

Variables

View Source
var (
	ErrSessionExpired  = errors.New("session expired")
	ErrSessionNotFound = errors.New("session not found")
)

Sentinel errors for session operations.

View Source
var (
	ErrTokenExpired = errors.New("auth: token expired")
	ErrTokenInvalid = errors.New("auth: token invalid")
)

Token errors.

View Source
var (
	// ErrUsernameEmpty reports that the username is empty, or normalized to
	// empty. RFC 8265 §3.1 requires a non-empty result; see [NormalizeUsername]
	// for why this library enforces that itself.
	ErrUsernameEmpty = errors.New("username must not be empty")

	// ErrUsernameInvalid reports that the username contains a code point the
	// PRECIS IdentifierClass disallows. The wrapped error carries the detail
	// from golang.org/x/text and is not part of this library's contract.
	ErrUsernameInvalid = errors.New("username contains a disallowed character")
)

Sentinel errors returned by NormalizeUsername.

View Source
var ErrInvalidAPIKey = errors.New("invalid API key")

ErrInvalidAPIKey is returned when an API key cannot be verified.

View Source
var ErrUnauthenticated = errors.New("unauthenticated")

ErrUnauthenticated is returned when no valid credential is found.

Functions

func APIKeyHash

func APIKeyHash(key string) string

APIKeyHash returns the hex-encoded SHA-256 hash of a key string.

func CSRFToken

func CSRFToken(key []byte, sessionHash string) (string, error)

CSRFToken generates a CSRF token bound to the given session hash using HMAC-SHA256 with a random 16-byte nonce per OWASP signed double-submit. Format: base64url(nonce[16] ∥ issuedAt[8] ∥ HMAC-SHA256(key, nonce ∥ sessionHash ∥ issuedAt))

func CanDisableMethod

func CanDisableMethod(method Method, avail MethodAvailability) bool

CanDisableMethod checks whether disabling the given auth method would leave the user with no viable authentication method.

func CheckBreachedPassword

func CheckBreachedPassword(ctx context.Context, client *http.Client, password string) (bool, error)

CheckBreachedPassword checks a password against the Have I Been Pwned Passwords API using k-anonymity. Returns true if the password has been found in a breach.

func DummyHash

func DummyHash() string

DummyHash returns a pre-computed Argon2id hash used by the login handler to equalize timing when the username doesn't exist (H2 mitigation). The hash is computed lazily on first call.

func GenerateAPIKey

func GenerateAPIKey(keyPrefix string) (plaintext, hash, displayPrefix, displaySuffix string)

GenerateAPIKey generates a new API key with 256 bits of entropy. The keyPrefix is prepended to the random hex string (e.g. "ak_"). It returns the plaintext key, its SHA-256 hash, a display prefix (first 8 chars), and a display suffix (last 4 chars). It cannot fail; see [generateRandomHex].

Example
package main

import (
	"fmt"

	"github.com/cplieger/auth/v5"
)

func main() {
	plaintext, hash, prefix, suffix := auth.GenerateAPIKey("ak_")
	fmt.Println(plaintext[:3], len(hash) == 64, len(prefix) == 8, len(suffix) == 4)
}
Output:
ak_ true true true

func GenerateOpaqueToken

func GenerateOpaqueToken() (plaintext, hash string)

GenerateOpaqueToken generates a cryptographically random opaque token suitable for password-reset or email-verification flows. Returns the plaintext token (to send to the user) and its SHA-256 hash (to store in the database). It cannot fail; see [generateRandomHex].

func GenerateSessionToken

func GenerateSessionToken() (plaintext, hash string)

GenerateSessionToken generates a cryptographically random session token (256 bits / 32 bytes). It returns the hex-encoded plaintext token and its SHA-256 hash (also hex-encoded). It cannot fail; see [generateRandomHex].

Example
package main

import (
	"fmt"

	"github.com/cplieger/auth/v5"
)

func main() {
	plaintext, hash := auth.GenerateSessionToken()
	fmt.Println(len(plaintext) == 64, len(hash) == 64, plaintext != hash)
}
Output:
true true true

func GenerateWebAuthnHandle

func GenerateWebAuthnHandle() []byte

GenerateWebAuthnHandle returns a new WebAuthn user handle: 64 random bytes, as WebAuthn §14.6.1 recommends.

The handle identifies an account to an authenticator, and an authenticator may reveal it without verifying the user first, so it must carry no information about who the account belongs to. That rules out a username, an email address, and any unsalted hash of one — and it also rules out a sequential database identifier, which is not personally identifying but does leak how many accounts the relying party has and in what order they were created.

Store the result on the account (see auth.User.WebAuthnHandle). The specification says to store it rather than derive it for a practical reason: a derived handle cannot be changed without invalidating every credential registered under the old derivation.

It cannot fail; see [generateRandomHex] for why a randomness failure is not a reportable error in this library.

func HasRole

func HasRole(user *User, role Role) bool

HasRole reports whether the user is authorized for the given role.

Example
package main

import (
	"fmt"

	"github.com/cplieger/auth/v5"
)

func main() {
	admin := &auth.User{Role: auth.RoleAdmin}
	user := &auth.User{Role: auth.RoleUser}
	fmt.Println(auth.HasRole(admin, auth.RoleUser))
	fmt.Println(auth.HasRole(user, auth.RoleAdmin))
}
Output:
true
false

func HashPassword

func HashPassword(password string) string

HashPassword hashes a password using Argon2id with OWASP parameters. Returns the hash in PHC string format: $argon2id$v=19$m=19456,t=2,p=1$<base64-salt>$<base64-hash> It cannot fail; see Hasher.Hash.

Example
package main

import (
	"fmt"

	"github.com/cplieger/auth/v5"
)

func main() {
	hash := auth.HashPassword("my-secure-password")
	ok, err := auth.VerifyPassword("my-secure-password", hash)
	if err != nil {
		panic(err)
	}
	fmt.Println(ok)
}
Output:
true

func HexSHA256

func HexSHA256(s string) string

HexSHA256 returns the hex-encoded SHA-256 hash of s.

func IsBrowserRequest

func IsBrowserRequest(r *http.Request) bool

IsBrowserRequest returns true if the request appears to be from a browser (Accept header contains text/html and no X-API-Key header).

func NeedsRehash

func NeedsRehash(encodedHash string) bool

NeedsRehash reports whether the encoded hash was produced with parameters different from the current OWASP-recommended defaults. Returns true if the hash is invalid or uses outdated parameters.

func NormalizeUsername

func NormalizeUsername(username string) (string, error)

NormalizeUsername returns the canonical form of a username: two names that normalize to the same string identify the same account, and two that do not are different accounts. A consumer's storage layer applies it to build the unique-username index key, and applies it again to the login input before the lookup, so the comparison happens on canonical forms at both ends.

The rule is the UsernameCaseMapped profile of the PRECIS IdentifierClass (RFC 8265 §3.3), which case-folds and applies Unicode normalization. Two consequences a caller should know, because neither matches a naive ASCII-lowercasing rule:

  • Case folding covers the whole of Unicode, so "Müller" and "MÜLLER" are one account. It is not a transliteration: "straße" does not fold to "strasse", so those remain two accounts.
  • The IdentifierClass disallows spaces, so "alex muller" is rejected rather than normalized. Dots, hyphens and underscores are allowed.

It returns ErrUsernameEmpty for an empty result and ErrUsernameInvalid, wrapping the underlying cause, for anything the profile refuses. The empty check is this library's own: RFC 8265 §3.1 requires a non-empty result, but precis.UsernameCaseMapped accepts the empty string (see https://github.com/golang/go/issues/64531), so the standard does not arrive complete from golang.org/x/text. Checking the result rather than the input covers both that case and any input the profile's mapping steps reduce to nothing.

func RotateSessionToken

func RotateSessionToken(oldPlaintext string) (newPlaintext, newHash, oldHash string)

RotateSessionToken generates a new session token, returning the new plaintext, new hash, and old hash. The caller is responsible for atomically replacing the session record in the store (delete old hash, insert new hash with same session data). It cannot fail; see GenerateSessionToken.

func SessionHash

func SessionHash(token string) string

SessionHash returns the hex-encoded SHA-256 hash of a plaintext token.

func ValidateMultiFactorPasswordLength

func ValidateMultiFactorPasswordLength(password string) error

ValidateMultiFactorPasswordLength enforces minimum and maximum password length for an account where the password is NOT the sole sufficient factor (minimum PasswordMinLengthMultiFactor). Use ValidateSoloPasswordLength when password login alone grants access.

Example
package main

import (
	"fmt"

	"github.com/cplieger/auth/v5"
)

func main() {
	// Multi-factor arm: password login is not the sole factor, minimum 8.
	err := auth.ValidateMultiFactorPasswordLength("okpass8!")
	fmt.Println(err == nil)
}
Output:
true

func ValidatePasswordContext

func ValidatePasswordContext(password string, pctx PasswordContext) error

ValidatePasswordContext rejects passwords that trivially embed the username or any of the forbidden words in pctx.

func ValidateRedirectURI

func ValidateRedirectURI(uri string) string

ValidateRedirectURI ensures the URI is a safe relative path.

Example
package main

import (
	"fmt"

	"github.com/cplieger/auth/v5"
)

func main() {
	fmt.Println(auth.ValidateRedirectURI("/dashboard"))
	fmt.Println(auth.ValidateRedirectURI("https://evil.com"))
}
Output:
/dashboard
/

func ValidateSession

func ValidateSession(sess *Session, timeouts SessionTimeouts, now time.Time) error

ValidateSession checks whether a session is still valid given the idle and absolute timeouts.

func ValidateSoloPasswordLength

func ValidateSoloPasswordLength(password string) error

ValidateSoloPasswordLength enforces minimum and maximum password length for an account where password login is enabled and thus a sole sufficient factor (minimum PasswordMinLengthSolo).

Example
package main

import (
	"fmt"

	"github.com/cplieger/auth/v5"
)

func main() {
	// Solo arm: password login alone grants access, minimum 15.
	err := auth.ValidateSoloPasswordLength("short")
	fmt.Println(err != nil)
}
Output:
true

func VerifyCSRFToken

func VerifyCSRFToken(key []byte, sessionHash, token string, maxAge time.Duration) error

VerifyCSRFToken verifies a CSRF token against the session hash and checks that it has not expired (maxAge duration from creation).

func VerifyOpaqueToken

func VerifyOpaqueToken(plaintext, storedHash string, expiresAt time.Time) error

VerifyOpaqueToken checks that the plaintext token matches the stored hash and that the token has not expired. Returns nil on success.

func VerifyPassword

func VerifyPassword(password, encodedHash string) (bool, error)

VerifyPassword verifies a password against an encoded Argon2id hash in PHC string format. Uses constant-time comparison.

Types

type APIKeyReader

type APIKeyReader interface {
	APIKeyByHash(ctx context.Context, hash string) (key *Key, found bool, err error)
}

APIKeyReader validates API keys (looked up by hash).

type APIKeyVerifier

type APIKeyVerifier struct {
	// contains filtered or unexported fields
}

APIKeyVerifier authenticates requests via the X-API-Key header. Create with NewAPIKeyVerifier.

func NewAPIKeyVerifier

func NewAPIKeyVerifier(store APIKeyVerifierStore, opts ...Option) *APIKeyVerifier

NewAPIKeyVerifier creates an APIKeyVerifier with the given store and options. Of the shared Option set it consults only WithLogger; every other option (cookie, timeouts, throttle, bypass, hooks) configures session or authenticator behavior this verifier does not have and is silently ignored.

func (*APIKeyVerifier) Verify

func (v *APIKeyVerifier) Verify(ctx context.Context, r *http.Request) (*User, string, error)

Verify checks the X-API-Key header and returns the user if the key is valid. API keys are accepted only via the header, never via a URL query parameter; a key in a query string leaks into access logs, browser history, and the Referer header (CWE-598).

type APIKeyVerifierStore

type APIKeyVerifierStore interface {
	APIKeyReader
	UserReader
}

APIKeyVerifierStore is the minimal interface for API key verification.

type Argon2Params

type Argon2Params struct {
	// Memory in KiB. Default: 19456 (19 MiB, OWASP recommendation #2).
	Memory uint32
	// Iterations (time cost). Default: 2.
	Iterations uint32
	// Parallelism (threads). Default: 1.
	Parallelism uint8
	// SaltLength in bytes. Default: 16.
	SaltLength uint32
	// KeyLength in bytes. Default: 32.
	KeyLength uint32
}

Argon2Params describes the Argon2id parameters for password hashing.

func DefaultArgon2Params

func DefaultArgon2Params() Argon2Params

DefaultArgon2Params returns the OWASP-recommended Argon2id parameters.

func (Argon2Params) Validate

func (p Argon2Params) Validate() error

Validate checks that the params are within safe bounds.

type Authenticator

type Authenticator struct {
	// contains filtered or unexported fields
}

Authenticator resolves an HTTP request to an authenticated user. Create with New.

func New

func New(store AuthenticatorStore, opts ...Option) (*Authenticator, error)

New creates an Authenticator with the given store and options. The store must implement SessionReader, UserReader, and APIKeyReader. It returns an error when the assembled configuration is unusable (see CookieConfig.Validate and WithActivityThrottle). If no idle/absolute timeout is provided, defaults of 1h and 24h are applied.

func (*Authenticator) Authenticate

func (a *Authenticator) Authenticate(r *http.Request) (*User, string, error)

Authenticate resolves the request to a user by running the credential verifier chain in order. The default chain checks the session cookie first, then the API key (accepted only via the X-Api-Key header, never a URL query parameter -- CWE-598). It returns the user and session hash, or ErrUnauthenticated when no verifier authenticates the request.

Every returned *User is the caller's to keep: on the bypass path it is a fresh copy of the synthetic admin, and on the credential paths it is whatever the store returned.

func (*Authenticator) RequireAuth

func (a *Authenticator) RequireAuth(w http.ResponseWriter, r *http.Request) (*User, string, bool)

RequireAuth checks authentication and returns the user. If not authenticated, it writes the appropriate response and returns ok=false. The default response is a 302 redirect to the login path for browser requests and a 401 JSON envelope otherwise; a hook installed via WithUnauthorizedResponse replaces both branches.

Example
package main

import (
	"fmt"
	"time"

	"github.com/cplieger/auth/v5"
	"github.com/cplieger/auth/v5/authtest"
)

func main() {
	store := authtest.NewMemStore()
	store.AddUser(&auth.User{
		Username: "alice",
		Role:     auth.RoleAdmin,
		Enabled:  true,
	})

	authn, err := auth.New(
		store,
		auth.WithIdleTimeout(1*time.Hour),
		auth.WithAbsTimeout(24*time.Hour),
	)
	if err != nil {
		panic(err)
	}
	_ = authn
	fmt.Println("authenticator configured")
}
Output:
authenticator configured

type AuthenticatorAttachment

type AuthenticatorAttachment string

AuthenticatorAttachment reports how the authenticator that created a credential is attached to the client device.

const (
	AttachmentPlatform      AuthenticatorAttachment = "platform"
	AttachmentCrossPlatform AuthenticatorAttachment = "cross-platform"
)

The attachment modalities defined by WebAuthn §5.4.5. The zero value means the client did not report one, which is legal.

type AuthenticatorStore

type AuthenticatorStore interface {
	SessionReader
	SessionActivityUpdater
	UserReader
	APIKeyReader
}

AuthenticatorStore is the composed interface needed by Authenticator — session lookup, user lookup, and API key lookup. It names the consumer it serves, matching SessionVerifierStore and APIKeyVerifierStore, which are the per-verifier subsets this interface unions.

type CookieConfig

type CookieConfig struct {
	// Name is the base cookie name (without __Host- prefix).
	// Default: "auth_session".
	Name string

	// Path is the cookie Path attribute. Default: "/".
	Path string

	// Domain is the cookie Domain attribute. Default: "" (unset).
	// Note: __Host- prefix requires Domain to be unset.
	Domain string

	// SameSite is the cookie SameSite attribute. Default: http.SameSiteLaxMode.
	SameSite http.SameSite

	// Posture selects the deploy-time cookie security posture.
	// Default: PostureSecure.
	Posture CookiePosture

	// TrustForwardedHeaders enables honoring X-Forwarded-Proto to detect HTTPS.
	// MUST only be enabled when the app is behind a reverse proxy that always
	// sets/overwrites this header. When false (default), only r.TLS is used.
	TrustForwardedHeaders bool
}

CookieConfig holds configurable cookie attributes for session cookies. Under every posture except PosturePerRequest the deployment has ONE stable cookie name; PosturePerRequest alternates between the __Host--prefixed and bare forms of the configured base name per request scheme.

func DefaultCookieConfig

func DefaultCookieConfig() CookieConfig

DefaultCookieConfig returns a CookieConfig with secure defaults.

func (*CookieConfig) ClearCookie

func (c *CookieConfig) ClearCookie(w http.ResponseWriter, r *http.Request)

ClearCookie clears the session cookie.

func (*CookieConfig) CookieName

func (c *CookieConfig) CookieName(r *http.Request) string

CookieName returns the cookie name for this config. In PosturePerRequest mode the name is selected from the request scheme (__Host-<base> over HTTPS, bare <base> over plain HTTP); in all other postures the request is ignored and the stable EffectiveName() is returned.

func (*CookieConfig) EffectiveName

func (c *CookieConfig) EffectiveName() string

EffectiveName returns the ONE stable cookie name for this deployment. Determined entirely by Posture at config time — no per-request logic.

For PosturePerRequest the actual emitted/read name varies per request (see CookieName / SetCookie / ReadCookie); EffectiveName returns the secure __Host-<base> form as the canonical name for request-less callers and validation.

func (*CookieConfig) ReadCookie

func (c *CookieConfig) ReadCookie(r *http.Request) string

ReadCookie reads the session token from the cookie using the request-appropriate name (per-request in PosturePerRequest mode, otherwise the stable EffectiveName()).

func (*CookieConfig) SetCookie

func (c *CookieConfig) SetCookie(w http.ResponseWriter, r *http.Request, token string, maxAge int)

SetCookie sets the session cookie on the response using this config.

The Secure attribute follows the posture via isSecureCookieForRequest: it is set for every HTTPS posture and omitted only for plain-HTTP delivery, namely PostureInsecureLAN or PosturePerRequest over an HTTP request. Omitting Secure there is deliberate: a browser never sends a Secure cookie over plain HTTP, so forcing it would silently break sessions on HTTP-only LAN deployments. The default posture (PostureSecure) always sets Secure. Static analysis flags the conditional Secure (gosec G124, CodeQL go/cookie-secure-not-set); that is a documented false positive for the HTTP-LAN support, exercised by cookie_perrequest_test.go and redteam_test.go.

func (*CookieConfig) Validate

func (c *CookieConfig) Validate() error

Validate reports whether the configuration will produce a usable session cookie. It returns an error when:

  • Name, Domain, or Path contains a control character, or Name contains a character invalid in a cookie name -- cases that would make http.SetCookie emit a malformed Set-Cookie header; or
  • the posture emits a __Host--prefixed name (every posture except PostureInsecureLAN) while Domain is set or Path is not "/". Browsers silently reject a __Host- cookie that carries a Domain or a non-root Path, breaking every session with no server-side error.

Validate is the single authority for cookie-config validity: the constructors (New, NewSessionVerifier) call it so an unusable configuration fails fast at construction, and consumers assembling a CookieConfig by hand may call it directly.

type CookiePosture

type CookiePosture int

CookiePosture determines the cookie security posture. Every posture except PosturePerRequest is a deploy-time decision with one stable cookie name; PosturePerRequest selects the name and Secure flag per request from the request scheme.

const (
	// PostureSecure is the default: __Host- prefix + Secure + HttpOnly + SameSite=Lax.
	// Works on any HTTPS deployment including self-signed certificates.
	PostureSecure CookiePosture = iota

	// PostureInsecureLAN is for HTTP-only LAN/Docker deployments (ip:port, dockername:port).
	// Uses a non-prefixed name, no Secure flag. Explicitly opt-in only.
	PostureInsecureLAN

	// PostureForceSecure forces Secure flag even behind a TLS-terminating proxy
	// where r.TLS is nil. Requires TrustForwardedHeaders=true to detect HTTPS.
	PostureForceSecure

	// PosturePerRequest selects the cookie name and Secure flag per request,
	// driven by isHTTPS(r) (which honors TrustForwardedHeaders): __Host-<base>
	// with Secure over HTTPS, and the bare <base> without Secure over plain
	// HTTP. Intended for a single instance serving both HTTP-LAN (ip:port) and
	// HTTPS-proxied traffic. The base name stays configurable via Name.
	PosturePerRequest
)

func (CookiePosture) String

func (p CookiePosture) String() string

String returns the posture's name so structured-log attributes render "PostureSecure" rather than the bare iota integer.

type CredentialVerifier

type CredentialVerifier interface {
	Verify(ctx context.Context, r *http.Request) (*User, string, error)
}

CredentialVerifier resolves an HTTP request to an authenticated user using a specific credential type (session, API key, passkey). Implementations return (nil, "", nil) to indicate "not my credential type" and allow the next verifier in the chain to attempt authentication.

Chain semantics (see Authenticator.Authenticate): the chain stops at the first verifier that returns a non-nil *User (granted) OR a non-nil error. A non-nil error ABORTS the whole chain - verifiers ordered after it never run - and is surfaced to the caller as a failed authentication. A verifier that wants the chain to continue to the next credential type MUST return (nil, "", nil), never an error, for a credential it cannot positively authenticate. The built-in verifiers differ deliberately: SessionVerifier treats every session problem as (nil, "", nil) and falls through, whereas APIKeyVerifier returns ErrUnauthenticated for a present-but-invalid key. In the default New chain APIKeyVerifier runs last, so this is unobservable; but a custom WithVerifiers chain that places an error-returning verifier before others will reject a request (HTTP 401) whose earlier-type credential is present-but-invalid even when a later verifier holds a valid credential. This fails closed (denial, never a bypass); to avoid masking a later valid credential, order error-returning verifiers last or have them return (nil, "", nil) on "not my credential".

type Hasher

type Hasher struct {
	// contains filtered or unexported fields
}

Hasher provides configurable Argon2id password hashing with optional pepper.

func NewHasher

func NewHasher(params Argon2Params, opts ...HasherOption) (*Hasher, error)

NewHasher creates a Hasher with the given params. Returns an error if params are invalid. Use WithPepper to enable HMAC peppering. A Hasher must be constructed with NewHasher: the zero value has all-zero Argon2 parameters, which panic inside x/crypto's argon2 on first use.

func (*Hasher) Hash

func (h *Hasher) Hash(password string) string

Hash hashes a password using Argon2id with the configured parameters. Returns the hash in PHC string format.

It cannot fail, and so returns no error. Its only former failure source was the salt draw, and since Go 1.24 crypto/rand.Read never returns an error; NewHasher has already rejected parameters that would make argon2 panic. The asymmetry with Hasher.Verify, which does return an error, is deliberate: Verify parses caller-supplied input and can genuinely fail.

func (*Hasher) NeedsRehash

func (h *Hasher) NeedsRehash(encodedHash string) bool

NeedsRehash reports whether the hash uses different parameters than this Hasher.

func (*Hasher) Verify

func (h *Hasher) Verify(password, encodedHash string) (bool, error)

Verify verifies a password against an encoded Argon2id hash in PHC format.

type HasherOption

type HasherOption func(*hasherConfig)

HasherOption configures a Hasher.

func WithPepper

func WithPepper(pepper []byte) HasherOption

WithPepper sets the HMAC pepper applied to passwords before hashing. If not provided, no pepper is applied.

type Key

type Key struct {
	CreatedAt time.Time `json:"created_at"`
	// ExpiresAt is when the key stops being accepted, or the zero Time for a
	// key that never expires. See [Session.OIDCExpiry] for why an optional
	// timestamp is a value here rather than a *time.Time.
	ExpiresAt time.Time `json:"expires_at,omitzero"`
	KeyHash   string    `json:"-"`
	KeyPrefix string    `json:"key_prefix"`
	KeySuffix string    `json:"key_suffix"`
	Label     string    `json:"label"`
	ID        int64     `json:"id"`
	UserID    int64     `json:"user_id"`
}

Key represents a machine-to-machine API key for a user.

func VerifyAPIKey

func VerifyAPIKey(ctx context.Context, store APIKeyReader, key string) (*Key, error)

VerifyAPIKey hashes the provided key, looks it up in the store, and returns the matching APIKey record. Returns ErrInvalidAPIKey if the key is not found or has expired.

Example
package main

import (
	"context"
	"fmt"

	"github.com/cplieger/auth/v5"
	"github.com/cplieger/auth/v5/authtest"
)

func main() {
	store := authtest.NewMemStore()
	store.AddUser(&auth.User{
		Username: "bot",
		Role:     auth.RoleUser,
		Enabled:  true,
	})

	plaintext, hash, prefix, suffix := auth.GenerateAPIKey("ak_")
	store.AddAPIKey(&auth.Key{
		UserID:    1,
		KeyHash:   hash,
		KeyPrefix: prefix,
		KeySuffix: suffix,
		Label:     "ci",
	})

	// context.Background() (not t.Context()): an Example has no *testing.T.
	key, err := auth.VerifyAPIKey(context.Background(), store, plaintext)
	fmt.Println(key != nil, err == nil)
}
Output:
true true

type KeyRef

type KeyRef struct {
	// ID is the key row ID (Key.ID).
	ID int64
	// UserID is the owning user; an operation must affect the key only when
	// it belongs to this user.
	UserID int64
}

KeyRef identifies one API key together with the user who must own it. See PasskeyRef for why the pair travels as one value. The zero value identifies nothing: no stored key has ID or UserID zero, so an operation given a zero or partial ref affects no row (fails closed).

type KeyStore

type KeyStore interface {
	CreateAPIKey(ctx context.Context, key *Key) error
	APIKeyByHash(ctx context.Context, hash string) (key *Key, found bool, err error)
	ListAPIKeysByUserID(ctx context.Context, userID int64) ([]Key, error)
	DeleteAPIKey(ctx context.Context, ref KeyRef) error
}

KeyStore persists machine-to-machine API keys.

type Method

type Method string

Method is a typed identifier for the authentication mechanism used to establish a session.

const (
	MethodPassword Method = "password"
	MethodPasskey  Method = "passkey"
	MethodOIDC     Method = "oidc"
)

Auth method identifiers stored in sessions and used for method guards.

type MethodAvailability

type MethodAvailability struct {
	// PasskeyCount is the number of passkeys registered to the user.
	PasskeyCount int
	// HasPassword reports whether the user has a password set.
	HasPassword bool
	// OIDCEnabled reports whether OIDC login is enabled server-wide.
	OIDCEnabled bool
	// OIDCLinked reports whether the user has a linked OIDC identity.
	OIDCLinked bool
}

MethodAvailability describes which authentication methods are currently viable for one user. The three method signals would otherwise sit as adjacent same-typed bool parameters, where a silent swap flips which method counts as remaining; the field names make each value's role explicit at the call site. The zero value reports no method available, so CanDisableMethod refuses every disable; an omitted field undercounts the remaining methods and can only make the answer more conservative (fails closed).

type OIDCCodeVerifier

type OIDCCodeVerifier string

OIDCCodeVerifier is the opaque single-use PKCE code verifier minted by the oidc subpackage (as oidc.CodeVerifier, an alias of this type). See OIDCState for why the store vocabulary is typed.

type OIDCConfig

type OIDCConfig struct {
	IssuerURL    string `json:"issuer_url" yaml:"issuer_url"`
	ClientID     string `json:"client_id" yaml:"client_id"`
	ClientSecret string `json:"-" yaml:"client_secret"`
	RedirectURI  string `json:"redirect_uri" yaml:"redirect_uri"`
	AutoRedirect bool   `json:"auto_redirect" yaml:"auto_redirect"`
}

OIDCConfig holds OIDC provider settings.

type OIDCNonce

type OIDCNonce string

OIDCNonce is the opaque single-use ID-token replay-protection nonce minted by the oidc subpackage (as oidc.Nonce, an alias of this type). See OIDCState for why the store vocabulary is typed.

type OIDCState

type OIDCState string

OIDCState is the opaque single-use CSRF-binding state value minted by the oidc subpackage (as oidc.State, an alias of this type). It is typed so a hand-written store implementation cannot transpose it with the equally opaque nonce or code verifier: the three are indistinguishable strings, and a swap in a Scan or INSERT would silently disable the protection each one carries.

type OIDCStateStore

type OIDCStateStore interface {
	CreateOIDCState(ctx context.Context, state OIDCState, nonce OIDCNonce, codeVerifier OIDCCodeVerifier, redirectURI string) error
	ConsumeOIDCState(ctx context.Context, state OIDCState) (nonce OIDCNonce, codeVerifier OIDCCodeVerifier, redirectURI string, err error)
	CleanupExpiredOIDCStates(ctx context.Context, now time.Time, maxAge time.Duration) (int64, error)
}

OIDCStateStore persists OIDC authentication state.

type Option

type Option func(*authConfig)

Option configures an Authenticator, SessionVerifier, or APIKeyVerifier.

func WithAbsTimeout

func WithAbsTimeout(d time.Duration) Option

WithAbsTimeout sets the session absolute timeout duration.

func WithActivityThrottle

func WithActivityThrottle(d time.Duration) Option

WithActivityThrottle sets the minimum interval between session-activity writes for a given session within a SessionVerifier.

The default (d == 0) preserves write-on-every-authenticated-request behavior. When d > 0, the verifier records a session-activity write at most once per d per session hash, coalescing the high-frequency writes that would otherwise hit the store on every request. The write remains best-effort (errors are logged, never fatal).

d must be less than the configured idle timeout (ideally much less): because the persisted LastActivity is only refreshed once per window, it lags real activity by up to d, so a throttle >= the idle timeout can cause ValidateSession to expire sessions that are actively in use. The constructors reject such a configuration with an error.

func WithBypass

func WithBypass(fn func() bool) Option

WithBypass sets a function that reports whether authentication is bypassed. When the function returns true, all requests are treated as authenticated with a synthetic admin user. Installing the hook logs one Info line at construction; the loud production-safety WARN fires once, on the first request the hook actually grants — an installed-but-inactive hook (the common hot-reloadable dev-flag shape) therefore never warns.

func WithCookie

func WithCookie(cfg CookieConfig) Option

WithCookie sets the cookie configuration for session cookies.

func WithIdleTimeout

func WithIdleTimeout(d time.Duration) Option

WithIdleTimeout sets the session idle timeout duration.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets the logger for debug/warning output. If not provided, slog.Default() is used.

func WithLoginPath

func WithLoginPath(path string) Option

WithLoginPath sets the redirect target for unauthenticated browser requests. Defaults to "/login".

func WithTimeoutSource

func WithTimeoutSource(fn func() SessionTimeouts) Option

WithTimeoutSource sets a callback that resolves the session timeouts per verification, instead of the static values configured via WithIdleTimeout/WithAbsTimeout. It exists for consumers whose timeouts are hot-reloadable configuration: the default SessionVerifier consults the source on every Verify, so a changed value takes effect without reconstructing the verifier. The source returns a SessionTimeouts so the two durations travel field-named end to end; a callback returning a raw (idle, abs) pair would reintroduce the silent-swap hazard the struct exists to prevent.

Validation is per-resolution (a construction-time check cannot bind dynamic values): a non-positive Idle or Absolute field returned by the source falls back to the corresponding static configured value, and the activity throttle (see WithActivityThrottle) is clamped to at most half the resolved idle timeout, so a source that shrinks the idle timeout below the configured throttle can never make the persisted LastActivity stale enough to expire a session that is actively in use.

func WithUnauthorizedResponse

func WithUnauthorizedResponse(fn func(w http.ResponseWriter, r *http.Request)) Option

WithUnauthorizedResponse sets the response written by Authenticator.RequireAuth when a request is not authenticated, replacing the default behavior (a 302 redirect to the login path for browser requests, a 401 JSON envelope otherwise). The hook owns the entire unauthorized response: it is called for browser and API requests alike, so a consumer that wants to keep the browser redirect applies IsBrowserRequest itself. A nil hook (the default) preserves the built-in behavior byte for byte.

func WithVerifiers

func WithVerifiers(vs []CredentialVerifier) Option

WithVerifiers sets an explicit, ordered credential-verifier chain for an Authenticator, replacing the default session + API-key chain. When the provided slice is empty (or this option is not used), the default chain is used. This lets consumers inject custom verifiers (e.g. a TOTP or app-specific session verifier) without copying Authenticate; a consumer that also needs its own unauthorized response pairs it with WithUnauthorizedResponse to keep RequireAuth.

type PasskeyCredential

type PasskeyCredential struct {
	CreatedAt time.Time `json:"created_at"`

	// Discoverable is the credProps.rk extension output: whether the credential
	// is client-side discoverable. Nil means the client did not report it, which
	// is distinct from a reported false. This library requests credProps on
	// every registration and refuses a credential reported as non-discoverable,
	// so a stored false should not occur; nil is normal.
	//
	// It is the only extension output stored, because it is the only one this
	// library requests. An extension that is not requested is not reported, so a
	// field for it would be permanently zero.
	Discoverable *bool `json:"-"`

	// AttestationType is the attestation type conveyed at registration
	// ("basic_full", "basic_surrogate", "attca", "anonca", "ecdaa", "none").
	AttestationType string `json:"-"`

	// AttestationFormat is the attestation statement format identifier
	// ("packed", "tpm", "android-key", "android-safetynet", "fido-u2f",
	// "apple", "compound", "none").
	AttestationFormat string `json:"-"`

	// RPID is the relying-party ID the credential was registered against. It
	// decides where the credential can be used, so a change to the relying
	// party's ID can be audited against it rather than silently orphaning every
	// passkey.
	RPID string `json:"-"`

	Transport string `json:"transport,omitempty"`
	Name      string `json:"name"`

	// Attachment is how the authenticator was attached at registration. Empty
	// when the client did not report it.
	Attachment AuthenticatorAttachment `json:"-"`

	CredentialID   []byte `json:"-"`
	PublicKey      []byte `json:"-"`
	AAGUID         []byte `json:"-"`
	RawAttestation []byte `json:"-"`

	ID     int64 `json:"id"`
	UserID int64 `json:"user_id"`

	SignCount uint32 `json:"-"`

	// RawFlags is the authenticator-data flags octet as conveyed at
	// registration, and it is the ONLY flag input this library reads. The
	// booleans below are a decoded view for a consumer to display or filter on;
	// nothing here reads them back, so a store that persists them and drops the
	// octet loses the flags. The octet also preserves the bits the booleans do
	// not (AT, ED), which no accessor exposes.
	//
	// A store MUST persist it. A real registration always sets user presence,
	// so a zero octet on a stored credential means the store did not record it,
	// and the flags it restores are all false — which go-webauthn refuses at
	// the next login when the authenticator asserts backup eligibility (see
	// the PASSKEY FLAGS note in store_contract.go).
	RawFlags uint8 `json:"-"`

	BackupEligible bool `json:"backup_eligible"`
	BackupState    bool `json:"-"`
	UserPresent    bool `json:"-"`

	// UserVerified is the specification's uvInitialized: it latches true once
	// any assertion has verified the user. To decide whether one PARTICULAR
	// ceremony verified the user, read that ceremony's own authenticator data.
	UserVerified bool `json:"-"`

	CloneWarning bool `json:"-"`
}

PasskeyCredential represents a WebAuthn/FIDO2 credential registered to a user.

The field set is the credential record of WebAuthn §Credential Record. Every item that specification lists as RECOMMENDED is here, so a store persisting all of it can execute both the registration and the assertion algorithms; the optional items are here too, because a record written without them cannot be backfilled later — the data was never conveyed.

type PasskeyFlags

type PasskeyFlags struct {
	UserPresent    bool
	UserVerified   bool
	BackupEligible bool
	BackupState    bool
	CloneWarning   bool
}

PasskeyFlags holds the boolean authenticator flags for a credential update.

type PasskeyRef

type PasskeyRef struct {
	// ID is the credential row ID (PasskeyCredential.ID).
	ID int64
	// UserID is the owning user; an operation must affect the credential only
	// when it belongs to this user.
	UserID int64
}

PasskeyRef identifies one passkey credential together with the user who must own it. Rename/delete operations take the pair as one value so the ownership check cannot be silently disarmed by swapping two adjacent int64 arguments: the field names make each value's role explicit at the call site. The zero value identifies nothing: no stored credential has ID or UserID zero, so an operation given a zero or partial ref affects no row (fails closed).

type PasskeyStore

type PasskeyStore interface {
	CreatePasskey(ctx context.Context, cred *PasskeyCredential) error
	PasskeysByUserID(ctx context.Context, userID int64) ([]PasskeyCredential, error)
	PasskeyByCredentialID(ctx context.Context, credID []byte) (cred *PasskeyCredential, found bool, err error)
	UpdatePasskeyAfterLogin(ctx context.Context, credID []byte, signCount uint32, flags PasskeyFlags) error
	RenamePasskey(ctx context.Context, ref PasskeyRef, name string) error
	DeletePasskey(ctx context.Context, ref PasskeyRef) error
	PasskeyCountForUser(ctx context.Context, userID int64) (int, error)
}

PasskeyStore persists WebAuthn/FIDO2 credentials.

type PasswordContext

type PasswordContext struct {
	// Username is rejected as a password substring when it is at least four
	// characters long (shorter names over-reject common words).
	Username string
	// ForbiddenWords are app-specific words (site name, product name) the
	// password must not contain; empty entries are ignored.
	ForbiddenWords []string
}

PasswordContext carries the user-specific values a candidate password must not trivially embed. Passing it as a field-named struct keeps the password and the username from sitting as adjacent same-typed parameters, where a silent swap would validate the username against itself.

WARNING: the zero value FAILS OPEN — it turns every context check off. An empty Username disables the username-substring check and an empty ForbiddenWords disables the forbidden-word check, so a partial literal silently validates less, not more. Populate every field the account has.

type Role

type Role string

Role is a typed string identifying a user's authorization level.

const (
	RoleAdmin Role = "admin"
	RoleUser  Role = "user"
)

User role constants.

type Session

type Session struct {
	CreatedAt    time.Time `json:"created_at"`
	LastActivity time.Time `json:"last_activity"`
	// OIDCExpiry is the underlying OIDC token's expiry, or the zero Time when
	// the session is not OIDC-backed or the provider issued no expiry. It is a
	// value, not a *time.Time: time.Time's zero value already encodes absence
	// (see [time.Time.IsZero]), so the pointer bought nothing and cost two
	// things — a nil dereference for any caller that read it without the nil
	// check, and a shared mutable cell, since a struct copy of a Session
	// carrying a pointer still aliases the pointee.
	OIDCExpiry time.Time `json:"oidc_expiry,omitzero"`
	TokenHash  string    `json:"-"`
	AuthMethod Method    `json:"auth_method"`
	IPAddress  string    `json:"ip_address"`
	UserID     int64     `json:"user_id"`
}

Session represents a server-side authenticated session.

type SessionActivityUpdater

type SessionActivityUpdater interface {
	UpdateSessionActivity(ctx context.Context, tokenHash string, now time.Time) error
}

SessionActivityUpdater updates the last activity timestamp for a session.

type SessionPersister

type SessionPersister interface {
	CreateSession(ctx context.Context, sess *Session) error
	SessionByHash(ctx context.Context, tokenHash string) (sess *Session, found bool, err error)
	UpdateSessionActivity(ctx context.Context, tokenHash string, now time.Time) error
	DeleteSession(ctx context.Context, tokenHash string) error
	DeleteUserSessions(ctx context.Context, userID int64, exceptHash string) error
	CleanupExpiredSessions(ctx context.Context, now time.Time, timeouts SessionTimeouts) (int64, error)
}

SessionPersister persists session data.

type SessionReader

type SessionReader interface {
	SessionByHash(ctx context.Context, tokenHash string) (sess *Session, found bool, err error)
}

SessionReader finds session data by token hash.

type SessionTimeouts

type SessionTimeouts struct {
	// Idle is the maximum time since the session's last activity.
	Idle time.Duration
	// Absolute is the maximum time since the session was created.
	Absolute time.Duration
}

SessionTimeouts groups the idle and absolute session timeouts into one value. The two durations always travel together and would otherwise sit as adjacent same-typed parameters, where a silent swap makes the idle timeout effectively unbounded; the field names make each value's role explicit at the call site. Both fields are required: the zero value — including a partial literal that omits one field — expires every session instantly (any positive elapsed time exceeds a zero timeout), and a zero pair passed to CleanupExpiredSessions deletes every session row. It fails closed (lockout, never a bypass).

type SessionVerifier

type SessionVerifier struct {
	// contains filtered or unexported fields
}

SessionVerifier authenticates requests via session cookie. Create with NewSessionVerifier.

func NewSessionVerifier

func NewSessionVerifier(store SessionVerifierStore, opts ...Option) (*SessionVerifier, error)

NewSessionVerifier creates a SessionVerifier with the given session store and options. It returns an error when the assembled configuration is unusable: for example a __Host- cookie posture combined with a Domain or a non-root Path (which browsers reject), or an activity throttle that is not less than the idle timeout. See CookieConfig.Validate. If no idle/absolute timeout is provided, defaults of 1h and 24h are applied.

func (*SessionVerifier) Verify

func (v *SessionVerifier) Verify(ctx context.Context, r *http.Request) (*User, string, error)

Verify checks the session cookie and returns the user if valid.

type SessionVerifierStore

type SessionVerifierStore interface {
	SessionReader
	SessionActivityUpdater
	UserReader
}

SessionVerifierStore is the minimal interface for session verification.

type SessionWriter

type SessionWriter interface {
	CreateSession(ctx context.Context, sess *Session) error
	UpdateSessionActivity(ctx context.Context, tokenHash string, now time.Time) error
	DeleteSession(ctx context.Context, tokenHash string) error
	DeleteUserSessions(ctx context.Context, userID int64, exceptHash string) error
}

SessionWriter persists and removes session data.

type User

type User struct {
	CreatedAt    time.Time `json:"created_at"`
	UpdatedAt    time.Time `json:"updated_at"`
	Username     string    `json:"username"`
	Email        string    `json:"email,omitempty"`
	DisplayName  string    `json:"display_name,omitempty"`
	PasswordHash string    `json:"-"`
	Role         Role      `json:"role"`
	OIDCSub      string    `json:"-"`
	OIDCIssuer   string    `json:"-"`

	// WebAuthnHandle is the account's WebAuthn user handle, the value an
	// authenticator stores to identify this account and returns during a
	// discoverable login. Set it with [GenerateWebAuthnHandle] when creating an
	// account, and never change it afterwards: every passkey already registered
	// is bound to the value in force at its registration, so a new handle
	// orphans all of them.
	//
	// It is deliberately not derived from any other field. An authenticator may
	// reveal a handle without verifying the user, so it must say nothing about
	// who the account belongs to.
	WebAuthnHandle []byte `json:"-"`

	ID      int64 `json:"id"`
	Enabled bool  `json:"-"`
}

User represents an authenticated user account.

type UserReader

type UserReader interface {
	UserByID(ctx context.Context, id int64) (user *User, found bool, err error)
}

UserReader retrieves user records for authentication.

type UserStore

type UserStore interface {
	CreateUser(ctx context.Context, user *User) error
	UserByID(ctx context.Context, id int64) (user *User, found bool, err error)
	UserByUsername(ctx context.Context, username string) (u *User, found bool, err error)
	UserByEmail(ctx context.Context, email string) (user *User, found bool, err error)
	UserByOIDCSub(ctx context.Context, issuer, sub string) (user *User, found bool, err error)
	UserByWebAuthnHandle(ctx context.Context, handle []byte) (user *User, found bool, err error)
	ListUsers(ctx context.Context) ([]User, error)
	UpdateUser(ctx context.Context, user *User) error
	DeleteUser(ctx context.Context, id int64) error
	UserCount(ctx context.Context) (int, error)
}

UserStore persists user account data.

Directories

Path Synopsis
Package authtest provides an in-memory implementation of auth.AuthenticatorStore for use in consumer tests.
Package authtest provides an in-memory implementation of auth.AuthenticatorStore for use in consumer tests.
internal
capture
Package capture is an auth-internal test helper: a slog.Handler that records log records so tests can assert on auth's logging decisions, plus a helper to install it as the default logger.
Package capture is an auth-internal test helper: a slog.Handler that records log records so tests can assert on auth's logging decisions, plus a helper to install it as the default logger.
Package oidc wraps coreos/go-oidc to provide OIDC/OAuth2 authentication flows with PKCE.
Package oidc wraps coreos/go-oidc to provide OIDC/OAuth2 authentication flows with PKCE.
Package ratelimit implements a dual sliding-window rate limiter for authentication attempts (per-IP and per-account).
Package ratelimit implements a dual sliding-window rate limiter for authentication attempts (per-IP and per-account).
Package webauthn wraps go-webauthn/webauthn to provide WebAuthn/FIDO2 passkey ceremony helpers.
Package webauthn wraps go-webauthn/webauthn to provide WebAuthn/FIDO2 passkey ceremony helpers.

Jump to

Keyboard shortcuts

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