171 lines
10 KiB
Python
171 lines
10 KiB
Python
import hashlib
|
|
import io
|
|
import json
|
|
from pathlib import Path
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
from unittest.mock import patch
|
|
|
|
sys.path.insert(0, str(Path(__file__).parent))
|
|
import git_delivery as d
|
|
|
|
class DeliveryTest(unittest.TestCase):
|
|
def test_only_trusted_git_aliases_receive_credentials(self):
|
|
for host in d.ALLOWED_HOSTS:
|
|
self.assertEqual('An-J/Iomatex_OS', d.repo_name('https://' + host + '/An-J/Iomatex_OS.git'))
|
|
with patch.object(d.urllib.request, 'build_opener') as opener:
|
|
d.open_git('An-J/Iomatex_OS', 'branches/ci-cd', {'username': 'u', 'password': 'p', 'host': host})
|
|
request = opener.return_value.open.call_args.args[0]
|
|
self.assertEqual('https://' + host + '/api/v1/repos/An-J/Iomatex_OS/branches/ci-cd', request.full_url)
|
|
for host in ['evil.example', 'git.iomatex.com.evil', 'user@git.iomatex.com', 'git.iomatex.com:443']:
|
|
with self.assertRaises(ValueError):
|
|
d.open_git('An-J/Iomatex_OS', 'branches/ci-cd', {'username': 'u', 'password': 'p', 'host': host})
|
|
|
|
def test_package_download_uses_persisted_host(self):
|
|
data = b'package'
|
|
config = {'host': 'git.iomatex.com', 'repo': 'An-J/Iomatex_OS', 'commit': 'a'*40,
|
|
'objects': {'debian/a.deb': {'path': 'third_party/a.deb', 'sha256': hashlib.sha256(data).hexdigest()}}}
|
|
with tempfile.TemporaryDirectory() as folder, patch.object(d, 'open_git', return_value=io.BytesIO(data)) as request:
|
|
d.download_object(config, 'debian/a.deb', Path(folder)/'a.deb', {'username': 'u', 'password': 'p'})
|
|
self.assertEqual('git.iomatex.com', request.call_args.args[2]['host'])
|
|
|
|
def test_payloads_excluded_from_edge_snapshot(self):
|
|
for name in ['third_party/debian/bullseye-arm64/repo/a.deb', 'third_party/zigbee2mqtt/z.tar.gz', 'stage_itscreen/itscreen']:
|
|
self.assertTrue(d.is_payload(name))
|
|
for name in ['third_party/node/Packages', 'third_party/SHA256SUMS', 'local_installer.sh']:
|
|
self.assertFalse(d.is_payload(name))
|
|
|
|
def test_private_git_commit_url_escapes_literal_package_percent(self):
|
|
url=d.raw_endpoint('third_party/a_2%3a1.deb', 'a'*40)
|
|
self.assertIn('a_2%253a1.deb?ref=',url)
|
|
with self.assertRaises(ValueError): d.raw_endpoint('../secret','a'*40)
|
|
with self.assertRaises(ValueError): d.raw_endpoint('valid', 'ci-cd')
|
|
with self.assertRaises(ValueError): d.repo_name('https://git.it-screen.com.evil/repo/test')
|
|
|
|
def test_download_checks_hash_and_removes_failed_payload(self):
|
|
with tempfile.TemporaryDirectory() as folder:
|
|
target=Path(folder)/'package.deb'
|
|
data=b'package contents'
|
|
config={'repo':'An-J/Iomatex_OS','commit':'a'*40,'objects':{'debian/test.deb':{'path':'third_party/test.deb','sha256':hashlib.sha256(data).hexdigest(),'size':len(data)}}}
|
|
with patch.object(d,'open_git',return_value=io.BytesIO(data)):
|
|
d.download_object(config,'debian/test.deb',target,{})
|
|
self.assertEqual(target.read_bytes(),data)
|
|
with patch.object(d,'open_git',return_value=io.BytesIO(b'corrupt')):
|
|
with self.assertRaises(ValueError): d.download_object(config,'debian/test.deb',target,{})
|
|
self.assertFalse(target.exists())
|
|
|
|
def test_read_timeout_retries_only_failed_file_and_verifies_result(self):
|
|
class Stalled(io.BytesIO):
|
|
def read(self, *args):
|
|
raise d.socket.timeout('read timed out')
|
|
with tempfile.TemporaryDirectory() as folder:
|
|
root = Path(folder)
|
|
data = b'verified content'
|
|
entry = {'path': 'a.sh', 'mode': '100755', 'sha': d.blob_hash(data)}
|
|
with patch.object(d, 'open_git', side_effect=[Stalled(), io.BytesIO(data)]) as opened, patch.object(d.time, 'sleep'):
|
|
d.materialize_file('An-J/Iomatex_OS', 'a'*40, {}, entry, root/'absent', root)
|
|
self.assertEqual(opened.call_count, 2)
|
|
self.assertEqual((root/'a.sh').read_bytes(), data)
|
|
|
|
def test_snapshot_retries_do_not_redownload_successful_files(self):
|
|
calls = {'good': 0, 'flaky': 0}
|
|
def open_file(repo, endpoint, auth, timeout):
|
|
path = endpoint.split('/')[1].split('?')[0]
|
|
calls[path] += 1
|
|
if path == 'flaky' and calls[path] == 1:
|
|
raise d.socket.timeout('temporary')
|
|
return io.BytesIO(path.encode())
|
|
with tempfile.TemporaryDirectory() as folder:
|
|
root = Path(folder)
|
|
entries = [{'path': path, 'mode': '100644', 'sha': d.blob_hash(path.encode())} for path in calls]
|
|
with patch.object(d, 'open_git', side_effect=open_file), patch.object(d.time, 'sleep'):
|
|
d.download_snapshot(entries, lambda e: d.materialize_file('An-J/Iomatex_OS', 'a'*40, {}, e, root/'absent', root))
|
|
self.assertEqual(calls, {'good': 1, 'flaky': 2})
|
|
self.assertEqual((root/'good').read_bytes(), b'good')
|
|
self.assertEqual((root/'flaky').read_bytes(), b'flaky')
|
|
|
|
def test_retry_exhaustion_has_path_and_no_partial_file(self):
|
|
with tempfile.TemporaryDirectory() as folder:
|
|
root = Path(folder)
|
|
entry = {'path': 'a.sh', 'mode': '100644', 'sha': d.blob_hash(b'ok')}
|
|
with patch.object(d, 'open_git', side_effect=TimeoutError()) as opened, patch.object(d.time, 'sleep'):
|
|
with self.assertRaisesRegex(RuntimeError, '3 attempts: a.sh'):
|
|
d.materialize_file('An-J/Iomatex_OS', 'a'*40, {}, entry, root/'absent', root)
|
|
self.assertEqual(opened.call_count, 3)
|
|
self.assertFalse((root/'a.sh').exists())
|
|
|
|
def test_authentication_and_certificate_failures_are_not_retried(self):
|
|
errors = [d.urllib.error.HTTPError('https://example', 401, 'Unauthorized', {}, None),
|
|
d.urllib.error.URLError(d.ssl.SSLCertVerificationError('certificate'))]
|
|
for error in errors:
|
|
with self.subTest(error=type(error).__name__), patch.object(d, 'open_git', side_effect=error) as opened:
|
|
with self.assertRaises(type(error)):
|
|
d.snapshot_bytes('An-J/Iomatex_OS', 'a'*40, {}, 'a.sh')
|
|
self.assertEqual(opened.call_count, 1)
|
|
self.assertTrue(d.transient_download_error(d.urllib.error.HTTPError('https://example', 503, 'Busy', {}, None)))
|
|
|
|
def test_catalog_includes_node_and_vendor_plugin(self):
|
|
text, objects=d.catalog(Path(__file__).resolve().parents[1])
|
|
self.assertIn('Package: nodejs\n',text)
|
|
self.assertIn('Package: qt-video-oes-plugins\n',text)
|
|
root = Path(__file__).resolve().parents[1]
|
|
expected = {prefix + '/' + p.name
|
|
for prefix, folder in [('debian', 'third_party/debian/bullseye-arm64/repo'), ('node', 'third_party/node')]
|
|
for p in (root / folder).glob('*.deb')}
|
|
actual = {k for k in objects if k.endswith('.deb') and not k.startswith('third_party/')}
|
|
self.assertEqual(expected, actual)
|
|
for package in ['ffmpeg', 'libavcodec-dev', 'libavformat-dev', 'libavutil-dev',
|
|
'libswresample-dev', 'libswscale-dev']:
|
|
self.assertIn('Package: ' + package + '\n', text)
|
|
|
|
def test_snapshot_refuses_local_edits(self):
|
|
with tempfile.TemporaryDirectory() as folder:
|
|
root=Path(folder)
|
|
(root/'local_installer.sh').write_bytes(b'changed')
|
|
(root/'.iomatex-source.json').write_text(json.dumps({'files':[{'path':'local_installer.sh','sha':d.blob_hash(b'original')}]}))
|
|
with self.assertRaisesRegex(ValueError,'Local change'): d.check_existing(root)
|
|
|
|
def test_apt_epoch_filename_decoded_only_once(self):
|
|
key='debian/xserver-common_2%3a1.0+deb11_all.deb'
|
|
objects={key:{}}
|
|
for path in [key, 'debian/xserver-common_2%253a1.0%2bdeb11_all.deb']:
|
|
self.assertEqual(key,d.apt_key('iomatex://git.it-screen.com/'+path,objects))
|
|
|
|
def test_unchanged_snapshot_file_is_reused_without_network(self):
|
|
with tempfile.TemporaryDirectory() as folder:
|
|
existing=Path(folder)/'old'; staged=Path(folder)/'new'
|
|
existing.mkdir(); staged.mkdir()
|
|
(existing/'installer.sh').write_bytes(b'unchanged')
|
|
entry={'path':'installer.sh','mode':'100755','sha':d.blob_hash(b'unchanged')}
|
|
with patch.object(d,'open_git',side_effect=AssertionError('Unnecessary download')):
|
|
d.materialize_file('An-J/Iomatex_OS','a'*40,{},entry,existing,staged)
|
|
self.assertEqual(b'unchanged',(staged/'installer.sh').read_bytes())
|
|
|
|
def test_no_redirect_even_on_same_host(self):
|
|
with self.assertRaisesRegex(ValueError,'redirect refused'):
|
|
d.NoRedirect().redirect_request(None,None,302,'',{},'https://git.it-screen.com/other')
|
|
|
|
class RecoveryDeliveryTest(unittest.TestCase):
|
|
def test_gate_runs_before_any_access_to_existing_snapshot(self):
|
|
with tempfile.TemporaryDirectory() as folder, \
|
|
patch.object(d, 'platform_check'), patch.object(d, 'auth_from_env', return_value={}), \
|
|
patch.object(d, 'open_git', return_value=io.StringIO(json.dumps({'tree': []}))), \
|
|
patch.object(d, 'recovery_gate', side_effect=d.RecoveryPending('pending')) as gate, \
|
|
patch.object(d, 'check_existing') as old:
|
|
with self.assertRaises(d.RecoveryPending):
|
|
d.bootstrap('https://git.it-screen.com/An-J/Iomatex_OS.git', 'ci-cd', folder,
|
|
commit='a'*40, recovery_stages=['stage_ui'])
|
|
old.assert_not_called()
|
|
self.assertEqual(['stage_ui'], gate.call_args.args[5])
|
|
|
|
def test_corrupt_recovery_code_is_rejected_before_import(self):
|
|
entry = {'path': 'stage_env/userdata_recovery.py', 'sha': d.blob_hash(b'expected'), 'mode': '100644'}
|
|
with patch.object(d, 'open_git', return_value=io.BytesIO(b'corrupt')), \
|
|
patch.object(d.importlib.util, 'spec_from_file_location') as load:
|
|
with self.assertRaisesRegex(ValueError, 'checksum'):
|
|
d.recovery_gate('An-J/Iomatex_OS', 'ci-cd', 'a'*40, {}, [entry], ['stage_ui'])
|
|
load.assert_not_called()
|
|
|
|
if __name__=='__main__': unittest.main()
|