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.

test(os): prepare the pinned T2 kernel and encrypted boot acceptance (#836)

Dee5e6960cd29be
diff --git a/.github/workflows/os-input.yml b/.github/workflows/os-input.yml
index bd8b241a4..6d4ad233d 100644
--- a/.github/workflows/os-input.yml
+++ b/.github/workflows/os-input.yml
@@ -9,9 +9,9 @@ on:
default: '37222390225'
required: true
probe:
- description: 'Laptop controls, Apple boot modules, install refusal or updater pane ownership'
+ description: 'Laptop controls, Apple/T2 boot modules, install refusal or updater pane ownership'
type: choice
- options: [laptop-input, apple-boot, install-preflight, update-pane, update-context]
+ options: [laptop-input, apple-boot, t2-boot, install-preflight, update-pane, update-context]
default: laptop-input
required: true
push:
@@ -42,7 +42,9 @@ jobs:
env:
PROBE: ${{ inputs.probe }}
run: |
- if [[ "$PROBE" == update-pane || "$PROBE" == update-context ]]; then
+ if [[ "$PROBE" == t2-boot ]]; then
+ python3 -m py_compile os/tests/t2_boot_vm.py os/tools/prepare-t2-kernel.py
+ elif [[ "$PROBE" == update-pane || "$PROBE" == update-context ]]; then
python3 -m py_compile os/tests/update_pane_vm.py os/tests/update_pane_guest.py os/tests/update_context_vm.py os/live_update.py os/root/usr/lib/harness-os/open-updates
elif [[ "$PROBE" == install-preflight ]]; then
PYTHONPATH=os/tests python3 -m unittest test_hardware test_installer
@@ -53,8 +55,26 @@ jobs:
fi
go run github.com/rhysd/actionlint/cmd/[email protected] .github/workflows/os-input.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 apt-get install -y --no-install-recommends qemu-system-x86 qemu-utils ovmf python3-pil tesseract-ocr zstd
sudo chmod a+rw /dev/kvm
+ - name: Prepare the pinned T2 kernel and check encrypted cold boot
+ if: ${{ inputs.probe == 't2-boot' }}
+ run: |
+ python3 -m unittest discover -s os/tests -p 'test_t2_kernel.py' -v
+ python3 - <<'PY'
+ import json, subprocess
+ from pathlib import Path
+ lock = json.loads(Path('os/platforms/apple-t2/kernel.json').read_text())
+ folder = Path('os/work/t2-inputs')
+ folder.mkdir(parents=True, exist_ok=False)
+ package = lock['package']
+ subprocess.run(['curl', '--fail', '--location', '--proto', '=https', '--proto-redir', '=https',
+ '--max-time', '180', package['url'], '-o', str(folder / package['filename'])], check=True)
+ PY
+ python3 os/tools/prepare-t2-kernel.py \
+ --package os/work/t2-inputs/*.pkg.tar.zst --output os/work/t2-kernel-bundle
+ python3 os/tests/t2_boot_vm.py --iso os/dist/*.iso \
+ --bundle os/work/t2-kernel-bundle --output os/test-results/t2-boot
- name: Check actual media-key input on USB and installed sessions
if: ${{ inputs.probe == 'laptop-input' || !inputs.probe }}
run: python3 os/tests/input_vm.py --iso os/dist/*.iso
@@ -78,6 +98,7 @@ jobs:
path: |
os/test-results/input/
os/test-results/apple-boot/
+ os/test-results/t2-boot/
os/test-results/install-preflight/
os/test-results/update-pane/
os/test-results/update-context/
@@ -85,6 +106,8 @@ jobs:
!os/test-results/input/OVMF_VARS.fd
!os/test-results/apple-boot/*.qcow2
!os/test-results/apple-boot/OVMF_VARS.fd
+ !os/test-results/t2-boot/*.qcow2
+ !os/test-results/t2-boot/OVMF_VARS.fd
!os/test-results/install-preflight/*.qcow2
!os/test-results/install-preflight/OVMF_VARS.fd
!os/test-results/update-pane/*.qcow2
diff --git a/os/platforms/apple-t2/README.md b/os/platforms/apple-t2/README.md
new file mode 100644
index 000000000..c9455a5a7
--- /dev/null
+++ b/os/platforms/apple-t2/README.md
@@ -0,0 +1,30 @@
+# Apple T2 platform preparation
+
+This directory pins the maintained T2 kernel and its required modules. It is
+preparation for a separate Intel Mac boot profile, not a supported T2 installer.
+The ordinary image still refuses T2 installation before any disk write.
+
+`kernel.json` records the upstream recipe, patch commit and exact release archive.
+`prepare-t2-kernel.py` verifies its checksum, package identity, kernel release and
+input/radio/audio modules without extracting package paths or installing anything
+on the build host. The resulting bundle retains the original package. It adds no
+compiler, kernel headers, desktop or extra service to the generic image.
+
+The **Harness OS laptop input** workflow accepts `probe=t2-boot` with image run
+`37257481538`. It installs the original preview 14 in an encrypted VM, installs
+the pinned kernel, checks early input modules in the generated initramfs and their
+kernel compatibility, then cold boots and types through the graphical unlock and
+Harness. Source, package hashes, boot output and screenshots are retained. A VM
+cannot establish that physical T2 devices work.
+
+Before enabling T2 installation, integrate the same kernel into both USB and
+installed boot, preserve model-specific Apple wireless firmware before erasing
+macOS, and make updates/recovery preserve the selected platform. Then validate
+built-in input, Wi-Fi, audio, graphics and suspend on real Macs. In particular,
+iMac Pro firmware needs the macOS export route. Never add a moving unsigned
+repository or copy Apple firmware into the public ISO as a shortcut.
+
+Upstream references: [maintained kernel](https://github.com/NoaHimesaka1873/linux-t2-arch),
+[early input and kernel parameters](https://wiki.t2linux.org/guides/postinstall/),
+[wireless firmware](https://wiki.t2linux.org/guides/wifi-bluetooth/), and
+[hardware status](https://wiki.t2linux.org/state/).
diff --git a/os/platforms/apple-t2/kernel.json b/os/platforms/apple-t2/kernel.json
new file mode 100644
index 000000000..8072db4b0
--- /dev/null
+++ b/os/platforms/apple-t2/kernel.json
@@ -0,0 +1,28 @@
+{
+ "schema": 1,
+ "platform": "apple-t2",
+ "architecture": "x86_64",
+ "package": {
+ "name": "linux-t2",
+ "version": "7.2.8.arch1-1",
+ "filename": "linux-t2-7.2.8.arch1-1-x86_64.pkg.tar.zst",
+ "url": "https://github.com/NoaHimesaka1873/linux-t2-arch/releases/download/v7.2.8.arch1/linux-t2-7.2.8.arch1-1-x86_64.pkg.tar.zst",
+ "bytes": 164068546,
+ "sha256": "e4f1bd7ca1ffccba32393244281a6271c9525139c0a501be236da939326ddf75"
+ },
+ "kernel_release": "7.2.8-arch1-Watanare-T2-1-t2",
+ "pkgbase": "linux-t2",
+ "source": {
+ "recipe_repository": "https://github.com/NoaHimesaka1873/linux-t2-arch",
+ "recipe_commit": "b9f7fe120cda0e36f796ff78c3ea8f4eae13f1d7",
+ "patch_repository": "https://github.com/t2linux/linux-t2-patches",
+ "patch_commit": "65fdd4d492d7e219a05742ce4768f16e5ba4f976",
+ "license": "GPL-2.0-only"
+ },
+ "early_modules": ["t2bce_dma", "t2bce_core", "t2bce_vhci"],
+ "required_modules": [
+ "t2bce_dma", "t2bce_core", "t2bce_vhci", "t2bce_audio",
+ "hid_apple", "hid_appletb_kbd", "brcmfmac", "hci_bcm4377", "apfs"
+ ],
+ "kernel_parameters": ["intel_iommu=on", "iommu=pt", "pm_async=off"]
+}
diff --git a/os/tests/t2_boot_vm.py b/os/tests/t2_boot_vm.py
new file mode 100644
index 000000000..a8d50d169
--- /dev/null
+++ b/os/tests/t2_boot_vm.py
@@ -0,0 +1,138 @@
+#!/usr/bin/env python3
+"""Boot the pinned T2 kernel in an encrypted Harness VM, without claiming Mac support."""
+import argparse
+from functools import partial
+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
+import importlib.util
+import json
+import os
+from pathlib import Path
+import shlex
+import subprocess
+import threading
+import time
+
+from footprint_vm import copy_file
+from hardware_update_vm import graceful_stop, verify_image
+from vm import VM, check_graphical_keyboard
+
+spec = importlib.util.spec_from_file_location('t2_kernel', Path(__file__).parents[1] / 'tools/prepare-t2-kernel.py')
+t2 = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(t2)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--iso', type=Path, required=True)
+ parser.add_argument('--bundle', type=Path, required=True)
+ parser.add_argument('--output', type=Path, required=True)
+ args = parser.parse_args()
+ if not os.access('/dev/kvm', os.R_OK | os.W_OK):
+ parser.error('Native x86 KVM is required.')
+ iso, bundle, folder = args.iso.resolve(), args.bundle.resolve(), args.output.absolute()
+ image = verify_image(iso, json.loads(Path(__file__).with_name('hardware-update.lock.json').read_text()))
+ lock = json.loads(t2.LOCK.read_text())
+ package = bundle / lock['package']['filename']
+ members = t2.inspect(package, lock)
+ folder.mkdir(parents=True, exist_ok=False)
+ source = subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip()
+ if subprocess.check_output(['git', 'status', '--porcelain'], text=True).strip():
+ parser.error('Commit the observer before native acceptance.')
+ record = {'status': 'running', 'started_at': time.time(), 'observer_source': source,
+ 'image_source': image['source_commit'], 'image': image['iso'], 'kernel': lock,
+ 'verified_package_files': members, 'checks': [],
+ 'limits': ['Virtual PC, not a T2 Mac: physical input, graphics, radio, audio and suspend remain unverified.',
+ 'Candidate kernel overlay on an installed preview 14 image; not a T2 ISO or installer acceptance.']}
+ vm = VM(folder, iso, 'uefi', 2048, cpu='Haswell-noTSX')
+ server = ThreadingHTTPServer(('127.0.0.1', 0), partial(SimpleHTTPRequestHandler, directory=str(bundle)))
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ config = dict(disk='/dev/vda', expected_serial='HN_OS_TEST', confirm_erase='/dev/vda',
+ username='me', hostname='harness', password='test-password-123', encrypt=True, serial_console=True)
+ try:
+ vm.start(live=True)
+ vm.monitor('set_link', name='hnnet', up=False)
+ vm.wait(r'root@[^\r\n]*[#] ')
+ vm.shell_ready = True
+ vm.command('stty -echo; nmcli networking off')
+ copy_file(vm, json.dumps(config).encode(), '/tmp/install.json')
+ output, _ = vm.command('harness install --config /tmp/install.json --yes-erase-disk', timeout=360)
+ (folder / 'install.log').write_text(output)
+ graceful_stop(vm, False)
+ vm.start(live=False)
+ vm.monitor('set_link', name='hnnet', up=False)
+ vm.login_installed(config)
+ vm.command('printf %s ' + shlex.quote(config['password'] + '\n') + ' | sudo -S -v')
+ vm.command('systemctl --user stop harness-update.timer harness-update.service')
+ before = vm.read_file('/proc/sys/kernel/random/boot_id')
+ vm.monitor('set_link', name='hnnet', up=True)
+ vm.command('sudo -n nmcli networking on && nm-online -q --timeout=30', timeout=35)
+ url = 'http://10.0.2.2:' + str(server.server_port) + '/' + package.name
+ vm.command('curl --fail --silent --show-error ' + shlex.quote(url) + ' -o /tmp/t2-kernel.pkg.tar.zst', timeout=120)
+ vm.command('printf %s ' + shlex.quote(lock['package']['sha256'] + ' /tmp/t2-kernel.pkg.tar.zst\n') + ' | sha256sum -c -')
+ output, _ = vm.command('sudo -n pacman -U --needed --noconfirm /tmp/t2-kernel.pkg.tar.zst', timeout=240)
+ (folder / 'kernel-install.log').write_text(output)
+ # Only the T2 preset gets its input modules. The retained original LTS
+ # kernel/preset must still build as a recovery option in this fixture.
+ mkinitcpio = 'source /etc/mkinitcpio.conf\nMODULES+=(' + ' '.join(lock['early_modules']) + ')\n'
+ copy_file(vm, mkinitcpio.encode(), '/tmp/mkinitcpio-t2.conf')
+ vm.command('sudo -n install -m 644 /tmp/mkinitcpio-t2.conf /etc/mkinitcpio-t2.conf')
+ preset = ('ALL_config="/etc/mkinitcpio-t2.conf"\nALL_kver="/boot/vmlinuz-linux-t2"\n'
+ "PRESETS=('default')\ndefault_image=\"/boot/initramfs-linux-t2.img\"\n")
+ copy_file(vm, preset.encode(), '/tmp/linux-t2.preset')
+ vm.command('sudo -n install -m 644 /tmp/linux-t2.preset /etc/mkinitcpio.d/linux-t2.preset && '
+ 'sudo -n cp /usr/lib/modules/' + lock['kernel_release'] + '/vmlinuz /boot/vmlinuz-linux-t2 && sudo -n mkinitcpio -P', timeout=240)
+ data, _ = vm.command('sudo -n lsinitcpio --list /boot/initramfs-linux-t2.img')
+ (folder / 'initramfs-files.txt').write_text(data)
+ for module in lock['early_modules']:
+ if '/' + module + '.ko' not in data:
+ raise ValueError('Early T2 input module missing from initramfs: ' + module)
+ output, _ = vm.command('sudo -n lsinitcpio --config /boot/initramfs-linux-t2.img')
+ (folder / 'initramfs-config.txt').write_text(output)
+ for module in lock['early_modules']:
+ if module not in output:
+ raise ValueError('T2 input module not configured for early loading: ' + module)
+ for module in lock['required_modules']:
+ output, _ = vm.command('modinfo -k ' + lock['kernel_release'] + ' -F vermagic ' + module)
+ if lock['kernel_release'] not in output:
+ raise ValueError('T2 module targets a different kernel: ' + module)
+ params = ' '.join(lock['kernel_parameters'])
+ vm.command('printf %s ' + shlex.quote('\nGRUB_CMDLINE_LINUX="$GRUB_CMDLINE_LINUX ' + params + '"\n') +
+ ' | sudo -n tee -a /etc/default/grub >/dev/null && sudo -n grub-mkconfig -o /boot/grub/grub.cfg')
+ record['checks'].append('Pinned kernel installs on the shipped userspace; mkinitcpio includes the three early input modules and every required module has matching vermagic.')
+ graceful_stop(vm, True)
+ vm.start(live=False)
+ vm.login_installed(config)
+ vm.command('test "$(uname -r)" = ' + shlex.quote(lock['kernel_release']))
+ if vm.read_file('/proc/sys/kernel/random/boot_id') == before:
+ raise ValueError('The candidate kernel was not cold booted.')
+ command_line = vm.read_file('/proc/cmdline').decode()
+ if not set(lock['kernel_parameters']) <= set(command_line.split()):
+ raise ValueError('T2 boot parameters were not applied.')
+ (folder / 'cmdline.txt').write_text(command_line)
+ check_graphical_keyboard(vm, 't2-kernel-keyboard')
+ vm.command('printf %s ' + shlex.quote(config['password'] + '\n') + ' | sudo -S -v')
+ output, _ = vm.command('sudo -n journalctl -b --no-pager')
+ (folder / 'candidate-boot.log').write_text(output)
+ record['checks'].append('A real cold boot runs the pinned T2 kernel, accepts the encrypted graphical unlock password and types into Harness.')
+ graceful_stop(vm, True)
+ record['status'] = 'passed'
+ except Exception as error:
+ record.update(status='failed', error=repr(error))
+ if vm.process and vm.process.poll() is None:
+ vm.screenshot('failure')
+ raise
+ finally:
+ vm.stop()
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=5)
+ vm.log.close()
+ vm.stderr.close()
+ vm.control.cleanup()
+ record['duration_seconds'] = round(time.time() - record['started_at'], 3)
+ (folder / 'receipt.json').write_text(json.dumps(record, indent=2) + '\n')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/os/tests/test_t2_kernel.py b/os/tests/test_t2_kernel.py
new file mode 100644
index 000000000..79b2edce1
--- /dev/null
+++ b/os/tests/test_t2_kernel.py
@@ -0,0 +1,85 @@
+import copy
+import hashlib
+import importlib.util
+import io
+import json
+from pathlib import Path
+import subprocess
+import tarfile
+import tempfile
+import unittest
+
+spec = importlib.util.spec_from_file_location('t2_kernel', Path(__file__).parents[1] / 'tools/prepare-t2-kernel.py')
+t2 = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(t2)
+
+
+class T2KernelBundleTests(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.root = Path(self.temp.name)
+ self.package = self.root / 'kernel.pkg.tar.zst'
+ self.lock = {'schema': 1, 'platform': 'apple-t2', 'architecture': 'x86_64',
+ 'kernel_release': '7.2.8-test-t2', 'pkgbase': 'linux-t2',
+ 'early_modules': ['t2bce_vhci'], 'required_modules': ['t2bce_vhci'],
+ 'package': {'name': 'linux-t2', 'version': '7.2.8-1', 'filename': self.package.name}}
+ prefix = 'usr/lib/modules/7.2.8-test-t2/'
+ self.files = {'.PKGINFO': b'pkgname = linux-t2\npkgbase = linux-t2\npkgver = 7.2.8-1\narch = x86_64\n',
+ prefix + 'pkgbase': b'linux-t2\n', prefix + 'vmlinuz': bytes(0x202) + b'HdrS',
+ prefix + 'kernel/t2bce_vhci.ko.zst': b'module fixture'}
+ self.write_package()
+
+ def write_package(self, extra=None):
+ archive = self.root / 'kernel.tar'
+ with tarfile.open(archive, 'w') as output:
+ for name, data in self.files.items():
+ member = tarfile.TarInfo(name)
+ member.mode, member.size = 0o644, len(data)
+ output.addfile(member, io.BytesIO(data))
+ if extra is not None:
+ output.addfile(extra, io.BytesIO(b''))
+ subprocess.run(['zstd', '-q', '-f', str(archive), '-o', str(self.package)], check=True, timeout=10)
+ self.lock['package'].update(t2.identity(self.package))
+
+ def test_exact_archive_is_staged_without_extracting_package_paths(self):
+ lock = self.root / 'lock.json'
+ lock.write_text(json.dumps(self.lock))
+ output = self.root / 'bundle'
+ receipt = t2.prepare(self.package, output, lock)
+ self.assertEqual(len(receipt['verified_files']), 4)
+ self.assertEqual(t2.identity(output / self.package.name), t2.identity(self.package))
+ self.assertFalse((self.root / 'usr').exists())
+ with self.assertRaisesRegex(ValueError, 'fresh'):
+ t2.prepare(self.package, output, lock)
+
+ def test_corruption_fails_before_archive_tool_runs(self):
+ self.package.write_bytes(b'truncated')
+ with self.assertRaisesRegex(ValueError, 'pinned artifact'):
+ t2.inspect(self.package, self.lock)
+
+ def test_another_architecture_kernel_or_missing_input_cannot_pass(self):
+ originals = dict(self.files)
+ for change in ('architecture', 'kernel', 'missing-input', 'duplicate-input'):
+ self.files = dict(originals)
+ if change == 'architecture':
+ self.files['.PKGINFO'] = self.files['.PKGINFO'].replace(b'x86_64', b'aarch64')
+ elif change == 'kernel':
+ self.files['usr/lib/modules/other/vmlinuz'] = bytes(0x202) + b'HdrS'
+ elif change == 'missing-input':
+ self.files.pop('usr/lib/modules/7.2.8-test-t2/kernel/t2bce_vhci.ko.zst')
+ else:
+ self.files['usr/lib/modules/7.2.8-test-t2/extra/t2bce_vhci.ko.zst'] = b'duplicate'
+ self.write_package()
+ with self.subTest(change=change), self.assertRaises(ValueError):
+ t2.inspect(self.package, self.lock)
+
+ def test_archive_traversal_and_duplicate_paths_are_rejected(self):
+ for name in ('../escape', '/absolute', '.PKGINFO'):
+ self.write_package(tarfile.TarInfo(name))
+ with self.subTest(name=name), self.assertRaisesRegex(ValueError, 'Unsafe or duplicate'):
+ t2.inspect(self.package, self.lock)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/os/tools/prepare-t2-kernel.py b/os/tools/prepare-t2-kernel.py
new file mode 100644
index 000000000..a761d8b2e
--- /dev/null
+++ b/os/tools/prepare-t2-kernel.py
@@ -0,0 +1,115 @@
+#!/usr/bin/env python3
+"""Prepare the pinned T2 kernel for an isolated image build; never install it."""
+import argparse
+import hashlib
+import json
+from pathlib import Path, PurePosixPath
+import re
+import shutil
+import subprocess
+import tarfile
+import tempfile
+
+LOCK = Path(__file__).resolve().parents[1] / 'platforms/apple-t2/kernel.json'
+
+
+def identity(path):
+ with path.open('rb') as handle:
+ return {'bytes': path.stat().st_size, 'sha256': hashlib.file_digest(handle, 'sha256').hexdigest()}
+
+
+def inspect(package, lock):
+ if (lock.get('schema') != 1 or lock.get('platform') != 'apple-t2'
+ or lock.get('architecture') != 'x86_64' or lock.get('pkgbase') != 'linux-t2'
+ or not re.fullmatch(r'[0-9A-Za-z.+_-]+', lock.get('kernel_release', ''))):
+ raise ValueError('Invalid T2 kernel lock.')
+ expected = lock['package']
+ if package.is_symlink() or not package.is_file() or identity(package) != {
+ key: expected[key] for key in ('bytes', 'sha256')}:
+ raise ValueError('T2 kernel package differs from the pinned artifact.')
+ modules = lock['required_modules']
+ if (not modules or len(set(modules)) != len(modules)
+ or any(not re.fullmatch(r'[a-z0-9_]+', name) for name in modules)
+ or not set(lock['early_modules']) <= set(modules)):
+ raise ValueError('Invalid T2 module requirements.')
+ prefix = 'usr/lib/modules/' + lock['kernel_release'] + '/'
+ selected = {}
+ seen = set()
+ # The package checksum is checked before invoking any archive tool. Spool
+ # to a temporary file so no package path is ever extracted onto the host.
+ with tempfile.TemporaryFile() as raw:
+ subprocess.run(['zstd', '--quiet', '--decompress', '--stdout', '--', str(package)],
+ stdout=raw, stderr=subprocess.PIPE, check=True, timeout=45)
+ if raw.tell() > 512 * 1024 * 1024:
+ raise ValueError('Unexpectedly large T2 kernel payload.')
+ raw.seek(0)
+ with tarfile.open(fileobj=raw, mode='r:') as archive:
+ for member in archive:
+ name = member.name.rstrip('/')
+ path = PurePosixPath(name)
+ if (not name or path.is_absolute() or '..' in path.parts or str(path) != name
+ or name in seen or any(ord(char) < 32 for char in name)):
+ raise ValueError('Unsafe or duplicate T2 package path.')
+ seen.add(name)
+ if not (member.isfile() or member.isdir() or member.issym()):
+ raise ValueError('Unexpected T2 package member type.')
+ if (member.uid, member.gid) != (0, 0):
+ raise ValueError('T2 kernel package must be root-owned.')
+ if name.startswith('usr/lib/modules/') and not member.isdir() and not name.startswith(prefix):
+ raise ValueError('T2 package contains another kernel release.')
+ module = path.name.removesuffix('.ko.zst').replace('-', '_') if name.endswith('.ko.zst') else None
+ if name in {'.PKGINFO', prefix + 'pkgbase', prefix + 'vmlinuz'} or module in modules:
+ if not member.isfile() or member.size > 64 * 1024 * 1024:
+ raise ValueError('Expected a regular T2 kernel/module file.')
+ data = archive.extractfile(member).read()
+ key = module if module in modules else path.name
+ if key in selected:
+ raise ValueError('Duplicate T2 kernel/module identity.')
+ selected[key] = {'path': name, 'bytes': len(data), 'sha256': hashlib.sha256(data).hexdigest()}
+ if name == '.PKGINFO':
+ fields = {}
+ for line in data.decode().splitlines():
+ if ' = ' in line:
+ field, value = line.split(' = ', 1)
+ fields.setdefault(field, []).append(value)
+ for field, value in [('pkgname', expected['name']), ('pkgver', expected['version']),
+ ('arch', 'x86_64'), ('pkgbase', 'linux-t2')]:
+ if fields.get(field) != [value]:
+ raise ValueError('T2 package metadata mismatch: ' + field)
+ elif name == prefix + 'pkgbase' and data.strip() != b'linux-t2':
+ raise ValueError('T2 kernel has a different package base.')
+ elif name == prefix + 'vmlinuz' and data[0x202:0x206] != b'HdrS':
+ raise ValueError('T2 boot image is not an x86 Linux kernel.')
+ if set(selected) != {'.PKGINFO', 'pkgbase', 'vmlinuz', *modules}:
+ raise ValueError('T2 package omits a required kernel or module file.')
+ return selected
+
+
+def prepare(package, output, lock_path=LOCK):
+ if output.exists():
+ raise ValueError('Use a fresh T2 bundle directory.')
+ lock = json.loads(lock_path.read_text())
+ selected = inspect(package, lock)
+ output.parent.mkdir(parents=True, exist_ok=True)
+ with tempfile.TemporaryDirectory(prefix='.harness-t2-', dir=output.parent) as temporary:
+ folder = Path(temporary)
+ target = folder / lock['package']['filename']
+ shutil.copyfile(package, target)
+ if identity(target) != {key: lock['package'][key] for key in ('bytes', 'sha256')}:
+ raise ValueError('T2 kernel changed during preparation.')
+ manifest = {'schema': 1, 'platform': 'apple-t2', 'kernel': lock,
+ 'verified_files': selected, 'lock': identity(lock_path),
+ 'validation': 'archive verified; native boot and physical hardware unverified'}
+ (folder / 'manifest.json').write_text(json.dumps(manifest, indent=2) + '\n')
+ folder.rename(output)
+ return manifest
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--package', type=Path, required=True)
+ parser.add_argument('--output', type=Path, required=True)
+ args = parser.parse_args()
+ result = prepare(args.package.resolve(), args.output.absolute())
+ print(json.dumps({'kernel': result['kernel']['kernel_release'], 'files': len(result['verified_files']),
+ 'output': str(args.output)}))