Skip to content

Authentication and tenancy

How a request is authenticated and scoped: the two independent session systems (tenant app and admin portal), the tenant role model (roles as permission sets, visible sites, the PM bundle, own-booking approvals, feature switches), Microsoft Entra SSO, the multi-tenant middleware and pools, and the security measures that hold it together. It was moved verbatim out of the repo-root CLAUDE.md, which keeps the security rules.

Code described: app/middleware/auth.py, app/middleware/tenant.py, app/services/session.py, app/services/permissions.py, app/services/site_access.py, app/services/project_access.py, app/services/user_access.py, app/services/sso.py, app/services/sso_errors.py, app/services/sso_test.py, app/services/login_throttle.py, app/services/encryption.py, app/services/tenant_manager.py, app/services/tenant_provisioner.py, app/routers/auth.py, app/routers/admin/auth.py.

Authentication, Sessions & SSO

Two independent auth systems

Tenant app Admin portal
Cookie connect.sid (s%3A<id>. express format) admin_session (raw id)
Session store sessions table, tenant DB admin_sessions table, master DB
Users users (tenant DB) admin_users (master DB)
Roles A role key per user (FK roles.key): system roles admin / superuser / user + custom roles, each a permission set superadmin > admin
Password hash bcrypt (rounds=12), lazy upgrade from legacy PBKDF2/plaintext on login PBKDF2-SHA512 pbkdf2_sha512$600000$salt$hash, lazy upgrade from legacy salt:hash
Login throttle 10 failures / 15 min per (tenant:<slug>, IP, e-mail) → 429; plus 100 / 15 min per public IP (all scopes) same, scope admin
Forced change — must_change_password → 403 everywhere but change-password / me
Dependencies get_current_user, require_permission / require_any_permission / require_project_permission, require_admin (roles only) (app/middleware/auth.py) get_current_admin, require_superadmin (app/routers/admin/auth.py)
  • SessionService (app/services/session.py) stores the full user dict (incl. site ids/names) in the session; get_current_user_optional builds a lightweight SessionUser from it without a DB hit, while get_current_user re-reads active, role and the role's permission matrix on every request (load_live_user: one users ⟕ roles ⟕ role_permissions query; 401 + session destroyed for missing/inactive users; the live role and matrix win over the snapshot, so a role edit applies on the next request) and stashes the user into scope["state"] for broadcast attribution. SessionService.destroy_user_sessions() is called on deactivate/delete/role change/password set so revocation is immediate — and also closes the user's open WebSockets on this process (manager.disconnect_user, close code 4001).
  • On startup, master_db.verify_admin_exists() auto-creates admin@milestone.local (superadmin, random password logged, must_change_password=true) if no admin exists.

