users

package
v0.231.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 13 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

Constants

View Source
const (
	RotateLeft     = "left"
	RotateToViewer = "viewer"
	RotateDisabled = "disabled"
)

The kinds of rotate reason, as /teams/{id}/hosts words them.

View Source
const (
	QueueCancelLeftTeam = "Cancelled: the person who queued it is no longer a member of the team."
	QueueCancelToViewer = "Cancelled: the person who queued it is no longer an operator of the team."
)

Why a member's queued send was cancelled by a change to their membership.

View Source
const (
	KindPerson = "person"
	KindTeam   = "team"
)

The two kinds of users row (migration 0126).

View Source
const EnabledPersonIDs = PersonIDs + ` AND disabled_at IS NULL`

EnabledPersonIDs is PersonIDs narrowed to people who are NOT DISABLED: THE predicate for a credential that is honoured on every use without a sign-in (a mirror host's token, a flow runner's token) and for a per-owner loop that should not act for a disabled account. It is PersonIDs plus one clause, so the person rule stays in one place.

🔴 A DISABLED OWNER IS CHECKED ON EVERY READ, NOT ONLY AT THE DISABLE. A disable also revokes the user's mirror tokens (SetDisabledAs), but a credential minted in the moment around a disable, or a table no disable path revokes, is still refused here (#681). It names PERSONS: when a team can own a credential (team sharing phase 2b), that door widens its own owner set, and a team is never disabled through this column.

View Source
const EnabledPersonOrTeamIDs = EnabledPersonIDs + ` UNION ALL SELECT id FROM public.users WHERE kind = 'team'`

EnabledPersonOrTeamIDs is EnabledPersonIDs WIDENED BY TEAMS: the owner set of a credential that a TEAM may own and that is honoured without a sign-in — a team host's mirror token (team sharing phase 2b.2; internal/mirror PGStore.Authenticate and TokenLive). It is EnabledPersonIDs plus a team arm, so the person rule — and its disabled clause (#681) — stays in one place: a disabled PERSON is still out. A team has no disabled_at (users_team_no_login); a team token held by a person who was disabled or left is the rotate mark's case (mirror_tokens.rotate_at), not this filter's.

🔴 NEVER WIDEN EnabledPersonIDs ITSELF. Its other readers (the focus refresher, the flow runner token, plugin tokens and pairing) must not yield a team.

View Source
const PersonIDs = `SELECT id FROM public.users WHERE kind = 'person'`

PersonIDs is THE "owners who are people" predicate, as a subquery: every users-table read outside this package that yields a user to act as, notify, look up by name or authenticate a credential for filters through it (`<col> IN (` + users.PersonIDs + `)`). A team (users.kind = 'team') owns things and is never acted as: a per-owner background loop that met one would build a principal for it, and authz.WithPrincipal refuses that. TestEveryUsersReadIsLedgered pins every users-table read in the module to a class, and requires the person-only class to use this.

View Source
const TeamNameMax = 64

TeamNameMax is the longest team name (users_team_no_login).

Variables

View Source
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")
)
View Source
var (
	// ErrTeamNameTaken: another team has that name (case-insensitively).
	ErrTeamNameTaken = errors.New("users: a team already has that name")
	// ErrTeamName: the name is empty or longer than TeamNameMax characters.
	ErrTeamName = errors.New("users: a team name is 1 to 64 characters")
	// ErrNotATeam: the id names no team.
	ErrNotATeam = errors.New("users: no such team")
	// ErrNotAPerson: the id names no person (a missing user, or a team).
	ErrNotAPerson = errors.New("users: no such person")
	// ErrNotAMember: the person is not a member of the team.
	ErrNotAMember = errors.New("users: not a member of that team")
	// ErrTeamRole: the role is not viewer, operator or manager.
	ErrTeamRole = errors.New("users: a team role is viewer, operator or manager")
)
View Source
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")
)
View Source
var ErrLastManager = errors.New("users: a team keeps at least one manager")

ErrLastManager: the change would leave the team with no manager. A manager cannot make it (an admin can, on /admin/teams).

View Source
var ErrNoRotateReason = errors.New("users: no audit row explains the rotate mark")

ErrNoRotateReason: no audit row explains the mark (a disable through a path that writes no audit row, SetDisabled with no actor).

Functions

func AuditTeamTx added in v0.227.0

func AuditTeamTx(ctx context.Context, tx pgx.Tx, by Actor, team int64, action, object string, detail map[string]any) error

AuditTeamTx is AuditTx recording the TEAM acted on (audit_log.team_id), so the team's managers read it: `muster-server mirror token create --team` records the team host token it mints in the mint's own transaction (team sharing 2b.2).

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 CancelQueuedByTx added in v0.231.0

