access

package module
v1.0.0-dev.18 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: Apache-2.0 Imports: 37 Imported by: 0

README

access

Go Reference Go version Mutation

access gives your Go web service its sign-in: Argon2id passwords, passkeys, authenticator-app codes, OIDC sign-in, sessions, API keys and invites, served as JSON routes you mount on your own mux, with a typed browser client. You write the storage and the pages.

It reads no environment variables, and every setting lives on the value you construct. It is licensed under Apache-2.0. It has five direct dependencies at run time: github.com/cplieger/go/keylock, golang.org/x/crypto, golang.org/x/oauth2, golang.org/x/sync and golang.org/x/text.

Why use it

access is built for a Go service that owns its login pages and its database.

  • Every sign-in path, password, passkey, OIDC, invite, self-registration and first-user setup, runs through one admission path, which checks the rate limits before any password is hashed.
  • Passwords hash with Argon2id at OWASP's parameters. When every Hasher is given the same HashBudget, that bound is process-wide. With no HashBudget, each Hasher has its own budget of four derivations. An unknown username costs the same work as a wrong password.
  • Repeated wrong passwords lock the method durably: after 100 consecutive failures for one account, method and trust context, that method is locked in that context until the user, signed in another way, re-enables it. A browser that signed in before keeps its own context, so a stranger's guesses do not lock the account's holder out.
  • Your store keeps only the SHA-256 hash of each 256-bit random session token. The session cookie holds only the token, and the cookies that carry state are sealed with AES-256-GCM.
  • A password sign-in from a user with an authenticator app asks for its code or a passkey before any session exists, and under RequireSecondFactor every password sign-in proves or binds a second factor. A recovery code or an admin's single-use temporary password lets a person back in.
  • Passkey ceremonies accept only your exact origin by default.
  • OIDC sign-in sends a PKCE S256 challenge, checks the ID token's nonce and keeps the flow in a sealed cookie, with nothing stored on the server.
  • API keys can carry scopes, and two permissions you grant explicitly let a key manage regular users or mint narrower keys, each act attributed to the key's whole lineage. A key rotates to a new secret in place, and its old secret keeps working through a short overlap.
  • Every credential is an access.Secret or an access.Hash, which print as redacted wherever they are logged.
  • Sign-ins and credential, key, role and account changes append a security-log entry in the same transaction that makes the change, so the change and its record commit together, and the next failure-record sweep records each lock. The security log lists what it leaves out, such as renames and failed attempts.

Consider Authboss if you want ready-made registration and recovery flows with HTML views. Consider Ory Kratos if you want identity as a separate server.

Packages

Package What it does
access The building blocks: the Authenticator that verifies a request, the refusal codes, the password hasher, session and API-key tokens, cookies, Secret, Hash and Sealer
access/gate Guards your own routes: one table of routes, each with the class of caller it admits, answered through your error writer. It needs nothing of passkeys or OIDC
account Sign-in, sessions, passkeys, OIDC, keys, invites, the user set and the security log, run over your account.Store
accesshttp Every account operation as a JSON route with a descriptor, for your own mux
ratelimit Per-IP, per-account and per-device limits on failed attempts, with trusted-device cookies
totp Authenticator-app codes, RFC 6238
webauthn Passkey ceremonies
oidc OpenID Connect sign-in, link, step-up and invite acceptance
accesstest An in-memory store, the store contract suite, a test identity provider and a software passkey
@cplieger/access The browser client for accesshttp's routes

Install

go get github.com/cplieger/access@latest

For the browser client:

npm install @cplieger/access @cplieger/reactive@dev

Usage

This service mounts every route under /api/auth and guards one route of its own. It uses the in-memory test store; yours is your implementation of account.Store.

package main

import (
	"context"
	"encoding/json"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/cplieger/access"
	"github.com/cplieger/access/account"
	"github.com/cplieger/access/accesshttp"
	"github.com/cplieger/access/accesstest"
	"github.com/cplieger/access/gate"
	"github.com/cplieger/access/ratelimit"
)

