diff --git a/docs/waves/decisions-2026-10-02.md b/docs/waves/decisions-2026-10-02.md new file mode 100644 index 0000000..92004bc --- /dev/null +++ b/docs/waves/decisions-2026-10-02.md @@ -0,0 +1,84 @@ +# Decisions — October 2, 2026 + +Three items, from the security review of 2026-10-01 +(`docs/reference/security-review-2026-10-01.md`). They get `D` ids because they +are internal security calls made mid-build, the same category as `D15` and +`D18`, not features a user asked for. + +Decided by Matt Mabrey, 2026-10-02. + +| Item | Title | Review finding | Task | +|---|---|---|---| +| `D19` | Uploaded files download safely | SEC-01, SEC-15e (BL-035, BL-036) | T16.2 | +| `D20` | One SOP per project | SEC-02 (BL-048) | T16.3 | +| `D21` | Session decode fails closed; PyJWT upgraded | SEC-07 (BL-052) | T16.1 | + +**Schedule:** wave 16. It is **independent of waves 12 to 15**: it touches +`server/` only, and no file in it is changed by a task in those waves except +`server/app.py`, in functions they do not touch (`get_wp_file`, `upsert_sop`, +the SOP baseline readers). Wave 16 may merge before wave 12. + +**Out of this round, by decision:** SEC-06 (session revocation) waits for the +AWS work. All other SEC findings stay as backlog drafts in +`docs/reference/security-review/backlog-drafts.md`. + +--- + +## D19 — Uploaded files download safely + +- **Problem:** an SVG drawing can carry a script. The server sends it back + `inline` with its own content type, on the app's origin, so the script runs + as whoever opens it (SEC-01). Separately, a file name that is not Latin-1 + (for example `Plan é.pdf`) makes the download fail with 500, and CR/LF in a + name reaches the response header (SEC-15e). +- **Decision:** SVG uploads stay **accepted**, but every file that is not a + PDF or a raster image downloads as an **attachment** inside a **sandbox**: + `Content-Disposition: attachment` and + `Content-Security-Policy: sandbox; default-src 'none'`. PDF and raster images + (PNG, JPEG, GIF, WebP, BMP, AVIF) keep opening inline. Every file name goes + out in the RFC 6266 / RFC 5987 form (ASCII fallback plus `filename*`). +- **Why accept SVG instead of refusing it:** no change for the person who + uploads, and no migration for SVGs already stored. The protection is on the + way out, which also covers any SVG already in the database. +- **Must not change:** inline preview of PDF and images (CR-007), the + `Cache-Control` the offline drawing cache relies on, the D8 limits, and the + upload API. + +## D20 — One SOP per project + +- **Problem:** the rule "changing a completed SOP is a Project Admin action" + checks only the SOP row being posted. A `project_user` can post a NEW SOP id + with `complete: true`. Every reader picks "the latest complete SOP", so that + row becomes the baseline every page loads and the source of PM, CM and QA + mail routing (SEC-02, probe S3). +- **Decision:** + 1. A project has one SOP, with the id `sop__`. The browser has + always written that id (`pushSOP` in `project-data.js`). A request with no + id gets it. A request that would CREATE a SOP with any other id on a + project is refused with 400. + 2. Existing SOP rows with other ids (for example rows `seed_demo.py` made) + stay. They can still be updated under the old rules. Nothing is deleted. + 3. While a project has a complete SOP, writing any SOP on that project with + `complete: true`, and changing a complete SOP, needs Project Admin on the + project. + 4. The readers prefer the canonical row: `project_sop_team`, + `project_qa_group`, `project_summary` and `GET /api/sops/latest` with + `complete=true&project_id=` read `sop__` when it is complete, + and fall back to "latest complete" only when it is not. So a rogue row + made before this fix cannot stay the baseline. +- **Must not change:** a project member drafting the SOP and completing it the + first time (allowed today, allowed after); admin access to project-less + SOPs; the response shape of every SOP route. + +## D21 — Session decode fails closed; PyJWT upgraded + +- **Problem:** a crafted 1.6 KB cookie makes PyJWT 2.13.0 raise an error that + `decode_token` does not catch, so an unauthenticated request gets a 500 and + a stack trace in the log (SEC-07, probe S12). `pip-audit` lists 13 + advisories for 2.13.0. +- **Decision:** pin **PyJWT 2.15.1** (`pip-audit`: no known vulnerabilities on + 2026-10-02). `decode_token` treats ANY decode failure, and any cookie longer + than 4096 characters, as "not signed in" (401). It also requires the `exp` + and `sub` claims, which every token this app issues carries. +- **Must not change:** every valid session, the D18 sliding refresh and + ceiling, and the fake Okta test seam. diff --git a/docs/waves/wave-16.md b/docs/waves/wave-16.md new file mode 100644 index 0000000..dda408e --- /dev/null +++ b/docs/waves/wave-16.md @@ -0,0 +1,155 @@ +# Wave 16 — Urgent security fixes + +**Items:** `D19`, `D20`, `D21` +**Depends on:** nothing. Independent of waves 12 to 15 (see the decision record). +**Decision record:** `docs/waves/decisions-2026-10-02.md` +**Background:** `docs/reference/security-review-2026-10-01.md` + +Four tasks, in build order. All server-side. No page markup or stylesheet +changes, so the 390px / 1440px screenshot rule does not apply; the +browser probes that read files and SOPs are still listed for a run on a +machine with Edge. + +New check for this wave: `tests/security_check.py`. It is self-contained (its +own SQLite database, in-process, no browser), so it runs anywhere. + +--- + +### T16.1 — D21: session decode fails closed; PyJWT 2.15.1 + +- **Items:** `D21` +- **Depends on:** nothing (first task) +- **Blocks:** T16.4 +- **Surface:** `server/` +- **Files:** `server/requirements.txt`, `server/auth.py` (`decode_token`), `tests/security_check.py` (new) + +**Do:** pin `PyJWT==2.15.1`. In `decode_token`, return `None` for an empty or +over-long token (over 4096 characters) and for any exception from +`jwt.decode`. Require the `exp` and `sub` claims. + +**Do not:** change token contents, the cookie, or the D18 refresh. + +**Done when:** + +- [x] the crafted-cookie request returns 401, not 500 +- [x] a valid session still works, and the D18 refresh still reissues +- [x] `pip-audit -r server/requirements.txt` reports no PyJWT advisory +- [x] smoke test 27/27 + +--- + +### T16.2 — D19: uploaded files download safely + +- **Items:** `D19` +- **Depends on:** nothing +- **Blocks:** T16.4 +- **Surface:** `server/` +- **Files:** `server/files_http.py` (new), `server/app.py` (`get_wp_file`), `tests/security_check.py` + +**Do:** serve PDF and raster images inline as today. Serve every other type, +SVG included, as an attachment with `Content-Security-Policy: sandbox; +default-src 'none'`. Send `X-Content-Type-Options: nosniff` from the API too +(NGINX already does; the dev server does not). Build `Content-Disposition` +with an ASCII fallback and an RFC 5987 `filename*`. Reference code: +`docs/reference/architecture-review/proposals/server/files_http.py` (P-6). + +**Do not:** refuse SVG uploads (decided: accept, download only). Do not change +`Cache-Control`. + +**Done when:** + +- [x] an SVG downloads as an attachment with the sandbox header +- [x] PNG, JPEG and PDF still open inline +- [x] `Plan é.pdf` downloads (was 500) +- [x] a name with CR/LF produces a valid header +- [x] `tests/files_check.py` passes on a machine with Edge (CR-007 offline drawings) + +--- + +### T16.3 — D20: one SOP per project + +- **Items:** `D20` +- **Depends on:** nothing +- **Blocks:** T16.4 +- **Surface:** `server/` +- **Files:** `server/app.py` (`upsert_sop`, `latest_sop`, `project_summary`, `project_sop_team`, `project_qa_group`), `tests/security_check.py` + +**Do:** the four rules in D20. One helper picks the project's baseline SOP +(canonical row if complete, else latest complete) and every baseline reader +uses it. + +**Do not:** delete or rename existing SOP rows. Do not change any response shape. + +**Done when:** + +- [x] a `project_user` cannot create a second SOP on a project (400) or post + `complete: true` while a complete SOP exists (403) +- [x] a `project_user` can still draft and complete the first SOP of a project +- [x] a Project Admin can still change the completed SOP +- [x] POST without an id lands on `sop__` +- [x] a rogue complete SOP made before the fix no longer drives the baseline + or the QA and PM/CM recipients +- [x] `tests/sample_check.py` and `tests/critical_reopen_check.py` pass on a + machine with Edge + +--- + +### T16.4 — D19, D20, D21: verification + +- **Items:** `D19`, `D20`, `D21` +- **Depends on:** T16.1 to T16.3 +- **Surface:** verification +- **Files:** this file (verification record) + +**Done when:** + +- [x] `tests/security_check.py` passes +- [x] `docs/reference/security-review/sec_probe.py`: S3 and S12 change as + expected; every other line is unchanged +- [x] the architecture review `equivalence_check.py` (current branch vs wave + 16) is IDENTICAL: the scenario does not use these paths, so it proves the + rest of the work-package flow did not move +- [x] smoke test 27/27 +- [x] the browser probes named in T16.2 and T16.3 are listed for a run on a + machine with Edge (not available in the build sandbox) + +## Verification record + +Run 2026-10-02 in the build sandbox (Linux, Python 3.10, no browser), on branch +`feat/wave-16-security` at T16.3. + +| Check | Result | +|---|---| +| `tests/security_check.py` | **36/36** (D21 6, D19 14, D20 16) | +| Same check against `da1325c` with PyJWT 2.13.0 | 20/36. The 16 failures are the findings (D21 3, D19 6, D20 7). The 20 passes are the "still works" checks plus three that already held (over-long cookie 401, non-member 404, SOP move refused by the existing completed-SOP rule) | +| `docs/reference/security-review/sec_probe.py`, before vs after | Exactly 4 of 27 lines change: S3 (new complete SOP 200 -> **400**; baseline `sop_rogue` -> **`sop__proj_a`**; QA group attacker -> **real group**) and S12 (crafted cookie 500 -> **401**). All other lines identical | +| `equivalence_check.py` (architecture review), `da1325c` vs wave 16 | **IDENTICAL**: 78 HTTP results, 89 audit rows, 24 notifications. The scenario's SOP id was changed from `sop_eq` to the canonical `sop__proj_eq` on both sides, because D20 refuses a non-canonical id on purpose | +| `server/smoketest.py` | **27/27** after each of T16.1, T16.2, T16.3 | +| `server/seed_demo.py` | Seeds the demo project; its SOP lands on the canonical id | +| `pip-audit -r server/requirements.txt` | No known vulnerabilities | + +**Browser probes, run 2026-10-02 on Matt's machine (Windows, Edge 154, +Python 3.12.10, `.venv`), one at a time:** + +| Probe | Task | Result | +|---|---|---| +| `tests/files_check.py` | T16.2 | **36/36**, including the 1440px creator, 390px Field View, and the offline drawing cache with the server gone | +| `tests/sample_check.py` | T16.3 | **10/10** | +| `tests/critical_reopen_check.py` | T16.3 | **11/11**, PM + CM + assignee mail, sink-verified | + +T16.2 and T16.3 are done. + +**Production data check for D20, 2026-10-02.** On the production database +(`wp_db`, psql): projects with more than one complete SOP: **0 rows**. D20 has +no legacy duplicates to handle on deploy. + +**Harness fix needed to get there (`tests/cdp.py`, committed with this record).** +Every probe failed first with "browser would not start ... exited rc=0 +without binding the port". Cause: the PowerShell session was elevated, and +Edge and Chrome de-elevate by relaunching themselves through Explorer as a +normal user; the relaunch drops `--remote-debugging-port`. Edge's log said so +(`Edge is running elevated: 1`). No browser policy was involved (all hives +checked). Two changes, both inert on a normal shell and on Linux/macOS: +`--do-not-de-elevate` on Windows, and a 15-second grace for the port when the +launched process exits rc=0. Probe results are unchanged by it; it only lets +the browser start. diff --git a/server/app.py b/server/app.py index 3df79e3..bc57f25 100644 --- a/server/app.py +++ b/server/app.py @@ -27,7 +27,7 @@ from sqlalchemy.orm import Session from starlette.middleware.sessions import SessionMiddleware from .db import Base, engine, get_db -from . import models, auth, notify, assets_db, okta_auth, okta_fake +from . import models, auth, notify, assets_db, okta_auth, okta_fake, files_http log = logging.getLogger("wpsuite.app") @@ -1331,6 +1331,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) @@ -1339,6 +1365,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) @@ -1348,6 +1379,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")) @@ -1380,6 +1433,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) @@ -1560,15 +1622,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 {} @@ -1586,15 +1643,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 {} @@ -2661,12 +2714,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( @@ -2910,10 +2958,9 @@ def get_wp_file(file_id: str, user: models.User = Depends(auth.get_current_user) if not row: raise HTTPException(status_code=404, detail="File not found") require_project_access(db, user, row.project_id) - return Response(content=row.data, media_type=row.mime or "application/octet-stream", - headers={"Content-Disposition": - f'inline; filename="{(row.name or "file").replace(chr(34), "")}"', - "Cache-Control": "private, max-age=86400"}) + # D19: PDF and raster images inline as before; anything else (SVG included) + # downloads as a sandboxed attachment, and every name is a valid header. + return files_http.file_response(row) @app.patch("/api/files/{file_id}") diff --git a/server/auth.py b/server/auth.py index 17b9bd2..fc3598c 100644 --- a/server/auth.py +++ b/server/auth.py @@ -173,12 +173,29 @@ def create_token(user: "models.User") -> str: return jwt.encode(payload, SECRET_KEY, algorithm=JWT_ALG) +# D21: a real session token is about 300 characters. Anything far larger is not +# one of ours, and refusing it before parsing keeps a crafted cookie from making +# the parser do work on our behalf. +_MAX_TOKEN_CHARS = 4096 + + def decode_token(token: str) -> Optional[dict]: """Return the token claims if the signature and expiry are valid, else None. - Session cookies only — a token of any other type is rejected.""" + Session cookies only — a token of any other type is rejected. + + D21: fails CLOSED on any error. This used to catch jwt.PyJWTError only, and + PyJWT 2.13.0 let a RecursionError out of header parsing, so a 1.6 KB cookie + from someone with no account produced a 500 and a stack trace instead of a + 401 (security review SEC-07). Whatever goes wrong inside the decoder, the + answer is the same: not signed in.""" + if not token or len(token) > _MAX_TOKEN_CHARS: + return None try: - claims = jwt.decode(token, SECRET_KEY, algorithms=[JWT_ALG]) - except jwt.PyJWTError: + # Every token this app issues carries exp and sub (create_token, + # maybe_refresh_token); one without them is not ours. + claims = jwt.decode(token, SECRET_KEY, algorithms=[JWT_ALG], + options={"require": ["exp", "sub"]}) + except Exception: # noqa: BLE001 — see docstring: every failure is "not signed in" return None # No route issues a `typ`-carrying token anymore (that was the password-reset # token, removed in T10.4), but a session token still must never validate as diff --git a/server/files_http.py b/server/files_http.py new file mode 100644 index 0000000..e5c8a17 --- /dev/null +++ b/server/files_http.py @@ -0,0 +1,66 @@ +"""Safe HTTP responses for uploaded drawings — D19 (T16.2). + +Security review 2026-10-01, SEC-01 and SEC-15e. + +WHY THIS EXISTS + Uploads accept `image/*`, which includes `image/svg+xml`. An SVG is a + document, not a picture: it can carry ') + check("D19", "an SVG upload is still accepted (decided: accept, download only)", code == 200, f"status {code}") + r = as_member.get(f"/api/files/{svg}") + disp, csp = r.headers.get("content-disposition", ""), r.headers.get("content-security-policy", "") + check("D19", "an SVG downloads as an attachment, never inline", disp.startswith("attachment"), disp) + check("D19", "an SVG download carries a sandbox CSP", "sandbox" in csp, csp or "no CSP") + check("D19", "file responses carry nosniff", r.headers.get("x-content-type-options") == "nosniff") + + for name, mime, data in (("plan.png", "image/png", b"\x89PNG\r\n\x1a\n"), + ("photo.jpg", "image/jpeg", b"\xff\xd8\xff"), + ("sheet.pdf", "application/pdf", b"%PDF-1.4")): + _, fid = upload(name, mime, data) + r = as_member.get(f"/api/files/{fid}") + check("D19", f"{mime} still opens inline, no sandbox", + r.status_code == 200 and r.headers.get("content-disposition", "").startswith("inline") + and "content-security-policy" not in r.headers, r.headers.get("content-disposition", "")) + check("D19", f"{mime} keeps the offline cache header", + r.headers.get("cache-control") == "private, max-age=86400", r.headers.get("cache-control", "")) + + _, fid = upload("Plan é – Nivel 2.pdf", "application/pdf", b"%PDF-1.4") + r = as_member.get(f"/api/files/{fid}") + check("D19", "a drawing with a non-Latin-1 name downloads (was 500)", r.status_code == 200, + f"status {r.status_code}") + check("D19", "the real name rides in filename*", + "filename*=UTF-8''Plan%20%C3%A9" in r.headers.get("content-disposition", ""), + r.headers.get("content-disposition", "")) + + _, fid = upload('a\r\nSet-Cookie: x=1;".pdf', "application/pdf", b"%PDF-1.4") + r = as_member.get(f"/api/files/{fid}") + disp = r.headers.get("content-disposition", "") + check("D19", "CR/LF and quotes in a name cannot reach the header", + r.status_code == 200 and "\r" not in disp and "\n" not in disp and "set-cookie" not in r.headers, + repr(disp)) + r = client(account("user_outsider")).get(f"/api/files/{svg}") + check("D19", "a non-member still gets 403 (access check unchanged)", r.status_code == 403, + f"status {r.status_code}") + + +# ── 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: + print("Wave 16 security checks") + try: + for section in SECTIONS: + section() + 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())