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, RecoveryCode.Hash, TemporaryPassword.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, the user's key attributions, TOTP, recovery code and temporary password) 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 user 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), 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, DeleteAuthFailure removes the one record its ref names, and DeleteAuthFailures removes the listed methods' records of one name in both trust contexts; both skip 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 6 × len(users) records of user names (three counted methods, 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, OneTimeToken.IssuedByKey and TemporaryPassword's IssuedByKey and IssuedByUser outlive the keys and users they name, and account refuses an issuer it cannot find, so a reused ID would let a later key or user 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, TOTP, RecoveryCode, TemporaryPassword, 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. Either hash reads the one current record, so a touch or a label write shows through both. 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.
- Per-user records. A user holds at most one TOTP, one RecoveryCode and one TemporaryPassword, each keyed by its UserID, and a write or delete for one user touches no other user's. A by-user lookup reports absence through found (rule 1). SetTOTP, SetRecoveryCode and SetTemporaryPassword write the whole record over any the user holds; DeleteTOTP, DeleteRecoveryCode and DeleteTemporaryPassword remove it, returning nil when there is none. ListTOTP pages in ascending UserID strictly above afterUserID, at most limit records (a limit below 1 may be refused), so a walk that passes each page's last UserID meets every record once. DeleteUser removes all three (rule 5).
- Waiting users. UsersWaiting returns at most limit users whose WaitingApproval is set, oldest CreatedAt first and equal times in ascending ID; a limit below 1 may be refused. An UpdateUser that clears the flag takes the user off the list.
- The SSO mode. SSOMode answers the mode of the last committed SetSSOMode with set true, and SSOAlongside with set false until one commits. The set bit is stored beside the mode, never derived from it, so an SSOAlongside written reads set. Both commit and roll back with their Update (rule 5) and survive a close and a reopen (rule 20).
Index ¶
- Constants
- Variables
- func AppEntryReasons() []string
- func CodeReasons() []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 CodeError
- type Config
- type CreateVia
- type CreatedKey
- type Credentials
- type CurrentSession
- type Decision
- type Enrolled
- type EnrolmentResult
- type Event
- type EventActor
- type EventKind
- type FailureCount
- type FailureRef
- type FailureStore
- type HTTPSFeature
- type Issued
- type IssuedTemporaryPassword
- 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 LoginResult
- type MalformedError
- type Me
- type MethodLock
- type MethodState
- type Methods
- type NewKey
- type NewUser
- type Next
- type OIDCAdmission
- type OIDCOutcome
- type OIDCOutcomeKind
- type Operation
- type Passkey
- type PasskeyStore
- type PasswordSet
- type Pending
- type PendingCeremony
- type PendingLink
- type PendingTOTP
- type Policy
- type PolicyError
- type Provision
- type Provisioning
- type Readiness
- type Registered
- type Registration
- type RegistrationMode
- type RegistrationModeName
- type RegistrationPasskey
- type RegistrationResult
- type RolePolicy
- type RotatedKey
- type Rotation
- type Rules
- type RulesError
- type SSOMode
- type SSOModeName
- type SSOModeStore
- type SecondFactorProof
- type SecondFactorStore
- type Service
- func (s *Service) APIKeys(ctx context.Context, p access.Principal) ([]access.Key, error)
- func (s *Service) AcceptInviteOIDCBegin(ctx context.Context, c Client, token access.Secret) (oidc.BeginRequest, error)
- func (s *Service) AcceptInvitePassword(ctx context.Context, c Client, in AcceptInvite) (LoginResult, error)
- func (s *Service) AdminRelinkOIDC(ctx context.Context, a Actor, userID int64, in TemporaryPasswordOptions) (IssuedTemporaryPassword, error)
- func (s *Service) AdminScope() string
- func (s *Service) AdminUnlinkOIDC(ctx context.Context, a Actor, userID int64) error
- 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) ApplySSO(ctx context.Context, a Actor, mode SSOMode) error
- func (s *Service) Authenticator() *access.Authenticator
- func (s *Service) BeginTOTP(ctx context.Context, p access.Principal) (TOTPEnrolment, error)
- func (s *Service) CheckRules(ctx context.Context, r Rules) error
- func (s *Service) CheckSSOReady(ctx context.Context, a Actor, mode SSOMode) error
- func (s *Service) CheckSecondFactorReady(ctx context.Context, c Client, p access.Principal) error
- 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) CreatePendingOIDC(ctx context.Context, c Client, pending PendingLink, username string) (SignedIn, error)
- 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) FinishTOTP(ctx context.Context, c Client, p access.Principal, in TOTPFinish) (Enrolled, 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) LinkPendingOIDCByAdmin(ctx context.Context, c Client, pl PendingLink, username string, ...) (SignedIn, 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) MigrateSSO(ctx context.Context, mode SSOMode) error
- func (s *Service) OIDCComplete(ctx context.Context, c Client, flow oidc.Flow, claims oidc.Claims) (OIDCOutcome, error)
- func (s *Service) Owner(ctx context.Context) (*access.User, 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, c Client, 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) ([]Passkey, error)
- func (s *Service) PasswordLogin(ctx context.Context, c Client, in Credentials) (LoginResult, error)
- func (s *Service) PendingPasskeyBegin(ctx context.Context, c Client, ticket access.Secret, origin webauthn.Origin) (PendingCeremony, error)
- func (s *Service) PendingPasskeyFinish(ctx context.Context, c Client, ceremonyID string, body io.Reader) (EnrolmentResult, error)
- func (s *Service) PendingTOTPBegin(ctx context.Context, c Client, ticket access.Secret) (PendingTOTP, error)
- func (s *Service) PendingTOTPFinish(ctx context.Context, c Client, ticket access.Secret, code string) (EnrolmentResult, error)
- func (s *Service) ReenableMethod(ctx context.Context, p access.Principal, method access.Method) error
- func (s *Service) RegenerateRecoveryCode(ctx context.Context, c Client, p access.Principal, proof SecondFactorProof) (access.Secret, error)
- func (s *Service) RegisterPasskeyBegin(ctx context.Context, c Client, in RegistrationPasskey) (PendingCeremony, error)
- func (s *Service) RegisterPasskeyFinish(ctx context.Context, c Client, ceremonyID string, body io.Reader) (EnrolmentResult, error)
- func (s *Service) RegisterPassword(ctx context.Context, c Client, in Registration) (RegistrationResult, error)
- func (s *Service) RemovePasskey(ctx context.Context, c Client, 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) RemoveTOTP(ctx context.Context, c Client, p access.Principal, proof SecondFactorProof) 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) RequireKeyPermission(p access.Principal, scope string) error
- func (s *Service) RequireKeyScope(p access.Principal, scope string) error
- func (s *Service) RequireRecentAuth(p access.Principal) error
- func (s *Service) ResealTOTP(ctx context.Context) (resealed, unopenable int, err error)
- func (s *Service) ResetSecondFactor(ctx context.Context, a Actor, userID int64) 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) SSO(ctx context.Context) (mode SSOMode, set bool, err error)
- func (s *Service) SSOReadiness(ctx context.Context, a Actor, mode SSOMode) (Readiness, error)
- func (s *Service) SecondFactorPasskeyBegin(ctx context.Context, c Client, ticket access.Secret, origin webauthn.Origin) (PendingCeremony, error)
- func (s *Service) SecondFactorPasskeyFinish(ctx context.Context, c Client, ceremonyID string, body io.Reader) (LoginResult, 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) SetCredentialPasskeyBegin(ctx context.Context, c Client, ticket access.Secret, origin webauthn.Origin) (PendingCeremony, error)
- func (s *Service) SetCredentialPasskeyFinish(ctx context.Context, c Client, ceremonyID string, body io.Reader) (SignedIn, error)
- func (s *Service) SetCredentialPassword(ctx context.Context, c Client, ticket, password access.Secret) (LoginResult, error)
- func (s *Service) SetOwner(ctx context.Context, a Actor, userID int64, owner bool) (*access.User, error)
- func (s *Service) SetPassword(ctx context.Context, c Client, p access.Principal, ...) (PasswordSet, error)
- func (s *Service) SetTemporaryPassword(ctx context.Context, a Actor, userID int64, in TemporaryPasswordOptions) (IssuedTemporaryPassword, 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) (LoginResult, error)
- func (s *Service) Shutdown(ctx context.Context) error
- func (s *Service) SignInWithCode(ctx context.Context, c Client, ticket access.Secret, code string) (LoginResult, error)
- func (s *Service) SignInWithRecoveryCode(ctx context.Context, c Client, ticket access.Secret, code string) (LoginResult, error)
- func (s *Service) State(ctx context.Context, c Client) (State, error)
- func (s *Service) StepUpCode(ctx context.Context, c Client, p access.Principal, code string) (Issued, 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) TemporaryPasswordHTTPSOnly(issued IssuedTemporaryPassword) bool
- 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 TOTPConfig
- type TOTPEnrolment
- type TOTPFinish
- type TOTPState
- type TemporaryPasswordOptions
- type TemporaryPasswordStore
- type TextError
- type TokenStore
- type Tx
- type UserChange
- type UserFilter
- type UserStore
- type UsernameError
- type Waiting
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" // an issue or reset of a principal's own factors ReasonOtherUser = "other_user" ReasonTargetNotEligible = "target_not_eligible" ReasonUnknownOperation = "unknown_operation" ReasonNotEnabledUser = "not_enabled_user" ReasonNotAdmin = "not_admin" ReasonSelfDelete = "self_delete" ReasonSingleOwner = "single_owner" ReasonNotOwner = "not_owner" ReasonUnknownVia = "unknown_via" ReasonViaWithActor = "via_with_actor" // The owner protections account applies after the Policy, for every // Policy. ReasonOwnerTarget = "owner_target" // a principal that is no owner acting on an owner ReasonOwnerRole = "owner_role" // a role change of an owner ReasonLastOwner = "last_owner" // a change that leaves no enabled owner ReasonOwnerNeedsLocalMethod = "owner_needs_local_method" // an owner must be an enabled admin with a usable password or passkey // ReasonRegistrationEnabled is SSOOnly refused while Rules.Registration // is on: under it, people join only through the identity provider. ReasonRegistrationEnabled = "registration_enabled" )
The PolicyError Reasons, in PolicyReasons order. RolePolicy and SingleOwnerPolicy give the role and owner reasons; 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 ( ReasonCodeInvalid = "code_invalid" ReasonCodeReused = "code_reused" // a code whose step was already accepted ReasonMethodLocked = "method_locked" // ReasonCurrentCodeInvalid is a replacement's current code, from the // old secret, that does not match. ReasonCurrentCodeInvalid = "current_code_invalid" )
The CodeError Reasons, in CodeReasons order.
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" // LogDetailOwnerNeedsLocalMethod is an owner New marked that holds no // password or passkey it signs in with. LogDetailOwnerNeedsLocalMethod = ReasonOwnerNeedsLocalMethod )
The library's LogEntry.Detail values: two on a session_revoked entry, one on an owner_set 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, the most entries one PruneLog call of New's log drain or // the sweep removes, and the most waiting accounts one UsersWaiting call // of the sweep reads; 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 // DefaultMaxWaitingRegistrations is Rules.MaxWaitingRegistrations's // default. DefaultMaxWaitingRegistrations = 50 // WaitingRegistrationLifetime is how long an account waits for // approval before the sweep deletes it, freeing its name. WaitingRegistrationLifetime = 30 * 24 * time.Hour )
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 session reached by any other // principal, and RequireKeyScope or RequireKeyPermission refusing an // empty scope. ErrSessionRequired = errors.New("account: a signed-in session is required") // ErrScopeRequired is RequireKeyScope or RequireKeyPermission under a // set scope, for a principal that is no 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 // user 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 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") 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 // ErrCodeInvalid is matched by every *CodeError: a TOTP or recovery // code that does not match, or a match refused as reused or locked. ErrCodeInvalid = errors.New("account: the code is not valid") // ErrCodeMalformed is matched by every *MalformedError. ErrCodeMalformed = errors.New("account: the code is malformed") // ErrSecondFactorProofRequired is a change that needs a current second // factor, sent with no proof; nothing is counted for it. ErrSecondFactorProofRequired = errors.New("account: a current second factor is required") // ErrLastSecondFactor is a removal Rules.RequireSecondFactor refuses, // since it leaves a user who holds a second factor none they can use; // it matches ErrLastMethod. ErrLastSecondFactor = fmt.Errorf("account: the last second factor cannot be removed: %w", ErrLastMethod) // ErrSecondFactorHeld is a password step-up of a user who holds a // second factor, who steps up with it; it matches // ErrSecondFactorRequired. ErrSecondFactorHeld = fmt.Errorf("account: a user holding a second factor steps up with it: %w", ErrSecondFactorRequired) // ErrPasswordRequired is a TOTP enrolment of a user who holds no // password, the only sign-in a code protects. ErrPasswordRequired = errors.New("account: an authenticator app needs a password to protect") // ErrSecondFactorRequired is a password sign-in or a setting that needs // a second factor the user cannot bind or does not hold. ErrSecondFactorRequired = errors.New("account: a second factor is required") // ErrNoUsableMethod is a sign-in whose next step the app's rules allow // no method for, so the account can take no step this app allows. ErrNoUsableMethod = errors.New("account: this app allows no method this sign-in's next step needs") // ErrEnrolNeedsKnownDevice is a password sign-in that would bind the // account's first second factor from a device no secure sign-in of it // has used; it matches ErrSecondFactorRequired. ErrEnrolNeedsKnownDevice = fmt.Errorf("account: a first second factor is bound only from a known device: %w", ErrSecondFactorRequired) // ErrEnableWithoutSecondFactor is CheckSecondFactorReady's refusal of an // admin who holds no usable second factor; it matches // ErrSecondFactorRequired. ErrEnableWithoutSecondFactor = fmt.Errorf("account: set up your own second factor before requiring one: %w", ErrSecondFactorRequired) // counts as no wrong code. ErrSecondFactorUnavailable = errors.New("account: the second factor cannot be opened") // ErrTOTPDisabled is a TOTP operation under Rules.DisableTOTP. ErrTOTPDisabled = errors.New("account: authenticator apps are turned off") // ErrRegistrationClosed is a registration while Rules.Registration is // off. ErrRegistrationClosed = errors.New("account: registration is closed") // ErrRegistrationFull is a registration while the waiting accounts are // at Rules.MaxWaitingRegistrations. ErrRegistrationFull = errors.New("account: registration is full") // ErrNoOwner is New refusing a store that holds users and no enabled // admin, and Service.Owner on a single-user store whose owner flag is // not on its one enabled admin alone. Its text names the repair. ErrNoOwner = errors.New("account: no owner") // ErrNotSingleUser is Service.Owner under a multi-user Policy. ErrNotSingleUser = errors.New("account: the policy admits more than one account") // ErrUnknownSSOMode is a mode outside the SSOMode constants. ErrUnknownSSOMode = errors.New("account: unknown SSO mode") // ErrSSOOnly is a local-method operation the stored SSO mode forbids // for the user. ErrSSOOnly = errors.New("account: the identity provider is this account's only sign-in") // ErrTemporaryPasswordExposed is a password sign-in that matched a // temporary password over plain HTTP where its path cannot finish; the // secret crossed in clear, so the sign-in deleted it. It matches // access.ErrHTTPSRequired. ErrTemporaryPasswordExposed = failreason.Wrap(fmt.Errorf("account: a temporary password sent over plain HTTP is cancelled: %w", access.ErrHTTPSRequired), failreason.TemporaryPasswordExposed) // ErrSSOLinked is a temporary password for a linked user whose local // methods the stored mode keeps dormant, which could neither sign in nor // link; it matches ErrSSOOnly. ErrSSOLinked = fmt.Errorf("account: a linked account signs in only by single sign-on: %w", ErrSSOOnly) )
Errors of the account operations. Errors of access, ratelimit, webauthn and oidc pass through unchanged and match with errors.Is.
var ( // ErrNotAdmitted is an OIDC identity whose token fails // Rules.OIDCAdmission, at any intent. ErrNotAdmitted = errors.New("account: identity not admitted") // ErrProvisioningDisabled is a pending account creation that // Rules.Provisioning no longer allows. ErrProvisioningDisabled = errors.New("account: provisioning is disabled") )
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 CodeReasons ¶
func CodeReasons() []string
CodeReasons returns every CodeError 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 CodeError ¶
type CodeError struct {
Reason string
}
CodeError is a code an operation refused, with why. Reason is one of CodeReasons. It matches ErrCodeInvalid.
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)
// TOTP wires authenticator-app codes; the zero value wires none, and
// New refuses a half-set value.
TOTP TOTPConfig
// 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 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 and invite 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 each of the two lists of pending WebAuthn
// ceremonies, anonymous begins and a user's or setup's own; zero means
// 10000. Pending sign-ins, enrolments and drafts have caps of their own.
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 ViaRegistration CreateVia = "registration" // an anonymous sign-up under open registration )
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
Owner bool // OpSetOwner: 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 Enrolled ¶
type Enrolled struct {
// RecoveryCode is the recovery code this binding issued, shown only
// here; zero when it issued none.
RecoveryCode access.Secret
}
Enrolled is the answer of a change that bound a second factor.
type EnrolmentResult ¶
EnrolmentResult is a pending enrolment finish's answer: Waiting when it created an account that waits for approval, else SignedIn.
type Event ¶
type Event struct {
At time.Time
Kind EventKind
Method access.Method // sign-in, step-up, lock, re-enable and a refused second step
// Role is the new role of an EventRoleChanged or EventRoleSynced, the
// kept one of an EventRoleSyncSkipped, 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, the issuing key of an
// invite-accepting EventUserCreated whose token a key issued, and of a
// temporary password an EventTemporaryPasswordWithdrawn withdrew or an
// admin link's EventOIDCLinked spent.
KeyID int64
PasskeyID int64 // passkey events
// IssuerUserID is the user whose session issued the temporary password
// of an EventTemporaryPasswordWithdrawn or an admin link's
// EventOIDCLinked; it and KeyID are zero for one issued out of band.
IssuerUserID int64
// SSOMode and PreviousSSOMode are an EventSSOModeChanged's new and old
// stored mode.
SSOMode, PreviousSSOMode SSOMode
// 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
// Plain is an EventTemporaryPasswordUsed whose secret crossed plain
// HTTP, so a reader of that network may hold it.
Plain bool
}
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 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" // ReenableMethod, or a correct secret, cleared a reported lock, after its commit EventOwnerSet EventKind = "owner_set" EventOwnerRemoved EventKind = "owner_removed" EventSSOModeChanged EventKind = "sso_mode_changed" // EventTemporaryPasswordWithdrawn is a dormant temporary password a // change that brings the user's methods back deleted. EventTemporaryPasswordWithdrawn EventKind = "temporary_password_withdrawn" // EventTemporaryPasswordSet is SetTemporaryPassword's issue. EventTemporaryPasswordSet EventKind = "temporary_password_set" // EventTemporaryPasswordUsed is a temporary password a password sign-in // matched and deleted, spent or, over plain HTTP where it cannot finish, // cancelled; Event.Plain names the transport it crossed. EventTemporaryPasswordUsed EventKind = "temporary_password_used" // EventOIDCNotAdmitted is a token Rules.OIDCAdmission refused; its // UserID is zero at an invite acceptance and for an identity no account // is linked to. EventOIDCNotAdmitted EventKind = "oidc_not_admitted" // EventRoleSynced is a role an OIDC sign-in's SyncRole changed, naming // the user's sessions the change ended, and EventRoleSyncSkipped one it // left because the claim was unreadable. EventRoleSynced EventKind = "role_synced" EventRoleSyncSkipped EventKind = "role_sync_skipped" EventTOTPAdded EventKind = "totp_added" EventTOTPReplaced EventKind = "totp_replaced" EventTOTPRemoved EventKind = "totp_removed" // EventRecoveryCodeIssued is a recovery code a binding issued, // EventRecoveryCodeUsed one a pending enrolment's finish spent, and // EventRecoveryCodeReplaced one RegenerateRecoveryCode drew in place of // the user's last. EventRecoveryCodeIssued EventKind = "recovery_code_issued" EventRecoveryCodeUsed EventKind = "recovery_code_used" EventRecoveryCodeReplaced EventKind = "recovery_code_replaced" // EventSecondFactorFailed is a pending sign-in's first refused second // step; later refusals on the same ticket add nothing, since the // failure record counts them. A refused code's entry carries the // CodeError Reason as its Detail. EventSecondFactorFailed EventKind = "second_factor_failed" // EventSecondFactorReset is ResetSecondFactor's deletion of a user's // TOTP record and recovery code. EventSecondFactorReset EventKind = "second_factor_reset" // EventUserApproved is the enable of an account waiting for approval, // in place of EventUserEnabled. EventUserApproved EventKind = "user_approved" // EventRegistrationExpired is the sweep's deletion of an account that // waited for approval longer than WaitingRegistrationLifetime. EventRegistrationExpired EventKind = "registration_expired" )
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; the record stays locked until account deletes it (ReenableMethod, or an operation that resets the method)
// 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)
// DeleteAuthFailure removes ref's one record; an absent one is skipped.
DeleteAuthFailure(ctx context.Context, ref FailureRef) 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 IssuedTemporaryPassword ¶
type IssuedTemporaryPassword struct {
ExpiresAt time.Time
// Password is the secret in its displayed form, XXXX-XXXX-XXXX-XXXX.
Password access.Secret
// HTTPSOrigin is Rules.HTTPSOrigin as the issue read it.
HTTPSOrigin string
// Dormant is the record's Dormant: the stored mode keeps the user's
// local methods dormant, so the issue kept them and the secret's one
// use is the admin link.
Dormant bool
// PasswordKept is a Dormant issue that kept a password the user holds.
PasswordKept bool
// contains filtered or unexported fields
}
IssuedTemporaryPassword is what an issue decided, to show its holder's admin once.
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 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, as its current record; 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 {
Username string // the key's user'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 {
// TemporaryPasswordExpiresAt is the expiry of the user's live temporary
// password; zero when they hold none or it has expired.
TemporaryPasswordExpiresAt time.Time
// 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
// LocalMethodsDormant is the stored SSO mode, read once for the list,
// keeping the user's password and passkeys dormant.
LocalMethodsDormant bool
// RoleFromProvider is whether Rules.Provisioning.SyncRole, read once for
// the list, sets the user's role at each OIDC sign-in.
RoleFromProvider bool
// TOTP is whether the user holds a TOTP record.
TOTP bool
}
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 one of the library's LogDetail
// values; 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 LoginResult ¶
LoginResult is a password sign-in's answer: Pending when the sign-in needs another step, else SignedIn.
type MalformedError ¶
type MalformedError struct {
Field string
}
MalformedError is a code that cannot be one: not six ASCII digits once spaces are removed. Field names the input that held it. Nothing is counted for it. It matches ErrCodeMalformed.
func (*MalformedError) Error ¶
func (e *MalformedError) Error() string
func (*MalformedError) Is ¶
func (*MalformedError) Is(target error) bool
Is reports ErrCodeMalformed.
type Me ¶
type Me struct {
User *access.User
Current CurrentSession
Methods Methods
CanLinkOIDC bool // OIDCAvailable and not OIDCLinked
// SingleUser is the Policy's declaration as New kept it.
SingleUser bool
// SSOOnly is the stored SSO mode keeping the user's local methods
// dormant: adding a password or passkey answers ErrSSOOnly, as does a
// step-up by either.
SSOOnly 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 {
TOTP TOTPState
Locks []MethodLock // locked methods only
PasskeyCount int
HasPassword bool
OIDCLinked bool
OIDCAvailable bool
PasskeysAvailable bool
PasswordLogin bool // !Rules.DisablePasswordLogin
RecoveryCode bool // a recovery code is stored
// SecondFactorHeld is secondFactorHeld: adding or removing a passkey
// needs a current second factor while it is true.
SecondFactorHeld bool
// PasswordStepUp is whether step-up may offer the password: the user
// holds one, no second factor is held, and neither DisablePasswordLogin
// nor the stored SSO mode refuses it.
PasswordStepUp bool
}
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
// user'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 Next ¶
type Next string
Next is the step a pending sign-in needs before it completes, by its wire name.
const ( // NextSecondFactor is a second factor the user holds. NextSecondFactor Next = "second_factor" // NextSetCredential is a password or passkey of the user's own choosing. NextSetCredential Next = "set_credential" //nolint:gosec // G101: a step's wire name, not a credential // NextEnrol is a first second factor to bind, which // Rules.RequireSecondFactor demands. NextEnrol Next = "enrol" )
type OIDCAdmission ¶
type OIDCAdmission struct {
// Claim names the claim to read, e.g. "groups": a string or an array
// of strings. Any other shape, absent included, is not admitted.
Claim string
// AllowedValues admit a token whose Claim holds one of them, compared
// exactly.
AllowedValues []string
}
OIDCAdmission gates every OIDC sign-in, link, invite acceptance and step-up on a claim the provider asserts. The zero value admits every identity.
func (OIDCAdmission) Validate ¶
func (a OIDCAdmission) Validate() error
Validate refuses a Claim without AllowedValues and AllowedValues without a Claim.
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" OpListUsers Operation = "list_users" // the admin user list, the live invite tokens and the security log OpManageAllKeys Operation = "manage_all_keys" // list and revoke every user's keys 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 OpSetOwner Operation = "set_owner" // Target's owner flag, to Decision.Owner // OpSetTemporaryPassword issues Target a temporary password. OpSetTemporaryPassword Operation = "set_temporary_password" OpResetSecondFactor Operation = "reset_second_factor" // delete Target's TOTP and recovery code OpUnlinkOIDC Operation = "unlink_oidc" // remove Target's identity-provider link for them // OpApplySSO is a change of the stored SSO mode. account decides it // itself, owners and out-of-band actors only, and asks no Policy; it // names the operation of its PolicyErrors. OpApplySSO Operation = "apply_sso" )
The operations a Policy decides.
type Passkey ¶
type Passkey struct {
Credential access.PasskeyCredential
Removable bool
}
Passkey is one of a user's own passkeys, with whether RemovePasskey would remove it: false when the last-method or the second-factor guard would refuse.
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 PasswordSet ¶
PasswordSet is SetPassword's answer: the rotated session, and the recovery code a first password issued, shown only here; zero when it issued none.
type Pending ¶
Pending is a sign-in whose first factor verified and that needs Next. Its Ticket lasts ten minutes, held by the client in memory and sent in a body only. A restart, the user's next password sign-in, SetPassword, RemovePassword, ResetSecondFactor, SetTemporaryPassword, disabling, deleting, AdminUnlinkOIDC and AdminRelinkOIDC drop it, as do an OIDC link, ApplySSO, MigrateSSO and SetOwner when they leave the user's local methods dormant. Methods are what Next accepts on this request's transport, the only one it finishes on. Recovered marks a NextEnrol that completes a recovery.
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 {
// Provision is set when provisioning admitted the identity but its name
// was taken, so CreatePendingOIDC may create an account with this role.
Provision *Provision
// Invite is set instead, to the invite's stored hash, when an invite's
// callback found its name taken, so CreatePendingOIDC may accept it.
Invite access.Hash
UsernameHint string // preferred_username as sent, display only
Email string // only when email_verified
// SuggestedUsername is the default name for CreatePendingOIDC, set only
// when CanCreate; it may be taken too.
SuggestedUsername string
Identity access.OIDCIdentity
}
PendingLink is an OIDC identity no account is linked to yet.
func (*PendingLink) CanCreate ¶
func (p *PendingLink) CanCreate() bool
CanCreate reports whether CreatePendingOIDC may create an account for p.
type PendingTOTP ¶
type PendingTOTP struct {
URI access.Secret // the Key Uri Format's otpauth URI, for a QR code
Text access.Secret // the secret in base32, for typing in
}
PendingTOTP is a TOTP enrolment begun inside a pending sign-in. URI and Text carry the new secret, shown only in this answer; the ticket keeps it for PendingTOTPFinish.
type Policy ¶
type Policy interface {
// Authorize returns nil, or a *PolicyError.
Authorize(ctx context.Context, d Decision) error
// SingleUser reports whether the Policy admits one account only. It
// must be constant for a Policy value: New reads it once, and under a
// true answer account itself refuses every creation but setup, every
// invite and every enable before Authorize is asked.
SingleUser() bool
}
Policy decides who may change the user set and mint credentials. An OutOfBand actor reaches it for OpCreateUser, OpCreateKeyFor, OpManageAllKeys, OpRotateKey, OpSetOwner, OpSetTemporaryPassword, OpResetSecondFactor and OpUnlinkOIDC, so an app's own Policy decides each. OpRotateKey's Target is the key's user as stored. account applies the owner protections itself, after Authorize allows, whatever the Policy.
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 Provision ¶
Provision is what the callback that admitted a pending identity decided for its account.
type Provisioning ¶
type Provisioning struct {
// Role is a provisioned account's role when RoleClaim is empty or
// holds none of AdminValues; empty means access.RoleUser.
Role access.Role
// RoleClaim names a claim, a string or an array of strings, whose
// value in AdminValues makes the account an admin. It must be one the
// provider asserts, never a profile field the user can edit.
RoleClaim string
AdminValues []string
Enabled bool
// SyncRole re-applies the RoleClaim mapping at each OIDC sign-in of a
// linked non-owner, whether or not Enabled, while the claim is present
// and readable; an in-app role change holds until the next sign-in. A
// sync that changes the role ends the user's other sessions, as
// UpdateUser's role change does.
SyncRole bool
}
Provisioning creates an account at the first OIDC sign-in of an admitted identity with no linked account, in a multi-user app. The zero value is off. Rules.OIDCAdmission decides which identities it may create.
func (Provisioning) Validate ¶
func (p Provisioning) Validate() error
Validate refuses a Role other than "", RoleUser or RoleAdmin, and AdminValues or SyncRole without a RoleClaim.
type Readiness ¶
type Readiness struct {
// Refusal is the state refusal the change would answer, nil when it
// would be made: ErrOIDCUnavailable for a provider that is off now, or a
// *PolicyError with ReasonSingleOwner, ReasonRegistrationEnabled or
// ReasonOwnerNeedsLocalMethod.
Refusal error
// LockedOut counts the enabled non-owners the mode would leave with no
// sign-in: under SSOOnly, those not linked.
LockedOut int
// MethodsMadeDormant and MethodsRestored count the enabled accounts
// holding a password or passkey that the change makes dormant or brings
// back; each is zero in the direction that does not apply.
MethodsMadeDormant, MethodsRestored int
// TemporaryPasswordsWithdrawn counts the dormant temporary passwords of
// the accounts the change brings back, which it deletes.
TemporaryPasswordsWithdrawn int
}
Readiness is what a change of the stored mode to a new one would do, read by SSOReadiness from the stored state.
type Registered ¶
type Registered struct {
// RecoveryCode is the recovery code the registration issued, shown
// only here; zero when it issued none.
RecoveryCode access.Secret
Issued Issued
Passkey Passkey
}
Registered is an enrolled passkey and the rotated session.
type Registration ¶
Registration is the input of RegisterPassword.
type RegistrationMode ¶
type RegistrationMode int
RegistrationMode is who may create their own account. It is an app setting, read from Rules on every operation.
const ( // RegistrationOff lets no one sign up. RegistrationOff RegistrationMode = iota // RegistrationOpen creates an enabled regular account. RegistrationOpen // RegistrationApproval creates a regular account that waits, disabled, // until an admin enables it. RegistrationApproval )
func ParseRegistrationMode ¶
func ParseRegistrationMode(name RegistrationModeName) (RegistrationMode, bool)
ParseRegistrationMode is the mode a wire name names; false for any other name.
func (RegistrationMode) Name ¶
func (m RegistrationMode) Name() RegistrationModeName
Name is the mode's wire name; empty for a value outside the modes.
func (RegistrationMode) String ¶
func (m RegistrationMode) String() string
String is the mode's wire name, and "RegistrationMode(n)" for a value outside the modes.
type RegistrationModeName ¶
type RegistrationModeName string
RegistrationModeName is a RegistrationMode's wire name.
const ( RegistrationNameOff RegistrationModeName = "off" RegistrationNameOpen RegistrationModeName = "open" RegistrationNameApproval RegistrationModeName = "approval" )
The wire names, in RegistrationMode order.
type RegistrationPasskey ¶
RegistrationPasskey is the input of RegisterPasskeyBegin.
type RegistrationResult ¶
RegistrationResult is a password registration's answer: Pending under Rules.RequireSecondFactor, Waiting under RegistrationApproval, else SignedIn.
type RolePolicy ¶
type RolePolicy struct {
// 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 an owner manages the owners.
func (RolePolicy) Authorize ¶
func (p RolePolicy) Authorize(_ context.Context, d Decision) error
Authorize applies the two-role rules to d.
func (RolePolicy) SingleUser ¶
func (RolePolicy) SingleUser() bool
SingleUser reports false: RolePolicy admits many accounts.
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, and tickets and second factors ask it for passkeys. tx is
// what the check reads: the deciding Update, the Store for a pre-check,
// Me and Passkeys, or the caller's tx in UsableMethods; an app may
// type-assert it. MethodUsable must not block or call the Store outside
// tx. Config.RP() and Config.OIDC() are read 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 by sign-in method m, read once before the change that
// creates it, so a password sign-in that then pends wastes one call; a
// step-up never calls it. 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, m access.Method) (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
// OIDCAdmission gates every OIDC sign-in, link, invite acceptance and
// step-up, owners' included. The zero value admits every identity.
OIDCAdmission OIDCAdmission
// Provisioning creates an account at an admitted identity's first
// OIDC sign-in, and maps its role. The zero value is off; a
// single-user Policy refuses it on.
Provisioning 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
// Registration is who may create their own account; the zero value is
// off. A single-user Policy refuses it on, and so does
// CheckRules while the stored SSO mode is SSOOnly.
Registration RegistrationMode
// MaxWaitingRegistrations bounds the accounts waiting for approval: at
// it, a registration under RegistrationApproval is ErrRegistrationFull.
// Zero means DefaultMaxWaitingRegistrations; negative is invalid.
MaxWaitingRegistrations int
// 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 step-up with
// ErrPasswordLoginDisabled; a password sign-in then verifies only a live
// temporary password, answering any other value as a wrong password. The
// zero value allows them.
DisablePasswordLogin bool
// DisableTOTP turns TOTP enrolment and the code step off; a stored
// record is kept, reads as absent, and works again once this is off.
// The zero value offers TOTP where Config.TOTP wires it.
DisableTOTP bool
// RequireSecondFactor makes every password sign-in prove a second
// factor, or bind one first; passkey and OIDC sign-ins meet it already.
// It needs Config.TOTP or Config.RP set. The zero value is off.
RequireSecondFactor bool
// RevokeKeysOnCredentialChange deletes the user's API keys and their
// tokens when SetPassword sets or changes the password. 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 SSOMode ¶
type SSOMode int
SSOMode is how single sign-on sits beside local sign-in for a non-owner. The store holds it (SSOModeStore); owners are exempt under every mode. A user whose password and passkeys the stored mode forbids is a dormant user in this package's docs. A store persists the number, so a value never changes meaning.
func ParseSSOMode ¶
func ParseSSOMode(name SSOModeName) (SSOMode, bool)
ParseSSOMode is the mode a wire name names; false for any other name.
func (SSOMode) Name ¶
func (m SSOMode) Name() SSOModeName
Name is the mode's wire name; empty for a value outside the modes.
type SSOModeName ¶
type SSOModeName string
SSOModeName is an SSOMode's wire name.
const ( SSONameAlongside SSOModeName = "alongside" SSONameForLinked SSOModeName = "for_linked" SSONameOnly SSOModeName = "only" )
The wire names, in SSOMode order.
type SSOModeStore ¶
type SSOModeStore interface {
// SSOMode answers SSOAlongside and set false until a SetSSOMode
// commits.
SSOMode(ctx context.Context) (mode SSOMode, set bool, err error)
SetSSOMode(ctx context.Context, mode SSOMode) error
}
SSOModeStore holds the one stored SSOMode and whether it was ever set (rule 26).
type SecondFactorProof ¶
type SecondFactorProof struct {
// contains filtered or unexported fields
}
SecondFactorProof is a current second factor sent with a change that needs one: a TOTP code, or an assertion from a ceremony StepUpPasskeyBegin began. The zero value is no proof.
func ProofPasskey ¶
func ProofPasskey(ceremony string, assertion []byte) SecondFactorProof
ProofPasskey is a proof by the passkey assertion that answers ceremony.
type SecondFactorStore ¶
type SecondFactorStore interface {
TOTPByUserID(ctx context.Context, userID int64) (rec access.TOTP, found bool, err error)
// SetTOTP writes rec over any record rec.UserID holds.
SetTOTP(ctx context.Context, rec access.TOTP) error
DeleteTOTP(ctx context.Context, userID int64) error // idempotent
// ListTOTP returns at most limit records whose UserID is above
// afterUserID, in ascending UserID.
ListTOTP(ctx context.Context, afterUserID int64, limit int) ([]access.TOTP, error)
RecoveryCodeByUserID(ctx context.Context, userID int64) (rec access.RecoveryCode, found bool, err error)
// SetRecoveryCode writes rec over any code rec.UserID holds.
SetRecoveryCode(ctx context.Context, rec access.RecoveryCode) error
DeleteRecoveryCode(ctx context.Context, userID int64) error // idempotent
}
SecondFactorStore holds each user's TOTP record and recovery code, at most one of each, keyed by UserID (rule 24).
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 half-set TOTP, a set key scope that is not one RFC 6750 scope-token or equals another, a negative CleanupInterval, MaxPending or Log* field, and a Rules() value checkRules refuses. 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, for a principal admitOwnKeys admits.
func (*Service) AcceptInviteOIDCBegin ¶
func (s *Service) AcceptInviteOIDCBegin(ctx context.Context, c Client, token access.Secret) (oidc.BeginRequest, error)
AcceptInviteOIDCBegin starts an invite's acceptance by OIDC after AdmitOIDC, writing nothing: the IntentInvite request for Provider.Begin, sealing token's stored hash. An absent, unknown, expired, used or other-purpose token is access.ErrTokenInvalid before the Policy (OpCreateUser, ViaInvite, its Role); plain: access.ErrHTTPSRequired; nil OIDC(): ErrOIDCUnavailable. Its callback asks both again, then creates the account linked, with the invite's role; a taken name commits nothing and gives OutcomeNotLinked holding the invite.
func (*Service) AcceptInvitePassword ¶
func (s *Service) AcceptInvitePassword(ctx context.Context, c Client, in AcceptInvite) (LoginResult, error)
AcceptInvitePassword creates the invited account with a password and signs it in, or under Rules.RequireSecondFactor answers a Pending NextEnrol whose finish consumes the invite; a plain c is access.ErrHTTPSRequired. The username, password and Policy (ViaInvite) checks and the IP limiter run before the hash; a refusal, a taken name or a backend error leaves the invite usable. One Update consumes the invite and creates the user and session; a key-issued invite's refused issuer deletes it and answers access.ErrTokenInvalid, an accepted one appends an invite_accepted record.
func (*Service) AdminRelinkOIDC ¶
func (s *Service) AdminRelinkOIDC(ctx context.Context, a Actor, userID int64, in TemporaryPasswordOptions) (IssuedTemporaryPassword, error)
AdminRelinkOIDC is AdminUnlinkOIDC then SetTemporaryPassword on userID in one Update, under both their Policies and checks, so a refusal of either writes nothing; an unlinked user is ErrNotFound. The issue sees the unlinked row: under SSOOnly it keeps the dormant methods beside a record for the admin link, and under the other modes it replaces them.
func (*Service) AdminScope ¶
AdminScope returns Config.AdminScope.
func (*Service) AdminUnlinkOIDC ¶
AdminUnlinkOIDC removes userID's OIDC link for an admin principal, a ManageUsersScope key presenting its current secret (key_retiring) or an out-of-band actor, under Policy (OpUnlinkOIDC) and the owner protections, in one Update that also ends every session of the user. A key unlinks RoleUser targets only (admin_target). A refusal answers before existence; a missing or unlinked user is ErrNotFound. No last-method guard applies: a link to a lost or reassigned provider account goes even when nothing else remains.
func (*Service) AdmitOIDC ¶
AdmitOIDC is an anonymous OIDC request's one provider read, for the sign-in and invite starts, the callback and the pending routes: 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 user's username, for an out-of-band actor or a principal RequireKeyScope admits under AdminScope; 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 Username is the name the key's own snapshot holds; a key whose user that snapshot lacks lists an empty Username.
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) ApplySSO ¶
ApplySSO stores mode as the SSO mode for a, in one Update after reading Config.OIDC outside it: CheckSSOReady's refusals on what the Update read, then the mode, the end of every non-owner session the mode forbids, the withdrawal of each dormant temporary password the mode brings back to use, and an EventSSOModeChanged; once it commits, the dormant users' pending sign-ins are dropped. A refusal writes nothing, so the old mode stays in force across restarts; the mode it already holds, set, writes nothing.
func (*Service) Authenticator ¶
func (s *Service) Authenticator() *access.Authenticator
Authenticator returns Config.Authenticator.
func (*Service) BeginTOTP ¶
BeginTOTP starts enrolling an authenticator app for p's own user, for a full session within RecentAuth on a secure request. A TOTP that is not usable is ErrTOTPDisabled, a dormant user ErrSSOOnly and a user holding no password ErrPasswordRequired, each before a secret is drawn. The ticket replaces the user's earlier one; while the enrolment list is full a newcomer is a *ratelimit.RefusedError.
func (*Service) CheckRules ¶
CheckRules reports whether r would pass every operation's Rules check, and refuses a registration mode while the stored SSO mode is SSOOnly, where registration is refused at use. An app calls it before it publishes a settings write or a reload.
func (*Service) CheckSSOReady ¶
CheckSSOReady is ApplySSO's every refusal, read now and writing nothing: ApplySSO's admission, its owner rule, then the state refusal for the acting owner.
func (*Service) CheckSecondFactorReady ¶
CheckSecondFactorReady is the check an app runs before it saves Rules.RequireSecondFactor on: it answers nil only for a full session p on a secure c whose user holds a usable TOTP or a usable passkey by the current Rules, and ErrEnableWithoutSecondFactor for any other p, a dormant factor counting for nothing. It writes nothing.
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 user (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) CreatePendingOIDC ¶
func (s *Service) CreatePendingOIDC(ctx context.Context, c Client, pending PendingLink, username string) (SignedIn, error)
CreatePendingOIDC creates an account named username for pending's identity and signs it in (plain: access.ErrHTTPSRequired; the zero PendingLink, a pending state that did not open: ErrNotFound). A pending Invite needs the invite (else access.ErrTokenInvalid) and the Policy (ViaInvite); otherwise Provision, Rules.Provisioning and a stored user (else ErrProvisioningDisabled) and the Policy (ViaProvisioning). One Update checks the identity unlinked (ErrOIDCIdentityTaken) and the name free (ErrUsernameTaken, which leaves pending usable for another name).
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) FinishTOTP ¶
func (s *Service) FinishTOTP(ctx context.Context, c Client, p access.Principal, in TOTPFinish) (Enrolled, error)
FinishTOTP stores the secret in.Ticket's enrolment holds once in.Code matches it, with its step spent, and answers the recovery code the binding issued (issueRecoveryIn). The ticket must be p's session's own and no older than a stored record (else access.ErrTokenInvalid). Replacing a record takes in.CurrentCode of the old secret (none: ErrSecondFactorProofRequired), counted as a proof; its refusals carry current_code_invalid, and the new code's code_invalid. Its refusals are BeginTOTP's, plus a plain c, all re-checked in the one Update.
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. A link that leaves the user's local methods dormant under the stored SSO mode moves p's session onto MethodOIDC, its AuthTime kept, and ends the user's other local sessions and pending sign-ins.
func (*Service) LinkPendingOIDCByAdmin ¶
func (s *Service) LinkPendingOIDCByAdmin(ctx context.Context, c Client, pl PendingLink, username string, secret access.Secret) (SignedIn, error)
LinkPendingOIDCByAdmin links pl's identity, under SSOOnly, to the account username names by the temporary password an admin issued it, and signs it in by OIDC. A plain c is access.ErrHTTPSRequired and the zero PendingLink ErrNotFound, before any hash. A name, secret, account, issuer or mode that cannot link is one ErrInvalidCredentials after one hash, counted on c's IP and pl's identity, never on the account; a verified secret meets ErrAlreadyLinked and ErrOIDCIdentityTaken. The name's lock is held from before the hash through the success Update.
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 the SSO mode keeps them dormant, 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) MigrateSSO ¶
MigrateSSO is ApplySSO by an out-of-band actor that writes nothing, and returns nil, once any write has set the mode, read inside its Update, so an app's old constant never overrides an owner's choice. A refusal leaves the mode unset, so the next call retries.
func (*Service) OIDCComplete ¶
func (s *Service) OIDCComplete(ctx context.Context, c Client, flow oidc.Flow, claims oidc.Claims) (OIDCOutcome, error)
OIDCComplete completes the callback Finish returned after AdmitOIDC, charging no limiter (plain: access.ErrHTTPSRequired; nil OIDC(): ErrOIDCUnavailable), the outcome carrying flow.Redirect. A sign-in signs in the linked user or a provisioned one, else gives one same OutcomeNotLinked (disabled, or unlinked in a single-user app: ErrInvalidCredentials). A link within RecentAuth or a step-up needs flow's live full session (else ErrSessionGone); an invite answers as AcceptInviteOIDCBegin says. A token Rules.OIDCAdmission refuses is then ErrNotAdmitted, journalled alone.
func (*Service) Owner ¶
Owner returns the owner of a single-user app: the one enabled admin when it alone carries access.User.Owner. An empty store is ErrNotFound and a nil user, since setup has not run. A store changed under the running Service answers no user: one that no longer fits answers the error New would refuse it with, and one whose flag is not on its one enabled admin alone an error matching ErrNoOwner whose repair is a restart. Under a multi-user Policy it is ErrNotSingleUser whatever the store holds.
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, an unknown, spent, expired or other ceremony ErrCeremonyInvalid, a credential no user holds webauthn.ErrUnknownCredential, and a disabled or dormant user 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, c Client, p access.Principal, origin webauthn.Origin, proof SecondFactorProof) (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 dormant user ErrSSOOnly. While the user holds a second factor it takes proof, which verifyProof answers and spends last: a full list's *ratelimit.RefusedError and the origin's *webauthn.OriginError answer before it, spending no code or step-up ceremony, and a passkey proof's ceremony is used once, verified or not. The ceremony replaces the user's earlier one.
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. The same Update runs the recovery code's issue rule (issueRecoveryIn).
func (*Service) Passkeys ¶
Passkeys returns p's own passkeys as stored, each with whether RemovePasskey would remove it, for a full session. It works with a nil RP(), so stale passkeys stay listable.
func (*Service) PasswordLogin ¶
func (s *Service) PasswordLogin(ctx context.Context, c Client, in Credentials) (LoginResult, error)
PasswordLogin is a password sign-in's step 1. It refuses before any store call a plain c under PostureSecure, a bad name, a *ratelimit.RefusedError and access.ErrHashBusy (ctx ending a wait for the name's lock included). It compares one hash, counted, locking at FailureCap: the user's live temporary password, else PasswordHash unless Rules.DisablePasswordLogin; every other arm is one ErrInvalidCredentials after the same work. A temporary password answers pendTemporary's ticket or refusal, a password a session or pendAt's ticket; each ticket replaces the user's earlier one.
func (*Service) PendingPasskeyBegin ¶
func (s *Service) PendingPasskeyBegin(ctx context.Context, c Client, ticket access.Secret, origin webauthn.Origin) (PendingCeremony, error)
PendingPasskeyBegin starts registering a passkey for the NextEnrol ticket names, at origin. Its refusals: enrolTicket's; a nil RP() ErrPasskeysUnavailable; c's IP request limit; a user the ticket no longer signs in, access.ErrTokenInvalid; the relying party's *webauthn.OriginError.
func (*Service) PendingPasskeyFinish ¶
func (s *Service) PendingPasskeyFinish(ctx context.Context, c Client, ceremonyID string, body io.Reader) (EnrolmentResult, error)
PendingPasskeyFinish completes the pending sign-in ceremonyID's ticket names by registering the passkey in body, as a session of MethodPassword with the recovery code it issued (issueRecoveryIn), or as PendingTOTPFinish's Waiting account. An unknown, spent or expired ceremony is ErrCeremonyInvalid; then enrolTicket's refusals, the limiter's, the registration's, the hasher's, ErrDuplicateCredential and enrolAccountIn's, of which those enrolAnswered lists end the ticket. A Recovered ticket's finish spends the recovery as PendingTOTPFinish does.
func (*Service) PendingTOTPBegin ¶
func (s *Service) PendingTOTPBegin(ctx context.Context, c Client, ticket access.Secret) (PendingTOTP, error)
PendingTOTPBegin draws a TOTP secret for the NextEnrol ticket names and keeps it on the ticket, replacing one an earlier begin drew. Its refusals: totpEnrolTicket's, c's IP request limit, and a user the ticket no longer signs in, access.ErrTokenInvalid.
func (*Service) PendingTOTPFinish ¶
func (s *Service) PendingTOTPFinish(ctx context.Context, c Client, ticket access.Secret, code string) (EnrolmentResult, error)
PendingTOTPFinish binds the secret PendingTOTPBegin drew once code matches it, its step spent, completing ticket's sign-in as a MethodPassword session, or a registration draft under RegistrationApproval as Waiting, with issueRecoveryIn's code. A Recovered ticket's finish spends the recovery code and deletes the lost TOTP. Its refusals: totpEnrolTicket's; no secret drawn, access.ErrTokenInvalid; c's IP request limit; a malformed or wrong code, counted nowhere; then the step limiter's, the hasher's and enrolAccountIn's, of which those enrolAnswered lists end the ticket.
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) RegenerateRecoveryCode ¶
func (s *Service) RegenerateRecoveryCode(ctx context.Context, c Client, p access.Principal, proof SecondFactorProof) (access.Secret, error)
RegenerateRecoveryCode replaces p's own user's recovery code with a new one, returned to show once, for a full session within RecentAuth on a secure request, with a current second factor as proof (verifyProof's answers). A dormant user is ErrSSOOnly and a user holding no recovery code ErrNotFound, both before any count.
func (*Service) RegisterPasskeyBegin ¶
func (s *Service) RegisterPasskeyBegin(ctx context.Context, c Client, in RegistrationPasskey) (PendingCeremony, error)
RegisterPasskeyBegin starts registering a regular account with a passkey under Rules.Registration: after the transport refusal and c's IP request limit, a nil RP() is ErrPasskeysUnavailable, then RegisterPassword's refusals before its IP attempt but the password rule. A passkey meets Rules.RequireSecondFactor, so no draft is kept.
func (*Service) RegisterPasskeyFinish ¶
func (s *Service) RegisterPasskeyFinish(ctx context.Context, c Client, ceremonyID string, body io.Reader) (EnrolmentResult, error)
RegisterPasskeyFinish verifies the attestation of the registration ceremonyID began, then in one Update re-checks the mode, the Policy, the stored SSO mode and the cap (admitRegistrantIn) and creates the account with its passkey: under RegistrationOpen signed in by passkey, under RegistrationApproval Waiting. A plain c is access.ErrHTTPSRequired, an unknown, spent, expired or other ceremony ErrCeremonyInvalid, and a taken name ErrUsernameTaken.
func (*Service) RegisterPassword ¶
func (s *Service) RegisterPassword(ctx context.Context, c Client, in Registration) (RegistrationResult, error)
RegisterPassword creates a regular account with a password under Rules.Registration, signed in under RegistrationOpen and Waiting under RegistrationApproval, in one Update re-checking the mode and the cap, or as a Pending NextEnrol under Rules.RequireSecondFactor. Refusals, in order: plain access.ErrHTTPSRequired; c's IP request limit; ErrRegistrationClosed; the username and password rules; the Policy (ViaRegistration); ErrSSOOnly; ErrRegistrationFull at RegistrationApproval's MaxWaitingRegistrations; c's IP attempt; a taken name ErrUsernameTaken.
func (*Service) RemovePasskey ¶
func (s *Service) RemovePasskey(ctx context.Context, c Client, p access.Principal, id int64, proof SecondFactorProof) error
RemovePasskey removes p's own passkey id, for a full session within RecentAuth, in one Update, with or without an RP(), so stale passkeys stay removable. A passkey the user does not hold is ErrNotFound, a removal that leaves no method able to sign the user in now ErrLastMethod, and one the second-factor guard refuses ErrLastSecondFactor, each with nothing written or counted. While the user holds a second factor it takes proof (verifyProof's answers).
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 being ErrCurrentPasswordRequired; then a user holding none is ErrNotFound and the last-method guard ErrLastMethod, all before any limiter charge or count. current is counted as SetPassword's. The removal commits only while the guard passes and the verified hash is stored, resets the password's failure record of c's trust context, deletes the TOTP record and recovery code it protected, and rotates p's session into Issued with the device cookie.
func (*Service) RemoveTOTP ¶
func (s *Service) RemoveTOTP(ctx context.Context, c Client, p access.Principal, proof SecondFactorProof) error
RemoveTOTP deletes p's own TOTP record and its failure records, for a full session (none held: ErrNotFound). While TOTP is usable it takes a proof (verifyProof's answers), and under Rules.RequireSecondFactor it is ErrLastSecondFactor for a user it would leave holding none. A record TOTP no longer reads is removed with no proof, any sent ignored, but only within RecentAuth (access.RequireRecentAuth's answers).
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 is a principal admitOwnKeys admits; 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) 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) RequireKeyScope ¶
RequireKeyScope admits p to an operation that scope opens to keys beside every session: nil for a session, or for a principal the built-in API-key verifier produced (access.Principal.IsAPIKey) carrying scope when scope is non-empty. Otherwise ErrSessionRequired when scope is empty, and ErrScopeRequired. It reads the request's principal only: the operation it guards re-reads a key's authority inside its transaction.
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) ResealTOTP ¶
ResealTOTP re-seals every TOTP record under the sealer's first key, in MaxSweepBatch pages, each record in its own Update that re-reads it, so a LastStep a sign-in sets meanwhile is kept. A record the first key already opens is left as is, one no key opens is logged at ERROR and counted in unopenable, and one deleted meanwhile is skipped; none is counted twice. It returns at the first store error with the counts so far, so a nil error means the walk reached the last record. TOTP unwired is ErrTOTPDisabled.
func (*Service) ResetSecondFactor ¶
ResetSecondFactor deletes userID's TOTP record and recovery code, with their failure records, sessions and pending sign-ins, for an admin principal, a ManageUsersScope key presenting its current secret (key_retiring) on a RoleUser (admin_target) or an out-of-band actor, under OpResetSecondFactor and the owner protections; the password, passkeys and keys stay. A principal's own user is ReasonSelfRecovery. A refusal answers before existence, and a missing user or one holding neither record is ErrNotFound, writing nothing.
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 is a principal admitOwnKeys admits, and a key may revoke itself; 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 key's user as stored, and an expired key is a refused key_expired; one EventKeyRotated follows the commit.
func (*Service) SSO ¶
SSO returns the stored mode and whether any ApplySSO or MigrateSSO has set it; a store never set answers SSOAlongside and false.
func (*Service) SSOReadiness ¶
SSOReadiness reports what changing the stored mode to mode would do now, for an admin's preview, writing nothing. a is an out-of-band actor, a session, or a built-in key carrying Config.AdminScope, its authority re-read inside the read; a principal then meets Policy OpListUsers, and the request must be secure. Readiness.Refusal is the one ApplySSO would give the reader: an owner session's own change, any other reader's out-of-band one. Its errors: the admission's, ErrOIDCUnavailable while Config.OIDC is unset, ErrUnknownSSOMode, and a store error.
func (*Service) SecondFactorPasskeyBegin ¶
func (s *Service) SecondFactorPasskeyBegin(ctx context.Context, c Client, ticket access.Secret, origin webauthn.Origin) (PendingCeremony, error)
SecondFactorPasskeyBegin starts the passkey second step of the pending sign-in ticket names, at origin, limited to the user's passkeys under the relying party's ID. Its refusals: stepTicket's under a secure-only rule; no live ticket listing passkey, access.ErrTokenInvalid; a nil RP() ErrPasskeysUnavailable; c's IP request limit; a user ticketUserIn no longer passes, access.ErrTokenInvalid ending the ticket; no passkey under the relying party's ID, access.ErrTokenInvalid; its *webauthn.OriginError.
func (*Service) SecondFactorPasskeyFinish ¶
func (s *Service) SecondFactorPasskeyFinish(ctx context.Context, c Client, ceremonyID string, body io.Reader) (LoginResult, error)
SecondFactorPasskeyFinish completes the pending sign-in ceremonyID's ticket names with the passkey assertion in body, as a session of MethodPassword. An unknown, spent or expired ceremony is ErrCeremonyInvalid; then stepTicket's refusals, a ticket gone access.ErrTokenInvalid, the limiter's, and the assertion's, which keep the ticket, the first journalling EventSecondFactorFailed.
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) SetCredentialPasskeyBegin ¶
func (s *Service) SetCredentialPasskeyBegin(ctx context.Context, c Client, ticket access.Secret, origin webauthn.Origin) (PendingCeremony, error)
SetCredentialPasskeyBegin starts registering a passkey for the NextSetCredential ticket names, at origin. Its refusals: stepTicket's under a secure-only rule; no live ticket listing passkey, access.ErrTokenInvalid; a nil RP() ErrPasskeysUnavailable; c's IP request limit; a user the ticket no longer signs in, access.ErrTokenInvalid; the relying party's *webauthn.OriginError.
func (*Service) SetCredentialPasskeyFinish ¶
func (s *Service) SetCredentialPasskeyFinish(ctx context.Context, c Client, ceremonyID string, body io.Reader) (SignedIn, error)
SetCredentialPasskeyFinish completes the NextSetCredential pending sign-in ceremonyID's ticket names by registering the passkey in body, as a session of MethodPassword under either setting of Rules.RequireSecondFactor, since a passkey meets it. An unknown, spent or expired ceremony is ErrCeremonyInvalid; then SetCredentialPasskeyBegin's ticket refusals, the limiter's, the registration's, ErrDuplicateCredential, and a user the ticket no longer signs in, ending it.
func (*Service) SetCredentialPassword ¶
func (s *Service) SetCredentialPassword(ctx context.Context, c Client, ticket, password access.Secret) (LoginResult, error)
SetCredentialPassword completes ticket's NextSetCredential sign-in with a password the user chose: with Rules.RequireSecondFactor off it writes it and signs in; on, it writes nothing and puts a NextEnrol sign-in holding it in the ticket's place. Refusals, in order: stepTicket's; no live NextSetCredential ticket, access.ErrTokenInvalid; password not listed or sign-in off, ErrPasswordLoginDisabled; the limiter's; *access.PasswordError (PasswordIsTemporary, then checkPassword's), keeping the ticket; the hasher's; a user it no longer signs in, or replaceTicket's, ending it.
func (*Service) SetOwner ¶
func (s *Service) SetOwner(ctx context.Context, a Actor, userID int64, owner bool) (*access.User, error)
SetOwner sets userID's owner flag for an owner's full session within Rules().RecentAuth, or an out-of-band actor, under Policy (OpSetOwner), and returns the user as committed. An owner needs an enabled admin with a password or passkey it signs in with (owner_needs_local_method), and the last enabled owner stays (last_owner). A refusal answers before existence and writes nothing, as does the flag it already has. A new owner's dormant temporary password is withdrawn, and an ex-owner now a dormant user loses its sessions of a local method and its pending sign-ins.
func (*Service) SetPassword ¶
func (s *Service) SetPassword(ctx context.Context, c Client, p access.Principal, current, password access.Secret) (PasswordSet, error)
SetPassword sets p's own password, for a full session within RecentAuth (plain c or p under PostureSecure: access.ErrHTTPSRequired); a dormant user is ErrSSOOnly. A user holding a password gives it as current (zero: ErrCurrentPasswordRequired before any limiter call), counted like StepUpPassword's attempt; for one holding none current is ignored. One Update writes the hash, rotates p's session into Issued, revokes the other sessions and, under RevokeKeysOnCredentialChange, the user's keys and tokens; a first password's Update runs issueRecoveryIn.
func (*Service) SetTemporaryPassword ¶
func (s *Service) SetTemporaryPassword(ctx context.Context, a Actor, userID int64, in TemporaryPasswordOptions) (IssuedTemporaryPassword, error)
SetTemporaryPassword issues userID a temporary password, returned to show once, for an admin principal, a ManageUsersScope key presenting its current secret (key_retiring) on a RoleUser (admin_target) or an out-of-band actor, under OpSetTemporaryPassword and the owner protections, on a secure request; a principal's own user is ReasonSelfRecovery and a linked dormant user ErrSSOLinked. Its one Update replaces any record, clears or, for a dormant user, keeps (Dormant) the password, TOTP and recovery code, applies the options, and ends sessions and locks.
func (*Service) SetupPasskeyBegin ¶
func (s *Service) SetupPasskeyBegin(ctx context.Context, c Client, in SetupPasskey) (PendingCeremony, error)
SetupPasskeyBegin starts creating the first account, an admin and an owner 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. The ceremony replaces the earlier one for the same token (or for none); while its list is full a newcomer is a *ratelimit.RefusedError.
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) (LoginResult, error)
SetupWithPassword creates the first account, an admin and an owner, and signs it in, or under Rules.RequireSecondFactor answers a Pending NextEnrol whose finish creates it. Every refusal but the Policy's (OpCreateUser, ViaSetup) runs before the hash: access.ErrHTTPSRequired where setupRule refuses c, the user count, the token SetupTokenRequired asks for (nil: always), the username and password rules, the IP limiter. A concurrent setup that won is 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) SignInWithCode ¶
func (s *Service) SignInWithCode(ctx context.Context, c Client, ticket access.Secret, code string) (LoginResult, error)
SignInWithCode completes the pending sign-in ticket names with a TOTP code, as a session of MethodPassword. Its refusals, in order: stepTicket's; a TOTP that is not usable, ErrTOTPDisabled with the ticket kept; no live ticket listing totp, access.ErrTokenInvalid; a *ratelimit.RefusedError; then countCode's, where a user ticketUserIn no longer passes, checked before anything is counted, or a record that is gone ends the ticket as access.ErrTokenInvalid. A wrong code keeps the ticket, and the first one journals EventSecondFactorFailed.
func (*Service) SignInWithRecoveryCode ¶
func (s *Service) SignInWithRecoveryCode(ctx context.Context, c Client, ticket access.Secret, code string) (LoginResult, error)
SignInWithRecoveryCode spends nothing: a matching code clears its own failure count and puts a Recovered NextEnrol sign-in in ticket's place, whose enrolment finish spends the code. Refusals, in order: stepTicket's; no live ticket listing recovery_code, access.ErrTokenInvalid; a code not 16 Crockford symbols once normalised, a *MalformedError; the limiter's, the hasher's, the count's, the clear's and replaceTicket's, a code, user or ticket gone ending it. A wrong code keeps it, journalling EventSecondFactorFailed once; an empty enrolment set is ErrNoUsableMethod.
func (*Service) State ¶
State reports whether setup is needed, the stored SSO mode, the registration mode a registration would meet, 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) StepUpCode ¶
func (s *Service) StepUpCode(ctx context.Context, c Client, p access.Principal, code string) (Issued, error)
StepUpCode re-proves p's user with a TOTP code and rotates p's session to AuthTime now and AuthMethod MethodTOTP, with the device cookie in Issued. A plain c or p is access.ErrHTTPSRequired, any but a full session ErrSessionRequired, a TOTP that is not usable ErrTOTPDisabled and a dormant user ErrSSOOnly. The code is counted and matched once, so a code used here is code_reused anywhere else; a user with no record is code_invalid.
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, a dormant user ErrSSOOnly, and a user holding no such passkey ErrNotFound. The ceremony replaces the user's earlier step-up ceremony; while its list is full a newcomer is a *ratelimit.RefusedError.
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, a dormant user ErrSSOOnly, 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. Before the limiter: a plain c or p is access.ErrHTTPSRequired, any but a full session ErrSessionRequired, Rules.DisablePasswordLogin ErrPasswordLoginDisabled, a dormant user ErrSSOOnly and one holding a second factor ErrSecondFactorHeld. The attempt is limited on the account and device and counted like PasswordLogin's without an allowance slot. A wrong or locked password is ErrInvalidCredentials, a session rotated or ended meanwhile ErrSessionGone.
func (*Service) TemporaryPasswordHTTPSOnly ¶
func (s *Service) TemporaryPasswordHTTPSOnly(issued IssuedTemporaryPassword) bool
TemporaryPasswordHTTPSOnly reports whether issued works only over HTTPS now: under access.PosturePerRequest, while the current Rules hold RequireSecondFactor or DisablePasswordLogin, or when the issue decided under SSOOnly. It reads no store and cannot fail, so a route calls it after the issue commits.
func (*Service) Tokens ¶
Tokens lists every live invite token, never a setup token, by expiry and then creation, for a principal RequireKeyScope admits under AdminScope 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) for an admin principal or a ManageUsersScope key, returning the user as committed. One Update asks OpSetRole, then OpSetEnabled with the role applied, so a refusal answers before ErrNotFound. A key 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 and key and the tokens those keys issued; an enable restores none, and of a user waiting for approval approves it, clearing WaitingApproval.
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, or the app's own Update) as the last-method guard counts: a password held, allowed and unlocked in a trust context, or a live temporary password; passkeys under st.RPID and an OIDC link of st.OIDCIssuer, each while st.Rules.MethodUsable allows it. A dormant user's local methods and an owner's link never count. The app decides with access.CanDisableMethod. ErrServiceClosed, ErrRulesInvalid for an invalid st.Rules, ErrNotFound for an unknown user, or the store's error.
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 RequireKeyScope admits under AdminScope 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
// RecoveryCode is the recovery code the sign-in's binding issued, shown
// only here; zero when it issued none.
RecoveryCode access.Secret
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: its owner is the account that carries access.User.Owner, which setup and New set, and nothing adds, removes or changes a user.
func (SingleOwnerPolicy) Authorize ¶
func (SingleOwnerPolicy) Authorize(_ context.Context, d Decision) error
Authorize applies the single-owner rules to d.
func (SingleOwnerPolicy) SingleUser ¶
func (SingleOwnerPolicy) SingleUser() bool
SingleUser reports true.
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
// SSO is the stored SSO mode.
SSO SSOMode
// Registration is Rules.Registration, and RegistrationOff under the
// stored mode SSOOnly, which refuses every registration.
Registration RegistrationMode
// 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
// TOTP is whether the app offers TOTP: wired, and Rules.DisableTOTP off.
TOTP bool
// TemporaryPasswordHTTPSOnly is set on a plain request under
// RequireSecondFactor, DisablePasswordLogin or the stored mode SSOOnly,
// where a plain sign-in burns a temporary password, so the plain form
// sends none.
TemporaryPasswordHTTPSOnly 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 TOTPConfig ¶
type TOTPConfig struct {
// Sealer seals each TOTP secret at rest; keep its ring for the store's
// lifetime, since a record no key opens cannot verify a code.
Sealer *access.Sealer
// Issuer names the app in an authenticator, the otpauth label's
// prefix; it holds no colon, the Key Uri Format's label separator.
Issuer string
}
TOTPConfig wires TOTP. A set value needs both fields.
type TOTPEnrolment ¶
type TOTPEnrolment struct {
URI access.Secret // the Key Uri Format's otpauth URI, for a QR code
Text access.Secret // the secret in base32, for typing in
Ticket access.Secret
}
TOTPEnrolment is a begun TOTP enrolment. URI and Text carry the new secret, shown only in this answer; Ticket is what FinishTOTP takes, for ten minutes, from the session that began it.
type TOTPFinish ¶
TOTPFinish is FinishTOTP's input: the enrolment's ticket, a code of the new secret, and, when a record already exists, a current code of it.
type TOTPState ¶
type TOTPState struct {
Since time.Time // the record's CreatedAt; zero with none
Enrolled bool // a record is stored
// Usable is a record that reads as present: TOTP wired and not turned
// off by Rules.DisableTOTP.
Usable bool
// Removable is whether RemoveTOTP would remove it: false with no
// record, and while the second-factor guard would refuse.
Removable bool
}
TOTPState is a user's TOTP record as their own view reads it.
type TemporaryPasswordOptions ¶
type TemporaryPasswordOptions struct {
// TTL is the password's lifetime: 0 is 24 hours, a negative one
// ErrTTLNegative and one above 7 days ErrTTLTooLong. A key's expiry caps
// it.
TTL time.Duration
// RevokePasskeys deletes the user's passkeys, for a lost device that
// held them.
RevokePasskeys bool
// KeepKeys keeps the user's API keys and the tokens they issued, which
// the issue otherwise deletes.
KeepKeys bool
}
TemporaryPasswordOptions are an issue's choices.
type TemporaryPasswordStore ¶
type TemporaryPasswordStore interface {
TemporaryPasswordByUserID(ctx context.Context, userID int64) (rec access.TemporaryPassword, found bool, err error)
// SetTemporaryPassword writes rec over any record rec.UserID holds.
SetTemporaryPassword(ctx context.Context, rec access.TemporaryPassword) error
DeleteTemporaryPassword(ctx context.Context, userID int64) error // idempotent
}
TemporaryPasswordStore holds each user's temporary password, at most one, keyed by UserID (rule 24).
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) (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 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
SecondFactorStore
TemporaryPasswordStore
SSOModeStore
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 and key of the user, every KeyAttribution whose
// UserID is the user, and the user's TOTP, RecoveryCode and
// TemporaryPassword. ErrNotFound when no user has id.
DeleteUser(ctx context.Context, id int64) error
UserCount(ctx context.Context) (int, error)
// UsersWaiting returns at most limit users whose WaitingApproval is
// set, oldest CreatedAt first and equal times in ascending ID (rule 25).
UsersWaiting(ctx context.Context, limit int) ([]access.User, 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
type Waiting ¶
type Waiting struct {
User *access.User
// RecoveryCode is the recovery code the registration's binding issued,
// shown only here; zero when it issued none.
RecoveryCode access.Secret
}
Waiting is an account a registration created under RegistrationApproval: disabled with WaitingApproval set, and no session, until an admin enables it.
Source Files
¶
- actor.go
- admin.go
- allowance.go
- code.go
- config.go
- doc.go
- drafts.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
- oidc_admin.go
- oidc_invite.go
- oidcpolicy.go
- owner.go
- passkey_setup.go
- passkeys.go
- password_login.go
- password_set.go
- pending.go
- policy.go
- profile.go
- proof.go
- ready.go
- recoverycode.go
- reenable.go
- registration.go
- reset.go
- results.go
- rotate.go
- rotate_key.go
- rules.go
- service.go
- sessions.go
- sessions_mint.go
- setup.go
- signin.go
- signin_enrol.go
- signin_setcredential.go
- signin_steps.go
- ssomode.go
- stepup.go
- store.go
- sweep.go
- temppw.go
- temppw_issue.go
- temppw_signin.go
- tokens.go
- totp.go
- transport.go
- users_create.go
- validate.go