func CancelQueuedByTx(ctx context.Context, tx pgx.Tx, team, user int64, at time.Time, detail string) (int64, error)

CancelQueuedByTx cancels, inside tx, every still-queued send_queue row user QUEUED into a team's queue — team's (team > 0) or every team's (team 0) — with detail as its reason, finished at at (zero: the transaction's now()). A person's own rows (owner_id = user) are not touched: those are CancelOwner's. It is THE statement for both callers: a membership change here, and internal/sendqueue's CancelQueuedBy.

func LockCredentialsTx

func LockCredentialsTx(ctx context.Context, tx pgx.Tx, id int64) error

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 TeamObject added in v0.224.0

func TeamObject(id int64) string

TeamObject is the audit_log object naming team id.

func UserObject

func UserObject(id int64) string

UserObject is the audit_log object naming user id.

Types

type Account added in v0.224.0

type Account struct {
	Role  authz.Role
	Team  bool
	Teams authz.Memberships
}

Account is what a request principal is built from (internal/api principalFor): users.role, users.kind and team_members, read together so one request has one consistent view of them.

type Actor

type Actor struct {
	UserID int64
	Via    authz.Via
}

Actor is who performed an audited action.

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.

func (Invite) State

func (i Invite) State(now time.Time) InviteState

State is the invite's state at now. Redeemed and revoked are final; a pending invite past its expiry is expired.

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 MyTeam added in v0.227.0

type MyTeam struct {
	ID     int64
	Name   string
	Role   authz.TeamRole
	Notify bool
}

MyTeam is one of a person's teams as Account -> Teams lists it.

type PGStore

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

PGStore is the Postgres store.

func NewPG

func NewPG(pool *pgxpool.Pool) *PGStore

NewPG returns the store over pool.

func (*PGStore) Account added in v0.224.0

func (s *PGStore) Account(ctx context.Context, id int64) (Account, error)

Account reads users.role and users.kind and the person's team_members rows in one statement. Like Role, the api package calls it under authz.System: it is how a request LEARNS who it is. An unknown role or team role is an error, never a guess.

func (*PGStore) AddTeamMemberByEmailAsManager added in v0.224.0

func (s *PGStore) AddTeamMemberByEmailAsManager(ctx context.Context, by Actor, team int64, email string, role authz.TeamRole) error

AddTeamMemberByEmailAsManager adds the person who signs in with email to team as role, for the team's own manager, and records it as by. It reports NOTHING about whether such a person exists: no person with that email, a DISABLED one, or one already in the team, is a nil answer with no change and no audit row, in the same one transaction a real add takes. The caller has checked by manages team.

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) AuditTeam added in v0.225.0

func (s *PGStore) AuditTeam(ctx context.Context, by Actor, team int64, action, object string, detail map[string]any) error

AuditTeam appends one audit_log row naming the TEAM acted on (audit_log.team_id, 0127), for an action on a team's object taken outside this package's transactions — a host spawn lent to or taken back from a team, a team officer's charter edit (team sharing phase 3, design §4). The team's managers read it on /teams/{id}.

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

func (s *PGStore) ByID(ctx context.Context, id int64) (User, error)

ByID returns user id, a PERSON: a team row (migration 0126) is ErrNotFound here, as it is to BySub and IDByEmail, so no sign-in, session or admin action can resolve to one. Teams are read through teams.go.

func (*PGStore) BySub

func (s *PGStore) BySub(ctx context.Context, sub string) (User, error)

BySub returns the user bound to GoTrue subject sub.

func (*PGStore) ClaimInviteLive

func (s *PGStore) ClaimInviteLive(ctx context.Context, tokenHash []byte) (bool, error)

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) CreateTeam added in v0.224.0

func (s *PGStore) CreateTeam(ctx context.Context, by Actor, name string, firstManager int64) (Team, error)

CreateTeam creates team name with firstManager as its manager, and records both as by. One transaction: the team, its first membership and their two audit rows commit together or not at all.

func (*PGStore) DisabledAmong

func (s *PGStore) DisabledAmong(ctx context.Context, ids []int64) (map[int64]bool, error)

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) FirstAdmin added in v0.230.0

func (s *PGStore) FirstAdmin(ctx context.Context) (int64, error)

FirstAdmin is the lowest-id ENABLED admin PERSON: the owner the server's Claude pool keeps its shared account state under — its rate-limit and auth-failure marks and the usage poller's readings (credentials.Plane.EnvPoolOwner). An admin's own Claude accounts ARE that pool, so nothing personal of theirs is ever kept under the same id. It is derived rather than fixed at user 1, so a demoted user 1's own accounts are not steered by the pool's marks. guardLastAdmin keeps at least one enabled admin, so ErrNotFound is a database with none at all.

func (*PGStore) IDByEmail

