Files
Project-SDE-WP-Suite/tests/security_check.py
Matt Mabrey 7bd5ab104d T16.3: D20 one SOP per project
- A SOP posted with no id lands on sop__<project_id>, 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.
2026-10-02 13:56:47 -07:00

264 lines
14 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/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")
# ── 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())