T13.6 (part): test T13.1's sliding session, and record what it found

T13.1 shipped with its done-when list unchecked and no test of its own. Adds
tests/session_idle_check.py (28 checks): continuous activity survives 30 minutes
but not the ceiling, an idle session gets 401, the cookie is not rewritten per
request, a pre-D18 token still gets a ceiling via iat, identity carries forward,
both variables are documented. Mutation-tested (no throttle, no ceiling, a fresh
ceiling for legacy tokens each fail it).

Notes in wave-13.md: /api/auth/* is exempt from the refresh, and the wave exit
criteria say AUTH_SESSION_HOURS 2 while T13.1 and the code say 8.
This commit is contained in:
2026-10-16 11:41:29 -07:00
parent 763ab8d98d
commit 253886923c
2 changed files with 256 additions and 6 deletions

View File

@@ -61,22 +61,40 @@ its own `iat` as `login_at`, not bypass the ceiling entirely.
**Done when:**
- [ ] a session with continuous activity stays alive past 30 minutes but is
- [x] a session with continuous activity stays alive past 30 minutes but is
cut off at the `AUTH_SESSION_HOURS` ceiling regardless
- [ ] a session with no activity for 30+ minutes is rejected on its next
*(2026-10-16, T13.6: a request every minute for 10 hours: alive well past 30 minutes, never extended past login + 8 h, cut off at the ceiling, original `login_at` kept.)*
- [x] a session with no activity for 30+ minutes is rejected on its next
request
- [ ] the cookie is not rewritten on every single request — verify the
*(2026-10-16, T13.6: an idle token gets 401 on a gated route; one inside the window gets 200.)*
- [x] the cookie is not rewritten on every single request — verify the
refresh is throttled, not unconditional
- [ ] a pre-existing token with no `login_at` claim (simulating a session
*(2026-10-16, T13.6: 20 rapid requests on a fresh session: 0 rewrites; 480 requests over 8 h: about one rewrite per 10 minutes; a refreshed cookie is not rewritten again on the next request. Mutation test: removing the throttle fails 3 checks.)*
- [x] a pre-existing token with no `login_at` claim (simulating a session
issued before this shipped) still gets a hard ceiling, via the `iat`
fallback
- [ ] `.env.example` and `DEPLOYMENT.md` explain both variables and flag both
*(2026-10-16, T13.6: a token with iat 9 h ago and a still-valid old exp is not extended; one with iat 1 h ago is refreshed with `login_at` taken from `iat`; no `login_at` and no `iat` is not refreshed and does not crash. Mutation test: giving it a fresh ceiling fails.)*
- [x] `.env.example` and `DEPLOYMENT.md` explain both variables and flag both
defaults as proposed, not confirmed against Okta's own session policy
- [ ] existing session/auth tests updated for the new mechanism, not just a
*(2026-10-16, T13.6: both variables are in both files, and both call the defaults proposed.)*
- [x] existing session/auth tests updated for the new mechanism, not just a
new number
*(2026-10-16, T13.6: there were none. T13.1 shipped with no test of its own. `tests/session_idle_check.py` is that test (T13.6 added it).)*
---
**Found while writing that test (T13.6, 2026-10-16):**
- Nothing under `/api/auth/` slides the session. `auth._EXEMPT_PREFIXES` covers
that whole prefix, so `auth_gate` never refreshes there (including
`/api/auth/me`). A page that only called `/api/auth/me` would not extend its
session. The spec says "after confirming a request is authenticated", and these
routes are not confirmed by the gate, so this is as written. Noted, not changed.
- The wave's exit criteria below say `AUTH_SESSION_HOURS` defaults to **2**. T13.1
(this section), `auth.py`, `.env.example` and `DEPLOYMENT.md` all say **8**. The
code and the T13.1 text agree, so the exit line looks like a leftover from
before the 2026-09-23 revision. Not changed here: it is a product number. Needs
Matt to say which one he means.
### T13.2 — D18: Okta Management API client
- **Items:** `D18`

232
tests/session_idle_check.py Normal file
View File

@@ -0,0 +1,232 @@
#!/usr/bin/env python3
"""Does the sliding session with a hard ceiling work? - D18 / T13.1 (checked in T13.6).
T13.1 shipped with its done-when list unchecked and no test of its own; the old
session tests had no idea about idle time. This is that test.
1. Continuous activity keeps a session alive past 30 minutes, but never past the
absolute ceiling (AUTH_SESSION_HOURS) measured from the ORIGINAL sign-in.
2. A session idle for more than 30 minutes is refused on its next request.
3. The cookie is not rewritten on every request (the refresh is throttled).
4. A token from before this shipped (no login_at) still gets a hard ceiling,
from its iat.
5. A refresh carries identity and login_at forward unchanged.
6. The two variables are documented, and both defaults are flagged as proposed.
Self-contained: throwaway SQLite, in-process test client, no network, no browser.
Exit 0 all passed, 1 a failure.
"""
import os
import re
import sys
import tempfile
from datetime import datetime, timedelta, timezone
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)
os.environ["DATABASE_URL"] = "sqlite:///" + os.path.join(tempfile.mkdtemp(prefix="wp-idle-"), "t.db").replace("\\", "/")
os.environ["AUTH_SECRET_KEY"] = "session-idle-check-secret-not-for-production"
os.environ.pop("AUTH_IDLE_MINUTES", None)
os.environ.pop("AUTH_SESSION_HOURS", None)
import jwt # noqa: E402
from fastapi.testclient import TestClient # noqa: E402
from server import app as appmod, auth, models # noqa: E402
from server.db import Base, SessionLocal, engine # noqa: E402
fails = 0
def chk(label, ok, extra=""):
global fails
print(("PASS " if ok else "FAIL ") + label + (f" [{extra}]" if (extra and not ok) else ""))
if not ok:
fails += 1
Base.metadata.create_all(bind=engine)
with SessionLocal() as db:
db.add(models.User(id="u1", username="alice", email="a@x.test", role=auth.ROLE_ADMIN))
db.commit()
USER = db.get(models.User, "u1")
db.expunge(USER)
# A route the auth gate covers. NOT /api/auth/me: everything under /api/auth/ is
# exempt from the gate (auth._EXEMPT_PREFIXES), so no session refresh happens there
# and a probe on it would pass without testing anything.
PROBE = "/api/projects"
IDLE = auth.IDLE_MINUTES
CEIL_H = auth.SESSION_HOURS
NOW = datetime.now(timezone.utc)
def mint(login_at=None, iat=None, exp=None, **extra):
"""A token with exactly the claims given (None = leave the claim out)."""
p = {"sub": "u1", "username": "alice", "role": auth.ROLE_ADMIN, "ver": 0}
if iat is not None:
p["iat"] = iat
if login_at is not None:
p["login_at"] = login_at.timestamp()
if exp is not None:
p["exp"] = exp
p.update(extra)
return jwt.encode(p, auth.SECRET_KEY, algorithm=auth.JWT_ALG)
def raw_claims(tok):
return jwt.decode(tok, auth.SECRET_KEY, algorithms=[auth.JWT_ALG], options={"verify_exp": False, "verify_iat": False, "verify_nbf": False})
class FakeClock(datetime):
_now = NOW
@classmethod
def now(cls, tz=None):
return cls._now
real_dt = auth.datetime
def at(t):
FakeClock._now = t
auth.datetime = FakeClock
def real():
auth.datetime = real_dt
print("defaults: idle %d min, ceiling %d h" % (IDLE, CEIL_H))
# ── 1. continuous activity, then the ceiling ──────────────────────────────────
print("\n1. continuous activity stays alive past 30 minutes, but is cut off at the ceiling")
at(NOW)
tok = auth.create_token(USER)
c = raw_claims(tok)
chk("a new token carries login_at", "login_at" in c)
chk("a new token expires one idle window out, not at the ceiling",
abs(c["exp"] - (NOW + timedelta(minutes=IDLE)).timestamp()) < 2)
login_at = NOW
cur = c
alive_past_30 = False
rewrites = 0
last_exp = cur["exp"]
t = NOW
STEP = timedelta(minutes=1) # an active user: a request every minute
end = NOW + timedelta(hours=CEIL_H + 2)
cut_off_at = None
while t < end:
t += STEP
at(t)
if cur["exp"] <= t.timestamp(): # the session already lapsed
cut_off_at = t
break
if t - NOW > timedelta(minutes=IDLE):
alive_past_30 = True
new = auth.maybe_refresh_token(cur)
if new:
rewrites += 1
cur = raw_claims(new)
last_exp = cur["exp"]
real()
chk("with a request every minute the session is alive well past 30 minutes", alive_past_30)
chk("it is never extended past the ceiling (last exp <= login + %d h)" % CEIL_H,
last_exp <= (login_at + timedelta(hours=CEIL_H)).timestamp() + 1,
str(datetime.fromtimestamp(last_exp, timezone.utc)))
chk("it IS cut off once the ceiling is reached, however active the session",
cut_off_at is not None and cut_off_at <= login_at + timedelta(hours=CEIL_H) + timedelta(minutes=IDLE) + STEP,
str(cut_off_at))
chk("the claims after the last refresh still carry the ORIGINAL login_at",
abs(cur["login_at"] - login_at.timestamp()) < 1)
steps = int((CEIL_H * 60) / 1)
chk("the cookie was rewritten far less often than once per request (%d rewrites for ~%d requests)" % (rewrites, steps),
0 < rewrites < steps / 5, f"{rewrites}/{steps}")
# ── 2. idle ───────────────────────────────────────────────────────────────────
print("\n2. a session idle for more than %d minutes is refused on its next request" % IDLE)
client = TestClient(appmod.app)
idle_tok = mint(login_at=NOW - timedelta(minutes=IDLE + 1), iat=NOW - timedelta(minutes=IDLE + 1),
exp=NOW - timedelta(minutes=1))
client.cookies.set(auth.COOKIE_NAME, idle_tok)
r = client.get(PROBE)
chk("an idle session gets 401", r.status_code == 401, r.status_code)
live_tok = mint(login_at=NOW - timedelta(minutes=5), iat=NOW - timedelta(minutes=5),
exp=NOW + timedelta(minutes=IDLE - 5))
client.cookies.clear()
client.cookies.set(auth.COOKIE_NAME, live_tok)
chk("a session inside the window gets 200", client.get(PROBE).status_code == 200)
# ── 3. throttle ───────────────────────────────────────────────────────────────
print("\n3. the cookie is not rewritten on every request")
fresh = auth.create_token(USER)
client.cookies.clear()
client.cookies.set(auth.COOKIE_NAME, fresh)
cookies_set = 0
for _ in range(20):
r = client.get(PROBE)
if "set-cookie" in r.headers and auth.COOKIE_NAME in r.headers["set-cookie"]:
cookies_set += 1
chk("20 rapid requests on a fresh session: 0 cookie rewrites", cookies_set == 0, cookies_set)
aged = mint(login_at=NOW - timedelta(minutes=20), iat=NOW - timedelta(minutes=20),
exp=NOW + timedelta(minutes=2)) # 2 minutes of idle window left
client.cookies.clear()
client.cookies.set(auth.COOKIE_NAME, aged)
r = client.get(PROBE)
chk("an aged session gets a refreshed cookie on its next request",
r.status_code == 200 and auth.COOKIE_NAME in r.headers.get("set-cookie", ""))
m = re.search(auth.COOKIE_NAME + r"=([^;]+)", r.headers.get("set-cookie", ""))
newc = raw_claims(m.group(1)) if m else {}
chk("the refreshed cookie keeps the original login_at",
abs(newc.get("login_at", 0) - (NOW - timedelta(minutes=20)).timestamp()) < 1)
client.cookies.clear()
client.cookies.set(auth.COOKIE_NAME, m.group(1) if m else "")
r2 = client.get(PROBE)
chk("...and the very next request does not rewrite it again", auth.COOKIE_NAME not in r2.headers.get("set-cookie", ""))
# ── 4. tokens from before D18 ─────────────────────────────────────────────────
print("\n4. a token with no login_at still gets a hard ceiling (via iat)")
old = {"sub": "u1", "username": "alice", "role": auth.ROLE_ADMIN, "ver": 0,
"iat": (NOW - timedelta(hours=CEIL_H + 1)).timestamp(),
"exp": (NOW + timedelta(hours=3)).timestamp()} # the old flat 12 h exp, still valid
chk("past its iat-based ceiling: no refresh, the old exp is not extended", auth.maybe_refresh_token(old) is None)
young = {"sub": "u1", "username": "alice", "role": auth.ROLE_ADMIN, "ver": 0,
"iat": (NOW - timedelta(hours=1)).timestamp(),
"exp": (NOW + timedelta(minutes=2)).timestamp()}
ref = auth.maybe_refresh_token(young)
rc = raw_claims(ref) if ref else {}
chk("inside the ceiling: refreshed, and login_at is taken from iat (not 'now')",
bool(ref) and abs(rc["login_at"] - young["iat"]) < 1)
chk("the refreshed token cannot outlive iat + ceiling",
bool(ref) and rc["exp"] <= young["iat"] + CEIL_H * 3600 + 1)
nothing = {"sub": "u1", "username": "alice", "role": auth.ROLE_ADMIN, "ver": 0,
"exp": (NOW + timedelta(minutes=2)).timestamp()}
chk("no login_at and no iat: no refresh, and no crash", auth.maybe_refresh_token(nothing) is None)
junk = dict(young, login_at="not-a-number")
chk("an unparseable login_at falls back to iat, no crash", auth.maybe_refresh_token(junk) is not None)
# ── 5. identity carried forward ───────────────────────────────────────────────
print("\n5. a refresh carries the identity forward unchanged")
src = {"sub": "u9", "username": "zed", "role": "project_admin", "ver": 7,
"iat": (NOW - timedelta(minutes=20)).timestamp(),
"login_at": (NOW - timedelta(minutes=20)).timestamp(),
"exp": (NOW + timedelta(minutes=2)).timestamp()}
rc = raw_claims(auth.maybe_refresh_token(src))
chk("sub, username, role, ver are unchanged",
(rc["sub"], rc["username"], rc["role"], rc["ver"]) == ("u9", "zed", "project_admin", 7))
# ── 6. documentation ──────────────────────────────────────────────────────────
print("\n6. the two variables are documented, defaults flagged as proposed")
env = open(os.path.join(ROOT, "server", ".env.example"), encoding="utf-8").read()
dep = open(os.path.join(ROOT, "DEPLOYMENT.md"), encoding="utf-8").read()
for name in ("AUTH_IDLE_MINUTES", "AUTH_SESSION_HOURS"):
chk(f"{name} is in .env.example", name in env)
chk(f"{name} is in DEPLOYMENT.md", name in dep)
chk(".env.example calls the defaults proposed, not confirmed", re.search(r"propos", env, re.I) is not None)
chk("DEPLOYMENT.md calls the defaults proposed, not confirmed", re.search(r"propos", dep, re.I) is not None)
print()
print("ALL PASSED" if not fails else f"{fails} FAILED")
sys.exit(0 if not fails else 1)