feat/wave-16-on-main #3

Merged
m.mabrey merged 8 commits from feat/wave-16-on-main into main 2026-10-06 22:40:22 +00:00
8 changed files with 697 additions and 33 deletions

View File

@@ -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__<project_id>`. 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__<project_id>` 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.

155
docs/waves/wave-16.md Normal file
View File

@@ -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__<project_id>`
- [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.

View File

@@ -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__<project_id>` (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}")

View File

@@ -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

66
server/files_http.py Normal file
View File

@@ -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 <script>. GET /api/files/{id} used to
return every file `inline` with the uploader's content type, on the app's own
origin, so a script inside an SVG ran as whoever opened the drawing - with
their session, and with an admin's power if an admin opened it.
The download name was built by hand with only `"` removed. A name outside
Latin-1 (`Plan é.pdf`) made the header unencodable, so the download failed
with 500; CR/LF in a name went into the header as typed.
THE RULE (D19, decided 2026-10-02)
* PDF and raster images open INLINE, exactly as before. That is what the
creator's drawing list, the printed package and Field View link to
(CR-007), and the offline drawing cache in sw.js stores.
* Every other type, SVG included, is an ATTACHMENT inside a sandbox: the
browser saves it instead of rendering it on our origin, and
`Content-Security-Policy: sandbox` strips script and same-origin access
even if someone opens the saved response directly.
* SVG UPLOADS STAY ACCEPTED (decided: accept, download only). The fix is on
the way out, so SVGs already in the database are covered too.
* `Cache-Control` is unchanged - the offline drawing cache depends on it.
"""
from __future__ import annotations
import re
from urllib.parse import quote
from fastapi.responses import Response
# Formats a browser shows as inert pixels, or in its own PDF viewer.
INLINE_SAFE_MIME = frozenset({
"application/pdf",
"image/png", "image/jpeg", "image/gif", "image/webp", "image/bmp", "image/avif",
})
# Control characters, and the characters that end or escape a quoted
# header parameter. Replaced, never passed through.
_UNSAFE_NAME = re.compile(r'[\x00-\x1f\x7f"\\;]')
def content_disposition(disposition: str, name: str) -> str:
"""A header value that is valid for ANY user-supplied file name: an ASCII
fallback for old clients plus RFC 5987 `filename*` with the real name."""
name = _UNSAFE_NAME.sub("_", name or "file").strip() or "file"
ascii_name = name.encode("ascii", "replace").decode("ascii").replace("?", "_")
return f"{disposition}; filename=\"{ascii_name}\"; filename*=UTF-8''{quote(name, safe='')}"
def file_response(row) -> Response:
"""The response for GET /api/files/{id}. `row` is a models.WpFile."""
mime = (row.mime or "application/octet-stream").lower()
headers = {
"Cache-Control": "private, max-age=86400", # unchanged: sw.js caches drawings offline
"X-Content-Type-Options": "nosniff", # NGINX adds it too; the dev server did not
}
if mime in INLINE_SAFE_MIME:
headers["Content-Disposition"] = content_disposition("inline", row.name)
else:
headers["Content-Disposition"] = content_disposition("attachment", row.name)
headers["Content-Security-Policy"] = "sandbox; default-src 'none'"
return Response(content=row.data, media_type=mime, headers=headers)

View File

@@ -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

View File

@@ -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"

270
tests/security_check.py Normal file
View File

@@ -0,0 +1,270 @@
#!/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")
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,)
check("D21", "server/requirements.txt pins PyJWT 2.15.1 or later", pinned >= (2, 15, 1),
pin.group(1) if pin else "no pin")
# ── D19: uploaded files download safely ──────────────────────────────────────
def d19():
print("\nD19 uploaded files download safely")
r = as_member.post("/api/wps", json={"id": "wp_files", "project_id": "proj_a", "number": "F1"})
assert r.status_code == 200, r.text
def upload(name, mime, data):
r = as_member.post("/api/wps/wp_files/files", json={
"name": name, "mime": mime, "data_base64": base64.b64encode(data).decode()})
return r.status_code, (r.json().get("file") or {}).get("id")
code, svg = upload("route.svg", "image/svg+xml",
b'<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>')
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__<project_id>",
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())