LifeMate — Personal, Family & Learning Companion

feat/weekly-planner-android
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 235 lines 19.3 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 expectedMigrations=(await fs.readdir(path.join(backend,'migrations'))).filter(name=>name.endsWith('.sql')).sort();
19 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};
20 const admin=new pg.Client(adminConfig);
21 const statePath=process.env.ROLE_TEST_STATE_FILE;
22 const ident=(name)=>`"${name.replaceAll('"','""')}"`;
23 const clientFor=(database,kind)=>new pg.Client({...adminConfig,database,user:roleNames[kind],password:process.env[`${{api:'API',migrator:'MIGRATOR',backup:'BACKUP'}[kind]}_DB_PASSWORD`]});
24 let state;
25 async function readState() {
26 const value=JSON.parse(await fs.readFile(statePath,'utf8'));
27 assert.match(value.run,/^[a-f0-9]{16}$/);
28 assert.equal(value.source_db,`lifeguide_roles_source_${value.run}`);
29 assert.equal(value.target_db,`lifeguide_roles_target_${value.run}`);
30 return value;
31 }
32 async function taggedDatabase(database) {
33 const result=await admin.query(`SELECT pg_get_userbyid(datdba) owner,shobj_description(oid,'pg_database') marker FROM pg_database WHERE datname=$1`,[database]);
34 if(!result.rowCount) return false;
35 assert.equal(result.rows[0].owner,(await admin.query('SELECT current_user')).rows[0].current_user,'Refusing another owner database');
36 assert.equal(result.rows[0].marker,`LifeGuide synthetic role acceptance ${state.run}`,'Refusing an untagged database');
37 return true;
38 }
39 async function denied(client,sql,label) {
40 try { await client.query(sql); assert.fail(`${label} unexpectedly succeeded`); }
41 catch(error) { assert.equal(error.code,'42501',`${label} must be denied by PostgreSQL permissions`); }
42 console.log(`PASS denied: ${label}`);
43 }
44 async function checkPolicy(database) {
45 const runtime=clientFor(database,'api'), backup=clientFor(database,'backup'), migrator=clientFor(database,'migrator');
46 await Promise.all([runtime.connect(),backup.connect(),migrator.connect()]);
47 try {
48 for(const [kind,client] of [['api',runtime],['backup',backup],['migrator',migrator]]) {
49 const row=(await client.query(`SELECT current_user,rolsuper,rolcreatedb,rolcreaterole,rolreplication,rolbypassrls,rolinherit
50 FROM pg_roles WHERE rolname=current_user`)).rows[0];
51 assert.equal(row.current_user,roleNames[kind]);
52 for(const flag of ['rolsuper','rolcreatedb','rolcreaterole','rolreplication','rolbypassrls','rolinherit']) assert.equal(row[flag],false,`${kind}.${flag}`);
53 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);
54 }
55 const capabilities=(await runtime.query(`SELECT has_database_privilege(current_user,current_database(),'CREATE') db_create,
56 has_database_privilege(current_user,current_database(),'TEMP') db_temp,has_schema_privilege(current_user,'public','CREATE') schema_create,
57 pg_has_role(current_user,'lifeguide_migrator','MEMBER') migrator_member,
58 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];
59 assert.ok(Object.values(capabilities).every(value=>value===false));
60 assert.equal((await migrator.query("SELECT pg_get_userbyid(nspowner) owner FROM pg_namespace WHERE nspname='public'")).rows[0].owner,roleNames.migrator);
61 assert.equal((await migrator.query("SELECT count(*)::int n FROM schema_migration WHERE sha256 IS NOT NULL")).rows[0].n,expectedMigrations.length);
62 await denied(runtime,'CREATE TABLE public.forbidden_runtime_table(id integer)','runtime CREATE TABLE');
63 await denied(runtime,'CREATE TEMP TABLE forbidden_runtime_temp(id integer)','runtime TEMP');
64 await denied(runtime,'ALTER TABLE public.plan_item ADD COLUMN forbidden_runtime_column integer','runtime ALTER TABLE');
65 await denied(runtime,"ALTER ROLE lifeguide_migrator PASSWORD 'synthetic-forbidden-only'",'runtime ALTER other ROLE');
66 await denied(runtime,'ALTER ROLE lifeguide_api SUPERUSER','runtime privilege escalation');
67 await denied(runtime,'SET ROLE lifeguide_migrator','runtime SET ROLE migrator');
68 await denied(runtime,"INSERT INTO public.schema_migration(filename) VALUES('forbidden-role-test')",'runtime ledger INSERT');
69 await denied(runtime,"UPDATE public.schema_migration SET sha256='forbidden'",'runtime ledger UPDATE');
70 await denied(runtime,'DELETE FROM public.schema_migration','runtime ledger DELETE');
71 await denied(runtime,'SELECT * FROM public.schema_migration','runtime ledger SELECT unnecessary');
72 await denied(runtime,'TRUNCATE public.plan_item','runtime TRUNCATE');
73 for(const table of ['curriculum_subject','textbook_catalog','learning_unit','learning_video_resource','learning_assessment',
74 'content_capability_grant','content_capability_audit','content_publication_audit']) {
75 assert.equal((await runtime.query(`SELECT count(*)::int n FROM public.${ident(table)}`)).rows.length,1);
76 await denied(runtime,`INSERT INTO public.${ident(table)} DEFAULT VALUES`,`${table}: runtime catalog INSERT`);
77 const field=table==='content_capability_grant'?'user_id':table==='content_publication_audit'?'mutation_id':'id';
78 await denied(runtime,`UPDATE public.${ident(table)} SET ${field}=${field}`,`${table}: runtime catalog UPDATE/publication`);
79 await denied(runtime,`DELETE FROM public.${ident(table)}`,`${table}: runtime catalog DELETE`);
80 }
81 for(const table of ['content_review_audit','content_review_mutation','content_review_brief','content_review_brief_source',
82 'learning_goal_mutation','family_lifecycle_mutation','school_lifecycle_mutation']) {
83 const field=['learning_goal_mutation','school_lifecycle_mutation'].includes(table)?'owner_user_id':
84 ['content_review_mutation','family_lifecycle_mutation'].includes(table)?'actor_user_id':
85 table==='content_review_brief_source'?'brief_id':'id';
86 assert.equal((await runtime.query(`SELECT count(*)::int n FROM public.${ident(table)}`)).rows.length,1);
87 await denied(runtime,`UPDATE public.${ident(table)} SET ${field}=${field}`,`${table}: runtime immutable receipt UPDATE`);
88 await denied(runtime,`DELETE FROM public.${ident(table)}`,`${table}: runtime immutable receipt DELETE`);
89 }
90 await denied(backup,'UPDATE public.app_user SET id=id','backup UPDATE');
91 await denied(backup,'CREATE TABLE public.forbidden_backup_table(id integer)','backup CREATE TABLE');
92 await denied(backup,'CREATE TEMP TABLE forbidden_backup_temp(id integer)','backup TEMP');
93 await denied(backup,'SELECT public.recompute_reminder_schedule(NULL)','backup side-effect application function');
94 await denied(backup,"SELECT setval('public.access_audit_id_seq',999)",'backup sequence setval');
95 assert.equal((await backup.query('SELECT count(*)::int n FROM public.schema_migration')).rows[0].n,expectedMigrations.length);
96 console.log('PASS runtime/migrator/backup flags, ownership, memberships and backup ledger read');
97 await migrator.query('CREATE TABLE public.future_role_probe(id integer PRIMARY KEY,value text)');
98 try {
99 await migrator.query("INSERT INTO public.future_role_probe VALUES(1,'synthetic-only')");
100 assert.equal((await runtime.query('SELECT value FROM public.future_role_probe WHERE id=1')).rows[0].value,'synthetic-only');
101 await migrator.query("UPDATE public.future_role_probe SET value='updated-synthetic' WHERE id=1");
102 assert.equal((await backup.query('SELECT value FROM public.future_role_probe WHERE id=1')).rows[0].value,'updated-synthetic');
103 await denied(runtime,"INSERT INTO public.future_role_probe VALUES(2,'forbidden')",'future-table runtime INSERT failclosed');
104 await denied(runtime,'UPDATE public.future_role_probe SET id=id','future-table runtime UPDATE failclosed');
105 await denied(runtime,'DELETE FROM public.future_role_probe','future-table runtime DELETE failclosed');
106 await denied(runtime,'ALTER TABLE public.future_role_probe ADD COLUMN forbidden integer','future-table ownership retained by migrator');
107 console.log('PASS future migrator-created table: default runtime/backup SELECT, write/DDL denied');
108 } finally { await migrator.query('DROP TABLE public.future_role_probe'); }
109 } finally { await Promise.all([runtime.end(),backup.end(),migrator.end()]); }
110 }
111 async function migrate(database) {
112 const env={...process.env,PGDATABASE:database,PGUSER:roleNames.migrator,PGPASSWORD:process.env.MIGRATOR_DB_PASSWORD};
113 delete env.DATABASE_URL;
114 const result=spawnSync(process.execPath,['scripts/migrate.js'],{cwd:backend,env,stdio:'inherit'});
115 assert.equal(result.status,0,'Non-superuser migration failed');
116 const imported=spawnSync(process.execPath,['scripts/import-learning-catalog.js'],{cwd:backend,env,stdio:'inherit'});
117 assert.equal(imported.status,0,'Non-superuser catalogue import failed');
118 }
119 try {
120 await admin.connect();
121 if(mode==='--synthetic-only') {
122 state={run:crypto.randomBytes(8).toString('hex')};
123 state.source_db=`lifeguide_roles_source_${state.run}`;
124 state.target_db=`lifeguide_roles_target_${state.run}`;
125 state.created=[];
126 await fs.writeFile(statePath,JSON.stringify(state),{mode:0o600,flag:'wx'});
127 for(const database of [state.source_db,state.target_db]) {
128 await admin.query(`CREATE DATABASE ${ident(database)}`);
129 state.created.push(database);
130 await fs.writeFile(statePath,JSON.stringify(state),{mode:0o600});
131 await admin.query(`COMMENT ON DATABASE ${ident(database)} IS 'LifeGuide synthetic role acceptance ${state.run}'`);
132 const db=new pg.Client({...adminConfig,database}); await db.connect();
133 try {
134 if(database===state.target_db) {
135 await admin.query(`ALTER DATABASE ${ident(database)} OWNER TO lifeguide_api`);
136 try {
137 await assert.rejects(prepareRoles(db),/must not own any database/);
138 // Also verify an API-owned OTHER database blocks source provisioning.
139 const other=new pg.Client({...adminConfig,database:state.source_db}); await other.connect();
140 try { await assert.rejects(prepareRoles(other),/must not own any database/); } finally { await other.end(); }
141 assert.equal((await admin.query('SELECT pg_get_userbyid(datdba) owner FROM pg_database WHERE datname=$1',[database])).rows[0].owner,roleNames.api);
142 } finally { await admin.query(`ALTER DATABASE ${ident(database)} OWNER TO ${ident(adminConfig.user)}`); }
143 await admin.query(`ALTER DATABASE ${ident(database)} OWNER TO lifeguide_migrator`);
144 try { await assert.rejects(prepareRoles(db),/must not own any database/); }
145 finally { await admin.query(`ALTER DATABASE ${ident(database)} OWNER TO ${ident(adminConfig.user)}`); }
146 await db.query('CREATE SCHEMA runtime_owned_probe AUTHORIZATION lifeguide_api');
147 try { await assert.rejects(prepareRoles(db),/ownership outside granted application data access is forbidden/); }
148 finally { await db.query('DROP SCHEMA runtime_owned_probe'); }
149 await db.query('CREATE SCHEMA backup_object_probe');
150 await db.query('CREATE TABLE backup_object_probe.fixture(id integer)');
151 await db.query('ALTER TABLE backup_object_probe.fixture OWNER TO lifeguide_backup');
152 try { await assert.rejects(prepareRoles(db),/ownership outside granted application data access is forbidden/); }
153 finally { await db.query('DROP TABLE backup_object_probe.fixture'); await db.query('DROP SCHEMA backup_object_probe'); }
154 await db.query('CREATE SCHEMA pgfixture_probe');
155 try {
156 await db.query('GRANT CREATE ON SCHEMA pgfixture_probe TO PUBLIC');
157 await assert.rejects(prepareRoles(db),/Unknown non-system schema/);
158 await db.query('REVOKE CREATE ON SCHEMA pgfixture_probe FROM PUBLIC');
159 await db.query('GRANT CREATE ON SCHEMA pgfixture_probe TO lifeguide_api');
160 await assert.rejects(prepareRoles(db),/Unknown non-system schema/);
161 await db.query('REVOKE CREATE ON SCHEMA pgfixture_probe FROM lifeguide_api');
162 await db.query('GRANT USAGE ON SCHEMA pgfixture_probe TO PUBLIC');
163 await db.query("CREATE FUNCTION pgfixture_probe.privileged_probe() RETURNS integer LANGUAGE SQL SECURITY DEFINER AS 'SELECT 1'");
164 await assert.rejects(prepareRoles(db),/Unknown non-system schema/);
165 await db.query('DROP FUNCTION pgfixture_probe.privileged_probe()');
166 } finally { await db.query('DROP SCHEMA pgfixture_probe'); }
167 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');
168 }
169 await prepareRoles(db);
170 } finally { await db.end(); }
171 }
172 await migrate(state.source_db); await migrate(state.source_db);
173 const source=new pg.Client({...adminConfig,database:state.source_db}); await source.connect();
174 try {
175 await reconcileGrants(source);
176 await source.query(await fs.readFile(new URL('./restore-smoke.sql',import.meta.url),'utf8').then(text=>text.replace(/^\\set.*$/gm,'')));
177 const fixture=process.env.DB_ROLE_RESTORE_FIXTURE ?? fileURLToPath(new URL('../../deployment/restore-fixture.sql',import.meta.url));
178 await source.query(await fs.readFile(fixture,'utf8').then(text=>text.replace(/^\\set.*$/gm,'')));
179 } finally { await source.end(); }
180 await checkPolicy(state.source_db);
181 const url=new URL('postgresql://localhost'); url.hostname=adminConfig.host; url.port=String(adminConfig.port);
182 url.pathname=`/${state.source_db}`; url.username=roleNames.api; url.password=process.env.API_DB_PASSWORD;
183 const fixtureUrl=new URL(url); fixtureUrl.username=roleNames.migrator; fixtureUrl.password=process.env.MIGRATOR_DB_PASSWORD;
184 const env={...process.env,TEST_FIXTURE_DATABASE_URL:fixtureUrl.toString(),DATABASE_URL:url.toString(),PGUSER:roleNames.api,PGPASSWORD:process.env.API_DB_PASSWORD,PGDATABASE:state.source_db,
185 JWT_SECRET:'synthetic-runtime-route-secret-at-least-32-characters',
186 SMS_PROVIDER:'disabled',EMAIL_PROVIDER:'disabled',ENABLE_SENSITIVE_FEATURES:'false'};
187 for(const key of ['SMS_PROVIDER_URL','SMS_PROVIDER_TOKEN','EMAIL_FROM','RESEND_API_KEY','SMTP_HOST','SMTP_USER','SMTP_PASSWORD',
188 'AI_API_KEY','AI_BASE_URL','AI_MODEL','OPENAI_API_KEY']) env[key]='';
189 for(const key of ['API_DB_PASSWORD','MIGRATOR_DB_PASSWORD','BACKUP_DB_PASSWORD','POSTGRES_PASSWORD']) delete env[key];
190 const familyEnv={...env};delete familyEnv.TEST_FIXTURE_DATABASE_URL;
191 // These new identity tests must use the runtime role directly. The broader
192 // catalog suite below uses a separate migrator only for fixture setup.
193 const family=spawnSync(process.execPath,['--test','--test-concurrency=1','tests/online_acceptance.test.js',
194 'tests/child_identity.test.js','tests/managed_child_server.test.js','tests/planner_series.test.js'],{cwd:backend,env:familyEnv,stdio:'inherit'});
195 assert.equal(family.status,0,'Runtime-role family HTTP/DB acceptance failed');
196 const acceptance=spawnSync(process.execPath,['--test',
197 'tests/learning_library.test.js','tests/learning_feedback.test.js','tests/learning_assessment.test.js',
198 'tests/content_review.test.js','tests/content_review_validation.test.js',
199 'tests/learning_goal_mutations.test.js','tests/family_lifecycle.test.js','tests/family_lifecycle_validation.test.js',
200 'tests/school_lifecycle.test.js','tests/report_periods.test.js','tests/learning_unit_locator.test.js'],{cwd:backend,env,stdio:'inherit'});
201 assert.equal(acceptance.status,0,'Real family/learning HTTP/DB acceptance with runtime role failed');
202 console.log('PASS role acceptance source: fresh checksum migrations + repeat, restrictive SQL capabilities and runtime family/learning/goals/school/report/locator HTTP scenarios');
203 console.log(`Synthetic restore state saved; source=${state.source_db}; target=${state.target_db}`);
204 } else {
205 state=await readState();
206 if(mode==='--verify-restored') {
207 assert.ok(await taggedDatabase(state.target_db));
208 const target=new pg.Client({...adminConfig,database:state.target_db}); await target.connect();
209 try {
210 await reconcileGrants(target);
211 assert.equal((await target.query("SELECT count(*)::int n FROM schema_migration WHERE sha256 IS NOT NULL")).rows[0].n,expectedMigrations.length);
212 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);
213 assert.equal((await target.query("SELECT pg_get_userbyid(extowner) owner FROM pg_extension WHERE extname='pgcrypto'")).rows[0].owner,roleNames.migrator);
214 } finally { await target.end(); }
215 await migrate(state.target_db); await checkPolicy(state.target_db);
216 const runtime=clientFor(state.target_db,'api'); await runtime.connect();
217 try {
218 assert.equal((await runtime.query("SELECT count(*)::int n FROM app_user WHERE identity_subject='restore-smoke'")).rows[0].n,1);
219 assert.equal((await runtime.query("SELECT count(*)::int n FROM profile WHERE display_name='Restore Smoke'")).rows[0].n,1);
220 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);
221 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);
222 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);
223 } finally { await runtime.end(); }
224 console.log('PASS restored checksum ledger entries, migrator ownership/repeat, runtime denial matrix, guardian/private policy and paused-study600seconds');
225 } else {
226 for(const database of state.created ?? []) {
227 assert.ok([state.source_db,state.target_db].includes(database),'Refusing unrelated cleanup');
228 if(await taggedDatabase(database)) {
229 await admin.query(`DROP DATABASE ${ident(database)}`);
230 }
231 }
232 console.log('PASS cleanup: only tagged newly-created role-test databases dropped; application DB preserved');
233 }
234 }
235 } finally { await admin.end(); }