🔐 Broker Access Control (RBAC)
LibreFolio implements a granular Role-Based Access Control (RBAC) system for Brokers. This allows users to share access to their brokerage accounts with other users (e.g., family members, accountants) while maintaining control over permissions.
📖 Overview
Access is managed via the BrokerUserAccess table, which links a User to a Broker with a specific UserRole.
erDiagram
USER ||--o{ BROKER_USER_ACCESS : "has access"
BROKER ||--o{ BROKER_USER_ACCESS : "granted to"
BROKER_USER_ACCESS {
int user_id FK
int broker_id FK
enum role "OWNER, EDITOR, VIEWER"
decimal share_percentage "0..1, OWNER-only, scales aggregation"
}
🛡️ Roles and Permissions
There are three roles with increasing levels of privilege:
| Feature | VIEWER | EDITOR | OWNER |
|---|---|---|---|
| View Broker Details | ✅ | ✅ | ✅ |
| View Transactions | ✅ | ✅ | ✅ |
| View Reports/Charts | ✅ | ✅ | ✅ |
| View Report Files (BRIM) | ✅ | ✅ | ✅ |
| Add/Edit Transactions | ❌ | ✅ | ✅ |
| Upload/Parse/Delete Files (BRIM) | ❌ | ✅ | ✅ |
| Edit Broker Settings | ❌ | ✅ | ✅ |
| Manage Access (Add/Remove Users) | ❌ | ❌ | ✅ |
| Delete Broker | ❌ | ❌ | ✅ |
For BRIM report files the administrator (is_superuser) needs no role, a file with no broker is its
uploader's and the administrator's only, and a parse also needs EDITOR or OWNER on the broker it
imports into: see Who reaches a report file.
📋 Role Definitions
- 👁️ VIEWER: Read-only access. Ideal for sharing portfolio visibility without risk of data modification.
- ✏️ EDITOR: Operational access. Can manage the day-to-day data (transactions, imports) and broker settings (name, icon), but cannot perform destructive administrative actions (deleting the broker) or change who has access.
- 👑 OWNER: Administrative access. Full control over the broker.
📏 Key Rules & Constraints
📊 Ownership share (share_percentage)
Each access row carries a share_percentage (0.000000–1.000000) used only for portfolio
aggregation, never for permissions:
- OWNER: the broker's creator gets 1.00; through
PUT /api/v1/brokers/{broker_id}/access, every OWNER gets the share its item carries — 0 when the item has none, even for an OWNER already on the broker. The share may be reduced for co-ownership (e.g. joint accounts); EDITOR and VIEWER default to 0.00 (delegated operator, read-only accountant). - The sum of shares across a broker's users must not exceed 1.00 (validated on add/update); it can be less (a co-owner may simply not be in the system).
- 0 % is a valid share: a 0 % OWNER keeps full admin rights but contributes nothing to the owner's aggregated numbers.
- Aggregation scales by share only for OWNERs — EDITOR/VIEWER rows always carry share 0 by
schema rule yet see full data, so the engine uses scale 1 for them (
effective_share()infinancial_math/native_cash.py, throughbroker_shares(), called byportfolio_service.pyandfinancial_math/portfolio/engine.py). Role/share edits change every scaled number but not the underlying data, so they also join the cache fingerprint for instant invalidation. apply_ownership_share=Falseon the report and the positions series (for the broker page) skips the scaling: every broker counts whole, as an EDITOR sees it, whatever the role and the share (native_cash.broker_shares(), the whole broker).
🔒 The "Last Owner" Rule
To prevent brokers from becoming "orphaned" (left without an OWNER to manage their access or delete them), the system enforces a strict rule:
A broker always keeps at least one OWNER. The last OWNER cannot be removed or downgraded — by anyone, themselves included — but can leave, and leaving deletes the broker.
If a broker has only one user with the OWNER role:
- ❌ Nobody — neither that user nor the administrator — can remove them or change their role to
EDITORorVIEWERwithout making another userOWNER:PUT /api/v1/brokers/{broker_id}/access(bulk_update_access()) refuses any configuration without anOWNER(400, "At least one OWNER is required"). - ❌ That user cannot demote themselves with
PATCH /api/v1/brokers/{broker_id}/access/me(update_own_role()): 400, "The last OWNER cannot demote themselves — promote another user first". - ⚠️ That user can leave with
DELETE /api/v1/brokers/{broker_id}/access/me(leave_broker()), and leaving deletes the broker with its transactions: see Self-Management. - ✅ To leave without deleting the broker, they first make another user
OWNERwith thePUT; they can then leave, or drop their own row in that samePUT.
🔧 Self-Management
- 🚪 Leaving: any user can remove themselves from a broker at any time (
leave_broker). EDITOR/VIEWER always succeed. An OWNER may leave when at least one other OWNER remains — otherwise leaving as the last OWNER deletes the broker entirely. Its transactions do not go by a database cascade:delete_by_broker()deletes them, and the other half of a pair held on another broker stays there without its link — as the standalone row a split of the pair leaves or, for the giving leg of aTRANSFERwhose cost needs a missing conversion, still aTRANSFER(see Broker Deletion). BRIM report files are cleaned up by the API layer. - ⬇️ Self-demotion (
update_own_role): EDITOR → VIEWER is always allowed; OWNER → EDITOR/VIEWER is allowed only when another OWNER remains, and demoting from OWNER zeroes the share (only OWNERs may hold share > 0). Promotions go through thePUT, OWNER or administrator only. - 🗑️ Deleting an account applies
leave_broker()to every broker of the account, in one commit: see Deleting an Account.
🔧 Implementation Details
The logic is centralized in backend/app/services/brokers/access.py (BrokerAccessMixin, part of BrokerService).
- 🔍
_check_user_access(broker_id, user_id, min_role): Core internal method to verify permissions. - 📋
list_accesses(): The users with access to a broker, with role and share. - 🔄
bulk_update_access(): Replaces a broker's whole access configuration in one step (OWNER or administrator): adds, role changes and removals; at least one OWNER must remain, and the shares add up to at most 100 %. - 🚪
leave_broker()/update_own_role(): The self-service paths described above.
🌐 API Endpoints
Access management is exposed via the following endpoints (backend/app/api/v1/brokers.py):
GET /api/v1/brokers/{broker_id}/access: the users with access, with role and share (list_accesses()). Any authenticated user can read the list of any existing broker, email addresses included; 404 only when the broker does not exist.PUT /api/v1/brokers/{broker_id}/access: replaces the whole access configuration in one step (bulk_update_access()). The body is the complete desired list of{user_id, role, share_percentage}: users missing from it lose their access, new ones are added, roles and shares are updated, in one transaction. Granting, changing and revoking access all go through it.OWNERor administrator only (403 otherwise); 400 when a rule fails (noOWNER, shares adding up to more than 1.0, a duplicate or unknown user); 422 for an empty list or a share the schema refuses (outside 0–1, or above 0 for anEDITORorVIEWER).PATCH /api/v1/brokers/{broker_id}/access/me: self-demotion only (update_own_role()), body{role}; 400 for any other change and for the lastOWNER's demotion, 403 without access to the broker.DELETE /api/v1/brokers/{broker_id}/access/me: leave the broker (leave_broker()); the response'sbroker_deletedis true when the lastOWNER's leaving deleted it. 403 without access to the broker.
👑 Superusers and the User CLI
Besides the broker roles, every account carries one system-wide flag, users.is_superuser: the
administrator of the admin manual. It belongs to the account, not to a broker.
- Granted to the first account registered (
POST /api/v1/auth/registerwhilefirst_account_open()holds, that is whilecount_users()is 0, inactive accounts counted: accepted whatever the registration mode, and an administrator even when the invitation it spends grants a regular account), to an account registered with an invitation that grants it (grants_admin, see Invitations), to an account created with./dev.py user createwithout--role user(--role adminis the default:scripts/user_cli.pymaps it to its internalcreate-superusercommand, which callsuser_service.create_user()withis_superuser=True), by./dev.py user promote, and byPATCH /api/v1/users/{user_id}withis_superuser: true../dev.py user create … --role usermaps to the internalcreate-usercommand instead (is_superuser=False): a regular account, even as the first account of an empty database. The administrator ofLIBREFOLIO_ADMIN_EMAILis a superuser from its creation by the startup, inactive until its setup link is spent (The Initial Administrator). - Promote and demote go through
user_service.set_user_admin()from the CLI, which refuses a no-op (already an admin, not an admin), the demotion of the last active administrator and, since lot A-43, the demotion of the initial administrator waiting for its setup, and throughuser_service.update_user_status()from the administrator API, whose route refuses that demotion first (409PENDING_SETUP). A demotion also ends every session of the account (user_service.end_sessions()raisesusers.session_version, see Session Revocation); a promotion does not. Self-deletion has the same guard:DELETE /api/v1/auth/users/meanswers400to an administrator when no other active administrator remains (count_active_superusers(), counted under the write lock since lot A-52: see Decided under the write lock), withdetail{"error_code": "LAST_ADMIN", "message": "Cannot delete account: you are the last active administrator"}since lot A-16 (a bare sentence before); the deletion dialog words it with its own key (Account Errors). The administrator API deletes no administrator, active or not:DELETE /api/v1/users/{user_id}answers409DEMOTE_FIRSTuntil the account is demoted (Deleting an Account), except for the initial administrator waiting for its setup, which cannot be demoted and is deleted directly. - Stale reads (lot A-51):
set_user_active()(user deactivate,user activate),set_user_admin()(user promote,user demote) andupdate_user_status()(the administrator API) read the account again under SQLite's write lock before they decide (refreshed_under_lock(), see Decided under the write lock): the last-administrator guard, then «waiting», whichset_user_admin()reads to refuse a demotion, andset_user_active()andupdate_user_status()to tell a cancellation from a deactivation (A setup completed meanwhile). The account they first read may be stale: on a new instance whose only account is the initial administrator waiting for its setup, the setup can complete in the same millisecond as the command. Read stale,user demoteused to remove the only administrator, anduser deactivateto answer success and end the new owner's sessions without deactivating it, since the column it set was equal to the stale value. Both now refuse it as the last active administrator, nothing changed. - Applied at the next request: the user CLI writes the database directly, with the server
running or not, and
get_current_user()reloads the user on every request. A deactivated account (user deactivate,user_service.set_user_active(), or the administrator API) gets401User account is disabled; its login, with the right password, gets403ACCOUNT_DISABLED— or403EMAIL_NOT_VERIFIEDwhile it waits for its email verification. Deactivation refuses the last active administrator, and ends every session of the account:user activatelets the user sign in again, but brings none of the old sessions back. - Password reset (
user reset,user_service.reset_password()) sets the new hash, computed in a worker thread off the event loop, and ends every session of the account in the same commit: each device gets401at its next request, and signs in again with the new password. The same commit revokes the account's live password-reset links (A-27) and retires its setup links (A-32, The Initial Administrator). A password-reset link does the same when it is spent. To keep the account out altogether, deactivate it. - The account's own changes end its other sessions as well: a password change
(
POST /api/v1/auth/change-password) and an email change (PUT /api/v1/auth/profile, which asks for the current password: see Changing the Email). The device that made the change gets a new cookie and stays signed in; a username change ends no session. Every change that ends sessions is in Session Revocation. - A new address revokes the account's live
email_changelinks together with its password-reset and setup links (user_service.update_profile, A5-4): a change of address asked for before cannot move it again. On a managed instance,./dev.py user reassign-owner <username>(cmd_reassign_owner) takes an account back to the address ofLIBREFOLIO_ADMIN_EMAIL: it runsinstance_owner.assign_owner_and_send_reset, the treatment of a restore (unusable password, sessions ended, links neutralised, one reset link), and refuses on a non-managed profile. - Password rules:
createandresetcallvalidate_password()inscripts/user_cli.py, a thin wrapper overpassword_policy.failed_rules(): the same rules as the API and the app (Password Rules), checked before anything is read from the database. Each rule missed prints a line that starts with its code, such asdigit: the password must contain a digit, and the command exits with1. - Usernames and addresses (lot A-21a):
createrefuses a username holding@and, since lot A-46, one outside 3 to 50 characters, as registration and the Profile do;createandset-emailrefuse an address that is another account's username, in any A–Z case: throughuser_service.create_user()anduser_service.update_profile(). The command prints the service's message after❌— A username cannot contain @: the sign-in reads it as an email address, A username must be 3 to 50 characters long, or Email already registered — and exits with1, writing nothing. The service's refusal is anAccountError, astrthat also carries acode(lot A-47), which the API reads instead of the message. See Which Account an Identifier Names.
The admin commands are in Command-Line Tools.
🚪 Registration, Invitations and the Admin API
Who may create an account, how many accounts an instance may hold, and what an administrator can do
to the other accounts. The rules are in backend/app/services/accounts/registration_service.py, the
account changes in user_service.py, and the variables in backend/app/config/accounts.py
(administrator side: Configuration, section «Accounts and Sign-ups»).
The administrator an operator creates from the environment has its own section:
The Initial Administrator.
🎚️ Registration Modes
effective_registration_mode(session) returns a RegistrationModeState(mode, locked):
LIBREFOLIO_REGISTRATION when it is set (blank counts as unset; case and surrounding spaces are
ignored), with locked=True; otherwise the global setting registration_mode
(Settings System), with locked=False.
The default of that setting is invite (decision 36), and it has one source:
GLOBAL_SETTINGS_DEFAULTS in backend/app/schemas/settings.py. The startup seeding writes it on a
new install, and get_setting_value() answers it while the row is missing: the service passes no
fallback of its own. The seeding creates only missing rows, so an existing install keeps its row,
whatever its value. An install that holds accounts but no row has run with the earlier default,
open: step 5 of migration 005_release_1_3_0_schema writes that open row before the seeding runs
(GLOBAL_SETTING), so an upgrade never closes
registration in silence.
| Mode | POST /api/v1/auth/register accepts |
|---|---|
open |
Anyone. An invite_token is optional, but must be a valid invitation when given, and then sets the role |
invite |
Only a valid invitation |
disabled |
Nobody, invitations included |
Both sources fail closed. A LIBREFOLIO_REGISTRATION that is not a mode makes the mode disabled,
and still locks the setting: registration_mode_pinned() only asks whether the variable is set. A
stored value that is not a mode also reads as disabled. Either is logged by _report_invalid() as
the error event Invalid account configuration, with two fields: problem, the variable or the row
and its value, and consequence, registration stays closed until it is fixed. The function is a
functools.cache, so each problem is logged once per process. The startup
configuration checks do not cover these variables.
register_user() holds the rule of POST /api/v1/auth/register (AuthRegisterRequest, with
an optional invite_token) and owns its transaction. The route checks the password before calling
it, so PASSWORD_TOO_WEAK comes first:
| Situation | Outcome |
|---|---|
A password that misses a password rule |
400 PASSWORD_TOO_WEAK, with rules, the codes missed. Checked by the route before anything else — the mode, the invitation, the limit, a taken username or email — the first account included. Nothing is written, and an invitation given with it stays unspent |
No account at all (first_account_open(): count_users() is 0, an inactive account counts) |
Created as an administrator, whatever the mode, the limit and the role of an invitation. Without an invite_token, nothing else is checked. With one, the invitation must be valid — otherwise 400 INVITE_INVALID, and the instance stays empty — and the registration spends it as any other does (row A valid invitation): its link then reads consumed |
Mode disabled |
403 REGISTRATION_DISABLED |
Mode invite, no invite_token |
403 INVITE_REQUIRED |
| A token that is not a valid invitation: unknown, of another purpose, expired, used or revoked | 400 INVITE_INVALID |
| A valid invitation | Created in the invitation's role (grants_admin; the first account is an administrator whatever it says). The account and the consumption of the invitation (consumed_by_user_id) are committed together. The limit is not checked: the invitation already holds its place |
Mode open, no invite_token |
Created as a regular account, within the user limit |
require_email_verification on, any account but the first |
Created inactive, with a verification token that holds its place; the answer says verification_required: true and verification_email: "sending", and the email goes after it — unless the client address already had the emails of LIBREFOLIO_SIGNUP_EMAILS_PER_ADDRESS registrations in the hour (20 by default): the answer then says verification_email: "held", the account waits without its email, and its owner, told so by the sign-in, asks for the link again from there. "sending" means queued, not delivered; verification_email is null without verification. With no email with a link able to go out, 409 EMAIL_VERIFICATION_UNAVAILABLE, and nothing is created: an invitation stays unspent. See Email Verification |
A username holding @ (lot A-21a: the sign-in reads it as an email address, see Which Account an Identifier Names) |
400 USERNAME_INVALID, the first check of create_user(), after the mode and the invitation; the first account included. register_user() raises it from the code of the service's refusal, USERNAME_INVALID, never from its wording (lot A-47). Nothing is written, and an invitation given with it stays unspent. A username outside 3 to 50 characters never reaches it: AuthRegisterRequest answers 422 first |
| Username or email already taken, or an email that is another account's username, in any A–Z case (lot A-21a) | 400, with the plain-string detail it always had: Username already taken, Email already registered. Any refusal of create_user() but USERNAME_INVALID (USERNAME_TAKEN, EMAIL_TAKEN) becomes the RegistrationError ACCOUNT_EXISTS, which _REGISTRATION_REFUSALS does not list |
The refusals with a code answer {"error_code": …, "message": …} in detail, plus rules for
PASSWORD_TOO_WEAK. Two requests racing for one invitation cannot both spend it: consume_token()
is one conditional UPDATE, and the loser rolls back with INVITE_INVALID.
With LIBREFOLIO_ADMIN_EMAIL the row No account at all never applies: the startup creates the
waiting administrator before the first request, so the instance is never empty while it serves, and
the mode decides (The Initial Administrator).
GET /api/v1/system/instance publishes the effective state as accounts: {registration_mode,
registration_locked, first_account_open, password_rules} (AccountsInstanceConfig). About the
users it says one thing only, whether there is one: first_account_open, from
first_account_open(session), is true while the users table is empty (never with
LIBREFOLIO_ADMIN_EMAIL, whose waiting administrator is a row), and the login page then
offers Register here whatever the mode. No count, no limit
(Public instance configuration; why the flag may be
public: The First-Account Flag). password_rules is the list of
the password rules, [{code, value}] (PasswordRuleRead), the same
on every instance: the app checks a new password against it while the user types.
✉️ Invitations
An invitation is an invite account token: 7 days, single use, link
/invite#token=…, and no user_id, as its account does not exist yet.
- Created by
create_invite(), fromPOST /api/v1/users/invitesor./dev.py user invite, withgrants_admin,emailandcreated_by_user_id(NULLfrom the command line). It refuses in modedisabled(REGISTRATION_DISABLED), and when the instance is full (USER_LIMIT_REACHED) unless called withenforce_limit=False, as only the command line does. It flushes and does not commit. - The email is a suggestion, not a constraint. It records whom the invitation is for, and
POST /api/v1/auth/tokens/inspectreturns it to whoever holds the token, but registration never compares it with the address of the new account: the developer rejected D-A16, the proposal to bind the two. - Listed by
list_pending_invites(): the live ones (not consumed, not revoked, not expired), oldest first. Revoked byrevoke_invite(invite_id), which returnsFalsefor anything that is not a live invitation; it flushes and does not commit. - Spent only by
register_user(), as above.
POST /api/v1/auth/tokens/inspect {token, purpose}, with purpose invite, password_reset or
admin_setup (The Initial Administrator), is public and writes nothing. It answers
{status, purpose}, the status being valid, expired, consumed, revoked or unknown (also for
a token of another purpose). Only a valid token adds expires_at, with grants_admin and email for
an invitation, or username for a reset or setup link.
📏 The User Limit
LIBREFOLIO_MAX_USERS (unset or blank: no limit) bounds the places counted by user_usage(): the
active accounts (users.is_active), the live invitations, and the inactive accounts that wait: those holding a
live email-verification token (Email Verification) and the administrator
waiting for its setup (The Initial Administrator), each account counted once. A deactivated or
deleted account frees its place; an invitation holds one from its creation until it is revoked or expires, and
hands it to the account it opens; an account waiting for its email verification holds one while its link is
live. A value that is not a whole number of at least 1 makes max_users() raise ValueError, and
log_configuration_audit() calls it, so the start stops with an error that names the variable (CL-1). The registration
check _max_users() still reads such a value as a limit of 0, logged like an invalid mode, for a process the audit does not
guard; GET /panel/status answers users_limit: null for it, never a 500.
Over the limit (A5-7)
The state «over the limit» is never stored: user_limit_service.over_limit_state() reads it from the accounts
every time (active > max_users, one COUNT; no limit, or a limit max_users() cannot read, is never a state). A
restore needs no code of its own: the restored accounts are counted like any other.
flowchart TD
A[Request of a signed-in user] --> B{allowed for everyone?}
B -- yes --> OK[answers as usual]
B -- no --> C{active > limit?}
C -- no --> OK
C -- yes --> D{administrator and on the admin list?}
D -- yes --> OK
D -- no --> E[423 user_limit_exceeded]
api/v1/user_limit.py: the dependencyrefuse_when_over_limit, the fourth of the/api/v1router, after the block, the awaiting-restore mode and the interrupted restore (the first that stands answers).ALLOWED_WHEN_OVER_LIMITisALLOWED_WHEN_BLOCKEDless the five routes of the administrator's backup;ALLOWED_WHEN_OVER_LIMIT_ADMINholds those five and the two routes of the choice. The app's own restore is in neither list.GET /users/over-limitlists the active accounts (who isprotected, how many brokers each owns alone);POST /users/over-limit/resolve {keep_user_ids}deactivates the others in one transaction under SQLite's write lock, asupdate_user_status(is_active=False)does (sessions end, links retired), neverdelete_user. Refusals: 409NOT_OVER_LIMIT; 422UNKNOWN_USER,TOO_MANY_KEPT,PROTECTED_MISSING,NO_ADMIN_KEPT.- Protected: the managed owner (
account_protection); with none, the administrator who chooses. At least one administrator stays. Live invitations are revoked newest first only as far as the kept accounts need their places; accounts waiting for a verification keep theirs. - The web app shows
UserLimitPageinstead of the app on the first423 user_limit_exceeded(features/instance/userLimit*.ts, the same shape as the instance block).
| Request | When used >= max_users |
|---|---|
POST /auth/register without an invitation |
The account is inserted, then counted in the same transaction: over the limit, rollback and 409 USER_LIMIT_REACHED, with no numbers and no link, as the caller is anonymous. The first writer holds SQLite's write lock until it commits, so two registrations racing for the last place cannot both take it |
POST /auth/register with a valid invitation, or for the first account |
Not checked |
POST /users/invites |
409 USER_LIMIT_REACHED with limit, used and billing_url, counted under SQLite's write lock (lot A-56: Decided under the write lock) |
PATCH /users/{user_id} reactivating an account |
The same 409, counted under the write lock too (lot A-56), except for an account waiting for its email verification whose link is live: holds_place() says that its place is already counted. Once the link has expired, the account needs a free place like any other. Promotions, demotions and deactivations are not checked |
./dev.py user create, ./dev.py user invite, ./dev.py user activate of an inactive account |
The warning The instance is at its limit (LIBREFOLIO_MAX_USERS: <used> of <max> places taken): the command line <action> anyway, <action> being creates the account, creates the invitation or reactivates the account; then the command goes ahead. user activate prints none for an account that already holds its place: one waiting for its email verification whose link is live (holds_place()), or, since lot A-40, the initial administrator waiting for its setup (registration_service.is_pending_admin(), the filter user_usage() counts it with; IMG-030f of ./dev.py test utils dev-cli-image) |
billing_link() returns LIBREFOLIO_BILLING_URL to administrators only: in usage.billing_url of
GET /users, in the 409 USER_LIMIT_REACHED of the administrator
routes, and in billing_url of GET /system/block, the block page of a blocked instance
(Security → Instance Block). An invalid LIBREFOLIO_BILLING_URL or LIBREFOLIO_PUBLIC_URL is treated as unset and logged
like an invalid mode, with its own consequence: the billing link stays hidden until it is fixed,
or links show the bare path until it is fixed.
🛠️ Administrator API
backend/app/api/v1/users.py, every route behind require_admin (401 without a valid session,
403 Admin access required for a regular account); the last row, the public half of the
address probe, is in auth.py. The static paths are declared before
/users/{user_id}, so /users/invites, /users/account-links and /users/address-probe are never read as a user id.
| Route | Body | Does | Answers |
|---|---|---|---|
GET /users |
— | Every account, oldest first (id, username, email, is_active, is_superuser, created_at, protected: see Protected Accounts, holds_place: inactive and waiting for its email verification with a live link, so its place is already counted, from place_holders() in one query — see Email Verification —, pending_verification: inactive and waiting for its email verification, a link neither used nor revoked, live or expired, so that the Users tab badges it — holds_place says whether it still holds a place —, from email_verification.waiting_ids() in one query (lot E-7), pending_setup: the initial administrator waiting for its setup, from registration_service.pending_admin_ids() in one query, and avatar_url: the account's avatar as its user settings store it, an image uploaded to the app or an address, null without one or without a settings row, from user_service.avatar_urls() in one query, lot N69-4), with usage: {used, max_users, billing_url} |
200 |
PATCH /users/{user_id} |
{is_active?, is_superuser?, cancel_setup?} |
update_user_status(), all or nothing: an omitted field, or a value equal to the current one, changes nothing, with two exceptions for is_active: false on an account inactive already: one waiting for its email verification ends the wait as user deactivate does — its links revoked, its place free —, and the initial administrator waiting for its setup has its setup links revoked, the cancellation of its link (any other account has the setup links it never consumed retired). cancel_setup: true (default false, lot A-51) makes the request that cancellation and nothing else: an account that does not wait for its setup is left as it is. The service reads the account again under SQLite's write lock before its own decisions — a deactivation or a demotion, the last active administrator, «waiting» —, so a change committed since the route's first read, a setup completed for one, is seen (Decided under the write lock). A deactivation or a demotion ends every session of the account. A change of is_active revokes the account's email-verification links and retires its setup links (The Initial Administrator) |
200 with the account, holds_place, pending_verification, pending_setup and avatar_url included (holds_place and pending_verification false once a wait has ended, pending_verification from awaiting_verification(); pending_setup still true after a cancellation); 404, also for an account deleted since the route's first read (lot A-54); 422 for cancel_setup: true without is_active: false; 409 ACCOUNT_PROTECTED for a deactivation, a demotion or a cancellation of a protected account, checked first; 409 PENDING_SETUP for is_superuser: false or is_active: true on the initial administrator waiting for its setup (is_pending_admin()), checked before the user limit, nothing changed; 409 LAST_ADMIN for the last active administrator; 409 SETUP_COMPLETED for cancel_setup: true on an account that does not wait for its setup, its setup completed since the caller looked (A setup completed meanwhile), nothing changed; 409 USER_LIMIT_REACHED for a reactivation over the limit, counted under the write lock (lot A-56), unless the account holds_place |
GET /users/{user_id}/deletion-preview |
— | preview_user_deletion(): what deleting the account would take with it. Writes nothing |
200 AccountDeletionPreviewRead; 404 |
DELETE /users/{user_id} |
— | delete_account(): the account, and the brokers it is the only OWNER of, all or nothing. Cannot be undone: see Deleting an Account |
204 with an empty body; 404, also for an account deleted since the route's first read; 409 SELF_DELETION, ACCOUNT_PROTECTED or DEMOTE_FIRST (never for the initial administrator waiting for its setup, deleted directly; whether the account is an administrator, and whether it still waits, is read under SQLite's write lock, so one set up or promoted since the route's first read answers DEMOTE_FIRST, lots A-51 and A-55: Decided under the write lock); 500 when the deletion fails, nothing deleted |
POST /users/{user_id}/password-reset-link |
— | A reset link, shown once | 201 {token, path, url, expires_at}; 404, also for an account deleted since the route's first read (under the write lock, lot A-54) |
POST /users/{user_id}/sessions/revoke |
— | end_sessions(): every device of the account is signed out at its next request |
204; 404, as above |
POST /users/{user_id}/onboarding/reset |
optional {flow} |
reset_onboarding_progress(): that flow, or every flow, back to pending, steps included, with completed_at and skipped_at cleared (backlog item 21-5) |
204; 404, as above; 422 for a flow that does not exist |
GET /users/account-links |
— | account_links.list_links(): every account token, of every purpose, newest first (lot UA3): id, purpose, state (revoked, used, expired or open, read in that order, as inspect_token() does: a retired link reads revoked), revocable, user_id and username, email, grants_admin, created_by_user_id and created_by_username, created_at, expires_at, used_at with used_by_user_id and used_by_username (the account that spent it: consumed_by_user_id, or the link's own account for a purpose other than invite), revoked_at. Never the token nor its hash |
200 |
POST /users/invites |
{grants_admin=false, email?} |
create_invite(); the link is shown once |
201 {invite, token, path, url}; 409 REGISTRATION_DISABLED; 409 USER_LIMIT_REACHED |
DELETE /users/account-links/{link_id} |
— | account_links.revoke_link(): an open link of a purpose in REVOCABLE_PURPOSES (invite, password_reset, email_verification) stops working at once; an invitation frees its place. One conditional UPDATE: a link spent meanwhile is not revoked |
204; 404 when no such link is open; 409 LINK_NOT_REVOCABLE for an open admin_setup link (cancelled from its account) or email_change link (the host's address drives it, and the next start issues it again) |
POST /users/address-probe |
— | issue_probe_nonce(): a signed nonce for the address probe, valid 120 s and stored nowhere; a new one at every call |
200 {nonce, expires_at}; 503 INSTANCE_KEY_UNAVAILABLE when the instance key cannot be used |
GET /auth/address-probe?nonce=… |
— | Public, the same answer with or without a session: verify_probe_nonce(), whether this instance issued the nonce. Readable from any origin (Access-Control-Allow-Origin: *) |
200 {match}: false for anything not issued here or expired, never 422 |
pathistoken_path(): the page, with the token in the fragment (#token=…, see Links in Use).urlisLIBREFOLIO_PUBLIC_URLfollowed by the path (public_link()),nullwhen the variable is unset or invalid.- Each change writes a structured log event with the id of the account or of the invitation, and
the administrator's (
admin_id, orcreated_by_user_idfor an invitation or a reset link): Invitation created, Invitation revoked by an administrator, Account updated by an administrator, Account deleted by an administrator, Password reset link created, Sessions ended by an administrator, Onboarding reset by an administrator. None carries the token or its hash.
Decided under the write lock (lots A-51 to A-56). A path that changes an account reads it, then
takes SQLite's write lock and reads it again before its first write:
user_service.refreshed_under_lock(session, user) calls backend.app.db.session.begin_writes(), then
selects the id. When the account was deleted in between, it rolls back and answers False, and the
caller answers as for an account that does not exist: 404 User not found, the bare string of
_user_or_404(), or User '<username>' not found on the command line (lot A-54; before, the API
answered a 500, or a success for nothing done, and the command line printed a traceback). Otherwise
it refreshes the account, and the decisions listed below read it as it is under the lock: a setup
completed or a promotion committed by another request since the first read is seen. The refusals a
route makes on its first read (SELF_DELETION, ACCOUNT_PROTECTED, PENDING_SETUP) write nothing.
PATCH /users/{user_id}(update_user_status(),"NOT_FOUND"for an account gone): the last-administrator rule, «waiting» for a cancellation, and the change;DELETE /users/{user_id}: whether the account is an administrator and whether it still waits for its setup, so one set up (A-51) or promoted (A-55) since the first read answers409DEMOTE_FIRST;POST /users/{user_id}/password-reset-link,/sessions/revokeand/onboarding/reset(A-54);DELETE /api/v1/auth/users/me(A-52): the other active administrators are counted under the lock, so of the last two active administrators deleting their own accounts at once, the second gets400LAST_ADMIN;./dev.py user activate,deactivate,promoteanddemote(set_user_active(),set_user_admin()): the last-administrator guard, then «waiting».
The user limit is counted under the lock too (A-56): the PATCH reactivating an account
takes it before user_usage(), and create_invite() (POST /users/invites) before its count, so of two
requests that saw the last free place, the second sees the first and answers 409
USER_LIMIT_REACHED, the PATCH's with the counts read under the lock. A refusal rolls back, and lets
the lock go. Tests: TestDecidedUnderTheWriteLock of ./dev.py test api users-admin (UADM-LOCK-01 to
UADM-LOCK-15) and of ./dev.py test api account-deletion (ACCDEL-LOCK-01 to ACCDEL-LOCK-03), and
LOCK-CLI-01 and LOCK-CLI-02 of ./dev.py test services admin-bootstrap: without threads, a rival commits
on another connection right before the code's first write.
🗑️ Deleting an Account
DELETE /api/v1/users/{user_id} deletes another account by the rule of deleting one's own: broker by
broker, the last-owner rule of BrokerService.leave_broker(). A broker the account is the only OWNER of
goes, with its transactions and its report files; on the others only the account's access goes. An inactive
co-owner's OWNER row counts as another owner. The rule, the shared helper and the preview are in
Deleting an Account.
GET /api/v1/users/{user_id}/deletion-preview tells the administrator beforehand what the deletion would
take, by the same rule, writing nothing: brokers_deleted, brokers_left and transfers_unpaired.
GET /api/v1/auth/users/me/deletion-preview gives any signed-in user the same for their own account.
After require_admin, the deletion refuses, in this order:
404User not found: no such account;409SELF_DELETION: the caller's own account, which is deleted from the profile (DELETE /api/v1/auth/users/me);409ACCOUNT_PROTECTED, with thereasonof the protection hook. It comes beforeDEMOTE_FIRSTbecause demoting a protected account is refused too;409DEMOTE_FIRST: an administrator, active or not. It must be demoted first, so the last administrator can never be deleted from here. Not the initial administrator waiting for its setup (is_pending_admin(), lot A-43): it cannot be demoted (409PENDING_SETUP) and never was an active administrator, so it is deleted directly, the hard cancellation of its setup: its setup links go with it (account_tokens.user_idcascades), its place is freed, and nobody waits any more:./dev.py user setup-linkfinds nobody, and a next start with the variables still set answersignored, since the instance has accounts (The Initial Administrator). Whether the account is an administrator, and whether it still waits, is read under SQLite's write lock, on the account read again (Decided under the write lock): one set up (lot A-51) or promoted (lot A-55) since the route's first read answersDEMOTE_FIRST, rolled back, nothing deleted; one deleted meanwhile answers the404of point 1 (lot A-54).
Each 409 carries detail {error_code, message}, plus reason for ACCOUNT_PROTECTED. Otherwise the
route calls user_service.delete_account(), the helper of DELETE /auth/users/me too, and answers 204
with an empty body. All or nothing: a technical failure rolls everything back and answers 500 Account
deletion failed: nothing was deleted. The deleted account's sessions get 401 at their next request.
- Log: one structured event, Account deleted by an administrator, with
user_id,username,admin_id,brokers_deleted(the ids of the deleted brokers) andfiles_removed. A failure logs Account deletion by an administrator failed: nothing was deleted, withuser_id,admin_idand the traceback. - Blocked instance: both previews and the administrator's deletion are outside
ALLOWED_WHEN_BLOCKED(Instance Block):423for a signed-in caller,401for anyone else. Of the deletion routes, onlyDELETE /api/v1/auth/users/meis on the list.
🛡️ Protected Accounts
user_service.account_protection(user) -> Optional[str] gives the reason why nobody may delete, deactivate
or demote an account, or None. It is the hook for the owner of a managed instance, the administrator who pays
for it (PAYING_ADMINISTRATOR). On any other profile it returns None for every account. On a managed instance
(LIBREFOLIO_PROFILE=managed):
- the account recorded as the instance owner (
users.is_instance_owner) is protected by that mark alone, whatever its address and whatever the variable says; - once the startup step
owner-synchas read the owner (user_service.note_recorded_owner()), the mark decides alone when an owner is recorded: an account that holds the address of a variable changed in conflict is a stranger and never receives the owner's protection; - when the step recorded nobody, the account with the address of
LIBREFOLIO_ADMIN_EMAIL(A–Z case aside) is protected by its address only while it is an active administrator (the criterion by which the step records an owner); -
before the step has run (a command, a test) the A5-1 address rule is the fallback: the address alone protects.
-
GET /usersreflects it inprotected(AdminUserRead), as do the accountsPATCHreturns. DELETE /users/{user_id}, and aPATCH /users/{user_id}that deactivates or demotes the account, or cancels the setup link of the initial administrator waiting for its setup (is_active: falseon that inactive account, lot A-43, The Initial Administrator), answer409ACCOUNT_PROTECTEDwith thatreason. ThePATCHchecks it first, beforePENDING_SETUP, the user limit and the last-administrator rule.- Promoting or reactivating a protected account is not refused.
- The command line stays above protection:
./dev.py user deactivate,user demoteand the other user commands never read the hook, as the operator of the server may do what the administrator API refuses.
📬 The Owner's Address
The protected owner cannot change its address from the app (PUT /auth/profile answers 409 ACCOUNT_PROTECTED).
The real change starts at the host, and services/accounts/instance_owner.py runs it:
startup_owner_sync(), the startup stepowner-sync(right afterrestore-commit, which revokes every live one-time link after a restore and would kill a link issued before it; skipped while the instance serves no data): managed only, with a usable variable. A waiting initial administrator (pending_admin): nothing,bootstrap_admin_servicefollows the variable as before. No owner recorded: the account with the variable's address is recorded (heal) only if it is an active administrator, else an error is logged and nobody is recorded. The owner has the variable's address: nothing, stale links revoked. Otherwise: another account holds the address →blocked, an error line, no change; a liveemail_changelink already carries it →waiting, nothing resent; else the owner's older links are revoked, a new one is issued (7 days,email= the new address) under SQLite's write lock (two workers issue one) and emailed to the NEW address in a background task (build_email_change_confirmation()). The link is logged atwarningonly when the email did not go.owner_change_status(session)answers"pending","blocked"orNonefor the security checks and the hosting panel. It reads only and never returns an address.POST /email/email-change/confirm(confirm_owner_email_change, no session):confirm_email_change()spends the link and, in the same transaction, checks that the instance is managed, that the token's account is the recorded owner, that the token's address is still the variable's and that no other account holds it; then sets the address (verified), ends the owner's sessions, and revokes its other change links and its reset links. A link that no longer matches is revoked and answersTOKEN_INVALIDrevoked. The notice to the old address isflows.email_changed_work, as for the profile.
Tests: ./dev.py test services owner-email-change, ./dev.py test api owner-email-change,
./dev.py test db migration-005.
🔑 Password-Reset Links
A reset link is a password_reset account token: 30 minutes, single
use, link /reset-password#token=…, bound to its account (user_id). Unlike ./dev.py user reset,
the administrator does not choose the new password: whoever spends the link does.
- Issued by
user_service.create_password_reset(), fromPOST /api/v1/users/{user_id}/password-reset-linkor./dev.py user reset-link <username>, and, when email works, from Forgot Password? on the login page (POST /api/v1/email/password-reset, workstream E): that link is never shown, only emailed to the account's own address, within its limits, and never while an administrator's reset link is still live (A Forgotten Password). It first revokes the account's live reset links, so only the newest one works. Issuing a link ends no session. - Spent by
POST /api/v1/auth/password-reset{token, new_password}, which is public.new_passwordmust meet the password rules, checked before the token is read: a weak one is400PASSWORD_TOO_WEAK, and the link is neither spent nor inspected, so a valid link stays valid.complete_password_reset()consumes the token, hashes the new password with bcrypt in a worker thread, ends every session of the account, revokes its other live reset links and retires its setup links (The Initial Administrator), in one commit; the answer is200. A link that is not valid (used, expired, revoked, unknown or of another purpose) changes nothing:400TOKEN_INVALID. - Revoked with the account's password or address: a password change, an email change (the same
address in another A–Z case is none) and
./dev.py user resetrevoke its live reset links, whoever issued them, in the commit of the change (lot A-27, Session Revocation).
Tests: ./dev.py test services registration
(backend/test_scripts/test_services/test_registration_service.py: the variables, the effective
mode, the usage, invitations, every branch of register_user(), the limit under a race),
./dev.py test api registration (backend/test_scripts/test_api/test_registration_api.py:
registration by mode, inspection, the password reset, the password rules on both, the accounts
block, the locked setting) and
./dev.py test api users-admin (backend/test_scripts/test_api/test_users_admin_api.py: the
administrator API with its guards and its logs; the deletion and its preview on the lane's server, and
in process the protection hook replaced, the log event and an injected failure; each account's
avatar_url, lot N69-4, UADM-AV-01 to UADM-AV-04: in GET /users and in the answer of a PATCH on
the lane's server, in process with the settings rows given the ids of other accounts, and the
schema; each account's pending_verification, lot E-7, UADM-VER-01 to UADM-VER-05: in process, on a private
database, in GET /users and in the answer of a PATCH, a live link and an expired one alike). The address probe has
its own tests, listed in Address Probe.
The web pages of the links, /invite and /reset-password, are in
Authentication Components.
The administrator's side is in Global Settings, section «Who Can Sign Up»; Configuration, section «Accounts and Sign-ups»; and Command-Line Tools, section «Manage Users».
👑 The Initial Administrator (F02)
Feature F02 of the release 1.3 plan (lot A7a): an operator, such as a hosting provider or a
scripted install, names the administrator of a new instance in the environment. The startup creates
it, inactive, with a single-use setup link; whoever spends the link chooses the password, activates
the account and is signed in. The variables are read in backend/app/config/accounts.py, the rest
is in backend/app/services/accounts/bootstrap_admin_service.py. Administrator side:
«The Initial Administrator» in Configuration.
The variables. admin_bootstrap_config() returns an AdminBootstrapConfig(email, username, token),
read at every call from the process environment only, or None while LIBREFOLIO_ADMIN_EMAIL is
unset or blank: without the variables, an install is unchanged.
| Variable | Rule | Refused with (AdminBootstrapConfigError.code) |
|---|---|---|
LIBREFOLIO_ADMIN_EMAIL |
An email address (pydantic EmailStr), surrounding spaces ignored. Turns F02 on |
ADMIN_EMAIL_INVALID |
LIBREFOLIO_ADMIN_USERNAME |
admin when unset (DEFAULT_ADMIN_USERNAME); 3 to 50 characters and no @, the rules of every new username (USERNAME_MIN_LENGTH, USERNAME_MAX_LENGTH, which user_service applies too since lot A-46; USERNAME_RESERVED_CHARACTER since lot A-21a, see Which Account an Identifier Names); surrounding spaces ignored |
ADMIN_USERNAME_INVALID, for the length and for the @; the message of the @ names it and says that the administrator signs in with LIBREFOLIO_ADMIN_EMAIL anyway. ADMIN_USERNAME_WITHOUT_EMAIL without the email |
LIBREFOLIO_ADMIN_BOOTSTRAP_TOKEN, or its _FILE (env_secret()) |
Optional: the token of the setup link, given by a hosting panel; None for a generated one. 32 to 200 characters (ADMIN_BOOTSTRAP_TOKEN_MIN_LENGTH; ADMIN_BOOTSTRAP_TOKEN_MAX_LENGTH, the longest token the link's requests accept), each one in ADMIN_BOOTSTRAP_TOKEN_CHARACTERS, the unreserved characters of a URL (A–Z a–z 0–9 - . _ ~): it travels in /setup#token=… as written. Not trimmed: like every secret env_secret() reads, it is used as written |
ADMIN_BOOTSTRAP_TOKEN_INVALID_CHARACTERS (a space included), ADMIN_BOOTSTRAP_TOKEN_TOO_SHORT, ADMIN_BOOTSTRAP_TOKEN_TOO_LONG; ADMIN_BOOTSTRAP_TOKEN_WITHOUT_EMAIL without the email. A _FILE that cannot give it raises SecretFileError |
AdminBootstrapConfigError(variable, code, message), a ValueError, names the variable in
variable and in its message, never the token. log_configuration_audit() calls
admin_bootstrap_config() (Configuration Checks), so an unusable
value stops the startup, on an instance with accounts too, as an unreadable LIBREFOLIO_BLOCKED
does.
At startup. The admin-bootstrap step, right after global-settings
(Server Startup), runs startup_admin_bootstrap(), which returns at
once with F02 off. Otherwise run_admin_bootstrap(session, config) applies the variables, commits
what it writes, and returns a BootstrapResult whose action (BootstrapAction) says what it did:
action |
When | What it does |
|---|---|---|
off |
F02 off | Nothing |
ignored |
Accounts exist and none is waiting, the setup done included, through the link or another way (below); or a re-arm that finds the setup completed in the meantime (rearmed) |
Logs LIBREFOLIO_ADMIN_* ignored: this instance already has accounts (INFO); after a re-arm cut short, the INFO line of rearmed instead |
created |
No account at all | In one transaction: the registration_mode row set to invite (inserted when missing, updated_by_user_id NULL); the administrator, superuser and inactive (create_user(..., is_superuser=True, is_active=False, commit=False)), whose password is the bcrypt hash of secrets.token_urlsafe(32), a secret nobody ever sees, so no password signs in and a login attempt costs what it costs for any account; an admin_setup token for it, the variable's or a generated one, 72 hours. A variable's token already stored once (an instance emptied after an earlier setup) is not stored again: a token is generated instead, with a warning naming the variable. link_token holds the plaintext of a generated token, and only of that |
rearmed |
An administrator waits, and the variable's token was never stored (_token_known(): no row has its hash, whatever its account or purpose) |
Revokes the administrator's setup links, then reads «waiting» again under the write lock that revocation took (lot A-42, The Setup Link's Lifecycle): an account set up in the meantime rolls everything back, and the start is ignored, with the INFO line LIBREFOLIO_ADMIN_BOOTSTRAP_TOKEN not re-armed: the initial administrator was set up meanwhile. Otherwise stores the new token, 72 hours. The token is neither logged nor emailed |
pending |
An administrator waits, with a live setup link | Nothing new: no link issued, none logged |
expired |
An administrator waits, with no live setup link: the link expired, or was revoked — by a cancellation, for one — and no token of the variable re-arms it, as one already stored never does | Logs one WARNING, which ends with the remedy run ./dev.py user setup-link, followed by , or set a new LIBREFOLIO_ADMIN_BOOTSTRAP_TOKEN when the variable is set. Which one (lot A-50): at the start that writes a new address, the WARNING of the address change (below); otherwise, when the account's latest setup link (by created_at, then id) was revoked and never consumed (_latest_setup_withdrawn()), a cancellation or an address change at an earlier start, The initial administrator's setup link was withdrawn (cancelled, or its address changed): …; otherwise The initial administrator's setup link has expired: … |
- The waiting administrator is
pending_admin(session), built onregistration_service.pending_admin_filter(): an inactive account with at least oneadmin_setuptoken, none of them consumed. An expired or revoked link keeps it waiting, a cancelled one included; a spent one ends the wait, and so does a retired one, the account set up another way (below). Beforerearmed,pendingorexpired, the account follows the variables (_follow_variables()): a differentusernameoremailis written, unless another account holds it, which logs an ERROR and keeps the account's own. - A new address (lot A7b-2, A-33) — not the same one in another A–Z case, whose spelling the
account simply takes (decision P18) — revokes the account's setup links in the transaction that
writes it: they went to the earlier address. Revoked, not retired: the account still waits. A
token of the variable never stored re-arms it at that start (
rearmed); otherwise no live link is left and the start isexpired, with the WARNINGThe initial administrator's address changed: the setup link handed over before no longer works; run ./dev.py user setup-link(and, or set a new LIBREFOLIO_ADMIN_BOOTSTRAP_TOKENwhen the variable is set), once: the next starts log the WARNING of a withdrawn link, since the latest setup link is revoked (lot A-50,expiredabove), until a new link is given. A new username alone, or an address another account holds, revokes nothing.user_service.update_profile()revokes them the same way on a real change of the address (./dev.py user set-email): the account then waits for a link of./dev.py user setup-link, and a next start whoseLIBREFOLIO_ADMIN_EMAILnames another address, the earlier one for instance, writes it, which revokes them again. - Registration. The waiting administrator is a
usersrow, sofirst_account_open()is false from the first start, and nobody registers as the first account:register_user()applies the mode,inviteunlessLIBREFOLIO_REGISTRATIONpins another. The step writesregistration_modeonly when it creates the administrator. - Delivery, only after
createdwith a generated token.deliver_setup_link(result, engine=…)writes the link once in the log, at WARNING:Setup link of the initial administrator, single use: open it to choose the password, withlink(public_link(): the full address withLIBREFOLIO_PUBLIC_URL, otherwise the path, and anoteasking to put the server's address in front of it) andexpires_at. Then, whenrequire_email()andrequire_links()allow it, it emails the link to the account's address withbuild_admin_setup()(Email Service), in the instance's language (instance_language()). The startup runs it in a background task (asyncio.create_task()), with a session of its own, so a slow SMTP server never delays the start. It never raises: an email that cannot go logsSetup link of the initial administrator not emailed(INFO), with the exception's class inreason, and the link in the log still works. A token from the variable is neither logged nor emailed: the panel that chose it delivers it. - Several workers. Each worker runs the step, and only one creates the administrator. SQLite
runs in WAL with a 30 s
busy_timeout: a transaction whose first statement writes waits for the write lock, while one that reads first and writes later can fail at once with database is locked if another connection wrote in between. So_create_pending_admin()commits, which ends its reads, and starts with a write, theregistration_moderow: it holds the write lock before it counts the accounts. The worker that comes second finds the account, goes on aspending, and delivers nothing. On a restart, a worker that finds the lock taken while another re-arms or renames answerspending, and lets that one apply the change.
The setup's status, for a hosting panel (lot H-61). admin_setup_status(session, *, now=None)
tells the status route of a hosting panel where the setup of the initial administrator stands. It
answers an AdminSetupStatus, a frozen dataclass: state, an AdminSetupState (a StrEnum, so it
formats and serialises as its value: none, pending, done or expired), and setup_expires_at,
in UTC, for pending only, None otherwise. It reads the admin_setup links of every account,
though only the F02 administrator ever gets one; the links of the other purposes (invitations,
password resets, email verifications) never count. The status is not «waiting» (pending_admin(),
above): an administrator whose link ran out or was cancelled still waits, and its
setup reads expired. The rule, in this order («done wins»):
- No
admin_setuplink stored:none. None was ever issued, or the account that held them was deleted:account_tokens.user_idisON DELETE CASCADE, and its links went with it (Deleting an Account). - Any
admin_setuplink consumed:done. Spent by the setup (complete_admin_setup(), below), or retired because the account was activated or given a password another way (A-32, below). A consumption is final: no link is issued after one (pending_admin()wants none consumed), so a stray newer link, which a setup through an older one leaves revoked, never makes a set-up instance readexpired. - Otherwise the latest link, by
created_atthenid, decides. Revoked without use — the setup cancelled (A-43), the address changed (A-33, above) — or past its expiry (expires_at <= now):expired. Otherwisepending, with that link'sexpires_atassetup_expires_at. A link replaced by a newer one (issue_setup_link(), a re-arm) is revoked too, but the newer one is then the latest, and decides.
now, the moment the expiry is compared with, is the clock (utcnow()) when left out. The function
only reads: it writes and commits nothing, leaves nothing in the session for its caller to commit,
and never takes SQLite's write lock.
The setup. POST /api/v1/auth/setup {token, new_password} (AdminSetupRequest, token of at
most 200 characters) is public:
- The password rules come first:
400PASSWORD_TOO_WEAKwithrules, as for registration, a reset and a password change. Nothing is read or written, and a valid link stays valid. complete_admin_setup(session, token, new_password)spends the token first, withconsume_token(), as a reset link does: of two requests racing for one link, only one gets it. A link that is not a live setup link (used, expired, revoked, unknown, of another purpose) changes nothing:400TOKEN_INVALID. The link of an account that is already active is refused the same way: the spending is rolled back, and every setup link of the account is retired (token_service.retire_tokens(), lot A7b-2), with the WARNING Setup link refused and retired: the account is already active. Since lot A-42, so is the link of an account another of whose setup links was already consumed (_setup_spent_before()): the setup done through it, or the links retired. That is a link left live by a race with a new link, or by an earlier 1.3 build, and its WARNING reads Setup link refused and retired: the account was set up before. Once the account is set up, by any way, none of its links may set its password, nor make it wait for its setup again once deactivated. Both refusals come before bcrypt (The Setup Link's Lifecycle).- Otherwise, in one commit: the bcrypt hash of the new password, computed in a worker thread; the
account active; its sessions ended (
end_sessions():session_version+ 1); the link'sconsumed_by_user_idset to the account; its other setup links revoked. - The answer is the login's:
200AuthLoginResponse,show_donation_popupanduser.whats_new(What's new) included, and the session cookie of_issue_session_cookie(). The administrator is signed in.
The route is not in ALLOWED_WHEN_BLOCKED (developer's decision P16: a blocked instance stays blocked until the
subscription is paid): on a blocked instance it answers 401, like registration, and the
link keeps running out its 72 hours. The pinned list of test_instance_block.py refuses any addition.
POST /api/v1/auth/tokens/inspect takes purpose: "admin_setup": a valid setup link answers
username and expires_at, as a reset link does (Invitations).
The command line. ./dev.py user setup-link, with no argument (cmd_setup_link() in
scripts/user_cli.py): issue_setup_link() revokes the waiting administrator's setup links, then,
under the write lock that revocation took, reads «waiting» again (lot A-42,
The Setup Link's Lifecycle): an account set up in the meantime
gets no link. Otherwise it issues a generated one, 72 hours, which the command prints as
reset-link prints its link: the full address with LIBREFOLIO_PUBLIC_URL, otherwise the path and
a note. It sends no email. Without a waiting administrator, or once it was set up in the meantime,
it prints ❌ No administrator account is waiting for its setup link and exits with 1.
Set up another way (lot A7b-2, A-32). The setup link is not the only way in, and the command
line stays permissive on purpose: ./dev.py user activate and ./dev.py user reset on the waiting
administrator are how an operator sets it up without its link (activate alone leaves an active
account whose password nobody knows, until user reset or a reset link gives it
one). Whatever the way, the account's setup links are retired in the transaction of the change,
with token_service.retire_tokens(…, purpose=AccountTokenPurpose.ADMIN_SETUP): revoked and
consumed at once (Revocation). The callers:
- an activation:
user_service.set_user_active(), behinduser activate, anduser_service.update_user_status(), behindPATCH /users/{user_id}, which refuses the waiting administrator itself first (409PENDING_SETUP); - a new password:
user_service.reset_password()(user reset),user_service.complete_password_reset()(a reset link spent, one an administrator issued for the waiting account included) andPOST /auth/change-password; complete_admin_setup(), when it refuses the link of an account already active, or, since lot A-42, of an account another of whose setup links was consumed (above).
This applies to every account with a setup link, not only the waiting one. Afterwards the old
link inspects revoked (the setup page's withdrawn card) and sets nothing (400
TOKEN_INVALID), and the account is out of pending_admin_filter(), inactive or not:
pending_setup is false, PATCH /users/{user_id} reactivates it as any inactive account (no
409 PENDING_SETUP), issue_setup_link() returns None (user setup-link prints its error),
and the startup answers ignored. A reset link issued and never spent retires nothing: the account
keeps waiting, and its link still works. Since lot A-43, a demotion of the waiting administrator is
refused, and its deactivation revokes its setup links: the account keeps waiting, but the link
handed over stops working (below).
The user limit. user_usage() counts the waiting administrator (pending_admin_filter())
beside the active accounts and the live invitations, its link live or not: it holds a place from
its creation, and keeps it once active. Set up another way but still inactive, it waits no more and
holds no place, as any inactive account.
The administrator API and the Users tab (lot A7b). The account waiting for its setup is marked:
GET /usersand the answer ofPATCH /users/{user_id}carrypending_setup(AdminUserRead, defaultfalse), true for an account ofpending_admin_filter(): inactive, with at least oneadmin_setuptoken and none of them consumed — live, expired or revoked alike, an administrator or not; a retired token is consumed, so an account set up another way isfalse.registration_service.pending_admin_ids()reads it for the list,is_pending_admin()for one account. An expired link keeps the account waiting, and so does a cancelled one:./dev.py user setup-linkgives it a new one.PATCH /users/{user_id}withis_active: trueon that account, alone or withis_superuser, answers409withdetail: {error_code: "PENDING_SETUP", message}and changes nothing: nobody knows its password, and an activation would retire its setup links (above). The check comes before the user limit. Since lot A-43 a demotion is refused with the same detail, word for word:is_superuser: false, alone or withis_active: false, changes nothing either, checked right after the protection hook. The account keeps its role until its setup: its link is cancelled, or the account deleted, instead (below).- The Users tab draws the account with the badge Waiting for setup; Cancel setup link in place
of Reactivate, Remove administrator turned off with the reason
pending-setup, Delete enabled (on a protected account, all three are off with the reasonprotected); and a hint that namesdev.py user setup-link(UserRow). - No route issues a new setup link: in release 1.3 the command line does (backlog).
Cancelling the setup link (lot A-43). Deactivating the waiting administrator cancels the link
handed over: PATCH /users/{user_id} with is_active: false (the Users tab's Cancel setup
link, after a confirmation, sends {is_active: false, cancel_setup: true}, lot A-51) and
./dev.py user deactivate <username> revoke its setup links, live
or expired (user_service._end_setup_links()). Whoever holds the link can no longer set the account
up: inspected, it answers revoked, and POST /auth/setup with it 400 TOKEN_INVALID. The
account keeps waiting: pending_setup stays true, in the 200 of the PATCH too, it keeps its
place, and its reactivation stays 409 PENDING_SETUP. A new link comes from
./dev.py user setup-link, or from a new LIBREFOLIO_ADMIN_BOOTSTRAP_TOKEN at the next start; the
same token re-arms nothing, being stored already, and that start is expired, with the WARNING of
a withdrawn link rather than of an expiry (lot A-50: the latest setup link is revoked and never
consumed), its remedy unchanged:
The initial administrator's setup link was withdrawn (cancelled, or its address changed): …. The
cancellation itself logs the WARNING of
The Setup Link's Lifecycle; a second PATCH
finds no link left to revoke and changes nothing. A protected account
refuses it on the API, 409 ACCOUNT_PROTECTED, nothing changed and the link still working:
update_account() asks the hook about the cancellation (cancel) as about a deactivation or a
demotion. The command line stays above protection. The hard cancellation is the deletion, which
needs no demotion first for this account (Deleting an Account).
Deactivating any other account retires the setup links it never consumed instead, so that a stray
one can never make it wait for its setup.
A setup completed meanwhile (lot A-51). The Users tab's row can be stale: the administrator may
have spent its link since the list was loaded, or in the same millisecond. Sent with
{is_active: false} alone, the same body as a deactivation, a cancellation from a row loaded
before the setup would have deactivated the new owner. So the tab adds cancel_setup: true, which
makes the request the cancellation and nothing else: update_user_status() reads «waiting» under
SQLite's write lock, on the account read again, and an account that no longer waits answers 409
SETUP_COMPLETED (This account does not wait for its setup: nothing was changed, a sentence that also fits a
direct API call on an account that never waited; the tab, which sends the field only from a waiting row, says the
administrator completed its setup in the meantime), rolled back, with the INFO line Setup cancellation refused: the
account does not wait for its setup (user_id). The tab reloads, and the row shows the account active.
Without the field, {is_active: false} keeps its meaning, a deactivation, decided on the account as
the lock finds it: in the same-millisecond race it deactivates the administrator just set up, and
its answer is what the database holds (before lot A-51, a 200 read from the stale account,
nothing deactivated). The deletion and the command line read the account again under the lock as
well (Deleting an Account, Superusers and the User CLI).
The web page. The link opens /setup, an anonymous page that reads the token from the fragment,
inspects it with the purpose admin_setup, then spends it with POST /auth/setup from
SetupCard, and enters the app signed in:
Account Link Pages.
How the setup link is protected (stored by its hash, single use, logged once by design) is in Links in Use.
Tests: ./dev.py test services admin-bootstrap
(backend/test_scripts/test_services/test_admin_bootstrap.py, PURE, every database a private file:
the variables and their codes, issue_token(token=), every action, two engines racing for the
creation, the expiry to the microsecond, the delivery and the logs, complete_admin_setup(), the
usage, user setup-link, the startup step) and ./dev.py test api admin-setup
(backend/test_scripts/test_api/test_admin_setup_api.py: POST /auth/setup and tokens/inspect
with admin_setup; in process on private databases for every case that needs a waiting
administrator, and on the lane's server only refusals that write nothing). The administrator API's
side is UADM-060 to UADM-067 of ./dev.py test api users-admin
(backend/test_scripts/test_api/test_users_admin_api.py), in process, on a private database where
the bootstrap itself creates the waiting administrator: pending_setup on each state of a setup
link, the 409 PENDING_SETUP, and what that refusal must not reach. Lot A7b-2 adds A32-001 to
A32-007 and A33-001 to A33-003 to admin-bootstrap (set up another way, the refused link of an
active account, a new address in the variables), SETUP-014 and SETUP-015 to admin-setup,
UADM-068 to UADM-071 to users-admin, UPROF-003 to UPROF-005 of
./dev.py test services user-profile (a new address through update_profile()), and contract 9 of
./dev.py test services account-tokens (retire_tokens()). Lots A-42 and A-43 add A42-001 to
A42-006 and A43-001 to A43-005 to admin-bootstrap (the issue and the re-arm under the write lock,
a stray link refused at its spending; the cancellation revoking, another account's deactivation
retiring, user demote refused), SETUP-016 to SETUP-018 to admin-setup (what leaves the account
waiting, user deactivate cancelling its link, the stray link of an account set up before) and
UADM-072 to UADM-079 to users-admin (the demotion refused, the cancellation through the PATCH,
another administrator's stray link retired, the direct deletion and the protection hook before it,
the cancellation of a protected waiting administrator refused, its link still working). Lot A-50
adds A50-001 to A50-004 to admin-bootstrap: the start after a cancellation, from the Users tab or
from user deactivate, and the starts after the one that wrote a new address, log the WARNING of a
withdrawn link; a link that ran out still logs the expiry, even when an earlier one was revoked by a
re-arm, as the latest link decides. Lot A-51 adds A51-001 to A51-006 to users-admin
(TestTheSetupCompletedWhileTheUsersTabActs: a cancellation from a stale list or in the setup's
window answers SETUP_COMPLETED and changes nothing, a cancellation of an account still waiting
works as before, cancel_setup without is_active: false is 422, a plain deactivation in that
window deactivates the administrator just set up and says so, a deletion in it answers
DEMOTE_FIRST) and A51-007 and A51-008 to admin-bootstrap (user deactivate and user demote
of the only administrator of a new instance while its setup completes, both refused as the last
active administrator). Lot H-61 adds H61-001 to H61-018 to admin-bootstrap, for
admin_setup_status(): the two types and the signature; none without any setup
link, the tokens of the other purposes counting for nothing, and once the administrator was
deleted; pending after the creation, until the expiry to the microsecond; done through the
link, another way, and through the older of two links; expired once the link was withdrawn; the
link that replaced another; of two links, a consumed one first, otherwise the newer; the order by
created_at then id; the links of every account; nothing written in any state; the clock without
now. Every test name holds setup_status, so ./dev.py test services admin-bootstrap setup_status
runs them alone.