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_optionalbuilds a lightweightSessionUserfrom it without a DB hit, whileget_current_userre-readsactive,roleand the role's permission matrix on every request (load_live_user: oneusers⟕roles⟕role_permissionsquery; 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 intoscope["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-createsadmin@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);adminholds every key in code, and the shippedsuperuser/userdefaults 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 underassignments.self_*); reads and writes are limited to the live visible sites (sites.view_all= every site). Account rules: editing an admin needsusers.edit_admins, a non-default role is assignable only withusers.change_roleand only if its permissions are within the caller's (the admin role: admins only;users.createalone creates accounts with the defaultuserrole), 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). Withsites.view_allevery site is visible and nothing is filtered; otherwise only the user's liveuser_sites. A site parameter or bodysite_idoutside them is a 403 (ensure_site_visible; site-less projects/equipment needsites.view_all), lists without one are filtered (visible_sites_clause), a project outside is a 403 on reads and on every project write even withprojects.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/dashboardsread; apersondimension also needsviews.staff— on a capacity measureabsences.view_otherstoo —, archivedinclude/onlyviews.archived),views.kanban(the/kanbancomment-count reads — comment threads and the mention list need only visibility since 2.0.0; disabled for everyone whilekanban_enabledis 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=allleaves archived projects out without it). Route tests serve other people's, projects' and equipment's sites from thesite_linksfixture (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: withabsences.view_otherstheir own plus those of the members of their visible sites — thesiteIdform 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 wherestaff_idis 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 thePM_BUNDLEkeys on the projects whosepm_idis the user:projects.edit_any(all fields incl. handing over viapm_id, phases/subphases),projects.archive,assignments.manage_others,equipment_bookings.manage,kanban.move_any,custom_columns.set_values. Neverprojects.delete,projects.create, import, exports or tag definitions. Evaluated byPermissionSet.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 (norole_permissionsrows; never editable or deletable), so it always sees every site and is the only holder ofroles.manage(Settings → Roles,require_adminroutes). 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_removeinapprovalmode (the shipped defaults areallow); see Approval workflow. Who approves is per action inapproval_policies(PM and/or roles; admins always). is_system=truemarks 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 byGET /staffand 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_adminson an admin). - Feature switches can disable keys for everyone.
PermissionSet.disabled_keys(validated againstDISABLEABLE_KEYS={views.kanban}, so a locked key can never be disabled) is checked first inPermissionSet.mode()— before the admin and always-allowed branches — sohas,can,effective_modes,allow_keysandapproval_keysall follow, the admin included;can()checks it at its top too.kanban_enabled = false→views.kanbandisabled (FLAG_DISABLESininstance_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_userreads the switch as a fifth column of its one query (a scalar subquery onsettings),/auth/meand login useeffective_permission_set(db, role)(one more query), androles.pybuilds role sets without it, so the matrix shows what is configured. The escalation guard ignores the switch:user_access.role_withincompares againstreplace(holder, disabled_keys=frozenset()), mirrored by the client'sroleWithin(role, user, disabledKeys)(utils/roles.ts;UsersPanelpassesDISABLEABLE_KEYSwhile the board is off) — otherwise only an admin could assign a role holdingviews.kanban.DISABLEABLE_KEYSis mirrored infrontend/src/types/permissions.tsandshared/permission-keys.json(disableable).
Microsoft Entra SSO¶
Two configuration levels, resolved by SSOService.get_effective_sso_config():
- 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 bytests/test_sso_guardrails.py). - Tenant SSO (
sso_configsingleton in the tenant DB) — per-tenant fallback. Itsclient_secretis encrypted at rest with the same key as tenant credentials (TENANT_ENCRYPTION_KEY; single-tenant: derived fromSESSION_SECRET). If the key changes,read_tenant_client_secretlogs once and returnsNone→ 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 (notBaseHTTPMiddleware— 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), rewritesscope["path"]to strip the prefix, and storestenant/tenant_slug/tenant_engineinscope["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_cachecapped 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 whenMULTI_TENANT=true.- Tenant info lives in
scope["state"](a plain dict). In HTTP handlers,request.state.tenant_slugattribute access works — Starlette'sRequest.statelazily wrapsscope["state"]in aStateobject. In code that handles raw ASGI scopes (middleware, helpers that may not receive a fullRequest), readscope["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_readonlyraise 503 (resolve_tenant_session_factoryinapp/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-slugasyncio.Lockso 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 beforeCREATE DATABASEand reassignspublicschema ownership.- Tenant DB credentials are stored AES-256-GCM-encrypted (
iv:tag:ciphertexthex, key =TENANT_ENCRYPTION_KEY) intenant_credentials, Node-compatible format.
Security¶
- Startup/runtime: the lifespan calls
Settings.check_startup_security()— withDEBUG=falsean empty or publishedSESSION_SECRET(INSECURE_SESSION_SECRETS) is aRuntimeError, so the app does not start; docs endpoints gated onsystem.api_docs; global exception handler returns opaque 500s;/healthand the tenant 503 never echo DB hosts/users/SQL; Docker runs as non-rootappuserwith a/healthhealthcheck. - 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 fromSESSION_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 legacysalt: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 withRetry-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 oneauth.login.failedmarkedsuppressed(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 proxyFORWARDED_ALLOW_IPSmust 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_passwordis enforced server-side (403 fromget_current_admin). - Sessions: HTTP-only cookies;
SECURE_COOKIES=truefor HTTPS deployments; expired-session cleanup inSessionService; every request re-checksactive,roleand the role's permissions; revocation (deactivate/delete/demote/password reset) destroys sessions and closes WebSockets. - WebSocket:
Originchecked against the host / CORS origins (close 4003) — cross-site WebSocket hijacking guard;/api/ws-debug*gated onsystem.ws_debug. - SSO: HMAC-signed state bound to the browser by the
sso_noncecookie (one-time, 10 min); only a validatedAADSTScode from Microsoft ever reaches a user, Entra's own error text is never reflected; secrets never returned unmasked (/sso/config/fullmasks; 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 holdingroles.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 /settingsandGET /settings/{key}have no auth dependency — never store sensitive values in the tenantsettingsKV table. - ⚠
/healthis public and includes the backend identifier anddefault_tenantin its response — don't add further config values to it.