Join the platform: one-account provision.sql and the FRAME_ANCESTORS switch

- db/managed/provision.sql is rendered with --identity-schema dredd
  --identity-owner atrium_migrator, as the platform's push.sh compares it;
  CI's --check-file step and db/managed/README.md follow.
- FRAME_ANCESTORS ('none' by default -> DENY, 'self' -> SAMEORIGIN; anything
  else refuses to start) drives the CSP frame-ancestors and X-Frame-Options,
  so Atrium can frame the console. deploy_check matches the middleware with
  its keyword argument.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-20 22:52:06 +02:00
co-authored by Claude Opus 5.5
parent 13ff35bbc8
commit e86e5bff84
9 changed files with 134 additions and 33 deletions
+4
View File
@@ -170,6 +170,10 @@ SESSION_COOKIE_SECURE=
# separately-served console in dev.
CORS_ALLOW_ORIGINS=
# Who may frame Insider: 'none' (default; X-Frame-Options DENY) or 'self' (SAMEORIGIN, what the
# platform's kit sets). Anything else refuses start-up.
FRAME_ANCESTORS='none'
# ── Bootstrap admin (seed) ───────────────────────────────────────────────────
BOOTSTRAP_ADMIN_EMAIL=admin@example.com
BOOTSTRAP_ADMIN_PASSWORD=admin12345
+1
View File
@@ -138,6 +138,7 @@ jobs:
run: |
python -m dredd_core.managed provision --sql-only \
--schema insider --app-role insider_app --migrator-role insider_migrator \
--identity-schema dredd --identity-owner atrium_migrator \
--check-file db/managed/provision.sql
- name: Emulate a managed Postgres (TEST-ONLY)
# The service is on localhost, so no --allow-remote (emulate refuses a non-local host without it).
+13
View File
@@ -311,6 +311,11 @@ class Settings(BaseSettings):
# separately-served console in dev.
cors_allow_origins: str = ""
# Who may frame the console: 'none' (default; X-Frame-Options DENY) or 'self' (SAMEORIGIN, what
# the platform's kit sets so Atrium can frame its modules same-origin). Anything else refuses
# start-up: a third-party origin here would let a foreign site frame privileged data.
frame_ancestors: str = "'none'"
# Bootstrap admin (seed)
bootstrap_admin_email: str = "admin@example.com"
bootstrap_admin_password: str = "admin12345"
@@ -320,6 +325,14 @@ class Settings(BaseSettings):
otel_service_name: str = "insider-backend"
otel_exporter_otlp_endpoint: str = "http://otel-collector:4317"
@field_validator("frame_ancestors")
@classmethod
def _known_frame_ancestors(cls, v: str) -> str:
bare = v.strip().strip("'")
if bare not in ("none", "self"):
raise ValueError("FRAME_ANCESTORS must be 'none' or 'self'")
return f"'{bare}'"
@property
def shares_identity(self) -> bool:
"""True when this deployment is a MODULE of the platform rather than a standalone app.
+18 -10
View File
@@ -33,12 +33,18 @@ MAX_BODY_BYTES = 100 * 1024 * 1024
# Content-Security-Policy for the console. 'unsafe-inline' is required by the theme pre-paint inline
# <script> in index.html, the inline onclick handlers app.js renders, and inline style=""
# attributes. Nothing loads from a CDN — the console is entirely same-origin, which is the point
# when the data is privileged.
CONSOLE_CSP = (
"default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; "
"frame-src 'self'; form-action 'self'; img-src 'self' data: blob:; font-src 'self' data:; "
"style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; connect-src 'self'"
)
# when the data is privileged. `frame-ancestors` comes from settings.frame_ancestors (FRAME_ANCESTORS):
# 'none' by default, 'self' on the platform, where Atrium's front door frames its modules same-origin.
def content_security_policy(frame_ancestors: str) -> str:
return (
f"default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors {frame_ancestors}; "
"frame-src 'self'; form-action 'self'; img-src 'self' data: blob:; font-src 'self' data:; "
"style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; connect-src 'self'"
)
# The default ('none') policy, pinned by tests/test_edge.py.
CONSOLE_CSP = content_security_policy("'none'")
def owns_path(path: str) -> bool:
@@ -60,15 +66,17 @@ class SecurityHeaders:
Pure ASGI (not `@app.middleware("http")`) so it wraps the responses the other middlewares
produce and a streamed body is not buffered. Added LAST in main.py, i.e. outermost.
Everywhere: nosniff, `X-Frame-Options: DENY`, `Referrer-Policy: same-origin`,
Everywhere: nosniff, `X-Frame-Options` (DENY for FRAME_ANCESTORS='none', SAMEORIGIN for 'self'), `Referrer-Policy: same-origin`,
`Cross-Origin-Opener-Policy: same-origin`. On the console only (anything outside /api and
/healthz): the CSP and `Cache-Control: no-cache` (revalidate by ETag, so a rebuilt app.js/app.css
is picked up without a hard refresh). Defaults only: a header a route already set wins. The
`Server` header is not removed here; uvicorn runs with --no-server-header.
"""
def __init__(self, app: ASGIApp) -> None:
def __init__(self, app: ASGIApp, *, frame_ancestors: str = "'none'") -> None:
self.app = app
self.csp = content_security_policy(frame_ancestors)
self.xfo = "SAMEORIGIN" if frame_ancestors == "'self'" else "DENY"
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
@@ -80,12 +88,12 @@ class SecurityHeaders:
if message["type"] == "http.response.start":
headers = MutableHeaders(scope=message)
headers.setdefault("X-Content-Type-Options", "nosniff")
headers.setdefault("X-Frame-Options", "DENY")
headers.setdefault("X-Frame-Options", self.xfo)
headers.setdefault("Referrer-Policy", "same-origin")
headers.setdefault("Cross-Origin-Opener-Policy", "same-origin")
if console:
headers.setdefault("Cache-Control", "no-cache")
headers.setdefault("Content-Security-Policy", CONSOLE_CSP)
headers.setdefault("Content-Security-Policy", self.csp)
await send(message)
await self.app(scope, receive, _send)
+1 -1
View File
@@ -185,7 +185,7 @@ def healthz() -> dict:
app.add_middleware(GZipMiddleware, minimum_size=1000)
# The security headers (app/edge.py). Added LAST, so it is the outermost middleware and also stamps
# the responses every other layer produces — 404, 405, 413 and the 500 problem response included.
app.add_middleware(SecurityHeaders)
app.add_middleware(SecurityHeaders, frame_ancestors=settings.frame_ancestors)
# The static console — this backend serves it itself; there is no reverse proxy. Mounted at "/"
# LAST so every API route wins, behind ConsoleUnlessApi so /api/* and /healthz never fall through
+1 -1
View File
@@ -147,7 +147,7 @@ if ENV_PATH.exists() and "DREDD_CORE_TOKEN" in ENV_PATH.read_text(encoding="utf-
# ── the backend's own edge is wired as documented ─────────────────────────────
edge_py = read("backend/app/edge.py")
check(bool(re.search(r'API_PREFIX = "([^"]+)"', main_py)), "cannot find API_PREFIX in main.py")
check("app.add_middleware(SecurityHeaders)" in main_py,
check("app.add_middleware(SecurityHeaders" in main_py,
"main.py does not add the edge's SecurityHeaders middleware",
"SecurityHeaders stamps every response")
check("ConsoleUnlessApi(SpaStaticFiles(" in main_py,
+41
View File
@@ -6,11 +6,13 @@ same order as main.py.
"""
from __future__ import annotations
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.edge import (
CONSOLE_CSP,
content_security_policy,
BodySizeLimit,
ConsoleUnlessApi,
SecurityHeaders,
@@ -72,3 +74,42 @@ def test_the_console_never_answers_for_the_api(tmp_path):
def test_an_oversized_body_is_refused(tmp_path):
r = _client(tmp_path).post("/api/v1/things", content=b"x" * 2048)
assert r.status_code == 413
def _framed(tmp_path, value: str):
from app.config import Settings
(tmp_path / "index.html").write_text("<!doctype html>", encoding="utf-8")
app = FastAPI()
app.add_middleware(SecurityHeaders, frame_ancestors=Settings(
_env_file=None, frame_ancestors=value).frame_ancestors)
app.mount("/", ConsoleUnlessApi(SpaStaticFiles(directory=str(tmp_path), html=True),
app.routes), name="console")
return TestClient(app).get("/").headers
def test_frame_ancestors_default_is_none_and_deny(tmp_path, monkeypatch):
from app.config import Settings
monkeypatch.delenv("FRAME_ANCESTORS", raising=False)
assert Settings(_env_file=None).frame_ancestors == "'none'"
h = _framed(tmp_path, "'none'")
assert h["x-frame-options"] == "DENY"
assert h["content-security-policy"] == CONSOLE_CSP
assert "frame-ancestors 'none';" in CONSOLE_CSP
@pytest.mark.parametrize("value", ["'self'", "self", " 'self' "])
def test_frame_ancestors_self_is_sameorigin(tmp_path, value):
h = _framed(tmp_path, value)
assert h["x-frame-options"] == "SAMEORIGIN"
assert h["content-security-policy"] == content_security_policy("'self'")
assert "frame-ancestors 'self';" in h["content-security-policy"]
@pytest.mark.parametrize("value", ["", "*", "https://evil.example", "'self' https://x.example",
"'unsafe-inline'"])
def test_frame_ancestors_anything_else_refuses_startup(value):
from pydantic import ValidationError
from app.config import Settings
with pytest.raises(ValidationError, match="FRAME_ANCESTORS must be 'none' or 'self'"):
Settings(_env_file=None, frame_ancestors=value)
+9 -6
View File
@@ -90,12 +90,14 @@ avoids.
```bash
python -m dredd_core.managed provision --sql-only --schema insider --app-role insider_app \
--migrator-role insider_migrator --output db/managed/provision.sql
--migrator-role insider_migrator --identity-schema dredd --identity-owner atrium_migrator \
--output db/managed/provision.sql
```
The committed file is the **standalone** rendering, which is what a generated app needs on day one.
Joining a platform adds two flags to that command, and therefore changes the file — which is exactly
why CI compares it. See section 6.
The committed file is the **one-account (platform)** rendering, exactly as Galena, Sygna and Counsel
ship theirs: Insider is a module of Atrium, and the platform's `deploy/push.sh` compares this file
with the rendering it provisions before it touches a database. A standalone install drops the two
identity flags from both commands (see section 6).
## 2. Configure `.env`
@@ -282,8 +284,9 @@ price of that correct choice is that an unqualified `app_user` resolves to a **l
exists — which is why the backend asserts at startup that it does not, and why that assertion is not
optional. Never "fix" anything by putting the identity schema first.
Re-render `provision.sql` with the same two flags and commit it, or CI's `--check-file` will fail —
correctly, because the committed file would no longer describe this deployment.
The committed `provision.sql` is already rendered with these two flags, and CI's `--check-file` step
carries them too, so a stale file fails CI — and the platform's `push.sh`, which compares it with the
same rendering.
### 6.2 The hub migrates
+46 -15
View File
@@ -1,16 +1,16 @@
-- =================================================================================================
-- Managed Postgres provisioning for one app of the family, in the shared database:
-- schema insider, migrator insider_migrator, app insider_app, extensions: none, migrator statement_timeout 30min
-- search_path insider, extensions; no shared identity schema (this app owns its own accounts)
-- search_path insider, dredd, extensions; shared identity schema dredd, owned by atrium_migrator (created by its owner, USAGE only here)
--
-- Rendered by dredd-core. Do not edit: re-render, and let CI check it is current (exit 1 = stale):
-- python -m dredd_core.managed provision --sql-only \
-- --schema insider --app-role insider_app --migrator-role insider_migrator \
-- --schema insider --app-role insider_app --migrator-role insider_migrator --identity-schema dredd --identity-owner atrium_migrator \
-- --output db/managed/provision.sql (CI: --check-file db/managed/provision.sql)
--
-- Preferred path, from a shell (passwords come from environment variables and are never printed):
-- python -m dredd_core.managed provision --admin-url ADMIN_DATABASE_URL \
-- --schema insider --app-role insider_app --migrator-role insider_migrator \
-- --schema insider --app-role insider_app --migrator-role insider_migrator --identity-schema dredd --identity-owner atrium_migrator \
-- --migrator-password-env INSIDER_MIGRATOR_PASSWORD --app-password-env INSIDER_APP_PASSWORD
--
-- SQL editor path (no shell): paste this whole file into the provider's SQL editor, replace both
@@ -30,8 +30,8 @@ DECLARE
app_role text := 'insider_app';
admin_roles text[] := ARRAY['postgres', 'postgres_managed']::text[];
extension_names text[] := '{}'::text[];
identity_schema text := '';
identity_owner text := '';
identity_schema text := 'dredd';
identity_owner text := 'atrium_migrator';
owns_identity boolean := false;
seen text;
r text;
@@ -200,19 +200,50 @@ BEGIN
END
$dredd_provision_extensions_usage$;
-- 9. search_path of insider_migrator
ALTER ROLE insider_migrator SET search_path = insider, extensions;
-- 9. temporary membership in the identity owner atrium_migrator: needed to grant on dredd
GRANT atrium_migrator TO CURRENT_USER;
-- 10. search_path of insider_app
ALTER ROLE insider_app SET search_path = insider, extensions;
-- 10. schema dredd: USAGE for insider_migrator and insider_app
GRANT USAGE ON SCHEMA dredd TO insider_migrator, insider_app;
-- 11. statement_timeout of insider_migrator
-- 11. schema dredd: check that the USAGE grant took
DO $dredd_provision_identity_usage$
DECLARE
identity_schema text := 'dredd';
migrator_role text := 'insider_migrator';
app_role text := 'insider_app';
identity_owner text := 'atrium_migrator';
BEGIN
IF NOT (has_schema_privilege(migrator_role, identity_schema, 'USAGE')
AND has_schema_privilege(app_role, identity_schema, 'USAGE')) THEN
RAISE EXCEPTION USING
MESSAGE = 'provision: could not grant USAGE on the shared identity schema '
|| quote_ident(identity_schema) || ' to ' || quote_ident(migrator_role) || ' and '
|| quote_ident(app_role),
HINT = 'The connected role holds no grant option there (PostgreSQL then only warns "no '
|| 'privileges were granted"), because the schema belongs to ' || quote_ident(identity_owner)
|| '. The temporary membership in that role is what carries the grant option: check '
|| '--identity-owner names the role that really owns the schema.';
END IF;
END
$dredd_provision_identity_usage$;
-- 12. search_path of insider_migrator
ALTER ROLE insider_migrator SET search_path = insider, dredd, extensions;
-- 13. search_path of insider_app
ALTER ROLE insider_app SET search_path = insider, dredd, extensions;
-- 14. statement_timeout of insider_migrator
ALTER ROLE insider_migrator SET statement_timeout = '30min';
-- 12. end the temporary membership: no standing SET ROLE insider_migrator for the admin
-- 15. end the temporary membership: no standing SET ROLE insider_migrator for the admin
REVOKE insider_migrator FROM CURRENT_USER;
-- 13. verify the end state
-- 16. end the temporary membership in atrium_migrator
REVOKE atrium_migrator FROM CURRENT_USER;
-- 17. verify the end state
DO $dredd_provision_verify$
DECLARE
target_schema text := 'insider';
@@ -220,9 +251,9 @@ DECLARE
app_role text := 'insider_app';
extension_names text[] := '{}'::text[];
timeout_setting text := 'statement_timeout=30min';
path_setting text := 'search_path=insider, extensions';
identity_schema text := '';
identity_owner text := '';
path_setting text := 'search_path=insider, dredd, extensions';
identity_schema text := 'dredd';
identity_owner text := 'atrium_migrator';
admin_roles text[] := ARRAY['postgres', 'postgres_managed']::text[];
admin_is_super boolean := (SELECT rolsuper FROM pg_roles WHERE rolname = current_user);
problems text[] := '{}'::text[];