@davoodmehraban89 / LifeMate / commits / 06d8452
Fork 0

LifeMate — Personal, Family & Learning Companion

test: rehearse original-to-sidecar recovery and default-database upgrade on API35

Quinn White committed Oct 22, 2026 at 06:19 UTC 06d8452cb0c54ef31c56e486b9d1e4bb9e842756
4 files changed +798 -1
.github/workflows/personal-recovery-android.yml new
+121
@@ -0,0 +1,121 @@
1 +name: LifeGuide personal recovery emulator QA
2 +on:
3 + push:
4 + branches: [test/personal-recovery-acceptance]
5 + pull_request:
6 + paths:
7 + - .github/workflows/personal-recovery-android.yml
8 + - apps/lifemate/tool/*personal_recovery*
9 + - apps/lifemate/android/app/src/recoveryQa/**
10 + workflow_dispatch:
11 +permissions:
12 + contents: read
13 + actions: read
14 +concurrency:
15 + group: lifeguide-recovery-qa-${{ github.ref }}
16 + cancel-in-progress: true
17 +jobs:
18 + synthetic-emulator:
19 + runs-on: ubuntu-latest
20 + timeout-minutes: 40
21 + defaults:
22 + run: {working-directory: apps/lifemate}
23 + env:
24 + ORG_GRADLE_PROJECT_lifeguideDevicePlanner: 'true'
25 + ORG_GRADLE_PROJECT_lifeguidePersonalRecoveryQa: 'true'
26 + steps:
27 + - uses: actions/checkout@v4
28 + - uses: actions/setup-python@v5
29 + with: {python-version: '3.11'}
30 + - run: python -m pip install -r ../../requirements-personal-recovery.txt
31 + - uses: actions/setup-java@v4
32 + with: {distribution: temurin, java-version: '17'}
33 + - uses: subosito/flutter-action@v2
34 + with: {flutter-version: '3.47.6', channel: stable, cache: true}
35 + - run: flutter pub get
36 + - name: Host safety and ordinary planner checks
37 + run: |
38 + dart format --output=none --set-exit-if-changed tool/personal_recovery_fixture.dart
39 + flutter analyze
40 + flutter test
41 + python -m unittest discover -s tool -p '*_test.py' -v
42 + cd ../..
43 + python -m unittest discover -s scripts/tests -p 'test_recovery*.py' -v
44 + - name: Retrieve exact original delivered APK, never a rebuilt substitute
45 + uses: actions/download-artifact@v4
46 + with:
47 + artifact-ids: '12292340083'
48 + run-id: '39480587450'
49 + github-token: ${{ github.token }}
50 + repository: davoodmehraban89/LifeMate
51 + path: apps/lifemate/build/original-delivered
52 + merge-multiple: true
53 + - name: Build two private QA versions with the same ephemeral test signer
54 + run: |
55 + for code in 10 11; do
56 + flutter build apk --debug --target=tool/personal_recovery_fixture.dart --dart-define=LIFEGUIDE_STANDALONE=true --dart-define=LIFEGUIDE_PERSONAL_RECOVERY_QA=true --build-name="0.7.2-recovery-qa.$code" --build-number="$code"
57 + cp build/app/outputs/flutter-apk/app-debug.apk "build/recovery-qa-$code.apk"
58 + python tool/check_personal_recovery_apk.py "build/recovery-qa-$code.apk" --expected-code "$code"
59 + done
60 + - name: Actually reject unsafe QA build combinations
61 + working-directory: apps/lifemate/android
62 + shell: bash
63 + run: |
64 + set -euo pipefail
65 + defines=$(python -c 'import base64; print(",".join(base64.b64encode(x.encode()).decode() for x in ("LIFEGUIDE_STANDALONE=true", "LIFEGUIDE_PERSONAL_RECOVERY_QA=true")))')
66 + expect_refusal() {
67 + reason="$1"
68 + shift
69 + log_file=$(mktemp)
70 + if "$@" > "$log_file" 2>&1; then
71 + rm -f "$log_file"
72 + echo 'FAIL: forbidden build unexpectedly succeeded'
73 + exit 1
74 + fi
75 + if ! grep -Fq "$reason" "$log_file"; then
76 + tail -n 40 "$log_file"
77 + rm -f "$log_file"
78 + echo 'FAIL: build failed without the expected safety refusal'
79 + exit 1
80 + fi
81 + rm -f "$log_file"
82 + echo "PASS: $reason"
83 + }
84 + expect_refusal 'requires the isolated device planner' ./gradlew :app:assembleDebug -PlifeguideDevicePlanner=false --console=plain
85 + expect_refusal 'requires its matching defines and entry point' ./gradlew :app:assembleDebug --console=plain
86 + expect_refusal 'cannot be packaged as a user application' ./gradlew :app:assembleDebug -PlifeguidePersonalRecoveryQa=false -Ptarget=tool/personal_recovery_fixture.dart -Pdart-defines="$defines" --console=plain
87 + expect_refusal 'debug-only initial edition' ./gradlew :app:assembleRelease -Ptarget=tool/personal_recovery_fixture.dart -Pdart-defines="$defines" --console=plain
88 + for task in :app:installDebug :app:packageDebug :app:build; do
89 + expect_refusal 'request assembleDebug explicitly' ./gradlew "$task" -Ptarget=tool/personal_recovery_fixture.dart -Pdart-defines="$defines" --console=plain
90 + done
91 + expect_refusal 'versions 10 and 11' bash -c 'cd ..; flutter build apk --debug --target=tool/personal_recovery_fixture.dart --dart-define=LIFEGUIDE_STANDALONE=true --dart-define=LIFEGUIDE_PERSONAL_RECOVERY_QA=true --build-number=12 --build-name=0.7.2-recovery-qa.12'
92 + - name: Enable KVM for a newly created synthetic SDK emulator
93 + run: |
94 + test -c /dev/kvm
95 + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
96 + sudo udevadm control --reload-rules
97 + sudo udevadm trigger --name-match=kvm
98 + - name: Exact old install, side-by-side recovery and new-app upgrade
99 + uses: reactivecircus/android-emulator-runner@a421e43855164a8197daf9d8d40fe71c6996bb0d
100 + with:
101 + api-level: 35
102 + target: google_apis
103 + arch: x86_64
104 + profile: pixel_6
105 + emulator-port: 5554
106 + avd-name: lifeguide-recovery-synthetic
107 + force-avd-creation: true
108 + emulator-options: -no-window -gpu swiftshader_indirect -no-snapshot -wipe-data -noaudio -no-boot-anim -camera-back none
109 + working-directory: apps/lifemate
110 + script: python tool/test_personal_recovery_android.py --serial emulator-5554 --original-apk build/original-delivered/LifeGuide.apk --qa-apk build/recovery-qa-10.apk --upgrade-apk build/recovery-qa-11.apk --acknowledge-synthetic-emulator-only --output exports/personal-recovery-android.json
111 + - name: Preserve only sanitized receipts and fictional screenshots
112 + if: always()
113 + uses: actions/upload-artifact@v4
114 + with:
115 + name: LifeGuide-synthetic-Android-recovery-verification
116 + path: |
117 + apps/lifemate/exports/personal-recovery-android.json
118 + apps/lifemate/exports/*.png
119 + if-no-files-found: warn
120 + retention-days: 14
121 + # No APK, SQLite, encrypted archive, private key or owner data is uploaded.
apps/lifemate/android/app/build.gradle.kts
+1 -1
@@ -33,7 +33,7 @@ if (personalRecoveryQa && (requestedTasks.isEmpty() || requestedTasks.any { it !
33 if (personalRecoveryQa && !(standaloneDefine && recoveryDefine && recoveryTarget)) {
34 throw GradleException("Synthetic recovery QA requires its matching defines and entry point.")
35 }
36 -if (assembling && !personalRecoveryQa && (recoveryDefine || recoveryTarget)) {
36 +if (!personalRecoveryQa && (recoveryDefine || recoveryTarget)) {
37 throw GradleException("Recovery fixtures cannot be packaged as a user application.")
38 }
39 if (devicePlannerOnly) {
apps/lifemate/tool/test_personal_recovery_android.py new
+449
@@ -0,0 +1,449 @@
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 + process = subprocess.Popen(['adb', '-s', serial, 'exec-out', remote],
64 + stdin=subprocess.PIPE if data is not None else subprocess.DEVNULL,
65 + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
66 + result, sent = bytearray(), 0
67 + with selectors.DefaultSelector() as poller:
68 + os.set_blocking(process.stdout.fileno(), False)
69 + poller.register(process.stdout, selectors.EVENT_READ, 'read')
70 + if data:
71 + os.set_blocking(process.stdin.fileno(), False)
72 + poller.register(process.stdin, selectors.EVENT_WRITE, 'write')
73 + elif data is not None:
74 + process.stdin.close()
75 + deadline = time.monotonic() + 30
76 + while poller.get_map():
77 + require(time.monotonic() < deadline, 'binary_adb_timeout')
78 + for key, _ in poller.select(0.2):
79 + if key.data == 'read':
80 + chunk = os.read(key.fd, min(65536, MAX_PAYLOAD_BYTES + 1 - len(result)))
81 + if not chunk:
82 + poller.unregister(key.fileobj)
83 + else:
84 + result.extend(chunk)
85 + require(len(result) <= MAX_PAYLOAD_BYTES, 'binary_output_limit')
86 + else:
87 + sent += os.write(key.fd, data[sent:sent + 65536])
88 + if sent == len(data):
89 + poller.unregister(key.fileobj)
90 + process.stdin.close()
91 + require(process.wait(timeout=max(0.01, deadline - time.monotonic())) == 0,
92 + 'binary_adb_failed')
93 + return bytes(result)
94 + except (OSError, subprocess.SubprocessError):
95 + raise AcceptanceError('binary_adb_failed') from None
96 + finally:
97 + if process is not None:
98 + if process.poll() is None:
99 + process.kill()
100 + process.wait()
101 + for pipe in (process.stdin, process.stdout):
102 + if pipe is not None:
103 + pipe.close()
104 +
105 +
106 +def notification_preferences_off(xml, *, choice):
107 + try:
108 + require(isinstance(xml, str) and len(xml) <= 32768 and '<!' not in xml,
109 + 'notification_state_not_off')
110 + root = ET.fromstring(xml)
111 + require(root.tag == 'map' and not root.attrib and not (root.text or '').strip(),
112 + 'notification_state_not_off')
113 + if len(root) == 0:
114 + return True
115 + require(choice and len(root) == 1 and root[0].tag == 'boolean' and
116 + root[0].attrib == {'name': 'enabled', 'value': 'false'} and
117 + len(root[0]) == 0 and not (root[0].text or '').strip() and
118 + not (root[0].tail or '').strip(), 'notification_state_not_off')
119 + return True
120 + except (ET.ParseError, TypeError, ValueError):
121 + raise AcceptanceError('notification_state_not_off') from None
122 +
123 +
124 +def normalized_snapshot(source, destination):
125 + """Normalize only a private host copy of a closed, sidecar-free owned DB.
126 +
127 + Android may leave a WAL-mode header after its last close without WAL/SHM.
128 + Immutable read-only backup reads that complete main file without touching it.
129 + DELETE journaling is selected exclusively on the separate host test copy.
130 + """
131 + source, destination = Path(source), Path(destination)
132 + before = read_bounded(source, MAX_PAYLOAD_BYTES)
133 + require(before[:16] == b'SQLite format 3\0' and len(before) >= 100,
134 + 'captured_database_invalid')
135 + require(all(not Path(str(source) + suffix).exists() for suffix in ('-wal', '-shm', '-journal')),
136 + 'host_source_sidecar_present')
137 + publish_new(destination, b'')
138 + try:
139 + with sqlite3.connect(source.resolve().as_uri() + '?mode=ro&immutable=1', uri=True) as src:
140 + require(src.execute('PRAGMA application_id').fetchone() == (FIXTURE_APPLICATION_ID,)
141 + and src.execute('PRAGMA user_version').fetchone() == (1,),
142 + 'synthetic_database_marker_required')
143 + with sqlite3.connect(destination) as dst:
144 + src.backup(dst)
145 + require(dst.execute('PRAGMA journal_mode=DELETE').fetchone() == ('delete',),
146 + 'host_copy_normalization_failed')
147 + return export_fixture(destination)
148 + finally:
149 + require(read_bounded(source, MAX_PAYLOAD_BYTES) == before, 'host_source_bytes_changed')
150 +
151 +
152 +def independent_sql(path):
153 + """All columns and IDs, using separate SELECTs independent of snapshot JSON."""
154 + with sqlite3.connect(Path(path).resolve().as_uri() + '?mode=ro&immutable=1', uri=True) as db:
155 + require(db.execute('PRAGMA quick_check').fetchall() == [('ok',)] and
156 + not db.execute('PRAGMA foreign_key_check').fetchall(), 'independent_sql_failed')
157 + return {table: db.execute(f'SELECT * FROM {table} ORDER BY {order}').fetchall()
158 + for table, order in TABLE_ORDER.items()}
159 +
160 +
161 +class Harness:
162 + def __init__(self, *, serial, original_apk, qa_apk, upgrade_apk, acknowledge, output,
163 + adb=None, original_check=original_manifest_check, qa_check=qa_manifest_check,
164 + certificate_check=certificate_digest, clock=time.monotonic, sleep=time.sleep):
165 + self.serial, self.acknowledge, self.output = serial, acknowledge, Path(output)
166 + self.paths = [Path(p) for p in (original_apk, qa_apk, upgrade_apk)]
167 + self.adb, self.original_check, self.qa_check = adb, original_check, qa_check
168 + self.certificate_check, self.clock, self.sleep = certificate_check, clock, sleep
169 + self.owned, self.seeded, self.launched = set(), set(), set()
170 + self.gated = False
171 + self.receipt = {'schemaVersion': 1, 'result': 'FAIL', 'syntheticDataOnly': True,
172 + 'currentPhase': 'preflight', 'checks': {}, 'limitations': LIMITATIONS.copy()}
173 +
174 + def binary(self, remote, data=None):
175 + return binary_adb(self.serial, remote, data)
176 +
177 + def preflight(self):
178 + validate_serial(self.serial)
179 + require(self.acknowledge is True, 'synthetic_emulator_acknowledgement_required')
180 + require(all(p.is_file() and not p.is_symlink() for p in self.paths), 'three_apk_files_required')
181 + try:
182 + reports = [self.original_check(self.paths[0])]
183 + require(reports[0].get('result') == 'PASS' and
184 + reports[0].get('package') == ORIGINAL and reports[0].get('versionCode') == 9
185 + and reports[0].get('versionName') == '0.7.2-personal.1'
186 + and reports[0].get('sha256') == ORIGINAL_SHA, 'original_apk_rejected')
187 + for path, code in zip(self.paths[1:], (10, 11)):
188 + report = self.qa_check(path, expected_code=code)
189 + require(report.get('result') == 'PASS' and report.get('package') == QA
190 + and report.get('versionCode') == code
191 + and report.get('versionName') == f'0.7.2-recovery-qa.{code}'
192 + and re.fullmatch('[0-9a-f]{64}', report.get('sha256', '')),
193 + 'qa_apk_rejected')
194 + reports.append(report)
195 + certificates = [self.certificate_check(p) for p in self.paths]
196 + require(certificates[0] == ORIGINAL_CERT, 'original_apk_certificate_rejected')
197 + require(all(re.fullmatch('[0-9a-f]{64}', c or '') for c in certificates),
198 + 'apk_certificate_rejected')
199 + require(certificates[1] == certificates[2], 'qa_upgrade_signer_mismatch')
200 + require(certificates[1] != ORIGINAL_CERT, 'qa_signer_must_differ_from_original')
201 + except AcceptanceError:
202 + raise
203 + except Exception:
204 + raise AcceptanceError('apk_inspection_failed') from None
205 + if self.adb is None:
206 + self.adb = Adb(self.serial)
207 + require(self.adb.command('get-state').strip() == 'device', 'emulator_not_ready')
208 + require('1' in (self.adb.shell('getprop', 'ro.kernel.qemu').strip(),
209 + self.adb.shell('getprop', 'ro.boot.qemu').strip()), 'qemu_emulator_required')
210 + require(self.adb.shell('getprop', 'ro.hardware').strip() in ('ranchu', 'goldfish'),
211 + 'android_emulator_hardware_required')
212 + require(re.fullmatch(r'sdk_(?:gphone|phone)[A-Za-z0-9_]*',
213 + self.adb.shell('getprop', 'ro.product.name').strip()), 'synthetic_sdk_product_required')
214 + require(self.adb.shell('getprop', 'ro.build.version.sdk').strip() == '35', 'api_35_required')
215 + require(not self.adb.shell('pm', 'list', 'packages', 'ir.lifeguide.app').strip(),
216 + 'fresh_emulator_required_package_already_present')
217 + self.gated = True
218 + self.receipt['apks'] = {role: {key: report[key] for key in
219 + ('package', 'versionCode', 'versionName', 'sha256')}
220 + for role, report in zip(('original', 'qaNeverDistribute', 'upgradeNeverDistribute'), reports)}
221 + self.receipt['certificatesSha256'] = certificates
222 + self.receipt['checks']['allApksAndFreshEmulatorGatedBeforeInstall'] = 'PASS'
223 +
224 + def _owned(self, package):
225 + require(package in (ORIGINAL, QA) and package in self.owned, 'package_not_owned_by_this_runner')
226 +
227 + def install(self, package, *, upgrade=False):
228 + require(self.gated, 'preflight_required')
229 + require(package in (ORIGINAL, QA), 'unexpected_package')
230 + require((package == QA and package in self.owned) if upgrade else package not in self.owned,
231 + 'invalid_install_lifecycle')
232 + path = self.paths[2 if upgrade else 0 if package == ORIGINAL else 1]
233 + parts = ('install', '-r', str(path)) if upgrade else ('install', str(path))
234 + output = self.adb.command(*parts)
235 + require('Success' in output.splitlines() and 'Failure' not in output and 'Error' not in output,
236 + 'apk_install_failed')
237 + self.owned.add(package)
238 +
239 + def process_state(self, package):
240 + self._owned(package)
241 + query = ('pids=$(pidof ' + package + '); code=$?; '
242 + 'if [ "$code" -eq 0 ] && [ -n "$pids" ]; then printf PRESENT; '
243 + 'elif [ "$code" -eq 1 ] && [ -z "$pids" ]; then printf ABSENT; else exit 2; fi')
244 + state = self.adb.shell('sh', '-c', query).strip()
245 + require(state in ('PRESENT', 'ABSENT'), 'process_query_failed')
246 + return state
247 +
248 + def _cold(self, package):
249 + require(self.process_state(package) == 'ABSENT', 'database_process_must_be_absent')
250 + query = ' && '.join('test ! -e ' + DATABASE + suffix for suffix in ('-wal', '-shm', '-journal'))
251 + output = self.adb.shell('run-as', package, 'sh', '-c',
252 + f'if {query}; then printf CLEAN; else printf SIDECAR; fi').strip()
253 + require(output == 'CLEAN', 'database_sidecar_present')
254 +
255 + def _remote(self, package, script):
256 + self._owned(package)
257 + return 'run-as ' + package + ' sh -c ' + shlex.quote(script)
258 +
259 + def seed(self, package, raw):
260 + self._owned(package)
261 + require(package not in self.launched and package not in self.seeded, 'seed_before_first_launch_only')
262 + require(isinstance(raw, bytes) and 100 <= len(raw) <= MAX_PAYLOAD_BYTES and
263 + raw[:16] == b'SQLite format 3\0' and
264 + int.from_bytes(raw[68:72], 'big') == FIXTURE_APPLICATION_ID, 'synthetic_seed_required')
265 + self._cold(package)
266 + tests = ' && '.join('test ! -e ' + DATABASE + suffix for suffix in ('', '-wal', '-shm', '-journal'))
267 + script = f'set -C; umask 077; mkdir -p databases && {tests} && cat > {DATABASE}'
268 + self.binary(self._remote(package, script), raw)
269 + self.seeded.add(package)
270 + require(self.capture(package) == raw, 'seed_bytes_not_confirmed')
271 +
272 + def capture(self, package):
273 + self._cold(package)
274 + raw = self.binary(self._remote(package, 'cat ' + DATABASE))
275 + self._cold(package)
276 + require(100 <= len(raw) <= MAX_PAYLOAD_BYTES and raw[:16] == b'SQLite format 3\0'
277 + and int.from_bytes(raw[68:72], 'big') == FIXTURE_APPLICATION_ID,
278 + 'captured_database_invalid')
279 + return raw
280 +
281 + def profile_visible(self, package):
282 + self._owned(package)
283 + path = '/data/local/tmp/lifeguide-recovery-' + secrets.token_hex(12) + '.xml'
284 + try:
285 + self.adb.shell('uiautomator', 'dump', path)
286 + xml = self.adb.shell('cat', path)
287 + require(len(xml) <= MAX_PAYLOAD_BYTES and '<!' not in xml, 'invalid_ui_hierarchy')
288 + root = ET.fromstring(xml)
289 + require(root.tag == 'hierarchy' and len(root) > 0 and
290 + all(node.tag == 'node' for node in root.iter() if node is not root),
291 + 'invalid_ui_hierarchy')
292 + return any(node.attrib.get('text') in (PROFILE, 'سلام ' + PROFILE)
293 + for node in root.iter('node'))
294 + except ET.ParseError:
295 + raise AcceptanceError('invalid_ui_hierarchy') from None
296 + finally:
297 + self.adb.shell('rm', path)
298 +
299 + def launch(self, package):
300 + self._owned(package)
301 + require(package in self.seeded, 'seed_required_before_launch')
302 + component = package + '/ir.lifeguide.app.MainActivity'
303 + output = self.adb.shell('am', 'start', '-W', '-f', '0x10008000', '-n', component)
304 + require('Error' not in output and 'Exception' not in output, 'ordinary_ui_launch_failed')
305 + self.launched.add(package)
306 + deadline = self.clock() + 30
307 + while not self.profile_visible(package):
308 + require(self.clock() < deadline, 'real_profile_ui_not_visible')
309 + self.sleep(0.5)
310 + require(self.process_state(package) == 'PRESENT', 'ordinary_ui_process_missing')
311 +
312 + def close(self, package):
313 + self._owned(package)
314 + self.adb.shell('input', 'keyevent', 'KEYCODE_HOME')
315 + deadline = self.clock() + 15
316 + while True:
317 + self.adb.shell('am', 'kill', package)
318 + if self.process_state(package) == 'ABSENT':
319 + return
320 + require(self.clock() < deadline, 'ordinary_process_exit_failed')
321 + self.sleep(0.25)
322 +
323 + def notifications_off(self):
324 + self._cold(QA)
325 + for path, choice in ((CHOICE, True), (REMINDERS, False)):
326 + script = f'if [ -e {path} ]; then cat {path}; else printf "<map/>"; fi'
327 + raw = self.binary(self._remote(QA, script))
328 + try:
329 + xml = raw.decode('utf-8')
330 + except UnicodeError:
331 + raise AcceptanceError('notification_state_not_off') from None
332 + notification_preferences_off(xml, choice=choice)
333 + package_dump = self.adb.shell('dumpsys', 'package', QA)
334 + permission_states = re.findall(
335 + r'(?m)^\s*android\.permission\.POST_NOTIFICATIONS: granted=(true|false)(?=,|\s*$)',
336 + package_dump)
337 + require(permission_states == ['false'], 'qa_notification_permission_not_denied')
338 + for line in self.adb.shell('cmd', 'notification', 'list').splitlines():
339 + require(QA not in line.split('|'), 'qa_os_notification_present')
340 + self._cold(QA)
341 +
342 + def screenshot(self):
343 + raw = self.binary('screencap -p')
344 + require(24 <= len(raw) <= MAX_PAYLOAD_BYTES and raw[:8] == b'\x89PNG\r\n\x1a\n'
345 + and raw[12:16] == b'IHDR', 'fictional_screenshot_failed')
346 + width, height = struct.unpack('>II', raw[16:24])
347 + require(100 <= width <= 4096 and 100 <= height <= 4096, 'fictional_screenshot_failed')
348 + publish_new(self.output.with_suffix('.png'), raw)
349 + self.receipt['fictionalUiScreenshotSha256'] = digest(raw)
350 +
351 + def run(self):
352 + self.preflight()
353 + with tempfile.TemporaryDirectory(prefix='lifeguide-synthetic-recovery-') as directory:
354 + private = Path(directory)
355 + os.chmod(private, 0o700)
356 + reference = private / 'fixture.sqlite'
357 + fixture = create_sample_database()
358 + publish_new(reference, fixture)
359 + expected, sql = export_fixture(reference), independent_sql(reference)
360 + self.receipt['counts'] = {table: len(rows) for table, rows in sql.items()}
361 + self.receipt['canonicalSnapshotSha256'] = digest(expected)
362 + self.receipt['currentPhase'] = 'original_seed_and_ordinary_ui'
363 + self.install(ORIGINAL)
364 + self.seed(ORIGINAL, fixture)
365 + self.launch(ORIGINAL)
366 + self.screenshot()
367 + self.close(ORIGINAL)
368 + original = self.capture(ORIGINAL)
369 + source = private / 'closed-original.sqlite'
370 + publish_new(source, original)
371 + snapshot = normalized_snapshot(source, private / 'original-copy.sqlite')
372 + require(snapshot == expected and independent_sql(private / 'original-copy.sqlite') == sql,
373 + 'original_full_field_mismatch')
374 + passphrase = secrets.token_urlsafe(32)
375 + archive = seal(snapshot, passphrase)
376 + restored = database_from_snapshot(open_archive(archive, passphrase))
377 + del passphrase
378 + require(source.read_bytes() == original, 'host_source_bytes_changed')
379 + self.receipt['checks']['hostEncryptedFullFieldRoundTripSourceUnchanged'] = 'PASS'
380 + self.receipt['currentPhase'] = 'side_by_side_restore'
381 + self.install(QA)
382 + self.seed(QA, restored)
383 +
384 + def verify_cycle(phase):
385 + self.receipt['currentPhase'] = phase
386 + for package, role in ((ORIGINAL, 'original'), (QA, 'qa')):
387 + self.launch(package)
388 + self.close(package)
389 + raw = self.capture(package)
390 + captured = private / (phase + '-' + role + '.sqlite')
391 + copied = private / (phase + '-' + role + '-copy.sqlite')
392 + publish_new(captured, raw)
393 + actual = normalized_snapshot(captured, copied)
394 + require(actual == expected and independent_sql(copied) == sql,
395 + 'full_field_or_independent_sql_mismatch')
396 + if package == ORIGINAL:
397 + require(raw == original, 'original_source_bytes_changed')
398 + self.notifications_off()
399 + self.receipt['checks'][phase] = 'PASS'
400 +
401 + verify_cycle('both_apps_after_first_close')
402 + verify_cycle('both_apps_after_reopen')
403 + self.receipt['currentPhase'] = 'qa_same_test_key_upgrade'
404 + self.install(QA, upgrade=True)
405 + verify_cycle('both_apps_after_qa_upgrade')
406 + verify_cycle('both_apps_after_upgrade_reopen')
407 + require(source.read_bytes() == original, 'host_source_bytes_changed')
408 + self.receipt['checks']['qaNotificationsDefaultOffNoConsentTransferred'] = 'PASS'
409 + self.receipt['checks']['originalSourceBytesUnchangedAcrossRestoreAndUpgrade'] = 'PASS'
410 + self.receipt['originalClosedDatabaseSha256'] = digest(original)
411 + self.receipt.update(result='PASS', currentPhase='complete')
412 + return self.receipt
413 +
414 +
415 +def main(argv=None):
416 + parser = argparse.ArgumentParser(description=__doc__)
417 + parser.add_argument('--serial', required=True)
418 + parser.add_argument('--original-apk', type=Path, required=True)
419 + parser.add_argument('--qa-apk', type=Path, required=True)
420 + parser.add_argument('--upgrade-apk', type=Path, required=True)
421 + parser.add_argument('--acknowledge-synthetic-emulator-only', action='store_true')
422 + parser.add_argument('--output', type=Path, required=True)
423 + args = parser.parse_args(argv)
424 + runner = Harness(serial=args.serial, original_apk=args.original_apk, qa_apk=args.qa_apk,
425 + upgrade_apk=args.upgrade_apk, acknowledge=args.acknowledge_synthetic_emulator_only,
426 + output=args.output)
427 + code = 0
428 + try:
429 + runner.run()
430 + except (AcceptanceError, RecoveryError) as error:
431 + runner.receipt['errorCode'] = error.code if isinstance(error, RecoveryError) else str(error)
432 + code = 2
433 + except KeyboardInterrupt:
434 + runner.receipt['errorCode'], code = 'interrupted', 130
435 + except Exception:
436 + runner.receipt['errorCode'], code = 'host_acceptance_failed', 2
437 + try:
438 + publish_new(args.output, (json.dumps(runner.receipt, sort_keys=True, indent=2) + '\n').encode())
439 + except (OSError, RecoveryError):
440 + print(json.dumps({'result': 'FAIL', 'errorCode': 'receipt_publication_failed',
441 + 'syntheticDataOnly': True}))
442 + return 2
443 + print(json.dumps({'result': runner.receipt['result'], 'currentPhase': runner.receipt['currentPhase'],
444 + **({'errorCode': runner.receipt['errorCode']} if code else {})}))
445 + return code
446 +
447 +
448 +if __name__ == '__main__':
449 + raise SystemExit(main())
apps/lifemate/tool/test_personal_recovery_android_test.py new
+227
@@ -0,0 +1,227 @@
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_private_normalization_preserves_wal_header_source_and_full_fields(self):
130 + raw = bytearray(subject.create_sample_database())
131 + raw[18:20] = b'\x02\x02'
132 + source = self.directory / 'closed.sqlite'
133 + source.write_bytes(raw)
134 + original = bytes(raw)
135 + normalized = subject.normalized_snapshot(source, self.directory / 'copy.sqlite')
136 + self.assertEqual(source.read_bytes(), original)
137 + reference = self.directory / 'reference.sqlite'
138 + reference.write_bytes(subject.create_sample_database())
139 + self.assertEqual(normalized, subject.export_fixture(reference))
140 + self.assertEqual(subject.independent_sql(self.directory / 'copy.sqlite'),
141 + subject.independent_sql(reference))
142 +
143 + def test_notification_choice_and_native_state_are_strictly_off(self):
144 + for xml in ('<map/>', '<map><boolean name="enabled" value="false" /></map>'):
145 + self.assertTrue(subject.notification_preferences_off(xml, choice=True))
146 + self.assertTrue(subject.notification_preferences_off('<map/>', choice=False))
147 + for xml, choice in (('<map><boolean name="enabled" value="true"/></map>', True),
148 + ('<map><string name="active">{}</string></map>', False),
149 + ('<!DOCTYPE map><map/>', True),
150 + ('<map><boolean name="enabled" value="false"/><boolean name="enabled" value="false"/></map>', True)):
151 + with self.subTest(xml=xml), self.assertRaises(subject.AcceptanceError):
152 + subject.notification_preferences_off(xml, choice=choice)
153 +
154 + def test_ui_requires_valid_profile_text_and_exact_owned_dump_cleanup(self):
155 + h = self.make()
156 + h.preflight()
157 + h.install(subject.ORIGINAL)
158 + xml = '<hierarchy rotation="0"><node text="Fictional آزمایشی"/></hierarchy>'
159 + def shell(*parts, **kwargs):
160 + self.adb.calls.append(parts)
161 + return xml if parts[0] == 'cat' else ''
162 + self.adb.shell = shell
163 + self.assertTrue(h.profile_visible(subject.ORIGINAL))
164 + dumps = [call for call in self.adb.calls if call[0] == 'uiautomator']
165 + self.assertRegex(dumps[0][2], r'^/data/local/tmp/lifeguide-recovery-[0-9a-f]+\.xml$')
166 + self.assertIn(('rm', dumps[0][2]), self.adb.calls)
167 + xml = '<hierarchy><node text="سلام Fictional آزمایشی"/></hierarchy>'
168 + self.assertTrue(h.profile_visible(subject.ORIGINAL))
169 + xml = '<hierarchy><node text="not fixture"/></hierarchy>'
170 + self.assertFalse(h.profile_visible(subject.ORIGINAL))
171 + xml = '<hierarchy><broken>'
172 + with self.assertRaises(subject.AcceptanceError):
173 + h.profile_visible(subject.ORIGINAL)
174 +
175 + def test_seed_checks_bytes_after_binary_exec_without_overwriting(self):
176 + h = self.make()
177 + h.preflight()
178 + h.install(subject.ORIGINAL)
179 + h.binary = lambda command, data=None: b''
180 + with self.assertRaises(subject.AcceptanceError):
181 + h.seed(subject.ORIGINAL, subject.create_sample_database())
182 +
183 + def test_notification_permission_requires_explicit_runtime_denial(self):
184 + h = self.make()
185 + h.preflight()
186 + h.install(subject.QA)
187 + h.binary = lambda command, data=None: b'<map/>'
188 + original_shell = self.adb.shell
189 + state = 'false'
190 + def shell(*parts, **kwargs):
191 + if parts[:2] == ('dumpsys', 'package'):
192 + return 'runtime permissions:\n android.permission.POST_NOTIFICATIONS: granted=' + state + ', flags=[]\n'
193 + return original_shell(*parts, **kwargs)
194 + self.adb.shell = shell
195 + h.notifications_off()
196 + state = 'true'
197 + with self.assertRaisesRegex(subject.AcceptanceError, 'qa_notification_permission_not_denied'):
198 + h.notifications_off()
199 + state = ''
200 + with self.assertRaisesRegex(subject.AcceptanceError, 'qa_notification_permission_not_denied'):
201 + h.notifications_off()
202 +
203 + def test_binary_transport_bounds_actual_child_output_and_input(self):
204 + with self.assertRaisesRegex(subject.AcceptanceError, 'binary_input_limit'):
205 + subject.binary_adb('emulator-5554', 'unused', b'a' * (subject.MAX_PAYLOAD_BYTES + 1))
206 + popen = subprocess.Popen
207 + def child(*args, **kwargs):
208 + return popen(['python3', '-c', 'import sys; sys.stdout.buffer.write(b"a" * (8*1024*1024+1))'], **kwargs)
209 + with patch.object(subject.subprocess, 'Popen', side_effect=child):
210 + with self.assertRaisesRegex(subject.AcceptanceError, 'binary_output_limit'):
211 + subject.binary_adb('emulator-5554', 'unused')
212 +
213 + def test_failure_receipt_without_device_is_sanitized(self):
214 + output = self.directory / 'failed.json'
215 + code = subject.main(['--serial', 'physical-phone', '--original-apk', str(self.paths[0]),
216 + '--qa-apk', str(self.paths[1]), '--upgrade-apk', str(self.paths[2]),
217 + '--acknowledge-synthetic-emulator-only', '--output', str(output)])
218 + self.assertEqual(code, 2)
219 + receipt = json.loads(output.read_text())
220 + self.assertEqual(receipt['result'], 'FAIL')
221 + self.assertEqual(receipt['errorCode'], 'explicit_emulator_serial_required')
222 + self.assertEqual(receipt['currentPhase'], 'preflight')
223 + self.assertNotIn('host test apk', output.read_text())
224 +
225 +
226 +if __name__ == '__main__':
227 + unittest.main()