Files
rust-discovery/tests/apt_transaction/test_partial_reconciliation.py
2026-11-13 17:20:50 +01:00

119 lines
8.7 KiB
Python

"""Original-bound readonly proof only; all native package queries mocked."""
from dataclasses import replace
from pathlib import Path
import tempfile
import uuid
from unittest import TestCase
from unittest.mock import patch
from test_guard import apt
from test_native_acceptance import signed_job, prechecks
import test_native_retry as retry_fixture
class PartialReconciliationTests(TestCase):
def scenario(self, variation=None):
with tempfile.TemporaryDirectory(dir='/tmp/opencode') as temp:
base = Path(temp)
with patch.object(apt, 'BASE', base), patch.object(apt, 'ACTIVE', base/'active'), \
patch.object(apt, 'secure_path', side_effect=lambda path, **kwargs: path), \
patch.object(apt, 'sealed_read', side_effect=lambda path, *args, **kwargs:
b'1.0\n' if path == Path('/usr/share/rmm-mvp-test/version') else path.read_bytes()):
tx, ctx, action, old, previous, original = retry_fixture.NativeRetryTests().setup_history(base)
ctx = replace(ctx, job_id=str(uuid.uuid4()), authorization_id=str(uuid.uuid4()))
job_bytes = apt.canonical(signed_job(ctx, action))
ctx = replace(ctx, job_payload_sha256=apt.digest(job_bytes))
active = base/'active'
(active/'context.json').write_bytes(apt.canonical(ctx.__dict__))
(active/'signed-action.json').write_bytes(job_bytes)
(active/'apt.conf').write_bytes(apt.apt_config())
# setup_history's manifest uses the current config only as a
# synthetic historical fixture; actual VM history may differ.
path, binding = apt.bootstrap_binding(tx, ctx, action)
apt.durable_once(path, binding)
files = {
'launch.json': {'transaction_sha256': ctx.transaction_sha256,
'effect_armed_ledger_id': ctx.effect_armed_ledger_id},
'native-prechecks.json': prechecks(ctx),
'sandbox-ready.json': {'sandbox_version': 1, 'transaction_sha256': ctx.transaction_sha256},
'sandbox-result.json': {'transaction_sha256': ctx.transaction_sha256,
'apt_exit_code': 0, 'reboot_required': False},
'hook-armed.json': {'armed_at_ms': 2000, 'effect_armed_ledger_id': ctx.effect_armed_ledger_id,
'grant_id': ctx.grant_id, 'transaction_sha256': ctx.transaction_sha256,
'protocol_sha256': 'e'*64},
}
for name, value in files.items(): (active/name).write_bytes(apt.canonical(value))
fields = ('transaction_sha256 job_payload_sha256 effect_armed_ledger_id grant_id '
'job_id attempt_id authorization_id plan_sha256')
request = {key: getattr(ctx, key) for key in fields.split()}
observed = {'rmm-mvp-test:all': {'version': '1.0', 'status': 'install ok unpacked'}}
expected_files = {str(p.relative_to(base)): p.read_bytes() for p in base.rglob('*') if p.is_file()}
if variation == 'foreign-lock': pass
elif variation == 'different-package': observed['other:amd64'] = {'version': '1', 'status': 'install ok installed'}
elif variation == 'installed': observed['rmm-mvp-test:all']['status'] = 'install ok installed'
elif variation == 'other-version': observed['rmm-mvp-test:all']['version'] = '1.1'
elif variation == 'missing-hook': (active/'hook-armed.json').unlink()
elif variation == 'false-exit':
files['sandbox-result.json']['apt_exit_code'] = False
(active/'sandbox-result.json').write_bytes(apt.canonical(files['sandbox-result.json']))
elif variation == 'apt-failed':
files['sandbox-result.json']['apt_exit_code'] = 100
(active/'sandbox-result.json').write_bytes(apt.canonical(files['sandbox-result.json']))
elif variation == 'wrong-context': request['grant_id'] = str(uuid.uuid4())
elif variation == 'config-tamper': (active/'apt.conf').write_bytes(b'changed')
elif variation == 'accepted': apt.record_path(tx).write_bytes(b'{}')
elif variation == 'precheck':
files['native-prechecks.json']['checks']['readonly_controlpaths'] = False
(active/'native-prechecks.json').write_bytes(apt.canonical(files['native-prechecks.json']))
before = {str(p.relative_to(base)): p.read_bytes() for p in base.rglob('*') if p.is_file()}
with patch.object(apt.os, 'geteuid', return_value=0), \
patch.object(Path, 'read_text', return_value=ctx.boot_id if variation != 'boot' else 'different-boot'), \
patch.object(apt, 'observe_host_frontend_lock', return_value=variation == 'foreign-lock'), \
patch.object(apt, 'status_fingerprint', side_effect=['a'*64, 'b'*64] if variation == 'changed' else None,
return_value='a'*64), \
patch.object(apt, 'partial_installed_snapshot', return_value=observed), \
patch.object(apt, 'verify_archive') as archive, \
patch.object(apt.subprocess, 'Popen', side_effect=AssertionError('No effect process permitted')):
if variation is not None:
with self.assertRaises((apt.Veto, OSError, ValueError)):
apt.verify_partial(request)
else:
result = apt.verify_partial(request)
self.assertEqual(result['effect_state'], 'known_failed')
self.assertEqual(result['code'], 'APT_PARTIAL_UNCONFIGURED_VERIFIED')
proof = result['proof']
self.assertEqual(proof['snapshot'], observed)
self.assertEqual(proof['observed_snapshot_sha256'], apt.digest(apt.canonical(observed)))
self.assertTrue(proof['partial_effect'])
self.assertFalse(proof['postconditions_passed'])
self.assertFalse(proof['reboot_required'])
self.assertEqual(proof['fixture_payload_sha256'], apt.digest(b'1.0\n'))
self.assertEqual({key: proof[key] for key in fields.split()}, request)
names = ('context.json', 'signed-action.json', 'expectation.json', 'baseline.json',
'launch.json', 'native-prechecks.json', 'sandbox-ready.json', 'sandbox-result.json', 'hook-armed.json')
raw = {name: (active/name).read_bytes() for name in names}
raw[original.name] = original.read_bytes(); raw[path.name] = path.read_bytes()
self.assertEqual(proof['original_evidence_sha256'], apt.digest(apt.canonical({n: apt.digest(v) for n,v in raw.items()})))
archive.assert_called_once_with(tx.packages[0])
after = {str(p.relative_to(base)): p.read_bytes() for p in base.rglob('*') if p.is_file()}
self.assertEqual(before, after, 'verification must never create/change/delete evidence')
if variation is None: self.assertEqual(expected_files, after)
def test_original_bound_partial_is_failed_not_success_and_has_no_writes(self):
self.scenario()
def test_uncertain_or_mismatched_partial_state_never_closes_unknown(self):
for variation in ('foreign-lock','different-package','installed','other-version','missing-hook',
'false-exit','apt-failed','wrong-context','config-tamper','accepted','precheck','boot','changed'):
with self.subTest(variation=variation): self.scenario(variation)
def test_partial_snapshot_does_not_relax_other_packages_or_ordinary_snapshot(self):
query = b'rmm-mvp-test\tall\t1.0\tinstall ok unpacked\n'
with patch.object(apt, 'run_read', return_value=query):
self.assertEqual(apt.partial_installed_snapshot()['rmm-mvp-test:all']['status'], 'install ok unpacked')
with self.assertRaisesRegex(apt.Veto, 'DPKG_INCONSISTENT'): apt.installed_snapshot()
for data in (query+query, b'other\tamd64\t1\tinstall ok unpacked\n',
b'rmm-mvp-test\tall\t1.1\tinstall ok unpacked\n', b'malformed\n'):
with self.subTest(data=data), patch.object(apt, 'run_read', return_value=data), self.assertRaises(apt.Veto):
apt.partial_installed_snapshot()