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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
os: build a private Apple Silicon image from Fedora Asahi Minimal (#916)
Deedb89229a5c18
diff --git a/.github/workflows/os-asahi-image.yml b/.github/workflows/os-asahi-image.ymlnew file mode 100644index 000000000..9c66c97d5--- /dev/null+++ b/.github/workflows/os-asahi-image.yml@@ -0,0 +1,140 @@+name: Harness OS private Apple Silicon image++on:+ workflow_dispatch:+ inputs:+ package_run_id:+ description: 'Successful private Fedora session package workflow run'+ type: string+ required: true+ package_source:+ description: 'Exact source commit recorded in that producer run and RPM manifest'+ type: string+ required: true+ push:+ branches: ['os-polish/asahi-image']+ paths:+ - 'os/platforms/apple-silicon/**'+ - 'os/tools/asahi_image.py'+ - 'os/tests/asahi_image_check.py'+ - 'os/tests/test_asahi_image.py'+ - '.github/workflows/os-asahi-image.yml'++permissions:+ contents: read+ actions: read++concurrency:+ group: harness-asahi-image-${{ github.ref }}+ cancel-in-progress: false++jobs:+ image:+ runs-on: ubuntu-24.04-arm+ timeout-minutes: 60+ env:+ PACKAGE_RUN: ${{ inputs.package_run_id || '37473135750' }}+ PACKAGE_SOURCE: ${{ inputs.package_source || '4c554682e6f79f20f267084f066bb0c2ef3bfc5a' }}+ steps:+ - uses: actions/checkout@v7+ with:+ fetch-depth: 1+ - name: Verify the private package producer+ env:+ GH_TOKEN: ${{ github.token }}+ run: |+ [[ "$PACKAGE_RUN" =~ ^[0-9]+$ ]]+ [[ "$PACKAGE_SOURCE" =~ ^[a-f0-9]{40}$ ]]+ gh api "repos/$GITHUB_REPOSITORY/actions/runs/$PACKAGE_RUN" > "$RUNNER_TEMP/package-producer.json"+ python3 - "$RUNNER_TEMP/package-producer.json" <<'PY'+ import json, os, sys+ run = json.load(open(sys.argv[1]))+ assert run['head_sha'] == os.environ['PACKAGE_SOURCE']+ assert run['path'] == '.github/workflows/os-fedora-package.yml'+ assert run['status'] == 'completed' and run['conclusion'] == 'success'+ assert run['repository']['full_name'] == os.environ['GITHUB_REPOSITORY']+ PY+ - uses: actions/download-artifact@v6+ with:+ name: harness-fedora-package+ run-id: ${{ env.PACKAGE_RUN }}+ github-token: ${{ github.token }}+ path: os/work/asahi-package-input+ - name: Portable checks and native builder+ run: |+ make -C os check+ df -h . "$RUNNER_TEMP"+ sudo apt-get update -qq+ sudo apt-get install -y --no-install-recommends podman+ python3 - <<'PY' >> "$GITHUB_ENV"+ import json+ lock = json.load(open('os/platforms/apple-silicon/source.lock.json'))+ print('BUILDER_IMAGE=' + lock['builder_image'])+ print('UPSTREAM_REPO=' + lock['upstream']['repository'])+ print('UPSTREAM_BRANCH=' + lock['upstream']['branch'])+ print('UPSTREAM_COMMIT=' + lock['upstream']['commit'])+ PY+ - name: Fetch the reviewed Fedora Asahi description+ run: |+ git clone --branch "$UPSTREAM_BRANCH" "$UPSTREAM_REPO" os/work/asahi-upstream+ git -C os/work/asahi-upstream checkout --detach "$UPSTREAM_COMMIT"+ sudo podman pull --arch arm64 "$BUILDER_IMAGE"+ mkdir -p os/work/asahi-output+ sudo podman image inspect "$BUILDER_IMAGE" > os/work/asahi-output/builder-image.json+ cp "$RUNNER_TEMP/package-producer.json" os/work/asahi-output/+ - name: Build the private image with signed Fedora and Asahi packages+ run: |+ # KIWI needs newly created loop partition nodes from this disposable runner.+ sudo podman run --rm --privileged --arch arm64 \+ --mount type=bind,source=/dev,target=/dev \+ --mount "type=bind,source=$PWD,target=/source,readonly" \+ --mount "type=bind,source=$PWD/os/work/asahi-output,target=/output" \+ -e PACKAGE_SOURCE="$PACKAGE_SOURCE" "$BUILDER_IMAGE" /bin/bash -euo pipefail -c '+ manager=$(command -v dnf5 || command -v microdnf)+ "$manager" install -y --setopt=install_weak_deps=False --setopt=gpgcheck=True \+ python3 git rpm kiwi kiwi-systemdeps-disk-images distribution-gpg-keys \+ qemu-img libselinux-utils util-linux zstd+ python3 /source/os/tools/asahi_image.py \+ --upstream /source/os/work/asahi-upstream \+ --package /source/os/work/asahi-package-input/work/fedora-package-output/first \+ --package-source "$PACKAGE_SOURCE" --output /output/recipe+ kiwi-ng --debug --type=oem --profile=Harness system build \+ --description /output/recipe/description --target-dir /output/disk+ python3 /source/os/tests/asahi_image_check.py \+ --image /output/disk/Harness-Asahi.aarch64-0.0.0.raw \+ --identity /output/recipe/image-inputs.json --output /output/inspection+ zstd -T2 -3 /output/disk/Harness-Asahi.aarch64-0.0.0.raw -o /output/harness-asahi-private.raw.zst+ cd /output+ sha256sum harness-asahi-private.raw.zst > SHA256SUMS+ '+ - name: Retain image construction evidence+ if: always()+ uses: actions/upload-artifact@v6+ with:+ name: harness-asahi-image-evidence+ path: |+ os/work/asahi-output/builder-image.json+ os/work/asahi-output/package-producer.json+ os/work/asahi-output/recipe/image-inputs.json+ os/work/asahi-output/recipe/recipe-files.json+ os/work/asahi-output/recipe/description/COPYING+ os/work/asahi-output/disk/*.packages+ os/work/asahi-output/disk/*.changes+ os/work/asahi-output/disk/kiwi.result.json+ os/work/asahi-output/disk/build/image-root.log+ os/work/asahi-output/inspection/+ if-no-files-found: error+ retention-days: 7+ compression-level: 6+ - name: Retain the private disk only after inspection passes+ if: success()+ uses: actions/upload-artifact@v6+ with:+ name: harness-asahi-private-disk+ path: |+ os/work/asahi-output/harness-asahi-private.raw.zst+ os/work/asahi-output/SHA256SUMS+ os/work/asahi-output/recipe/image-inputs.json+ if-no-files-found: error+ retention-days: 3+ compression-level: 0diff --git a/os/platforms/apple-silicon/README.md b/os/platforms/apple-silicon/README.mdnew file mode 100644index 000000000..910f81116--- /dev/null+++ b/os/platforms/apple-silicon/README.md@@ -0,0 +1,53 @@+# Apple Silicon image work++The private image builder combines the pinned **Fedora Asahi Remix Minimal**+KIWI description with a separately verified Harness session RPM. It includes+hn, OpenCode with upstream defaults, terminal panes and the optional Chromium+browser. It selects no GNOME or KDE desktop profile.++This is image construction work, **not an installable Harness release**. First-boot+account setup, encryption, Fedora base-system updates/recovery and physical Apple+hardware acceptance remain required. The image currently retains Fedora's text+initial setup; it contains no pre-created user or known login password. Never+flash this raw disk over a Mac's disk or use the PC whole-disk installer on Apple+Silicon. No public installer metadata or download feed is generated.++## Maintained platform foundation++`source.lock.json` pins the upstream description commit/tree and native Fedora+builder image. Our `Harness` profile extends `Minimal`; it keeps Asahi's existing+4096-byte-sector EFI/ext4/Btrfs layout, kernel, m1n1, U-Boot, firmware integration,+first-boot platform services and SELinux policy. The small graphical session also+includes Asahi's audio configuration and speaker protection. Fedora package+signatures stay enabled. No Apple firmware is copied from a developer's Mac.++The Harness RPM is selected from a successful private package workflow by exact+source commit and SHA-256. Its dependencies are installed by KIWI from the signed+Fedora/Asahi repositories. A later, repository-disabled transaction installs only+that exact unsigned private RPM. No Desktop, TUI, CLI or daemon is built or+published by this workflow; the package carries its original runtime provenance.++Upstream image descriptions are GPL-3.0-or-later. Their `COPYING`, author metadata+and original platform files are retained in the generated recipe. The image keeps+Fedora's package identity for platform maintenance; this does not imply Fedora or+Asahi endorsement of Harness.++## Private build and evidence++Run **Harness OS private Apple Silicon image** with an existing successful+**Harness OS private Fedora package** run and its full producer commit. It builds+on native AArch64 Linux using Podman, then inspects the produced raw disk through+read-only loop mounts. Evidence includes the actual partition table, boot object+hashes, complete RPM inventory, exact Harness/OpenCode files, locked root account,+absence of fixture credentials/machine keys, and enforcing SELinux configuration.++The workflow retains a compressed private disk only after inspection passes.+That evidence proves image contents, not Apple boot, firmware extraction,+encryption, suspend, audio, Wi-Fi or recovery. Platform acceptance must use actual+hardware before a supported install is offered.++The intended installation must preserve macOS and Apple recovery, using the+space prepared by Asahi. The upstream prebuilt-image and UEFI-media paths are+described in the [distribution guidelines](https://asahilinux.org/docs/alt/policy/).+This build is the image foundation for that work; it does not invoke either+installer on the host.diff --git a/os/platforms/apple-silicon/configure.py b/os/platforms/apple-silicon/configure.pynew file mode 100644index 000000000..671e6d931--- /dev/null+++ b/os/platforms/apple-silicon/configure.py@@ -0,0 +1,71 @@+#!/usr/bin/python3+"""KIWI chroot hook; never run on a user's installed system."""+import hashlib+import json+import os+from pathlib import Path+import platform+import re+import shutil+import subprocess+++INPUT = Path('/var/tmp/harness-image-input')+++def digest(path):+ with path.open('rb') as stream:+ return hashlib.file_digest(stream, 'sha256').hexdigest()+++def require_build_environment():+ release = platform.freedesktop_os_release()+ context = {'enabled': os.environ.get('HARNESS_ASAHI_IMAGE_BUILD') == '1',+ 'uid': os.geteuid(), 'architecture': platform.machine(),+ 'kiwi': Path('/.kconfig').is_file(), 'id': release.get('ID'),+ 'release': release.get('VERSION_ID')}+ if context != {'enabled': True, 'uid': 0, 'architecture': 'aarch64', 'kiwi': True,+ 'id': 'fedora-asahi-remix', 'release': '44'}:+ raise RuntimeError('Run only in the native Fedora Asahi KIWI chroot: ' + json.dumps(context))+++def main():+ require_build_environment()+ identity = json.loads((INPUT / 'image.json').read_text())+ if identity.get('kind') != 'harness-asahi-image-construction' or identity.get('release_ready') is not False:+ raise ValueError('Missing private image construction identity.')+ manifest = identity['session_package']+ item = manifest['package']+ if not re.fullmatch(r'harness-os-session-[A-Za-z0-9.~+-]+\.aarch64\.rpm', item['name']):+ raise ValueError('Invalid session RPM name.')+ package = INPUT / item['name']+ if package.is_symlink() or package.stat().st_size != item['bytes'] or digest(package) != item['sha256']:+ raise ValueError('The declared session RPM has changed.')+ # The upstream recipe checks signatures for every Fedora/Asahi dependency.+ # Only this exact SHA-256-verified private RPM is unsigned. With all repos+ # disabled this transaction cannot resolve/download a different package.+ subprocess.run(['dnf5', '-y', '--disable-repo=*', '--setopt=localpkg_gpgcheck=False',+ 'install', str(package)], check=True)+ subprocess.run(['rpm', '-V', 'harness-os-session'], check=True)+ for name, expected in manifest['files'].items():+ path = Path('/') / name+ if path.is_symlink() or digest(path) != expected:+ raise ValueError('Installed session payload differs: ' + name)+ for name, expected in manifest['symlinks'].items():+ if os.readlink(Path('/') / name) != expected:+ raise ValueError('Installed session link differs: ' + name)+ Path('/etc/hostname').write_text('harness\n')+ Path('/usr/share/harness-os/image.json').write_text(json.dumps(identity, indent=2) + '\n')+ # No known-password fixture users, autologin or broad privilege grants.+ # Fedora's stock initial-setup remains until Harness first boot is integrated.+ accounts = [row.split(':') for row in Path('/etc/passwd').read_text().splitlines()]+ if any(1000 <= int(row[2]) < 65534 for row in accounts):+ raise RuntimeError('An image must not contain a pre-provisioned login account.')+ root = next(row.split(':') for row in Path('/etc/shadow').read_text().splitlines() if row.startswith('root:'))+ if not root[1].startswith(('!', '*')):+ raise RuntimeError('An image must not contain an unlocked root account.')+ shutil.rmtree(INPUT)+++if __name__ == '__main__':+ main()diff --git a/os/platforms/apple-silicon/source.lock.json b/os/platforms/apple-silicon/source.lock.jsonnew file mode 100644index 000000000..d12ba555e--- /dev/null+++ b/os/platforms/apple-silicon/source.lock.json@@ -0,0 +1,11 @@+{+ "schema": 1,+ "fedora_release": "44",+ "upstream": {+ "repository": "https://forge.fedoraproject.org/asahi/kiwi-descriptions.git",+ "branch": "f44",+ "commit": "bf502c9e39d99e7be58f60b976d09b1e7ef711c4",+ "tree": "72e09071b813d70f5e81244e4e32ba2685a0e845"+ },+ "builder_image": "registry.fedoraproject.org/fedora-minimal@sha256:481d1f308c3d4c0dc98b9b58613163be04271a137ffeae3d398a8c029c46b259"+}diff --git a/os/tests/asahi_image_check.py b/os/tests/asahi_image_check.pynew file mode 100644index 000000000..cadf37dfc--- /dev/null+++ b/os/tests/asahi_image_check.py@@ -0,0 +1,182 @@+#!/usr/bin/env python3+"""Inspect the actual private Asahi disk image in an isolated Linux builder.++Read-only loop mounts cover the produced filesystems, not just KIWI's working+directory. This is image construction evidence, never Apple boot acceptance.+"""+import argparse+import contextlib+import hashlib+import json+import os+from pathlib import Path+import platform+import re+import stat+import subprocess+import tempfile+import time+++PLATFORM_PACKAGES = (+ 'kernel-16k-core', 'kernel-16k-modules', 'kernel-16k-modules-extra',+ 'asahi-platform-metapackage', 'fedora-asahi-remix-scripts', 'asahi-fwupdate',+ 'dracut-asahi', 'update-m1n1', 'uboot-images-armv8', 'grub2-efi-aa64',+ 'asahi-audio', 'speakersafetyd', 'tiny-dfr', 'NetworkManager-wifi',+ 'mesa-dri-drivers', 'greetd', 'chromium', 'harness-os-session',+)+++def digest(path):+ with path.open('rb') as stream:+ return hashlib.file_digest(stream, 'sha256').hexdigest()+++def partition_layout(table, image_bytes):+ table = table['partitiontable']+ if table.get('label') != 'gpt' or table.get('unit') != 'sectors' or table.get('sectorsize') != 4096:+ raise ValueError('Expected Asahi GPT with 4096-byte sectors.')+ partitions = table['partitions']+ if len(partitions) != 3:+ raise ValueError('Expected only EFI, boot and root image partitions.')+ # Current KIWI assigns the Discoverable Partitions Specification types:+ # EFI, XBOOTLDR, then the native ARM64 root (not generic Linux data).+ expected_types = ('c12a7328-f81f-11d2-ba4b-00a0c93ec93b',+ 'bc13c2ff-59e6-4262-a352-b275fd6f7172',+ 'b921b045-1df0-41c3-af44-4c6f280d3fae')+ end = 2+ for row, expected in zip(partitions, expected_types):+ if (row['type'].lower() != expected or type(row['start']) is not int or+ type(row['size']) is not int or row['start'] < end or row['size'] <= 0 or+ (row['start'] + row['size']) * 4096 > image_bytes):+ raise ValueError('Unexpected, overlapping or out-of-bounds image partition.')+ end = row['start'] + row['size']+ return partitions+++def inspect_root(root, boot, esp, identity):+ manifest = identity['session_package']+ if json.loads((root / 'usr/share/harness-os/image.json').read_text()) != identity:+ raise ValueError('The image lost its exact build/package provenance.')+ for relative, expected in manifest['files'].items():+ path = root / relative+ if path.is_symlink() or not path.is_file() or digest(path) != expected:+ raise ValueError('Actual image payload differs: ' + relative)+ for relative, expected in manifest['symlinks'].items():+ if os.readlink(root / relative) != expected:+ raise ValueError('Actual image link differs: ' + relative)+ if (root / 'var/tmp/harness-image-input').exists():+ raise ValueError('Image still contains temporary builder inputs.')+ accounts = [row.split(':') for row in (root / 'etc/passwd').read_text().splitlines()]+ if any(1000 <= int(row[2]) < 65534 for row in accounts):+ raise ValueError('Image contains a pre-provisioned login account.')+ shadow = next(row.split(':') for row in (root / 'etc/shadow').read_text().splitlines() if row.startswith('root:'))+ if not shadow[1].startswith(('!', '*')):+ raise ValueError('Image contains an unlocked root account.')+ if (root / 'etc/machine-id').read_text().strip() not in ('', 'uninitialized'):+ raise ValueError('Image contains a fixed machine ID.')+ if (root / 'var/lib/systemd/random-seed').exists() or list((root / 'etc/ssh').glob('ssh_host_*_key')):+ raise ValueError('Image contains a machine-specific seed or SSH host key.')+ if not re.search(r'^SELINUX=enforcing$', (root / 'etc/selinux/config').read_text(), re.M):+ raise ValueError('Fedora SELinux policy is not enforcing.')+ if (root / 'etc/hostname').read_text().strip() != 'harness':+ raise ValueError('Image hostname differs.')+ boot_files = {'esp/m1n1/boot.bin': esp / 'm1n1/boot.bin',+ 'esp/EFI/BOOT/BOOTAA64.EFI': esp / 'EFI/BOOT/BOOTAA64.EFI'}+ kernels = list(boot.glob('vmlinuz-*'))+ initrds = list(boot.glob('initramfs-*'))+ if not kernels or not initrds:+ raise ValueError('The image is missing a kernel or initramfs.')+ for path in [*kernels, *initrds]:+ boot_files['boot/' + path.name] = path+ evidence = {}+ for relative, path in boot_files.items():+ if path.is_symlink() or not path.is_file() or path.stat().st_size < 1024:+ raise ValueError('Incomplete image boot file: ' + relative)+ evidence[relative] = {'bytes': path.stat().st_size, 'sha256': digest(path)}+ return evidence+++def mounted_image(raw, temporary, run):+ loop = run('losetup', '--find', '--show', '--read-only', '--partscan', '--sector-size', '4096', raw).strip()+ if not re.fullmatch(r'/dev/loop[0-9]+', loop):+ raise ValueError('Unexpected image loop device: ' + loop)+ mounted = []+ try:+ folders = {}+ for label, number, options in [('esp', 1, 'ro'), ('boot', 2, 'ro,noload'),+ ('root', 3, 'ro,rescue=nologreplay,subvol=root')]:+ folder = temporary / label+ folder.mkdir()+ run('mount', '-o', options, loop + 'p' + str(number), folder)+ mounted.append(folder)+ folders[label] = folder+ yield folders+ finally:+ for folder in reversed(mounted):+ run('umount', folder)+ run('losetup', '--detach', loop)+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--image', type=Path, required=True)+ parser.add_argument('--identity', type=Path, required=True)+ parser.add_argument('--output', type=Path, required=True)+ args = parser.parse_args()+ if (platform.system() != 'Linux' or platform.machine() != 'aarch64' or os.geteuid() != 0 or+ not (Path('/run/.containerenv').is_file() or Path('/.dockerenv').is_file())):+ parser.error('Use an isolated, native ARM Linux image builder.')+ if args.image.is_symlink() or not stat.S_ISREG(args.image.stat().st_mode):+ parser.error('Read a regular image file, never a host disk.')+ raw = args.image.resolve()+ identity = json.loads(args.identity.read_text())+ if (identity.get('kind') != 'harness-asahi-image-construction' or+ identity.get('published') is not False or identity.get('release_ready') is not False):+ parser.error('Expected private image construction identity.')+ output = args.output.resolve()+ output.mkdir(parents=True, exist_ok=False)+ receipt = {'schema': 1, 'status': 'running', 'started_at': time.time(), 'image': identity,+ 'scope': 'Produced disk filesystems and package/boot inputs; no boot or physical hardware test',+ 'checks': []}+ with (output / 'commands.log').open('w') as log:+ def run(*command):+ log.write(json.dumps(list(map(str, command))) + '\n')+ log.flush()+ result = subprocess.run(list(map(str, command)), text=True, stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT, timeout=120)+ log.write(result.stdout)+ log.flush()+ result.check_returncode()+ return result.stdout+ try:+ table = json.loads(run('sfdisk', '--json', '--sector-size', '4096', raw))+ receipt['partitions'] = partition_layout(table, raw.stat().st_size)+ with tempfile.TemporaryDirectory(prefix='harness-asahi-inspect-') as temporary:+ with mounted_image(raw, Path(temporary), run) as mounts:+ receipt['boot_files'] = inspect_root(mounts['root'], mounts['boot'], mounts['esp'], identity)+ receipt['platform_packages'] = run('chroot', mounts['root'], 'rpm', '-q', *PLATFORM_PACKAGES).splitlines()+ run('chroot', mounts['root'], 'rpm', '-V', 'harness-os-session')+ inventory = run('chroot', mounts['root'], 'rpm', '-qa', '--qf',+ '%{NAME}\t%{VERSION}\t%{RELEASE}\t%{ARCH}\t%{SIZE}\t%{SOURCERPM}\n')+ (output / 'packages.tsv').write_text('\n'.join(sorted(inventory.splitlines())) + '\n')+ receipt['checks'].extend([+ 'Actual EFI/ext4/Btrfs image partitions mounted read-only',+ 'Exact RPM-owned Harness/OpenCode payload and provenance',+ 'Asahi kernel, boot objects, firmware integration, audio safety and minimal graphical dependencies present',+ 'No login users, unlocked root, fixed machine identity, private keys or builder payload',+ 'SELinux enforcing policy retained',+ ])+ receipt.update(status='passed', artifact={'name': raw.name, 'bytes': raw.stat().st_size,+ 'sha256': digest(raw)})+ except Exception as error:+ receipt.update(status='failed', error=str(error))+ raise+ finally:+ receipt['completed_at'] = time.time()+ (output / 'receipt.json').write_text(json.dumps(receipt, indent=2) + '\n')+++if __name__ == '__main__':+ main()diff --git a/os/tests/test_asahi_image.py b/os/tests/test_asahi_image.pynew file mode 100644index 000000000..8e5ae6bc7--- /dev/null+++ b/os/tests/test_asahi_image.py@@ -0,0 +1,232 @@+import copy+import importlib.util+import json+import os+from pathlib import Path+import subprocess+import sys+import tempfile+import unittest+from unittest.mock import patch+import xml.etree.ElementTree as ET+++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT / 'os/tools'))+import asahi_image as image++spec = importlib.util.spec_from_file_location('asahi_image_check', Path(__file__).with_name('asahi_image_check.py'))+check = importlib.util.module_from_spec(spec)+spec.loader.exec_module(check)+hook_spec = importlib.util.spec_from_file_location('asahi_configure', ROOT / 'os/platforms/apple-silicon/configure.py')+hook = importlib.util.module_from_spec(hook_spec)+hook_spec.loader.exec_module(hook)+++class Recipe(unittest.TestCase):+ def setUp(self):+ folder = tempfile.TemporaryDirectory()+ self.addCleanup(folder.cleanup)+ self.root = Path(folder.name)++ def test_lock_requires_native_content_addressed_builder_and_known_release(self):+ original = image.read_lock()+ for key, value in [('builder_image', 'fedora:latest'), ('fedora_release', 'rawhide')]:+ lock = copy.deepcopy(original)+ lock[key] = value+ path = self.root / 'lock.json'+ path.write_text(json.dumps(lock))+ with self.assertRaisesRegex(ValueError, 'reviewed'):+ image.read_lock(path)++ def test_chroot_guard_requires_the_actual_asahi_release_identity(self):+ with patch.dict(os.environ, {'HARNESS_ASAHI_IMAGE_BUILD': '1'}), \+ patch.object(hook.os, 'geteuid', return_value=0), \+ patch.object(hook.platform, 'machine', return_value='aarch64'), \+ patch.object(hook.Path, 'is_file', return_value=True), \+ patch.object(hook.platform, 'freedesktop_os_release') as release:+ release.return_value = {'ID': 'fedora-asahi-remix', 'VERSION_ID': '44', 'ID_LIKE': 'fedora'}+ hook.require_build_environment()+ for identity in ({'ID': 'fedora', 'VERSION_ID': '44'},+ {'ID': 'fedora-asahi-remix', 'VERSION_ID': '45'},+ {'ID': 'ubuntu', 'ID_LIKE': 'fedora', 'VERSION_ID': '44'}):+ release.return_value = identity+ with self.subTest(identity=identity), self.assertRaisesRegex(RuntimeError, 'Asahi KIWI'):+ hook.require_build_environment()++ def test_upstream_tree_cannot_drift_from_pinned_source(self):+ def git(*args):+ return subprocess.check_output(['git', '-C', str(self.root), *args], text=True).strip()+ git('init', '-q')+ (self.root / 'config.xml').write_text('<image/>')+ git('add', 'config.xml')+ git('-c', 'user.name=Image test', '-c', '[email protected]', 'commit', '-qm', 'fixture')+ lock = {'upstream': {'commit': git('rev-parse', 'HEAD'), 'tree': git('rev-parse', 'HEAD^{tree}')}}+ self.assertIn('config.xml', image.upstream_identity(self.root, lock))+ with self.assertRaisesRegex(ValueError, 'pinned'):+ image.upstream_identity(self.root, {'upstream': {**lock['upstream'], 'tree': '0' * 40}})+ (self.root / 'config.xml').write_text('<image changed="true"/>')+ with self.assertRaisesRegex(ValueError, 'clean'):+ image.upstream_identity(self.root, lock)++ def test_rpm_requirements_preserve_provides_but_reject_unreviewed_expressions(self):+ base = 'python3\nfoot\nlabwc\nNetworkManager\n'+ result = image.requirements(base + 'rpmlib(CompressedFileNames) <= 3.0.4-1\nnodejs22 >= 22.0\n/usr/bin/sh\nlibc.so.6(GLIBC_2.17)(64bit)\n')+ self.assertIn('nodejs22 >= 22.0', result)+ self.assertIn('/usr/bin/sh', result)+ self.assertIn('libc.so.6(GLIBC_2.17)(64bit)', result)+ self.assertFalse(any(item.startswith('rpmlib') for item in result))+ for invalid in ['nodejs; false', '-y', 'nodejs $(id)', '(nodejs or nodejs22)']:+ with self.subTest(invalid=invalid), self.assertRaises(ValueError):+ image.requirements(base + invalid)+ with self.assertRaisesRegex(ValueError, 'missing'):+ image.requirements('python3\n')++ def test_harness_extends_minimal_and_preserves_platform_and_signature_policy(self):+ (self.root / 'platforms').mkdir()+ (self.root / 'platforms/minimal.xml').write_text('<image><preferences>original partition layout</preferences></image>')+ (self.root / 'config.xml').write_text('''<image name="Fedora-Asahi-Remix">+ <description><specification>Fedora</specification></description>+ <preferences><release-version>44</release-version><rpm-check-signatures>true</rpm-check-signatures></preferences>+ <include from="this://./platforms/minimal.xml"/>+ </image>''')+ (self.root / 'config.sh').write_text('#!/bin/bash\nupdate-m1n1 /boot/efi/m1n1/boot.bin\nexit 0\n')+ image.extend_recipe(self.root, ['python3', 'foot'], {'base': {'fedora_release': '44'}})+ profile = ET.parse(self.root / 'platforms/harness.xml')+ self.assertEqual(profile.find('profiles/profile/requires').get('profile'), 'Minimal')+ packages = {element.get('name') for element in profile.findall('packages/package')}+ self.assertTrue({'foot', 'greetd', 'chromium', 'asahi-audio', 'speakersafetyd'} <= packages)+ self.assertFalse(any('gnome' in name or 'plasma' in name for name in packages))+ self.assertEqual(ET.parse(self.root / 'config.xml').findtext('preferences/rpm-check-signatures'), 'true')+ self.assertIn('original partition layout', (self.root / 'platforms/minimal.xml').read_text())+ self.assertIn('update-m1n1 /boot/efi/m1n1/boot.bin', (self.root / 'config.sh').read_text())+++class ActualDiskContract(unittest.TestCase):+ def table(self):+ return {'partitiontable': {'label': 'gpt', 'unit': 'sectors', 'sectorsize': 4096, 'partitions': [+ {'start': 256, 'size': 128000, 'type': 'C12A7328-F81F-11D2-BA4B-00A0C93EC93B'},+ {'start': 128256, 'size': 262144, 'type': 'BC13C2FF-59E6-4262-A352-B275FD6F7172'},+ {'start': 390400, 'size': 1048576, 'type': 'B921B045-1DF0-41C3-AF44-4C6F280D3FAE'},+ ]}}++ def test_actual_partition_table_rejects_foreign_overlapping_and_truncated_images(self):+ good = self.table()+ self.assertEqual(len(check.partition_layout(good, 6 * 1024 ** 3)), 3)+ for label in ('sector', 'foreign', 'generic', 'overlap', 'extra'):+ table = self.table()+ part = table['partitiontable']+ if label == 'sector':+ part['sectorsize'] = 512+ elif label == 'foreign':+ part['partitions'][2]['type'] = '7C3457EF-0000-11AA-AA11-00306543ECAC' # APFS+ elif label == 'generic':+ part['partitions'][2]['type'] = '0FC63DAF-8483-4772-8E79-3D69D8477DE4'+ elif label == 'overlap':+ part['partitions'][2]['start'] = 300000+ else:+ part['partitions'].append(part['partitions'][2])+ with self.subTest(label=label), self.assertRaises(ValueError):+ check.partition_layout(table, 6 * 1024 ** 3)+ with self.assertRaisesRegex(ValueError, 'out-of-bounds'):+ check.partition_layout(good, 1024 ** 3)++ def test_partial_mount_failure_releases_only_its_own_image_devices(self):+ with tempfile.TemporaryDirectory() as temporary:+ calls = []+ def run(*args):+ calls.append(args)+ if args[0] == 'losetup' and '--find' in args:+ return '/dev/loop7\n'+ if args[0] == 'mount' and '/dev/loop7p2' in args:+ raise RuntimeError('ext4 mount failed')+ return ''+ with self.assertRaisesRegex(RuntimeError, 'ext4 mount'):+ with check.mounted_image(Path('/image.raw'), Path(temporary), run):+ self.fail('Must not inspect incomplete mounts')+ self.assertEqual(calls[-2:], [('umount', Path(temporary) / 'esp'), ('losetup', '--detach', '/dev/loop7')])+ self.assertIn('--read-only', calls[0])++ def test_inspection_mounts_prevent_journal_replay_and_release_owned_devices(self):+ with tempfile.TemporaryDirectory() as temporary:+ calls = []+ def run(*args):+ calls.append(args)+ return '/dev/loop7\n' if args[0] == 'losetup' and '--find' in args else ''+ with check.mounted_image(Path('/image.raw'), Path(temporary), run) as mounts:+ self.assertEqual(set(mounts), {'esp', 'boot', 'root'})+ options = {args[-1].name: args[2] for args in calls if args[0] == 'mount'}+ self.assertEqual(options['boot'], 'ro,noload')+ self.assertEqual(options['root'], 'ro,rescue=nologreplay,subvol=root')+ self.assertIn('--read-only', calls[0])+ self.assertEqual(calls[-4:], [('umount', Path(temporary) / label)+ for label in ('root', 'boot', 'esp')] ++ [('losetup', '--detach', '/dev/loop7')])++ def setUp(self):+ temporary = tempfile.TemporaryDirectory()+ self.addCleanup(temporary.cleanup)+ self.folder = Path(temporary.name)+ self.root, self.boot, self.esp = (self.folder / name for name in ('root', 'boot', 'esp'))+ for folder in (self.root, self.boot, self.esp):+ folder.mkdir()+ self.identity = {'session_package': {'files': {}, 'symlinks': {}}}+ files = {+ 'usr/share/harness-os/image.json': json.dumps(self.identity),+ 'etc/passwd': 'root:x:0:0:root:/root:/bin/bash\nnobody:x:65534:65534:Nobody:/:/sbin/nologin\n',+ 'etc/shadow': 'root:!:20732:0:99999:7:::\n',+ 'etc/machine-id': 'uninitialized\n', 'etc/hostname': 'harness\n',+ 'etc/selinux/config': 'SELINUX=enforcing\n',+ }+ for relative, text in files.items():+ self.put(self.root, relative, text)+ for folder, relative in [(self.boot, 'vmlinuz-test'), (self.boot, 'initramfs-test.img'),+ (self.esp, 'm1n1/boot.bin'), (self.esp, 'EFI/BOOT/BOOTAA64.EFI')]:+ self.put(folder, relative, 'x' * 4096)++ def put(self, folder, name, text):+ path = folder / name+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text)+ return path++ def inspect(self):+ return check.inspect_root(self.root, self.boot, self.esp, self.identity)++ def test_actual_root_boot_provenance_and_pristine_identity(self):+ evidence = self.inspect()+ self.assertIn('esp/m1n1/boot.bin', evidence)+ self.assertEqual(evidence['boot/vmlinuz-test']['bytes'], 4096)++ def test_reject_known_password_fixture_or_fixed_machine_secrets(self):+ mutations = [+ ('etc/passwd', 'me:x:1000:1000::/home/me:/bin/bash\n', 'pre-provisioned'),+ ('etc/shadow', 'root:$knownpassword:20732:0:99999:7:::\n', 'unlocked root'),+ ('etc/machine-id', 'a' * 32, 'fixed machine ID'),+ ('etc/selinux/config', 'SELINUX=permissive\n', 'SELinux'),+ ]+ for name, text, message in mutations:+ path = self.root / name+ original = path.read_text()+ with self.subTest(name=name):+ path.write_text(text)+ with self.assertRaisesRegex(ValueError, message):+ self.inspect()+ path.write_text(original)+ self.put(self.root, 'etc/ssh/ssh_host_ed25519_key', 'not for distribution')+ with self.assertRaisesRegex(ValueError, 'SSH host key'):+ self.inspect()++ def test_reject_incomplete_boot_files_and_unproven_payload(self):+ path = self.esp / 'm1n1/boot.bin'+ path.write_bytes(b'')+ with self.assertRaisesRegex(ValueError, 'boot file'):+ self.inspect()+ path.write_bytes(b'x' * 4096)+ self.put(self.root, 'usr/share/harness-os/image.json', '{}')+ with self.assertRaisesRegex(ValueError, 'provenance'):+ self.inspect()+++if __name__ == '__main__':+ unittest.main()diff --git a/os/tools/asahi_image.py b/os/tools/asahi_image.pynew file mode 100644index 000000000..fb201f6a8--- /dev/null+++ b/os/tools/asahi_image.py@@ -0,0 +1,172 @@+#!/usr/bin/env python3+"""Prepare a private Asahi disk-image recipe from declared upstream/RPM inputs.++This does not partition a computer, publish an installer, or build shared clients.+Fedora/Asahi owns boot, firmware, kernel, filesystems and initial setup. The next+integration steps are Harness first boot, encryption and base update/recovery.+"""+import argparse+import hashlib+import json+from pathlib import Path+import re+import shutil+import subprocess+import xml.etree.ElementTree as ET++from fedora_payload import package_identity+++ROOT = Path(__file__).resolve().parents[2]+LOCK = ROOT / 'os/platforms/apple-silicon/source.lock.json'+PLATFORM_PACKAGES = (+ 'greetd', 'chromium', 'mesa-dri-drivers', 'mesa-vulkan-drivers',+ 'asahi-audio', 'speakersafetyd',+)+++def digest(path):+ with path.open('rb') as stream:+ return hashlib.file_digest(stream, 'sha256').hexdigest()+++def run(*args):+ return subprocess.check_output(list(map(str, args)), text=True).strip()+++def read_lock(path=LOCK):+ lock = json.loads(path.read_text())+ upstream = lock.get('upstream', {})+ if (lock.get('schema') != 1 or lock.get('fedora_release') != '44' or+ upstream.get('repository') != 'https://forge.fedoraproject.org/asahi/kiwi-descriptions.git' or+ upstream.get('branch') != 'f44' or+ any(not re.fullmatch(r'[a-f0-9]{40}', str(upstream.get(key))) for key in ('commit', 'tree')) or+ not re.fullmatch(r'registry\.fedoraproject\.org/fedora-minimal@sha256:[a-f0-9]{64}',+ str(lock.get('builder_image')))):+ raise ValueError('Use the reviewed Fedora Asahi source and native builder lock.')+ return lock+++def upstream_identity(folder, lock):+ def git(*args):+ return run('git', '-c', f'safe.directory={folder}', '-C', folder, *args)+ if (git('rev-parse', 'HEAD') != lock['upstream']['commit'] or+ git('rev-parse', 'HEAD^{tree}') != lock['upstream']['tree'] or+ git('status', '--porcelain', '--untracked-files=normal')):+ raise ValueError('Upstream checkout must be clean and match the pinned commit and tree.')+ return git('ls-files', '-z').split('\0')+++def requirements(text):+ """Keep RPM dependency expressions as data, including file provides."""+ result = []+ for expression in text.splitlines():+ if expression.startswith('rpmlib('):+ continue+ if not re.fullmatch(r'[A-Za-z0-9_/][A-Za-z0-9_./+():-]*(?:\s+[<=>]+\s+[A-Za-z0-9_.+:~^-]+)?', expression):+ raise ValueError('Unreviewed session RPM requirement: ' + expression)+ result.append(expression)+ if not result or not {'python3', 'foot', 'labwc', 'NetworkManager'} <= set(result):+ raise ValueError('The declared package is missing the Harness session dependencies.')+ return sorted(set(result))+++def extend_recipe(destination, dependencies, image_identity):+ """Extend Minimal without rewriting its partition or platform definitions."""+ config = destination / 'config.xml'+ tree = ET.parse(config)+ root = tree.getroot()+ if (root.get('name') != 'Fedora-Asahi-Remix' or+ root.findtext('preferences/release-version') != image_identity['base']['fedora_release'] or+ root.findtext('preferences/rpm-check-signatures') != 'true'):+ raise ValueError('The upstream image contract changed; review it before building.')+ root.set('name', 'Harness-Asahi')+ root.set('displayname', 'Harness')+ root.find('description/specification').text = 'Private Harness image using Fedora Asahi Remix Minimal'+ ET.SubElement(root, 'include', {'from': 'this://./platforms/harness.xml'})+ ET.indent(tree, space=' ')+ tree.write(config, encoding='utf-8', xml_declaration=True)+ profile = ET.Element('image')+ profiles = ET.SubElement(profile, 'profiles')+ selected = ET.SubElement(profiles, 'profile', {'name': 'Harness', 'description': 'Harness terminal and agents'})+ ET.SubElement(selected, 'requires', {'profile': 'Minimal'})+ packages = ET.SubElement(profile, 'packages', {'type': 'image', 'profiles': 'Harness'})+ for name in sorted(set(dependencies) | set(PLATFORM_PACKAGES)):+ ET.SubElement(packages, 'package', {'name': name})+ ET.indent(profile, space=' ')+ ET.ElementTree(profile).write(destination / 'platforms/harness.xml', encoding='utf-8', xml_declaration=True)+ script = destination / 'config.sh'+ text = script.read_text()+ if text.count('\nexit 0\n') != 1 or 'update-m1n1 /boot/efi/m1n1/boot.bin' not in text:+ raise ValueError('The upstream image configuration hook changed.')+ script.write_text(text.replace('\nexit 0\n',+ '\n# Install the separately verified local Harness RPM after signed platform dependencies.\n'+ 'HARNESS_ASAHI_IMAGE_BUILD=1 python3 /var/tmp/harness-image-input/configure.py\n\nexit 0\n'))+ identity = destination / 'root/var/tmp/harness-image-input/image.json'+ identity.parent.mkdir(parents=True)+ identity.write_text(json.dumps(image_identity, indent=2) + '\n')+++def prepare(upstream, package, package_source, output, source=ROOT):+ lock = read_lock(source / 'os/platforms/apple-silicon/source.lock.json')+ entries = upstream_identity(upstream, lock)+ metadata = package_identity(package, package_source)+ artifact = package / metadata['package']['name']+ dependencies = requirements(run('rpm', '-qp', '--requires', artifact))+ source_commit = run('git', '-c', f'safe.directory={source}', '-C', source, 'rev-parse', 'HEAD')+ if run('git', '-c', f'safe.directory={source}', '-C', source, 'status', '--porcelain', '--untracked-files=normal'):+ raise ValueError('Commit the image source before preparing a build.')+ identity = {+ 'schema': 1, 'kind': 'harness-asahi-image-construction', 'published': False,+ 'source_commit': source_commit, 'base': lock, 'architecture': 'aarch64',+ 'profile': 'Harness', 'session_package': metadata,+ 'release_ready': False,+ 'pending': ['Harness first-boot account setup', 'Disk encryption',+ 'Fedora base updates and recovery', 'Physical Apple hardware acceptance'],+ }+ output.mkdir(parents=True, exist_ok=False)+ description = output / 'description'+ description.mkdir()+ for name in entries:+ if not name:+ continue+ relative = Path(name)+ origin = upstream / relative+ if relative.is_absolute() or '..' in relative.parts or not origin.is_file():+ raise ValueError('Unexpected upstream source entry: ' + name)+ target = description / relative+ target.parent.mkdir(parents=True, exist_ok=True)+ if origin.is_symlink():+ link = origin.readlink()+ if link.is_absolute() or '..' in link.parts or not origin.resolve().is_relative_to(upstream.resolve()):+ raise ValueError('Upstream link leaves the description: ' + name)+ target.symlink_to(link)+ else:+ shutil.copy2(origin, target)+ extend_recipe(description, dependencies, identity)+ inputs = description / 'root/var/tmp/harness-image-input'+ shutil.copyfile(artifact, inputs / artifact.name)+ shutil.copyfile(source / 'os/platforms/apple-silicon/configure.py', inputs / 'configure.py')+ (output / 'image-inputs.json').write_text(json.dumps(identity, indent=2) + '\n')+ (output / 'recipe-files.json').write_text(json.dumps({+ str(path.relative_to(description)): ({'symlink': str(path.readlink())} if path.is_symlink()+ else {'sha256': digest(path)})+ for path in sorted(description.rglob('*')) if path.is_file()+ }, indent=2) + '\n')+ return identity+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--upstream', required=True, type=Path)+ parser.add_argument('--package', required=True, type=Path)+ parser.add_argument('--package-source', required=True)+ parser.add_argument('--output', required=True, type=Path)+ args = parser.parse_args()+ identity = prepare(args.upstream.resolve(), args.package.resolve(), args.package_source, args.output.resolve())+ print(json.dumps({'source_commit': identity['source_commit'], 'profile': identity['profile'],+ 'release_ready': False}, indent=2))+++if __name__ == '__main__':+ main()