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.
This commit is contained in:
2026-10-02 13:51:43 -07:00
parent 1c221a122e
commit 01ce7e941c
3 changed files with 162 additions and 4 deletions

View File

@@ -256,12 +256,29 @@ def maybe_refresh_token(claims: dict) -> Optional[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

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

139
tests/security_check.py Normal file
View File

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