Files
PacketStation/tests/server/pshelpers.py
T
spencermandClaude Fable 5.1 97b0973130 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]>
2026-10-16 07:40:29 -06:00

93 lines
3.2 KiB
Python

"""Helpers shared by the server tests."""
from __future__ import annotations
import os
from pathlib import Path
from types import SimpleNamespace
from typing import Any
import pytest
from packetstation.settings import Settings
TEST_SESSION_KEY = "test-session-key-0123456789abcdef0123456789"
ORIGIN_HEADERS = {"Origin": "http://testserver", "X-Requested-With": "PacketStation"}
def make_settings(tmp: Path, **over: Any) -> Settings:
"""Settings for tests. Writes a throwaway session key file unless `session_key_file` is given."""
if "session_key_file" not in over:
key_file = tmp / "session_key"
if not key_file.exists():
key_file.parent.mkdir(parents=True, exist_ok=True)
key_file.write_text(TEST_SESSION_KEY + "\n")
over["session_key_file"] = key_file
values: dict[str, Any] = {
"_env_file": None,
"stack": "ci",
"trusted_proxy_host": "",
"static_dir": tmp / "no-static",
"assets_dir": tmp / "assets",
"backup_dir": tmp / "no-backups",
}
values.update(over)
return Settings(**values)
def fake_visual(production: bool = False, explicit: bool = False) -> SimpleNamespace:
server, database = ("vsql", "PESCOINC") if production else (r"VSQL\DEV", "PESCOINCDEV")
return SimpleNamespace(
is_production=production,
server=server,
database=database,
model_fields_set={"server", "database"} if explicit else set(),
)
PG_URL = os.environ.get("TEST_PG_SUPERUSER_URL")
needs_pg = pytest.mark.skipif(not PG_URL, reason="TEST_PG_SUPERUSER_URL not set (no PostgreSQL)")
def sign_in(client: Any, login: str, password: str | None = None) -> Any:
"""Password sign-in through the API (FakeDirectory password by default); returns the response."""
from fakedir import FAKE_PASSWORD
return client.post(
"/api/auth/signin/password", json={"login": login, "password": FAKE_PASSWORD if password is None else password}
)
def app_conn(settings: Settings) -> Any:
"""An autocommit connection as the app role (for test setup and checks)."""
from packetstation import db
return db.connect_as("app", settings, autocommit=True)
PIN = "246810"
def register_device(client: Any, sam: str = "sup.wes", name: str = "Bldg 2 tablet 3") -> dict[str, str]:
assert sign_in(client, sam).status_code == 200
r = client.post("/api/account/device", json={"name": name})
assert r.status_code == 200, r.text
assert "ps_device=" in r.headers["set-cookie"] and "max-age=31536000" in r.headers["set-cookie"].lower()
assert client.post("/api/auth/signout").status_code == 204
device: dict[str, str] = r.json()["device"]
return device
def set_pin(client: Any, sam: str, pin: str = PIN) -> None:
from fakedir import FAKE_PASSWORD
assert sign_in(client, sam).status_code == 200
r = client.post("/api/account/pin", json={"password": FAKE_PASSWORD, "pin": pin})
assert r.status_code == 200, r.text
assert r.json() == {"pin": {"set": True, "disabled": False}}
assert client.post("/api/auth/signout").status_code == 204
def pin_signin(client: Any, emp_no: str, pin: str = PIN) -> Any:
return client.post("/api/auth/signin/pin", json={"emp_no": emp_no, "pin": pin})