func main() {
	ctx := context.Background()
	store := accesstest.NewMemStore() // use your database-backed account.Store here

	authn, err := access.New(store, access.Config{
		IdleTimeout: time.Hour,
		AbsTimeout:  24 * time.Hour,
		Cookie:      access.DefaultCookieConfig(),
	})
	if err != nil {
		log.Fatal(err)
	}
	hasher, err := access.NewHasher(access.HasherConfig{})
	if err != nil {
		log.Fatal(err)
	}
	devices, err := access.NewSealer(loadKey("device.key")) // persisted, so trusted browsers survive a restart
	if err != nil {
		log.Fatal(err)
	}
	limits := ratelimit.DefaultConfig()
	limits.Devices = devices
	limiter, err := ratelimit.New(ctx, limits)
	if err != nil {
		log.Fatal(err)
	}

	svc, err := account.New(ctx, account.Config{
		Store:         store,
		Policy:        account.RolePolicy{},
		Authenticator: authn,
		Hasher:        hasher,
		Limiter:       limiter,
		Rules:         func() account.Rules { return account.Rules{} },
		FailureKey:    loadKey("failure.key"),
	})
	if err != nil {
		log.Fatal(err)
	}

	routes, err := accesshttp.New(accesshttp.Config{
		Account:    svc,
		Errors:     writeError,
		Prefix:     "/api/auth",
		OIDCPrefix: "/api/auth/oidc",
		SignInPath: "/login",
	})
	if err != nil {
		log.Fatal(err)
	}
	mux := http.NewServeMux()
	for _, rt := range routes.Routes() {
		mux.Handle(rt.Method+" "+rt.Path, rt.Handler)
	}
	app, err := gate.New(gate.Config{Authenticator: authn, Errors: writeError},
		[]gate.Route{{Name: "me", Method: http.MethodGet, Path: "/api/me", Class: gate.Session}},
		map[string]http.Handler{"me": http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			p, _ := gate.Principal(r.Context()) // the session the gate admitted
			_ = json.NewEncoder(w).Encode(map[string]string{"user": p.User.Username})
		})})
	if err != nil {
		log.Fatal(err)
	}
	mux.Handle("/api/", app)
	log.Fatal(http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", mux))
}

// writeError renders every refusal in the app's own JSON envelope.
func writeError(w http.ResponseWriter, _ *http.Request, e access.Error) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(e.Status)
	_ = json.NewEncoder(w).Encode(map[string]string{"code": string(e.Code), "reason": e.Reason, "detail": e.Detail})
}

// loadKey reads a 32-byte key the app generated once with access.GenerateSealerKey.
func loadKey(path string) []byte {
	b, err := os.ReadFile(path)
	if err != nil {
		log.Fatal(err)
	}
	return b
}

The service ends TLS itself, so the default resolver reads each request as secure. Behind a TLS proxy, set Config.ClientAddr instead (Authenticator configuration): under the default PostureSecure, a request your resolver reads as plain HTTP is refused, and Plain HTTP explains the posture that serves one.

The gate serves /api/me to a signed-in session only, and answers every other request under /api/ itself. The handler reads the request's Principal, which names the user, the method that authenticated it, and the session or key behind it. The Authenticator reads the session cookie first, then a verifier you add as Config.Verifier, then an Authorization: Bearer API key. Guarding your own routes explains the route classes, the codes and how to mount the gate.

Neither accesshttp nor the gate writes an error body itself: every refusal reaches your ErrorWriter as an access.Error with a stable Code and Reason, so the envelope is yours. You may mount any subset of the auth routes. Configuration explains both.

API

  • access: New builds the Authenticator that returns a Principal, with the refusal types Error, Code and ErrorWriter, the Hasher, the token generators, Secret, Hash and Sealer.
  • access/gate: New builds a Gate from a Config and a table of Route values, Principal reads the admitted caller, and Codes and MountCodes list the codes a route can answer.
  • account: New builds the Service that runs every operation over your Store, and Actor names who performs each operation.
  • accesshttp: New builds the Handler whose Route values carry each operation, and the request and view types are its wire format.
  • ratelimit, oidc, webauthn and totp: the Limiter, the Provider with its Flow, the RelyingParty with its ceremony functions, and Match with the secret and URI helpers.
  • accesstest: MemStore, the IdP fake and StoreContract.

The full reference is on pkg.go.dev.

The limits on guessing

  • The rate limiter counts failed attempts per IP address, per account and per trusted device. Its limits are exact for the MaxEntries keys each dimension used most recently, 10,000 by default. Past that, MaxEntries bounds its memory, not a spray of new keys, and the rate limiter section names what bounds each route.
  • The durable failure cap bounds what such a spray gets: at most 100 consecutive password guesses at each account in each trust context, counted in your store before the password is checked, so a restart does not reset it.
  • These are the library's own bounds. It makes no claim of conformance to a password-guessing standard.

