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:
@@ -7,3 +7,7 @@ Dockerfile text eol=lf
|
|||||||
*.woff binary
|
*.woff binary
|
||||||
*.woff2 binary
|
*.woff2 binary
|
||||||
*.pdf binary
|
*.pdf binary
|
||||||
|
*.yml text eol=lf
|
||||||
|
*.yaml text eol=lf
|
||||||
|
*.env text eol=lf
|
||||||
|
deploy/samba/groups.txt text eol=lf
|
||||||
|
|||||||
+38
-18
@@ -133,21 +133,41 @@ jobs:
|
|||||||
cache-to: type=registry,ref=${{ env.IMAGE_NAME }}:buildcache,mode=max
|
cache-to: type=registry,ref=${{ env.IMAGE_NAME }}:buildcache,mode=max
|
||||||
provenance: false
|
provenance: false
|
||||||
|
|
||||||
# Phase 1: end to end. Compose up with the CI overlay and the Samba DC, seed fixtures,
|
# End to end. Compose up with the CI overlay and the throwaway Samba DC, run the Playwright
|
||||||
# run the Playwright scenarios, upload the report, then down -v.
|
# scenarios, upload the report, then down -v. The runner needs a Docker daemon whose bind
|
||||||
# e2e:
|
# mounts see this checkout (open question 15, deploy/samba/README.md).
|
||||||
# needs: [server, frontend]
|
e2e:
|
||||||
# runs-on: ubuntu-latest
|
needs: [server, frontend]
|
||||||
# steps:
|
runs-on: ubuntu-latest
|
||||||
# - uses: actions/checkout@v4
|
timeout-minutes: 30
|
||||||
# - run: deploy/ci/make-secrets.sh
|
env:
|
||||||
# - run: >-
|
COMPOSE: >-
|
||||||
# docker compose -p packetstation-ci --env-file deploy/ci/ci.env
|
docker compose -p packetstation-ci --env-file deploy/ci/ci.env
|
||||||
# -f deploy/compose.yaml -f deploy/compose.ci.yaml up -d --build --wait
|
-f deploy/compose.yaml -f deploy/compose.ci.yaml
|
||||||
# - run: >-
|
steps:
|
||||||
# docker compose -p packetstation-ci --env-file deploy/ci/ci.env
|
- uses: actions/checkout@v4
|
||||||
# -f deploy/compose.yaml -f deploy/compose.ci.yaml --profile e2e run --rm playwright
|
|
||||||
# - if: always()
|
- name: Throwaway secrets
|
||||||
# run: >-
|
run: bash deploy/ci/make-secrets.sh
|
||||||
# docker compose -p packetstation-ci --env-file deploy/ci/ci.env
|
|
||||||
# -f deploy/compose.yaml -f deploy/compose.ci.yaml down -v
|
- name: Stack up (app, worker, postgres, Samba DC)
|
||||||
|
run: $COMPOSE up -d --build --wait --wait-timeout 300
|
||||||
|
|
||||||
|
- name: Playwright
|
||||||
|
run: $COMPOSE --profile e2e run --rm playwright
|
||||||
|
|
||||||
|
- name: Stack logs
|
||||||
|
if: failure()
|
||||||
|
run: $COMPOSE logs --no-color --tail 300 samba-dc migrate app worker
|
||||||
|
|
||||||
|
- name: Upload Playwright report
|
||||||
|
if: always()
|
||||||
|
uses: actions/upload-artifact@v3
|
||||||
|
with:
|
||||||
|
name: playwright-report
|
||||||
|
path: tests/e2e/playwright-report
|
||||||
|
if-no-files-found: ignore
|
||||||
|
|
||||||
|
- name: Stack down
|
||||||
|
if: always()
|
||||||
|
run: $COMPOSE --profile e2e down -v
|
||||||
|
|||||||
@@ -6,6 +6,20 @@ All notable changes to this project are recorded here. The format follows [Keep
|
|||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|
||||||
|
- Phase 1: identity. Sign-in with the domain account and password against PESCO's Active Directory over LDAPS (search with the service account, then bind as the user; nested groups resolved; disabled accounts refused). Roles are the union of a person's `PS-*` groups, mapped by a table derived from the department list.
|
||||||
|
- Server-side sessions: HttpOnly, SameSite=Strict cookie, idle sign-out after 15 minutes, absolute 12 hours for password sessions and 10 hours for PIN sessions, server-recorded lock after 3 idle minutes or a tab hidden for over a minute, step-up unlock with PIN or password. Origin and `X-Requested-With` check on every state-changing request.
|
||||||
|
- Optional Packet Station PIN, 6 to 12 digits, set by the user with their domain password, hashed with Argon2id. PIN sign-in by employee ID on registered devices only. Five wrong attempts disable the PIN; three wrong attempts at unlock or signature end the session.
|
||||||
|
- Rate limits before any AD bind: 5 failed attempts per account per 5 minutes then a 10-minute cooldown, 30 per client address per 5 minutes.
|
||||||
|
- Device registration by an Admin or a shop Supervisor in a password session, with a device cookie; devices listed and revocable by Admin.
|
||||||
|
- Signatures table and the `sign` helper for the sign-off actions of later phases.
|
||||||
|
- Audit rows for every identity event through the hash-chained audit log.
|
||||||
|
- `GET /api/events`: server-sent events over PostgreSQL LISTEN/NOTIFY with presence.
|
||||||
|
- Account settings: AD details, PIN create or change, sessions and sign-out-others, own access log, register this device.
|
||||||
|
- Admin: read-only AD view of users and any account, devices, PIN clearing with a reason, the group map with missing-group flags, sign-in attempts, and "Refresh from AD now", which enumerates the groups' members and creates or refreshes the users.
|
||||||
|
- Frontend: real sign-in (password tab, PIN keypad tab on registered devices), lock screen, role switcher, Account settings, Admin shell, placeholders for the screens of later phases.
|
||||||
|
- CLI: `packetstation ad-groups --list` and `packetstation ad-refresh`.
|
||||||
|
- Migration 0002: users keyed on the AD objectGUID, user_roles, sessions, devices, user_pins, signin_attempts, signatures, departments and stations seeded with the 18 departments.
|
||||||
|
- CI: a Samba Active Directory domain controller container (`PSTEST.LOCAL`) with a generated CA, seeded groups and test users; the CI compose overlay and Gitea workflow run it; a Playwright sign-in scenario runs against the stack.
|
||||||
- Phase 0: new repo for the Packet Station rebuild.
|
- Phase 0: new repo for the Packet Station rebuild.
|
||||||
- CLAUDE.md with the safety rules, connection facts, layout, commands and related projects.
|
- CLAUDE.md with the safety rules, connection facts, layout, commands and related projects.
|
||||||
- README with the status, phase list, folder map and how to run.
|
- README with the status, phase list, folder map and how to run.
|
||||||
|
|||||||
@@ -6,15 +6,15 @@ This repo is the rebuild of Packet Station as a server application: Docker Compo
|
|||||||
|
|
||||||
## Status
|
## Status
|
||||||
|
|
||||||
**Rebuild in progress. Phase 0: skeleton, image, doctor.**
|
**Rebuild in progress. Phase 1 done: identity, sessions, audit, frontend shell.**
|
||||||
|
|
||||||
No user feature exists yet. The old build on `M:\Production\Packet Station` stays the live system until go-live. The new system starts empty; nothing is migrated from M:.
|
People can sign in; no packet feature exists yet. The old build on `M:\Production\Packet Station` stays the live system until go-live. The new system starts empty; nothing is migrated from M:.
|
||||||
|
|
||||||
| Area | Exists yet? |
|
| Area | Exists yet? |
|
||||||
|---|---|
|
|---|---|
|
||||||
| Repo, docs, CLAUDE.md | Yes (phase 0) |
|
| Repo, docs, CLAUDE.md | Yes (phase 0) |
|
||||||
| Image, compose, CI, `doctor`, migration runner, security headers, build version endpoint | Yes (phase 0, image and stack verified on docker-1) |
|
| Image, compose, CI, `doctor`, migration runner, security headers, build version endpoint | Yes (phase 0, image and stack verified on docker-1) |
|
||||||
| Sign-in, sessions, audit, frontend shell | No (phase 1) |
|
| Sign-in (AD password, PIN on registered devices), sessions, lock screen, Account settings, Admin shell, audit, SSE | Yes (phase 1, verified against the Samba DC in the CI stack on docker-1) |
|
||||||
| Packets, policy, Clerical screens | No (phase 2) |
|
| Packets, policy, Clerical screens | No (phase 2) |
|
||||||
| VISUAL feed and drawings | No (phase 3) |
|
| VISUAL feed and drawings | No (phase 3) |
|
||||||
| Warehouse, shop, Q.C., close and file, PDFs | No (phases 4 to 7) |
|
| Warehouse, shop, Q.C., close and file, PDFs | No (phases 4 to 7) |
|
||||||
@@ -76,7 +76,18 @@ docker compose -p packetstation-test --env-file /etc/packetstation/test/stack.en
|
|||||||
-f deploy/compose.yaml -f deploy/compose.proxy.yaml up -d
|
-f deploy/compose.yaml -f deploy/compose.proxy.yaml up -d
|
||||||
```
|
```
|
||||||
|
|
||||||
The `packetstation` command has `doctor`, `migrate`, `app` and `worker`.
|
The `packetstation` command has `doctor`, `migrate`, `app`, `worker`, `ad-groups --list` (the 50 AD group names the app expects) and `ad-refresh` (create or refresh the users from the groups' members).
|
||||||
|
|
||||||
|
CI stack with the Samba domain controller and the Playwright scenario, on a Docker host:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
deploy/ci/make-secrets.sh
|
||||||
|
docker compose -p packetstation-ci --env-file deploy/ci/ci.env -f deploy/compose.yaml -f deploy/compose.ci.yaml up -d --build --wait
|
||||||
|
docker compose -p packetstation-ci --env-file deploy/ci/ci.env -f deploy/compose.yaml -f deploy/compose.ci.yaml --profile e2e run --rm playwright
|
||||||
|
docker compose -p packetstation-ci --env-file deploy/ci/ci.env -f deploy/compose.yaml -f deploy/compose.ci.yaml down -v
|
||||||
|
```
|
||||||
|
|
||||||
|
Server tests that need PostgreSQL run when `TEST_PG_SUPERUSER_URL` is set; the ones that need the domain controller run when the `TEST_LDAP_*` variables and `TEST_DC_USERS_FILE` are set. See [deploy/samba/README.md](deploy/samba/README.md).
|
||||||
|
|
||||||
## Docs
|
## Docs
|
||||||
|
|
||||||
|
|||||||
+14
-13
@@ -1,7 +1,8 @@
|
|||||||
# CI stack settings. Committed on purpose: it holds no secret.
|
# CI stack settings. Committed on purpose: it holds no secret.
|
||||||
# Secrets come from ci/ci-secrets/, made fresh by ci/make-secrets.sh on every run.
|
# Secrets come from ci/ci-secrets/, made fresh by ci/make-secrets.sh on every run.
|
||||||
# Relative paths resolve against deploy/, the compose project directory.
|
# Relative paths resolve against deploy/, the compose project directory.
|
||||||
# CI never reaches VISUAL, M-Files, AD or the mail relay. Phase 1 adds the Samba DC and fixtures.
|
# CI never reaches VISUAL, M-Files, PESCO's AD or the mail relay. LDAP goes to the throwaway
|
||||||
|
# Samba DC in compose.ci.yaml.
|
||||||
|
|
||||||
# ---- Compose (read by docker compose; also passed to the containers, which ignore them) ----
|
# ---- Compose (read by docker compose; also passed to the containers, which ignore them) ----
|
||||||
# Compose project name. Keeps prod and test volumes apart.
|
# Compose project name. Keeps prod and test volumes apart.
|
||||||
@@ -25,7 +26,7 @@ SITE_ID=PESCO
|
|||||||
# Site time zone for schedules and display. Containers run in UTC.
|
# Site time zone for schedules and display. Containers run in UTC.
|
||||||
SITE_TZ=America/Denver
|
SITE_TZ=America/Denver
|
||||||
# Public URL, used in links and mail.
|
# Public URL, used in links and mail.
|
||||||
PUBLIC_URL=http://app:8000
|
PUBLIC_URL=http://ps-app:8000
|
||||||
# Only this container may set X-Forwarded-*. The app re-resolves it. Empty trusts nobody.
|
# Only this container may set X-Forwarded-*. The app re-resolves it. Empty trusts nobody.
|
||||||
TRUSTED_PROXY_HOST=
|
TRUSTED_PROXY_HOST=
|
||||||
# DEBUG, INFO, WARNING or ERROR. Logs go to stdout.
|
# DEBUG, INFO, WARNING or ERROR. Logs go to stdout.
|
||||||
@@ -59,24 +60,24 @@ ASSETS_DIR=/data/assets
|
|||||||
# Built frontend. Compose sets it too.
|
# Built frontend. Compose sets it too.
|
||||||
STATIC_DIR=/app/static
|
STATIC_DIR=/app/static
|
||||||
|
|
||||||
# ---- LDAP (PESCO Active Directory; CI gets the Samba DC in phase 1) ----
|
# ---- LDAP (the throwaway Samba DC from deploy/samba, domain PSTEST.LOCAL; never PESCO's AD) ----
|
||||||
# Both domain controllers, tried in order.
|
# The DC's alias on the backend network. LDAPS with the CA it generates on first start.
|
||||||
LDAP_URL=
|
LDAP_URL=ldaps://dc1.pstest.local:636
|
||||||
# Search base for users.
|
# Search base for users.
|
||||||
LDAP_BASE_DN=
|
LDAP_BASE_DN=DC=pstest,DC=local
|
||||||
# Service account for searches.
|
# Service account for searches. seed.sh sets its password from the ldap_bind_password secret.
|
||||||
LDAP_BIND_DN=
|
LDAP_BIND_DN=CN=svc-packetstation,OU=System_Accounts,OU=Admin,DC=pstest,DC=local
|
||||||
# Service account password, from the compose secret.
|
# Service account password, from the compose secret.
|
||||||
LDAP_PASSWORD_FILE=/run/secrets/ldap_bind_password
|
LDAP_PASSWORD_FILE=/run/secrets/ldap_bind_password
|
||||||
# User search filter. {0} is the escaped sign-in name.
|
# User search filter. {0} is the escaped sign-in name.
|
||||||
LDAP_USER_FILTER="(|(sAMAccountName={0})(userPrincipalName={0}))"
|
LDAP_USER_FILTER="(|(sAMAccountName={0})(userPrincipalName={0}))"
|
||||||
# OU that holds the 50 PS-* groups.
|
# OU that holds the PS-* groups (49 of the 50 plus one extra, on purpose).
|
||||||
LDAP_GROUP_BASE_DN=
|
LDAP_GROUP_BASE_DN=OU=PacketStation,OU=Groups,OU=PESCO_FARMINGTON,DC=pstest,DC=local
|
||||||
# CA chain used to verify the controllers.
|
# The DC's CA, from the ci-dc-export volume mounted at /etc/ssl/pstest.
|
||||||
LDAP_CA_BUNDLE=/etc/ssl/pesco/ca.pem
|
LDAP_CA_BUNDLE=/etc/ssl/pstest/ca.pem
|
||||||
# false with ldaps://. true only with ldap:// on 389.
|
# false with ldaps://. true only with ldap:// on 389.
|
||||||
LDAP_STARTTLS=false
|
LDAP_STARTTLS=false
|
||||||
# Never true outside local development.
|
# Never true outside local development. The DC refuses plain LDAP simple binds anyway.
|
||||||
LDAP_ALLOW_INSECURE=false
|
LDAP_ALLOW_INSECURE=false
|
||||||
|
|
||||||
# ---- Mail (relay app-03, no auth) ----
|
# ---- Mail (relay app-03, no auth) ----
|
||||||
|
|||||||
@@ -2,7 +2,8 @@
|
|||||||
# Make throwaway secrets for a CI or local end-to-end run of compose.ci.yaml.
|
# Make throwaway secrets for a CI or local end-to-end run of compose.ci.yaml.
|
||||||
# Every value is random and new on each run. Nothing here is ever committed:
|
# Every value is random and new on each run. Nothing here is ever committed:
|
||||||
# deploy/ci/ci-secrets/ and deploy/ci/ci-backups/ are gitignored and dockerignored.
|
# deploy/ci/ci-secrets/ and deploy/ci/ci-backups/ are gitignored and dockerignored.
|
||||||
# Also makes an empty CA bundle placeholder (phase 1 swaps in the Samba DC's CA)
|
# Also makes an empty CA bundle placeholder for the base stack's /etc/ssl/pesco mount
|
||||||
|
# (LDAP in CI uses the Samba DC's own CA from the ci-dc-export volume instead)
|
||||||
# and an empty backup folder for the worker's read-only mount.
|
# and an empty backup folder for the worker's read-only mount.
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
@@ -26,6 +27,9 @@ do
|
|||||||
rand > "$out/$name"
|
rand > "$out/$name"
|
||||||
done
|
done
|
||||||
|
|
||||||
|
# Samba DC Administrator. Samba wants upper, lower, digits and a symbol.
|
||||||
|
printf 'Ci-%s-Adm!' "$(rand)" > "$out/samba_admin_password"
|
||||||
|
|
||||||
: > "$out/ca.pem"
|
: > "$out/ca.pem"
|
||||||
|
|
||||||
# CI only: the containers run as uid 10001 and uid 999 (postgres), not as the runner's
|
# CI only: the containers run as uid 10001 and uid 999 (postgres), not as the runner's
|
||||||
|
|||||||
+95
-27
@@ -1,13 +1,23 @@
|
|||||||
# Overlay for CI and local end-to-end runs. Builds the image from this checkout
|
# Overlay for CI and local end-to-end runs. Builds the image from this checkout
|
||||||
# instead of pulling it, and reads throwaway secrets made by ci/make-secrets.sh.
|
# instead of pulling it, and reads throwaway secrets made by ci/make-secrets.sh.
|
||||||
|
# Adds the throwaway Samba AD DC (deploy/samba/) and the Playwright runner (profile e2e).
|
||||||
#
|
#
|
||||||
# deploy/ci/make-secrets.sh
|
# deploy/ci/make-secrets.sh
|
||||||
# docker compose -p packetstation-ci --env-file deploy/ci/ci.env \
|
# docker compose -p packetstation-ci --env-file deploy/ci/ci.env \
|
||||||
# -f deploy/compose.yaml -f deploy/compose.ci.yaml up -d --build --wait
|
# -f deploy/compose.yaml -f deploy/compose.ci.yaml up -d --build --wait --wait-timeout 300
|
||||||
# docker compose -p packetstation-ci -f deploy/compose.yaml -f deploy/compose.ci.yaml down -v
|
# docker compose -p packetstation-ci --env-file deploy/ci/ci.env \
|
||||||
|
# -f deploy/compose.yaml -f deploy/compose.ci.yaml --profile e2e run --rm playwright
|
||||||
|
# docker compose -p packetstation-ci --env-file deploy/ci/ci.env \
|
||||||
|
# -f deploy/compose.yaml -f deploy/compose.ci.yaml down -v
|
||||||
#
|
#
|
||||||
# Never combine this overlay with compose.proxy.yaml.
|
# Never combine this overlay with compose.proxy.yaml.
|
||||||
|
|
||||||
|
x-logging: &logging
|
||||||
|
driver: json-file
|
||||||
|
options:
|
||||||
|
max-size: "10m"
|
||||||
|
max-file: "5"
|
||||||
|
|
||||||
x-build: &build
|
x-build: &build
|
||||||
context: ..
|
context: ..
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
@@ -19,40 +29,98 @@ services:
|
|||||||
build: *build
|
build: *build
|
||||||
image: ${IMAGE:-packetstation:ci}
|
image: ${IMAGE:-packetstation:ci}
|
||||||
pull_policy: build
|
pull_policy: build
|
||||||
|
volumes:
|
||||||
|
- ci-dc-export:/etc/ssl/pstest:ro # the DC's CA, LDAP_CA_BUNDLE=/etc/ssl/pstest/ca.pem
|
||||||
|
|
||||||
app:
|
app:
|
||||||
build: *build
|
build: *build
|
||||||
image: ${IMAGE:-packetstation:ci}
|
image: ${IMAGE:-packetstation:ci}
|
||||||
pull_policy: build
|
pull_policy: build
|
||||||
|
volumes:
|
||||||
|
- ci-dc-export:/etc/ssl/pstest:ro
|
||||||
|
# Playwright reaches the app as ps-app, never as "app": "app" is a top-level domain on
|
||||||
|
# Chromium's HSTS preload list, so http://app:8000 is forced to TLS and fails.
|
||||||
|
networks:
|
||||||
|
backend:
|
||||||
|
aliases:
|
||||||
|
- ps-app
|
||||||
|
egress: {}
|
||||||
|
depends_on:
|
||||||
|
samba-dc:
|
||||||
|
condition: service_healthy
|
||||||
|
|
||||||
worker:
|
worker:
|
||||||
build: *build
|
build: *build
|
||||||
image: ${IMAGE:-packetstation:ci}
|
image: ${IMAGE:-packetstation:ci}
|
||||||
pull_policy: build
|
pull_policy: build
|
||||||
|
volumes:
|
||||||
|
- ci-dc-export:/etc/ssl/pstest:ro
|
||||||
|
|
||||||
# Phase 1: Samba AD DC (PSTEST.LOCAL) so LDAP sign-in runs over real TLS in CI.
|
# Throwaway Samba AD DC (PSTEST.LOCAL) so LDAP sign-in runs over real TLS in CI.
|
||||||
# Built from deploy/samba/. Its generated CA becomes LDAP_CA_BUNDLE.
|
# Built from deploy/samba/. Runs as root, as Samba needs. No published port.
|
||||||
# samba-dc:
|
# The app reaches it as ldaps://dc1.pstest.local:636 on the internal backend network.
|
||||||
# build:
|
# It writes ca.pem, users.json and seeded to ci-dc-export.
|
||||||
# context: ./samba
|
samba-dc:
|
||||||
# hostname: dc1
|
build:
|
||||||
# networks:
|
context: ./samba
|
||||||
# backend:
|
image: packetstation-samba-dc:ci
|
||||||
# aliases: [dc1.pstest.local]
|
pull_policy: build
|
||||||
# healthcheck:
|
hostname: dc1
|
||||||
# test: ["CMD", "/usr/local/bin/healthcheck.sh"]
|
networks:
|
||||||
# interval: 10s
|
backend:
|
||||||
# retries: 30
|
aliases:
|
||||||
|
- dc1.pstest.local
|
||||||
|
secrets:
|
||||||
|
- samba_admin_password
|
||||||
|
- ldap_bind_password
|
||||||
|
volumes:
|
||||||
|
- ci-dc-data:/var/lib/samba
|
||||||
|
- ci-dc-export:/export
|
||||||
|
# Provisioning sets NT ACLs on sysvol, which needs security.* xattrs and therefore
|
||||||
|
# CAP_SYS_ADMIN (verified on docker-1, Samba 4.17: without it the provision step fails).
|
||||||
|
cap_add:
|
||||||
|
- SYS_ADMIN
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "/usr/local/bin/healthcheck.sh"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 30
|
||||||
|
start_period: 120s
|
||||||
|
restart: "no"
|
||||||
|
logging: *logging
|
||||||
|
|
||||||
# Phase 1: Playwright runner. Joins backend and drives the app at http://app:8000.
|
# Playwright runner. Drives the app at http://ps-app:8000 over backend.
|
||||||
# playwright:
|
# Also on egress, because npm ci fetches @playwright/test from the public registry
|
||||||
# image: mcr.microsoft.com/playwright:<pinned version>
|
# and backend is internal. The image tag must match @playwright/test in tests/e2e/package.json.
|
||||||
# working_dir: /work/tests/e2e
|
playwright:
|
||||||
# volumes:
|
image: mcr.microsoft.com/playwright:v1.64.1-noble
|
||||||
# - ../tests/e2e:/work/tests/e2e
|
profiles: ["e2e"]
|
||||||
# networks:
|
working_dir: /work/tests/e2e
|
||||||
# backend: {}
|
environment:
|
||||||
# depends_on:
|
E2E_BASE_URL: http://ps-app:8000
|
||||||
# app:
|
E2E_DC_USERS_FILE: /export/users.json
|
||||||
# condition: service_healthy
|
CI: "true"
|
||||||
# profiles: ["e2e"]
|
volumes:
|
||||||
|
- ../tests/e2e:/work/tests/e2e
|
||||||
|
- /work/tests/e2e/node_modules # anonymous volume: node_modules stays out of the checkout
|
||||||
|
- ci-dc-export:/export:ro
|
||||||
|
networks:
|
||||||
|
backend: {}
|
||||||
|
egress: {}
|
||||||
|
depends_on:
|
||||||
|
app:
|
||||||
|
condition: service_healthy
|
||||||
|
init: true
|
||||||
|
shm_size: 1g
|
||||||
|
command: ["sh", "-c", "npm ci --no-audit --no-fund && npx playwright test"]
|
||||||
|
logging: *logging
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
ci-dc-data: {}
|
||||||
|
ci-dc-export: {}
|
||||||
|
|
||||||
|
secrets:
|
||||||
|
samba_admin_password:
|
||||||
|
file: ${SECRETS_DIR:?set SECRETS_DIR in the stack env file}/samba_admin_password
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# Throwaway Samba Active Directory domain controller for CI and local end-to-end runs.
|
||||||
|
# Domain PSTEST.LOCAL. Never used outside the CI stack. Never points at PESCO's AD.
|
||||||
|
# The integrating session may pin this base by digest:
|
||||||
|
# docker buildx imagetools inspect debian:bookworm-slim
|
||||||
|
FROM debian:bookworm-slim
|
||||||
|
|
||||||
|
ENV DEBIAN_FRONTEND=noninteractive
|
||||||
|
|
||||||
|
# samba brings samba-tool and its python3 bindings. winbind is started by the DC.
|
||||||
|
# ldb-tools gives ldbmodify for employeeID. openssl makes the CA and the server certificate.
|
||||||
|
RUN apt-get update \
|
||||||
|
&& apt-get install -y --no-install-recommends \
|
||||||
|
samba samba-ad-provision samba-dsdb-modules samba-vfs-modules winbind ldb-tools krb5-user \
|
||||||
|
openssl ca-certificates tini \
|
||||||
|
&& rm -rf /var/lib/apt/lists/* \
|
||||||
|
&& rm -f /etc/samba/smb.conf
|
||||||
|
|
||||||
|
COPY entrypoint.sh seed.sh healthcheck.sh /usr/local/bin/
|
||||||
|
COPY groups.txt /usr/local/share/pstest/groups.txt
|
||||||
|
RUN chmod 0755 /usr/local/bin/entrypoint.sh /usr/local/bin/seed.sh /usr/local/bin/healthcheck.sh
|
||||||
|
|
||||||
|
VOLUME ["/var/lib/samba", "/export"]
|
||||||
|
EXPOSE 389 636
|
||||||
|
|
||||||
|
HEALTHCHECK --interval=10s --timeout=10s --start-period=120s --retries=30 \
|
||||||
|
CMD ["/usr/local/bin/healthcheck.sh"]
|
||||||
|
|
||||||
|
ENTRYPOINT ["/usr/bin/tini", "--", "/usr/local/bin/entrypoint.sh"]
|
||||||
+142
-11
@@ -1,15 +1,146 @@
|
|||||||
# Samba AD DC for CI (phase 1)
|
# Samba AD DC for CI
|
||||||
|
|
||||||
Placeholder. Phase 1 builds a throwaway Samba Active Directory domain controller here
|
A throwaway Active Directory domain controller for CI and local end-to-end runs. It lets
|
||||||
so CI and local end-to-end runs exercise real LDAP over TLS.
|
sign-in run over real LDAPS against a real directory without touching PESCO's AD.
|
||||||
|
It is only ever started by `deploy/compose.ci.yaml`. Nothing here is used by the test or
|
||||||
|
production stacks.
|
||||||
|
|
||||||
Planned contents:
|
## What it is
|
||||||
|
|
||||||
- `Dockerfile` from `debian:bookworm-slim` with samba, provisioned as `PSTEST.LOCAL`.
|
- Domain `PSTEST.LOCAL`, NetBIOS `PSTEST`, base `DC=pstest,DC=local`, host `dc1.pstest.local`.
|
||||||
- Its generated CA exported to `deploy/ci/ci-secrets/ca.pem`, which becomes `LDAP_CA_BUNDLE`.
|
- Debian bookworm with the distribution's Samba. Built from `Dockerfile` in this folder.
|
||||||
- `seed.sh`: the OU tree, the 50 PS-* groups from `packetstation ad-groups --list` (one left
|
- No published port. The app reaches it on the internal `backend` network as
|
||||||
out and one extra, to test the reconcile report), and test users per role. Also multi-role,
|
`ldaps://dc1.pstest.local:636`. Port 389 also answers, for STARTTLS tests.
|
||||||
nested, disabled, no-employeeID, duplicate-employeeID and no-role users.
|
- Simple binds work only over TLS (`ldap server require strong auth = allow_sasl_over_tls`).
|
||||||
|
A plain LDAP simple bind is refused, as on PESCO's DCs.
|
||||||
|
|
||||||
Open question 15: whether the Gitea runner can run this container (overlayfs xattrs,
|
## Files
|
||||||
possibly `SYS_ADMIN`). If not, CI uses a runner with the Docker socket on docker-1.
|
|
||||||
|
| File | Job |
|
||||||
|
|---|---|
|
||||||
|
| `Dockerfile` | Debian bookworm-slim, samba, ldb-tools, openssl, tini. |
|
||||||
|
| `entrypoint.sh` | Provisions on first start, makes the TLS certificates, seeds once, refreshes `/export`, runs samba in the foreground. |
|
||||||
|
| `seed.sh` | OU tree, service account, groups, test users, `users.json`. |
|
||||||
|
| `healthcheck.sh` | Healthy once seeded, exported, and LDAPS verifies against the exported CA. |
|
||||||
|
| `groups.txt` | The 50 group names, a copy of `packetstation ad-groups --list`. A server test keeps them equal. |
|
||||||
|
|
||||||
|
## First start
|
||||||
|
|
||||||
|
1. `samba-tool domain provision` with `--use-rfc2307 --dns-backend=NONE`.
|
||||||
|
The Administrator password comes from the compose secret `samba_admin_password`.
|
||||||
|
Setting the sysvol NT ACLs needs `security.*` xattrs, so the service runs with
|
||||||
|
`cap_add: [SYS_ADMIN]` (verified on docker-1 with Samba 4.17; without it the provision
|
||||||
|
step fails with access denied).
|
||||||
|
2. openssl makes a CA (`PSTEST CI CA`) and a server certificate for `dc1.pstest.local` and
|
||||||
|
`dc1`, valid 10 years, under `/var/lib/samba/private/tls/`. smb.conf points at them.
|
||||||
|
3. The password policy is relaxed: no complexity, no age, no history.
|
||||||
|
4. `seed.sh` runs once against the local `sam.ldb`, before samba starts.
|
||||||
|
5. smb.conf is kept on the data volume (`/var/lib/samba/etc/smb.conf`), so a recreated
|
||||||
|
container starts from the same domain.
|
||||||
|
|
||||||
|
Provisioning and seeding take about one to two minutes. The healthcheck allows 120 seconds of
|
||||||
|
start period and 30 retries after that.
|
||||||
|
|
||||||
|
Later starts skip provisioning and seeding but always refresh the export.
|
||||||
|
|
||||||
|
## What seed.sh creates
|
||||||
|
|
||||||
|
- `OU=PESCO_FARMINGTON` with `OU=Groups`, `OU=Groups` -> `OU=PacketStation`, and `OU=Users`.
|
||||||
|
`OU=Admin` -> `OU=System_Accounts`.
|
||||||
|
- `CN=svc-packetstation,OU=System_Accounts,OU=Admin,DC=pstest,DC=local`. Its password is the
|
||||||
|
`ldap_bind_password` compose secret, the same one the app reads. It never expires.
|
||||||
|
- In `OU=PacketStation`: the 50 groups from `groups.txt` except `PS-14-Electrical-Lead`
|
||||||
|
(missing on purpose), plus `PS-Extra-Legacy` (extra on purpose). Global security groups.
|
||||||
|
- In `OU=Groups`: `Shop-Welders-Nested`, a member of `PS-10-WeldAssembly-Worker`.
|
||||||
|
- In `OU=Users`: the 17 test users from the phase 1 contract. CN is the account name.
|
||||||
|
employeeID and displayName are set with `ldbmodify`. `nested.ned` is only in the nested
|
||||||
|
group. `disabled.dan` is disabled. `noemp.nora` has no employeeID. `dup.dave` and
|
||||||
|
`dup.dina` share 9001. `norole.nick` is in no group.
|
||||||
|
|
||||||
|
Every user gets a new random password on each seed. Nothing secret is committed.
|
||||||
|
|
||||||
|
## The export volume
|
||||||
|
|
||||||
|
The DC writes to the `ci-dc-export` volume, mounted at `/export`:
|
||||||
|
|
||||||
|
- `ca.pem`: the CI CA. migrate, app and worker mount the volume at `/etc/ssl/pstest`, and
|
||||||
|
`ci.env` sets `LDAP_CA_BUNDLE=/etc/ssl/pstest/ca.pem`.
|
||||||
|
- `users.json`: the test accounts, mode 0444.
|
||||||
|
`{"domain": "pstest.local", "users": {"<sam>": {"password", "emp_no", "display_name"}}}`.
|
||||||
|
`emp_no` is `null` for `noemp.nora`.
|
||||||
|
- `seeded`: the time of the seed. The healthcheck waits for it.
|
||||||
|
|
||||||
|
The Playwright service mounts the same volume read-only and reads `E2E_DC_USERS_FILE`.
|
||||||
|
|
||||||
|
## Running the CI stack on docker-1
|
||||||
|
|
||||||
|
From the repository root:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bash deploy/ci/make-secrets.sh
|
||||||
|
CI="docker compose -p packetstation-ci --env-file deploy/ci/ci.env -f deploy/compose.yaml -f deploy/compose.ci.yaml"
|
||||||
|
$CI up -d --build --wait --wait-timeout 300
|
||||||
|
$CI --profile e2e run --rm playwright # report in tests/e2e/playwright-report
|
||||||
|
$CI logs samba-dc # provisioning and seeding log, no secrets
|
||||||
|
$CI --profile e2e down -v
|
||||||
|
```
|
||||||
|
|
||||||
|
To run the server's DC-backed tests from docker-1 against this DC, copy the export out:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mkdir -p tests/fixtures/local/dc
|
||||||
|
docker run --rm -v packetstation-ci_ci-dc-export:/export:ro -v "$PWD/tests/fixtures/local/dc:/out" \
|
||||||
|
debian:bookworm-slim cp /export/ca.pem /export/users.json /out/
|
||||||
|
```
|
||||||
|
|
||||||
|
`tests/fixtures/local/` is ignored by git. The DC publishes no port, so those tests must run in
|
||||||
|
a container on the stack's `backend` network (for example `$CI run --rm --entrypoint pytest app`
|
||||||
|
with the tests mounted), with `TEST_LDAP_URL=ldaps://dc1.pstest.local:636`,
|
||||||
|
`TEST_DC_USERS_FILE` and the other `TEST_LDAP_*` values set.
|
||||||
|
|
||||||
|
## What CI does today
|
||||||
|
|
||||||
|
- The `e2e` job in `.gitea/workflows/ci.yml` builds this DC with the stack, runs the
|
||||||
|
Playwright scenarios in `tests/e2e/`, uploads the report and tears down with `down -v`.
|
||||||
|
- The `server` job does not start the DC. Its DC-backed tests skip because `TEST_LDAP_URL`
|
||||||
|
is unset. Follow-up: run them against the DC, either as a job service or inside the e2e stack.
|
||||||
|
|
||||||
|
## Running the server suite against the DC by hand
|
||||||
|
|
||||||
|
On docker-1, with the CI stack up, run the suite from a container on the stack's `backend`
|
||||||
|
network (it is internal, so bake pytest into a derived image first):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
printf "FROM packetstation:ci
|
||||||
|
USER root
|
||||||
|
RUN pip install -q pytest==9.1.1 anyio==4.15.1
|
||||||
|
" | docker build -q -t packetstation:ci-test -
|
||||||
|
docker run --rm --user root --network packetstation-ci_backend -v "$PWD/tests:/work/tests:ro" -v "$PWD/pyproject.toml:/work/pyproject.toml:ro" -v "$PWD/server:/work/server:ro" -v "$PWD/deploy/samba/groups.txt:/work/deploy/samba/groups.txt:ro" -v packetstation-ci_ci-dc-export:/export:ro -v "$PWD/deploy/ci/ci-secrets:/secrets:ro" -w /work -e STACK=ci -e TEST_LDAP_URL=ldaps://dc1.pstest.local:636 -e TEST_LDAP_BASE_DN=DC=pstest,DC=local -e TEST_LDAP_BIND_DN=CN=svc-packetstation,OU=System_Accounts,OU=Admin,DC=pstest,DC=local -e TEST_LDAP_PASSWORD_FILE=/secrets/ldap_bind_password -e TEST_LDAP_GROUP_BASE_DN=OU=PacketStation,OU=Groups,OU=PESCO_FARMINGTON,DC=pstest,DC=local -e TEST_LDAP_CA_BUNDLE=/export/ca.pem -e TEST_DC_USERS_FILE=/export/users.json -e TEST_PG_SUPERUSER_URL=postgresql://postgres:PW@some-other-postgres:5432/postgres --entrypoint python packetstation:ci-test -m pytest -q
|
||||||
|
```
|
||||||
|
|
||||||
|
Point `TEST_PG_SUPERUSER_URL` at a throwaway PostgreSQL, never at the stack's own. The
|
||||||
|
`pg_settings` fixture resets the `ps_app` and `ps_migrate` passwords on the server it is given,
|
||||||
|
which breaks the running app and worker (seen on docker-1 on 2026-10-16; `down -v` and `up`
|
||||||
|
repair it). Omit the variable to run only the DC tests that need no database.
|
||||||
|
|
||||||
|
## Open question 15
|
||||||
|
|
||||||
|
Whether the Gitea runner can run this container. Status: verified on docker-1 (Docker 29,
|
||||||
|
Ubuntu 24.04) on 2026-10-16; not yet tried on the Gitea runner.
|
||||||
|
|
||||||
|
What it needs:
|
||||||
|
|
||||||
|
- A Docker daemon that can run a root container with `cap_add: [SYS_ADMIN]`. Provisioning
|
||||||
|
sets NT ACLs on sysvol, which needs `security.*` xattrs; without the capability Samba 4.17
|
||||||
|
fails with access denied (tried on docker-1). The volume's filesystem must support xattrs
|
||||||
|
and POSIX ACLs (ext4 and xfs under `/var/lib/docker/volumes` do). If provisioning fails,
|
||||||
|
the provision log tail is printed in `$CI logs samba-dc`.
|
||||||
|
- Debian bookworm's `samba-ad-provision` package, which the Dockerfile installs (the schema
|
||||||
|
files live there, not in `samba`).
|
||||||
|
- Bind mounts that resolve. The base stack bind-mounts `deploy/ci/ci-secrets/` (secrets),
|
||||||
|
`deploy/postgres/initdb` and `tests/e2e`. If act_runner runs the job inside a container that
|
||||||
|
talks to the host daemon through its socket, those paths must exist on the host at the same
|
||||||
|
place. If they do not, use a runner on docker-1 in host mode, or one whose workdir is
|
||||||
|
mounted at the same path on the host.
|
||||||
|
- Outbound HTTPS from the playwright container to the npm registry and from the builder to
|
||||||
|
the Debian mirrors.
|
||||||
|
|||||||
@@ -0,0 +1,137 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Samba AD DC for CI. Provisions PSTEST.LOCAL on first start, makes the TLS certificates,
|
||||||
|
# seeds the OU tree, groups and users once, refreshes /export, then runs samba in the foreground.
|
||||||
|
# Never prints a password. Run as root (Samba needs it). tini is PID 1.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
REALM=PSTEST.LOCAL
|
||||||
|
DOMAIN=PSTEST
|
||||||
|
HOST=dc1
|
||||||
|
FQDN=dc1.pstest.local
|
||||||
|
STATE=/var/lib/samba
|
||||||
|
PRIVATE=$STATE/private
|
||||||
|
TLS=$PRIVATE/tls
|
||||||
|
CONF_DIR=$STATE/etc # smb.conf lives on the volume so it survives a recreated container
|
||||||
|
CONF=$CONF_DIR/smb.conf
|
||||||
|
EXPORT=/export
|
||||||
|
ADMIN_SECRET=/run/secrets/samba_admin_password
|
||||||
|
|
||||||
|
log() { echo "samba-dc: $*"; }
|
||||||
|
|
||||||
|
read_secret() {
|
||||||
|
# One line, CR stripped. Never echoed.
|
||||||
|
local f=$1
|
||||||
|
if [ ! -s "$f" ]; then
|
||||||
|
log "missing or empty secret file $f" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
head -n 1 "$f" | tr -d '\r\n'
|
||||||
|
}
|
||||||
|
|
||||||
|
make_tls() {
|
||||||
|
log "making the CI CA and the server certificate"
|
||||||
|
mkdir -p "$TLS"
|
||||||
|
local tmp
|
||||||
|
tmp=$(mktemp -d)
|
||||||
|
openssl req -x509 -new -nodes -newkey rsa:3072 -sha256 -days 3650 \
|
||||||
|
-keyout "$TLS/ca.key" -out "$TLS/ca.pem" -subj "/CN=PSTEST CI CA" \
|
||||||
|
-addext "basicConstraints=critical,CA:TRUE" \
|
||||||
|
-addext "keyUsage=critical,keyCertSign,cRLSign" \
|
||||||
|
-addext "subjectKeyIdentifier=hash" 2>/dev/null
|
||||||
|
openssl req -new -nodes -newkey rsa:3072 -sha256 \
|
||||||
|
-keyout "$TLS/key.pem" -out "$tmp/server.csr" -subj "/CN=$FQDN" 2>/dev/null
|
||||||
|
cat > "$tmp/server.ext" <<EXT
|
||||||
|
basicConstraints=critical,CA:FALSE
|
||||||
|
keyUsage=critical,digitalSignature,keyEncipherment
|
||||||
|
extendedKeyUsage=serverAuth
|
||||||
|
subjectAltName=DNS:$FQDN,DNS:$HOST
|
||||||
|
subjectKeyIdentifier=hash
|
||||||
|
authorityKeyIdentifier=keyid,issuer
|
||||||
|
EXT
|
||||||
|
openssl x509 -req -sha256 -days 3650 -in "$tmp/server.csr" \
|
||||||
|
-CA "$TLS/ca.pem" -CAkey "$TLS/ca.key" -CAcreateserial -CAserial "$tmp/ca.srl" \
|
||||||
|
-extfile "$tmp/server.ext" -out "$TLS/cert.pem" 2>/dev/null
|
||||||
|
rm -rf "$tmp"
|
||||||
|
# Samba refuses a private key that others can read.
|
||||||
|
chmod 0600 "$TLS/key.pem" "$TLS/ca.key"
|
||||||
|
chmod 0644 "$TLS/ca.pem" "$TLS/cert.pem"
|
||||||
|
openssl verify -CAfile "$TLS/ca.pem" "$TLS/cert.pem" >/dev/null
|
||||||
|
}
|
||||||
|
|
||||||
|
set_global() {
|
||||||
|
# Add lines right after [global] in smb.conf.
|
||||||
|
local line
|
||||||
|
for line in "$@"; do
|
||||||
|
sed -i "/^\[global\]/a $line" "$CONF"
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
provision() {
|
||||||
|
log "provisioning $REALM (first start)"
|
||||||
|
local adminpass
|
||||||
|
adminpass=$(read_secret "$ADMIN_SECRET")
|
||||||
|
rm -f /etc/samba/smb.conf
|
||||||
|
mkdir -p "$CONF_DIR"
|
||||||
|
# The sysvol ACL step needs security.* xattrs, so the container runs with CAP_SYS_ADMIN
|
||||||
|
# (compose.ci.yaml). Samba 4.17 has no --use-xattrs option. --dns-backend=NONE: the stack
|
||||||
|
# resolves names itself.
|
||||||
|
samba-tool domain provision \
|
||||||
|
--use-rfc2307 \
|
||||||
|
--realm="$REALM" \
|
||||||
|
--domain="$DOMAIN" \
|
||||||
|
--host-name="$HOST" \
|
||||||
|
--server-role=dc \
|
||||||
|
--dns-backend=NONE \
|
||||||
|
--adminpass="$adminpass" >/var/log/samba-provision.log 2>&1 || {
|
||||||
|
log "provision failed; last lines of the log follow" >&2
|
||||||
|
tail -n 40 /var/log/samba-provision.log >&2
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
unset adminpass
|
||||||
|
mv /etc/samba/smb.conf "$CONF"
|
||||||
|
ln -sf "$CONF" /etc/samba/smb.conf
|
||||||
|
|
||||||
|
make_tls
|
||||||
|
# Simple binds only over TLS (LDAPS or STARTTLS), like PESCO's DCs. Plain LDAP simple binds fail.
|
||||||
|
set_global \
|
||||||
|
"ldap server require strong auth = allow_sasl_over_tls" \
|
||||||
|
"tls keyfile = $TLS/key.pem" \
|
||||||
|
"tls certfile = $TLS/cert.pem" \
|
||||||
|
"tls cafile = $TLS/ca.pem" \
|
||||||
|
"tls enabled = yes"
|
||||||
|
|
||||||
|
# Relaxed policy: CI passwords are random per run and never change.
|
||||||
|
samba-tool domain passwordsettings set \
|
||||||
|
--complexity=off --min-pwd-age=0 --max-pwd-age=0 --history-length=0 >/dev/null
|
||||||
|
cp "$PRIVATE/krb5.conf" /etc/krb5.conf 2>/dev/null || true
|
||||||
|
log "provisioned"
|
||||||
|
}
|
||||||
|
|
||||||
|
if [ ! -f "$PRIVATE/sam.ldb" ]; then
|
||||||
|
provision
|
||||||
|
else
|
||||||
|
log "already provisioned; skipping"
|
||||||
|
ln -sf "$CONF" /etc/samba/smb.conf
|
||||||
|
cp "$PRIVATE/krb5.conf" /etc/krb5.conf 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Seed once, offline, before samba starts. samba-tool writes sam.ldb directly.
|
||||||
|
if [ ! -f "$PRIVATE/.seeded" ]; then
|
||||||
|
/usr/local/bin/seed.sh
|
||||||
|
date -u +%Y-%m-%dT%H:%M:%SZ > "$PRIVATE/.seeded"
|
||||||
|
else
|
||||||
|
log "already seeded; skipping"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Refresh the export on every start: the CA, the users file and the seeded marker.
|
||||||
|
mkdir -p "$EXPORT"
|
||||||
|
chmod 0755 "$EXPORT"
|
||||||
|
rm -f "$EXPORT/seeded"
|
||||||
|
install -m 0444 "$TLS/ca.pem" "$EXPORT/ca.pem"
|
||||||
|
install -m 0444 "$PRIVATE/users.json" "$EXPORT/users.json"
|
||||||
|
cp "$PRIVATE/.seeded" "$EXPORT/seeded"
|
||||||
|
chmod 0444 "$EXPORT/seeded"
|
||||||
|
log "exported ca.pem and users.json to $EXPORT"
|
||||||
|
|
||||||
|
log "starting samba"
|
||||||
|
exec samba -i -F --no-process-group
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
PS-Admins
|
||||||
|
PS-Clerical
|
||||||
|
PS-Clerical-Supervisor
|
||||||
|
PS-Warehouse
|
||||||
|
PS-Warehouse-Supervisor
|
||||||
|
PS-QC
|
||||||
|
PS-QC-Supervisor
|
||||||
|
PS-ProjectMgmt
|
||||||
|
PS-01-Layout-Worker
|
||||||
|
PS-01-Layout-Lead
|
||||||
|
PS-01-Layout-Supervisor
|
||||||
|
PS-02-SouthLayout-Worker
|
||||||
|
PS-02-SouthLayout-Lead
|
||||||
|
PS-02-SouthLayout-Supervisor
|
||||||
|
PS-03-WeldParts-Worker
|
||||||
|
PS-03-WeldParts-Lead
|
||||||
|
PS-03-WeldParts-Supervisor
|
||||||
|
PS-04-SouthWeld-Worker
|
||||||
|
PS-04-SouthWeld-Lead
|
||||||
|
PS-04-SouthWeld-Supervisor
|
||||||
|
PS-05-SouthWeldSS-Worker
|
||||||
|
PS-05-SouthWeldSS-Lead
|
||||||
|
PS-05-SouthWeldSS-Supervisor
|
||||||
|
PS-06-CodeBldg2-Worker
|
||||||
|
PS-06-CodeBldg2-Lead
|
||||||
|
PS-06-CodeBldg2-Supervisor
|
||||||
|
PS-07-CodeBldg3-Worker
|
||||||
|
PS-07-CodeBldg3-Lead
|
||||||
|
PS-07-CodeBldg3-Supervisor
|
||||||
|
PS-08-Subassembly-Worker
|
||||||
|
PS-08-Subassembly-Lead
|
||||||
|
PS-08-Subassembly-Supervisor
|
||||||
|
PS-09-Hydro-Worker
|
||||||
|
PS-09-Hydro-Lead
|
||||||
|
PS-09-Hydro-Supervisor
|
||||||
|
PS-10-WeldAssembly-Worker
|
||||||
|
PS-10-WeldAssembly-Lead
|
||||||
|
PS-10-WeldAssembly-Supervisor
|
||||||
|
PS-11-FinalAssyNorth-Worker
|
||||||
|
PS-11-FinalAssyNorth-Lead
|
||||||
|
PS-11-FinalAssyNorth-Supervisor
|
||||||
|
PS-12-FinalAssySouth-Worker
|
||||||
|
PS-12-FinalAssySouth-Lead
|
||||||
|
PS-12-FinalAssySouth-Supervisor
|
||||||
|
PS-13-PaintSandblast-Worker
|
||||||
|
PS-13-PaintSandblast-Lead
|
||||||
|
PS-13-PaintSandblast-Supervisor
|
||||||
|
PS-14-Electrical-Worker
|
||||||
|
PS-14-Electrical-Lead
|
||||||
|
PS-14-Electrical-Supervisor
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Healthy only when the domain is seeded, the export is written and LDAPS answers
|
||||||
|
# with a certificate that verifies against the exported CA for dc1.pstest.local.
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
test -f /export/seeded
|
||||||
|
test -s /export/ca.pem
|
||||||
|
test -s /export/users.json
|
||||||
|
|
||||||
|
# TLS on 636: the handshake must verify the chain and the host name.
|
||||||
|
openssl s_client -connect 127.0.0.1:636 -servername dc1.pstest.local \
|
||||||
|
-CAfile /export/ca.pem -verify_hostname dc1.pstest.local -verify_return_error \
|
||||||
|
</dev/null >/dev/null 2>&1
|
||||||
|
|
||||||
|
# The directory answers: the service account exists in the seeded tree.
|
||||||
|
ldbsearch -H /var/lib/samba/private/sam.ldb \
|
||||||
|
-b "OU=System_Accounts,OU=Admin,DC=pstest,DC=local" \
|
||||||
|
"(sAMAccountName=svc-packetstation)" dn 2>/dev/null | grep -q '^dn: '
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Seed the CI domain: the OU tree, the service account, the PS-* groups and the test users.
|
||||||
|
# Runs once from entrypoint.sh, before samba starts, against the local sam.ldb.
|
||||||
|
# Safe to rerun: "already exists" is ignored and every user gets a new random password.
|
||||||
|
# Never prints a password. Writes $PRIVATE/users.json (0600); the entrypoint exports it.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
BASE="DC=pstest,DC=local"
|
||||||
|
PRIVATE=/var/lib/samba/private
|
||||||
|
SAM=$PRIVATE/sam.ldb
|
||||||
|
GROUPS_FILE=/usr/local/share/pstest/groups.txt
|
||||||
|
BIND_SECRET=/run/secrets/ldap_bind_password
|
||||||
|
PS_OU="OU=PacketStation,OU=Groups,OU=PESCO_FARMINGTON"
|
||||||
|
USERS_OU="OU=Users,OU=PESCO_FARMINGTON"
|
||||||
|
MISSING_GROUP="PS-14-Electrical-Lead" # left out on purpose: the reconcile report must flag it
|
||||||
|
EXTRA_GROUP="PS-Extra-Legacy" # added on purpose: the reconcile report must list it
|
||||||
|
NESTED_GROUP="Shop-Welders-Nested"
|
||||||
|
|
||||||
|
log() { echo "samba-dc seed: $*"; }
|
||||||
|
|
||||||
|
# Run a command. Ignore "already exists". On any other failure show its output and stop.
|
||||||
|
# Callers never pass a password in a way that ends up in this output.
|
||||||
|
try() {
|
||||||
|
local out
|
||||||
|
if out=$("$@" 2>&1); then
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
if printf '%s' "$out" | grep -qiE 'already exists|ENTRY_ALREADY_EXISTS|already a member'; then
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
log "failed: $1 $2 $3" >&2
|
||||||
|
printf '%s\n' "$out" | sed 's/^/ /' >&2
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
add_ou() {
|
||||||
|
local dn="$1,$BASE"
|
||||||
|
local ldif
|
||||||
|
ldif=$(mktemp)
|
||||||
|
printf 'dn: %s\nobjectClass: top\nobjectClass: organizationalUnit\n' "$dn" > "$ldif"
|
||||||
|
try ldbadd -H "$SAM" "$ldif"
|
||||||
|
rm -f "$ldif"
|
||||||
|
}
|
||||||
|
|
||||||
|
random_password() {
|
||||||
|
# 24 random base64 characters plus a fixed tail with upper, lower, digit and symbol.
|
||||||
|
printf '%s-Pa9' "$(openssl rand -base64 18 | tr -d '\n')"
|
||||||
|
}
|
||||||
|
|
||||||
|
set_password() {
|
||||||
|
# $1 sam, $2 password. Not logged. Visible only inside this container's process list.
|
||||||
|
try samba-tool user setpassword "$1" --newpassword="$2"
|
||||||
|
}
|
||||||
|
|
||||||
|
set_attrs() {
|
||||||
|
# $1 dn, $2 display name, $3 employeeID or empty.
|
||||||
|
local ldif
|
||||||
|
ldif=$(mktemp)
|
||||||
|
{
|
||||||
|
printf 'dn: %s\nchangetype: modify\n' "$1"
|
||||||
|
printf 'replace: displayName\ndisplayName: %s\n-\n' "$2"
|
||||||
|
if [ -n "$3" ]; then
|
||||||
|
printf 'replace: employeeID\nemployeeID: %s\n-\n' "$3"
|
||||||
|
fi
|
||||||
|
} > "$ldif"
|
||||||
|
try ldbmodify -H "$SAM" "$ldif"
|
||||||
|
rm -f "$ldif"
|
||||||
|
}
|
||||||
|
|
||||||
|
# ---- OU tree, mirroring PESCO ----
|
||||||
|
log "OU tree"
|
||||||
|
add_ou "OU=PESCO_FARMINGTON"
|
||||||
|
add_ou "OU=Groups,OU=PESCO_FARMINGTON"
|
||||||
|
add_ou "$PS_OU"
|
||||||
|
add_ou "$USERS_OU"
|
||||||
|
add_ou "OU=Admin"
|
||||||
|
add_ou "OU=System_Accounts,OU=Admin"
|
||||||
|
|
||||||
|
# ---- Service account (password = the app's ldap_bind_password secret) ----
|
||||||
|
log "service account svc-packetstation"
|
||||||
|
if [ ! -s "$BIND_SECRET" ]; then
|
||||||
|
log "missing or empty secret file $BIND_SECRET" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
try samba-tool user create svc-packetstation --random-password --use-username-as-cn \
|
||||||
|
--userou="OU=System_Accounts,OU=Admin" --description="Packet Station service account (CI)"
|
||||||
|
set_password svc-packetstation "$(head -n 1 "$BIND_SECRET" | tr -d '\r\n')"
|
||||||
|
try samba-tool user setexpiry svc-packetstation --noexpiry
|
||||||
|
|
||||||
|
# ---- Groups ----
|
||||||
|
log "PacketStation groups"
|
||||||
|
count=0
|
||||||
|
while IFS= read -r name || [ -n "$name" ]; do
|
||||||
|
name=$(printf '%s' "$name" | tr -d '\r' | sed 's/[[:space:]]*$//')
|
||||||
|
[ -z "$name" ] && continue
|
||||||
|
[ "$name" = "$MISSING_GROUP" ] && continue
|
||||||
|
try samba-tool group add "$name" --groupou="$PS_OU" \
|
||||||
|
--group-scope=Global --group-type=Security --description="Packet Station: $name"
|
||||||
|
count=$((count + 1))
|
||||||
|
done < "$GROUPS_FILE"
|
||||||
|
try samba-tool group add "$EXTRA_GROUP" --groupou="$PS_OU" \
|
||||||
|
--group-scope=Global --group-type=Security --description="Packet Station: $EXTRA_GROUP"
|
||||||
|
try samba-tool group add "$NESTED_GROUP" --groupou="OU=Groups,OU=PESCO_FARMINGTON" \
|
||||||
|
--group-scope=Global --group-type=Security --description="Helper group for the nested membership test"
|
||||||
|
try samba-tool group addmembers PS-10-WeldAssembly-Worker "$NESTED_GROUP"
|
||||||
|
log "created $count mapped groups (without $MISSING_GROUP), plus $EXTRA_GROUP and $NESTED_GROUP"
|
||||||
|
|
||||||
|
# ---- Users: sam|given|surname|employeeID|groups (comma separated) ----
|
||||||
|
ROSTER='admin.ann|Ann|Admin|1001|PS-Admins
|
||||||
|
clerk.clara|Clara|Clerk|4001|PS-Clerical
|
||||||
|
clerk.leo|Leo|Lead|4002|PS-Clerical-Supervisor
|
||||||
|
wh.wade|Wade|Warehouse|6001|PS-Warehouse
|
||||||
|
qc.quinn|Quinn|QC|5001|PS-QC
|
||||||
|
pm.paula|Paula|PM|7001|PS-ProjectMgmt
|
||||||
|
weld.andy|Andy|Welder|3003|PS-03-WeldParts-Worker
|
||||||
|
lead.lou|Lou|Lead|3002|PS-03-WeldParts-Lead
|
||||||
|
sup.wes|Wes|Super|2003|PS-03-WeldParts-Supervisor
|
||||||
|
multi.mia|Mia|Multi|2006|PS-Clerical,PS-06-CodeBldg2-Supervisor
|
||||||
|
nested.ned|Ned|Nested|3010|Shop-Welders-Nested
|
||||||
|
both.bo|Bo|Both|3011|PS-03-WeldParts-Worker,PS-03-WeldParts-Supervisor
|
||||||
|
disabled.dan|Dan|Disabled|3004|PS-03-WeldParts-Worker
|
||||||
|
noemp.nora|Nora|NoEmp||PS-Warehouse
|
||||||
|
dup.dave|Dave|Dup|9001|PS-03-WeldParts-Worker
|
||||||
|
dup.dina|Dina|Dup|9001|PS-Warehouse
|
||||||
|
norole.nick|Nick|NoRole|8001|'
|
||||||
|
|
||||||
|
umask 077
|
||||||
|
rows=$(mktemp) # sam, password, emp, display; tab separated; 0600; removed below
|
||||||
|
log "users"
|
||||||
|
while IFS='|' read -r sam given surname emp groups; do
|
||||||
|
[ -z "$sam" ] && continue
|
||||||
|
display="$given $surname"
|
||||||
|
dn="CN=$sam,$USERS_OU,$BASE"
|
||||||
|
try samba-tool user create "$sam" --random-password --use-username-as-cn \
|
||||||
|
--userou="$USERS_OU" --given-name="$given" --surname="$surname" \
|
||||||
|
--mail-address="$sam@pstest.local"
|
||||||
|
pw=$(random_password)
|
||||||
|
set_password "$sam" "$pw"
|
||||||
|
set_attrs "$dn" "$display" "$emp"
|
||||||
|
if [ -n "$groups" ]; then
|
||||||
|
IFS=',' read -r -a list <<< "$groups"
|
||||||
|
for g in "${list[@]}"; do
|
||||||
|
try samba-tool group addmembers "$g" "$sam"
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
printf '%s\t%s\t%s\t%s\n' "$sam" "$pw" "$emp" "$display" >> "$rows"
|
||||||
|
unset pw
|
||||||
|
log " $sam"
|
||||||
|
done <<< "$ROSTER"
|
||||||
|
|
||||||
|
try samba-tool user disable disabled.dan
|
||||||
|
|
||||||
|
# ---- users.json, the format in the phase 1 contract ----
|
||||||
|
python3 - "$rows" "$PRIVATE/users.json" <<'PY'
|
||||||
|
import json, sys
|
||||||
|
users = {}
|
||||||
|
with open(sys.argv[1], encoding="utf-8") as f:
|
||||||
|
for line in f:
|
||||||
|
sam, password, emp, display = line.rstrip("\n").split("\t")
|
||||||
|
users[sam] = {"password": password, "emp_no": emp or None, "display_name": display}
|
||||||
|
with open(sys.argv[2], "w", encoding="utf-8") as f:
|
||||||
|
json.dump({"domain": "pstest.local", "users": users}, f, indent=2, sort_keys=True)
|
||||||
|
f.write("\n")
|
||||||
|
PY
|
||||||
|
rm -f "$rows"
|
||||||
|
chmod 0600 "$PRIVATE/users.json"
|
||||||
|
log "done: $(grep -c '"password"' "$PRIVATE/users.json") users written to users.json"
|
||||||
@@ -65,6 +65,8 @@ Key settings:
|
|||||||
- `LDAP_URL=ldaps://DC-02.PESCO.COM:636 ldaps://PDC-1.PESCO.COM:636`, `LDAP_BIND_DN=CN=svc-packetstation,OU=System_Accounts,OU=Admin,DC=PESCO,DC=com`, `LDAP_GROUP_BASE_DN=OU=PacketStation,OU=Groups,OU=PESCO_FARMINGTON,DC=PESCO,DC=com`, `LDAP_PASSWORD_FILE`, `LDAP_CA_BUNDLE`.
|
- `LDAP_URL=ldaps://DC-02.PESCO.COM:636 ldaps://PDC-1.PESCO.COM:636`, `LDAP_BIND_DN=CN=svc-packetstation,OU=System_Accounts,OU=Admin,DC=PESCO,DC=com`, `LDAP_GROUP_BASE_DN=OU=PacketStation,OU=Groups,OU=PESCO_FARMINGTON,DC=PESCO,DC=com`, `LDAP_PASSWORD_FILE`, `LDAP_CA_BUNDLE`.
|
||||||
- `SMTP_HOST=app-03.pesco.com`, `SMTP_PORT=25`, `SMTP_STARTTLS=true`, `[email protected]`, `SMTP_CA_BUNDLE`.
|
- `SMTP_HOST=app-03.pesco.com`, `SMTP_PORT=25`, `SMTP_STARTTLS=true`, `[email protected]`, `SMTP_CA_BUNDLE`.
|
||||||
- `APP_ALIAS` per stack.
|
- `APP_ALIAS` per stack.
|
||||||
|
- Identity timing and limits, all optional with these defaults: `SESSION_IDLE_MINUTES=15`, `SESSION_LOCK_MINUTES=3`, `SESSION_HIDDEN_LOCK_SECONDS=60`, `SESSION_PASSWORD_HOURS=12`, `SESSION_PIN_HOURS=10`, `ROLES_REFRESH_MINUTES=15`, `SIGNIN_ACCOUNT_LIMIT=5`, `SIGNIN_ACCOUNT_WINDOW_MINUTES=5`, `SIGNIN_ACCOUNT_COOLDOWN_MINUTES=10`, `SIGNIN_IP_LIMIT=30`, `SIGNIN_IP_WINDOW_MINUTES=5`, `PIN_MAX_FAILURES=5`, `STEPUP_MAX_FAILURES=3`, `DEVICE_COOKIE_DAYS=365`, `PIN_MIN_DIGITS=6`, `PIN_MAX_DIGITS=12`.
|
||||||
|
- The session cookie is marked `Secure` when the request arrived over https (as reported by NPM through `X-Forwarded-Proto`). Behind the proxy that is always the case.
|
||||||
|
|
||||||
## Deploy command
|
## Deploy command
|
||||||
|
|
||||||
@@ -148,6 +150,14 @@ The image built on docker-1 from this tree (python:3.12-slim-bookworm, ODBC Driv
|
|||||||
|
|
||||||
Inside containers the short name `VSQL\DEV` does not resolve. The env files use `vsql.pesco.com\DEV`.
|
Inside containers the short name `VSQL\DEV` does not resolve. The env files use `vsql.pesco.com\DEV`.
|
||||||
|
|
||||||
|
## CI stack and the Samba domain controller (phase 1)
|
||||||
|
|
||||||
|
`deploy/compose.ci.yaml` adds a throwaway Samba Active Directory domain controller (`samba-dc`, realm `PSTEST.LOCAL`, host `dc1.pstest.local` on the internal `backend` network) built from `deploy/samba/`. On first start it provisions the domain, generates a CA and a server certificate, seeds the OU tree, the service account, the groups (49 of the 50, plus one extra, to test the report) and 17 test users with random passwords, and exports `ca.pem` and `users.json` to the `ci-dc-export` volume. The app, migrate and worker mount that volume at `/etc/ssl/pstest` and `deploy/ci/ci.env` points `LDAP_CA_BUNDLE` at it, so CI exercises the real LDAPS path. The `playwright` service (profile `e2e`) drives the app at `http://ps-app:8000` with the exported users. [deploy/samba/README.md](../deploy/samba/README.md) has the details and the commands.
|
||||||
|
|
||||||
|
The DC runs with `cap_add: [SYS_ADMIN]`, which Samba needs to set the sysvol ACLs. The app carries the alias `ps-app` for Playwright because `app` is a top-level domain on Chromium's HSTS preload list, so `http://app:8000` is forced to TLS and fails. Running the server test suite against the stack's own PostgreSQL is not safe: the `pg_settings` fixture resets the role passwords (see deploy/samba/README.md).
|
||||||
|
|
||||||
|
The real PESCO domain controllers are never used by CI. The test and production stacks do not run the DC.
|
||||||
|
|
||||||
## Backup (planned, phase 9)
|
## Backup (planned, phase 9)
|
||||||
|
|
||||||
`pg_dump` of both stacks from a systemd timer on the host at 02:00 America/Denver, before the 03:00 PBS run. Seven dumps kept in `/var/backups/packetstation/<stack>/` with last-success and last-failure markers. The worker's backup-check job alerts if the newest dump is missing or older than 26 hours. Scripts and units go in `scripts/`.
|
`pg_dump` of both stacks from a systemd timer on the host at 02:00 America/Denver, before the 03:00 PBS run. Seven dumps kept in `/var/backups/packetstation/<stack>/` with last-success and last-failure markers. The worker's backup-check job alerts if the newest dump is missing or older than 26 hours. Scripts and units go in `scripts/`.
|
||||||
|
|||||||
+1
-1
@@ -232,7 +232,7 @@ Smaller questions from the design, with the default the build takes unless told
|
|||||||
12. Partspecs, title or folded-operation target changes on an in-shop packet: default no change order, as the old build.
|
12. Partspecs, title or folded-operation target changes on an in-shop packet: default no change order, as the old build.
|
||||||
13. Work-order-gone confirmation after 2 consecutive runs and the 10% suspect-batch guard: defaults as stated.
|
13. Work-order-gone confirmation after 2 consecutive runs and the 10% suspect-batch guard: defaults as stated.
|
||||||
14. Pause scope: default pauses the feed, the drawing job and auto-release together.
|
14. Pause scope: default pauses the feed, the drawing job and auto-release together.
|
||||||
15. Gitea runner: whether the Samba DC container can run there (overlayfs xattrs, possibly cap SYS_ADMIN). Checked in phase 1; if not, CI uses a runner with a Docker socket on docker-1.
|
15. Gitea runner: whether the Samba DC container can run there (overlayfs xattrs, possibly cap SYS_ADMIN). Checked in phase 1; if not, CI uses a runner with a Docker socket on docker-1. Phase 1 finding (2026-10-16): the container needs `cap_add: [SYS_ADMIN]` (Samba 4.17 sets sysvol NT ACLs through `security.*` xattrs) and runs that way on docker-1; the Gitea runner itself is still to be tried.
|
||||||
16. NPM: confirm `Block common exploits` does not interfere with uploads; checked when the test proxy host is made in phase 0.
|
16. NPM: confirm `Block common exploits` does not interfere with uploads; checked when the test proxy host is made in phase 0.
|
||||||
17. SET_DATABOOK_AT is writable by anyone in the old build, even when filed: default restrict to Clerical and Q.C.
|
17. SET_DATABOOK_AT is writable by anyone in the old build, even when filed: default restrict to Clerical and Q.C.
|
||||||
18. CO verifications cannot be withdrawn; ITP line signatures can be undone by the same inspector or an Admin before the block is signed.
|
18. CO verifications cannot be withdrawn; ITP line signatures can be undone by the same inspector or an Admin before the block is signed.
|
||||||
|
|||||||
+19
-5
@@ -1,6 +1,6 @@
|
|||||||
# Packet Station schema
|
# Packet Station schema
|
||||||
|
|
||||||
Status: planned, phases 1 to 3. This is a stub. The full DDL lands here as the migrations are written. See [PLAN.md](PLAN.md), "Schema".
|
Status: phase 1 built (identity and organisation seed). Phases 2 and 3 add the rest. The DDL is in `server/packetstation/migrations/`; this file explains it. See [PLAN.md](PLAN.md), "Schema".
|
||||||
|
|
||||||
## Conventions
|
## Conventions
|
||||||
|
|
||||||
@@ -10,13 +10,27 @@ Identity bigints, except users, keyed on the AD objectGUID. Postgres enums for w
|
|||||||
|
|
||||||
A superuser for bootstrap, the migrate role `ps_migrate` (owns the schema, runs migrations) and the app role `ps_app`. The plan's deployment section also names a worker role `ps_worker`. Phase 0 creates only the first three; whether the worker gets its own role is still to settle.
|
A superuser for bootstrap, the migrate role `ps_migrate` (owns the schema, runs migrations) and the app role `ps_app`. The plan's deployment section also names a worker role `ps_worker`. Phase 0 creates only the first three; whether the worker gets its own role is still to settle.
|
||||||
|
|
||||||
## Identity (phase 1)
|
## Identity (phase 1, migration 0002)
|
||||||
|
|
||||||
users, user_roles, sessions, devices, user_pins, signin_attempts, signatures.
|
Enums: `role_kind` (admin, clerical, clerical_supervisor, warehouse, warehouse_supervisor, qc, qc_supervisor, pm, shop_worker, shop_lead, shop_supervisor), `session_kind` (password, pin), `sig_factor` (password, pin), `dept_kind` (support, shop).
|
||||||
|
|
||||||
## Organisation (phase 2)
|
- `users`: `id uuid` is the AD `objectGUID`, stable across renames. Caches `sam_account` (unique, case-insensitive), `upn`, `display_name`, `emp_no` (text; indexed but not unique, because a duplicate must be storable and flagged), `email`, `welder_stamp`, `active`, `directory_flags` jsonb (disabled, missing or duplicate employee ID), `ad_synced_at`, `last_signin_at`. A user whose AD account is disabled or gone keeps the row, marked inactive.
|
||||||
|
- `user_roles`: (`user_id`, `role`, `dept_code`) rebuilt at every sign-in, at the 15-minute role refresh and by the AD refresh. Office roles carry their department code, admin carries null, shop roles carry the two-digit code. Only the highest shop level per department is stored.
|
||||||
|
- `sessions`: `token_hash` (HMAC-SHA256 of the cookie token with the session key), `kind`, `device_id` for PIN sessions, `expires_at` (absolute), `last_seen_at` (idle), `locked_since`, `revoked_at` and `revoked_reason`, `ip`, `user_agent`, `roles_snapshot` jsonb (`{"roles": [...], "groups": [...]}`), `roles_checked_at`, `stepup_failures`, `hidden_since` (the last hidden-tab report, cleared by the next request).
|
||||||
|
- `devices`: registered shop devices. `name`, `token_hash` of the device cookie, `registered_by`, `last_seen_at`, `revoked_at`, `revoked_by`.
|
||||||
|
- `user_pins`: one row per user with a PIN. Argon2id `hash`, `failed_count` (across sign-in, unlock and signature), `disabled_at`, `set_at`. Never readable by Admin in clear; Admin may delete the row.
|
||||||
|
- `signin_attempts`: append-only. `account` (`lower(login)`, `emp:<emp_no>` or `user:<uuid>`), `ip`, `kind` (password, pin, unlock, signature, pin_set), `ok`, `reason`, `user_id`, `session_id`. Both rate limits count the failed rows here.
|
||||||
|
- `signatures`: append-only. Who (`user_id`, `account` and `display_name` snapshots), the `session_id` and `session_kind`, the `factor`, `action`, `meaning`, `packet_id`, `subject_type`, `subject_id` and a `content_hash` (sha256 of the canonical JSON of what was signed). Later phases reference it from every sign-off row.
|
||||||
|
|
||||||
departments (code and slug immutable), stations, user_station_limits.
|
Append-only tables use the `ps_append_only` trigger from 0001 and revoke UPDATE, DELETE and TRUNCATE from `ps_app`.
|
||||||
|
|
||||||
|
## Organisation (phase 1 seed, phase 2 completes)
|
||||||
|
|
||||||
|
- `departments`: `code` (text PK, `CL`, `WH`, `QC`, `PM`, `01` to `14`), `slug` (the AD group short name, unique), `name`, `kind`, `sort`, `active`, `supervisor_group` (false only for PM). A trigger refuses changes to `code` and `slug`. Seeded with the 18 departments from the brief and the old `depts.js`.
|
||||||
|
- `stations`: (`dept_code`, `name`, `sort`, `active`), seeded with the old station lists (Stall 1 to 6, Station 1 to 4, Hydro Bay 1 and 2, Blast Booth, Paint Booth 1 and 2).
|
||||||
|
- `user_station_limits`: phase 2.
|
||||||
|
|
||||||
|
The 50 AD group names are derived from `departments` plus `PS-Admins`: `PS-<slug>` and `PS-<slug>-Supervisor` for support departments, `PS-<code>-<slug>-<Worker|Lead|Supervisor>` for shop departments. `packetstation ad-groups --list` prints them.
|
||||||
|
|
||||||
## Projects and units (phase 2)
|
## Projects and units (phase 2)
|
||||||
|
|
||||||
|
|||||||
+16
-3
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
This document is rewritten for the server build. The old browser build's security document is in the old repo (`C:\Users\spencerm\Coding\PacketStation\docs\SECURITY.md`). The design comes from [BRIEF.md](BRIEF.md) and [PLAN.md](PLAN.md).
|
This document is rewritten for the server build. The old browser build's security document is in the old repo (`C:\Users\spencerm\Coding\PacketStation\docs\SECURITY.md`). The design comes from [BRIEF.md](BRIEF.md) and [PLAN.md](PLAN.md).
|
||||||
|
|
||||||
Status: phase 0. Most controls below are designed, not built. Each one names the phase that builds it.
|
Status: phase 1. The identity controls (sessions, PIN, rate limits, audit, Origin check, derived group map) are built and tested against a Samba domain controller in CI. Every other control names the phase that builds it.
|
||||||
|
|
||||||
Contents:
|
Contents:
|
||||||
|
|
||||||
@@ -44,9 +44,12 @@ The M: drive build had 20 layers of protection, most of them enforced in the bro
|
|||||||
- HttpOnly, SameSite=Strict session cookie. The session row on the server decides.
|
- HttpOnly, SameSite=Strict session cookie. The session row on the server decides.
|
||||||
- Password sessions: idle sign-out after 15 minutes, absolute 12 hours. PIN shop sessions: absolute 10 hours, idle 15 minutes. All are settings.
|
- Password sessions: idle sign-out after 15 minutes, absolute 12 hours. PIN shop sessions: absolute 10 hours, idle 15 minutes. All are settings.
|
||||||
- Idle and background lock are reported by the browser and enforced by the server. Unlock is a step-up check with the PIN or the domain password.
|
- Idle and background lock are reported by the browser and enforced by the server. Unlock is a step-up check with the PIN or the domain password.
|
||||||
- Origin check on every state-changing request.
|
- Origin check on every state-changing request: the `Origin` header (or the `Referer` origin) must match the request host, and `X-Requested-With: PacketStation` must be present. Otherwise 403.
|
||||||
- Admin is a password session only. A PIN session cannot open Admin or change Account settings.
|
- Admin is a password session only. A PIN session cannot open Admin or change Account settings.
|
||||||
- Roles are resolved from AD at sign-in, cached on the session, and re-resolved every 15 minutes and nightly. A disabled AD account is always refused.
|
- Roles are resolved from AD at sign-in (nested groups through `LDAP_MATCHING_RULE_IN_CHAIN`), cached on the session, and re-resolved every 15 minutes on the session and by the AD refresh. A disabled AD account is always refused. A session whose user has lost every role is ended at the next refresh.
|
||||||
|
- The session cookie token is stored only as an HMAC with the session key. The AD password is used for the bind and discarded.
|
||||||
|
- The group-to-role map is derived from the department table and the `PS-` naming convention at startup. No screen edits it, so nobody can promote a group or themselves inside the app.
|
||||||
|
- The browser reports hidden tabs and idle time; the server records `locked_since` and refuses a locked session with 423 until a step-up unlock. The server also locks a session itself when no request arrived for the lock interval (3 minutes, as the old build's screen lock), and when a tab stayed hidden for over a minute (the old build's background lock). A reload or an in-app navigation never locks.
|
||||||
|
|
||||||
### PIN (phase 1)
|
### PIN (phase 1)
|
||||||
|
|
||||||
@@ -54,6 +57,8 @@ The M: drive build had 20 layers of protection, most of them enforced in the bro
|
|||||||
- 6 to 12 digits, hashed with Argon2id on the server. Never visible to Admin. Admin can clear a PIN (audited), not set one.
|
- 6 to 12 digits, hashed with Argon2id on the server. Never visible to Admin. Admin can clear a PIN (audited), not set one.
|
||||||
- PIN sign-in uses the employee ID and works only on registered devices. Devices are registered by an Admin or a shop department Supervisor in a password session.
|
- PIN sign-in uses the employee ID and works only on registered devices. Devices are registered by an Admin or a shop department Supervisor in a password session.
|
||||||
- Five wrong PIN attempts in a row, across sign-in, unlock and signature, disable the PIN. Three wrong attempts at unlock or signature end the session. A guessed PIN never touches AD.
|
- Five wrong PIN attempts in a row, across sign-in, unlock and signature, disable the PIN. Three wrong attempts at unlock or signature end the session. A guessed PIN never touches AD.
|
||||||
|
- A PIN sign-in still checks AD with the service account: a disabled account, or one removed from every group, is refused.
|
||||||
|
- The device cookie is a random token stored as an HMAC; revoking a device ends every PIN session on it.
|
||||||
|
|
||||||
### Rate limits (phase 1)
|
### Rate limits (phase 1)
|
||||||
|
|
||||||
@@ -61,6 +66,8 @@ The M: drive build had 20 layers of protection, most of them enforced in the bro
|
|||||||
- Defaults: 5 failed password sign-ins per account per 5 minutes, then a 10-minute cooldown. 30 failed attempts per client address per 5 minutes. Successful sign-ins never count.
|
- Defaults: 5 failed password sign-ins per account per 5 minutes, then a 10-minute cooldown. 30 failed attempts per client address per 5 minutes. Successful sign-ins never count.
|
||||||
- The domain's own lockout (20 attempts in 5 minutes) stays the last line.
|
- The domain's own lockout (20 attempts in 5 minutes) stays the last line.
|
||||||
- The client address comes from `X-Forwarded-For` only when the request comes from `npm_app_1` itself, re-resolved on change. Other containers on `npm_default` are not trusted.
|
- The client address comes from `X-Forwarded-For` only when the request comes from `npm_app_1` itself, re-resolved on change. Other containers on `npm_default` are not trusted.
|
||||||
|
- A refused attempt answers 429 with `Retry-After`, is recorded as `rate_limited` and never counts toward the limits itself.
|
||||||
|
- Failed sign-ins answer one message for an unknown account, a wrong password and a disabled account, so accounts cannot be enumerated. The audit and `signin_attempts` keep the real reason.
|
||||||
|
|
||||||
### Policy (phase 2)
|
### Policy (phase 2)
|
||||||
|
|
||||||
@@ -74,6 +81,12 @@ The M: drive build had 20 layers of protection, most of them enforced in the bro
|
|||||||
- Append-only `audit_events`, with a hash chain (`prev_hash`, `row_hash`).
|
- Append-only `audit_events`, with a hash chain (`prev_hash`, `row_hash`).
|
||||||
- The app role may insert and select, never update or delete. A trigger also refuses updates and deletes. Migrations run as a separate role.
|
- The app role may insert and select, never update or delete. A trigger also refuses updates and deletes. Migrations run as a separate role.
|
||||||
- `packetstation doctor` checks that an audit UPDATE fails.
|
- `packetstation doctor` checks that an audit UPDATE fails.
|
||||||
|
- Every identity event is a row: sign-in, failed sign-in with a reason, sign-out, lock, unlock, session ended, PIN set, disabled or cleared, device registered or revoked, signature, AD refresh. Each carries the user, session, roles, client address and a small detail object, never a secret.
|
||||||
|
- `signin_attempts` and `signatures` are append-only in the same way.
|
||||||
|
|
||||||
|
### CI identity fixtures (phase 1)
|
||||||
|
|
||||||
|
- CI runs a throwaway Samba Active Directory domain controller (`PSTEST.LOCAL`) built from `deploy/samba/`, with a generated CA so the LDAPS path is real. It is seeded with the 50 groups (one missing and one extra on purpose) and test users for every role, including nested, disabled, multi-role, missing and duplicate employee ID cases. Passwords are random per run and exported to a volume the tests read. PESCO's AD is never used by CI.
|
||||||
|
|
||||||
### Seals (phase 7)
|
### Seals (phase 7)
|
||||||
|
|
||||||
|
|||||||
+295
-24
@@ -1,35 +1,306 @@
|
|||||||
import { render, screen } from "@testing-library/react";
|
import { act, fireEvent, screen, waitFor, within } from "@testing-library/react";
|
||||||
import { MemoryRouter } from "react-router";
|
import { describe, expect, it, vi } from "vitest";
|
||||||
import { describe, expect, it } from "vitest";
|
import { DEPARTMENTS, NO_SESSION, makeMe, renderApp } from "./test/auth";
|
||||||
import { mockFetch } from "./test/fetchMock";
|
import { callsTo, mockFetch } from "./test/fetchMock";
|
||||||
import { AppRoutes } from "./App";
|
|
||||||
|
|
||||||
function renderAt(path: string) {
|
const NO_DEVICE = { body: { device: null, stack: "test", insecure_ldap: false, pin_digits: { min: 6, max: 12 } } };
|
||||||
return render(
|
const WITH_DEVICE = {
|
||||||
<MemoryRouter initialEntries={[path]}>
|
body: { device: { id: "dev-1", name: "Weld Parts Stall 3" }, stack: "test", insecure_ldap: false, pin_digits: { min: 6, max: 12 } },
|
||||||
<AppRoutes />
|
};
|
||||||
</MemoryRouter>,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("routes", () => {
|
describe("routes", () => {
|
||||||
it("home shows the top bar and the version", async () => {
|
it("home sends a signed-out visitor to sign-in", async () => {
|
||||||
mockFetch({ "/api/version": { body: { version: "0.0.1" } }, "/healthz": { body: "ok" } });
|
mockFetch({ "/api/auth/me": NO_SESSION, "/api/auth/context": NO_DEVICE });
|
||||||
renderAt("/");
|
renderApp("/");
|
||||||
|
expect(await screen.findByRole("heading", { name: "Sign in" })).toBeInTheDocument();
|
||||||
expect(screen.getByRole("img", { name: "PESCO" })).toBeInTheDocument();
|
expect(screen.getByRole("img", { name: "PESCO" })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("about shows the version", async () => {
|
||||||
|
mockFetch({ "/api/auth/me": NO_SESSION, "/api/version": { body: { version: "0.0.1" } }, "/healthz": { body: "ok" } });
|
||||||
|
renderApp("/about");
|
||||||
expect(await screen.findByText("0.0.1")).toBeInTheDocument();
|
expect(await screen.findByText("0.0.1")).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("sign-in shows both tabs with disabled inputs", () => {
|
it("unknown deep paths show the 404 page", async () => {
|
||||||
renderAt("/signin");
|
mockFetch({ "/api/auth/me": NO_SESSION });
|
||||||
expect(screen.getByRole("tab", { name: "Domain password" })).toHaveAttribute("aria-selected", "true");
|
renderApp("/no/such/page");
|
||||||
expect(screen.getByRole("tab", { name: "PIN" })).toBeInTheDocument();
|
expect(await screen.findByRole("heading", { name: "Page not found" })).toBeInTheDocument();
|
||||||
expect(screen.getByLabelText("Password")).toBeDisabled();
|
|
||||||
expect(screen.getByText(/phase 1/)).toBeInTheDocument();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("unknown paths show the 404 page", () => {
|
it("a screen route without a session goes to sign-in", async () => {
|
||||||
renderAt("/no/such/page");
|
mockFetch({ "/api/auth/me": NO_SESSION, "/api/auth/context": NO_DEVICE });
|
||||||
expect(screen.getByRole("heading", { name: "Page not found" })).toBeInTheDocument();
|
renderApp("/clerical");
|
||||||
|
expect(await screen.findByRole("heading", { name: "Sign in" })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("a disallowed screen goes to the user's first screen", async () => {
|
||||||
|
mockFetch({ "/api/auth/me": { body: makeMe() } });
|
||||||
|
renderApp("/admin");
|
||||||
|
expect(await screen.findByRole("heading", { name: "Clerical" })).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("This screen arrives in phase 2.")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("sign-in", () => {
|
||||||
|
it("posts the password and lands on the user's first screen", async () => {
|
||||||
|
const me = makeMe({ roles: ["shop:03:supervisor"], screens: ["supervisor", "stall"] });
|
||||||
|
const fetch = mockFetch({
|
||||||
|
"/api/auth/me": NO_SESSION,
|
||||||
|
"/api/auth/context": NO_DEVICE,
|
||||||
|
"POST /api/auth/signin/password": { body: me },
|
||||||
|
"/api/departments": { body: DEPARTMENTS },
|
||||||
|
});
|
||||||
|
renderApp("/signin");
|
||||||
|
fireEvent.change(await screen.findByLabelText("User name"), { target: { value: " sup.wes " } });
|
||||||
|
fireEvent.change(screen.getByLabelText("Password"), { target: { value: "secret-pass" } });
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Sign in" }));
|
||||||
|
|
||||||
|
expect(await screen.findByRole("heading", { name: "Supervisor" })).toBeInTheDocument();
|
||||||
|
expect(callsTo(fetch, "POST", "/api/auth/signin/password")).toEqual([{ login: "sup.wes", password: "secret-pass" }]);
|
||||||
|
expect(screen.getByText("Clara Clerk")).toBeInTheDocument();
|
||||||
|
expect(screen.getByRole("link", { name: "Account" })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows the server message on a failed sign-in", async () => {
|
||||||
|
mockFetch({
|
||||||
|
"/api/auth/me": NO_SESSION,
|
||||||
|
"/api/auth/context": NO_DEVICE,
|
||||||
|
"POST /api/auth/signin/password": {
|
||||||
|
status: 403,
|
||||||
|
body: { detail: "No role in Packet Station. Ask IT to add you to a group.", code: "no_role" },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
renderApp("/signin");
|
||||||
|
fireEvent.change(await screen.findByLabelText("User name"), { target: { value: "norole.nick" } });
|
||||||
|
fireEvent.change(screen.getByLabelText("Password"), { target: { value: "x" } });
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Sign in" }));
|
||||||
|
expect(await screen.findByRole("alert")).toHaveTextContent("No role in Packet Station. Ask IT to add you to a group.");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows the retry time on 429", async () => {
|
||||||
|
mockFetch({
|
||||||
|
"/api/auth/me": NO_SESSION,
|
||||||
|
"/api/auth/context": NO_DEVICE,
|
||||||
|
"POST /api/auth/signin/password": { status: 429, body: { detail: "Too many attempts", code: "rate_limited", retry_after: 150 } },
|
||||||
|
});
|
||||||
|
renderApp("/signin");
|
||||||
|
fireEvent.change(await screen.findByLabelText("User name"), { target: { value: "a" } });
|
||||||
|
fireEvent.change(screen.getByLabelText("Password"), { target: { value: "b" } });
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Sign in" }));
|
||||||
|
expect(await screen.findByRole("alert")).toHaveTextContent("Try again in 3 minutes.");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("hides the PIN tab without a registered device", async () => {
|
||||||
|
const fetch = mockFetch({ "/api/auth/me": NO_SESSION, "/api/auth/context": NO_DEVICE });
|
||||||
|
renderApp("/signin");
|
||||||
|
expect(await screen.findByRole("tab", { name: "Domain password" })).toHaveAttribute("aria-selected", "true");
|
||||||
|
await waitFor(() => expect(callsTo(fetch, "GET", "/api/auth/context")).toHaveLength(1));
|
||||||
|
expect(screen.queryByRole("tab", { name: "PIN" })).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows the PIN tab on a registered device and types with the keypad", async () => {
|
||||||
|
const me = makeMe({ session: { kind: "pin" } });
|
||||||
|
const fetch = mockFetch({
|
||||||
|
"/api/auth/me": NO_SESSION,
|
||||||
|
"/api/auth/context": WITH_DEVICE,
|
||||||
|
"POST /api/auth/signin/pin": { body: me },
|
||||||
|
});
|
||||||
|
renderApp("/signin");
|
||||||
|
const pinTab = await screen.findByRole("tab", { name: "PIN" });
|
||||||
|
expect(pinTab).toHaveAttribute("aria-selected", "true");
|
||||||
|
expect(screen.getByText(/Weld Parts Stall 3/)).toBeInTheDocument();
|
||||||
|
|
||||||
|
// The keypad types into the employee ID first.
|
||||||
|
for (const d of ["0", "4", "0", "0", "1"]) fireEvent.click(screen.getByRole("button", { name: `Digit ${d}` }));
|
||||||
|
expect(screen.getByLabelText("Employee ID")).toHaveValue("04001");
|
||||||
|
// Then into the PIN once it has the focus.
|
||||||
|
fireEvent.focus(screen.getByLabelText("PIN", { selector: "input" }));
|
||||||
|
for (const d of ["1", "2", "3", "4", "5", "6", "7"]) fireEvent.click(screen.getByRole("button", { name: `Digit ${d}` }));
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Back" }));
|
||||||
|
expect(screen.getByLabelText("PIN", { selector: "input" })).toHaveValue("123456");
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Sign in" }));
|
||||||
|
expect(await screen.findByRole("heading", { name: "Clerical" })).toBeInTheDocument();
|
||||||
|
expect(callsTo(fetch, "POST", "/api/auth/signin/pin")).toEqual([{ emp_no: "04001", pin: "123456" }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("redirects away from sign-in when already signed in", async () => {
|
||||||
|
mockFetch({ "/api/auth/me": { body: makeMe() } });
|
||||||
|
renderApp("/signin");
|
||||||
|
expect(await screen.findByRole("heading", { name: "Clerical" })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("lock screen", () => {
|
||||||
|
it("appears on 423 from /api/auth/me and a right password hides it", async () => {
|
||||||
|
const fetch = mockFetch({
|
||||||
|
"/api/auth/me": { status: 423, body: { detail: "Locked", code: "locked" } },
|
||||||
|
"POST /api/auth/unlock": { body: makeMe() },
|
||||||
|
});
|
||||||
|
renderApp("/clerical");
|
||||||
|
const dialog = await screen.findByRole("dialog");
|
||||||
|
expect(dialog).toHaveAttribute("aria-modal", "true");
|
||||||
|
expect(within(dialog).getByText("Locked")).toBeInTheDocument();
|
||||||
|
fireEvent.change(within(dialog).getByLabelText("Password"), { target: { value: "pw" } });
|
||||||
|
fireEvent.click(within(dialog).getByRole("button", { name: "Unlock" }));
|
||||||
|
|
||||||
|
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
|
||||||
|
expect(callsTo(fetch, "POST", "/api/auth/unlock")).toEqual([{ factor: "password", secret: "pw" }]);
|
||||||
|
expect(screen.getByRole("heading", { name: "Clerical" })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses the PIN keypad, warns after a miss, and ends on session_ended", async () => {
|
||||||
|
let tries = 0;
|
||||||
|
mockFetch({
|
||||||
|
"/api/auth/me": { body: makeMe({ pin: { set: true, disabled: false }, session: { locked: true } }) },
|
||||||
|
"/api/auth/context": NO_DEVICE,
|
||||||
|
"POST /api/auth/unlock": () =>
|
||||||
|
++tries < 2
|
||||||
|
? { status: 401, body: { detail: "Wrong PIN.", code: "bad_secret" } }
|
||||||
|
: { status: 401, body: { detail: "Signed out after three wrong attempts.", code: "session_ended" } },
|
||||||
|
});
|
||||||
|
renderApp("/clerical");
|
||||||
|
const dialog = await screen.findByRole("dialog");
|
||||||
|
expect(within(dialog).getByRole("heading", { name: "Clara Clerk" })).toBeInTheDocument();
|
||||||
|
for (const d of ["9", "9", "9", "9", "9", "9"]) fireEvent.click(within(dialog).getByRole("button", { name: `Digit ${d}` }));
|
||||||
|
fireEvent.click(within(dialog).getByRole("button", { name: "Unlock" }));
|
||||||
|
expect(await within(dialog).findByText("Wrong PIN.")).toBeInTheDocument();
|
||||||
|
expect(within(dialog).getByText("Three wrong attempts end the session.")).toBeInTheDocument();
|
||||||
|
|
||||||
|
for (const d of ["1", "1", "1", "1", "1", "1"]) fireEvent.click(within(dialog).getByRole("button", { name: `Digit ${d}` }));
|
||||||
|
fireEvent.click(within(dialog).getByRole("button", { name: "Unlock" }));
|
||||||
|
expect(await screen.findByRole("heading", { name: "Sign in" })).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("Signed out after three wrong attempts.")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("locks after the idle time and tells the server", async () => {
|
||||||
|
const fetch = mockFetch({ "/api/auth/me": { body: makeMe() }, "POST /api/auth/lock": { status: 204 } });
|
||||||
|
renderApp("/clerical", { idleLockMs: 30, idleCheckMs: 10 });
|
||||||
|
expect(await screen.findByRole("dialog")).toBeInTheDocument();
|
||||||
|
expect(callsTo(fetch, "POST", "/api/auth/lock")).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
function setHidden(hidden: boolean) {
|
||||||
|
Object.defineProperty(document, "hidden", { configurable: true, get: () => hidden });
|
||||||
|
act(() => {
|
||||||
|
document.dispatchEvent(new Event("visibilitychange"));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
it("a short hidden spell does not lock, and both reports are posted", async () => {
|
||||||
|
const fetch = mockFetch({ "/api/auth/me": { body: makeMe() }, "POST /api/auth/visibility": { status: 204 } });
|
||||||
|
renderApp("/clerical");
|
||||||
|
expect(await screen.findByRole("heading", { name: "Clerical" })).toBeInTheDocument();
|
||||||
|
setHidden(true);
|
||||||
|
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
||||||
|
setHidden(false);
|
||||||
|
await waitFor(() => expect(callsTo(fetch, "GET", "/api/auth/me")).toHaveLength(2));
|
||||||
|
expect(callsTo(fetch, "POST", "/api/auth/visibility")).toEqual([{ hidden: true }, { hidden: false }]);
|
||||||
|
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
||||||
|
Reflect.deleteProperty(document, "hidden");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("a tab hidden over 60 s comes back locked", async () => {
|
||||||
|
let now = 1_000_000;
|
||||||
|
vi.spyOn(Date, "now").mockImplementation(() => now);
|
||||||
|
let returned = false;
|
||||||
|
const fetch = mockFetch({
|
||||||
|
"/api/auth/me": () => ({ body: makeMe({ session: { locked: returned } }) }),
|
||||||
|
"POST /api/auth/visibility": ({ body }) => {
|
||||||
|
if ((body as { hidden: boolean }).hidden === false) returned = true;
|
||||||
|
return { status: 204 };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
renderApp("/clerical");
|
||||||
|
expect(await screen.findByRole("heading", { name: "Clerical" })).toBeInTheDocument();
|
||||||
|
setHidden(true);
|
||||||
|
now += 61_000;
|
||||||
|
setHidden(false);
|
||||||
|
// Locked at once, before the server answers, and still locked once Me says so.
|
||||||
|
expect(screen.getByRole("dialog")).toBeInTheDocument();
|
||||||
|
await waitFor(() => expect(callsTo(fetch, "GET", "/api/auth/me")).toHaveLength(2));
|
||||||
|
expect(screen.getByRole("dialog")).toBeInTheDocument();
|
||||||
|
expect(callsTo(fetch, "POST", "/api/auth/visibility")).toEqual([{ hidden: true }, { hidden: false }]);
|
||||||
|
Reflect.deleteProperty(document, "hidden");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("locks on 423 from any other call", async () => {
|
||||||
|
mockFetch({
|
||||||
|
"/api/auth/me": { body: makeMe() },
|
||||||
|
"/api/account": { status: 423, body: { detail: "Locked", code: "locked" } },
|
||||||
|
});
|
||||||
|
renderApp("/account");
|
||||||
|
expect(await screen.findByRole("dialog")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("role switcher", () => {
|
||||||
|
it("shows only the user's screens and switches between them", async () => {
|
||||||
|
mockFetch({
|
||||||
|
"/api/auth/me": { body: makeMe({ roles: ["clerical", "shop:06:supervisor"], screens: ["clerical", "supervisor", "stall"] }) },
|
||||||
|
});
|
||||||
|
renderApp("/clerical");
|
||||||
|
const nav = await screen.findByRole("navigation", { name: "Screens" });
|
||||||
|
const buttons = within(nav).getAllByRole("button");
|
||||||
|
expect(buttons.map((b) => b.textContent)).toEqual(["Clerical", "Supervisor", "Weld Stall"]);
|
||||||
|
expect(within(nav).getByRole("button", { name: "Clerical" })).toHaveAttribute("aria-pressed", "true");
|
||||||
|
|
||||||
|
fireEvent.click(within(nav).getByRole("button", { name: "Weld Stall" }));
|
||||||
|
expect(await screen.findByRole("heading", { name: "Weld Stall" })).toBeInTheDocument();
|
||||||
|
expect(within(nav).getByRole("button", { name: "Weld Stall" })).toHaveAttribute("aria-pressed", "true");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is hidden for a user with one screen", async () => {
|
||||||
|
mockFetch({ "/api/auth/me": { body: makeMe() } });
|
||||||
|
renderApp("/clerical");
|
||||||
|
expect(await screen.findByRole("heading", { name: "Clerical" })).toBeInTheDocument();
|
||||||
|
expect(screen.queryByRole("navigation", { name: "Screens" })).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("signs out from the top bar", async () => {
|
||||||
|
const fetch = mockFetch({
|
||||||
|
"/api/auth/me": { body: makeMe() },
|
||||||
|
"POST /api/auth/signout": { status: 204 },
|
||||||
|
"/api/auth/context": NO_DEVICE,
|
||||||
|
});
|
||||||
|
renderApp("/clerical");
|
||||||
|
fireEvent.click(await screen.findByRole("button", { name: "Sign out" }));
|
||||||
|
expect(await screen.findByRole("heading", { name: "Sign in" })).toBeInTheDocument();
|
||||||
|
expect(callsTo(fetch, "POST", "/api/auth/signout")).toHaveLength(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("events", () => {
|
||||||
|
it("a session revoked event for this session signs out", async () => {
|
||||||
|
const sources: FakeEventSource[] = [];
|
||||||
|
class FakeEventSource {
|
||||||
|
url: string;
|
||||||
|
listeners = new Map<string, (ev: MessageEvent) => void>();
|
||||||
|
constructor(url: string) {
|
||||||
|
this.url = url;
|
||||||
|
sources.push(this);
|
||||||
|
}
|
||||||
|
addEventListener(type: string, fn: (ev: MessageEvent) => void) {
|
||||||
|
this.listeners.set(type, fn);
|
||||||
|
}
|
||||||
|
close() {}
|
||||||
|
emit(type: string, data: unknown) {
|
||||||
|
this.listeners.get(type)?.(new MessageEvent(type, { data: JSON.stringify(data) }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
vi.stubGlobal("EventSource", FakeEventSource);
|
||||||
|
mockFetch({ "/api/auth/me": { body: makeMe() }, "/api/auth/context": NO_DEVICE });
|
||||||
|
renderApp("/clerical");
|
||||||
|
expect(await screen.findByRole("heading", { name: "Clerical" })).toBeInTheDocument();
|
||||||
|
const es = sources.at(-1);
|
||||||
|
expect(es?.url).toBe("/api/events");
|
||||||
|
|
||||||
|
act(() => es?.emit("session", { session_id: "other", action: "revoked" }));
|
||||||
|
expect(screen.getByRole("heading", { name: "Clerical" })).toBeInTheDocument();
|
||||||
|
|
||||||
|
act(() => es?.emit("session", { session_id: "sess-1", action: "revoked" }));
|
||||||
|
expect(await screen.findByRole("heading", { name: "Sign in" })).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("This session was signed out from another place.")).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+13
-1
@@ -1,8 +1,13 @@
|
|||||||
import { BrowserRouter, Route, Routes } from "react-router";
|
import { BrowserRouter, Route, Routes } from "react-router";
|
||||||
|
import { AuthProvider } from "./auth/AuthProvider";
|
||||||
import { Layout } from "./components/Layout";
|
import { Layout } from "./components/Layout";
|
||||||
|
import { RequireAuth } from "./components/RequireAuth";
|
||||||
|
import { AboutPage } from "./pages/AboutPage";
|
||||||
import { HomePage } from "./pages/HomePage";
|
import { HomePage } from "./pages/HomePage";
|
||||||
import { NotFoundPage } from "./pages/NotFoundPage";
|
import { NotFoundPage } from "./pages/NotFoundPage";
|
||||||
import { SignInPage } from "./pages/SignInPage";
|
import { SignInPage } from "./pages/SignInPage";
|
||||||
|
import { AccountPage } from "./screens/account/AccountPage";
|
||||||
|
import { ScreenRoute } from "./screens/ScreenRoute";
|
||||||
|
|
||||||
/** Route table. Exported apart from the router so tests can mount it in a MemoryRouter. */
|
/** Route table. Exported apart from the router so tests can mount it in a MemoryRouter. */
|
||||||
export function AppRoutes() {
|
export function AppRoutes() {
|
||||||
@@ -11,6 +16,11 @@ export function AppRoutes() {
|
|||||||
<Route element={<Layout />}>
|
<Route element={<Layout />}>
|
||||||
<Route index element={<HomePage />} />
|
<Route index element={<HomePage />} />
|
||||||
<Route path="signin" element={<SignInPage />} />
|
<Route path="signin" element={<SignInPage />} />
|
||||||
|
<Route path="about" element={<AboutPage />} />
|
||||||
|
<Route element={<RequireAuth />}>
|
||||||
|
<Route path="account" element={<AccountPage />} />
|
||||||
|
<Route path=":screen" element={<ScreenRoute />} />
|
||||||
|
</Route>
|
||||||
<Route path="*" element={<NotFoundPage />} />
|
<Route path="*" element={<NotFoundPage />} />
|
||||||
</Route>
|
</Route>
|
||||||
</Routes>
|
</Routes>
|
||||||
@@ -20,7 +30,9 @@ export function AppRoutes() {
|
|||||||
export default function App() {
|
export default function App() {
|
||||||
return (
|
return (
|
||||||
<BrowserRouter>
|
<BrowserRouter>
|
||||||
<AppRoutes />
|
<AuthProvider>
|
||||||
|
<AppRoutes />
|
||||||
|
</AuthProvider>
|
||||||
</BrowserRouter>
|
</BrowserRouter>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -61,6 +61,37 @@ async function readBody(res: Response): Promise<unknown> {
|
|||||||
return text;
|
return text;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Called for every non-2xx answer. The auth layer uses it to react to 401 and 423 from any call. */
|
||||||
|
export type ErrorListener = (err: ApiError, path: string, method: Method) => void;
|
||||||
|
|
||||||
|
const errorListeners = new Set<ErrorListener>();
|
||||||
|
|
||||||
|
/** Adds a listener for failed responses. Returns the function that removes it. */
|
||||||
|
export function onApiError(fn: ErrorListener): () => void {
|
||||||
|
errorListeners.add(fn);
|
||||||
|
return () => {
|
||||||
|
errorListeners.delete(fn);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The snake_case code the server puts on every error ({"detail", "code"}), if any. */
|
||||||
|
export function errorCode(err: unknown): string | undefined {
|
||||||
|
if (err instanceof ApiError && err.body && typeof err.body === "object" && "code" in err.body) {
|
||||||
|
const code = (err.body as { code: unknown }).code;
|
||||||
|
if (typeof code === "string") return code;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Seconds from a 429 body ({"retry_after": N}), if any. */
|
||||||
|
export function retryAfter(err: unknown): number | undefined {
|
||||||
|
if (err instanceof ApiError && err.body && typeof err.body === "object" && "retry_after" in err.body) {
|
||||||
|
const n = Number((err.body as { retry_after: unknown }).retry_after);
|
||||||
|
if (Number.isFinite(n) && n > 0) return n;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
export async function request<T>(path: string, opts: RequestOptions = {}): Promise<T> {
|
export async function request<T>(path: string, opts: RequestOptions = {}): Promise<T> {
|
||||||
assertSameOrigin(path);
|
assertSameOrigin(path);
|
||||||
const method: Method = opts.method ?? "GET";
|
const method: Method = opts.method ?? "GET";
|
||||||
@@ -88,7 +119,11 @@ export async function request<T>(path: string, opts: RequestOptions = {}): Promi
|
|||||||
}
|
}
|
||||||
|
|
||||||
const parsed = await readBody(res);
|
const parsed = await readBody(res);
|
||||||
if (!res.ok) throw new ApiError(res.status, parsed);
|
if (!res.ok) {
|
||||||
|
const err = new ApiError(res.status, parsed);
|
||||||
|
for (const fn of errorListeners) fn(err, path, method);
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
return parsed as T;
|
return parsed as T;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,4 +134,5 @@ export const api = {
|
|||||||
put: <T>(path: string, body?: unknown) => request<T>(path, { method: "PUT", body }),
|
put: <T>(path: string, body?: unknown) => request<T>(path, { method: "PUT", body }),
|
||||||
patch: <T>(path: string, body?: unknown) => request<T>(path, { method: "PATCH", body }),
|
patch: <T>(path: string, body?: unknown) => request<T>(path, { method: "PATCH", body }),
|
||||||
del: <T>(path: string) => request<T>(path, { method: "DELETE" }),
|
del: <T>(path: string) => request<T>(path, { method: "DELETE" }),
|
||||||
|
delWithBody: <T>(path: string, body: unknown) => request<T>(path, { method: "DELETE", body }),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,231 @@
|
|||||||
|
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||||
|
import { ApiError, errorCode, onApiError } from "../api/client";
|
||||||
|
import { authApi, departmentsApi } from "./api";
|
||||||
|
import { AuthCtx, type AuthState, type AuthStatus } from "./context";
|
||||||
|
import { roleLabel as labelFor } from "./roles";
|
||||||
|
import type { Department, Factor, Me } from "./types";
|
||||||
|
import { useEvents } from "./useEvents";
|
||||||
|
|
||||||
|
/** The old build's screen lock. The server locks at SESSION_LOCK_MINUTES too; it is the authority. */
|
||||||
|
export const IDLE_LOCK_MS = 3 * 60_000;
|
||||||
|
/** A tab hidden for longer than this comes back locked (the old build's rule). */
|
||||||
|
export const HIDDEN_LOCK_MS = 60_000;
|
||||||
|
const IDLE_CHECK_MS = 15_000;
|
||||||
|
const ACTIVITY_EVENTS = ["pointerdown", "keydown", "wheel", "touchstart"] as const;
|
||||||
|
|
||||||
|
/** 401 codes that mean this browser's session is gone. Other 401s (a wrong unlock PIN) are not. */
|
||||||
|
const SESSION_GONE = new Set(["no_session", "session_expired", "session_ended"]);
|
||||||
|
|
||||||
|
function goneNotice(err: ApiError): string {
|
||||||
|
const code = errorCode(err);
|
||||||
|
if (code === "no_session") return "Your session ended. Sign in again.";
|
||||||
|
return err.message || "Your session ended. Sign in again.";
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AuthProviderProps {
|
||||||
|
children: ReactNode;
|
||||||
|
/** Idle time before the local lock. Tests pass a small value. */
|
||||||
|
idleLockMs?: number;
|
||||||
|
/** How often the idle timer checks. */
|
||||||
|
idleCheckMs?: number;
|
||||||
|
/** Hidden time after which the tab comes back locked. Tests pass a small value. */
|
||||||
|
hiddenLockMs?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AuthProvider({ children, idleLockMs = IDLE_LOCK_MS, idleCheckMs = IDLE_CHECK_MS, hiddenLockMs = HIDDEN_LOCK_MS }: AuthProviderProps) {
|
||||||
|
const [status, setStatusState] = useState<AuthStatus>("loading");
|
||||||
|
const [me, setMeState] = useState<Me | null>(null);
|
||||||
|
const [departments, setDepartments] = useState<Department[]>([]);
|
||||||
|
const [notice, setNotice] = useState<string | null>(null);
|
||||||
|
const statusRef = useRef<AuthStatus>("loading");
|
||||||
|
const lastActivity = useRef(Date.now());
|
||||||
|
const deptsFor = useRef<string | null>(null);
|
||||||
|
|
||||||
|
const setStatus = useCallback((s: AuthStatus) => {
|
||||||
|
statusRef.current = s;
|
||||||
|
setStatusState(s);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const accept = useCallback(
|
||||||
|
(m: Me) => {
|
||||||
|
setMeState(m);
|
||||||
|
setNotice(null);
|
||||||
|
lastActivity.current = Date.now();
|
||||||
|
setStatus(m.session.locked ? "locked" : "ready");
|
||||||
|
},
|
||||||
|
[setStatus],
|
||||||
|
);
|
||||||
|
|
||||||
|
const endSession = useCallback(
|
||||||
|
(msg: string | null) => {
|
||||||
|
setMeState(null);
|
||||||
|
setDepartments([]);
|
||||||
|
deptsFor.current = null;
|
||||||
|
setNotice(msg);
|
||||||
|
setStatus("anonymous");
|
||||||
|
},
|
||||||
|
[setStatus],
|
||||||
|
);
|
||||||
|
|
||||||
|
const refresh = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
accept(await authApi.me());
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof ApiError && err.status === 423) setStatus("locked");
|
||||||
|
else if (err instanceof ApiError && err.status === 401) endSession(null);
|
||||||
|
else endSession(err instanceof Error ? err.message : "Could not reach the server.");
|
||||||
|
}
|
||||||
|
}, [accept, endSession, setStatus]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void refresh();
|
||||||
|
}, [refresh]);
|
||||||
|
|
||||||
|
// 401 and 423 from any call, not only the auth calls.
|
||||||
|
useEffect(
|
||||||
|
() =>
|
||||||
|
onApiError((err, path) => {
|
||||||
|
if (path.startsWith("/api/auth/signin")) return;
|
||||||
|
const st = statusRef.current;
|
||||||
|
if (st === "loading" || st === "anonymous") return;
|
||||||
|
if (err.status === 423) {
|
||||||
|
setStatus("locked");
|
||||||
|
} else if (err.status === 401 && SESSION_GONE.has(errorCode(err) ?? "")) {
|
||||||
|
endSession(goneNotice(err));
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
[endSession, setStatus],
|
||||||
|
);
|
||||||
|
|
||||||
|
// Department names for the role labels, once per signed-in user.
|
||||||
|
const userId = me?.user.id ?? null;
|
||||||
|
useEffect(() => {
|
||||||
|
if (status !== "ready" || !userId || deptsFor.current === userId) return;
|
||||||
|
deptsFor.current = userId;
|
||||||
|
departmentsApi
|
||||||
|
.list()
|
||||||
|
.then((d) => setDepartments(Array.isArray(d) ? d : []))
|
||||||
|
.catch(() => {
|
||||||
|
deptsFor.current = null;
|
||||||
|
});
|
||||||
|
}, [status, userId]);
|
||||||
|
|
||||||
|
const signInPassword = useCallback(
|
||||||
|
async (login: string, password: string) => {
|
||||||
|
const m = await authApi.signInPassword(login, password);
|
||||||
|
accept(m);
|
||||||
|
return m;
|
||||||
|
},
|
||||||
|
[accept],
|
||||||
|
);
|
||||||
|
|
||||||
|
const signInPin = useCallback(
|
||||||
|
async (empNo: string, pin: string) => {
|
||||||
|
const m = await authApi.signInPin(empNo, pin);
|
||||||
|
accept(m);
|
||||||
|
return m;
|
||||||
|
},
|
||||||
|
[accept],
|
||||||
|
);
|
||||||
|
|
||||||
|
const signOut = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
await authApi.signOut();
|
||||||
|
} catch {
|
||||||
|
// The cookie may already be gone. Signing out locally is what matters here.
|
||||||
|
}
|
||||||
|
endSession(null);
|
||||||
|
}, [endSession]);
|
||||||
|
|
||||||
|
const unlock = useCallback(
|
||||||
|
async (factor: Factor, secret: string) => {
|
||||||
|
const m = await authApi.unlock(factor, secret);
|
||||||
|
accept({ ...m, session: { ...m.session, locked: false } });
|
||||||
|
return m;
|
||||||
|
},
|
||||||
|
[accept],
|
||||||
|
);
|
||||||
|
|
||||||
|
const lock = useCallback(async () => {
|
||||||
|
if (statusRef.current !== "ready") return;
|
||||||
|
setStatus("locked");
|
||||||
|
try {
|
||||||
|
await authApi.lock();
|
||||||
|
} catch {
|
||||||
|
// A 401 here signs out through the listener. Otherwise the local lock stands.
|
||||||
|
}
|
||||||
|
}, [setStatus]);
|
||||||
|
|
||||||
|
// Hidden is reported, never locked at once: a reload or navigation fires hidden on the old page.
|
||||||
|
// Coming back is reported, then Me decides. Hidden longer than hiddenLockMs locks locally right away.
|
||||||
|
const hiddenAt = useRef<number | null>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
const onVisibility = () => {
|
||||||
|
const st = statusRef.current;
|
||||||
|
if (st !== "ready" && st !== "locked") return;
|
||||||
|
if (document.hidden) {
|
||||||
|
hiddenAt.current = Date.now();
|
||||||
|
authApi.visibility(true).catch(() => undefined);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const since = hiddenAt.current;
|
||||||
|
hiddenAt.current = null;
|
||||||
|
if (since !== null && Date.now() - since > hiddenLockMs && st === "ready") setStatus("locked");
|
||||||
|
authApi
|
||||||
|
.visibility(false)
|
||||||
|
.catch(() => undefined)
|
||||||
|
.then(() => refresh());
|
||||||
|
};
|
||||||
|
document.addEventListener("visibilitychange", onVisibility);
|
||||||
|
return () => document.removeEventListener("visibilitychange", onVisibility);
|
||||||
|
}, [setStatus, refresh, hiddenLockMs]);
|
||||||
|
|
||||||
|
// Local idle lock.
|
||||||
|
useEffect(() => {
|
||||||
|
const bump = () => {
|
||||||
|
lastActivity.current = Date.now();
|
||||||
|
};
|
||||||
|
for (const ev of ACTIVITY_EVENTS) document.addEventListener(ev, bump, { capture: true, passive: true });
|
||||||
|
return () => {
|
||||||
|
for (const ev of ACTIVITY_EVENTS) document.removeEventListener(ev, bump, { capture: true });
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (status !== "ready") return;
|
||||||
|
lastActivity.current = Date.now();
|
||||||
|
const id = window.setInterval(() => {
|
||||||
|
if (Date.now() - lastActivity.current >= idleLockMs) void lock();
|
||||||
|
}, idleCheckMs);
|
||||||
|
return () => window.clearInterval(id);
|
||||||
|
}, [status, idleLockMs, idleCheckMs, lock]);
|
||||||
|
|
||||||
|
const sessionId = status === "ready" || status === "locked" ? (me?.session.id ?? null) : null;
|
||||||
|
const presence = useEvents(sessionId, {
|
||||||
|
onRevoked: () => endSession("This session was signed out from another place."),
|
||||||
|
});
|
||||||
|
|
||||||
|
const roleLabel = useCallback((role: string) => labelFor(role, departments), [departments]);
|
||||||
|
|
||||||
|
const value = useMemo<AuthState>(
|
||||||
|
() => ({
|
||||||
|
status,
|
||||||
|
me,
|
||||||
|
departments,
|
||||||
|
notice,
|
||||||
|
presence,
|
||||||
|
refresh,
|
||||||
|
signInPassword,
|
||||||
|
signInPin,
|
||||||
|
signOut,
|
||||||
|
endSession,
|
||||||
|
unlock,
|
||||||
|
lock,
|
||||||
|
setMe: setMeState,
|
||||||
|
roleLabel,
|
||||||
|
}),
|
||||||
|
[status, me, departments, notice, presence, refresh, signInPassword, signInPin, signOut, endSession, unlock, lock, roleLabel],
|
||||||
|
);
|
||||||
|
|
||||||
|
return <AuthCtx.Provider value={value}>{children}</AuthCtx.Provider>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
// Typed calls for the phase 1 endpoints. Paths and shapes follow the design contract.
|
||||||
|
import { api } from "../api/client";
|
||||||
|
import type {
|
||||||
|
AccessLogRow,
|
||||||
|
AccountInfo,
|
||||||
|
AdLookup,
|
||||||
|
AdRefreshResult,
|
||||||
|
AdminDevice,
|
||||||
|
AdminUser,
|
||||||
|
AdminUserDetail,
|
||||||
|
AuthContextInfo,
|
||||||
|
Department,
|
||||||
|
DeviceRef,
|
||||||
|
Factor,
|
||||||
|
GroupMap,
|
||||||
|
Me,
|
||||||
|
PinState,
|
||||||
|
SessionRow,
|
||||||
|
SigninAttempt,
|
||||||
|
} from "./types";
|
||||||
|
|
||||||
|
const enc = encodeURIComponent;
|
||||||
|
|
||||||
|
export const authApi = {
|
||||||
|
context: (signal?: AbortSignal) => api.get<AuthContextInfo>("/api/auth/context", signal),
|
||||||
|
me: (signal?: AbortSignal) => api.get<Me>("/api/auth/me", signal),
|
||||||
|
signInPassword: (login: string, password: string) =>
|
||||||
|
api.post<Me>("/api/auth/signin/password", { login, password }),
|
||||||
|
signInPin: (emp_no: string, pin: string) => api.post<Me>("/api/auth/signin/pin", { emp_no, pin }),
|
||||||
|
signOut: () => api.post<null>("/api/auth/signout"),
|
||||||
|
lock: () => api.post<null>("/api/auth/lock"),
|
||||||
|
visibility: (hidden: boolean) => api.post<null>("/api/auth/visibility", { hidden }),
|
||||||
|
unlock: (factor: Factor, secret: string) => api.post<Me>("/api/auth/unlock", { factor, secret }),
|
||||||
|
};
|
||||||
|
|
||||||
|
export const accountApi = {
|
||||||
|
get: (signal?: AbortSignal) => api.get<AccountInfo>("/api/account", signal),
|
||||||
|
setPin: (password: string, pin: string) =>
|
||||||
|
api.post<{ pin: PinState }>("/api/account/pin", { password, pin }),
|
||||||
|
sessions: (signal?: AbortSignal) => api.get<SessionRow[]>("/api/account/sessions", signal),
|
||||||
|
signOutOthers: () => api.post<{ revoked: number }>("/api/account/sessions/signout-others"),
|
||||||
|
accessLog: (limit = 50, signal?: AbortSignal) =>
|
||||||
|
api.get<AccessLogRow[]>(`/api/account/access-log?limit=${limit}`, signal),
|
||||||
|
registerDevice: (name: string) => api.post<{ device: DeviceRef }>("/api/account/device", { name }),
|
||||||
|
};
|
||||||
|
|
||||||
|
export const adminApi = {
|
||||||
|
users: (q: string, signal?: AbortSignal) =>
|
||||||
|
api.get<AdminUser[]>(q ? `/api/admin/users?q=${enc(q)}` : "/api/admin/users", signal),
|
||||||
|
user: (id: string, signal?: AbortSignal) => api.get<AdminUserDetail>(`/api/admin/users/${enc(id)}`, signal),
|
||||||
|
lookup: (login: string, signal?: AbortSignal) =>
|
||||||
|
api.get<AdLookup>(`/api/admin/ad/lookup?login=${enc(login)}`, signal),
|
||||||
|
clearPin: (id: string, reason: string) =>
|
||||||
|
api.delWithBody<null>(`/api/admin/users/${enc(id)}/pin`, { reason }),
|
||||||
|
devices: (signal?: AbortSignal) => api.get<AdminDevice[]>("/api/admin/devices", signal),
|
||||||
|
revokeDevice: (id: string) => api.del<null>(`/api/admin/devices/${enc(id)}`),
|
||||||
|
groups: (signal?: AbortSignal) => api.get<GroupMap>("/api/admin/groups", signal),
|
||||||
|
refresh: () => api.post<AdRefreshResult>("/api/admin/ad/refresh"),
|
||||||
|
signinAttempts: (limit = 100, signal?: AbortSignal) =>
|
||||||
|
api.get<SigninAttempt[]>(`/api/admin/signin-attempts?limit=${limit}`, signal),
|
||||||
|
};
|
||||||
|
|
||||||
|
export const departmentsApi = {
|
||||||
|
list: (signal?: AbortSignal) => api.get<Department[]>("/api/departments", signal),
|
||||||
|
};
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { createContext } from "react";
|
||||||
|
import type { Department, Factor, Me, PresenceUser } from "./types";
|
||||||
|
|
||||||
|
export type AuthStatus = "loading" | "anonymous" | "ready" | "locked";
|
||||||
|
|
||||||
|
export interface AuthState {
|
||||||
|
status: AuthStatus;
|
||||||
|
/** Null while loading, when signed out, and when a 423 arrived before /me answered. */
|
||||||
|
me: Me | null;
|
||||||
|
departments: Department[];
|
||||||
|
/** Shown on the sign-in page once, for example after a session ended. */
|
||||||
|
notice: string | null;
|
||||||
|
presence: PresenceUser[];
|
||||||
|
refresh: () => Promise<void>;
|
||||||
|
signInPassword: (login: string, password: string) => Promise<Me>;
|
||||||
|
signInPin: (empNo: string, pin: string) => Promise<Me>;
|
||||||
|
signOut: () => Promise<void>;
|
||||||
|
/** Drops the session in the browser without calling the server, with a notice for the sign-in page. */
|
||||||
|
endSession: (notice: string | null) => void;
|
||||||
|
unlock: (factor: Factor, secret: string) => Promise<Me>;
|
||||||
|
lock: () => Promise<void>;
|
||||||
|
/** Replaces the cached Me, for example after a PIN change. */
|
||||||
|
setMe: (me: Me) => void;
|
||||||
|
roleLabel: (role: string) => string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const AuthCtx = createContext<AuthState | null>(null);
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { DEPARTMENTS } from "../test/auth";
|
||||||
|
import type { Department } from "./types";
|
||||||
|
import { firstScreen, homePath, roleChipClass, roleFromKind, roleLabel, screensFor } from "./roles";
|
||||||
|
|
||||||
|
const depts = DEPARTMENTS as Department[];
|
||||||
|
|
||||||
|
describe("roles", () => {
|
||||||
|
it("labels shop and office roles", () => {
|
||||||
|
expect(roleLabel("shop:03:supervisor", depts)).toBe("03 Weld Parts · Supervisor");
|
||||||
|
expect(roleLabel("shop:09:lead")).toBe("09 · Lead");
|
||||||
|
expect(roleLabel("clerical_supervisor")).toBe("Clerical supervisor");
|
||||||
|
expect(roleLabel("qc")).toBe("Q.C.");
|
||||||
|
expect(roleLabel("pm")).toBe("Project Management");
|
||||||
|
expect(roleLabel("admin")).toBe("Admin");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("maps roles to screens", () => {
|
||||||
|
expect(screensFor(["clerical", "shop:06:supervisor"])).toEqual(["clerical", "supervisor", "stall"]);
|
||||||
|
expect(screensFor(["shop:03:worker"])).toEqual(["stall"]);
|
||||||
|
expect(screensFor(["warehouse_supervisor", "qc"])).toEqual(["warehouse", "qc"]);
|
||||||
|
expect(screensFor(["admin"])).toHaveLength(7);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("lands on the first non-admin screen", () => {
|
||||||
|
expect(firstScreen(["admin", "clerical"])).toBe("clerical");
|
||||||
|
expect(firstScreen(["admin"])).toBe("admin");
|
||||||
|
expect(homePath(["stall", "supervisor"])).toBe("/supervisor");
|
||||||
|
expect(homePath([])).toBe("/account");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("builds role strings from kinds and picks chip colours", () => {
|
||||||
|
expect(roleFromKind("shop_lead", "03")).toBe("shop:03:lead");
|
||||||
|
expect(roleFromKind("qc_supervisor", "QC")).toBe("qc_supervisor");
|
||||||
|
expect(roleChipClass("shop:03:supervisor")).toBe("rchip supervisor");
|
||||||
|
expect(roleChipClass("admin")).toBe("rchip admin");
|
||||||
|
expect(roleChipClass("clerical")).toBe("rchip");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
// Role strings, the static role-to-screen map and the labels.
|
||||||
|
// The server decides access on every request. This file only shapes the screens.
|
||||||
|
import type { Department } from "./types";
|
||||||
|
|
||||||
|
/** Screens in the order the role switcher shows them (the old build's order). */
|
||||||
|
export const SCREENS = ["clerical", "warehouse", "supervisor", "stall", "qc", "pm", "admin"] as const;
|
||||||
|
export type Screen = (typeof SCREENS)[number];
|
||||||
|
|
||||||
|
export const SCREEN_LABELS: Record<Screen, string> = {
|
||||||
|
clerical: "Clerical",
|
||||||
|
warehouse: "Warehouse",
|
||||||
|
supervisor: "Supervisor",
|
||||||
|
stall: "Weld Stall",
|
||||||
|
qc: "Q.C.",
|
||||||
|
pm: "Project Mgmt",
|
||||||
|
admin: "Admin",
|
||||||
|
};
|
||||||
|
|
||||||
|
/** The phase in which each placeholder screen gets its real content. */
|
||||||
|
export const SCREEN_PHASE: Record<Exclude<Screen, "admin">, number> = {
|
||||||
|
clerical: 2,
|
||||||
|
warehouse: 4,
|
||||||
|
supervisor: 5,
|
||||||
|
stall: 5,
|
||||||
|
qc: 6,
|
||||||
|
pm: 8,
|
||||||
|
};
|
||||||
|
|
||||||
|
export function isScreen(s: string | undefined): s is Screen {
|
||||||
|
return s !== undefined && (SCREENS as readonly string[]).includes(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ShopLevel = "worker" | "lead" | "supervisor";
|
||||||
|
|
||||||
|
export type ParsedRole =
|
||||||
|
| { shop: false; kind: string }
|
||||||
|
| { shop: true; dept: string; level: ShopLevel };
|
||||||
|
|
||||||
|
const SHOP_LEVELS: readonly ShopLevel[] = ["worker", "lead", "supervisor"];
|
||||||
|
|
||||||
|
/** "shop:03:supervisor" -> shop role; anything else is an office role kind. */
|
||||||
|
export function parseRole(role: string): ParsedRole {
|
||||||
|
const m = /^shop:([^:]+):(worker|lead|supervisor)$/.exec(role);
|
||||||
|
if (m && m[1] !== undefined && m[2] !== undefined) {
|
||||||
|
return { shop: true, dept: m[1], level: m[2] as ShopLevel };
|
||||||
|
}
|
||||||
|
return { shop: false, kind: role };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Turns a role kind and department ("shop_lead", "03") into the role string ("shop:03:lead"). */
|
||||||
|
export function roleFromKind(kind: string, dept: string | null): string {
|
||||||
|
if (kind.includes(":")) return kind;
|
||||||
|
const m = /^shop_(worker|lead|supervisor)$/.exec(kind);
|
||||||
|
if (m && m[1] && dept) return `shop:${dept}:${m[1]}`;
|
||||||
|
return kind;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The static map. Same rule as the server's screens_for(roles). */
|
||||||
|
export function screensFor(roles: readonly string[]): Screen[] {
|
||||||
|
const out = new Set<Screen>();
|
||||||
|
for (const r of roles) {
|
||||||
|
const p = parseRole(r);
|
||||||
|
if (p.shop) {
|
||||||
|
out.add("stall");
|
||||||
|
if (p.level !== "worker") out.add("supervisor");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (p.kind === "clerical" || p.kind === "clerical_supervisor") out.add("clerical");
|
||||||
|
else if (p.kind.startsWith("warehouse")) out.add("warehouse");
|
||||||
|
else if (p.kind.startsWith("qc")) out.add("qc");
|
||||||
|
else if (p.kind === "pm") out.add("pm");
|
||||||
|
else if (p.kind === "admin") SCREENS.forEach((s) => out.add(s));
|
||||||
|
}
|
||||||
|
return SCREENS.filter((s) => out.has(s));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Known screens from a server list, in switcher order. */
|
||||||
|
export function orderScreens(list: readonly string[]): Screen[] {
|
||||||
|
return SCREENS.filter((s) => list.includes(s));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The screen a user lands on: the first non-admin screen, else admin, else null. */
|
||||||
|
export function firstScreen(list: readonly string[]): Screen | null {
|
||||||
|
const ordered = orderScreens(list);
|
||||||
|
return ordered.find((s) => s !== "admin") ?? ordered[0] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function homePath(list: readonly string[]): string {
|
||||||
|
const s = firstScreen(list);
|
||||||
|
return s ? `/${s}` : "/account";
|
||||||
|
}
|
||||||
|
|
||||||
|
const OFFICE_LABELS: Record<string, string> = {
|
||||||
|
admin: "Admin",
|
||||||
|
clerical: "Clerical",
|
||||||
|
clerical_supervisor: "Clerical supervisor",
|
||||||
|
warehouse: "Warehouse",
|
||||||
|
warehouse_supervisor: "Warehouse supervisor",
|
||||||
|
qc: "Q.C.",
|
||||||
|
qc_supervisor: "Q.C. supervisor",
|
||||||
|
pm: "Project Management",
|
||||||
|
};
|
||||||
|
|
||||||
|
const LEVEL_LABELS: Record<ShopLevel, string> = { worker: "Worker", lead: "Lead", supervisor: "Supervisor" };
|
||||||
|
|
||||||
|
/** "shop:03:supervisor" -> "03 Weld Parts · Supervisor". Office roles get their plain name. */
|
||||||
|
export function roleLabel(role: string, departments: readonly Department[] = []): string {
|
||||||
|
const p = parseRole(role);
|
||||||
|
if (!p.shop) return OFFICE_LABELS[p.kind] ?? p.kind;
|
||||||
|
const dept = departments.find((d) => d.code === p.dept);
|
||||||
|
const where = dept ? `${p.dept} ${dept.name}` : p.dept;
|
||||||
|
return `${where} · ${LEVEL_LABELS[p.level]}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The .rchip variant for a role: supervisors pink, leads green, admin amber. */
|
||||||
|
export function roleChipClass(role: string): string {
|
||||||
|
const p = parseRole(role);
|
||||||
|
if (p.shop) return p.level === "worker" ? "rchip" : `rchip ${p.level}`;
|
||||||
|
if (p.kind === "admin") return "rchip admin";
|
||||||
|
if (p.kind.endsWith("_supervisor")) return "rchip supervisor";
|
||||||
|
return "rchip";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Office roles first in a fixed order, then shop roles by department and level. */
|
||||||
|
export function sortRoles(roles: readonly string[]): string[] {
|
||||||
|
const office = Object.keys(OFFICE_LABELS);
|
||||||
|
const rank = (r: string): [number, string, number] => {
|
||||||
|
const p = parseRole(r);
|
||||||
|
if (!p.shop) return [0, "", office.includes(p.kind) ? office.indexOf(p.kind) : office.length];
|
||||||
|
return [1, p.dept, SHOP_LEVELS.indexOf(p.level)];
|
||||||
|
};
|
||||||
|
return [...roles].sort((a, b) => {
|
||||||
|
const [a0, a1, a2] = rank(a);
|
||||||
|
const [b0, b1, b2] = rank(b);
|
||||||
|
return a0 - b0 || a1.localeCompare(b1) || a2 - b2;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,193 @@
|
|||||||
|
// API shapes from the phase 1 design contract. IDs stay text. Timestamps are ISO strings.
|
||||||
|
|
||||||
|
export type SessionKind = "password" | "pin";
|
||||||
|
export type Factor = "password" | "pin";
|
||||||
|
|
||||||
|
export interface DeviceRef {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UserInfo {
|
||||||
|
id: string;
|
||||||
|
sam_account: string;
|
||||||
|
upn: string | null;
|
||||||
|
display_name: string;
|
||||||
|
emp_no: string | null;
|
||||||
|
email: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PinState {
|
||||||
|
set: boolean;
|
||||||
|
disabled: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SessionInfo {
|
||||||
|
id: string;
|
||||||
|
kind: SessionKind;
|
||||||
|
created_at: string;
|
||||||
|
expires_at: string;
|
||||||
|
locked: boolean;
|
||||||
|
locked_since: string | null;
|
||||||
|
device: DeviceRef | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** GET /api/auth/me and every sign-in or unlock answer. */
|
||||||
|
export interface Me {
|
||||||
|
user: UserInfo;
|
||||||
|
roles: string[];
|
||||||
|
screens: string[];
|
||||||
|
groups: string[];
|
||||||
|
session: SessionInfo;
|
||||||
|
pin: PinState;
|
||||||
|
can_register_device: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** GET /api/auth/context. No session needed. */
|
||||||
|
export interface AuthContextInfo {
|
||||||
|
device: DeviceRef | null;
|
||||||
|
stack: string;
|
||||||
|
insecure_ldap: boolean;
|
||||||
|
pin_digits: { min: number; max: number };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** GET /api/account. */
|
||||||
|
export interface AccountInfo {
|
||||||
|
user: UserInfo;
|
||||||
|
groups: string[];
|
||||||
|
roles: string[];
|
||||||
|
pin: PinState;
|
||||||
|
ad_synced_at: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One row of GET /api/account/sessions. Admin user detail uses the same shape. */
|
||||||
|
export interface SessionRow {
|
||||||
|
id: string;
|
||||||
|
kind: SessionKind;
|
||||||
|
created_at: string;
|
||||||
|
last_seen_at: string;
|
||||||
|
ip: string | null;
|
||||||
|
user_agent: string | null;
|
||||||
|
device: DeviceRef | null;
|
||||||
|
current?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One row of GET /api/account/access-log. */
|
||||||
|
export interface AccessLogRow {
|
||||||
|
at: string;
|
||||||
|
action: string;
|
||||||
|
detail: unknown;
|
||||||
|
ip: string | null;
|
||||||
|
ok: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UserFlags {
|
||||||
|
emp_missing: boolean;
|
||||||
|
emp_duplicate: boolean;
|
||||||
|
disabled: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One row of GET /api/admin/users. */
|
||||||
|
export interface AdminUser {
|
||||||
|
id: string;
|
||||||
|
sam_account: string;
|
||||||
|
display_name: string;
|
||||||
|
emp_no: string | null;
|
||||||
|
email: string | null;
|
||||||
|
active: boolean;
|
||||||
|
roles: string[];
|
||||||
|
pin: PinState;
|
||||||
|
flags: UserFlags;
|
||||||
|
last_signin_at: string | null;
|
||||||
|
ad_synced_at: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** GET /api/admin/users/{id}. */
|
||||||
|
export interface AdminUserDetail extends AdminUser {
|
||||||
|
groups: string[];
|
||||||
|
/** "cache" when AD was unreachable. Absent or "live" otherwise. */
|
||||||
|
groups_source?: string;
|
||||||
|
sessions: SessionRow[];
|
||||||
|
note: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** GET /api/admin/ad/lookup. */
|
||||||
|
export interface AdLookup {
|
||||||
|
found: boolean;
|
||||||
|
user?: Partial<UserInfo> | null;
|
||||||
|
groups?: string[];
|
||||||
|
roles?: string[];
|
||||||
|
disabled?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One row of GET /api/admin/devices. */
|
||||||
|
export interface AdminDevice {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
registered_by: { id: string; display_name: string } | null;
|
||||||
|
registered_at: string | null;
|
||||||
|
last_seen_at: string | null;
|
||||||
|
revoked_at: string | null;
|
||||||
|
active_sessions: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GroupRow {
|
||||||
|
name: string;
|
||||||
|
/** A role kind ("shop_supervisor") or a role string ("shop:03:supervisor"). Both are handled. */
|
||||||
|
role: string;
|
||||||
|
dept_code: string | null;
|
||||||
|
in_ad: boolean | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** GET /api/admin/groups. */
|
||||||
|
export interface GroupMap {
|
||||||
|
checked_at: string | null;
|
||||||
|
ad_reachable: boolean;
|
||||||
|
groups: GroupRow[];
|
||||||
|
extra_in_ou: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** POST /api/admin/ad/refresh. */
|
||||||
|
export interface AdRefreshResult {
|
||||||
|
groups_checked: number;
|
||||||
|
groups_missing: string[];
|
||||||
|
users_seen: number;
|
||||||
|
created: number;
|
||||||
|
updated: number;
|
||||||
|
deactivated: number;
|
||||||
|
emp_missing: string[];
|
||||||
|
emp_duplicate: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One row of GET /api/admin/signin-attempts. The contract does not list the fields.
|
||||||
|
* These are the signin_attempts columns.
|
||||||
|
*/
|
||||||
|
export interface SigninAttempt {
|
||||||
|
id?: number | string;
|
||||||
|
at: string;
|
||||||
|
account: string;
|
||||||
|
ip: string | null;
|
||||||
|
kind: string;
|
||||||
|
ok: boolean;
|
||||||
|
reason: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stations may come as names or as rows. */
|
||||||
|
export type StationEntry = string | { name: string; active?: boolean };
|
||||||
|
|
||||||
|
/** One row of GET /api/departments. */
|
||||||
|
export interface Department {
|
||||||
|
code: string;
|
||||||
|
slug: string;
|
||||||
|
name: string;
|
||||||
|
kind: "support" | "shop";
|
||||||
|
stations: StationEntry[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Payload of an SSE `presence` event. */
|
||||||
|
export interface PresenceUser {
|
||||||
|
user_id: string;
|
||||||
|
display_name: string;
|
||||||
|
screen: string | null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { useContext } from "react";
|
||||||
|
import { AuthCtx, type AuthState } from "./context";
|
||||||
|
|
||||||
|
/** The auth state. Must be used under AuthProvider. */
|
||||||
|
export function useAuth(): AuthState {
|
||||||
|
const ctx = useContext(AuthCtx);
|
||||||
|
if (!ctx) throw new Error("useAuth must be used inside AuthProvider");
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
import type { PresenceUser } from "./types";
|
||||||
|
|
||||||
|
interface EventHandlers {
|
||||||
|
/** Called when the server revokes this browser's own session. */
|
||||||
|
onRevoked: () => void;
|
||||||
|
/** Called for every `changed` event. Later phases refresh their data from it. */
|
||||||
|
onChanged?: (payload: unknown) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parse(data: unknown): unknown {
|
||||||
|
if (typeof data !== "string") return null;
|
||||||
|
try {
|
||||||
|
return JSON.parse(data) as unknown;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Opens /api/events with EventSource while `sessionId` is set.
|
||||||
|
* A `session` event with this session id and action "revoked" calls onRevoked.
|
||||||
|
* `presence` is kept in state for later phases.
|
||||||
|
*/
|
||||||
|
export function useEvents(sessionId: string | null, handlers: EventHandlers): PresenceUser[] {
|
||||||
|
const [presence, setPresence] = useState<PresenceUser[]>([]);
|
||||||
|
const ref = useRef(handlers);
|
||||||
|
useEffect(() => {
|
||||||
|
ref.current = handlers;
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!sessionId || typeof EventSource === "undefined") return;
|
||||||
|
const es = new EventSource("/api/events", { withCredentials: true });
|
||||||
|
|
||||||
|
es.addEventListener("session", (ev) => {
|
||||||
|
const p = parse((ev as MessageEvent).data);
|
||||||
|
if (p && typeof p === "object") {
|
||||||
|
const o = p as { session_id?: unknown; action?: unknown };
|
||||||
|
if (o.session_id === sessionId && o.action === "revoked") ref.current.onRevoked();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
es.addEventListener("presence", (ev) => {
|
||||||
|
const p = parse((ev as MessageEvent).data);
|
||||||
|
if (p && typeof p === "object" && Array.isArray((p as { users?: unknown }).users)) {
|
||||||
|
setPresence((p as { users: PresenceUser[] }).users);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
es.addEventListener("changed", (ev) => {
|
||||||
|
ref.current.onChanged?.(parse((ev as MessageEvent).data));
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
es.close();
|
||||||
|
setPresence([]);
|
||||||
|
};
|
||||||
|
}, [sessionId]);
|
||||||
|
|
||||||
|
return presence;
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import type { KeypadKey } from "../lib/keypad";
|
||||||
|
|
||||||
|
const KEYS: ReadonlyArray<{ key: KeypadKey; text: string; label: string }> = [
|
||||||
|
...(["1", "2", "3", "4", "5", "6", "7", "8", "9"] as const).map((d) => ({ key: d, text: d, label: `Digit ${d}` })),
|
||||||
|
{ key: "clear", text: "Clear", label: "Clear" },
|
||||||
|
{ key: "0", text: "0", label: "Digit 0" },
|
||||||
|
{ key: "back", text: "Back", label: "Back" },
|
||||||
|
];
|
||||||
|
|
||||||
|
interface KeypadProps {
|
||||||
|
onKey: (key: KeypadKey) => void;
|
||||||
|
disabled?: boolean;
|
||||||
|
label?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** On-screen keypad. Pressing a key keeps the focus in the field that had it. */
|
||||||
|
export function Keypad({ onKey, disabled = false, label = "Keypad" }: KeypadProps) {
|
||||||
|
return (
|
||||||
|
<div className="keypad" role="group" aria-label={label}>
|
||||||
|
{KEYS.map((k) => (
|
||||||
|
<button
|
||||||
|
key={k.key}
|
||||||
|
type="button"
|
||||||
|
aria-label={k.label}
|
||||||
|
disabled={disabled}
|
||||||
|
onMouseDown={(e) => e.preventDefault()}
|
||||||
|
onClick={() => onKey(k.key)}
|
||||||
|
>
|
||||||
|
{k.text}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,16 +1,59 @@
|
|||||||
import { Outlet } from "react-router";
|
import { useEffect, useRef } from "react";
|
||||||
|
import { Link, Outlet, useLocation } from "react-router";
|
||||||
|
import { SCREEN_LABELS, firstScreen, isScreen, orderScreens, type Screen } from "../auth/roles";
|
||||||
|
import { useAuth } from "../auth/useAuth";
|
||||||
|
import { LockScreen } from "./LockScreen";
|
||||||
|
import { RoleSwitcher } from "./RoleSwitcher";
|
||||||
import { TopBar } from "./TopBar";
|
import { TopBar } from "./TopBar";
|
||||||
|
|
||||||
/** Page frame: the top bar, then the routed page inside main.wrap. */
|
function chipClass(s: Screen): string {
|
||||||
|
if (s === "admin") return "rchip admin";
|
||||||
|
if (s === "supervisor") return "rchip supervisor";
|
||||||
|
return "rchip";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Page frame: the top bar, then the routed page inside main.wrap, and the lock screen over both. */
|
||||||
export function Layout() {
|
export function Layout() {
|
||||||
|
const auth = useAuth();
|
||||||
|
const { pathname } = useLocation();
|
||||||
|
const mainRef = useRef<HTMLElement>(null);
|
||||||
|
const locked = auth.status === "locked";
|
||||||
|
const me = auth.status === "ready" || locked ? auth.me : null;
|
||||||
|
|
||||||
|
const screens = me ? orderScreens(me.screens) : [];
|
||||||
|
const seg = pathname.split("/")[1];
|
||||||
|
const active = isScreen(seg) && screens.includes(seg) ? seg : null;
|
||||||
|
const shown = active ?? firstScreen(screens);
|
||||||
|
|
||||||
|
// Keep the page mounted behind the lock, but out of reach of the keyboard and screen readers.
|
||||||
|
useEffect(() => {
|
||||||
|
mainRef.current?.toggleAttribute("inert", locked);
|
||||||
|
}, [locked]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<TopBar>
|
<TopBar nav={me && !locked ? <RoleSwitcher screens={screens} active={active} /> : null}>
|
||||||
<span className="proto">Rebuild preview</span>
|
{me ? (
|
||||||
|
<>
|
||||||
|
<b className="uname">{me.user.display_name}</b>
|
||||||
|
{shown ? <span className={chipClass(shown)}>{SCREEN_LABELS[shown]}</span> : null}
|
||||||
|
<Link className="btn sm ghost" to="/account">
|
||||||
|
Account
|
||||||
|
</Link>
|
||||||
|
<button className="btn sm ghost" type="button" onClick={() => void auth.signOut()}>
|
||||||
|
Sign out
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<span className="proto">Rebuild preview</span>
|
||||||
|
)}
|
||||||
</TopBar>
|
</TopBar>
|
||||||
<main className="wrap" id="main">
|
<div className={locked ? "blur-hidden" : undefined}>
|
||||||
<Outlet />
|
<main className="wrap" id="main" ref={mainRef} aria-hidden={locked ? true : undefined}>
|
||||||
</main>
|
<Outlet />
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
{locked ? <LockScreen key={auth.me?.user.id ?? "unknown"} /> : null}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,127 @@
|
|||||||
|
import { useEffect, useRef, useState, type FormEvent } from "react";
|
||||||
|
import { errorCode } from "../api/client";
|
||||||
|
import { useAuth } from "../auth/useAuth";
|
||||||
|
import type { Factor } from "../auth/types";
|
||||||
|
import { errorText } from "../lib/format";
|
||||||
|
import { applyKey, type KeypadKey } from "../lib/keypad";
|
||||||
|
import { Keypad } from "./Keypad";
|
||||||
|
|
||||||
|
const PIN_MAX = 12;
|
||||||
|
|
||||||
|
/** Full-screen lock. The page stays mounted behind it, blurred and inert. */
|
||||||
|
export function LockScreen() {
|
||||||
|
const auth = useAuth();
|
||||||
|
const me = auth.me;
|
||||||
|
// Without Me (a 423 before /me answered) the PIN state is unknown, so start on the password.
|
||||||
|
const hasPin = me ? me.pin.set && !me.pin.disabled : false;
|
||||||
|
const [factor, setFactor] = useState<Factor>(hasPin ? "pin" : "password");
|
||||||
|
const [secret, setSecret] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [missed, setMissed] = useState(false);
|
||||||
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
inputRef.current?.focus();
|
||||||
|
}, [factor]);
|
||||||
|
|
||||||
|
const switchTo = (f: Factor) => {
|
||||||
|
setFactor(f);
|
||||||
|
setSecret("");
|
||||||
|
setError(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
const submit = async (e: FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!secret) return;
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
await auth.unlock(factor, secret);
|
||||||
|
} catch (err) {
|
||||||
|
if (errorCode(err) === "session_ended") {
|
||||||
|
// The provider has signed out through the 401 listener. Make sure, with the server's words.
|
||||||
|
auth.endSession(errorText(err));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setError(errorText(err));
|
||||||
|
setMissed(true);
|
||||||
|
setSecret("");
|
||||||
|
setBusy(false);
|
||||||
|
inputRef.current?.focus();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const onKey = (k: KeypadKey) => setSecret((v) => applyKey(v, k, PIN_MAX));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="scrim lock" role="dialog" aria-modal="true" aria-labelledby="lock-title">
|
||||||
|
<div className="auth-card">
|
||||||
|
<div>
|
||||||
|
<div className="eyebrow">Locked</div>
|
||||||
|
<h1 id="lock-title">{me ? me.user.display_name : "Screen locked"}</h1>
|
||||||
|
</div>
|
||||||
|
<div className="small muted">
|
||||||
|
{factor === "pin" ? "Enter your PIN to continue, or sign out." : "Enter your password to continue, or sign out."}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error ? (
|
||||||
|
<div className="callout warn flush" role="alert">
|
||||||
|
{error}
|
||||||
|
{missed ? <div className="small">Three wrong attempts end the session.</div> : null}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<form className="auth-form" onSubmit={submit} noValidate autoComplete="off">
|
||||||
|
{factor === "pin" ? (
|
||||||
|
<>
|
||||||
|
<label className="f">
|
||||||
|
PIN
|
||||||
|
<input
|
||||||
|
ref={inputRef}
|
||||||
|
className="in big"
|
||||||
|
name="unlock-pin"
|
||||||
|
type="password"
|
||||||
|
inputMode="numeric"
|
||||||
|
autoComplete="off"
|
||||||
|
maxLength={PIN_MAX}
|
||||||
|
value={secret}
|
||||||
|
onChange={(e) => setSecret(e.target.value.replace(/\D/g, "").slice(0, PIN_MAX))}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<Keypad onKey={onKey} disabled={busy} label="Keypad, PIN" />
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<label className="f">
|
||||||
|
Password
|
||||||
|
<input
|
||||||
|
ref={inputRef}
|
||||||
|
className="in"
|
||||||
|
name="unlock-password"
|
||||||
|
type="password"
|
||||||
|
autoComplete="current-password"
|
||||||
|
value={secret}
|
||||||
|
onChange={(e) => setSecret(e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
<button className="btn pri wide" type="submit" disabled={busy || !secret}>
|
||||||
|
{busy ? "Checking" : "Unlock"}
|
||||||
|
</button>
|
||||||
|
{factor === "pin" ? (
|
||||||
|
<button className="lnk small center" type="button" onClick={() => switchTo("password")}>
|
||||||
|
Use your password instead
|
||||||
|
</button>
|
||||||
|
) : hasPin || !me ? (
|
||||||
|
<button className="lnk small center" type="button" onClick={() => switchTo("pin")}>
|
||||||
|
Use your PIN instead
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
<button className="btn ghost" type="button" onClick={() => void auth.signOut()}>
|
||||||
|
Sign out
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { Navigate, Outlet } from "react-router";
|
||||||
|
import { useAuth } from "../auth/useAuth";
|
||||||
|
|
||||||
|
/** Routes below need a session. Signed out goes to /signin. A locked session stays, under the lock screen. */
|
||||||
|
export function RequireAuth() {
|
||||||
|
const { status } = useAuth();
|
||||||
|
if (status === "loading") return <div className="empty">Loading</div>;
|
||||||
|
if (status === "anonymous") return <Navigate to="/signin" replace />;
|
||||||
|
return <Outlet />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { useNavigate } from "react-router";
|
||||||
|
import { SCREEN_LABELS, type Screen } from "../auth/roles";
|
||||||
|
|
||||||
|
interface RoleSwitcherProps {
|
||||||
|
screens: readonly Screen[];
|
||||||
|
active: Screen | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One button per screen the user has. Drawn only when there is more than one. */
|
||||||
|
export function RoleSwitcher({ screens, active }: RoleSwitcherProps) {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
if (screens.length < 2) return null;
|
||||||
|
return (
|
||||||
|
<nav className="roles" aria-label="Screens">
|
||||||
|
{screens.map((s) => (
|
||||||
|
<button key={s} type="button" aria-pressed={active === s} onClick={() => navigate(`/${s}`)}>
|
||||||
|
{SCREEN_LABELS[s]}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -3,12 +3,14 @@ import { Link } from "react-router";
|
|||||||
import logo from "../assets/logo.png";
|
import logo from "../assets/logo.png";
|
||||||
|
|
||||||
interface TopBarProps {
|
interface TopBarProps {
|
||||||
/** Right-hand side: the signed-in user, role switcher and so on. */
|
/** The role switcher, drawn between the brand and the spacer. */
|
||||||
|
nav?: ReactNode;
|
||||||
|
/** Right-hand side: the signed-in user, the role chip, Account and Sign out. */
|
||||||
children?: ReactNode;
|
children?: ReactNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Sticky shop header. Same markup classes as the old page's header.top. */
|
/** Sticky shop header. Same markup classes as the old page's header.top. */
|
||||||
export function TopBar({ children }: TopBarProps) {
|
export function TopBar({ nav, children }: TopBarProps) {
|
||||||
return (
|
return (
|
||||||
<header className="top">
|
<header className="top">
|
||||||
<div className="top-in">
|
<div className="top-in">
|
||||||
@@ -18,6 +20,7 @@ export function TopBar({ children }: TopBarProps) {
|
|||||||
Packet <span>Station</span>
|
Packet <span>Station</span>
|
||||||
</div>
|
</div>
|
||||||
</Link>
|
</Link>
|
||||||
|
{nav}
|
||||||
<div className="sp" />
|
<div className="sp" />
|
||||||
{children ? <div className="who">{children}</div> : null}
|
{children ? <div className="who">{children}</div> : null}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import { ApiError, retryAfter } from "../api/client";
|
||||||
|
|
||||||
|
/** A short local date and time, or a dash. */
|
||||||
|
export function fmtTime(iso: string | null | undefined): string {
|
||||||
|
if (!iso) return "-";
|
||||||
|
const d = new Date(iso);
|
||||||
|
if (Number.isNaN(d.getTime())) return iso;
|
||||||
|
return d.toLocaleString(undefined, {
|
||||||
|
year: "numeric",
|
||||||
|
month: "short",
|
||||||
|
day: "numeric",
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An audit detail dict as "key: value, key: value". Never shows nested objects in full. */
|
||||||
|
export function fmtDetail(detail: unknown): string {
|
||||||
|
if (detail === null || detail === undefined) return "";
|
||||||
|
if (typeof detail !== "object") return String(detail);
|
||||||
|
return Object.entries(detail as Record<string, unknown>)
|
||||||
|
.filter(([, v]) => v !== null && v !== undefined && v !== "")
|
||||||
|
.map(([k, v]) => `${k.replace(/_/g, " ")}: ${typeof v === "object" ? JSON.stringify(v) : String(v)}`)
|
||||||
|
.join(", ");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "Try again in N minutes." from a 429, rounded up, at least one. */
|
||||||
|
export function retryText(err: unknown): string {
|
||||||
|
const secs = retryAfter(err) ?? 60;
|
||||||
|
const mins = Math.max(1, Math.ceil(secs / 60));
|
||||||
|
return `Try again in ${mins} ${mins === 1 ? "minute" : "minutes"}.`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The message to show for a failed call. 429 adds the retry time. */
|
||||||
|
export function errorText(err: unknown): string {
|
||||||
|
if (err instanceof ApiError) {
|
||||||
|
if (err.status === 429) return `Too many failed attempts. ${retryText(err)}`;
|
||||||
|
return err.message;
|
||||||
|
}
|
||||||
|
if (err instanceof Error) return err.message;
|
||||||
|
return "Something went wrong.";
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DIGITS = /^\d+$/;
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
// Keypad keys and how one press changes a field value.
|
||||||
|
export type KeypadKey = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "clear" | "back";
|
||||||
|
|
||||||
|
/** Applies one key press to a field value. Digits stop at `max` characters. */
|
||||||
|
export function applyKey(value: string, key: KeypadKey, max = 64): string {
|
||||||
|
if (key === "clear") return "";
|
||||||
|
if (key === "back") return value.slice(0, -1);
|
||||||
|
return value.length >= max ? value : value + key;
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { DIGITS } from "./format";
|
||||||
|
|
||||||
|
export const PIN_MIN = 6;
|
||||||
|
export const PIN_MAX = 12;
|
||||||
|
|
||||||
|
/** Checks a new PIN the way the server does. Returns the message to show, or null. */
|
||||||
|
export function pinProblem(pin: string, confirm: string, min = PIN_MIN, max = PIN_MAX): string | null {
|
||||||
|
if (!pin) return "Enter a new PIN.";
|
||||||
|
if (!DIGITS.test(pin)) return "The PIN must be digits only.";
|
||||||
|
if (pin.length < min || pin.length > max) return `The PIN must be ${min} to ${max} digits.`;
|
||||||
|
if (pin !== confirm) return "The two PINs do not match.";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import { useCallback, useEffect, useState } from "react";
|
||||||
|
import { errorText } from "./format";
|
||||||
|
|
||||||
|
export type Load<T> =
|
||||||
|
| { state: "loading" }
|
||||||
|
| { state: "ok"; data: T }
|
||||||
|
| { state: "error"; message: string };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs `fetcher` on mount and whenever `key` changes. `reload()` runs it again.
|
||||||
|
* Answers from an older run are dropped.
|
||||||
|
*/
|
||||||
|
export function useLoad<T>(fetcher: (signal: AbortSignal) => Promise<T>, key: string = ""): [Load<T>, () => void] {
|
||||||
|
const [load, setLoad] = useState<Load<T>>({ state: "loading" });
|
||||||
|
const [tick, setTick] = useState(0);
|
||||||
|
|
||||||
|
// The fetcher is read fresh on each run; callers pass inline arrows, and `key` says when to rerun.
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
const run = useCallback(fetcher, [key, tick]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const ctl = new AbortController();
|
||||||
|
run(ctl.signal)
|
||||||
|
.then((data) => {
|
||||||
|
if (!ctl.signal.aborted) setLoad({ state: "ok", data });
|
||||||
|
})
|
||||||
|
.catch((err: unknown) => {
|
||||||
|
if (!ctl.signal.aborted) setLoad({ state: "error", message: errorText(err) });
|
||||||
|
});
|
||||||
|
return () => ctl.abort();
|
||||||
|
}, [run]);
|
||||||
|
|
||||||
|
const reload = useCallback(() => setTick((t) => t + 1), []);
|
||||||
|
return [load, reload];
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { VersionStatus } from "../components/VersionStatus";
|
||||||
|
|
||||||
|
/** Build and API health. Open to anyone, so a broken sign-in can still be diagnosed. */
|
||||||
|
export function AboutPage() {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className="phead">
|
||||||
|
<div>
|
||||||
|
<div className="eyebrow">About</div>
|
||||||
|
<h1>Packet Station</h1>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<VersionStatus />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,25 +1,12 @@
|
|||||||
import { Link } from "react-router";
|
import { Navigate } from "react-router";
|
||||||
import { VersionStatus } from "../components/VersionStatus";
|
import { homePath } from "../auth/roles";
|
||||||
|
import { useAuth } from "../auth/useAuth";
|
||||||
|
|
||||||
/** Placeholder home. Shows the build and the API health until the real home lands in phase 2. */
|
/** "/" sends a signed-in user to their first screen, and everyone else to sign-in. */
|
||||||
export function HomePage() {
|
export function HomePage() {
|
||||||
return (
|
const { status, me } = useAuth();
|
||||||
<>
|
if (status === "loading") return <div className="empty">Loading</div>;
|
||||||
<div className="phead">
|
if (status === "anonymous") return <Navigate to="/signin" replace />;
|
||||||
<div>
|
if (!me) return null;
|
||||||
<div className="eyebrow">Phase 0 shell</div>
|
return <Navigate to={homePath(me.screens)} replace />;
|
||||||
<h1>Packet Station</h1>
|
|
||||||
</div>
|
|
||||||
<div className="pacts">
|
|
||||||
<Link className="btn pri" to="/signin">
|
|
||||||
Sign in
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<VersionStatus />
|
|
||||||
<div className="callout">
|
|
||||||
<b>Skeleton build.</b> Boards, packets and sign-in arrive in the next phases.
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +1,104 @@
|
|||||||
import { useState } from "react";
|
import { useEffect, useRef, useState, type FormEvent } from "react";
|
||||||
|
import { Link, Navigate, useNavigate } from "react-router";
|
||||||
|
import { authApi } from "../auth/api";
|
||||||
|
import { homePath } from "../auth/roles";
|
||||||
|
import type { AuthContextInfo } from "../auth/types";
|
||||||
|
import { useAuth } from "../auth/useAuth";
|
||||||
|
import { Keypad } from "../components/Keypad";
|
||||||
|
import { errorText } from "../lib/format";
|
||||||
|
import { applyKey, type KeypadKey } from "../lib/keypad";
|
||||||
|
|
||||||
type Mode = "password" | "pin";
|
type Mode = "password" | "pin";
|
||||||
|
type PinField = "emp" | "pin";
|
||||||
|
|
||||||
const TABS: ReadonlyArray<{ id: Mode; label: string }> = [
|
const PIN_MAX = 12;
|
||||||
{ id: "password", label: "Domain password" },
|
|
||||||
{ id: "pin", label: "PIN" },
|
|
||||||
];
|
|
||||||
|
|
||||||
const KEYS = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "Clear", "0", "Back"] as const;
|
/** Sign-in. Domain password everywhere. Employee ID and PIN only on a registered device. */
|
||||||
|
|
||||||
/** Placeholder sign-in. Both tabs are drawn, every input is disabled until phase 1 wires the server. */
|
|
||||||
export function SignInPage() {
|
export function SignInPage() {
|
||||||
|
const auth = useAuth();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const [context, setContext] = useState<AuthContextInfo | null>(null);
|
||||||
const [mode, setMode] = useState<Mode>("password");
|
const [mode, setMode] = useState<Mode>("password");
|
||||||
|
const [login, setLogin] = useState("");
|
||||||
|
const [password, setPassword] = useState("");
|
||||||
|
const [emp, setEmp] = useState("");
|
||||||
|
const [pin, setPin] = useState("");
|
||||||
|
const [field, setField] = useState<PinField>("emp");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const empRef = useRef<HTMLInputElement>(null);
|
||||||
|
const pinRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const ctl = new AbortController();
|
||||||
|
authApi
|
||||||
|
.context(ctl.signal)
|
||||||
|
.then((c) => {
|
||||||
|
if (ctl.signal.aborted) return;
|
||||||
|
setContext(c);
|
||||||
|
// A registered shop device starts on the PIN tab.
|
||||||
|
if (c.device) setMode("pin");
|
||||||
|
})
|
||||||
|
.catch(() => undefined);
|
||||||
|
return () => ctl.abort();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
if (auth.status === "loading") return <div className="empty">Loading</div>;
|
||||||
|
if (auth.status === "ready" || auth.status === "locked") {
|
||||||
|
return <Navigate to={homePath(auth.me?.screens ?? [])} replace />;
|
||||||
|
}
|
||||||
|
|
||||||
|
const device = context?.device ?? null;
|
||||||
|
const pinMax = context?.pin_digits.max ?? PIN_MAX;
|
||||||
|
const tabs: ReadonlyArray<{ id: Mode; label: string }> = device
|
||||||
|
? [
|
||||||
|
{ id: "password", label: "Domain password" },
|
||||||
|
{ id: "pin", label: "PIN" },
|
||||||
|
]
|
||||||
|
: [{ id: "password", label: "Domain password" }];
|
||||||
|
const active: Mode = device ? mode : "password";
|
||||||
|
|
||||||
|
const run = async (call: () => Promise<{ screens: string[] }>) => {
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const me = await call();
|
||||||
|
navigate(homePath(me.screens), { replace: true });
|
||||||
|
} catch (err) {
|
||||||
|
setError(errorText(err));
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const submitPassword = (e: FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!login.trim() || !password) {
|
||||||
|
setError("Enter your user name and password.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
void run(() => auth.signInPassword(login.trim(), password));
|
||||||
|
};
|
||||||
|
|
||||||
|
const submitPin = (e: FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!emp.trim()) {
|
||||||
|
setError("Enter your employee ID.");
|
||||||
|
setField("emp");
|
||||||
|
empRef.current?.focus();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!pin) {
|
||||||
|
setField("pin");
|
||||||
|
pinRef.current?.focus();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
void run(() => auth.signInPin(emp.trim(), pin));
|
||||||
|
};
|
||||||
|
|
||||||
|
const onKey = (k: KeypadKey) => {
|
||||||
|
if (field === "emp") setEmp((v) => applyKey(v, k, 32));
|
||||||
|
else setPin((v) => applyKey(v, k, pinMax));
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="auth">
|
<div className="auth">
|
||||||
@@ -21,62 +108,104 @@ export function SignInPage() {
|
|||||||
<h1>Sign in</h1>
|
<h1>Sign in</h1>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{auth.notice ? <div className="callout warn flush">{auth.notice}</div> : null}
|
||||||
|
|
||||||
<div className="tabs static" role="tablist" aria-label="Sign-in method">
|
<div className="tabs static" role="tablist" aria-label="Sign-in method">
|
||||||
{TABS.map((t) => (
|
{tabs.map((t) => (
|
||||||
<button
|
<button
|
||||||
key={t.id}
|
key={t.id}
|
||||||
type="button"
|
type="button"
|
||||||
role="tab"
|
role="tab"
|
||||||
id={`tab-${t.id}`}
|
id={`tab-${t.id}`}
|
||||||
aria-selected={mode === t.id}
|
aria-selected={active === t.id}
|
||||||
aria-controls={`panel-${t.id}`}
|
aria-controls={`panel-${t.id}`}
|
||||||
onClick={() => setMode(t.id)}
|
onClick={() => {
|
||||||
|
setMode(t.id);
|
||||||
|
setError(null);
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
{t.label}
|
{t.label}
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="callout">
|
{error ? (
|
||||||
Sign-in arrives in <b>phase 1</b>. The fields below are disabled.
|
<div className="callout warn flush" role="alert">
|
||||||
</div>
|
{error}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
{mode === "password" ? (
|
{active === "password" ? (
|
||||||
<form className="auth-form" id="panel-password" role="tabpanel" aria-labelledby="tab-password" onSubmit={(e) => e.preventDefault()}>
|
<form className="auth-form" id="panel-password" role="tabpanel" aria-labelledby="tab-password" onSubmit={submitPassword} noValidate>
|
||||||
<label className="f">
|
<label className="f">
|
||||||
User name
|
User name
|
||||||
<input className="in" name="username" autoComplete="username" disabled />
|
<input
|
||||||
|
className="in"
|
||||||
|
name="username"
|
||||||
|
autoComplete="username"
|
||||||
|
autoCapitalize="none"
|
||||||
|
spellCheck={false}
|
||||||
|
value={login}
|
||||||
|
onChange={(e) => setLogin(e.target.value)}
|
||||||
|
/>
|
||||||
</label>
|
</label>
|
||||||
<label className="f">
|
<label className="f">
|
||||||
Password
|
Password
|
||||||
<input className="in" name="password" type="password" autoComplete="current-password" disabled />
|
<input
|
||||||
|
className="in"
|
||||||
|
name="password"
|
||||||
|
type="password"
|
||||||
|
autoComplete="current-password"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
/>
|
||||||
</label>
|
</label>
|
||||||
<button className="btn pri" type="submit" disabled>
|
<button className="btn pri wide" type="submit" disabled={busy}>
|
||||||
Sign in
|
{busy ? "Checking" : "Sign in"}
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
) : (
|
) : (
|
||||||
<form className="auth-form" id="panel-pin" role="tabpanel" aria-labelledby="tab-pin" onSubmit={(e) => e.preventDefault()}>
|
<form className="auth-form" id="panel-pin" role="tabpanel" aria-labelledby="tab-pin" onSubmit={submitPin} noValidate autoComplete="off">
|
||||||
|
{device ? <div className="small muted">This device: {device.name}</div> : null}
|
||||||
<label className="f">
|
<label className="f">
|
||||||
Employee ID
|
Employee ID
|
||||||
<input className="in" name="employee" inputMode="numeric" disabled />
|
<input
|
||||||
|
ref={empRef}
|
||||||
|
className="in big"
|
||||||
|
name="employee"
|
||||||
|
inputMode="numeric"
|
||||||
|
autoComplete="off"
|
||||||
|
spellCheck={false}
|
||||||
|
value={emp}
|
||||||
|
onFocus={() => setField("emp")}
|
||||||
|
onChange={(e) => setEmp(e.target.value.trim())}
|
||||||
|
/>
|
||||||
</label>
|
</label>
|
||||||
<label className="f">
|
<label className="f">
|
||||||
PIN
|
PIN
|
||||||
<input className="in big" name="pin" type="password" inputMode="numeric" disabled />
|
<input
|
||||||
|
ref={pinRef}
|
||||||
|
className="in big"
|
||||||
|
name="pin"
|
||||||
|
type="password"
|
||||||
|
inputMode="numeric"
|
||||||
|
autoComplete="off"
|
||||||
|
maxLength={pinMax}
|
||||||
|
value={pin}
|
||||||
|
onFocus={() => setField("pin")}
|
||||||
|
onChange={(e) => setPin(e.target.value.replace(/\D/g, "").slice(0, pinMax))}
|
||||||
|
/>
|
||||||
</label>
|
</label>
|
||||||
<div className="keypad" aria-label="PIN keypad">
|
<Keypad onKey={onKey} disabled={busy} label={field === "emp" ? "Keypad, employee ID" : "Keypad, PIN"} />
|
||||||
{KEYS.map((k) => (
|
<button className="btn pri wide" type="submit" disabled={busy}>
|
||||||
<button key={k} type="button" disabled>
|
{busy ? "Checking" : "Sign in"}
|
||||||
{k}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
<button className="btn pri" type="submit" disabled>
|
|
||||||
Sign in
|
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<Link className="small muted center" to="/about">
|
||||||
|
About this build
|
||||||
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { SCREEN_LABELS, SCREEN_PHASE, type Screen } from "../auth/roles";
|
||||||
|
|
||||||
|
/** Stand-in for a screen that a later phase builds. */
|
||||||
|
export function PlaceholderScreen({ screen }: { screen: Exclude<Screen, "admin"> }) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className="phead">
|
||||||
|
<div>
|
||||||
|
<div className="eyebrow">Screen</div>
|
||||||
|
<h1>{SCREEN_LABELS[screen]}</h1>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="callout">This screen arrives in phase {SCREEN_PHASE[screen]}.</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { Navigate, useParams } from "react-router";
|
||||||
|
import { homePath, isScreen, orderScreens } from "../auth/roles";
|
||||||
|
import { useAuth } from "../auth/useAuth";
|
||||||
|
import { AdminPage } from "./admin/AdminPage";
|
||||||
|
import { PlaceholderScreen } from "./PlaceholderScreen";
|
||||||
|
|
||||||
|
/** /:screen. An unknown screen, or one the user does not have, goes to the user's first screen. */
|
||||||
|
export function ScreenRoute() {
|
||||||
|
const { screen } = useParams();
|
||||||
|
const { me } = useAuth();
|
||||||
|
if (!me) return null;
|
||||||
|
const allowed = orderScreens(me.screens);
|
||||||
|
if (!isScreen(screen) || !allowed.includes(screen)) return <Navigate to={homePath(me.screens)} replace />;
|
||||||
|
if (screen === "admin") return <AdminPage />;
|
||||||
|
return <PlaceholderScreen key={screen} screen={screen} />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
import { fireEvent, screen } from "@testing-library/react";
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { pinProblem } from "../../lib/pin";
|
||||||
|
import { makeMe, renderApp } from "../../test/auth";
|
||||||
|
import { callsTo, mockFetch } from "../../test/fetchMock";
|
||||||
|
|
||||||
|
const ACCOUNT = {
|
||||||
|
user: makeMe().user,
|
||||||
|
groups: ["PS-Clerical"],
|
||||||
|
roles: ["clerical"],
|
||||||
|
pin: { set: false, disabled: false },
|
||||||
|
ad_synced_at: "2026-10-16T08:00:00Z",
|
||||||
|
};
|
||||||
|
|
||||||
|
function routes(me = makeMe()) {
|
||||||
|
return {
|
||||||
|
"/api/auth/me": { body: me },
|
||||||
|
"/api/account": { body: ACCOUNT },
|
||||||
|
"/api/account/sessions": {
|
||||||
|
body: [
|
||||||
|
{
|
||||||
|
id: "sess-1",
|
||||||
|
kind: "password",
|
||||||
|
created_at: "2026-10-16T08:00:00Z",
|
||||||
|
last_seen_at: "2026-10-16T08:05:00Z",
|
||||||
|
ip: "10.0.0.5",
|
||||||
|
user_agent: "Firefox",
|
||||||
|
device: null,
|
||||||
|
current: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"/api/account/access-log": {
|
||||||
|
body: [{ at: "2026-10-16T08:00:00Z", action: "auth.signin", detail: { kind: "password" }, ip: "10.0.0.5", ok: true }],
|
||||||
|
},
|
||||||
|
"/api/auth/context": { body: { device: null, stack: "test", insecure_ldap: false, pin_digits: { min: 6, max: 12 } } },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("pinProblem", () => {
|
||||||
|
it("checks digits, length and the confirmation", () => {
|
||||||
|
expect(pinProblem("12ab56", "12ab56")).toBe("The PIN must be digits only.");
|
||||||
|
expect(pinProblem("12345", "12345")).toBe("The PIN must be 6 to 12 digits.");
|
||||||
|
expect(pinProblem("1234567890123", "1234567890123")).toBe("The PIN must be 6 to 12 digits.");
|
||||||
|
expect(pinProblem("123456", "123465")).toBe("The two PINs do not match.");
|
||||||
|
expect(pinProblem("123456", "123456")).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("AccountPage", () => {
|
||||||
|
it("shows the AD details, sessions and the access log", async () => {
|
||||||
|
mockFetch(routes());
|
||||||
|
renderApp("/account");
|
||||||
|
expect(await screen.findByRole("heading", { name: "Clara Clerk" })).toBeInTheDocument();
|
||||||
|
expect(await screen.findByText("PS-Clerical")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("04001")).toBeInTheDocument();
|
||||||
|
expect(await screen.findByText("This session")).toBeInTheDocument();
|
||||||
|
expect(await screen.findByText("auth.signin")).toBeInTheDocument();
|
||||||
|
expect(screen.queryByRole("heading", { name: "Register this device" })).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("validates the PIN before it posts, then saves it", async () => {
|
||||||
|
const fetch = mockFetch({ ...routes(), "POST /api/account/pin": { body: { pin: { set: true, disabled: false } } } });
|
||||||
|
renderApp("/account");
|
||||||
|
const submit = await screen.findByRole("button", { name: "Create PIN" });
|
||||||
|
fireEvent.change(screen.getByLabelText("Password"), { target: { value: "pw" } });
|
||||||
|
|
||||||
|
fireEvent.change(screen.getByLabelText("New PIN"), { target: { value: "12ab56" } });
|
||||||
|
fireEvent.change(screen.getByLabelText("Confirm PIN"), { target: { value: "12ab56" } });
|
||||||
|
fireEvent.click(submit);
|
||||||
|
expect(await screen.findByRole("alert")).toHaveTextContent("The PIN must be digits only.");
|
||||||
|
|
||||||
|
fireEvent.change(screen.getByLabelText("New PIN"), { target: { value: "123" } });
|
||||||
|
fireEvent.change(screen.getByLabelText("Confirm PIN"), { target: { value: "123" } });
|
||||||
|
fireEvent.click(submit);
|
||||||
|
expect(await screen.findByRole("alert")).toHaveTextContent("The PIN must be 6 to 12 digits.");
|
||||||
|
|
||||||
|
fireEvent.change(screen.getByLabelText("New PIN"), { target: { value: "135790" } });
|
||||||
|
fireEvent.change(screen.getByLabelText("Confirm PIN"), { target: { value: "135791" } });
|
||||||
|
fireEvent.click(submit);
|
||||||
|
expect(await screen.findByRole("alert")).toHaveTextContent("The two PINs do not match.");
|
||||||
|
expect(callsTo(fetch, "POST", "/api/account/pin")).toHaveLength(0);
|
||||||
|
|
||||||
|
fireEvent.change(screen.getByLabelText("Confirm PIN"), { target: { value: "135790" } });
|
||||||
|
fireEvent.click(submit);
|
||||||
|
expect(await screen.findByText("PIN saved.")).toBeInTheDocument();
|
||||||
|
expect(callsTo(fetch, "POST", "/api/account/pin")).toEqual([{ password: "pw", pin: "135790" }]);
|
||||||
|
expect(screen.getByRole("button", { name: "Change PIN" })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("a PIN session cannot change the PIN and sees why", async () => {
|
||||||
|
mockFetch(routes(makeMe({ session: { kind: "pin" }, pin: { set: true, disabled: false } })));
|
||||||
|
renderApp("/account");
|
||||||
|
expect(await screen.findByText("Sign in with your password to change account settings.")).toBeInTheDocument();
|
||||||
|
expect(screen.queryByLabelText("New PIN")).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows the disabled notice and the device form for a registrar", async () => {
|
||||||
|
const fetch = mockFetch({
|
||||||
|
...routes(makeMe({ pin: { set: true, disabled: true }, can_register_device: true })),
|
||||||
|
"POST /api/account/device": { body: { device: { id: "dev-9", name: "Weld Parts Stall 3" } } },
|
||||||
|
});
|
||||||
|
renderApp("/account");
|
||||||
|
expect(await screen.findByText(/Your PIN is disabled/)).toBeInTheDocument();
|
||||||
|
fireEvent.change(screen.getByLabelText("Device name"), { target: { value: "Weld Parts Stall 3" } });
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Register this device" }));
|
||||||
|
expect(await screen.findByText("Weld Parts Stall 3")).toBeInTheDocument();
|
||||||
|
expect(callsTo(fetch, "POST", "/api/account/device")).toEqual([{ name: "Weld Parts Stall 3" }]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,396 @@
|
|||||||
|
import { useState, type FormEvent } from "react";
|
||||||
|
import { Link } from "react-router";
|
||||||
|
import { accountApi, authApi } from "../../auth/api";
|
||||||
|
import { roleChipClass, sortRoles } from "../../auth/roles";
|
||||||
|
import type { AccountInfo, DeviceRef, Me } from "../../auth/types";
|
||||||
|
import { useAuth } from "../../auth/useAuth";
|
||||||
|
import { errorText, fmtDetail, fmtTime } from "../../lib/format";
|
||||||
|
import { PIN_MAX, pinProblem } from "../../lib/pin";
|
||||||
|
import { useLoad, type Load } from "../../lib/useLoad";
|
||||||
|
|
||||||
|
function Problem({ load }: { load: Load<unknown> }) {
|
||||||
|
if (load.state === "loading") return <div className="empty slim">Loading</div>;
|
||||||
|
if (load.state === "error") return <div className="callout warn">{load.message}</div>;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function Details({ me, account }: { me: Me; account: AccountInfo | null }) {
|
||||||
|
const { roleLabel } = useAuth();
|
||||||
|
const user = account?.user ?? me.user;
|
||||||
|
const groups = account?.groups ?? me.groups;
|
||||||
|
const roles = sortRoles(account?.roles ?? me.roles);
|
||||||
|
const rows: Array<[string, string | null]> = [
|
||||||
|
["Name", user.display_name],
|
||||||
|
["Account", user.sam_account],
|
||||||
|
["UPN", user.upn],
|
||||||
|
["Email", user.email],
|
||||||
|
["Employee ID", user.emp_no],
|
||||||
|
];
|
||||||
|
return (
|
||||||
|
<section className="sec" aria-labelledby="acct-ad">
|
||||||
|
<div className="sec-h">
|
||||||
|
<h2 id="acct-ad">Directory details</h2>
|
||||||
|
<span className="ct">From Active Directory. Read only.</span>
|
||||||
|
</div>
|
||||||
|
<div className="panel">
|
||||||
|
<dl className="kv">
|
||||||
|
{rows.map(([k, v]) => (
|
||||||
|
<div key={k}>
|
||||||
|
<dt>{k}</dt>
|
||||||
|
<dd className={k === "Employee ID" || k === "Account" ? "mono" : undefined}>{v || <span className="muted">Not set</span>}</dd>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<div>
|
||||||
|
<dt>Groups</dt>
|
||||||
|
<dd>
|
||||||
|
<ul className="chips plain" aria-label="Groups">
|
||||||
|
{groups.map((g) => (
|
||||||
|
<li key={g} className="chip static mono">
|
||||||
|
{g}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>Roles</dt>
|
||||||
|
<dd>
|
||||||
|
<ul className="chips plain" aria-label="Roles">
|
||||||
|
{roles.map((r) => (
|
||||||
|
<li key={r} className={roleChipClass(r)}>
|
||||||
|
{roleLabel(r)}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
</dl>
|
||||||
|
{account?.ad_synced_at ? <div className="small muted">Read from AD {fmtTime(account.ad_synced_at)}.</div> : null}
|
||||||
|
<div className="small muted">Roles come from AD groups. Ask IT to change them.</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function PinSection({ me, onSaved }: { me: Me; onSaved: () => void }) {
|
||||||
|
const auth = useAuth();
|
||||||
|
const [password, setPassword] = useState("");
|
||||||
|
const [pin, setPin] = useState("");
|
||||||
|
const [confirm, setConfirm] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [done, setDone] = useState(false);
|
||||||
|
const isPinSession = me.session.kind === "pin";
|
||||||
|
|
||||||
|
const submit = async (e: FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setDone(false);
|
||||||
|
if (!password) {
|
||||||
|
setError("Enter your password.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const problem = pinProblem(pin, confirm);
|
||||||
|
if (problem) {
|
||||||
|
setError(problem);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const res = await accountApi.setPin(password, pin);
|
||||||
|
auth.setMe({ ...me, pin: res.pin });
|
||||||
|
setPassword("");
|
||||||
|
setPin("");
|
||||||
|
setConfirm("");
|
||||||
|
setDone(true);
|
||||||
|
onSaved();
|
||||||
|
} catch (err) {
|
||||||
|
setError(errorText(err));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="sec" aria-labelledby="acct-pin">
|
||||||
|
<div className="sec-h">
|
||||||
|
<h2 id="acct-pin">PIN</h2>
|
||||||
|
<span className="ct">{me.pin.set ? (me.pin.disabled ? "Disabled" : "Set") : "Not set"}</span>
|
||||||
|
</div>
|
||||||
|
<div className="panel stack">
|
||||||
|
<div className="small">The PIN signs you in on a registered shop device and unlocks the screen. Use 6 to 12 digits.</div>
|
||||||
|
{me.pin.disabled ? (
|
||||||
|
<div className="callout warn flush">Your PIN is disabled after too many wrong attempts. Set a new one to use it again.</div>
|
||||||
|
) : null}
|
||||||
|
{isPinSession ? (
|
||||||
|
<div className="callout flush">Sign in with your password to change account settings.</div>
|
||||||
|
) : (
|
||||||
|
<form className="stack" onSubmit={submit} noValidate autoComplete="off">
|
||||||
|
<div className="frow">
|
||||||
|
<label className="f">
|
||||||
|
Password
|
||||||
|
<input className="in" type="password" autoComplete="current-password" value={password} onChange={(e) => setPassword(e.target.value)} />
|
||||||
|
</label>
|
||||||
|
<label className="f">
|
||||||
|
New PIN
|
||||||
|
<input
|
||||||
|
className="in mono"
|
||||||
|
type="password"
|
||||||
|
inputMode="numeric"
|
||||||
|
autoComplete="new-password"
|
||||||
|
maxLength={PIN_MAX}
|
||||||
|
value={pin}
|
||||||
|
onChange={(e) => setPin(e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="f">
|
||||||
|
Confirm PIN
|
||||||
|
<input
|
||||||
|
className="in mono"
|
||||||
|
type="password"
|
||||||
|
inputMode="numeric"
|
||||||
|
autoComplete="new-password"
|
||||||
|
maxLength={PIN_MAX}
|
||||||
|
value={confirm}
|
||||||
|
onChange={(e) => setConfirm(e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
{error ? (
|
||||||
|
<div className="callout warn flush" role="alert">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
{done ? (
|
||||||
|
<div className="callout flush" role="status">
|
||||||
|
PIN saved.
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
<div>
|
||||||
|
<button className="btn pri" type="submit" disabled={busy}>
|
||||||
|
{me.pin.set ? "Change PIN" : "Create PIN"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DeviceSection({ device, onRegistered }: { device: DeviceRef | null; onRegistered: (d: DeviceRef) => void }) {
|
||||||
|
const [name, setName] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const submit = async (e: FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!name.trim()) {
|
||||||
|
setError("Give the device a name, for example Weld Parts Stall 3.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const res = await accountApi.registerDevice(name.trim());
|
||||||
|
onRegistered(res.device);
|
||||||
|
setName("");
|
||||||
|
} catch (err) {
|
||||||
|
setError(errorText(err));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="sec" aria-labelledby="acct-device">
|
||||||
|
<div className="sec-h">
|
||||||
|
<h2 id="acct-device">Register this device</h2>
|
||||||
|
</div>
|
||||||
|
<div className="panel stack">
|
||||||
|
<div className="small">A registered device shows the PIN sign-in. Register shared shop screens only.</div>
|
||||||
|
{device ? (
|
||||||
|
<div className="callout flush" role="status">
|
||||||
|
This browser is registered as <b>{device.name}</b>.
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
<form className="frow" onSubmit={submit} noValidate>
|
||||||
|
<label className="f">
|
||||||
|
Device name
|
||||||
|
<input className="in" value={name} maxLength={80} onChange={(e) => setName(e.target.value)} />
|
||||||
|
</label>
|
||||||
|
<div className="end">
|
||||||
|
<button className="btn pri" type="submit" disabled={busy}>
|
||||||
|
Register this device
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
{error ? (
|
||||||
|
<div className="callout warn flush" role="alert">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function SessionsSection({ me }: { me: Me }) {
|
||||||
|
const [load, reload] = useLoad((s) => accountApi.sessions(s));
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [msg, setMsg] = useState<string | null>(null);
|
||||||
|
const isPinSession = me.session.kind === "pin";
|
||||||
|
|
||||||
|
const signOutOthers = async () => {
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const res = await accountApi.signOutOthers();
|
||||||
|
setMsg(res.revoked === 1 ? "Signed out 1 other session." : `Signed out ${res.revoked} other sessions.`);
|
||||||
|
reload();
|
||||||
|
} catch (err) {
|
||||||
|
setMsg(errorText(err));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const rows = load.state === "ok" ? load.data : [];
|
||||||
|
return (
|
||||||
|
<section className="sec" aria-labelledby="acct-sessions">
|
||||||
|
<div className="sec-h">
|
||||||
|
<h2 id="acct-sessions">Sessions</h2>
|
||||||
|
<span className="ct">Signed in now</span>
|
||||||
|
<span className="grow" />
|
||||||
|
<button className="btn sm" type="button" disabled={busy || isPinSession} onClick={() => void signOutOthers()}>
|
||||||
|
Sign out other sessions
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{msg ? (
|
||||||
|
<div className="callout" role="status">
|
||||||
|
{msg}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
<Problem load={load} />
|
||||||
|
{load.state === "ok" ? (
|
||||||
|
<div className="tw">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Started</th>
|
||||||
|
<th>Last seen</th>
|
||||||
|
<th>Sign-in</th>
|
||||||
|
<th>Device</th>
|
||||||
|
<th>Address</th>
|
||||||
|
<th>Browser</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{rows.map((s) => (
|
||||||
|
<tr key={s.id}>
|
||||||
|
<td className="small mono">
|
||||||
|
{fmtTime(s.created_at)} {s.current ? <span className="pill st-ok">This session</span> : null}
|
||||||
|
</td>
|
||||||
|
<td className="small mono">{fmtTime(s.last_seen_at)}</td>
|
||||||
|
<td>{s.kind === "pin" ? "PIN" : "Password"}</td>
|
||||||
|
<td>{s.device?.name ?? <span className="muted">-</span>}</td>
|
||||||
|
<td className="mono small">{s.ip ?? "-"}</td>
|
||||||
|
<td className="small clip">{s.user_agent ?? "-"}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
{rows.length === 0 ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={6} className="muted">
|
||||||
|
No active sessions.
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : null}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AccessLogSection() {
|
||||||
|
const [load] = useLoad((s) => accountApi.accessLog(50, s));
|
||||||
|
const rows = load.state === "ok" ? load.data : [];
|
||||||
|
return (
|
||||||
|
<section className="sec" aria-labelledby="acct-log">
|
||||||
|
<div className="sec-h">
|
||||||
|
<h2 id="acct-log">Access log</h2>
|
||||||
|
<span className="ct">Your sign-ins, failures and PIN changes. Newest first.</span>
|
||||||
|
</div>
|
||||||
|
<Problem load={load} />
|
||||||
|
{load.state === "ok" ? (
|
||||||
|
<div className="tw">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>When</th>
|
||||||
|
<th>What</th>
|
||||||
|
<th>Detail</th>
|
||||||
|
<th>Address</th>
|
||||||
|
<th>Result</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{rows.map((r, i) => (
|
||||||
|
<tr key={`${r.at}-${i}`}>
|
||||||
|
<td className="small mono">{fmtTime(r.at)}</td>
|
||||||
|
<td className="mono small">{r.action}</td>
|
||||||
|
<td className="small">{fmtDetail(r.detail)}</td>
|
||||||
|
<td className="mono small">{r.ip ?? "-"}</td>
|
||||||
|
<td>{r.ok ? <span className="pill st-ok">OK</span> : <span className="pill st-bad">Failed</span>}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
{rows.length === 0 ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={5} className="muted">
|
||||||
|
Nothing yet.
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : null}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** /account: the user's own AD details, PIN, device registration, sessions and access log. */
|
||||||
|
export function AccountPage() {
|
||||||
|
const { me } = useAuth();
|
||||||
|
const [account, reloadAccount] = useLoad((s) => accountApi.get(s));
|
||||||
|
const [context] = useLoad((s) => authApi.context(s));
|
||||||
|
const [registered, setRegistered] = useState<DeviceRef | null>(null);
|
||||||
|
if (!me) return null;
|
||||||
|
|
||||||
|
const device = registered ?? (context.state === "ok" ? context.data.device : null);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className="phead">
|
||||||
|
<div>
|
||||||
|
<div className="eyebrow">Account</div>
|
||||||
|
<h1>{me.user.display_name}</h1>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{me.session.kind === "pin" ? (
|
||||||
|
<div className="callout">
|
||||||
|
You signed in with a PIN{me.session.device ? ` on ${me.session.device.name}` : ""}. Some settings need a password sign-in.
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
{account.state === "error" ? <div className="callout warn">{account.message}</div> : null}
|
||||||
|
<Details me={me} account={account.state === "ok" ? account.data : null} />
|
||||||
|
<PinSection me={me} onSaved={reloadAccount} />
|
||||||
|
{me.can_register_device && me.session.kind === "password" ? <DeviceSection device={device} onRegistered={setRegistered} /> : null}
|
||||||
|
<SessionsSection me={me} />
|
||||||
|
<AccessLogSection />
|
||||||
|
<div className="small muted">
|
||||||
|
<Link to="/about">About this build</Link>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
import { fireEvent, screen, within } from "@testing-library/react";
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { DEPARTMENTS, makeMe, renderApp } from "../../test/auth";
|
||||||
|
import { callsTo, mockFetch } from "../../test/fetchMock";
|
||||||
|
|
||||||
|
const ADMIN = makeMe({
|
||||||
|
user: { display_name: "Ann Admin", sam_account: "admin.ann" },
|
||||||
|
roles: ["admin"],
|
||||||
|
screens: ["clerical", "warehouse", "supervisor", "stall", "qc", "pm", "admin"],
|
||||||
|
});
|
||||||
|
|
||||||
|
const USERS = [
|
||||||
|
{
|
||||||
|
id: "u-1",
|
||||||
|
sam_account: "dup.dave",
|
||||||
|
display_name: "Dave Dup",
|
||||||
|
emp_no: "9001",
|
||||||
|
email: null,
|
||||||
|
active: true,
|
||||||
|
roles: ["shop:03:worker"],
|
||||||
|
pin: { set: true, disabled: false },
|
||||||
|
flags: { emp_missing: false, emp_duplicate: true, disabled: false },
|
||||||
|
last_signin_at: null,
|
||||||
|
ad_synced_at: null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "u-2",
|
||||||
|
sam_account: "noemp.nora",
|
||||||
|
display_name: "Nora NoEmp",
|
||||||
|
emp_no: null,
|
||||||
|
email: null,
|
||||||
|
active: true,
|
||||||
|
roles: ["warehouse"],
|
||||||
|
pin: { set: false, disabled: false },
|
||||||
|
flags: { emp_missing: true, emp_duplicate: false, disabled: false },
|
||||||
|
last_signin_at: null,
|
||||||
|
ad_synced_at: null,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const GROUPS = {
|
||||||
|
checked_at: "2026-10-16T08:00:00Z",
|
||||||
|
ad_reachable: true,
|
||||||
|
groups: [
|
||||||
|
{ name: "PS-Admins", role: "admin", dept_code: null, in_ad: true },
|
||||||
|
{ name: "PS-03-WeldParts-Supervisor", role: "shop_supervisor", dept_code: "03", in_ad: true },
|
||||||
|
{ name: "PS-14-Electrical-Lead", role: "shop_lead", dept_code: "14", in_ad: false },
|
||||||
|
],
|
||||||
|
extra_in_ou: ["PS-Extra-Legacy"],
|
||||||
|
};
|
||||||
|
|
||||||
|
function base(me = ADMIN) {
|
||||||
|
return {
|
||||||
|
"/api/auth/me": { body: me },
|
||||||
|
"/api/departments": { body: DEPARTMENTS },
|
||||||
|
"/api/admin/users": { body: USERS },
|
||||||
|
"/api/admin/groups": { body: GROUPS },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("AdminPage", () => {
|
||||||
|
it("lists users with employee ID flags and opens the detail", async () => {
|
||||||
|
mockFetch({
|
||||||
|
...base(),
|
||||||
|
"/api/admin/users/u-1": {
|
||||||
|
body: { ...USERS[0], groups: ["PS-03-WeldParts-Worker"], sessions: [], note: "Roles come from AD groups. Ask IT to change them." },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
renderApp("/admin");
|
||||||
|
const row = (await screen.findByText("Dave Dup")).closest("tr") as HTMLElement;
|
||||||
|
expect(within(row).getByText("Duplicate")).toHaveClass("pill", "st-bad");
|
||||||
|
expect(await within(row).findByText("03 Weld Parts · Worker")).toHaveClass("rchip");
|
||||||
|
const nora = screen.getByText("Nora NoEmp").closest("tr") as HTMLElement;
|
||||||
|
expect(within(nora).getByText("Missing")).toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.click(row);
|
||||||
|
expect(await screen.findByText("Roles come from AD groups. Ask IT to change them.")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("PS-03-WeldParts-Worker")).toBeInTheDocument();
|
||||||
|
expect(screen.getByRole("button", { name: "Clear PIN" })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("clears a PIN with a reason", async () => {
|
||||||
|
const fetch = mockFetch({
|
||||||
|
...base(),
|
||||||
|
"/api/admin/users/u-1": { body: { ...USERS[0], groups: [], sessions: [], note: "" } },
|
||||||
|
"DELETE /api/admin/users/u-1/pin": { status: 204 },
|
||||||
|
});
|
||||||
|
renderApp("/admin");
|
||||||
|
fireEvent.click(await screen.findByText("Dave Dup"));
|
||||||
|
const clear = await screen.findByRole("button", { name: "Clear PIN" });
|
||||||
|
fireEvent.click(clear);
|
||||||
|
expect(await screen.findByRole("alert")).toHaveTextContent("at least 8 characters");
|
||||||
|
fireEvent.change(screen.getByLabelText("Reason for clearing the PIN"), { target: { value: "Forgot the PIN, asked by phone" } });
|
||||||
|
fireEvent.click(clear);
|
||||||
|
expect(await screen.findByText(/PIN cleared/)).toBeInTheDocument();
|
||||||
|
expect(callsTo(fetch, "DELETE", "/api/admin/users/u-1/pin")).toEqual([{ reason: "Forgot the PIN, asked by phone" }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("flags a group missing in AD, lists extras, and refreshes", async () => {
|
||||||
|
const fetch = mockFetch({
|
||||||
|
...base(),
|
||||||
|
"POST /api/admin/ad/refresh": {
|
||||||
|
body: {
|
||||||
|
groups_checked: 50,
|
||||||
|
groups_missing: ["PS-14-Electrical-Lead"],
|
||||||
|
users_seen: 16,
|
||||||
|
created: 2,
|
||||||
|
updated: 14,
|
||||||
|
deactivated: 1,
|
||||||
|
emp_missing: ["noemp.nora"],
|
||||||
|
emp_duplicate: ["9001"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
renderApp("/admin");
|
||||||
|
fireEvent.click(await screen.findByRole("tab", { name: "Group map" }));
|
||||||
|
expect(screen.getByRole("tab", { name: "Group map" })).toHaveAttribute("aria-selected", "true");
|
||||||
|
|
||||||
|
const row = (await screen.findByText("PS-14-Electrical-Lead")).closest("tr") as HTMLElement;
|
||||||
|
expect(within(row).getByText("Missing in AD")).toHaveClass("pill", "st-bad");
|
||||||
|
expect(within(row).getByText("14 Electrical · Lead")).toBeInTheDocument();
|
||||||
|
const ok = screen.getByText("PS-Admins").closest("tr") as HTMLElement;
|
||||||
|
expect(within(ok).getByText("In AD")).toHaveClass("st-ok");
|
||||||
|
expect(screen.getByText("PS-Extra-Legacy")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(/1 group is missing in AD/)).toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Refresh from AD now" }));
|
||||||
|
expect(await screen.findByText("Users seen")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("16")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(/noemp\.nora/)).toBeInTheDocument();
|
||||||
|
expect(callsTo(fetch, "POST", "/api/admin/ad/refresh")).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("marks groups as unreachable when AD is down", async () => {
|
||||||
|
mockFetch({
|
||||||
|
...base(),
|
||||||
|
"/api/admin/groups": {
|
||||||
|
body: { ...GROUPS, ad_reachable: false, groups: GROUPS.groups.map((g) => ({ ...g, in_ad: null })), extra_in_ou: [] },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
renderApp("/admin");
|
||||||
|
fireEvent.click(await screen.findByRole("tab", { name: "Group map" }));
|
||||||
|
expect(await screen.findByText(/AD is unreachable/)).toBeInTheDocument();
|
||||||
|
expect(screen.getAllByText("AD unreachable")).toHaveLength(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("a PIN session sees only the notice", async () => {
|
||||||
|
const fetch = mockFetch(base(makeMe({ ...ADMIN, session: { kind: "pin" } })));
|
||||||
|
renderApp("/admin");
|
||||||
|
expect(await screen.findByText(/Admin needs a password sign-in/)).toBeInTheDocument();
|
||||||
|
expect(screen.queryByRole("tab", { name: "Users" })).not.toBeInTheDocument();
|
||||||
|
expect(callsTo(fetch, "GET", "/api/admin/users")).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("revokes a device after a confirm", async () => {
|
||||||
|
const fetch = mockFetch({
|
||||||
|
...base(),
|
||||||
|
"/api/admin/devices": {
|
||||||
|
body: [
|
||||||
|
{
|
||||||
|
id: "dev-1",
|
||||||
|
name: "Weld Parts Stall 3",
|
||||||
|
registered_by: { id: "u-9", display_name: "Wes Super" },
|
||||||
|
registered_at: null,
|
||||||
|
last_seen_at: null,
|
||||||
|
revoked_at: null,
|
||||||
|
active_sessions: 2,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"DELETE /api/admin/devices/dev-1": { status: 204 },
|
||||||
|
});
|
||||||
|
renderApp("/admin");
|
||||||
|
fireEvent.click(await screen.findByRole("tab", { name: "Devices" }));
|
||||||
|
fireEvent.click(await screen.findByRole("button", { name: "Revoke" }));
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Confirm revoke" }));
|
||||||
|
await screen.findByRole("button", { name: "Revoke" });
|
||||||
|
expect(callsTo(fetch, "DELETE", "/api/admin/devices/dev-1")).toHaveLength(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,702 @@
|
|||||||
|
import { useEffect, useState, type FormEvent, type KeyboardEvent } from "react";
|
||||||
|
import { adminApi } from "../../auth/api";
|
||||||
|
import { roleChipClass, roleFromKind, sortRoles } from "../../auth/roles";
|
||||||
|
import type { AdLookup, AdRefreshResult, AdminUser, GroupRow, PinState } from "../../auth/types";
|
||||||
|
import { useAuth } from "../../auth/useAuth";
|
||||||
|
import { errorText, fmtTime } from "../../lib/format";
|
||||||
|
import { useLoad, type Load } from "../../lib/useLoad";
|
||||||
|
|
||||||
|
type Tab = "users" | "lookup" | "devices" | "groups" | "attempts";
|
||||||
|
|
||||||
|
const TABS: ReadonlyArray<{ id: Tab; label: string }> = [
|
||||||
|
{ id: "users", label: "Users" },
|
||||||
|
{ id: "lookup", label: "Look up AD account" },
|
||||||
|
{ id: "devices", label: "Devices" },
|
||||||
|
{ id: "groups", label: "Group map" },
|
||||||
|
{ id: "attempts", label: "Sign-in attempts" },
|
||||||
|
];
|
||||||
|
|
||||||
|
const ROLES_NOTE = "Roles come from AD groups. Ask IT to change them.";
|
||||||
|
|
||||||
|
function Problem({ load }: { load: Load<unknown> }) {
|
||||||
|
if (load.state === "loading") return <div className="empty slim">Loading</div>;
|
||||||
|
if (load.state === "error") return <div className="callout warn">{load.message}</div>;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function RoleChips({ roles, label }: { roles: readonly string[]; label: string }) {
|
||||||
|
const { roleLabel } = useAuth();
|
||||||
|
if (roles.length === 0) return <span className="muted small">No roles</span>;
|
||||||
|
return (
|
||||||
|
<ul className="chips plain tight" aria-label={label}>
|
||||||
|
{sortRoles(roles).map((r) => (
|
||||||
|
<li key={r} className={roleChipClass(r)}>
|
||||||
|
{roleLabel(r)}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function GroupChips({ groups }: { groups: readonly string[] }) {
|
||||||
|
if (groups.length === 0) return <span className="muted small">No Packet Station groups</span>;
|
||||||
|
return (
|
||||||
|
<ul className="chips plain tight" aria-label="Groups">
|
||||||
|
{groups.map((g) => (
|
||||||
|
<li key={g} className="chip static mono">
|
||||||
|
{g}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function PinPill({ pin }: { pin: PinState }) {
|
||||||
|
if (!pin.set) return <span className="muted small">None</span>;
|
||||||
|
if (pin.disabled) return <span className="pill st-bad">Disabled</span>;
|
||||||
|
return <span className="pill st-ok">Set</span>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Users ---------- */
|
||||||
|
|
||||||
|
function UserDetail({ id, onChanged, onClose }: { id: string; onChanged: () => void; onClose: () => void }) {
|
||||||
|
const [load, reload] = useLoad((s) => adminApi.user(id, s), id);
|
||||||
|
const [reason, setReason] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
|
||||||
|
|
||||||
|
const clearPin = async (e: FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (reason.trim().length < 8) {
|
||||||
|
setMsg({ ok: false, text: "Give a reason of at least 8 characters." });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
await adminApi.clearPin(id, reason.trim());
|
||||||
|
setReason("");
|
||||||
|
setMsg({ ok: true, text: "PIN cleared. The user sets a new one from Account." });
|
||||||
|
reload();
|
||||||
|
onChanged();
|
||||||
|
} catch (err) {
|
||||||
|
setMsg({ ok: false, text: errorText(err) });
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (load.state !== "ok") {
|
||||||
|
return (
|
||||||
|
<div className="panel">
|
||||||
|
<Problem load={load} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const u = load.data;
|
||||||
|
return (
|
||||||
|
<section className="panel stack" aria-labelledby="user-detail-h">
|
||||||
|
<div className="sec-h">
|
||||||
|
<h3 id="user-detail-h">{u.display_name}</h3>
|
||||||
|
<span className="mono small muted">{u.sam_account}</span>
|
||||||
|
<span className="grow" />
|
||||||
|
<button className="btn sm ghost" type="button" onClick={onClose}>
|
||||||
|
Close
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<dl className="kv">
|
||||||
|
<div>
|
||||||
|
<dt>Employee ID</dt>
|
||||||
|
<dd className="mono">{u.emp_no ?? <span className="muted">Missing</span>}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>Email</dt>
|
||||||
|
<dd>{u.email ?? "-"}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>Last sign-in</dt>
|
||||||
|
<dd className="mono small">{fmtTime(u.last_signin_at)}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>Read from AD</dt>
|
||||||
|
<dd className="mono small">{fmtTime(u.ad_synced_at)}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>Groups{u.groups_source === "cache" ? " (cached, AD unreachable)" : " (live)"}</dt>
|
||||||
|
<dd>
|
||||||
|
<GroupChips groups={u.groups} />
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>Roles</dt>
|
||||||
|
<dd>
|
||||||
|
<RoleChips roles={u.roles} label="Roles" />
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
</dl>
|
||||||
|
<div className="callout flush">{u.note || ROLES_NOTE}</div>
|
||||||
|
|
||||||
|
<h3>Sessions</h3>
|
||||||
|
<div className="tw">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Started</th>
|
||||||
|
<th>Last seen</th>
|
||||||
|
<th>Sign-in</th>
|
||||||
|
<th>Device</th>
|
||||||
|
<th>Address</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{u.sessions.map((s) => (
|
||||||
|
<tr key={s.id}>
|
||||||
|
<td className="small mono">{fmtTime(s.created_at)}</td>
|
||||||
|
<td className="small mono">{fmtTime(s.last_seen_at)}</td>
|
||||||
|
<td>{s.kind === "pin" ? "PIN" : "Password"}</td>
|
||||||
|
<td>{s.device?.name ?? "-"}</td>
|
||||||
|
<td className="mono small">{s.ip ?? "-"}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
{u.sessions.length === 0 ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={5} className="muted">
|
||||||
|
Not signed in.
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : null}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h3>PIN</h3>
|
||||||
|
<div>
|
||||||
|
<PinPill pin={u.pin} />
|
||||||
|
</div>
|
||||||
|
{u.pin.set ? (
|
||||||
|
<form className="frow" onSubmit={clearPin} noValidate>
|
||||||
|
<label className="f">
|
||||||
|
Reason for clearing the PIN
|
||||||
|
<input className="in" value={reason} maxLength={300} onChange={(e) => setReason(e.target.value)} />
|
||||||
|
</label>
|
||||||
|
<div className="end">
|
||||||
|
<button className="btn rejb" type="submit" disabled={busy}>
|
||||||
|
Clear PIN
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
) : null}
|
||||||
|
{msg ? (
|
||||||
|
<div className={msg.ok ? "callout flush" : "callout warn flush"} role={msg.ok ? "status" : "alert"}>
|
||||||
|
{msg.text}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function UsersTab() {
|
||||||
|
const [q, setQ] = useState("");
|
||||||
|
const [query, setQuery] = useState("");
|
||||||
|
const [selected, setSelected] = useState<string | null>(null);
|
||||||
|
const [load, reload] = useLoad((s) => adminApi.users(query, s), query);
|
||||||
|
|
||||||
|
// Search as the admin types, a moment after the last key.
|
||||||
|
useEffect(() => {
|
||||||
|
const t = window.setTimeout(() => setQuery(q.trim()), 250);
|
||||||
|
return () => window.clearTimeout(t);
|
||||||
|
}, [q]);
|
||||||
|
|
||||||
|
const rows: AdminUser[] = load.state === "ok" ? load.data : [];
|
||||||
|
const open = (id: string) => setSelected((cur) => (cur === id ? null : id));
|
||||||
|
const onRowKey = (e: KeyboardEvent, id: string) => {
|
||||||
|
if (e.key === "Enter" || e.key === " ") {
|
||||||
|
e.preventDefault();
|
||||||
|
open(id);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="stack">
|
||||||
|
<form className="frow" role="search" onSubmit={(e) => e.preventDefault()}>
|
||||||
|
<label className="f">
|
||||||
|
Search users
|
||||||
|
<input className="in" type="search" placeholder="Name, account or employee ID" value={q} onChange={(e) => setQ(e.target.value)} />
|
||||||
|
</label>
|
||||||
|
</form>
|
||||||
|
<Problem load={load} />
|
||||||
|
{load.state === "ok" ? (
|
||||||
|
<div className="tw">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Name</th>
|
||||||
|
<th>Account</th>
|
||||||
|
<th>Employee ID</th>
|
||||||
|
<th>Roles</th>
|
||||||
|
<th>PIN</th>
|
||||||
|
<th>Status</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{rows.map((u) => (
|
||||||
|
<tr
|
||||||
|
key={u.id}
|
||||||
|
className={selected === u.id ? "rowlink on" : "rowlink"}
|
||||||
|
tabIndex={0}
|
||||||
|
aria-selected={selected === u.id}
|
||||||
|
onClick={() => open(u.id)}
|
||||||
|
onKeyDown={(e) => onRowKey(e, u.id)}
|
||||||
|
>
|
||||||
|
<td>{u.display_name}</td>
|
||||||
|
<td className="mono small">{u.sam_account}</td>
|
||||||
|
<td className="mono">
|
||||||
|
{u.emp_no ?? ""} {u.flags.emp_missing ? <span className="pill st-bad">Missing</span> : null}
|
||||||
|
{u.flags.emp_duplicate ? <span className="pill st-bad">Duplicate</span> : null}
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<RoleChips roles={u.roles} label={`Roles of ${u.display_name}`} />
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<PinPill pin={u.pin} />
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
{u.flags.disabled ? (
|
||||||
|
<span className="pill st-bad">Disabled in AD</span>
|
||||||
|
) : u.active ? (
|
||||||
|
<span className="pill st-ok">Active</span>
|
||||||
|
) : (
|
||||||
|
<span className="pill st-filed">Inactive</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
{rows.length === 0 ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={6} className="muted">
|
||||||
|
No users match.
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : null}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
{selected ? <UserDetail key={selected} id={selected} onChanged={reload} onClose={() => setSelected(null)} /> : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Look up AD account ---------- */
|
||||||
|
|
||||||
|
function LookupTab() {
|
||||||
|
const [login, setLogin] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [result, setResult] = useState<AdLookup | null>(null);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const submit = async (e: FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!login.trim()) return;
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
setResult(await adminApi.lookup(login.trim()));
|
||||||
|
} catch (err) {
|
||||||
|
setResult(null);
|
||||||
|
setError(errorText(err));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const u = result?.user ?? null;
|
||||||
|
return (
|
||||||
|
<div className="stack">
|
||||||
|
<div className="small muted">Reads one account live from AD. Nothing is saved.</div>
|
||||||
|
<form className="frow" onSubmit={submit} noValidate>
|
||||||
|
<label className="f">
|
||||||
|
Account name
|
||||||
|
<input className="in" autoCapitalize="none" spellCheck={false} value={login} onChange={(e) => setLogin(e.target.value)} />
|
||||||
|
</label>
|
||||||
|
<div className="end">
|
||||||
|
<button className="btn pri" type="submit" disabled={busy}>
|
||||||
|
Look up
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
{error ? (
|
||||||
|
<div className="callout warn" role="alert">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
{result && !result.found ? <div className="callout">No account by that name in AD.</div> : null}
|
||||||
|
{result && result.found ? (
|
||||||
|
<div className="panel stack">
|
||||||
|
<div className="sec-h">
|
||||||
|
<h3>{u?.display_name ?? login}</h3>
|
||||||
|
<span className="mono small muted">{u?.sam_account ?? ""}</span>
|
||||||
|
{result.disabled ? <span className="pill st-bad">Disabled in AD</span> : <span className="pill st-ok">Enabled</span>}
|
||||||
|
</div>
|
||||||
|
<dl className="kv">
|
||||||
|
<div>
|
||||||
|
<dt>UPN</dt>
|
||||||
|
<dd>{u?.upn ?? "-"}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>Email</dt>
|
||||||
|
<dd>{u?.email ?? "-"}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>Employee ID</dt>
|
||||||
|
<dd className="mono">{u?.emp_no ?? <span className="muted">Missing</span>}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>Groups</dt>
|
||||||
|
<dd>
|
||||||
|
<GroupChips groups={result.groups ?? []} />
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>Roles</dt>
|
||||||
|
<dd>
|
||||||
|
<RoleChips roles={result.roles ?? []} label="Roles" />
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Devices ---------- */
|
||||||
|
|
||||||
|
function DevicesTab() {
|
||||||
|
const [load, reload] = useLoad((s) => adminApi.devices(s));
|
||||||
|
const [confirm, setConfirm] = useState<string | null>(null);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const revoke = async (id: string) => {
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
await adminApi.revokeDevice(id);
|
||||||
|
setConfirm(null);
|
||||||
|
reload();
|
||||||
|
} catch (err) {
|
||||||
|
setError(errorText(err));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const rows = load.state === "ok" ? load.data : [];
|
||||||
|
return (
|
||||||
|
<div className="stack">
|
||||||
|
<div className="small muted">Revoking a device ends every PIN session on it.</div>
|
||||||
|
{error ? (
|
||||||
|
<div className="callout warn" role="alert">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
<Problem load={load} />
|
||||||
|
{load.state === "ok" ? (
|
||||||
|
<div className="tw">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Name</th>
|
||||||
|
<th>Registered by</th>
|
||||||
|
<th>Registered</th>
|
||||||
|
<th>Last seen</th>
|
||||||
|
<th className="num">Sessions</th>
|
||||||
|
<th>Status</th>
|
||||||
|
<th />
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{rows.map((d) => (
|
||||||
|
<tr key={d.id}>
|
||||||
|
<td>{d.name}</td>
|
||||||
|
<td>{d.registered_by?.display_name ?? "-"}</td>
|
||||||
|
<td className="small mono">{fmtTime(d.registered_at)}</td>
|
||||||
|
<td className="small mono">{fmtTime(d.last_seen_at)}</td>
|
||||||
|
<td className="num">{d.active_sessions}</td>
|
||||||
|
<td>{d.revoked_at ? <span className="pill st-filed">Revoked</span> : <span className="pill st-ok">Active</span>}</td>
|
||||||
|
<td className="nowrap">
|
||||||
|
{d.revoked_at ? null : confirm === d.id ? (
|
||||||
|
<>
|
||||||
|
<button className="btn sm rejb" type="button" onClick={() => void revoke(d.id)}>
|
||||||
|
Confirm revoke
|
||||||
|
</button>{" "}
|
||||||
|
<button className="btn sm ghost" type="button" onClick={() => setConfirm(null)}>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<button className="btn sm ghost" type="button" onClick={() => setConfirm(d.id)}>
|
||||||
|
Revoke
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
{rows.length === 0 ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={7} className="muted">
|
||||||
|
No devices registered.
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : null}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Group map ---------- */
|
||||||
|
|
||||||
|
function InAdPill({ inAd }: { inAd: boolean | null }) {
|
||||||
|
if (inAd === true) return <span className="pill st-ok">In AD</span>;
|
||||||
|
if (inAd === false) return <span className="pill st-bad">Missing in AD</span>;
|
||||||
|
return <span className="pill st-wait">AD unreachable</span>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function RefreshResult({ r }: { r: AdRefreshResult }) {
|
||||||
|
const tiles: Array<[number, string, boolean]> = [
|
||||||
|
[r.groups_checked, "Groups checked", false],
|
||||||
|
[r.groups_missing.length, "Groups missing", r.groups_missing.length > 0],
|
||||||
|
[r.users_seen, "Users seen", false],
|
||||||
|
[r.created, "Created", false],
|
||||||
|
[r.updated, "Updated", false],
|
||||||
|
[r.deactivated, "Deactivated", r.deactivated > 0],
|
||||||
|
];
|
||||||
|
return (
|
||||||
|
<div role="status">
|
||||||
|
<div className="kpis">
|
||||||
|
{tiles.map(([n, l, hot]) => (
|
||||||
|
<div key={l} className={hot ? "kpi hot" : n === 0 ? "kpi zero" : "kpi"}>
|
||||||
|
<div className="n">{n}</div>
|
||||||
|
<div className="l">{l}</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
{r.groups_missing.length ? (
|
||||||
|
<div className="callout warn">
|
||||||
|
Missing groups: <span className="mono">{r.groups_missing.join(", ")}</span>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
{r.emp_missing.length ? (
|
||||||
|
<div className="callout warn">
|
||||||
|
No employee ID in AD: <span className="mono">{r.emp_missing.join(", ")}</span>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
{r.emp_duplicate.length ? (
|
||||||
|
<div className="callout warn">
|
||||||
|
Employee IDs used by more than one account: <span className="mono">{r.emp_duplicate.join(", ")}</span>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function GroupsTab() {
|
||||||
|
const { roleLabel } = useAuth();
|
||||||
|
const [load, reload] = useLoad((s) => adminApi.groups(s));
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [result, setResult] = useState<AdRefreshResult | null>(null);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const refresh = async () => {
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
setResult(await adminApi.refresh());
|
||||||
|
reload();
|
||||||
|
} catch (err) {
|
||||||
|
setError(errorText(err));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const map = load.state === "ok" ? load.data : null;
|
||||||
|
const missing = map ? map.groups.filter((g) => g.in_ad === false).length : 0;
|
||||||
|
const label = (g: GroupRow) => roleLabel(roleFromKind(g.role, g.dept_code));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="stack">
|
||||||
|
<div className="sec-h">
|
||||||
|
<span className="small muted">
|
||||||
|
The groups Packet Station reads, from the departments table.
|
||||||
|
{map?.checked_at ? ` Checked ${fmtTime(map.checked_at)}.` : ""}
|
||||||
|
</span>
|
||||||
|
<span className="grow" />
|
||||||
|
<button className="btn sm pri" type="button" disabled={busy} onClick={() => void refresh()}>
|
||||||
|
{busy ? "Reading AD" : "Refresh from AD now"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{error ? (
|
||||||
|
<div className="callout warn" role="alert">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
{result ? <RefreshResult r={result} /> : null}
|
||||||
|
<Problem load={load} />
|
||||||
|
{map && !map.ad_reachable ? <div className="callout warn">AD is unreachable. Showing the expected groups only.</div> : null}
|
||||||
|
{map && missing > 0 ? (
|
||||||
|
<div className="callout warn">
|
||||||
|
{missing === 1 ? "1 group is" : `${missing} groups are`} missing in AD. Ask IT to create {missing === 1 ? "it" : "them"}.
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
{map ? (
|
||||||
|
<div className="tw">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Group</th>
|
||||||
|
<th>Role</th>
|
||||||
|
<th>In AD</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{map.groups.map((g) => (
|
||||||
|
<tr key={g.name}>
|
||||||
|
<td className="mono small">{g.name}</td>
|
||||||
|
<td>
|
||||||
|
<span className={roleChipClass(roleFromKind(g.role, g.dept_code))}>{label(g)}</span>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<InAdPill inAd={g.in_ad} />
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
{map ? (
|
||||||
|
<section aria-labelledby="extra-h">
|
||||||
|
<h3 id="extra-h">Other groups in the OU</h3>
|
||||||
|
{map.extra_in_ou.length ? (
|
||||||
|
<>
|
||||||
|
<div className="small muted">Packet Station does not use these.</div>
|
||||||
|
<ul className="chips plain">
|
||||||
|
{map.extra_in_ou.map((g) => (
|
||||||
|
<li key={g} className="chip static mono">
|
||||||
|
{g}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<div className="small muted">None.</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Sign-in attempts ---------- */
|
||||||
|
|
||||||
|
function AttemptsTab() {
|
||||||
|
const [load, reload] = useLoad((s) => adminApi.signinAttempts(100, s));
|
||||||
|
const rows = load.state === "ok" ? load.data : [];
|
||||||
|
return (
|
||||||
|
<div className="stack">
|
||||||
|
<div className="sec-h">
|
||||||
|
<span className="small muted">Recent failed attempts. Newest first.</span>
|
||||||
|
<span className="grow" />
|
||||||
|
<button className="btn sm ghost" type="button" onClick={reload}>
|
||||||
|
Refresh
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<Problem load={load} />
|
||||||
|
{load.state === "ok" ? (
|
||||||
|
<div className="tw">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>When</th>
|
||||||
|
<th>Account</th>
|
||||||
|
<th>Kind</th>
|
||||||
|
<th>Reason</th>
|
||||||
|
<th>Address</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{rows.map((a, i) => (
|
||||||
|
<tr key={a.id ?? `${a.at}-${i}`}>
|
||||||
|
<td className="small mono">{fmtTime(a.at)}</td>
|
||||||
|
<td className="mono small">{a.account}</td>
|
||||||
|
<td>{a.kind}</td>
|
||||||
|
<td>{a.reason ? a.reason.replace(/_/g, " ") : "-"}</td>
|
||||||
|
<td className="mono small">{a.ip ?? "-"}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
{rows.length === 0 ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={5} className="muted">
|
||||||
|
No failed attempts.
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : null}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** /admin: users, AD lookup, devices, the group map and failed sign-ins. Needs a password session. */
|
||||||
|
export function AdminPage() {
|
||||||
|
const { me } = useAuth();
|
||||||
|
const [tab, setTab] = useState<Tab>("users");
|
||||||
|
|
||||||
|
const head = (
|
||||||
|
<div className="phead">
|
||||||
|
<div>
|
||||||
|
<div className="eyebrow">Admin</div>
|
||||||
|
<h1>Users and access</h1>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
if (me?.session.kind !== "password") {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{head}
|
||||||
|
<div className="callout warn">Admin needs a password sign-in. Sign out and sign in with your domain password.</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{head}
|
||||||
|
<div className="tabs" role="tablist" aria-label="Admin">
|
||||||
|
{TABS.map((t) => (
|
||||||
|
<button
|
||||||
|
key={t.id}
|
||||||
|
type="button"
|
||||||
|
role="tab"
|
||||||
|
id={`admtab-${t.id}`}
|
||||||
|
aria-selected={tab === t.id}
|
||||||
|
aria-controls={`admpanel-${t.id}`}
|
||||||
|
onClick={() => setTab(t.id)}
|
||||||
|
>
|
||||||
|
{t.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div role="tabpanel" id={`admpanel-${tab}`} aria-labelledby={`admtab-${tab}`}>
|
||||||
|
{tab === "users" ? <UsersTab /> : null}
|
||||||
|
{tab === "lookup" ? <LookupTab /> : null}
|
||||||
|
{tab === "devices" ? <DevicesTab /> : null}
|
||||||
|
{tab === "groups" ? <GroupsTab /> : null}
|
||||||
|
{tab === "attempts" ? <AttemptsTab /> : null}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import { render } from "@testing-library/react";
|
||||||
|
import { MemoryRouter } from "react-router";
|
||||||
|
import { AppRoutes } from "../App";
|
||||||
|
import { AuthProvider } from "../auth/AuthProvider";
|
||||||
|
import type { Me } from "../auth/types";
|
||||||
|
|
||||||
|
export const DEPARTMENTS = [
|
||||||
|
{ code: "CL", slug: "Clerical", name: "Clerical", kind: "support", stations: [] },
|
||||||
|
{ code: "03", slug: "WeldParts", name: "Weld Parts", kind: "shop", stations: ["Stall 1", "Stall 2"] },
|
||||||
|
{ code: "14", slug: "Electrical", name: "Electrical", kind: "shop", stations: [] },
|
||||||
|
];
|
||||||
|
|
||||||
|
/** A signed-in Me. Override any part. */
|
||||||
|
export function makeMe(over: Partial<Omit<Me, "session" | "user">> & { session?: Partial<Me["session"]>; user?: Partial<Me["user"]> } = {}): Me {
|
||||||
|
const { session, user, ...rest } = over;
|
||||||
|
return {
|
||||||
|
user: {
|
||||||
|
id: "11111111-1111-1111-1111-111111111111",
|
||||||
|
sam_account: "clerk.clara",
|
||||||
|
upn: "[email protected]",
|
||||||
|
display_name: "Clara Clerk",
|
||||||
|
emp_no: "04001",
|
||||||
|
email: "[email protected]",
|
||||||
|
...user,
|
||||||
|
},
|
||||||
|
roles: ["clerical"],
|
||||||
|
screens: ["clerical"],
|
||||||
|
groups: ["PS-Clerical"],
|
||||||
|
pin: { set: false, disabled: false },
|
||||||
|
can_register_device: false,
|
||||||
|
...rest,
|
||||||
|
session: {
|
||||||
|
id: "sess-1",
|
||||||
|
kind: "password",
|
||||||
|
created_at: "2026-10-16T08:00:00Z",
|
||||||
|
expires_at: "2026-10-16T20:00:00Z",
|
||||||
|
locked: false,
|
||||||
|
locked_since: null,
|
||||||
|
device: null,
|
||||||
|
...session,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const NO_SESSION = { status: 401, body: { detail: "Not signed in", code: "no_session" } };
|
||||||
|
|
||||||
|
/** Mounts the whole app at `path` under the auth provider. */
|
||||||
|
export function renderApp(path: string, props: { idleLockMs?: number; idleCheckMs?: number; hiddenLockMs?: number } = {}) {
|
||||||
|
return render(
|
||||||
|
<MemoryRouter initialEntries={[path]}>
|
||||||
|
<AuthProvider {...props}>
|
||||||
|
<AppRoutes />
|
||||||
|
</AuthProvider>
|
||||||
|
</MemoryRouter>,
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,20 +1,58 @@
|
|||||||
import { vi } from "vitest";
|
import { vi } from "vitest";
|
||||||
|
|
||||||
export type Route = { status?: number; body?: unknown; contentType?: string } | Error;
|
export type Reply = { status?: number; body?: unknown; contentType?: string } | Error;
|
||||||
|
|
||||||
/** Stubs global fetch. Routes are keyed by path. Unknown paths answer 404. */
|
/** What a route function sees about the request. */
|
||||||
|
export interface MockRequest {
|
||||||
|
method: string;
|
||||||
|
/** Path with the query string, as the app passed it. */
|
||||||
|
url: string;
|
||||||
|
path: string;
|
||||||
|
/** Parsed JSON body, or undefined. */
|
||||||
|
body: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Route = Reply | ((req: MockRequest) => Reply);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stubs global fetch. Routes are keyed by path, or by "METHOD path".
|
||||||
|
* Lookup order: "METHOD url", "METHOD path", "url", "path". A url key includes the query string.
|
||||||
|
* A route may be a function of the request, for answers that change between calls.
|
||||||
|
* Unknown paths answer 404.
|
||||||
|
*/
|
||||||
export function mockFetch(routes: Record<string, Route>) {
|
export function mockFetch(routes: Record<string, Route>) {
|
||||||
const fn = vi.fn(async (input: RequestInfo | URL, _init?: RequestInit) => {
|
const fn = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||||
const path = typeof input === "string" ? input : input instanceof URL ? input.pathname : input.url;
|
const url = typeof input === "string" ? input : input instanceof URL ? input.pathname + input.search : input.url;
|
||||||
const r = routes[path];
|
const path = url.split("?")[0] ?? url;
|
||||||
|
const method = (init?.method ?? "GET").toUpperCase();
|
||||||
|
let body: unknown;
|
||||||
|
if (typeof init?.body === "string") {
|
||||||
|
try {
|
||||||
|
body = JSON.parse(init.body) as unknown;
|
||||||
|
} catch {
|
||||||
|
body = init.body;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const route = routes[`${method} ${url}`] ?? routes[`${method} ${path}`] ?? routes[url] ?? routes[path];
|
||||||
|
const r = typeof route === "function" ? route({ method, url, path, body }) : route;
|
||||||
if (r instanceof Error) throw r;
|
if (r instanceof Error) throw r;
|
||||||
const status = r?.status ?? (r ? 200 : 404);
|
const status = r?.status ?? (r ? 200 : 404);
|
||||||
const body = r?.body;
|
const replyBody = r?.body;
|
||||||
const isText = typeof body === "string";
|
const isText = typeof replyBody === "string";
|
||||||
const contentType = r?.contentType ?? (isText ? "text/plain" : "application/json");
|
const contentType = r?.contentType ?? (isText ? "text/plain" : "application/json");
|
||||||
const text = body === undefined ? "" : isText ? body : JSON.stringify(body);
|
const text = replyBody === undefined ? "" : isText ? replyBody : JSON.stringify(replyBody);
|
||||||
return new Response(status === 204 ? null : text, { status, headers: { "content-type": contentType } });
|
return new Response(status === 204 ? null : text, { status, headers: { "content-type": contentType } });
|
||||||
});
|
});
|
||||||
vi.stubGlobal("fetch", fn);
|
vi.stubGlobal("fetch", fn);
|
||||||
return fn;
|
return fn;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The calls made to one method and path, with parsed JSON bodies. */
|
||||||
|
export function callsTo(fn: ReturnType<typeof mockFetch>, method: string, path: string): unknown[] {
|
||||||
|
return fn.mock.calls
|
||||||
|
.filter(([input, init]) => {
|
||||||
|
const url = typeof input === "string" ? input : input instanceof URL ? input.pathname : input.url;
|
||||||
|
return (init?.method ?? "GET").toUpperCase() === method && url.split("?")[0] === path;
|
||||||
|
})
|
||||||
|
.map(([, init]) => (typeof init?.body === "string" ? (JSON.parse(init.body) as unknown) : undefined));
|
||||||
|
}
|
||||||
|
|||||||
@@ -239,3 +239,27 @@ td .sub { color: var(--muted); font-size: 12.5px; }
|
|||||||
.brand .nm { font-size: 18px; }
|
.brand .nm { font-size: 18px; }
|
||||||
.phead h1 { font-size: 26px; }
|
.phead h1 { font-size: 26px; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ===== New in the rebuild (phase 1) ===== */
|
||||||
|
/* Sign-in, lock screen, Account and Admin. Built only from the tokens above. */
|
||||||
|
.callout.flush { margin: 0; }
|
||||||
|
.btn.wide { width: 100%; min-height: 56px; font-size: 17px; }
|
||||||
|
.center { align-self: center; text-align: center; }
|
||||||
|
.grow { flex: 1; }
|
||||||
|
.end { display: flex; align-items: flex-end; }
|
||||||
|
.nowrap { white-space: nowrap; }
|
||||||
|
.stack { display: flex; flex-direction: column; gap: 12px; }
|
||||||
|
.uname { color: var(--near); font-weight: 600; font-size: 14px; }
|
||||||
|
.chips.plain { list-style: none; margin: 0; padding: 0; }
|
||||||
|
.chips.tight { gap: 4px; }
|
||||||
|
.chip.static { cursor: default; min-height: 0; padding: 4px 10px; font-size: 12.5px; }
|
||||||
|
.kv { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 10px 20px; margin: 0 0 10px; }
|
||||||
|
.kv dt { font-size: 11.5px; font-weight: 700; letter-spacing: .06em; text-transform: uppercase; color: var(--muted); }
|
||||||
|
.kv dd { margin: 2px 0 0; color: var(--near); overflow-wrap: anywhere; }
|
||||||
|
td.clip { max-width: 280px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
tr.rowlink { cursor: pointer; }
|
||||||
|
tr.rowlink:hover td { background: var(--panel); }
|
||||||
|
tr.rowlink.on td { background: var(--sel); }
|
||||||
|
tr.rowlink:focus-visible { outline: 2px solid var(--cyan); outline-offset: -2px; }
|
||||||
|
td .pill + .pill { margin-left: 4px; }
|
||||||
|
.lock .auth-card { max-height: calc(100dvh - 32px); overflow: auto; }
|
||||||
|
|||||||
@@ -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
|
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:
|
def cmd_version(_: argparse.Namespace) -> int:
|
||||||
print(f"packetstation {__version__} build {os.environ.get('PS_BUILD', 'dev')}")
|
print(f"packetstation {__version__} build {os.environ.get('PS_BUILD', 'dev')}")
|
||||||
return 0
|
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("--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.add_argument("--send-test", metavar="ADDR", help="Also send one test message to ADDR")
|
||||||
d.set_defaults(func=cmd_doctor)
|
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)
|
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 = sub.add_parser("healthcheck", help="Container healthcheck (exit 0 healthy, 1 not)")
|
||||||
h.add_argument("target", choices=["app", "worker"])
|
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 starlette.concurrency import run_in_threadpool
|
||||||
|
|
||||||
from . import db, guard
|
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 .proxy import TrustedProxies, TrustedProxyMiddleware
|
||||||
from .security import RequestLogMiddleware, SecurityHeadersMiddleware
|
from .security import RequestLogMiddleware, SecurityHeadersMiddleware
|
||||||
from .settings import Settings, get_settings
|
from .settings import Settings, get_settings
|
||||||
@@ -39,22 +43,43 @@ def _static_file(static_dir: Path, path: str) -> Path | None:
|
|||||||
return candidate
|
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()
|
s = settings or get_settings()
|
||||||
if run_guard:
|
if run_guard:
|
||||||
guard.startup_checks(s)
|
guard.startup_checks(s)
|
||||||
trusted = TrustedProxies(s.trusted_proxy_host)
|
trusted = TrustedProxies(s.trusted_proxy_host)
|
||||||
|
hub = EventHub(connect=lambda: db.connect_as("app", s, autocommit=True))
|
||||||
|
|
||||||
@contextlib.asynccontextmanager
|
@contextlib.asynccontextmanager
|
||||||
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
|
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
|
||||||
await asyncio.to_thread(trusted.refresh)
|
await asyncio.to_thread(trusted.refresh)
|
||||||
task = asyncio.create_task(trusted.run()) if trusted.host else None
|
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}})
|
log.info("packetstation app starting", extra={"ps": {"build": s.ps_build, "stack": s.stack}})
|
||||||
try:
|
try:
|
||||||
yield
|
yield
|
||||||
finally:
|
finally:
|
||||||
if task:
|
if task:
|
||||||
task.cancel()
|
task.cancel()
|
||||||
|
deps_task.cancel()
|
||||||
|
await asyncio.to_thread(hub.stop)
|
||||||
await run_in_threadpool(db.close_pool)
|
await run_in_threadpool(db.close_pool)
|
||||||
|
|
||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
@@ -62,6 +87,17 @@ def create_app(settings: Settings | None = None, *, run_guard: bool = True) -> F
|
|||||||
)
|
)
|
||||||
app.state.settings = s
|
app.state.settings = s
|
||||||
app.state.trusted = trusted
|
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")
|
@app.get("/healthz")
|
||||||
def healthz() -> dict[str, Any]:
|
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(found)
|
||||||
return FileResponse(index, headers={"Cache-Control": "no-cache"})
|
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(SecurityHeadersMiddleware)
|
||||||
app.add_middleware(RequestLogMiddleware, build=s.ps_build)
|
app.add_middleware(RequestLogMiddleware, build=s.ps_build)
|
||||||
app.add_middleware(TrustedProxyMiddleware, trusted=trusted)
|
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
|
smtp_ca_bundle: Path | None = None
|
||||||
notify_dry_run: bool = False
|
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")
|
@model_validator(mode="before")
|
||||||
@classmethod
|
@classmethod
|
||||||
def _blank_is_unset(cls, data: Any) -> Any:
|
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")
|
raise ValueError("LDAP_ALLOW_INSECURE=true is refused on STACK=prod")
|
||||||
return self
|
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
|
@property
|
||||||
def ldap_urls(self) -> list[str]:
|
def ldap_urls(self) -> list[str]:
|
||||||
return self.ldap_url.split()
|
return self.ldap_url.split()
|
||||||
@@ -129,6 +152,13 @@ class Settings(BaseSettings):
|
|||||||
def ldap_password(self) -> str:
|
def ldap_password(self) -> str:
|
||||||
return read_secret(self.ldap_password_file, "LDAP_PASSWORD_FILE")
|
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)
|
@lru_cache(maxsize=1)
|
||||||
def get_settings() -> Settings:
|
def get_settings() -> Settings:
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
node_modules/
|
||||||
|
playwright-report/
|
||||||
|
test-results/
|
||||||
Generated
+60
@@ -0,0 +1,60 @@
|
|||||||
|
{
|
||||||
|
"name": "packetstation-e2e",
|
||||||
|
"version": "0.0.0",
|
||||||
|
"lockfileVersion": 3,
|
||||||
|
"requires": true,
|
||||||
|
"packages": {
|
||||||
|
"": {
|
||||||
|
"name": "packetstation-e2e",
|
||||||
|
"version": "0.0.0",
|
||||||
|
"devDependencies": {
|
||||||
|
"@playwright/test": "1.64.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@playwright/test": {
|
||||||
|
"version": "1.64.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.64.1.tgz",
|
||||||
|
"integrity": "sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"playwright": "1.64.1"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"playwright": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/playwright": {
|
||||||
|
"version": "1.64.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz",
|
||||||
|
"integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"playwright-core": "1.64.1"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"playwright": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/playwright-core": {
|
||||||
|
"version": "1.64.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz",
|
||||||
|
"integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"bin": {
|
||||||
|
"playwright-core": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"name": "packetstation-e2e",
|
||||||
|
"version": "0.0.0",
|
||||||
|
"private": true,
|
||||||
|
"description": "Playwright scenarios against the CI stack and its Samba DC.",
|
||||||
|
"scripts": {
|
||||||
|
"test": "playwright test"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@playwright/test": "1.64.1"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { defineConfig, devices } from "@playwright/test";
|
||||||
|
|
||||||
|
// Runs inside the playwright service of deploy/compose.ci.yaml.
|
||||||
|
// E2E_BASE_URL points at the app on the backend network. The scenarios share state
|
||||||
|
// (a registered device, a PIN), so they run in order on one worker.
|
||||||
|
export default defineConfig({
|
||||||
|
testDir: "./tests",
|
||||||
|
timeout: 60_000,
|
||||||
|
expect: { timeout: 10_000 },
|
||||||
|
retries: 0,
|
||||||
|
workers: 1,
|
||||||
|
fullyParallel: false,
|
||||||
|
forbidOnly: !!process.env.CI,
|
||||||
|
reporter: [["list"], ["html", { outputFolder: "playwright-report", open: "never" }]],
|
||||||
|
use: {
|
||||||
|
baseURL: process.env.E2E_BASE_URL ?? "http://ps-app:8000",
|
||||||
|
trace: "on-first-retry",
|
||||||
|
screenshot: "only-on-failure",
|
||||||
|
},
|
||||||
|
projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
|
||||||
|
});
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
import { expect, type Locator, type Page } from "@playwright/test";
|
||||||
|
|
||||||
|
// users.json is written by deploy/samba/seed.sh on the ci-dc-export volume.
|
||||||
|
// Shape: {"domain": "pstest.local", "users": {"<sam>": {"password", "emp_no", "display_name"}}}
|
||||||
|
export interface DcUser {
|
||||||
|
password: string;
|
||||||
|
emp_no: string | null;
|
||||||
|
display_name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
let cache: Record<string, DcUser> | null = null;
|
||||||
|
|
||||||
|
export function dcUser(sam: string): DcUser & { sam: string } {
|
||||||
|
if (!cache) {
|
||||||
|
const file = process.env.E2E_DC_USERS_FILE;
|
||||||
|
if (!file) throw new Error("E2E_DC_USERS_FILE is not set");
|
||||||
|
cache = (JSON.parse(readFileSync(file, "utf-8")) as { users: Record<string, DcUser> }).users;
|
||||||
|
}
|
||||||
|
const u = cache[sam];
|
||||||
|
if (!u) throw new Error(`user ${sam} is not in users.json`);
|
||||||
|
return { sam, ...u };
|
||||||
|
}
|
||||||
|
|
||||||
|
export const PIN = "246813";
|
||||||
|
|
||||||
|
/** The top bar. */
|
||||||
|
export function topBar(page: Page): Locator {
|
||||||
|
return page.getByRole("banner");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A tab by name. Tabs may be drawn as role=tab or as plain buttons. */
|
||||||
|
export function tab(page: Page, name: RegExp): Locator {
|
||||||
|
return page.getByRole("tab", { name }).or(page.getByRole("button", { name })).first();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The card, section or form that holds a heading matching `heading`. */
|
||||||
|
export function section(page: Page, heading: RegExp): Locator {
|
||||||
|
return page
|
||||||
|
.locator("section, .card, form, fieldset")
|
||||||
|
.filter({ has: page.getByRole("heading", { name: heading }) })
|
||||||
|
.last();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function openSignIn(page: Page): Promise<void> {
|
||||||
|
await page.goto("/signin");
|
||||||
|
await expect(page.getByRole("heading", { name: /sign in/i })).toBeVisible();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fill and submit the password tab. Does not wait for the outcome. */
|
||||||
|
export async function submitPassword(page: Page, login: string, password: string): Promise<void> {
|
||||||
|
await openSignIn(page);
|
||||||
|
const pwTab = page.getByRole("tab", { name: /password/i });
|
||||||
|
if (await pwTab.count()) await pwTab.first().click();
|
||||||
|
await page.getByLabel(/user ?name|account/i).first().fill(login);
|
||||||
|
await page.getByLabel(/^password$/i).fill(password);
|
||||||
|
await page.getByRole("button", { name: /^sign in$/i }).click();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Password sign-in that must succeed. */
|
||||||
|
export async function signInPassword(page: Page, sam: string): Promise<void> {
|
||||||
|
const u = dcUser(sam);
|
||||||
|
await submitPassword(page, u.sam, u.password);
|
||||||
|
await expect(page).not.toHaveURL(/\/signin/);
|
||||||
|
await expect(topBar(page).getByText(u.display_name)).toBeVisible();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function signOut(page: Page): Promise<void> {
|
||||||
|
const bar = topBar(page);
|
||||||
|
await bar
|
||||||
|
.getByRole("button", { name: /sign out/i })
|
||||||
|
.or(bar.getByRole("link", { name: /sign out/i }))
|
||||||
|
.first()
|
||||||
|
.click();
|
||||||
|
await expect(page).toHaveURL(/\/signin/);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enter a PIN with the on-screen keypad. Focuses `field` first so the keypad targets it.
|
||||||
|
* If the keypad left the field short (it fed another field), fills the field directly.
|
||||||
|
*/
|
||||||
|
export async function enterPin(scope: Page | Locator, field: Locator, pin: string): Promise<void> {
|
||||||
|
await field.click();
|
||||||
|
const keypad = scope.getByLabel(/keypad/i).first();
|
||||||
|
if (await keypad.count()) {
|
||||||
|
for (const d of pin) {
|
||||||
|
await keypad.getByRole("button", { name: new RegExp(`^(Digit )?${d}$`) }).click();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ((await field.inputValue()) !== pin) {
|
||||||
|
await field.fill(pin);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
import { expect, test } from "@playwright/test";
|
||||||
|
import {
|
||||||
|
PIN,
|
||||||
|
dcUser,
|
||||||
|
enterPin,
|
||||||
|
openSignIn,
|
||||||
|
section,
|
||||||
|
signInPassword,
|
||||||
|
signOut,
|
||||||
|
submitPassword,
|
||||||
|
tab,
|
||||||
|
topBar,
|
||||||
|
} from "./helpers";
|
||||||
|
|
||||||
|
// Phase 1 sign-in scenarios against the CI stack and the Samba DC (PSTEST.LOCAL).
|
||||||
|
// Scenarios 1 to 5 stand alone. 6 registers a device and sets weld.andy's PIN, and 7 and 8
|
||||||
|
// rely on it, so those three run as one serial group. The config runs one worker, in file order.
|
||||||
|
|
||||||
|
test("1. a fresh browser has no PIN tab", async ({ page }) => {
|
||||||
|
await openSignIn(page);
|
||||||
|
await expect(page.getByRole("tab", { name: /password/i })).toBeVisible();
|
||||||
|
await expect(page.getByRole("tab", { name: /^PIN$/ })).toHaveCount(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("2. a wrong password shows Sign-in failed", async ({ page }) => {
|
||||||
|
await submitPassword(page, "clerk.clara", `${dcUser("clerk.clara").password}-wrong`);
|
||||||
|
await expect(page.getByText(/Sign-in failed/)).toBeVisible();
|
||||||
|
await expect(page).toHaveURL(/\/signin/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("3. a user with no PS group sees the no-role message", async ({ page }) => {
|
||||||
|
const u = dcUser("norole.nick");
|
||||||
|
await submitPassword(page, u.sam, u.password);
|
||||||
|
await expect(page.getByText(/No role in Packet Station/)).toBeVisible();
|
||||||
|
await expect(page).toHaveURL(/\/signin/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("4. clerk.clara lands on Clerical with no role switcher", async ({ page }) => {
|
||||||
|
await signInPassword(page, "clerk.clara");
|
||||||
|
await expect(page).toHaveURL(/\/clerical/);
|
||||||
|
await expect(page.getByText(/Arrives in phase/i)).toBeVisible();
|
||||||
|
await expect(page.locator(".roles")).toHaveCount(0);
|
||||||
|
await expect(topBar(page).getByRole("button", { name: /^Supervisor$/ })).toHaveCount(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("5. multi.mia switches between Clerical and Supervisor", async ({ page }) => {
|
||||||
|
await signInPassword(page, "multi.mia");
|
||||||
|
const switcher = page.locator(".roles");
|
||||||
|
await expect(switcher).toBeVisible();
|
||||||
|
const choice = (name: RegExp) =>
|
||||||
|
switcher.getByRole("button", { name }).or(switcher.getByRole("link", { name })).first();
|
||||||
|
await expect(choice(/^Clerical$/)).toBeVisible();
|
||||||
|
await expect(choice(/^Supervisor$/)).toBeVisible();
|
||||||
|
await choice(/^Supervisor$/).click();
|
||||||
|
await expect(page).toHaveURL(/\/supervisor/);
|
||||||
|
await choice(/^Clerical$/).click();
|
||||||
|
await expect(page).toHaveURL(/\/clerical/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test.describe.serial("device, PIN and admin", () => {
|
||||||
|
test("6. admin registers a device, weld.andy sets a PIN and signs in with it", async ({ page }) => {
|
||||||
|
// Admin registers this browser.
|
||||||
|
await signInPassword(page, "admin.ann");
|
||||||
|
await page.goto("/account");
|
||||||
|
const device = section(page, /register this device/i);
|
||||||
|
await device.getByRole("textbox").first().fill("CI tablet");
|
||||||
|
const registered = page.waitForResponse(
|
||||||
|
(r) => r.url().endsWith("/api/account/device") && r.request().method() === "POST",
|
||||||
|
);
|
||||||
|
await device.getByRole("button", { name: /register/i }).click();
|
||||||
|
expect((await registered).ok()).toBe(true);
|
||||||
|
await signOut(page);
|
||||||
|
|
||||||
|
// The device cookie now shows the PIN tab.
|
||||||
|
await expect(page.getByRole("tab", { name: /^PIN$/ })).toBeVisible();
|
||||||
|
|
||||||
|
// weld.andy sets a PIN with his password.
|
||||||
|
const andy = dcUser("weld.andy");
|
||||||
|
await signInPassword(page, andy.sam);
|
||||||
|
await page.goto("/account");
|
||||||
|
const pin = section(page, /\bPIN\b/);
|
||||||
|
await pin.getByLabel(/password/i).fill(andy.password);
|
||||||
|
await pin.getByLabel(/^(new )?PIN$/i).fill(PIN);
|
||||||
|
await pin.getByLabel(/confirm/i).fill(PIN);
|
||||||
|
const saved = page.waitForResponse(
|
||||||
|
(r) => r.url().endsWith("/api/account/pin") && r.request().method() === "POST",
|
||||||
|
);
|
||||||
|
await pin.getByRole("button", { name: /(create|change|save) PIN|^save$/i }).click();
|
||||||
|
expect((await saved).ok()).toBe(true);
|
||||||
|
await signOut(page);
|
||||||
|
|
||||||
|
// PIN sign-in on the registered device.
|
||||||
|
await openSignIn(page);
|
||||||
|
await page.getByRole("tab", { name: /^PIN$/ }).click();
|
||||||
|
await page.getByRole("textbox", { name: /employee id/i }).fill(andy.emp_no ?? "");
|
||||||
|
await enterPin(page, page.getByRole("textbox", { name: /^PIN$/ }), PIN);
|
||||||
|
await page.getByRole("button", { name: /^sign in$/i }).click();
|
||||||
|
await expect(page).toHaveURL(/\/stall/);
|
||||||
|
await expect(topBar(page).getByText(andy.display_name)).toBeVisible();
|
||||||
|
|
||||||
|
// Nothing admin-ish for a shop worker.
|
||||||
|
await page.goto("/admin");
|
||||||
|
await expect(page.getByRole("tab", { name: /group map/i })).toHaveCount(0);
|
||||||
|
await expect(page.getByRole("button", { name: /refresh from ad/i })).toHaveCount(0);
|
||||||
|
await expect(page.getByRole("button", { name: /clear pin/i })).toHaveCount(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("7. admin sees the group map report, the device and the AD refresh counts", async ({ page }) => {
|
||||||
|
await signInPassword(page, "admin.ann");
|
||||||
|
await page.goto("/admin");
|
||||||
|
|
||||||
|
await tab(page, /group map/i).click();
|
||||||
|
const missing = page.getByRole("row").filter({ hasText: "PS-14-Electrical-Lead" });
|
||||||
|
await expect(missing).toBeVisible();
|
||||||
|
await expect(missing.locator(".pill.st-bad").or(missing.getByText(/missing/i)).first()).toBeVisible();
|
||||||
|
await expect(page.getByText("PS-Extra-Legacy").first()).toBeVisible();
|
||||||
|
|
||||||
|
const refreshed = page.waitForResponse(
|
||||||
|
(r) => r.url().endsWith("/api/admin/ad/refresh") && r.request().method() === "POST",
|
||||||
|
);
|
||||||
|
await page.getByRole("button", { name: /refresh from ad now/i }).click();
|
||||||
|
const resp = await refreshed;
|
||||||
|
expect(resp.ok()).toBe(true);
|
||||||
|
const counts = (await resp.json()) as { users_seen: number; emp_duplicate: string[] };
|
||||||
|
expect(counts.users_seen).toBeGreaterThanOrEqual(15);
|
||||||
|
expect(counts.emp_duplicate).toContain("9001");
|
||||||
|
await expect(page.getByText(/9001/).first()).toBeVisible();
|
||||||
|
|
||||||
|
await tab(page, /devices/i).click();
|
||||||
|
await expect(page.getByText("CI tablet").first()).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("8. three idle minutes lock the screen and the PIN unlocks it", async ({ page }) => {
|
||||||
|
// A hidden tab locks only after a minute away (the old build's rule), and a reload never
|
||||||
|
// locks, so the scenario drives the idle lock with a fake clock instead: the client's
|
||||||
|
// 3-minute idle timer posts /api/auth/lock and the server locks the session.
|
||||||
|
await page.clock.install();
|
||||||
|
const andy = dcUser("weld.andy");
|
||||||
|
await signInPassword(page, andy.sam);
|
||||||
|
await expect(page).toHaveURL(/\/stall/);
|
||||||
|
|
||||||
|
const locked = page.waitForResponse(
|
||||||
|
(r) => r.url().endsWith("/api/auth/lock") && r.request().method() === "POST",
|
||||||
|
);
|
||||||
|
await page.clock.runFor(3 * 60_000 + 20_000);
|
||||||
|
expect((await locked).status()).toBe(204);
|
||||||
|
|
||||||
|
const lock = page.getByRole("dialog").or(page.locator(".scrim.lock")).first();
|
||||||
|
await expect(lock).toBeVisible();
|
||||||
|
await expect(lock.getByText(andy.display_name)).toBeVisible();
|
||||||
|
|
||||||
|
// The server refuses a locked session until the step-up unlock.
|
||||||
|
const probe = await page.request.get("/api/account");
|
||||||
|
expect(probe.status()).toBe(423);
|
||||||
|
|
||||||
|
await enterPin(lock, lock.getByRole("textbox", { name: /^PIN$/ }), PIN);
|
||||||
|
await lock.getByRole("button", { name: /unlock/i }).click();
|
||||||
|
await expect(lock).toBeHidden();
|
||||||
|
await expect(page).toHaveURL(/\/stall/);
|
||||||
|
await expect(topBar(page).getByText(andy.display_name)).toBeVisible();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -7,7 +7,9 @@ from collections.abc import Iterator
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from pshelpers import PG_URL, fake_visual, make_settings
|
from fakedir import FakeDirectory
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from pshelpers import ORIGIN_HEADERS, PG_URL, fake_visual, make_settings
|
||||||
|
|
||||||
from packetstation.settings import Settings
|
from packetstation.settings import Settings
|
||||||
|
|
||||||
@@ -55,3 +57,17 @@ def pg_settings(tmp_path: Path) -> Iterator[Settings]:
|
|||||||
db.close_pool()
|
db.close_pool()
|
||||||
with psycopg.connect(PG_URL, autocommit=True) as su:
|
with psycopg.connect(PG_URL, autocommit=True) as su:
|
||||||
su.execute(sql.SQL("DROP DATABASE IF EXISTS {} WITH (FORCE)").format(sql.Identifier(name)))
|
su.execute(sql.SQL("DROP DATABASE IF EXISTS {} WITH (FORCE)").format(sql.Identifier(name)))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def fake_dir() -> FakeDirectory:
|
||||||
|
return FakeDirectory()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def pg_client(pg_settings: Settings, fake_dir: FakeDirectory, dev_visual: None) -> Iterator[TestClient]:
|
||||||
|
"""The app on a fresh migrated database with the fake directory; Origin headers set on every call."""
|
||||||
|
from packetstation.main import create_app
|
||||||
|
|
||||||
|
with TestClient(create_app(pg_settings, directory=fake_dir), headers=ORIGIN_HEADERS) as client:
|
||||||
|
yield client
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
"""An in-memory DirectoryProtocol for tests. Passwords here are obviously fake fixture values."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
|
||||||
|
from packetstation.auth.groups import group_names
|
||||||
|
from packetstation.auth.ldap import AdUser, LdapUnavailable
|
||||||
|
|
||||||
|
FAKE_PASSWORD = "fake-password-1"
|
||||||
|
NESTED_GROUP = "Shop-Welders-Nested"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class FakeUser:
|
||||||
|
sam: str
|
||||||
|
display: str
|
||||||
|
emp_no: str | None
|
||||||
|
groups: list[str]
|
||||||
|
password: str = FAKE_PASSWORD
|
||||||
|
disabled: bool = False
|
||||||
|
guid: uuid.UUID = field(default_factory=uuid.uuid4)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def dn(self) -> str:
|
||||||
|
return f"CN={self.display},OU=Users,OU=PESCO_FARMINGTON,DC=pstest,DC=local"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def upn(self) -> str:
|
||||||
|
return f"{self.sam}@pstest.local"
|
||||||
|
|
||||||
|
|
||||||
|
def default_users() -> list[FakeUser]:
|
||||||
|
"""The same people as the CI domain controller (deploy/samba)."""
|
||||||
|
return [
|
||||||
|
FakeUser("admin.ann", "Ann Admin", "1001", ["PS-Admins"]),
|
||||||
|
FakeUser("clerk.clara", "Clara Clerk", "4001", ["PS-Clerical"]),
|
||||||
|
FakeUser("clerk.leo", "Leo Lead", "4002", ["PS-Clerical-Supervisor"]),
|
||||||
|
FakeUser("wh.wade", "Wade Warehouse", "6001", ["PS-Warehouse"]),
|
||||||
|
FakeUser("qc.quinn", "Quinn QC", "5001", ["PS-QC"]),
|
||||||
|
FakeUser("pm.paula", "Paula PM", "7001", ["PS-ProjectMgmt"]),
|
||||||
|
FakeUser("weld.andy", "Andy Welder", "3003", ["PS-03-WeldParts-Worker"]),
|
||||||
|
FakeUser("lead.lou", "Lou Lead", "3002", ["PS-03-WeldParts-Lead"]),
|
||||||
|
FakeUser("sup.wes", "Wes Super", "2003", ["PS-03-WeldParts-Supervisor"]),
|
||||||
|
FakeUser("multi.mia", "Mia Multi", "2006", ["PS-Clerical", "PS-06-CodeBldg2-Supervisor"]),
|
||||||
|
FakeUser("nested.ned", "Ned Nested", "3010", [NESTED_GROUP]),
|
||||||
|
FakeUser("both.bo", "Bo Both", "3011", ["PS-03-WeldParts-Worker", "PS-03-WeldParts-Supervisor"]),
|
||||||
|
FakeUser("disabled.dan", "Dan Disabled", "3004", ["PS-03-WeldParts-Worker"], disabled=True),
|
||||||
|
FakeUser("noemp.nora", "Nora NoEmp", None, ["PS-Warehouse"]),
|
||||||
|
FakeUser("dup.dave", "Dave Dup", "9001", ["PS-03-WeldParts-Worker"]),
|
||||||
|
FakeUser("dup.dina", "Dina Dup", "9001", ["PS-Warehouse"]),
|
||||||
|
FakeUser("norole.nick", "Nick NoRole", "8001", []),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class FakeDirectory:
|
||||||
|
"""Users, groups in the PacketStation OU, and nested groups outside it."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
users: list[FakeUser] | None = None,
|
||||||
|
ou_groups: list[str] | None = None,
|
||||||
|
nested: dict[str, list[str]] | None = None,
|
||||||
|
):
|
||||||
|
self.users = users if users is not None else default_users()
|
||||||
|
if ou_groups is None:
|
||||||
|
ou_groups = [g for g in group_names() if g != "PS-14-Electrical-Lead"] + ["PS-Extra-Legacy"]
|
||||||
|
self.ou_groups = ou_groups
|
||||||
|
self.nested = nested if nested is not None else {NESTED_GROUP: ["PS-10-WeldAssembly-Worker"]}
|
||||||
|
self.down = False
|
||||||
|
self.binds = 0
|
||||||
|
self.searches = 0
|
||||||
|
|
||||||
|
# ------------------------------------------------ helpers
|
||||||
|
|
||||||
|
def user(self, sam: str) -> FakeUser:
|
||||||
|
return next(u for u in self.users if u.sam == sam)
|
||||||
|
|
||||||
|
def _check(self) -> None:
|
||||||
|
if self.down:
|
||||||
|
raise LdapUnavailable("fake directory is down")
|
||||||
|
self.searches += 1
|
||||||
|
|
||||||
|
def _ad(self, u: FakeUser) -> AdUser:
|
||||||
|
return AdUser(u.guid, u.dn, u.sam, u.upn, u.display, u.emp_no, f"{u.sam}@example.test", u.disabled)
|
||||||
|
|
||||||
|
def _closure(self, u: FakeUser) -> set[str]:
|
||||||
|
seen: set[str] = set()
|
||||||
|
todo = list(u.groups)
|
||||||
|
while todo:
|
||||||
|
g = todo.pop()
|
||||||
|
if g.lower() in seen:
|
||||||
|
continue
|
||||||
|
seen.add(g.lower())
|
||||||
|
todo.extend(self.nested.get(g, []))
|
||||||
|
return seen
|
||||||
|
|
||||||
|
def _in_ou(self, names: set[str]) -> list[str]:
|
||||||
|
return sorted(g for g in self.ou_groups if g.lower() in names)
|
||||||
|
|
||||||
|
# ------------------------------------------------ protocol
|
||||||
|
|
||||||
|
def find_user(self, login: str) -> AdUser | None:
|
||||||
|
self._check()
|
||||||
|
key = login.strip().lower()
|
||||||
|
for u in self.users:
|
||||||
|
if key in (u.sam.lower(), u.upn.lower()):
|
||||||
|
return self._ad(u)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def get_user_by_guid(self, guid: uuid.UUID) -> AdUser | None:
|
||||||
|
self._check()
|
||||||
|
for u in self.users:
|
||||||
|
if u.guid == guid:
|
||||||
|
return self._ad(u)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def verify_password(self, dn: str, password: str) -> bool:
|
||||||
|
if self.down:
|
||||||
|
raise LdapUnavailable("fake directory is down")
|
||||||
|
if not password:
|
||||||
|
return False
|
||||||
|
self.binds += 1
|
||||||
|
return any(u.dn == dn and u.password == password for u in self.users)
|
||||||
|
|
||||||
|
def groups_of(self, dn: str) -> list[str]:
|
||||||
|
self._check()
|
||||||
|
u = next((x for x in self.users if x.dn == dn), None)
|
||||||
|
return [] if u is None else self._in_ou(self._closure(u))
|
||||||
|
|
||||||
|
def list_groups(self) -> list[str]:
|
||||||
|
self._check()
|
||||||
|
return sorted(self.ou_groups)
|
||||||
|
|
||||||
|
def members_of(self, group_cn: str) -> list[AdUser]:
|
||||||
|
self._check()
|
||||||
|
if group_cn.lower() not in {g.lower() for g in self.ou_groups}:
|
||||||
|
return []
|
||||||
|
return [self._ad(u) for u in self.users if group_cn.lower() in self._closure(u)]
|
||||||
@@ -11,8 +11,18 @@ import pytest
|
|||||||
|
|
||||||
from packetstation.settings import Settings
|
from packetstation.settings import Settings
|
||||||
|
|
||||||
|
TEST_SESSION_KEY = "test-session-key-0123456789abcdef0123456789"
|
||||||
|
ORIGIN_HEADERS = {"Origin": "http://testserver", "X-Requested-With": "PacketStation"}
|
||||||
|
|
||||||
|
|
||||||
def make_settings(tmp: Path, **over: Any) -> Settings:
|
def make_settings(tmp: Path, **over: Any) -> Settings:
|
||||||
|
"""Settings for tests. Writes a throwaway session key file unless `session_key_file` is given."""
|
||||||
|
if "session_key_file" not in over:
|
||||||
|
key_file = tmp / "session_key"
|
||||||
|
if not key_file.exists():
|
||||||
|
key_file.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
key_file.write_text(TEST_SESSION_KEY + "\n")
|
||||||
|
over["session_key_file"] = key_file
|
||||||
values: dict[str, Any] = {
|
values: dict[str, Any] = {
|
||||||
"_env_file": None,
|
"_env_file": None,
|
||||||
"stack": "ci",
|
"stack": "ci",
|
||||||
@@ -37,3 +47,46 @@ def fake_visual(production: bool = False, explicit: bool = False) -> SimpleNames
|
|||||||
|
|
||||||
PG_URL = os.environ.get("TEST_PG_SUPERUSER_URL")
|
PG_URL = os.environ.get("TEST_PG_SUPERUSER_URL")
|
||||||
needs_pg = pytest.mark.skipif(not PG_URL, reason="TEST_PG_SUPERUSER_URL not set (no PostgreSQL)")
|
needs_pg = pytest.mark.skipif(not PG_URL, reason="TEST_PG_SUPERUSER_URL not set (no PostgreSQL)")
|
||||||
|
|
||||||
|
|
||||||
|
def sign_in(client: Any, login: str, password: str | None = None) -> Any:
|
||||||
|
"""Password sign-in through the API (FakeDirectory password by default); returns the response."""
|
||||||
|
from fakedir import FAKE_PASSWORD
|
||||||
|
|
||||||
|
return client.post(
|
||||||
|
"/api/auth/signin/password", json={"login": login, "password": FAKE_PASSWORD if password is None else password}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def app_conn(settings: Settings) -> Any:
|
||||||
|
"""An autocommit connection as the app role (for test setup and checks)."""
|
||||||
|
from packetstation import db
|
||||||
|
|
||||||
|
return db.connect_as("app", settings, autocommit=True)
|
||||||
|
|
||||||
|
|
||||||
|
PIN = "246810"
|
||||||
|
|
||||||
|
|
||||||
|
def register_device(client: Any, sam: str = "sup.wes", name: str = "Bldg 2 tablet 3") -> dict[str, str]:
|
||||||
|
assert sign_in(client, sam).status_code == 200
|
||||||
|
r = client.post("/api/account/device", json={"name": name})
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
assert "ps_device=" in r.headers["set-cookie"] and "max-age=31536000" in r.headers["set-cookie"].lower()
|
||||||
|
assert client.post("/api/auth/signout").status_code == 204
|
||||||
|
device: dict[str, str] = r.json()["device"]
|
||||||
|
return device
|
||||||
|
|
||||||
|
|
||||||
|
def set_pin(client: Any, sam: str, pin: str = PIN) -> None:
|
||||||
|
from fakedir import FAKE_PASSWORD
|
||||||
|
|
||||||
|
assert sign_in(client, sam).status_code == 200
|
||||||
|
r = client.post("/api/account/pin", json={"password": FAKE_PASSWORD, "pin": pin})
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
assert r.json() == {"pin": {"set": True, "disabled": False}}
|
||||||
|
assert client.post("/api/auth/signout").status_code == 204
|
||||||
|
|
||||||
|
|
||||||
|
def pin_signin(client: Any, emp_no: str, pin: str = PIN) -> Any:
|
||||||
|
return client.post("/api/auth/signin/pin", json={"emp_no": emp_no, "pin": pin})
|
||||||
|
|||||||
@@ -0,0 +1,153 @@
|
|||||||
|
"""Admin routes: users, AD view, PIN clearing, devices, group map, AD refresh, attempts."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from fakedir import FAKE_PASSWORD, FakeDirectory
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from pshelpers import ORIGIN_HEADERS, PIN, app_conn, needs_pg, pin_signin, register_device, set_pin, sign_in
|
||||||
|
|
||||||
|
from packetstation.main import create_app
|
||||||
|
from packetstation.settings import Settings
|
||||||
|
|
||||||
|
pytestmark = needs_pg
|
||||||
|
|
||||||
|
|
||||||
|
def test_admin_only(pg_client: TestClient) -> None:
|
||||||
|
sign_in(pg_client, "clerk.clara")
|
||||||
|
for path in ("/api/admin/users", "/api/admin/devices", "/api/admin/groups", "/api/admin/signin-attempts"):
|
||||||
|
r = pg_client.get(path)
|
||||||
|
assert r.status_code == 403 and r.json()["code"] == "forbidden", path
|
||||||
|
assert pg_client.post("/api/admin/ad/refresh").status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_group_map_flags_missing_and_extra(pg_client: TestClient, fake_dir: FakeDirectory) -> None:
|
||||||
|
sign_in(pg_client, "admin.ann")
|
||||||
|
view = pg_client.get("/api/admin/groups").json()
|
||||||
|
assert view["ad_reachable"] is True and view["checked_at"]
|
||||||
|
assert len(view["groups"]) == 50
|
||||||
|
missing = [g["name"] for g in view["groups"] if g["in_ad"] is False]
|
||||||
|
assert missing == ["PS-14-Electrical-Lead"]
|
||||||
|
assert view["extra_in_ou"] == ["PS-Extra-Legacy"]
|
||||||
|
first = view["groups"][0]
|
||||||
|
assert first == {"name": "PS-Admins", "role": "admin", "dept_code": None, "in_ad": True}
|
||||||
|
weld = next(g for g in view["groups"] if g["name"] == "PS-03-WeldParts-Lead")
|
||||||
|
assert weld["role"] == "shop:03:lead" and weld["dept_code"] == "03"
|
||||||
|
|
||||||
|
|
||||||
|
def test_ad_refresh_counts_and_flags(pg_client: TestClient, pg_settings: Settings, fake_dir: FakeDirectory) -> None:
|
||||||
|
sign_in(pg_client, "admin.ann")
|
||||||
|
res = pg_client.post("/api/admin/ad/refresh").json()
|
||||||
|
assert res == {
|
||||||
|
"groups_checked": 49,
|
||||||
|
"groups_missing": ["PS-14-Electrical-Lead"],
|
||||||
|
"users_seen": 16,
|
||||||
|
"created": 15,
|
||||||
|
"updated": 1,
|
||||||
|
"deactivated": 0,
|
||||||
|
"emp_missing": ["noemp.nora"],
|
||||||
|
"emp_duplicate": ["9001"],
|
||||||
|
}
|
||||||
|
users = {u["sam_account"]: u for u in pg_client.get("/api/admin/users").json()}
|
||||||
|
assert "norole.nick" not in users and len(users) == 16
|
||||||
|
assert users["dup.dave"]["flags"]["emp_duplicate"] and users["dup.dina"]["flags"]["emp_duplicate"]
|
||||||
|
assert users["noemp.nora"]["flags"]["emp_missing"] and users["noemp.nora"]["emp_no"] is None
|
||||||
|
assert users["disabled.dan"]["active"] is False and users["disabled.dan"]["flags"]["disabled"]
|
||||||
|
assert users["nested.ned"]["roles"] == ["shop:10:worker"]
|
||||||
|
assert users["both.bo"]["roles"] == ["shop:03:supervisor"]
|
||||||
|
assert users["multi.mia"]["roles"] == ["clerical", "shop:06:supervisor"]
|
||||||
|
assert [u["sam_account"] for u in pg_client.get("/api/admin/users", params={"q": "dup"}).json()] == [
|
||||||
|
"dup.dave",
|
||||||
|
"dup.dina",
|
||||||
|
]
|
||||||
|
|
||||||
|
# Clara signs in elsewhere, then AD disables her; the next refresh deactivates her and ends the session
|
||||||
|
|
||||||
|
with TestClient(create_app(pg_settings, directory=fake_dir), headers=ORIGIN_HEADERS) as other:
|
||||||
|
sign_in(other, "clerk.clara")
|
||||||
|
fake_dir.user("clerk.clara").disabled = True
|
||||||
|
fake_dir.users.remove(fake_dir.user("wh.wade")) # gone from AD
|
||||||
|
fake_dir.user("qc.quinn").groups = [] # still in AD, in no group
|
||||||
|
res = pg_client.post("/api/admin/ad/refresh").json()
|
||||||
|
assert res["deactivated"] == 2 and res["users_seen"] == 14
|
||||||
|
assert other.get("/api/auth/me").json()["code"] == "no_session"
|
||||||
|
users = {u["sam_account"]: u for u in pg_client.get("/api/admin/users").json()}
|
||||||
|
assert users["clerk.clara"]["active"] is False and users["wh.wade"]["active"] is False
|
||||||
|
assert users["qc.quinn"]["active"] is True and users["qc.quinn"]["roles"] == []
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
acts = conn.execute("SELECT action FROM audit_events WHERE action LIKE 'ad.%' ORDER BY id").fetchall()
|
||||||
|
assert [a[0] for a in acts] == ["ad.refresh", "ad.user_deactivated", "ad.user_deactivated", "ad.refresh"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_user_detail_and_lookup(pg_client: TestClient, fake_dir: FakeDirectory) -> None:
|
||||||
|
sign_in(pg_client, "admin.ann")
|
||||||
|
pg_client.post("/api/admin/ad/refresh")
|
||||||
|
mia = next(u for u in pg_client.get("/api/admin/users", params={"q": "mia"}).json())
|
||||||
|
detail = pg_client.get(f"/api/admin/users/{mia['id']}").json()
|
||||||
|
assert detail["groups"] == ["PS-06-CodeBldg2-Supervisor", "PS-Clerical"] and detail["groups_source"] == "ad"
|
||||||
|
assert detail["note"] == "Roles come from AD groups. Ask IT to change them." and detail["sessions"] == []
|
||||||
|
fake_dir.down = True
|
||||||
|
cached = pg_client.get(f"/api/admin/users/{mia['id']}").json()
|
||||||
|
assert cached["groups_source"] == "cache" and set(cached["groups"]) == set(detail["groups"])
|
||||||
|
assert pg_client.get("/api/admin/ad/lookup", params={"login": "mia"}).status_code == 503
|
||||||
|
fake_dir.down = False
|
||||||
|
found = pg_client.get("/api/admin/ad/lookup", params={"login": "norole.nick"}).json()
|
||||||
|
assert found["found"] is True and found["roles"] == [] and found["user"]["emp_no"] == "8001"
|
||||||
|
assert pg_client.get("/api/admin/ad/lookup", params={"login": "ghost"}).json()["found"] is False
|
||||||
|
assert pg_client.get("/api/admin/users/00000000-0000-0000-0000-000000000000").status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_clear_pin(pg_client: TestClient, pg_settings: Settings, fake_dir: FakeDirectory) -> None:
|
||||||
|
set_pin(pg_client, "weld.andy")
|
||||||
|
andy = str(fake_dir.user("weld.andy").guid)
|
||||||
|
sign_in(pg_client, "admin.ann")
|
||||||
|
r = pg_client.request("DELETE", f"/api/admin/users/{andy}/pin", json={"reason": " "})
|
||||||
|
assert r.status_code == 400 and r.json()["code"] == "reason_required"
|
||||||
|
r = pg_client.request("DELETE", f"/api/admin/users/{andy}/pin", json={"reason": "Forgot it, ticket 4411"})
|
||||||
|
assert r.status_code == 204
|
||||||
|
assert pg_client.request("DELETE", f"/api/admin/users/{andy}/pin", json={"reason": "again"}).status_code == 404
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT user_id, subject_id, it_reason FROM audit_events WHERE action = 'pin.cleared'"
|
||||||
|
).fetchone()
|
||||||
|
assert str(row[0]) == str(fake_dir.user("admin.ann").guid) and row[1] == andy
|
||||||
|
assert row[2] == "Forgot it, ticket 4411"
|
||||||
|
sign_in(pg_client, "weld.andy")
|
||||||
|
assert pg_client.get("/api/account").json()["pin"] == {"set": False, "disabled": False}
|
||||||
|
assert any(e["action"] == "pin.cleared" for e in pg_client.get("/api/account/access-log").json())
|
||||||
|
|
||||||
|
|
||||||
|
def test_devices_and_revoke_ends_pin_sessions(
|
||||||
|
pg_client: TestClient, pg_settings: Settings, fake_dir: FakeDirectory
|
||||||
|
) -> None:
|
||||||
|
device = register_device(pg_client)
|
||||||
|
set_pin(pg_client, "admin.ann")
|
||||||
|
assert pin_signin(pg_client, "1001").status_code == 200
|
||||||
|
# Admin is a password session only
|
||||||
|
r = pg_client.get("/api/admin/users")
|
||||||
|
assert r.status_code == 403 and r.json()["code"] == "password_session_required"
|
||||||
|
|
||||||
|
with TestClient(create_app(pg_settings, directory=fake_dir), headers=ORIGIN_HEADERS) as admin:
|
||||||
|
sign_in(admin, "admin.ann")
|
||||||
|
listed = admin.get("/api/admin/devices").json()
|
||||||
|
assert len(listed) == 1 and listed[0]["id"] == device["id"] and listed[0]["active_sessions"] == 1
|
||||||
|
assert listed[0]["registered_by"]["display_name"] == "Wes Super"
|
||||||
|
assert admin.delete(f"/api/admin/devices/{device['id']}").status_code == 204
|
||||||
|
assert admin.get("/api/admin/devices").json()[0]["revoked_at"] is not None
|
||||||
|
assert admin.get("/api/auth/me").status_code == 200 # the password session is not on the device
|
||||||
|
|
||||||
|
assert pg_client.get("/api/auth/me").json()["code"] == "no_session"
|
||||||
|
assert pg_client.get("/api/auth/context").json()["device"] is None
|
||||||
|
r = pin_signin(pg_client, "1001")
|
||||||
|
assert r.status_code == 403 and r.json()["code"] == "device_required"
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
assert conn.execute("SELECT revoked_reason FROM sessions WHERE kind = 'pin'").fetchone()[0] == "device_revoked"
|
||||||
|
assert conn.execute("SELECT count(*) FROM audit_events WHERE action = 'device.revoked'").fetchone()[0] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_signin_attempts_list(pg_client: TestClient) -> None:
|
||||||
|
sign_in(pg_client, "clerk.clara", "wrong")
|
||||||
|
sign_in(pg_client, "admin.ann", FAKE_PASSWORD)
|
||||||
|
rows = pg_client.get("/api/admin/signin-attempts").json()
|
||||||
|
assert len(rows) == 1 and rows[0]["account"] == "clerk.clara" and rows[0]["reason"] == "bad_password"
|
||||||
|
assert set(rows[0]) == {"id", "at", "account", "ip", "kind", "reason", "user_id", "display_name"}
|
||||||
|
assert FAKE_PASSWORD not in str(rows) and PIN not in str(rows)
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from pshelpers import needs_pg
|
||||||
|
|
||||||
|
from packetstation import db, events
|
||||||
|
from packetstation.settings import Settings
|
||||||
|
|
||||||
|
|
||||||
|
def _sub(hub: events.EventHub, name: str, screen: str | None = None) -> events.Subscriber:
|
||||||
|
return hub.subscribe(session_id=uuid.uuid4(), user_id=uuid.uuid4(), display_name=name, screen=screen)
|
||||||
|
|
||||||
|
|
||||||
|
async def _drain(q: asyncio.Queue[events.Item]) -> list[events.Item]:
|
||||||
|
await asyncio.sleep(0) # let call_soon_threadsafe callbacks run
|
||||||
|
out = []
|
||||||
|
while not q.empty():
|
||||||
|
out.append(q.get_nowait())
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def test_fan_out_presence_and_session_targeting() -> None:
|
||||||
|
async def run() -> None:
|
||||||
|
hub = events.EventHub()
|
||||||
|
a = _sub(hub, "Ann", "admin")
|
||||||
|
b = _sub(hub, "Bo", "stall")
|
||||||
|
got_a = await _drain(a.queue)
|
||||||
|
assert [n for n, _ in got_a] == ["presence", "presence"]
|
||||||
|
assert got_a[-1][1] == {
|
||||||
|
"users": [
|
||||||
|
{"user_id": a.user_id, "display_name": "Ann", "screen": "admin"},
|
||||||
|
{"user_id": b.user_id, "display_name": "Bo", "screen": "stall"},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
await _drain(b.queue)
|
||||||
|
|
||||||
|
hub._deliver(json.dumps({"event": "changed", "collection": "packets", "id": 7}))
|
||||||
|
hub._deliver(json.dumps({"collection": "projects"})) # no event name means changed
|
||||||
|
hub._deliver("not json")
|
||||||
|
for q in (a.queue, b.queue):
|
||||||
|
assert await _drain(q) == [
|
||||||
|
("changed", {"collection": "packets", "id": 7}),
|
||||||
|
("changed", {"collection": "projects"}),
|
||||||
|
]
|
||||||
|
|
||||||
|
hub._deliver(json.dumps({"event": "session", "session_id": b.session_id, "action": "revoked"}))
|
||||||
|
assert await _drain(a.queue) == []
|
||||||
|
assert await _drain(b.queue) == [("session", {"session_id": b.session_id, "action": "revoked"})]
|
||||||
|
|
||||||
|
hub.unsubscribe(b)
|
||||||
|
got = await _drain(a.queue)
|
||||||
|
assert got == [("presence", {"users": [{"user_id": a.user_id, "display_name": "Ann", "screen": "admin"}]})]
|
||||||
|
|
||||||
|
asyncio.run(run())
|
||||||
|
|
||||||
|
|
||||||
|
def test_sse_stream_hello_ping_and_end_on_own_revoke() -> None:
|
||||||
|
async def run() -> list[str]:
|
||||||
|
hub = events.EventHub()
|
||||||
|
sub = _sub(hub, "Ann")
|
||||||
|
await _drain(sub.queue)
|
||||||
|
|
||||||
|
async def connected() -> bool:
|
||||||
|
return False
|
||||||
|
|
||||||
|
gen = events.stream(
|
||||||
|
hub, sub, hello={"session_id": sub.session_id, "build": "t"}, is_disconnected=connected, ping_seconds=0.05
|
||||||
|
)
|
||||||
|
chunks = [await gen.__anext__(), await gen.__anext__()]
|
||||||
|
hub._deliver(json.dumps({"event": "changed", "collection": "packets"}))
|
||||||
|
chunks.append(await gen.__anext__())
|
||||||
|
hub._deliver(json.dumps({"event": "session", "session_id": sub.session_id, "action": "revoked"}))
|
||||||
|
chunks.append(await gen.__anext__())
|
||||||
|
rest = [c async for c in gen]
|
||||||
|
assert rest == []
|
||||||
|
assert hub.presence() == {"users": []}
|
||||||
|
return chunks
|
||||||
|
|
||||||
|
chunks = asyncio.run(run())
|
||||||
|
assert chunks[0].startswith("event: hello\ndata: {") and '"build":"t"' in chunks[0]
|
||||||
|
assert chunks[1] == ": ping\n\n"
|
||||||
|
assert chunks[2] == 'event: changed\ndata: {"collection":"packets"}\n\n'
|
||||||
|
assert chunks[3].startswith("event: session\n")
|
||||||
|
|
||||||
|
|
||||||
|
@needs_pg
|
||||||
|
def test_pg_notify_round_trip(pg_settings: Settings) -> None:
|
||||||
|
async def run() -> events.Item:
|
||||||
|
hub = events.EventHub(connect=lambda: db.connect_as("app", pg_settings, autocommit=True))
|
||||||
|
sub = _sub(hub, "Ann")
|
||||||
|
await _drain(sub.queue)
|
||||||
|
hub.start()
|
||||||
|
try:
|
||||||
|
for _ in range(100):
|
||||||
|
if hub.connected:
|
||||||
|
break
|
||||||
|
await asyncio.sleep(0.05)
|
||||||
|
assert hub.connected
|
||||||
|
with db.connect_as("app", pg_settings, autocommit=True) as conn:
|
||||||
|
events.publish(conn, {"event": "changed", "collection": "packets", "id": "7A"})
|
||||||
|
return await asyncio.wait_for(sub.queue.get(), timeout=5)
|
||||||
|
finally:
|
||||||
|
await asyncio.to_thread(hub.stop)
|
||||||
|
|
||||||
|
assert asyncio.run(run()) == ("changed", {"collection": "packets", "id": "7A"})
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from packetstation import cli
|
||||||
|
from packetstation.auth import groups
|
||||||
|
|
||||||
|
GROUPS_TXT = Path(__file__).resolve().parents[2] / "deploy" / "samba" / "groups.txt"
|
||||||
|
|
||||||
|
|
||||||
|
def test_fifty_names_in_contract_order() -> None:
|
||||||
|
names = groups.group_names()
|
||||||
|
assert len(names) == 50 == len(set(names))
|
||||||
|
assert names[:8] == [
|
||||||
|
"PS-Admins",
|
||||||
|
"PS-Clerical",
|
||||||
|
"PS-Clerical-Supervisor",
|
||||||
|
"PS-Warehouse",
|
||||||
|
"PS-Warehouse-Supervisor",
|
||||||
|
"PS-QC",
|
||||||
|
"PS-QC-Supervisor",
|
||||||
|
"PS-ProjectMgmt",
|
||||||
|
]
|
||||||
|
assert names[8:11] == ["PS-01-Layout-Worker", "PS-01-Layout-Lead", "PS-01-Layout-Supervisor"]
|
||||||
|
assert names[-1] == "PS-14-Electrical-Supervisor"
|
||||||
|
|
||||||
|
|
||||||
|
def test_cli_list_equals_committed_file(capsys: pytest.CaptureFixture[str]) -> None:
|
||||||
|
assert cli.main(["ad-groups", "--list"]) == 0
|
||||||
|
out = capsys.readouterr().out
|
||||||
|
assert out == GROUPS_TXT.read_text(encoding="utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def test_role_for_group_is_case_insensitive() -> None:
|
||||||
|
assert str(groups.role_for_group("ps-03-weldparts-LEAD")) == "shop:03:lead"
|
||||||
|
assert str(groups.role_for_group("PS-Admins")) == "admin"
|
||||||
|
assert groups.role_for_group("PS-Admins").dept_code is None # type: ignore[union-attr]
|
||||||
|
assert str(groups.role_for_group("PS-QC-Supervisor")) == "qc_supervisor"
|
||||||
|
assert groups.role_for_group("PS-Extra-Legacy") is None
|
||||||
|
assert groups.role_for_group("PS-ProjectMgmt-Supervisor") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_roles_union_and_highest_shop_level() -> None:
|
||||||
|
assert groups.roles_from_groups(["PS-03-WeldParts-Worker", "PS-03-WeldParts-Supervisor"]) == ["shop:03:supervisor"]
|
||||||
|
assert groups.roles_from_groups(["PS-Clerical", "PS-06-CodeBldg2-Supervisor", "x"]) == [
|
||||||
|
"clerical",
|
||||||
|
"shop:06:supervisor",
|
||||||
|
]
|
||||||
|
assert groups.roles_from_groups(["PS-Clerical", "PS-Clerical-Supervisor"]) == ["clerical", "clerical_supervisor"]
|
||||||
|
assert groups.roles_from_groups(["PS-10-WeldAssembly-Lead", "PS-03-WeldParts-Worker"]) == [
|
||||||
|
"shop:03:worker",
|
||||||
|
"shop:10:lead",
|
||||||
|
]
|
||||||
|
assert groups.roles_from_groups([]) == []
|
||||||
|
assert groups.roles_from_groups(["Domain Users"]) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_screens() -> None:
|
||||||
|
assert groups.screens_for(["clerical", "shop:03:supervisor"]) == ["clerical", "supervisor", "stall"]
|
||||||
|
assert groups.screens_for(["shop:03:worker"]) == ["stall"]
|
||||||
|
assert groups.screens_for(["shop:03:lead"]) == ["supervisor", "stall"]
|
||||||
|
assert groups.screens_for(["warehouse_supervisor", "qc", "pm"]) == ["warehouse", "qc", "pm"]
|
||||||
|
assert groups.screens_for(["admin"]) == list(groups.SCREENS)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("text", ["admin", "clerical", "qc_supervisor", "pm", "shop:03:worker", "shop:14:supervisor"])
|
||||||
|
def test_parse_role_round_trip(text: str) -> None:
|
||||||
|
assert str(groups.parse_role(text)) == text
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("text", ["", "shop:03", "shop:03:boss", "root", "shop::lead"])
|
||||||
|
def test_parse_role_rejects(text: str) -> None:
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
groups.parse_role(text)
|
||||||
|
|
||||||
|
|
||||||
|
def test_departments_mirror_and_custom_map() -> None:
|
||||||
|
assert [d.code for d in groups.DEPARTMENTS][:4] == ["CL", "WH", "QC", "PM"]
|
||||||
|
custom = groups.GroupMap([*groups.DEPARTMENTS, groups.Department("15", "Machining", "Machining", "shop", 190)])
|
||||||
|
assert custom.names()[-3:] == ["PS-15-Machining-Worker", "PS-15-Machining-Lead", "PS-15-Machining-Supervisor"]
|
||||||
|
assert len(custom.names()) == 53
|
||||||
|
assert groups.is_shop_supervisor(["shop:01:supervisor"]) and not groups.is_shop_supervisor(["shop:01:lead"])
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
"""Against the CI Samba domain controller (deploy/samba). Skipped unless the TEST_LDAP_* values are set.
|
||||||
|
|
||||||
|
TEST_LDAP_URL, TEST_LDAP_BASE_DN, TEST_LDAP_BIND_DN, TEST_LDAP_PASSWORD_FILE, TEST_LDAP_GROUP_BASE_DN,
|
||||||
|
TEST_LDAP_CA_BUNDLE and TEST_DC_USERS_FILE (the users.json the DC seed writes, with per-run passwords).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from pshelpers import ORIGIN_HEADERS, app_conn, make_settings, needs_pg
|
||||||
|
|
||||||
|
from packetstation.auth import groups
|
||||||
|
from packetstation.auth.directory import refresh_from_ad
|
||||||
|
from packetstation.auth.ldap import Directory
|
||||||
|
from packetstation.settings import Settings
|
||||||
|
|
||||||
|
ENV = (
|
||||||
|
"TEST_LDAP_URL",
|
||||||
|
"TEST_LDAP_BASE_DN",
|
||||||
|
"TEST_LDAP_BIND_DN",
|
||||||
|
"TEST_LDAP_PASSWORD_FILE",
|
||||||
|
"TEST_LDAP_GROUP_BASE_DN",
|
||||||
|
"TEST_LDAP_CA_BUNDLE",
|
||||||
|
"TEST_DC_USERS_FILE",
|
||||||
|
)
|
||||||
|
MISSING = [k for k in ENV if not os.environ.get(k)]
|
||||||
|
pytestmark = pytest.mark.skipif(bool(MISSING), reason=f"no test domain controller ({', '.join(MISSING)} not set)")
|
||||||
|
|
||||||
|
|
||||||
|
def ldap_values() -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"ldap_url": os.environ["TEST_LDAP_URL"],
|
||||||
|
"ldap_base_dn": os.environ["TEST_LDAP_BASE_DN"],
|
||||||
|
"ldap_bind_dn": os.environ["TEST_LDAP_BIND_DN"],
|
||||||
|
"ldap_password_file": Path(os.environ["TEST_LDAP_PASSWORD_FILE"]),
|
||||||
|
"ldap_group_base_dn": os.environ["TEST_LDAP_GROUP_BASE_DN"],
|
||||||
|
"ldap_ca_bundle": Path(os.environ["TEST_LDAP_CA_BUNDLE"]),
|
||||||
|
"ldap_starttls": os.environ.get("TEST_LDAP_STARTTLS", "").lower() == "true",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def dc_users() -> dict[str, dict[str, str]]:
|
||||||
|
data = json.loads(Path(os.environ["TEST_DC_USERS_FILE"]).read_text(encoding="utf-8"))
|
||||||
|
users: dict[str, dict[str, str]] = data["users"]
|
||||||
|
return users
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def directory(tmp_path: Path) -> Directory:
|
||||||
|
return Directory(make_settings(tmp_path, **ldap_values()))
|
||||||
|
|
||||||
|
|
||||||
|
def roles_of(d: Directory, login: str) -> list[str]:
|
||||||
|
u = d.find_user(login)
|
||||||
|
assert u is not None, login
|
||||||
|
return groups.roles_from_groups(d.groups_of(u.dn))
|
||||||
|
|
||||||
|
|
||||||
|
def test_password_bind(directory: Directory, dc_users: dict[str, dict[str, str]]) -> None:
|
||||||
|
u = directory.find_user("clerk.clara")
|
||||||
|
assert u is not None and not u.disabled and u.emp_no == "4001" and u.display_name == "Clara Clerk"
|
||||||
|
assert directory.verify_password(u.dn, dc_users["clerk.clara"]["password"]) is True
|
||||||
|
assert directory.verify_password(u.dn, "not-the-password") is False
|
||||||
|
assert directory.verify_password(u.dn, "") is False
|
||||||
|
assert roles_of(directory, "clerk.clara") == ["clerical"]
|
||||||
|
again = directory.get_user_by_guid(u.guid)
|
||||||
|
assert again is not None and again.sam_account == "clerk.clara"
|
||||||
|
|
||||||
|
|
||||||
|
def test_nested_and_levels(directory: Directory) -> None:
|
||||||
|
assert roles_of(directory, "nested.ned") == ["shop:10:worker"]
|
||||||
|
assert roles_of(directory, "both.bo") == ["shop:03:supervisor"]
|
||||||
|
assert roles_of(directory, "multi.mia") == ["clerical", "shop:06:supervisor"]
|
||||||
|
assert roles_of(directory, "norole.nick") == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_disabled_account(directory: Directory, dc_users: dict[str, dict[str, str]]) -> None:
|
||||||
|
u = directory.find_user("disabled.dan")
|
||||||
|
assert u is not None and u.disabled is True
|
||||||
|
assert directory.verify_password(u.dn, dc_users["disabled.dan"]["password"]) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_group_listing_and_members(directory: Directory) -> None:
|
||||||
|
found = directory.list_groups()
|
||||||
|
lower = {g.lower() for g in found}
|
||||||
|
assert "ps-14-electrical-lead" not in lower and "ps-extra-legacy" in lower
|
||||||
|
assert sum(1 for n in groups.group_names() if n.lower() in lower) == 49
|
||||||
|
sams = {u.sam_account for u in directory.members_of("PS-03-WeldParts-Worker")}
|
||||||
|
assert {"weld.andy", "both.bo", "dup.dave"} <= sams
|
||||||
|
assert directory.members_of("PS-No-Such-Group") == []
|
||||||
|
|
||||||
|
|
||||||
|
@needs_pg
|
||||||
|
def test_refresh_flags_duplicates(pg_settings: Settings, directory: Directory) -> None:
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
res = refresh_from_ad(conn, directory)
|
||||||
|
assert res.groups_missing == ["PS-14-Electrical-Lead"]
|
||||||
|
assert "9001" in res.emp_duplicate and "noemp.nora" in res.emp_missing
|
||||||
|
|
||||||
|
|
||||||
|
@needs_pg
|
||||||
|
def test_signin_api_against_dc(
|
||||||
|
pg_settings: Settings, tmp_path: Path, dev_visual: None, dc_users: dict[str, dict[str, str]]
|
||||||
|
) -> None:
|
||||||
|
from packetstation.main import create_app
|
||||||
|
|
||||||
|
s = make_settings(
|
||||||
|
tmp_path / "dc",
|
||||||
|
**ldap_values(),
|
||||||
|
**{k: getattr(pg_settings, k) for k in ("pg_host", "pg_port", "pg_database")},
|
||||||
|
pg_app_password_file=pg_settings.pg_app_password_file,
|
||||||
|
pg_migrate_password_file=pg_settings.pg_migrate_password_file,
|
||||||
|
)
|
||||||
|
with TestClient(create_app(s), headers=ORIGIN_HEADERS) as c:
|
||||||
|
|
||||||
|
def signin(sam: str, pw: str | None = None) -> Any:
|
||||||
|
password = dc_users[sam]["password"] if pw is None else pw
|
||||||
|
return c.post("/api/auth/signin/password", json={"login": sam, "password": password})
|
||||||
|
|
||||||
|
r = signin("clerk.clara")
|
||||||
|
assert r.status_code == 200 and r.json()["roles"] == ["clerical"]
|
||||||
|
assert signin("clerk.clara", "wrong").status_code == 401
|
||||||
|
assert signin("disabled.dan").status_code == 401
|
||||||
|
r = signin("norole.nick")
|
||||||
|
assert r.status_code == 403 and r.json()["code"] == "no_role"
|
||||||
|
assert signin("nested.ned").json()["roles"] == ["shop:10:worker"]
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
"""LDAP helpers and the fake directory; no domain controller needed."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fakedir import FAKE_PASSWORD, FakeDirectory
|
||||||
|
from pshelpers import make_settings
|
||||||
|
|
||||||
|
from packetstation.auth import groups
|
||||||
|
from packetstation.auth.ldap import Directory, LdapUnavailable, guid_filter, parse_guid, user_from_entry
|
||||||
|
|
||||||
|
GUID = uuid.UUID("01234567-89ab-cdef-0123-456789abcdef")
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_guid_bytes_and_string() -> None:
|
||||||
|
raw = GUID.bytes_le
|
||||||
|
assert parse_guid(raw) == GUID
|
||||||
|
assert parse_guid([raw]) == GUID
|
||||||
|
assert parse_guid("{01234567-89ab-cdef-0123-456789abcdef}") == GUID
|
||||||
|
assert parse_guid("01234567-89AB-CDEF-0123-456789ABCDEF") == GUID
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
parse_guid(b"short")
|
||||||
|
|
||||||
|
|
||||||
|
def test_guid_filter_escapes_every_byte() -> None:
|
||||||
|
flt = guid_filter(GUID)
|
||||||
|
assert flt.startswith("(objectGUID=\\67\\45\\23\\01") and flt.endswith(")")
|
||||||
|
assert flt.count("\\") == 16
|
||||||
|
|
||||||
|
|
||||||
|
def test_user_from_entry() -> None:
|
||||||
|
entry = {
|
||||||
|
"dn": "CN=Andy,DC=x",
|
||||||
|
"raw_attributes": {"objectGUID": [GUID.bytes_le]},
|
||||||
|
"attributes": {
|
||||||
|
"sAMAccountName": ["weld.andy"],
|
||||||
|
"userPrincipalName": ["[email protected]"],
|
||||||
|
"displayName": ["Andy Welder"],
|
||||||
|
"employeeID": ["0303"],
|
||||||
|
"mail": [],
|
||||||
|
"userAccountControl": ["514"],
|
||||||
|
"distinguishedName": ["CN=Andy,DC=x"],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
u = user_from_entry(entry)
|
||||||
|
assert u.guid == GUID and u.sam_account == "weld.andy" and u.display_name == "Andy Welder"
|
||||||
|
assert u.emp_no == "0303" # text, leading zero kept
|
||||||
|
assert u.email is None and u.disabled is True and u.dn == "CN=Andy,DC=x"
|
||||||
|
|
||||||
|
|
||||||
|
def test_plain_ldap_refused_without_starttls(tmp_path: Path) -> None:
|
||||||
|
pw = tmp_path / "pw"
|
||||||
|
pw.write_text("x")
|
||||||
|
s = make_settings(tmp_path, ldap_url="ldap://dc.example:389", ldap_bind_dn="CN=svc", ldap_password_file=pw)
|
||||||
|
with pytest.raises(LdapUnavailable, match="plain LDAP"):
|
||||||
|
Directory(s).find_user("someone")
|
||||||
|
|
||||||
|
|
||||||
|
def test_empty_password_never_binds(tmp_path: Path) -> None:
|
||||||
|
s = make_settings(tmp_path, ldap_url="ldaps://dc.invalid:636")
|
||||||
|
assert Directory(s).verify_password("CN=x,DC=y", "") is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_service_secret_is_unavailable(tmp_path: Path) -> None:
|
||||||
|
s = make_settings(
|
||||||
|
tmp_path, ldap_url="ldaps://dc.invalid:636", ldap_bind_dn="CN=svc", ldap_password_file=tmp_path / "none"
|
||||||
|
)
|
||||||
|
with pytest.raises(LdapUnavailable, match="LDAP_PASSWORD_FILE"):
|
||||||
|
Directory(s).list_groups()
|
||||||
|
|
||||||
|
|
||||||
|
def test_fake_directory_nested_and_ou() -> None:
|
||||||
|
d = FakeDirectory()
|
||||||
|
ned = d.find_user("NESTED.NED")
|
||||||
|
assert ned is not None
|
||||||
|
assert groups.roles_from_groups(d.groups_of(ned.dn)) == ["shop:10:worker"]
|
||||||
|
bo = d.find_user("[email protected]")
|
||||||
|
assert bo is not None
|
||||||
|
assert groups.roles_from_groups(d.groups_of(bo.dn)) == ["shop:03:supervisor"]
|
||||||
|
assert "PS-14-Electrical-Lead" not in d.list_groups() and "PS-Extra-Legacy" in d.list_groups()
|
||||||
|
sams = {u.sam_account for u in d.members_of("PS-03-WeldParts-Worker")}
|
||||||
|
assert {"weld.andy", "both.bo", "dup.dave", "disabled.dan"} <= sams
|
||||||
|
assert d.verify_password(bo.dn, FAKE_PASSWORD) and not d.verify_password(bo.dn, "nope")
|
||||||
|
assert d.verify_password(bo.dn, "") is False
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fakedir import FakeDirectory
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from pshelpers import ORIGIN_HEADERS, make_settings
|
||||||
|
|
||||||
|
from packetstation.api.origin import allowed
|
||||||
|
from packetstation.main import create_app
|
||||||
|
|
||||||
|
|
||||||
|
def scope(method: str = "POST", path: str = "/api/auth/lock", scheme: str = "https", **headers: str) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"type": "http",
|
||||||
|
"method": method,
|
||||||
|
"path": path,
|
||||||
|
"scheme": scheme,
|
||||||
|
"headers": [(k.replace("_", "-").encode(), v.encode()) for k, v in headers.items()],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_allowed_rules() -> None:
|
||||||
|
good = {"host": "ps.pesco.com", "origin": "https://ps.pesco.com", "x_requested_with": "PacketStation"}
|
||||||
|
assert allowed(scope(**good))
|
||||||
|
assert allowed(scope(method="GET", host="ps.pesco.com")) # safe methods pass
|
||||||
|
assert allowed(scope(path="/healthz", host="x")) # outside /api
|
||||||
|
assert not allowed(scope(**{**good, "origin": "https://evil.example"}))
|
||||||
|
assert not allowed(scope(**{**good, "origin": "http://ps.pesco.com"})) # scheme must match
|
||||||
|
assert not allowed(scope(host="ps.pesco.com", origin="https://ps.pesco.com")) # marker missing
|
||||||
|
assert not allowed(scope(**{**good, "x_requested_with": "XMLHttpRequest"}))
|
||||||
|
no_origin = {"host": "ps.pesco.com", "x_requested_with": "PacketStation"}
|
||||||
|
assert not allowed(scope(**no_origin))
|
||||||
|
assert allowed(scope(**no_origin, referer="https://ps.pesco.com/account"))
|
||||||
|
assert not allowed(scope(**no_origin, referer="https://ps.pesco.com.evil.example/"))
|
||||||
|
for method in ("PUT", "PATCH", "DELETE"):
|
||||||
|
assert not allowed(scope(method=method, host="ps.pesco.com"))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client(tmp_path: Path, dev_visual: None) -> TestClient:
|
||||||
|
return TestClient(create_app(make_settings(tmp_path), directory=FakeDirectory()))
|
||||||
|
|
||||||
|
|
||||||
|
def test_wrong_origin_refused_on_signin(client: TestClient) -> None:
|
||||||
|
body = {"login": "clerk.clara", "password": "x"}
|
||||||
|
r = client.post("/api/auth/signin/password", json=body, headers={**ORIGIN_HEADERS, "Origin": "http://evil.example"})
|
||||||
|
assert r.status_code == 403
|
||||||
|
assert r.json() == {"detail": "Cross-origin request refused", "code": "bad_origin"}
|
||||||
|
assert r.headers["x-frame-options"] == "DENY"
|
||||||
|
r = client.post("/api/auth/signin/password", json=body, headers={"Origin": "http://testserver"})
|
||||||
|
assert r.status_code == 403 and r.json()["code"] == "bad_origin"
|
||||||
|
|
||||||
|
|
||||||
|
def test_right_origin_passes_the_check(client: TestClient) -> None:
|
||||||
|
# No database here, so the request gets past the Origin check and stops at the database
|
||||||
|
r = client.post("/api/auth/signin/password", json={"login": "a", "password": "b"}, headers=ORIGIN_HEADERS)
|
||||||
|
assert r.status_code == 503
|
||||||
|
assert r.json()["code"] == "database_unavailable"
|
||||||
|
|
||||||
|
|
||||||
|
def test_me_without_cookie_is_no_session(client: TestClient) -> None:
|
||||||
|
r = client.get("/api/auth/me")
|
||||||
|
assert r.status_code == 401
|
||||||
|
assert r.json()["code"] == "no_session"
|
||||||
|
assert client.get("/api/events").json()["code"] == "no_session"
|
||||||
|
assert client.get("/api/account").status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_context_without_device(client: TestClient) -> None:
|
||||||
|
r = client.get("/api/auth/context")
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert r.json() == {"device": None, "stack": "ci", "insecure_ldap": False, "pin_digits": {"min": 6, "max": 12}}
|
||||||
|
|
||||||
|
|
||||||
|
def test_validation_error_carries_a_code(client: TestClient) -> None:
|
||||||
|
r = client.post("/api/auth/signin/password", json={"login": "x"}, headers=ORIGIN_HEADERS)
|
||||||
|
assert r.status_code == 422
|
||||||
|
assert r.json()["code"] == "invalid_request"
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_session_key_fails_cleanly(tmp_path: Path, dev_visual: None) -> None:
|
||||||
|
s = make_settings(tmp_path, session_key_file=tmp_path / "missing")
|
||||||
|
c = TestClient(create_app(s, directory=FakeDirectory()))
|
||||||
|
r = c.post("/api/auth/signin/password", json={"login": "a", "password": "b"}, headers=ORIGIN_HEADERS)
|
||||||
|
assert r.status_code == 503
|
||||||
|
assert r.json()["code"] == "server_misconfigured"
|
||||||
|
assert str(tmp_path) not in r.json()["detail"]
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
"""The Packet Station PIN: format, hashing, and the whole lifecycle through the API."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fakedir import FAKE_PASSWORD, FakeDirectory
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from pshelpers import PIN, app_conn, make_settings, needs_pg, pin_signin, register_device, set_pin, sign_in
|
||||||
|
|
||||||
|
from packetstation.auth import pin as pins
|
||||||
|
from packetstation.settings import Settings
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("value", "ok"),
|
||||||
|
[
|
||||||
|
("123456", True),
|
||||||
|
("123456789012", True),
|
||||||
|
("12345", False),
|
||||||
|
("1234567890123", False),
|
||||||
|
("12345a", False),
|
||||||
|
("١٢٣٤٥٦", False),
|
||||||
|
("", False),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_format(tmp_path: Path, value: str, ok: bool) -> None:
|
||||||
|
assert pins.valid_format(value, make_settings(tmp_path)) is ok
|
||||||
|
|
||||||
|
|
||||||
|
def test_hash_is_argon2id_and_verifies() -> None:
|
||||||
|
h = pins.hash_pin(PIN)
|
||||||
|
assert h.startswith("$argon2id$") and PIN not in h
|
||||||
|
assert pins.verify_hash(h, PIN) and not pins.verify_hash(h, "135791") and not pins.verify_hash("junk", PIN)
|
||||||
|
|
||||||
|
|
||||||
|
@needs_pg
|
||||||
|
def test_pin_needs_a_registered_device(pg_client: TestClient) -> None:
|
||||||
|
set_pin(pg_client, "weld.andy")
|
||||||
|
r = pg_client.post("/api/auth/signin/pin", json={"emp_no": "3003", "pin": PIN})
|
||||||
|
assert r.status_code == 403 and r.json()["code"] == "device_required"
|
||||||
|
assert pg_client.get("/api/auth/context").json()["device"] is None
|
||||||
|
|
||||||
|
|
||||||
|
@needs_pg
|
||||||
|
def test_only_registrars_register_devices(pg_client: TestClient) -> None:
|
||||||
|
sign_in(pg_client, "weld.andy")
|
||||||
|
r = pg_client.post("/api/account/device", json={"name": "x"})
|
||||||
|
assert r.status_code == 403
|
||||||
|
sign_in(pg_client, "lead.lou")
|
||||||
|
assert pg_client.post("/api/account/device", json={"name": "x"}).status_code == 403
|
||||||
|
sign_in(pg_client, "admin.ann")
|
||||||
|
assert pg_client.post("/api/account/device", json={"name": "Office PC"}).status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
@needs_pg
|
||||||
|
def test_pin_set_rules(pg_client: TestClient, pg_settings: Settings) -> None:
|
||||||
|
sign_in(pg_client, "weld.andy")
|
||||||
|
r = pg_client.post("/api/account/pin", json={"password": FAKE_PASSWORD, "pin": "12ab56"})
|
||||||
|
assert r.status_code == 400 and r.json()["code"] == "invalid_pin"
|
||||||
|
r = pg_client.post("/api/account/pin", json={"password": "wrong", "pin": PIN})
|
||||||
|
assert r.status_code == 403 and r.json()["code"] == "bad_password"
|
||||||
|
assert pg_client.get("/api/account").json()["pin"] == {"set": False, "disabled": False}
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
row = conn.execute("SELECT account, kind, reason FROM signin_attempts WHERE NOT ok").fetchone()
|
||||||
|
assert row[0].startswith("user:") and row[1:] == ("pin_set", "bad_password")
|
||||||
|
assert conn.execute("SELECT count(*) FROM user_pins").fetchone()[0] == 0
|
||||||
|
|
||||||
|
|
||||||
|
@needs_pg
|
||||||
|
def test_pin_lifecycle(pg_client: TestClient, pg_settings: Settings, fake_dir: FakeDirectory) -> None:
|
||||||
|
device = register_device(pg_client)
|
||||||
|
assert pg_client.get("/api/auth/context").json()["device"] == device
|
||||||
|
set_pin(pg_client, "weld.andy")
|
||||||
|
|
||||||
|
r = pin_signin(pg_client, "3003")
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
me = r.json()
|
||||||
|
assert me["session"]["kind"] == "pin" and me["session"]["device"] == device
|
||||||
|
assert me["roles"] == ["shop:03:worker"] and me["pin"] == {"set": True, "disabled": False}
|
||||||
|
# A PIN session cannot change account settings
|
||||||
|
r = pg_client.post("/api/account/pin", json={"password": FAKE_PASSWORD, "pin": "135791"})
|
||||||
|
assert r.status_code == 403 and r.json()["code"] == "password_session_required"
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
hours = conn.execute(
|
||||||
|
"SELECT extract(epoch FROM expires_at - created_at) / 3600 FROM sessions WHERE id = %s",
|
||||||
|
(me["session"]["id"],),
|
||||||
|
).fetchone()[0]
|
||||||
|
assert float(hours) == 10
|
||||||
|
detail = conn.execute(
|
||||||
|
"SELECT detail FROM audit_events WHERE action = 'auth.signin' ORDER BY id DESC"
|
||||||
|
).fetchone()
|
||||||
|
assert detail[0] == {"kind": "pin", "device_id": device["id"], "device_name": device["name"]}
|
||||||
|
log = pg_client.get("/api/account/access-log").json()
|
||||||
|
assert any(e["action"] == "auth.signin" and e["detail"]["device_name"] == device["name"] for e in log)
|
||||||
|
pg_client.post("/api/auth/signout")
|
||||||
|
|
||||||
|
# Unknown, duplicate and wrong all answer the same
|
||||||
|
for emp in ("0000", "9001"):
|
||||||
|
r = pin_signin(pg_client, emp)
|
||||||
|
assert r.status_code == 401 and r.json() == {"detail": "Sign-in failed.", "code": "signin_failed"}
|
||||||
|
|
||||||
|
# Five wrong PINs disable it
|
||||||
|
for _ in range(5):
|
||||||
|
assert pin_signin(pg_client, "3003", "000000").status_code == 401
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
failed, disabled = conn.execute("SELECT failed_count, disabled_at IS NOT NULL FROM user_pins").fetchone()
|
||||||
|
assert failed == 5 and disabled
|
||||||
|
assert conn.execute("SELECT count(*) FROM audit_events WHERE action = 'pin.disabled'").fetchone()[0] == 1
|
||||||
|
assert pin_signin(pg_client, "3003").status_code in (401, 429) # disabled (and the account is now limited)
|
||||||
|
|
||||||
|
# A password sign-in and a new PIN bring it back
|
||||||
|
set_pin(pg_client, "weld.andy", "13579135")
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
assert conn.execute("SELECT failed_count, disabled_at FROM user_pins").fetchone() == (0, None)
|
||||||
|
assert conn.execute("SELECT count(*) FROM audit_events WHERE action = 'pin.set'").fetchone()[0] == 2
|
||||||
|
|
||||||
|
|
||||||
|
@needs_pg
|
||||||
|
def test_pin_unlock_failures_count_and_end_session(pg_client: TestClient, pg_settings: Settings) -> None:
|
||||||
|
register_device(pg_client)
|
||||||
|
set_pin(pg_client, "weld.andy")
|
||||||
|
assert pin_signin(pg_client, "3003").status_code == 200
|
||||||
|
pg_client.post("/api/auth/lock")
|
||||||
|
r = pg_client.post("/api/auth/unlock", json={"factor": "pin", "secret": "111111"})
|
||||||
|
assert r.status_code == 403 and r.json()["attempts_left"] == 2
|
||||||
|
r = pg_client.post("/api/auth/unlock", json={"factor": "pin", "secret": PIN})
|
||||||
|
assert r.status_code == 200 and r.json()["session"]["locked"] is False
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
assert conn.execute("SELECT failed_count FROM user_pins").fetchone()[0] == 0
|
||||||
|
pg_client.post("/api/auth/lock")
|
||||||
|
for _ in range(2):
|
||||||
|
assert pg_client.post("/api/auth/unlock", json={"factor": "pin", "secret": "111111"}).status_code == 403
|
||||||
|
r = pg_client.post("/api/auth/unlock", json={"factor": "pin", "secret": "111111"})
|
||||||
|
assert r.status_code == 401 and r.json()["code"] == "session_ended"
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
assert conn.execute("SELECT failed_count FROM user_pins").fetchone()[0] == 3
|
||||||
|
reason = conn.execute("SELECT revoked_reason FROM sessions WHERE kind = 'pin'").fetchone()[0]
|
||||||
|
assert reason == "stepup_failures"
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from pshelpers import needs_pg
|
||||||
|
|
||||||
|
from packetstation import db
|
||||||
|
from packetstation.auth import ratelimit
|
||||||
|
from packetstation.settings import Settings
|
||||||
|
|
||||||
|
T0 = datetime(2026, 10, 16, 8, 0, tzinfo=UTC)
|
||||||
|
W = timedelta(minutes=5)
|
||||||
|
C = timedelta(minutes=10)
|
||||||
|
|
||||||
|
|
||||||
|
def m(n: float) -> datetime:
|
||||||
|
return T0 + timedelta(minutes=n)
|
||||||
|
|
||||||
|
|
||||||
|
def test_account_under_limit_is_free() -> None:
|
||||||
|
assert ratelimit.account_block_until([m(0), m(1), m(2), m(3)], limit=5, window=W, cooldown=C) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_account_limit_hit_blocks_for_cooldown_from_the_fifth() -> None:
|
||||||
|
fails = [m(0), m(1), m(2), m(3), m(4)]
|
||||||
|
until = ratelimit.account_block_until(fails, limit=5, window=W, cooldown=C)
|
||||||
|
assert until == m(14)
|
||||||
|
# Still refused after the failures leave the window: the cooldown is longer than the window
|
||||||
|
assert ratelimit.retry_seconds(until, m(9)) == 300
|
||||||
|
assert ratelimit.retry_seconds(until, m(14)) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_account_failures_spread_wider_than_window_do_not_block() -> None:
|
||||||
|
fails = [m(0), m(2), m(4), m(6), m(8), m(10)]
|
||||||
|
assert ratelimit.account_block_until(fails, limit=5, window=W, cooldown=C) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_ip_rule_counts_only_the_last_window() -> None:
|
||||||
|
now = m(10)
|
||||||
|
fails = [m(4.5)] + [m(6 + i * 0.1) for i in range(29)]
|
||||||
|
assert ratelimit.ip_block_until(fails, now=now, limit=30, window=W) is None # m(4.5) is out of the window
|
||||||
|
fails.append(m(9))
|
||||||
|
until = ratelimit.ip_block_until(fails, now=now, limit=30, window=W)
|
||||||
|
assert until == m(11) # the oldest of the 30 (m(6)) leaves the window at m(11)
|
||||||
|
assert ratelimit.retry_seconds(until, now) == 60
|
||||||
|
|
||||||
|
|
||||||
|
def test_retry_seconds_rounds_up() -> None:
|
||||||
|
assert ratelimit.retry_seconds(T0 + timedelta(seconds=0.2), T0) == 1
|
||||||
|
assert ratelimit.retry_seconds(None, T0) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_record_refuses_unknown_kind() -> None:
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
ratelimit.record(None, account="x", ip=None, kind="sneaky", ok=False)
|
||||||
|
|
||||||
|
|
||||||
|
@needs_pg
|
||||||
|
def test_pg_check_with_explicit_times(pg_settings: Settings) -> None:
|
||||||
|
with db.connect_as("app", pg_settings, autocommit=True) as conn:
|
||||||
|
now = ratelimit.db_now(conn)
|
||||||
|
acct = "weld.andy"
|
||||||
|
for i in range(4):
|
||||||
|
ratelimit.record(
|
||||||
|
conn, account=acct, ip="10.0.0.9", kind="password", ok=False, reason="bad_password", at=now - W / 5 * i
|
||||||
|
)
|
||||||
|
# A success and rate-limited refusals never count
|
||||||
|
ratelimit.record(conn, account=acct, ip="10.0.0.9", kind="password", ok=True, at=now)
|
||||||
|
ratelimit.record(conn, account=acct, ip="10.0.0.9", kind="password", ok=False, reason="rate_limited", at=now)
|
||||||
|
assert ratelimit.check(conn, pg_settings, accounts=[acct], ip="10.0.0.9", now=now) is None
|
||||||
|
ratelimit.record(conn, account=acct, ip="10.0.0.9", kind="password", ok=False, reason="bad_password", at=now)
|
||||||
|
wait = ratelimit.check(conn, pg_settings, accounts=[acct], ip="10.0.0.9", now=now)
|
||||||
|
assert wait == 600
|
||||||
|
# Another account from the same address is still allowed
|
||||||
|
assert ratelimit.check(conn, pg_settings, accounts=["clerk.clara"], ip="10.0.0.9", now=now) is None
|
||||||
|
# Aliases count together
|
||||||
|
assert ratelimit.check(conn, pg_settings, accounts=["andy@x", acct], ip=None, now=now) == 600
|
||||||
|
# After the cooldown the account may try again
|
||||||
|
assert ratelimit.check(conn, pg_settings, accounts=[acct], ip=None, now=now + C + timedelta(seconds=1)) is None
|
||||||
|
|
||||||
|
|
||||||
|
@needs_pg
|
||||||
|
def test_pg_ip_limit(pg_settings: Settings) -> None:
|
||||||
|
with db.connect_as("app", pg_settings, autocommit=True) as conn:
|
||||||
|
now = ratelimit.db_now(conn)
|
||||||
|
for i in range(30):
|
||||||
|
ratelimit.record(
|
||||||
|
conn, account=f"user{i}", ip="10.9.9.9", kind="password", ok=False, reason="no_such_user", at=now
|
||||||
|
)
|
||||||
|
assert ratelimit.check(conn, pg_settings, accounts=["fresh"], ip="10.9.9.9", now=now) == 300
|
||||||
|
assert ratelimit.check(conn, pg_settings, accounts=["fresh"], ip="10.9.9.8", now=now) is None
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
"""Session timeouts and the roles refresh, enforced by the server."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from fakedir import FakeDirectory
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from pshelpers import ORIGIN_HEADERS, app_conn, make_settings, needs_pg, sign_in
|
||||||
|
|
||||||
|
from packetstation.auth import sessions
|
||||||
|
from packetstation.settings import Settings
|
||||||
|
|
||||||
|
pytestmark = needs_pg
|
||||||
|
|
||||||
|
|
||||||
|
def _age(settings: Settings, sql: str) -> None:
|
||||||
|
with app_conn(settings) as conn:
|
||||||
|
conn.execute(sql)
|
||||||
|
|
||||||
|
|
||||||
|
def test_token_is_stored_only_as_hmac(pg_client: TestClient, pg_settings: Settings) -> None:
|
||||||
|
sign_in(pg_client, "clerk.clara")
|
||||||
|
token = pg_client.cookies.get(sessions.SESSION_COOKIE)
|
||||||
|
assert token
|
||||||
|
key = pg_settings.session_key()
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
stored = bytes(conn.execute("SELECT token_hash FROM sessions").fetchone()[0])
|
||||||
|
assert stored == sessions.token_hash(key, token) and token.encode() not in stored
|
||||||
|
|
||||||
|
|
||||||
|
def test_idle_lock_after_lock_minutes(pg_client: TestClient, pg_settings: Settings) -> None:
|
||||||
|
sign_in(pg_client, "clerk.clara")
|
||||||
|
_age(pg_settings, "UPDATE sessions SET last_seen_at = now() - interval '4 minutes'")
|
||||||
|
r = pg_client.get("/api/account")
|
||||||
|
assert r.status_code == 423 and r.json()["code"] == "locked"
|
||||||
|
assert pg_client.get("/api/auth/me").json()["session"]["locked"] is True
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
assert conn.execute("SELECT locked_since IS NOT NULL FROM sessions").fetchone()[0]
|
||||||
|
lock = conn.execute("SELECT detail FROM audit_events WHERE action = 'auth.lock'").fetchone()[0]
|
||||||
|
assert lock == {"source": "idle"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_hidden_tab_locks_only_after_a_minute(pg_client: TestClient, pg_settings: Settings) -> None:
|
||||||
|
sign_in(pg_client, "clerk.clara")
|
||||||
|
# A reload fires a hidden report and the next request follows at once: no lock
|
||||||
|
assert pg_client.post("/api/auth/visibility", json={"hidden": True}, headers=ORIGIN_HEADERS).status_code == 204
|
||||||
|
assert pg_client.get("/api/account").status_code == 200
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
assert conn.execute("SELECT hidden_since IS NULL AND locked_since IS NULL FROM sessions").fetchone()[0]
|
||||||
|
# Hidden for over a minute: the visible report (or any request) locks
|
||||||
|
assert pg_client.post("/api/auth/visibility", json={"hidden": True}, headers=ORIGIN_HEADERS).status_code == 204
|
||||||
|
_age(pg_settings, "UPDATE sessions SET hidden_since = now() - interval '61 seconds'")
|
||||||
|
assert pg_client.post("/api/auth/visibility", json={"hidden": False}, headers=ORIGIN_HEADERS).status_code == 204
|
||||||
|
r = pg_client.get("/api/account")
|
||||||
|
assert r.status_code == 423 and r.json()["code"] == "locked"
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
lock = conn.execute("SELECT detail FROM audit_events WHERE action = 'auth.lock'").fetchone()[0]
|
||||||
|
assert lock == {"source": "hidden"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_idle_signout_after_idle_minutes(pg_client: TestClient, pg_settings: Settings) -> None:
|
||||||
|
sign_in(pg_client, "clerk.clara")
|
||||||
|
_age(pg_settings, "UPDATE sessions SET last_seen_at = now() - interval '16 minutes'")
|
||||||
|
r = pg_client.get("/api/auth/me")
|
||||||
|
assert r.status_code == 401 and r.json()["code"] == "session_expired"
|
||||||
|
assert pg_client.get("/api/auth/me").json()["code"] == "no_session"
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
assert conn.execute("SELECT revoked_reason FROM sessions").fetchone()[0] == "idle"
|
||||||
|
ended = conn.execute("SELECT detail FROM audit_events WHERE action = 'auth.session_ended'").fetchone()[0]
|
||||||
|
assert ended == {"reason": "idle"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_locked_session_does_not_stay_alive_by_polling(pg_client: TestClient, pg_settings: Settings) -> None:
|
||||||
|
sign_in(pg_client, "clerk.clara")
|
||||||
|
pg_client.post("/api/auth/lock")
|
||||||
|
_age(pg_settings, "UPDATE sessions SET last_seen_at = now() - interval '14 minutes'")
|
||||||
|
assert pg_client.get("/api/auth/me").status_code == 200
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
age = conn.execute("SELECT now() - last_seen_at > interval '13 minutes' FROM sessions").fetchone()[0]
|
||||||
|
assert age # /me while locked does not count as activity
|
||||||
|
|
||||||
|
|
||||||
|
def test_last_seen_updates_after_30_seconds(pg_client: TestClient, pg_settings: Settings) -> None:
|
||||||
|
sign_in(pg_client, "clerk.clara")
|
||||||
|
_age(pg_settings, "UPDATE sessions SET last_seen_at = now() - interval '2 minutes'")
|
||||||
|
pg_client.get("/api/account")
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
assert conn.execute("SELECT now() - last_seen_at < interval '10 seconds' FROM sessions").fetchone()[0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_absolute_expiry(pg_client: TestClient, pg_settings: Settings) -> None:
|
||||||
|
sign_in(pg_client, "clerk.clara")
|
||||||
|
_age(pg_settings, "UPDATE sessions SET expires_at = now() - interval '1 second'")
|
||||||
|
r = pg_client.get("/api/auth/me")
|
||||||
|
assert r.status_code == 401 and r.json()["code"] == "no_session"
|
||||||
|
|
||||||
|
|
||||||
|
def test_session_hours_are_settings(
|
||||||
|
pg_settings: Settings, fake_dir: FakeDirectory, dev_visual: None, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
from pshelpers import ORIGIN_HEADERS
|
||||||
|
|
||||||
|
from packetstation.main import create_app
|
||||||
|
|
||||||
|
s = make_settings(
|
||||||
|
tmp_path / "s2",
|
||||||
|
**{k: getattr(pg_settings, k) for k in ("pg_host", "pg_port", "pg_database")},
|
||||||
|
pg_app_password_file=pg_settings.pg_app_password_file,
|
||||||
|
pg_migrate_password_file=pg_settings.pg_migrate_password_file,
|
||||||
|
session_password_hours=3,
|
||||||
|
)
|
||||||
|
with TestClient(create_app(s, directory=fake_dir), headers=ORIGIN_HEADERS) as c:
|
||||||
|
me = sign_in(c, "clerk.clara").json()
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
hours = conn.execute(
|
||||||
|
"SELECT extract(epoch FROM expires_at - created_at) / 3600 FROM sessions WHERE id = %s",
|
||||||
|
(me["session"]["id"],),
|
||||||
|
).fetchone()[0]
|
||||||
|
assert float(hours) == 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_roles_refresh_rewrites_snapshot(pg_client: TestClient, pg_settings: Settings, fake_dir: FakeDirectory) -> None:
|
||||||
|
assert sign_in(pg_client, "weld.andy").json()["roles"] == ["shop:03:worker"]
|
||||||
|
fake_dir.user("weld.andy").groups = ["PS-03-WeldParts-Lead", "PS-QC"]
|
||||||
|
assert pg_client.get("/api/auth/me").json()["roles"] == ["shop:03:worker"] # not due yet
|
||||||
|
_age(pg_settings, "UPDATE sessions SET roles_checked_at = now() - interval '16 minutes'")
|
||||||
|
me = pg_client.get("/api/auth/me").json()
|
||||||
|
assert me["roles"] == ["qc", "shop:03:lead"] and me["screens"] == ["supervisor", "stall", "qc"]
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
rows = conn.execute("SELECT role::text, dept_code FROM user_roles ORDER BY role").fetchall()
|
||||||
|
assert rows == [("qc", "QC"), ("shop_lead", "03")]
|
||||||
|
snap = conn.execute("SELECT roles_snapshot FROM sessions").fetchone()[0]
|
||||||
|
assert snap["groups"] == ["PS-03-WeldParts-Lead", "PS-QC"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_roles_refresh_ends_session_when_roles_gone(
|
||||||
|
pg_client: TestClient, pg_settings: Settings, fake_dir: FakeDirectory
|
||||||
|
) -> None:
|
||||||
|
sign_in(pg_client, "weld.andy")
|
||||||
|
fake_dir.user("weld.andy").groups = []
|
||||||
|
_age(pg_settings, "UPDATE sessions SET roles_checked_at = now() - interval '16 minutes'")
|
||||||
|
r = pg_client.get("/api/auth/me")
|
||||||
|
assert r.status_code == 401 and r.json()["code"] == "session_expired"
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
assert conn.execute("SELECT revoked_reason FROM sessions").fetchone()[0] == "roles_lost"
|
||||||
|
assert conn.execute("SELECT count(*) FROM user_roles").fetchone()[0] == 0
|
||||||
|
assert conn.execute("SELECT active FROM users").fetchone()[0] is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_roles_refresh_disabled_account(pg_client: TestClient, pg_settings: Settings, fake_dir: FakeDirectory) -> None:
|
||||||
|
sign_in(pg_client, "weld.andy")
|
||||||
|
fake_dir.user("weld.andy").disabled = True
|
||||||
|
_age(pg_settings, "UPDATE sessions SET roles_checked_at = now() - interval '16 minutes'")
|
||||||
|
assert pg_client.get("/api/auth/me").json()["code"] == "session_expired"
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
assert conn.execute("SELECT active FROM users").fetchone()[0] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_roles_refresh_keeps_roles_when_ad_down(
|
||||||
|
pg_client: TestClient, pg_settings: Settings, fake_dir: FakeDirectory
|
||||||
|
) -> None:
|
||||||
|
sign_in(pg_client, "weld.andy")
|
||||||
|
fake_dir.down = True
|
||||||
|
_age(pg_settings, "UPDATE sessions SET roles_checked_at = now() - interval '16 minutes'")
|
||||||
|
assert pg_client.get("/api/auth/me").json()["roles"] == ["shop:03:worker"]
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
assert conn.execute("SELECT now() - roles_checked_at < interval '1 minute' FROM sessions").fetchone()[0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_signout_others(pg_client: TestClient, pg_settings: Settings, fake_dir: FakeDirectory) -> None:
|
||||||
|
from pshelpers import ORIGIN_HEADERS
|
||||||
|
|
||||||
|
from packetstation.main import create_app
|
||||||
|
|
||||||
|
with TestClient(create_app(pg_settings, directory=fake_dir), headers=ORIGIN_HEADERS) as other:
|
||||||
|
sign_in(other, "clerk.clara")
|
||||||
|
sign_in(pg_client, "clerk.clara")
|
||||||
|
listed = pg_client.get("/api/account/sessions").json()
|
||||||
|
assert len(listed) == 2 and sum(s["current"] for s in listed) == 1
|
||||||
|
assert pg_client.post("/api/account/sessions/signout-others").json() == {"revoked": 1}
|
||||||
|
assert other.get("/api/auth/me").json()["code"] == "no_session"
|
||||||
|
assert pg_client.get("/api/auth/me").status_code == 200
|
||||||
|
log = pg_client.get("/api/account/access-log").json()
|
||||||
|
assert log[0]["action"] == "auth.signout_others" and log[0]["detail"] == {"count": 1} and log[0]["ok"] is True
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
"""signatures.sign: step-up, the append-only row, its content hash and the audit row."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import uuid
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import psycopg
|
||||||
|
import pytest
|
||||||
|
from fakedir import FAKE_PASSWORD, FakeDirectory
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from pshelpers import PIN, app_conn, needs_pg, set_pin, sign_in
|
||||||
|
|
||||||
|
from packetstation import audit
|
||||||
|
from packetstation.api.errors import ApiError
|
||||||
|
from packetstation.auth import sessions, signatures
|
||||||
|
from packetstation.settings import Settings
|
||||||
|
|
||||||
|
|
||||||
|
def test_content_hash_is_canonical() -> None:
|
||||||
|
a = signatures.content_hash({"b": [1, 2], "a": "7A"})
|
||||||
|
b = signatures.content_hash({"a": "7A", "b": [1, 2]})
|
||||||
|
assert a == b == hashlib.sha256(b'{"a":"7A","b":[1,2]}').digest()
|
||||||
|
assert signatures.content_hash(None) is None
|
||||||
|
|
||||||
|
|
||||||
|
def _actor(conn: Any, sam: str) -> sessions.Actor:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT s.id, u.id, u.sam_account, u.display_name, s.kind::text"
|
||||||
|
" FROM sessions s JOIN users u ON u.id = s.user_id"
|
||||||
|
" WHERE u.sam_account = %s AND s.revoked_at IS NULL ORDER BY s.created_at DESC LIMIT 1",
|
||||||
|
(sam,),
|
||||||
|
).fetchone()
|
||||||
|
assert row is not None
|
||||||
|
return sessions.Actor(row[0], row[1], row[2], row[3], row[4], ("shop:03:worker",))
|
||||||
|
|
||||||
|
|
||||||
|
@needs_pg
|
||||||
|
def test_sign_with_pin_and_password(pg_client: TestClient, pg_settings: Settings, fake_dir: FakeDirectory) -> None:
|
||||||
|
set_pin(pg_client, "weld.andy")
|
||||||
|
sign_in(pg_client, "weld.andy")
|
||||||
|
content = {"packet": "L662001/1", "lot": "7A", "step": "submit"}
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
actor = _actor(conn, "weld.andy")
|
||||||
|
sig = signatures.sign(
|
||||||
|
conn,
|
||||||
|
fake_dir,
|
||||||
|
actor,
|
||||||
|
factor="pin",
|
||||||
|
secret=PIN,
|
||||||
|
action="packet.submit",
|
||||||
|
meaning="Work complete",
|
||||||
|
packet_id=12,
|
||||||
|
subject_type="packet",
|
||||||
|
subject_id=12,
|
||||||
|
content=content,
|
||||||
|
settings=pg_settings,
|
||||||
|
)
|
||||||
|
assert sig.content_hash == signatures.content_hash(content) and sig.factor == "pin"
|
||||||
|
sig2 = signatures.sign(
|
||||||
|
conn,
|
||||||
|
fake_dir,
|
||||||
|
actor,
|
||||||
|
factor="password",
|
||||||
|
secret=FAKE_PASSWORD,
|
||||||
|
action="x",
|
||||||
|
meaning=None,
|
||||||
|
settings=pg_settings,
|
||||||
|
)
|
||||||
|
assert sig2.id > sig.id and sig2.content_hash is None
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT account, display_name, session_kind::text, factor::text, action, packet_id, subject_id,"
|
||||||
|
" content_hash FROM signatures WHERE id = %s",
|
||||||
|
(sig.id,),
|
||||||
|
).fetchone()
|
||||||
|
assert row[:7] == ("weld.andy", "Andy Welder", "password", "pin", "packet.submit", 12, "12")
|
||||||
|
assert bytes(row[7]) == signatures.content_hash(content)
|
||||||
|
detail = conn.execute("SELECT detail FROM audit_events WHERE action = 'sig.signed' ORDER BY id").fetchone()[0]
|
||||||
|
assert detail == {"signature_id": sig.id, "action": "packet.submit", "factor": "pin"}
|
||||||
|
for stmt in ("UPDATE signatures SET action = 'x'", "DELETE FROM signatures", "TRUNCATE signatures"):
|
||||||
|
with pytest.raises(psycopg.errors.InsufficientPrivilege):
|
||||||
|
conn.execute(stmt)
|
||||||
|
for stmt in ("UPDATE signin_attempts SET ok = true", "DELETE FROM signin_attempts"):
|
||||||
|
with pytest.raises(psycopg.errors.InsufficientPrivilege):
|
||||||
|
conn.execute(stmt)
|
||||||
|
assert audit.verify_chain(conn)[0]
|
||||||
|
|
||||||
|
|
||||||
|
@needs_pg
|
||||||
|
def test_wrong_signatures_end_the_session(
|
||||||
|
pg_client: TestClient, pg_settings: Settings, fake_dir: FakeDirectory
|
||||||
|
) -> None:
|
||||||
|
sign_in(pg_client, "weld.andy")
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
actor = _actor(conn, "weld.andy")
|
||||||
|
for code in ("wrong_secret", "wrong_secret", "session_ended"):
|
||||||
|
with pytest.raises(ApiError) as e:
|
||||||
|
signatures.sign(
|
||||||
|
conn,
|
||||||
|
fake_dir,
|
||||||
|
actor,
|
||||||
|
factor="password",
|
||||||
|
secret="nope",
|
||||||
|
action="x",
|
||||||
|
meaning=None,
|
||||||
|
settings=pg_settings,
|
||||||
|
)
|
||||||
|
assert e.value.code == code
|
||||||
|
assert conn.execute("SELECT count(*) FROM signatures").fetchone()[0] == 0
|
||||||
|
kinds = conn.execute("SELECT DISTINCT kind FROM signin_attempts WHERE NOT ok").fetchall()
|
||||||
|
assert kinds == [("signature",)]
|
||||||
|
assert pg_client.get("/api/auth/me").json()["code"] == "no_session"
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_factor_refused() -> None:
|
||||||
|
actor = sessions.Actor(uuid.uuid4(), uuid.uuid4(), "a", "A", "password", ())
|
||||||
|
with pytest.raises(ApiError) as e:
|
||||||
|
signatures.sign(
|
||||||
|
None,
|
||||||
|
FakeDirectory(),
|
||||||
|
actor,
|
||||||
|
factor="sms",
|
||||||
|
secret="1",
|
||||||
|
action="x",
|
||||||
|
meaning=None,
|
||||||
|
settings=Settings(_env_file=None, stack="ci"),
|
||||||
|
)
|
||||||
|
assert e.value.code == "bad_factor"
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
"""Sign-in, Me, sign-out, lock and unlock through the API, on PostgreSQL with the fake directory."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from fakedir import FakeDirectory
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from pshelpers import app_conn, needs_pg, sign_in
|
||||||
|
|
||||||
|
from packetstation import audit
|
||||||
|
from packetstation.settings import Settings
|
||||||
|
|
||||||
|
pytestmark = needs_pg
|
||||||
|
|
||||||
|
GENERIC = "Sign-in failed. Check the account name and password."
|
||||||
|
NO_ROLE = "No role in Packet Station. Ask IT to add you to a group."
|
||||||
|
|
||||||
|
|
||||||
|
def test_password_signin_and_me_shape(pg_client: TestClient, pg_settings: Settings, fake_dir: FakeDirectory) -> None:
|
||||||
|
r = sign_in(pg_client, "clerk.clara")
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
cookie = r.headers["set-cookie"].lower()
|
||||||
|
assert cookie.startswith("ps_session=") and "httponly" in cookie and "samesite=strict" in cookie
|
||||||
|
assert "max-age" not in cookie and "secure" not in cookie # plain http in tests
|
||||||
|
me = r.json()
|
||||||
|
assert set(me) == {"user", "roles", "screens", "groups", "session", "pin", "can_register_device"}
|
||||||
|
clara = fake_dir.user("clerk.clara")
|
||||||
|
assert me["user"] == {
|
||||||
|
"id": str(clara.guid),
|
||||||
|
"sam_account": "clerk.clara",
|
||||||
|
"upn": "[email protected]",
|
||||||
|
"display_name": "Clara Clerk",
|
||||||
|
"emp_no": "4001",
|
||||||
|
"email": "[email protected]",
|
||||||
|
}
|
||||||
|
assert me["roles"] == ["clerical"] and me["screens"] == ["clerical"] and me["groups"] == ["PS-Clerical"]
|
||||||
|
assert set(me["session"]) == {"id", "kind", "created_at", "expires_at", "locked", "locked_since", "device"}
|
||||||
|
assert me["session"]["kind"] == "password" and me["session"]["locked"] is False
|
||||||
|
assert me["session"]["device"] is None and me["session"]["locked_since"] is None
|
||||||
|
assert me["pin"] == {"set": False, "disabled": False} and me["can_register_device"] is False
|
||||||
|
assert pg_client.get("/api/auth/me").json() == me
|
||||||
|
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
hours = conn.execute(
|
||||||
|
"SELECT extract(epoch FROM expires_at - created_at) / 3600 FROM sessions WHERE id = %s",
|
||||||
|
(me["session"]["id"],),
|
||||||
|
).fetchone()[0]
|
||||||
|
assert float(hours) == 12
|
||||||
|
assert conn.execute("SELECT role::text, dept_code FROM user_roles").fetchall() == [("clerical", "CL")]
|
||||||
|
ok = conn.execute("SELECT account, kind, ok FROM signin_attempts").fetchall()
|
||||||
|
assert ok == [("clerk.clara", "password", True)]
|
||||||
|
row = conn.execute("SELECT action, detail, role_snapshot FROM audit_events").fetchone()
|
||||||
|
assert row[0] == "auth.signin" and row[1]["kind"] == "password" and row[2] == "clerical"
|
||||||
|
assert conn.execute("SELECT last_signin_at IS NOT NULL FROM users").fetchone()[0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_roles_union_nested_and_upn(pg_client: TestClient) -> None:
|
||||||
|
me = sign_in(pg_client, "multi.mia").json()
|
||||||
|
assert me["roles"] == ["clerical", "shop:06:supervisor"]
|
||||||
|
assert me["screens"] == ["clerical", "supervisor", "stall"] and me["can_register_device"] is True
|
||||||
|
assert sign_in(pg_client, "nested.ned").json()["roles"] == ["shop:10:worker"]
|
||||||
|
assert sign_in(pg_client, "[email protected]").json()["roles"] == ["shop:03:supervisor"]
|
||||||
|
admin = sign_in(pg_client, "ADMIN.ANN").json()
|
||||||
|
assert admin["roles"] == ["admin"] and admin["screens"][-1] == "admin" and len(admin["screens"]) == 7
|
||||||
|
|
||||||
|
|
||||||
|
def test_failures_do_not_reveal_which(pg_client: TestClient, pg_settings: Settings, fake_dir: FakeDirectory) -> None:
|
||||||
|
for login, pw in (("clerk.clara", "wrong"), ("nobody.here", None), ("disabled.dan", None), ("clerk.clara", "")):
|
||||||
|
r = sign_in(pg_client, login, pw)
|
||||||
|
assert r.status_code == 401, login
|
||||||
|
assert r.json() == {"detail": GENERIC, "code": "signin_failed"}
|
||||||
|
assert "set-cookie" not in r.headers
|
||||||
|
r = sign_in(pg_client, "norole.nick")
|
||||||
|
assert r.status_code == 403 and r.json() == {"detail": NO_ROLE, "code": "no_role"}
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
reasons = [r[0] for r in conn.execute("SELECT reason FROM signin_attempts ORDER BY id").fetchall()]
|
||||||
|
assert reasons == ["bad_password", "no_such_user", "disabled", "empty", "no_role"]
|
||||||
|
audited = conn.execute("SELECT detail->>'reason' FROM audit_events ORDER BY id").fetchall()
|
||||||
|
assert [a[0] for a in audited] == ["disabled", "no_role"]
|
||||||
|
assert conn.execute("SELECT count(*) FROM sessions").fetchone()[0] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_account_rate_limit_before_bind(pg_client: TestClient, fake_dir: FakeDirectory) -> None:
|
||||||
|
for _ in range(5):
|
||||||
|
assert sign_in(pg_client, "weld.andy", "wrong").status_code == 401
|
||||||
|
binds = fake_dir.binds
|
||||||
|
r = sign_in(pg_client, "weld.andy") # even the right password is refused now
|
||||||
|
assert r.status_code == 429
|
||||||
|
body = r.json()
|
||||||
|
assert body["code"] == "rate_limited" and 590 <= body["retry_after"] <= 600
|
||||||
|
assert r.headers["retry-after"] == str(body["retry_after"])
|
||||||
|
assert fake_dir.binds == binds # no bind while limited
|
||||||
|
r = sign_in(pg_client, "[email protected]") # the UPN alias is limited too
|
||||||
|
assert r.status_code == 429 and fake_dir.binds == binds
|
||||||
|
assert sign_in(pg_client, "clerk.clara").status_code == 200 # other accounts are not
|
||||||
|
|
||||||
|
|
||||||
|
def test_ldap_unavailable(pg_client: TestClient, fake_dir: FakeDirectory) -> None:
|
||||||
|
fake_dir.down = True
|
||||||
|
r = sign_in(pg_client, "clerk.clara")
|
||||||
|
assert r.status_code == 503 and r.json()["code"] == "ldap_unavailable"
|
||||||
|
|
||||||
|
|
||||||
|
def test_signout(pg_client: TestClient, pg_settings: Settings) -> None:
|
||||||
|
sign_in(pg_client, "clerk.clara")
|
||||||
|
r = pg_client.post("/api/auth/signout")
|
||||||
|
assert r.status_code == 204
|
||||||
|
assert pg_client.get("/api/auth/me").json()["code"] == "no_session"
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
assert conn.execute("SELECT revoked_reason FROM sessions").fetchone()[0] == "signout"
|
||||||
|
|
||||||
|
|
||||||
|
def test_lock_unlock_and_audit_chain(pg_client: TestClient, pg_settings: Settings) -> None:
|
||||||
|
sign_in(pg_client, "clerk.clara")
|
||||||
|
assert pg_client.post("/api/auth/lock").status_code == 204
|
||||||
|
r = pg_client.get("/api/account")
|
||||||
|
assert r.status_code == 423 and r.json()["code"] == "locked"
|
||||||
|
me = pg_client.get("/api/auth/me").json()
|
||||||
|
assert me["session"]["locked"] is True and me["session"]["locked_since"]
|
||||||
|
r = pg_client.post("/api/auth/unlock", json={"factor": "password", "secret": "wrong"})
|
||||||
|
assert r.status_code == 403 and r.json()["code"] == "wrong_secret" and r.json()["attempts_left"] == 2
|
||||||
|
r = pg_client.post("/api/auth/unlock", json={"factor": "pin", "secret": "123456"})
|
||||||
|
assert r.status_code == 409 and r.json()["code"] == "pin_not_set"
|
||||||
|
r = pg_client.post("/api/auth/unlock", json={"factor": "password", "secret": "fake-password-1"})
|
||||||
|
assert r.status_code == 200 and r.json()["session"]["locked"] is False
|
||||||
|
assert pg_client.get("/api/account").status_code == 200
|
||||||
|
assert pg_client.post("/api/auth/visibility", json={"hidden": False}).status_code == 204
|
||||||
|
assert pg_client.get("/api/account").status_code == 200
|
||||||
|
assert pg_client.post("/api/auth/visibility", json={"hidden": True}).status_code == 204
|
||||||
|
assert pg_client.get("/api/account").status_code == 200 # hidden under a minute: no lock
|
||||||
|
assert pg_client.post("/api/auth/signout").status_code == 204
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
actions = [r[0] for r in conn.execute("SELECT action FROM audit_events ORDER BY id").fetchall()]
|
||||||
|
assert actions == ["auth.signin", "auth.lock", "auth.unlock", "auth.signout"]
|
||||||
|
sources = conn.execute("SELECT detail->>'source' FROM audit_events WHERE action = 'auth.lock' ORDER BY id")
|
||||||
|
assert [s[0] for s in sources.fetchall()] == ["manual"]
|
||||||
|
ok, n, detail = audit.verify_chain(conn)
|
||||||
|
assert ok and n == 4, detail
|
||||||
|
|
||||||
|
|
||||||
|
def test_three_wrong_unlocks_end_the_session(pg_client: TestClient, pg_settings: Settings) -> None:
|
||||||
|
sign_in(pg_client, "clerk.clara")
|
||||||
|
pg_client.post("/api/auth/lock")
|
||||||
|
for left in (2, 1):
|
||||||
|
r = pg_client.post("/api/auth/unlock", json={"factor": "password", "secret": "wrong"})
|
||||||
|
assert r.json()["attempts_left"] == left
|
||||||
|
r = pg_client.post("/api/auth/unlock", json={"factor": "password", "secret": "wrong"})
|
||||||
|
assert r.status_code == 401 and r.json()["code"] == "session_ended"
|
||||||
|
assert pg_client.get("/api/auth/me").json()["code"] == "no_session"
|
||||||
|
with app_conn(pg_settings) as conn:
|
||||||
|
assert conn.execute("SELECT revoked_reason FROM sessions").fetchone()[0] == "stepup_failures"
|
||||||
|
kinds = conn.execute("SELECT kind, account FROM signin_attempts WHERE NOT ok").fetchall()
|
||||||
|
assert len(kinds) == 3 and all(k == "unlock" and a.startswith("user:") for k, a in kinds)
|
||||||
|
assert audit.verify_chain(conn)[0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_departments(pg_client: TestClient) -> None:
|
||||||
|
sign_in(pg_client, "weld.andy")
|
||||||
|
deps = pg_client.get("/api/departments").json()
|
||||||
|
assert [d["code"] for d in deps][:5] == ["CL", "WH", "QC", "PM", "01"]
|
||||||
|
weld = next(d for d in deps if d["code"] == "03")
|
||||||
|
assert weld == {
|
||||||
|
"code": "03",
|
||||||
|
"slug": "WeldParts",
|
||||||
|
"name": "Weld Parts",
|
||||||
|
"kind": "shop",
|
||||||
|
"stations": [f"Stall {i}" for i in range(1, 7)],
|
||||||
|
}
|
||||||
|
hydro = next(d for d in deps if d["code"] == "09")
|
||||||
|
assert hydro["stations"] == ["Hydro Bay 1", "Hydro Bay 2"]
|
||||||
Reference in New Issue
Block a user