Skip to content
MSO CloudDocumentation

ADR 0045 — Branded per-org sign-in page and per-org OpenID Connect

On this page
  • Status: Accepted. Batches C1/E1 (2026-09-03), commits 2123ff6f, 69bca3da, a237ad68.
  • Owners: Platform (security / site programme).
  • Extends: ADR 0016 (host-first tenant resolution; the NEXTAUTH_URL-precedence gap this ADR's callback design routes around), ADR 0033 (org-owned-row pattern; the login page deliberately stops short of site_themes), ADR 0034 (LDAP D2 entitlement shape, D4 identity rules, and D5 egress-guard shape, all reused verbatim).

Context#

Sign-in was one global page: platform copy, platform logo, platform theme, no org-specific branding or method visibility anywhere. No OIDC/SAML provider existed. An org that wants its own logo, colours, and "Sign in with Google/Entra" needs a per-org config surface resolved BEFORE any session exists (the same constraint ADR 0016/0034 already solved for host and directory resolution), and a per-org OAuth provider — a materially different problem from the four existing Credentials providers, because Auth.js drives the authorization-code redirect itself and needs clientId/issuer known at NextAuth() construction time, not inside a provider's own authorize().

Decisions#

D1 — org_login_page: one draft/published pair per org, publish-to-go-live

Migration 0189: org_login_page (one row per org, enabled — a super-admin entitlement flag, identical shape to org_auth_ldap.enabled — plus the draft copy fields: logo light/dark, favicon, one accent colour, bilingual headline/tagline, support email, legal links, method order, method visibility) and org_login_page_versions (append-only, one row per publish, holding the published snapshot). Editing the draft never changes what a visitor sees — publishing does. Rollback copies a past version's config into published and inserts a NEW history row rather than rewriting history, the same append-only discipline the decision-replay ledger runs on. methodVisible can only HIDE a method that is otherwise entitled (its own enabled flag, e.g. org_auth_ldap.enabled or an org_auth_oidc row) — it can never grant one.

D2 — Resolution: a SECURITY DEFINER locator, not an RLS exception

app_get_org_login_page(p_org_id uuid) — STRICT, SECURITY DEFINER, returns only the published jsonb, GRANT EXECUTE to the app role only, called with the org id getRequestTenant() already resolved from the host. Rejected the site_themes-style RLS-exception route (ADR 0033 D2): that exception exists because ONE row must satisfy TWO cohorts (platform union this org) for an anonymous reader that does not yet know which org it is; a login page has no such ambiguity — the org is already the exact output of the host locator — so a policy exception would be pure overhead for a narrower problem. Re-validated on read (orgLoginPageConfigSchema.safeParse) and falls through to the platform default on any failure (unresolvable row, failed parse, DB error) — the same never-throw contract getSiteIdentity/loadSiteTheme already use. Request-memoized.

D3 — Ceiling: what an org can brand, what it cannot

An org sets logo/favicon/one accent colour/copy/method order/method visibility — never the full colour system (site_themes' brand/surface/sidebar/border/chrome payload, ADR 0033's refusal list), the auth method implementations themselves, error/lockout copy, or the domain binding. accentColor paints the login CARD only (button/link/focus-ring), applied client-side from the fetched config, never through the <style id="yng-skin"> §69 injection path — the login editor is a strict subset of the ADR 0033 override surface. The editor's live preview renders the ACTUAL SignInForm component fed the draft as props, so the preview can never drift from the real page.

D4 — org_auth_oidc: one row per (org, provider); super-admin entitlement, LDAP D2 shape

Migration 0192: one row per (org_id, provider_key) — unlike LDAP's one directory per org, an org may run Google Workspace AND Entra AND a generic IdP at once. enabled is the SAME super-admin entitlement flag ADR 0034 D2 defines, and is enforced in the router itself, not only by the UI — orgAuthOidc.get/save/test (apps/web/src/server/routers/org-auth-oidc.ts) checks isSuperAdmin || row.enabled === true before returning or accepting a mutation, so a disabled row is unreachable from the API even by a caller who bypasses the settings screen. The client secret is envelope-encrypted (AES-256-GCM), the exact shape of org_auth_ldap/ai_connections. Group-to-role and group-to-brand maps (group_role_map, group_brand_map) and a JIT-provisioning switch (jit_provisioning, off by default) ship from day one — ahead of LDAP's own still-open P6 phase — via a standalone, directory-agnostic module (D8) LDAP can adopt later instead of forking.

D5 — One platform-host callback per provider TYPE; org identity carried in signed state

The decision that reversed the initial per-org-host-callback design, made after a spike proved it unworkable: next-auth@5.0.0-beta.32's request-aware initializer (NextAuth(async req => config)) correctly constructs a per-org-host OIDC provider, but Auth.js's own reqWithEnvURL rewrites every request's origin to NEXTAUTH_URL BEFORE computing redirect_uri — a layer the request-aware initializer cannot reach — and this repo's production docker-compose.prod.yml sets NEXTAUTH_URL to the fixed platform apex. A per-org-host callback would therefore always collapse to the platform apex regardless of which org's flow was running, breaking "each org registers its own callback URL." Removing NEXTAUTH_URL platform-wide (the ADR-0016-consistent fix) was rejected as too broad a change to land inside this batch. Decision: custom route handlers, not NextAuth()'s own OAuth machinery — /api/auth/oidc/start and /api/auth/oidc/callback/[providerId], always reached at the PLATFORM host, providerId naming a provider TYPE (oidc-google/oidc-entra/oidc-generic), never an org. The org id, provider key, and return host travel in a signed, HMAC'd state payload (oidc-state.ts, the same mechanism connector-oauth.ts already ships for TikTok Shop/Lazada/LinkedIn authorization) with a 10-minute TTL. state alone proves the token was minted by this server for this org/provider/return-host; it does NOT bind the callback to the same browser that started the flow (login-CSRF), so a separate flow COOKIE (oidc-flow-cookie.ts) carries the same state value and the callback route refuses unless the cookie's copy matches the query param.

D6 — PKCE, state, and platform-host session handed off via the existing magic-link token

checks: ['pkce','state'] equivalent hand-rolled in oidc.ts (generatePkcePair, buildAuthorizationUrl) since the flow does not go through NextAuth()'s own provider machinery (D5). Because the callback lands on the PLATFORM host but the session cookie must be host-scoped to the org's tenant host (ADR 0016 §2), the platform-host request cannot set that cookie directly — the callback hands off to the org's own host through the EXISTING single-use magic-link token mechanism (issueMagicLinkToken), never a new session-transfer primitive. Every failure redirects to /auth/signin?error=oidc-refused with one generic error — never a reason that would let a caller distinguish "wrong org" from "expired flow" from "directory refused" (mirrors LDAP D5's posture).

