Integrate D-Bus managed overlay build and composition sources

This commit is contained in:
Pavel Isaev 2026-11-08 02:06:35 +03:00
parent d9eba7d716
commit 9c4f4764e1
10 changed files with 929 additions and 0 deletions

105
MANAGED-OVERLAYS.md Normal file
View file

@ -0,0 +1,105 @@
# Managed Overlay producer checkpoint
`build-overlay.sh` now sequences resolve/download in a network-enabled private
bootstrap, then install/capture/pack in a separate private-network nspawn. Offline
also isolates the first phase. Installation/capture share one /run lifetime;
locks, receipts, logs and final artifact remain in the protected job directory.
An OSTree commit/ref and result receipt are produced only after successful packing.
`system/src/service/overlay_build.rs` supplies the supervised invocation and
embedded adapters. PrepareSet/PrepareUpdate now call it through authenticated source
extraction and a private bootstrap. The target base must supply reviewed policy at
`/usr/lib/archipelago/hook-policy/overlay-build.json`; its producer and build-tool
binding remain unfinished, so ordinary current bases fail this prerequisite. Explicit
manifest actions are rejected until their locked executor exists, not ignored.
System/builder compile-only and driver bash syntax passed on yabloko; the driver
has not been executed. Network isolation and final output require pipeline evidence.
`adapters/capture-overlay.py` connects an installation result to the packer. It
verifies the resolution hash and installed package set/versions, indexes local DB
records once, and selects each package's files without rescanning or copying the
entire root. Vendor defaults map from installation `/etc` to artifact `/usr/etc`.
The packer accepts a private `path_sources` map for these shared-root inputs;
otherwise its separate-package-root mode remains available. Original ALPM bytes
are retained. Unowned installation outputs do not become package payload merely
because they exist; generated outputs need explicit finalization provenance.
Absent paths, canonical alias collisions and new lifecycle paths still require
their explicit adapters. This does not silently make arbitrary packages supported.
The normal-pipeline fixture covers capture→pack and exclusion of an unowned file.
`adapters/install-overlay.py` is the private offline installation phase (embedded
as `builder::overlay::INSTALLER`). It consumes the resolved lock, download receipt,
an authenticated profile's action policy and retained archives, creating a fresh
`/run` target inside the layer sandbox. It checks receipt/closure, archive checksums,
detached signature identity and libalpm signature validation before installation.
It inventories `.INSTALL`/ALPM hooks before committing; every observed action must
have an exact hash and `layer-build` classification. Unknown actions and hook
overrides fail. Native ALPM transaction dependencies/triggers apply; logged errors
or failure warnings fail the result even if commit returns success.
Policy v0 is `{version:0,actions:[{kind:scriptlet|hook,sha256,phase:layer-build}]}`.
This is an internal executor input, not blanket approval of existing package
scripts. The caller must bind policy provenance. Other lifecycle phases need
explicit adapters rather than relabeling their actions as layer-build.
The fresh target may lack build tools needed by scripts: locked build dependencies
and target preparation are still required in orchestration. No runtime success or
general package conformance is claimed. Installation result records root/database,
resolution hash, policy hash and observed action identities.
Python syntax and builder compile-only passed on yabloko; installation has not run.
`adapters/download-overlay.py` implements the exact-closure download phase inside
the layer sandbox. It reconstructs the resolver's empty local DB from pinned sync
DBs and checks repository bytes/order, package versions/architectures/filenames,
archive checksums and detached signature identities before the transaction.
Only libalpm download-only commit is used; no package installation runs.
All retained archives are checksum-checked and loaded with mandatory signature
verification, including offline/warm-cache use. Offline requires every archive
already present and never commits a download transaction. A receipt binds the
resolution content hash, snapshot and verified archive hashes.
Invocation: `download-overlay.py LOCK FRESH_RUN_WORKSPACE CACHE NEW_RECEIPT [--offline]`.
The resolver script must be installed alongside it; caller owns the sandbox,
cache and network isolation. Runtime libalpm/network acceptance is still pending.
`src/overlay.rs` exposes canonical YAML normalization via contracts::layer and
embeds the private resolver/packer scripts for isolated worker invocation.
`adapters/resolve-overlay.py` resolves runtime constraints with libalpm using a
fresh empty local DB and copied pinned sync DBs inside the selected base sandbox.
It never refreshes repositories or commits an installation transaction. Output
retains repository DB hashes/order, archive checksums/signatures, exact dependency
names and requirement/provider bindings. Provider lookups use a name index.
The script requires the layer-sandbox marker and matching snapshot identity;
these are execution guards, not substitutes for caller-side signature validation.
Compile-only builder and resolver Python syntax passed on yabloko. libalpm runtime
execution has not yet been exercised in the normal pipeline.
`adapters/indexed-overlay.py` is the private offline packaging phase for the
generic overlay builder. It accepts a structurally validated normalized Layer v1
manifest and protected prepared inputs. It does not implement package resolution,
signature admission, installation or hook execution.
Invocation: `indexed-overlay.py COMPOSER_ADAPTER_DIR MANIFEST_JSON REQUEST_JSON NEW_OUTPUT`.
The request has version 0, snapshot_id, source_root and packages. Each package has
name/version/architecture, archive/archive_sha256, exact resolved dependency names,
an adapted immutable root and an original ALPM record directory. The caller must
authenticate the archives and bind the resolution to the selected snapshot first.
The packer hashes retained archives/records/payload objects, constructs contribution
identities and namespaced package trees, copies authored content with declared
metadata, emits indexes/lock and runs the existing artifact checker. It preserves
original ALPM bytes. Persistent/boot payload without a lifecycle adapter is rejected.
Payload writes reject symlink ancestors; no live host mutation is performed.
Remaining integration: worker invocation of normalization/resolution,
worker invocation and runtime validation of download/install, profile action policy
binding, build-tool closure, non-build lifecycle actions, capture invocation,
runtime/lifecycle adapters, source retention,
OSTree commit creation and update worker orchestration. This file is not evidence
that rebuild-on-update works or that hardware overlays are supported.
`tests/indexed_overlay.py` is registered in the normal release source checks;
fixtures cover snapshot rebinding and symlink escape rejection. Only Python syntax
has been checked on yabloko; runtime fixtures have not run.
The packer now accepts optional `requirement_bindings` from the resolver and
retains them in the lock. The checker verifies complete declaration/provider
accounting; a fixture covers a version-constrained virtual requirement and a
mismatched constraint. It does not replace runtime signature/provider checks.

