270 lines
12 KiB
Python
270 lines
12 KiB
Python
#!/usr/bin/env python3
|
|
"""Run unchanged native lifecycle gates with a disposable real systemd manager.
|
|
|
|
CPU-only offline fixture. Setup alone gets mount/UID capabilities; journald,
|
|
D-Bus, manager, Rust CLI and synthetic workers have empty capability sets.
|
|
The private writable cgroup mount enables real manager process tracking.
|
|
Setup uses fixture-only apparmor=unconfined for the private cgroup mount;
|
|
default seccomp stays enabled. No host paths/devices/namespaces are shared.
|
|
Existing tests exercise stop/rollback; this is not a separate forced-descendant
|
|
KillMode test, installed-driver inference, or model quality evidence.
|
|
"""
|
|
import argparse
|
|
import glob
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import shutil
|
|
import signal
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
import uuid
|
|
|
|
UID = 10001
|
|
CAPS = ('SYS_ADMIN', 'CHOWN', 'SETUID', 'SETGID', 'SETPCAP')
|
|
FILES = ('smoke-service-unit.py', 'smoke-native-switch.py', 'smoke-worker-cancel.py')
|
|
|
|
|
|
def run(*args, **kwargs):
|
|
return subprocess.run(args, check=True, **kwargs)
|
|
|
|
|
|
def no_gpu():
|
|
assert not glob.glob('/dev/nvidia*'), 'raw NVIDIA devices are forbidden'
|
|
assert os.environ.get('NVIDIA_VISIBLE_DEVICES') == 'void'
|
|
assert os.environ.get('CUDA_VISIBLE_DEVICES') == ''
|
|
|
|
|
|
def zero_caps(pid='self'):
|
|
status = Path(f'/proc/{pid}/status').read_text()
|
|
found = [line.split(':', 1)[1].strip() for line in status.splitlines()
|
|
if line.startswith(('CapInh:', 'CapPrm:', 'CapEff:', 'CapBnd:', 'CapAmb:'))]
|
|
assert found == ['0000000000000000'] * 5, (pid, found)
|
|
assert any(line.startswith('NoNewPrivs:') and line.split(':', 1)[1].strip() == '1'
|
|
for line in status.splitlines()), (pid, 'NoNewPrivs missing')
|
|
|
|
|
|
def drop_command(*args):
|
|
return ['setpriv', f'--reuid={UID}', f'--regid={UID}', '--clear-groups',
|
|
'--bounding-set=-all', '--inh-caps=-all', '--ambient-caps=-all', *args]
|
|
|
|
|
|
def root_setup():
|
|
# Direct host invocation must fail before any mount, chown, or unit operation.
|
|
assert Path('/.dockerenv').is_file() and os.getpid() == 1 and os.getuid() == 0
|
|
nonce = os.environ['LELEKA_MANAGER_FIXTURE_NONCE']
|
|
assert len(nonce) == 32 and all(c in '0123456789abcdef' for c in nonce)
|
|
no_gpu()
|
|
run('dpkg-query', '-W', 'systemd', 'dbus', 'dbus-user-session', 'python3', 'util-linux',
|
|
'ca-certificates')
|
|
assert Path('/proc/self/cgroup').read_text().strip() == '0::/'
|
|
target = Path('/sys/fs/cgroup')
|
|
assert target.is_dir() and not target.is_symlink()
|
|
mounts = Path('/proc/self/mountinfo').read_text().splitlines()
|
|
assert any(line.split()[4] == str(target) and ' - cgroup2 ' in line for line in mounts)
|
|
owned = Path('/run') / ('leleka-cgroup-' + nonce)
|
|
assert not owned.exists()
|
|
owned.mkdir(mode=0o700)
|
|
run('mount', '-t', 'cgroup2', 'none', str(owned))
|
|
run('mount', '--move', str(owned), str(target))
|
|
assert set(Path('/sys/fs/cgroup/cgroup.procs').read_text().split()) <= {str(os.getpid())}
|
|
for path in (target, target/'cgroup.procs', target/'cgroup.subtree_control'):
|
|
os.chown(path, UID, UID)
|
|
# Only known staged regular files are normalized. The CLI remains root-owned.
|
|
for name in (*FILES, 'smoke-systemd-manager.py', 'strata-next'):
|
|
path = Path('/work') / name
|
|
assert path.is_file() and not path.is_symlink()
|
|
os.chown(path, 0, 0)
|
|
path.chmod(0o755 if name == 'strata-next' else 0o644)
|
|
for path in (Path('/run/systemd/journal'), Path('/run/log/journal')):
|
|
path.mkdir(parents=True, exist_ok=True)
|
|
os.chown(path, UID, UID)
|
|
config = Path('/etc/systemd/journald.conf.d')
|
|
config.mkdir(exist_ok=True)
|
|
(config/'fixture.conf').write_text('[Journal]\nStorage=volatile\nReadKMsg=no\n'
|
|
'ForwardToKMsg=no\nForwardToConsole=no\nForwardToWall=no\n')
|
|
journal = subprocess.Popen(drop_command('/usr/lib/systemd/systemd-journald'))
|
|
env = dict(os.environ, HOME='/home/fixture', USER='fixture', LOGNAME='fixture',
|
|
XDG_CONFIG_HOME='/home/fixture/.config',
|
|
DBUS_SESSION_BUS_ADDRESS='unix:path=/run/user/10001/fixture-bus',
|
|
PYTHONDONTWRITEBYTECODE='1', LELEKA_JOURNAL_PID=str(journal.pid))
|
|
# exec retains journald's parent for bounded waitpid/reaping by the test user.
|
|
os.execvpe('setpriv', drop_command('python3', '/work/smoke-systemd-manager.py',
|
|
'--inside-user'), env)
|
|
|
|
|
|
def finish_process(process):
|
|
if process is None:
|
|
return
|
|
if process.poll() is None:
|
|
process.terminate()
|
|
try:
|
|
process.wait(timeout=5)
|
|
except subprocess.TimeoutExpired:
|
|
process.kill()
|
|
process.wait(timeout=5)
|
|
|
|
|
|
def finish_journal(pid):
|
|
try:
|
|
os.kill(pid, signal.SIGTERM)
|
|
except ProcessLookupError:
|
|
pass
|
|
deadline = time.monotonic() + 5
|
|
while time.monotonic() < deadline:
|
|
if os.waitpid(pid, os.WNOHANG)[0]:
|
|
return
|
|
time.sleep(.05)
|
|
os.kill(pid, signal.SIGKILL)
|
|
deadline = time.monotonic() + 5
|
|
while time.monotonic() < deadline:
|
|
if os.waitpid(pid, os.WNOHANG)[0]:
|
|
return
|
|
time.sleep(.05)
|
|
raise TimeoutError('journald did not reap after SIGKILL; outer container removal required')
|
|
|
|
|
|
def user_tests():
|
|
assert Path('/.dockerenv').is_file() and os.getpid() == 1
|
|
no_gpu()
|
|
assert os.getuid() == UID
|
|
zero_caps()
|
|
journal_pid = int(os.environ['LELEKA_JOURNAL_PID'])
|
|
bus = manager = None
|
|
failed = False
|
|
cleanup_errors = []
|
|
try:
|
|
bus = subprocess.Popen(['dbus-daemon', '--session', '--nofork',
|
|
'--address=' + os.environ['DBUS_SESSION_BUS_ADDRESS']])
|
|
manager = subprocess.Popen(['/usr/lib/systemd/systemd', '--user', '--unit=basic.target',
|
|
'--log-target=console', '--log-level=warning'])
|
|
deadline = time.monotonic() + 25
|
|
while True:
|
|
assert manager.poll() is None and bus.poll() is None, 'manager or bus exited'
|
|
result = subprocess.run(['systemctl', '--user', 'show', '--property=Version'],
|
|
text=True, capture_output=True, timeout=3)
|
|
if result.returncode == 0 and Path('/run/systemd/journal/stdout').exists():
|
|
break
|
|
assert time.monotonic() < deadline, result.stderr
|
|
time.sleep(.2)
|
|
zero_caps(manager.pid)
|
|
zero_caps(bus.pid)
|
|
zero_caps(journal_pid)
|
|
assert str(manager.pid) in Path('/sys/fs/cgroup/init.scope/cgroup.procs').read_text().split()
|
|
print(result.stdout.strip(), flush=True)
|
|
print('Private real manager, bus, journal and cgroup ready; all capabilities zero', flush=True)
|
|
run('python3', '/work/smoke-service-unit.py', '/work/strata-next', '--lifecycle', timeout=600)
|
|
run('python3', '/work/smoke-native-switch.py', '/work/strata-next', timeout=300)
|
|
except BaseException:
|
|
failed = True
|
|
raise
|
|
finally:
|
|
# Every owned process is cleaned even if another cleanup step fails.
|
|
for cleanup in (
|
|
lambda: subprocess.run(['systemctl', '--user', 'exit'], check=False, timeout=5),
|
|
lambda: finish_process(manager), lambda: finish_process(bus),
|
|
lambda: finish_journal(journal_pid),
|
|
):
|
|
try:
|
|
cleanup()
|
|
except Exception as error:
|
|
cleanup_errors.append(str(error))
|
|
if cleanup_errors:
|
|
print('Fixture cleanup errors: ' + '; '.join(cleanup_errors), file=sys.stderr)
|
|
if not failed:
|
|
raise RuntimeError('owned manager fixture cleanup failed')
|
|
|
|
|
|
def host(binary):
|
|
assert not glob.glob('/dev/nvidia*'), 'manager fixture is restricted to a CPU host'
|
|
root = Path(__file__).resolve().parents[1]
|
|
binary = binary.resolve(strict=True)
|
|
nonce = uuid.uuid4().hex
|
|
name = 'leleka-systemd-smoke-' + nonce
|
|
image = name + ':fixture'
|
|
with tempfile.TemporaryDirectory(prefix=name + '-') as directory:
|
|
stage = Path(directory)
|
|
dockerfile = root/'deploy/Dockerfile.systemd-smoke'
|
|
context = stage/'image-context'
|
|
context.mkdir()
|
|
shutil.copy2(dockerfile, context/'Dockerfile')
|
|
for filename in (*FILES, 'smoke-systemd-manager.py'):
|
|
shutil.copy2(root/'scripts'/filename, stage/filename)
|
|
shutil.copy2(binary, stage/'strata-next')
|
|
def digest(path):
|
|
checksum = hashlib.sha256()
|
|
with path.open('rb') as source:
|
|
for block in iter(lambda: source.read(1024 * 1024), b''):
|
|
checksum.update(block)
|
|
return checksum.hexdigest()
|
|
hashes = {path.name: digest(path) for path in stage.iterdir() if path.is_file()}
|
|
hashes['Dockerfile.systemd-smoke'] = digest(dockerfile)
|
|
print(json.dumps({'fixture_sha256': hashes}, sort_keys=True), flush=True)
|
|
try:
|
|
run('docker', 'build', '--platform', 'linux/amd64', '-t', image, str(context), timeout=600)
|
|
run('docker', 'create', '--name', name, '--platform', 'linux/amd64', '--tty',
|
|
'--network', 'none', '--cgroupns', 'private', '--user', '0', '--cap-drop', 'ALL',
|
|
*(arg for cap in CAPS for arg in ('--cap-add', cap)),
|
|
'--security-opt', 'no-new-privileges',
|
|
'--security-opt', 'apparmor=unconfined',
|
|
'-e', 'NVIDIA_VISIBLE_DEVICES=void', '-e', 'CUDA_VISIBLE_DEVICES=',
|
|
'-e', 'LELEKA_MANAGER_FIXTURE_NONCE=' + nonce,
|
|
image, 'python3', '/work/smoke-systemd-manager.py', '--inside-root', timeout=30)
|
|
info = json.loads(subprocess.check_output(['docker', 'inspect', name], text=True))[0]
|
|
config = info['HostConfig']
|
|
assert config['CgroupnsMode'] == 'private' and config['NetworkMode'] == 'none'
|
|
assert not config['Privileged'] and config['PidMode'] == ''
|
|
assert not config['Binds'] and not info['Mounts'] and not config['Devices']
|
|
assert not config['DeviceRequests'] and config['IpcMode'] == 'private'
|
|
assert config['CapDrop'] == ['ALL']
|
|
assert {cap.removeprefix('CAP_') for cap in config['CapAdd']} == set(CAPS)
|
|
assert set(config['SecurityOpt']) == {'no-new-privileges', 'apparmor=unconfined'}
|
|
print(json.dumps({'image_id': info['Image'], 'source': 'isolated CPU fixture',
|
|
'setup_security_options': config['SecurityOpt'],
|
|
'setup_capabilities': config['CapAdd'],
|
|
'user_capabilities': 'zero', 'seccomp': 'Docker default'}), flush=True)
|
|
# docker cp works with a remote daemon; runner paths are not bind-mounted.
|
|
for filename in (*FILES, 'smoke-systemd-manager.py', 'strata-next'):
|
|
run('docker', 'cp', str(stage/filename), name + ':/work/' + filename, timeout=60)
|
|
run('docker', 'start', '--attach', name, timeout=1000)
|
|
state = json.loads(subprocess.check_output(['docker', 'inspect', name], text=True))[0]['State']
|
|
assert state['ExitCode'] == 0, state
|
|
finally:
|
|
# Container removal is the final namespace-wide cleanup safety net.
|
|
original_failure = sys.exc_info()[0] is not None
|
|
errors = []
|
|
for kind, command in (('container', ['docker', 'rm', '--force', name]),
|
|
('image', ['docker', 'image', 'rm', image])):
|
|
try:
|
|
result = subprocess.run(command, text=True, capture_output=True, timeout=30)
|
|
if result.returncode and 'No such ' not in result.stderr:
|
|
errors.append(kind + ': ' + result.stderr)
|
|
except Exception as error:
|
|
errors.append(kind + ': ' + str(error))
|
|
if errors:
|
|
print('Outer fixture cleanup errors: ' + '; '.join(errors), file=sys.stderr)
|
|
if not original_failure:
|
|
raise RuntimeError('outer fixture cleanup failed')
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('binary', nargs='?', type=Path)
|
|
parser.add_argument('--inside-root', action='store_true')
|
|
parser.add_argument('--inside-user', action='store_true')
|
|
args = parser.parse_args()
|
|
if args.inside_root:
|
|
root_setup()
|
|
elif args.inside_user:
|
|
user_tests()
|
|
else:
|
|
assert args.binary is not None
|
|
host(args.binary)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|