From 8dd0afaba42eb073c7be11191b89fbfa11001a5f Mon Sep 17 00:00:00 2001 From: Matt Mabrey Date: Fri, 2 Oct 2026 13:50:00 -0700 Subject: [PATCH 1/8] wave 16: planning docs for D19, D20, D21 D19 - uploaded files download safely (SEC-01, SEC-15e) D20 - one SOP per project (SEC-02) D21 - session decode fails closed, PyJWT 2.15.1 (SEC-07) From the security review of 2026-10-01. Decision record and task breakdown only in this commit - no code yet. (cherry picked from commit 1c221a122ea15ab566d753aa63a45b1139903eed) --- docs/waves/decisions-2026-10-02.md | 84 ++++++++++++++++++++ docs/waves/wave-16.md | 118 +++++++++++++++++++++++++++++ 2 files changed, 202 insertions(+) create mode 100644 docs/waves/decisions-2026-10-02.md create mode 100644 docs/waves/wave-16.md 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..de155a9 --- /dev/null +++ b/docs/waves/wave-16.md @@ -0,0 +1,118 @@ +# 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:** + +- [ ] the crafted-cookie request returns 401, not 500 +- [ ] a valid session still works, and the D18 refresh still reissues +- [ ] `pip-audit -r server/requirements.txt` reports no PyJWT advisory +- [ ] 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:** + +- [ ] an SVG downloads as an attachment with the sandbox header +- [ ] PNG, JPEG and PDF still open inline +- [ ] `Plan é.pdf` downloads (was 500) +- [ ] a name with CR/LF produces a valid header +- [ ] `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:** + +- [ ] a `project_user` cannot create a second SOP on a project (400) or post + `complete: true` while a complete SOP exists (403) +- [ ] a `project_user` can still draft and complete the first SOP of a project +- [ ] a Project Admin can still change the completed SOP +- [ ] POST without an id lands on `sop__` +- [ ] a rogue complete SOP made before the fix no longer drives the baseline + or the QA and PM/CM recipients +- [ ] `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:** + +- [ ] `tests/security_check.py` passes +- [ ] `docs/reference/security-review/sec_probe.py`: S3 and S12 change as + expected; every other line is unchanged +- [ ] 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 +- [ ] smoke test 27/27 +- [ ] 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 + +(filled in at T16.4) -- 2.49.1 From d962ab23814fec4571c1a155363a6cfe70a57bad Mon Sep 17 00:00:00 2001 From: Matt Mabrey Date: Fri, 2 Oct 2026 13:51:43 -0700 Subject: [PATCH 2/8] T16.1: D21 session decode fails closed; PyJWT 2.15.1 decode_token treats any decode failure, and any cookie over 4096 chars, as not signed in, and requires exp and sub. PyJWT 2.13.0 -> 2.15.1 (pip-audit: 13 advisories -> none). Security review SEC-07: a crafted 1.6 KB cookie with no account gave 500 + stack trace; now 401. New tests/security_check.py (no browser): D21 section 6/6. Against da1325c with PyJWT 2.13.0 it fails 3 checks (crafted cookie 500, token with no exp accepted, old pin) - the findings. The over-long cookie and the two still-works checks pass on both. Smoke test 27/27. (cherry picked from commit 01ce7e941c46e0c3007be1fa0ed559022a7c878b) --- server/auth.py | 23 ++++++- server/requirements.txt | 4 +- tests/security_check.py | 139 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 162 insertions(+), 4 deletions(-) create mode 100644 tests/security_check.py 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/requirements.txt b/server/requirements.txt index 8bcd040..6fb9773 100644 --- a/server/requirements.txt +++ b/server/requirements.txt @@ -17,7 +17,9 @@ pymssql==2.3.13 # read-only lookups against the Micron asset DB (SQL # MICRON_DB_URL to mssql+pyodbc://…?driver=ODBC+Driver+18+for+SQL+Server pydantic==2.13.4 python-dotenv==1.2.2 -PyJWT==2.13.0 # signed session tokens +PyJWT==2.15.1 # signed session tokens. D21 (2026-10-02): was 2.13.0, which + # pip-audit lists 13 advisories for (GHSA-8wjv-2p76-3863 let a + # crafted cookie raise past decode_token). 2.15.1: none known. starlette==1.3.1 # pinned transitive (cookie / CORS handling — security-relevant) Authlib==1.7.2 # Okta OIDC authorization-code flow (T10.1, wave 10 / D15) httpx==0.28.1 # Authlib's OIDC client needs an HTTP client; explicit, not transitive diff --git a/tests/security_check.py b/tests/security_check.py new file mode 100644 index 0000000..4668f4d --- /dev/null +++ b/tests/security_check.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +"""Wave 16 security checks: D19, D20, D21. + + python tests/security_check.py + +Self-contained, like the other probes, but needs NO browser: it builds its own +throwaway SQLite database in a temp folder, drives the API in-process with +FastAPI's TestClient, and deletes everything afterward. Your real wpsuite.db is +never touched, and no network traffic leaves the process. + +Each check tests what was BROKEN, measured by the security review of +2026-10-01 (docs/reference/security-review-2026-10-01.md), not only what is +easy to assert. Every check that tests a fix FAILED against da1325c, the +commit before wave 16; the checks that say "still works" passed there too, +and are what proves the fix broke nothing. + +Exit codes: 0 all passed, 1 a check failed, 2 the run could not start. +""" +import base64 +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-security-check-") +# db.py reads DATABASE_URL at import, so the environment is set first. +os.environ["DATABASE_URL"] = "sqlite:///" + os.path.join(TMP, "security.db").replace("\\", "/") +os.environ["AUTH_SECRET_KEY"] = "security-check-key-security-check-key-0000" +os.environ.pop("WP_OKTA_FAKE_DIRECTORY", None) +sys.path.insert(0, ROOT) + +try: + from fastapi.testclient import TestClient + 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(item, name, ok, detail=""): + RESULTS.append(bool(ok)) + print(f" {'PASS' if ok else 'FAIL'} {item:<4} {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 client(user=None, token=None): + c = TestClient(A.app, base_url="http://127.0.0.1", raise_server_exceptions=False) + if user is not None: + c.cookies.set(auth.COOKIE_NAME, auth.create_token(user)) + if token is not None: + c.cookies.set(auth.COOKIE_NAME, token) + return c + + +admin = account("user_admin", "admin") +member = account("user_member") # project_user on proj_a +padmin = account("user_padmin") # project_admin on proj_a +as_admin, as_member, as_padmin = client(admin), client(member), client(padmin) +for pid in ("proj_a", "proj_b", "proj_c"): + as_admin.post("/api/projects", json={"id": pid, "name": pid}) +for uid, role in (("user_member", ""), ("user_padmin", "project_admin")): + for pid in ("proj_a", "proj_b"): + db.add(models.ProjectMember(id=f"pm_{uid}_{pid}", user_id=uid, project_id=pid, role=role)) +db.commit() + + +def b64url(raw: bytes) -> str: + return base64.urlsafe_b64encode(raw).rstrip(b"=").decode() + + +# ── D21: session decode fails closed ───────────────────────────────────────── +def d21(): + print("\nD21 session decode fails closed") + crafted = b64url(b"[" * 1200) + "." + b64url(b"{}") + ".x" + r = client(token=crafted).get("/api/projects") + check("D21", "a crafted 1.6 KB cookie with no account gets 401, not 500", + r.status_code == 401, f"status {r.status_code}") + r = client(token="x" * 5000).get("/api/projects") + check("D21", "an over-long cookie gets 401", r.status_code == 401, f"status {r.status_code}") + no_exp = __import__("jwt").encode({"sub": member.id, "ver": 0}, auth.SECRET_KEY, algorithm="HS256") + r = client(token=no_exp).get("/api/projects") + check("D21", "a correctly signed token with no exp is refused", r.status_code == 401, + f"status {r.status_code}") + r = as_member.get("/api/auth/me") + check("D21", "a real session still works", r.status_code == 200 and r.json()["user"]["id"] == member.id, + f"status {r.status_code}") + # D18 sliding refresh must survive the stricter decode: a token near its idle + # edge, used now, comes back with a fresh cookie. + from datetime import datetime, timedelta, timezone + now = datetime.now(timezone.utc) + near = __import__("jwt").encode({"sub": member.id, "username": member.username, "role": member.role, + "ver": 0, "iat": now - timedelta(minutes=25), + "login_at": (now - timedelta(minutes=25)).timestamp(), + "exp": now + timedelta(minutes=5)}, auth.SECRET_KEY, algorithm="HS256") + r = client(token=near).get("/api/projects") + check("D21", "the D18 sliding refresh still reissues the session", + r.status_code == 200 and auth.COOKIE_NAME in (r.headers.get("set-cookie") or ""), + f"status {r.status_code}") + import re + pin = re.search(r"(?im)^pyjwt==([0-9.]+)", open(os.path.join(ROOT, "server", "requirements.txt")).read()) + pinned = tuple(int(x) for x in pin.group(1).split(".")) if pin else (0,) + check("D21", "server/requirements.txt pins PyJWT 2.15.1 or later", pinned >= (2, 15, 1), + pin.group(1) if pin else "no pin") + + +SECTIONS = [d21] + + +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()) -- 2.49.1 From f4d74879cc95066cf3a18b7ca3ee6484160abc22 Mon Sep 17 00:00:00 2001 From: Matt Mabrey Date: Fri, 2 Oct 2026 13:52:43 -0700 Subject: [PATCH 3/8] T16.2: D19 uploaded files download safely New server/files_http.py; get_wp_file uses it. - PDF and raster images (png, jpeg, gif, webp, bmp, avif) open inline, as before; Cache-Control unchanged for the offline drawing cache. - Every other type, SVG included, downloads as an attachment with Content-Security-Policy: sandbox; default-src 'none'. - SVG uploads stay accepted (decided 2026-10-02: accept, download only). - Content-Disposition: ASCII fallback + RFC 5987 filename*, control characters and quotes replaced. nosniff from the API too. Security review SEC-01 (stored XSS through an SVG drawing) and SEC-15e (non-Latin-1 names gave 500; CR/LF reached the header). security_check.py D19: 20/20 total with D21. Against da1325c: 6 fails (the findings); every inline/cache/access check passes on both. (cherry picked from commit 14ecb75c887bc3b812145dc45e948c7a6cea57fd) --- server/app.py | 9 +++--- server/files_http.py | 66 +++++++++++++++++++++++++++++++++++++++++ tests/security_check.py | 52 +++++++++++++++++++++++++++++++- 3 files changed, 121 insertions(+), 6 deletions(-) create mode 100644 server/files_http.py diff --git a/server/app.py b/server/app.py index 3df79e3..e71b0b9 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") @@ -2910,10 +2910,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/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}") + + +SECTIONS = [d21, d19] def main() -> int: -- 2.49.1 From c0b736e5037ce4c57e009c5109746aec8c22fe49 Mon Sep 17 00:00:00 2001 From: Matt Mabrey Date: Fri, 2 Oct 2026 13:55:17 -0700 Subject: [PATCH 4/8] T16.3: D20 one SOP per project - A SOP posted with no id lands on sop__, the id pushSOP has always used. Creating (or moving in) a SOP under any other id on a project is refused with 400. - While a project has a complete SOP, writing another complete one needs Project Admin (the existing rule only checked the posted row). - New project_baseline_sop(): canonical row when complete, else the latest complete (pre-D20 rows). Used by /api/sops/latest with complete=true&project_id, project_summary, project_sop_team and project_qa_group, so a rogue row made before the fix cannot stay the baseline or the mail routing. - Existing rows under other ids stay and keep their old rules. Security review SEC-02 (a project_user took over the baseline and the PM/CM/QA mail routing with one POST). security_check.py: 36/36 with D19-D21. Against da1325c: 7 D20 checks fail (the findings). Smoke test 27/27; seed_demo writes the canonical id. (cherry picked from commit 7bd5ab104de94bfc7459cf680443323f15e87055) --- server/app.py | 88 +++++++++++++++++++++++++++++++---------- tests/security_check.py | 76 ++++++++++++++++++++++++++++++++++- 2 files changed, 143 insertions(+), 21 deletions(-) diff --git a/server/app.py b/server/app.py index e71b0b9..bc57f25 100644 --- a/server/app.py +++ b/server/app.py @@ -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( 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: -- 2.49.1 From 0157b4b325b97f3ea731a3a251601307ec078595 Mon Sep 17 00:00:00 2001 From: Matt Mabrey Date: Fri, 2 Oct 2026 13:57:00 -0700 Subject: [PATCH 5/8] T16.4: wave 16 verification record security_check.py 36/36 (da1325c: 20/36, the 16 failures are the findings). sec_probe.py: only S3 and S12 change. equivalence_check IDENTICAL vs da1325c (canonical SOP id in the scenario). Smoke test 27/27. pip-audit clean. Open: files_check.py (T16.2), sample_check.py and critical_reopen_check.py (T16.3) need a machine with Edge; those two tasks stay not-done until they pass. (cherry picked from commit f0750212cae500d5359aea87d6479457ba4b9500) --- docs/waves/wave-16.md | 58 +++++++++++++++++++++++++++++-------------- 1 file changed, 39 insertions(+), 19 deletions(-) diff --git a/docs/waves/wave-16.md b/docs/waves/wave-16.md index de155a9..3dd1947 100644 --- a/docs/waves/wave-16.md +++ b/docs/waves/wave-16.md @@ -31,10 +31,10 @@ over-long token (over 4096 characters) and for any exception from **Done when:** -- [ ] the crafted-cookie request returns 401, not 500 -- [ ] a valid session still works, and the D18 refresh still reissues -- [ ] `pip-audit -r server/requirements.txt` reports no PyJWT advisory -- [ ] smoke test 27/27 +- [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 --- @@ -58,10 +58,10 @@ with an ASCII fallback and an RFC 5987 `filename*`. Reference code: **Done when:** -- [ ] an SVG downloads as an attachment with the sandbox header -- [ ] PNG, JPEG and PDF still open inline -- [ ] `Plan é.pdf` downloads (was 500) -- [ ] a name with CR/LF produces a valid header +- [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 - [ ] `tests/files_check.py` passes on a machine with Edge (CR-007 offline drawings) --- @@ -82,12 +82,12 @@ uses it. **Done when:** -- [ ] a `project_user` cannot create a second SOP on a project (400) or post +- [x] a `project_user` cannot create a second SOP on a project (400) or post `complete: true` while a complete SOP exists (403) -- [ ] a `project_user` can still draft and complete the first SOP of a project -- [ ] a Project Admin can still change the completed SOP -- [ ] POST without an id lands on `sop__` -- [ ] a rogue complete SOP made before the fix no longer drives the baseline +- [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 - [ ] `tests/sample_check.py` and `tests/critical_reopen_check.py` pass on a machine with Edge @@ -103,16 +103,36 @@ uses it. **Done when:** -- [ ] `tests/security_check.py` passes -- [ ] `docs/reference/security-review/sec_probe.py`: S3 and S12 change as +- [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 -- [ ] the architecture review `equivalence_check.py` (current branch vs wave +- [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 -- [ ] smoke test 27/27 -- [ ] the browser probes named in T16.2 and T16.3 are listed for a run on a +- [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 -(filled in at T16.4) +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 | + +**Not run (no headless browser in the sandbox).** These done-when items stay +open until someone runs them on a machine with Edge, so T16.2 and T16.3 are +**not marked done** yet: + +- T16.2: `python tests/files_check.py` (CR-007 drawings, offline cache) +- T16.3: `python tests/sample_check.py` and `python tests/critical_reopen_check.py` + +Run them one at a time (file-map.md: chained runs exhaust the browser's ports). -- 2.49.1 From be3157baf2facb4a26d524a65723c0f1206e16c3 Mon Sep 17 00:00:00 2001 From: Matt Mabrey Date: Fri, 2 Oct 2026 14:51:48 -0700 Subject: [PATCH 6/8] T16.4: browser probes pass; cdp.py starts from an elevated shell files_check.py 36/36 (T16.2), sample_check.py 10/10 and critical_reopen_check.py 11/11 (T16.3), run on Matt's machine with Edge 154. T16.2 and T16.3 done; wave 16 verification complete. tests/cdp.py: every probe first failed 'exited rc=0 without binding the port'. The shell was elevated; Edge and Chrome de-elevate by relaunching through Explorer and the relaunch drops the debugging port ('Edge is running elevated: 1' in the browser log). Adds --do-not-de-elevate on Windows and a 15 s grace for the port after an rc=0 exit. Both inert on a normal shell and off Windows. (cherry picked from commit f752ae36775a458f268c3e295e9a7453d535d3b5) --- docs/waves/wave-16.md | 29 +++++++++++++++++++++-------- tests/cdp.py | 31 +++++++++++++++++++++++++++---- 2 files changed, 48 insertions(+), 12 deletions(-) diff --git a/docs/waves/wave-16.md b/docs/waves/wave-16.md index 3dd1947..7ed20d2 100644 --- a/docs/waves/wave-16.md +++ b/docs/waves/wave-16.md @@ -62,7 +62,7 @@ with an ASCII fallback and an RFC 5987 `filename*`. Reference code: - [x] PNG, JPEG and PDF still open inline - [x] `Plan é.pdf` downloads (was 500) - [x] a name with CR/LF produces a valid header -- [ ] `tests/files_check.py` passes on a machine with Edge (CR-007 offline drawings) +- [x] `tests/files_check.py` passes on a machine with Edge (CR-007 offline drawings) --- @@ -89,7 +89,7 @@ uses it. - [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 -- [ ] `tests/sample_check.py` and `tests/critical_reopen_check.py` pass on a +- [x] `tests/sample_check.py` and `tests/critical_reopen_check.py` pass on a machine with Edge --- @@ -128,11 +128,24 @@ Run 2026-10-02 in the build sandbox (Linux, Python 3.10, no browser), on branch | `server/seed_demo.py` | Seeds the demo project; its SOP lands on the canonical id | | `pip-audit -r server/requirements.txt` | No known vulnerabilities | -**Not run (no headless browser in the sandbox).** These done-when items stay -open until someone runs them on a machine with Edge, so T16.2 and T16.3 are -**not marked done** yet: +**Browser probes, run 2026-10-02 on Matt's machine (Windows, Edge 154, +Python 3.12.10, `.venv`), one at a time:** -- T16.2: `python tests/files_check.py` (CR-007 drawings, offline cache) -- T16.3: `python tests/sample_check.py` and `python tests/critical_reopen_check.py` +| 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 | -Run them one at a time (file-map.md: chained runs exhaust the browser's ports). +T16.2 and T16.3 are done. + +**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/tests/cdp.py b/tests/cdp.py index 6ace6a6..3f93bdf 100644 --- a/tests/cdp.py +++ b/tests/cdp.py @@ -190,8 +190,26 @@ class Browser: f"--user-data-dir={self.profile}", "--remote-allow-origins=*", "--no-first-run", "--no-default-browser-check", "--disable-gpu", "--disable-extensions", "--disable-sync", - "--window-size=1400,1000", "about:blank"], + "--window-size=1400,1000"] + # Run from an elevated (Administrator) shell, Edge and Chrome + # "de-elevate": they relaunch themselves as a normal user through + # Explorer and the launched process exits rc=0. The relaunch does + # not keep the debugging port, so the port is never bound (found + # 2026-10-02; Edge logs "Edge is running elevated: 1"). This + # Chromium switch keeps the process we started. Ignored when the + # shell is not elevated, and on other platforms. + + (["--do-not-de-elevate"] if sys.platform == "win32" else []) + + ["about:blank"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + # On some Windows installs msedge.exe is a launcher: it starts the real + # browser and exits rc=0 at once, and the real browser binds the port a + # moment later. Giving up the instant the launched process exited + # failed every attempt on such a machine although Edge worked when + # started by hand (found 2026-10-02 running the wave 16 probes). An + # rc=0 exit now gets a grace period to bind; a non-zero exit is still + # a failure at once. Teardown is unaffected: close() sweeps by the + # unique profile path, which also catches the handed-off process. + exited_at = None for _ in range(160): try: with urllib.request.urlopen( @@ -199,9 +217,14 @@ class Browser: json.load(r) return except Exception: - if self.proc.poll() is not None: - last = f"exited rc={self.proc.returncode} without binding the port" - break + rc = self.proc.poll() + if rc is not None: + last = f"exited rc={rc} without binding the port" + if rc != 0: + break + exited_at = exited_at or time.time() + if time.time() - exited_at > 15: + break time.sleep(0.25) else: last = "never bound the debugging port" -- 2.49.1 From cfecdca3f78def76df533e2c32ec6f5bbcd6cdad Mon Sep 17 00:00:00 2001 From: Matt Mabrey Date: Fri, 2 Oct 2026 15:06:22 -0700 Subject: [PATCH 7/8] T16.4: record the production check for D20 (no duplicate complete SOPs) (cherry picked from commit 2420c73de476a88422530fead154af64d57b8b0d) --- docs/waves/wave-16.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/waves/wave-16.md b/docs/waves/wave-16.md index 7ed20d2..dda408e 100644 --- a/docs/waves/wave-16.md +++ b/docs/waves/wave-16.md @@ -139,6 +139,10 @@ Python 3.12.10, `.venv`), one at a time:** 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 -- 2.49.1 From b2b3774dea14074bd7764a7f914985e7569ef7fc Mon Sep 17 00:00:00 2001 From: Matt Mabrey Date: Tue, 6 Oct 2026 13:28:22 -0700 Subject: [PATCH 8/8] T16.4: security_check skips the D18 refresh check where D18 is absent Wave 16 rebuilt on main (feat/wave-16-on-main, 2026-10-06) so it can ship without wave 11 and T13.1. main has no sliding refresh, so the one D18 check now runs only when auth.maybe_refresh_token exists; on main it instead proves a valid token near its expiry is still accepted. security_check 36/36 on this branch; smoke 27/27. --- tests/security_check.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/tests/security_check.py b/tests/security_check.py index 310651f..9ee4e62 100644 --- a/tests/security_check.py +++ b/tests/security_check.py @@ -108,9 +108,16 @@ def d21(): "login_at": (now - timedelta(minutes=25)).timestamp(), "exp": now + timedelta(minutes=5)}, auth.SECRET_KEY, algorithm="HS256") r = client(token=near).get("/api/projects") - check("D21", "the D18 sliding refresh still reissues the session", - r.status_code == 200 and auth.COOKIE_NAME in (r.headers.get("set-cookie") or ""), - f"status {r.status_code}") + if hasattr(auth, "maybe_refresh_token"): + check("D21", "the D18 sliding refresh still reissues the session", + r.status_code == 200 and auth.COOKIE_NAME in (r.headers.get("set-cookie") or ""), + f"status {r.status_code}") + else: + # D18 (T13.1) is not on this branch (wave 16 built on main, 2026-10-06): + # there is no refresh to keep working, so prove the stricter decode still + # accepts a valid token about to expire. + check("D21", "a valid token close to its expiry is still accepted (no D18 on this branch)", + r.status_code == 200, f"status {r.status_code}") import re pin = re.search(r"(?im)^pyjwt==([0-9.]+)", open(os.path.join(ROOT, "server", "requirements.txt")).read()) pinned = tuple(int(x) for x in pin.group(1).split(".")) if pin else (0,) -- 2.49.1