Documentation
¶
Overview ¶
Package access 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 AllowRecoverySession(ctx context.Context) context.Context
- func CanDisableMethod(method Method, avail MethodAvailability) bool
- func CheckBreachedPassword(ctx context.Context, client *http.Client, password string) (bool, error)
- func DecodePasskeyFlags(octet uint8) (userPresent, userVerified, backupEligible, backupState bool)
- func GenerateOpaqueToken() (plaintext Secret, hash Hash)
- func GenerateSealerKey() []byte
- func GenerateSessionToken() (plaintext Secret, hash Hash)
- func GenerateWebAuthnHandle() []byte
- func HasRole(user *User, role Role) bool
- func HashCost(p Argon2Params) int64
- func HexSHA256(s string) string
- func IsBrowserRequest(r *http.Request) bool
- func IsPassive(ctx context.Context) bool
- func NewOneTimeToken(purpose TokenPurpose, subject int64, ttl time.Duration, now time.Time) (plaintext Secret, rec OneTimeToken)
- func NormalizeUsername(username string) (string, error)
- func Passive(ctx context.Context) context.Context
- func RequestIsHTTPS(r *http.Request) bool
- func RequireRecentAuth(p Principal, maxAge time.Duration, now time.Time) error
- func SessionDeadlines(s *Session, t SessionTimeouts) (idle, absolute time.Time)
- func ValidateKeyPrefix(prefix string) error
- func ValidatePasswordCommon(password string) error
- func ValidatePasswordContext(password string, pctx PasswordContext) error
- func ValidatePasswordLength(password string) error
- func ValidateRedirectURI(uri string) string
- func ValidateSession(sess *Session, timeouts SessionTimeouts, now time.Time) error
- func VerifyOpaqueToken(plaintext string, storedHash Hash, expiresAt time.Time) error
- type APIKeyReader
- type APIKeyToucher
- type Argon2Params
- type AttributionAction
- type Authenticator
- func (a *Authenticator) Authenticate(r *http.Request) (Principal, error)
- func (a *Authenticator) ClientAddr(r *http.Request) ClientAddr
- func (a *Authenticator) Cookie() CookieConfig
- func (a *Authenticator) Recheck(ctx context.Context, p Principal) (Principal, error)
- func (a *Authenticator) RequireAuth(w http.ResponseWriter, r *http.Request) (Principal, bool)
- func (a *Authenticator) Timeouts() SessionTimeouts
- type AuthenticatorAttachment
- type AuthenticatorStore
- type ClientAddr
- type Config
- type CookieConfig
- func (c *CookieConfig) ClearCookie(w http.ResponseWriter, r *http.Request)
- func (c *CookieConfig) CookieName(r *http.Request) string
- func (c CookieConfig) Derive(suffix string, sameSite http.SameSite) CookieConfig
- 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 GeneratedKey
- type Hash
- type HashBudget
- type HashKey
- type HashPermit
- type Hasher
- type HasherConfig
- type InvalidCredentialError
- type Key
- type KeyAttribution
- type KeyRef
- type Method
- type MethodAvailability
- type OIDCIdentity
- type OneTimeToken
- type PasskeyCredential
- type PasskeyLoginUpdate
- type PasskeyRef
- type PasswordContext
- type PasswordError
- type PasswordRejection
- type Principal
- type Rechecker
- type Role
- type Sealer
- type Secret
- type Session
- type SessionActivity
- type SessionActivityUpdater
- type SessionKind
- type SessionReader
- type SessionRef
- type SessionTimeouts
- type TokenPurpose
- type User
- type UserReader
Examples ¶
Constants ¶
const ( DefaultIdleTimeout = 1 * time.Hour DefaultAbsTimeout = 24 * time.Hour )
DefaultIdleTimeout and DefaultAbsTimeout are what a zero Config.IdleTimeout and Config.AbsTimeout mean.
const MaxCookieNameBytes = 64
MaxCookieNameBytes is the longest CookieConfig.Name Validate accepts: far above any real name, it leaves a derived cookie room for a sealed value in a browser's 4096 bytes (RFC 6265 §6.1).
const MaxSealPayload = 3032
MaxSealPayload is the longest payload Seal accepts: the largest whose sealed, encoded form is no longer than the 4096 bytes Open accepts. 4096 base64url characters decode to 3072 bytes, less the 12-byte nonce, the 12-byte expiry frame and the 16-byte tag.
const PasswordMaxLength = 128
PasswordMaxLength is the longest password ValidatePasswordLength accepts, in runes after NFC: an upper bound NIST SP 800-63B-4 §3.1.1.2 permits (it asks for at least 64). It is not a DoS guard, because Argon2 first hashes the password into its 64-byte H0 (RFC 9106 §3.2), so the length barely changes a derivation's cost.
const PasswordMinLength = 15
PasswordMinLength is the shortest password ValidatePasswordLength accepts, in runes after NFC. A password is always a sole sufficient factor here, so the floor never drops below NIST's 15 (SP 800-63B-4 §3.1.1.2).
const RecoverySessionLifetime = 15 * time.Minute
RecoverySessionLifetime bounds a SessionRecovery session's idle and absolute life, whatever the policy timeouts.
const SealerKeySize = 32
SealerKeySize is the length of every Sealer key: AES-256.
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 ( // ErrUnauthenticated means no usable credential. It is bare when none // was presented, and wraps [ErrSessionExpired] or [ErrSessionNotFound] // when the only one was a session cookie whose session is gone. ErrUnauthenticated = errors.New("unauthenticated") // ErrInvalidCredential means a credential was presented and refused. // The error is an [*InvalidCredentialError] naming why. ErrInvalidCredential = errors.New("access: invalid credential") // ErrAuthBackend means a store failed while authenticating; the error // wraps the store's. ErrAuthBackend = errors.New("access: authentication backend failed") // ErrRecentAuthRequired is [RequireRecentAuth]'s refusal. ErrRecentAuthRequired = errors.New("access: recent authentication required") // ErrNotRecheckable is the answer for a principal no verifier can // re-validate. ErrNotRecheckable = errors.New("access: principal cannot be rechecked") // ErrAccountDisabled is the detail for a credential whose user is // missing or disabled. ErrAccountDisabled = errors.New("access: account disabled") // ErrRestrictedSession is the detail for a recovery session presented // on a request that does not allow one (see [AllowRecoverySession]). ErrRestrictedSession = errors.New("access: restricted session") )
Errors of authentication. A verifier's or the Authenticator's refusal carries one of the first three; the rest are details or the answers of RequireRecentAuth and Authenticator.Recheck.
var ( // ErrHashBudgetTooSmall reports a budget that cannot hold one derivation // at the hasher's parameters. ErrHashBudgetTooSmall = errors.New("access: hash budget smaller than one derivation") // ErrHashInvalid reports a stored hash whose cost exceeds the whole // budget, so no wait could ever admit it. ErrHashInvalid = errors.New("access: stored hash exceeds the hash budget") )
var ( // ErrSealInvalid covers every value Open cannot authenticate: malformed, // too long, sealed for another purpose, or under no key of the ring. ErrSealInvalid = errors.New("access: sealed value invalid") // ErrSealExpired is an authentic value opened at or after its expiry. ErrSealExpired = errors.New("access: sealed value expired") // ErrSealTooLarge is Seal's refusal of a payload over MaxSealPayload. ErrSealTooLarge = errors.New("access: payload too large to seal") )
Sealer errors.
var ( ErrSessionExpired = errors.New("session expired") ErrSessionNotFound = errors.New("session not found") )
Sentinel errors for session operations.
var ( ErrTokenExpired = errors.New("access: token expired") ErrTokenInvalid = errors.New("access: 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. 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.
ErrBreachCheckUnavailable reports that CheckBreachedPassword got no verdict.
var ErrHashBusy = errors.New("access: hash budget busy")
ErrHashBusy reports that a hash budget could not admit a derivation within the wait. When the caller's context ended first, the error also wraps the context's error.
var ErrInvalidAPIKey = errors.New("invalid API key")
ErrInvalidAPIKey is returned when an API key cannot be verified.
var ErrInvalidKeyPrefix = errors.New("access: API key prefix must match ^[A-Za-z0-9_]{0,16}$")
ErrInvalidKeyPrefix is returned by ValidateKeyPrefix and GenerateAPIKey for a prefix that is not 0 to 16 ASCII letters, digits or underscores.
Functions ¶
func AllowRecoverySession ¶
AllowRecoverySession marks a request on which a SessionRecovery principal may authenticate. Every other request refuses it.
func CanDisableMethod ¶
func CanDisableMethod(method Method, avail MethodAvailability) bool
CanDisableMethod reports whether the user keeps at least one way to sign in after removing method, given avail as the availability after that removal (see MethodAvailability). The password and OIDC signals of the method being removed are ignored; PasskeyCount counts whatever the method, so a passkey removal is allowed while another passkey remains.
func CheckBreachedPassword ¶
CheckBreachedPassword reports whether the Have I Been Pwned Passwords API lists the password, sending only the first five hex characters of the SHA-1 of its NFC form (k-anonymity). It never logs or follows a redirect. A nil client, a failed request, a non-200 status, a failed read or a body over 2 MiB returns false and an error wrapping ErrBreachCheckUnavailable, naming the cause but not the URL, and also wrapping ctx.Err() once ctx has ended.
func DecodePasskeyFlags ¶
DecodePasskeyFlags is the one decoder of the authenticator-data flags octet.
func GenerateOpaqueToken ¶
GenerateOpaqueToken generates a cryptographically random opaque token suitable for password-reset or email-verification flows. Returns the plaintext token (to Reveal only into what is sent to the user) and its hex SHA-256 hash (to store in the database). It cannot fail; see [generateRandomHex].
func GenerateSealerKey ¶
func GenerateSealerKey() []byte
GenerateSealerKey returns SealerKeySize random bytes, which the caller persists and passes to NewSealer.
func GenerateSessionToken ¶
GenerateSessionToken generates a cryptographically random session token (256 bits / 32 bytes). It returns the hex-encoded plaintext token, to Reveal only into the cookie, and its SessionHash, to store. It cannot fail; see [generateRandomHex].
Example ¶
package main
import (
"fmt"
"github.com/cplieger/access"
)
func main() {
plaintext, hash := access.GenerateSessionToken()
cookieValue := plaintext.Reveal() // reveal only into the cookie
fmt.Println(plaintext, len(cookieValue) == 64, access.SessionHash(cookieValue).Equal(hash))
}
Output: [redacted] true true
func GenerateWebAuthnHandle ¶
func GenerateWebAuthnHandle() []byte
GenerateWebAuthnHandle returns a new WebAuthn user handle: 64 random bytes, as WebAuthn §14.6.1 recommends. An authenticator may reveal the handle without verifying the user, so it carries nothing about the account: no username, no email, no sequential ID. Store it on User.WebAuthnHandle; it cannot fail (see [generateRandomHex]).
func HasRole ¶
HasRole reports whether the user is authorized for the given role.
Example ¶
package main
import (
"fmt"
"github.com/cplieger/access"
)
func main() {
admin := &access.User{Role: access.RoleAdmin}
user := &access.User{Role: access.RoleUser}
fmt.Println(access.HasRole(admin, access.RoleUser))
fmt.Println(access.HasRole(user, access.RoleAdmin))
}
Output: true false
func HashCost ¶
func HashCost(p Argon2Params) int64
HashCost returns what one derivation at p is charged against a budget, in bytes: max(Memory, 8 × Parallelism) KiB, an upper bound on the block matrix x/crypto/argon2 allocates (Memory rounded down to a multiple of 4 × Parallelism KiB, at least 8 KiB per lane). The derived key and the worker goroutines' stacks are not charged.
func IsBrowserRequest ¶
IsBrowserRequest reports whether the request appears to come from a browser: its Accept header contains text/html and it carries no Authorization header, whatever its scheme or value.
func NewOneTimeToken ¶
func NewOneTimeToken(purpose TokenPurpose, subject int64, ttl time.Duration, now time.Time) (plaintext Secret, rec OneTimeToken)
NewOneTimeToken mints a 256-bit token expiring ttl after now. Store only the record; hand out only the plaintext. IssuedByKey and Role are left for the issuer to set.
func NormalizeUsername ¶
NormalizeUsername returns the canonical form of a username, so two names with the same form are one account: apply it to the unique-username index key and again to the login input. The rule is RFC 8265 §3.3's UsernameCaseMapped profile, which case-folds all of Unicode ("Müller" is "MÜLLER") without transliterating ("straße" stays apart from "strasse") and refuses spaces. It bounds no length and refuses no confusable: the consumer owns both policies. It returns ErrUsernameEmpty for an empty result and ErrUsernameInvalid, wrapping the profile's cause, for a refused name.
func Passive ¶
Passive marks a request whose verification must not count as session activity: presence receipts, polling, stream reconnects. The session is still fully verified; only the activity write is skipped.
func RequestIsHTTPS ¶
RequestIsHTTPS is upgrade-only: it reports true for a TLS request, or when the first token of X-Forwarded-Proto is "https" (case-insensitive), from any peer. A forged "https" only makes the forger's own browser refuse the Secure cookie, so no proxy trust is needed.
func RequireRecentAuth ¶
RequireRecentAuth returns nil only for a principal for which IsSession is true and whose AuthTime is within maxAge of now and not after it; every other principal, a custom verifier's included, gets ErrRecentAuthRequired. An AuthTime after now is refused on purpose: this gate guards a sensitive operation, a job apart from session validity, and fails closed where it cannot place the proof of a recent sign-in.
func SessionDeadlines ¶
func SessionDeadlines(s *Session, t SessionTimeouts) (idle, absolute time.Time)
SessionDeadlines returns the instants after which s is expired: its last activity plus the idle limit, and its creation plus the absolute limit. Each limit is the policy's in t, lowered to RecoverySessionLifetime for a SessionRecovery session and to the session's positive IdleCap or AbsoluteCap. s must not be nil.
func ValidateKeyPrefix ¶
ValidateKeyPrefix returns nil for a prefix GenerateAPIKey accepts, and ErrInvalidKeyPrefix otherwise.
func ValidatePasswordCommon ¶
ValidatePasswordCommon refuses a password on the embedded list of common passwords (NIST SP 800-63B-4 §3.1.1.2), with a *PasswordError whose Reason is "common". The list holds SecLists' most frequent passwords that reach PasswordMinLength runes after NFC and case folding, the form the comparison uses; a shorter password is ValidatePasswordLength's to refuse.
func ValidatePasswordContext ¶
func ValidatePasswordContext(password string, pctx PasswordContext) error
ValidatePasswordContext refuses a password that is one of pctx's words or a simple derivative of one, with a *PasswordError whose Reason is "contains_forbidden_word" or "contains_username". Both sides are NFC and case-folded, as Hasher hashes. It refuses the word itself, or the word's core once or repeated with only digits, spaces and punctuation around and between the copies (a core strips those from both ends). A password that only contains a word is accepted (NIST SP 800-63B-4 §3.1.1.2).
Example ¶
package main
import (
"fmt"
"github.com/cplieger/access"
)
func main() {
pctx := access.PasswordContext{Username: "alice", ForbiddenWords: []string{"subflux"}}
fmt.Println(access.ValidatePasswordContext("Alice2024!", pctx))
fmt.Println(access.ValidatePasswordContext("my subflux library passphrase", pctx))
}
Output: access: password refused: contains_username <nil>
func ValidatePasswordLength ¶
ValidatePasswordLength refuses a password shorter than PasswordMinLength or longer than PasswordMaxLength runes after NFC, with a *PasswordError whose Reason is "too_short" or "too_long".
Example ¶
package main
import (
"errors"
"fmt"
"github.com/cplieger/access"
)
func main() {
var pe *access.PasswordError
if err := access.ValidatePasswordLength("short"); errors.As(err, &pe) {
fmt.Println(pe.Reason, pe.Min)
}
fmt.Println(access.ValidatePasswordLength("correct horse battery staple"))
}
Output: too_short 15 <nil>
func ValidateRedirectURI ¶
ValidateRedirectURI returns uri when it is a safe relative path of at most 2048 bytes, and "/" otherwise.
Example ¶
package main
import (
"fmt"
"github.com/cplieger/access"
)
func main() {
fmt.Println(access.ValidateRedirectURI("/dashboard"))
fmt.Println(access.ValidateRedirectURI("https://evil.com"))
}
Output: /dashboard /
func ValidateSession ¶
func ValidateSession(sess *Session, timeouts SessionTimeouts, now time.Time) error
ValidateSession returns ErrSessionExpired when now is after either of the session's SessionDeadlines, and ErrSessionNotFound for a nil session.
Types ¶
type APIKeyReader ¶
type APIKeyReader interface {
APIKeyByHash(ctx context.Context, hash Hash) (key *Key, found bool, err error)
}
APIKeyReader validates API keys (looked up by hash).
type APIKeyToucher ¶
APIKeyToucher records a key's use as its LastUsedAt. It sets LastUsedAt to at only when at is after the stored value, atomically; an older or equal at, or an ID no key has, writes nothing and returns nil.
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 refuses parameters outside the bounds: memory at least OWASP's minimum for min(Iterations, 5) iterations (argonFloor) and at most 4 GiB, iterations 1 to 100, parallelism 1 to 16, salt and key 16 to 64 bytes.
type AttributionAction ¶
type AttributionAction string
AttributionAction names what a key did to a user.
const ( AttributionCreated AttributionAction = "created" // CreateUser by a key AttributionInviteAccepted AttributionAction = "invite_accepted" // a key-issued invite created the user AttributionRecoveryStarted AttributionAction = "recovery_started" // a key-issued recovery link opened a recovery session AttributionRecovered AttributionAction = "recovered" // a key-issued recovery session set a credential AttributionEnabled AttributionAction = "enabled" // UpdateUser by a key re-enabled the user AttributionDisabled AttributionAction = "disabled" // UpdateUser by a key disabled the user )
Attribution actions.
type Authenticator ¶
type Authenticator struct {
// contains filtered or unexported fields
}
Authenticator resolves an HTTP request to a Principal. Create with New.
func New ¶
func New(store AuthenticatorStore, cfg Config) (*Authenticator, error)
New builds the one session configuration (cookie, timeouts, throttle) and the chain: the session verifier, cfg.Verifier if set, then the API-key verifier. Every zero field of cfg means its default (see Config). A nil store, or an interface holding a nil pointer, map, slice, func or chan, is refused, and so is such a cfg.Verifier, before any verifier is built, so a miswired app fails at startup and not at its first request. So are a negative timeout or throttle, a throttle not below the idle timeout, and a Cookie CookieConfig.Validate refuses.
func (*Authenticator) Authenticate ¶
func (a *Authenticator) Authenticate(r *http.Request) (Principal, error)
Authenticate runs the chain on r. It returns the first Principal a verifier grants; else the first error matching ErrUnauthenticated a verifier returned; else bare ErrUnauthenticated. Any other verifier error is returned at once. A granted principal whose User is nil or disabled, or whose Method is empty, is refused with an *InvalidCredentialError. The principal's User and Scopes are copies the caller may keep and change.
func (*Authenticator) ClientAddr ¶
func (a *Authenticator) ClientAddr(r *http.Request) ClientAddr
ClientAddr resolves r's client through the Config.ClientAddr resolver, the one resolver behind SessionActivity.IP, the limiter's IP key and the setup rule.
func (*Authenticator) Cookie ¶
func (a *Authenticator) Cookie() CookieConfig
Cookie returns the session cookie configuration the session verifier reads.
func (*Authenticator) Recheck ¶
Recheck re-validates p for a long-lived connection and returns it with its deadlines re-read, writing no activity. A session principal re-reads its session and user, a key principal its key and user, and any other principal goes to Config.Verifier when it implements Rechecker; a Rechecker's ok false with a nil error, and any principal no verifier can recheck, is ErrNotRecheckable. Its errors and its refusal of a granted principal are Authenticate's.
func (*Authenticator) RequireAuth ¶
func (a *Authenticator) RequireAuth(w http.ResponseWriter, r *http.Request) (Principal, bool)
RequireAuth authenticates r and returns its principal. If r is not authenticated, it writes the Config.Unauthorized response, or the default one that field describes, and returns ok=false.
Example ¶
package main
import (
"context"
"fmt"
"time"
"github.com/cplieger/access"
"github.com/cplieger/access/accesstest"
)
func main() {
store := accesstest.NewMemStore()
if err := store.CreateUser(context.Background(), &access.User{
Username: "alice",
Role: access.RoleAdmin,
Enabled: true,
}); err != nil {
panic(err)
}
authn, err := access.New(store, access.Config{
IdleTimeout: time.Hour,
AbsTimeout: 24 * time.Hour,
})
if err != nil {
panic(err)
}
_ = authn
fmt.Println("authenticator configured")
}
Output: authenticator configured
func (*Authenticator) Timeouts ¶
func (a *Authenticator) Timeouts() SessionTimeouts
Timeouts returns the session timeouts in force now: the Config.TimeoutSource value, each non-positive field replaced by the static configured one.
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
APIKeyToucher
}
AuthenticatorStore is the store New takes: the session, user and API-key reads, the session activity write and the key touch.
type ClientAddr ¶
type ClientAddr struct {
// IP is the resolved client address; the limiter keys on it.
IP netip.Addr
// Peer is the connection's remote address.
Peer netip.Addr
// Proxied reports that IP came from a forwarding header sent by a peer
// the app trusts as a proxy.
Proxied bool
// UntrustedForwarding reports that the request carried a forwarding
// header (Forwarded, X-Forwarded-For, X-Real-IP) from a peer the app
// does not trust, which the resolver ignored.
UntrustedForwarding bool
}
ClientAddr is how the app resolved the caller's address. The app's proxy-aware resolver (Config.ClientAddr) fills it; the library never reads a forwarding header to decide an address.
type Config ¶
type Config struct {
// Logger receives the warnings and debug lines.
Logger *slog.Logger
// Bypass reports whether authentication is bypassed. While it returns
// true, [Authenticator.Authenticate] grants every request [MethodBypass]
// with its own copy of a synthetic admin user whose ID is 0, which names
// no stored user. [New] logs one Info line when it is set; each request
// that finds it on after one that found it off, the first included, logs
// a WARN.
Bypass func() bool
// that is not authenticated, given [Authenticator.Authenticate]'s error.
// Nil answers 503 with Retry-After: 5 for [ErrAuthBackend], and otherwise
// 401 with WWW-Authenticate: Bearer and a JSON body whose code is
// auth_session_expired when the error wraps [ErrSessionExpired] or
// [ErrSessionNotFound], and auth_required otherwise.
Unauthorized func(w http.ResponseWriter, r *http.Request, err error)
// TimeoutSource is read on every verification, so a hot-reloaded value
// applies without a new Authenticator. Each non-positive field it
// returns falls back to IdleTimeout or AbsTimeout, and ActivityThrottle's
// clamp applies to the idle timeout it returns.
TimeoutSource func() SessionTimeouts
// ClientAddr is the app's one client resolver, served by
// [Authenticator.ClientAddr]. Nil treats no peer as a proxy: IP and Peer
// are the socket peer of r.RemoteAddr, unmapped, Proxied is false, and
// UntrustedForwarding is true when Forwarded, X-Forwarded-For or
// X-Real-IP is present.
ClientAddr func(*http.Request) ClientAddr
// Verifier runs between the built-in session and API-key verifiers. The
// API-key verifier refuses every Bearer value it cannot find, so a
// Verifier for another Bearer credential answers ok false and a nil error
// for every value not its own. It may grant an app-synthesised User with
// no stored row: non-nil, enabled and with a non-empty Method, never
// looked up in the store, and refused by every account operation that
// needs a stored user, because IsSession() is false.
Verifier CredentialVerifier
// Cookie is the session cookie, checked by [CookieConfig.Validate].
Cookie CookieConfig
// IdleTimeout is how long a session may sit unused.
IdleTimeout time.Duration
// AbsTimeout is how long a session may live at most.
AbsTimeout time.Duration
// ActivityThrottle is how old a key's stored LastUsedAt must be before a
// request writes it again through [APIKeyToucher.TouchAPIKey]. A session's
// activity is written once its stored LastActivity is the lesser of it and
// half the session's idle limit old, that limit lowered by its IdleCap
// and, for a recovery session, by [RecoverySessionLifetime], so a session
// in use never expires between two writes. A failed write is logged,
// never fatal, and the next request retries it. [New] refuses a negative
// throttle and one at or above the idle timeout.
ActivityThrottle time.Duration
}
Config configures an Authenticator. Every zero value is the default: a nil Logger is slog.Default() at call time, a nil Bypass is none, a nil Unauthorized is the default 401 or 503 writer, a nil TimeoutSource is the static timeouts, a nil ClientAddr is the default resolver, a nil Verifier is none, the zero Cookie is the default session cookie, zero IdleTimeout and AbsTimeout are DefaultIdleTimeout and DefaultAbsTimeout, and a zero ActivityThrottle writes activity on every request.
type CookieConfig ¶
type CookieConfig struct {
// HTTPS decides the name and the Secure flag under PosturePerRequest,
// and is required there. Pass [RequestIsHTTPS]. A predicate that trusts
// X-Forwarded-Proto only from listed proxies must not be passed: behind
// a TLS proxy the app does not list it answers false, and the cookie
// loses Secure.
HTTPS func(*http.Request) bool
// Persistent reports whether a cookie set on r may outlive the browser
// session. False makes SetCookie drop a positive maxAge, sending neither
// Max-Age nor Expires. Nil means always persistent.
Persistent func(*http.Request) bool
// 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: unset (Lax), Lax or Strict.
// Validate refuses every other value, None included.
SameSite http.SameSite
// Posture selects the deploy-time cookie security posture.
// Default: PostureSecure.
Posture CookiePosture
}
CookieConfig holds the session cookie's attributes. Its cookie methods require a config CookieConfig.Validate accepts: under PosturePerRequest a nil HTTPS panics.
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 CookieConfig.HTTPS (__Host-<base> when it reports true, bare <base> otherwise); in all other postures the request is ignored and the stable EffectiveName() is returned.
func (CookieConfig) Derive ¶
func (c CookieConfig) Derive(suffix string, sameSite http.SameSite) CookieConfig
Derive returns the config for a companion cookie: the same Posture, Path, Domain and HTTPS predicate, the name <base>_<suffix>, the given SameSite, and a nil Persistent (each companion keeps its own lifetime). The derived name always differs from the base name. Derive panics unless suffix matches ^[a-z_]{1,16}$ and sameSite is one Validate accepts (unset, Lax or Strict), because both are fixed by the calling code.
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 named for r. It returns "" unless r carries exactly one cookie of that name, so a planted second cookie cannot choose the session.
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 and sends Cache-Control: no-store. A positive maxAge is dropped when Persistent reports false for r; a negative maxAge (a clear) sends Max-Age=0.
Secure is omitted only for plain-HTTP delivery (PostureInsecureLAN, or PosturePerRequest over HTTP), because a browser never sends a Secure cookie over plain HTTP; gosec G124 and CodeQL go/cookie-secure-not-set flag that conditional as a false positive.
func (*CookieConfig) Validate ¶
func (c *CookieConfig) Validate() error
Validate refuses a configuration browsers would drop or mis-scope: an undeclared Posture; a name, Path or Domain http.Cookie.Valid refuses; a Name over MaxCookieNameBytes, or with a __Secure-, __Host- or __Http- prefix in any letter case; a Path not starting with "/" or over 1024 bytes; a SameSite other than unset, Lax or Strict; a nil HTTPS under PosturePerRequest; and, under a __Host- posture (all but PostureInsecureLAN), a Domain or a Path other than "/". The 4096 bytes of name and value stay the caller's, since Validate never sees the value.
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 CookieConfig.HTTPS.
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 // PosturePerRequest selects the cookie name and Secure flag per request // from [CookieConfig.HTTPS]: __Host-<base> with Secure when it reports // true, and the bare <base> without Secure otherwise. 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) (p Principal, ok bool, err error)
}
CredentialVerifier resolves one credential type. ok true with a nil error grants p. ok false with a nil error means "not my credential", and p is ignored. A non-nil error decides whatever ok says: one matching ErrUnauthenticated means "presented but unusable" (expired, revoked), so the chain continues and that error is the result if nothing later grants; any other stops the chain: ErrInvalidCredential for a refused credential, ErrAuthBackend for a store failure.
type GeneratedKey ¶
type GeneratedKey struct {
// Plaintext is the prefix followed by 64 hex characters (256 random bits).
Plaintext Secret
// Hash is the [APIKeyHash] of Plaintext.
Hash Hash
// DisplayPrefix is the first 8 bytes of Plaintext, all ASCII.
DisplayPrefix string
// DisplaySuffix is the last 4 bytes of Plaintext, all ASCII.
DisplaySuffix string
}
GeneratedKey is a new API key. Plaintext is shown to the user once; Hash, DisplayPrefix and DisplaySuffix are what a store keeps.
func GenerateAPIKey ¶
func GenerateAPIKey(prefix string) (GeneratedKey, error)
GenerateAPIKey generates a new API key with 256 bits of entropy behind prefix (e.g. "ak_"). prefix must match ^[A-Za-z0-9_]{0,16}$, so every byte of the key, and so of its display parts, is ASCII; any other prefix is ErrInvalidKeyPrefix.
Example ¶
package main
import (
"fmt"
"github.com/cplieger/access"
)
func main() {
key, err := access.GenerateAPIKey("ak_")
if err != nil {
panic(err)
}
shown := key.Plaintext.Reveal() // reveal only into the one-time display
fmt.Println(key.Plaintext, shown[:3], len(key.Hash.Reveal()) == 64, key.DisplayPrefix == shown[:8], len(key.DisplaySuffix) == 4)
}
Output: [redacted] ak_ true true true
type Hash ¶
type Hash struct {
// contains filtered or unexported fields
}
Hash holds a stored credential hash: a PHC Argon2id string, or the hex SHA-256 of a session token, an API key or a one-time token. Every printing route (fmt verbs, slog, encoding/json, reflection) renders "[redacted]", masked bytes or an address, or "" for the zero value; only Reveal returns the text. == does not compile on a Hash: compare with Equal, and key an in-memory map on Key. Hash has no decoder: a store writes Reveal() and reads with NewHash.
func APIKeyHash ¶
APIKeyHash returns the hex-encoded SHA-256 hash of a key string.
func SessionHash ¶
SessionHash returns the hex-encoded SHA-256 hash of a plaintext token.
func (Hash) Equal ¶
Equal reports, in constant time for any two values, whether h and o hold the same text: it compares two fixed-size 32-byte tags, never the texts. Two zero values are equal, and a zero value equals no other.
func (Hash) Format ¶
Format writes "[redacted]", or nothing for the zero value, for every verb fmt routes to it.
func (Hash) Key ¶
Key returns h's HashKey, the masked value's tag; the zero Hash gives the zero HashKey.
func (Hash) MarshalJSON ¶
MarshalJSON encodes the redacted rendering as a JSON string.
type HashBudget ¶
type HashBudget struct {
// contains filtered or unexported fields
}
HashBudget bounds the memory all Argon2 work sharing it may hold at once. Build one with NewHashBudget and share it through HasherConfig.Budget: one budget per process bounds every Hasher in it together. The zero value is not usable. Its state is held by pointer, so a copied HashBudget shares it. Waiters are admitted first in, first out.
Example ¶
package main
import (
"fmt"
"github.com/cplieger/access"
)
func main() {
// One budget per process, shared by every Hasher, bounds their memory together.
budget, err := access.NewHashBudget(76 << 20)
if err != nil {
panic(err)
}
passwords, err := access.NewHasher(access.HasherConfig{Budget: budget})
if err != nil {
panic(err)
}
_ = passwords
fmt.Println(budget.Capacity() / access.HashCost(access.DefaultArgon2Params()))
}
Output: 4
func NewHashBudget ¶
func NewHashBudget(bytes int64) (*HashBudget, error)
NewHashBudget returns a budget of bytes. It validates only the capacity, which must be positive; NewHasher checks that its parameters fit.
func (*HashBudget) Capacity ¶
func (b *HashBudget) Capacity() int64
Capacity returns the budget's size in bytes.
type HashKey ¶
type HashKey [32]byte
HashKey is a Hash's comparable form: equal texts give equal keys within the process, so it is a valid map key, and == on it is a fixed-size compare. It reveals nothing a reflective printer of the Hash does not already show. A non-zero key is valid only in the process that made it: a durable index keys on Reveal().
type HashPermit ¶
type HashPermit struct {
// contains filtered or unexported fields
}
HashPermit is one admitted derivation's share of a HashBudget, from Hasher.Reserve. It is used once, by Verify or Release. The zero value is not usable. Its used flag is held by pointer, so a copied permit shares it and the share is returned once.
func (*HashPermit) Release ¶
func (p *HashPermit) Release()
Release returns an unused permit's share; after Verify or Release it does nothing.
func (*HashPermit) Verify ¶
func (p *HashPermit) Verify(password string, encoded Hash) (ok, needsRehash bool, err error)
Verify parses encoded first. A cost at or below the share derives under the share; a cost above it and within Capacity() releases the share and acquires that cost all-or-nothing within the hasher's wait (the timer alone), else returns ErrHashBusy without deriving. A cost above Capacity() derives once under the share at the hasher's own parameters and returns ErrHashInvalid. Verify runs to completion whatever happens to the context passed to Reserve, then releases. On a used permit it derives nothing and returns an error.
type Hasher ¶
type Hasher struct {
// contains filtered or unexported fields
}
Hasher hashes and verifies passwords with Argon2id under a HashBudget. Build one with NewHasher; the zero value is not usable.
Example ¶
package main
import (
"context"
"fmt"
"github.com/cplieger/access"
)
func main() {
hasher, err := access.NewHasher(access.HasherConfig{})
if err != nil {
panic(err)
}
ctx := context.Background()
hash, err := hasher.Hash(ctx, "correct horse battery staple")
if err != nil {
panic(err) // access.ErrHashBusy: the budget stayed full for the whole wait
}
ok, needsRehash, err := hasher.Verify(ctx, "correct horse battery staple", hash)
fmt.Println(ok, needsRehash, err)
// For an unknown username, verify against the zero Hash: it costs the same.
ok, _, err = hasher.Verify(ctx, "correct horse battery staple", access.Hash{})
fmt.Println(ok, err)
}
Output: true false <nil> false <nil>
func NewHasher ¶
func NewHasher(cfg HasherConfig) (*Hasher, error)
NewHasher builds a Hasher. It refuses non-zero Params that fail Argon2Params.Validate, a negative Wait, and a Budget smaller than HashCost(Params) with ErrHashBudgetTooSmall.
func (*Hasher) Hash ¶
Hash returns the PHC string of password, NFC-normalised, as a Hash, or ErrHashBusy when the budget cannot admit it within the wait or ctx.
func (*Hasher) NeedsRehash ¶
NeedsRehash reports whether encoded is unparseable, out of bounds, or made with parameters other than the hasher's.
func (*Hasher) Reserve ¶
func (h *Hasher) Reserve(ctx context.Context) (*HashPermit, error)
Reserve takes one derivation's share of the budget, HashCost of the hasher's params, waiting as Hash does, or returns ErrHashBusy. Callers defer HashPermit.Release; it does nothing after HashPermit.Verify.
func (*Hasher) Verify ¶
func (h *Hasher) Verify(ctx context.Context, password string, encoded Hash) (ok, needsRehash bool, err error)
Verify derives once unless it returns ErrHashBusy. A zero, malformed or out-of-bounds stored hash derives at the hasher's own parameters and reports (false, false, nil), so every arm costs the same. needsRehash reports a parsed stored hash made with parameters other than the hasher's. Verify is Hasher.Reserve followed by HashPermit.Verify, and returns the error of either; ctx bounds only the reservation.
type HasherConfig ¶
type HasherConfig struct {
// Budget bounds this Hasher's derivations. Passing the same budget to
// every Hasher makes one bound cover them all; a nil Budget gets a
// private one.
Budget *HashBudget
// Params are the Argon2id parameters.
Params Argon2Params
// Wait is how long Hash, Verify and Reserve wait for the budget before
// [ErrHashBusy]. The caller's context also bounds Hash and Reserve,
// including Verify's reservation; a permit's wait for a costlier stored
// hash is bounded by Wait alone.
Wait time.Duration
}
HasherConfig configures a Hasher. Every zero value is the default: the zero Params is DefaultArgon2Params, a nil Budget is a private budget of 4 × HashCost(Params), and a zero Wait is 2 s.
type InvalidCredentialError ¶
type InvalidCredentialError struct {
// Err is [ErrInvalidAPIKey], [ErrAccountDisabled] or
// [ErrRestrictedSession], or nil for a granted principal refused only
// for an empty Method.
Err error
// Method is the refused credential's: [MethodAPIKey] for an API key, a
// recovery session's AuthMethod, the granted principal's own Method for
// a refused grant.
Method Method
// KeyID is the ID of the stored key a refused API key named, set only
// when the store found it (expired, owner missing or disabled) and zero
// otherwise, so a refusal carries no byte of a presented value.
KeyID int64
}
InvalidCredentialError is the detail of ErrInvalidCredential; the error matches both ErrInvalidCredential and Err.
func (*InvalidCredentialError) Error ¶
func (e *InvalidCredentialError) Error() string
func (*InvalidCredentialError) Unwrap ¶
func (e *InvalidCredentialError) Unwrap() []error
Unwrap returns ErrInvalidCredential and Err, when set.
type Key ¶
type Key struct {
CreatedAt time.Time `json:"created_at"`
ExpiresAt time.Time `json:"expires_at,omitzero"` // zero = never
LastUsedAt time.Time `json:"last_used_at,omitzero"` // written through a throttled touch
KeyHash Hash `json:"-"`
KeyPrefix string `json:"key_prefix"`
KeySuffix string `json:"key_suffix"`
Label string `json:"label"`
Scopes []string `json:"scopes"` // opaque to the library; the app's vocabulary
// LineageIDs is the key's ancestor path, fixed at mint: root first, the
// key's own ID last. A key minted by a key has its parent's path plus its
// own ID; a key a session or an out-of-band actor minted has its own ID
// alone. Revoking a key revokes every key whose path contains it, and
// every KeyAttribution records the acting key's path. Store key IDs are
// never reused, so a path names its keys for the life of the store.
LineageIDs []int64 `json:"lineage_ids"`
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 record. It returns ErrInvalidAPIKey when the store finds no key, answers found with a nil key, holds a key whose stored hash is not the computed one, or holds a key whose ExpiresAt is set and not after now: the Authenticator refuses a key from the same instant. A store error is returned as is.
Example ¶
package main
import (
"context"
"fmt"
"github.com/cplieger/access"
"github.com/cplieger/access/accesstest"
)
func main() {
ctx := context.Background()
store := accesstest.NewMemStore()
bot := &access.User{
Username: "bot",
Role: access.RoleUser,
Enabled: true,
}
if err := store.CreateUser(ctx, bot); err != nil {
panic(err)
}
generated, err := access.GenerateAPIKey("ak_")
if err != nil {
panic(err)
}
if err := store.CreateAPIKey(ctx, &access.Key{
UserID: bot.ID,
KeyHash: generated.Hash,
KeyPrefix: generated.DisplayPrefix,
KeySuffix: generated.DisplaySuffix,
Label: "ci",
}); err != nil {
panic(err)
}
key, err := access.VerifyAPIKey(ctx, store, generated.Plaintext.Reveal())
fmt.Println(key != nil, err == nil)
}
Output: true true
func (Key) ParentKeyID ¶
ParentKeyID is the key that minted k (the second-last ID of LineageIDs), or 0 for a key a session or an out-of-band actor minted.
type KeyAttribution ¶
type KeyAttribution struct {
At time.Time `json:"at"`
Action AttributionAction `json:"action"`
// KeyLineage is the acting or issuing key's LineageIDs as read inside
// the writing update: root first, that key last.
KeyLineage []int64 `json:"key_lineage"`
ID int64 `json:"id"` // assigned by the store, increasing in append order
UserID int64 `json:"user_id"`
}
KeyAttribution is one append-only record that a key acted on a user. It is written in the same store update as the act, never updated, and deleted only with its user; revoking or deleting the key, or disabling the user, leaves it.
func (*KeyAttribution) Clone ¶
func (a *KeyAttribution) Clone() *KeyAttribution
Clone returns a deep copy, or nil for a nil a.
func (KeyAttribution) Contains ¶
func (a KeyAttribution) Contains(keyID int64) bool
Contains reports whether keyID is in KeyLineage.
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 Method ¶
type Method string
Method names how a principal was authenticated. Values outside the constants below are app-defined and opaque to the library.
const ( MethodPassword Method = "password" MethodPasskey Method = "passkey" MethodOIDC Method = "oidc" MethodRecovery Method = "recovery" // the restricted session a recovery token opens MethodAPIKey Method = "api_key" MethodBypass Method = "bypass" )
Auth method identifiers stored in sessions and used for method guards.
type MethodAvailability ¶
type MethodAvailability struct {
// PasskeyCount is the number of the user's passkeys, leaving out one
// being removed.
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 the authentication methods one user keeps after a removal: what can sign in now and remains, not what is held. A caller removing a passkey who passes the held passkey count counts the removed passkey as remaining. The three method signals would otherwise sit as adjacent same-typed bool parameters, where a silent swap flips which method counts as remaining. The zero value reports no method available, so CanDisableMethod refuses every removal; an omitted field undercounts the remaining methods and can only make the answer more conservative.
type OIDCIdentity ¶
OIDCIdentity is an account's link to an identity provider. The zero value means unlinked.
func (OIDCIdentity) IsZero ¶
func (i OIDCIdentity) IsZero() bool
IsZero reports whether i links no identity.
type OneTimeToken ¶
type OneTimeToken struct {
CreatedAt time.Time
ExpiresAt time.Time
Hash Hash `json:"-"`
Purpose TokenPurpose
Role Role // PurposeInvite only: the role the invited account receives
Subject int64 // the user the token acts on; 0 for setup and invite
// IssuedByKey is the API key whose principal issued this invite or
// recovery token; 0 when a session or an out-of-band actor issued it. A
// key-issued token expires no later than that key, dies with it, and is
// re-checked against it when used.
IssuedByKey int64
}
OneTimeToken is the stored record of a single-use token.
func (OneTimeToken) LogValue ¶
func (t OneTimeToken) LogValue() slog.Value
LogValue emits the purpose, subject, issuer key and expiry, never Hash.
type PasskeyCredential ¶
type PasskeyCredential struct {
CreatedAt time.Time `json:"created_at"`
LastUsedAt time.Time `json:"last_used_at,omitzero"`
// Discoverable is the credProps.rk extension output; nil means the client
// did not report it. Registration requests credProps and refuses a reported
// false, so a stored false should not occur. It is the only extension output
// stored, because credProps is the only extension requested.
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, written at registration
// and by each login's [PasskeyLoginUpdate]; it is the only flag input this
// library reads, and it keeps the AT and ED bits the booleans below drop.
// Those booleans are a decoded view nothing here reads back. A store MUST
// persist the octet: a real registration sets user presence, so a zero
// octet means the store dropped it, and go-webauthn then refuses the next
// login whose authenticator asserts backup eligibility (rule 8 of the
// account package's store contract).
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.
func (*PasskeyCredential) Clone ¶
func (c *PasskeyCredential) Clone() *PasskeyCredential
Clone returns a deep copy, or nil for a nil c.
type PasskeyLoginUpdate ¶
PasskeyLoginUpdate is the custody write after an assertion. It carries the flags octet, which the store decodes with DecodePasskeyFlags, so the octet and the booleans cannot diverge.
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 PasswordContext ¶
type PasswordContext struct {
// Username is compared only when it has at least four runes after NFC.
Username string
// ForbiddenWords are app-specific words (site name, product name) the
// password must not be; an entry of only digits, spaces and punctuation
// refuses only a password equal to it.
ForbiddenWords []string
}
PasswordContext carries the user-specific values a candidate password must not be. A field-named struct keeps the password and the username from being swapped silently as adjacent same-typed parameters.
WARNING: the zero value FAILS OPEN: an empty Username and an empty ForbiddenWords compare against nothing, so a partial literal silently validates less. Populate every field the account has.
type PasswordError ¶
type PasswordError struct {
Reason PasswordRejection
Min, Max int
}
PasswordError reports a policy refusal. Min and Max carry the length bounds for "too_short" and "too_long" and are zero for every other Reason.
func (*PasswordError) Error ¶
func (e *PasswordError) Error() string
Error describes the refusal without the password.
type PasswordRejection ¶
type PasswordRejection string
PasswordRejection names why a password was refused; PasswordRejections lists every value, each stable data for UIs.
const ( PasswordTooShort PasswordRejection = "too_short" PasswordTooLong PasswordRejection = "too_long" PasswordContainsUsername PasswordRejection = "contains_username" PasswordContainsForbiddenWord PasswordRejection = "contains_forbidden_word" PasswordCommon PasswordRejection = "common" PasswordBreached PasswordRejection = "breached" )
The rejections, in PasswordRejections order. This package's validators return the first five; PasswordBreached is for a caller that refuses a password CheckBreachedPassword reports breached.
func PasswordRejections ¶
func PasswordRejections() []PasswordRejection
PasswordRejections returns every PasswordRejection, in a stable order.
type Principal ¶
type Principal struct {
// AuthTime is the session's last primary sign-in or step-up; session
// principals only.
AuthTime time.Time
// IdleDeadline and AbsoluteDeadline are when this principal lapses if
// nothing else happens. A session's are its [SessionDeadlines]; a key's
// AbsoluteDeadline is its non-zero ExpiresAt and its IdleDeadline zero;
// both are zero for a key with no expiry and for every other principal.
// A stream ends itself at the earlier non-zero one without a store read.
IdleDeadline time.Time
AbsoluteDeadline time.Time
User *User
Method Method
// SessionID and SessionKind name the session; session principals only.
SessionID string
SessionKind SessionKind
// Scopes are a key's or a custom verifier's scopes; nil for sessions.
Scopes []string
// KeyID is the authenticating key; MethodAPIKey only.
KeyID int64
// contains filtered or unexported fields
}
Principal is the outcome of authenticating one request.
func (Principal) IsAPIKey ¶
IsAPIKey reports a principal the built-in API-key verifier produced. A custom verifier's principal never passes it, whatever its Method and KeyID.
func (Principal) IsRecoverySession ¶
IsRecoverySession reports a principal the built-in session verifier produced from a SessionRecovery session.
func (Principal) IsSession ¶
IsSession reports a principal the built-in session verifier produced from a full session (SessionFull). Keys, custom verifiers and the bypass never pass it.
func (Principal) LogValue ¶
LogValue emits the method, the user's ID, the session ID and kind, the key ID and the scopes; never the credential hash.
func (Principal) SessionTokenHash ¶
SessionTokenHash returns the stored hash of the session that produced p, or the zero Hash for any other principal.
type Rechecker ¶
type Rechecker interface {
Recheck(ctx context.Context, p Principal) (q Principal, ok bool, err error)
}
Rechecker re-validates a principal for a long-lived connection without writing activity. ok false with a nil error means "not a principal I produced", which Authenticator.Recheck answers as ErrNotRecheckable; a non-nil error is the re-validation's refusal.
type Role ¶
type Role string
Role is a typed string identifying a user's authorization level. Values outside the constants are app-defined.
type Sealer ¶
type Sealer struct {
// contains filtered or unexported fields
}
Sealer seals short payloads with AES-256-GCM under a key ring. The first key seals; every key opens, so a ring can rotate (current, then previous). Build one with NewSealer or NewEphemeralSealer; the zero value opens nothing, and its Seal panics on any payload within MaxSealPayload.
The ring is held masked, and each call builds its cipher from an opened key and drops it, so no field holds a key or its expanded schedule and no printer, reflection-based ones included, can show one.
func NewEphemeralSealer ¶
func NewEphemeralSealer() *Sealer
NewEphemeralSealer returns a Sealer under one random key that no one else holds, so what it seals cannot be opened after a restart.
func NewSealer ¶
NewSealer returns a Sealer whose first key seals and whose every key opens. It takes 1 to 4 keys of SealerKeySize bytes each and copies them; an error names the count or the bad key's index, never its bytes.
func (*Sealer) Open ¶
Open returns the payload of a value Seal made for purpose, trying each key in ring order. It returns ErrSealInvalid for anything it cannot authenticate, a value over 4096 bytes refused before decoding, and ErrSealExpired for an authentic value when now is not before its expiry.
func (*Sealer) Seal ¶
Seal returns base64url(nonce || ciphertext) of payload under the first key, with expires sealed inside and purpose bound as additional data, so a payload sealed for one cookie cannot open as another. A payload longer than MaxSealPayload is refused with ErrSealTooLarge, so Open never refuses what Seal accepted. Every value carries a random 96-bit nonce, whichever GCM constructor the build accepts, so a first key seals at most 2^32 values: before then, put a new key first and keep the old one after it.
type Secret ¶
type Secret struct {
// contains filtered or unexported fields
}
Secret holds a plaintext credential. Every printing route (fmt verbs, slog, encoding/json, reflection) renders "[redacted]", masked bytes or an address, or "" for the zero value; only Reveal returns the text. The plaintext is never held in clear, so a printer walking any holder's fields by reflection (%p of a struct value, go-cmp, go-spew) finds only masked bytes. == does not compile on a Secret. A Secret is not a wire or storage type and has no decoder: a caller converts at its seam, with NewSecret on a decoded string and Reveal on the way out.
func (Secret) Format ¶
Format writes "[redacted]", or nothing for the zero value, for every verb fmt routes to it.
func (Secret) MarshalJSON ¶
MarshalJSON encodes the redacted rendering as a JSON string, which nothing decodes.
type Session ¶
type Session struct {
CreatedAt time.Time
LastActivity time.Time
// AuthTime is the last primary sign-in or step-up.
AuthTime time.Time
ID string // 128-bit random hex; stable across a token rotation
TokenHash Hash `json:"-"`
AuthMethod Method
Kind SessionKind
UserAgent string // sanitised and capped at 256 bytes by its writer
Label string // user-editable, at most 64 runes
LastIP string // netip.Addr.String() of the client, as its writer last recorded it
UserID int64
// IssuedByKey is set on a SessionRecovery session only: the IssuedByKey
// of the recovery token that opened it, so completion re-checks that key
// and attributes the credential it sets to that key's lineage; 0
// otherwise.
IssuedByKey int64
// IdleCap and AbsoluteCap are this session's own idle and absolute
// limits; a zero or negative cap is none. [SessionDeadlines] applies them.
IdleCap time.Duration
AbsoluteCap time.Duration
}
Session is a server-side session record. Its wire view is the HTTP layer's, so it carries no JSON tags beyond keeping the hash out.
type SessionActivity ¶
SessionActivity is what an active verified request writes back.
type SessionActivityUpdater ¶
type SessionActivityUpdater interface {
UpdateSessionActivity(ctx context.Context, tokenHash Hash, act SessionActivity) error
}
SessionActivityUpdater writes an active verified request's activity back to its session. For a hash no session has, it writes nothing and returns nil. It stores act's LastActivity and LastIP only when act.At is after the stored LastActivity, atomically; an older or equal At writes nothing, LastIP included, and returns nil.
type SessionKind ¶
type SessionKind string
SessionKind distinguishes an ordinary session from a restricted one.
const ( SessionFull SessionKind = "" // an ordinary signed-in session SessionRecovery SessionKind = "recovery" // may only add or replace a sign-in method )
Session kinds.
type SessionReader ¶
type SessionReader interface {
SessionByHash(ctx context.Context, tokenHash Hash) (sess *Session, found bool, err error)
}
SessionReader finds session data by token hash.
type SessionRef ¶
SessionRef names one session of one user; the zero value matches nothing.
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, so a swap of two adjacent durations cannot leave the idle timeout unbounded. Both fields are required: a zero field, a partial literal included, expires every session instantly, and a zero pair passed to a store's CleanupExpiredSessions would delete every session, which account never passes and a store may refuse. It fails closed (lockout, never a bypass).
type TokenPurpose ¶
type TokenPurpose string
TokenPurpose names what a one-time token unlocks. Values outside the constants are app-defined.
const ( PurposeSetup TokenPurpose = "setup" PurposeRecovery TokenPurpose = "recovery" // out-of-band recovery and admin-issued reset PurposeInvite TokenPurpose = "invite" )
One-time token purposes.
type User ¶
type User struct {
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Username string `json:"username"` // canonical form; see NormalizeUsername
Email string `json:"email,omitempty"`
DisplayName string `json:"display_name,omitempty"`
PasswordHash Hash `json:"-"`
Role Role `json:"role"`
OIDC OIDCIdentity `json:"-"`
// WebAuthnHandle is the account's WebAuthn user handle, which an
// authenticator returns during a discoverable login. Set it once with
// [GenerateWebAuthnHandle] and never change it: every registered passkey is
// bound to it, so a new handle orphans them all. It is derived from no other
// field, because an authenticator may reveal it without verifying the user.
WebAuthnHandle []byte `json:"-"`
ID int64 `json:"id"`
Enabled bool `json:"-"`
}
User represents an authenticated user account. It carries no key attribution: what a key did to a user is a KeyAttribution record.
Source Files
¶
- apikey.go
- apikey_verifier.go
- auth_cookie.go
- clientaddr.go
- cookie_config.go
- errors.go
- hash.go
- hashbudget.go
- hasher.go
- masked.go
- middleware.go
- options.go
- password.go
- password_validate.go
- principal.go
- sealer.go
- secret.go
- session.go
- session_verifier.go
- store_iface.go
- token.go
- types.go
- username.go
- verifier.go
- webauthn_handle.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package accesshttp serves the access HTTP routes over an account.Service.
|
Package accesshttp serves the access HTTP routes over an account.Service. |
|
Package accesstest supports tests of access and its stores: MemStore is an in-memory account.Store for consumer tests, not for production, and StoreContract runs account's store contract against any store.
|
Package accesstest supports tests of access and its stores: MemStore is an in-memory account.Store for consumer tests, not for production, and StoreContract runs account's store contract against any store. |
|
Package account defines the store SPI: the role interfaces a store implements, the Tx that groups them inside one Store.Update, the Sweeper the background sweep calls, and the contract every store keeps.
|
Package account defines the store SPI: the role interfaces a store implements, the Tx that groups them inside one Store.Update, the Sweeper the background sweep calls, and the contract every store keeps. |
|
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. |
|
blocklist
Package blocklist holds the embedded list of common passwords access refuses, generated from SecLists by "go generate ./internal/blocklist", and the fold the password-context and common-password checks share.
|
Package blocklist holds the embedded list of common passwords access refuses, generated from SecLists by "go generate ./internal/blocklist", and the fold the password-context and common-password checks share. |
|
capture
Package capture is an access-internal test helper: a slog.Handler that records log records so tests can assert on access's logging decisions, plus a helper to install it as the default logger.
|
Package capture is an access-internal test helper: a slog.Handler that records log records so tests can assert on access'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. |
|
cmd/genblocklist
command
Command genblocklist regenerates internal/blocklist/common.txt from the SecLists password lists at blocklist.SeclistsCommit.
|
Command genblocklist regenerates internal/blocklist/common.txt from the SecLists password lists at blocklist.SeclistsCommit. |
|
failreason
Package failreason carries why a refusal happened beside the public sentinel a client sees, so accesshttp can audit it or name it in an error body while every caller's errors.Is and error text stay the sentinel's.
|
Package failreason carries why a refusal happened beside the public sentinel a client sees, so accesshttp can audit it or name it in an error body while every caller's errors.Is and error text stay the sentinel's. |
|
printcheck
Package printcheck finds a secret a printer could show.
|
Package printcheck finds a secret a printer could show. |
|
Package oidc signs a user in with an OpenID Connect provider, on coreos/go-oidc.
|
Package oidc signs a user in with an OpenID Connect provider, on coreos/go-oidc. |
|
Package ratelimit admits authentication attempts against sliding windows of failures per IP key, per account and per trusted device, and counts requests on anonymous begin routes per IP key.
|
Package ratelimit admits authentication attempts against sliding windows of failures per IP key, per account and per trusted device, and counts requests on anonymous begin routes per IP key. |
|
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. |