Skip to content

feat(platform): own trusted-header keys per organization - #3418

Merged
larryro merged 26 commits into
mainfrom
feat/trusted-headers-org-keys
Sep 18, 2026
Merged

larryro merged 26 commits into
mainfrom
feat/trusted-headers-org-keys

Conversation

@larryro

@larryro larryro commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The trusted-headers door (GET /api/trusted-headers/authenticate) becomes an organization-level feature. An admin turns it on, sets the highest role a proxy may assert and mints keys under Settings > Enterprise SSO > Trusted headers; an application's authenticating reverse proxy presents one of those keys with the identity headers, and the door resolves the organization from the key — the SCIM token's posture. The deployment-wide switch (TRUSTED_HEADERS_ENABLED, TRUSTED_HEADERS_INTERNAL_SECRET) and the login page's global auto-redirect are removed.

A second card on the same page, Embedding, lets the organization name the web origins that may show Tale inside a frame — the frame-ancestors allowlist a host application needs when it embeds Tale rather than opening it in a tab.

A proxied visitor is signed in without a sign-in page: the first request the app makes for itself that carries the key and the identity header (and no session cookie) is answered signed in, the session minted on the spot. The sign-in page still hands off by itself as a fallback, the door answers a redirect instead of a page of its own, refusals come back to the app rendered in its own words, and the proxy owns the session — no Log out is offered for it, and an inactivity sign-out pauses the automatic sign-in until the member continues.

Why

The old mode was one env switch and one env secret for the whole deployment: every proxy sign-in landed in the earliest organization with an owner or admin, the login page redirected everyone, and rotating the secret meant a redeploy. None of that works on a deployment that hosts several organizations, where a hosting application must sign its users into its organization and no other. Nobody runs the deployment-wide mode, so it goes without a compatibility shim.

Framing was refused outright (frame-ancestors 'none' + X-Frame-Options: DENY on every response), so an application that wanted Tale inside its own page had no knob at all.

