account

package
v1.0.0-dev.6 Latest Latest
Warning

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

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

Documentation

Overview

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. accesstest.StoreContract tests each rule below.

Hashes

Every hash the SPI carries, as a record field (User.PasswordHash, Session.TokenHash, Key.KeyHash, OneTimeToken.Hash, Rotation.ExpectHash) or as a by-hash key, is an access.Hash, and so are the by-hash parameters of the root roles (access.SessionReader, access.SessionActivityUpdater, access.APIKeyReader). A store persists and indexes h.Reveal() when it writes, rebuilds the field with access.NewHash(stored) when it reads, and treats two hashes as the same key exactly when their texts are equal, which is what access.Hash.Equal reports. An index held in memory keys on h.Key(), the comparable access.HashKey, so no map key holds a hash text and no store defines a comparable form of its own. A store maps each field explicitly and never encodes a record through encoding/json: the record fields carry `json:"-"`, and Hash has no decoder.

Transactions

Every account operation that changes more than one record runs wholly inside one Update, so a backend error or a crash leaves the whole old state or the whole new state. Slow steps (Argon2, the breach call, the identity provider exchange, WebAuthn verification) run before Update, and the callback re-reads what it decides on, so a check made before the slow step is never trusted.

Two Updates never interleave, and a single-call write outside Update is ordered against them, so a read-check-write inside one callback (last admin, last method, user count) is race-free without an in-process lock. The callback resets, then fills, its local results and events on each run, so a re-run under a grouped commit reports and emits nothing twice, and no event is emitted until Update returns nil.

An Update commits every record set it touches as one unit. A store that spreads its records over several files must still publish one Update with one atomic step: every file written into a new generation directory and published by one rename of a pointer, or every record kept in one file. Two renames in sequence do not meet the rule, because a fault or a crash between them leaves half the writes durable.

The callback uses only its tx. Calling the Store from inside it can deadlock (bbolt's single writer), and account never does. A Tx is not retained.

Contract rules

  1. Absence. A by-key lookup reports absence through found with a nil error, never through a nil value with a nil error, and never through an error. A list is a search: an empty slice with a nil error is its correct empty answer.
  2. Ownership. A lookup returns values the caller owns: deep copies of User.WebAuthnHandle, Key.Scopes, Key.LineageIDs, KeyAttribution.KeyLineage, PasskeyCredential's byte slices, and every other reference field. A write never retains a pointer or slice it was given.
  3. Canonical usernames. account passes access.NormalizeUsername output to CreateUser, UpdateUser and UserByUsername. The store indexes and compares those bytes exactly, and never normalises again.
  4. Uniqueness. Username (ErrUsernameTaken); a non-zero OIDCIdentity (ErrOIDCIdentityTaken); WebAuthnHandle; credential ID across all users (ErrDuplicateCredential); key hash; session hash and session ID; token hash. Two hashes are the same key exactly when Hash.Equal holds, and a hash read back is Equal to the one written.
  5. Atomicity. RotateSession, ConsumeOneTimeToken and CreateInitialUser are each linearisable: concurrent calls on the same key give exactly one success. CreatePasskey's uniqueness holds under concurrent inserts. DeleteUser's cascade (sessions, passkeys, keys, tokens whose Subject is the user, and the user's key attributions) is one transaction. A failed single-call write leaves no partial state. In Update, a callback returning an error, or panicking, leaves no write visible; a nil return makes every write visible at once and durably; concurrent Updates are serialisable, also when the store groups them into one commit; a read inside the callback sees the callback's own earlier writes. A callback the store re-runs leaves only its last run's writes. The same rules hold when the callback's writes are single-call writes through tx. A store with a durable medium groups concurrently pending Updates into shared durable commits.
  6. Scoping. User-scoped operations affect nothing when the owner does not match, and they report ErrNotFound as for an absent row, so there is no ownership oracle. The operations: DeletePasskey, RenamePasskey, UpdatePasskeyAfterLogin, DeleteSession, UpdateSessionLabel, DeleteAPIKey and RotateSession. A zero or partial ref (access.PasskeyRef, access.KeyRef, access.SessionRef) matches nothing. DeleteOneTimeTokensIssuedBy removes exactly the tokens whose IssuedByKey it lists, and an empty list or a 0 matches nothing.
  7. Expiry at consume. ConsumeOneTimeToken refuses an expired token at the call, not only in a sweep, and LiveOneTimeTokens never lists a token whose ExpiresAt is not after now.
  8. Flags. UpdatePasskeyAfterLogin writes the octet, the derived booleans (access.DecodePasskeyFlags), the sign count, the clone warning and LastUsedAt together. A stored credential always carries RawFlags.
  9. Handle probing. UserByWebAuthnHandle answers an unknown handle and a malformed one the same way.
  10. Durability. A write or an Update returns nil only when its new state is durable in the store's medium. On an error account treats the operation as not done: it answers access.ErrAuthBackend and fires no event, and it holds no state that could diverge, because every record it decides on lives in the store. A medium that can publish before it confirms durability (a file store whose directory sync fails after its rename) therefore returns an error there; how that store then stays consistent, for example by fencing writes until a durable rewrite, is its own business. bbolt's db.Update reports durability with its commit.
  11. Time. Stored time.Time values round-trip to at least millisecond precision.
  12. Errors. Caller faults use only the sentinels of this package. Everything else is a backend error. context.Canceled and context.DeadlineExceeded pass through wrapped.
  13. Concurrency. Safe for concurrent use by many goroutines. No goroutine outlives a call.
  14. Cleanup. CleanupExpiredSessions deletes exactly the sessions for which access.ValidateSession(s, timeouts, now) fails: past idle or absolute, a SessionRecovery session past min(timeouts, access.RecoverySessionLifetime), and a session past its own IdleCap or AbsoluteCap. A store calls access.ValidateSession (or access.SessionDeadlines) rather than restating the rule. account passes the timeouts the verifier enforces, and never a zero SessionTimeouts; a store may refuse one. A call deletes at most limit such sessions, in one atomic step (rule 5), and returns exactly the access.SessionRef of each session it deleted, none twice and no other, so across calls that return nil, a close and a reopen included, the refs returned are exactly the rows those calls removed; a session created, rotated or touched concurrently is named only if that call deleted it. A store whose call can run more than once before it returns (a grouped commit that re-runs its batch, as bbolt's db.Batch may) builds the result afresh on each run and returns only the last run's, so a re-run never names a session twice. A call returning fewer than limit refs left no session ValidateSession refuses at now. account never passes a limit below 1; a store may refuse one. A call that returns an error is treated as having deleted nothing, and account emits nothing for it (rules 5 and 10).
  15. Failure records. AuthFailure reports absence through found (rule 1). PutAuthFailure upserts one record, and DeleteAuthFailures removes the listed methods' records of one name in both trust contexts, skipping absent ones. A Name is opaque: the store indexes it and derives nothing from it. PruneAuthFailures(keep) leaves exactly the records whose Name is in keep and reports how many it removed. UnreportedLocks returns exactly the records with Unreported set. The bound, which the store's prune and account's admission make together: at any time the store holds at most 2 × len(users) records of user names (one counted method, two trust contexts), plus 2 × 20,000 records of other names, plus the records of users deleted since the last sweep, plus at most one trusted record per counted method for each user deleted within the device-cookie lifetime (180 days), whose old cookie can recreate it.
  16. Reads never wait across a write's fsync or rename. A read sees the last committed state and never blocks on an in-progress Update or single-call write. bbolt's read transactions give this, except that a commit growing the file past its mapping remaps under db.mmaplock, which new read transactions wait out (go.etcd.io/bbolt@v1.5.0 db.go:457 and db.go:801); that is file growth, which an attacker steers only up to rule 15's bound. A file store publishes snapshots through an atomic pointer and holds its writer mutex only among writers. Without the rule a cheap read stalls during a commit, and whatever triggers a commit becomes observable.
  17. IDs and lineage. A store assigns User.ID, Key.ID, PasskeyCredential.ID and KeyAttribution.ID as positive integers no larger than 2^53 − 1, so every ID survives a JSON number in the browser. A User.ID or Key.ID the store has assigned is never assigned again, to a user or a key respectively, for the life of the store, after that row's deletion and across restarts included. Each KeyAttribution.ID is larger than every one assigned before it, so ascending ID is append order whatever the clock says. CreateAPIKey appends the ID it assigns to the LineageIDs it was given, so a stored key's path ends with its own ID. Key.LineageIDs, KeyAttribution.KeyLineage, Session.IssuedByKey and OneTimeToken.IssuedByKey outlive the keys they name, and account refuses an issuer it cannot find, so a reused ID would let a later key stand in for a revoked one. bbolt's per-bucket NextSequence keeps the rule, because the sequence commits with the row and only SetSequence lowers it; an allocator that takes the highest live ID plus one, or the lowest free one, breaks it, and such a store keeps a high-water mark instead, which a delete never lowers and which commits with the row. Session.ID is the 128-bit hex string account mints.
  18. Context. A store call receives the context of the caller it serves, unchanged except for added values. Every call made while an account operation or a request runs receives that caller's context: every read, every Update and every Tx call inside it, CreateSession, RotateSession and the counted attempt's failure write included, and the Authenticator's SessionByHash, UpdateSessionActivity, UserByID, APIKeyByHash and TouchAPIKey. The background sweep serves no caller and runs on the service context. A store never detaches or replaces the context it receives, so in any call made for a request it may read a value the app put on that request's context.
  19. Writes to an absent row. UpdateSessionActivity, TouchAPIKey and UpdatePasskeyAfterLogin never create a row. For a hash or ID that names nothing, UpdateSessionActivity and TouchAPIKey write nothing and return nil; UpdatePasskeyAfterLogin returns ErrNotFound (rule 6). A verification that read a session just before it was revoked or rotated can therefore never bring it back.
  20. Fidelity. Every exported field of every record a store keeps (User, Session, PasskeyCredential, Key, OneTimeToken, KeyAttribution, FailureCount, and the structs they embed or hold, OIDCIdentity and FailureRef) reads back as it was written, apart from what the store assigns (IDs, the LineageIDs append of rule 17). The record fields carry `json:"-"`, and Hash's MarshalJSON writes "[redacted]" ("" for the zero Hash) with no UnmarshalJSON, so every store maps every field by hand. A persistent store keeps the same fidelity across a close and a reopen of its medium.
  21. Activity never moves backwards. UpdateSessionActivity stores act.At as LastActivity, and act.IP as LastIP, only when act.At is after the stored LastActivity, comparing and writing in one atomic step; an older or equal At writes nothing, LastIP included, and returns nil. LastIP therefore always belongs to the newest LastActivity; UserAgent is set at creation and no activity write touches it. TouchAPIKey does the same for LastUsedAt, and RotateSession keeps the stored LastActivity and LastIP when the stored LastActivity is after Next's, so no write path lowers either. Two verified requests can reach the store in the reverse order of their clocks: without the rule a late, older write would move a session's idle deadline back. A store implements it as a conditional update (UPDATE … WHERE last_activity < ?, or a compare inside its write transaction or writer mutex), never as a read followed by a separate write.

Index

Constants

View Source
const (
	ReasonOutOfBandOnly      = "out_of_band_only"
	ReasonKeyNotCurrent      = "key_not_current"
	ReasonAdminTarget        = "admin_target"
	ReasonScopesNotSubset    = "scopes_not_subset"
	ReasonExpiryAfterParent  = "expiry_after_parent"
	ReasonLineageTooDeep     = "lineage_too_deep"
	ReasonPermissionNotAdmin = "permission_not_admin"
	ReasonSelfRecovery       = "self_recovery"
	ReasonOtherUser          = "other_user"
	ReasonTargetNotEligible  = "target_not_eligible"
	ReasonNotPrincipal       = "not_principal"
	ReasonUnknownOperation   = "unknown_operation"
	ReasonNotEnabledUser     = "not_enabled_user"
	ReasonNotAdmin           = "not_admin"
	ReasonSelfDelete         = "self_delete"
	ReasonLastAdmin          = "last_admin"
	ReasonLastLocalAdmin     = "last_local_admin"
	ReasonSingleOwner        = "single_owner"
	ReasonNotOwner           = "not_owner"
	ReasonUnknownVia         = "unknown_via"
	ReasonViaWithActor       = "via_with_actor"
)

The PolicyError Reasons, in PolicyReasons order. RolePolicy and SingleOwnerPolicy give the role and owner reasons; ReasonNotPrincipal, ReasonUnknownOperation, ReasonUnknownVia and ReasonViaWithActor answer a Decision no account operation builds.

View Source
const (
	ReasonEmpty               = "empty"
	ReasonDisallowedCharacter = "disallowed_character"
	ReasonTooLong             = "too_long"
)

The UsernameError and TextError Reasons.

View Source
const (
	TextFieldLabel       = "label" // a key or session label, or a passkey name
	TextFieldDisplayName = "display_name"
)

The TextError Fields.

View Source
const (
	// MaxUsernameLength is the longest username, in runes after
	// access.NormalizeUsername, that any creation path accepts.
	MaxUsernameLength = 64
	// FailureCap is the consecutive-failure count, per (name, method) and
	// trust context, at which the method locks for that context.
	FailureCap = 100
	// MaxUntrustedCounts is how many untrusted attempts the whole process
	// counts between two failure-record prunes; spending it wakes a prune,
	// and untrusted counted attempts are refused until it commits.
	MaxUntrustedCounts = 10000
	// MaxKeyLineage is the most IDs a Key.LineageIDs holds: a root and seven
	// generations of keys minted by keys. Minting below a key whose path is
	// full is *PolicyError{Reason: "lineage_too_deep"}.
	MaxKeyLineage = 8
	// MaxSweepBatch is the most sessions one CleanupExpiredSessions call
	// deletes, and so the most IDs one call's EventSessionsExpired events
	// carry together; the sweep calls again within the tick until a call
	// returns fewer.
	MaxSweepBatch = 1000
)

Variables

View Source
var (
	ErrNotFound            = errors.New("account: not found")
	ErrUsernameTaken       = errors.New("account: username taken")
	ErrOIDCIdentityTaken   = errors.New("account: identity provider account already linked")
	ErrDuplicateCredential = errors.New("account: passkey already registered")
	ErrSetupComplete       = errors.New("account: setup already completed")
)

Errors a store returns for caller faults. An operation answers one only where it is that operation's own refusal; any other store error is a backend failure, which account wraps as access.ErrAuthBackend.

View Source
var (
	ErrInvalidCredentials    = errors.New("account: invalid credentials")
	ErrPasswordLoginDisabled = errors.New("account: password sign-in is disabled")
	ErrAlreadyLinked         = errors.New("account: an identity provider account is already linked")
	// ErrMethodNotLocked is ReenableMethod on a method locked in neither
	// trust context.
	ErrMethodNotLocked = errors.New("account: method is not locked")
	// ErrSessionRequired is an operation for a full or a recovery session
	// reached by any other principal, and RequireAdminScope or
	// RequireKeyPermission refusing a recovery session or an empty scope.
	ErrSessionRequired = errors.New("account: a signed-in session is required")
	// ErrScopeRequired is RequireAdminScope or RequireKeyPermission under a
	// set scope, for a principal that is no full session and no key carrying
	// that scope.
	ErrScopeRequired = errors.New("account: a key scope is required")
	// ErrNoChange is an UpdateUser with no field set.
	ErrNoChange = errors.New("account: no change requested")
	// ErrCurrentPasswordRequired is a SetPassword with a zero current for a
	// user who holds a password, or a RemovePassword with a zero current.
	ErrCurrentPasswordRequired = errors.New("account: the current password is required")
	ErrKeyExpiryInvalid        = errors.New("account: key expiry must not be negative")
	// ErrRulesInvalid is matched by every *RulesError: New refusing the
	// Rules() value, and an operation refusing a later invalid one.
	ErrRulesInvalid = errors.New("account: rules invalid")
	// ErrServiceClosed is every operation called after Shutdown began; it
	// matches access.ErrAuthBackend.
	ErrServiceClosed = fmt.Errorf("account: service closed: %w", access.ErrAuthBackend)
	// ErrTTLTooLong is a token lifetime above 7 times its kind's default.
	ErrTTLTooLong = errors.New("account: token lifetime too long")
	// ErrTTLNegative is a negative token lifetime given to IssueRecovery,
	// CreateInvite or IssueSetupToken.
	ErrTTLNegative        = errors.New("account: token lifetime must not be negative")
	ErrSetupTokenRequired = errors.New("account: a setup token is required")
	// ErrPolicyRefused is matched by every *PolicyError.
	ErrPolicyRefused = errors.New("account: refused by policy")
	// ErrLastMethod is a removal that would leave the user no method that
	// can sign in now.
	ErrLastMethod          = errors.New("account: the last sign-in method cannot be removed")
	ErrSSOGoverned         = errors.New("account: the account is governed by its identity provider")
	ErrPasskeysUnavailable = errors.New("account: passkeys are not available")
	ErrOIDCUnavailable     = errors.New("account: OIDC is not available")
	ErrCeremonyInvalid     = errors.New("account: ceremony unknown, expired or of another kind")
	ErrSessionGone         = errors.New("account: the session no longer exists")
	// ErrUnknownScope is a key scope outside Rules.Scopes.
	ErrUnknownScope = errors.New("account: unknown key scope")
	// ErrBreachCheckUnavailable is access's sentinel, so either name matches
	// the refusal under BreachFailClosed.
	ErrBreachCheckUnavailable = access.ErrBreachCheckUnavailable
)

Errors of the account operations. Errors of access, ratelimit, webauthn and oidc pass through unchanged and match with errors.Is.

Functions

func PolicyReasons

func PolicyReasons() []string

PolicyReasons returns every Reason account's own rules and policies put in a PolicyError, in a stable order.

func TextErrorFields

func TextErrorFields() []string

TextErrorFields returns every TextError Field, in a stable order.

func TextErrorReasons

func TextErrorReasons() []string

TextErrorReasons returns every TextError Reason, in a stable order.

func UsernameReasons

func UsernameReasons() []string

UsernameReasons returns every UsernameError Reason, in a stable order.

Types

type AcceptInvite

type AcceptInvite struct {
	Token    access.Secret
	Password access.Secret
	Username string
}

AcceptInvite is the input of AcceptInvitePassword.

type Actor

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

Actor is who performs an operation. The zero Actor is anonymous: the caller proved nothing yet (setup, invite acceptance, OIDC provisioning).

func As

func As(p access.Principal) Actor

As is the actor of a request's principal.

func OutOfBand

func OutOfBand(channel string) Actor

OutOfBand is an actor outside any request (an admin socket, a CLI); channel names it in events.

func (Actor) OutOfBandChannel

func (a Actor) OutOfBandChannel() (string, bool)

OutOfBandChannel returns the channel of an out-of-band actor, and false for any other.

func (Actor) Principal

func (a Actor) Principal() (access.Principal, bool)

Principal returns the actor's principal, and false for an out-of-band or the zero Actor.

type AttributionStore

type AttributionStore interface {
	// CreateKeyAttribution assigns a.ID, larger than every ID it assigned
	// before (rule 17), and stores a copy.
	CreateKeyAttribution(ctx context.Context, a *access.KeyAttribution) error
	// ListKeyAttributions returns every record, in ascending ID order.
	ListKeyAttributions(ctx context.Context) ([]access.KeyAttribution, error)
}

AttributionStore holds the append-only key attribution records. It has no update and no delete: a record goes only with its user, in UserStore.DeleteUser's cascade.

type BreachMode

type BreachMode int

BreachMode is what a password set does with the breached-password check.

const (
	// BreachOff runs no breach check.
	BreachOff BreachMode = iota
	// BreachFailOpen refuses a breached password and accepts one the check
	// could not judge, logging one WARN; a caller whose context ended gets
	// that context's error instead.
	BreachFailOpen
	// BreachFailClosed refuses a breached password, and one the check could
	// not judge with ErrBreachCheckUnavailable.
	BreachFailClosed
)

type Client

type Client struct {
	// Host is the request's Host header (r.Host) as the transport received
	// it, port included; only the setup rule reads it. Empty when the
	// transport has none.
	Host      string
	UserAgent string        // sanitised and capped before storage
	Device    access.Secret // the device cookie as presented; zero when absent
	// ClientAddr is the Authenticator's resolver's answer for the request;
	// account never reads a header.
	access.ClientAddr
}

Client is what the transport knows about the caller, as data.

type Config

type Config struct {
	Store  Store
	Policy Policy // RolePolicy or SingleOwnerPolicy, or the app's own
	// Authenticator owns the session cookie and timeouts; account reads both
	// from it and holds no copy.
	Authenticator *access.Authenticator
	Hasher        *access.Hasher
	Limiter       *ratelimit.Limiter
	RP            func() *webauthn.RelyingParty // nil func or nil result: passkeys off
	OIDC          func() *oidc.Provider         // likewise for OIDC
	Rules         func() Rules                  // read once per operation (hot reload)
	// OnEvent receives every Event after its commit, synchronously in the
	// committing goroutine. It must not block; a durable sink enqueues.
	OnEvent func(Event)
	// Breach is the client for the breached-password check. A Rules value
	// whose Breach is not BreachOff is invalid while it is nil, at New and
	// at every later Rules() call.
	Breach *http.Client
	Logger *slog.Logger     // nil: slog.Default() at each log call
	Now    func() time.Time // nil: time.Now
	// AdminScope, when set, lets a key of an admin user that carries this
	// scope list users and every user's keys, and revoke any key. Empty:
	// session only.
	AdminScope string
	// ManageUsersScope, when set, lets a key carrying this scope create,
	// update and delete RoleUser accounts, invite RoleUser accounts and
	// issue recovery for RoleUser accounts; never an admin. Empty: session
	// only, under recent auth.
	ManageUsersScope string
	// CreateKeysScope, when set, lets a key carrying this scope mint keys
	// for its own user, each no broader and no longer-lived than itself.
	// Empty: session only, under recent auth.
	CreateKeysScope string
	// FailureKey is the HMAC-SHA256 key that names failure records: exactly
	// 32 bytes, required, persisted by the app beside its device-cookie key
	// ring. A new key orphans every record, which the next sweep prunes, so
	// rotating it resets every count and clears every lock with no
	// EventMethodLocked or EventMethodReenabled for them; keep it for the
	// store's lifetime. New copies it and keeps no reference to the slice.
	FailureKey []byte
	// CleanupInterval is how often expired sessions, tokens, pending
	// ceremonies and failure records of names that are not users are swept,
	// and locks reported; zero means 5m.
	CleanupInterval time.Duration
	// MaxPending bounds the pending WebAuthn ceremonies; zero means 10000.
	MaxPending int
}

Config configures a Service. It has no LogValue or Format: it is a construction input holding the caller's own key bytes, which New copies into masked state.

type CreateVia

type CreateVia string

CreateVia names what authorises an OpCreateUser. account alone sets it, from the code path; a caller cannot choose it.

const (
	ViaActor        CreateVia = ""             // the Decision's Actor: an admin principal or OutOfBand
	ViaSetup        CreateVia = "setup"        // first-account setup; account sets it only while UserCount == 0
	ViaInvite       CreateVia = "invite"       // a consumed invite, minted earlier under OpInvite
	ViaProvisioning CreateVia = "provisioning" // an OIDC identity Rules.Provisioning admitted
)

The creation paths.

type CreatedKey

type CreatedKey struct {
	Plaintext access.Secret
	Key       access.Key
	Issued    Issued // zero for an out-of-band or a key actor
}

CreatedKey is a minted key; Plaintext is shown once.

type Credentials

type Credentials struct {
	Password access.Secret
	Username string
}

Credentials is the input of PasswordLogin.

type CurrentSession

type CurrentSession struct {
	AuthTime, IdleDeadline, AbsoluteDeadline time.Time
	ID                                       string
	Method                                   access.Method
}

CurrentSession is the caller's own session.

type Decision

type Decision struct {
	// Target is nil for OpCreateUser, OpInvite and the list operations, and
	// for a user operation whose target does not exist; the policy then
	// decides on the actor alone.
	Target *access.User
	Op     Operation
	Role   access.Role // OpCreateUser, OpSetRole, OpInvite
	Via    CreateVia   // OpCreateUser only
	// Users is the user set read inside the operation's Update, with any
	// earlier change of the same UpdateUser call applied.
	Users   []access.User
	Actor   Actor // the zero Actor for every Via other than ViaActor
	Enabled bool  // OpSetEnabled: the value being set
}

Decision is one question to the Policy. A write that decides on stored rows asks it inside its Update, with the rows read there; a list read, and an invite acceptance's OpCreateUser, which no row decides, ask it before.

type Event

type Event struct {
	At         time.Time
	Kind       EventKind
	Method     access.Method // sign-in, step-up, lock and re-enable
	SessionIDs []string      // sessions ended or rotated
	Actor      EventActor
	UserID     int64 // the account the event is about (target)
	// KeyID is the key of a key event, and the issuing key of an
	// EventRecoveryConsumed, EventRecoveryCompleted or invite-accepting
	// EventUserCreated whose token a key issued.
	KeyID     int64
	PasskeyID int64 // passkey events
	Trusted   bool  // EventMethodLocked: which context locked
}

Event is one committed change, delivered to Config.OnEvent after the Update that made it returns nil. Delivery is at most once: a crash between the commit and the dispatch loses the event.

type EventActor

type EventActor struct {
	SessionID string
	OutOfBand string // the channel; empty for a principal
	UserID    int64
	KeyID     int64
}

EventActor is who caused an Event; the zero value is no actor (the sweep, an anonymous caller).

type EventKind

type EventKind string

EventKind names what an Event reports.

const (
	EventSignedIn            EventKind = "signed_in"
	EventSessionRevoked      EventKind = "session_revoked"
	EventUserSessionsRevoked EventKind = "user_sessions_revoked"
	EventSessionRotated      EventKind = "session_rotated"
	EventSessionsExpired     EventKind = "sessions_expired" // the sweep deleted expired sessions; after a call that returns nil
	EventPasswordSet         EventKind = "password_set"
	EventPasswordChanged     EventKind = "password_changed"
	EventPasswordRemoved     EventKind = "password_removed"
	EventPasskeyAdded        EventKind = "passkey_added"
	EventPasskeyRemoved      EventKind = "passkey_removed"
	EventOIDCLinked          EventKind = "oidc_linked"
	EventOIDCUnlinked        EventKind = "oidc_unlinked"
	EventSetupTokenIssued    EventKind = "setup_token_issued" //nolint:gosec // G101: an event name, not a credential
	EventRecoveryIssued      EventKind = "recovery_issued"
	EventRecoveryConsumed    EventKind = "recovery_consumed"
	EventRecoveryCompleted   EventKind = "recovery_completed"
	EventKeyMinted           EventKind = "key_minted"
	EventKeyRevoked          EventKind = "key_revoked"
	EventSteppedUp           EventKind = "stepped_up"
	EventUserDisabled        EventKind = "user_disabled"
	EventUserEnabled         EventKind = "user_enabled"
	EventUserDeleted         EventKind = "user_deleted"
	EventRoleChanged         EventKind = "role_changed"
	EventUserCreated         EventKind = "user_created"
	EventMethodLocked        EventKind = "method_locked"    // a failure counter reached the cap; reported by the sweep
	EventMethodReenabled     EventKind = "method_reenabled" // recovery, ReenableMethod or a sign-in cleared a lock, after its commit
)

The event kinds.

type FailureCount

type FailureCount struct {
	LockedAt time.Time // set with Locked; the time the lock was reached
	FailureRef
	Count  int
	Locked bool // Count reached the failure cap; stays set until recovery or re-enable
	// Unreported is set with Locked; the sweep reports the lock when Name
	// is a user's and clears it.
	Unreported bool
}

FailureCount is one record: consecutive failed attempts, counted before verification, for one (name, method, trust context).

type FailureRef

type FailureRef struct {
	// Name is the hex HMAC-SHA256, under the service's failure key, of the
	// canonical typed username, whether or not a user has that name. The
	// name itself is never stored.
	Name    string
	Method  access.Method
	Trusted bool // the attempts carried a valid device cookie for that account
}

FailureRef names one failure record.

type FailureStore

type FailureStore interface {
	AuthFailure(ctx context.Context, ref FailureRef) (f FailureCount, found bool, err error)
	PutAuthFailure(ctx context.Context, f FailureCount) error // upsert
	// UnreportedLocks returns every record whose Unreported is set.
	UnreportedLocks(ctx context.Context) ([]FailureCount, error)
	// DeleteAuthFailures removes name's records for each listed method, in
	// both trust contexts; an absent record is skipped.
	DeleteAuthFailures(ctx context.Context, name string, methods []access.Method) error
	// PruneAuthFailures removes every record whose Name is not in keep and
	// returns how many it removed.
	PruneAuthFailures(ctx context.Context, keep []string) (int64, error)
}

FailureStore holds the failure records.

type Issued

type Issued struct {
	Token        access.Secret
	DeviceCookie access.Secret // set after a step-up or a verified current password; zero otherwise
	Session      access.Session
}

Issued is a rotated or restricted session.

type IssuedToken

type IssuedToken struct {
	ExpiresAt time.Time // the stored expiry, capped at an issuing key's
	Plaintext access.Secret
}

IssuedToken is a minted invite or recovery token; Plaintext is shown once.

type KeyStore

type KeyStore interface {
	// CreateAPIKey assigns key.ID and appends it to key.LineageIDs, which
	// account sets to the minting key's path, or leaves empty for a key a
	// session or an out-of-band actor mints (rule 17).
	CreateAPIKey(ctx context.Context, key *access.Key) error
	APIKeyByHash(ctx context.Context, hash access.Hash) (key *access.Key, found bool, err error)
	ListAPIKeysByUserID(ctx context.Context, userID int64) ([]access.Key, error)
	ListAPIKeys(ctx context.Context) ([]access.Key, error) // every user's
	DeleteAPIKey(ctx context.Context, ref access.KeyRef) error
	DeleteUserAPIKeys(ctx context.Context, userID int64) ([]int64, error) // the IDs removed
	// TouchAPIKey sets LastUsedAt to at only when at is after the stored
	// value, atomically; an older or equal at, or an unknown key, writes
	// nothing and returns nil (rules 19 and 21).
	TouchAPIKey(ctx context.Context, keyID int64, at time.Time) error
}

KeyStore holds the API keys.

type ListedKey

type ListedKey struct {
	Owner string // the owner's username; empty when its user row is gone
	Key   access.Key
}

ListedKey is one row of the admin key list.

type ListedToken

type ListedToken struct {
	// IssuerLineage is the LineageIDs of the key named by Token.IssuedByKey,
	// read with the list; nil for a token no key issued.
	IssuerLineage []int64
	Token         access.OneTimeToken
}

ListedToken is one row of the admin token list.

type ListedUser

type ListedUser struct {
	// KeyLineage is the KeyLineage of the user's most recent KeyAttribution
	// that the filter matched (of its most recent one, unfiltered), derived
	// at read; nil when no key has acted on the user.
	KeyLineage []int64
	User       access.User
	// PasskeyCount is how many passkeys the user holds, read with the list;
	// with User.PasswordHash and User.OIDC it is the user's sign-in methods
	// on the admin list.
	PasskeyCount int
}

ListedUser is one row of the admin user list.

type LoginMode

type LoginMode int

LoginMode is how a passkey sign-in asks the browser for a credential.

const (
	// LoginModal is the default: the browser shows its passkey dialog.
	LoginModal LoginMode = iota
	// LoginConditional offers the passkeys through the browser's autofill
	// (conditional mediation).
	LoginConditional
)

type Me

type Me struct {
	User        *access.User
	Current     CurrentSession
	Methods     Methods
	CanLinkOIDC bool // OIDCAvailable and not OIDCLinked
}

Me is the signed-in user's own view.

type MethodLock

type MethodLock struct {
	Method             access.Method
	Untrusted, Trusted bool
}

MethodLock is a method locked by the failure cap, per trust context.

type MethodState

type MethodState struct {
	// RPID is the relying party ID a counted passkey is registered under;
	// empty means passkeys are off.
	RPID string
	// OIDCIssuer is the issuer a counted OIDC link carries; empty means
	// OIDC is off.
	OIDCIssuer string
	Rules      Rules
}

MethodState is the configuration UsableMethods counts under, in place of the published Config.Rules(), Config.RP() and Config.OIDC(), so an app can check values before it publishes them.

type Methods

type Methods struct {
	Locks             []MethodLock // locked methods only
	PasskeyCount      int
	HasPassword       bool
	OIDCLinked        bool
	OIDCAvailable     bool
	PasskeysAvailable bool
	PasswordLogin     bool // !Rules.DisablePasswordLogin
}

Methods is what a user can sign in with.

type NewKey

type NewKey struct {
	Label     string
	Scopes    []string
	ExpiresIn time.Duration // 0 = never; a negative value is ErrKeyExpiryInvalid
}

NewKey is the input of CreateAPIKey.

type NewUser

type NewUser struct {
	Password access.Secret // zero creates a user with no sign-in method
	Username string
	Role     access.Role // empty is access.RoleUser
}

NewUser is the input of CreateUser.

type OIDCOutcome

type OIDCOutcome struct {
	Redirect string      // the sealed redirect, already validated
	Pending  PendingLink // OutcomeNotLinked
	Issued   Issued      // OutcomeLinked, OutcomeSteppedUp: the rotated session
	SignedIn SignedIn    // OutcomeSignedIn
	Kind     OIDCOutcomeKind
}

OIDCOutcome is what an OIDC callback did.

type OIDCOutcomeKind

type OIDCOutcomeKind int

OIDCOutcomeKind is which arm of an OIDCOutcome is set.

const (
	OutcomeSignedIn OIDCOutcomeKind = iota
	OutcomeNotLinked
	OutcomeLinked
	OutcomeSteppedUp
)

The outcome kinds.

type Operation

type Operation string

Operation names what a Decision asks the Policy to allow.

const (
	OpCreateUser    Operation = "create_user" // admin create, invite accept, JIT provisioning
	OpDeleteUser    Operation = "delete_user"
	OpSetRole       Operation = "set_role"
	OpSetEnabled    Operation = "set_enabled"
	OpInvite        Operation = "invite"
	OpIssueRecovery Operation = "issue_recovery"
	OpListUsers     Operation = "list_users"      // the admin user list and the live invite and recovery tokens
	OpManageAllKeys Operation = "manage_all_keys" // list and revoke every user's keys
	OpMigrateToSSO  Operation = "migrate_to_sso"  // an OIDC link under Rules.SSOGoverned
	OpCreateKeyFor  Operation = "create_key_for"  // an out-of-band actor mints a key for Target
	OpCreateOwnKey  Operation = "create_own_key"  // a session or a key mints a key for its own user
)

The operations a Policy decides.

type PasskeyStore

type PasskeyStore interface {
	// CreatePasskey assigns cred.ID and refuses a credential ID registered
	// to any user with ErrDuplicateCredential (WebAuthn L3 §7.1 step 26).
	CreatePasskey(ctx context.Context, cred *access.PasskeyCredential) error
	PasskeysByUserID(ctx context.Context, userID int64) ([]access.PasskeyCredential, error)
	UpdatePasskeyAfterLogin(ctx context.Context, userID int64, credID []byte, upd access.PasskeyLoginUpdate) error
	RenamePasskey(ctx context.Context, ref access.PasskeyRef, name string) error
	DeletePasskey(ctx context.Context, ref access.PasskeyRef) error
	// DeleteUserPasskeys returns the IDs it removed.
	DeleteUserPasskeys(ctx context.Context, userID int64) ([]int64, error)
}

PasskeyStore holds the passkey credentials.

type PendingCeremony

type PendingCeremony struct {
	Creation  *webauthn.CredentialCreation  // registration ceremonies
	Assertion *webauthn.CredentialAssertion // login, step-up
	ID        string                        // 256-bit random hex; the X-Auth-Ceremony value
}

PendingCeremony is a begun WebAuthn ceremony, held by the service until its finish call takes it.

type PendingLink struct {
	UsernameHint string // preferred_username as sent, display only
	Email        string // only when email_verified
	Identity     access.OIDCIdentity
}

PendingLink is an OIDC identity no account is linked to yet.

type Policy

type Policy interface {
	// Authorize returns nil, or a *PolicyError.
	Authorize(ctx context.Context, d Decision) error
}

Policy decides who may change the user set and mint credentials.

type PolicyError

type PolicyError struct {
	Op     Operation
	Reason string
}

PolicyError is a refusal by a Policy, or by a rule account applies itself. Reason is one of PolicyReasons for account's own rules and policies, or whatever an app's own Policy sets. It matches ErrPolicyRefused.

func (*PolicyError) Error

func (e *PolicyError) Error() string

func (*PolicyError) Is

func (*PolicyError) Is(target error) bool

Is reports ErrPolicyRefused.

type RecoverOptions

type RecoverOptions struct {
	KeepSessions bool // false: every other session of the user is revoked
	KeepKeys     bool // false: every API key of the user is deleted, with every token it issued
}

RecoverOptions keeps what a recovery completion revokes by default.

type Recovery

type Recovery struct {
	Username string
	Methods  Methods
	Issued   Issued
}

Recovery is a started recovery: the restricted session and what the user holds.

type Registered

type Registered struct {
	Issued  Issued
	Passkey access.PasskeyCredential
}

Registered is an enrolled passkey and the rotated session.

type RolePolicy

type RolePolicy struct {
	// KeepLocalAdmin refuses removing, demoting, disabling or migrating to
	// SSO the last enabled admin who holds a password.
	KeepLocalAdmin bool
	// KeysAdminOnly lets only an admin mint keys for itself
	// (OpCreateOwnKey); false lets any enabled user.
	KeysAdminOnly bool
}

RolePolicy is the two-role policy: an admin manages the user set, and the last enabled admin cannot be removed, demoted or disabled.

func (RolePolicy) Authorize

func (p RolePolicy) Authorize(_ context.Context, d Decision) error

Authorize applies the two-role rules to d.

type Rotation

type Rotation struct {
	ID         string
	ExpectHash access.Hash `json:"-"` // optional compare-and-swap on the current hash
	// Next is the session after rotation; account copies it from the
	// current session and changes only the fields the operation names.
	Next   access.Session
	UserID int64
}

Rotation is one SessionStore.RotateSession call.

type Rules

type Rules struct {
	// SetupTokenRequired reports whether a setup from c needs a token. It
	// gets the request context and the resolved client with its
	// provenance. Nil means always.
	SetupTokenRequired func(ctx context.Context, c Client) bool
	// MethodUsable reports whether m can sign u in now under the app's own
	// rules; the last-method guard and UsableMethods AND it into every
	// method they count. tx is what the count reads: a removal's own Update
	// when it decides, the Store for RemovePassword's pre-check, the
	// caller's tx in UsableMethods. An app may type-assert tx to its own
	// transaction type; MethodUsable must not block or call the Store
	// outside tx. The guard reads Config.RP() and Config.OIDC() as
	// published. Nil means every held method is usable.
	MethodUsable func(ctx context.Context, tx Tx, u *access.User, m access.Method) bool
	// SessionCaps returns per-session limits for a session about to be
	// created for c, read once at creation. A positive value caps that
	// limit for the session's whole life (Session.IdleCap,
	// Session.AbsoluteCap; kept on rotation); zero or less, or a nil func,
	// means no cap.
	SessionCaps func(ctx context.Context, c Client) (idle, absolute time.Duration)
	// KeyPrefix starts every minted key's plaintext; see access.GenerateAPIKey.
	KeyPrefix string
	// ForbiddenWords join the username in the password context check.
	ForbiddenWords []string
	// Scopes is the key-scope vocabulary; CreateAPIKey refuses any other.
	Scopes []string
	// Provisioning gates just-in-time creation on an OIDC sign-in with no
	// linked account. The zero value is off.
	Provisioning oidc.Provisioning
	// RecentAuth is how recent a sign-in or step-up must be for an
	// operation that requires recent authentication. Zero means 10m; a
	// value below 1m is invalid.
	RecentAuth time.Duration
	// Breach is the breached-password check's mode; the zero value is off.
	Breach BreachMode
	// MaxSessionsPerUser bounds each user's sessions; creating one past it
	// ends the user's least recently active. Zero is unlimited.
	MaxSessionsPerUser int
	// DisablePasswordLogin refuses password sign-in and step-up with
	// ErrPasswordLoginDisabled. The zero value allows them.
	DisablePasswordLogin bool
	// SSOGoverned makes an OIDC link migrate the account: the password and
	// passkeys are removed, and only recovery restores a local method. A
	// full session of a user with a linked identity may not then set a
	// password or enrol a passkey (ErrSSOGoverned); unlinked users are
	// unaffected.
	SSOGoverned bool
	// RevokeKeysOnCredentialChange deletes the user's API keys when the
	// password is set or changed or an OIDC identity is linked. Disable and
	// delete always delete keys, whatever this says.
	RevokeKeysOnCredentialChange bool
}

Rules is the app's policy as data. Config.Rules is read once per operation, so a reloaded value applies from the next operation on.

An app may refuse a sign-in method in its own gate before account sees the attempt; Rules has no sign-in hook for it, and MethodUsable keeps the last-method guard from counting such a method.

func (Rules) Validate

func (r Rules) Validate() error

Validate checks every bounded field, KeyPrefix and Provisioning. The error is a *RulesError naming the field, which matches ErrRulesInvalid.

type RulesError

type RulesError struct {
	Err    error
	Field  string
	Reason string
}

RulesError names the Rules field that is invalid. It matches ErrRulesInvalid, and unwraps to Err when a check of another package refused the field.

func (*RulesError) Error

func (e *RulesError) Error() string

func (*RulesError) Is

func (*RulesError) Is(target error) bool

Is reports ErrRulesInvalid.

func (*RulesError) Unwrap

func (e *RulesError) Unwrap() error

type Service

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

Service runs the account operations over one Store. Build it with New and stop it with Shutdown.

func New

func New(ctx context.Context, cfg Config) (*Service, error)

New refuses a nil Store, Policy, Authenticator, Hasher, Limiter or Rules, a FailureKey that is not 32 bytes (naming the field, never the bytes), two equal non-empty scopes among AdminScope, ManageUsersScope and CreateKeysScope, a negative CleanupInterval or MaxPending, and a Rules() value Rules.Validate refuses or whose breach mode lacks Config.Breach. It runs the failure-record sweep once and returns its store error, then starts the cleanup sweep on ctx's values, not its cancellation, until Shutdown.

func (*Service) APIKeys

func (s *Service) APIKeys(ctx context.Context, p access.Principal) ([]access.Key, error)

APIKeys returns p's own keys, expired ones included, by ID. p must be a full session (ErrSessionRequired).

func (*Service) AcceptInvitePassword

func (s *Service) AcceptInvitePassword(ctx context.Context, c Client, in AcceptInvite) (SignedIn, error)

AcceptInvitePassword creates the invited account with a password and signs it in. The username, password and Policy (ViaInvite) checks and the IP limiter run before the hash; a refusal there, a taken name or a backend error leaves the invite usable. One Update consumes the invite and creates the user and session, re-checking a key-issued invite's issuer: a refused issuer deletes the invite and answers access.ErrTokenInvalid, an accepted one appends an invite_accepted attribution.

func (*Service) AdminScope

func (s *Service) AdminScope() string

AdminScope returns Config.AdminScope.

func (*Service) AdmitOIDC

func (s *Service) AdmitOIDC(c Client) (*oidc.Provider, error)

AdmitOIDC is an anonymous OIDC request's one provider read, for the sign-in start and the callback: ErrServiceClosed, then ErrOIDCUnavailable for a nil OIDC(), both charging nothing, then Limiter.Request on c's IP (*ratelimit.RefusedError), else the provider for the whole request.

func (*Service) AllAPIKeys

func (s *Service) AllAPIKeys(ctx context.Context, p access.Principal) ([]ListedKey, error)

AllAPIKeys returns every user's keys by ID, each with its owner's username, for a principal RequireAdminScope admits and Policy allows OpManageAllKeys. The keys and the users are read in one transaction, so each Owner is the name the key's own snapshot holds; a key whose owner that snapshot lacks lists an empty Owner.

func (*Service) Authenticator

func (s *Service) Authenticator() *access.Authenticator

Authenticator returns Config.Authenticator.

func (*Service) CreateAPIKey

func (s *Service) CreateAPIKey(ctx context.Context, a Actor, userID int64, in NewKey) (CreatedKey, error)

CreateAPIKey mints a key for userID and returns its plaintext once, for OutOfBand (OpCreateKeyFor) or a principal of userID's own user that RequireKeyPermission admits under CreateKeysScope (OpCreateOwnKey; another user is other_user). Scopes come from Rules().Scopes (ErrUnknownScope), a permission scope only on a RoleAdmin owner (permission_not_admin); the label is one line of at most 128 runes and ExpiresIn not negative. A key actor's parent is re-read in the Update and bounds the child's scopes, expiry and depth. Only a session actor's session rotates into Issued.

func (*Service) CreateInvite

func (s *Service) CreateInvite(ctx context.Context, p access.Principal, role access.Role, ttl time.Duration) (IssuedToken, error)

CreateInvite mints an invite for an account of role (empty is access.RoleUser), for an admin principal or a ManageUsersScope key, and returns its plaintext once. Policy (OpInvite) decides inside the Update; a key's authority is re-read there (key_not_current), its invite may carry RoleUser only (admin_target), records the key as IssuedByKey and expires no later than the key. A ttl of 0 means 7 days; one above 7 × 7 days is ErrTTLTooLong.

func (*Service) CreateKeysScope

func (s *Service) CreateKeysScope() string

CreateKeysScope returns Config.CreateKeysScope.

func (*Service) CreateUser

func (s *Service) CreateUser(ctx context.Context, a Actor, in NewUser) (*access.User, error)

CreateUser creates a user for an admin principal, a ManageUsersScope key or an out-of-band actor, under the same rules: the username rule, the password rule when in.Password is set (zero: no sign-in method), and Policy (OpCreateUser, ViaActor) on the user set read inside the creating Update. The hash runs first and authorises nothing: a key is re-read inside the Update (key_not_current), creates a RoleUser only (admin_target), and appends a created attribution with its LineageIDs.

func (*Service) DeleteUser

func (s *Service) DeleteUser(ctx context.Context, p access.Principal, userID int64) error

DeleteUser deletes a user (the Policy decides self-deletion) with every session, passkey, key, attribution record and token of theirs, and every token their keys issued, in one Update, for an admin principal or a ManageUsersScope key. The Policy (OpDeleteUser) answers before existence: a refusal is ErrPolicyRefused whether or not userID exists, and an allowed call on a missing user is ErrNotFound. A key deletes RoleUser targets only (admin_target). EventUserDeleted names the deleted sessions; one EventKeyRevoked per key follows.

func (*Service) IssueRecovery

func (s *Service) IssueRecovery(ctx context.Context, a Actor, userID int64, ttl time.Duration) (IssuedToken, error)

IssueRecovery mints a recovery token for userID and voids the user's earlier ones, for an out-of-band actor (ttl 0: 15 min) or an admin principal or ManageUsersScope key (ttl 0: 24 h); above 7 × that default is ErrTTLTooLong. A principal naming its own ID is self_recovery before any Policy call or store read. Policy (OpIssueRecovery) answers before existence (ErrNotFound after). A key is re-read inside the Update (key_not_current), issues for a RoleUser only (admin_target), and its token records IssuedByKey and expires no later than the key.

func (*Service) IssueSetupToken

func (s *Service) IssueSetupToken(ctx context.Context, a Actor, ttl time.Duration) (access.Secret, error)

IssueSetupToken mints the token for the first account. Only an out-of-band actor may call it, and only while no user exists (ErrSetupComplete). It asks no Policy: the token creates the account only through setup's own Policy call. It voids every earlier setup token. A ttl of 0 means 24h; one above 7 × 24h is ErrTTLTooLong.

func (*Service) LinkPendingOIDC

func (s *Service) LinkPendingOIDC(ctx context.Context, p access.Principal, pending PendingLink) (Issued, Me, error)

LinkPendingOIDC links pending's identity to p's own user (a full session within RecentAuth) in one Update that re-reads the user, rotates p's session into Issued and reads the returned Me, so a failed read rolls the link back. No identity is ErrNotFound, a disabled user ErrSessionGone, a linked user ErrAlreadyLinked, an identity of another user ErrOIDCIdentityTaken. Under Rules.SSOGoverned the link migrates the account: Policy (OpMigrateToSSO), then the password, the passkeys, the other sessions and, under RevokeKeysOnCredentialChange, the keys go.

func (*Service) Logout

func (s *Service) Logout(ctx context.Context, tokenHash access.Hash) error

Logout ends the session whose token hashes to tokenHash. It is idempotent: no such session is nil, and only a session it ended emits EventSessionRevoked.

func (*Service) ManageUsersScope

func (s *Service) ManageUsersScope() string

ManageUsersScope returns Config.ManageUsersScope.

func (*Service) Me

func (s *Service) Me(ctx context.Context, p access.Principal) (Me, error)

Me returns p's own view: the user as stored, its sign-in methods with their failure-cap locks, and p's session with the deadlines p was verified under. Only a full session may call it (ErrSessionRequired); a user deleted since p was verified is ErrSessionGone. It writes nothing.

func (*Service) OIDCComplete

func (s *Service) OIDCComplete(ctx context.Context, c Client, flow oidc.Flow, claims oidc.Claims) (OIDCOutcome, error)

OIDCComplete completes the callback oidc.Provider.Finish returned, after AdmitOIDC admitted it and returned that provider; OIDCComplete charges no limiter. A nil OIDC() is ErrOIDCUnavailable; the outcome carries flow.Redirect. A sign-in signs in the linked user (disabled: ErrInvalidCredentials) or one Rules.Provisioning admits, else gives one same OutcomeNotLinked. A link begun within RecentAuth, or a step-up of the linked identity (else ErrInvalidCredentials), needs flow's live full session (else ErrSessionGone).

func (*Service) OIDCProvider

func (s *Service) OIDCProvider() *oidc.Provider

OIDCProvider resolves Config.OIDC once; nil means OIDC is off. accesshttp calls it once per OIDC request, so a provider swapped by the app is used from the next request on.

func (*Service) PasskeyLoginBegin

func (s *Service) PasskeyLoginBegin(_ context.Context, c Client, origin webauthn.Origin, mode LoginMode) (PendingCeremony, error)

PasskeyLoginBegin starts a discoverable passkey sign-in at origin, in mode. A nil RP() is ErrPasskeysUnavailable and an unknown mode an error; a call past those counts against c's IP request limit (*ratelimit.RefusedError) before the pending cache grows. An origin the relying party refuses is its *webauthn.OriginError.

func (*Service) PasskeyLoginFinish

func (s *Service) PasskeyLoginFinish(ctx context.Context, c Client, ceremonyID string, body io.Reader) (SignedIn, error)

PasskeyLoginFinish completes the sign-in ceremonyID began and creates a full session for the asserting user, with a device cookie that keeps the ID of c.Device when that is valid for the user. An unknown, spent, expired or other ceremony is ErrCeremonyInvalid; a credential no user holds is webauthn.ErrUnknownCredential; a disabled user is ErrInvalidCredentials, after the credential's custody update is stored. CloneWarning reports a regressed sign counter.

func (*Service) PasskeyRegisterBegin

func (s *Service) PasskeyRegisterBegin(ctx context.Context, p access.Principal, origin webauthn.Origin) (PendingCeremony, error)

PasskeyRegisterBegin starts enrolling a passkey for p's own user, for a full session within RecentAuth. A nil RP() is ErrPasskeysUnavailable, and a linked user under Rules.SSOGoverned is ErrSSOGoverned.

func (*Service) PasskeyRegisterFinish

func (s *Service) PasskeyRegisterFinish(ctx context.Context, p access.Principal, ceremonyID string, body io.Reader) (Registered, error)

PasskeyRegisterFinish stores the passkey ceremonyID enrols for p's own user, named by webauthn.PasskeyFriendlyName against the user's passkeys, and rotates p's session into Issued, in one Update. A ceremony another user began is ErrCeremonyInvalid; a credential already registered to any user is ErrDuplicateCredential.

func (*Service) Passkeys

Passkeys returns p's own passkeys as stored, for a full session. It works with a nil RP(), so stale passkeys stay listable.

func (*Service) PasswordLogin

func (s *Service) PasswordLogin(ctx context.Context, c Client, in Credentials) (SignedIn, error)

PasswordLogin signs a user in with a password. Before any store call it answers ErrPasswordLoginDisabled, a *UsernameError, a *ratelimit.RefusedError (the limiter's, or Dimension "untrusted" once the untrusted allowance is spent) or access.ErrHashBusy. Each later attempt is counted before it is compared, and FailureCap failures lock the password in their trust context. An unknown, disabled, passwordless, locked or wrong-password arm is one ErrInvalidCredentials after the same work; a stored hash costlier than the hasher's can be access.ErrHashBusy after the count. A success returns the device cookie, resets the failure records and rehashes an old hash.

func (*Service) RecoverOutOfBand

func (s *Service) RecoverOutOfBand(ctx context.Context, a Actor, userID int64, password access.Secret, opts RecoverOptions) error

RecoverOutOfBand sets userID's password for an out-of-band actor (a principal is *PolicyError{Reason: ReasonOutOfBandOnly} before any read), with no recovery session, Client or limiter: the shared password rules, then one Update that asks the Policy (OpIssueRecovery), writes the password and runs RecoverWithPassword's completion under opts. A missing user is ErrNotFound; Enabled and the user's attributions stay as they are. The events are RecoverWithPassword's, with the channel as actor.

func (*Service) RecoverPasskeyBegin

func (s *Service) RecoverPasskeyBegin(ctx context.Context, p access.Principal, origin webauthn.Origin) (PendingCeremony, error)

RecoverPasskeyBegin starts enrolling a passkey for p's user, for a recovery session (ErrSessionRequired otherwise). A nil RP() is ErrPasskeysUnavailable.

func (*Service) RecoverPasskeyFinish

func (s *Service) RecoverPasskeyFinish(ctx context.Context, p access.Principal, ceremonyID string, body io.Reader, opts RecoverOptions) error

RecoverPasskeyFinish verifies the registration ceremonyID began and completes the recovery with that passkey, as RecoverWithPassword does with a password. A ceremony another user began is ErrCeremonyInvalid, and a credential registered to any user ErrDuplicateCredential.

func (*Service) RecoverWithPassword

func (s *Service) RecoverWithPassword(ctx context.Context, p access.Principal, password access.Secret, opts RecoverOptions) error

RecoverWithPassword sets p's password for a recovery session (ErrSessionRequired otherwise; ErrSessionGone once it ended). After the password rules, one Update re-checks a key-issued session's issuer as StartRecovery does (a refusal deletes the session alone: access.ErrTokenInvalid), writes the password and a key's recovered record, ends the session and the recovery tokens, revokes the other sessions and keys unless opts keeps them, and clears the failure records. Nobody signs in; the events follow in emitRecovered's order.

func (*Service) ReenableMethod

func (s *Service) ReenableMethod(ctx context.Context, p access.Principal, method access.Method) error

ReenableMethod clears method's failure-cap locks and counts for p's own user, in both trust contexts, in one Update: nil means durable, and an error leaves the lock. p must be a full session (ErrSessionRequired) within Rules().RecentAuth (access.ErrRecentAuthRequired) whose AuthMethod is not method (access.ErrRecentAuthRequired too, carrying an internal reason). No lock in either context is ErrMethodNotLocked. After the commit it emits EventMethodLocked for each lock the sweep had not reported, then EventMethodReenabled per lock.

func (*Service) RemovePasskey

func (s *Service) RemovePasskey(ctx context.Context, p access.Principal, id int64) error

RemovePasskey removes p's own passkey id, for a full session within RecentAuth, in one Update, with or without an RP(), so stale passkeys stay removable: a passkey the user does not hold is ErrNotFound, and a removal that leaves no method able to sign the user in now ErrLastMethod, both with nothing written.

func (*Service) RemovePassword

func (s *Service) RemovePassword(ctx context.Context, c Client, p access.Principal, current access.Secret) (Issued, error)

RemovePassword removes p's own password, for a full session within RecentAuth. current is that password: zero is ErrCurrentPasswordRequired before any limiter call. A user holding no password is ErrNotFound, and the last-method guard (ErrLastMethod) runs next, both before the count, so neither refusal charges or counts anything. current is then counted as SetPassword's. The removal commits only while the guard passes and the verified hash is still stored, resets the password's failure records, and rotates p's session into Issued with the device cookie.

func (*Service) RenamePasskey

func (s *Service) RenamePasskey(ctx context.Context, p access.Principal, id int64, name string) error

RenamePasskey renames p's own passkey id, for a full session, with or without an RP(). A name of more than 128 runes or not on one line is a *TextError with Field label; a passkey p's user does not hold is ErrNotFound.

func (*Service) RenameSession

func (s *Service) RenameSession(ctx context.Context, p access.Principal, in SessionLabel) error

RenameSession labels one of p's own sessions: at most 64 runes on one line (*TextError), the empty label clearing it. A session of another user, or none, is ErrNotFound.

func (*Service) RequireAdminScope

func (s *Service) RequireAdminScope(p access.Principal) error

RequireAdminScope admits p to the admin-scope operations: nil for a full session, or for a principal the built-in API-key verifier produced (access.Principal.IsAPIKey) carrying Config.AdminScope when that is set. Otherwise ErrSessionRequired for a recovery session or when AdminScope is empty, and ErrScopeRequired.

func (*Service) RequireKeyPermission

func (s *Service) RequireKeyPermission(p access.Principal, scope string) error

RequireKeyPermission admits p to an operation that scope opens to keys: nil for a full session within Rules().RecentAuth, or for a built-in API-key principal (access.Principal.IsAPIKey) carrying scope when scope is non-empty. Otherwise the session answers of RequireRecentAuth (ErrSessionRequired, ErrRecentAuthRequired), and ErrScopeRequired for a key, a custom verifier's principal or a bypass principal when scope is set. It reads the request's principal only: the write it guards re-checks a key's authority inside its Update.

func (*Service) RequireRecentAuth

func (s *Service) RequireRecentAuth(p access.Principal) error

RequireRecentAuth is access.RequireRecentAuth with the current Rules().RecentAuth and Config.Now; accesshttp's recent_auth guard calls it. An invalid Rules() value is ErrRulesInvalid.

func (*Service) RevokeAPIKey

func (s *Service) RevokeAPIKey(ctx context.Context, p access.Principal, id int64) error

RevokeAPIKey deletes one of p's own keys with its subtree, every key whose LineageIDs holds it, and every token those keys issued, in one Update; one EventKeyRevoked per key follows the commit. p must be a full session (ErrSessionRequired); a key of another user, or none, is ErrNotFound.

func (*Service) RevokeAnyAPIKey

func (s *Service) RevokeAnyAPIKey(ctx context.Context, p access.Principal, id int64) error

RevokeAnyAPIKey deletes any user's key with its subtree and their tokens, as RevokeAPIKey does, for a principal RequireAdminScope admits. A key principal's authority is re-read inside the Update with AdminScope (key_not_current), and that actor meets Policy (OpManageAllKeys) before the key is looked up, so a refusal says nothing of which keys exist; an unknown key is ErrNotFound.

func (*Service) RevokeOtherSessions

func (s *Service) RevokeOtherSessions(ctx context.Context, p access.Principal) error

RevokeOtherSessions ends every session of p's user but p's own. p must be a full session within Rules().RecentAuth. It emits EventUserSessionsRevoked with the ended IDs when there were any.

func (*Service) RevokeSession

func (s *Service) RevokeSession(ctx context.Context, p access.Principal, id string) error

RevokeSession ends one of p's own sessions, the current one included, and emits EventSessionRevoked after the commit. A session of another user, or none, is ErrNotFound.

func (*Service) Sessions

func (s *Service) Sessions(ctx context.Context, p access.Principal) ([]access.Session, error)

Sessions returns p's own sessions that the session verifier still accepts under Authenticator.Timeouts, oldest first. p must be a full session (ErrSessionRequired).

func (*Service) SetPassword

func (s *Service) SetPassword(ctx context.Context, c Client, p access.Principal, current, password access.Secret) (Issued, error)

SetPassword sets p's own password, for a full session within RecentAuth; a linked user under Rules.SSOGoverned is ErrSSOGoverned. A user holding a password must give it as current (zero: ErrCurrentPasswordRequired before any limiter call), counted like StepUpPassword's attempt. A user holding none has current ignored and commits only while still holding none. One Update writes the hash, rotates p's session into Issued (with the device cookie after a verified current), revokes the other sessions and, under Rules.RevokeKeysOnCredentialChange, the user's keys and their tokens.

func (*Service) SetupPasskeyBegin

func (s *Service) SetupPasskeyBegin(ctx context.Context, c Client, in SetupPasskey) (PendingCeremony, error)

SetupPasskeyBegin starts creating the first account, an admin signing in with a passkey. A nil RP() is ErrPasskeysUnavailable; then, as SetupWithPassword, a user present is ErrSetupComplete, a missing or invalid token where Rules.SetupTokenRequired asks for one ErrSetupTokenRequired or access.ErrTokenInvalid, and a refused name *UsernameError. Only a call past those refusals counts against c's IP request limit (*ratelimit.RefusedError). The token is only peeked; the finish spends it.

func (*Service) SetupPasskeyFinish

func (s *Service) SetupPasskeyFinish(ctx context.Context, c Client, ceremonyID string, body io.Reader) (SignedIn, error)

SetupPasskeyFinish verifies the attestation of the setup ceremonyID began, then in one Update spends the token the begin peeked, asks the Policy (OpCreateUser, ViaSetup), and creates the admin, its passkey and a full session. A concurrent setup that won is ErrSetupComplete or access.ErrTokenInvalid, with nothing written. An unknown, spent, expired or other ceremony is ErrCeremonyInvalid.

func (*Service) SetupWithPassword

func (s *Service) SetupWithPassword(ctx context.Context, c Client, in SetupPassword) (SignedIn, error)

SetupWithPassword creates the first account, an admin, and signs it in. Every check that can refuse runs before the hash: the user count, the token when Rules.SetupTokenRequired asks for one (nil: always), the username and password rules, then the IP limiter. One Update then consumes the token, asks the Policy (OpCreateUser, ViaSetup), creates the user and the session; a concurrent setup that won makes it ErrSetupComplete or access.ErrTokenInvalid, and a backend error leaves the token usable.

func (*Service) Shutdown

func (s *Service) Shutdown(ctx context.Context) error

Shutdown stops the sweep and waits for a sweep in progress, or returns ctx's error when ctx ends first; the sweep then still dispatches the events of a cleanup call that returned and stops before the next. Every operation called after Shutdown begins returns ErrServiceClosed. A second Shutdown waits the same way.

func (*Service) StartRecovery

func (s *Service) StartRecovery(ctx context.Context, c Client, token access.Secret) (Recovery, error)

StartRecovery consumes a recovery token and opens a SessionRecovery session for its subject in one Update, under Rules.SessionCaps and MaxSessionsPerUser; nobody is signed in. A zero, absent, expired or non-recovery token, or a gone or disabled subject, is access.ErrTokenInvalid before c's IP attempt limit. A key-issued token's issuer is re-checked as at its issue: a refusal commits only the token's deletion (access.ErrTokenInvalid), a pass records the key as Session.IssuedByKey with a recovery_started attribution. EventRecoveryConsumed names the key.

func (*Service) State

func (s *Service) State(ctx context.Context) (State, error)

State reports whether setup is needed and which sign-in methods are offered. It writes nothing.

func (*Service) StepUpPasskeyBegin

func (s *Service) StepUpPasskeyBegin(ctx context.Context, p access.Principal, origin webauthn.Origin) (PendingCeremony, error)

StepUpPasskeyBegin starts re-proving p's user with one of its passkeys under the current relying party's ID, for a full session. A nil RP() is ErrPasskeysUnavailable, and a user holding no such passkey ErrNotFound.

func (*Service) StepUpPasskeyFinish

func (s *Service) StepUpPasskeyFinish(ctx context.Context, c Client, p access.Principal, ceremonyID string, body io.Reader) (Issued, error)

StepUpPasskeyFinish completes the step-up ceremonyID began, against the passkeys p's user holds now, and rotates p's session to AuthTime now and AuthMethod MethodPasskey, returning in Issued a device cookie that keeps the ID of c.Device when that is valid for the user. A ceremony another user began is ErrCeremonyInvalid, and a session rotated or ended meanwhile ErrSessionGone.

func (*Service) StepUpPassword

func (s *Service) StepUpPassword(ctx context.Context, c Client, p access.Principal, password access.Secret) (Issued, error)

StepUpPassword re-proves p's user with password and rotates p's session to AuthTime now and AuthMethod MethodPassword, returning the device cookie in Issued. It needs a full session (ErrSessionRequired) and is refused under Rules.DisablePasswordLogin (ErrPasswordLoginDisabled). The attempt is limited on the account and device dimensions, never the client's IP, and counted like PasswordLogin's on the user's name, without an untrusted allowance slot. A wrong or locked password is ErrInvalidCredentials, and a session rotated or ended meanwhile ErrSessionGone.

func (*Service) Tokens

func (s *Service) Tokens(ctx context.Context, p access.Principal) ([]ListedToken, error)

Tokens lists every live invite and recovery token, never a setup token, by expiry and then creation, for a principal RequireAdminScope admits and Policy allows OpListUsers. Each key-issued row carries its issuer's LineageIDs from a second read; an issuer gone by then leaves it nil. It writes nothing.

func (*Service) UnlinkOIDC

func (s *Service) UnlinkOIDC(ctx context.Context, p access.Principal) error

UnlinkOIDC removes p's own user's OIDC link, for a full session within RecentAuth, in one Update: a user with no link is ErrNotFound, and a removal that leaves no method able to sign the user in now ErrLastMethod, both with nothing written.

func (*Service) UpdateProfile

func (s *Service) UpdateProfile(ctx context.Context, p access.Principal, displayName string) (Me, error)

UpdateProfile sets p's own display name: at most 128 runes on one line (*TextError), the empty name clearing it. p must be a full session (ErrSessionRequired); a user deleted since p was verified is ErrSessionGone. It returns p's Me view as committed, read inside the same Update, so a failed read rolls the name back.

func (*Service) UpdateUser

func (s *Service) UpdateUser(ctx context.Context, p access.Principal, userID int64, ch UserChange) (*access.User, error)

UpdateUser changes a user's role, enabled state or both (neither is ErrNoChange; the Policy decides self-changes), for an admin principal or a ManageUsersScope key. One Update asks OpSetRole, then OpSetEnabled on the user set with the role applied, for every set field even when unchanged, so a refusal answers before existence (ErrNotFound after). A key sets and acts on RoleUser only (admin_target). A role change revokes the sessions; a disable revokes every session, key and token those keys issued, and re-enabling restores none. It returns the user as committed.

func (*Service) UsableMethods

func (s *Service) UsableMethods(ctx context.Context, tx Tx, userID int64, st MethodState) (access.MethodAvailability, error)

UsableMethods counts what userID can sign in with under st, read through tx (the Store itself, or the app's own Update) as the last-method guard counts: a password held, allowed, usable and not locked in both trust contexts; passkeys registered under st.RPID; an OIDC link of st.OIDCIssuer; each only while st.Rules.MethodUsable allows it. The app decides with access.CanDisableMethod or its own rule. ErrServiceClosed after Shutdown, ErrRulesInvalid for an invalid st.Rules, ErrNotFound for an unknown user; a store error is returned as it is.

func (*Service) Users

func (s *Service) Users(ctx context.Context, p access.Principal, f UserFilter) ([]ListedUser, error)

Users lists every user by ID with its passkey count, for a principal RequireAdminScope admits and Policy allows OpListUsers. With f.AttributedToKey set it keeps the users holding a KeyAttribution whose KeyLineage contains that key, whether the key is live or gone. Each row carries the KeyLineage of the user's most recent record the filter matched. It writes nothing.

func (*Service) WebAuthnSignals

func (s *Service) WebAuthnSignals(ctx context.Context, p access.Principal) (webauthn.Signals, error)

WebAuthnSignals returns the reconciliation payloads for p's own user and the passkeys it holds under the current relying party's ID, for a full session. A nil RP() is ErrPasskeysUnavailable.

type SessionLabel

type SessionLabel struct{ ID, Label string }

SessionLabel is the input of RenameSession.

type SessionStore

type SessionStore interface {
	CreateSession(ctx context.Context, sess *access.Session) error
	SessionByHash(ctx context.Context, tokenHash access.Hash) (sess *access.Session, found bool, err error)
	SessionsByUserID(ctx context.Context, userID int64) ([]access.Session, error)
	// UpdateSessionActivity changes an existing session only; for a hash
	// no session has, it writes nothing and returns nil (rule 19). 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 (rule 21).
	UpdateSessionActivity(ctx context.Context, tokenHash access.Hash, act access.SessionActivity) error
	// RotateSession writes rot.Next over the session (rot.UserID, rot.ID),
	// atomically; Next keeps that ID and user, and the stored LastActivity
	// and LastIP stay when the stored LastActivity is after Next's (rule 21).
	// ErrNotFound when no session of that user has that ID, or when
	// ExpectHash is non-zero and not Equal to the session's TokenHash.
	RotateSession(ctx context.Context, rot Rotation) error
	UpdateSessionLabel(ctx context.Context, ref access.SessionRef, label string) error
	DeleteSession(ctx context.Context, ref access.SessionRef) error
	DeleteSessionByHash(ctx context.Context, tokenHash access.Hash) error // idempotent
	// DeleteUserSessions removes every session of userID but exceptID and
	// returns the IDs it removed.
	DeleteUserSessions(ctx context.Context, userID int64, exceptID string) ([]string, error)
}

SessionStore holds the session records.

type SetupLocality

type SetupLocality struct {
	// Local reports whether the resolved client counts as local. Nil means
	// no client is local, so the zero SetupLocality always requires a token:
	// which peers are local depends on a proxy topology only the app knows,
	// and behind a same-host reverse proxy that adds no forwarding header
	// the app's resolver sees, every client arrives as a loopback peer.
	Local func(access.ClientAddr) bool
	// Hosts lists the host names, besides IP literals and "localhost",
	// that a token-free setup may send as its Host.
	Hosts []string
}

SetupLocality is the library's rule for token-free first-run setup, for an app that passes TokenRequired as Rules.SetupTokenRequired. A nil SetupTokenRequired still means a token is always required.

func (SetupLocality) TokenRequired

func (l SetupLocality) TokenRequired(_ context.Context, c Client) bool

TokenRequired requires a setup token unless Local is set, Local(c.ClientAddr) holds and c.Host, with its port removed, ASCII lower-cased and one trailing dot dropped, is an IP literal with no zone, "localhost", or a Hosts entry canonicalised the same way. An empty or unparsable Host requires one. The Host rule closes DNS rebinding: a page that rebinds its own name to the server sends that name from a local peer.

type SetupPasskey

type SetupPasskey struct {
	Token    access.Secret // zero when the setup rule asks for none
	Username string
	Origin   webauthn.Origin
}

SetupPasskey is the input of SetupPasskeyBegin.

type SetupPassword

type SetupPassword struct {
	Token    access.Secret // zero when the setup rule asks for none
	Password access.Secret
	Username string
}

SetupPassword is the input of SetupWithPassword.

type SignedIn

type SignedIn struct {
	User         *access.User
	Token        access.Secret // the session cookie value
	DeviceCookie access.Secret // set when non-zero
	Session      access.Session
	CloneWarning bool
}

SignedIn is a new session for a sign-in, a setup or an invite acceptance.

type SingleOwnerPolicy

type SingleOwnerPolicy struct{}

SingleOwnerPolicy is the one-user policy: the account setup creates is the owner, and nothing adds, removes or changes a user.

func (SingleOwnerPolicy) Authorize

Authorize applies the single-owner rules to d.

type State

type State struct{ SetupRequired, PasswordLogin, Passkeys, OIDC bool }

State is what an anonymous caller may learn: whether setup is needed, and which sign-in methods are offered.

type Store

type Store interface {
	Tx
	Sweeper
	// Update runs fn in one serialisable read-write transaction. fn's nil
	// return commits every write durably and at once; an error or a panic
	// discards every write, and a panic is re-raised after the rollback.
	// A store with a durable medium serves concurrently pending Updates
	// with one durable commit (bbolt db.Batch, a file store's group commit),
	// so a burst of counted sign-ins costs one publish, not one each; fn may
	// then run more than once, and only its last run's writes count (rule 5).
	Update(ctx context.Context, fn func(tx Tx) error) error
}

Store is everything account reads and writes.

type Sweeper

type Sweeper interface {
	// CleanupExpiredSessions deletes, in one atomic step, at most limit of
	// the sessions access.ValidateSession refuses at now under timeouts, and
	// returns the ref of each session it deleted; fewer than limit refs
	// means none such is left (rule 14). A store may refuse a limit below 1
	// or a zero timeouts with an error.
	CleanupExpiredSessions(ctx context.Context, now time.Time, timeouts access.SessionTimeouts, limit int) ([]access.SessionRef, error)
	// CleanupExpiredOneTimeTokens deletes every token whose ExpiresAt is not
	// after now and returns how many it deleted.
	CleanupExpiredOneTimeTokens(ctx context.Context, now time.Time) (int64, error)
}

Sweeper holds the two expiry cleanups the background sweep calls, each a single-call write outside Update. They are not on Tx: inside a transaction, "exactly the refs it deleted, in one atomic step" cannot hold, since the Update may roll back or run again.

type TextError

type TextError struct {
	Field  string
	Reason string
}

TextError is a display text an operation refuses before any write. Field is one of TextErrorFields and Reason one of TextErrorReasons: disallowed_character is invalid UTF-8, a control, bidi control or line separator character.

func (*TextError) Error

func (e *TextError) Error() string

type TokenStore

type TokenStore interface {
	CreateOneTimeToken(ctx context.Context, tok access.OneTimeToken) error
	OneTimeTokenByHash(ctx context.Context, hash access.Hash) (tok access.OneTimeToken, found bool, err error)
	// ConsumeOneTimeToken reads and deletes in one step. An expired token is
	// deleted and reported as not found.
	ConsumeOneTimeToken(ctx context.Context, hash access.Hash, now time.Time) (tok access.OneTimeToken, found bool, err error)
	DeleteOneTimeTokens(ctx context.Context, purpose access.TokenPurpose, subject int64) (int, error)
	// LiveOneTimeTokens returns every token whose Purpose is in purposes
	// and whose ExpiresAt is after now, in any order.
	LiveOneTimeTokens(ctx context.Context, purposes []access.TokenPurpose, now time.Time) ([]access.OneTimeToken, error)
	// DeleteOneTimeTokensIssuedBy removes every token whose IssuedByKey is
	// in keyIDs, of any purpose and subject, and never one whose
	// IssuedByKey is 0.
	DeleteOneTimeTokensIssuedBy(ctx context.Context, keyIDs []int64) (int, error)
}

TokenStore holds the one-time tokens.

type Tx

Tx is the view of the store inside one transaction. It is valid only until the Update callback returns.

type UserChange

type UserChange struct {
	Role    *access.Role // empty is access.RoleUser
	Enabled *bool
}

UserChange is an admin's change to a user; a nil field is left as it is, and at least one must be set (ErrNoChange).

type UserFilter

type UserFilter struct {
	// AttributedToKey, when non-zero, keeps only the users with a
	// KeyAttribution whose KeyLineage contains it, for a live, expired,
	// revoked or deleted key alike.
	AttributedToKey int64
}

UserFilter narrows Users; the zero value lists every user.

type UserStore

type UserStore interface {
	// CreateUser assigns user.ID. Errors: ErrUsernameTaken, ErrOIDCIdentityTaken.
	CreateUser(ctx context.Context, user *access.User) error
	// CreateInitialUser creates user only while no user exists, atomically;
	// otherwise ErrSetupComplete.
	CreateInitialUser(ctx context.Context, user *access.User) error
	UserByID(ctx context.Context, id int64) (user *access.User, found bool, err error)
	UserByUsername(ctx context.Context, canonical string) (user *access.User, found bool, err error)
	UserByOIDC(ctx context.Context, id access.OIDCIdentity) (user *access.User, found bool, err error)
	UserByWebAuthnHandle(ctx context.Context, handle []byte) (user *access.User, found bool, err error)
	ListUsers(ctx context.Context) ([]access.User, error)
	// UpdateUser errors: ErrNotFound, ErrUsernameTaken, ErrOIDCIdentityTaken.
	UpdateUser(ctx context.Context, user *access.User) error
	// DeleteUser removes the user and, in the same transaction, every
	// session, passkey, key and token whose Subject is the user, and every
	// KeyAttribution whose UserID is the user. ErrNotFound when no user has id.
	DeleteUser(ctx context.Context, id int64) error
	UserCount(ctx context.Context) (int, error)
}

UserStore holds the user records.

type UsernameError

type UsernameError struct {
	Reason string
}

UsernameError is a username a creation path refuses, before any limiter call or hash. Reason is one of UsernameReasons.

func (*UsernameError) Error

func (e *UsernameError) Error() string

Jump to

Keyboard shortcuts

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