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
+1
View File
@@ -0,0 +1 @@
"""Identity: AD groups and roles, LDAP, sessions, devices, PINs, rate limits, step-up and signatures."""
+63
View File
@@ -0,0 +1,63 @@
"""Registered devices (shop tablets). Only a registered device may offer PIN sign-in."""
from __future__ import annotations
import uuid
from typing import Any
from psycopg.rows import dict_row
from .sessions import new_token, token_hash
NAME_MAX = 80
def register(conn: Any, key: bytes, *, name: str, user_id: Any) -> tuple[str, uuid.UUID]:
"""Insert a device; returns (cookie token, device id)."""
token = new_token()
row = conn.execute(
"INSERT INTO devices (name, token_hash, registered_by, registered_at, last_seen_at)"
" VALUES (%s, %s, %s, now(), now()) RETURNING id",
(name, token_hash(key, token), user_id),
).fetchone()
return token, row[0]
def find(conn: Any, key: bytes, token: str | None) -> dict[str, Any] | None:
"""The unrevoked device for a cookie token, or None."""
if not token:
return None
with conn.cursor(row_factory=dict_row) as cur:
row: dict[str, Any] | None = cur.execute(
"SELECT id, name, registered_at, last_seen_at FROM devices WHERE token_hash = %s AND revoked_at IS NULL",
(token_hash(key, token),),
).fetchone()
return row
def touch(conn: Any, device_id: Any) -> None:
conn.execute(
"UPDATE devices SET last_seen_at = now() WHERE id = %s"
" AND (last_seen_at IS NULL OR last_seen_at < now() - interval '1 minute')",
(device_id,),
)
def get(conn: Any, device_id: Any) -> dict[str, Any] | None:
with conn.cursor(row_factory=dict_row) as cur:
row: dict[str, Any] | None = cur.execute(
"SELECT id, name, revoked_at FROM devices WHERE id = %s", (device_id,)
).fetchone()
return row
def revoke(conn: Any, device_id: Any, by: Any) -> bool:
row = conn.execute(
"UPDATE devices SET revoked_at = now(), revoked_by = %s WHERE id = %s AND revoked_at IS NULL RETURNING id",
(by, device_id),
).fetchone()
return row is not None
def public(row: dict[str, Any] | None) -> dict[str, Any] | None:
return None if row is None else {"id": str(row["id"]), "name": row["name"]}
+247
View File
@@ -0,0 +1,247 @@
"""The cached directory: `users` and `user_roles` rows written from what AD reports.
Packet Station grants no roles. `user_roles` is a cache of the roles AD groups give, rebuilt at every
sign-in, on the session's roles refresh and by the AD refresh.
"""
from __future__ import annotations
import logging
import uuid
from collections import Counter
from dataclasses import dataclass, field
from typing import Any
from psycopg.rows import dict_row
from psycopg.types.json import Jsonb
from .. import audit
from . import groups as groupmap
from . import sessions
from .ldap import AdUser, DirectoryProtocol
log = logging.getLogger(__name__)
def upsert_user(conn: Any, u: AdUser, *, groups: list[str], signin: bool = False) -> bool:
"""Insert or refresh the users row for an AD account. True when the row is new.
A different, older row holding the same sAMAccountName (a deleted and re-created AD account) is renamed
and marked inactive so the unique index holds and its history keeps its name.
"""
with conn.transaction():
conn.execute(
"UPDATE users SET sam_account = sam_account || '~' || left(id::text, 8), active = false"
" WHERE lower(sam_account) = lower(%s) AND id <> %s",
(u.sam_account, u.guid),
)
flags = {"disabled": u.disabled, "emp_missing": not u.emp_no, "groups": groups}
row = conn.execute(
"INSERT INTO users (id, sam_account, upn, display_name, emp_no, email, active, directory_flags,"
" ad_synced_at, last_signin_at)"
" VALUES (%s, %s, %s, %s, %s, %s, %s, %s, now(), CASE WHEN %s THEN now() END)"
" ON CONFLICT (id) DO UPDATE SET sam_account = EXCLUDED.sam_account, upn = EXCLUDED.upn,"
" display_name = EXCLUDED.display_name, emp_no = EXCLUDED.emp_no, email = EXCLUDED.email,"
" active = EXCLUDED.active, directory_flags = users.directory_flags || EXCLUDED.directory_flags,"
" ad_synced_at = now(), last_signin_at = coalesce(EXCLUDED.last_signin_at, users.last_signin_at)"
" RETURNING (xmax = 0) AS inserted",
(
u.guid,
u.sam_account,
u.upn,
u.display_name,
u.emp_no,
u.email,
not u.disabled,
Jsonb(flags),
signin,
),
).fetchone()
return bool(row[0])
def set_roles(conn: Any, user_id: Any, roles: list[str]) -> None:
"""Rebuild a user's `user_roles` rows from role strings."""
with conn.transaction():
conn.execute("DELETE FROM user_roles WHERE user_id = %s", (user_id,))
for text in roles:
r = groupmap.parse_role(text)
conn.execute(
"INSERT INTO user_roles (user_id, role, dept_code) VALUES (%s, %s::role_kind, %s)",
(user_id, r.kind, r.dept_code),
)
def roles_of(conn: Any, user_id: Any) -> list[str]:
rows = conn.execute("SELECT role::text, dept_code FROM user_roles WHERE user_id = %s", (user_id,)).fetchall()
return groupmap.current().sort_roles(groupmap.role_from_row(r[0], r[1]) for r in rows)
def get_user(conn: Any, user_id: Any) -> dict[str, Any] | None:
with conn.cursor(row_factory=dict_row) as cur:
row: dict[str, Any] | None = cur.execute("SELECT * FROM users WHERE id = %s", (user_id,)).fetchone()
return row
def mark_inactive(conn: Any, user_id: Any, *, reason: str, gone: bool) -> None:
conn.execute(
"UPDATE users SET active = false, directory_flags = directory_flags || %s, ad_synced_at = now() WHERE id = %s",
(Jsonb({"disabled": not gone, "gone": gone}), user_id),
)
conn.execute("DELETE FROM user_roles WHERE user_id = %s", (user_id,))
sessions.revoke_user(conn, user_id, reason)
def public_user(row: dict[str, Any]) -> dict[str, Any]:
return {
"id": str(row["id"]),
"sam_account": row["sam_account"],
"upn": row.get("upn"),
"display_name": row["display_name"],
"emp_no": row.get("emp_no"),
"email": row.get("email"),
}
def ad_user_public(u: AdUser) -> dict[str, Any]:
return {
"id": str(u.guid),
"dn": u.dn,
"sam_account": u.sam_account,
"upn": u.upn,
"display_name": u.display_name,
"emp_no": u.emp_no,
"email": u.email,
}
# ---------------------------------------------------------------- AD refresh
@dataclass
class RefreshResult:
groups_checked: int = 0
groups_missing: list[str] = field(default_factory=list)
users_seen: int = 0
created: int = 0
updated: int = 0
deactivated: int = 0
emp_missing: list[str] = field(default_factory=list)
emp_duplicate: list[str] = field(default_factory=list)
def as_dict(self) -> dict[str, Any]:
return {
"groups_checked": self.groups_checked,
"groups_missing": self.groups_missing,
"users_seen": self.users_seen,
"created": self.created,
"updated": self.updated,
"deactivated": self.deactivated,
"emp_missing": self.emp_missing,
"emp_duplicate": self.emp_duplicate,
}
def refresh_from_ad(
conn: Any, directory: DirectoryProtocol, *, actor: sessions.Actor | None = None, ip: str | None = None
) -> RefreshResult:
"""Enumerate every mapped group, upsert its members and rebuild their roles; deactivate gone accounts.
All AD reads happen first, then the database writes in one transaction, so no lock is held while AD
answers. Raises LdapUnavailable when AD cannot be read.
"""
res = RefreshResult()
names = groupmap.group_names()
in_ad = {g.lower() for g in directory.list_groups()}
res.groups_missing = [n for n in names if n.lower() not in in_ad]
present = [n for n in names if n.lower() in in_ad]
seen: dict[uuid.UUID, AdUser] = {}
member_groups: dict[uuid.UUID, set[str]] = {}
for name in present:
for u in directory.members_of(name):
seen.setdefault(u.guid, u)
member_groups.setdefault(u.guid, set()).add(name)
res.groups_checked = len(present)
res.users_seen = len(seen)
known = conn.execute("SELECT id FROM users WHERE active").fetchall()
unseen = [r[0] for r in known if r[0] not in seen]
# Accounts not in any group: still in AD (keep, no roles), disabled, or gone
unseen_state: dict[uuid.UUID, AdUser | None] = {uid: directory.get_user_by_guid(uid) for uid in unseen}
enabled = [u for u in seen.values() if not u.disabled]
res.emp_missing = sorted(u.sam_account for u in enabled if not u.emp_no)
counts = Counter(u.emp_no for u in enabled if u.emp_no)
res.emp_duplicate = sorted(e for e, n in counts.items() if n > 1)
dup = set(res.emp_duplicate)
with conn.transaction():
for guid, u in seen.items():
grp = groupmap.mapped_groups(member_groups[guid])
was_active_row = conn.execute("SELECT active FROM users WHERE id = %s", (guid,)).fetchone()
created = upsert_user(conn, u, groups=grp)
conn.execute(
"UPDATE users SET directory_flags = directory_flags || %s WHERE id = %s",
(Jsonb({"emp_duplicate": bool(u.emp_no and u.emp_no in dup), "gone": False}), guid),
)
if created:
res.created += 1
else:
res.updated += 1
if u.disabled:
set_roles(conn, guid, [])
sessions.revoke_user(conn, guid, "ad_disabled")
if was_active_row is not None and was_active_row[0]:
res.deactivated += 1
audit.append(
conn,
action="ad.user_deactivated",
user_id=actor.user_id if actor else None,
session_id=actor.session_id if actor else None,
role_snapshot=actor.role_snapshot if actor else None,
subject_type="user",
subject_id=guid,
detail={"reason": "disabled", "sam_account": u.sam_account},
ip=ip,
)
else:
set_roles(conn, guid, groupmap.roles_from_groups(grp))
for uid, found in unseen_state.items():
if found is None or found.disabled:
mark_inactive(conn, uid, reason="ad_disabled" if found else "ad_gone", gone=found is None)
res.deactivated += 1
audit.append(
conn,
action="ad.user_deactivated",
user_id=actor.user_id if actor else None,
session_id=actor.session_id if actor else None,
role_snapshot=actor.role_snapshot if actor else None,
subject_type="user",
subject_id=uid,
detail={"reason": "gone" if found is None else "disabled"},
ip=ip,
)
else:
upsert_user(conn, found, groups=[])
set_roles(conn, uid, [])
sessions.revoke_user(conn, uid, "roles_lost")
audit.append(
conn,
action="ad.refresh",
user_id=actor.user_id if actor else None,
session_id=actor.session_id if actor else None,
role_snapshot=actor.role_snapshot if actor else None,
detail={
"groups_checked": res.groups_checked,
"groups_missing": len(res.groups_missing),
"users_seen": res.users_seen,
"created": res.created,
"updated": res.updated,
"deactivated": res.deactivated,
"emp_missing": len(res.emp_missing),
"emp_duplicate": len(res.emp_duplicate),
},
ip=ip,
)
log.info("AD refresh: %s", {k: v for k, v in res.as_dict().items() if isinstance(v, int)})
return res
+236
View File
@@ -0,0 +1,236 @@
"""The derived group-to-role map. Roles come only from AD groups; nothing in the app can change the map.
The department table is seed data (migration 0002). The map is built from it plus `PS-Admins`.
`DEPARTMENTS` here mirrors the seed so the map works without a database (CLI, tests).
"""
from __future__ import annotations
from collections.abc import Iterable, Sequence
from dataclasses import dataclass
from typing import Any
ADMIN_GROUP = "PS-Admins"
SHOP_LEVELS = ("worker", "lead", "supervisor")
SCREENS = ("clerical", "warehouse", "supervisor", "stall", "qc", "pm", "admin")
# Office role kinds per support department code: (member kind, supervisor kind or None)
OFFICE_KINDS: dict[str, tuple[str, str | None]] = {
"CL": ("clerical", "clerical_supervisor"),
"WH": ("warehouse", "warehouse_supervisor"),
"QC": ("qc", "qc_supervisor"),
"PM": ("pm", None),
}
OFFICE_DEPT: dict[str, str] = {kind: code for code, kinds in OFFICE_KINDS.items() for kind in kinds if kind}
ROLE_KINDS = (
"admin",
"clerical",
"clerical_supervisor",
"warehouse",
"warehouse_supervisor",
"qc",
"qc_supervisor",
"pm",
"shop_worker",
"shop_lead",
"shop_supervisor",
)
@dataclass(frozen=True)
class Department:
code: str
slug: str
name: str
kind: str # support | shop
sort: int
supervisor_group: bool = True
active: bool = True
def _stations(prefix: str, n: int) -> tuple[str, ...]:
return tuple(f"{prefix} {i}" for i in range(1, n + 1))
# code, slug, name, kind, supervisor_group, stations. Mirrors the seed in migration 0002.
SEED: tuple[tuple[str, str, str, str, bool, tuple[str, ...]], ...] = (
("CL", "Clerical", "Clerical", "support", True, ()),
("WH", "Warehouse", "Warehouse", "support", True, ()),
("QC", "QC", "Q.C.", "support", True, ()),
("PM", "ProjectMgmt", "Project Management", "support", False, ()),
("01", "Layout", "Layout", "shop", True, _stations("Station", 4)),
("02", "SouthLayout", "PESCO South Layout", "shop", True, _stations("Station", 4)),
("03", "WeldParts", "Weld Parts", "shop", True, _stations("Stall", 6)),
("04", "SouthWeld", "PESCO South Weld", "shop", True, _stations("Stall", 6)),
("05", "SouthWeldSS", "PESCO South Weld SS", "shop", True, _stations("Stall", 6)),
("06", "CodeBldg2", "Code Bldg 2", "shop", True, _stations("Stall", 6)),
("07", "CodeBldg3", "Code Bldg 3", "shop", True, _stations("Stall", 6)),
("08", "Subassembly", "Subassembly", "shop", True, _stations("Station", 4)),
("09", "Hydro", "Hydro", "shop", True, ("Hydro Bay 1", "Hydro Bay 2")),
("10", "WeldAssembly", "Weld Assembly", "shop", True, _stations("Stall", 6)),
("11", "FinalAssyNorth", "Final Assembly - North", "shop", True, _stations("Station", 4)),
("12", "FinalAssySouth", "Final Assembly - South", "shop", True, _stations("Station", 4)),
("13", "PaintSandblast", "Paint-Sandblast", "shop", True, ("Blast Booth", "Paint Booth 1", "Paint Booth 2")),
("14", "Electrical", "Electrical", "shop", True, _stations("Station", 4)),
)
DEPARTMENTS: tuple[Department, ...] = tuple(
Department(code, slug, name, kind, (i + 1) * 10, sup) for i, (code, slug, name, kind, sup, _) in enumerate(SEED)
)
@dataclass(frozen=True)
class Role:
"""One role: a kind and its department code (None for admin)."""
kind: str
dept_code: str | None = None
def __str__(self) -> str:
if self.kind.startswith("shop_"):
return f"shop:{self.dept_code}:{self.kind.removeprefix('shop_')}"
return self.kind
def parse_role(text: str) -> Role:
"""`"shop:03:supervisor"` -> Role("shop_supervisor", "03"); `"clerical"` -> Role("clerical", "CL")."""
if text.startswith("shop:"):
parts = text.split(":")
if len(parts) != 3 or parts[2] not in SHOP_LEVELS or not parts[1]:
raise ValueError(f"bad role {text!r}")
return Role(f"shop_{parts[2]}", parts[1])
if text == "admin":
return Role("admin", None)
if text in OFFICE_DEPT:
return Role(text, OFFICE_DEPT[text])
raise ValueError(f"bad role {text!r}")
def role_from_row(kind: str, dept_code: str | None) -> str:
"""The role string for a `user_roles` row."""
return str(Role(kind, dept_code))
def _level(r: Role) -> int:
return SHOP_LEVELS.index(r.kind.removeprefix("shop_"))
class GroupMap:
"""Group name -> Role for a list of departments. Matching is case-insensitive on the cn."""
def __init__(self, departments: Sequence[Department]):
self.departments = sorted(departments, key=lambda d: (0 if d.kind == "support" else 1, d.sort, d.code))
self.entries: list[tuple[str, Role]] = [(ADMIN_GROUP, Role("admin"))]
for d in self.departments:
if d.kind != "support" or d.code not in OFFICE_KINDS:
continue
member, sup = OFFICE_KINDS[d.code]
self.entries.append((f"PS-{d.slug}", Role(member, d.code)))
if d.supervisor_group and sup:
self.entries.append((f"PS-{d.slug}-Supervisor", Role(sup, d.code)))
for d in self.departments:
if d.kind == "shop":
for level in SHOP_LEVELS:
self.entries.append((f"PS-{d.code}-{d.slug}-{level.capitalize()}", Role(f"shop_{level}", d.code)))
self._by_lower = {name.lower(): (name, role) for name, role in self.entries}
self._order = {str(role): i for i, (_, role) in enumerate(self.entries)}
def names(self) -> list[str]:
return [name for name, _ in self.entries]
def role_for(self, name: str) -> Role | None:
hit = self._by_lower.get(name.strip().lower())
return hit[1] if hit else None
def canonical(self, name: str) -> str | None:
"""The map's spelling of a group name, or None when it is not mapped."""
hit = self._by_lower.get(name.strip().lower())
return hit[0] if hit else None
def sort_roles(self, roles: Iterable[str]) -> list[str]:
return sorted(set(roles), key=lambda s: (self._order.get(s, 10_000), s))
def roles(self, names: Iterable[str]) -> list[str]:
"""Role strings for a set of group names: the union, highest shop level per department."""
found = {r for n in names if (r := self.role_for(n)) is not None}
best: dict[str, Role] = {}
out: set[str] = set()
for r in found:
if r.kind.startswith("shop_"):
code = r.dept_code or ""
cur = best.get(code)
if cur is None or _level(r) > _level(cur):
best[code] = r
else:
out.add(str(r))
out.update(str(r) for r in best.values())
return self.sort_roles(out)
_default = GroupMap(DEPARTMENTS)
def current() -> GroupMap:
return _default
def use_departments(departments: Sequence[Department]) -> GroupMap:
"""Replace the process-wide map (the app calls this at startup with the departments table)."""
global _default
_default = GroupMap(departments)
return _default
def load_departments(conn: Any) -> list[Department]:
rows = conn.execute(
"SELECT code, slug, name, kind::text, sort, supervisor_group, active FROM departments ORDER BY sort, code"
).fetchall()
return [Department(r[0], r[1], r[2], r[3], r[4], r[5], r[6]) for r in rows]
def group_names() -> list[str]:
"""The mapped group names in contract order: PS-Admins, CL, WH, QC, PM, then shop 01..14."""
return _default.names()
def role_for_group(name: str) -> Role | None:
return _default.role_for(name)
def roles_from_groups(names: Iterable[str]) -> list[str]:
return _default.roles(names)
def mapped_groups(names: Iterable[str]) -> list[str]:
"""The map's spelling of every mapped name in `names`, in map order, without duplicates."""
keep = {c for n in names if (c := _default.canonical(n))}
return [n for n in _default.names() if n in keep]
def screens_for(roles: Iterable[str]) -> list[str]:
"""The screens a role set may open. Admin gets every screen."""
have: set[str] = set()
for r in roles:
if r == "admin":
have.update(SCREENS)
elif r.startswith("clerical"):
have.add("clerical")
elif r.startswith("warehouse"):
have.add("warehouse")
elif r.startswith("qc"):
have.add("qc")
elif r == "pm":
have.add("pm")
elif r.startswith("shop:"):
have.add("stall")
if r.endswith((":lead", ":supervisor")):
have.add("supervisor")
return [s for s in SCREENS if s in have]
def is_admin(roles: Iterable[str]) -> bool:
return "admin" in set(roles)
def is_shop_supervisor(roles: Iterable[str]) -> bool:
return any(r.startswith("shop:") and r.endswith(":supervisor") for r in roles)
+304
View File
@@ -0,0 +1,304 @@
"""Read-only access to Active Directory with ldap3: search with the service account, bind to verify a password.
Every operation opens its own connection and unbinds when done. A user's password is used for one bind and
never stored or logged.
"""
from __future__ import annotations
import contextlib
import logging
import ssl
import uuid
from collections.abc import Iterator
from dataclasses import dataclass, field
from typing import Any, Protocol
from ..settings import SecretFileError, Settings
log = logging.getLogger(__name__)
IN_CHAIN = "1.2.840.113556.1.4.1941"
USER_ATTRS = (
"objectGUID",
"sAMAccountName",
"userPrincipalName",
"displayName",
"employeeID",
"mail",
"userAccountControl",
"distinguishedName",
)
ACCOUNTDISABLE = 2
INVALID_CREDENTIALS = 49
PAGE_SIZE = 500
class LdapUnavailable(Exception):
"""No domain controller answered, TLS failed, or the service bind was refused. Never holds a password."""
@dataclass
class AdUser:
guid: uuid.UUID
dn: str
sam_account: str
upn: str | None
display_name: str
emp_no: str | None
email: str | None
disabled: bool
groups: list[str] = field(default_factory=list)
class DirectoryProtocol(Protocol):
"""What the app needs from AD. `Directory` talks to a domain controller; tests use a fake."""
def find_user(self, login: str) -> AdUser | None: ...
def get_user_by_guid(self, guid: uuid.UUID) -> AdUser | None: ...
def verify_password(self, dn: str, password: str) -> bool: ...
def groups_of(self, dn: str) -> list[str]: ...
def list_groups(self) -> list[str]: ...
def members_of(self, group_cn: str) -> list[AdUser]: ...
# ---------------------------------------------------------------- attribute helpers
def parse_guid(value: Any) -> uuid.UUID:
"""objectGUID as ldap3 returns it: 16 raw bytes (little-endian fields) or a "{...}" string."""
if isinstance(value, list | tuple):
if not value:
raise ValueError("empty objectGUID")
value = value[0]
if isinstance(value, bytes | bytearray):
if len(value) != 16:
raise ValueError("objectGUID must be 16 bytes")
return uuid.UUID(bytes_le=bytes(value))
if isinstance(value, uuid.UUID):
return value
return uuid.UUID(str(value).strip().strip("{}"))
def guid_filter(guid: uuid.UUID) -> str:
"""`(objectGUID=\\xx...)` with the bytes escaped for a search filter."""
from ldap3.utils.conv import escape_bytes
return f"(objectGUID={escape_bytes(guid.bytes_le)})"
def _first(attrs: dict[str, Any], name: str) -> Any:
v = attrs.get(name)
if isinstance(v, list | tuple):
return v[0] if v else None
return v
def _text(attrs: dict[str, Any], name: str) -> str | None:
v = _first(attrs, name)
if v is None:
return None
if isinstance(v, bytes | bytearray):
v = bytes(v).decode("utf-8", "replace")
text = str(v).strip()
return text or None
def user_from_entry(entry: dict[str, Any]) -> AdUser:
"""An AdUser from one ldap3 search response entry (`attributes` plus `raw_attributes`)."""
attrs = entry.get("attributes") or {}
raw = entry.get("raw_attributes") or {}
guid_raw = _first(raw, "objectGUID") or _first(attrs, "objectGUID")
if guid_raw is None:
raise ValueError("entry has no objectGUID")
uac_text = _text(attrs, "userAccountControl") or "0"
try:
uac = int(uac_text)
except ValueError:
uac = 0
sam = _text(attrs, "sAMAccountName") or ""
return AdUser(
guid=parse_guid(guid_raw),
dn=_text(attrs, "distinguishedName") or str(entry.get("dn") or ""),
sam_account=sam,
upn=_text(attrs, "userPrincipalName"),
display_name=_text(attrs, "displayName") or sam,
emp_no=_text(attrs, "employeeID"),
email=_text(attrs, "mail"),
disabled=bool(uac & ACCOUNTDISABLE),
)
def _entries(response: Any) -> list[dict[str, Any]]:
return [e for e in (response or []) if e.get("type") == "searchResEntry"]
# ---------------------------------------------------------------- the real directory
class Directory:
"""AD over ldaps:// (or ldap:// with STARTTLS). Built from Settings; every method is synchronous."""
def __init__(self, settings: Settings):
self.settings = settings
self._pool: Any = None
# ------------------------------------------------ connections
def _servers(self) -> Any:
import ldap3
if self._pool is not None:
return self._pool
s = self.settings
urls = s.ldap_urls
if not urls:
raise LdapUnavailable("LDAP_URL is not set")
servers = []
for url in urls:
ldaps = url.lower().startswith("ldaps://")
if not ldaps and not s.ldap_starttls and not s.ldap_allow_insecure:
raise LdapUnavailable(f"{url} is plain LDAP without STARTTLS; refused")
tls = ldap3.Tls(
validate=ssl.CERT_REQUIRED,
version=ssl.PROTOCOL_TLS_CLIENT,
ca_certs_file=str(s.ldap_ca_bundle) if s.ldap_ca_bundle else None,
)
servers.append(ldap3.Server(url, use_ssl=ldaps, tls=tls, get_info=ldap3.NONE, connect_timeout=10))
# FIRST: the first healthy controller is used. active=1 tries the list once (True would loop
# forever when every controller is down); exhaust=60 skips a dead controller for a minute.
self._pool = ldap3.ServerPool(servers, ldap3.FIRST, active=1, exhaust=60)
return self._pool
def _open(self, user: str, password: str) -> Any:
"""An open, TLS-protected connection, not yet bound."""
import ldap3
conn = ldap3.Connection(
self._servers(),
user=user,
password=password,
authentication=ldap3.SIMPLE,
receive_timeout=15,
raise_exceptions=False,
auto_referrals=False,
read_only=True,
)
conn.open()
url_is_ldaps = bool(getattr(conn.server, "ssl", False))
if self.settings.ldap_starttls and not url_is_ldaps and not conn.start_tls():
with contextlib.suppress(Exception):
conn.unbind()
raise LdapUnavailable(f"STARTTLS failed: {conn.result.get('description')}")
return conn
@contextlib.contextmanager
def _service(self) -> Iterator[Any]:
"""A connection bound as the service account; always unbound afterwards."""
from ldap3.core.exceptions import LDAPException
s = self.settings
if not s.ldap_bind_dn:
raise LdapUnavailable("LDAP_BIND_DN is not set")
try:
password = s.ldap_password()
except SecretFileError as e:
raise LdapUnavailable(str(e)) from None
conn = None
try:
conn = self._open(s.ldap_bind_dn, password)
if not conn.bind():
raise LdapUnavailable(f"service bind failed: {conn.result.get('description')}")
yield conn
except LDAPException as e:
raise LdapUnavailable(f"{type(e).__name__}: {e}") from None
finally:
if conn is not None:
with contextlib.suppress(Exception):
conn.unbind()
def _search(self, conn: Any, base: str, flt: str, attrs: tuple[str, ...] | list[str]) -> list[dict[str, Any]]:
import ldap3
results = conn.extend.standard.paged_search(
base, flt, ldap3.SUBTREE, attributes=list(attrs), paged_size=PAGE_SIZE, generator=False
)
desc = conn.result.get("description") if conn.result else "success"
if desc not in ("success", None, "noSuchObject"):
raise LdapUnavailable(f"search failed: {desc}")
return _entries(results)
# ------------------------------------------------ protocol
def find_user(self, login: str) -> AdUser | None:
from ldap3.utils.conv import escape_filter_chars
login = login.strip()
if not login:
return None
flt = self.settings.ldap_user_filter.replace("{0}", escape_filter_chars(login))
with self._service() as conn:
found = self._search(conn, self.settings.ldap_base_dn, flt, USER_ATTRS)
users = [user_from_entry(e) for e in found]
if len(users) != 1:
if len(users) > 1:
log.warning("LDAP_USER_FILTER matched %d entries for one login; refusing", len(users))
return None
return users[0]
def get_user_by_guid(self, guid: uuid.UUID) -> AdUser | None:
with self._service() as conn:
found = self._search(conn, self.settings.ldap_base_dn, guid_filter(guid), USER_ATTRS)
return user_from_entry(found[0]) if found else None
def verify_password(self, dn: str, password: str) -> bool:
"""Simple bind as the user. An empty password is refused here: AD treats it as an anonymous bind."""
from ldap3.core.exceptions import LDAPException
if not password or not dn:
return False
conn = None
try:
conn = self._open(dn, password)
if conn.bind():
return True
code = conn.result.get("result") if conn.result else None
if code == INVALID_CREDENTIALS:
return False
raise LdapUnavailable(f"user bind failed: {conn.result.get('description')}")
except LDAPException as e:
raise LdapUnavailable(f"{type(e).__name__}") from None
finally:
if conn is not None:
with contextlib.suppress(Exception):
conn.unbind()
def groups_of(self, dn: str) -> list[str]:
from ldap3.utils.conv import escape_filter_chars
flt = f"(&(objectClass=group)(member:{IN_CHAIN}:={escape_filter_chars(dn)}))"
with self._service() as conn:
found = self._search(conn, self.settings.ldap_group_base_dn, flt, ["cn"])
return sorted({cn for e in found if (cn := _text(e.get("attributes") or {}, "cn"))})
def list_groups(self) -> list[str]:
with self._service() as conn:
found = self._search(conn, self.settings.ldap_group_base_dn, "(objectClass=group)", ["cn"])
return sorted({cn for e in found if (cn := _text(e.get("attributes") or {}, "cn"))})
def members_of(self, group_cn: str) -> list[AdUser]:
from ldap3.utils.conv import escape_filter_chars
with self._service() as conn:
groups = self._search(
conn,
self.settings.ldap_group_base_dn,
f"(&(objectClass=group)(cn={escape_filter_chars(group_cn)}))",
["cn", "distinguishedName"],
)
if not groups:
return []
gdn = _text(groups[0].get("attributes") or {}, "distinguishedName") or str(groups[0].get("dn") or "")
flt = f"(&(objectClass=user)(objectCategory=person)(memberOf:{IN_CHAIN}:={escape_filter_chars(gdn)}))"
found = self._search(conn, self.settings.ldap_base_dn, flt, USER_ATTRS)
return [user_from_entry(e) for e in found]
+109
View File
@@ -0,0 +1,109 @@
"""The optional Packet Station PIN: Argon2id hash on the server, set by the user, cleared by an Admin."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError
from .. import audit
from ..settings import Settings
_hasher = PasswordHasher()
@dataclass
class PinState:
set: bool
disabled: bool
failed_count: int = 0
def public(self) -> dict[str, bool]:
return {"set": self.set, "disabled": self.disabled}
def valid_format(pin: str, settings: Settings) -> bool:
"""Digits only (ASCII), PIN_MIN_DIGITS to PIN_MAX_DIGITS long."""
return pin.isascii() and pin.isdigit() and settings.pin_min_digits <= len(pin) <= settings.pin_max_digits
def hash_pin(pin: str) -> str:
return _hasher.hash(pin)
def verify_hash(stored: str, pin: str) -> bool:
if not pin:
return False
try:
return _hasher.verify(stored, pin)
except (VerifyMismatchError, VerificationError, InvalidHashError):
return False
def state(conn: Any, user_id: Any) -> PinState:
row = conn.execute("SELECT failed_count, disabled_at FROM user_pins WHERE user_id = %s", (user_id,)).fetchone()
if row is None:
return PinState(False, False)
return PinState(True, row[1] is not None, int(row[0]))
def stored_hash(conn: Any, user_id: Any) -> tuple[str, bool] | None:
"""(hash, disabled) or None when the user has no PIN."""
row = conn.execute("SELECT hash, disabled_at FROM user_pins WHERE user_id = %s", (user_id,)).fetchone()
return None if row is None else (str(row[0]), row[1] is not None)
def set_pin(conn: Any, user_id: Any, pin: str) -> None:
"""Store a new PIN hash and clear the failure count and the disabled mark."""
h = hash_pin(pin)
conn.execute(
"INSERT INTO user_pins (user_id, hash, failed_count, disabled_at, set_at) VALUES (%s, %s, 0, NULL, now())"
" ON CONFLICT (user_id) DO UPDATE SET hash = EXCLUDED.hash, failed_count = 0, disabled_at = NULL,"
" set_at = now()",
(user_id, h),
)
def reset_failures(conn: Any, user_id: Any) -> None:
conn.execute("UPDATE user_pins SET failed_count = 0 WHERE user_id = %s AND failed_count <> 0", (user_id,))
def register_failure(
conn: Any,
settings: Settings,
user_id: Any,
*,
session_id: Any = None,
role_snapshot: str | None = None,
ip: str | None = None,
where: str = "signin",
) -> bool:
"""Count one wrong PIN. At PIN_MAX_FAILURES the PIN is disabled and `pin.disabled` audited. True if disabled now."""
with conn.transaction():
row = conn.execute(
"UPDATE user_pins SET failed_count = failed_count + 1 WHERE user_id = %s AND disabled_at IS NULL"
" RETURNING failed_count",
(user_id,),
).fetchone()
if row is None or int(row[0]) < settings.pin_max_failures:
return False
conn.execute("UPDATE user_pins SET disabled_at = now() WHERE user_id = %s", (user_id,))
audit.append(
conn,
action="pin.disabled",
user_id=user_id,
session_id=session_id,
role_snapshot=role_snapshot,
subject_type="user",
subject_id=user_id,
detail={"failures": int(row[0]), "where": where},
ip=ip,
)
return True
def clear(conn: Any, user_id: Any) -> bool:
row = conn.execute("DELETE FROM user_pins WHERE user_id = %s RETURNING user_id", (user_id,)).fetchone()
return row is not None
+115
View File
@@ -0,0 +1,115 @@
"""Sign-in rate limits, checked before any LDAP bind and before any PIN hash check.
Only failed attempts count, and never those refused as `rate_limited`. Per account: when an account has
SIGNIN_ACCOUNT_LIMIT failures inside one window, it is refused until the limit-hitting failure plus the
cooldown. Per client address: SIGNIN_IP_LIMIT failures in the last window refuse it until enough of them
fall out of the window. Times come from the database clock unless the caller passes `now`.
"""
from __future__ import annotations
import math
from collections.abc import Sequence
from datetime import datetime, timedelta
from typing import Any
from ..settings import Settings
RATE_LIMITED = "rate_limited"
KINDS = ("password", "pin", "unlock", "signature", "pin_set")
def account_block_until(
failures: Sequence[datetime], *, limit: int, window: timedelta, cooldown: timedelta
) -> datetime | None:
"""The latest "refused until" time implied by a list of failure times, or None."""
times = sorted(failures)
until: datetime | None = None
for i in range(limit - 1, len(times)):
if times[i] - times[i - limit + 1] < window:
candidate = times[i] + cooldown
if until is None or candidate > until:
until = candidate
return until
def ip_block_until(failures: Sequence[datetime], *, now: datetime, limit: int, window: timedelta) -> datetime | None:
"""When the address may try again, or None. Only failures inside (now - window, now] count."""
recent = sorted(t for t in failures if now - window < t <= now)
if len(recent) < limit:
return None
# Allowed again once the count drops below the limit: the (n - limit + 1)th oldest leaves the window
return recent[len(recent) - limit] + window
def retry_seconds(until: datetime | None, now: datetime) -> int | None:
if until is None or until <= now:
return None
return max(1, math.ceil((until - now).total_seconds()))
def db_now(conn: Any) -> datetime:
row = conn.execute("SELECT now()").fetchone()
now: datetime = row[0]
return now
def check(
conn: Any,
settings: Settings,
*,
accounts: Sequence[str],
ip: str | None,
now: datetime | None = None,
) -> int | None:
"""Seconds until another attempt is allowed, or None when allowed. Failures of all `accounts` count together."""
now = now or db_now(conn)
window = timedelta(minutes=settings.signin_account_window_minutes)
cooldown = timedelta(minutes=settings.signin_account_cooldown_minutes)
waits: list[int] = []
keys = sorted({a for a in accounts if a})
if keys:
since = now - window - cooldown
rows = conn.execute(
"SELECT at FROM signin_attempts WHERE account = ANY(%s) AND NOT ok"
" AND reason IS DISTINCT FROM %s AND at > %s AND at <= %s",
(keys, RATE_LIMITED, since, now),
).fetchall()
until = account_block_until(
[r[0] for r in rows], limit=settings.signin_account_limit, window=window, cooldown=cooldown
)
if (w := retry_seconds(until, now)) is not None:
waits.append(w)
if ip:
ip_window = timedelta(minutes=settings.signin_ip_window_minutes)
rows = conn.execute(
"SELECT at FROM signin_attempts WHERE ip = %s::inet AND NOT ok"
" AND reason IS DISTINCT FROM %s AND at > %s AND at <= %s",
(ip, RATE_LIMITED, now - ip_window, now),
).fetchall()
until = ip_block_until([r[0] for r in rows], now=now, limit=settings.signin_ip_limit, window=ip_window)
if (w := retry_seconds(until, now)) is not None:
waits.append(w)
return max(waits) if waits else None
def record(
conn: Any,
*,
account: str,
ip: str | None,
kind: str,
ok: bool,
reason: str | None = None,
user_id: Any = None,
session_id: Any = None,
at: datetime | None = None,
) -> None:
"""Append one signin_attempts row. Never holds a password or PIN."""
if kind not in KINDS:
raise ValueError(f"bad attempt kind {kind!r}")
conn.execute(
"INSERT INTO signin_attempts (at, account, ip, kind, ok, reason, user_id, session_id)"
" VALUES (coalesce(%s, now()), %s, %s::inet, %s, %s, %s, %s, %s)",
(at, account, ip, kind, ok, reason, user_id, session_id),
)
+122
View File
@@ -0,0 +1,122 @@
"""Server-side sessions. The cookie holds a random token; the row holds HMAC-SHA256(session key, token)."""
from __future__ import annotations
import hashlib
import hmac
import secrets
import uuid
from dataclasses import dataclass
from typing import Any
from psycopg.rows import dict_row
from psycopg.types.json import Jsonb
from .. import events
from ..settings import Settings
SESSION_COOKIE = "ps_session"
DEVICE_COOKIE = "ps_device"
@dataclass(frozen=True)
class Actor:
"""Who is acting in a session: what step-up checks, signatures and audit rows need."""
session_id: uuid.UUID
user_id: uuid.UUID
sam_account: str
display_name: str
kind: str # password | pin
roles: tuple[str, ...]
@property
def role_snapshot(self) -> str:
return ",".join(self.roles)
def new_token() -> str:
return secrets.token_urlsafe(32)
def token_hash(key: bytes, token: str) -> bytes:
return hmac.new(key, token.encode("utf-8"), hashlib.sha256).digest()
def create(
conn: Any,
settings: Settings,
key: bytes,
*,
user_id: Any,
kind: str,
roles: list[str],
groups: list[str],
device_id: Any = None,
ip: str | None = None,
user_agent: str | None = None,
) -> tuple[str, dict[str, Any]]:
"""Insert a session row; returns (cookie token, row). The token itself is never stored."""
token = new_token()
hours = settings.session_pin_hours if kind == "pin" else settings.session_password_hours
with conn.cursor(row_factory=dict_row) as cur:
row = cur.execute(
"INSERT INTO sessions (user_id, token_hash, kind, device_id, expires_at, last_seen_at, ip, user_agent,"
" roles_snapshot, roles_checked_at)"
" VALUES (%s, %s, %s::session_kind, %s, now() + make_interval(hours => %s::int), now(), %s::inet, %s, %s,"
" now()) RETURNING *",
(
user_id,
token_hash(key, token),
kind,
device_id,
hours,
ip,
(user_agent or "")[:400] or None,
Jsonb({"roles": roles, "groups": groups}),
),
).fetchone()
assert row is not None
return token, row
def load(conn: Any, key: bytes, token: str) -> dict[str, Any] | None:
"""The session row for a cookie token plus `db_now`, or None. Revoked and expired rows are returned too."""
with conn.cursor(row_factory=dict_row) as cur:
row: dict[str, Any] | None = cur.execute(
"SELECT s.*, s.kind::text AS kind, now() AS db_now FROM sessions s WHERE s.token_hash = %s",
(token_hash(key, token),),
).fetchone()
return row
def revoke(conn: Any, session_id: Any, reason: str, *, notify: bool = True) -> bool:
"""Revoke one session. Publishes a `session` event so that browser signs out. False when already revoked."""
row = conn.execute(
"UPDATE sessions SET revoked_at = now(), revoked_reason = %s WHERE id = %s AND revoked_at IS NULL RETURNING id",
(reason, session_id),
).fetchone()
if row is None:
return False
if notify:
events.publish(conn, {"event": "session", "session_id": str(row[0]), "action": "revoked"})
return True
def revoke_where(conn: Any, where: str, params: tuple[Any, ...], reason: str) -> list[uuid.UUID]:
"""Revoke every active session matching a WHERE fragment; publishes one `session` event each."""
rows = conn.execute(
f"UPDATE sessions SET revoked_at = now(), revoked_reason = %s WHERE revoked_at IS NULL AND ({where})" # noqa: S608
" RETURNING id",
(reason, *params),
).fetchall()
ids = [r[0] for r in rows]
for sid in ids:
events.publish(conn, {"event": "session", "session_id": str(sid), "action": "revoked"})
return ids
def revoke_user(conn: Any, user_id: Any, reason: str, *, except_id: Any = None) -> list[uuid.UUID]:
if except_id is None:
return revoke_where(conn, "user_id = %s", (user_id,), reason)
return revoke_where(conn, "user_id = %s AND id <> %s", (user_id, except_id), reason)
+116
View File
@@ -0,0 +1,116 @@
"""Electronic signatures: a step-up check, then an append-only `signatures` row and a `sig.signed` audit row.
Later phases call `sign` from every sign-off action. There is no HTTP endpoint for it in phase 1.
"""
from __future__ import annotations
import hashlib
import json
from dataclasses import dataclass
from datetime import datetime
from typing import Any
from .. import audit
from ..settings import Settings, get_settings
from . import stepup
from .ldap import DirectoryProtocol
from .sessions import Actor
@dataclass(frozen=True)
class Signature:
id: int
at: datetime
user_id: Any
session_id: Any
account: str
display_name: str
session_kind: str
factor: str
action: str
meaning: str | None
packet_id: int | None
subject_type: str | None
subject_id: str | None
content_hash: bytes | None
def canonical_json(content: Any) -> bytes:
return json.dumps(content, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str).encode("utf-8")
def content_hash(content: Any) -> bytes | None:
"""sha256 of the canonical JSON of what was signed; None when nothing was given."""
return None if content is None else hashlib.sha256(canonical_json(content)).digest()
def sign(
conn: Any,
directory: DirectoryProtocol,
session: Actor,
*,
factor: str,
secret: str,
action: str,
meaning: str | None,
packet_id: int | None = None,
subject_type: str | None = None,
subject_id: Any = None,
content: Any = None,
ip: str | None = None,
settings: Settings | None = None,
) -> Signature:
"""Check the PIN or password (raises ApiError when wrong), then record the signature."""
s = settings or get_settings()
stepup.verify(conn, directory, s, session, factor=factor, secret=secret, kind="signature", ip=ip)
h = content_hash(content)
sid = None if subject_id is None else str(subject_id)
with conn.transaction():
row = conn.execute(
"INSERT INTO signatures (user_id, session_id, account, display_name, session_kind, factor, action,"
" meaning, packet_id, subject_type, subject_id, content_hash)"
" VALUES (%s, %s, %s, %s, %s::session_kind, %s::sig_factor, %s, %s, %s, %s, %s, %s) RETURNING id, at",
(
session.user_id,
session.session_id,
session.sam_account,
session.display_name,
session.kind,
factor,
action,
meaning,
packet_id,
subject_type,
sid,
h,
),
).fetchone()
audit.append(
conn,
action="sig.signed",
user_id=session.user_id,
session_id=session.session_id,
role_snapshot=session.role_snapshot,
subject_type=subject_type,
subject_id=sid,
packet_id=packet_id,
detail={"signature_id": int(row[0]), "action": action, "factor": factor},
ip=ip,
)
return Signature(
id=int(row[0]),
at=row[1],
user_id=session.user_id,
session_id=session.session_id,
account=session.sam_account,
display_name=session.display_name,
session_kind=session.kind,
factor=factor,
action=action,
meaning=meaning,
packet_id=packet_id,
subject_type=subject_type,
subject_id=sid,
content_hash=h,
)
+441
View File
@@ -0,0 +1,441 @@
"""Password and PIN sign-in, and setting a PIN. Rate limits run before any LDAP bind or PIN hash check.
Failures are written to `signin_attempts` at once (the API connection is in autocommit mode), so they count
even though the request then fails. LDAP calls never run inside a database transaction.
"""
from __future__ import annotations
import logging
from dataclasses import dataclass
from typing import Any, NoReturn
from psycopg.rows import dict_row
from .. import audit
from ..api.errors import ApiError
from ..settings import Settings
from . import devices, ratelimit, sessions
from . import directory as userdir
from . import groups as groupmap
from . import pin as pins
from .ldap import AdUser, DirectoryProtocol, LdapUnavailable
log = logging.getLogger(__name__)
PASSWORD_FAILED = "Sign-in failed. Check the account name and password." # noqa: S105 (a message)
PIN_FAILED = "Sign-in failed."
NO_ROLE = "No role in Packet Station. Ask IT to add you to a group."
LDAP_DOWN = "The directory cannot be reached. Try again in a few minutes."
@dataclass
class SigninResult:
token: str
session: dict[str, Any]
user_id: Any
roles: list[str]
groups: list[str]
device: dict[str, Any] | None
def ldap_down(e: Exception) -> ApiError:
log.warning("AD unavailable: %s", e)
return ApiError(503, "ldap_unavailable", LDAP_DOWN)
def rate_gate(
conn: Any,
settings: Settings,
*,
accounts: list[str],
ip: str | None,
kind: str,
record_account: str,
user_id: Any = None,
session_id: Any = None,
) -> None:
"""Raise 429 when the accounts or the address are over their limit; the refusal is recorded and audited."""
wait = ratelimit.check(conn, settings, accounts=accounts, ip=ip)
if wait is None:
return
with conn.transaction():
ratelimit.record(
conn,
account=record_account,
ip=ip,
kind=kind,
ok=False,
reason=ratelimit.RATE_LIMITED,
user_id=user_id,
session_id=session_id,
)
audit.append(
conn,
action="auth.signin_failed",
user_id=user_id,
session_id=session_id,
detail={"reason": "rate_limited", "account": record_account, "kind": kind},
ip=ip,
)
minutes = max(1, (wait + 59) // 60)
raise ApiError(
429,
"rate_limited",
f"Too many failed attempts. Try again in {minutes} minute{'s' if minutes != 1 else ''}.",
headers={"Retry-After": str(wait)},
extra={"retry_after": wait},
)
def _fail(
conn: Any,
*,
account: str,
ip: str | None,
kind: str,
reason: str,
status: int,
code: str,
detail: str,
user_id: Any = None,
audited: bool = False,
) -> NoReturn:
with conn.transaction():
ratelimit.record(conn, account=account, ip=ip, kind=kind, ok=False, reason=reason, user_id=user_id)
if audited:
audit.append(
conn,
action="auth.signin_failed",
user_id=user_id,
detail={"reason": reason, "account": account, "kind": kind},
ip=ip,
)
raise ApiError(status, code, detail)
def _start(
conn: Any,
settings: Settings,
key: bytes,
u: AdUser,
*,
kind: str,
account: str,
groups: list[str],
roles: list[str],
device: dict[str, Any] | None,
ip: str | None,
user_agent: str | None,
) -> SigninResult:
with conn.transaction():
userdir.upsert_user(conn, u, groups=groups, signin=True)
userdir.set_roles(conn, u.guid, roles)
if kind == "pin":
pins.reset_failures(conn, u.guid)
token, row = sessions.create(
conn,
settings,
key,
user_id=u.guid,
kind=kind,
roles=roles,
groups=groups,
device_id=device["id"] if device else None,
ip=ip,
user_agent=user_agent,
)
ratelimit.record(conn, account=account, ip=ip, kind=kind, ok=True, user_id=u.guid, session_id=row["id"])
audit.append(
conn,
action="auth.signin",
user_id=u.guid,
session_id=row["id"],
role_snapshot=",".join(roles),
detail={
"kind": kind,
"device_id": str(device["id"]) if device else None,
"device_name": device["name"] if device else None,
},
ip=ip,
)
if device:
devices.touch(conn, device["id"])
return SigninResult(token, row, u.guid, roles, groups, device)
def resolve_groups(directory: DirectoryProtocol, u: AdUser) -> tuple[list[str], list[str]]:
"""(groups in the PacketStation OU, roles they give)."""
found = sorted(directory.groups_of(u.dn))
return found, groupmap.roles_from_groups(found)
def password_signin(
conn: Any,
directory: DirectoryProtocol,
settings: Settings,
key: bytes,
*,
login: str,
password: str,
ip: str | None,
user_agent: str | None,
) -> SigninResult:
login = (login or "").strip()
account = login.lower()[:256]
if not login or not password:
# Refused before LDAP: an empty password would be an anonymous bind
_fail(
conn,
account=account or "(empty)",
ip=ip,
kind="password",
reason="empty",
status=401,
code="signin_failed",
detail=PASSWORD_FAILED,
)
rate_gate(conn, settings, accounts=[account], ip=ip, kind="password", record_account=account)
try:
u = directory.find_user(login)
except LdapUnavailable as e:
raise ldap_down(e) from None
if u is None:
_fail(
conn,
account=account,
ip=ip,
kind="password",
reason="no_such_user",
status=401,
code="signin_failed",
detail=PASSWORD_FAILED,
)
# The same person may type the account name or the UPN: both keys count before the bind
aliases = sorted({a for a in (u.sam_account.lower(), (u.upn or "").lower()) if a and a != account})
if aliases:
rate_gate(
conn,
settings,
accounts=[account, *aliases],
ip=None,
kind="password",
record_account=account,
user_id=u.guid,
)
try:
ok = directory.verify_password(u.dn, password)
except LdapUnavailable as e:
raise ldap_down(e) from None
if not ok:
_fail(
conn,
account=account,
ip=ip,
kind="password",
reason="bad_password",
status=401,
code="signin_failed",
detail=PASSWORD_FAILED,
user_id=u.guid,
)
if u.disabled:
_fail(
conn,
account=account,
ip=ip,
kind="password",
reason="disabled",
status=401,
code="signin_failed",
detail=PASSWORD_FAILED,
user_id=u.guid,
audited=True,
)
try:
groups, roles = resolve_groups(directory, u)
except LdapUnavailable as e:
raise ldap_down(e) from None
if not roles:
_fail(
conn,
account=account,
ip=ip,
kind="password",
reason="no_role",
status=403,
code="no_role",
detail=NO_ROLE,
user_id=u.guid,
audited=True,
)
return _start(
conn,
settings,
key,
u,
kind="password",
account=account,
groups=groups,
roles=roles,
device=None,
ip=ip,
user_agent=user_agent,
)
def pin_signin(
conn: Any,
directory: DirectoryProtocol,
settings: Settings,
key: bytes,
*,
device: dict[str, Any],
emp_no: str,
pin: str,
ip: str | None,
user_agent: str | None,
) -> SigninResult:
emp = (emp_no or "").strip()[:64]
account = f"emp:{emp}"
def fail(reason: str, user_id: Any = None, *, audited: bool = False) -> NoReturn:
_fail(
conn,
account=account,
ip=ip,
kind="pin",
reason=reason,
status=401,
code="signin_failed",
detail=PIN_FAILED,
user_id=user_id,
audited=audited,
)
if not emp or not pin:
fail("empty")
rate_gate(conn, settings, accounts=[account], ip=ip, kind="pin", record_account=account)
with conn.cursor(row_factory=dict_row) as cur:
rows = cur.execute(
"SELECT u.id, u.active, p.hash, p.disabled_at FROM users u"
" LEFT JOIN user_pins p ON p.user_id = u.id WHERE u.emp_no = %s",
(emp,),
).fetchall()
if not rows:
fail("no_such_user")
if len(rows) > 1:
fail("emp_duplicate")
row = rows[0]
uid = row["id"]
if not row["active"]:
fail("inactive", uid)
if row["hash"] is None:
fail("no_pin", uid)
if row["disabled_at"] is not None:
fail("pin_disabled", uid)
if not pins.verify_hash(row["hash"], pin):
with conn.transaction():
ratelimit.record(conn, account=account, ip=ip, kind="pin", ok=False, reason="bad_pin", user_id=uid)
pins.register_failure(conn, settings, uid, ip=ip, where="signin")
raise ApiError(401, "signin_failed", PIN_FAILED)
try:
u = directory.get_user_by_guid(uid)
except LdapUnavailable as e:
raise ldap_down(e) from None
if u is None or u.disabled:
with conn.transaction():
userdir.mark_inactive(conn, uid, reason="ad_gone" if u is None else "ad_disabled", gone=u is None)
fail("disabled", uid, audited=True)
try:
groups, roles = resolve_groups(directory, u)
except LdapUnavailable as e:
raise ldap_down(e) from None
if not roles:
_fail(
conn,
account=account,
ip=ip,
kind="pin",
reason="no_role",
status=403,
code="no_role",
detail=NO_ROLE,
user_id=uid,
audited=True,
)
return _start(
conn,
settings,
key,
u,
kind="pin",
account=account,
groups=groups,
roles=roles,
device=device,
ip=ip,
user_agent=user_agent,
)
def set_pin(
conn: Any,
directory: DirectoryProtocol,
settings: Settings,
actor: sessions.Actor,
*,
password: str,
new_pin: str,
ip: str | None,
) -> None:
"""Set or change the actor's PIN. Needs the domain password in the same request (password session only)."""
if not pins.valid_format(new_pin or "", settings):
raise ApiError(
400,
"invalid_pin",
f"The PIN must be {settings.pin_min_digits} to {settings.pin_max_digits} digits.",
)
account = f"user:{actor.user_id}"
rate_gate(
conn,
settings,
accounts=[account, actor.sam_account.lower()],
ip=ip,
kind="pin_set",
record_account=account,
user_id=actor.user_id,
session_id=actor.session_id,
)
try:
u = directory.get_user_by_guid(actor.user_id)
ok = bool(u and not u.disabled and password and directory.verify_password(u.dn, password))
except LdapUnavailable as e:
raise ldap_down(e) from None
if not ok:
ratelimit.record(
conn,
account=account,
ip=ip,
kind="pin_set",
ok=False,
reason="bad_password",
user_id=actor.user_id,
session_id=actor.session_id,
)
raise ApiError(403, "bad_password", "The password is wrong.")
with conn.transaction():
pins.set_pin(conn, actor.user_id, new_pin)
ratelimit.record(
conn, account=account, ip=ip, kind="pin_set", ok=True, user_id=actor.user_id, session_id=actor.session_id
)
audit.append(
conn,
action="pin.set",
user_id=actor.user_id,
session_id=actor.session_id,
role_snapshot=actor.role_snapshot,
subject_type="user",
subject_id=actor.user_id,
ip=ip,
)
+136
View File
@@ -0,0 +1,136 @@
"""Step-up checks inside a session (screen unlock and signatures): PIN or domain password.
Wrong attempts are recorded (account `user:<uuid>`), count toward the PIN's failures when the factor is the
PIN, and raise `sessions.stepup_failures`. At STEPUP_MAX_FAILURES the session ends. A right answer resets
the session's count.
"""
from __future__ import annotations
from typing import Any
from .. import audit
from ..api.errors import ApiError
from ..settings import Settings
from . import pin as pins
from . import ratelimit, sessions
from .ldap import DirectoryProtocol, LdapUnavailable
from .signin import ldap_down, rate_gate
FACTORS = ("pin", "password")
def end_session(conn: Any, actor: sessions.Actor, reason: str, ip: str | None) -> None:
with conn.transaction():
if sessions.revoke(conn, actor.session_id, reason):
audit.append(
conn,
action="auth.session_ended",
user_id=actor.user_id,
session_id=actor.session_id,
role_snapshot=actor.role_snapshot,
detail={"reason": reason},
ip=ip,
)
def verify(
conn: Any,
directory: DirectoryProtocol,
settings: Settings,
actor: sessions.Actor,
*,
factor: str,
secret: str,
kind: str,
ip: str | None,
) -> None:
"""Return when the secret is right; raise ApiError otherwise.
Wrong: 403 `wrong_secret` with `attempts_left`. The last allowed miss: 401 `session_ended`.
"""
if factor not in FACTORS:
raise ApiError(400, "bad_factor", "factor must be pin or password")
if kind not in ("unlock", "signature"):
raise ValueError(f"bad step-up kind {kind!r}")
account = f"user:{actor.user_id}"
secret = secret or ""
if factor == "pin":
stored = pins.stored_hash(conn, actor.user_id)
if stored is None:
raise ApiError(409, "pin_not_set", "No PIN is set. Use your password.")
if stored[1]:
raise ApiError(409, "pin_disabled", "Your PIN is disabled. Use your password.")
ok = pins.verify_hash(stored[0], secret)
else:
rate_gate(
conn,
settings,
accounts=[account, actor.sam_account.lower()],
ip=ip,
kind=kind,
record_account=account,
user_id=actor.user_id,
session_id=actor.session_id,
)
try:
u = directory.get_user_by_guid(actor.user_id)
if u is None or u.disabled:
end_session(conn, actor, "roles_lost", ip)
raise ApiError(401, "session_ended", "Your account is no longer active. Sign in again.")
ok = bool(secret) and directory.verify_password(u.dn, secret)
except LdapUnavailable as e:
raise ldap_down(e) from None
if ok:
with conn.transaction():
conn.execute(
"UPDATE sessions SET stepup_failures = 0 WHERE id = %s AND stepup_failures <> 0", (actor.session_id,)
)
if factor == "pin":
pins.reset_failures(conn, actor.user_id)
ratelimit.record(
conn, account=account, ip=ip, kind=kind, ok=True, user_id=actor.user_id, session_id=actor.session_id
)
return
pin_disabled = False
with conn.transaction():
ratelimit.record(
conn,
account=account,
ip=ip,
kind=kind,
ok=False,
reason="bad_pin" if factor == "pin" else "bad_password",
user_id=actor.user_id,
session_id=actor.session_id,
)
if factor == "pin":
pin_disabled = pins.register_failure(
conn,
settings,
actor.user_id,
session_id=actor.session_id,
role_snapshot=actor.role_snapshot,
ip=ip,
where=kind,
)
row = conn.execute(
"UPDATE sessions SET stepup_failures = stepup_failures + 1 WHERE id = %s RETURNING stepup_failures",
(actor.session_id,),
).fetchone()
failures = int(row[0]) if row else settings.stepup_max_failures
if failures >= settings.stepup_max_failures:
end_session(conn, actor, "stepup_failures", ip)
raise ApiError(
401,
"session_ended",
f"{settings.stepup_max_failures} wrong attempts. The session has ended. Sign in again.",
)
raise ApiError(
403,
"wrong_secret",
"Wrong PIN." if factor == "pin" else "Wrong password.",
extra={"attempts_left": settings.stepup_max_failures - failures, "pin_disabled": pin_disabled},
)