106 lines
5.4 KiB
Python
106 lines
5.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Download an exact resolved overlay closure inside the layer sandbox.
|
|
|
|
No install, action execution or repository refresh. Warm-cache inputs undergo
|
|
the same mandatory checksum/signature validation as downloaded archives.
|
|
"""
|
|
import base64
|
|
import hashlib
|
|
import importlib.util
|
|
import json
|
|
from pathlib import Path
|
|
import stat
|
|
import subprocess
|
|
import sys
|
|
|
|
spec = importlib.util.spec_from_file_location('resolver', Path(__file__).with_name('resolve-overlay.py'))
|
|
resolver = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(resolver)
|
|
require = resolver.require
|
|
|
|
|
|
def checksum(path):
|
|
with path.open('rb') as stream:
|
|
return hashlib.file_digest(stream, 'sha256').hexdigest()
|
|
|
|
|
|
def download(lock, workspace, cache, offline=False):
|
|
import pyalpm
|
|
require(type(lock.get('version')) is int and lock['version'] == 0, 'Invalid resolver protocol')
|
|
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 private archive cache')
|
|
handle, databases, repositories = resolver.snapshot_handle(lock['snapshot_id'], lock['architecture'], workspace)
|
|
require(repositories == lock['repositories'], 'Pinned repository bytes or order changed')
|
|
# This initializes only the disposable sandbox keyring from packaged trust.
|
|
for args in (['pacman-key', '--init'], ['pacman-key', '--populate', 'archlinux', 'archipelago']):
|
|
subprocess.run(args, check=True, stdout=sys.stderr, stderr=sys.stderr)
|
|
handle.cachedirs = [str(cache)]
|
|
handle.logfile = str(workspace / 'download.log')
|
|
errors = []
|
|
def log(level, message):
|
|
if level & pyalpm.LOG_ERROR:
|
|
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
|
|
by_repository = {db.name: db for db in databases}
|
|
rows = lock['packages']
|
|
require(isinstance(rows, list), 'Missing exact package closure')
|
|
expected = {}
|
|
filenames = set()
|
|
for row in rows:
|
|
require(row['name'] not in expected and row['filename'] not in filenames, 'Duplicate locked package/archive')
|
|
filename = row['filename']
|
|
require(filename and Path(filename).name == filename and filename not in ('.', '..'), 'Invalid locked archive name')
|
|
expected[row['name']] = row
|
|
filenames.add(filename)
|
|
path = cache / filename
|
|
for candidate in (path, cache / (filename + '.sig'), cache / (filename + '.part')):
|
|
if candidate.exists() or candidate.is_symlink():
|
|
require(stat.S_ISREG(candidate.lstat().st_mode), 'Invalid cached archive object')
|
|
if path.exists():
|
|
require(checksum(path) == row['archive_sha256'], 'Cached archive checksum mismatch')
|
|
elif offline:
|
|
raise ValueError('Required archive absent from offline cache')
|
|
transaction = handle.init_transaction(downloadonly=True)
|
|
try:
|
|
for row in rows:
|
|
db = by_repository.get(row['repository'])
|
|
package = db.get_pkg(row['name']) if db else None
|
|
require(package is not None and
|
|
(package.version, package.arch, package.filename, package.sha256sum, package.base64_sig) ==
|
|
(row['version'], row['architecture'], row['filename'], row['archive_sha256'], row['signature']),
|
|
'Snapshot package differs from resolved lock')
|
|
transaction.add_pkg(package)
|
|
transaction.prepare()
|
|
actual = {(pkg.name, pkg.version, pkg.arch) for pkg in transaction.to_add}
|
|
require(not transaction.to_remove and actual == {(row['name'], row['version'], row['architecture']) for row in rows},
|
|
'Download changed the resolved closure')
|
|
if not offline and rows:
|
|
transaction.commit()
|
|
require(not errors, 'Required download action failed')
|
|
for row in rows:
|
|
path = cache / row['filename']
|
|
require(stat.S_ISREG(path.lstat().st_mode) and checksum(path) == row['archive_sha256'], 'Downloaded archive mismatch')
|
|
signature = base64.b64decode(row['signature'], validate=True)
|
|
(cache / (row['filename'] + '.sig')).write_bytes(signature)
|
|
package = handle.load_pkg(str(path), check_sig=pyalpm.SIG_PACKAGE)
|
|
require((package.name, package.version, package.arch) == (row['name'], row['version'], row['architecture']),
|
|
'Verified archive identity mismatch')
|
|
finally:
|
|
transaction.release()
|
|
return dict(version=0, snapshot_id=lock['snapshot_id'],
|
|
resolution_sha256=hashlib.sha256(json.dumps(lock, sort_keys=True, separators=(',', ':')).encode()).hexdigest(),
|
|
archives=[dict(filename=row['filename'], sha256=row['archive_sha256']) for row in rows])
|
|
|
|
|
|
if __name__ == '__main__':
|
|
require(len(sys.argv) in (5, 6), 'Usage: download-overlay.py LOCK FRESH_RUN_WORKSPACE CACHE NEW_RECEIPT [--offline]')
|
|
require(len(sys.argv) == 5 or sys.argv[5] == '--offline', 'Unknown download option')
|
|
lock = json.loads(Path(sys.argv[1]).read_bytes())
|
|
receipt = download(lock, Path(sys.argv[2]), Path(sys.argv[3]), len(sys.argv) == 6)
|
|
with Path(sys.argv[4]).open('x') as stream:
|
|
json.dump(receipt, stream, sort_keys=True, separators=(',', ':'))
|
|
stream.write('\n')
|