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: start the private Asahi image with Harness account setup (#938)

Deef4bce07c5cc6
diff --git a/os/platforms/apple-silicon/01-harness-firstboot.preset b/os/platforms/apple-silicon/01-harness-firstboot.preset
new file mode 100644
index 000000000..fb8c38edf
--- /dev/null
+++ b/os/platforms/apple-silicon/01-harness-firstboot.preset
@@ -0,0 +1,4 @@
+# Harness owns account setup only in its private Asahi image.
+enable harness-firstboot.service
+disable initial-setup.service
+disable initial-setup-reconfiguration.service
diff --git a/os/platforms/apple-silicon/README.md b/os/platforms/apple-silicon/README.md
index 910f81116..43a773cc2 100644
--- a/os/platforms/apple-silicon/README.md
+++ b/os/platforms/apple-silicon/README.md
@@ -5,10 +5,9 @@ KIWI description with a separately verified Harness session RPM. It includes
hn, OpenCode with upstream defaults, terminal panes and the optional Chromium
browser. It selects no GNOME or KDE desktop profile.
-This is image construction work, **not an installable Harness release**. First-boot
-account setup, encryption, Fedora base-system updates/recovery and physical Apple
-hardware acceptance remain required. The image currently retains Fedora's text
-initial setup; it contains no pre-created user or known login password. Never
+This is image construction work, **not an installable Harness release**. Encryption,
+Fedora base-system updates/recovery and physical Apple hardware acceptance remain
+required. 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.
@@ -51,3 +50,23 @@ space prepared by Asahi. The upstream prebuilt-image and UEFI-media paths are
described in the [distribution guidelines](https://asahilinux.org/docs/alt/policy/).
This build is the image foundation for that work; it does not invoke either
installer on the host.
+
+## First boot
+
+The image's first screen asks for **Password** and **Repeat password**, then
+**Start Harness**. It creates `me@harness` through Fedora's account tools and
+enables the existing Harness session through greetd. The new account belongs to
+Fedora's `wheel` group; administrative commands and recovery-console login use
+the chosen password. Root stays locked. No password or password hash is saved in
+the setup receipt, command arguments or temporary files.
+
+Account creation belongs only to this private image, not to installing or updating
+the session RPM on an existing Fedora system. First boot refuses existing accounts,
+homes and conflicting login settings. A private receipt lets interrupted account
+creation or login configuration resume; it does not overwrite another account.
+After setup, the normal OS networking page runs when needed, followed by the
+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.
diff --git a/os/platforms/apple-silicon/configure.py b/os/platforms/apple-silicon/configure.py
index 671e6d931..1f588b5ba 100644
--- a/os/platforms/apple-silicon/configure.py
+++ b/os/platforms/apple-silicon/configure.py
@@ -7,6 +7,7 @@ from pathlib import Path
import platform
import re
import shutil
+import stat
import subprocess
@@ -56,8 +57,23 @@ def main():
raise ValueError('Installed session link differs: ' + name)
Path('/etc/hostname').write_text('harness\n')
Path('/usr/share/harness-os/image.json').write_text(json.dumps(identity, indent=2) + '\n')
- # No known-password fixture users, autologin or broad privilege grants.
- # Fedora's stock initial-setup remains until Harness first boot is integrated.
+ # Only the dedicated image configures first boot; the general session RPM
+ # still has no account-creation or automatic login side effects.
+ first_boot = identity['first_boot']['files']
+ if set(first_boot) != {'usr/lib/harness-os/firstboot.py',
+ 'usr/lib/systemd/system/harness-firstboot.service',
+ 'usr/lib/systemd/system-preset/01-harness-firstboot.preset'}:
+ raise ValueError('Incomplete first-boot payload declaration.')
+ for name, expected in first_boot.items():
+ path = Path('/') / name
+ if (path.is_symlink() or digest(path) != expected['sha256'] or
+ stat.S_IMODE(path.stat().st_mode) != expected['mode']):
+ raise ValueError('First-boot payload differs: ' + name)
+ subprocess.run(['systemctl', 'disable', 'initial-setup.service',
+ 'initial-setup-reconfiguration.service'], check=True)
+ Path('/etc/reconfigSys').unlink(missing_ok=True)
+ subprocess.run(['systemctl', 'enable', 'harness-firstboot.service'], check=True)
+ # No account, known password, or enabled Harness autologin is baked in.
accounts = [row.split(':') for row in Path('/etc/passwd').read_text().splitlines()]
if any(1000 <= int(row[2]) < 65534 for row in accounts):
raise RuntimeError('An image must not contain a pre-provisioned login account.')
diff --git a/os/platforms/apple-silicon/firstboot.py b/os/platforms/apple-silicon/firstboot.py
new file mode 100644
index 000000000..939430d64
--- /dev/null
+++ b/os/platforms/apple-silicon/firstboot.py
@@ -0,0 +1,281 @@
+#!/usr/bin/python3
+"""First local account for a pristine, private Harness Asahi image only.
+
+The session RPM never provisions users. This image-owned step uses Fedora's
+account tools, keeps root locked and hands login to the existing greetd setup.
+Its durable receipt contains identity and progress, never a password or hash.
+"""
+import curses
+import importlib.util
+import json
+import os
+from pathlib import Path
+import platform
+import re
+import shutil
+import stat
+import subprocess
+import uuid
+
+
+def sibling(name):
+ spec = importlib.util.spec_from_file_location('harness_' + name, Path(__file__).with_name(name + '.py'))
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+session = sibling('fedora_session')
+STATE = 'var/lib/harness-os/firstboot.json'
+DONE = 'var/lib/harness-os/firstboot.done'
+WORDMARK = ('█ █ ▄▀█ █▀█ █▄ █ █▀▀ █▀ █▀', '█▀█ █▀█ █▀▄ █ ▀█ ██▄ ▄█ ▄█')
+
+
+class FirstBoot(session.Setup):
+ def image(self):
+ image = json.loads(self.path('usr/share/harness-os/image.json').read_text())
+ release = self.path('etc/os-release').read_text()
+ if (os.geteuid() != 0 or platform.machine() != 'aarch64' or
+ not re.search(r'^ID=[\"\']?fedora-asahi-remix[\"\']?$', release, re.M) or
+ image.get('kind') != 'harness-asahi-image-construction' or
+ image.get('profile') != 'Harness' or image.get('release_ready') is not False or
+ not re.fullmatch(r'[a-f0-9]{40}', str(image.get('source_commit')))):
+ raise session.SetupError('This setup belongs to the private Harness Mac image.')
+ return image['source_commit']
+
+ def read_state(self):
+ entry = self.snapshot(STATE)
+ if entry is None:
+ return None
+ if entry['kind'] != 'file' or entry['mode'] != 0o600:
+ raise session.SetupError('The first-boot receipt is not a private regular file.')
+ state = json.loads(entry['text'])
+ if (set(state) != {'schema', 'source', 'token', 'phase'} or state['schema'] != 1 or
+ state['source'] != self.image() or
+ not re.fullmatch(r'[a-f0-9]{32}', str(state['token'])) or
+ state['phase'] not in {'account', 'password', 'complete'}):
+ raise session.SetupError('The first-boot receipt has changed. Preserve it for recovery.')
+ return state
+
+ def save_state(self, state):
+ self.write(STATE, session.regular(json.dumps(state, indent=2) + '\n', 0o600), replace=True)
+
+ def records(self, name):
+ return [row.split(':') for row in self.path('etc/' + name).read_text().splitlines()]
+
+ def identity(self, state=None):
+ accounts = self.records('passwd')
+ root = next(row for row in self.records('shadow') if row[0] == 'root')
+ if not root[1].startswith(('!', '*')):
+ raise session.SetupError('Keep the existing root authentication policy; setup cannot continue.')
+ user = next((row for row in accounts if row[0] == 'me'), None)
+ groups = self.records('group')
+ group = next((row for row in groups if row[0] == 'me' or row[2] == '1000'), None)
+ if any(1000 <= int(row[2]) < 65534 and row[0] != 'me' for row in accounts):
+ raise session.SetupError('This computer already has an account. Keep its existing setup.')
+ if state is None:
+ if user or group or os.path.lexists(self.root / 'home/me') or self.load():
+ raise session.SetupError('This computer already has account or login settings.')
+ else:
+ expected = ['me', 'x', '1000', '1000', 'Harness setup ' + state['token'], '/home/me', '/bin/bash']
+ if state['phase'] == 'complete' and user and user[4] == 'me':
+ expected[4] = 'me'
+ if user is not None and user != expected:
+ raise session.SetupError('The local account differs from this setup. Keep it unchanged.')
+ if group is not None and group not in (['me', 'x', '1000', ''], ['me', 'x', '1000', 'me']):
+ raise session.SetupError('The local group differs from this setup. Keep it unchanged.')
+ if state['phase'] != 'account' and user is None:
+ raise session.SetupError('The account created by setup is missing.')
+ return user, group
+
+ def prepare(self):
+ source = self.image()
+ state = self.read_state()
+ self.identity(state)
+ if state is None:
+ self.run('/usr/sbin/visudo', '-c')
+ state = {'schema': 1, 'source': source, 'token': uuid.uuid4().hex, 'phase': 'account'}
+ self.save_state(state) # Before creating an account, group or home.
+ return state
+
+ def ensure_home(self, state):
+ home = self.root / 'home/me'
+ # Check /home independently: the final directory is intentionally user-owned.
+ self.path('home/.harness-firstboot-parent-check')
+ if os.path.lexists(home):
+ info = home.lstat()
+ if not stat.S_ISDIR(info.st_mode) or (info.st_uid, info.st_gid, stat.S_IMODE(info.st_mode)) != (1000, 1000, 0o700):
+ raise session.SetupError('The account home differs from this setup. Keep it unchanged.')
+ return
+ staging = self.path('home/.harness-firstboot-' + state['token'])
+ if staging.exists():
+ info = staging.lstat()
+ if not stat.S_ISDIR(info.st_mode) or info.st_uid != 0 or stat.S_IMODE(info.st_mode) != 0o700:
+ raise session.SetupError('The temporary home is not securely owned.')
+ shutil.rmtree(staging) # Only this receipt's inaccessible, unfinished copy.
+ staging.mkdir(mode=0o700)
+ new = staging / 'home'
+ shutil.copytree(self.path('etc/skel'), new, symlinks=True)
+ for path in [*new.rglob('*'), new]:
+ os.chown(path, 1000, 1000, follow_symlinks=False)
+ new.chmod(0o700)
+ self.run('/usr/bin/sync', '-f', str(staging))
+ os.rename(new, home)
+ self.sync_directory(home.parent)
+ staging.rmdir()
+ self.run('/usr/sbin/restorecon', '-RF', str(home))
+
+ @staticmethod
+ def validate_password(password, repeat):
+ if not password:
+ raise ValueError('Enter a password.')
+ if any(char in password for char in '\n\r\0'):
+ raise ValueError('Use a password without line breaks.')
+ if password != repeat:
+ raise ValueError('Passwords do not match.')
+
+ def set_password(self, password):
+ # Neither process arguments, logs, receipts nor temporary files carry it.
+ result = subprocess.run(['/usr/sbin/chpasswd'], input='me:' + password + '\n',
+ text=True, capture_output=True, timeout=20)
+ if result.returncode:
+ raise session.SetupError('Could not set the password. Try another password.')
+
+ def provision(self, state, password):
+ if state['phase'] != 'account':
+ raise session.SetupError('This account already has its password. Continue setup instead.')
+ self.validate_password(password, password)
+ user, group = self.identity(state)
+ if not group:
+ self.run('/usr/sbin/groupadd', '--gid', '1000', 'me')
+ if not user:
+ self.run('/usr/sbin/useradd', '--no-create-home', '--uid', '1000', '--gid', '1000',
+ '--groups', 'wheel', '--home-dir', '/home/me', '--shell', '/bin/bash',
+ '--comment', 'Harness setup ' + state['token'], 'me')
+ self.identity(state)
+ self.ensure_home(state)
+ self.set_password(password)
+ self.run('/usr/bin/sync', '-f', str(self.root / 'etc/shadow'))
+ state['phase'] = 'password'
+ self.save_state(state)
+
+ def finish(self, state):
+ self.identity(state)
+ if state['phase'] == 'account':
+ raise session.SetupError('Set the account password before starting Harness.')
+ previous = self.load()
+ if previous and previous['phase'] != 'enabled':
+ # Restore only a matching, interrupted transaction from our existing
+ # session helper. Its verifier rejects administrator modifications.
+ if previous['user'] != 'me' or previous['uid'] != 1000:
+ raise session.SetupError('Keep the existing login configuration.')
+ self.disable()
+ self.enable('me')
+ state['phase'] = 'complete'
+ self.save_state(state)
+ self.run('/usr/sbin/usermod', '--comment', 'me', 'me')
+ self.write(DONE, session.regular('me@harness\n', 0o600), replace=True)
+
+
+class PasswordPage:
+ def __init__(self, screen):
+ self.screen = screen
+ self.values = ['', '']
+ self.focus = 0
+ self.error = ''
+ self.accent = curses.A_BOLD
+ try:
+ curses.start_color()
+ curses.use_default_colors()
+ curses.init_pair(1, curses.COLOR_YELLOW, -1)
+ self.accent |= curses.color_pair(1)
+ except curses.error:
+ pass
+ screen.keypad(True)
+
+ def render(self, status=None):
+ self.screen.erase()
+ height, width = self.screen.getmaxyx()
+ top, left, span = max(0, (height - 14) // 2), max(0, (width - 52) // 2), min(52, width - 2)
+ def line(row, text, offset=0, active=False, accent=False):
+ y, x = top + row, left + offset
+ if 0 <= y < height and 0 <= x < width - 1:
+ self.screen.addnstr(y, x, text, width - x - 1,
+ curses.A_REVERSE if active else self.accent if accent else curses.A_NORMAL)
+ for row, word in enumerate(WORDMARK):
+ line(row, word.center(span), accent=True)
+ if status:
+ line(5, status.center(span))
+ elif width < 54 or height < 18:
+ line(4, 'Resize to 54 columns and 18 rows.')
+ else:
+ line(4, 'Set your password'.center(span))
+ for index, label in enumerate(('Password', 'Repeat password')):
+ line(7 + index * 2, label)
+ mask = ('*' * len(self.values[index]))[-(span - 21):]
+ line(7 + index * 2, (' ' + mask).ljust(span - 18), 18, active=self.focus == index)
+ line(11, self.error)
+ line(13, '[ Start Harness ]', (span - 17) // 2, active=self.focus == 2)
+ try:
+ curses.curs_set(0)
+ except curses.error:
+ pass
+ self.screen.refresh()
+ return width >= 54 and height >= 18
+
+ def password(self):
+ while True:
+ usable = self.render()
+ key = self.screen.get_wch()
+ 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:
+ FirstBoot.validate_password(*self.values)
+ password = self.values[0]
+ self.values = ['', '']
+ return password
+ except ValueError as error:
+ self.error = str(error)
+ elif self.focus < 2:
+ if key in ('\b', '\x7f', curses.KEY_BACKSPACE):
+ self.values[self.focus] = self.values[self.focus][:-1]
+ elif key == '\x15':
+ self.values[self.focus] = ''
+ elif isinstance(key, str) and key.isprintable() and len(self.values[self.focus]) < 4096:
+ self.values[self.focus] += key
+ self.error = ''
+
+
+def main():
+ setup = FirstBoot()
+ def page(screen):
+ curses.raw()
+ view = PasswordPage(screen)
+ with setup.locked():
+ state = setup.prepare()
+ while state['phase'] == 'account':
+ password = view.password()
+ view.render('Starting Harness…')
+ try:
+ setup.provision(state, password)
+ except session.SetupError as error:
+ view.error = str(error)
+ view.focus = 0
+ finally:
+ password = None
+ view.render('Starting Harness…')
+ setup.finish(state)
+ curses.set_escdelay(25)
+ curses.wrapper(page)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/os/platforms/apple-silicon/harness-firstboot.service b/os/platforms/apple-silicon/harness-firstboot.service
new file mode 100644
index 000000000..69021dcc2
--- /dev/null
+++ b/os/platforms/apple-silicon/harness-firstboot.service
@@ -0,0 +1,29 @@
+[Unit]
+Description=Set up Harness
+After=local-fs.target systemd-vconsole-setup.service systemd-user-sessions.service
+Wants=getty-pre.target
+Before=getty-pre.target display-manager.service
+ConditionPathExists=/usr/share/harness-os/image.json
+ConditionPathExists=!/var/lib/harness-os/firstboot.done
+
+[Service]
+Type=oneshot
+ExecStartPre=/usr/bin/chvt 1
+ExecStart=/usr/bin/python3 -I /usr/lib/harness-os/firstboot.py
+ExecStartPost=/usr/bin/systemctl daemon-reload
+ExecStartPost=/usr/bin/systemctl --no-block start graphical.target
+StandardInput=tty
+StandardOutput=tty
+StandardError=journal
+TTYPath=/dev/tty1
+TTYReset=yes
+TTYVHangup=yes
+TTYVTDisallocate=yes
+Environment=TERM=linux
+TimeoutStartSec=0
+RemainAfterExit=yes
+UMask=0077
+LimitCORE=0
+
+[Install]
+WantedBy=multi-user.target
diff --git a/os/tests/asahi_firstboot_vm.py b/os/tests/asahi_firstboot_vm.py
new file mode 100644
index 000000000..f9114afdc
--- /dev/null
+++ b/os/tests/asahi_firstboot_vm.py
@@ -0,0 +1,245 @@
+#!/usr/bin/env python3
+"""Observe first boot on a disposable copy of the actual private Asahi image.
+
+This native Apple Silicon-host VM checks the image, not physical Apple hardware.
+It never opens a host disk and never modifies the declared source image.
+"""
+import argparse
+import json
+from pathlib import Path
+import platform
+import select
+import shutil
+import subprocess
+import sys
+import threading
+import time
+
+from arm_boot import digest
+from arm_session import SessionVM
+from fedora_session_vm import LOGIN_PROBE
+from session_vm import put
+
+
+PASSWORD = 'firstboot-local-42' # Public fixture credential, never a real user's password.
+
+
+class ImageVM(SessionVM):
+ def start(self):
+ firmware = json.loads(Path('/opt/homebrew/share/qemu/firmware/60-edk2-aarch64.json').read_text())['mapping']
+ variables = self.folder / 'uefi-vars.fd'
+ shutil.copyfile(firmware['nvram-template']['filename'], variables)
+ self.started = time.monotonic()
+ command = ['qemu-system-aarch64', '-machine', 'virt,gic-version=3', '-accel', 'hvf',
+ '-cpu', 'host', '-rtc', 'base=localtime', '-smp', '2', '-m', '3072',
+ '-nodefaults', '-display', 'none', '-no-reboot',
+ '-drive', f'if=pflash,format=raw,readonly=on,file={firmware["executable"]["filename"]}',
+ '-drive', f'if=pflash,format=raw,file={variables}',
+ '-drive', f'file={self.disk},format=raw,if=none,id=root',
+ '-device', 'virtio-blk-pci,drive=root,serial=HARNESS_ASAHI_FIRSTBOOT,logical_block_size=4096,physical_block_size=4096,bootindex=1',
+ '-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(command, indent=2) + '\n')
+ self.process = subprocess.Popen(command, stdout=self.stderr, stderr=self.stderr)
+ self.serial = self.connect('serial.sock')
+ # Firmware and kernel console writes can block QEMU's main loop if the
+ # observer only takes screenshots. Drain boot output while no login
+ # command is using the console, retaining all bytes in serial.log.
+ self.drain_stop = threading.Event()
+ def drain():
+ while not self.drain_stop.is_set():
+ if select.select([self.serial], [], [], .1)[0]:
+ data = self.serial.recv(65536)
+ if not data:
+ return
+ self.log.write(data)
+ self.drain_thread = threading.Thread(target=drain, daemon=True)
+ self.drain_thread.start()
+ 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')
+
+ def stop_drain(self):
+ if hasattr(self, 'drain_stop'):
+ self.drain_stop.set()
+ self.drain_thread.join(timeout=2)
+ if self.drain_thread.is_alive():
+ raise RuntimeError('The boot console observer did not stop.')
+
+ def close(self):
+ self.stop_drain()
+ super().close()
+
+ def authenticate(self):
+ self.stop_drain()
+ self.send('\n') # Ask the existing getty to repeat its consumed prompt.
+ self.wait('login:', timeout=120)
+ self.send('me\n')
+ self.wait('Password:', timeout=30)
+ self.send(PASSWORD + '\n')
+ self.wait(r'\[me@[^\r\n]*\]\$ ', timeout=30)
+ self.send('sudo /bin/bash --noprofile --norc -i\n')
+ self.wait('password for me:', timeout=30)
+ self.send(PASSWORD + '\n')
+ self.wait(r'bash-[^\r\n]*# ', timeout=30)
+ self.send("stty -echo; export PS1='HARNESS_ARM_CONSOLE> '\n")
+ self.wait('HARNESS_ARM_CONSOLE> ', timeout=30)
+ self.shell_ready = True
+
+
+def type_line(vm, value):
+ vm.type_probe(value)
+ vm.keys('ret')
+
+
+def setup_screen(vm):
+ vm.frame('01-password', 'Set your password', seconds=120)
+ type_line(vm, 'wrong')
+ type_line(vm, 'mismatch')
+ vm.keys('ret')
+ vm.frame('02-mismatch', 'Passwords do not match')
+ 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('03-masked', 'Repeat password', absent=[PASSWORD])
+ vm.keys('ret')
+ vm.keys('ret')
+ vm.keys('ret')
+ vm.frame('04-workspace', ['opencode', 'Ask anything'], seconds=150,
+ absent=['Bun has crashed', 'panic'])
+
+
+def evidence(vm, folder):
+ vm.command('test "$(getconf PAGESIZE)" = 16384 && test "$(getenforce)" = Enforcing && rpm -V harness-os-session')
+ put(vm, '/tmp/harness-firstboot-login-probe.py', LOGIN_PROBE)
+ vm.command('python3 /tmp/harness-firstboot-login-probe.py')
+ (folder / 'login.json').write_bytes(vm.read_file('/tmp/harness-login-probe.json'))
+ script = '''import hashlib,json,pathlib,subprocess
+root=pathlib.Path('/')
+state=json.loads((root/'var/lib/harness-os/firstboot.json').read_text())
+assert state['phase']=='complete'
+image=json.loads((root/'usr/share/harness-os/image.json').read_text())
+assert state['source']==image['source_commit']
+for name,entry in image['first_boot']['files'].items():
+ assert hashlib.sha256((root/name).read_bytes()).hexdigest()==entry['sha256']
+passwd=[r.split(':') for r in (root/'etc/passwd').read_text().splitlines()]
+assert [r for r in passwd if 1000<=int(r[2])<65534]==[['me','x','1000','1000','me','/home/me','/bin/bash']]
+shadow=[r.split(':') for r in (root/'etc/shadow').read_text().splitlines()]
+assert next(r for r in shadow if r[0]=='root')[1].startswith(('!','*'))
+assert next(r for r in shadow if r[0]=='me')[1].startswith('$')
+assert 'wheel' in subprocess.check_output(['id','-Gn','me'],text=True).split()
+record={}
+for name in ['etc/passwd','etc/shadow','etc/group','etc/gshadow','etc/pam.d/greetd',
+ 'etc/sudoers','etc/selinux/config','var/lib/harness-os/firstboot.json',
+ 'var/lib/harness-os/firstboot.done','var/lib/harness-os/session-setup.json']:
+ p=root/name;s=p.stat()
+ record[name]={'sha256':hashlib.sha256(p.read_bytes()).hexdigest(),'mode':s.st_mode&0o7777,'uid':s.st_uid}
+for name in ['var/lib/harness-os/firstboot.json','var/lib/harness-os/firstboot.done']:
+ assert record[name]['mode']==0o600 and record[name]['uid']==0
+pathlib.Path('/tmp/harness-firstboot-evidence.json').write_text(json.dumps(record,indent=2)+'\\n')
+'''
+ put(vm, '/tmp/harness-firstboot-evidence.py', script)
+ vm.command('python3 /tmp/harness-firstboot-evidence.py')
+ raw = vm.read_file('/tmp/harness-firstboot-evidence.json')
+ (folder / 'account.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('--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.')
+ 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.')
+ output = args.output.resolve()
+ output.mkdir(parents=True, exist_ok=False)
+ disk = output / 'guest.raw'
+ subprocess.run(['cp', '-c', source, disk], check=True, timeout=60)
+ receipt = {'status': 'running', 'started_at': time.time(), 'image_sha256': args.sha256,
+ 'scope': 'Produced image, native ARM 16 KiB UEFI VM; no physical Apple hardware claim',
+ 'checks': [], 'publication': False,
+ 'observer_files': {name: digest(Path(__file__).with_name(name)) for name in
+ ('asahi_firstboot_vm.py', 'arm_boot.py', 'arm_session.py', 'fedora_session_vm.py',
+ 'session_vm.py', 'vm.py')}}
+ vm = None
+ try:
+ vm = ImageVM(output / 'boot-01-interrupted', disk, None)
+ vm.start()
+ vm.frame('01-password', 'Set your password', seconds=120)
+ # Deliberately cut power while setup is pending, on this copy only.
+ vm.close()
+ vm = ImageVM(output / 'boot-02-resumed', disk, None)
+ vm.start()
+ setup_screen(vm)
+ vm.authenticate()
+ first = evidence(vm, vm.folder)
+ vm.wait_user('pgrep -u 1000 -x opencode >/dev/null')
+ vm.wait_user('test "$(hn list-panes -F "#{pane_id}" | wc -l)" -eq 3')
+ receipt['checks'].extend(['Password screen survives interrupted first boot',
+ 'Mismatch stays in masked form; valid password reaches actual three-pane workspace',
+ 'New me account, locked root, wheel, native greetd/PAM session and enforcing SELinux'])
+ print('First boot reached the actual Harness workspace', flush=True)
+ vm.keys('ctrl', 'alt', 'f2')
+ vm.frame('05-recovery-login', 'login:')
+ type_line(vm, 'me')
+ vm.frame('06-recovery-password', 'password:')
+ type_line(vm, 'incorrect-password')
+ vm.frame('07-recovery-rejected', 'incorrect', seconds=30)
+ vm.frame('08-recovery-retry', 'login:')
+ type_line(vm, 'me')
+ vm.frame('09-recovery-password', 'password:')
+ type_line(vm, PASSWORD)
+ vm.frame('10-recovery-shell', 'me@harness')
+ vm.command('mkdir -p /var/lib/harness-test')
+ type_line(vm, 'sudo -k')
+ type_line(vm, 'sudo touch /var/lib/harness-test/firstboot-sudo')
+ vm.frame('11-sudo-password', 'password for me')
+ type_line(vm, PASSWORD)
+ vm.command('for n in $(seq 1 30); do test -f /var/lib/harness-test/firstboot-sudo && exit 0; sleep .2; done; exit 1')
+ receipt['checks'].append('Recovery console rejects wrong password, accepts chosen password; sudo authenticates')
+ receipt['shutdown_first'] = vm.poweroff()
+ vm.close()
+ vm = ImageVM(output / 'boot-03-normal', disk, None)
+ vm.start()
+ vm.authenticate()
+ vm.wait_user('systemctl --user is-active --quiet hn-screen')
+ second = evidence(vm, vm.folder)
+ assert first == second, 'Account, authentication or setup state changed on the second configured boot'
+ vm.command('test "$(systemctl show harness-firstboot.service -p ConditionResult --value)" = no')
+ vm.screenshot('01-normal-workspace')
+ receipt['checks'].append('Later boot skips account setup and preserves account/authentication/setup bytes')
+ receipt['shutdown_second'] = vm.poweroff()
+ receipt['status'] = 'passed'
+ 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-firstboot -u greetd --no-pager; ausearch -m AVC -ts boot', check=False)
+ (vm.folder / 'diagnosis.txt').write_text(logs)
+ except Exception as diagnostic:
+ receipt['diagnostic_error'] = str(diagnostic)
+ raise
+ finally:
+ if vm:
+ vm.close()
+ receipt['finished_at'] = time.time()
+ receipt['source_unchanged'] = digest(source) == args.sha256
+ (output / 'receipt.json').write_text(json.dumps(receipt, indent=2) + '\n')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/os/tests/asahi_image_check.py b/os/tests/asahi_image_check.py
index cadf37dfc..4cac5689c 100644
--- a/os/tests/asahi_image_check.py
+++ b/os/tests/asahi_image_check.py
@@ -54,7 +54,7 @@ def partition_layout(table, image_bytes):
return partitions
-def inspect_root(root, boot, esp, identity):
+def inspect_root(root, boot, esp, identity, owner_uid=0):
manifest = identity['session_package']
if json.loads((root / 'usr/share/harness-os/image.json').read_text()) != identity:
raise ValueError('The image lost its exact build/package provenance.')
@@ -65,6 +65,26 @@ def inspect_root(root, boot, esp, identity):
for relative, expected in manifest['symlinks'].items():
if os.readlink(root / relative) != expected:
raise ValueError('Actual image link differs: ' + relative)
+ first_boot = identity['first_boot']['files']
+ if set(first_boot) != {'usr/lib/harness-os/firstboot.py',
+ 'usr/lib/systemd/system/harness-firstboot.service',
+ 'usr/lib/systemd/system-preset/01-harness-firstboot.preset'}:
+ raise ValueError('Incomplete first-boot payload declaration.')
+ for relative, expected in first_boot.items():
+ path = root / relative
+ if (path.is_symlink() or not path.is_file() or digest(path) != expected['sha256'] or
+ stat.S_IMODE(path.stat().st_mode) != expected['mode'] or path.stat().st_uid != owner_uid):
+ raise ValueError('Actual first-boot payload differs: ' + relative)
+ enabled = root / 'etc/systemd/system/multi-user.target.wants/harness-firstboot.service'
+ if not enabled.is_symlink() or os.readlink(enabled) != '/usr/lib/systemd/system/harness-firstboot.service':
+ raise ValueError('Harness first boot is not enabled.')
+ for target in ('graphical.target', 'multi-user.target'):
+ if os.path.lexists(root / ('etc/systemd/system/' + target + '.wants/initial-setup.service')):
+ raise ValueError('The competing account wizard is still enabled.')
+ for name in ('var/lib/harness-os/firstboot.json', 'var/lib/harness-os/firstboot.done',
+ 'var/lib/harness-os/session-setup.json', 'etc/reconfigSys'):
+ if os.path.lexists(root / name):
+ raise ValueError('The image has already entered account setup: ' + name)
if (root / 'var/tmp/harness-image-input').exists():
raise ValueError('Image still contains temporary builder inputs.')
accounts = [row.split(':') for row in (root / 'etc/passwd').read_text().splitlines()]
diff --git a/os/tests/test_asahi_firstboot.py b/os/tests/test_asahi_firstboot.py
new file mode 100644
index 000000000..a83ff6934
--- /dev/null
+++ b/os/tests/test_asahi_firstboot.py
@@ -0,0 +1,188 @@
+"""First-account transaction checks. Native account/PAM behavior needs the VM."""
+import importlib.util
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import tempfile
+import unittest
+from unittest.mock import patch
+
+
+ROOT = Path(__file__).resolve().parents[1]
+_modules = tempfile.TemporaryDirectory()
+for source in (ROOT / 'fedora_session.py', ROOT / 'platforms/apple-silicon/firstboot.py'):
+ shutil.copyfile(source, Path(_modules.name) / source.name)
+spec = importlib.util.spec_from_file_location('asahi_firstboot', Path(_modules.name) / 'firstboot.py')
+first = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(first)
+session = first.session
+
+
+class Fixture(first.FirstBoot):
+ def __init__(self, root):
+ super().__init__(root)
+ self.commands = []
+ self.failure = None
+
+ def image(self):
+ return 'a' * 40
+
+ def run(self, *command, check=True):
+ self.commands.append(command)
+ if self.failure == Path(command[0]).name:
+ raise session.SetupError('Injected command failure')
+ if command[0].endswith('groupadd'):
+ with self.path('etc/group').open('a') as stream:
+ stream.write('me:x:1000:\n')
+ if command[0].endswith('useradd'):
+ token = command[command.index('--comment') + 1]
+ with self.path('etc/passwd').open('a') as stream:
+ stream.write(f'me:x:1000:1000:{token}:/home/me:/bin/bash\n')
+ if command[0].endswith('usermod'):
+ rows = self.records('passwd')
+ for row in rows:
+ if row[0] == 'me':
+ row[4] = 'me'
+ self.path('etc/passwd').write_text('\n'.join(':'.join(row) for row in rows) + '\n')
+ return ''
+
+ def ensure_home(self, state):
+ (self.root / 'home/me').mkdir(parents=True, exist_ok=True)
+
+ def set_password(self, password):
+ if self.failure == 'password':
+ raise session.SetupError('Injected password failure')
+
+
+class FirstAccount(unittest.TestCase):
+ def setUp(self):
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = Path(temporary.name)
+ self.setup = Fixture(self.root)
+ self.put('etc/passwd', 'root:x:0:0:root:/root:/bin/bash\nnobody:x:65534:65534:Nobody:/:/sbin/nologin\n')
+ self.put('etc/group', 'root:x:0:\nwheel:x:10:\n')
+ self.put('etc/shadow', 'root:!:20732:0:99999:7:::\n')
+ self.put('etc/os-release', 'ID=fedora-asahi-remix\nVERSION_ID=44\n')
+ self.put('usr/share/harness-os/image.json', json.dumps({
+ 'kind': 'harness-asahi-image-construction', 'profile': 'Harness',
+ 'release_ready': False, 'source_commit': 'a' * 40}))
+ (self.root / 'run').mkdir()
+
+ def put(self, name, text):
+ path = self.root / name
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text)
+ return path
+
+ def test_refuse_existing_account_group_home_or_unlocked_root_without_a_write(self):
+ mutations = [
+ ('etc/passwd', 'owner:x:1000:1000:Owner:/home/owner:/bin/bash\n'),
+ ('etc/passwd', 'me:x:1000:1000:Me:/home/me:/bin/bash\n'),
+ ('etc/group', 'me:x:1000:\n'),
+ ('home/me/project', 'keep this work\n'),
+ ('etc/shadow', 'root:$6$existing-hash:20732:0:99999:7:::\n'),
+ ]
+ for name, text in mutations:
+ with self.subTest(name=name, text=text):
+ path = self.root / name
+ before = path.read_text() if path.exists() else None
+ self.put(name, text)
+ with self.assertRaises(session.SetupError):
+ self.setup.prepare()
+ self.assertEqual(path.read_text(), text)
+ self.assertFalse((self.root / first.STATE).exists())
+ if before is not None:
+ path.write_text(before)
+ else:
+ shutil.rmtree(self.root / 'home')
+
+ def test_receipt_is_durable_before_user_creation_and_never_contains_password(self):
+ state = self.setup.prepare()
+ receipt = self.root / first.STATE
+ self.assertEqual(receipt.stat().st_mode & 0o777, 0o600)
+ self.assertEqual(self.setup.commands, [('/usr/sbin/visudo', '-c')])
+ self.setup.provision(state, 'private-fixture-password')
+ with patch.object(self.setup, 'enable') as enable:
+ self.setup.finish(state)
+ enable.assert_called_once_with('me')
+ self.assertEqual(self.setup.read_state()['phase'], 'complete')
+ self.assertEqual(self.setup.prepare()['phase'], 'complete')
+ for path in (receipt, self.root / first.DONE):
+ self.assertNotIn('private-fixture-password', path.read_text())
+ self.assertEqual(path.stat().st_mode & 0o777, 0o600)
+ self.assertNotIn('private-fixture-password', repr(self.setup.commands))
+ self.assertIn('me:x:1000:1000:me:/home/me:/bin/bash', (self.root / 'etc/passwd').read_text())
+
+ def test_resume_after_group_creation_user_creation_or_password_rejection(self):
+ for failure in ('useradd', 'password'):
+ with self.subTest(failure=failure):
+ self.setUp()
+ state = self.setup.prepare()
+ self.setup.failure = failure
+ with self.assertRaises(session.SetupError):
+ self.setup.provision(state, 'fixture-password')
+ self.setup.failure = None
+ resumed = self.setup.prepare()
+ self.assertEqual(resumed, state)
+ self.setup.provision(resumed, 'retry-password')
+ self.assertEqual(self.setup.read_state()['phase'], 'password')
+ users = [row for row in self.setup.records('passwd') if row[0] == 'me']
+ self.assertEqual(len(users), 1)
+ groups = [row for row in self.setup.records('group') if row[0] == 'me']
+ self.assertEqual(len(groups), 1)
+
+ def test_completed_password_is_not_reset_after_restart(self):
+ state = self.setup.prepare()
+ self.setup.provision(state, 'fixture-password')
+ with patch.object(self.setup, 'set_password') as password:
+ with self.assertRaisesRegex(session.SetupError, 'already has'):
+ self.setup.provision(self.setup.prepare(), 'replacement')
+ password.assert_not_called()
+
+ def test_refuse_changed_account_or_receipt_on_resume(self):
+ state = self.setup.prepare()
+ self.setup.provision(state, 'fixture-password')
+ passwd = self.root / 'etc/passwd'
+ passwd.write_text(passwd.read_text().replace('Harness setup ' + state['token'], 'Different owner'))
+ with self.assertRaisesRegex(session.SetupError, 'differs'):
+ self.setup.prepare()
+ receipt = self.root / first.STATE
+ data = json.loads(receipt.read_text())
+ data['source'] = 'b' * 40
+ receipt.write_text(json.dumps(data))
+ with self.assertRaisesRegex(session.SetupError, 'receipt has changed'):
+ self.setup.prepare()
+
+ def test_password_is_stdin_only_and_rejection_does_not_repeat_secret(self):
+ password = 'unique-fixture-secret'
+ with patch.object(first.subprocess, 'run', return_value=subprocess.CompletedProcess(
+ [], 1, '', password)) as run:
+ with self.assertRaises(session.SetupError) as error:
+ first.FirstBoot.set_password(self.setup, password)
+ self.assertNotIn(password, str(error.exception))
+ args, kwargs = run.call_args
+ self.assertNotIn(password, repr(args))
+ self.assertEqual(kwargs['input'], 'me:' + password + '\n')
+
+ def test_empty_mismatch_and_linebreak_passwords_are_rejected(self):
+ for password, repeat in [('', ''), ('one', 'two'), ('one\ntwo', 'one\ntwo')]:
+ with self.subTest(password=password), self.assertRaises(ValueError):
+ self.setup.validate_password(password, repeat)
+ self.setup.validate_password('a', 'a')
+
+ def test_native_image_guard_does_not_accept_other_distributions(self):
+ # Exercise the actual guard, while path ownership remains that of the test runner.
+ with patch.object(first.platform, 'machine', return_value='aarch64'), \
+ patch.object(first.os, 'geteuid', return_value=0), \
+ patch.object(self.setup, 'path', side_effect=lambda name: self.root / name):
+ self.assertEqual(first.FirstBoot.image(self.setup), 'a' * 40)
+ self.put('etc/os-release', 'ID=fedora\nVERSION_ID=44\n')
+ with self.assertRaisesRegex(session.SetupError, 'private Harness Mac image'):
+ first.FirstBoot.image(self.setup)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/os/tests/test_asahi_image.py b/os/tests/test_asahi_image.py
index 8e5ae6bc7..d7174fc19 100644
--- a/os/tests/test_asahi_image.py
+++ b/os/tests/test_asahi_image.py
@@ -170,7 +170,14 @@ class ActualDiskContract(unittest.TestCase):
self.root, self.boot, self.esp = (self.folder / name for name in ('root', 'boot', 'esp'))
for folder in (self.root, self.boot, self.esp):
folder.mkdir()
- self.identity = {'session_package': {'files': {}, 'symlinks': {}}}
+ self.identity = {'session_package': {'files': {}, 'symlinks': {}}, 'first_boot': {'files': {}}}
+ for name, (local, mode) in image.FIRST_BOOT_FILES.items():
+ path = self.put(self.root, name, (ROOT / 'os/platforms/apple-silicon' / local).read_text())
+ path.chmod(mode)
+ self.identity['first_boot']['files'][name] = {'sha256': image.digest(path), 'mode': mode}
+ enabled = self.root / 'etc/systemd/system/multi-user.target.wants/harness-firstboot.service'
+ enabled.parent.mkdir(parents=True)
+ enabled.symlink_to('/usr/lib/systemd/system/harness-firstboot.service')
files = {
'usr/share/harness-os/image.json': json.dumps(self.identity),
'etc/passwd': 'root:x:0:0:root:/root:/bin/bash\nnobody:x:65534:65534:Nobody:/:/sbin/nologin\n',
@@ -191,13 +198,28 @@ class ActualDiskContract(unittest.TestCase):
return path
def inspect(self):
- return check.inspect_root(self.root, self.boot, self.esp, self.identity)
+ return check.inspect_root(self.root, self.boot, self.esp, self.identity, owner_uid=os.geteuid())
def test_actual_root_boot_provenance_and_pristine_identity(self):
evidence = self.inspect()
self.assertIn('esp/m1n1/boot.bin', evidence)
self.assertEqual(evidence['boot/vmlinuz-test']['bytes'], 4096)
+ def test_reject_firstboot_tampering_or_already_provisioned_image(self):
+ path = self.root / 'usr/lib/harness-os/firstboot.py'
+ original = path.read_bytes()
+ path.write_text('changed')
+ with self.assertRaisesRegex(ValueError, 'first-boot payload'):
+ self.inspect()
+ path.write_bytes(original)
+ done = self.put(self.root, 'var/lib/harness-os/firstboot.done', 'me@harness\n')
+ with self.assertRaisesRegex(ValueError, 'already entered'):
+ self.inspect()
+ done.unlink()
+ self.put(self.root, 'etc/systemd/system/multi-user.target.wants/initial-setup.service', 'conflict')
+ with self.assertRaisesRegex(ValueError, 'competing'):
+ self.inspect()
+
def test_reject_known_password_fixture_or_fixed_machine_secrets(self):
mutations = [
('etc/passwd', 'me:x:1000:1000::/home/me:/bin/bash\n', 'pre-provisioned'),
diff --git a/os/tools/asahi_image.py b/os/tools/asahi_image.py
index fb201f6a8..0cb8c0bd0 100644
--- a/os/tools/asahi_image.py
+++ b/os/tools/asahi_image.py
@@ -2,8 +2,8 @@
"""Prepare a private Asahi disk-image recipe from declared upstream/RPM inputs.
This does not partition a computer, publish an installer, or build shared clients.
-Fedora/Asahi owns boot, firmware, kernel, filesystems and initial setup. The next
-integration steps are Harness first boot, encryption and base update/recovery.
+Fedora/Asahi owns boot, firmware, kernel and filesystems. Harness owns the first
+account screen. Encryption and base update/recovery remain separate work.
"""
import argparse
import hashlib
@@ -23,6 +23,11 @@ PLATFORM_PACKAGES = (
'greetd', 'chromium', 'mesa-dri-drivers', 'mesa-vulkan-drivers',
'asahi-audio', 'speakersafetyd',
)
+FIRST_BOOT_FILES = {
+ 'usr/lib/harness-os/firstboot.py': ('firstboot.py', 0o755),
+ 'usr/lib/systemd/system/harness-firstboot.service': ('harness-firstboot.service', 0o644),
+ 'usr/lib/systemd/system-preset/01-harness-firstboot.preset': ('01-harness-firstboot.preset', 0o644),
+}
def digest(path):
@@ -121,7 +126,10 @@ def prepare(upstream, package, package_source, output, source=ROOT):
'source_commit': source_commit, 'base': lock, 'architecture': 'aarch64',
'profile': 'Harness', 'session_package': metadata,
'release_ready': False,
- 'pending': ['Harness first-boot account setup', 'Disk encryption',
+ 'first_boot': {'files': {name: {'sha256': digest(source / 'os/platforms/apple-silicon' / local),
+ 'mode': mode}
+ for name, (local, mode) in FIRST_BOOT_FILES.items()}},
+ 'pending': ['Disk encryption',
'Fedora base updates and recovery', 'Physical Apple hardware acceptance'],
}
output.mkdir(parents=True, exist_ok=False)
@@ -144,6 +152,11 @@ def prepare(upstream, package, package_source, output, source=ROOT):
else:
shutil.copy2(origin, target)
extend_recipe(description, dependencies, identity)
+ for name, (local, mode) in FIRST_BOOT_FILES.items():
+ target = description / 'root' / name
+ target.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(source / 'os/platforms/apple-silicon' / local, target)
+ target.chmod(mode)
inputs = description / 'root/var/tmp/harness-image-input'
shutil.copyfile(artifact, inputs / artifact.name)
shutil.copyfile(source / 'os/platforms/apple-silicon/configure.py', inputs / 'configure.py')