Phase 1: identity, sessions, audit, frontend shell

AD sign-in over LDAPS (search with the service account, bind as the user,
nested groups through LDAP_MATCHING_RULE_IN_CHAIN, disabled accounts refused),
roles as the union of PS-* groups mapped by a table derived from the seeded
departments. Server-side sessions with idle, lock and absolute timeouts, Origin
and X-Requested-With check, step-up unlock. Optional Argon2id PIN set with the
domain password; PIN sign-in by employee ID on registered devices only; five
wrong attempts disable the PIN, three wrong at unlock or signature end the
session. Rate limits per account and per address before any bind. Devices,
signatures table and sign helper, audit rows for every identity event, SSE over
LISTEN/NOTIFY with presence. Account settings and Admin APIs and screens
(AD view, devices, PIN clearing, group map with missing-group flags, refresh
from AD now). CLI ad-groups --list and ad-refresh. Migration 0002.

Frontend: real sign-in (password tab, PIN keypad on registered devices), lock
screen, role switcher, Account settings, Admin shell, screen placeholders.

CI: Samba AD DC container (PSTEST.LOCAL) with a generated CA, 49 of the 50
groups plus one extra, 17 test users; wired into the CI compose overlay and
the Gitea workflow; Playwright sign-in scenario.

Verified on docker-1: 171 server tests green inside the CI stack against
PostgreSQL and the Samba DC, 48 frontend tests, 8 Playwright scenarios against
the live stack (password and PIN sign-in, lock and unlock, Admin group map).
Findings recorded in the docs: the DC needs CAP_SYS_ADMIN, a hidden tab locks
only after a minute as the old build did,
and the app uses the alias ps-app for Playwright because "app" is on
Chromium's HSTS preload list.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
This commit is contained in:
2026-10-16 07:40:29 -06:00
co-authored by Claude Fable 5.1
parent 0b663bb2b2
commit 97b0973130
95 changed files with 9609 additions and 183 deletions
+140
View File
@@ -0,0 +1,140 @@
"""The Packet Station PIN: format, hashing, and the whole lifecycle through the API."""
from __future__ import annotations
from pathlib import Path
import pytest
from fakedir import FAKE_PASSWORD, FakeDirectory
from fastapi.testclient import TestClient
from pshelpers import PIN, app_conn, make_settings, needs_pg, pin_signin, register_device, set_pin, sign_in
from packetstation.auth import pin as pins
from packetstation.settings import Settings
@pytest.mark.parametrize(
("value", "ok"),
[
("123456", True),
("123456789012", True),
("12345", False),
("1234567890123", False),
("12345a", False),
("١٢٣٤٥٦", False),
("", False),
],
)
def test_format(tmp_path: Path, value: str, ok: bool) -> None:
assert pins.valid_format(value, make_settings(tmp_path)) is ok
def test_hash_is_argon2id_and_verifies() -> None:
h = pins.hash_pin(PIN)
assert h.startswith("$argon2id$") and PIN not in h
assert pins.verify_hash(h, PIN) and not pins.verify_hash(h, "135791") and not pins.verify_hash("junk", PIN)
@needs_pg
def test_pin_needs_a_registered_device(pg_client: TestClient) -> None:
set_pin(pg_client, "weld.andy")
r = pg_client.post("/api/auth/signin/pin", json={"emp_no": "3003", "pin": PIN})
assert r.status_code == 403 and r.json()["code"] == "device_required"
assert pg_client.get("/api/auth/context").json()["device"] is None
@needs_pg
def test_only_registrars_register_devices(pg_client: TestClient) -> None:
sign_in(pg_client, "weld.andy")
r = pg_client.post("/api/account/device", json={"name": "x"})
assert r.status_code == 403
sign_in(pg_client, "lead.lou")
assert pg_client.post("/api/account/device", json={"name": "x"}).status_code == 403
sign_in(pg_client, "admin.ann")
assert pg_client.post("/api/account/device", json={"name": "Office PC"}).status_code == 200
@needs_pg
def test_pin_set_rules(pg_client: TestClient, pg_settings: Settings) -> None:
sign_in(pg_client, "weld.andy")
r = pg_client.post("/api/account/pin", json={"password": FAKE_PASSWORD, "pin": "12ab56"})
assert r.status_code == 400 and r.json()["code"] == "invalid_pin"
r = pg_client.post("/api/account/pin", json={"password": "wrong", "pin": PIN})
assert r.status_code == 403 and r.json()["code"] == "bad_password"
assert pg_client.get("/api/account").json()["pin"] == {"set": False, "disabled": False}
with app_conn(pg_settings) as conn:
row = conn.execute("SELECT account, kind, reason FROM signin_attempts WHERE NOT ok").fetchone()
assert row[0].startswith("user:") and row[1:] == ("pin_set", "bad_password")
assert conn.execute("SELECT count(*) FROM user_pins").fetchone()[0] == 0
@needs_pg
def test_pin_lifecycle(pg_client: TestClient, pg_settings: Settings, fake_dir: FakeDirectory) -> None:
device = register_device(pg_client)
assert pg_client.get("/api/auth/context").json()["device"] == device
set_pin(pg_client, "weld.andy")
r = pin_signin(pg_client, "3003")
assert r.status_code == 200, r.text
me = r.json()
assert me["session"]["kind"] == "pin" and me["session"]["device"] == device
assert me["roles"] == ["shop:03:worker"] and me["pin"] == {"set": True, "disabled": False}
# A PIN session cannot change account settings
r = pg_client.post("/api/account/pin", json={"password": FAKE_PASSWORD, "pin": "135791"})
assert r.status_code == 403 and r.json()["code"] == "password_session_required"
with app_conn(pg_settings) as conn:
hours = conn.execute(
"SELECT extract(epoch FROM expires_at - created_at) / 3600 FROM sessions WHERE id = %s",
(me["session"]["id"],),
).fetchone()[0]
assert float(hours) == 10
detail = conn.execute(
"SELECT detail FROM audit_events WHERE action = 'auth.signin' ORDER BY id DESC"
).fetchone()
assert detail[0] == {"kind": "pin", "device_id": device["id"], "device_name": device["name"]}
log = pg_client.get("/api/account/access-log").json()
assert any(e["action"] == "auth.signin" and e["detail"]["device_name"] == device["name"] for e in log)
pg_client.post("/api/auth/signout")
# Unknown, duplicate and wrong all answer the same
for emp in ("0000", "9001"):
r = pin_signin(pg_client, emp)
assert r.status_code == 401 and r.json() == {"detail": "Sign-in failed.", "code": "signin_failed"}
# Five wrong PINs disable it
for _ in range(5):
assert pin_signin(pg_client, "3003", "000000").status_code == 401
with app_conn(pg_settings) as conn:
failed, disabled = conn.execute("SELECT failed_count, disabled_at IS NOT NULL FROM user_pins").fetchone()
assert failed == 5 and disabled
assert conn.execute("SELECT count(*) FROM audit_events WHERE action = 'pin.disabled'").fetchone()[0] == 1
assert pin_signin(pg_client, "3003").status_code in (401, 429) # disabled (and the account is now limited)
# A password sign-in and a new PIN bring it back
set_pin(pg_client, "weld.andy", "13579135")
with app_conn(pg_settings) as conn:
assert conn.execute("SELECT failed_count, disabled_at FROM user_pins").fetchone() == (0, None)
assert conn.execute("SELECT count(*) FROM audit_events WHERE action = 'pin.set'").fetchone()[0] == 2
@needs_pg
def test_pin_unlock_failures_count_and_end_session(pg_client: TestClient, pg_settings: Settings) -> None:
register_device(pg_client)
set_pin(pg_client, "weld.andy")
assert pin_signin(pg_client, "3003").status_code == 200
pg_client.post("/api/auth/lock")
r = pg_client.post("/api/auth/unlock", json={"factor": "pin", "secret": "111111"})
assert r.status_code == 403 and r.json()["attempts_left"] == 2
r = pg_client.post("/api/auth/unlock", json={"factor": "pin", "secret": PIN})
assert r.status_code == 200 and r.json()["session"]["locked"] is False
with app_conn(pg_settings) as conn:
assert conn.execute("SELECT failed_count FROM user_pins").fetchone()[0] == 0
pg_client.post("/api/auth/lock")
for _ in range(2):
assert pg_client.post("/api/auth/unlock", json={"factor": "pin", "secret": "111111"}).status_code == 403
r = pg_client.post("/api/auth/unlock", json={"factor": "pin", "secret": "111111"})
assert r.status_code == 401 and r.json()["code"] == "session_ended"
with app_conn(pg_settings) as conn:
assert conn.execute("SELECT failed_count FROM user_pins").fetchone()[0] == 3
reason = conn.execute("SELECT revoked_reason FROM sessions WHERE kind = 'pin'").fetchone()[0]
assert reason == "stepup_failures"