LifeMate — Personal, Family & Learning Companion

docs/offline-data-rescue-options
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 244 lines 14.3 KB
Raw
1 import test, { after } from 'node:test';
2 import assert from 'node:assert/strict';
3 import crypto from 'node:crypto';
4 import { spawn } from 'node:child_process';
5 import { once } from 'node:events';
6 import net from 'node:net';
7 import pg from 'pg';
8 import { pruneExpiredAuthRateLimits } from '../src/auth_rate_limit.js';
9
10 const fixtureUrl = process.env.TEST_FIXTURE_DATABASE_URL ?? process.env.DATABASE_URL;
11 assert.ok(fixtureUrl, 'Auth IP tests require migrated synthetic PostgreSQL');
12 const database = new URL(fixtureUrl);
13 assert.ok(['localhost', '127.0.0.1', '[::1]', '::1'].includes(database.hostname), 'Only loopback PostgreSQL allowed');
14 assert.ok(['/lifeguide_library_test', '/lifeguide_contentops_test', '/lifemate_ci'].includes(database.pathname) ||
15 /^\/lifeguide_roles_source_[a-f0-9]{16}$/.test(database.pathname), 'Only synthetic test databases allowed');
16 const pool = new pg.Pool({ connectionString: fixtureUrl });
17 const processes = new Set();
18 const secret = `synthetic-auth-ip-key-${crypto.randomUUID()}`;
19 const fixtureIps = new Set(['127.0.0.1']);
20
21 async function start({ trusted = '127.0.0.1/32', connectionString = fixtureUrl, quota = 3, sessionQuota = 5, windowSeconds = 600 } = {}) {
22 const reservation = net.createServer().listen(0, '127.0.0.1');
23 await once(reservation, 'listening');
24 const port = reservation.address().port;
25 await new Promise(resolve => reservation.close(resolve));
26 const env = { ...process.env, DATABASE_URL: connectionString, NODE_ENV: 'production', PORT: String(port),
27 JWT_SECRET: secret, LOG_REQUESTS: 'false', TRUSTED_PROXY_CIDRS: trusted, CORS_ORIGINS: '',
28 RATE_LIMIT_AUTH_MAX: String(quota), RATE_LIMIT_AUTH_WINDOW_SECONDS: String(windowSeconds),
29 RATE_LIMIT_SESSION_MAX: String(sessionQuota), RATE_LIMIT_SESSION_WINDOW_SECONDS: String(windowSeconds),
30 RATE_LIMIT_GENERAL_MAX: '2000', SMS_PROVIDER: 'disabled', SMS_PROVIDER_URL: '', SMS_PROVIDER_TOKEN: '',
31 KAVENEGAR_API_KEY: '', EMAIL_FROM: '', RESEND_API_KEY: '', SMTP_HOST: '', SMTP_USER: '', SMTP_PASSWORD: '',
32 AI_API_KEY: '', AI_BASE_URL: '', AI_MODEL: '', OPENAI_API_KEY: '', ENABLE_SENSITIVE_FEATURES: 'false' };
33 delete env.TEST_FIXTURE_DATABASE_URL;
34 delete env.AUTH_RATE_LIMIT_KEY;
35 const child = spawn(process.execPath, ['src/entrypoint.js'], { cwd: new URL('../', import.meta.url),
36 env, stdio: ['ignore', 'pipe', 'pipe'] });
37 processes.add(child);
38 child.stderr.on('data', () => {});
39 await new Promise((resolve, reject) => {
40 let output = '';
41 const timer = setTimeout(() => reject(new Error('Auth IP fixture startup timed out')), 10000);
42 child.stdout.on('data', chunk => {
43 output += chunk;
44 if (output.includes('"type":"startup"')) { clearTimeout(timer); resolve(); }
45 });
46 child.once('error', () => { clearTimeout(timer); reject(new Error('Auth IP fixture process failed')); });
47 child.once('exit', () => {
48 if (!output.includes('"type":"startup"')) { clearTimeout(timer); reject(new Error('Auth IP fixture exited before startup')); }
49 });
50 });
51 return { child, url: `http://127.0.0.1:${port}` };
52 }
53
54 async function stop(service) {
55 const child = service.child;
56 if (child.exitCode === null && child.signalCode === null) {
57 const closed = once(child, 'close'); child.kill('SIGTERM'); await closed;
58 }
59 processes.delete(child);
60 }
61
62 async function request(service, path = '/v1/auth/login', { ip = '192.0.2.11', method = 'POST', headers = {} } = {}) {
63 fixtureIps.add(ip);
64 const response = await fetch(service.url + path, { method,
65 headers: { 'content-type': 'application/json', 'x-forwarded-for': ip, ...headers },
66 ...(['GET', 'HEAD', 'OPTIONS'].includes(method) ? {} : { body: '{}' }) });
67 const raw = await response.text();
68 return { status: response.status, headers: response.headers,
69 body: raw && response.headers.get('content-type')?.includes('application/json') ? JSON.parse(raw) : null };
70 }
71
72 after(async () => {
73 await Promise.all([...processes].map(child => stop({ child })));
74 try {
75 // These are test-owned HMACs only; never delete another test/API's bucket.
76 const digests = [...fixtureIps].map(ip => crypto.createHmac('sha256', secret)
77 .update('lifeguide:auth-ip:v1\0').update(ip).digest('hex'));
78 await pool.query('delete from auth_ip_rate_limit where client_digest=any($1::text[])', [digests]);
79 } catch (error) { if (error.code !== '42P01') throw error; }
80 finally { await pool.end(); }
81 });
82
83 test('auth quota is shared atomically between API instances and survives process restart', async () => {
84 const first = await start(), second = await start();
85 // Syntactically valid forwarding data is accepted only from the explicitly
86 // trusted loopback gateway. No real account/contact is involved.
87 const results = await Promise.all(Array.from({ length: 8 }, (_, index) => request(index % 2 ? first : second)));
88 assert.deepEqual(results.map(result => result.status).sort(), [401, 401, 401, 429, 429, 429, 429, 429],
89 'Two processes must share one atomic quota, not each allow three requests');
90 for (const result of results) assert.equal(result.headers.get('RateLimit-Limit'), '3');
91 const limited = results.find(result => result.status === 429);
92 assert.equal(limited.body.error, 'rate_limited');
93 const retry = Number(limited.headers.get('Retry-After'));
94 const clock = (await pool.query('select extract(epoch from statement_timestamp())::bigint n')).rows[0].n;
95 const expected = 600 - (Number(clock) % 600);
96 assert.ok(Number.isInteger(retry) && retry > 0 && retry <= 600 && Math.abs(retry - expected) <= 2);
97 await stop(first); await stop(second);
98 const restarted = await start();
99 assert.equal((await request(restarted)).status, 429, 'Restart must not reset auth abuse protection');
100 await stop(restarted);
101 });
102
103 test('strict and session budgets are separate, capability discovery and OPTIONS do not charge either', async () => {
104 const service = await start({ quota: 2, sessionQuota: 2 });
105 const options = { ip: '192.0.2.12' };
106 for (let index = 0; index < 4; index++) {
107 assert.equal((await request(service, '/v1/auth/capabilities', { ...options, method: 'GET' })).status, 200);
108 assert.equal((await request(service, '/v1/auth/login', { ...options, method: 'OPTIONS' })).status, 204);
109 }
110 assert.equal((await request(service, '/v1/auth/login', options)).status, 401);
111 assert.equal((await request(service, '/v1/auth/login', options)).status, 401);
112 assert.equal((await request(service, '/v1/auth/login', options)).status, 429);
113 assert.equal((await request(service, '/v1/auth/logout', options)).status, 204);
114 assert.equal((await request(service, '/v1/auth/logout', options)).status, 204);
115 assert.equal((await request(service, '/v1/auth/refresh', options)).status, 429);
116 for (const [method, path] of [
117 ['HEAD', '/v1/auth/capabilities'], ['POST', '/v1/auth/capabilities'],
118 ['GET', '/v1/auth/capabilities/'], ['GET', '/v1/auth/Capabilities'],
119 ['GET', '/V1/AUTH/capabilities'], ['POST', '/v1/auth/refresh/'], ['POST', '/v1/auth/refreshing'],
120 ]) assert.equal((await request(service, path, { ...options, method })).status, 429, `${method} ${path} stays strict`);
121 await stop(service);
122 });
123
124 test('untrusted forwarding headers cannot rotate a quota, and an explicitly pinned gateway separates clients', async () => {
125 const standalone = await start({ trusted: '', quota: 2 });
126 assert.equal((await request(standalone, '/v1/auth/login', { ip: '198.51.100.1' })).status, 401);
127 assert.equal((await request(standalone, '/v1/auth/login', { ip: '198.51.100.2' })).status, 401);
128 assert.equal((await request(standalone, '/v1/auth/login', { ip: '198.51.100.3', headers: {
129 forwarded: 'for=203.0.113.123', 'x-real-ip': '203.0.113.123',
130 } })).status, 429);
131 await stop(standalone);
132 const gateway = await start({ quota: 2 });
133 assert.equal((await request(gateway, '/v1/auth/login', { ip: '192.0.2.13' })).status, 401);
134 assert.equal((await request(gateway, '/v1/auth/login', { ip: '192.0.2.13' })).status, 401);
135 assert.equal((await request(gateway, '/v1/auth/login', { ip: '203.0.113.123, 192.0.2.13' })).status, 429);
136 assert.equal((await request(gateway, '/v1/auth/login', { ip: '192.0.2.14' })).status, 401);
137 await stop(gateway);
138 });
139
140 test('database failure closes auth with generic 503 while public discovery remains available', async () => {
141 const schema = `synthetic_auth_unavailable_${crypto.randomBytes(6).toString('hex')}`;
142 await pool.query(`create schema ${schema}`);
143 try {
144 const isolated = new URL(fixtureUrl);
145 isolated.searchParams.set('options', `-c search_path=${schema}`);
146 const service = await start({ connectionString: isolated.href });
147 const result = await request(service, '/v1/auth/login', { ip: '192.0.2.15' });
148 assert.equal(result.status, 503);
149 assert.deepEqual(result.body, { error: 'temporarily_unavailable' });
150 assert.equal(result.headers.get('Retry-After'), '5');
151 assert.equal((await request(service, '/v1/auth/capabilities', { method: 'GET' })).status, 200);
152 assert.equal((await request(service, '/live', { method: 'GET' })).status, 200);
153 await stop(service);
154 } finally { await pool.query(`drop schema ${schema}`); }
155 });
156
157 test('persisted buckets contain only HMAC metadata and the server-clock window expires', async () => {
158 const service = await start({ quota: 1, windowSeconds: 5 });
159 const options = { ip: '192.0.2.16' };
160 // Align against the actual PostgreSQL clock, not an injected fake clock.
161 // Keep both immediate calls away from a natural fixed-window rollover.
162 for (;;) {
163 const now = Number((await pool.query('select extract(epoch from clock_timestamp()) n')).rows[0].n);
164 if (now % 5 < 1) break;
165 await new Promise(resolve => setTimeout(resolve, 100));
166 }
167 assert.equal((await request(service, '/v1/auth/window-probe', options)).status, 401);
168 assert.equal((await request(service, '/v1/auth/window-probe', options)).status, 429);
169 const columns = (await pool.query(`select column_name from information_schema.columns
170 where table_schema=current_schema() and table_name='auth_ip_rate_limit' order by ordinal_position`)).rows.map(row => row.column_name);
171 assert.deepEqual(columns, ['quota_profile', 'client_digest', 'window_start', 'window_end', 'request_count']);
172 const rows = (await pool.query("select * from auth_ip_rate_limit where window_end-window_start=interval '5 seconds'")).rows;
173 assert.ok(rows.length > 0);
174 for (const row of rows) {
175 assert.match(row.client_digest, /^[a-f0-9]{64}$/);
176 assert.equal(JSON.stringify(row).includes(options.ip), false);
177 }
178 await new Promise(resolve => setTimeout(resolve, 5100));
179 assert.equal((await request(service, '/v1/auth/window-probe', options)).status, 401, 'New server-clock window receives a new quota');
180 await stop(service);
181 });
182
183 test('a request waiting for the shared lock samples its quota window after the wait', async () => {
184 const ip = '192.0.2.17', options = { ip };
185 // One second guarantees this controlled wait stays below the production
186 // two-second lock timeout, even when the request starts near a boundary.
187 const service = await start({ quota: 1, windowSeconds: 1 });
188 const digest = crypto.createHmac('sha256', secret).update('lifeguide:auth-ip:v1\0').update(ip).digest('hex');
189 assert.equal((await request(service, '/v1/auth/window-probe', options)).status, 401);
190 const client = await pool.connect();
191 let pending;
192 try {
193 await client.query('begin');
194 const pid = Number((await client.query('select pg_backend_pid() pid')).rows[0].pid);
195 await client.query("select pg_advisory_xact_lock(hashtextextended('lifeguide:auth-ip:auth:' || $1,0))", [digest]);
196 pending = request(service, '/v1/auth/window-probe', options);
197 let blocked = false;
198 for (let index = 0; index < 100; index++) {
199 blocked = (await pool.query('select exists(select 1 from pg_stat_activity where $1=any(pg_blocking_pids(pid))) blocked', [pid])).rows[0].blocked;
200 if (blocked) break;
201 await new Promise(resolve => setTimeout(resolve, 10));
202 }
203 assert.ok(blocked, 'Independent PostgreSQL confirms the API is waiting on the shared quota lock');
204 const waitMs = Number((await pool.query(`select greatest(0,extract(epoch from max(window_end)-clock_timestamp())*1000)::integer ms
205 from auth_ip_rate_limit where quota_profile='auth' and client_digest=$1`, [digest])).rows[0].ms);
206 await new Promise(resolve => setTimeout(resolve, waitMs + 100));
207 await client.query('commit');
208 assert.equal((await pending).status, 401, 'Expired pre-wait window must not reject a new-window request');
209 const windows = (await pool.query('select request_count from auth_ip_rate_limit where client_digest=$1 order by window_start', [digest])).rows;
210 assert.equal(windows.length, 2);
211 assert.ok(windows.every(row => Number(row.request_count) === 1));
212 } finally {
213 await client.query('rollback').catch(() => {});
214 client.release();
215 if (pending) await pending;
216 await stop(service);
217 }
218 });
219
220 test('explicit housekeeping is bounded and retains active quotas', async () => {
221 const schema = `synthetic_auth_cleanup_${crypto.randomBytes(6).toString('hex')}`;
222 await pool.query(`create schema ${schema}`);
223 await pool.query(`create table ${schema}.auth_ip_rate_limit (like auth_ip_rate_limit including all)`);
224 const isolated = new URL(fixtureUrl);
225 isolated.searchParams.set('options', `-c search_path=${schema}`);
226 const cleanupPool = new pg.Pool({ connectionString: isolated.href });
227 try {
228 await cleanupPool.query(`insert into auth_ip_rate_limit values
229 ('auth',$1,now()-interval '2 hours',now()-interval '1 hour',1),
230 ('session',$1,now()-interval '2 hours',now()-interval '1 hour',1),
231 ('auth',$1,now(),now()+interval '1 hour',1)`, ['a'.repeat(64)]);
232 assert.equal(await pruneExpiredAuthRateLimits(cleanupPool, 1), 1);
233 assert.equal(Number((await cleanupPool.query('select count(*) n from auth_ip_rate_limit')).rows[0].n), 2);
234 assert.equal(await pruneExpiredAuthRateLimits(cleanupPool, 1), 1);
235 assert.equal(await pruneExpiredAuthRateLimits(cleanupPool, 1), 0);
236 const remaining = (await cleanupPool.query('select window_end>statement_timestamp() active from auth_ip_rate_limit')).rows;
237 assert.deepEqual(remaining, [{ active: true }]);
238 await assert.rejects(pruneExpiredAuthRateLimits(cleanupPool, 501), /Invalid auth limiter cleanup batch/);
239 await assert.rejects(pruneExpiredAuthRateLimits(cleanupPool, 0), /Invalid auth limiter cleanup batch/);
240 } finally {
241 await cleanupPool.end();
242 await pool.query(`drop schema ${schema} cascade`);
243 }
244 });