The old auto-redirect was driven by the deployment flag and hit every visitor; the new one is driven by the request itself (does it carry the proxy's headers?), so a deployment without a proxy never sees it and a deployment with one needs no extra routing.

What changes

  • Migration 0108 — app.trusted_header_settings (switch + role ceiling per organization) and app.trusted_header_keys (name, SHA-256 hash, display prefix, created / last-used / revoked stamps; unique hash index). Revocation is a stamp, never a delete.
  • /api/app/trusted-headers — admin surface (orgSettings ability): read the view, PUT /settings, POST /keys (plaintext answered once, at most 10 live keys), DELETE /keys/:id (idempotent). Every write audits (trusted_headers_enabled|disabled|policy_updated, trusted_header_key_created|revoked).
  • The door — reads the key from the key header (TRUSTED_SECRET_HEADER, default Remote-Internal-Secret; an Authorization header is ignored, so the REST API key can never be mistaken for it), resolves the organization by hash, refuses a paused organization or a revoked key, charges unknown keys to the source IP (trusted-headers:auth-fail-ip), clamps Remote-Role to the organization's ceiling (owner never), and applies the SSO org-binding contract: existing member → sign in; address new to the deployment → JIT member inside this organization; existing account from another organization → refused before any write. Sessions carry trustedRole + a new trustedOrganizationId; backend/auth/org.ts applies the override to that organization only and never demotes an owner. Every sign-in audits trusted_headers_sign_in naming the key.
  • Settings card — switch, ceiling, hand-off URL, effective header names, key list with create (shown once, each copy field labelled with the header the key travels in, button beside the list it grows) and revoke (confirm) flows; en/de/fr copy.
  • Removed — the deployment switch in the backend, lib/env.ts, server.ts and the login page; the orphaned common.sessionIdle.continueToSignIn key.
  • Shared helper — backend/core/lib/opaque_token.ts; the SCIM token helpers delegate to it (same bytes, same prefix shape).

Signing a proxied visitor in

  • Transparent sign-in — a GET the app makes for itself (/api/app/*, Better Auth's session probe) that carries the organization's key and the identity header but no session cookie is answered signed in: the backend mints the session on the spot (trustedHeadersSessionMint), the cookie rides on the response, and the session gates read the request as if the browser had sent it (auth/minted-cookie.ts). Never on a POST, never for a cross-site fetch, never while a session cookie is present, never while the app's hold cookie stands. The dashboard opens directly; no sign-in page, no hop through the door.
  • The door answers a redirect — a success is a 302 to the in-app return path with the cookie; no page of its own. A refusal of a hand-off the app started (via=app) goes back to the sign-in page with its reason, rendered there in the app's own words (login.proxyHandoff.errors.* + a recovery hint); a proxy-routed or terminal refusal is answered as a plain, colour-scheme-aware page with its status code — a redirect to /log-in would only bounce back through a proxy that routes /log-in here. One shared function (handOffFromHeaders) judges a request for the door and the middleware alike.
  • Sign-out belongs to the proxy — the account menu offers no Log out for a proxied session (session.trustedOrganizationId). After an inactivity sign-out the watchdog sets a short-lived hold cookie (tale_handoff_hold): the backend does not mint while it stands and the sign-in page waits behind Continue with automatic sign-in, so the inactivity notice is seen (Feature: Session idle timeout (server-side enforcement + client watchdog) #1502).
  • Sign-in page fallback — the page still hands off by itself when it lands on a proxied request (a stale cookie), shows a refusal the door sent back instead of retrying, and reloads when it comes out of the back/forward cache mid hand-off rather than reviving a frozen "signing you in" notice.
  • GET /api/app/sso/discovery/trusted-headers — public, on the existing login-page discovery lane, answers { handoff }: does this request carry the key (bearer / key header) or the proxy's identity email header? Presence only, Cache-Control: no-store; validation stays at the door, which already budgets failures per source IP, so no second key oracle opens.
  • Login page — asks before rendering; on a yes it sends the browser to the door on the origin the browser is on (a same-origin path, never SITE_URL, so a gateway on another hostname stays in the path and keeps injecting the key) with the validated return path (?redirect=, same-origin paths only) and shows a "signing you in" notice instead of the form. Held back on a fresh deployment (setup wins), after an inactivity sign-out (the notice stays visible behind Continue with automatic sign-in, Feature: Session idle timeout (server-side enforcement + client watchdog) #1502), and when this tab was sent to the door within the last minute and came back without a session (refused, or the cookie never reached a cross-site frame) — then the form shows with a notice and Try again, never a redirect loop. sessionStorage marker, fail-closed to the form when storage is unavailable.
  • Copy auth.login.proxyHandoff.* in en/de/fr.

Role and teams follow the proxy

  • Seat follows the assertion — an existing member who signs in through the proxy has their seat moved to the (clamped) asserted role, with the same update_member_role audit a manual change writes; an owner seat is never moved. GET /api/app/members/me reports the role the org gate enforces on the request, so the app never shows a stale seat while the backend enforces another role.
  • Plain team names — Remote-Teams accepts Finance,Operations (the form most authenticating proxies emit) as well as id:name pairs; teams are matched and created by name. A bare list used to be dropped as "no teams", which revoked synced memberships.
  • One key header — the key travels in the key header only; the key-created dialog shows one field labelled with that header.

Embedding (frame ancestors)

  • embedding governance policy (@tale/shared) — { enabled, frameAncestors[] }; an origin is https://host[:port] (lowercase) or plain http:// on loopback, at most 16, matched by a character-restricted pattern because the value lands in a response header. Disabled or absent admits nothing. It rides the existing policy file lane (<org>/governance/embedding.yml, generic /api/app/governance/policies/embedding routes, tale config apply) — no new endpoint; the seed catalog ships the closed default.
  • Web tier — lib/org-frame-ancestors.ts scans every organization's policy (TTL-cached, same shape as the storage-origin scan) and the SPA shell's CSP carries frame-ancestors 'self' <union>; X-Frame-Options, which cannot express an allowlist, is left off while anything is admitted and returns to DENY when nothing is. The canvas preview, framed by the shell, admits the same list (the browser checks every ancestor of a document).
  • Backend — the trusted-headers door stamps its framing headers per organization once the key has named one (frame-ancestors 'none' + DENY before that); backendSecureHeaders({ frameable }) lets that door alone own the header, every other response keeps the fixed DENY.
  • Settings card — switch (saves at once), origin list (saves from its own button once every line is an admissible origin), same-site note; en/de/fr + a de-CH override.

Caveats, documented: the shell is one document for the whole deployment, so an origin any organization admits may load the shell (the session inside the frame still decides what it can reach; the door judges per organization). The session cookie stays SameSite=Lax, so a frame carries the signed-in session only when the host page is on the same site as Tale (a subdomain, or Tale served under the host's domain); a cross-site frame shows the sign-in page — which, with the loop guard above, offers a retry instead of bouncing. The dev-server preview plugin keeps its fixed SAMEORIGIN.

Proxy contract (documented)

Strip client-supplied Remote-* headers, add the key only on the hand-off request, keep the backend reachable only through the proxy. Routing /log-in to the hand-off address remains supported; a proxied visitor is signed in on the app's first request without it. Header names stay renamable via TRUSTED_*_HEADER.

Docs

self-hosted/configuration/authentication.md (proxy section rewritten, table and diagnosis rows, embedding paragraph, hand-off paragraph), environment-reference.md (two variables removed, two descriptions updated), platform/admin/enterprise-sso.md (new section incl. embedding + hand-off sentence + troubleshooting row) — en/de/fr; docs manifest regenerated.

Tests

  • unit: domains/trusted_headers/service.test.ts, routes.test.ts, domains/sso/trusted-headers.test.ts (rewritten, framing cases), domains/sso/admin-routes.discovery.test.ts (probe), domains/sso/trusted-headers.mint.test.ts (transparent sign-in: mints on a cookieless GET, forwards the cookie to the gate and to Better Auth, never on POST / cross-site / with a cookie / under the hold, charges an unknown key), domains/members/member-context.test.ts (enforced role reported), user-button.test.tsx (no Log out for a proxied session), use-session-idle-watchdog.test.tsx (hold cookie), parseTeamsHeader cases (plain names, id:name, blanks), trusted-headers-section.test.tsx, embedding-section.test.tsx, login-proxy-handoff.test.tsx (hand-off, return-path sanitising, loop guard, idle hold, setup wins), lib/org-frame-ancestors.test.ts, server.test.ts (frame ancestors + canvas preview), backend/lib/http-hygiene.test.ts (frameable variant), @tale/shared governance.test.ts (origin pattern, cap, frameAncestorsOf)
  • integration: checkTrustedHeaders rewritten (card → key → door → refusals → pause → revoke → audit) and extended: door headers DENY / frame-ancestors 'none' before the policy write, frame-ancestors 'self' https://embed.example with no X-Frame-Options after
  • manual: AUTH-F21, AUTH-F22, AUTH-F23, AUTH-F24, AUTH-B10; automation + error-code registers
  • live, on the dev stack: the door with a real key → 200, session cookie, member of the issuing organization only, meta-refresh to the dashboard; the probe → {"handoff":false} plain, true with the identity header or the key header

One commit realigns two integration probes that were already red on main and truncated the suite: the unverified-reply refusal now forces an unverified fixture (every provisioned account arrives verified since #3408), and the robots probes read the stored policy through the crawler's own reader (the object shape from #3410). Neither is about this branch; without them the suite stopped at lane 95 of 150.

Gates observed (after the hand-off commits, rebased on 05f7027)

  • @tale/platform + @tale/shared lint and typecheck: clean; Knip clean
  • @tale/platform server + pii unit projects: 743 files / 76 180 tests passed
  • @tale/platform UI suite: 404 files / 3 192 tests passed
  • @tale/shared governance tests 49 passed; @tale/cli config tests 182 passed
  • backend:integration against a throwaway Postgres + MinIO: 693/693 checks across 150/150 lanes (re-run after every round; the door lane now covers the 302 answer, the transparent sign-in on /api/app/users/me, the hold cookie, the seat move with its audit, and the refusal that returns to the app)
  • @tale/platform browser-mode project: 20 files / 69 tests, from a cold Vite cache too. The Checks / Browser job had failed twice on this head with two different symptoms (an import-time "failed to find the current suite", then a second React inside Radix) — both were Vite discovering twelve dependencies mid-run and reloading the page; the project now pre-bundles them (optimizeDeps), reproduced and verified locally from a cold cache
  • @tale/docs test (166) + lint, lint:manual, format:check: green
  • CI on the previous head b2f3d6d: all six workflows green

Operator follow-up (not in this PR)

A hosted deployment that wants to admit an application's proxy adds that proxy's public origin to additionalOrigins and creates the organization the proxy will sign users into; the admin then enables the trusted-headers card, hands the key to the proxy and, for an in-page embed, lists the host page's origin under Embedding.

@larryro
larryro force-pushed the feat/trusted-headers-org-keys branch from d090c02 to e8c90e0 Compare September 18, 2026 14:03
The trusted-headers door becomes an organization-level feature: an admin
mints keys under Settings > Enterprise SSO, and the door resolves the
organization FROM the presented key (the SCIM token's posture) instead of
landing every proxy sign-in in the earliest admin organization.

- migration 0108: app.trusted_header_settings (switch + role ceiling) and
  app.trusted_header_keys (SHA-256 hash, prefix, revoke stamp)
- /api/app/trusted-headers: view, PUT settings, POST keys (plaintext once,
  10 live keys), DELETE keys/:id; every write audited
- the door reads the key from Authorization: Bearer or the configurable
  key header, refuses paused organizations and revoked keys, charges
  unknown keys to the source IP, clamps Remote-Role to the ceiling and
  applies the SSO org-binding contract (member signs in, new address is
  created inside the organization, a stranger is refused before any write)
- sessions carry trustedRole + trustedOrganizationId; the org middleware
  applies the override to that organization only and never to an owner
- the deployment-wide TRUSTED_HEADERS_ENABLED / _INTERNAL_SECRET mode is
  removed; TRUSTED_*_HEADER name overrides stay
- SCIM token helpers delegate to the shared opaque-token helper
- integration probe rewritten: card -> key -> door -> refusals -> pause ->
  revoke -> audit
The card carries the organization's switch, the highest role a proxy may
assert, the hand-off URL and header names the proxy must speak, and the
keys: created in a dialog that shows the plaintext once, revoked behind a
confirm. Copy in en/de/fr.

The login page no longer auto-redirects for a deployment-wide proxy mode
(the host proxy routes /log-in to the door itself), and the flag leaves
the SPA env; the orphaned continue-to-sign-in message goes with it.
The authentication page's proxy section, its table rows and diagnosis
row now describe the per-organization key; the environment reference
drops the two deployment switches and re-describes the key and role
headers; the Enterprise SSO admin page gains the proxy sign-in section
and a troubleshooting row. en/de/fr, manifest regenerated.
AUTH-F21 (card), AUTH-F22 (proxy hand-off signs a member in) and
AUTH-B10 (door refusals), the automation register row for the specs
that own the rest, and the door's error surface in the error-code map.
The unverified-reply refusal needs an unverified fixture now that every
provisioned account arrives verified, and the robots probes read the
stored policy through the crawler's own reader instead of expecting the
legacy bare array. Both were red on main; neither is about this branch.
An organization may name the web origins allowed to show its pages
inside a frame. The policy is {enabled, frameAncestors[]}: an origin is
https with a lowercase host and optional port, or plain http on loopback,
at most 16 of them, matched by a character-restricted pattern because the
values are interpolated into a response header. Disabled or absent admits
nothing, which is what every deployment does today. The seed catalog
ships the closed default so a new organization's config tree shows the
knob, and the file lane (tale config apply) covers it like every other
policy.
… door

Tale's security headers refused every frame ancestor. With the embedding
policy an organization can admit a host page's origin: the web tier scans
every organization's policy file (TTL-cached, like the storage origins)
and puts 'self' plus the union on the SPA shell's frame-ancestors;
X-Frame-Options, which cannot express an allowlist, is left off while
anything is admitted. The canvas preview, framed by the shell, admits the
same list because the browser checks every ancestor of a document.

The trusted-headers door judges framing per organization once the key
has named one; nothing may frame the door before that, and the backend's
fixed DENY steps aside for that door alone. The integration probe writes
the policy and reads the door's headers before and after.
The card beside the trusted-headers card edits the embedding policy: the
switch saves at once, the origin list saves from its own button once
every line is an admissible origin, and a note explains that a frame
carries the session only on the same site. Copy in en/de/fr with a
Swiss-German override.
The authentication page's proxy section and the Enterprise SSO admin page
explain the Embedding card, the frame-ancestors headers it drives, the
union-across-organizations caveat of the one shell document and the
same-site cookie rule for frames. en/de/fr.
AUTH-F23 walks the card, the header change on an app page and the close
on switch-off; the automation register names the specs that own the rest.
…hemas

The settings and key-create input types inferred from the request schemas
were exported and never read, which Knip refuses. The SPA contract's
mutation args and the service signatures now derive from them, so the
wire body, the adapter and the service share one shape.
@larryro
larryro force-pushed the feat/trusted-headers-org-keys branch from b74d3dc to b2f3d6d Compare September 18, 2026 14:48
A request that arrives through an application's authenticating proxy no
longer depends on a proxy rule for /log-in: the sign-in page asks the
backend whether the proxy's identity header or the organization's key rode
on the request (GET /api/app/sso/discovery/trusted-headers, public,
presence only — the door keeps validating) and sends the browser to the
hand-off door with the validated return path. Routing /log-in at the proxy
still works and saves the round trip.

The page holds back on a fresh deployment (setup wins), after an
inactivity sign-out (the notice stays visible behind a Continue button)
and when this tab was sent to the door within the last minute and came
back without a session — refused, or the cookie never reached a cross-site
frame — where it shows the form with a notice and a retry instead of
looping. Copy in en/de/fr.
The sign-in page hands off to the door by itself when it sees the proxy's
identity header; routing /log-in at the proxy saves the round trip and
stays recommended. Both pages also say what happens when a hand-off does
not end in a session. en/de/fr.
AUTH-F24 walks the automatic hand-off with injected headers, the no-loop
notice after a refused door and the Continue hold after an inactivity
sign-out; the automation register names the probe and page specs.
The button sat in the trusted-headers card header, three settings above
the list it adds to. It now shares the Keys heading row, right-aligned,
with the same enablement (admin, loaded, under the key limit).
The login page built the door's address from SITE_URL. A browser that reaches Tale through a gateway on another hostname would have been sent straight to the canonical origin — past the proxy that injects the key, and with the cookie landing on the wrong host. The address is now a same-origin path.
The key-created dialog showed a bare secret and left the person to find
the header name three settings up the card. It now shows two copyable
fields labelled with the headers the proxy may send the key in — the
deployment's key header with the key, and Authorization with the bearer
form — plus the one-time-copy notice. Copy in en/de/fr.
The door and the login-page probe read the key from the key header only
(Remote-Internal-Secret unless TRUSTED_SECRET_HEADER renames it). The
Authorization: Bearer variant was a second thing to document and easy to
confuse with the REST API key; an Authorization header on the door is now
ignored. The key-created dialog shows one field, labelled with that
header, and the card copy names one way to send it. Copy in en/de/fr.
…ign-in

An existing member who signed in through the proxy kept the seat they
were created with: the session carried the newly asserted role and the
org gate enforced it, but the app read its role from the seat row and
showed the old one. The seat now follows the (clamped) assertion on every
sign-in — an owner seat is never moved — with the same update_member_role
audit a manual change writes, and GET /api/app/members/me reports the
role the org gate enforces on the request.

Remote-Teams accepted only id:name pairs and dropped a plain group list
such as "teamA,teamB" — the form most authenticating proxies send — which
then read as "no teams" and revoked synced memberships. Teams are matched
and created by name, so a bare entry is its own id; id:name still works.
The integration probe checks the seat and its audit after a re-assertion.
…m names

The proxy sends the key in the key header only; the member's seat follows
the asserted role on every sign-in (owner never); Remote-Teams takes plain
team names, with id:name still accepted. en/de/fr.
… boxes

AUTH-F22 sends the key in the key header, asserts teams by name and
re-asserts a lower role to watch the seat and its audit follow; AUTH-B10
drops the key header instead of the bearer.
A GET the app makes for itself — the session probe, a read under
/api/app — that carries the organization's key and the identity header
but no session cookie is now answered signed in: the session is minted on
the spot, the cookie rides on the response, and the session gates read
the request as if the browser had sent it. Never on a POST, never for a
cross-site fetch, never while a session cookie is present, and never
while the app's hold cookie (set after an inactivity sign-out) stands.

The hand-off door and the new middleware judge a request through one
shared function. The door answers a success with a 302 to the in-app
return path — no page of its own — and a refusal of a hand-off the app
started (via=app) goes back to the sign-in page with its reason, while a
proxy-routed refusal is answered as a plain page with its status code,
since a redirect to /log-in would only bounce back through a proxy that
routes /log-in here. The integration probe covers the redirect, the
transparent sign-in, the hold and the refusal that returns to the app.
…n-out

The account menu offers no Log out for a session an authenticating proxy
asserted — a sign-out would be undone by the very next request the proxy
signs in. The inactivity watchdog sets a short-lived hold cookie before
it signs out; the backend does not mint while it stands and the sign-in
page waits behind a Continue button, so the inactivity notice is seen.
The page also shows a refusal the door sent back instead of handing off
again, tells the door it came from the app, and reloads when it comes out
of the back/forward cache mid hand-off rather than reviving a frozen
"signing you in" notice. Copy in en/de/fr.
The authentication and Enterprise SSO pages describe the sign-in without
a page, the door's redirect answer, the refusal that returns to the app,
the missing sign-out for proxied members and the pause after an
inactivity sign-out. en/de/fr.
… hold

AUTH-F22 expects the door's redirect; AUTH-F24 walks the dashboard opening
directly, the missing Log out, the refusal rendered in the page and the
hold behind Continue; the automation register names the new specs.
In browser mode Vite pre-bundled only what its first scan reached, so the dependencies the component tests import were found one test file at a time while the run was under way; every late find re-bundled and reloaded the page and killed the files in flight — an import-time "failed to find the current suite" in one run, a second React inside Radix's TooltipProvider in the next. The scan now covers the browser test files themselves and names the twelve packages the runs kept discovering late, so the first bundle is the last. Reproduced from a cold cache locally: the same reload and failures without this, twenty green files with it.
@larryro
larryro merged commit 3c39e4f into main Sep 18, 2026
56 checks passed
@larryro
larryro deleted the feat/trusted-headers-org-keys branch September 18, 2026 17:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant