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 log entries on each run, so a re-run under a grouped commit appends and reports nothing twice, and no event is dispatched 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.
An app records its own change in the log by calling Service.AppendLog with its callback's tx. Tx.AppendLog is account's: a direct call skips AppendLog's validation and the class trim.
Contract rules ¶
- 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.
- 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.
- Canonical usernames. account passes access.NormalizeUsername output to CreateUser, UpdateUser and UserByUsername. The store indexes and compares those bytes exactly, and never normalises again.
- Uniqueness. Username (ErrUsernameTaken); a non-zero OIDCIdentity (ErrOIDCIdentityTaken); WebAuthnHandle; credential ID across all users (ErrDuplicateCredential); key hash, a KeyHash and a non-zero PreviousHash sharing one index (rule 23); 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.
- 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.
- 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, UpdateAPIKeySecret, UpdateAPIKeyLabel 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.
- 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.
- 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.
- Handle probing. UserByWebAuthnHandle answers an unknown handle and a malformed one the same way.
- 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.
- Time. Stored time.Time values round-trip to at least millisecond precision.
- Errors. Caller faults use only the sentinels of this package. Everything else is a backend error. context.Canceled and context.DeadlineExceeded pass through wrapped.
- Concurrency. Safe for concurrent use by many goroutines. No goroutine outlives a call.
- Cleanup. CleanupExpiredSessions deletes exactly the sessions for which access.ValidateSession(s, timeouts, now) fails: past idle or absolute, a plain session (Secure false) past min(timeouts, access.PlainSessionIdle and access.PlainSessionAbsolute), 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).
- 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 × MaxUntrustedCounts (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.
- 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.
- 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.
- 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.
- 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.
- Fidelity. Every exported field of every record a store keeps (User, Session, PasskeyCredential, Key, OneTimeToken, KeyAttribution, FailureCount, LogEntry, and the structs they embed or hold, OIDCIdentity, FailureRef, Event and EventActor) reads back as it was written, apart from what the store assigns (IDs, the LineageIDs append of rule 17, Event.Seq of rule 22). 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.
- 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 writes only when the stored KeyHash is the hash it carries, so a touch for a superseded secret writes nothing. RotateSession keeps the stored LastActivity and LastIP when the stored LastActivity is after Next's. No activity write lowers either; UpdateAPIKeySecret alone sets LastUsedAt to zero, in the same atomic write as the new KeyHash, because after a rotation LastUsedAt records only the new secret's use. 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.
- The security log. AppendLog assigns Event.Seq a positive integer no larger than 2^53 − 1 (rule 17's JSON bound), in commit order: a reader that sees an entry already sees every committed entry with a smaller Seq, and no entry with a smaller Seq commits after one with a larger Seq is visible. Rule 5 lets concurrent Updates be serialisable rather than serial, so "larger than every entry committed before it" is not enough: two writers could take 5 and 6 and commit 6 first, and a reader catching up with AfterSeq = 6 would never see 5. A store meets the rule by assigning Seq under the lock that orders its commits (MemStore's writer lock, bbolt's single writer transaction, a single-writer file store's mutex); a store with concurrent writers assigns it at commit, in commit order. A Seq is never assigned to two committed entries, after any prune and across a close and a reopen included, while a rolled-back or re-run Update may consume numbers no entry keeps, so gaps are allowed. An appended entry commits and rolls back with its Update (rule 5), and a re-run callback leaves only its last run's entries. A stored entry reads back with every field as written (rule 20), Event.SessionIDs and IP included, and reads return deep copies (rule 2). ListLog returns exactly the committed entries in its open range, in the asked order, at most Limit (a Limit below 1 may be refused). PruneLog removes exactly what its comment says, never an entry of another class and never more than Limit (a Limit below 1 may be refused), refuses a LogPrune with both Keep and Before set or neither, and returns the count. A Keep prune adds the count to its class's Evicted in the same Update; Evicted rolls back with that Update, survives a close and a reopen, and nothing else changes it. LogStats returns, per class that has ever held an entry, the committed Count and Evicted, and never waits on a write (rule 16). No other SPI method removes or changes an entry: DeleteUser's cascade deletes none. A store keeps the log with the durability of its users and keys: a store that resets derived data on a format change classifies its log records as durable, never derived.
- Key secrets. APIKeyByHash finds a key by its KeyHash or by its non-zero PreviousHash, and a zero hash finds nothing. UpdateAPIKeySecret writes KeyHash, KeyPrefix, KeySuffix, PreviousHash and PreviousUntil and zeroes LastUsedAt in one atomic write (rule 21); the hash it supersedes as PreviousHash leaves the index in that write, so after rotations A to B to C only B and C find the key. A delete removes both hashes. ClearRetiredAPIKeySecrets zeroes PreviousHash and PreviousUntil where its predicate holds, evaluated inside its own atomic write and never from a list read before it, so a rotation committed meanwhile keeps its new previous secret. It clears at most limit keys, never writes KeyHash, and a count below limit left no key to clear at now.
Index ¶
- Constants
- Variables
- func AppEntryReasons() []string
- func LogFilterReasons() []string
- func PolicyReasons() []string
- func TextErrorFields() []string
- func TextErrorReasons() []string
- func UsernameReasons() []string
- type AcceptInvite
- type Actor
- type AppEntry
- type AppEntryError
- type AttributionStore
- type BreachMode
- type Client
- type Config
- type CreateVia
- type CreatedKey
- type Credentials
- type CurrentSession
- type Decision
- type Event
- type EventActor
- type EventKind
- type FailureCount
- type FailureRef
- type FailureStore
- type HTTPSFeature
- type Issued
- type IssuedToken
- type KeyStore
- type ListedKey
- type ListedToken
- type ListedUser
- type Locality
- type LogClass
- type LogClassStats
- type LogEntry
- type LogFilter
- type LogFilterError
- type LogPage
- type LogPrune
- type LogRange
- type LogStore
- type LoginMode
- type Me
- type MethodLock
- type MethodState
- type Methods
- type NewKey
- type NewUser
- type OIDCOutcome
- type OIDCOutcomeKind
- type Operation
- type PasskeyStore
- type PendingCeremony
- type PendingLink
- type Policy
- type PolicyError
- type RecoverOptions
- type Recovery
- type Registered
- type RolePolicy
- type RotatedKey
- type Rotation
- type Rules
- type RulesError
- type Service
- func (s *Service) APIKeys(ctx context.Context, p access.Principal) ([]access.Key, error)
- func (s *Service) AcceptInvitePassword(ctx context.Context, c Client, in AcceptInvite) (SignedIn, error)
- func (s *Service) AdminScope() string
- func (s *Service) AdmitOIDC(c Client) (*oidc.Provider, error)
- func (s *Service) AdmitOIDCSession(c Client, p access.Principal) (*oidc.Provider, error)
- func (s *Service) AllAPIKeys(ctx context.Context, a Actor) ([]ListedKey, error)
- func (s *Service) AppendLog(ctx context.Context, tx Tx, e AppEntry) (LogEntry, error)
- func (s *Service) Authenticator() *access.Authenticator
- func (s *Service) CreateAPIKey(ctx context.Context, a Actor, userID int64, in NewKey) (CreatedKey, error)
- func (s *Service) CreateInvite(ctx context.Context, p access.Principal, role access.Role, ttl time.Duration) (IssuedToken, error)
- func (s *Service) CreateKeysScope() string
- func (s *Service) CreateUser(ctx context.Context, a Actor, in NewUser) (*access.User, error)
- func (s *Service) DeleteUser(ctx context.Context, p access.Principal, userID int64) error
- func (s *Service) IssueRecovery(ctx context.Context, a Actor, userID int64, ttl time.Duration) (IssuedToken, error)
- func (s *Service) IssueSetupToken(ctx context.Context, a Actor, ttl time.Duration) (access.Secret, error)
- func (s *Service) LinkPendingOIDC(ctx context.Context, p access.Principal, pending PendingLink) (Issued, Me, error)
- func (s *Service) Logout(ctx context.Context, tokenHash access.Hash) error
- func (s *Service) ManageUsersScope() string
- func (s *Service) Me(ctx context.Context, p access.Principal) (Me, error)
- func (s *Service) OIDCComplete(ctx context.Context, c Client, flow oidc.Flow, claims oidc.Claims) (OIDCOutcome, error)
- func (s *Service) PasskeyLoginBegin(_ context.Context, c Client, origin webauthn.Origin, mode LoginMode) (PendingCeremony, error)
- func (s *Service) PasskeyLoginFinish(ctx context.Context, c Client, ceremonyID string, body io.Reader) (SignedIn, error)
- func (s *Service) PasskeyRegisterBegin(ctx context.Context, p access.Principal, origin webauthn.Origin) (PendingCeremony, error)
- func (s *Service) PasskeyRegisterFinish(ctx context.Context, p access.Principal, ceremonyID string, body io.Reader) (Registered, error)
- func (s *Service) Passkeys(ctx context.Context, p access.Principal) ([]access.PasskeyCredential, error)
- func (s *Service) PasswordLogin(ctx context.Context, c Client, in Credentials) (SignedIn, error)
- func (s *Service) RecoverOutOfBand(ctx context.Context, a Actor, userID int64, password access.Secret, ...) error
- func (s *Service) RecoverPasskeyBegin(ctx context.Context, p access.Principal, origin webauthn.Origin) (PendingCeremony, error)
- func (s *Service) RecoverPasskeyFinish(ctx context.Context, p access.Principal, ceremonyID string, body io.Reader, ...) error
- func (s *Service) RecoverWithPassword(ctx context.Context, p access.Principal, password access.Secret, ...) error
- func (s *Service) ReenableMethod(ctx context.Context, p access.Principal, method access.Method) error
- func (s *Service) RemovePasskey(ctx context.Context, p access.Principal, id int64) error
- func (s *Service) RemovePassword(ctx context.Context, c Client, p access.Principal, current access.Secret) (Issued, error)
- func (s *Service) RenameAPIKey(ctx context.Context, p access.Principal, id int64, label string) error
- func (s *Service) RenamePasskey(ctx context.Context, p access.Principal, id int64, name string) error
- func (s *Service) RenameSession(ctx context.Context, p access.Principal, in SessionLabel) error
- func (s *Service) RequireAdminScope(p access.Principal) error
- func (s *Service) RequireKeyPermission(p access.Principal, scope string) error
- func (s *Service) RequireRecentAuth(p access.Principal) error
- func (s *Service) RevokeAPIKey(ctx context.Context, p access.Principal, id int64) error
- func (s *Service) RevokeAnyAPIKey(ctx context.Context, a Actor, id int64) error
- func (s *Service) RevokeOtherSessions(ctx context.Context, p access.Principal) error
- func (s *Service) RevokeSession(ctx context.Context, p access.Principal, id string) error
- func (s *Service) RevokeTransportMismatch(ctx context.Context, ref access.SessionRef) error
- func (s *Service) RotateAPIKey(ctx context.Context, a Actor, id int64) (RotatedKey, error)
- func (s *Service) SecurityLog(ctx context.Context, p access.Principal, f LogFilter) (LogPage, error)
- func (s *Service) Sessions(ctx context.Context, p access.Principal) ([]access.Session, error)
- func (s *Service) SetPassword(ctx context.Context, c Client, p access.Principal, ...) (Issued, error)
- func (s *Service) SetupPasskeyBegin(ctx context.Context, c Client, in SetupPasskey) (PendingCeremony, error)
- func (s *Service) SetupPasskeyFinish(ctx context.Context, c Client, ceremonyID string, body io.Reader) (SignedIn, error)
- func (s *Service) SetupWithPassword(ctx context.Context, c Client, in SetupPassword) (SignedIn, error)
- func (s *Service) Shutdown(ctx context.Context) error
- func (s *Service) StartRecovery(ctx context.Context, c Client, token access.Secret) (Recovery, error)
- func (s *Service) State(ctx context.Context, c Client) (State, error)
- func (s *Service) StepUpPasskeyBegin(ctx context.Context, p access.Principal, origin webauthn.Origin) (PendingCeremony, error)
- func (s *Service) StepUpPasskeyFinish(ctx context.Context, c Client, p access.Principal, ceremonyID string, ...) (Issued, error)
- func (s *Service) StepUpPassword(ctx context.Context, c Client, p access.Principal, password access.Secret) (Issued, error)
- func (s *Service) Tokens(ctx context.Context, p access.Principal) ([]ListedToken, error)
- func (s *Service) UnlinkOIDC(ctx context.Context, p access.Principal) error
- func (s *Service) UpdateProfile(ctx context.Context, p access.Principal, displayName string) (Me, error)
- func (s *Service) UpdateUser(ctx context.Context, p access.Principal, userID int64, ch UserChange) (*access.User, error)
- func (s *Service) UsableMethods(ctx context.Context, tx Tx, userID int64, st MethodState) (access.MethodAvailability, error)
- func (s *Service) Users(ctx context.Context, p access.Principal, f UserFilter) ([]ListedUser, error)
- func (s *Service) WebAuthnSignals(ctx context.Context, p access.Principal) (webauthn.Signals, error)
- type SessionLabel
- type SessionStore
- type SetupPasskey
- type SetupPassword
- type SignedIn
- type SingleOwnerPolicy
- type State
- type Store
- type Sweeper
- type TextError
- type TokenStore
- type Tx
- type UserChange
- type UserFilter
- type UserStore
- type UsernameError
Constants ¶
const ( ReasonOutOfBandOnly = "out_of_band_only" ReasonKeyNotCurrent = "key_not_current" ReasonKeyRetiring = "key_retiring" ReasonKeyExpired = "key_expired" 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. ReasonKeyRetiring is a key principal presenting a secret a rotation superseded, which an operation that creates or restores a way in refuses.
const ( ReasonLogLimit = "log_limit" // Limit negative or above MaxLogPage ReasonLogRange = "log_range" // a Seq bound above 2^53 - 1, or no Seq between AfterSeq and BeforeSeq ReasonLogKind = "log_kind" // a kind that is neither an EventKinds value nor an app kind ReasonLogID = "log_id" // a negative user or key ID )
The LogFilterError Reasons, in LogFilterReasons order.
const ( ReasonAppKind = "app_kind" ReasonAppDetail = "app_detail" ReasonAppMethod = "app_method" )
The AppEntryError Reasons, in AppEntryReasons order.
const ( ReasonEmpty = "empty" ReasonDisallowedCharacter = "disallowed_character" ReasonTooLong = "too_long" )
The UsernameError and TextError Reasons. A TextError is ReasonEmpty only for a key label: every other display text may be empty.
const ( TextFieldLabel = "label" // a key or session label, or a passkey name TextFieldDisplayName = "display_name" )
The TextError Fields.
const ( // LogDetailTransportChanged is a session revoked for being presented on // the other transport (see [access.Session.Secure]). LogDetailTransportChanged = access.ReasonTransportChanged // LogDetailSignedInAgain is the session a fresh sign-in replaced: the // one its request presented (Client.Presented). LogDetailSignedInAgain = "signed_in_again" )
The library's LogEntry.Detail values, each on a session_revoked entry.
const ( DefaultLogPage = 50 // a LogFilter's zero Limit MaxLogPage = 500 // the largest Limit, and the size of each store read )
The SecurityLog page sizes.
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 most keys one ClearRetiredAPIKeySecrets call // clears, and the most entries one PruneLog call of New's log drain or // the sweep removes; each calls again until a call removes fewer. MaxSweepBatch = 1000 // DefaultLogMaxAge is Config.LogMaxAge's default. DefaultLogMaxAge = 365 * 24 * time.Hour // DefaultLogMaxChanges is Config.LogMaxChanges's default. DefaultLogMaxChanges = 10000 // DefaultLogMaxSessions is Config.LogMaxSessions's default. DefaultLogMaxSessions = 10000 )
Variables ¶
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.
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") // ErrKeyLabelTaken is a key label another unexpired key of the same // owner already carries, compared after NFC and Unicode case folding. ErrKeyLabelTaken = errors.New("account: a key with this label already exists") // 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") 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") // 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.
var ErrLogFilterInvalid = errors.New("account: log filter invalid")
ErrLogFilterInvalid is matched by every *LogFilterError.
Functions ¶
func AppEntryReasons ¶
func AppEntryReasons() []string
AppEntryReasons returns every AppEntryError Reason, in a stable order.
func LogFilterReasons ¶
func LogFilterReasons() []string
LogFilterReasons returns every LogFilterError Reason, in a stable order.
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 ¶
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 OutOfBand ¶
OutOfBand is an actor outside any request (an admin socket, a CLI); channel names it in events.
func (Actor) OutOfBandChannel ¶
OutOfBandChannel returns the channel of an out-of-band actor, and false for any other.
type AppEntry ¶
type AppEntry struct {
Kind string // "<app>.<name>": lowercase, at least one dot, at most 64 bytes
Method access.Method // optional; a lowercase token of at most 64 bytes, auth's or the app's own
Detail string // at most 256 bytes, one line, printable
Actor Actor // As(p), OutOfBand(channel), or the zero Actor for none
}
AppEntry is an app's own entry, appended in the app's own Update.
type AppEntryError ¶
type AppEntryError struct {
Reason string
}
AppEntryError reports why AppendLog refused an entry. Reason is one of AppEntryReasons.
func (*AppEntryError) Error ¶
func (e *AppEntryError) Error() string
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
// Presented is the hash of the session cookie the request carried under
// its own transport's name (access.CookieConfig.ReadCookie), never the
// other name's; zero when none. A full sign-in replaces that session
// when it is the same user's on the same transport.
Presented access.Hash
// 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, in Seq order,
// synchronously in the committing goroutine. It must not block. Delivery
// is at most once; the security log, appended in the same Update, is
// the durable record.
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 carrying it list users, every user's
// keys and the live invite and recovery tokens, read the security log and
// revoke any key, where Policy allows. 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, failure records of names that are not users and
// security-log entries past LogMaxAge are swept, and locks reported;
// zero means 5m.
CleanupInterval time.Duration
// MaxPending bounds the pending WebAuthn ceremonies; zero means 10000.
MaxPending int
// LogMaxAge is how long a security-log entry is kept; zero means
// DefaultLogMaxAge. Each sweep removes older entries, so one may stay up
// to a CleanupInterval longer.
LogMaxAge time.Duration
// LogMaxChanges and LogMaxSessions cap the entries of LogClassChange and
// LogClassSession; zero means DefaultLogMaxChanges and
// DefaultLogMaxSessions. Every append removes its class's oldest entries
// beyond the cap in the same Update, counted in LogClassStats.Evicted,
// and New first drains a log already past a cap.
LogMaxChanges int
LogMaxSessions 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 ¶
Credentials is the input of PasswordLogin.
type CurrentSession ¶
type CurrentSession struct {
AuthTime, IdleDeadline, AbsoluteDeadline time.Time
ID string
Method access.Method
Secure bool // the session's transport, access.Principal.Secure
}
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, and so does AllAPIKeys, whose key actor is re-read there; the other list reads, 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, re-enable, and the credential a recovery installed
// Role is the new role of an EventRoleChanged, the created user's of an
// EventUserCreated and the invite's of an EventInviteIssued.
Role access.Role
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
// Seq is the Seq of the log entry this event's commit appended; 0 for
// EventSessionsExpired, which the log does not hold.
Seq uint64
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, never its log entry.
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" 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" EventKeyRotated EventKind = "key_rotated" EventSteppedUp EventKind = "stepped_up" EventUserDisabled EventKind = "user_disabled" EventUserEnabled EventKind = "user_enabled" EventUserDeleted EventKind = "user_deleted" EventRoleChanged EventKind = "role_changed" EventUserCreated EventKind = "user_created" EventInviteIssued EventKind = "invite_issued" EventMethodLocked EventKind = "method_locked" // a failure counter reached the cap; reported by the sweep, or by the Update that clears an unreported lock EventMethodReenabled EventKind = "method_reenabled" // recovery, ReenableMethod or a sign-in cleared a lock, after its commit )
The event kinds.
func EventKinds ¶
func EventKinds() []EventKind
EventKinds returns every EventKind, in declaration order.
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 HTTPSFeature ¶
type HTTPSFeature string
HTTPSFeature is a sign-in feature a plain request is refused.
const ( HTTPSPassword HTTPSFeature = "password" HTTPSSetup HTTPSFeature = "setup" HTTPSPasskeys HTTPSFeature = "passkeys" HTTPSOIDC HTTPSFeature = "oidc" )
The features, in State.HTTPSRequired's order.
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 finds the key whose KeyHash, or whose non-zero
// PreviousHash, equals hash; a zero hash finds nothing (rule 23).
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 the stored KeyHash equals
// hash and at is after the stored LastUsedAt, atomically; otherwise, an
// unknown key included, it writes nothing and returns nil (rules 19
// and 21).
TouchAPIKey(ctx context.Context, keyID int64, hash access.Hash, at time.Time) error
// UpdateAPIKeySecret writes s's five fields over the key ref names and
// zeroes its LastUsedAt, in one atomic write (rules 21 and 23).
// ErrNotFound when no key of ref.UserID has ref.ID (rule 6).
UpdateAPIKeySecret(ctx context.Context, ref access.KeyRef, s access.KeySecret) error
// UpdateAPIKeyLabel writes label over the key ref names and nothing
// else. ErrNotFound when no key of ref.UserID has ref.ID (rule 6).
UpdateAPIKeyLabel(ctx context.Context, ref access.KeyRef, label string) 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 Locality ¶
type Locality struct {
// Forwarder reports whether a direct peer relays others' connections
// into this network namespace: a container bridge's gateway, the host's
// own addresses seen through a port proxy. It is the app's, since only
// the app can read its routes and interfaces, and it gets the peer with
// no zone and unmapped. Nil means it cannot tell, so no client is local.
// An app with no forwarder at all passes
// func(netip.Addr) bool { return false } and says so in its code.
Forwarder func(netip.Addr) bool
// Hosts lists the host names, besides IP literals and "localhost", that
// a token-free setup may send as its Host.
Hosts []string
}
Locality is the library's rule for a local client, one a decision may trust more. TokenRequired, passed as Rules.SetupTokenRequired, lets a local client set up the first user with no token, and an app calls Local for any other such decision. The zero value makes no client local, and a nil Rules.SetupTokenRequired still means a token is always required.
func (Locality) Local ¶
func (l Locality) Local(c access.ClientAddr) bool
Local reports whether c is a local client: c.Via is ViaDirect, Forwarder is set, and c.Peer is valid, loopback or private (127.0.0.0/8, ::1, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7), and not a Forwarder. An IPv4-mapped peer is judged as IPv4, so ::ffff:192.168.1.5 is local and ::ffff:100.64.0.1 is not. A forwarded address is never local. A remote client behind a loopback relay, a NAT outside the namespace or an IPv6 overlay inside fc00::/7 reads as local.
func (Locality) TokenRequired ¶
TokenRequired requires a setup token unless 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 LogClass ¶
type LogClass string
LogClass separates the entries retention counts apart, so session churn never evicts an account change.
type LogClassStats ¶
type LogClassStats struct {
Class LogClass
Count int // entries the class holds now
Evicted uint64 // entries Keep prunes have removed, ever; never lowered
}
LogClassStats is one class's entry count and cap evictions.
type LogEntry ¶
type LogEntry struct {
// At is when the Update appended the entry, from Config.Now at
// millisecond precision (rule 11); Seq order is append order.
At time.Time
IP netip.Addr // the acting request's client address; zero for none
Class LogClass
// The actor's display data, from the run's snapshot cache, resolved
// when the operation's callback returns; empty when it does not apply.
ActorLabel string // the acting session's Label, or the acting key's Label
ActorUserAgent string // the acting session's UserAgent
ActorKeySuffix string // the acting key's Suffix
// Detail is an app entry's own detail, or a library session_revoked's
// LogDetailTransportChanged or LogDetailSignedInAgain; empty on every
// other library entry.
Detail string
Event Event // Kind, the subject, the actor's IDs, the kind's fields, and Seq
}
LogEntry is one committed change. The store assigns Event.Seq; account fills every other field inside the Update that made the change.
type LogFilter ¶
type LogFilter struct {
Kinds []EventKind // library or app kinds; nil is every kind
AfterSeq, BeforeSeq uint64 // exclusive bounds; 0 is unbounded; neither sets the order
UserID int64 // the subject (Event.UserID); 0 is every entry
ActorUserID int64 // Event.Actor.UserID; 0 is any
ActorKeyID int64 // Event.Actor.KeyID; 0 is any
Limit int // 0 is DefaultLogPage; at most MaxLogPage
OldestFirst bool // ascending Seq; false is newest first
}
LogFilter narrows SecurityLog; the zero value is the newest DefaultLogPage entries of every kind, app entries included.
type LogFilterError ¶
type LogFilterError struct {
Reason string
}
LogFilterError is a LogFilter SecurityLog refuses, before any store read. Reason is one of LogFilterReasons. It matches ErrLogFilterInvalid.
func (*LogFilterError) Error ¶
func (e *LogFilterError) Error() string
func (*LogFilterError) Is ¶
func (*LogFilterError) Is(target error) bool
Is reports ErrLogFilterInvalid.
type LogPage ¶
type LogPage struct {
Entries []LogEntry
Classes []LogClassStats // one per LogClasses() value; a class never written has zero counts
}
LogPage is one SecurityLog answer: the matching entries, and every class's count and cap evictions, read from the same store as the page.
type LogPrune ¶
LogPrune is one LogStore.PruneLog call, with exactly one of Keep (a positive cap) and Before (a non-zero age bound) set.
type LogRange ¶
LogRange is one LogStore.ListLog call: an open Seq range, 0 BeforeSeq being unbounded.
type LogStore ¶
type LogStore interface {
// AppendLog assigns e.Event.Seq and stores a deep copy (rule 22).
AppendLog(ctx context.Context, e *LogEntry) error
// ListLog returns the entries with r.AfterSeq < Seq, and Seq <
// r.BeforeSeq when r.BeforeSeq is non-zero, in ascending Seq, or
// descending when r.Descending, at most r.Limit of them (rule 22).
ListLog(ctx context.Context, r LogRange) ([]LogEntry, error)
// PruneLog removes entries of p.Class, lowest Seq first: with p.Keep
// set, each beyond the newest p.Keep of that class, adding the number
// removed to the class's Evicted; with p.Before set, each with At
// before p.Before. Exactly one of the two is set, else it returns an
// error. It removes at most p.Limit and returns how many (rule 22).
PruneLog(ctx context.Context, p LogPrune) (int, error)
// LogStats returns one LogClassStats per class that has ever held an
// entry, in [LogClasses] order (rule 22).
LogStats(ctx context.Context) ([]LogClassStats, error)
}
LogStore holds the append-only security log (LogEntry). It has no update; entries leave only through PruneLog.
type LoginMode ¶
type LoginMode int
LoginMode is how a passkey sign-in asks the browser for a credential.
type Me ¶
type Me struct {
User *access.User
Current CurrentSession
Methods Methods
CanLinkOIDC bool // OIDCAvailable and not OIDCLinked
// SSOGoverned is Rules.SSOGoverned on a linked user: SetPassword and
// passkey registration answer ErrSSOGoverned.
SSOGoverned bool
}
Me is the signed-in user's own view.
type MethodLock ¶
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 is required, one line of at most 128 runes, and no label of the
// owner's unexpired keys after NFC and case folding (ErrKeyLabelTaken).
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, the live invite and recovery tokens, and the security log 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 OpRotateKey Operation = "rotate_key" // a new secret for Target's key, by OutOfBand or Target's own session )
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 ¶
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. An OutOfBand actor reaches it for OpCreateUser, OpIssueRecovery, OpCreateKeyFor, OpManageAllKeys and OpRotateKey, so an app's own Policy decides each. OpRotateKey's Target is the key's owner as stored.
type PolicyError ¶
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
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 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) and rotate its own (OpRotateKey); 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.
type RotatedKey ¶
type RotatedKey struct {
Plaintext access.Secret
Key access.Key // PreviousUntil set, LastUsedAt zero
Issued Issued // zero for an out-of-band actor
}
RotatedKey is a key RotateAPIKey gave a new secret; Plaintext is shown once.
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; [Locality.TokenRequired] is the
// library's rule for a local client.
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
// HTTPSOrigin is the app's HTTPS origin ("https://host[:port]"), which
// State answers a plain request so its screen can link there. It is a
// link only, and nothing trusts it. Empty means none.
HTTPSOrigin string
// ForbiddenWords join the username in the password context check.
ForbiddenWords []string
// Scopes is the key-scope vocabulary; CreateAPIKey refuses any other.
// Each is one RFC 6750 scope-token: printable ASCII but space, '"' and '\'.
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
// KeyRotationOverlap is how long RotateAPIKey lets a key's superseded
// secret verify while its new one is unused. Zero means 1h; a value
// below 1m or above 24h is invalid.
KeyRotationOverlap 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 and their
// tokens when SetPassword sets or changes the password, and when an OIDC
// link migrates the account under SSOGoverned. 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.
type RulesError ¶
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) 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 ¶
New refuses a nil Store, Policy, Authenticator, Hasher, Limiter or Rules, a FailureKey that is not 32 bytes (naming the field, never the bytes), a non-empty key scope that is not one RFC 6750 scope-token or equals another, a negative CleanupInterval, MaxPending or Log* field, and a Rules() value Rules.Validate refuses or whose breach mode lacks Config.Breach. It drains the security log and sweeps the failure records, returning either's store error, then registers the Service as the Authenticator's one session revoker (an error if one is). It sweeps on ctx's values, not its cancellation, until Shutdown.
func (*Service) APIKeys ¶
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; a plain c is access.ErrHTTPSRequired. 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 ¶
AdminScope returns Config.AdminScope.
func (*Service) AdmitOIDC ¶
AdmitOIDC is an anonymous OIDC request's one provider read, for the sign-in start, the callback and the pending-link read: ErrServiceClosed, then access.ErrHTTPSRequired for a plain c, then ErrOIDCUnavailable for a nil OIDC(), each charging nothing, then Limiter.Request on c's IP (*ratelimit.RefusedError), else the provider for the whole request.
func (*Service) AdmitOIDCSession ¶
AdmitOIDCSession is a session-bound OIDC start's one provider read, for a link or a step-up by p from c: ErrServiceClosed, then access.ErrHTTPSRequired unless c and p are both secure, then ErrOIDCUnavailable for a nil OIDC(), else the provider for the whole request. It charges no limiter.
func (*Service) AllAPIKeys ¶
AllAPIKeys returns every user's keys by ID, each with its owner's username, for an out-of-band actor or a principal RequireAdminScope admits; the zero Actor is ErrSessionRequired. Inside one read transaction a key principal's authority is re-read with AdminScope (key_not_current), and the actor meets Policy (OpManageAllKeys). The keys and the users are read in that 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) AppendLog ¶
AppendLog appends e through tx, the caller's own Store.Update callback's, and returns the entry with its Seq. It sets At, Class (LogClassChange), the actor snapshot and IP, and trims the change class in the same tx. It fires no OnEvent and reads no Config.Rules value, so an invalid one never fails the app's own change. e.Method is open: an app's own method passes. A refused entry is an *AppEntryError, after Shutdown ErrServiceClosed, a store error matches access.ErrAuthBackend, and none appends anything. Return the error from the callback, so the app's change rolls back with the entry.
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, for OutOfBand (OpCreateKeyFor) or a principal of userID's own user that RequireKeyPermission admits under CreateKeysScope (OpCreateOwnKey; another user is other_user; plain: access.ErrHTTPSRequired). Scopes come from Rules().Scopes (ErrUnknownScope), a permission scope only on a RoleAdmin owner (permission_not_admin); Label and ExpiresIn meet NewKey's rules. A key actor's parent is re-read in the Update, needs its current secret (key_retiring), and bounds the child's scopes, expiry and depth.
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 (plain: access.ErrHTTPSRequired), and returns its plaintext once. Policy (OpInvite) decides inside the Update; a key's authority is re-read there (key_not_current) and needs its current secret (key_retiring), 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 ¶
CreateKeysScope returns Config.CreateKeysScope.
func (*Service) CreateUser ¶
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) and needs its current secret (key_retiring), creates a RoleUser only (admin_target), and appends a created attribution with its LineageIDs.
func (*Service) DeleteUser ¶
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, voiding earlier ones, for an out-of-band actor (ttl 0: 15 min) or an admin principal or ManageUsersScope key (ttl 0: 24 h; plain: access.ErrHTTPSRequired); above 7 × that default is ErrTTLTooLong. A principal naming its own ID is self_recovery before any Policy or store call. Policy (OpIssueRecovery) answers before existence (ErrNotFound after). A key, re-read in the Update (key_not_current), needs its current secret (key_retiring) and issues for a RoleUser only (admin_target) a token recording IssuedByKey, expiring within the key's life.
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; plain: access.ErrHTTPSRequired) 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 ¶
Logout ends the session whose token hashes to tokenHash. It is idempotent: no such session is nil, and only a session it ended has an EventSessionRevoked, carrying that session's display data.
func (*Service) ManageUsersScope ¶
ManageUsersScope returns Config.ManageUsersScope.
func (*Service) Me ¶
Me returns p's own view: the user as stored, its sign-in methods with their failure-cap locks, whether single sign-on governs them, 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, charging no limiter. A plain c is access.ErrHTTPSRequired and a nil OIDC() 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) 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 plain c is access.ErrHTTPSRequired, a nil RP() 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. A plain c is access.ErrHTTPSRequired, and an unknown, spent, expired or other ceremony 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 plain p is access.ErrHTTPSRequired, a nil RP() ErrPasskeysUnavailable, and a linked user under Rules.SSOGoverned 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 plain p is access.ErrHTTPSRequired, a ceremony another user began ErrCeremonyInvalid, and a credential already registered to any user ErrDuplicateCredential.
func (*Service) Passkeys ¶
func (s *Service) Passkeys(ctx context.Context, p access.Principal) ([]access.PasskeyCredential, error)
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 ¶
PasswordLogin signs a user in with a password. Before any store call it answers access.ErrHTTPSRequired (plain c, PostureSecure), ErrPasswordLoginDisabled, a *UsernameError, a *ratelimit.RefusedError (the limiter's, or Dimension "untrusted" past its allowance) or access.ErrHashBusy. Each later attempt is counted before the compare, 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 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 plain p is access.ErrHTTPSRequired and a nil RP() 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 plain p is access.ErrHTTPSRequired, a ceremony another user began 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 (plain: access.ErrHTTPSRequired; 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 addRecovered'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. The same Update appends EventMethodLocked for each lock the sweep had not reported, then EventMethodReenabled per lock.
func (*Service) RemovePasskey ¶
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 (plain c or p: access.ErrHTTPSRequired). 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) RenameAPIKey ¶
func (s *Service) RenameAPIKey(ctx context.Context, p access.Principal, id int64, label string) error
RenameAPIKey sets the label of p's own key id, expired or not, under NewKey.Label's rule, the key's own label aside, so a key can be recased. p must be a full session (ErrSessionRequired); a key of another user, or none, is ErrNotFound. A rename changes no authority and logs no event.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
RevokeAnyAPIKey deletes any user's key with its subtree and their tokens, as RevokeAPIKey does, for the actors AllAPIKeys admits. A key principal's authority is re-read inside the Update with AdminScope (key_not_current), and the actor meets Policy (OpManageAllKeys) before the key is looked up, so a refusal says nothing of which keys exist; an unknown key is ErrNotFound. Each EventKeyRevoked names a.
func (*Service) RevokeOtherSessions ¶
RevokeOtherSessions ends every session of p's user but p's own. p must be a full session within Rules().RecentAuth. Its EventUserSessionsRevoked names the ended IDs, when there were any.
func (*Service) RevokeSession ¶
RevokeSession ends one of p's own sessions, the current one included, with its EventSessionRevoked. A session of another user, or none, is ErrNotFound.
func (*Service) RevokeTransportMismatch ¶
RevokeTransportMismatch ends the session ref names, which the Authenticator's session verifier refused for its transport; New registers the Service for it with access.Authenticator.UseSessionRevoker. A session already gone is nil with no event; otherwise one Update deletes it and journals its EventSessionRevoked with LogDetailTransportChanged.
func (*Service) RotateAPIKey ¶
RotateAPIKey gives key id a new secret and keeps the rest of it; the old secret verifies for Rules.KeyRotationOverlap or until the new one's first use, and a rotation during an overlap replaces it. a is OutOfBand, reaching every key, or a full session within RecentAuth, reaching its own user's keys and rotating into Issued; a plain one is access.ErrHTTPSRequired and any other actor ErrSessionRequired before any read. An unreachable key is ErrNotFound; then Policy (OpRotateKey) decides on the owner as stored, and an expired key is a refused key_expired; one EventKeyRotated follows the commit.
func (*Service) SecurityLog ¶
func (s *Service) SecurityLog(ctx context.Context, p access.Principal, f LogFilter) (LogPage, error)
SecurityLog returns the entries matching f, newest first, or oldest first when f.OldestFirst is set, at most f.Limit of them, and every class's stats. It admits what Users admits: a full session or an admin-scope key whose Policy allows OpListUsers. A refused principal never learns whether f is valid; an invalid f is a *LogFilterError, refused before any store read. It reads outside Update, so it never waits on a commit.
func (*Service) Sessions ¶
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 (plain c or p under PostureSecure: access.ErrHTTPSRequired); a linked user under Rules.SSOGoverned is ErrSSOGoverned. A user holding a password gives it as current (zero: ErrCurrentPasswordRequired before any limiter call), counted like StepUpPassword's attempt; one holding none has current ignored, committing while it still holds none. One Update writes the hash, rotates p's session into Issued, revokes the other sessions and, under RevokeKeysOnCredentialChange, the user's keys and 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 plain c is access.ErrHTTPSRequired and a nil RP() 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. A plain c is access.ErrHTTPSRequired, and an unknown, spent, expired or other ceremony 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: access.ErrHTTPSRequired for a plain c under access.PostureSecure, 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 ¶
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 signs in. A plain c is access.ErrHTTPSRequired; a zero, absent, expired or non-recovery token, or a gone or disabled subject, access.ErrTokenInvalid before c's IP attempt limit. A key-issued token's issuer is re-checked as at issue: a refusal commits only the token's deletion (access.ErrTokenInvalid), a pass records it as Session.IssuedByKey with a recovery_started attribution and in EventRecoveryConsumed.
func (*Service) State ¶
State reports whether setup is needed, which sign-in methods c's transport admits, and what HTTPS would add (docs/plain-http.md owns the table). It checks no transport, so it answers a plain c under both postures, and 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 plain p is access.ErrHTTPSRequired, a nil RP() 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 plain c or p is access.ErrHTTPSRequired, a ceremony another user began 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, with the device cookie in Issued. A plain c or p is access.ErrHTTPSRequired, any but a full session ErrSessionRequired, and 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, a session rotated or ended meanwhile ErrSessionGone.
func (*Service) Tokens ¶
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 ¶
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, and returns the user as committed. One Update asks OpSetRole, then OpSetEnabled with the role applied, for each set field, so a refusal answers before existence (ErrNotFound after). A key sets and acts on RoleUser only (admin_target) and enables only with its current secret (key_retiring). A role change revokes the sessions; a disable, every session, key and token those keys issued, and re-enabling restores none.
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 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.
type State ¶
type State struct {
// PlainSession is the longest a session signed in by this request may
// last; set only on a plain request under access.PosturePerRequest.
PlainSession *access.SessionTimeouts
// HTTPSOrigin is Rules.HTTPSOrigin on a plain request, else empty.
HTTPSOrigin string
// HTTPSRequired is each offered feature the request's transport
// withholds, in the HTTPSFeature constants' order; empty when secure.
HTTPSRequired []HTTPSFeature
// PasswordLogin, Passkeys and OIDC are each offered and admitted over
// the request's transport.
SetupRequired, PasswordLogin, Passkeys, OIDC bool
// Secure is the request's Client.Secure.
Secure bool
}
State is what an anonymous caller may learn: whether setup is needed, which sign-in methods the request's transport admits, and what HTTPS would add.
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)
// ClearRetiredAPIKeySecrets zeroes PreviousHash and PreviousUntil, in
// one atomic step, on at most limit keys whose previous secret no
// longer verifies: PreviousHash set, and PreviousUntil not after now or
// LastUsedAt non-zero. It evaluates that predicate in its own write,
// never writes KeyHash, and returns how many keys it cleared; fewer
// than limit means none such is left (rule 23). A store may refuse a
// limit below 1 with an error.
ClearRetiredAPIKeySecrets(ctx context.Context, now time.Time, limit int) (int, error)
}
Sweeper holds the three 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 ¶
TextError is a display text an operation refuses before any write. Field is one of TextErrorFields, Reason one of TextErrorReasons, and the pair one of TextErrors: disallowed_character is invalid UTF-8, a control, bidi control or line separator character.
func TextErrors ¶
func TextErrors() []TextError
TextErrors returns every {Field, Reason} pair an operation returns as a *TextError, in a stable order: a label is refused empty, a display name never is.
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 ¶
type Tx interface {
UserStore
SessionStore
PasskeyStore
KeyStore
TokenStore
AttributionStore
FailureStore
LogStore
}
Tx is the view of the store inside one transaction. It is valid only until the Update callback returns.
type UserChange ¶
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
Source Files
¶
- actor.go
- admin.go
- allowance.go
- config.go
- doc.go
- errors.go
- events.go
- failurecap.go
- invite.go
- journal.go
- keyactor.go
- keylabel.go
- keys.go
- lastmethod.go
- locality.go
- log.go
- log_append.go
- log_read.go
- me.go
- oidc.go
- passkey_setup.go
- passkeys.go
- password_login.go
- password_set.go
- pending.go
- policy.go
- profile.go
- recovery.go
- recovery_issue.go
- reenable.go
- results.go
- rotate.go
- rotate_key.go
- rules.go
- service.go
- sessions.go
- sessions_mint.go
- setup.go
- stepup.go
- store.go
- sweep.go
- tokens.go
- transport.go
- users_create.go
- validate.go