Archive projects, auto-add default members, rebuild the admin console

Three things asked for together, plus the migration they share (a7c31f9e5b02 —
additive, with database defaults for existing rows, so unlike the users.role
rewrite it is safe under a code-only rollback).

ARCHIVE A PROJECT. A finished job leaves every picker, switcher and search, and
freezes read-only, without losing anything. Hiding is free: GET /api/projects
defaults to archived=exclude, so the home picker and the app-bar switcher drop it
without either of them changing. Freezing is require_project_writable(), which
every write that lands on a project now goes through — SOP and WP upserts (both
ends, so a package can be moved neither into nor out of an archived job), deletes,
issue, status, WP archive, and comments on its WPs/SOPs. It answers 409, not 403:
nobody lacks a permission, the project's state is the objection, and the browser
outbox in project-data.js retires 4xx ops instead of retrying them against a job
that will never accept them. Unarchive and delete stay allowed on purpose —
unarchive is the one write an archived project must take, and archive-then-delete
is a normal sequence.

DEFAULT MEMBERS ON NEW PROJECTS. users.auto_add_projects / auto_add_role flag the
people who belong on every job, so an admin says it once instead of remembering it
at each project creation. It runs on the is_new branch of upsert_project, which is
the single road into project creation, so the home page, the sample project and the
demo seeder are all covered and an update never re-runs it. Note the interaction
with the existing creator-grant: that row commits first and add_default_members
never overwrites an existing membership, so the creator grant now carries the
creator's own auto_add_role — otherwise someone flagged "Project Admin on every
job" would land as a plain member on the one job they started themselves.

ADMIN CONSOLE. The user table had outgrown .wrap{max-width:860px}: nine columns in
an 860px card meant every cell wrapped, so one user occupied a ~100px band, the
action buttons stacked, and the table spilled outside its own white card. Now
1240px, with wide tables scrolling inside .tscroll so the page itself never scrolls
sideways, and one spacing/control scale across all twelve cards. Truncation hangs
off a span inside the cell rather than max-width on the td, which table-layout:auto
treats as advisory — the usual reason cell ellipsis works in the stylesheet and not
on the page.

Found in review and fixed here rather than later:

- Stored XSS in the new Projects card, reachable by any signed-in user, landing in
  an admin's session. The uesc(v).replace(/'/g,"\'") idiom this file already used
  in eight places escapes in the wrong order — uesc leaves backslashes alone, so a
  stored name containing \' closes the JS string literal and the rest executes.
  jsq() does backslash, then quote, then HTML, and all thirteen handler bindings go
  through it. The same bug, unescaped entirely, was in the SOP builder's custom
  constraint names (escHandlerArg there). Three of seven test payloads escaped the
  literal under the old idiom — one of them a plain name ending in a backslash, so
  it was breaking buttons for innocent input too.
- _save_comment resolved wp_id and sop_id with if/elif but stored both, so a
  payload naming a WP you may touch and a SOP you may not was authorised on the WP
  alone and still wrote into the other project's thread. Both are checked now.
- Promoting an account to admin left its default-member flag set but invisible,
  ready to take effect again on demotion — cleared, as set_user_auto_add already
  does for the role.

smoketest.py and the console's own smoke test both assert the archive round trip:
out of the default list, present with archived=all, writes refused with 409, and
all of it undone by unarchiving.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-08-05 13:48:43 -07:00
parent e5977758c0
commit 928ab8c900
14 changed files with 1092 additions and 136 deletions

View File

