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