Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

os: verify encrypted Asahi boot and offline recovery (#944)

Dee0be41ffe6dd5
diff --git a/os/platforms/apple-silicon/README.md b/os/platforms/apple-silicon/README.md
index 43a773cc2..630a80d4e 100644
--- a/os/platforms/apple-silicon/README.md
+++ b/os/platforms/apple-silicon/README.md
@@ -70,3 +70,38 @@ existing agent workspace. Subsequent boots enter Harness directly.
This step does not encrypt the disk. It keeps the maintained Fedora/Asahi boot,
swap, extras, authentication and SELinux configuration. The stock account wizard
remains installed but is disabled in the Harness image.
+
+## Private encrypted-root acceptance
+
+`os/tests/asahi_encryption_vm.py` tests LUKS2 around a disposable copy of the
+produced image on an Apple Silicon host. It requires that image's full source
+commit and SHA-256, plus a verified native ARM maintenance fixture. It never
+opens a host disk. The maintenance VM sees only its own root and the cloned
+image, identified by a test-only device serial.
+
+```sh
+python3 os/tests/asahi_encryption_vm.py \
+ --image /path/to/harness-asahi-private.raw --sha256 IMAGE_SHA256 \
+ --image-source FULL_IMAGE_COMMIT \
+ --fixture /path/to/verified-arm-fixture --fixture-source FULL_FIXTURE_COMMIT \
+ --output os/test-results/asahi-encryption
+```
+
+The test shrinks the pristine Btrfs root and encrypts it with Fedora cryptsetup,
+checks that every decrypted filesystem byte matches its baseline, and regenerates
+the Fedora initramfs and boot entries. Mounts stay in a private namespace so
+background services cannot retain the target after cleanup. The partition table,
+EFI partition, Harness payload and Asahi keyboard modules must remain intact.
+Only the clone gains QEMU console arguments and its virtio keyboard driver.
+
+Acceptance covers graphical wrong/correct password entry, first account setup,
+the initial OpenCode and two terminal panes, subsequent unlock, and offline
+read-only recovery of a project. Each boot must have enforcing SELinux and no
+failed system services. Receipts retain input hashes, screenshots, boot journals,
+clean shutdown events, and a final check that the original image is unchanged.
+
+This establishes encrypted-root compatibility, not an installation or encryption
+enrollment flow. The test uses a public fixture password: **never publish its disk
+copies**. A user installer still needs to create a unique encryption key, preserve
+macOS and recovery, and handle interruption before it can offer encrypted installs.
+Physical Apple keyboard, storage and recovery acceptance remain separate.
diff --git a/os/tests/asahi_encryption_guest.py b/os/tests/asahi_encryption_guest.py
new file mode 100644
index 000000000..ea5e5a346
--- /dev/null
+++ b/os/tests/asahi_encryption_guest.py
@@ -0,0 +1,229 @@
+#!/usr/bin/env python3
+"""Encrypt/recover only the second cloned disk in the private Asahi test VM.
+
+This is destructive fixture construction, not a user installer. The runner owns
+both disks; the public fixture password must never appear in a released image.
+"""
+import argparse
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import subprocess
+import time
+
+ROOT = Path('/mnt/harness-encryption-test')
+DEVICE = '/dev/vdb3'
+MAPPER = 'harness-encryption-test'
+PASSWORD = b'firstboot-local-42'
+PROJECT = 'home/me/projects/encryption-check/result.txt'
+PROJECT_TEXT = b'Harness encrypted project survives reboot and offline recovery.\n'
+
+
+def run(*args, secret=None, timeout=120):
+ result = subprocess.run(args, input=secret, stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT, timeout=timeout, check=False)
+ text = result.stdout.decode(errors='replace')
+ if result.returncode:
+ raise RuntimeError(f'{args[0]} exited {result.returncode}: {text}')
+ return text.strip()
+
+
+def digest(path, count=None):
+ result = hashlib.sha256()
+ with open(path, 'rb') as stream:
+ while count is None or count:
+ data = stream.read(min(count, 1024**2) if count is not None else 1024**2)
+ if not data:
+ if count:
+ raise ValueError('Device ended before the declared byte count.')
+ break
+ result.update(data)
+ if count is not None:
+ count -= len(data)
+ return result.hexdigest()
+
+
+def leaked_mounts():
+ current = os.readlink('/proc/self/ns/mnt')
+ leaks = []
+ for process in Path('/proc').glob('[0-9]*'):
+ try:
+ if os.readlink(process / 'ns/mnt') == current:
+ continue
+ for row in (process / 'mountinfo').read_text().splitlines():
+ if row.split()[4] == str(ROOT):
+ leaks.append({'pid': int(process.name), 'mount': row})
+ except (FileNotFoundError, ProcessLookupError):
+ pass
+ return leaks
+
+
+def guard(source):
+ if os.geteuid() != 0 or run('uname', '-m') != 'aarch64':
+ raise ValueError('Use the owned native ARM maintenance VM.')
+ if (os.readlink('/proc/self/ns/mnt') == os.readlink('/proc/1/ns/mnt') or
+ run('findmnt', '-nro', 'PROPAGATION', '/') != 'private'):
+ raise ValueError('Run in unshare --mount --propagation private.')
+ if run('findmnt', '-no', 'SOURCE', '/') != '/dev/vda':
+ raise ValueError('The maintenance root must be the first disk.')
+ if (run('lsblk', '-ndo', 'SERIAL', '/dev/vdb') != 'HARNESS_ENCRYPT_TEST' or
+ run('blockdev', '--getss', '/dev/vdb') != '4096'):
+ raise ValueError('The target is not the owned 4096-byte-sector clone.')
+ table = json.loads(run('sfdisk', '--json', '/dev/vdb'))
+ if [p['node'] for p in table['partitiontable']['partitions']] != ['/dev/vdb1', '/dev/vdb2', '/dev/vdb3']:
+ raise ValueError('Unexpected target partitions.')
+ if (run('lsblk', '-nro', 'MOUNTPOINTS', '/dev/vdb') or leaked_mounts() or
+ Path('/dev/mapper', MAPPER).exists() or not re.fullmatch('[a-f0-9]{40}', source)):
+ raise ValueError('The cloned target is in use or lacks its source identity.')
+ return table
+
+
+def identity(source):
+ image = json.loads((ROOT / 'usr/share/harness-os/image.json').read_text())
+ assert image['source_commit'] == source
+ assert image['release_ready'] is False and image['kind'] == 'harness-asahi-image-construction'
+ for name, expected in image['first_boot']['files'].items():
+ assert digest(ROOT / name) == expected['sha256'], name
+ for name, expected in image['session_package']['files'].items():
+ assert digest(ROOT / name) == expected, name
+ return image
+
+
+def boot_configuration(uuid, result):
+ crypttab = ROOT / 'etc/crypttab'
+ assert not crypttab.exists() or not crypttab.read_text().strip()
+ crypttab.write_text(f'harness-root UUID={uuid} none luks,x-initrd.attach\n')
+ crypttab.chmod(0o600)
+ # Name the root consistently in the initramfs and installed system. With
+ # only rd.luks.uuid, a generic initramfs uses luks-UUID and the real root
+ # attempts to open the same volume again under its crypttab name.
+ arg = f'rd.luks.name={uuid}=harness-root'
+ # QEMU's virt board defaults to a serial-only kernel console. Explicitly
+ # select its graphical console so acceptance exercises actual key events.
+ # These observer-only arguments are not additions to the produced image.
+ consoles = 'console=ttyAMA0 console=tty0'
+ added = arg + ' ' + consoles
+ cmdline = ROOT / 'etc/kernel/cmdline'
+ cmdline.write_text(cmdline.read_text().strip() + ' ' + added + '\n')
+ grub = ROOT / 'etc/default/grub'
+ content, count = re.subn(r'(?m)^GRUB_CMDLINE_LINUX_DEFAULT="([^"]*)"$',
+ lambda m: 'GRUB_CMDLINE_LINUX_DEFAULT="' + m[1] + ' ' + added + '"',
+ grub.read_text())
+ assert count == 1
+ grub.write_text(content)
+ config = ROOT / 'etc/dracut.conf.d/20-harness-crypt.conf'
+ config.write_text('add_dracutmodules+=" crypt "\n'
+ '# The acceptance VM uses a virtio keyboard, not Apple HID.\n'
+ 'force_drivers+=" virtio_input "\n')
+ run('chroot', str(ROOT), 'restorecon', '-F', '/etc/crypttab', '/etc/kernel/cmdline',
+ '/etc/default/grub', '/etc/dracut.conf.d/20-harness-crypt.conf')
+ run('chroot', str(ROOT), 'grubby', '--update-kernel=ALL', '--args=' + added)
+ run('chroot', str(ROOT), 'grub2-mkconfig', '-o', '/boot/grub2/grub.cfg')
+ kernels = [p.name for p in (ROOT / 'usr/lib/modules').iterdir() if p.is_dir() and (p / 'vmlinuz').is_file()]
+ assert len(kernels) == 1
+ initrd = '/boot/initramfs-' + kernels[0] + '.img'
+ run('chroot', str(ROOT), 'dracut', '--force', '--no-hostonly', initrd, kernels[0], timeout=180)
+ result['boot_entries'] = {p.name: p.read_text() for p in (ROOT / 'boot/loader/entries').glob('*.conf')}
+ assert result['boot_entries'] and all(arg in value for value in result['boot_entries'].values())
+ result['initramfs_modules'] = run('chroot', str(ROOT), 'lsinitrd', '-m', initrd)
+ assert 'crypt' in result['initramfs_modules'] and 'kernel-modules-asahi' in result['initramfs_modules']
+ contents = run('chroot', str(ROOT), 'lsinitrd', initrd)
+ result['keyboard_modules'] = ['spi-hid-apple.ko', 'dockchannel-hid.ko', 'virtio_input.ko']
+ assert all(name in contents for name in result['keyboard_modules'])
+ result['observer_console_arguments'] = consoles
+ result['observer_keyboard_driver'] = 'virtio_input'
+
+
+def prepare(source, result):
+ assert run('blkid', '-s', 'TYPE', '-o', 'value', DEVICE) == 'btrfs'
+ run('mount', '-o', 'ro,rescue=nologreplay,subvol=root', DEVICE, str(ROOT))
+ image = identity(source)
+ assert not (ROOT / 'var/lib/harness-os/firstboot.json').exists()
+ assert not any(1000 <= int(r.split(':')[2]) < 65534 for r in (ROOT / 'etc/passwd').read_text().splitlines())
+ run('umount', str(ROOT))
+ payload = int(run('blockdev', '--getsize64', DEVICE)) - 32 * 1024**2
+ print('Preparing private LUKS2 root', flush=True)
+ run('mount', '-o', 'subvol=root', DEVICE, str(ROOT))
+ run('btrfs', 'filesystem', 'resize', str(payload), str(ROOT))
+ run('umount', str(ROOT))
+ result.update(plaintext_bytes=payload, plaintext_sha256=digest(DEVICE, payload))
+ run('cryptsetup', 'reencrypt', '--encrypt', '--type', 'luks2', '--reduce-device-size', '32M',
+ '--batch-mode', '--key-file', '-', '--init-only', DEVICE, secret=PASSWORD)
+ run('cryptsetup', 'reencrypt', '--resume-only', '--key-file', '-', '--progress-json', DEVICE,
+ secret=PASSWORD, timeout=300)
+ uuid = run('cryptsetup', 'luksUUID', DEVICE)
+ result['luks_uuid'] = uuid
+ meta = json.loads(run('cryptsetup', 'luksDump', '--dump-json-metadata', DEVICE))
+ assert all(s['type'] == 'crypt' for s in meta['segments'].values())
+ assert not any('reencrypt' in json.dumps(s) for s in meta['keyslots'].values())
+ run('cryptsetup', 'open', '--key-file', '-', DEVICE, MAPPER, secret=PASSWORD)
+ assert digest('/dev/mapper/' + MAPPER, payload) == result['plaintext_sha256']
+ result['plaintext_preserved'] = True
+ run('mount', '-o', 'subvol=root', '/dev/mapper/' + MAPPER, str(ROOT))
+ run('mount', '/dev/vdb2', str(ROOT / 'boot'))
+ run('mount', '-o', 'ro', '/dev/vdb1', str(ROOT / 'boot/efi'))
+ for name in ('dev', 'proc', 'sys', 'run'):
+ run('mount', '--rbind', '/' + name, str(ROOT / name))
+ run('mount', '--make-rslave', str(ROOT / name))
+ assert not leaked_mounts(), 'Test mounts escaped into another namespace'
+ boot_configuration(uuid, result)
+ for name, expected in image['session_package']['files'].items():
+ assert digest(ROOT / name) == expected, name
+ run('sync')
+
+
+def recover(source, result):
+ assert run('blkid', '-s', 'TYPE', '-o', 'value', DEVICE) == 'crypto_LUKS'
+ failed = subprocess.run(['cryptsetup', 'open', '--readonly', '--key-file', '-', DEVICE, MAPPER],
+ input=b'incorrect-fixture-password', capture_output=True, timeout=30)
+ assert failed.returncode == 2 and not Path('/dev/mapper', MAPPER).exists()
+ result['incorrect_password_rejected'] = True
+ run('cryptsetup', 'open', '--readonly', '--key-file', '-', DEVICE, MAPPER, secret=PASSWORD)
+ run('mount', '-o', 'ro,rescue=nologreplay,subvol=root', '/dev/mapper/' + MAPPER, str(ROOT))
+ run('mount', '-o', 'ro,rescue=nologreplay,subvol=home', '/dev/mapper/' + MAPPER, str(ROOT / 'home'))
+ identity(source)
+ assert (ROOT / PROJECT).read_bytes() == PROJECT_TEXT
+ result['project_sha256'] = digest(ROOT / PROJECT)
+ result['readonly'] = run('blockdev', '--getro', '/dev/mapper/' + MAPPER) == '1'
+ assert result['readonly'] and not leaked_mounts()
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('phase', choices=['prepare', 'recover'])
+ parser.add_argument('--source', required=True)
+ args = parser.parse_args()
+ table = guard(args.source)
+ state = Path('/var/tmp/harness-encryption-' + args.phase + '.json')
+ if state.exists():
+ raise ValueError('Use a fresh owned fixture for each preparation or recovery attempt.')
+ ROOT.mkdir(exist_ok=True)
+ assert not any(ROOT.iterdir())
+ result = {'status': 'running', 'started_at': time.time(), 'phase': args.phase, 'source': args.source,
+ 'table': table, 'esp_sha256': digest('/dev/vdb1'), 'versions': run('rpm', '-q', 'cryptsetup', 'btrfs-progs')}
+ try:
+ try:
+ (prepare if args.phase == 'prepare' else recover)(args.source, result)
+ finally:
+ # Never force removal or close a still-mounted filesystem. Private
+ # propagation prevents service namespaces from retaining our mounts.
+ if ROOT.is_mount():
+ run('umount', '-R', str(ROOT))
+ if Path('/dev/mapper', MAPPER).exists():
+ run('cryptsetup', 'close', MAPPER, timeout=20)
+ assert not leaked_mounts() and not Path('/dev/mapper', MAPPER).exists()
+ assert table == json.loads(run('sfdisk', '--json', '/dev/vdb'))
+ assert digest('/dev/vdb1') == result['esp_sha256']
+ result.update(status='passed', mounts_isolated=True, mapping_closed=True)
+ except BaseException as error:
+ result.update(status='failed', error=str(error))
+ raise
+ finally:
+ result['finished_at'] = time.time()
+ state.write_text(json.dumps(result, indent=2) + '\n')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/os/tests/asahi_encryption_vm.py b/os/tests/asahi_encryption_vm.py
new file mode 100644
index 000000000..12980e084
--- /dev/null
+++ b/os/tests/asahi_encryption_vm.py
@@ -0,0 +1,233 @@
+#!/usr/bin/env python3
+"""Private encrypted-root acceptance on a disposable produced Asahi image.
+
+The maintenance VM sees only regular cloned image files. This does not install
+on a Mac, publish a password-bearing image, or claim physical keyboard support.
+"""
+import argparse
+import hashlib
+import json
+from pathlib import Path
+import platform
+import re
+import shlex
+import subprocess
+import time
+
+from arm_boot import digest
+from arm_session import SessionVM, fixture_identity
+from asahi_firstboot_vm import ImageVM, PASSWORD, evidence, setup_screen, type_line
+from asahi_encryption_guest import PROJECT, PROJECT_TEXT
+from session_vm import put
+
+
+class MaintenanceVM(SessionVM):
+ def __init__(self, folder, disk, kernel, target):
+ super().__init__(folder, disk, kernel)
+ if not target.is_file() or target.is_symlink():
+ raise ValueError('The encryption target must be a cloned regular file.')
+ self.target = target
+
+ def start(self, offline=False):
+ self.started = time.monotonic()
+ args = ['qemu-system-aarch64', '-machine', 'virt,gic-version=3', '-accel', 'hvf',
+ '-cpu', 'host', '-smp', '2', '-m', '3072', '-nodefaults', '-display', 'none', '-no-reboot',
+ '-kernel', str(self.kernel), '-append', 'root=/dev/vda rw console=tty0 console=ttyAMA0 loglevel=3 panic=1',
+ '-drive', f'file={self.disk},format=raw,if=none,id=root',
+ '-device', 'virtio-blk-pci,drive=root,serial=HARNESS_ARM_TEST',
+ '-drive', f'file={self.target},format=raw,if=none,id=target',
+ '-device', 'virtio-blk-pci,drive=target,serial=HARNESS_ENCRYPT_TEST,logical_block_size=4096,physical_block_size=4096',
+ '-device', 'virtio-gpu-pci', '-device', 'virtio-keyboard-pci', '-device', 'virtio-tablet-pci',
+ '-netdev', 'user,id=net', '-device', 'virtio-net-pci,netdev=net,id=hnnet,romfile=',
+ '-serial', f'unix:{self.control_path / "serial.sock"},server=on,wait=off',
+ '-qmp', f'unix:{self.control_path / "qmp.sock"},server=on,wait=off']
+ (self.folder / 'command.json').write_text(json.dumps(args, indent=2) + '\n')
+ self.process = subprocess.Popen(args, stdout=self.stderr, stderr=self.stderr)
+ self.serial = self.connect('serial.sock')
+ self.qmp = self.connect('qmp.sock')
+ self.qmp.settimeout(10)
+ self.qmp_file = self.qmp.makefile('rb', buffering=0)
+ json.loads(self.qmp_file.readline())
+ self.monitor('qmp_capabilities')
+ if offline:
+ self.monitor('set_link', name='hnnet', up=False)
+ self.wait('HARNESS_ARM_CONSOLE> ', timeout=180)
+ self.command('stty -echo')
+ self.command('test "$(getconf PAGESIZE)" = 16384 && test "$(uname -m)" = aarch64')
+ self.shell_ready = True
+
+
+def maintenance_phase(vm, phase, source):
+ script = Path(__file__).with_name('asahi_encryption_guest.py')
+ put(vm, '/var/tmp/harness-encryption-guest.py', script.read_text())
+ try:
+ vm.command('unshare --mount --propagation private python3 /var/tmp/harness-encryption-guest.py '
+ + phase + ' --source ' + shlex.quote(source), timeout=600)
+ except BaseException as error:
+ try:
+ raw = vm.read_file('/var/tmp/harness-encryption-' + phase + '.json')
+ (vm.folder / (phase + '.json')).write_bytes(raw)
+ except Exception as diagnostic:
+ error.add_note('Could not collect the partial phase receipt: ' + str(diagnostic))
+ raise
+ else:
+ raw = vm.read_file('/var/tmp/harness-encryption-' + phase + '.json')
+ (vm.folder / (phase + '.json')).write_bytes(raw)
+ result = json.loads(raw)
+ assert result['status'] == 'passed' and result['mounts_isolated'] and result['mapping_closed']
+ vm.command('test ! -e /dev/mapper/harness-encryption-test && '
+ 'test -z "$(findmnt -rn --mountpoint /mnt/harness-encryption-test)"')
+ return result
+
+
+def unlock(vm, *, reject_wrong=False):
+ vm.frame('01-unlock', 'passphrase', seconds=90)
+ if reject_wrong:
+ serial = vm.folder / 'serial.log'
+ offset = serial.stat().st_size
+ type_line(vm, 'incorrect-password')
+ # Plymouth repeats the prompt without displaying cryptsetup's journal
+ # error. Wait for that new prompt (not an old screenshot), then check
+ # the actual rejection in the initrd journal after successful unlock.
+ deadline = time.monotonic() + 45
+ while b'\nPlease enter passphrase for disk ' not in serial.read_bytes()[offset:]:
+ if vm.process.poll() is not None or time.monotonic() > deadline:
+ raise RuntimeError('Wrong graphical password did not reach a fresh unlock prompt.')
+ time.sleep(.1)
+ vm.frame('02-rejected', 'passphrase')
+ vm.type_probe(PASSWORD)
+ vm.frame('03-masked-unlock', 'passphrase', absent=[PASSWORD])
+ vm.keys('ret')
+
+
+def encrypted_root(vm):
+ script = '''import json,pathlib,subprocess
+def command(*args): return subprocess.check_output(args,text=True).strip()
+assert command('getconf','PAGESIZE')=='16384'
+assert command('getenforce')=='Enforcing'
+assert command('findmnt','-no','SOURCE','/')=='/dev/mapper/harness-root[/root]'
+assert command('findmnt','-no','SOURCE','/home')=='/dev/mapper/harness-root[/home]'
+assert command('blkid','-s','TYPE','-o','value','/dev/vda3')=='crypto_LUKS'
+assert command('cryptsetup','status','harness-root').find('/dev/vda3')>=0
+assert command('systemctl','--failed','--no-pager','--no-legend')==''
+subprocess.run(['rpm','-V','harness-os-session'],check=True)
+record={'kernel':command('uname','-r'),'root':command('findmnt','-no','SOURCE','/'),
+ 'home':command('findmnt','-no','SOURCE','/home'),'luks_uuid':command('cryptsetup','luksUUID','/dev/vda3'),
+ 'selinux':command('getenforce'),'failed_units':[],
+ 'initrd_journal':command('journalctl','-b','--no-pager','-o','cat','-u','systemd-cryptsetup@harness\\\\x2droot.service')}
+pathlib.Path('/tmp/harness-encrypted-root.json').write_text(json.dumps(record,indent=2)+'\\n')
+'''
+ put(vm, '/tmp/harness-encrypted-root.py', script)
+ vm.command('python3 /tmp/harness-encrypted-root.py')
+ raw = vm.read_file('/tmp/harness-encrypted-root.json')
+ (vm.folder / 'encrypted-root.json').write_bytes(raw)
+ return json.loads(raw)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--image', type=Path, required=True)
+ parser.add_argument('--sha256', required=True)
+ parser.add_argument('--image-source', required=True)
+ parser.add_argument('--fixture', type=Path, required=True, help='Verified native ARM maintenance VM fixture.')
+ parser.add_argument('--fixture-source', required=True)
+ parser.add_argument('--output', type=Path, required=True)
+ args = parser.parse_args()
+ if (platform.system(), platform.machine()) != ('Darwin', 'arm64'):
+ parser.error('Use the native Apple Silicon host observer.')
+ if not re.fullmatch('[a-f0-9]{40}', args.image_source) or not re.fullmatch('[a-f0-9]{64}', args.sha256):
+ parser.error('Use full source and image SHA-256 identities.')
+ source = args.image.resolve()
+ if args.image.is_symlink() or not source.is_file() or digest(source) != args.sha256:
+ parser.error('Use the regular, SHA-256-verified private image.')
+ info = fixture_identity(args.fixture, args.fixture_source)
+ output = args.output.resolve()
+ output.mkdir(parents=True, exist_ok=False)
+ disk, maintenance = output / 'encrypted.raw', output / 'maintenance.raw'
+ subprocess.run(['cp', '-c', source, disk], check=True, timeout=60)
+ subprocess.run(['zstd', '-d', '--sparse', args.fixture / 'guest.raw.zst', '-o', maintenance],
+ check=True, timeout=120)
+ assert digest(maintenance) == info['raw_disk']['sha256']
+ receipt = {'status': 'running', 'started_at': time.time(), 'image_sha256': args.sha256,
+ 'image_source': args.image_source, 'maintenance_source': args.fixture_source,
+ 'maintenance_manifest_sha256': digest(args.fixture / 'manifest.json'),
+ 'scope': 'Native ARM 16 KiB UEFI VM, cloned produced Asahi image; no physical Apple hardware claim',
+ 'publication': False, 'checks': [],
+ 'limitations': ['Fixture conversion is not an installer or power-loss-safe enrollment flow',
+ 'Public fixture password; this encrypted copy must never be published',
+ 'VM consoles and virtio input differ from physical Apple hardware'],
+ 'observer_files': {name: digest(Path(__file__).with_name(name)) for name in
+ ('asahi_encryption_vm.py', 'asahi_encryption_guest.py', 'asahi_firstboot_vm.py',
+ 'arm_boot.py', 'arm_session.py', 'fedora_session_vm.py', 'session_vm.py', 'vm.py')}}
+ vm = None
+ try:
+ vm = MaintenanceVM(output / 'maintenance-prepare', maintenance, args.fixture / 'Image', disk)
+ vm.start()
+ vm.command('dnf5 install -y --setopt=install_weak_deps=False --setopt=gpgcheck=True cryptsetup btrfs-progs', timeout=240)
+ receipt['prepare'] = maintenance_phase(vm, 'prepare', args.image_source)
+ receipt['checks'].append('Isolated LUKS2 conversion preserves exact plaintext filesystem bytes, partition table, ESP, Harness files and Asahi initrd drivers')
+ receipt['maintenance_shutdown'] = vm.poweroff()
+ vm.close()
+ vm = ImageVM(output / 'encrypted-firstboot', disk, None)
+ vm.start()
+ unlock(vm, reject_wrong=True)
+ setup_screen(vm)
+ vm.authenticate()
+ receipt['first_root'] = encrypted_root(vm)
+ assert 'Failed to activate with specified passphrase.' in receipt['first_root']['initrd_journal']
+ first_account = evidence(vm, vm.folder)
+ vm.wait_user('pgrep -u 1000 -x opencode >/dev/null && test "$(hn list-panes -F "#{pane_id}" | wc -l)" -eq 3')
+ vm.user('mkdir -p ~/projects/encryption-check && printf %s ' + shlex.quote(PROJECT_TEXT.decode()) +
+ ' > ' + shlex.quote('/' + PROJECT))
+ assert vm.read_file('/' + PROJECT) == PROJECT_TEXT
+ receipt['checks'].append('Graphical keyboard rejects a wrong disk password; correct masked input reaches account setup and OpenCode with two terminals; no failed services')
+ receipt['first_shutdown'] = vm.poweroff()
+ vm.close()
+ vm = ImageVM(output / 'encrypted-reboot', disk, None)
+ vm.start()
+ unlock(vm)
+ vm.authenticate()
+ receipt['second_root'] = encrypted_root(vm)
+ vm.wait_user('systemctl --user is-active --quiet hn-screen && test "$(hn list-panes -F "#{pane_id}" | wc -l)" -eq 3')
+ assert evidence(vm, vm.folder) == first_account
+ assert vm.read_file('/' + PROJECT) == PROJECT_TEXT
+ vm.screenshot('04-restored-workspace')
+ receipt['checks'].append('Subsequent graphical unlock reaches the restored three-pane workspace and preserves account and project bytes')
+ receipt['second_shutdown'] = vm.poweroff()
+ vm.close()
+ vm = MaintenanceVM(output / 'offline-recovery', maintenance, args.fixture / 'Image', disk)
+ vm.start(offline=True)
+ receipt['recovery'] = maintenance_phase(vm, 'recover', args.image_source)
+ receipt['recovery_shutdown'] = vm.poweroff()
+ receipt['checks'].append('Offline read-only recovery rejects an incorrect password, recovers the exact project, and closes all mounts/mappings')
+ receipt.update(status='passed', project_sha256=hashlib.sha256(PROJECT_TEXT).hexdigest())
+ print('Encrypted root boot, account setup, reboot and offline recovery passed', flush=True)
+ except BaseException as error:
+ receipt.update(status='failed', error=str(error))
+ if vm:
+ try:
+ vm.screenshot('failure')
+ if vm.shell_ready:
+ logs, _ = vm.command('journalctl -b --no-pager -n 150; systemctl --failed --no-pager', check=False, timeout=30)
+ (vm.folder / 'diagnosis.txt').write_text(logs)
+ except Exception as diagnostic:
+ receipt['diagnostic_error'] = str(diagnostic)
+ raise
+ finally:
+ try:
+ if vm:
+ vm.close()
+ except Exception as error:
+ receipt.update(status='failed', cleanup_error=str(error))
+ raise
+ finally:
+ receipt.update(finished_at=time.time(), source_unchanged=digest(source) == args.sha256)
+ if not receipt['source_unchanged']:
+ receipt.update(status='failed', error='Original source image changed.')
+ (output / 'receipt.json').write_text(json.dumps(receipt, indent=2) + '\n')
+ if receipt['status'] != 'passed':
+ raise SystemExit(1)
+
+
+if __name__ == '__main__':
+ main()