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.

Fix native ARM updates, Wi-Fi reconnects, and Broadcom driver ownership (#771)

Dee29f44543601e
diff --git a/.github/workflows/os-runtime-updates.yml b/.github/workflows/os-runtime-updates.yml
new file mode 100644
index 000000000..b6e21e544
--- /dev/null
+++ b/.github/workflows/os-runtime-updates.yml
@@ -0,0 +1,72 @@
+name: Harness OS private runtime update fixtures
+
+on:
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: harness-runtime-updates-${{ github.ref }}
+ cancel-in-progress: false
+
+jobs:
+ prepare:
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - { architecture: x86_64, runner: ubuntu-24.04 }
+ - { architecture: aarch64, runner: ubuntu-24.04-arm }
+ runs-on: ${{ matrix.runner }}
+ timeout-minutes: 25
+ steps:
+ - uses: actions/checkout@v7
+ with:
+ fetch-depth: 0
+ - uses: actions/setup-node@v7
+ with:
+ node-version: 22.23.2
+ cache: npm
+ cache-dependency-path: cli/package-lock.json
+ - uses: dtolnay/rust-toolchain@stable
+ with:
+ targets: ${{ matrix.architecture }}-unknown-linux-musl
+ - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
+ with:
+ workspaces: tui
+ shared-key: tui-${{ matrix.architecture }}-unknown-linux-musl
+ cache-bin: false
+ - name: Native build tools and portable OS checks
+ run: |
+ df -h . "$RUNNER_TEMP"
+ sudo apt-get update -qq
+ sudo apt-get install -y --no-install-recommends musl-tools
+ mkdir -p os/test-results/runtime-updates
+ timeout 180 make -C os check \
+ 2>&1 | tee os/test-results/runtime-updates/portable-checks.log
+ - name: Build the exact native baseline runtime
+ run: bash os/tools/build-runtime.sh
+ - name: Compile and verify the private update fixture
+ run: python3 os/tests/build-update-fixture.py
+ # Preparation proves the binaries and manifests, not VM activation or
+ # surviving agent work. These fixtures never enter a product channel.
+ - name: Retain baseline and private update binaries
+ if: success()
+ uses: actions/upload-artifact@v6
+ with:
+ name: harness-runtime-update-fixture-${{ matrix.architecture }}
+ path: |
+ os/work/runtime/
+ os/work/fast-update-fixture/
+ if-no-files-found: error
+ retention-days: 7
+ compression-level: 0
+ - name: Retain scoped preparation evidence
+ if: always()
+ uses: actions/upload-artifact@v6
+ with:
+ name: harness-runtime-update-evidence-${{ matrix.architecture }}
+ path: os/test-results/runtime-updates/
+ if-no-files-found: error
+ retention-days: 14
diff --git a/.github/workflows/os.yml b/.github/workflows/os.yml
index d67bff7c3..f0cc7a9ca 100644
--- a/.github/workflows/os.yml
+++ b/.github/workflows/os.yml
@@ -255,13 +255,21 @@ jobs:
github-token: ${{ github.token }}
- name: Check the fixture and install VM tools
run: |
+ python3 -m unittest discover -s os/tests -p 'test_hardware*.py'
python3 -m py_compile os/tests/hardware_install_guest.py os/tests/hardware_install_vm.py
go run github.com/rhysd/actionlint/cmd/[email protected] .github/workflows/os.yml
sudo apt-get update -qq
sudo apt-get install -y --no-install-recommends qemu-system-x86 qemu-utils ovmf python3-pil tesseract-ocr
sudo chmod a+rw /dev/kvm
- name: Install the selected driver offline and reboot with 1 GiB
- run: python3 os/tests/hardware_install_vm.py --iso os/dist/*.iso
+ env:
+ REUSED_IMAGE: ${{ inputs.image_run_id }}
+ run: |
+ args=(--iso os/dist/*.iso)
+ if [[ -n "$REUSED_IMAGE" ]]; then
+ args+=(--candidate-hardware os/hardware.py)
+ fi
+ python3 os/tests/hardware_install_vm.py "${args[@]}"
- name: Retain hardware installation and rebuild evidence
if: always()
uses: actions/upload-artifact@v6
@@ -330,7 +338,7 @@ jobs:
sudo apt-get install -y qemu-system-x86 qemu-utils ovmf python3-pil tesseract-ocr
if test -e /dev/kvm; then sudo chmod a+rw /dev/kvm; fi
- name: Exercise Wi-Fi and audio in the real image
- run: python3 os/tests/essentials_vm.py --iso os/dist/*.iso
+ run: python3 os/tests/essentials_vm.py --iso os/dist/*.iso --network-script os/network.py
- name: Retain hardware plumbing evidence
if: always()
uses: actions/upload-artifact@v6
diff --git a/os/DEVELOPMENT.md b/os/DEVELOPMENT.md
index 82b64e9e7..82383ae1d 100644
--- a/os/DEVELOPMENT.md
+++ b/os/DEVELOPMENT.md
@@ -595,6 +595,36 @@ tests that older image, not product changes in the newer test checkout.
Apple firmware provisioning, physical drivers, platform installation and Fedora
update/recovery integration remain separate work before releasing this port.
+### Native runtime updates in the ARM fixture
+
+The **Harness OS private runtime update fixtures** workflow builds native x86 and
+ARM baseline runtimes plus unpublished `999.0.1` updates. It runs portable OS checks
+on both architectures, preserves the original runtime, and uploads exact-source
+artifacts. These manifests never enter a product update channel.
+
+Use the ARM artifact with an existing verified graphical fixture:
+
+```sh
+python3 os/tests/arm_update_vm.py \
+ --fixture /path/to/harness-arm-session-fixture \
+ --fixture-source FULL_IMAGE_PRODUCER_SHA \
+ --updates /path/to/fast-update-fixture \
+ --updates-source FULL_UPDATE_PRODUCER_SHA \
+ --output os/test-results/arm-updates
+```
+
+The driver verifies both immutable inputs, then adds only the candidate user
+updater and its shortcut/timer to a private writable copy. It exercises staged
+downloads, a failed screen restart, mouse activation, Super+u, and rollback with
+actual native binaries. The same agent and terminal processes, heartbeat, boot ID,
+and keyboard input must survive. Its ancestor-release check requires that the
+fixture's recorded public CLI baseline is already included in the boot image.
+
+Receipts distinguish the boot image, update producer, and test/updater source.
+This tests per-user runtime changes, not Fedora package updates, boot recovery,
+physical Apple hardware, or an ARM product installation. The passwordless test
+account and writable test disk must never be published.
+
## Mac support targets
Intel Macs and Apple Silicon are both intended OS targets. They share the Harness
diff --git a/os/hardware.py b/os/hardware.py
index 9e47457b2..5efbb6915 100644
--- a/os/hardware.py
+++ b/os/hardware.py
@@ -53,14 +53,25 @@ def pci_devices(sysfs=Path('/sys')):
if (interface / 'device').is_symlink() and (interface / 'device').resolve().is_relative_to(path.resolve()):
interfaces.append({'name': interface.name, 'wireless': (interface / 'wireless').is_dir() or (interface / 'phy80211').exists()})
driver = (path / 'driver').resolve().name if (path / 'driver').is_symlink() else None
+ override = read(path / 'driver_override')
devices.append({'address': path.name, 'id': vendor + ':' + device,
- 'class': kind, 'driver': driver, 'interfaces': interfaces})
+ 'class': kind, 'driver': driver,
+ 'driver_override': None if override in {'', '(null)'} else override,
+ 'interfaces': interfaces})
return devices
def needs_broadcom(device):
- return device['id'] in BROADCOM_IDS and device['class'] == '028000' and (
- device['driver'] == 'wl' or not any(i['wireless'] for i in device['interfaces']))
+ if device['id'] not in BROADCOM_IDS or device['class'] != '028000':
+ return False
+ # A missing wireless interface does not mean the radio is available: it
+ # may be assigned to a VM or explicitly disabled with driver_override.
+ # Apply the same ownership policy to live activation and offline packages.
+ if device.get('driver_override') not in {None, '', 'wl'}:
+ return False
+ if device['driver'] not in {None, 'wl', 'bcma-pci-bridge', 'ssb'}:
+ return False
+ return device['driver'] == 'wl' or not any(i['wireless'] for i in device['interfaces'])
def report(sysfs=Path('/sys'), proc=Path('/proc')):
@@ -199,8 +210,6 @@ def activate(address, sysfs=Path('/sys'), bundle=BUNDLE):
device = next((d for d in devices if d['address'] == address), None)
if not device or not needs_broadcom(device) or device['driver'] == 'wl':
return {'status': 'unchanged', 'address': address}
- if device['driver'] not in {None, 'bcma-pci-bridge', 'ssb'}:
- return {'status': 'unchanged', 'address': address, 'reason': 'Keep an existing driver.'}
# Verify availability before changing a binding. The live image carries only
# a prebuilt module here; installed machines use the ordinary DKMS package.
if (bundle / 'manifest.json').is_file():
diff --git a/os/live_update.py b/os/live_update.py
index 8141a2cbd..0d4e3cd29 100644
--- a/os/live_update.py
+++ b/os/live_update.py
@@ -15,6 +15,7 @@ import importlib.util
import json
import os
from pathlib import Path
+import platform
import re
import shutil
import subprocess
@@ -143,6 +144,27 @@ def fetch(url, limit):
return data
+def runtime_platform():
+ """Match the public hn release keys to the native Linux executable format."""
+ machine = platform.machine()
+ targets = {'x86_64': ('linux-x64', 62), 'aarch64': ('linux-arm64', 183)}
+ if platform.system() != 'Linux' or machine not in targets:
+ raise ValueError('Harness runtime updates require x86-64 or ARM64 Linux.')
+ return targets[machine]
+
+
+def verify_hn(data):
+ target, machine = runtime_platform()
+ # Check before executing even a version probe: binfmt/emulation can make a
+ # binary for the wrong CPU appear usable. Releases use 64-bit little-endian
+ # ELF executables (ET_EXEC or ET_DYN), never scripts or native Mac binaries.
+ if (len(data) < 64 or data[:7] != b'\x7fELF\x02\x01\x01' or
+ int.from_bytes(data[16:18], 'little') not in (2, 3) or
+ int.from_bytes(data[18:20], 'little') != machine or
+ int.from_bytes(data[20:24], 'little') != 1):
+ raise ValueError(f'The hn build does not match this computer ({target}).')
+
+
def release(feed, component):
meta = json.loads(fetch(feed, 65536))
if not isinstance(meta, dict):
@@ -151,7 +173,10 @@ def release(feed, component):
builds = meta.get('builds')
if not isinstance(builds, dict):
raise ValueError('Invalid hn release manifest.')
- value, refs = meta.get('version'), {'harness-tui': builds.get('linux-x64')}
+ target, _ = runtime_platform()
+ if target not in builds:
+ raise ValueError(f'No hn build is available for {target}.')
+ value, refs = meta.get('version'), {'harness-tui': builds[target]}
else:
entry = meta.get('cli', {})
if not isinstance(entry, dict):
@@ -175,6 +200,8 @@ def run(*args, timeout=45, **kwargs):
def versions(folder):
# Version probes do not open a terminal, start a daemon or require a network.
+ with (folder / 'harness-tui').open('rb') as handle:
+ verify_hn(handle.read(64))
hn = run(folder / 'harness-tui', '--version', env=dict(os.environ, HN_AS_TMUX='0'))
match = re.fullmatch(r'hn (\d+\.\d+\.\d+)(?: \(tmux [^\r\n]+\))?', hn)
if not match:
@@ -294,6 +321,8 @@ def check(feeds=None, progress=lambda _: None, force_system=False):
ref.get('size') is not None and len(data) != ref['size']
):
raise ValueError('Download checksum or size does not match the release.')
+ if name == 'harness-tui':
+ verify_hn(data)
component_files[name] = data
changes.update(component_files)
target_versions[component] = candidate
diff --git a/os/network.py b/os/network.py
index f6589fde4..d34dbf32a 100644
--- a/os/network.py
+++ b/os/network.py
@@ -44,9 +44,13 @@ def connected():
return False
-def scan(rescan=True):
+def scan(rescan=None):
+ # Opening the page should reuse a recent scan, especially just after a
+ # reconnect. NetworkManager refreshes results older than 30 seconds in auto
+ # mode. Force a scan only when the user chooses Rescan.
+ mode = 'auto' if rescan is None else 'yes' if rescan else 'no'
result = nmcli('-t', '-e', 'yes', '-f', 'SSID,SIGNAL,SECURITY,DEVICE,BSSID,IN-USE',
- 'device', 'wifi', 'list', '--rescan', 'yes' if rescan else 'no', wait=10)
+ 'device', 'wifi', 'list', '--rescan', mode, wait=10)
if result.returncode:
raise ValueError('Could not scan Wi-Fi. Check airplane mode, then choose Rescan.')
networks = {}
@@ -71,6 +75,17 @@ def wired_devices():
if len(row := fields(line)) == 3 and row[1] == 'ethernet' and row[2] != 'unavailable']
+def still_connected(network):
+ # The page can stay open through a lost connection or suspend. IN-USE is
+ # current NetworkManager state even without a new radio scan; never trust
+ # the Connected label captured when the page opened.
+ try:
+ return any(row['active'] and all(row[key] == network[key]
+ for key in ('ssid', 'device', 'security')) for row in scan(rescan=False))
+ except (OSError, subprocess.TimeoutExpired, ValueError):
+ return False
+
+
def saved_connection(network):
result = nmcli('-t', '-f', 'UUID,TYPE', 'connection', 'show', wait=3)
if result.returncode:
@@ -192,16 +207,23 @@ class NetworkPage:
self.line(6, 'Connect to Wi-Fi')
return height
- def refresh(self):
+ def refresh(self, rescan=None):
self.begin()
self.line(8, 'Finding Wi-Fi…')
self.screen.refresh()
self.message = ''
+ self.networks, self.wired = [], []
try:
nmcli('radio', 'wifi', 'on', wait=3)
- self.networks, self.wired = scan(), wired_devices()
+ self.networks = scan(rescan=rescan)
except (OSError, subprocess.TimeoutExpired, ValueError) as error:
self.message = str(error) if isinstance(error, ValueError) else 'Wi-Fi is unavailable. Choose Rescan to try again.'
+ # A missing or unavailable Wi-Fi radio must not hide the wired path.
+ try:
+ self.wired = wired_devices()
+ except (OSError, subprocess.TimeoutExpired):
+ if not self.message:
+ self.message = 'Could not check Ethernet. Choose Rescan to try again.'
self.selected = 0
def busy(self, name):
@@ -294,11 +316,11 @@ class NetworkPage:
elif key in (curses.KEY_DOWN, '\t'):
self.selected = (self.selected + 1) % len(rows)
elif key in ('r', 'R'):
- self.refresh()
+ self.refresh(rescan=True)
elif key in ('\n', '\r', curses.KEY_ENTER):
kind, value = rows[self.selected]
if kind == 'rescan':
- self.refresh()
+ self.refresh(rescan=True)
continue
self.busy(value['ssid'] if kind == 'wifi' else 'Ethernet')
try:
@@ -306,7 +328,7 @@ class NetworkPage:
if nmcli('device', 'connect', value[0], wait=30).returncode == 0:
return 0
self.message = 'Could not connect Ethernet. Check the cable and try again.'
- elif value['active'] or connect(value):
+ elif (value['active'] and still_connected(value)) or connect(value):
return 0
elif value['security'] and value['security'] != '--':
if self.password(value):
diff --git a/os/tests/arm_update_vm.py b/os/tests/arm_update_vm.py
new file mode 100644
index 000000000..794d31d9b
--- /dev/null
+++ b/os/tests/arm_update_vm.py
@@ -0,0 +1,219 @@
+#!/usr/bin/env python3
+"""Exercise real runtime updates in the private ARM graphical fixture.
+
+This is not an ARM installer or a Fedora system updater. Only the per-user
+Harness runtime and its screen reconnect are exercised, using unpublished
+native binaries. The fixture's boot kernel and board support are unchanged.
+"""
+import argparse
+from functools import partial
+import hashlib
+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
+import json
+from pathlib import Path
+import re
+import shlex
+import shutil
+import subprocess
+import tempfile
+import threading
+import time
+import xml.etree.ElementTree as ET
+
+from arm_boot import digest
+from arm_session import ROOT, SessionVM, failure_evidence, fixture_identity
+from fast_update_vm import exercise
+from session_vm import put
+
+
+def update_identity(folder, source):
+ record = folder / 'fixture.json'
+ if record.is_symlink() or not record.is_file():
+ raise ValueError('Use a regular unpublished update fixture.')
+ info = json.loads(record.read_text())
+ if (not isinstance(info, dict) or info.get('published') is not False or info.get('status') != 'prepared' or
+ info.get('source_commit') != source or info.get('architecture') != 'aarch64' or
+ info.get('target') != 'aarch64-unknown-linux-musl' or info.get('version') != '999.0.1'):
+ raise ValueError('Use the exact-source prepared native ARM update fixture.')
+ required = {'harness-tui', 'cli.mjs', 'notify.mjs', 'cli-current.mjs', 'hn.json',
+ 'cli.json', 'cli-current.json', 'cli-ancestor.json',
+ 'feeds-ancestor.json', 'feeds-hn.json', 'feeds-both.json'}
+ if not isinstance(info.get('files'), dict) or set(info['files']) != required:
+ raise ValueError('The private update fixture is incomplete.')
+ if {path.name for path in folder.iterdir()} != required | {'fixture.json'}:
+ raise ValueError('The private update fixture contains unverified entries.')
+ for name, checksum in info['files'].items():
+ path = folder / name
+ if (not re.fullmatch(r'[a-f0-9]{64}', str(checksum)) or path.is_symlink() or
+ not path.is_file() or digest(path) != checksum):
+ raise ValueError('Update fixture checksum mismatch: ' + name)
+ with (folder / 'harness-tui').open('rb') as handle:
+ header = handle.read(64)
+ if header[:7] != b'\x7fELF\x02\x01\x01' or int.from_bytes(header[18:20], 'little') != 183:
+ raise ValueError('The update terminal must be native ARM64 ELF.')
+ release = json.loads((folder / 'hn.json').read_text())
+ if set(release.get('builds', {})) != {'linux-arm64'}:
+ raise ValueError('The update must exercise the linux-arm64 release entry.')
+ # The private HTTP server and guest must consume the files whose hashes
+ # were checked above, not a different URL or another checksummed artifact.
+ # In particular, a valid CLI version probe does not execute notify.mjs.
+ try:
+ current_cli = info['runtime']['versions']['cli']
+ ancestor_cli = info['runtime']['release_baselines']['cli']['version']
+ except (KeyError, TypeError) as error:
+ raise ValueError('Missing original CLI versions in the update fixture.') from error
+ if any(not isinstance(value, str) or not re.fullmatch(r'\d+\.\d+\.\d+', value)
+ for value in [current_cli, ancestor_cli]):
+ raise ValueError('Invalid original CLI versions in the update fixture.')
+ base_url = 'http://127.0.0.1:19447/'
+
+ def ref(name):
+ return {'url': base_url + name, 'sha256': info['files'][name], 'size': (folder / name).stat().st_size}
+
+ expected = {
+ 'hn.json': {'version': info['version'], 'builds': {'linux-arm64': ref('harness-tui')}},
+ 'cli.json': {'cli': {'version': info['version'], 'cli': ref('cli.mjs'), 'notify': ref('notify.mjs')}},
+ 'cli-current.json': {'cli': {'version': current_cli, 'cli': ref('cli-current.mjs'), 'notify': ref('notify.mjs')}},
+ 'cli-ancestor.json': {'cli': {'version': ancestor_cli, 'cli': ref('cli.mjs'), 'notify': ref('notify.mjs')}},
+ 'feeds-ancestor.json': {'cli': base_url + 'cli-ancestor.json'},
+ 'feeds-hn.json': {'hn': base_url + 'hn.json', 'cli': base_url + 'cli-current.json'},
+ 'feeds-both.json': {'hn': base_url + 'hn.json', 'cli': base_url + 'cli.json'},
+ }
+ for name, document in expected.items():
+ if json.loads((folder / name).read_text()) != document:
+ raise ValueError('Private update manifest does not match its verified local assets: ' + name)
+ return info
+
+
+class UserSession:
+ """The shared PC acceptance uses a user console; ARM has a root test console."""
+ def __init__(self, machine):
+ self.machine = machine
+ self.folder = machine.folder
+
+ def command(self, command, **kwargs):
+ return self.machine.user(command, **kwargs)
+
+ def __getattr__(self, name):
+ return getattr(self.machine, name)
+
+
+def prepare_updates(machine):
+ # Install only the user updater into this private disk. PC installation,
+ # pacman, system-release feeds and their privileged helpers stay absent.
+ files = {
+ 'os/live_update.py': '/usr/lib/harness-os/live_update.py',
+ 'os/root/usr/lib/harness-os/open-updates': '/usr/lib/harness-os/open-updates',
+ 'os/root/usr/lib/systemd/user/harness-update.service': '/usr/lib/systemd/user/harness-update.service',
+ 'os/root/usr/lib/systemd/user/harness-update.timer': '/usr/lib/systemd/user/harness-update.timer',
+ }
+ receipt = {}
+ for source, destination in files.items():
+ content = (ROOT / source).read_text()
+ put(machine, destination, content)
+ machine.command('chmod ' + ('644' if '/systemd/' in destination else '755') + ' ' + shlex.quote(destination))
+ actual = hashlib.sha256(machine.read_file(destination)).hexdigest()
+ if actual != digest(ROOT / source):
+ raise ValueError('Updater transfer changed: ' + source)
+ receipt[source] = actual
+ # The shared acceptance performs fault injection via sudo inside its guest.
+ # This passwordless test account already has a private root serial console;
+ # this additional permission must never enter any published image.
+ put(machine, '/etc/sudoers.d/99-harness-update-test', 'me ALL=(ALL) NOPASSWD: ALL\n')
+ machine.command('chmod 440 /etc/sudoers.d/99-harness-update-test; visudo -cf /etc/sudoers.d/99-harness-update-test')
+ config_path = '/usr/share/harness-os/labwc/rc.xml'
+ config = ET.fromstring(machine.read_file(config_path))
+ keyboard = config.find('keyboard')
+ if keyboard is None:
+ raise ValueError('ARM fixture lacks its graphical keyboard configuration.')
+ for binding in list(keyboard.findall('keybind')):
+ if binding.get('key') == 'W-u':
+ keyboard.remove(binding)
+ original = ET.parse(ROOT / 'os/root/usr/share/harness-os/labwc/rc.xml')
+ binding = original.find('.//keybind[@key="W-u"]')
+ if binding is None:
+ raise ValueError('No production update shortcut to exercise.')
+ keyboard.append(binding)
+ put(machine, config_path, ET.tostring(config, encoding='unicode'))
+ receipt['effective_labwc_sha256'] = hashlib.sha256(machine.read_file(config_path)).hexdigest()
+ machine.user('systemctl --user daemon-reload')
+ machine.command('pkill -HUP -u 1000 -x labwc')
+ return receipt
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--fixture', type=Path, required=True)
+ parser.add_argument('--fixture-source', required=True, help='Actual producer SHA of the immutable ARM boot fixture')
+ parser.add_argument('--updates', type=Path, required=True)
+ parser.add_argument('--updates-source', help='Explicit producer SHA when the update fixture precedes this test driver')
+ parser.add_argument('--output', type=Path, default=Path('os/test-results/arm-updates'))
+ args = parser.parse_args()
+ source = subprocess.check_output(['git', '-C', str(ROOT), 'rev-parse', 'HEAD'], text=True).strip()
+ if subprocess.check_output(['git', '-C', str(ROOT), 'status', '--porcelain', '--untracked-files=no'], text=True).strip():
+ parser.error('Commit the exact test source before acceptance.')
+ fixture, updates = args.fixture.resolve(), args.updates.resolve()
+ image = fixture_identity(fixture, args.fixture_source)
+ release = update_identity(updates, args.updates_source or source)
+ output = args.output.resolve()
+ output.mkdir(parents=True, exist_ok=False)
+ receipt = {'status': 'running', 'test_source_commit': source,
+ 'image_source_commit': args.fixture_source, 'image_manifest_sha256': digest(fixture / 'manifest.json'),
+ 'update_fixture': release, 'update_manifest_sha256': digest(updates / 'fixture.json'),
+ 'started_at': time.time(), 'checks': [],
+ 'scope': 'Native ARM per-user runtime activation/rollback on private Fedora/Asahi VM',
+ 'limitations': ['No ARM product image, firmware provisioning or physical hardware test',
+ 'No Fedora package update or boot recovery coverage',
+ 'Private passwordless test account and local root console; never publish this disk']}
+ machine = server = None
+ with tempfile.TemporaryDirectory(prefix='harness-arm-updates-') as temporary:
+ work = Path(temporary)
+ try:
+ disk = work / 'guest.raw'
+ subprocess.run(['zstd', '-d', '--sparse', str(fixture / 'guest.raw.zst'), '-o', str(disk)],
+ check=True, timeout=180)
+ if disk.stat().st_size != image['raw_disk']['bytes'] or digest(disk) != image['raw_disk']['sha256']:
+ raise ValueError('Decompressed boot fixture changed.')
+ served = work / 'served'
+ served.mkdir()
+ # Only this fixture's files are exposed on the local test server.
+ shutil.copytree(updates, served / 'fast')
+ server = ThreadingHTTPServer(('127.0.0.1', 0), partial(SimpleHTTPRequestHandler, directory=str(served)))
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ machine = SessionVM(output / 'first-boot', disk, fixture / 'Image')
+ machine.start()
+ machine.wait_user('test -f ~/.local/state/harness-os/onboarded && pgrep -u 1000 -x opencode >/dev/null', 150)
+ machine.frame('01-workspace', ['OpenCode', 'Ask anything'], 90)
+ receipt['accelerator'] = machine.accelerator
+ receipt['candidate_files'] = prepare_updates(machine)
+ receipt['fast_updates'] = exercise(UserSession(machine), updates, f'http://10.0.2.2:{server.server_port}')
+ # Capture identity independently of the staged manifest and probe
+ # actual keyboard input before the private disk is discarded.
+ state, _ = machine.user('harness updates status')
+ (output / 'native-runtime-status.txt').write_text(state)
+ machine.keyboard('after-updates')
+ receipt['checks'].append('Shared activation, rollback, mouse, Super+u and surviving-work acceptance passed with real ARM binaries')
+ receipt['shutdown'] = machine.poweroff()
+ receipt['status'] = 'passed'
+ print('Native ARM runtime update and surviving-work acceptance passed', flush=True)
+ except BaseException as error:
+ receipt.update(status='failed', error=str(error))
+ failure_evidence(machine)
+ raise
+ finally:
+ try:
+ if machine:
+ machine.close()
+ if server:
+ server.shutdown()
+ server.server_close()
+ except (OSError, RuntimeError) as error:
+ receipt.update(status='failed', cleanup_error=str(error))
+ raise
+ finally:
+ receipt['finished_at'] = time.time()
+ (output / 'receipt.json').write_text(json.dumps(receipt, indent=2) + '\n')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/os/tests/build-update-fixture.py b/os/tests/build-update-fixture.py
index fcf1c5ed2..2e905656b 100644
--- a/os/tests/build-update-fixture.py
+++ b/os/tests/build-update-fixture.py
@@ -1,55 +1,181 @@
#!/usr/bin/env python3
-"""Build unpublished real runtimes for the private VM update feed. Never publish these."""
+"""Build real, unpublished native runtimes for the private VM update feed."""
+import argparse
import hashlib
import json
import os
from pathlib import Path
+import platform
import re
import shutil
import subprocess
+import sys
import tempfile
+import time
+import tomllib
-source = Path(__file__).resolve().parents[2]
-output = source / 'os/work/fast-update-fixture'
-output.mkdir(parents=True, exist_ok=False)
-fixture_version = '999.0.1'
-base_url = 'http://127.0.0.1:19447/'
-runtime = source / 'os/work/runtime'
-# Keep the production runtime/package already built from clean source untouched.
-with tempfile.TemporaryDirectory(prefix='harness-update-fixture-') as temporary:
- project = Path(temporary) / 'tui'
- shutil.copytree(source / 'tui', project, ignore=shutil.ignore_patterns('target', '.git'))
- manifest = project / 'Cargo.toml'
- manifest.write_text(re.sub(r'(?m)^version = "[^"]+"', f'version = "{fixture_version}"', manifest.read_text(), count=1))
- lock = project / 'Cargo.lock'
- lock.write_text(re.sub(r'(name = "harness-tui"\nversion = ")[^"]+', r'\g<1>' + fixture_version, lock.read_text()))
- subprocess.run(['cargo', 'build', '--locked', '--release', '--target', 'x86_64-unknown-linux-musl',
- '--manifest-path', str(manifest)], check=True,
- env=dict(os.environ, CARGO_TARGET_DIR=str(source / 'tui/target')))
- shutil.copyfile(source / 'tui/target/x86_64-unknown-linux-musl/release/harness-tui', output / 'harness-tui')
-subprocess.run(['node', 'build-bundle.mjs'], cwd=source / 'cli', check=True,
- env=dict(os.environ, ADAPTER_VERSION=fixture_version))
-shutil.copyfile(source / 'cli/dist/cli.js', output / 'cli.mjs')
-shutil.copyfile(source / 'cli/dist/notify.mjs', output / 'notify.mjs')
-shutil.copyfile(runtime / 'cli.js', output / 'cli-current.mjs')
-current_cli = subprocess.check_output(['node', str(output / 'cli-current.mjs'), 'version'], text=True).strip()
-
-def ref(name):
- data = (output / name).read_bytes()
- return {'url': base_url + name, 'sha256': hashlib.sha256(data).hexdigest(), 'size': len(data)}
-
-baseline = json.loads((runtime / 'source.json').read_text())['release_baselines']['cli']['version']
-documents = {
- 'hn.json': {'version': fixture_version, 'builds': {'linux-x64': ref('harness-tui')}},
- 'cli.json': {'cli': {'version': fixture_version, 'cli': ref('cli.mjs'), 'notify': ref('notify.mjs')}},
- 'cli-current.json': {'cli': {'version': current_cli, 'cli': ref('cli-current.mjs'), 'notify': ref('notify.mjs')}},
- 'cli-ancestor.json': {'cli': {'version': baseline, 'cli': ref('cli.mjs'), 'notify': ref('notify.mjs')}},
- 'feeds-ancestor.json': {'cli': base_url + 'cli-ancestor.json'},
- 'feeds-hn.json': {'hn': base_url + 'hn.json', 'cli': base_url + 'cli-current.json'},
- 'feeds-both.json': {'hn': base_url + 'hn.json', 'cli': base_url + 'cli.json'},
-}
-for name, data in documents.items():
- (output / name).write_text(json.dumps(data) + '\n')
-(output / 'fixture.json').write_text(json.dumps({'version': fixture_version, 'published': False,
- 'source_commit': subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip(),
- 'files': {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in output.iterdir() if p.is_file()}}, indent=2) + '\n')
+ROOT = Path(__file__).resolve().parents[2]
+VERSION = '999.0.1'
+BASE_URL = 'http://127.0.0.1:19447/'
+FILES = {'harness-tui', 'cli.js', 'notify.mjs'}
+TARGETS = {'x86_64': ('linux-x64', 'x64', 62), 'aarch64': ('linux-arm64', 'arm64', 183)}
+
+
+def command(*args, cwd=ROOT, **kwargs):
+ return subprocess.check_output([str(arg) for arg in args], cwd=cwd, text=True,
+ timeout=30, **kwargs).strip()
+
+
+def digest(path):
+ with path.open('rb') as handle:
+ return hashlib.file_digest(handle, 'sha256').hexdigest()
+
+
+def clean_source(source):
+ commit = command('git', 'rev-parse', 'HEAD', cwd=source)
+ if not re.fullmatch(r'[0-9a-f]{40}', commit) or command('git', 'status', '--porcelain', '--untracked-files=normal', cwd=source):
+ raise ValueError('Commit source changes before building a traceable update fixture.')
+ return commit
+
+
+def verify_elf(path, architecture):
+ with path.open('rb') as handle:
+ header = handle.read(64)
+ if (len(header) != 64 or header[:7] != b'\x7fELF\x02\x01\x01' or
+ int.from_bytes(header[16:18], 'little') not in (2, 3) or
+ int.from_bytes(header[18:20], 'little') != TARGETS[architecture][2] or
+ int.from_bytes(header[20:24], 'little') != 1):
+ raise ValueError('The fixture requires a matching native Linux ELF executable.')
+
+
+def validate_runtime(runtime, commit, architecture, versions, baselines):
+ if {path.name for path in runtime.iterdir()} != FILES | {'source.json'}:
+ raise ValueError('Use the complete, unmodified baseline runtime directory.')
+ if (runtime / 'source.json').is_symlink():
+ raise ValueError('The baseline identity cannot be a symlink.')
+ info = json.loads((runtime / 'source.json').read_text())
+ if (not isinstance(info, dict) or info.get('source_commit') != commit or info.get('dirty') is not False or
+ info.get('architecture') != architecture or info.get('target') != architecture + '-unknown-linux-musl' or
+ info.get('versions') != versions or info.get('release_baselines') != baselines or
+ not isinstance(info.get('files'), dict) or
+ set(info.get('files', {})) != FILES):
+ raise ValueError('The baseline runtime must match this exact clean source and native architecture.')
+ for name, identity in info['files'].items():
+ path = runtime / name
+ if (not isinstance(identity, dict) or path.is_symlink() or not path.is_file() or path.stat().st_size != identity.get('bytes') or
+ digest(path) != identity.get('sha256')):
+ raise ValueError('The baseline runtime failed verification: ' + name)
+ verify_elf(runtime / 'harness-tui', architecture)
+ return info
+
+
+def probe_versions(folder, architecture, expected, cli_name):
+ verify_elf(folder / 'harness-tui', architecture)
+ hn = command(folder / 'harness-tui', '--version', env=dict(os.environ, HN_AS_TMUX='0'))
+ match = re.fullmatch(r'hn (\d+\.\d+\.\d+)(?: \(tmux [^\r\n]+\))?', hn)
+ versions = {'hn': match[1] if match else None, 'cli': command('node', folder / cli_name, 'version')}
+ if versions != expected:
+ raise ValueError('The compiled runtime did not report the expected versions.')
+ return versions
+
+
+def copy_tui(source, destination):
+ # Compile tracked source only; ignored files cannot quietly enter a fixture.
+ paths = subprocess.check_output(['git', '-C', str(source), 'ls-files', '-z', '--', 'tui'], timeout=30)
+ for value in paths.split(b'\0'):
+ if not value:
+ continue
+ relative = Path(os.fsdecode(value))
+ target = destination / relative.relative_to('tui')
+ target.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(source / relative, target, follow_symlinks=False)
+ manifest, lock = destination / 'Cargo.toml', destination / 'Cargo.lock'
+ for path, pattern in [(manifest, r'(?m)(^version = ")[^"]+'),
+ (lock, r'(name = "harness-tui"\nversion = ")[^"]+')]:
+ updated, count = re.subn(pattern, r'\g<1>' + VERSION, path.read_text(), count=1)
+ if count != 1:
+ raise ValueError('Could not set the private fixture version in ' + path.name)
+ path.write_text(updated)
+
+
+def write_manifests(folder, architecture, current_cli, baseline):
+ def ref(name):
+ return {'url': BASE_URL + name, 'sha256': digest(folder / name), 'size': (folder / name).stat().st_size}
+
+ documents = {
+ 'hn.json': {'version': VERSION, 'builds': {TARGETS[architecture][0]: ref('harness-tui')}},
+ 'cli.json': {'cli': {'version': VERSION, 'cli': ref('cli.mjs'), 'notify': ref('notify.mjs')}},
+ 'cli-current.json': {'cli': {'version': current_cli, 'cli': ref('cli-current.mjs'), 'notify': ref('notify.mjs')}},
+ 'cli-ancestor.json': {'cli': {'version': baseline, 'cli': ref('cli.mjs'), 'notify': ref('notify.mjs')}},
+ 'feeds-ancestor.json': {'cli': BASE_URL + 'cli-ancestor.json'},
+ 'feeds-hn.json': {'hn': BASE_URL + 'hn.json', 'cli': BASE_URL + 'cli-current.json'},
+ 'feeds-both.json': {'hn': BASE_URL + 'hn.json', 'cli': BASE_URL + 'cli.json'},
+ }
+ for name, data in documents.items():
+ (folder / name).write_text(json.dumps(data) + '\n')
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--runtime', type=Path, default=ROOT / 'os/work/runtime')
+ parser.add_argument('--output', type=Path, default=ROOT / 'os/work/fast-update-fixture')
+ args = parser.parse_args(argv)
+ architecture = platform.machine()
+ if platform.system() != 'Linux' or architecture not in TARGETS or os.geteuid() == 0:
+ parser.error('Build as an ordinary user on native x86-64 or ARM64 Linux.')
+ output, runtime = args.output.absolute(), args.runtime.resolve(strict=True)
+ if output.exists() or output.is_symlink():
+ parser.error('Use a fresh output directory; fixtures are immutable.')
+ if shutil.disk_usage(ROOT).free < 4 * 1024 ** 3:
+ parser.error('The native build requires at least 4 GiB of free space.')
+ if command('node', '-p', 'process.arch') != TARGETS[architecture][1]:
+ parser.error('Node must match the native Linux build architecture.')
+ started = time.time()
+ commit = clean_source(ROOT)
+ versions = {'hn': tomllib.loads((ROOT / 'tui/Cargo.toml').read_text())['package']['version'],
+ 'cli': json.loads((ROOT / 'cli/package.json').read_text())['version']}
+ baselines = json.loads(command(sys.executable, ROOT / 'os/tools/runtime-baseline.py'))
+ baseline = baselines.get('cli', {}).get('version')
+ if not isinstance(baseline, str) or not re.fullmatch(r'\d+\.\d+\.\d+', baseline):
+ parser.error('The fixture needs a published CLI ancestor; fetch complete history and release tags.')
+ info = validate_runtime(runtime, commit, architecture, versions, baselines)
+ probe_versions(runtime, architecture, versions, 'cli.js')
+ target = architecture + '-unknown-linux-musl'
+ output.parent.mkdir(parents=True, exist_ok=True)
+ with tempfile.TemporaryDirectory(prefix='.update-fixture-', dir=output.parent) as temporary:
+ work = Path(temporary)
+ project, stage = work / 'tui', work / 'fixture'
+ stage.mkdir()
+ copy_tui(ROOT, project)
+ subprocess.run(['cargo', 'build', '--locked', '--release', '--target', target,
+ '--manifest-path', str(project / 'Cargo.toml')], check=True, cwd=ROOT, timeout=1200,
+ env=dict(os.environ, CARGO_TARGET_DIR=str(ROOT / 'tui/target')))
+ shutil.copy2(ROOT / 'tui/target' / target / 'release/harness-tui', stage / 'harness-tui')
+ # The CLI already exposes a separate output directory for real update tests.
+ subprocess.run(['node', 'build-bundle.mjs'], cwd=ROOT / 'cli', check=True, timeout=180,
+ env=dict(os.environ, ADAPTER_VERSION=VERSION, BUNDLE_OUT_DIR=str(work / 'cli')))
+ shutil.copyfile(work / 'cli/cli.js', stage / 'cli.mjs')
+ shutil.copyfile(work / 'cli/notify.mjs', stage / 'notify.mjs')
+ shutil.copyfile(runtime / 'cli.js', stage / 'cli-current.mjs')
+ compiled = probe_versions(stage, architecture, {'hn': VERSION, 'cli': VERSION}, 'cli.mjs')
+ if command('node', stage / 'cli-current.mjs', 'version') != versions['cli']:
+ raise ValueError('The original CLI changed while preparing the fixture.')
+ if clean_source(ROOT) != commit or validate_runtime(runtime, commit, architecture, versions, baselines) != info:
+ raise ValueError('Source or baseline runtime changed during the build.')
+ write_manifests(stage, architecture, versions['cli'], baseline)
+ receipt = {'status': 'prepared', 'version': VERSION, 'published': False, 'source_commit': commit,
+ 'architecture': architecture, 'target': target, 'platform': TARGETS[architecture][0],
+ 'versions': compiled, 'runtime': info, 'runtime_identity_sha256': digest(runtime / 'source.json'),
+ 'node': command('node', '--version'), 'rust': command('rustc', '--version'),
+ 'started_at': started, 'finished_at': time.time(),
+ 'files': {path.name: digest(path) for path in sorted(stage.iterdir())}}
+ (stage / 'fixture.json').write_text(json.dumps(receipt, indent=2) + '\n')
+ stage.rename(output)
+ print(f'Private {TARGETS[architecture][0]} fixture: {output}')
+
+
+if __name__ == '__main__':
+ try:
+ main()
+ except (ValueError, OSError, KeyError, TypeError, subprocess.SubprocessError) as error:
+ raise SystemExit('Harness update fixture: ' + str(error))
diff --git a/os/tests/essentials_vm.py b/os/tests/essentials_vm.py
index 55d4d6068..4e3a88b3a 100644
--- a/os/tests/essentials_vm.py
+++ b/os/tests/essentials_vm.py
@@ -87,7 +87,7 @@ def wait_screen(vm, words, name, timeout=20):
time.sleep(.25)
-def wireless(vm, result, installed=False):
+def wireless(vm, result):
print('Preparing simulated WPA2 access point inside the disposable guest', flush=True)
vm.command('systemctl start harness-keyring', timeout=240)
output, _ = vm.command('pacman -S --needed --noconfirm hostapd dnsmasq iw', timeout=180)
@@ -100,8 +100,8 @@ def wireless(vm, result, installed=False):
vm.command('! ip route show default | grep -v "dev $(cat /run/harness-station)"')
form = 'sudo python3 /usr/lib/harness-os/network.py --first-use; result=$?; printf %s "$result" > /tmp/wifi-form-result; exec bash -l'
vm.command(USER_ENV + 'hn new-window -n Wi-Fi ' + shlex.quote(form))
- offline_label = 'set up later' if installed else 'install without connecting'
- wait_screen(vm, ['harness-test', offline_label], 'wifi-01-networks')
+ text = wait_screen(vm, ['harness-test', 'Rescan'], 'wifi-01-networks')
+ assert all(label not in text for label in ['set up later', 'install without connecting', 'continue offline']), text
vm.keys('esc')
wait_screen(vm, ['harness-test'], 'wifi-01-escape-keeps-welcome')
vm.keys('ctrl', 'c')
@@ -140,6 +140,24 @@ def wireless(vm, result, installed=False):
'grep -Fx harness-wifi-success; then exit 0; fi; sleep 1; done; exit 1', timeout=100)
vm.command('find /etc/NetworkManager/system-connections -name "*.nmconnection" -exec stat -c "%a %U %n" {} \\;')
result['checks'].append('Wireless reconnects after a radio off/on cycle using its stored profile')
+ # The on-demand Wi-Fi page is a snapshot. Lose the connection while it is
+ # open, then select the stale Connected row. Success requires a new DHCP
+ # address and actual traffic, not merely a zero exit from the form.
+ reconnect_form = form.replace(' --first-use', '').replace('/tmp/wifi-form-result', '/tmp/wifi-reconnect-result')
+ vm.command(USER_ENV + 'hn new-window -n Reconnect ' + shlex.quote(reconnect_form))
+ wait_screen(vm, [SSID, 'Connected'], 'wifi-05-before-drop')
+ vm.command('nmcli device disconnect "$(cat /run/harness-station)" && '
+ 'test -z "$(ip -4 -o address show dev "$(cat /run/harness-station)" scope global)"')
+ vm.screenshot('wifi-05-stale-connected-row')
+ vm.keys('ret')
+ vm.command('for n in $(seq 1 120); do test -s /tmp/wifi-reconnect-result && '
+ 'test "$(cat /tmp/wifi-reconnect-result)" = 0 && exit 0; sleep .5; done; exit 1', timeout=65)
+ output, _ = vm.command('ip -4 -o address show dev "$(cat /run/harness-station)" scope global | grep "10[.]77[.]0[.]" && '
+ 'resolvectl query harness.test && '
+ 'test "$(curl --noproxy "*" -fsS --max-time 10 http://harness.test:8080)" = harness-wifi-success')
+ (vm.folder / 'wifi-reconnected-route-and-dns.txt').write_text(output)
+ vm.screenshot('wifi-05-reconnected')
+ result['checks'].append('Selecting a stale Connected row after link loss reconnects the saved Wi-Fi profile, obtains DHCP and resolves/fetches HTTP with Ethernet still disconnected')
# The AP has DHCP, DNS and HTTP but no upstream Internet. NM can report
# "connected (site only)"; this must not reopen Wi-Fi in the agent pane.
# Run the complete packaged onboarding, not just its network sub-form.
@@ -158,19 +176,6 @@ def wireless(vm, result, installed=False):
vm.screenshot('wifi-04-onboarded-without-second-prompt')
result['checks'].append('Full onboarding opens three panes on a saved local-only Wi-Fi connection without asking for Wi-Fi again')
vm.command('nmcli connection modify ' + SSID + ' ipv4.never-default no ipv6.never-default no')
- # The full-page offline action returns an explicit install result; Esc does
- # not strand a first-time user in an empty shell.
- vm.command('nmcli device disconnect "$(cat /run/harness-station)"')
- vm.command(USER_ENV + 'hn new-window -n Offline ' + shlex.quote(form.replace('/tmp/wifi-form-result', '/tmp/wifi-offline-result')))
- wait_screen(vm, [offline_label], 'wifi-05-offline')
- if installed:
- vm.keys('shift', 'tab')
- vm.keys('ret')
- else:
- vm.keys('i')
- expected = 11 if installed else 10
- vm.command('for n in $(seq 1 40); do test "$(cat /tmp/wifi-offline-result 2>/dev/null)" = ' + str(expected) + ' && exit 0; sleep .25; done; exit 1')
- result['checks'].append('Installed Wi-Fi can continue to offline work without exposing installation' if installed else 'First-use Wi-Fi always offers offline installation, and selecting it exits with the native install action')
vm.command('nmcli connection up ' + SSID, timeout=60)
vm.monitor('set_link', name='hnnet', up=True)
vm.command('while read -r dev; do nmcli device set "$dev" managed yes; nmcli device connect "$dev"; done < /run/harness-ethernet')
@@ -222,6 +227,8 @@ def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--iso', type=Path, required=True)
parser.add_argument('--output', type=Path, default=Path('os/test-results/essentials'))
+ parser.add_argument('--network-script', type=Path,
+ help='Test this candidate Wi-Fi form over the verified image; record and verify its hash')
args = parser.parse_args()
if not os.access('/dev/kvm', os.R_OK | os.W_OK):
parser.error('Use native x86 KVM for these hardware-plumbing checks.')
@@ -259,7 +266,18 @@ def main():
result['checks'].append('Wi-Fi and audio checks run on an encrypted installed system after offline USB installation')
vm.command(USER_ENV + '/usr/lib/harness-os/wait-runtime')
vm.command(USER_ENV + 'sh -c ' + shlex.quote('for n in $(seq 1 60); do systemctl --user is-active --quiet hn-screen && pgrep -u 1000 -x foot >/dev/null && exit 0; sleep .25; done; exit 1'))
- wireless(vm, result, installed=installed)
+ if args.network_script:
+ candidate = args.network_script.read_bytes()
+ checksum = hashlib.sha256(candidate).hexdigest()
+ result['candidate_network'] = {'path': str(args.network_script), 'sha256': checksum,
+ 'scope': 'Only /usr/lib/harness-os/network.py replaced in disposable guest; other product files are the verified image'}
+ put(vm, '/tmp/network-candidate.py', candidate.decode())
+ vm.command('test "$(sha256sum /tmp/network-candidate.py | cut -d " " -f 1)" = ' + shlex.quote(checksum))
+ vm.command('install -o root -g root -m 755 /tmp/network-candidate.py /usr/lib/harness-os/network.py')
+ result['network_script_sha256'] = hashlib.sha256(vm.read_file('/usr/lib/harness-os/network.py')).hexdigest()
+ if args.network_script:
+ assert result['network_script_sha256'] == result['candidate_network']['sha256']
+ wireless(vm, result)
sound(vm, result)
vm.stop()
with wave.open(str(folder / ('audio-2.wav' if installed else 'audio-1.wav')), 'rb') as recording:
diff --git a/os/tests/hardware_install_guest.py b/os/tests/hardware_install_guest.py
index 46b776e12..f71a0978e 100644
--- a/os/tests/hardware_install_guest.py
+++ b/os/tests/hardware_install_guest.py
@@ -4,10 +4,15 @@
QEMU has no Broadcom radio. Only device discovery is substituted; the image's
installer, bundle verification, pacman, signature checks and DKMS run normally.
"""
+import argparse
+import hashlib
import importlib.util
import json
+import os
from pathlib import Path
+import shutil
import subprocess
+import tempfile
import time
@@ -18,7 +23,67 @@ def load(name, path):
return module
+def apply_candidate(source, destination, expected):
+ data = source.read_bytes()
+ actual = hashlib.sha256(data).hexdigest()
+ if actual != expected:
+ raise ValueError('Candidate hardware policy checksum mismatch.')
+ destination.write_bytes(data)
+ destination.chmod(0o755)
+ return actual
+
+
+def assigned_devices(hardware, sysfs):
+ """Exercise discovery and activation with private files, never real PCI nodes."""
+ expected = []
+ for index, (driver, override) in enumerate([
+ ('vfio-pci', '(null)'), (None, 'none'),
+ ('bcma-pci-bridge', 'bcma-pci-bridge')]):
+ path = sysfs / 'bus/pci/devices' / f'0000:{index + 3:02x}:00.0'
+ path.mkdir(parents=True)
+ for name, value in [('vendor', '0x14e4'), ('device', '0x43a0'),
+ ('class', '0x028000'), ('driver_override', override)]:
+ (path / name).write_text(value + '\n')
+ if driver:
+ binding = sysfs / 'bus/pci/drivers' / driver
+ binding.mkdir(parents=True)
+ (binding / 'unbind').touch()
+ (path / 'driver').symlink_to(binding)
+ expected.append((path, driver, override))
+ devices = hardware.pci_devices(sysfs)
+ assert len(devices) == len(expected)
+ original_run = hardware.run
+
+ def forbidden_command(*args, **kwargs):
+ raise AssertionError('Assigned PCI device triggered a module operation: ' + repr(args))
+
+ hardware.run = forbidden_command
+ try:
+ for device, (path, driver, override) in zip(devices, expected):
+ assert device['id'] == '14e4:43a0' and device['class'] == '028000'
+ assert not hardware.needs_broadcom(device), device
+ assert hardware.activate(path.name, sysfs)['status'] == 'unchanged'
+ assert (path / 'driver_override').read_text() == override + '\n'
+ if driver:
+ assert (path / 'driver/unbind').read_text() == ''
+ finally:
+ hardware.run = original_run
+ return devices
+
+
def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--candidate-hardware', type=Path)
+ parser.add_argument('--candidate-sha256')
+ options = parser.parse_args()
+ if bool(options.candidate_hardware) != bool(options.candidate_sha256):
+ parser.error('The candidate and its checksum must be supplied together.')
+ assert os.geteuid() == 0 and Path('/etc/harness-live').is_file(), 'Disposable live guest only'
+ assert subprocess.check_output(['lsblk', '-ndo', 'SERIAL', '/dev/vda'], text=True).strip() == 'HN_OS_TEST'
+ hardware_path = Path('/usr/lib/harness-os/hardware.py')
+ original_hash = hashlib.sha256(hardware_path.read_bytes()).hexdigest()
+ if options.candidate_hardware:
+ apply_candidate(options.candidate_hardware, hardware_path, options.candidate_sha256)
hardware = load('hardware', '/usr/lib/harness-os/hardware.py')
installer = load('installer', '/usr/lib/harness-os/install.py')
assert subprocess.check_output(['nmcli', 'networking'], text=True).strip() == 'disabled'
@@ -38,15 +103,34 @@ def main():
devices = [dict(address='0000:03:00.0', id='14e4:43a0',
**{'class': '028000'}, driver=None, interfaces=[])]
original_run = installer.run
- evidence = {}
+ hardware_hash = hashlib.sha256(hardware_path.read_bytes()).hexdigest()
+ evidence = {'image_hardware_sha256': original_hash, 'hardware_sha256': hardware_hash}
def hardware_selection(*args, **kwargs):
if args[:3] != ('/usr/bin/python3', '/usr/lib/harness-os/hardware.py', 'configure-install'):
return original_run(*args, **kwargs)
target = Path(args[3])
+ assert target == Path('/mnt/harness-os') and target.is_mount() and (target / 'etc/harness-live').is_file()
+ installed_hardware = target / hardware_path.relative_to('/')
+ # The extracted payload still contains the base policy. Install the same
+ # explicitly identified candidate before hardware setup and mkinitcpio.
+ if options.candidate_hardware:
+ apply_candidate(hardware_path, installed_hardware, hardware_hash)
+ assert hashlib.sha256(installed_hardware.read_bytes()).hexdigest() == hardware_hash
module = target / hardware.BUNDLE.relative_to('/') / bundle['module']
original_module = module.read_bytes()
before = hardware.run('arch-chroot', target, 'pacman', '-Q', capture=True)
+ with tempfile.TemporaryDirectory(prefix='harness-pci-', dir='/run') as directory:
+ reserved = assigned_devices(hardware, Path(directory))
+ result = hardware.configure_install(target, reserved)
+ assert result == {'drivers': [], 'devices': []}, result
+ assert hardware.run('arch-chroot', target, 'pacman', '-Q', capture=True) == before
+ assert not module.parent.exists()
+ evidence['explicit_assignments'] = {'devices': reserved, 'packages_unchanged': True,
+ 'activation_unchanged': True, 'optional_cache_removed': True}
+ # The negative installation pruned only this target's optional cache.
+ # Restore it from the untouched USB for the positive offline transaction.
+ shutil.copytree(hardware.BUNDLE, module.parent)
# Corruption must fail before a package transaction or binding change.
module.write_bytes(b'corrupt-module')
try:
@@ -81,7 +165,7 @@ def main():
installer.run = hardware_selection
started = time.monotonic()
installer.install(config, installer.live_payload(), Path('/mnt/harness-os'))
- assert evidence, 'The actual installer did not invoke hardware preparation'
+ assert 'optional_packages' in evidence, 'The actual installer did not invoke hardware preparation'
evidence.update(status='passed', kernel=bundle['kernel'], installation_seconds=round(time.monotonic() - started, 3),
scope='Offline encrypted installation with synthetic PCI selection; no physical radio')
print('HN_HARDWARE_RESULT=' + json.dumps(evidence), flush=True)
diff --git a/os/tests/hardware_install_vm.py b/os/tests/hardware_install_vm.py
index df7353ec7..37f0db877 100644
--- a/os/tests/hardware_install_vm.py
+++ b/os/tests/hardware_install_vm.py
@@ -1,7 +1,6 @@
#!/usr/bin/env python3
"""Validate optional hardware packages on the actual ISO and installed system."""
import argparse
-import base64
import hashlib
import json
import os
@@ -10,6 +9,7 @@ import re
import shlex
import subprocess
import time
+from footprint_vm import copy_file
from vm import VM, check_graphical_keyboard
@@ -18,10 +18,29 @@ def digest(path):
return hashlib.file_digest(handle, 'sha256').hexdigest()
+def candidate_record(path):
+ """Record a committed candidate; never label working edits as that commit."""
+ if path.is_symlink():
+ raise ValueError('The candidate must be a regular tracked file.')
+ path = path.resolve()
+ root = Path(subprocess.check_output(
+ ['git', '-C', str(path.parent), 'rev-parse', '--show-toplevel'], text=True).strip())
+ relative = str(path.relative_to(root))
+ source = subprocess.check_output(['git', '-C', str(root), 'rev-parse', 'HEAD'], text=True).strip()
+ committed = subprocess.check_output(['git', '-C', str(root), 'show', source + ':' + relative])
+ data = path.read_bytes()
+ if data != committed:
+ raise ValueError('Commit the candidate before native validation.')
+ return {'source_commit': source, 'path': relative, 'bytes': len(data),
+ 'sha256': hashlib.sha256(data).hexdigest()}
+
+
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--iso', required=True, type=Path)
parser.add_argument('--output', type=Path, default=Path('os/test-results/hardware-install'))
+ parser.add_argument('--candidate-hardware', type=Path,
+ help='Test a committed hardware.py over the verified image; retain its hash and source separately')
args = parser.parse_args()
if not os.access('/dev/kvm', os.R_OK | os.W_OK):
parser.error('Native x86 KVM is required')
@@ -37,6 +56,8 @@ def main():
test_source_commit=subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip(),
memory_mib=1024, firmware='uefi', live_transport='usb',
limitations=['Synthetic PCI selection; physical Wi-Fi association and Mac sleep/wake remain unverified.'])
+ if args.candidate_hardware:
+ receipt['candidate_hardware'] = candidate_record(args.candidate_hardware)
vm = VM(folder, iso, 'uefi', 1024, 'usb')
try:
vm.start(live=True)
@@ -44,19 +65,24 @@ def main():
vm.shell_ready = True
vm.command('stty -echo; nmcli networking off')
script = Path(__file__).with_name('hardware_install_guest.py')
- encoded = base64.b64encode(script.read_bytes()).decode()
- vm.command('umask 077; : > /run/hardware-test.b64')
- # Serial canonical mode caps each line; no network is needed to stage it.
- for offset in range(0, len(encoded), 2400):
- vm.command('printf %s ' + shlex.quote(encoded[offset:offset + 2400]) + ' >> /run/hardware-test.b64')
- vm.command('base64 -d /run/hardware-test.b64 > /run/hardware-test.py')
+ # Transfers use the private serial console, with networking still off.
+ vm.command('umask 077')
+ copy_file(vm, script.read_bytes(), '/run/hardware-test.py')
+ command = ['python3', '/run/hardware-test.py']
+ if args.candidate_hardware:
+ candidate = receipt['candidate_hardware']
+ copy_file(vm, args.candidate_hardware.read_bytes(), '/run/hardware-candidate.py')
+ command += ['--candidate-hardware', '/run/hardware-candidate.py',
+ '--candidate-sha256', candidate['sha256']]
receipt['guest_fixture_sha256'] = digest(script)
- output, _ = vm.command('python3 /run/hardware-test.py', timeout=1200)
+ output, _ = vm.command(shlex.join(command), timeout=1200)
(folder / 'installation.log').write_text(output)
match = re.search(r'HN_HARDWARE_RESULT=(\{[^\r\n]+\})', output)
assert match, 'Offline hardware acceptance receipt is missing'
receipt['installation'] = json.loads(match.group(1))
assert receipt['installation']['status'] == 'passed'
+ if args.candidate_hardware:
+ assert receipt['installation']['hardware_sha256'] == candidate['sha256']
vm.screenshot('01-live-install-complete')
vm.command('sync')
vm.stop()
@@ -65,6 +91,9 @@ def main():
receipt['keyboard'] = check_graphical_keyboard(vm, 'optional-wifi-installed')
vm.command('printf %s ' + shlex.quote(config['password'] + '\n') + ' | sudo -S true')
vm.command('sudo nmcli networking off')
+ installed_hardware = vm.read_file('/usr/lib/harness-os/hardware.py')
+ receipt['installed_hardware_sha256'] = hashlib.sha256(installed_hardware).hexdigest()
+ assert receipt['installed_hardware_sha256'] == receipt['installation']['hardware_sha256'], 'Installed hardware policy differs'
vm.command('test ! -e /usr/share/harness-os/hardware/broadcom && test ! -e /etc/harness-live')
output, _ = vm.command('pacman -Q broadcom-wl-dkms dkms gcc linux-lts-headers; dkms status; harness hardware')
(folder / 'installed-hardware.txt').write_text(output)
diff --git a/os/tests/test_arm_updates.py b/os/tests/test_arm_updates.py
new file mode 100644
index 000000000..90c5fa58a
--- /dev/null
+++ b/os/tests/test_arm_updates.py
@@ -0,0 +1,159 @@
+"""Reject mislabeled/corrupted private ARM updates before starting a VM."""
+import copy
+import json
+from pathlib import Path
+import tempfile
+import unittest
+
+from arm_boot import digest
+from arm_update_vm import update_identity
+
+
+class ARMUpdateInputs(unittest.TestCase):
+ def setUp(self):
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = Path(temporary.name)
+ self.folder = self.root / 'updates'
+ self.folder.mkdir()
+ # Format-validation fixture only; this is deliberately not executable.
+ binary = bytearray(64)
+ binary[:7] = b'\x7fELF\x02\x01\x01'
+ binary[18:20] = (183).to_bytes(2, 'little')
+ (self.folder / 'harness-tui').write_bytes(binary)
+ for name in ['cli.mjs', 'notify.mjs', 'cli-current.mjs']:
+ (self.folder / name).write_text('format fixture ' + name)
+ base_url = 'http://127.0.0.1:19447/'
+
+ def ref(name):
+ path = self.folder / name
+ return {'url': base_url + name, 'sha256': digest(path), 'size': path.stat().st_size}
+
+ documents = {
+ 'hn.json': {'version': '999.0.1', 'builds': {'linux-arm64': ref('harness-tui')}},
+ 'cli.json': {'cli': {'version': '999.0.1', 'cli': ref('cli.mjs'), 'notify': ref('notify.mjs')}},
+ 'cli-current.json': {'cli': {'version': '0.0.1', 'cli': ref('cli-current.mjs'), 'notify': ref('notify.mjs')}},
+ 'cli-ancestor.json': {'cli': {'version': '0.3.58', 'cli': ref('cli.mjs'), 'notify': ref('notify.mjs')}},
+ 'feeds-ancestor.json': {'cli': base_url + 'cli-ancestor.json'},
+ 'feeds-hn.json': {'hn': base_url + 'hn.json', 'cli': base_url + 'cli-current.json'},
+ 'feeds-both.json': {'hn': base_url + 'hn.json', 'cli': base_url + 'cli.json'},
+ }
+ for name, document in documents.items():
+ (self.folder / name).write_text(json.dumps(document))
+ self.info = {'status': 'prepared', 'published': False, 'source_commit': 'a' * 40,
+ 'architecture': 'aarch64', 'target': 'aarch64-unknown-linux-musl',
+ 'version': '999.0.1',
+ 'runtime': {'versions': {'cli': '0.0.1'},
+ 'release_baselines': {'cli': {'version': '0.3.58'}}},
+ 'files': {p.name: digest(p) for p in self.folder.iterdir()}}
+ self.save()
+
+ def save(self):
+ (self.folder / 'fixture.json').write_text(json.dumps(self.info))
+
+ def test_retains_the_actual_producer_source(self):
+ self.assertEqual(update_identity(self.folder, 'a' * 40)['source_commit'], 'a' * 40)
+ with self.assertRaisesRegex(ValueError, 'exact-source'):
+ update_identity(self.folder, 'b' * 40)
+
+ def test_rejects_published_or_wrong_architecture_inputs(self):
+ for key, wrong in [('published', True), ('architecture', 'x86_64'),
+ ('target', 'x86_64-unknown-linux-musl'), ('status', 'passed')]:
+ original = self.info[key]
+ self.info[key] = wrong
+ self.save()
+ with self.subTest(key=key), self.assertRaisesRegex(ValueError, 'native ARM'):
+ update_identity(self.folder, 'a' * 40)
+ self.info[key] = original
+
+ def test_corruption_and_symlinks_do_not_borrow_checksums(self):
+ path = self.folder / 'cli.mjs'
+ original = path.read_bytes()
+ path.write_bytes(b'changed')
+ with self.assertRaisesRegex(ValueError, 'checksum mismatch'):
+ update_identity(self.folder, 'a' * 40)
+ target = self.root / 'elsewhere'
+ target.write_bytes(original)
+ path.unlink()
+ path.symlink_to(target)
+ with self.assertRaisesRegex(ValueError, 'checksum mismatch'):
+ update_identity(self.folder, 'a' * 40)
+
+ def test_rejects_other_file_names_before_resolving_them(self):
+ self.info['files']['../elsewhere'] = self.info['files'].pop('cli.mjs')
+ self.save()
+ with self.assertRaisesRegex(ValueError, 'incomplete'):
+ update_identity(self.folder, 'a' * 40)
+
+ def test_unmanifested_files_directories_and_symlinks_are_not_served(self):
+ path = self.folder / 'unverified'
+ for kind in ['file', 'directory', 'symlink']:
+ if kind == 'file':
+ path.write_text('must not be served')
+ elif kind == 'directory':
+ path.mkdir()
+ else:
+ path.symlink_to(self.root / 'not-an-artifact')
+ with self.subTest(kind=kind), self.assertRaisesRegex(ValueError, 'unverified entries'):
+ update_identity(self.folder, 'a' * 40)
+ path.rmdir() if kind == 'directory' else path.unlink()
+
+ def test_matching_outer_hash_does_not_allow_unbound_release_or_feed_references(self):
+ wrong_notify = json.loads((self.folder / 'cli.json').read_text())['cli']['cli']
+ changes = [
+ ('hn.json', ('version',), '1.2.3'),
+ ('hn.json', ('builds', 'linux-arm64', 'url'), 'https://example.test/another-hn'),
+ ('hn.json', ('builds', 'linux-arm64', 'sha256'), 'f' * 64),
+ ('hn.json', ('builds', 'linux-arm64', 'size'), 999),
+ ('cli.json', ('cli', 'notify'), wrong_notify),
+ ('cli-current.json', ('cli', 'version'), '999.0.1'),
+ ('cli-ancestor.json', ('cli', 'version'), '999.0.1'),
+ ('feeds-ancestor.json', ('cli',), 'http://127.0.0.1:19447/cli.json'),
+ ('feeds-hn.json', ('hn',), 'http://127.0.0.1:19447/cli.json'),
+ ('feeds-both.json', ('cli',), 'https://example.test/cli.json'),
+ ]
+ for name, keys, value in changes:
+ path = self.folder / name
+ original = path.read_bytes()
+ document = copy.deepcopy(json.loads(original))
+ target = document
+ for key in keys[:-1]:
+ target = target[key]
+ target[keys[-1]] = value
+ path.write_text(json.dumps(document))
+ self.info['files'][name] = digest(path)
+ self.save()
+ with self.subTest(name=name, keys=keys), self.assertRaisesRegex(ValueError, 'verified local assets'):
+ update_identity(self.folder, 'a' * 40)
+ path.write_bytes(original)
+ self.info['files'][name] = digest(path)
+ self.save()
+
+ def test_baseline_versions_are_required_for_current_and_ancestor_feeds(self):
+ self.info.pop('runtime')
+ self.save()
+ with self.assertRaisesRegex(ValueError, 'Missing original CLI versions'):
+ update_identity(self.folder, 'a' * 40)
+
+ def test_elf_and_release_entry_must_both_be_arm(self):
+ path = self.folder / 'harness-tui'
+ original = path.read_bytes()
+ wrong = bytearray(original)
+ wrong[18:20] = (62).to_bytes(2, 'little')
+ path.write_bytes(wrong)
+ self.info['files'][path.name] = digest(path)
+ self.save()
+ with self.assertRaisesRegex(ValueError, 'native ARM64 ELF'):
+ update_identity(self.folder, 'a' * 40)
+ path.write_bytes(original)
+ self.info['files'][path.name] = digest(path)
+ manifest = self.folder / 'hn.json'
+ manifest.write_text(json.dumps({'builds': {'linux-x64': {}}}))
+ self.info['files'][manifest.name] = digest(manifest)
+ self.save()
+ with self.assertRaisesRegex(ValueError, 'linux-arm64 release'):
+ update_identity(self.folder, 'a' * 40)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/os/tests/test_hardware.py b/os/tests/test_hardware.py
index 1366229d9..25eefa313 100644
--- a/os/tests/test_hardware.py
+++ b/os/tests/test_hardware.py
@@ -19,12 +19,12 @@ class HardwarePolicy(unittest.TestCase):
self.root = Path(self.temp.name)
self.sysfs = self.root / 'sys'
- def device(self, address='0000:03:00.0', device='43a0', driver=None, wireless=False, kind='028000'):
+ def device(self, address='0000:03:00.0', device='43a0', driver=None, wireless=False, kind='028000', override='(null)'):
path = self.sysfs / 'bus/pci/devices' / address
path.mkdir(parents=True)
for name, value in [('vendor', '14e4'), ('device', device), ('class', kind)]:
(path / name).write_text('0x' + value)
- (path / 'driver_override').write_text('(null)\n')
+ (path / 'driver_override').write_text(override + '\n')
if driver:
bound = self.sysfs / 'bus/pci/drivers' / driver
bound.mkdir(parents=True, exist_ok=True)
@@ -68,6 +68,29 @@ class HardwarePolicy(unittest.TestCase):
self.assertEqual([d['address'] for d in hardware.pci_devices(self.sysfs) if hardware.needs_broadcom(d)],
['0000:03:00.0', '0000:04:00.0'])
+ def test_explicit_assignment_is_preserved_before_loading_or_unbinding(self):
+ for index, (driver, override) in enumerate([
+ ('vfio-pci', '(null)'), ('pci-stub', '(null)'),
+ ('another-driver', '(null)'), (None, 'vfio-pci'),
+ (None, 'none'), ('bcma-pci-bridge', 'bcma-pci-bridge'),
+ ('wl', 'pci-stub')]):
+ path = self.device(address=f'0000:{index + 3:02x}:00.0', driver=driver, override=override)
+ with self.subTest(driver=driver, override=override), patch.object(hardware, 'run') as run:
+ device = next(d for d in hardware.pci_devices(self.sysfs) if d['address'] == path.name)
+ self.assertFalse(hardware.needs_broadcom(device))
+ self.assertEqual(hardware.activate(path.name, self.sysfs)['status'], 'unchanged')
+ run.assert_not_called()
+ self.assertEqual((path / 'driver_override').read_text(), override + '\n')
+ if driver:
+ self.assertEqual((path / 'driver/unbind').read_text(), '')
+
+ def test_ordinary_and_wl_overrides_retain_offline_driver_selection(self):
+ for index, override in enumerate(['(null)', '', 'wl']):
+ self.device(address=f'0000:{index + 3:02x}:00.0', override=override)
+ devices = hardware.pci_devices(self.sysfs)
+ self.assertTrue(all(hardware.needs_broadcom(device) for device in devices))
+ self.assertEqual([device['driver_override'] for device in devices], [None, None, 'wl'])
+
def test_damaged_module_is_rejected_before_unbinding(self):
device = self.device(driver='bcma-pci-bridge')
bundle = self.bundle()
@@ -126,6 +149,21 @@ class HardwarePolicy(unittest.TestCase):
self.assertTrue(keep.is_file())
self.assertTrue((target / 'etc/harness-live').exists())
+ def test_assigned_radio_does_not_install_optional_driver_or_compiler(self):
+ self.device(driver='vfio-pci')
+ self.device(address='0000:04:00.0', override='none')
+ target = self.root / 'target'
+ (target / 'etc').mkdir(parents=True)
+ (target / 'etc/harness-live').touch()
+ folder = self.bundle(target / hardware.BUNDLE.relative_to('/'))
+ with patch.object(hardware.Path, 'is_mount', return_value=True), \
+ patch.object(hardware, 'run') as run, patch.object(hardware, 'bundle_manifest') as manifest:
+ result = hardware.configure_install(target, hardware.pci_devices(self.sysfs))
+ self.assertEqual(result, {'drivers': [], 'devices': []})
+ run.assert_not_called()
+ manifest.assert_not_called()
+ self.assertFalse(folder.exists())
+
def test_dependency_mismatch_stops_before_package_transaction(self):
self.device()
target = self.root / 'target'
diff --git a/os/tests/test_hardware_fixture.py b/os/tests/test_hardware_fixture.py
new file mode 100644
index 000000000..b815556d8
--- /dev/null
+++ b/os/tests/test_hardware_fixture.py
@@ -0,0 +1,72 @@
+"""Keep candidate hardware evidence tied to the bytes actually exercised."""
+import hashlib
+from pathlib import Path
+import stat
+import subprocess
+import tempfile
+import unittest
+
+from hardware_install_guest import apply_candidate, assigned_devices, load
+from hardware_install_vm import candidate_record
+
+
+class HardwareCandidate(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.root = Path(self.temp.name).resolve()
+ self.candidate = self.root / 'hardware.py'
+ self.candidate.write_text('CANDIDATE = True\n')
+ for args in [('init', '-q'), ('add', 'hardware.py'),
+ ('-c', 'user.name=Fixture', '-c', '[email protected]',
+ '-c', 'commit.gpgsign=false', '-c', 'core.hooksPath=/dev/null',
+ 'commit', '-qm', 'candidate')]:
+ subprocess.run(['git', '-C', str(self.root), *args], check=True, capture_output=True, timeout=10)
+
+ def test_committed_source_matches_staged_and_installed_bytes(self):
+ record = candidate_record(self.candidate)
+ self.assertEqual(record['source_commit'], subprocess.check_output(
+ ['git', '-C', str(self.root), 'rev-parse', 'HEAD'], text=True).strip())
+ self.assertEqual(record['path'], 'hardware.py')
+ self.assertEqual(record['bytes'], len(self.candidate.read_bytes()))
+ self.assertEqual(record['sha256'], hashlib.sha256(self.candidate.read_bytes()).hexdigest())
+ live = self.root / 'live.py'
+ installed = self.root / 'installed.py'
+ for source, destination in [(self.candidate, live), (live, installed)]:
+ self.assertEqual(apply_candidate(source, destination, record['sha256']), record['sha256'])
+ self.assertEqual(destination.read_bytes(), self.candidate.read_bytes())
+ self.assertEqual(stat.S_IMODE(destination.stat().st_mode), 0o755)
+
+ def test_dirty_or_symlinked_candidate_cannot_borrow_commit_identity(self):
+ self.candidate.write_text('CANDIDATE = False\n')
+ with self.assertRaisesRegex(ValueError, 'Commit the candidate'):
+ candidate_record(self.candidate)
+ link = self.root / 'linked.py'
+ link.symlink_to(self.candidate)
+ with self.assertRaisesRegex(ValueError, 'regular tracked'):
+ candidate_record(link)
+
+ def test_changed_transfer_is_rejected_before_replacing_destination(self):
+ record = candidate_record(self.candidate)
+ self.candidate.write_text('MODIFIED_AFTER_RECORD = True\n')
+ destination = self.root / 'installed.py'
+ destination.write_text('ORIGINAL = True\n')
+ with self.assertRaisesRegex(ValueError, 'checksum mismatch'):
+ apply_candidate(self.candidate, destination, record['sha256'])
+ self.assertEqual(destination.read_text(), 'ORIGINAL = True\n')
+
+
+class NativeAssignmentFixture(unittest.TestCase):
+ def test_exact_supported_radio_assignment_cases_use_private_sysfs(self):
+ hardware = load('hardware_policy_fixture', Path(__file__).resolve().parents[1] / 'hardware.py')
+ original_run = hardware.run
+ with tempfile.TemporaryDirectory() as directory:
+ devices = assigned_devices(hardware, Path(directory))
+ self.assertEqual(len(devices), 3)
+ self.assertEqual({d['id'] for d in devices}, {'14e4:43a0'})
+ self.assertTrue(all(not hardware.needs_broadcom(d) for d in devices))
+ self.assertIs(hardware.run, original_run)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/os/tests/test_live_update.py b/os/tests/test_live_update.py
index d01a0b803..b89086458 100644
--- a/os/tests/test_live_update.py
+++ b/os/tests/test_live_update.py
@@ -4,6 +4,7 @@ import fcntl
import importlib.util
import json
from pathlib import Path
+import struct
import subprocess
import tempfile
import unittest
@@ -14,6 +15,12 @@ update = importlib.util.module_from_spec(spec)
spec.loader.exec_module(update)
+def elf_fixture(machine=62, payload=b''):
+ """A synthetic ELF header; version execution is stubbed in staging tests."""
+ return struct.pack('<16sHHIQQQIHHHHHH', b'\x7fELF\x02\x01\x01' + b'\0' * 9,
+ 2, machine, 1, 0, 64, 0, 0, 64, 56, 0, 0, 0, 0) + payload
+
+
class FastUpdates(unittest.TestCase):
def setUp(self):
temporary = tempfile.TemporaryDirectory()
@@ -24,12 +31,15 @@ class FastUpdates(unittest.TestCase):
self.base.write_text('{"source_commit":"initial"}\n')
self.bundled.mkdir()
for name in update.FILES:
- (self.bundled / name).write_bytes(('old ' + name).encode())
+ data = ('old ' + name).encode()
+ (self.bundled / name).write_bytes(elf_fixture(payload=data) if name == 'harness-tui' else data)
self.patches = [patch.object(update, 'STATE', self.state), patch.object(update, 'BUNDLED', self.bundled),
patch.object(update, 'BASE_ID', self.base),
patch.object(update, 'BOOT_ID', self.root / 'boot-id'),
patch.object(update, 'RESTART_REQUIRED', self.root / 'restart-required'),
patch.object(update, 'SYSTEM_LOCK', self.root / 'system.lock'),
+ patch.object(update.platform, 'system', return_value='Linux'),
+ patch.object(update.platform, 'machine', return_value='x86_64'),
patch.object(update, 'check_system', return_value={}),
patch.object(update, 'screen_ready'),
patch.object(update, 'capture_view', return_value=None),
@@ -40,15 +50,16 @@ class FastUpdates(unittest.TestCase):
update.BOOT_ID.write_text('first-boot')
def versions(self, folder):
- return {component: '1.1.0' if (folder / name).read_bytes().startswith(b'new') else '1.0.0'
+ return {component: '1.1.0' if (folder / name).read_bytes().endswith(('new ' + name).encode()) else '1.0.0'
for component, name in [('hn', 'harness-tui'), ('cli', 'cli.mjs')]}
- def feed(self, fail=None):
+ def feed(self, fail=None, target='linux-x64', machine=62):
assets = {name: ('new ' + name).encode() for name in update.FILES}
+ assets['harness-tui'] = elf_fixture(machine, assets['harness-tui'])
refs = {name: dict(url='https://example.test/' + name, sha256=hashlib.sha256(data).hexdigest(), size=len(data))
for name, data in assets.items()}
manifests = {
- update.FEEDS['hn']: json.dumps(dict(version='1.1.0', builds={'linux-x64': refs['harness-tui']})).encode(),
+ update.FEEDS['hn']: json.dumps(dict(version='1.1.0', builds={target: refs['harness-tui']})).encode(),
update.FEEDS['cli']: json.dumps(dict(cli=dict(version='1.1.0', cli=refs['cli.mjs'], notify=refs['notify.mjs']))).encode(),
}
def fetch(url, limit):
@@ -74,7 +85,7 @@ class FastUpdates(unittest.TestCase):
self.assertEqual(record['versions'], {'hn': '1.1.0', 'cli': '1.1.0'})
self.assertEqual(update.selected(), self.bundled)
restart.assert_not_called()
- self.assertEqual((self.bundled / 'harness-tui').read_bytes(), b'old harness-tui')
+ self.assertEqual((self.bundled / 'harness-tui').read_bytes(), elf_fixture(payload=b'old harness-tui'))
self.assertTrue(update.check())
self.assertEqual(update.prepared(), target)
self.assertEqual(len(list((self.state / 'builds').iterdir())), 1)
@@ -111,6 +122,49 @@ class FastUpdates(unittest.TestCase):
self.assertEqual(update.verify(update.prepared())['versions'], {'hn': '1.0.0', 'cli': '1.1.0'})
self.assertEqual(update.selected(), self.bundled)
+ def test_arm_stages_native_hn_and_cli_without_activation(self):
+ (self.bundled / 'harness-tui').write_bytes(elf_fixture(183, b'old harness-tui'))
+ with patch.object(update.platform, 'machine', return_value='aarch64'), self.feed(target='linux-arm64', machine=183), patch.object(update, 'restart') as restart:
+ self.assertTrue(update.check())
+ self.assertEqual(update.verify(update.prepared())['versions'], {'hn': '1.1.0', 'cli': '1.1.0'})
+ self.assertEqual((update.prepared() / 'harness-tui').read_bytes(), elf_fixture(183, b'new harness-tui'))
+ self.assertEqual(update.selected(), self.bundled)
+ restart.assert_not_called()
+
+ def test_missing_arm_release_keeps_hn_but_allows_independent_cli(self):
+ original = elf_fixture(183, b'old harness-tui')
+ (self.bundled / 'harness-tui').write_bytes(original)
+ with patch.object(update.platform, 'machine', return_value='aarch64'), self.feed() as fetch:
+ self.assertTrue(update.check())
+ self.assertEqual(update.verify(update.prepared())['versions'], {'hn': '1.0.0', 'cli': '1.1.0'})
+ self.assertEqual((update.prepared() / 'harness-tui').read_bytes(), original)
+ self.assertNotIn('https://example.test/harness-tui', [call.args[0] for call in fetch.call_args_list])
+ self.assertIn('No hn build is available for linux-arm64', str(update.read(self.state / 'check.json')['errors']))
+ self.assertEqual(update.selected(), self.bundled)
+
+ def test_wrong_architecture_with_valid_checksum_keeps_hn_but_allows_cli(self):
+ original = elf_fixture(183, b'old harness-tui')
+ (self.bundled / 'harness-tui').write_bytes(original)
+ # The manifest is correctly named and checksummed, but the payload is x86.
+ with patch.object(update.platform, 'machine', return_value='aarch64'), self.feed(target='linux-arm64'):
+ self.assertTrue(update.check())
+ self.assertEqual(update.verify(update.prepared())['versions'], {'hn': '1.0.0', 'cli': '1.1.0'})
+ self.assertEqual((update.prepared() / 'harness-tui').read_bytes(), original)
+ self.assertIn('does not match this computer (linux-arm64)', str(update.read(self.state / 'check.json')['errors']))
+ self.assertEqual(update.selected(), self.bundled)
+
+ def test_unusable_hn_only_feed_does_not_prepare_or_activate_an_update(self):
+ (self.bundled / 'harness-tui').write_bytes(elf_fixture(183, b'old harness-tui'))
+ for target in ['linux-x64', 'linux-arm64']:
+ # The ARM entry, when present, deliberately contains an x86 binary.
+ with (self.subTest(target=target), patch.object(update.platform, 'machine', return_value='aarch64'),
+ self.feed(target=target), patch.object(update, 'restart') as restart):
+ with self.assertRaisesRegex(ValueError, 'Could not check for updates'):
+ update.check(feeds={'hn': update.FEEDS['hn']})
+ self.assertIsNone(update.prepared())
+ self.assertEqual(update.selected(), self.bundled)
+ restart.assert_not_called()
+
def test_staged_file_changed_after_download_is_rejected_before_selection(self):
with self.feed():
update.check()
@@ -329,6 +383,95 @@ class FastUpdates(unittest.TestCase):
self.assertFalse((self.state / 'request.json').exists())
+class RuntimeArchitecture(unittest.TestCase):
+ def setUp(self):
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = Path(temporary.name)
+ for item in [patch.object(update.platform, 'system', return_value='Linux'),
+ patch.object(update.platform, 'machine', return_value='x86_64')]:
+ item.start()
+ self.addCleanup(item.stop)
+
+ def test_release_uses_exact_native_asset_when_both_architectures_exist(self):
+ refs = {key: {'url': f'https://example.test/{key}', 'sha256': str(index) * 64}
+ for index, key in enumerate(['linux-x64', 'linux-arm64'], 1)}
+ manifest = json.dumps({'version': '1.2.3', 'builds': refs}).encode()
+ for machine, key in [('x86_64', 'linux-x64'), ('aarch64', 'linux-arm64')]:
+ with self.subTest(machine=machine), patch.object(update.platform, 'machine', return_value=machine), patch.object(update, 'fetch', return_value=manifest):
+ self.assertEqual(update.release('https://example.test/feed', 'hn'),
+ ('1.2.3', {'harness-tui': refs[key]}))
+
+ def test_unsupported_platforms_never_fall_back_to_x86(self):
+ for system, machine in [('Linux', 'armv7l'), ('Linux', 'riscv64'), ('Darwin', 'arm64')]:
+ with self.subTest(system=system, machine=machine), patch.object(update.platform, 'system', return_value=system), patch.object(update.platform, 'machine', return_value=machine):
+ with self.assertRaisesRegex(ValueError, 'require x86-64 or ARM64 Linux'):
+ update.runtime_platform()
+
+ def test_matching_elf_version_probes_run_on_each_native_platform(self):
+ for machine, elf_machine, elf_type in [('x86_64', 62, 2), ('aarch64', 183, 2), ('aarch64', 183, 3)]:
+ header = bytearray(elf_fixture(elf_machine))
+ header[16:18] = elf_type.to_bytes(2, 'little')
+ (self.root / 'harness-tui').write_bytes(header)
+ with (self.subTest(machine=machine, elf_type=elf_type),
+ patch.object(update.platform, 'machine', return_value=machine),
+ patch.object(update, 'run', side_effect=['hn 1.2.3', '2.3.4']) as run):
+ self.assertEqual(update.versions(self.root), {'hn': '1.2.3', 'cli': '2.3.4'})
+ self.assertEqual(run.call_args_list[0].args, (self.root / 'harness-tui', '--version'))
+
+ def test_wrong_or_malformed_binary_is_rejected_before_any_execution(self):
+ cases = {'x86-on-arm': elf_fixture(), 'script': b'#!/bin/sh\nprintf "hn 1.2.3\\n"\n',
+ 'truncated': elf_fixture(183)[:63]}
+ for name, offset, value in [('class32', 4, 1), ('big-endian', 5, 2), ('ident-version', 6, 0),
+ ('elf-version', 20, 0), ('core-dump', 16, 4)]:
+ data = bytearray(elf_fixture(183))
+ data[offset] = value
+ cases[name] = bytes(data)
+ with patch.object(update.platform, 'machine', return_value='aarch64'):
+ for name, data in cases.items():
+ (self.root / 'harness-tui').write_bytes(data)
+ with self.subTest(case=name), patch.object(update, 'run') as run:
+ with self.assertRaisesRegex(ValueError, 'does not match this computer'):
+ update.versions(self.root)
+ run.assert_not_called()
+
+ def record(self, folder, machine):
+ folder.mkdir(parents=True)
+ for name in update.FILES:
+ (folder / name).write_bytes(elf_fixture(machine) if name == 'harness-tui' else b'fixture')
+ # Older x86 prepared updates have no architecture field; the actual ELF
+ # remains authoritative without invalidating their on-disk record format.
+ record = {'versions': {'hn': '1.2.3', 'cli': '2.3.4'}, 'files': {
+ name: {'sha256': update.digest(folder / name), 'bytes': (folder / name).stat().st_size}
+ for name in update.FILES}}
+ update.write(folder / 'release.json', record)
+ return record
+
+ def test_existing_x86_prepared_record_still_verifies(self):
+ folder = self.root / 'build'
+ record = self.record(folder, 62)
+ with patch.object(update, 'run', side_effect=['hn 1.2.3', '2.3.4']):
+ self.assertEqual(update.verify(folder), record)
+
+ def test_wrong_architecture_with_matching_manifest_cannot_be_activated(self):
+ folder = self.root / 'state/builds' / ('a' * 64)
+ self.record(folder, 62)
+ base = self.root / 'base.json'
+ base.write_text('{}\n')
+ (folder / 'base.json').write_bytes(base.read_bytes())
+ with (patch.object(update.platform, 'machine', return_value='aarch64'),
+ patch.object(update, 'STATE', self.root / 'state'), patch.object(update, 'BASE_ID', base),
+ patch.object(update, 'SYSTEM_LOCK', self.root / 'lock'),
+ patch.object(update, 'RESTART_REQUIRED', self.root / 'restart'),
+ patch.object(update, 'prepared', return_value=folder), patch.object(update, 'run') as run,
+ patch.object(update, 'select') as select, patch.object(update, 'restart') as restart):
+ with self.assertRaisesRegex(ValueError, 'does not match this computer'):
+ update.apply()
+ run.assert_not_called()
+ select.assert_not_called()
+ restart.assert_not_called()
+
+
class ScreenSelection(unittest.TestCase):
def test_capture_chooses_os_screen_among_other_clients_and_rejects_bad_ids(self):
rows = '201\t$1\t@2\t%3\t/dev/pts/8\n202\t$4\t@5\t%6\t/dev/pts/9'
diff --git a/os/tests/test_network.py b/os/tests/test_network.py
index 0a7fc7f5b..409d84fc1 100644
--- a/os/tests/test_network.py
+++ b/os/tests/test_network.py
@@ -48,6 +48,29 @@ class Network(unittest.TestCase):
self.assertEqual(found[0]['signal'], 88)
self.assertEqual(found[0]['bssid'], 'cc:dd')
+ def test_opening_wifi_uses_recent_scan_when_forced_rescan_would_stall(self):
+ def command(*args, **kwargs):
+ if args[-2:] == ('--rescan', 'yes'):
+ raise subprocess.TimeoutExpired('nmcli', 13)
+ return result(output='a\\:network:88:WPA2:wlan0:cc\\:dd:*\n')
+ with patch.object(network, 'nmcli', side_effect=command):
+ found = network.scan()
+ self.assertEqual(found[0]['ssid'], WIFI['ssid'])
+ self.assertTrue(found[0]['active'])
+
+ def test_explicit_rescan_still_requests_a_new_radio_scan(self):
+ real_scan = network.scan
+ screen, page = self.page(['r', '\x1b'], first_use=False)
+ modes = []
+ def command(*args, **kwargs):
+ if '--rescan' in args:
+ modes.append(args[args.index('--rescan') + 1])
+ return result(output='a\\:network:88:WPA2:wlan0:cc\\:dd:*\n')
+ return result()
+ with patch.object(network, 'scan', side_effect=real_scan), patch.object(network, 'nmcli', side_effect=command):
+ self.assertEqual(page.run(), 1)
+ self.assertEqual(modes, ['auto', 'yes'])
+
def test_password_is_only_passed_on_stdin_and_only_success_enables_reconnect(self):
calls = []
def run(*args, **kwargs):
@@ -143,6 +166,50 @@ class Network(unittest.TestCase):
self.assertEqual(page.run(), 1)
password.assert_not_called()
+ def test_selected_connected_row_reconnects_when_link_dropped_after_scan(self):
+ screen, page = self.page(['\n'], first_use=False)
+ active = dict(WIFI, active=True)
+ with patch.object(network, 'scan', side_effect=[[active], [WIFI]]) as scan, \
+ patch.object(network, 'connect', return_value=True) as connect:
+ self.assertEqual(page.run(), 0)
+ connect.assert_called_once_with(active)
+ self.assertEqual(scan.call_args.kwargs, {'rescan': False})
+
+ def test_selecting_current_connection_does_not_interrupt_work(self):
+ screen, page = self.page(['\n'], first_use=False)
+ with patch.object(network, 'scan', return_value=[dict(WIFI, active=True)]) as scan, \
+ patch.object(network, 'connect') as connect:
+ self.assertEqual(page.run(), 0)
+ connect.assert_not_called()
+ self.assertEqual(scan.call_count, 2)
+ self.assertEqual(scan.call_args.kwargs, {'rescan': False})
+
+ def test_same_ssid_on_another_radio_is_not_the_selected_connection(self):
+ screen, page = self.page(['\n'], first_use=False)
+ active = dict(WIFI, active=True)
+ other = dict(active, device='wlan1')
+ with patch.object(network, 'scan', side_effect=[[active], [other]]), \
+ patch.object(network, 'connect', return_value=True) as connect:
+ self.assertEqual(page.run(), 0)
+ connect.assert_called_once_with(active)
+
+ def test_wifi_scan_error_does_not_hide_ethernet_or_keep_stale_rows(self):
+ screen, page = self.page([], first_use=False)
+ with patch.object(network, 'scan', side_effect=[[WIFI], ValueError('Could not scan Wi-Fi.')]):
+ page.refresh()
+ self.assertEqual(page.networks, [WIFI])
+ page.refresh()
+ self.assertEqual(page.networks, [])
+ self.assertEqual(page.wired, [['eth0', 'ethernet', 'disconnected']])
+ self.assertEqual(page.message, 'Could not scan Wi-Fi.')
+
+ def test_ethernet_is_usable_when_wifi_scan_fails(self):
+ screen, page = self.page([curses.KEY_DOWN, '\n'])
+ with patch.object(network, 'scan', side_effect=ValueError('Could not scan Wi-Fi.')), \
+ patch.object(network, 'nmcli', return_value=result()) as command:
+ self.assertEqual(page.run(), 0)
+ self.assertEqual(command.call_args.args, ('device', 'connect', 'eth0'))
+
def test_wide_and_control_characters_fit_the_terminal(self):
self.assertEqual(network.fit('網路123', 5), '網路1')
self.assertEqual(network.fit('a\x1b\tb', 6), 'a b ')
diff --git a/os/tests/test_update_fixture.py b/os/tests/test_update_fixture.py
new file mode 100644
index 000000000..ec1827a2d
--- /dev/null
+++ b/os/tests/test_update_fixture.py
@@ -0,0 +1,180 @@
+import copy
+import hashlib
+import importlib.util
+import json
+from pathlib import Path
+import struct
+import subprocess
+import tempfile
+import tomllib
+import unittest
+from unittest.mock import patch
+
+spec = importlib.util.spec_from_file_location('update_fixture', Path(__file__).with_name('build-update-fixture.py'))
+fixture = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(fixture)
+
+
+def elf(machine):
+ # This only tests format guards. CI builds and executes the actual runtime.
+ return struct.pack('<16sHHIQQQIHHHHHH', b'\x7fELF\x02\x01\x01' + b'\0' * 9,
+ 2, machine, 1, 0, 64, 0, 0, 64, 56, 0, 0, 0, 0)
+
+
+class FixtureContracts(unittest.TestCase):
+ def setUp(self):
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = Path(temporary.name)
+ self.versions = {'hn': '0.1.12', 'cli': '0.0.1'}
+ self.baselines = {'cli': {'version': '0.3.58', 'commit': 'b' * 40}}
+
+ def runtime(self, architecture):
+ folder = self.root / architecture
+ folder.mkdir()
+ for name in fixture.FILES:
+ (folder / name).write_bytes(elf(fixture.TARGETS[architecture][2]) if name == 'harness-tui' else name.encode())
+ record = {'source_commit': 'a' * 40, 'dirty': False, 'architecture': architecture,
+ 'target': architecture + '-unknown-linux-musl', 'versions': self.versions,
+ 'release_baselines': self.baselines, 'files': {
+ name: {'sha256': fixture.digest(folder / name), 'bytes': (folder / name).stat().st_size}
+ for name in fixture.FILES}}
+ self.write_record(folder, record)
+ return folder, record
+
+ def write_record(self, folder, record):
+ (folder / 'source.json').write_text(json.dumps(record))
+
+ def validate(self, folder, architecture='aarch64'):
+ return fixture.validate_runtime(folder, 'a' * 40, architecture, self.versions, self.baselines)
+
+ def test_accepts_complete_native_baseline_on_each_architecture(self):
+ for architecture in ['x86_64', 'aarch64']:
+ folder, record = self.runtime(architecture)
+ with self.subTest(architecture=architecture):
+ self.assertEqual(self.validate(folder, architecture), record)
+
+ def test_rejects_stale_dirty_cross_arch_or_changed_ancestry_before_building(self):
+ folder, original = self.runtime('aarch64')
+ changes = {'source_commit': 'c' * 40, 'dirty': True, 'architecture': 'x86_64',
+ 'target': 'x86_64-unknown-linux-musl', 'versions': {'hn': '0.1.11', 'cli': '0.0.1'},
+ 'release_baselines': {}, 'files': list(fixture.FILES)}
+ for key, value in changes.items():
+ modified = copy.deepcopy(original)
+ modified[key] = value
+ self.write_record(folder, modified)
+ with self.subTest(key=key), self.assertRaisesRegex(ValueError, 'exact clean source'):
+ self.validate(folder)
+
+ def test_rejects_truncated_tampered_missing_and_unexpected_runtime_files(self):
+ folder, original = self.runtime('aarch64')
+ cli = folder / 'cli.js'
+ for payload in [b'x', b'changed payload']:
+ cli.write_bytes(payload)
+ with self.subTest(payload=payload), self.assertRaisesRegex(ValueError, 'failed verification'):
+ self.validate(folder)
+ cli.unlink()
+ with self.assertRaisesRegex(ValueError, 'complete, unmodified'):
+ self.validate(folder)
+ cli.write_bytes(b'cli.js')
+ (folder / 'stale-binary').touch()
+ with self.assertRaisesRegex(ValueError, 'complete, unmodified'):
+ self.validate(folder)
+
+ def test_rejects_symlinked_artifacts_and_valid_hash_for_wrong_elf(self):
+ folder, original = self.runtime('aarch64')
+ binary = folder / 'harness-tui'
+ binary.unlink()
+ other = self.root / 'external-binary'
+ other.write_bytes(elf(183))
+ binary.symlink_to(other)
+ with self.assertRaisesRegex(ValueError, 'failed verification'):
+ self.validate(folder)
+ binary.unlink()
+ binary.write_bytes(elf(62))
+ original['files']['harness-tui']['sha256'] = fixture.digest(binary)
+ self.write_record(folder, original)
+ with self.assertRaisesRegex(ValueError, 'native Linux ELF'):
+ self.validate(folder)
+
+ def test_version_probe_cannot_accept_a_fake_executable_or_wrong_version(self):
+ binary = self.root / 'harness-tui'
+ binary.write_text('#!/bin/sh\necho "hn 999.0.1"\n')
+ with patch.object(fixture, 'command') as run:
+ with self.assertRaisesRegex(ValueError, 'native Linux ELF'):
+ fixture.probe_versions(self.root, 'aarch64', {'hn': fixture.VERSION, 'cli': fixture.VERSION}, 'cli.mjs')
+ run.assert_not_called()
+ binary.write_bytes(elf(183))
+ with patch.object(fixture, 'command', side_effect=['hn 0.1.12 (tmux 3.7c)', fixture.VERSION]):
+ with self.assertRaisesRegex(ValueError, 'expected versions'):
+ fixture.probe_versions(self.root, 'aarch64', {'hn': fixture.VERSION, 'cli': fixture.VERSION}, 'cli.mjs')
+
+ def test_architecture_metadata_checksums_and_existing_private_feed_contract(self):
+ for architecture, key in [('x86_64', 'linux-x64'), ('aarch64', 'linux-arm64')]:
+ folder = self.root / architecture
+ folder.mkdir()
+ for name in ['harness-tui', 'cli.mjs', 'notify.mjs', 'cli-current.mjs']:
+ (folder / name).write_bytes(name.encode())
+ fixture.write_manifests(folder, architecture, '0.0.1', '0.3.58')
+ hn = json.loads((folder / 'hn.json').read_text())
+ self.assertEqual(hn['version'], '999.0.1')
+ self.assertEqual(set(hn['builds']), {key})
+ documents = [hn['builds'], json.loads((folder / 'cli.json').read_text())['cli'],
+ json.loads((folder / 'cli-current.json').read_text())['cli']]
+ for document in documents:
+ for ref in document.values():
+ if isinstance(ref, dict):
+ self.assertTrue(ref['url'].startswith('http://127.0.0.1:19447/'))
+ data = (folder / ref['url'].rsplit('/', 1)[1]).read_bytes()
+ self.assertEqual(ref['sha256'], hashlib.sha256(data).hexdigest())
+ self.assertEqual(ref['size'], len(data))
+ self.assertEqual(json.loads((folder / 'cli-ancestor.json').read_text())['cli']['version'], '0.3.58')
+ for name in ['feeds-ancestor.json', 'feeds-hn.json', 'feeds-both.json']:
+ for url in json.loads((folder / name).read_text()).values():
+ self.assertTrue((folder / url.rsplit('/', 1)[1]).is_file())
+
+
+class SourceIsolation(unittest.TestCase):
+ def setUp(self):
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = Path(temporary.name)
+ self.source = self.root / 'source'
+ self.source.mkdir()
+ self.git('init', '-b', 'main')
+ (self.source / 'tui/src').mkdir(parents=True)
+ (self.source / 'tui/Cargo.toml').write_text('[package]\nname = "harness-tui"\nversion = "0.1.12"\n')
+ (self.source / 'tui/Cargo.lock').write_text('[[package]]\nname = "harness-tui"\nversion = "0.1.12"\n\n'
+ '[[package]]\nname = "dependency"\nversion = "1.0.0"\n')
+ (self.source / 'tui/src/main.rs').write_text('fn main() {}\n')
+ (self.source / '.gitignore').write_text('ignored.rs\n')
+ self.git('add', '.')
+ self.git('commit', '-m', 'baseline')
+
+ def git(self, *args):
+ return subprocess.check_output(['git', '-C', str(self.source), '-c', 'user.name=Fixture',
+ '-c', '[email protected]', '-c', 'core.hooksPath=/dev/null',
+ *args], text=True, stderr=subprocess.DEVNULL).strip()
+
+ def test_private_version_changes_only_tracked_temporary_source(self):
+ commit = fixture.clean_source(self.source)
+ (self.source / 'tui/src/ignored.rs').write_text('must not enter the fixture')
+ output = self.root / 'copy'
+ fixture.copy_tui(self.source, output)
+ self.assertFalse((output / 'src/ignored.rs').exists())
+ self.assertEqual(tomllib.loads((output / 'Cargo.toml').read_text())['package']['version'], '999.0.1')
+ packages = tomllib.loads((output / 'Cargo.lock').read_text())['package']
+ self.assertEqual({p['name']: p['version'] for p in packages}, {'harness-tui': '999.0.1', 'dependency': '1.0.0'})
+ self.assertEqual(tomllib.loads((self.source / 'tui/Cargo.toml').read_text())['package']['version'], '0.1.12')
+ self.assertEqual(fixture.clean_source(self.source), commit)
+
+ def test_dirty_and_untracked_source_cannot_be_mislabeled_clean(self):
+ tracked = self.source / 'tui/src/main.rs'
+ original = tracked.read_text()
+ tracked.write_text(original + '// changed\n')
+ with self.assertRaisesRegex(ValueError, 'Commit source changes'):
+ fixture.clean_source(self.source)
+ tracked.write_text(original)
+ (self.source / 'tui/src/untracked.rs').write_text('new source')
+ with self.assertRaisesRegex(ValueError, 'Commit source changes'):
+ fixture.clean_source(self.source)