@davoodmehraban89 / LifeMate / commits / 23ac69b
Fork 0

LifeMate — Personal, Family & Learning Companion

fix(ops): separate database roles and validate explicit adoption

Codex committed Oct 9, 2026 at 06:23 UTC 23ac69bdfbaf5a76ee0175413d9c74214fcc1484
13 files changed +658 -78
.env.example
+8
@@ -3,6 +3,14 @@ COMPOSE_PROJECT_NAME=lifeguide-stage0
3 POSTGRES_DB=lifemate
4 POSTGRES_USER=lifeguide
5 POSTGRES_PASSWORD=CHANGE_ME_TO_A_RANDOM_SECRET
6 +# Bootstrap credentials above are only for postgres and short-lived ops jobs.
7 +# Do not reuse them in API/migrations/backups. Names are protocol identifiers.
8 +API_DB_USER=lifeguide_api
9 +API_DB_PASSWORD=CHANGE_ME_TO_A_DIFFERENT_RANDOM_SECRET
10 +MIGRATOR_DB_USER=lifeguide_migrator
11 +MIGRATOR_DB_PASSWORD=CHANGE_ME_TO_A_THIRD_RANDOM_SECRET
12 +BACKUP_DB_USER=lifeguide_backup
13 +BACKUP_DB_PASSWORD=CHANGE_ME_TO_A_FOURTH_RANDOM_SECRET
14 JWT_SECRET=CHANGE_ME_TO_AT_LEAST_32_RANDOM_CHARACTERS
15 PUBLIC_APP_URL=https://192.168.1.10
16 CORS_ORIGINS=https://192.168.1.10
backend/package-lock.json
+2 -2
@@ -1,12 +1,12 @@
1 {
2 "name": "lifemate-backend",
3 - "version": "0.5.0",
3 + "version": "0.5.1",
4 "lockfileVersion": 3,
5 "requires": true,
6 "packages": {
7 "": {
8 "name": "lifemate-backend",
9 - "version": "0.5.0",
9 + "version": "0.5.1",
10 "dependencies": {
11 "argon2": "^0.44.0",
12 "cors": "^2.8.5",
backend/package.json
+1 -1
@@ -1,7 +1,7 @@
1 {
2 "name": "lifemate-backend",
3 "private": true,
4 - "version": "0.5.0",
4 + "version": "0.5.1",
5 "type": "module",
6 "scripts": {
7 "start": "node src/entrypoint.js",
backend/scripts/db-role-policy.js new
+210
@@ -0,0 +1,210 @@
1 +// Operations-only policy. Keep application object names stable; these are not
2 +// product labels. No REASSIGN OWNED, catalog writes or broad ownership transfer.
3 +import crypto from 'node:crypto';
4 +import fs from 'node:fs/promises';
5 +
6 +export const applicationTables = [
7 + 'academic_term', 'academic_year', 'access_audit', 'activity_state_event',
8 + 'ai_guide_message', 'ai_guide_session', 'ai_plan_proposal', 'app_user',
9 + 'auth_credential', 'auth_delivery_attempt', 'auth_phone_challenge', 'auth_session',
10 + 'auth_token', 'class_session', 'curriculum_subject', 'education_profile',
11 + 'family_invitation', 'family_membership', 'family_workspace', 'guardian_relationship',
12 + 'iran_calendar_event', 'learning_checkin', 'learning_goal', 'life_context',
13 + 'menstrual_cycle_entry', 'notification_outbox', 'notification_preference',
14 + 'plan_item', 'profile', 'reminder', 'schema_migration', 'sharing_grant',
15 + 'study_interval', 'study_mutation', 'study_session', 'subject', 'sync_mutation',
16 + 'textbook_catalog', 'wellbeing_checkin', 'wellbeing_safety_event',
17 +];
18 +export const applicationTypes = ['member_role', 'invitation_status', 'visibility_scope',
19 + 'auth_token_kind', 'life_context_kind', 'plan_item_kind', 'plan_item_status',
20 + 'plan_priority', 'sharing_scope', 'reminder_status'];
21 +export const applicationSequences = ['access_audit_id_seq', 'notification_outbox_id_seq',
22 + 'study_interval_id_seq', 'activity_state_event_id_seq'];
23 +export const applicationFunctions = [
24 + 'is_active_family_member(uuid, uuid)', 'is_family_admin(uuid, uuid)',
25 + 'is_active_guardian(uuid, uuid, uuid)', 'can_view_student_academic(uuid, uuid)',
26 + 'can_view_plan_item(uuid, uuid)', 'recompute_reminder_schedule(uuid)',
27 + 'plan_item_revision()', 'revoke_changed_plan_item_grants()',
28 + 'revoke_ended_membership_grants()', 'plan_item_legacy_activity()',
29 +];
30 +export const roleNames = Object.freeze({ api: 'lifeguide_api', migrator: 'lifeguide_migrator', backup: 'lifeguide_backup' });
31 +const ident = (value) => `"${String(value).replaceAll('"', '""')}"`;
32 +export function validateRoles(env) {
33 + const configured = { api: env.API_DB_USER ?? roleNames.api, migrator: env.MIGRATOR_DB_USER ?? roleNames.migrator, backup: env.BACKUP_DB_USER ?? roleNames.backup };
34 + for (const kind of Object.keys(roleNames)) {
35 + if (configured[kind] !== roleNames[kind]) throw new Error('Use the three canonical, distinct application role names');
36 + }
37 + return configured;
38 +}
39 +
40 +async function grantUuidDefault(client,roles) {
41 + // Existing table DEFAULT expressions bind to pgcrypto's public UUID function,
42 + // even when the runtime search_path prefers the equivalent pg_catalog one.
43 + // Allow only this value-generating extension function, never backup execution.
44 + const uuid = await client.query(`SELECT 1 FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace
45 + JOIN pg_depend d ON d.classid='pg_proc'::regclass AND d.objid=p.oid AND d.deptype='e'
46 + JOIN pg_extension e ON e.oid=d.refobjid
47 + WHERE n.nspname='public' AND p.proname='gen_random_uuid' AND p.pronargs=0 AND e.extname='pgcrypto'`);
48 + if(uuid.rowCount) await client.query(`GRANT EXECUTE ON FUNCTION public.gen_random_uuid() TO ${ident(roles.api)},${ident(roles.migrator)}`);
49 +}
50 +
51 +async function inventory(client) {
52 + const tables = await client.query(`SELECT c.relname name,c.relkind kind,pg_get_userbyid(c.relowner) owner
53 + FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace
54 + WHERE n.nspname='public' AND c.relkind IN ('r','p','S','v','m','f')
55 + AND NOT EXISTS(SELECT 1 FROM pg_depend d WHERE d.classid='pg_class'::regclass AND d.objid=c.oid AND d.deptype='e')`);
56 + const types = await client.query(`SELECT t.typname name,pg_get_userbyid(t.typowner) owner FROM pg_type t
57 + JOIN pg_namespace n ON n.oid=t.typnamespace WHERE n.nspname='public' AND t.typtype IN ('e','d')
58 + AND NOT EXISTS(SELECT 1 FROM pg_depend d WHERE d.classid='pg_type'::regclass AND d.objid=t.oid AND d.deptype='e')`);
59 + const functions = await client.query(`SELECT p.proname||'('||oidvectortypes(p.proargtypes)||')' name,
60 + pg_get_userbyid(p.proowner) owner,p.prosecdef security_definer FROM pg_proc p
61 + JOIN pg_namespace n ON n.oid=p.pronamespace WHERE n.nspname='public'
62 + AND NOT EXISTS(SELECT 1 FROM pg_depend d WHERE d.classid='pg_proc'::regclass AND d.objid=p.oid AND d.deptype='e')`);
63 + return { tables: tables.rows, types: types.rows, functions: functions.rows };
64 +}
65 +
66 +function isKnown(object, category) {
67 + if (category === 'tables') return (object.kind === 'S' ? applicationSequences : applicationTables).includes(object.name);
68 + if (category === 'types') return applicationTypes.includes(object.name);
69 + return applicationFunctions.includes(object.name);
70 +}
71 +
72 +export async function prepareRoles(client, { env = process.env, adoptOwner, backupFile } = {}) {
73 + const roles = validateRoles(env);
74 + const passwords = { api: env.API_DB_PASSWORD, migrator: env.MIGRATOR_DB_PASSWORD, backup: env.BACKUP_DB_PASSWORD };
75 + const values = Object.values(passwords);
76 + if (values.some((v) => typeof v !== 'string' || v.length < 32 || v.startsWith('CHANGE_ME')) || new Set(values).size !== 3 || values.includes(env.PGPASSWORD)) {
77 + throw new Error('Three independent non-placeholder role passwords of at least32 characters are required');
78 + }
79 + let backupDigest;
80 + let backupManifest;
81 + if (adoptOwner) {
82 + if (!/^[a-z_][a-z0-9_]{0,62}$/.test(adoptOwner) || Object.values(roles).includes(adoptOwner)) throw new Error('Invalid expected previous owner');
83 + if (!backupFile) throw new Error('Existing ownership adoption requires an explicit verified backup file');
84 + const content = await fs.readFile(backupFile);
85 + if (content.length < 6 || content.subarray(0,5).toString() !== 'PGDMP') throw new Error('Adoption backup must be a PostgreSQL custom-format archive');
86 + backupDigest = crypto.createHash('sha256').update(content).digest('hex');
87 + backupManifest=JSON.parse(await fs.readFile(`${backupFile}.validated.json`,'utf8'));
88 + if(backupManifest.format!=='LifeGuide-adoption-backup-v1' || backupManifest.sha256!==backupDigest || backupManifest.pgRestoreList!==true ||
89 + !Number.isFinite(Date.parse(backupManifest.validatedAt)) || Date.now()-Date.parse(backupManifest.validatedAt)>15*60*1000 || Date.parse(backupManifest.validatedAt)>Date.now()+60000) {
90 + throw new Error('Run the local adoption helper to validate this exact backup first');
91 + }
92 + }
93 + await client.query('BEGIN');
94 + try {
95 + await client.query("SELECT pg_advisory_xact_lock(hashtextextended('lifeguide_role_provision',0))");
96 + await client.query("SET LOCAL lock_timeout='5s'");
97 + const session = (await client.query(`SELECT current_user, current_database() database,
98 + (SELECT rolsuper FROM pg_roles WHERE rolname=current_user) superuser`)).rows[0];
99 + if (!session.superuser || Object.values(roles).includes(session.current_user)) throw new Error('Provisioning requires the separate bootstrap administrator');
100 + if(backupManifest && backupManifest.database!==session.database) throw new Error('Adoption backup belongs to another database');
101 + const restricted=[roles.api,roles.backup];
102 + const databaseOwnership=await client.query(`SELECT EXISTS(SELECT 1 FROM pg_database
103 + WHERE datdba IN (SELECT oid FROM pg_roles WHERE rolname=ANY($1::text[]))) owned`,[Object.values(roles)]);
104 + if(databaseOwnership.rows[0].owned) throw new Error('Application roles must not own any database; operator must resolve unexpected ownership explicitly');
105 + const unexpectedOwnership=await client.query(`SELECT EXISTS(
106 + SELECT 1 FROM pg_namespace WHERE nspowner IN (SELECT oid FROM pg_roles WHERE rolname=ANY($1::text[]))
107 + UNION ALL SELECT 1 FROM pg_class WHERE relowner IN (SELECT oid FROM pg_roles WHERE rolname=ANY($1::text[]))
108 + UNION ALL SELECT 1 FROM pg_proc WHERE proowner IN (SELECT oid FROM pg_roles WHERE rolname=ANY($1::text[]))
109 + UNION ALL SELECT 1 FROM pg_type WHERE typowner IN (SELECT oid FROM pg_roles WHERE rolname=ANY($1::text[]))
110 + UNION ALL SELECT 1 FROM pg_extension WHERE extowner IN (SELECT oid FROM pg_roles WHERE rolname=ANY($1::text[]))) owned`,[restricted]);
111 + if(unexpectedOwnership.rows[0].owned) throw new Error('Runtime/backup ownership outside granted application data access is forbidden; operator must resolve it explicitly');
112 + const unknownSchema=await client.query(`SELECT EXISTS(SELECT 1 FROM pg_namespace
113 + WHERE nspname<>'public' AND nspname<>'information_schema' AND nspname !~ '^pg_') present`);
114 + // A dedicated app DB has only public plus PostgreSQL system schemas.
115 + // Refuse auxiliary namespaces: inherited CREATE, TRIGGER or executable
116 + // SECURITY DEFINER there could undo this policy. Never rewrite their ACLs.
117 + if(unknownSchema.rows[0].present) throw new Error('Unknown non-system schema in dedicated application DB; operator must isolate or explicitly resolve it');
118 + const objects = await inventory(client);
119 + for (const [category, list] of Object.entries(objects)) for (const object of list) {
120 + if (object.security_definer) throw new Error('Application SECURITY DEFINER is outside the approved role policy');
121 + if (object.owner !== roles.migrator && (!adoptOwner || object.owner !== adoptOwner || !isKnown(object, category))) {
122 + throw new Error('Existing ownership differs. Stop writers, verify backup, then explicitly adopt the known application owner');
123 + }
124 + }
125 + for (const [kind, name] of Object.entries(roles)) {
126 + const existing = (await client.query(`SELECT rolsuper,rolcreatedb,rolcreaterole,rolreplication,rolbypassrls,rolinherit,
127 + EXISTS(SELECT 1 FROM pg_auth_members WHERE member=pg_roles.oid) memberships
128 + FROM pg_roles WHERE rolname=$1`, [name])).rows[0];
129 + if (existing && Object.values(existing).some(Boolean)) throw new Error('Existing application role has unexpected privileges or memberships; refusing to change it');
130 + // Parameterized session settings keep password values out of SQL text and
131 + // error statements. The exception handler deliberately removes context
132 + // containing the dynamically constructed CREATE/ALTER ROLE password.
133 + await client.query("SELECT set_config('lifeguide_provision.role_name',$1,true),set_config('lifeguide_provision.role_password',$2,true)", [name,passwords[kind]]);
134 + await client.query(`DO $$ BEGIN
135 + IF NOT EXISTS(SELECT 1 FROM pg_roles WHERE rolname=current_setting('lifeguide_provision.role_name')) THEN
136 + EXECUTE format('CREATE ROLE %I LOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS',current_setting('lifeguide_provision.role_name'));
137 + END IF;
138 + EXECUTE format('ALTER ROLE %I PASSWORD %L',current_setting('lifeguide_provision.role_name'),current_setting('lifeguide_provision.role_password'));
139 + EXCEPTION WHEN OTHERS THEN RAISE EXCEPTION 'Role credential provisioning failed' USING ERRCODE='P0001'; END $$`);
140 + }
141 + const db = ident(session.database);
142 + await client.query(`REVOKE ALL ON DATABASE ${db} FROM PUBLIC`);
143 + for (const name of Object.values(roles)) await client.query(`REVOKE ALL ON DATABASE ${db} FROM ${ident(name)}`);
144 + await client.query(`GRANT CONNECT ON DATABASE ${db} TO ${Object.values(roles).map(ident).join(',')}`);
145 + // pgcrypto is a trusted PG16 extension. CREATE applies only to this DB,
146 + // never CREATEDB/CREATEROLE. Migrator owns the extension on a fresh restore.
147 + await client.query(`GRANT CREATE ON DATABASE ${db} TO ${ident(roles.migrator)}`);
148 + await client.query(`ALTER SCHEMA public OWNER TO ${ident(roles.migrator)}`);
149 + await client.query('REVOKE ALL ON SCHEMA public FROM PUBLIC');
150 + await client.query(`REVOKE ALL ON SCHEMA public FROM ${ident(roles.api)},${ident(roles.backup)}`);
151 + await client.query(`GRANT USAGE ON SCHEMA public TO ${ident(roles.api)},${ident(roles.backup)}`);
152 + for (const object of objects.tables) if (object.kind !== 'S' && object.owner !== roles.migrator) {
153 + // ALTER TABLE also transfers its identity/serial sequences. PostgreSQL
154 + // rejects independent OWNER changes on those linked sequences.
155 + await client.query(`ALTER TABLE public.${ident(object.name)} OWNER TO ${ident(roles.migrator)}`);
156 + }
157 + for(const object of objects.tables) if(object.kind==='S') {
158 + const current=(await client.query("SELECT pg_get_userbyid(relowner) owner FROM pg_class WHERE oid=$1::regclass",[`public.${object.name}`])).rows[0];
159 + if(current.owner!==roles.migrator) throw new Error('Sequence ownership did not follow its application table; refusing automatic repair');
160 + }
161 + for (const object of objects.types) if (object.owner !== roles.migrator) await client.query(`ALTER TYPE public.${ident(object.name)} OWNER TO ${ident(roles.migrator)}`);
162 + for (const object of objects.functions) if (object.owner !== roles.migrator) await client.query(`ALTER FUNCTION public.${object.name} OWNER TO ${ident(roles.migrator)}`);
163 + await client.query(`ALTER ROLE ${ident(roles.api)} IN DATABASE ${db} SET search_path=pg_catalog,public,pg_temp`);
164 + await client.query(`ALTER ROLE ${ident(roles.backup)} IN DATABASE ${db} SET search_path=pg_catalog,public,pg_temp`);
165 + await client.query(`ALTER ROLE ${ident(roles.migrator)} IN DATABASE ${db} SET search_path=public,pg_catalog,pg_temp`);
166 + // Global per-creator revocation removes PostgreSQL's default PUBLIC EXECUTE;
167 + // a per-schema REVOKE alone cannot override that global default.
168 + await client.query(`ALTER DEFAULT PRIVILEGES FOR ROLE ${ident(roles.migrator)} REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC`);
169 + await client.query(`ALTER DEFAULT PRIVILEGES FOR ROLE ${ident(roles.migrator)} IN SCHEMA public GRANT SELECT,INSERT,UPDATE,DELETE ON TABLES TO ${ident(roles.api)}`);
170 + await client.query(`ALTER DEFAULT PRIVILEGES FOR ROLE ${ident(roles.migrator)} IN SCHEMA public GRANT SELECT ON TABLES TO ${ident(roles.backup)}`);
171 + await client.query(`ALTER DEFAULT PRIVILEGES FOR ROLE ${ident(roles.migrator)} IN SCHEMA public GRANT USAGE,SELECT ON SEQUENCES TO ${ident(roles.api)}`);
172 + await client.query(`ALTER DEFAULT PRIVILEGES FOR ROLE ${ident(roles.migrator)} IN SCHEMA public GRANT SELECT ON SEQUENCES TO ${ident(roles.backup)}`);
173 + await grantUuidDefault(client,roles);
174 + await client.query('COMMIT');
175 + return { database: session.database, adopted: Boolean(adoptOwner), backupDigest };
176 + } catch (error) { await client.query('ROLLBACK'); throw error; }
177 +}
178 +
179 +export async function reconcileGrants(client, env = process.env) {
180 + const roles = validateRoles(env);
181 + await client.query('BEGIN');
182 + try {
183 + await client.query("SELECT pg_advisory_xact_lock(hashtextextended('lifeguide_role_provision',0))");
184 + const objects = await inventory(client);
185 + if (Object.values(objects).flat().some((object) => object.owner !== roles.migrator || object.security_definer)) throw new Error('Grant reconciliation refuses non-migrator application ownership');
186 + // Bootstrap runs this short-lived step so legacy pgcrypto PUBLIC grants are
187 + // revoked as well, without modifying extension ownership or member objects.
188 + await client.query('REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC');
189 + await client.query('REVOKE ALL ON ALL SEQUENCES IN SCHEMA public FROM PUBLIC');
190 + await client.query('REVOKE ALL ON ALL FUNCTIONS IN SCHEMA public FROM PUBLIC');
191 + for (const role of [roles.api,roles.backup]) {
192 + await client.query(`REVOKE ALL ON ALL TABLES IN SCHEMA public FROM ${ident(role)}`);
193 + await client.query(`REVOKE ALL ON ALL SEQUENCES IN SCHEMA public FROM ${ident(role)}`);
194 + await client.query(`REVOKE ALL ON ALL FUNCTIONS IN SCHEMA public FROM ${ident(role)}`);
195 + }
196 + for (const object of objects.tables) {
197 + const relation = `public.${ident(object.name)}`;
198 + if (object.kind === 'S') {
199 + await client.query(`GRANT USAGE,SELECT ON SEQUENCE ${relation} TO ${ident(roles.api)}`);
200 + await client.query(`GRANT SELECT ON SEQUENCE ${relation} TO ${ident(roles.backup)}`);
201 + } else {
202 + if (object.name !== 'schema_migration') await client.query(`GRANT SELECT,INSERT,UPDATE,DELETE ON TABLE ${relation} TO ${ident(roles.api)}`);
203 + await client.query(`GRANT SELECT ON TABLE ${relation} TO ${ident(roles.backup)}`);
204 + }
205 + }
206 + for (const object of objects.functions) if (applicationFunctions.includes(object.name)) await client.query(`GRANT EXECUTE ON FUNCTION public.${object.name} TO ${ident(roles.api)}`);
207 + await grantUuidDefault(client,roles);
208 + await client.query('COMMIT');
209 + } catch (error) { await client.query('ROLLBACK'); throw error; }
210 +}
backend/scripts/provision-db-roles.js new
+29
@@ -0,0 +1,29 @@
1 +// Explicit operations entrypoint; never imported or executed by the API.
2 +import pg from 'pg';
3 +import { prepareRoles,reconcileGrants } from './db-role-policy.js';
4 +
5 +const args = process.argv.slice(2);
6 +const mode = args.shift();
7 +let adoptOwner,backupFile;
8 +if (args.length) {
9 + if (mode !== '--prepare' || args[0] !== '--adopt-existing' || args[1] !== '--expected-owner' || args[3] !== '--backup-file' || args.length !== 5) {
10 + throw new Error('Usage: --prepare [--adopt-existing --expected-owner ROLE --backup-file PATH] or --grants');
11 + }
12 + adoptOwner=args[2]; backupFile=args[4];
13 +}
14 +if (!['--prepare','--grants'].includes(mode)) throw new Error('Use --prepare or --grants explicitly');
15 +const client = new pg.Client();
16 +try {
17 + await client.connect();
18 + if (mode === '--prepare') {
19 + const result = await prepareRoles(client,{adoptOwner,backupFile});
20 + console.log(`PASS database roles prepared; adoption=${result.adopted}; ${result.backupDigest ? `archive SHA256=${result.backupDigest} (decoding checked separately by operator helper)` : 'existing ownership preserved'}`);
21 + } else {
22 + await reconcileGrants(client);
23 + console.log('PASS database grants reconciled; API has no ledger/DDL rights and backup is read-only');
24 + }
25 +} catch (error) {
26 + // No SQL, connection strings or credential contents in operator logs.
27 + console.error(`Database role operation failed: ${error.code ?? 'policy'}; ${error.code ? 'inspect role/ownership metadata without secrets' : error.message}`);
28 + process.exitCode=1;
29 +} finally { await client.end(); }
backend/scripts/test-db-roles.js new
+198
@@ -0,0 +1,198 @@
1 +// Operations acceptance against freshly generated synthetic databases only.
2 +// Run separately from the maintainer suite: its API uses runtime credentials.
3 +import assert from 'node:assert/strict';
4 +import crypto from 'node:crypto';
5 +import fs from 'node:fs/promises';
6 +import path from 'node:path';
7 +import {fileURLToPath} from 'node:url';
8 +import {spawnSync} from 'node:child_process';
9 +import pg from 'pg';
10 +import {prepareRoles,reconcileGrants,roleNames} from './db-role-policy.js';
11 +
12 +const mode=process.argv[2];
13 +assert.ok(['--synthetic-only','--verify-restored','--cleanup'].includes(mode),'Use an explicit synthetic test phase');
14 +assert.equal(process.argv.length,3,'No database identifiers may be passed on the command line');
15 +assert.ok(['postgres','localhost','127.0.0.1','::1'].includes(process.env.PGHOST ?? 'localhost'),'Only the local test PostgreSQL host is allowed');
16 +assert.ok(process.env.ROLE_TEST_STATE_FILE,'Set a private local ROLE_TEST_STATE_FILE');
17 +const backend=path.dirname(path.dirname(fileURLToPath(import.meta.url)));
18 +const adminConfig={host:process.env.PGHOST ?? 'localhost',port:Number(process.env.PGPORT ?? 5432),user:process.env.PGUSER,password:process.env.PGPASSWORD,database:process.env.PGDATABASE};
19 +const admin=new pg.Client(adminConfig);
20 +const statePath=process.env.ROLE_TEST_STATE_FILE;
21 +const ident=(name)=>`"${name.replaceAll('"','""')}"`;
22 +const clientFor=(database,kind)=>new pg.Client({...adminConfig,database,user:roleNames[kind],password:process.env[`${{api:'API',migrator:'MIGRATOR',backup:'BACKUP'}[kind]}_DB_PASSWORD`]});
23 +let state;
24 +async function readState() {
25 + const value=JSON.parse(await fs.readFile(statePath,'utf8'));
26 + assert.match(value.run,/^[a-f0-9]{16}$/);
27 + assert.equal(value.source_db,`lifeguide_roles_source_${value.run}`);
28 + assert.equal(value.target_db,`lifeguide_roles_target_${value.run}`);
29 + return value;
30 +}
31 +async function taggedDatabase(database) {
32 + const result=await admin.query(`SELECT pg_get_userbyid(datdba) owner,shobj_description(oid,'pg_database') marker FROM pg_database WHERE datname=$1`,[database]);
33 + if(!result.rowCount) return false;
34 + assert.equal(result.rows[0].owner,(await admin.query('SELECT current_user')).rows[0].current_user,'Refusing another owner database');
35 + assert.equal(result.rows[0].marker,`LifeGuide synthetic role acceptance ${state.run}`,'Refusing an untagged database');
36 + return true;
37 +}
38 +async function denied(client,sql,label) {
39 + try { await client.query(sql); assert.fail(`${label} unexpectedly succeeded`); }
40 + catch(error) { assert.equal(error.code,'42501',`${label} must be denied by PostgreSQL permissions`); }
41 + console.log(`PASS denied: ${label}`);
42 +}
43 +async function checkPolicy(database) {
44 + const runtime=clientFor(database,'api'), backup=clientFor(database,'backup'), migrator=clientFor(database,'migrator');
45 + await Promise.all([runtime.connect(),backup.connect(),migrator.connect()]);
46 + try {
47 + for(const [kind,client] of [['api',runtime],['backup',backup],['migrator',migrator]]) {
48 + const row=(await client.query(`SELECT current_user,rolsuper,rolcreatedb,rolcreaterole,rolreplication,rolbypassrls,rolinherit
49 + FROM pg_roles WHERE rolname=current_user`)).rows[0];
50 + assert.equal(row.current_user,roleNames[kind]);
51 + for(const flag of ['rolsuper','rolcreatedb','rolcreaterole','rolreplication','rolbypassrls','rolinherit']) assert.equal(row[flag],false,`${kind}.${flag}`);
52 + assert.equal((await client.query("SELECT EXISTS(SELECT 1 FROM pg_auth_members m JOIN pg_roles r ON r.oid=m.member WHERE r.rolname=current_user) value")).rows[0].value,false);
53 + }
54 + const capabilities=(await runtime.query(`SELECT has_database_privilege(current_user,current_database(),'CREATE') db_create,
55 + has_database_privilege(current_user,current_database(),'TEMP') db_temp,has_schema_privilege(current_user,'public','CREATE') schema_create,
56 + pg_has_role(current_user,'lifeguide_migrator','MEMBER') migrator_member,
57 + EXISTS(SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='public' AND c.relowner=(SELECT oid FROM pg_roles WHERE rolname=current_user)) owns_objects`)).rows[0];
58 + assert.ok(Object.values(capabilities).every(value=>value===false));
59 + assert.equal((await migrator.query("SELECT pg_get_userbyid(nspowner) owner FROM pg_namespace WHERE nspname='public'")).rows[0].owner,roleNames.migrator);
60 + assert.equal((await migrator.query("SELECT count(*)::int n FROM schema_migration WHERE sha256 IS NOT NULL")).rows[0].n,12);
61 + await denied(runtime,'CREATE TABLE public.forbidden_runtime_table(id integer)','runtime CREATE TABLE');
62 + await denied(runtime,'CREATE TEMP TABLE forbidden_runtime_temp(id integer)','runtime TEMP');
63 + await denied(runtime,'ALTER TABLE public.plan_item ADD COLUMN forbidden_runtime_column integer','runtime ALTER TABLE');
64 + await denied(runtime,"ALTER ROLE lifeguide_migrator PASSWORD 'synthetic-forbidden-only'",'runtime ALTER other ROLE');
65 + await denied(runtime,'ALTER ROLE lifeguide_api SUPERUSER','runtime privilege escalation');
66 + await denied(runtime,'SET ROLE lifeguide_migrator','runtime SET ROLE migrator');
67 + await denied(runtime,"INSERT INTO public.schema_migration(filename) VALUES('forbidden-role-test')",'runtime ledger INSERT');
68 + await denied(runtime,"UPDATE public.schema_migration SET sha256='forbidden'",'runtime ledger UPDATE');
69 + await denied(runtime,'DELETE FROM public.schema_migration','runtime ledger DELETE');
70 + await denied(runtime,'SELECT * FROM public.schema_migration','runtime ledger SELECT unnecessary');
71 + await denied(runtime,'TRUNCATE public.plan_item','runtime TRUNCATE');
72 + await denied(backup,'UPDATE public.app_user SET id=id','backup UPDATE');
73 + await denied(backup,'CREATE TABLE public.forbidden_backup_table(id integer)','backup CREATE TABLE');
74 + await denied(backup,'CREATE TEMP TABLE forbidden_backup_temp(id integer)','backup TEMP');
75 + await denied(backup,'SELECT public.recompute_reminder_schedule(NULL)','backup side-effect application function');
76 + await denied(backup,"SELECT setval('public.access_audit_id_seq',999)",'backup sequence setval');
77 + assert.equal((await backup.query('SELECT count(*)::int n FROM public.schema_migration')).rows[0].n,12);
78 + console.log('PASS runtime/migrator/backup flags, ownership, memberships and backup ledger read');
79 + await migrator.query('CREATE TABLE public.future_role_probe(id integer PRIMARY KEY,value text)');
80 + try {
81 + await runtime.query("INSERT INTO public.future_role_probe VALUES(1,'synthetic-only')");
82 + assert.equal((await runtime.query('SELECT value FROM public.future_role_probe WHERE id=1')).rows[0].value,'synthetic-only');
83 + await runtime.query("UPDATE public.future_role_probe SET value='updated-synthetic' WHERE id=1");
84 + assert.equal((await backup.query('SELECT value FROM public.future_role_probe WHERE id=1')).rows[0].value,'updated-synthetic');
85 + await runtime.query('DELETE FROM public.future_role_probe WHERE id=1');
86 + await denied(runtime,'ALTER TABLE public.future_role_probe ADD COLUMN forbidden integer','future-table ownership retained by migrator');
87 + console.log('PASS future migrator-created table: default runtime CRUD/backup SELECT, DDL denied');
88 + } finally { await migrator.query('DROP TABLE public.future_role_probe'); }
89 + } finally { await Promise.all([runtime.end(),backup.end(),migrator.end()]); }
90 +}
91 +async function migrate(database) {
92 + const env={...process.env,PGDATABASE:database,PGUSER:roleNames.migrator,PGPASSWORD:process.env.MIGRATOR_DB_PASSWORD};
93 + delete env.DATABASE_URL;
94 + const result=spawnSync(process.execPath,['scripts/migrate.js'],{cwd:backend,env,stdio:'inherit'});
95 + assert.equal(result.status,0,'Non-superuser migration failed');
96 +}
97 +try {
98 + await admin.connect();
99 + if(mode==='--synthetic-only') {
100 + state={run:crypto.randomBytes(8).toString('hex')};
101 + state.source_db=`lifeguide_roles_source_${state.run}`;
102 + state.target_db=`lifeguide_roles_target_${state.run}`;
103 + state.created=[];
104 + await fs.writeFile(statePath,JSON.stringify(state),{mode:0o600,flag:'wx'});
105 + for(const database of [state.source_db,state.target_db]) {
106 + await admin.query(`CREATE DATABASE ${ident(database)}`);
107 + state.created.push(database);
108 + await fs.writeFile(statePath,JSON.stringify(state),{mode:0o600});
109 + await admin.query(`COMMENT ON DATABASE ${ident(database)} IS 'LifeGuide synthetic role acceptance ${state.run}'`);
110 + const db=new pg.Client({...adminConfig,database}); await db.connect();
111 + try {
112 + if(database===state.target_db) {
113 + await admin.query(`ALTER DATABASE ${ident(database)} OWNER TO lifeguide_api`);
114 + try {
115 + await assert.rejects(prepareRoles(db),/must not own any database/);
116 + // Also verify an API-owned OTHER database blocks source provisioning.
117 + const other=new pg.Client({...adminConfig,database:state.source_db}); await other.connect();
118 + try { await assert.rejects(prepareRoles(other),/must not own any database/); } finally { await other.end(); }
119 + assert.equal((await admin.query('SELECT pg_get_userbyid(datdba) owner FROM pg_database WHERE datname=$1',[database])).rows[0].owner,roleNames.api);
120 + } finally { await admin.query(`ALTER DATABASE ${ident(database)} OWNER TO ${ident(adminConfig.user)}`); }
121 + await admin.query(`ALTER DATABASE ${ident(database)} OWNER TO lifeguide_migrator`);
122 + try { await assert.rejects(prepareRoles(db),/must not own any database/); }
123 + finally { await admin.query(`ALTER DATABASE ${ident(database)} OWNER TO ${ident(adminConfig.user)}`); }
124 + await db.query('CREATE SCHEMA runtime_owned_probe AUTHORIZATION lifeguide_api');
125 + try { await assert.rejects(prepareRoles(db),/ownership outside granted application data access is forbidden/); }
126 + finally { await db.query('DROP SCHEMA runtime_owned_probe'); }
127 + await db.query('CREATE SCHEMA backup_object_probe');
128 + await db.query('CREATE TABLE backup_object_probe.fixture(id integer)');
129 + await db.query('ALTER TABLE backup_object_probe.fixture OWNER TO lifeguide_backup');
130 + try { await assert.rejects(prepareRoles(db),/ownership outside granted application data access is forbidden/); }
131 + finally { await db.query('DROP TABLE backup_object_probe.fixture'); await db.query('DROP SCHEMA backup_object_probe'); }
132 + await db.query('CREATE SCHEMA pgfixture_probe');
133 + try {
134 + await db.query('GRANT CREATE ON SCHEMA pgfixture_probe TO PUBLIC');
135 + await assert.rejects(prepareRoles(db),/Unknown non-system schema/);
136 + await db.query('REVOKE CREATE ON SCHEMA pgfixture_probe FROM PUBLIC');
137 + await db.query('GRANT CREATE ON SCHEMA pgfixture_probe TO lifeguide_api');
138 + await assert.rejects(prepareRoles(db),/Unknown non-system schema/);
139 + await db.query('REVOKE CREATE ON SCHEMA pgfixture_probe FROM lifeguide_api');
140 + await db.query('GRANT USAGE ON SCHEMA pgfixture_probe TO PUBLIC');
141 + await db.query("CREATE FUNCTION pgfixture_probe.privileged_probe() RETURNS integer LANGUAGE SQL SECURITY DEFINER AS 'SELECT 1'");
142 + await assert.rejects(prepareRoles(db),/Unknown non-system schema/);
143 + await db.query('DROP FUNCTION pgfixture_probe.privileged_probe()');
144 + } finally { await db.query('DROP SCHEMA pgfixture_probe'); }
145 + console.log('PASS failclosed preflight: current/other API-owned DB, migrator-owned DB, non-public API-owned schema, backup-owned relation, PUBLIC/direct schema CREATE and auxiliary SECURITY DEFINER; no automatic ownership or unrelated ACL repair');
146 + }
147 + await prepareRoles(db);
148 + } finally { await db.end(); }
149 + }
150 + await migrate(state.source_db); await migrate(state.source_db);
151 + const source=new pg.Client({...adminConfig,database:state.source_db}); await source.connect();
152 + try {
153 + await reconcileGrants(source);
154 + await source.query(await fs.readFile(new URL('./restore-smoke.sql',import.meta.url),'utf8').then(text=>text.replace(/^\\set.*$/gm,'')));
155 + const fixture=process.env.DB_ROLE_RESTORE_FIXTURE ?? fileURLToPath(new URL('../../deployment/restore-fixture.sql',import.meta.url));
156 + await source.query(await fs.readFile(fixture,'utf8').then(text=>text.replace(/^\\set.*$/gm,'')));
157 + } finally { await source.end(); }
158 + await checkPolicy(state.source_db);
159 + const url=new URL('postgresql://localhost'); url.hostname=adminConfig.host; url.port=String(adminConfig.port);
160 + url.pathname=`/${state.source_db}`; url.username=roleNames.api; url.password=process.env.API_DB_PASSWORD;
161 + const env={...process.env,DATABASE_URL:url.toString(),PGUSER:roleNames.api,PGPASSWORD:process.env.API_DB_PASSWORD,PGDATABASE:state.source_db};
162 + for(const key of ['API_DB_PASSWORD','MIGRATOR_DB_PASSWORD','BACKUP_DB_PASSWORD','POSTGRES_PASSWORD']) delete env[key];
163 + const acceptance=spawnSync(process.execPath,['--test','tests/online_acceptance.test.js'],{cwd:backend,env,stdio:'inherit'});
164 + assert.equal(acceptance.status,0,'Real family HTTP/DB acceptance with runtime role failed');
165 + console.log('PASS role acceptance source: fresh12 migrations + repeat, restrictive SQL capabilities and runtime family HTTP scenario');
166 + console.log(`Synthetic restore state saved; source=${state.source_db}; target=${state.target_db}`);
167 + } else {
168 + state=await readState();
169 + if(mode==='--verify-restored') {
170 + assert.ok(await taggedDatabase(state.target_db));
171 + const target=new pg.Client({...adminConfig,database:state.target_db}); await target.connect();
172 + try {
173 + await reconcileGrants(target);
174 + assert.equal((await target.query("SELECT count(*)::int n FROM schema_migration WHERE sha256 IS NOT NULL")).rows[0].n,12);
175 + assert.equal((await target.query("SELECT recorded_duration_seconds FROM study_session WHERE id='00000000-0000-4000-8000-000000000005'")).rows[0].recorded_duration_seconds,600);
176 + assert.equal((await target.query("SELECT pg_get_userbyid(extowner) owner FROM pg_extension WHERE extname='pgcrypto'")).rows[0].owner,roleNames.migrator);
177 + } finally { await target.end(); }
178 + await migrate(state.target_db); await checkPolicy(state.target_db);
179 + const runtime=clientFor(state.target_db,'api'); await runtime.connect();
180 + try {
181 + assert.equal((await runtime.query("SELECT count(*)::int n FROM app_user WHERE identity_subject='restore-smoke'")).rows[0].n,1);
182 + assert.equal((await runtime.query("SELECT count(*)::int n FROM profile WHERE display_name='Restore Smoke'")).rows[0].n,1);
183 + assert.equal((await runtime.query("SELECT can_view_plan_item('00000000-0000-4000-8000-000000000005','00000000-0000-4000-8000-000000000005') allowed")).rows[0].allowed,true);
184 + assert.equal((await runtime.query("SELECT can_view_plan_item('00000000-0000-4000-8000-000000000005','00000000-0000-4000-8000-000000000006') allowed")).rows[0].allowed,false);
185 + assert.equal((await runtime.query("SELECT can_view_plan_item('00000000-0000-4000-8000-000000000007','00000000-0000-4000-8000-000000000005') allowed")).rows[0].allowed,false);
186 + } finally { await runtime.end(); }
187 + console.log('PASS restored12 checksum ledger entries, migrator ownership/repeat, runtime denial matrix, guardian/private policy and paused-study600seconds');
188 + } else {
189 + for(const database of state.created ?? []) {
190 + assert.ok([state.source_db,state.target_db].includes(database),'Refusing unrelated cleanup');
191 + if(await taggedDatabase(database)) {
192 + await admin.query(`DROP DATABASE ${ident(database)}`);
193 + }
194 + }
195 + console.log('PASS cleanup: only tagged newly-created role-test databases dropped; application DB preserved');
196 + }
197 + }
198 +} finally { await admin.end(); }
docker-compose.yml
+92 -5
@@ -6,8 +6,8 @@ x-api-environment: &api-environment
6 PGHOST: postgres
7 PGPORT: 5432
8 PGDATABASE: ${POSTGRES_DB:-lifemate}
9 - PGUSER: ${POSTGRES_USER:-lifeguide}
10 - PGPASSWORD: ${POSTGRES_PASSWORD:?Generate POSTGRES_PASSWORD in .env}
9 + PGUSER: ${API_DB_USER:-lifeguide_api}
10 + PGPASSWORD: ${API_DB_PASSWORD:?Generate independent API_DB_PASSWORD in .env}
11 JWT_SECRET: ${JWT_SECRET:?Generate JWT_SECRET in .env}
12 PUBLIC_APP_URL: ${PUBLIC_APP_URL:?Set the operator-approved HTTPS origin}
13 CORS_ORIGINS: ${CORS_ORIGINS:?Set the operator-approved HTTPS origin}
@@ -23,6 +23,23 @@ x-api-environment: &api-environment
23 SMS_PROVIDER_TOKEN: ${SMS_PROVIDER_TOKEN:-}
24 TRUSTED_PROXY_CIDRS: ${GATEWAY_PROXY_IP:-172.30.86.10}/32
25
26 +x-admin-environment: &admin-environment
27 + PGHOST: postgres
28 + PGPORT: 5432
29 + PGDATABASE: ${POSTGRES_DB:-lifemate}
30 + PGUSER: ${POSTGRES_USER:-lifeguide}
31 + PGPASSWORD: ${POSTGRES_PASSWORD:?Generate POSTGRES_PASSWORD in .env}
32 + API_DB_USER: ${API_DB_USER:-lifeguide_api}
33 + MIGRATOR_DB_USER: ${MIGRATOR_DB_USER:-lifeguide_migrator}
34 + BACKUP_DB_USER: ${BACKUP_DB_USER:-lifeguide_backup}
35 +
36 +x-migration-environment: &migration-environment
37 + PGHOST: postgres
38 + PGPORT: 5432
39 + PGDATABASE: ${POSTGRES_DB:-lifemate}
40 + PGUSER: ${MIGRATOR_DB_USER:-lifeguide_migrator}
41 + PGPASSWORD: ${MIGRATOR_DB_PASSWORD:?Generate independent MIGRATOR_DB_PASSWORD in .env}
42 +
43 services:
44 postgres:
45 image: postgres:16
@@ -41,15 +58,51 @@ services:
58 retries: 20
59 networks: [private]
60
61 + db-provision:
62 + image: ${API_IMAGE:-lifeguide-api:local}
63 + build:
64 + context: ./backend
65 + command: [node, scripts/provision-db-roles.js, --prepare]
66 + # Short-lived ops job reads root-owned mode600 backups read-only; the API
67 + # remains USER node and never mounts this volume or receives admin secrets.
68 + user: '0:0'
69 + read_only: true
70 + tmpfs: [/tmp]
71 + security_opt: [no-new-privileges:true]
72 + environment:
73 + <<: *admin-environment
74 + API_DB_PASSWORD: ${API_DB_PASSWORD:?Generate independent API_DB_PASSWORD in .env}
75 + MIGRATOR_DB_PASSWORD: ${MIGRATOR_DB_PASSWORD:?Generate independent MIGRATOR_DB_PASSWORD in .env}
76 + BACKUP_DB_PASSWORD: ${BACKUP_DB_PASSWORD:?Generate independent BACKUP_DB_PASSWORD in .env}
77 + volumes:
78 + - backups:/backups:ro
79 + depends_on:
80 + postgres:
81 + condition: service_healthy
82 + restart: 'no'
83 + networks: [private]
84 +
85 migrate:
86 image: ${API_IMAGE:-lifeguide-api:local}
87 build:
88 context: ./backend
89 command: [node, scripts/migrate.js]
49 - environment: *api-environment
90 + environment: *migration-environment
91 depends_on:
92 postgres:
93 condition: service_healthy
94 + db-provision:
95 + condition: service_completed_successfully
96 + restart: 'no'
97 + networks: [private]
98 +
99 + db-grants:
100 + image: ${API_IMAGE:-lifeguide-api:local}
101 + command: [node, scripts/provision-db-roles.js, --grants]
102 + environment: *admin-environment
103 + depends_on:
104 + migrate:
105 + condition: service_completed_successfully
106 restart: 'no'
107 networks: [private]
108
@@ -67,6 +120,8 @@ services:
120 condition: service_healthy
121 migrate:
122 condition: service_completed_successfully
123 + db-grants:
124 + condition: service_completed_successfully
125 healthcheck:
126 test: [CMD, node, -e, "fetch('http://127.0.0.1:8080/ready').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
127 interval: 10s
@@ -112,8 +167,8 @@ services:
167 dockerfile: deployment/backup/Dockerfile
168 restart: unless-stopped
169 environment:
115 - DATABASE_URL: postgresql://${POSTGRES_USER:-lifeguide}@postgres:5432/${POSTGRES_DB:-lifemate}
116 - PGPASSWORD: ${POSTGRES_PASSWORD:?Generate POSTGRES_PASSWORD in .env}
170 + DATABASE_URL: postgresql://${BACKUP_DB_USER:-lifeguide_backup}@postgres:5432/${POSTGRES_DB:-lifemate}
171 + PGPASSWORD: ${BACKUP_DB_PASSWORD:?Generate independent BACKUP_DB_PASSWORD in .env}
172 BACKUP_SCHEDULE: ${BACKUP_SCHEDULE:-0 2 * * *}
173 BACKUP_KEEP_DAYS: ${BACKUP_KEEP_DAYS:-14}
174 BACKUP_MAX_AGE_SECONDS: ${BACKUP_MAX_AGE_SECONDS:-93600}
@@ -122,6 +177,8 @@ services:
177 depends_on:
178 postgres:
179 condition: service_healthy
180 + db-grants:
181 + condition: service_completed_successfully
182 healthcheck:
183 test: [CMD-SHELL, 'kill -0 1 && test -f /backups/last-success && test "$$(( $$(date +%s) - $$(stat -c %Y /backups/last-success) ))" -lt "$${BACKUP_MAX_AGE_SECONDS:-93600}"']
184 interval: 60s
@@ -130,6 +187,36 @@ services:
187 start_period: 60s
188 networks: [private]
189
190 + # Explicit operator tools: never start these as a background application.
191 + restore:
192 + profiles: [ops]
193 + build:
194 + context: .
195 + dockerfile: deployment/backup/Dockerfile
196 + entrypoint: [/opt/lifeguide/restore.sh]
197 + environment:
198 + DATABASE_URL: postgresql://${MIGRATOR_DB_USER:-lifeguide_migrator}@postgres:5432/${POSTGRES_DB:-lifemate}
199 + PGPASSWORD: ${MIGRATOR_DB_PASSWORD:?Generate independent MIGRATOR_DB_PASSWORD in .env}
200 + volumes: [backups:/backups]
201 + restart: 'no'
202 + networks: [private]
203 +
204 + db-role-test:
205 + profiles: [ops]
206 + image: ${API_IMAGE:-lifeguide-api:local}
207 + command: [node, scripts/test-db-roles.js, --synthetic-only]
208 + environment:
209 + <<: *admin-environment
210 + API_DB_PASSWORD: ${API_DB_PASSWORD:?Generate independent API_DB_PASSWORD in .env}
211 + MIGRATOR_DB_PASSWORD: ${MIGRATOR_DB_PASSWORD:?Generate independent MIGRATOR_DB_PASSWORD in .env}
212 + BACKUP_DB_PASSWORD: ${BACKUP_DB_PASSWORD:?Generate independent BACKUP_DB_PASSWORD in .env}
213 + DB_ROLE_RESTORE_FIXTURE: /app/restore-fixture.sql
214 + volumes:
215 + - ./backend/tests/online_acceptance.test.js:/app/tests/online_acceptance.test.js:ro
216 + - ./deployment/restore-fixture.sql:/app/restore-fixture.sql:ro
217 + restart: 'no'
218 + networks: [private]
219 +
220 volumes:
221 postgres-data:
222 backups:
scripts/adopt-db-roles.sh new
+26
@@ -0,0 +1,26 @@
1 +#!/usr/bin/env bash
2 +# Explicit operator-only adoption. Never SSHs or restores/drops application data.
3 +set -euo pipefail
4 +cd "$(dirname "${BASH_SOURCE[0]}")/.."
5 +[[ "${1:-}" == '--local-existing' && "${2:-}" == '--expected-owner' && "${4:-}" == '--backup-file' && "$#" -eq 5 ]] || { echo 'Usage: --local-existing --expected-owner ROLE --backup-file /backups/LifeGuide-....dump' >&2; exit 1; }
6 +expected_owner="$3"
7 +backup_file="$5"
8 +[[ "$expected_owner" =~ ^[a-z_][a-z0-9_]{0,62}$ && "$backup_file" =~ ^/backups/LifeGuide-[A-Za-z0-9._-]+\.dump$ ]] || { echo 'Use an explicit safe expected owner and archive within the backup volume' >&2; exit 1; }
9 +if [[ -n "${DOCKER_CONTEXT:-}" ]]; then endpoint="$(docker context inspect "$DOCKER_CONTEXT" --format '{{.Endpoints.docker.Host}}')"; else endpoint="${DOCKER_HOST:-$(docker context inspect --format '{{.Endpoints.docker.Host}}')}"; fi
10 +case "$endpoint" in unix://*|npipe://*) ;; *) echo 'Refusing remote Docker' >&2; exit 1;; esac
11 +docker compose config --quiet
12 +# Stop writers deliberately before invoking this helper; it refuses an active API.
13 +if [[ -n "$(docker compose ps --status running -q api)" ]]; then echo 'Stop the local API/gateway writers and take a fresh verified backup before adoption' >&2; exit 1; fi
14 +database="$(sed -n 's/^POSTGRES_DB=//p' .env)"
15 +[[ "$database" =~ ^[a-z_][a-z0-9_]{0,62}$ ]] || { echo 'Invalid configured app database name' >&2; exit 1; }
16 +toc_file="$(mktemp "${TMPDIR:-/tmp}/lifeguide-adoption-toc.XXXXXX")"
17 +trap 'rm -f "$toc_file"' EXIT
18 +docker compose run --rm --no-deps --entrypoint pg_restore -e TZ=UTC backup --list "$backup_file" >"$toc_file"
19 +archive_db="$(sed -n 's/^;[[:space:]]*dbname: //p' "$toc_file")"
20 +[[ "$archive_db" == "$database" ]] || { echo 'Backup is for another database; refusing adoption' >&2; exit 1; }
21 +digest="$(docker compose run --rm --no-deps --entrypoint sha256sum backup "$backup_file" | cut -d' ' -f1)"
22 +[[ "$digest" =~ ^[a-f0-9]{64}$ ]] || { echo 'Cannot hash verified archive' >&2; exit 1; }
23 +node --input-type=module -e 'console.log(JSON.stringify({format:"LifeGuide-adoption-backup-v1",database:process.argv[1],sha256:process.argv[2],pgRestoreList:true,validatedAt:new Date().toISOString()}))' "$database" "$digest" | \
24 + docker compose run --rm --no-deps --entrypoint sh backup -c 'umask 077; cat > "$1.validated.json"' sh "$backup_file"
25 +docker compose run --rm --no-deps db-provision node scripts/provision-db-roles.js --prepare --adopt-existing --expected-owner "$expected_owner" --backup-file "$backup_file"
26 +echo 'PASS explicit local ownership adoption. Run migrations/grants/start and synthetic acceptance before admitting users.'
scripts/local-deploy.ps1
+6 -2
@@ -43,7 +43,9 @@ if (!(Test-Path '.env')) {
43 } else {
44 Write-Host '.env exists and is preserved; Origin/certificate changes require a deliberate .env edit.'
45 }
46 -if ((Get-Content '.env' -Raw) -match '(?m)^(POSTGRES_PASSWORD|JWT_SECRET)=CHANGE_ME') {
46 +& node scripts/prepare-db-role-env.mjs --write
47 +if ($LASTEXITCODE -ne 0) { throw 'Independent database role environment preparation failed.' }
48 +if ((Get-Content '.env' -Raw) -match '(?m)^(POSTGRES_PASSWORD|API_DB_PASSWORD|MIGRATOR_DB_PASSWORD|BACKUP_DB_PASSWORD|JWT_SECRET)=CHANGE_ME') {
49 throw 'Replace placeholder secrets in .env.'
50 }
51 $endpoint = $null
@@ -82,7 +84,9 @@ if ($env:BUILD_CA_FILE) {
84 Invoke-CheckedDocker -Arguments ($composeBuild + @('build', '--build-arg', 'HTTP_PROXY', '--build-arg', 'HTTPS_PROXY', 'api', 'gateway', 'backup'))
85 }
86 Invoke-CheckedDocker -Arguments @('compose', 'up', '-d', '--wait', '--wait-timeout', '120', 'postgres')
85 -Invoke-CheckedDocker -Arguments @('compose', 'run', '--rm', 'migrate')
87 +Invoke-CheckedDocker -Arguments @('compose', 'run', '--rm', '--no-deps', 'db-provision')
88 +Invoke-CheckedDocker -Arguments @('compose', 'run', '--rm', '--no-deps', 'migrate')
89 +Invoke-CheckedDocker -Arguments @('compose', 'run', '--rm', '--no-deps', 'db-grants')
90 Invoke-CheckedDocker -Arguments @('compose', 'up', '-d', '--wait', '--wait-timeout', '180', 'api', 'gateway', 'backup')
91 Invoke-CheckedDocker -Arguments @('compose', 'ps')
92 Write-Host 'Local stack started. Run the HTTPS smoke test with synthetic accounts.'
scripts/local-deploy.sh
+6 -2
@@ -31,7 +31,9 @@ if [[ "${1:-}" == '--init' ]]; then
31 fi
32 fi
33 [[ -f .env ]] || { echo 'Create .env first, or use --init https://LAN-IP' >&2; exit 1; }
34 -if grep -Eq '^((POSTGRES_PASSWORD|JWT_SECRET)=CHANGE_ME|JWT_SECRET=.{0,31}$)' .env; then
34 +command -v node >/dev/null || { echo 'Node >=22 required to prepare/check independent database role settings' >&2; exit 1; }
35 +node scripts/prepare-db-role-env.mjs --write
36 +if grep -Eq '^((POSTGRES_PASSWORD|API_DB_PASSWORD|MIGRATOR_DB_PASSWORD|BACKUP_DB_PASSWORD|JWT_SECRET)=CHANGE_ME|JWT_SECRET=.{0,31}$)' .env; then
37 echo 'Replace placeholder/short secrets in .env' >&2; exit 1
38 fi
39 if [[ -n "${DOCKER_CONTEXT:-}" ]]; then
@@ -66,7 +68,9 @@ else
68 docker compose "${compose_build[@]}" build --build-arg HTTP_PROXY --build-arg HTTPS_PROXY api gateway backup
69 fi
70 docker compose up -d --wait --wait-timeout 120 postgres
69 -docker compose run --rm migrate
71 +docker compose run --rm --no-deps db-provision
72 +docker compose run --rm --no-deps migrate
73 +docker compose run --rm --no-deps db-grants
74 docker compose up -d --wait --wait-timeout 180 api gateway backup
75 docker compose ps
76 echo 'Local stack started. Run the HTTPS smoke test; health alone does not prove family CRUD.'
scripts/prepare-db-role-env.mjs new
+36
@@ -0,0 +1,36 @@
1 +// Offline local-file preparation only. Preserves existing secrets/settings.
2 +import crypto from 'node:crypto';
3 +import fs from 'node:fs/promises';
4 +const envFile = new URL('../.env',import.meta.url);
5 +if (process.argv[2] !== '--write' || process.argv.length !== 3) throw new Error('Use --write to append missing private local role settings');
6 +let contents = await fs.readFile(envFile,'utf8');
7 +const original = contents;
8 +const additions=[];
9 +for(const [prefix,user] of [['API','lifeguide_api'],['MIGRATOR','lifeguide_migrator'],['BACKUP','lifeguide_backup']]) {
10 + const userPattern = new RegExp(`^${prefix}_DB_USER=(.*)$`,'m');
11 + const existingUser=contents.match(userPattern)?.[1];
12 + if(existingUser && existingUser!==user) throw new Error('Configured application roles must use their canonical distinct names');
13 + if(!existingUser) {
14 + if(userPattern.test(contents)) contents=contents.replace(userPattern,`${prefix}_DB_USER=${user}`);
15 + else additions.push(`${prefix}_DB_USER=${user}`);
16 + }
17 + const passwordPattern = new RegExp(`^${prefix}_DB_PASSWORD=(.*)$`,'m');
18 + const existingPassword = contents.match(passwordPattern)?.[1];
19 + if(!existingPassword || existingPassword.startsWith('CHANGE_ME')) {
20 + const value=`${prefix}_DB_PASSWORD=${crypto.randomBytes(32).toString('hex')}`;
21 + if(passwordPattern.test(contents)) contents=contents.replace(passwordPattern,value);
22 + else additions.push(value);
23 + }
24 +}
25 +if(additions.length) {
26 + contents=contents.replace(/\s*$/,'')+'\n# Independent local application DB credentials\n'+additions.join('\n')+'\n';
27 +}
28 +if(contents!==original) {
29 + const temporary = new URL(`../.env.roles-${crypto.randomBytes(8).toString('hex')}.tmp`,import.meta.url);
30 + try {
31 + const file=await fs.open(temporary,'wx',0o600);
32 + try { await file.writeFile(contents); await file.sync(); } finally { await file.close(); }
33 + await fs.rename(temporary,envFile);
34 + } finally { await fs.rm(temporary,{force:true}); }
35 + console.log('Appended missing private role settings; existing values preserved. No database/server operation ran.');
36 +} else console.log('Private role settings already present; preserved unchanged.');
scripts/restore-drill.sh
+3 -66
@@ -1,70 +1,7 @@
1 #!/usr/bin/env bash
2 -# Only two newly-created local databases are restored/deleted, never the app DB.
2 +# Fresh synthetic databases only: read-only dump, migrator restore, runtime
3 +# authentication/family scenario and denied privileges are checked together.
4 set -euo pipefail
5 cd "$(dirname "${BASH_SOURCE[0]}")/.."
6 [[ "${1:-}" == '--synthetic-only' ]] || { echo 'Usage: scripts/restore-drill.sh --synthetic-only' >&2; exit 1; }
6 -if [[ -n "${DOCKER_CONTEXT:-}" ]]; then
7 - endpoint="$(docker context inspect "$DOCKER_CONTEXT" --format '{{.Endpoints.docker.Host}}')"
8 -else
9 - endpoint="${DOCKER_HOST:-$(docker context inspect --format '{{.Endpoints.docker.Host}}')}"
10 -fi
11 -case "$endpoint" in unix://*|npipe://*) ;; *) echo 'Refusing remote Docker' >&2; exit 1;; esac
12 -suffix="$(date -u +%Y%m%d%H%M%S)_${RANDOM}${RANDOM}${RANDOM}"
13 -source_db="lifeguide_drill_source_$suffix"
14 -target_db="lifeguide_drill_target_$suffix"
15 -source_created=no
16 -target_created=no
17 -cleanup() {
18 - if [[ "$target_created" == yes ]]; then
19 - docker compose exec -T postgres sh -c 'dropdb --if-exists --username "$POSTGRES_USER" "$1"' sh "$target_db" >/dev/null 2>&1 || true
20 - fi
21 - if [[ "$source_created" == yes ]]; then
22 - docker compose exec -T postgres sh -c 'dropdb --if-exists --username "$POSTGRES_USER" "$1"; rm -f "/tmp/$1.dump"' sh "$source_db" >/dev/null 2>&1 || true
23 - fi
24 -}
25 -trap cleanup EXIT
26 -docker compose exec -T postgres sh -c 'createdb --username "$POSTGRES_USER" "$1"' sh "$source_db"
27 -source_created=yes
28 -docker compose exec -T postgres sh -c 'createdb --username "$POSTGRES_USER" "$1"' sh "$target_db"
29 -target_created=yes
30 -docker compose run --rm -e "PGDATABASE=$source_db" migrate
31 -docker compose exec -T postgres sh -c 'psql --username "$POSTGRES_USER" --dbname "$1" --set ON_ERROR_STOP=1' sh "$source_db" <backend/scripts/restore-smoke.sql
32 -docker compose exec -T postgres sh -c 'psql --username "$POSTGRES_USER" --dbname "$1" --set ON_ERROR_STOP=1' sh "$source_db" <deployment/restore-fixture.sql
33 -# Copy the already-existing repository backup/restore programs into this
34 -# disposable container, then run them against only the generated drill DBs.
35 -container_id="$(docker compose ps -q postgres)"
36 -docker cp backend/scripts/backup.sh "$container_id:/tmp/lifeguide-backup.sh"
37 -docker cp backend/scripts/restore.sh "$container_id:/tmp/lifeguide-restore.sh"
38 -docker compose exec -T postgres bash -c 'export DATABASE_URL="postgresql:///$1?user=$POSTGRES_USER"; bash /tmp/lifeguide-backup.sh "/tmp/$1.dump"' bash "$source_db"
39 -docker compose exec -T postgres bash -c 'export DATABASE_URL="postgresql:///$2?user=$POSTGRES_USER"; bash /tmp/lifeguide-restore.sh "/tmp/$1.dump"' bash "$source_db" "$target_db"
40 -docker compose exec -T postgres sh -c 'psql --username "$POSTGRES_USER" --dbname "$1" --set ON_ERROR_STOP=1' sh "$target_db" <<'SQL'
41 -do $$
42 -begin
43 - if (select count(*) from app_user where identity_subject='restore-smoke') <> 1 then
44 - raise exception 'Synthetic restore row missing';
45 - end if;
46 - if (select count(*) from profile where display_name='Restore Smoke') <> 1 then
47 - raise exception 'Synthetic profile missing';
48 - end if;
49 - if not can_view_plan_item('00000000-0000-4000-8000-000000000005','00000000-0000-4000-8000-000000000005') then
50 - raise exception 'Restored guardian cannot read permitted homework';
51 - end if;
52 - if can_view_plan_item('00000000-0000-4000-8000-000000000005','00000000-0000-4000-8000-000000000006') then
53 - raise exception 'Restored private task exposed to guardian';
54 - end if;
55 - if can_view_plan_item('00000000-0000-4000-8000-000000000007','00000000-0000-4000-8000-000000000005') then
56 - raise exception 'Restored homework exposed to unrelated parent';
57 - end if;
58 - if (select recorded_duration_seconds from study_session where id='00000000-0000-4000-8000-000000000005') <> 600
59 - or (select sum(extract(epoch from ends_at-starts_at)) from study_interval where session_id='00000000-0000-4000-8000-000000000005') <> 600 then
60 - raise exception 'Restored paused study intervals/duration changed';
61 - end if;
62 -end $$;
63 -SQL
64 -expected_migrations=0
65 -for migration_file in backend/migrations/[0-9][0-9][0-9][0-9]_*.sql; do
66 - [[ -f "$migration_file" ]] && expected_migrations=$((expected_migrations+1))
67 -done
68 -restored_migrations="$(docker compose exec -T postgres sh -c 'psql --username "$POSTGRES_USER" --dbname "$1" --tuples-only --no-align --command "select count(*) from schema_migration"' sh "$target_db")"
69 -[[ "$restored_migrations" -eq "$expected_migrations" ]] || { echo 'Migration ledger count differs from source version' >&2; exit 1; }
70 -echo "PASS synthetic PostgreSQL dump/restore: identity, family permissions, private task, paused study intervals and $restored_migrations migrations preserved."
7 +exec bash scripts/test-db-roles.sh --synthetic-only
scripts/test-db-roles.sh new
+41
@@ -0,0 +1,41 @@
1 +#!/usr/bin/env bash
2 +# Fresh synthetic databases only; never targets the application DB for restore.
3 +set -euo pipefail
4 +cd "$(dirname "${BASH_SOURCE[0]}")/.."
5 +[[ "${1:-}" == '--synthetic-only' ]] || { echo 'Use --synthetic-only explicitly' >&2; exit 1; }
6 +if [[ -n "${DOCKER_CONTEXT:-}" ]]; then
7 + endpoint="$(docker context inspect "$DOCKER_CONTEXT" --format '{{.Endpoints.docker.Host}}')"
8 +else
9 + endpoint="${DOCKER_HOST:-$(docker context inspect --format '{{.Endpoints.docker.Host}}')}"
10 +fi
11 +case "$endpoint" in unix://*|npipe://*) ;; *) echo 'Refusing remote Docker' >&2; exit 1;; esac
12 +docker compose config --quiet
13 +state_dir="$(mktemp -d "${TMPDIR:-/tmp}/lifeguide-role-test.XXXXXX")"
14 +chmod 700 "$state_dir"
15 +tool_args=(compose run --rm --no-deps --user "$(id -u):$(id -g)" -v "$state_dir:/role-test-state" -e ROLE_TEST_STATE_FILE=/role-test-state/state.json db-role-test)
16 +dump_file=''
17 +cleanup() {
18 + cleanup_ok=yes
19 + if [[ -f "$state_dir/state.json" ]]; then
20 + if ! docker "${tool_args[@]}" node scripts/test-db-roles.js --cleanup; then
21 + cleanup_ok=no
22 + echo "UNVERIFIED: test database cleanup needs operator review; state preserved in $state_dir" >&2
23 + fi
24 + fi
25 + if [[ -n "$dump_file" ]]; then
26 + docker compose run --rm --no-deps --entrypoint rm backup -f "$dump_file" >/dev/null 2>&1 || true
27 + fi
28 + if [[ "$cleanup_ok" == yes ]]; then rm -rf "$state_dir"; fi
29 +}
30 +trap cleanup EXIT
31 +docker "${tool_args[@]}"
32 +source_db="$(node -p 'JSON.parse(require("fs").readFileSync(process.argv[1],"utf8")).source_db' "$state_dir/state.json")"
33 +target_db="$(node -p 'JSON.parse(require("fs").readFileSync(process.argv[1],"utf8")).target_db' "$state_dir/state.json")"
34 +[[ "$source_db" =~ ^lifeguide_roles_source_[a-f0-9]{16}$ && "$target_db" =~ ^lifeguide_roles_target_[a-f0-9]{16}$ ]] || { echo 'Invalid synthetic database names' >&2; exit 1; }
35 +dump_file="/backups/LifeGuide-role-test-${source_db#lifeguide_roles_source_}.dump"
36 +docker compose run --rm --no-deps --entrypoint /opt/lifeguide/backup.sh \
37 + -e "DATABASE_URL=postgresql://lifeguide_backup@postgres:5432/$source_db" backup "$dump_file"
38 +docker compose run --rm --no-deps --entrypoint pg_restore backup --list "$dump_file" >/dev/null
39 +docker compose run --rm --no-deps -e "DATABASE_URL=postgresql://lifeguide_migrator@postgres:5432/$target_db" restore "$dump_file"
40 +docker "${tool_args[@]}" node scripts/test-db-roles.js --verify-restored
41 +echo 'PASS local least-privilege SQL + runtime HTTP scenario + read-only dump/migrator restore with12 migrations'