Tenant role model

  • Roles are permission sets. Every gate is a catalogue key (app/services/permissions.py); admin holds every key in code, and the shipped superuser / user defaults reproduce the bullets below, so they describe the defaults of those two system roles. The PM rule is the PM bundle (projects.manage_as_pm); staff assignments are editor first (assignments.manage_others, else own rows under assignments.self_*); reads and writes are limited to the live visible sites (sites.view_all = every site). Account rules: editing an admin needs users.edit_admins, a non-default role is assignable only with users.change_role and only if its permissions are within the caller's (the admin role: admins only; users.create alone creates accounts with the default user role), a non-admin may change the role only of users whose current role is within theirs, nobody changes their own role, and the last active admin cannot be demoted, deactivated or deleted (app/services/user_access.py).
  • Visible sites scope every read and write (app/services/site_access.py). With sites.view_all every site is visible and nothing is filtered; otherwise only the user's live user_sites. A site parameter or body site_id outside them is a 403 (ensure_site_visible; site-less projects/equipment need sites.view_all), lists without one are filtered (visible_sites_clause), a project outside is a 403 on reads and on every project write even with projects.edit_any (ensure_project_visible), equipment / a site / a team / a person outside is a 404 on reads; people (staff, users, absences of others, skills) are visible when oneself or sharing a visible site (person_is_visible). The view keys gate their reads: views.dashboards (every /dashboards read; a person dimension also needs views.staff — on a capacity measure absences.view_others too —, archived include / only views.archived), views.kanban (the /kanban comment-count reads — comment threads and the mention list need only visibility since 2.0.0; disabled for everyone while kanban_enabled is off), views.staff (/staff/{id}/availability|assignments), views.equipment (equipment, booking, availability and block reads), views.crosssite (includeOtherSites=true: every visible site's projects, in full — no masking since 2.1.0), views.archived (archived=true → 403; archived=all leaves archived projects out without it). Route tests serve other people's, projects' and equipment's sites from the site_links fixture (tests/conftest.py). Custom-column values are read and written only on projects (and their phases/subphases) at visible sites; bookings of shared equipment by projects outside show [External Project]. Not scoped: GET /equipment-types (configuration).
  • user — read access within their sites (absences: with absences.view_others their own plus those of the members of their visible sites — the siteId form needs the key and a visible site — without it their own only; GET /vacations/{id} is a 404 outside that scope) + self-service (own vacations, custom-column values (definitions are admin-only), own staff assignments: a user may add/update/remove assignments where staff_id is their own id at project/phase/subphase level, and join/leave Kanban cards).
  • Project manager rule (PM bundle) — a role holding projects.manage_as_pm (both editable system roles by default) gets the PM_BUNDLE keys on the projects whose pm_id is the user: projects.edit_any (all fields incl. handing over via pm_id, phases/subphases), projects.archive, assignments.manage_others, equipment_bookings.manage, kanban.move_any, custom_columns.set_values. Never projects.delete, projects.create, import, exports or tag definitions. Evaluated by PermissionSet.can(key, pm_id=, user_id=) / project_access.user_can / can_on_project.
  • superuser (default) — everything a user can, plus create/edit/archive/delete/import/export projects, manage anyone's bookings and equipment bookings, move any card, moderate comments, others' absences, staff notes, equipment, equipment types and blocks, holidays/events, teams, predefined phases, skills (definitions and assignment), view and edit non-admin users, site export, What-If, build and share their own dashboards (dashboards.manage) — all within their visible sites. Not: sites.view_all, site definitions, user creation/credentials/roles/activation/deletion, admin accounts, settings, SSO, tags, project fields (project_fields.manage), absence types, custom-column definitions, roles, approvals.view_all, the API docs and WS debug.
  • admin — every key in code (no role_permissions rows; never editable or deletable), so it always sees every site and is the only holder of roles.manage (Settings → Roles, require_admin routes). Admins always approve own-booking requests, see every dashboard and may edit or delete any (the default one only they may delete).
  • Own-booking approvals — a role may hold assignments.self_create / self_update / self_remove in approval mode (the shipped defaults are allow); see Approval workflow. Who approves is per action in approval_policies (PM and/or roles; admins always).
  • is_system=true marks the provisioned admin; deletion is rejected.
  • Bookable as a resource (users.is_resource) is a per-user flag, not a role rule: only bookable people are listed by GET /staff and may receive a new booking (project_access.require_bookable_staff: 400 on the three staff POSTs and the Kanban assignee POST, before any 202). Turning it off keeps the existing bookings. New admins default to off, everyone else on; changing it is a profile edit (users.edit, users.edit_admins on an admin).
  • Feature switches can disable keys for everyone. PermissionSet.disabled_keys (validated against DISABLEABLE_KEYS = {views.kanban}, so a locked key can never be disabled) is checked first in PermissionSet.mode() — before the admin and always-allowed branches — so has, can, effective_modes, allow_keys and approval_keys all follow, the admin included; can() checks it at its top too. kanban_enabled = false → views.kanban disabled (FLAG_DISABLES in instance_settings.py): the board, its sidebar entry, the bell and My Work card links and the two comment-count reads go away as if nobody held the key; comments stay stored and readable (the thread and mention-list reads gate on visibility only, so the booking dialog's thread keeps working), and the card status / assignee / comment writes stay reachable (they gate on other keys). load_live_user reads the switch as a fifth column of its one query (a scalar subquery on settings), /auth/me and login use effective_permission_set(db, role) (one more query), and roles.py builds role sets without it, so the matrix shows what is configured. The escalation guard ignores the switch: user_access.role_within compares against replace(holder, disabled_keys=frozenset()), mirrored by the client's roleWithin(role, user, disabledKeys) (utils/roles.ts; UsersPanel passes DISABLEABLE_KEYS while the board is off) — otherwise only an admin could assign a role holding views.kanban. DISABLEABLE_KEYS is mirrored in frontend/src/types/permissions.ts and shared/permission-keys.json (disableable).

Microsoft Entra SSO

Two configuration levels, resolved by SSOService.get_effective_sso_config():

  1. Organization SSO (master DB, organization_sso_config) — shared by every tenant in the organization; secret encrypted; takes precedence. Tenant-level SSO cannot be enabled while org SSO is active (409, _reject_if_org_sso_active — covered by tests/test_sso_guardrails.py).
  2. Tenant SSO (sso_config singleton in the tenant DB) — per-tenant fallback. Its client_secret is encrypted at rest with the same key as tenant credentials (TENANT_ENCRYPTION_KEY; single-tenant: derived from SESSION_SECRET). If the key changes, read_tenant_client_secret logs once and returns None → SSO reports "not configured" until the secret is re-entered.

Flow: GET /auth/sso/login builds the Entra authorization URL with an HMAC-signed state carrying the tenant slug and a nonce (org SSO uses one shared callback URL with no /t/{slug}/ prefix, so the slug must survive the round-trip) and sets the nonce as the sso_nonce cookie (10 min) → GET /auth/sso/callback verifies the state signature and that its nonce equals this browser's cookie (so the flow only completes in the browser that started it and a callback URL cannot be replayed; the cookie is cleared on every outcome), exchanges the code, fetches the profile from Microsoft Graph /me, optionally validates group membership (fetch_user_groups pages Graph /me/memberOf; required_group_ids + group_membership_mode any/all on the tenant), finds or auto-creates the user (auto_create_users, default_role), creates a session, and redirects to /t/{slug}/.

Failure handling (app/routers/auth.py, app/services/sso_errors.py): - Entra token-endpoint and Graph failures go through parse_entra_token_error(): the only remote-derived text a user can see is a regex-validated AADSTS\d{4,7} code, mapped to one of our fixed messages; Entra's error / error_description are never reflected. - Callback failures redirect to /t/{slug}/?sso_error=<message> (_sso_error_redirect, slug recovered from the signed state); unexpected exceptions are caught and redirected the same way instead of a 500, and an unreachable identity provider reads "Could not reach the identity provider". - An organization-SSO lookup or decrypt failure fails closed (OrgSSOLookupError → "temporarily unavailable"); it never falls back to tenant-level SSO. - Both hops log a config fingerprint (_config_fingerprint, no secrets) so an operator can see which config served a sign-in; config values are whitespace-stripped. - SSOConfig.is_configured requires a client secret, so a row without one hides the sign-in button instead of failing with Entra's misleading "invalid client". - Credentials can be tested without a user sign-in at both levels, through one diagnostic (app/services/sso_test.py): the organization's saved values (POST /api/admin/organizations/{id}/sso/test, admin portal) and a tenant's entered values (POST /api/auth/sso/test, settings.sso, Settings → SSO). In Settings → SSO, saving a change to live sign-in values (ids, secret, redirect URI, switching off) asks for the typed word CHANGE.

Audit rows of the sign-in flow

Every sign-in event is an auth row of the audit log (app/routers/auth.py, audit_log.record). Failure rows are committed before the 401 / 429 is raised or the SSO redirect returned.

Event Action Outcome Reason / context
The failure that reaches the throttle limit (record_login_failure reports it) auth.login.locked failure throttled; retry_after (seconds), locked_until (ISO UTC); subject_email; written once, right after that attempt's auth.login.failed — a refused attempt while locked (the 429) records nothing, so a locked-out client cannot grow the table
Unknown e-mail auth.login.failed failure unknown_user; subject_email
Wrong password auth.login.failed failure bad_password; actor = the account
Disabled account auth.login.failed failure inactive; actor = the account
Past 100 unknown-user / wrong-password failures from one (tenant, IP) in the window (audit_failure_mode) auth.login.failed failure once, with context.suppressed: true (and no auth.login.locked), at most once per window (_audit_suppressed_at, so a steady rate just past the cap is not one row per try); otherwise nothing until the count falls back under the cap — the throttle answers as before
Successful sign-in auth.login.succeeded success — (the users table keeps no last sign-in, so no first_login)
POST /auth/logout with a live session auth.logout success actor resolved from the session before it is deleted; nothing without one
Own password change auth.password.changed success sessions_revoked
SSO callback, session created auth.sso.succeeded success provider: entra, created (auto-created this call)
SSO callback failure after the tenant session was resolved auth.sso.failed failure config_missing (disabled, no client secret, organization lookup failed), exchange_failed (token endpoint refused or unreachable), graph_failed (profile or group lookup failed), group_denied, no_email, no_account, inactive; provider: entra; committed on active_db

Failures before the tenant is known (bad state, foreign nonce, unknown tenant) have no tenant database and record nothing; the admin portal records nothing either.

Multi-Tenancy Internals

  • TenantMiddleware (app/middleware/tenant.py) is a pure ASGI middleware (not BaseHTTPMiddleware — that breaks WebSockets). It matches /t/{slug}/..., resolves the tenant through a 60-second in-memory cache (plain dicts, not ORM objects, to avoid session-detachment issues), rewrites scope["path"] to strip the prefix, and stores tenant / tenant_slug / tenant_engine in scope["state"]. Missing/inactive/unreachable tenants → 404/403/503 (the 503 body is a fixed message; the DB error goes only to the log). Misses are cached too (60 s, in a separate _negative_cache capped at 1 000 entries, expired/oldest evicted first — hits are never evicted by a miss flood), so a flood of unknown slugs doesn't hit the master DB; clear_tenant_cache(slug) drops hits and misses. WebSocket scopes are passed through untouched (the WS handler resolves the tenant itself). Only wraps the app when MULTI_TENANT=true.
  • Tenant info lives in scope["state"] (a plain dict). In HTTP handlers, request.state.tenant_slug attribute access works — Starlette's Request.state lazily wraps scope["state"] in a State object. In code that handles raw ASGI scopes (middleware, helpers that may not receive a full Request), read scope["state"]["tenant_slug"] directly; the broadcast helper handles both forms.
  • No fallthrough to DB_*: when a request carries a tenant slug but no pool exists, get_db / get_db_readonly raise 503 (resolve_tenant_session_factory in app/database.py) instead of silently serving the default database.
  • tenant_manager (app/services/tenant_manager.py) keeps lazy per-tenant engine pools (size 20 + 10 overflow; creation guarded by a per-slug asyncio.Lock so concurrent first requests build one pool), closes pools idle > 15 min (cleanup loop every 5 min), decrypts the tenant DB password on first connect, pins the session timezone to UTC like the default engine, and runs idempotent per-tenant auto-migrations on pool creation.
  • tenant_provisioner (app/services/tenant_provisioner.py) creates the PG role + database, grants, applies the tenant schema, and seeds defaults (predefined phases, skills, "Main Site", admin user). It validates identifiers against injection and handles managed PostgreSQL (Azure/RDS/Cloud SQL) where the admin is not a superuser: grants the tenant role to the admin before CREATE DATABASE and reassigns public schema ownership.
  • Tenant DB credentials are stored AES-256-GCM-encrypted (iv:tag:ciphertext hex, key = TENANT_ENCRYPTION_KEY) in tenant_credentials, Node-compatible format.

Security

  • Startup/runtime: the lifespan calls Settings.check_startup_security() — with DEBUG=false an empty or published SESSION_SECRET (INSECURE_SESSION_SECRETS) is a RuntimeError, so the app does not start; docs endpoints gated on system.api_docs; global exception handler returns opaque 500s; /health and the tenant 503 never echo DB hosts/users/SQL; Docker runs as non-root appuser with a /health healthcheck.
  • Secrets at rest: tenant DB passwords, org SSO secrets and tenant-level SSO secrets (sso_config.client_secret, since 1.5.0; legacy plaintext encrypted by the tenant auto-migration) AES-256-GCM encrypted (app/services/encryption.py); TENANT_ENCRYPTION_KEY (64-char hex) required in multi-tenant mode (single-tenant derives a key from SESSION_SECRET).
  • Passwords: bcrypt rounds=12 (tenant users, lazy upgrade from legacy hashes on login, > 72 bytes rejected); PBKDF2-SHA512 600 000 iterations, self-describing pbkdf2_sha512$… (admin users, lazy upgrade from legacy salt:hash). Minimum 8 characters for new/changed passwords in both systems; existing shorter passwords still log in.
  • Login throttle (app/services/login_throttle.py): sliding window, 10 failures / 15 min per (scope, client IP, e-mail) → 429 with Retry-After; success clears the key; plus a per-IP bucket (100 failures / 15 min across scopes and e-mails, not cleared by a success) that only applies to global addresses — private/loopback/CGNAT ones may be a shared proxy or NAT, where it would be a site-wide lockout switch; ≤ 10 000 tracked keys per bucket. A third bucket caps the audit rows, not the attempts: per (scope, client IP), shared addresses included, past 100 failures in the window the tenant login writes one auth.login.failed marked suppressed (at most one per window) and then none while the count stays past the cap (audit_failure_mode). The lockout is per (IP, e-mail), so behind a reverse proxy FORWARDED_ALLOW_IPS must list the proxy or every client shares one key. In-memory and per process — N workers allow N × 10. Unknown e-mails run a dummy hash (dummy_verify_user_password / dummy_verify_admin_password) so timing doesn't reveal accounts.
  • Admin portal: must_change_password is enforced server-side (403 from get_current_admin).
  • Sessions: HTTP-only cookies; SECURE_COOKIES=true for HTTPS deployments; expired-session cleanup in SessionService; every request re-checks active, role and the role's permissions; revocation (deactivate/delete/demote/password reset) destroys sessions and closes WebSockets.
  • WebSocket: Origin checked against the host / CORS origins (close 4003) — cross-site WebSocket hijacking guard; /api/ws-debug* gated on system.ws_debug.
  • SSO: HMAC-signed state bound to the browser by the sso_nonce cookie (one-time, 10 min); only a validated AADSTS code from Microsoft ever reaches a user, Entra's own error text is never reflected; secrets never returned unmasked (/sso/config/full masks; a masked value submitted back keeps the stored secret on every write route); optional Entra group gating per tenant.
  • Multi-tenant isolation: a tenant request without a pool is a 503, never the DB_* database; tenant status/edit/delete changes reset the tenant cache and pool on the handling process.
  • Provisioning: tenant identifiers validated against SQL injection in tenant_provisioner.
  • Authorization: every tenant route gates on a catalogue key (require_permission*, the access services) and on the live visible sites; the admin role cannot be edited or deleted and is the only one holding roles.manage, so nobody can lock the tenant out; role assignment is capped by the escalation guard (user_access.py) and the last active admin is protected.
  • ⚠ GET /settings and GET /settings/{key} have no auth dependency — never store sensitive values in the tenant settings KV table.
  • ⚠ /health is public and includes the backend identifier and default_tenant in its response — don't add further config values to it.