diff --git a/tools/deploy_fast.py b/tools/deploy_fast.py new file mode 100644 index 0000000000..6130cd27d2 --- /dev/null +++ b/tools/deploy_fast.py @@ -0,0 +1,300 @@ +#!/usr/bin/env python3 +"""Deploy session-helper changes by grafting them into the latest main CI APK. + +Downloads the newest release-signed main build from DroidDeck-CI that this checkout +descends from, replaces the helper assets whose sources differ from that build, re-signs +the result with the local release signer and optionally installs it. Any other change +(Kotlin, resources, native code, runtime components, deletions) stops the run so a full +build covers it. +""" +import argparse +import copy +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import time +from zipfile import ZipFile + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tools/release')) +from check_session_assets import source_assets + +CI_REPO = 'Droid-Deck/DroidDeck-CI' +CACHE = Path.home() / '.cache/droiddeck-donors' +IGNORED_PREFIXES = ('docs/', '.github/', 'tools/tests/', 'tools/ci/') +IGNORED_FILES = {'.gitignore', 'LICENSE', 'tools/deploy_fast.py'} +SIGNATURE_SUFFIXES = ('.SF', '.RSA', '.DSA', '.EC') +SIGNER = Path(os.environ.get('LOCALAPPDATA', '')) / 'DroidDeckSigning/Sign-DroidDeckApk.ps1' +PWSH_FALLBACK = Path.home() / '.cache/codex-runtimes/codex-primary-runtime/dependencies/native/powershell/pwsh.exe' + + +class Refused(Exception): + pass + + +def run_bounded(command, timeout, **options): + try: + return subprocess.run(command, timeout=timeout, **options) + except subprocess.TimeoutExpired: + raise Refused(' '.join(map(str, command[:4])) + ' timed out') + + +def git(*args, check=True): + result = run_bounded(['git', '-C', str(ROOT), *args], 300, capture_output=True, check=False) + if check and result.returncode: + raise Refused('git ' + ' '.join(args) + ' failed: ' + result.stderr.decode(errors='replace').strip()) + return result.stdout + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def is_ignored(path): + return path in IGNORED_FILES or path.endswith('.md') or path.startswith(IGNORED_PREFIXES) + + +def graft_targets(): + return {source.relative_to(ROOT).as_posix(): asset for source, asset in source_assets().items()} + + +def changed_paths(donor_commit): + """Return {path: status} for the checkout, uncommitted and untracked files included.""" + changes = {} + fields = git('diff', '--name-status', '-z', '--no-renames', donor_commit).decode().split('\0') + for status, path in zip(fields[0::2], fields[1::2]): + changes[path] = status + for path in filter(None, git('ls-files', '-z', '-o', '--exclude-standard').decode().split('\0')): + changes[path] = 'A' + return changes + + +def classify(changes, targets, donor_entries): + """Split changes into grafts {path: asset}, ignored paths and blockers {path: reason}.""" + grafts, ignored, blocked = {}, [], {} + for path, status in sorted(changes.items()): + if is_ignored(path): + ignored.append(path) + elif path not in targets: + blocked[path] = 'not a graftable session helper' + elif status == 'D': + blocked[path] = 'deleted helper' + elif targets[path] not in donor_entries: + blocked[path] = 'new helper the donor APK does not carry' + else: + grafts[path] = targets[path] + return grafts, ignored, blocked + + +def helper_bytes(path): + data = (ROOT / path).read_bytes() + return data if b'\0' in data else data.replace(b'\r\n', b'\n') + + +def graft(donor, replacements, output): + """Copy the donor with entries replaced, dropping its signature so it can be re-signed.""" + with ZipFile(donor) as source, ZipFile(output, 'w') as target: + for info in source.infolist(): + name = info.filename + if name.startswith('META-INF/') and (name == 'META-INF/MANIFEST.MF' or name.endswith(SIGNATURE_SUFFIXES)): + continue + data = replacements.get(name) + if data is None: + data = source.read(name) + entry = copy.copy(info) + entry.extra = b'' + target.writestr(entry, data, compress_type=info.compress_type) + missing = set(replacements) - {i.filename for i in ZipFile(output).infolist()} + if missing: + raise Refused('Replacement entries missing from the output: ' + ', '.join(sorted(missing))) + + +def release_tags(limit=60): + out = run_bounded(['gh', 'release', 'list', '-R', CI_REPO, '--limit', str(limit), '--json', 'tagName'], + 120, capture_output=True, text=True) + if out.returncode: + raise Refused('Could not list DroidDeck-CI releases: ' + out.stderr.strip()) + return [item['tagName'] for item in json.loads(out.stdout) if item['tagName'].startswith('main-')] + + +def donor_commit(tag): + short = tag.removeprefix('main-') + commit = git('rev-parse', '--verify', '--quiet', short + '^{commit}', check=False).decode().strip() + if not commit: + git('fetch', '--no-tags', 'origin', 'main') + commit = git('rev-parse', '--verify', short + '^{commit}').decode().strip() + return commit + + +def is_ancestor(commit): + return subprocess.run(['git', '-C', str(ROOT), 'merge-base', '--is-ancestor', commit, 'HEAD']).returncode == 0 + + +def pick_tag(requested): + if requested: + return requested + for tag in release_tags(): + try: + if is_ancestor(donor_commit(tag)): + return tag + except Refused: + continue + raise Refused('No recent DroidDeck-CI main build is an ancestor of this checkout; merge main first.') + + +def fetch_donor(tag): + folder = CACHE / tag + apk = folder / f'DroidDeck-{tag}.apk' + sums = folder / 'SHA256SUMS.txt' + if not (apk.is_file() and sums.is_file()): + folder.mkdir(parents=True, exist_ok=True) + for pattern in (apk.name, sums.name): + try: + result = run_bounded(['gh', 'release', 'download', tag, '-R', CI_REPO, '-p', pattern, + '-D', str(folder), '--clobber'], 900, capture_output=True, text=True) + if result.returncode: + raise Refused('Download failed: ' + result.stderr.strip()) + except Refused: + apk.unlink(missing_ok=True) + raise + expected = dict(reversed(line.split(None, 1)) for line in sums.read_text().splitlines() if line.strip()) + if digest(apk) != expected.get(apk.name, '').strip(): + apk.unlink() + raise Refused('Donor APK does not match SHA256SUMS.txt: ' + apk.name) + return apk + + +def sdk_root(): + return Path(os.environ.get('ANDROID_HOME') or os.environ.get('ANDROID_SDK_ROOT') or Path.home() / 'android-sdk') + + +def apksigner(): + candidates = sorted((sdk_root() / 'build-tools').glob('*/apksigner*'), reverse=True) + for path in candidates: + if path.suffix in ('', '.bat'): + return str(path) + raise Refused('apksigner not found under ' + str(sdk_root() / 'build-tools')) + + +def signer_sha256(apk): + result = subprocess.run([apksigner(), 'verify', '--print-certs', str(apk)], capture_output=True, text=True) + if result.returncode: + raise Refused('APK signature does not verify: ' + (result.stdout + result.stderr).strip()) + for line in result.stdout.splitlines(): + if 'certificate SHA-256 digest:' in line: + return line.rsplit(':', 1)[1].strip().lower() + raise Refused('apksigner reported no certificate digest') + + +def pwsh(): + found = shutil.which('pwsh') + if found: + return found + if PWSH_FALLBACK.is_file(): + return str(PWSH_FALLBACK) + raise Refused('PowerShell 7 (pwsh) is required for the local signer') + + +def sign(unsigned, signed): + # Microsoft Store Python virtualizes AppData for child processes too and hides the signer; use a python.org install. + def quoted(value): + return "'" + str(value).replace("'", "''") + "'" + command = (f"if (-not (Test-Path -LiteralPath {quoted(SIGNER)})) {{ Write-Error 'Local signer not found'; exit 1 }}; " + f"& {quoted(SIGNER)} -InputApk {quoted(unsigned)} -OutputApk {quoted(signed)} -SdkRoot {quoted(sdk_root())}") + result = subprocess.run([pwsh(), '-NoProfile', '-Command', command], capture_output=True, text=True) + if result.returncode or not signed.is_file(): + raise Refused('Signing failed:\n' + (result.stdout + result.stderr).strip()) + + +def verify_output(apk, grafts, pinned): + if signer_sha256(apk) != pinned: + raise Refused('Output is not signed with the release certificate') + with ZipFile(apk) as package: + for path, asset in grafts.items(): + if package.read(asset) != helper_bytes(path): + raise Refused('Grafted helper does not match its source: ' + asset) + for path, asset in graft_targets().items(): + if asset in package.namelist() and package.read(asset) != helper_bytes(path): + raise Refused('Stale helper in the output: ' + asset) + + +def install(apk): + adb = Path(os.environ.get('ADB') or sdk_root() / 'platform-tools/adb.exe') + if not adb.is_file(): + adb = Path(shutil.which('adb') or '') + if not adb.is_file(): + raise Refused('adb not found; set ADB or ANDROID_HOME') + serial = subprocess.run([sys.executable, str(ROOT / 'tools/adb_device.py'), '--adb', str(adb)], + capture_output=True, text=True) + if serial.returncode: + raise Refused(serial.stderr.strip() or 'No device resolved') + device = serial.stdout.strip() + result = subprocess.run([str(adb), '-s', device, 'install', '-r', '--no-incremental', str(apk)]) + if result.returncode: + raise Refused('adb install failed (a different signing certificate needs a manual uninstall)') + print('Installed on ' + device) + + +def run(args): + pinned = (ROOT / 'keystore/release-signer.sha256').read_text().strip().lower() + tag = pick_tag(args.donor) + commit = donor_commit(tag) + if not is_ancestor(commit): + raise Refused(f'{tag} is not an ancestor of this checkout; merge main or pick an older build') + donor = fetch_donor(tag) + if signer_sha256(donor) != pinned: + raise Refused('Donor APK is not signed with the release certificate') + with ZipFile(donor) as package: + entries = set(package.namelist()) + grafts, ignored, blocked = classify(changed_paths(commit), graft_targets(), entries) + print(f'Donor {tag} ({commit[:7]})') + for path in ignored: + print(' ignored', path) + for path, asset in grafts.items(): + print(' graft ', path, '->', asset) + if blocked: + for path, reason in blocked.items(): + print(' BLOCKED', path, f'({reason})') + raise Refused('Changes outside the graftable set; run tools/build_local.sh for these.') + if not grafts: + print('Nothing to graft; the donor already matches this checkout.') + if not args.plan: + print('Donor APK:', donor) + if args.install: + install(donor) + return + if args.plan: + return + out_dir = ROOT / 'app/build/outputs/apk/fast' + out_dir.mkdir(parents=True, exist_ok=True) + stamp = f'{tag}-{git("rev-parse", "--short", "HEAD").decode().strip()}-{int(time.time())}' + unsigned = out_dir / f'unsigned-{stamp}.apk' + signed = out_dir / f'DroidDeck-fast-{stamp}.apk' + graft(donor, {asset: helper_bytes(path) for path, asset in grafts.items()}, unsigned) + try: + sign(unsigned, signed) + finally: + unsigned.unlink(missing_ok=True) + verify_output(signed, grafts, pinned) + print('Signed APK:', signed) + if args.install: + install(signed) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--donor', help='DroidDeck-CI main tag such as main-4aa19b6; default is the newest ancestor build') + parser.add_argument('--plan', action='store_true', help='Show what would be grafted without building') + parser.add_argument('--install', action='store_true', help='Install the signed APK on the connected device') + try: + run(parser.parse_args()) + except Refused as error: + parser.exit(2, str(error) + '\n') + + +if __name__ == '__main__': + main() diff --git a/tools/tests/test_deploy_fast.py b/tools/tests/test_deploy_fast.py new file mode 100644 index 0000000000..fd1a66b9e7 --- /dev/null +++ b/tools/tests/test_deploy_fast.py @@ -0,0 +1,209 @@ +import hashlib +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest import mock +from zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile, ZipInfo + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import deploy_fast + + +def make_apk(path, entries): + with ZipFile(path, 'w') as package: + for name, (data, method) in entries.items(): + info = ZipInfo(name) + info.extra = b'\0' * 6 + package.writestr(info, data, compress_type=method) + + +class ClassifyTest(unittest.TestCase): + agent = 'tools/linuxfs/overlay/usr/local/bin/droiddeck-agent' + targets = {agent: 'assets/linuxfs/usr/local/bin/droiddeck-agent', + 'tools/linuxfs/overlay/usr/local/bin/droiddeck-new': 'assets/linuxfs/usr/local/bin/droiddeck-new'} + entries = {'assets/linuxfs/usr/local/bin/droiddeck-agent'} + + def classify(self, changes): + return deploy_fast.classify(changes, self.targets, self.entries) + + def test_helpers_graft_and_tests_or_docs_are_ignored(self): + grafts, ignored, blocked = self.classify({ + self.agent: 'M', 'tools/tests/test_x.py': 'M', 'docs/a/b.txt': 'A', 'README.md': 'M'}) + self.assertEqual(grafts, {self.agent: 'assets/linuxfs/usr/local/bin/droiddeck-agent'}) + self.assertEqual(sorted(ignored), ['README.md', 'docs/a/b.txt', 'tools/tests/test_x.py']) + self.assertEqual(blocked, {}) + + def test_everything_else_fails_closed(self): + changes = {'app/src/main/java/com/droiddeck/launcher/Foo.kt': 'M', 'tools/proot/build.sh': 'M', + 'tools/linuxfs/overlay/usr/local/bin/droiddeck-new': 'A'} + self.assertEqual(set(self.classify(changes)[2]), set(changes)) + self.assertEqual(set(self.classify({self.agent: 'D'})[2]), {self.agent}) + + def test_real_graft_targets_exist_in_the_overlay(self): + for path in deploy_fast.graft_targets(): + self.assertTrue((deploy_fast.ROOT / path).is_file(), path) + + +class GraftTest(unittest.TestCase): + def test_replaces_entries_keeps_the_rest_and_drops_the_signature(self): + with tempfile.TemporaryDirectory() as directory: + donor, output = Path(directory) / 'donor.apk', Path(directory) / 'out.apk' + make_apk(donor, {'classes.dex': (b'dex', ZIP_DEFLATED), 'lib/arm64-v8a/libx.so': (b'elf', ZIP_STORED), + 'assets/a': (b'old', ZIP_DEFLATED), 'META-INF/MANIFEST.MF': (b'm', ZIP_DEFLATED), + 'META-INF/CERT.SF': (b's', ZIP_DEFLATED), 'META-INF/CERT.RSA': (b'r', ZIP_DEFLATED), + 'META-INF/keep.version': (b'v', ZIP_DEFLATED)}) + deploy_fast.graft(donor, {'assets/a': b'new'}, output) + with ZipFile(output) as package: + self.assertEqual(package.read('assets/a'), b'new') + self.assertEqual(package.read('classes.dex'), b'dex') + self.assertEqual(package.getinfo('lib/arm64-v8a/libx.so').compress_type, ZIP_STORED) + self.assertEqual(package.getinfo('classes.dex').compress_type, ZIP_DEFLATED) + self.assertEqual(package.getinfo('classes.dex').extra, b'') + self.assertEqual([n for n in package.namelist() if n.startswith('META-INF/')], + ['META-INF/keep.version']) + + def test_unknown_replacement_entry_is_refused(self): + with tempfile.TemporaryDirectory() as directory: + donor = Path(directory) / 'donor.apk' + make_apk(donor, {'assets/a': (b'old', ZIP_DEFLATED)}) + with self.assertRaises(deploy_fast.Refused): + deploy_fast.graft(donor, {'assets/missing': b'x'}, Path(directory) / 'out.apk') + + +class RepoTest(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.root = Path(self.directory.name) + patch = mock.patch.object(deploy_fast, 'ROOT', self.root) + patch.start() + self.addCleanup(patch.stop) + self.git('init', '-q', '-b', 'trunk') + self.git('config', 'user.email', 'a@b.c') + self.git('config', 'user.name', 'a') + (self.root / 'kept').write_text('1') + (self.root / 'gone').write_text('1') + self.git('add', '.') + self.git('commit', '-q', '-m', 'base') + self.base = self.git('rev-parse', 'HEAD').strip() + + def git(self, *args): + return subprocess.run(['git', '-C', str(self.root), *args], capture_output=True, text=True, check=True).stdout + + def test_changed_paths_cover_staged_untracked_and_deleted_files(self): + (self.root / 'kept').write_text('2') + (self.root / 'gone').unlink() + (self.root / 'fresh').write_text('x') + self.git('add', 'kept') + self.assertEqual(deploy_fast.changed_paths(self.base), {'kept': 'M', 'gone': 'D', 'fresh': 'A'}) + + def test_helper_bytes_normalize_text_but_not_binaries(self): + (self.root / 'script').write_bytes(b'a\r\nb\r\n') + (self.root / 'binary').write_bytes(b'\0a\r\n') + self.assertEqual(deploy_fast.helper_bytes('script'), b'a\nb\n') + self.assertEqual(deploy_fast.helper_bytes('binary'), b'\0a\r\n') + + def test_a_donor_ahead_of_the_checkout_is_not_an_ancestor(self): + self.git('checkout', '-q', '-b', 'side') + (self.root / 'kept').write_text('3') + self.git('commit', '-qam', 'side') + side = self.git('rev-parse', 'HEAD').strip() + self.git('checkout', '-q', 'trunk') + self.assertTrue(deploy_fast.is_ancestor(self.base)) + self.assertFalse(deploy_fast.is_ancestor(side)) + + +class DonorTest(unittest.TestCase): + def test_pick_tag_takes_the_newest_ancestor(self): + commits = {'main-new': 'n', 'main-mid': 'm', 'main-old': 'o'} + with mock.patch.object(deploy_fast, 'release_tags', return_value=list(commits)), \ + mock.patch.object(deploy_fast, 'donor_commit', side_effect=lambda tag: commits[tag]), \ + mock.patch.object(deploy_fast, 'is_ancestor', side_effect=lambda commit: commit != 'n'): + self.assertEqual(deploy_fast.pick_tag(None), 'main-mid') + self.assertEqual(deploy_fast.pick_tag('main-new'), 'main-new') + + def test_pick_tag_without_an_ancestor_is_refused(self): + with mock.patch.object(deploy_fast, 'release_tags', return_value=['main-a']), \ + mock.patch.object(deploy_fast, 'donor_commit', return_value='a'), \ + mock.patch.object(deploy_fast, 'is_ancestor', return_value=False): + with self.assertRaises(deploy_fast.Refused): + deploy_fast.pick_tag(None) + + def test_checksum_mismatch_discards_the_cached_donor(self): + with tempfile.TemporaryDirectory() as directory: + folder = Path(directory) / 'main-x' + folder.mkdir() + apk = folder / 'DroidDeck-main-x.apk' + sums = folder / 'SHA256SUMS.txt' + apk.write_bytes(b'apk') + sums.write_text('0' * 64 + ' DroidDeck-main-x.apk\n') + with mock.patch.object(deploy_fast, 'CACHE', Path(directory)): + with self.assertRaises(deploy_fast.Refused): + deploy_fast.fetch_donor('main-x') + self.assertFalse(apk.exists()) + apk.write_bytes(b'apk') + sums.write_text(hashlib.sha256(b'apk').hexdigest() + ' DroidDeck-main-x.apk\n') + self.assertEqual(deploy_fast.fetch_donor('main-x'), apk) + + def test_a_cached_apk_without_checksums_is_downloaded_again(self): + with tempfile.TemporaryDirectory() as directory: + folder = Path(directory) / 'main-x' + folder.mkdir() + apk = folder / 'DroidDeck-main-x.apk' + apk.write_bytes(b'truncated') + calls = [] + sums = hashlib.sha256(b'apk').hexdigest() + ' ' + apk.name + '\n' + + def download(command, timeout, **options): + pattern = command[command.index('-p') + 1] + calls.append(pattern) + (folder / pattern).write_bytes(b'apk' if pattern.endswith('.apk') else sums.encode()) + return mock.Mock(returncode=0, stderr='') + + with mock.patch.object(deploy_fast, 'CACHE', Path(directory)): + with mock.patch.object(deploy_fast, 'run_bounded', download): + self.assertEqual(deploy_fast.fetch_donor('main-x'), apk) + self.assertEqual(calls, [apk.name, 'SHA256SUMS.txt']) + + def test_a_failed_download_removes_the_apk_and_a_timeout_is_refused(self): + with tempfile.TemporaryDirectory() as directory: + folder = Path(directory) / 'main-x' + folder.mkdir() + apk = folder / 'DroidDeck-main-x.apk' + apk.write_bytes(b'partial') + failed = mock.Mock(returncode=1, stderr='boom') + with mock.patch.object(deploy_fast, 'CACHE', Path(directory)): + with mock.patch.object(deploy_fast, 'run_bounded', return_value=failed): + with self.assertRaises(deploy_fast.Refused): + deploy_fast.fetch_donor('main-x') + self.assertFalse(apk.exists()) + timeout = deploy_fast.subprocess.TimeoutExpired('git', 1) + with mock.patch.object(deploy_fast.subprocess, 'run', side_effect=timeout): + with self.assertRaises(deploy_fast.Refused): + deploy_fast.git('status') + + +class SignTest(unittest.TestCase): + def test_paths_with_apostrophes_are_escaped_for_powershell(self): + seen = [] + + def run(command, **options): + seen.append(command) + return mock.Mock(returncode=1, stdout='', stderr='') + + with mock.patch.object(deploy_fast, 'pwsh', return_value='pwsh'): + with mock.patch.object(deploy_fast, 'SIGNER', Path("C:/O'Brien/sign.ps1")): + with mock.patch.object(deploy_fast.subprocess, 'run', side_effect=run): + with self.assertRaises(deploy_fast.Refused): + deploy_fast.sign(Path("C:/a'b/in.apk"), Path("C:/a'b/out.apk")) + script = seen[0][-1] + self.assertIn("O''Brien", script) + self.assertIn("a''b", script) + self.assertNotIn("a'b", script.replace("a''b", '')) + self.assertNotIn("O'Brien", script.replace("O''Brien", '')) + + +if __name__ == '__main__': + unittest.main()