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: install the private Asahi image through one terminal form (#952)

Deee0d2189b3b5a
diff --git a/os/platforms/apple-silicon/README.md b/os/platforms/apple-silicon/README.md
index f117de930..ee3c5bac1 100644
--- a/os/platforms/apple-silicon/README.md
+++ b/os/platforms/apple-silicon/README.md
@@ -6,8 +6,9 @@ hn, OpenCode with upstream defaults, terminal panes and the optional Chromium
browser. It selects no GNOME or KDE desktop profile.
This is private installation work, **not an installable Harness release**. Installer
-media/UI, Fedora base-system updates/recovery and physical Apple hardware acceptance remain
-required. The image contains no pre-created user or known login password. Never
+media, Fedora base-system updates/recovery and physical Apple hardware acceptance remain
+required. A private terminal installer joins the tested stages below; bootable
+installer media is still pending. The image contains no pre-created user or known login password. Never
flash this raw disk over a Mac's disk or use the PC whole-disk installer on Apple
Silicon. No public installer metadata or download feed is generated.
@@ -113,7 +114,8 @@ It reads Asahi's firmware-provided EFI partition identity and uses only the
unallocated space immediately after that partition. It never shrinks, moves,
formats or removes existing macOS, recovery or other operating-system partitions.
The prepared gap must hold a 1 GiB boot partition and at least 12 GiB for the
-encrypted root. This module is not yet packaged or connected to an installer UI.
+encrypted root. The private terminal installer uses this module; it is not yet
+packaged into bootable installer media.
Before either GPT entry is written, a plan is atomically saved in a private
directory on the owning FAT EFI partition. Mount that ESP with root ownership,
@@ -139,7 +141,8 @@ kernel partition geometry, repeated execution, and refusal of changed or damaged
metadata. QEMU injects the firmware ESP identity; its protected partitions contain
sentinels, not macOS filesystems. These checks do not establish physical Apple
support or recovery from a torn GPT write. Fresh encryption, payload copying,
-boot configuration and installer-media integration remain the next stages.
+boot configuration and installer-media integration require their separate checks
+below; partition preparation alone does not install an operating system.
## Private encrypted payload copy
@@ -225,6 +228,52 @@ services. The observer adds only QEMU console and keyboard configuration.
This does not validate Apple's boot policy, m1n1 handoff, physical hardware or
recovery from arbitrary power loss. The existing Apple boot chain still needs its
-platform integration and hardware acceptance. These modules are not yet packaged
-into installer media or connected to a user-facing installation screen. Never
-publish the test disk, which contains a known fixture password.
+platform integration and hardware acceptance. The terminal installer below joins
+these stages, but bootable installer media is still pending. Never publish the test
+disk, which contains a known fixture password.
+
+## Private terminal installer
+
+`install.py` presents the prepared storage, enabled encryption, **Password**,
+**Repeat password**, and **Install Harness**. Password is focused initially; Tab,
+Enter and ordinary field-editing keys work. Labels stay unhighlighted, entered
+characters stay masked, and the install button gains emphasis when focused. The
+same centered wordmark and status placement carry through progress and completion.
+
+Actual private ARM VM console, with the password field focused and then the install
+button focused. These are interface checks, not physical Apple hardware evidence.
+
+![Password field focused; install button gray](screenshots/install.png)
+![Install button focused; black text on white](screenshots/install-focused.png)
+
+Asahi firmware identifies the destination. There is no whole-disk picker or
+macOS partition-resizing action. Opening or canceling the form mounts the owning
+EFI partition read-only and creates no installation record. Pressing Install
+first verifies the payload checksum, rechecks the target, and only then saves
+the plan and runs partition preparation, encryption, copying, account enrollment
+and boot setup. A mounted installation is refused. Existing progress resumes
+through the stages' durable records; passwords are never written to them.
+
+The command takes a read-only raw image block device, SHA-256 and producer commit
+from private media. It enters a private mount namespace and takes an installer
+lock. It accepts no password in arguments or configuration. Diagnostics go to
+root-only `/var/log/harness-asahi-install.log`; a failed attempt returns to the
+form. Completion unmounts the target before offering **Shut down**. A failed
+shutdown stays on that completed screen and never reruns installation.
+
+```sh
+python3 os/tests/asahi_install_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-install
+```
+
+The native observer drives the actual terminal with graphical keyboard input.
+It checks cancellation, mismatched passwords and an invalid image checksum
+against unchanged target metadata and full EFI bytes; then completes installation
+offline, uses the screen's shutdown action, and unlocks the resulting target into
+OpenCode and two terminals. Protected partition sentinels, image provenance,
+frozen runtime files, SELinux and account configuration remain checked. Screenshots
+and failed attempts are retained. This uses QEMU's firmware and console; physical
+Apple boot, keyboard and pointer acceptance remain separate.
diff --git a/os/platforms/apple-silicon/install.py b/os/platforms/apple-silicon/install.py
new file mode 100644
index 000000000..2ae7f0181
--- /dev/null
+++ b/os/platforms/apple-silicon/install.py
@@ -0,0 +1,355 @@
+#!/usr/bin/python3
+"""Private Asahi installer UI. Use only space prepared by the Asahi installer.
+
+Media supplies the read-only payload and its immutable identity. This command
+never selects or erases a whole disk and is not an Apple boot-policy installer.
+"""
+import argparse
+from contextlib import contextmanager
+import curses
+import fcntl
+import importlib.util
+import json
+import os
+from pathlib import Path
+import platform
+import stat
+import subprocess
+import sys
+import textwrap
+
+spec = importlib.util.spec_from_file_location('asahi_startup', Path(__file__).with_name('startup.py'))
+startup = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(startup)
+storage, target = startup.storage, startup.target
+WORDMARK = ('█ █ ▄▀█ █▀█ █▄ █ █▀▀ █▀ █▀', '█▀█ █▀█ █▀▄ █ ▀█ ██▄ ▄█ ▄█')
+RECORD = Path('asahi/harness-install/target.json')
+LOG = Path('/var/log/harness-asahi-install.log')
+
+
+def validate_password(password, repeat):
+ if not password:
+ raise ValueError('Enter a password.')
+ if any(c in password for c in '\n\r\0'):
+ raise ValueError('Use a password without line breaks.')
+ if password != repeat:
+ raise ValueError('Passwords do not match.')
+
+
+def verify_destination(plan):
+ """Read-only recheck before presenting or committing the selected space."""
+ target.validate_plan(plan)
+ device = plan['original']['device']
+ esp = target.platform_esp()
+ if esp != plan['esp_uuid'] or target.owning_disk(target.inventory(), esp) != device:
+ raise target.TargetError('This space belongs to another Asahi installation.')
+ fd = os.open(device, os.O_RDONLY | os.O_NOFOLLOW)
+ try:
+ if (not stat.S_ISBLK(os.fstat(fd).st_mode) or
+ target.command('blockdev', '--getss', device) != '4096' or
+ target.command('blockdev', '--getro', device) != '0'):
+ raise target.TargetError('Use the writable internal Asahi disk.')
+ target.lock_disk(fd)
+ snapshot = target.read_table(device)
+ target.verify_gpt(fd, int(target.command('blockdev', '--getsize64', device)), target.normalize(snapshot))
+ target.remaining(plan, snapshot)
+ nodes = {part['node'] for part in plan['additions']}
+ inventory = json.loads(target.command('lsblk', '--json', '--paths', '--output', 'NAME,MOUNTPOINTS', device))
+ def mounted(entry):
+ return any(entry.get('mountpoints') or []) or any(mounted(c) for c in entry.get('children', []))
+ for entry in inventory['blockdevices']:
+ for part in entry.get('children', []):
+ if part['name'] in nodes and mounted(part):
+ raise target.TargetError('The installed system is in use. Start from installer media.')
+ finally:
+ os.close(fd)
+
+
+@contextmanager
+def destination():
+ """Inspect the firmware-owned ESP read-only; cancellation writes nothing."""
+ if (platform.system() != 'Linux' or os.geteuid() != 0 or
+ os.readlink('/proc/self/ns/mnt') == os.readlink('/proc/1/ns/mnt') or
+ target.command('findmnt', '-nro', 'PROPAGATION', '/') != 'private'):
+ raise target.TargetError('Start the installer in its private Linux mount namespace.')
+ esp = target.platform_esp()
+ disk = target.owning_disk(target.inventory(), esp)
+ table = target.normalize(target.read_table(disk))
+ part = next(p for p in table['partitions'] if p['uuid'] == esp)
+ if part['type'] != target.EFI:
+ raise target.TargetError('The Asahi boot partition has changed.')
+ with storage.work_directory() as work:
+ with storage.mounted(part['node'], work / 'esp', 'ro,noatime,uid=0,gid=0,fmask=0177,dmask=0077') as root:
+ path = root / RECORD
+ plan = target.load_plan(path) if os.path.lexists(path) else target.new_plan(
+ {'partitiontable': {**table, 'label': 'gpt', 'unit': 'sectors'}}, esp)
+ verify_destination(plan)
+ yield root, plan
+
+
+def install(root, plan, payload, password, progress):
+ validate_password(password, password)
+ progress('Checking installation files…')
+ # An invalid source must not even create destination partitions or a receipt.
+ with payload.open():
+ verify_destination(plan)
+ progress('Preparing storage…')
+ storage.run('mount', '-o', 'remount,rw', root)
+ path = root / RECORD
+ if os.path.lexists(path):
+ if target.load_plan(path) != plan:
+ raise target.TargetError('The installation plan changed. Keep it for recovery.')
+ else:
+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
+ target.save_plan(path, plan)
+ target.apply_plan(path)
+ storage.install(path, payload, password, progress=progress)
+ progress('Preparing startup…')
+ def phase(value):
+ progress({'boot': 'Setting up your account…', 'account': 'Finishing installation…',
+ 'complete': 'Harness is installed.'}[value])
+ state = startup.finish(path, payload, password, progress=phase)
+ if state['phase'] != 'complete':
+ raise storage.StorageError('Installation has not finished. Start the installer again to continue.')
+ storage.run('sync', '-f', root)
+ return state
+
+
+def diagnostic(error):
+ fd = os.open(LOG, os.O_WRONLY | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW, 0o600)
+ with os.fdopen(fd, 'a') as stream:
+ os.fchmod(stream.fileno(), 0o600)
+ stream.write(type(error).__name__ + ': ' + str(error) + '\n')
+
+
+class Page:
+ """One terminal page: prepared space, two hidden fields, one install action."""
+ def __init__(self, screen):
+ self.screen = screen
+ self.values, self.positions, self.focus = ['', ''], [0, 0], 0
+ self.error = ''
+ self.accent, self.idle, self.active = curses.A_BOLD, curses.A_REVERSE, curses.A_REVERSE
+ self.palette = []
+ self.hits = []
+ screen.keypad(True)
+ try:
+ curses.start_color()
+ curses.use_default_colors()
+ curses.init_pair(1, curses.COLOR_YELLOW, -1)
+ idle, active = (250, 255) if curses.COLORS >= 256 else (curses.COLOR_WHITE, curses.COLOR_WHITE)
+ if curses.COLORS < 256 and curses.can_change_color():
+ # The Linux console exposes eight colors. Bold black becomes
+ # gray rather than making a background brighter. Reserve two
+ # palette entries so focus is black-on-white, never gray-on-gray.
+ idle, active = curses.COLOR_CYAN, curses.COLOR_WHITE
+ for color, level in ((idle, 700), (active, 1000)):
+ self.palette.append((color, *curses.color_content(color)))
+ curses.init_color(color, level, level, level)
+ curses.init_pair(2, curses.COLOR_BLACK, idle)
+ curses.init_pair(3, curses.COLOR_BLACK, active)
+ self.accent |= curses.color_pair(1)
+ self.idle, self.active = curses.color_pair(2), curses.color_pair(3)
+ curses.mousemask(curses.BUTTON1_CLICKED | curses.BUTTON1_RELEASED)
+ except curses.error:
+ pass
+
+ def close(self):
+ for entry in reversed(self.palette):
+ try:
+ curses.init_color(*entry)
+ except curses.error:
+ pass
+
+ def line(self, row, text, *, offset=0, width=None, attr=0):
+ height, columns = self.screen.getmaxyx()
+ y, x = self.top + row, self.left + offset
+ limit = min(self.width - offset if width is None else width, columns - x - 1)
+ if 0 <= y < height and 0 <= x < columns - 1 and limit > 0:
+ self.screen.addnstr(y, x, text, limit, attr)
+
+ def render(self, storage_label='', status=None, done=False):
+ self.screen.erase()
+ height, columns = self.screen.getmaxyx()
+ self.width = min(60, max(1, columns - 4))
+ self.left, self.top = max(0, (columns - self.width) // 2), max(0, height // 2 - 7)
+ self.hits = []
+ for row, word in enumerate(WORDMARK):
+ self.line(row, word.center(self.width), attr=self.accent)
+ usable = columns >= 54 and height >= 18
+ if status is not None:
+ for row, text in enumerate(textwrap.wrap(status, min(48, self.width))):
+ self.line(5 + row, text.center(self.width))
+ if done:
+ self.button(9, 'Shut down', 2, compact=True)
+ elif not usable:
+ self.line(5, 'Resize to 54 columns and 18 rows.')
+ else:
+ self.line(4, 'Disk')
+ self.line(4, storage_label, offset=18)
+ self.line(6, 'Encryption')
+ self.line(6, '[x]', offset=18)
+ capacity = self.width - 20
+ for index, label in enumerate(('Password', 'Repeat password')):
+ row = 8 + index * 2
+ position = self.positions[index]
+ start = max(0, position - capacity + 1)
+ mask = '*' * len(self.values[index][start:start + capacity])
+ self.line(row, label)
+ self.line(row, (' ' + mask).ljust(self.width - 18), offset=18,
+ attr=self.active if self.focus == index else 0)
+ self.hits.append((self.top + row, self.left + 18, self.left + self.width, index))
+ for row, text in enumerate(self.error.splitlines()[:2]):
+ self.line(12 + row, text)
+ self.button(14, 'Install Harness', 2)
+ try:
+ editing = usable and status is None and self.focus < 2
+ curses.curs_set(int(editing))
+ if editing:
+ self.screen.move(self.top + 8 + self.focus * 2,
+ self.left + 19 + min(self.positions[self.focus], self.width - 21))
+ except curses.error:
+ pass
+ self.screen.refresh()
+ return usable
+
+ def button(self, row, text, index, compact=False):
+ label = '[ ' + text + ' ]' if compact else text
+ width = len(label) if compact else self.width
+ offset = (self.width - width) // 2
+ self.line(row, label.center(width), offset=offset, width=width,
+ attr=self.active if self.focus == index or compact else self.idle)
+ self.hits.append((self.top + row, self.left + offset, self.left + offset + width, index))
+
+ def edit(self, key):
+ i = self.focus
+ value, position = self.values[i], self.positions[i]
+ if key in ('\b', '\x7f', curses.KEY_BACKSPACE) and position:
+ value, position = value[:position - 1] + value[position:], position - 1
+ elif key == curses.KEY_DC:
+ value = value[:position] + value[position + 1:]
+ elif key == '\x15':
+ value, position = '', 0
+ elif key == curses.KEY_LEFT:
+ position = max(0, position - 1)
+ elif key == curses.KEY_RIGHT:
+ position = min(len(value), position + 1)
+ elif key == curses.KEY_HOME:
+ position = 0
+ elif key == curses.KEY_END:
+ position = len(value)
+ elif isinstance(key, str) and key.isprintable() and len(value) < 4096:
+ value, position = value[:position] + key + value[position:], position + len(key)
+ self.values[i], self.positions[i], self.error = value, position, ''
+
+ def key(self):
+ key = self.screen.get_wch()
+ if key == curses.KEY_MOUSE:
+ try:
+ _, x, y, _, buttons = curses.getmouse()
+ if buttons & (curses.BUTTON1_CLICKED | curses.BUTTON1_RELEASED):
+ for row, first, end, index in self.hits:
+ if y == row and first <= x < end:
+ self.focus = index
+ return '\n' if index == 2 else None
+ except curses.error:
+ pass
+ return key
+
+ def password(self, label):
+ while True:
+ usable = self.render(label)
+ key = self.key()
+ if key in ('\x1b', '\x03'):
+ self.values = ['', '']
+ return None
+ if not usable:
+ continue
+ if key in ('\t', curses.KEY_DOWN):
+ self.focus = (self.focus + 1) % 3
+ elif key in (curses.KEY_UP, curses.KEY_BTAB):
+ self.focus = (self.focus - 1) % 3
+ elif key in ('\r', '\n', curses.KEY_ENTER):
+ if self.focus < 2:
+ self.focus += 1
+ else:
+ try:
+ validate_password(*self.values)
+ password = self.values[0]
+ self.values, self.positions = ['', ''], [0, 0]
+ return password
+ except ValueError as error:
+ self.error = str(error)
+ elif self.focus < 2:
+ self.edit(key)
+
+ def progress(self, message):
+ try:
+ self.render(status=message)
+ except curses.error:
+ pass # Resizing or losing the display must not interrupt disk work.
+
+ def complete(self):
+ curses.flushinp()
+ message = 'Harness is installed. Shut down, remove the USB, then turn on your computer.'
+ while True:
+ self.render(status=message, done=True)
+ if self.key() in ('\r', '\n', curses.KEY_ENTER):
+ try:
+ storage.run('systemctl', 'poweroff')
+ return
+ except (OSError, ValueError, subprocess.SubprocessError) as error:
+ diagnostic(error)
+ message = 'Harness is installed. Could not shut down. Try again.'
+
+
+def application(screen, payload):
+ curses.raw()
+ view = Page(screen)
+ try:
+ with destination() as (root, plan):
+ size = sum(p['size'] for p in plan['additions']) * 4096 / 1024**3
+ label = f'{Path(plan["original"]["device"]).name} · {size:.1f} GiB prepared'
+ while True:
+ password = view.password(label)
+ if password is None:
+ return
+ try:
+ install(root, plan, payload, password, view.progress)
+ break
+ except (OSError, ValueError, subprocess.SubprocessError) as error:
+ diagnostic(error)
+ view.error, view.focus = 'Installation stopped. Details:\n' + str(LOG), 0
+ finally:
+ password = None
+ # Unmount the ESP before reporting success or asking the computer to stop.
+ view.complete()
+ finally:
+ view.close()
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--source-device', required=True, help='Read-only raw image device supplied by installer media')
+ parser.add_argument('--sha256', required=True)
+ parser.add_argument('--image-source', required=True)
+ args = parser.parse_args()
+ if platform.system() != 'Linux' or os.geteuid() != 0:
+ parser.error('Start from the private Harness Asahi installer media.')
+ payload = storage.Payload(args.source_device, args.sha256, args.image_source)
+ if not sys.stdin.isatty() or not sys.stdout.isatty():
+ parser.error('The installer needs a terminal.')
+ if os.readlink('/proc/self/ns/mnt') == os.readlink('/proc/1/ns/mnt'):
+ os.execv('/usr/bin/unshare', ['unshare', '--mount', '--propagation', 'private',
+ '/usr/bin/python3', str(Path(__file__).resolve()), *sys.argv[1:]])
+ lock = os.open('/run/harness-asahi-install.lock', os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
+ try:
+ target.private_file(lock)
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ curses.set_escdelay(25)
+ curses.wrapper(lambda screen: application(screen, payload))
+ finally:
+ os.close(lock)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/os/platforms/apple-silicon/screenshots/install-focused.png b/os/platforms/apple-silicon/screenshots/install-focused.png
new file mode 100644
index 000000000..e00783142
Binary files /dev/null and b/os/platforms/apple-silicon/screenshots/install-focused.png differ
diff --git a/os/platforms/apple-silicon/screenshots/install.png b/os/platforms/apple-silicon/screenshots/install.png
new file mode 100644
index 000000000..72ef9a0df
Binary files /dev/null and b/os/platforms/apple-silicon/screenshots/install.png differ
diff --git a/os/tests/arm_session.py b/os/tests/arm_session.py
index cc1d96285..2ebf3449f 100644
--- a/os/tests/arm_session.py
+++ b/os/tests/arm_session.py
@@ -118,6 +118,13 @@ class SessionVM(VM):
ImageOps.expand(readable, border=24, fill=255).save(ocr_frame)
output = subprocess.check_output(['tesseract', str(ocr_frame), 'stdout', '--psm', '11'],
text=True, stderr=subprocess.DEVNULL, timeout=15)
+ if not frame_contains(output, text, absent):
+ # Sparse-text segmentation can omit a reverse-video button on
+ # the Linux console. Also read the same real frame as a block;
+ # retain both readings, including all forbidden-text checks.
+ output += '\n' + subprocess.check_output(
+ ['tesseract', str(ocr_frame), 'stdout', '--psm', '6'],
+ text=True, stderr=subprocess.DEVNULL, timeout=15)
(self.folder / (name + '.txt')).write_text(output)
if frame_contains(output, text, absent):
return
@@ -141,7 +148,7 @@ class SessionVM(VM):
self.frame(name, marker)
self.keys('ctrl', 'd')
- def poweroff(self, timeout=60):
+ def poweroff(self, timeout=60, *, request=True):
started = time.monotonic()
report = {'status': 'waiting', 'events': []}
streams = {self.serial: 'serial', self.qmp: 'qmp'}
@@ -149,7 +156,8 @@ class SessionVM(VM):
try:
# The test console may terminate before printing a command result.
# Require the guest's actual shutdown event and clean QEMU exit.
- self.send('sync; systemctl poweroff --no-block\n')
+ if request:
+ self.send('sync; systemctl poweroff --no-block\n')
while True:
remaining = timeout - (time.monotonic() - started)
exited = self.process.poll() is not None
diff --git a/os/tests/asahi_install_guest.py b/os/tests/asahi_install_guest.py
new file mode 100644
index 000000000..8b4459c36
--- /dev/null
+++ b/os/tests/asahi_install_guest.py
@@ -0,0 +1,88 @@
+#!/usr/bin/python3
+"""VM-only observer for the real private installer. Never run on host disks."""
+import importlib.util
+import json
+from pathlib import Path
+import sys
+
+
+def module(name, path):
+ spec = importlib.util.spec_from_file_location(name, path)
+ value = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(value)
+ return value
+
+
+ui = module('install', '/var/tmp/install.py')
+fixture = module('fixture', '/var/tmp/harness-target-guest.py')
+fixture.guard()
+ui.target.platform_esp = lambda: fixture.ESP
+assert fixture.run('lsblk', '-ndo', 'SERIAL', '/dev/vdc') == 'HARNESS_PAYLOAD'
+
+
+def inspect():
+ # The live form already has a read-only view. Observe with the same flags;
+ # asking for a writable FAT superblock here would conflict with that view.
+ fixture.run('mount', '-t', 'vfat', '-o', 'ro,noatime,uid=0,gid=0,fmask=0177,dmask=0077',
+ fixture.DISK + '2', fixture.ROOT)
+ try:
+ baseline = json.loads(fixture.BASELINE.read_text())
+ protected = fixture.protected()
+ assert protected == {k: v for k, v in baseline.items() if k not in ('table', 'started_at')}
+ result = {'protected': protected, 'metadata': fixture.metadata(),
+ 'esp_sha256': fixture.digest(fixture.DISK + '2')}
+ if fixture.PLAN.exists():
+ plan = ui.target.load_plan(fixture.PLAN)
+ result['plan'] = plan
+ result['remaining'] = ui.target.remaining(plan, ui.target.read_table(fixture.DISK))
+ for name in ('storage', 'startup'):
+ result[name] = json.loads(fixture.PLAN.with_name(name + '.json').read_text())
+ Path('/var/tmp/harness-install-inspection.json').write_text(json.dumps(result, indent=2) + '\n')
+ finally:
+ fixture.run('umount', fixture.ROOT)
+
+
+if sys.argv[1] == 'reset-plan':
+ # initialize() owns this blank fixture and creates its first plan. Remove
+ # only that never-applied plan so the real UI must discover and save its own.
+ fixture.mount()
+ try:
+ plan = ui.target.load_plan(fixture.PLAN)
+ assert ui.target.remaining(plan, ui.target.read_table(fixture.DISK)) == plan['additions']
+ fixture.PLAN.unlink()
+ fixture.PLAN.with_name('target.json.lock').unlink()
+ fixture.PLAN.parent.rmdir()
+ finally:
+ fixture.run('umount', fixture.ROOT)
+ inspect()
+elif sys.argv[1] == 'inspect':
+ inspect()
+elif sys.argv[1] == 'reject-mounted':
+ occupied = Path('/mnt/harness-occupied-test')
+ occupied.mkdir()
+ fixture.run('mount', '-o', 'ro,noload', '/dev/vdb5', occupied)
+ try:
+ try:
+ with ui.destination():
+ raise AssertionError('An in-use target was offered for installation')
+ except ui.target.TargetError as error:
+ assert 'in use' in str(error)
+ finally:
+ fixture.run('umount', occupied)
+ occupied.rmdir()
+else:
+ assert sys.argv[1] == 'screen'
+ # QEMU has no Apple firmware handoff. It also needs only these two display
+ # observer additions for the installed boot; all target guards still run.
+ configuration = ui.startup.configuration
+ def observed(*args):
+ config = configuration(*args)
+ consoles = ' console=ttyAMA0 console=tty0'
+ config['etc/kernel/cmdline'] = config['etc/kernel/cmdline'].strip() + consoles + '\n'
+ config['etc/default/grub'] = config['etc/default/grub'].replace(
+ '=harness-root"', '=harness-root' + consoles + '"')
+ config['etc/dracut.conf.d/20-harness-crypt.conf'] += 'force_drivers+=" virtio_input "\n'
+ return config
+ ui.startup.configuration = observed
+ sys.argv = [sys.argv[0], *sys.argv[2:]]
+ ui.main()
diff --git a/os/tests/asahi_install_vm.py b/os/tests/asahi_install_vm.py
new file mode 100644
index 000000000..a15a965a3
--- /dev/null
+++ b/os/tests/asahi_install_vm.py
@@ -0,0 +1,186 @@
+#!/usr/bin/env python3
+"""Drive the real install form, then unlock and boot its fresh encrypted target."""
+import argparse
+import json
+from pathlib import Path
+import platform
+import re
+import subprocess
+import time
+
+from arm_boot import digest
+from arm_session import fixture_identity
+from asahi_encryption_vm import MaintenanceVM, unlock
+from asahi_firstboot_vm import ImageVM, PASSWORD, evidence, type_line
+from asahi_startup_vm import installed
+from asahi_target_vm import guest as target_guest
+from session_vm import put
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def stage(vm):
+ for name in ('install.py', 'startup.py', 'storage.py', 'target.py'):
+ put(vm, '/var/tmp/' + name, (ROOT / 'platforms/apple-silicon' / name).read_text())
+ put(vm, '/var/tmp/harness-install-guest.py', Path(__file__).with_name('asahi_install_guest.py').read_text())
+
+
+def inspect(vm, action='inspect'):
+ vm.command('unshare --mount --propagation private python3 /var/tmp/harness-install-guest.py ' + action)
+ return json.loads(vm.read_file('/var/tmp/harness-install-inspection.json'))
+
+
+def launch(vm, sha, source):
+ assert re.fullmatch('[a-f0-9]{64}', sha) and re.fullmatch('[a-f0-9]{40}', source)
+ service = '''[Unit]
+Description=Private installer acceptance
+After=systemd-vconsole-setup.service
+[Service]
+ExecStartPre=/usr/bin/chvt 1
+ExecStart=/usr/bin/unshare --mount --propagation private /usr/bin/python3 /var/tmp/harness-install-guest.py screen --source-device /dev/vdc --sha256 SHA --image-source SOURCE
+StandardInput=tty
+StandardOutput=tty
+StandardError=journal
+TTYPath=/dev/tty1
+TTYReset=yes
+TTYVHangup=yes
+Environment=TERM=linux LANG=C.UTF-8
+UMask=0077
+LimitCORE=0
+'''.replace('SHA', sha).replace('SOURCE', source)
+ put(vm, '/etc/systemd/system/harness-install-acceptance.service', service)
+ vm.command('systemctl daemon-reload && systemctl start harness-install-acceptance.service')
+ vm.frame('01-install', ['Disk', 'Encryption', 'Repeat password', 'Install Harness'], seconds=60)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ for name in ('fixture', 'image', 'output'):
+ parser.add_argument('--' + name, type=Path, required=True)
+ for name in ('fixture-source', 'image-source', 'sha256'):
+ parser.add_argument('--' + name, required=True)
+ args = parser.parse_args()
+ if (platform.system(), platform.machine()) != ('Darwin', 'arm64'):
+ parser.error('Use the native Apple Silicon 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 immutable image and source identities.')
+ source = args.image.resolve()
+ if args.image.is_symlink() or not source.is_file() or digest(source) != args.sha256:
+ parser.error('Use the verified regular source image.')
+ info = fixture_identity(args.fixture, args.fixture_source)
+ output = args.output.resolve()
+ output.mkdir(parents=True, exist_ok=False)
+ maintenance, disk = output / 'maintenance.raw', output / 'target.raw'
+ with disk.open('xb') as stream:
+ stream.truncate(24 * 1024**3)
+ subprocess.run(['zstd', '-d', '--sparse', args.fixture / 'guest.raw.zst', '-o', maintenance], check=True, timeout=120)
+ assert digest(maintenance) == info['raw_disk']['sha256']
+ paths = [ROOT / 'platforms/apple-silicon' / n for n in ('install.py', 'startup.py', 'storage.py', 'target.py')]
+ paths += [Path(__file__).with_name(n) for n in ('asahi_install_vm.py', 'asahi_install_guest.py',
+ 'asahi_startup_vm.py', 'asahi_target_vm.py', 'asahi_target_guest.py', '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')]
+ receipt = {'status': 'running', 'started_at': time.time(), 'publication': False,
+ 'image_sha256': args.sha256, 'image_source': args.image_source,
+ 'fixture_source': args.fixture_source, 'fixture_manifest_sha256': digest(args.fixture / 'manifest.json'),
+ 'inputs': {str(p.relative_to(ROOT)): digest(p) for p in paths}, 'shutdowns': [],
+ 'limitations': ['QEMU firmware identity injected, not Apple firmware/m1n1 or physical hardware acceptance.',
+ 'Protected partitions contain sentinel bytes; this does not test actual macOS recovery.',
+ 'Known public fixture password: never release either test disk.',
+ 'Graphical keyboard drives the Linux console; pointer behavior is portable-test coverage only.',
+ 'No installer-media artifact is built by this observer.']}
+ vm = None
+ try:
+ vm = MaintenanceVM(output / 'installer', maintenance, args.fixture / 'Image', disk, source=source)
+ vm.start()
+ vm.command('dnf5 install -y --setopt=install_weak_deps=False --setopt=gpgcheck=True gdisk dosfstools cryptsetup btrfs-progs e2fsprogs rsync', timeout=180)
+ target_guest(vm, 'initialize', output)
+ stage(vm)
+ receipt['before'] = inspect(vm, 'reset-plan')
+ vm.monitor('set_link', name='hnnet', up=False)
+ launch(vm, args.sha256, args.image_source)
+ vm.type_probe('cancel-secret')
+ vm.keys('esc')
+ vm.command('for n in $(seq 1 30); do systemctl is-active --quiet harness-install-acceptance.service || break; sleep .1; done; '
+ 'test "$(systemctl show -p ExecMainStatus --value harness-install-acceptance.service)" = 0')
+ assert inspect(vm) == receipt['before']
+ receipt['cancel_unchanged'] = True
+ launch(vm, '0' * 64, args.image_source)
+ type_line(vm, PASSWORD)
+ type_line(vm, PASSWORD)
+ vm.keys('ret')
+ vm.frame('02-bad-image', 'Installation stopped', seconds=90, absent=[PASSWORD])
+ assert inspect(vm) == receipt['before']
+ vm.keys('esc')
+ vm.command('for n in $(seq 1 30); do systemctl is-active --quiet harness-install-acceptance.service || break; sleep .1; done')
+ receipt['bad_image_unchanged'] = True
+ launch(vm, args.sha256, args.image_source)
+ type_line(vm, 'wrong')
+ type_line(vm, 'mismatch')
+ vm.keys('ret')
+ vm.frame('03-mismatch', 'Passwords do not match')
+ assert inspect(vm) == receipt['before']
+ receipt['mismatch_unchanged'] = True
+ vm.keys('shift', 'tab')
+ vm.keys('ctrl', 'u')
+ vm.type_probe(PASSWORD)
+ vm.keys('shift', 'tab')
+ vm.keys('ctrl', 'u')
+ vm.type_probe(PASSWORD)
+ vm.frame('04-masked', 'Repeat password', absent=[PASSWORD])
+ vm.keys('ret')
+ vm.keys('ret')
+ vm.frame('05-ready', 'Install Harness', absent=[PASSWORD])
+ vm.keys('ret')
+ vm.frame('06-progress', 'Checking installation files', seconds=60)
+ vm.frame('07-complete', ['Harness is installed', 'Shut down'], seconds=400)
+ receipt['after'] = inspect(vm)
+ assert receipt['after']['storage']['phase'] == 'copied'
+ assert receipt['after']['startup']['phase'] == 'complete'
+ assert not receipt['after']['remaining']
+ vm.command('unshare --mount --propagation private python3 /var/tmp/harness-install-guest.py reject-mounted')
+ receipt['mounted_target_refused'] = True
+ log = vm.read_file('/var/log/harness-asahi-install.log')
+ assert PASSWORD.encode() not in log
+ (vm.folder / 'installer.log').write_bytes(log)
+ vm.keys('ret')
+ receipt['shutdowns'].append(vm.poweroff(request=False))
+ vm.close()
+ print('Actual install form passed offline; cancellation, mismatch and invalid image kept the disk unchanged.', flush=True)
+ vm = ImageVM(output / 'installed-boot', disk, None)
+ vm.start()
+ unlock(vm, reject_wrong=True)
+ vm.frame('04-workspace', ['opencode', 'Ask anything'], seconds=150, absent=['Set your password', 'panic'])
+ vm.authenticate()
+ receipt['installed'] = installed(vm)
+ receipt['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')
+ receipt['shutdowns'].append(vm.poweroff())
+ receipt['status'] = 'passed'
+ print('The installation produced by the form unlocks into OpenCode and two terminals.', 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 -u harness-install-acceptance --no-pager; '
+ 'cat /var/log/harness-asahi-install.log', check=False, timeout=20)
+ (vm.folder / 'diagnosis.txt').write_text(logs)
+ except Exception as diagnostic:
+ receipt['diagnostic_error'] = str(diagnostic)
+ raise
+ finally:
+ try:
+ if vm:
+ vm.close()
+ finally:
+ receipt.update(finished_at=time.time(), original_source_unchanged=digest(source) == args.sha256)
+ if not receipt['original_source_unchanged']:
+ receipt.update(status='failed', error='The source image changed.')
+ (output / 'receipt.json').write_text(json.dumps(receipt, indent=2) + '\n')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/os/tests/test_asahi_install.py b/os/tests/test_asahi_install.py
new file mode 100644
index 000000000..68dc4f635
--- /dev/null
+++ b/os/tests/test_asahi_install.py
@@ -0,0 +1,111 @@
+"""Installer orchestration boundaries. Native acceptance drives the actual form."""
+from contextlib import contextmanager
+import curses
+import importlib.util
+from pathlib import Path
+from types import SimpleNamespace
+import unittest
+from unittest.mock import Mock, patch
+
+spec = importlib.util.spec_from_file_location('asahi_install', Path(__file__).resolve().parents[1] /
+ 'platforms/apple-silicon/install.py')
+install = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(install)
+
+
+class Screen:
+ def __init__(self, keys=(), size=(30, 90)):
+ self.keys, self.size, self.lines = iter(keys), size, []
+ def keypad(self, *_): pass
+ def erase(self): self.lines = []
+ def refresh(self): pass
+ def move(self, *_): pass
+ def getmaxyx(self): return self.size
+ def get_wch(self): return next(self.keys)
+ def addnstr(self, row, column, text, size, attr): self.lines.append((row, column, text[:size], attr))
+
+
+class Installer(unittest.TestCase):
+ def page(self, keys=(), size=(30, 90)):
+ with patch.object(curses, 'start_color', side_effect=curses.error):
+ return install.Page(Screen(keys, size))
+
+ def test_cancel_clears_secrets_without_installing(self):
+ view = self.page(['s', 'e', 'c', 'r', 'e', 't', '\x1b'])
+ with patch.object(install, 'install') as commit:
+ self.assertIsNone(view.password('Prepared space'))
+ self.assertEqual(view.values, ['', ''])
+ commit.assert_not_called()
+
+ def test_mismatch_stays_in_form_then_corrected_password_submits(self):
+ view = self.page(['x', '\n', 'y', '\n', '\n', curses.KEY_BTAB, '\x15', 'x', '\n', '\n'])
+ messages = []
+ render = view.render
+ def observe(*args, **kwargs):
+ messages.append(view.error)
+ return render(*args, **kwargs)
+ view.render = observe
+ self.assertEqual(view.password('Prepared space'), 'x')
+ self.assertIn('Passwords do not match.', messages)
+ self.assertEqual(view.values, ['', ''])
+
+ def test_secrets_never_render_and_labels_are_not_highlighted(self):
+ view = self.page()
+ view.values = ['fixture secret', 'fixture secret']
+ view.positions = [14, 14]
+ view.render('Prepared space')
+ self.assertNotIn('fixture secret', str(view.screen.lines))
+ self.assertTrue(any('**************' in line[2] for line in view.screen.lines))
+ self.assertEqual(next(line[3] for line in view.screen.lines if line[2] == 'Password'), 0)
+ focused = [line for line in view.screen.lines if line[0] == view.top + 8 and line[1] == view.left + 18]
+ self.assertEqual(focused[0][3], view.active)
+
+ def test_resize_and_mouse_cannot_submit_a_hidden_form(self):
+ view = self.page([curses.KEY_MOUSE, '\x1b'], size=(10, 25))
+ with patch.object(curses, 'getmouse', return_value=(0, 30, 22, 0, curses.BUTTON1_CLICKED)):
+ self.assertIsNone(view.password('Prepared space'))
+
+ def test_only_a_visible_button_click_submits(self):
+ view = self.page([curses.KEY_MOUSE])
+ view.render('Prepared space')
+ row, x, end, _ = view.hits[-1]
+ with patch.object(curses, 'getmouse', return_value=(0, x + 2, row, 0, curses.BUTTON1_CLICKED)):
+ self.assertEqual(view.key(), '\n')
+ self.assertEqual(view.focus, 2)
+
+ def test_bad_payload_stops_before_any_destination_write(self):
+ @contextmanager
+ def bad():
+ raise install.storage.StorageError('Image checksum changed')
+ yield
+ payload = SimpleNamespace(open=bad)
+ with patch.object(install.storage, 'run') as command, patch.object(install.target, 'save_plan') as save:
+ with self.assertRaisesRegex(ValueError, 'checksum'):
+ install.install(Path('/unused'), {}, payload, 'pw', lambda _: None)
+ command.assert_not_called()
+ save.assert_not_called()
+
+ def test_password_validation_precedes_payload_access(self):
+ for password in ('', 'a\nb', 'a\rb', 'a\0b'):
+ payload = Mock()
+ with self.subTest(password=repr(password)), self.assertRaises(ValueError):
+ install.install(Path('/unused'), {}, payload, password, lambda _: None)
+ payload.open.assert_not_called()
+
+ def test_lost_screen_does_not_interrupt_disk_progress(self):
+ view = self.page()
+ view.render = Mock(side_effect=curses.error)
+ view.progress('Copying Harness…')
+
+ def test_shutdown_failure_does_not_restart_installation(self):
+ view = self.page(['\n', '\n'])
+ with patch.object(curses, 'flushinp'), patch.object(install, 'diagnostic'), \
+ patch.object(install.storage, 'run', side_effect=[OSError('unavailable'), '']) as run, \
+ patch.object(install, 'install') as commit:
+ view.complete()
+ self.assertEqual(run.call_args_list, [unittest.mock.call('systemctl', 'poweroff')] * 2)
+ commit.assert_not_called()
+
+
+if __name__ == '__main__':
+ unittest.main()