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 ¶
- Constants
- Variables
- func APIKeyHash(key string) string
- func CSRFToken(key []byte, sessionHash string) (string, error)
- func CanDisableMethod(method Method, avail MethodAvailability) bool
- func CheckBreachedPassword(ctx context.Context, client *http.Client, password string) (bool, error)
- func DummyHash() string
- func GenerateAPIKey(keyPrefix string) (plaintext, hash, displayPrefix, displaySuffix string)
- func GenerateOpaqueToken() (plaintext, hash string)
- func GenerateSessionToken() (plaintext, hash string)
- func GenerateWebAuthnHandle() []byte
- func HasRole(user *User, role Role) bool
- func HashPassword(password string) string
- func HexSHA256(s string) string
- func IsBrowserRequest(r *http.Request) bool
- func NeedsRehash(encodedHash string) bool
- func NormalizeUsername(username string) (string, error)
- func RotateSessionToken(oldPlaintext string) (newPlaintext, newHash, oldHash string)
- func SessionHash(token string) string
- func ValidateMultiFactorPasswordLength(password string) error
- func ValidatePasswordContext(password string, pctx PasswordContext) error
- func ValidateRedirectURI(uri string) string
- func ValidateSession(sess *Session, timeouts SessionTimeouts, now time.Time) error
- func ValidateSoloPasswordLength(password string) error
- func VerifyCSRFToken(key []byte, sessionHash, token string, maxAge time.Duration) error
- func VerifyOpaqueToken(plaintext, storedHash string, expiresAt time.Time) error
- func VerifyPassword(password, encodedHash string) (bool, error)
- type APIKeyReader
- type APIKeyVerifier
- type APIKeyVerifierStore
- type Argon2Params
- type Authenticator
- type AuthenticatorAttachment
- type AuthenticatorStore
- type CookieConfig
- func (c *CookieConfig) ClearCookie(w http.ResponseWriter, r *http.Request)
- func (c *CookieConfig) CookieName(r *http.Request) string
- func (c *CookieConfig) EffectiveName() string
- func (c *CookieConfig) ReadCookie(r *http.Request) string
- func (c *CookieConfig) SetCookie(w http.ResponseWriter, r *http.Request, token string, maxAge int)
- func (c *CookieConfig) Validate() error
- type CookiePosture
- type CredentialVerifier
- type Hasher
- type HasherOption
- type Key
- type KeyRef
- type KeyStore
- type Method
- type MethodAvailability
- type OIDCCodeVerifier
- type OIDCConfig
- type OIDCNonce
- type OIDCState
- type OIDCStateStore
- type Option
- func WithAbsTimeout(d time.Duration) Option
- func WithActivityThrottle(d time.Duration) Option
- func WithBypass(fn func() bool) Option
- func WithCookie(cfg CookieConfig) Option
- func WithIdleTimeout(d time.Duration) Option
- func WithLogger(l *slog.Logger) Option
- func WithLoginPath(path string) Option
- func WithTimeoutSource(fn func() SessionTimeouts) Option
- func WithUnauthorizedResponse(fn func(w http.ResponseWriter, r *http.Request)) Option
- func WithVerifiers(vs []CredentialVerifier) Option
- type PasskeyCredential
- type PasskeyFlags
- type PasskeyRef
- type PasskeyStore
- type PasswordContext
- type Role
- type Session
- type SessionActivityUpdater
- type SessionPersister
- type SessionReader
- type SessionTimeouts
- type SessionVerifier
- type SessionVerifierStore
- type SessionWriter
- type User
- type UserReader
- type UserStore
Examples ¶
Constants ¶
const ( DefaultIdleTimeout = 1 * time.Hour DefaultAbsTimeout = 24 * time.Hour )
Default session timeout values matching the pre-refactor struct-field defaults.
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).
const PasswordMaxLength = 128
PasswordMaxLength is the maximum password length to prevent DoS via extremely long inputs to Argon2id (OWASP recommendation).
const PasswordMinLengthMultiFactor = 8
PasswordMinLengthMultiFactor is the minimum password length when password login is not the sole sufficient factor.
const PasswordMinLengthSolo = 15
PasswordMinLengthSolo is the minimum password length when password login is enabled and thus a sole sufficient factor.
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 ¶
var ( ErrSessionExpired = errors.New("session expired") ErrSessionNotFound = errors.New("session not found") )
Sentinel errors for session operations.
var ( ErrTokenExpired = errors.New("auth: token expired") ErrTokenInvalid = errors.New("auth: token invalid") )
Token errors.
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.
var ErrInvalidAPIKey = errors.New("invalid API key")
ErrInvalidAPIKey is returned when an API key cannot be verified.
var ErrUnauthenticated = errors.New("unauthenticated")
ErrUnauthenticated is returned when no valid credential is found.
Functions ¶
func APIKeyHash ¶
APIKeyHash returns the hex-encoded SHA-256 hash of a key string.
func CSRFToken ¶
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 ¶
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 ¶
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/v6"
)
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/v6"
)
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 ¶
HasRole reports whether the user is authorized for the given role.
Example ¶
package main
import (
"fmt"
"github.com/cplieger/auth/v6"
)
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 ¶
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/v6"
)
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 IsBrowserRequest ¶
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 ¶
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 ¶
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 ¶
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 ¶
SessionHash returns the hex-encoded SHA-256 hash of a plaintext token.
func ValidateMultiFactorPasswordLength ¶
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/v6"
)
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 ¶
ValidateRedirectURI ensures the URI is a safe relative path.
Example ¶
package main
import (
"fmt"
"github.com/cplieger/auth/v6"
)
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 ¶
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/v6"
)
func main() {
// Solo arm: password login alone grants access, minimum 15.
err := auth.ValidateSoloPasswordLength("short")
fmt.Println(err != nil)
}
Output: true
func VerifyCSRFToken ¶
VerifyCSRFToken verifies a CSRF token against the session hash and checks that it has not expired (maxAge duration from creation).
func VerifyOpaqueToken ¶
VerifyOpaqueToken checks that the plaintext token matches the stored hash and that the token has not expired. Returns nil on success.
func VerifyPassword ¶
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.
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 ¶
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/v6"
"github.com/cplieger/auth/v6/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.
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 sets the __Host- prefix and Secure on every request // without consulting the request scheme, so it behaves as PostureSecure, // including behind a TLS-terminating proxy where r.TLS is nil. 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 ¶
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 ¶
NeedsRehash reports whether the hash uses different parameters than this Hasher.
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 ¶
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/v6"
"github.com/cplieger/auth/v6/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.
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 ¶
WithAbsTimeout sets the session absolute timeout duration.
func WithActivityThrottle ¶
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 ¶
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 ¶
WithIdleTimeout sets the session idle timeout duration.
func WithLogger ¶
WithLogger sets the logger for debug/warning output. If not provided, slog.Default() is used.
func WithLoginPath ¶
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 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.
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.
Source Files
¶
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
|
|
|
aaguidgen
Package aaguidgen builds the webauthn package's authenticator name table from the community passkey AAGUID list at https://github.com/passkeydeveloper/passkey-authenticator-aaguids.
|
Package aaguidgen builds the webauthn package's authenticator name table from the community passkey AAGUID list at https://github.com/passkeydeveloper/passkey-authenticator-aaguids. |
|
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. |
|
cmd/genaaguids
command
Command genaaguids regenerates webauthn/aaguids_gen.go from the community list at the commit webauthn/aaguids_source.go pins; see internal/aaguidgen.
|
Command genaaguids regenerates webauthn/aaguids_gen.go from the community list at the commit webauthn/aaguids_source.go pins; see internal/aaguidgen. |
|
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. |