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