130 lines
6.7 KiB
Python
130 lines
6.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Private offline install phase. Execute inside the isolated layer builder.
|
|
|
|
Only fresh target roots are accepted. Action inventory is supplied by the
|
|
authenticated build profile, not by the package or a D-Bus caller.
|
|
"""
|
|
import base64
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
import stat
|
|
import subprocess
|
|
import sys
|
|
|
|
|
|
def require(value, message):
|
|
if not value:
|
|
raise ValueError(message)
|
|
|
|
|
|
def digest(path):
|
|
with path.open('rb') as stream:
|
|
return hashlib.file_digest(stream, 'sha256').hexdigest()
|
|
|
|
|
|
def member(archive, name):
|
|
result = subprocess.run(['bsdtar', '-xOf', str(archive), name], check=True,
|
|
stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=60)
|
|
require(len(result.stdout) <= 16 * 1024 * 1024, 'Oversized package action')
|
|
return result.stdout
|
|
|
|
|
|
def install(lock, receipt, policy, cache, target):
|
|
import pyalpm
|
|
require(Path('/run/archipelago-layer-sandbox').is_file(), 'Layer sandbox required')
|
|
require(type(lock.get('version')) is int and lock['version'] == 0 and receipt.get('version') == 0, 'Invalid input version')
|
|
require(Path('/usr/lib/archipelago/snapshot').read_text().strip() == lock['snapshot_id'], 'Snapshot mismatch')
|
|
resolution_hash = hashlib.sha256(json.dumps(lock, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
|
|
require(receipt['resolution_sha256'] == resolution_hash and receipt['snapshot_id'] == lock['snapshot_id'], 'Download receipt mismatch')
|
|
require(target.is_absolute() and target.parent == Path('/run') and not target.exists() and not target.is_symlink(), 'Fresh private target required')
|
|
require(cache.is_absolute() and cache.is_dir() and not cache.is_symlink() and
|
|
all(not parent.is_symlink() for parent in cache.parents), 'Invalid archive cache')
|
|
require(policy.get('version') == 0 and isinstance(policy.get('actions'), list), 'Invalid action policy')
|
|
actions = {}
|
|
for entry in policy['actions']:
|
|
require(set(entry) == {'kind', 'sha256', 'phase'} and entry['kind'] in ('scriptlet', 'hook') and
|
|
re.fullmatch('[0-9a-f]{64}', entry['sha256']) and entry['phase'] == 'layer-build',
|
|
'Unsupported action policy entry')
|
|
key = (entry['kind'], entry['sha256'])
|
|
require(key not in actions, 'Duplicate policy action')
|
|
actions[key] = entry
|
|
archives = []
|
|
expected = {}
|
|
for row in lock['packages']:
|
|
filename = row['filename']
|
|
require(filename and Path(filename).name == filename and filename not in ('.', '..'), 'Invalid archive name')
|
|
path = cache / filename
|
|
require(stat.S_ISREG(path.lstat().st_mode) and digest(path) == row['archive_sha256'], 'Archive checksum mismatch')
|
|
signature = cache / (filename + '.sig')
|
|
require(stat.S_ISREG(signature.lstat().st_mode) and signature.read_bytes() == base64.b64decode(row['signature'], validate=True),
|
|
'Archive signature differs from locked input')
|
|
require(row['name'] not in expected, 'Duplicate package')
|
|
expected[row['name']] = (row['version'], row['architecture'])
|
|
archives.append((path, row))
|
|
require(receipt['archives'] == [dict(filename=row['filename'], sha256=row['archive_sha256']) for _, row in archives],
|
|
'Receipt does not cover exact closure')
|
|
target.mkdir(mode=0o700)
|
|
database = target / 'var/lib/pacman'
|
|
database.mkdir(parents=True)
|
|
handle = pyalpm.Handle(str(target), str(database))
|
|
handle.arch = [lock['architecture']]
|
|
handle.gpgdir = '/etc/pacman.d/gnupg'
|
|
handle.cachedirs = [str(cache)]
|
|
handle.logfile = str(target / 'install.log')
|
|
errors = []
|
|
def log(level, message):
|
|
if level & pyalpm.LOG_ERROR or (level & pyalpm.LOG_WARNING and re.search(r'fail(ed|ure)', message, re.I)):
|
|
errors.append(message)
|
|
if level & (pyalpm.LOG_ERROR | pyalpm.LOG_WARNING):
|
|
print(message, file=sys.stderr)
|
|
handle.logcb = log
|
|
handle.eventcb = lambda *_: None
|
|
handle.progresscb = lambda *_: None
|
|
packages = []
|
|
observed = []
|
|
for archive, row in archives:
|
|
package = handle.load_pkg(str(archive), check_sig=pyalpm.SIG_PACKAGE)
|
|
require((package.name, package.version, package.arch) == (row['name'], row['version'], row['architecture']), 'Archive identity mismatch')
|
|
listing = subprocess.run(['bsdtar', '-tf', str(archive)], check=True, stdout=subprocess.PIPE,
|
|
stderr=subprocess.PIPE, timeout=60).stdout.decode().splitlines()
|
|
seen = set()
|
|
for raw in listing:
|
|
path = raw.removeprefix('./').rstrip('/')
|
|
require(path and not path.startswith('/') and all(part not in ('', '.', '..') for part in path.split('/')),
|
|
'Invalid archive member path')
|
|
require(path not in seen, 'Duplicate archive member')
|
|
seen.add(path)
|
|
require(not path.startswith('etc/pacman.d/hooks/'), 'Unreviewed hook override')
|
|
kind = 'scriptlet' if path == '.INSTALL' else 'hook' if path.startswith('usr/share/libalpm/hooks/') and path.endswith('.hook') else None
|
|
if kind:
|
|
identity = hashlib.sha256(member(archive, raw)).hexdigest()
|
|
require((kind, identity) in actions, 'Unclassified package action: ' + path)
|
|
observed.append(dict(package=package.name, path=path, kind=kind, sha256=identity, phase='layer-build'))
|
|
packages.append(package)
|
|
transaction = handle.init_transaction()
|
|
try:
|
|
for package in packages:
|
|
transaction.add_pkg(package)
|
|
transaction.prepare()
|
|
require(not transaction.to_remove and {p.name: (p.version, p.arch) for p in transaction.to_add} == expected,
|
|
'Installation changed exact closure')
|
|
transaction.commit()
|
|
require(not errors, 'Required package action failed')
|
|
require({p.name: (p.version, p.arch) for p in handle.get_localdb().pkgcache} == expected,
|
|
'Installed package DB differs from lock')
|
|
finally:
|
|
transaction.release()
|
|
return dict(version=0, resolution_sha256=resolution_hash,
|
|
policy_sha256=hashlib.sha256(json.dumps(policy, sort_keys=True, separators=(',', ':')).encode()).hexdigest(),
|
|
actions=observed, root=str(target), database=str(database))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
require(len(sys.argv) == 7, 'Usage: install-overlay.py LOCK RECEIPT POLICY CACHE FRESH_RUN_TARGET NEW_RESULT')
|
|
values = [json.loads(Path(path).read_bytes()) for path in sys.argv[1:4]]
|
|
result = install(*values, Path(sys.argv[4]), Path(sys.argv[5]))
|
|
with Path(sys.argv[6]).open('x') as stream:
|
|
json.dump(result, stream, sort_keys=True, separators=(',', ':'))
|
|
stream.write('\n')
|