134 lines
6.4 KiB
Python
134 lines
6.4 KiB
Python
"""Real local APT argument regression; dpkg effects are independently replaced.
|
|
|
|
Opt in only inside the documented offline, read-only, unprivileged container:
|
|
RMM_APT_ARGUMENT_REGRESSION=1 python3 -m unittest discover ...
|
|
This is neither a native Cloud-VM test nor a package installation proof.
|
|
"""
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import tempfile
|
|
import unittest
|
|
|
|
from test_guard import apt
|
|
|
|
|
|
def digest(path):
|
|
return hashlib.sha256(path.read_bytes()).hexdigest()
|
|
|
|
|
|
def guarded_dpkg(path, calls):
|
|
# No arbitrary argv is ever delegated to real dpkg. Read-only, one-argument
|
|
# architecture/version/feature queries are the entire delegation allowlist.
|
|
path.write_text('''#!/usr/bin/python3 -I
|
|
import json, os, re, sys
|
|
from pathlib import Path
|
|
args = sys.argv[1:]
|
|
query = [arg for arg in args if not arg.startswith('--log=')]
|
|
if len(query) == 1 and (query[0] in (
|
|
'--version', '--print-architecture', '--print-foreign-architectures')
|
|
or re.fullmatch(r'--assert-[a-z0-9-]+', query[0])):
|
|
os.execve('/usr/bin/dpkg', ['/usr/bin/dpkg', query[0]], dict(os.environ))
|
|
data = sys.stdin.buffer.read() if '--set-selections' in args else b''
|
|
with Path(''' + repr(str(calls)) + ''').open('a', encoding='utf-8') as out:
|
|
out.write(json.dumps({'argv': args, 'stdin': data.decode('ascii')}) + '\\n')
|
|
# Effect calls are recorded and simulated; real dpkg is NEVER invoked here.
|
|
if any(op in args for op in ('--unpack', '--configure', '--set-selections')):
|
|
sys.exit(0)
|
|
sys.exit(91)
|
|
''', encoding='utf-8')
|
|
path.chmod(0o700)
|
|
|
|
|
|
def run_case(work, fixed):
|
|
for name in ('empty', 'lists', 'cache', 'log', 'state', 'dpkg'):
|
|
(work / name).mkdir(mode=0o700)
|
|
status = work / 'dpkg/status'
|
|
status.write_bytes(Path('/var/lib/dpkg/status').read_bytes())
|
|
fixture = work / 'rmm-mvp-test_1.0_all.deb'
|
|
fixture.write_bytes(apt.fixture_archive('1.0'))
|
|
calls = work / 'dpkg-calls.jsonl'
|
|
guard = work / 'dpkg-guard'
|
|
guarded_dpkg(guard, calls)
|
|
config = apt.apt_config().decode('ascii')
|
|
# This test reaches actual dpkg command generation. The production hook is
|
|
# removed only in this copied-state harness, whose dpkg cannot have effects.
|
|
config = '\n'.join(line for line in config.splitlines()
|
|
if not line.startswith(('DPkg::Pre-Install-Pkgs',
|
|
'DPkg::Tools::Options'))) + '\n'
|
|
if not fixed:
|
|
config = config.replace('dpkg::selection::remove::approved "false";\n', '')
|
|
config = config.replace(str(apt.ACTIVE), str(work))
|
|
config = config.replace(str(apt.BASE / 'log'), str(work / 'log'))
|
|
config = config.replace(str(apt.BASE / 'state'), str(work / 'state'))
|
|
config = config.replace('/var/lib/dpkg/status', str(status))
|
|
config = config.replace('Dir::Bin::dpkg "/usr/bin/dpkg";',
|
|
'Dir::Bin::dpkg "' + str(guard) + '";')
|
|
config += 'Dir::State "' + str(work / 'state') + '";\n'
|
|
config += 'Dir::Cache "' + str(work / 'cache') + '";\n'
|
|
config_path = work / 'apt.conf'
|
|
config_path.write_text(config, encoding='ascii')
|
|
before = digest(status)
|
|
result = subprocess.run(
|
|
['/usr/bin/apt-get', '--yes', '--no-remove', '--no-install-recommends',
|
|
'install', '--', str(fixture)],
|
|
env={'PATH': '/usr/sbin:/usr/bin:/sbin:/bin', 'LC_ALL': 'C',
|
|
'DEBIAN_FRONTEND': 'noninteractive', 'HOME': str(work),
|
|
'APT_CONFIG': str(config_path)},
|
|
stdin=subprocess.DEVNULL, capture_output=True, timeout=25,
|
|
)
|
|
records = [json.loads(line) for line in calls.read_text().splitlines()] if calls.exists() else []
|
|
return {'exit_code': result.returncode, 'calls': records,
|
|
'status_unchanged': digest(status) == before,
|
|
'fixture': str(fixture), 'stderr': result.stderr.decode('ascii', errors='replace')}
|
|
|
|
|
|
@unittest.skipUnless(os.environ.get('RMM_APT_ARGUMENT_REGRESSION') == '1',
|
|
'explicit offline read-only container regression only')
|
|
class RealAptConfigureArguments(unittest.TestCase):
|
|
def test_exact_fixture_configure_survives_without_any_pending_command(self):
|
|
self.assertNotEqual(os.geteuid(), 0, 'must run unprivileged')
|
|
host_status = Path('/var/lib/dpkg/status')
|
|
original = digest(host_status)
|
|
summaries = {}
|
|
with tempfile.TemporaryDirectory(prefix='rmm-apt-arguments-') as temp:
|
|
for fixed in (False, True):
|
|
name = 'fixed' if fixed else 'original'
|
|
work = Path(temp) / name
|
|
work.mkdir(mode=0o700)
|
|
result = run_case(work, fixed)
|
|
self.assertEqual(result['exit_code'], 0, result['stderr'])
|
|
self.assertTrue(result['status_unchanged'])
|
|
effects = []
|
|
for call in result['calls']:
|
|
args = call['argv']
|
|
self.assertNotIn('--pending', args)
|
|
self.assertNotIn('--triggers-only', args)
|
|
self.assertNotIn('--remove', args)
|
|
self.assertNotIn('--purge', args)
|
|
if '--unpack' in args:
|
|
self.assertEqual(args[args.index('--unpack') + 1:],
|
|
['--auto-deconfigure', result['fixture']])
|
|
effects.append('unpack:exact-fixture-archive')
|
|
elif '--configure' in args:
|
|
self.assertEqual(args[args.index('--configure') + 1:],
|
|
['rmm-mvp-test:all'])
|
|
effects.append('configure:rmm-mvp-test:all')
|
|
else:
|
|
self.assertIn('--set-selections', args)
|
|
for line in call['stdin'].splitlines():
|
|
self.assertEqual(line.split()[0].split(':')[0], 'rmm-mvp-test')
|
|
self.assertEqual(effects, ['unpack:exact-fixture-archive'] +
|
|
(['configure:rmm-mvp-test:all'] if fixed else []))
|
|
summaries[name] = effects
|
|
self.assertEqual(digest(host_status), original)
|
|
version = subprocess.check_output(['/usr/bin/apt-get', '--version']).decode().splitlines()[0]
|
|
print(json.dumps({'apt_version': version, 'dpkg_effects_simulated': True,
|
|
'host_and_copied_status_unchanged': True, 'cases': summaries}))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|