func (s *PGStore) IDByEmail(ctx context.Context, email string) (int64, bool, error)

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

func (s *PGStore) ListInvites(ctx context.Context) ([]Invite, error)

ListInvites returns the general invites (not admin-claim links), newest first.

func (*PGStore) ListTeams added in v0.224.0

func (s *PGStore) ListTeams(ctx context.Context) ([]Team, error)

ListTeams returns every team with its members, oldest team first.

func (*PGStore) ListUsers

func (s *PGStore) ListUsers(ctx context.Context) ([]User, error)

ListUsers returns every PERSON, oldest first (teams are on /admin/teams).

func (*PGStore) MembershipsAmong added in v0.229.0

func (s *PGStore) MembershipsAmong(ctx context.Context, persons []int64) (map[int64][]authz.Membership, error)

MembershipsAmong is every team membership of each of persons, in ONE query: the team stream sweep's read (internal/api team_live.go), every DisableSweepInterval, of the people who hold an open team stream. A person with no row in the answer is in no team now. Under System: team_members is self-read, and the sweep reads other people's rows.

func (*PGStore) MyTeams added in v0.227.0

func (s *PGStore) MyTeams(ctx context.Context, user int64) ([]MyTeam, error)

MyTeams is person user's teams, by name, with their role in each and their notify switch. Read under System: the caller passes the request principal's own id.

func (*PGStore) OpenInvite

func (s *PGStore) OpenInvite(ctx context.Context, tokenHash []byte) (Invite, error)

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

func (s *PGStore) RecentAudit(ctx context.Context, limit int) ([]AuditEntry, error)

RecentAudit returns the newest audit rows, newest first.

func (*PGStore) RecordSignOutEverywhere

func (s *PGStore) RecordSignOutEverywhere(ctx context.Context, id int64) (time.Time, error)

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) RemoveTeamMember added in v0.224.0

func (s *PGStore) RemoveTeamMember(ctx context.Context, by Actor, team, user int64) error

RemoveTeamMember removes person user from team and records it as by.

func (*PGStore) RemoveTeamMemberAsManager added in v0.224.0

func (s *PGStore) RemoveTeamMemberAsManager(ctx context.Context, by Actor, team, user int64) error

RemoveTeamMemberAsManager is RemoveTeamMember for a team's own manager, refused when it would leave the team with no manager.

func (*PGStore) ReroleTeamMemberAsManager added in v0.224.0

func (s *PGStore) ReroleTeamMemberAsManager(ctx context.Context, by Actor, team, user int64, role authz.TeamRole) error

ReroleTeamMemberAsManager changes the role of an EXISTING member of team, for the team's own MANAGER (/teams/{id}), and records it as by. It never ADDS anyone: a person who is not a member, and an id that names no one, both answer ErrNotAMember — one answer, so the id form is neither a way to add a person without their consent nor an oracle for which ids exist. It refuses a change that would leave the team with no manager. The caller has checked by manages team.

func (*PGStore) ResetCredentials

func (s *PGStore) ResetCredentials(ctx context.Context, id int64) (time.Time, error)

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

func (s *PGStore) RevokeInvite(ctx context.Context, by Actor, id int64) error

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

func (s *PGStore) Role(ctx context.Context, id int64) (authz.Role, error)

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

func (s *PGStore) SetDisabled(ctx context.Context, id int64, disabled bool) (User, error)

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. The user's MIRROR HOST tokens and FLOW RUNNER tokens are revoked the same way, in the same transaction (revokeMirrorTokensTx, revokeRunnerTokensTx; #681), and their hosts' open mirror connections end at the next token recheck (mirror.TokenRecheck).

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.

func (*PGStore) SetRole

func (s *PGStore) SetRole(ctx context.Context, by Actor, id int64, role authz.Role) (User, error)

SetRole changes user id's role. Demoting the last enabled admin is refused (ErrLastAdmin). The change is audited with its before and after.

func (*PGStore) SetTeamMember added in v0.224.0

func (s *PGStore) SetTeamMember(ctx context.Context, by Actor, team, user int64, role authz.TeamRole) error

SetTeamMember adds person user to team with role, or changes their role, and records it as by. Setting the role a member already has changes nothing and records nothing.

func (*PGStore) SetTeamNotify added in v0.227.0

func (s *PGStore) SetTeamNotify(ctx context.Context, user, team int64, on bool) error

SetTeamNotify sets person user's OWN notify switch in team (0133): it updates only team_members.notify, only on the caller's own row, and only while they are a member — ErrNotAMember otherwise, the same answer for a team that does not exist. Under System: team_members is self-read, and the caller passes the request principal's own id (it is in the System ledger). A manager does not set it for anyone else; there is no other writer.

func (*PGStore) TeamAudit added in v0.224.0