Security

access hardens the building blocks, and the security of your service depends on how you wire them.

  • Each password hash has its own random salt. Password hashes, API keys and tokens are compared in constant time.
  • The default cookie carries the __Host- prefix with the Secure, HttpOnly and SameSite=Lax attributes, Path=/ and no Domain, on every request.
  • API keys are read from the Authorization: Bearer header only, never from a URL query parameter.
  • Every unsafe-method route applies Go's http.CrossOriginProtection itself, whatever your own middleware does.
  • Config.Bypass grants a synthetic admin user, whose ID is 0 and names no stored user, to every request while its callback returns true. account refuses every write made under it. Keep it off in production.
  • When hosts you do not control share your relying-party domain, keep the default exact origin. Passkeys explains AllowSubdomains and Origins.
  • Three rules stay with you. Guard every route of your own with access/gate, set ClientAddr.Secure from where TLS ends (Authenticator configuration), and keep the store contract. Implementing the store states the contract, and accesstest.StoreContract checks it.
  • Fuzz targets cover password hashes and checks, cookie settings, API keys, opaque tokens, sealed values, redirect paths, the JSON body decoder, OIDC claims, ID tokens, discovery documents and key sets, the rate limiter, TOTP codes and URIs, temporary-password and recovery-code input, and WebAuthn origins, stored credentials, and registration and sign-in responses.
  • The cryptography has had no independent third-party audit.

Report a vulnerability privately through the security policy, not in a public issue.

Unsupported by design

These are left out on purpose. Non-goals gives the reason for each and what to use instead.

  • Several processes over one store. Every read-check-write decision runs inside one store transaction, but the rate limiter's windows, the pending passkey ceremonies and the pending sign-ins and enrolments live in the process, so run one process per store.
  • Page rendering. The browser client renders nothing.
  • A CSRF token, because Go's http.CrossOriginProtection refuses cross-origin state-changing requests without needing one.
  • OIDC token refresh, a registry of several providers, back-channel logout and the userinfo endpoint.
  • WebAuthn metadata-service verification, attestation conveyance, filtering authenticators by AAGUID, and the passkey well-known endpoints.
  • Role hierarchies and permission sets. Each user has one role, and HasRole passes when it matches the role a route needs or when the user is an admin.
  • Encrypting or signing the session cookie, because it holds only a random token.
  • SMS and email codes, and recovery by an emailed link. The library stores no phone number or address.

Documentation

  • Guarding your own routes explains the gate's route classes, matching, codes, challenge and audit events.
  • Configuration lists every setting and default, the cookie postures, the rate limiter's limits, the key permissions and the HTTP handlers' error contract.
  • Plain HTTP lists what a request without TLS may do under each cookie posture, and what binding a session to its transport protects.
  • Passwords, sessions and tokens covers each building block in detail.
  • Implementing the store explains the transaction boundary, the store contract and what each write costs.
  • The security log lists what is logged, how long it is kept, and who can read it.
  • Passkeys explains how ceremonies check origins and what registration requires.
  • OIDC sign-in explains the sealed flow cookie, the link, step-up and invite checks and the limits on outbound calls.
  • Second factors and temporary passwords covers authenticator apps, the recovery code and an admin's ways to let a person back in.
  • Identity and single sign-on explains owners, the SSO mode, linking and offboarding.
  • Migrating from auth v6 lists every change and its replacement.
  • Non-goals gives the reason for each feature left out.

Contributing

Issues and pull requests are welcome. The shared contributing rules apply.

Disclaimer

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

This project was built with AI assistance. The human maintainer defines architecture, supervises implementation, and makes all final decisions.

License

Apache-2.0. See LICENSE. Third-party attributions are in THIRD_PARTY_NOTICES.md.

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

Examples

Constants

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

DefaultIdleTimeout and DefaultAbsTimeout are what a zero Config.IdleTimeout and Config.AbsTimeout mean.

View Source
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.

View Source
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.

View Source
const DefaultRealm = "access"

DefaultRealm is what an empty Config.Realm means.

View Source
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).

View Source
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.

View Source
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.

View Source
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).

View Source
const SealerKeySize = 32

SealerKeySize is the length of every Sealer key: AES-256.

View Source
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

View Source
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.

