#!/usr/bin/env python3 """Private mirror transport capture; not a sealed Archipelago Snapshot descriptor. Does not install packages, trust signatures or publish anything. The retained databases contain upstream signatures for the subsequent Arch verification stage. """ from contextlib import contextmanager from pathlib import Path import argparse import datetime import fcntl import hashlib import json import os import re import shutil import subprocess import tarfile def run(*args): return subprocess.check_output(args, text=True).strip() def inventory(database, repository, source): packages = [] with tarfile.open(database, 'r:gz') as archive: for member in archive: if not member.isfile() or not member.name.endswith('/desc'): continue if member.size > 1024 * 1024: raise ValueError('Oversized package record') fields = {} for section in archive.extractfile(member).read().decode().strip().split('\n\n'): lines = section.splitlines() if lines[0] in fields: raise ValueError('Duplicate database field') fields[lines[0]] = lines[1:] def one(key): values = fields['%' + key + '%'] if len(values) != 1: raise ValueError('Expected scalar database field: ' + key) return values[0] filename = one('FILENAME') if not re.fullmatch(r'[A-Za-z0-9@_+.:-]+\.pkg\.tar\.(zst|xz|gz)', filename): raise ValueError('Invalid package filename: ' + filename) digest = one('SHA256SUM') if not re.fullmatch('[a-f0-9]{64}', digest): raise ValueError('Invalid package digest') if not one('PGPSIG'): raise ValueError('Missing package signature') package = (source / repository / 'os/x86_64' / filename).resolve(strict=True) if not package.is_relative_to(source.resolve()) or not package.is_file(): raise ValueError('Package escapes mirror: ' + filename) size = int(one('CSIZE')) if size <= 0 or package.stat().st_size != size: raise ValueError('Package size mismatch: ' + filename) packages.append({'repository': repository, 'name': one('NAME'), 'version': one('VERSION'), 'filename': filename, 'size': size, 'sha256': digest, 'source': package}) if not packages or len({p['filename'] for p in packages}) != len(packages): raise ValueError('Empty or duplicate package catalog') return packages @contextmanager def mirror_lock(): # The descriptor belongs to the same container/lock inode as /syncrepo. process = subprocess.Popen(['docker', 'exec', '-i', 'arch-syncronizator', 'flock', '-w', '600', '/var/lock/syncrepo.lck', 'sh', '-c', 'echo locked; cat >/dev/null'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) try: if process.stdout.readline().strip() != 'locked': raise RuntimeError('Could not acquire mirror synchronization lock') yield process if process.poll() is not None: raise RuntimeError('Mirror synchronization lock lost') finally: process.stdin.close() try: process.wait(timeout=10) except subprocess.TimeoutExpired: process.terminate() process.wait(timeout=10) process.stdout.close() def capture(policy, month): if not policy.get('capture_enabled', False): raise ValueError('Mirror capture is disabled: experimental builds use the live mirror') dataset = policy['capture_dataset'] if dataset != 'tank/archipelago/mirror-capture' or policy['monthly_snapshot_limit'] != 3: raise ValueError('Unsupported capture binding or retention limit') target = Path(run('zfs', 'get', '-H', '-o', 'value', 'mountpoint', dataset)) if not target.is_absolute() or not target.is_dir(): raise ValueError('Capture dataset must already be mounted') with (target / '.capture.lock').open('a') as lock: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) snapshots = run('zfs', 'list', '-H', '-t', 'snapshot', '-o', 'name', '-r', policy['dataset']).splitlines() name = dataset + '@monthly-' + month if name in snapshots: raise ValueError('This month already exists; immutable captures are not replaced') monthly = [s for s in snapshots if '@monthly-' in s] if len(monthly) >= 3: raise ValueError('Three monthly snapshots retained; retire an unreferenced snapshot before capture') if any(target.glob('capture-*')): raise ValueError('Previous live capture remains; inspect it before another capture') source = Path(policy['source_root']) # A failed attempt is retained for inspection; never silently reuse it. work = target / ('capture-' + month) work.mkdir(mode=0o700) with mirror_lock() as guard: packages = [] databases = [] for repository in policy['repositories']: if repository not in ('core', 'extra'): raise ValueError('Unsupported repository') output = work / repository / 'os/x86_64' output.mkdir(parents=True) database = output / (repository + '.db') shutil.copyfile(source / repository / 'os/x86_64' / (repository + '.db'), database) databases.append({'repository': repository, 'sha256': hashlib.sha256(database.read_bytes()).hexdigest()}) packages.extend(inventory(database, repository, source)) for package in packages: if guard.poll() is not None: raise RuntimeError('Mirror synchronization lock lost') output = work / package['repository'] / 'os/x86_64' / package['filename'] digest = hashlib.sha256() with package['source'].open('rb') as src, output.open('xb') as dst: while data := src.read(1024 * 1024): digest.update(data) dst.write(data) if output.stat().st_size != package['size'] or digest.hexdigest() != package['sha256']: raise ValueError('Package integrity mismatch: ' + package['filename']) del package['source'] report = {'status': 'transport-verified-signatures-pending', 'month': month, 'databases': databases, 'packages': packages} (work / 'capture-report.json').write_text(json.dumps(report, sort_keys=True, indent=2) + '\n') # ZFS snapshot synchronizes dataset writes. Only complete captures get this name. run('zfs', 'snapshot', name) snapshot_path = target / '.zfs/snapshot' / ('monthly-' + month) / work.name if not (snapshot_path / 'capture-report.json').is_file(): raise RuntimeError('Snapshot is not readable; live capture retained') # The immutable snapshot retains this capture. Do not accumulate old live # copies inside subsequent snapshots, which would defeat the retention cap. shutil.rmtree(work) print(json.dumps({'snapshot': name, 'packages': len(packages), 'status': report['status'], 'path': str(snapshot_path)})) if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--policy', type=Path, default=Path(__file__).with_name('snapshot-policy.json')) parser.add_argument('--month', default=datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m')) args = parser.parse_args() if not re.fullmatch(r'\d{4}-(0[1-9]|1[0-2])', args.month): parser.error('Month must be YYYY-MM') if os.geteuid() != 0: parser.error('Run on the infrastructure host as root') capture(json.loads(args.policy.read_text()), args.month)