LifeMate — Personal, Family & Learning Companion

test/personal-recovery-acceptance
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
py 424 lines 21.4 KB
Raw
1 """Synthetic-only SQLite portability and refusal checks; never open owner data."""
2 import copy
3 import hashlib
4 import importlib
5 import importlib.util
6 import json
7 from pathlib import Path
8 import re
9 import sqlite3
10 import tempfile
11 import unittest
12 from unittest import mock
13
14 from scripts.personal_recovery import files
15 from scripts.personal_recovery.common import (
16 FIXTURE_APPLICATION_ID, MAX_PAYLOAD_BYTES, MAX_ROWS, RecoveryError,
17 )
18
19 ROOT = Path(__file__).resolve().parents[2]
20 P = '11111111-1111-4111-8111-111111111111'
21 A = '22222222-2222-4222-8222-222222222222'
22 B = '33333333-3333-4333-8333-333333333333'
23 O = '44444444-4444-4444-8444-444444444444'
24
25
26 def fixture_connection(path, *, marked=True):
27 """Use the actual application's DDL, independently of the new exporter."""
28 connection = sqlite3.connect(path)
29 source = (ROOT / 'apps/lifemate/lib/standalone/store.dart').read_text()
30 for sql in re.findall(r"'''(CREATE TABLE .*?)'''", source, re.DOTALL):
31 connection.execute(sql)
32 connection.execute('CREATE INDEX local_occurrences_date ON local_occurrences(occurrence_date)')
33 connection.execute('PRAGMA user_version = 1')
34 if marked:
35 connection.execute(f'PRAGMA application_id = {FIXTURE_APPLICATION_ID}')
36 connection.execute('INSERT INTO local_profiles VALUES (1,?,?,?,?,?)',
37 (P, 'Fictional آزمایشی', 'girl_minor', 'Fictional همراه', 'mint'))
38 connection.execute('INSERT INTO local_plans VALUES (?,?,?,?,?,?,?,?,?,?,?)',
39 (A, P, 'Fictional weekly', 'routine', 'weekly', '2024-01-01',
40 '2024-02-29', 400, 500, 30, 1))
41 connection.execute('INSERT INTO local_plans VALUES (?,?,?,?,?,?,?,?,?,?,?)',
42 (B, P, 'Fictional one-off', 'event', 'once', '2024-02-29',
43 None, 0, 1440, None, 0))
44 connection.executemany('INSERT INTO local_weekly_slots VALUES (?,?,?,?)',
45 [(A, 7, 700, 750), (A, 1, 600, 630)])
46 connection.execute('INSERT INTO local_occurrences VALUES (?,?,?,?,?,?,?,?,?,?)',
47 (O, A, '2024-01-01', 'Fictional edited independent title',
48 'task', 800, 900, 1, 1, 0))
49 connection.commit()
50 return connection
51
52
53 class SnapshotTests(unittest.TestCase):
54 def setUp(self):
55 self.directory = tempfile.TemporaryDirectory()
56 self.addCleanup(self.directory.cleanup)
57 self.path = Path(self.directory.name) / 'fictional.sqlite'
58 connection = fixture_connection(self.path)
59 connection.close()
60 self.assertIsNotNone(importlib.util.find_spec('scripts.personal_recovery.snapshot'),
61 'snapshot module is required')
62 self.module = importlib.import_module('scripts.personal_recovery.snapshot')
63
64 def document(self):
65 return json.loads(self.module.export_fixture(self.path))
66
67 def reject_document(self, document):
68 with self.assertRaises(RecoveryError):
69 self.module.database_from_snapshot(json.dumps(document).encode())
70
71 def test_exact_roundtrip_all_fields_and_source_digest(self):
72 before = hashlib.sha256(self.path.read_bytes()).hexdigest()
73 payload = self.module.export_fixture(self.path)
74 self.assertEqual(hashlib.sha256(self.path.read_bytes()).hexdigest(), before)
75 self.assertEqual(sorted(p.name for p in self.path.parent.iterdir()), ['fictional.sqlite'])
76 document = json.loads(payload)
77 self.assertEqual(set(document), {'format', 'schemaVersion', 'syntheticOnly', 'tables'})
78 self.assertEqual(document['format'], 'LifeGuideSyntheticRecovery')
79 self.assertIs(document['syntheticOnly'], True)
80 self.assertEqual(document['schemaVersion'], 1)
81 self.assertEqual(document['tables']['local_occurrences'][0]['title'],
82 'Fictional edited independent title')
83 self.assertEqual([s['weekday'] for s in document['tables']['local_weekly_slots']], [1, 7])
84 self.assertEqual(payload, json.dumps(document, ensure_ascii=False, sort_keys=True,
85 separators=(',', ':'), allow_nan=False).encode())
86 restored = self.path.parent / 'restored.sqlite'
87 restored.write_bytes(self.module.database_from_snapshot(payload))
88 self.assertEqual(self.module.export_fixture(restored), payload)
89 with sqlite3.connect(self.path) as original, sqlite3.connect(restored) as result:
90 for table in document['tables']:
91 self.assertEqual(sorted(original.execute(f'SELECT * FROM {table}').fetchall()),
92 sorted(result.execute(f'SELECT * FROM {table}').fetchall()))
93 self.assertEqual(result.execute('PRAGMA integrity_check').fetchall(), [('ok',)])
94 self.assertEqual(result.execute('PRAGMA foreign_key_check').fetchall(), [])
95
96 def test_sample_has_fictional_past_rows_for_all_recurrences_and_independent_state(self):
97 self.path.write_bytes(self.module.create_sample_database())
98 tables = self.document()['tables']
99 self.assertEqual({p['recurrence'] for p in tables['local_plans']},
100 {'once', 'daily', 'everyTwoDays', 'weekly'})
101 self.assertEqual({p['kind'] for p in tables['local_plans']}, {'task', 'event', 'routine'})
102 self.assertTrue(all(p['start_date'].startswith('2024-') for p in tables['local_plans']))
103 self.assertTrue(all('Fictional' in p['title'] for p in tables['local_plans']))
104 self.assertTrue(any(o['completed'] and o['archived'] for o in tables['local_occurrences']))
105 self.assertTrue(any(p['archived'] for p in tables['local_plans']))
106 plans = {p['id']: p for p in tables['local_plans']}
107 self.assertTrue(any(o['title'] != plans[o['plan_id']]['title']
108 for o in tables['local_occurrences']))
109
110 def test_marker_checked_before_any_schema_or_content_query(self):
111 with sqlite3.connect(self.path) as connection:
112 connection.execute('PRAGMA application_id = 0')
113 real_connect = sqlite3.connect
114 queries = []
115
116 def traced_connect(*args, **kwargs):
117 connection = real_connect(*args, **kwargs)
118 connection.set_trace_callback(queries.append)
119 return connection
120
121 with mock.patch.object(self.module.sqlite3, 'connect', side_effect=traced_connect):
122 with self.assertRaises(RecoveryError):
123 self.module.export_fixture(self.path)
124 self.assertEqual(queries, [])
125 with real_connect(self.path) as connection:
126 connection.execute(f'PRAGMA application_id = {FIXTURE_APPLICATION_ID}')
127 with mock.patch.object(self.module.sqlite3, 'connect', side_effect=traced_connect):
128 self.module.export_fixture(self.path)
129 marker = next(index for index, query in enumerate(queries) if query == 'PRAGMA application_id')
130 first_select = next(index for index, query in enumerate(queries) if 'SELECT' in query.upper())
131 self.assertLess(marker, first_select)
132
133 def test_marker_is_safety_gate_not_authentication(self):
134 self.assertIn('not authentication', self.module.__doc__)
135
136 def test_unknown_version_refused_without_source_change(self):
137 with sqlite3.connect(self.path) as connection:
138 connection.execute('PRAGMA user_version = 2')
139 before = self.path.read_bytes()
140 with self.assertRaises(RecoveryError):
141 self.module.export_fixture(self.path)
142 self.assertEqual(before, self.path.read_bytes())
143
144 def test_extra_sql_objects_or_modified_schema_refused(self):
145 cases = [
146 'CREATE TABLE unexpected (secret TEXT)',
147 'CREATE VIEW unexpected AS SELECT * FROM local_profiles',
148 'CREATE TRIGGER unexpected AFTER INSERT ON local_plans BEGIN DELETE FROM local_profiles; END',
149 'CREATE INDEX unexpected ON local_profiles(display_name)',
150 'ALTER TABLE local_profiles ADD COLUMN unexpected TEXT',
151 ]
152 for sql in cases:
153 with self.subTest(sql=sql):
154 path = self.path.parent / 'modified.sqlite'
155 path.write_bytes(self.path.read_bytes())
156 with sqlite3.connect(path) as connection:
157 connection.execute(sql)
158 with self.assertRaises(RecoveryError):
159 self.module.export_fixture(path)
160
161 def test_android_metadata_optional_and_never_exported(self):
162 expected = self.module.export_fixture(self.path)
163 with sqlite3.connect(self.path) as connection:
164 connection.execute('CREATE TABLE android_metadata (locale TEXT)')
165 connection.execute("INSERT INTO android_metadata VALUES ('fictional_locale')")
166 self.assertEqual(self.module.export_fixture(self.path), expected)
167 with sqlite3.connect(self.path) as connection:
168 connection.execute('ALTER TABLE android_metadata ADD COLUMN extra TEXT')
169 with self.assertRaises(RecoveryError):
170 self.module.export_fixture(self.path)
171
172 def test_invalid_database_types_and_dates_refused(self):
173 for sql in ["UPDATE local_plans SET start_date='2024-02-30'",
174 "UPDATE local_plans SET id='xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' WHERE title='Fictional weekly'",
175 "UPDATE local_plans SET start_minute='secret invalid value'",
176 "UPDATE local_occurrences SET plan_id='99999999-9999-4999-8999-999999999999'"]:
177 with self.subTest(sql=sql):
178 path = self.path.parent / 'invalid.sqlite'
179 path.write_bytes(self.path.read_bytes())
180 with sqlite3.connect(path) as connection:
181 connection.execute('PRAGMA ignore_check_constraints = ON')
182 connection.execute(sql)
183 with self.assertRaises(RecoveryError) as error:
184 self.module.export_fixture(path)
185 self.assertNotIn('secret', str(error.exception))
186
187 def test_nonexistent_corrupt_and_symlink_sources_refused(self):
188 for path in [self.path.parent / 'missing', self.path.parent / 'corrupt',
189 self.path.parent / 'symlink']:
190 if path.name == 'corrupt':
191 path.write_bytes(b'fictional not sqlite')
192 if path.name == 'symlink':
193 path.symlink_to(self.path)
194 with self.subTest(path=path.name), self.assertRaises(RecoveryError):
195 self.module.export_fixture(path)
196 self.assertFalse((self.path.parent / 'missing').exists())
197
198 def test_source_symlink_swap_refused_before_sqlite_content_read(self):
199 replacement = self.path.parent / 'replacement.sqlite'
200 saved_original = self.path.parent / 'original.sqlite'
201 replacement.write_bytes(self.path.read_bytes())
202 with sqlite3.connect(replacement) as connection:
203 connection.execute("UPDATE local_profiles SET display_name='Fictional swap canary'")
204 original_hash = hashlib.sha256(self.path.read_bytes()).hexdigest()
205 replacement_hash = hashlib.sha256(replacement.read_bytes()).hexdigest()
206 real_lstat = Path.lstat
207 real_connect = sqlite3.connect
208 queries = []
209 swapped = False
210
211 def swapping_lstat(candidate, *args, **kwargs):
212 nonlocal swapped
213 info = real_lstat(candidate, *args, **kwargs)
214 if candidate == self.path and not swapped:
215 swapped = True
216 self.path.rename(saved_original)
217 self.path.symlink_to(replacement)
218 return info
219
220 def traced_connect(*args, **kwargs):
221 connection = real_connect(*args, **kwargs)
222 connection.set_trace_callback(queries.append)
223 return connection
224
225 with mock.patch.object(Path, 'lstat', new=swapping_lstat), \
226 mock.patch.object(self.module.sqlite3, 'connect', side_effect=traced_connect):
227 with self.assertRaises(RecoveryError):
228 self.module.export_fixture(self.path)
229 self.assertTrue(swapped)
230 self.assertFalse(any('SELECT' in query.upper() for query in queries), queries)
231 self.assertEqual(hashlib.sha256(saved_original.read_bytes()).hexdigest(), original_hash)
232 self.assertEqual(hashlib.sha256(replacement.read_bytes()).hexdigest(), replacement_hash)
233
234 def test_unmarked_and_future_schema_headers_refused_before_body_read(self):
235 original = self.path.read_bytes()
236 cases = [(68, b'\x00\x00\x00\x00', 'synthetic_marker_required'),
237 (60, b'\x00\x00\x00\x02', 'unsupported_schema')]
238 for offset, changed, code in cases:
239 with self.subTest(code=code):
240 modified = original[:offset] + changed + original[offset + 4:]
241 self.path.write_bytes(modified)
242 before = hashlib.sha256(modified).hexdigest()
243 real_fdopen = files.os.fdopen
244 reads = []
245
246 class ObservedStream:
247 def __init__(self, stream):
248 self.stream = stream
249
250 def __enter__(self):
251 return self
252
253 def __exit__(self, *args):
254 self.stream.close()
255
256 def read(self, size=-1):
257 chunk = self.stream.read(size)
258 reads.append(len(chunk))
259 return chunk
260
261 def observed_fdopen(*args, **kwargs):
262 return ObservedStream(real_fdopen(*args, **kwargs))
263
264 with mock.patch.object(files.os, 'fdopen', side_effect=observed_fdopen), \
265 mock.patch.object(self.module.sqlite3, 'connect') as connection:
266 with self.assertRaises(RecoveryError) as error:
267 self.module.export_fixture(self.path)
268 self.assertEqual(reads, [100])
269 self.assertEqual(error.exception.code, code)
270 connection.assert_not_called()
271 self.assertEqual(hashlib.sha256(self.path.read_bytes()).hexdigest(), before)
272
273 def test_cold_wal_headers_refused_before_sqlite_open(self):
274 original = self.path.read_bytes()
275 real_connect = sqlite3.connect
276 calls = []
277
278 def recording_connect(*args, **kwargs):
279 calls.append(args[0])
280 return real_connect(*args, **kwargs)
281
282 for versions in [b'\x02\x02', b'\x01\x02', b'\x02\x01']:
283 with self.subTest(versions=versions):
284 modified = original[:18] + versions + original[20:]
285 self.path.write_bytes(modified)
286 calls.clear()
287 with mock.patch.object(self.module.sqlite3, 'connect', side_effect=recording_connect):
288 with self.assertRaises(RecoveryError):
289 self.module.export_fixture(self.path)
290 self.assertEqual(calls, [])
291 self.assertEqual(self.path.read_bytes(), modified)
292
293 def test_active_sidecars_refused(self):
294 for suffix in ['-wal', '-shm', '-journal']:
295 sidecar = Path(str(self.path) + suffix)
296 sidecar.write_bytes(b'fictional')
297 with self.subTest(suffix=suffix), self.assertRaises(RecoveryError):
298 self.module.export_fixture(self.path)
299 sidecar.unlink()
300
301 def test_strict_json_and_top_level_contract(self):
302 for raw in [b'{}', b'[]', b'null', b'\xff', b'{', b'{"format":1,"format":2}',
303 b'{"x":NaN}', b'{"x":Infinity}', b'[' * 1100]:
304 with self.subTest(raw=raw[:30]), self.assertRaises(RecoveryError):
305 self.module.database_from_snapshot(raw)
306 document = self.document()
307 for key, value in [('schemaVersion', True), ('schemaVersion', 2),
308 ('syntheticOnly', 1), ('syntheticOnly', False),
309 ('format', 'unknown'), ('extra', 'forbidden')]:
310 changed = copy.deepcopy(document)
311 changed[key] = value
312 with self.subTest(key=key, value=value):
313 self.reject_document(changed)
314 raw = self.module.export_fixture(self.path).decode()
315 raw = raw.replace('"singleton":1', '"singleton":1,"singleton":1')
316 with self.assertRaises(RecoveryError):
317 self.module.database_from_snapshot(raw.encode())
318
319 def test_unknown_missing_tables_rows_and_columns_refused(self):
320 document = self.document()
321 changes = []
322 extra = copy.deepcopy(document)
323 extra['tables']['android_metadata'] = []
324 changes.append(extra)
325 missing = copy.deepcopy(document)
326 del missing['tables']['local_plans']
327 changes.append(missing)
328 for value in [{}, None, ['wrong']]:
329 changed = copy.deepcopy(document)
330 changed['tables']['local_plans'] = value
331 changes.append(changed)
332 for remove in [False, True]:
333 changed = copy.deepcopy(document)
334 row = changed['tables']['local_plans'][0]
335 if remove:
336 del row['title']
337 else:
338 row['extra'] = 'forbidden'
339 changes.append(changed)
340 for changed in changes:
341 with self.subTest(changed=changes.index(changed)):
342 self.reject_document(changed)
343
344 def test_invalid_scalar_values_refused(self):
345 document = self.document()
346 cases = [
347 ('local_profiles', 'singleton', True), ('local_profiles', 'singleton', 0),
348 ('local_profiles', 'id', 'not-a-uuid'),
349 ('local_profiles', 'id', P.upper().replace('11111111', 'AAAAAAAA', 1)),
350 ('local_profiles', 'category', 'child'), ('local_profiles', 'theme_key', 'unknown'),
351 ('local_profiles', 'display_name', ' '), ('local_profiles', 'display_name', 'a' * 81),
352 ('local_profiles', 'companion_name', 'a' * 41),
353 ('local_profiles', 'display_name', '\x00'),
354 ('local_plans', 'title', 'a' * 201), ('local_plans', 'title', 42),
355 ('local_plans', 'kind', 'other'), ('local_plans', 'recurrence', 'monthly'),
356 ('local_plans', 'start_date', '2024-02-30'), ('local_plans', 'start_date', '2024-1-01'),
357 ('local_plans', 'start_date', '0000-01-01'),
358 ('local_plans', 'until_date', '2023-12-31'),
359 ('local_plans', 'start_minute', True), ('local_plans', 'start_minute', 1.0),
360 ('local_plans', 'start_minute', '1'), ('local_plans', 'start_minute', -1),
361 ('local_plans', 'end_minute', 1441), ('local_plans', 'end_minute', 400),
362 ('local_plans', 'archived', 2), ('local_plans', 'reminder_minutes', 20),
363 ('local_weekly_slots', 'weekday', 8), ('local_weekly_slots', 'weekday', False),
364 ('local_weekly_slots', 'end_minute', 1),
365 ('local_occurrences', 'completed', True), ('local_occurrences', 'archived', -1),
366 ('local_occurrences', 'occurrence_date', '2023-02-29'),
367 ('local_occurrences', 'reminder_minutes', 1),
368 ]
369 for table, key, value in cases:
370 with self.subTest(table=table, key=key, value=value):
371 changed = copy.deepcopy(document)
372 changed['tables'][table][0][key] = value
373 self.reject_document(changed)
374
375 def test_duplicate_primary_and_unique_keys_refused(self):
376 document = self.document()
377 for table in document['tables']:
378 changed = copy.deepcopy(document)
379 changed['tables'][table].append(copy.deepcopy(changed['tables'][table][0]))
380 with self.subTest(table=table):
381 self.reject_document(changed)
382 changed = copy.deepcopy(document)
383 occurrence = copy.deepcopy(changed['tables']['local_occurrences'][0])
384 occurrence['id'] = '55555555-5555-4555-8555-555555555555'
385 changed['tables']['local_occurrences'].append(occurrence)
386 self.reject_document(changed)
387
388 def test_foreign_keys_and_weekly_recurrence_links_refused(self):
389 document = self.document()
390 for table, key in [('local_plans', 'profile_id'),
391 ('local_occurrences', 'plan_id'), ('local_weekly_slots', 'plan_id')]:
392 changed = copy.deepcopy(document)
393 changed['tables'][table][0][key] = O
394 with self.subTest(table=table):
395 self.reject_document(changed)
396 changed = copy.deepcopy(document)
397 changed['tables']['local_weekly_slots'] = []
398 self.reject_document(changed)
399 changed = copy.deepcopy(document)
400 changed['tables']['local_plans'][0]['recurrence'] = 'daily'
401 self.reject_document(changed)
402
403 def test_payload_and_row_limits(self):
404 with self.assertRaises(RecoveryError):
405 self.module.database_from_snapshot(b' ' * (MAX_PAYLOAD_BYTES + 1))
406 changed = self.document()
407 changed['tables']['local_occurrences'] = [changed['tables']['local_occurrences'][0]] * (MAX_ROWS + 1)
408 self.reject_document(changed)
409 with self.path.open('ab') as stream:
410 stream.truncate(MAX_PAYLOAD_BYTES + 1)
411 with self.assertRaises(RecoveryError):
412 self.module.export_fixture(self.path)
413
414 def test_empty_v1_database_roundtrips(self):
415 with sqlite3.connect(self.path) as connection:
416 for table in ['local_occurrences', 'local_weekly_slots', 'local_plans', 'local_profiles']:
417 connection.execute(f'DELETE FROM {table}')
418 payload = self.module.export_fixture(self.path)
419 self.path.write_bytes(self.module.database_from_snapshot(payload))
420 self.assertTrue(all(not rows for rows in self.document()['tables'].values()))
421
422
423 if __name__ == '__main__':
424 unittest.main()