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
test(os): verify one-action updates from the original preview 14 installation (#833)
Dee1826cdef72c3
diff --git a/.github/workflows/os.yml b/.github/workflows/os.ymlindex 49512ed8c..a5c8f9f15 100644--- a/.github/workflows/os.yml+++ b/.github/workflows/os.yml@@ -51,7 +51,7 @@ on:required: falsedefault: imagetype: choice- options: [image, browser, browser-suspend, session, recovery, essentials, hardware, zram, hardware-update]+ options: [image, browser, browser-suspend, session, recovery, essentials, hardware, zram, hardware-update, public-update]browser_memory:description: 'With checks=browser, diagnose memory in the UEFI VM only; retain ordinary workload and deadlines'required: false@@ -66,12 +66,12 @@ permissions:actions: readconcurrency:- group: programmer-os-${{ github.ref }}-${{ inputs.memory_mib || '2048' }}-${{ inputs.live_transport || 'cdrom' }}-${{ inputs.development_update && 'update' || inputs.checks == 'browser-suspend' && 'browser-suspend' || inputs.checks == 'browser' && 'browser' || inputs.checks == 'session' && 'session' || inputs.checks == 'recovery' && 'recovery' || inputs.checks == 'essentials' && 'essentials' || inputs.checks == 'hardware' && 'hardware' || inputs.checks == 'hardware-update' && 'hardware-update' || inputs.dsh && 'dsh' || inputs.workloads && 'workloads' || 'image' }}+ group: programmer-os-${{ github.ref }}-${{ inputs.memory_mib || '2048' }}-${{ inputs.live_transport || 'cdrom' }}-${{ inputs.development_update && 'update' || inputs.checks == 'public-update' && 'public-update' || inputs.checks == 'browser-suspend' && 'browser-suspend' || inputs.checks == 'browser' && 'browser' || inputs.checks == 'session' && 'session' || inputs.checks == 'recovery' && 'recovery' || inputs.checks == 'essentials' && 'essentials' || inputs.checks == 'hardware' && 'hardware' || inputs.checks == 'hardware-update' && 'hardware-update' || inputs.dsh && 'dsh' || inputs.workloads && 'workloads' || 'image' }}cancel-in-progress: falsejobs:image:- if: ${{ !inputs.image_run_id && !inputs.publish_run_id && !inputs.development_update && inputs.checks != 'zram' && inputs.checks != 'hardware-update' && inputs.checks != 'browser-suspend' }}+ if: ${{ !inputs.image_run_id && !inputs.publish_run_id && !inputs.development_update && inputs.checks != 'zram' && inputs.checks != 'hardware-update' && inputs.checks != 'browser-suspend' && inputs.checks != 'public-update' }}runs-on: ubuntu-24.04timeout-minutes: 50steps:@@ -159,7 +159,7 @@ jobs:machine:needs: image- if: ${{ always() && !inputs.publish_run_id && !inputs.development_update && inputs.checks != 'essentials' && inputs.checks != 'hardware' && inputs.checks != 'zram' && inputs.checks != 'hardware-update' && (needs.image.result == 'success' || inputs.image_run_id != '' || inputs.checks == 'browser-suspend') && !cancelled() }}+ if: ${{ always() && !inputs.publish_run_id && !inputs.development_update && inputs.checks != 'essentials' && inputs.checks != 'hardware' && inputs.checks != 'zram' && inputs.checks != 'hardware-update' && inputs.checks != 'public-update' && (needs.image.result == 'success' || inputs.image_run_id != '' || inputs.checks == 'browser-suspend') && !cancelled() }}runs-on: ubuntu-24.04timeout-minutes: 65strategy:@@ -470,7 +470,7 @@ jobs:retention-days: 14development-update:- if: ${{ inputs.development_update && !inputs.publish_run_id && inputs.checks != 'hardware-update' }}+ if: ${{ inputs.development_update && !inputs.publish_run_id && inputs.checks != 'hardware-update' && inputs.checks != 'public-update' }}runs-on: ubuntu-24.04timeout-minutes: 30steps:@@ -534,8 +534,100 @@ jobs:retention-days: 14compression-level: 0+ public-update:+ if: ${{ inputs.checks == 'public-update' && !inputs.publish_run_id && !inputs.development_update }}+ runs-on: ubuntu-24.04+ timeout-minutes: 30+ steps:+ - uses: actions/checkout@v7+ with:+ fetch-depth: 0+ - name: Require an exact successful candidate producer+ env:+ CANDIDATE_RUN: ${{ inputs.image_run_id }}+ GH_TOKEN: ${{ github.token }}+ run: |+ [[ "$CANDIDATE_RUN" =~ ^[0-9]+$ ]]+ mkdir -p os/test-results/public-update-source+ gh api "repos/$GITHUB_REPOSITORY/actions/runs/$CANDIDATE_RUN" > os/test-results/public-update-source/candidate-run.json+ gh api "repos/$GITHUB_REPOSITORY/actions/runs/$CANDIDATE_RUN/artifacts" > os/test-results/public-update-source/candidate-artifacts.json+ gh api "repos/$GITHUB_REPOSITORY/actions/runs/37257481538" > os/test-results/public-update-source/baseline-run.json+ python3 - <<'PY'+ import json+ from pathlib import Path+ folder = Path('os/test-results/public-update-source')+ for name in ('candidate', 'baseline'):+ run = json.loads((folder / (name + '-run.json')).read_text())+ assert run['repository']['full_name'] == 'autonomous-ai/openharness'+ assert run['path'] == '.github/workflows/os.yml'+ assert run['status'] == 'completed' and run['conclusion'] == 'success'+ assert json.loads((folder / 'baseline-run.json').read_text())['head_sha'] == 'b6cbaf3e3090f43106ad1ee47606349bd1a0ae89'+ PY+ - uses: actions/download-artifact@v6+ with:+ name: programmer-os-x86_64+ path: os/work/public-update-baseline+ run-id: '37257481538'+ github-token: ${{ github.token }}+ - uses: actions/download-artifact@v6+ with:+ name: programmer-os-x86_64+ path: os/work/public-update-candidate+ run-id: ${{ inputs.image_run_id }}+ github-token: ${{ github.token }}+ - uses: actions/download-artifact@v6+ with:+ name: harness-os-candidate-inputs+ path: os/work/public-update-inputs+ run-id: ${{ inputs.image_run_id }}+ github-token: ${{ github.token }}+ - name: Validate observer and install native tools+ run: |+ sudo apt-get update -qq+ sudo apt-get install -y --no-install-recommends qemu-system-x86 qemu-utils ovmf python3-pil tesseract-ocr openssl xorriso squashfs-tools+ sudo chmod a+rw /dev/kvm+ python3 -m unittest discover -s os/tests -p 'test_package_image_binding.py' -v+ python3 -m unittest discover -s os/tests -p 'test_public_update_*.py' -v+ go run github.com/rhysd/actionlint/cmd/[email protected] .github/workflows/os.yml+ python3 - <<'PY'+ import json+ from pathlib import Path+ run = json.loads(Path('os/test-results/public-update-source/candidate-run.json').read_text())+ image = json.loads(Path('os/work/public-update-candidate/manifest.json').read_text())+ assert image['source_commit'] == run['head_sha']+ PY+ - name: Compare every update package file with the actual candidate ISO+ run: |+ python3 os/tests/package_image_binding.py \+ --iso os/work/public-update-candidate/*.iso \+ --bundle os/work/public-update-inputs/repo \+ --output os/test-results/public-update-source/package-image-binding.json+ - name: Update untouched preview 14 with one public shortcut and cold boot+ run: |+ python3 os/tests/public_update_vm.py \+ --iso os/work/public-update-baseline/*.iso \+ --bundle os/work/public-update-inputs/repo \+ --candidate-image-manifest os/work/public-update-candidate/manifest.json \+ --candidate-image-binding os/test-results/public-update-source/package-image-binding.json \+ --output os/test-results/public-update+ - name: Retain binding, transport and machine evidence+ if: always()+ uses: actions/upload-artifact@v6+ with:+ name: harness-os-public-update+ path: |+ os/test-results/public-update-source/+ os/test-results/public-update/+ !os/test-results/public-update/*.qcow2+ !os/test-results/public-update/OVMF_VARS.fd+ !os/test-results/public-update/https/*.key+ !os/test-results/public-update/https/*.pkg.tar.gz+ !os/test-results/public-update/transfer/+ retention-days: 14+ compression-level: 0+publish:- if: ${{ inputs.publish_run_id != '' && inputs.checks != 'hardware-update' }}+ if: ${{ inputs.publish_run_id != '' && inputs.checks != 'hardware-update' && inputs.checks != 'public-update' }}runs-on: ubuntu-24.04timeout-minutes: 30concurrency:diff --git a/os/DEVELOPMENT.md b/os/DEVELOPMENT.mdindex 0e5f23c26..39f3c0db4 100644--- a/os/DEVELOPMENT.md+++ b/os/DEVELOPMENT.md@@ -458,6 +458,27 @@ change, explicitly approved for all platforms. Publishing the ISO did not releasthese through the general TUI channel. The small updater adds no changes to `tui/`or `cli/`.+### Public update acceptance++Run the OS workflow with `checks=public-update` and the candidate's successful+`image_run_id`. The producer must retain both `programmer-os-x86_64` and+`harness-os-candidate-inputs`. This check compares every update-package file,+permission, owner and link with the actual ISO before installing the original+preview 14 image to a disposable encrypted disk.++The stock updater receives the candidate through its ordinary HTTPS URLs. A+temporary server and certificate authority exist only in the disposable test+machine; host trust, public feeds, updater code and sudo policy stay unchanged.+The test first proves that the guest rejects the untrusted certificate. Its+private metadata holds the separate hn/CLI channels at the image's baselines.++One real Super+u with cleared sudo credentials must apply the package, preserve+agent/daemon/terminal processes and keyboard input, retain a verified recovery+checkpoint, and cold boot into the candidate with project files unchanged. The+receipt records the image producer and observer separately. This establishes+the installed public update path with private transport, not CDN publication,+kernel migration or physical hardware support. The job never publishes.+## Installation and first-use onboardingThe USB starts `harness-install.service`: foot runs the offline installer directly.diff --git a/os/tests/package_image_binding.py b/os/tests/package_image_binding.pynew file mode 100644index 000000000..da768c7ac--- /dev/null+++ b/os/tests/package_image_binding.py@@ -0,0 +1,263 @@+#!/usr/bin/env python3+"""Compare the retained update archive with every owned file in the actual ISO.++This is a read-only artifact check. It neither installs nor rebuilds the package.+The receipt identifies the observer separately from the package/image producer.+"""+import argparse+from datetime import datetime, timezone+import hashlib+import json+from pathlib import Path, PurePosixPath+import re+import shutil+import stat+import subprocess+import sys+import tarfile+import tempfile+import time+++def identity(path):+ with path.open('rb') as handle:+ value = hashlib.file_digest(handle, 'sha256').hexdigest()+ return {'bytes': path.stat().st_size, 'sha256': value}+++def tool_version(tool):+ result = subprocess.run([tool, '-version'], capture_output=True, text=True, timeout=10)+ value = (result.stdout + result.stderr).strip()+ # SquashFS 4.6.1 prints the version then exits 1 without a filesystem+ # argument. This applies only to its identification command; every actual+ # listing/extraction below still requires exit 0.+ allowed = {0, 1} if tool == 'unsquashfs' else {0}+ prefix = r'^unsquashfs version \d+\.' if tool == 'unsquashfs' else r'^xorriso \d+\.'+ if result.returncode not in allowed or not re.search(prefix, value):+ raise ValueError(f'Cannot identify extraction tool: {tool} (exit {result.returncode}): {value}')+ return {'version': value, 'version_exit_code': result.returncode}+++def safe_path(value):+ path = PurePosixPath(value)+ # These are OS-owned paths, not arbitrary user filenames. In particular,+ # reject controls and the listing format's symlink separator as ambiguous.+ if (not re.fullmatch(r'[A-Za-z0-9_+.@/-]+', value) or path.is_absolute()+ or '..' in path.parts or not path.parts or str(path) != value.rstrip('/')):+ raise ValueError('Unsafe or ambiguous archive path: ' + value)+ return str(path)+++def archive_inventory(package, expected_version):+ rows = {}+ with tarfile.open(package, 'r:gz') as archive:+ for member in archive:+ name = safe_path(member.name)+ if name in rows:+ raise ValueError('Duplicate archive path: ' + name)+ if not (member.isfile() or member.isdir() or member.issym()):+ raise ValueError('Unsupported archive member: ' + name)+ if member.uid != 0 or member.gid != 0:+ raise ValueError('Archive member is not root-owned: ' + name)+ if name != '.PKGINFO' and PurePosixPath(name).parts[0] not in {'etc', 'usr'}:+ raise ValueError('Unexpected OS package path: ' + name)+ row = dict(name=name, mode=member.mode, uid=member.uid, gid=member.gid)+ if member.isfile():+ handle = archive.extractfile(member)+ row.update(type='file', bytes=member.size,+ sha256=hashlib.file_digest(handle, 'sha256').hexdigest())+ elif member.issym():+ safe_path(member.linkname)+ row.update(type='symlink', target=member.linkname)+ else:+ row['type'] = 'directory'+ rows[name] = row+ for name in rows:+ for parent in PurePosixPath(name).parents:+ if str(parent) in rows and rows[str(parent)]['type'] != 'directory':+ raise ValueError('Archive path traverses a non-directory: ' + name)+ metadata = rows.get('.PKGINFO', {})+ if metadata.get('type') != 'file' or metadata['bytes'] > 65536:+ raise ValueError('Missing or invalid package metadata')+ fields = {}+ for line in archive.extractfile('.PKGINFO').read().decode().splitlines():+ if ' = ' in line:+ key, value = line.split(' = ', 1)+ fields.setdefault(key, []).append(value)+ for key, value in [('pkgname', 'harness-os'), ('pkgver', expected_version), ('arch', 'x86_64')]:+ if fields.get(key) != [value]:+ raise ValueError('Package metadata mismatch: ' + key)+ return [rows[name] for name in sorted(rows)+ if name != '.PKGINFO' and rows[name]['type'] != 'directory']+++def parse_listing(text):+ entries = {}+ for line in text.splitlines():+ fields = line.split(maxsplit=5)+ if len(fields) != 6 or not re.fullmatch(r'\d+/\d+', fields[1]):+ continue+ mode, owner, size, _date, _time, name = fields+ if not name.startswith('squashfs-root/'):+ continue+ target = None+ if mode.startswith('l'):+ name, separator, target = name.partition(' -> ')+ if not separator:+ raise ValueError('Unparseable SquashFS symlink')+ name = name.removeprefix('squashfs-root/')+ if name in entries:+ raise ValueError('Duplicate SquashFS listing path: ' + name)+ uid, gid = map(int, owner.split('/'))+ entries[name] = {'mode_string': mode, 'uid': uid, 'gid': gid,+ 'bytes': int(size) if size.isdigit() else None, 'target': target}+ if not entries:+ raise ValueError('SquashFS listing was empty or unrecognized')+ return entries+++def compare_members(rows, listing, read):+ compared = []+ for row in rows:+ name = row['name']+ actual = listing.get(name)+ if actual is None:+ raise ValueError('Package member missing from ISO: ' + name)+ kind = stat.S_IFREG if row['type'] == 'file' else stat.S_IFLNK+ if (actual['mode_string'] != stat.filemode(kind | row['mode'])+ or (actual['uid'], actual['gid']) != (row['uid'], row['gid'])):+ raise ValueError('Package/ISO mode or ownership mismatch: ' + name)+ if row['type'] == 'file':+ data = read(name)+ observed = {'bytes': len(data), 'sha256': hashlib.sha256(data).hexdigest()}+ if observed != {key: row[key] for key in ('bytes', 'sha256')} or actual['bytes'] != len(data):+ raise ValueError('Package/ISO file mismatch: ' + name)+ else:+ observed = {'target': actual['target']}+ if actual['target'] != row['target']:+ raise ValueError('Package/ISO link mismatch: ' + name)+ compared.append({'archive': row, 'iso': {**actual, **observed}, 'equal': True})+ if not compared:+ raise ValueError('No owned package files were compared')+ return compared+++def verify_owned_paths(rows, package_database):+ blocks = {}+ for block in package_database.strip().split('\n\n'):+ lines = block.splitlines()+ if lines:+ blocks[lines[0]] = lines[1:]+ paths = [path for path in blocks.get('%FILES%', []) if not path.endswith('/')]+ expected = {row['name'] for row in rows}+ if len(paths) != len(set(paths)) or set(paths) != expected:+ raise ValueError('ISO package ownership list differs from archive members')+++def validate_inputs(iso, bundle):+ image_path, package_path = iso.with_name('manifest.json'), bundle / 'package-manifest.json'+ image, manifest = [json.loads(path.read_text()) for path in (image_path, package_path)]+ source = image.get('source_commit', '')+ if not re.fullmatch(r'[a-f0-9]{40}', source) or source != manifest.get('source_commit'):+ raise ValueError('Image and package sources differ')+ if (image.get('architecture') != 'x86_64' or manifest.get('architecture') != 'x86_64'+ or manifest.get('schema') != 1 or manifest.get('kind') != 'harness-os-package'):+ raise ValueError('Expected x86-64 Harness image and package manifests')+ for key, other in [('version', 'requires_os_version'), ('arch_snapshot', 'arch_snapshot'),+ ('package_version', None), ('harness_inputs', 'runtime')]:+ expected = manifest['package']['version'] if other is None else manifest.get(other)+ if image.get(key) != expected:+ raise ValueError('Image/package manifest mismatch: ' + key)+ runtime = manifest['runtime']+ if (runtime.get('source_commit') != source or runtime.get('dirty') is not False+ or runtime.get('target') != 'x86_64-unknown-linux-musl'+ or set(runtime.get('files', {})) != {'harness-tui', 'cli.mjs', 'notify.mjs'}):+ raise ValueError('Expected a complete clean runtime from the image producer')+ package = manifest['package']+ name = package.get('name', '')+ version = package.get('version', '')+ if not re.fullmatch(r'[0-9A-Za-z.+_-]+', version) or name != f'harness-os-{version}-x86_64.pkg.tar.gz':+ raise ValueError('Invalid package filename')+ package_file = bundle / name+ for path, declared in [(iso, image['iso']), (package_file, package)]:+ if path.is_symlink() or not path.is_file() or path.name != declared['name']:+ raise ValueError('Artifact path does not match its manifest')+ if identity(path) != {key: declared[key] for key in ('bytes', 'sha256')}:+ raise ValueError('Artifact hash or size mismatch: ' + path.name)+ return image, manifest, package_file+++def bind(iso, bundle, output):+ if output.exists():+ raise ValueError('Use a fresh receipt path')+ source = Path(__file__).resolve().parents[2]+ started = time.monotonic()+ record = {'schema': 1, 'status': 'running', 'started_at': datetime.now(timezone.utc).isoformat(),+ 'overrides': [], 'limitations': ['Artifact equality only; not installation, update, boot or hardware acceptance.']}+ output.parent.mkdir(parents=True, exist_ok=True)+ try:+ record['observer'] = {+ 'source_commit': subprocess.check_output(['git', '-C', str(source), 'rev-parse', 'HEAD'], text=True).strip(),+ 'source_dirty': bool(subprocess.check_output(['git', '-C', str(source), 'status', '--porcelain'], text=True).strip()),+ 'inputs': {str(Path(__file__).relative_to(source)): identity(Path(__file__))},+ 'invocation': ['--iso', str(iso), '--bundle', str(bundle), '--output', str(output)]}+ if record['observer']['source_dirty']:+ raise ValueError('Commit the observer before accepting native artifact evidence')+ image, manifest, package = validate_inputs(iso, bundle)+ rows = archive_inventory(package, manifest['package']['version'])+ record.update(source_commit=image['source_commit'], image=identity(iso),+ image_manifest=identity(iso.with_name('manifest.json')),+ package={'name': package.name, **identity(package)},+ package_manifest=identity(bundle / 'package-manifest.json'),+ runtime=manifest['runtime'], package_version=manifest['package']['version'])+ record['tools'] = {'python': {'version': sys.version, 'path': sys.executable,+ **identity(Path(sys.executable))}}+ for tool in ('xorriso', 'unsquashfs'):+ version = tool_version(tool)+ executable = Path(shutil.which(tool)).resolve()+ record['tools'][tool] = {**version, 'path': str(executable), **identity(executable)}+ with tempfile.TemporaryDirectory(prefix='harness-package-image-') as temporary:+ payload = Path(temporary) / 'airootfs.sfs'+ subprocess.run(['xorriso', '-no_rc', '-osirrox', 'on', '-indev', str(iso), '-extract',+ '/arch/x86_64/airootfs.sfs', str(payload)], check=True, timeout=180)+ record['payload'] = identity(payload)+ listing = parse_listing(subprocess.check_output(['unsquashfs', '-lln', str(payload)], text=True, timeout=60))++ def read(name):+ return subprocess.check_output(['unsquashfs', '-cat', str(payload), name], timeout=30)++ record['members'] = compare_members(rows, listing, read)+ verify_owned_paths(rows, read('var/lib/pacman/local/harness-os-' ++ manifest['package']['version'] + '/files').decode())+ if json.loads(read('usr/share/harness-os/runtime.json')) != manifest['runtime']:+ raise ValueError('ISO runtime identity differs from the package manifest')+ for name, expected in manifest['runtime']['files'].items():+ data = read('usr/lib/harness/' + name)+ if expected != {'bytes': len(data), 'sha256': hashlib.sha256(data).hexdigest()}:+ raise ValueError('Runtime byte identity differs: ' + name)+ lock = json.loads(read('usr/share/harness-os/lock.json'))+ if (lock['version'], lock['arch_snapshot']) != (image['version'], image['arch_snapshot']):+ raise ValueError('ISO lock identity differs')+ inventory = dict(line.split(maxsplit=1) for line in read('usr/share/harness-os/packages.txt').decode().splitlines())+ if inventory.get('harness-os') != manifest['package']['version']:+ raise ValueError('Installed image inventory differs from the update package')+ record['status'] = 'passed'+ except Exception as error:+ record.update(status='failed', error=f'{type(error).__name__}: {error}')+ raise+ finally:+ record['exit_code'] = 0 if record['status'] == 'passed' else 1+ record['finished_at'] = datetime.now(timezone.utc).isoformat()+ record['duration_seconds'] = round(time.monotonic() - started, 3)+ output.write_text(json.dumps(record, indent=2) + '\n')+ print(json.dumps({'status': record['status'], 'members': len(record['members']), 'receipt': str(output)}))+ return record+++if __name__ == '__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()+ bind(args.iso.absolute(), args.bundle.absolute(), args.output.absolute())diff --git a/os/tests/public_update_guest.py b/os/tests/public_update_guest.pynew file mode 100644index 000000000..ca51d6d81--- /dev/null+++ b/os/tests/public_update_guest.py@@ -0,0 +1,115 @@+#!/usr/bin/env python3+"""Read-only observations for an untouched installed-OS update journey."""+import argparse+import hashlib+import json+import os+from pathlib import Path+import re+import stat+import subprocess++HOME = Path('/home/me')+ROOT_STATE = Path('/var/lib/harness-os/runtime-updates')+++def digest(path):+ with path.open('rb') as handle:+ return hashlib.file_digest(handle, 'sha256').hexdigest()+++def file_record(path):+ info = path.lstat()+ record = {'mode': stat.S_IMODE(info.st_mode), 'uid': info.st_uid, 'gid': info.st_gid,+ 'mtime_ns': info.st_mtime_ns}+ if stat.S_ISLNK(info.st_mode):+ record.update(type='symlink', target=os.readlink(path))+ elif stat.S_ISREG(info.st_mode):+ record.update(type='file', bytes=info.st_size, sha256=digest(path))+ else:+ raise ValueError('Expected an owned file or link: ' + str(path))+ return record+++def package_files(root, version):+ text = (root / 'var/lib/pacman/local' / ('harness-os-' + version) / 'files').read_text()+ blocks = {}+ for block in text.strip().split('\n\n'):+ lines = block.splitlines()+ blocks[lines[0]] = lines[1:]+ paths = [path for path in blocks['%FILES%'] if not path.endswith('/')]+ if len(set(paths)) != len(paths) or any(path.startswith('/') or '..' in Path(path).parts for path in paths):+ raise ValueError('Unexpected installed ownership list')+ return {name: file_record(root / name) for name in sorted(paths)}+++def system():+ package = subprocess.check_output(['pacman', '-Q', 'harness-os'], text=True).strip().split()+ assert package[0] == 'harness-os' and len(package) == 2+ policy = [Path('/etc/sudoers'), *sorted(Path('/etc/sudoers.d').iterdir())]+ return {'package_version': package[1], 'owned_files': package_files(Path('/'), package[1]),+ 'sudo_policy': {str(path): file_record(path) for path in policy if path.is_file()},+ 'runtime': json.loads(Path('/usr/share/harness-os/runtime.json').read_text()),+ 'lock': json.loads(Path('/usr/share/harness-os/lock.json').read_text()),+ 'boot_id': Path('/proc/sys/kernel/random/boot_id').read_text().strip()}+++def process(pid):+ folder = Path('/proc') / str(pid)+ fields = (folder / 'stat').read_text().rsplit(')', 1)[1].split()+ if fields[0] in ('Z', 'X'):+ raise ValueError('Work process is no longer live: ' + str(pid))+ return {'pid': int(pid), 'start': fields[19], 'uid': folder.stat().st_uid,+ 'argv': (folder / 'cmdline').read_bytes().rstrip(b'\0').decode().split('\0')}+++def project():+ folder = HOME / 'projects/public-update-proof'+ return {str(path.relative_to(folder)): file_record(path) for path in sorted(folder.rglob('*')) if path.is_file()}+++def work():+ assert os.getuid() == 1000+ agents = subprocess.check_output(['pgrep', '-u', '1000', '-x', 'opencode'], text=True).split()+ daemon = subprocess.check_output(['systemctl', '--user', 'show', 'harness-daemon.service', '-p', 'MainPID', '--value'], text=True).strip()+ terminal = (HOME / 'projects/session-probe/pid').read_text().strip()+ return {'agents': [process(pid) for pid in sorted(agents)], 'daemon': process(daemon),+ 'terminal': process(terminal), 'project': project(),+ 'heartbeat': (HOME / 'projects/session-probe/heartbeat').stat().st_mtime_ns,+ 'boot_id': Path('/proc/sys/kernel/random/boot_id').read_text().strip()}+++def checkpoint():+ pointer = json.loads((ROOT_STATE / 'latest.json').read_text())['id']+ if not re.fullmatch(r'[0-9TZ-]+-[a-f0-9]{8}', pointer):+ raise ValueError('Invalid root receipt identity')+ folder = ROOT_STATE / pointer+ receipt = json.loads((folder / 'receipt.json').read_text())+ name = receipt['checkpoint']+ if not re.fullmatch(r'[a-zA-Z0-9][a-zA-Z0-9_-]{0,79}', name):+ raise ValueError('Invalid checkpoint identity')+ saved = Path('/.snapshots') / name+ metadata = json.loads((saved / 'checkpoint.json').read_text())+ if metadata['root_uuid'] != receipt['root_uuid'] or metadata['name'] != name:+ raise ValueError('Checkpoint and transaction identities differ')+ boot = {}+ for path, expected in metadata['boot_sha256'].items():+ if Path(path).is_absolute() or '..' in Path(path).parts:+ raise ValueError('Invalid saved boot path')+ boot[path] = digest(saved / 'boot' / path)+ if boot[path] != expected:+ raise ValueError('Saved boot file was modified: ' + path)+ backup = digest(folder / 'previous.pkg.tar.gz')+ if backup != receipt['backup_sha256']:+ raise ValueError('Saved package was modified')+ return {'receipt': receipt, 'checkpoint': metadata, 'boot_sha256': boot,+ 'backup_sha256': backup, 'previous_files': package_files(saved / 'root', receipt['previous_version'])}+++if __name__ == '__main__':+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('action', choices=['system', 'work', 'checkpoint', 'project'])+ parser.add_argument('output', type=Path)+ args = parser.parse_args()+ result = {'system': system, 'work': work, 'checkpoint': checkpoint, 'project': project}[args.action]()+ args.output.write_text(json.dumps(result, indent=2) + '\n')diff --git a/os/tests/public_update_transport.py b/os/tests/public_update_transport.pynew file mode 100644index 000000000..740c0a253--- /dev/null+++ b/os/tests/public_update_transport.py@@ -0,0 +1,155 @@+#!/usr/bin/env python3+"""Private HTTPS fixture for the stock OS updater's exact official URLs.++Install its CA only inside the disposable guest. No production URL, parser,+privilege policy or TLS verification is changed by this fixture.+"""+import argparse+from datetime import datetime, timezone+import hashlib+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+import json+from pathlib import Path+import re+import shutil+import ssl+import subprocess++ASSETS = '/autonomous-ai/openharness/releases/download/'+FEED = ASSETS + 'os-preview-updates/metadata.json'+HN = '/s3-autonomous-upgrade-3/harness/tui/metadata.json'+CLI = '/s3-autonomous-upgrade-3/harness/cli/metadata.json'+HOSTS = {'github.com', 'storage.googleapis.com'}+++def file_identity(path):+ with path.open('rb') as handle:+ return {'bytes': path.stat().st_size, 'sha256': hashlib.file_digest(handle, 'sha256').hexdigest()}+++def prepare(bundle, folder, baselines):+ folder.mkdir(parents=True, exist_ok=False)+ manifest_path = bundle / 'package-manifest.json'+ manifest = json.loads(manifest_path.read_text())+ version = manifest['requires_os_version']+ package = manifest['package']+ if not re.fullmatch(r'\d+\.\d+\.\d+-preview\.\d+', version):+ raise ValueError('Expected a numbered OS preview')+ name = package['name']+ if not re.fullmatch(r'harness-os-[0-9A-Za-z.+_-]+-x86_64\.pkg\.tar\.gz', name):+ raise ValueError('Invalid package path')+ if file_identity(bundle / name) != {key: package[key] for key in ('bytes', 'sha256')}:+ raise ValueError('Package differs from its manifest')+ for item in (name, 'package-manifest.json'):+ shutil.copyfile(bundle / item, folder / item)+ prefix = ASSETS + 'os-v' + version + '/'++ def asset(item):+ return {'url': 'https://github.com' + prefix + item, **file_identity(folder / item)}++ metadata = {'schema': 1, 'channel': 'preview', 'architecture': 'x86_64',+ 'manifest': asset('package-manifest.json'), 'package': asset(name)}+ unused = {'url': 'https://storage.googleapis.com/harness-public-test-no-payload',+ 'sha256': '0' * 64, 'size': 1}+ for component in ('hn', 'cli'):+ if not re.fullmatch(r'\d+\.\d+\.\d+', baselines[component]['version']):+ raise ValueError('Invalid frozen baseline')+ hn = {'version': baselines['hn']['version'], 'builds': {'linux-x64': unused}}+ cli = {'cli': {'version': baselines['cli']['version'], 'cli': unused, 'notify': unused}}+ for item, data in [('metadata.json', metadata), ('hn.json', hn), ('cli.json', cli)]:+ (folder / item).write_text(json.dumps(data) + '\n')+ routes = [+ {'host': 'github.com', 'path': FEED, 'file': 'metadata.json'},+ {'host': 'github.com', 'path': prefix + 'package-manifest.json', 'file': 'package-manifest.json'},+ {'host': 'github.com', 'path': prefix + name, 'file': name},+ {'host': 'storage.googleapis.com', 'path': HN, 'file': 'hn.json'},+ {'host': 'storage.googleapis.com', 'path': CLI, 'file': 'cli.json'}]+ for route in routes:+ route.update(file_identity(folder / route['file']))+ (folder / 'routes.json').write_text(json.dumps(routes, indent=2) + '\n')+ return routes+++def certificates(folder):+ folder.mkdir(parents=True, exist_ok=True)+ (folder / 'leaf.ext').write_text('subjectAltName=DNS:github.com,DNS:storage.googleapis.com\n'+ 'extendedKeyUsage=serverAuth\nbasicConstraints=critical,CA:FALSE\n'+ 'keyUsage=critical,digitalSignature,keyEncipherment\n'+ 'subjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid,issuer\n')+ commands = [+ ['openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-days', '2',+ '-subj', '/CN=Harness disposable VM test CA', '-addext', 'basicConstraints=critical,CA:TRUE',+ '-addext', 'keyUsage=critical,keyCertSign,cRLSign',+ '-keyout', 'ca.key', '-out', 'ca.crt'],+ ['openssl', 'req', '-newkey', 'rsa:2048', '-nodes', '-subj', '/CN=github.com',+ '-keyout', 'leaf.key', '-out', 'leaf.csr'],+ ['openssl', 'x509', '-req', '-in', 'leaf.csr', '-CA', 'ca.crt', '-CAkey', 'ca.key',+ '-CAcreateserial', '-days', '2', '-extfile', 'leaf.ext', '-out', 'leaf.crt']]+ for command in commands:+ subprocess.run(command, cwd=folder, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=30)+ for name in ('ca.key', 'leaf.key'):+ (folder / name).chmod(0o600)+ return {name: file_identity(folder / name) for name in ('ca.crt', 'leaf.crt')}+++class Handler(BaseHTTPRequestHandler):+ def log_message(self, *_args):+ pass++ def do_GET(self):+ host = self.headers.get('Host', '').lower()+ if host.endswith(':443'):+ host = host[:-4]+ route = self.server.routes.get((host, self.path))+ record = {'at': datetime.now(timezone.utc).isoformat(), 'host': host, 'path': self.path}+ if route is None:+ self.send_error(404)+ record.update(status=404, complete=True, bytes=0)+ else:+ digest = hashlib.sha256()+ count = 0+ try:+ self.send_response(200)+ self.send_header('Content-Length', str(route['bytes']))+ self.send_header('Content-Type', 'application/octet-stream')+ self.end_headers()+ with (self.server.folder / route['file']).open('rb') as handle:+ while chunk := handle.read(128 * 1024):+ self.wfile.write(chunk)+ digest.update(chunk)+ count += len(chunk)+ record.update(status=200, complete=(count == route['bytes'] and digest.hexdigest() == route['sha256']),+ bytes=count, sha256=digest.hexdigest())+ except (OSError, ssl.SSLError) as error:+ record.update(status=200, complete=False, bytes=count, error=str(error))+ with (self.server.folder / 'requests.jsonl').open('a') as log:+ log.write(json.dumps(record) + '\n')+++def server(folder, port=443):+ routes = json.loads((folder / 'routes.json').read_text())+ mapping = {}+ for row in routes:+ if (row['host'] not in HOSTS or not row['path'].startswith('/')+ or Path(row['file']).name != row['file'] or row['file'] in {'.', '..'}+ or (folder / row['file']).is_symlink()+ or file_identity(folder / row['file']) != {key: row[key] for key in ('bytes', 'sha256')}):+ raise ValueError('Invalid private HTTPS route')+ key = row['host'], row['path']+ if key in mapping:+ raise ValueError('Duplicate private HTTPS route')+ mapping[key] = row+ service = ThreadingHTTPServer(('127.0.0.1', port), Handler)+ service.folder, service.routes = folder, mapping+ context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)+ context.load_cert_chain(folder / 'leaf.crt', folder / 'leaf.key')+ service.socket = context.wrap_socket(service.socket, server_side=True)+ return service+++if __name__ == '__main__':+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('folder', type=Path)+ args = parser.parse_args()+ with server(args.folder) as instance:+ instance.serve_forever()diff --git a/os/tests/public_update_vm.py b/os/tests/public_update_vm.pynew file mode 100644index 000000000..2fb520a9f--- /dev/null+++ b/os/tests/public_update_vm.py@@ -0,0 +1,366 @@+#!/usr/bin/env python3+"""Install untouched preview 14, press Super+u once, preserve work and cold boot."""+import argparse+from functools import partial+import hashlib+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer+import json+from pathlib import Path+import re+import shlex+import shutil+import subprocess+import tarfile+import threading+import time++import package_image_binding as binding+import public_update_transport as transport+from footprint_vm import copy_file+from hardware_update_vm import graceful_stop+from session_vm import PROBE, screen_text+from vm import VM, check_graphical_keyboard++BASE = 'b6cbaf3e3090f43106ad1ee47606349bd1a0ae89'+BASE_ISO = 'fa4f282644ac81e9e3b7de55276edd7dc08405e50875da544dc7f9fd6d50ba12'+STATE = '/home/me/.local/state/harness-os/updates'+GUEST = '/home/me/public-update-observer.py'+FIXTURE = '/var/lib/harness-public-update-test'+++def verify_binding(bundle, image_manifest, receipt_path):+ manifest = json.loads((bundle / 'package-manifest.json').read_text())+ image = json.loads(image_manifest.read_text())+ receipt = json.loads(receipt_path.read_text())+ package = bundle / manifest['package']['name']+ if receipt.get('status') != 'passed' or receipt.get('overrides') != []:+ raise ValueError('Require a complete package-to-ISO comparison without overrides')+ expected = {'source_commit': manifest['source_commit'], 'runtime': manifest['runtime'],+ 'package_version': manifest['package']['version'],+ 'package': {'name': package.name, **binding.identity(package)},+ 'package_manifest': binding.identity(bundle / 'package-manifest.json'),+ 'image_manifest': binding.identity(image_manifest),+ 'image': {key: image['iso'][key] for key in ('bytes', 'sha256')}}+ if any(receipt.get(key) != value for key, value in expected.items()):+ raise ValueError('Binding receipt does not identify the supplied artifacts')+ if image['source_commit'] != manifest['source_commit'] or image['harness_inputs'] != manifest['runtime']:+ raise ValueError('Candidate image and runtime producers differ')+ rows = binding.archive_inventory(package, manifest['package']['version'])+ if [row['archive'] for row in receipt['members']] != rows or not all(row['equal'] is True for row in receipt['members']):+ raise ValueError('Binding receipt omits or changes an archive member')+ return manifest, image, receipt+++def same_work(before, after):+ for key in ('agents', 'daemon', 'terminal', 'project', 'boot_id'):+ if before[key] != after[key]:+ raise ValueError('Running work changed during update: ' + key)+ if after['heartbeat'] <= before['heartbeat']:+ raise ValueError('Terminal stopped making progress during update')+++def installed_matches(record, receipt):+ if record['runtime'] != receipt['runtime'] or record['package_version'] != receipt['package_version']:+ raise ValueError('Installed candidate identity differs')+ rows = {row['archive']['name']: row['archive'] for row in receipt['members']}+ if set(record['owned_files']) != set(rows):+ raise ValueError('Installed ownership list differs from the candidate package')+ for name, expected in rows.items():+ actual = record['owned_files'][name]+ if any(actual.get(key) != value for key, value in expected.items() if key != 'name'):+ raise ValueError('Installed file differs from the ISO-bound package: ' + name)+++def shutdown(vm, record, name, root=False):+ # Drain the diagnostic serial socket while waiting for the fresh QMP+ # shutdown event. An unread console can stall QEMU during guest poweroff.+ event = graceful_stop(vm, privileged=not root)+ record.setdefault('shutdowns', []).append({'name': name, **event})+++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('--candidate-image-manifest', type=Path, required=True)+ parser.add_argument('--candidate-image-binding', type=Path, required=True)+ parser.add_argument('--output', type=Path, required=True)+ args = parser.parse_args()+ iso, bundle, folder = args.iso.absolute(), args.bundle.absolute(), args.output.absolute()+ folder.mkdir(parents=True, exist_ok=False)+ base = json.loads(iso.with_name('manifest.json').read_text())+ if base['source_commit'] != BASE or base['version'] != '0.1.0-preview.14' or base['iso']['sha256'] != BASE_ISO:+ raise ValueError('Use the original preview 14 image')+ if iso.name != base['iso']['name'] or binding.identity(iso) != {key: base['iso'][key] for key in ('bytes', 'sha256')}:+ raise ValueError('Baseline ISO bytes differ')+ candidate, image, bound = verify_binding(bundle, args.candidate_image_manifest, args.candidate_image_binding)+ source = Path(__file__).resolve().parents[2]+ head = subprocess.check_output(['git', '-C', str(source), 'rev-parse', 'HEAD'], text=True).strip()+ if subprocess.check_output(['git', '-C', str(source), 'status', '--porcelain'], text=True).strip():+ raise ValueError('Commit the observer before native acceptance')+ if bound['observer']['source_commit'] != head:+ raise ValueError('Run artifact binding with this reviewed observer source')+ record = {'status': 'running', 'started_at': time.time(), 'observer_source': head,+ 'baseline': base, 'candidate': candidate, 'candidate_image': image,+ 'binding_receipt': binding.identity(args.candidate_image_binding), 'checks': [],+ 'test_inputs': {name: binding.identity(Path(__file__).with_name(name)) for name in+ ['public_update_vm.py', 'public_update_guest.py', 'public_update_transport.py',+ 'package_image_binding.py', 'vm.py', 'session_vm.py', 'footprint_vm.py',+ 'hardware_update_vm.py', 'hardware_update_guest.py', 'hardware_install_vm.py']},+ 'limits': ['Private official-path HTTPS fixture; not GitHub/CDN publication.',+ 'Same Arch snapshot; no kernel migration or physical hardware claim.']}+ for name, path in [('baseline-manifest.json', iso.with_name('manifest.json')),+ ('candidate-manifest.json', args.candidate_image_manifest),+ ('package-manifest.json', bundle / 'package-manifest.json'),+ ('package-image-binding.json', args.candidate_image_binding)]:+ shutil.copyfile(path, folder / name)+ fixture = folder / 'https'+ transport.prepare(bundle, fixture, base['harness_inputs']['release_baselines'])+ record['certificates'] = transport.certificates(fixture)+ shutil.copyfile(Path(__file__).with_name('public_update_transport.py'), fixture / 'server.py')+ transfer = folder / 'transfer'+ transfer.mkdir()+ archive = transfer / 'fixture.tar.gz'+ with tarfile.open(archive, 'w:gz') as target:+ for path in sorted(fixture.iterdir()):+ if path.name not in {'ca.key', 'ca.srl', 'leaf.csr', 'leaf.ext'}:+ target.add(path, arcname=path.name, recursive=False)+ vm = VM(folder, iso, 'uefi', 2048, cpu='Nehalem')+ http = ThreadingHTTPServer(('127.0.0.1', 0), partial(SimpleHTTPRequestHandler, directory=str(transfer)))+ thread = threading.Thread(target=http.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)++ def authenticate():+ vm.command('printf %s ' + shlex.quote(config['password'] + '\n') + ' | sudo -S -v')++ def observe(name, action, privileged=False):+ target = '/tmp/public-update-' + name + '.json'+ vm.command(('sudo -n ' if privileged else '') + 'python3 ' + GUEST + ' ' + action + ' ' + target)+ data = vm.read_file(target)+ (folder / (name + '.json')).write_bytes(data)+ return json.loads(data)++ def keyboard(label):+ vm.command('hn select-window -t ' + shlex.quote(terminal) + ' && hn select-pane -t ' + shlex.quote(terminal))+ vm.keys('meta_l', 'ret')+ vm.type_probe(label)+ vm.keys('ret')+ vm.command('timeout 10 sh -c ' + shlex.quote('until grep -qx ' + shlex.quote(label) + ' ~/projects/session-probe/input; do sleep .1; done'))+ vm.screenshot(label)++ try:+ vm.start(live=True)+ record.update(firmware='uefi', memory_mib=2048, cpu='Nehalem', acceleration=vm.acceleration)+ 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-config.json')+ output, _ = vm.command('harness install --config /tmp/install-config.json --yes-erase-disk', timeout=360)+ (folder / 'install.log').write_text(output)+ shutdown(vm, record, 'baseline-install', root=True)+ vm.start(live=False)+ vm.monitor('set_link', name='hnnet', up=False)+ vm.login_installed(config)+ authenticate()+ vm.command('systemctl --user stop harness-update.timer harness-update.service')+ vm.command('test ! -e ' + STATE + '/current && test ! -e ' + STATE + '/ready.json && test ! -e ' + STATE + '/approved.json')+ copy_file(vm, Path(__file__).with_name('public_update_guest.py').read_bytes(), GUEST)+ original = observe('01-original-system', 'system', True)+ (folder / 'hosts-before.txt').write_bytes(vm.read_file('/etc/hosts'))+ if original['runtime'] != base['harness_inputs'] or original['package_version'] != base['package_version']:+ raise ValueError('Baseline installed runtime differs from the original ISO')+ # Only network/trust fixture files are added. Update timers are paused+ # during fixture setup so no real public channel is contacted in between.+ vm.monitor('set_link', name='hnnet', up=True)+ vm.command('sudo -n nmcli networking on && nm-online -q --timeout=30', timeout=35)+ address = 'http://10.0.2.2:' + str(http.server_port) + '/fixture.tar.gz'+ vm.command('curl --fail --silent --show-error ' + shlex.quote(address) + ' -o /tmp/public-update-fixture.tar.gz', timeout=90)+ expected = binding.identity(archive)['sha256']+ vm.command('printf %s ' + shlex.quote(expected + ' /tmp/public-update-fixture.tar.gz\n') + ' | sha256sum -c -')+ vm.command('sudo -n mkdir -m 700 ' + FIXTURE + ' && sudo -n tar -xzf /tmp/public-update-fixture.tar.gz -C ' + FIXTURE)+ service = ('[Unit]\nDescription=Private Harness update transport fixture\nAfter=local-fs.target\n'+ '[Service]\nExecStart=/usr/bin/python3 ' + FIXTURE + '/server.py ' + FIXTURE + '\n'+ '[Install]\nWantedBy=multi-user.target\n')+ copy_file(vm, service.encode(), '/tmp/harness-public-update-test.service')+ vm.command('sudo -n install -m 644 /tmp/harness-public-update-test.service /etc/systemd/system/harness-public-update-test.service && '+ 'sudo -n systemctl daemon-reload && sudo -n systemctl enable --now harness-public-update-test.service')+ vm.command('printf %s ' + shlex.quote('\n127.0.0.1 github.com storage.googleapis.com\n') + ' | sudo -n tee -a /etc/hosts >/dev/null')+ (folder / 'hosts-fixture.txt').write_bytes(vm.read_file('/etc/hosts'))+ # Arch's resolve NSS module precedes files; the observed baseline still+ # resolved public addresses after flush-caches. This is an explicit+ # guest-only transport fixture, so put its hosts entries first. Do not+ # change the updater, its URLs, signature/hash checks or privilege policy.+ nss = vm.read_file('/etc/nsswitch.conf').decode()+ (folder / 'nsswitch-before.txt').write_text(nss)+ lines = nss.splitlines(keepends=True)+ rows = [i for i, line in enumerate(lines) if line.startswith('hosts:')]+ if len(rows) != 1:+ raise ValueError('Expected one hosts NSS entry for the private transport')+ lines[rows[0]] = 'hosts: files mymachines resolve [!UNAVAIL=return] myhostname dns\n'+ copy_file(vm, ''.join(lines).encode(), '/tmp/harness-test-nsswitch.conf')+ vm.command('sudo -n install -m 644 /tmp/harness-test-nsswitch.conf /etc/nsswitch.conf')+ vm.command('timeout 10 sh -c ' + shlex.quote("until ss -ltnH | grep -q '127.0.0.1:443 '; do sleep .1; done"))+ # The original session has already queried the public hosts. Flush its+ # resolver cache after adding the private hosts file; prove this request+ # reaches loopback before interpreting an HTTPS result as fixture trust.+ vm.command('sudo -n resolvectl flush-caches')+ diagnostic = ('import json, socket, urllib.request; '+ 'print(json.dumps({"addresses": {host: sorted({item[4][0] for item in '+ 'socket.getaddrinfo(host,443,type=socket.SOCK_STREAM)}) for host in '+ '["github.com","storage.googleapis.com"]}, '+ '"proxy_keys": sorted(urllib.request.getproxies())}))')+ output, _ = vm.command('python3 -c ' + shlex.quote(diagnostic), timeout=15)+ (folder / '02-private-resolution.log').write_text(output)+ (folder / '02-nsswitch.txt').write_bytes(vm.read_file('/etc/nsswitch.conf'))+ vm.command('python3 -c ' + shlex.quote('import socket; '+ 'assert all({i[4][0] for i in socket.getaddrinfo(host,443,type=socket.SOCK_STREAM)} == {"127.0.0.1"} '+ 'for host in ["github.com","storage.googleapis.com"]), "Private transport must resolve only to loopback"'))+ check = 'import urllib.request; print(urllib.request.urlopen(' + repr('https://github.com' + transport.FEED) + ', timeout=10).status)'+ output, status = vm.command('python3 -c ' + shlex.quote(check), timeout=15, check=False)+ (folder / '02-untrusted-tls.log').write_text(output)+ if status == 0 or 'CERTIFICATE_VERIFY_FAILED' not in output:+ raise ValueError('Guest HTTPS did not enforce trust before installing the fixture CA')+ vm.command('sudo -n install -m 644 ' + FIXTURE + '/ca.crt /etc/ca-certificates/trust-source/anchors/harness-public-update-test.crt && sudo -n update-ca-trust')+ output, _ = vm.command('python3 -c ' + shlex.quote(check), timeout=15)+ (folder / '03-trusted-tls.log').write_text(output)+ anchor = vm.read_file('/etc/ca-certificates/trust-source/anchors/harness-public-update-test.crt')+ if hashlib.sha256(anchor).hexdigest() != record['certificates']['ca.crt']['sha256']:+ raise ValueError('Guest trust anchor differs from the disposable fixture CA')+ record['guest_trust_anchor'] = {'path': '/etc/ca-certificates/trust-source/anchors/harness-public-update-test.crt',+ 'sha256': hashlib.sha256(anchor).hexdigest()}+ prepared = observe('04-prepared-system', 'system', True)+ if prepared != original:+ raise ValueError('Fixture preparation changed installed Harness or privilege policy')+ vm.command('systemctl --user start harness-update.timer harness-update.service', timeout=120)+ vm.command('python3 -c ' + shlex.quote("import json; assert json.load(open('" + STATE + "/system.json'))['available'] is True"))+ vm.command('for n in $(seq 1 90); do pgrep -u 1000 -x opencode >/dev/null && exit 0; sleep .5; done; exit 1', timeout=50)+ copy_file(vm, PROBE.encode(), '/home/me/public-update-terminal.py')+ vm.command('mkdir -p ~/projects/public-update-proof && printf work-survives > ~/projects/public-update-proof/notes.txt && '+ "hn new-window -P -F '#{pane_id}' -n update-proof 'python3 /home/me/public-update-terminal.py' > /tmp/public-update-terminal-id")+ vm.command('for n in $(seq 1 60); do test -s ~/projects/session-probe/pid && exit 0; sleep .1; done; exit 1')+ terminal = vm.read_file('/tmp/public-update-terminal-id').decode().strip()+ if not re.fullmatch(r'%\d+', terminal):+ raise ValueError('Invalid probe pane identity')+ keyboard('before-public-update')+ before = observe('05-running-work', 'work')+ vm.command('sudo -K')+ for command in ['/usr/bin/true', '/usr/bin/harness upgrade /tmp/untrusted-bundle']:+ output, status = vm.command('sudo -n ' + command, check=False)+ if status == 0 or 'password' not in output.lower():+ raise ValueError('Unexpected no-password privilege: ' + command)+ record['public_action'] = {'keys': ['meta_l', 'u'], 'count': 1, 'at': time.time()}+ vm.keys('meta_l', 'u')+ vm.command('for n in $(seq 1 720); do test -f /run/harness-os-restart-required && '+ 'grep -q ready /run/harness-os-restart-required && exit 0; sleep .5; done; exit 1', timeout=365)+ deadline = time.monotonic() + 15+ while 'updated. restart when ready.' not in screen_text(vm, '06-updated-screen'):+ if time.monotonic() >= deadline:+ raise TimeoutError('Updated screen was not visibly rendered')+ time.sleep(.25)+ after = observe('07-preserved-work', 'work')+ same_work(before, after)+ keyboard('after-public-update')+ # Only after success and preserved work are observed may the diagnostic+ # serial shell authenticate again to read the private root receipt.+ authenticate()+ installed = observe('08-installed-candidate', 'system', True)+ installed_matches(installed, bound)+ saved = observe('09-checkpoint', 'checkpoint', True)+ if (saved['receipt']['status'] != 'applied' or saved['receipt']['candidate'] != candidate+ or saved['previous_files'] != original['owned_files']+ or saved['receipt']['previous_runtime'] != base['harness_inputs']):+ raise ValueError('Root update receipt/checkpoint did not preserve the original package')+ vm.command('printf new-work-after-checkpoint > ~/projects/public-update-proof/after.txt')+ project = observe('10-project-before-reboot', 'project')+ vm.command('journalctl --user -b --no-pager > /tmp/public-update-user-journal.log && '+ 'sudo -n journalctl -b --no-pager > /tmp/public-update-system-journal.log')+ for kind in ('user', 'system'):+ (folder / (kind + '-journal-before-reboot.log')).write_bytes(vm.read_file('/tmp/public-update-' + kind + '-journal.log'))+ record['checks'].append('One public Super+u with empty sudo credentials applies the ISO-bound package; original code/policy were untouched and live work/keyboard survived.')+ shutdown(vm, record, 'updated-system')+ vm.start(live=False)+ vm.login_installed(config)+ authenticate()+ rebooted = observe('11-cold-boot-system', 'system', True)+ installed_matches(rebooted, bound)+ if rebooted['boot_id'] == before['boot_id']:+ raise ValueError('No real cold boot occurred')+ if observe('12-project-after-reboot', 'project') != project:+ raise ValueError('Home/project files changed across update reboot')+ if observe('13-checkpoint-after-reboot', 'checkpoint', True) != saved:+ raise ValueError('Checkpoint changed across candidate reboot')+ check_graphical_keyboard(vm, '14-candidate-keyboard')+ # The unchanged client restores shells, not their previous foreground+ # commands. Live agent preservation was proved before shutdown above;+ # now prove the bundled agent can start normally on the updated OS.+ vm.command('hn new-window -n agent-after-update ' + shlex.quote(+ 'cd "$HOME/projects/public-update-proof" && exec /usr/bin/opencode'))+ vm.command('for n in $(seq 1 90); do pgrep -u 1000 -x opencode >/dev/null && exit 0; sleep .5; done; exit 1', timeout=50)+ vm.command('test ! -e ' + STATE + '/current && test ! -e ' + STATE + '/ready.json')+ # The unchanged user timer finishes the one approved request after boot.+ # Do not manually activate the worker or issue a second update action.+ # Its two-minute startup delay also has up to 30 seconds of random delay+ # and systemd's default one-minute timer accuracy window. Retain the+ # actual scheduling evidence; a three-minute wait can expire too early.+ output, _ = vm.command('systemctl --user --no-pager show harness-update.timer harness-update.service', check=False)+ (folder / '15-update-units-before-wait.log').write_text(output)+ output, status = vm.command('for n in $(seq 1 600); do test ! -e ' + STATE ++ '/approved.json && exit 0; sleep .5; done; exit 1', timeout=305, check=False)+ (folder / '16-update-completion-wait.log').write_text(output)+ diagnostic = ('import json; from pathlib import Path; p=Path(' + repr(STATE) + '); '+ 'print(json.dumps({n:json.loads((p/n).read_text()) if (p/n).is_file() else None '+ 'for n in ["approved.json","check.json","system.json"]},indent=2))')+ output, _ = vm.command('python3 -c ' + shlex.quote(diagnostic))+ (folder / '17-update-completion-state.log').write_text(output)+ output, _ = vm.command('systemctl --user --no-pager show harness-update.timer harness-update.service', check=False)+ (folder / '18-update-units-after-wait.log').write_text(output)+ if status:+ authenticate()+ vm.command('sudo -n journalctl -b --no-pager > /tmp/public-update-completion-failed.log')+ (folder / 'completion-failed-journal.log').write_bytes(vm.read_file('/tmp/public-update-completion-failed.log'))+ raise TimeoutError('The ordinary update timer did not finish the approved request; see retained unit, state and journal evidence.')+ vm.command('test ! -e ' + STATE + '/current && test ! -e ' + STATE + '/ready.json')+ vm.command('sudo -n cat ' + FIXTURE + '/requests.jsonl > /tmp/public-update-requests.jsonl')+ requests = vm.read_file('/tmp/public-update-requests.jsonl')+ (folder / 'requests.jsonl').write_bytes(requests)+ logs = [json.loads(line) for line in requests.splitlines()]+ if not all(row['status'] == 200 and row['complete'] for row in logs):+ raise ValueError('Unexpected route, truncated response or attempted fast-runtime download')+ for suffix in ['metadata.json', 'package-manifest.json', candidate['package']['name']]:+ if not any(row['host'] == 'github.com' and row['path'].endswith('/' + suffix) for row in logs):+ raise ValueError('Missing actual release-channel request: ' + suffix)+ vm.command('sudo -n journalctl -b --no-pager > /tmp/public-update-final-journal.log')+ (folder / 'final-journal.log').write_bytes(vm.read_file('/tmp/public-update-final-journal.log'))+ record['checks'].append('Encrypted candidate cold boot accepts real keyboard input and an explicitly launched bundled agent, and preserves project bytes/ownership/times and the verified original checkpoint. Foreground command auto-resume is not claimed.')+ shutdown(vm, record, 'acceptance-complete')+ record['status'] = 'passed'+ except Exception as error:+ record.update(status='failed', error=f'{type(error).__name__}: {error}')+ try:+ if vm.process and vm.process.poll() is None:+ vm.screenshot('failure')+ except Exception as diagnostic:+ record['screenshot_error'] = str(diagnostic)+ raise+ finally:+ vm.stop()+ http.shutdown()+ http.server_close()+ thread.join(timeout=5)+ record['finished_at'] = time.time()+ record['duration_seconds'] = round(record['finished_at'] - record['started_at'], 3)+ record['private_transfer_stopped'] = not thread.is_alive()+ record['qemu_exit_code'] = vm.process.poll() if vm.process else None+ vm.control.cleanup()+ record['control_directory_removed'] = not vm.control_path.exists()+ for path in (fixture / 'ca.key', fixture / 'leaf.key', archive):+ path.unlink(missing_ok=True)+ (folder / 'receipt.json').write_text(json.dumps(record, indent=2) + '\n')+ print(json.dumps({'status': record['status'], 'receipt': str(folder / 'receipt.json')}))+++if __name__ == '__main__':+ main()diff --git a/os/tests/test_package_image_binding.py b/os/tests/test_package_image_binding.pynew file mode 100644index 000000000..0897cee81--- /dev/null+++ b/os/tests/test_package_image_binding.py@@ -0,0 +1,154 @@+import copy+import hashlib+import io+import json+from pathlib import Path+import shutil+import subprocess+import tarfile+import tempfile+import unittest+from unittest.mock import patch++import package_image_binding as binding+++class PackageImageBindingTests(unittest.TestCase):+ def test_version_identification_handles_unsquashfs_exit_convention_only(self):+ for tool, code, output, valid in [+ ('unsquashfs', 1, 'unsquashfs version 4.6.1 (2023/03/25)\n', True),+ ('unsquashfs', 0, 'unsquashfs version 4.7.2\n', True),+ ('unsquashfs', 1, 'unknown option\n', False),+ ('unsquashfs', 127, 'unsquashfs version 4.6.1\n', False),+ ('xorriso', 1, 'xorriso 1.5.6\n', False),+ ('xorriso', 0, 'xorriso 1.5.6\n', True)]:+ result = subprocess.CompletedProcess([tool, '-version'], code, output, '')+ with self.subTest(tool=tool, code=code, output=output), patch.object(binding.subprocess, 'run', return_value=result):+ if valid:+ self.assertEqual(binding.tool_version(tool)['version_exit_code'], code)+ else:+ with self.assertRaises(ValueError):+ binding.tool_version(tool)++ def setUp(self):+ self.temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self.temporary.cleanup)+ self.root = Path(self.temporary.name)+ self.version = '0.1.0pre15.r123.g1234567890-1'+ self.package = self.root / ('harness-os-' + self.version + '-x86_64.pkg.tar.gz')+ self.files = {'usr/lib/harness/harness-tui': b'actual runtime bytes',+ 'etc/sudoers.d/30-harness-updates': b'me ALL=(root) NOPASSWD: /usr/bin/harness upgrade\n'}+ self.write_archive()++ def write_archive(self, extra=()):+ with tarfile.open(self.package, 'w:gz') as archive:+ metadata = ('pkgname = harness-os\npkgver = ' + self.version + '\narch = x86_64\n').encode()+ for name, data in {'.PKGINFO': metadata, **self.files}.items():+ info = tarfile.TarInfo(name)+ info.mode = 0o440 if name.startswith('etc/') else 0o755+ info.size = len(data)+ archive.addfile(info, io.BytesIO(data))+ link = tarfile.TarInfo('usr/lib/harness/hn')+ link.type, link.linkname, link.mode = tarfile.SYMTYPE, 'harness-tui', 0o777+ archive.addfile(link)+ for entry in extra:+ archive.addfile(entry, io.BytesIO(b''))++ def listing(self):+ return binding.parse_listing('\n'.join([+ 'drwxr-xr-x 0/0 42 2026-10-05 01:00 squashfs-root/usr',+ f'-rwxr-xr-x 0/0 {len(self.files["usr/lib/harness/harness-tui"])} 2026-10-05 01:00 squashfs-root/usr/lib/harness/harness-tui',+ f'-r--r----- 0/0 {len(self.files["etc/sudoers.d/30-harness-updates"])} 2026-10-05 01:00 squashfs-root/etc/sudoers.d/30-harness-updates',+ 'lrwxrwxrwx 0/0 11 2026-10-05 01:00 squashfs-root/usr/lib/harness/hn -> harness-tui']))++ def test_real_archive_compares_every_file_and_link(self):+ rows = binding.archive_inventory(self.package, self.version)+ compared = binding.compare_members(rows, self.listing(), self.files.__getitem__)+ self.assertEqual({row['archive']['name'] for row in compared}, {*self.files, 'usr/lib/harness/hn'})+ self.assertTrue(all(row['equal'] for row in compared))+ binding.verify_owned_paths(rows, '%FILES%\nusr/\n' + '\n'.join(row['name'] for row in rows) + '\n\n')+ with self.assertRaisesRegex(ValueError, 'ownership list'):+ binding.verify_owned_paths(rows, '%FILES%\nusr/\nusr/lib/harness/harness-tui\n')++ def test_modified_missing_or_incorrectly_owned_iso_members_fail(self):+ rows = binding.archive_inventory(self.package, self.version)+ runtime = 'usr/lib/harness/harness-tui'+ for kind in ['bytes', 'missing', 'mode', 'owner', 'link']:+ with self.subTest(kind=kind):+ files, listing = dict(self.files), self.listing()+ if kind == 'bytes':+ files[runtime] = b'changed runtime bytes'+ elif kind == 'missing':+ listing.pop(runtime)+ elif kind == 'mode':+ listing[runtime]['mode_string'] = '-rw-r--r--'+ elif kind == 'owner':+ listing[runtime]['uid'] = 1000+ else:+ listing['usr/lib/harness/hn']['target'] = 'other-binary'+ with self.assertRaises(ValueError):+ binding.compare_members(rows, listing, files.__getitem__)++ def test_unsafe_duplicate_and_hardlinked_archive_entries_fail(self):+ entries = [tarfile.TarInfo('../escape'), tarfile.TarInfo('/absolute'),+ tarfile.TarInfo('usr/lib/harness/harness-tui'), tarfile.TarInfo('usr/ambiguous -> name')]+ hardlink = tarfile.TarInfo('usr/hardlink')+ hardlink.type, hardlink.linkname = tarfile.LNKTYPE, 'usr/lib/harness/harness-tui'+ entries.append(hardlink)+ for entry in entries:+ with self.subTest(name=entry.name):+ self.write_archive([entry])+ with self.assertRaises(ValueError):+ binding.archive_inventory(self.package, self.version)++ def test_manifests_bind_real_package_and_image_bytes(self):+ iso = self.root / 'candidate.iso'+ iso.write_bytes(b'private image fixture')+ runtime = {'source_commit': 'a' * 40, 'dirty': False, 'target': 'x86_64-unknown-linux-musl',+ 'files': {name: {'bytes': 1, 'sha256': hashlib.sha256(b'x').hexdigest()}+ for name in ('harness-tui', 'cli.mjs', 'notify.mjs')}}+ manifest = {'schema': 1, 'kind': 'harness-os-package', 'source_commit': 'a' * 40,+ 'architecture': 'x86_64', 'requires_os_version': '0.1.0-preview.15',+ 'arch_snapshot': '2026/10/01', 'runtime': runtime,+ 'package': {'name': self.package.name, 'version': self.version, **binding.identity(self.package)}}+ image = {'source_commit': 'a' * 40, 'architecture': 'x86_64', 'version': '0.1.0-preview.15',+ 'arch_snapshot': '2026/10/01', 'package_version': self.version, 'harness_inputs': runtime,+ 'iso': {'name': iso.name, **binding.identity(iso)}}+ (self.root / 'manifest.json').write_text(json.dumps(image))+ (self.root / 'package-manifest.json').write_text(json.dumps(manifest))+ binding.validate_inputs(iso, self.root)+ for key in ('source_commit', 'runtime', 'package'):+ altered = copy.deepcopy(manifest)+ if key == 'source_commit':+ altered[key] = 'b' * 40+ elif key == 'runtime':+ altered[key]['dirty'] = True+ else:+ altered[key]['sha256'] = '0' * 64+ (self.root / 'package-manifest.json').write_text(json.dumps(altered))+ with self.subTest(key=key), self.assertRaises(ValueError):+ binding.validate_inputs(iso, self.root)+ (self.root / 'package-manifest.json').write_text(json.dumps(manifest))+ iso.write_bytes(b'changed image fixture')+ with self.assertRaisesRegex(ValueError, 'hash or size'):+ binding.validate_inputs(iso, self.root)++ @unittest.skipUnless(shutil.which('mksquashfs') and shutil.which('unsquashfs'), 'Native SquashFS tools required')+ def test_native_squashfs_listing_and_bytes(self):+ root = self.root / 'payload'+ for name, data in self.files.items():+ path = root / name+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(data)+ path.chmod(0o440 if name.startswith('etc/') else 0o755)+ (root / 'usr/lib/harness/hn').symlink_to('harness-tui')+ payload = self.root / 'payload.sfs'+ subprocess.run(['mksquashfs', str(root), str(payload), '-all-root', '-noappend', '-no-progress', '-processors', '1'],+ check=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=15)+ listing = binding.parse_listing(subprocess.check_output(['unsquashfs', '-lln', str(payload)], text=True))+ rows = binding.archive_inventory(self.package, self.version)+ binding.compare_members(rows, listing, lambda name: subprocess.check_output(['unsquashfs', '-cat', str(payload), name]))+++if __name__ == '__main__':+ unittest.main()diff --git a/os/tests/test_public_update_observer.py b/os/tests/test_public_update_observer.pynew file mode 100644index 000000000..3d30f767c--- /dev/null+++ b/os/tests/test_public_update_observer.py@@ -0,0 +1,88 @@+import copy+import io+import json+from pathlib import Path+import tarfile+import tempfile+import unittest++import package_image_binding as binding+import public_update_vm as observer+++class PublicUpdateObserverTests(unittest.TestCase):+ def test_one_replaced_process_or_project_change_cannot_pass(self):+ before = {'agents': [{'pid': 42, 'start': 100}], 'daemon': {'pid': 12, 'start': 1},+ 'terminal': {'pid': 50, 'start': 101}, 'project': {'notes': 'digest'},+ 'boot_id': 'original-boot', 'heartbeat': 100}+ after = dict(before, heartbeat=200)+ observer.same_work(before, after)+ for key in ('agents', 'daemon', 'terminal', 'project', 'boot_id', 'heartbeat'):+ bad = copy.deepcopy(after)+ bad[key] = 100 if key == 'heartbeat' else 'changed'+ with self.subTest(key=key), self.assertRaises(ValueError):+ observer.same_work(before, bad)++ def test_installed_bytes_permissions_links_and_ownership_are_checked(self):+ files = [dict(name='usr/lib/harness/hn', type='symlink', target='harness-tui', mode=0o777, uid=0, gid=0),+ dict(name='usr/lib/harness/harness-tui', type='file', bytes=10, sha256='a'*64, mode=0o755, uid=0, gid=0)]+ receipt = dict(runtime={'source_commit': 'a'*40}, package_version='1-1',+ members=[dict(archive=row) for row in files])+ installed = dict(runtime=receipt['runtime'], package_version='1-1', owned_files={+ row['name']: {k: v for k, v in row.items() if k != 'name'} for row in files})+ observer.installed_matches(installed, receipt)+ for key in ('mode', 'uid', 'gid', 'bytes', 'sha256', 'type'):+ bad = copy.deepcopy(installed)+ bad['owned_files'][files[1]['name']][key] = 'wrong'+ with self.subTest(key=key), self.assertRaises(ValueError):+ observer.installed_matches(bad, receipt)+ for change in ('missing', 'extra', 'link'):+ bad = copy.deepcopy(installed)+ if change == 'missing': bad['owned_files'].pop(files[0]['name'])+ elif change == 'extra': bad['owned_files']['usr/undeclared'] = files[1]+ else: bad['owned_files'][files[0]['name']]['target'] = 'another-binary'+ with self.subTest(change=change), self.assertRaises(ValueError):+ observer.installed_matches(bad, receipt)++ def test_binding_must_cover_exact_artifacts_and_every_member(self):+ with tempfile.TemporaryDirectory() as temporary:+ root = Path(temporary)+ version = '0.1.0pre15-1'+ package = root / ('harness-os-' + version + '-x86_64.pkg.tar.gz')+ with tarfile.open(package, 'w:gz') as archive:+ for name, data in {'.PKGINFO': ('pkgname = harness-os\npkgver = '+version+'\narch = x86_64\n').encode(),+ 'usr/test': b'actual candidate bytes'}.items():+ info = tarfile.TarInfo(name)+ info.mode, info.size = 0o644, len(data)+ archive.addfile(info, io.BytesIO(data))+ runtime = {'source_commit': 'a'*40}+ manifest = dict(source_commit='a'*40, runtime=runtime,+ package=dict(name=package.name, version=version, **binding.identity(package)))+ image = dict(source_commit='a'*40, harness_inputs=runtime,+ iso={'name': 'candidate.iso', 'bytes': 42, 'sha256': 'b'*64})+ manifest_path, image_path, receipt_path = (root / name for name in ('package-manifest.json', 'manifest.json', 'binding.json'))+ manifest_path.write_text(json.dumps(manifest))+ image_path.write_text(json.dumps(image))+ receipt = dict(status='passed', overrides=[], source_commit='a'*40, runtime=runtime,+ package_version=version, package=dict(name=package.name, **binding.identity(package)),+ package_manifest=binding.identity(manifest_path), image_manifest=binding.identity(image_path),+ image={k: image['iso'][k] for k in ('bytes', 'sha256')},+ members=[dict(archive=row, equal=True) for row in binding.archive_inventory(package, version)])+ receipt_path.write_text(json.dumps(receipt))+ observer.verify_binding(root, image_path, receipt_path)+ for change in ('source', 'failed', 'override', 'omitted', 'unequal', 'changed-archive', 'wrong-image'):+ bad = copy.deepcopy(receipt)+ if change == 'source': bad['source_commit'] = 'c'*40+ elif change == 'failed': bad['status'] = 'failed'+ elif change == 'override': bad['overrides'] = ['ignore changed bytes']+ elif change == 'omitted': bad['members'] = []+ elif change == 'unequal': bad['members'][0]['equal'] = False+ elif change == 'changed-archive': bad['members'][0]['archive']['mode'] = 0o777+ else: bad['image']['sha256'] = '0'*64+ receipt_path.write_text(json.dumps(bad))+ with self.subTest(change=change), self.assertRaises(ValueError):+ observer.verify_binding(root, image_path, receipt_path)+++if __name__ == '__main__':+ unittest.main()diff --git a/os/tests/test_public_update_transport.py b/os/tests/test_public_update_transport.pynew file mode 100644index 000000000..b5d7c45d4--- /dev/null+++ b/os/tests/test_public_update_transport.py@@ -0,0 +1,88 @@+import hashlib+import json+from pathlib import Path+import socket+import ssl+import tempfile+import threading+import unittest++import public_update_transport as transport+++class PrivateTransportTests(unittest.TestCase):+ def setUp(self):+ self.temp = tempfile.TemporaryDirectory()+ self.addCleanup(self.temp.cleanup)+ self.root = Path(self.temp.name)+ self.bundle = self.root / 'bundle'+ self.bundle.mkdir()+ self.name = 'harness-os-0.1.0pre15-1-x86_64.pkg.tar.gz'+ (self.bundle / self.name).write_bytes(b'exact candidate package')+ manifest = {'requires_os_version': '0.1.0-preview.15',+ 'package': {'name': self.name, **transport.file_identity(self.bundle / self.name)}}+ (self.bundle / 'package-manifest.json').write_text(json.dumps(manifest))+ self.folder = self.root / 'server'+ self.routes = transport.prepare(self.bundle, self.folder, {'hn': {'version': '0.1.12'}, 'cli': {'version': '0.3.58'}})++ def test_routes_offer_exact_os_assets_and_no_new_fast_runtime(self):+ self.assertEqual(len(self.routes), 5)+ metadata = json.loads((self.folder / 'metadata.json').read_text())+ for field, name in [('manifest', 'package-manifest.json'), ('package', self.name)]:+ self.assertEqual(metadata[field], {'url': 'https://github.com' + transport.ASSETS ++ 'os-v0.1.0-preview.15/' + name,+ **transport.file_identity(self.bundle / name)})+ self.assertEqual(json.loads((self.folder / 'hn.json').read_text())['version'], '0.1.12')+ self.assertEqual(json.loads((self.folder / 'cli.json').read_text())['cli']['version'], '0.3.58')+ (self.bundle / self.name).write_bytes(b'changed candidate package')+ with self.assertRaisesRegex(ValueError, 'differs'):+ transport.prepare(self.bundle, self.root / 'corrupt', {'hn': {'version': '0.1.12'}, 'cli': {'version': '0.3.58'}})++ def test_real_tls_requires_trust_and_correct_hostname_and_exact_route(self):+ transport.certificates(self.folder)+ service = transport.server(self.folder, port=0)+ thread = threading.Thread(target=service.serve_forever, daemon=True)+ thread.start()+ try:+ def request(context, hostname='github.com', host='github.com', path=transport.FEED):+ with socket.create_connection(service.server_address, timeout=5) as raw:+ with context.wrap_socket(raw, server_hostname=hostname) as connection:+ connection.sendall(f'GET {path} HTTP/1.0\r\nHost: {host}\r\n\r\n'.encode())+ chunks = []+ while chunk := connection.recv(65536):+ chunks.append(chunk)+ return b''.join(chunks)++ with self.assertRaises(ssl.SSLCertVerificationError):+ request(ssl.create_default_context())+ trusted = ssl.create_default_context(cafile=self.folder / 'ca.crt')+ with self.assertRaises(ssl.SSLCertVerificationError):+ request(trusted, hostname='unrelated.example')+ valid = request(trusted)+ self.assertIn(b' 200 ', valid.split(b'\r\n', 1)[0])+ body = valid.split(b'\r\n\r\n', 1)[1]+ self.assertEqual(body, (self.folder / 'metadata.json').read_bytes())+ for host, path in [('github.com', '/ca.key'), ('github.com', transport.FEED + '?extra=1'),+ ('github.com', '/../../package-manifest.json'), ('unrelated.example', transport.FEED)]:+ result = request(trusted, host=host, path=path)+ self.assertIn(b' 404 ', result.split(b'\r\n', 1)[0])+ finally:+ service.shutdown()+ service.server_close()+ thread.join(timeout=5)+ self.assertFalse(thread.is_alive())+ records = [json.loads(line) for line in (self.folder / 'requests.jsonl').read_text().splitlines()]+ successful = [record for record in records if record['status'] == 200]+ self.assertEqual(len(successful), 1)+ self.assertTrue(successful[0]['complete'])+ self.assertEqual(successful[0]['sha256'], hashlib.sha256(body).hexdigest())+ self.assertEqual(sum(record['status'] == 404 for record in records), 4)++ def test_server_refuses_modified_asset(self):+ (self.folder / 'metadata.json').write_text('{}')+ with self.assertRaisesRegex(ValueError, 'route'):+ transport.server(self.folder, port=0)+++if __name__ == '__main__':+ unittest.main()