Documentation
¶
Overview ¶
Package access holds the building blocks of sign-in: the Authenticator that guards a route with session and idle/absolute timeouts, Argon2id password hashing in PHC string format, session and API-key tokens, cookies, Secret, Hash and Sealer, and the role check. Passkeys live in webauthn, TOTP codes in totp, OIDC in oidc, the account operations in account and their routes in accesshttp.
Index ¶
- Constants
- Variables
- 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 ErrorReasons() []string
- 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, ttl time.Duration, now time.Time) (plaintext Secret, rec OneTimeToken)
- func NormalizeUsername(username string) (string, error)
- func Passive(ctx context.Context) context.Context
- func RequireRecentAuth(p Principal, maxAge time.Duration, now time.Time) error
- func SessionDeadlines(s *Session, t SessionTimeouts) (idle, absolute time.Time)
- func StatusOf(code Code) int
- 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 AuditEvent
- type Authenticator
- func (a *Authenticator) Authenticate(r *http.Request) (Principal, error)
- func (a *Authenticator) Challenge(h http.Header, code Code, scope string)
- 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) Timeouts() SessionTimeouts
- func (a *Authenticator) UseSessionRevoker(r SessionRevoker) error
- type AuthenticatorAttachment
- type AuthenticatorStore
- type ClientAddr
- type Code
- type Config
- type CookieConfig
- func (c *CookieConfig) ClearCookie(w http.ResponseWriter, secure bool)
- func (c *CookieConfig) CookieName(secure bool) string
- func (c CookieConfig) Derive(suffix string, sameSite http.SameSite) CookieConfig
- func (c *CookieConfig) ReadCookie(r *http.Request, secure bool) string
- func (c *CookieConfig) SetCookie(w http.ResponseWriter, secure bool, value string, maxAge int)
- func (c *CookieConfig) Validate() error
- type CookiePosture
- type CredentialVerifier
- type Error
- type ErrorWriter
- type GeneratedKey
- type Hash
- type HashBudget
- type HashKey
- type HashPermit
- type Hasher
- type HasherConfig
- type InvalidCredentialError
- type Key
- type KeyAttribution
- type KeyRef
- type KeySecret
- 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 RecoveryCode
- type Role
- type Sealer
- func (s *Sealer) IsZero() bool
- func (s *Sealer) Open(purpose, sealed string, now time.Time) ([]byte, error)
- func (s *Sealer) OpenAtRest(purpose, sealed string) (payload []byte, current bool, err error)
- func (s *Sealer) Seal(purpose string, payload []byte, expires time.Time) (string, error)
- func (s *Sealer) SealAtRest(purpose string, payload []byte) (string, error)
- type Secret
- type Session
- type SessionActivity
- type SessionActivityUpdater
- type SessionReader
- type SessionRef
- type SessionRevoker
- type SessionTimeouts
- type TOTP
- type TemporaryPassword
- type TokenPurpose
- type User
- type UserReader
- type Via
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 ( // ReasonTransportChanged is a session presented on the other transport, // answered with [CodeSessionExpired] once the session is revoked. ReasonTransportChanged = failreason.TransportChanged // ReasonSignInAgain is [RequireRecentAuth] refusing a plain session, // answered with [CodeRecentAuthRequired]: a step-up cannot run over // plain HTTP, so the client asks for a fresh sign-in. ReasonSignInAgain = failreason.SignInAgain )
The Error Reason values access assigns, in ErrorReasons order.
const ( PlainSessionIdle = 30 * time.Minute PlainSessionAbsolute = 12 * time.Hour )
PlainSessionIdle and PlainSessionAbsolute bound a plain session (Secure false), whatever the policy timeouts: its token crossed a network in clear, so it lives no longer than one sitting.
const DefaultRealm = "access"
DefaultRealm is what an empty Config.Realm means.
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 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 §5.4.3 caps a user handle at 64 bytes, and WebAuthn §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") // ErrSessionTransport is the detail for a session presented on the // other transport than the one it was created on (see // [Session.Secure]); the session verifier revokes it. ErrSessionTransport = errors.New("access: session bound to the other transport") // ErrHTTPSRequired refuses a plain request ([ClientAddr.Secure] false) // where only a secure one is served: [Authenticator.Authenticate]'s // answer under [PostureSecure]. It wraps no other error, so it stops // the chain. ErrHTTPSRequired = errors.New("access: HTTPS required") )
Errors of authentication. A verifier's or the Authenticator's refusal carries one of the first three or ErrHTTPSRequired; 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 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 ErrorReasons ¶
func ErrorReasons() []string
ErrorReasons returns every Reason access assigns, in a stable order.
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. A nil user has no 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, 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 activity: presence receipts, polling, stream reconnects. The credential is still fully verified; only the session's activity write and the key's touch are skipped. A key's first use, LastUsedAt zero, is still touched, because it ends a rotation's overlap.
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. The refusal of such a session over plain HTTP (Secure false) carries ReasonSignInAgain, since only a fresh sign-in refreshes its AuthTime. An AuthTime after now is refused on purpose: this gate guards a sensitive operation and fails closed where it cannot place the proof of a 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 PlainSessionIdle and PlainSessionAbsolute for a plain session (Secure false), and to the session's positive IdleCap or AbsoluteCap. s must not be nil.
func StatusOf ¶
StatusOf is the HTTP status a refusal with code answers, 0 for a code Codes does not list.
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 holding no ASCII control byte (0x00 to 0x1F, 0x7F) anywhere, its fragment included, 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 finds the key whose KeyHash, or whose non-zero
// PreviousHash, equals hash, as its current record; a zero hash finds
// nothing.
APIKeyByHash(ctx context.Context, hash Hash) (key *Key, found bool, err error)
}
APIKeyReader validates API keys (looked up by hash).
type APIKeyToucher ¶
type APIKeyToucher interface {
// TouchAPIKey sets LastUsedAt to at only when the stored KeyHash equals
// hash and at is after the stored LastUsedAt, comparing and writing in
// one atomic step. Otherwise, an ID no key has included, it writes
// nothing and returns nil, so a touch sampled before a rotation, which
// carries the superseded hash, never ends the new overlap.
TouchAPIKey(ctx context.Context, keyID int64, hash Hash, at time.Time) error
}
APIKeyToucher records a use of a key's current secret as its LastUsedAt.
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 AttributionEnabled AttributionAction = "enabled" // UpdateUser by a key re-enabled the user AttributionDisabled AttributionAction = "disabled" // UpdateUser by a key disabled the user // AttributionTemporaryPasswordSet is SetTemporaryPassword by a key. AttributionTemporaryPasswordSet AttributionAction = "temporary_password_set" )
Attribution actions.
type AuditEvent ¶
type AuditEvent struct {
Kind string // "login.success", "login.pending", "login.failure", "login.rate_limited", "setup.failure", ...
Username string // canonical, or "" when the input was refused; never the raw input
IP string
Method Method
// Reason is a code-like class: "invalid_credentials", "method_locked",
// "provider_error:access_denied", "exchange_failed".
Reason string
SessionID string
UserID int64
KeyID int64
Success bool
}
AuditEvent is one request-level outcome that changes no state: a failure, a refusal or a rate limit, and the sign-ins beside them. It carries no raw request text: no user agent, no provider error_description, no typed username that failed normalisation.
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). It refuses, before building any verifier, a nil store, a store or cfg.Verifier holding a nil pointer, map, slice, func or chan, a negative timeout or throttle, a throttle not below the idle timeout, a Realm holding '"', '\' or a control character, and a Cookie CookieConfig.Validate refuses, so a miswired app fails at startup.
func (*Authenticator) Authenticate ¶
func (a *Authenticator) Authenticate(r *http.Request) (Principal, error)
Authenticate runs the chain on r and returns the first Principal a verifier grants, with IP and Secure from Config.ClientAddr's answer and copies of User and Scopes; else the first error matching ErrUnauthenticated a verifier returned, or bare ErrUnauthenticated, and any other verifier error at once. A granted principal whose User is nil or disabled, or whose Method is empty, is refused with an *InvalidCredentialError. A plain request claiming https logs a rate-limited WARN, and under PostureSecure gets ErrHTTPSRequired first.
func (*Authenticator) Challenge ¶
func (a *Authenticator) Challenge(h http.Header, code Code, scope string)
Challenge sets h's one WWW-Authenticate for a refusal answered with code (RFC 6750 §3 and §3.1), realm Config.Realm: auth_key_invalid gets error="invalid_token"; auth_scope_required gets error="insufficient_scope" and, when scope is set, scope="S"; every other 401, and auth_key_required, gets the bare Bearer realm="R"; any other code leaves h unchanged. scope is empty or one RFC 6750 scope-token; any other panics, as a programming error.
func (*Authenticator) ClientAddr ¶
func (a *Authenticator) ClientAddr(r *http.Request) ClientAddr
ClientAddr returns the Config.ClientAddr resolver's answer for r as it is, Via included; every address the library records or limits on comes from it.
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) 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.
func (*Authenticator) UseSessionRevoker ¶
func (a *Authenticator) UseSessionRevoker(r SessionRevoker) error
UseSessionRevoker registers r as the revoker of every session refused for its transport. It refuses a nil r and a second registration; with none registered, such a session is refused but left in the store.
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 {
Peer netip.Addr // the connection's remote address, unmapped
Forwarded netip.Addr // the client a trusted proxy forwarded; read only under ViaProxy
Via Via
// Secure reports that the request crossed no network in clear: TLS
// ended at this server or at a proxy the resolver trusts.
Secure bool
}
ClientAddr is how the app's resolver (Config.ClientAddr) answered for the caller; the library never reads a forwarding header to decide an address. The zero value is ViaUnknown and plain.
func (ClientAddr) IP ¶
func (c ClientAddr) IP() netip.Addr
IP is the client address: Forwarded under ViaProxy, else Peer.
type Code ¶
type Code string
Code is a stable error code; Codes lists every one.
const ( CodeAuthRequired Code = "auth_required" CodeSessionExpired Code = "auth_session_expired" CodeInvalidCredentials Code = "auth_invalid_credentials" //nolint:gosec // G101: an error code, not a credential CodeKeyInvalid Code = "auth_key_invalid" CodeRecentAuthRequired Code = "auth_recent_auth_required" CodeSessionRequired Code = "auth_session_required" CodeScopeRequired Code = "auth_scope_required" CodeKeyRequired Code = "auth_key_required" CodeHTTPSRequired Code = "auth_https_required" CodeForbidden Code = "auth_forbidden" CodeRateLimited Code = "auth_rate_limited" CodeBusy Code = "auth_busy" CodeBadRequest Code = "auth_bad_request" CodeBodyTooLarge Code = "auth_body_too_large" CodeUsernameInvalid Code = "auth_username_invalid" CodeUsernameTaken Code = "auth_username_taken" CodeKeyLabelTaken Code = "auth_key_label_taken" CodePasswordRejected Code = "auth_password_rejected" CodePasswordLoginDisabled Code = "auth_password_login_disabled" CodeCodeInvalid Code = "auth_code_invalid" CodeSecondFactorRequired Code = "auth_second_factor_required" CodeTOTPDisabled Code = "auth_totp_disabled" CodeSetupComplete Code = "auth_setup_complete" CodeSetupTokenRequired Code = "auth_setup_token_required" //nolint:gosec // G101: an error code, not a credential CodeRegistrationClosed Code = "auth_registration_closed" CodeRegistrationFull Code = "auth_registration_full" CodeTokenInvalid Code = "auth_token_invalid" //nolint:gosec // G101: an error code, not a credential CodeLastMethod Code = "auth_last_method" CodeIdentityTaken Code = "auth_identity_taken" CodeAlreadyLinked Code = "auth_already_linked" CodeMethodNotLocked Code = "auth_method_not_locked" CodeCrossOrigin Code = "auth_cross_origin" CodeDuplicateCredential Code = "auth_duplicate_credential" //nolint:gosec // G101: an error code, not a credential CodeUnknownScope Code = "auth_unknown_scope" CodeOriginRefused Code = "auth_origin_refused" CodeCeremonyInvalid Code = "auth_ceremony_invalid" CodeNotDiscoverable Code = "auth_not_discoverable" CodeUnknownCredential Code = "auth_unknown_credential" //nolint:gosec // G101: an error code, not a credential CodeAssertionFailed Code = "auth_assertion_failed" CodeRegistrationFailed Code = "auth_registration_failed" CodeOIDCFailed Code = "auth_oidc_failed" CodeSSOOnly Code = "auth_sso_only" CodeNotFound Code = "auth_not_found" CodeMethodNotAllowed Code = "auth_method_not_allowed" )
The codes, in Codes order.
type Config ¶
type Config struct {
// Logger receives the warnings and debug lines.
Logger *slog.Logger
// Realm is the realm of every challenge [Authenticator.Challenge] writes.
// [New] refuses one holding '"', '\' or a control character, so it
// quotes as it is.
Realm string
// Bypass reports whether authentication is bypassed. While it returns
// true, [Authenticator.Authenticate] grants [MethodBypass] to every
// request, a plain one under [PostureSecure] excepted, 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
// 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]. Its answer's Via says how the request
// arrived. Authenticate calls it once per request and accesshttp and gate
// call it again, so it must answer the same for one request. Nil treats
// no peer as a proxy: Peer is r.RemoteAddr's address, unmapped, Secure is
// r.TLS != nil, and Via is [ViaDirect], or [ViaUntrustedForwarding] when
// Forwarded, X-Forwarded-For, X-Real-IP or X-Forwarded-Proto 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 key's
// first use, LastUsedAt zero, is written whatever the throttle. 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), so a session in use never expires between two writes. [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 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, an empty Realm is DefaultRealm, zero IdleTimeout and AbsTimeout are DefaultIdleTimeout and DefaultAbsTimeout, and a zero ActivityThrottle writes activity on every request.
type CookieConfig ¶
type CookieConfig struct {
// Name is the base cookie name (without __Host- prefix).
// Default: "auth_session".
Name 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. Each cookie method takes the request's transport, the ClientAddr.Secure the app's resolver answers for it. Every cookie is HttpOnly with Path "/" and no Domain, as the __Host- prefix requires.
func DefaultCookieConfig ¶
func DefaultCookieConfig() CookieConfig
DefaultCookieConfig returns a CookieConfig with secure defaults.
func (*CookieConfig) ClearCookie ¶
func (c *CookieConfig) ClearCookie(w http.ResponseWriter, secure bool)
ClearCookie clears the cookie named for a request whose transport is secure.
func (*CookieConfig) CookieName ¶
func (c *CookieConfig) CookieName(secure bool) string
CookieName returns the cookie name for a request whose transport is secure: __Host-<base>, unless Posture is PosturePerRequest and secure is false, which gives the bare <base>.
func (CookieConfig) Derive ¶
func (c CookieConfig) Derive(suffix string, sameSite http.SameSite) CookieConfig
Derive returns the config for a companion cookie: the same Posture, the name <base>_<suffix> and the given SameSite. 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) ReadCookie ¶
func (c *CookieConfig) ReadCookie(r *http.Request, secure bool) string
ReadCookie reads the cookie named for a request whose transport is secure, never the other transport's name. 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, secure bool, value string, maxAge int)
SetCookie sets the cookie for a request whose transport is secure, and sends Cache-Control: no-store. A plain request's cookie ends with the browser: a positive maxAge is dropped, so it carries neither Max-Age nor Expires. A negative maxAge (a clear) sends Max-Age=0.
func (*CookieConfig) Validate ¶
func (c *CookieConfig) Validate() error
Validate refuses a configuration browsers would drop: an undeclared Posture; a Name http.Cookie.Valid refuses, one over MaxCookieNameBytes, or one with a __Secure-, __Host- or __Http- prefix in any letter case; and a SameSite other than unset, Lax or Strict. The 4096 bytes of name and value stay the caller's, since Validate never sees the value.
type CookiePosture ¶
type CookiePosture int
CookiePosture decides how the cookie methods use the transport they are given, ClientAddr.Secure.
const ( // PostureSecure is the default: every cookie is __Host-<base> with // Secure, HttpOnly and SameSite, whatever the transport, and // [Authenticator.Authenticate] refuses every plain request with // [ErrHTTPSRequired]. Works on any HTTPS deployment, self-signed // certificates included. PostureSecure CookiePosture = iota // PosturePerRequest names each cookie from the transport: // __Host-<base> with Secure for a secure request, the bare <base> // without Secure for a plain one. For one instance served both over // plain HTTP on a LAN and over HTTPS. 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 Error ¶
type Error struct {
Err error // for the app's log; never sent
Code Code // stable data a client branches on
Detail string // safe to show; never a secret or a raw cause
Reason string // a stable sub-reason a client may branch on
RetryAfter time.Duration // set with 429 and every 503 but auth_second_factor_unavailable
Status int
}
Error is one refusal, handed to the ErrorWriter.
func ErrorFor ¶
ErrorFor maps an error Authenticator.Authenticate or RequireRecentAuth returned to its refusal. Its Reason is empty, so the answer names no stored state, except ReasonTransportChanged for a session presented on the other transport, which the verifier revokes when a SessionRevoker is registered, and for ErrRecentAuthRequired and ErrHTTPSRequired the reason the refusal carries, such as ReasonSignInAgain. It reports false for any other error.
type ErrorWriter ¶
type ErrorWriter func(w http.ResponseWriter, r *http.Request, e Error)
ErrorWriter renders one refusal in the app's own envelope. The library writes no error body itself: Cache-Control, the WWW-Authenticate Authenticator.Challenge sets for e.Code and, when RetryAfter is set, Retry-After are already on w when it is called.
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
// [ErrSessionTransport], 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
// 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, its user 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 is the current secret's last use, as the Authenticator's
// touch records it; a rotation zeroes it, so zero after a rotation means
// the new secret is unused.
LastUsedAt time.Time `json:"last_used_at,omitzero"`
// PreviousUntil bounds the overlap in which PreviousHash still verifies.
PreviousUntil time.Time `json:"previous_until,omitzero"`
KeyHash Hash `json:"-"`
// PreviousHash is the secret the last rotation superseded, zero when
// none; it verifies while [Key.PreviousSecretUsable].
PreviousHash 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 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, or holds a key with neither the computed hash as its KeyHash nor as its PreviousHash; for a key whose ExpiresAt is set and not after now, as the Authenticator does; and for a previous secret unless Key.PreviousSecretUsable. It never touches, so a previous secret lasts until PreviousUntil. 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 KeySecret ¶
type KeySecret struct {
PreviousUntil time.Time
KeyHash Hash
PreviousHash Hash
KeyPrefix string
KeySuffix string
}
KeySecret is the part of a Key a rotation replaces: the new secret's hash and display parts, and the superseded secret with its overlap bound.
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" MethodTOTP Method = "totp" MethodRecoveryCode Method = "recovery_code" 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
// IssuedByKey is the API key whose principal issued this invite; 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, 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:"-"`
// 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:"-"`
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 the webauthn package 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.
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" PasswordIsTemporary PasswordRejection = "is_temporary_password" )
The rejections, in PasswordRejections order. This package's validators return the first five. account produces the last two: PasswordBreached for a password CheckBreachedPassword reports breached, and PasswordIsTemporary for a chosen password equal to the temporary password it replaces.
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, or for a previous secret
// the earlier of that and PreviousUntil, 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
// IP is the client address of the request Authenticate verified,
// Recheck's input's for a rechecked principal; zero for a principal
// built elsewhere.
IP netip.Addr
User *User
Method Method
// SessionID names the session; session principals only.
SessionID string
// KeyLabel is the authenticating key's Label; built-in API-key
// principals only, and empty for a key stored with no label.
KeyLabel string
// 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
// Secure is the [ClientAddr.Secure] of the request Authenticate verified,
// or Recheck's input's; false for a principal built elsewhere.
Secure bool
// 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) IsSession ¶
IsSession reports a principal the built-in session verifier produced. Keys, custom verifiers and the bypass never pass it.
func (Principal) KeyHash ¶
KeyHash returns the hash of the key secret that produced p, the previous secret's for a principal verified during a rotation's overlap, or the zero Hash for any other principal.
func (Principal) LogValue ¶
LogValue emits the method, the user's ID, the session ID, 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 RecoveryCode ¶
RecoveryCode is a user's saved recovery code, one per user, stored only as the password hasher's salted hash (NIST SP 800-63B-4 §4.2.1.1).
func (RecoveryCode) LogValue ¶
func (c RecoveryCode) LogValue() slog.Value
LogValue emits the user and creation time, never Hash.
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) IsZero ¶
IsZero reports a Sealer that holds no key, nil or the zero value, whose Seal and SealAtRest panic; a caller holding an optional Sealer refuses it.
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. A purpose holding a NUL byte panics, as a programming error.
func (*Sealer) OpenAtRest ¶
OpenAtRest returns the payload of a value SealAtRest made for purpose, trying each key in ring order, and current, which reports that the ring's first key opened it, so a false answer marks a value to re-seal. It returns ErrSealInvalid for anything it cannot authenticate.
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 over MaxSealPayload is refused with ErrSealTooLarge, so Open never refuses what Seal accepted; a purpose holding a NUL byte panics. Each value carries a random 96-bit nonce, so a first key seals at most 2^32 values, at-rest values included: before then, put a new key first and keep the old one after it.
func (*Sealer) SealAtRest ¶
SealAtRest returns base64url(nonce || ciphertext) of payload under the first key, for a value a store keeps: no expiry is sealed inside, and the additional data is "access/at-rest\x00" + purpose, so it never opens with Open and a Seal value never opens with OpenAtRest. A payload longer than MaxSealPayload is refused with ErrSealTooLarge.
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
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
// 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
// Secure is the transport of the request that created the session, set at
// creation from [ClientAddr.Secure]. The zero value is plain, the weakest
// binding, so a store that drops the field fails closed.
Secure bool
}
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 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 SessionRevoker ¶
type SessionRevoker interface {
// RevokeTransportMismatch deletes the session ref names, answering nil
// when it is already gone.
RevokeTransportMismatch(ctx context.Context, ref SessionRef) error
}
SessionRevoker ends a session the session verifier refused for its transport (see Session.Secure).
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 TOTP ¶
TOTP is a user's authenticator-app record, one per user. Sealed is the secret sealed with Sealer.SealAtRest for the purpose "totp:" and the user's ID, so a record copied onto another user's row does not open. LastStep is the highest time step accepted, which no later code may reuse.
type TemporaryPassword ¶
type TemporaryPassword struct {
CreatedAt time.Time
ExpiresAt time.Time
Hash Hash `json:"-"`
UserID int64
IssuedByUser int64
IssuedByKey int64
Dormant bool
}
TemporaryPassword is an admin-issued, single-use password, one per user, kept apart from User.PasswordHash, so a store that drops it fails closed. IssuedByUser is the issuing admin and IssuedByKey the issuing API key; both are zero for an out-of-band issue. Dormant marks one issued while the user's local methods were dormant, whose one use is the admin link.
func (TemporaryPassword) LogValue ¶
func (p TemporaryPassword) LogValue() slog.Value
LogValue emits every field but Hash.
type TokenPurpose ¶
type TokenPurpose string
TokenPurpose names what a one-time token unlocks. Values outside the constants are app-defined.
const ( PurposeSetup TokenPurpose = "setup" 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:"-"`
// Owner marks a break-glass account; an owner always has RoleAdmin.
Owner bool `json:"-"`
// WaitingApproval marks a registration an admin has not approved yet;
// such an account is also not Enabled.
WaitingApproval bool `json:"-"`
}
User represents an authenticated user account. It carries no key attribution: what a key did to a user is a KeyAttribution record.
type UserReader ¶
type UserReader interface {
UserByID(ctx context.Context, id int64) (user *User, found bool, err error)
}
UserReader retrieves user records for authentication.
type Via ¶
type Via uint8
Via is how the request reached the app, as the app's resolver saw it.
const ( ViaUnknown Via = iota // the zero value: the resolver did not say ViaDirect // the peer is the client; no forwarding header ViaUntrustedForwarding // a peer the app does not trust sent a forwarding header, which was ignored ViaProxy // a trusted proxy forwarded the client, in Forwarded ViaProxyNoClient // a trusted proxy forwarded no client address )
The Via values a resolver answers.
Source Files
¶
- apikey.go
- apikey_verifier.go
- audit.go
- auth_cookie.go
- challenge.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
- refusal.go
- sealer.go
- secret.go
- session.go
- session_verifier.go
- store_iface.go
- token.go
- types.go
- username.go
- verifier.go
- warn.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. |
|
Package gate guards an app's own routes with an access.Authenticator: one table of rows, each with its class, and one handler per row.
|
Package gate guards an app's own routes with an access.Authenticator: one table of rows, each with its class, and one handler per row. |
|
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 and its name-only snapshot from the community list at -commit, or at the commit the current aaguids_gen.go names on its Source line; see internal/aaguidgen.
|
Command genaaguids regenerates webauthn/aaguids_gen.go and its name-only snapshot from the community list at -commit, or at the commit the current aaguids_gen.go names on its Source line; see internal/aaguidgen. |
|
cmd/genblocklist
command
Command genblocklist regenerates internal/blocklist/common.txt from the SecLists password lists at -commit, or at the commit the current common.txt's header records.
|
Command genblocklist regenerates internal/blocklist/common.txt from the SecLists password lists at -commit, or at the commit the current common.txt's header records. |
|
cmd/refresh
command
Command refresh regenerates access's community data, the common-password list from SecLists and the passkey AAGUID list, at the newest commit of each upstream branch, and writes the proposal cplieger/ci's community data refresh opens a pull request from.
|
Command refresh regenerates access's community data, the common-password list from SecLists and the passkey AAGUID list, at the newest commit of each upstream branch, and writes the proposal cplieger/ci's community data refresh opens a pull request from. |
|
crockford
Package crockford is Douglas Crockford's base32 (https://www.crockford.com/base32.html): the symbols 0-9 and A-Z without I, L, O and U, five bits each, most significant bit first.
|
Package crockford is Douglas Crockford's base32 (https://www.crockford.com/base32.html): the symbols 0-9 and A-Z without I, L, O and U, five bits each, most significant bit first. |
|
crossorigin
Package crossorigin is the one cross-origin check every tree serving a session cookie runs before an unsafe-method route.
|
Package crossorigin is the one cross-origin check every tree serving a session cookie runs before an unsafe-method route. |
|
failreason
Package failreason carries why a refusal happened beside the public sentinel a client sees, so an audit event can name it, or accesshttp 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 an audit event can name it, or accesshttp 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. |
|
refusal
Package refusal writes one refusal the way access.ErrorWriter's contract promises, for every tree that answers through one.
|
Package refusal writes one refusal the way access.ErrorWriter's contract promises, for every tree that answers through one. |
|
scopetoken
Package scopetoken holds the one rule for a key scope's characters, so every scope access accepts quotes unescaped in a WWW-Authenticate scope attribute.
|
Package scopetoken holds the one rule for a key scope's characters, so every scope access accepts quotes unescaped in a WWW-Authenticate scope attribute. |
|
Package oidc signs a user in with an OpenID Connect provider.
|
Package oidc signs a user in with an OpenID Connect provider. |
|
internal/bodycap
Package bodycap caps every response body an http.Client reads at MaxBytes, whatever length the response declares.
|
Package bodycap caps every response body an http.Client reads at MaxBytes, whatever length the response declares. |
|
internal/discovery
Package discovery fetches and checks an OpenID Connect provider's discovery document (OpenID Connect Discovery 1.0).
|
Package discovery fetches and checks an OpenID Connect provider's discovery document (OpenID Connect Discovery 1.0). |
|
internal/jsonmember
Package jsonmember reads JSON documents member by member, by each member's JSON kind (RFC 8259).
|
Package jsonmember reads JSON documents member by member, by each member's JSON kind (RFC 8259). |
|
internal/jwk
Package jwk parses a JWK Set (RFC 7517) into the public keys oidc verifies ID tokens with: RSA, EC on P-256, P-384 and P-521, and OKP Ed25519 (RFC 7518 §6, RFC 8037 §2).
|
Package jwk parses a JWK Set (RFC 7517) into the public keys oidc verifies ID tokens with: RSA, EC on P-256, P-384 and P-521, and OKP Ed25519 (RFC 7518 §6, RFC 8037 §2). |
|
internal/jws
Package jws verifies a compact JWS (RFC 7515) carrying a signed JWT (RFC 7519) under the algorithms of package jwk, and returns its payload.
|
Package jws verifies a compact JWS (RFC 7515) carrying a signed JWT (RFC 7519) under the algorithms of package jwk, and returns its payload. |
|
Package ratelimit admits authentication attempts against sliding windows of failures per IP key, per account and per trusted device, and counts requests on anonymous 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 routes per IP key. |
|
Package totp computes and checks time-based one-time passwords on the standard library: RFC 6238 over RFC 4226's HOTP, fixed at HMAC-SHA-1, six digits and a 30-second step, since Google Authenticator ignores any other algorithm, length or period.
|
Package totp computes and checks time-based one-time passwords on the standard library: RFC 6238 over RFC 4226's HOTP, fixed at HMAC-SHA-1, six digits and a 30-second step, since Google Authenticator ignores any other algorithm, length or period. |
|
Package webauthn is a WebAuthn Level 3 relying party on Go's standard library: passkey registration, discoverable sign-in and step-up ceremonies.
|
Package webauthn is a WebAuthn Level 3 relying party on Go's standard library: passkey registration, discoverable sign-in and step-up ceremonies. |
|
internal/cbor
Package cbor decodes the RFC 8949 data items WebAuthn carries: one item per call, bounded in size, depth and item count, with no indefinite lengths or tags.
|
Package cbor decodes the RFC 8949 data items WebAuthn carries: one item per call, bounded in size, depth and item count, with no indefinite lengths or tags. |
|
internal/cose
Package cose reads a WebAuthn credential public key, a COSE_Key (RFC 9052 §7), for the algorithms access offers, and verifies an assertion or self attestation signature under it.
|
Package cose reads a WebAuthn credential public key, a COSE_Key (RFC 9052 §7), for the algorithms access offers, and verifies an assertion or self attestation signature under it. |