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
+133
View File
@@ -0,0 +1,133 @@
"""Against the CI Samba domain controller (deploy/samba). Skipped unless the TEST_LDAP_* values are set.
TEST_LDAP_URL, TEST_LDAP_BASE_DN, TEST_LDAP_BIND_DN, TEST_LDAP_PASSWORD_FILE, TEST_LDAP_GROUP_BASE_DN,
TEST_LDAP_CA_BUNDLE and TEST_DC_USERS_FILE (the users.json the DC seed writes, with per-run passwords).
"""
from __future__ import annotations
import json
import os
from pathlib import Path
from typing import Any
import pytest
from fastapi.testclient import TestClient
from pshelpers import ORIGIN_HEADERS, app_conn, make_settings, needs_pg
from packetstation.auth import groups
from packetstation.auth.directory import refresh_from_ad
from packetstation.auth.ldap import Directory
from packetstation.settings import Settings
ENV = (
"TEST_LDAP_URL",
"TEST_LDAP_BASE_DN",
"TEST_LDAP_BIND_DN",
"TEST_LDAP_PASSWORD_FILE",
"TEST_LDAP_GROUP_BASE_DN",
"TEST_LDAP_CA_BUNDLE",
"TEST_DC_USERS_FILE",
)
MISSING = [k for k in ENV if not os.environ.get(k)]
pytestmark = pytest.mark.skipif(bool(MISSING), reason=f"no test domain controller ({', '.join(MISSING)} not set)")
def ldap_values() -> dict[str, Any]:
return {
"ldap_url": os.environ["TEST_LDAP_URL"],
"ldap_base_dn": os.environ["TEST_LDAP_BASE_DN"],
"ldap_bind_dn": os.environ["TEST_LDAP_BIND_DN"],
"ldap_password_file": Path(os.environ["TEST_LDAP_PASSWORD_FILE"]),
"ldap_group_base_dn": os.environ["TEST_LDAP_GROUP_BASE_DN"],
"ldap_ca_bundle": Path(os.environ["TEST_LDAP_CA_BUNDLE"]),
"ldap_starttls": os.environ.get("TEST_LDAP_STARTTLS", "").lower() == "true",
}
@pytest.fixture(scope="module")
def dc_users() -> dict[str, dict[str, str]]:
data = json.loads(Path(os.environ["TEST_DC_USERS_FILE"]).read_text(encoding="utf-8"))
users: dict[str, dict[str, str]] = data["users"]
return users
@pytest.fixture
def directory(tmp_path: Path) -> Directory:
return Directory(make_settings(tmp_path, **ldap_values()))
def roles_of(d: Directory, login: str) -> list[str]:
u = d.find_user(login)
assert u is not None, login
return groups.roles_from_groups(d.groups_of(u.dn))
def test_password_bind(directory: Directory, dc_users: dict[str, dict[str, str]]) -> None:
u = directory.find_user("clerk.clara")
assert u is not None and not u.disabled and u.emp_no == "4001" and u.display_name == "Clara Clerk"
assert directory.verify_password(u.dn, dc_users["clerk.clara"]["password"]) is True
assert directory.verify_password(u.dn, "not-the-password") is False
assert directory.verify_password(u.dn, "") is False
assert roles_of(directory, "clerk.clara") == ["clerical"]
again = directory.get_user_by_guid(u.guid)
assert again is not None and again.sam_account == "clerk.clara"
def test_nested_and_levels(directory: Directory) -> None:
assert roles_of(directory, "nested.ned") == ["shop:10:worker"]
assert roles_of(directory, "both.bo") == ["shop:03:supervisor"]
assert roles_of(directory, "multi.mia") == ["clerical", "shop:06:supervisor"]
assert roles_of(directory, "norole.nick") == []
def test_disabled_account(directory: Directory, dc_users: dict[str, dict[str, str]]) -> None:
u = directory.find_user("disabled.dan")
assert u is not None and u.disabled is True
assert directory.verify_password(u.dn, dc_users["disabled.dan"]["password"]) is False
def test_group_listing_and_members(directory: Directory) -> None:
found = directory.list_groups()
lower = {g.lower() for g in found}
assert "ps-14-electrical-lead" not in lower and "ps-extra-legacy" in lower
assert sum(1 for n in groups.group_names() if n.lower() in lower) == 49
sams = {u.sam_account for u in directory.members_of("PS-03-WeldParts-Worker")}
assert {"weld.andy", "both.bo", "dup.dave"} <= sams
assert directory.members_of("PS-No-Such-Group") == []
@needs_pg
def test_refresh_flags_duplicates(pg_settings: Settings, directory: Directory) -> None:
with app_conn(pg_settings) as conn:
res = refresh_from_ad(conn, directory)
assert res.groups_missing == ["PS-14-Electrical-Lead"]
assert "9001" in res.emp_duplicate and "noemp.nora" in res.emp_missing
@needs_pg
def test_signin_api_against_dc(
pg_settings: Settings, tmp_path: Path, dev_visual: None, dc_users: dict[str, dict[str, str]]
) -> None:
from packetstation.main import create_app
s = make_settings(
tmp_path / "dc",
**ldap_values(),
**{k: getattr(pg_settings, k) for k in ("pg_host", "pg_port", "pg_database")},
pg_app_password_file=pg_settings.pg_app_password_file,
pg_migrate_password_file=pg_settings.pg_migrate_password_file,
)
with TestClient(create_app(s), headers=ORIGIN_HEADERS) as c:
def signin(sam: str, pw: str | None = None) -> Any:
password = dc_users[sam]["password"] if pw is None else pw
return c.post("/api/auth/signin/password", json={"login": sam, "password": password})
r = signin("clerk.clara")
assert r.status_code == 200 and r.json()["roles"] == ["clerical"]
assert signin("clerk.clara", "wrong").status_code == 401
assert signin("disabled.dan").status_code == 401
r = signin("norole.nick")
assert r.status_code == 403 and r.json()["code"] == "no_role"
assert signin("nested.ned").json()["roles"] == ["shop:10:worker"]