chain-rdeveloper portal
build

Authentication Flow

Overview

Authentication is delegated entirely to Auth0 (OAuth2 / OIDC). There is no local username/password system. svc-auth owns the OAuth flow and session management; the browser never sees an access token.

Authentication Method

OAuth2 Authorization Code flow via Auth0.

  • Auth0 is the source of truth for user identity.

  • svc-core maintains a local mirror (users table, keyed on auth0_id) for relational ownership of platform resources.

  • Tokens are stored server-side in Redis only.

Login Flow

1. Browser → GET app.dev.datachainr.com (unauthenticated)
2. nginx → auth_request → svc-auth /verify → 401
3. nginx → redirect to svc-auth /login
4. svc-auth → generate state + nonce, store in Redis (TTL: 10 min)
5. svc-auth → redirect browser to Auth0 /authorize
6. Auth0 → user authenticates
7. Auth0 → GET svc-auth /callback?code=...&state=...
8. svc-auth → validate state (CSRF check)
9. svc-auth → POST Auth0 /oauth/token (exchange code for tokens)
10. svc-auth → store access_token + refresh_token in Redis (keyed by session_id)
11. svc-auth → set signed HTTP-only session cookie (sid=<session_id>)
12. svc-auth → redirect browser to FRONTEND_URL

Verified Request Flow

Browser → GET app.dev.datachainr.com/some-page
  Cookie: sid=<session_id>
    ↓
nginx auth_request → svc-auth /verify
  ↓  decode cookie → session_id
  ↓  Redis GET session:{session_id} → user_id, access_token
  ↓  200 OK (X-User-Id, X-Session-Id headers)
    ↓
nginx → forwards request to svc-bff
  Cookie: sid=<session_id>
    ↓
svc-bff → decode cookie, get access_token from Redis
svc-bff → mint short-lived internal JWT (aud=svc-core, sub=user_id)
svc-bff → svc-core
  Authorization: Bearer <access_token>
  X-Internal-Token: <signed internal JWT>   # verified by svc-core
  X-User-Id: <user_id>
  X-User-Email: <email>
  X-User-Name: <name>
    ↓
svc-core → verify X-Internal-Token (signature, aud, exp) → trust sub as user id
svc-core → mint internal JWT (aud=svc-ai) → svc-ai
  X-Internal-Token: <signed internal JWT>   # verified by svc-ai middleware

When internal auth is enabled (INTERNAL_JWT_SECRET set), svc-core derives the trusted user id from the verified X-Internal-Token sub claim — not from the raw X-User-Id header — and svc-ai rejects any request lacking a valid token.

Token Lifecycle

TokenStorageTTL
Auth0 refresh tokenRedis (server-side only)Per Auth0 config (typically 30 days)
Session cookieBrowser (HTTP-only, signed)SESSION_MAX_AGE (default 15 min, extended on activity)

Token refresh: svc-auth checks whether the access token expires within TOKEN_REFRESH_THRESHOLD (300 s) on each /verify call. If so, it exchanges the refresh token with Auth0 and updates Redis transparently — no browser interaction required.

Security Measures

  • CSRF protection: state parameter generated per login, validated on callback; nonce stored alongside state in Redis

  • Token isolation: tokens stored only in Redis; session cookie contains only a signed session ID

  • Cookie flags: HTTP-only (no JS access), SameSite=Lax, Secure=true in production

  • Cookie signing: itsdangerous.URLSafeTimedSerializer with SESSION_SECRET; tampered cookies are rejected

  • Rate limiting: nginx enforces 5r/m on the auth.dev.datachainr.com virtual host

Auth Boundary Contract

This contract defines how identity propagates from edge traffic to internal services.

Runtime Trust Assumptions

  • svc-auth is the authentication authority and the only service that holds tokens.

  • nginx is the first enforcement point — no authenticated traffic reaches svc-bff without a valid /verify response.

  • svc-bff receives already-authenticated user context; it must not trust user-supplied identity headers from external requests.

  • svc-core and svc-ai are not internet-facing. They are isolated on an internal Docker network with no host ports published (see docker-compose.yml; host ports are added only by docker-compose.override.yml for local dev).

  • Identity is propagated via a signed, audience-bound internal token, not raw headers alone.

Internal Contract (implemented)

Calls from svc-bff to svc-core, and from svc-core to svc-ai, carry a signed internal token (X-Internal-Token):

  • Algorithm: HS256 with a shared secret (INTERNAL_JWT_SECRET).

  • Short-lived: INTERNAL_JWT_TTL (default 120 s).

  • Audience-bound per service (aud=svc-core or aud=svc-ai); a token for one service is rejected by the other.

  • Claims: sub (user id), iss, aud, iat, exp (plus email, name, and optional org and roles: see Platform roles).

  • Verification: signature, audience, and expiry are all enforced; required claims (exp, iat, sub, aud) must be present.

Implementation:

ServiceModuleBehaviour
svc-coreapp/common/internal_auth.pyVerifies inbound (aud=svc-core); mints aud=svc-ai for outbound svc-ai calls
svc-aiapp/middleware/internal_auth.pyVerifies every non-probe request (aud=svc-ai)

Migration safety: in development, when INTERNAL_JWT_SECRET is unset, verification falls back to the legacy forwarded-header trust (svc-ai becomes inert and logs a warning). The secret is required in staging and production across all three services — svc-bff, svc-core, and svc-ai each hard-fail at startup if it is missing (or shorter than 32 characters).

Service Responsibilities

ServiceResponsibility
svc-bffSession validation, token retrieval, header injection
svc-coreResource-level authorization (ownership, project membership)
svc-aiModel/workspace/document access constraints

Header Rules

  • External ingress must not be allowed to set X-Internal-Token, X-User-Id, X-User-Email, X-User-Name or X-User-Roles. nginx clears these on the /api/ and /api/ws/ locations (/api/ sets X-User-Id from svc-auth's /verify answer instead), and svc-bff drops any client-supplied copies before proxying. tools/security/test_identity_headers.py pins both.

  • Only svc-bff (and svc-core, for svc-ai) may set internal identity headers.

  • Downstream services reject requests when identity context is missing or invalid.

Migration Path (status)

  1. ✅ Keep nginx auth_request flow for edge authentication.

  2. ✅ Internal JWT verification in svc-core (get_current_user) and svc-ai (middleware).

  3. ✅ svc-bff mints audience-bound short-lived tokens for downstream calls; svc-core mints them for svc-ai.

  4. ✅ Identity derived from the verified token sub, not raw headers (when the secret is configured).

Remaining hardening

  • Rotate INTERNAL_JWT_SECRET via a secret manager; consider asymmetric (RS256/EdDSA + JWKS) if the signer/verifier trust boundary widens.

  • Propagate richer claims (permissions, org) and enforce them in svc-ai for per-workspace/model access. (Platform roles are carried as far as svc-core: see below.)

Platform roles

A platform role says what a person may do on CHAIN-R itself (run its developer tools, administer it), where a membership role (authorization.md) says what they may do in an organisation or project. They are assigned in Auth0 and travel with the identity on every request:

  1. Auth0: a post-login Action puts the user's assigned roles in one custom claim on the ID token (and, for completeness, the access token):

    ``js exports.onExecutePostLogin = async (event, api) => { // Without authorization the login says nothing about roles: leave // the claim off, and CHAIN-R changes nothing. An empty list would // take every role away. if (!event.authorization) return; const claim = "https://datachainr.com/roles"; const roles = event.authorization.roles ?? []; api.idToken.setCustomClaim(claim, roles); api.accessToken.setCustomClaim(claim, roles); }; ``

    The claim is namespaced on purpose: Auth0 restricts plain names such as roles. It is matched exactly, so if you choose another, set svc-auth's AUTH0_ROLES_CLAIM to it.

    In the Auth0 dashboard: Actions → Library → Create Action (Login / Post Login), paste the code, Deploy, then add it to Actions → Triggers → post-login. Create the roles under User Management → Roles (developer, superuser: the names CHAIN-R knows) and assign them to users there.

  2. svc-auth reads the claim (AUTH0_ROLES_CLAIM, default https://datachainr.com/roles; app/roles.py) at the callback, and again from a refreshed ID token in /verify, and keeps the list on the Redis session. /me serves it.

  3. svc-bff adds it to the internal token (roles) and, for the legacy header path, X-User-Roles (comma-separated).

  4. svc-core (app/services/platform_roles.py) keeps the user's row in step on every request (get_current_user, and at provisioning): users.platform_roles holds the roles it knows, and is_superuser is superuser in that list. require_role(PlatformRole.developer) guards a route, and a superuser holds every role. fe-core reads them as coreUser.platform_roles through hasPlatformRole.

Absent is not empty. A token without the claim (no Action configured, a session from before it) says nothing, and nothing changes: a superuser seeded locally, or the platform's system user, keeps it. A token whose claim is an empty list says "none", and every role is taken away. So once the Action runs, Auth0 is the source of truth: a superuser set by hand in the database loses it at their next sign-in unless Auth0 assigns it.

When a change takes effect: at the user's next sign-in, or sooner when their access token is refreshed (/verify refreshes within TOKEN_REFRESH_THRESHOLD of expiry, and Auth0 runs post-login Actions on refresh-token exchanges: Auth0's Post Login trigger). Signing out and in is the sure way.

RoleUnlocks
developerDeveloper tools such as scenario runs, on a deployment that switches them on. Changes no access check.

Logout Flow

1. Browser → GET /logout (svc-auth)
2. svc-auth → delete session and tokens from Redis
3. svc-auth → clear session cookie (set Max-Age=0)
4. svc-auth → redirect to Auth0 /v2/logout?returnTo=PUBLIC_URL