Files
adminandClaude Opus 5 e1987569ce One account, one admin pane: the hub owns identity
Atrium becomes the platform's identity: it creates app_user, session and
module_moderator in a neutral shared schema and is the only writer of
them. Sign in here and every module resolves the same session -- one
origin, one cookie, nothing handed between apps.

Revision 0004 creates those tables, applies each role its tier, and moves
Atrium's own accounts into them. Nothing is renumbered here: the
surviving row keeps its UUID, so all fourteen columns in this schema that
name a person -- audit actors, node owners, permission grants, module
assignments -- keep the values they have, and only the constraint moves.
The modules do the opposite in their own revisions, matching on
lower(email) and repointing every reference, which is why theirs are the
risky ones and this one is not.

The administration this hub was always supposed to have:

- An administrator resets a forgotten password. The platform had lost
  that: Galena could do it, the hub could not, and POST /me/password
  needs the current one -- so a forgotten password locked someone out of
  all four modules permanently. The reset revokes every session and app
  token in every module, clears the lockout the forgetting caused, and is
  audited under its own action.
- An administrator corrects a name or an email, with a case-insensitive
  clash check, because the unique index is on lower(email).
- Administrators and moderators are granted and revoked here, per module.
- A last-administrator guard on deactivate and on the administrator
  toggle. There was none, so the platform could be locked out in two
  clicks.
- An app-token screen. Minting moved to the hub, and no console had one,
  so after the cutover the only way to get a token was curl.

Revision 0005 renames the catalogue slug counsel-scorecard to counsel and
carries any moderator rows with it. The catalogue and the module
disagreed, so granting someone Counsel moderator wrote a row, changed
nothing, and reported no error -- and no Counsel app token could be
minted at all. A slug is an address, not a label.

deploy/
- push.sh learns the identity flags through PLATFORM_IDENTITY_SCHEMA in
  db.env. Without this a routine deploy after the cutover rewrote each
  role's search_path and silently undid it -- the roles kept USAGE, so
  nothing failed that day. It also refuses, before connecting, when an
  app's env file names a schema that db.env does not.
- RUNBOOK-one-account.md: the cutover, walked end to end on a replica of
  the live deployment rather than reviewed. Walking it is what found the
  ordering error that made Atrium's own migration fail, the first command
  exiting on a missing driver, and a rollback that restored everything as
  postgres -- which looks like success, and breaks the next deploy days
  later with permission denied on a schema the migrator used to own.

Requires dredd-core v0.10.0.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-26 12:55:09 +02:00

356 lines
18 KiB
PL/PgSQL