D7 — Verified email required; discovery/token/userinfo/JWKS fetches pinned; id_token verified

Three security-review fixes (batch 14, applied before this ADR's implementation status below counts D5-D6 as landed):

  • Verified email required per provider preset (claimMap.emailVerified, default email_verified for google/generic, xms_edov for entra) — an unverified email is refused before matching or provisioning a user; unverified was previously trusted implicitly.
  • Connection-pinned fetches (oidc-pinned-fetch.ts): every OIDC network call (discovery, token, userinfo, JWKS) resolves-and-vets the host once via the same resolveAndPinLdapHost guard ADR 0034 D5 built for LDAP, then dials the exact pinned IP while keeping servername/Host at the original hostname — closing the same DNS-rebind TOCTOU class ADR 0034 closed for LDAP, one layer up (fetch() otherwise re-resolves DNS itself after the host was already vetted). A 3xx redirect is followed only when its target is the SAME pinned hostname.
  • id_token signature, issuer, audience, expiry, and nonce verified (oidc-jwt-verify.ts) against the cached JWKS via Node's own crypto.verify() (no external JOSE dependency) — the module previously decoded the token without verifying its JWS signature, trusting the back-channel TLS connection alone; alg: 'none' and any algorithm outside an explicit allow-list are refused, never silently skipped.

D8 — Directory group mapping is directory-agnostic, built once

directory-group-mapping.ts: pure, no db, no network — resolves a configured group -> role / group -> brand ids mapping against the groups an identity was handed, highest-privilege-first when more than one group matches a different role. owner is never a reachable target of an automatic mapping (filtered out before precedence runs) — a self-editable "groups" claim on a generic IdP could otherwise let a low-privilege member self-assign an org-mapped group name and escalate on next login. Membership validation (a mapped brand id actually belongs to this org) is the CALLER's job, over the DB, not this module's. Shared by both OIDC (built first) and LDAP's still-open P6 phase, rather than forked.

D9 — Identity resolution reuses ADR 0034 D4 verbatim

resolveDirectoryUser (shared with LDAP): match by email, sync name only, no auto-provisioning unless jit_provisioning is explicitly on; no super-admin via SSO; single-org members only.

Consequences#

  • An org's IT admin registers exactly one callback URL per provider type on the platform host in their IdP console — never a per-org host, and never the fixed platform apex silently substituted for their own registered value.
  • OIDC is inert (every route 404/refuses) until BOTH a super-admin enables the row AND an org admin configures it — the same two-key entitlement shape LDAP already established.
  • The branded login page and OIDC are independently toggleable: an org can brand its sign-in page without ever configuring SSO, and vice versa.

Implementation status (declared 2026-09-03)#

Decision Status Evidence
D1 org_login_page + versions Landed migration 0189_org_login_page.sql; apps/web/src/server/routers/org-login-page.ts
D2 SECURITY DEFINER locator Landed app_get_org_login_page, same migration file; login-page-render.ts
D3 branding ceiling + live preview Landed settings/login-page/_components/login-page-settings-form.tsx; org-login-page-toggle.tsx (admin)
D4 org_auth_oidc + entitlement Landed migration 0192_org_auth_oidc.sql; entitlement enforced in org-auth-oidc.ts router, not only the UI
D5 platform-host callback + signed state Landed /api/auth/oidc/start, /api/auth/oidc/callback/[providerId]; oidc-state.ts; oidc-state-tampering.test.ts
D6 PKCE + magic-link handoff Landed oidc.ts (PKCE), oidc-flow-cookie.ts, issueMagicLinkToken reused; auth/magic/route.ts
D7 verified-email + pinned fetch + id_token verify Landed oidc-email-verified.test.ts, oidc-pinned-fetch.ts + test, oidc-jwt-verify.ts + test (security review batch 14)
D8 shared group-mapping module Landed apps/web/src/auth/directory-group-mapping.ts; oidc-group-mapping.test.ts
D9 identity resolution reuse Landed apps/web/src/auth/directory-user.ts (resolveDirectoryUser), shared by LDAP and OIDC

Non-goal (recorded, not built)#

Apex (non-tenant-host) OIDC sign-in with an org picker — out of scope, same posture as ADR 0034 D1's LDAP non-goal. Removing NEXTAUTH_URL platform-wide (D5's rejected broader fix) stays a named, sizeable follow-up, not silently abandoned.