349 lines
15 KiB
Python
349 lines
15 KiB
Python
"""Publication/closeout with tiny payloads; no real build, SDK or live data."""
|
|
|
|
import hashlib
|
|
import importlib.util
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import zipfile
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from pathlib import Path
|
|
from unittest.mock import patch
|
|
|
|
import pytest
|
|
|
|
REPO = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(REPO / 'scripts/packaging'))
|
|
import qualified_payloads as q # noqa: E402
|
|
|
|
|
|
@pytest.fixture
|
|
def store(tmp_path, monkeypatch):
|
|
archive_root = tmp_path / 'build'
|
|
archive_root.mkdir()
|
|
qualified = archive_root / 'qualified'
|
|
qualified.mkdir()
|
|
monkeypatch.setattr(q, 'open_files', lambda paths: None)
|
|
return q.QualifiedPayloads(qualified, archive_root, tmp_path)
|
|
|
|
|
|
def seed(store, payloads=None):
|
|
payloads = payloads or {'node.deb': b'qualified-package', 'dependency.deb': b'dependency'}
|
|
report = json.dumps({'state': 'complete', 'artifacts': {
|
|
name: {'bytes': len(data), 'sha256': hashlib.sha256(data).hexdigest()}
|
|
for name, data in payloads.items()}}).encode()
|
|
(store.qualified / 'qualification.json').write_bytes(report)
|
|
for name, data in payloads.items():
|
|
(store.qualified / name).write_bytes(data)
|
|
output = store.archive_root / ('mission-core-node-install-' + 'a' * 24 + '.pyz')
|
|
with store.locked():
|
|
archive = store.publish(output, {'release.json': report, **payloads})
|
|
store.register(archive, payloads, 'qualification.json', report)
|
|
return output, payloads
|
|
|
|
|
|
def test_automatic_closeout_preserves_archive_report_and_unknown_files(store):
|
|
output, payloads = seed(store)
|
|
(store.qualified / 'foreign.deb').write_bytes(b'not admitted')
|
|
with store.locked():
|
|
result = store.closeout()
|
|
assert result['state'] == 'complete'
|
|
for name, data in payloads.items():
|
|
assert not (store.qualified / name).exists()
|
|
assert store.read(name) == data
|
|
assert store.closeout()['state'] == 'complete'
|
|
assert output.exists()
|
|
assert (store.qualified / 'foreign.deb').read_bytes() == b'not admitted'
|
|
assert (store.qualified / 'qualification.json').exists()
|
|
|
|
|
|
def test_persistent_consumer_hold_and_release_across_instances(store):
|
|
with store.locked():
|
|
token = store.hold('dependent qualification')
|
|
_, payloads = seed(store)
|
|
with store.locked():
|
|
assert store.closeout() == {'state': 'deferred', 'reason': 'consumer-hold'}
|
|
other = q.QualifiedPayloads(store.qualified, store.archive_root, store.repository)
|
|
with other.locked():
|
|
with pytest.raises(q.PayloadError, match='Unknown consumer'):
|
|
other.release('wrong-owner')
|
|
assert other.release(token)['state'] == 'complete'
|
|
assert all(not (store.qualified / n).exists() for n in payloads)
|
|
|
|
|
|
@pytest.mark.parametrize('reason', ['payload-in-use', 'open-file-check-unavailable'])
|
|
def test_active_or_unknown_reader_defers_and_retry_finishes(store, monkeypatch, reason):
|
|
_, payloads = seed(store)
|
|
monkeypatch.setattr(q, 'open_files', lambda paths: reason)
|
|
with store.locked():
|
|
assert store.closeout()['state'] == 'deferred'
|
|
assert all((store.qualified / n).exists() for n in payloads)
|
|
monkeypatch.setattr(q, 'open_files', lambda paths: None)
|
|
with store.locked():
|
|
assert store.closeout()['state'] == 'complete'
|
|
|
|
|
|
@pytest.mark.parametrize('target', ['archive', 'payload', 'qualification'])
|
|
def test_changed_inputs_block_all_unlinks(store, target):
|
|
output, payloads = seed(store)
|
|
path = {'archive': output, 'payload': store.qualified / 'dependency.deb',
|
|
'qualification': store.qualified / 'qualification.json'}[target]
|
|
path.write_bytes(b'changed')
|
|
with store.locked(), pytest.raises(q.PayloadError):
|
|
store.closeout()
|
|
assert all((store.qualified / n).exists() for n in payloads)
|
|
|
|
|
|
def test_archive_changed_during_reader_check_blocks_retirement(store, monkeypatch):
|
|
output, payloads = seed(store)
|
|
def change_archive(paths):
|
|
output.write_bytes(b'changed after verification')
|
|
monkeypatch.setattr(q, 'open_files', change_archive)
|
|
with store.locked(), pytest.raises(q.PayloadError, match='evidence changed'):
|
|
store.closeout()
|
|
assert all((store.qualified / n).exists() for n in payloads)
|
|
|
|
|
|
def test_pointer_write_failure_does_not_delete_source(store, monkeypatch):
|
|
_, payloads = seed(store)
|
|
def fail(*args):
|
|
raise OSError('disk full')
|
|
monkeypatch.setattr(q, 'atomic_json', fail)
|
|
with store.locked(), pytest.raises(OSError, match='disk full'):
|
|
store.closeout()
|
|
assert all((store.qualified / n).exists() for n in payloads)
|
|
|
|
|
|
def test_interruption_between_unlinks_is_recoverable(store, monkeypatch):
|
|
_, payloads = seed(store)
|
|
original = Path.unlink
|
|
def interrupted(path, *args, **kwargs):
|
|
if path == store.qualified / 'dependency.deb':
|
|
raise OSError('simulated shutdown')
|
|
return original(path, *args, **kwargs)
|
|
with monkeypatch.context() as m:
|
|
m.setattr(Path, 'unlink', interrupted)
|
|
with store.locked(), pytest.raises(OSError, match='shutdown'):
|
|
store.closeout()
|
|
assert not (store.qualified / 'node.deb').exists()
|
|
replacement = q.QualifiedPayloads(store.qualified, store.archive_root, store.repository)
|
|
with replacement.locked():
|
|
assert replacement.closeout()['state'] == 'complete'
|
|
for name, data in payloads.items():
|
|
assert replacement.read(name) == data
|
|
|
|
|
|
def test_hardlinks_retire_without_changing_other_owner(store):
|
|
_, payloads = seed(store, {'a.deb': b'shared', 'b.deb': b'shared'})
|
|
first, second = [store.qualified / n for n in payloads]
|
|
second.unlink()
|
|
second.hardlink_to(first)
|
|
retained = store.repository / 'other-owner.deb'
|
|
retained.hardlink_to(first)
|
|
with store.locked():
|
|
assert store.closeout()['state'] == 'complete'
|
|
assert retained.read_bytes() == b'shared'
|
|
|
|
|
|
@pytest.mark.parametrize('target', ['payload', 'archive', 'pointer'])
|
|
def test_symlinks_are_refused(store, target):
|
|
output, payloads = seed(store)
|
|
path = {'payload': store.qualified / 'node.deb', 'archive': output,
|
|
'pointer': store.pointer}[target]
|
|
retained = store.repository / 'foreign'
|
|
path.rename(retained)
|
|
path.symlink_to(retained)
|
|
with store.locked(), pytest.raises(q.PayloadError):
|
|
store.closeout()
|
|
assert retained.exists()
|
|
assert (store.qualified / 'dependency.deb').exists()
|
|
|
|
|
|
def test_legacy_pointer_is_readable_but_not_automatically_adopted(store):
|
|
_, payloads = seed(store)
|
|
doc = store.document()
|
|
doc.pop('managed_members')
|
|
doc.pop('qualification')
|
|
q.atomic_json(store.pointer, doc)
|
|
with store.locked():
|
|
assert store.closeout()['state'] == 'unmanaged'
|
|
for name, data in payloads.items():
|
|
(store.qualified / name).unlink()
|
|
assert store.read(name) == data
|
|
|
|
|
|
def test_unknown_and_traversal_records_do_not_delete_files(store):
|
|
seed(store)
|
|
doc = store.document()
|
|
doc['managed_members'] = ['../victim.deb']
|
|
q.atomic_json(store.pointer, doc)
|
|
victim = store.archive_root / 'victim.deb'
|
|
victim.write_bytes(b'foreign')
|
|
with store.locked(), pytest.raises(q.PayloadError):
|
|
store.closeout()
|
|
assert victim.read_bytes() == b'foreign'
|
|
|
|
|
|
def test_partial_publication_recovered_under_lock(store):
|
|
temporary = store.archive_root / ('.mission-core-node-install-' + 'a'*24 + '.pyz.' + 'b'*32)
|
|
temporary.write_bytes(b'incomplete transport')
|
|
q.atomic_json(store.archive_root / '.payload-publication.json',
|
|
{'temporary': temporary.name, 'identity': list(q.identity(temporary)[:2])})
|
|
output, _ = seed(store)
|
|
assert not temporary.exists()
|
|
assert not (store.archive_root / '.payload-publication.json').exists()
|
|
with zipfile.ZipFile(output) as z:
|
|
assert z.read('node.deb') == b'qualified-package'
|
|
|
|
|
|
def test_failed_publication_keeps_inputs_and_cleans_owned_scratch(store, monkeypatch):
|
|
output = store.archive_root / ('mission-core-node-install-' + 'a' * 24 + '.pyz')
|
|
source = store.qualified / 'node.deb'
|
|
source.write_bytes(b'unpublished')
|
|
def fail(*args, **kwargs):
|
|
raise OSError('simulated write failure')
|
|
monkeypatch.setattr(zipfile.ZipFile, 'writestr', fail)
|
|
with store.locked(), pytest.raises(OSError, match='write failure'):
|
|
store.publish(output, {'node.deb': b'unpublished'})
|
|
assert source.read_bytes() == b'unpublished'
|
|
assert not output.exists()
|
|
assert not (store.archive_root / '.payload-publication.json').exists()
|
|
assert not list(store.archive_root.glob('.mission-core-*.pyz.*'))
|
|
|
|
|
|
def test_interrupted_publication_does_not_remove_replaced_file(store):
|
|
temporary = store.archive_root / ('.mission-core-node-install-' + 'a'*24 + '.pyz.' + 'b'*32)
|
|
temporary.write_bytes(b'foreign replacement')
|
|
q.atomic_json(store.archive_root / '.payload-publication.json',
|
|
{'temporary': temporary.name, 'identity': [0, 0]})
|
|
output = store.archive_root / ('mission-core-node-install-' + 'a'*24 + '.pyz')
|
|
with store.locked(), pytest.raises(q.PayloadError, match='identity changed'):
|
|
store.publish(output, {'node.deb': b'payload'})
|
|
assert temporary.read_bytes() == b'foreign replacement'
|
|
assert not output.exists()
|
|
|
|
|
|
def load_builder(relative, name):
|
|
spec = importlib.util.spec_from_file_location(name, REPO / relative)
|
|
module = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(module)
|
|
return module
|
|
|
|
|
|
@pytest.mark.parametrize('kind', ['node', 'x4'])
|
|
def test_real_builders_auto_retire_and_can_rebuild_from_archive(tmp_path, monkeypatch, kind):
|
|
family = 'apps/node-agent' if kind == 'node' else 'plugins/insta360-x4'
|
|
module = load_builder(
|
|
family + '/packaging/build_owner_release.py',
|
|
'payload_builder_' + kind,
|
|
)
|
|
root = tmp_path / ('apps/node-agent' if kind == 'node' else 'plugins/insta360-x4')
|
|
(root / 'build').mkdir(parents=True)
|
|
(root / 'packaging').mkdir()
|
|
for name in ['install-owner-release', 'vesc_hall_recovery.py', 'can_maintenance.py',
|
|
'k1_maintenance.py', 'install_owner_release.py', 'install', 'install_release.py',
|
|
'owner_release_entry.py']:
|
|
(root / 'packaging' / name).write_bytes(b'# fixture\n')
|
|
entry = tmp_path / 'plugins/insta360-x4/packaging/owner_release_entry.py'
|
|
entry.parent.mkdir(parents=True, exist_ok=True)
|
|
entry.write_bytes(b'# fixture entry\n')
|
|
monkeypatch.setattr(module, 'ROOT', root)
|
|
monkeypatch.setattr(module, 'REPO', tmp_path)
|
|
monkeypatch.setattr(q, 'open_files', lambda paths: None)
|
|
qualified = root / 'build/fixture'
|
|
qualified.mkdir()
|
|
name = 'mission-core-' + ('node' if kind == 'node' else 'insta360-x4') + '_1.2.3_amd64.deb'
|
|
payloads = {name: b'qualified package'}
|
|
if kind == 'node':
|
|
payloads.update({n: n.encode() for n in module.NODE_DEPENDENCIES})
|
|
evidence = {'state': 'complete', 'artifacts': {n: {
|
|
'sha256': hashlib.sha256(b).hexdigest(), 'bytes': len(b)} for n, b in payloads.items()}}
|
|
if kind == 'x4':
|
|
evidence = {'version': '1.2.3', 'revision': 1, **evidence['artifacts'][name]}
|
|
report = qualified / ('qualification.json' if kind == 'node' else 'package-result.json')
|
|
report.write_text(json.dumps(evidence))
|
|
for n, b in payloads.items():
|
|
(qualified / n).write_bytes(b)
|
|
# Concurrent publication retries serialize; second call reads retained payloads.
|
|
with ThreadPoolExecutor(max_workers=2) as executor:
|
|
results = list(executor.map(lambda _: module.build(qualified), range(2)))
|
|
assert results[0]['artifact'] == results[1]['artifact']
|
|
assert results[0]['sha256'] == results[1]['sha256']
|
|
assert all(x['payload_cleanup']['state'] == 'complete' for x in results)
|
|
assert not list(qualified.glob('*.deb'))
|
|
assert len(list((root / 'build').glob('*.pyz'))) == 1
|
|
with zipfile.ZipFile(results[0]['artifact']) as z:
|
|
assert all(z.read(n) == b for n, b in payloads.items())
|
|
|
|
|
|
def test_real_lsof_reports_open_file(tmp_path):
|
|
path = tmp_path / 'held.deb'
|
|
path.write_bytes(b'held')
|
|
with path.open('rb'):
|
|
assert q.open_files([path]) == 'payload-in-use'
|
|
|
|
|
|
def test_x4_isolated_builder_uses_bundled_helper_without_repository(tmp_path):
|
|
root = tmp_path / 'portable'
|
|
packaging = root / 'packaging'
|
|
qualified = root / 'build'
|
|
packaging.mkdir(parents=True)
|
|
qualified.mkdir()
|
|
for name in ['build_owner_release.py', 'install', 'install_release.py',
|
|
'owner_release_entry.py']:
|
|
(packaging / name).write_bytes((REPO / 'plugins/insta360-x4/packaging' / name).read_bytes())
|
|
helper = REPO / 'scripts/packaging/qualified_payloads.py'
|
|
(packaging / 'qualified_payloads.py').write_bytes(helper.read_bytes())
|
|
name = 'mission-core-insta360-x4_1.2.3_amd64.deb'
|
|
payload = b'qualified fixture'
|
|
(qualified / name).write_bytes(payload)
|
|
(qualified / 'package-result.json').write_text(json.dumps({
|
|
'version': '1.2.3', 'revision': 1, 'bytes': len(payload),
|
|
'sha256': hashlib.sha256(payload).hexdigest(),
|
|
}))
|
|
command = [sys.executable, '-B', '-I', str(packaging / 'build_owner_release.py'),
|
|
'--qualified', str(qualified)]
|
|
result = subprocess.run(command, capture_output=True, text=True, check=True,
|
|
env={**os.environ, 'PATH': str(tmp_path / 'no-tools')}, timeout=30)
|
|
receipt = json.loads(result.stdout)
|
|
assert receipt['payload_cleanup'] == {
|
|
'state': 'deferred', 'reason': 'open-file-check-unavailable',
|
|
}
|
|
assert (qualified / name).exists()
|
|
with zipfile.ZipFile(receipt['artifact']) as z:
|
|
assert z.read(name) == payload
|
|
|
|
|
|
def test_open_file_check_failure_never_guesses(tmp_path):
|
|
path = tmp_path / 'p.deb'
|
|
with patch.object(q.shutil, 'which', return_value=None):
|
|
assert q.open_files([path]) == 'open-file-check-unavailable'
|
|
|
|
|
|
@pytest.mark.parametrize('corrupt', [False, True])
|
|
def test_runtime_repack_reads_verified_retired_base(tmp_path, monkeypatch, corrupt):
|
|
monkeypatch.syspath_prepend(str(REPO / 'apps/node-agent/packaging'))
|
|
module = load_builder('apps/node-agent/packaging/repack_runtime.py', 'retired_repack')
|
|
root = tmp_path / 'apps/node-agent/build'
|
|
qualified = root / 'qualified'
|
|
qualified.mkdir(parents=True)
|
|
payloads = q.QualifiedPayloads(qualified, root, tmp_path)
|
|
monkeypatch.setattr(q, 'open_files', lambda paths: None)
|
|
archive, _ = seed(payloads, {'base.deb': b'qualified predecessor'})
|
|
with payloads.locked():
|
|
payloads.closeout()
|
|
monkeypatch.setattr(module, 'REPO', tmp_path)
|
|
seen = []
|
|
def parse(data):
|
|
seen.append(data)
|
|
raise RuntimeError('parser reached')
|
|
monkeypatch.setattr(module, 'parts', parse)
|
|
if corrupt:
|
|
archive.write_bytes(b'corrupted installer')
|
|
with pytest.raises(q.PayloadError if corrupt else RuntimeError):
|
|
module.build(qualified / 'base.deb', hashlib.sha256(b'qualified predecessor').hexdigest(),
|
|
tmp_path / 'unused-binary', '1.2.3-4', tmp_path / 'output.deb')
|
|
assert seen == ([] if corrupt else [b'qualified predecessor'])
|
|
assert not (qualified / 'base.deb').exists()
|