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.

Verify T2 kernel updates and retain offline rollback (#852)

Dee2290cc071c3c
diff --git a/.github/workflows/os-t2-update.yml b/.github/workflows/os-t2-update.yml
new file mode 100644
index 000000000..58befab32
--- /dev/null
+++ b/.github/workflows/os-t2-update.yml
@@ -0,0 +1,95 @@
+name: Harness OS T2 kernel update
+
+on:
+ workflow_dispatch:
+ push:
+ branches: ['os-checks/t2-kernel-*']
+ paths: ['os/**', '.github/workflows/os-t2-update.yml']
+
+permissions:
+ contents: read
+ actions: read
+
+concurrency:
+ group: harness-t2-update-${{ github.ref }}
+ cancel-in-progress: false
+
+jobs:
+ update:
+ runs-on: ubuntu-24.04
+ timeout-minutes: 35
+ env:
+ CARGO_INCREMENTAL: '0'
+ steps:
+ - uses: actions/checkout@v7
+ with:
+ fetch-depth: 0
+ - name: Require unchanged public shared runtime sources
+ run: |
+ python3 - <<'PY'
+ import subprocess
+ expected = {'tui': '1ec2af97a8695bdcc8429ddc498747bd86eada08',
+ 'cli': '27f50e77fa9bdc8de75a64c9e9166c932c559a8b',
+ 'store': 'ea5589e2d8db518a85453fa3c9efc60d29a16085'}
+ for path, tree in expected.items():
+ assert subprocess.check_output(['git', 'rev-parse', 'HEAD:' + path], text=True).strip() == tree, path
+ PY
+ - 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:
+ toolchain: '1.99.0'
+ targets: x86_64-unknown-linux-musl
+ - uses: actions/download-artifact@v6
+ with:
+ name: harness-os-t2-image
+ path: os/dist
+ run-id: 37409262209
+ github-token: ${{ github.token }}
+ - name: Install native test tools and verify source contracts
+ run: |
+ sudo apt-get update -qq
+ sudo apt-get install -y --no-install-recommends musl=1.2.4-2 musl-dev=1.2.4-2 musl-tools=1.2.4-2 zstd qemu-system-x86 qemu-utils ovmf python3-pil tesseract-ocr
+ sudo chmod a+rw /dev/kvm
+ make -C os check
+ go run github.com/rhysd/actionlint/cmd/[email protected] .github/workflows/os-t2-update.yml
+ - name: Build private update and verify both immutable kernel archives
+ run: |
+ make -C os runtime
+ python3 os/tools/build-package.py --runtime os/work/runtime --output os/work/t2-update --development
+ python3 - <<'PY'
+ import importlib.util, json
+ from pathlib import Path
+ spec = importlib.util.spec_from_file_location('t2', 'os/t2_update.py')
+ t2 = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(t2)
+ folder = Path('os/work/t2-kernel-inputs')
+ folder.mkdir(parents=True)
+ for path in ['os/tests/t2-kernel-before.json', 'os/platforms/apple-t2/kernel.json']:
+ pin = t2.validate_pin(json.loads(Path(path).read_text()))
+ package = folder / pin['package']['filename']
+ t2.download(pin, package)
+ t2.KERNEL.inspect(package, pin)
+ PY
+ - name: Change actual T2 kernel, reboot, roll back offline, and recover
+ run: |
+ python3 os/tests/t2_update_vm.py --iso os/dist/*.iso --bundle os/work/t2-update \
+ --kernels os/work/t2-kernel-inputs --output os/test-results/t2-kernel-update
+ - name: Retain source, kernel transaction and cold-boot evidence
+ if: always()
+ uses: actions/upload-artifact@v6
+ with:
+ name: harness-os-t2-kernel-update
+ path: |
+ os/test-results/t2-kernel-update/
+ !os/test-results/t2-kernel-update/*.qcow2
+ !os/test-results/t2-kernel-update/OVMF_VARS.fd
+ !os/test-results/t2-kernel-update/synthetic-firmware/
+ !os/test-results/t2-kernel-update/served/
+ os/work/t2-update/package-manifest.json
+ os/work/t2-update/SHA256SUMS
+ retention-days: 14
+ compression-level: 0
diff --git a/os/boot_profile.py b/os/boot_profile.py
index f93f814c1..8eb01a4ed 100644
--- a/os/boot_profile.py
+++ b/os/boot_profile.py
@@ -37,12 +37,11 @@ def boot_files(identity):
return {'vmlinuz-' + kernel, 'initramfs-' + kernel + '.img', 'grub/grub.cfg'}
-def validate_update(package, root=Path('/')):
+def validate_update(package, root=Path('/'), *, allow_kernel_change=False, kernel_rollback=False):
if selected(root)['id'] != 'apple-t2':
return
- # The initial T2 image has one verified kernel. A general PC package must
- # not remove its helpers or silently advance the required T2 kernel. A
- # future kernel change needs its own staged, verified package transaction.
+ # A general package must retain the platform. Only the updater that stages
+ # both verified kernels and retains an offline rollback can advance the pin.
pin = 'usr/share/harness-os/apple-t2/kernel.json'
required = {'usr/lib/harness-os/' + name + '.py' for name in
['boot_profile', 't2_install', 't2_firmware', 'firmware_names']}
@@ -53,8 +52,21 @@ def validate_update(package, root=Path('/')):
if files[pin].size > 65536:
raise ValueError('Invalid T2 kernel requirements in the update.')
requested = json.loads(archive.extractfile(files[pin]).read())
- if requested != json.loads((root / pin).read_text()):
+ if requested != json.loads((root / pin).read_text()) and not allow_kernel_change:
raise ValueError('This update needs a different T2 kernel; a verified T2 kernel update is required. Nothing updated.')
+ if allow_kernel_change and not kernel_rollback and requested != json.loads((root / pin).read_text()):
+ if any(not files.get('usr/lib/harness-os/' + name + '.py') or
+ not files['usr/lib/harness-os/' + name + '.py'].isfile()
+ for name in ['t2_update', 't2_kernel']):
+ raise ValueError('This update omits the T2 kernel transaction helpers.')
+ return requested
+
+
+def prepare_update(package, source, destination):
+ requested = validate_update(package, allow_kernel_change=True)
+ if requested is None or requested == json.loads(Path('/usr/share/harness-os/apple-t2/kernel.json').read_text()):
+ return None
+ return module('t2_update').prepare(requested, source, destination)
def restore_firmware(root=Path('/')):
@@ -64,7 +76,8 @@ def restore_firmware(root=Path('/')):
def module(name):
- paths = {'t2_install': 't2_install.py', 't2_firmware': 'tools/prepare-t2-firmware.py'}
+ paths = {'t2_install': 't2_install.py', 't2_firmware': 'tools/prepare-t2-firmware.py',
+ 't2_update': 't2_update.py'}
if name not in paths:
raise ValueError('Unknown platform helper.')
path = Path(__file__).with_name(name + '.py')
diff --git a/os/platforms/apple-t2/README.md b/os/platforms/apple-t2/README.md
index 3d1c7e276..dee3aed3d 100644
--- a/os/platforms/apple-t2/README.md
+++ b/os/platforms/apple-t2/README.md
@@ -95,11 +95,35 @@ fresh verified bundle from `prepare-t2-kernel.py`. The output is named
`harness-t2-<version>-x86_64.iso`. The default PC build and its NVIDIA/Broadcom
bundle selection are unchanged.
-The initial image retains its pinned T2 kernel during ordinary Arch updates.
-An OS update must retain the T2 helpers and the identical kernel pin; older PC
-packages and a changed pin are refused before mutation. Automatic T2 kernel
-upgrades need a separately validated download/transaction path before this image
-can become a supported release. Do not add a moving unsigned repository.
+## Kernel updates and recovery
+
+Ordinary Arch updates retain the pinned T2 kernel. A Harness update can advance
+that pin through `t2_update.py`: it downloads and verifies both the old and new
+immutable upstream archives before changing any packages. Corrupt or missing
+inputs stop the update. The old archive is retained privately with the recovery
+receipt, and one pacman transaction installs the new kernel and matching Harness
+package. Verification reads back the installed kernel, required modules, early
+unlock drivers, initramfs and GRUB parameters. Apple firmware is restored from
+the computer's verified local copy. No headers, compiler or moving kernel
+repository are added.
+
+The running session stays alive; a restart activates the new kernel. Package
+rollback uses the retained old archive without network access, regenerates the
+matching boot files and verifies them. USB checkpoint recovery restores root and
+its exact boot files together while keeping newer home/project files. A failed
+transaction retains its original checkpoint and blocks another package update
+until rollback completes.
+
+An initial T2 installation must first receive an update that adds this capable
+updater while keeping its kernel pin unchanged. Older updaters deliberately refuse
+a changed pin. Do not publish a changed-pin update as that first migration or
+bypass the platform checks. No T2 kernel update has been published yet.
+
+The private **Harness OS T2 kernel update** workflow uses real pinned 7.2.7 and
+7.2.8 kernel packages, an explicitly constructed older-version Harness fixture,
+encrypted cold boots, interrupted transactions, offline rollback and USB recovery.
+It verifies running terminal process preservation and retained project files.
+Its synthetic Mac identity and firmware do not establish physical hardware support.
Upstream references: [maintained kernel](https://github.com/NoaHimesaka1873/linux-t2-arch),
[early input and kernel parameters](https://wiki.t2linux.org/guides/postinstall/),
diff --git a/os/release_update.py b/os/release_update.py
index ffceedd88..999808145 100644
--- a/os/release_update.py
+++ b/os/release_update.py
@@ -119,6 +119,7 @@ def apply(feed=FEED):
raise ValueError('Restore the previous Harness package before starting another system update.')
base = json.loads(LOCK.read_text())
updater.validate_bundle(folder, base)
+ updater.prepare_kernel_bundle(folder)
date = system.snapshot_date(manifest['arch_snapshot'])
text = system.PACMAN_CONFIG.read_text()
dates = set(re.findall(r'https://archive\.archlinux\.org/repos/(\d{4}/\d{2}/\d{2})/', text))
diff --git a/os/root/usr/share/harness-os/AGENTS.md b/os/root/usr/share/harness-os/AGENTS.md
index 9e5820b1b..080859eb7 100644
--- a/os/root/usr/share/harness-os/AGENTS.md
+++ b/os/root/usr/share/harness-os/AGENTS.md
@@ -91,8 +91,11 @@ is required.
`/boot/harness-apple-firmware.tar`. Firmware package hooks restore this data
automatically. Retain both copies; never upload them as diagnostic attachments.
Use the T2 USB for offline recovery. The current T2 kernel stays pinned during
- ordinary Arch updates; a changed kernel pin requires a separately verified
- upgrade path. Do not bypass the updater's platform checks or add a moving
+ ordinary Arch updates. Harness updates that change the pin stage and verify
+ both kernel archives before mutation and retain the old one for offline
+ rollback. The update receipt records both identities and the checkpoint.
+ Older updaters refuse a changed pin and first need an update with the same
+ pin that adds this capability. Do not bypass these checks or add a moving
kernel repository to work around a refused update.
- Ethernet uses NetworkManager automatically. For Wi-Fi, use
`Super+w` or `hn-os wifi`, which opens the Harness Wi-Fi form.
diff --git a/os/runtime_update.py b/os/runtime_update.py
index dac3a374a..fffde317a 100644
--- a/os/runtime_update.py
+++ b/os/runtime_update.py
@@ -24,7 +24,7 @@ LOCK = Path('/usr/share/harness-os/lock.json')
PACKAGE_DB = Path('/var/lib/pacman/local')
RESTART_REQUIRED = Path('/run/harness-os-restart-required')
BOOTSTRAP_FILES = ('apply-update.py', 'boot_profile.py', 't2_install.py',
- 't2_firmware.py', 'firmware_names.py')
+ 't2_firmware.py', 'firmware_names.py', 't2_update.py', 't2_kernel.py')
def digest(path):
@@ -148,7 +148,7 @@ def validate_bundle(folder, base):
if path.is_symlink() or not path.is_file() or package.get('bytes') != path.stat().st_size or digest(path) != package.get('sha256'):
raise ValueError('Package checksum or size mismatch; download the complete bundle again.')
inspect_package(path, version, runtime)
- boot_module().validate_update(path)
+ boot_module().validate_update(path, allow_kernel_change=True)
return manifest, path
@@ -159,6 +159,18 @@ def installed_version():
return value[1]
+def prepare_kernel_bundle(folder):
+ """Finish T2 downloads before the public updater advances any Arch packages."""
+ manifest = read_json(folder / 'package-manifest.json')
+ with tempfile.TemporaryDirectory(prefix='.kernels-', dir=folder) as temp:
+ staging = Path(temp)
+ change = boot_module().prepare_update(folder / manifest['package']['name'], folder, staging)
+ if change:
+ for pin in (change['previous'], change['candidate']):
+ name = pin['package']['filename']
+ (staging / name).replace(folder / name)
+
+
def verify_runtime(expected):
if read_json(RUNTIME) != expected:
raise ValueError('Installed runtime identity differs from the expected package.')
@@ -216,10 +228,10 @@ def latest():
return receipt
-def install_package(package, version, runtime):
+def install_package(package, version, runtime, additional=()):
# The caller already holds the system-operation lock and made its checkpoint.
# Keep pacman's own lock and other hooks; suppress only our duplicate checkpoint.
- subprocess.run(['pacman', '--noconfirm', '-U', str(package)], check=True,
+ subprocess.run(['pacman', '--noconfirm', '-U', *map(str, additional), str(package)], check=True,
env=dict(os.environ, HN_OS_UPDATE_CHECKPOINT='1'))
if installed_version() != version:
raise ValueError('The installed package version did not change as expected.')
@@ -245,32 +257,46 @@ def apply(folder, system, base, installation):
STATE.mkdir(parents=True, exist_ok=True, mode=0o700)
STATE.chmod(0o700)
# Copy before mutation; a user-owned download may change while it is being read.
- with tempfile.TemporaryDirectory(prefix='.incoming-', dir=STATE) as temp:
+ # Stage outside the root subvolume: a kernel download must not be copied
+ # into every root checkpoint in addition to the retained rollback package.
+ with tempfile.TemporaryDirectory(prefix='.harness-incoming-', dir=system.CHECKPOINTS) as temp:
incoming = Path(temp)
shutil.copyfile(source_package, incoming / source_package.name)
system.write_json(incoming / 'package-manifest.json', manifest)
validate_bundle(incoming, base)
+ kernel_change = boot.prepare_update(incoming / source_package.name, folder, incoming)
+ kernel = boot.module('t2_update') if kernel_change else None
checkpoint = system.checkpoint('before-harness-update')
identity = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ-') + uuid.uuid4().hex[:8]
saved = STATE / identity
saved.mkdir(mode=0o700)
backup = saved / 'previous.pkg.tar.gz'
package_backup(system.CHECKPOINTS / checkpoint / 'root', old_version, backup)
+ with backup.open('rb') as handle:
+ os.fsync(handle.fileno())
+ if kernel_change:
+ kernel.retain(kernel_change, incoming, saved)
receipt = {'id': identity, 'status': 'applying', 'started_at': now(),
'root_uuid': installation['root_uuid'], 'checkpoint': checkpoint,
'previous_version': old_version, 'previous_runtime': old_runtime,
'backup_sha256': digest(backup), 'candidate': manifest}
+ if kernel_change:
+ receipt['kernel_update'] = kernel_change
system.write_json(saved / 'receipt.json', receipt)
system.write_json(STATE / 'latest.json', {'id': identity})
try:
# The fast user updater must not mix a running old session with newly
# installed OS integration. /run clears this only on a real reboot.
system.write_json(RESTART_REQUIRED, {'status': 'applying', 'package': manifest['package']['version']})
- install_package(incoming / source_package.name, manifest['package']['version'], manifest['runtime'])
+ additional = [incoming / kernel_change['candidate']['package']['filename']] if kernel_change else []
+ install_package(incoming / source_package.name, manifest['package']['version'], manifest['runtime'], additional)
boot.restore_firmware()
# Plymouth and other initramfs assets may change without a kernel
# package transaction, so rebuild them on this path as well.
system.run('mkinitcpio', '-P')
+ if kernel_change:
+ system.run('grub-mkconfig', '-o', '/boot/grub/grub.cfg')
+ kernel.verify(kernel_change['candidate'], kernel_change['candidate_files'])
except BaseException:
receipt.update(status='failed', finished_at=now())
system.write_json(saved / 'receipt.json', receipt)
@@ -300,13 +326,21 @@ def rollback(system, installation):
# A legacy PC rollback removes the new platform helpers from disk. Retain
# the loaded helper until this transaction finishes using it.
boot = boot_module()
- boot.validate_update(backup)
+ change = receipt.get('kernel_update')
+ boot.validate_update(backup, allow_kernel_change=bool(change), kernel_rollback=bool(change))
+ kernel = boot.module('t2_update') if change else None
+ # Verify the retained archive and matching previous Harness pin before
+ # recording rollback or touching pacman's database. No network is needed.
+ additional = [kernel.rollback(change, folder, backup)] if change else []
receipt.update(status='rolling-back', rollback_started_at=now())
system.write_json(folder / 'receipt.json', receipt)
system.write_json(RESTART_REQUIRED, {'status': 'failed'})
- install_package(backup, receipt['previous_version'], receipt['previous_runtime'])
+ install_package(backup, receipt['previous_version'], receipt['previous_runtime'], additional)
boot.restore_firmware()
system.run('mkinitcpio', '-P')
+ if change:
+ system.run('grub-mkconfig', '-o', '/boot/grub/grub.cfg')
+ kernel.verify(change['previous'], change['previous_files'])
receipt.update(status='rolled-back', rollback_finished_at=now())
system.write_json(folder / 'receipt.json', receipt)
system.write_json(RESTART_REQUIRED, {'status': 'ready', 'package': receipt['previous_version']})
diff --git a/os/t2_update.py b/os/t2_update.py
new file mode 100644
index 000000000..e89cef6c3
--- /dev/null
+++ b/os/t2_update.py
@@ -0,0 +1,187 @@
+"""Stage a release-pinned T2 kernel and retain the old package for offline rollback."""
+import hashlib
+import importlib.util
+import json
+import os
+from pathlib import Path
+import re
+import shutil
+import subprocess
+import tarfile
+import time
+from urllib.request import Request, urlopen
+
+PIN = Path('usr/share/harness-os/apple-t2/kernel.json')
+CACHE = Path('/var/cache/pacman/pkg')
+UPSTREAM = 'https://github.com/NoaHimesaka1873/linux-t2-arch/releases/download/'
+
+
+def inspector():
+ path = Path(__file__).with_name('t2_kernel.py')
+ if not path.is_file():
+ path = Path(__file__).parent / 'tools/prepare-t2-kernel.py'
+ spec = importlib.util.spec_from_file_location('harness_t2_kernel', path)
+ value = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(value)
+ return value
+
+
+# A rollback may remove these helpers from the filesystem. Keep the complete
+# verifier loaded before pacman changes the installed Harness package.
+KERNEL = inspector()
+
+
+def validate_pin(pin):
+ if (not isinstance(pin, dict) or type(pin.get('schema')) is not int or pin['schema'] != 1
+ or pin.get('platform') != 'apple-t2' or pin.get('architecture') != 'x86_64'
+ or pin.get('pkgbase') != 'linux-t2'
+ or not re.fullmatch(r'[0-9A-Za-z.+_-]{1,128}', str(pin.get('kernel_release', '')))):
+ raise ValueError('Invalid T2 kernel identity.')
+ package = pin.get('package', {})
+ if (not isinstance(package, dict) or package.get('name') != 'linux-t2'
+ or not isinstance(package.get('version'), str)
+ or not re.fullmatch(r'[0-9A-Za-z.+_-]{1,80}', str(package.get('version', '')))
+ or package.get('filename') != 'linux-t2-' + package['version'] + '-x86_64.pkg.tar.zst'
+ or type(package.get('bytes')) is not int or not 0 < package['bytes'] <= 256 * 1024 * 1024
+ or not re.fullmatch(r'[a-f0-9]{64}', str(package.get('sha256', '')))):
+ raise ValueError('Invalid T2 kernel package identity.')
+ url = package.get('url', '')
+ suffix = url.removeprefix(UPSTREAM) if isinstance(url, str) else ''
+ if (not isinstance(url, str) or not url.startswith(UPSTREAM)
+ or not re.fullmatch(r'v[0-9A-Za-z.+_-]+/' + re.escape(package['filename']), suffix)):
+ raise ValueError('T2 kernel must use its pinned upstream release URL.')
+ modules = pin.get('required_modules')
+ early = pin.get('early_modules')
+ if (not isinstance(modules, list) or not 1 <= len(modules) <= 64
+ or any(not isinstance(x, str) or not re.fullmatch(r'[a-z0-9_]{1,64}', x) for x in modules)
+ or len(set(modules)) != len(modules) or not isinstance(early, list)
+ or early != ['t2bce_dma', 't2bce_core', 't2bce_vhci']
+ or not set(early) <= set(modules)
+ or pin.get('kernel_parameters') != ['intel_iommu=on', 'iommu=pt', 'pm_async=off']):
+ raise ValueError('T2 update changes the required boot platform.')
+ return pin
+
+
+def package_pin(package):
+ with tarfile.open(package, 'r:gz') as archive:
+ matches = [entry for entry in archive if entry.name == str(PIN)]
+ if len(matches) != 1 or not matches[0].isfile() or matches[0].size > 65536:
+ raise ValueError('Missing or ambiguous T2 kernel pin.')
+ return validate_pin(json.load(archive.extractfile(matches[0])))
+
+
+def download(pin, target):
+ """Stream a bounded, immutable package; never resolve an upstream 'latest'."""
+ expected = pin['package']
+ deadline = time.monotonic() + 180
+ size, checksum = 0, hashlib.sha256()
+ created = False
+ try:
+ with urlopen(Request(expected['url'], headers={'User-Agent': 'Harness-T2-Updates/1'}), timeout=30) as response:
+ if not response.url.startswith('https://'):
+ raise ValueError('T2 kernel download redirected away from HTTPS.')
+ with target.open('xb') as output:
+ created = True
+ while chunk := response.read(1024 * 1024):
+ size += len(chunk)
+ if size > expected['bytes'] or time.monotonic() > deadline:
+ raise ValueError('T2 kernel download exceeded its size or time limit.')
+ output.write(chunk)
+ checksum.update(chunk)
+ if size != expected['bytes'] or checksum.hexdigest() != expected['sha256']:
+ raise ValueError('T2 kernel download failed verification.')
+ except BaseException:
+ if created:
+ target.unlink(missing_ok=True)
+ raise
+
+
+def stage(pin, source, destination):
+ expected = pin['package']
+ name = expected['filename']
+ target = destination / name
+ supplied = source / name
+ cached = CACHE / name
+ if supplied.exists() or supplied.is_symlink():
+ # A malformed explicitly supplied package is an error, not a reason to
+ # ignore the owner's offline bundle and silently go to the network.
+ KERNEL.inspect(supplied, pin)
+ shutil.copyfile(supplied, target)
+ elif cached.is_file() and not cached.is_symlink() and KERNEL.identity(cached) == {
+ key: expected[key] for key in ('bytes', 'sha256')}:
+ shutil.copyfile(cached, target)
+ else:
+ download(pin, target)
+ selected = KERNEL.inspect(target, pin)
+ target.chmod(0o600)
+ return selected
+
+
+def prepare(requested, source, destination, root=Path('/')):
+ current = validate_pin(json.loads((root / PIN).read_text()))
+ requested = validate_pin(requested)
+ if requested == current:
+ return None
+ old, new = current['package'], requested['package']
+ if (int(subprocess.check_output(['vercmp', new['version'], old['version']], text=True)) <= 0
+ or requested['kernel_release'] == current['kernel_release']):
+ raise ValueError('T2 kernel updates must advance the pinned version and kernel release; use rollback to go back.')
+ installed = subprocess.check_output(['pacman', '-Q', 'linux-t2'], text=True).strip().split()
+ if installed != ['linux-t2', old['version']]:
+ raise ValueError('Installed T2 kernel differs from its release pin; repair it before updating.')
+ # Both downloads and complete archive inspections finish before a checkpoint
+ # or package mutation. The original package remains available without Wi-Fi.
+ previous_files = stage(current, source, destination)
+ candidate_files = stage(requested, source, destination)
+ return {'previous': current, 'candidate': requested,
+ 'previous_files': previous_files, 'candidate_files': candidate_files}
+
+
+def retain(change, incoming, saved):
+ old = change['previous']
+ target = saved / 'previous-kernel.pkg.tar.zst'
+ shutil.copyfile(incoming / old['package']['filename'], target)
+ target.chmod(0o600)
+ KERNEL.inspect(target, old)
+ with target.open('rb') as handle:
+ os.fsync(handle.fileno())
+
+
+def rollback(change, saved, package):
+ old = validate_pin(change['previous'])
+ if package_pin(package) != old:
+ raise ValueError('Harness rollback and retained T2 kernel differ.')
+ kernel = saved / 'previous-kernel.pkg.tar.zst'
+ if KERNEL.inspect(kernel, old) != change['previous_files']:
+ raise ValueError('Retained T2 kernel differs from the update checkpoint.')
+ return kernel
+
+
+def verify(pin, selected, root=Path('/')):
+ """Read back the installed kernel, required modules and generated initramfs."""
+ version = subprocess.check_output(['pacman', '-Q', 'linux-t2'], text=True).strip().split()
+ if version != ['linux-t2', pin['package']['version']] or json.loads((root / PIN).read_text()) != pin:
+ raise ValueError('Installed T2 kernel and Harness pin differ.')
+ for name, info in selected.items():
+ if name == '.PKGINFO':
+ continue
+ path = root / info['path']
+ if path.is_symlink() or not path.is_file() or KERNEL.identity(path) != {
+ key: info[key] for key in ('bytes', 'sha256')}:
+ raise ValueError('Installed T2 kernel/module failed readback: ' + name)
+ if KERNEL.identity(root / 'boot/vmlinuz-linux-t2') != {
+ key: selected['vmlinuz'][key] for key in ('bytes', 'sha256')}:
+ raise ValueError('T2 boot kernel differs from the installed package.')
+ release = pin['kernel_release']
+ for module in pin['required_modules']:
+ value = subprocess.check_output(['modinfo', '-k', release, '-F', 'vermagic', module], text=True).strip()
+ if not value.startswith(release + ' '):
+ raise ValueError('T2 module belongs to another kernel: ' + module)
+ image = root / 'boot/initramfs-linux-t2.img'
+ files = subprocess.check_output(['lsinitcpio', '--list', str(image)], text=True)
+ for module in pin['early_modules']:
+ if not re.search(r'/' + re.escape(module).replace('_', '[-_]') + r'\.ko(?:\.(?:zst|xz|gz))?(?:\n|$)', files):
+ raise ValueError('T2 unlock input module missing from initramfs: ' + module)
+ config = (root / 'boot/grub/grub.cfg').read_text()
+ if any(value not in config for value in pin['kernel_parameters']) or 'vmlinuz-linux-t2' not in config:
+ raise ValueError('T2 boot configuration omitted its kernel or required parameters.')
diff --git a/os/tests/release_update_vm.py b/os/tests/release_update_vm.py
index 5f37f803c..8ec5982b3 100644
--- a/os/tests/release_update_vm.py
+++ b/os/tests/release_update_vm.py
@@ -27,13 +27,15 @@ def exercise(vm, manifest, config):
'/usr/lib/harness-os/runtime_update.py /usr/lib/harness-os/system.py /usr/lib/harness-os/live_update.py '
'/usr/lib/harness-os/boot_profile.py /usr/lib/harness-os/t2_install.py '
'/usr/lib/harness-os/t2_firmware.py /usr/lib/harness-os/firmware_names.py '
+ '/usr/lib/harness-os/t2_update.py /usr/lib/harness-os/t2_kernel.py '
'/usr/lib/harness-os/open-updates /tmp/system-channel/; '
'sudo cat /etc/sudoers.d/30-harness-updates > /tmp/system-channel/30-harness-updates')
source = Path(__file__).resolve().parents[1]
helper_hashes = {}
helpers = {name: name for name in ['system.py', 'release_update.py', 'runtime_update.py',
- 'live_update.py', 'boot_profile.py', 't2_install.py']}
+ 'live_update.py', 'boot_profile.py', 't2_install.py', 't2_update.py']}
helpers.update({'t2_firmware.py': 'tools/prepare-t2-firmware.py',
+ 't2_kernel.py': 'tools/prepare-t2-kernel.py',
'firmware_names.py': 'platforms/apple-t2/firmware_names.py'})
for name, relative in helpers.items():
expected = hashlib.sha256((source / relative).read_bytes()).hexdigest()
@@ -101,7 +103,8 @@ metadata = dict(schema=1, channel='preview', architecture='x86_64',
# loopback feed; the shipped helper never accepts a user-owned feed cache.
# This case tests the candidate's combined action on the old package, after
# the independent real bootstrap/rollback checks. Its system updater must
- # match the new caller (the old update() has no noninteractive argument).
+ # match the new caller (the old update() has no noninteractive argument,
+ # and the old runtime updater has no kernel-prefetch API).
# Keep new dependencies in a root-owned private directory so pacman can
# install its actual files without an "exists in filesystem" collision.
baseline_system_sha256 = hashlib.sha256(vm.read_file('/usr/lib/harness-os/system.py')).hexdigest()
@@ -109,12 +112,16 @@ metadata = dict(schema=1, channel='preview', architecture='x86_64',
match = re.search(r'HN_UPDATE_BOOTSTRAP=(/tmp/harness-update-bootstrap\.[A-Za-z0-9]+)', output)
assert match, 'The private root bootstrap directory was not created'
bootstrap = match[1]
- for name in ['boot_profile.py', 't2_install.py', 't2_firmware.py', 'firmware_names.py']:
+ for name in ['boot_profile.py', 't2_install.py', 't2_firmware.py', 'firmware_names.py',
+ 't2_update.py', 't2_kernel.py']:
vm.command('sudo install -m 644 ' + shlex.quote('/tmp/system-channel/' + name) + ' ' + shlex.quote(bootstrap + '/' + name))
system_helper = relocate_boot_loader(vm.read_file('/tmp/system-channel/system.py').decode(), bootstrap)
+ runtime_helper = relocate_boot_loader(vm.read_file('/tmp/system-channel/runtime_update.py').decode(), bootstrap)
put(vm, '/tmp/system-channel/test-system-helper.py', system_helper)
+ put(vm, '/tmp/system-channel/test-runtime-helper.py', runtime_helper)
vm.command('sudo install -m 644 /tmp/system-channel/live_update.py /usr/lib/harness-os/live_update.py; '
'sudo install -m 644 /tmp/system-channel/test-system-helper.py /usr/lib/harness-os/system.py; '
+ 'sudo install -m 644 /tmp/system-channel/test-runtime-helper.py /usr/lib/harness-os/runtime_update.py; '
'sudo install -m 755 /tmp/system-channel/open-updates /usr/lib/harness-os/open-updates; '
# The old package does not own the new policy path. Use a
# fixture-only name so pacman can install its actual owned file
@@ -128,6 +135,7 @@ metadata = dict(schema=1, channel='preview', architecture='x86_64',
vm.command('sudo install -m 644 /tmp/system-channel/test-release-helper.py /usr/lib/harness-os/release_update.py; '
'sudo visudo -c -f /etc/sudoers')
for name, expected in [('system.py', hashlib.sha256(system_helper.encode()).hexdigest()),
+ ('runtime_update.py', hashlib.sha256(runtime_helper.encode()).hexdigest()),
('release_update.py', hashlib.sha256(helper.encode()).hexdigest())]:
assert hashlib.sha256(vm.read_file('/usr/lib/harness-os/' + name)).hexdigest() == expected, \
'The test helper was not activated: ' + name
@@ -176,6 +184,10 @@ metadata = dict(schema=1, channel='preview', architecture='x86_64',
'sha256': hashlib.sha256(system_helper.encode()).hexdigest(),
'boot_loader_directory': bootstrap,
'scope': 'Candidate system helper with only its boot dependency path relocated; real legacy upgrade and rollback are separate checks'}
+ public_retry['private_runtime_helper'] = {'path': '/usr/lib/harness-os/runtime_update.py',
+ 'sha256': hashlib.sha256(runtime_helper.encode()).hexdigest(),
+ 'boot_loader_directory': bootstrap,
+ 'scope': 'Candidate runtime updater with only its boot dependency path relocated; includes the required kernel-prefetch API'}
public_retry['private_feed_helper'] = {'path': '/usr/lib/harness-os/release_update.py',
'sha256': hashlib.sha256(helper.encode()).hexdigest()}
public_retry['fixture_sha256'] = fixture_hashes
diff --git a/os/tests/t2-kernel-before.json b/os/tests/t2-kernel-before.json
new file mode 100644
index 000000000..3fe6c886a
--- /dev/null
+++ b/os/tests/t2-kernel-before.json
@@ -0,0 +1,43 @@
+{
+ "schema": 1,
+ "platform": "apple-t2",
+ "architecture": "x86_64",
+ "package": {
+ "name": "linux-t2",
+ "version": "7.2.7.arch1-1",
+ "filename": "linux-t2-7.2.7.arch1-1-x86_64.pkg.tar.zst",
+ "url": "https://github.com/NoaHimesaka1873/linux-t2-arch/releases/download/v7.2.7.arch1/linux-t2-7.2.7.arch1-1-x86_64.pkg.tar.zst",
+ "bytes": 164003969,
+ "sha256": "1dade8bb396891f61018946b3b2d12dfbd3ac45110ac80cbb8ee6066c32d7f91"
+ },
+ "kernel_release": "7.2.7-arch1-Watanare-T2-1-t2",
+ "pkgbase": "linux-t2",
+ "source": {
+ "recipe_repository": "https://github.com/NoaHimesaka1873/linux-t2-arch",
+ "recipe_commit": "04fda9159aa85accbbe4238fa829ca5a133cb455",
+ "patch_repository": "https://github.com/t2linux/linux-t2-patches",
+ "patch_commit": "9e773c8876708924dd5e0e5d3093068a0f806ea1",
+ "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_update_guest.py b/os/tests/t2_update_guest.py
new file mode 100644
index 000000000..5ee7f8a52
--- /dev/null
+++ b/os/tests/t2_update_guest.py
@@ -0,0 +1,157 @@
+#!/usr/bin/env python3
+"""T2 update acceptance, only on the disposable encrypted HN_OS_TEST disk."""
+from functools import partial
+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
+import importlib.util
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+import threading
+import time
+
+
+def load(name, path):
+ spec = importlib.util.spec_from_file_location(name, path)
+ value = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(value)
+ return value
+
+
+def run(*args, check=True):
+ result = subprocess.run(list(map(str, args)), text=True, stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT, timeout=180)
+ print(result.stdout, flush=True)
+ if check and result.returncode:
+ raise RuntimeError('Command failed: ' + repr(args))
+ return result
+
+
+def main():
+ assert os.geteuid() == 0 and sys.platform == 'linux'
+ assert subprocess.check_output(['lsblk', '-dn', '-o', 'SERIAL', '/dev/vda'], text=True).strip() == 'HN_OS_TEST'
+ assert Path('/var/lib/harness-os/install.json').is_file() and not Path('/etc/harness-live').exists()
+ action, folder = sys.argv[1], Path(sys.argv[2]).resolve()
+ before, after = [json.loads((folder / (x + '.json')).read_text()) for x in ['before', 'after']]
+ manifest = json.loads((folder / 'package-manifest.json').read_text())
+ t2 = load('t2_update_fixture', folder / 't2_update.py')
+ preservation = load('t2_preservation_fixture', folder / 't2_install_guest.py')
+ updater = load('t2_runtime_fixture', folder / 'apply-update.py')
+ system = updater.system_module()
+ project = Path('/home/me/projects/t2-update-survivor')
+ if action == 'baseline':
+ for pin in [before, after]:
+ name = pin['package']['filename']
+ t2.KERNEL.inspect(folder / name, pin)
+ shutil.copyfile(folder / name, Path('/var/cache/pacman/pkg') / name)
+ baseline = folder / 'harness-os-0.1.0pre15.r1-1-x86_64.pkg.tar.gz'
+ run('pacman', '--noconfirm', '-U', folder / before['package']['filename'], baseline)
+ run('mkinitcpio', '-P')
+ run('grub-mkconfig', '-o', '/boot/grub/grub.cfg')
+ t2.verify(before, t2.KERNEL.inspect(folder / before['package']['filename'], before))
+ return dict(status='passed', **preservation.verify())
+
+ if action == 'verify-recovered':
+ assert (project / 'work.txt').read_text() == 'newer work survives kernel recovery\n'
+ assert run('pacman', '-Q', 'linux-t2').stdout.strip() == 'linux-t2 ' + before['package']['version']
+ t2.verify(before, t2.KERNEL.inspect(folder / before['package']['filename'], before))
+ return dict(status='passed', **preservation.verify())
+
+ if action == 'rollback':
+ latest = updater.latest()
+ assert latest['status'] == 'applied' and latest['kernel_update']['candidate'] == after
+ # No upstream cache or bundle kernel can rescue this rollback. It must
+ # use the independently retained original package with the recorded hash.
+ for pin in [before, after]:
+ (Path('/var/cache/pacman/pkg') / pin['package']['filename']).unlink(missing_ok=True)
+ run('python3', '/usr/lib/harness-os/runtime_update.py', 'rollback')
+ assert updater.latest()['status'] == 'rolled-back'
+ t2.verify(before, t2.KERNEL.inspect(folder / before['package']['filename'], before))
+ return dict(status='passed', **preservation.verify())
+
+ # A real user terminal keeps writing while root updates the kernel.
+ run('runuser', '-u', 'me', '--', 'mkdir', '-p', project)
+ script = project / 'heartbeat.py'
+ script.write_text("import os,pathlib,time\np=pathlib.Path(__file__).parent\n(p/'pid').write_text(str(os.getpid()))\nwhile True:\n with (p/'heartbeat').open('a') as f:f.write('alive\\n')\n time.sleep(.2)\n")
+ os.chown(script, 1000, 1000)
+ (project / 'pid').unlink(missing_ok=True)
+ run('runuser', '-u', 'me', '--', 'env', 'XDG_RUNTIME_DIR=/run/user/1000', 'hn',
+ 'new-window', '-n', 'kernel-survivor', 'python3 ' + str(script))
+ for _ in range(100):
+ if (project / 'pid').exists():
+ break
+ time.sleep(.1)
+ pid = int((project / 'pid').read_text())
+ process_start = Path(f'/proc/{pid}/stat').read_text().split()[21]
+ hn_pid = subprocess.check_output(['pgrep', '-u', '1000', '-xo', 'hn|harness-tui'], text=True).strip()
+ def alive():
+ assert Path(f'/proc/{pid}/stat').read_text().split()[21] == process_start
+ size = (project / 'heartbeat').stat().st_size
+ time.sleep(.5)
+ assert (project / 'heartbeat').stat().st_size > size
+ assert subprocess.check_output(['pgrep', '-u', '1000', '-xo', 'hn|harness-tui'], text=True).strip() == hn_pid
+ before_boot = system.boot_hashes(Path('/boot'))
+ original = preservation.verify()
+
+ if action == 'exercise':
+ broken = folder / 'broken'
+ broken.mkdir()
+ for name in ['package-manifest.json', manifest['package']['name'], before['package']['filename']]:
+ shutil.copyfile(folder / name, broken / name)
+ (broken / after['package']['filename']).write_bytes(b'corrupt kernel fixture')
+ prior = updater.latest()
+ result = run('python3', folder / 'apply-update.py', 'apply', broken, check=False)
+ assert result.returncode and 'pinned artifact' in result.stdout
+ assert updater.latest() == prior and system.boot_hashes(Path('/boot')) == before_boot
+ alive()
+ hook = Path('/etc/pacman.d/hooks/00-t2-update-failure.hook')
+ hook.write_text('[Trigger]\nOperation = Upgrade\nType = Package\nTarget = harness-os\n[Action]\nDescription = Disposable failure fixture\nWhen = PreTransaction\nExec = /usr/bin/false\nAbortOnFail\n')
+ try:
+ assert run('python3', folder / 'apply-update.py', 'apply', folder, check=False).returncode
+ finally:
+ hook.unlink()
+ failed = updater.latest()
+ assert failed['status'] == 'failed' and failed['kernel_update']['previous'] == before
+ assert run('python3', folder / 'apply-update.py', 'apply', folder, check=False).returncode
+ assert updater.latest() == failed
+ run('python3', folder / 'apply-update.py', 'rollback')
+ alive()
+
+ # The installed public-channel implementation is unmodified. Only its
+ # documented development feed points to this guest's private HTTP fixture.
+ for pin in [before, after]:
+ shutil.copyfile(folder / pin['package']['filename'], Path('/var/cache/pacman/pkg') / pin['package']['filename'])
+ server = ThreadingHTTPServer(('127.0.0.1', 0), partial(SimpleHTTPRequestHandler, directory=str(folder)))
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ url = f'http://127.0.0.1:{server.server_port}/'
+ def asset(name):
+ path = folder / name
+ return dict(url=url + name, **t2.KERNEL.identity(path))
+ metadata = dict(schema=1, channel='preview', architecture='x86_64',
+ manifest=asset('package-manifest.json'), package=asset(manifest['package']['name']))
+ (folder / 'metadata.json').write_text(json.dumps(metadata))
+ try:
+ started = time.monotonic()
+ run('python3', '/usr/lib/harness-os/release_update.py', 'apply', '--feed', url + 'metadata.json')
+ seconds = time.monotonic() - started
+ finally:
+ server.shutdown()
+ server.server_close()
+ alive()
+ latest = updater.latest()
+ assert latest['status'] == 'applied' and latest['kernel_update']['candidate'] == after
+ assert run('pacman', '-Q', 'harness-os').stdout.strip() == 'harness-os ' + manifest['package']['version']
+ assert json.loads(Path('/usr/share/harness-os/runtime.json').read_text()) == manifest['runtime']
+ t2.verify(after, t2.KERNEL.inspect(folder / after['package']['filename'], after))
+ assert preservation.verify()['firmware_sha256'] == original['firmware_sha256']
+ (project / 'work.txt').write_text('newer work survives kernel recovery\n')
+ return dict(status='passed', checkpoint=latest['checkpoint'], before_boot_sha256=before_boot,
+ firmware_sha256=original['firmware_sha256'], apply_seconds=round(seconds, 3),
+ survivor_pid=pid, survivor_start=process_start, harness_pid=hn_pid,
+ kernel_update=latest['kernel_update'])
+
+
+if __name__ == '__main__':
+ print('T2_RESULT=' + json.dumps(main()), flush=True)
diff --git a/os/tests/t2_update_vm.py b/os/tests/t2_update_vm.py
new file mode 100644
index 000000000..ee7b843cc
--- /dev/null
+++ b/os/tests/t2_update_vm.py
@@ -0,0 +1,198 @@
+#!/usr/bin/env python3
+"""Actual T2 kernel upgrade, rollback and recovery; no physical Mac claim."""
+import argparse
+from functools import partial
+import hashlib
+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
+import io
+import json
+import os
+from pathlib import Path
+import re
+import shlex
+import shutil
+import subprocess
+import tarfile
+import threading
+import time
+
+from footprint_vm import copy_file
+from hardware_update_vm import graceful_stop
+from session_vm import screen_text
+from t2_install_vm import guest_result
+from test_t2_firmware import firmware, source_fixture
+from vm import VM, check_graphical_keyboard
+
+
+def identity(path):
+ with path.open('rb') as stream:
+ return {'bytes': path.stat().st_size, 'sha256': hashlib.file_digest(stream, 'sha256').hexdigest()}
+
+
+def baseline_package(candidate, target, pin):
+ """An explicit private prior-version fixture, retaining the exact new updater."""
+ with tarfile.open(candidate, 'r:gz') as original, tarfile.open(target, 'w:gz') as output:
+ for entry in original:
+ data = original.extractfile(entry).read() if entry.isfile() else None
+ if entry.name == '.PKGINFO':
+ data = re.sub(rb'(?m)^pkgver = .+$', b'pkgver = 0.1.0pre15.r1-1', data)
+ elif entry.name == 'usr/share/harness-os/apple-t2/kernel.json':
+ data = (json.dumps(pin, indent=2) + '\n').encode()
+ if data is not None:
+ entry.size = len(data)
+ output.addfile(entry, io.BytesIO(data) if data is not None else None)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--iso', required=True, type=Path)
+ parser.add_argument('--bundle', required=True, type=Path)
+ parser.add_argument('--kernels', required=True, type=Path)
+ parser.add_argument('--output', required=True, type=Path)
+ args = parser.parse_args()
+ assert os.access('/dev/kvm', os.R_OK | os.W_OK), 'Native KVM is required'
+ source = subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip()
+ assert not subprocess.check_output(['git', 'status', '--porcelain'], text=True).strip()
+ iso, folder = args.iso.resolve(), args.output.absolute()
+ image = json.loads(iso.with_name('manifest.json').read_text())
+ assert image['platform'] == 'apple-t2'
+ assert image['source_commit'] == '59a0b7f75e31e0c3ed13af2105895db8d4665018'
+ assert identity(iso) == {'bytes': 1536999424, 'sha256': '375d333e13fcbac3724b807f030980c3a4121dbcc4c82659ead52709bb682afa'}
+ manifest = json.loads((args.bundle / 'package-manifest.json').read_text())
+ assert manifest['source_commit'] == source
+ expected = {'harness-tui': 'bd221059a24d7f7ca8ce69bb3b6d69c2fb66cb655aae6658627c278a548a8fa8',
+ 'cli.mjs': '23b46a7c498fd1ef8ff5936aeb431f1de08b959b957141fa732d2cede870d147',
+ 'notify.mjs': '5690159e964f9ce022bdb2a5e4bc9d853e595e822f254478df241e1386dde68e'}
+ assert {name: value['sha256'] for name, value in manifest['runtime']['files'].items()} == expected
+ before = json.loads(Path(__file__).with_name('t2-kernel-before.json').read_text())
+ after = json.loads((Path(__file__).parents[1] / 'platforms/apple-t2/kernel.json').read_text())
+ folder.mkdir(parents=True, exist_ok=False)
+ served = folder / 'served'
+ shutil.copytree(args.bundle, served)
+ for pin in (before, after):
+ package = pin['package']
+ original = args.kernels / package['filename']
+ assert identity(original) == {key: package[key] for key in ['bytes', 'sha256']}
+ shutil.copyfile(original, served / package['filename'])
+ (served / 'before.json').write_text(json.dumps(before))
+ (served / 'after.json').write_text(json.dumps(after))
+ baseline = served / 'harness-os-0.1.0pre15.r1-1-x86_64.pkg.tar.gz'
+ baseline_package(served / manifest['package']['name'], baseline, before)
+ for name in ['t2_update_guest.py', 't2_install_guest.py']:
+ shutil.copyfile(Path(__file__).with_name(name), served / name)
+ source_fixture(folder / 'synthetic-firmware')
+ firmware.prepare(folder / 'synthetic-firmware', served / 'harness-apple-firmware.tar', 'MacBookAir9,1')
+ server = ThreadingHTTPServer(('127.0.0.1', 0), partial(SimpleHTTPRequestHandler, directory=str(served)))
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ record = {'status': 'running', 'started_at': time.time(), 'source_commit': source,
+ 'image': image['iso'], 'image_source': image['source_commit'], 'candidate': manifest,
+ 'before': before, 'after': after, 'baseline_package': identity(baseline), 'checks': [],
+ 'limits': ['Synthetic DMI and invented firmware; no physical T2 hardware is emulated.',
+ 'Prior-version fixture changes only candidate .PKGINFO version and kernel pin.',
+ 'Shared runtime is byte-identical public preview14; no shared product release.',
+ 'Historical ISO installs the baseline; this does not validate a new ISO.']}
+ vm = VM(folder, iso, 'uefi', 2048, cpu='Haswell-noTSX', apple_model='MacBookAir9,1')
+ 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)
+ guest = '/home/me/t2-update'
+
+ def installed(label, pin):
+ 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')
+ vm.command('test "$(uname -r)" = ' + shlex.quote(pin['kernel_release']))
+ record[label + '_boot_id'] = vm.read_file('/proc/sys/kernel/random/boot_id').decode().strip()
+ for _ in range(60):
+ text = screen_text(vm, label + '-workspace')
+ if 'me@harness' in re.sub(r'\s+', '', text):
+ break
+ if 'connect to wi-fi' in text:
+ vm.keys('meta_l', 't')
+ break
+ time.sleep(.5)
+ else:
+ raise TimeoutError('Offline workspace never rendered')
+ record[label + '_keyboard'] = check_graphical_keyboard(vm, label)
+
+ def probe(action, timeout=360):
+ output, _ = vm.command('sudo -n python3 ' + guest + '/t2_update_guest.py ' + action + ' ' + guest, timeout=timeout)
+ (folder / (action + '.log')).write_text(output)
+ result = guest_result(output)
+ record[action] = result
+ return result
+
+ 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; mkdir -p /var/lib/harness-os')
+ copy_file(vm, (served / 'harness-apple-firmware.tar').read_bytes(), '/var/lib/harness-os/apple-firmware.tar')
+ copy_file(vm, json.dumps(config).encode(), '/tmp/install.json')
+ output, _ = vm.command('harness install --config /tmp/install.json --yes-erase-disk', timeout=420)
+ (folder / 'install.log').write_text(output)
+ graceful_stop(vm, False)
+ installed('image', after)
+ vm.monitor('set_link', name='hnnet', up=True)
+ vm.command('sudo -n nmcli networking on')
+ vm.command('nm-online --quiet --timeout=30', timeout=40)
+ vm.command('mkdir -p ' + guest)
+ url = f'http://10.0.2.2:{server.server_port}'
+ for file in served.iterdir():
+ if file.is_file():
+ vm.command('curl -fsS --retry 3 --max-time 90 ' + shlex.quote(url + '/' + file.name) +
+ ' -o ' + shlex.quote(guest + '/' + file.name), timeout=100)
+ vm.command('sudo -n nmcli networking off')
+ vm.monitor('set_link', name='hnnet', up=False)
+ probe('baseline')
+ graceful_stop(vm, True)
+ installed('before', before)
+ first = probe('exercise', 480)
+ graceful_stop(vm, True)
+ installed('updated', after)
+ probe('rollback')
+ graceful_stop(vm, True)
+ installed('rolled-back', before)
+ restore = probe('reapply')
+ graceful_stop(vm, True)
+ 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')
+ vm.command('printf %s ' + shlex.quote(config['password']) + ' | cryptsetup open --key-file=- /dev/vda3 hn-recovery')
+ output, _ = vm.command('hn-os recover /dev/mapper/hn-recovery ' + shlex.quote(restore['checkpoint']), timeout=180)
+ (folder / 'offline-recovery.log').write_text(output)
+ vm.command('cryptsetup close hn-recovery')
+ graceful_stop(vm, False)
+ installed('recovered', before)
+ recovered = probe('verify-recovered')
+ assert recovered['boot_sha256'] == restore['before_boot_sha256']
+ assert recovered['firmware_sha256'] == first['firmware_sha256']
+ assert len({record[x + '_boot_id'] for x in ['before', 'updated', 'rolled-back', 'recovered']}) == 4
+ record['checks'] = ['Offline encrypted installation from the historical T2 ISO.',
+ 'Actual 7.2.7 kernel baseline cold-boots and accepts graphical input.',
+ 'Corrupt candidate and a failed package transaction retain original recovery and running work.',
+ 'The release updater stages both real kernels, upgrades 7.2.7 to 7.2.8 and cold-boots through unlock.',
+ 'Installed updater rolls back completely offline to 7.2.7 and cold-boots through unlock.',
+ 'Offline USB recovery restores exact old boot hashes and private firmware while newer project work survives.']
+ graceful_stop(vm, True)
+ record['status'] = 'passed'
+ except BaseException as error:
+ record.update(status='failed', error=repr(error))
+ if vm.process and vm.process.poll() is None:
+ vm.screenshot('failure')
+ raise
+ finally:
+ record['finished_at'] = time.time()
+ (folder / 'receipt.json').write_text(json.dumps(record, indent=2) + '\n')
+ vm.stop()
+ server.shutdown()
+ server.server_close()
+ shutil.rmtree(served)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/os/tests/test_boot_profile.py b/os/tests/test_boot_profile.py
index 1fb841b0e..4b052c9c0 100644
--- a/os/tests/test_boot_profile.py
+++ b/os/tests/test_boot_profile.py
@@ -23,12 +23,15 @@ class BootProfiles(unittest.TestCase):
pin.parent.mkdir(parents=True)
pin.write_text('{"kernel_release":"tested"}')
package = root / 'package.tar.gz'
- def archive(version, helpers=True):
+ def archive(version, helpers=True, kernel_helpers=False):
with tarfile.open(package, 'w:gz') as output:
entries = {'usr/share/harness-os/apple-t2/kernel.json': json.dumps({'kernel_release': version}).encode()}
if helpers:
entries.update({'usr/lib/harness-os/' + name + '.py': b'fixture' for name in
['boot_profile', 't2_install', 't2_firmware', 'firmware_names']})
+ if kernel_helpers:
+ entries.update({'usr/lib/harness-os/' + name + '.py': b'fixture' for name in
+ ['t2_update', 't2_kernel']})
for name, data in entries.items():
info = tarfile.TarInfo(name)
info.size = len(data)
@@ -38,6 +41,13 @@ class BootProfiles(unittest.TestCase):
archive('untested')
with self.assertRaisesRegex(ValueError, 'different T2 kernel'):
boot.validate_update(package, root)
+ with self.assertRaisesRegex(ValueError, 'transaction helpers'):
+ boot.validate_update(package, root, allow_kernel_change=True)
+ archive('untested', kernel_helpers=True)
+ self.assertEqual(boot.validate_update(package, root, allow_kernel_change=True), {'kernel_release': 'untested'})
+ archive('untested')
+ self.assertEqual(boot.validate_update(package, root, allow_kernel_change=True, kernel_rollback=True),
+ {'kernel_release': 'untested'})
archive('tested', False)
with self.assertRaisesRegex(ValueError, 'does not include the T2 platform'):
boot.validate_update(package, root)
diff --git a/os/tests/test_release_update.py b/os/tests/test_release_update.py
index 763e540fa..78283dfa8 100644
--- a/os/tests/test_release_update.py
+++ b/os/tests/test_release_update.py
@@ -135,6 +135,7 @@ class ReleaseChannel(unittest.TestCase):
self.assertEqual(folder.stat().st_mode & 0o777, 0o700)
self.events.append(('harness', folder))
return SimpleNamespace(system_module=lambda: system, validate_bundle=Mock(),
+ prepare_kernel_bundle=Mock(),
validate_base=update.load_runtime_updater().validate_base, latest=lambda: None, apply=apply)
def test_root_download_is_private_and_full_base_upgrade_precedes_package_application(self):
@@ -155,6 +156,14 @@ class ReleaseChannel(unittest.TestCase):
self.assertEqual(self.events, [])
updater.validate_bundle.assert_not_called()
+ def test_kernel_preparation_failure_leaves_arch_and_harness_unchanged(self):
+ updater = self.fake_updater()
+ updater.prepare_kernel_bundle.side_effect = ValueError('T2 kernel download failed verification')
+ with patch.object(update.os, 'geteuid', return_value=0), patch.object(update, 'load_runtime_updater', return_value=updater):
+ with self.assertRaisesRegex(ValueError, 'T2 kernel download'):
+ update.apply(self.url + '/metadata.json')
+ self.assertEqual(self.events, [])
+
def test_public_base_upgrade_completes_without_terminal_input(self):
updater = self.fake_updater()
public_system = updater.system_module()
diff --git a/os/tests/test_release_update_fixture.py b/os/tests/test_release_update_fixture.py
index 4c94e1f7a..8a90b0f14 100644
--- a/os/tests/test_release_update_fixture.py
+++ b/os/tests/test_release_update_fixture.py
@@ -33,6 +33,27 @@ class ReleaseUpdateFixture(unittest.TestCase):
with self.assertRaises(ValueError):
relocate_boot_loader(changed, '/tmp/unused')
+ def test_relocated_release_helper_loads_complete_runtime_prefetch_api(self):
+ source = Path(__file__).resolve().parents[1]
+ with tempfile.TemporaryDirectory() as temporary:
+ root = Path(temporary)
+ dependencies = root / 'dependencies'
+ dependencies.mkdir()
+ shutil.copyfile(source / 'boot_profile.py', dependencies / 'boot_profile.py')
+ original = (source / 'runtime_update.py').read_text()
+ relocated = relocate_boot_loader(original, dependencies)
+ self.assertEqual(relocated.replace('Path(' + repr(str(dependencies / 'boot_profile.py')) + ')',
+ "Path(__file__).with_name('boot_profile.py')"), original)
+ (root / 'runtime_update.py').write_text(relocated)
+ shutil.copyfile(source / 'release_update.py', root / 'release_update.py')
+ spec = importlib.util.spec_from_file_location('candidate_release_fixture', root / 'release_update.py')
+ release = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(release)
+ updater = release.load_runtime_updater()
+ self.assertTrue(callable(updater.prepare_kernel_bundle))
+ self.assertEqual(Path(updater.__file__), root / 'runtime_update.py')
+ self.assertEqual(Path(updater.boot_module().__file__), dependencies / 'boot_profile.py')
+
if __name__ == '__main__':
unittest.main()
diff --git a/os/tests/test_runtime_update.py b/os/tests/test_runtime_update.py
index 22cdd74e4..c3cefa033 100644
--- a/os/tests/test_runtime_update.py
+++ b/os/tests/test_runtime_update.py
@@ -73,6 +73,17 @@ class BundleGuards(unittest.TestCase):
helper = standalone.boot_module().module('t2_install').helper()
helper.check_model('MacBookAir9,1')
self.assertEqual(Path(helper.__file__).parent, folder)
+ kernel = standalone.boot_module().module('t2_update').KERNEL
+ self.assertEqual(Path(kernel.__file__).parent, folder)
+
+ def test_kernel_and_harness_use_one_pacman_transaction(self):
+ kernel = self.root / 'linux-t2.pkg.tar.zst'
+ with patch.object(update.subprocess, 'run') as run, \
+ patch.object(update, 'installed_version', return_value=self.version), \
+ patch.object(update, 'verify_runtime'):
+ update.install_package(self.package, self.version, self.runtime, [kernel])
+ run.assert_called_once()
+ self.assertEqual(run.call_args.args[0], ['pacman', '--noconfirm', '-U', str(kernel), str(self.package)])
def test_legacy_rollback_completes_after_package_removes_platform_helper(self):
folder = self.root / 'installed'
diff --git a/os/tests/test_t2_update.py b/os/tests/test_t2_update.py
new file mode 100644
index 000000000..b71063410
--- /dev/null
+++ b/os/tests/test_t2_update.py
@@ -0,0 +1,173 @@
+import copy
+import hashlib
+import importlib.util
+import io
+import json
+from pathlib import Path
+import subprocess
+import tarfile
+import tempfile
+import unittest
+from unittest.mock import patch
+
+spec = importlib.util.spec_from_file_location('t2_update', Path(__file__).parents[1] / 't2_update.py')
+t2 = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(t2)
+
+
+class T2Updates(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.root = Path(self.temp.name)
+ self.source, self.staging, self.saved = [self.root / x for x in ['source', 'staging', 'saved']]
+ for path in [self.source, self.staging, self.saved]:
+ path.mkdir()
+ self.old = self.kernel('7.2.7')
+ self.new = self.kernel('7.2.8')
+ (self.root / t2.PIN).parent.mkdir(parents=True)
+ (self.root / t2.PIN).write_text(json.dumps(self.old))
+
+ def kernel(self, version):
+ pin = copy.deepcopy(json.loads((Path(__file__).parents[1] / 'platforms/apple-t2/kernel.json').read_text()))
+ pin['kernel_release'] = version + '-test-t2'
+ package = pin['package']
+ package.update(version=version + '-1', filename='linux-t2-' + version + '-1-x86_64.pkg.tar.zst')
+ package['url'] = t2.UPSTREAM + 'v' + version + '/' + package['filename']
+ prefix = 'usr/lib/modules/' + pin['kernel_release'] + '/'
+ files = {'.PKGINFO': ('pkgname = linux-t2\npkgbase = linux-t2\npkgver = ' + version + '-1\narch = x86_64\n').encode(),
+ prefix + 'pkgbase': b'linux-t2\n', prefix + 'vmlinuz': bytes(0x202) + b'HdrS' + version.encode()}
+ for name in pin['required_modules']:
+ files[prefix + 'kernel/' + name + '.ko.zst'] = (version + name).encode()
+ raw = self.root / (version + '.tar')
+ with tarfile.open(raw, 'w') as output:
+ for name, data in files.items():
+ member = tarfile.TarInfo(name)
+ member.mode, member.size = 0o644, len(data)
+ output.addfile(member, io.BytesIO(data))
+ path = self.source / package['filename']
+ subprocess.run(['zstd', '-q', str(raw), '-o', str(path)], check=True, timeout=10)
+ package.update(t2.KERNEL.identity(path))
+ return pin
+
+ def commands(self, argv, **kwargs):
+ if argv[0] == 'vercmp':
+ return '1\n'
+ if argv == ['pacman', '-Q', 'linux-t2']:
+ return 'linux-t2 ' + self.old['package']['version'] + '\n'
+ raise AssertionError(argv)
+
+ def prepare(self):
+ with patch.object(t2.subprocess, 'check_output', side_effect=self.commands), \
+ patch.object(t2, 'download', side_effect=AssertionError('Offline bundle must not use network')):
+ return t2.prepare(self.new, self.source, self.staging, self.root)
+
+ def harness_package(self, pin):
+ target = self.root / 'previous-harness.pkg.tar.gz'
+ with tarfile.open(target, 'w:gz') as output:
+ data = json.dumps(pin).encode()
+ member = tarfile.TarInfo(str(t2.PIN))
+ member.size = len(data)
+ output.addfile(member, io.BytesIO(data))
+ return target
+
+ def test_offline_staging_and_retained_rollback_verify_real_archives(self):
+ change = self.prepare()
+ self.assertEqual(change['candidate'], self.new)
+ self.assertEqual(change['previous'], self.old)
+ self.assertEqual(set(change['candidate_files']), {'.PKGINFO', 'pkgbase', 'vmlinuz', *self.new['required_modules']})
+ self.assertEqual((self.staging / self.new['package']['filename']).stat().st_mode & 0o777, 0o600)
+ t2.retain(change, self.staging, self.saved)
+ package = self.harness_package(self.old)
+ with patch.object(t2, 'download', side_effect=AssertionError('Rollback must remain offline')):
+ previous = t2.rollback(change, self.saved, package)
+ self.assertEqual(t2.KERNEL.identity(previous), t2.KERNEL.identity(self.source / self.old['package']['filename']))
+ previous.write_bytes(b'corrupt rollback')
+ with self.assertRaisesRegex(ValueError, 'pinned artifact'):
+ t2.rollback(change, self.saved, package)
+
+ def test_corrupt_supplied_kernel_cannot_be_used_or_silently_downloaded(self):
+ (self.source / self.new['package']['filename']).write_bytes(b'incomplete')
+ with self.assertRaisesRegex(ValueError, 'pinned artifact'):
+ self.prepare()
+
+ def test_rollback_refuses_an_unrelated_harness_kernel_pin(self):
+ change = self.prepare()
+ t2.retain(change, self.staging, self.saved)
+ with self.assertRaisesRegex(ValueError, 'rollback and retained'):
+ t2.rollback(change, self.saved, self.harness_package(self.new))
+
+ def test_unchanged_pin_does_not_download_and_downgrade_is_refused(self):
+ with patch.object(t2, 'stage', side_effect=AssertionError('No download')), \
+ patch.object(t2.subprocess, 'check_output', return_value='-1'):
+ self.assertIsNone(t2.prepare(self.old, self.source, self.staging, self.root))
+ with self.assertRaisesRegex(ValueError, 'advance the pinned'):
+ t2.prepare(self.new, self.source, self.staging, self.root)
+
+ def test_malformed_download_identity_and_boot_contract_are_rejected(self):
+ changes = [lambda p: p['package'].update(name='linux-lts'),
+ lambda p: p['package'].update(filename='../elsewhere'),
+ lambda p: p['package'].update(bytes=True),
+ lambda p: p['package'].update(bytes=257 * 1024 * 1024),
+ lambda p: p['package'].update(url='file:///etc/passwd'),
+ lambda p: p['package'].update(url=p['package']['url'].replace('github.com/', 'github.com.evil.test/')),
+ lambda p: p.update(early_modules=['brcmfmac']),
+ lambda p: p.update(kernel_parameters=['init=/bin/sh'])]
+ for change in changes:
+ pin = copy.deepcopy(self.new)
+ change(pin)
+ with self.subTest(pin=pin), self.assertRaises(ValueError):
+ t2.validate_pin(pin)
+
+ def test_streamed_download_rejects_corruption_truncation_and_http_redirect(self):
+ good = (self.source / self.new['package']['filename']).read_bytes()
+ for data, url in [(good, self.new['package']['url']), (b'wrong', self.new['package']['url']),
+ (good + b'extra', self.new['package']['url']), (good, 'http://example.test/file')]:
+ response = io.BytesIO(data)
+ response.url = url
+ target = self.staging / 'download.pkg.tar.zst'
+ with patch.object(t2, 'urlopen', return_value=response):
+ if data == good and url.startswith('https://'):
+ t2.download(self.new, target)
+ self.assertEqual(target.read_bytes(), good)
+ target.unlink()
+ else:
+ with self.assertRaises(ValueError):
+ t2.download(self.new, target)
+ self.assertFalse(target.exists())
+
+ def test_readback_detects_missing_unlock_module_and_altered_kernel(self):
+ change = self.prepare()
+ selected = change['candidate_files']
+ raw = self.root / '7.2.8.tar'
+ # Extract only the invented fixture files into this disposable test root.
+ with tarfile.open(raw) as archive:
+ for member in archive:
+ if member.name == '.PKGINFO':
+ continue
+ target = self.root / member.name
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(archive.extractfile(member).read())
+ (self.root / t2.PIN).write_text(json.dumps(self.new))
+ boot = self.root / 'boot'
+ (boot / 'grub').mkdir(parents=True)
+ (boot / 'vmlinuz-linux-t2').write_bytes((self.root / selected['vmlinuz']['path']).read_bytes())
+ (boot / 'grub/grub.cfg').write_text('vmlinuz-linux-t2 ' + ' '.join(self.new['kernel_parameters']))
+ files = ''.join('/' + name + '.ko.zst\n' for name in self.new['early_modules'])
+ def command(argv, **kwargs):
+ if argv[0] == 'pacman': return 'linux-t2 ' + self.new['package']['version']
+ if argv[0] == 'modinfo': return self.new['kernel_release'] + ' SMP preempt '
+ if argv[0] == 'lsinitcpio': return files
+ raise AssertionError(argv)
+ with patch.object(t2.subprocess, 'check_output', side_effect=command):
+ t2.verify(self.new, selected, self.root)
+ files = ''
+ with self.assertRaisesRegex(ValueError, 'unlock input module missing'):
+ t2.verify(self.new, selected, self.root)
+ (boot / 'vmlinuz-linux-t2').write_bytes(b'wrong kernel')
+ with self.assertRaisesRegex(ValueError, 'boot kernel differs'):
+ t2.verify(self.new, selected, self.root)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/os/tools/build-package.py b/os/tools/build-package.py
index 4054beb8f..a43c2e16c 100644
--- a/os/tools/build-package.py
+++ b/os/tools/build-package.py
@@ -50,6 +50,8 @@ def stage(source, runtime, destination, commit):
'os/system.py': 'usr/lib/harness-os/system.py',
'os/boot_profile.py': 'usr/lib/harness-os/boot_profile.py',
'os/t2_install.py': 'usr/lib/harness-os/t2_install.py',
+ 'os/t2_update.py': 'usr/lib/harness-os/t2_update.py',
+ 'os/tools/prepare-t2-kernel.py': 'usr/lib/harness-os/t2_kernel.py',
'os/tools/prepare-t2-firmware.py': 'usr/lib/harness-os/t2_firmware.py',
'os/platforms/apple-t2/firmware_names.py': 'usr/lib/harness-os/firmware_names.py',
'os/platforms/apple-t2/kernel.json': 'usr/share/harness-os/apple-t2/kernel.json',
@@ -124,7 +126,8 @@ def bootstrap(source, folder):
"""Ship every helper needed before the first platform-aware OS package."""
files = {'apply-update.py': 'runtime_update.py', 'boot_profile.py': 'boot_profile.py',
't2_install.py': 't2_install.py', 't2_firmware.py': 'tools/prepare-t2-firmware.py',
- 'firmware_names.py': 'platforms/apple-t2/firmware_names.py'}
+ 'firmware_names.py': 'platforms/apple-t2/firmware_names.py',
+ 't2_update.py': 't2_update.py', 't2_kernel.py': 'tools/prepare-t2-kernel.py'}
spec = importlib.util.spec_from_file_location('bootstrap_runtime', source / 'os/runtime_update.py')
updater = importlib.util.module_from_spec(spec)
spec.loader.exec_module(updater)