LifeMate — Personal, Family & Learning Companion

feat/local-signing-preflight
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 425 lines 21.4 KB
Raw
1 """Host safety boundaries. Real emulator acceptance is a separate CI run."""
2 import hashlib
3 import json
4 from pathlib import Path
5 import sqlite3
6 import subprocess
7 import tempfile
8 import unittest
9 from unittest.mock import patch
10
11 import test_personal_recovery_android as subject
12
13
14 class FakeAdb:
15 def __init__(self):
16 self.calls = []
17 self.packages = ''
18 self.hardware = 'ranchu'
19 self.process = 'ABSENT'
20 self.sidecars = 'CLEAN'
21
22 def command(self, *parts, **kwargs):
23 self.calls.append(parts)
24 return 'device' if parts == ('get-state',) else 'Success\n'
25
26 def shell(self, *parts, **kwargs):
27 self.calls.append(parts)
28 if parts[0] == 'getprop':
29 return {'ro.kernel.qemu': '1', 'ro.boot.qemu': '1',
30 'ro.hardware': self.hardware, 'ro.product.name': 'sdk_gphone64_x86_64',
31 'ro.build.version.sdk': '35'}[parts[1]]
32 if parts[:3] == ('pm', 'list', 'packages'):
33 return self.packages
34 if parts[:2] == ('sh', '-c') and 'pidof ' in parts[2]:
35 return self.process
36 if parts[0] == 'run-as':
37 return self.sidecars
38 return ''
39
40
41 class RecoveryBoundaryTest(unittest.TestCase):
42 def setUp(self):
43 directory = tempfile.TemporaryDirectory()
44 self.addCleanup(directory.cleanup)
45 self.directory = Path(directory.name)
46 self.paths = [self.directory / name for name in ('original.apk', 'qa.apk', 'upgrade.apk')]
47 for path in self.paths:
48 path.write_bytes(b'host test apk')
49 self.adb = FakeAdb()
50
51 def make(self, **options):
52 defaults = dict(serial='emulator-5554', original_apk=self.paths[0],
53 qa_apk=self.paths[1], upgrade_apk=self.paths[2],
54 acknowledge=True, output=self.directory / 'receipt.json', adb=self.adb,
55 original_check=lambda _: {'result': 'PASS', 'package': subject.ORIGINAL,
56 'versionCode': 9, 'versionName': '0.7.2-personal.1',
57 'sha256': subject.ORIGINAL_SHA},
58 qa_check=lambda _, expected_code=None: {'result': 'PASS',
59 'package': subject.QA, 'versionCode': expected_code,
60 'versionName': f'0.7.2-recovery-qa.{expected_code}', 'sha256': 'a' * 64},
61 certificate_check=lambda p: subject.ORIGINAL_CERT if p == self.paths[0] else 'b' * 64)
62 defaults.update(options)
63 return subject.Harness(**defaults)
64
65 def assert_no_install(self):
66 self.assertFalse(any(call[0] == 'install' for call in self.adb.calls))
67
68 def test_all_inputs_gated_before_any_install(self):
69 for options, code in (({'serial': 'physical-phone'}, 'explicit_emulator_serial_required'),
70 ({'acknowledge': False}, 'synthetic_emulator_acknowledgement_required'),
71 ({'certificate_check': lambda _: subject.ORIGINAL_CERT}, 'qa_signer_must_differ_from_original'),
72 ({'original_check': lambda _: {'sha256': '0' * 64}}, 'original_apk_rejected')):
73 with self.subTest(code=code):
74 self.adb.calls.clear()
75 with self.assertRaisesRegex(subject.AcceptanceError, code):
76 self.make(**options).preflight()
77 self.assert_no_install()
78
79 def test_rejects_existing_lifeguide_package_and_physical_hardware(self):
80 for attribute, value in (('packages', 'package:ir.lifeguide.app\n'),
81 ('hardware', 'physical')):
82 with self.subTest(attribute=attribute):
83 old = getattr(self.adb, attribute)
84 setattr(self.adb, attribute, value)
85 with self.assertRaises(subject.AcceptanceError):
86 self.make().preflight()
87 self.assert_no_install()
88 setattr(self.adb, attribute, old)
89
90 def test_seed_is_owned_unlaunched_and_no_clobber(self):
91 h = self.make()
92 sent = []
93 raw = subject.create_sample_database()
94 h.binary = lambda command, data=None: (sent.append((command, data)) or b'') if data is not None else raw
95 with self.assertRaises(subject.AcceptanceError):
96 h.seed(subject.ORIGINAL, raw)
97 h.preflight()
98 h.install(subject.ORIGINAL)
99 h.seed(subject.ORIGINAL, raw)
100 self.assertIn('set -C', sent[0][0])
101 self.assertIn('test ! -e', sent[0][0])
102 self.assertEqual(sent[0][1], raw)
103 with self.assertRaises(subject.AcceptanceError):
104 h.seed(subject.ORIGINAL, raw)
105
106 def test_capture_requires_absence_and_sidecars_before_and_after_read(self):
107 h = self.make()
108 h.preflight()
109 h.install(subject.ORIGINAL)
110 reads = []
111 h.binary = lambda command, data=None: reads.append(command) or subject.create_sample_database()
112 self.adb.process = 'PRESENT'
113 with self.assertRaises(subject.AcceptanceError):
114 h.capture(subject.ORIGINAL)
115 self.assertEqual(reads, [])
116 self.adb.process = 'ABSENT'
117 self.adb.sidecars = 'SIDECAR'
118 with self.assertRaises(subject.AcceptanceError):
119 h.capture(subject.ORIGINAL)
120 self.assertEqual(reads, [])
121 self.adb.sidecars = 'CLEAN'
122 def racing_read(command, data=None):
123 self.adb.sidecars = 'SIDECAR'
124 return subject.create_sample_database()
125 h.binary = racing_read
126 with self.assertRaises(subject.AcceptanceError):
127 h.capture(subject.ORIGINAL)
128
129 def test_capture_accepts_only_stable_empty_wal_cache_shapes(self):
130 h = self.make()
131 h.preflight()
132 h.install(subject.ORIGINAL)
133 raw = subject.create_sample_database()
134 h.binary = lambda command, data=None: raw
135 for shape in ('CLEAN', 'EMPTY_WAL', 'EMPTY_WAL_SHM', 'EMPTY_JOURNAL'):
136 self.adb.sidecars = shape
137 self.assertEqual(h.capture(subject.ORIGINAL), raw)
138 self.adb.sidecars = 'EMPTY_WAL_SHM'
139 def changing_read(command, data=None):
140 self.adb.sidecars = 'EMPTY_WAL'
141 return raw
142 h.binary = changing_read
143 with self.assertRaisesRegex(subject.AcceptanceError, 'database_cache_shape_changed'):
144 h.capture(subject.ORIGINAL)
145 for state in ('NONEMPTY_WAL', 'ORPHAN_SHM', 'JOURNAL', 'SIDECAR'):
146 self.adb.sidecars = state
147 with self.assertRaisesRegex(subject.AcceptanceError, 'database_sidecar_present'):
148 h.capture(subject.ORIGINAL)
149
150 def test_sidecar_refusal_records_only_strict_file_metadata(self):
151 h = self.make()
152 h.preflight()
153 h.install(subject.ORIGINAL)
154 previous_shell = self.adb.shell
155 metadata = 'main FILE 45056\nwal FILE 32768\nshm FILE 32768\njournal ABSENT\n'
156 def shell(*parts, **kwargs):
157 if parts[0] == 'run-as' and 'stat -c' in parts[-1]:
158 return metadata
159 return previous_shell(*parts, **kwargs)
160 self.adb.shell = shell
161 self.adb.sidecars = 'SIDECAR'
162 with self.assertRaisesRegex(subject.AcceptanceError, '^database_sidecar_present$'):
163 h._cold(subject.ORIGINAL)
164 self.assertEqual(h.receipt['lastColdFileObservation']['wal'],
165 {'kind': 'FILE', 'bytes': 32768})
166 metadata = 'untrusted diagnostic content must not be published'
167 with self.assertRaisesRegex(subject.AcceptanceError, '^database_sidecar_present$'):
168 h._cold(subject.ORIGINAL)
169 self.assertEqual(h.receipt['lastColdFileObservation'], 'UNAVAILABLE')
170 self.assertNotIn('untrusted', json.dumps(h.receipt))
171
172 def test_actual_committed_truncate_journal_is_safe_after_process_exit(self):
173 source = self.directory / subject.DATABASE
174 source.parent.mkdir()
175 fixture = subject.create_sample_database()
176 source.write_bytes(fixture)
177 script = ("import os,sqlite3,sys; d=sqlite3.connect(sys.argv[1]); "
178 "d.execute('PRAGMA journal_mode=TRUNCATE'); "
179 "d.execute('CREATE TABLE android_metadata (locale TEXT)'); "
180 "d.execute(\"INSERT INTO android_metadata VALUES ('en_US')\"); "
181 "d.commit(); os._exit(0)")
182 subprocess.run(['python3', '-c', script, str(source)], check=True)
183 journal = Path(str(source) + '-journal')
184 self.assertTrue(journal.is_file())
185 self.assertEqual(journal.stat().st_size, 0)
186 before = {p: p.read_bytes() for p in (source, journal)}
187 h = self.make()
188 h.preflight()
189 h.install(subject.ORIGINAL)
190 previous_shell = self.adb.shell
191 def shell(*parts, **kwargs):
192 if parts[0] == 'run-as':
193 return subprocess.run(['sh', '-c', parts[-1]], cwd=self.directory,
194 capture_output=True, text=True, check=True, timeout=2).stdout
195 return previous_shell(*parts, **kwargs)
196 self.adb.shell = shell
197 h.binary = lambda command, data=None: source.read_bytes()
198 try:
199 captured = h.capture(subject.ORIGINAL)
200 except subject.AcceptanceError as error:
201 self.fail('Committed TRUNCATE journal is empty, but capture refused: ' + str(error))
202 self.assertEqual(h.receipt['coldCaptureStates'][subject.ORIGINAL], 'EMPTY_JOURNAL')
203 copy = self.directory / 'captured-main.sqlite'
204 copy.write_bytes(captured)
205 reference = self.directory / 'reference.sqlite'
206 reference.write_bytes(fixture)
207 actual = subject.normalized_snapshot(copy, self.directory / 'normalized.sqlite')
208 self.assertEqual(actual, subject.export_fixture(reference))
209 self.assertEqual(subject.independent_sql(reference),
210 subject.independent_sql(self.directory / 'normalized.sqlite'))
211 self.assertEqual({p: p.read_bytes() for p in before}, before)
212
213 def test_actual_shell_rejects_unsafe_sidecar_shapes(self):
214 h = self.make()
215 h.preflight()
216 h.install(subject.ORIGINAL)
217 previous_shell = self.adb.shell
218 cases = ('byte', 'directory', 'fifo', 'symlink', 'dangling', 'with_wal',
219 'with_shm', 'shm_directory', 'shm_fifo', 'wal_dangling', 'shm_dangling')
220 for kind in cases:
221 with self.subTest(kind=kind), tempfile.TemporaryDirectory() as root:
222 db = Path(root) / subject.DATABASE
223 db.parent.mkdir()
224 journal = Path(str(db) + '-journal')
225 wal = Path(str(db) + '-wal')
226 shm = Path(str(db) + '-shm')
227 def shell(*parts, **kwargs):
228 if parts[0] == 'run-as':
229 return subprocess.run(['sh', '-c', parts[-1]], cwd=root,
230 capture_output=True, text=True, check=True, timeout=2).stdout
231 return previous_shell(*parts, **kwargs)
232 self.adb.shell = shell
233 if kind == 'byte':
234 journal.write_bytes(b'x')
235 elif kind == 'directory':
236 journal.mkdir()
237 elif kind == 'fifo':
238 subject.os.mkfifo(journal)
239 elif kind in ('symlink', 'dangling'):
240 target = Path(root) / 'empty-target'
241 if kind == 'symlink':
242 target.write_bytes(b'')
243 journal.symlink_to(target if kind == 'symlink' else Path(root) / 'missing')
244 elif kind in ('shm_directory', 'shm_fifo'):
245 wal.write_bytes(b'')
246 if kind == 'shm_directory':
247 shm.mkdir()
248 else:
249 subject.os.mkfifo(shm)
250 elif kind in ('wal_dangling', 'shm_dangling'):
251 (wal if kind == 'wal_dangling' else shm).symlink_to(Path(root) / 'missing')
252 else:
253 journal.write_bytes(b'')
254 (wal if kind == 'with_wal' else shm).write_bytes(b'')
255 with self.assertRaisesRegex(subject.AcceptanceError, 'database_sidecar_present'):
256 h._cold(subject.ORIGINAL)
257
258 def test_actual_exited_sqlite_reader_leaves_empty_wal_cache_only(self):
259 source = self.directory / 'real-closed-reader.sqlite'
260 fixture = subject.create_sample_database()
261 source.write_bytes(fixture)
262 script = ("import os,sqlite3,sys; d=sqlite3.connect(sys.argv[1]); "
263 "d.execute('PRAGMA journal_mode=WAL'); "
264 "d.execute('SELECT * FROM local_profiles').fetchall(); os._exit(0)")
265 subprocess.run(['python3', '-c', script, str(source)], check=True)
266 wal, shm = Path(str(source) + '-wal'), Path(str(source) + '-shm')
267 self.assertEqual(wal.stat().st_size, 0)
268 self.assertGreater(shm.stat().st_size, 0)
269 before = {p: p.read_bytes() for p in (source, wal, shm)}
270 # The AVD harness captures the main bytes only AFTER its cold zero-WAL gate.
271 captured = self.directory / 'captured-main.sqlite'
272 captured.write_bytes(source.read_bytes())
273 reference = self.directory / 'reference.sqlite'
274 reference.write_bytes(fixture)
275 normalized = subject.normalized_snapshot(captured, self.directory / 'normalized.sqlite')
276 self.assertEqual(normalized, subject.export_fixture(reference))
277 self.assertEqual(subject.independent_sql(reference),
278 subject.independent_sql(self.directory / 'normalized.sqlite'))
279 self.assertEqual({p: p.read_bytes() for p in before}, before)
280
281 def test_private_normalization_preserves_wal_header_source_and_full_fields(self):
282 raw = bytearray(subject.create_sample_database())
283 raw[18:20] = b'\x02\x02'
284 source = self.directory / 'closed.sqlite'
285 source.write_bytes(raw)
286 original = bytes(raw)
287 normalized = subject.normalized_snapshot(source, self.directory / 'copy.sqlite')
288 self.assertEqual(source.read_bytes(), original)
289 reference = self.directory / 'reference.sqlite'
290 reference.write_bytes(subject.create_sample_database())
291 self.assertEqual(normalized, subject.export_fixture(reference))
292 self.assertEqual(subject.independent_sql(self.directory / 'copy.sqlite'),
293 subject.independent_sql(reference))
294
295 def test_notification_choice_and_native_state_are_strictly_off(self):
296 for xml in ('<map/>', '<map><boolean name="enabled" value="false" /></map>'):
297 self.assertTrue(subject.notification_preferences_off(xml, choice=True))
298 self.assertTrue(subject.notification_preferences_off('<map/>', choice=False))
299 for xml, choice in (('<map><boolean name="enabled" value="true"/></map>', True),
300 ('<map><string name="active">{}</string></map>', False),
301 ('<!DOCTYPE map><map/>', True),
302 ('<map><boolean name="enabled" value="false"/><boolean name="enabled" value="false"/></map>', True)):
303 with self.subTest(xml=xml), self.assertRaises(subject.AcceptanceError):
304 subject.notification_preferences_off(xml, choice=choice)
305
306 def test_ui_requires_exact_owned_profile_semantics_and_dump_cleanup(self):
307 h = self.make()
308 h.preflight()
309 h.install(subject.ORIGINAL)
310 xml = ''
311 def shell(*parts, **kwargs):
312 self.adb.calls.append(parts)
313 return xml if parts[0] == 'cat' else ''
314 self.adb.shell = shell
315 for attribute in ('text', 'content-desc'):
316 for value in (subject.PROFILE, 'سلام ' + subject.PROFILE):
317 with self.subTest(attribute=attribute, value=value):
318 xml = f'<hierarchy><node package="{subject.ORIGINAL}" {attribute}="{value}"/></hierarchy>'
319 self.assertTrue(h.profile_visible(subject.ORIGINAL))
320 for attrs in ('text="not fixture"',
321 f'text="extra {subject.PROFILE}"',
322 f'content-desc="سلام {subject.PROFILE} extra"',
323 f'content-desc="{subject.PROFILE}" package="another.app"',
324 f'text="{subject.PROFILE}"'):
325 with self.subTest(attrs=attrs):
326 xml = '<hierarchy><node ' + attrs + '/></hierarchy>'
327 self.assertFalse(h.profile_visible(subject.ORIGINAL))
328 for xml in ('<hierarchy><broken>', '<wrong><node/></wrong>'):
329 with self.assertRaises(subject.AcceptanceError):
330 h.profile_visible(subject.ORIGINAL)
331 dumps = [call for call in self.adb.calls if call[0] == 'uiautomator']
332 self.assertEqual(len(dumps), 11)
333 for call in dumps:
334 self.assertRegex(call[2], r'^/data/local/tmp/lifeguide-recovery-[0-9a-f]+\.xml$')
335 self.assertIn(('rm', call[2]), self.adb.calls)
336
337 def test_ui_timeout_keeps_failure_even_if_synthetic_diagnostic_fails(self):
338 for diagnostic_fails in (False, True):
339 with self.subTest(diagnostic_fails=diagnostic_fails):
340 ticks = iter((0, 31))
341 h = self.make(clock=lambda: next(ticks))
342 h.preflight()
343 h.install(subject.ORIGINAL)
344 h.seeded.add(subject.ORIGINAL)
345 h.profile_visible = lambda _: False
346 captures = []
347 def screenshot(kind='ordinary'):
348 captures.append(kind)
349 if diagnostic_fails:
350 raise subject.AcceptanceError('fictional_screenshot_failed')
351 h.screenshot = screenshot
352 with self.assertRaisesRegex(subject.AcceptanceError, '^real_profile_ui_not_visible$'):
353 h.launch(subject.ORIGINAL)
354 self.assertEqual(captures, ['ui-failure-original'])
355
356 def test_seed_checks_bytes_after_binary_exec_without_overwriting(self):
357 h = self.make()
358 h.preflight()
359 h.install(subject.ORIGINAL)
360 h.binary = lambda command, data=None: b''
361 with self.assertRaises(subject.AcceptanceError):
362 h.seed(subject.ORIGINAL, subject.create_sample_database())
363
364 def test_notification_permission_requires_explicit_runtime_denial(self):
365 h = self.make()
366 h.preflight()
367 h.install(subject.QA)
368 h.binary = lambda command, data=None: b'<map/>'
369 original_shell = self.adb.shell
370 state = 'false'
371 def shell(*parts, **kwargs):
372 if parts[:2] == ('dumpsys', 'package'):
373 return 'runtime permissions:\n android.permission.POST_NOTIFICATIONS: granted=' + state + ', flags=[]\n'
374 return original_shell(*parts, **kwargs)
375 self.adb.shell = shell
376 h.notifications_off()
377 state = 'true'
378 with self.assertRaisesRegex(subject.AcceptanceError, 'qa_notification_permission_not_denied'):
379 h.notifications_off()
380 state = ''
381 with self.assertRaisesRegex(subject.AcceptanceError, 'qa_notification_permission_not_denied'):
382 h.notifications_off()
383
384 def test_binary_transport_bounds_actual_child_output_and_input(self):
385 with self.assertRaisesRegex(subject.AcceptanceError, 'binary_input_limit'):
386 subject.binary_adb('emulator-5554', 'unused', b'a' * (subject.MAX_PAYLOAD_BYTES + 1))
387 popen = subprocess.Popen
388 def child(*args, **kwargs):
389 return popen(['python3', '-c', 'import sys; sys.stdout.buffer.write(b"a" * (8*1024*1024+1))'], **kwargs)
390 with patch.object(subject.subprocess, 'Popen', side_effect=child):
391 with self.assertRaisesRegex(subject.AcceptanceError, 'binary_output_limit'):
392 subject.binary_adb('emulator-5554', 'unused')
393
394 def test_binary_transport_uses_adb_input_and_output_directions(self):
395 # Android15 adb commandline.cpp: exec-in copies stdin to device;
396 # exec-out only copies device bytes to stdout and never consumes stdin.
397 uploaded = self.directory / 'uploaded-fixture'
398 real_popen = subprocess.Popen
399 child_source = ("import sys; from pathlib import Path; "
400 "mode=sys.argv[1]; "
401 "Path(sys.argv[2]).write_bytes(sys.stdin.buffer.read()) "
402 "if mode == 'exec-in' else sys.stdout.buffer.write(b'fictional capture')")
403 def child(argv, **kwargs):
404 return real_popen(['python3', '-c', child_source, argv[3], str(uploaded)], **kwargs)
405 payload = bytes(range(256)) * 32
406 with patch.object(subject.subprocess, 'Popen', side_effect=child):
407 self.assertEqual(subject.binary_adb('emulator-5554', 'fixed synthetic command', payload), b'')
408 self.assertEqual(uploaded.read_bytes(), payload)
409 self.assertEqual(subject.binary_adb('emulator-5554', 'fixed synthetic command'), b'fictional capture')
410
411 def test_failure_receipt_without_device_is_sanitized(self):
412 output = self.directory / 'exports' / 'failed.json'
413 code = subject.main(['--serial', 'physical-phone', '--original-apk', str(self.paths[0]),
414 '--qa-apk', str(self.paths[1]), '--upgrade-apk', str(self.paths[2]),
415 '--acknowledge-synthetic-emulator-only', '--output', str(output)])
416 self.assertEqual(code, 2)
417 receipt = json.loads(output.read_text())
418 self.assertEqual(receipt['result'], 'FAIL')
419 self.assertEqual(receipt['errorCode'], 'explicit_emulator_serial_required')
420 self.assertEqual(receipt['currentPhase'], 'preflight')
421 self.assertNotIn('host test apk', output.read_text())
422
423
424 if __name__ == '__main__':
425 unittest.main()