Documentation
¶
Overview ¶
Package users is muster's account store: the `users` and `invites` tables (migration 0006). It answers a user's ROLE for the request Principal (accounts PR 3b) and, for accounts PR 4, reads users by GoTrue subject, disables them, and runs the admin bootstrap claim that binds a new GoTrue user to users.id = 1. Accounts PR 5 adds general link invites, the admin's user management (role, last-admin guard) and the audit log (invites.go).
🔴 THE ROLE IS READ, NOT ASSUMED, AND IT IS READ IN ONE PLACE: Role, which internal/api's roleOf calls for every principal (failure → member). Nothing else in this package returns a role — the User row deliberately has no Role field, so a second, divergent role read cannot creep in beside roleOf.
🔴 BOTH TABLES ARE UNDER FORCE ROW-LEVEL SECURITY (migration 0009): a user principal may SELECT only its own users row, and invites are reachable only at scope 'all'. Every query here except Role therefore runs as authz.System, through the one helper sys (ledgered in internal/authz/ledger_test.go): these lookups are how a request LEARNS who it is (a token's sub → users row), or they run for an anonymous claim-link visitor — there is no principal to run as yet. Role takes the caller's context; api.roleOf hands it System for the same reason.
Index ¶
- Variables
- func AuditTx(ctx context.Context, tx pgx.Tx, by Actor, action, object string, ...) error
- func LockCredentialsTx(ctx context.Context, tx pgx.Tx, id int64) error
- func UserObject(id int64) string
- type Actor
- type AuditEntry
- type Invite
- type InviteState
- type PGStore
- func (s *PGStore) Audit(ctx context.Context, by Actor, action, object string, detail map[string]any) error
- func (s *PGStore) Audited(ctx context.Context, by Actor, action, object string, detail map[string]any, ...) error
- func (s *PGStore) ByID(ctx context.Context, id int64) (User, error)
- func (s *PGStore) BySub(ctx context.Context, sub string) (User, error)
- func (s *PGStore) ClaimInviteLive(ctx context.Context, tokenHash []byte) (bool, error)
- func (s *PGStore) CreateClaimInvite(ctx context.Context, tokenHash []byte, claimUserID, createdBy int64, ...) error
- func (s *PGStore) CreateInvite(ctx context.Context, by Actor, tokenHash []byte, email string, ...) (Invite, error)
- func (s *PGStore) DisabledAmong(ctx context.Context, ids []int64) (map[int64]bool, error)
- func (s *PGStore) IDByEmail(ctx context.Context, email string) (int64, bool, error)
- func (s *PGStore) ListInvites(ctx context.Context) ([]Invite, error)
- func (s *PGStore) ListUsers(ctx context.Context) ([]User, error)
- func (s *PGStore) OpenInvite(ctx context.Context, tokenHash []byte) (Invite, error)
- func (s *PGStore) RecentAudit(ctx context.Context, limit int) ([]AuditEntry, error)
- func (s *PGStore) RecordSignOutEverywhere(ctx context.Context, id int64) (time.Time, error)
- func (s *PGStore) RedeemClaim(ctx context.Context, tokenHash []byte, email string, ...) (User, error)
- func (s *PGStore) RedeemInvite(ctx context.Context, tokenHash []byte, email, displayName string, ...) (User, error)
- func (s *PGStore) ResetCredentials(ctx context.Context, id int64) (time.Time, error)
- func (s *PGStore) RevokeInvite(ctx context.Context, by Actor, id int64) error
- func (s *PGStore) Role(ctx context.Context, id int64) (authz.Role, error)
- func (s *PGStore) SetDisabled(ctx context.Context, id int64, disabled bool) (User, error)
- func (s *PGStore) SetDisabledAs(ctx context.Context, by *Actor, id int64, disabled bool) (User, error)
- func (s *PGStore) SetRole(ctx context.Context, by Actor, id int64, role authz.Role) (User, error)
- type Store
- type User
Constants ¶
This section is empty.
Variables ¶
var ( // ErrEmailMismatch: the invite is bound to a different email. The // invitee's page shows the same "invalid or expired" as every other // failure; this error exists so the caller can count it. ErrEmailMismatch = errors.New("users: the invite is bound to a different email") // ErrEmailTaken: a muster account already has this email. ErrEmailTaken = errors.New("users: a muster account already uses this email") // ErrLastAdmin: the change would leave no enabled admin. ErrLastAdmin = errors.New("users: this is the last enabled admin") // ErrNotRevocable: the invite is not pending (redeemed, revoked, or a // claim link), or does not exist. ErrNotRevocable = errors.New("users: no pending invite with that id") )
var ( // ErrNotFound reports that no user has the id (or subject). ErrNotFound = errors.New("users: no such user") // ErrInvalidInvite: the token names no live claim invite (unknown, // expired, revoked, already redeemed, or its user is already claimed). // Deliberately ONE error, so the page a visitor sees cannot tell the cases // apart. ErrInvalidInvite = errors.New("users: invalid or expired invite") // ErrAlreadyClaimed: the user already has a GoTrue subject. ErrAlreadyClaimed = errors.New("users: this user is already bound to a login") )
Functions ¶
func AuditTx ¶
func AuditTx(ctx context.Context, tx pgx.Tx, by Actor, action, object string, detail map[string]any) error
AuditTx writes one audit_log row inside the CALLER's transaction tx, so an action and its record commit together. It is the account packages' one audit writer: apitokens (accounts PR 6) records token create/revoke through it, as the token's owner (0009's self_append policy).
func LockCredentialsTx ¶
LockCredentialsTx takes user id's credentials lock for the rest of tx.
⚠AN ADVISORY LOCK, NOT `SELECT … FROM users FOR SHARE`: apitokens.Create runs as the USER, and under row-level security a locking read of the user's own row returns NO row (0009 gives users no UPDATE policy, and FOR SHARE is checked against UPDATE policies — measured: 0 rows). An advisory lock needs no row and no policy.
🔴 ORDER RULE: A TRANSACTION THAT WRITES api_tokens OR devices TAKES THIS LOCK FIRST — before any users row lock and before any api_tokens, devices or device_pairing_codes row lock. The writers, enumerated (TestCredentialWritersNeverDeadlock runs them all against one admin and demands zero deadlocks):
- apitokens.Create lock → reads users → INSERT api_tokens, audit_log
- apitokens.Revoke lock → token row FOR UPDATE → UPDATE, audit_log
- SetDisabledAs (disable) lockAccountWritersTx → lock → guardLastAdmin (FOR UPDATE on every enabled admin) → UPDATE users → invites → DELETE devices → UPDATE api_tokens → audit_log
- ResetCredentials lock → UPDATE users → UPDATE api_tokens → DELETE devices
- RecordSignOutEverywhere lock → UPDATE users → DELETE devices
- devices.Redeem an UNLOCKED read of the code's owner → lock → code row FOR UPDATE → reads users → UPDATE code, INSERT devices, audit_log
- devices.Remove lock → DELETE devices → audit_log
- push.ClaimNative lock → the owner's push advisory lock → device row FOR KEY SHARE → DELETE/INSERT push rows (whose foreign keys take KEY SHARE on the device and the users row)
NOT api_tokens writers, and deliberately outside the rule: the bring-your-own-credentials writers (internal/credentials Put*/Delete). Each writes user_credentials and an audit row, needing only FOR KEY SHARE on the owner's users row; nothing else writes user_credentials, so they can wait for a disable but hold nothing it wants. They are in the stress test all the same (0 deadlocks).
and the one api_tokens writer that deliberately does NOT take it: apitokens.Authenticate's last_used_at stamp, a single autocommit UPDATE of one token row that takes no users lock (last_used_at is in no foreign key), so it can only ever wait, never hold-and-wait.
Why first: Create and Revoke end by inserting rows whose foreign keys need FOR KEY SHARE on the user's row, and a disable holds FOR UPDATE on it. A disable that locked rows first and THEN waited for this lock deadlocked against a mint by an ADMIN — measured: SQLSTATE 40P01, the disable lost, the user stayed enabled with the minted token live. Taking it first also keeps the session cutoff honest: clock_timestamp() is stamped AFTER the wait for this lock (TestTheCutoffIsStampedAfterTheCredentialsLockWait).
func UserObject ¶
UserObject is the audit_log object naming user id.
Types ¶
type AuditEntry ¶
type AuditEntry struct {
ID int64
At time.Time
UserID int64
Via string
Action string
Object string
Detail map[string]any
}
AuditEntry is one audit_log row.
type Invite ¶
type Invite struct {
ID int64
Email string // "" when the invite is not bound to an email
Role authz.Role
CreatedBy int64
CreatedByEmail string
CreatedAt time.Time
ExpiresAt time.Time
RedeemedAt *time.Time
RedeemedBy int64
RedeemedByEmail string
RevokedAt *time.Time
}
Invite is one general (non-claim) invite. Its token is never stored; only its sha256 is, and that never leaves this package.
type InviteState ¶
type InviteState string
InviteState is an invite's lifecycle state.
const ( InvitePending InviteState = "pending" InviteRedeemed InviteState = "redeemed" InviteExpired InviteState = "expired" InviteRevoked InviteState = "revoked" )
type PGStore ¶
type PGStore struct {
// contains filtered or unexported fields
}
PGStore is the Postgres store.
func (*PGStore) Audit ¶
func (s *PGStore) Audit(ctx context.Context, by Actor, action, object string, detail map[string]any) error
Audit appends one audit_log row for an action taken outside this package's own transactions (a disable, a reset link).
func (*PGStore) Audited ¶
func (s *PGStore) Audited(ctx context.Context, by Actor, action, object string, detail map[string]any, fn func() error) error
Audited runs action fn with its audit row ALREADY WRITTEN in an open transaction, and commits the row only if fn succeeded — for an action that happens outside the database (a GoTrue call), so the log holds a row for it exactly when it happened. If the commit itself fails after fn succeeded, the error says so; the caller must then not hand out what fn produced.
func (*PGStore) ClaimInviteLive ¶
ClaimInviteLive reports whether tokenHash names a live claim invite. It is for rendering the form; RedeemClaim re-checks under a lock.
func (*PGStore) CreateClaimInvite ¶
func (s *PGStore) CreateClaimInvite(ctx context.Context, tokenHash []byte, claimUserID, createdBy int64, expiresAt time.Time) error
CreateClaimInvite stores a single-use claim invite binding a future GoTrue user to claimUserID, and REVOKES every earlier unredeemed claim invite for that user — so exactly one claim link is live at a time.
It refuses (ErrAlreadyClaimed) when the user is already bound: re-binding the admin to a different login is not what a bootstrap is for.
func (*PGStore) CreateInvite ¶
func (s *PGStore) CreateInvite(ctx context.Context, by Actor, tokenHash []byte, email string, expiresAt time.Time) (Invite, error)
CreateInvite stores a general invite: tokenHash (sha256 of a token the caller shows once), an optional bound email, a role and an expiry. A bound email that a muster account already uses is refused (ErrEmailTaken).
func (*PGStore) DisabledAmong ¶
DisabledAmong reports, for each of ids that exists, whether it is disabled, in one query. An id with no row is absent from the result.
func (*PGStore) IDByEmail ¶
IDByEmail returns the id of the user whose email is email (case-folded), and whether there is one. The sign-in limiter keys a KNOWN account's backoff on this id (internal/api/signin_limiter.go).
func (*PGStore) ListInvites ¶
ListInvites returns the general invites (not admin-claim links), newest first.
func (*PGStore) OpenInvite ¶
OpenInvite returns the live general invite tokenHash names, for rendering the invitee's form (its bound email). ErrInvalidInvite for every other case. RedeemInvite re-checks under a lock.
func (*PGStore) RecentAudit ¶
RecentAudit returns the newest audit rows, newest first.
func (*PGStore) RecordSignOutEverywhere ¶
RecordSignOutEverywhere stamps user id's signed_out_at with clock_timestamp() — never lowering it — and returns it: the durable record of a "sign out everywhere" that the send queue's delivery checks (migration 0019). It moves nothing else: sessions_not_before, the API tokens and GoTrue are the session tier's.
🔴 AND IT DELETES THE USER'S PAIRED PHONES (deleteDevicesTx), in the same transaction, under the credentials lock taken first. Every phone that exists at this moment was paired by a sign-in at or before it, so the rule the device credential is checked by would refuse each one anyway; deleting them also stops their pushes, frees the 20-device cap and takes them off Account → Devices (docs/decisions.md).
func (*PGStore) RedeemClaim ¶
func (s *PGStore) RedeemClaim(ctx context.Context, tokenHash []byte, email string, create func(context.Context) (string, error), undo func(sub string)) (User, error)
RedeemClaim redeems a claim invite in ONE transaction.
🔴 THE INVITE ROW IS LOCKED (FOR UPDATE) BEFORE create RUNS, AND THAT IS WHAT MAKES THE LINK SINGLE-USE UNDER CONCURRENCY. Two redemptions of one token serialize on the lock; the second sees redeemed_at set and gets ErrInvalidInvite, having never called create — so GoTrue gets exactly one user (TestTheClaimLinkIsSingleUseUnderConcurrency).
⚠THE users ROW IS LOCKED TOO, AND FOR A CLAIM EITHER LOCK ALONE SUFFICES — measured by mutation: removing one leaves that test green, removing both turns it red. The users lock is what stops two DIFFERENT links bound to one user both binding it; the invite lock is what single-use rests on for an invite with no claim user (accounts PR 5). Neither is decoration.
create makes the GoTrue user and returns its subject. If anything after it fails, undo(sub) is called so a GoTrue user is not left behind with no muster row bound to it.
func (*PGStore) RedeemInvite ¶
func (s *PGStore) RedeemInvite(ctx context.Context, tokenHash []byte, email, displayName string, create func(context.Context) (string, error), undo func(sub string)) (User, error)
RedeemInvite redeems a general invite in ONE transaction: lock the invite row (FOR UPDATE), check the bound email, create the GoTrue user, insert the users row — ALWAYS a member, whatever the invite row says (D1) — mark the invite redeemed, write the audit row, commit.
🔴 THE INVITE ROW LOCK IS WHAT MAKES THE LINK SINGLE-USE UNDER CONCURRENCY. Two redemptions of one token serialize on it; the second re-evaluates the live predicate after the first commits, finds redeemed_at set, and gets ErrInvalidInvite having never called create — so GoTrue gets exactly one user (TestAnInviteLinkIsSingleUseUnderConcurrency).
create makes the GoTrue user and returns its subject. undo(sub) is called when the muster side is known NOT to have committed (commitDeciding), so a GoTrue user is not left behind with no muster row bound to it.
func (*PGStore) ResetCredentials ¶
ResetCredentials is a password reset's database half: in ONE transaction it moves user id's session cutoff to clock_timestamp() — every GoTrue token issued at or before it is refused from now on (TestAResetEndsOtherDevicesAccessTokensAtOnce) — and revokes every live personal API token the user holds (accounts PR 6; TestAPasswordResetRevokesTheUsersAPITokens). It returns the cutoff.
âš "SIGN OUT EVERYWHERE" IS NOT THIS: it ends GoTrue sessions only, and the /account page says so next to its button.
func (*PGStore) RevokeInvite ¶
RevokeInvite revokes a PENDING general invite. Anything else — redeemed, already revoked, a claim link, no such id — is ErrNotRevocable. An expired invite may still be revoked (it changes nothing but the record).
func (*PGStore) Role ¶
Role reads users.role. Under row-level security a user principal sees only its own row, so the api package reads it under authz.System: it is how a request's role is LEARNED, before any principal exists.
func (*PGStore) SetDisabled ¶
SetDisabled sets (or clears) disabled_at and returns the updated row. Disabling an already-disabled user keeps its original timestamp.
🔴 DISABLING THE LAST ENABLED ADMIN IS REFUSED (ErrLastAdmin), for the reason SetRole refuses demoting it: nobody would be left who can reach /admin to undo it. The check runs under guardLastAdmin's lock (accounts PR 5).
🔴 A DISABLE ALSO MOVES sessions_not_before TO NOW, AND AN ENABLE LEAVES IT. A GoTrue unban resurrects every pre-ban session (migration 0010), so the session tier's cutoff is what keeps a disable from being undone by an enable.
🔴 A DISABLE ALSO REVOKES EVERY PERSONAL API TOKEN THE USER HOLDS, in the same transaction (SetDisabledAs → revokeAPITokensTx; accounts PR 6). Without it, re-enabling the user brought every old token back to life — including one that leaked, which is often WHY the user was disabled. An enable revokes nothing and restores nothing: the user mints new tokens.
func (*PGStore) SetDisabledAs ¶
func (s *PGStore) SetDisabledAs(ctx context.Context, by *Actor, id int64, disabled bool) (User, error)
SetDisabledAs is SetDisabled that, when by is non-nil, writes the user.disable / user.enable audit row in the SAME transaction as the change. A disable also revokes the user's pending invites, in that transaction.
type Store ¶
type Store interface {
// Role returns the role of user id. ErrNotFound when there is no such
// user. An unknown role value is an error, never a guess.
Role(ctx context.Context, id int64) (authz.Role, error)
}
Store answers a user's role.
type User ¶
type User struct {
ID int64
GotrueSub string // "" until claimed
Email string
DisplayName string
DisabledAt *time.Time
// SessionsNotBefore is the session cutoff (migration 0010): a token issued
// at or before it is refused. Set by every disable and every password
// reset, never cleared.
SessionsNotBefore *time.Time
// SignedOutAt is the latest "sign out everywhere" (migration 0019), nil
// for none. Only the send queue reads it: a message queued under a sign-in
// at or before it is not sent. It is NOT a session cutoff — the session
// tier keeps its own, in memory (internal/api gotrueState.notBefore).
SignedOutAt *time.Time
}
User is one muster account, as the session tier needs it. No Role: see the package doc.