View Source
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")
)
View Source
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.

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

Sentinel errors for session operations.

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

Token errors.

View Source
var (
	// ErrUsernameEmpty reports that the username is empty, or normalized to
	// empty. RFC 8265 §3.1 requires a non-empty result.
	ErrUsernameEmpty = errors.New("username must not be empty")

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

Sentinel errors returned by NormalizeUsername.

View Source
var ErrBreachCheckUnavailable = errors.New("access: breached-password check unavailable")

ErrBreachCheckUnavailable reports that CheckBreachedPassword got no verdict.

View Source
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.

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

ErrInvalidAPIKey is returned when an API key cannot be verified.

View Source
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

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

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

func DecodePasskeyFlags(octet uint8) (userPresent, userVerified, backupEligible, backupState bool)

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

func GenerateOpaqueToken() (plaintext Secret, hash Hash)

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

func GenerateSessionToken() (plaintext Secret, hash Hash)

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

func HasRole(user *User, role Role) bool

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 HexSHA256

func HexSHA256(s string) string

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

func IsBrowserRequest

func IsBrowserRequest(r *http.Request) bool

IsBrowserRequest 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 IsPassive

func IsPassive(ctx context.Context) bool

IsPassive reports whether ctx carries Passive.

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

func NormalizeUsername(username string) (string, error)

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

func Passive(ctx context.Context) context.Context

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

func RequireRecentAuth(p Principal, maxAge time.Duration, now time.Time) error

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

func StatusOf(code Code) int

StatusOf is the HTTP status a refusal with code answers, 0 for a code Codes does not list.

func ValidateKeyPrefix

func ValidateKeyPrefix(prefix string) error

ValidateKeyPrefix returns nil for a prefix GenerateAPIKey accepts, and ErrInvalidKeyPrefix otherwise.

func ValidatePasswordCommon

func ValidatePasswordCommon(password string) error

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

func ValidatePasswordLength(password string) error

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

func ValidateRedirectURI(uri string) string

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.

func VerifyOpaqueToken

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

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

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

func (a *Authenticator) Recheck(ctx context.Context, p Principal) (Principal, error)

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

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"
	CodeUnavailable             Code = "auth_unavailable"
	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"
	CodeBreachCheckUnavailable  Code = "auth_breach_check_unavailable"
	CodePasswordLoginDisabled   Code = "auth_password_login_disabled"
	CodeCodeInvalid             Code = "auth_code_invalid"
	CodeSecondFactorRequired    Code = "auth_second_factor_required"
	CodeSecondFactorUnavailable Code = "auth_second_factor_unavailable"
	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"
	CodePasskeysUnavailable     Code = "auth_passkeys_unavailable" //nolint:gosec // G101: an error code, not a credential
	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"
	CodeOIDCUnavailable         Code = "auth_oidc_unavailable"
	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.

func Codes

func Codes() []Code

Codes returns every code the library answers, in its table's 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

func ErrorFor(err error) (Error, bool)

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.

func NewError

func NewError(code Code, reason string, err error) Error

NewError builds the refusal for code: Status and Detail from the code table, and RetryAfter for auth_busy, auth_unavailable and auth_breach_check_unavailable. It panics for a code Codes does not list, which is a programming 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

func APIKeyHash(key string) Hash

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

func NewHash

func NewHash(encoded string) Hash

NewHash wraps encoded. NewHash("") is the zero Hash.

func SessionHash

func SessionHash(token string) Hash

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

func (Hash) Equal

func (h Hash) Equal(o Hash) bool

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

func (h Hash) Format(f fmt.State, _ rune)

Format writes "[redacted]", or nothing for the zero value, for every verb fmt routes to it.

func (Hash) IsZero

func (h Hash) IsZero() bool

IsZero reports whether h holds no text.

func (Hash) Key

func (h Hash) Key() HashKey

Key returns h's HashKey, the masked value's tag; the zero Hash gives the zero HashKey.

func (Hash) LogValue

func (h Hash) LogValue() slog.Value

LogValue returns the redacted rendering as a string value.

func (Hash) MarshalJSON

func (h Hash) MarshalJSON() ([]byte, error)

MarshalJSON encodes the redacted rendering as a JSON string.

func (Hash) Reveal

func (h Hash) Reveal() string

Reveal returns the text, or "" for the zero value.

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

func (h *Hasher) Hash(ctx context.Context, password string) (Hash, error)

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

func (h *Hasher) NeedsRehash(encoded Hash) bool

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

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

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) Clone

