Files
rust-discovery/tests/apt_transaction/test_readiness_probe.py
2026-11-13 13:49:11 +01:00

192 lines
11 KiB
Python

"""Readiness isolation tests. No root setup/APT/host package effects are run."""
import json
import os
from pathlib import Path
import subprocess
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 prechecks, context
class ReadinessProbeTests(TestCase):
def test_controller_requires_actual_unit_caps_nnp_and_readonly_system(self):
mask = sum(1 << bit for bit in (0, 1, 3, 4, 6, 7, 8, 31, 21, 27))
for fault in ('none', 'boot-cap', 'nnp', 'filter', 'unit', 'writable', 'readonly-target', 'extra-write'):
current_mask = mask | (1 << 22) if fault == 'boot-cap' else mask
status = ('NoNewPrivs: ' + ('0' if fault == 'nnp' else '1') + '\n' +
'Seccomp: ' + ('0' if fault == 'filter' else '2') + '\n' +
''.join(key + ': ' + format(current_mask, 'x') + '\n' for key in ('CapEff', 'CapPrm', 'CapBnd')) +
'CapInh: 0\nCapAmb: 0\n')
cgroup = '0::/system.slice/' + ('other.service' if fault == 'unit' else 'rmm-apt-helper.service')
mounts = '1 0 0:1 / /usr ro - ext4 root ro\n'
if fault == 'extra-write':
mounts += '2 1 0:1 /usr/share /usr/share rw - ext4 root rw\n'
def text(path, *args, **kwargs):
return {'/proc/self/status': status, '/proc/self/cgroup': cgroup,
'/proc/self/mountinfo': mounts}[str(path)]
def flags(path):
ro = path in ('/usr', '/etc', '/var')
if fault == 'writable':
ro = False
if fault == 'readonly-target':
ro = True
return SimpleNamespace(f_flag=os.ST_RDONLY if ro else 0)
with self.subTest(fault=fault), patch.object(apt.os, 'geteuid', return_value=0), \
patch.object(Path, 'read_text', text), patch.object(apt.os, 'statvfs', side_effect=flags):
if fault == 'none':
apt.verify_controller_profile()
else:
with self.assertRaises(apt.Veto):
apt.verify_controller_profile()
def test_host_lock_observation_uses_only_readonly_getlk(self):
calls = []
def query(fd, operation, data):
calls.append(operation)
return data # same F_WRLCK query denotes a foreign owner; no acquisition
with patch.object(apt, 'secure_path', return_value=Path('/var/lib/dpkg/lock-frontend')), \
patch.object(apt.os, 'open', return_value=123) as opened, \
patch.object(apt.os, 'close'), patch.object(apt.fcntl, 'fcntl', side_effect=query), \
patch.object(apt.fcntl, 'lockf') as lockf, patch.object(apt.fcntl, 'flock') as flock:
self.assertTrue(apt.observe_host_frontend_lock())
self.assertEqual(calls, [apt.fcntl.F_GETLK])
flags = opened.call_args.args[1]
self.assertEqual(flags & os.O_ACCMODE, os.O_RDONLY)
lockf.assert_not_called()
flock.assert_not_called()
def test_probe_config_has_no_hooks_sources_or_install_command(self):
workspace = Path('/var/lib/rmm-apt-transaction/probes/00000000-0000-4000-8000-000000000001')
config = apt.probe_config(workspace)
self.assertNotIn(b'DPkg::Pre-Install-Pkgs', config)
self.assertNotIn(b'DPkg::Tools::Options', config)
self.assertIn(b'Dir::Etc::sourcelist "/dev/null"', config)
self.assertIn(str(workspace / 'log').encode(), config)
def test_probe_publishes_only_readiness_with_mocked_native_child(self):
self.probe_scenario('success')
def test_failed_or_partial_native_probe_never_publishes_readiness(self):
for scenario in ('child-failed', 'partial', 'syscalls', 'same-namespace'):
with self.subTest(scenario=scenario):
self.probe_scenario(scenario)
def probe_scenario(self, scenario):
with tempfile.TemporaryDirectory(dir='/tmp/opencode') as temp:
base = Path(temp)
(base / 'probes').mkdir(mode=0o700)
host_status = b'Package: read-only-host-baseline\n'
original_open = os.open
def no_host_writes(path, flags, *args, **kwargs):
if flags & (os.O_WRONLY | os.O_RDWR | os.O_CREAT | os.O_TRUNC):
self.assertTrue(str(path).startswith(str(base) + '/'), str(path))
return original_open(path, flags, *args, **kwargs)
def sealed(path, *args):
if path == Path('/var/lib/dpkg/status'):
return host_status
return path.read_bytes()
def native(argv, **kwargs):
self.assertEqual(argv[-1], 'probe-worker')
self.assertNotIn('install', argv)
request = json.loads(kwargs['input'])
workspace = base / 'probes' / request['probe_id']
self.assertEqual((workspace / 'dpkg/status').read_bytes(), host_status)
self.assertFalse((workspace / 'context.json').exists())
if scenario != 'child-failed':
result = {'probe_id': request['probe_id'], 'checks': prechecks(context())['checks'],
'isolated_dpkg_check': True,
'namespaces': {name: name + ':[999999999]' for name in ('pid', 'mnt', 'net')}}
if scenario == 'partial':
result.pop('checks')
elif scenario == 'syscalls':
result['checks']['control_syscalls']['invalid_reboot_magic'] = 'EINVAL'
elif scenario == 'same-namespace':
result['namespaces'] = json.loads((workspace / 'host-namespaces.json').read_bytes())
(workspace / 'probe-result.json').write_bytes(apt.canonical(result))
return SimpleNamespace(returncode=100 if scenario == 'child-failed' else 0)
with patch.object(apt, 'BASE', base), patch.object(apt.os, 'geteuid', return_value=0), \
patch.object(apt, 'secure_path'), patch.object(apt, 'runtime_identity', return_value={}), \
patch.object(apt, 'sealed_read', side_effect=sealed), \
patch.object(apt, 'observe_host_frontend_lock', return_value=False), \
patch.object(apt, 'verify_controller_profile'), \
patch.object(apt.os, 'open', side_effect=no_host_writes), \
patch.object(apt.subprocess, 'run', side_effect=native):
if scenario == 'success':
outcome = apt.probe_native()
self.assertTrue(outcome['readiness_only'])
self.assertFalse(outcome['native_acceptance'])
status = apt.readiness_status()
self.assertTrue(status['fixture_acceptance_ready'])
self.assertEqual(status['accepted_recipes'], [])
# A valid readiness report cannot promote a partial fixture
# acceptance file into an accepted package capability.
partial = base / ('acceptance-' + next(iter(apt.FIXTURE_RECIPES)) + '.json')
partial.write_bytes(b'{"schema_version":2,"test_acceptance":true}')
with self.assertRaises(apt.Veto):
apt.readiness_status()
partial.unlink() # only this artificially injected temp test file
else:
with self.assertRaises(apt.Veto):
apt.probe_native()
self.assertFalse((base / 'native-readiness.json').exists())
for pattern in ('**/hook-armed.json', '**/launch.json', '**/context.json',
'**/prefetch-*.json', '**/acceptance-*.json', '**/bootstrap-attempt-*.json'):
self.assertEqual(list(base.glob(pattern)), [])
def test_clone_namespace_flags_and_clone3_closed_but_fork_exec_works(self):
code = '''import ctypes,importlib.util,sys,subprocess,errno
sys.dont_write_bytecode=True
s=importlib.util.spec_from_file_location('apt_transaction',sys.argv[1])
m=importlib.util.module_from_spec(s);sys.modules[s.name]=m;s.loader.exec_module(m)
m.seccomp_filter()
lib=ctypes.CDLL('libseccomp.so.2');lib.seccomp_syscall_resolve_name.argtypes=[ctypes.c_char_p]
c=ctypes.CDLL(None,use_errno=True);c.syscall.restype=ctypes.c_long
clone=lib.seccomp_syscall_resolve_name(b'clone');clone3=lib.seccomp_syscall_resolve_name(b'clone3')
for bit in (0x80,0x20000,0x2000000,0x4000000,0x8000000,0x10000000,0x20000000,0x40000000):
ctypes.set_errno(0)
# Invalid exit signal ensures no child can be created even without a filter.
assert c.syscall(clone,ctypes.c_ulong(bit|255),0,0,0,0)==-1
assert ctypes.get_errno()==errno.EPERM
ctypes.set_errno(0);assert c.syscall(clone3,0,0)==-1 and ctypes.get_errno()==errno.ENOSYS
assert subprocess.check_output(['/usr/bin/python3','-I','-c','print("fork-ok")'])==b'fork-ok\\n'
print('CLONE_GAPS_CLOSED')
'''
result = subprocess.check_output(['/usr/bin/python3', '-I', '-c', code,
str(ROOT / 'tools/apt-transaction/apt_transaction.py')])
self.assertEqual(result, b'CLONE_GAPS_CLOSED\n')
def test_dedicated_unit_has_narrow_profile_without_weakening_general_unit(self):
unit = (ROOT / 'deploy/linux/rmm-apt-helper.service').read_text()
# Explicit User=root triggers systemd 255's seccomp/setuid path:
# CAP_SETUID disappears from E/P and setup capabilities leak into I.
# Default root preserves the exact controller profile, not extra caps.
self.assertFalse(any(line.startswith('User=') for line in unit.splitlines()))
self.assertIn('Group=rmm-agent', unit)
self.assertIn('SystemCallFilter=adjtimex clock_adjtime', unit)
self.assertNotIn('CAP_SYS_TIME', next(line for line in unit.splitlines() if line.startswith('CapabilityBoundingSet=')))
for required in ('NoNewPrivileges=true', 'PrivateNetwork=true', 'ProtectSystem=strict',
'RestrictNamespaces=mnt pid net', 'DevicePolicy=strict', 'PrivateDevices=no',
'AmbientCapabilities=', 'SystemCallArchitectures=native'):
self.assertIn(required, unit)
bounding = next(line for line in unit.splitlines() if line.startswith('CapabilityBoundingSet='))
self.assertIn('CAP_SYS_ADMIN', bounding)
self.assertIn('CAP_MKNOD', bounding)
self.assertNotIn('CAP_SYS_BOOT', bounding)
self.assertNotIn('CAP_SYS_CHROOT', bounding)
writable = next(line for line in unit.splitlines() if line.startswith('ReadWritePaths='))
self.assertEqual(writable.split('=', 1)[1].split(), ['/var/lib/dpkg', '/var/lib/rmm-helper',
'/var/lib/rmm-apt-transaction', '/usr/share/rmm-mvp-test'])