diff --git a/server/app.py b/server/app.py index b183564..fdd8b4c 100644 --- a/server/app.py +++ b/server/app.py @@ -1352,6 +1352,32 @@ def archive_project(project_id: str, body: ArchiveIn, user: models.User = Depend # ── SOPs ───────────────────────────────────────────────────────────────────── +def canonical_sop_id(project_id: Optional[str]) -> Optional[str]: + """D20: the one id a project's SOP lives at - the id pushSOP has always used.""" + return f"sop__{project_id}" if project_id else None + + +def project_baseline_sop(db: Session, project_id: Optional[str]) -> Optional["models.Sop"]: + """D20: THE completed SOP of a project, for every reader that treats it as the + baseline (page load, PM/CM mail, QA mail, the launcher summary). + + The canonical row wins when it is complete. "Most recent complete" is only the + fallback, for projects whose SOP predates the fixed id (seed data, API + clients). Before D20 "most recent" was the whole rule, which is what let a + second complete SOP take the baseline over (security review SEC-02).""" + if not project_id: + return None + row = db.get(models.Sop, canonical_sop_id(project_id)) + if row is not None and row.complete and row.project_id == project_id: + return row + return db.scalars( + select(models.Sop) + .where((models.Sop.project_id == project_id) & (models.Sop.complete.is_(True))) + .order_by(models.Sop.updated_at.desc()) + .limit(1) + ).first() + + @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) @@ -1360,6 +1386,11 @@ def upsert_sop(body: SopIn, user: models.User = Depends(auth.get_current_user), # 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") + # D20: one SOP per project, at a fixed id. The browser has always written + # `sop__` (pushSOP); a request with no id now gets it too. + canonical = canonical_sop_id(body.project_id) + if not body.id and canonical: + body.id = canonical 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) @@ -1369,6 +1400,28 @@ def upsert_sop(body: SopIn, user: models.User = Depends(auth.get_current_user), # project member, including marking it complete the first time. if sop.complete: require_project_admin(db, user, sop.project_id, "Changing a completed SOP") + # D20 (security review SEC-02): the rule above checked only the row being + # posted, so a project_user could post a NEW id with complete=true and every + # "latest complete SOP" reader - the page baseline and the PM/CM/QA mail + # routing - followed it. A project gets no second SOP row (creating one, or + # moving one in, under any id but the canonical one is refused), and while + # it has a complete SOP, writing another complete one is a Project Admin act. + # Rows made before D20 under other ids stay and keep their old rules. + if canonical and body.id != canonical and (sop is None or sop.project_id != body.project_id): + raise HTTPException( + status_code=400, + detail=f"A project has one SOP. Save it as {canonical}.", + ) + if body.project_id and body.complete: + other_complete = db.scalar( + select(models.Sop.id).where( + (models.Sop.project_id == body.project_id) + & (models.Sop.complete.is_(True)) + & (models.Sop.id != body.id) + ).limit(1) + ) + if other_complete: + require_project_admin(db, user, body.project_id, "Changing a completed SOP") is_new = sop is None if sop is None: sop = models.Sop(id=body.id or gen_id("sop")) @@ -1401,6 +1454,15 @@ def list_sops(project_id: Optional[str] = Query(None), full: bool = Query(False) @app.get("/api/sops/latest") def latest_sop(complete: Optional[bool] = None, project_id: Optional[str] = Query(None), user: models.User = Depends(auth.get_current_user), db: Session = Depends(get_db)): + # D20: "the project's completed SOP" is what pullProject() asks for on every + # page load, so it is answered by the baseline rule, not by "most recent". + # Same 404 as before for a project the caller cannot reach. + if complete is True and project_id: + ids = accessible_project_ids(db, user) + sop = project_baseline_sop(db, project_id) if (ids is None or project_id in ids) else None + if not sop: + raise HTTPException(status_code=404, detail="No SOP found") + return sop.to_dict() stmt = select(models.Sop) if complete is not None: stmt = stmt.where(models.Sop.complete == complete) @@ -1581,15 +1643,10 @@ def reopened_critical(old_data: Optional[dict], new_data: Optional[dict]) -> lis def project_sop_team(db: Session, project_id: Optional[str]) -> list[str]: - """PM + CM user ids from the project's most recent complete SOP.""" + """PM + CM user ids from the project's baseline SOP (D20: project_baseline_sop).""" if not project_id: return [] - sop = db.scalars( - select(models.Sop) - .where((models.Sop.project_id == project_id) & (models.Sop.complete.is_(True))) - .order_by(models.Sop.updated_at.desc()) - .limit(1) - ).first() + sop = project_baseline_sop(db, project_id) if not sop: return [] data = sop.data or {} @@ -1607,15 +1664,11 @@ def project_qa_group(db: Session, project_id: Optional[str]) -> list["models.Use """D2: the QA group named on the project's latest complete SOP. pushSOP writes the row as data={sop, state}, so the project block is data['sop']['project'] - project_sop_team above read the flat shape until BL-021 was fixed - (2026-08-20); both now read nested-first, exactly alike.""" + (2026-08-20); both now read nested-first, exactly alike. D20: both also read + the same row, project_baseline_sop.""" if not project_id: return [] - sop = db.scalars( - select(models.Sop) - .where((models.Sop.project_id == project_id) & (models.Sop.complete.is_(True))) - .order_by(models.Sop.updated_at.desc()) - .limit(1) - ).first() + sop = project_baseline_sop(db, project_id) if not sop: return [] data = sop.data or {} @@ -2682,12 +2735,7 @@ def project_summary(project_id: str, user: models.User = Depends(auth.get_curren raise HTTPException(status_code=404, detail="Project not found") require_project_access(db, user, project_id) - sop = db.scalars( - select(models.Sop) - .where(models.Sop.project_id == project_id, models.Sop.complete.is_(True)) - .order_by(models.Sop.updated_at.desc()) - .limit(1) - ).first() + sop = project_baseline_sop(db, project_id) # D20: the same row every page loads wp_total = db.scalar( select(func.count()).select_from(models.WorkPackage).where( diff --git a/tests/security_check.py b/tests/security_check.py index 1df209f..310651f 100644 --- a/tests/security_check.py +++ b/tests/security_check.py @@ -168,7 +168,81 @@ def d19(): f"status {r.status_code}") -SECTIONS = [d21, d19] +# ── D20: one SOP per project ───────────────────────────────────────────────── +def d20(): + print("\nD20 one SOP per project") + from datetime import datetime, timedelta, timezone + + def sop(c, **body): + body.setdefault("project_id", "proj_a") + return c.post("/api/sops", json=body) + + def team(qa): + return {"sop": {"project": {"pmId": qa, "cmId": qa, "qaGroupIds": [qa]}}, "state": {}} + + r = sop(as_member, name="draft", complete=False, data=team("user_padmin")) + check("D20", "a SOP posted with no id lands on sop__", + r.status_code == 200 and r.json().get("id") == "sop__proj_a", f"{r.status_code} {r.json().get('id')}") + r = sop(as_member, id="sop__proj_a", name="done", complete=True, data=team("user_padmin")) + check("D20", "a project_user still completes the first SOP of a project", r.status_code == 200, + f"status {r.status_code}") + r = sop(as_member, id="sop_rogue", name="mine", complete=True, data=team("user_member")) + check("D20", "a project_user cannot create a second SOP (the SEC-02 attack)", r.status_code == 400, + f"status {r.status_code}") + r = sop(as_member, id="sop__proj_a", name="edit", complete=True, data=team("user_member")) + check("D20", "a project_user still cannot change the completed SOP", r.status_code == 403, + f"status {r.status_code}") + r = sop(as_member, id="sop__proj_a", name="undo", complete=False, data=team("user_member")) + check("D20", "a project_user cannot un-complete it either", r.status_code == 403, f"status {r.status_code}") + r = sop(as_padmin, id="sop__proj_a", name="revised", complete=True, data=team("user_padmin")) + check("D20", "a Project Admin can still change the completed SOP", r.status_code == 200, + f"status {r.status_code}") + qa = [u.id for u in A.project_qa_group(SessionLocal(), "proj_a")] + check("D20", "QA mail still goes to the group the real SOP names", qa == ["user_padmin"], str(qa)) + + # A rogue complete SOP made BEFORE D20 (written straight to the table, newer + # than the real one) must not stay the baseline. + s = SessionLocal() + old, new = datetime.now(timezone.utc) - timedelta(days=2), datetime.now(timezone.utc) + s.add(models.Sop(id="sop__proj_b", project_id="proj_b", name="real", complete=True, + data=team("user_padmin"), updated_at=old)) + s.add(models.Sop(id="sop_rogue_b", project_id="proj_b", name="rogue", complete=True, + data=team("user_member"), updated_at=new)) + s.commit() + r = as_member.get("/api/sops/latest?complete=true&project_id=proj_b") + check("D20", "the page-load baseline is the canonical SOP, not a newer rogue row", + r.status_code == 200 and r.json().get("id") == "sop__proj_b", f"{r.status_code} {r.json().get('id')}") + qa = [u.id for u in A.project_qa_group(SessionLocal(), "proj_b")] + team_ids = A.project_sop_team(SessionLocal(), "proj_b") + check("D20", "QA and PM/CM mail follow the canonical SOP", qa == ["user_padmin"] and team_ids == ["user_padmin", "user_padmin"], + f"qa={qa} team={team_ids}") + r = as_member.get("/api/projects/proj_b/summary") + check("D20", "the launcher summary reports the canonical SOP", r.json().get("sop_id") == "sop__proj_b", + str(r.json().get("sop_id"))) + + # Rows made before D20 under other ids keep working under the old rules. + s.add(models.Sop(id="sop_legacy", project_id="proj_c", name="legacy", complete=False, data={})) + db.add(models.ProjectMember(id="pm_member_c", user_id="user_member", project_id="proj_c", role="")) + db.commit(); s.commit() + r = sop(as_member, id="sop_legacy", project_id="proj_c", name="legacy edited", complete=False) + check("D20", "an existing non-canonical SOP can still be edited", r.status_code == 200, + f"status {r.status_code}") + r = sop(as_member, id="sop_legacy", project_id="proj_c", name="legacy done", complete=True) + check("D20", "...and completed the first time", r.status_code == 200, f"status {r.status_code}") + r = sop(as_member, id="sop__proj_c", project_id="proj_c", name="second", complete=True) + check("D20", "while a project has a complete SOP, another complete one needs Project Admin", + r.status_code == 403, f"status {r.status_code}") + r = sop(as_member, id="sop_legacy", project_id="proj_a", name="moved", complete=False) + check("D20", "a SOP cannot be moved into another project under a non-canonical id", + r.status_code in (400, 403), f"status {r.status_code}") + r = client(account("user_stranger")).get("/api/sops/latest?complete=true&project_id=proj_a") + check("D20", "a non-member still gets 404 for the baseline", r.status_code == 404, f"status {r.status_code}") + r = as_admin.post("/api/sops", json={"project_id": "proj_c", "name": "x", "complete": False}) + check("D20", "an id-less write (smoke test, seed_demo, admin diagnostics) targets the canonical row", + r.status_code == 200 and r.json().get("id") == "sop__proj_c", f"{r.status_code} {r.json().get('id')}") + + +SECTIONS = [d21, d19, d20] def main() -> int: