200 lines
12 KiB
Python
200 lines
12 KiB
Python
"""Harmless tmp fixtures only; root ownership/system state/providers mocked."""
|
|
import copy
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import stat
|
|
import tempfile
|
|
from types import SimpleNamespace
|
|
from unittest import TestCase
|
|
from unittest.mock import patch
|
|
|
|
from test_guard import apt, ROOT
|
|
from test_native_acceptance import fixture_transaction, context, action_manifest
|
|
|
|
|
|
class PlanningTests(TestCase):
|
|
def run_planning(self, variation=None):
|
|
with tempfile.TemporaryDirectory(dir='/tmp/opencode') as temp:
|
|
base = Path(temp)
|
|
(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}))
|
|
pin = apt.FIXTURE_SHA256['1.0']
|
|
if variation == 'bytes':
|
|
(base / 'archives' / (pin + '.deb')).write_bytes(b'x' * 20672)
|
|
if variation == 'receipt':
|
|
(base / ('prefetch-' + pin + '.json')).write_bytes(apt.canonical({
|
|
'schema_version': 1, 'sha256': pin, 'size': 20672, 'sealed_at_ms': 10**30}))
|
|
if variation == 'missing':
|
|
(base / ('prefetch-' + pin + '.json')).unlink()
|
|
initial = {'rmm-mvp-test:all': {'version': '1.0', 'status': 'install ok installed'},
|
|
'private-business-package:amd64': {'version': 'secret', 'status': 'install ok installed'}}
|
|
current = copy.deepcopy(initial)
|
|
runtime = {'apt_config_sha256': apt.digest(apt.apt_config()), 'schema_version': 1}
|
|
def read(path, *args):
|
|
if path == apt.CODE:
|
|
return b'code'
|
|
if path == Path(apt.HOOK):
|
|
return apt.hook_script()
|
|
return path.read_bytes()
|
|
original_metadata = apt.archive_metadata
|
|
def metadata(st, size):
|
|
# Only ownership is simulated. Real bytes/size/link count are
|
|
# used, and production metadata validation remains exercised.
|
|
original_metadata(SimpleNamespace(st_uid=0,
|
|
st_mode=stat.S_IFREG | (0o622 if variation == 'writable' else 0o600),
|
|
st_size=st.st_size, st_nlink=st.st_nlink), size)
|
|
fingerprint_error = apt.Veto('DPKG_DIRTY_UPDATES') if variation == 'dirty' else None
|
|
if variation == 'drift':
|
|
fingerprint_error = ['b' * 64, 'c' * 64]
|
|
with patch.object(apt, 'BASE', base), patch.object(apt.os, 'geteuid', return_value=0), \
|
|
patch.object(apt, 'secure_path', side_effect=lambda p, **k: p), \
|
|
patch.object(apt, 'sealed_read', side_effect=read), \
|
|
patch.object(apt, 'archive_metadata', side_effect=metadata), \
|
|
patch.object(apt, 'observe_host_frontend_lock', return_value=variation == 'locked'), \
|
|
patch.object(apt, 'status_fingerprint', return_value='b' * 64, side_effect=fingerprint_error), \
|
|
patch.object(apt, 'installed_snapshot', side_effect=lambda: copy.deepcopy(current)), \
|
|
patch.object(apt, 'runtime_identity', return_value=runtime), \
|
|
patch.object(apt.os, 'fsync', wraps=os.fsync) as sync:
|
|
first = apt.planning_status()
|
|
self.assertIs(type(first['host_reboot_required']),bool)
|
|
self.assertGreaterEqual(sync.call_count, 2)
|
|
self.assertNotIn('private-business-package', json.dumps(first))
|
|
sealed = base / 'baselines' / (first['baseline_sha256'] + '.json')
|
|
self.assertEqual(apt.digest(sealed.read_bytes()), first['baseline_sha256'])
|
|
self.assertEqual(json.loads(sealed.read_bytes()), initial)
|
|
self.assertEqual(first['baseline_sha256'], first['sealed_baseline_sha256'])
|
|
self.assertEqual(first['runtime_sha256'], apt.digest(apt.canonical(runtime)))
|
|
before = sealed.stat().st_mtime_ns
|
|
self.assertEqual(apt.planning_status()['baseline_sha256'], first['baseline_sha256'])
|
|
self.assertEqual(sealed.stat().st_mtime_ns, before)
|
|
current['rmm-mvp-test:all']['version'] = '1.1'
|
|
fresh = apt.planning_status()
|
|
self.assertNotEqual(first['baseline_sha256'], fresh['baseline_sha256'])
|
|
self.assertEqual(fresh['fixture_package']['version'], '1.1')
|
|
self.assertEqual(len(list((base / 'baselines').iterdir())), 2)
|
|
self.assertFalse((base / 'active').exists())
|
|
|
|
def test_passive_seal_is_content_addressed_fresh_and_private(self):
|
|
self.run_planning()
|
|
|
|
def test_bad_receipts_bytes_ownership_dirty_or_locked_are_not_observations(self):
|
|
for variation in ('bytes', 'receipt', 'missing', 'writable', 'dirty', 'locked'):
|
|
with self.subTest(variation=variation), self.assertRaises((apt.Veto, OSError)):
|
|
self.run_planning(variation)
|
|
|
|
def test_state_changes_during_sampling_cannot_publish(self):
|
|
with patch.object(apt, 'durable_once') as write:
|
|
with self.assertRaisesRegex(apt.Veto, 'PLANNING_STATE_CHANGED'):
|
|
self.run_planning('drift')
|
|
write.assert_not_called()
|
|
|
|
def test_shared_canonical_golden_bytes(self):
|
|
raw = (ROOT / 'tests/apt_transaction/fixtures/planning-canonical.json').read_bytes().rstrip(b'\n')
|
|
self.assertEqual(apt.canonical(json.loads(raw)), raw)
|
|
self.assertEqual(apt.digest(raw), 'f5c1f569110924eca83ad5d347882390b47e077fbef91c4eb86abb68621b92c4')
|
|
|
|
|
|
class NoChangeTests(TestCase):
|
|
def check_noop(self, recipe, version=None, status='install ok installed', locked=False, changed=False,
|
|
architecture='all', dirty=False, audit=b'', payload=None, expired=False):
|
|
obj = fixture_transaction(recipe)
|
|
desired = obj['packages'][0]['new_version']
|
|
baseline = {'rmm-mvp-test:' + architecture: {'version': version or desired, 'status': status}}
|
|
obj['baseline_sha256'] = apt.digest(apt.canonical(baseline))
|
|
obj['status_fingerprint'] = 'b' * 64
|
|
tx = apt.ResolvedAptTransaction.parse(obj)
|
|
ctx = context('apt-execute')
|
|
current = copy.deepcopy(baseline)
|
|
if changed:
|
|
current['rmm-mvp-test:all']['version'] = '9.0'
|
|
with patch.object(apt, 'installed_snapshot', return_value=current), \
|
|
patch.object(apt, 'status_fingerprint', return_value='b' * 64,
|
|
side_effect=apt.Veto('DPKG_PENDING_TRIGGERS') if dirty else None), \
|
|
patch.object(apt, 'observe_host_frontend_lock', return_value=locked), \
|
|
patch.object(apt, 'run_read', return_value=audit), \
|
|
patch.object(apt, 'sealed_read', return_value=payload if payload is not None else (desired + '\n').encode()), \
|
|
patch.object(apt.VerifiedHelperContext, 'check_deadline',
|
|
side_effect=apt.Veto('START_DEADLINE') if expired else None), \
|
|
patch.object(apt.subprocess, 'Popen') as spawn:
|
|
result = apt.verified_no_change(tx, baseline, ctx)
|
|
spawn.assert_not_called()
|
|
return result, tx, baseline
|
|
|
|
def test_install_and_update_already_desired_skip_only_old_version(self):
|
|
for recipe in apt.FIXTURE_RECIPES:
|
|
result, tx, baseline = self.check_noop(recipe)
|
|
self.assertFalse(result['changed'])
|
|
self.assertTrue(result['postcondition_already_met'])
|
|
self.assertFalse(result['transaction_executed'])
|
|
# Mutating preconditions still forbid a reinstall of that version.
|
|
with patch.object(apt, 'status_fingerprint', return_value='b' * 64), \
|
|
patch.object(apt, 'installed_snapshot', return_value=baseline):
|
|
with self.assertRaisesRegex(apt.Veto, 'PACKAGE_PRECONDITION'):
|
|
apt.check_preconditions(tx, baseline)
|
|
|
|
def test_missing_target_dirty_arch_or_newer_version_cannot_claim_no_change(self):
|
|
for version, status in (('1.0', 'install ok installed'), ('1.2', 'install ok installed'),
|
|
('1.1', 'deinstall ok config-files')):
|
|
result, _, _ = self.check_noop('rmm-apt-fixture-update-1.1', version, status)
|
|
self.assertIsNone(result)
|
|
for variation in ({'locked': True}, {'changed': True}):
|
|
with self.assertRaises(apt.Veto):
|
|
self.check_noop('rmm-apt-fixture-update-1.1', **variation)
|
|
result, _, _ = self.check_noop('rmm-apt-fixture-update-1.1', architecture='amd64')
|
|
self.assertIsNone(result)
|
|
|
|
def test_noop_dirty_state_audit_payload_and_expiry_are_not_success(self):
|
|
for variation in ({'dirty': True}, {'audit': b'pending package'}, {'payload': b'wrong\n'}, {'expired': True}):
|
|
with self.subTest(variation=variation), self.assertRaises(apt.Veto):
|
|
self.check_noop('rmm-apt-fixture-update-1.1', **variation)
|
|
|
|
def test_full_driver_no_launch_no_effect_markers_after_all_checks(self):
|
|
with tempfile.TemporaryDirectory(dir='/tmp/opencode') as temp:
|
|
base = Path(temp)
|
|
active = base / 'active'
|
|
active.mkdir()
|
|
for directory in ('empty', 'lists', 'cache'):
|
|
(active / directory).mkdir()
|
|
(active / 'apt.conf').write_bytes(apt.apt_config())
|
|
obj = fixture_transaction('rmm-apt-fixture-update-1.1')
|
|
baseline = {'rmm-mvp-test:all': {'version': '1.1', 'status': 'install ok installed'}}
|
|
obj['baseline_sha256'] = apt.digest(apt.canonical(baseline))
|
|
obj['status_fingerprint'] = 'b' * 64
|
|
tx = apt.ResolvedAptTransaction.parse(obj)
|
|
ctx = context('apt-execute')
|
|
def read(path, *args, **kwargs):
|
|
if path == Path(apt.HOOK):
|
|
return apt.hook_script()
|
|
if str(path) == '/usr/share/rmm-mvp-test/version':
|
|
return b'1.1\n'
|
|
return path.read_bytes()
|
|
with patch.object(apt, 'BASE', base), patch.object(apt, 'ACTIVE', active), \
|
|
patch.object(apt.os, 'geteuid', return_value=0), \
|
|
patch.object(apt, 'secure_path', side_effect=lambda p, **k: p), \
|
|
patch.object(apt, 'sealed_read', side_effect=read), \
|
|
patch.object(apt, 'runtime_identity', return_value={}), \
|
|
patch.object(apt, 'load_active', return_value=(tx, ctx, baseline)), \
|
|
patch.object(apt, 'load_signed_action', return_value=action_manifest(ctx, obj, {})) as signed, \
|
|
patch.object(apt, 'check_native_gate') as gate, patch.object(apt, 'verify_archive') as archive, \
|
|
patch.object(apt, 'installed_snapshot', return_value=baseline), \
|
|
patch.object(apt, 'status_fingerprint', return_value='b' * 64), \
|
|
patch.object(apt, 'observe_host_frontend_lock', return_value=False), \
|
|
patch.object(apt, 'run_read', return_value=b''), \
|
|
patch.object(apt.VerifiedHelperContext, 'check_deadline'), \
|
|
patch.object(apt.subprocess, 'Popen') as spawn:
|
|
request = {'transaction_sha256': ctx.transaction_sha256,
|
|
'effect_armed_ledger_id': ctx.effect_armed_ledger_id}
|
|
result = apt.execute(request)
|
|
self.assertEqual(result['effect_state'], 'verified_no_change')
|
|
self.assertEqual(result['code'], 'POSTCONDITION_ALREADY_MET')
|
|
signed.assert_called_once()
|
|
gate.assert_called_once()
|
|
archive.assert_called_once()
|
|
spawn.assert_not_called()
|
|
self.assertEqual({p.name for p in active.iterdir()}, {'empty', 'lists', 'cache', 'apt.conf'})
|