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:
@@ -0,0 +1 @@
|
||||
"""HTTP API routers. Each module exposes `router`; main.create_app includes them."""
|
||||
@@ -0,0 +1,194 @@
|
||||
"""Account settings: own AD details, PIN, sessions, access log, and registering this device."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, Request, Response
|
||||
from psycopg.rows import dict_row
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from .. import audit
|
||||
from ..auth import devices, sessions, signin
|
||||
from ..auth import directory as userdir
|
||||
from ..auth import pin as pins
|
||||
from .deps import (
|
||||
Db,
|
||||
Principal,
|
||||
current_principal,
|
||||
directory_of,
|
||||
get_db,
|
||||
require_device_registrar,
|
||||
require_password_session,
|
||||
session_key,
|
||||
set_device_cookie,
|
||||
settings_of,
|
||||
)
|
||||
from .errors import ApiError
|
||||
|
||||
router = APIRouter(prefix="/api/account", tags=["account"])
|
||||
|
||||
LOG_PREFIXES = ("auth.%", "pin.%", "device.%", "sig.%")
|
||||
|
||||
|
||||
class PinBody(BaseModel):
|
||||
password: str = Field(max_length=1024)
|
||||
pin: str = Field(max_length=64)
|
||||
|
||||
|
||||
class DeviceBody(BaseModel):
|
||||
name: str = Field(max_length=devices.NAME_MAX)
|
||||
|
||||
|
||||
@router.get("")
|
||||
def account(p: Principal = Depends(current_principal), d: Db = Depends(get_db)) -> dict[str, Any]: # noqa: B008
|
||||
return {
|
||||
"user": userdir.public_user(p.user),
|
||||
"groups": p.groups,
|
||||
"roles": p.roles,
|
||||
"pin": pins.state(d.conn, p.user_id).public(),
|
||||
"ad_synced_at": p.user.get("ad_synced_at"),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/pin")
|
||||
def set_pin(
|
||||
body: PinBody,
|
||||
request: Request,
|
||||
p: Principal = Depends(current_principal), # noqa: B008
|
||||
d: Db = Depends(get_db), # noqa: B008
|
||||
) -> dict[str, Any]:
|
||||
require_password_session(p)
|
||||
signin.set_pin(
|
||||
d.conn,
|
||||
directory_of(request),
|
||||
settings_of(request),
|
||||
p.actor,
|
||||
password=body.password,
|
||||
new_pin=body.pin,
|
||||
ip=p.ip,
|
||||
)
|
||||
return {"pin": {"set": True, "disabled": False}}
|
||||
|
||||
|
||||
def device_names(conn: Any, ids: list[Any]) -> dict[Any, dict[str, Any]]:
|
||||
if not ids:
|
||||
return {}
|
||||
rows = conn.execute("SELECT id, name FROM devices WHERE id = ANY(%s)", (ids,)).fetchall()
|
||||
return {r[0]: {"id": str(r[0]), "name": r[1]} for r in rows}
|
||||
|
||||
|
||||
def active_sessions(conn: Any, user_id: Any, current_id: Any = None) -> list[dict[str, Any]]:
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
rows = cur.execute(
|
||||
"SELECT id, kind::text AS kind, created_at, last_seen_at, host(ip) AS ip, user_agent, device_id"
|
||||
" FROM sessions WHERE user_id = %s AND revoked_at IS NULL AND expires_at > now()"
|
||||
" ORDER BY last_seen_at DESC",
|
||||
(user_id,),
|
||||
).fetchall()
|
||||
names = device_names(conn, list({r["device_id"] for r in rows if r["device_id"]}))
|
||||
return [
|
||||
{
|
||||
"id": str(r["id"]),
|
||||
"kind": r["kind"],
|
||||
"created_at": r["created_at"],
|
||||
"last_seen_at": r["last_seen_at"],
|
||||
"ip": r["ip"],
|
||||
"user_agent": r["user_agent"],
|
||||
"device": names.get(r["device_id"]) if r["device_id"] else None,
|
||||
"current": current_id is not None and r["id"] == current_id,
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
|
||||
@router.get("/sessions")
|
||||
def my_sessions(p: Principal = Depends(current_principal), d: Db = Depends(get_db)) -> list[dict[str, Any]]: # noqa: B008
|
||||
return active_sessions(d.conn, p.user_id, p.session_id)
|
||||
|
||||
|
||||
@router.post("/sessions/signout-others")
|
||||
def signout_others(p: Principal = Depends(current_principal), d: Db = Depends(get_db)) -> dict[str, Any]: # noqa: B008
|
||||
require_password_session(p)
|
||||
conn = d.conn
|
||||
with conn.transaction():
|
||||
ids = sessions.revoke_user(conn, p.user_id, "signout_others", except_id=p.session_id)
|
||||
audit.append(
|
||||
conn,
|
||||
action="auth.signout_others",
|
||||
user_id=p.user_id,
|
||||
session_id=p.session_id,
|
||||
role_snapshot=p.role_snapshot,
|
||||
detail={"count": len(ids)},
|
||||
ip=p.ip,
|
||||
)
|
||||
return {"revoked": len(ids)}
|
||||
|
||||
|
||||
@router.get("/access-log")
|
||||
def access_log(
|
||||
p: Principal = Depends(current_principal), # noqa: B008
|
||||
d: Db = Depends(get_db), # noqa: B008
|
||||
limit: int = Query(50, ge=1, le=500),
|
||||
) -> list[dict[str, Any]]:
|
||||
conn = d.conn
|
||||
u = p.user
|
||||
accounts = [
|
||||
a
|
||||
for a in (
|
||||
(u.get("sam_account") or "").lower(),
|
||||
(u.get("upn") or "").lower(),
|
||||
f"emp:{u['emp_no']}" if u.get("emp_no") else "",
|
||||
f"user:{u['id']}",
|
||||
)
|
||||
if a
|
||||
]
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
audits = cur.execute(
|
||||
"SELECT at, action, detail, host(ip) AS ip FROM audit_events"
|
||||
" WHERE (user_id = %s OR (subject_type = 'user' AND subject_id = %s)) AND action LIKE ANY(%s)"
|
||||
" ORDER BY id DESC LIMIT %s",
|
||||
(p.user_id, str(p.user_id), list(LOG_PREFIXES), limit),
|
||||
).fetchall()
|
||||
failed = cur.execute(
|
||||
"SELECT at, kind, reason, host(ip) AS ip FROM signin_attempts"
|
||||
" WHERE NOT ok AND (user_id = %s OR account = ANY(%s)) ORDER BY at DESC LIMIT %s",
|
||||
(p.user_id, accounts, limit),
|
||||
).fetchall()
|
||||
out = [{"at": r["at"], "action": r["action"], "detail": r["detail"], "ip": r["ip"], "ok": True} for r in audits]
|
||||
out += [
|
||||
{"at": r["at"], "action": f"attempt.{r['kind']}", "detail": {"reason": r["reason"]}, "ip": r["ip"], "ok": False}
|
||||
for r in failed
|
||||
]
|
||||
out.sort(key=lambda r: r["at"], reverse=True)
|
||||
return out[:limit]
|
||||
|
||||
|
||||
@router.post("/device")
|
||||
def register_device(
|
||||
body: DeviceBody,
|
||||
request: Request,
|
||||
response: Response,
|
||||
p: Principal = Depends(current_principal), # noqa: B008
|
||||
d: Db = Depends(get_db), # noqa: B008
|
||||
) -> dict[str, Any]:
|
||||
require_device_registrar(p)
|
||||
name = " ".join(body.name.split())
|
||||
if not name:
|
||||
raise ApiError(400, "name_required", "Give the device a name.")
|
||||
conn = d.conn
|
||||
with conn.transaction():
|
||||
token, device_id = devices.register(conn, session_key(request), name=name, user_id=p.user_id)
|
||||
audit.append(
|
||||
conn,
|
||||
action="device.registered",
|
||||
user_id=p.user_id,
|
||||
session_id=p.session_id,
|
||||
role_snapshot=p.role_snapshot,
|
||||
subject_type="device",
|
||||
subject_id=device_id,
|
||||
detail={"name": name},
|
||||
ip=p.ip,
|
||||
)
|
||||
set_device_cookie(request, response, token, settings_of(request).device_cookie_days)
|
||||
return {"device": {"id": str(device_id), "name": name}}
|
||||
@@ -0,0 +1,309 @@
|
||||
"""Admin: users and their AD view (read-only), PIN clearing, devices, the group map, AD refresh, attempts.
|
||||
|
||||
Every route needs the admin role and a password session. Roles cannot be changed here: they come from AD.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, Request, Response
|
||||
from psycopg.rows import dict_row
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from .. import audit
|
||||
from ..auth import devices, sessions
|
||||
from ..auth import directory as userdir
|
||||
from ..auth import groups as groupmap
|
||||
from ..auth import pin as pins
|
||||
from ..auth.ldap import LdapUnavailable
|
||||
from ..auth.signin import ldap_down
|
||||
from .account import active_sessions
|
||||
from .deps import Db, Principal, admin_principal, directory_of, get_db
|
||||
from .errors import ApiError
|
||||
|
||||
router = APIRouter(prefix="/api/admin", tags=["admin"])
|
||||
|
||||
GROUPS_CACHE_SECONDS = 300
|
||||
ROLES_NOTE = "Roles come from AD groups. Ask IT to change them."
|
||||
|
||||
|
||||
class ReasonBody(BaseModel):
|
||||
reason: str = Field(max_length=500)
|
||||
|
||||
|
||||
def _like(q: str) -> str:
|
||||
return "%" + q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
|
||||
|
||||
|
||||
def _roles_by_user(conn: Any, ids: list[Any]) -> dict[Any, list[str]]:
|
||||
out: dict[Any, list[str]] = {}
|
||||
if not ids:
|
||||
return out
|
||||
rows = conn.execute(
|
||||
"SELECT user_id, role::text, dept_code FROM user_roles WHERE user_id = ANY(%s)", (ids,)
|
||||
).fetchall()
|
||||
for uid, kind, dept in rows:
|
||||
out.setdefault(uid, []).append(groupmap.role_from_row(kind, dept))
|
||||
gm = groupmap.current()
|
||||
return {k: gm.sort_roles(v) for k, v in out.items()}
|
||||
|
||||
|
||||
USER_SELECT = (
|
||||
"SELECT u.*, p.user_id IS NOT NULL AS pin_set, p.disabled_at IS NOT NULL AS pin_disabled,"
|
||||
" (SELECT count(*) FROM users x WHERE x.emp_no = u.emp_no) AS emp_count"
|
||||
" FROM users u LEFT JOIN user_pins p ON p.user_id = u.id"
|
||||
)
|
||||
|
||||
|
||||
def _user_row(r: dict[str, Any], roles: list[str]) -> dict[str, Any]:
|
||||
flags = r.get("directory_flags") or {}
|
||||
return {
|
||||
"id": str(r["id"]),
|
||||
"sam_account": r["sam_account"],
|
||||
"display_name": r["display_name"],
|
||||
"emp_no": r["emp_no"],
|
||||
"email": r["email"],
|
||||
"active": r["active"],
|
||||
"roles": roles,
|
||||
"pin": {"set": bool(r["pin_set"]), "disabled": bool(r["pin_disabled"])},
|
||||
"flags": {
|
||||
"emp_missing": not r["emp_no"],
|
||||
"emp_duplicate": bool(r["emp_no"]) and int(r["emp_count"] or 0) > 1,
|
||||
"disabled": bool(flags.get("disabled")) or bool(flags.get("gone")),
|
||||
},
|
||||
"last_signin_at": r["last_signin_at"],
|
||||
"ad_synced_at": r["ad_synced_at"],
|
||||
}
|
||||
|
||||
|
||||
@router.get("/users")
|
||||
def users(
|
||||
p: Principal = Depends(admin_principal), # noqa: B008
|
||||
d: Db = Depends(get_db), # noqa: B008
|
||||
q: str = Query("", max_length=100),
|
||||
) -> list[dict[str, Any]]:
|
||||
conn = d.conn
|
||||
q = q.strip()
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
if q:
|
||||
pat = _like(q)
|
||||
rows = cur.execute(
|
||||
USER_SELECT + " WHERE u.sam_account ILIKE %s OR u.display_name ILIKE %s OR u.email ILIKE %s"
|
||||
" OR u.emp_no = %s ORDER BY lower(u.display_name) LIMIT 500",
|
||||
(pat, pat, pat, q),
|
||||
).fetchall()
|
||||
else:
|
||||
rows = cur.execute(USER_SELECT + " ORDER BY lower(u.display_name) LIMIT 500").fetchall()
|
||||
roles = _roles_by_user(conn, [r["id"] for r in rows])
|
||||
return [_user_row(r, roles.get(r["id"], [])) for r in rows]
|
||||
|
||||
|
||||
@router.get("/users/{user_id}")
|
||||
def user_detail(
|
||||
user_id: uuid.UUID,
|
||||
request: Request,
|
||||
p: Principal = Depends(admin_principal), # noqa: B008
|
||||
d: Db = Depends(get_db), # noqa: B008
|
||||
) -> dict[str, Any]:
|
||||
conn = d.conn
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
r = cur.execute(USER_SELECT + " WHERE u.id = %s", (user_id,)).fetchone()
|
||||
if r is None:
|
||||
raise ApiError(404, "not_found", "No such user.")
|
||||
out = _user_row(r, _roles_by_user(conn, [user_id]).get(user_id, []))
|
||||
directory = directory_of(request)
|
||||
try:
|
||||
u = directory.get_user_by_guid(user_id)
|
||||
out["groups"] = sorted(directory.groups_of(u.dn)) if u is not None else []
|
||||
out["groups_source"] = "ad"
|
||||
out["in_ad"] = u is not None
|
||||
except LdapUnavailable:
|
||||
out["groups"] = list((r.get("directory_flags") or {}).get("groups", []))
|
||||
out["groups_source"] = "cache"
|
||||
out["in_ad"] = None
|
||||
out["sessions"] = active_sessions(conn, user_id)
|
||||
out["note"] = ROLES_NOTE
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/ad/lookup")
|
||||
def ad_lookup(
|
||||
request: Request,
|
||||
p: Principal = Depends(admin_principal), # noqa: B008
|
||||
login: str = Query(..., min_length=1, max_length=256),
|
||||
) -> dict[str, Any]:
|
||||
directory = directory_of(request)
|
||||
try:
|
||||
u = directory.find_user(login)
|
||||
if u is None:
|
||||
return {"found": False, "user": None, "groups": [], "roles": [], "disabled": False}
|
||||
found = sorted(directory.groups_of(u.dn))
|
||||
except LdapUnavailable as e:
|
||||
raise ldap_down(e) from None
|
||||
return {
|
||||
"found": True,
|
||||
"user": userdir.ad_user_public(u),
|
||||
"groups": found,
|
||||
"roles": groupmap.roles_from_groups(found),
|
||||
"disabled": u.disabled,
|
||||
"note": ROLES_NOTE,
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/users/{user_id}/pin", status_code=204)
|
||||
def clear_pin(
|
||||
user_id: uuid.UUID,
|
||||
body: ReasonBody,
|
||||
p: Principal = Depends(admin_principal), # noqa: B008
|
||||
d: Db = Depends(get_db), # noqa: B008
|
||||
) -> Response:
|
||||
reason = body.reason.strip()
|
||||
if not reason:
|
||||
raise ApiError(400, "reason_required", "Give a reason for clearing the PIN.")
|
||||
conn = d.conn
|
||||
with conn.transaction():
|
||||
if not pins.clear(conn, user_id):
|
||||
raise ApiError(404, "not_found", "That user has no PIN.")
|
||||
audit.append(
|
||||
conn,
|
||||
action="pin.cleared",
|
||||
user_id=p.user_id,
|
||||
session_id=p.session_id,
|
||||
role_snapshot=p.role_snapshot,
|
||||
subject_type="user",
|
||||
subject_id=user_id,
|
||||
it_reason=reason,
|
||||
ip=p.ip,
|
||||
)
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@router.get("/devices")
|
||||
def device_list(p: Principal = Depends(admin_principal), d: Db = Depends(get_db)) -> list[dict[str, Any]]: # noqa: B008
|
||||
with d.conn.cursor(row_factory=dict_row) as cur:
|
||||
rows = cur.execute(
|
||||
"SELECT d.id, d.name, d.registered_by, u.display_name AS registered_by_name, d.registered_at,"
|
||||
" d.last_seen_at, d.revoked_at,"
|
||||
" (SELECT count(*) FROM sessions s WHERE s.device_id = d.id AND s.revoked_at IS NULL"
|
||||
" AND s.expires_at > now()) AS active_sessions"
|
||||
" FROM devices d LEFT JOIN users u ON u.id = d.registered_by"
|
||||
" ORDER BY d.revoked_at IS NOT NULL, lower(d.name)"
|
||||
).fetchall()
|
||||
return [
|
||||
{
|
||||
"id": str(r["id"]),
|
||||
"name": r["name"],
|
||||
"registered_by": (
|
||||
{"id": str(r["registered_by"]), "display_name": r["registered_by_name"]} if r["registered_by"] else None
|
||||
),
|
||||
"registered_at": r["registered_at"],
|
||||
"last_seen_at": r["last_seen_at"],
|
||||
"revoked_at": r["revoked_at"],
|
||||
"active_sessions": int(r["active_sessions"]),
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
|
||||
@router.delete("/devices/{device_id}", status_code=204)
|
||||
def revoke_device(
|
||||
device_id: uuid.UUID,
|
||||
p: Principal = Depends(admin_principal), # noqa: B008
|
||||
d: Db = Depends(get_db), # noqa: B008
|
||||
) -> Response:
|
||||
conn = d.conn
|
||||
found = devices.get(conn, device_id)
|
||||
if found is None:
|
||||
raise ApiError(404, "not_found", "No such device.")
|
||||
with conn.transaction():
|
||||
if devices.revoke(conn, device_id, p.user_id):
|
||||
ended = sessions.revoke_where(conn, "device_id = %s AND kind = 'pin'", (device_id,), "device_revoked")
|
||||
audit.append(
|
||||
conn,
|
||||
action="device.revoked",
|
||||
user_id=p.user_id,
|
||||
session_id=p.session_id,
|
||||
role_snapshot=p.role_snapshot,
|
||||
subject_type="device",
|
||||
subject_id=device_id,
|
||||
detail={"name": found["name"], "sessions_ended": len(ended)},
|
||||
ip=p.ip,
|
||||
)
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
def _group_map_view(request: Request) -> dict[str, Any]:
|
||||
cache: dict[str, Any] | None = getattr(request.app.state, "groups_cache", None)
|
||||
if cache is None or time.monotonic() - cache["t"] > GROUPS_CACHE_SECONDS:
|
||||
try:
|
||||
in_ad: list[str] | None = directory_of(request).list_groups()
|
||||
except LdapUnavailable:
|
||||
in_ad = None
|
||||
cache = {"t": time.monotonic(), "checked_at": datetime.now(UTC), "in_ad": in_ad}
|
||||
request.app.state.groups_cache = cache
|
||||
names: list[str] | None = cache["in_ad"]
|
||||
lower = {n.lower() for n in names} if names is not None else None
|
||||
gm = groupmap.current()
|
||||
out = []
|
||||
for name, role in gm.entries:
|
||||
out.append(
|
||||
{
|
||||
"name": name,
|
||||
"role": str(role),
|
||||
"dept_code": role.dept_code,
|
||||
"in_ad": None if lower is None else name.lower() in lower,
|
||||
}
|
||||
)
|
||||
extra = sorted(n for n in names or [] if gm.role_for(n) is None)
|
||||
return {"checked_at": cache["checked_at"], "ad_reachable": names is not None, "groups": out, "extra_in_ou": extra}
|
||||
|
||||
|
||||
@router.get("/groups")
|
||||
def group_map(request: Request, p: Principal = Depends(admin_principal)) -> dict[str, Any]: # noqa: B008
|
||||
return _group_map_view(request)
|
||||
|
||||
|
||||
@router.post("/ad/refresh")
|
||||
def ad_refresh(
|
||||
request: Request,
|
||||
p: Principal = Depends(admin_principal), # noqa: B008
|
||||
d: Db = Depends(get_db), # noqa: B008
|
||||
) -> dict[str, Any]:
|
||||
try:
|
||||
res = userdir.refresh_from_ad(d.conn, directory_of(request), actor=p.actor, ip=p.ip)
|
||||
except LdapUnavailable as e:
|
||||
raise ldap_down(e) from None
|
||||
request.app.state.groups_cache = None
|
||||
return res.as_dict()
|
||||
|
||||
|
||||
@router.get("/signin-attempts")
|
||||
def signin_attempts(
|
||||
p: Principal = Depends(admin_principal), # noqa: B008
|
||||
d: Db = Depends(get_db), # noqa: B008
|
||||
limit: int = Query(100, ge=1, le=1000),
|
||||
) -> list[dict[str, Any]]:
|
||||
with d.conn.cursor(row_factory=dict_row) as cur:
|
||||
rows = cur.execute(
|
||||
"SELECT a.id, a.at, a.account, host(a.ip) AS ip, a.kind, a.reason, a.user_id, a.session_id,"
|
||||
" u.display_name FROM signin_attempts a LEFT JOIN users u ON u.id = a.user_id"
|
||||
" WHERE NOT a.ok ORDER BY a.id DESC LIMIT %s",
|
||||
(limit,),
|
||||
).fetchall()
|
||||
return [
|
||||
{
|
||||
"id": r["id"],
|
||||
"at": r["at"],
|
||||
"account": r["account"],
|
||||
"ip": r["ip"],
|
||||
"kind": r["kind"],
|
||||
"reason": r["reason"],
|
||||
"user_id": str(r["user_id"]) if r["user_id"] else None,
|
||||
"display_name": r["display_name"],
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
@@ -0,0 +1,244 @@
|
||||
"""Sign-in, sign-out, lock, unlock and the Me payload."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, Request, Response
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from .. import audit
|
||||
from ..auth import devices, signin, stepup
|
||||
from ..auth import directory as userdir
|
||||
from ..auth import pin as pins
|
||||
from .deps import (
|
||||
Db,
|
||||
Principal,
|
||||
can_register_device,
|
||||
clear_session_cookie,
|
||||
current_device,
|
||||
current_principal,
|
||||
current_principal_any,
|
||||
directory_of,
|
||||
get_db,
|
||||
ip_of,
|
||||
resolve,
|
||||
session_key,
|
||||
set_session_cookie,
|
||||
settings_of,
|
||||
user_agent_of,
|
||||
)
|
||||
from .errors import ApiError
|
||||
|
||||
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
||||
|
||||
|
||||
class PasswordSignin(BaseModel):
|
||||
login: str = Field(max_length=256)
|
||||
password: str = Field(max_length=1024)
|
||||
|
||||
|
||||
class PinSignin(BaseModel):
|
||||
emp_no: str = Field(max_length=64)
|
||||
pin: str = Field(max_length=64)
|
||||
|
||||
|
||||
class Visibility(BaseModel):
|
||||
hidden: bool
|
||||
|
||||
|
||||
class Unlock(BaseModel):
|
||||
factor: str = Field(max_length=16)
|
||||
secret: str = Field(max_length=1024)
|
||||
|
||||
|
||||
def me_payload(conn: Any, p: Principal) -> dict[str, Any]:
|
||||
s = p.session
|
||||
return {
|
||||
"user": userdir.public_user(p.user),
|
||||
"roles": p.roles,
|
||||
"screens": p.screens,
|
||||
"groups": p.groups,
|
||||
"session": {
|
||||
"id": str(s["id"]),
|
||||
"kind": p.kind,
|
||||
"created_at": s["created_at"],
|
||||
"expires_at": s["expires_at"],
|
||||
"locked": s.get("locked_since") is not None,
|
||||
"locked_since": s.get("locked_since"),
|
||||
"device": devices.public(p.device),
|
||||
},
|
||||
"pin": pins.state(conn, p.user_id).public(),
|
||||
"can_register_device": can_register_device(p),
|
||||
}
|
||||
|
||||
|
||||
def _me_after_signin(request: Request, response: Response, d: Db, result: signin.SigninResult) -> dict[str, Any]:
|
||||
set_session_cookie(request, response, result.token)
|
||||
# Resolve the new session the normal way so the payload is exactly what GET /me returns
|
||||
p = resolve(request, d, allow_locked=True, token=result.token)
|
||||
return me_payload(d.conn, p)
|
||||
|
||||
|
||||
@router.get("/context")
|
||||
def context(request: Request, d: Db = Depends(get_db)) -> dict[str, Any]: # noqa: B008
|
||||
s = settings_of(request)
|
||||
device = None
|
||||
if request.cookies.get("ps_device"):
|
||||
device = devices.public(current_device(request, d.conn))
|
||||
return {
|
||||
"device": device,
|
||||
"stack": s.stack,
|
||||
"insecure_ldap": s.ldap_allow_insecure,
|
||||
"pin_digits": {"min": s.pin_min_digits, "max": s.pin_max_digits},
|
||||
}
|
||||
|
||||
|
||||
@router.post("/signin/password")
|
||||
def signin_password(
|
||||
body: PasswordSignin,
|
||||
request: Request,
|
||||
response: Response,
|
||||
d: Db = Depends(get_db), # noqa: B008
|
||||
) -> dict[str, Any]:
|
||||
key = session_key(request)
|
||||
result = signin.password_signin(
|
||||
d.conn,
|
||||
directory_of(request),
|
||||
settings_of(request),
|
||||
key,
|
||||
login=body.login,
|
||||
password=body.password,
|
||||
ip=ip_of(request),
|
||||
user_agent=user_agent_of(request),
|
||||
)
|
||||
return _me_after_signin(request, response, d, result)
|
||||
|
||||
|
||||
@router.post("/signin/pin")
|
||||
def signin_pin(
|
||||
body: PinSignin,
|
||||
request: Request,
|
||||
response: Response,
|
||||
d: Db = Depends(get_db), # noqa: B008
|
||||
) -> dict[str, Any]:
|
||||
key = session_key(request)
|
||||
device = current_device(request, d.conn)
|
||||
if device is None:
|
||||
raise ApiError(403, "device_required", "PIN sign-in works only on a registered device.")
|
||||
result = signin.pin_signin(
|
||||
d.conn,
|
||||
directory_of(request),
|
||||
settings_of(request),
|
||||
key,
|
||||
device=device,
|
||||
emp_no=body.emp_no,
|
||||
pin=body.pin,
|
||||
ip=ip_of(request),
|
||||
user_agent=user_agent_of(request),
|
||||
)
|
||||
return _me_after_signin(request, response, d, result)
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
def me(p: Principal = Depends(current_principal_any), d: Db = Depends(get_db)) -> dict[str, Any]: # noqa: B008
|
||||
return me_payload(d.conn, p)
|
||||
|
||||
|
||||
@router.post("/signout", status_code=204)
|
||||
def signout(
|
||||
request: Request,
|
||||
p: Principal = Depends(current_principal_any), # noqa: B008
|
||||
d: Db = Depends(get_db), # noqa: B008
|
||||
) -> Response:
|
||||
from ..auth import sessions
|
||||
|
||||
conn = d.conn
|
||||
with conn.transaction():
|
||||
if sessions.revoke(conn, p.session_id, "signout", notify=False):
|
||||
audit.append(
|
||||
conn,
|
||||
action="auth.signout",
|
||||
user_id=p.user_id,
|
||||
session_id=p.session_id,
|
||||
role_snapshot=p.role_snapshot,
|
||||
ip=p.ip,
|
||||
)
|
||||
response = Response(status_code=204)
|
||||
clear_session_cookie(request, response)
|
||||
return response
|
||||
|
||||
|
||||
def _lock(d: Db, p: Principal, source: str) -> None:
|
||||
conn = d.conn
|
||||
with conn.transaction():
|
||||
row = conn.execute(
|
||||
"UPDATE sessions SET locked_since = now() WHERE id = %s AND locked_since IS NULL RETURNING id",
|
||||
(p.session_id,),
|
||||
).fetchone()
|
||||
if row is not None:
|
||||
audit.append(
|
||||
conn,
|
||||
action="auth.lock",
|
||||
user_id=p.user_id,
|
||||
session_id=p.session_id,
|
||||
role_snapshot=p.role_snapshot,
|
||||
detail={"source": source},
|
||||
ip=p.ip,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/lock", status_code=204)
|
||||
def lock(p: Principal = Depends(current_principal), d: Db = Depends(get_db)) -> Response: # noqa: B008
|
||||
_lock(d, p, "manual")
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@router.post("/visibility", status_code=204)
|
||||
def visibility(
|
||||
body: Visibility,
|
||||
p: Principal = Depends(current_principal_any), # noqa: B008
|
||||
d: Db = Depends(get_db), # noqa: B008
|
||||
) -> Response:
|
||||
# Hidden is only recorded. The lock comes from `resolve` once the report is older than
|
||||
# SESSION_HIDDEN_LOCK_SECONDS (the old build's "tab hidden over 1 min"), so a reload or an
|
||||
# in-app navigation, which also fire a hidden report, never lock the screen.
|
||||
if body.hidden:
|
||||
d.conn.execute(
|
||||
"UPDATE sessions SET hidden_since = coalesce(hidden_since, now()) WHERE id = %s", (p.session_id,)
|
||||
)
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@router.post("/unlock")
|
||||
def unlock(
|
||||
body: Unlock,
|
||||
request: Request,
|
||||
p: Principal = Depends(current_principal_any), # noqa: B008
|
||||
d: Db = Depends(get_db), # noqa: B008
|
||||
) -> dict[str, Any]:
|
||||
conn = d.conn
|
||||
if p.locked:
|
||||
stepup.verify(
|
||||
conn,
|
||||
directory_of(request),
|
||||
settings_of(request),
|
||||
p.actor,
|
||||
factor=body.factor,
|
||||
secret=body.secret,
|
||||
kind="unlock",
|
||||
ip=p.ip,
|
||||
)
|
||||
with conn.transaction():
|
||||
conn.execute("UPDATE sessions SET locked_since = NULL, last_seen_at = now() WHERE id = %s", (p.session_id,))
|
||||
audit.append(
|
||||
conn,
|
||||
action="auth.unlock",
|
||||
user_id=p.user_id,
|
||||
session_id=p.session_id,
|
||||
role_snapshot=p.role_snapshot,
|
||||
detail={"factor": body.factor},
|
||||
ip=p.ip,
|
||||
)
|
||||
p.session["locked_since"] = None
|
||||
return me_payload(conn, p)
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Departments and their stations (read-only in phase 1)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from .deps import Db, Principal, current_principal, get_db
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["departments"])
|
||||
|
||||
|
||||
@router.get("/departments")
|
||||
def departments(_: Principal = Depends(current_principal), d: Db = Depends(get_db)) -> list[dict[str, Any]]: # noqa: B008
|
||||
conn = d.conn
|
||||
rows = conn.execute(
|
||||
"SELECT code, slug, name, kind::text FROM departments WHERE active ORDER BY sort, code"
|
||||
).fetchall()
|
||||
stations = conn.execute(
|
||||
"SELECT dept_code, name FROM stations WHERE active ORDER BY dept_code, sort, name"
|
||||
).fetchall()
|
||||
by_dept: dict[str, list[str]] = {}
|
||||
for code, name in stations:
|
||||
by_dept.setdefault(code, []).append(name)
|
||||
return [{"code": r[0], "slug": r[1], "name": r[2], "kind": r[3], "stations": by_dept.get(r[0], [])} for r in rows]
|
||||
@@ -0,0 +1,361 @@
|
||||
"""Request dependencies: the database connection, the directory, the session key and the signed-in Principal."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import logging
|
||||
import uuid
|
||||
from collections.abc import Iterator
|
||||
from contextlib import AbstractContextManager
|
||||
from dataclasses import dataclass
|
||||
from datetime import timedelta
|
||||
from typing import Any
|
||||
|
||||
from fastapi import Depends, Request, Response
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from .. import audit, db
|
||||
from ..auth import devices, sessions
|
||||
from ..auth import directory as userdir
|
||||
from ..auth import groups as groupmap
|
||||
from ..auth.ldap import Directory, DirectoryProtocol, LdapUnavailable
|
||||
from ..proxy import client_ip
|
||||
from ..settings import SecretFileError, Settings
|
||||
from .errors import ApiError
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
LAST_SEEN_SLACK = timedelta(seconds=30)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- plumbing
|
||||
|
||||
|
||||
def settings_of(request: Request) -> Settings:
|
||||
s: Settings = request.app.state.settings
|
||||
return s
|
||||
|
||||
|
||||
def directory_of(request: Request) -> DirectoryProtocol:
|
||||
d: DirectoryProtocol | None = request.app.state.directory
|
||||
if d is None:
|
||||
d = Directory(settings_of(request))
|
||||
request.app.state.directory = d
|
||||
return d
|
||||
|
||||
|
||||
def session_key(request: Request) -> bytes:
|
||||
key: bytes | None = getattr(request.app.state, "session_key", None)
|
||||
if key is None:
|
||||
try:
|
||||
key = settings_of(request).session_key()
|
||||
except SecretFileError as e:
|
||||
log.error("session key unavailable: %s", e)
|
||||
raise ApiError(503, "server_misconfigured", "The server is missing its session key.") from None
|
||||
request.app.state.session_key = key
|
||||
return key
|
||||
|
||||
|
||||
class Db:
|
||||
"""One pooled app-role connection per request, opened on first use, in autocommit mode."""
|
||||
|
||||
def __init__(self, settings: Settings):
|
||||
self.settings = settings
|
||||
self._cm: AbstractContextManager[Any] | None = None
|
||||
self._conn: Any = None
|
||||
|
||||
@property
|
||||
def conn(self) -> Any:
|
||||
if self._conn is None:
|
||||
try:
|
||||
cm = db.get_pool(self.settings).connection(timeout=5.0)
|
||||
conn = cm.__enter__()
|
||||
except Exception as e:
|
||||
log.warning("database unavailable: %s", type(e).__name__)
|
||||
raise ApiError(503, "database_unavailable", "The database is not available.") from None
|
||||
conn.autocommit = True
|
||||
self._cm, self._conn = cm, conn
|
||||
return self._conn
|
||||
|
||||
def close(self) -> None:
|
||||
if self._cm is not None:
|
||||
cm, self._cm, self._conn = self._cm, None, None
|
||||
cm.__exit__(None, None, None)
|
||||
|
||||
|
||||
def get_db(request: Request) -> Iterator[Db]:
|
||||
d = Db(settings_of(request))
|
||||
try:
|
||||
yield d
|
||||
finally:
|
||||
d.close()
|
||||
|
||||
|
||||
def ip_of(request: Request) -> str | None:
|
||||
"""The client address as text, or None when it is not an IP address (test clients)."""
|
||||
host = client_ip(request)
|
||||
if not host:
|
||||
return None
|
||||
try:
|
||||
return str(ipaddress.ip_address(host))
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def user_agent_of(request: Request) -> str | None:
|
||||
ua = request.headers.get("user-agent")
|
||||
return ua[:400] if ua else None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- cookies
|
||||
|
||||
|
||||
def set_session_cookie(request: Request, response: Response, token: str) -> None:
|
||||
response.set_cookie(
|
||||
sessions.SESSION_COOKIE,
|
||||
token,
|
||||
httponly=True,
|
||||
samesite="strict",
|
||||
secure=request.url.scheme == "https",
|
||||
path="/",
|
||||
)
|
||||
|
||||
|
||||
def clear_session_cookie(request: Request, response: Response) -> None:
|
||||
response.delete_cookie(
|
||||
sessions.SESSION_COOKIE, path="/", httponly=True, samesite="strict", secure=request.url.scheme == "https"
|
||||
)
|
||||
|
||||
|
||||
def set_device_cookie(request: Request, response: Response, token: str, days: int) -> None:
|
||||
response.set_cookie(
|
||||
sessions.DEVICE_COOKIE,
|
||||
token,
|
||||
max_age=days * 86400,
|
||||
httponly=True,
|
||||
samesite="strict",
|
||||
secure=request.url.scheme == "https",
|
||||
path="/",
|
||||
)
|
||||
|
||||
|
||||
def current_device(request: Request, conn: Any) -> dict[str, Any] | None:
|
||||
token = request.cookies.get(sessions.DEVICE_COOKIE)
|
||||
if not token:
|
||||
return None
|
||||
return devices.find(conn, session_key(request), token)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- principal
|
||||
|
||||
|
||||
@dataclass
|
||||
class Principal:
|
||||
session: dict[str, Any]
|
||||
user: dict[str, Any]
|
||||
roles: list[str]
|
||||
groups: list[str]
|
||||
screens: list[str]
|
||||
is_admin: bool
|
||||
kind: str
|
||||
device: dict[str, Any] | None
|
||||
ip: str | None
|
||||
|
||||
@property
|
||||
def session_id(self) -> uuid.UUID:
|
||||
sid: uuid.UUID = self.session["id"]
|
||||
return sid
|
||||
|
||||
@property
|
||||
def user_id(self) -> uuid.UUID:
|
||||
uid: uuid.UUID = self.user["id"]
|
||||
return uid
|
||||
|
||||
@property
|
||||
def locked(self) -> bool:
|
||||
return self.session.get("locked_since") is not None
|
||||
|
||||
@property
|
||||
def role_snapshot(self) -> str:
|
||||
return ",".join(self.roles)
|
||||
|
||||
@property
|
||||
def actor(self) -> sessions.Actor:
|
||||
return sessions.Actor(
|
||||
session_id=self.session_id,
|
||||
user_id=self.user_id,
|
||||
sam_account=self.user["sam_account"],
|
||||
display_name=self.user["display_name"],
|
||||
kind=self.kind,
|
||||
roles=tuple(self.roles),
|
||||
)
|
||||
|
||||
|
||||
def _expire(conn: Any, row: dict[str, Any], reason: str, ip: str | None) -> None:
|
||||
with conn.transaction():
|
||||
if sessions.revoke(conn, row["id"], reason):
|
||||
snap = row.get("roles_snapshot") or {}
|
||||
audit.append(
|
||||
conn,
|
||||
action="auth.session_ended",
|
||||
user_id=row["user_id"],
|
||||
session_id=row["id"],
|
||||
role_snapshot=",".join(snap.get("roles", [])),
|
||||
detail={"reason": reason},
|
||||
ip=ip,
|
||||
)
|
||||
|
||||
|
||||
def _refresh_roles(
|
||||
conn: Any, directory: DirectoryProtocol, row: dict[str, Any], ip: str | None
|
||||
) -> tuple[list[str], list[str]]:
|
||||
"""Re-resolve the session's groups from AD. Raises 401 session_expired when the roles are gone."""
|
||||
uid = row["user_id"]
|
||||
try:
|
||||
u = directory.get_user_by_guid(uid)
|
||||
found = sorted(directory.groups_of(u.dn)) if u is not None and not u.disabled else []
|
||||
except LdapUnavailable as e:
|
||||
# Keep the cached roles; try again after the next interval rather than on every request
|
||||
log.warning("roles refresh skipped, AD unavailable: %s", e)
|
||||
conn.execute("UPDATE sessions SET roles_checked_at = now() WHERE id = %s", (row["id"],))
|
||||
snap = row.get("roles_snapshot") or {}
|
||||
return list(snap.get("roles", [])), list(snap.get("groups", []))
|
||||
roles = groupmap.roles_from_groups(found)
|
||||
if u is None or u.disabled or not roles:
|
||||
with conn.transaction():
|
||||
if u is None or u.disabled:
|
||||
userdir.mark_inactive(conn, uid, reason="roles_lost", gone=u is None)
|
||||
else:
|
||||
userdir.set_roles(conn, uid, [])
|
||||
_expire(conn, row, "roles_lost", ip)
|
||||
raise ApiError(401, "session_expired", "Your Packet Station roles have changed. Sign in again.")
|
||||
with conn.transaction():
|
||||
userdir.upsert_user(conn, u, groups=found)
|
||||
userdir.set_roles(conn, uid, roles)
|
||||
conn.execute(
|
||||
"UPDATE sessions SET roles_snapshot = %s, roles_checked_at = now() WHERE id = %s",
|
||||
(Jsonb({"roles": roles, "groups": found}), row["id"]),
|
||||
)
|
||||
return roles, found
|
||||
|
||||
|
||||
def resolve(request: Request, d: Db, *, allow_locked: bool, token: str | None = None) -> Principal:
|
||||
"""Load and check the session for this request (or for `token`). See the contract's "Sessions and cookies"."""
|
||||
token = token or request.cookies.get(sessions.SESSION_COOKIE)
|
||||
if not token:
|
||||
raise ApiError(401, "no_session", "Not signed in.")
|
||||
s = settings_of(request)
|
||||
key = session_key(request)
|
||||
conn = d.conn
|
||||
ip = ip_of(request)
|
||||
row = sessions.load(conn, key, token)
|
||||
if row is None or row["revoked_at"] is not None or row["expires_at"] <= row["db_now"]:
|
||||
raise ApiError(401, "no_session", "Not signed in.")
|
||||
now = row["db_now"]
|
||||
idle = now - row["last_seen_at"]
|
||||
if idle > timedelta(minutes=s.session_idle_minutes):
|
||||
_expire(conn, row, "idle", ip)
|
||||
raise ApiError(401, "session_expired", "Signed out after a period of no activity.")
|
||||
lock_source: str | None = None
|
||||
if row["locked_since"] is None and idle > timedelta(minutes=s.session_lock_minutes):
|
||||
lock_source = "idle"
|
||||
hidden_since = row.get("hidden_since")
|
||||
if hidden_since is not None:
|
||||
# The browser reported a hidden tab. Any request means it is back (or was never really
|
||||
# away, as on a reload): lock only when it stayed hidden for the old build's minute.
|
||||
if row["locked_since"] is None and now - hidden_since > timedelta(seconds=s.session_hidden_lock_seconds):
|
||||
lock_source = lock_source or "hidden"
|
||||
conn.execute("UPDATE sessions SET hidden_since = NULL WHERE id = %s", (row["id"],))
|
||||
if lock_source is not None:
|
||||
with conn.transaction():
|
||||
conn.execute(
|
||||
"UPDATE sessions SET locked_since = %s WHERE id = %s AND locked_since IS NULL", (now, row["id"])
|
||||
)
|
||||
snap = row.get("roles_snapshot") or {}
|
||||
audit.append(
|
||||
conn,
|
||||
action="auth.lock",
|
||||
user_id=row["user_id"],
|
||||
session_id=row["id"],
|
||||
role_snapshot=",".join(snap.get("roles", [])),
|
||||
detail={"source": lock_source},
|
||||
ip=ip,
|
||||
)
|
||||
row["locked_since"] = now
|
||||
if row["locked_since"] is not None and not allow_locked:
|
||||
raise ApiError(423, "locked", "The session is locked.")
|
||||
if row["locked_since"] is None and idle > LAST_SEEN_SLACK:
|
||||
conn.execute("UPDATE sessions SET last_seen_at = now() WHERE id = %s", (row["id"],))
|
||||
user = userdir.get_user(conn, row["user_id"])
|
||||
if user is None:
|
||||
raise ApiError(401, "no_session", "Not signed in.")
|
||||
snap = row.get("roles_snapshot") or {}
|
||||
roles, groups = list(snap.get("roles", [])), list(snap.get("groups", []))
|
||||
if now - row["roles_checked_at"] > timedelta(minutes=s.roles_refresh_minutes):
|
||||
roles, groups = _refresh_roles(conn, directory_of(request), row, ip)
|
||||
device = devices.get(conn, row["device_id"]) if row.get("device_id") else None
|
||||
return Principal(
|
||||
session=row,
|
||||
user=user,
|
||||
roles=roles,
|
||||
groups=groups,
|
||||
screens=groupmap.screens_for(roles),
|
||||
is_admin=groupmap.is_admin(roles),
|
||||
kind=str(row["kind"]),
|
||||
device=device,
|
||||
ip=ip,
|
||||
)
|
||||
|
||||
|
||||
def current_principal(request: Request, d: Db = Depends(get_db)) -> Principal: # noqa: B008
|
||||
"""A signed-in, unlocked session."""
|
||||
return resolve(request, d, allow_locked=False)
|
||||
|
||||
|
||||
def current_principal_any(request: Request, d: Db = Depends(get_db)) -> Principal: # noqa: B008
|
||||
"""A signed-in session, locked or not (me, unlock, signout, visibility, events)."""
|
||||
return resolve(request, d, allow_locked=True)
|
||||
|
||||
|
||||
def resolve_standalone(request: Request) -> Principal:
|
||||
"""For long-lived responses (SSE): check the session on its own connection and release it at once."""
|
||||
d = Db(settings_of(request))
|
||||
try:
|
||||
return resolve(request, d, allow_locked=True)
|
||||
finally:
|
||||
d.close()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- policy helpers
|
||||
|
||||
|
||||
def require_password_session(p: Principal) -> Principal:
|
||||
if p.kind != "password":
|
||||
raise ApiError(403, "password_session_required", "Sign in with your password to do this. A PIN session cannot.")
|
||||
return p
|
||||
|
||||
|
||||
def require_admin(p: Principal) -> Principal:
|
||||
if not p.is_admin:
|
||||
raise ApiError(403, "forbidden", "Admin only.")
|
||||
return p
|
||||
|
||||
|
||||
def can_register_device(p: Principal) -> bool:
|
||||
return p.kind == "password" and (p.is_admin or groupmap.is_shop_supervisor(p.roles))
|
||||
|
||||
|
||||
def require_device_registrar(p: Principal) -> Principal:
|
||||
require_password_session(p)
|
||||
if not can_register_device(p):
|
||||
raise ApiError(403, "forbidden", "Only an Admin or a shop Supervisor can register a device.")
|
||||
return p
|
||||
|
||||
|
||||
def admin_principal(p: Principal = Depends(current_principal)) -> Principal: # noqa: B008
|
||||
require_admin(p)
|
||||
return require_password_session(p)
|
||||
|
||||
|
||||
def password_principal(p: Principal = Depends(current_principal)) -> Principal: # noqa: B008
|
||||
return require_password_session(p)
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Every API error is JSON `{"detail": "<message>", "code": "<snake_code>"}`, with extra fields when useful."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
HTTP_CODES = {
|
||||
400: "bad_request",
|
||||
401: "no_session",
|
||||
403: "forbidden",
|
||||
404: "not_found",
|
||||
405: "method_not_allowed",
|
||||
409: "conflict",
|
||||
413: "too_large",
|
||||
429: "rate_limited",
|
||||
503: "unavailable",
|
||||
}
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(
|
||||
self,
|
||||
status: int,
|
||||
code: str,
|
||||
detail: str,
|
||||
*,
|
||||
headers: dict[str, str] | None = None,
|
||||
extra: dict[str, Any] | None = None,
|
||||
):
|
||||
super().__init__(detail)
|
||||
self.status = status
|
||||
self.code = code
|
||||
self.detail = detail
|
||||
self.headers = headers or {}
|
||||
self.extra = extra or {}
|
||||
|
||||
def body(self) -> dict[str, Any]:
|
||||
return {"detail": self.detail, "code": self.code, **self.extra}
|
||||
|
||||
|
||||
def error_response(err: ApiError) -> JSONResponse:
|
||||
return JSONResponse(err.body(), status_code=err.status, headers=err.headers)
|
||||
|
||||
|
||||
def install(app: FastAPI) -> None:
|
||||
@app.exception_handler(ApiError)
|
||||
async def _api_error(_: Request, exc: ApiError) -> JSONResponse:
|
||||
return error_response(exc)
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def _invalid(_: Request, exc: RequestValidationError) -> JSONResponse:
|
||||
errors = [{"loc": [str(x) for x in e.get("loc", ())], "msg": str(e.get("msg", ""))} for e in exc.errors()]
|
||||
where = ", ".join(".".join(e["loc"][1:]) or e["loc"][0] for e in errors if e["loc"]) or "request"
|
||||
return JSONResponse(
|
||||
{"detail": f"Invalid request: {where}", "code": "invalid_request", "errors": errors}, status_code=422
|
||||
)
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def _http(_: Request, exc: StarletteHTTPException) -> JSONResponse:
|
||||
code = HTTP_CODES.get(exc.status_code, "http_error")
|
||||
return JSONResponse(
|
||||
{"detail": str(exc.detail), "code": code}, status_code=exc.status_code, headers=exc.headers or None
|
||||
)
|
||||
@@ -0,0 +1,34 @@
|
||||
"""`GET /api/events`: the server-sent event stream (session required; locked sessions allowed)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Query, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from ..auth.groups import SCREENS
|
||||
from ..events import EventHub, stream
|
||||
from .deps import resolve_standalone, settings_of
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["events"])
|
||||
|
||||
SSE_HEADERS = {"Cache-Control": "no-cache", "X-Accel-Buffering": "no", "Connection": "keep-alive"}
|
||||
|
||||
|
||||
@router.get("/events")
|
||||
async def events(request: Request, screen: str | None = Query(None, max_length=32)) -> StreamingResponse:
|
||||
# The session check runs on its own pooled connection, returned before the stream starts
|
||||
p = await run_in_threadpool(resolve_standalone, request)
|
||||
hub: EventHub = request.app.state.events
|
||||
sub = hub.subscribe(
|
||||
session_id=p.session_id,
|
||||
user_id=p.user_id,
|
||||
display_name=p.user["display_name"],
|
||||
screen=screen if screen in SCREENS and screen in p.screens else None,
|
||||
)
|
||||
hello = {"session_id": str(p.session_id), "build": settings_of(request).ps_build}
|
||||
return StreamingResponse(
|
||||
stream(hub, sub, hello=hello, is_disconnected=request.is_disconnected),
|
||||
media_type="text/event-stream",
|
||||
headers=SSE_HEADERS,
|
||||
)
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Origin check for state-changing API requests (CSRF defence on top of SameSite=Strict cookies)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from starlette.types import ASGIApp, Receive, Scope, Send
|
||||
|
||||
UNSAFE = frozenset({"POST", "PUT", "PATCH", "DELETE"})
|
||||
MARKER = "PacketStation"
|
||||
REFUSED = {"detail": "Cross-origin request refused", "code": "bad_origin"}
|
||||
|
||||
|
||||
def _origin_of(url: str) -> str | None:
|
||||
try:
|
||||
parts = urlsplit(url)
|
||||
except ValueError:
|
||||
return None
|
||||
if not parts.scheme or not parts.netloc:
|
||||
return None
|
||||
return f"{parts.scheme}://{parts.netloc}".lower()
|
||||
|
||||
|
||||
def allowed(scope: Scope) -> bool:
|
||||
"""True when the request is safe, not under /api, or carries a same-origin Origin and the marker header."""
|
||||
if scope.get("method", "GET").upper() not in UNSAFE or not scope.get("path", "").startswith("/api"):
|
||||
return True
|
||||
headers = {k.decode("latin-1").lower(): v.decode("latin-1") for k, v in scope.get("headers", [])}
|
||||
if headers.get("x-requested-with", "") != MARKER:
|
||||
return False
|
||||
host = headers.get("host", "").strip().lower()
|
||||
if not host:
|
||||
return False
|
||||
expected = f"{scope.get('scheme', 'http')}://{host}"
|
||||
origin = headers.get("origin")
|
||||
if origin and origin != "null":
|
||||
got = _origin_of(origin)
|
||||
elif headers.get("referer"):
|
||||
got = _origin_of(headers["referer"])
|
||||
else:
|
||||
got = None
|
||||
return got == expected
|
||||
|
||||
|
||||
class OriginCheckMiddleware:
|
||||
"""Runs after TrustedProxyMiddleware so the scheme is the client's."""
|
||||
|
||||
def __init__(self, app: ASGIApp):
|
||||
self.app = app
|
||||
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||
if scope["type"] != "http" or allowed(scope):
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
body = json.dumps(REFUSED).encode("utf-8")
|
||||
await send(
|
||||
{
|
||||
"type": "http.response.start",
|
||||
"status": 403,
|
||||
"headers": [(b"content-type", b"application/json"), (b"content-length", str(len(body)).encode())],
|
||||
}
|
||||
)
|
||||
await send({"type": "http.response.body", "body": body})
|
||||
@@ -0,0 +1 @@
|
||||
"""Identity: AD groups and roles, LDAP, sessions, devices, PINs, rate limits, step-up and signatures."""
|
||||
@@ -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"]}
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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]
|
||||
@@ -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
|
||||
@@ -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),
|
||||
)
|
||||
@@ -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)
|
||||
@@ -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,
|
||||
)
|
||||
@@ -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,
|
||||
)
|
||||
@@ -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},
|
||||
)
|
||||
@@ -88,6 +88,40 @@ def cmd_doctor(a: argparse.Namespace) -> int:
|
||||
return 1 if doctor.failed(checks) else 0
|
||||
|
||||
|
||||
def cmd_ad_groups(a: argparse.Namespace) -> int:
|
||||
"""Print the 50 mapped group names, one per line, in map order (deploy/samba/groups.txt is a copy)."""
|
||||
from .auth import groups
|
||||
|
||||
if a.list:
|
||||
for name in groups.group_names():
|
||||
print(name)
|
||||
return 0
|
||||
print("packetstation ad-groups: say what to do (--list)", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
def cmd_ad_refresh(_: argparse.Namespace) -> int:
|
||||
"""Enumerate the mapped AD groups with the service account and refresh the users table."""
|
||||
from . import db
|
||||
from .auth import groups
|
||||
from .auth.directory import refresh_from_ad
|
||||
from .auth.ldap import Directory, LdapUnavailable
|
||||
|
||||
s = _settings()
|
||||
_setup_logging(s.log_level)
|
||||
try:
|
||||
with db.connect_as("app", s, autocommit=True) as conn:
|
||||
deps = groups.load_departments(conn)
|
||||
if deps:
|
||||
groups.use_departments(deps)
|
||||
res = refresh_from_ad(conn, Directory(s))
|
||||
except LdapUnavailable as e:
|
||||
log.error("ad-refresh: AD unavailable: %s", e)
|
||||
return 1
|
||||
print(json.dumps(res.as_dict(), indent=2))
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_version(_: argparse.Namespace) -> int:
|
||||
print(f"packetstation {__version__} build {os.environ.get('PS_BUILD', 'dev')}")
|
||||
return 0
|
||||
@@ -126,6 +160,12 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
d.add_argument("--skip", metavar="LIST", help="Comma list of: visual,mfiles,ldap,smtp,db,volume")
|
||||
d.add_argument("--send-test", metavar="ADDR", help="Also send one test message to ADDR")
|
||||
d.set_defaults(func=cmd_doctor)
|
||||
g = sub.add_parser("ad-groups", help="The AD groups Packet Station maps to roles")
|
||||
g.add_argument("--list", action="store_true", help="Print the 50 group names, one per line")
|
||||
g.set_defaults(func=cmd_ad_groups)
|
||||
sub.add_parser("ad-refresh", help="Refresh users and roles from AD now; prints the counts as JSON").set_defaults(
|
||||
func=cmd_ad_refresh
|
||||
)
|
||||
sub.add_parser("version", help="Print the version and build").set_defaults(func=cmd_version)
|
||||
h = sub.add_parser("healthcheck", help="Container healthcheck (exit 0 healthy, 1 not)")
|
||||
h.add_argument("target", choices=["app", "worker"])
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
"""Server-sent events: one LISTEN connection per process, fanned out to every subscriber queue, plus presence.
|
||||
|
||||
A thread holds a sync psycopg connection (app role) doing LISTEN ps_events and pushes each NOTIFY payload
|
||||
to the event loop with call_soon_threadsafe. It reconnects with backoff when the database drops. Presence is
|
||||
kept in process (one uvicorn worker); phase 8 completes it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import uuid
|
||||
from collections.abc import AsyncIterator, Awaitable, Callable
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
CHANNEL = "ps_events"
|
||||
PING_SECONDS = 25.0
|
||||
QUEUE_MAX = 1000
|
||||
BACKOFF_MAX = 30.0
|
||||
|
||||
Item = tuple[str, dict[str, Any]]
|
||||
|
||||
|
||||
def publish(conn: Any, payload: dict[str, Any]) -> None:
|
||||
"""NOTIFY ps_events with a JSON payload. Inside a transaction it is delivered on commit.
|
||||
|
||||
`payload["event"]` names the SSE event (default `changed`); the rest is the event data.
|
||||
"""
|
||||
conn.execute("SELECT ps_notify(%s, %s)", (CHANNEL, json.dumps(payload, default=str, separators=(",", ":"))))
|
||||
|
||||
|
||||
@dataclass(eq=False)
|
||||
class Subscriber:
|
||||
queue: asyncio.Queue[Item]
|
||||
loop: asyncio.AbstractEventLoop
|
||||
session_id: str
|
||||
user_id: str
|
||||
display_name: str
|
||||
screen: str | None = None
|
||||
id: str = field(default_factory=lambda: uuid.uuid4().hex)
|
||||
closed: bool = False
|
||||
|
||||
def put(self, item: Item) -> None:
|
||||
"""Called on the event loop."""
|
||||
try:
|
||||
self.queue.put_nowait(item)
|
||||
except asyncio.QueueFull:
|
||||
log.warning("event queue full for a subscriber; dropping one event")
|
||||
|
||||
|
||||
class EventHub:
|
||||
def __init__(self, connect: Callable[[], Any] | None = None):
|
||||
self._connect = connect
|
||||
self._subs: dict[str, Subscriber] = {}
|
||||
self._lock = threading.Lock()
|
||||
self._stop = threading.Event()
|
||||
self._thread: threading.Thread | None = None
|
||||
self.connected = False
|
||||
|
||||
# ------------------------------------------------ subscribers
|
||||
|
||||
def subscribe(self, *, session_id: Any, user_id: Any, display_name: str, screen: str | None = None) -> Subscriber:
|
||||
"""Register a subscriber on the running loop and broadcast presence."""
|
||||
sub = Subscriber(
|
||||
queue=asyncio.Queue(maxsize=QUEUE_MAX),
|
||||
loop=asyncio.get_running_loop(),
|
||||
session_id=str(session_id),
|
||||
user_id=str(user_id),
|
||||
display_name=display_name,
|
||||
screen=screen,
|
||||
)
|
||||
with self._lock:
|
||||
self._subs[sub.id] = sub
|
||||
self._broadcast_presence()
|
||||
return sub
|
||||
|
||||
def unsubscribe(self, sub: Subscriber) -> None:
|
||||
sub.closed = True
|
||||
with self._lock:
|
||||
removed = self._subs.pop(sub.id, None)
|
||||
if removed is not None:
|
||||
self._broadcast_presence()
|
||||
|
||||
def presence(self) -> dict[str, Any]:
|
||||
with self._lock:
|
||||
subs = list(self._subs.values())
|
||||
seen: dict[tuple[str, str | None], dict[str, Any]] = {}
|
||||
for s in subs:
|
||||
seen.setdefault(
|
||||
(s.user_id, s.screen), {"user_id": s.user_id, "display_name": s.display_name, "screen": s.screen}
|
||||
)
|
||||
users = sorted(seen.values(), key=lambda u: (u["display_name"].lower(), u["screen"] or ""))
|
||||
return {"users": users}
|
||||
|
||||
def _send(self, sub: Subscriber, item: Item) -> None:
|
||||
try:
|
||||
sub.loop.call_soon_threadsafe(sub.put, item)
|
||||
except RuntimeError: # loop closed
|
||||
pass
|
||||
|
||||
def _broadcast_presence(self) -> None:
|
||||
item: Item = ("presence", self.presence())
|
||||
with self._lock:
|
||||
subs = list(self._subs.values())
|
||||
for s in subs:
|
||||
self._send(s, item)
|
||||
|
||||
def _deliver(self, payload: str) -> None:
|
||||
"""Fan one NOTIFY payload out. `session` events go only to the subscribers of that session."""
|
||||
try:
|
||||
data = json.loads(payload)
|
||||
except ValueError:
|
||||
log.warning("ignoring a non-JSON ps_events payload")
|
||||
return
|
||||
if not isinstance(data, dict):
|
||||
return
|
||||
name = str(data.pop("event", "changed"))
|
||||
with self._lock:
|
||||
subs = list(self._subs.values())
|
||||
if name == "session":
|
||||
target = str(data.get("session_id"))
|
||||
subs = [s for s in subs if s.session_id == target]
|
||||
for s in subs:
|
||||
self._send(s, (name, data))
|
||||
|
||||
# ------------------------------------------------ listener thread
|
||||
|
||||
def start(self) -> None:
|
||||
if self._connect is None or (self._thread and self._thread.is_alive()):
|
||||
return
|
||||
self._stop.clear()
|
||||
self._thread = threading.Thread(target=self._run, name="ps-events", daemon=True)
|
||||
self._thread.start()
|
||||
|
||||
def stop(self, timeout: float = 5.0) -> None:
|
||||
self._stop.set()
|
||||
if self._thread is not None:
|
||||
self._thread.join(timeout)
|
||||
self._thread = None
|
||||
|
||||
def _run(self) -> None:
|
||||
assert self._connect is not None
|
||||
delay = 1.0
|
||||
while not self._stop.is_set():
|
||||
conn = None
|
||||
try:
|
||||
conn = self._connect()
|
||||
conn.execute(f"LISTEN {CHANNEL}")
|
||||
self.connected = True
|
||||
delay = 1.0
|
||||
log.info("events hub listening on %s", CHANNEL)
|
||||
while not self._stop.is_set():
|
||||
for n in conn.notifies(timeout=1.0):
|
||||
self._deliver(n.payload)
|
||||
except Exception as e:
|
||||
if not self._stop.is_set():
|
||||
log.warning("events hub: %s; retrying in %.0f s", type(e).__name__, delay)
|
||||
finally:
|
||||
self.connected = False
|
||||
if conn is not None:
|
||||
with contextlib.suppress(Exception):
|
||||
conn.close()
|
||||
if self._stop.wait(delay):
|
||||
break
|
||||
delay = min(delay * 2, BACKOFF_MAX)
|
||||
|
||||
|
||||
def format_sse(event: str, data: dict[str, Any]) -> str:
|
||||
return f"event: {event}\ndata: {json.dumps(data, default=str, separators=(',', ':'))}\n\n"
|
||||
|
||||
|
||||
async def stream(
|
||||
hub: EventHub,
|
||||
sub: Subscriber,
|
||||
*,
|
||||
hello: dict[str, Any],
|
||||
is_disconnected: Callable[[], Awaitable[bool]],
|
||||
ping_seconds: float = PING_SECONDS,
|
||||
) -> AsyncIterator[str]:
|
||||
"""The SSE body: `hello`, then queued events, with a `: ping` comment when idle. Ends on own revoke."""
|
||||
try:
|
||||
yield format_sse("hello", hello)
|
||||
while True:
|
||||
if await is_disconnected():
|
||||
break
|
||||
try:
|
||||
name, data = await asyncio.wait_for(sub.queue.get(), timeout=ping_seconds)
|
||||
except TimeoutError:
|
||||
yield ": ping\n\n"
|
||||
continue
|
||||
yield format_sse(name, data)
|
||||
if name == "session" and data.get("session_id") == sub.session_id and data.get("action") == "revoked":
|
||||
break
|
||||
finally:
|
||||
hub.unsubscribe(sub)
|
||||
@@ -14,6 +14,10 @@ from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from . import db, guard
|
||||
from .api import errors as api_errors
|
||||
from .api.origin import OriginCheckMiddleware
|
||||
from .auth.ldap import DirectoryProtocol
|
||||
from .events import EventHub
|
||||
from .proxy import TrustedProxies, TrustedProxyMiddleware
|
||||
from .security import RequestLogMiddleware, SecurityHeadersMiddleware
|
||||
from .settings import Settings, get_settings
|
||||
@@ -39,22 +43,43 @@ def _static_file(static_dir: Path, path: str) -> Path | None:
|
||||
return candidate
|
||||
|
||||
|
||||
def create_app(settings: Settings | None = None, *, run_guard: bool = True) -> FastAPI:
|
||||
def _load_departments(s: Settings) -> None:
|
||||
"""Rebuild the group map from the departments table; the built-in seed stays when the DB is not there."""
|
||||
from .auth import groups
|
||||
|
||||
try:
|
||||
with db.connect_as("app", s, autocommit=True) as conn:
|
||||
deps = groups.load_departments(conn)
|
||||
except Exception as e:
|
||||
log.warning("group map from the built-in departments (database: %s)", type(e).__name__)
|
||||
return
|
||||
if deps:
|
||||
groups.use_departments(deps)
|
||||
|
||||
|
||||
def create_app(
|
||||
settings: Settings | None = None, *, run_guard: bool = True, directory: DirectoryProtocol | None = None
|
||||
) -> FastAPI:
|
||||
s = settings or get_settings()
|
||||
if run_guard:
|
||||
guard.startup_checks(s)
|
||||
trusted = TrustedProxies(s.trusted_proxy_host)
|
||||
hub = EventHub(connect=lambda: db.connect_as("app", s, autocommit=True))
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
|
||||
await asyncio.to_thread(trusted.refresh)
|
||||
task = asyncio.create_task(trusted.run()) if trusted.host else None
|
||||
deps_task = asyncio.create_task(asyncio.to_thread(_load_departments, s))
|
||||
hub.start() # connects in its own thread and retries with backoff; never blocks startup
|
||||
log.info("packetstation app starting", extra={"ps": {"build": s.ps_build, "stack": s.stack}})
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if task:
|
||||
task.cancel()
|
||||
deps_task.cancel()
|
||||
await asyncio.to_thread(hub.stop)
|
||||
await run_in_threadpool(db.close_pool)
|
||||
|
||||
app = FastAPI(
|
||||
@@ -62,6 +87,17 @@ def create_app(settings: Settings | None = None, *, run_guard: bool = True) -> F
|
||||
)
|
||||
app.state.settings = s
|
||||
app.state.trusted = trusted
|
||||
app.state.directory = directory # None: built from settings on first use
|
||||
app.state.events = hub
|
||||
app.state.session_key = None
|
||||
app.state.groups_cache = None
|
||||
api_errors.install(app)
|
||||
|
||||
from .api import account, admin, auth, departments
|
||||
from .api import events as events_api
|
||||
|
||||
for module in (auth, account, admin, departments, events_api):
|
||||
app.include_router(module.router)
|
||||
|
||||
@app.get("/healthz")
|
||||
def healthz() -> dict[str, Any]:
|
||||
@@ -93,7 +129,8 @@ def create_app(settings: Settings | None = None, *, run_guard: bool = True) -> F
|
||||
return FileResponse(found)
|
||||
return FileResponse(index, headers={"Cache-Control": "no-cache"})
|
||||
|
||||
# Last added runs first: proxy rewrite, then the log (sees the real ip), then headers
|
||||
# Last added runs first: proxy rewrite, then the log (sees the real ip), then headers, then the Origin check
|
||||
app.add_middleware(OriginCheckMiddleware)
|
||||
app.add_middleware(SecurityHeadersMiddleware)
|
||||
app.add_middleware(RequestLogMiddleware, build=s.ps_build)
|
||||
app.add_middleware(TrustedProxyMiddleware, trusted=trusted)
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
-- 0002_identity: departments and stations (seed), users, roles, devices, sessions, PINs,
|
||||
-- sign-in attempts and signatures. Runs as ps_migrate; 0001's default privileges give ps_app
|
||||
-- SELECT, INSERT, UPDATE, DELETE on every table here. Append-only tables revoke below.
|
||||
|
||||
CREATE TYPE role_kind AS ENUM (
|
||||
'admin', 'clerical', 'clerical_supervisor', 'warehouse', 'warehouse_supervisor', 'qc',
|
||||
'qc_supervisor', 'pm', 'shop_worker', 'shop_lead', 'shop_supervisor'
|
||||
);
|
||||
CREATE TYPE session_kind AS ENUM ('password', 'pin');
|
||||
CREATE TYPE sig_factor AS ENUM ('password', 'pin');
|
||||
CREATE TYPE dept_kind AS ENUM ('support', 'shop');
|
||||
|
||||
-- ---------------------------------------------------------------- departments and stations
|
||||
|
||||
CREATE TABLE departments (
|
||||
code text PRIMARY KEY,
|
||||
slug text UNIQUE NOT NULL,
|
||||
name text NOT NULL,
|
||||
kind dept_kind NOT NULL,
|
||||
sort int NOT NULL,
|
||||
active bool NOT NULL DEFAULT true,
|
||||
supervisor_group bool NOT NULL DEFAULT true
|
||||
);
|
||||
|
||||
-- The group names derive from code and slug, so neither may ever change.
|
||||
CREATE FUNCTION ps_departments_immutable() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF NEW.code IS DISTINCT FROM OLD.code OR NEW.slug IS DISTINCT FROM OLD.slug THEN
|
||||
RAISE EXCEPTION 'departments.code and departments.slug cannot change'
|
||||
USING ERRCODE = 'insufficient_privilege';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
|
||||
CREATE TRIGGER departments_code_slug_immutable
|
||||
BEFORE UPDATE ON departments
|
||||
FOR EACH ROW EXECUTE FUNCTION ps_departments_immutable();
|
||||
|
||||
CREATE TABLE stations (
|
||||
id bigserial PRIMARY KEY,
|
||||
dept_code text NOT NULL REFERENCES departments (code),
|
||||
name text NOT NULL,
|
||||
sort int NOT NULL DEFAULT 0,
|
||||
active bool NOT NULL DEFAULT true,
|
||||
UNIQUE (dept_code, name)
|
||||
);
|
||||
|
||||
INSERT INTO departments (code, slug, name, kind, sort, supervisor_group) VALUES
|
||||
('CL', 'Clerical', 'Clerical', 'support', 10, true),
|
||||
('WH', 'Warehouse', 'Warehouse', 'support', 20, true),
|
||||
('QC', 'QC', 'Q.C.', 'support', 30, true),
|
||||
('PM', 'ProjectMgmt', 'Project Management', 'support', 40, false),
|
||||
('01', 'Layout', 'Layout', 'shop', 50, true),
|
||||
('02', 'SouthLayout', 'PESCO South Layout', 'shop', 60, true),
|
||||
('03', 'WeldParts', 'Weld Parts', 'shop', 70, true),
|
||||
('04', 'SouthWeld', 'PESCO South Weld', 'shop', 80, true),
|
||||
('05', 'SouthWeldSS', 'PESCO South Weld SS', 'shop', 90, true),
|
||||
('06', 'CodeBldg2', 'Code Bldg 2', 'shop', 100, true),
|
||||
('07', 'CodeBldg3', 'Code Bldg 3', 'shop', 110, true),
|
||||
('08', 'Subassembly', 'Subassembly', 'shop', 120, true),
|
||||
('09', 'Hydro', 'Hydro', 'shop', 130, true),
|
||||
('10', 'WeldAssembly', 'Weld Assembly', 'shop', 140, true),
|
||||
('11', 'FinalAssyNorth', 'Final Assembly - North', 'shop', 150, true),
|
||||
('12', 'FinalAssySouth', 'Final Assembly - South', 'shop', 160, true),
|
||||
('13', 'PaintSandblast', 'Paint-Sandblast', 'shop', 170, true),
|
||||
('14', 'Electrical', 'Electrical', 'shop', 180, true);
|
||||
|
||||
INSERT INTO stations (dept_code, name, sort)
|
||||
SELECT d.code, 'Station ' || n, n
|
||||
FROM departments d CROSS JOIN generate_series(1, 4) AS n
|
||||
WHERE d.code IN ('01', '02', '08', '11', '12', '14');
|
||||
|
||||
INSERT INTO stations (dept_code, name, sort)
|
||||
SELECT d.code, 'Stall ' || n, n
|
||||
FROM departments d CROSS JOIN generate_series(1, 6) AS n
|
||||
WHERE d.code IN ('03', '04', '05', '06', '07', '10');
|
||||
|
||||
INSERT INTO stations (dept_code, name, sort) VALUES
|
||||
('09', 'Hydro Bay 1', 1),
|
||||
('09', 'Hydro Bay 2', 2),
|
||||
('13', 'Blast Booth', 1),
|
||||
('13', 'Paint Booth 1', 2),
|
||||
('13', 'Paint Booth 2', 3);
|
||||
|
||||
-- ---------------------------------------------------------------- users and roles
|
||||
|
||||
-- id is the AD objectGUID. emp_no stays text and is not unique: duplicates are stored and flagged.
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
sam_account text NOT NULL,
|
||||
upn text,
|
||||
display_name text NOT NULL,
|
||||
emp_no text,
|
||||
email text,
|
||||
welder_stamp text,
|
||||
active bool NOT NULL DEFAULT true,
|
||||
directory_flags jsonb NOT NULL DEFAULT '{}',
|
||||
ad_synced_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
last_signin_at timestamptz
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX users_sam_account_lower ON users (lower(sam_account));
|
||||
CREATE INDEX users_emp_no ON users (emp_no);
|
||||
|
||||
CREATE TABLE user_roles (
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
role role_kind NOT NULL,
|
||||
dept_code text REFERENCES departments (code),
|
||||
synced_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX user_roles_unique ON user_roles (user_id, role, coalesce(dept_code, ''));
|
||||
|
||||
-- ---------------------------------------------------------------- devices and sessions
|
||||
|
||||
CREATE TABLE devices (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
name text NOT NULL,
|
||||
token_hash bytea UNIQUE NOT NULL,
|
||||
registered_by uuid REFERENCES users (id),
|
||||
registered_at timestamptz NOT NULL DEFAULT now(),
|
||||
last_seen_at timestamptz,
|
||||
revoked_at timestamptz,
|
||||
revoked_by uuid
|
||||
);
|
||||
|
||||
CREATE TABLE sessions (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id uuid NOT NULL REFERENCES users (id),
|
||||
token_hash bytea UNIQUE NOT NULL,
|
||||
kind session_kind NOT NULL,
|
||||
device_id uuid REFERENCES devices (id),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
expires_at timestamptz NOT NULL,
|
||||
last_seen_at timestamptz NOT NULL DEFAULT now(),
|
||||
locked_since timestamptz,
|
||||
revoked_at timestamptz,
|
||||
revoked_reason text,
|
||||
ip inet,
|
||||
user_agent text,
|
||||
roles_snapshot jsonb NOT NULL,
|
||||
roles_checked_at timestamptz NOT NULL DEFAULT now(),
|
||||
stepup_failures int NOT NULL DEFAULT 0,
|
||||
hidden_since timestamptz
|
||||
);
|
||||
|
||||
CREATE INDEX sessions_user_active ON sessions (user_id) WHERE revoked_at IS NULL;
|
||||
CREATE INDEX sessions_device_active ON sessions (device_id) WHERE revoked_at IS NULL;
|
||||
|
||||
CREATE TABLE user_pins (
|
||||
user_id uuid PRIMARY KEY REFERENCES users (id) ON DELETE CASCADE,
|
||||
hash text NOT NULL,
|
||||
failed_count int NOT NULL DEFAULT 0,
|
||||
disabled_at timestamptz,
|
||||
set_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------- append-only records
|
||||
|
||||
-- account: lower(login) for password sign-in, emp:<emp_no> for PIN sign-in,
|
||||
-- user:<uuid> for unlock, signature and pin_set.
|
||||
CREATE TABLE signin_attempts (
|
||||
id bigserial PRIMARY KEY,
|
||||
at timestamptz NOT NULL DEFAULT now(),
|
||||
account text NOT NULL,
|
||||
ip inet,
|
||||
kind text NOT NULL CHECK (kind IN ('password', 'pin', 'unlock', 'signature', 'pin_set')),
|
||||
ok bool NOT NULL,
|
||||
reason text,
|
||||
user_id uuid,
|
||||
session_id uuid
|
||||
);
|
||||
|
||||
CREATE INDEX signin_attempts_account_at ON signin_attempts (account, at);
|
||||
CREATE INDEX signin_attempts_ip_at ON signin_attempts (ip, at);
|
||||
CREATE INDEX signin_attempts_user_at ON signin_attempts (user_id, at);
|
||||
|
||||
CREATE TRIGGER signin_attempts_append_only
|
||||
BEFORE UPDATE OR DELETE ON signin_attempts
|
||||
FOR EACH ROW EXECUTE FUNCTION ps_append_only();
|
||||
CREATE TRIGGER signin_attempts_no_truncate
|
||||
BEFORE TRUNCATE ON signin_attempts
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION ps_append_only();
|
||||
|
||||
CREATE TABLE signatures (
|
||||
id bigserial PRIMARY KEY,
|
||||
at timestamptz NOT NULL DEFAULT now(),
|
||||
user_id uuid NOT NULL,
|
||||
session_id uuid,
|
||||
account text,
|
||||
display_name text,
|
||||
session_kind session_kind,
|
||||
factor sig_factor,
|
||||
action text NOT NULL,
|
||||
meaning text,
|
||||
packet_id bigint,
|
||||
subject_type text,
|
||||
subject_id text,
|
||||
content_hash bytea
|
||||
);
|
||||
|
||||
CREATE INDEX signatures_packet ON signatures (packet_id) WHERE packet_id IS NOT NULL;
|
||||
CREATE INDEX signatures_user_at ON signatures (user_id, at);
|
||||
|
||||
CREATE TRIGGER signatures_append_only
|
||||
BEFORE UPDATE OR DELETE ON signatures
|
||||
FOR EACH ROW EXECUTE FUNCTION ps_append_only();
|
||||
CREATE TRIGGER signatures_no_truncate
|
||||
BEFORE TRUNCATE ON signatures
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION ps_append_only();
|
||||
|
||||
-- Explicit, after the default privileges: the app may only read and append these two.
|
||||
REVOKE UPDATE, DELETE, TRUNCATE ON signin_attempts, signatures FROM ps_app;
|
||||
GRANT SELECT, INSERT ON signin_attempts, signatures TO ps_app;
|
||||
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO ps_app;
|
||||
@@ -83,6 +83,23 @@ class Settings(BaseSettings):
|
||||
smtp_ca_bundle: Path | None = None
|
||||
notify_dry_run: bool = False
|
||||
|
||||
session_idle_minutes: int = Field(default=15, ge=1)
|
||||
session_lock_minutes: int = Field(default=3, ge=1)
|
||||
session_hidden_lock_seconds: int = Field(default=60, ge=0)
|
||||
session_password_hours: int = Field(default=12, ge=1)
|
||||
session_pin_hours: int = Field(default=10, ge=1)
|
||||
roles_refresh_minutes: int = Field(default=15, ge=1)
|
||||
signin_account_limit: int = Field(default=5, ge=1)
|
||||
signin_account_window_minutes: int = Field(default=5, ge=1)
|
||||
signin_account_cooldown_minutes: int = Field(default=10, ge=0)
|
||||
signin_ip_limit: int = Field(default=30, ge=1)
|
||||
signin_ip_window_minutes: int = Field(default=5, ge=1)
|
||||
pin_max_failures: int = Field(default=5, ge=1)
|
||||
stepup_max_failures: int = Field(default=3, ge=1)
|
||||
device_cookie_days: int = Field(default=365, ge=1)
|
||||
pin_min_digits: int = Field(default=6, ge=4)
|
||||
pin_max_digits: int = Field(default=12, ge=4)
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _blank_is_unset(cls, data: Any) -> Any:
|
||||
@@ -110,6 +127,12 @@ class Settings(BaseSettings):
|
||||
raise ValueError("LDAP_ALLOW_INSECURE=true is refused on STACK=prod")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _pin_digits(self) -> Settings:
|
||||
if self.pin_min_digits > self.pin_max_digits:
|
||||
raise ValueError("PIN_MIN_DIGITS must not exceed PIN_MAX_DIGITS")
|
||||
return self
|
||||
|
||||
@property
|
||||
def ldap_urls(self) -> list[str]:
|
||||
return self.ldap_url.split()
|
||||
@@ -129,6 +152,13 @@ class Settings(BaseSettings):
|
||||
def ldap_password(self) -> str:
|
||||
return read_secret(self.ldap_password_file, "LDAP_PASSWORD_FILE")
|
||||
|
||||
def session_key(self) -> bytes:
|
||||
"""The HMAC key for session and device tokens, from SESSION_KEY_FILE."""
|
||||
key = read_secret(self.session_key_file, "SESSION_KEY_FILE").strip()
|
||||
if len(key) < 16:
|
||||
raise SecretFileError(f"SESSION_KEY_FILE file {self.session_key_file} holds a key that is too short")
|
||||
return key.encode("utf-8")
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def get_settings() -> Settings:
|
||||
|
||||
Reference in New Issue
Block a user