my-homelab-configs/tests/jeannie/test_network_sandbox_guests.py

56 lines
2.6 KiB
Python

"""Offline checks for sandbox guest image verification."""
import hashlib
import gzip
import importlib.util
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[2]
spec = importlib.util.spec_from_file_location('sandbox_guests', ROOT / 'scripts/network-sandbox-guests-host.py')
guests = importlib.util.module_from_spec(spec)
spec.loader.exec_module(guests)
class SandboxGuestTests(unittest.TestCase):
def test_openwrt_gzip_with_appended_metadata(self):
content = b'openwrt image data' * 1000
with tempfile.TemporaryDirectory() as directory:
archive = Path(directory) / 'image.gz'
output = Path(directory) / 'image'
archive.write_bytes(gzip.compress(content) + b'# appended metadata')
guests.extract_openwrt_image(archive, output)
self.assertEqual(output.read_bytes(), content)
def test_truncated_openwrt_gzip_is_rejected(self):
with tempfile.TemporaryDirectory() as directory:
archive = Path(directory) / 'image.gz'
archive.write_bytes(gzip.compress(b'content')[:-4])
with self.assertRaisesRegex(RuntimeError, 'truncated'):
guests.extract_openwrt_image(archive, Path(directory) / 'image')
def test_download_requires_matching_vendor_checksum(self):
content = b'example guest image'
digest = hashlib.sha256(content).hexdigest()
with tempfile.TemporaryDirectory() as directory:
def fetch(url, destination):
destination.write_bytes((digest + ' image.gz\n').encode() if url.endswith('checksum') else content)
with patch.object(guests, 'fetch', side_effect=fetch):
image = guests.verified_download('https://example.invalid/', 'image.gz',
'https://example.invalid/checksum', Path(directory))
self.assertEqual(image.read_bytes(), content)
def test_checksum_mismatch_is_rejected(self):
with tempfile.TemporaryDirectory() as directory:
def fetch(url, destination):
destination.write_bytes((('0' * 64) + ' image.gz\n').encode() if url.endswith('checksum') else b'image')
with patch.object(guests, 'fetch', side_effect=fetch):
with self.assertRaisesRegex(RuntimeError, 'Checksum mismatch'):
guests.verified_download('https://example.invalid/', 'image.gz',
'https://example.invalid/checksum', Path(directory))
if __name__ == '__main__':
unittest.main()