POST /api/auth/bulk-users/resolve reads a list of usernames (first
column; comma, semicolon or tab; header skipped) and answers line by
line, the CR-005 validate-and-report pattern. A line is rejected, with
its number and reason, when it names nobody the caller can see ('User
not found', as everywhere else), an account they may not change (the
single route's own reason), their own account, or a username already
listed (duplicate of line N). An email address resolves only when
exactly one account has it. Nothing is changed by this route.
The console's 'Select from CSV' turns the accepted accounts into the
ordinary selection (filter reset so every selected row is visible) and
lists every rejected line. The action, confirm and per-row report are
the checkbox ones, through the same T12.1 routes, which re-check each
row: a CSV cannot reach an account a checkbox could not.
Usernames only, action in the toolbar (decided 2026-10-06). Files over
1 MB are refused before upload; FileReader fallback for browsers
without Blob.text().
bulk_users_check.py: 61/61. DOM harness: 40/40.
327 lines
18 KiB
Python
327 lines
18 KiB
Python
#!/usr/bin/env python3
|
|
"""CR-020 (wave 12): bulk user administration, server side.
|
|
|
|
python tests/bulk_users_check.py
|
|
|
|
Self-contained and needs NO browser: a throwaway SQLite database in a temp
|
|
folder, the API driven in-process with FastAPI's TestClient, everything deleted
|
|
afterward. Your real wpsuite.db is never touched.
|
|
|
|
What it proves is the wave's own exit criteria, measured on the server, where
|
|
they are enforced:
|
|
- every bulk action works on a list, row by row, with the single-user rules;
|
|
- the caller's own account is refused on its own row, never the whole batch;
|
|
- a super user's batch cannot reach an account or project outside their scope;
|
|
- one AuditLog row per changed account, the same shape the single route writes;
|
|
- a partial failure is reported row by row, never as a clean success;
|
|
- project add/remove never touches the user's other projects or their roles;
|
|
- the single-user routes, now built on the same functions, behave as before.
|
|
|
|
Exit codes: 0 all passed, 1 a check failed, 2 the run could not start.
|
|
"""
|
|
import os
|
|
import shutil
|
|
import sys
|
|
import tempfile
|
|
import warnings
|
|
|
|
warnings.filterwarnings("ignore")
|
|
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
TMP = tempfile.mkdtemp(prefix="wp-bulk-users-check-")
|
|
os.environ["DATABASE_URL"] = "sqlite:///" + os.path.join(TMP, "bulk.db").replace("\\", "/")
|
|
os.environ["AUTH_SECRET_KEY"] = "bulk-users-check-key-bulk-users-check-0000"
|
|
os.environ.pop("WP_OKTA_FAKE_DIRECTORY", None)
|
|
sys.path.insert(0, ROOT)
|
|
|
|
try:
|
|
from fastapi.testclient import TestClient
|
|
from sqlalchemy import select
|
|
from server import app as A, auth, models
|
|
from server.db import SessionLocal
|
|
except Exception as exc: # noqa: BLE001
|
|
print("could not start:", exc)
|
|
sys.exit(2)
|
|
|
|
RESULTS = []
|
|
|
|
|
|
def check(name, ok, detail=""):
|
|
RESULTS.append(bool(ok))
|
|
print(f" {'PASS' if ok else 'FAIL'} {name}" + (f" ({detail})" if detail and not ok else ""))
|
|
|
|
|
|
db = SessionLocal()
|
|
|
|
|
|
def account(uid, role="project_user"):
|
|
u = models.User(id=uid, username=uid[5:], role=role, email=uid[5:] + "@example.test")
|
|
db.add(u)
|
|
db.commit()
|
|
return u
|
|
|
|
|
|
def member(uid, pid, role=""):
|
|
db.add(models.ProjectMember(id=f"pm_{uid}_{pid}", user_id=uid, project_id=pid, role=role))
|
|
db.commit()
|
|
|
|
|
|
def client(user):
|
|
c = TestClient(A.app, base_url="http://127.0.0.1", raise_server_exceptions=False)
|
|
c.cookies.set(auth.COOKIE_NAME, auth.create_token(user))
|
|
return c
|
|
|
|
|
|
def fresh():
|
|
s = SessionLocal()
|
|
s.expire_all()
|
|
return s
|
|
|
|
|
|
def audit(action, entity_id=None):
|
|
s = fresh()
|
|
q = select(models.AuditLog).where(models.AuditLog.action == action)
|
|
if entity_id:
|
|
q = q.where(models.AuditLog.entity_id == entity_id)
|
|
return s.scalars(q.order_by(models.AuditLog.at)).all()
|
|
|
|
|
|
def roles_of(uid):
|
|
s = fresh()
|
|
return {m.project_id: (m.role or "") for m in
|
|
s.scalars(select(models.ProjectMember).where(models.ProjectMember.user_id == uid))}
|
|
|
|
|
|
def by_user(resp):
|
|
return {r["user_id"]: r for r in resp.json().get("results", [])}
|
|
|
|
|
|
# ── fixture ──────────────────────────────────────────────────────────────────
|
|
admin = account("user_admin", "admin")
|
|
admin2 = account("user_admin2", "admin")
|
|
superu = account("user_super") # super user on proj1 and proj4 by membership
|
|
pu = account("user_pu") # plain project user: manages nobody
|
|
for n in range(1, 10):
|
|
account(f"user_u{n}")
|
|
for pid in ("proj1", "proj2", "proj3", "proj4"):
|
|
db.add(models.Project(id=pid, name=pid))
|
|
db.commit()
|
|
member("user_super", "proj1", "project_super_user")
|
|
member("user_super", "proj4", "project_super_user")
|
|
member("user_pu", "proj1")
|
|
for n in (1, 2, 3, 4, 5):
|
|
member(f"user_u{n}", "proj1")
|
|
member("user_u6", "proj1"); member("user_u6", "proj2", "project_admin") # partly outside super's scope
|
|
member("user_u7", "proj2") # wholly outside it
|
|
member("user_u8", "proj1"); member("user_u8", "proj4", "project_super_user") # a role super may not grant
|
|
ca, cs, cp = client(admin), client(superu), client(pu)
|
|
|
|
|
|
def single_routes():
|
|
print("\n0. the single-user routes still behave as before (now on the shared functions)")
|
|
r = ca.post("/api/auth/users/user_admin/role", json={"role": "project_user"})
|
|
check("changing your own role: 400, same words", r.status_code == 400 and "own role" in r.json()["detail"])
|
|
r = ca.post("/api/auth/users/user_admin/active", json={"is_active": False})
|
|
check("disabling yourself: 400, same words", r.status_code == 400 and "disable your own" in r.json()["detail"])
|
|
r = ca.delete("/api/auth/users/user_admin")
|
|
check("deleting yourself: 400, same words", r.status_code == 400 and "delete your own" in r.json()["detail"])
|
|
r = cs.post("/api/auth/users/user_u6/role", json={"role": "project_admin"})
|
|
check("a super user changing an account outside their scope: 403", r.status_code == 403)
|
|
r = cs.put("/api/auth/users/user_u3/projects", json={"project_ids": ["proj1", "proj2"]})
|
|
check("a super user assigning a project they don't run: 403", r.status_code == 403)
|
|
r = ca.post("/api/auth/users/user_u9/role", json={"role": "project_admin"})
|
|
check("a single role change still works and returns the directory row",
|
|
r.status_code == 200 and r.json().get("role") == "project_admin")
|
|
one = audit("role_changed", "user_u9")
|
|
check("...and writes one role_changed row", len(one) == 1 and one[0].detail == {"from": "project_user", "to": "project_admin"},
|
|
str([e.detail for e in one]))
|
|
ca.post("/api/auth/users/user_u9/role", json={"role": "project_user"})
|
|
|
|
|
|
def bulk_role():
|
|
print("\n1. bulk permissions role")
|
|
r = ca.post("/api/auth/bulk-users/role", json={
|
|
"user_ids": ["user_u1", "user_u2", "user_admin", "user_nobody", "user_u1", "bad id!"],
|
|
"role": "project_admin"})
|
|
res = by_user(r)
|
|
check("200 even though some rows fail (a partial failure is a result, not an error)", r.status_code == 200)
|
|
check("u1 and u2 changed", res["user_u1"]["status"] == "ok" and res["user_u2"]["status"] == "ok")
|
|
check("your own row is refused with its reason; the rest still ran",
|
|
res["user_admin"]["status"] == "failed" and "own role" in res["user_admin"]["reason"])
|
|
check("an unknown account is refused as 'User not found'",
|
|
res["user_nobody"]["status"] == "failed" and res["user_nobody"]["reason"] == "User not found")
|
|
check("a malformed id is refused, not crashed on", res["bad id!"]["status"] == "failed")
|
|
check("a duplicated id is applied once", r.json()["requested"] == 5)
|
|
check("counts match the rows", (r.json()["ok"], r.json()["failed"]) == (2, 3), str(r.json()))
|
|
rows = audit("role_changed", "user_u1")
|
|
check("one role_changed audit row per changed account, same shape as the single route",
|
|
len(rows) == 1 and rows[0].detail == {"from": "project_user", "to": "project_admin"}
|
|
and rows[0].actor == "admin" and rows[0].entity_type == "user", str([e.detail for e in rows]))
|
|
r = ca.post("/api/auth/bulk-users/role", json={"user_ids": ["user_u1"], "role": "project_admin"})
|
|
check("a row already in that role is 'unchanged' and writes no audit row",
|
|
by_user(r)["user_u1"]["status"] == "unchanged" and len(audit("role_changed", "user_u1")) == 1)
|
|
r = cs.post("/api/auth/bulk-users/role", json={"user_ids": ["user_u3"], "role": "admin"})
|
|
check("a super user cannot grant admin in bulk either (grantable_roles, whole request 400)",
|
|
r.status_code == 400)
|
|
r = cs.post("/api/auth/bulk-users/role", json={"user_ids": ["user_u3", "user_u6", "user_u7"],
|
|
"role": "project_admin"})
|
|
res = by_user(r)
|
|
check("super user: an account wholly inside their projects changes", res["user_u3"]["status"] == "ok")
|
|
check("super user: an account also on a project they don't run is refused, with the reason",
|
|
res["user_u6"]["status"] == "failed" and "don't administer" in res["user_u6"]["reason"],
|
|
res["user_u6"]["reason"])
|
|
check("super user: an account they cannot see is 'User not found' (no existence leak)",
|
|
res["user_u7"]["status"] == "failed" and res["user_u7"]["reason"] == "User not found")
|
|
r = ca.post("/api/auth/bulk-users/role", json={"user_ids": ["user_admin2"], "role": "project_user"})
|
|
check("demoting another admin works while one active admin remains (the caller)",
|
|
by_user(r)["user_admin2"]["status"] == "ok")
|
|
|
|
|
|
def bulk_active():
|
|
print("\n2. bulk activate / disable")
|
|
r = ca.post("/api/auth/bulk-users/active", json={"user_ids": ["user_u4", "user_admin", "user_u5"],
|
|
"is_active": False})
|
|
res = by_user(r)
|
|
check("u4 and u5 disabled", res["user_u4"]["status"] == "ok" and res["user_u5"]["status"] == "ok"
|
|
and not fresh().get(models.User, "user_u4").is_active)
|
|
check("your own account is refused on its own row",
|
|
res["user_admin"]["status"] == "failed" and "disable your own" in res["user_admin"]["reason"])
|
|
check("one user_disabled audit row each, same shape as the single route",
|
|
[e.detail for e in audit("user_disabled", "user_u4")] == [{"is_active": False}])
|
|
r = ca.post("/api/auth/bulk-users/active", json={"user_ids": ["user_u4", "user_u2"], "is_active": True})
|
|
res = by_user(r)
|
|
check("re-enable: u4 ok, u2 (already active) unchanged",
|
|
res["user_u4"]["status"] == "ok" and res["user_u2"]["status"] == "unchanged")
|
|
|
|
|
|
def bulk_projects():
|
|
print("\n3. bulk project add / remove")
|
|
r = cs.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u1", "user_u2", "user_u8"],
|
|
"project_id": "proj1", "op": "add", "role": "project_admin"})
|
|
res = by_user(r)
|
|
check("add with a per-project role: every row ok", all(res[u]["status"] == "ok" for u in ("user_u1", "user_u2", "user_u8")),
|
|
str(res))
|
|
check("the role landed on that project", roles_of("user_u1").get("proj1") == "project_admin")
|
|
check("the user's OTHER project and its role are untouched - even a role the caller could not grant",
|
|
roles_of("user_u8").get("proj4") == "project_super_user", str(roles_of("user_u8")))
|
|
rows = audit("project_access_changed", "user_u1")
|
|
check("one project_access_changed row per account, in the single route's shape",
|
|
len(rows) == 1 and set(rows[0].detail) == {"projects", "scope", "overrides"}
|
|
and rows[0].detail["scope"] == "managed", str([e.detail for e in rows]))
|
|
r = cs.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u1"], "project_id": "proj2", "op": "add"})
|
|
check("a super user cannot add anyone to a project they don't run (403)", r.status_code == 403)
|
|
r = cs.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u1"], "project_id": "proj1",
|
|
"op": "add", "role": "project_super_user"})
|
|
check("a super user cannot hand out super user on a project (400)", r.status_code == 400)
|
|
r = ca.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u6"], "project_id": "proj3", "op": "add"})
|
|
check("admin adds u6 to proj3; proj1 and proj2 memberships and roles stay",
|
|
by_user(r)["user_u6"]["status"] == "ok"
|
|
and roles_of("user_u6") == {"proj1": "", "proj2": "project_admin", "proj3": ""}, str(roles_of("user_u6")))
|
|
r = cs.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u2", "user_u9"], "project_id": "proj1", "op": "remove"})
|
|
res = by_user(r)
|
|
check("remove: u2 taken off proj1", res["user_u2"]["status"] == "ok" and "proj1" not in roles_of("user_u2"))
|
|
check("remove: someone not on it is 'User not found' to a super user who cannot see them",
|
|
res["user_u9"]["status"] == "failed")
|
|
r = ca.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u9"], "project_id": "proj1", "op": "remove"})
|
|
check("remove: an admin removing someone not on the project gets 'unchanged'",
|
|
by_user(r)["user_u9"]["status"] == "unchanged")
|
|
r = ca.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u1"], "project_id": "proj1", "op": "replace"})
|
|
check("only add and remove exist: no replace-the-whole-list (400)", r.status_code == 400)
|
|
|
|
|
|
def bulk_delete():
|
|
print("\n4. bulk delete")
|
|
r = ca.post("/api/auth/bulk-users/delete", json={"user_ids": ["user_u5", "user_admin", "user_gone"]})
|
|
res = by_user(r)
|
|
check("u5 deleted", res["user_u5"]["status"] == "ok" and fresh().get(models.User, "user_u5") is None)
|
|
check("your own account is refused on its own row, the others still ran",
|
|
res["user_admin"]["status"] == "failed" and "delete your own" in res["user_admin"]["reason"])
|
|
check("an account that no longer exists is reported, not hidden",
|
|
res["user_gone"]["status"] == "failed" and res["user_gone"]["reason"] == "User not found")
|
|
check("one user_deleted audit row, same shape as the single route",
|
|
[e.detail for e in audit("user_deleted", "user_u5")] == [{"role": "project_user"}])
|
|
check("the deleted account's memberships went with it", roles_of("user_u5") == {})
|
|
|
|
|
|
def csv_resolve():
|
|
print("\n6. CSV upload: usernames in, a line-by-line report out (T12.4)")
|
|
text = ("username\n" # header, skipped
|
|
"u3\n"
|
|
"U3\n" # same person, different case: a duplicate
|
|
"nobody\n"
|
|
"\n" # blank lines are not rows
|
|
"u6\n" # visible to the super user, but also on a project they don't run
|
|
"u7\n" # not visible to the super user at all
|
|
"super\n" # the caller themself
|
|
"u8@example.test,extra column\n" # an email address, matched to exactly one account
|
|
",\n") # an empty first column
|
|
r = cs.post("/api/auth/bulk-users/resolve", json={"text": text})
|
|
j = r.json()
|
|
rows = {x["line"]: x for x in j["rows"]}
|
|
check("200 with a row for every non-blank line after the header",
|
|
r.status_code == 200 and sorted(rows) == [2, 3, 4, 6, 7, 8, 9, 10], sorted(rows))
|
|
check("a valid username is accepted", rows[2]["status"] == "ok" and rows[2]["user_id"] == "user_u3")
|
|
check("a repeated username is rejected as a duplicate of its first line, not applied twice",
|
|
rows[3]["status"] == "rejected" and rows[3]["reason"] == "duplicate of line 2")
|
|
check("an unknown username: 'User not found', with its line number", rows[4]["reason"] == "User not found")
|
|
check("an account the caller may not change: rejected with the single route's own reason",
|
|
rows[6]["status"] == "rejected" and "don't administer" in rows[6]["reason"], rows[6]["reason"])
|
|
check("an account the caller cannot see: 'User not found' (a CSV leaks no more than the table)",
|
|
rows[7]["reason"] == "User not found")
|
|
check("the caller's own account is rejected with a clear reason", "your own account" in rows[8]["reason"])
|
|
check("an email address resolves when exactly one account has it",
|
|
rows[9]["status"] == "ok" and rows[9]["user_id"] == "user_u8")
|
|
check("an empty first column is rejected, not skipped", rows[10]["reason"] == "no username in the first column")
|
|
check("the ids handed back are exactly the accepted rows",
|
|
j["user_ids"] == ["user_u3", "user_u8"] and (j["accepted"], j["rejected"]) == (2, 6), str(j["user_ids"]))
|
|
r = cs.post("/api/auth/bulk-users/active", json={"user_ids": j["user_ids"] + ["user_u7"], "is_active": False})
|
|
res = by_user(r)
|
|
check("the CSV's ids go through the same bulk route and the same guards: an id slipped in by hand "
|
|
"is still refused", res["user_u7"]["status"] == "failed" and res["user_u3"]["status"] == "ok")
|
|
ca.post("/api/auth/bulk-users/active", json={"user_ids": ["user_u3", "user_u8"], "is_active": True})
|
|
r = cp.post("/api/auth/bulk-users/resolve", json={"text": "u3"})
|
|
check("a plain project user cannot resolve a list (403)", r.status_code == 403)
|
|
r = cs.post("/api/auth/bulk-users/resolve", json={"text": "x" * 200_001})
|
|
check("an oversized upload is refused (422)", r.status_code == 422)
|
|
s = fresh()
|
|
s.add(models.User(id="user_twin1", username="twin1", email="shared@example.test"))
|
|
s.add(models.User(id="user_twin2", username="twin2", email="shared@example.test"))
|
|
s.commit()
|
|
r = ca.post("/api/auth/bulk-users/resolve", json={"text": "shared@example.test"})
|
|
check("an email shared by two accounts matches neither", r.json()["rows"][0]["reason"] == "User not found")
|
|
|
|
|
|
def gates():
|
|
print("\n7. who may call, and how much")
|
|
for path, body in (("role", {"role": "project_user"}), ("active", {"is_active": False}),
|
|
("projects", {"project_id": "proj1", "op": "add"}), ("delete", {})):
|
|
r = cp.post(f"/api/auth/bulk-users/{path}", json={"user_ids": ["user_u3"], **body})
|
|
check(f"a plain project user is refused /bulk-users/{path} (403)", r.status_code == 403, str(r.status_code))
|
|
anon = TestClient(A.app, base_url="http://127.0.0.1", raise_server_exceptions=False)
|
|
check("no session: 401", anon.post("/api/auth/bulk-users/delete", json={"user_ids": ["user_u3"]}).status_code == 401)
|
|
r = ca.post("/api/auth/bulk-users/active", json={"user_ids": [f"user_x{i}" for i in range(501)], "is_active": False})
|
|
check("more than 500 ids in one request is refused (422)", r.status_code == 422, str(r.status_code))
|
|
|
|
|
|
SECTIONS = [single_routes, bulk_role, bulk_active, bulk_projects, bulk_delete, csv_resolve, gates]
|
|
|
|
|
|
def main() -> int:
|
|
print("Wave 12 bulk user administration - server checks")
|
|
try:
|
|
for section in SECTIONS:
|
|
try:
|
|
section()
|
|
except Exception as exc: # noqa: BLE001 - a missing route must read as FAIL, not a traceback
|
|
check(f"section {section.__name__} ran to the end", False, f"{type(exc).__name__}: {exc}")
|
|
finally:
|
|
db.close()
|
|
A.engine.dispose()
|
|
shutil.rmtree(TMP, ignore_errors=True)
|
|
passed = sum(RESULTS)
|
|
print(f"\n{passed}/{len(RESULTS)} checks passed.")
|
|
return 0 if passed == len(RESULTS) else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|