LifeMate — Personal, Family & Learning Companion

feat/online-family-stage0
chore/phase1-repository-cleanup deploy/stable-web-apk deployment-static design/mobile-accessibility-v2 design/mobile-navigation-review docs/child-education-access-decision docs/offline-data-rescue-options docs/owner-guide-and-delivery-plan docs/phase1-policy-options docs/public-review-live-2026-10-15 feat/aparat-learning-library feat/child-device-safety feat/child-identity-schema feat/flutter-mobile-navigation feat/learning-content-operations feat/local-signing-preflight feat/online-family-stage0 feat/personal-encrypted-recovery feat/private-planner-series-api feat/public-review-page feat/standalone-weekly-planner feat/weekly-planner-android final-feature-1/iran-family-school fix/auth-abuse-expiry-safety fix/auth-expiry-after-lock fix/backend-request-safety fix/lifeguide-bootstrap-naming-ci fix/lifeguide-pages-qa-base-preflight fix/lifeguide-qa-pages-env-deployment fix/local-task-persistence fix/managed-child-session-boundary fix/personal-jalali-dates fix/personal-notification-controls fix/personal-upgrade-delivery-guard fix/sms-approval-gates fix/study-duration-display infra/cloudflare-neon-migration infra/lifeguide-cloudflare-qa infra/lifeguide-github-pages-qa infra/lifeguide-supabase-qa main phase-1/foundation-completion phase-2/product-foundation-identity phase-3/planner-school-family-core phase-4/ai-learning-wellbeing phase-5/hardening-observability-release test/android-reminder-acceptance test/personal-notification-settings test/personal-recovery-acceptance test/role-entry-apk
js 198 lines 15.5 KB
Raw
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(); }