@davoodmehraban89 / LifeMate / commits / a21eba1
Fork 0

LifeMate — Personal, Family & Learning Companion

fix(personal): block incompatible APK update delivery

Quinn White committed Oct 21, 2026 at 04:32 UTC a21eba1163d7a604929570661d463a8e5b7a4092
5 files changed +418 -1
.github/workflows/standalone-personal-apk.yml
+9 -1
@@ -9,6 +9,7 @@ on:
9 - 'apps/lifemate/tool/*standalone*'
10 - 'apps/lifemate/android/**'
11 - 'apps/lifemate/pubspec*'
12 + - 'docs/operations/personal-delivered-baseline.json'
13 workflow_dispatch:
14 permissions:
15 contents: read
@@ -70,7 +71,14 @@ jobs:
71 emulator-options: -no-window -gpu swiftshader_indirect -no-snapshot -wipe-data -noaudio -no-boot-anim -camera-back none
72 working-directory: apps/lifemate
73 script: python3 tool/test_standalone_android.py --serial emulator-5554 --user-apk build/LifeGuide.apk --fixture-apk build/standalone-private-fixture.apk --allow-synthetic-emulator-reset --output exports/standalone-android.json
73 - - name: Deliver user APK only after acceptance passes
74 + - name: Require compatibility with the delivered personal APK
75 + run: python3 tool/check_standalone_update.py build/LifeGuide.apk > exports/standalone-update-compatibility.json
76 + # Reviewed source hold: the same-run fixture above does not test the exact
77 + # delivered APK -> candidate with data in the default product database.
78 + # Remove only with implemented, independently verified upgrade acceptance.
79 + # No workflow input, environment flag or manual dispatch bypasses this hold.
80 + - name: User APK delivery blocked pending default-database upgrade acceptance
81 + if: ${{ false }}
82 uses: actions/upload-artifact@v4
83 with:
84 name: LifeGuide-personal-Android-0.7.2-9
apps/lifemate/tool/check_standalone_update.py new
+111
@@ -0,0 +1,111 @@
1 +#!/usr/bin/env python3
2 +"""Check necessary APK update compatibility; data-preserving delivery stays blocked."""
3 +import argparse
4 +import hashlib
5 +import json
6 +import re
7 +from pathlib import Path
8 +from zipfile import ZipFile
9 +
10 +from check_apk_manifest import manifest_tags
11 +from test_standalone_android import certificate_digest
12 +
13 +BASELINE_PATH = Path(__file__).resolve().parents[3] / 'docs/operations/personal-delivered-baseline.json'
14 +PACKAGE = 'ir.lifeguide.app.device'
15 +
16 +
17 +def _digest(value):
18 + return isinstance(value, str) and re.fullmatch(r'[0-9a-f]{64}', value) is not None
19 +
20 +
21 +def load_baseline():
22 + """Only reviewed repository source supplies the public delivered baseline."""
23 + baseline = json.loads(BASELINE_PATH.read_text(encoding='utf-8'))
24 + if (not isinstance(baseline, dict) or baseline.get('schemaVersion') != 1 or
25 + baseline.get('status') != 'DELIVERED' or baseline.get('package') != PACKAGE or
26 + type(baseline.get('versionCode')) is not int or baseline['versionCode'] < 1 or
27 + not _digest(baseline.get('certificateSha256')) or not _digest(baseline.get('apkSha256')) or
28 + baseline.get('installedDeviceVerification') != 'UNVERIFIED' or
29 + not isinstance(baseline.get('source'), dict) or
30 + type(baseline['source'].get('artifactId')) is not int):
31 + raise ValueError('delivered_baseline_invalid')
32 + return baseline
33 +
34 +
35 +def _report(reasons):
36 + return {'result': 'BLOCKED' if reasons else 'PASS', 'reasonCodes': reasons,
37 + 'dataPreservation': 'UNVERIFIED', 'installedDeviceVerification': 'UNVERIFIED',
38 + 'delivery': 'BLOCKED', 'deliveryReasonCode': 'default_database_upgrade_acceptance_missing'}
39 +
40 +
41 +def validate_compatibility(evidence, baseline):
42 + """Pure policy over independently inspected evidence, never an APK verifier.
43 +
44 + The command-line path below obtains these values from the actual APK and
45 + apksigner. Passing these checks cannot establish database preservation.
46 + """
47 + reasons = []
48 + if evidence.get('package') != baseline['package']:
49 + reasons.append('package_mismatch')
50 + certificate = evidence.get('certificateSha256')
51 + if not _digest(certificate):
52 + reasons.append('certificate_invalid')
53 + elif certificate != baseline['certificateSha256']:
54 + reasons.append('certificate_mismatch')
55 + version = evidence.get('versionCode')
56 + if type(version) is not int or version < 1:
57 + reasons.append('version_code_invalid')
58 + elif version <= baseline['versionCode']:
59 + reasons.append('version_code_not_incremented')
60 + if not _digest(evidence.get('apkSha256')):
61 + reasons.append('apk_digest_invalid')
62 + return _report(reasons)
63 +
64 +
65 +def check(apk):
66 + try:
67 + baseline = load_baseline()
68 + except Exception:
69 + return _report(['delivered_baseline_invalid'])
70 + try:
71 + apk = Path(apk)
72 + with ZipFile(apk) as archive:
73 + if archive.namelist().count('AndroidManifest.xml') != 1:
74 + raise ValueError('ambiguous_manifest')
75 + tags = manifest_tags(archive.read('AndroidManifest.xml'))
76 + manifests = [attributes for tag, attributes in tags if tag == 'manifest']
77 + if len(manifests) != 1:
78 + raise ValueError('ambiguous_manifest')
79 + evidence = {key: manifests[0].get(key) for key in ('package', 'versionCode')}
80 + evidence['apkSha256'] = hashlib.sha256(apk.read_bytes()).hexdigest()
81 + except Exception:
82 + return _report(['candidate_manifest_invalid'])
83 + try:
84 + # Existing verifier requires a successful apksigner process and exactly
85 + # one certificate digest. No CLI flag/report can supply a trusted signer.
86 + evidence['certificateSha256'] = certificate_digest(apk)
87 + except Exception:
88 + return _report(['candidate_signature_unverified'])
89 + return validate_compatibility(evidence, baseline)
90 +
91 +
92 +class _Parser(argparse.ArgumentParser):
93 + def error(self, message):
94 + raise ValueError('arguments_invalid')
95 +
96 +
97 +def main(argv=None):
98 + parser = _Parser(description=__doc__)
99 + parser.add_argument('apk', type=Path)
100 + try:
101 + options = parser.parse_args(argv)
102 + except ValueError:
103 + result = _report(['arguments_invalid'])
104 + else:
105 + result = check(options.apk)
106 + print(json.dumps(result, sort_keys=True))
107 + return 0 if result['result'] == 'PASS' else 1
108 +
109 +
110 +if __name__ == '__main__':
111 + raise SystemExit(main())
apps/lifemate/tool/check_standalone_update_test.py new
+153
@@ -0,0 +1,153 @@
1 +"""Delivery policy and verifier-output tests, not real APK/upgrade acceptance."""
2 +import contextlib
3 +import importlib
4 +import io
5 +import json
6 +import subprocess
7 +import tempfile
8 +import unittest
9 +from pathlib import Path
10 +from unittest.mock import patch
11 +from zipfile import ZipFile
12 +
13 +try:
14 + subject = importlib.import_module('check_standalone_update')
15 +except ModuleNotFoundError:
16 + subject = None
17 +
18 +DELIVERED_CERTIFICATE = '4ef990d647fc98ac41113d5dbe7ee476ba80bf95b71b5f219b7863fa95263391'
19 +LATEST_CI_CERTIFICATE = '0e5c979c14a3f293a443aba20e7e54e228ae98d78ed9861a1f0fb3f00ec20889'
20 +
21 +
22 +class StandaloneUpdateTest(unittest.TestCase):
23 + def setUp(self):
24 + self.assertIsNotNone(subject, 'The fail-closed personal update guard is missing')
25 + self.baseline = subject.load_baseline()
26 + self.evidence = {'package': 'ir.lifeguide.app.device', 'versionCode': 10,
27 + 'certificateSha256': DELIVERED_CERTIFICATE,
28 + 'apkSha256': 'a' * 64}
29 +
30 + def validate(self, **changes):
31 + return subject.validate_compatibility(self.evidence | changes, self.baseline)
32 +
33 + def test_committed_baseline_identifies_delivered_artifact_not_verified_device(self):
34 + self.assertEqual(self.baseline['status'], 'DELIVERED')
35 + self.assertEqual(self.baseline['versionCode'], 9)
36 + self.assertEqual(self.baseline['certificateSha256'], DELIVERED_CERTIFICATE)
37 + self.assertEqual(self.baseline['apkSha256'],
38 + 'c24ff6e75a987945399b0d96129f5d1a72525fa0270f31b0c481f9780f84db8e')
39 + self.assertEqual(self.baseline['source']['artifactId'], 12292340083)
40 + self.assertEqual(self.baseline['installedDeviceVerification'], 'UNVERIFIED')
41 +
42 + def test_matching_signer_higher_code_only_passes_necessary_compatibility(self):
43 + result = self.validate()
44 + self.assertEqual(result['result'], 'PASS')
45 + self.assertEqual(result['reasonCodes'], [])
46 + self.assertEqual(result['dataPreservation'], 'UNVERIFIED')
47 + self.assertEqual(result['installedDeviceVerification'], 'UNVERIFIED')
48 + self.assertEqual(result['delivery'], 'BLOCKED')
49 +
50 + def test_new_random_signer_is_rejected(self):
51 + result = self.validate(certificateSha256=LATEST_CI_CERTIFICATE)
52 + self.assertEqual(result['result'], 'BLOCKED')
53 + self.assertIn('certificate_mismatch', result['reasonCodes'])
54 +
55 + def test_equal_lower_missing_or_noninteger_version_is_rejected(self):
56 + for value in (9, 8, 0, -1, None, '10', True):
57 + with self.subTest(version=value):
58 + result = self.validate(versionCode=value)
59 + self.assertEqual(result['result'], 'BLOCKED')
60 + self.assertTrue({'version_code_not_incremented', 'version_code_invalid'} &
61 + set(result['reasonCodes']))
62 +
63 + def test_wrong_package_is_rejected_without_echoing_untrusted_value(self):
64 + result = self.validate(package='PRIVATE_UNTRUSTED_PACKAGE')
65 + self.assertIn('package_mismatch', result['reasonCodes'])
66 + self.assertNotIn('PRIVATE_UNTRUSTED_PACKAGE', json.dumps(result))
67 +
68 + def test_missing_or_malformed_certificate_is_rejected(self):
69 + for value in (None, '', 'a' * 63, ['a' * 64], 'PRIVATE_EXCEPTION'):
70 + with self.subTest(certificate=value):
71 + result = self.validate(certificateSha256=value)
72 + self.assertEqual(result['result'], 'BLOCKED')
73 + self.assertIn('certificate_invalid', result['reasonCodes'])
74 +
75 + def test_recorded_ci39_evidence_is_blocked_for_both_independent_reasons(self):
76 + result = self.validate(versionCode=9, certificateSha256=LATEST_CI_CERTIFICATE,
77 + apkSha256='7eea3d839179d02d140389da62ba7c2a14894c031f96b6a21a47e742164284b0')
78 + self.assertEqual(result['result'], 'BLOCKED')
79 + self.assertEqual(set(result['reasonCodes']),
80 + {'certificate_mismatch', 'version_code_not_incremented'})
81 +
82 +
83 +class ActualInspectionBoundaryTest(unittest.TestCase):
84 + def setUp(self):
85 + self.assertIsNotNone(subject, 'The fail-closed personal update guard is missing')
86 + self.directory = tempfile.TemporaryDirectory()
87 + self.addCleanup(self.directory.cleanup)
88 + self.apk = Path(self.directory.name) / 'synthetic-not-a-real-apk.zip'
89 + with ZipFile(self.apk, 'w') as archive:
90 + archive.writestr('AndroidManifest.xml', b'synthetic parser boundary')
91 + self.tags = [('manifest', {'package': 'ir.lifeguide.app.device', 'versionCode': 10})]
92 + self.signer_output = 'V2 Signer: certificate SHA-256 digest: ' + DELIVERED_CERTIFICATE + '\n'
93 +
94 + def inspect(self, output=None, returncode=0):
95 + # Only the external verifier/parser boundaries are mocked. This proves
96 + # rejection behavior and wiring, never a cryptographic APK acceptance.
97 + with patch.object(subject, 'manifest_tags', return_value=self.tags), \
98 + patch('test_standalone_android.shutil.which', return_value='/synthetic/apksigner'), \
99 + patch('test_standalone_android.subprocess.run', return_value=subprocess.CompletedProcess(
100 + [], returncode, self.signer_output if output is None else output, 'PRIVATE_STDERR')):
101 + return subject.check(self.apk)
102 +
103 + def test_actual_probe_reads_apk_manifest_and_verified_digest(self):
104 + result = self.inspect()
105 + self.assertEqual(result['result'], 'PASS')
106 + self.assertEqual(result['dataPreservation'], 'UNVERIFIED')
107 + self.assertEqual(result['delivery'], 'BLOCKED')
108 + self.tags[0][1]['versionCode'] = 9
109 + self.assertIn('version_code_not_incremented', self.inspect()['reasonCodes'])
110 +
111 + def test_unverified_missing_malformed_or_multiple_signer_output_blocks(self):
112 + for code, output in ((1, self.signer_output), (0, ''),
113 + (0, self.signer_output.replace(DELIVERED_CERTIFICATE, 'a' * 63)),
114 + (0, self.signer_output + self.signer_output),
115 + (0, self.signer_output.replace('certificate', 'public key'))):
116 + with self.subTest(code=code, output=output):
117 + result = self.inspect(output, code)
118 + self.assertEqual(result['result'], 'BLOCKED')
119 + self.assertEqual(result['reasonCodes'], ['candidate_signature_unverified'])
120 + self.assertNotIn('PRIVATE_STDERR', json.dumps(result))
121 +
122 + def test_missing_verifier_cannot_use_cli_supplied_certificate(self):
123 + with patch.object(subject, 'manifest_tags', return_value=self.tags), \
124 + patch('test_standalone_android.shutil.which', return_value=None), \
125 + patch.dict('os.environ', {'ANDROID_HOME': '', 'ANDROID_SDK_ROOT': ''}):
126 + self.assertEqual(subject.check(self.apk)['reasonCodes'], ['candidate_signature_unverified'])
127 + output = io.StringIO()
128 + with contextlib.redirect_stdout(output):
129 + code = subject.main([str(self.apk), '--certificate-sha256', DELIVERED_CERTIFICATE])
130 + self.assertNotEqual(code, 0)
131 + self.assertEqual(json.loads(output.getvalue())['reasonCodes'], ['arguments_invalid'])
132 +
133 + def test_unreadable_or_ambiguous_manifest_is_sanitized(self):
134 + for tags in ([], self.tags + self.tags):
135 + with self.subTest(tags=tags), patch.object(subject, 'manifest_tags', return_value=tags):
136 + self.assertEqual(subject.check(self.apk)['reasonCodes'], ['candidate_manifest_invalid'])
137 + self.apk.write_bytes(b'PRIVATE_INVALID_APK_BYTES')
138 + result = subject.check(self.apk)
139 + self.assertEqual(result['reasonCodes'], ['candidate_manifest_invalid'])
140 + self.assertNotIn('PRIVATE_INVALID_APK_BYTES', json.dumps(result))
141 +
142 + def test_unavailable_or_invalid_baseline_blocks_before_candidate_inspection(self):
143 + for content in (None, '{', '{}'):
144 + with self.subTest(content=content):
145 + path = Path(self.directory.name) / 'baseline.json'
146 + if content is not None:
147 + path.write_text(content, encoding='utf-8')
148 + with patch.object(subject, 'BASELINE_PATH', path):
149 + self.assertEqual(subject.check(self.apk)['reasonCodes'], ['delivered_baseline_invalid'])
150 +
151 +
152 +if __name__ == '__main__':
153 + unittest.main()
docs/operations/PERSONAL_UPDATE_GUARD.md new
+129
@@ -0,0 +1,129 @@
1 +# Personal Android update delivery guard — 2026-10-21
2 +
3 +Offline data preservation takes priority. This change blocks incompatible APK
4 +delivery; it does not provide a new installable update or prove preservation of
5 +the child's installed data. App code9, the normal manifest checker, SQLite
6 +schema1 and the online edition remain unchanged.
7 +
8 +The public [baseline](personal-delivered-baseline.json) describes the **DELIVERED**
9 +APK, not a verified reading of the actual device. Its identity comes from
10 +[the existing handoff](PERSONAL_ANDROID.md) and
11 +[recorded APK verification](../audits/evidence/personal-android-2026-10-20.json).
12 +Actual-device signer/version and upgrade preservation remain **UNVERIFIED**.
13 +
14 +## Recorded comparison
15 +
16 +| Evidence | Delivered baseline | PR39 personal CI |
17 +| --- | --- | --- |
18 +| Run | 39480587450 | 39541418453 |
19 +| Source | `3e36dfd4f01d51e11816c0f97d1abda4266f1945` | `c5cb3084f665cb5b1546447e34e35963e5ea5597` |
20 +| User APK artifact | 12292340083 | 12320495397 |
21 +| Package | `ir.lifeguide.app.device` | `ir.lifeguide.app.device` |
22 +| Version code | 9 | 9 |
23 +| Certificate SHA256 | `4ef990d647fc98ac41113d5dbe7ee476ba80bf95b71b5f219b7863fa95263391` | `0e5c979c14a3f293a443aba20e7e54e228ae98d78ed9861a1f0fb3f00ec20889` |
24 +| APK SHA256 | `c24ff6e75a987945399b0d96129f5d1a72525fa0270f31b0c481f9780f84db8e` | `7eea3d839179d02d140389da62ba7c2a14894c031f96b6a21a47e742164284b0` |
25 +
26 +The latest CI succeeded. Its verification artifact12320565252 was obtained
27 +through the official GitHub connector and inspected in memory. ZIP SHA256
28 +`ba787baff54364a0f9d32b713c43447f3d53f84fd2a1a52be5d0e2a02a03d055`
29 +matched GitHub's artifact digest. Its apksigner report and emulator receipt agree
30 +on the newer certificate; the signature report says Android Debug, v2 verified,
31 +v3 false. This is recorded CI evidence, **not a new local cryptographic
32 +verification of the whole APK**. The baseline must never advance to a random
33 +new debug certificate just to pass CI.
34 +
35 +The certificate mismatch prevents a normal update over the delivered package.
36 +Equal code9 also fails the new monotonic-delivery policy; Android can allow
37 +same-version replacement in some circumstances. Availability of the original
38 +matching private key is unknown. An unrelated new owner key cannot replace
39 +this v2-signed installation. A certificate/APK does not supply its private key.
40 +No signing key was read, generated, exported or configured.
41 +
42 +## Enforced delivery policy
43 +
44 +`tool/check_standalone_update.py` accepts only an actual APK path. It reads the
45 +binary manifest with the existing parser, computes the APK hash and invokes the
46 +existing `certificate_digest` apksigner probe. A successful verifier process and
47 +exactly one valid certificate digest are required. Neither a CLI-provided digest
48 +nor a CLI-provided baseline can establish trust.
49 +
50 +The reviewed baseline requires the same package and original signer plus a
51 +strictly greater version code. Missing verifier, invalid/multiple signer output,
52 +invalid manifest/baseline and incompatible candidates produce sanitized reason
53 +codes and a nonzero exit. A necessary-compatibility PASS still reports
54 +`dataPreservation: UNVERIFIED` and `delivery: BLOCKED`.
55 +
56 +The workflow keeps existing build/tests and fresh-emulator SQLite/notification
57 +acceptance before the new compatibility check. The check is immediately before
58 +the user-APK upload so a signer mismatch does not prevent native regression
59 +evidence. That upload additionally has an explicit source-level `if: ${{ false }}`
60 +hold, with no environment, workflow-input or manual-dispatch bypass. Diagnostic
61 +artifacts still upload with `always()`. Current code9 must fail compatibility;
62 +the resulting failed delivery job is intentional and is not a green-APK claim.
63 +
64 +Removing the upload hold requires reviewed implementation and independent
65 +acceptance of exact delivered APK → candidate using the default product DB.
66 +The current same-run fixture uses another DB and creates records after its
67 +replacement, so it does not meet this requirement. Acceptance must preserve
68 +profile/UUIDs/theme/companion, weekly dates/times, per-occurrence edits/ticks and
69 +archives, reminder opt-in/off and native pending/delivered state. It must verify
70 +no onboarding/data reset/duplicate notification, and a future reminder after
71 +replacement with the process absent. Never uninstall or clear child data to
72 +resolve a signature conflict. Physical-device acceptance remains separate.
73 +
74 +## Local verification actually run
75 +
76 +Commands below run from `apps/lifemate` unless stated otherwise. All new tests
77 +were written first. Before implementation:
78 +
79 +```text
80 +python3 -B -m unittest discover -s tool -p 'check_standalone_update_test.py' -v
81 +Ran 12 tests in 0.002s
82 +FAILED (failures=12)
83 +AssertionError: unexpectedly None : The fail-closed personal update guard is missing
84 +```
85 +
86 +After implementation:
87 +
88 +```text
89 +python3 -B -m unittest discover -s tool -p '*standalone*test.py' -v
90 +Ran 35 tests in 0.026s
91 +OK
92 +
93 +python3 -B -m unittest discover -s tool -p '*test.py' -v
94 +Ran 60 tests in 0.030s
95 +OK
96 +```
97 +
98 +The new policy tests cover wrong signer/package, equal/lower/invalid version,
99 +missing/malformed/multiple/failed verifier output and a necessary-compatible
100 +candidate that still cannot claim data preservation. External-process outputs
101 +and parser results are mocked only to test rejection boundaries; those tests
102 +are **not cryptographic or Android acceptance evidence**.
103 +
104 +The pure policy replay below uses the independently obtained CI report values,
105 +not an APK verifier result from this workspace:
106 +
107 +```sh
108 +python3 -B - <<'PY'
109 +import json
110 +import sys
111 +sys.path.insert(0, 'tool')
112 +from check_standalone_update import load_baseline, validate_compatibility
113 +reported_ci_evidence = {
114 + 'package': 'ir.lifeguide.app.device',
115 + 'versionCode': 9,
116 + 'certificateSha256': '0e5c979c14a3f293a443aba20e7e54e228ae98d78ed9861a1f0fb3f00ec20889',
117 + 'apkSha256': '7eea3d839179d02d140389da62ba7c2a14894c031f96b6a21a47e742164284b0',
118 +}
119 +print(json.dumps(validate_compatibility(reported_ci_evidence, load_baseline()), sort_keys=True))
120 +PY
121 +```
122 +
123 +```json
124 +{"dataPreservation": "UNVERIFIED", "delivery": "BLOCKED", "deliveryReasonCode": "default_database_upgrade_acceptance_missing", "installedDeviceVerification": "UNVERIFIED", "reasonCodes": ["certificate_mismatch", "version_code_not_incremented"], "result": "BLOCKED"}
125 +```
126 +
127 +No new local Android build, apksigner verification or device installation was
128 +performed for this guard. No merge, deploy, live configuration or real data was
129 +changed. Existing code9 builds and random debug signing are not repair claims.
docs/operations/personal-delivered-baseline.json new
+16
@@ -0,0 +1,16 @@
1 +{
2 + "schemaVersion": 1,
3 + "status": "DELIVERED",
4 + "package": "ir.lifeguide.app.device",
5 + "versionName": "0.7.2-personal.1",
6 + "versionCode": 9,
7 + "certificateSha256": "4ef990d647fc98ac41113d5dbe7ee476ba80bf95b71b5f219b7863fa95263391",
8 + "apkSha256": "c24ff6e75a987945399b0d96129f5d1a72525fa0270f31b0c481f9780f84db8e",
9 + "installedDeviceVerification": "UNVERIFIED",
10 + "source": {
11 + "repository": "davoodmehraban89/LifeMate",
12 + "runId": 39480587450,
13 + "artifactId": 12292340083,
14 + "url": "https://github.com/davoodmehraban89/LifeMate/actions/runs/39480587450/artifacts/12292340083"
15 + }
16 +}