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
py 407 lines 21 KB
Raw
1 """Host safety tests; these are not evidence of Android or SQLite execution."""
2 import contextlib
3 import io
4 import json
5 import tempfile
6 import unittest
7 from pathlib import Path
8 from unittest.mock import patch
9 from urllib.parse import parse_qs, urlparse
10 from xml.sax.saxutils import escape
11
12 import test_standalone_android as subject
13
14
15 class CertificateTest(unittest.TestCase):
16 def test_sdk36_v2_output_and_legacy_single_signer(self):
17 from subprocess import CompletedProcess
18 for prefix in ('V2 Signer:', 'Signer #1'):
19 output = prefix + ' certificate SHA-256 digest: ' + 'a' * 64 + '\n'
20 with self.subTest(prefix=prefix), patch.object(subject.shutil, 'which', return_value='/synthetic/apksigner'), patch.object(subject.subprocess, 'run', return_value=CompletedProcess([], 0, output, '')):
21 self.assertEqual(subject.certificate_digest(Path('/synthetic/never-read.apk')), 'a' * 64)
22
23 def test_bad_or_multiple_certificates_or_failed_verification_rejected(self):
24 from subprocess import CompletedProcess
25 valid = 'V2 Signer: certificate SHA-256 digest: ' + 'a' * 64 + '\n'
26 for code, output in ((1, valid), (0, ''), (0, valid + valid), (0, valid.replace('certificate', 'public key'))):
27 with self.subTest(code=code, output=output), patch.object(subject.shutil, 'which', return_value='/synthetic/apksigner'), patch.object(subject.subprocess, 'run', return_value=CompletedProcess([], code, output, '')):
28 with self.assertRaisesRegex(subject.AcceptanceError, 'apk_signature_rejected'):
29 subject.certificate_digest(Path('/synthetic/never-read.apk'))
30
31
32 class FakeAdb:
33 def __init__(self, overrides=None):
34 self.calls = []
35 self.responses = {
36 ("get-state",): "device\n",
37 ("shell", "getprop", "ro.kernel.qemu"): "1\n",
38 ("shell", "getprop", "ro.boot.qemu"): "1\n",
39 ("shell", "getprop", "ro.hardware"): "ranchu\n",
40 ("shell", "getprop", "ro.product.name"): "sdk_gphone64_x86_64\n",
41 ("shell", "getprop", "ro.build.version.sdk"): "35\n",
42 ("shell", "pm", "list", "packages", subject.PACKAGE): "",
43 }
44 self.responses.update(overrides or {})
45
46 def command(self, *parts, allow_failure=False):
47 self.calls.append(parts)
48 if parts[0] == "install":
49 return "Success\n"
50 return self.responses.get(parts, "")
51
52 def shell(self, *parts, allow_failure=False):
53 return self.command("shell", *parts, allow_failure=allow_failure)
54
55
56 class SafetyTest(unittest.TestCase):
57 def setUp(self):
58 self.directory = tempfile.TemporaryDirectory()
59 self.addCleanup(self.directory.cleanup)
60 self.user = Path(self.directory.name) / "user.apk"
61 self.fixture = Path(self.directory.name) / "fixture.apk"
62 self.user.write_bytes(b"user placeholder")
63 self.fixture.write_bytes(b"fixture placeholder")
64 self.manifest = {"result": "PASS", "package": subject.PACKAGE,
65 "label": subject.LABEL, "debuggable": True, "internetPermission": False,
66 "targetSdkVersion": 36, "sha256": "a" * 64}
67
68 def harness(self, adb, **extra):
69 values = dict(serial="emulator-5554", user_apk=self.user,
70 fixture_apk=self.fixture, allow_reset=True, adb=adb,
71 manifest_check=lambda path: self.manifest,
72 certificate_check=lambda path: "b" * 64,
73 screenshot=Path(self.directory.name) / "first-launch.png")
74 values.update(extra)
75 return subject.Harness(**values)
76
77 def assert_read_only(self, adb):
78 for parts in adb.calls:
79 self.assertNotEqual(parts[0], "install")
80 if parts[0] == "shell":
81 self.assertIn(parts[1:3], [("getprop", "ro.kernel.qemu"),
82 ("getprop", "ro.boot.qemu"), ("getprop", "ro.hardware"),
83 ("getprop", "ro.product.name"), ("getprop", "ro.build.version.sdk"),
84 ("pm", "list")])
85
86 def test_physical_and_implicit_serial_refused_without_adb(self):
87 for serial in ("", "R58PHONE", "emulator-5554;bad", "emulator-5555", "emulator-5554\n"):
88 adb = FakeAdb()
89 with self.subTest(serial=serial), self.assertRaises(subject.AcceptanceError):
90 self.harness(adb, serial=serial).install_user()
91 self.assertEqual(adb.calls, [])
92
93 def test_confirmation_and_two_existing_apks_required_before_adb(self):
94 for change in ({"allow_reset": False}, {"user_apk": self.user.with_name("absent")},
95 {"fixture_apk": self.fixture.with_name("absent")}):
96 adb = FakeAdb()
97 with self.subTest(change=change), self.assertRaises(subject.AcceptanceError):
98 self.harness(adb, **change).install_user()
99 self.assertEqual(adb.calls, [])
100
101 def test_both_manifest_and_same_certificate_checked_before_adb(self):
102 for change in ({"debuggable": False}, {"internetPermission": True},
103 {"label": "other"}, {"package": "ir.lifeguide.app"},
104 {"targetSdkVersion": 35}):
105 adb = FakeAdb()
106 with self.subTest(change=change), self.assertRaises(subject.AcceptanceError):
107 self.harness(adb, manifest_check=lambda path: self.manifest | change).install_user()
108 self.assertEqual(adb.calls, [])
109 adb = FakeAdb()
110 with self.assertRaisesRegex(subject.AcceptanceError, "apk_certificates_differ"):
111 self.harness(adb, certificate_check=lambda path: ("b" if path == self.user else "c") * 64).install_user()
112 self.assertEqual(adb.calls, [])
113
114 def test_all_emulator_gates_precede_writes(self):
115 for override in ({("get-state",): "offline"},
116 {("shell", "getprop", "ro.kernel.qemu"): "0", ("shell", "getprop", "ro.boot.qemu"): "0"},
117 {("shell", "getprop", "ro.hardware"): "phone"},
118 {("shell", "getprop", "ro.product.name"): "owner"},
119 {("shell", "getprop", "ro.build.version.sdk"): "34"},
120 {("shell", "pm", "list", "packages", subject.PACKAGE): "package:" + subject.PACKAGE}):
121 adb = FakeAdb(override)
122 with self.subTest(override=override), self.assertRaises(subject.AcceptanceError):
123 self.harness(adb).install_user()
124 self.assert_read_only(adb)
125
126 def test_owned_upgrade_requires_actual_first_launch_proof(self):
127 adb = FakeAdb()
128 harness = self.harness(adb)
129 harness.install_user()
130 with self.assertRaisesRegex(subject.AcceptanceError, "user_first_launch_not_verified"):
131 harness.install_fixture()
132 installs = [call for call in adb.calls if call[0] == "install"]
133 self.assertEqual(installs, [("install", str(self.user))])
134 harness.user_launched = True
135 adb.responses[("shell", "sh", "-c", subject.PID_QUERY)] = "ABSENT"
136 harness.install_fixture()
137 self.assertIn(("install", "-r", str(self.fixture)), adb.calls)
138 commands = " ".join(" ".join(call) for call in adb.calls)
139 for forbidden in ("uninstall", "force-stop", "kill-server", "logcat -c"):
140 self.assertNotIn(forbidden, commands)
141
142 def test_empty_pid_response_is_not_absence_and_late_absence_is_not_proof(self):
143 adb = FakeAdb()
144 harness = self.harness(adb)
145 harness.installed = True
146 with self.assertRaisesRegex(subject.AcceptanceError, "fixture_process_query_failed"):
147 harness.process_dead()
148 adb.responses[("shell", "sh", "-c", subject.PID_QUERY)] = "ABSENT"
149 adb.responses[("shell", "date", "+%s")] = "1800000046"
150 with self.assertRaisesRegex(subject.AcceptanceError, "process_absence_missed_alarm_deadline"):
151 harness.process_dead(before=1800000045000)
152 self.assertNotIn("processAbsentBeforeAlarm", harness.receipt["checks"])
153
154 def test_cli_refusal_receipt_does_not_expose_raw_arguments(self):
155 output = Path(self.directory.name) / "receipt.json"
156 with patch.object(subject, "Adb") as adb, contextlib.redirect_stdout(io.StringIO()):
157 code = subject.main(["--user-apk", str(self.user), "--fixture-apk", str(self.fixture),
158 "--serial", "PRIVATE_PHONE", "--allow-synthetic-emulator-reset", "--output", str(output)])
159 self.assertEqual(code, 1)
160 adb.assert_not_called()
161 self.assertNotIn("PRIVATE_PHONE", output.read_text())
162
163
164 class ParsingTest(unittest.TestCase):
165 def marker(self, mode="seed"):
166 return {"nonce": "0123456789abcdef", "mode": mode, "syntheticDataOnly": True,
167 "database": subject.DATABASE, "checks": {"rawSqlAfterClose": True,
168 "profilePersists": True, "weeklyDifferentTimes": True,
169 "onceAndEveryTwoDays": True},
170 "status": {"supported": True, "permissionGranted": True, "active": True, "enabled": True,
171 "activeScope": subject.SCOPE, "scheduledCount": 1,
172 "timing": "exact", "canScheduleExactAlarms": True},
173 "scheduledAtEpochMs": 1800000045000}
174
175 def test_marker_whitelist_discards_arbitrary_private_fields(self):
176 marker = self.marker() | {"private": "DO_NOT_PUBLISH"}
177 marker["checks"]["private"] = "DO_NOT_PUBLISH"
178 parsed = subject.fixture_marker(subject.MARKER + json.dumps(marker), marker["nonce"], "seed")
179 self.assertNotIn("DO_NOT_PUBLISH", json.dumps(parsed))
180 self.assertIsNone(subject.fixture_marker(subject.MARKER + json.dumps(marker), "a" * 16, "seed"))
181
182 def test_marker_rejects_wrong_database_scope_or_fixture_label(self):
183 for update in ({"database": "lifeguide_standalone_v1.sqlite"},
184 {"syntheticDataOnly": False}, {"mode": "inspect"},
185 {"status": self.marker()["status"] | {"activeScope": "private"}}):
186 marker = self.marker() | update
187 with self.subTest(update=update), self.assertRaises(subject.AcceptanceError):
188 subject.fixture_marker(subject.MARKER + json.dumps(marker), marker["nonce"], "seed")
189
190 def test_public_lock_screen_version_has_separate_generic_title(self):
191 key = '0|' + subject.PACKAGE + '|1|lifeguide-plan:' + '22222222-2222-4222-8222-222222222222' + '|10001'
192 primary = (f'NotificationRecord(pkg={subject.PACKAGE} key={key}: Notification(channel={subject.CHANNEL}))\n'
193 f'android.title=String ({subject.COMPANION})\nandroid.text=String ({subject.GENERIC_BODY})\n')
194 public = f'publicVersion\nandroid.title=String (LifeGuide)\nandroid.text=String ({subject.GENERIC_BODY})\n'
195 self.assertTrue(subject.check_notification_record(primary + public, key)['titleMatches'])
196 for bad in (primary.replace(subject.COMPANION, 'wrong') + public,
197 primary + public.replace('LifeGuide)', 'wrong)'),
198 primary + public.replace(subject.GENERIC_BODY, subject.CANARY)):
199 with self.assertRaises(subject.AcceptanceError):
200 subject.check_notification_record(bad, key)
201
202 def test_notification_parser_accepts_only_owned_uuid_tag(self):
203 identifier = "33333333-3333-4333-8333-333333333333"
204 key = f"0|{subject.PACKAGE}|1|lifeguide-plan:{identifier}|10123"
205 self.assertEqual(subject.active_fixture_keys(key), [key])
206 with self.assertRaisesRegex(subject.AcceptanceError, "unexpected_fixture_notification"):
207 subject.active_fixture_keys(f"0|{subject.PACKAGE}|1|private-title|10123")
208
209 def test_preferences_only_allow_synthetic_scope_and_companion(self):
210 from xml.sax.saxutils import escape
211 row = {"id": "33333333-3333-4333-8333-333333333333",
212 "planItemId": "33333333-3333-4333-8333-333333333333",
213 "scheduledAtEpochMs": 1800000045000, "companionName": subject.COMPANION}
214 state = {"scope": subject.SCOPE, "generation": "44444444-4444-4444-8444-444444444444",
215 "issuedAtEpochMs": 1800000000000, "validUntilEpochMs": 1800086400000,
216 "reminders": [row], "leaseKind": "device-planner-v1"}
217 def xml():
218 return '<map><string name="active">' + escape(json.dumps(state)) + '</string></map>'
219 self.assertEqual(subject.parse_preferences(xml()), state)
220 row["companionName"] = "private user name"
221 with self.assertRaises(subject.AcceptanceError) as caught:
222 subject.parse_preferences(xml())
223 self.assertNotIn("private user name", str(caught.exception))
224
225 def test_fixture_source_has_separate_db_and_no_server_acknowledgement(self):
226 source = Path(__file__).with_name("standalone_acceptance_fixture.dart").read_text()
227 self.assertIn("LG_STANDALONE_ACCEPTANCE", source)
228 self.assertIn("StandaloneStore.open", source)
229 self.assertIn("rawQuery", source)
230 self.assertIn(subject.DATABASE, source)
231 self.assertNotIn("serverAcknowledged", source)
232 self.assertNotIn("LocalOnlyApi", source)
233
234
235 class SyntheticEmulator(FakeAdb):
236 """A host model for orchestration checks, never Android acceptance evidence."""
237 def __init__(self):
238 super().__init__()
239 self.elapsed = 0
240 self.alive = self.posted = self.enabled = False
241 self.state = None
242 self.markers, self.modes = [], []
243 self.refuse_kill = False
244 self.pid_failure = False
245 self.background_delay = 0
246 self.background_ready = 0
247 self.late_kill = False
248 self.identifier = "33333333-3333-4333-8333-333333333333"
249
250 def clock(self):
251 return self.elapsed
252
253 def epoch(self):
254 return 1800000010000 + int(self.elapsed * 1000)
255
256 def sleep(self, seconds):
257 self.elapsed += seconds
258 if self.state and self.state["reminders"]:
259 row = self.state["reminders"][0]
260 if not row.get("delivered") and row["scheduledAtEpochMs"] <= self.epoch():
261 row["delivered"] = True
262 self.posted = self.alive = True
263
264 def key(self):
265 return f"0|{subject.PACKAGE}|1|lifeguide-plan:{self.identifier}|10123"
266
267 def command(self, *parts, allow_failure=False):
268 if parts[0] == "install":
269 return super().command(*parts, allow_failure=allow_failure)
270 self.calls.append(parts)
271 if parts == ("shell", "input", "keyevent", "KEYCODE_HOME"):
272 self.background_ready = self.elapsed + self.background_delay
273 return ""
274 if parts == ("shell", "am", "kill", subject.PACKAGE):
275 if self.late_kill and self.state and self.state["reminders"]:
276 self.sleep(60)
277 self.alive = self.refuse_kill or self.elapsed < self.background_ready
278 return ""
279 if parts == ("shell", "sh", "-c", subject.PID_QUERY):
280 return "" if self.pid_failure else ("PRESENT" if self.alive else "ABSENT")
281 if parts == ("shell", "date", "+%s"):
282 return str(self.epoch() // 1000)
283 if parts[0] == "logcat":
284 return "\n".join(self.markers)
285 if parts[:3] == ("shell", "run-as", subject.PACKAGE):
286 return "<map/>" if self.state is None else ('<map><string name="active">' +
287 escape(json.dumps(self.state)) + '</string></map>')
288 if parts == ("shell", "cmd", "notification", "list"):
289 return self.key() if self.posted else ""
290 if parts[:3] == ("shell", "dumpsys", "notification"):
291 return (f"NotificationRecord(pkg={subject.PACKAGE} key={self.key()}: "
292 f"Notification(channel={subject.CHANNEL}))\n"
293 f"android.title=String ({subject.COMPANION})\n"
294 f"android.text=String ({subject.GENERIC_BODY})\n")
295 if parts[:3] == ("shell", "am", "start"):
296 self.alive = True
297 if "--es" not in parts:
298 return "Status: ok"
299 route = urlparse(parts[-1])
300 mode = route.path[1:]
301 self.modes.append(mode)
302 at = None
303 if mode in ("seed", "change"):
304 at = (self.epoch() // 60000 + 1) * 60000
305 self.enabled, self.posted = True, False
306 self.state = {"scope": subject.SCOPE,
307 "generation": "44444444-4444-4444-8444-444444444444",
308 "issuedAtEpochMs": self.epoch(), "validUntilEpochMs": self.epoch() + 31 * 86400000,
309 "leaseKind": "device-planner-v1", "reminders": [{"id": self.identifier,
310 "planItemId": self.identifier, "companionName": subject.COMPANION,
311 "scheduledAtEpochMs": at}]}
312 elif mode == "cancel":
313 self.state["reminders"] = []
314 self.posted = False
315 elif mode == "off":
316 self.enabled, self.posted, self.state = False, False, None
317 status = {"supported": True, "permissionGranted": True,
318 "active": self.state is not None, "enabled": self.enabled,
319 "activeScope": subject.SCOPE if self.state else None,
320 "scheduledCount": sum(r["scheduledAtEpochMs"] > self.epoch()
321 for r in self.state["reminders"]) if self.state else 0,
322 "timing": "exact", "canScheduleExactAlarms": True}
323 marker = {"nonce": parse_qs(route.query)["nonce"][0], "mode": mode,
324 "syntheticDataOnly": True, "database": subject.DATABASE, "status": status,
325 "checks": {k: True for k in subject.CHECKS}}
326 if at:
327 marker["scheduledAtEpochMs"] = at
328 self.markers.append(subject.MARKER + json.dumps(marker))
329 return "Status: ok"
330 return self.responses.get(parts, "")
331
332
333 class LifecycleTest(unittest.TestCase):
334 setUp = SafetyTest.setUp
335
336 def harness(self, adb, **extra):
337 values = {"clock": adb.clock, "sleep": adb.sleep}
338 values.update(extra)
339 return SafetyTest.harness(self, adb, **values)
340
341 def first_launch(self, harness):
342 # Real screenshot handling is separately tested below; this host model
343 # cannot provide a genuine image from an Android display.
344 harness.adb.shell("am", "start", "-W", "-f", "0x10008000", "-n", subject.COMPONENT)
345 harness.user_launched = True
346
347 def test_full_mode_sequence_and_sanitized_receipt(self):
348 adb = SyntheticEmulator()
349 harness = self.harness(adb)
350 with patch.object(harness, "first_user_launch", side_effect=lambda: self.first_launch(harness)):
351 receipt = harness.run()
352 self.assertEqual(receipt["result"], "PASS")
353 self.assertEqual(adb.modes, ["seed", "inspect", "change", "cancel", "off"])
354 self.assertIsNone(adb.state)
355 self.assertFalse(adb.posted)
356 self.assertGreater(adb.elapsed, 95)
357 self.assertTrue(all(value == "UNVERIFIED" for value in receipt["limitations"].values()))
358 serialized = json.dumps(receipt)
359 for forbidden in (subject.CANARY, "NotificationRecord", "<map", "nonce"):
360 self.assertNotIn(forbidden, serialized)
361 launches = [p for p in adb.calls if p[:3] == ("shell", "am", "start")]
362 self.assertNotIn("--es", launches[0])
363 for parts in launches:
364 self.assertIn(subject.COMPONENT, parts)
365 self.assertEqual(parts[parts.index("-f") + 1], "0x10008000")
366 commands = " ".join(" ".join(call) for call in adb.calls)
367 for forbidden in ("uninstall", "force-stop", "kill-server", "logcat -c"):
368 self.assertNotIn(forbidden, commands)
369
370 def test_real_first_launch_path_requires_present_pid_and_valid_png(self):
371 import struct
372 adb = SyntheticEmulator()
373 harness = self.harness(adb)
374 harness.install_user()
375 png = b"\x89PNG\r\n\x1a\n" + b"\0\0\0\rIHDR" + struct.pack(">II", 1080, 1920)
376 result = type("Result", (), {"returncode": 0, "stdout": png})()
377 with patch.object(subject.subprocess, "run", return_value=result):
378 harness.first_user_launch()
379 self.assertTrue(harness.user_launched)
380 self.assertEqual(harness.screenshot.read_bytes(), png)
381 self.assertTrue(harness.receipt["userFirstLaunch"]["ordinaryLaunchNoExtras"])
382
383 def test_background_transition_retries_and_failed_pid_never_claims_absence(self):
384 adb = SyntheticEmulator()
385 adb.background_delay = 1
386 harness = self.harness(adb)
387 harness.installed = True
388 harness.process_dead()
389 self.assertGreaterEqual(adb.elapsed, 1)
390 self.assertGreater(harness.receipt["processExit"]["ordinaryKillAttempts"], 1)
391 adb.pid_failure = True
392 with self.assertRaisesRegex(subject.AcceptanceError, "fixture_process_query_failed"):
393 harness.process_dead()
394 self.assertNotIn("processExit", harness.receipt)
395
396 def test_late_absence_cannot_claim_notification_after_process_death(self):
397 adb = SyntheticEmulator()
398 adb.late_kill = True
399 harness = self.harness(adb)
400 with patch.object(harness, "first_user_launch", side_effect=lambda: self.first_launch(harness)):
401 with self.assertRaisesRegex(subject.AcceptanceError, "process_absence_missed_alarm_deadline"):
402 harness.run()
403 self.assertNotIn("processAbsentBeforeAlarm", harness.receipt["checks"])
404
405
406 if __name__ == "__main__":
407 unittest.main()