func (s *PGStore) TeamAudit(ctx context.Context, team int64, limit int) ([]AuditEntry, error)

TeamAudit is the newest audit rows that name team as their owner, read AS the caller: audit_log's self_read admits a team's MANAGERS to them (migration 0127), and nobody else but the rows' own actors.

func (*PGStore) TeamMembers added in v0.224.0

func (s *PGStore) TeamMembers(ctx context.Context, team int64) ([]TeamMember, error)

TeamMembers is team's members with their roles, read under System: the caller has checked the principal manages team (/teams/{id}) or is an admin.

func (*PGStore) TeamNames added in v0.224.0

func (s *PGStore) TeamNames(ctx context.Context, ids []int64) (map[int64]string, error)

TeamNames is the display name of each of ids that is a team (a person's id is left out). It names the teams a caller's own memberships list — the task board's owner groups and the Owner select — so the caller is a member of each; it returns nothing else about them.

func (*PGStore) TeamPushTargets added in v0.227.0

func (s *PGStore) TeamPushTargets(ctx context.Context, owner int64) (TeamPushTargets, error)

TeamPushTargets reads owner's TeamPushTargets: one query for a person, two for a team. Both member lists are sorted by id.

func (*PGStore) TeamRotateReason added in v0.227.0

func (s *PGStore) TeamRotateReason(ctx context.Context, team int64, at time.Time) (RotateReason, error)

TeamRotateReason is the reason for a rotate mark on team's tokens set at at: the triggering audit row written IN THE MARK'S OWN TRANSACTION — the team's team.member.remove of an operator or manager, its team.member.set from operator or manager to viewer, or a user.disable — with that person's name. rotate_at and audit_log.at are both now() of that one transaction, so the row is matched on at = rotate_at exactly, never "the newest row before it": a mark whose transaction wrote no audit row (a disable with no actor) has NO reason (ErrNoRotateReason), rather than a STALE row from another change (#685 round 1, G4: an older disable of someone who was a viewer then, and an operator now, was shown). The role each condition reads is the row's own (detail.role / detail.before, written at the change), never today's membership. A disable carries no role in its row; it is matched only by its transaction's time, and the disable trigger marks only for an operator's or manager's disable (markRotateForDisableTx).

Read under System: audit_log's self_read admits a team's managers to the team's own rows but not to a user.disable row, which names no team. The caller (/teams/{id}/hosts) has checked the principal manages team.

type RotateReason added in v0.227.0

type RotateReason struct {
	UserID int64
	Name   string
	Kind   string // RotateLeft, RotateToViewer or RotateDisabled
	At     time.Time
}

RotateReason is why a team host token is marked rotate: the person whose change set the mark, what the change was, and when.

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)
	// Account returns everything a request principal is built from, in ONE
	// read: the role, whether the row is a team (which no request may act
	// as), and the person's team memberships. ErrNotFound when there is no
	// such user.
	Account(ctx context.Context, id int64) (Account, error)
}

Store answers a user's role.

type Team added in v0.224.0

type Team struct {
	ID        int64
	Name      string
	CreatedAt time.Time
	Members   []TeamMember
}

Team is one team and its members.

type TeamMember added in v0.224.0

type TeamMember struct {
	UserID      int64
	Email       string
	DisplayName string
	Role        authz.TeamRole
	AddedBy     int64
	AddedAt     time.Time
}

TeamMember is one person's membership.

type TeamPushTargets added in v0.227.0

type TeamPushTargets struct {
	// Team: owner is a team. False for a person (whose push is their own) and
	// for an id that names no one.
	Team bool
	// Name is the team's name, for the title's prefix.
	Name string
	// Notify is who a push reaches: the team's OPERATORS and MANAGERS whose
	// own notify switch (team_members.notify, 0133) is on — persons only, not
	// disabled. A viewer, someone who has left, a disabled person and a member
	// who turned the switch off get nothing.
	Notify []int64
	// Managers is the MANAGERS among Notify (switch on): who a push only a
	// manager can act on reaches (a team agent's connector request, team
	// sharing 4.8: only a manager approves it).
	Managers []int64
	// Withdraw is who a withdrawal (a "resolved" notification) reaches: the
	// same operators and managers WHATEVER their switch says (operator
	// decision G1: "the team's current operators and managers"), so a member
	// who turns the switch off after a push still has it closed.
	Withdraw []int64
}

TeamPushTargets is who a notification owned by owner reaches when owner is a TEAM (team sharing phase 2b, part C: the one team fan-out, in internal/api goNotify). It is read NOW, at send time, under System: team_members and users are self-read, and the caller is a background push naming the owner, not a person.

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.

func (User) Disabled

func (u User) Disabled() bool

Disabled reports whether the account is disabled.

Jump to

Keyboard shortcuts

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