274 lines
17 KiB
Python
274 lines
17 KiB
Python
#!/usr/bin/env python3
|
|
"""Atomic, evidence-validated hardware-test publication; not testing/stable."""
|
|
import argparse
|
|
import fcntl
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import tempfile
|
|
|
|
|
|
def digest(path):
|
|
with Path(path).open('rb') as stream:
|
|
return hashlib.file_digest(stream, 'sha256').hexdigest()
|
|
|
|
|
|
def ostree(repo, *args):
|
|
return subprocess.check_output(['ostree', '--repo=' + str(repo), *args], text=True).strip()
|
|
|
|
|
|
def publish(public, records, gpg_home=None, gpg_key=None, archives=None, validate_only=False,
|
|
url_prefix='', refs=None, channel='hardware-test', exception=None, compatibility=None):
|
|
compatibility = compatibility or {'core': [], 'gnome': []}
|
|
if channel not in ('hardware-test', 'testing', 'stable'):
|
|
raise ValueError('Invalid release channel')
|
|
if channel != 'hardware-test':
|
|
identities = [{k: r[k] for k in ('variant', 'version', 'sha256', 'image_commit', 'layer_commit')} for r in records]
|
|
if not exception or exception.get('channel') != channel or not exception.get('decision') or not exception.get('reason') or not exception.get('limitations') or sorted(exception.get('candidates', []), key=lambda r: r['variant']) != sorted(identities, key=lambda r: r['variant']):
|
|
raise ValueError('This interim publisher requires an exact, explicitly approved release exception for production channels')
|
|
if url_prefix and not re.fullmatch(r'(?:/[A-Za-z0-9_-]+)+', url_prefix):
|
|
raise ValueError('URL prefix must be an absolute path without trailing slash')
|
|
refs = refs or {'core': 'hardware-test/core', 'gnome': 'hardware-test/gnome'}
|
|
if set(refs) != {'core', 'gnome'} or len(set(refs.values())) != 2:
|
|
raise ValueError('Distinct Core and GNOME refs required')
|
|
if set(compatibility) != {'core', 'gnome'}:
|
|
raise ValueError('Invalid compatibility ref map')
|
|
all_refs = list(refs.values()) + [ref for values in compatibility.values() for ref in values]
|
|
if len(set(all_refs)) != len(all_refs):
|
|
raise ValueError('Publication refs must be distinct')
|
|
for ref in all_refs:
|
|
if not re.fullmatch(r'[A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+)*', ref) or any(p in ('.', '..') for p in ref.split('/')) or ref.startswith('history/'):
|
|
raise ValueError('Invalid publication ref')
|
|
archives = archives or []
|
|
if bool(gpg_home) != bool(gpg_key):
|
|
raise ValueError('Signing home and fingerprint must be supplied together')
|
|
if len(records) != 2 or {r['variant'] for r in records} != {'core', 'gnome'}:
|
|
raise ValueError('Exactly one Core and one GNOME candidate required')
|
|
for r in records + archives:
|
|
if r['variant'] not in ('core', 'gnome'):
|
|
raise ValueError('Invalid variant')
|
|
if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._-]{0,127}', r['version']):
|
|
raise ValueError('Invalid version')
|
|
for key in ('sha256', 'image_commit', 'layer_commit'):
|
|
if not re.fullmatch(r'[0-9a-f]{64}', r[key]):
|
|
raise ValueError('Invalid ' + key)
|
|
if digest(r['iso']) != r['sha256']:
|
|
raise ValueError('ISO checksum mismatch')
|
|
acceptance = json.loads(Path(r['acceptance']).read_text())
|
|
if acceptance.get('scope') != 'hardware-test' or acceptance.get('accepted') is not True:
|
|
raise ValueError('Explicit hardware-test acceptance required')
|
|
for key in ('variant', 'version', 'sha256', 'image_commit', 'layer_commit'):
|
|
if acceptance.get(key) != r[key]:
|
|
raise ValueError('Acceptance identity mismatch: ' + key)
|
|
if not acceptance.get('checks'):
|
|
raise ValueError('Acceptance must identify checks')
|
|
for check in acceptance['checks']:
|
|
if digest(check['path']) != check['sha256']:
|
|
raise ValueError('Evidence checksum mismatch')
|
|
for key in ('image_commit', 'layer_commit'):
|
|
ostree(r['repo'], 'show', r[key])
|
|
linked = ostree(r['repo'], 'show', '--print-metadata-key=archipelago.layer-core', r['image_commit'])
|
|
if linked != "'" + r['layer_commit'] + "'":
|
|
raise ValueError('Image/layer provenance mismatch')
|
|
if r.get('purpose_layer_commit'):
|
|
purpose = r['purpose_layer_commit']
|
|
if not re.fullmatch(r'[0-9a-f]{64}', purpose) or acceptance.get('purpose_layer_commit') != purpose:
|
|
raise ValueError('Purpose identity mismatch')
|
|
ostree(r['repo'], 'show', purpose)
|
|
if ostree(r['repo'], 'show', '--print-metadata-key=archipelago.layer-purpose', r['image_commit']) != "'" + purpose + "'":
|
|
raise ValueError('Image/Purpose provenance mismatch')
|
|
if validate_only:
|
|
print(json.dumps({'valid': True, 'variants': [r['variant'] for r in records]}))
|
|
return
|
|
public.mkdir(parents=True, exist_ok=True)
|
|
with (public / '.publish.lock').open('a') as lock:
|
|
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
generations = public / '.generations'
|
|
generations.mkdir(exist_ok=True)
|
|
previous = (public / 'current').resolve() if (public / 'current').is_symlink() else None
|
|
if (public / 'current').exists() and previous is None:
|
|
raise ValueError('current must be a managed symlink')
|
|
stage = Path(tempfile.mkdtemp(prefix='hardware-', dir=generations))
|
|
stage.chmod(0o755)
|
|
switched = False
|
|
try:
|
|
for directory in ('iso', 'v1', 'ostree'):
|
|
(stage / directory).mkdir()
|
|
history = json.loads((previous / 'history.json').read_text()) if previous else {'core': [], 'gnome': []}
|
|
for kind in ('images', 'layers'):
|
|
repo = stage / 'ostree' / kind
|
|
if previous:
|
|
subprocess.run(['cp', '-a', '--reflink=auto', str(previous / 'ostree' / kind), str(repo)], check=True)
|
|
old_refs_file = previous / 'publication-refs.json'
|
|
old_refs = json.loads(old_refs_file.read_text()) if old_refs_file.exists() else {
|
|
'core': 'hardware-test/core', 'gnome': 'hardware-test/gnome'}
|
|
old_alias_file = previous / 'compatibility-refs.json'
|
|
old_aliases = json.loads(old_alias_file.read_text()) if old_alias_file.exists() else {}
|
|
old_names = set(old_refs.values()) | {ref for values in old_aliases.values() for ref in values}
|
|
for old_ref in old_names - set(all_refs):
|
|
# Experimental publication must not move or remove a
|
|
# previously accepted production channel.
|
|
if channel == 'hardware-test' and old_ref.startswith(('stable/', 'testing/')):
|
|
continue
|
|
ostree(repo, 'refs', '--delete', old_ref)
|
|
else:
|
|
ostree(repo, 'init', '--mode=archive')
|
|
releases = []
|
|
api_releases = []
|
|
for r in records:
|
|
variant = r['variant']
|
|
entry = {k: r[k] for k in ('version', 'image_commit', 'layer_commit', 'sha256')}
|
|
entry['channel'] = channel
|
|
if r.get('purpose_layer_commit'):
|
|
entry['purpose_layer_commit'] = r['purpose_layer_commit']
|
|
if exception:
|
|
entry['release_exception'] = {k: exception[k] for k in ('decision', 'reason', 'limitations')}
|
|
old = history[variant]
|
|
if any(e['version'] == r['version'] and any(e.get(k, r[k]) != r[k]
|
|
for k in ('image_commit', 'layer_commit', 'sha256')) for e in old):
|
|
raise ValueError('Version identity cannot change')
|
|
candidates = [e for e in old if e['version'] != r['version']] + [entry]
|
|
protected = []
|
|
if channel == 'hardware-test':
|
|
image_repo = stage / 'ostree/images'
|
|
existing_refs = set(ostree(image_repo, 'refs').splitlines())
|
|
production = {ostree(image_repo, 'rev-parse', ref) for ref in
|
|
('stable/' + variant, 'testing/' + variant) if ref in existing_refs}
|
|
protected = [e for e in candidates if e['image_commit'] in production]
|
|
ordinary = [e for e in candidates if e not in protected]
|
|
history[variant] = protected + ordinary[-(3 - len(protected)):] if len(protected) < 3 else protected[-3:]
|
|
if r.get('purpose_layer_commit'):
|
|
repo = stage / 'ostree/layers'
|
|
ostree(repo, 'pull-local', '--depth=0', r['repo'], r['purpose_layer_commit'])
|
|
for ref in ostree(repo, 'refs').splitlines():
|
|
if ref.startswith('history/purpose/' + variant + '/'):
|
|
ostree(repo, 'refs', '--delete', ref)
|
|
for e in history[variant]:
|
|
if e.get('purpose_layer_commit'):
|
|
ostree(repo, 'refs', '--create=history/purpose/' + variant + '/' + e['version'], e['purpose_layer_commit'])
|
|
ostree(repo, 'refs', '--force', '--create=purpose/desktop/' + variant, r['purpose_layer_commit'])
|
|
for kind, key in (('images', 'image_commit'), ('layers', 'layer_commit')):
|
|
repo = stage / 'ostree' / kind
|
|
ostree(repo, 'pull-local', '--depth=0', r['repo'], r[key])
|
|
for ref in ostree(repo, 'refs').splitlines():
|
|
if ref.startswith('history/' + variant + '/'):
|
|
ostree(repo, 'refs', '--delete', ref)
|
|
for e in history[variant]:
|
|
ostree(repo, 'refs', '--create=history/' + variant + '/' + e['version'], e[key])
|
|
ostree(repo, 'refs', '--force', '--create=' + refs[variant], r[key])
|
|
for alias in compatibility[variant]:
|
|
ostree(repo, 'refs', '--force', '--create=' + alias, r[key])
|
|
name = 'archipelago-' + variant + '.iso'
|
|
available = []
|
|
for e in history[variant]:
|
|
relative = Path('iso') / variant / e['version'] / name
|
|
target = stage / relative
|
|
source_record = next((a for a in records + archives
|
|
if a['variant'] == variant and a['version'] == e['version']), None)
|
|
if source_record:
|
|
if any(source_record[k] != e[k] for k in ('image_commit', 'layer_commit')):
|
|
raise ValueError('Archive identity mismatch')
|
|
if e.get('sha256') and source_record['sha256'] != e['sha256']:
|
|
raise ValueError('Archive ISO identity cannot change')
|
|
source = Path(source_record['iso'])
|
|
e['sha256'] = source_record['sha256']
|
|
elif previous and (previous / relative).is_file() and e.get('sha256'):
|
|
source = previous / relative
|
|
else:
|
|
# Old history can retain commits without ISO bytes.
|
|
continue
|
|
target.parent.mkdir(parents=True, exist_ok=True)
|
|
if previous and source.is_relative_to(previous):
|
|
os.link(source, target)
|
|
else:
|
|
shutil.copyfile(source, target)
|
|
if digest(target) != e['sha256']:
|
|
raise ValueError('Archived ISO checksum mismatch')
|
|
target.with_suffix('.iso.sha256').write_text(e['sha256'] + ' ' + name + '\n')
|
|
item = dict(variant=variant, architecture='x86_64', channel=e.get('channel', 'hardware-test'),
|
|
version=e['version'], sha256=e['sha256'], image_commit=e['image_commit'],
|
|
layer_commit=e['layer_commit'], size_bytes=target.stat().st_size,
|
|
current=e['version'] == r['version'],
|
|
url=url_prefix + '/' + relative.as_posix(),
|
|
checksum_url=url_prefix + '/' + relative.as_posix() + '.sha256')
|
|
if e.get('release_exception'):
|
|
item['release_exception'] = e['release_exception']
|
|
if e.get('purpose_layer_commit'):
|
|
item['purpose_layer_commit'] = e['purpose_layer_commit']
|
|
available.append(item)
|
|
detail = stage / 'v1/releases' / variant / (e['version'] + '.json')
|
|
detail.parent.mkdir(parents=True, exist_ok=True)
|
|
detail.write_text(json.dumps(dict(apiVersion='archipelago.releases/v1', release=item), indent=2) + '\n')
|
|
available.reverse()
|
|
api_releases.extend(available)
|
|
(stage / 'v1/releases' / (variant + '.json')).write_text(json.dumps(
|
|
dict(apiVersion='archipelago.releases/v1', releases=available), indent=2) + '\n')
|
|
os.link(stage / 'iso' / variant / r['version'] / name, stage / 'iso' / name)
|
|
(stage / 'iso' / (name + '.sha256')).write_text(r['sha256'] + ' ' + name + '\n')
|
|
# Expose identities/check names, not private evidence paths.
|
|
(stage / 'v1' / (variant + '.json')).write_text(json.dumps(entry, indent=2) + '\n')
|
|
releases.append(dict(variant={'core': 'Arch Core', 'gnome': 'GNOME Desktop'}[variant],
|
|
architecture='x86_64', channel=channel, version=r['version'],
|
|
sha256=r['sha256'], image_commit=r['image_commit'], url=url_prefix + '/iso/' + name))
|
|
if exception:
|
|
releases[-1]['release_exception'] = entry['release_exception']
|
|
for kind in ('images', 'layers'):
|
|
repo = stage / 'ostree' / kind
|
|
ostree(repo, 'prune', '--refs-only', '--depth=0')
|
|
ostree(repo, 'fsck')
|
|
if gpg_key:
|
|
commits = {ostree(repo, 'rev-parse', ref) for ref in ostree(repo, 'refs').splitlines()}
|
|
for commit in commits:
|
|
ostree(repo, 'gpg-sign', '--delete', '--gpg-homedir=' + str(gpg_home), commit, gpg_key)
|
|
ostree(repo, 'gpg-sign', '--gpg-homedir=' + str(gpg_home), commit, gpg_key)
|
|
ostree(repo, 'summary', '--update', '--gpg-sign=' + gpg_key,
|
|
'--gpg-homedir=' + str(gpg_home))
|
|
else:
|
|
ostree(repo, 'summary', '--update')
|
|
(stage / 'history.json').write_text(json.dumps(history, indent=2) + '\n')
|
|
(stage / 'publication-refs.json').write_text(json.dumps(refs, indent=2) + '\n')
|
|
(stage / 'compatibility-refs.json').write_text(json.dumps(compatibility, indent=2) + '\n')
|
|
(stage / 'v1/releases.json').write_text(json.dumps(dict(
|
|
apiVersion='archipelago.releases/v1', retention_per_variant=3,
|
|
releases=api_releases), indent=2) + '\n')
|
|
(stage / 'releases.json').write_text(json.dumps(dict(version=1, releases=releases,
|
|
reason=os.environ.get('ARCHIPELAGO_RELEASE_REASON', '')), indent=2) + '\n')
|
|
subprocess.run(['sync', '-f', str(stage)], check=True)
|
|
link = public / '.next-publication'
|
|
link.unlink(missing_ok=True)
|
|
link.symlink_to(stage.relative_to(public))
|
|
os.replace(link, public / 'current')
|
|
switched = True
|
|
subprocess.run(['sync', '-f', str(public)], check=True)
|
|
if previous and previous.parent == generations.resolve():
|
|
shutil.rmtree(previous)
|
|
finally:
|
|
if not switched:
|
|
shutil.rmtree(stage)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('public_root', type=Path)
|
|
parser.add_argument('candidates', type=Path)
|
|
parser.add_argument('--gpg-home', type=Path, required=True)
|
|
parser.add_argument('--gpg-key', required=True)
|
|
parser.add_argument('--archive-candidates', type=Path)
|
|
parser.add_argument('--check-only', action='store_true')
|
|
parser.add_argument('--url-prefix', default='')
|
|
parser.add_argument('--core-ref', default='hardware-test/core')
|
|
parser.add_argument('--gnome-ref', default='hardware-test/gnome')
|
|
parser.add_argument('--channel', default='hardware-test')
|
|
parser.add_argument('--release-exception', type=Path)
|
|
parser.add_argument('--compat-core-ref', action='append', default=[])
|
|
parser.add_argument('--compat-gnome-ref', action='append', default=[])
|
|
args = parser.parse_args()
|
|
publish(args.public_root.resolve(), json.loads(args.candidates.read_text()), args.gpg_home, args.gpg_key,
|
|
json.loads(args.archive_candidates.read_text()) if args.archive_candidates else None,
|
|
args.check_only, args.url_prefix, {'core': args.core_ref, 'gnome': args.gnome_ref},
|
|
args.channel, json.loads(args.release_exception.read_text()) if args.release_exception else None,
|
|
{'core': args.compat_core_ref, 'gnome': args.compat_gnome_ref})
|