The last-administrator guard counts under a lock; GET /users keeps tiers for administrators

Two items from the security review (#42).

The guard was a count followed by a write with nothing in between, so two
requests in flight at once ("demote A", "demote B") each counted the other
and both passed, leaving no active administrator. It now locks the active
administrators' rows first (FOR NO KEY UPDATE, ordered by id) and counts
after: the second request waits, sees what the first committed, and is
refused. NO KEY, so a foreign-key insert that names an administrator (a
session, an audit row, in any module) does not wait on it.

GET /users answers any credential, a read-only app token included, and
every row carried is_admin and the per-module roles: the list of whose
account is worth taking over. An administrator still gets the whole
standing (UserOut). Everybody else gets UserBriefOut (id, email, full_name,
is_active); the tiers are absent rather than blanked. The console reads
this route only from administrator screens, so nothing there changes.

Tests added (unit and integration). Not run here: no dredd-core install and
no database on this machine; the files parse and the new source assertions
hold.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Piotr Chojnacki
2026-11-18 11:20:05 +01:00
co-authored by Claude Fable 5.2
parent 52e95a9d3a
commit 98ff301912
6 changed files with 116 additions and 6 deletions
+1 -1
View File
@@ -76,7 +76,7 @@ changes when the family shares a host.
| Who | Endpoints (under `/api/v1`) |
|---|---|
| anyone | `GET /health` · `POST /auth/login` · `POST /auth/logout` |
| any signed-in user | `GET /auth/me` · `GET /launcher` · `GET /marketplace?q=&category=` · `GET /marketplace/{slug}` · `POST /marketplace/{slug}/requests` · `GET /me/access-requests` · `GET /config` · `GET /users` · `POST /me/password` · `GET/POST /me/tokens` · `DELETE /me/tokens/{id}` · `POST /me/modules/{slug}/tokens` (an app token for a module — minting lives only here, because no module holds `INSERT` on `session`) · the org tree, filtered to units you can read: `GET /tree/containers` · `GET /nodes/{id}/children` |
| any signed-in user | `GET /auth/me` · `GET /launcher` · `GET /marketplace?q=&category=` · `GET /marketplace/{slug}` · `POST /marketplace/{slug}/requests` · `GET /me/access-requests` · `GET /config` · `GET /users` (names and email addresses; who holds which tier is told to an administrator only) · `POST /me/password` · `GET/POST /me/tokens` · `DELETE /me/tokens/{id}` · `POST /me/modules/{slug}/tokens` (an app token for a module — minting lives only here, because no module holds `INSERT` on `session`) · the org tree, filtered to units you can read: `GET /tree/containers` · `GET /nodes/{id}/children` |
| administrators | `POST /users` · `POST /users/{id}/deactivate\|reactivate` · `POST /users/{id}/administrator` (the platform-wide tier; refuses to remove the last one) · `GET/POST /admin/modules` · `GET/PATCH/DELETE /admin/modules/{slug}` · `GET/POST /admin/modules/{slug}/moderators` · `DELETE /admin/modules/{slug}/moderators/{user_id}` · `POST /admin/modules/{slug}/assignments` · `DELETE /admin/modules/{slug}/assignments/{id}` · `POST /admin/modules/{slug}/probe` · `GET /admin/access-requests?status=` · `POST /admin/access-requests/{id}/approve\|decline` · `GET/PUT /admin/settings` · `GET /admin/overview` · `GET /admin/audit?action=` |
| unit managers (and administrators) | `POST /nodes` (a top-level workspace: administrators only) · `DELETE /nodes/{id}` · `GET/PUT /nodes/{id}/grants` · `DELETE /nodes/{id}/grants/{user_id}` |
+22 -5
View File
@@ -34,6 +34,7 @@ from ..schemas import (
ModuleTokenIn,
PasswordChangeIn,
PasswordResetIn,
UserBriefOut,
UserCreateIn,
UserOut,
UserProfileIn,
@@ -54,15 +55,31 @@ def _user_out(u: AppUser, modules: dict[str, str] | None = None) -> dict:
"modules": modules or {}}
@router.get("/users", response_model=list[UserOut])
def _user_brief(u: AppUser) -> UserBriefOut:
"""What anybody signed in may know about an account: who it is, and whether it can be picked."""
return UserBriefOut(id=str(u.id), email=u.email, full_name=u.full_name, is_active=u.is_active)
@router.get("/users", response_model=list[UserOut] | list[UserBriefOut])
def list_users(db: Session = Depends(get_db),
_: AppUser = Depends(get_current_user)) -> list[dict]:
"""Every signed-in user may list users: the console needs names to render "assigned to"
pickers, and an email address inside the instance is not the secret worth hiding here."""
user: AppUser = Depends(get_current_user)) -> list[UserOut] | list[UserBriefOut]:
"""Every signed-in user may list users: a picker needs names, and an email address inside the
instance is not the secret worth hiding here.
**Who holds which tier is another matter, and only an administrator is told.** `is_admin` and
the per-module roles are the map of whose account is worth taking over, and this route answers
any credential — an ordinary account, a read-only app token. They used to come along because
one helper built every row. So an administrator gets the whole standing (`UserOut`, what the
Users screen draws) and everybody else gets `UserBriefOut`: the fields a picker uses and nothing
about tiers. Absent, not `false` or empty: a row that said `is_admin: false` about an
administrator would be a lie, and a client must not be able to mistake "not told" for "none".
"""
users = auth_service.list_users(db)
if not user.is_admin:
return [_user_brief(u) for u in users]
# One query for the whole page, not one per row — see services/moderation.py.
standing = moderation.module_roles_by_user(db, [u.id for u in users])
return [_user_out(u, standing.get(u.id)) for u in users]
return [UserOut(**_user_out(u, standing.get(u.id))) for u in users]
@router.post("/users", response_model=UserOut, status_code=201)
+10
View File
@@ -74,6 +74,16 @@ class UserOut(BaseModel):
modules: dict[str, str] = {}
class UserBriefOut(BaseModel):
"""A person as anybody signed in may see them in `GET /users`: enough to pick somebody, and
nothing about what they may do. The tiers (`is_admin`, `modules`) are for administrators only
and are left out here rather than blanked — see `routers/users.list_users`."""
id: str
email: str
full_name: str
is_active: bool
class LoginOut(BaseModel):
"""The reply to a sign-in: who signed in, and NOT the session token. That lives in the HttpOnly
cookie only, where no page script can read it (`routers/auth.py`). `response_model` filters the
+27
View File
@@ -57,6 +57,28 @@ def count_administrators(db: DbSession, *, excluding: uuid.UUID | None = None) -
return db.scalar(stmt) or 0
def _lock_administrators(db: DbSession) -> None:
"""Hold every usable administrator's row until this transaction ends, so that the count that
follows is still true when the change is written.
Without it the guard is a check followed by a write with nothing in between: "demote A" and
"demote B", in flight at once, each count the other as still there, both pass, and the platform
is left with nobody — the very state the guard is for, reached by two clicks landing together.
With it the second request waits here; when the first commits, PostgreSQL re-checks the rows it
waited for, and the count below (a new statement) sees what was committed, so the second one is
refused.
`FOR NO KEY UPDATE`, not `FOR UPDATE`: every row another table writes with a foreign key to
`app_user` — a session, an audit row, in any module — takes a key-share lock on the person, and
`FOR UPDATE` would make all of those wait on an administrator's row. The weaker lock still
excludes itself and every `UPDATE` of the row, which is all this needs. Ordered by id, so two
requests always take the rows in the same order and cannot deadlock each other.
"""
db.execute(select(AppUser.id)
.where(AppUser.is_admin.is_(True), AppUser.is_active.is_(True))
.order_by(AppUser.id).with_for_update(key_share=True)).all()
def _assert_not_last_administrator(db: DbSession, user: AppUser) -> None:
"""Refuse a change that would leave the platform with no administrator who can sign in.
@@ -64,9 +86,14 @@ def _assert_not_last_administrator(db: DbSession, user: AppUser) -> None:
administrator is perfectly ordinary while somebody else still holds the tier. What is refused is
the *last* one, and the message says what to do instead, because a person who hits this guard
has a job to finish and a bare 409 does not help them finish it.
Counted under a lock on the administrators' rows (`_lock_administrators`): the caller writes
straight after this returns, in the same transaction, and two such changes must not each pass on
a count the other is about to make false.
"""
if not user.is_admin or not user.is_active:
return
_lock_administrators(db)
if count_administrators(db, excluding=user.id) == 0:
raise ConflictError(
"This is the last administrator. Make someone else an administrator first: with "
+39
View File
@@ -390,6 +390,31 @@ class TestTheTwoTiers:
out = UserOut(id="x", email="a@b.test", full_name="A", is_admin=False, is_active=True)
assert out.modules == {} # always a mapping, never absent
def test_only_an_administrator_is_told_who_holds_which_tier(self):
"""`GET /users` answers any credential, a read-only app token included, and the tiers are
the map of whose account is worth taking over. Everybody else gets a row with no tier in
it at all: absent, never `false` or empty, which would be a lie about an administrator."""
from pydantic import TypeAdapter
from app.schemas import UserBriefOut, UserOut
assert set(UserBriefOut.model_fields) == {"id", "email", "full_name", "is_active"}
# The route's own response type, fed what the handler returns for somebody who is not an
# administrator: nothing in the reply may put a tier back.
reply = TypeAdapter(list[UserOut] | list[UserBriefOut])
brief = UserBriefOut(id="x", email="a@b.test", full_name="A", is_active=True)
assert reply.dump_python(reply.validate_python([brief])) == [
{"id": "x", "email": "a@b.test", "full_name": "A", "is_active": True}]
full = UserOut(id="x", email="a@b.test", full_name="A", is_admin=True, is_active=True,
modules={"galena": "moderator"})
assert reply.dump_python(reply.validate_python([full]))[0]["modules"] == {
"galena": "moderator"}
source = (BACKEND / "app" / "routers" / "users.py").read_text(encoding="utf-8")
body = source.split("def list_users", 1)[1].split("@router.post", 1)[0]
assert "response_model=list[UserOut] | list[UserBriefOut]" in source
assert body.index("if not user.is_admin") < body.index("module_roles_by_user")
def test_a_new_account_gets_no_tier_and_no_module_by_default(self):
"""The default is an account that can sign in and open nothing. Before `module_permission`
there was no way to express that: everybody could open everything."""
@@ -478,6 +503,20 @@ class TestTheLastAdministratorGuard:
body = source.split("def count_administrators", 1)[1].split("def _assert", 1)[0]
assert "is_active.is_(True)" in body
def test_the_count_is_taken_under_a_lock_on_the_administrators(self):
"""A check followed by a write, with nothing in between, is passed by two requests at once:
"demote A" and "demote B" each count the other and both go through. So the guard locks the
administrators' rows first and counts after — FOR NO KEY UPDATE (a plain FOR UPDATE would
make every foreign-key insert that names an administrator wait), in a fixed order."""
source = (BACKEND / "app" / "services" / "accounts.py").read_text(encoding="utf-8")
lock = source.split("def _lock_administrators", 1)[1].split("def _assert", 1)[0]
assert "with_for_update(key_share=True)" in lock
assert "order_by(AppUser.id)" in lock
assert "is_admin.is_(True)" in lock and "is_active.is_(True)" in lock
guard = source.split("def _assert_not_last_administrator", 1)[1].split(
"def set_administrator", 1)[0]
assert guard.index("_lock_administrators(db)") < guard.index("count_administrators(db")
def test_the_routers_do_not_reimplement_it(self):
"""Layering: routers never build SQL, and a second copy of a guard is a guard that will
disagree with the first one."""
+17
View File
@@ -98,6 +98,23 @@ def test_admin_endpoints_refuse_ordinary_users(client, make_user):
assert r.status_code == 403, (path, r.status_code)
def test_the_user_list_tells_only_an_administrator_who_holds_which_tier(admin_client, client,
make_user):
"""Anybody signed in may list people (a picker needs names). Who is an administrator and who
may open which module is told to an administrator only: for everybody else those fields are
absent, on every row, their own and the administrators' included."""
alice = make_user("brief")
rows = client.get("/api/v1/users", headers=bearer(alice["token"]))
assert rows.status_code == 200, rows.text
assert rows.json() and all(set(row) == {"id", "email", "full_name", "is_active"}
for row in rows.json())
assert any(row["id"] == alice["id"] for row in rows.json())
full = admin_client.get("/api/v1/users").json()
assert all({"is_admin", "modules"} <= set(row) for row in full)
assert any(row["is_admin"] for row in full)
# ── people: the way back in ───────────────────────────────────────────────────
# A forgotten password had no answer on this platform: `POST /me/password` needs the password that
# is missing, a module's own reset 409s because no module may write `app_user`, and there is no