T12.1: CR-020 bulk user endpoints

POST /api/auth/bulk-users/{active,role,projects,delete} take a list of
user ids (max 500) and run each row through the same guards and audit
as the single-user route: the rules now live once, in guard_target and
apply_user_{active,role,delete,projects}, which the single-user routes
call too.

- A refused row is reported with its reason; the rest still run; the
  response counts ok / unchanged / failed. Never a blanket success.
- The caller's own account is refused only on its own row.
- One AuditLog row per changed account, same action and shape as the
  single route. A row already in the requested state is 'unchanged'
  and writes no audit row.
- Project assignment is add/remove to ONE project with a per-project
  role (confirmed 2026-10-06); roles on the user's other projects are
  carried over as stored.
- Routes sit under /api/auth/bulk-users/ because /api/auth/users/bulk/
  would match {user_id}='bulk'.

New tests/bulk_users_check.py (no browser): 47/47. Against main: the
7 single-route checks pass, every bulk check fails.
Single-user routes compared before/after on 16 calls (200/400/403/404):
identical responses, audit rows and memberships. Smoke test 27/27.
This commit is contained in:
2026-10-06 10:57:48 -07:00
parent 286e629782
commit 0e79e17a57
2 changed files with 519 additions and 58 deletions

View File

@@ -1013,16 +1013,100 @@ def create_user(body: NewUserIn, actor: models.User = Depends(require_user_manag
return directory_entry(db, u, actor)
# ── One account-level change, used by the single-user routes AND the bulk routes ──
# CR-020 (T12.1): a bulk action is the single-user action, once per row. So each
# rule lives in exactly one function below, and both kinds of route call it: a
# bulk request cannot reach further than a one-at-a-time request, because there
# is no second copy of the rules for it to reach through. Every function checks
# all of its guards BEFORE it changes anything, so a row that is refused leaves
# nothing half-written, and writes its AuditLog row the way the single route
# always has. None of them commits; the route owns the transaction.
def guard_target(db: Session, actor: "models.User", u: "models.User") -> None:
"""The two checks every account change starts with: may the caller see this
account (404 if not, so existence does not leak), and may they change it."""
require_see_user(db, actor, u)
require_manage_user(db, actor, u)
def apply_user_active(db: Session, actor: "models.User", u: "models.User", is_active: bool) -> None:
if u.id == actor.id and not is_active:
raise HTTPException(status_code=400, detail="You cannot disable your own account")
u.is_active = is_active
log_event(db, actor, "user_enabled" if is_active else "user_disabled", "user", u.id,
summary=u.username, detail={"is_active": bool(is_active)})
def apply_user_role(db: Session, actor: "models.User", u: "models.User", role: str) -> None:
"""The role guards: never your own role, never the last active admin. The
grantable-roles check is the caller's, made once per request before this."""
if u.id == actor.id:
raise HTTPException(status_code=400, detail="You cannot change your own role")
if auth.is_admin(u) and role != auth.ROLE_ADMIN:
other_admins = db.scalars(
select(models.User.id).where(
(models.User.role == auth.ROLE_ADMIN)
& (models.User.id != u.id)
& (models.User.is_active.is_(True))
)
).all()
if not other_admins:
raise HTTPException(status_code=400, detail="Can't remove the last admin account")
old_role = u.role
u.role = role
detail = {"from": old_role, "to": role}
# Promoting someone to admin retires their default-member flag: an admin already
# reaches every project, so the flag would do nothing except sit there invisibly
# (the console shows admins no controls) and come back to life the day they are
# demoted. Same reasoning as clearing the role in set_user_auto_add.
if role == auth.ROLE_ADMIN and (u.auto_add_projects or u.auto_add_role):
u.auto_add_projects = False
u.auto_add_role = ""
detail["auto_add_cleared"] = True
log_event(db, actor, "role_changed", "user", u.id, summary=u.username, detail=detail)
def apply_user_delete(db: Session, actor: "models.User", u: "models.User") -> None:
if u.id == actor.id:
raise HTTPException(status_code=400, detail="You cannot delete your own account")
log_event(db, actor, "user_deleted", "user", u.id, summary=u.username, detail={"role": u.role})
db.delete(u)
def apply_user_projects(db: Session, actor: "models.User", u: "models.User",
managed: Optional[set], valid: set, roles: dict) -> None:
"""Replace the caller's slice of `u`'s memberships with `valid`, each carrying
its role from `roles` ('' = inherit). `valid` must already be checked to exist
and to sit inside `managed`."""
# Rebuild only the rows this caller owns. Scoping the DELETE is the whole of the
# "leave other jobs alone" guarantee — get it wrong and a super user's save
# silently revokes access everywhere else.
doomed = delete(models.ProjectMember).where(models.ProjectMember.user_id == u.id)
if managed is not None:
# in_() on an empty set is a valid always-false predicate, so a caller who
# administers nothing deletes nothing (require_manage_user already refused them).
doomed = doomed.where(models.ProjectMember.project_id.in_(managed))
db.execute(doomed)
for pid in valid:
db.add(models.ProjectMember(id=gen_id("pm"), user_id=u.id, project_id=pid,
role=roles.get(pid, "")))
log_event(db, actor, "project_access_changed", "user", u.id, summary=u.username,
detail={"projects": len(valid),
"scope": "all" if managed is None else "managed",
"overrides": {p: r for p, r in roles.items() if p in valid}})
def project_scoped_grantable(actor: "models.User") -> tuple:
"""Per-project roles `actor` may hand out. Only an app admin can make someone a
super user on a project. user_scope and get_user_projects still spell the same
rule inline for the console; left as they are to keep this diff to CR-020."""
return auth.PROJECT_SCOPED_ROLES if auth.is_admin(actor) else (auth.ROLE_PROJECT_ADMIN, auth.ROLE_PROJECT_USER)
@app.post("/api/auth/users/{user_id}/active")
def set_user_active(user_id: str, body: ActiveIn, actor: models.User = Depends(require_user_manager), db: Session = Depends(get_db)):
u = load_target_user(db, user_id)
require_see_user(db, actor, u)
require_manage_user(db, actor, u)
if u.id == actor.id and not body.is_active:
raise HTTPException(status_code=400, detail="You cannot disable your own account")
u.is_active = body.is_active
log_event(db, actor, "user_enabled" if body.is_active else "user_disabled", "user", u.id,
summary=u.username, detail={"is_active": bool(body.is_active)})
guard_target(db, actor, u)
apply_user_active(db, actor, u, body.is_active)
db.commit()
return directory_entry(db, u, actor)
@@ -1039,32 +1123,8 @@ def set_user_role(user_id: str, body: RoleIn, actor: models.User = Depends(requi
if body.role not in allowed:
raise HTTPException(status_code=400, detail=f"role must be one of {', '.join(allowed)}")
u = load_target_user(db, user_id)
require_see_user(db, actor, u)
require_manage_user(db, actor, u)
if u.id == actor.id:
raise HTTPException(status_code=400, detail="You cannot change your own role")
if auth.is_admin(u) and body.role != auth.ROLE_ADMIN:
other_admins = db.scalars(
select(models.User.id).where(
(models.User.role == auth.ROLE_ADMIN)
& (models.User.id != u.id)
& (models.User.is_active.is_(True))
)
).all()
if not other_admins:
raise HTTPException(status_code=400, detail="Can't remove the last admin account")
old_role = u.role
u.role = body.role
detail = {"from": old_role, "to": body.role}
# Promoting someone to admin retires their default-member flag: an admin already
# reaches every project, so the flag would do nothing except sit there invisibly
# (the console shows admins no controls) and come back to life the day they are
# demoted. Same reasoning as clearing the role in set_user_auto_add.
if body.role == auth.ROLE_ADMIN and (u.auto_add_projects or u.auto_add_role):
u.auto_add_projects = False
u.auto_add_role = ""
detail["auto_add_cleared"] = True
log_event(db, actor, "role_changed", "user", u.id, summary=u.username, detail=detail)
guard_target(db, actor, u)
apply_user_role(db, actor, u, body.role)
db.commit()
db.refresh(u)
return directory_entry(db, u, actor)
@@ -1121,12 +1181,8 @@ def set_user_auto_add(user_id: str, body: AutoAddIn, admin: models.User = Depend
@app.delete("/api/auth/users/{user_id}")
def delete_user(user_id: str, actor: models.User = Depends(require_user_manager), db: Session = Depends(get_db)):
u = load_target_user(db, user_id)
require_see_user(db, actor, u)
require_manage_user(db, actor, u)
if u.id == actor.id:
raise HTTPException(status_code=400, detail="You cannot delete your own account")
log_event(db, actor, "user_deleted", "user", u.id, summary=u.username, detail={"role": u.role})
db.delete(u)
guard_target(db, actor, u)
apply_user_delete(db, actor, u)
db.commit()
return {"deleted": user_id}
@@ -1179,8 +1235,7 @@ def set_user_projects(user_id: str, body: ProjectAssignIn, actor: models.User =
exactly as they were, because a payload that simply omits them would otherwise cut
someone off from a job the caller can't even see."""
u = load_target_user(db, user_id)
require_see_user(db, actor, u)
require_manage_user(db, actor, u)
guard_target(db, actor, u)
requested = [p for p in dict.fromkeys(body.project_ids) if p]
for pid in requested:
check_id(pid)
@@ -1193,28 +1248,156 @@ def set_user_projects(user_id: str, body: ProjectAssignIn, actor: models.User =
# A super user may hand out the project-scoped roles below their own; only an app
# admin can make someone a super user on a project. Anything unrecognised falls
# back to inheriting the account's own role.
allowed = auth.PROJECT_SCOPED_ROLES if auth.is_admin(actor) else (auth.ROLE_PROJECT_ADMIN, auth.ROLE_PROJECT_USER)
allowed = project_scoped_grantable(actor)
roles = {pid: r for pid, r in (body.roles or {}).items() if r in allowed}
# Rebuild only the rows this caller owns. Scoping the DELETE is the whole of the
# "leave other jobs alone" guarantee — get it wrong and a super user's save
# silently revokes access everywhere else.
doomed = delete(models.ProjectMember).where(models.ProjectMember.user_id == user_id)
if managed is not None:
# in_() on an empty set is a valid always-false predicate, so a caller who
# administers nothing deletes nothing (require_manage_user already refused them).
doomed = doomed.where(models.ProjectMember.project_id.in_(managed))
db.execute(doomed)
for pid in valid:
db.add(models.ProjectMember(id=gen_id("pm"), user_id=user_id, project_id=pid,
role=roles.get(pid, "")))
log_event(db, actor, "project_access_changed", "user", u.id, summary=u.username,
detail={"projects": len(valid),
"scope": "all" if managed is None else "managed",
"overrides": {p: r for p, r in roles.items() if p in valid}})
apply_user_projects(db, actor, u, managed, valid, roles)
db.commit()
return {"assigned": sorted(valid), "roles": {p: roles.get(p, "") for p in sorted(valid)}}
# ── Bulk user administration — CR-020 (T12.1) ─────────────────────────────────
# Four actions over a list of accounts: activate/disable, permissions role,
# project add/remove (with the per-project role), delete. Each row runs exactly
# the guards and the audit of the single-user route, through the same apply_*
# function above. Rules, decided 2026-09-17 and confirmed 2026-10-06:
# * a row that is refused is reported with its reason and the rest still run;
# a batch is never reported as a success when part of it failed;
# * one AuditLog row per changed account, the same as the single route writes -
# never one opaque "bulk" entry;
# * the caller's own account is refused only on its own row (disable, demote,
# delete), never by failing the whole batch;
# * project assignment adds to or removes from ONE project; it never replaces a
# user's whole project list.
# A row already in the requested state is reported "unchanged" and writes no
# audit row: nothing changed, so there is nothing to audit.
#
# The routes live under /api/auth/bulk-users/ rather than /api/auth/users/bulk/,
# because POST /api/auth/users/{user_id}/active would otherwise match "bulk" as
# a user id.
BULK_MAX_USERS = 500
class BulkUsersIn(BaseModel):
user_ids: list[str] = Field(default_factory=list, max_length=BULK_MAX_USERS)
class BulkActiveIn(BulkUsersIn):
is_active: bool
class BulkRoleIn(BulkUsersIn):
role: str
class BulkProjectIn(BulkUsersIn):
project_id: str
op: str # "add" | "remove"
role: str = "" # per-project role on add; '' = inherit the account's own
def run_bulk(db: Session, actor: "models.User", user_ids: list[str], action: str, apply) -> dict:
"""Run `apply(u)` once per distinct id, in the order given. `apply` returns
"ok" or "unchanged", or raises HTTPException with the reason the single-user
route would have given. The flush after every row matters: the session does
not autoflush, and a later row's guard (the last-admin count, for one) has to
see what an earlier row already changed."""
results = []
for uid in dict.fromkeys(i for i in user_ids if i):
row = {"user_id": uid, "username": "", "status": "", "reason": ""}
try:
check_id(uid)
u = load_target_user(db, uid)
row["username"] = u.username
guard_target(db, actor, u)
row["status"] = apply(u)
db.flush()
except HTTPException as exc:
row["status"] = "failed"
row["reason"] = exc.detail if isinstance(exc.detail, str) else str(exc.detail)
results.append(row)
db.commit()
counts = {s: sum(1 for r in results if r["status"] == s) for s in ("ok", "unchanged", "failed")}
return {"action": action, "requested": len(results), **counts, "results": results}
@app.post("/api/auth/bulk-users/active")
def bulk_set_active(body: BulkActiveIn, actor: models.User = Depends(require_user_manager), db: Session = Depends(get_db)):
def apply(u):
if bool(u.is_active) == bool(body.is_active):
return "unchanged"
apply_user_active(db, actor, u, body.is_active)
return "ok"
return run_bulk(db, actor, body.user_ids, "enable" if body.is_active else "disable", apply)
@app.post("/api/auth/bulk-users/role")
def bulk_set_role(body: BulkRoleIn, actor: models.User = Depends(require_user_manager), db: Session = Depends(get_db)):
allowed = grantable_roles(actor)
if body.role not in allowed:
raise HTTPException(status_code=400, detail=f"role must be one of {', '.join(allowed)}")
def apply(u):
# Compared as stored: a legacy 'user' row moved to 'project_user' is a real
# change of the stored value, so it is applied and audited, as one at a time.
if u.role == body.role:
return "unchanged"
apply_user_role(db, actor, u, body.role)
return "ok"
return run_bulk(db, actor, body.user_ids, "role", apply)
@app.post("/api/auth/bulk-users/projects")
def bulk_set_project(body: BulkProjectIn, actor: models.User = Depends(require_user_manager), db: Session = Depends(get_db)):
"""Add every listed account to one project (with a per-project role), or remove
them from it. Implemented as the single route's replace of the caller's slice,
computed per user, so the audit row is the same shape the dialog writes."""
if body.op not in ("add", "remove"):
raise HTTPException(status_code=400, detail="op must be 'add' or 'remove'")
check_id(body.project_id)
if not db.get(models.Project, body.project_id):
raise HTTPException(status_code=404, detail="Project not found")
managed = managed_project_ids(db, actor)
if managed is not None and body.project_id not in managed:
raise HTTPException(status_code=403, detail="You don't administer the users of that project")
role = (body.role or "").strip()
if body.op == "add" and role and role not in project_scoped_grantable(actor):
raise HTTPException(
status_code=400,
detail=f"role must be '' (inherit) or one of {', '.join(project_scoped_grantable(actor))}")
pid = body.project_id
def apply(u):
mine = [m for m in db.scalars(select(models.ProjectMember)
.where(models.ProjectMember.user_id == u.id)).all()
if managed is None or m.project_id in managed]
current = {m.project_id: (m.role or "") for m in mine}
if body.op == "add":
if current.get(pid) == role:
return "unchanged"
current[pid] = role
else:
if pid not in current:
return "unchanged"
current.pop(pid)
# Roles on the caller's OTHER projects are carried over exactly as stored -
# adding someone to one job must never reset their role on another.
apply_user_projects(db, actor, u, managed, set(current),
{p: r for p, r in current.items() if r})
return "ok"
return run_bulk(db, actor, body.user_ids, "project_" + body.op, apply)
@app.post("/api/auth/bulk-users/delete")
def bulk_delete(body: BulkUsersIn, actor: models.User = Depends(require_user_manager), db: Session = Depends(get_db)):
"""Hard delete, the same as DELETE /api/auth/users/{id} (decided 2026-09-17:
no soft delete invented for the bulk case). The console asks for the typed
word DELETE first; the server's guard is the per-row rules, as for one."""
def apply(u):
apply_user_delete(db, actor, u)
return "ok"
return run_bulk(db, actor, body.user_ids, "delete", apply)
# ── Projects ─────────────────────────────────────────────────────────────────
@app.post("/api/projects")
def upsert_project(body: ProjectIn, user: models.User = Depends(auth.get_current_user), db: Session = Depends(get_db)):