system/adapters/package-transaction.py

259 lines
14 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 local_file_policy(text):
"""Allow one unsigned local Host Extension in the same -U transaction.
Repository archives keep their detached .sig files, so Optional still verifies
present signatures; a local archive has no signature by design (D-115). The
service has already checked its exact bytes and .PKGINFO identity.
"""
updated, count = re.subn(r'(?m)^\s*LocalFileSigLevel\s*=.*$',
'LocalFileSigLevel = Optional', text)
if count == 0:
updated = re.sub(r'(?m)^\[options\]\s*$',
'[options]\nLocalFileSigLevel = Optional', updated, count=1)
require('LocalFileSigLevel = Optional' in updated,
'Could not relax the local package signature policy')
return updated
def kernel_headers(handle, databases, additions, modules_root=Path('/usr/lib/modules')):
"""Resolve DKMS build inputs against the target image, never uname or live repos."""
localdb = handle.get_localdb()
if not any(pkg.name == 'dkms' for pkg in additions) and localdb.get_pkg('dkms') is None:
return []
headers = {}
kernels = 0
for modules in sorted(modules_root.iterdir()):
if not (modules / 'vmlinuz').is_file():
continue
kernels += 1
pkgbase = (modules / 'pkgbase').read_text().strip()
require(re.fullmatch(r'[a-zA-Z0-9_+-]+', pkgbase), 'Invalid target kernel package base')
kernel = localdb.get_pkg(pkgbase)
require(kernel is not None, 'Target kernel absent from image package database')
name = pkgbase + '-headers'
installed = localdb.get_pkg(name)
if installed is not None:
require(installed.version == kernel.version, 'Installed headers differ from target kernel')
continue
candidate = next((pkg for db in databases if (pkg := db.get_pkg(name)) is not None), None)
require(candidate is not None and candidate.version == kernel.version,
'Exact target kernel headers unavailable in selected snapshot: ' + name + '=' + kernel.version)
headers[name] = candidate
require(kernels > 0, 'No target kernel for DKMS')
return list(headers.values())
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')
if mode != 'install':
additions = list(transaction.to_add)
headers = kernel_headers(handle, databases, additions)
if headers:
# Re-prepare the complete closure with exact kernel build inputs.
# Explicit user requests remain separate in the durable plan.
#
# release() invalidates every package the transaction owns, and
# pyalpm holds no reference that would keep them alive: a package
# loaded from a local archive is freed with it. Reusing those
# objects in the second transaction made libalpm sort a freed
# package and crash in strcmp (packages named NULL), so the new
# transaction is rebuilt from the durable request rows.
requested = {pkg.name: pkg.version for pkg in additions}
header_rows = [(pkg.name, pkg.version, pkg.arch) for pkg in headers]
transaction.release()
transaction = handle.init_transaction(downloadonly=(mode == 'download'), needed=False)
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')
transaction.add_pkg(handle.load_pkg(str(path), check_sig=0))
continue
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)
for name, version, architecture in header_rows:
if name in requested:
require(requested[name] == version, 'Requested headers differ from target kernel')
continue
pkg = next((db.get_pkg(name) for db in databases if db.get_pkg(name) is not None), None)
require(pkg is not None and (pkg.version, pkg.arch) == (version, architecture),
'Kernel headers changed between transaction passes')
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':
# pyalpm does not expose libalpm hook-directory configuration. Its
# default handle ignores /etc/pacman.d/hooks masks, so using commit()
# here would run DKMS/mkinitcpio prematurely. Native pacman honors
# the staging config and masks, using the exact already-checked files.
transaction.release()
transaction = None
# A single -U transaction applies one local-file policy. Repository
# signatures are present and verified; the local extension is
# intentionally unsigned. Never touch the image's /etc/pacman.conf.
install_config = Path('/run/archipelago-package-install.conf')
install_config.parent.mkdir(parents=True, exist_ok=True)
install_config.write_text(local_file_policy(Path('/etc/pacman.conf').read_text()))
subprocess.run(['pacman', '--config', str(install_config),
'--dbpath', '/usr/lib/archipelago/package-db',
'--cachedir', '/inputs', '-U', '--noconfirm', '--',
*[str(Path('/inputs', item['filename'])) for item in resolved]],
check=True, stdout=sys.stderr, stderr=sys.stderr)
require(not action_errors, 'Required package action failed')
print(json.dumps(dict(version=1, resolved=resolved), separators=(',', ':')))
finally:
if transaction is not None:
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)