55
adapters/build-overlay.sh Normal file
View file

@ -0,0 +1,55 @@
#!/bin/bash
# Private worker driver. All paths/identities are selected by the daemon/builder.
set -euo pipefail
export LC_ALL=C
work=$1
bootstrap=$2
snapshot=$3
repository=$4
reference=$5
offline=${6:-0}
[[ $work == /* && $bootstrap == /* && $repository == /* ]]
[[ $snapshot =~ ^[0-9a-f]{64}$ && $reference =~ ^service/overlay-builds/[a-zA-Z0-9_-]+$ ]]
[[ $offline == 0 || $offline == 1 ]]
[[ -d $work && ! -L $work && -d $bootstrap && ! -L $bootstrap ]]
[[ -f $work/manifest.json && -f $work/policy.json && -d $work/sources && -d $work/adapters ]]
[[ ! -e $work/result.json && ! -e $work/artifact && ! -e $work/resolution.json ]]
mkdir -p "$work/cache" "$work/logs"
printf 'isolated layer builder\n' > "$work/sandbox-marker"
network=(--resolv-conf=replace-host)
if [[ $offline == 1 ]]; then network=(--private-network --resolv-conf=off); fi
common=(--quiet --settings=no --register=no "--directory=$bootstrap"
"--bind=$work:/job" "--bind-ro=$work/sandbox-marker:/run/archipelago-layer-sandbox")
# Bootstrap is a private checkout of the authenticated new base, never live /usr.
# Scripts are copied into the job by the supervised caller, not fetched at runtime.
systemd-nspawn "${common[@]}" "${network[@]}" /bin/bash -euo pipefail -c '
python3 -I -B /job/adapters/resolve-overlay.py /job/manifest.json "$1" /run/overlay-resolve /job/resolution.json
args=()
if [[ $2 == 1 ]]; then args+=(--offline); fi
python3 -I -B /job/adapters/download-overlay.py /job/resolution.json /run/overlay-download /job/cache /job/download.json "${args[@]}"
' overlay-download "$snapshot" "$offline" > "$work/logs/download.log" 2>&1
# Installation and packing share one private /run lifecycle. No build result
# contains these transient paths: the indexed artifact uses relative namespaces.
systemd-nspawn "${common[@]}" --private-network --resolv-conf=off /bin/bash -euo pipefail -c '
python3 -I -B /job/adapters/install-overlay.py /job/resolution.json /job/download.json /job/policy.json /job/cache /run/overlay-target /job/installation.json
python3 -I -B /job/adapters/capture-overlay.py /job/adapters /job/resolution.json /job/installation.json /job/cache /job/sources /job/packing.json
python3 -I -B /job/adapters/indexed-overlay.py /job/adapters /job/manifest.json /job/packing.json /job/artifact > /job/packed.json
' > "$work/logs/install.log" 2>&1
# No ref is updated unless all preceding required steps succeeded.
commit=$(ostree --repo="$repository" commit --branch="$reference" --tree="dir=$work/artifact" \
--add-metadata-string="archipelago.snapshot=$snapshot")
[[ $commit =~ ^[0-9a-f]{64}$ ]]
python3 -I -B - "$work" "$commit" "$snapshot" <<'PY'
import json
from pathlib import Path
import sys
work = Path(sys.argv[1])
packed = json.loads((work / 'packed.json').read_bytes())
with (work / 'result.json').open('x') as stream:
json.dump(dict(version=0, commit=sys.argv[2], snapshot_id=sys.argv[3],
lock_sha256=packed['lock_sha256']), stream, sort_keys=True)
stream.write('\n')
PY

View file

@ -0,0 +1,82 @@
#!/usr/bin/env python3
"""Select installed package contributions by ALPM ownership, without tree copies.
Inputs are protected outputs of the isolated builder. This does not authenticate
an installation receipt or replace the subsequent artifact consistency checker.
"""
import hashlib
import importlib.util
import json
from pathlib import Path
import stat
import sys
def capture(checker, lock, installed, cache, source_root):
require = checker.require
expected_hash = hashlib.sha256(json.dumps(lock, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
require(installed['version'] == 0 and installed['resolution_sha256'] == expected_hash, 'Installation resolution mismatch')
root = Path(installed['root'])
database = Path(installed['database'])
for path in (root, database, cache, source_root):
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 capture input')
require(database == root / 'var/lib/pacman', 'Unexpected installation DB location')
records = {}
local = database / 'local'
require(local.is_dir() and not local.is_symlink(), 'Invalid local database')
for entry in sorted(local.iterdir()):
if entry.name == 'ALPM_DB_VERSION':
continue
require(stat.S_ISDIR(entry.lstat().st_mode), 'Invalid local package record')
desc = entry / 'desc'
require(stat.S_ISREG(desc.lstat().st_mode), 'Invalid original desc')
fields = checker.alpm_fields(desc.read_bytes())
names = fields.get('%NAME%', [])
require(len(names) == 1 and names[0] not in records, 'Duplicate installed package')
records[names[0]] = (entry, fields)
require(set(records) == {row['name'] for row in lock['packages']}, 'Installed package set differs from resolution')
packages = []
for row in lock['packages']:
record, fields = records[row['name']]
require(fields.get('%VERSION%') == [row['version']] and fields.get('%ARCH%') == [row['architecture']],
'Installed package identity differs from resolution')
file_list = record / 'files'
require(stat.S_ISREG(file_list.lstat().st_mode), 'Invalid original file list')
paths = checker.alpm_fields(file_list.read_bytes()).get('%FILES%', [])
sources = {}
for runtime in paths:
canonical = checker.image_path('/' + runtime.rstrip('/'))
require(canonical == '/usr' or (canonical.startswith('/usr/') and canonical != '/usr/local' and
not canonical.startswith('/usr/local/')), 'New package lifecycle path requires a named adapter: ' + runtime)
# The install root still has runtime /etc. Vendor-default relocation
# occurs in the layer output, never in the shared installation tree.
relative = canonical.removeprefix('/usr/') if canonical.startswith('/usr/etc/') else canonical.lstrip('/')
if canonical == '/usr/etc':
relative = 'etc'
checker.objects.safe_parent(root, checker.relative(relative))
require((root / relative).exists() or (root / relative).is_symlink(), 'Installed package path is absent: ' + runtime)
require(canonical not in sources, 'Aliased package paths require explicit accounting: ' + runtime)
sources[canonical] = relative
filename = row['filename']
require(filename and Path(filename).name == filename and filename not in ('.', '..'), 'Invalid archive filename')
packages.append(dict(name=row['name'], version=row['version'], architecture=row['architecture'],
archive=str(cache / filename), archive_sha256=row['archive_sha256'], dependencies=row['dependencies'],
root=str(root), record=str(record), path_sources=sources))
return dict(version=0, snapshot_id=lock['snapshot_id'], source_root=str(source_root),
packages=packages, requirement_bindings=lock['requirements'])
if __name__ == '__main__':
if len(sys.argv) != 7:
raise SystemExit('Usage: capture-overlay.py COMPOSER_ADAPTER_DIR LOCK INSTALLED CACHE SOURCES NEW_REQUEST')
spec = importlib.util.spec_from_file_location('artifact', Path(sys.argv[1]) / 'artifact.py')
checker = importlib.util.module_from_spec(spec)
spec.loader.exec_module(checker)
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 = capture(checker, read(sys.argv[2]), read(sys.argv[3]), 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')

View file

@ -0,0 +1,106 @@
#!/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')

190
adapters/indexed-overlay.py Normal file
View file

@ -0,0 +1,190 @@
#!/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'])))

130
adapters/install-overlay.py Normal file
View file

@ -0,0 +1,130 @@
#!/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')

123
adapters/resolve-overlay.py Normal file
View file

@ -0,0 +1,123 @@
#!/usr/bin/env python3
"""Private isolated snapshot resolver. No package install or metadata refresh.
Caller validates the manifest with contracts::layer and binds the signed base
snapshot. Execute inside the layer build sandbox, with a fresh runtime workspace.
"""
import base64
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import sys
def require(value, message):
if not value:
raise ValueError(message)
def expression(item):
require(isinstance(item, dict) and set(item) <= {'name', 'constraint'} and 'name' in item,
'Invalid package requirement')
name = item['name']
require(isinstance(name, str) and re.fullmatch(r'[A-Za-z0-9@._+\-]+', name), 'Invalid package name')
constraint = item.get('constraint', '')
require(isinstance(constraint, str) and (not constraint or
re.fullmatch(r'(?:>=|<=|=|>|<)[^\s<>=]+', constraint)), 'Invalid package constraint')
return name + constraint
def snapshot_handle(snapshot, architecture, workspace):
import pyalpm
from pycman.config import PacmanConfig
require(Path('/run/archipelago-layer-sandbox').is_file(), 'Layer sandbox marker required')
require(re.fullmatch('[0-9a-f]{64}', snapshot), 'Invalid snapshot identity')
require(Path('/usr/lib/archipelago/snapshot').read_text().strip() == snapshot, 'Snapshot binding mismatch')
require(architecture == os.uname().machine, 'Overlay architecture mismatch')
require(workspace.is_absolute() and workspace.parent == Path('/run') and
not workspace.exists() and not workspace.is_symlink(), 'Fresh isolated workspace required')
workspace.mkdir(mode=0o700)
database = workspace / 'db'
(database / 'local').mkdir(parents=True)
(database / 'sync').mkdir()
# An empty local DB makes this an independent layer closure, not a delta
# whose dependencies happen to be installed in the build machine.
config = PacmanConfig(conf='/etc/pacman.conf')
handle = pyalpm.Handle('/', str(database))
handle.arch = [architecture]
handle.gpgdir = '/etc/pacman.d/gnupg'
databases = []
hashes = {}
for name in config.repos:
require(re.fullmatch(r'[A-Za-z0-9_.\-]+', name), 'Invalid repository name')
source = Path('/usr/lib/archipelago/package-db/sync') / (name + '.db')
require(source.is_file() and not source.is_symlink(), 'Missing pinned repository DB')
with source.open('rb') as stream:
hashes[name] = hashlib.file_digest(stream, 'sha256').hexdigest()
shutil.copyfile(source, database / 'sync' / (name + '.db'))
db = handle.register_syncdb(name, pyalpm.SIG_PACKAGE)
db.servers = [url.replace('$repo', name).replace('$arch', architecture) for url in config.repos[name]]
databases.append(db)
return handle, databases, [dict(name=name, sha256=hashes[name]) for name in config.repos]
def resolve(manifest, snapshot, workspace):
import pyalpm
require(manifest['spec']['type'] == 'overlay', 'Expected overlay manifest')
requirements = manifest['spec'].get('packages', {}).get('runtime', [])
requested = [expression(item) for item in requirements]
require(len(set(item['name'] for item in requirements)) == len(requirements), 'Duplicate package requirement')
handle, databases, repositories = snapshot_handle(snapshot, manifest['spec']['architecture'], workspace)
transaction = handle.init_transaction()
try:
bindings = []
chosen = set()
for requirement in requested:
package = pyalpm.find_dbs_satisfier(databases, requirement)
require(package is not None, 'Unsatisfied snapshot requirement: ' + requirement)
bindings.append(dict(requirement=requirement, package=package.name))
if package.name not in chosen:
transaction.add_pkg(package)
chosen.add(package.name)
transaction.prepare()
require(not transaction.to_remove, 'Independent layer resolution unexpectedly removes packages')
packages = sorted(transaction.to_add, key=lambda pkg: pkg.name)
providers = {}
for package in packages:
keys = {package.name} | {re.split(r'[<>=]', value, maxsplit=1)[0] for value in package.provides}
for key in keys:
providers.setdefault(key, []).append(package)
rows = []
for package in packages:
require(package.db is not None and re.fullmatch('[0-9a-f]{64}', package.sha256sum or ''),
'Snapshot package lacks checksum')
require(package.filename and Path(package.filename).name == package.filename and package.base64_sig,
'Snapshot package lacks archive/signature identity')
base64.b64decode(package.base64_sig, validate=True)
dependencies = []
for dependency in package.depends:
name = re.split(r'[<>=]', dependency, maxsplit=1)[0]
provider = pyalpm.find_satisfier(providers.get(name, []), dependency)
require(provider is not None, 'Incomplete resolved dependency closure')
dependencies.append(dict(requirement=dependency, package=provider.name))
rows.append(dict(name=package.name, version=package.version, architecture=package.arch,
repository=package.db.name, filename=package.filename, archive_sha256=package.sha256sum,
signature=package.base64_sig, dependencies=sorted(set(row['package'] for row in dependencies)),
dependency_bindings=dependencies))
return dict(version=0, snapshot_id=snapshot, architecture=manifest['spec']['architecture'],
repositories=repositories,
requirements=bindings, packages=rows)
finally:
transaction.release()
if __name__ == '__main__':
require(len(sys.argv) == 5, 'Usage: resolve-overlay.py MANIFEST_JSON SNAPSHOT_ID FRESH_RUN_WORKSPACE NEW_RESULT')
manifest = json.loads(Path(sys.argv[1]).read_bytes())
result = resolve(manifest, sys.argv[2], Path(sys.argv[3]))
with Path(sys.argv[4]).open('x') as stream:
json.dump(result, stream, sort_keys=True, separators=(',', ':'))
stream.write('\n')

View file

@ -1,4 +1,6 @@
//! Experimental x86_64 Core ISO profile. Native tools execute inside nspawn.
pub mod overlay;
pub fn build_iso_script() -> String {
render_iso(false)
}

28
src/overlay.rs Normal file
View file

@ -0,0 +1,28 @@
//! Private generic overlay build phases; invocation belongs to the isolated worker.
pub const RESOLVER: &str = include_str!("../adapters/resolve-overlay.py");
pub const DOWNLOADER: &str = include_str!("../adapters/download-overlay.py");
pub const INSTALLER: &str = include_str!("../adapters/install-overlay.py");
pub const CAPTURE: &str = include_str!("../adapters/capture-overlay.py");
pub const DRIVER: &str = include_str!("../adapters/build-overlay.sh");
/// Files copied into a protected build workspace by the supervised worker.
/// Composer's artifact.py/materialize.py must be supplied alongside these.
pub fn adapters() -> [(&'static str, &'static str); 6] {
[("resolve-overlay.py", RESOLVER), ("download-overlay.py", DOWNLOADER),
("install-overlay.py", INSTALLER), ("capture-overlay.py", CAPTURE),
("indexed-overlay.py", PACKER), ("build-overlay.sh", DRIVER)]
}
pub const PACKER: &str = include_str!("../adapters/indexed-overlay.py");
/// Normalize YAML using the canonical Layer v1 validator before any build action.
pub fn normalize(source: &str) -> Result<String, String> {
let manifest = archipelago_contracts::layer::validate(source)?;
if manifest["spec"]["type"] != "overlay" {
return Err("Managed Overlay builder requires an overlay manifest".into());
}
if manifest["spec"]["actions"].as_array().is_some_and(|actions| !actions.is_empty()) {
return Err("Declared overlay actions require the locked action executor".into());
}
Ok(manifest.to_string())
}

108
tests/indexed_overlay.py Normal file
View file

@ -0,0 +1,108 @@
"""Offline producer fixtures; executed only by normal release source checks."""
import importlib.util
import gzip
import hashlib
from pathlib import Path
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
spec = importlib.util.spec_from_file_location('producer', ROOT / 'builder/adapters/indexed-overlay.py')
producer = importlib.util.module_from_spec(spec)
spec.loader.exec_module(producer)
checker = producer.load_checker(ROOT / 'composer')
capture_spec = importlib.util.spec_from_file_location('capture', ROOT / 'builder/adapters/capture-overlay.py')
capture = importlib.util.module_from_spec(capture_spec)
capture_spec.loader.exec_module(capture)
class Producer(unittest.TestCase):
def test_capture_selects_owned_defaults_without_copying_unowned_files(self):
import json
with tempfile.TemporaryDirectory() as temp:
work = Path(temp)
root = work / 'installed'
record = root / 'var/lib/pacman/local/example-1-1'
record.mkdir(parents=True)
(root / 'etc').mkdir()
(root / 'etc/example').write_bytes(b'default')
(root / 'etc/unowned').write_bytes(b'not package payload')
(record / 'desc').write_bytes(b'%NAME%\nexample\n\n%VERSION%\n1-1\n\n%ARCH%\nany\n\n')
(record / 'files').write_bytes(b'%FILES%\netc/example\n\n')
(record / 'mtree').write_bytes(gzip.compress(b'#mtree\n', mtime=0))
(work / 'cache').mkdir()
(work / 'source').mkdir()
archive = work / 'cache/example.pkg.tar.zst'
archive.write_bytes(b'fixture')
lock = dict(snapshot_id='a' * 64, requirements=[dict(requirement='example', package='example')],
packages=[dict(name='example', version='1-1', architecture='any', dependencies=[],
filename=archive.name, archive_sha256=hashlib.sha256(archive.read_bytes()).hexdigest())])
installed = dict(version=0, root=str(root), database=str(root / 'var/lib/pacman'),
resolution_sha256=hashlib.sha256(json.dumps(lock, sort_keys=True, separators=(',', ':')).encode()).hexdigest())
request = capture.capture(checker, lock, installed, work / 'cache', work / 'source')
self.assertEqual(request['packages'][0]['path_sources'], {'/usr/etc/example': 'etc/example'})
manifest = dict(apiVersion='archipelago/v1', kind='Layer', metadata=dict(name='example', version='1'),
spec=dict(type='overlay', architecture='x86_64', packages=dict(runtime=[dict(name='example')])))
result = producer.pack(checker, manifest, request, work / 'output')
self.assertEqual([row['path'] for row in result['objects']], ['/usr/etc/example'])
self.assertEqual((root / 'etc/unowned').read_bytes(), b'not package payload')
def test_virtual_requirement_retains_the_resolved_provider(self):
with tempfile.TemporaryDirectory() as temp:
work = Path(temp)
for name in ('source', 'root', 'record'):
(work / name).mkdir()
archive = work / 'provider.pkg.tar.zst'
archive.write_bytes(b'fixture authenticated archive input')
(work / 'record/desc').write_bytes(b'%NAME%\nprovider\n\n%VERSION%\n1-1\n\n%ARCH%\nany\n\n%PROVIDES%\nvirtual=1\n\n')
(work / 'record/files').write_bytes(b'%FILES%\n\n')
(work / 'record/mtree').write_bytes(gzip.compress(b'#mtree\n', mtime=0))
manifest = dict(apiVersion='archipelago/v1', kind='Layer', metadata=dict(name='example', version='1'),
spec=dict(type='overlay', architecture='x86_64', packages=dict(runtime=[dict(name='virtual', constraint='>=1')])))
request = dict(version=0, snapshot_id='a' * 64, source_root=str(work / 'source'),
requirement_bindings=[dict(requirement='virtual>=1', package='provider')], packages=[dict(
name='provider', version='1-1', architecture='any', archive=str(archive),
archive_sha256=hashlib.sha256(archive.read_bytes()).hexdigest(), dependencies=[],
root=str(work / 'root'), record=str(work / 'record'))])
result = producer.pack(checker, manifest, request, work / 'output')
self.assertEqual(result['lock']['requirements'], ['provider'])
self.assertEqual(result['lock']['requirement_bindings'], request['requirement_bindings'])
request['requirement_bindings'][0]['requirement'] = 'virtual>=2'
with self.assertRaisesRegex(ValueError, 'requirement binding'):
producer.pack(checker, manifest, request, work / 'mismatch')
def test_rebuild_binds_new_snapshot_and_same_authored_intent(self):
with tempfile.TemporaryDirectory() as temp:
work = Path(temp)
source = work / 'source'
source.mkdir()
(source / 'example').write_bytes(b'vendor configuration\n')
manifest = dict(apiVersion='archipelago/v1', kind='Layer', metadata=dict(name='example', version='1'),
spec=dict(type='overlay', architecture='x86_64', files=[dict(path='/etc/example',
source='example', mode='0644', owner='root', group='root')]))
request = dict(version=0, snapshot_id='a' * 64, source_root=str(source), packages=[])
first = producer.pack(checker, manifest, request, work / 'first')
request['snapshot_id'] = 'b' * 64
second = producer.pack(checker, manifest, request, work / 'second')
self.assertNotEqual(first['lock_sha256'], second['lock_sha256'])
self.assertEqual(first['objects'], second['objects'])
self.assertEqual((work / 'second/payload/files/root/usr/etc/example').read_bytes(), b'vendor configuration\n')
def test_authored_symlink_cannot_redirect_a_later_write(self):
with tempfile.TemporaryDirectory() as temp:
work = Path(temp)
source = work / 'source'
source.mkdir()
(source / 'example').write_bytes(b'payload')
outside = work / 'outside'
outside.mkdir()
manifest = dict(spec=dict(type='overlay', architecture='x86_64', files=[
dict(path='/usr/share/escape', type='symlink', target=str(outside), mode='0777', owner='root', group='root'),
dict(path='/usr/share/escape/example', source='example', mode='0644', owner='root', group='root')]))
with self.assertRaisesRegex(ValueError, 'payload ancestor'):
producer.pack(checker, manifest, dict(version=0, snapshot_id='a' * 64, source_root=str(source), packages=[]), work / 'output')
self.assertFalse((outside / 'example').exists())
if __name__ == '__main__':
unittest.main()