@@ -170,6 +170,29 @@ def require_project_admin(db: Session, user: "models.User", project_id: Optional
)
def require_project_writable(db: Session, user_or_none, project_id: Optional[str],
what: str = "This change") -> None:
"""An archived project is frozen: everything on it stays readable, nothing on it
may be written. Every mutating path that lands on a project goes through here —
saving a SOP or a package, issuing, status changes, deletes, comments.
It is 409 and not 403 on purpose. Nobody lacks a permission here: the state of
the project is the objection, and even an admin gets refused until they unarchive
it — hence the caller identity is accepted for symmetry with the other guards but
deliberately unused. 409 also matters offline: the browser outbox in
html/project-data.js retires any 4xx op instead of retrying it forever, so an edit
queued before the archive dies quietly rather than looping against a frozen job."""
if not project_id:
return
proj = db.get(models.Project, project_id)
if proj is not None and proj.archived_at is not None:
raise HTTPException(
status_code=409,
detail=(f"{what} — this project is archived (read-only). An administrator "
f"can unarchive it from the admin console."),
)
def scope_to_access(stmt, column, db: Session, user: "models.User"):
"""Restrict a SELECT to the user's accessible projects (no-op for admins)."""
ids = accessible_project_ids(db, user)
@@ -178,16 +201,50 @@ def scope_to_access(stmt, column, db: Session, user: "models.User"):
return stmt.where(column.in_(ids))
def grant_project_access(db: Session, user_id: str, project_id: str) -> None:
"""Add a (user, project) membership if it isn't already there."""
def grant_project_access(db: Session, user_id: str, project_id: str, role: str = "") -> bool:
"""Add a (user, project) membership if it isn't already there, carrying an
optional per-project role override ('' = inherit the account's own). Returns True
only when a row was actually added, so a caller can report what it did. Does NOT
commit — the caller owns the transaction."""
exists = db.scalar(
select(models.ProjectMember.id).where(
(models.ProjectMember.user_id == user_id)
& (models.ProjectMember.project_id == project_id)
)
)
if not exists:
db.add(models.ProjectMember(id=gen_id("pm"), user_id=user_id, project_id=project_id))
if exists:
return False
db.add(models.ProjectMember(id=gen_id("pm"), user_id=user_id, project_id=project_id, role=role))
return True
def add_default_members(db: Session, project_id: str, actor) -> list[str]:
"""Put the standing default members onto a brand-new project.
Some people belong on every job the moment it exists — the PM who runs them all,
the QC lead — and flagging their account (users.auto_add_projects) is how an admin
says that once instead of remembering it at every project creation. App admins are
skipped because they already reach every project, an inactive account is not
revived by a new job, and an existing membership is never duplicated or
overwritten. Returns the usernames added; does NOT commit, matching
grant_project_access."""
rows = db.scalars(
select(models.User).where(
(models.User.auto_add_projects.is_(True)) & (models.User.is_active.is_(True))
).order_by(models.User.username)
).all()
added = []
for u in rows:
if auth.is_admin(u):
continue
if grant_project_access(db, u.id, project_id, (u.auto_add_role or "").strip()):
added.append(u.username)
if added:
# One line for the batch, not one per person — this is a single automatic act.
log_event(db, actor, "project_access_granted", "project", project_id,
project_id=project_id, summary=f"{len(added)} default member(s) added",
detail={"users": added, "reason": "auto_add_projects"})
return added
# ── Audit trail ────────────────────────────────────────────────────────────────
@@ -381,6 +438,13 @@ class ProjectAssignIn(BaseModel):
roles: dict[str, str] = Field(default_factory=dict)
class AutoAddIn(BaseModel):
auto_add: bool
# Role to give this user on the projects they're auto-added to; '' inherits the
# account's own role, same value space as ProjectMember.role.
role: str = ""
LOGIN_MAX_ATTEMPTS = int(os.getenv("AUTH_MAX_ATTEMPTS", "5"))
LOGIN_LOCKOUT_MINUTES = int(os.getenv("AUTH_LOCKOUT_MINUTES", "15"))
@@ -690,8 +754,16 @@ def set_user_role(user_id: str, body: RoleIn, admin: models.User = Depends(auth.
raise HTTPException(status_code=400, detail="Can't remove the last admin account")
old_role = u.role
u.role = body.role
log_event(db, admin, "role_changed", "user", u.id, summary=u.username,
detail={"from": old_role, "to": 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, admin, "role_changed", "user", u.id, summary=u.username, detail=detail)
db.commit()
db.refresh(u)
return u.to_dict()
@@ -714,6 +786,33 @@ def set_user_project_role(user_id: str, body: ProjectRoleIn, admin: models.User
return u.to_dict()
@app.post("/api/auth/users/{user_id}/auto-add")
def set_user_auto_add(user_id: str, body: AutoAddIn, admin: models.User = Depends(auth.require_admin), db: Session = Depends(get_db)):
"""Flag a user as a default member of every project created from here on, with
an optional role on those projects. It only touches NEW projects — existing
assignments stay under the admin's hand (see set_user_projects), because
back-filling everyone onto historical jobs is never what this flag means."""
allowed = ("", auth.ROLE_PROJECT_ADMIN, auth.ROLE_PROJECT_USER)
role = (body.role or "").strip()
if role not in allowed:
raise HTTPException(
status_code=400,
detail=f"role must be '' (inherit) or one of {auth.ROLE_PROJECT_ADMIN}, {auth.ROLE_PROJECT_USER}",
)
u = db.get(models.User, user_id)
if not u:
raise HTTPException(status_code=404, detail="User not found")
u.auto_add_projects = bool(body.auto_add)
# A role left behind on a switched-off flag is a trap: it would quietly take
# effect the day someone switches the flag back on.
u.auto_add_role = role if u.auto_add_projects else ""
log_event(db, admin, "auto_add_changed", "user", u.id, summary=u.username,
detail={"auto_add": bool(u.auto_add_projects), "role": u.auto_add_role})
db.commit()
db.refresh(u)
return u.to_dict()
@app.delete("/api/auth/users/{user_id}")
def delete_user(user_id: str, admin: models.User = Depends(auth.require_admin), db: Session = Depends(get_db)):
u = db.get(models.User, user_id)
@@ -741,7 +840,11 @@ def get_user_projects(user_id: str, _admin: models.User = Depends(auth.require_a
"assigned": [r.project_id for r in rows],
# Per-project role overrides, keyed by project id ('' = inherit the account's).
"roles": {r.project_id: (r.role or "") for r in rows},
"projects": [{"id": p.id, "name": p.name, "number": p.number} for p in projects],
# Archived projects stay on this list on purpose — an existing assignment has
# to remain visible and removable — but they're flagged so the dialog can say
# so, rather than offering a finished job as though it were live work.
"projects": [{"id": p.id, "name": p.name, "number": p.number,
"archived": p.archived_at is not None} for p in projects],
}
@@ -775,6 +878,7 @@ def upsert_project(body: ProjectIn, user: models.User = Depends(auth.get_current
is_new = proj is None
if not is_new:
require_project_access(db, user, proj.id)
require_project_writable(db, user, proj.id, "Editing a project")
if proj is None:
proj = models.Project(id=body.id or gen_id("proj"))
db.add(proj)
@@ -789,18 +893,36 @@ def upsert_project(body: ProjectIn, user: models.User = Depends(auth.get_current
log_event(db, user, "created" if is_new else "updated", "project", proj.id,
project_id=proj.id, summary=(proj.name or proj.number or proj.id))
db.commit()
# A project created by a non-admin auto-grants its creator access.
# A project created by a non-admin auto-grants its creator access. If that
# creator is ALSO a standing default member, this is the row that sticks —
# add_default_members below never overwrites an existing membership — so it has
# to carry the role they'd have been given, or someone whose flag says
# "Project Admin on every job" would silently land as a plain member on the one
# job they started themselves.
if is_new and not auth.is_admin(user):
grant_project_access(db, user.id, proj.id)
creator_role = (user.auto_add_role or "").strip() if user.auto_add_projects else ""
grant_project_access(db, user.id, proj.id, creator_role)
db.commit()
# …and anyone flagged as a default member joins at creation time too.
if is_new:
add_default_members(db, proj.id, user)
db.commit()
db.refresh(proj)
return proj.to_dict()
@app.get("/api/projects")
def list_projects(user: models.User = Depends(auth.get_current_user), db: Session = Depends(get_db)):
stmt = scope_to_access(select(models.Project), models.Project.id, db, user).order_by(models.Project.updated_at.desc())
rows = db.scalars(stmt).all()
def list_projects(
archived: str = Query("exclude", description="exclude (default) | only | all"),
user: models.User = Depends(auth.get_current_user),
db: Session = Depends(get_db),
):
stmt = scope_to_access(select(models.Project), models.Project.id, db, user)
if archived == "only":
stmt = stmt.where(models.Project.archived_at.is_not(None))
elif archived != "all":
stmt = stmt.where(models.Project.archived_at.is_(None)) # default: hide archived
rows = db.scalars(stmt.order_by(models.Project.updated_at.desc())).all()
return [p.summary() for p in rows]
@@ -827,14 +949,46 @@ def delete_project(project_id: str, user: models.User = Depends(auth.get_current
return {"deleted": project_id}
@app.post("/api/projects/{project_id}/archive")
def archive_project(project_id: str, body: ArchiveIn, user: models.User = Depends(auth.get_current_user), db: Session = Depends(get_db)):
"""Archive (or unarchive) a whole project — it drops out of every picker,
switcher and search, and freezes read-only, without losing a thing. This is how
a finished job gets out of everyone's way while staying on the record; delete is
still there for a job that should never have existed."""
proj = db.get(models.Project, project_id)
if not proj:
raise HTTPException(status_code=404, detail="Project not found")
# Takes the whole job out of circulation for everyone on it, so it sits at the
# same bar as deleting it. Note the deliberate absence of require_project_writable
# — unarchiving is the one write an archived project must still accept.
require_project_admin(db, user, proj.id, "Archiving a project")
was_archived = proj.archived_at is not None
if body.archived and not was_archived:
proj.archived_at = models.utcnow()
log_event(db, user, "archived", "project", proj.id, project_id=proj.id,
summary=(proj.name or proj.number or proj.id))
elif not body.archived and was_archived:
proj.archived_at = None
log_event(db, user, "unarchived", "project", proj.id, project_id=proj.id,
summary=(proj.name or proj.number or proj.id))
db.commit()
db.refresh(proj)
return proj.to_dict()
# ── SOPs ─────────────────────────────────────────────────────────────────────
@app.post("/api/sops")
def upsert_sop(body: SopIn, user: models.User = Depends(auth.get_current_user), db: Session = Depends(get_db)):
check_id(body.id)
require_project_access(db, user, body.project_id)
# Both ends are checked: the project the SOP is being written INTO here, and the
# one it currently sits on below — so an archived job can be neither edited nor
# used as a source to move a SOP out of.
require_project_writable(db, user, body.project_id, "Saving a SOP")
sop = db.get(models.Sop, body.id) if body.id else None
if sop is not None:
require_project_access(db, user, sop.project_id)
require_project_writable(db, user, sop.project_id, "Saving a SOP")
# The SOP is the project's baseline: once it's been completed, changing it
# is a Project Admin action. Authoring and revising a draft is open to any
# project member, including marking it complete the first time.
@@ -899,6 +1053,7 @@ def delete_sop(sop_id: str, user: models.User = Depends(auth.get_current_user),
if not sop:
raise HTTPException(status_code=404, detail="SOP not found")
require_project_admin(db, user, sop.project_id, "Deleting a SOP")
require_project_writable(db, user, sop.project_id, "Deleting a SOP")
log_event(db, user, "deleted", "sop", sop.id, project_id=sop.project_id,
summary=(sop.name or sop.number or sop.id))
db.delete(sop)
@@ -1090,9 +1245,12 @@ def upsert_wp(body: WpIn, background_tasks: BackgroundTasks, user: models.User =
check_id(body.parent_id)
check_id(body.assignee_id)
require_project_access(db, user, body.project_id)
# Destination and origin both have to be live — see upsert_sop.
require_project_writable(db, user, body.project_id, "Saving a work package")
wp = db.get(models.WorkPackage, body.id) if body.id else None
if wp is not None:
require_project_access(db, user, wp.project_id)
require_project_writable(db, user, wp.project_id, "Saving a work package")
is_new = wp is None
old_status = None if is_new else wp.status
old_assignee = None if is_new else wp.assignee_id
@@ -1276,6 +1434,7 @@ def delete_wp(wp_id: str, user: models.User = Depends(auth.get_current_user), db
# Deleting a work package is irreversible — Project Admin only. A project_user
# who wants one out of the way can archive it instead (reversible).
require_project_admin(db, user, wp.project_id, "Deleting a work package")
require_project_writable(db, user, wp.project_id, "Deleting a work package")
log_event(db, user, "deleted", "wp", wp.id, project_id=wp.project_id,
summary=(wp.number or wp.subject or wp.id))
db.delete(wp)
@@ -1291,6 +1450,7 @@ def issue_wp(wp_id: str, user: models.User = Depends(auth.get_current_user), db:
if not wp:
raise HTTPException(status_code=404, detail="Work Package not found")
require_project_access(db, user, wp.project_id)
require_project_writable(db, user, wp.project_id, "Issuing a work package")
enforce_release_gates(db, wp.id, wp.data, "Issued", wp.status)
wp.status = "Issued"
wp.issued_at = models.utcnow()
@@ -1307,6 +1467,7 @@ def set_wp_status(wp_id: str, body: StatusIn, user: models.User = Depends(auth.g
if not wp:
raise HTTPException(status_code=404, detail="Work Package not found")
require_project_access(db, user, wp.project_id)
require_project_writable(db, user, wp.project_id, "Changing a work package's status")
old_status = wp.status
# Same gates as /issue — this route must not be a way around them.
enforce_release_gates(db, wp.id, wp.data, body.status, old_status)
@@ -1329,6 +1490,9 @@ def archive_wp(wp_id: str, body: ArchiveIn, user: models.User = Depends(auth.get
if not wp:
raise HTTPException(status_code=404, detail="Work Package not found")
require_project_access(db, user, wp.project_id)
# An archived project is frozen whole: its packages keep the archive state they
# had, and tidying inside it waits until the job is unarchived.
require_project_writable(db, user, wp.project_id, "Archiving a work package")
was_archived = wp.archived_at is not None
if body.archived and not was_archived:
wp.archived_at = models.utcnow()
@@ -1399,12 +1563,23 @@ def global_search(
pat = _like_term(term)
esc = "\\"
# An archived project is meant to be gone from view, and search is the one place
# it would otherwise come back — as the project itself, or as one of its packages
# or SOPs. So the archived ids are read once here and filtered out of all three
# result sets. Rows with no project at all (orphan/legacy, admin-only) survive
# explicitly: SQL's NOT IN drops NULLs, and they aren't on an archived job.
archived_pids = set(db.scalars(
select(models.Project.id).where(models.Project.archived_at.is_not(None))
).all())
proj_stmt = select(models.Project).where(
func.lower(models.Project.name).like(pat, escape=esc)
| func.lower(models.Project.number).like(pat, escape=esc)
| func.lower(models.Project.client).like(pat, escape=esc)
| func.lower(models.Project.site).like(pat, escape=esc)
)
if archived_pids:
proj_stmt = proj_stmt.where(models.Project.id.not_in(archived_pids))
proj_stmt = scope_to_access(proj_stmt, models.Project.id, db, user)
projects = db.scalars(proj_stmt.order_by(models.Project.updated_at.desc()).limit(limit)).all()
@@ -1417,6 +1592,11 @@ def global_search(
| func.lower(models.WorkPackage.status).like(pat, escape=esc)
)
)
if archived_pids:
wp_stmt = wp_stmt.where(
models.WorkPackage.project_id.is_(None)
| models.WorkPackage.project_id.not_in(archived_pids)
)
wp_stmt = scope_to_access(wp_stmt, models.WorkPackage.project_id, db, user)
wps = db.scalars(wp_stmt.order_by(models.WorkPackage.updated_at.desc()).limit(limit)).all()
@@ -1424,6 +1604,10 @@ def global_search(
func.lower(models.Sop.name).like(pat, escape=esc)
| func.lower(models.Sop.number).like(pat, escape=esc)
)
if archived_pids:
sop_stmt = sop_stmt.where(
models.Sop.project_id.is_(None) | models.Sop.project_id.not_in(archived_pids)
)
sop_stmt = scope_to_access(sop_stmt, models.Sop.project_id, db, user)
sops = db.scalars(sop_stmt.order_by(models.Sop.updated_at.desc()).limit(limit)).all()
@@ -1535,17 +1719,28 @@ def project_members(project_id: str, user: models.User = Depends(auth.get_curren
# ── Comments / feedback ──────────────────────────────────────────────────────
def _save_comment(body: CommentIn, db: Session, user: "models.User") -> dict:
# A comment tied to a WP/SOP requires access to that resource's project, so
# a user can't write into another project's review thread.
# a user can't write into another project's review thread. A review thread on an
# archived project is frozen with the rest of it; general app feedback isn't tied
# to a project at all and keeps working regardless.
#
# Both ids are checked independently — NOT if/elif. The row stores whichever ids
# the payload carried, so a body naming a WP you may touch AND a SOP you may not
# would, under an elif, be authorised on the WP alone and still land in the other
# project's SOP thread.
check_id(body.wp_id)
check_id(body.sop_id)
if body.wp_id:
wp = db.get(models.WorkPackage, body.wp_id)
if not wp:
raise HTTPException(status_code=404, detail="Work Package not found")
require_project_access(db, user, wp.project_id)
elif body.sop_id:
require_project_writable(db, user, wp.project_id, "Commenting on a work package")
if body.sop_id:
sop = db.get(models.Sop, body.sop_id)
if not sop:
raise HTTPException(status_code=404, detail="SOP not found")
require_project_access(db, user, sop.project_id)
require_project_writable(db, user, sop.project_id, "Commenting on a SOP")
extra = body.model_extra or {}
c = models.Comment(
id=gen_id("c"),