235 lines
13 KiB
Python
235 lines
13 KiB
Python
#!/usr/bin/env python3
|
|
"""HTTP boundary, full log access, and durable action failures; no real systemd changes."""
|
|
import importlib.util
|
|
import json
|
|
from pathlib import Path
|
|
import subprocess
|
|
import tempfile
|
|
import threading
|
|
import unittest
|
|
from urllib.error import HTTPError
|
|
from urllib.request import Request, urlopen
|
|
|
|
spec = importlib.util.spec_from_file_location('control', Path(__file__).parents[1] / 'control/server.py')
|
|
control = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(control)
|
|
|
|
|
|
class Portal(unittest.TestCase):
|
|
def test_http_boundaries_and_complete_logs(self):
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
base = Path(directory)
|
|
config = dict(coordinator_root=directory, worker_root=str(base / 'worker'),
|
|
worker_source_root=str(base / 'source'), allowed_networks=['127.0.0.0/8'], hosts=[])
|
|
app = control.App(config)
|
|
identity = '20261109T000000Z'
|
|
root = app.history / identity
|
|
root.mkdir(parents=True)
|
|
(root / 'state.json').write_text(json.dumps(dict(run=identity, state='failed')))
|
|
payload = b'first-line\n' + b'full output\n' * 40000 + b'last-line\n'
|
|
(root / 'large.log').write_bytes(payload)
|
|
(root / 'escape.log').symlink_to('/etc/passwd')
|
|
app.unit = lambda name: {'ActiveState': 'inactive'}
|
|
called = []
|
|
app.control = lambda action, parameters=None: called.append((action, parameters)) or {'accepted': True}
|
|
server = control.ThreadingHTTPServer(('127.0.0.1', 0), control.Handler)
|
|
server.app = app
|
|
host = f'127.0.0.1:{server.server_port}'
|
|
config['hosts'] = [host]
|
|
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
|
thread.start()
|
|
url = 'http://' + host
|
|
try:
|
|
with urlopen(url + '/api/run?run=' + identity) as response:
|
|
logs = json.load(response)['logs']
|
|
self.assertNotIn('monitor/escape.log', [l['id'] for l in logs])
|
|
address = url + '/api/log?run=' + identity + '&id=monitor/large.log'
|
|
reconstructed = b''
|
|
while len(reconstructed) < len(payload):
|
|
with urlopen(address + '&offset=' + str(len(reconstructed))) as response:
|
|
page = json.load(response)
|
|
reconstructed += page['text'].encode()
|
|
self.assertEqual(reconstructed, payload)
|
|
with urlopen(address + '&download=1') as response:
|
|
self.assertEqual(response.read(), payload)
|
|
for bad in ('/api/run?run=../', '/api/log?run='+identity+'&id=monitor/../../etc/passwd'):
|
|
with self.assertRaises(HTTPError):
|
|
urlopen(url + bad)
|
|
headers = {'Content-Type': 'application/json', 'X-Archipelago-Control': '1'}
|
|
with self.assertRaises(HTTPError) as error:
|
|
urlopen(Request(url+'/api/control', data=b'{"action":"start"}', headers=headers))
|
|
self.assertEqual(error.exception.code, 403)
|
|
headers['Origin'] = url
|
|
with urlopen(Request(url+'/api/control', data=b'{"action":"start"}', headers=headers)) as response:
|
|
self.assertEqual(response.status, 202)
|
|
self.assertEqual(called, [('start', {'action': 'start'})])
|
|
with self.assertRaises(HTTPError):
|
|
urlopen(Request(url+'/', headers={'Host':'attacker.example'}))
|
|
finally:
|
|
server.shutdown()
|
|
server.server_close()
|
|
|
|
def test_start_pins_mode_and_snapshot_before_the_unit_starts(self):
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
base = Path(directory)
|
|
app = control.App(dict(coordinator_root=directory, worker_root=str(base / 'worker'),
|
|
worker_source_root=str(base / 'source'),
|
|
allowed_networks=['127.0.0.0/8'], hosts=[]))
|
|
app.unit = lambda name: {'ActiveState': 'inactive'}
|
|
asked = []
|
|
app.snapshot_date = lambda choice: asked.append(choice) or '2026-11-12'
|
|
calls = []
|
|
original = control.subprocess.run
|
|
control.subprocess.run = lambda argv, **kwargs: (calls.append(argv)
|
|
or subprocess.CompletedProcess(argv, 0, b'', b''))
|
|
try:
|
|
result = app.control('start', {'action': 'start', 'mode': 'ostree', 'snapshot': 'latest'})
|
|
finally:
|
|
control.subprocess.run = original
|
|
request = json.loads((app.archive / 'cycle-request.json').read_text())
|
|
self.assertEqual((request['mode'], request['snapshot']), ('ostree', '2026-11-12'))
|
|
self.assertIn('requested_at', request)
|
|
self.assertEqual(result['request']['snapshot'], '2026-11-12')
|
|
self.assertEqual(calls, [['systemctl', 'start', '--no-block', control.SERVICE]])
|
|
self.assertEqual(asked, ['latest'])
|
|
# Unknown modes are rejected before anything is pinned or started.
|
|
(app.archive / 'cycle-request.json').unlink()
|
|
with self.assertRaises(ValueError):
|
|
app.control('start', {'mode': 'reboot'})
|
|
self.assertFalse((app.archive / 'cycle-request.json').exists())
|
|
# A resume keeps the failed run's mode and snapshot: it pins neither,
|
|
# so the same ordinary service unit and the same stop button apply.
|
|
asked.clear()
|
|
control.subprocess.run = lambda argv, **kwargs: subprocess.CompletedProcess(argv, 0, b'', b'')
|
|
try:
|
|
resumed = app.control('start', {'action': 'start', 'resume': True})
|
|
finally:
|
|
control.subprocess.run = original
|
|
request = json.loads((app.archive / 'cycle-request.json').read_text())
|
|
self.assertEqual(request.get('resume'), True)
|
|
self.assertNotIn('mode', request)
|
|
self.assertNotIn('snapshot', request)
|
|
self.assertEqual(asked, [])
|
|
self.assertEqual(resumed['request'], request)
|
|
|
|
def test_snapshot_listing_uses_the_published_manifest(self):
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
base = Path(directory)
|
|
manifest = base / 'snapshots.json'
|
|
manifest.write_text(json.dumps({'updated': '2026-11-15T00:00:00Z', 'snapshots': [
|
|
{'date': '2026-11-12', 'url': '/archipelago/arch-repo-snapshot/2026-11-12/$repo/os/$arch'},
|
|
{'date': '../../etc'},
|
|
]}))
|
|
app = control.App(dict(coordinator_root=directory, worker_root=directory,
|
|
worker_source_root=directory, snapshot_manifest=str(manifest),
|
|
allowed_networks=['127.0.0.0/8'], hosts=[]))
|
|
self.assertEqual([item['date'] for item in app.snapshots()], ['2026-11-12'])
|
|
self.assertEqual(app.snapshot_date('latest'), '2026-11-12')
|
|
self.assertEqual(app.snapshot_date('2026-11-12'), '2026-11-12')
|
|
for choice in ('2026-11-01', '../../etc', ''):
|
|
with self.assertRaises(ValueError):
|
|
app.snapshot_date(choice)
|
|
# No published manifest is a clear refusal, not an empty build input.
|
|
manifest.unlink()
|
|
with self.assertRaises(ValueError):
|
|
app.snapshot_date('latest')
|
|
|
|
def test_snapshot_must_be_downloadable_before_a_build_starts(self):
|
|
served = set()
|
|
|
|
class Handler(control.BaseHTTPRequestHandler):
|
|
def do_HEAD(self):
|
|
self.send_response(200 if self.path in served else 404)
|
|
self.end_headers()
|
|
|
|
def log_message(self, *args):
|
|
pass
|
|
|
|
server = control.ThreadingHTTPServer(('127.0.0.1', 0), Handler)
|
|
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
|
thread.start()
|
|
try:
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
base = Path(directory)
|
|
manifest = base / 'snapshots.json'
|
|
manifest.write_text(json.dumps({'snapshots': [{'date': '2026-11-15'}]}))
|
|
app = control.App(dict(coordinator_root=directory, worker_root=directory,
|
|
worker_source_root=directory, snapshot_manifest=str(manifest),
|
|
snapshot_verify_url=f'http://127.0.0.1:{server.server_port}/archipelago',
|
|
snapshot_verify_timeout=5,
|
|
allowed_networks=['127.0.0.0/8'], hosts=[]))
|
|
path = '/archipelago/arch-repo-snapshot/2026-11-15/core/os/x86_64/core.db'
|
|
# A published manifest date is not proof that the view is served: the
|
|
# artifact container can still hold the mount view it started with.
|
|
with self.assertRaises(ValueError):
|
|
app.snapshot_date('latest')
|
|
served.add(path)
|
|
self.assertEqual(app.snapshot_date('latest'), '2026-11-15')
|
|
self.assertEqual(app.snapshot_date('2026-11-15'), '2026-11-15')
|
|
finally:
|
|
server.shutdown()
|
|
server.server_close()
|
|
|
|
def test_snapshot_views_reach_the_artifact_container(self):
|
|
# Host mounts made after the serving container started are invisible to it
|
|
# without slave propagation, and a 404 in the first pacman -Syu fails a run.
|
|
compose = (Path(__file__).parents[1] / 'compose.yaml').read_text()
|
|
self.assertIn('propagation: rslave', compose)
|
|
script = (Path(__file__).parents[1] / 'deploy/mirror-snapshot-mount.sh').read_text()
|
|
self.assertIn('container_serves', script)
|
|
self.assertIn('excluded from the published list', script)
|
|
|
|
def test_snapshot_retention_detaches_before_destroy(self):
|
|
# A published view is a mount of the snapshot itself, and `zfs destroy`
|
|
# of a mounted snapshot fails with "dataset is busy". Retention must
|
|
# detach the view and every other namespace mount (`.zfs/snapshot`
|
|
# automounts of the mirror rsync container) before the destroy.
|
|
script = (Path(__file__).parents[1] / 'deploy/mirror-snapshot.sh').read_text()
|
|
destroy = script.index('zfs destroy')
|
|
self.assertLess(script.index('unmount_view "$view/$date"'), destroy)
|
|
self.assertLess(script.index('detach_snapshot_mounts "$snap"'), destroy)
|
|
self.assertIn('/proc/[0-9]*/mountinfo', script)
|
|
self.assertIn('nsenter -t "$pid" -m -- umount', script)
|
|
# A container can keep the propagated mount busy; retention must still be
|
|
# able to detach it lazily instead of keeping a fourth snapshot.
|
|
self.assertIn('nsenter -t "$pid" -m -- umount -l', script)
|
|
self.assertIn('dataset is busy', script)
|
|
self.assertIn('umount -l', script)
|
|
|
|
def test_release_unit_can_be_stopped_promptly(self):
|
|
# A long-running driver must not be a oneshot: systemd then refuses to
|
|
# deliver SIGTERM until TimeoutStopSec, so a stop looks ignored for minutes.
|
|
unit = (Path(__file__).parents[1] / 'deploy/archipelago-release-cycle.service').read_text()
|
|
self.assertIn('Type=exec', unit)
|
|
self.assertNotIn('Type=oneshot', unit)
|
|
|
|
def test_progress_markup_and_percentage_rules(self):
|
|
root = Path(__file__).parents[1] / 'control'
|
|
html = (root / 'index.html').read_text()
|
|
script = (root / 'app.js').read_text()
|
|
self.assertIn('id="run-progress-track"', html)
|
|
self.assertIn('role="progressbar"', html)
|
|
self.assertIn('aria-valuenow', html)
|
|
self.assertIn('id="build-mode"', html)
|
|
self.assertIn('id="build-snapshot"', html)
|
|
self.assertIn('function progressOf(', script)
|
|
self.assertIn("track.setAttribute('aria-valuenow'", script)
|
|
self.assertIn("control('start',{mode:$('build-mode').value,snapshot:$('build-snapshot').value})", script)
|
|
# Resume is the same start action: one unit, one stop button, one status.
|
|
self.assertIn('id="resume"', html)
|
|
self.assertIn("$('resume').onclick=()=>control('start',{resume:true})", script)
|
|
self.assertIn("latest.state!=='failed'", script)
|
|
|
|
def test_failed_action_is_durable(self):
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
observer = control.monitor.Monitor(Path(directory), '20261109T000000Z')
|
|
with self.assertRaises(subprocess.CalledProcessError):
|
|
observer.call(['python3', '-c', 'import sys; print("diagnostic"); sys.exit(7)'])
|
|
action = json.loads((observer.root / 'action-0001.json').read_text())
|
|
self.assertEqual(action['returncode'], 7)
|
|
self.assertEqual(action['state'], 'failed')
|
|
self.assertIn('diagnostic', (observer.root / action['log']).read_text())
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|