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. Againstda1325cwith 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 commit01ce7e941c)
140 lines
5.5 KiB
Python
140 lines
5.5 KiB
Python
#!/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())
|