system/adapters/package-transaction.py

157 lines
8 KiB
Python

"""Private isolated libalpm adapter; never run against the live root/database.
The Rust engine supplies exact inputs and owns authorization and durable state.
Resolve never commits; install uses only checksum-bound retained archives.
"""
import base64
import hashlib
import json
import os
from pathlib import Path
import re
import sys
import subprocess
import pyalpm
from pycman.config import PacmanConfig
def require(condition, message):
if not condition:
raise ValueError(message)
def digest(path):
with open(path, 'rb') as stream:
return hashlib.file_digest(stream, 'sha256').hexdigest()
def package(pkg, local=None):
if local:
return dict(name=pkg.name, version=pkg.version, architecture=pkg.arch,
source='local', checksum=local['checksum'], filename=local['filename'],
input_id=local['input_id'], size=Path('/inputs', local['filename']).stat().st_size)
require(pkg.db is not None and re.fullmatch('[0-9a-f]{64}', pkg.sha256sum or ''),
'Repository package lacks exact snapshot identity')
require(pkg.filename and Path(pkg.filename).name == pkg.filename, 'Invalid package archive name')
require(pkg.base64_sig, 'Repository package lacks mandatory signature')
return dict(name=pkg.name, version=pkg.version, architecture=pkg.arch,
source='repository', repository=pkg.db.name, checksum=pkg.sha256sum,
filename=pkg.filename, signature=pkg.base64_sig, size=pkg.size)
def main():
require(Path('/run/archipelago-package-sandbox').is_file(), 'Isolated package environment required')
require(len(sys.argv) == 3 and sys.argv[1] in ('catalog', 'resolve', 'download', 'install'), 'Invalid adapter mode')
mode = sys.argv[1]
request = json.loads(Path(sys.argv[2]).read_text())
require(request['version'] == 1, 'Unknown adapter request version')
if mode == 'download':
for args in (['pacman-key', '--init'], ['pacman-key', '--populate', 'archlinux', 'archipelago']):
subprocess.run(args, check=True, stdout=sys.stderr, stderr=sys.stderr)
config = PacmanConfig(conf='/etc/pacman.conf')
# This process runs inside the target checkout. Do not refresh its databases.
handle = pyalpm.Handle('/', '/usr/lib/archipelago/package-db')
handle.arch = [os.uname().machine]
handle.gpgdir = '/etc/pacman.d/gnupg'
handle.cachedirs = ['/inputs']
handle.logfile = '/var/log/archipelago-package-transaction.log'
handle.eventcb = lambda *_: None
handle.progresscb = lambda *_: None
action_errors = []
def log(level, message):
if level & (pyalpm.LOG_ERROR | pyalpm.LOG_WARNING):
print(message, file=sys.stderr)
if level & pyalpm.LOG_ERROR or re.search(r'fail(ed|ure)', message, re.I):
action_errors.append(message)
handle.logcb = log
databases = []
for name, servers in config.repos.items():
# DB bytes are bound by the signed base; package signatures remain required.
db = handle.register_syncdb(name, pyalpm.SIG_PACKAGE)
db.servers = [url.replace('$repo', name).replace('$arch', os.uname().machine) for url in servers]
databases.append(db)
if mode == 'catalog':
rows = []
seen = set()
for db in databases:
for pkg in sorted(db.pkgcache, key=lambda pkg: pkg.name):
if pkg.name in seen:
continue
seen.add(pkg.name)
row = package(pkg)
# The resolver reads signatures from the same pinned DB again;
# avoid duplicating large detached signatures in query catalogs.
row.pop('signature')
row['summary'] = (pkg.desc or '')[:256]
rows.append(row)
print(json.dumps(dict(version=1, packages=rows), separators=(',', ':')))
return
require(len(request['requests']) <= 256, 'Package request limit exceeded')
transaction = handle.init_transaction(downloadonly=(mode == 'download'), needed=False)
local = {}
try:
if mode == 'install':
for item in request['resolved']:
path = Path('/inputs', item['filename'])
require(path.parent == Path('/inputs') and path.is_file(), 'Invalid retained archive path')
require(digest(path) == item['checksum'], 'Retained archive checksum mismatch')
if item['source'] == 'repository':
require(Path(str(path) + '.sig').is_file(), 'Missing repository package signature')
pkg = handle.load_pkg(str(path), check_sig=pyalpm.SIG_PACKAGE if item['source'] == 'repository' else 0)
require((pkg.name, pkg.version, pkg.arch) == (item['name'], item['version'], item['architecture']), 'Archive identity mismatch')
transaction.add_pkg(pkg)
else:
for item in request['requests']:
if item['source'] == 'local':
path = Path('/inputs', item['filename'])
require(path.parent == Path('/inputs') and digest(path) == item['checksum'], 'Invalid retained local input')
pkg = handle.load_pkg(str(path), check_sig=0)
local[pkg.name] = item
else:
pkg = next((db.get_pkg(item['name']) for db in databases
if db.name == item['repository']), None)
require(pkg is not None, 'Requested package absent from selected snapshot')
require((pkg.version, pkg.sha256sum) == (item['version'], item['checksum']), 'Snapshot package identity changed')
transaction.add_pkg(pkg)
transaction.prepare()
require(not transaction.to_remove, 'Transaction would remove managed packages')
additions = list(transaction.to_add)
resolved = [package(pkg, local.get(pkg.name)) for pkg in additions] if mode != 'install' else request['resolved']
if mode == 'install':
actual = sorted((pkg.name, pkg.version, pkg.arch) for pkg in additions)
expected = sorted((item['name'], item['version'], item['architecture']) for item in resolved)
require(actual == expected, 'Execution changed the checked dependency closure')
managed = {pkg.name: pkg.version for pkg in handle.get_localdb().pkgcache}
overrides = {item['name']: item for item in request['requests'] if item.get('override') is True}
for item in resolved:
if item['name'] in managed:
override = overrides.get(item['name'])
require(override and override['replaces'] == item['name'] and override['reason'].strip(),
'Managed package replacement requires an explicit whole-package override')
if mode == 'download':
require(resolved == request['resolved'], 'Download changed the checked dependency closure')
transaction.commit()
for item in resolved:
path = Path('/inputs', item['filename'])
require(path.is_file() and digest(path) == item['checksum'], 'Downloaded package checksum mismatch')
if item['source'] == 'repository':
signature = base64.b64decode(item['signature'], validate=True)
Path(str(path) + '.sig').write_bytes(signature)
handle.load_pkg(str(path), check_sig=pyalpm.SIG_PACKAGE)
elif mode == 'install':
transaction.commit()
require(not action_errors, 'Required package action failed')
print(json.dumps(dict(version=1, resolved=resolved), separators=(',', ':')))
finally:
transaction.release()
if __name__ == '__main__':
try:
main()
except Exception as error:
# The worker stores a sanitized failure; private detailed errors must not
# accidentally expose repository credentials through public progress.
print('Package adapter failed: ' + type(error).__name__ + ': ' + str(error), file=sys.stderr)
sys.exit(1)