Skip to content

Auth Flow Across Layers

1. Overview

The auth system binds every session to a real EPFL identity via Microsoft Entra OAuth, holds that identity in a signed JWT in an httpOnly cookie, and enforces role-scoped permissions through in-code RBAC at every request (app/core/policy.py, app/core/security.py; the module borrows OPA-style naming but runs no policy engine — see ADR-005).

flowchart LR
    U[User] --> SPA[Frontend SPA]
    SPA -->|1. /v1/auth/login| API[Backend API]
    API -->|2. 302| Entra[Entra ID]
    Entra -->|3. 302 with code| API
    API -->|4. Set-Cookie + 302 /| SPA
    SPA -->|5. cookie on every request| API

2. Trust boundaries

Three boundaries pinned by tests. The module docstring at backend/app/api/v1/auth.py is the canonical source.

Boundary Trusted artefact Untrusted artefact Test that pins it
IdP → backend userinfo claims from authorize_access_token (signed by IdP) Query params, headers, request body on /callback test_callback_binds_session_to_idp_institutional_id
Backend → cookie JWT minted by issue_session_cookie, signed with settings.JWT_HMAC_KEY Anything else the client could return as evidence of identity test_auth_cookies_secure_when_cookie_secure_true
Cookie → backend decode_jwt(cookie) payload after signature + algorithm + exp validation Cookie body in transit, query params, headers carrying identity test_jwt_expired_rejected, test_jwt_tampered_signature_rejected

/auth/login-test deliberately bypasses boundary 1; its only safeguard is settings.DEBUG, pinned by test_login_test_registration_matches_debug_flag.

3. OAuth Authorization Code flow

sequenceDiagram
    autonumber
    participant U as User
    participant SPA as Frontend SPA
    participant API as Backend API
    participant Entra as Entra ID
    participant DB as Database

    U->>SPA: Click "Login"
    SPA->>API: GET /v1/auth/login
    API-->>SPA: 302 to Entra authorize endpoint
    SPA->>Entra: Authorize request
    U->>Entra: Authenticate
    Entra-->>API: 302 to /v1/auth/callback?code=...
    API->>Entra: Exchange code for access token
    Entra-->>API: access_token + userinfo
    API->>API: Fetch roles via RoleProvider
    API->>DB: Upsert user, audit event
    API-->>SPA: 302 to FRONTEND/ + Set-Cookie auth_token (with auth_time)
    SPA->>SPA: Hydrate auth store (GET /v1/session)
    SPA-->>U: Navigate to home

Why Set-Cookie on the callback redirect? Frontend and backend share the same domain in all deployments (/api prefix in production, localhost on both sides in dev). A cookie set on a same-domain 302 is accepted by all browsers without ITP interference. See ADR-019 for the original BFF exchange design that was superseded by this approach.

4. Session lifecycle

