{_h(_finding_title(finding))}
' + f'{_h(finding.get("remediation", "Review the cited evidence with the platform owner."))}
' + 'Evidence and affected field
' + f'{_h(finding.get("field"))}
' + f'{_h(finding.get("evidence"))}| Target | Resource | Field | Scope | ' + '
|---|
No rendered field changes were recorded.
' + files = ''.join(f'{_h(path)}The correction outcome includes the exact patch, permitted files and rendered fields. ' + 'Delivery and functional recovery are separate stages.
' + html.escape(markdown) + '' + for name, raw in (('report.json', _canonical(report)), ('report.md', markdown.encode()), ('report.html', document.encode())): + _exclusive(output / name, raw) + + +def qualify_and_write(path, output): + path = _safe_path(Path(path)) + report = qualify(path) + raw = _read(path, MAX_DOCUMENT_BYTES) + if _sha(raw) != report['qualification_sha256']: + raise QualificationError('Qualification input changed before report publication') + document = validate('qualification', _json(raw)) + roots = [_relative(path.parent, row['result']['path']).parent for row in document['runs']] + write_report(report, output, protected_directories=roots) + return report diff --git a/plugins/devsecops/src/devsecops/factory/qualification_contracts.py b/plugins/devsecops/src/devsecops/factory/qualification_contracts.py new file mode 100644 index 0000000..8d1d9e4 --- /dev/null +++ b/plugins/devsecops/src/devsecops/factory/qualification_contracts.py @@ -0,0 +1,101 @@ +"""Closed qualification and video contracts; assertions are not live authority.""" +from .contracts import DIGEST, array, document, object_schema + +UTC = {'type': 'string', 'format': 'date-time'} +LABEL = {'type': 'string', 'minLength': 1, 'maxLength': 160} +RELATIVE = {'type': 'string', 'minLength': 1, 'maxLength': 4096, + 'pattern': r'^(?!/)(?!.*(?:^|/)\.\.(?:/|$))[^\u0000\r\n\\]+$'} +REFERENCE = object_schema({'path': RELATIVE, 'sha256': DIGEST, + 'bytes': {'type': 'integer', 'minimum': 1, 'maximum': 1_000_000_000_000}}) +IDENTITIES = object_schema({key + '_sha256': DIGEST for key in + ('scenario', 'assertions', 'config', 'lock', 'package', 'environment')}) +DECISION = {'enum': ['pass', 'fail', 'incomplete']} +SECONDS = {'type': 'number', 'minimum': 0, 'maximum': 2_592_000} +RANGE = object_schema({'start_seconds': SECONDS, 'end_seconds': SECONDS}) +HANDOFFS = ('source-to-ci', 'ci-registry-deployment', 'deployment-to-argo', + 'argo-to-runtime', 'fault-correction-recovery') +HANDOFF_REQUIREMENTS = { + 'source-to-ci': ({'build-promote'}, {'source-commit', 'pipeline-id', 'job-id'}), + 'ci-registry-deployment': ({'build-promote', 'primary-deliver'}, + {'mission-image-digest', 'nginx-image-digest', 'sbom-subject', + 'signature-subject', 'deployment-commit'}), + 'deployment-to-argo': ({'primary-deliver', 'primary-probes'}, + {'deployment-commit', 'argo-revision', 'application'}), + 'argo-to-runtime': ({'primary-baseline', 'primary-probes'}, + {'cluster-uid', 'namespace', 'workload-uid', 'runtime-image-digest', + 'http-probe', 'metrics-query', 'isolation-probe'}), + 'fault-correction-recovery': ({'primary-confirm-fault', 'primary-correction', 'primary-deliver', + 'primary-recovery', 'reset', 'replay-verify', 'cleanup'}, + {'fault-commit', 'correction-patch-sha256', 'deployment-commit', + 'recovery-evidence', 'reset-commit', 'cleanup-evidence'}), +} +CLAIM_ROLES = sorted(set().union(*(roles for _, roles in HANDOFF_REQUIREMENTS.values()))) +CLAIM = object_schema({'artifact': RELATIVE, 'json_pointer': {'type': 'string', 'maxLength': 2048}, + 'role': {'enum': CLAIM_ROLES}, 'label': LABEL, + 'value': {'type': ['string', 'number', 'boolean', 'null']}}) + +CHAPTERS_SCHEMA = document('video-chapters', { + 'schema_version': {'const': 1}, 'kind': {'const': 'factory-video-chapters'}, + 'run_id': LABEL, 'duration_seconds': {'type': 'number', 'exclusiveMinimum': 0, 'maximum': 2_592_000}, + 'chapters': array(object_schema({ + 'id': LABEL, 'title': LABEL, 'phase_id': {'type': ['string', 'null'], 'maxLength': 160}, + 'attempt': {'enum': ['shared', 'primary', 'replay']}, + 'source_range': RANGE, 'observed_at': UTC, 'evidence_paths': array(RELATIVE, maximum=200), + }), minimum=35, maximum=35), + 'handoffs': array(object_schema({'kind': {'enum': list(HANDOFFS)}, 'source_range': RANGE, + 'phase_ids': array(LABEL, minimum=1, maximum=33), + 'claims': array(CLAIM, minimum=1, maximum=100)}), minimum=5, maximum=5), +}) + +VIDEO_REVIEW_SCHEMA = document('video-review', { + 'schema_version': {'const': 1}, 'kind': {'const': 'factory-video-review'}, + 'run_id': LABEL, 'profile': {'const': 'bigbang-live'}, 'environment_id': LABEL, + 'identities': IDENTITIES, 'native_identity_sha256': DIGEST, + 'requested_client_model': {'oneOf': [object_schema({'client_version': LABEL, 'client_sha256': DIGEST, + 'model': LABEL, 'reasoning_effort': LABEL}), {'type': 'null'}]}, + 'result': REFERENCE, 'evidence_manifest': REFERENCE, + 'video': REFERENCE, 'chapters': REFERENCE, 'transcript': REFERENCE, + 'video_format': {'enum': ['mp4', 'webm', 'mov', 'mkv']}, + 'transcript_format': {'enum': ['webvtt', 'srt']}, + 'duration_seconds': {'type': 'number', 'exclusiveMinimum': 0, 'maximum': 2_592_000}, + 'capture_started_at': UTC, 'capture_ended_at': UTC, 'recording_date': UTC, + 'reviewer': LABEL, 'reviewed_at': UTC, + 'reviewer_did_not_build_demo': {'type': 'boolean'}, 'watched_full_delivered_video': {'type': 'boolean'}, + 'playback_decision': DECISION, 'completeness_decision': DECISION, 'clarity_decision': DECISION, + 'continuous_source': {'type': 'boolean'}, 'no_off_camera_repair': {'type': 'boolean'}, + 'no_fixture_replacement': {'type': 'boolean'}, 'readable_text': {'type': 'boolean'}, + 'narration_or_captions_explain_transitions': {'type': 'boolean'}, 'no_exposed_credentials': {'type': 'boolean'}, + 'answers': object_schema({key: {'type': 'string', 'minLength': 1, 'maxLength': 8000} + for key in ('what_deployed', 'codex_contribution', 'fault_cause', + 'delivered_patch', 'recovery_and_isolation', 'how_to_rerun')}), + 'confusing_steps': array({'type': 'string', 'minLength': 1, 'maxLength': 2000}, maximum=100), + 'unresolved_material_gaps': array({'type': 'string', 'minLength': 1, 'maxLength': 2000}, maximum=100), + 'optional_edits': array(object_schema({'video': REFERENCE, 'duration_seconds': SECONDS, + 'discloses_cuts_speed_and_elapsed_time': {'type': 'boolean'}, + 'segments': array(object_schema({'source_range': RANGE, 'edit_range': RANGE, + 'speed': {'type': 'number', 'exclusiveMinimum': 0, 'maximum': 100}}), + minimum=1, maximum=10000)}), maximum=20), +}) + +QUALIFICATION_SCHEMA = document('qualification', { + 'schema_version': {'const': 1}, 'kind': {'const': 'factory-release-qualification'}, + 'qualification_id': LABEL, 'created_at': UTC, 'author_id': LABEL, + 'package_manifest_sha256': DIGEST, 'scenario_sha256': DIGEST, 'assertions_sha256': DIGEST, + 'lock_sha256': DIGEST, + 'runs': array(object_schema({ + 'role': {'enum': ['fresh-1', 'fresh-2', 'reset-replay']}, + 'result': REFERENCE, 'operator_id': LABEL, 'operator_attested_at': UTC, + 'operator_performed_run': {'type': 'boolean'}, + 'environment_origin': {'enum': ['fresh', 'retained', 'unknown']}, + 'cluster_uid': {'type': ['string', 'null'], 'maxLength': 256}, + 'environment_evidence': array(RELATIVE, maximum=32), + }), minimum=3, maximum=3), + 'video_review': REFERENCE, + # Retain independent gate receipts without promoting unimplemented adapters. + 'additional_gate_evidence': array(object_schema({'gate': {'enum': ['G' + str(i) for i in range(1, 11)]}, + 'artifacts': array(REFERENCE, minimum=1, maximum=100)}), + maximum=10), +}) + +SCHEMAS = {'qualification': QUALIFICATION_SCHEMA, 'video-review': VIDEO_REVIEW_SCHEMA, + 'video-chapters': CHAPTERS_SCHEMA} diff --git a/plugins/devsecops/src/devsecops/factory/qualification_runner.py b/plugins/devsecops/src/devsecops/factory/qualification_runner.py new file mode 100644 index 0000000..5cfb4aa --- /dev/null +++ b/plugins/devsecops/src/devsecops/factory/qualification_runner.py @@ -0,0 +1,295 @@ +"""Bounded installed qualification entry point, using only factory_demo.py. + +No deployment, mutation reconciliation, model correction or lifecycle graph is +implemented here. A timed-out invocation remains uncertain and is never retried. +""" +from __future__ import annotations + +import argparse +from contextlib import redirect_stderr, redirect_stdout +from datetime import datetime, timezone +import io +import os +from pathlib import Path +import re +import sys +import time +import zipfile + +from . import native_codex +from .lifecycle import PACKAGE_ROOT +from .qualification import QualificationError, qualify_and_write, _relative +from .state import MAX_ARTIFACT_BYTES, _canonical, _exclusive, _json, _read, _safe_path, _sha + + +def _now(): + return datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z') + + +def _outside(path, author): + path, author = _safe_path(Path(path)), _safe_path(Path(author)) + if path.is_relative_to(author): + raise QualificationError('Qualification must operate outside the author checkout') + return path + + +def _new_output(path, author): + path = _outside(path, author) + if path.exists(): + raise QualificationError('Qualification output must be new; inspect existing attempts before continuing') + path.mkdir(mode=0o700) + return path + + +def _identity(plugin_id, version): + if plugin_id != 'devsecops@devsecops-local' or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._+-]{0,119}', version): + raise QualificationError('Unsupported explicit local plugin identity or version') + + +def _environment(): + # Credentials remain inherited references used by the canonical operator + # path; their values are never serialized. -I also isolates Python imports. + return {key: value for key, value in os.environ.items() + if key not in ('PYTHONPATH', 'PYTHONHOME', 'PYTHONSTARTUP', 'PYTHONINSPECT')} + + + +def _engine_outside_sources(engine, *, author_checkout, installed_root): + """Check the actual interpreter and import origins, not only its venv link.""" + author = _safe_path(Path(author_checkout)) + cache = installed_root.parents[2] + try: + runtime = engine['runtime'] + locations = [engine['resolved_executable'], runtime['executable'], runtime['prefix'], runtime['base_prefix']] + imports = runtime['imports'] + if type(imports) is not list or len(imports) != 3: + raise ValueError + locations.extend(item['file'] for item in imports) + for value in locations: + if not isinstance(value, str): + raise ValueError + path = Path(value) + if not path.is_absolute() or '..' in path.parts: + raise ValueError + # An explicitly selected venv executable may be a symlink. Check + # its containing path and resolved target without changing argv. + _safe_path(path.parent) + resolved = path.resolve(strict=True) + for candidate in (path, resolved): + if candidate.is_relative_to(author) or candidate.is_relative_to(cache): + raise ValueError + except (KeyError, TypeError, ValueError, OSError): + raise QualificationError('Dependency interpreter or actual import origin is inside author source/cache or unavailable') from None + + +def run_canonical(*, installed_root, package_sha256, plugin_id, plugin_version, engine_python, + author_checkout, output, timeout, arguments): + _identity(plugin_id, plugin_version) + if not 1 <= timeout <= 2_592_000: + raise QualificationError('Canonical invocation deadline is outside its supported bound') + root = _outside(installed_root, author_checkout) + if root != _safe_path(PACKAGE_ROOT): + raise QualificationError('Run qualification using the script from the selected installed package') + deadline = time.monotonic() + timeout + package_raw, paths = native_codex._package(root, package_sha256, plugin_id, plugin_version, deadline) + required = {'scripts/factory_demo.py', 'scripts/qualify_release.py', + 'src/devsecops/factory/terminal_evidence.py', 'src/devsecops/factory/qualification.py'} + if not required <= paths.keys(): + raise QualificationError('Installed candidate lacks the canonical qualification entry points') + from .cli import build_parser + arguments = list(arguments) + if arguments and arguments[0] == '--': + arguments.pop(0) + try: + with redirect_stderr(io.StringIO()), redirect_stdout(io.StringIO()): + args = build_parser().parse_args(arguments) + except SystemExit: + raise QualificationError('Arguments do not match the installed canonical factory command') from None + if (args.command != 'e2e' or args.profile != 'bigbang-live' or args.operation_backend != 'owned-linux' + or args.plugin_id != plugin_id or args.plugin_version != plugin_version + or _safe_path(args.package_manifest) != root / 'SHA256SUMS'): + raise QualificationError('Qualification requires the same installed canonical bigbang-live owned-linux command') + for path in (args.config, args.lock, args.environment_inventory, args.output or args.resume): + if not path.is_absolute(): + raise QualificationError('Canonical qualification input and run paths must be explicit and absolute') + run_dir = _outside(args.output or args.resume, author_checkout) + if run_dir.is_relative_to(root) or root.is_relative_to(run_dir): + raise QualificationError('Run evidence must be separate from the installed package') + output = _outside(output, author_checkout) + if output.is_relative_to(run_dir) or run_dir.is_relative_to(output) or output.is_relative_to(root): + raise QualificationError('Invocation evidence must be outside the run and installed package') + python = Path(engine_python) + if not python.is_absolute() or '..' in python.parts: + raise QualificationError('Dependency interpreter must be an explicit absolute path') + _outside(python.parent, author_checkout) + environ = _environment() + engine = native_codex._engine_identity(python, cwd=root, deadline=deadline, environ=environ, cancel=None) + _engine_outside_sources(engine, author_checkout=author_checkout, installed_root=root) + output = _new_output(output, author_checkout) + started = _now() + argv = [str(python), '-I', '-B', str(root / 'scripts/factory_demo.py'), *arguments] + # A durable started receipt prevents a missing final receipt being interpreted + # as nonexecution. A fresh invocation output is mandatory even for a resume. + started_record = {'schema_version': 1, 'kind': 'canonical-qualification-invocation-started', + 'started_at': started, 'run_directory': str(run_dir), 'package_sha256': _sha(package_raw), + 'entrypoint_sha256': paths['scripts/factory_demo.py'], 'arguments_sha256': _sha(_canonical(arguments)), + 'engine_identity': engine, 'effect': 'unobserved-until-terminal-receipt'} + _exclusive(output / 'started.json', _canonical(started_record)) + try: + result = native_codex._process(argv, cwd=output, stdin=b'', deadline=deadline, limit=16_000_000, + environ=environ) + except OSError: + result = {'reason': 'process-launch-error', 'returncode': None, 'stdout': b'', 'stderr': b'', 'spawned': False} + for name in ('stdout', 'stderr'): + _exclusive(output / (name + '.bin'), result[name]) + status = ('uncertain-needs-reconciliation' if result['reason'] else + 'native-handoff-required' if result['returncode'] == 3 else 'completed-invocation') + terminal = None + if result['reason'] is None and result['returncode'] == 0: + from .terminal_evidence import verify_terminal + try: + terminal = verify_terminal(run_dir)['result'] + native_codex._package(root, package_sha256, plugin_id, plugin_version, time.monotonic() + 120) + if (terminal['canonical_success'] is not True or terminal['exit_code'] != 0 + or terminal['identities']['package_sha256'] != package_sha256): + terminal = None + except (OSError, ValueError): + terminal = None + if terminal is None: + status = 'terminal-result-not-qualified' + final = {**started_record, 'kind': 'canonical-qualification-invocation', 'finished_at': _now(), + 'status': status, 'effect': 'canonical-journal-is-authority', 'spawned': result['spawned'], + 'process_exit_code': result['returncode'], 'process_reason': result['reason'], + 'canonical_success': terminal is not None, + 'stdout_sha256': _sha(result['stdout']), 'stderr_sha256': _sha(result['stderr']), + 'automatic_retry': False, 'release_qualified': False} + _exclusive(output / 'invocation.json', _canonical(final)) + return final + + +def stage_candidate(*, archive, archive_sha256, package_sha256, plugin_id, plugin_version, + author_checkout, output, codex_executable, codex_sha256, codex_version, codex_home): + """Prepare a hash-checked local marketplace and exact reviewable install plan. + + Installation is deliberately separate from staging. Existing CLI/plugin + state, approvals and authentication cannot be inferred from an archive. + """ + _identity(plugin_id, plugin_version) + if codex_version not in native_codex.CLIENT_VERSIONS or not re.fullmatch(r'[a-f0-9]{64}', codex_sha256): + raise QualificationError('A supported explicitly pinned local installer is required') + executable = _safe_path(Path(codex_executable)) + if native_codex._file_digest(executable, time.monotonic() + 60) != codex_sha256: + raise QualificationError('Local installer bytes differ from the declared client identity') + archive = _safe_path(Path(archive)) + raw = _read(archive, native_codex.MAX_PACKAGE_BYTES) + if _sha(raw) != archive_sha256: + raise QualificationError('Candidate archive identity differs') + home = _outside(codex_home, author_checkout) + if home.exists(): + raise QualificationError('An isolated new Codex home must be selected before installing') + files, total = {}, 0 + with zipfile.ZipFile(io.BytesIO(raw)) as zipped: + entries = zipped.infolist() + if len(entries) > native_codex.MAX_PACKAGE_FILES + 1: + raise QualificationError('Candidate archive contains too many files') + for entry in entries: + if not entry.filename.startswith('devsecops/') or entry.is_dir() or entry.flag_bits & 1: + raise QualificationError('Candidate archive membership is unsupported') + name = entry.filename[len('devsecops/'):] + _relative(Path('/candidate'), name) + if name in files or (entry.external_attr >> 16) & 0o170000 not in (0, 0o100000): + raise QualificationError('Candidate archive contains duplicate or nonregular members') + if entry.file_size > MAX_ARTIFACT_BYTES or total + entry.file_size > native_codex.MAX_PACKAGE_BYTES: + raise QualificationError('Candidate archive exceeds bounded extraction limits') + files[name] = zipped.read(entry) + total += len(files[name]) + if 'SHA256SUMS' not in files or _sha(files['SHA256SUMS']) != package_sha256: + raise QualificationError('Candidate content-manifest identity differs') + expected = {} + try: + for line in files['SHA256SUMS'].decode('ascii').splitlines(): + digest, name = line.split(' ', 1) + if not re.fullmatch(r'[a-f0-9]{64}', digest) or name in expected or name == 'SHA256SUMS': + raise ValueError + expected[name] = digest + if expected != {name: _sha(value) for name, value in files.items() if name != 'SHA256SUMS'}: + raise ValueError + except (ValueError, UnicodeError): + raise QualificationError('Candidate archive differs from its exact content manifest') from None + metadata = _json(files.get('.codex-plugin/plugin.json', b'{}')) + if metadata.get('name') != 'devsecops' or metadata.get('version') != plugin_version: + raise QualificationError('Candidate metadata differs from the selected plugin version') + if not {'scripts/factory_demo.py', 'scripts/qualify_release.py', 'src/devsecops/factory/qualification.py'} <= files.keys(): + raise QualificationError('Candidate is missing canonical qualification entry points') + output = _outside(output, author_checkout) + if home.is_relative_to(output) or output.is_relative_to(home): + raise QualificationError('Installer home and staged source must be separate') + output = _new_output(output, author_checkout) + for name, content in files.items(): + target = output / 'marketplace/plugins/devsecops' / name + target.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + _exclusive(target, content) + marketplace = output / 'marketplace' + registry = marketplace / '.agents/plugins' + registry.mkdir(mode=0o700, parents=True) + _exclusive(registry / 'marketplace.json', _canonical({ + 'name': 'devsecops-local', 'interface': {'displayName': 'DevSecOps Local'}, + 'plugins': [{'name': 'devsecops', 'source': {'source': 'local', 'path': './plugins/devsecops'}, + 'policy': {'installation': 'AVAILABLE', 'authentication': 'ON_INSTALL'}, 'category': 'Developer Tools'}]})) + commands = [[str(executable), '--version'], + [str(executable), 'plugin', 'marketplace', 'add', str(marketplace), '--json'], + [str(executable), 'plugin', 'add', plugin_id, '--json'], + [str(executable), 'plugin', 'list', '--json']] + plan = {'schema_version': 1, 'kind': 'canonical-qualification-install-plan', 'status': 'staged-not-installed', + 'archive_sha256': archive_sha256, 'package_sha256': package_sha256, 'plugin_id': plugin_id, + 'plugin_version': plugin_version, 'client_sha256': codex_sha256, 'client_version': codex_version, + 'environment': {'CODEX_HOME': str(home)}, 'commands': commands, + 'expected_installed_root': str(home / 'plugins/cache/devsecops-local/devsecops' / plugin_version), + 'required_next_steps': ['Review and execute the supported local installer under its required authorization.', + 'Verify the actual installed and enabled inventory and exact cache bytes.', + 'Prepare a locked dependency interpreter outside the author checkout and installed cache.', + 'Configure approved native authentication and explicitly pinned operation inputs.', + 'Invoke qualify_release.py run from the installed package; then verify actual run/media evidence.'], + 'release_qualified': False} + _exclusive(output / 'install-plan.json', _canonical(plan)) + return plan + + +def main(argv=None): + parser = argparse.ArgumentParser(prog='qualify-release') + commands = parser.add_subparsers(dest='command', required=True) + verify = commands.add_parser('verify', help='Read-only terminal/media consistency and recorded viewer decisions') + verify.add_argument('--qualification', type=Path, required=True) + verify.add_argument('--output', type=Path, required=True) + stage = commands.add_parser('stage-install', help='Prepare candidate archive and exact supported local installer plan') + for name in ('archive', 'author-checkout', 'output', 'codex-executable', 'codex-home'): + stage.add_argument('--' + name, type=Path, required=True) + for name in ('archive-sha256', 'package-sha256', 'plugin-id', 'plugin-version', 'codex-sha256', 'codex-version'): + stage.add_argument('--' + name, required=True) + run = commands.add_parser('run', help='Invoke only the selected installed canonical factory_demo.py') + for name in ('installed-root', 'engine-python', 'author-checkout', 'output'): + run.add_argument('--' + name, type=Path, required=True) + for name in ('package-sha256', 'plugin-id', 'plugin-version'): + run.add_argument('--' + name, required=True) + run.add_argument('--timeout', type=int, required=True) + run.add_argument('arguments', nargs=argparse.REMAINDER) + args = vars(parser.parse_args(argv)) + command = args.pop('command') + try: + if command == 'verify': + report = qualify_and_write(args['qualification'], args['output']) + result, code = report, report['exit_code'] + elif command == 'stage-install': + result, code = stage_candidate(**args), 0 + else: + result = run_canonical(**args) + code = (3 if result['status'] == 'native-handoff-required' else + 0 if result['canonical_success'] else 1 if result['process_exit_code'] == 1 else 2) + print(_canonical(result).decode(), end='') + return code + except (OSError, ValueError, KeyError, UnicodeError, zipfile.BadZipFile): + print(_canonical({'execution_status': 'incomplete', 'release_qualified': False, + 'message': 'Qualification input, installed capability or immutable evidence is unavailable or invalid.'}).decode(), + end='', file=sys.stderr) + return 2 + diff --git a/plugins/devsecops/src/devsecops/factory/qualify_builder.py b/plugins/devsecops/src/devsecops/factory/qualify_builder.py new file mode 100644 index 0000000..0646522 --- /dev/null +++ b/plugins/devsecops/src/devsecops/factory/qualify_builder.py @@ -0,0 +1,776 @@ +"""Owned Linux rootless executor qualification using a fixed offline fixture. + +This is a real executor probe, not an Iron Bank mission build or promotion. +It makes no system configuration changes and never uses a Docker daemon. +""" +from __future__ import annotations + +from contextlib import contextmanager +from datetime import datetime, timezone +import hashlib +import math +import os +from pathlib import Path +import platform +import pwd +import re +import signal +import socket +import stat +import struct +import subprocess +import tarfile +import time +import uuid + +from devsecops.adapters.artifacts import _BoundedTarInfo, _canonical, _oci_archive, _open_directory +from devsecops.adapters.http import _json +from devsecops.adapters.signatures import _snapshot +from devsecops.factory.build import inspect_rootless_worker + +ROOT = Path(__file__).resolve().parents[3] +MAX_LOG = 8_000_000 +MAX_IMAGE = 128_000_000 +RUNTIME_NAMES = ("rootless", "buildkit-state", "home", "config", "cache", "docker", "tmp", "tools", "fixture") + + +class QualificationError(ValueError): + def __init__(self, code): + self.code = code + super().__init__(code) + + +class Interrupted(BaseException): + pass + + +def _sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def _now(): + return datetime.now(timezone.utc).isoformat() + + +def _boot_id(): + value = Path("/proc/sys/kernel/random/boot_id").read_text().strip() + if str(uuid.UUID(value)) != value: + raise QualificationError("kernel-boot-identity-invalid") + return value + + +def _remaining(deadline): + value = deadline - time.monotonic() + if value <= 0: + raise QualificationError("qualification-deadline") + return value + + +def _regular(path, limit=64_000, *, root_owned=False): + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + with os.fdopen(fd, "rb") as stream: + before = os.fstat(stream.fileno()) + if (not stat.S_ISREG(before.st_mode) or before.st_nlink != 1 or before.st_size > limit + or root_owned and (before.st_uid != 0 or before.st_mode & 0o022)): + raise QualificationError("prerequisite-file-authority") + raw = stream.read(limit + 1) + after = os.fstat(stream.fileno()) + keys = ("st_dev", "st_ino", "st_size", "st_mtime_ns", "st_ctime_ns") + if len(raw) > limit or any(getattr(before, key) != getattr(after, key) for key in keys): + raise QualificationError("prerequisite-file-changed") + return raw, before + + +def _image_receipt(path, limit, deadline): + """Hash a bounded stable exported image without loading it all into RAM.""" + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + with os.fdopen(fd, 'rb') as stream: + before = os.fstat(fd) + if (not stat.S_ISREG(before.st_mode) or before.st_nlink != 1 or before.st_uid != os.getuid() + or before.st_mode & 0o077 or not 0 < before.st_size <= limit): + raise QualificationError('output-image-authority') + size, checksum = 0, hashlib.sha256() + while chunk := stream.read(65536): + _remaining(deadline) + size += len(chunk) + if size > limit: + raise QualificationError('output-image-limit') + checksum.update(chunk) + after = os.fstat(fd) + if any(getattr(before, key) != getattr(after, key) for key in ('st_dev', 'st_ino', 'st_size', 'st_mtime_ns', 'st_ctime_ns')): + raise QualificationError('output-image-changed') + _remaining(deadline) + return {'archive_sha256': checksum.hexdigest(), 'archive_bytes': size} + + +@contextmanager +def _private_image_export(output): + """Reserve a private inode; buildctl resets umask before opening its export.""" + identity = _root_identity(output) + parent, descriptor = _open_directory(output), None + try: + value = os.fstat(parent) + if identity != {'device': value.st_dev, 'inode': value.st_ino, 'uid': value.st_uid}: + raise QualificationError('run-directory-identity-changed') + descriptor = os.open('image.oci.tar', os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, + 0o600, dir_fd=parent) + os.fchmod(descriptor, 0o600) + reserved = os.fstat(descriptor) + yield + if _root_identity(output) != identity: + raise QualificationError('run-directory-identity-changed') + exported = os.stat('image.oci.tar', dir_fd=parent, follow_symlinks=False) + if (reserved.st_dev, reserved.st_ino) != (exported.st_dev, exported.st_ino): + raise QualificationError('output-image-replaced') + finally: + if descriptor is not None: + os.close(descriptor) + os.close(parent) + + +def _private_export_metadata(output, limit=1_000_000): + """Seal buildctl's atomic metadata output inside the owned private directory. + + Buildctl replaces this file with mode 0666, so precreation cannot protect it. + Validate ownership and links before narrowing permissions through its fd. + """ + identity = _root_identity(output) + parent, descriptor = _open_directory(output), None + try: + value = os.fstat(parent) + if identity != {'device': value.st_dev, 'inode': value.st_ino, 'uid': value.st_uid}: + raise QualificationError('run-directory-identity-changed') + descriptor = os.open('build-metadata.json', os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent) + before = os.fstat(descriptor) + if (not stat.S_ISREG(before.st_mode) or before.st_nlink != 1 or before.st_uid != os.getuid() + or not 0 < before.st_size <= limit): + raise QualificationError('output-metadata-authority') + os.fchmod(descriptor, 0o600) + sealed = os.fstat(descriptor) + if any(getattr(before, key) != getattr(sealed, key) for key in + ('st_dev', 'st_ino', 'st_uid', 'st_nlink', 'st_size', 'st_mtime_ns')): + raise QualificationError('output-metadata-changed') + chunks, size = [], 0 + while size <= limit: + chunk = os.read(descriptor, min(65536, limit + 1 - size)) + if not chunk: + break + chunks.append(chunk) + size += len(chunk) + raw = b''.join(chunks) + after = os.fstat(descriptor) + current = os.stat('build-metadata.json', dir_fd=parent, follow_symlinks=False) + if ((current.st_dev, current.st_ino) != (before.st_dev, before.st_ino) + or any(getattr(sealed, key) != getattr(after, key) for key in + ('st_dev', 'st_ino', 'st_uid', 'st_mode', 'st_nlink', 'st_size', 'st_mtime_ns', 'st_ctime_ns')) + or stat.S_IMODE(after.st_mode) != 0o600 or len(raw) != after.st_size or len(raw) > limit): + raise QualificationError('output-metadata-changed') + if _root_identity(output) != identity: + raise QualificationError('run-directory-identity-changed') + return raw + finally: + if descriptor is not None: + os.close(descriptor) + os.close(parent) + + +def _proc(pid): + try: + raw = Path(f"/proc/{pid}/stat").read_bytes() + fields = raw.rsplit(b")", 1)[1].split() + if fields[0] == b"Z": + return None + command = Path(f"/proc/{pid}/cmdline").read_bytes() + if len(command) > 16_000: + raise QualificationError("process-command-limit") + executable = os.stat(f"/proc/{pid}/exe") + owner = os.stat(f"/proc/{pid}").st_uid + return {"pid": pid, "start_ticks": int(fields[19]), "uid": owner, + "executable_device": executable.st_dev, "executable_inode": executable.st_ino, + "argv_sha256": _sha(command)} + except (FileNotFoundError, ProcessLookupError): + return None + + +def _same_process(identity): + current = _proc(identity["pid"]) + if current is not None and current != identity: + raise QualificationError("process-identity-changed") + return current is not None + + +def _signal_owned(identity, signum): + """Pin the kernel process before checking identity and delivering a signal.""" + if not hasattr(os, "pidfd_open") or not hasattr(signal, "pidfd_send_signal"): + raise QualificationError("linux-pidfd-signaling-required") + try: + descriptor = os.pidfd_open(identity["pid"], 0) + except ProcessLookupError: + return False + try: + if not _same_process(identity): + return False + try: + signal.pidfd_send_signal(descriptor, signum, None, 0) + return True + except ProcessLookupError: + return False + finally: + os.close(descriptor) + + +def _atomic(root, name, value, *, directory=None): + raw = _canonical(value) + b"\n" + if len(raw) > 64_000: + raise QualificationError("receipt-size-limit") + temporary = "." + name + ".tmp" + directory = _open_directory(root) if directory is None else os.dup(directory) + try: + descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=directory) + try: + with os.fdopen(descriptor, "wb") as stream: + stream.write(raw) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, name, src_dir_fd=directory, dst_dir_fd=directory) + os.fsync(directory) + finally: + try: + os.unlink(temporary, dir_fd=directory) + except FileNotFoundError: + pass + finally: + os.close(directory) + + +def _root_identity(root): + descriptor = _open_directory(root) + try: + value = os.fstat(descriptor) + if value.st_uid != os.getuid() or value.st_mode & 0o077: + raise QualificationError("run-directory-authority") + return {"device": value.st_dev, "inode": value.st_ino, "uid": value.st_uid} + finally: + os.close(descriptor) + + +def _guard(root, state): + if _root_identity(root) != state["directory"]: + raise QualificationError("run-directory-identity-changed") + boot = _boot_id() + if boot != state["boot_id"]: + raise QualificationError("kernel-boot-identity-changed") + + +def _id_range(raw, name, uid): + selected, all_ranges = [], [] + for line in raw.decode("ascii").splitlines(): + if not line.strip() or line.startswith("#"): + continue + parts = line.split(":") + if len(parts) != 3 or not parts[1].isdigit() or not parts[2].isdigit(): + raise QualificationError("subordinate-id-format") + start, count = int(parts[1]), int(parts[2]) + if start <= 0 or count <= 0 or start + count > 2**32 - 1: + raise QualificationError("subordinate-id-range") + item = (parts[0], start, start + count) + all_ranges.append(item) + if parts[0] in {name, str(uid)}: + selected.append(item) + if len(selected) != 1 or selected[0][2] - selected[0][1] < 65536: + raise QualificationError("subordinate-id-allocation-required") + chosen = selected[0] + if any(item is not chosen and max(item[1], chosen[1]) < min(item[2], chosen[2]) for item in all_ranges): + raise QualificationError("subordinate-id-allocation-overlap") + return {"start": chosen[1], "count": chosen[2] - chosen[1]} + + +def prerequisites(expected_uid): + if platform.system() != "Linux" or type(expected_uid) is not int or expected_uid <= 0 or expected_uid != os.getuid(): + raise QualificationError("owned-nonroot-linux-user-required") + try: + status, _ = _regular(Path("/proc/self/status")) + except (OSError, QualificationError): + raise QualificationError("linux-no-new-privs-status-unavailable") from None + flags = [line.partition(b":")[2].strip() for line in status.splitlines() + if line.partition(b":")[0] == b"NoNewPrivs"] + if len(flags) != 1 or flags[0] not in (b"0", b"1"): + raise QualificationError("linux-no-new-privs-status-invalid") + # This fixed route needs privileged helpers to map subordinate IDs. The + # inherited kernel flag cannot be cleared and prevents their setuid exec. + if flags[0] == b"1": + raise QualificationError("uidmap-incompatible-no-new-privs") + if not hasattr(os, "pidfd_open") or not hasattr(signal, "pidfd_send_signal"): + raise QualificationError("linux-pidfd-signaling-required") + try: + descriptor = os.pidfd_open(os.getpid(), 0) + try: + signal.pidfd_send_signal(descriptor, 0, None, 0) # Read-only capability probe of this process. + finally: + os.close(descriptor) + except OSError: + raise QualificationError("linux-pidfd-signaling-required") from None + user = pwd.getpwuid(expected_uid).pw_name + result = {"uid": expected_uid, "gid": os.getgid(), "user": user, "helpers": {}, "pidfd_signaling": "available"} + for name in ("newuidmap", "newgidmap"): + raw, info = _regular(Path("/usr/bin") / name, 2_000_000, root_owned=True) + if not info.st_mode & stat.S_ISUID or not info.st_mode & stat.S_IXOTH: + raise QualificationError("root-owned-uidmap-helper-required") + result["helpers"][name] = {"sha256": _sha(raw), "bytes": len(raw), "mode": stat.S_IMODE(info.st_mode)} + for name in ("subuid", "subgid"): + raw, _ = _regular(Path("/etc") / name, root_owned=True) + result[name] = {"sha256": _sha(raw), **_id_range(raw, user, expected_uid)} + return result + + +def _commands(root, recipe=None): + tools = root / "tools" + daemon = [str(tools / "buildkitd"), "--rootless", "--addr", "unix://" + str(root / "buildkit.sock"), + "--root", str(root / "buildkit-state"), "--oci-worker=true", "--containerd-worker=false", + "--oci-worker-snapshotter=native", "--oci-worker-binary", str(tools / "buildkit-runc"), + "--oci-worker-net=host", "--config", str(root / "buildkitd.toml")] + parent = [str(tools / "rootlesskit"), "--state-dir", str(root / "rootless"), "--net=none", "--pidns", + "--ipcns", "--utsns", "--copy-up=/etc", "--copy-up=/run", *daemon] + client = [str(tools / "buildctl"), "--addr", "unix://" + str(root / "buildkit.sock"), "build", + "--frontend", "dockerfile.v0", "--local", "context=" + str(root / "fixture"), + "--local", "dockerfile=" + str(root / "fixture"), "--no-cache", "--progress", "plain", + "--output", "type=oci,dest=" + str(root / "image.oci.tar") + ",oci-mediatypes=true", + "--metadata-file", str(root / "build-metadata.json")] + if recipe is not None: + if recipe.get('kind') == 'mission-image-build-v1': + from .mission_recipe import arguments + client.extend(arguments(root, recipe)) + else: + from .runtime_recipe import client_arguments + client.extend(client_arguments(root, recipe)) + return {"rootlesskit": parent, "buildkitd": daemon, "buildctl": client} + + +def _runtime_names(state): + return RUNTIME_NAMES + (("base",) if state.get("recipe") is not None else ()) + + +def _environment(root): + # No inherited token, proxy, agent, Docker, telemetry or helper settings. + return {"PATH": str(root / "tools") + ":/usr/bin:/bin", "HOME": str(root / "home"), "LANG": "C.UTF-8", + "LC_ALL": "C", "XDG_CONFIG_HOME": str(root / "config"), "XDG_CACHE_HOME": str(root / "cache"), + "XDG_RUNTIME_DIR": str(root / "tmp"), "DOCKER_CONFIG": str(root / "docker"), + "TMPDIR": str(root / "tmp"), "OTEL_SDK_DISABLED": "true"} + + +def _remember(root, state, role, pid, argv): + identity = _proc(pid) + expected_command = _sha(b"\x00".join(os.fsencode(arg) for arg in argv) + b"\x00") + if identity is None or identity["uid"] != os.getuid() or identity["argv_sha256"] != expected_command: + raise QualificationError("owned-process-identity-unavailable") + state["processes"][role] = identity + _guard(root, state) + _atomic(root, "process-state.json", state) + return identity + + +def _remember_daemon_peer(root, state, argv, deadline): + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client: + client.settimeout(min(3, _remaining(deadline))) + client.connect(str(root / "buildkit.sock")) + pid, uid, _ = struct.unpack("3i", client.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12)) + if uid != os.getuid(): + raise QualificationError("daemon-peer-owner-changed") + return _remember(root, state, "buildkitd", pid, argv) + + +def _log_receipt(path): + raw, _ = _regular(path, MAX_LOG) + return {"sha256": _sha(raw), "bytes": len(raw)} + + +def _watch(root, process, state, deadline, files): + while process.poll() is None: + _remaining(deadline) + _guard(root, state) + for name, limit in files.items(): + path = root / name + if path.exists() and (not path.is_file() or path.is_symlink() or path.stat().st_size > limit): + raise QualificationError("execution-output-limit") + time.sleep(0.05) + for name, limit in files.items(): + path = root / name + if path.exists() and (not path.is_file() or path.is_symlink() or path.stat().st_size > limit): + raise QualificationError("execution-output-limit") + return process.returncode + + +def _remove_tree(parent, name, deadline, *, budget, depth=0): + _remaining(deadline) + if depth > 64: + raise QualificationError("cleanup-depth-limit") + info = os.stat(name, dir_fd=parent, follow_symlinks=False) + budget[0] += 1 + if budget[0] > 50_000: + raise QualificationError("cleanup-entry-limit") + if stat.S_ISDIR(info.st_mode): + directory = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent) + try: + with os.scandir(directory) as entries: + names = [] + for entry in entries: + _remaining(deadline) + if len(names) + budget[0] > 50_000: + raise QualificationError("cleanup-entry-limit") + names.append(entry.name) + for child in names: + _remove_tree(directory, child, deadline, budget=budget, depth=depth + 1) + finally: + os.close(directory) + os.rmdir(name, dir_fd=parent) + else: + os.unlink(name, dir_fd=parent) + + +def _untracked_processes(root, state, deadline): + """Read kernel state for exact run commands; never infer cleanup from files.""" + commands = {_sha(b"\x00".join(os.fsencode(arg) for arg in argv) + b"\x00"): role + for role, argv in _commands(root, state.get("recipe")).items()} + remaining, examined = [], 0 + with os.scandir("/proc") as entries: + for entry in entries: + _remaining(deadline) + if not entry.name.isdigit(): + continue + examined += 1 + if examined > 32_000: + raise QualificationError("process-inventory-limit") + try: + if entry.stat(follow_symlinks=False).st_uid != os.getuid(): + continue + with open(entry.path + "/cmdline", "rb") as stream: + raw = stream.read(16_001) + role = commands.get(_sha(raw)) + if role is not None: + identity = _proc(int(entry.name)) + if identity is not None: + remaining.append({"role": role, "identity": identity}) + except (FileNotFoundError, ProcessLookupError): + continue + return remaining + + +def cleanup(root, *, timeout=30): + """Stop only recorded exact processes belonging to this private run directory.""" + if type(timeout) not in (int, float) or not math.isfinite(timeout) or not 1 <= timeout <= 60: + raise QualificationError("cleanup-timeout-unsupported") + _root_identity(root) + raw, info = _regular(root / "process-state.json") + if info.st_uid != os.getuid() or info.st_mode & 0o077: + raise QualificationError("process-state-authority") + state = _json(raw) + if state.get("kind") != "owned-rootless-executor-processes" or state.get("schema_version") != 1: + raise QualificationError("process-state-format") + _guard(root, state) + commands = _commands(root, state.get("recipe")) + if not isinstance(state.get("processes"), dict) or not set(state["processes"]) <= set(commands): + raise QualificationError("process-state-roles") + deadline, stopped = time.monotonic() + timeout, [] + # Stop client first, then the namespace parent and its PID-namespace init. + for role in ("buildctl", "rootlesskit", "buildkitd"): + identity = state["processes"].get(role) + if identity is None: + continue + expected = _sha(b"\x00".join(os.fsencode(arg) for arg in commands[role]) + b"\x00") + if (identity.get("uid") != os.getuid() or identity.get("argv_sha256") != expected + or type(identity.get("pid")) is not int or identity["pid"] <= 1): + raise QualificationError("cleanup-process-authority") + if _same_process(identity): + _signal_owned(identity, signal.SIGTERM) + grace = min(deadline, time.monotonic() + 5) + while _same_process(identity) and time.monotonic() < grace: + time.sleep(0.05) + if _same_process(identity): + _signal_owned(identity, signal.SIGKILL) + while _same_process(identity): + _remaining(deadline) + time.sleep(0.05) + stopped.append(role) + if _untracked_processes(root, state, deadline): + raise QualificationError("owned-processes-still-present") + _guard(root, state) + socket = root / "buildkit.sock" + if socket.exists() or socket.is_symlink(): + current = socket.lstat() + expected = state.get("socket") + if (not stat.S_ISSOCK(current.st_mode) or expected is None + or {"device": current.st_dev, "inode": current.st_ino, "uid": current.st_uid} != expected): + raise QualificationError("cleanup-socket-identity") + socket.unlink() + budget, directory = [0], _open_directory(root) + try: + opened = os.fstat(directory) + if {"device": opened.st_dev, "inode": opened.st_ino, "uid": opened.st_uid} != state["directory"]: + raise QualificationError("run-directory-identity-changed") + for name in _runtime_names(state): + try: + os.stat(name, dir_fd=directory, follow_symlinks=False) + except FileNotFoundError: + continue + _remove_tree(directory, name, deadline, budget=budget) + finally: + os.close(directory) + result = {"kind": "rootless-executor-cleanup", "decision": "pass", "finished_at": _now(), + "processes_stopped": stopped, "process_identities": state["processes"], + "kernel_matching_processes_remaining": 0, "socket_removed": True, + "runtime_directories_removed": list(_runtime_names(state))} + state["historical_processes"] = state["processes"] or state.get("historical_processes", {}) + state["processes"] = {} + state["runtime_removed"] = True + _remaining(deadline) + _guard(root, state) + _atomic(root, "process-state.json", state) + _atomic(root, "cleanup.json", result) + return result + + +def qualify(*, output, tools, expected_uid, timeout=180, _python_probe=None, _mission_build=None): + """Execute one fixed no-cache recipe, then remove its owned runtime.""" + if (not isinstance(output, Path) or not output.is_absolute() or ".." in output.parts + or len(os.fsencode(output)) > 70 or not re.fullmatch(r"/[A-Za-z0-9._/-]+", str(output)) + or not isinstance(tools, Path) or not tools.is_absolute() + or type(timeout) not in (int, float) or not math.isfinite(timeout) or not 30 <= timeout <= 600): + raise QualificationError("explicit-short-run-path-and-bounded-time-required") + recipe = None + mission = _mission_build is not None + if mission: + from .mission_recipe import authorize, descriptor + if _python_probe is not None: + raise QualificationError('one-closed-recipe-required') + authorize(_mission_build) + recipe = descriptor(_mission_build['recipe']) + if _python_probe is not None: + from .runtime_recipe import descriptor + if not isinstance(_python_probe, dict) or set(_python_probe) != {"recipe", "acquired", "wheel"}: + raise QualificationError("closed-runtime-probe-input-required") + recipe = descriptor(_python_probe["recipe"]) + requirements = prerequisites(expected_uid) + parent = _open_directory(output.parent) + try: + os.mkdir(output.name, 0o700, dir_fd=parent) + finally: + os.close(parent) + state = {"schema_version": 1, "kind": "owned-rootless-executor-processes", "run_id": str(uuid.uuid4()), + "directory": _root_identity(output), "boot_id": _boot_id(), + "processes": {}} + if recipe is not None: + state["recipe"] = recipe + _atomic(output, "process-state.json", state) + report = {"schema_version": 1, "kind": "rootless-executor-qualification", "run_id": state["run_id"], + "decision": "unknown", "started_at": _now(), "scope": "offline-scratch-tool-execution", + "canonical_demo": "not-run", "mission_build": "not-run", "registry_trust": "not-tested", + "prerequisites": requirements, "tools": {}, "gaps": [], "harness_sha256": _sha(Path(__file__).read_bytes()), + "python_version": platform.python_version()} + if recipe is not None: + report["scope"] = "local-mission-image-build" if mission else "mission-python-runtime-probe" + report["registry_trust"] = "separate-calling-issuer-check" + report["base"] = recipe + deadline, processes = time.monotonic() + timeout, [] + previous_handlers = {} + try: + for name in RUNTIME_NAMES: + (output / name).mkdir(mode=0o700) + lock_record = _snapshot(ROOT / "supplychain.lock.json", output / "supplychain.lock.json", 64_000, deadline=deadline) + lock = _json((output / "supplychain.lock.json").read_bytes()) + architecture = {"x86_64": "amd64", "aarch64": "arm64"}.get(platform.machine()) + if architecture is None or lock["builder"]["version"] != "0.34.1" or lock["rootlesskit"]["version"] != "3.3.0": + raise QualificationError("locked-toolchain-platform-required") + if recipe is not None and recipe["architecture"] != architecture: + raise QualificationError("runtime-probe-host-platform-mismatch") + expected = dict(lock["builder"]["platforms"]["linux-" + architecture]["binaries"]) + rk = lock["rootlesskit"]["platforms"]["linux-" + architecture] + expected["rootlesskit"] = {"sha256": rk["binary_sha256"], "bytes": rk["binary_bytes"]} + if set(expected) != {"buildctl", "buildkitd", "buildkit-runc", "rootlesskit"}: + raise QualificationError("locked-toolchain-shape") + for name, wanted in expected.items(): + receipt = _snapshot(tools / name, output / "tools" / name, 200_000_000, deadline=deadline) + if receipt != wanted: + raise QualificationError("toolchain-binary-mismatch") + (output / "tools" / name).chmod(0o500) + report["tools"][name] = receipt + report["tool_lock"] = lock_record + if recipe is None: + _snapshot(output / "tools/rootlesskit", output / "fixture/probe", 32_000_000, deadline=deadline) + (output / "fixture/probe").chmod(0o500) + fixture = b'FROM scratch\nCOPY probe /probe\nRUN --network=none ["/probe", "--version"]\n' + (output / "fixture/Dockerfile").write_bytes(fixture) + (output / "fixture/Dockerfile").chmod(0o600) + elif not mission: + from .runtime_recipe import prepare + report["runtime_inputs"] = prepare(output, recipe, acquired=_python_probe["acquired"], + wheel=_python_probe["wheel"], deadline=deadline) + fixture = (output / "fixture/Dockerfile").read_bytes() + else: + from .mission_recipe import prepare, MAX_IMAGE as MISSION_MAX_IMAGE + report['mission_inputs'] = prepare(output, _mission_build, deadline) + fixture = (output / 'fixture/Dockerfile').read_bytes() + image_limit = MISSION_MAX_IMAGE if mission else MAX_IMAGE + # Empty explicit config avoids reading candidate or user's daemon config. + (output / "buildkitd.toml").write_text('[worker.oci]\n max-parallelism = 1\n[cdi]\n disabled = true\n') + (output / "buildkitd.toml").chmod(0o600) + (output / "docker/config.json").write_text('{"auths":{}}') + (output / "docker/config.json").chmod(0o600) + commands, env = _commands(output, recipe), _environment(output) + def interrupted(signum, frame): + raise Interrupted() + for signum in (signal.SIGTERM, signal.SIGINT): + previous_handlers[signum] = signal.signal(signum, interrupted) + _atomic(output, "intent.json", {"operation": "start-owned-offline-rootless-probe", "run_id": state["run_id"], + "fixture_sha256": _sha(fixture), "tool_lock_sha256": lock_record["sha256"]}) + with (output / "daemon.log").open("xb") as daemon_log: + os.chmod(output / "daemon.log", 0o600) + if mission: + authorize(_mission_build) + daemon = subprocess.Popen(commands["rootlesskit"], cwd=output, env=env, stdin=subprocess.DEVNULL, + stdout=daemon_log, stderr=daemon_log, start_new_session=True, umask=0o077) + processes.append(daemon) + _remember(output, state, "rootlesskit", daemon.pid, commands["rootlesskit"]) + socket = output / "buildkit.sock" + while not socket.exists(): + _remaining(deadline) + _guard(output, state) + if daemon.poll() is not None: + raise QualificationError("rootless-daemon-start-failed") + if (output / "daemon.log").stat().st_size > MAX_LOG: + raise QualificationError("daemon-log-limit") + time.sleep(0.1) + value = socket.lstat() + if not stat.S_ISSOCK(value.st_mode) or value.st_uid != expected_uid: + raise QualificationError("owned-daemon-socket-required") + state["socket"] = {"device": value.st_dev, "inode": value.st_ino, "uid": value.st_uid} + _atomic(output, "process-state.json", state) + os.chmod(socket, 0o600, follow_symlinks=False) + daemon_identity = _remember_daemon_peer(output, state, commands["buildkitd"], deadline) + worker = inspect_rootless_worker(socket_path=socket, expected_uid=expected_uid, + expected_device=value.st_dev, expected_inode=value.st_ino, buildctl=output / "tools/buildctl", + architecture=architecture, timeout=min(60, _remaining(deadline))) + if worker["peer"]["pid"] != daemon_identity["pid"] or not _same_process(daemon_identity): + raise QualificationError("daemon-peer-changed-during-admission") + report["worker_before"] = worker + with (_private_image_export(output), (output / "client.stdout").open("xb") as stdout, + (output / "client.stderr").open("xb") as stderr): + os.chmod(output / "client.stdout", 0o600) + os.chmod(output / "client.stderr", 0o600) + if mission: + authorize(_mission_build) + client = subprocess.Popen(commands["buildctl"], cwd=output, env=env, stdin=subprocess.DEVNULL, + stdout=stdout, stderr=stderr, start_new_session=True, umask=0o077) + processes.append(client) + _remember(output, state, "buildctl", client.pid, commands["buildctl"]) + code = _watch(output, client, state, deadline, + {"client.stdout": MAX_LOG, "client.stderr": MAX_LOG, "daemon.log": MAX_LOG, + "image.oci.tar": image_limit, "build-metadata.json": 1_000_000}) + report["client"] = {"exit_code": code, "stdout": _log_receipt(output / "client.stdout"), + "stderr": _log_receipt(output / "client.stderr")} + if code: + raise QualificationError("scratch-executor-build-failed" if recipe is None else + "mission-image-build-failed" if mission else "base-runtime-probe-build-failed") + text, _ = _regular(output / "client.stderr", MAX_LOG) + marker = None if mission else (b"rootlesskit version 3.3.0" if recipe is None else + ("DEVSECOPS_RUNTIME_PROBE " + recipe["nonce"]).encode()) + if marker is not None and not re.search(rb"(?m)^#\d+\s+[0-9.]+\s+" + re.escape(marker) + rb"\s*$", text): + raise QualificationError("actual-run-output-unverified") + image = _image_receipt(output / "image.oci.tar", image_limit, deadline) + with tarfile.open(output / "image.oci.tar", "r:", tarinfo=_BoundedTarInfo) as archive: + member = archive.getmember("index.json") + if member.size > 64_000 or not member.isfile(): + raise QualificationError("output-index-format") + index = _json(archive.extractfile(member).read(64_001)) + if len(index.get("manifests", [])) != 1: + raise QualificationError("output-platform-count") + digest = index["manifests"][0]["digest"] + mapping = _oci_archive(output / "image.oci.tar", digest, architecture, deadline=deadline) + metadata = _private_export_metadata(output) + if _json(metadata).get("containerimage.digest") != digest: + raise QualificationError("build-export-digest-mismatch") + if recipe is not None and not mission: + from .runtime_recipe import proof + report["runtime_proof"] = proof(output / "image.oci.tar", digest, recipe, + report["runtime_inputs"]["dependency_version"], deadline) + elif mission: + from .mission_recipe import inspect_output + report['image_lineage'] = inspect_output(output / 'image.oci.tar', digest, + base_layout=output / 'base/layout', base_manifest_digest=recipe['manifest_digest'], + context=report['mission_inputs']['context'], deadline=deadline) + if _image_receipt(output / 'image.oci.tar', image_limit, deadline) != image: + raise QualificationError('output-image-changed') + report["artifact"] = {"path": "image.oci.tar", **image, **mapping, + "metadata_sha256": _sha(metadata), "runtime_output": marker.decode() if marker is not None else None, "no_cache": True} + after = inspect_rootless_worker(socket_path=socket, expected_uid=expected_uid, + expected_device=value.st_dev, expected_inode=value.st_ino, buildctl=output / "tools/buildctl", + architecture=architecture, timeout=min(60, _remaining(deadline))) + if after["peer"] != worker["peer"] or after["worker"] != worker["worker"]: + raise QualificationError("worker-changed-during-build") + report["worker_after"] = after + if prerequisites(expected_uid) != requirements: + raise QualificationError("guest-user-authority-changed") + report["execution"] = "verified" + except (Interrupted, KeyboardInterrupt): + report["gaps"].append({"code": "qualification-interrupted"}) + except (OSError, ValueError, TypeError, KeyError, IndexError, tarfile.TarError) as error: + report["gaps"].append({"code": error.code if isinstance(error, QualificationError) else "qualification-incomplete"}) + finally: + for signum in previous_handlers: + signal.signal(signum, signal.SIG_IGN) + # Popen references remain valid even if a state write failed immediately + # after spawn. Terminate those children before independent reconciliation. + for process in reversed(processes): + if process.poll() is None and process.pid not in {v["pid"] for v in state["processes"].values()}: + process.kill() + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + report["gaps"].append({"code": "unrecorded-owned-process-wait-timeout"}) + try: + report["cleanup"] = cleanup(output) + except (OSError, ValueError, TypeError, KeyError, IndexError) as error: + report["cleanup"] = {"decision": "unknown", "code": error.code if isinstance(error, QualificationError) else "cleanup-incomplete"} + for process in processes: + try: + process.wait(timeout=2) + except subprocess.TimeoutExpired: + report["cleanup"] = {"decision": "unknown", "code": "owned-process-still-running"} + for signum, handler in previous_handlers.items(): + signal.signal(signum, handler) + report["finished_at"] = _now() + if mission: + try: + authorize(_mission_build) + except (ValueError, TypeError, KeyError): + report['gaps'].append({'code': 'mission-base-authority-expired-or-changed'}) + # Cleanup keeps its independent safety budget, but may not extend the + # caller's deadline for a successful qualification. + if time.monotonic() >= deadline: + report["gaps"].append({"code": "qualification-deadline"}) + if report.get("execution") == "verified" and report["cleanup"]["decision"] == "pass" and not report["gaps"]: + report["decision"] = "pass" + directory = _open_directory(output) + try: + current = os.fstat(directory) + if {"device": current.st_dev, "inode": current.st_ino, "uid": current.st_uid} != state["directory"]: + raise QualificationError("run-directory-changed") + _guard(output, state) + try: + _atomic(output, "qualification.json", report, directory=directory) + _guard(output, state) + if report["decision"] == "pass": + _remaining(deadline) + if mission: + authorize(_mission_build) + except BaseException: + # Retained directory authority permits withdrawing only this run's + # receipt even if the route was swapped during publication. + try: + os.unlink("qualification.json", dir_fd=directory) + except FileNotFoundError: + pass + os.fsync(directory) + raise + finally: + os.close(directory) + return report diff --git a/plugins/devsecops/src/devsecops/factory/registry_qualification.py b/plugins/devsecops/src/devsecops/factory/registry_qualification.py new file mode 100644 index 0000000..6f39e0c --- /dev/null +++ b/plugins/devsecops/src/devsecops/factory/registry_qualification.py @@ -0,0 +1,280 @@ +"""Fixed stdlib-only storage exercise. Never mission or publisher authority. + +This module is shipped with exactly three existing HTTP/OCI adapter modules in +a verified zip, then run in a dedicated owned container. No dynamic callback, +customer code, package install, signature claim or opaque capability is used. +""" +from __future__ import annotations + +import hashlib +from datetime import datetime, timezone +import io +import json +import os +from pathlib import Path +import re +import stat +import sys +import time + +from devsecops.adapters.http import APIError, HTTPSReadClient, _json +from devsecops.adapters.oci import INDEX, MANIFEST, _descriptor, _repository +from devsecops.adapters.staging_registry import _StagingRegistry + +ARTIFACT = 'application/vnd.devsecops.registry-storage-qualification.v1+json' +EMPTY = 'application/vnd.oci.empty.v1+json' + + +def canonical(value): + return (json.dumps(value, sort_keys=True, separators=(',', ':'))+'\n').encode() + + +def descriptor(raw, media): + return {'digest': 'sha256:'+hashlib.sha256(raw).hexdigest(), 'size': len(raw), 'mediaType': media} + + +def objects(binding): + if not isinstance(binding, str) or not re.fullmatch('[a-f0-9]{64}', binding): + raise ValueError('Exact registry operation binding required') + config = b'{}' + payload = canonical({'kind': 'registry-storage-qualification-only', 'binding_sha256': binding}) + subject = canonical({'schemaVersion': 2, 'mediaType': MANIFEST, 'artifactType': ARTIFACT, + 'config': descriptor(config, EMPTY), 'layers': [descriptor(payload, ARTIFACT)]}) + referrer = canonical({'schemaVersion': 2, 'mediaType': MANIFEST, 'artifactType': ARTIFACT, + 'subject': descriptor(subject, MANIFEST), 'config': descriptor(config, EMPTY), + 'layers': [descriptor(payload, ARTIFACT)]}) + return config, payload, subject, referrer + + +def _withdraw(directory, name, identity): + try: + current = os.stat(name, dir_fd=directory, follow_symlinks=False) + except FileNotFoundError: + return + if (current.st_dev, current.st_ino) == identity: + os.unlink(name, dir_fd=directory) + os.fsync(directory) + + +def _write(directory, name, value): + fd = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=directory) + info = os.fstat(fd) + identity = (info.st_dev, info.st_ino) + try: + with os.fdopen(fd, 'wb') as stream: + stream.write(canonical(value)) + stream.flush() + os.fsync(stream.fileno()) + os.fsync(directory) + except BaseException: + _withdraw(directory, name, identity) + raise + return identity + + +def qualify(*, origin, repository, ca_bundle, operator, reader, binding, output, timeout=90, expires_at=None, service_route=None): + """Write bounded probe objects once, independently read and retain all effects. + + `operator` and `reader` contain existing env reference names, never secrets. + Failure receipts retain ambiguous attempts; a caller must not retry them. + """ + if (not _repository(repository) or type(timeout) not in (int, float) or not 1 <= timeout <= 90 + or any(set(item) != {'basic_username_env', 'basic_password_env'} for item in (operator, reader))): + raise ValueError('Unsupported fixed registry qualification') + config, payload, subject, referrer = objects(binding) + expiry = datetime.fromisoformat(expires_at.replace('Z', '+00:00')) if expires_at is not None else None + if expiry is not None and expiry.tzinfo is None: + raise ValueError('Registry qualification window must have a timezone') + deadline = time.monotonic()+timeout + output = Path(output) + directory = os.open(output, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + if os.listdir(directory): + raise ValueError('Registry qualification output must be empty; retain prior attempts without retry') + # Concurrent callers cannot both acquire this attempt, even if both + # observed an empty directory. Claim before any network request. + _write(directory, 'attempt.json', {'binding_sha256': binding, 'origin': origin, 'repository': repository}) + except BaseException: + os.close(directory) + raise + report = {'schema_version': 1, 'kind': 'registry-storage-qualification-only', + 'binding_sha256': binding, 'origin': origin, 'repository': repository, + 'subject': descriptor(subject, MANIFEST), 'referrer': descriptor(referrer, MANIFEST), + 'status': 'unknown', 'canonical_success': False, 'mutation_effect': 'not_applied', + 'anonymous_read': 'unknown', 'reader_write': 'unknown', 'effects': [], 'requests': []} + clients = [] + + def checkpoint(): + if time.monotonic() >= deadline: + raise APIError('deadline') + if expiry is not None and datetime.now(timezone.utc) >= expiry: + raise APIError('operator-window-expired') + current, held = os.stat(output, follow_symlinks=False), os.fstat(directory) + if (current.st_dev, current.st_ino) != (held.st_dev, held.st_ino): + raise APIError('qualification-output-changed') + + def read_client(credentials): + checkpoint() + client = HTTPSReadClient(origin, ca_bundle=ca_bundle, timeout=min(15, deadline-time.monotonic()), + total_timeout=min(90, deadline-time.monotonic()), max_body_bytes=65536, + max_total_bytes=262144, max_requests=16, **credentials, + **({} if service_route is None else {'service_route': service_route})) + client._deadline = deadline + clients.append(client) + return client + + def writer(credentials): + checkpoint() + client = _StagingRegistry(origin, repository=repository, ca_bundle=ca_bundle, + deadline=deadline, **credentials, + **({} if service_route is None else {'service_route': service_route})) + clients.append(client) + return client + + def effect(kind, body, call): + checkpoint() + item = {'sequence': len(report['effects']), 'kind': kind, 'outcome': 'unknown', + 'sha256': hashlib.sha256(body).hexdigest(), 'bytes': len(body)} + _write(directory, 'intent-'+str(item['sequence'])+'.json', item) + report['effects'].append(item) + report['mutation_effect'] = 'unknown' + result = call() + checkpoint() + item['outcome'] = 'response-acknowledged-awaiting-independent-readback' + _write(directory, 'response-'+str(item['sequence'])+'.json', item) + return result + + def referrers(client, expected=None): + response = client.get_bytes('/v2/'+repository+'/referrers/'+descriptor(subject, MANIFEST)['digest'], + params={'artifactType': ARTIFACT}, accept=(INDEX,)) + doc = _json(response.body) + if (response.status != 200 or response.media_type != INDEX or doc.get('schemaVersion') != 2 + or doc.get('mediaType') != INDEX or not isinstance(doc.get('manifests'), list) + or len(doc['manifests']) > 128): + raise APIError('native-referrers-unavailable') + found = 0 + for entry in doc['manifests']: + _descriptor(entry) + if expected is not None and entry['digest'] == expected['digest']: + if any(entry.get(k) != v for k, v in expected.items()) or entry.get('artifactType') != ARTIFACT: + raise APIError('referrer-identity-mismatch') + found += 1 + if expected is not None and found != 1: + raise APIError('referrer-discovery-unknown') + checkpoint() + + try: + # API capability is checked before any write. Negative authorization is + # tested against actual existing content after independent readback. + readiness = read_client(reader) + for attempt in range(5): + try: + referrers(readiness) + break + except APIError as error: + if error.code != 'transport' or attempt == 4: + raise + checkpoint() + time.sleep(min(1, max(0, deadline-time.monotonic()))) + first = writer(operator) + first.authenticate(descriptor(subject, MANIFEST)['digest']) + for raw, media in ((config, EMPTY), (payload, ARTIFACT)): + location = effect('upload-session', b'', first.begin_blob) + effect('blob', raw, lambda raw=raw, media=media, location=location: + first.finish_blob(location, io.BytesIO(raw), descriptor(raw, media))) + effect('subject-manifest', subject, lambda: first.put_manifest(io.BytesIO(subject), descriptor(subject, MANIFEST))) + second = writer(operator) + second.authenticate(descriptor(referrer, MANIFEST)['digest']) + effect('referrer-manifest', referrer, lambda: second.put_manifest(io.BytesIO(referrer), descriptor(referrer, MANIFEST))) + fresh = read_client(reader) + for raw, media, route in ((config, EMPTY, 'blobs'), (payload, ARTIFACT, 'blobs'), + (subject, MANIFEST, 'manifests'), (referrer, MANIFEST, 'manifests')): + expected = descriptor(raw, media) + response = fresh.get_bytes('/v2/'+repository+'/'+route+'/'+expected['digest'], + accept=(media, 'application/octet-stream') if route == 'blobs' else (media,)) + if (response.status != 200 or response.body != raw + or response.content_digest not in (None, expected['digest'])): + raise APIError('independent-readback-mismatch') + checkpoint() + referrers(fresh, descriptor(referrer, MANIFEST)) + anonymous = read_client({}) + denied = anonymous.get_bytes('/v2/'+repository+'/manifests/'+descriptor(subject, MANIFEST)['digest'], + accept=(MANIFEST,), allow_unauthorized=True) + if denied.status != 401: + raise APIError('anonymous-read-not-denied') + report['anonymous_read'] = 'denied-401' + limited = writer(reader) + limited.authenticate(descriptor(subject, MANIFEST)['digest']) + # Record this attempt even though a rejection is expected. An unexpected + # accepted session is a real storage effect, not a harmless assertion. + try: + effect('reader-upload-denial-probe', b'', limited.begin_blob) + except APIError as error: + if error.code != 'staging-upload-not-acknowledged' or error.status not in (401, 403): + raise + report['effects'][-1]['outcome'] = 'denied-'+str(error.status) + report['reader_write'] = 'denied-'+str(error.status) + else: + raise APIError('reader-write-not-denied') + checkpoint() + report.update(status='pass', mutation_effect='applied', independent_readback='exact-bytes', + referrer_discovery='exact-inclusion') + except (APIError, ValueError, OSError, KeyError, TypeError) as error: + report['error'] = error.code if isinstance(error, APIError) else 'qualification-invalid-or-interrupted' + finally: + for client in clients: + report['requests'].extend(client.receipts) + if isinstance(client, _StagingRegistry): + client.close() + terminal_identity = None + try: + checkpoint() + terminal_identity = _write(directory, 'qualification.json', report) + checkpoint() + except BaseException: + if terminal_identity is not None: + _withdraw(directory, 'qualification.json', terminal_identity) + os.close(directory) + raise + os.close(directory) + return report + + +def main(): + # No caller-selected path/module/command. The fixed container mount contract + # supplies this private file; credentials never enter Docker argv/env/logs. + if sys.version_info < (3, 11) or len(sys.argv) != 1: + raise SystemExit(2) + try: + fd = os.open('/input/qualification.json', os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + with os.fdopen(fd, 'rb') as stream: + info = os.fstat(stream.fileno()) + if not stat.S_ISREG(info.st_mode) or info.st_size > 16384 or info.st_nlink != 1: + raise ValueError + raw = stream.read(16385) + if len(raw) > 16384: + raise ValueError + settings = _json(raw) + if set(settings) != {'origin', 'repository', 'binding', 'expires_at', 'operator', 'reader'}: + raise ValueError + for actor in ('operator', 'reader'): + if set(settings[actor]) != {'username', 'password'}: + raise ValueError + for field in ('username', 'password'): + value = settings[actor][field] + if not isinstance(value, str) or not 1 <= len(value) <= 1024 or any(ord(c) < 33 or ord(c) > 126 for c in value): + raise ValueError + os.environ['REGISTRY_'+actor.upper()+'_'+field.upper()] = value + credentials = {actor: {'basic_username_env': 'REGISTRY_'+actor.upper()+'_USERNAME', + 'basic_password_env': 'REGISTRY_'+actor.upper()+'_PASSWORD'} for actor in ('operator', 'reader')} + report = qualify(origin=settings['origin'], repository=settings['repository'], + ca_bundle='/input/ca.crt', binding=settings['binding'], output='/evidence', + expires_at=settings['expires_at'], **credentials) + print(canonical(report).decode(), end='') + except (APIError, ValueError, OSError, KeyError, TypeError): + print('{"status":"unknown","error":"qualification-interrupted"}') + raise SystemExit(2) from None + + +if __name__ == '__main__': + main() diff --git a/plugins/devsecops/src/devsecops/factory/registry_remote.py b/plugins/devsecops/src/devsecops/factory/registry_remote.py new file mode 100644 index 0000000..d8d4296 --- /dev/null +++ b/plugins/devsecops/src/devsecops/factory/registry_remote.py @@ -0,0 +1,474 @@ +"""Fixed registry Docker operations, transported with verified stdlib support. + +Only `execute` is called by the installed component. There is no command field, +image acquisition, credential creation, port publication or host configuration. +""" +from __future__ import annotations + +import base64 +import fcntl +import hashlib +from datetime import datetime, timezone +import os +from pathlib import Path +import re +import shutil +import stat +import time + +LABEL = 'io.devsecops.registry.binding' +OPERATION = 'io.devsecops.registry.operation' + + + +def _purge_owned_payload(root, expected_identity, deadline): + """Delete only inventoried owned payload trees, never metadata or parents. + + A full no-follow, same-device inventory precedes the first unlink. Open + directory descriptors keep traversal inside the observed generation. Hard + links, devices, sockets, symlinks, mounts and changed inodes stop cleanup. + """ + flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW + directory = os.open(root, flags) + try: + info = os.fstat(directory) + if (info.st_dev, info.st_ino) != expected_identity or info.st_uid != os.getuid(): + raise ValueError('Registry purge generation changed') + nodes = [] + def inventory(fd, parts=()): + if len(parts) > 20 or len(nodes) > 20000 or time.monotonic() >= deadline: + raise ValueError('Registry purge inventory exceeds bound') + for name in sorted(os.listdir(fd)): + if len(nodes) >= 20000 or time.monotonic() >= deadline: + raise ValueError('Registry purge inventory exceeds bound') + current = os.stat(name, dir_fd=fd, follow_symlinks=False) + if (current.st_dev != info.st_dev or current.st_uid != os.getuid() + or not (stat.S_ISREG(current.st_mode) or stat.S_ISDIR(current.st_mode)) + or stat.S_ISREG(current.st_mode) and current.st_nlink != 1): + raise ValueError('Registry purge encountered unowned or linked data') + entry = (parts+(name,), current.st_dev, current.st_ino, stat.S_ISDIR(current.st_mode)) + nodes.append(entry) + if entry[3]: + child = os.open(name, flags, dir_fd=fd) + try: + actual = os.fstat(child) + if (actual.st_dev, actual.st_ino) != entry[1:3]: + raise ValueError('Registry purge inventory changed') + inventory(child, entry[0]) + finally: + os.close(child) + roots = ('data', 'config', 'probe-input', 'probe-output') + for name in roots: + try: + current = os.stat(name, dir_fd=directory, follow_symlinks=False) + except FileNotFoundError: + continue + if (not stat.S_ISDIR(current.st_mode) or current.st_dev != info.st_dev + or current.st_uid != os.getuid()): + raise ValueError('Registry purge root is not the owned directory') + nodes.append(((name,), current.st_dev, current.st_ino, True)) + child = os.open(name, flags, dir_fd=directory) + try: + actual = os.fstat(child) + if (actual.st_dev, actual.st_ino) != (current.st_dev, current.st_ino): + raise ValueError('Registry purge root changed') + inventory(child, (name,)) + finally: + os.close(child) + for parts, device, inode, is_directory in reversed(nodes): + if time.monotonic() >= deadline: + raise ValueError('Registry purge deadline expired') + parent = os.dup(directory) + try: + for name in parts[:-1]: + child = os.open(name, flags, dir_fd=parent) + os.close(parent) + parent = child + current = os.stat(parts[-1], dir_fd=parent, follow_symlinks=False) + if (current.st_dev, current.st_ino) != (device, inode): + raise ValueError('Registry purge target changed') + (os.rmdir if is_directory else os.unlink)(parts[-1], dir_fd=parent) + os.fsync(parent) + finally: + os.close(parent) + if any(name in os.listdir(directory) for name in roots): + raise ValueError('Registry private payload remains') + os.fsync(directory) + finally: + os.close(directory) + + +def execute(payload, support, recipes): + """The support module is the package's existing bounded TCG transport code.""" + recipe = recipes.validate(payload['recipe']) + action, operation = payload['action'], payload['operation_id'] + if action not in ('up', 'down', 'reconcile') or not re.fullmatch('[a-f0-9-]{36}', operation): + raise ValueError('Unsupported fixed registry operation') + expected = recipes.binding(recipe, run_id=payload['run_id'], identities=payload['identities'], + package_modules=payload['package_modules']) + if (payload['binding'] != expected or type(payload['timeout']) not in (int, float) + or not 0 < payload['timeout'] <= 240): + raise ValueError('Registry operation binding or deadline differs') + expiry = datetime.fromisoformat(payload['expires_at'].replace('Z', '+00:00')) + if expiry.tzinfo is None or action == 'up' and datetime.now(timezone.utc) >= expiry: + raise ValueError('Registry provisioning window expired') + if action == 'up' and (os.getuid() == 0 or os.geteuid() == 0): + raise ValueError('Registry provisioning requires a non-root operator UID') + deadline = time.monotonic()+payload['timeout'] + root = Path(recipe['remote_directory']) + parent = support._private(root.parent) + if not root.exists(): + if action != 'up': + return {'bootstrap': 'absent', 'resources': [], 'storage_qualification': 'not-observed', + 'cleanup': 'not-observed', 'mutation_effect': 'unknown'} + support._private(root, create=True) + support._write(root/'owner.json', recipes.canonical({'binding': expected, 'created_by': operation})) + support._write(root/'lock', b'') + support._private(root) + root_identity = root.stat() + if support._json(support._read(root/'owner.json'))['binding'] != expected: + raise ValueError('Registry private directory belongs to another binding') + locked = support._lock_descriptor(root/'lock') + fcntl.flock(locked, (fcntl.LOCK_SH if action == 'reconcile' else fcntl.LOCK_EX) | fcntl.LOCK_NB) + report = {'bootstrap': 'unknown', 'storage_qualification': 'not-observed', 'cleanup': 'incomplete', + 'resources': [], 'mutation_effect': 'unknown', 'canonical_success': False} + state_path = root/'state.json' + state = support._json(support._read(state_path)) if state_path.exists() else { + 'history': [], 'inflight': None, 'ids': {}, 'storage_identity': None, + 'probe_settings_sha256': None, 'bootstrap': 'not-started'} + prefix = 'devsecops-registry-'+expected[:20] + names = {'network': prefix+'-net', 'registry': prefix+'-zot', 'probe': prefix+'-probe'} + if (not isinstance(state, dict) or not isinstance(state.get('history'), list) + or len(state['history']) > 128 or not isinstance(state.get('ids'), dict) + or set(state['ids']) - set(names) + or any(not isinstance(value, str) or not re.fullmatch('[a-f0-9]{64}', value) for value in state['ids'].values())): + os.close(locked) + raise ValueError('Registry retained state is invalid') + inflight = state.get('inflight') + if inflight is not None and (not isinstance(inflight, dict) + or set(inflight) != {'operation_id', 'role', 'verb'} + or inflight['operation_id'] not in state['history'] + or inflight['role'] not in names or inflight['verb'] not in ('create', 'start', 'stop', 'remove')): + os.close(locked) + raise ValueError('Registry retained inflight intent is invalid') + + purge = state.get('private_purge') + if purge is not None and (not isinstance(purge, dict) + or set(purge) != {'operation_id', 'state', 'root_identity'} + or purge['operation_id'] not in state['history'] or purge['state'] not in ('unknown', 'absent') + or purge['root_identity'] != {'device': root_identity.st_dev, 'inode': root_identity.st_ino} + or recipe.get('cleanup') != 'remove-owned-private-material'): + os.close(locked) + raise ValueError('Registry purge ownership generation changed') + + def check(): + if time.monotonic() >= deadline: + raise ValueError('Registry operation deadline expired') + support._private(parent) + support._private(root) + current = root.stat() + if (current.st_dev, current.st_ino) != (root_identity.st_dev, root_identity.st_ino): + raise ValueError('Registry private directory was replaced') + if action == 'up' and datetime.now(timezone.utc) >= datetime.fromisoformat(payload['expires_at'].replace('Z', '+00:00')): + raise ValueError('Registry provisioning window expired') + purging = state.get('private_purge') is not None + if state['storage_identity'] is not None and not purging: + data = support._private(root/'data').stat() + if state['storage_identity'] != {'device': data.st_dev, 'inode': data.st_ino}: + raise ValueError('Registry storage directory was replaced') + # Private files are immutable selected inputs, not merely trusted by + # their original creation. Verify their bytes before each Docker call. + for key, filename in (('ca', 'ca.crt'), ('certificate', 'certificate.pem'), + ('private_key', 'private-key.pem'), ('htpasswd', 'htpasswd')): + path = root/'config'/filename + if path.exists() and hashlib.sha256(support._read(path, 1000000)).hexdigest() != recipe['materials'][key]['sha256']: + raise ValueError('Registry mounted material changed') + configured = root/'config/config.json' + if configured.exists() and support._read(configured) != recipes.canonical(recipes.configuration(recipe)): + raise ValueError('Registry mounted configuration changed') + zipped = root/'probe-input/probe.zip' + if zipped.exists() and hashlib.sha256(support._read(zipped)).hexdigest() != payload['probe_zip_sha256']: + raise ValueError('Registry qualification code changed') + settings = root/'probe-input/qualification.json' + settings_sha = state.get('probe_settings_sha256') + if settings.exists() or settings_sha is not None and not purging: + if (not isinstance(settings_sha, str) or not re.fullmatch('[a-f0-9]{64}', settings_sha) + or hashlib.sha256(support._read(settings, 16384)).hexdigest() != settings_sha): + raise ValueError('Registry mounted qualification settings changed or lack a retained pin') + if hashlib.sha256(support._read(root/'probe-input/ca.crt', 1000000)).hexdigest() != recipe['materials']['ca']['sha256']: + raise ValueError('Registry mounted qualification CA changed') + if support._json(support._read(root/'owner.json'))['binding'] != expected: + raise ValueError('Registry directory ownership changed') + + def save(): + check() + support._write(state_path, recipes.canonical(state), replace=state_path.exists()) + + def command(argv, seconds=30, check_status=True): + check() + result = support._run(argv, min(deadline, time.monotonic()+seconds), check=check_status) + check() + return result + + def inspect(kind, identifier): + result = command(['docker', kind, 'inspect', identifier], check_status=False) + if result.returncode: + if b'No such' in result.stderr or b'not found' in result.stderr: + return None + raise ValueError('Registry Docker observation failed') + value = support._json(result.stdout) + if not isinstance(value, list) or len(value) != 1: + raise ValueError('Unexpected registry Docker inspection') + return value[0] + + def observed(): + found = {} + for role in names: + kind = 'network' if role == 'network' else 'container' + item = inspect(kind, state['ids'].get(role, names[role])) + extras = command(['docker', kind, 'ls', *(['-a'] if kind == 'container' else []), '-q', '--no-trunc', + '--filter', 'label='+LABEL+'='+expected, '--filter', 'label=io.devsecops.registry.role='+role]).stdout.decode().split() + if item is not None: + labels = item.get('Labels', {}) if role == 'network' else item.get('Config', {}).get('Labels', {}) + ident = item.get('Id') + creation = labels.get(OPERATION) + if (not isinstance(ident, str) or not re.fullmatch('[a-f0-9]{64}', ident) + or labels.get(LABEL) != expected or labels.get('io.devsecops.registry.role') != role + or creation not in state['history'] or extras != [ident] + or item.get('Name', '').removeprefix('/') != names[role] + or state['ids'].get(role, ident) != ident): + raise ValueError('Registry resource identity or ownership differs') + if role == 'network': + if item.get('Internal') is not True or item.get('Driver') != 'bridge': + raise ValueError('Registry network isolation differs') + else: + host, config = item.get('HostConfig', {}), item.get('Config', {}) + image = recipe['image']['image_id'] if role == 'registry' else recipe['tool_image'] + networks = item.get('NetworkSettings', {}).get('Networks', {}) + mounts = item.get('Mounts', []) + wanted = [('config', '/config', False), ('data', '/data', True)] if role == 'registry' else [ + ('probe-input', '/input', False), ('probe-output', '/evidence', True)] + actual_mounts = sorted((m.get('Source'), m.get('Destination'), m.get('RW')) for m in mounts) + wanted_mounts = sorted((str(root/name), destination, writable) for name, destination, writable in wanted) + entrypoint = [recipe['image']['entrypoint']] if role == 'registry' else ['/usr/bin/python3'] + args = ['serve', '/config/config.json'] if role == 'registry' else ['-I', '-B', '/input/probe.zip'] + if (item.get('Image') != image or config.get('User') != f'{os.getuid()}:{os.getgid()}' + or config.get('Entrypoint') != entrypoint or config.get('Cmd') != args + or config.get('Healthcheck', {}).get('Test') != ['NONE'] + or host.get('Privileged') is not False or host.get('ReadonlyRootfs') is not True + or host.get('CapAdd') or host.get('CapDrop') != ['ALL'] + or host.get('SecurityOpt') not in (['no-new-privileges'], ['no-new-privileges=true']) + or host.get('PortBindings') or host.get('PidMode') not in ('', None) + or host.get('IpcMode') not in ('private', '') or host.get('Devices') + or host.get('NetworkMode') != names['network'] or host.get('Binds') + or host.get('PidsLimit') != 128 or host.get('Memory') != 1024**3 + or host.get('MemorySwap') != 1024**3 or host.get('NanoCpus') != 10**9 + or host.get('RestartPolicy', {}).get('Name') not in ('no', '') + or set(networks) != {names['network']} or actual_mounts != wanted_mounts): + raise ValueError('Registry container isolation differs') + network = found.get('network') + attached = networks[names['network']].get('NetworkID') + created = item.get('State', {}).get('Status') == 'created' and not item['State'].get('Running') + if network is None or attached != network['Id'] and not (created and attached in ('', None)): + raise ValueError('Registry container network identity differs') + found[role] = item + elif extras: + raise ValueError('Unexpected owned registry resources require reconciliation') + else: + found[role] = None + return found + + def mutate(argv, role, verb, seconds=30): + state['inflight'] = {'operation_id': operation, 'role': role, 'verb': verb} + save() + result = command(argv, seconds) + # Store acknowledgement only after a separate inspect by the caller. + return result + + def retain_material(name, raw, maximum=1000000): + if not isinstance(raw, bytes) or not 1 <= len(raw) <= maximum: + raise ValueError('Registry material exceeds its bound') + path = root/name + if path.exists(): + if support._read(path, maximum) != raw: + raise ValueError('Registry private material changed') + else: + support._write(path, raw) + + try: + resources = observed() + if action == 'reconcile': + report['inflight'] = state['inflight'] + elif action == 'up': + if state['inflight'] or operation in state['history']: + raise ValueError('Registry operation already attempted; reconcile without retry') + if any(resources.values()): + raise ValueError('Existing registry requires read-only observation, not recreation') + # Independent local cache identity checks. Docker never pulls images. + for selected, reference in ((recipe['image']['image_id'], recipe['image']['reference']), + (recipe['tool_image'], None)): + image = inspect('image', selected) + if (image is None or image.get('Id') != selected or image.get('Os') != 'linux' + or image.get('Architecture') != 'amd64' + or reference is not None and (reference not in image.get('RepoDigests', []) + or image.get('Config', {}).get('Entrypoint') != [recipe['image']['entrypoint']])): + raise ValueError('Pinned Linux amd64 image must already exist in the local cache') + if shutil.disk_usage(root).free < 2*1024**3: + raise ValueError('Registry storage headroom is insufficient') + for name in ('config', 'data', 'probe-input', 'probe-output'): + support._private(root/name, create=True) + info = (root/'data').stat() + state['storage_identity'] = {'device': info.st_dev, 'inode': info.st_ino} + for key, filename in (('ca', 'ca.crt'), ('certificate', 'certificate.pem'), + ('private_key', 'private-key.pem'), ('htpasswd', 'htpasswd')): + raw = base64.b64decode(payload['materials'][key], validate=True) + if hashlib.sha256(raw).hexdigest() != recipe['materials'][key]['sha256']: + raise ValueError('Registry material pin differs') + retain_material('config/'+filename, raw) + retain_material('config/config.json', recipes.canonical(recipes.configuration(recipe))) + retain_material('probe-input/ca.crt', base64.b64decode(payload['materials']['ca'], validate=True)) + probe = base64.b64decode(payload['probe_zip'], validate=True) + if hashlib.sha256(probe).hexdigest() != payload['probe_zip_sha256']: + raise ValueError('Registry probe package differs') + retain_material('probe-input/probe.zip', probe) + settings = payload['probe_settings'] + if settings['origin'] != recipe['origin'] or settings['repository'] != recipe['repository']+'/qualification' or settings['binding'] != expected: + raise ValueError('Registry probe scope differs') + if settings.get('expires_at') != payload['expires_at']: + raise ValueError('Registry probe window differs') + settings_raw = recipes.canonical(settings) + retain_material('probe-input/qualification.json', settings_raw, 16384) + state['probe_settings_sha256'] = hashlib.sha256(settings_raw).hexdigest() + state['history'].append(operation) + save() + def labels(role): + return ['--label', LABEL+'='+expected, '--label', OPERATION+'='+operation, + '--label', 'io.devsecops.registry.role='+role] + network = mutate(['docker', 'network', 'create', '--internal', *labels('network'), names['network']], 'network', 'create') + state['ids']['network'] = network.stdout.decode().strip() + if not re.fullmatch('[a-f0-9]{64}', state['ids']['network']): + raise ValueError('Registry network creation did not return an exact ID') + resources = observed() + state['inflight'] = None + save() + for role in ('registry', 'probe'): + mounts = [('config', '/config', True), ('data', '/data', False)] if role == 'registry' else [ + ('probe-input', '/input', True), ('probe-output', '/evidence', False)] + argv = ['docker', 'create', '--pull=never', '--name', names[role], *labels(role), + '--user', f'{os.getuid()}:{os.getgid()}', '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges', + '--read-only', '--no-healthcheck', '--pids-limit', '128', '--cpus', '1', '--memory', str(1024**3), + '--memory-swap', str(1024**3), '--ulimit', 'core=0', '--network', names['network']] + for source, target, readonly in mounts: + argv += ['--mount', f'type=bind,src={root/source},dst={target}'+(',readonly' if readonly else '')] + if role == 'registry': + argv += ['--network-alias', recipes.hostname(recipe), '--entrypoint', recipe['image']['entrypoint'], + recipe['image']['image_id'], 'serve', '/config/config.json'] + else: + # Python admission is native execution in the exact tool + # image, before this fixed entry point can attempt uploads. + argv += ['--entrypoint', '/usr/bin/python3', recipe['tool_image'], '-I', '-B', '/input/probe.zip'] + created = mutate(argv, role, 'create') + state['ids'][role] = created.stdout.decode().strip() + if not re.fullmatch('[a-f0-9]{64}', state['ids'][role]): + raise ValueError('Registry creation did not return an exact ID') + resources = observed() + state['inflight'] = None + save() + mutate(['docker', 'start', state['ids'][role]], role, 'start') + resources = observed() + state['inflight'] = None + if role == 'registry': + if not resources[role]['State']['Running']: + raise ValueError('Registry did not start') + state['bootstrap'] = 'container-running-readiness-unverified' + save() + # Wait on only the owned probe. No automatic re-run on failure. + result = command(['docker', 'wait', state['ids']['probe']], 100) + resources = observed() + if result.stdout.strip() != b'0': + report['storage_qualification'] = 'unknown' + elif (root/'probe-output/qualification.json').exists(): + raw = support._read(root/'probe-output/qualification.json', 1000000) + qualification = support._json(raw) + if (qualification.get('binding_sha256') != expected or qualification.get('origin') != recipe['origin'] + or qualification.get('repository') != recipe['repository']+'/qualification' + or qualification.get('kind') != 'registry-storage-qualification-only' + or qualification.get('canonical_success') is not False): + raise ValueError('Registry qualification output identity differs') + report['qualification'] = qualification + report['storage_qualification'] = qualification['status'] + state['qualification_attempted'] = True + save() + elif inflight is not None and inflight['verb'] == 'create' and resources[inflight['role']] is None: + # A timed-out client does not cancel a Docker daemon request. An + # absent target can still appear later; preserve the original + # creation intent and do not remove its network or replace it with + # a cleanup intent. Only later observation of that exact creation + # can establish a target that this component may remove. + report['cleanup'] = 'unknown-create-still-inflight' + else: + # Cleanup may follow a failed creation; reconcile each exact object + # before removing it. A named match without owned intent is rejected. + if inflight is not None and inflight['verb'] == 'create': + target = resources[inflight['role']] + labels = target['Labels'] if inflight['role'] == 'network' else target['Config']['Labels'] + if labels.get(OPERATION) != inflight['operation_id']: + raise ValueError('Observed creation differs from unresolved registry intent') + if operation not in state['history']: + state['history'].append(operation) + save() + for role in ('probe', 'registry'): + item = resources[role] + if item: + if item['State']['Running']: + mutate(['docker', 'stop', '--time', '10', item['Id']], role, 'stop', 20) + resources = observed() + mutate(['docker', 'rm', item['Id']], role, 'remove') + resources = observed() + if resources[role] is not None: + raise ValueError('Registry container deletion is not observed') + if resources['network']: + if resources['network'].get('Containers'): + raise ValueError('Registry network contains an undeleted member') + mutate(['docker', 'network', 'rm', resources['network']['Id']], 'network', 'remove') + resources = observed() + # Storage and credentials are retained intentionally in this first + # component. It cannot release the factory environment or promise + # irreversible data deletion from a reusable service directory. + state['inflight'] = None + save() + report['cleanup'] = 'owned-runtime-absent-private-material-retained' + if recipe.get('cleanup') == 'remove-owned-private-material': + if state.get('private_purge') is not None: + raise ValueError('Private material purge already attempted; reconcile without retry') + state['private_purge'] = {'operation_id': operation, 'state': 'unknown', + 'root_identity': {'device': root_identity.st_dev, 'inode': root_identity.st_ino}} + save() + _purge_owned_payload(root, (root_identity.st_dev, root_identity.st_ino), deadline) + state['private_purge']['state'] = 'absent' + save() + report['cleanup'] = 'owned-runtime-and-private-material-absent' + report['bootstrap'] = 'container-running' if resources.get('registry') and resources['registry']['State']['Running'] else 'absent' + for role, item in resources.items(): + report['resources'].append({'role': role, 'id': item['Id'] if item else None, + 'state': 'present' if item else 'absent', 'ownership': 'verified' if item else 'not-observed', 'disposition': 'remove'}) + purged = (state.get('private_purge', {}).get('operation_id') == operation + and not any((root/name).exists() or (root/name).is_symlink() + for name in ('data', 'config', 'probe-input', 'probe-output')) + and not any(resources.values()) and state['inflight'] is None) + if action == 'reconcile' and purged: + report['cleanup'] = 'owned-runtime-and-private-material-absent' + report['resources'].append({'role': 'private-storage-and-credentials', 'path': str(root), + 'storage_identity': state['storage_identity'], 'state': 'absent' if purged else 'retained', + 'disposition': 'remove' if recipe.get('cleanup') == 'remove-owned-private-material' else 'preserve'}) + report['resources'].append({'role': 'ownership-and-reconciliation-evidence', 'path': str(root), + 'identity': {'device': root_identity.st_dev, 'inode': root_identity.st_ino}, + 'state': 'preserved', 'disposition': 'preserve'}) + for role, image in (('zot-image-cache', recipe['image']['image_id']), ('probe-tool-image-cache', recipe['tool_image'])): + report['resources'].append({'role': role, 'identity': image, 'disposition': 'preserve', + 'ownership': 'operator-selected-prerequisite', 'created_by_component': False}) + report['inflight'] = state['inflight'] + check() + return report + finally: + os.close(locked) diff --git a/plugins/devsecops/src/devsecops/factory/replay_acceptance.py b/plugins/devsecops/src/devsecops/factory/replay_acceptance.py new file mode 100644 index 0000000..235fcf6 --- /dev/null +++ b/plugins/devsecops/src/devsecops/factory/replay_acceptance.py @@ -0,0 +1,584 @@ +"""D6 acceptance from this process's interrupted child, Git reset and cleanup. + +The final check is read-only. It cannot restore a native, delivery or cleanup +capability from a report, and it performs no API access after resource removal. +""" + +from copy import deepcopy +from dataclasses import replace +import os +import re + +from .lifecycle import AssertionResult, PhaseContext, PhaseOutcome +from .state import ( + MAX_ARTIFACT_BYTES, + MAX_ARTIFACT_TOTAL_BYTES, + StateError, + _canonical, + _exclusive, + _json, + _read, + _sha, +) + +ASSERTIONS = ( + "interruption-has-no-success-receipt", + "baseline-restored-through-git", + "one-new-attempt-d1-d2-replay", + "unowned-resources-preserved", + "owned-resource-deletions-verified", + "residual-resources-reported", + "cleanup-before-terminal-result", +) +_MAIN_STEPS = tuple( + attempt + "-" + step + for attempt in ("primary", "replay") + for step in ("review", "diagnose", "correction", "recovery") +) +_RUNNER_CONTRACT = "owned-runner-vm-v1" +_CLEANUP_SCOPES = frozenset( + { + "foundation", + "registry", + "services", + "service-links", + "kubernetes", + "writer", + "reader", + "gitlab", + "runner-service", + "runner-routes", + "runner-vm", + } +) + + +def _runner_identity(value, *, run_id): + """Check a retained original observation, never issue a VM capability.""" + fields = { + "binding", + "generation", + "guest_boot_id", + "guest_uid", + "guest_gid", + "root_identity", + "disk_identity", + "runtime_id", + "network_id", + "ssh_host_key_sha256", + } + if ( + type(value) is not dict + or set(value) != fields + or value["generation"] != "runner-vm-" + run_id + or type(value["guest_uid"]) is not int + or value["guest_uid"] != 10001 + or type(value["guest_gid"]) is not int + or value["guest_gid"] != 10001 + or any( + not isinstance(value[key], str) or not re.fullmatch("[a-f0-9]{64}", value[key]) + for key in ("binding", "runtime_id", "network_id", "ssh_host_key_sha256") + ) + or not isinstance(value["guest_boot_id"], str) + or not re.fullmatch("[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}", value["guest_boot_id"]) + ): + raise StateError("D6 requires the complete original nonroot runner guest identity") + for key in ("root_identity", "disk_identity"): + if ( + type(value[key]) is not dict + or set(value[key]) != {"device", "inode"} + or any(type(item) is not int or item < 0 for item in value[key].values()) + or value[key]["inode"] == 0 + ): + raise StateError("D6 runner guest filesystem identity is missing or changed") + if value["root_identity"] == value["disk_identity"]: + raise StateError("D6 runner root and disk cannot be the same filesystem object") + return deepcopy(value) + + +def _runner_originals(cleanup, *, journal, report): + """Audit original up/down handles after cleanup; no endpoint access.""" + from .owned_runner_vm import OwnedRunnerVM + from .owned_runner_service import OwnedRunnerService + from .runner_vm_routes import OwnedRunnerVMRoutes + from .owned_linux import _plain + + selected = { + "runner-vm": OwnedRunnerVM, + "runner-service": OwnedRunnerService, + "runner-routes": OwnedRunnerVMRoutes, + } + vm = cleanup.components.get("runner-vm") + if ( + type(vm) is not OwnedRunnerVM + or getattr(cleanup.components.get("runner-service"), "vm", None) is not vm + or getattr(cleanup.components.get("runner-routes"), "vm", None) is not vm + or getattr(vm, "_children", None) + != { + "runner": cleanup.components.get("runner-service"), + "routes": cleanup.components.get("runner-routes"), + } + ): + raise StateError("D6 requires the original runner service and routes bound to this VM") + original, history = None, {} + for kind, cls in selected.items(): + component, attempt = cleanup.components.get(kind), cleanup.attempts.get(kind) + if ( + type(component) is not cls + or component.journal is not journal + or type(attempt) is not dict + or attempt.get("up_outcome") is None + or attempt.get("outcome") is None + or not attempt.get("up_operation") + or attempt.get("down_attempted") is not True + ): + raise StateError("D6 requires original runner creation and cleanup handles: " + kind) + up = _plain(component.cleanup_observation(attempt["up_outcome"])) + down = _plain(component.cleanup_observation(attempt["outcome"])) + if ( + up.get("run_id") != journal.state["run_id"] + or down.get("run_id") != journal.state["run_id"] + or up.get("identities") != journal.identities + or down.get("identities") != journal.identities + or up.get("action") != "up" + or up.get("operation_id") != attempt["up_operation"] + or down.get("action") not in ("down", "reconcile") + or down.get("operation_id") != attempt.get("down_operation") + or down != report["components"].get(kind) + or down != attempt.get("observation") + ): + raise StateError("D6 runner history differs from original accepted observations: " + kind) + identity = _runner_identity(up.get("runner_vm"), run_id=journal.state["run_id"]) + if identity != down.get("runner_vm") or original is not None and identity != original: + raise StateError("D6 runner service, routes and VM do not share one original guest") + original = identity + history[kind] = { + "up_operation_id": up["operation_id"], + "down_operation_id": down["operation_id"], + "up_observation_sha256": _sha(_canonical(up)), + "down_observation_sha256": _sha(_canonical(down)), + } + if kind == "runner-service": + registration = {key: up.get(key) for key in ("runner_id", "runner_manager_system_identity")} + if ( + type(registration["runner_id"]) is not int + or registration["runner_id"] <= 0 + or not isinstance(registration["runner_manager_system_identity"], str) + or not 1 <= len(registration["runner_manager_system_identity"]) <= 256 + or up.get("service_ready") is not True + or down.get("service_ready") is not False + or any(down.get(key) != value for key, value in registration.items()) + ): + raise StateError("D6 runner service removal differs from its original running registration") + history[kind]["registration"] = registration + if len({row["up_operation_id"] for row in history.values()}) != 1: + raise StateError("D6 runner components were not created by the same original provisioning operation") + return { + "runner_vm": original, + "component_history": history, + "basis": "original-resident-up-and-cleanup-observations", + } + + +def _reset_binding(baseline, recovery, reset, *, run_id, operation_id): + """Check actual authenticated deliveries; this function issues no origin.""" + rows = (baseline, recovery, reset) + if any( + row.get("run_id") != run_id + or row.get("delivery_stage") != "merged-watched-branch" + or row.get("watched_revision") != row.get("deployment_commit") + or not re.fullmatch("[a-f0-9]{40}", row.get("deployment_commit", "")) + for row in rows + ): + raise StateError("D6 requires the original watched Git deliveries") + if ( + baseline.get("phase") != "build-promote" + or recovery.get("phase") != "primary-deliver" + or reset.get("phase") != "reset" + or reset.get("attempt") != "replay" + or reset.get("operation_id") != operation_id + or reset.get("parent") != recovery["deployment_commit"] + or reset["deployment_commit"] in {baseline["deployment_commit"], recovery["deployment_commit"]} + or any( + reset.get(key) != baseline.get(key) or reset.get(key) is None + for key in ("tree", "source_commit", "repository_url", "project_id", "image_refs") + ) + or reset.get("source_kind") != "qualified-policy-change" + ): + raise StateError( + "D6 reset must create a new observed commit restoring the exact baseline tree and images" + ) + source = reset.get("source_provenance", {}) + if ( + source.get("kind") != "qualified-policy-source" + or source.get("run_id") != run_id + or source.get("operation_id") != operation_id + or source.get("phase") != "reset" + or source.get("previous_commit") != recovery["deployment_commit"] + or not re.fullmatch("[a-f0-9]{64}", source.get("qualification_sha256", "")) + or source.get("native_request_sha256") is not None + ): + raise StateError("D6 reset differs from its original qualified baseline-restoration source") + return { + "baseline_commit": baseline["deployment_commit"], + "recovery_commit": recovery["deployment_commit"], + "reset_commit": reset["deployment_commit"], + "restored_tree": reset["tree"], + "source_commit": reset["source_commit"], + "image_refs": deepcopy(reset["image_refs"]), + "operation_id": operation_id, + "source_provenance": deepcopy(source), + } + + +def _replay_checks(state, assertion_document, *, child_run_id, child_request_id): + """Require the actual accepted main history, not a count or fixture verdict.""" + life = state["lifecycle"] + expected = [phase["id"] for phase in life["phases"] if phase["id"] != "finalize"] + records = life["phase_records"] + if ( + life.get("abort") is not None + or [row["phase_id"] for row in records] != expected + or len(set(expected)) != 32 + or any(row["outcome"] != "completed" for row in records) + ): + raise StateError("D6 needs exactly the completed primary, reset, replay and cleanup history") + phases = {phase["id"]: phase for phase in life["phases"]} + for attempt in ("primary", "replay"): + seen = set() + for row in records: + if phases[row["phase_id"]]["attempt"] != attempt: + continue + for check in row["assertions"]: + if check["case_id"] not in ("D1", "D2"): + continue + if check["status"] != "pass": + raise StateError("D6 cannot promote failed or unknown primary/replay evidence") + seen.add((check["case_id"], check["assertion_id"])) + required = {(case, check) for case in ("D1", "D2") for check in assertion_document["cases"][case]} + if not required or seen != required: + raise StateError("D6 requires every original D1/D2 assertion in both attempts") + native = state["native_results"] + if ( + [row["step_id"] for row in native] != list(_MAIN_STEPS) + or any(row["status"] != "completed" for row in native) + or len({row["request_id"] for row in native}) != 8 + or child_request_id in {row["request_id"] for row in native} + or child_run_id == state["run_id"] + ): + raise StateError("D6 needs eight distinct accepted main requests and a separate interrupted attempt") + requests = state["native_requests"] + if [row["step_id"] for row in requests] != list(_MAIN_STEPS) or { + row["request_id"] for row in requests + } != {row["request_id"] for row in native}: + raise StateError("D6 main native request history differs from its accepted results") + return { + "main_steps": list(_MAIN_STEPS), + "main_request_ids": [row["request_id"] for row in native], + "replay_count": 1, + "accepted_d1_d2_per_attempt": len(required), + } + + +def _cleanup_checks(state, report, validation, *, inventory_contract): + checks = { + "owned-resource-inventory-closed", + "owned-resource-absence-observed", + "retained-resources-protected", + "cleanup-current-operation-bound", + } + if ( + state["execution_status"] != "released" + or state["environment_reserved"] + or state["active_mutation"] is not None + or state["active_native"] is not None + or state["lifecycle"]["final_result"] is not None + or report.get("kind") != "canonical-owned-cleanup" + or report.get("complete_cleanup") is not True + or report.get("mutation_effect") != "applied" + or report.get("gaps") != [] + or report.get("run_id") != state["run_id"] + or report.get("identities") != state["identities"] + or validation.get("run_id") != state["run_id"] + or validation.get("environment_sha256") != state["identities"]["environment_sha256"] + or validation.get("operation_id") != report.get("operation_id") + or not checks <= set(validation.get("checks", [])) + ): + raise StateError("D6 needs the original validated and durably released complete cleanup") + scopes = _CLEANUP_SCOPES + if ( + inventory_contract != _RUNNER_CONTRACT + or report.get("inventory_contract") != inventory_contract + or set(report.get("components", {})) != scopes + or report.get("never_dispatched_scopes") != [] + or report.get("resident_no_effects_closure") is not False + ): + raise StateError("D6 requires the exact runner-VM factory inventory, not legacy or early cleanup") + from .owned_cleanup import OwnedCleanupCoordinator + + if any( + not isinstance(value, dict) or not OwnedCleanupCoordinator._resolved(kind, value) + for kind, value in report["components"].items() + ): + raise StateError("D6 has an unresolved component cleanup observation") + foundation = report["components"]["foundation"] + protected = [row for row in foundation.get("resources", []) if row.get("disposition") == "preserve"] + if not protected or any(row.get("state") != "preserved" for row in protected): + raise StateError("D6 lacks actual preservation of selected source and baseline resources") + for name in ("runner-vm", "runner-service", "runner-routes"): + rows = report["components"][name].get("resources", []) + if ( + not rows + or not any(row.get("disposition") == "remove" for row in rows) + or any( + row.get("disposition") not in ("remove", "preserve") + or row.get("state") != ("absent" if row["disposition"] == "remove" else "preserved") + for row in rows + ) + ): + raise StateError("D6 runner resource removal or preservation is incomplete: " + name) + runner_protected = [ + row for row in report["components"]["runner-vm"]["resources"] if row.get("disposition") == "preserve" + ] + if not runner_protected: + raise StateError("D6 lacks preservation of the runner VM source assets") + removed = [ + row + for value in report["components"].values() + for row in value.get("resources", []) + if row.get("disposition") == "remove" + ] + if not removed or any(row.get("state") != "absent" for row in removed): + raise StateError("D6 owned resource absence is incomplete") + return { + "operation_id": report["operation_id"], + "inventory_contract": inventory_contract, + "component_scopes": sorted(scopes), + "protected_resources": deepcopy(protected), + "runner_protected_resources": deepcopy(runner_protected), + "removed_resource_count": len(removed), + "reported_gaps": [], + "unowned_scope": "selected-preserved-inputs-and-original-baseline-resources", + "published_before_terminal": True, + } + + +class OwnedReplayAcceptance: + def __init__(self, production): + from .owned_production import OwnedProductionCoordinator + + if type(production) is not OwnedProductionCoordinator: + raise StateError("D6 needs the original concrete production coordinator") + self.production, self.journal, self.pid = production, production.journal, os.getpid() + self.run_id, self.identities = self.journal.state["run_id"], dict(self.journal.identities) + self._started, self._interruption, self._reset = False, None, None + self._files, self._deliveries = {}, None + + def __reduce__(self): + raise StateError("D6 acceptance cannot be restored from saved evidence") + + def _admit(self, context, operation): + self.production._current() + if ( + self.pid != os.getpid() + or self.production.journal is not self.journal + or self.journal.state["run_id"] != self.run_id + or self.journal.identities != self.identities + or type(context) is not PhaseContext + or context.phase["id"] != operation + or context.phase["operation"] != operation + or context.run_id != self.run_id + or context.run_dir != self.journal.run_dir + or dict(context.identities) != self.identities + or context.remaining_seconds() <= 0 + ): + raise StateError("D6 requires its original current reset or finalization phase") + self.production.driver._admit(context, context.deadline) + self.production.driver._package(self.identities["package_sha256"], context.deadline) + for path, pin in self._files.items(): + if _sha(_read(path, MAX_ARTIFACT_BYTES)) != pin: + raise StateError("Original D6 acceptance bytes changed") + + def _save(self, name, value): + path = self.journal.run_dir / "canonical-cases" / "D6" / name + _exclusive(path, _canonical(value)) + self._files[path] = _sha(_read(path, MAX_ARTIFACT_BYTES)) + return path + + def begin_reset(self, context): + self._admit(context, "reset") + if self._started: + raise StateError("D6 reset/interruption was already attempted") + self.journal.current_mutation("reset", "reset") + self._started = True + root = self.journal.run_dir / "canonical-cases" + root.mkdir(mode=0o700, exist_ok=True) + (root / "D6").mkdir(mode=0o700) + from .case_interruption import execute_interrupted_review, require_interruption + + self._interruption = execute_interrupted_review( + context, production=self.production, output=root / "D6" / "interruption" + ) + binding = require_interruption(self._interruption, journal=self.journal) + self._interrupted(binding) + self._save("interruption-acceptance.json", binding) + + def _interrupted(self, value): + if ( + value.get("parent_run_id") != self.run_id + or value.get("child_run_id") == self.run_id + or not value.get("child_run_id") + or not value.get("request_id") + or value.get("status") != "cancelled" + or value.get("spawned") is not True + or value.get("reaped") is not True + or value.get("accepted_results") != 0 + or value.get("usable_success_receipt") is not False + ): + raise StateError("D6 needs an actual spawned, reaped and cancelled separate native attempt") + + def retain_reset(self, context, outcome): + self._admit(context, "reset") + if self._interruption is None or self._reset is not None: + raise StateError("D6 reset requires its original interruption and one new reset effect") + if outcome.status != "completed" or outcome.mutation_effect != "applied": + return outcome + operations = self.production.operations + keys = (("primary", "baseline"), ("primary", "recovery"), ("replay", "baseline")) + self._deliveries = tuple(operations.delivery(*key) for key in keys) + from .owned_git_delivery import require_delivery + + bindings = [require_delivery(value, journal=self.journal) for value in self._deliveries] + self._reset = _reset_binding( + *bindings, run_id=self.run_id, operation_id=self.journal.current_mutation("reset", "reset") + ) + self._save( + "reset-git-acceptance.json", {"run_id": self.run_id, "identities": self.identities, **self._reset} + ) + return replace(outcome, artifacts=self._artifacts(outcome.artifacts)) + + def _artifacts(self, other=()): + from .case_interruption import interruption_artifacts + + paths = tuple( + sorted( + set( + (*other, *self._files, *interruption_artifacts(self._interruption, journal=self.journal)) + ), + key=str, + ) + ) + if ( + len(paths) > 255 + or sum(len(_read(path, MAX_ARTIFACT_BYTES)) for path in paths) > MAX_ARTIFACT_TOTAL_BYTES + ): + raise StateError("D6 original evidence exceeds the phase artifact bound") + return paths + + def finalize(self, context): + self._admit(context, "finalize") + if self._reset is None or self._deliveries is None or self._interruption is None: + raise StateError("D6 has no original reset/interruption proof") + from .case_interruption import require_interruption + from .owned_git_delivery import require_delivery + from .owned_cleanup import OwnedCleanupCoordinator + from .native_factory_session import NativeFactorySession + from .canonical_bootstrap import OwnedBootstrapCoordinator + + interrupted = require_interruption(self._interruption, journal=self.journal) + self._interrupted(interrupted) + bindings = [require_delivery(value, journal=self.journal) for value in self._deliveries] + if ( + _reset_binding(*bindings, run_id=self.run_id, operation_id=self._reset["operation_id"]) + != self._reset + ): + raise StateError("D6 original Git reset binding changed") + state = self.journal.state + replay = _replay_checks( + state, + context.inputs["assertions"], + child_run_id=interrupted["child_run_id"], + child_request_id=interrupted["request_id"], + ) + native = self.production.driver._native_session + if ( + type(native) is not NativeFactorySession + or native._journal is not self.journal + or native._driver is not self.production.driver + ): + raise StateError("D6 needs the original resident main native session") + # The same accessor already binds each accepted result/request/manifest + # to its resident origin. Audit all eight again, without duplicating + # their trace files into this final phase or renewing model authority. + for step in _MAIN_STEPS: + native.completed_step_artifacts(step) + cleanup = self.production.cleanup + if ( + type(cleanup) is not OwnedCleanupCoordinator + or cleanup.journal is not self.journal + or cleanup.pid != os.getpid() + or cleanup._terminal is None + ): + raise StateError("D6 requires the original resident cleanup observer") + report = cleanup._observations.observe(cleanup._terminal) + originals = tuple(_read(path, MAX_ARTIFACT_BYTES) for path in cleanup._terminal.artifacts) + frozen = tuple( + _read(self.journal._artifact_path(ref["path"]), MAX_ARTIFACT_BYTES) + for ref in state["cleanup_artifacts"] + ) + if originals != frozen: + raise StateError("D6 cleanup differs from the exact atomically accepted receipts") + for kind, attempt in cleanup.attempts.items(): + if attempt["outcome"] is not None: + from .owned_linux import _plain + + if ( + _plain(cleanup.components[kind].cleanup_observation(attempt["outcome"])) + != attempt["observation"] + ): + raise StateError("D6 original cleanup component evidence changed") + validation_path = self.journal._artifact_path(state["cleanup_validation"]["path"]) + validation = _json(_read(validation_path, MAX_ARTIFACT_BYTES)) + bootstrap = self.production.bootstrap + if ( + type(bootstrap) is not OwnedBootstrapCoordinator + or bootstrap.journal is not self.journal + or bootstrap.driver is not self.production.driver + or bootstrap.cleanup is not cleanup + or any( + getattr(bootstrap, attribute, None) is not cleanup.components.get(scope) + for attribute, scope in ( + ("_runner_vm", "runner-vm"), + ("_runner_service", "runner-service"), + ("_runner_routes", "runner-routes"), + ) + ) + ): + raise StateError("D6 requires the original bootstrap inventory selection") + cleaned = _cleanup_checks( + state, report, validation, inventory_contract=bootstrap.cleanup_inventory_contract() + ) + cleaned["runner"] = _runner_originals(cleanup, journal=self.journal, report=report) + self._save( + "case-result.json", + { + "schema_version": 1, + "kind": "original-live-replay-acceptance", + "run_id": self.run_id, + "identities": self.identities, + "interruption": interrupted, + "git_reset": self._reset, + "replay": replay, + "cleanup": cleaned, + "assertions": list(ASSERTIONS), + "authority": "historical-acceptance-only", + "canonical_success": False, + }, + ) + return PhaseOutcome( + "completed", + "owned-live-replay-and-cleanup-observed", + self._artifacts((*cleanup._terminal.artifacts, validation_path)), + tuple(AssertionResult("D6", name, "pass") for name in ASSERTIONS), + mutation_effect="not_applied", + ) diff --git a/plugins/devsecops/src/devsecops/factory/resident_cleanup_control.py b/plugins/devsecops/src/devsecops/factory/resident_cleanup_control.py new file mode 100644 index 0000000..3c21f69 --- /dev/null +++ b/plugins/devsecops/src/devsecops/factory/resident_cleanup_control.py @@ -0,0 +1,119 @@ +"""Bounded explicit terminal controls retaining the original lifecycle process. + +Only an opted-in interactive terminal can request these fixed actions. No saved +report, control file, pipe, command callback or automatic deletion retry exists. +""" + +from __future__ import annotations + +import json +import os +import secrets +import select +import sys +import time + +from .state import StateError, PARENT_DISPOSAL_MODE + + +def require_terminal(): + if not sys.stdin.isatty() or not sys.stderr.isatty(): + raise StateError("Resident cleanup controls require interactive stdin and stderr terminals") + return sys.stdin.fileno() + + +def _line(fd, deadline): + value = bytearray() + while len(value) < 512: + remaining = deadline - time.monotonic() + if remaining <= 0: + return None + readable, _, _ = select.select([fd], [], [], min(60, remaining)) + if not readable: + continue + item = os.read(fd, 1) + if not item: + return None + if item == b"\n": + if time.monotonic() >= deadline: + return None + try: + return value.decode("ascii").strip() + except UnicodeDecodeError as error: + raise StateError("Cleanup control must be bounded ASCII") from error + value.extend(item) + raise StateError("Cleanup control exceeds its bound") + + +def wait_for_cleanup(engine, result, *, enabled=False): + if not enabled: + return result + from .lifecycle import LifecycleEngine + + if type(engine) is not LifecycleEngine: + raise StateError("Resident cleanup controls require the original lifecycle engine") + fd = require_terminal() + deadline = time.monotonic() + 300 + for _ in range(16): + state = engine.journal.state + if state["execution_status"] == "released": + return engine.advance() + pending = state["active_mutation"] + previous = next((o for o in reversed(state["operations"]) if o["action"] == "down"), None) + if pending is not None and pending["action"] == "down": + action, operation = "reconcile", pending["operation_id"] + elif pending is None and previous is not None and previous["status"] == "partial": + modes = previous.get("cleanup_continuation_modes", ["normal"]) + if modes not in (["normal"], [PARENT_DISPOSAL_MODE]): + raise StateError("Unsupported cleanup continuation selection") + action = "dispose-runner-guest" if modes == [PARENT_DISPOSAL_MODE] else "continue" + operation = previous["operation_id"] + else: + return result + nonce = secrets.token_hex(12) + print( + json.dumps( + { + "kind": "resident-cleanup-control", + "run_id": state["run_id"], + "operation_id": operation, + "state": "unknown" if action == "reconcile" else "terminal-partial", + "command": f"{action} {operation} {nonce}", + "stop_command": f"stop {nonce}", + "action": "read-only-reconciliation" + if action == "reconcile" + else "new-authorized-runner-guest-disposal" + if action == "dispose-runner-guest" + else "new-authorized-cleanup-operation", + "expires_in_seconds": max(0, int(deadline - time.monotonic())), + } + ), + file=sys.stderr, + flush=True, + ) + command = _line(fd, deadline) + if time.monotonic() >= deadline or command is None or command == f"stop {nonce}": + return result + if command != f"{action} {operation} {nonce}": + raise StateError( + "Cleanup command does not match the current operation and fresh terminal challenge" + ) + try: + result = ( + engine.reconcile_cleanup(operation_id=operation) + if action == "reconcile" + else engine.continue_cleanup(prior_operation_id=operation, + cleanup_mode=PARENT_DISPOSAL_MODE) + if action == "dispose-runner-guest" + else engine.continue_cleanup(prior_operation_id=operation) + ) + except Exception: + # Do not disclose provider/credential details. The current journal + # determines whether the next explicit action is still read-only. + result = engine._snapshot("cleanup-control-requires-inspection") + print( + '{"kind":"resident-cleanup-control","action_result":"not-completed-inspect-retained-evidence"}', + file=sys.stderr, + flush=True, + ) + return result diff --git a/plugins/devsecops/src/devsecops/factory/runner_install.py b/plugins/devsecops/src/devsecops/factory/runner_install.py new file mode 100644 index 0000000..8d3eaa9 --- /dev/null +++ b/plugins/devsecops/src/devsecops/factory/runner_install.py @@ -0,0 +1,291 @@ +"""Direct, bounded runner-input compilation from the current approved templates.""" + +from copy import deepcopy +import os +import uuid +from pathlib import Path +from weakref import WeakKeyDictionary +from .bootstrap_recipe import canonical +from .mission_git_invocation import invocation_configuration +from .state import StateError, _json, _read, _safe_path, _sha + +_PLANS = WeakKeyDictionary() +_NAMES = ("build", "staging", "security", "signing", "publication", "proposal") +_ROOT = "/opt/devsecops/runner-inputs/" + + +class RunnerInstallPlan: + __slots__ = ("__weakref__",) + + def __new__(cls): + raise TypeError("Runner installation requires direct current template compilation") + + def __reduce__(self): + raise TypeError("Runner installation plan cannot be serialized") + + +def prepare_runner_install(stack, context): + from .owned_services import OwnedServiceStack + + if type(stack) is not OwnedServiceStack: + raise StateError("Fixed owned service stack required") + stack.driver._admit(context, context.deadline) + raw_recipe = _read(_safe_path(stack.recipe_path), 256000) + if _sha(raw_recipe) != stack.recipe_sha256: + raise StateError("Selected runner recipe changed") + from .bootstrap_recipe import validate + + recipe = validate(_json(raw_recipe)) + vm_recipe = None + input_root = _ROOT + extra_refs = {str(stack.recipe_path): (stack.recipe_sha256, 256000)} + guest = None + if recipe["schema_version"] == 2: + from . import runner_vm_recipe + from .owned_linux import _plain + + vm_ref = recipe["services"]["runner_vm"] + raw_vm = _read(_safe_path(Path(vm_ref["path"])), 64000) + if _sha(raw_vm) != vm_ref["sha256"]: + raise StateError("Selected runner VM recipe changed") + vm_recipe = runner_vm_recipe.validate_against_foundation( + _json(raw_vm), _plain(context.inputs["config"]["runtime"]["foundation"]) + ) + extra_refs[vm_ref["path"]] = (vm_ref["sha256"], 64000) + download_ref = vm_recipe["egress"].get("blob_download_policy") + if download_ref is not None: + download_raw = _read(_safe_path(Path(download_ref["path"])), 16384) + runner_vm_recipe.blob_policy_document(download_raw, download_ref["sha256"]) + extra_refs[download_ref["path"]] = (download_ref["sha256"], 16384) + guest = runner_vm_recipe.guest_paths(context.run_id) + input_root = guest["inputs"] + "/" + + def input_target(value): + if not value.startswith(_ROOT): + raise StateError("Runner input requires its original logical target prefix") + return input_root + value.removeprefix(_ROOT) + + source = stack.driver.auxiliary_sources.get("mission_git_invocation") + if type(source) is not tuple: + raise StateError("Owned runner requires the original pinned mission invocation") + raw = _read(_safe_path(source[0]), 64000) + if _sha(raw) != source[1]: + raise StateError("Original runner invocation changed") + selected = invocation_configuration(raw) + if selected["run_scope"] != stack.journal.identities: + raise StateError("Runner templates differ from current run") + if vm_recipe and ( + selected["plugin_id"] != stack.driver.plugin_id + or selected["plugin_version"] != stack.driver.plugin_version + ): + raise StateError("Runner VM must use the actual current installed package identity") + refs = {**extra_refs, str(source[0]): (source[1], 64000)} + entries = {} + mapping = {} + for material in recipe["services"]["runner_materials"]: + ref = material["file"] + path = _safe_path(Path(ref["path"])) + data = _read(path, 1000000) + if _sha(data) != ref["sha256"] or material["private"] and path.stat().st_mode & 0o077: + raise StateError("Runner selected material differs or lacks private permissions") + refs[str(path)] = (ref["sha256"], 1000000) + target = input_target(material["target"]) + mapping[str(path)] = target + entries[target] = {"content": data, "private": material["private"]} + + registry_ref = recipe["registry"] + registry_raw = _read(_safe_path(Path(registry_ref["path"])), 64000) + if _sha(registry_raw) != registry_ref["sha256"]: + raise StateError("Runner registry trust selection changed") + from .service_recipe import validate as registry_configuration + + registry = registry_configuration(_json(registry_raw)) + refs[registry_ref["path"]] = (registry_ref["sha256"], 64000) + trust = {} + trust_refs = [ + ("gitlab", recipe["services"]["materials"]["ca"]), + ("registry", registry["materials"]["ca"]), + ] + if vm_recipe and vm_recipe["egress"]["external_ca_bundle"] is not None: + trust_refs.append(("external", vm_recipe["egress"]["external_ca_bundle"])) + for service, ref in trust_refs: + path = _safe_path(Path(ref["path"])) + data = _read(path, 1000000) + if _sha(data) != ref["sha256"]: + raise StateError("Runner owned service public CA differs from its selected pin") + target = input_root + "service-trust/" + service + "-ca.pem" + if target in entries or ( + str(path) in mapping + and mapping[str(path)] != target + and mapping[str(path)] not in {row["path"] for row in trust.values()} + ): + raise StateError("Runner service trust conflicts with an existing material mapping") + refs[str(path)] = (ref["sha256"], 1000000) + mapping.setdefault(str(path), target) + entries[target] = {"content": data, "private": False} + trust[service] = {"path": target, "sha256": ref["sha256"]} + + def mapped(value): + if type(value) is dict: + return {key: mapped(child) for key, child in value.items()} + if type(value) is list: + return [mapped(child) for child in value] + return mapping.get(value, value) if type(value) is str else value + + from .mission_operation import _configuration as build + from .mission_staging import _configuration as staging + from .mission_security_operation import _configuration as security + from .mission_signing import signing_configuration as signing + from .mission_publication import publication_configuration as publication + + from .deployment_proposal import proposal_configuration as proposal + + parsers = dict(zip(_NAMES, (build, staging, security, signing, publication, proposal))) + digests, original = {}, {} + for name in _NAMES: + ref = selected["configurations"][name] + data = _read(_safe_path(Path(ref["path"])), 64000) + if _sha(data) != ref["sha256"]: + raise StateError("Runner original component template changed") + refs[ref["path"]] = (ref["sha256"], 64000) + original[name] = ref["sha256"] + original_value = parsers[name](data) + if vm_recipe and name == "build": + external = vm_recipe["egress"]["external_ca_bundle"] + if ( + "https://registry1.dso.mil" not in vm_recipe["egress"]["external_origins"] + or external is None + or original_value.get("registry_auth", {}).get("ca_bundle") != external["path"] + ): + raise StateError( + "Runner VM build requires explicit Registry1 selection and its exact pinned external trust" + ) + download_ref = vm_recipe["egress"].get("blob_download_policy") + if original_value.get("blob_download_policy") != download_ref: + raise StateError("Runner VM route and build blob policies must be the same pinned selection") + if download_ref is not None and ( + download_ref["path"] not in mapping + or _sha(entries[mapping[download_ref["path"]]]["content"]) != download_ref["sha256"] + ): + raise StateError("Runner blob policy must be an explicitly staged immutable material") + if name == "build" and "attestation_size_policy" in original_value: + from devsecops.adapters.registry_attestation_policy import parse_attestation_size_policy + from devsecops.adapters.image_policy import _policy as image_policy + + size_ref = original_value["attestation_size_policy"] + image_ref = original_value["image"] + if size_ref["path"] not in mapping or image_ref["policy"] not in mapping: + raise StateError("Runner attestation and image policies must be explicitly staged materials") + size_raw = entries[mapping[size_ref["path"]]]["content"] + image_raw = entries[mapping[image_ref["policy"]]]["content"] + if _sha(size_raw) != size_ref["sha256"] or _sha(image_raw) != image_ref["policy_sha256"]: + raise StateError("Runner attestation or image policy differs from its original pin") + try: + subject = image_policy(image_raw)["subject"] + parse_attestation_size_policy(size_raw, size_ref["sha256"], origin=subject["origin"], + repository=subject["repository"], subject_digest=subject["digest"]) + except ValueError: + raise StateError("Runner attestation policy does not bind the exact selected image") from None + value = mapped(original_value) + if name == "build": + value["owner_uid"] = 10001 + elif name == "proposal": + validation = recipe["services"]["runner_validation"] + for tool in ("helm", "kubeconform"): + value[tool + "_path"] = validation[tool]["path"] + value[tool + "_sha256"] = validation[tool]["sha256"] + value["schemas_path"] = validation["schemas_path"] + encoded = canonical(value) + parsers[name](encoded) + target = input_root + name + ".json" + digests[name] = _sha(encoded) + if target in entries: + raise StateError("Runner material collides with a derived configuration") + entries[target] = {"content": encoded, "private": False} + selected["configurations"][name] = {"path": target, "sha256": digests[name]} + selected["output"] = "/home/gitlab-runner/builds/factory-" + context.run_id + "/publication" + # Keep all 128 run-identity bits while fitting the real build admission's + # 60-byte runtime-root limit and the existing runner-builds volume. + run_identity = uuid.UUID(context.run_id) + if str(run_identity) != context.run_id: + raise StateError("Runner requires the exact canonical run UUID") + selected["runtime_root"] = "/home/gitlab-runner/builds/" + run_identity.hex + target = recipe["services"]["runner_environment"]["DEVSECOPS_GIT_INVOCATION"] + if vm_recipe: + target = input_target(target) + if target in entries: + raise StateError("Runner material collides with its derived invocation") + encoded = canonical(selected) + invocation_configuration(encoded) + entries[target] = {"content": encoded, "private": False} + environment = deepcopy(recipe["services"]["runner_environment"]) + environment["DEVSECOPS_GIT_INVOCATION"] = target + environment["DEVSECOPS_GIT_INVOCATION_SHA256"] = _sha(encoded) + secrets = {} + for name in recipe["services"]["runner_secret_environment"]: + value = os.environ.get(name) + if ( + not isinstance(value, str) + or not 1 <= len(value) <= 8192 + or any(ord(c) < 32 or ord(c) > 126 for c in value) + ): + raise StateError("Selected runner private environment is unavailable") + secrets[name] = value + if sum(len(row["content"]) for row in entries.values()) > 1500000: + raise StateError( + "Runner inline input bundle exceeds bound; large locked assets belong in the selected runner image" + ) + plan = object.__new__(RunnerInstallPlan) + _PLANS[plan] = { + "stack": stack, + "pid": os.getpid(), + "run_id": context.run_id, + "refs": refs, + "entries": entries, + "environment": environment, + "secrets": secrets, + "config_sha256": digests, + "original_template_sha256": original, + "service_trust": trust, + "runner_profile": "owned-runner-vm-v1" if vm_recipe else "legacy-container-runner-v1", + "guest_paths": guest, + "guest_package": None + if vm_recipe is None + else { + "root": environment["DEVSECOPS_PLUGIN_ROOT"], + "manifest_sha256": stack.journal.identities["package_sha256"], + "plugin_id": selected["plugin_id"], + "plugin_version": selected["plugin_version"], + }, + } + return plan + + +def _original_runner_install(plan, stack, context): + record = _PLANS.get(plan) if type(plan) is RunnerInstallPlan else None + if ( + record is None + or record["stack"] is not stack + or record["pid"] != os.getpid() + or record["run_id"] != context.run_id + ): + raise StateError("Original same-process runner installation plan required") + return record + + +def inspect_runner_install(plan, stack, context): + """Reaudit original compiled data; this does not admit guest installation.""" + record = _original_runner_install(plan, stack, context) + stack.driver._admit(context, context.deadline) + for path, (digest, bound) in record["refs"].items(): + if _sha(_read(_safe_path(Path(path)), bound)) != digest: + raise StateError("Runner selected input changed before staging") + if any(os.environ.get(name) != value for name, value in record["secrets"].items()): + raise StateError("Runner selected private environment changed before staging") + return deepcopy({key: value for key, value in record.items() if key not in ("stack", "pid", "refs")}) + + +def require_runner_install(plan, stack, context): + _original_runner_install(plan, stack, context) + stack._admit(context, "up") + return inspect_runner_install(plan, stack, context) diff --git a/plugins/devsecops/src/devsecops/factory/runner_package.py b/plugins/devsecops/src/devsecops/factory/runner_package.py new file mode 100644 index 0000000..9df4db1 --- /dev/null +++ b/plugins/devsecops/src/devsecops/factory/runner_package.py @@ -0,0 +1,275 @@ +"""Read-only admission of the preselected package in the owned Linux CI guest. + +Only the two fixed CI entry points use this contract. It is not a Codex install, +capability restoration, or an alternative path for the native desktop driver. +""" + +from __future__ import annotations + +import math +import os +from pathlib import Path +import platform +import pwd +import re +import stat +import sys + +from devsecops.adapters.vulnerability_policy import checkpoint +from .state import _json, _sha + +ROOT = Path(__file__).resolve().parents[3] +_PREFIX = Path("/opt/devsecops") +_HOME = "/home/gitlab-runner" +_UID = 10001 +_MAX_FILES = 1024 +_MAX_DIRECTORIES = 1024 +_MAX_FILE_BYTES = 16_000_000 +_MAX_TOTAL_BYTES = 128_000_000 +_SEGMENT = r"[A-Za-z0-9][A-Za-z0-9._+-]{0,119}" +_ENTRYPOINTS = ("scripts/publish_owned_mission.py", "scripts/validate_owned_deployment.py") + + +def _identity(info): + return ( + info.st_dev, + info.st_ino, + info.st_mode, + info.st_uid, + info.st_gid, + info.st_size, + info.st_mtime_ns, + info.st_ctime_ns, + ) + + +def _owned(path, deadline, *, directory=False): + checkpoint(deadline) + if not path.is_absolute() or str(path) != os.path.normpath(str(path)) or ".." in path.parts: + raise ValueError("Absolute immutable guest package paths required") + for current in (path, *path.parents): + checkpoint(deadline) + row = current.lstat() + if ( + row.st_uid != 0 + or row.st_mode & 0o022 + or stat.S_ISLNK(row.st_mode) + or current != path + and not stat.S_ISDIR(row.st_mode) + ): + raise ValueError("Root-owned guest paths must be immutable to the runner") + row = path.lstat() + if not (stat.S_ISDIR(row.st_mode) if directory else stat.S_ISREG(row.st_mode)): + raise ValueError("Guest package member has an unsupported file type") + checkpoint(deadline) + return row + + +def _read_immutable(path, limit, deadline): + before = _owned(path, deadline) + if before.st_size > limit: + raise ValueError("Guest package member exceeds its bound") + descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + try: + if _identity(os.fstat(descriptor)) != _identity(before): + raise ValueError("Guest package member changed before reading") + chunks, size = [], 0 + while True: + checkpoint(deadline) + part = os.read(descriptor, min(65536, limit + 1 - size)) + checkpoint(deadline) + if not part: + break + chunks.append(part) + size += len(part) + if size > limit: + raise ValueError("Guest package member exceeds its bound") + if _identity(os.fstat(descriptor)) != _identity(before) or _identity( + _owned(path, deadline) + ) != _identity(before): + raise ValueError("Guest package member changed during reading") + return b"".join(chunks) + finally: + os.close(descriptor) + + +def _guest(deadline): + checkpoint(deadline) + user = pwd.getpwuid(os.getuid()) + if ( + sys.platform != "linux" + or sys.version_info < (3, 11) + or sys.flags.isolated != 1 + or sys.flags.dont_write_bytecode != 1 + or sys.pycache_prefix is not None + or platform.machine() != "x86_64" + or any(value != _UID for value in (os.getuid(), os.geteuid(), os.getgid(), os.getegid())) + or set(os.getgroups()) - {_UID} + or user.pw_name != "gitlab-runner" + or user.pw_dir != _HOME + or os.environ.get("HOME") != _HOME + ): + raise ValueError("The original nonroot Linux amd64 CI guest is required") + selected = os.environ.get("DEVSECOPS_PLUGIN_ROOT") + if ( + not isinstance(selected, str) + or selected != str(ROOT) + or not ROOT.is_relative_to(_PREFIX) + or ROOT == _PREFIX + ): + raise ValueError("The preselected /opt guest package must contain this loaded engine") + _owned(ROOT, deadline, directory=True) + # The selected prebuilt interpreter may be a root-owned venv symlink. Its + # literal selection and every link/target ancestor must be immutable; it + # cannot select an interpreter bundled inside the plugin or a user runtime. + selected_python = os.environ.get("DEVSECOPS_PYTHON") + if ( + not isinstance(selected_python, str) + or not re.fullmatch(re.escape(str(_PREFIX)) + r"/[A-Za-z0-9_./-]+", selected_python) + or ".." in Path(selected_python).parts + or str(Path(selected_python)) != selected_python + or sys.executable != selected_python + or Path(selected_python).is_relative_to(ROOT) + ): + raise ValueError("The selected external prebuilt guest interpreter is required") + path = Path(selected_python) + for _ in range(16): + checkpoint(deadline) + _owned(path.parent, deadline, directory=True) + row = path.lstat() + if row.st_uid != 0: + raise ValueError("Guest interpreter link is not root owned") + if not stat.S_ISLNK(row.st_mode): + info = _owned(path, deadline) + if path.is_relative_to(ROOT): + raise ValueError("Guest interpreter target must remain outside the plugin") + if not info.st_mode & 0o111: + raise ValueError("Guest interpreter is not executable") + break + target = os.readlink(path) + path = Path(os.path.normpath(target if os.path.isabs(target) else str(path.parent / target))) + else: + raise ValueError("Guest interpreter link chain exceeds its bound") + + checkpoint(deadline) + + +def _members(deadline): + actual, directories, queue = set(), 0, [ROOT] + while queue: + checkpoint(deadline) + current = queue.pop() + _owned(current, deadline, directory=True) + directories += 1 + if directories > _MAX_DIRECTORIES: + raise ValueError("Guest package directory bound exceeded") + with os.scandir(current) as entries: + for item in entries: + checkpoint(deadline) + if item.is_symlink(): + raise ValueError("Guest package contains a symlink") + if item.is_dir(follow_symlinks=False): + queue.append(Path(item.path)) + if len(queue) + directories > _MAX_DIRECTORIES: + raise ValueError("Guest package directory bound exceeded") + elif item.is_file(follow_symlinks=False): + actual.add(str(Path(item.path).relative_to(ROOT))) + if len(actual) > _MAX_FILES + 1: + raise ValueError("Guest package file bound exceeded") + else: + raise ValueError("Guest package contains a nonregular member") + return actual + + +def _installed(expected, plugin_id, version, deadline, *, entrypoint): + if ( + not isinstance(expected, str) + or not re.fullmatch("[a-f0-9]{64}", expected) + or not isinstance(plugin_id, str) + or not re.fullmatch(_SEGMENT + "@" + _SEGMENT, plugin_id) + or not isinstance(version, str) + or not re.fullmatch("[A-Za-z0-9_.-]{1,100}", version) + or type(deadline) not in (int, float) + or not math.isfinite(deadline) + or entrypoint not in _ENTRYPOINTS + ): + raise ValueError("Exact current package and bounded fixed CI selection required") + _guest(deadline) + manifest = _read_immutable(ROOT / "SHA256SUMS", 256000, deadline) + if _sha(manifest) != expected: + raise ValueError("Guest installed manifest differs from the selected current package") + lines = manifest.decode("ascii").splitlines() + if not 1 <= len(lines) <= _MAX_FILES: + raise ValueError("Guest package member count exceeds its bound") + members, total, metadata = {}, 0, None + for line in lines: + checkpoint(deadline) + match = re.fullmatch(r"([a-f0-9]{64}) ([A-Za-z0-9_./-]+)", line) + if not match: + raise ValueError("Malformed guest package manifest") + digest, name = match.groups() + if ( + name in members + or name == "SHA256SUMS" + or name.endswith((".pyc", ".pyo", ".pth")) + or "__pycache__" in Path(name).parts + or Path(name).is_absolute() + or ".." in Path(name).parts + or str(Path(name)) != name + ): + raise ValueError("Guest package manifest member is not unique and relative") + raw = _read_immutable(ROOT / name, _MAX_FILE_BYTES, deadline) + total += len(raw) + if total > _MAX_TOTAL_BYTES or _sha(raw) != digest: + raise ValueError("Guest package contents differ or exceed their bound") + members[name] = digest + if name == ".codex-plugin/plugin.json": + metadata = _json(raw) + if _members(deadline) != set(members) | {"SHA256SUMS"}: + raise ValueError("Guest package has unmanifested or missing files") + if ( + not isinstance(metadata, dict) + or metadata.get("name") != plugin_id.split("@")[0] + or metadata.get("version") != version + ): + raise ValueError("Guest plugin identity differs from the selected current package") + if any(key in metadata for key in ("mcpServers", "mcp_servers", "hooks")) or any( + name == ".mcp.json" or name.startswith("hooks/") for name in members + ): + raise ValueError("Fixed CI supports the selected skills-only package") + for name, module in tuple(sys.modules.items()): + checkpoint(deadline) + if name == "__main__": + allowed = (entrypoint,) + elif name == "publish_and_prepare_mission_git": + allowed = ("scripts/publish_and_prepare_mission_git.py",) + elif name == "devsecops" or name.startswith("devsecops."): + relative = "src/" + name.replace(".", "/") + allowed = (relative + ".py", relative + "/__init__.py") + else: + continue + location = getattr(module, "__file__", None) + selected = next( + (item for item in allowed if isinstance(location, str) and Path(location) == ROOT / item), None + ) + if ( + selected is None + or selected not in members + or _sha(_read_immutable(ROOT / selected, _MAX_FILE_BYTES, deadline)) != members[selected] + ): + raise ValueError("Loaded CI code differs from the selected guest package") + if "__main__" not in sys.modules or "devsecops.factory.runner_package" not in sys.modules: + raise ValueError("Fixed CI entry point and package admission module must be loaded") + if _read_immutable(ROOT / "SHA256SUMS", 256000, deadline) != manifest: + raise ValueError("Guest package manifest changed during admission") + _guest(deadline) + checkpoint(deadline) + return expected + + +def installed_publication_package(expected, plugin_id, version, deadline): + return _installed(expected, plugin_id, version, deadline, entrypoint=_ENTRYPOINTS[0]) + + +def installed_deployment_package(expected, plugin_id, version, deadline): + return _installed(expected, plugin_id, version, deadline, entrypoint=_ENTRYPOINTS[1]) diff --git a/plugins/devsecops/src/devsecops/factory/runner_service_guest.py b/plugins/devsecops/src/devsecops/factory/runner_service_guest.py new file mode 100644 index 0000000..9f1aaea --- /dev/null +++ b/plugins/devsecops/src/devsecops/factory/runner_service_guest.py @@ -0,0 +1,1212 @@ +"""Package-pinned, nonroot runner supervisor. No disk receipt enrolls a process. + +The host owns the original nonce and VM scope. The live guest supervisor owns +all child handles and cleanup state; losing it requires original VM disposal. +This module has no import-time effects and is bundled by the fixed VM worker. +""" + +import json +import shlex + +CONTEXT_TYPE = None + +GUEST_PROGRAM = r""" +import base64 +import ctypes +import hashlib +import hmac +import json +import math +import os +import platform +from pathlib import Path +import pwd +import re +import select +import signal +import socket +import stat +import struct +import subprocess +import sys +import time +from uuid import UUID + +HOME = Path("/home/gitlab-runner") +ROOT = HOME / ".local/share/devsecops" +BOOT = Path("/proc/sys/kernel/random/boot_id") +RUNNER = Path("/usr/bin/gitlab-runner") +UID = 10001 +MAX = 2400000 + + +def encoded(value): + return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def remaining(deadline): + value = deadline - time.monotonic() + if value <= 0: + raise ValueError("Runner service deadline expired") + return value + + +def uuid(value): + if type(value) is not str or str(UUID(value)) != value: + raise ValueError("Canonical original UUID required") + return value + + +def shape(value, keys): + if type(value) is not dict or set(value) != set(keys.split()): + raise ValueError("Closed runner service selection required") + + +def paths(run_id): + private = ROOT / UUID(run_id).hex + return { + "private": str(private), + "inputs": str(private / "inputs"), + "output": str(HOME / "builds" / ("factory-" + run_id) / "publication"), + "runtime": str(HOME / "builds" / UUID(run_id).hex), + } + + +def validate(packet): + common = "schema_version action run_id operation_id runner_vm timeout service_nonce" + action = packet.get("action") if type(packet) is dict else None + shape(packet, common + (" installation" if action == "install" else " expected_process")) + if ( + type(packet["schema_version"]) is not int + or packet["schema_version"] != 1 + or action not in ("install", "observe", "down", "reconcile") + ): + raise ValueError("Unsupported runner service action") + uuid(packet["run_id"]) + uuid(packet["service_nonce"]) + operation = packet["operation_id"] + if type(operation) is not str or not re.fullmatch(r"[A-Za-z0-9_.:-]{1,160}", operation): + raise ValueError("Original operation identity required") + seconds = packet["timeout"] + if type(seconds) not in (int, float) or not math.isfinite(seconds) or not 0 < seconds <= 300: + raise ValueError("Finite bounded service deadline required") + vm = packet["runner_vm"] + shape( + vm, + "binding generation guest_boot_id guest_uid guest_gid root_identity disk_identity runtime_id network_id ssh_host_key_sha256", + ) + if ( + vm["generation"] != "runner-vm-" + packet["run_id"] + or type(vm["guest_uid"]) is not int + or vm["guest_uid"] != UID + or type(vm["guest_gid"]) is not int + or vm["guest_gid"] != UID + ): + raise ValueError("Original separate nonroot runner VM required") + uuid(vm["guest_boot_id"]) + for name in ("binding", "runtime_id", "network_id", "ssh_host_key_sha256"): + if type(vm[name]) is not str or not re.fullmatch("[a-f0-9]{64}", vm[name]): + raise ValueError("Complete VM pins required") + for name in ("root_identity", "disk_identity"): + shape(vm[name], "device inode") + if any(type(v) is not int or v < 0 for v in vm[name].values()) or vm[name]["inode"] == 0: + raise ValueError("Original VM inode identity required") + if action == "install": + validate_install(packet["installation"], packet["run_id"]) + elif packet["expected_process"] is not None and type(packet["expected_process"]) is not dict: + raise ValueError("Original resident process observation required") + return packet + + +def validate_install(value, run_id): + shape( + value, + "runner_id runner_token description origin entries environment secrets service_trust route_trust guest_package guest_paths", + ) + if ( + type(value["runner_id"]) is not int + or value["runner_id"] <= 0 + or type(value["runner_token"]) is not str + or not re.fullmatch(r"[A-Za-z0-9_.-]{20,8192}", value["runner_token"]) + or type(value["description"]) is not str + or not re.fullmatch(r"[A-Za-z0-9_.:-]{1,180}", value["description"]) + or type(value["origin"]) is not str + or not re.fullmatch(r"https://gitlab\.[a-z0-9-]{1,63}\.test:8444", value["origin"]) + or value["guest_paths"] != paths(run_id) + ): + raise ValueError("Original runner registration or private guest paths differ") + public = value["environment"] + shape( + public, + "DEVSECOPS_GIT_INVOCATION DEVSECOPS_GIT_INVOCATION_SHA256 DEVSECOPS_PYTHON DEVSECOPS_PLUGIN_ROOT", + ) + if ( + not re.fullmatch("[a-f0-9]{64}", public["DEVSECOPS_GIT_INVOCATION_SHA256"]) + or not public["DEVSECOPS_GIT_INVOCATION"].startswith(paths(run_id)["inputs"] + "/") + or any( + not isinstance(public[k], str) + or not re.fullmatch("/opt/devsecops/[A-Za-z0-9_./-]+", public[k]) + or ".." in Path(public[k]).parts + for k in ("DEVSECOPS_PYTHON", "DEVSECOPS_PLUGIN_ROOT") + ) + ): + raise ValueError("Fixed runner invocation and prebuilt tools required") + secrets = value["secrets"] + if type(secrets) is not dict or len(secrets) > 32: + raise ValueError("Bounded explicitly selected secrets required") + for key, text in secrets.items(): + if ( + not re.fullmatch("DEVSECOPS_[A-Z0-9_]{1,100}", key) + or key in public + or type(text) is not str + or not 1 <= len(text) <= 8192 + or any(ord(c) < 32 or ord(c) > 126 for c in text) + ): + raise ValueError("Private runner environment differs") + entries = value["entries"] + if type(entries) is not dict or not 1 <= len(entries) <= 80: + raise ValueError("Bounded selected input files required") + total = 0 + for name, row in entries.items(): + shape(row, "content sha256 private") + path = Path(name) + if ( + not name.startswith(paths(run_id)["inputs"] + "/") + or str(path) != name + or ".." in path.parts + or not re.fullmatch(r"[A-Za-z0-9_./-]+", name) + or type(row["private"]) is not bool + ): + raise ValueError("Runner input escaped its private selection") + raw = base64.b64decode(row["content"], validate=True) + total += len(raw) + if len(raw) > 1000000 or sha(raw) != row["sha256"] or total > 1500000: + raise ValueError("Runner input bytes differ or exceed bound") + if ( + public["DEVSECOPS_GIT_INVOCATION"] not in entries + or entries[public["DEVSECOPS_GIT_INVOCATION"]]["sha256"] != public["DEVSECOPS_GIT_INVOCATION_SHA256"] + ): + raise ValueError("Invocation is not the exact installed input") + trust = value["service_trust"] + if ( + type(trust) is not dict + or not {"gitlab", "registry"} <= set(trust) + or not set(trust) <= {"gitlab", "registry", "external"} + ): + raise ValueError("Separate exact service trust required") + for role, row in trust.items(): + shape(row, "path sha256") + if ( + row["path"] != paths(run_id)["inputs"] + "/service-trust/" + role + "-ca.pem" + or row["path"] not in entries + or entries[row["path"]]["sha256"] != row["sha256"] + ): + raise ValueError("Selected CA path or bytes differ") + route = value["route_trust"] + shape(route, "files environment empty_directory") + if type(route["files"]) is not dict or not 3 <= len(route["files"]) <= 8: + raise ValueError("Original bounded route trust facts required") + for name, row in route["files"].items(): + shape(row, "path sha256 bytes device inode uid gid mode") + if ( + name + not in { + "gitlab-ca.pem", + "registry-ca.pem", + "external-ca.pem", + "registry1-ca.pem", + "p1docs-ca.pem", + "ca-bundle.pem", + "environment.json", + } + or row["path"] != paths(run_id)["inputs"] + "/service-trust/" + name + or not re.fullmatch("[a-f0-9]{64}", row["sha256"]) + or any( + type(row[k]) is not int or row[k] < 0 + for k in ("bytes", "device", "inode", "uid", "gid", "mode") + ) + or not 0 < row["bytes"] <= 1000000 + or row["inode"] == 0 + or row["uid"] != UID + or row["gid"] != UID + or row["mode"] != 0o600 + ): + raise ValueError("Original route trust file identity differs") + bundle = paths(run_id)["inputs"] + "/service-trust/ca-bundle.pem" + expected_env = { + name: bundle for name in ("SSL_CERT_FILE", "GIT_SSL_CAINFO", "CURL_CA_BUNDLE", "REQUESTS_CA_BUNDLE") + } + expected_env["SSL_CERT_DIR"] = paths(run_id)["inputs"] + "/service-trust/empty-ca-directory" + expected_env.update( + { + name: "" + for name in ( + "HTTP_PROXY", + "HTTPS_PROXY", + "ALL_PROXY", + "NO_PROXY", + "http_proxy", + "https_proxy", + "all_proxy", + "no_proxy", + ) + } + ) + empty = route["empty_directory"] + shape(empty, "path device inode uid gid mode") + if ( + empty["path"] != expected_env["SSL_CERT_DIR"] + or any(type(empty[k]) is not int or empty[k] < 0 for k in ("device", "inode", "uid", "gid", "mode")) + or empty["inode"] == 0 + or empty["uid"] != UID + or empty["gid"] != UID + or empty["mode"] != 0o700 + ): + raise ValueError("Original empty private CA directory required") + if route["environment"] != expected_env: + raise ValueError("Fixed private CA environment required") + if "ca-bundle.pem" not in route["files"]: + raise ValueError("Original route CA bundle required") + for row in trust.values(): + original = route["files"].get(Path(row["path"]).name) + if original is None or any(original[k] != row[k] for k in ("path", "sha256")): + raise ValueError("Selected service trust differs from original routes") + package = value["guest_package"] + shape(package, "root manifest_sha256 plugin_id plugin_version") + if ( + package["root"] != public["DEVSECOPS_PLUGIN_ROOT"] + or not re.fullmatch("[a-f0-9]{64}", package["manifest_sha256"]) + or not isinstance(package["plugin_id"], str) + or not re.fullmatch( + r"[A-Za-z0-9][A-Za-z0-9._+-]{0,119}@[A-Za-z0-9][A-Za-z0-9._+-]{0,119}", package["plugin_id"] + ) + or not isinstance(package["plugin_version"], str) + or not re.fullmatch("[A-Za-z0-9_.-]{1,100}", package["plugin_version"]) + ): + raise ValueError("Actual current package identity required") + + +def identity(path): + st = path.lstat() + return { + "device": st.st_dev, + "inode": st.st_ino, + "uid": st.st_uid, + "gid": st.st_gid, + "mode": stat.S_IMODE(st.st_mode), + } + + +def safe(path): + if path.resolve() != path or path.is_symlink(): + raise ValueError("Runner path changed or contains a symlink") + return path + + +def directory(path): + safe(path) + row = identity(path) + if not path.is_dir() or row["uid"] != UID or row["gid"] != UID or row["mode"] & 0o077: + raise ValueError("Original private runner directory required") + return row + + +def read(path, limit=MAX, *, owner=UID, private=True): + safe(path) + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + with os.fdopen(fd, "rb") as stream: + st = os.fstat(stream.fileno()) + if ( + not stat.S_ISREG(st.st_mode) + or st.st_nlink != 1 + or st.st_uid != owner + or st.st_mode & (0o077 if private else 0o022) + or st.st_size > limit + ): + raise ValueError("Bounded original runner file required") + raw = stream.read(limit + 1) + after = os.fstat(stream.fileno()) + if ( + len(raw) > limit + or (st.st_dev, st.st_ino, st.st_size, st.st_mtime_ns, st.st_ctime_ns) + != (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns, after.st_ctime_ns) + or identity(path)["inode"] != st.st_ino + ): + raise ValueError("Runner file changed during observation") + return raw + + +def immutable_path(path): + path = path.resolve(strict=True) + for parent in (path, *path.parents): + row = identity(parent) + if row["uid"] != 0 or row["mode"] & 0o022: + raise ValueError("Prebuilt root-owned immutable tool or package required") + return path + + +def immutable(path, limit=128000000): + path = immutable_path(path) + return path, sha(read(path, limit, owner=0, private=False)) + + +def guard(packet, deadline): + remaining(deadline) + user = pwd.getpwuid(os.getuid()) + if ( + os.getuid() != UID + or os.geteuid() != UID + or os.getgid() != UID + or os.getegid() != UID + or set(os.getgroups()) - {UID} + or user.pw_name != "gitlab-runner" + or user.pw_dir != str(HOME) + or BOOT.read_text().strip() != packet["runner_vm"]["guest_boot_id"] + ): + raise ValueError("Original nonroot guest identity changed") + if sys.platform != "linux" or platform.machine() != "x86_64": + raise ValueError("Prebuilt Linux amd64 runner guest required") + status = Path("/proc/self/status").read_bytes() + if len(status) > 64000: + raise ValueError("Guest process status exceeds bound") + lines = status.decode("ascii").splitlines() + flags = [line.split(":", 1)[1].strip() for line in lines if line.startswith("NoNewPrivs:")] + for name in ("CapEff", "CapPrm", "CapAmb"): + caps = [line.split(":", 1)[1].strip() for line in lines if line.startswith(name + ":")] + if len(caps) != 1 or not re.fullmatch("0{16}", caps[0]): + raise ValueError("Unprivileged original supervisor required") + if flags != ["0"]: + raise ValueError("Prebuilt separate guest uidmap prerequisites unavailable") + for path in (Path(paths(packet["run_id"])["private"]), Path(paths(packet["run_id"])["inputs"])): + directory(path) + + +def proc(pid): + root = Path("/proc") / str(pid) + raw = (root / "stat").read_bytes() + fields = raw[raw.rfind(b")") + 2 :].split() + if len(fields) < 20: + raise ValueError("Incomplete original process observation") + status = (root / "status").read_text() + uid = re.findall(r"^Uid:\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)$", status, re.M) + gid = re.findall(r"^Gid:\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)$", status, re.M) + if len(uid) != 1 or len(gid) != 1: + raise ValueError("Incomplete process account observation") + exe = Path(os.readlink(root / "exe")) + # Read the kernel's executable reference itself: a job may have a different + # mount namespace. Never resolve its pathname against this host namespace. + fd = os.open(root / "exe", os.O_RDONLY) + with os.fdopen(fd, "rb") as stream: + info = os.fstat(stream.fileno()) + if not stat.S_ISREG(info.st_mode) or info.st_size > 128000000: + raise ValueError("Bounded original executable observation required") + digest = hashlib.sha256() + count = 0 + while True: + block = stream.read(65536) + if not block: + break + count += len(block) + if count > 128000000: + raise ValueError("Executable observation exceeds bound") + digest.update(block) + after = os.fstat(stream.fileno()) + if (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns) != ( + after.st_dev, + after.st_ino, + after.st_size, + after.st_mtime_ns, + after.st_ctime_ns, + ): + raise ValueError("Original executable changed during observation") + argv = (root / "cmdline").read_bytes() + if len(argv) > 262144: + raise ValueError("Process arguments exceed fixed observation bound") + return { + "pid": pid, + "start_ticks": int(fields[19]), + "boot_id": BOOT.read_text().strip(), + "uid": [int(x) for x in uid[0]], + "gid": [int(x) for x in gid[0]], + "executable": str(exe), + "executable_sha256": digest.hexdigest(), + "argv_sha256": sha(argv), + } + + +def exited(fd): + poll = select.poll() + poll.register(fd, select.POLLIN) + return bool(poll.poll(0)) + + +def open_process(pid): + fd = os.pidfd_open(pid, 0) + try: + value = proc(pid) + if exited(fd): + raise ValueError("Process ceased during identity observation") + return fd, value + except BaseException: + os.close(fd) + raise + + +def send(fd, value): + signal.pidfd_send_signal(fd, value, None, 0) + + +def receive(sock, deadline): + data = bytearray() + while True: + sock.settimeout(remaining(deadline)) + block = sock.recv(min(65536, MAX + 1 - len(data))) + if not block: + raise ValueError("Incomplete runner control response") + data.extend(block) + if len(data) > MAX: + raise ValueError("Runner control message exceeds bound") + if b"\n" in data: + line, tail = data.split(b"\n", 1) + if tail: + raise ValueError("Extra runner control data rejected") + return json.loads(line) + + +class Supervisor: + def __init__(self, packet, deadline): + self.packet = packet + self.deadline = deadline + self.nonce = packet["service_nonce"] + self.root = Path(paths(packet["run_id"])["private"]) + self.socket_path = self.root / "runner.sock" + self.files, self.dirs, self.handles = {}, {}, {} + self.file_digests = {} + self.pending_paths = set() + self.removed = [] + self.down_operation = None + self.runner = None + self.runner_identity = None + self.manager = None + self.ready = False + self.closed = False + self.unresolved = [] + self.failure = None + self.installation = packet["installation"] + self.trust_rows = self.installation["route_trust"]["files"] + self.empty_trust = self.installation["route_trust"]["empty_directory"] + self.registration = self.installation["runner_id"] + self.process_identity = None + + def write(self, path, raw): + remaining(self.deadline) + parent = path.parent + pending = [] + while not parent.exists(): + pending.append(parent) + parent = parent.parent + directory(parent) + for item in reversed(pending): + self.pending_paths.add(str(item)) + os.mkdir(item, 0o700) + self.dirs[str(item)] = identity(item) + self.pending_paths.remove(str(item)) + safe(path.parent) + self.pending_paths.add(str(path)) + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + # Retain ownership before the first write. A partial write remains ours; + # cleanup compares its original inode, never a guessed content receipt. + st = os.fstat(fd) + self.files[str(path)] = { + "device": st.st_dev, + "inode": st.st_ino, + "uid": st.st_uid, + "gid": st.st_gid, + "mode": stat.S_IMODE(st.st_mode), + } + self.pending_paths.remove(str(path)) + with os.fdopen(fd, "wb") as stream: + stream.write(raw) + stream.flush() + os.fsync(stream.fileno()) + if identity(path) != self.files[str(path)]: + raise ValueError("New runner file identity changed") + self.file_digests[str(path)] = sha(raw) + + def preflight(self): + package = self.installation["guest_package"] + root = Path(package["root"]) + manifest = root / "SHA256SUMS" + immutable_path(manifest) + raw_manifest = read(manifest, 256000, owner=0, private=False) + if sha(raw_manifest) != package["manifest_sha256"]: + raise ValueError("Guest installed package manifest differs") + lines = raw_manifest.decode("ascii").splitlines() + if not 1 <= len(lines) <= 1024: + raise ValueError("Guest package member count differs") + seen, total = set(), 0 + for line in lines: + remaining(self.deadline) + match = re.fullmatch(r"([a-f0-9]{64}) ([A-Za-z0-9_./-]+)", line) + if ( + not match + or match[2] in seen + or match[2] == "SHA256SUMS" + or Path(match[2]).is_absolute() + or ".." in Path(match[2]).parts + or str(Path(match[2])) != match[2] + ): + raise ValueError("Closed immutable package members required") + seen.add(match[2]) + member = immutable_path(root / match[2]) + raw = read(member, 16000000, owner=0, private=False) + total += len(raw) + if total > 128000000 or sha(raw) != match[1]: + raise ValueError("Guest package member differs or exceeds aggregate bound") + actual, directories, queue = set(), 0, [root] + while queue: + remaining(self.deadline) + directory_path = queue.pop() + immutable_path(directory_path) + directories += 1 + if directories > 1024: + raise ValueError("Guest package directory bound exceeded") + with os.scandir(directory_path) as entries: + for entry in entries: + remaining(self.deadline) + if entry.is_symlink(): + raise ValueError("Guest package contains a symlink") + if entry.is_dir(follow_symlinks=False): + queue.append(Path(entry.path)) + if len(queue) + directories > 1024: + raise ValueError("Guest package directory bound exceeded") + elif entry.is_file(follow_symlinks=False): + actual.add(str(Path(entry.path).relative_to(root))) + if len(actual) > 1025: + raise ValueError("Guest package file bound exceeded") + else: + raise ValueError("Guest package contains a nonregular member") + if actual != seen | {"SHA256SUMS"}: + raise ValueError("Guest package has unmanifested or missing files") + if ".codex-plugin/plugin.json" not in seen: + raise ValueError("Original package manifest omits plugin identity") + plugin = json.loads(read(root / ".codex-plugin/plugin.json", 64000, owner=0, private=False)) + if ( + plugin.get("name") != package["plugin_id"].split("@")[0] + or plugin.get("version") != package["plugin_version"] + ): + raise ValueError("Guest plugin identity differs") + immutable(Path(self.installation["environment"]["DEVSECOPS_PYTHON"])) + binary, digest = immutable(RUNNER) + version = subprocess.run( + [str(binary), "--version"], + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + timeout=min(10, remaining(self.deadline)), + check=True, + env={"PATH": "/usr/bin:/bin", "HOME": str(HOME)}, + ) + if len(version.stdout) > 64000 or not re.search(rb"(?m)^Version:\s+19\.5\.1\s*$", version.stdout): + raise ValueError("Prebuilt GitLab Runner 19.5.1 required") + self.binary, self.binary_sha = str(binary), digest + + def install(self): + guard(self.packet, self.deadline) + self.preflight() + trust_paths = {row["path"] for row in self.installation["service_trust"].values()} + for name, row in self.installation["entries"].items(): + raw = base64.b64decode(row["content"], validate=True) + path = Path(name) + if name in trust_paths: + if sha(read(path)) != row["sha256"]: + raise ValueError("Original route-owned CA bytes changed") + else: + self.write(path, raw) + route = self.installation["route_trust"] + for row in route["files"].values(): + path = Path(row["path"]) + raw = read(path, 1000000) + if ( + identity(path) != {k: row[k] for k in ("device", "inode", "uid", "gid", "mode")} + or len(raw) != row["bytes"] + or sha(raw) != row["sha256"] + ): + raise ValueError("Original route-owned trust file changed") + self.audit_empty_trust() + env = { + "HOME": str(HOME), + "USER": "gitlab-runner", + "LOGNAME": "gitlab-runner", + "PATH": "/opt/devsecops/bin:/usr/local/bin:/usr/bin:/bin", + **self.installation["environment"], + **self.installation["secrets"], + **route["environment"], + } + config = self.root / "runner-service/config.toml" + + def quote(value): + return json.dumps(value, ensure_ascii=True) + + body = ( + "concurrent = 1\ncheck_interval = 3\n[[runners]]\nname = " + + quote(self.installation["description"]) + + "\nurl = " + + quote(self.installation["origin"]) + + "\nid = " + + str(self.registration) + + "\ntoken = " + + quote(self.installation["runner_token"]) + + '\nexecutor = "shell"\nshell = "bash"\n' + + "builds_dir = " + + quote(str(HOME / "builds")) + + "\nrequest_concurrency = 1\ntls-ca-file = " + + quote(self.installation["service_trust"]["gitlab"]["path"]) + + "\nenvironment = [" + + ",".join( + quote(k + "=" + v) + for k, v in sorted(env.items()) + if k.startswith("DEVSECOPS_") or k in route["environment"] + ) + + "]\n" + ) + self.write(config, body.encode()) + guard(self.packet, self.deadline) + self.runner = subprocess.Popen( + [self.binary, "run", "--config", str(config), "--working-directory", str(HOME)], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=env, + close_fds=True, + ) + fd, observed = open_process(self.runner.pid) + self.runner_identity = observed + if ( + observed["executable"] != self.binary + or observed["executable_sha256"] != self.binary_sha + or observed["uid"] != [UID] * 4 + or observed["gid"] != [UID] * 4 + ): + os.close(fd) + raise ValueError("Actual runner process identity differs") + self.handles[self.runner.pid] = (fd, observed) + manager = config.parent / ".runner_system_id" + while True: + remaining(self.deadline) + if exited(fd): + raise ValueError("Runner exited before manager identity observation") + if manager.exists(): + raw = read(manager, 100, private=False).strip() + if not re.fullmatch(rb"[sr]_[A-Za-z0-9]{12}", raw): + raise ValueError("Actual runner manager identity differs") + self.files[str(manager)] = identity(manager) + self.file_digests[str(manager)] = sha(read(manager, 100, private=False)) + self.manager = raw.decode() + break + time.sleep(min(0.05, remaining(self.deadline))) + self.ready = True + # Secrets remain only in the private config and the running process. + self.installation = None + + def processes(self): + return { + "supervisor": self.process_identity, + "runner": self.runner_identity, + "control_socket": self.socket_identity, + "service_nonce_sha256": sha(self.nonce.encode()), + } + + def audit_live(self): + if proc(os.getpid()) != self.process_identity: + raise ValueError("Original supervisor identity changed") + if self.runner is None or proc(self.runner.pid) != self.runner_identity: + raise ValueError("Original runner identity changed") + if identity(self.socket_path) != self.socket_identity: + raise ValueError("Original live control socket changed") + for name, original in self.files.items(): + path = Path(name) + if identity(safe(path)) != original or sha( + read(path, private=not bool(original["mode"] & 0o077)) + ) != self.file_digests.get(name): + raise ValueError("Original installed private input changed") + self.audit_route_trust() + + def report(self, action): + alive = self.ready and self.runner is not None and not exited(self.handles[self.runner.pid][0]) + if alive: + try: + self.audit_live() + except BaseException: + alive = False + self.ready = False + self.failure = "original-live-identity-changed" + unresolved = list(self.unresolved) + if self.failure and not self.closed: + unresolved.append(self.packet["operation_id"]) + return { + "runner_vm": self.packet["runner_vm"], + "resources": [ + { + "kind": "runner-service", + "state": "absent" if self.closed else ("owned-present" if alive else "residual"), + "runner_id": self.registration, + "disposition": "remove", + }, + { + "kind": "runner-private-inputs", + "state": "absent" if self.closed else "owned-present", + "disposition": "remove", + }, + {"kind": "route-owned-trust", "state": "preserved", "disposition": "preserve"}, + ], + "unresolved_operations": sorted(set(unresolved)), + "mutation_effect": "applied" if not unresolved else "unknown", + "complete_cleanup": self.closed, + "service_ready": alive and not unresolved, + "runner_id": self.registration, + "runner_manager_system_identity": self.manager, + "process": self.processes(), + "descendants_reaped": self.closed, + "supervisor_terminated": False, + "action": action, + } + + def child_edges(self, parent, deadline): + remaining(deadline) + root = Path("/proc") / str(parent) / "task" + threads = list(root.iterdir()) + if len(threads) > 256: + raise ValueError("Original process thread bound exceeded") + children = set() + for thread in threads: + remaining(deadline) + raw = (thread / "children").read_bytes() + if len(raw) > 8192: + raise ValueError("Runner child observation exceeds bound") + children.update(int(item) for item in raw.split()) + return children + + def freeze(self, pid, deadline): + fd, observed = self.handles[pid] + if exited(fd): + return + if proc(pid) != observed: + raise ValueError("Original descendant process changed") + remaining(deadline) + send(fd, signal.SIGSTOP) + # SIGSTOP is asynchronous. Wait until every original thread is stopped + # before examining its child edges; a mere signal send is insufficient. + while not exited(fd): + remaining(deadline) + states = [] + for task in (Path("/proc") / str(pid) / "task").iterdir(): + raw = (task / "stat").read_bytes() + states.append(raw[raw.rfind(b")") + 2 :].split()[0]) + if states and all(value in (b"T", b"t", b"Z") for value in states): + return + time.sleep(min(0.005, remaining(deadline))) + + def enroll(self, pid, parent): + if pid in self.handles: + return + fd = os.pidfd_open(pid, 0) + try: + raw = (Path("/proc") / str(pid) / "stat").read_bytes() + fields = raw[raw.rfind(b")") + 2 :].split() + # Reparenting into our original subreaper is admissible; unrelated + # PID reuse is not. The pidfd pins this exact kernel process. + if int(fields[1]) not in (parent, os.getpid()): + raise ValueError("Observed child left the original ancestry") + if fields[0] == b"Z" and int(fields[1]) == os.getpid(): + reaped, _ = os.waitpid(pid, os.WNOHANG) + if reaped != pid: + raise ValueError("Original zombie child reaping unobserved") + return + observed = proc(pid) + if observed.get("uid") != [UID] * 4 or observed.get("gid") != [UID] * 4: + raise ValueError("Privileged or mapped-account descendant requires original VM disposal") + if exited(fd): + raise ValueError("Original child exited during enrollment") + self.handles[pid] = (fd, observed) + fd = None + finally: + if fd is not None: + os.close(fd) + + def collect(self, deadline): + # Only live kernel child edges of this original subreaper enroll a + # process. Freeze each parent before discovery, including all threads. + visited = set() + for _ in range(257): + todo = [(pid, os.getpid()) for pid in self.child_edges(os.getpid(), deadline)] + discovered = False + while todo: + remaining(deadline) + pid, parent = todo.pop() + if pid in visited: + continue + if len(visited) >= 256: + raise ValueError("Runner descendant bound exceeded") + try: + self.enroll(pid, parent) + except (ProcessLookupError, FileNotFoundError): + # No signal is issued from a vanished edge. A survivor will + # appear in a subsequent original subreaper child read. + continue + visited.add(pid) + if pid not in self.handles: + continue # Affirmatively reaped zombie. + self.freeze(pid, deadline) + discovered = True + if not exited(self.handles[pid][0]): + todo.extend((child, pid) for child in self.child_edges(pid, deadline)) + fresh = self.child_edges(os.getpid(), deadline) + if fresh <= visited: + return + if not discovered and not fresh: + return + raise ValueError("Original runner descendant closure remains uncertain") + + def audit_empty_trust(self): + row = self.empty_trust + path = Path(row["path"]) + if directory(path) != {k: row[k] for k in ("device", "inode", "uid", "gid", "mode")} or any( + path.iterdir() + ): + raise ValueError("Original empty private CA directory changed") + + def audit_route_trust(self): + for row in self.trust_rows.values(): + path = Path(row["path"]) + raw = read(path) + if ( + identity(safe(path)) != {k: row[k] for k in ("device", "inode", "uid", "gid", "mode")} + or len(raw) != row["bytes"] + or sha(raw) != row["sha256"] + ): + raise ValueError("Preserved original route trust changed") + self.audit_empty_trust() + + def stop(self, deadline): + remaining(deadline) + if self.pending_paths: + raise ValueError("Unacknowledged file effect requires original VM disposal") + self.ready = False + self.audit_route_trust() + self.collect(deadline) + for fd, observed in self.handles.values(): + remaining(deadline) + if not exited(fd): + if proc(observed["pid"]) != observed: + raise ValueError("Original descendant process changed before termination") + remaining(deadline) + send(fd, signal.SIGKILL) + while self.handles: + remaining(deadline) + try: + pid, _ = os.waitpid(-1, os.WNOHANG) + except ChildProcessError: + if self.handles: + raise ValueError("Original descendant reaping remains unproven") + break + if pid: + if pid not in self.handles: + raise ValueError("Unexpected child cannot grant cleanup") + os.close(self.handles.pop(pid)[0]) + else: + time.sleep(min(0.01, remaining(deadline))) + # Affirmative ECHILD is required after every enrolled process was reaped. + try: + pid, _ = os.waitpid(-1, os.WNOHANG) + except ChildProcessError: + pass + else: + raise ValueError("Unobserved runner descendant remains") + for name, original in reversed(list(self.files.items())): + remaining(deadline) + path = Path(name) + if identity(safe(path)) != original: + raise ValueError("Original private runner file changed identity") + path.unlink() + self.removed.append((name, original)) + del self.files[name] + for name, original in reversed(list(self.dirs.items())): + remaining(deadline) + path = Path(name) + if directory(path) != original: + raise ValueError("Original private runner directory changed identity") + path.rmdir() + self.removed.append((name, original)) + del self.dirs[name] + self.audit_route_trust() + remaining(deadline) + self.failure = None + self.unresolved.clear() + self.closed = True + + def serve(self): + libc = ctypes.CDLL(None, use_errno=True) + if libc.prctl(36, 1, 0, 0, 0) != 0: # PR_SET_CHILD_SUBREAPER; no privilege change. + raise ValueError("Original child reaper unavailable") + immutable(Path(sys.executable)) + self.process_identity = proc(os.getpid()) + if self.process_identity["uid"] != [UID] * 4 or self.process_identity["gid"] != [UID] * 4: + raise ValueError("Nonroot supervisor required") + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + sock.bind(str(self.socket_path)) + os.chmod(self.socket_path, 0o600) + self.socket_identity = identity(self.socket_path) + sock.listen(1) + try: + self.install() + except BaseException: + self.failure = "installation-incomplete" + while not self.closed: + conn, _ = sock.accept() + with conn: + accepted_at = time.monotonic() + deadline = accepted_at + 5 + try: + peer = struct.unpack("3i", conn.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12)) + if peer[1:] != (UID, UID): + raise ValueError("Original guest control user required") + wire = receive(conn, deadline) + shape(wire, "challenge request authentication") + if ( + type(wire["challenge"]) is not str + or not re.fullmatch("[a-f0-9]{64}", wire["challenge"]) + or type(wire["request"]) is not dict + or "service_nonce" in wire["request"] + or type(wire["authentication"]) is not str + ): + raise ValueError("Closed authenticated runner control frame required") + signed = bytes.fromhex(wire["challenge"]) + encoded(wire["request"]) + if not hmac.compare_digest( + wire["authentication"], + hmac.new(self.nonce.encode(), signed, hashlib.sha256).hexdigest(), + ): + raise ValueError("Original resident control authentication differs") + request = validate({**wire["request"], "service_nonce": self.nonce}) + if ( + request["action"] == "install" + or request["runner_vm"] != self.packet["runner_vm"] + or request["run_id"] != self.packet["run_id"] + or not hmac.compare_digest(request["service_nonce"], self.nonce) + or request["expected_process"] is not None + and request["expected_process"] != self.processes() + ): + raise ValueError("Original live runner controller required") + deadline = accepted_at + request["timeout"] + guard(request, deadline) + if request["action"] == "reconcile" and request["operation_id"] not in ( + self.packet["operation_id"], + self.down_operation, + ): + raise ValueError("Reconciliation must identify the original uncertain operation") + if request["action"] == "down": + if self.down_operation is not None: + raise ValueError("Original cleanup already attempted; no implicit retry") + self.down_operation = request["operation_id"] + try: + self.stop(deadline) + except BaseException: + self.unresolved.append(request["operation_id"]) + response = self.report(request["action"]) + conn.settimeout(remaining(deadline)) + conn.sendall( + encoded( + { + "result": response, + "authentication": hmac.new( + self.nonce.encode(), + bytes.fromhex(wire["challenge"]) + encoded(response), + hashlib.sha256, + ).hexdigest(), + } + ) + + b"\n" + ) + except BaseException: + # No exception text, configuration, token, nonce or environment + # is copied into a public report or inherited SSH output. + try: + conn.sendall(b'{"error":"runner-control-rejected"}\n') + except OSError: + pass + sock.close() + if identity(self.socket_path) != self.socket_identity: + raise ValueError("Original supervisor socket changed") + self.socket_path.unlink() + + +def peer(sock, packet, expected=None): + pid, uid, gid = struct.unpack("3i", sock.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12)) + if uid != UID or gid != UID: + raise ValueError("Original nonroot supervisor peer required") + fd, observed = open_process(pid) + if ( + observed["boot_id"] != packet["runner_vm"]["guest_boot_id"] + or observed["uid"] != [UID] * 4 + or observed["gid"] != [UID] * 4 + or expected is not None + and observed != expected + ): + os.close(fd) + raise ValueError("Original resident supervisor process changed") + return fd, observed + + +def transact(packet, deadline, *, spawned=None, spawned_pid=None): + path = Path(paths(packet["run_id"])["private"]) / "runner.sock" + expected = packet["expected_process"] + while True: + remaining(deadline) + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + sock.settimeout(min(1, remaining(deadline))) + sock.connect(str(path)) + break + except (FileNotFoundError, ConnectionRefusedError): + sock.close() + if spawned is None: + raise ValueError("Original resident supervisor is unavailable; VM disposal proof required") + if exited(spawned): + raise ValueError("Original supervisor exited before observation") + time.sleep(min(0.02, remaining(deadline))) + with sock: + original_socket = identity(path) + if expected is not None and original_socket != expected["control_socket"]: + raise ValueError("Original control socket inode changed") + fd, observed = peer(sock, packet, None if expected is None else expected["supervisor"]) + try: + if spawned_pid is not None and observed["pid"] != spawned_pid: + raise ValueError("Initial control peer is not the original forked supervisor") + request = {key: value for key, value in packet.items() if key != "service_nonce"} + request["timeout"] = min(packet["timeout"], remaining(deadline)) + challenge = os.urandom(32) + authentication = hmac.new( + packet["service_nonce"].encode(), challenge + encoded(request), hashlib.sha256 + ).hexdigest() + sock.sendall( + encoded({"challenge": challenge.hex(), "request": request, "authentication": authentication}) + + b"\n" + ) + reply = receive(sock, deadline) + shape(reply, "result authentication") + result = reply["result"] + if type(reply["authentication"]) is not str or not hmac.compare_digest( + reply["authentication"], + hmac.new( + packet["service_nonce"].encode(), challenge + encoded(result), hashlib.sha256 + ).hexdigest(), + ): + raise ValueError("Original supervisor response authentication differs") + if ( + result.get("runner_vm") != packet["runner_vm"] + or result.get("process", {}).get("supervisor") != observed + or result["process"].get("control_socket") != original_socket + or result["process"].get("service_nonce_sha256") != sha(packet["service_nonce"].encode()) + ): + raise ValueError("Original live runner response differs") + if result.get("complete_cleanup") is True: + poll = select.poll() + poll.register(fd, select.POLLIN) + if not poll.poll(max(1, int(remaining(deadline) * 1000))): + raise ValueError("Original supervisor termination remains unobserved") + if path.exists(): + raise ValueError("Original runner control socket cleanup incomplete") + result["supervisor_terminated"] = True + remaining(deadline) + return result + finally: + os.close(fd) + + +def dispatch(packet): + validate(packet) + deadline = time.monotonic() + packet["timeout"] + guard(packet, deadline) + if packet["action"] != "install": + return transact(packet, deadline) + # Existing socket/installation is never adopted or implicitly retried. + path = Path(paths(packet["run_id"])["private"]) / "runner.sock" + if path.exists() or path.is_symlink(): + raise ValueError("Runner install was already attempted") + pid = os.fork() + if pid == 0: + try: + os.setsid() + os.umask(0o077) + null = os.open("/dev/null", os.O_RDWR) + for number in (0, 1, 2): + os.dup2(null, number) + for number in list(Path("/proc/self/fd").iterdir()): + if int(number.name) > 2: + try: + os.close(int(number.name)) + except OSError: + pass + Supervisor(packet, deadline).serve() + os._exit(0) + except BaseException: + os._exit(73) + fd = os.pidfd_open(pid, 0) + try: + request = {key: value for key, value in packet.items() if key != "installation"} + request.update(action="observe", expected_process=None) + return transact(request, deadline, spawned=fd, spawned_pid=pid) + finally: + os.close(fd) + + +def main(): + try: + raw = sys.stdin.buffer.read(MAX + 1) + if len(raw) > MAX: + raise ValueError("Runner packet exceeds bound") + value = dispatch(json.loads(raw)) + sys.stdout.buffer.write(encoded(value) + b"\n") + sys.stdout.buffer.flush() + except BaseException: + sys.stderr.write( + "Fixed runner guest operation incomplete; original outcome requires reconciliation.\n" + ) + raise SystemExit(73) + + +if __name__ == "__main__": + main() +""" + + +def execute(packet, *, scope): + """Called only by the fixed VM worker with its original current scope.""" + if CONTEXT_TYPE is None or type(scope) is not CONTEXT_TYPE: + raise ValueError("Original RunnerVMRemoteContext required") + if ( + type(packet) is not dict + or packet.get("runner_vm") != scope.identity() + or packet.get("run_id") != scope.packet["run_id"] + ): + raise ValueError("Runner service packet differs from its original VM") + namespace = {"__name__": "runner_service_validation"} + exec(compile(GUEST_PROGRAM, "
{escape(gap['code'])} — {escape(gap['message'])}Aggregate decision: unknown
+Each condition uses its scoped provider result. Verified HTTPS binds reads to the configured service endpoints; it does not establish authenticated build, image, delivery or recovery provenance. Controlled inputs are identified in the JSON.
+| '+escape(label)+' | ' for label in headings)}
|---|
Read the evidence JSON · Artifact integrity
{_h(item)}{_h(finding.get("remediation", "Review the cited evidence with the platform owner."))}
' + '{_h(finding.get("field"))}
' + f'{_h(finding.get("evidence"))}Matched findings remain visible but are excluded from the configured rule gate. ' + 'Exceptions do not excuse validation failures or missing required evidence.
' + + "".join(cards) + "These gaps limit the conclusion. An unavailable check is not a pass.
' + + _details("Review gaps", global_gaps, opened=True) + + "Read-only context. Pipeline status does not prove deployment safety.
' + f'{_h(ci)}A review of the declared candidate, profile, and local validation. ' + 'Use the findings and coverage below to decide the next engineering step.
{_h(code)}No change was established by the available observations.
' + if remaining: + sections += f'Ordered by the number of supporting observations. This order does not measure causal confidence. ' + 'The structured report retains counterevidence and required independent controls.
') + sections += table(headers, supported) if supported else 'No alternative has direct supporting observations.
' + if unsupported: + sections += f'A historical failure remains evidence of that recorded window, even when it is too old to describe current health.
' + '| Input | Target | Observation | Freshness | ' + f'
|---|
Input validity checks structure and hashes; it does not authenticate the source. ' + sections += 'Application HTTP health was not observed. Causality remains unproven.
| Condition | Phase | Target | ' + 'Observation | Source origin |
|---|
Each observation is checked against the ' + 'approved contract. An observed match does not authenticate its source. ' + 'A matching fault condition means the expected defect was observed.
') + if exceptions: + sections += f'No recovery condition could be evaluated.
' + sections += '' + sections += ('The configured provenance adapter authenticated the consumed input bytes.' + if result.get('provenance', {}).get('verified') else + 'The origin of the supplied evidence has not been independently authenticated. ' + 'Content hashes alone cannot establish native execution, Git delivery or live recovery.') + sections += '
Causality remains unproven. The structured evidence preserves exact input hashes, ' + sections += 'condition pointers and retained failure observations.
These observations describe ' + 'the earlier fault window. Later recovery checks do not erase them.
' + f'{_h(next_step)}
Pod readiness is separate from application HTTP health.
' + '| Target | Argo status | Workload readiness | Telemetry | ' + f'
|---|
Hashes detect changed content. An independent trusted journal must authenticate the inputs.