builder/adapters/indexed-overlay.py

190 lines
10 KiB
Python

#!/usr/bin/env python3
"""Private offline layer packer, after isolated resolve/install/action adaptation.
The caller validates Layer v1 and authenticates the pinned package inputs. This
program does not resolve packages, install archives, or grant trust to a commit.
Request paths refer to protected builder workspaces, never D-Bus client paths.
"""
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import shutil
import stat
import sys
def load_checker(directory):
spec = importlib.util.spec_from_file_location('artifact', directory / 'artifact.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def encode(value):
return (json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=False) + '\n').encode()
def pack(checker, manifest, request, output):
require = checker.require
checker.field_set(request, ['version', 'snapshot_id', 'source_root', 'packages'], ['requirement_bindings'])
require(checker.version(request['version']) and checker.digest(request['snapshot_id']), 'Invalid build request')
require(manifest['spec']['type'] == 'overlay' and manifest['spec']['architecture'] == 'x86_64', 'Expected x86_64 overlay')
require(isinstance(request['packages'], list), 'Missing resolved package contributions')
def directory(value):
path = Path(value)
require(path.is_absolute() and path.is_dir() and not path.is_symlink() and
all(not parent.is_symlink() for parent in path.parents), 'Invalid protected build directory')
return path
directory(output.parent)
require(not output.exists() and not output.is_symlink(), 'Layer output already exists')
source_root = directory(request['source_root'])
require(output != source_root and source_root not in output.parents, 'Output inside source tree')
prepared = []
names = set()
# Validate every package before creating an artifact directory.
for package in request['packages']:
checker.field_set(package, ['name', 'version', 'architecture', 'archive', 'archive_sha256',
'dependencies', 'root', 'record'], ['path_sources'])
name = package['name']
require(isinstance(name, str) and name and name not in names, 'Duplicate package contribution')
names.add(name)
root = directory(package['root'])
record = directory(package['record'])
require(root != output and root not in output.parents and record not in output.parents, 'Output overlaps package input')
archive = Path(package['archive'])
require(archive.is_absolute() and all(not parent.is_symlink() for parent in archive.parents) and
stat.S_ISREG(archive.lstat().st_mode), 'Invalid retained archive')
with archive.open('rb') as stream:
require(hashlib.file_digest(stream, 'sha256').hexdigest() == package['archive_sha256'], 'Archive checksum mismatch')
records = {}
for filename in ('desc', 'files', 'mtree'):
path = record / filename
require(stat.S_ISREG(path.lstat().st_mode) and path.stat().st_size <= 16 * 1024 * 1024, 'Invalid ALPM record')
records[filename] = path.read_bytes()
fields = checker.alpm_fields(records['desc'])
for field, expected in [('%NAME%', name), ('%VERSION%', package['version']), ('%ARCH%', package['architecture'])]:
require(fields.get(field) == [expected], 'Original package identity mismatch')
objects = []
sources = {}
if 'path_sources' in package:
require(isinstance(package['path_sources'], dict), 'Invalid package path selection')
for target, source in package['path_sources'].items():
checker.objects.relative(target)
relative = checker.relative(source)
checker.objects.safe_parent(root, relative)
sources[target] = relative
else:
for parent, directories, files in os.walk(root, followlinks=False):
for entry in sorted(directories + files):
relative = (Path(parent) / entry).relative_to(root)
sources['/' + relative.as_posix()] = relative
for target, relative in sorted(sources.items()):
path = root / relative
# /usr is structural; contributed descendants carry metadata.
if target == '/usr':
require(stat.S_ISDIR(path.lstat().st_mode), 'Invalid package /usr')
continue
require(target.startswith('/usr/') and target != '/usr/local' and not target.startswith('/usr/local/'),
'Package lifecycle payload requires an explicit adapter')
objects.append(dict(path=target, object=checker.objects.identity(path)))
objects.sort(key=lambda row: row['path'])
contribution = dict(name=name, version=package['version'], architecture=package['architecture'],
archive_sha256=package['archive_sha256'], dependencies=sorted(package['dependencies']),
alpm={key: hashlib.sha256(raw).hexdigest() for key, raw in records.items()}, objects=objects)
# Identity serialization matches artifact.py; it deliberately has no LF.
identity = hashlib.sha256(json.dumps(contribution, sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode()).hexdigest()
prepared.append((package, root, records, objects, identity, sources))
output.mkdir(mode=0o700)
(output / 'metadata').mkdir()
(output / 'payload').mkdir()
rows = []
packages = []
def copy_object(source, destination, value):
current = output
for part in destination.relative_to(output).parts[:-1]:
current /= part
if not current.exists() and not current.is_symlink():
current.mkdir()
require(stat.S_ISDIR(current.lstat().st_mode), 'Symlink or non-directory payload ancestor')
require(not destination.exists() and not destination.is_symlink(), 'Duplicate payload destination')
if value['kind'] == 'directory':
destination.mkdir()
elif value['kind'] == 'symlink':
destination.symlink_to(value['target'])
else:
shutil.copyfile(source, destination, follow_symlinks=False)
checker.objects.metadata(destination, value)
for package, root, records, objects, identity, sources in prepared:
prefix = 'payload/packages/' + identity + '/root'
# Parents must precede children, independently of walk order.
for row in sorted(objects, key=lambda row: (row['path'].count('/'), row['path'])):
relative = checker.objects.relative(row['path'])
destination = output / prefix / relative
copy_object(root / sources[row['path']], destination, row['object'])
rows.append(dict(source=prefix + row['path'], path=row['path'], package=identity, object=row['object']))
record_path = 'metadata/alpm/' + identity
(output / record_path).mkdir(parents=True)
for filename, raw in records.items():
(output / record_path / filename).write_bytes(raw)
packages.append({key: package[key] for key in ('name', 'version', 'architecture', 'archive_sha256', 'dependencies')} |
dict(identity=identity, alpm=record_path))
authored_sources = {}
for entry in sorted(manifest['spec'].get('files', []), key=lambda row: (row['path'].count('/'), row['path'])):
target = checker.image_path(entry['path'])
require(target.startswith('/usr/') and target != '/usr/local' and not target.startswith('/usr/local/'),
'Authored lifecycle payload requires an explicit adapter')
require(entry['owner'] == entry['group'] == 'root', 'Authored identity adapter required')
kind = entry.get('type', 'file')
value = dict(kind=kind, mode=int(entry['mode'], 8), uid=0, gid=0, xattrs={})
source = None
if kind == 'file':
relative = checker.relative(entry['source'])
checker.objects.safe_parent(source_root, relative)
source = source_root / relative
require(stat.S_ISREG(source.lstat().st_mode), 'Invalid authored source')
with source.open('rb') as stream:
value['sha256'] = hashlib.file_digest(stream, 'sha256').hexdigest()
authored_sources[entry['source']] = value['sha256']
elif kind == 'symlink':
value['target'] = entry['target']
checker.object_shape(value)
prefix = 'payload/files/root'
copy_object(source, output / prefix / checker.objects.relative(target), value)
rows.append(dict(source=prefix + target, path=target, package=None, object=value))
def write(name, value):
raw = encode(value)
(output / 'metadata' / name).write_bytes(raw)
return hashlib.sha256(raw).hexdigest()
manifest_hash = write('manifest.json', manifest)
packages_hash = write('packages.json', dict(version=0, packages=packages))
files_hash = write('files.json', dict(version=0, objects=rows))
lock = dict(version=0, manifest_sha256=manifest_hash, snapshot_id=request['snapshot_id'],
architecture=manifest['spec']['architecture'], packages_sha256=packages_hash, files_sha256=files_hash,
requirements=[entry['name'] for entry in manifest['spec'].get('packages', {}).get('runtime', [])],
authored_sources=authored_sources)
if 'requirement_bindings' in request:
lock['requirement_bindings'] = request['requirement_bindings']
lock['requirements'] = sorted({row['package'] for row in request['requirement_bindings']})
write('lock.json', lock)
return checker.check(output)
if __name__ == '__main__':
if len(sys.argv) != 5:
raise SystemExit('Usage: indexed-overlay.py COMPOSER_ADAPTER_DIR MANIFEST_JSON REQUEST_JSON NEW_OUTPUT')
checker = load_checker(Path(sys.argv[1]))
def read(path):
return json.loads(Path(path).read_bytes(), object_pairs_hook=checker.pairs,
parse_float=checker.reject_number, parse_constant=checker.reject_number)
result = pack(checker, read(sys.argv[2]), read(sys.argv[3]), Path(sys.argv[4]))
print(json.dumps(dict(version=0, lock_sha256=result['lock_sha256'])))