One httponly cookie, auth_token, slides on activity and is capped from the login instant (ADR-020, #2943). There is no refresh token and no refresh endpoint.

stateDiagram-v2
    [*] --> Anonymous
    Anonymous --> Authenticating: GET /v1/auth/login
    Authenticating --> Authenticated: /v1/auth/callback sets auth_token + 302 /
    Authenticated --> Authenticated: any request past half the idle window re-issues the cookie
    Authenticated --> Anonymous: idle window or cap reached (401, login page)
    Authenticated --> Anonymous: DELETE /v1/session (clears the cookie)
Setting Deployed value Meaning
ACCESS_TOKEN_EXPIRE_MINUTES 2880 (48 h) Idle window. Renewed on the first request past its half, so anyone back within 24 h stays logged in
REFRESH_TOKEN_EXPIRE_HOURS 168 (7 days) Hard cap from auth_time: no renewal extends a session beyond it

The names date from the two-cookie design and were kept so no environment had to change. Values live in the openshift-app-config overlays; set the idle window to a minute in a local .env to watch renewals happen after 30 s.

Renewal. get_optional_user (backend/app/core/security.py) checks every authenticated request. Past half the idle window it mints a new cookie with the same auth_time and exp = min(now + idle, auth_time + cap), and queues two background tasks with their own DB sessions: a "Session renewed" audit row carrying renewed_exp (the exp it replaced, so the parallel requests of one page load group together) and the role sync of section 6a. The cookie is parked on request.state and SessionRenewalMiddleware (backend/app/core/session_renewal.py) appends it at response start, so it reaches responses a route builds itself too: 304s, downloads, SSE streams, redirects.

Bootstrap. GET /v1/session answers 200 with user: null when there is no cookie, so the SPA learns "anonymous" in one request. A cookie that is present but refused (expired, capped, tampered, retired refresh type) is still a 401, and the SPA reads it as anonymous too. The frontend never retries a 401: on any other route it means "log in again".

Logout. DELETE /v1/session clears the cookie client-side but does not invalidate the JWT server-side: a leaked cookie remains valid until exp. F6 (server-side denylist) is deferred — see issue #458 follow-up comment.

5. JWT structure

Claims minted by issue_session_cookie in backend/app/core/security.py:

Claim Purpose
sub IdP sub claim (Entra object UUID); fallback to str(user.id) if IdP omits it
institutional_id Stable EPFL identifier — the primary trust-boundary key
provider UserProvider enum value (1=DEFAULT, 2=TEST, 3=ACCRED)
type Always "access" (TOKEN_TYPE_ACCESS); a retired "refresh" JWT is refused
auth_time OIDC login instant, copied unchanged by every renewal; the cap counts from it
exp UTC expiry: min(now + idle window, auth_time + cap)

Algorithm: HS256. Key: settings.JWT_HMAC_KEY (single shared symmetric secret — see ADR-012).

Validation path in backend/app/core/security.py:

  1. decode_jwt(token) — jwt.decode(...) runs signature + algorithm check. Every joserfc error is a 401; before #2943 an alg=none token on a protected route was a 500.
  2. _CLAIMS_REGISTRY.validate(payload.claims) — explicit exp check. Before F10 this call was missing; expired tokens silently passed.
  3. resolve_user_by_jwt_payload(payload, db, expected_token_type=...) — the centralized identity-resolution helper, called from get_optional_user, which backs both GET /v1/session and get_current_user.

6. Role provider plugin

backend/app/providers/role_provider.py defines three providers:

  • JwtClaimsRoleProvider — reads roles from JWT claims. Used in development and synthetic-data flows.
  • AccredRoleProvider — fetches from the EPFL Accred API. Production.
  • TestRoleProvider — synthetic roles for /auth/login-test (DEBUG-only route).

Selection is driven by settings.ROLE_PROVIDER_TYPE through the factory get_role_provider(provider_type). F9 hardened the factory: an unknown provider type now raises ValueError instead of silently falling back to JwtClaimsRoleProvider. F11/F12 hardened claim parsing: malformed RoleName entries and unknown scope types are skipped with a warning rather than aborting the login.

6a. Background role sync

Every session renewal (section 4) fires a BackgroundTask — trigger_role_sync_for_user — that re-checks the role provider so a long-lived session eventually picks up role changes without forcing a logout. With a 48 h idle window that is at most once per 24 h of activity per user. Login itself resolves roles synchronously on the critical path and is unaffected by any of this — see #2531 and its plan for the failure this replaced (an empty provider response was written as user.roles = [], silently — the 403 wave).

RoleSyncService.sync_user_roles:

  • TTL gate (settings.ROLE_SYNC_TTL_MINUTES, default 60) — skips the provider call entirely if synced within the window. Not a security boundary; ACCESS_TOKEN_EXPIRE_MINUTES and REFRESH_TOKEN_EXPIRE_HOURS are. This is a debounce so a burst of near-simultaneous calls (the parallel requests of one page load all renewing) doesn't all re-hit the provider.
  • An empty response never wipes on its own. roles_empty_since is stamped on the first empty result and cleared on any non-empty one. A second empty result, confirmed 2 * ROLE_SYNC_TTL_MINUTES after the first, is what a genuine revocation looks like — that one applies for real. See #2539 for the design.
  • Backoff on every skip outcome (TTL debounce aside) — the network-error and suspicious-empty paths both stamp last_roles_sync_at, so a repeated failure waits one TTL period before the next attempt instead of retrying on every call.
  • force=True bypasses both the TTL gate and the suspicious-empty guard — reachable only from the admin POST /v1/users/{user_id}/revoke-roles endpoint (backoffice.users.edit), never from the automatic /v1/session path. It re-runs the provider check right now and applies whatever comes back, including empty — it does not invent a revocation the provider doesn't confirm.
  • Every skip outcome is counted via an OTel counter (role_sync.skipped → role_sync_skipped_total{outcome=...}) — see #2623.
  • A 5xx, a 401/403/429, a timeout or a connection error from Accred raises RoleProviderNetworkError in both lookups and counts accred.request.failures{endpoint,status_code}; so does missing Accred config (endpoint=config). Role sync skips as skipped_provider_unavailable; the login callback redirects to /login?reason=accred-unavailable and the frontend adds the UI language. A 404 is not an outage.

7. Security gotchas

  • COOKIE_SECURE env var — defaults to True (correct for prod HTTPS). It must be False in backend/.env for HTTP localhost dev; Safari and httpx clients silently drop Secure cookies on the return trip over http://. This decoupling from DEBUG was the F2 regression caught during PR #1310 review.
  • /auth/login-test is registered only in DEBUG builds — not a runtime gate. The route literally does not exist in production app.routes. Pinned by test_login_test_registration_matches_debug_flag.
  • F6 deferred — logout does not denylist the JWT. A leaked cookie remains valid until exp. A JTI denylist is the planned remediation; see issue #458 follow-up.
  • JWTClaimsRegistry default leeway=0 — no clock-skew tolerance. Brief NTP drift across pods can cause spurious 401s on tokens near expiry. A 30 s leeway is on the future-work list.

8. Tests — what's pinned where

Mapping each Tier-1 finding (F1–F12) to its regression test. Source of truth: the implementation plan docs/src/implementation-plans/458-security-authentication-integration-hardening.md (landed with PR #1310 — issue #458).

Finding Test file Test name
F1 backend/tests/integration/v1/test_auth_security.py test_callback_binds_session_to_idp_institutional_id
F2 backend/tests/integration/v1/test_auth_security.py test_auth_cookies_secure_when_cookie_secure_true, test_auth_cookies_not_secure_when_cookie_secure_false
F3 backend/tests/integration/v1/test_auth_security.py test_login_test_registration_matches_debug_flag, test_login_test_returns_404_in_prod_build
F4 backend/tests/integration/v1/test_auth_security.py test_jwt_alg_none_rejected, test_jwt_wrong_alg_rejected, test_jwt_tampered_signature_rejected
F5 backend/tests/integration/v1/test_auth_security.py test_session_past_half_life_is_renewed_on_any_request (refresh rotation retired by #2943)
F6 deferred server-side JTI denylist — see follow-up comment
F7 backend/tests/integration/v1/test_auth_security.py test_audit_event_failure_logs_error_with_marker, test_audit_event_must_succeed_propagates_failure
F8 backend/tests/integration/v1/test_auth_security.py test_me_rejects_legacy_user_id_only_token
F9 backend/tests/unit/providers/test_role_provider.py test_get_unknown_role_provider_raises (in TestGetRoleProvider)
F10 backend/tests/integration/v1/test_auth_security.py test_jwt_expired_rejected
F11 backend/tests/unit/providers/test_role_provider.py test_unknown_role_name_is_skipped_not_raised, test_empty_role_name_is_skipped_not_raised (in TestJwtClaimsRoleProviderClaimCombinations)
F12 backend/tests/unit/providers/test_role_provider.py test_unknown_scope_type_warns_when_skipped (in TestJwtClaimsRoleProviderClaimCombinations)

Additional pinning tests:

  • test_callback_sets_cookies_and_redirects_to_frontend — pins the direct cookie-on-callback behaviour (PR #1687).
  • test_e2e_callback_session_logout_happy_path — end-to-end happy path.
  • Session cookie (#2943), in test_auth_security.py: test_session_younger_than_half_life_is_left_alone, test_session_at_hard_cap_is_not_renewed, test_pre_2943_token_without_auth_time_is_never_renewed, test_anonymous_session_is_200_with_null_user_and_no_cookie, test_me_rejects_refresh_token_in_auth_cookie.
  • backend/tests/unit/core/test_session_renewal_middleware.py — the renewed cookie reaches JSON, 304 and streaming responses.
  • frontend/tests/unit/session-bootstrap.spec.ts — bootstrap is one request: 200 without user and 401 are anonymous, a 500 is an error.
  • test_secure_cookie_is_dropped_over_http_breaking_followup_calls — F2 regression guard; demonstrates the cookie-drop symptom.
  • TestJwtClaimsRoleProviderClaimCombinations::* — claim-combination matrix for the role provider.
  • backend/tests/unit/core/test_security_gates.py::* — permission gate unit tests covering is_permitted / check_permission / require_permission.

9. Design choices and trade-offs

Why direct cookies on the callback (not a BFF exchange step)

Frontend and backend share the same domain in all deployments (production: /api path prefix on the same host; localhost dev: same localhost host, different ports that are treated as same-site). A Set-Cookie header on the OAuth-callback 302 is a same-site response; browsers accept it without ITP interference. The previous BFF exchange design (ADR-019) was motivated by a Safari ITP regression that only reproduced on localhost when the two processes ran on different ports — not a production concern. Removing it eliminates one DB table, one endpoint, one SPA page, and one round-trip on every login.

Why HS256 with a shared secret, not RS256 with a key pair

Single-tenant deployment; the backend is the only verifier. A symmetric secret is simpler to operate (no JWKS endpoint, no key-pair rotation choreography). The cost — no public verifiability — does not apply here. See ADR-012.

Why httpOnly session cookies, not bearer tokens in localStorage

Bearer tokens in JS-readable storage are the OWASP cheat-sheet anti-pattern for SPAs: any XSS sink lifts the token. httpOnly cookies are out of reach of JavaScript, and the CSRF exposure they bring in exchange is covered by SameSite=Lax plus the request-origin check described below.

CSRF: SameSite plus a request-origin check

Cookie auth is forgeable by construction, so two controls stand in front of every state-changing request:

  1. SameSite=Lax on the auth cookie — browser-enforced, so it holds independently of our own code, and it keeps the cookie off a cross-site request entirely rather than receiving one and refusing it.
  2. RequestOriginMiddleware (backend/app/core/request_origin.py) — rejects any request carrying an auth cookie that cannot show, via Sec-Fetch-Site, Origin or Referer, that it came from our own origin. Fail-closed: none of the three headers means 403.

The second exists because the first is not sufficient here. SameSite is evaluated against the registrable domain, so every application under *.epfl.ch is same-site to us and Lax will attach auth_token to its requests. Sec-Fetch-Site: same-site is therefore rejected, not just cross-site.

Two rebuttals worth recording, so they are not re-litigated each review:

  • Why not SameSite=Strict? The attacker in our threat model is same-site by definition, so Strict blocks nothing they can do — while breaking session state on every inbound link into the app.
  • Why no CSRF token? Naive double-submit is defeated by that same attacker: any *.epfl.ch host can set a Domain=epfl.ch cookie and forge the matching header. Signed double-submit would work but is machinery a same-origin SPA does not need. A genuinely cross-origin frontend would reopen the question as an ADR.

CORS stays disabled on this instance, deliberately — with no CORS headers the browser preflights and drops every JSON-body and PUT/PATCH/DELETE forgery before it is sent. The middleware covers what preflights do not: POST requests whose body type is CORS-simple.

See plan #89.

10. Future work

  • F6 — Logout JWT denylist (server-side JTI store). The only way to cut a stolen cookie short of its exp; until then the idle window and the 7-day cap bound it.
  • JWTClaimsRegistry leeway tuning — currently default 0 seconds; 30 s is the candidate value to absorb pod-to-pod NTP drift.
  • Narrow the role-provider boundary — F11/F12 are delivered, but the provider surface deserves its own scope-narrowing pass in a future tier (typed schema for IdP role payloads, strict mode for production).
  • Ingress rate limiting on /v1/auth/callback — no app-level throttle exists on the callback endpoint; a nginx.ingress.kubernetes.io/limit-rps annotation on the ingress is the recommended mitigation.