"""Bound configure-only recovery on temporary sealed files; no package effects.""" import copy from contextlib import contextmanager 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 context, fixture_transaction, action_manifest, signed_job, prechecks, host_before import test_native_retry as retry_fixture def recovery_transaction(): obj = fixture_transaction() obj.update(schema_version=2, operation='configure_only') obj['packages'][0]['old_version'] = '1.0' return obj @contextmanager def recovery_files(): with tempfile.TemporaryDirectory(dir='/tmp/opencode') as temp: base = Path(temp) def read(path, *args, **kwargs): if path == apt.CODE: return b'code' if path == Path(apt.HOOK): return apt.hook_script() if path == Path('/usr/share/rmm-mvp-test/version'): return b'1.0\n' return path.read_bytes() 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=read): tx, old, action, _, _, _ = retry_fixture.NativeRetryTests().setup_history(base) old = replace(old, job_id=str(uuid.uuid4()), authorization_id=str(uuid.uuid4())) old_job = apt.canonical(signed_job(old, action)) old = replace(old, job_payload_sha256=apt.digest(old_job)) active = apt.ACTIVE (active/'context.json').write_bytes(apt.canonical(old.__dict__)) (active/'signed-action.json').write_bytes(old_job) (active/'apt.conf').write_bytes(apt.apt_config()) marker, binding = apt.bootstrap_binding(tx, old, action) apt.durable_once(marker, binding) files = {'launch.json': {'transaction_sha256': old.transaction_sha256, 'effect_armed_ledger_id': old.effect_armed_ledger_id}, 'native-prechecks.json': prechecks(old), 'sandbox-ready.json': {'sandbox_version': 1, 'transaction_sha256': old.transaction_sha256}, 'sandbox-result.json': {'transaction_sha256': old.transaction_sha256, 'apt_exit_code': 0, 'reboot_required': False}, 'hook-armed.json': {'armed_at_ms': 2000, 'effect_armed_ledger_id': old.effect_armed_ledger_id, 'grant_id': old.grant_id, 'transaction_sha256': old.transaction_sha256, 'protocol_sha256': 'e'*64}} for name, obj in files.items(): (active/name).write_bytes(apt.canonical(obj)) snapshot = {'rmm-mvp-test:all': {'version': '1.0', 'status': 'install ok unpacked'}} fields = ('transaction_sha256 job_payload_sha256 effect_armed_ledger_id grant_id ' 'job_id attempt_id authorization_id plan_sha256') with patch.object(apt.os, 'geteuid', return_value=0), \ patch.object(Path, 'read_text', return_value=old.boot_id), \ patch.object(apt, 'observe_host_frontend_lock', return_value=False), \ patch.object(apt, 'status_fingerprint', return_value='a'*64), \ patch.object(apt, 'partial_installed_snapshot', return_value=snapshot), \ patch.object(apt, 'verify_archive'): proof = apt.verify_partial({key: getattr(old, key) for key in fields.split()})['proof'] previous = base/'history'/old.grant_id active.rename(previous) active.mkdir() obj = recovery_transaction() obj.update(status_fingerprint=proof['status_fingerprint'], baseline_sha256=proof['observed_snapshot_sha256']) tx = apt.ResolvedAptTransaction.parse(obj) new = replace(context(), transaction_sha256=apt.digest(apt.canonical(obj)), grant_id=str(uuid.uuid4()), attempt_id=str(uuid.uuid4()), job_id=str(uuid.uuid4()), authorization_id=str(uuid.uuid4()), plan_sha256='f'*64) action = action_manifest(new, obj, {}) action.update(schema_version=4, native_recovery={'schema_version': 1, 'previous_grant_id': old.grant_id, 'previous_attempt_id': old.attempt_id, 'partial_proof_sha256': apt.digest(apt.canonical(proof))}) new_job = apt.canonical(signed_job(new, action)) new = replace(new, job_payload_sha256=apt.digest(new_job)) for name, data in {'context.json': apt.canonical(new.__dict__), 'signed-action.json': new_job, 'expectation.json': apt.canonical(obj), 'baseline.json': apt.canonical(snapshot), 'partial-proof.json': apt.canonical(proof), 'apt.conf': apt.apt_config(), 'host-reboot-before.json': apt.canonical(host_before(new)), 'native-prechecks.json': apt.canonical(prechecks(new,host_before(new))), 'sandbox-result.json': apt.canonical({'transaction_sha256':new.transaction_sha256,'apt_exit_code':0,'reboot_required':False}), 'hook-armed.json': b'{}'}.items(): (active/name).write_bytes(data) yield base, tx, new, action, proof, previous class NativeRecoveryTests(TestCase): def test_configure_only_schema_and_actual_action_set_are_fixed(self): obj = recovery_transaction() tx = apt.ResolvedAptTransaction.parse(obj) configure = apt.Action('rmm-mvp-test','1.0','all','none','=','1.0','all','none','**CONFIGURE**') apt.validate_actions(tx, (configure,)) for actions in ((), (configure,configure), (replace(configure, action=tx.packages[0].archive_path),), (replace(configure, direction='<'),), (replace(configure, name='other'),), (replace(configure, new_version='1.1'),)): with self.subTest(actions=actions), self.assertRaises(apt.Veto): apt.validate_actions(tx, actions) for change in ({'schema_version':1}, {'operation':'repair_pending'}, {'recipe_id':'other'}): bad = copy.deepcopy(obj);bad.update(change) with self.subTest(change=change), self.assertRaises(apt.Veto): apt.ResolvedAptTransaction.parse(bad) for old,new in ((None,'1.0'),('1.0','1.1'),('1.1','1.1')): bad = copy.deepcopy(obj);bad['packages'][0].update(old_version=old,new_version=new) with self.assertRaises(apt.Veto): apt.ResolvedAptTransaction.parse(bad) def test_new_signed_recovery_preserves_history_and_cannot_create_install_acceptance(self): with recovery_files() as (base,tx,ctx,action,proof,previous): original = {str(p.relative_to(base)): p.read_bytes() for p in base.rglob('*') if p.is_file() and 'active/' not in str(p.relative_to(base))} self.assertEqual(apt.load_signed_action(tx,ctx),action) self.assertEqual(apt.verify_recovery_reference(tx,ctx,action),proof) apt.check_native_gate(tx,ctx,action,{},True) path,binding = apt.bootstrap_binding(tx,ctx,action) self.assertEqual(path.name,'recovery-attempt-'+proof['grant_id']+'.json') apt.durable_once(path,binding) with self.assertRaisesRegex(apt.Veto,'ALREADY_HANDED_OFF'): apt.durable_once(path,binding) with patch.object(apt,'runtime_identity',return_value={}),patch.object(Path,'read_text',return_value=ctx.boot_id): evidence = apt.complete_acceptance(tx,ctx,action,{}, {'reboot_required':False}) self.assertTrue(evidence['native_recovery']) self.assertNotIn('native_record_sha256',evidence) record = apt.json_bytes((base/('recovery-'+proof['grant_id']+'.json')).read_bytes()) self.assertEqual(record['operation'],'configure_only') self.assertEqual(record['native_recovery'],action['native_recovery']) self.assertFalse(apt.record_path(tx).exists()) for name,data in original.items(): self.assertEqual((base/name).read_bytes(),data) with self.assertRaisesRegex(apt.Veto,'RECOVERY_ALREADY_RECORDED'): apt.check_native_gate(tx,ctx,action,{},True) def test_recovery_rejects_proof_history_approval_and_current_state_mismatch(self): with recovery_files() as (_,tx,ctx,action,proof,previous): for changed in (replace(ctx,grant_id=proof['grant_id']),replace(ctx,job_id=proof['job_id']), replace(ctx,authorization_id=proof['authorization_id']),replace(ctx,plan_sha256=proof['plan_sha256'])): with self.assertRaises(apt.Veto): apt.verify_recovery_reference(tx,changed,action) bad = copy.deepcopy(action);bad['native_recovery']['partial_proof_sha256']='0'*64 with self.assertRaises(apt.Veto): apt.verify_recovery_reference(tx,ctx,bad) (previous/'sandbox-result.json').write_bytes(b'{}') with self.assertRaisesRegex(apt.Veto,'RECOVERY_HISTORY_CHANGED'): apt.verify_recovery_reference(tx,ctx,action) with patch.object(apt,'status_fingerprint',return_value=tx.status_fingerprint), \ patch.object(apt,'partial_installed_snapshot',return_value={}), \ patch.object(apt,'installed_snapshot',side_effect=AssertionError('ordinary parser stays strict')): with self.assertRaisesRegex(apt.Veto,'STATUS_BASELINE_CHANGED'): apt.check_preconditions(tx,proof['snapshot']) def test_passive_recovery_planning_rechecks_original_and_seals_only_exact_partial_baseline(self): with recovery_files() as (base,tx,ctx,action,proof,previous): apt.ACTIVE.rename(base/'new-staged') previous.rename(apt.ACTIVE) old = apt.json_bytes((apt.ACTIVE/'context.json').read_bytes()) (base/'archives').mkdir();(base/'baselines').mkdir() for version,sha in apt.FIXTURE_SHA256.items(): (base/'archives'/(sha+'.deb')).write_bytes(apt.fixture_archive(version)) (base/('prefetch-'+sha+'.json')).write_bytes(apt.canonical({ 'schema_version':1,'sha256':sha,'size':20672,'sealed_at_ms':1000})) request = {'native_recovery':action['native_recovery'],'proof':proof} before = {p: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=old['boot_id']), \ patch.object(apt,'observe_host_frontend_lock',return_value=False), \ patch.object(apt,'status_fingerprint',return_value=proof['status_fingerprint']), \ patch.object(apt,'partial_installed_snapshot',return_value=proof['snapshot']), \ patch.object(apt,'installed_snapshot',side_effect=apt.Veto('DPKG_INCONSISTENT')), \ patch.object(apt,'verify_archive'),patch.object(apt,'archive_metadata'), \ patch.object(apt,'runtime_identity',return_value={}): result = apt.recovery_planning(request) self.assertEqual(result['native_recovery'],request['native_recovery']) self.assertEqual(result['baseline_sha256'],proof['observed_snapshot_sha256']) self.assertEqual(result['fixture_package'],{'version':'1.0','status':'install ok unpacked'}) with self.assertRaisesRegex(apt.Veto,'DPKG_INCONSISTENT'): apt.planning_status() changed = copy.deepcopy(request);changed['proof']['original_evidence_sha256']='0'*64 changed['native_recovery']['partial_proof_sha256']=apt.digest(apt.canonical(changed['proof'])) with self.assertRaisesRegex(apt.Veto,'RECOVERY_PLANNING_STATE_CHANGED'): apt.recovery_planning(changed) with patch.object(apt,'observe_host_frontend_lock',return_value=True): with self.assertRaisesRegex(apt.Veto,'FOREIGN_PACKAGE_LOCK'): apt.recovery_planning(request) for path,data in before.items(): self.assertEqual(path.read_bytes(),data) self.assertEqual((base/'baselines'/(proof['observed_snapshot_sha256']+'.json')).read_bytes(),apt.canonical(proof['snapshot'])) self.assertFalse((base/('recovery-attempt-'+proof['grant_id']+'.json')).exists())