func (k *Key) Clone() *Key

Clone returns a deep copy, or nil for a nil k.

func (Key) LogValue

func (k Key) LogValue() slog.Value

LogValue emits the id, user, prefix, suffix and scopes, never KeyHash.

func (Key) ParentKeyID

func (k Key) ParentKeyID() int64

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.

func (*Key) PreviousSecretUsable

func (k *Key) PreviousSecretUsable(now time.Time) bool

PreviousSecretUsable reports whether k's previous secret verifies at now: PreviousHash is set, now is before PreviousUntil, and the current secret is unused (LastUsedAt zero).

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

type OIDCIdentity struct {
	Issuer  string
	Subject string
}

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

Clone returns a deep copy, or nil for a nil c.

type PasskeyLoginUpdate

type PasskeyLoginUpdate struct {
	At           time.Time
	SignCount    uint32
	RawFlags     uint8
	CloneWarning bool
}

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) HasScope

func (p Principal) HasScope(scope string) bool

HasScope reports whether scope is among p's Scopes.

func (Principal) IsAPIKey

func (p Principal) IsAPIKey() bool

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

func (p Principal) IsSession() bool

IsSession reports a principal the built-in session verifier produced. Keys, custom verifiers and the bypass never pass it.

func (Principal) KeyHash

func (p Principal) KeyHash() Hash

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

func (p Principal) LogValue() slog.Value

LogValue emits the method, the user's ID, the session ID, the key ID and the scopes; never the credential hash.

func (Principal) SessionTokenHash

func (p Principal) SessionTokenHash() Hash

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

type RecoveryCode struct {
	CreatedAt time.Time
	Hash      Hash `json:"-"`
	UserID    int64
}

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.

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

User role constants.

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

func NewSealer(keys ...[]byte) (*Sealer, error)

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

func (s *Sealer) IsZero() bool

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

func (s *Sealer) Open(purpose, sealed string, now time.Time) ([]byte, error)

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

func (s *Sealer) OpenAtRest(purpose, sealed string) (payload []byte, current bool, err error)

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

func (s *Sealer) Seal(purpose string, payload []byte, expires time.Time) (string, error)

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

func (s *Sealer) SealAtRest(purpose string, payload []byte) (string, error)

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 NewSecret

func NewSecret(plaintext string) Secret

NewSecret wraps plaintext. NewSecret("") is the zero Secret.

func (Secret) Format

func (s Secret) Format(f fmt.State, _ rune)

Format writes "[redacted]", or nothing for the zero value, for every verb fmt routes to it.

func (Secret) IsZero

func (s Secret) IsZero() bool

IsZero reports whether s holds no plaintext.

func (Secret) LogValue

func (s Secret) LogValue() slog.Value

LogValue returns the redacted rendering as a string value.

func (Secret) MarshalJSON

func (s Secret) MarshalJSON() ([]byte, error)

MarshalJSON encodes the redacted rendering as a JSON string, which nothing decodes.

func (Secret) Reveal

func (s Secret) Reveal() string

Reveal returns the plaintext, or "" for the zero value.

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.

func (Session) LogValue

func (s Session) LogValue() slog.Value

LogValue emits the session's identity, transport and times, never the hash.

type SessionActivity

type SessionActivity struct {
	At time.Time
	IP string
}

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

type SessionRef struct {
	ID     string
	UserID int64
}

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

type TOTP struct {
	CreatedAt time.Time
	Sealed    string `json:"-"`
	UserID    int64
	LastStep  int64
}

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.

func (TOTP) LogValue

func (t TOTP) LogValue() slog.Value

LogValue emits the user, creation time and last step, never Sealed.

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.

func (*User) Clone

func (u *User) Clone() *User

Clone returns a deep copy, or nil for a nil u.

func (User) LogValue

func (u User) LogValue() slog.Value

LogValue emits the id, username, role, owner and waiting flags, and presence markers for the password hash, the WebAuthn handle and the OIDC link.

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.

func (Via) String

func (v Via) String() string

String returns the constant's name ("ViaUnknown", "ViaDirect", "ViaUntrustedForwarding", "ViaProxy", "ViaProxyNoClient"), and "Via(N)" for a value out of range.

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 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.
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.

Jump to

Keyboard shortcuts

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