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})
|
||||
Reference in New Issue
Block a user