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 510 lines 26.8 KB
Raw
1 #!/usr/bin/env python3
2 """Synthetic-only recovery rehearsal on an explicitly selected fresh API35 AVD.
3
4 Never point this tool at an owner phone, owner data or owner signing key. Only
5 the exact delivered original and two explicitly marked debug QA APKs qualify.
6 No uninstall, clear-data, force-stop, root, permission grant or source checkpoint.
7 """
8 import argparse
9 import hashlib
10 import json
11 import os
12 from pathlib import Path
13 import re
14 import secrets
15 import selectors
16 import shlex
17 import sqlite3
18 import struct
19 import subprocess
20 import sys
21 import tempfile
22 import time
23 import xml.etree.ElementTree as ET
24
25 from test_native_reminders_android import Adb, AcceptanceError, require, validate_serial
26 from test_standalone_android import certificate_digest
27 from check_standalone_apk import check as original_manifest_check
28 from check_personal_recovery_apk import check as qa_manifest_check
29
30 sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
31 from scripts.personal_recovery.archive import open_archive, seal
32 from scripts.personal_recovery.common import FIXTURE_APPLICATION_ID, MAX_PAYLOAD_BYTES, RecoveryError
33 from scripts.personal_recovery.files import publish_new, read_bounded
34 from scripts.personal_recovery.snapshot import create_sample_database, database_from_snapshot, export_fixture
35
36 ORIGINAL = 'ir.lifeguide.app.device'
37 QA = 'ir.lifeguide.app.personal'
38 ORIGINAL_SHA = 'c24ff6e75a987945399b0d96129f5d1a72525fa0270f31b0c481f9780f84db8e'
39 ORIGINAL_CERT = '4ef990d647fc98ac41113d5dbe7ee476ba80bf95b71b5f219b7863fa95263391'
40 DATABASE = 'databases/lifeguide_standalone_v1.sqlite'
41 PROFILE = 'Fictional آزمایشی'
42 CHOICE = 'shared_prefs/lifeguide_device_planner_reminders_v1.xml'
43 REMINDERS = 'shared_prefs/lifeguide_local_reminders_v1.xml'
44 TABLE_ORDER = {'local_profiles': 'singleton', 'local_plans': 'id',
45 'local_weekly_slots': 'plan_id,weekday', 'local_occurrences': 'id'}
46 LIMITATIONS = {name: 'UNVERIFIED' for name in (
47 'physicalDevice', 'Windows', 'USB', 'ownerSigningKey', 'ownerData',
48 'originalNotificationsEnabled', 'Doze', 'reboot', 'soundOrVibration',
49 'powerLossOrFullDisk', 'distributionApk')}
50
51
52 def digest(raw):
53 return hashlib.sha256(raw).hexdigest()
54
55
56 def binary_adb(serial, remote, data=None):
57 """Bound both pipes while keeping SQLite/PNG bytes out of text decoding/logs."""
58 validate_serial(serial)
59 require(data is None or isinstance(data, bytes) and len(data) <= MAX_PAYLOAD_BYTES,
60 'binary_input_limit')
61 process = None
62 try:
63 direction = 'exec-in' if data is not None else 'exec-out'
64 process = subprocess.Popen(['adb', '-s', serial, direction, remote],
65 stdin=subprocess.PIPE if data is not None else subprocess.DEVNULL,
66 stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
67 result, sent = bytearray(), 0
68 with selectors.DefaultSelector() as poller:
69 os.set_blocking(process.stdout.fileno(), False)
70 poller.register(process.stdout, selectors.EVENT_READ, 'read')
71 if data:
72 os.set_blocking(process.stdin.fileno(), False)
73 poller.register(process.stdin, selectors.EVENT_WRITE, 'write')
74 elif data is not None:
75 process.stdin.close()
76 deadline = time.monotonic() + 30
77 while poller.get_map():
78 require(time.monotonic() < deadline, 'binary_adb_timeout')
79 for key, _ in poller.select(0.2):
80 if key.data == 'read':
81 chunk = os.read(key.fd, min(65536, MAX_PAYLOAD_BYTES + 1 - len(result)))
82 if not chunk:
83 poller.unregister(key.fileobj)
84 else:
85 result.extend(chunk)
86 require(len(result) <= MAX_PAYLOAD_BYTES, 'binary_output_limit')
87 else:
88 sent += os.write(key.fd, data[sent:sent + 65536])
89 if sent == len(data):
90 poller.unregister(key.fileobj)
91 process.stdin.close()
92 require(process.wait(timeout=max(0.01, deadline - time.monotonic())) == 0,
93 'binary_adb_failed')
94 return bytes(result)
95 except (OSError, subprocess.SubprocessError):
96 raise AcceptanceError('binary_adb_failed') from None
97 finally:
98 if process is not None:
99 if process.poll() is None:
100 process.kill()
101 process.wait()
102 for pipe in (process.stdin, process.stdout):
103 if pipe is not None:
104 pipe.close()
105
106
107 def notification_preferences_off(xml, *, choice):
108 try:
109 require(isinstance(xml, str) and len(xml) <= 32768 and '<!' not in xml,
110 'notification_state_not_off')
111 root = ET.fromstring(xml)
112 require(root.tag == 'map' and not root.attrib and not (root.text or '').strip(),
113 'notification_state_not_off')
114 if len(root) == 0:
115 return True
116 require(choice and len(root) == 1 and root[0].tag == 'boolean' and
117 root[0].attrib == {'name': 'enabled', 'value': 'false'} and
118 len(root[0]) == 0 and not (root[0].text or '').strip() and
119 not (root[0].tail or '').strip(), 'notification_state_not_off')
120 return True
121 except (ET.ParseError, TypeError, ValueError):
122 raise AcceptanceError('notification_state_not_off') from None
123
124
125 def normalized_snapshot(source, destination):
126 """Normalize only a private host copy of a closed, sidecar-free owned DB.
127
128 Android may leave a WAL-mode header after its last close without WAL/SHM.
129 Immutable read-only backup reads that complete main file without touching it.
130 DELETE journaling is selected exclusively on the separate host test copy.
131 """
132 source, destination = Path(source), Path(destination)
133 before = read_bounded(source, MAX_PAYLOAD_BYTES)
134 require(before[:16] == b'SQLite format 3\0' and len(before) >= 100,
135 'captured_database_invalid')
136 require(all(not Path(str(source) + suffix).exists() for suffix in ('-wal', '-shm', '-journal')),
137 'host_source_sidecar_present')
138 publish_new(destination, b'')
139 try:
140 with sqlite3.connect(source.resolve().as_uri() + '?mode=ro&immutable=1', uri=True) as src:
141 require(src.execute('PRAGMA application_id').fetchone() == (FIXTURE_APPLICATION_ID,)
142 and src.execute('PRAGMA user_version').fetchone() == (1,),
143 'synthetic_database_marker_required')
144 with sqlite3.connect(destination) as dst:
145 src.backup(dst)
146 require(dst.execute('PRAGMA journal_mode=DELETE').fetchone() == ('delete',),
147 'host_copy_normalization_failed')
148 return export_fixture(destination)
149 finally:
150 require(read_bounded(source, MAX_PAYLOAD_BYTES) == before, 'host_source_bytes_changed')
151
152
153 def independent_sql(path):
154 """All columns and IDs, using separate SELECTs independent of snapshot JSON."""
155 with sqlite3.connect(Path(path).resolve().as_uri() + '?mode=ro&immutable=1', uri=True) as db:
156 require(db.execute('PRAGMA quick_check').fetchall() == [('ok',)] and
157 not db.execute('PRAGMA foreign_key_check').fetchall(), 'independent_sql_failed')
158 return {table: db.execute(f'SELECT * FROM {table} ORDER BY {order}').fetchall()
159 for table, order in TABLE_ORDER.items()}
160
161
162 class Harness:
163 def __init__(self, *, serial, original_apk, qa_apk, upgrade_apk, acknowledge, output,
164 adb=None, original_check=original_manifest_check, qa_check=qa_manifest_check,
165 certificate_check=certificate_digest, clock=time.monotonic, sleep=time.sleep):
166 self.serial, self.acknowledge, self.output = serial, acknowledge, Path(output)
167 self.paths = [Path(p) for p in (original_apk, qa_apk, upgrade_apk)]
168 self.adb, self.original_check, self.qa_check = adb, original_check, qa_check
169 self.certificate_check, self.clock, self.sleep = certificate_check, clock, sleep
170 self.owned, self.seeded, self.launched = set(), set(), set()
171 self.gated = False
172 self.receipt = {'schemaVersion': 1, 'result': 'FAIL', 'syntheticDataOnly': True,
173 'currentPhase': 'preflight', 'checks': {}, 'limitations': LIMITATIONS.copy()}
174
175 def binary(self, remote, data=None):
176 return binary_adb(self.serial, remote, data)
177
178 def preflight(self):
179 validate_serial(self.serial)
180 require(self.acknowledge is True, 'synthetic_emulator_acknowledgement_required')
181 require(all(p.is_file() and not p.is_symlink() for p in self.paths), 'three_apk_files_required')
182 try:
183 reports = [self.original_check(self.paths[0])]
184 require(reports[0].get('result') == 'PASS' and
185 reports[0].get('package') == ORIGINAL and reports[0].get('versionCode') == 9
186 and reports[0].get('versionName') == '0.7.2-personal.1'
187 and reports[0].get('sha256') == ORIGINAL_SHA, 'original_apk_rejected')
188 for path, code in zip(self.paths[1:], (10, 11)):
189 report = self.qa_check(path, expected_code=code)
190 require(report.get('result') == 'PASS' and report.get('package') == QA
191 and report.get('versionCode') == code
192 and report.get('versionName') == f'0.7.2-recovery-qa.{code}'
193 and re.fullmatch('[0-9a-f]{64}', report.get('sha256', '')),
194 'qa_apk_rejected')
195 reports.append(report)
196 certificates = [self.certificate_check(p) for p in self.paths]
197 require(certificates[0] == ORIGINAL_CERT, 'original_apk_certificate_rejected')
198 require(all(re.fullmatch('[0-9a-f]{64}', c or '') for c in certificates),
199 'apk_certificate_rejected')
200 require(certificates[1] == certificates[2], 'qa_upgrade_signer_mismatch')
201 require(certificates[1] != ORIGINAL_CERT, 'qa_signer_must_differ_from_original')
202 except AcceptanceError:
203 raise
204 except Exception:
205 raise AcceptanceError('apk_inspection_failed') from None
206 if self.adb is None:
207 self.adb = Adb(self.serial)
208 require(self.adb.command('get-state').strip() == 'device', 'emulator_not_ready')
209 require('1' in (self.adb.shell('getprop', 'ro.kernel.qemu').strip(),
210 self.adb.shell('getprop', 'ro.boot.qemu').strip()), 'qemu_emulator_required')
211 require(self.adb.shell('getprop', 'ro.hardware').strip() in ('ranchu', 'goldfish'),
212 'android_emulator_hardware_required')
213 require(re.fullmatch(r'sdk_(?:gphone|phone)[A-Za-z0-9_]*',
214 self.adb.shell('getprop', 'ro.product.name').strip()), 'synthetic_sdk_product_required')
215 require(self.adb.shell('getprop', 'ro.build.version.sdk').strip() == '35', 'api_35_required')
216 require(not self.adb.shell('pm', 'list', 'packages', 'ir.lifeguide.app').strip(),
217 'fresh_emulator_required_package_already_present')
218 self.gated = True
219 self.receipt['apks'] = {role: {key: report[key] for key in
220 ('package', 'versionCode', 'versionName', 'sha256')}
221 for role, report in zip(('original', 'qaNeverDistribute', 'upgradeNeverDistribute'), reports)}
222 self.receipt['certificatesSha256'] = certificates
223 self.receipt['checks']['allApksAndFreshEmulatorGatedBeforeInstall'] = 'PASS'
224
225 def _owned(self, package):
226 require(package in (ORIGINAL, QA) and package in self.owned, 'package_not_owned_by_this_runner')
227
228 def install(self, package, *, upgrade=False):
229 require(self.gated, 'preflight_required')
230 require(package in (ORIGINAL, QA), 'unexpected_package')
231 require((package == QA and package in self.owned) if upgrade else package not in self.owned,
232 'invalid_install_lifecycle')
233 path = self.paths[2 if upgrade else 0 if package == ORIGINAL else 1]
234 parts = ('install', '-r', str(path)) if upgrade else ('install', str(path))
235 output = self.adb.command(*parts)
236 require('Success' in output.splitlines() and 'Failure' not in output and 'Error' not in output,
237 'apk_install_failed')
238 self.owned.add(package)
239
240 def process_state(self, package):
241 self._owned(package)
242 query = ('pids=$(pidof ' + package + '); code=$?; '
243 'if [ "$code" -eq 0 ] && [ -n "$pids" ]; then printf PRESENT; '
244 'elif [ "$code" -eq 1 ] && [ -z "$pids" ]; then printf ABSENT; else exit 2; fi')
245 state = self.adb.shell('sh', '-c', query).strip()
246 require(state in ('PRESENT', 'ABSENT'), 'process_query_failed')
247 return state
248
249 def _cold(self, package):
250 require(self.process_state(package) == 'ABSENT', 'database_process_must_be_absent')
251 # A terminated read-only Android WAL connection can leave a zero-byte
252 # WAL plus SHM cache. Only a strictly empty WAL has no frames to replay.
253 wal, shm, journal = (DATABASE + suffix for suffix in ('-wal', '-shm', '-journal'))
254 # Android TRUNCATE mode also retains a regular zero-byte journal after
255 # a committed transaction. It has no rollback record to recover.
256 query = (f'if [ -L {wal} ] || [ -L {shm} ] || [ -L {journal} ]; then printf SIDECAR; '
257 f'elif [ -e {journal} ]; then '
258 f'if [ -f {journal} ] && [ ! -s {journal} ] && [ ! -e {wal} ] && [ ! -e {shm} ]; '
259 'then printf EMPTY_JOURNAL; else printf SIDECAR; fi; '
260 f'elif [ ! -e {wal} ] && [ ! -e {shm} ]; then printf CLEAN; '
261 f'elif [ -f {wal} ] && [ ! -s {wal} ] && ( [ ! -e {shm} ] || [ -f {shm} ] ); then '
262 f'if [ -e {shm} ]; then printf EMPTY_WAL_SHM; else printf EMPTY_WAL; fi; '
263 'else printf SIDECAR; fi')
264 output = self.adb.shell('run-as', package, 'sh', '-c', query).strip()
265 if output not in ('CLEAN', 'EMPTY_WAL', 'EMPTY_WAL_SHM', 'EMPTY_JOURNAL'):
266 self._diagnose_cold_files(package)
267 require(output in ('CLEAN', 'EMPTY_WAL', 'EMPTY_WAL_SHM', 'EMPTY_JOURNAL'), 'database_sidecar_present')
268 return output
269
270 def _diagnose_cold_files(self, package):
271 """Metadata only, never file contents; diagnosis cannot mask the refusal."""
272 self.receipt['lastColdFileObservation'] = 'UNAVAILABLE'
273 try:
274 commands = []
275 for label, suffix in (('main', ''), ('wal', '-wal'), ('shm', '-shm'), ('journal', '-journal')):
276 path = DATABASE + suffix
277 commands.append(f'printf "{label} "; '
278 f'if [ -L {path} ]; then echo SYMLINK; '
279 f'elif [ -f {path} ]; then printf "FILE "; stat -c %s {path}; '
280 f'elif [ -e {path} ]; then echo OTHER; else echo ABSENT; fi')
281 raw = self.adb.shell('run-as', package, 'sh', '-c', '; '.join(commands))
282 require(len(raw) <= 256, 'invalid_file_metadata')
283 report = {}
284 for line in raw.splitlines():
285 match = re.fullmatch(r'(main|wal|shm|journal) (ABSENT|SYMLINK|OTHER|FILE ([0-9]{1,12}))', line)
286 require(match is not None and match[1] not in report, 'invalid_file_metadata')
287 report[match[1]] = ({'kind': 'FILE', 'bytes': int(match[3])} if match[3]
288 else {'kind': match[2]})
289 require(set(report) == {'main', 'wal', 'shm', 'journal'}, 'invalid_file_metadata')
290 self.receipt['lastColdFileObservation'] = report
291 except Exception:
292 pass
293
294 def _remote(self, package, script):
295 self._owned(package)
296 return 'run-as ' + package + ' sh -c ' + shlex.quote(script)
297
298 def seed(self, package, raw):
299 self._owned(package)
300 require(package not in self.launched and package not in self.seeded, 'seed_before_first_launch_only')
301 require(isinstance(raw, bytes) and 100 <= len(raw) <= MAX_PAYLOAD_BYTES and
302 raw[:16] == b'SQLite format 3\0' and
303 int.from_bytes(raw[68:72], 'big') == FIXTURE_APPLICATION_ID, 'synthetic_seed_required')
304 self._cold(package)
305 tests = ' && '.join('test ! -e ' + DATABASE + suffix for suffix in ('', '-wal', '-shm', '-journal'))
306 script = f'set -C; umask 077; mkdir -p databases && {tests} && cat > {DATABASE}'
307 self.binary(self._remote(package, script), raw)
308 self.seeded.add(package)
309 require(self.capture(package) == raw, 'seed_bytes_not_confirmed')
310
311 def capture(self, package):
312 before = self._cold(package)
313 raw = self.binary(self._remote(package, 'cat ' + DATABASE))
314 require(self._cold(package) == before, 'database_cache_shape_changed')
315 self.receipt.setdefault('coldCaptureStates', {})[package] = before
316 require(100 <= len(raw) <= MAX_PAYLOAD_BYTES and raw[:16] == b'SQLite format 3\0'
317 and int.from_bytes(raw[68:72], 'big') == FIXTURE_APPLICATION_ID,
318 'captured_database_invalid')
319 return raw
320
321 def profile_visible(self, package):
322 self._owned(package)
323 path = '/data/local/tmp/lifeguide-recovery-' + secrets.token_hex(12) + '.xml'
324 try:
325 self.adb.shell('uiautomator', 'dump', path)
326 xml = self.adb.shell('cat', path)
327 require(len(xml) <= MAX_PAYLOAD_BYTES and '<!' not in xml, 'invalid_ui_hierarchy')
328 root = ET.fromstring(xml)
329 require(root.tag == 'hierarchy' and len(root) > 0 and
330 all(node.tag == 'node' for node in root.iter() if node is not root),
331 'invalid_ui_hierarchy')
332 nodes = list(root.iter('node'))
333 owned = [node for node in nodes if node.attrib.get('package') == package]
334 labels = (PROFILE, 'سلام ' + PROFILE)
335 observation = {'package': package, 'nodeCount': len(nodes),
336 'ownedPackageNodeCount': len(owned),
337 'exactTextMatch': any(node.attrib.get('text') in labels for node in owned),
338 'exactContentDescriptionMatch': any(
339 node.attrib.get('content-desc') in labels for node in owned)}
340 self.receipt['lastUiObservation'] = observation
341 return observation['exactTextMatch'] or observation['exactContentDescriptionMatch']
342 except ET.ParseError:
343 raise AcceptanceError('invalid_ui_hierarchy') from None
344 finally:
345 self.adb.shell('rm', path)
346
347 def launch(self, package):
348 self._owned(package)
349 require(package in self.seeded, 'seed_required_before_launch')
350 component = package + '/ir.lifeguide.app.MainActivity'
351 output = self.adb.shell('am', 'start', '-W', '-f', '0x10008000', '-n', component)
352 require('Error' not in output and 'Exception' not in output, 'ordinary_ui_launch_failed')
353 self.launched.add(package)
354 deadline = self.clock() + 30
355 while not self.profile_visible(package):
356 if self.clock() >= deadline:
357 try:
358 self.screenshot('ui-failure-original' if package == ORIGINAL else 'ui-failure-qa')
359 except Exception:
360 self.receipt['uiFailureScreenshot'] = 'UNAVAILABLE'
361 raise AcceptanceError('real_profile_ui_not_visible')
362 self.sleep(0.5)
363 require(self.process_state(package) == 'PRESENT', 'ordinary_ui_process_missing')
364
365 def close(self, package):
366 self._owned(package)
367 self.adb.shell('input', 'keyevent', 'KEYCODE_HOME')
368 deadline = self.clock() + 15
369 while True:
370 self.adb.shell('am', 'kill', package)
371 if self.process_state(package) == 'ABSENT':
372 return
373 require(self.clock() < deadline, 'ordinary_process_exit_failed')
374 self.sleep(0.25)
375
376 def notifications_off(self):
377 self._cold(QA)
378 for path, choice in ((CHOICE, True), (REMINDERS, False)):
379 script = f'if [ -e {path} ]; then cat {path}; else printf "<map/>"; fi'
380 raw = self.binary(self._remote(QA, script))
381 try:
382 xml = raw.decode('utf-8')
383 except UnicodeError:
384 raise AcceptanceError('notification_state_not_off') from None
385 notification_preferences_off(xml, choice=choice)
386 package_dump = self.adb.shell('dumpsys', 'package', QA)
387 permission_states = re.findall(
388 r'(?m)^\s*android\.permission\.POST_NOTIFICATIONS: granted=(true|false)(?=,|\s*$)',
389 package_dump)
390 require(permission_states == ['false'], 'qa_notification_permission_not_denied')
391 for line in self.adb.shell('cmd', 'notification', 'list').splitlines():
392 require(QA not in line.split('|'), 'qa_os_notification_present')
393 self._cold(QA)
394
395 def screenshot(self, kind='ordinary'):
396 require(self.gated and bool(self.seeded & self.launched) and
397 kind in ('ordinary', 'qa-restored', 'ui-failure-original', 'ui-failure-qa'),
398 'synthetic_screenshot_boundary_required')
399 raw = self.binary('screencap -p')
400 require(24 <= len(raw) <= MAX_PAYLOAD_BYTES and raw[:8] == b'\x89PNG\r\n\x1a\n'
401 and raw[12:16] == b'IHDR', 'fictional_screenshot_failed')
402 width, height = struct.unpack('>II', raw[16:24])
403 require(100 <= width <= 4096 and 100 <= height <= 4096, 'fictional_screenshot_failed')
404 path = (self.output.with_suffix('.png') if kind == 'ordinary' else
405 self.output.with_name(self.output.stem + '-' + kind + '.png'))
406 publish_new(path, raw)
407 self.receipt.setdefault('fictionalScreenshotsSha256', {})[path.name] = digest(raw)
408
409 def run(self):
410 self.preflight()
411 with tempfile.TemporaryDirectory(prefix='lifeguide-synthetic-recovery-') as directory:
412 private = Path(directory)
413 os.chmod(private, 0o700)
414 reference = private / 'fixture.sqlite'
415 fixture = create_sample_database()
416 publish_new(reference, fixture)
417 expected, sql = export_fixture(reference), independent_sql(reference)
418 self.receipt['counts'] = {table: len(rows) for table, rows in sql.items()}
419 self.receipt['canonicalSnapshotSha256'] = digest(expected)
420 self.receipt['currentPhase'] = 'original_seed_and_ordinary_ui'
421 self.install(ORIGINAL)
422 self.seed(ORIGINAL, fixture)
423 self.launch(ORIGINAL)
424 self.screenshot()
425 self.close(ORIGINAL)
426 original = self.capture(ORIGINAL)
427 source = private / 'closed-original.sqlite'
428 publish_new(source, original)
429 snapshot = normalized_snapshot(source, private / 'original-copy.sqlite')
430 require(snapshot == expected and independent_sql(private / 'original-copy.sqlite') == sql,
431 'original_full_field_mismatch')
432 passphrase = secrets.token_urlsafe(32)
433 archive = seal(snapshot, passphrase)
434 restored = database_from_snapshot(open_archive(archive, passphrase))
435 del passphrase
436 require(source.read_bytes() == original, 'host_source_bytes_changed')
437 self.receipt['checks']['hostEncryptedFullFieldRoundTripSourceUnchanged'] = 'PASS'
438 self.receipt['currentPhase'] = 'side_by_side_restore'
439 self.install(QA)
440 self.seed(QA, restored)
441
442 def verify_cycle(phase):
443 self.receipt['currentPhase'] = phase
444 for package, role in ((ORIGINAL, 'original'), (QA, 'qa')):
445 self.launch(package)
446 if phase == 'both_apps_after_first_close' and package == QA:
447 self.screenshot('qa-restored')
448 self.close(package)
449 raw = self.capture(package)
450 captured = private / (phase + '-' + role + '.sqlite')
451 copied = private / (phase + '-' + role + '-copy.sqlite')
452 publish_new(captured, raw)
453 actual = normalized_snapshot(captured, copied)
454 require(actual == expected and independent_sql(copied) == sql,
455 'full_field_or_independent_sql_mismatch')
456 if package == ORIGINAL:
457 require(raw == original, 'original_source_bytes_changed')
458 self.notifications_off()
459 self.receipt['checks'][phase] = 'PASS'
460
461 verify_cycle('both_apps_after_first_close')
462 verify_cycle('both_apps_after_reopen')
463 self.receipt['currentPhase'] = 'qa_same_test_key_upgrade'
464 self.install(QA, upgrade=True)
465 verify_cycle('both_apps_after_qa_upgrade')
466 verify_cycle('both_apps_after_upgrade_reopen')
467 require(source.read_bytes() == original, 'host_source_bytes_changed')
468 self.receipt['checks']['qaNotificationsDefaultOffNoConsentTransferred'] = 'PASS'
469 self.receipt['checks']['originalSourceBytesUnchangedAcrossRestoreAndUpgrade'] = 'PASS'
470 self.receipt['originalClosedDatabaseSha256'] = digest(original)
471 self.receipt.update(result='PASS', currentPhase='complete')
472 return self.receipt
473
474
475 def main(argv=None):
476 parser = argparse.ArgumentParser(description=__doc__)
477 parser.add_argument('--serial', required=True)
478 parser.add_argument('--original-apk', type=Path, required=True)
479 parser.add_argument('--qa-apk', type=Path, required=True)
480 parser.add_argument('--upgrade-apk', type=Path, required=True)
481 parser.add_argument('--acknowledge-synthetic-emulator-only', action='store_true')
482 parser.add_argument('--output', type=Path, required=True)
483 args = parser.parse_args(argv)
484 runner = Harness(serial=args.serial, original_apk=args.original_apk, qa_apk=args.qa_apk,
485 upgrade_apk=args.upgrade_apk, acknowledge=args.acknowledge_synthetic_emulator_only,
486 output=args.output)
487 code = 0
488 try:
489 args.output.parent.mkdir(parents=True, mode=0o700, exist_ok=True)
490 runner.run()
491 except (AcceptanceError, RecoveryError) as error:
492 runner.receipt['errorCode'] = error.code if isinstance(error, RecoveryError) else str(error)
493 code = 2
494 except KeyboardInterrupt:
495 runner.receipt['errorCode'], code = 'interrupted', 130
496 except Exception:
497 runner.receipt['errorCode'], code = 'host_acceptance_failed', 2
498 try:
499 publish_new(args.output, (json.dumps(runner.receipt, sort_keys=True, indent=2) + '\n').encode())
500 except (OSError, RecoveryError):
501 print(json.dumps({'result': 'FAIL', 'errorCode': 'receipt_publication_failed',
502 'syntheticDataOnly': True}))
503 return 2
504 print(json.dumps({'result': runner.receipt['result'], 'currentPhase': runner.receipt['currentPhase'],
505 **({'errorCode': runner.receipt['errorCode']} if code else {})}))
506 return code
507
508
509 if __name__ == '__main__':
510 raise SystemExit(main())