#!/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)