Integrate D-Bus managed overlay build and composition sources
This commit is contained in:
parent
64f33b616b
commit
4456f8b160
17 changed files with 2605 additions and 7 deletions
104
ARTIFACT-V0.md
Normal file
104
ARTIFACT-V0.md
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
# Private indexed artifact adapter v0
|
||||
|
||||
This is an implementation protocol under development, not a frozen artifact API.
|
||||
The caller authenticates the exact OSTree commit against its configured remote,
|
||||
creates a protected checkout, runs `artifact.py`, then passes its exact result to
|
||||
`artifact::read_checked`. The checker neither authenticates commits nor executes
|
||||
layer code. Rust validates the Layer v1 manifest before using the result.
|
||||
|
||||
## Metadata
|
||||
|
||||
All metadata is UTF-8 JSON with unique object keys. Floating-point values,
|
||||
nonfinite numbers and boolean substitutes for integers are rejected.
|
||||
|
||||
- `metadata/manifest.json`: Layer v1 manifest.
|
||||
- `metadata/lock.json`: `version: 0`, `manifest_sha256`, `packages_sha256`,
|
||||
`files_sha256` (hashes of exact metadata bytes), `snapshot_id`, `architecture`,
|
||||
`requirements` (declared runtime package names), and `authored_sources` (source
|
||||
names from manifest file entries mapped to SHA-256 of the source bytes).
|
||||
- `metadata/packages.json`: `version: 0` and `packages` array. Each record has
|
||||
`name`, `version`, `architecture`, `identity`, `archive_sha256`, `dependencies`
|
||||
(resolved package names), and `alpm: metadata/alpm/<identity>`.
|
||||
- `metadata/files.json`: `version: 0` and `objects` array. Each row has `source`,
|
||||
`path`, `package` (contribution identity or null), and `object`.
|
||||
|
||||
Objects contain `kind`, integer `mode`, `uid`, `gid`, and `xattrs` (names to
|
||||
lowercase hexadecimal bytes). Files additionally have `sha256`; symlinks have
|
||||
literal `target` and mode 0777. Directories have neither. Sources use
|
||||
`payload/packages/<identity>/root/<target>` or `payload/files/root/<target>`.
|
||||
Targets are canonical `/usr/...` paths excluding `/usr/local`. Namespace parent
|
||||
directories can be implicit; contributed objects must be indexed.
|
||||
|
||||
Every layer-authored object must correspond one-to-one to `spec.files`, including
|
||||
type, mode and symlink target. The private Arch path profile maps `/bin` and
|
||||
`/sbin` to `/usr/bin`, `/lib` and `/lib64` to `/usr/lib`, and `/etc` defaults to
|
||||
`/usr/etc` before checking declarations. Normalization collisions fail. File bytes
|
||||
must match `authored_sources`. Currently only root/root authored ownership is
|
||||
supported; other identities fail pending locked resolution evidence. Authored
|
||||
xattrs are rejected until an explicit declaration/evidence adapter exists.
|
||||
|
||||
## Package contribution identity
|
||||
|
||||
Original `desc`, `files`, and `mtree` bytes live in `metadata/alpm/<identity>/`.
|
||||
The contribution identity hashes UTF-8 JSON serialized with sorted keys, compact
|
||||
separators and unescaped Unicode. Its fields are `name`, `version`, `architecture`,
|
||||
`archive_sha256`, sorted `dependencies`, `alpm` (each of those three filenames
|
||||
mapped to its byte SHA-256), and `objects` (records containing `path` and `object`,
|
||||
sorted by target path). Source paths are omitted to avoid self-reference.
|
||||
This private canonicalization is not a substitute for the public JCS contract.
|
||||
|
||||
The checker verifies original ALPM name/version/architecture and every indexed
|
||||
object. Dependency resolution, original-to-effective ALPM transformations,
|
||||
kernel/ABI checks, whole-package replacements and finalization still require
|
||||
integration before the artifact can produce an installed deployment.
|
||||
|
||||
Fixtures in `tests/artifact.py` run in the normal release pipeline. Compilation
|
||||
and Python syntax checks alone are not runtime acceptance.
|
||||
|
||||
## Effective database adapter
|
||||
|
||||
Private layer locks may additionally carry `requirement_bindings`, an array of
|
||||
`{requirement, package}` from isolated libalpm resolution. Each declared runtime
|
||||
name plus its exact constraint must occur once; the selected provider must exist
|
||||
in the package index, and the resolved provider set must equal `requirements`.
|
||||
This preserves virtual-package choices without rewriting the manifest. Structural
|
||||
validation does not prove libalpm version/provider conformance: the isolated
|
||||
resolver and subsequent effective database checks remain mandatory.
|
||||
|
||||
The optional private `inherited` package field binds retained legacy base records:
|
||||
`adapter: legacy-managed-base-v0`, `hashes` of desc/files/mtree, a `lifecycle` map
|
||||
from canonical paths to original runtime spellings, and `absent` immutable paths.
|
||||
These sets are disjoint from effective and explicitly removed paths. All original
|
||||
paths must still be accounted for. The adapter verifies record hashes, retains
|
||||
the inherited file-list and backup entries, and expands flat ALPM mtree defaults
|
||||
when retaining their original mtree entries. It neither creates lifecycle objects
|
||||
nor reads their state from the live host. Inherited absent paths must remain absent
|
||||
before finalization; the explicit post-finalization transition is described below.
|
||||
The ledger records inherited evidence separately from composition deletions.
|
||||
After successful offline finalization the service sends a separate request with
|
||||
`finalizer_sha256`. Previously absent immutable paths that now exist are emitted
|
||||
as effective objects with fresh mtree/backup metadata and `generated` provenance
|
||||
bound to that finalizer. Before that phase their presence is an error. Lifecycle
|
||||
paths never use this transition. The original request and original records remain
|
||||
unchanged.
|
||||
This preservation adapter does not implement lifecycle actions for new overlay
|
||||
packages, and requires real pacman conformance checks in the normal pipeline.
|
||||
|
||||
`package_db.py ROOT OUTPUT REQUEST` creates a fresh output, never mutating a live
|
||||
database. Its version-0 request has a `packages` array; records contain `name`,
|
||||
`identity`, effective layer `owner`, protected original `record` directory,
|
||||
integer install `reason` (0 explicit, 1 dependency), canonical image `paths`,
|
||||
explicit `removed_paths`, and `path_owners` (each retained path to `{layer,package}`).
|
||||
The two path sets must account for every original ALPM file-list entry after
|
||||
Arch path normalization. Missing lifecycle adapters fail rather than silently
|
||||
discarding persistent/package paths. Removed objects must actually be absent.
|
||||
|
||||
Output `local/` holds effective desc/files/mtree; `originals/<identity>/` retains
|
||||
the original three records, and `transformations.json` binds original/effective
|
||||
hashes, adapter identity, removed paths, effective object hashes/metadata and
|
||||
content ownership independently of package ownership. Vendor defaults map back
|
||||
to runtime `etc/`; backup MD5 values use effective default bytes. Mtree uses
|
||||
numeric ownership, epoch mtimes and escaped literal paths/links. Its gzip stream
|
||||
has timestamp zero. The service rebuilds this output after offline finalization.
|
||||
This adapter still needs real libalpm/pacman acceptance and lifecycle-path adapters
|
||||
for the existing full Core/Purpose images before it can stage a general composition.
|
||||
|
|
@ -7,3 +7,4 @@ publish = false
|
|||
|
||||
[dependencies]
|
||||
archipelago-contracts = { path = "../contracts" }
|
||||
serde_json = "1.0"
|
||||
|
|
|
|||
57
README.md
57
README.md
|
|
@ -1,13 +1,56 @@
|
|||
# Archipelago composer
|
||||
|
||||
Первый шаг: чистая проверка заголовков входных слоёв до доступа к payload.
|
||||
Чистая проверка заголовков входных слоёв до доступа к payload.
|
||||
Проверяются ровно один Core, максимум один Purpose, порядок категорий,
|
||||
общий snapshot и целевая архитектура (D-023, D-039, D-055).
|
||||
|
||||
Успех этой проверки не означает совместимость пакетов/ABI, корректность lock,
|
||||
подписи, разрешение overrides или проверку ограничений конкретных overlays.
|
||||
Идентичности поступают от будущего адаптера проверенных артефактов.
|
||||
`selection` добавляет явный порядок, required/conflicts/before/after, циклы,
|
||||
выбор точного package payload и детерминированное владение общей зависимостью.
|
||||
Удаление слоя пересчитывает владение без изменения исходных commits. Необъявленные
|
||||
замены пакетов отклоняются; исполнитель объявленных whole-package replacements
|
||||
пока не реализован.
|
||||
|
||||
Временная межрепозиторная сборка использует соседний `../contracts`.
|
||||
Это локальный прототип; release-сборке нужны закреплённые ревизии обоих репозиториев.
|
||||
Запуск на `superserv1`: `cargo test --offline --locked`, из каталога `composer`.
|
||||
`paths` вычисляет новый эффективный индекс и provenance файловых операций до
|
||||
записи на диск: ожидаемые owner/hash, ограниченные операции, общие каталоги,
|
||||
запрет implicit recursion, symlink traversal и удаления пакета через список файлов.
|
||||
`materialize.py` выполняет внутренний проверенный план в новом частном дереве,
|
||||
с повторной проверкой исходных объектов, содержимого и конечных mode/uid/gid/xattrs.
|
||||
Удаление каталогов использует только `rmdir`, без рекурсивного обхода.
|
||||
|
||||
Это внутренние типы/протокол executor, не frozen layer serialization. Успех этих
|
||||
проверок не заменяет подпись, ABI/dependency resolution, authenticated artifact
|
||||
reader, ALPM record transforms или общую финализацию. Подключение catalog/service
|
||||
и полноценная Managed Overlay capability ещё не завершены.
|
||||
|
||||
`artifact.py` и `artifact::read_checked` проверяют и преобразуют indexed artifact
|
||||
после аутентификации checkout службой. Точный частный формат и текущие ограничения:
|
||||
[`ARTIFACT-V0.md`](ARTIFACT-V0.md). `artifact::validate_selection` дополнительно
|
||||
проверяет Core/Purpose logical-ID constraints; kernel-bound входы пока отклоняются
|
||||
до подключения ABI evidence. `artifact::permissions` нормализует runtime paths
|
||||
и отклоняет дублирующие aliases в разрешениях overrides.
|
||||
|
||||
`compose::plan` связывает эти проверки с package contributions, authored files,
|
||||
удалениями и metadata overrides поверх чистой Core/Purpose базы, возвращая effective
|
||||
index, полную историю и физический executor plan. Внутри-слойные package conflicts
|
||||
не скрываются дедупликацией; объединяются только одинаковые каталоги. Подключение
|
||||
effective ALPM database и finalization к этому плану остаётся незавершённым.
|
||||
|
||||
`Plan::database_request` и `package_db.py` добавляют частный ALPM adapter:
|
||||
оригинальные desc/files/mtree сохраняются отдельно; effective records содержат
|
||||
runtime `/etc` paths, explicit/dependency reasons, epoch mtimes, backup checksums
|
||||
и ledger original/effective hashes + content owners. Каждый исходный путь должен
|
||||
иметь effective entry либо явное удаление; неиндексированные lifecycle paths
|
||||
нельзя молча отбросить. Generated outputs перечитываются после финализации.
|
||||
Проверки `pacman -Q/-Qo/-Qkk` в целевой VM ещё необходимы до заявления conformance.
|
||||
Fixtures добавлены в штатный pipeline, отдельно не запускались.
|
||||
|
||||
`base.py` читает существующие private Core package-index/Purpose delta только
|
||||
после аутентификации image/layer checkouts вызывающей стороной. Он сверяет набор
|
||||
и версии пакетов/snapshot, формирует effective `/usr` ownership и отдельно сохраняет
|
||||
lifecycle/absent paths. Его identity относится к адаптированному signed base payload,
|
||||
а не к оригинальному package archive. Подключение этих base inputs к транзакции
|
||||
ещё требуется; наличие scanner не означает готовность PrepareSet.
|
||||
|
||||
Межрепозиторная сборка использует соседний `../contracts`; system зависит от
|
||||
composer. Компиляция на yabloko использует общий CLI lock. Unit/filesystem tests
|
||||
включены в штатный release pipeline; отдельные исполнения/VM не запускаются.
|
||||
|
|
|
|||
249
artifact.py
Normal file
249
artifact.py
Normal file
|
|
@ -0,0 +1,249 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Validate a protected checkout of an already authenticated layer commit.
|
||||
|
||||
Private artifact-index adapter v0 implementing RFC-0008's indexed layout. This
|
||||
does not authenticate an OSTree commit: the service verifies its configured
|
||||
remote/signature before supplying the checkout. It never executes layer code.
|
||||
"""
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import sys
|
||||
|
||||
spec = importlib.util.spec_from_file_location('materialize', Path(__file__).with_name('materialize.py'))
|
||||
objects = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(objects)
|
||||
require = objects.require
|
||||
|
||||
|
||||
def pairs(items):
|
||||
result = {}
|
||||
for key, value in items:
|
||||
require(key not in result, 'Duplicate JSON key: ' + key)
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
|
||||
def digest(value):
|
||||
return isinstance(value, str) and len(value) == 64 and all(c in '0123456789abcdef' for c in value)
|
||||
|
||||
|
||||
def reject_number(value):
|
||||
raise ValueError('Non-integer JSON number: ' + value)
|
||||
|
||||
|
||||
def version(value):
|
||||
return type(value) is int and value == 0
|
||||
|
||||
|
||||
def object_shape(value):
|
||||
require(isinstance(value, dict), 'Expected payload object')
|
||||
kind = value.get('kind')
|
||||
require(kind in ('file', 'directory', 'symlink'), 'Invalid object kind')
|
||||
field_set(value, ['kind', 'mode', 'uid', 'gid', 'xattrs'] +
|
||||
(['sha256'] if kind == 'file' else ['target'] if kind == 'symlink' else []))
|
||||
for field, maximum in [('mode', 0o7777), ('uid', 2**32 - 1), ('gid', 2**32 - 1)]:
|
||||
require(type(value[field]) is int and 0 <= value[field] <= maximum, 'Invalid object ' + field)
|
||||
require(isinstance(value['xattrs'], dict), 'Invalid xattrs')
|
||||
for key, data in value['xattrs'].items():
|
||||
require(isinstance(key, str) and key and '\0' not in key and isinstance(data, str) and
|
||||
len(data) % 2 == 0 and all(c in '0123456789abcdef' for c in data), 'Invalid xattr')
|
||||
if kind == 'file':
|
||||
require(digest(value['sha256']), 'Invalid file digest')
|
||||
if kind == 'symlink':
|
||||
require(isinstance(value['target'], str) and value['target'] and '\0' not in value['target'] and
|
||||
value['mode'] == 0o777, 'Invalid symlink')
|
||||
|
||||
|
||||
def image_path(path):
|
||||
objects.relative(path)
|
||||
# Locked private v0 Arch /usr-merge and vendor-defaults profile.
|
||||
for alias, destination in [('/bin', '/usr/bin'), ('/sbin', '/usr/bin'),
|
||||
('/lib', '/usr/lib'), ('/lib64', '/usr/lib'), ('/etc', '/usr/etc')]:
|
||||
if path == alias or path.startswith(alias + '/'):
|
||||
return destination + path[len(alias):]
|
||||
return path
|
||||
|
||||
|
||||
def authored_files(manifest, rows, sources):
|
||||
require(isinstance(sources, dict), 'Invalid locked authored sources')
|
||||
used_sources = set()
|
||||
declared = {}
|
||||
for entry in manifest['spec'].get('files', []):
|
||||
path = image_path(entry['path'])
|
||||
require(path not in declared, 'Duplicate normalized authored path')
|
||||
declared[path] = entry
|
||||
authored = {row['path']: row['object'] for row in rows if row['package'] is None}
|
||||
require(authored.keys() == declared.keys(), 'Authored payload does not match manifest files')
|
||||
for path, entry in declared.items():
|
||||
value = authored[path]
|
||||
require(value['kind'] == entry.get('type', 'file') and value['mode'] == int(entry['mode'], 8),
|
||||
'Authored type/mode differs from manifest')
|
||||
# Other identities require locked resolution evidence, not host NSS lookup.
|
||||
require(entry['owner'] == entry['group'] == 'root' and value['uid'] == value['gid'] == 0,
|
||||
'Authored ownership requires supported locked identity resolution')
|
||||
require(not value['xattrs'], 'Undeclared authored xattrs')
|
||||
if value['kind'] == 'file':
|
||||
source = entry['source']
|
||||
relative(source)
|
||||
require(source in sources and digest(sources[source]) and sources[source] == value['sha256'],
|
||||
'Authored bytes differ from locked source')
|
||||
used_sources.add(source)
|
||||
if value['kind'] == 'symlink':
|
||||
require(value['target'] == entry['target'], 'Authored symlink target mismatch')
|
||||
require(used_sources == sources.keys(), 'Unused locked authored source')
|
||||
|
||||
|
||||
def relative(value):
|
||||
require(isinstance(value, str) and not value.startswith('/'), 'Expected relative artifact path')
|
||||
return objects.relative('/' + value)
|
||||
|
||||
|
||||
def read(root, name):
|
||||
rel = relative(name)
|
||||
objects.safe_parent(root, rel)
|
||||
path = root / rel
|
||||
info = path.lstat()
|
||||
require(stat.S_ISREG(info.st_mode) and info.st_size <= 16 * 1024 * 1024, 'Invalid metadata file: ' + name)
|
||||
raw = path.read_bytes()
|
||||
return json.loads(raw, object_pairs_hook=pairs, parse_float=reject_number,
|
||||
parse_constant=reject_number), hashlib.sha256(raw).hexdigest()
|
||||
|
||||
|
||||
def field_set(value, required, optional=()):
|
||||
require(isinstance(value, dict) and set(required) <= value.keys() and
|
||||
value.keys() <= set(required) | set(optional), 'Unknown or missing index fields')
|
||||
|
||||
|
||||
def alpm_fields(raw):
|
||||
fields = {}
|
||||
active = None
|
||||
for line in raw.decode('utf-8').splitlines():
|
||||
if line.startswith('%') and line.endswith('%'):
|
||||
require(line not in fields, 'Duplicate ALPM record field')
|
||||
fields[line] = []
|
||||
active = line
|
||||
elif line:
|
||||
require(active is not None, 'Invalid ALPM record')
|
||||
fields[active].append(line)
|
||||
return fields
|
||||
|
||||
|
||||
def check(root):
|
||||
require(root.is_absolute() and root.is_dir() and not root.is_symlink(), 'Invalid checkout root')
|
||||
require(all(not parent.is_symlink() for parent in root.parents), 'Checkout symlink ancestor')
|
||||
manifest, manifest_digest = read(root, 'metadata/manifest.json')
|
||||
lock, lock_digest = read(root, 'metadata/lock.json')
|
||||
packages, packages_digest = read(root, 'metadata/packages.json')
|
||||
files, files_digest = read(root, 'metadata/files.json')
|
||||
field_set(lock, ['version', 'manifest_sha256', 'snapshot_id', 'architecture', 'packages_sha256', 'files_sha256', 'requirements', 'authored_sources'], ['requirement_bindings'])
|
||||
require(version(lock['version']) and lock['manifest_sha256'] == manifest_digest and
|
||||
lock['packages_sha256'] == packages_digest and lock['files_sha256'] == files_digest,
|
||||
'Lock does not bind the exact manifest and indexes')
|
||||
require(digest(lock['snapshot_id']) and lock['architecture'] == 'x86_64', 'Invalid locked target')
|
||||
# Full Layer v1 structural/semantic validation is performed by the Rust reader.
|
||||
require(manifest['apiVersion'] == 'archipelago/v1' and manifest['kind'] == 'Layer', 'Wrong manifest kind')
|
||||
require(manifest['spec']['architecture'] == lock['architecture'], 'Manifest architecture mismatch')
|
||||
field_set(packages, ['version', 'packages'])
|
||||
field_set(files, ['version', 'objects'])
|
||||
require(version(packages['version']) and version(files['version']), 'Unsupported private index version')
|
||||
require(isinstance(packages['packages'], list) and len(packages['packages']) <= 100000, 'Invalid package list')
|
||||
require(isinstance(files['objects'], list) and len(files['objects']) <= 1000000, 'Invalid file list')
|
||||
package_ids = {}
|
||||
package_names = set()
|
||||
contribution_inputs = {}
|
||||
for package in packages['packages']:
|
||||
field_set(package, ['name', 'version', 'architecture', 'identity', 'archive_sha256', 'dependencies', 'alpm'])
|
||||
name = package['name']
|
||||
require(isinstance(package['version'], str) and package['version'], 'Invalid package version')
|
||||
require(isinstance(name, str) and name and all(c.isascii() and (c.isalnum() or c in '@._+-') for c in name), 'Invalid package name')
|
||||
require(name not in package_names and digest(package['identity']) and digest(package['archive_sha256']), 'Invalid/duplicate package identity')
|
||||
require(package['identity'] not in package_ids and package['architecture'] in ('any', 'x86_64'), 'Invalid package architecture/identity')
|
||||
require(isinstance(package['dependencies'], list) and all(isinstance(dep, str) and dep for dep in package['dependencies']) and
|
||||
len(set(package['dependencies'])) == len(package['dependencies']), 'Invalid resolved dependency list')
|
||||
record = relative(package['alpm'])
|
||||
require(str(record) == 'metadata/alpm/' + package['identity'], 'ALPM record outside its package namespace')
|
||||
objects.safe_parent(root, record / 'desc')
|
||||
data = {}
|
||||
for filename in ('desc', 'files', 'mtree'):
|
||||
path = root / record / filename
|
||||
require(stat.S_ISREG(path.lstat().st_mode), 'Missing original ALPM record')
|
||||
require(path.stat().st_size <= 16 * 1024 * 1024, 'Oversized ALPM record')
|
||||
data[filename] = path.read_bytes()
|
||||
fields = alpm_fields(data['desc'])
|
||||
for key, expected in [('%NAME%', name), ('%VERSION%', package['version']), ('%ARCH%', package['architecture'])]:
|
||||
require(fields.get(key) == [expected], 'ALPM identity disagrees with package index')
|
||||
package_ids[package['identity']] = package
|
||||
contribution_inputs[package['identity']] = dict(name=name, version=package['version'],
|
||||
architecture=package['architecture'], archive_sha256=package['archive_sha256'],
|
||||
dependencies=sorted(package['dependencies']),
|
||||
alpm={filename: hashlib.sha256(raw).hexdigest() for filename, raw in data.items()}, objects=[])
|
||||
package_names.add(name)
|
||||
requirements = lock['requirements']
|
||||
require(isinstance(requirements, list) and all(isinstance(name, str) and name in package_names for name in requirements) and
|
||||
len(set(requirements)) == len(requirements), 'Invalid locked package requirements')
|
||||
declarations = manifest['spec'].get('packages', {}).get('runtime', [])
|
||||
declared = {item['name'] for item in declarations}
|
||||
if 'requirement_bindings' in lock:
|
||||
bindings = lock['requirement_bindings']
|
||||
require(isinstance(bindings, list), 'Invalid requirement bindings')
|
||||
expected = {item['name'] + item.get('constraint', '') for item in declarations}
|
||||
seen = set()
|
||||
resolved = set()
|
||||
for binding in bindings:
|
||||
field_set(binding, ['requirement', 'package'])
|
||||
require(isinstance(binding['requirement'], str) and binding['requirement'] in expected and
|
||||
binding['requirement'] not in seen and isinstance(binding['package'], str) and
|
||||
binding['package'] in package_names, 'Unknown, duplicate or unresolved requirement binding')
|
||||
seen.add(binding['requirement'])
|
||||
resolved.add(binding['package'])
|
||||
require(seen == expected and resolved == set(requirements), 'Incomplete resolved requirement bindings')
|
||||
else:
|
||||
require(set(requirements) == declared, 'Lock does not retain the declared package requirements')
|
||||
indexed = set()
|
||||
destinations = set()
|
||||
for row in files['objects']:
|
||||
field_set(row, ['source', 'path', 'package', 'object'])
|
||||
source = relative(row['source'])
|
||||
target = row['path']
|
||||
objects.relative(target)
|
||||
require(target.startswith('/usr/') and target != '/usr/local' and not target.startswith('/usr/local/'), 'Unadapted persistent or boot path')
|
||||
package_id = row['package']
|
||||
require(package_id is None or (isinstance(package_id, str) and package_id in package_ids), 'Unknown object package')
|
||||
prefix = 'payload/files/root/' if package_id is None else 'payload/packages/' + package_id + '/root/'
|
||||
require(str(source) == prefix + target.lstrip('/'), 'Payload source/target mapping mismatch')
|
||||
require(str(source) not in indexed and (package_id, target) not in destinations, 'Duplicate indexed object')
|
||||
objects.safe_parent(root, source)
|
||||
object_shape(row['object'])
|
||||
require(objects.identity(root / source) == row['object'], 'Payload identity mismatch: ' + str(source))
|
||||
indexed.add(str(source))
|
||||
destinations.add((package_id, target))
|
||||
if package_id is not None:
|
||||
contribution_inputs[package_id]['objects'].append(dict(path=target, object=row['object']))
|
||||
authored_files(manifest, files['objects'], lock['authored_sources'])
|
||||
for identity, contribution in contribution_inputs.items():
|
||||
contribution['objects'].sort(key=lambda row: row['path'])
|
||||
canonical = json.dumps(contribution, sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode('utf-8')
|
||||
require(hashlib.sha256(canonical).hexdigest() == identity, 'Package contribution identity mismatch')
|
||||
# Structural namespace directories may be implicit; all contributed payload
|
||||
# objects, including empty directories, must be indexed explicitly.
|
||||
parents = set()
|
||||
for source in indexed:
|
||||
parents.update(str(p) for p in Path(source).parents if str(p) != '.')
|
||||
payload = root / 'payload'
|
||||
require(payload.is_dir() and not payload.is_symlink(), 'Missing payload tree')
|
||||
for parent, directories, leaves in os.walk(payload, followlinks=False):
|
||||
for name in directories + leaves:
|
||||
path = Path(parent) / name
|
||||
rel = path.relative_to(root).as_posix()
|
||||
require(rel in indexed or (rel in parents and stat.S_ISDIR(path.lstat().st_mode)), 'Unindexed payload: ' + rel)
|
||||
return dict(version=0, manifest=manifest, lock=lock, lock_sha256=lock_digest,
|
||||
packages=packages['packages'], objects=files['objects'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
require(len(sys.argv) == 2, 'Usage: artifact.py AUTHENTICATED_CHECKOUT')
|
||||
print(json.dumps(check(Path(sys.argv[1])), separators=(',', ':'), sort_keys=True))
|
||||
157
base.py
Normal file
157
base.py
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Read the signed legacy Core/Purpose composition into a private base index.
|
||||
|
||||
Caller authenticates the image and its exact referenced layer commits first.
|
||||
This adapter describes the already transformed managed base, not original archive
|
||||
bytes. Its package identities deliberately include the legacy adapter identity.
|
||||
"""
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import sys
|
||||
|
||||
spec = importlib.util.spec_from_file_location('artifact', Path(__file__).with_name('artifact.py'))
|
||||
artifact = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(artifact)
|
||||
require = artifact.require
|
||||
|
||||
|
||||
def regular(root, relative):
|
||||
path = artifact.relative(relative)
|
||||
artifact.objects.safe_parent(root, path)
|
||||
source = root / path
|
||||
require(stat.S_ISREG(source.lstat().st_mode), 'Expected regular base metadata')
|
||||
return source.read_bytes()
|
||||
|
||||
|
||||
def database(root, relative):
|
||||
directory = artifact.relative(relative)
|
||||
artifact.objects.safe_parent(root, directory / 'entry')
|
||||
result = {}
|
||||
for entry in sorted((root / directory).iterdir()):
|
||||
if entry.name == 'ALPM_DB_VERSION':
|
||||
continue
|
||||
require(stat.S_ISDIR(entry.lstat().st_mode), 'Unexpected local DB object')
|
||||
raw = regular(root, str(entry.relative_to(root) / 'desc'))
|
||||
fields = artifact.alpm_fields(raw)
|
||||
name = fields.get('%NAME%', [])
|
||||
version = fields.get('%VERSION%', [])
|
||||
require(len(name) == len(version) == 1 and name[0] not in result, 'Invalid base package identity')
|
||||
result[name[0]] = dict(version=version[0], record=str(entry), fields=fields)
|
||||
require(result, 'Empty base package database')
|
||||
return result
|
||||
|
||||
|
||||
def read_base(root, core, purpose=None):
|
||||
for directory in [root, core] + ([purpose] if purpose is not None else []):
|
||||
require(directory.is_absolute() and directory.is_dir() and not directory.is_symlink() and
|
||||
all(not p.is_symlink() for p in directory.parents), 'Invalid authenticated base checkout')
|
||||
snapshot = regular(root, 'usr/lib/archipelago/snapshot').decode().strip()
|
||||
require(artifact.digest(snapshot), 'Invalid base snapshot identity')
|
||||
require(regular(core, 'metadata/snapshot').decode().strip() == snapshot, 'Core snapshot mismatch')
|
||||
core_packages = database(core, 'metadata/package-index')
|
||||
effective = database(root, 'usr/lib/archipelago/package-db/local')
|
||||
owners = {name: 'core' for name in core_packages}
|
||||
authored = {}
|
||||
purpose_id = None
|
||||
if purpose is not None:
|
||||
delta, _ = artifact.read(purpose, 'metadata/delta.json')
|
||||
require(artifact.version(delta['version']) and delta['snapshot'] == snapshot, 'Purpose snapshot mismatch')
|
||||
require(delta['requires_packages'] == {name: item['version'] for name, item in core_packages.items()},
|
||||
'Purpose Core requirements disagree with verified Core')
|
||||
purpose_id = regular(root, 'usr/lib/archipelago/purpose').decode().strip()
|
||||
require(purpose_id in ('purpose/desktop/gnome', 'purpose/desktop/kde'), 'Unknown legacy Purpose identity')
|
||||
for name, version in delta['packages'].items():
|
||||
require(name not in owners and name in effective and effective[name]['version'] == version,
|
||||
'Purpose package ownership/version mismatch')
|
||||
owners[name] = purpose_id
|
||||
for row in delta['paths']:
|
||||
path = '/' + str(artifact.relative(row['path']))
|
||||
require(path not in authored, 'Duplicate Purpose delta path')
|
||||
authored[path] = purpose_id
|
||||
require(effective.keys() == owners.keys(), 'Effective base package set differs from referenced layers')
|
||||
for name, package in core_packages.items():
|
||||
require(effective[name]['version'] == package['version'], 'Managed base replaced a Core package')
|
||||
# Package membership and effective content ownership are independent. A
|
||||
# Purpose-authored replacement keeps the lower package association as evidence.
|
||||
memberships = {}
|
||||
packages = []
|
||||
for name, item in sorted(effective.items()):
|
||||
reason = item['fields'].get('%REASON%', ['0'])
|
||||
require(reason in (['0'], ['1']), 'Invalid base package install reason')
|
||||
record = Path(item['record'])
|
||||
original = {filename: regular(record, filename) for filename in ('desc', 'files', 'mtree')}
|
||||
listed = artifact.alpm_fields(original['files']).get('%FILES%', [])
|
||||
paths = []
|
||||
lifecycle = []
|
||||
for path in listed:
|
||||
canonical = artifact.image_path('/' + path.rstrip('/'))
|
||||
if canonical == '/usr' or (canonical.startswith('/usr/') and
|
||||
canonical != '/usr/local' and not canonical.startswith('/usr/local/')):
|
||||
paths.append(canonical)
|
||||
members = memberships.setdefault(canonical, [])
|
||||
if name not in members:
|
||||
members.append(name)
|
||||
else:
|
||||
# Retain explicitly: the ALPM adapter must handle these through
|
||||
# a lifecycle policy, never silently discard them from the DB.
|
||||
lifecycle.append(dict(runtime_path=path, canonical_path=canonical))
|
||||
packages.append(dict(name=name, version=item['version'], reason=int(reason[0]), owner=owners[name], record=str(record),
|
||||
paths=sorted(set(paths)), lifecycle_paths=lifecycle,
|
||||
original_hashes={key: hashlib.sha256(raw).hexdigest() for key, raw in original.items()}))
|
||||
index = []
|
||||
candidates = [root / 'usr']
|
||||
for parent, directories, leaves in os.walk(root / 'usr', followlinks=False):
|
||||
for name in sorted(directories + leaves):
|
||||
path = Path(parent) / name
|
||||
if path == root / 'usr/local':
|
||||
if name in directories:
|
||||
directories.remove(name)
|
||||
continue
|
||||
candidates.append(path)
|
||||
package_objects = {item['name']: [] for item in packages}
|
||||
for path in candidates:
|
||||
relative = '/' + path.relative_to(root).as_posix()
|
||||
value = artifact.objects.identity(path)
|
||||
members = memberships.get(relative, [])
|
||||
require(len(members) <= 1 or value['kind'] == 'directory', 'Conflicting base package file ownership')
|
||||
# Shared directory ownership follows Core then Purpose, then package name.
|
||||
members.sort(key=lambda name: (owners[name] != 'core', name))
|
||||
package = members[0] if members else None
|
||||
owner = authored.get(relative, owners[package] if package else 'core')
|
||||
content_package = package if package is not None and owners[package] == owner else None
|
||||
index.append(dict(path=relative, object=value, owner=dict(layer=owner, package=content_package)))
|
||||
for name in members:
|
||||
package_objects[name].append(dict(path=relative, object=value))
|
||||
present = {row['path'] for row in index}
|
||||
for item in packages:
|
||||
item['absent_immutable_paths'] = sorted(set(item['paths']) - present)
|
||||
contribution = dict(adapter='legacy-managed-base-v0', snapshot=snapshot,
|
||||
name=item['name'], version=item['version'], original_hashes=item['original_hashes'],
|
||||
objects=sorted(package_objects[item['name']], key=lambda row: row['path']),
|
||||
lifecycle_paths=item['lifecycle_paths'], absent_immutable_paths=item['absent_immutable_paths'])
|
||||
raw = json.dumps(contribution, sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode()
|
||||
item['identity'] = hashlib.sha256(raw).hexdigest()
|
||||
return dict(version=0, adapter='legacy-managed-base-v0', snapshot_id=snapshot,
|
||||
architecture='x86_64', core_id='core', purpose_id=purpose_id, packages=packages, index=index)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
args = sys.argv[1:]
|
||||
output = None
|
||||
if len(args) >= 2 and args[0] == '--output':
|
||||
output = Path(args[1])
|
||||
args = args[2:]
|
||||
require(len(args) in (2, 3), 'Usage: base.py [--output NEW_FILE] AUTHENTICATED_IMAGE CORE_LAYER [PURPOSE_LAYER]')
|
||||
result = read_base(*(Path(value) for value in args))
|
||||
if output is None:
|
||||
print(json.dumps(result, sort_keys=True, separators=(',', ':')))
|
||||
else:
|
||||
# The worker owns this directory. Exclusive creation prevents reuse of
|
||||
# stale evidence and never follows an existing destination symlink.
|
||||
with output.open('x') as stream:
|
||||
json.dump(result, stream, sort_keys=True, separators=(',', ':'))
|
||||
stream.write('\n')
|
||||
168
materialize.py
Normal file
168
materialize.py
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Execute a service-owned, fully checked path plan into a fresh private tree.
|
||||
|
||||
This is an internal executor protocol, not a layer artifact format. The caller
|
||||
authenticates layer checkouts and computes ownership/permissions in the Rust
|
||||
planner before invoking this process. No network, package installation or live
|
||||
deployment mutation occurs here. Failed output remains private for diagnosis.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def require(value, message):
|
||||
if not value:
|
||||
raise ValueError(message)
|
||||
|
||||
|
||||
def relative(path):
|
||||
require(isinstance(path, str) and path.startswith('/') and '\0' not in path,
|
||||
'Expected absolute canonical image path')
|
||||
parts = path[1:].split('/')
|
||||
require(all(part not in ('', '.', '..') for part in parts), 'Noncanonical path')
|
||||
return Path(*parts)
|
||||
|
||||
|
||||
def safe_parent(root, relative_path):
|
||||
current = root
|
||||
for part in relative_path.parts[:-1]:
|
||||
current /= part
|
||||
require(stat.S_ISDIR(current.lstat().st_mode), 'Missing or symlink ancestor: ' + str(current))
|
||||
|
||||
|
||||
def identity(path):
|
||||
metadata = path.lstat()
|
||||
value = dict(mode=stat.S_IMODE(metadata.st_mode), uid=metadata.st_uid, gid=metadata.st_gid,
|
||||
xattrs={key: os.getxattr(path, key, follow_symlinks=False).hex()
|
||||
for key in os.listxattr(path, follow_symlinks=False)})
|
||||
if stat.S_ISREG(metadata.st_mode):
|
||||
with path.open('rb') as stream:
|
||||
value.update(kind='file', sha256=hashlib.file_digest(stream, 'sha256').hexdigest())
|
||||
elif stat.S_ISDIR(metadata.st_mode):
|
||||
value.update(kind='directory')
|
||||
elif stat.S_ISLNK(metadata.st_mode):
|
||||
value.update(kind='symlink', target=os.readlink(path))
|
||||
else:
|
||||
raise ValueError('Unsupported payload object: ' + str(path))
|
||||
return value
|
||||
|
||||
|
||||
def input_object(root, rel):
|
||||
"""Read an object without following any ancestor symlink, including when a
|
||||
planned directory addition/type change makes that descendant absent today."""
|
||||
current = root
|
||||
for part in rel.parts[:-1]:
|
||||
current /= part
|
||||
try:
|
||||
mode = current.lstat().st_mode
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
if not stat.S_ISDIR(mode):
|
||||
return None
|
||||
target = root / rel
|
||||
try:
|
||||
target.lstat()
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
return identity(target)
|
||||
|
||||
|
||||
def metadata(path, expected):
|
||||
# chown can clear special mode bits and capabilities: restore them afterwards.
|
||||
os.chown(path, expected['uid'], expected['gid'], follow_symlinks=False)
|
||||
if expected['kind'] != 'symlink':
|
||||
os.chmod(path, expected['mode'], follow_symlinks=False)
|
||||
for key in os.listxattr(path, follow_symlinks=False):
|
||||
if key not in expected['xattrs']:
|
||||
os.removexattr(path, key, follow_symlinks=False)
|
||||
for key, value in expected['xattrs'].items():
|
||||
os.setxattr(path, key, bytes.fromhex(value), follow_symlinks=False)
|
||||
|
||||
|
||||
def materialize(base, output, plan):
|
||||
require(plan['version'] == 0, 'Unsupported internal executor plan')
|
||||
require(base.is_absolute() and output.is_absolute(), 'Absolute workspace paths required')
|
||||
for root in (base, output.parent):
|
||||
require(root.is_dir() and not root.is_symlink(), 'Invalid workspace directory')
|
||||
for parent in root.parents:
|
||||
require(not parent.is_symlink(), 'Workspace symlink ancestor')
|
||||
require(not output.exists() and not output.is_symlink(), 'Output already exists')
|
||||
require(output != base and base not in output.parents, 'Output must be outside input')
|
||||
require(output.parent.stat().st_uid == os.geteuid() and output.parent.stat().st_mode & 0o022 == 0,
|
||||
'Output parent must be service-owned and not writable by others')
|
||||
changes = plan['effects']
|
||||
require(isinstance(changes, list) and len(changes) <= 1000000, 'Invalid effect list')
|
||||
seen = set()
|
||||
sources = {}
|
||||
for change in changes:
|
||||
path = change['path']
|
||||
rel = relative(path)
|
||||
require(path.startswith('/usr/') and path != '/usr/local' and not path.startswith('/usr/local/'),
|
||||
'Effects outside immutable vendor payload require another adapter')
|
||||
require(path not in seen, 'Duplicate effect')
|
||||
seen.add(path)
|
||||
before = input_object(base, rel)
|
||||
require(before == change['before'], 'Input changed after planning: ' + path)
|
||||
after = change['after']
|
||||
if after is not None and after['kind'] == 'file':
|
||||
source_root = Path(change['source_root'])
|
||||
source_rel = relative(change['source_path'])
|
||||
require(source_root.is_absolute() and source_root.is_dir() and not source_root.is_symlink(), 'Invalid source root')
|
||||
for parent in source_root.parents:
|
||||
require(not parent.is_symlink(), 'Source root symlink ancestor')
|
||||
safe_parent(source_root, source_rel)
|
||||
source = source_root / source_rel
|
||||
source_identity = identity(source)
|
||||
require(source_identity['kind'] == 'file' and source_identity['sha256'] == after['sha256'],
|
||||
'Source does not match planned bytes: ' + path)
|
||||
sources[path] = source
|
||||
subprocess.run(['cp', '-a', '--reflink=auto', '--', str(base), str(output)], check=True)
|
||||
# Remove explicit objects deepest-first. rmdir refuses undeclared children;
|
||||
# there is deliberately no recursive delete, even in this private workspace.
|
||||
for change in sorted(changes, key=lambda c: (-len(relative(c['path']).parts), c['path'])):
|
||||
if change['before'] is None:
|
||||
continue
|
||||
if change['after'] is not None and change['before']['kind'] == change['after']['kind'] == 'directory':
|
||||
continue
|
||||
rel = relative(change['path'])
|
||||
safe_parent(output, rel)
|
||||
target = output / rel
|
||||
require(identity(target) == change['before'], 'Copied input mismatch')
|
||||
if change['before']['kind'] == 'directory':
|
||||
target.rmdir()
|
||||
else:
|
||||
target.unlink()
|
||||
for change in sorted(changes, key=lambda c: (len(relative(c['path']).parts), c['path'])):
|
||||
after = change['after']
|
||||
if after is None:
|
||||
continue
|
||||
rel = relative(change['path'])
|
||||
safe_parent(output, rel)
|
||||
target = output / rel
|
||||
if after['kind'] == 'directory':
|
||||
target.mkdir(exist_ok=True)
|
||||
elif after['kind'] == 'symlink':
|
||||
target.symlink_to(after['target'])
|
||||
elif after['kind'] == 'file':
|
||||
with sources[change['path']].open('rb') as source, target.open('xb') as destination:
|
||||
shutil.copyfileobj(source, destination)
|
||||
else:
|
||||
raise ValueError('Unknown object type')
|
||||
metadata(target, after)
|
||||
require(identity(target) == after, 'Materialized identity mismatch: ' + change['path'])
|
||||
for change in changes:
|
||||
actual = input_object(output, relative(change['path']))
|
||||
require(actual == change['after'], 'Final effect verification failed: ' + change['path'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
require(len(sys.argv) == 4, 'Usage: materialize.py BASE OUTPUT PLAN')
|
||||
with open(sys.argv[3]) as stream:
|
||||
plan = json.load(stream)
|
||||
materialize(Path(sys.argv[1]), Path(sys.argv[2]), plan)
|
||||
262
package_db.py
Normal file
262
package_db.py
Normal file
|
|
@ -0,0 +1,262 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Private effective ALPM database adapter; never installs packages or runs hooks.
|
||||
|
||||
Inputs are protected original records and a complete checked per-package path
|
||||
selection. Output is a new private directory with local/, originals/ and a
|
||||
transformation ledger. Caller installs it only after all composition checks pass.
|
||||
"""
|
||||
import gzip
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import sys
|
||||
|
||||
spec = importlib.util.spec_from_file_location('artifact', Path(__file__).with_name('artifact.py'))
|
||||
artifact = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(artifact)
|
||||
require = artifact.require
|
||||
|
||||
|
||||
def hash_bytes(raw):
|
||||
return hashlib.sha256(raw).hexdigest()
|
||||
|
||||
|
||||
def encode(fields):
|
||||
return ''.join(key + '\n' + '\n'.join(values) + '\n\n' for key, values in fields.items()).encode('utf-8')
|
||||
|
||||
|
||||
def escape(text):
|
||||
# mtree accepts octal byte escapes; encode whitespace, comments and backslash
|
||||
# without locale-dependent interpretation or shell quoting.
|
||||
return ''.join(chr(byte) if 33 <= byte <= 126 and byte not in (35, 61, 92)
|
||||
else '\\%03o' % byte for byte in os.fsencode(text))
|
||||
|
||||
|
||||
def runtime_path(image_path):
|
||||
artifact.objects.relative(image_path)
|
||||
require((image_path == '/usr' or image_path.startswith('/usr/')) and
|
||||
image_path != '/usr/local' and not image_path.startswith('/usr/local/'), 'Unsupported DB payload path')
|
||||
if image_path == '/usr/etc':
|
||||
return 'etc'
|
||||
return image_path.removeprefix('/usr/') if image_path.startswith('/usr/etc/') else image_path[1:]
|
||||
|
||||
|
||||
def mtree(root, image_path, value):
|
||||
path = root / artifact.objects.relative(image_path)
|
||||
fields = ['type=' + {'directory': 'dir', 'file': 'file', 'symlink': 'link'}[value['kind']],
|
||||
'uid=' + str(value['uid']), 'gid=' + str(value['gid']), 'mode=%o' % value['mode'], 'time=0.0']
|
||||
if value['kind'] == 'file':
|
||||
fields.extend(['size=' + str(path.lstat().st_size), 'sha256digest=' + value['sha256']])
|
||||
if value['kind'] == 'symlink':
|
||||
fields.append('link=' + escape(value['target']))
|
||||
return './' + escape(runtime_path(image_path)) + ' ' + ' '.join(fields) + '\n'
|
||||
|
||||
|
||||
def protected_directory(path):
|
||||
require(path.is_absolute() and path.is_dir() and not path.is_symlink(), 'Invalid protected directory')
|
||||
require(all(not p.is_symlink() for p in path.parents), 'Symlink in protected directory ancestry')
|
||||
|
||||
|
||||
def inherited_mtree(raw, retained):
|
||||
"""Expand flat ALPM mtree defaults, retaining original runtime entries only."""
|
||||
defaults = {}
|
||||
result = []
|
||||
seen = set()
|
||||
for line in gzip.decompress(raw).decode('utf-8').splitlines():
|
||||
if not line or line.startswith('#'):
|
||||
continue
|
||||
words = line.split()
|
||||
if words[0] == '/set':
|
||||
for word in words[1:]:
|
||||
key, sep, value = word.partition('=')
|
||||
require(sep, 'Invalid mtree default')
|
||||
defaults[key] = value
|
||||
continue
|
||||
if words[0] == '/unset':
|
||||
for key in words[1:]:
|
||||
if key == 'all':
|
||||
defaults.clear()
|
||||
else:
|
||||
defaults.pop(key, None)
|
||||
continue
|
||||
require(words[0].startswith('./') or words[0] == '.', 'Unsupported hierarchical mtree')
|
||||
encoded = words[0].removeprefix('./')
|
||||
path = re.sub(r'\\([0-7]{3})', lambda match: chr(int(match[1], 8)), encoded)
|
||||
if path not in retained:
|
||||
continue
|
||||
require(path not in seen, 'Duplicate inherited mtree path')
|
||||
seen.add(path)
|
||||
fields = defaults.copy()
|
||||
for word in words[1:]:
|
||||
key, sep, value = word.partition('=')
|
||||
fields[key] = value if sep else None
|
||||
result.append('./' + escape(path) + ' ' + ' '.join(
|
||||
key if value is None else key + '=' + value for key, value in sorted(fields.items())) + '\n')
|
||||
# Some original records intentionally omit lifecycle objects. Preserve that
|
||||
# omission; do not synthesize metadata from the running host.
|
||||
return result
|
||||
|
||||
|
||||
def assemble(root, output, request):
|
||||
protected_directory(root)
|
||||
protected_directory(output.parent)
|
||||
require(output.is_absolute() and not output.exists() and not output.is_symlink(), 'Database output already exists')
|
||||
require(output != root and root not in output.parents, 'Database output must be outside composed root')
|
||||
artifact.field_set(request, ['version', 'packages'], ['finalizer_sha256'])
|
||||
require(artifact.version(request['version']) and isinstance(request['packages'], list), 'Invalid DB request')
|
||||
finalizer = request.get('finalizer_sha256')
|
||||
require(finalizer is None or artifact.digest(finalizer), 'Invalid finalization identity')
|
||||
seen = set()
|
||||
prepared = []
|
||||
for package in request['packages']:
|
||||
artifact.field_set(package, ['name', 'identity', 'owner', 'record', 'reason', 'paths', 'removed_paths', 'path_owners'], ['inherited'])
|
||||
name = package['name']
|
||||
require(isinstance(name, str) and name and name not in seen and
|
||||
all(c.isascii() and (c.isalnum() or c in '@._+-') for c in name), 'Invalid or duplicate DB package')
|
||||
seen.add(name)
|
||||
require(artifact.digest(package['identity']) and isinstance(package['owner'], str) and package['owner'], 'Missing package provenance')
|
||||
require(type(package['reason']) is int and package['reason'] in (0, 1), 'Invalid install reason')
|
||||
record = Path(package['record'])
|
||||
protected_directory(record)
|
||||
original = {}
|
||||
for filename in ('desc', 'files', 'mtree'):
|
||||
source = record / filename
|
||||
require(stat.S_ISREG(source.lstat().st_mode) and source.stat().st_size <= 16 * 1024 * 1024, 'Invalid original record')
|
||||
original[filename] = source.read_bytes()
|
||||
desc = artifact.alpm_fields(original['desc'])
|
||||
require(desc.get('%NAME%') == [name] and len(desc.get('%VERSION%', [])) == 1, 'Original DB identity mismatch')
|
||||
version = desc['%VERSION%'][0]
|
||||
require(version and '/' not in version and '\0' not in version and '\n' not in version, 'Invalid DB version')
|
||||
original_files = artifact.alpm_fields(original['files'])
|
||||
require(set(original_files) <= {'%FILES%', '%BACKUP%'}, 'Unknown ALPM file-list field')
|
||||
listed = original_files.get('%FILES%', [])
|
||||
normalized = {}
|
||||
for path in listed:
|
||||
canonical = artifact.image_path('/' + path.rstrip('/'))
|
||||
require(canonical not in normalized, 'Aliased original package paths')
|
||||
normalized[canonical] = path
|
||||
paths = package['paths']
|
||||
removed = package['removed_paths']
|
||||
require(isinstance(paths, list) and all(isinstance(p, str) for p in paths) and len(set(paths)) == len(paths), 'Invalid effective paths')
|
||||
require(isinstance(removed, list) and all(isinstance(p, str) for p in removed) and len(set(removed)) == len(removed), 'Invalid removed paths')
|
||||
removed = set(removed)
|
||||
retained = set()
|
||||
generated = {}
|
||||
inherited = package.get('inherited')
|
||||
if inherited is not None:
|
||||
artifact.field_set(inherited, ['adapter', 'hashes', 'lifecycle', 'absent'])
|
||||
require(inherited['adapter'] == 'legacy-managed-base-v0' and
|
||||
inherited['hashes'] == {k: hash_bytes(v) for k, v in original.items()},
|
||||
'Inherited ALPM records changed')
|
||||
require(isinstance(inherited['lifecycle'], dict) and isinstance(inherited['absent'], list), 'Invalid inherited paths')
|
||||
retained = set(inherited['lifecycle']) | set(inherited['absent'])
|
||||
require(len(set(inherited['absent'])) == len(inherited['absent']) and
|
||||
not set(inherited['lifecycle']) & set(inherited['absent']) and retained <= normalized.keys(),
|
||||
'Invalid inherited path accounting')
|
||||
for path, runtime in inherited['lifecycle'].items():
|
||||
immutable = (path == '/usr' or path.startswith('/usr/')) and not (
|
||||
path == '/usr/local' or path.startswith('/usr/local/'))
|
||||
require(normalized[path] == runtime and not immutable,
|
||||
'Invalid inherited lifecycle classification')
|
||||
for path in inherited['absent']:
|
||||
require((path == '/usr' or path.startswith('/usr/')) and
|
||||
path != '/usr/local' and not path.startswith('/usr/local/'), 'Invalid absent immutable path')
|
||||
value = artifact.objects.input_object(root, artifact.objects.relative(path))
|
||||
if value is not None:
|
||||
require(finalizer is not None, 'Inherited absent path is present before finalization')
|
||||
generated[path] = value
|
||||
require(not set(paths) & removed and not (set(paths) | removed) & retained and
|
||||
set(paths) | removed | retained == normalized.keys(),
|
||||
'Effective package list does not account for every original path')
|
||||
for path in removed:
|
||||
require(artifact.objects.input_object(root, artifact.objects.relative(path)) is None,
|
||||
'Removed package path still exists in the effective tree')
|
||||
owners = package['path_owners']
|
||||
require(isinstance(owners, dict) and owners.keys() == set(paths), 'Incomplete effective content ownership')
|
||||
for owner in owners.values():
|
||||
artifact.field_set(owner, ['layer', 'package'])
|
||||
require(isinstance(owner['layer'], str) and owner['layer'] and
|
||||
(owner['package'] is None or (isinstance(owner['package'], str) and owner['package'])), 'Invalid effective owner')
|
||||
# Validate the original request partition first, then record newly
|
||||
# generated objects as effective paths. Never mutate the saved request.
|
||||
retained -= generated.keys()
|
||||
paths = list(paths) + list(generated)
|
||||
effective = []
|
||||
lines = ['#mtree\n']
|
||||
if retained:
|
||||
effective.extend(normalized[path] for path in sorted(retained))
|
||||
lines.extend(inherited_mtree(original['mtree'], {normalized[path].rstrip('/') for path in retained}))
|
||||
objects = {}
|
||||
for path in sorted(paths):
|
||||
rel = artifact.objects.relative(path)
|
||||
artifact.objects.safe_parent(root, rel)
|
||||
value = artifact.objects.identity(root / rel)
|
||||
runtime = runtime_path(path)
|
||||
effective.append(runtime + ('/' if value['kind'] == 'directory' else ''))
|
||||
objects[path] = value
|
||||
lines.append(mtree(root, path, value))
|
||||
backups = []
|
||||
for backup in original_files.get('%BACKUP%', []):
|
||||
parts = backup.split('\t')
|
||||
require(len(parts) == 2, 'Invalid original backup record')
|
||||
image = artifact.image_path('/' + parts[0])
|
||||
require(image in normalized, 'Backup outside original package file list')
|
||||
if image in removed:
|
||||
continue
|
||||
if image in retained:
|
||||
backups.append(backup)
|
||||
continue
|
||||
require(objects[image]['kind'] == 'file', 'Backup no longer a regular file')
|
||||
with (root / artifact.objects.relative(image)).open('rb') as stream:
|
||||
checksum = hashlib.file_digest(stream, 'md5').hexdigest()
|
||||
backups.append(runtime_path(image) + '\t' + checksum)
|
||||
desc['%REASON%'] = [str(package['reason'])]
|
||||
desc['%INSTALLDATE%'] = ['0']
|
||||
fields = {'%FILES%': sorted(effective)}
|
||||
if backups:
|
||||
fields['%BACKUP%'] = sorted(backups)
|
||||
transformed = {'desc': encode(desc), 'files': encode(fields),
|
||||
'mtree': gzip.compress(''.join(lines).encode('utf-8'), mtime=0)}
|
||||
prepared.append((package, name + '-' + version, original, transformed, objects, generated))
|
||||
# All path/record checks finish before creating the output. Failed output is
|
||||
# never a replacement for the current deployment database.
|
||||
output.mkdir(mode=0o700)
|
||||
(output / 'local').mkdir()
|
||||
(output / 'originals').mkdir()
|
||||
(output / 'local/ALPM_DB_VERSION').write_text('9\n')
|
||||
ledger = []
|
||||
for package, directory, original, transformed, objects, generated in prepared:
|
||||
destination = output / 'local' / directory
|
||||
destination.mkdir()
|
||||
retained = output / 'originals' / package['identity']
|
||||
retained.mkdir()
|
||||
for filename, raw in transformed.items():
|
||||
(destination / filename).write_bytes(raw)
|
||||
for filename, raw in original.items():
|
||||
(retained / filename).write_bytes(raw)
|
||||
ledger.append(dict(package=package['name'], identity=package['identity'], owner=package['owner'],
|
||||
adapter='effective-alpm-v0', original={k: hash_bytes(v) for k, v in original.items()},
|
||||
effective={k: hash_bytes(v) for k, v in transformed.items()},
|
||||
removed_paths=sorted(package['removed_paths']), inherited=package.get('inherited'),
|
||||
generated={path: dict(finalizer_sha256=finalizer, object=value) for path, value in generated.items()},
|
||||
path_owners=package['path_owners'], objects=objects))
|
||||
(output / 'transformations.json').write_text(json.dumps(dict(version=0, packages=ledger),
|
||||
sort_keys=True, separators=(',', ':'), ensure_ascii=False) + '\n')
|
||||
# Runtime read-only package queries must not inherit the worker's 0077 umask.
|
||||
for parent, directories, leaves in os.walk(output):
|
||||
for name in directories:
|
||||
os.chmod(Path(parent) / name, 0o755)
|
||||
for name in leaves:
|
||||
os.chmod(Path(parent) / name, 0o644)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
require(len(sys.argv) == 4, 'Usage: package_db.py COMPOSED_ROOT NEW_OUTPUT REQUEST')
|
||||
with open(sys.argv[3]) as stream:
|
||||
request = json.load(stream, object_pairs_hook=artifact.pairs, parse_float=artifact.reject_number,
|
||||
parse_constant=artifact.reject_number)
|
||||
assemble(Path(sys.argv[1]), Path(sys.argv[2]), request)
|
||||
255
src/artifact.rs
Normal file
255
src/artifact.rs
Normal file
|
|
@ -0,0 +1,255 @@
|
|||
//! Conversion of the offline artifact checker's result to engine inputs.
|
||||
//! Signature verification and protected checkout creation belong to the service;
|
||||
//! this reader does not turn an arbitrary directory into a trusted layer.
|
||||
use crate::{paths, selection};
|
||||
use archipelago_contracts::{LayerInput, LayerKind};
|
||||
use serde_json::Value;
|
||||
use std::{collections::{BTreeMap, BTreeSet}, path::{Path, PathBuf}};
|
||||
|
||||
pub const CHECKER: &str = include_str!("../artifact.py");
|
||||
|
||||
pub struct Payload {
|
||||
pub path: String,
|
||||
pub package: Option<String>,
|
||||
pub object: paths::Object,
|
||||
pub source: paths::Source,
|
||||
}
|
||||
|
||||
pub struct Artifact {
|
||||
pub layer: selection::Layer,
|
||||
pub manifest: Value,
|
||||
pub lock: Value,
|
||||
pub lock_sha256: String,
|
||||
pub payload: Vec<Payload>,
|
||||
/// Original records remain separate from the effective runtime database.
|
||||
pub alpm: BTreeMap<String, PathBuf>,
|
||||
}
|
||||
|
||||
/// Validate constraints which refer to other selected manifests before any tree
|
||||
/// effects. Package/ABI evidence is not inferred from a matching logical ID.
|
||||
pub fn validate_selection(artifacts: &[Artifact], architecture: &str) -> Result<Vec<selection::Ownership>, String> {
|
||||
let layers: Vec<_> = artifacts.iter().map(|a| a.layer.clone()).collect();
|
||||
let ownership = selection::plan(&layers, architecture).map_err(|e| format!("Layer selection: {e:?}"))?;
|
||||
let core = artifacts.iter().find(|a| a.layer.header.kind == LayerKind::Core).ok_or("Missing Core")?;
|
||||
let purpose = artifacts.iter().find(|a| a.layer.header.kind == LayerKind::Purpose);
|
||||
validate_compatibility(artifacts, &core.layer.id, purpose.map(|p| p.layer.id.as_str()))?;
|
||||
Ok(ownership)
|
||||
}
|
||||
|
||||
pub(crate) fn validate_compatibility(artifacts: &[Artifact], core: &str, purpose: Option<&str>) -> Result<(), String> {
|
||||
for artifact in artifacts {
|
||||
let policy = &artifact.manifest["spec"]["compatibility"];
|
||||
if let Some(allowed) = policy.get("core") {
|
||||
if !list(allowed)?.iter().any(|id| id == core) { return Err(format!("{} rejects selected Core", artifact.layer.id)); }
|
||||
}
|
||||
if let Some(allowed) = policy.get("purpose") {
|
||||
let ids = list(allowed)?;
|
||||
if !purpose.is_some_and(|p| ids.iter().any(|id| id == p)) {
|
||||
return Err(format!("{} requires a compatible Purpose", artifact.layer.id));
|
||||
}
|
||||
}
|
||||
// Kernel constraints require an actual ABI evidence adapter. Merely
|
||||
// comparing two declarations would accept equally false claims.
|
||||
if policy.get("kernel").is_some() {
|
||||
return Err("Kernel-bound artifacts require verified kernel ABI evidence".into());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn normalized_path(path: &str) -> Result<String, String> {
|
||||
if !path.starts_with('/') || path.contains('\0') ||
|
||||
path.split('/').skip(1).any(|p| p.is_empty() || p == "." || p == "..") {
|
||||
return Err("Invalid runtime path".into());
|
||||
}
|
||||
for (alias, target) in [("/bin", "/usr/bin"), ("/sbin", "/usr/bin"),
|
||||
("/lib", "/usr/lib"), ("/lib64", "/usr/lib"), ("/etc", "/usr/etc")] {
|
||||
if path == alias { return Ok(target.into()); }
|
||||
if let Some(suffix) = path.strip_prefix(&format!("{alias}/")) { return Ok(format!("{target}/{suffix}")); }
|
||||
}
|
||||
Ok(path.into())
|
||||
}
|
||||
|
||||
/// Expand exact manifest permissions once. Aliased duplicate targets must not
|
||||
/// acquire a second authorization through a different runtime spelling.
|
||||
pub fn permissions(artifact: &Artifact) -> Result<BTreeMap<String, paths::Permission>, String> {
|
||||
let mut result = BTreeMap::new();
|
||||
let Some(entries) = artifact.manifest["spec"].get("overrides") else { return Ok(result); };
|
||||
for entry in entries.as_array().ok_or("Invalid overrides")? {
|
||||
let operation = match text(entry,"operation")? {
|
||||
"replace-file" => paths::Operation::ReplaceFile,
|
||||
"replace-symlink" => paths::Operation::ReplaceSymlink,
|
||||
"change-type" => paths::Operation::ChangeType,
|
||||
"delete-path" => paths::Operation::DeletePath,
|
||||
"set-metadata" => paths::Operation::SetMetadata,
|
||||
_ => return Err("Unknown override operation".into()),
|
||||
};
|
||||
let owner = &entry["expected_owner"];
|
||||
let expected_owner = paths::Owner { layer:text(owner,"layer")?.into(),
|
||||
package:owner.get("package").map(|_| text(owner,"package").map(str::to_owned)).transpose()? };
|
||||
let mut hashes = BTreeMap::new();
|
||||
if let Some(values) = entry.get("expected_sha256") {
|
||||
for (path, digest) in values.as_object().ok_or("Invalid expected digests")? {
|
||||
if hashes.insert(normalized_path(path)?, digest.as_str().ok_or("Invalid expected digest")?.to_owned()).is_some() {
|
||||
return Err("Duplicate normalized digest path".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
for path in list(&entry["paths"])? {
|
||||
let path = normalized_path(&path)?;
|
||||
let permission = paths::Permission { operation, expected_owner:expected_owner.clone(),
|
||||
expected_sha256:hashes.remove(&path), reason:text(entry,"reason")?.into() };
|
||||
if result.insert(path, permission).is_some() { return Err("Duplicate normalized override path".into()); }
|
||||
}
|
||||
if !hashes.is_empty() { return Err("Expected digest outside override path list".into()); }
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn text<'a>(value: &'a Value, field: &str) -> Result<&'a str, String> {
|
||||
value[field].as_str().filter(|s| !s.is_empty()).ok_or_else(|| format!("Missing or invalid {field}"))
|
||||
}
|
||||
fn list(value: &Value) -> Result<Vec<String>, String> {
|
||||
value.as_array().ok_or("Expected string array")?.iter().map(|s|
|
||||
s.as_str().filter(|s| !s.is_empty()).map(str::to_owned).ok_or("Invalid string array entry".into())).collect()
|
||||
}
|
||||
fn optional_list(value: &Value, field: &str) -> Result<Vec<String>, String> {
|
||||
match value.get(field) { Some(value) => list(value), None => Ok(Vec::new()) }
|
||||
}
|
||||
fn number(value: &Value, field: &str) -> Result<u32, String> {
|
||||
value[field].as_u64().and_then(|n| n.try_into().ok()).ok_or_else(|| format!("Invalid numeric {field}"))
|
||||
}
|
||||
fn hex(value: &str) -> Result<Vec<u8>, String> {
|
||||
if value.len() % 2 != 0 || !value.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) {
|
||||
return Err("Invalid hexadecimal attribute".into());
|
||||
}
|
||||
value.as_bytes().chunks_exact(2).map(|pair| u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16)
|
||||
.map_err(|_| "Invalid hexadecimal attribute".into())).collect()
|
||||
}
|
||||
pub(crate) fn object(value: &Value) -> Result<paths::Object, String> {
|
||||
let kind = match text(value, "kind")? {
|
||||
"directory" => paths::Kind::Directory,
|
||||
"file" => paths::Kind::File { sha256: text(value, "sha256")?.into() },
|
||||
"symlink" => paths::Kind::Symlink { target: text(value, "target")?.into() },
|
||||
_ => return Err("Unsupported payload object type".into()),
|
||||
};
|
||||
let xattrs = value["xattrs"].as_object().ok_or("Missing object attributes")?.iter().map(|(key, value)|
|
||||
Ok((key.clone(), hex(value.as_str().ok_or("Invalid attribute value")?)?))).collect::<Result<_, String>>()?;
|
||||
Ok(paths::Object { kind, mode:number(value,"mode")?, uid:number(value,"uid")?, gid:number(value,"gid")?, xattrs })
|
||||
}
|
||||
fn beneath(root: &Path, relative: &str) -> Result<PathBuf, String> {
|
||||
if !root.is_absolute() || relative.starts_with('/') || relative.contains('\0') ||
|
||||
relative.split('/').any(|part| part.is_empty() || part == "." || part == "..") {
|
||||
return Err("Invalid protected artifact path".into());
|
||||
}
|
||||
Ok(root.join(relative))
|
||||
}
|
||||
|
||||
/// `checked` is the exact output of CHECKER running over the supplied protected
|
||||
/// authenticated checkout. The caller must not accept this value over D-Bus.
|
||||
pub fn read_checked(root: &Path, commit: &str, checked: Value) -> Result<Artifact, String> {
|
||||
if checked["version"].as_u64() != Some(0) { return Err("Unsupported artifact checker protocol".into()); }
|
||||
if !archipelago_contracts::system_bus::checksum(commit) { return Err("Invalid layer commit".into()); }
|
||||
let manifest = archipelago_contracts::layer::validate(&checked["manifest"].to_string())?;
|
||||
let spec = &manifest["spec"];
|
||||
let kind = match text(spec,"type")? {
|
||||
"core" => LayerKind::Core, "purpose" => LayerKind::Purpose, "overlay" => LayerKind::Overlay,
|
||||
_ => return Err("Invalid layer kind".into()),
|
||||
};
|
||||
let lock = checked["lock"].clone();
|
||||
if lock["version"].as_u64() != Some(0) { return Err("Unsupported private layer lock".into()); }
|
||||
let snapshot = text(&lock,"snapshot_id")?;
|
||||
let lock_sha256 = text(&checked,"lock_sha256")?.to_owned();
|
||||
if !archipelago_contracts::system_bus::checksum(snapshot) || !archipelago_contracts::system_bus::checksum(&lock_sha256) {
|
||||
return Err("Invalid snapshot/lock identity".into());
|
||||
}
|
||||
if lock["architecture"] != spec["architecture"] { return Err("Locked architecture mismatch".into()); }
|
||||
let mut payloads = Vec::new();
|
||||
let mut names = BTreeMap::new();
|
||||
let mut alpm = BTreeMap::new();
|
||||
for package in checked["packages"].as_array().ok_or("Missing package index")? {
|
||||
let name = text(package,"name")?.to_owned();
|
||||
let identity = text(package,"identity")?.to_owned();
|
||||
if names.insert(identity.clone(), name.clone()).is_some() || alpm.contains_key(&name) {
|
||||
return Err("Duplicate package index entry".into());
|
||||
}
|
||||
let record = text(package,"alpm")?;
|
||||
if record != format!("metadata/alpm/{identity}") { return Err("Invalid original record namespace".into()); }
|
||||
alpm.insert(name.clone(), beneath(root, record)?);
|
||||
payloads.push(selection::Package { name, identity, dependencies:list(&package["dependencies"])? });
|
||||
}
|
||||
let policy = &spec["compatibility"];
|
||||
let layer = selection::Layer {
|
||||
id:text(&manifest["metadata"],"name")?.into(), commit:commit.into(),
|
||||
header:LayerInput { kind, snapshot_id:snapshot.into(), architecture:text(spec,"architecture")?.into() },
|
||||
requires:optional_list(policy,"requires")?, before:optional_list(policy,"before")?,
|
||||
after:optional_list(policy,"after")?, conflicts:optional_list(policy,"conflicts")?,
|
||||
packages:list(&lock["requirements"])?, payload:payloads,
|
||||
};
|
||||
let mut payload = Vec::new();
|
||||
let mut seen = BTreeSet::new();
|
||||
for row in checked["objects"].as_array().ok_or("Missing payload index")? {
|
||||
let path = text(row,"path")?.to_owned();
|
||||
let package = match row.get("package") {
|
||||
Some(Value::Null) => None,
|
||||
Some(Value::String(id)) => Some(names.get(id).ok_or("Unknown indexed package")?.clone()),
|
||||
_ => return Err("Invalid package ownership".into()),
|
||||
};
|
||||
if !seen.insert((package.clone(), path.clone())) { return Err("Duplicate payload object".into()); }
|
||||
let relative = text(row,"source")?;
|
||||
beneath(root, relative)?;
|
||||
payload.push(Payload { path, package, object:object(&row["object"])?,
|
||||
source:paths::Source { root:root.into(), path:format!("/{relative}") } });
|
||||
}
|
||||
Ok(Artifact { layer, manifest, lock, lock_sha256, payload, alpm })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn artifact(id: &str, kind: &str) -> Artifact {
|
||||
read_checked(Path::new("/protected/layer"), &"a".repeat(64), json!({
|
||||
"version":0, "manifest":{"apiVersion":"archipelago/v1", "kind":"Layer",
|
||||
"metadata":{"name":id,"version":"1.0.0"}, "spec":{"type":kind,"architecture":"x86_64"}},
|
||||
"lock":{"version":0,"snapshot_id":"b".repeat(64),"architecture":"x86_64","requirements":[]},
|
||||
"lock_sha256":"c".repeat(64), "packages":[], "objects":[]
|
||||
})).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn logical_core_constraints_and_absent_purpose_are_enforced() {
|
||||
let core = artifact("core", "core");
|
||||
let mut overlay = artifact("overlay", "overlay");
|
||||
overlay.manifest["spec"]["compatibility"] = json!({"core":["different"]});
|
||||
assert!(validate_selection(&[core, overlay], "x86_64").is_err());
|
||||
let core = artifact("core", "core");
|
||||
let mut overlay = artifact("overlay", "overlay");
|
||||
overlay.manifest["spec"]["compatibility"] = json!({"core":["core"],"purpose":["desktop"]});
|
||||
assert!(validate_selection(&[core, overlay], "x86_64").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalized_override_aliases_cannot_authorize_twice() {
|
||||
let mut overlay = artifact("overlay", "overlay");
|
||||
overlay.manifest["spec"]["overrides"] = json!([
|
||||
{"operation":"replace-file","paths":["/bin/example","/usr/bin/example"],
|
||||
"expected_owner":{"layer":"core"},"reason":"replacement"}
|
||||
]);
|
||||
assert!(permissions(&overlay).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expected_hash_follows_vendor_path_normalization() {
|
||||
let mut overlay = artifact("overlay", "overlay");
|
||||
overlay.manifest["spec"]["overrides"] = json!([
|
||||
{"operation":"replace-file","paths":["/etc/example"],
|
||||
"expected_sha256":{"/etc/example":"d".repeat(64)},
|
||||
"expected_owner":{"layer":"core","package":"example"},"reason":"vendor default"}
|
||||
]);
|
||||
let values = permissions(&overlay).unwrap();
|
||||
assert_eq!(values["/usr/etc/example"].expected_sha256, Some("d".repeat(64)));
|
||||
assert_eq!(values["/usr/etc/example"].expected_owner.package.as_deref(), Some("example"));
|
||||
}
|
||||
}
|
||||
212
src/base.rs
Normal file
212
src/base.rs
Normal file
|
|
@ -0,0 +1,212 @@
|
|||
//! Typed result of scanning authenticated legacy base checkouts.
|
||||
//! Authentication and scanner execution belong to the service worker.
|
||||
use crate::{artifact, paths};
|
||||
use serde_json::Value;
|
||||
use std::{collections::{BTreeMap, BTreeSet}, path::{Path, PathBuf}};
|
||||
|
||||
pub const SCANNER: &str = include_str!("../base.py");
|
||||
|
||||
pub struct Package {
|
||||
pub version: String,
|
||||
pub reason: u32,
|
||||
pub identity: String,
|
||||
pub owner: String,
|
||||
pub record: PathBuf,
|
||||
pub paths: BTreeSet<String>,
|
||||
pub absent: BTreeSet<String>,
|
||||
/// Canonical path to original runtime spelling (including directory slash).
|
||||
pub lifecycle: BTreeMap<String, String>,
|
||||
/// Complete adapter evidence, including lifecycle and absent immutable paths.
|
||||
pub evidence: Value,
|
||||
}
|
||||
|
||||
pub struct Base {
|
||||
pub snapshot: String,
|
||||
pub architecture: String,
|
||||
pub purpose: Option<String>,
|
||||
pub index: paths::Index,
|
||||
pub packages: BTreeMap<String, Package>,
|
||||
}
|
||||
|
||||
fn text<'a>(row: &'a Value, key: &str) -> Result<&'a str, String> {
|
||||
row[key].as_str().filter(|s| !s.is_empty()).ok_or_else(|| format!("Invalid base {key}"))
|
||||
}
|
||||
|
||||
fn immutable(path: &str) -> bool {
|
||||
(path == "/usr" || path.starts_with("/usr/")) &&
|
||||
path != "/usr/local" && !path.starts_with("/usr/local/")
|
||||
}
|
||||
|
||||
fn path_set(row: &Value, key: &str) -> Result<BTreeSet<String>, String> {
|
||||
let mut result = BTreeSet::new();
|
||||
for value in row[key].as_array().ok_or_else(|| format!("Missing base {key}"))? {
|
||||
let path = value.as_str().ok_or("Invalid base package path")?;
|
||||
if artifact::normalized_path(path)? != path || !immutable(path) || !result.insert(path.into()) {
|
||||
return Err("Invalid or duplicate base package path".into());
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Only accepts the scanner output for this exact protected image checkout.
|
||||
pub fn read_checked(root: &Path, checked: Value) -> Result<Base, String> {
|
||||
if !root.is_absolute() || checked["version"].as_u64() != Some(0) ||
|
||||
checked["adapter"] != "legacy-managed-base-v0" || checked["core_id"] != "core" {
|
||||
return Err("Invalid legacy base protocol".into());
|
||||
}
|
||||
let snapshot = text(&checked, "snapshot_id")?.to_owned();
|
||||
if !archipelago_contracts::system_bus::checksum(&snapshot) { return Err("Invalid base snapshot".into()); }
|
||||
let architecture = text(&checked, "architecture")?.to_owned();
|
||||
let purpose = match &checked["purpose_id"] {
|
||||
Value::Null => None,
|
||||
Value::String(id) if matches!(id.as_str(), "purpose/desktop/gnome" | "purpose/desktop/kde") => Some(id.clone()),
|
||||
_ => return Err("Invalid base Purpose".into()),
|
||||
};
|
||||
let valid_owner = |id: &str| id == "core" || purpose.as_deref() == Some(id);
|
||||
let mut packages = BTreeMap::new();
|
||||
let database = root.join("usr/lib/archipelago/package-db/local");
|
||||
for row in checked["packages"].as_array().ok_or("Missing base packages")? {
|
||||
let name = text(row, "name")?.to_owned();
|
||||
let version = text(row, "version")?.to_owned();
|
||||
let reason = match row["reason"].as_u64() {
|
||||
Some(n @ 0..=1) => n as u32,
|
||||
_ => return Err("Invalid base install reason".into()),
|
||||
};
|
||||
let identity = text(row, "identity")?.to_owned();
|
||||
let owner = text(row, "owner")?.to_owned();
|
||||
let record = PathBuf::from(text(row, "record")?);
|
||||
if !archipelago_contracts::system_bus::checksum(&identity) || !valid_owner(&owner) ||
|
||||
record.parent() != Some(database.as_path()) ||
|
||||
record.components().any(|c| matches!(c, std::path::Component::ParentDir | std::path::Component::CurDir)) {
|
||||
return Err("Invalid base package provenance".into());
|
||||
}
|
||||
let paths = path_set(row, "paths")?;
|
||||
let absent = path_set(row, "absent_immutable_paths")?;
|
||||
if !absent.is_subset(&paths) { return Err("Absent path outside package membership".into()); }
|
||||
let mut lifecycle = BTreeMap::new();
|
||||
for entry in row["lifecycle_paths"].as_array().ok_or("Missing lifecycle evidence")? {
|
||||
let canonical = text(entry, "canonical_path")?;
|
||||
let runtime = text(entry, "runtime_path")?;
|
||||
if runtime.starts_with('/') || immutable(canonical) ||
|
||||
artifact::normalized_path(&format!("/{}", runtime.trim_end_matches('/')))? != canonical ||
|
||||
lifecycle.insert(canonical.into(), runtime.into()).is_some() {
|
||||
return Err("Invalid or duplicate lifecycle path".into());
|
||||
}
|
||||
}
|
||||
if packages.insert(name, Package { version, reason, identity, owner, record,
|
||||
paths, absent, lifecycle, evidence:row.clone() }).is_some() {
|
||||
return Err("Duplicate base package".into());
|
||||
}
|
||||
}
|
||||
let mut index = paths::Index::new();
|
||||
for row in checked["index"].as_array().ok_or("Missing base index")? {
|
||||
let path = text(row, "path")?;
|
||||
if artifact::normalized_path(path)? != path ||
|
||||
!(path == "/usr" || path.starts_with("/usr/")) ||
|
||||
path == "/usr/local" || path.starts_with("/usr/local/") {
|
||||
return Err("Invalid immutable base path".into());
|
||||
}
|
||||
let layer = text(&row["owner"], "layer")?.to_owned();
|
||||
let package = match &row["owner"]["package"] {
|
||||
Value::Null => None,
|
||||
Value::String(name) if packages.get(name).is_some_and(|p| p.owner == layer) => Some(name.clone()),
|
||||
_ => return Err("Invalid base content owner".into()),
|
||||
};
|
||||
if !valid_owner(&layer) { return Err("Unknown base content layer".into()); }
|
||||
let entry = paths::Entry { object:artifact::object(&row["object"])?, owner:paths::Owner { layer, package } };
|
||||
if index.insert(path.into(), entry).is_some() { return Err("Duplicate base path".into()); }
|
||||
}
|
||||
if packages.is_empty() || !index.contains_key("/usr") { return Err("Incomplete base index".into()); }
|
||||
// Indexed lookups keep this proportional to package membership, rather than
|
||||
// rescanning the entire OS tree for each package.
|
||||
for package in packages.values() {
|
||||
for path in &package.paths {
|
||||
if index.contains_key(path) == package.absent.contains(path) {
|
||||
return Err(format!("Base path presence disagrees with package evidence: {path}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (path, entry) in &index {
|
||||
if let Some(name) = &entry.owner.package {
|
||||
if !packages[name].paths.contains(path) {
|
||||
return Err(format!("Content owner does not declare path: {path}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Base { snapshot, architecture, purpose, index, packages })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn input() -> Value {
|
||||
json!({"version":0,"adapter":"legacy-managed-base-v0","core_id":"core",
|
||||
"snapshot_id":"a".repeat(64),"architecture":"x86_64","purpose_id":null,
|
||||
"packages":[{"name":"example","version":"1-1","reason":1,
|
||||
"identity":"b".repeat(64),"owner":"core",
|
||||
"record":"/protected/usr/lib/archipelago/package-db/local/example-1-1",
|
||||
"paths":["/usr","/usr/missing"],"absent_immutable_paths":["/usr/missing"],
|
||||
"lifecycle_paths":[{"canonical_path":"/var/lib/example","runtime_path":"var/lib/example/"}]}],
|
||||
"index":[{"path":"/usr","owner":{"layer":"core","package":"example"},
|
||||
"object":{"kind":"directory","mode":493,"uid":0,"gid":0,"xattrs":{}}}]})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retains_membership_lifecycle_and_install_reason() {
|
||||
let base = read_checked(Path::new("/protected"), input()).unwrap();
|
||||
let package = &base.packages["example"];
|
||||
assert_eq!(package.reason, 1);
|
||||
assert!(package.absent.contains("/usr/missing"));
|
||||
assert_eq!(package.lifecycle["/var/lib/example"], "var/lib/example/");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_overlay_selection_retains_base_packages_and_paths() {
|
||||
let base = read_checked(Path::new("/protected"), input()).unwrap();
|
||||
let plan = crate::compose::plan_with_base(&base, Path::new("/protected"), &"c".repeat(64), &[]).unwrap();
|
||||
assert_eq!(plan.packages.len(), 1);
|
||||
assert_eq!(plan.packages[0].package, "example");
|
||||
assert_eq!(plan.packages[0].owner, "core");
|
||||
assert_eq!(plan.packages[0].identity, base.packages["example"].identity);
|
||||
assert_eq!(plan.index, base.index);
|
||||
assert!(plan.history.is_empty());
|
||||
assert!(crate::compose::plan_with_base(&base, Path::new("/protected"), "moving-ref", &[]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base_database_request_preserves_dependency_reason() {
|
||||
let temp = std::env::temp_dir().join(format!("archipelago-base-db-{}-{}", std::process::id(),
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()));
|
||||
std::fs::create_dir(&temp).unwrap();
|
||||
let record = temp.join("usr/lib/archipelago/package-db/local/example-1-1");
|
||||
std::fs::create_dir_all(&record).unwrap();
|
||||
std::fs::write(record.join("files"), "%FILES%\nusr/\n\n").unwrap();
|
||||
let mut value = input();
|
||||
value["packages"][0]["record"] = json!(record);
|
||||
value["packages"][0]["paths"] = json!(["/usr"]);
|
||||
value["packages"][0]["absent_immutable_paths"] = json!([]);
|
||||
value["packages"][0]["lifecycle_paths"] = json!([]);
|
||||
let base = read_checked(&temp, value).unwrap();
|
||||
let plan = crate::compose::plan_with_base(&base, &temp, &"c".repeat(64), &[]).unwrap();
|
||||
let request = plan.database_request_with_base(&base, &[]).unwrap();
|
||||
assert_eq!(request["packages"][0]["reason"], 1);
|
||||
assert_eq!(request["packages"][0]["record"], json!(record));
|
||||
assert_eq!(request["packages"][0]["paths"], json!(["/usr"]));
|
||||
std::fs::remove_dir_all(&temp).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_missing_or_contradictory_membership_evidence() {
|
||||
let mut missing = input();
|
||||
missing["packages"][0]["absent_immutable_paths"] = json!([]);
|
||||
assert!(read_checked(Path::new("/protected"), missing).is_err());
|
||||
let mut present = input();
|
||||
present["packages"][0]["absent_immutable_paths"] = json!(["/usr", "/usr/missing"]);
|
||||
assert!(read_checked(Path::new("/protected"), present).is_err());
|
||||
let mut alias = input();
|
||||
alias["packages"][0]["lifecycle_paths"][0]["runtime_path"] = json!("etc/example");
|
||||
assert!(read_checked(Path::new("/protected"), alias).is_err());
|
||||
}
|
||||
}
|
||||
275
src/compose.rs
Normal file
275
src/compose.rs
Normal file
|
|
@ -0,0 +1,275 @@
|
|||
//! Compose an authenticated managed base with an ordered set of indexed overlays.
|
||||
//! Base indexes and sources are service-owned inputs, not client-supplied JSON.
|
||||
use crate::{artifact::{self, Artifact}, paths, selection};
|
||||
use archipelago_contracts::LayerKind;
|
||||
use std::{collections::{BTreeMap, BTreeSet}, path::Path};
|
||||
|
||||
pub struct Plan {
|
||||
pub index: paths::Index,
|
||||
pub history: Vec<paths::Effect>,
|
||||
pub packages: Vec<selection::Ownership>,
|
||||
pub executor: serde_json::Value,
|
||||
}
|
||||
|
||||
impl Plan {
|
||||
/// Build a complete original-to-effective package file selection. The Python
|
||||
/// adapter independently checks it against original ALPM records and hashes
|
||||
/// the actual final tree after finalization.
|
||||
pub fn database_request(&self, artifacts: &[Artifact]) -> Result<serde_json::Value, String> {
|
||||
self.database_request_inner(None, artifacts)
|
||||
}
|
||||
|
||||
pub fn database_request_with_base(&self, base: &crate::base::Base,
|
||||
overlays: &[Artifact]) -> Result<serde_json::Value, String> {
|
||||
self.database_request_inner(Some(base), overlays)
|
||||
}
|
||||
|
||||
fn database_request_inner(&self, base: Option<&crate::base::Base>,
|
||||
artifacts: &[Artifact]) -> Result<serde_json::Value, String> {
|
||||
let sources: BTreeMap<_, _> = artifacts.iter().map(|a|
|
||||
((a.layer.id.as_str(), a.layer.commit.as_str()), a)).collect();
|
||||
let deleted: BTreeSet<_> = self.history.iter().filter(|e| e.before.is_some() && e.after.is_none())
|
||||
.map(|e| e.path.as_str()).collect();
|
||||
let explicit: BTreeSet<_> = artifacts.iter().flat_map(|a| a.layer.packages.iter().map(String::as_str)).collect();
|
||||
let mut records = Vec::new();
|
||||
for package in &self.packages {
|
||||
let inherited = base.and_then(|b| b.packages.get(&package.package))
|
||||
.filter(|p| p.identity == package.identity && p.owner == package.source_layer);
|
||||
let (record, reason) = if let Some(original) = inherited {
|
||||
(&original.record, original.reason)
|
||||
} else {
|
||||
let source = sources.get(&(package.source_layer.as_str(), package.source_commit.as_str()))
|
||||
.ok_or("Missing database source layer")?;
|
||||
(source.alpm.get(&package.package).ok_or("Missing original package record")?,
|
||||
if explicit.contains(package.package.as_str()) {0} else {1})
|
||||
};
|
||||
let raw = std::fs::read_to_string(record.join("files")).map_err(|e| format!("Original file list: {e}"))?;
|
||||
let mut in_files = false;
|
||||
let mut paths = Vec::new();
|
||||
let mut removed = Vec::new();
|
||||
for line in raw.lines() {
|
||||
if line.starts_with('%') && line.ends_with('%') { in_files = line == "%FILES%"; continue; }
|
||||
if !in_files || line.is_empty() { continue; }
|
||||
let path = artifact::normalized_path(&format!("/{}", line.trim_end_matches('/')))?;
|
||||
if inherited.is_some_and(|p| p.lifecycle.contains_key(&path) || p.absent.contains(&path)) { continue; }
|
||||
if self.index.contains_key(&path) { paths.push(path); }
|
||||
else if deleted.contains(path.as_str()) { removed.push(path); }
|
||||
else { return Err(format!("Original package path lacks an effective entry or explicit deletion adapter: {path}")); }
|
||||
}
|
||||
let path_owners: BTreeMap<_, _> = paths.iter().map(|path| {
|
||||
let owner = &self.index[path].owner;
|
||||
(path, serde_json::json!({"layer":owner.layer,"package":owner.package}))
|
||||
}).collect();
|
||||
let mut request = serde_json::json!({"name":package.package,"identity":package.identity,
|
||||
"owner":package.owner,"record":record.to_str().ok_or("Non-UTF-8 record path")?,
|
||||
"reason":reason,"paths":paths,"removed_paths":removed,"path_owners":path_owners});
|
||||
if let Some(original) = inherited {
|
||||
request["inherited"] = serde_json::json!({"adapter":"legacy-managed-base-v0",
|
||||
"hashes":original.evidence["original_hashes"],
|
||||
"lifecycle":original.lifecycle,"absent":original.absent});
|
||||
}
|
||||
records.push(request);
|
||||
}
|
||||
Ok(serde_json::json!({"version":0,"packages":records}))
|
||||
}
|
||||
}
|
||||
|
||||
/// The base is the clean Core/Purpose image, not an earlier overlay deployment.
|
||||
/// Rebuilding from it makes removal and ordering changes use the same path.
|
||||
pub fn plan(base: &paths::Index, base_root: &Path, artifacts: &[Artifact], architecture: &str) -> Result<Plan, String> {
|
||||
let packages = artifact::validate_selection(artifacts, architecture)?;
|
||||
plan_selected(base, base_root, artifacts, packages)
|
||||
}
|
||||
|
||||
/// Compose indexed overlays over an already authenticated, complete base.
|
||||
/// Base packages are a retained closure, not newly resolved archive payloads.
|
||||
/// ALPM validation of the complete effective DB remains mandatory before staging.
|
||||
pub fn plan_with_base(base: &crate::base::Base, base_root: &Path, image: &str,
|
||||
overlays: &[Artifact]) -> Result<Plan, String> {
|
||||
if !archipelago_contracts::system_bus::checksum(image) {
|
||||
return Err("Invalid authenticated base image identity".into());
|
||||
}
|
||||
if overlays.iter().any(|a| a.layer.header.kind != LayerKind::Overlay) {
|
||||
return Err("Only overlays may extend the authenticated base".into());
|
||||
}
|
||||
let mut layers = Vec::new();
|
||||
let mut owners = BTreeMap::<&str, Vec<selection::Package>>::new();
|
||||
for (name, package) in &base.packages {
|
||||
owners.entry(&package.owner).or_default().push(selection::Package {
|
||||
name:name.clone(), identity:package.identity.clone(), dependencies:Vec::new(),
|
||||
});
|
||||
}
|
||||
for (id, kind) in std::iter::once(("core", LayerKind::Core))
|
||||
.chain(base.purpose.as_deref().map(|id| (id, LayerKind::Purpose))) {
|
||||
let payload = owners.remove(id).unwrap_or_default();
|
||||
layers.push(selection::Layer { id:id.into(), commit:image.into(),
|
||||
header:archipelago_contracts::LayerInput { kind, snapshot_id:base.snapshot.clone(),
|
||||
architecture:base.architecture.clone() },
|
||||
requires:Vec::new(), before:Vec::new(), after:Vec::new(), conflicts:Vec::new(),
|
||||
packages:payload.iter().map(|p| p.name.clone()).collect(), payload });
|
||||
}
|
||||
if !owners.is_empty() { return Err("Unknown base package owner".into()); }
|
||||
layers.extend(overlays.iter().map(|a| a.layer.clone()));
|
||||
let packages = selection::plan(&layers, &base.architecture).map_err(|e| format!("Layer selection: {e:?}"))?;
|
||||
artifact::validate_compatibility(overlays, "core", base.purpose.as_deref())?;
|
||||
plan_selected(&base.index, base_root, overlays, packages)
|
||||
}
|
||||
|
||||
fn plan_selected(base: &paths::Index, base_root: &Path, artifacts: &[Artifact],
|
||||
packages: Vec<selection::Ownership>) -> Result<Plan, String> {
|
||||
if !base_root.is_absolute() { return Err("Base checkout must be absolute".into()); }
|
||||
for input in artifacts {
|
||||
if input.manifest["spec"]["packages"]["replacements"].as_array().is_some_and(|v| !v.is_empty()) {
|
||||
return Err("Whole-package replacement executor is not connected".into());
|
||||
}
|
||||
}
|
||||
// Index references, not copies of payload objects. Each file is visited once
|
||||
// here instead of rescanning its entire layer for every selected package.
|
||||
let mut payloads: BTreeMap<_, Vec<_>> = BTreeMap::new();
|
||||
for input in artifacts {
|
||||
for row in &input.payload {
|
||||
if let Some(package) = &row.package {
|
||||
payloads.entry((input.layer.id.as_str(), input.layer.commit.as_str(), package.as_str()))
|
||||
.or_default().push(row);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut owned: BTreeMap<_, Vec<_>> = BTreeMap::new();
|
||||
for package in &packages { owned.entry(package.owner.as_str()).or_default().push(package); }
|
||||
let mut index = base.clone();
|
||||
let mut history = Vec::new();
|
||||
let mut sources: BTreeMap<String, paths::Source> = base.iter()
|
||||
.filter(|(_, entry)| matches!(entry.object.kind, paths::Kind::File { .. }))
|
||||
.map(|(path, _)| (path.clone(), paths::Source { root:base_root.into(), path:path.clone() })).collect();
|
||||
for input in artifacts.iter().filter(|a| a.layer.header.kind == LayerKind::Overlay) {
|
||||
let mut permissions = artifact::permissions(input)?;
|
||||
// Merge only identical shared directories. All other within-layer
|
||||
// collisions fail before inserting a second contribution into the map.
|
||||
let mut package_changes: BTreeMap<String, paths::Change> = BTreeMap::new();
|
||||
for selected in owned.get(input.layer.id.as_str()).into_iter().flatten() {
|
||||
let key = (selected.source_layer.as_str(), selected.source_commit.as_str(), selected.package.as_str());
|
||||
// Metapackages legitimately have no payload objects.
|
||||
for row in payloads.get(&key).into_iter().flatten() {
|
||||
if let Some(previous) = package_changes.get(&row.path) {
|
||||
if row.object.kind == paths::Kind::Directory && previous.object.as_ref() == Some(&row.object) { continue; }
|
||||
return Err(format!("Conflicting package contributions: {}", row.path));
|
||||
}
|
||||
package_changes.insert(row.path.clone(), paths::Change { path:row.path.clone(), object:Some(row.object.clone()),
|
||||
owner:paths::Owner { layer:input.layer.id.clone(), package:Some(selected.package.clone()) },
|
||||
permission:permissions.remove(&row.path) });
|
||||
sources.insert(row.path.clone(), paths::Source { root:row.source.root.clone(), path:row.source.path.clone() });
|
||||
}
|
||||
}
|
||||
let package_changes = package_changes.into_values().collect::<Vec<_>>();
|
||||
check_metadata_changes(input, &index, &package_changes)?;
|
||||
let (next, effects) = paths::apply(&index, &input.layer.id, &package_changes)
|
||||
.map_err(|e| format!("Package paths: {e:?}"))?;
|
||||
index = next;
|
||||
history.extend(effects);
|
||||
let mut changes = Vec::new();
|
||||
for row in input.payload.iter().filter(|row| row.package.is_none()) {
|
||||
changes.push(paths::Change { path:row.path.clone(), object:Some(row.object.clone()),
|
||||
owner:paths::Owner { layer:input.layer.id.clone(), package:None }, permission:permissions.remove(&row.path) });
|
||||
sources.insert(row.path.clone(), paths::Source { root:row.source.root.clone(), path:row.source.path.clone() });
|
||||
}
|
||||
// Delete/metadata operations have no authored payload. All other unused
|
||||
// permissions indicate a missing replacement, not a successful no-op.
|
||||
for (path, permission) in permissions {
|
||||
let object = match permission.operation {
|
||||
paths::Operation::DeletePath => None,
|
||||
paths::Operation::SetMetadata => Some(metadata(input, &index, &path)?),
|
||||
_ => return Err(format!("Override lacks its replacement: {path}")),
|
||||
};
|
||||
changes.push(paths::Change { path, object,
|
||||
owner:paths::Owner { layer:input.layer.id.clone(), package:None }, permission:Some(permission) });
|
||||
}
|
||||
check_metadata_changes(input, &index, &changes)?;
|
||||
let (next, effects) = paths::apply(&index, &input.layer.id, &changes).map_err(|e| format!("Authored paths: {e:?}"))?;
|
||||
index = next;
|
||||
history.extend(effects);
|
||||
}
|
||||
let effects = paths::squash(base, &index, &history).map_err(|e| format!("Composition provenance: {e:?}"))?;
|
||||
let executor = paths::executor_plan(&effects, &sources).map_err(|e| format!("Executor sources: {e:?}"))?;
|
||||
Ok(Plan { index, history, packages, executor })
|
||||
}
|
||||
|
||||
fn check_metadata_changes(input: &Artifact, index: &paths::Index, changes: &[paths::Change]) -> Result<(), String> {
|
||||
for change in changes {
|
||||
if change.permission.as_ref().is_some_and(|p| p.operation == paths::Operation::SetMetadata) &&
|
||||
change.object.as_ref() != Some(&metadata(input, index, &change.path)?) {
|
||||
return Err(format!("Payload differs from declared metadata operation: {}", change.path));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn metadata(input: &Artifact, index: &paths::Index, path: &str) -> Result<paths::Object, String> {
|
||||
let mut object = index.get(path).ok_or("Metadata override target is absent")?.object.clone();
|
||||
let entries = input.manifest["spec"]["overrides"].as_array().ok_or("Missing overrides")?;
|
||||
let mut declaration = None;
|
||||
for entry in entries {
|
||||
if entry["operation"] != "set-metadata" { continue; }
|
||||
for candidate in entry["paths"].as_array().ok_or("Missing metadata paths")? {
|
||||
if artifact::normalized_path(candidate.as_str().ok_or("Invalid metadata path")?)? == path {
|
||||
declaration = Some(&entry["metadata"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
let declaration = declaration.ok_or("Missing metadata declaration")?;
|
||||
if let Some(mode) = declaration.get("mode") {
|
||||
object.mode = u32::from_str_radix(mode.as_str().ok_or("Invalid metadata mode")?, 8)
|
||||
.map_err(|_| "Invalid metadata mode")?;
|
||||
}
|
||||
for field in ["owner", "group"] {
|
||||
if let Some(identity) = declaration.get(field) {
|
||||
if identity != "root" { return Err("Metadata ownership requires locked identity resolution".into()); }
|
||||
if field == "owner" { object.uid = 0; } else { object.gid = 0; }
|
||||
}
|
||||
}
|
||||
Ok(object)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn input(id: &str, kind: &str, hash: Option<&str>) -> Artifact {
|
||||
let mut artifact = artifact::read_checked(Path::new("/protected/source"), &"a".repeat(64), json!({
|
||||
"version":0,"manifest":{"apiVersion":"archipelago/v1","kind":"Layer",
|
||||
"metadata":{"name":id,"version":"1.0.0"},"spec":{"type":kind,"architecture":"x86_64"}},
|
||||
"lock":{"version":0,"snapshot_id":"b".repeat(64),"architecture":"x86_64","requirements":[]},
|
||||
"lock_sha256":"c".repeat(64),"packages":[],"objects":[]
|
||||
})).unwrap();
|
||||
if let Some(hash) = hash {
|
||||
artifact.payload.push(artifact::Payload { path:"/usr/share/example".into(), package:None,
|
||||
object:paths::Object { kind:paths::Kind::File { sha256:hash.into() }, mode:0o644,
|
||||
uid:0,gid:0,xattrs:BTreeMap::new() },
|
||||
source:paths::Source { root:format!("/protected/{id}").into(),path:"/payload/example".into() } });
|
||||
}
|
||||
artifact
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordered_replacement_retains_chain_and_final_source() {
|
||||
let base: paths::Index = ["/usr", "/usr/share"].into_iter().map(|path| (path.into(), paths::Entry {
|
||||
object:paths::Object { kind:paths::Kind::Directory,mode:0o755,uid:0,gid:0,xattrs:BTreeMap::new() },
|
||||
owner:paths::Owner { layer:"core".into(),package:None }
|
||||
})).collect();
|
||||
let core = input("core", "core", None);
|
||||
let first = input("first", "overlay", Some(&"d".repeat(64)));
|
||||
let mut second = input("second", "overlay", Some(&"e".repeat(64)));
|
||||
second.manifest["spec"]["overrides"] = json!([{"operation":"replace-file",
|
||||
"paths":["/usr/share/example"],"expected_owner":{"layer":"first"},
|
||||
"expected_sha256":{"/usr/share/example":"d".repeat(64)},"reason":"explicit replacement"}]);
|
||||
let result = plan(&base, Path::new("/protected/base"), &[core, first, second], "x86_64").unwrap();
|
||||
assert_eq!(result.history.len(), 2);
|
||||
assert_eq!(result.executor["effects"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(result.executor["effects"][0]["before"], serde_json::Value::Null);
|
||||
assert_eq!(result.executor["effects"][0]["source_root"], "/protected/second");
|
||||
let removed = plan(&base, Path::new("/protected/base"), &[input("core", "core", None)], "x86_64").unwrap();
|
||||
assert_eq!(removed.index, base);
|
||||
assert!(removed.executor["effects"].as_array().unwrap().is_empty());
|
||||
assert!(!base.contains_key("/usr/share/example"));
|
||||
}
|
||||
}
|
||||
10
src/lib.rs
10
src/lib.rs
|
|
@ -1,5 +1,15 @@
|
|||
//! Pre-payload checks only. Success is not authorization to publish or merge.
|
||||
|
||||
pub mod selection;
|
||||
pub mod paths;
|
||||
pub mod artifact;
|
||||
pub mod compose;
|
||||
pub mod base;
|
||||
|
||||
/// Internal offline materializer, invoked under the service worker's supervision.
|
||||
pub const MATERIALIZER: &str = include_str!("../materialize.py");
|
||||
pub const PACKAGE_DB: &str = include_str!("../package_db.py");
|
||||
|
||||
use archipelago_contracts::{LayerInput, LayerKind};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
|
|
|
|||
298
src/paths.rs
Normal file
298
src/paths.rs
Normal file
|
|
@ -0,0 +1,298 @@
|
|||
//! Pure effective-path planning. No filesystem effects occur until the complete
|
||||
//! plan has passed; persistence/boot adapters and artifact authentication are
|
||||
//! deliberately outside this internal interface.
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Kind { Directory, File { sha256: String }, Symlink { target: String } }
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Object {
|
||||
pub kind: Kind,
|
||||
pub mode: u32,
|
||||
pub uid: u32,
|
||||
pub gid: u32,
|
||||
pub xattrs: BTreeMap<String, Vec<u8>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Owner { pub layer: String, pub package: Option<String> }
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Entry { pub object: Object, pub owner: Owner }
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Operation { ReplaceFile, ReplaceSymlink, SetMetadata, ChangeType, DeletePath }
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Permission {
|
||||
pub operation: Operation,
|
||||
pub expected_owner: Owner,
|
||||
pub expected_sha256: Option<String>,
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Change {
|
||||
/// Canonical image path: /etc defaults must already be mapped to /usr/etc.
|
||||
pub path: String,
|
||||
pub object: Option<Object>,
|
||||
pub owner: Owner,
|
||||
pub permission: Option<Permission>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Effect {
|
||||
pub path: String,
|
||||
pub before: Option<Entry>,
|
||||
pub after: Option<Entry>,
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Error { pub path: String, pub message: &'static str }
|
||||
pub type Index = BTreeMap<String, Entry>;
|
||||
|
||||
/// Protected checkout root and indexed source path, supplied by the verified
|
||||
/// artifact reader, never by an installed-host D-Bus caller.
|
||||
pub struct Source { pub root: std::path::PathBuf, pub path: String }
|
||||
|
||||
/// Collapse sequential layer effects into one physical base-to-image diff while
|
||||
/// retaining the unsquashed history separately for provenance. Two overlays may
|
||||
/// legitimately replace the same path when each names its immediate owner.
|
||||
pub fn squash(base: &Index, final_index: &Index, history: &[Effect]) -> Result<Vec<Effect>, Error> {
|
||||
let mut replay = base.clone();
|
||||
let mut reasons = BTreeMap::new();
|
||||
for effect in history {
|
||||
if replay.get(&effect.path) != effect.before.as_ref() {
|
||||
return Err(fail(&effect.path, "Broken provenance chain"));
|
||||
}
|
||||
if let Some(after) = &effect.after {
|
||||
replay.insert(effect.path.clone(), after.clone());
|
||||
} else {
|
||||
replay.remove(&effect.path);
|
||||
}
|
||||
reasons.insert(effect.path.clone(), effect.reason.clone());
|
||||
}
|
||||
if &replay != final_index { return Err(fail("/", "Final index disagrees with provenance")); }
|
||||
let paths: BTreeSet<_> = base.keys().chain(final_index.keys()).collect();
|
||||
Ok(paths.into_iter().filter_map(|path| {
|
||||
let before = base.get(path);
|
||||
let after = final_index.get(path);
|
||||
if before.map(|e| &e.object) == after.map(|e| &e.object) { return None; }
|
||||
Some(Effect { path: path.clone(), before: before.cloned(), after: after.cloned(),
|
||||
reason: reasons.get(path).cloned().flatten() })
|
||||
}).collect())
|
||||
}
|
||||
|
||||
fn wire_object(entry: &Entry) -> serde_json::Value {
|
||||
let object = &entry.object;
|
||||
let xattrs: BTreeMap<_, String> = object.xattrs.iter().map(|(key, bytes)|
|
||||
(key, bytes.iter().map(|byte| format!("{byte:02x}")).collect())).collect();
|
||||
let mut value = serde_json::json!({"mode":object.mode,"uid":object.uid,"gid":object.gid,"xattrs":xattrs});
|
||||
match &object.kind {
|
||||
Kind::Directory => value["kind"] = "directory".into(),
|
||||
Kind::File { sha256 } => { value["kind"] = "file".into(); value["sha256"] = sha256.clone().into(); }
|
||||
Kind::Symlink { target } => { value["kind"] = "symlink".into(); value["target"] = target.clone().into(); }
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
/// Serialize effects only after `apply` has checked the full effective topology.
|
||||
/// Sources are required even for metadata-only file operations: no implicit read
|
||||
/// through a path that an earlier operation could replace with a symlink.
|
||||
pub fn executor_plan(effects: &[Effect], sources: &BTreeMap<String, Source>) -> Result<serde_json::Value, Error> {
|
||||
let mut changes = Vec::new();
|
||||
for effect in effects {
|
||||
let mut value = serde_json::json!({"path":effect.path,
|
||||
"before":effect.before.as_ref().map(wire_object),
|
||||
"after":effect.after.as_ref().map(wire_object)});
|
||||
if effect.after.as_ref().is_some_and(|e| matches!(e.object.kind, Kind::File { .. })) {
|
||||
let source = sources.get(&effect.path).ok_or_else(|| fail(&effect.path, "Missing verified payload source"))?;
|
||||
if !source.root.is_absolute() || !source.path.starts_with('/') ||
|
||||
source.path.split('/').skip(1).any(|p| p.is_empty() || p == "." || p == "..") {
|
||||
return Err(fail(&effect.path, "Invalid verified payload path"));
|
||||
}
|
||||
value["source_root"] = source.root.to_str().ok_or_else(|| fail(&effect.path, "Non-UTF-8 source root"))?.into();
|
||||
value["source_path"] = source.path.clone().into();
|
||||
}
|
||||
changes.push(value);
|
||||
}
|
||||
Ok(serde_json::json!({"version":0,"effects":changes}))
|
||||
}
|
||||
|
||||
fn fail(path: &str, message: &'static str) -> Error { Error { path: path.into(), message } }
|
||||
fn canonical(path: &str) -> bool {
|
||||
path.starts_with("/usr/") && path != "/usr/local" && !path.starts_with("/usr/local/") &&
|
||||
path.split('/').skip(1).all(|part| !part.is_empty() && part != "." && part != "..") &&
|
||||
!path.contains('\0')
|
||||
}
|
||||
fn same_type(a: &Kind, b: &Kind) -> bool {
|
||||
std::mem::discriminant(a) == std::mem::discriminant(b)
|
||||
}
|
||||
fn validate_object(path: &str, object: &Object) -> Result<(), Error> {
|
||||
if object.mode & !0o7777 != 0 { return Err(fail(path, "Invalid mode")); }
|
||||
match &object.kind {
|
||||
Kind::File { sha256 } if sha256.len() != 64 || !sha256.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) =>
|
||||
Err(fail(path, "Invalid content digest")),
|
||||
Kind::Symlink { target } if target.is_empty() || target.contains('\0') || object.mode != 0o777 =>
|
||||
Err(fail(path, "Invalid symlink object")),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply one ordered layer to an in-memory copy. On error the caller's index is
|
||||
/// unchanged. The caller retains the returned effects as composition provenance.
|
||||
pub fn apply(index: &Index, layer: &str, changes: &[Change]) -> Result<(Index, Vec<Effect>), Error> {
|
||||
let mut next = index.clone();
|
||||
let mut effects = Vec::new();
|
||||
let mut seen = BTreeSet::new();
|
||||
for change in changes {
|
||||
let path = change.path.as_str();
|
||||
if !canonical(path) || !seen.insert(path) { return Err(fail(path, "Noncanonical or duplicate path")); }
|
||||
if layer.is_empty() || change.owner.layer != layer || change.owner.package.as_ref().is_some_and(String::is_empty) {
|
||||
return Err(fail(path, "Invalid contribution owner"));
|
||||
}
|
||||
if let Some(object) = &change.object { validate_object(path, object)?; }
|
||||
let before = next.get(path).cloned();
|
||||
// A shared directory is not a replacement. Later position never grants
|
||||
// file ownership, even when two unrelated files have identical bytes.
|
||||
if let (Some(old), Some(object)) = (&before, &change.object) {
|
||||
if old.object.kind == Kind::Directory && object.kind == Kind::Directory && old.object == *object && change.permission.is_none() {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
match (&before, &change.permission) {
|
||||
(Some(old), Some(permission)) => {
|
||||
if permission.reason.trim().is_empty() || permission.expected_owner != old.owner {
|
||||
return Err(fail(path, "Missing reason or unexpected effective owner"));
|
||||
}
|
||||
if let Some(expected) = &permission.expected_sha256 {
|
||||
if old.object.kind != (Kind::File { sha256: expected.clone() }) {
|
||||
return Err(fail(path, "Expected file digest mismatch"));
|
||||
}
|
||||
}
|
||||
let valid = match (permission.operation, &change.object) {
|
||||
(Operation::DeletePath, None) => true,
|
||||
(Operation::ReplaceFile, Some(new)) => matches!(old.object.kind, Kind::File { .. }) && matches!(new.kind, Kind::File { .. }),
|
||||
(Operation::ReplaceSymlink, Some(new)) => matches!(old.object.kind, Kind::Symlink { .. }) && matches!(new.kind, Kind::Symlink { .. }),
|
||||
(Operation::ChangeType, Some(new)) => !same_type(&old.object.kind, &new.kind),
|
||||
(Operation::SetMetadata, Some(new)) => old.object.kind == new.kind && old.object.xattrs == new.xattrs,
|
||||
_ => false,
|
||||
};
|
||||
if !valid { return Err(fail(path, "Permission does not authorize this operation")); }
|
||||
}
|
||||
(Some(_), None) => return Err(fail(path, "Undeclared path conflict")),
|
||||
(None, Some(_)) => return Err(fail(path, "Override target is absent")),
|
||||
(None, None) if change.object.is_none() => return Err(fail(path, "Deletion target is absent")),
|
||||
_ => (),
|
||||
}
|
||||
let after = change.object.as_ref().map(|object| Entry { object: object.clone(), owner: change.owner.clone() });
|
||||
match &after {
|
||||
Some(entry) => { next.insert(path.into(), entry.clone()); }
|
||||
None => { next.remove(path); }
|
||||
}
|
||||
effects.push(Effect { path: path.into(), before, after,
|
||||
reason: change.permission.as_ref().map(|p| p.reason.clone()) });
|
||||
}
|
||||
// Validate the final topology, including unchanged children. This catches
|
||||
// nonrecursive deletion/type changes and traversals through symlink parents.
|
||||
// Physical execution must also use no-follow operations and explicit ordering.
|
||||
for path in next.keys() {
|
||||
let mut parent = path.as_str();
|
||||
while let Some((prefix, _)) = parent.rsplit_once('/') {
|
||||
if prefix.is_empty() { break; }
|
||||
if !next.get(prefix).is_some_and(|entry| entry.object.kind == Kind::Directory) {
|
||||
return Err(fail(path, "Parent is absent or is not an explicit directory"));
|
||||
}
|
||||
parent = prefix;
|
||||
}
|
||||
}
|
||||
// A file-deletion list must not disguise removal of an entire lower package.
|
||||
let mut retained = BTreeMap::new();
|
||||
for (path, entry) in index {
|
||||
if entry.object.kind == Kind::Directory { continue; }
|
||||
if let Some(package) = entry.owner.package.as_deref() {
|
||||
let present = retained.entry(package).or_insert(false);
|
||||
*present |= next.contains_key(path);
|
||||
}
|
||||
}
|
||||
for (package, present) in retained {
|
||||
if !present {
|
||||
return Err(fail(package, "File operations cannot remove a lower package"));
|
||||
}
|
||||
}
|
||||
Ok((next, effects))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn shared_directory_does_not_hide_complete_package_deletion() {
|
||||
let mut index = base();
|
||||
let package_owner = Owner { layer:"core".into(), package:Some("example".into()) };
|
||||
index.get_mut("/usr/share").unwrap().owner = package_owner.clone();
|
||||
index.insert("/usr/share/file".into(), Entry {
|
||||
object:object(Kind::File { sha256:"a".repeat(64) }), owner:package_owner.clone() });
|
||||
let deletion = Change { path:"/usr/share/file".into(), object:None, owner:owner("overlay"),
|
||||
permission:Some(Permission { operation:Operation::DeletePath, expected_owner:package_owner.clone(),
|
||||
expected_sha256:None, reason:"explicit deletion".into() }) };
|
||||
assert!(apply(&index, "overlay", &[deletion.clone()]).is_err());
|
||||
index.insert("/usr/share/retained".into(), Entry {
|
||||
object:object(Kind::File { sha256:"b".repeat(64) }), owner:package_owner });
|
||||
let (next, _) = apply(&index, "overlay", &[deletion]).unwrap();
|
||||
assert!(next.contains_key("/usr/share/retained"));
|
||||
assert!(!next.contains_key("/usr/share/file"));
|
||||
}
|
||||
fn owner(layer: &str) -> Owner { Owner { layer: layer.into(), package: None } }
|
||||
fn object(kind: Kind) -> Object { Object { kind, mode: 0o755, uid: 0, gid: 0, xattrs: BTreeMap::new() } }
|
||||
fn base() -> Index {
|
||||
["/usr", "/usr/share"].into_iter().map(|path| (path.into(), Entry {
|
||||
object: object(Kind::Directory), owner: owner("core"),
|
||||
})).collect()
|
||||
}
|
||||
#[test]
|
||||
fn rejects_traversal_and_implicit_recursive_deletion() {
|
||||
let mut index = base();
|
||||
index.insert("/usr/share/child".into(), Entry { object: object(Kind::File { sha256: "a".repeat(64) }), owner: owner("core") });
|
||||
let change = Change { path: "/usr/share".into(), object: None, owner: owner("overlay"),
|
||||
permission: Some(Permission { operation: Operation::DeletePath, expected_owner: owner("core"), expected_sha256: None, reason: "explicit".into() }) };
|
||||
assert!(apply(&index, "overlay", &[change]).is_err());
|
||||
assert!(index.contains_key("/usr/share/child"));
|
||||
let change = Change { path: "/usr/share/../escape".into(), object: Some(object(Kind::Directory)), owner: owner("overlay"), permission: None };
|
||||
assert!(apply(&index, "overlay", &[change]).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn identical_files_still_require_owner_permission() {
|
||||
let mut index = base();
|
||||
let file = object(Kind::File { sha256: "a".repeat(64) });
|
||||
index.insert("/usr/share/file".into(), Entry { object: file.clone(), owner: owner("core") });
|
||||
let mut change = Change { path: "/usr/share/file".into(), object: Some(file), owner: owner("overlay"), permission: None };
|
||||
assert!(apply(&index, "overlay", &[change.clone()]).is_err());
|
||||
change.permission = Some(Permission { operation: Operation::ReplaceFile, expected_owner: owner("core"), expected_sha256: Some("a".repeat(64)), reason: "reviewed replacement".into() });
|
||||
let (next, effects) = apply(&index, "overlay", &[change]).unwrap();
|
||||
assert_eq!(next["/usr/share/file"].owner.layer, "overlay");
|
||||
assert_eq!(effects[0].before.as_ref().unwrap().owner.layer, "core");
|
||||
}
|
||||
#[test]
|
||||
fn squashing_keeps_original_base_precondition_and_checks_chain() {
|
||||
let index = base();
|
||||
let change = Change { path: "/usr/share/file".into(),
|
||||
object: Some(object(Kind::File { sha256: "a".repeat(64) })),
|
||||
owner: owner("first"), permission: None };
|
||||
let (first, mut history) = apply(&index, "first", &[change]).unwrap();
|
||||
let replace = Change { path: "/usr/share/file".into(),
|
||||
object: Some(object(Kind::File { sha256: "b".repeat(64) })), owner: owner("second"),
|
||||
permission: Some(Permission { operation: Operation::ReplaceFile, expected_owner: owner("first"),
|
||||
expected_sha256: Some("a".repeat(64)), reason: "second overlay replacement".into() }) };
|
||||
let (last, second_history) = apply(&first, "second", &[replace]).unwrap();
|
||||
history.extend(second_history);
|
||||
let collapsed = squash(&index, &last, &history).unwrap();
|
||||
assert_eq!(collapsed.len(), 1);
|
||||
assert_eq!(collapsed[0].before, None);
|
||||
assert_eq!(collapsed[0].after.as_ref().unwrap().owner.layer, "second");
|
||||
history[1].before.as_mut().unwrap().owner = owner("wrong");
|
||||
assert!(squash(&index, &last, &history).is_err());
|
||||
}
|
||||
}
|
||||
225
src/selection.rs
Normal file
225
src/selection.rs
Normal file
|
|
@ -0,0 +1,225 @@
|
|||
//! Ordered selection and effective package ownership for verified layer inputs.
|
||||
//!
|
||||
//! Internal engine types, not an artifact serialization. The artifact reader must
|
||||
//! authenticate commits, check indexes and resolve package dependency expressions
|
||||
//! against the common snapshot before constructing these exact inputs.
|
||||
use archipelago_contracts::{LayerInput, LayerKind};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Layer {
|
||||
pub id: String,
|
||||
pub commit: String,
|
||||
pub header: LayerInput,
|
||||
pub requires: Vec<String>,
|
||||
pub before: Vec<String>,
|
||||
pub after: Vec<String>,
|
||||
pub conflicts: Vec<String>,
|
||||
/// Package names required by this layer, excluding automatically resolved
|
||||
/// dependencies. Dependencies are traversed below to assign effective owners.
|
||||
pub packages: Vec<String>,
|
||||
pub payload: Vec<Package>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Package {
|
||||
pub name: String,
|
||||
/// Immutable identity of the indexed package contribution, including archive
|
||||
/// checksum and adapters. Equality of names/versions is not sufficient.
|
||||
pub identity: String,
|
||||
/// Exact, already resolved package names. No rolling resolution in compose.
|
||||
pub dependencies: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Ownership {
|
||||
pub package: String,
|
||||
pub identity: String,
|
||||
pub owner: String,
|
||||
/// Payload source and semantic owner are distinct after removing a layer.
|
||||
pub source_layer: String,
|
||||
pub source_commit: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
Headers(crate::InputError),
|
||||
InvalidLayer(String),
|
||||
DuplicateLayer(String),
|
||||
MissingLayer { layer: String, required: String },
|
||||
Conflict { layer: String, other: String },
|
||||
Order { earlier: String, later: String },
|
||||
DependencyCycle(String),
|
||||
InvalidPackage { layer: String, package: String },
|
||||
PackageConflict(String),
|
||||
MissingPackage { layer: String, package: String },
|
||||
}
|
||||
|
||||
fn digest(value: &str) -> bool {
|
||||
value.len() == 64 && value.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
|
||||
}
|
||||
|
||||
/// Preserve caller order; never sort the layer list, insert dependencies, or
|
||||
/// silently choose among different payloads with the same package name.
|
||||
pub fn plan(layers: &[Layer], architecture: &str) -> Result<Vec<Ownership>, Error> {
|
||||
if layers.len() > 258 { return Err(Error::InvalidLayer("Layer count exceeds engine limit".into())); }
|
||||
crate::validate_headers(&layers.iter().map(|l| l.header.clone()).collect::<Vec<_>>(), architecture)
|
||||
.map_err(Error::Headers)?;
|
||||
let mut positions = BTreeMap::new();
|
||||
for (index, layer) in layers.iter().enumerate() {
|
||||
if layer.id.is_empty() || !digest(&layer.commit) {
|
||||
return Err(Error::InvalidLayer(layer.id.clone()));
|
||||
}
|
||||
if positions.insert(layer.id.as_str(), index).is_some() {
|
||||
return Err(Error::DuplicateLayer(layer.id.clone()));
|
||||
}
|
||||
}
|
||||
for (index, layer) in layers.iter().enumerate() {
|
||||
for required in &layer.requires {
|
||||
if required == &layer.id || !positions.contains_key(required.as_str()) {
|
||||
return Err(Error::MissingLayer { layer: layer.id.clone(), required: required.clone() });
|
||||
}
|
||||
}
|
||||
for other in &layer.conflicts {
|
||||
if positions.contains_key(other.as_str()) {
|
||||
return Err(Error::Conflict { layer: layer.id.clone(), other: other.clone() });
|
||||
}
|
||||
}
|
||||
// Optional ordering references constrain present layers only. Required
|
||||
// dependencies are explicit in `requires`. Cycles cannot satisfy a strict
|
||||
// order and therefore fail without topological reordering.
|
||||
for other in &layer.before {
|
||||
if positions.get(other.as_str()).is_some_and(|position| index >= *position) {
|
||||
return Err(Error::Order { earlier: layer.id.clone(), later: other.clone() });
|
||||
}
|
||||
}
|
||||
for other in &layer.after {
|
||||
if positions.get(other.as_str()).is_some_and(|position| index <= *position) {
|
||||
return Err(Error::Order { earlier: other.clone(), later: layer.id.clone() });
|
||||
}
|
||||
}
|
||||
}
|
||||
fn visit<'a>(id: &'a str, layers: &'a [Layer], positions: &BTreeMap<&str, usize>,
|
||||
active: &mut BTreeSet<&'a str>, done: &mut BTreeSet<&'a str>) -> Result<(), Error> {
|
||||
if done.contains(id) { return Ok(()); }
|
||||
if !active.insert(id) { return Err(Error::DependencyCycle(id.into())); }
|
||||
for dependency in &layers[positions[id]].requires {
|
||||
visit(dependency, layers, positions, active, done)?;
|
||||
}
|
||||
active.remove(id); done.insert(id);
|
||||
Ok(())
|
||||
}
|
||||
let mut done = BTreeSet::new();
|
||||
for layer in layers {
|
||||
visit(&layer.id, layers, &positions, &mut BTreeSet::new(), &mut done)?;
|
||||
}
|
||||
let mut payloads: BTreeMap<&str, (&Package, &Layer)> = BTreeMap::new();
|
||||
for layer in layers {
|
||||
let mut seen = BTreeSet::new();
|
||||
for package in &layer.payload {
|
||||
let dependencies: BTreeSet<_> = package.dependencies.iter().collect();
|
||||
if package.name.is_empty() || !digest(&package.identity) ||
|
||||
!seen.insert(package.name.as_str()) || dependencies.len() != package.dependencies.len() ||
|
||||
package.dependencies.iter().any(String::is_empty) {
|
||||
return Err(Error::InvalidPackage { layer: layer.id.clone(), package: package.name.clone() });
|
||||
}
|
||||
if let Some((previous, _)) = payloads.get(package.name.as_str()) {
|
||||
if previous.identity != package.identity ||
|
||||
previous.dependencies.iter().collect::<BTreeSet<_>>() != dependencies {
|
||||
return Err(Error::PackageConflict(package.name.clone()));
|
||||
}
|
||||
} else {
|
||||
payloads.insert(package.name.as_str(), (package, layer));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut selected = BTreeMap::new();
|
||||
for layer in layers {
|
||||
let mut pending: Vec<_> = layer.packages.iter().map(String::as_str).collect();
|
||||
let mut visited = BTreeSet::new();
|
||||
while let Some(name) = pending.pop() {
|
||||
if !visited.insert(name) { continue; }
|
||||
let (package, source) = payloads.get(name).ok_or_else(|| Error::MissingPackage {
|
||||
layer: layer.id.clone(), package: name.into(),
|
||||
})?;
|
||||
if positions[source.id.as_str()] > positions[layer.id.as_str()] {
|
||||
return Err(Error::MissingPackage { layer: layer.id.clone(), package: name.into() });
|
||||
}
|
||||
selected.entry(name).or_insert_with(|| Ownership {
|
||||
package: name.into(), identity: package.identity.clone(), owner: layer.id.clone(),
|
||||
source_layer: source.id.clone(), source_commit: source.commit.clone(),
|
||||
});
|
||||
pending.extend(package.dependencies.iter().map(String::as_str));
|
||||
}
|
||||
}
|
||||
// Core/Purpose packages cannot be removed by an Overlay. Their complete input
|
||||
// closures must be declared as requirements by the artifact adapter.
|
||||
for layer in layers.iter().filter(|l| l.header.kind != LayerKind::Overlay) {
|
||||
for package in &layer.payload {
|
||||
if !selected.contains_key(package.name.as_str()) {
|
||||
return Err(Error::InvalidPackage { layer: layer.id.clone(), package: package.name.clone() });
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(selected.into_values().collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn layer(id: &str, kind: LayerKind) -> Layer {
|
||||
Layer { id: id.into(), commit: "a".repeat(64),
|
||||
header: LayerInput { kind, snapshot_id: "snapshot".into(), architecture: "x86_64".into() },
|
||||
requires: vec![], before: vec![], after: vec![], conflicts: vec![], packages: vec![], payload: vec![] }
|
||||
}
|
||||
fn package(name: &str, dependencies: &[&str]) -> Package {
|
||||
Package { name: name.into(), identity: "b".repeat(64),
|
||||
dependencies: dependencies.iter().map(|s| (*s).into()).collect() }
|
||||
}
|
||||
#[test]
|
||||
fn removal_reassigns_shared_dependency_without_modifying_inputs() {
|
||||
let core = layer("core", LayerKind::Core);
|
||||
let mut a = layer("overlay/a", LayerKind::Overlay);
|
||||
let mut b = layer("overlay/b", LayerKind::Overlay);
|
||||
a.packages = vec!["app-a".into()];
|
||||
b.packages = vec!["app-b".into()];
|
||||
a.payload = vec![package("app-a", &["shared"]), package("shared", &[])];
|
||||
b.payload = vec![package("app-b", &["shared"]), package("shared", &[])];
|
||||
let original = b.payload.clone();
|
||||
let first = plan(&[core.clone(), a, b.clone()], "x86_64").unwrap();
|
||||
assert_eq!(first.iter().find(|p| p.package == "shared").unwrap().owner, "overlay/a");
|
||||
let remaining = plan(&[core, b.clone()], "x86_64").unwrap();
|
||||
assert_eq!(remaining.iter().find(|p| p.package == "shared").unwrap().owner, "overlay/b");
|
||||
assert!(!remaining.iter().any(|p| p.package == "app-a"));
|
||||
assert_eq!(b.payload, original);
|
||||
}
|
||||
#[test]
|
||||
fn does_not_reorder_or_add_missing_layers() {
|
||||
let core = layer("core", LayerKind::Core);
|
||||
let mut a = layer("a", LayerKind::Overlay);
|
||||
let b = layer("b", LayerKind::Overlay);
|
||||
a.after.push("b".into());
|
||||
assert!(matches!(plan(&[core.clone(), a.clone(), b.clone()], "x86_64"), Err(Error::Order { .. })));
|
||||
a.after.clear(); a.requires.push("missing".into());
|
||||
assert!(matches!(plan(&[core, a, b], "x86_64"), Err(Error::MissingLayer { .. })));
|
||||
}
|
||||
#[test]
|
||||
fn rejects_conflicting_payload_and_snapshot_before_composition() {
|
||||
let mut core = layer("core", LayerKind::Core);
|
||||
core.packages.push("shared".into()); core.payload.push(package("shared", &[]));
|
||||
let mut overlay = layer("overlay", LayerKind::Overlay);
|
||||
let mut replacement = package("shared", &[]); replacement.identity = "c".repeat(64);
|
||||
overlay.payload.push(replacement);
|
||||
assert!(matches!(plan(&[core.clone(), overlay.clone()], "x86_64"), Err(Error::PackageConflict(_))));
|
||||
overlay.header.snapshot_id = "different".into();
|
||||
assert!(matches!(plan(&[core, overlay], "x86_64"), Err(Error::Headers(crate::InputError::SnapshotMismatch { .. }))));
|
||||
}
|
||||
#[test]
|
||||
fn rejects_required_layer_cycles_without_order_edges() {
|
||||
let core = layer("core", LayerKind::Core);
|
||||
let mut a = layer("a", LayerKind::Overlay);
|
||||
let mut b = layer("b", LayerKind::Overlay);
|
||||
a.requires.push("b".into()); b.requires.push("a".into());
|
||||
assert!(matches!(plan(&[core, a, b], "x86_64"), Err(Error::DependencyCycle(_))));
|
||||
}
|
||||
}
|
||||
96
tests/artifact.py
Normal file
96
tests/artifact.py
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
"""Checked artifact fixtures for the normal pipeline, without layer-code execution."""
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
spec = importlib.util.spec_from_file_location('artifact', Path(__file__).parents[1] / 'artifact.py')
|
||||
reader = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(reader)
|
||||
|
||||
|
||||
class Artifact(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temporary = tempfile.TemporaryDirectory(prefix='archipelago-layer-')
|
||||
self.root = Path(self.temporary.name)
|
||||
(self.root / 'metadata').mkdir()
|
||||
self.file = self.root / 'payload/files/root/usr/share/example'
|
||||
self.file.parent.mkdir(parents=True)
|
||||
self.file.write_bytes(b'indexed payload\n')
|
||||
self.file.chmod(0o644)
|
||||
manifest = dict(apiVersion='archipelago/v1', kind='Layer', metadata=dict(name='overlay/example', version='1.0.0'),
|
||||
spec=dict(type='overlay', architecture='x86_64', files=[dict(
|
||||
path='/usr/share/example', source='example', mode='0644', owner='root', group='root')]))
|
||||
packages = dict(version=0, packages=[])
|
||||
files = dict(version=0, objects=[dict(source='payload/files/root/usr/share/example',
|
||||
path='/usr/share/example', package=None, object=reader.objects.identity(self.file))])
|
||||
self.lock = dict(version=0, snapshot_id='a' * 64, architecture='x86_64', requirements=[],
|
||||
authored_sources={'example': hashlib.sha256(self.file.read_bytes()).hexdigest()},
|
||||
manifest_sha256=self.write('manifest', manifest), packages_sha256=self.write('packages', packages),
|
||||
files_sha256=self.write('files', files))
|
||||
self.write('lock', self.lock)
|
||||
|
||||
def write(self, name, value):
|
||||
raw = json.dumps(value, sort_keys=True).encode()
|
||||
(self.root / ('metadata/' + name + '.json')).write_bytes(raw)
|
||||
return hashlib.sha256(raw).hexdigest()
|
||||
|
||||
def tearDown(self):
|
||||
self.temporary.cleanup()
|
||||
|
||||
def test_indexed_payload_checked_without_execution(self):
|
||||
checked = reader.check(self.root)
|
||||
self.assertEqual(checked['objects'][0]['path'], '/usr/share/example')
|
||||
|
||||
def test_changed_payload_and_extra_objects_rejected(self):
|
||||
self.file.write_bytes(b'changed\n')
|
||||
with self.assertRaises(ValueError):
|
||||
reader.check(self.root)
|
||||
self.file.write_bytes(b'indexed payload\n')
|
||||
self.file.with_name('extra').write_bytes(b'unindexed')
|
||||
with self.assertRaises(ValueError):
|
||||
reader.check(self.root)
|
||||
|
||||
def test_metadata_symlink_is_not_followed(self):
|
||||
original = self.root / 'metadata/manifest.json'
|
||||
original.rename(self.root / 'manifest-outside-metadata')
|
||||
original.symlink_to('../manifest-outside-metadata')
|
||||
with self.assertRaises(ValueError):
|
||||
reader.check(self.root)
|
||||
|
||||
def test_lock_cannot_substitute_a_different_index(self):
|
||||
self.write('files', dict(version=0, objects=[]))
|
||||
with self.assertRaises(ValueError):
|
||||
reader.check(self.root)
|
||||
|
||||
def rebind(self, name, value):
|
||||
self.lock[name + '_sha256'] = self.write(name, value)
|
||||
self.write('lock', self.lock)
|
||||
|
||||
def test_payload_requires_manifest_declaration(self):
|
||||
manifest = json.loads((self.root / 'metadata/manifest.json').read_text())
|
||||
manifest['spec']['files'] = []
|
||||
self.rebind('manifest', manifest)
|
||||
with self.assertRaisesRegex(ValueError, 'does not match manifest'):
|
||||
reader.check(self.root)
|
||||
|
||||
def test_numeric_coercions_rejected_even_with_rebound_index(self):
|
||||
original = json.loads((self.root / 'metadata/files.json').read_text())
|
||||
for number in (False, 0.0, float('nan')):
|
||||
value = json.loads(json.dumps(original))
|
||||
value['objects'][0]['object']['uid'] = number
|
||||
self.rebind('files', value)
|
||||
with self.assertRaises(ValueError):
|
||||
reader.check(self.root)
|
||||
|
||||
def test_authored_source_identity_is_enforced(self):
|
||||
self.lock['authored_sources']['example'] = 'b' * 64
|
||||
self.write('lock', self.lock)
|
||||
with self.assertRaisesRegex(ValueError, 'locked source'):
|
||||
reader.check(self.root)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
56
tests/base.py
Normal file
56
tests/base.py
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
"""Legacy base adapter fixtures, run by the normal release source checks."""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
spec = importlib.util.spec_from_file_location('base', Path(__file__).parents[1] / 'base.py')
|
||||
adapter = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(adapter)
|
||||
|
||||
|
||||
class BaseIndex(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory(prefix='archipelago-base-')
|
||||
self.work = Path(self.temp.name)
|
||||
self.root = self.work / 'image'
|
||||
self.core = self.work / 'core'
|
||||
self.record = self.root / 'usr/lib/archipelago/package-db/local/example-1-1'
|
||||
self.original = self.core / 'metadata/package-index/example-1-1'
|
||||
for record in (self.record, self.original):
|
||||
record.mkdir(parents=True)
|
||||
(record / 'desc').write_text('%NAME%\nexample\n\n%VERSION%\n1-1\n\n')
|
||||
(record / 'files').write_text('%FILES%\nusr/share/example\nvar/lib/example/\nusr/share/absent\n\n')
|
||||
(record / 'mtree').write_bytes(b'original-record-evidence')
|
||||
(self.core / 'metadata/snapshot').write_text('a' * 64 + '\n')
|
||||
(self.root / 'usr/lib/archipelago/snapshot').write_text('a' * 64 + '\n')
|
||||
(self.root / 'usr/share').mkdir()
|
||||
(self.root / 'usr/share/example').write_bytes(b'verified-base-payload')
|
||||
|
||||
def tearDown(self):
|
||||
self.temp.cleanup()
|
||||
|
||||
def test_lifecycle_and_absent_paths_are_retained_not_silently_dropped(self):
|
||||
result = adapter.read_base(self.root, self.core)
|
||||
package = result['packages'][0]
|
||||
self.assertEqual(package['lifecycle_paths'], [dict(runtime_path='var/lib/example/', canonical_path='/var/lib/example')])
|
||||
self.assertEqual(package['absent_immutable_paths'], ['/usr/share/absent'])
|
||||
entry = next(row for row in result['index'] if row['path'] == '/usr/share/example')
|
||||
self.assertEqual(entry['owner'], dict(layer='core', package='example'))
|
||||
before = package['identity']
|
||||
(self.root / 'usr/share/example').write_bytes(b'different-base-payload')
|
||||
self.assertNotEqual(before, adapter.read_base(self.root, self.core)['packages'][0]['identity'])
|
||||
|
||||
def test_referenced_core_version_mismatch_fails(self):
|
||||
(self.original / 'desc').write_text('%NAME%\nexample\n\n%VERSION%\n2-1\n\n')
|
||||
with self.assertRaisesRegex(ValueError, 'replaced a Core package'):
|
||||
adapter.read_base(self.root, self.core)
|
||||
|
||||
def test_snapshot_mismatch_fails_before_indexing(self):
|
||||
(self.core / 'metadata/snapshot').write_text('b' * 64 + '\n')
|
||||
with self.assertRaisesRegex(ValueError, 'snapshot mismatch'):
|
||||
adapter.read_base(self.root, self.core)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
69
tests/materialize.py
Normal file
69
tests/materialize.py
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
"""Filesystem contract fixtures; executed only by the normal release pipeline."""
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
spec = importlib.util.spec_from_file_location('materialize', Path(__file__).parents[1] / 'materialize.py')
|
||||
engine = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(engine)
|
||||
|
||||
|
||||
class Materialization(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temporary = tempfile.TemporaryDirectory(prefix='archipelago-compose-')
|
||||
self.root = Path(self.temporary.name)
|
||||
self.base = self.root / 'base'
|
||||
self.output = self.root / 'output'
|
||||
(self.base / 'usr/share').mkdir(parents=True)
|
||||
self.sources = self.root / 'sources'
|
||||
self.sources.mkdir()
|
||||
(self.sources / 'file').write_bytes(b'new payload\n')
|
||||
|
||||
def tearDown(self):
|
||||
self.temporary.cleanup()
|
||||
|
||||
def file(self, path, before=None):
|
||||
return dict(path=path, before=before, after=engine.identity(self.sources / 'file'),
|
||||
source_root=str(self.sources), source_path='/file')
|
||||
|
||||
def run_plan(self, effects):
|
||||
engine.materialize(self.base, self.output, dict(version=0, effects=effects))
|
||||
|
||||
def test_new_directory_and_file_preserve_exact_metadata(self):
|
||||
os.chmod(self.sources / 'file', 0o4750)
|
||||
os.setxattr(self.sources / 'file', 'user.archipelago', b'fixture')
|
||||
directory = engine.identity(self.base / 'usr/share')
|
||||
self.run_plan([self.file('/usr/share/new/file'),
|
||||
dict(path='/usr/share/new', before=None, after=directory)])
|
||||
self.assertEqual(engine.identity(self.output / 'usr/share/new/file'), engine.identity(self.sources / 'file'))
|
||||
self.assertFalse((self.base / 'usr/share/new').exists())
|
||||
|
||||
def test_replacement_does_not_follow_old_symlink(self):
|
||||
victim = self.root / 'victim'
|
||||
victim.write_bytes(b'keep this\n')
|
||||
link = self.base / 'usr/share/link'
|
||||
link.symlink_to(victim)
|
||||
self.run_plan([self.file('/usr/share/link', engine.identity(link))])
|
||||
self.assertEqual(victim.read_bytes(), b'keep this\n')
|
||||
self.assertTrue(link.is_symlink())
|
||||
self.assertFalse((self.output / 'usr/share/link').is_symlink())
|
||||
|
||||
def test_changed_source_rejected_before_output_creation(self):
|
||||
effect = self.file('/usr/share/file')
|
||||
(self.sources / 'file').write_bytes(b'changed after planning\n')
|
||||
with self.assertRaises(ValueError):
|
||||
self.run_plan([effect])
|
||||
self.assertFalse(self.output.exists())
|
||||
|
||||
def test_no_implicit_recursive_delete(self):
|
||||
(self.base / 'usr/share/retained').write_text('retain')
|
||||
with self.assertRaises(OSError):
|
||||
self.run_plan([dict(path='/usr/share', before=engine.identity(self.base / 'usr/share'), after=None)])
|
||||
self.assertEqual((self.base / 'usr/share/retained').read_text(), 'retain')
|
||||
self.assertEqual((self.output / 'usr/share/retained').read_text(), 'retain')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
118
tests/package_db.py
Normal file
118
tests/package_db.py
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
"""Original/effective record fixtures; normal release pipeline only."""
|
||||
import gzip
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
spec = importlib.util.spec_from_file_location('package_db', Path(__file__).parents[1] / 'package_db.py')
|
||||
adapter = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(adapter)
|
||||
|
||||
|
||||
class EffectiveDatabase(unittest.TestCase):
|
||||
def test_inherited_lifecycle_and_absent_records_are_not_deletions(self):
|
||||
original = self.original.copy()
|
||||
original['files'] = original['files'].replace(b'usr/share/deleted\n', b'usr/share/deleted\nvar/lib/example/\n')
|
||||
original['mtree'] = gzip.compress(b'#mtree\n/set type=dir uid=12 gid=34 mode=750\n./var/lib/example time=123\n./usr/share/deleted type=file size=3\n', mtime=0)
|
||||
for name, raw in original.items():
|
||||
(self.record / name).write_bytes(raw)
|
||||
package = self.request['packages'][0]
|
||||
package['removed_paths'] = []
|
||||
package['inherited'] = dict(adapter='legacy-managed-base-v0',
|
||||
hashes={key: hashlib.sha256(raw).hexdigest() for key, raw in original.items()},
|
||||
lifecycle={'/var/lib/example': 'var/lib/example/'}, absent=['/usr/share/deleted'])
|
||||
output = self.work / 'inherited'
|
||||
adapter.assemble(self.root, output, self.request)
|
||||
local = output / 'local/example-1.0-1'
|
||||
self.assertIn('var/lib/example/', (local / 'files').read_text())
|
||||
self.assertIn('usr/share/deleted', (local / 'files').read_text())
|
||||
mtree = gzip.decompress((local / 'mtree').read_bytes()).decode()
|
||||
self.assertIn('./var/lib/example gid=34 mode=750 time=123 type=dir uid=12', mtree)
|
||||
self.assertFalse((self.root / 'var').exists())
|
||||
ledger = json.loads((output / 'transformations.json').read_text())['packages'][0]
|
||||
self.assertEqual(ledger['removed_paths'], [])
|
||||
self.assertEqual(ledger['inherited'], package['inherited'])
|
||||
(self.root / 'usr/share/deleted').write_bytes(b'generated output\n')
|
||||
with self.assertRaisesRegex(ValueError, 'before finalization'):
|
||||
adapter.assemble(self.root, self.work / 'premature', self.request)
|
||||
self.request['finalizer_sha256'] = 'f' * 64
|
||||
adapter.assemble(self.root, self.work / 'finalized', self.request)
|
||||
final = self.work / 'finalized'
|
||||
mtree = gzip.decompress((final / 'local/example-1.0-1/mtree').read_bytes()).decode()
|
||||
self.assertEqual(mtree.count('./usr/share/deleted '), 1)
|
||||
self.assertIn('sha256digest=' + hashlib.sha256(b'generated output\n').hexdigest(), mtree)
|
||||
ledger = json.loads((final / 'transformations.json').read_text())['packages'][0]
|
||||
self.assertEqual(ledger['generated']['/usr/share/deleted']['finalizer_sha256'], 'f' * 64)
|
||||
(self.record / 'desc').write_bytes(original['desc'] + b'\n')
|
||||
with self.assertRaisesRegex(ValueError, 'records changed'):
|
||||
adapter.assemble(self.root, self.work / 'changed', self.request)
|
||||
|
||||
def setUp(self):
|
||||
self.temporary = tempfile.TemporaryDirectory(prefix='archipelago-alpm-')
|
||||
self.work = Path(self.temporary.name)
|
||||
self.root = self.work / 'root'
|
||||
(self.root / 'usr/etc').mkdir(parents=True)
|
||||
(self.root / 'usr/share').mkdir()
|
||||
(self.root / 'usr/etc/example').write_bytes(b'overridden default\n')
|
||||
(self.root / 'usr/share/space name').symlink_to('literal target')
|
||||
self.record = self.work / 'original'
|
||||
self.record.mkdir()
|
||||
self.original = {
|
||||
'desc': b'%NAME%\nexample\n\n%VERSION%\n1.0-1\n\n%REASON%\n1\n\n%INSTALLDATE%\n1234\n\n',
|
||||
'files': b'%FILES%\netc/example\nusr/share/space name\nusr/share/deleted\n\n%BACKUP%\netc/example\t' + b'0' * 32 + b'\n\n',
|
||||
'mtree': gzip.compress(b'#mtree\n', mtime=0),
|
||||
}
|
||||
for filename, raw in self.original.items():
|
||||
(self.record / filename).write_bytes(raw)
|
||||
self.request = dict(version=0, packages=[dict(name='example', identity='a' * 64, owner='core',
|
||||
record=str(self.record), reason=0, paths=['/usr/etc/example', '/usr/share/space name'],
|
||||
removed_paths=['/usr/share/deleted'], path_owners={
|
||||
'/usr/etc/example': dict(layer='overlay', package=None),
|
||||
'/usr/share/space name': dict(layer='core', package='example')})])
|
||||
|
||||
def tearDown(self):
|
||||
self.temporary.cleanup()
|
||||
|
||||
def test_overridden_backup_and_original_evidence_remain_distinct(self):
|
||||
output = self.work / 'output'
|
||||
adapter.assemble(self.root, output, self.request)
|
||||
local = output / 'local/example-1.0-1'
|
||||
expected = hashlib.md5(b'overridden default\n').hexdigest()
|
||||
self.assertIn('etc/example\t' + expected, (local / 'files').read_text())
|
||||
self.assertNotIn('usr/etc/', (local / 'files').read_text())
|
||||
self.assertNotIn('deleted', (local / 'files').read_text())
|
||||
mtree = gzip.decompress((local / 'mtree').read_bytes()).decode()
|
||||
self.assertIn('./etc/example type=file', mtree)
|
||||
self.assertIn('./usr/share/space\\040name type=link', mtree)
|
||||
self.assertIn('link=literal\\040target', mtree)
|
||||
self.assertIn('time=0.0', mtree)
|
||||
for filename, raw in self.original.items():
|
||||
self.assertEqual((output / 'originals' / ('a' * 64) / filename).read_bytes(), raw)
|
||||
ledger = json.loads((output / 'transformations.json').read_text())['packages'][0]
|
||||
self.assertNotEqual(ledger['original']['files'], ledger['effective']['files'])
|
||||
self.assertEqual(ledger['removed_paths'], ['/usr/share/deleted'])
|
||||
second = self.work / 'second'
|
||||
adapter.assemble(self.root, second, self.request)
|
||||
for filename in ('desc', 'files', 'mtree'):
|
||||
self.assertEqual((local / filename).read_bytes(), (second / 'local/example-1.0-1' / filename).read_bytes())
|
||||
|
||||
def test_missing_accounting_cannot_silently_drop_package_paths(self):
|
||||
self.request['packages'][0]['removed_paths'] = []
|
||||
output = self.work / 'rejected'
|
||||
with self.assertRaisesRegex(ValueError, 'every original path'):
|
||||
adapter.assemble(self.root, output, self.request)
|
||||
self.assertFalse(output.exists())
|
||||
|
||||
def test_symlink_parent_does_not_redirect_effective_file_reads(self):
|
||||
(self.root / 'usr/etc/example').unlink()
|
||||
(self.root / 'usr/etc').rmdir()
|
||||
(self.root / 'usr/etc').symlink_to(self.record)
|
||||
with self.assertRaises(ValueError):
|
||||
adapter.assemble(self.root, self.work / 'rejected', self.request)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Loading…
Add table
Reference in a new issue