infrastructure/tests/snapshot.py
2026-11-04 21:39:11 +00:00

68 lines
2.6 KiB
Python

"""Negative transport-capture checks without touching ZFS or the real mirror."""
import hashlib
import importlib.util
import io
import json
from pathlib import Path
import tarfile
import tempfile
from unittest.mock import patch
spec = importlib.util.spec_from_file_location('capture', Path(__file__).parents[1] / 'deploy/capture-mirror.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
policy = json.loads((Path(__file__).parents[1] / 'deploy/snapshot-policy.json').read_text())
def reject(call):
try:
call()
except (ValueError, FileNotFoundError):
return
raise AssertionError('Invalid capture accepted')
with tempfile.TemporaryDirectory() as directory:
with patch.object(module, 'run') as run:
reject(lambda: module.capture(policy, '2026-11'))
run.assert_not_called()
policy['capture_enabled'] = True
root = Path(directory)
source = root / 'mirror'
package_dir = source / 'core/os/x86_64'
package_dir.mkdir(parents=True)
payload = b'fixture package bytes'
filename = 'fixture-1-1-x86_64.pkg.tar.zst'
package = package_dir / filename
package.write_bytes(payload)
database = root / 'core.db'
def db(name=filename, size=len(payload), signature='fixture-untrusted-signature'):
record = {'FILENAME': name, 'CSIZE': str(size), 'SHA256SUM': hashlib.sha256(payload).hexdigest(),
'PGPSIG': signature, 'NAME': 'fixture', 'VERSION': '1-1'}
text = ''.join(f'%{k}%\n{v}\n\n' for k, v in record.items()).encode()
with tarfile.open(database, 'w:gz') as archive:
info = tarfile.TarInfo('fixture-1-1/desc')
info.size = len(text)
archive.addfile(info, io.BytesIO(text))
db()
assert len(module.inventory(database, 'core', source)) == 1
db(name='../outside.pkg.tar.zst')
reject(lambda: module.inventory(database, 'core', source))
db(size=len(payload) + 1)
reject(lambda: module.inventory(database, 'core', source))
db()
package.unlink()
outside = root / filename
outside.write_bytes(payload)
package.symlink_to(outside)
reject(lambda: module.inventory(database, 'core', source))
target = root / 'capture'
target.mkdir()
snapshots = '\n'.join(policy['capture_dataset'] + '@monthly-2026-' + month for month in ('08', '09', '10'))
with patch.object(module, 'run', side_effect=[str(target), snapshots]) as run:
reject(lambda: module.capture(policy, '2026-11'))
assert run.call_count == 2
assert not (target / 'capture-2026-11').exists()
print('PASS: database inventory, traversal, size, symlink escape, three-snapshot cap')