-- =================================================================================================
-- Managed Postgres provisioning for one app of the family, in the shared database:
-- schema atrium, migrator atrium_migrator, app atrium_app, extensions: none, migrator statement_timeout 30min
-- search_path atrium, dredd, extensions; shared identity schema dredd, owned by atrium_migrator (created 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 atrium --app-role atrium_app --migrator-role atrium_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 atrium --app-role atrium_app --migrator-role atrium_migrator --identity-schema dredd --identity-owner atrium_migrator \
-- --migrator-password-env ATRIUM_MIGRATOR_PASSWORD --app-password-env ATRIUM_APP_PASSWORD
--
-- SQL editor path (no shell): paste this whole file into the provider's SQL editor, replace both
-- change_me passwords in step 2 there (never in the committed file; at least 16 printable ASCII
-- characters, different per role), and run it once as the platform admin (postgres). Re-running is
-- safe: an existing role keeps its password unless reset_passwords is set to true (do that after a
-- restore, which may drop custom role passwords). It never touches schema public and never drops
-- anything.
-- =================================================================================================
BEGIN;
-- 1. preflight: refuse a connection, schema, role or extension this must not touch
DO $dredd_provision_preflight$
DECLARE
target_schema text := 'atrium';
migrator_role text := 'atrium_migrator';
app_role text := 'atrium_app';
admin_roles text[] := ARRAY['postgres', 'postgres_managed']::text[];
extension_names text[] := '{}'::text[];
identity_schema text := 'dredd';
identity_owner text := 'atrium_migrator';
owns_identity boolean := true;
seen text;
r text;
e text;
BEGIN
IF current_user::text IN (migrator_role, app_role) THEN
RAISE EXCEPTION USING
MESSAGE = 'provision: connected as ' || quote_ident(current_user::text)
|| ', one of the roles being provisioned',
HINT = 'Run it as the platform admin: postgres on a managed provider (postgres_managed in the local emulation).';
END IF;
IF (SELECT rolsuper FROM pg_roles WHERE rolname = current_user) THEN
RAISE WARNING USING
MESSAGE = 'provision: connected as the superuser ' || quote_ident(current_user::text),
HINT = 'Fine on a local cluster or in CI; on a managed provider run it as postgres, which is not a superuser there.';
ELSIF NOT (current_user::text = ANY (admin_roles)) THEN
RAISE EXCEPTION USING
MESSAGE = 'provision: connected as ' || quote_ident(current_user::text)
|| ', which is neither the platform admin (' || array_to_string(admin_roles, ', ')
|| ') nor a superuser',
HINT = 'Run it as postgres on a managed provider (postgres_managed in the local emulation).';
ELSIF NOT (SELECT rolcreaterole FROM pg_roles WHERE rolname = current_user)
AND EXISTS (SELECT 1 FROM unnest(ARRAY[migrator_role, app_role]) AS n
WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = n)) THEN
RAISE EXCEPTION USING
MESSAGE = 'provision: ' || quote_ident(current_user::text) || ' has no CREATEROLE, and a role is missing',
HINT = 'Run it as the platform admin, which can create roles.';
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = 'extensions') THEN
RAISE EXCEPTION USING
MESSAGE = 'provision: schema extensions does not exist',
HINT = 'A managed provider has it. On a plain PostgreSQL test cluster run '
|| 'python -m dredd_core.managed emulate (TEST-ONLY) first.';
END IF;
SELECT pg_get_userbyid(nspowner)::text INTO seen FROM pg_namespace WHERE nspname = target_schema;
IF seen IS NOT NULL AND seen <> migrator_role THEN
RAISE EXCEPTION USING
MESSAGE = 'provision: schema ' || quote_ident(target_schema) || ' already exists and is owned by '
|| quote_ident(seen) || ', not ' || quote_ident(migrator_role),
HINT = 'Another app, or an earlier setup, uses that schema; provisioning never takes a schema over. '
|| 'Check the schema and role names.';
END IF;
IF identity_schema <> '' THEN
SELECT pg_get_userbyid(nspowner)::text INTO seen FROM pg_namespace WHERE nspname = identity_schema;
IF seen IS NOT NULL AND seen <> identity_owner THEN
RAISE EXCEPTION USING
MESSAGE = 'provision: the shared identity schema ' || quote_ident(identity_schema)
|| ' already exists and is owned by ' || quote_ident(seen) || ', not '
|| quote_ident(identity_owner),
HINT = 'Another deployment, or an earlier setup, uses that name; provisioning never takes a '
|| 'schema over. Check --identity-schema and --identity-owner.';
END IF;
IF seen IS NULL AND NOT owns_identity THEN
RAISE EXCEPTION USING
MESSAGE = 'provision: the shared identity schema ' || quote_ident(identity_schema)
|| ' does not exist, and this app does not own it',
HINT = 'Provision the app whose migrator is ' || quote_ident(identity_owner) || ' first: its '
|| 'run creates the schema, and this one only asks for USAGE on it. (Ordering the other '
|| 'way round is what a compose depends_on is for.)';
END IF;
END IF;
FOREACH r IN ARRAY ARRAY[migrator_role, app_role] LOOP
IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = r
AND (rolsuper OR rolcreaterole OR rolcreatedb OR rolreplication OR rolbypassrls
OR NOT rolcanlogin)) THEN
RAISE EXCEPTION USING
MESSAGE = 'provision: role ' || quote_ident(r) || ' already exists and is not a plain LOGIN role',
HINT = 'An app role is LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS: '
|| 'fix it with ALTER ROLE, or check the role names.';
END IF;
END LOOP;
FOREACH e IN ARRAY extension_names LOOP
SELECT n.nspname::text INTO seen
FROM pg_extension x JOIN pg_namespace n ON n.oid = x.extnamespace WHERE x.extname = e;
IF seen IS NOT NULL AND seen <> 'extensions' THEN
RAISE EXCEPTION USING
MESSAGE = 'provision: extension ' || quote_ident(e) || ' is installed in schema ' || quote_ident(seen)
|| ', not extensions',
HINT = 'The app roles'' search_path is their schema and extensions, so its functions and operator '
|| 'classes would not resolve. Move it (ALTER EXTENSION ... SET SCHEMA extensions) once '
|| 'nothing depends on where it is.';
END IF;
END LOOP;
END
$dredd_provision_preflight$;
-- 2. roles: create atrium_migrator and atrium_app (plain LOGIN roles) where missing
DO $dredd_provision_roles$
DECLARE
migrator_role text := 'atrium_migrator';
app_role text := 'atrium_app';
migrator_password text := 'change_me'; -- replace change_me here (in the SQL editor, never in the committed file)
app_password text := 'change_me'; -- replace change_me here (in the SQL editor, never in the committed file)
reset_passwords boolean := false; -- true: also set the password of a role that already exists
placeholders text[] := ARRAY['change_me', 'changeme', 'change-me', 'replace_me', 'replaceme', 'placeholder', 'password', 'your_password', 'yourpassword']::text[];
names text[];
passwords text[];
pw text;
i int;
BEGIN
names := ARRAY[migrator_role, app_role];
passwords := ARRAY[migrator_password, app_password];
FOR i IN 1..2 LOOP
CONTINUE WHEN EXISTS (SELECT 1 FROM pg_roles WHERE rolname = names[i]) AND NOT reset_passwords;
pw := passwords[i];
IF pw IS NULL
OR (NOT starts_with(pw, 'SCRAM-SHA-256$')
AND (pw !~ '^[!-~]([ -~]*[!-~])?$'
OR length(pw) < 16
OR (SELECT count(DISTINCT c) FROM regexp_split_to_table(pw, '') AS c) < 6
OR EXISTS (SELECT 1 FROM unnest(placeholders) AS w WHERE strpos(lower(pw), w) > 0)
OR lower(pw) IN (migrator_role, app_role))) THEN
RAISE EXCEPTION USING
MESSAGE = 'provision: the password for ' || quote_ident(names[i]) || ' is empty or a placeholder',
HINT = 'Use at least 16 printable ASCII characters, not change_me, and a different one per role.';
END IF;
IF passwords[3 - i] IS NOT NULL AND pw = passwords[3 - i] THEN
RAISE EXCEPTION USING
MESSAGE = 'provision: the passwords for ' || quote_ident(migrator_role) || ' and '
|| quote_ident(app_role) || ' are identical',
HINT = 'Each role needs its own password.';
END IF;
END LOOP;
FOR i IN 1..2 LOOP
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = names[i]) THEN
EXECUTE 'CREATE ROLE ' || quote_ident(names[i])
|| ' LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS INHERIT PASSWORD '
|| quote_literal(passwords[i]);
ELSIF reset_passwords THEN
EXECUTE 'ALTER ROLE ' || quote_ident(names[i]) || ' PASSWORD ' || quote_literal(passwords[i]);
END IF;
END LOOP;
END
$dredd_provision_roles$;
-- 3. temporary membership: PostgreSQL 16+ needs SET on atrium_migrator to hand it a schema
GRANT atrium_migrator TO CURRENT_USER;
-- 4. schema atrium, owned by atrium_migrator
CREATE SCHEMA IF NOT EXISTS atrium AUTHORIZATION atrium_migrator;
-- 5. schema atrium: nothing for PUBLIC
REVOKE ALL ON SCHEMA atrium FROM PUBLIC;
-- 6. schema atrium: USAGE for atrium_app
GRANT USAGE ON SCHEMA atrium TO atrium_app;
-- 7. schema extensions: USAGE for atrium_migrator and atrium_app
GRANT USAGE ON SCHEMA extensions TO atrium_migrator, atrium_app;
-- 8. schema extensions: check that the USAGE grant took
DO $dredd_provision_extensions_usage$
DECLARE
migrator_role text := 'atrium_migrator';
app_role text := 'atrium_app';
BEGIN
IF NOT (has_schema_privilege(migrator_role, 'extensions', 'USAGE')
AND has_schema_privilege(app_role, 'extensions', 'USAGE')) THEN
RAISE EXCEPTION USING
MESSAGE = 'provision: could not grant USAGE on schema extensions to ' || quote_ident(migrator_role)
|| ' and ' || quote_ident(app_role),
HINT = 'The connected role holds no grant option on schema extensions (PostgreSQL then only warns '
|| '"no privileges were granted"). The apps need it for pg_trgm operator classes and extension '
|| 'functions: have the platform owner GRANT USAGE ON SCHEMA extensions TO both roles.';
END IF;
END
$dredd_provision_extensions_usage$;
-- 9. shared identity schema dredd, owned by atrium_migrator
CREATE SCHEMA IF NOT EXISTS dredd AUTHORIZATION atrium_migrator;
-- 10. schema dredd: nothing for PUBLIC
REVOKE ALL ON SCHEMA dredd FROM PUBLIC;
-- 11. schema dredd: USAGE for atrium_migrator and atrium_app
GRANT USAGE ON SCHEMA dredd TO atrium_migrator, atrium_app;
-- 12. schema dredd: check that the USAGE grant took
DO $dredd_provision_identity_usage$
DECLARE
identity_schema text := 'dredd';
migrator_role text := 'atrium_migrator';
app_role text := 'atrium_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$;
-- 13. search_path of atrium_migrator
ALTER ROLE atrium_migrator SET search_path = atrium, dredd, extensions;
-- 14. search_path of atrium_app
ALTER ROLE atrium_app SET search_path = atrium, dredd, extensions;
-- 15. statement_timeout of atrium_migrator
ALTER ROLE atrium_migrator SET statement_timeout = '30min';
-- 16. end the temporary membership: no standing SET ROLE atrium_migrator for the admin
REVOKE atrium_migrator FROM CURRENT_USER;
-- 17. verify the end state
DO $dredd_provision_verify$
DECLARE
target_schema text := 'atrium';
migrator_role text := 'atrium_migrator';
app_role text := 'atrium_app';
extension_names text[] := '{}'::text[];
timeout_setting text := 'statement_timeout=30min';
path_setting text := 'search_path=atrium, 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[];
held boolean;
seen text;
r text;
e text;
BEGIN
FOREACH r IN ARRAY ARRAY[migrator_role, app_role] LOOP
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = r AND rolcanlogin
AND NOT (rolsuper OR rolcreaterole OR rolcreatedb OR rolreplication OR rolbypassrls)) THEN
problems := problems || ('role ' || quote_ident(r) || ' is missing or not a plain LOGIN role');
CONTINUE;
END IF;
IF NOT has_schema_privilege(r, 'extensions', 'USAGE') THEN
problems := problems || (quote_ident(r) || ' has no USAGE on schema extensions');
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_db_role_setting s
WHERE s.setrole = (SELECT oid FROM pg_roles WHERE rolname = r) AND s.setdatabase = 0
AND path_setting = ANY (s.setconfig)) THEN
problems := problems || (quote_ident(r) || ' does not have ' || path_setting);
END IF;
IF NOT admin_is_super THEN
IF current_setting('server_version_num')::int >= 160000 THEN
held := pg_has_role(r::name, 'SET') OR pg_has_role(r::name, 'USAGE');
ELSE
held := pg_has_role(r::name, 'MEMBER');
END IF;
IF held THEN
problems := problems || (quote_ident(current_user::text) || ' can still SET ROLE or use the privileges of '
|| quote_ident(r) || ' (a membership granted by another role?)');
END IF;
END IF;
END LOOP;
IF (SELECT pg_get_userbyid(nspowner)::text FROM pg_namespace WHERE nspname = target_schema)
IS DISTINCT FROM migrator_role THEN
problems := problems || ('schema ' || quote_ident(target_schema) || ' is missing or not owned by '
|| quote_ident(migrator_role));
ELSE
IF has_schema_privilege('public', target_schema, 'USAGE') OR has_schema_privilege('public', target_schema, 'CREATE') THEN
problems := problems || ('PUBLIC still holds a privilege on schema ' || quote_ident(target_schema));
END IF;
IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = app_role) THEN
IF NOT has_schema_privilege(app_role, target_schema, 'USAGE') THEN
problems := problems || (quote_ident(app_role) || ' has no USAGE on schema ' || quote_ident(target_schema));
END IF;
IF has_schema_privilege(app_role, target_schema, 'CREATE') THEN
problems := problems || (quote_ident(app_role) || ' can CREATE in schema ' || quote_ident(target_schema));
END IF;
END IF;
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_db_role_setting s
WHERE s.setrole = (SELECT oid FROM pg_roles WHERE rolname = migrator_role) AND s.setdatabase = 0
AND timeout_setting = ANY (s.setconfig)) THEN
problems := problems || (quote_ident(migrator_role) || ' does not have ' || timeout_setting);
END IF;
IF identity_schema <> '' THEN
SELECT pg_get_userbyid(nspowner)::text INTO seen FROM pg_namespace WHERE nspname = identity_schema;
IF seen IS DISTINCT FROM identity_owner THEN
problems := problems || ('the shared identity schema ' || quote_ident(identity_schema)
|| ' is missing or not owned by ' || quote_ident(identity_owner));
ELSE
IF (SELECT rolsuper FROM pg_roles WHERE rolname = identity_owner)
OR identity_owner = ANY (admin_roles) THEN
problems := problems || ('the identity owner ' || quote_ident(identity_owner)
|| ' is a superuser or the platform admin role');
END IF;
IF has_schema_privilege('public', identity_schema, 'USAGE')
OR has_schema_privilege('public', identity_schema, 'CREATE') THEN
problems := problems || ('PUBLIC still holds a privilege on schema ' || quote_ident(identity_schema));
END IF;
FOREACH r IN ARRAY ARRAY[migrator_role, app_role] LOOP
CONTINUE WHEN NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = r);
IF NOT has_schema_privilege(r, identity_schema, 'USAGE') THEN
problems := problems || (quote_ident(r) || ' has no USAGE on schema ' || quote_ident(identity_schema));
END IF;
-- Only the owner creates in the shared schema: its tables are the owning app's migration,
-- and a second app creating one there is how two apps end up with two account tables.
IF r <> identity_owner AND has_schema_privilege(r, identity_schema, 'CREATE') THEN
problems := problems || (quote_ident(r) || ' can CREATE in schema ' || quote_ident(identity_schema));
END IF;
END LOOP;
END IF;
END IF;
FOREACH e IN ARRAY extension_names LOOP
IF NOT EXISTS (SELECT 1 FROM pg_extension x JOIN pg_namespace n ON n.oid = x.extnamespace
WHERE x.extname = e AND n.nspname = 'extensions') THEN
problems := problems || ('extension ' || quote_ident(e) || ' is not installed in schema extensions');
END IF;
END LOOP;
IF cardinality(problems) > 0 THEN
RAISE EXCEPTION USING
MESSAGE = 'provision: the end state does not hold: ' || array_to_string(problems, '; '),
HINT = 'Nothing was committed. Fix the cause and run the provisioning again.';
END IF;
END
$dredd_provision_verify$;
COMMIT;