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 132 lines 5.51 KB
Raw
1 """Ephemeral, fictional signing fixtures. Never use with owner material."""
2
3 from contextlib import contextmanager
4 from dataclasses import dataclass, field
5 import hashlib
6 import os
7 from pathlib import Path
8 import secrets
9 import struct
10 import subprocess
11 import tempfile
12
13
14 ROOT = Path(__file__).resolve().parents[2]
15 HELPER = ROOT / "scripts/java/LifeGuideKeyInspector.java"
16 JVM_OPTION_VARIABLES = ("JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS", "JDK_JAVA_OPTIONS", "CLASSPATH")
17
18
19 def clean_java_environment():
20 return {key: value for key, value in os.environ.items()
21 if key.upper() not in JVM_OPTION_VARIABLES}
22
23
24 def request_frame(keystore, alias, store_password, key_password):
25 fields = [keystore, alias.encode("utf-8"), store_password.encode("utf-8"),
26 key_password.encode("utf-8")]
27 return b"LGKI" + b"".join(struct.pack(">I", len(value)) + value for value in fields)
28
29
30 def run_inspector(frame):
31 return subprocess.run(
32 ["java", "-Xmx96m", "--source", "17", str(HELPER)], input=frame,
33 stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=30,
34 env=clean_java_environment(), check=False,
35 )
36
37
38 @dataclass(repr=False)
39 class SyntheticKeystores:
40 directory: Path
41 alias: str
42 store_password: str = field(repr=False)
43 key_password: str = field(repr=False)
44
45 def __post_init__(self):
46 self.jks_path = self.directory / "fictional-rsa.jks"
47 self.pkcs12_path = self.directory / "fictional-ec.p12"
48 self.debug_path = self.directory / "fictional-debug.jks"
49 self.cert_only_path = self.directory / "fictional-certificate.jks"
50 self.dsa_path = self.directory / "fictional-dsa.jks"
51 self.fingerprints = {}
52
53 def keytool(self, *arguments, input_bytes=None):
54 environment = clean_java_environment()
55 environment["LG_TEST_STORE_PASSWORD"] = self.store_password
56 environment["LG_TEST_KEY_PASSWORD"] = self.key_password
57 try:
58 result = subprocess.run(
59 ["keytool", *map(str, arguments)], input=input_bytes,
60 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
61 timeout=30, env=environment, check=False,
62 )
63 except (OSError, subprocess.SubprocessError):
64 raise RuntimeError("synthetic keytool invocation failed") from None
65 if result.returncode != 0:
66 raise RuntimeError("synthetic keytool fixture creation failed")
67 return result.stdout
68
69 def create_key(self, path, algorithm, *, debug=False, expired=False):
70 pkcs12 = path.suffix == ".p12"
71 arguments = [
72 "-genkeypair", "-keystore", path, "-storetype", "PKCS12" if pkcs12 else "JKS",
73 "-alias", self.alias, "-keyalg", algorithm,
74 "-dname", "CN=Android Debug,O=Android,C=US" if debug else "CN=Fictional Signing Fixture,O=Example,C=US",
75 "-validity", "1" if expired else "3650", "-noprompt",
76 "-storepass:env", "LG_TEST_STORE_PASSWORD",
77 "-keypass:env", "LG_TEST_STORE_PASSWORD" if pkcs12 else "LG_TEST_KEY_PASSWORD",
78 ]
79 if algorithm in ("RSA", "DSA"):
80 arguments += ["-keysize", "2048"]
81 if expired:
82 arguments += ["-startdate", "2020/01/01 00:00:00"]
83 self.keytool(*arguments)
84 certificate = self.keytool(
85 "-exportcert", "-keystore", path, "-alias", self.alias,
86 "-storepass:env", "LG_TEST_STORE_PASSWORD",
87 )
88 self.fingerprints[path] = hashlib.sha256(certificate).hexdigest()
89 return certificate
90
91 def mismatched_certificate_store(self):
92 """Replace only a public certificate in a disposable encrypted JKS.
93
94 Its unchanged encrypted private key belongs to a different RSA keypair.
95 Recompute the legacy JKS integrity checksum so proof is actually reached.
96 """
97 def certificate(path):
98 return self.keytool("-exportcert", "-keystore", path, "-alias", self.alias,
99 "-storepass:env", "LG_TEST_STORE_PASSWORD")
100
101 original = certificate(self.jks_path)
102 replacement = certificate(self.debug_path)
103 body = self.jks_path.read_bytes()[:-20]
104 offset = body.rfind(original)
105 if offset < 4 or body[offset - 4:offset] != struct.pack(">I", len(original)):
106 raise RuntimeError("synthetic JKS certificate framing unavailable")
107 body = (body[:offset - 4] + struct.pack(">I", len(replacement))
108 + replacement + body[offset + len(original):])
109 integrity = hashlib.sha1(self.store_password.encode("utf-16-be")
110 + b"Mighty Aphrodite" + body).digest()
111 target = self.directory / "fictional-mismatched.jks"
112 target.write_bytes(body + integrity)
113 return target
114
115
116 @contextmanager
117 def synthetic_keystores():
118 with tempfile.TemporaryDirectory(prefix="lifeguide-synthetic-signing-") as directory:
119 fixtures = SyntheticKeystores(
120 Path(directory), "fixture-" + secrets.token_hex(8),
121 secrets.token_hex(24), secrets.token_hex(24),
122 )
123 certificate = fixtures.create_key(fixtures.jks_path, "RSA")
124 fixtures.create_key(fixtures.pkcs12_path, "EC")
125 fixtures.create_key(fixtures.debug_path, "RSA", debug=True)
126 fixtures.create_key(fixtures.dsa_path, "DSA")
127 fixtures.keytool(
128 "-importcert", "-keystore", fixtures.cert_only_path, "-storetype", "JKS",
129 "-alias", fixtures.alias, "-noprompt", "-storepass:env", "LG_TEST_STORE_PASSWORD",
130 input_bytes=certificate,
131 )
132 yield fixtures