diff --git a/.github/tests/test_fleet_native_route.py b/.github/tests/test_fleet_native_route.py index 52fff61..e3adb4e 100644 --- a/.github/tests/test_fleet_native_route.py +++ b/.github/tests/test_fleet_native_route.py @@ -3,15 +3,24 @@ """Bounded security contract for the explicit native QA route; no guest execution.""" import ast +import base64 import importlib.util +import hashlib import json import os +import runpy +import selectors import subprocess +import shutil +import sys import tempfile import tomllib import traceback +import types import unittest -from contextlib import contextmanager, nullcontext +import sqlite3 +import zipfile +from contextlib import ExitStack, contextmanager, nullcontext from pathlib import Path from types import SimpleNamespace from unittest.mock import patch @@ -30,13 +39,1043 @@ ) +@contextmanager +def private_owner_temp(module): + """Use a private fixture with ancestry accepted by the real custody policy.""" + parent = None + if module.platform.system() == "Linux": + parent = Path.home() + if parent.lstat().st_uid != os.geteuid(): + raise ValueError("observation fixture home must belong to the current user") + module.observation_directories(parent, private=False) + with tempfile.TemporaryDirectory(dir=parent) as directory: + module.observation_directories(Path(directory)) + yield directory + + +@contextmanager +def owner_file_read_audit(module, limits, *, grow=None): + """Observe real descriptor reads; short reads/growth defeat stat-only bounds.""" + opened, attempts = {}, [] + original_open, original_read, original_stat, original_loads = os.open, os.read, os.fstat, json.loads + grown = set() + def opening(name, *args, **kwargs): + descriptor = original_open(name, *args, **kwargs) + opened.pop(descriptor, None) # Descriptor numbers can be reused for another record. + if isinstance(name, (str, bytes, os.PathLike)) and Path(name) in limits: + item = {"path": Path(name), "limit": limits[Path(name)], "total": 0, "requests": []} + attempts.append(item); opened[descriptor] = item + return descriptor + def stating(descriptor): + info = original_stat(descriptor) + item = opened.get(descriptor) + if item and item["path"] == grow and grow not in grown: + with open(grow, "ab") as stream: + stream.write(b" ") + grown.add(grow) + return info + def reading(descriptor, count): + item = opened.get(descriptor) + if item: + assert type(count) is int and 0 < count <= item["limit"] + 1 - item["total"] + item["requests"].append(count) + raw = original_read(descriptor, min(count, 8191) if item else count) + if item: + item["total"] += len(raw) + assert item["total"] <= item["limit"] + 1 + return raw + def parsing(raw, *args, **kwargs): + assert len(raw) <= max(limits.values()), "overflow must be rejected before JSON parsing" + return original_loads(raw, *args, **kwargs) + with patch.object(module.os, "open", side_effect=opening), patch.object(module.os, "read", side_effect=reading), patch.object(module.os, "fstat", side_effect=stating), patch.object(module.json, "loads", side_effect=parsing): + yield attempts + + +@contextmanager +def owner_inspect_boundary(module, payload, mode="ok"): + """Only low-level child/clock/selector/read substitutes; no process is launched.""" + clock = [100.0] + audit = {"requests": [], "total": 0, "waits": [], "events": []} + stdout = SimpleNamespace(fileno=lambda: 77, close=unittest.mock.Mock()) + exited = [False] + def waiting(timeout): + assert type(timeout) in (int, float) and 0 < timeout <= (105 if audit["killed"] or exited[0] else 104) - clock[0] + audit["waits"].append((clock[0], timeout)) + if mode == "cleanup-timeout" or (mode == "eof-live" and not audit["killed"]): + clock[0] += timeout + raise subprocess.TimeoutExpired("PRIVATE", timeout) + exited[0] = True + return 17 if mode == "nonzero" else 0 + audit["killed"] = False + def killing(): + audit["killed"] = True + child = SimpleNamespace(stdout=stdout, poll=lambda: (0 if exited[0] else None), wait=unittest.mock.Mock(side_effect=waiting), kill=unittest.mock.Mock(side_effect=killing)) + def spawning(argv, **kwargs): + self_expected = {"shell": False, "stdin": subprocess.DEVNULL, "stdout": subprocess.PIPE, + "stderr": subprocess.DEVNULL, "bufsize": 0, "close_fds": True} + assert argv == ["docker", "inspect", "cryptolabs-proxy"] and kwargs == self_expected + clock[0] += 0.25 # Spawn time belongs to the same absolute deadline. + if mode == "spawn-error": + raise OSError("PRIVATE_SPAWN") + return child + def selecting(timeout): + assert 0 < timeout <= 104 - clock[0] + audit["events"].append(("select", clock[0], timeout)) + if mode == "timeout": + clock[0] += timeout + return [] + clock[0] += 0.00001 + return [(SimpleNamespace(fd=77, fileobj=stdout), selectors.EVENT_READ)] + selector = SimpleNamespace(register=unittest.mock.Mock(), unregister=unittest.mock.Mock(), close=unittest.mock.Mock(), select=unittest.mock.Mock(side_effect=selecting)) + def reading(descriptor, count): + assert descriptor == 77 + assert count == min(65536, 1048577 - audit["total"]) and count > 0 + audit["requests"].append(count) + if mode == "read-error": + raise OSError("PRIVATE_READ") + if mode == "short" and len(audit["requests"]) == 1: + raise BlockingIOError() + raw = payload[audit["total"]:audit["total"] + min(count, 8191)] + audit["total"] += len(raw) + assert audit["total"] <= 1048577 + return raw + setup = OSError("PRIVATE_SELECTOR") if mode == "setup-error" else None + forbidden = AssertionError("unbounded/general command runner forbidden") + with patch.object(module.subprocess, "Popen", side_effect=spawning) as spawn, patch.object(selectors, "DefaultSelector", side_effect=setup, return_value=selector), patch.object(module, "selectors", selectors, create=True), patch.object(module.os, "read", side_effect=reading), patch.object(module.os, "set_blocking", side_effect=lambda fd, enabled: (_ for _ in ()).throw(AssertionError("must be own nonblocking descriptor")) if (fd, enabled) != (77, False) else None), patch.object(module.time, "monotonic", side_effect=lambda: clock[0]), patch.object(module, "run", side_effect=forbidden), patch.object(module, "docker", side_effect=forbidden), patch.object(module, "inspect", side_effect=forbidden): + yield audit + assert spawn.call_count == 1 + if mode != "spawn-error": + assert stdout.close.called + assert child.wait.called + if mode != "setup-error": + assert selector.close.called + assert clock[0] <= 105 + audit["child"] = child + + class FleetNativeRouteTest(unittest.TestCase): + # TRACEWEAVER: verifies=VER-AUTOADVANCE-008; req=REQ-AUTOADVANCE-008; trace=TRACE-AUTOADVANCE-008 + def test_selector_observer_coordinates_match_reviewed_broker(self): + broker = ast.parse((ROOT / 'src/dc_overview/release_broker.py').read_text()) + operation = next(n for n in ast.walk(broker) + if isinstance(n, ast.FunctionDef) and n.name == 'run_operation') + calls = [n.lineno for n in ast.walk(operation) + if isinstance(n, ast.Call) and isinstance(n.func, ast.Name) + and n.func.id == 'select_release_components'] + self.assertEqual(len(calls), 1) + verifier = ast.parse(SCRIPT.read_text()) + observer = next(n for n in ast.walk(verifier) + if isinstance(n, ast.FunctionDef) and n.name == 'observe_broker_owner_failures') + coordinates = [n.comparators[0].value for n in ast.walk(observer) + if isinstance(n, ast.Compare) and isinstance(n.left, ast.Attribute) + and n.left.attr == 'tb_lineno' and len(n.comparators) == 1 + and isinstance(n.comparators[0], ast.Constant)] + self.assertEqual(coordinates, calls) + + # TRACEWEAVER: verifies=VER-AUTOADVANCE-008; req=REQ-AUTOADVANCE-008; trace=TRACE-AUTOADVANCE-008 + def test_approved_policy_source_pair_passes_real_guard_and_tampering_fails(self): + module = self.native_module() + proxy = ROOT.parent / "proxy" + self.assertTrue(proxy.is_dir(), "Run with the reviewed Proxy checkout beside DC as proxy") + proxy_sha = subprocess.check_output(["git", "-C", str(proxy), "rev-parse", "HEAD"]).decode().strip() + self.assertEqual(proxy_sha, "6e5186401e78cc8ba7b6ffe18eb24712ef9263b1") + workflow = yaml.safe_load(WORKFLOW.read_text()) + self.assertEqual(workflow["env"]["PROXY_SOURCE_SHA"], proxy_sha) + required = { + "src/dc_overview/release_policy.py", + "src/dc_overview/templates/systemd/dc-overview-release-refresh.service", + "src/dc_overview/templates/systemd/dc-overview-release-refresh.timer", + } + self.assertTrue(required <= module.FROZEN_PRODUCT_HASHES["dc"].keys()) + tree = ast.parse(SCRIPT.read_text()) + preflight = next(n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name == "preflight") + guard = next(n for n in ast.walk(preflight) if isinstance(n, ast.For) + and isinstance(n.target, ast.Tuple) + and [getattr(v, "id", None) for v in n.target.elts] == ["source", "expected", "product"]) + code = compile(ast.Module(body=[guard], type_ignores=[]), str(SCRIPT), "exec") + with tempfile.TemporaryDirectory() as temporary: + roots = {product: Path(temporary) / product for product in ("dc", "proxy")} + for product, source in (("dc", ROOT), ("proxy", proxy)): + for name in module.FROZEN_PRODUCT_HASHES[product]: + destination = roots[product] / name + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source / name, destination) + args = SimpleNamespace(dc_source=roots["dc"], dc_sha="a" * 40, + proxy_source=roots["proxy"], proxy_sha=proxy_sha) + def git_identity(*arguments): + self.assertEqual(arguments[0], "git") + return SimpleNamespace(stdout=(args.dc_sha if arguments[2] == roots["dc"] else proxy_sha).encode()) + context = dict(self=SimpleNamespace(args=args), run=git_identity, + FROZEN_PRODUCT_HASHES=module.FROZEN_PRODUCT_HASHES, + digest=lambda value: hashlib.sha256(value).hexdigest()) + exec(code, context) + for product, name in (("dc", "src/dc_overview/release_policy.py"), + ("proxy", "src/cryptolabs_proxy/release_client.py")): + path = roots[product] / name + original = path.read_bytes() + path.write_bytes(original + b"\n# altered source\n") + with self.assertRaisesRegex(RuntimeError, "frozen product source hash mismatch"): + exec(code, context) + path.write_bytes(original) + exec(code, context) + + def assert_bootstrap_failure_shape(self, metadata): + failure = metadata.get("bootstrap_failure") + self.assertIsInstance(failure, dict, "inner bootstrap diagnostics must survive the existing collector") + self.assertEqual(set(failure), {"bootstrap_step", "code_label", "source_line", "guard_line", + "error_kind", "command_outcome", "command_returncode", "scoped_select_diagnostic", + "scoped_select_inner_diagnostic"}) + self.assertIs(type(failure["scoped_select_diagnostic"]), str) + inner = failure['scoped_select_inner_diagnostic'] + self.assertIs(type(inner), dict) + self.assertEqual(set(inner), {'guards', 'condition', 'require_capability', 'continuity_equal'}) + self.assertTrue(inner['continuity_equal'] == 'unknown' or + (type(inner['continuity_equal']) is dict and + set(inner['continuity_equal']) == set(self.native_module().CONTINUITY_FIELDS) and + all(type(v) is bool for v in inner['continuity_equal'].values()))) + self.assertIs(type(inner['guards']), list) + for name in ('condition', 'require_capability'): + self.assertTrue(type(inner[name]) is bool or (type(inner[name]) is str and inner[name] == 'unknown')) + self.assertIn(failure["bootstrap_step"], { + "legacy-runtime-inspect", "legacy-updater-probe", "legacy-capabilities-probe", + "synthetic-runtime-inspect", "synthetic-db-seed", "synthetic-read-aggregate", + "synthetic-root-custody", "synthetic-protection-helper", "legacy-job-seed", + "compatible-wheel-install", "legacy-owner-rejection", "legacy-reconcile", + "legacy-reconcile-replay", "scoped-select", "proxy-plan", "proxy-adopt", "proxy-health", "unknown", + }) + self.assertIn(failure["code_label"], {"legacy-bootstrap", "synthetic-seed", "synthetic-helper", "native-command", "unknown"}) + self.assertIn(failure["error_kind"], {"assertion-error", "file-not-found", "permission-error", "os-error", "runtime-error", "unknown"}) + self.assertIn(failure["command_outcome"], {"nonzero-exit", "timeout", "spawn-error", "none", "unknown"}) + for field in ("source_line", "guard_line"): + if failure[field] is not None: + self.assertIs(type(failure[field]), int) + self.assertGreater(failure[field], 0) + if failure["command_returncode"] is not None: + self.assertIs(type(failure["command_returncode"]), int) + self.assertTrue(-255 <= failure["command_returncode"] <= 255) + return failure + def native_module(self): spec = importlib.util.spec_from_file_location("fleet_native_diagnostics", SCRIPT) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module + def test_proxy_adoption_finish_retains_original_failure_without_replay(self): + """Execute the real adoption prefix and finish/status failure path.""" + module = self.native_module() + tree = ast.parse(SCRIPT.read_text()) + klass = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'NativeQA') + method = next(n for n in klass.body if isinstance(n, ast.FunctionDef) and n.name == 'proxy_adopt') + stop = next(i for i, n in enumerate(method.body) if isinstance(n, ast.Assign) + and any(isinstance(t, ast.Name) and t.id == 'final' for t in n.targets)) + prefix = compile(ast.Module(body=method.body[1:stop + 1], type_ignores=[]), str(SCRIPT), 'exec') + identity = '00000000-0000-4000-8000-000000000011' + params, preview, body = {'operation_kind': 'proxy-adopt'}, {'disconnect_expected': True}, {'operation_id': identity} + for layout, reply, expected_branch in ( + ('named-volume', {'ok': True, 'result': {'state': 'recovery-required'}}, 'terminal-state'), + ('named-volume', {'ok': False, 'error': {'status': 503, 'message': 'PRIVATE'}}, 'status-rejected'), + ('bind', {'ok': True, 'result': {'state': 'recovery-required'}}, None)): + with self.subTest(layout=layout, branch=expected_branch), tempfile.TemporaryDirectory() as directory: + root = Path(directory) + qa = module.NativeQA(SimpleNamespace(evidence_dir=root / 'evidence')) + qa.layout, qa.auth = layout, root + (root / 'users.json').write_bytes(b'PRIVATE') + qa.preview = unittest.mock.Mock(return_value=(params, preview)) + qa.apply = unittest.mock.Mock(return_value=(identity, body)) + qa.proxy_adoption_observation = unittest.mock.Mock(return_value={'qualification': 'unknown'}) + qa.record = unittest.mock.Mock() + with patch.object(module, 'raw_request', return_value=reply) as request: + try: + exec(prefix, {'self': qa, 'inspect': lambda name: {'Id': 'a' * 64}, 'digest': module.digest}) + except RuntimeError as error: + original = error + else: + self.fail('original failing owner operation was accepted') + self.assertEqual(str(original), 'owner operation held: recovery-required' if reply['ok'] else 'installed status unavailable') + self.assertEqual(request.call_args_list, [unittest.mock.call('status', {'operation_id': identity})]) + qa.apply.assert_called_once_with(params, preview) + if expected_branch is None: + qa.record.assert_not_called() + qa.proxy_adoption_observation.assert_not_called() + continue + self.assertEqual(qa.record.call_count, 1, 'the named-volume failure currently loses its original branch') + self.assertEqual(qa.record.call_args.args, ('proxy-adoption-observation',)) + packet = qa.record.call_args.kwargs + self.assertEqual(packet['finish_branch'], expected_branch) + self.assertEqual(packet['status_ok'], reply['ok']) + self.assertEqual(packet['owner_state'], 'recovery-required' if reply['ok'] else 'unknown') + self.assertEqual(packet['error_kind'], 'runtime-error') + self.assertEqual(qa.proxy_adoption_observation.call_count, 1) + self.assertNotIn('PRIVATE', json.dumps(packet)) + + def test_proxy_adoption_collector_failure_keeps_exception_identity_and_trace(self): + module = self.native_module() + for failed_boundary in ('projection', 'record'): + with self.subTest(failed_boundary=failed_boundary), tempfile.TemporaryDirectory() as directory: + qa = module.NativeQA(SimpleNamespace(evidence_dir=Path(directory))) + qa.layout = 'named-volume' + original = RuntimeError('PRIVATE_ORIGINAL') + qa.status = unittest.mock.Mock(side_effect=original) + captured = [] + def project(*args): + self.assertIs(sys.exception(), original) + captured.append(original.__traceback__) + if failed_boundary == 'projection': + raise RuntimeError('PRIVATE_COLLECTOR') + return {'qualification': 'unknown'} + qa.proxy_adoption_observation = unittest.mock.Mock(side_effect=project) + qa.record = unittest.mock.Mock(side_effect=RuntimeError('PRIVATE_RECORD') if failed_boundary == 'record' else None) + # The opt-in is part of the bounded verifier, never product API. + try: + qa.finish('00000000-0000-4000-8000-000000000011', adoption_expected={}) + except TypeError: + self.fail('finish must support the source-scoped adoption diagnostic without changing its failure') + except RuntimeError as caught: + self.assertIs(caught, original) + self.assertIs(caught.__traceback__.tb_next, captured[0], + 'explicit raise(error) would add a duplicate finish traceback frame') + else: + self.fail('original exception must escape') + self.assertEqual(qa.status.call_count, 1) + self.assertEqual(qa.proxy_adoption_observation.call_count, 1) + + def test_proxy_adoption_original_wait_deadline_is_observed_without_retry(self): + module = self.native_module() + with tempfile.TemporaryDirectory() as directory: + qa = module.NativeQA(SimpleNamespace(evidence_dir=Path(directory))) + qa.layout = 'named-volume' + qa.status = unittest.mock.Mock(return_value={'state': 'adopting'}) + qa.proxy_adoption_observation = unittest.mock.Mock(return_value={'qualification': 'unknown'}) + qa.record = unittest.mock.Mock() + original = RuntimeError('actual owner operation did not finish') + def timed_out(predicate, **kwargs): + self.assertEqual(kwargs, {'timeout': 420, 'message': 'actual owner operation did not finish'}) + self.assertIsNone(predicate()) + raise original + with patch.object(module, 'wait', side_effect=timed_out) as waiting: + try: + qa.finish('00000000-0000-4000-8000-000000000011', adoption_expected={}) + except TypeError: + self.fail('missing bounded adoption diagnostic') + except RuntimeError as caught: + self.assertIs(caught, original) + else: + self.fail('original deadline failure must escape') + waiting.assert_called_once() + qa.status.assert_called_once() + qa.proxy_adoption_observation.assert_called_once() + self.assertEqual(qa.record.call_args.kwargs['finish_branch'], 'waiting') + self.assertEqual(qa.record.call_args.kwargs['owner_state'], 'adopting') + + def test_proxy_adoption_transport_keeps_original_wait_retry_and_deadline(self): + module = self.native_module() + with tempfile.TemporaryDirectory() as directory: + qa = module.NativeQA(SimpleNamespace(evidence_dir=Path(directory))) + qa.layout = 'named-volume' + qa.proxy_adoption_observation = unittest.mock.Mock(return_value={'qualification': 'unknown'}) + qa.record = unittest.mock.Mock() + # Original wait deliberately absorbs OSError and eventually emits + # its own deadline error. Advance only its clock; keep that code. + with patch.object(module, 'raw_request', side_effect=OSError('PRIVATE_TRANSPORT')) as request, \ + patch.object(module.time, 'monotonic', side_effect=[0.0, 0.0, 421.0]), \ + patch.object(module.time, 'sleep'): + try: + qa.finish('00000000-0000-4000-8000-000000000011', adoption_expected={}) + except TypeError: + self.fail('missing bounded adoption diagnostic') + except RuntimeError as caught: + self.assertEqual(str(caught), 'actual owner operation did not finish') + else: + self.fail('original wait must exhaust its 420-second deadline') + request.assert_called_once_with('status', {'operation_id': '00000000-0000-4000-8000-000000000011'}) + qa.proxy_adoption_observation.assert_called_once() + packet = qa.record.call_args.kwargs + self.assertEqual(packet['finish_branch'], 'status-call') + self.assertEqual(packet['status_error_kind'], 'os-error') + self.assertEqual(packet['error_kind'], 'runtime-error') + self.assertIsNone(packet['status_ok']) + self.assertNotIn('PRIVATE', json.dumps(packet)) + + def test_proxy_adoption_malformed_status_keeps_original_exception(self): + module = self.native_module() + with tempfile.TemporaryDirectory() as directory: + qa = module.NativeQA(SimpleNamespace(evidence_dir=Path(directory))) + qa.layout = 'named-volume' + qa.proxy_adoption_observation = unittest.mock.Mock(return_value={'qualification': 'unknown'}) + qa.record = unittest.mock.Mock() + for value in ([], None, 7, 'PRIVATE'): + with self.subTest(value_type=type(value).__name__): + # The original final predicate indexes the response. Retain + # its precise exception and args even when it is malformed. + try: + value['state'] + except TypeError as original: + expected_args = original.args + qa.status = unittest.mock.Mock(return_value=value) + qa.proxy_adoption_observation.reset_mock(); qa.record.reset_mock() + with self.assertRaises(TypeError) as caught: + qa.finish('00000000-0000-4000-8000-000000000011', adoption_expected={}) + self.assertEqual(caught.exception.args, expected_args) + qa.status.assert_called_once() + qa.proxy_adoption_observation.assert_called_once() + qa.record.assert_called_once() + self.assertEqual(qa.record.call_args.kwargs['owner_state'], 'unknown') + self.assertNotIn('PRIVATE', json.dumps(qa.record.call_args.kwargs)) + + def test_proxy_adoption_diagnostic_uses_closed_original_source_roles(self): + module = self.native_module() + self.assertTrue(hasattr(module, 'ADOPTION_CODE_SPECS'), 'adoption guards need a separate bounded original-code lane') + specs = module.ADOPTION_CODE_SPECS + self.assertLessEqual(len(specs) + len(module.BROKER_CODE_LABELS), 32) + self.assertEqual(len(module.SELECTOR_CODE_SPECS), 13, 'do not borrow or replace selector roles') + self.assertTrue(any(path == 'dc_overview.release_broker' and ancestry == ('InstalledOwner', 'adopt') + for _, path, ancestry in specs)) + self.assertTrue(any(path == 'cryptolabs_proxy.standard_adoption' and ancestry == ('StandardAdoption', 'adopt') + for _, path, ancestry in specs)) + module.sysconfig.get_config_vars() + with private_owner_temp(module) as directory: + prefix = Path(directory).resolve() / 'legacy-host-venv' + site = prefix / ('lib/python' + str(sys.version_info.major) + '.' + str(sys.version_info.minor)) / 'site-packages' + installed = {} + for _, name, ancestry in specs: + if name not in installed: + role = 'dc' if name.startswith('dc_overview.') else 'proxy' + original = (ROOT if role == 'dc' else ROOT.parent / 'proxy') / 'src' / (name.replace('.', '/') + '.py') + raw = original.read_bytes() + self.assertEqual(module.digest(raw), module.FROZEN_PRODUCT_HASHES[role]['src/' + name.replace('.', '/') + '.py']) + path = site / (name.replace('.', '/') + '.py') + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(raw) + loaded = types.ModuleType(name) + loaded.__file__ = str(path) + installed[name] = (loaded, compile(raw, str(path), 'exec'), path) + loaded, expected, _ = installed[name] + owner = loaded + for item in ancestry[:-1]: + expected = next(code for code in expected.co_consts if type(code) is types.CodeType and code.co_name == item) + if not hasattr(owner, item): + setattr(owner, item, type(item, (), {})) + owner = getattr(owner, item) + code = next(code for code in expected.co_consts if type(code) is types.CodeType and code.co_name == ancestry[-1]) + setattr(owner, ancestry[-1], types.FunctionType(code, {})) + modules = {name: item[0] for name, item in installed.items()} + with patch.dict(sys.modules, modules), patch.object(module.sys, 'prefix', str(prefix)): + codes = module.naturally_loaded_adoption_codes(module.time.monotonic() + 1) + self.assertEqual({label for label, _ in codes}, {label for label, _, _ in specs}) + original = installed['dc_overview.release_broker'][0].InstalledOwner.adopt + self.assertTrue(any(code is original.__code__ for _, code in codes)) + def foreign(*args): + raise RuntimeError('PRIVATE') + installed['dc_overview.release_broker'][0].InstalledOwner.adopt = foreign + refused = module.naturally_loaded_adoption_codes(module.time.monotonic() + 1) + self.assertFalse(any(label == next(label for label, name, ancestry in specs + if name == 'dc_overview.release_broker' and ancestry == ('InstalledOwner', 'adopt')) + for label, _ in refused)) + installed['dc_overview.release_broker'][0].InstalledOwner.adopt = original + path = installed['dc_overview.release_broker'][2] + path.write_bytes(path.read_bytes() + b'\n') + refused = module.naturally_loaded_adoption_codes(module.time.monotonic() + 1) + self.assertFalse(any(label in {label for label, name, _ in specs if name == 'dc_overview.release_broker'} + for label, _ in refused)) + + def test_fixture_broker_execstart_uses_layout_selected_interpreter(self): + """Execute the actual drop-in statements; no Engine or systemd calls.""" + tree = ast.parse(SCRIPT.read_text()) + klass = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'NativeQA') + fixture = next(n for n in klass.body if isinstance(n, ast.FunctionDef) and n.name == 'fixture') + start = next(i for i, n in enumerate(fixture.body) if isinstance(n, ast.Assign) + and any(isinstance(t, ast.Name) and t.id == 'dropin' for t in n.targets)) + statements = fixture.body[start:start + 2] + for layout in ('named-volume', 'bind'): + with self.subTest(layout=layout), tempfile.TemporaryDirectory() as directory: + root = Path(directory) + qa = SimpleNamespace(recovery=SimpleNamespace(host_env=root / 'legacy-host-venv')) + writes = [] + namespace = {'Path': Path, 'SERVICE': 'synthetic-broker.service', 'sys': sys, + 'self': qa, 'layout': layout, 'write': lambda *args: writes.append(args)} + exec(compile(ast.Module(body=statements, type_ignores=[]), str(SCRIPT), 'exec'), namespace) + self.assertEqual(len(writes), 1) + expected = str(qa.recovery.host_env / 'bin/python') if layout == 'named-volume' else sys.executable + self.assertEqual(writes[0][1], ( + '[Service]\nExecStart=\nExecStart=' + expected + + ' /opt/fleet-native-qa/verify_fleet_release_native.py --broker-child\n').encode()) + self.assertEqual(writes[0][2], 0o644) + + def test_selected_host_proof_uses_real_installed_layout_and_provenance_guard(self): + """Real isolated Python prefix/full code/metadata, with no system services.""" + import shutil + tree = ast.parse(SCRIPT.read_text()) + klass = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'LegacyRecoveryFixture') + method = next(n for n in klass.body if isinstance(n, ast.FunctionDef) and n.name == 'install_compatible_host') + proof = next((n for n in method.body if isinstance(n, ast.Assign) + and any(isinstance(t, ast.Name) and t.id == 'installed_layout_proof' for t in n.targets)), None) + self.assertIsNotNone(proof, 'native fixture must qualify the actual selected interpreter and wheel provenance') + source = ast.literal_eval(proof.value) + with private_owner_temp(self.native_module()) as directory: + root = Path(directory).resolve() + prefix = root / 'legacy-host-venv' + subprocess.run([sys.executable, '-m', 'venv', '--without-pip', '--system-site-packages', str(prefix)], + check=True, capture_output=True, timeout=30) + python = prefix / 'bin/python' + site = Path(subprocess.run([str(python), '-I', '-c', 'import sysconfig; print(sysconfig.get_path("purelib"))'], + check=True, capture_output=True, text=True, timeout=10).stdout.strip()) + # Keep dependencies available without shadowing this prefix's product. + dependency_sites = [p for p in sys.path if p.endswith('site-packages') and Path(p).is_dir()] + (site / 'test-dependencies.pth').write_text('\n'.join(dependency_sites) + '\n') + package = site / 'dc_overview' + package.mkdir() + # Minimal installed package shell avoids importing CLI dependencies + # absent from the route-unit job. The complete selector module and + # every source/hash/provenance predicate remain the original code. + # The native proof still imports the actual complete wheel package. + (package / '__init__.py').write_text('__version__ = "1.6.4"\n') + shutil.copyfile(ROOT / 'src/dc_overview/fleet_upgrade.py', package / 'fleet_upgrade.py') + distribution = site / 'dc_overview-1.6.4.dist-info' + distribution.mkdir() + (distribution / 'METADATA').write_text('Metadata-Version: 2.4\nName: dc-overview\nVersion: 1.6.4\n') + target = {'release': '1.6.4', 'url': 'https://github.com/cryptolabsza/dc-overview/releases/download/native-fixture/selected.whl', + 'sha256': 'a' * 64} + provenance = distribution / 'direct_url.json' + provenance.write_text(json.dumps({'url': target['url'], 'archive_info': {'hashes': {'sha256': target['sha256']}}})) + argv = [str(python), '-I', '-c', source, str(prefix), str(root), str(SCRIPT), json.dumps(target)] + passed = subprocess.run(argv, capture_output=True, text=True, timeout=20) + self.assertEqual(passed.returncode, 0, passed.stderr) + self.assertEqual(json.loads(passed.stdout), {'interpreter': 'compatible-host-venv', 'selector_source': True, + 'cli_provenance': True}) + provenance.write_text(json.dumps({'url': 'file:///synthetic/original-local.whl', + 'archive_info': {'hashes': {'sha256': target['sha256']}}})) + refused = subprocess.run(argv, capture_output=True, text=True, timeout=20) + self.assertNotEqual(refused.returncode, 0, 'same version/hash cannot bypass the real HTTPS URL predicate') + self.assertIn('requires_cli_upgrade:', refused.stderr) + self.assertEqual(refused.stdout, '') + + def test_selector_failure_stage_is_a_closed_non_authorizing_witness(self): + module = self.native_module() + value = module.selector_failure_details(RuntimeError('PRIVATE'), (), {}, module.time.monotonic() + 1) + self.assertEqual(value.get('source_stage'), 'failure-sample') + self.assertTrue(module.selector_details_valid(value)) + for stage in ('unknown', 'broker-source', 'selector-discovery', 'proxy-discovery', 'selector-required', 'failure-sample'): + self.assertTrue(module.selector_details_valid({**value, 'source_stage': stage})) + for stage in ('PRIVATE/path', '', 1, True, None): + self.assertFalse(module.selector_details_valid({**value, 'source_stage': stage})) + self.assertEqual(value['qualification'], 'innermost-unknown') + self.assertEqual(value['frames'], []) + self.assertNotIn('PRIVATE', json.dumps(value)) + + def test_actual_broker_observer_emits_attempted_source_stage_without_guard_bypass(self): + module = self.native_module() + with private_owner_temp(module) as directory: + root = Path(directory).resolve() + prefix = root / 'legacy-host-venv' + source = prefix / 'dc_overview/release_broker.py' + source.parent.mkdir(parents=True) + frozen = (ROOT / 'src/dc_overview/release_broker.py').read_bytes() + identity = '00000000-0000-4000-8000-000000000001' + actor = {'kind': 'host-peer', 'uid': 0} + request = {'candidate_ids': ['synthetic-candidate'], 'components': ['ipmi-monitor'], + 'expected_selection_id': 'synthetic-selected', 'expected_selection_sha256': 'a' * 64, + 'operation_kind': 'services-update'} + canonical = lambda v: json.dumps(v, sort_keys=True, separators=(',', ':'), allow_nan=False).encode() + manifest = canonical({'components': {}}) + preview = {'preview_id': '00000000-0000-4000-8000-000000000002', 'actor': actor, 'request': request, + 'manifest': base64.b64encode(manifest).decode(), 'selection_sha256': 'b' * 64, + 'selection_id': 'synthetic-next', 'manifest_sha256': module.digest(manifest), 'generation': 1, + 'owner_plan': None, 'owner_declaration': None, 'public_sha256': 'c' * 64, + 'owner_identity': {'updater_directory': str(root / 'named-volume/jobs'), 'device': 1, 'inode': 2, + 'proxy_config_dir': str(root / 'proxy'), 'declaration_path': str(root / 'declaration')}, + 'policy_sha256': 'd' * 64, 'channel': 'main'} + apply = {'operation_id': identity, 'preview_id': preview['preview_id'], + 'preview_sha256': module.digest(canonical(preview)), + 'expected_selection_id': request['expected_selection_id'], + 'expected_selection_sha256': request['expected_selection_sha256']} + record = {**preview, **apply, 'request_fingerprint': module.digest(canonical({'params': apply, 'actor': actor})), + 'state': 'selecting', 'phase': 'selection', 'components': ['ipmi-monitor'], + 'operation_kind': 'services-update'} + self.assertEqual(module.selector_operation(record, identity), {'components': {}}) + for changed, expected in ((True, 'broker-source'), (False, 'selector-required')): + with self.subTest(changed=changed): + source.write_bytes(frozen + (b'\n' if changed else b'')) + saved = [] + broker = types.ModuleType('synthetic_broker_boundary') + broker.__file__ = str(source) + broker.private_write = lambda *args, **kwargs: 'original-write-result' + namespace = {} + # A synthetic exception at the fixed observer coordinate; + # neither a real broker guard nor historical cause proof. + code = '\n' * 915 + ('def fail(broker, path, record):\n' + ' try:\n' + ' raise RuntimeError("PRIVATE")\n' + ' except RuntimeError:\n' + ' return broker.private_write(path, record)\n') + exec(compile(code, '', 'exec'), namespace) + boundary = namespace['fail'] + with patch.object(module.sys, 'prefix', str(prefix)), patch.object(module, 'ROOT', root), \ + patch.dict(sys.modules, {'dc_overview.fleet_upgrade': None, 'cryptolabs_proxy.updates': None}), \ + patch.object(module, 'write_owner_observation', side_effect=lambda *args: saved.append(args)): + original = broker.private_write + with module.observe_broker_owner_failures(broker, root / 'operations', (('broker-operation', boundary.__code__),)): + self.assertEqual(boundary(broker, root / 'operations' / (identity + '.json'), record), 'original-write-result') + self.assertIs(broker.private_write, original) + self.assertEqual(len(saved), 1) + detail = saved[0][1]['selector'] + self.assertEqual(detail.get('source_stage'), expected) + self.assertEqual(detail['qualification'], 'source-refused') + self.assertEqual(detail['frames'], []) + self.assertTrue(all(detail[k] is None for k in ('module_version_match', 'distribution_version_match', 'url_match', 'hash_match'))) + self.assertTrue(module.observation_failure_valid(saved[0][1])) + self.assertNotIn('PRIVATE', json.dumps(saved)) + + def test_synthetic_seed_generated_volume_reaches_helper_filesystem_guard(self): + module = self.native_module() + helper_path = ROOT / "scripts/fixtures/legacy-selected-state-protection.py" + class SeedCaptured(Exception): + pass + class FilesystemGuardReached(Exception): + pass + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + data = root / "data"; data.mkdir() + config = root / "servers.yaml"; config.write_text("servers: []\n") + with sqlite3.connect(data / "ipmi_events.db") as db: + for sql in ( + "CREATE TABLE system_settings(key TEXT PRIMARY KEY,value TEXT)", + "CREATE TABLE cloud_sync(id INTEGER PRIMARY KEY,license_key TEXT,sync_enabled INTEGER,subscription_valid INTEGER,site_id TEXT,site_name TEXT)", + "CREATE TABLE server(id INTEGER PRIMARY KEY,bmc_ip TEXT,server_name TEXT,status TEXT,updated_at TEXT)", + "CREATE TABLE server_status(bmc_ip TEXT PRIMARY KEY,server_name TEXT,last_check TEXT)", + ): + db.execute(sql) + db.execute("INSERT INTO cloud_sync(id,site_id,site_name) VALUES (1,?,?)", + ('synthetic-fleet-native-site', 'SYNTHETIC Fleet native fixture')) + volume = "native-fleet-named-volume-123-data" + observed = {"Id": "a" * 64, "Image": "sha256:" + "b" * 64, + "State": {"Running": True}, "Config": {"Labels": {"io.cryptolabs.native-qa.run": "123"}}, + "Mounts": [{"Destination": "/app/data", "Type": "volume", "Name": volume, "Source": str(data)}, + {"Destination": "/app/config/servers.yaml", "Type": "bind", "Source": str(config)}]} + qa = module.NativeQA(SimpleNamespace(evidence_dir=root / "evidence", protection_helper=helper_path)) + qa.recovery.backup_root = root / "owned-backup-root" + qa.volumes = [volume] + qa.network = "native-fleet-named-volume-123" + qa.label = "io.cryptolabs.native-qa.run=123" + # A missing/wrong initialization must fail before even account seed writes. + with sqlite3.connect(data / "ipmi_events.db") as db: + db.execute("UPDATE cloud_sync SET site_name='wrong'") + with patch.object(module, "inspect", return_value=observed): + with self.assertRaises(AssertionError): + qa.recovery.seed_synthetic_selected_state() + with sqlite3.connect(data / "ipmi_events.db") as db: + self.assertEqual(db.execute('SELECT count(*) FROM system_settings').fetchone()[0], 0) + self.assertEqual(db.execute('SELECT license_key,site_name FROM cloud_sync').fetchall(), [(None, 'wrong')]) + db.execute('UPDATE cloud_sync SET site_name=?', ('SYNTHETIC Fleet native fixture',)) + captured = {} + original_spec = importlib.util.spec_from_file_location + def capture_spec(name, path): + spec = original_spec(name, path) + execute = spec.loader.exec_module + def load(helper): + execute(helper) + # Native root-chain custody is not a macOS test capability; + # constrain this pre-creation boundary to our temporary FS. + helper.safe_chain = lambda path: path.stat() + captured["helper"] = helper + def stop(site): + captured["pin"] = helper.PINS[site] + raise SeedCaptured() + captured["main"] = helper.main + helper.main = stop + spec.loader.exec_module = load + return spec + with patch.object(module, "inspect", return_value=observed), patch.object(module, "docker", side_effect=AssertionError("Engine mutation forbidden")), patch.object(importlib.util, "spec_from_file_location", side_effect=capture_spec): + with self.assertRaises(SeedCaptured): + qa.recovery.seed_synthetic_selected_state() + helper = captured["helper"] + with sqlite3.connect(data / "ipmi_events.db") as db: + self.assertEqual(db.execute('SELECT site_id,site_name FROM cloud_sync').fetchall(), + [('synthetic-fleet-native-site', 'SYNTHETIC Fleet native fixture')]) + self.assertEqual(captured["pin"]["mounts"], observed["Mounts"]) + self.assertEqual(captured["pin"]["container_id"], observed["Id"]) + # The producer and runtime identity checks remain real. Stop the + # actual helper exactly at its first filesystem guard after mounts. + with patch.object(helper.os, "geteuid", return_value=0), patch.object(helper.os, "umask"), patch.object(helper.signal, "signal"), patch.object(helper.signal, "alarm"), patch.object(helper.subprocess, "check_output", return_value=json.dumps([observed]).encode()), patch.object(helper, "safe_chain", side_effect=FilesystemGuardReached): + foreign = json.loads(json.dumps(observed)) + foreign["Mounts"][0]["Name"] = "foreign-unowned-volume" + with patch.object(helper.subprocess, "check_output", return_value=json.dumps([foreign]).encode()): + with self.assertRaisesRegex(RuntimeError, "runtime-full-mount-records"): + captured["main"]("ltx") + with self.assertRaises(FilesystemGuardReached): + captured["main"]("ltx") + with patch.dict(captured["pin"], {"data_volume_name": None}): + with self.assertRaisesRegex(RuntimeError, "data-mount"): + captured["main"]("ltx") + # Run the actual seed/read-only helper up to its custody guard. + # Temporary ancestry is not root-private; no privileged paths or + # helper main entrypoint are reached and no helper code is replaced. + qa.recovery.backup_root = root / "diagnostic-parent" / "backup" + def fixture_boundary(): + qa.recovery.seed_synthetic_selected_state() + with patch.object(module, "inspect", return_value=observed), patch.object(module, "docker", side_effect=AssertionError("Engine mutation forbidden")): + try: + fixture_boundary() + except RuntimeError as error: + metadata = module.native_phase_failure_metadata(error, "fixture", (("fixture", fixture_boundary.__code__),)) + else: + self.fail("the real helper custody predicate must reject temporary ancestry") + failure = self.assert_bootstrap_failure_shape(metadata) + self.assertEqual(failure["bootstrap_step"], "synthetic-root-custody") + self.assertEqual(failure["code_label"], "synthetic-helper") + self.assertEqual(failure["error_kind"], "runtime-error") + helper_tree = ast.parse(helper_path.read_text()) + custody = next(n for n in helper_tree.body if isinstance(n, ast.FunctionDef) and n.name == "safe_chain") + self.assertIn(failure["guard_line"], range(custody.lineno, custody.end_lineno + 1)) + self.assertEqual(failure["command_outcome"], "none") + self.assertIsNone(failure["command_returncode"]) + + def test_synthetic_site_initialization_orders_real_fixture_and_holds_failures(self): + """Real fixture/orchestration; only Engine and unavailable root FS custody substituted.""" + module = self.native_module() + tree = ast.parse(SCRIPT.read_text()) + klass = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'NativeQA') + fixture = next(n for n in klass.body if isinstance(n, ast.FunctionDef) and n.name == 'fixture') + def assignment(node, name): + return isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == name for t in node.targets) + start = next(i for i, n in enumerate(fixture.body) if assignment(n, 'empty')) + stop = next(i for i, n in enumerate(fixture.body) if assignment(n, 'socket_mount')) + code = compile(ast.fix_missing_locations(ast.Module(body=fixture.body[start:stop], type_ignores=[])), str(SCRIPT), 'exec') + scenarios = ('pass', 'bind', 'foreign-volume', 'nonempty', 'preexisting-empty', 'existing-runtime', 'stopped-writer', + 'wrong-image', 'wrong-site-name', 'create-timeout', 'start-failed', 'wait-timeout', + 'nonzero', 'still-running', 'wrong-terminal-id', 'deadline', 'changed-volume', + 'config-swap', 'symlink-volume', 'cleanup-foreign', 'volume-create-timeout', + 'cleanup-volume-label', 'cleanup-volume-inode', 'truncated-before-create', + 'malformed-before-create', 'truncated-after-create', 'malformed-after-create', + 'same-prefix-writer') + for scenario in scenarios: + with self.subTest(scenario=scenario), tempfile.TemporaryDirectory() as directory: + root = Path(directory).resolve() + data = root / 'data'; data.mkdir() + preexisting = scenario in ('foreign-volume', 'nonempty', 'preexisting-empty') + if scenario in ('foreign-volume', 'nonempty'): + (data / 'prior.db').write_bytes(b'SYNTHETIC retained data') + initial_volume_inode = data.stat().st_ino + volume = 'native-fleet-named-volume-123-data' + if scenario == 'symlink-volume': + (root / 'alias').symlink_to(data, target_is_directory=True) + qa = module.NativeQA(SimpleNamespace(evidence_dir=root / 'evidence')) + qa.data = root + qa.label = 'io.cryptolabs.native-qa.run=123' + qa.refs = {'ipmi-old': 'ghcr.io/cryptolabsza/ipmi-monitor@sha256:' + 'c' * 64} + image_id, identity = 'sha256:' + 'b' * 64, 'a' * 64 + foreign_identity = identity[:12] + 'd' * 52 + clock, calls, timeouts = [100.0], [], [] + state = dict(created=False, started=False, exited=False, removed=False, runtime=False, + volume_exists=preexisting) + volume_labels = {'io.cryptolabs.native-qa.run': 'foreign' if scenario == 'foreign-volume' else '123'} + value = {} + def reply(output=b''): + return SimpleNamespace(returncode=0, stdout=output, stderr=b'') + def record_json(item): + return reply(json.dumps([item]).encode()) + def engine(*args, **kwargs): + calls.append(args) + if 'timeout' in kwargs: + timeouts.append(kwargs['timeout']) + self.assertGreater(kwargs['timeout'], 0) + self.assertLessEqual(kwargs['timeout'], 60) + clock[0] += 1 + if args[:2] == ('volume', 'ls'): + return reply(volume.encode() if state['volume_exists'] else b'') + if args[:2] == ('volume', 'create'): + # Engine create is idempotent: existing data and labels survive it. + if not state['volume_exists']: + volume_labels.update(dict(args[i + 1].split('=', 1) for i, arg in enumerate(args) if arg == '--label')) + state['volume_exists'] = True + if scenario == 'volume-create-timeout': + raise module.NativeCommandFailure('timeout') + return reply(volume.encode()) + if args[:2] == ('image', 'inspect'): + return record_json({'Id': ('sha256:' + 'd' * 64 if scenario == 'wrong-image' and args[2] != module.IPMI_OLD else image_id), + 'RepoDigests': [args[2]], 'Os': 'linux', 'Architecture': 'amd64', + 'Config': {'Labels': {'org.opencontainers.image.revision': 'a5cfd4ea0d6e43c6346f641693fcb6eef449433b'}}}) + if args[:2] == ('volume', 'inspect'): + return record_json({'Name': volume, 'Driver': 'local', 'Options': None, + 'Labels': dict(volume_labels), + 'Mountpoint': str(root / 'alias' if scenario == 'symlink-volume' else data)}) + if args[0] == 'ps': + if state['removed']: + return reply() + if args == ('ps', '-aq', '--no-trunc'): + if scenario == ('truncated-after-create' if state['created'] else 'truncated-before-create'): + return reply(identity[:12].encode()) + if scenario == ('malformed-after-create' if state['created'] else 'malformed-before-create'): + return reply(b'g' * 64) + if state['created']: + if scenario == 'same-prefix-writer': + return reply(('\n'.join((identity, foreign_identity)) if '--no-trunc' in args + else '\n'.join((identity[:12], foreign_identity[:12]))).encode()) + return reply((identity if '--no-trunc' in args else identity[:12]).encode()) + foreign = 'f' * 64 if scenario in ('existing-runtime', 'stopped-writer') else '' + return reply((foreign if '--no-trunc' in args else foreign[:12]).encode()) + if args[0] == 'create': + name = args[args.index('--name') + 1] + self.assertIn(name, qa.site_initializers) + self.assertIsNone(qa.site_initializers[name]['id']) + self.assertIn(volume, qa.volumes) + mounts = [args[i + 1] for i, arg in enumerate(args) if arg == '--mount'] + self.assertEqual(mounts, [f'type=volume,src={volume},dst=/app/data', f'type=bind,src={root}/servers.yaml,dst=/app/config/servers.yaml,readonly']) + value.update(Id=identity, Name='/' + name, Image=image_id, + Config={'Labels': {'io.cryptolabs.native-qa.run': '123'}, 'Image': args[-3], + 'Entrypoint': [args[args.index('--entrypoint') + 1]], 'Cmd': list(args[-2:]), + 'Env': [args[i + 1] for i, arg in enumerate(args) if arg == '-e']}, + HostConfig={'NetworkMode': args[args.index('--network') + 1], 'Privileged': False}, + Mounts=[{'Destination': '/app/data', 'Type': 'volume', 'Name': volume, 'Source': str(data), 'RW': True}, + {'Destination': '/app/config/servers.yaml', 'Type': 'bind', 'Source': str(root / 'servers.yaml'), 'RW': False}], + State={'Running': False, 'Status': 'created'}) + if scenario == 'wrong-site-name': + value['Config']['Env'][-1] = 'SITE_NAME=wrong' + state['created'] = True + if scenario == 'create-timeout': + raise module.NativeCommandFailure('timeout') + return reply(identity.encode()) + if args[0] == 'inspect': + if args[1] == foreign_identity: + return record_json({'Id': foreign_identity, 'Name': '/foreign-writer', + 'State': {'Running': False}, 'Mounts': [{'Name': volume, 'Source': str(data)}]}) + if args[1] in ('f' * 64, 'f' * 12): + return record_json({'Name': '/ipmi-monitor' if scenario == 'existing-runtime' else '/stopped', + 'State': {'Running': False}, 'Mounts': [{'Name': volume}]}) + self.assertIn(args[1], (identity, identity[:12])) + if scenario == 'wrong-terminal-id' and state['exited']: + return record_json(dict(value, Id='e' * 64)) + return record_json(value) + if args[0] == 'start': + self.assertEqual(qa.site_initializers[value['Name'][1:]]['id'], identity) + self.assertEqual(args[1], identity) + state['started'] = True + if scenario == 'start-failed': + raise module.NativeCommandFailure('nonzero-exit', 1) + if scenario == 'deadline': + clock[0] += 60 + return reply() + if args[0] == 'wait': + self.assertTrue(state['started']) + if scenario == 'wait-timeout': + raise module.NativeCommandFailure('timeout') + state['exited'] = True + value['State'] = {'Running': scenario == 'still-running', 'Status': 'running' if scenario == 'still-running' else 'exited', 'ExitCode': 0} + if scenario == 'changed-volume': + data.rename(root / 'old-data'); data.mkdir() + if scenario == 'config-swap': + (root / 'servers.yaml').rename(root / 'old-config') + (root / 'servers.yaml').write_text('servers: []\n') + return reply(b'7' if scenario == 'nonzero' else b'0') + if args[0] == 'run': + self.assertIn('ipmi-monitor', args) + if scenario != 'bind': + self.assertTrue(state['exited']) + self.assertIs(value['State']['Running'], False) + self.assertEqual(args[-3:], ('-e', 'SITE_NAME=SYNTHETIC Fleet native fixture', image_id)) + else: + self.assertFalse(state['created']) + self.assertEqual(args[-1], qa.refs['ipmi-old']) + self.assertNotIn('SITE_NAME=SYNTHETIC Fleet native fixture', args) + state['runtime'] = True + if args[:2] == ('rm', '-f'): + self.assertEqual(args[2], identity) + state['removed'] = True + if args[:2] == ('volume', 'rm'): + if not preexisting: + self.assertTrue(state['removed']) + # Model successful Engine removal with actual temporary data deletion, + # so the rejection/reset composition observes harm, not just argv. + for child in data.iterdir(): + child.unlink() + data.rmdir() + state['volume_exists'] = False + return reply() + scope = dict(module.__dict__, self=qa, layout='bind' if scenario == 'bind' else 'named-volume', network='native-fleet-named-volume-123') + # Root-only ancestry/file ownership is unavailable in portable CI. + # Keep actual no-follow path identities/content and replacement checks. + def directories(path): + return [(str(path), module.trust_identity(path.lstat()))] + def read_config(path): + with path.open('rb') as stream: + return stream.read(), os.fstat(stream.fileno()) + with patch.object(module, 'docker', side_effect=engine), patch.object(module.time, 'monotonic', side_effect=lambda: clock[0]), patch.object(module, 'trust_directories', side_effect=directories), patch.object(module, 'trust_read', side_effect=read_config): + scope['docker'] = module.docker + if preexisting: + original_error = None + try: + exec(code, scope) + except (AssertionError, module.NativeCommandFailure) as error: + original_error = error + qa.consume_child_failure = lambda: None + qa.recovery.reset = lambda: None + cleanup_error = None + with patch.object(module, 'run'), patch.object(module.shutil, 'rmtree'): + try: + qa.reset_fixture() + except Exception as error: + cleanup_error = error + # Inspect survival before checking the original refusal. Initial + # candidate accepts the empty same-label case, then deletes it too. + self.assertTrue(data.is_dir(), 'actual reset deleted a preexisting volume; ' + f'initial={type(original_error).__name__}, cleanup={type(cleanup_error).__name__}') + self.assertEqual(data.stat().st_ino, initial_volume_inode) + if scenario != 'preexisting-empty': + self.assertEqual((data / 'prior.db').read_bytes(), b'SYNTHETIC retained data') + self.assertTrue(state['volume_exists']) + self.assertFalse(state['runtime']) + self.assertIsInstance(original_error, (AssertionError, module.NativeCommandFailure)) + self.assertFalse(any(args[:2] == ('volume', 'rm') for args in calls)) + continue + if scenario in ('pass', 'bind', 'cleanup-foreign', 'cleanup-volume-label', 'cleanup-volume-inode'): + exec(code, scope) + self.assertTrue(state['runtime']) + else: + with self.assertRaises((AssertionError, module.NativeCommandFailure)): + exec(code, scope) + self.assertFalse(state['runtime']) + self.assertEqual(timeouts, sorted(timeouts, reverse=True)) + if scenario == 'pass': + scans = [args for args in calls if args[0] == 'ps'] + self.assertEqual(scans, [('ps', '-aq', '--no-trunc')] * 2) + before_start = calls[:next(i for i, args in enumerate(calls) if args[0] == 'start')] + self.assertEqual([args for args in before_start if args[0] == 'inspect'], [('inspect', identity)]) + if scenario.startswith(('truncated-', 'malformed-')): + self.assertFalse(state['started']) + inspected = [args[1] for args in calls if args[0] == 'inspect'] + self.assertNotIn(identity[:12], inspected) + self.assertNotIn('g' * 64, inspected) + self.assertEqual(state['created'], scenario.endswith('after-create')) + if scenario == 'same-prefix-writer': + self.assertEqual(identity[:12], foreign_identity[:12]) + self.assertNotEqual(identity, foreign_identity) + self.assertIn(('inspect', foreign_identity), calls) + self.assertFalse(state['started']) + if scenario in ('pass', 'create-timeout', 'cleanup-foreign', 'volume-create-timeout', + 'cleanup-volume-label', 'cleanup-volume-inode'): + qa.consume_child_failure = lambda: None + qa.recovery.reset = lambda: None + if scenario == 'cleanup-foreign': + value['Config']['Labels']['io.cryptolabs.native-qa.run'] = 'foreign' + if scenario == 'cleanup-volume-label': + volume_labels['io.cryptolabs.native-qa.volume'] = 'foreign-nonce' + if scenario == 'cleanup-volume-inode': + data.rename(root / 'retained-owned-volume'); data.mkdir() + (data / 'prior.db').write_bytes(b'SYNTHETIC replacement data') + cleanup_inode = data.stat().st_ino + with patch.object(module, 'run'), patch.object(module.shutil, 'rmtree'): + if scenario == 'volume-create-timeout': + with self.assertRaisesRegex(RuntimeError, 'volume creation custody uncertain'): + qa.reset_fixture() + self.assertFalse(state['created']) + self.assertTrue(state['volume_exists']) + self.assertTrue(data.is_dir()) + self.assertEqual(data.stat().st_ino, cleanup_inode) + self.assertFalse(any(args[:2] == ('volume', 'rm') for args in calls)) + elif scenario in ('cleanup-volume-label', 'cleanup-volume-inode'): + with self.assertRaises(AssertionError): + qa.reset_fixture() + self.assertTrue(state['removed'], 'the exact owned one-shot may be removed') + self.assertTrue(state['volume_exists']) + self.assertTrue(data.is_dir()) + self.assertEqual(data.stat().st_ino, cleanup_inode) + if scenario == 'cleanup-volume-inode': + self.assertEqual((data / 'prior.db').read_bytes(), b'SYNTHETIC replacement data') + self.assertTrue((root / 'retained-owned-volume').is_dir()) + self.assertFalse(any(args[:2] == ('volume', 'rm') for args in calls)) + elif scenario == 'cleanup-foreign': + with self.assertRaises(AssertionError): + qa.reset_fixture() + self.assertFalse(state['removed']) + self.assertFalse(any(args[:2] == ('volume', 'rm') for args in calls)) + else: + qa.reset_fixture() + self.assertTrue(state['removed']) + self.assertEqual(qa.site_initializers, {}) + + def test_rejected_preexisting_backup_root_survives_actual_reset(self): + module = self.native_module() + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + wheels = root / "wheels"; wheels.mkdir() + expected = {} + for name, version in (("dc-overview", "1.8.0"), ("cryptolabs-proxy", "1.5.4")): + path = wheels / (name + ".whl") + with zipfile.ZipFile(path, "w") as archive: + archive.writestr(name.replace("-", "_") + ".dist-info/METADATA", "Name: " + name + "\nVersion: " + version + "\n") + expected[name] = (version, hashlib.sha256(path.read_bytes()).hexdigest()) + qa = module.NativeQA(SimpleNamespace(evidence_dir=root / "evidence", legacy_wheel_dir=wheels, wheel_dir=wheels, + protection_helper=ROOT / "scripts/fixtures/legacy-selected-state-protection.py")) + recovery = qa.recovery + recovery.host_env = root / "unoccupied-host-env" + recovery.backup_root = root / "preexisting-empty-backup" + recovery.backup_root.mkdir() + before = recovery.backup_root.stat().st_ino + # Only the unrelated package input digest boundary is substituted; + # occupied-path validation and reset execute their actual code. + with patch.object(module, "LEGACY_WHEELS", expected), patch.object(module, "run", side_effect=AssertionError("runtime forbidden")): + with self.assertRaisesRegex(RuntimeError, "fresh disposable guest fixture path occupied"): + recovery.validate_inputs() + def local_path(value): + return root / "unoccupied-cli-link" if str(value) == "/usr/local/bin/dc-overview" else Path(value) + with patch.object(module, "Path", side_effect=local_path): + recovery.reset() + self.assertTrue(recovery.backup_root.is_dir(), "rejected foreign root must survive cleanup") + self.assertEqual(recovery.backup_root.stat().st_ino, before) + recovery.backup_root = root / "owned-positive" + with patch.object(module, "Path", side_effect=local_path): + recovery.claim_backup_root() + recovery.reset() + self.assertFalse(recovery.backup_root.exists()) + recovery.backup_root = root / "owned-before-replacement" + recovery.claim_backup_root() + retained = root / "retained-owned-root" + recovery.backup_root.rename(retained) + recovery.backup_root.mkdir(mode=0o700) + replacement_inode = recovery.backup_root.stat().st_ino + with patch.object(module, "Path", side_effect=local_path): + with self.assertRaises(AssertionError): + recovery.reset() + self.assertEqual(recovery.backup_root.stat().st_ino, replacement_inode) + self.assertTrue(retained.is_dir()) + + def test_recovery_rejects_unfrozen_inputs_before_guest_commands(self): + module = self.native_module() + with patch.object(module, "RECOVERY_INPUTS_FROZEN", False), patch.object(module, "run", side_effect=AssertionError("guest command forbidden")): + with self.assertRaisesRegex(RuntimeError, "recovery inputs"): + module.check_recovery_inputs("a" * 40) + with patch.object(module, "RECOVERY_INPUTS_FROZEN", True): + module.check_recovery_inputs("a" * 40) + with self.assertRaisesRegex(RuntimeError, "published reviewed proxy"): + module.check_recovery_inputs("ROOT_MUST_SET_REVIEWED_RECOVERY_PROXY_SHA") + + def test_reconcile_fixture_requires_only_receipt_and_unchanged_native_history(self): + module = self.native_module() + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + identity = "a" * 32 + job = json.dumps({"id": identity, "state": "failed"}).encode() + active = json.dumps({"id": identity}).encode() + for name, raw in ((identity + ".json", job), ("active.json", active), ("dispatch.lock", b""), ("operation.lock", b"")): + (root / name).write_bytes(raw) + before = module.recovery_store_snapshot(root) + receipt = {"job_sha256": hashlib.sha256(job).hexdigest(), "active_sha256": hashlib.sha256(active).hexdigest(), "original_container_id": "b" * 64} + receipt_path = root / ("service-recovery-" + identity + ".json") + receipt_path.write_text(json.dumps(receipt)) + receipt_path.chmod(0o600) + self.assertEqual(module.verify_recovery_store(root, before, identity, "b" * 64), receipt_path.read_bytes()) + receipt_path.chmod(0o644) + with self.assertRaises(AssertionError): + module.verify_recovery_store(root, before, identity, "b" * 64) + receipt_path.chmod(0o600) + (root / "active.json").write_bytes(b"{}") + with self.assertRaises(AssertionError): + module.verify_recovery_store(root, before, identity, "b" * 64) + (root / "active.json").write_bytes(active) + (root / "unexpected.json").write_bytes(b"{}") + with self.assertRaises(AssertionError): + module.verify_recovery_store(root, before, identity, "b" * 64) + def test_service_snapshot_exports_only_closed_fields(self): module = self.native_module() valid = b"ActiveState=active\nSubState=running\nResult=success\nMainPID=123\nExecMainStatus=0\n" @@ -215,6 +1254,922 @@ def foreign(): self.assertIsNone(metadata["source_line"]) self.assertNotIn(private, json.dumps(metadata)) + with tempfile.TemporaryDirectory() as directory: + qa = module.NativeQA(SimpleNamespace(evidence_dir=Path(directory))) + def fixture_boundary(): + qa.recovery.bootstrap() + # Actual bootstrap -> inspect -> docker -> run, with only the + # subprocess boundary substituted. No old product is simulated. + for returncode in (17, -9, True, 256): + with self.subTest(returncode=returncode), patch.object(module.subprocess, "run", return_value=SimpleNamespace(returncode=returncode, stdout=private.encode(), stderr=private.encode())): + try: + fixture_boundary() + except RuntimeError as error: + metadata = module.native_phase_failure_metadata(error, "fixture", (("fixture", fixture_boundary.__code__),)) + else: + self.fail("checked subprocess failure must escape") + self.assertIn(metadata["source_line"], {line for _, _, line in fixture_boundary.__code__.co_lines()}) + self.assertEqual(metadata["error_kind"], "runtime-error") + failure = self.assert_bootstrap_failure_shape(metadata) + self.assertEqual(failure["bootstrap_step"], "legacy-runtime-inspect") + self.assertIn(failure["code_label"], {"legacy-bootstrap", "native-command"}) + trusted_lines = {line for code in (module.LegacyRecoveryFixture.bootstrap.__code__, module.run.__code__) for _, _, line in code.co_lines()} + self.assertIn(failure["source_line"], trusted_lines) + self.assertEqual(failure["command_outcome"], "nonzero-exit") + self.assertEqual(failure["command_returncode"], returncode if type(returncode) is int and -255 <= returncode <= 255 else None) + self.assertNotIn(private, json.dumps(metadata)) + + # Reproduce the reviewed constructed API witness through the real + # run/bootstrap frames. Current run-created outcomes are literals; + # this protects the closed contract, not a claimed native leak. + class EqualString(str): + def __eq__(self, other): + return True + with self.subTest("constructed hostile outcome"): + error = module.NativeCommandFailure(EqualString(private), 17) + with patch.object(module.subprocess, "run", side_effect=error): + try: + fixture_boundary() + except RuntimeError as caught: + metadata = module.native_phase_failure_metadata(caught, "fixture", (("fixture", fixture_boundary.__code__),)) + else: + self.fail("the original owned exception must preserve failure") + self.assertNotIn(private, json.dumps(metadata)) + outcome, _ = module.command_failure_facts(error) + self.assertIs(type(outcome), str) + self.assertEqual(outcome, "unknown") + self.assertEqual(metadata["bootstrap_failure"]["command_outcome"], "unknown") + for supplied, expected in (("nonzero-exit", "nonzero-exit"), ("timeout", "timeout"), ("spawn-error", "spawn-error"), (None, "unknown")): + with self.subTest(canonical_outcome=supplied): + outcome, _ = module.command_failure_facts(module.NativeCommandFailure(supplied, 17)) + self.assertIs(type(outcome), str) + self.assertEqual(outcome, expected) + + # Judge immutability through public facts after ordinary mutation + # attempts; arbitrary reflection/object.__setattr__ is out of scope. + mutations = ( + ("set", lambda error: setattr(error, "_command_returncode", 23)), + ("delete returncode", lambda error: delattr(error, "_command_returncode")), + ("delete outcome", lambda error: delattr(error, "_command_outcome")), + ("reinitialize", lambda error: error.__init__("timeout")), + ) + for name, mutate in mutations: + with self.subTest(ordinary_mutation=name): + error = module.NativeCommandFailure("nonzero-exit", 17) + before = module.command_failure_facts(error) + try: + mutate(error) + except (AttributeError, TypeError): + pass + try: + after = module.command_failure_facts(error) + except AttributeError: + after = None + self.assertEqual(after, before) + + @contextmanager + def propagation_boundary(): + try: + yield + finally: + propagated.append(True) + propagated = [] + error = module.NativeCommandFailure("nonzero-exit", 17) + cause = ValueError(private) + try: + with propagation_boundary(): + raise error from cause + except module.NativeCommandFailure as caught: + self.assertIs(caught, error) + self.assertIs(caught.__cause__, cause) + caught.__traceback__ = caught.__traceback__ + caught.__context__ = cause + caught.__suppress_context__ = True + self.assertIs(caught.__context__, cause) + self.assertEqual(module.command_failure_facts(caught), ("nonzero-exit", 17)) + self.assertEqual(propagated, [True]) + + class UntrustedError(RuntimeError): + @property + def returncode(self): + raise AssertionError("untrusted exception property inspected") + def __str__(self): + raise AssertionError("untrusted exception text inspected") + def replacement(self): + raise UntrustedError(private) + original = module.LegacyRecoveryFixture.bootstrap.__code__ + replacement.__code__ = replacement.__code__.replace(co_filename=original.co_filename, co_name=original.co_name) + with patch.object(module.LegacyRecoveryFixture, "bootstrap", replacement): + try: + fixture_boundary() + except RuntimeError as error: + metadata = module.native_phase_failure_metadata(error, "fixture", (("fixture", fixture_boundary.__code__),)) + failure = self.assert_bootstrap_failure_shape(metadata) + self.assertEqual(failure, {"bootstrap_step": "unknown", "code_label": "unknown", "source_line": None, + "guard_line": None, "error_kind": "unknown", "command_outcome": "unknown", "command_returncode": None, + "scoped_select_diagnostic": "unknown", + "scoped_select_inner_diagnostic": module.inner_unknown()}) + self.assertNotIn(private, json.dumps(metadata)) + + # Exercise the exact installed-wheel predicate, rather than a replacement + # selector or mocked distribution. This portable source test cannot + # establish which interpreter/guard failed in a historical native run. + import importlib.metadata + upgrade_path = ROOT / "src/dc_overview/fleet_upgrade.py" + upgrade_source = upgrade_path.read_text() + self.assertEqual(hashlib.sha256(upgrade_source.encode()).hexdigest(), + "ac7d1e55de5707130b2acbf6e92b861ec960413a8fea4d6ff0097984111b8934") + node = next(n for n in ast.parse(upgrade_source).body + if isinstance(n, ast.FunctionDef) and n.name == "verify_running_cli") + self.assertEqual(hashlib.sha256(ast.get_source_segment(upgrade_source, node).encode()).hexdigest(), + "c830c355e09f81bdbf28f34286116558eebf752d51aab45bdeeaf80d16b5c344") + init_source = (ROOT / "src/dc_overview/__init__.py").read_text() + version = next(ast.literal_eval(n.value) for n in ast.parse(init_source).body + if isinstance(n, ast.Assign) + and any(isinstance(t, ast.Name) and t.id == "__version__" for t in n.targets)) + package_name = "_fleet_selector_predicate_fixture" + package = types.ModuleType(package_name) + package.__version__ = version + namespace = {"__name__": package_name + ".fleet_upgrade", "__package__": package_name, "json": json} + exec(compile(ast.Module(body=[node], type_ignores=[]), str(upgrade_path), "exec"), namespace) + predicate = namespace["verify_running_cli"] + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + package.__path__ = [str(root)] + distribution = root / ("dc_overview-" + version + ".dist-info") + distribution.mkdir() + metadata_path = distribution / "METADATA" + provenance_path = distribution / "direct_url.json" + metadata_path.write_text("Metadata-Version: 2.4\nName: dc-overview\nVersion: " + version + "\n") + target = {"release": version, "url": "https://example.invalid/PRIVATE_SELECTED_WHEEL.whl", + "sha256": "a" * 64} + provenance = {"url": target["url"], "archive_info": {"hashes": {"sha256": target["sha256"]}}} + with patch.dict(sys.modules, {package_name: package}), patch.object(sys, "path", [str(root)]): + provenance_path.write_text(json.dumps(provenance)) + installed = importlib.metadata.distribution("dc-overview") + self.assertEqual(installed.version, version) + self.assertEqual(json.loads(installed.read_text("direct_url.json")), provenance) + expected = target["url"] + "#sha256=" + target["sha256"] + self.assertEqual(predicate(target), {"success": True, "state": "verified", "owner": "host-cli", + "desired": expected, "observed": expected}) + provenance_path.write_text(json.dumps({"url": "https://example.invalid/PRIVATE_OTHER_WHEEL.whl", + "archive_info": {"hashes": {"sha256": "b" * 64}}})) + before = {p: p.read_bytes() for p in (metadata_path, provenance_path)} + try: + predicate(target) + except RuntimeError as error: + original_kind, original_args = type(error), error.args + trace = error.__traceback__ + observed = module.broker_failure_metadata(error, (("dc-running-cli", predicate.__code__),)) + self.assertIs(type(error), original_kind) + self.assertEqual(error.args, original_args) + self.assertIs(error.__traceback__, trace) + line = None + while trace is not None: + if trace.tb_frame.f_code is predicate.__code__: + line = trace.tb_lineno + trace = trace.tb_next + self.assertEqual(line, 141, "the real original provenance refusal must be exercised") + self.assertTrue(str(error).startswith("requires_cli_upgrade:")) + else: + self.fail("version equality must not bypass original URL/hash provenance checks") + self.assertEqual({p: p.read_bytes() for p in before}, before) + self.assertEqual(upgrade_path.read_text(), upgrade_source) + for private in ("PRIVATE", str(root), target["url"], target["sha256"]): + self.assertNotIn(private, json.dumps(observed)) + self.assertEqual(observed["code_label"], "dc-running-cli", + "the original selector predicate is currently lost behind its outer broker frame") + self.assertEqual(observed["source_line"], line) + self.assertEqual(observed["error_kind"], "runtime-error") + + # Exercise the same bounded reader/loaded-code qualifier in a private + # installed-layout fixture. Only exact original function bodies are + # compiled; no immutable Proxy code or product module is imported. + module.sysconfig.get_config_vars() # Load stdlib build data before restricting metadata discovery. + with private_owner_temp(module) as directory: + root = Path(directory) + prefix = root / "legacy-host-venv" + site = prefix / ("lib/python" + str(sys.version_info.major) + "." + str(sys.version_info.minor)) / "site-packages" + package_path = site / "dc_overview" + package_path.mkdir(parents=True, mode=0o700) + init_path = package_path / "__init__.py" + init_path.write_text(init_source) + installed_upgrade = package_path / "fleet_upgrade.py" + installed_upgrade.write_text(upgrade_source) + installed_package = types.ModuleType("dc_overview") + installed_package.__file__ = str(init_path) + installed_package.__version__ = version + installed_module = types.ModuleType("dc_overview.fleet_upgrade") + installed_module.__file__ = str(installed_upgrade) + installed_module.__package__ = "dc_overview" + installed_module.json = json + imports = [n for n in ast.parse(upgrade_source).body if isinstance(n, (ast.Import, ast.ImportFrom))] + exec(compile(ast.Module(body=[*imports, node], type_ignores=[]), str(installed_upgrade), "exec"), vars(installed_module)) + original_predicate = installed_module.verify_running_cli + distribution = site / ("dc_overview-" + version + ".dist-info") + distribution.mkdir(mode=0o700) + metadata_path = distribution / "METADATA" + provenance_path = distribution / "direct_url.json" + metadata_path.write_text("Metadata-Version: 2.4\nName: dc-overview\nVersion: " + version + "\n") + provenance_path.write_text(json.dumps({"url": "https://example.invalid/PRIVATE_OTHER_WHEEL.whl", + "archive_info": {"hashes": {"sha256": "b" * 64}}})) + selected_manifest = {"components": {"dc-overview-cli": {"owner": "host-cli", "release": version, + "artifacts": {"any": {"kind": "wheel", "url": target["url"], "sha256": target["sha256"]}}}}} + with patch.dict(sys.modules, {"dc_overview": installed_package, "dc_overview.fleet_upgrade": installed_module}), patch.object(sys, "path", [str(site)]), patch.object(sys, "prefix", str(prefix)), patch.object(module, "ROOT", root): + # The predicate-only fixture below cannot prove the observer's + # required selector role. Qualify the complete unchanged module + # first, without calling its selector, guards or owner APIs. + full_module = types.ModuleType("dc_overview.fleet_upgrade") + full_module.__file__ = str(installed_upgrade) + full_module.__package__ = "dc_overview" + full_code = compile(upgrade_source, str(installed_upgrade), "exec") + exec(full_code, vars(full_module)) + original_selector = full_module.select_release_components.__code__ + with patch.dict(sys.modules, {"dc_overview.fleet_upgrade": full_module}): + full_codes = module.naturally_loaded_selector_codes(module.time.monotonic() + 1) + required = [code for label, code in full_codes if label == "dc-scoped-selector"] + self.assertEqual(len(required), 1, "full frozen source must qualify exactly one original selector") + self.assertIs(required[0], original_selector) + self.assertEqual(installed_upgrade.read_text(), upgrade_source) + deadline = module.time.monotonic() + 1 + codes = module.naturally_loaded_selector_codes(deadline) + self.assertEqual(codes, (("dc-running-cli", original_predicate.__code__),)) + before = {p: p.read_bytes() for p in (metadata_path, provenance_path, installed_upgrade)} + try: + original_predicate(target) + except RuntimeError as error: + with owner_file_read_audit(module, {metadata_path: 65536, provenance_path: 65536}) as reads: + detail = module.selector_failure_details(error, codes, selected_manifest, module.time.monotonic() + 1) + self.assertEqual([item["path"] for item in reads], [metadata_path, provenance_path]) + self.assertEqual(detail["frames"], [{"role": "dc-running-cli", "line": 141}]) + self.assertEqual(detail["qualification"], "qualified") + self.assertEqual(detail["actual_interpreter"], "compatible-host-venv") + self.assertEqual([detail[k] for k in ("module_version_match", "distribution_version_match", "url_match", "hash_match")], [True, True, False, False]) + self.assertTrue(module.selector_details_valid(detail)) + self.assertNotIn("PRIVATE", json.dumps(detail)) + self.assertNotIn(str(root), json.dumps(detail)) + self.assertLessEqual(len(module.encoded(detail)), 4096) + with self.assertRaises(module.ObservationRefused): + module.selector_failure_details(error, codes, selected_manifest, module.time.monotonic() - 1) + installed_module.__file__ = str(prefix / "foreign/dc_overview/fleet_upgrade.py") + self.assertEqual(module.naturally_loaded_selector_codes(module.time.monotonic() + 1), ()) + installed_module.__file__ = str(installed_upgrade) + installed_package.__file__ = str(prefix / "foreign/dc_overview/__init__.py") + self.assertEqual(module.selector_failure_details(error, codes, selected_manifest, + module.time.monotonic() + 1)["qualification"], "source-refused") + installed_package.__file__ = str(init_path) + # A source-identical filename/name does not qualify foreign code. + installed_module.verify_running_cli = foreign + self.assertEqual(module.naturally_loaded_selector_codes(module.time.monotonic() + 1), ()) + installed_module.verify_running_cli = original_predicate + installed_upgrade.write_text(upgrade_source + "\n") + self.assertEqual(module.naturally_loaded_selector_codes(module.time.monotonic() + 1), ()) + installed_upgrade.write_text(upgrade_source) + alias = distribution / "retained-metadata" + metadata_path.rename(alias) + metadata_path.symlink_to(alias) + with self.assertRaises(module.ObservationRefused): + module.selector_failure_details(error, codes, selected_manifest, module.time.monotonic() + 1) + metadata_path.unlink(); alias.rename(metadata_path) + provenance_path.write_bytes(b"x" * 65537) + with self.assertRaises(module.ObservationRefused): + module.selector_failure_details(error, codes, selected_manifest, module.time.monotonic() + 1) + provenance_path.write_bytes(before[provenance_path]) + else: + self.fail("real provenance mismatch must retain its original predicate failure") + self.assertEqual({p: p.read_bytes() for p in before}, before) + + # Actual frozen parser -> unmapped _json failure: retain context without + # promoting its recognized outer Manifest frame into the inner cause. + catalog_path = ROOT / "src/dc_overview/release_catalog.py" + self.assertEqual(hashlib.sha256(catalog_path.read_bytes()).hexdigest(), + "21d4cf4731226c4ca9498cd4999bec1ec90bb9d3628faa615e13f20ccd9a29f6") + catalog = runpy.run_path(str(catalog_path)) + parser_code = catalog["Manifest"].from_bytes.__func__.__code__ + try: + catalog["Manifest"].from_bytes(b"PRIVATE_INVALID_JSON") + except ValueError as error: + codes = (("catalog-manifest", parser_code),) + self.assertEqual(module.broker_failure_metadata(error, codes), + {"code_label": None, "source_line": None, "error_kind": "unknown"}) + detail = module.selector_failure_details(error, codes, {}, module.time.monotonic() + 1) + self.assertEqual(detail["qualification"], "innermost-unknown") + self.assertTrue(detail["frames"]) + self.assertIsNone(detail["url_match"]) + self.assertNotIn("PRIVATE", json.dumps(detail)) + else: + self.fail("the original strict parser must refuse malformed JSON") + + def test_scoped_select_closed_observation_and_transport(self): + native = self.native_module() + PRIVATE = "PRIVATE_SCOPED_ARGUMENT_PATH_OUTPUT" + product_modules = {name: value for name, value in sys.modules.items() if name == "dc_overview" or name.startswith("dc_overview.") or name == "cryptolabs_proxy" or name.startswith("cryptolabs_proxy.")} + messages = [ + { + "category": "cli-provenance-rejected", + "stderr_utf8_exact": "Error: requires_cli_upgrade: install the verified exact wheel from the selected manifest using the documented package-manager step, then rerun this command\n" + }, + { + "category": "recovery-required", + "stderr_utf8_exact": "Error: native_service_recovery_required\n" + }, + { + "category": "updater-busy", + "stderr_utf8_exact": "Error: updater is busy; retry scoped selection after it finishes\n" + }, + { + "category": "updater-custody-changed", + "stderr_utf8_exact": "Error: updater custody changed during scoped selection\n" + }, + { + "category": "updater-store-changed", + "stderr_utf8_exact": "Error: updater store changed during scoped selection\n" + }, + { + "category": "updater-lock-changed", + "stderr_utf8_exact": "Error: updater lock changed during scoped selection\n" + }, + { + "category": "public-reference-stale", + "stderr_utf8_exact": "Error: public configuration/selection snapshot is stale\n" + }, + { + "category": "public-reference-changed", + "stderr_utf8_exact": "Error: public configuration changed after release preflight\n" + }, + { + "category": "proxy-identity-required", + "stderr_utf8_exact": "Error: running proxy identity is required for scoped selection\n" + }, + { + "category": "proxy-identity-changed", + "stderr_utf8_exact": "Error: proxy changed during scoped selection\n" + }, + { + "category": "proxy-release-mount-required", + "stderr_utf8_exact": "Error: proxy read-only release mount prerequisite\n" + }, + { + "category": "updater-mount-changed", + "stderr_utf8_exact": "Error: updater mount changed during scoped selection\n" + }, + { + "category": "manifest-changed", + "stderr_utf8_exact": "Error: manifest changed during scoped preparation\n" + }, + { + "category": "runtime-changed", + "stderr_utf8_exact": "Error: scoped runtime changed during selection\n" + }, + { + "category": "proxy-authority-required", + "stderr_utf8_exact": "Error: Proxy updater authority prerequisite: install the compatible published cryptolabs-proxy package, then use cryptolabs-proxy configuration plan and cryptolabs-proxy configuration adopt to migrate the existing proxy before retrying. The running updater must advertise selection contract 1 and proxy_replacement_policy=host-adoption-required-v1; no update was submitted or release changes applied.\n" + } + ] + # Baseline privacy is already present and must survive this extension. + with patch.object(native.subprocess, 'run', return_value=SimpleNamespace(returncode=1, stdout=PRIVATE.encode(), stderr=PRIVATE.encode())) as child: + with self.assertRaises(native.NativeCommandFailure) as raised: + native.run('fixed-cli', PRIVATE) + self.assertEqual(native.command_failure_facts(raised.exception), ('nonzero-exit', 1)) + self.assertNotIn(PRIVATE, str(raised.exception) + repr(raised.exception) + repr(raised.exception.args)) + self.assertEqual(child.call_count, 1) + + def boundary(flag): + _bootstrap_step = 'scoped-select' + native.run('fixed-cli', 'release', 'select', PRIVATE, input_bytes=b'fixed-input', timeout=37, + env={'PUBLIC_FIXED': '1'}, scoped_select_diagnostic=flag) + + codes = ((boundary.__code__, 'legacy-bootstrap', native.bootstrap_step_offsets(boundary.__code__)), + (native.run.__code__, 'native-command', ())) + + def observation(result, flag=True, step='scoped-select'): + with patch.object(native.subprocess, 'run', return_value=result) as child: + try: + boundary(flag) + except native.NativeCommandFailure as error: + saved_error = error + value = native.bootstrap_failure_metadata(error, codes=codes, bootstrap_codes=(boundary.__code__,)) + except TypeError: + self.fail('MISSING_NEW_DIAGNOSTIC: real run wrapper rejects scoped_select_diagnostic=True; baseline RED, not native cause reproduction') + else: + self.fail('original checked command failure was lost') + self.assertEqual(child.call_count, 1) + error = saved_error + self.assertEqual(child.call_args.args, (['fixed-cli', 'release', 'select', PRIVATE],)) + self.assertEqual(child.call_args.kwargs, dict(input=b'fixed-input', capture_output=True, timeout=37, env={'PUBLIC_FIXED': '1'})) + self.assertEqual(native.command_failure_facts(error), ('nonzero-exit', result.returncode if type(result.returncode) is int and -255 <= result.returncode <= 255 else None)) + self.assertIsNone(value['guard_line']) + self.assertNotIn(PRIVATE, json.dumps(value) + str(error) + repr(error) + repr(error.args)) + self.assertIn('scoped_select_diagnostic', value) + self.assertIs(type(value['scoped_select_diagnostic']), str) + # Untrusted/non-bootstrap frame projections stay unknown. + self.assertEqual(native.bootstrap_failure_metadata(error, codes=codes, bootstrap_codes=())['scoped_select_diagnostic'], 'unknown') + return value['scoped_select_diagnostic'], error + + # Fail once at the first absent observable contract before the wider + # GREEN matrix; avoid redundant baseline failures for the same gap. + first = messages[0] + self.assertEqual(observation(SimpleNamespace(returncode=1, stdout=b'', stderr=first['stderr_utf8_exact'].encode()))[0], first['category']) + for entry in messages: + raw = entry['stderr_utf8_exact'].encode() + with self.subTest(category=entry['category']): + category, error = observation(SimpleNamespace(returncode=1, stdout=b'', stderr=raw)) + self.assertEqual(category, entry['category']) + # Discover owned diagnostic slot without prescribing its private name. + new_slots = set(native.NativeCommandFailure.__slots__) - {'_command_outcome', '_command_returncode', '_scoped_select_inner_diagnostic'} + self.assertEqual(len(new_slots), 1) + slot = next(iter(new_slots)) + self.assertEqual(type(getattr(error, slot)), str) + for owned in (slot, '_scoped_select_inner_diagnostic'): + saved = getattr(error, owned) + for mutation in (lambda: setattr(error, owned, PRIVATE), lambda: delattr(error, owned), lambda: error.__init__('timeout')): + with self.assertRaises((AttributeError, TypeError)): + mutation() + self.assertEqual(getattr(error, owned), saved) + self.assertEqual(getattr(error, slot), entry['category']) + + raw = messages[0]['stderr_utf8_exact'].encode() + class BytesSubclass(bytes): + pass + class StringTrap: + def __str__(self): + raise AssertionError('must not coerce arbitrary output') + cases = [ + (1, b'', b'prefix ' + raw), (1, b'', raw + b'\n'), (1, b'', raw[:-1]), + (1, b'', raw + messages[1]['stderr_utf8_exact'].encode()), + (1, PRIVATE.encode(), raw), (1, b'', b'x' * 513), (1, b'', b'\xff'), + (1, b'', 'text'), (1, b'', BytesSubclass(raw)), (1, BytesSubclass(b''), raw), + (1, b'', StringTrap()), (1, b'', b'Error: unknown\n'), (17, b'', raw), + (-1, b'', raw), (True, b'', raw), (1, None, raw), (1, b'', None), + ] + for index, (code, stdout, stderr) in enumerate(cases): + with self.subTest(negative=index): + self.assertEqual(observation(SimpleNamespace(returncode=code, stdout=stdout, stderr=stderr))[0], 'unknown') + for flag in (False, 1, 'True', None): + with self.subTest(default_off=repr(flag)): + self.assertEqual(observation(SimpleNamespace(returncode=1, stdout=b'', stderr=raw), flag=flag)[0], 'unknown') + def nonscoped_boundary(): + _bootstrap_step = 'legacy-runtime-inspect' + native.run('fixed-cli', scoped_select_diagnostic=True) + nonscoped_codes = ((nonscoped_boundary.__code__, 'legacy-bootstrap', native.bootstrap_step_offsets(nonscoped_boundary.__code__)), + (native.run.__code__, 'native-command', ())) + with patch.object(native.subprocess, 'run', return_value=SimpleNamespace(returncode=1, stdout=b'', stderr=raw)): + with self.assertRaises(native.NativeCommandFailure) as caught: + nonscoped_boundary() + self.assertEqual(native.bootstrap_failure_metadata(caught.exception, codes=nonscoped_codes, bootstrap_codes=(nonscoped_boundary.__code__,))['scoped_select_diagnostic'], 'unknown') + # Projection rejects subclasses and malformed stored categories without coercion. + class ForeignFailure(native.NativeCommandFailure): + pass + malformed = native.NativeCommandFailure('nonzero-exit', 1) + object.__setattr__(malformed, slot, StringTrap()) + for supplied in (ForeignFailure('nonzero-exit', 1), malformed): + with patch.object(native.subprocess, 'run', side_effect=supplied): + with self.assertRaises(native.NativeCommandFailure) as caught: + boundary(True) + value = native.bootstrap_failure_metadata(caught.exception, codes=codes, bootstrap_codes=(boundary.__code__,)) + self.assertEqual(value['scoped_select_diagnostic'], 'unknown') + # Unchecked/success and system exceptions preserve previous transport outcomes. + for code, check in ((0, True), (1, False)): + result = SimpleNamespace(returncode=code, stdout=b'', stderr=raw) + with patch.object(native.subprocess, 'run', return_value=result) as child: + self.assertIs(native.run('fixed-cli', check=check, scoped_select_diagnostic=True), result) + self.assertEqual(child.call_count, 1) + for side_effect, facts in ((native.subprocess.TimeoutExpired('fixed', 1), ('timeout', None)), (OSError(PRIVATE), ('spawn-error', None))): + with patch.object(native.subprocess, 'run', side_effect=side_effect) as child: + with self.assertRaises(native.NativeCommandFailure) as caught: + native.run('fixed-cli', scoped_select_diagnostic=True) + self.assertEqual(native.command_failure_facts(caught.exception), facts) + self.assertNotIn(PRIVATE, str(caught.exception) + repr(caught.exception.args)) + self.assertEqual(child.call_count, 1) + self.assertEqual({name: value for name, value in sys.modules.items() if name == 'dc_overview' or name.startswith('dc_overview.') or name == 'cryptolabs_proxy' or name.startswith('cryptolabs_proxy.')}, product_modules) + # Default-off means the keyword can be omitted, even in a scoped frame. + def default_boundary(): + _bootstrap_step = 'scoped-select' + native.run('fixed-cli') + default_codes = ((default_boundary.__code__, 'legacy-bootstrap', native.bootstrap_step_offsets(default_boundary.__code__)), + (native.run.__code__, 'native-command', ())) + with patch.object(native.subprocess, 'run', return_value=SimpleNamespace(returncode=1, stdout=b'', stderr=raw)): + with self.assertRaises(native.NativeCommandFailure) as caught: + default_boundary() + self.assertEqual(native.bootstrap_failure_metadata(caught.exception, codes=default_codes, bootstrap_codes=(default_boundary.__code__,))['scoped_select_diagnostic'], 'unknown') + for size in (511, 512, 513): + self.assertEqual(observation(SimpleNamespace(returncode=1, stdout=b'', stderr=b'x' * size))[0], 'unknown') + for stderr in (raw.replace(b'\n', b'\r\n'), raw.rstrip(b'\n'), raw + b' '): + self.assertEqual(observation(SimpleNamespace(returncode=1, stdout=b'', stderr=stderr))[0], 'unknown') + for code, stdout in ((1.0, b''), ('1', b''), (1, ''), (1, bytearray())): + self.assertEqual(observation(SimpleNamespace(returncode=code, stdout=stdout, stderr=raw))[0], 'unknown') + + # A collection fault never substitutes its private exception or loses cleanup. + cleaned = [] + @contextmanager + def cleanup_boundary(): + try: + yield + finally: + cleaned.append(True) + with patch.object(native, 'classify_scoped_select_output', side_effect=RuntimeError(PRIVATE)): + with cleanup_boundary(): + category, error = observation(SimpleNamespace(returncode=1, stdout=b'', stderr=raw)) + self.assertEqual(category, 'unknown') + self.assertEqual(native.command_failure_facts(error), ('nonzero-exit', 1)) + self.assertEqual(cleaned, [True]) + self.assertNotIn(PRIVATE, str(error) + repr(error) + repr(error.args)) + + # Same filename/name grants no frame identity; missing/hostile slots stay unknown. + def foreign_boundary(flag): + _bootstrap_step = 'scoped-select' + native.run('fixed-cli', scoped_select_diagnostic=flag) + foreign_boundary.__code__ = foreign_boundary.__code__.replace(co_filename=boundary.__code__.co_filename, co_name=boundary.__code__.co_name) + with patch.object(native.subprocess, 'run', return_value=SimpleNamespace(returncode=1, stdout=b'', stderr=raw)): + with self.assertRaises(native.NativeCommandFailure) as caught: + foreign_boundary(True) + self.assertEqual(native.bootstrap_failure_metadata(caught.exception, codes=codes, bootstrap_codes=(boundary.__code__,))['scoped_select_diagnostic'], 'unknown') + class EqualString(str): + def __eq__(self, other): + raise AssertionError('must reject subclasses before equality') + for category in (PRIVATE, EqualString(PRIVATE), StringTrap()): + malformed = native.NativeCommandFailure('nonzero-exit', 1) + object.__setattr__(malformed, slot, category) + with patch.object(native.subprocess, 'run', side_effect=malformed): + with self.assertRaises(native.NativeCommandFailure) as caught: + boundary(True) + self.assertEqual(native.bootstrap_failure_metadata(caught.exception, codes=codes, bootstrap_codes=(boundary.__code__,))['scoped_select_diagnostic'], 'unknown') + missing = native.NativeCommandFailure('nonzero-exit', 1) + object.__delattr__(missing, slot) + with patch.object(native.subprocess, 'run', side_effect=missing): + with self.assertRaises(native.NativeCommandFailure) as caught: + boundary(True) + self.assertEqual(native.bootstrap_failure_metadata(caught.exception, codes=codes, bootstrap_codes=(boundary.__code__,))['scoped_select_diagnostic'], 'unknown') + + + def test_inner_recovery_observer_bounds_and_original_child_contract(self): + native = self.native_module() + private = 'PRIVATE_INNER_EXCEPTION_OR_PATH' + def require(condition): + if not condition: + raise ValueError(private) + calls = [] + def dependency(*args, require_capability=True): + calls.append((args, require_capability)) + require(False) + trusted = ((dependency.__code__, 'proxy-updates', 'service_recovery_dependency'), + (require.__code__, 'proxy-recovery', 'require')) + def failure(): + try: + dependency('original', require_capability=False) + except ValueError as error: + return error + original = failure() + value = native.project_inner_failure(original, trusted) + self.assertTrue(value['guards']) + self.assertIs(value['condition'], False) + self.assertIs(value['require_capability'], False) + self.assertNotIn(private, json.dumps(value)) + self.assertEqual(native.project_inner_failure(original, ()), native.inner_unknown()) + spoof = require.__code__.replace(co_name=require.__code__.co_name) + self.assertEqual(native.project_inner_failure(original, ((spoof, 'proxy-recovery', 'require'),)), native.inner_unknown()) + class ForeignError(ValueError): + def __str__(self): + raise AssertionError('exception text must not be read') + foreign = ForeignError(private).with_traceback(original.__traceback__) + self.assertEqual(native.project_inner_failure(foreign, trusted), native.inner_unknown()) + # Exactly the context/frame limits remain usable; overflow/cycles do not. + contexts = [failure() for _ in range(9)] + for first, second in zip(contexts, contexts[1:]): + first.__context__ = second + self.assertEqual(native.project_inner_failure(contexts[0], trusted), native.inner_unknown()) + contexts[7].__context__ = None + self.assertTrue(native.project_inner_failure(contexts[0], trusted)['guards']) + contexts[7].__context__ = contexts[0] + self.assertEqual(native.project_inner_failure(contexts[0], trusted), native.inner_unknown()) + leaf = original.__traceback__ + while leaf.tb_next is not None: + leaf = leaf.tb_next + for count in (32, 33): + trace = None + for _ in range(count): + trace = types.TracebackType(trace, leaf.tb_frame, leaf.tb_lasti, leaf.tb_lineno) + bounded = ValueError(private).with_traceback(trace) + self.assertEqual(bool(native.project_inner_failure(bounded, trusted)['guards']), count == 32) + # Hostile values never cross the finite built-in schema. + class Trap: + def __str__(self): + raise AssertionError('foreign coercion') + def __eq__(self, other): + raise AssertionError('foreign comparison') + invalid = [None, Trap(), {**value, 'private': private}, {**value, 'condition': 1}, + {**value, 'condition': Trap()}, {**value, 'guards': tuple(value['guards'])}, + {**value, 'guards': [{'source': 'proxy-recovery', 'guard': 'require', 'line': True}]}, + {**value, 'guards': [{'source': private, 'guard': 'require', 'line': 1}]}] + for item in invalid: + self.assertEqual(native.inner_record(item), native.inner_unknown()) + # The real binding wrapper calls the original once and rethrows the + # identical failure. A recovered or ambiguous failure is never a cause. + module = SimpleNamespace(service_recovery_dependency=dependency) + for recovered, observer_fault, setup_fault, broken_pipe, multiple in ( + (False, False, False, False, False), (True, False, False, False, False), + (False, True, False, False, False), (False, False, True, False, False), + (False, False, False, True, False), (False, False, False, False, True)): + with self.subTest(recovered=recovered, observer_fault=observer_fault, setup_fault=setup_fault, + broken_pipe=broken_pipe, multiple=multiple): + entered, caught, calls = [], [], [] + def console(path, run_name): + entered.append((path, run_name, sys.argv[:])) + for turn in range(2 if multiple else 1): + try: + module.service_recovery_dependency('original', require_capability=False) + except ValueError as error: + caught.append(error) + if not recovered and (not multiple or turn == 1): + raise + reader, writer = os.pipe() + if broken_pipe: + os.close(reader) + try: + with patch.object(native, 'inner_trusted_codes', side_effect=RuntimeError(private) if setup_fault else None, return_value=trusted), patch.object(native.importlib, 'import_module', return_value=module), patch.object(runpy, 'run_path', side_effect=console), patch.object(native, 'project_inner_failure', side_effect=RuntimeError(private) if observer_fault else None, wraps=None if observer_fault else native.project_inner_failure): + if recovered: + native.scoped_select_child(writer, [], ['fixed-console', 'same-arg']) + else: + try: + native.scoped_select_child(writer, [], ['fixed-console', 'same-arg']) + except ValueError as error: + self.assertIs(error, caught[-1]) + else: + self.fail('original dependency failure must escape') + self.assertIs(module.service_recovery_dependency, dependency) + self.assertEqual(len(entered), 1) + self.assertEqual(entered[0], ('fixed-console', '__main__', ['fixed-console', 'same-arg'])) + self.assertEqual(calls, [(('original',), False)] * (2 if multiple else 1)) + with self.assertRaises(OSError): + os.fstat(writer) + if not broken_pipe: + raw = os.read(reader, 8193) + self.assertLessEqual(len(raw), 8192) + self.assertEqual(os.read(reader, 1), b'') + record = json.loads(raw) + self.assertNotIn(private, raw.decode()) + self.assertEqual(bool(record['guards']), not (recovered or observer_fault or setup_fault or multiple)) + finally: + if not broken_pipe: + os.close(reader) + # Capture the original traceback nodes before the observer rethrows. + # Original callers may catch and chain the same exception immediately. + for mode in ('context', 'cause', 'suppressed'): + with self.subTest(original_exception_chain=mode): + state = {} + original_error, outer_error = ValueError(private), RuntimeError(private) + def original_dependency(): + raise original_error + def capture(error, codes): + state['error'] = error + state['original_nodes'] = BaseException.__traceback__.__get__(error, type(error)).tb_next + state['chain'] = (error.__cause__, error.__context__, error.__suppress_context__) + return native.inner_unknown() + observed_module = SimpleNamespace(service_recovery_dependency=original_dependency) + def original_console(path, run_name): + try: + observed_module.service_recovery_dependency() + except ValueError as error: + self.assertIs(error, state['error']) + trace = BaseException.__traceback__.__get__(error, type(error)) + self.assertIs(trace.tb_frame.f_code, original_console.__code__) + self.assertIs(trace.tb_next, state['original_nodes']) + self.assertEqual((error.__cause__, error.__context__, error.__suppress_context__), state['chain']) + if mode == 'cause': + raise outer_error from error + if mode == 'suppressed': + raise outer_error from None + raise outer_error + reader, writer = os.pipe() + try: + with patch.object(native, 'inner_trusted_codes', return_value=trusted), patch.object(native.importlib, 'import_module', return_value=observed_module), patch.object(runpy, 'run_path', side_effect=original_console), patch.object(native, 'project_inner_failure', side_effect=capture): + try: + native.scoped_select_child(writer, [], ['fixed-console']) + except RuntimeError as error: + self.assertIs(error, outer_error) + else: + self.fail('original contextualized exception must escape') + self.assertIs(observed_module.service_recovery_dependency, original_dependency) + self.assertIs(outer_error.__context__, original_error) + self.assertIs(outer_error.__cause__, original_error if mode == 'cause' else None) + self.assertIs(outer_error.__suppress_context__, mode != 'context') + self.assertEqual((original_error.__cause__, original_error.__context__, original_error.__suppress_context__), state['chain']) + self.assertIs(original_error.__traceback__.tb_next, state['original_nodes']) + self.assertEqual(os.read(reader, 8193), native.encoded(native.inner_unknown())) + finally: + os.close(reader) + # Real subprocess/pipe/console execution: original argv, input, env, + # streams and success/nonzero/timeout results retain their meanings. + with tempfile.TemporaryDirectory() as directory: + root = Path(directory).resolve() + (root/'python').symlink_to(sys.executable) + cli = root/'console' + cli.write_text("import os,sys\nassert sys.argv[1:]==['same-arg']\nassert sys.stdin.buffer.read()==b'fixed-input'\nassert os.environ['FIXED_PUBLIC']=='1'\nsys.stdout.buffer.write(b'fixed-out')\nsys.stderr.buffer.write(b'fixed-err')\nraise SystemExit(7)\n") + result = native.run(cli, 'same-arg', input_bytes=b'fixed-input', env={**os.environ, 'FIXED_PUBLIC':'1'}, + check=False, scoped_select_diagnostic=True, scoped_select_wheels={}) + self.assertEqual((result.returncode, result.stdout, result.stderr), (7, b'fixed-out', b'fixed-err')) + cli.write_text("import sys\nsys.stderr.write('Error: native_service_recovery_required\\n')\nraise SystemExit(1)\n") + with self.assertRaises(native.NativeCommandFailure) as caught: + native.run(cli, scoped_select_diagnostic=True, scoped_select_wheels={}) + self.assertEqual(native.command_failure_facts(caught.exception), ('nonzero-exit', 1)) + self.assertEqual(native.scoped_select_failure_fact(caught.exception), 'recovery-required') + self.assertEqual(native.scoped_select_inner_fact(caught.exception), native.inner_unknown()) + cli.write_text("import time\ntime.sleep(2)\n") + with self.assertRaises(native.NativeCommandFailure) as caught: + native.run(cli, timeout=0.05, scoped_select_diagnostic=True, scoped_select_wheels={}) + self.assertEqual(native.command_failure_facts(caught.exception), ('timeout', None)) + # ADV-001: the interpreter renders the original application nodes, + # including application-owned runpy, without observer scaffolding. + counter = root/'calls' + (root/'application.py').write_text('raise RuntimeError("fixed-public-application")\n') + cases = { + 'runtime': 'raise RuntimeError("fixed-public-runtime")\n', + 'import': 'import fixed_public_absent_import_for_ADV001\n', + 'context': 'try:\n raise ValueError("fixed-public-context")\nexcept ValueError:\n raise RuntimeError("fixed-public-outer")\n', + 'cause': 'try:\n raise ValueError("fixed-public-cause")\nexcept ValueError as cause:\n raise RuntimeError("fixed-public-outer") from cause\n', + 'suppressed': 'try:\n raise ValueError("fixed-public-suppressed")\nexcept ValueError:\n raise RuntimeError("fixed-public-outer") from None\n', + 'application-runpy': 'import runpy\nrunpy.run_path(str(Path(__file__).with_name("application.py")),run_name="__main__")\n', + } + prefix = ('#!'+sys.executable+'\nfrom pathlib import Path\n' + 'counter=Path('+repr(str(counter))+')\n' + 'counter.write_text(str(int(counter.read_text())+1))\n' + 'print("fixed-public-once",flush=True)\n') + for name, body in cases.items(): + with self.subTest(original_terminal_output=name): + cli.write_text(prefix+body) + cli.chmod(0o700) + kwargs = dict(capture_output=True, timeout=5) + counter.write_text('0') + direct = subprocess.run([str(cli)], **kwargs) + self.assertEqual(counter.read_text(), '1') + counter.write_text('0') + wrapped, inner = native.scoped_select_subprocess([str(cli)], kwargs, {}) + self.assertEqual(counter.read_text(), '1') + self.assertEqual((wrapped.returncode, wrapped.stdout, wrapped.stderr), + (direct.returncode, direct.stdout, direct.stderr)) + self.assertEqual((direct.returncode, direct.stdout), (1, b'fixed-public-once\n')) + self.assertEqual(inner, native.inner_unknown()) + if name == 'application-runpy': + self.assertIn(b'', direct.stderr) + # The reader accepts one <=8KiB strict object, not concatenation, + # duplicate fields, overflow or a fault. No additional child runs occur. + raw = native.encoded(value) + for payload, qualified in ((raw+b' '*(8192-len(raw)), True), (raw+b' '*(8193-len(raw)), False), + (raw+raw, False), (b'{"guards":[],"guards":[],"condition":"unknown","require_capability":"unknown"}', False)): + with patch.object(native.subprocess, 'run', return_value=SimpleNamespace(returncode=1)) as child, patch.object(native.os, 'read', side_effect=[payload, b'']): + _, record = native.scoped_select_subprocess(['fixed-console'], {}, {}) + self.assertEqual(child.call_count, 1) + self.assertEqual(bool(record['guards']), qualified) + + def test_continuity_projection_is_closed_qualified_and_preserves_transport(self): + native = self.native_module() + # Qualification boundary only: the separate immutable Proxy2f contract + # executes the genuine producer/guard. This fixture isolates hostile + # locals/global drift without installing product packages or probing IO. + fields = native.CONTINUITY_FIELDS + namespace = types.ModuleType('fixed_continuity_projection_fixture') + source = ('from dataclasses import dataclass\n@dataclass(frozen=True)\n' + 'class OriginalObservation:\n container_id: str\n image_id: str\n' + ' helper_terminated: bool\n healthy: bool\n continuity: dict\n' + 'def hold():\n raise ValueError("PRIVATE_CONTINUITY_FAILURE")\n' + 'def require(condition):\n if not condition: hold()\n' + 'def validate_receipt(value):\n return value\n' + 'def validate_job(value):\n return value\n' + 'def validate_continuity(value):\n return value\n' + 'def _pattern(value, pattern):\n return True\n' + 'def validate_original_restored(receipt, observation):\n value=validate_receipt(receipt)\n') + source += '\n' * (227 - source.count('\n')) + source += ' require(validate_continuity(observation.continuity)==value["continuity"])\n' + with patch.dict(sys.modules, {namespace.__name__: namespace}): + exec(compile(source, '', 'exec'), namespace.__dict__) + namespace.HASH_KEYS = set(fields[:10]) + namespace.CONTINUITY_KEYS = set(fields) | {'projection', 'saved_identity_field_count', 'stored_key_digest_matches', 'sync_enabled'} + trusted = tuple((getattr(namespace, name).__code__, 'proxy-recovery', name) + for name in ('validate_original_restored', 'validate_receipt', 'validate_job', + 'validate_continuity', 'require', 'hold', '_pattern')) + unbound = trusted + trusted = native.bind_inner_trusted_context(trusted, namespace) + genuine_class = namespace.OriginalObservation + self.assertIs(trusted.observation_class, genuine_class) + baseline = {key: 'b' * 64 for key in fields[:10]} + baseline.update(database_device=1, database_inode=2, projection='ipmi-original-continuity-v1', + saved_identity_field_count=5, stored_key_digest_matches=True, sync_enabled=False) + def failure(changed=('database_inode',)): + before, after = dict(baseline), dict(baseline) + for key in changed: + after[key] = 'c' * 64 if key.endswith('_sha256') else after[key] + 1 + observation = namespace.OriginalObservation('1' * 64, 'sha256:' + '2' * 64, True, True, after) + try: + namespace.validate_original_restored({'continuity': before}, observation) + except ValueError as error: + return error, observation, before + self.fail('original equality guard must reject fixture') + for changed in [(key,) for key in fields] + [fields[:2]]: + with self.subTest(fields=changed): + error, observation, before = failure(changed) + record = native.project_inner_failure(error, trusted) + expected = {key: key not in changed for key in fields} + self.assertEqual(record['continuity_equal'], expected) + self.assertIs(record['condition'], False) + self.assertEqual(native.inner_record(record), record) + self.assertNotIn('PRIVATE_CONTINUITY_FAILURE', json.dumps(record)) + self.assertLessEqual(len(native.encoded(record)), 8192) + owned = native.NativeCommandFailure('nonzero-exit', 1, 'recovery-required', record) + record['continuity_equal']['database_inode'] = not expected['database_inode'] + self.assertEqual(native.scoped_select_inner_fact(owned)['continuity_equal'], expected) + payload = native.encoded(native.scoped_select_inner_fact(owned)) + with patch.object(native.subprocess, 'run', return_value=SimpleNamespace(returncode=1)) as child, patch.object(native.os, 'read', side_effect=[payload, b'']): + _, transported = native.scoped_select_subprocess(['fixed-console'], {}, {}) + self.assertEqual(child.call_count, 1) + self.assertEqual(transported['continuity_equal'], expected) + self.assertEqual(before, baseline) + self.assertEqual(error.args, ('PRIVATE_CONTINUITY_FAILURE',)) + error, _, _ = failure() + self.assertEqual(native.project_inner_failure(error, unbound)['continuity_equal'], 'unknown') + calls = {'eq': 0, 'getattr': 0, 'hash': 0} + class Trap: + def __hash__(self): + calls['hash'] += 1 + return 0 + def __eq__(self, other): + calls['eq'] += 1 + raise AssertionError('foreign equality must not execute') + def __getattribute__(self, name): + calls['getattr'] += 1 + raise AssertionError('foreign attributes must not execute') + class ForeignDict(dict): + def __eq__(self, other): + calls['eq'] += 1 + raise AssertionError('foreign dictionary equality must not execute') + for key, value in [('database_inode', True), ('database_device', -1), ('settings_sha256', Trap()), + ('settings_sha256', 'X' * 64), ('projection', Trap()), + ('saved_identity_field_count', True), ('stored_key_digest_matches', 1), + ('sync_enabled', 0)]: + with self.subTest(malformed=key, value_type=type(value).__name__): + error, observation, _ = failure() + observation.continuity[key] = value + self.assertEqual(native.project_inner_failure(error, trusted)['continuity_equal'], 'unknown') + self.assertEqual(calls, {'eq': 0, 'getattr': 0, 'hash': 0}) + for change in ('missing', 'extra', 'foreign-dict', 'foreign-observation', 'all-equal', 'globals', 'class', 'replacement-global', 'replacement-both', 'module', 'schema', 'ambiguous', 'source', 'line'): + with self.subTest(rejection=change): + error, observation, before = failure() + with patch.dict(namespace.__dict__): + selected = trusted + if change == 'missing': observation.continuity.pop('network_sha256') + if change == 'extra': observation.continuity['PRIVATE_EXTRA'] = Trap() + if change == 'foreign-dict': object.__setattr__(observation, 'continuity', ForeignDict(observation.continuity)) + if change == 'foreign-observation': + class ForeignObservation(namespace.OriginalObservation): + def __getattribute__(self, name): + calls['getattr'] += 1 + raise AssertionError('subclass attribute must not execute') + object.__setattr__(observation, '__class__', ForeignObservation) + if change == 'all-equal': observation.continuity.update(before) + if change == 'globals': namespace.require = lambda condition: None + if change == 'class': namespace.OriginalObservation = Trap + if change in ('replacement-global', 'replacement-both'): + attributes = {key: value for key, value in vars(genuine_class).items() + if key not in ('__dict__', '__weakref__')} + replacement = type('OriginalObservation', (), attributes) + self.assertIsNot(replacement, genuine_class) + namespace.OriginalObservation = replacement + if change == 'replacement-both': object.__setattr__(observation, '__class__', replacement) + if change == 'module': namespace.__name__ = Trap() + if change == 'schema': namespace.HASH_KEYS = set() + if change == 'ambiguous': error.__context__ = failure()[0] + if change == 'source': selected = tuple(row for row in trusted if row[2] != 'validate_continuity') + if change == 'line': + trace = error.__traceback__ + while trace.tb_frame.f_code is not namespace.validate_original_restored.__code__: + trace = trace.tb_next + error.__traceback__ = types.TracebackType(trace.tb_next, trace.tb_frame, trace.tb_lasti, 227) + self.assertEqual(native.project_inner_failure(error, selected)['continuity_equal'], 'unknown') + self.assertEqual(calls, {'eq': 0, 'getattr': 0, 'hash': 0}) + error, _, _ = failure() + method = namespace.OriginalObservation.__setattr__ + constants = method.__code__.co_consts + index = next(i for i, value in enumerate(constants) if type(value) in (tuple, frozenset)) + hostile = type(constants[index])([Trap()]) + calls.update(eq=0, getattr=0, hash=0) # Ignore construction; observe only the projector. + original_code = method.__code__ + try: + method.__code__ = original_code.replace(co_consts=constants[:index] + (hostile,) + constants[index + 1:]) + self.assertEqual(native.project_inner_failure(error, trusted)['continuity_equal'], 'unknown') + self.assertEqual(calls, {'eq': 0, 'getattr': 0, 'hash': 0}) + finally: + method.__code__ = original_code + record = native.project_inner_failure(error, trusted) + for value in ({}, {**record['continuity_equal'], 'database_inode': 0}, + {**record['continuity_equal'], 'PRIVATE_EXTRA': True}, + {key: True for key in fields}, Trap(), ForeignDict(record['continuity_equal'])): + self.assertEqual(native.inner_record({**record, 'continuity_equal': value}), native.inner_unknown()) + self.assertEqual(calls, {'eq': 0, 'getattr': 0, 'hash': 0}) + owned = native.NativeCommandFailure('nonzero-exit', 1, 'recovery-required', record) + raw = owned._scoped_select_inner_diagnostic + object.__setattr__(owned, '_scoped_select_inner_diagnostic', (*raw[:3], ((Trap(), True),) * 12)) + self.assertEqual(native.scoped_select_inner_fact(owned), native.inner_unknown()) + self.assertEqual(calls, {'eq': 0, 'getattr': 0, 'hash': 0}) + def test_broker_child_preserves_original_exception_when_collection_fails(self): module = self.native_module() cause = RuntimeError("PRIVATE_CHILD_EXCEPTION_ARGUMENT") @@ -250,6 +2205,31 @@ def run_operation(self): self.assertIn(metadata["source_line"], {line for _, _, line in serve.__code__.co_lines()}) self.assertNotIn("PRIVATE", json.dumps(metadata)) + # Existing execute/cleanup orchestration must survive a diagnostic + # collector failure. Only whole phase boundaries are substituted. + for cleanup_fails in (False, True): + with self.subTest(cleanup_fails=cleanup_fails), tempfile.TemporaryDirectory() as directory: + qa = module.NativeQA(SimpleNamespace(evidence_dir=Path(directory))) + cleaned = [] + def failed_fixture(layout): + raise RuntimeError("PRIVATE_BOOTSTRAP_FAILURE") + def cleanup_boundary(): + cleaned.append(True) + if cleanup_fails: + raise RuntimeError("PRIVATE_CLEANUP_CUSTODY_FAILURE") + with patch.object(qa, "preflight"), patch.object(qa, "images"), patch.object(qa, "units_install"), patch.object(qa, "fixture", side_effect=failed_fixture), patch.object(qa, "cleanup", side_effect=cleanup_boundary), patch.object(module, "native_phase_failure_metadata", side_effect=RuntimeError("PRIVATE_COLLECTOR_FAILURE")): + expected = "fixture cleanup held" if cleanup_fails else "native verification failed" + with self.assertRaisesRegex(RuntimeError, "^" + expected + "; native gate held$"): + qa.execute() + self.assertEqual(cleaned, [True]) + event = next(event for event in qa.events if event["case"] == "native-flow") + self.assertEqual(event["result"], "failed") + self.assertEqual(event["phase"], "fixture") + self.assertNotIn("PRIVATE", json.dumps(qa.events)) + if cleanup_fails: + self.assertTrue(any(event['case'] == 'native-flow' and event.get('phase') == 'cleanup' + for event in qa.events)) + def test_child_file_is_private_bounded_reset_and_consumed_before_cleanup(self): module = self.native_module() with tempfile.TemporaryDirectory() as d, patch.object(module, "ROOT", Path(d) / "fixture"): @@ -295,6 +2275,511 @@ def test_child_file_is_private_bounded_reset_and_consumed_before_cleanup(self): guest.execute() self.assertEqual(events, ["consume", "cleanup"]) + def test_owner_observation_slot_requires_private_retained_inode_exact_uuid_and_closed_shape(self): + module = self.native_module() + identity = "00000000-0000-4000-8000-000000000001" + other = "00000000-0000-4000-8000-000000000002" + failure = {"code_label": "broker-operation", "source_line": 924, "error_kind": "os-error"} + with private_owner_temp(module) as d, patch.object(module, "ROOT", Path(d) / "fixture"): + module.ROOT.mkdir(mode=0o700) + qa = module.NativeQA(SimpleNamespace(evidence_dir=Path(d) / "evidence")) + qa.layout = "bind" + qa.reset_owner_observation() + path = module.ROOT / "broker-owner-observation.json" + inode = path.stat().st_ino + self.assertEqual(path.stat().st_mode & 0o777, 0o600) + module.write_owner_observation(identity, failure) + raw = path.read_bytes() + self.assertLessEqual(len(raw), 4096) + self.assertEqual(qa.read_owner_observation(identity), failure) + self.assertEqual(path.read_bytes(), raw, "projection must not consume/reset the slot") + self.assertIsNone(qa.read_owner_observation(other)) + value = json.loads(raw) + self.assertEqual(set(value), {"schema_version", "operation_id", "failure"}) + for overflow, grows in ((False, False), (True, False), (True, True)): + content = raw.ljust(4096 + int(overflow and not grows), b" ") + path.write_bytes(content) + with owner_file_read_audit(module, {path: 4096}, grow=path if grows else None) as reads: + result = qa.read_owner_observation(identity) + self.assertEqual(result, None if overflow else failure) + if not overflow or grows: + self.assertEqual(len(reads), 1) + self.assertEqual(reads[0]["total"], 4096 + int(overflow)) + self.assertTrue(reads[0]["requests"]) + self.assertEqual(path.read_bytes(), content + (b" " if grows else b"")) + invalid = [b"{", b"x" * 4097, module.encoded({**value, "operation_id": other}), + module.encoded({**value, "schema_version": True}), + module.encoded({**value, "failure": {**failure, "source_line": True}}), + module.encoded({**value, "failure": {**failure, "code_label": "PRIVATE"}}), + module.encoded({**value, "private": "PRIVATE"})] + for data in invalid: + with self.subTest(data=data[:20]): + path.write_bytes(data) + self.assertIsNone(qa.read_owner_observation(identity)) + self.assertEqual(path.read_bytes(), data) + path.write_bytes(raw) + alias = module.ROOT / "alias" + os.link(path, alias) + self.assertIsNone(qa.read_owner_observation(identity)) + alias.unlink() + path.chmod(0o644) + self.assertIsNone(qa.read_owner_observation(identity)) + path.chmod(0o600) + path.rename(alias) + path.write_bytes(raw) + path.chmod(0o600) + self.assertNotEqual(path.stat().st_ino, inode) + self.assertIsNone(qa.read_owner_observation(identity)) + path.unlink() + path.symlink_to(alias) + self.assertIsNone(qa.read_owner_observation(identity)) + self.assertEqual(alias.read_bytes(), raw) + self.assertNotIn("PRIVATE", json.dumps(qa.events)) + + def test_owner_mapping_projection_reads_only_fixed_private_files_without_owner_calls(self): + module = self.native_module() + product_modules = {name: value for name, value in sys.modules.items() + if name in ("dc_overview", "cryptolabs_proxy") + or name.startswith(("dc_overview.", "cryptolabs_proxy."))} + release_broker = product_modules.get("dc_overview.release_broker") + identity = "00000000-0000-4000-8000-000000000001" + with private_owner_temp(module) as d: + root = Path(d).resolve() + qa = module.NativeQA(SimpleNamespace(evidence_dir=root / "evidence")) + qa.layout = "bind" + qa.store = SimpleNamespace(root=root / "releases") + qa.data = root / "bind" + qa.auth = qa.data / "auth" + qa.jobs = qa.auth / "update-jobs" + operations = qa.store.root / "broker" / "operations" + mapping = qa.jobs / "operations" + for directory in (qa.store.root, qa.store.root / "broker", operations, qa.data, qa.auth, qa.jobs, mapping): + directory.mkdir(mode=0o700, parents=True, exist_ok=True) + path = operations / (identity + ".json") + # Emit the record from the pinned producer expressions. Handwriting + # schema_version here hid the actual producer/observer mismatch. + broker_path = ROOT / "src/dc_overview/release_broker.py" + broker_source = broker_path.read_text() + self.assertEqual(hashlib.sha256(broker_source.encode()).hexdigest(), + "5916872d5ec87a2e9b69529c2c8a16f9a871667d9ff0ae27a0f1691fcaa296b7") + broker_tree = ast.parse(broker_source) + canonical = lambda value: json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() + sha = lambda raw: hashlib.sha256(raw).hexdigest() + def producer_expression(function, target, checksum): + node = next(n for n in ast.walk(broker_tree) + if isinstance(n, ast.FunctionDef) and n.name == function) + value = next(n.value for n in ast.walk(node) if isinstance(n, ast.Assign) + and any(isinstance(t, ast.Name) and t.id == target for t in n.targets)) + self.assertEqual(hashlib.sha256(ast.get_source_segment(broker_source, value).encode()).hexdigest(), checksum) + return compile(ast.Expression(body=value), str(broker_path), "eval") + preview_expression = producer_expression("_preview", "value", + "795e4f0aab87ef606559be825cb883a2a82d12aa268fc141c7e35fcbb6e8cc58") + operation_expression = producer_expression("_apply", "operation", + "b14b3da31a5afad812f29fd8a58d3e3a89ed4145b84e577b121afb6d04a6bc53") + # Model the unchanged native workflow at the OS boundary: sudo + # parent is root, checkout ancestry belongs to runner (1001), and + # the installed current wheel lives in the root-owned native venv. + checkout = root / "runner-checkout" + checkout_source = checkout / "src/dc_overview/release_broker.py" + checkout_source.parent.mkdir(parents=True) + checkout_source.write_text(broker_source) + qa.args.dc_source = checkout + native_prefix = Path("/opt/fleet-native-qa/venv") + native_site = native_prefix / "lib/python3.12/site-packages" + native_source = native_site / "dc_overview/release_broker.py" + installed_source = root / "installed-release-broker.py" + installed_source.write_text(broker_source) + original_lstat, fixture_open, original_fstat = Path.lstat, os.open, os.fstat + def root_info(info, *, runner=False, ancestor=False): + return SimpleNamespace(**{name: (1001 if runner else 0) if name == "st_uid" else + (0o40755 if ancestor else info.st_mode) if name == "st_mode" else getattr(info, name) + for name in ("st_uid", "st_gid", "st_mode", "st_dev", "st_ino", "st_nlink", + "st_size", "st_mtime_ns")}) + def native_lstat(name, *args, **kwargs): + name = Path(name) + if name == native_source: + return root_info(original_lstat(installed_source)) + if name in native_source.parents and name != Path("/"): + return root_info(original_lstat(root), ancestor=True) + return root_info(original_lstat(name, *args, **kwargs), + runner=name == checkout or checkout in name.parents, ancestor=name in root.parents) + def native_open(name, *args, **kwargs): + return fixture_open(installed_source if Path(name) == native_source else name, *args, **kwargs) + def native_purelib(name, *args, **kwargs): + self.assertEqual((name, args, kwargs), ("purelib", (), {"scheme": "posix_prefix", + "vars": {"base": str(native_prefix), "platbase": str(native_prefix)}})) + return str(native_site) + public = root / "fleet-config.yaml" + public.write_bytes(b"site_name: PRIVATE_SYNTHETIC_SITE\n") + actor = {"kind": "host-peer", "uid": 0} + params = {"candidate_ids": ["PRIVATE_candidate"], "components": ["ipmi-monitor"], + "expected_selection_id": "PRIVATE_selected", "expected_selection_sha256": "a" * 64, + "operation_kind": "services-update"} + manifest_raw = canonical({"schema_version": 1, "baseline_id": "PRIVATE_proposed", "selection_contract": 1, + "components": {"dc-overview-cli": {"owner": "host-cli", "release": "1.6.4", + "artifacts": {"any": {"kind": "wheel", "url": "https://example.invalid/PRIVATE.whl", "sha256": "b" * 64}}}, + "ipmi-monitor": {"owner": "proxy-updater", "release": "1.3.2", + "artifacts": {"linux/amd64": {"kind": "oci", "reference": module.IPMI_NEW}}}}}) + owner_identity = {"updater_directory": str(qa.jobs), "device": 1, "inode": 2, + "proxy_config_dir": str(root / "proxy"), "declaration_path": str(root / "declaration")} + namespace = {"self": SimpleNamespace(config=SimpleNamespace(config_dir=root), policy={"writes_enabled": True}, + owner=SimpleNamespace(identity=lambda: owner_identity)), + "preview_id": "00000000-0000-4000-8000-000000000003", "actor": actor, "params": params, + "manifest": SimpleNamespace(raw=manifest_raw, sha256=sha(manifest_raw)), + "proposed": SimpleNamespace(selection_sha256="c" * 64), "selection": {"selection_id": "PRIVATE_proposed"}, + "candidates": [SimpleNamespace(index={"generation": 1})], "owner_plan": None, "owner_declaration": None, + "entries": {"ipmi-monitor": {"channel": "main"}}, "canonical": canonical, "sha": sha, "base64": base64} + preview = eval(preview_expression, namespace) + preview["preview_sha256"] = sha(canonical(preview)) + apply_params = {"operation_id": identity, "preview_id": preview["preview_id"], + "preview_sha256": preview["preview_sha256"], "expected_selection_id": params["expected_selection_id"], + "expected_selection_sha256": params["expected_selection_sha256"]} + operation = eval(operation_expression, {"preview": preview, "params": apply_params, + "fingerprint": sha(canonical({"params": apply_params, "actor": actor}))}) + self.assertNotIn("schema_version", operation) + self.assertEqual(operation["state"], "prepared") + self.assertEqual(operation["phase"], "selection") + operation.update(state="recovery-required", phase="owner", + reason="Owner operation interrupted; reconcile retained operation before retry") + path.write_bytes(module.encoded(operation)); path.chmod(0o600) + mapped = mapping / (identity + ".json") + mapped.write_bytes(module.encoded({"operation_id": identity, "job_id": "f" * 32})); mapped.chmod(0o600) + inspected = [{"Mounts": [{"Source": str(qa.auth), "Destination": "/data/auth", "Type": "bind", "RW": True}], + "Config": {"Env": ["PRIVATE_INSPECT"]}}] + commands = [] + def fixed_inspect(): + commands.append(True) + return inspected + forbidden = AssertionError("passive projection called a functional API") + with ExitStack() as guards, patch.object(module, "inspect_owner_mounts_bounded", side_effect=fixed_inspect), patch.object(module, "run", side_effect=forbidden), patch.object(module, "docker", side_effect=forbidden), patch.object(module, "inspect", side_effect=forbidden), patch.object(qa, "status", side_effect=forbidden): + guards.enter_context(patch.object(module.os, "geteuid", return_value=0)) + guards.enter_context(patch.object(module.platform, "system", return_value="Linux")) + guards.enter_context(patch.object(module.sys, "prefix", str(native_prefix))) + guards.enter_context(patch.object(module.sysconfig, "get_path", side_effect=native_purelib)) + guards.enter_context(patch.object(Path, "lstat", native_lstat)) + guards.enter_context(patch.object(module.os, "open", side_effect=native_open)) + guards.enter_context(patch.object(module.os, "fstat", side_effect=lambda fd: root_info(original_fstat(fd)))) + with self.assertRaises(module.ObservationRefused) as refused: + module.selector_read_bytes(checkout_source, 1048576, module.time.monotonic() + 1) + self.assertEqual(refused.exception.args, ("custody-refused",)) + self.assertEqual(module.selector_read_bytes(native_source, 1048576, module.time.monotonic() + 1), broker_source.encode()) + if release_broker is not None: + guards.enter_context(patch.multiple(release_broker.InstalledOwner, **{name: unittest.mock.Mock(side_effect=forbidden) for name in ("capabilities", "identity", "submit", "status", "recover", "adopt")})) + guards.enter_context(patch.object(release_broker.ReleaseBroker, "dispatch", side_effect=forbidden)) + guards.enter_context(patch.object(release_broker.ReleaseBroker, "run_operation", side_effect=forbidden)) + before = {p: p.read_bytes() for p in (path, mapped)} + with owner_file_read_audit(module, {native_source: 1048576}) as source_reads: + value = qa.owner_mapping_observation(identity) + self.assertEqual([item["path"] for item in source_reads], [native_source]) + self.assertEqual(value["operation_qualification"], "valid") + self.assertEqual(value["operation"], {"observation": "present", "state": "recovery-required", "phase": "owner", "reason_category": "owner-interrupted", "job_id_present": False}) + self.assertEqual(value["fixture_mapping"], {"observation": "present", "job_id_present": True}) + self.assertEqual(value["current_mapping"], value["fixture_mapping"]) + self.assertEqual(value["owner_store"]["observation"], "same") + self.assertIs(value["owner_store"]["auth_equal"], True) + self.assertIs(value["owner_store"]["jobs_equal"], True) + self.assertEqual(len(commands), 1) + raw = module.encoded(value) + for private in (b"PRIVATE", str(root).encode(), b"f" * 32): + self.assertNotIn(private, raw) + self.assertEqual({p: p.read_bytes() for p in before}, before) + # Exact prefix/purelib and frozen bytes are compulsory. A + # readable checkout never supplies fallback after a refusal. + self.assertTrue(hasattr(qa, 'proxy_adoption_observation'), + 'proxy adoption needs a bounded read of its actual retained operation') + adopt_id = '00000000-0000-4000-8000-000000000005' + adopt_request = {**params, 'operation_kind': 'proxy-adopt', 'components': ['cryptolabs-proxy']} + adopt_preview = {k: v for k, v in preview.items() if k != 'preview_sha256'} + adopt_preview.update(request=adopt_request, owner_plan={'plan_id': 'e' * 64}, + owner_declaration={'canonical_json_base64': 'e30=', 'sha256': 'f' * 64}, + owner_identity={**owner_identity, 'updater_directory': str(root / 'named-volume/auth/update-jobs')}) + adopt_preview['preview_sha256'] = sha(canonical(adopt_preview)) + adopt_apply = {**apply_params, 'operation_id': adopt_id, + 'preview_sha256': adopt_preview['preview_sha256']} + adoption = eval(operation_expression, {'preview': adopt_preview, 'params': adopt_apply, + 'fingerprint': sha(canonical({'params': adopt_apply, 'actor': actor}))}) + adoption.update(state='recovery-required', phase='owner', + reason='Proxy source or declaration changed after preview') + adopt_path = operations / (adopt_id + '.json') + adopt_path.write_bytes(module.encoded(adoption)); adopt_path.chmod(0o600) + expected = {'apply': adopt_apply, 'request': adopt_request, 'preview': adopt_preview} + saved_layout = qa.layout + qa.layout = 'named-volume' + source_before, operation_before = installed_source.read_bytes(), adopt_path.read_bytes() + with owner_file_read_audit(module, {native_source: 1048576, adopt_path: 1048576}) as reads: + observation = qa.proxy_adoption_observation(adopt_id, expected) + self.assertEqual([item['path'] for item in reads], [native_source, adopt_path]) + self.assertEqual(observation['qualification'], 'valid') + self.assertEqual(observation['operation_state'], 'recovery-required') + self.assertEqual(observation['operation_phase'], 'owner') + self.assertEqual(observation['reason_category'], 'proxy-preview-plan-changed') + self.assertIs(observation['owner_plan_matches_preview'], True) + self.assertIs(observation['owner_declaration_matches_preview'], True) + self.assertIsNone(observation['failure']) + for private in ('PRIVATE', str(root), 'e' * 64, 'f' * 64): + self.assertNotIn(private, json.dumps(observation)) + self.assertLessEqual(len(module.encoded(observation)), 4096) + # Execute the unchanged InstalledOwner.adopt plan-conflict + # guard, then the actual child wrapper/private slot/parent + # projection. Only the passive plan and persistence boundary + # are substituted; no product mutation or qualification guard. + loaded = types.ModuleType('dc_overview.release_broker') + loaded.__file__ = str(native_source) + owner_code = next(code for code in compile(broker_source, str(native_source), 'exec').co_consts + if type(code) is types.CodeType and code.co_name == 'InstalledOwner') + adopt_code = next(code for code in owner_code.co_consts + if type(code) is types.CodeType and code.co_name == 'adopt') + error_node = next(node for node in broker_tree.body if isinstance(node, ast.ClassDef) and node.name == 'BrokerError') + error_namespace = {} + exec(compile(ast.Module(body=[error_node], type_ignores=[]), str(native_source), 'exec'), error_namespace) + loaded.InstalledOwner = type('InstalledOwner', (), {}) + loaded.InstalledOwner.adopt = types.FunctionType(adopt_code, error_namespace) + passive_plan = unittest.mock.Mock(return_value={'plan_id': 'different'}) + loaded.InstalledOwner.adoption = lambda self: (SimpleNamespace(plan=passive_plan), {}) + loaded.private_write = unittest.mock.Mock() + def actual_guard(owner, broker, target, value): + try: + owner.adopt(value['owner_plan']) + except Exception: + broker.private_write(target, value) + raise + adopt_node = next(node for node in ast.walk(broker_tree) + if isinstance(node, ast.FunctionDef) and node.name == 'adopt') + guard_line = next(node.lineno for node in ast.walk(adopt_node) if isinstance(node, ast.Raise)) + role = next(label for label, name, ancestry in module.ADOPTION_CODE_SPECS + if name == 'dc_overview.release_broker' and ancestry == ('InstalledOwner', 'adopt')) + with patch.object(module, 'ROOT', root), patch.dict(sys.modules, { + 'dc_overview.release_broker': loaded, 'cryptolabs_proxy.standard_adoption': None, + 'cryptolabs_proxy.update_recovery': None}): + qa.reset_owner_observation() + for changed in (False, True): + with self.subTest(adoption_source_changed=changed): + installed_source.write_bytes(source_before + (b'\n' if changed else b'')) + passive_plan.reset_mock(); loaded.private_write.reset_mock() + with module.observe_broker_owner_failures(loaded, operations, (('broker-operation', actual_guard.__code__),)): + with self.assertRaises(error_namespace['BrokerError']): + actual_guard(loaded.InstalledOwner(), loaded, adopt_path, adoption) + passive_plan.assert_called_once_with({}) + loaded.private_write.assert_called_once_with(adopt_path, adoption) + child = qa.read_owner_observation(adopt_id) + self.assertIsInstance(child, dict, 'the actual adoption lane must persist a source-qualified packet') + if changed: + self.assertEqual(child['adoption']['qualification'], 'source-refused') + self.assertIsNone(child['code_label']) + continue + self.assertEqual(child['adoption']['qualification'], 'qualified') + self.assertEqual(child['code_label'], role) + self.assertEqual(child['source_line'], guard_line) + self.assertEqual(child['adoption']['frames'][-1], {'role': role, 'line': guard_line}) + observed = qa.proxy_adoption_observation(adopt_id, expected) + self.assertEqual(observed['failure'], child) + self.assertNotIn('PRIVATE', json.dumps(observed)) + self.assertNotIn(str(root), json.dumps(observed)) + installed_source.write_bytes(source_before) + foreign_expected = {**expected, 'request': {**adopt_request, 'components': ['ipmi-monitor']}} + self.assertEqual(qa.proxy_adoption_observation(adopt_id, foreign_expected)['qualification'], 'identity-refused') + installed_source.write_bytes(source_before + b'\n') + self.assertEqual(qa.proxy_adoption_observation(adopt_id, expected)['qualification'], 'source-refused') + installed_source.write_bytes(source_before) + adopt_path.write_bytes(b'x' * 1048577) + self.assertEqual(qa.proxy_adoption_observation(adopt_id, expected)['qualification'], 'overflow') + adopt_path.write_bytes(operation_before) + with patch.object(module.time, 'monotonic', side_effect=[100.0, 102.0]): + self.assertEqual(qa.proxy_adoption_observation(adopt_id, expected)['qualification'], 'deadline') + self.assertEqual(adopt_path.read_bytes(), operation_before) + self.assertEqual(installed_source.read_bytes(), source_before) + qa.layout = saved_layout + for prefix in ("/usr", str(root / "other-venv")): + with self.subTest(prefix=prefix), patch.object(module.sys, "prefix", prefix): + rejected = qa.owner_mapping_observation(identity) + self.assertEqual(rejected["operation_qualification"], "source-refused") + self.assertEqual(rejected["operation"]["observation"], "unknown") + with patch.object(module.sysconfig, "get_path", return_value=str(native_prefix / "foreign")): + self.assertEqual(qa.owner_mapping_observation(identity)["operation_qualification"], "source-refused") + installed_source.write_text(broker_source + "\n") + self.assertEqual(qa.owner_mapping_observation(identity)["operation_qualification"], "source-refused") + installed_source.write_text(broker_source) + for mode in (0o666, 0o644): + installed_source.chmod(mode) + self.assertEqual(qa.owner_mapping_observation(identity)["operation_qualification"], + "custody-refused" if mode == 0o666 else "valid") + source_alias = root / "installed-source-alias" + os.link(installed_source, source_alias) + self.assertEqual(qa.owner_mapping_observation(identity)["operation_qualification"], "custody-refused") + source_alias.unlink() + installed_source.rename(source_alias) + installed_source.symlink_to(source_alias) + self.assertEqual(qa.owner_mapping_observation(identity)["operation_qualification"], "custody-refused") + installed_source.unlink(); source_alias.rename(installed_source) + self.assertEqual(checkout_source.read_text(), broker_source) + self.assertEqual(qa.owner_mapping_observation(identity)["operation_qualification"], "valid") + for target, field, valid in ((path, "operation", module.encoded(operation)), (mapped, "fixture_mapping", mapped.read_bytes())): + for overflow, grows in ((False, False), (True, False), (True, True)): + content = valid.ljust(1048576 + int(overflow and not grows), b" ") + target.write_bytes(content) + with owner_file_read_audit(module, {target: 1048576}, grow=target if grows else None) as reads: + projected = qa.owner_mapping_observation(identity) + self.assertEqual(projected[field]["observation"], "unknown" if overflow else "present") + self.assertLessEqual(len(reads), 1, "equal owner directories must be read once") + if not overflow or grows: + self.assertEqual(len(reads), 1) + self.assertEqual(reads[0]["total"], 1048576 + int(overflow)) + self.assertGreater(len(reads[0]["requests"]), 1) + self.assertNotIn("PRIVATE", module.encoded(projected).decode()) + self.assertEqual(target.read_bytes(), content + (b" " if grows else b"")) + target.write_bytes(valid) + mapped.unlink() + self.assertEqual(qa.owner_mapping_observation(identity)["fixture_mapping"]["observation"], "absent") + duplicate = module.encoded(operation).rstrip()[:-1] + b',"state":"recovery-required"}' + for content in (b"{", b"x" * 1048577, duplicate, + module.encoded({**operation, "operation_id": "00000000-0000-4000-8000-000000000002"}), + module.encoded({**operation, "generation": True}), + module.encoded({**operation, "PRIVATE_UNKNOWN_FIELD": "PRIVATE"}), + module.encoded({k: v for k, v in operation.items() if k != "manifest_sha256"})): + path.write_bytes(content) + self.assertEqual(qa.owner_mapping_observation(identity)["operation"]["observation"], "unknown") + self.assertEqual(path.read_bytes(), content) + path.write_bytes(module.encoded({**operation, "state": "PRIVATE_STATE", "phase": "PRIVATE_PHASE", "reason": "PRIVATE_REASON"})) + unknown = qa.owner_mapping_observation(identity)["operation"] + self.assertEqual((unknown["state"], unknown["phase"], unknown["reason_category"]), ("unknown", "unknown", "unknown")) + path.write_bytes(module.encoded(operation)) + original_open = module.os.open + replaced = [] + def replace_after_open(name, *args, **kwargs): + descriptor = original_open(name, *args, **kwargs) + if Path(name) == path and not replaced: + path.rename(operations / "replaced-original") + path.write_bytes(module.encoded(operation)); path.chmod(0o600) + replaced.append(True) + return descriptor + with patch.object(module.os, "open", side_effect=replace_after_open): + raced = qa.owner_mapping_observation(identity) + self.assertEqual(replaced, [True]) + self.assertEqual(raced["operation"]["observation"], "unknown") + # Initial absence and losing an already-open basename are different observations. + retained = operations / "retained-after-rename" + original_raw = path.read_bytes() + path.rename(retained) + initially_absent = qa.owner_mapping_observation(identity) + self.assertEqual(initially_absent["operation"]["observation"], "absent") + self.assertEqual(retained.read_bytes(), original_raw) + retained.rename(path) + opened = [] + def rename_away_after_open(name, *args, **kwargs): + descriptor = original_open(name, *args, **kwargs) + opened.append(Path(name)) + if Path(name) == path: + path.rename(retained) + return descriptor + with patch.object(module.os, "open", side_effect=rename_away_after_open): + lost_path = qa.owner_mapping_observation(identity) + self.assertFalse(path.exists()) + self.assertEqual(retained.read_bytes(), original_raw) + self.assertEqual(opened.count(path), 1) + self.assertLessEqual(set(opened), {path, mapped}) + with self.subTest(case="post-open-rename-away-is-unknown"): + self.assertEqual(lost_path["operation"]["observation"], "unknown") + retained.rename(path) + for mode in (0o644, 0o600): + path.chmod(mode) + if mode == 0o644: + self.assertEqual(qa.owner_mapping_observation(identity)["operation"]["observation"], "unknown") + alias = operations / "alias" + os.link(path, alias) + self.assertEqual(qa.owner_mapping_observation(identity)["operation"]["observation"], "unknown") + alias.unlink(); path.rename(alias); path.symlink_to(alias) + self.assertEqual(qa.owner_mapping_observation(identity)["operation"]["observation"], "unknown") + # A foreign inspect source never licenses reading another directory. + inspected[0]["Mounts"][0]["Source"] = str(root / "foreign") + foreign = qa.owner_mapping_observation(identity) + self.assertEqual(foreign["owner_store"]["observation"], "foreign") + self.assertEqual(foreign["current_mapping"]["observation"], "unknown") + self.assertFalse((root / "foreign").exists()) + with patch.object(module, "inspect_owner_mounts_bounded", return_value=None): + timed_out = qa.owner_mapping_observation(identity) + self.assertEqual(timed_out["owner_store"]["observation"], "unknown") + # A valid correlated failure is independent of unavailable mount metadata. + failure = {"code_label": "broker-operation", "source_line": 944, "error_kind": "os-error"} + with patch.object(module, "ROOT", root): + qa.reset_owner_observation() + module.write_owner_observation(identity, failure) + slot = root / "broker-owner-observation.json" + original_slot = slot.read_bytes() + self.assertEqual(qa.read_owner_observation(identity), failure) + foreign_inspect = [{"Mounts": [{"Source": str(root / "foreign"), "Destination": "/data/auth", "Type": "bind", "RW": True}]}] + for case, unavailable, store_state in (("inspect-unavailable", None, "unknown"), + ("foreign-mount", foreign_inspect, "foreign"), + ("malformed-mounts", [{"Mounts": "PRIVATE_MALFORMED"}], "unknown")): + with self.subTest(case=case), patch.object(module, "inspect_owner_mounts_bounded", return_value=unavailable): + observed = qa.owner_mapping_observation(identity) + self.assertEqual(slot.read_bytes(), original_slot) + self.assertEqual(observed["owner_store"]["observation"], store_state) + self.assertEqual(observed["current_mapping"]["observation"], "unknown") + self.assertNotIn("PRIVATE", module.encoded(observed).decode()) + self.assertEqual(observed["failure"], failure) + after_modules = {name: value for name, value in sys.modules.items() + if name in ("dc_overview", "cryptolabs_proxy") + or name.startswith(("dc_overview.", "cryptolabs_proxy."))} + self.assertEqual(set(after_modules), set(product_modules)) + self.assertTrue(all(after_modules[name] is value for name, value in product_modules.items())) + + def test_owner_inspect_capture_accepts_exact_limit_short_reads_and_requires_zero_exit(self): + module = self.native_module() + data = [{"Mounts": [], "Config": {"Env": ["PRIVATE_INSPECT"]}}] + raw = json.dumps(data).encode() + for payload, mode in ((raw, "ok"), (raw.ljust(1048576, b" "), "short"), (raw, "nonzero"), (raw, "spawn-error")): + with owner_inspect_boundary(module, payload, mode) as audit: + result = module.inspect_owner_mounts_bounded() + self.assertEqual(result, data if mode in ("ok", "short") else None) + if mode in ("ok", "short"): + self.assertEqual(audit["total"], len(payload)) + self.assertFalse(audit["killed"]) + + def test_owner_inspect_capture_stops_at_overflow_without_parse_and_reaps_exact_child(self): + module = self.native_module() + with owner_inspect_boundary(module, b"x" * 1052672) as audit, patch.object(module.json, "loads", side_effect=AssertionError("overflow must not parse")): + result = module.inspect_owner_mounts_bounded() + self.assertIsNone(result) + self.assertEqual(audit["total"], 1048577) + self.assertTrue(audit["killed"]) + self.assertEqual(audit["child"].kill.call_count, 1) + + def test_owner_inspect_capture_deadline_setup_and_read_failures_close_owned_resources(self): + module = self.native_module() + for mode in ("timeout", "eof-live", "setup-error", "read-error", "cleanup-timeout"): + with owner_inspect_boundary(module, b"", mode) as audit: + result = module.inspect_owner_mounts_bounded() + self.assertIsNone(result) + self.assertTrue(audit["killed"]) + self.assertEqual(audit["child"].kill.call_count, 1) + + def test_mapping_wait_failure_observes_once_and_preserves_original_gate(self): + module = self.native_module() + identity = "00000000-0000-4000-8000-000000000001" + for collector_fails in (False, True): + with tempfile.TemporaryDirectory() as directory: + qa = module.NativeQA(SimpleNamespace(evidence_dir=Path(directory) / "evidence")) + qa.jobs = Path(directory) / "update-jobs" + qa.policy = {"writes_enabled": False} + qa.layout = "bind" + # The preceding native policy procedure has its own full contract. + qa.policy_before_update = unittest.mock.Mock() + original = RuntimeError("actual owner mapping was not created") + observed = [] + def collect(operation_id): + observed.append(operation_id) + if collector_fails: + raise OSError("PRIVATE_DIAGNOSTIC") + return {"operation": {"observation": "unknown"}} + with patch.object(module, "inspect", return_value={"Id": "b" * 64}), patch.object(module, "write"), patch.object(qa, "selection", return_value={}), patch.object(qa, "preview", return_value=({}, {})), patch.object(qa, "apply", return_value=(identity, {})), patch.object(qa, "owner_mapping_observation", side_effect=collect), patch.object(module, "wait", side_effect=original) as waiting, patch.object(qa, "status", side_effect=AssertionError("passive failure cannot call status")): + with self.assertRaises(RuntimeError) as caught: + qa.service_update() + self.assertIs(caught.exception, original) + self.assertEqual(observed, [identity]) + self.assertEqual(waiting.call_count, 1) + self.assertEqual(waiting.call_args.kwargs, {"timeout": 90, "message": "actual owner mapping was not created"}) + self.assertNotIn("PRIVATE", json.dumps(qa.events)) + def test_lost_reply_keeps_request_connected_until_durable_acceptance(self): spec = importlib.util.spec_from_file_location("fleet_native_lost_reply", SCRIPT) module = importlib.util.module_from_spec(spec) @@ -452,13 +2937,21 @@ def test_route_is_exact_public_pr_and_never_inherits_authority(self): self.assertEqual(checkouts[0]["with"]["ref"], "${{ github.event.pull_request.head.sha }}") self.assertEqual(checkouts[1]["with"]["repository"], "cryptolabsza/cryptolabs-proxy") pin = data["env"]["PROXY_SOURCE_SHA"] - self.assertEqual(pin, "5db15086c26095179f2af56bfa434c85426a6699") + self.assertEqual(pin, "6e5186401e78cc8ba7b6ffe18eb24712ef9263b1") preflight = next( i for i, s in enumerate(job["steps"]) if s.get("name") == "Reject unresolved source pin" ) self.assertLess(preflight, job["steps"].index(checkouts[1])) self.assertIn("--check-inputs-only", job["steps"][preflight]["run"]) self.assertEqual(checkouts[1]["with"]["ref"], "${{ env.PROXY_SOURCE_SHA }}") + build = next(step["run"] for step in job["steps"] if step.get("name") == "Verify route and build exact wheels") + for version, checksum in (("dc_overview-1.8.0", "72fcf2fde1d765cdfebfd2e4071261e3ff28d202f7ffb1975340e9d362969304"), + ("cryptolabs_proxy-1.5.4", "5e64f0ae59d38ebcf4885d8aa60822bc3187d5a63f9abb8bdd11927d1ffd2b47")): + self.assertIn(version + "-py3-none-any.whl", build) + self.assertIn(checksum, build) + execution = next(step["run"] for step in job["steps"] if step.get("id") == "qa") + self.assertIn("--legacy-wheel-dir", execution) + self.assertIn("--protection-helper", execution) def test_placeholder_fails_before_guest_commands(self): spec = importlib.util.spec_from_file_location("fleet_native_qa", SCRIPT) @@ -1291,5 +3784,770 @@ def fixture(self, layout, cause=cause): ) + # TRACEWEAVER: verifies=VER-AUTOADVANCE-008; req=REQ-AUTOADVANCE-008; trace=TRACE-AUTOADVANCE-008 + def test_native_policy_versions_are_bound_to_existing_immutable_images(self): + module = self.native_module() + self.assertTrue(hasattr(module, 'IPMI_POLICY_PROOFS'), + 'native policy proof needs actual source-qualified versions') + expected = { + 'ipmi-old': ('1.3.1', module.IPMI_OLD, 'a5cfd4ea0d6e43c6346f641693fcb6eef449433b'), + 'ipmi-new': ('1.3.3', module.IPMI_NEW, 'cf79b1258e9b6c0daed8c9c998218e4fb48cc0db'), + } + self.assertEqual(set(module.IPMI_POLICY_PROOFS), set(expected)) + qa = module.NativeQA.__new__(module.NativeQA) + qa.refs = {name: value[1] for name, value in expected.items()} + for name, (version, reference, revision) in expected.items(): + proof = module.IPMI_POLICY_PROOFS[name] + self.assertEqual((proof['version'], proof['reference'], proof['source_revision']), + (version, reference, revision)) + self.assertEqual(qa.component(name)['release'], version) + self.assertEqual(qa.component(name)['artifacts']['linux/amd64']['reference'], reference) + self.assertEqual(module.IPMI_OLD, + 'ghcr.io/cryptolabsza/ipmi-monitor@sha256:738f11f7b432c4d9d8409154c9ca3f531a1e069999eb639a9d86433e84ac279d') + self.assertEqual(module.IPMI_NEW, + 'ghcr.io/cryptolabsza/ipmi-monitor@sha256:1d616479a3842f5101615b6d97552f732de73fd424fcb844a9c643e92abc8bb1') + + def test_native_policy_checks_real_package_version_and_rechecks_container_identity(self): + module = self.native_module() + self.assertTrue(hasattr(module.NativeQA, 'policy_installed_version'), + 'manifest version alone cannot prove the installed package version') + import copy + for fault in (None, 'package-version', 'image-reference', 'source-revision', 'container-race'): + with self.subTest(fault=fault): + qa = module.NativeQA.__new__(module.NativeQA) + qa.label = 'io.cryptolabs.native-qa=fixture' + qa.refs = {'ipmi-old': module.IPMI_OLD} + before = {'Id': 'c' * 64, 'Image': 'sha256:' + 'd' * 64, + 'State': {'Running': True}, + 'Config': {'Labels': {'io.cryptolabs.native-qa': 'fixture'}}} + image = {'Id': before['Image'], 'Os': 'linux', 'Architecture': 'amd64', + 'RepoDigests': [] if fault == 'image-reference' else [module.IPMI_OLD], + 'Config': {'Labels': {'org.opencontainers.image.revision': + 'e' * 40 if fault == 'source-revision' else + 'a5cfd4ea0d6e43c6346f641693fcb6eef449433b'}}} + reads = [] + def inspecting(name, *, image=False): + if image: + self.assertEqual(name, before['Image']) + return copy.deepcopy(image_value) + self.assertEqual(name, 'ipmi-monitor') + value = copy.deepcopy(before) + if reads and fault == 'container-race': + value['Id'] = 'f' * 64 + reads.append(value) + return value + image_value = image + engine_calls = [] + def engine(*args, **kwargs): + engine_calls.append((args, kwargs)) + self.assertEqual(args[:2], ('exec', before['Id'])) + self.assertIn('-I', args); self.assertIn('-B', args) + self.assertIn('importlib.metadata', args[-1]) + self.assertNotIn('ipmi_monitor.app', args[-1]) + self.assertNotIn('subprocess', args[-1]) + self.assertLessEqual(kwargs.get('timeout', 30), 30) + return SimpleNamespace(returncode=0, + stdout=b'9.9.9\n' if fault == 'package-version' else b'1.3.1\n', stderr=b'') + with patch.object(module, 'inspect', side_effect=inspecting), patch.object(module, 'docker', side_effect=engine): + if fault: + with self.assertRaises((AssertionError, RuntimeError, ValueError)): + qa.policy_installed_version('ipmi-old') + else: + self.assertEqual(qa.policy_installed_version('ipmi-old'), '1.3.1') + self.assertGreaterEqual(len(reads), 2) + self.assertEqual(len(engine_calls), 1) + + def test_native_policy_discovery_failures_restore_exact_signed_assets(self): + module = self.native_module() + self.assertTrue(hasattr(module.NativeQA, 'policy_discovery_refusals'), + 'native proof must exercise invalid and unavailable signed discovery') + for failure in (None, 'transport', 'unexpected-success'): + with self.subTest(failure=failure), tempfile.TemporaryDirectory() as directory: + root = Path(directory) + assets = root / 'admission'; assets.mkdir() + originals = {'admission-index.sig': b'PRIVATE-SIGNATURE-BYTES', + 'admission-index.json': b'PRIVATE-INDEX-BYTES'} + for name, value in originals.items(): + (assets / name).write_bytes(value) + qa = module.NativeQA.__new__(module.NativeQA) + current = {'selection_id': 'selected', 'selection_sha256': 'a' * 64, + 'components': {'ipmi-monitor': {'mode': 'follow-stable'}}} + qa.policy_listing = lambda: current + qa.policy_state_snapshot = lambda: {'policy': 'p', 'selection': 's', 'runtime': 'r'} + qa.record = unittest.mock.Mock() + seen = [] + def http(method, path, *, body=None, **kwargs): + self.assertEqual((method, path), ('POST', '/api/releases/policy-refresh')) + self.assertEqual(body, {'expected_selection_id': 'selected', + 'expected_selection_sha256': 'a' * 64}) + if not (assets / 'admission-index.json').exists(): + self.assertEqual((assets / 'admission-index.sig').read_bytes(), originals['admission-index.sig']) + seen.append('unavailable') + else: + self.assertNotEqual((assets / 'admission-index.sig').read_bytes(), originals['admission-index.sig']) + seen.append('invalid-signature') + if failure == 'transport': + raise RuntimeError('PRIVATE-TRANSPORT-DETAIL') + return SimpleNamespace(status_code=200 if failure == 'unexpected-success' else 503, + json=lambda: {'error': {'code': 'unavailable'}}) + qa.http = http + with patch.object(module, 'ROOT', root): + if failure: + with self.assertRaises((AssertionError, RuntimeError, ValueError)): + qa.policy_discovery_refusals() + else: + qa.policy_discovery_refusals() + self.assertCountEqual(seen, ['invalid-signature', 'unavailable']) + for name, value in originals.items(): + self.assertEqual((assets / name).read_bytes(), value) + self.assertEqual(set(p.name for p in assets.iterdir()), set(originals)) + self.assertNotIn('PRIVATE', repr(qa.record.call_args_list)) + + def test_native_policy_race_uses_separate_sessions_and_one_selection_cas(self): + module = self.native_module() + self.assertTrue(hasattr(module.NativeQA, 'policy_cas_race'), + 'native proof needs an actual two-client CAS race') + import threading + for winner in ('pin', 'refresh'): + with self.subTest(winner=winner): + current = {'selection_id': 'before', 'selection_sha256': 'a' * 64, + 'components': {'ipmi-monitor': {'mode': 'follow-stable', 'major': 1, + 'installed_release': '1.3.1', 'selected_release': '1.3.1'}}} + sessions, posts, closed = [], [], [] + won = threading.Event(); lock = threading.Lock() + class Client: + def __init__(client): + client.cookies = {}; client.verify = None + with lock: + client.number = len(sessions); sessions.append(client) + def get(client, url, **kwargs): + self.assertEqual(url, module.ORIGIN + '/api/releases/session') + return SimpleNamespace(status_code=200, + json=lambda: {'csrf_token': 'PRIVATE-' + str(client.number)}) + def post(client, url, **kwargs): + return client.request('POST', url, **kwargs) + def request(client, method, url, *, json=None, headers=None, timeout=None, **kwargs): + self.assertEqual(method, 'POST') + self.assertEqual(len(sessions), 2) + self.assertEqual(headers['X-CSRF-Token'], 'PRIVATE-' + str(client.number)) + self.assertEqual(headers['Origin'], module.ORIGIN) + self.assertIsNotNone(timeout); self.assertLessEqual(timeout, 15) + role = 'pin' if url.endswith('/policy-set') else 'refresh' + expected = {'expected_selection_id': 'before', 'expected_selection_sha256': 'a' * 64} + if role == 'pin': expected.update(component='ipmi-monitor', mode='pinned') + self.assertEqual(json, expected) + if role != winner: + self.assertTrue(won.wait(2), 'other client never completed') + with lock: + posts.append((role, client.number)) + status = 200 if role == winner else 409 + if status == 200: + won.set() + return SimpleNamespace(status_code=status, + json=lambda: {'error': {'code': 'selection-conflict'}} if status == 409 else current) + def close(client): closed.append(client.number) + qa = module.NativeQA.__new__(module.NativeQA) + qa.session = SimpleNamespace(cookies={'session': 'PRIVATE-AUTH'}, verify='/fixed/fixture-ca.crt') + qa.record = unittest.mock.Mock() + with patch.dict(sys.modules, {'requests': SimpleNamespace(Session=Client)}): + result = qa.policy_cas_race(current) + self.assertEqual(result, winner) + self.assertEqual(len(sessions), 2) + self.assertEqual(len(posts), 2) + self.assertEqual(len({number for _, number in posts}), 2) + self.assertCountEqual(closed, [0, 1]) + self.assertTrue(all(client.cookies == qa.session.cookies and + client.verify == qa.session.verify for client in sessions)) + self.assertNotIn('PRIVATE', repr(qa.record.call_args_list)) + + def test_native_policy_timer_requires_pin_before_persistent_enable(self): + module = self.native_module() + self.assertTrue(hasattr(module.NativeQA, 'policy_timer_prepare'), + 'packaged timer must be tested with catch-up control') + qa = module.NativeQA.__new__(module.NativeQA) + qa.policy_listing = lambda: {'components': {'ipmi-monitor': {'mode': 'follow-stable'}}} + with patch.object(module, 'run', side_effect=AssertionError('timer effect before pin')) as command: + with self.assertRaises((AssertionError, RuntimeError, ValueError)): + qa.policy_timer_prepare() + command.assert_not_called() + + def test_native_policy_timer_uncertain_creation_cannot_authorize_cleanup(self): + module = self.native_module() + self.assertTrue(hasattr(module.NativeQA, 'policy_timer_quiesce'), + 'new fixture units need positive cleanup ownership') + qa = module.NativeQA.__new__(module.NativeQA) + qa.policy_timer_attempted = True + qa.policy_timer_record = None + with patch.object(module, 'run', side_effect=AssertionError('unowned unit mutation')) as command: + with self.assertRaises((AssertionError, RuntimeError, ValueError)): + qa.policy_timer_quiesce() + command.assert_not_called() + + def test_native_policy_proof_surrounds_original_manual_upgrade_and_cleanup(self): + tree = ast.parse(SCRIPT.read_text()) + klass = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'NativeQA') + methods = {n.name: n for n in klass.body if isinstance(n, ast.FunctionDef)} + self.assertTrue({'policy_before_update', 'policy_after_update', 'policy_timer_quiesce'} <= methods.keys(), + 'source guard/unit tests alone cannot prove native policy controls') + calls = [(n.lineno, n.func.attr) for n in ast.walk(methods['service_update']) + if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute) + and isinstance(n.func.value, ast.Name) and n.func.value.id == 'self'] + lines = {name: [line for line, call in calls if call == name] + for name in ('policy_before_update', 'apply', 'finish', 'policy_after_update')} + self.assertTrue(all(len(value) == 1 for value in lines.values())) + self.assertLess(lines['policy_before_update'][0], lines['apply'][0]) + self.assertLess(lines['finish'][0], lines['policy_after_update'][0]) + for name in ('wait_mapped_worker', 'kill_broker', 'wait_fresh_broker'): + self.assertIn(name, [call for _, call in calls]) + reset_calls = [n.func.attr for n in ast.walk(methods['reset_fixture']) + if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute) + and isinstance(n.func.value, ast.Name) and n.func.value.id == 'self'] + self.assertIn('policy_timer_quiesce', reset_calls) + reset_lines = {n.func.attr: n.lineno for n in ast.walk(methods['reset_fixture']) + if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute) + and isinstance(n.func.value, ast.Name) and n.func.value.id == 'self'} + self.assertLess(reset_lines['policy_timer_quiesce'], reset_lines['consume_child_failure']) + + def test_native_policy_retains_actual_old_manifest_without_editing_desired_input(self): + module = self.native_module() + self.assertTrue(hasattr(module.NativeQA, 'policy_retain_installed_manifest'), + 'pending legacy desired selection must not masquerade as installed provenance') + import copy + with tempfile.TemporaryDirectory() as directory: + qa = module.NativeQA.__new__(module.NativeQA) + qa.data = Path(directory) + qa.refs = {'ipmi-old': module.IPMI_OLD} + desired = {'schema_version': 1, 'selection_contract': 1, 'baseline_id': 'legacy-desired', + 'components': {'ipmi-monitor': {'owner': 'proxy-updater', 'release': '1.3.2', + 'artifacts': {'linux/amd64': {'kind': 'oci', 'reference': module.LEGACY_DESIRED}}}, + 'cryptolabs-proxy': {'preserve': 'proxy'}, 'grafana': {'preserve': 'pin'}}} + original = copy.deepcopy(desired) + policies = {'ipmi-monitor': {'origin': 'baseline', 'enabled': True}, + 'grafana': {'origin': 'customer-pin', 'enabled': False}} + prepared = object(); captured = [] + def prepare(path, **kwargs): + captured.append((json.loads(Path(path).read_bytes()), kwargs)) + return prepared + qa.store = SimpleNamespace(prepare=unittest.mock.Mock(side_effect=prepare), + commit=unittest.mock.Mock()) + qa.policy_retain_installed_manifest(desired, policies) + self.assertEqual(desired, original) + qa.store.commit.assert_called_once_with(prepared) + self.assertEqual(len(captured), 1) + data, options = captured[0] + self.assertEqual(data['components']['ipmi-monitor'], qa.component('ipmi-old')) + for name in ('cryptolabs-proxy', 'grafana'): + self.assertEqual(data['components'][name], desired['components'][name]) + self.assertEqual(options, {'platform': 'linux/amd64', 'policies': policies}) + tree = ast.parse(SCRIPT.read_text()) + fixture = next(n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name == 'fixture') + retained = [n.lineno for n in ast.walk(fixture) if isinstance(n, ast.Call) + and isinstance(n.func, ast.Attribute) and n.func.attr == 'policy_retain_installed_manifest'] + selected = [n.lineno for n in ast.walk(fixture) if isinstance(n, ast.Call) + and isinstance(n.func, ast.Attribute) and n.func.attr == 'commit'] + self.assertEqual(len(retained), 1); self.assertEqual(len(selected), 1) + self.assertLess(retained[0], selected[0], 'original desired selection must remain the final fixture commit') + + def test_native_policy_kernel_lock_refusal_releases_real_flock_on_every_exit(self): + module = self.native_module() + self.assertTrue(hasattr(module.NativeQA, 'policy_lock_refusal'), + 'native proof must exercise the real lifecycle lock') + import fcntl + for transport_failure in (False, True): + with self.subTest(transport_failure=transport_failure), tempfile.TemporaryDirectory() as directory: + root = Path(directory); lock_path = root / '.lifecycle-config.lock' + lock_path.write_bytes(b''); lock_path.chmod(0o600) + qa = module.NativeQA.__new__(module.NativeQA) + qa.policy_listing = lambda: {'selection_id': 'before', 'selection_sha256': 'a' * 64, + 'components': {'ipmi-monitor': {'mode': 'follow-stable', 'major': 1}}} + qa.policy_state_snapshot = lambda: {'policy': 'p', 'selection': 's', 'runtime': 'r'} + qa.record = unittest.mock.Mock(); called = [] + def http(method, path, *, body=None, **kwargs): + self.assertEqual((method, path), ('POST', '/api/releases/policy-set')) + self.assertEqual(body, {'component': 'ipmi-monitor', 'mode': 'pinned', + 'expected_selection_id': 'before', 'expected_selection_sha256': 'a' * 64}) + descriptor = os.open(lock_path, os.O_RDONLY) + try: + with self.assertRaises(BlockingIOError): + fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB) + finally: + os.close(descriptor) + called.append(True) + if transport_failure: + raise RuntimeError('PRIVATE-TRANSPORT') + return SimpleNamespace(status_code=409, json=lambda: {'error': {'code': 'busy'}}) + qa.http = http + actual_fstat, actual_lstat = os.fstat, os.lstat + def root_metadata(info): + # Model root file custody; real descriptors and kernel flock + # acquisition/refusal/release remain unchanged. + values = {name: getattr(info, name) for name in dir(info) if name.startswith('st_')} + values.update(st_uid=0, st_gid=0) + return SimpleNamespace(**values) + with patch.object(module, 'CONFIG', root), \ + patch.object(module.os, 'fstat', side_effect=lambda *a, **kw: root_metadata(actual_fstat(*a, **kw))), \ + patch.object(module.os, 'lstat', side_effect=lambda *a, **kw: root_metadata(actual_lstat(*a, **kw))): + if transport_failure: + with self.assertRaises(RuntimeError): qa.policy_lock_refusal() + else: + qa.policy_lock_refusal() + self.assertEqual(called, [True]) + descriptor = os.open(lock_path, os.O_RDONLY) + try: + fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB) + fcntl.flock(descriptor, fcntl.LOCK_UN) + finally: + os.close(descriptor) + self.assertNotIn('PRIVATE', repr(qa.record.call_args_list)) + + def test_native_policy_timer_cleanup_validates_both_owned_files_before_effects(self): + module = self.native_module() + self.assertTrue(hasattr(module.NativeQA, 'policy_timer_quiesce') and + hasattr(module, 'POLICY_REFRESH_SYSTEMD'), + 'timer cleanup needs a fixed two-file ownership boundary') + import stat + for fault in (None, 'changed-bytes', 'changed-inode', 'extra-unit', 'still-active'): + with self.subTest(fault=fault), tempfile.TemporaryDirectory() as directory: + root = Path(directory); files = {} + for suffix in ('service', 'timer'): + path = root / ('dc-overview-release-refresh.' + suffix) + path.write_bytes(('[Unit]\nDescription=owned-' + suffix + '\n').encode()) + path.chmod(0o600); info = path.lstat() + files[str(path)] = {'sha256': module.digest(path.read_bytes()), + 'device': info.st_dev, 'inode': info.st_ino} + if fault == 'changed-bytes': + next(root.iterdir()).write_bytes(b'foreign unit bytes') + if fault == 'changed-inode': + files[str(root / 'dc-overview-release-refresh.service')]['inode'] += 1 + if fault == 'extra-unit': files[str(root / 'unrelated.service')] = dict(next(iter(files.values()))) + qa = module.NativeQA.__new__(module.NativeQA) + qa.policy_timer_attempted = True + qa.policy_timer_record = {'files': files} + actual_lstat, actual_fstat = os.lstat, os.fstat + def native_root_info(info): + # OS ownership and ancestor directory modes are synthetic; + # file bytes, inode/device, type, link count and faults are real. + values = {name: getattr(info, name) for name in dir(info) if name.startswith('st_')} + values.update(st_uid=0, st_gid=0) + if stat.S_ISDIR(info.st_mode): values['st_mode'] = stat.S_IFDIR | 0o755 + return SimpleNamespace(**values) + calls = [] + def command(*args, **kwargs): + self.assertEqual(args[0], 'systemctl') + self.assertTrue(all(name in ('dc-overview-release-refresh.service', + 'dc-overview-release-refresh.timer') for name in args[2:] if not name.startswith('-'))) + calls.append(args) + if args[1] == 'is-active': + return SimpleNamespace(returncode=0 if fault == 'still-active' else 3, + stdout=b'active\n' if fault == 'still-active' else b'inactive\n', stderr=b'') + if args[1] == 'is-enabled': return SimpleNamespace(returncode=1, stdout=b'disabled\n', stderr=b'') + self.assertIn(args[1], ('disable', 'stop')) + return SimpleNamespace(returncode=0, stdout=b'', stderr=b'') + with patch.object(module, 'POLICY_REFRESH_SYSTEMD', root), \ + patch.object(module.os, 'lstat', side_effect=lambda *a, **kw: native_root_info(actual_lstat(*a, **kw))), \ + patch.object(module.os, 'fstat', side_effect=lambda *a, **kw: native_root_info(actual_fstat(*a, **kw))), \ + patch.object(module, 'run', side_effect=command): + if fault: + with self.assertRaises((AssertionError, RuntimeError, ValueError)): + qa.policy_timer_quiesce() + if fault != 'still-active': + self.assertEqual(calls, [], 'unproven files cannot authorize even a fixed unit effect') + else: + self.assertIn(('systemctl', 'disable', '--now', 'dc-overview-release-refresh.timer'), calls) + else: + qa.policy_timer_quiesce() + self.assertIn(('systemctl', 'disable', '--now', 'dc-overview-release-refresh.timer'), calls) + self.assertIn(('systemctl', 'stop', 'dc-overview-release-refresh.service'), calls) + + def test_native_policy_race_refuses_uncertain_or_non_cas_results_without_retry(self): + module = self.native_module() + self.assertTrue(hasattr(module.NativeQA, 'policy_cas_race')) + import threading + for outcome in ('both-success', 'both-conflict', 'transport'): + with self.subTest(outcome=outcome): + clients = []; lock = threading.Lock() + class Client: + def __init__(client): + client.cookies = {}; client.verify = None; client.calls = 0; client.closed = False + with lock: clients.append(client) + def get(client, *args, **kwargs): + return SimpleNamespace(status_code=200, json=lambda: {'csrf_token': 'PRIVATE'}) + def post(client, url, **kwargs): return client.request('POST', url, **kwargs) + def request(client, *args, **kwargs): + client.calls += 1 + if outcome == 'transport': raise RuntimeError('PRIVATE-TRANSPORT') + return SimpleNamespace(status_code=200 if outcome == 'both-success' else 409, + json=lambda: {}) + def close(client): client.closed = True + qa = module.NativeQA.__new__(module.NativeQA) + qa.session = SimpleNamespace(cookies={'session': 'PRIVATE'}, verify='/fixture-ca') + qa.record = unittest.mock.Mock() + with patch.dict(sys.modules, {'requests': SimpleNamespace(Session=Client)}): + with self.assertRaises((AssertionError, RuntimeError, ValueError)): + qa.policy_cas_race({'selection_id': 'before', 'selection_sha256': 'a' * 64}) + self.assertEqual(len(clients), 2) + self.assertTrue(all(client.calls <= 1 and client.closed for client in clients)) + self.assertNotIn('PRIVATE', repr(qa.record.call_args_list)) + + def test_native_policy_full_procedure_requires_real_actions_and_preserves_runtime_scope(self): + module = self.native_module() + self.assertTrue(hasattr(module.NativeQA, 'policy_before_update') and + hasattr(module.NativeQA, 'policy_after_update'), + 'native control procedures must be executable, not empty proof labels') + import copy + for winner, fault in (('pin', None), ('refresh', None), + ('refresh', 'runtime-change'), ('pin', 'unrelated-change')): + with self.subTest(winner=winner, fault=fault): + qa = module.NativeQA.__new__(module.NativeQA) + qa.layout = 'named-volume' + qa.refs = {'ipmi-old': module.IPMI_OLD, 'ipmi-new': module.IPMI_NEW} + state = {'serial': 0, 'mode': 'pinned', 'installed': '1.3.1', 'selected': '1.3.2', + 'runtime': {'ipmi-monitor': 'original-ipmi', 'cryptolabs-proxy': 'original-proxy'}, + 'unrelated': {'grafana': 'original-pin', 'vast-price-manager': 'external-owner'}} + events = [] + def listing(): + return {'selection_id': 's-' + str(state['serial']), + 'selection_sha256': hashlib.sha256(str(state['serial']).encode()).hexdigest(), + 'components': {'ipmi-monitor': {'supported': True, 'mode': state['mode'], + 'major': 1 if state['mode'] == 'follow-stable' else None, + 'installed_release': state['installed'], 'selected_release': state['selected']}}} + def snapshot(): + return copy.deepcopy({'selection': listing()['selection_sha256'], 'policy': state['mode'], + 'runtime': state['runtime'], 'unrelated': state['unrelated']}) + def http(method, path, *, body=None, **kwargs): + if method == 'GET': + self.assertEqual(path, '/api/releases/policies') + return SimpleNamespace(status_code=200, json=listing) + self.assertEqual((method, path), ('POST', '/api/releases/policy-set')) + current = listing() + self.assertEqual(body['expected_selection_id'], current['selection_id']) + self.assertEqual(body['expected_selection_sha256'], current['selection_sha256']) + self.assertEqual(set(body), {'component', 'mode', 'expected_selection_id', 'expected_selection_sha256'}) + self.assertEqual(body['component'], 'ipmi-monitor') + state['mode'] = body['mode']; state['serial'] += 1 + if body['mode'] == 'pinned': state['selected'] = state['installed'] + if fault == 'unrelated-change': state['unrelated']['grafana'] = 'changed-pin' + events.append(('mode', body['mode'])) + value = listing() + return SimpleNamespace(status_code=200, json=lambda: value) + def race(current): + self.assertEqual(current['selection_id'], listing()['selection_id']) + self.assertEqual((state['mode'], state['selected']), ('follow-stable', '1.3.1')) + state['serial'] += 1 + if winner == 'refresh': state['selected'] = '1.3.3' + else: state.update(mode='pinned', selected='1.3.1') + events.append(('race', winner)); return winner + def timer_prepare(): + self.assertEqual(state['mode'], 'pinned', 'Persistent catch-up must run while pinned') + unchanged = snapshot() + # A catch-up refresh while pinned cannot advance selection. + self.assertEqual(snapshot(), unchanged) + events.append(('timer', 'prepared-and-quiesced')) + def timer_refresh(): + if state['mode'] == 'follow-stable': + state.update(selected='1.3.3', serial=state['serial'] + 1) + if fault == 'runtime-change': state['runtime']['ipmi-monitor'] = 'unexpected-restart' + events.append(('timer', 'refresh')) + qa.http = http; qa.policy_listing = listing; qa.policy_state_snapshot = snapshot + qa.policy_installed_version = unittest.mock.Mock(side_effect=lambda key: state['installed']) + qa.policy_discovery_refusals = unittest.mock.Mock() + qa.policy_lock_refusal = unittest.mock.Mock() + qa.policy_cas_race = unittest.mock.Mock(side_effect=race) + qa.policy_timer_prepare = unittest.mock.Mock(side_effect=timer_prepare) + qa.policy_timer_refresh = unittest.mock.Mock(side_effect=timer_refresh) + qa.record = unittest.mock.Mock() + def command(*args, **kwargs): + self.assertEqual(args, ('systemctl', 'restart', module.SERVICE)) + events.append(('broker', 'restart')) + return SimpleNamespace(returncode=0, stdout=b'', stderr=b'') + with patch.object(module, 'run', side_effect=command): + if fault: + with self.assertRaises((AssertionError, RuntimeError, ValueError)): + qa.policy_before_update() + else: + qa.policy_before_update() + self.assertEqual((state['mode'], state['selected'], state['installed']), + ('follow-stable', '1.3.3', '1.3.1')) + qa.policy_discovery_refusals.assert_called_once() + qa.policy_lock_refusal.assert_called_once() + qa.policy_cas_race.assert_called_once() + qa.policy_timer_prepare.assert_called_once() + self.assertIn(('broker', 'restart'), events) + self.assertEqual(state['runtime']['ipmi-monitor'], 'original-ipmi') + self.assertEqual(state['unrelated']['grafana'], 'original-pin') + # The original native manual flow, outside these policy + # procedures, is the sole operation that changes runtime. + state['installed'] = '1.3.3' + state['runtime']['ipmi-monitor'] = 'manually-updated-ipmi' + qa.policy_after_update() + self.assertEqual((state['mode'], state['selected']), ('pinned', '1.3.3')) + self.assertEqual(state['runtime']['ipmi-monitor'], 'manually-updated-ipmi') + self.assertEqual(state['runtime']['cryptolabs-proxy'], 'original-proxy') + self.assertEqual(state['unrelated']['grafana'], 'original-pin') + self.assertEqual(qa.policy_timer_refresh.call_count, 2) + self.assertEqual(qa.policy_installed_version.call_args_list, + [unittest.mock.call('ipmi-old'), unittest.mock.call('ipmi-new')]) + + def test_native_policy_timer_prepare_runs_packaged_cli_pinned_then_quiesces_owned_units(self): + module = self.native_module() + self.assertTrue(hasattr(module.NativeQA, 'policy_timer_prepare') and + hasattr(module, 'POLICY_REFRESH_SYSTEMD')) + import stat + with tempfile.TemporaryDirectory() as directory: + root = Path(directory); names = ('dc-overview-release-refresh.service', 'dc-overview-release-refresh.timer') + qa = module.NativeQA.__new__(module.NativeQA) + qa.args = SimpleNamespace(dc_source=ROOT) + qa.units = []; qa.record = unittest.mock.Mock() + qa.policy_listing = lambda: {'components': {'ipmi-monitor': {'mode': 'pinned'}}} + qa.policy_state_snapshot = lambda: {'policy': 'pinned', 'selection': 'old', 'runtime': 'unchanged'} + live = {'timer': False, 'service': False, 'installer_calls': 0} + calls = []; cli = str(Path(module.sys.executable).parent / 'dc-overview') + actual_lstat, actual_fstat = os.lstat, os.fstat + def root_metadata(info): + values = {name: getattr(info, name) for name in dir(info) if name.startswith('st_')} + values.update(st_uid=0, st_gid=0) + if stat.S_ISDIR(info.st_mode): values['st_mode'] = stat.S_IFDIR | 0o755 + return SimpleNamespace(**values) + def command(*args, **kwargs): + arguments = tuple(map(str, args)); calls.append(arguments) + if arguments == (cli, 'release', 'policy-install-timer'): + self.assertEqual(qa.policy_listing()['components']['ipmi-monitor']['mode'], 'pinned') + live['installer_calls'] += 1 + for name in names: + raw = (ROOT / 'src/dc_overview/templates/systemd' / name).read_text() + path = root / name; path.write_text(raw.replace('@RELEASE_CLI@', cli)); path.chmod(0o600) + # Model systemd's Persistent catch-up on enable. It happens + # before FOLLOW, so the pinned selection remains untouched. + live['timer'] = True + elif arguments[:2] == ('systemctl', 'show'): + return SimpleNamespace(returncode=0, stderr=b'', stdout=( + b'ActiveState=active\nUnitFileState=enabled\nPersistent=yes\n' + b'NextElapseUSecRealtime=Sat 2026-11-07 00:05:00 UTC\n')) + elif arguments == ('systemctl', 'disable', '--now', names[1]): live['timer'] = False + elif arguments == ('systemctl', 'stop', names[0]): live['service'] = False + elif arguments[:2] == ('systemctl', 'is-active'): + active = live['timer'] if arguments[2] == names[1] else live['service'] + return SimpleNamespace(returncode=0 if active else 3, + stdout=b'active\n' if active else b'inactive\n', stderr=b'') + elif arguments[:2] == ('systemctl', 'is-enabled'): + return SimpleNamespace(returncode=0 if live['timer'] else 1, + stdout=b'enabled\n' if live['timer'] else b'disabled\n', stderr=b'') + elif arguments[:2] == ('systemd-analyze', 'verify'): + self.assertEqual(set(arguments[2:]), {str(root / name) for name in names}) + else: self.fail('unreviewed timer command: ' + repr(arguments)) + return SimpleNamespace(returncode=0, stdout=b'', stderr=b'') + with patch.object(module, 'POLICY_REFRESH_SYSTEMD', root), \ + patch.object(module.os, 'lstat', side_effect=lambda *a, **kw: root_metadata(actual_lstat(*a, **kw))), \ + patch.object(module.os, 'fstat', side_effect=lambda *a, **kw: root_metadata(actual_fstat(*a, **kw))), \ + patch.object(module, 'run', side_effect=command): + qa.policy_timer_prepare() + self.assertEqual(live['installer_calls'], 1) + self.assertFalse(live['timer']); self.assertFalse(live['service']) + self.assertTrue(qa.policy_timer_attempted) + self.assertEqual(set(qa.policy_timer_record['files']), {str(root / name) for name in names}) + self.assertTrue({root / name for name in names} <= set(qa.units)) + for name in names: + path = root / name; info = path.lstat(); recorded = qa.policy_timer_record['files'][str(path)] + self.assertEqual(recorded, {'sha256': module.digest(path.read_bytes()), + 'device': info.st_dev, 'inode': info.st_ino}) + self.assertIn(('systemctl', 'disable', '--now', names[1]), calls) + + def test_native_policy_timer_refresh_executes_fixed_oneshot_without_http_or_retry(self): + module = self.native_module() + self.assertTrue(hasattr(module.NativeQA, 'policy_timer_refresh'), + 'headless proof must execute the real packaged service') + unit = 'dc-overview-release-refresh.service' + for fault in (None, 'enabled', 'active', 'unknown', 'start-failure', + 'result-failure', 'missing-status', 'still-active'): + with self.subTest(fault=fault): + qa = module.NativeQA.__new__(module.NativeQA) + qa.record = unittest.mock.Mock() + qa.http = unittest.mock.Mock(side_effect=AssertionError('HTTP substitution forbidden')) + qa.policy_listing = unittest.mock.Mock(side_effect=AssertionError('HTTP listing forbidden here')) + calls = [] + def quiesce(): + calls.append(('quiesce',)) + if fault in ('enabled', 'active', 'unknown'): + raise RuntimeError('PRIVATE-UNCERTAIN-UNIT') + qa.policy_timer_quiesce = unittest.mock.Mock(side_effect=quiesce) + def command(*args, **kwargs): + calls.append(args) + if args == ('systemctl', 'start', unit): + if fault == 'start-failure': raise RuntimeError('PRIVATE-START-FAILURE') + return SimpleNamespace(returncode=0, stdout=b'', stderr=b'') + self.assertEqual(args[:3], ('systemctl', 'show', unit)) + fields = {'Id': unit, 'ActiveState': 'inactive', 'SubState': 'dead', + 'MainPID': '0', 'Result': 'success', 'ExecMainStatus': '0'} + if fault == 'result-failure': fields.update(Result='exit-code', ExecMainStatus='1') + if fault == 'missing-status': del fields['ExecMainStatus'] + if fault == 'still-active': fields.update(ActiveState='active', SubState='running', MainPID='123') + return SimpleNamespace(returncode=0, stderr=b'', + stdout=('\n'.join(name + '=' + value for name, value in fields.items()) + '\n').encode()) + with patch.object(module, 'run', side_effect=command): + if fault: + with self.assertRaises((AssertionError, RuntimeError, ValueError)): + qa.policy_timer_refresh() + else: + qa.policy_timer_refresh() + self.assertEqual(calls[0], ('quiesce',)) + qa.policy_timer_quiesce.assert_called_once() + starts = [call for call in calls if call[:2] == ('systemctl', 'start')] + self.assertEqual(len(starts), 0 if fault in ('enabled', 'active', 'unknown') else 1) + qa.http.assert_not_called(); qa.policy_listing.assert_not_called() + self.assertNotIn('PRIVATE', repr(qa.record.call_args_list)) + + def test_native_policy_snapshot_is_sensitive_to_real_identity_and_pin_changes(self): + module = self.native_module() + self.assertTrue(hasattr(module.NativeQA, 'policy_state_snapshot'), + 'a constant projection cannot prove no restart or pin preservation') + import copy + with tempfile.TemporaryDirectory() as directory: + root = Path(directory); store_root = root / 'releases' + policy = store_root / 'broker/policy-state.json'; policy.parent.mkdir(parents=True) + policy.write_bytes(b'{"schema_version":1,"components":{}}\n'); policy.chmod(0o600) + current = SimpleNamespace(selection_sha256='a' * 64, + manifest=SimpleNamespace(data={'components': {'ipmi-monitor': {'release': '1.3.1'}, + 'grafana': {'release': 'pinned'}, 'vast-price-manager': {'release': 'external'}}}), + selection={'components': {'ipmi-monitor': {'origin': 'baseline'}, + 'grafana': {'origin': 'customer-pin', 'pin': 'g' * 64}, + 'vast-price-manager': {'origin': 'unmanaged'}}}) + records = {} + for number, name, running in ((1, 'ipmi-monitor', True), (2, 'cryptolabs-proxy', True), + (3, 'native-fleet-registry', True), (4, 'owned-initializer', False)): + identity = str(number) * 64 + records[identity] = {'Id': identity, 'Name': '/' + name, + 'Image': 'sha256:' + str(number + 4) * 64, + 'State': {'Running': running, 'StartedAt': '2026-11-06T00:00:00Z'}, + 'Config': {'Env': ['PRIVATE=must-not-be-projected']}} + qa = module.NativeQA.__new__(module.NativeQA) + qa.store = SimpleNamespace(root=store_root) + qa.selection = lambda: current + inventory = list(records) + def engine(*args, **kwargs): + self.assertEqual(args, ('ps', '-aq', '--no-trunc')) + return SimpleNamespace(returncode=0, stdout=('\n'.join(inventory) + '\n').encode(), stderr=b'') + def inspecting(identity, **kwargs): + self.assertIn(identity, records) + return copy.deepcopy(records[identity]) + with patch.object(module, 'CONFIG', root), patch.object(module, 'docker', side_effect=engine), \ + patch.object(module, 'inspect', side_effect=inspecting) as read: + baseline = qa.policy_state_snapshot() + self.assertEqual(set(baseline), {'selection', 'policy', 'runtime', 'unrelated'}) + self.assertEqual(baseline, qa.policy_state_snapshot()) + self.assertEqual(len(baseline['runtime']), 4, 'include registry and stopped fixture objects') + self.assertNotIn('PRIVATE', json.dumps(baseline)) + for number, field, changed in ((1, 'Id', '9' * 64), (1, 'Image', 'sha256:' + 'f' * 64), + (1, 'StartedAt', '2026-11-06T00:01:00Z'), (1, 'Running', False), + (2, 'Id', '8' * 64), (3, 'Id', '7' * 64)): + identity = str(number) * 64; original = copy.deepcopy(records[identity]) + if field in ('StartedAt', 'Running'): records[identity]['State'][field] = changed + else: records[identity][field] = changed + try: + # A mismatched inspected ID may be refused instead of + # yielding a snapshot; it must never equal the baseline. + try: observed = qa.policy_state_snapshot() + except (AssertionError, RuntimeError, ValueError): observed = None + self.assertNotEqual(observed, baseline) + finally: records[identity] = original + for mapping, name, value in ((current.manifest.data['components']['grafana'], 'release', 'changed'), + (current.selection['components']['grafana'], 'pin', 'changed')): + old = mapping[name]; mapping[name] = value + self.assertNotEqual(qa.policy_state_snapshot(), baseline); mapping[name] = old + current.selection_sha256 = 'b' * 64 + self.assertNotEqual(qa.policy_state_snapshot(), baseline) + current.selection_sha256 = 'a' * 64 + original_component = copy.deepcopy(current.manifest.data['components']['ipmi-monitor']) + current.manifest.data['components']['ipmi-monitor']['release'] = '1.3.3' + self.assertEqual(qa.policy_state_snapshot()['unrelated'], baseline['unrelated']) + current.manifest.data['components']['ipmi-monitor'] = original_component + policy.write_bytes(b'{"schema_version":1,"components":{"ipmi-monitor":{"mode":"follow-stable","major":1}}}\n') + self.assertNotEqual(qa.policy_state_snapshot(), baseline) + policy.unlink() + self.assertNotEqual(qa.policy_state_snapshot(), baseline) + self.assertNotIn('PRIVATE', json.dumps(baseline), 'retained snapshots must be detached from later state') + read.reset_mock(); inventory[:] = ['f' * 64] * 65 + with self.assertRaises((AssertionError, RuntimeError, ValueError)): + qa.policy_state_snapshot() + read.assert_not_called() + for invalid in (['not-an-id'], ['1' * 64, '1' * 64]): + inventory[:] = invalid; read.reset_mock() + with self.assertRaises((AssertionError, RuntimeError, ValueError)): + qa.policy_state_snapshot() + read.assert_not_called() + + + def test_native_policy_cleanup_preserves_unproven_timer_files_and_continues_independent_cleanup(self): + module = self.native_module() + import stat + for fault in (None, 'changed-bytes', 'changed-inode', 'unknown-record'): + with self.subTest(fault=fault), tempfile.TemporaryDirectory() as directory: + root = Path(directory); systemd = root / 'systemd'; systemd.mkdir() + work = root / 'work'; work.mkdir() + paths = [systemd / ('dc-overview-release-refresh.' + suffix) for suffix in ('service', 'timer')] + files = {} + for path in paths: + path.write_bytes(('owned ' + path.name).encode()); path.chmod(0o600) + info = path.lstat() + files[str(path)] = {'sha256': module.digest(path.read_bytes()), + 'device': info.st_dev, 'inode': info.st_ino} + if fault == 'changed-bytes': paths[0].write_bytes(b'replaced unproven service') + if fault == 'changed-inode': files[str(paths[0])]['inode'] += 1 + retained = {path: path.read_bytes() for path in paths} + broker = systemd / module.SERVICE; broker.write_bytes(b'independently owned broker') + qa = module.NativeQA.__new__(module.NativeQA) + qa.units = [broker, *paths] + qa.label = 'io.cryptolabs.native-qa=fixture' + qa.hosts = None; qa.registry_ca_file = None + qa.policy_timer_attempted = True; qa.policy_timer_quiesced = False + qa.policy_timer_record = None if fault == 'unknown-record' else {'files': files} + qa.reset_fixture = lambda: qa.policy_timer_quiesce() + qa.restore_registry_trust = unittest.mock.Mock() + qa.remove_registry_ca = unittest.mock.Mock() + qa.record = unittest.mock.Mock() + actual_lstat, actual_fstat = os.lstat, os.fstat + def root_metadata(info): + # Offline owner/directory-mode projection; real file bytes, + # device/inode and replacement/refusal observations remain. + values = {name: getattr(info, name) for name in dir(info) if name.startswith('st_')} + values.update(st_uid=0, st_gid=0) + if stat.S_ISDIR(info.st_mode): values['st_mode'] = stat.S_IFDIR | 0o755 + return SimpleNamespace(**values) + commands = [] + def command(*args, **kwargs): + commands.append(args) + self.assertEqual(args[0], 'systemctl') + if args[1] == 'is-active': return SimpleNamespace(returncode=3, stdout=b'inactive\n', stderr=b'') + if args[1] == 'is-enabled': return SimpleNamespace(returncode=1, stdout=b'disabled\n', stderr=b'') + self.assertIn(args[1], ('disable', 'stop', 'daemon-reload')) + return SimpleNamespace(returncode=0, stdout=b'', stderr=b'') + def engine(*args, **kwargs): + self.assertIn(args, (('ps', '-aq', '--filter', 'name=^/native-fleet-registry$'), + ('ps', '-aq', '--filter', 'label=' + qa.label))) + return SimpleNamespace(returncode=0, stdout=b'', stderr=b'') + def fixture_path(*args): + value = Path(*args) + return root / 'absent-cli-link' if str(value) == '/usr/local/bin/dc-overview' else value + with patch.object(module, 'ROOT', work), patch.object(module, 'POLICY_REFRESH_SYSTEMD', systemd), \ + patch.object(module, 'Path', side_effect=fixture_path), \ + patch.object(module.os, 'lstat', side_effect=lambda *a, **kw: root_metadata(actual_lstat(*a, **kw))), \ + patch.object(module.os, 'fstat', side_effect=lambda *a, **kw: root_metadata(actual_fstat(*a, **kw))), \ + patch.object(module, 'run', side_effect=command), patch.object(module, 'docker', side_effect=engine): + if fault: + with self.assertRaises(RuntimeError): qa.cleanup() + else: + qa.cleanup() + self.assertFalse(broker.exists(), 'independent original cleanup must continue') + if fault: + for path, content in retained.items(): + self.assertTrue(path.exists(), 'custody refusal must retain the unproven unit') + self.assertEqual(path.read_bytes(), content) + self.assertFalse(qa.policy_timer_quiesced) + qa.restore_registry_trust.assert_not_called() + self.assertFalse(any(call[1] in ('disable', 'stop') for call in commands)) + else: + self.assertTrue(all(not path.exists() for path in paths)) + qa.restore_registry_trust.assert_called_once() + + if __name__ == "__main__": unittest.main() diff --git a/.github/workflows/fleet-release-native-qa.yml b/.github/workflows/fleet-release-native-qa.yml index e12f97a..245323c 100644 --- a/.github/workflows/fleet-release-native-qa.yml +++ b/.github/workflows/fleet-release-native-qa.yml @@ -6,7 +6,7 @@ name: Fleet release native verification permissions: contents: read env: - PROXY_SOURCE_SHA: 5db15086c26095179f2af56bfa434c85426a6699 + PROXY_SOURCE_SHA: 6e5186401e78cc8ba7b6ffe18eb24712ef9263b1 jobs: native: if: >- @@ -48,6 +48,18 @@ jobs: mkdir -p "$RUNNER_TEMP/fleet-native-wheels" "$RUNNER_TEMP/fleet-native-evidence" python -m build dc --wheel --outdir "$RUNNER_TEMP/fleet-native-wheels" python -m build proxy --wheel --outdir "$RUNNER_TEMP/fleet-native-wheels" + mkdir -p "$RUNNER_TEMP/fleet-native-legacy-wheels" + curl --disable --fail --silent --show-error --location --connect-timeout 10 --max-time 120 --proto '=https' --proto-redir '=https' --tlsv1.2 \ + 'https://github.com/cryptolabsza/dc-overview/releases/download/v1.8.0/dc_overview-1.8.0-py3-none-any.whl' \ + --output "$RUNNER_TEMP/fleet-native-legacy-wheels/dc_overview-1.8.0-py3-none-any.whl" + curl --disable --fail --silent --show-error --location --connect-timeout 10 --max-time 120 --proto '=https' --proto-redir '=https' --tlsv1.2 \ + 'https://github.com/cryptolabsza/cryptolabs-proxy/releases/download/v1.5.4/cryptolabs_proxy-1.5.4-py3-none-any.whl' \ + --output "$RUNNER_TEMP/fleet-native-legacy-wheels/cryptolabs_proxy-1.5.4-py3-none-any.whl" + (cd "$RUNNER_TEMP/fleet-native-legacy-wheels" && sha256sum --check <<'LEGACY_SHA256' + 72fcf2fde1d765cdfebfd2e4071261e3ff28d202f7ffb1975340e9d362969304 dc_overview-1.8.0-py3-none-any.whl + 5e64f0ae59d38ebcf4885d8aa60822bc3187d5a63f9abb8bdd11927d1ffd2b47 cryptolabs_proxy-1.5.4-py3-none-any.whl + LEGACY_SHA256 + ) sudo -n install -d -m 0755 -o "$(id -u)" -g "$(id -g)" /opt/fleet-native-qa python -m venv /opt/fleet-native-qa/venv /opt/fleet-native-qa/venv/bin/pip install "$RUNNER_TEMP"/fleet-native-wheels/*.whl @@ -64,6 +76,8 @@ jobs: --dc-source "$GITHUB_WORKSPACE/dc" --dc-sha "$DC_SOURCE_SHA" \ --proxy-source "$GITHUB_WORKSPACE/proxy" --proxy-sha "$PROXY_SOURCE_SHA" \ --wheel-dir "$RUNNER_TEMP/fleet-native-wheels" \ + --legacy-wheel-dir "$RUNNER_TEMP/fleet-native-legacy-wheels" \ + --protection-helper "$GITHUB_WORKSPACE/dc/scripts/fixtures/legacy-selected-state-protection.py" \ --evidence-dir "$RUNNER_TEMP/fleet-native-evidence" env: DC_SOURCE_SHA: ${{ github.event.pull_request.head.sha }} diff --git a/.traceweaver/auto-advance-20261104/anchors-final.md b/.traceweaver/auto-advance-20261104/anchors-final.md new file mode 100644 index 0000000..0a6ac2a --- /dev/null +++ b/.traceweaver/auto-advance-20261104/anchors-final.md @@ -0,0 +1,2 @@ +# Code Traceability Findings + diff --git a/.traceweaver/auto-advance-20261104/authority-gate.json b/.traceweaver/auto-advance-20261104/authority-gate.json new file mode 100644 index 0000000..bbbc0fd --- /dev/null +++ b/.traceweaver/auto-advance-20261104/authority-gate.json @@ -0,0 +1,11 @@ +{ + "decision": "Proceed", + "scope": "exactapprovedplanC1-C8andnamedfiles;noinferrednewrequirements", + "authority": "authority.json andowner-approval.json", + "profile": "profile.json/frozenbeforeproductionmutations", + "vv": "vv-capsule.json/review-definition.json", + "baseline_hash": "94b783d925834004cd3f111dd2437f8ae531850f0184aaa29c52f89f84267795", + "must_not_change": "otherroles/modes/pins/runtimes/accounts/data;existingtrustandlifecycleguardcontracts;installationmanual", + "publication": "separatecontrolledrouteaftercleanreview/verification", + "runtime_acceptance": "helduntilactualnative/browser/publisher/bridgeevidence" +} diff --git a/.traceweaver/auto-advance-20261104/authority.json b/.traceweaver/auto-advance-20261104/authority.json new file mode 100644 index 0000000..2acb99a --- /dev/null +++ b/.traceweaver/auto-advance-20261104/authority.json @@ -0,0 +1,19 @@ +{ + "mode": "approved implementation and controlled publication/LTX activation", + "baseline_id": "AUTOADVANCE-20261104", + "approved_plan_sha256": "94b783d925834004cd3f111dd2437f8ae531850f0184aaa29c52f89f84267795", + "owner_record": "owner-approval.json", + "ids_are_administrative_mappings": true, + "requirements": { + "REQ-AUTOADVANCE-001": "exact approved plan C1", + "REQ-AUTOADVANCE-002": "exact approved plan C2", + "REQ-AUTOADVANCE-003": "exact approved plan C3", + "REQ-AUTOADVANCE-004": "exact approved plan C4", + "REQ-AUTOADVANCE-005": "exact approved plan C5", + "REQ-AUTOADVANCE-006": "exact approved plan C6", + "REQ-AUTOADVANCE-007": "exact approved plan C7", + "REQ-AUTOADVANCE-008": "exact approved plan C8" + }, + "must_preserve": "allother service modes,pins,data,accounts,lifecycleowner/trustcontracts;manualinstallation;no prerelease/majorautoadvance", + "existing_Fleet_dependency": "native/publisher acceptance still required beforeactivation" +} diff --git a/.traceweaver/auto-advance-20261104/browser-verification.json b/.traceweaver/auto-advance-20261104/browser-verification.json new file mode 100644 index 0000000..9eb8d35 --- /dev/null +++ b/.traceweaver/auto-advance-20261104/browser-verification.json @@ -0,0 +1,16 @@ +{ + "scope": "real Chrome on actual candidate page; synthetic API fixture; no LTX operation", + "result": "passed", + "steps": [ + "default pinned", + "select Follow stable", + "Check Updates selects synthetic1.4.1 without changing installed1.4.0", + "reload retains mode and pending target", + "repin returns installed1.4.0", + "next check stays pinned" + ], + "requests": 4, + "install_requests": 0, + "pending_screenshot": "follow-stable-pending.jpg", + "repin_screenshot": "repinned.jpg" +} diff --git a/.traceweaver/auto-advance-20261104/final-anchors-policy-tests.log b/.traceweaver/auto-advance-20261104/final-anchors-policy-tests.log new file mode 100644 index 0000000..6b2a273 --- /dev/null +++ b/.traceweaver/auto-advance-20261104/final-anchors-policy-tests.log @@ -0,0 +1,3 @@ +........................................................................ [ 79%] +................... [100%] +91 passed in 3.63s diff --git a/.traceweaver/auto-advance-20261104/full-tests-final.log b/.traceweaver/auto-advance-20261104/full-tests-final.log new file mode 100644 index 0000000..4732215 --- /dev/null +++ b/.traceweaver/auto-advance-20261104/full-tests-final.log @@ -0,0 +1,175 @@ +........................................................................ [ 3%] +........................................................................ [ 6%] +........................................................................ [ 10%] +........................................................................ [ 13%] +........................................................................ [ 16%] +........................................................................ [ 20%] +........................................................................ [ 23%] +........................................................................ [ 27%] +........................................................................ [ 30%] +........................................................................ [ 33%] +........................................................................ [ 37%] +........................................................................ [ 40%] +........................................................................ [ 44%] +........................................................................ [ 47%] +........................................................................ [ 50%] +........................................................................ [ 54%] +........................................................................ [ 57%] +........................................................................ [ 61%] +........................................................................ [ 64%] +........................................................................ [ 67%] +........................................................................ [ 71%] +........................................................................ [ 74%] +........................................................................ [ 78%] +........................................................................ [ 81%] +........................................................................ [ 84%] +........................................................................ [ 88%] +........................................................................ [ 91%] +........................................................................ [ 95%] +........................................................................ [ 98%] +................................. [100%] +=============================== warnings summary =============================== +tests/test_credential_propagation.py: 64 warnings +tests/test_dc_lifecycle_review_repairs.py: 4 warnings +tests/test_exporter_install_ui.py: 72 warnings +tests/test_exporter_toggle.py: 6 warnings +tests/test_http_inventory.py: 23 warnings +tests/test_inventory_sync.py: 154 warnings +tests/test_ipmi_sync.py: 2 warnings +tests/test_operational_customer_contract.py: 20 warnings +tests/test_prometheus_sync.py: 2 warnings +tests/test_selected_completion_versions.py: 21 warnings +tests/test_selected_ssh_identity_authority.py: 6 warnings +tests/test_selected_worker_enrollment.py: 30 warnings +tests/test_selected_worker_enrollment_review_repairs.py: 48 warnings +tests/test_server_delete.py: 4 warnings +tests/test_servers_inventory_ui.py: 7 warnings +tests/test_ssh_key_management.py: 18 warnings + /private/tmp/ltx-auto-advance-20261104/venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py:4362: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC). + return util.wrap_callable(lambda ctx: fn(), fn) # type: ignore[call-arg, no-any-return, no-untyped-call] # noqa: E501 + +tests/test_credential_propagation.py: 13 warnings +tests/test_exporter_install_ui.py: 8 warnings +tests/test_exporter_toggle.py: 3 warnings +tests/test_http_inventory.py: 3 warnings +tests/test_inventory_sync.py: 14 warnings +tests/test_operational_customer_contract.py: 1 warning +tests/test_selected_completion_versions.py: 10 warnings +tests/test_selected_ssh_identity_authority.py: 4 warnings +tests/test_selected_worker_enrollment.py: 76 warnings +tests/test_selected_worker_enrollment_review_repairs.py: 39 warnings +tests/test_server_delete.py: 2 warnings +tests/test_servers_inventory_ui.py: 2 warnings +tests/test_ssh_key_management.py: 7 warnings + /private/tmp/ltx-auto-advance-20261104/venv/lib/python3.12/site-packages/flask_sqlalchemy/query.py:30: LegacyAPIWarning: The Query.get() method is considered legacy as of the 1.x series of SQLAlchemy and becomes a legacy construct in 2.0. The method is now available as Session.get() (deprecated since: 2.0) (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9) + rv = self.get(ident) + +tests/test_credential_propagation.py::test_local_credential_save_queues_only_an_encrypted_bundle_and_requires_credential_ack +tests/test_selected_worker_enrollment_review_repairs.py::test_selected_completion_rejects_each_concurrent_identity_field_before_probe[ssh_key_id] + /private/tmp/ltx-auto-advance-20261104/dc-overview/src/dc_overview/app.py:2889: LegacyAPIWarning: The Query.get() method is considered legacy as of the 1.x series of SQLAlchemy and becomes a legacy construct in 2.0. The method is now available as Session.get() (deprecated since: 2.0) (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9) + if key_id and not SSHKey.query.get(key_id): + +tests/test_credential_propagation.py::test_local_credential_save_queues_only_an_encrypted_bundle_and_requires_credential_ack + /private/tmp/ltx-auto-advance-20261104/dc-overview/tests/test_credential_propagation.py:66: LegacyAPIWarning: The Query.get() method is considered legacy as of the 1.x series of SQLAlchemy and becomes a legacy construct in 2.0. The method is now available as Session.get() (deprecated since: 2.0) (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9) + assert Server.query.get(server_id).bmc_password != "bmc-secret" + +tests/test_credential_propagation.py::test_saved_bmc_username_with_blank_password_preserves_existing_secret_on_ssh_edit + /private/tmp/ltx-auto-advance-20261104/dc-overview/tests/test_credential_propagation.py:105: LegacyAPIWarning: The Query.get() method is considered legacy as of the 1.x series of SQLAlchemy and becomes a legacy construct in 2.0. The method is now available as Session.get() (deprecated since: 2.0) (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9) + ciphertext = Server.query.get(server_id).bmc_password + +tests/test_credential_propagation.py::test_saved_bmc_username_with_blank_password_preserves_existing_secret_on_ssh_edit + /private/tmp/ltx-auto-advance-20261104/dc-overview/tests/test_credential_propagation.py:111: LegacyAPIWarning: The Query.get() method is considered legacy as of the 1.x series of SQLAlchemy and becomes a legacy construct in 2.0. The method is now available as Session.get() (deprecated since: 2.0) (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9) + server = Server.query.get(server_id) + +tests/test_credential_propagation.py::test_vault_mode_blocks_credential_mutations_without_changing_local_state + /private/tmp/ltx-auto-advance-20261104/dc-overview/tests/test_credential_propagation.py:123: LegacyAPIWarning: The Query.get() method is considered legacy as of the 1.x series of SQLAlchemy and becomes a legacy construct in 2.0. The method is now available as Session.get() (deprecated since: 2.0) (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9) + with app.app_context(): assert Server.query.get(server_id).ssh_port == 22 + +tests/test_credential_propagation.py::test_invalid_bmc_input_and_missing_transport_key_do_not_mutate + /private/tmp/ltx-auto-advance-20261104/dc-overview/tests/test_credential_propagation.py:148: LegacyAPIWarning: The Query.get() method is considered legacy as of the 1.x series of SQLAlchemy and becomes a legacy construct in 2.0. The method is now available as Session.get() (deprecated since: 2.0) (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9) + server = Server.query.get(server_id) + +tests/test_exporter_install_ui.py: 6 warnings +tests/test_exporter_toggle.py: 1 warning +tests/test_operational_customer_contract.py: 3 warnings + /private/tmp/ltx-auto-advance-20261104/dc-overview/src/dc_overview/app.py:1710: LegacyAPIWarning: The Query.get() method is considered legacy as of the 1.x series of SQLAlchemy and becomes a legacy construct in 2.0. The method is now available as Session.get() (deprecated since: 2.0) (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9) + server = Server.query.get(server_id) + +tests/test_exporter_install_ui.py::TestLiveCheckInstalledState::test_failed_service_read_preserves_confirmed_installation +tests/test_exporter_install_ui.py::TestLiveCheckInstalledState::test_service_exists_but_stopped +tests/test_exporter_install_ui.py::TestLiveCheckInstalledState::test_service_active_and_port_open +tests/test_exporter_install_ui.py::TestLiveCheckInstalledState::test_no_services_skips_version_ssh +tests/test_exporter_install_ui.py::test_health_reads_preserve_monitoring_intent_and_discovery[True-False-live] +tests/test_exporter_install_ui.py::test_health_reads_preserve_monitoring_intent_and_discovery[False-True-live] + /private/tmp/ltx-auto-advance-20261104/dc-overview/src/dc_overview/app.py:1785: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC). + ts_val = datetime.utcnow().isoformat() + +tests/test_exporter_install_ui.py: 2 warnings +tests/test_selected_completion_versions.py: 3 warnings +tests/test_selected_worker_enrollment.py: 4 warnings +tests/test_selected_worker_enrollment_review_repairs.py: 3 warnings + /private/tmp/ltx-auto-advance-20261104/dc-overview/src/dc_overview/app.py:1444: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC). + ts_val = datetime.utcnow().isoformat() + +tests/test_exporter_install_ui.py::test_health_reads_preserve_monitoring_intent_and_discovery[True-False-watchdog-sync] +tests/test_exporter_install_ui.py::test_health_reads_preserve_monitoring_intent_and_discovery[False-True-watchdog-sync] + /private/tmp/ltx-auto-advance-20261104/dc-overview/src/dc_overview/app.py:2401: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC). + server.watchdog_agent_last_seen = datetime.utcnow() + +tests/test_exporter_install_ui.py: 1 warning +tests/test_selected_completion_versions.py: 5 warnings +tests/test_selected_worker_enrollment.py: 4 warnings +tests/test_selected_worker_enrollment_review_repairs.py: 3 warnings + /private/tmp/ltx-auto-advance-20261104/dc-overview/src/dc_overview/app.py:1404: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC). + server.last_seen = datetime.utcnow() + +tests/test_inventory_sync.py::test_delete_keeps_tombstone_outbox_when_receiver_is_unavailable + /private/tmp/ltx-auto-advance-20261104/dc-overview/tests/test_inventory_sync.py:103: LegacyAPIWarning: The Query.get() method is considered legacy as of the 1.x series of SQLAlchemy and becomes a legacy construct in 2.0. The method is now available as Session.get() (deprecated since: 2.0) (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9) + assert Server.query.get(server_id) is None + +tests/test_inventory_sync.py::test_existing_server_mapping_update_and_pending_outbox_are_visible_and_retryable + /private/tmp/ltx-auto-advance-20261104/dc-overview/tests/test_inventory_sync.py:149: LegacyAPIWarning: The Query.get() method is considered legacy as of the 1.x series of SQLAlchemy and becomes a legacy construct in 2.0. The method is now available as Session.get() (deprecated since: 2.0) (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9) + server = Server.query.get(server_id) + +tests/test_inventory_sync.py::test_readding_then_mapping_a_retired_bmc_restores_its_identity + /private/tmp/ltx-auto-advance-20261104/dc-overview/tests/test_inventory_sync.py:181: LegacyAPIWarning: The Query.get() method is considered legacy as of the 1.x series of SQLAlchemy and becomes a legacy construct in 2.0. The method is now available as Session.get() (deprecated since: 2.0) (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9) + identity = Server.query.get(original_id).inventory_server_id + +tests/test_inventory_sync.py::test_readding_then_mapping_a_retired_bmc_restores_its_identity + /private/tmp/ltx-auto-advance-20261104/dc-overview/tests/test_inventory_sync.py:191: LegacyAPIWarning: The Query.get() method is considered legacy as of the 1.x series of SQLAlchemy and becomes a legacy construct in 2.0. The method is now available as Session.get() (deprecated since: 2.0) (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9) + restored = Server.query.get(recreated.get_json()['id']) + +tests/test_inventory_sync.py::test_rebinding_the_same_current_bmc_keeps_its_identity_and_advances_revision + /private/tmp/ltx-auto-advance-20261104/dc-overview/tests/test_inventory_sync.py:217: LegacyAPIWarning: The Query.get() method is considered legacy as of the 1.x series of SQLAlchemy and becomes a legacy construct in 2.0. The method is now available as Session.get() (deprecated since: 2.0) (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9) + identity = Server.query.get(server_id).inventory_server_id + +tests/test_inventory_sync.py::test_rebinding_the_same_current_bmc_keeps_its_identity_and_advances_revision + /private/tmp/ltx-auto-advance-20261104/dc-overview/tests/test_inventory_sync.py:221: LegacyAPIWarning: The Query.get() method is considered legacy as of the 1.x series of SQLAlchemy and becomes a legacy construct in 2.0. The method is now available as Session.get() (deprecated since: 2.0) (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9) + current = Server.query.get(server_id) + +tests/test_selected_worker_enrollment.py::test_real_api_registration_lost_response_reuses_committed_identity + /private/tmp/ltx-auto-advance-20261104/dc-overview/tests/test_selected_worker_enrollment.py:272: LegacyAPIWarning: The Query.get() method is considered legacy as of the 1.x series of SQLAlchemy and becomes a legacy construct in 2.0. The method is now available as Session.get() (deprecated since: 2.0) (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9) + with app.app_context():assert InventoryServer.query.get(registered['id']).inventory_server_id==identity + +tests/test_selected_worker_enrollment.py::test_real_cli_parser_api_preflight_install_repeat_and_partial_resume + /private/tmp/ltx-auto-advance-20261104/dc-overview/tests/test_selected_worker_enrollment.py:389: LegacyAPIWarning: The Query.get() method is considered legacy as of the 1.x series of SQLAlchemy and becomes a legacy construct in 2.0. The method is now available as Session.get() (deprecated since: 2.0) (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9) + with app.app_context():assert InventoryServer.query.get(saved_id).inventory_server_id==saved_identity + +tests/test_selected_worker_enrollment.py::test_real_api_repeat_preserves_pending_outbox_and_credentials + /private/tmp/ltx-auto-advance-20261104/dc-overview/tests/test_selected_worker_enrollment.py:467: LegacyAPIWarning: The Query.get() method is considered legacy as of the 1.x series of SQLAlchemy and becomes a legacy construct in 2.0. The method is now available as Session.get() (deprecated since: 2.0) (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9) + row=InventoryServer.query.get(created.get_json()['id']);identity=row.inventory_server_id + +tests/test_server_delete.py::TestServerDelete::test_delete_server_without_csrf_token_succeeds + /private/tmp/ltx-auto-advance-20261104/dc-overview/tests/test_server_delete.py:19: LegacyAPIWarning: The Query.get() method is considered legacy as of the 1.x series of SQLAlchemy and becomes a legacy construct in 2.0. The method is now available as Session.get() (deprecated since: 2.0) (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9) + assert Server.query.get(sample_server) is not None + +tests/test_server_delete.py::TestServerDelete::test_delete_server_without_csrf_token_succeeds + /private/tmp/ltx-auto-advance-20261104/dc-overview/tests/test_server_delete.py:30: LegacyAPIWarning: The Query.get() method is considered legacy as of the 1.x series of SQLAlchemy and becomes a legacy construct in 2.0. The method is now available as Session.get() (deprecated since: 2.0) (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9) + assert Server.query.get(sample_server) is None + +tests/test_server_delete.py::TestServerDelete::test_delete_server_unauthenticated_returns_401 + /private/tmp/ltx-auto-advance-20261104/dc-overview/tests/test_server_delete.py:47: LegacyAPIWarning: The Query.get() method is considered legacy as of the 1.x series of SQLAlchemy and becomes a legacy construct in 2.0. The method is now available as Session.get() (deprecated since: 2.0) (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9) + assert Server.query.get(sample_server) is not None + +-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html +2121 passed, 725 warnings in 185.55s (0:03:05) diff --git a/.traceweaver/auto-advance-20261104/native-negative.log b/.traceweaver/auto-advance-20261104/native-negative.log new file mode 100644 index 0000000..c7a9731 --- /dev/null +++ b/.traceweaver/auto-advance-20261104/native-negative.log @@ -0,0 +1 @@ +{"scope": "disposable Linux fixture; no production key or catalog", "cases": [{"case": "bad-real-signature-no-partial-persistence", "result": "passed"}, {"case": "real-SO_PEERCRED-rejects-UID65534-claiming-root", "result": "passed", "restored_socket_mode": "0600"}]} diff --git a/.traceweaver/auto-advance-20261104/native-qualification-repair/dev-integration.json b/.traceweaver/auto-advance-20261104/native-qualification-repair/dev-integration.json new file mode 100644 index 0000000..4d5063d --- /dev/null +++ b/.traceweaver/auto-advance-20261104/native-qualification-repair/dev-integration.json @@ -0,0 +1,47 @@ +{ + "parents": [ + "488e404c50e6abb6fb7b1e34f05f6d45a5278b75", + "91061265708e6c387dfb9bb883ed471052868b78" + ], + "automatic_merge_tree": "eeb4cac983ac22f27c2ca8097ff3eba9f1a67ce5", + "manual_files": { + ".traceweaver/intent-contract.yml": { + "conflicts_resolved": 1, + "both_approved_blocks_preserved": true, + "sha256": "c597d5c3306c6ed03efba9798760f1401808f52e30c794bbceed80c92ced5cc1" + }, + "requirements.md": { + "conflicts_resolved": 1, + "both_approved_blocks_preserved": true, + "sha256": "031352dd4c2033d081ca56c01e7ad54ecc03118d3601c2d0b1cc49441d28cb09" + }, + "traceability-matrix.md": { + "conflicts_resolved": 1, + "both_approved_blocks_preserved": true, + "sha256": "1c6ddf388810015579bf6ef06866e9a3d4a7df7d09111ed0dfc50f4cfadd6bf8" + } + }, + "authority_semantics": "union of both approved append-only sections; all original YAML values from both parents equal; no new requirements", + "doc_review": { + "reviewer": "button_correctness_review", + "findings": [], + "result": "passed", + "facts": "All original parent lines/order preserved; no new nonempty authority lines; strict YAML duplicate-free, every parent key-value identical; holds retained" + }, + "unconflicted_incoming_files": "all34 exactly equal approved dev9106126 bytes", + "application_guarded_files": "unchanged from reviewed source pair", + "verification": { + "native_route": "12passed", + "policy_regression": "293passed", + "full_regression": "2125passed;11blocked by sandbox loopback permissions; eightPrometheuscases replayed with permitted loopback and passed; threeunchangedUIcases remain localenvironmentheld", + "new_application_behavior": false + }, + "scope": "local integration of already approved dev; not remote PR merge or release", + "held": [ + "native runtime", + "three unchanged local UI cases blocked before browser startup", + "recovery prerequisite", + "signed catalog publisher", + "deployment" + ] +} diff --git a/.traceweaver/auto-advance-20261104/native-qualification-repair/native-profile-hash-changes.json b/.traceweaver/auto-advance-20261104/native-qualification-repair/native-profile-hash-changes.json new file mode 100644 index 0000000..40997c0 --- /dev/null +++ b/.traceweaver/auto-advance-20261104/native-qualification-repair/native-profile-hash-changes.json @@ -0,0 +1,86 @@ +[ + { + "product": "dc", + "file": "src/dc_overview/cli.py", + "before": "39ec1edbf04d91293eed13a63f7fd8cc7d6f1a3f2d4f83017829cfe3b7c83b7f", + "after": "63501cf00a6cb238d8f386b16f8f2393342344c5c69493cbf6fcb37a20e9276e", + "provenance": "published exact reviewed feature head; final source-hashes receipt where present" + }, + { + "product": "dc", + "file": "src/dc_overview/fleet_upgrade.py", + "before": "5f4504f38f64c59d00ca90b13cf94eb905c5fe3fe5ebd3fa49b28561f0d8cc14", + "after": "a2d9cf730de5b0d68b1071d4329dd9e4b2af1bf285f1857b5d6abd52f205674e", + "provenance": "published exact reviewed feature head; final source-hashes receipt where present" + }, + { + "product": "dc", + "file": "src/dc_overview/release_broker.py", + "before": "137c990c00ba4d59ade7c8490b9fd9b574709f73c0d072466bbc41e253fbb33b", + "after": "5916872d5ec87a2e9b69529c2c8a16f9a871667d9ff0ae27a0f1691fcaa296b7", + "provenance": "published exact reviewed feature head; final source-hashes receipt where present" + }, + { + "product": "dc", + "file": "src/dc_overview/release_policy.py", + "before": null, + "after": "0061e5a66b4f5495fe7bc83e8426b085983a1c42c12bb25cfdf853c33dc06b7b", + "provenance": "published exact reviewed feature head; final source-hashes receipt where present" + }, + { + "product": "dc", + "file": "src/dc_overview/templates/systemd/dc-overview-release-refresh.service", + "before": null, + "after": "b21ecf63d9ab5ce9a39ed84aeedb706a8064a38485bb22f85c3bdfbc0ed9dd2e", + "provenance": "published exact reviewed feature head; final source-hashes receipt where present" + }, + { + "product": "dc", + "file": "src/dc_overview/templates/systemd/dc-overview-release-refresh.timer", + "before": null, + "after": "1bfcb7323a7e29f240c923e6e9d2f75f41717e2fd0ee385e4232d0fd34dfd3ca", + "provenance": "published exact reviewed feature head; final source-hashes receipt where present" + }, + { + "product": "proxy", + "file": "landing-page/index.html", + "before": "20061e8140c5132b68f0bdc5a7ebfd48023534cf6f1ea7f2921ea6d04530ff37", + "after": "1d88cf658c71b58af29d501837e876c0f48c0e7d5083a0f90fab4ba8e6774552", + "provenance": "published exact reviewed feature head; final source-hashes receipt where present" + }, + { + "product": "proxy", + "file": "src/cryptolabs_proxy/auth.py", + "before": "e9bda16030012f4045364ea4fa6929c6d42e6da5d4e1392259298fbcff3fb679", + "after": "dd0149b619ee37aced86cd8de4829e3487b476217cd0733a570c727bff1be08d", + "provenance": "published exact reviewed feature head; final source-hashes receipt where present" + }, + { + "product": "proxy", + "file": "src/cryptolabs_proxy/release_client.py", + "before": "d3ed1dd31ea3a54f07a17772fefdbbb1bc9105880ab7b0d563f17d73a4332c25", + "after": "dd496ad4d007cb98039e5ba8bdf899398dc576d2448e199be6e875b7c1d75fec", + "provenance": "published exact reviewed feature head; final source-hashes receipt where present" + }, + { + "product": "proxy", + "file": "src/cryptolabs_proxy/standard_adoption.py", + "before": "46f7bd6d889d00d41f632e6246f9269ea9a1833626482383acbfd30454d079a2", + "after": "dbb9cbc33727efabf6b267a8c909d7fb0269d4aba97cb0dd7178379bcea15e08", + "provenance": "published exact reviewed feature head; final source-hashes receipt where present" + }, + { + "product": "proxy", + "file": "src/cryptolabs_proxy/updates.py", + "before": "cdb0958893eb6a11dc2764c4384ea784bf4b9632418a0871c3cee35bde3d00b6", + "after": "c1b800399824f05af8dfcd764ac32639b4ed7d428545282f080e4386fc571fe2", + "provenance": "published exact reviewed feature head; final source-hashes receipt where present" + }, + { + "product": "proxy", + "file": "src/cryptolabs_proxy/update_recovery.py", + "before": null, + "after": "0063848821dd41d8f600e936a432bee10c80f9851ce0b99a00aea8aa43f29316", + "provenance": "published exact reviewed feature head; final source-hashes receipt where present" + } +] diff --git a/.traceweaver/auto-advance-20261104/native-qualification-repair/native-repair-authority.json b/.traceweaver/auto-advance-20261104/native-qualification-repair/native-repair-authority.json new file mode 100644 index 0000000..cf7d4ea --- /dev/null +++ b/.traceweaver/auto-advance-20261104/native-qualification-repair/native-repair-authority.json @@ -0,0 +1,27 @@ +{ + "utc": "2026-11-05T06:44:56.669950+00:00", + "decision": "Proceed with qualification-reference repair only", + "user_instruction": "ok we need to fix this or bypasss it for this upgrade or refersh the mirror", + "approved_plan_sha256": "94b783d925834004cd3f111dd2437f8ae531850f0184aaa29c52f89f84267795", + "requirements": [ + "REQ-AUTOADVANCE-008" + ], + "trace": "TRACE-AUTOADVANCE-008", + "verification": "VER-AUTOADVANCE-008", + "scope": [ + ".github/tests/test_fleet_native_route.py", + ".github/workflows/fleet-release-native-qa.yml", + "scripts/verify_fleet_release_native.py" + ], + "red_evidence": "native-route-red.log: two assertion failures on old Proxy pin", + "must_not_change": [ + "runtime application code", + "existing frozen guard entries or source/wheel identity rejection", + "runner privileges/trust boundaries", + "recovery continuity guard", + "catalog/signing trust", + "existing native/deployment journals" + ], + "claim_limit": "Passing source preflight does not establish native feature acceptance or close PR34 recovery/publisher prerequisites", + "publication": "separate reviewed route; no automatic source publication from debug" +} diff --git a/.traceweaver/auto-advance-20261104/native-qualification-repair/native-route-green.log b/.traceweaver/auto-advance-20261104/native-qualification-repair/native-route-green.log new file mode 100644 index 0000000..b1890f1 --- /dev/null +++ b/.traceweaver/auto-advance-20261104/native-qualification-repair/native-route-green.log @@ -0,0 +1,17 @@ +test_approved_policy_source_pair_passes_real_guard_and_tampering_fails (test_fleet_native_route.FleetNativeRouteTest.test_approved_policy_source_pair_passes_real_guard_and_tampering_fails) ... ok +test_broker_child_preserves_original_exception_when_collection_fails (test_fleet_native_route.FleetNativeRouteTest.test_broker_child_preserves_original_exception_when_collection_fails) ... ok +test_child_file_is_private_bounded_reset_and_consumed_before_cleanup (test_fleet_native_route.FleetNativeRouteTest.test_child_file_is_private_bounded_reset_and_consumed_before_cleanup) ... ok +test_child_metadata_uses_original_code_identity_and_fixed_error_kind (test_fleet_native_route.FleetNativeRouteTest.test_child_metadata_uses_original_code_identity_and_fixed_error_kind) ... ok +test_kill_records_numeric_failure_and_never_restarts_or_masks_it (test_fleet_native_route.FleetNativeRouteTest.test_kill_records_numeric_failure_and_never_restarts_or_masks_it) ... ok +test_lost_reply_keeps_request_connected_until_durable_acceptance (test_fleet_native_route.FleetNativeRouteTest.test_lost_reply_keeps_request_connected_until_durable_acceptance) ... ok +test_main_crash_rejects_unsupported_or_invalid_live_identity (test_fleet_native_route.FleetNativeRouteTest.test_main_crash_rejects_unsupported_or_invalid_live_identity) ... ok +test_main_crash_requires_old_identity_death_before_start_and_fresh_broker (test_fleet_native_route.FleetNativeRouteTest.test_main_crash_requires_old_identity_death_before_start_and_fresh_broker) ... ok +test_placeholder_fails_before_guest_commands (test_fleet_native_route.FleetNativeRouteTest.test_placeholder_fails_before_guest_commands) ... ok +test_process_stat_identity_is_bounded_and_validated (test_fleet_native_route.FleetNativeRouteTest.test_process_stat_identity_is_bounded_and_validated) ... ok +test_route_is_exact_public_pr_and_never_inherits_authority (test_fleet_native_route.FleetNativeRouteTest.test_route_is_exact_public_pr_and_never_inherits_authority) ... ok +test_service_snapshot_exports_only_closed_fields (test_fleet_native_route.FleetNativeRouteTest.test_service_snapshot_exports_only_closed_fields) ... ok + +---------------------------------------------------------------------- +Ran 12 tests in 0.184s + +OK diff --git a/.traceweaver/auto-advance-20261104/native-qualification-repair/native-route-red.log b/.traceweaver/auto-advance-20261104/native-qualification-repair/native-route-red.log new file mode 100644 index 0000000..7cbf3e0 --- /dev/null +++ b/.traceweaver/auto-advance-20261104/native-qualification-repair/native-route-red.log @@ -0,0 +1,41 @@ +test_approved_policy_source_pair_passes_real_guard_and_tampering_fails (test_fleet_native_route.FleetNativeRouteTest.test_approved_policy_source_pair_passes_real_guard_and_tampering_fails) ... FAIL +test_broker_child_preserves_original_exception_when_collection_fails (test_fleet_native_route.FleetNativeRouteTest.test_broker_child_preserves_original_exception_when_collection_fails) ... ok +test_child_file_is_private_bounded_reset_and_consumed_before_cleanup (test_fleet_native_route.FleetNativeRouteTest.test_child_file_is_private_bounded_reset_and_consumed_before_cleanup) ... ok +test_child_metadata_uses_original_code_identity_and_fixed_error_kind (test_fleet_native_route.FleetNativeRouteTest.test_child_metadata_uses_original_code_identity_and_fixed_error_kind) ... ok +test_kill_records_numeric_failure_and_never_restarts_or_masks_it (test_fleet_native_route.FleetNativeRouteTest.test_kill_records_numeric_failure_and_never_restarts_or_masks_it) ... ok +test_lost_reply_keeps_request_connected_until_durable_acceptance (test_fleet_native_route.FleetNativeRouteTest.test_lost_reply_keeps_request_connected_until_durable_acceptance) ... ok +test_main_crash_rejects_unsupported_or_invalid_live_identity (test_fleet_native_route.FleetNativeRouteTest.test_main_crash_rejects_unsupported_or_invalid_live_identity) ... ok +test_main_crash_requires_old_identity_death_before_start_and_fresh_broker (test_fleet_native_route.FleetNativeRouteTest.test_main_crash_requires_old_identity_death_before_start_and_fresh_broker) ... ok +test_placeholder_fails_before_guest_commands (test_fleet_native_route.FleetNativeRouteTest.test_placeholder_fails_before_guest_commands) ... ok +test_process_stat_identity_is_bounded_and_validated (test_fleet_native_route.FleetNativeRouteTest.test_process_stat_identity_is_bounded_and_validated) ... ok +test_route_is_exact_public_pr_and_never_inherits_authority (test_fleet_native_route.FleetNativeRouteTest.test_route_is_exact_public_pr_and_never_inherits_authority) ... FAIL +test_service_snapshot_exports_only_closed_fields (test_fleet_native_route.FleetNativeRouteTest.test_service_snapshot_exports_only_closed_fields) ... ok + +====================================================================== +FAIL: test_approved_policy_source_pair_passes_real_guard_and_tampering_fails (test_fleet_native_route.FleetNativeRouteTest.test_approved_policy_source_pair_passes_real_guard_and_tampering_fails) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/private/tmp/ltx-native-repair-20261105/dc-overview/.github/tests/test_fleet_native_route.py", line 44, in test_approved_policy_source_pair_passes_real_guard_and_tampering_fails + self.assertEqual(workflow["env"]["PROXY_SOURCE_SHA"], proxy_sha) + ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +AssertionError: '5db15086c26095179f2af56bfa434c85426a6699' != '6e5186401e78cc8ba7b6ffe18eb24712ef9263b1' +- 5db15086c26095179f2af56bfa434c85426a6699 ++ 6e5186401e78cc8ba7b6ffe18eb24712ef9263b1 + + +====================================================================== +FAIL: test_route_is_exact_public_pr_and_never_inherits_authority (test_fleet_native_route.FleetNativeRouteTest.test_route_is_exact_public_pr_and_never_inherits_authority) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/private/tmp/ltx-native-repair-20261105/dc-overview/.github/tests/test_fleet_native_route.py", line 504, in test_route_is_exact_public_pr_and_never_inherits_authority + self.assertEqual(pin, "6e5186401e78cc8ba7b6ffe18eb24712ef9263b1") + ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +AssertionError: '5db15086c26095179f2af56bfa434c85426a6699' != '6e5186401e78cc8ba7b6ffe18eb24712ef9263b1' +- 5db15086c26095179f2af56bfa434c85426a6699 ++ 6e5186401e78cc8ba7b6ffe18eb24712ef9263b1 + + +---------------------------------------------------------------------- +Ran 12 tests in 0.176s + +FAILED (failures=2) diff --git a/.traceweaver/auto-advance-20261104/native-qualification-repair/review-security.json b/.traceweaver/auto-advance-20261104/native-qualification-repair/review-security.json new file mode 100644 index 0000000..2dcf93e --- /dev/null +++ b/.traceweaver/auto-advance-20261104/native-qualification-repair/review-security.json @@ -0,0 +1,7 @@ +{ + "reviewer": "advance_vv_security", + "findings": [], + "result": "passed", + "verification": "All25frozenhashes match exact publishedgitblobs; alloriginalentriesretained;ASTunchangedoutsidemap;workflowpinonly", + "limit": "Native runtime,publisher,deploymentacceptanceheld" +} diff --git a/.traceweaver/auto-advance-20261104/native-qualification-repair/review-testing.json b/.traceweaver/auto-advance-20261104/native-qualification-repair/review-testing.json new file mode 100644 index 0000000..602050c --- /dev/null +++ b/.traceweaver/auto-advance-20261104/native-qualification-repair/review-testing.json @@ -0,0 +1,7 @@ +{ + "reviewer": "advance_vv_correctness", + "findings": [], + "result": "passed", + "verification": "12 focused tests pass, actual source guard AST rejects DC and Proxy tampering; sibling paths match CI", + "limit": "Native guest execution and installed-wheel verification not established" +} diff --git a/.traceweaver/auto-advance-20261104/native-qualification-repair/verification.json b/.traceweaver/auto-advance-20261104/native-qualification-repair/verification.json new file mode 100644 index 0000000..d70317c --- /dev/null +++ b/.traceweaver/auto-advance-20261104/native-qualification-repair/verification.json @@ -0,0 +1,30 @@ +{ + "requirement": "REQ-AUTOADVANCE-008", + "trace": "TRACE-AUTOADVANCE-008", + "verification": "VER-AUTOADVANCE-008", + "approved_plan_sha256": "94b783d925834004cd3f111dd2437f8ae531850f0184aaa29c52f89f84267795", + "baseline_DC": "fa4e8256fe927e490aabd6657f060ac2d28bb094", + "reviewed_Proxy": "6e5186401e78cc8ba7b6ffe18eb24712ef9263b1", + "scope": "Native source-qualification references only; no application or recovery behavior changes", + "red": "native-route-red.log: 2 failures", + "green": "native-route-green.log: 12 tests passed", + "guard_preservation": "all21originalguardedfilesretained;3policy/timerfilesandProxyrecoveryadded;sourceandinstalledwheelcheckcodeunchanged", + "validation_question": "Does the exact approved source pair clear source qualification while changed bytes are refused?", + "answer": "yes in isolated source-guard regression; not native runtime acceptance", + "reviews": [ + "review-testing.json", + "review-security.json" + ], + "source_sha256": { + ".github/tests/test_fleet_native_route.py": "818aae1827d91ac3143f7a778ac88d4fb24f77b31cdb936522caf966a26ce45f", + ".github/workflows/fleet-release-native-qa.yml": "2f4336f0b6dfb1ee98bfbc7942f45c58034c3495227a7ec41238aa2f39035a66", + "scripts/verify_fleet_release_native.py": "456f4c72faaddfc62fdf8bf095b95f56f69353d913341ffe036b4befcd091b43" + }, + "held": [ + "full native feature runtime", + "existingPR34cloudcontinuityfailure", + "trusted production publisher/catalog", + "main release and both-site activation" + ], + "reproduce": "Checkout DC candidate as dc and reviewed Proxy6e518640 as sibling proxy; python3 -m unittest discover -s dc/.github/tests -p test_fleet_native_route.py -v" +} diff --git a/.traceweaver/auto-advance-20261104/native-source-equivalence.json b/.traceweaver/auto-advance-20261104/native-source-equivalence.json new file mode 100644 index 0000000..4719dba --- /dev/null +++ b/.traceweaver/auto-advance-20261104/native-source-equivalence.json @@ -0,0 +1,21 @@ +{ + "method": "Both Python3.12 AST without comments/locations; trace-comment changes after wheel build", + "matched": true, + "initial_attempt": "cross-version Python3.14/3.12 AST hashes incomparable; rerun with matching Python3.12", + "guest": { + "cryptolabs_proxy/auth.py": "c40e04b318910ce1a2c1eedfac710d1f8c5ce60959da43f5316979229a21b42d", + "cryptolabs_proxy/release_client.py": "66dd68c121586470256923237436033d60e308e7c60f84ad6141d42c4bf63fe7", + "dc_overview/cli.py": "3255b052cac6e7dd165189fc95f5357c92a32854254c4ea392b24122c303f04c", + "dc_overview/fleet_upgrade.py": "5f696be2b9c06780b76e8c617485857752d171f025f27425ef292089997894dc", + "dc_overview/release_broker.py": "afb854ac3640f6dcc528cf5aa8fce8f19eacc0916f0fecc7bfa2ceff8000cc1e", + "dc_overview/release_policy.py": "b72cf1d61337b9dbcf2cb9bb0ecb9c95659efde0d1074e1ede22d730392c86ee" + }, + "local": { + "cryptolabs_proxy/auth.py": "c40e04b318910ce1a2c1eedfac710d1f8c5ce60959da43f5316979229a21b42d", + "cryptolabs_proxy/release_client.py": "66dd68c121586470256923237436033d60e308e7c60f84ad6141d42c4bf63fe7", + "dc_overview/cli.py": "3255b052cac6e7dd165189fc95f5357c92a32854254c4ea392b24122c303f04c", + "dc_overview/fleet_upgrade.py": "5f696be2b9c06780b76e8c617485857752d171f025f27425ef292089997894dc", + "dc_overview/release_broker.py": "afb854ac3640f6dcc528cf5aa8fce8f19eacc0916f0fecc7bfa2ceff8000cc1e", + "dc_overview/release_policy.py": "b72cf1d61337b9dbcf2cb9bb0ecb9c95659efde0d1074e1ede22d730392c86ee" + } +} diff --git a/.traceweaver/auto-advance-20261104/native-verification.json b/.traceweaver/auto-advance-20261104/native-verification.json new file mode 100644 index 0000000..8fac944 --- /dev/null +++ b/.traceweaver/auto-advance-20261104/native-verification.json @@ -0,0 +1 @@ +{"application_health":"not exercised; two controller images kept idle","discovery":"synthetic signed raw bundles; actual signature verification; no production catalog claim","production":false,"results":[{"case":"real-docker-pin-follow-refresh","result":"passed"},{"case":"repin-installed-no-advance","result":"passed"},{"case":"abrupt-death-before-native","exit":77,"recovered_mode":"pinned","result":"passed"},{"case":"abrupt-death-after-selection","exit":77,"recovered_mode":"pinned","result":"passed"},{"case":"abrupt-death-after-public","exit":77,"recovered_mode":"follow-stable","result":"passed"},{"case":"abrupt-death-before-policy","exit":77,"recovered_mode":"follow-stable","result":"passed"},{"case":"competing-process-and-repin-cas","result":"passed"},{"case":"actual-root-socket-cli-and-systemd-refresh","result":"passed","service_status":"Result=success\nExecMainStatus=0","timer":"NextElapseUSecRealtime=Thu 2026-11-05 00:10:52 SAST\nActiveState=active","unauthorized_uid_denied":65534},{"case":"zero-container-replacement-or-restarts","identities":{"cryptolabs-proxy":{"Id":"9a0b552ae7fc78d9e19334ad0e16133f28b777c3ae9679996be57ab00b50b180","Image":"sha256:8fc51cde1555f7b6a3b21faf20740cae3eff145c6d661868c4a1ad6a07dd7874","RestartCount":0,"StartedAt":"2026-11-04T17:31:14.768729077Z"},"ipmi-monitor":{"Id":"a6d86e80adb3d052b96fde553957106d9a795e2bae983f7cb1761c1006178d81","Image":"sha256:84563cf838bd34c12cc83239c06c44f9a69c01b9dfff570e35ca913ef1825dac","RestartCount":0,"StartedAt":"2026-11-04T17:31:16.84448682Z"}},"result":"passed"}]} \ No newline at end of file diff --git a/.traceweaver/auto-advance-20261104/owner-approval.json b/.traceweaver/auto-advance-20261104/owner-approval.json new file mode 100644 index 0000000..3dd0cf1 --- /dev/null +++ b/.traceweaver/auto-advance-20261104/owner-approval.json @@ -0,0 +1,8 @@ +{ + "utc": "2026-11-04T16:34:29.958547+00:00", + "owner": "Hannes Zietsman", + "message": "Yes approve the plan", + "approved_plan_sha256": "94b783d925834004cd3f111dd2437f8ae531850f0184aaa29c52f89f84267795", + "scope": "all candidatebehavior C1-C8, numberedimplementation andCI/release/LTXverification inexactplan", + "no_repeat_approval_needed": true +} diff --git a/.traceweaver/auto-advance-20261104/plan.md b/.traceweaver/auto-advance-20261104/plan.md new file mode 100644 index 0000000..58083ab --- /dev/null +++ b/.traceweaver/auto-advance-20261104/plan.md @@ -0,0 +1,50 @@ +# Per-service pin removal and stable release following — candidate plan + +Status: prepared for owner plan approval; no implementation or target changes. +Source request: owner approved verified stable selection advancement with manual installation, and added that users must be able to remove a pin and follow stable releases. +Scope: LTX Fleet website, reversible per-service administrator choice, trusted selection advancement, manual Update action, CI/release and LTX verification through the existing controlled routes. Existing services keep their current mode until an administrator changes it. + +## Observed source boundaries + +- Deployed Proxy1.6.2 source main c5e88a99b4da6fe37cacc64fc0cda5a59e3617de; upstream dev10f48b4474a1c2c771bf72449d22efddd91f0d02 contains additional unreleased release-client/auth bridge work. Do not import dev wholesale. +- Current production release_selection.py permits baseline/customer-pin/unmanaged, and release-selection docs keep selection files root-owned/read-only in Proxy. A browser toggle cannot safely be a direct file write. +- Existing DC Fleet source worktree dc-overview-fleet-service-recovery-20261102 at01011f44d93ec86027db1c0d33238b4ea90e6880 includes release_broker.py, release_catalog.py, release_candidates.py and fixed systemd socket transport. Its authority explicitly retains native/publisher/deployment holds. This is reusable source context, not accepted live infrastructure. +- Existing broker previews update a pinned identity when explicitly selecting a candidate; durable follow/pin intent and selection-only refresh are missing. Current list/preview/apply/status/recover protocol must be extended deliberately. +- Second Brain did not locate relevant current release-policy context; direct source and exact GitHub refs supplied these findings. Existing project graph covers older monitoring/exporter paths, not this feature. + +## Candidate behavior and acceptance criteria + +C1. An authenticated Fleet administrator can switch one supported managed service between Pinned and Follow stable; the visible installed/selected version and mode remain distinct. +C2. Removing a pin opts only that service into verified stable candidates. Existing pins remain pinned by default. Pin current version freezes the verified installed digest; if its identity/provenance cannot be established, the operation fails without changing policy. +C3. Follow stable selects the newest admitted compatible non-prerelease version within the installed major version. No downgrade; a major upgrade requires explicit selection. No usable newer candidate leaves the current selection intact and reports why. +C4. Selection refresh occurs on Check Updates and a daily host-side check, including when no browser is open. It changes only opted-in services. Mode changes and refresh never install or restart containers. The existing Update action handles installation. +C5. Policy mutation uses the existing host owner boundary, authenticated administrator/session/CSRF/origin checks, explicit service scope, bounded fields, selection compare-and-swap, and existing lifecycle locks. A native CLI exposes the same choices. Failed persistence, stale requests, active operations, unavailable discovery or failed trust verification preserve prior selections and modes. +C6. Use verified published release/admission metadata, fixed trusted repository/channel sources and exact immutable digests. Do not replace digests with mutable :latest tags or loosen publisher/signature checks. External-owned services retain their owning lifecycle workflow; unsupported services show an explanation rather than pretending the change succeeded. +C7. Show current mode, installed version, selected target and clear failure/progress states; refreshes cannot silently re-pin or cross major versions. Re-pinning prevents a concurrent scheduled refresh from advancing afterward. +C8. TDD, independent correctness/security review, native Linux lifecycle/policy verification and real-browser checks precede release. Existing LTX data/accounts/settings and unrelated pins/runtimes remain preserved. + +## Numbered implementation plan + +1. Write failing tests first. DC: new tests/test_release_policy.py plus existing tests/test_release_broker.py, test_release_candidates.py and test_scoped_release_selection.py. Proxy: API/client tests for the existing release bridge plus tests/test_latest_status.py. Cover pin removal/re-pinning, stable choice, same-major rule, downgrade/prerelease rejection, no eligible candidate, mode persistence, no restarts, selection races, active lifecycle locks, unauthorized/CSRF/origin rejection, interrupted publication and unrelated-service preservation. +2. Add the smallest per-service policy owner module src/dc_overview/release_policy.py. Extend src/dc_overview/release_broker.py and release_catalog.py with bounded policy read/change and selection-only refresh, reusing existing trusted candidate discovery and atomic lifecycle publication. Add CLI parity in cli.py and a daily installed systemd timer/service invoking that exact owner operation. Policy intent lives in a separate root-owned versioned record; do not add unrecognized fields to the existing selection schema. Preserve all existing source policies on first install. +3. Extend Proxy src/cryptolabs_proxy/release_client.py and the existing administrator/CSRF-protected release routes in auth.py. Add mode and target controls to landing-page/index.html and consistent status in scripts/health-api.py/updates.py where required. Browser sends only bounded service/mode/expected identity fields; it cannot supply file paths, commands or arbitrary registry URLs. No new public trust source or credential store. +4. Verify Red-Green-Refactor, focused and appropriate regression suites, independent correctness/security/API review and real Linux owner tests. Native scenarios include two competing refresh/pin requests, crash/restart, unavailable catalog, invalid admission, persistent daily refresh without a browser, and zero lifecycle calls for policy-only operations. Run real Chrome with pending and installed targets; prove unpin -> verified target -> manual update -> healthy, then re-pin -> no subsequent advance. Do not manufacture a production downgrade or extra hardware restart solely for a demo. +5. Complete the existing broker/bridge native and publisher acceptance prerequisites before activation. Publish only the reviewed required source on dev, release through main with normal versioning and GitHub CI, inspect immutable official artifacts, deploy through native LTX ownership, then verify UI persistence, exact selected digests, original history/accounts and unrelated containers. Keep automatic installation off. If prerequisite infrastructure remains held, report that specific deployment hold without claiming the feature is live. + +## Dependencies, risks and decisions + +No new third-party service or Python dependency is proposed. Host systemd timer and the accepted broker/bridge runtime are infrastructure changes. The existing Fleet broker source is not currently accepted on LTX; finishing that dependency is required and must not be hidden as a simple UI-only change. + +Selected approach: immutable digests plus explicit persisted follow intent. A mutable :latest tag loses the selected artifact contract; a frontend-only toggle cannot cross root custody safely; duplicating a second lifecycle controller creates competing writers. Reuse and extend the existing owner and release pipeline instead. + +The principal risks are choosing an untrusted/incompatible release, advancing a freshly re-pinned service, lost multi-component updates, and selection/installation confusion. Mitigations are admitted candidates, same-major/no-downgrade rules, explicit compare-and-swap plus existing locks, transactional policy publication/recovery, strict one-service scope, clear UI and native concurrency/failure tests. + +## Verification and validation plan + +Verification owner: main implementation chat. Every result records tested source, command/scenario, expected/actual state and evidence path under this directory. A local synthetic UI tests controls/request contracts only; actual Linux owner evidence is required for root custody, sockets, timer, atomic changes and lifecycle preservation. + +Stakeholder acceptance owner/rater: Hannes Zietsman, operator requesting the behavior, independent of implementation. Observable acceptance: an administrator removes IPMI's pin in Fleet, sees Follow stable persist across reload, sees a verified compatible stable target chosen without an automatic restart, can install through Update, and can re-pin so future checks keep the version. If no genuine newer admitted release exists on LTX, pending-release installation is demonstrated on native disposable staging and LTX validates current mode/identity/preservation; no false production upgrade claim. + +## Authority and publication status + +Source request supports the feature intent. This plan introduces concrete files, API/root-owner behavior and scheduling details, so it remains candidate authority until explicit plan approval under project AGENTS.md section2. No production source, selection, service, credential, CI publication or deployment has changed in this planning turn. Current implementation baseline documents are read for constraints; existing Fleet-held acceptance claims are not promoted by this plan. diff --git a/.traceweaver/auto-advance-20261104/profile.json b/.traceweaver/auto-advance-20261104/profile.json new file mode 100644 index 0000000..9744cf2 --- /dev/null +++ b/.traceweaver/auto-advance-20261104/profile.json @@ -0,0 +1,25 @@ +{ + "revision": 1, + "level": "L3", + "reason": "root-owned release policy, authenticated write API, scheduled selections, external artifact trust and deployment", + "review_scopes": [ + "correctness/concurrency/recovery", + "security/API/auth/trust" + ], + "review_repair_caps": "initial reviews plus at most two targeted repair reviews per changed scope; unresolved findings hold publication", + "controls": [ + "TDD", + "strict candidate trust", + "native Linux concurrency/crash/timer tests", + "browser admin controls", + "normal CI publication", + "native LTX deployment preservation" + ], + "subagent_builders": false, + "models": "current inherited model; review perspectives only if native review workflow dispatched", + "frozen_for_build": true, + "estimate_delivery_minutes": 240, + "estimate_process_target_minutes": 45, + "estimate_process_ceiling_minutes": 120, + "profile_hash": "3ac80e3c2632f12a44fa3e984bb69840579edca0e0bfb492fb635321c9f28a83" +} diff --git a/.traceweaver/auto-advance-20261104/red-integration.log b/.traceweaver/auto-advance-20261104/red-integration.log new file mode 100644 index 0000000..5db9419 --- /dev/null +++ b/.traceweaver/auto-advance-20261104/red-integration.log @@ -0,0 +1,2251 @@ +............FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF.... [ 96%] +FFF [100%] +=================================== FAILURES =================================== +_____ test_existing_components_default_pinned_with_no_implicit_follow[ltx] _____ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) + + def test_existing_components_default_pinned_with_no_implicit_follow(policy_product): + host, service, owner = policy_product + before = host.store.load().selection_raw +> listing = service.dispatch("policy-list", {}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +tests/test_release_policy.py:109: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-list', params = {} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +__ test_existing_components_default_pinned_with_no_implicit_follow[charlotte] __ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) + + def test_existing_components_default_pinned_with_no_implicit_follow(policy_product): + host, service, owner = policy_product + before = host.store.load().selection_raw +> listing = service.dispatch("policy-list", {}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +tests/test_release_policy.py:109: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-list', params = {} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_ test_unpin_survives_restart_and_changes_only_one_policy_without_install[ltx] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) + + def test_unpin_survives_restart_and_changes_only_one_policy_without_install(policy_product): + host, service, owner = policy_product + before = host.store.load() +> result = set_mode(service, "follow-stable") + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +tests/test_release_policy.py:119: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '686172db625bed42d2fd2b63c6fa43b6fa22322e4f019bae4ef9679537c7521f'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_ test_unpin_survives_restart_and_changes_only_one_policy_without_install[charlotte] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) + + def test_unpin_survives_restart_and_changes_only_one_policy_without_install(policy_product): + host, service, owner = policy_product + before = host.store.load() +> result = set_mode(service, "follow-stable") + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +tests/test_release_policy.py:119: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '7f0ed032b41772c6aa18c81f0a70d8a2509ebffa8a2d579e9b660fd003f98b69'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_ test_refresh_only_advances_opted_in_service_and_repin_installed_freezes_it[ltx] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +admitted = {'times': {'issued_at': '2026-11-04T16:43:21.679174+00:00', 'expires_at': '2026-11-04T16:45:31.679174+00:00'}, 'produc...95aceaf7040fb6828e1d62a85f9db794f3bb97791501e78550', 'verify': .verify at 0x10d0f7560>, ...} + + def test_refresh_only_advances_opted_in_service_and_repin_installed_freezes_it(policy_product, admitted): + host, service, owner = policy_product +> set_mode(service, "follow-stable") + +tests/test_release_policy.py:134: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '686172db625bed42d2fd2b63c6fa43b6fa22322e4f019bae4ef9679537c7521f'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_ test_refresh_only_advances_opted_in_service_and_repin_installed_freezes_it[charlotte] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +admitted = {'times': {'issued_at': '2026-11-04T16:43:21.700362+00:00', 'expires_at': '2026-11-04T16:45:31.700362+00:00'}, 'produc...c19ab394059365642df6c77eb353238a936dbcdf1a53f81e09', 'verify': .verify at 0x10d1b53a0>, ...} + + def test_refresh_only_advances_opted_in_service_and_repin_installed_freezes_it(policy_product, admitted): + host, service, owner = policy_product +> set_mode(service, "follow-stable") + +tests/test_release_policy.py:134: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '7f0ed032b41772c6aa18c81f0a70d8a2509ebffa8a2d579e9b660fd003f98b69'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +____ test_mode_failure_has_no_partial_policy_or_selection_change[ltx-stale] ____ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +fault = 'stale' + + @pytest.mark.parametrize("fault", ["stale", "busy", "disabled", "unproven-installed"]) + def test_mode_failure_has_no_partial_policy_or_selection_change(policy_product, fault): + host, service, owner = policy_product + from dc_overview.release_broker import BrokerError +> set_mode(service, "follow-stable") + +tests/test_release_policy.py:153: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '686172db625bed42d2fd2b63c6fa43b6fa22322e4f019bae4ef9679537c7521f'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +____ test_mode_failure_has_no_partial_policy_or_selection_change[ltx-busy] _____ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +fault = 'busy' + + @pytest.mark.parametrize("fault", ["stale", "busy", "disabled", "unproven-installed"]) + def test_mode_failure_has_no_partial_policy_or_selection_change(policy_product, fault): + host, service, owner = policy_product + from dc_overview.release_broker import BrokerError +> set_mode(service, "follow-stable") + +tests/test_release_policy.py:153: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '686172db625bed42d2fd2b63c6fa43b6fa22322e4f019bae4ef9679537c7521f'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +__ test_mode_failure_has_no_partial_policy_or_selection_change[ltx-disabled] ___ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +fault = 'disabled' + + @pytest.mark.parametrize("fault", ["stale", "busy", "disabled", "unproven-installed"]) + def test_mode_failure_has_no_partial_policy_or_selection_change(policy_product, fault): + host, service, owner = policy_product + from dc_overview.release_broker import BrokerError +> set_mode(service, "follow-stable") + +tests/test_release_policy.py:153: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '686172db625bed42d2fd2b63c6fa43b6fa22322e4f019bae4ef9679537c7521f'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_ test_mode_failure_has_no_partial_policy_or_selection_change[ltx-unproven-installed] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +fault = 'unproven-installed' + + @pytest.mark.parametrize("fault", ["stale", "busy", "disabled", "unproven-installed"]) + def test_mode_failure_has_no_partial_policy_or_selection_change(policy_product, fault): + host, service, owner = policy_product + from dc_overview.release_broker import BrokerError +> set_mode(service, "follow-stable") + +tests/test_release_policy.py:153: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '686172db625bed42d2fd2b63c6fa43b6fa22322e4f019bae4ef9679537c7521f'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_ test_mode_failure_has_no_partial_policy_or_selection_change[charlotte-stale] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +fault = 'stale' + + @pytest.mark.parametrize("fault", ["stale", "busy", "disabled", "unproven-installed"]) + def test_mode_failure_has_no_partial_policy_or_selection_change(policy_product, fault): + host, service, owner = policy_product + from dc_overview.release_broker import BrokerError +> set_mode(service, "follow-stable") + +tests/test_release_policy.py:153: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '7f0ed032b41772c6aa18c81f0a70d8a2509ebffa8a2d579e9b660fd003f98b69'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_ test_mode_failure_has_no_partial_policy_or_selection_change[charlotte-busy] __ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +fault = 'busy' + + @pytest.mark.parametrize("fault", ["stale", "busy", "disabled", "unproven-installed"]) + def test_mode_failure_has_no_partial_policy_or_selection_change(policy_product, fault): + host, service, owner = policy_product + from dc_overview.release_broker import BrokerError +> set_mode(service, "follow-stable") + +tests/test_release_policy.py:153: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '7f0ed032b41772c6aa18c81f0a70d8a2509ebffa8a2d579e9b660fd003f98b69'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_ test_mode_failure_has_no_partial_policy_or_selection_change[charlotte-disabled] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +fault = 'disabled' + + @pytest.mark.parametrize("fault", ["stale", "busy", "disabled", "unproven-installed"]) + def test_mode_failure_has_no_partial_policy_or_selection_change(policy_product, fault): + host, service, owner = policy_product + from dc_overview.release_broker import BrokerError +> set_mode(service, "follow-stable") + +tests/test_release_policy.py:153: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '7f0ed032b41772c6aa18c81f0a70d8a2509ebffa8a2d579e9b660fd003f98b69'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_ test_mode_failure_has_no_partial_policy_or_selection_change[charlotte-unproven-installed] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +fault = 'unproven-installed' + + @pytest.mark.parametrize("fault", ["stale", "busy", "disabled", "unproven-installed"]) + def test_mode_failure_has_no_partial_policy_or_selection_change(policy_product, fault): + host, service, owner = policy_product + from dc_overview.release_broker import BrokerError +> set_mode(service, "follow-stable") + +tests/test_release_policy.py:153: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '7f0ed032b41772c6aa18c81f0a70d8a2509ebffa8a2d579e9b660fd003f98b69'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_ test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure[ltx-signature] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +admitted = {'times': {'issued_at': '2026-11-04T16:43:21.948765+00:00', 'expires_at': '2026-11-04T16:45:31.948765+00:00'}, 'produc...e53c3df42c52d63af8b4077bf67bc3b7666e6c38c0f21b72ee', 'verify': .verify at 0x10d1b4f40>, ...} +fault = 'signature' + + @pytest.mark.parametrize('fault', ['signature','expired','revoked','replay','digest','unavailable']) + def test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure(policy_product, admitted, fault): + from dataclasses import replace + from dc_overview.release_broker import BrokerError, canonical, sha + from datetime import timedelta + host, service, owner = policy_product +> set_mode(service, 'follow-stable') + +tests/test_release_policy.py:182: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '686172db625bed42d2fd2b63c6fa43b6fa22322e4f019bae4ef9679537c7521f'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_ test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure[ltx-expired] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +admitted = {'times': {'issued_at': '2026-11-04T16:43:21.966934+00:00', 'expires_at': '2026-11-04T16:45:31.966934+00:00'}, 'produc...e3716848a278d116a67c8e93cdaa026f85c12d09091ca919db', 'verify': .verify at 0x10d1b6020>, ...} +fault = 'expired' + + @pytest.mark.parametrize('fault', ['signature','expired','revoked','replay','digest','unavailable']) + def test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure(policy_product, admitted, fault): + from dataclasses import replace + from dc_overview.release_broker import BrokerError, canonical, sha + from datetime import timedelta + host, service, owner = policy_product +> set_mode(service, 'follow-stable') + +tests/test_release_policy.py:182: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '686172db625bed42d2fd2b63c6fa43b6fa22322e4f019bae4ef9679537c7521f'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_ test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure[ltx-revoked] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +admitted = {'times': {'issued_at': '2026-11-04T16:43:21.984610+00:00', 'expires_at': '2026-11-04T16:45:31.984610+00:00'}, 'produc...cf27c9f4aac7082e2a5799193de985396b77cfb061e3966bfd', 'verify': .verify at 0x10d1b7420>, ...} +fault = 'revoked' + + @pytest.mark.parametrize('fault', ['signature','expired','revoked','replay','digest','unavailable']) + def test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure(policy_product, admitted, fault): + from dataclasses import replace + from dc_overview.release_broker import BrokerError, canonical, sha + from datetime import timedelta + host, service, owner = policy_product +> set_mode(service, 'follow-stable') + +tests/test_release_policy.py:182: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '686172db625bed42d2fd2b63c6fa43b6fa22322e4f019bae4ef9679537c7521f'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_ test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure[ltx-replay] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +admitted = {'times': {'issued_at': '2026-11-04T16:43:22.002599+00:00', 'expires_at': '2026-11-04T16:45:32.002599+00:00'}, 'produc...577be9bd88d04958f7b32f11bb044f73f0c1ad89d4e0b89038', 'verify': .verify at 0x10d1772e0>, ...} +fault = 'replay' + + @pytest.mark.parametrize('fault', ['signature','expired','revoked','replay','digest','unavailable']) + def test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure(policy_product, admitted, fault): + from dataclasses import replace + from dc_overview.release_broker import BrokerError, canonical, sha + from datetime import timedelta + host, service, owner = policy_product +> set_mode(service, 'follow-stable') + +tests/test_release_policy.py:182: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '686172db625bed42d2fd2b63c6fa43b6fa22322e4f019bae4ef9679537c7521f'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_ test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure[ltx-digest] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +admitted = {'times': {'issued_at': '2026-11-04T16:43:22.019892+00:00', 'expires_at': '2026-11-04T16:45:32.019892+00:00'}, 'produc...2f91e8aed5385bc321be86203b29bb9e3a8d22b6f3677eec89', 'verify': .verify at 0x10d0f7ce0>, ...} +fault = 'digest' + + @pytest.mark.parametrize('fault', ['signature','expired','revoked','replay','digest','unavailable']) + def test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure(policy_product, admitted, fault): + from dataclasses import replace + from dc_overview.release_broker import BrokerError, canonical, sha + from datetime import timedelta + host, service, owner = policy_product +> set_mode(service, 'follow-stable') + +tests/test_release_policy.py:182: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '686172db625bed42d2fd2b63c6fa43b6fa22322e4f019bae4ef9679537c7521f'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_ test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure[ltx-unavailable] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +admitted = {'times': {'issued_at': '2026-11-04T16:43:22.037778+00:00', 'expires_at': '2026-11-04T16:45:32.037778+00:00'}, 'produc...ac38add26b005c248d16f47d6cee7083cd3201bed0b9104e4e', 'verify': .verify at 0x10d175c60>, ...} +fault = 'unavailable' + + @pytest.mark.parametrize('fault', ['signature','expired','revoked','replay','digest','unavailable']) + def test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure(policy_product, admitted, fault): + from dataclasses import replace + from dc_overview.release_broker import BrokerError, canonical, sha + from datetime import timedelta + host, service, owner = policy_product +> set_mode(service, 'follow-stable') + +tests/test_release_policy.py:182: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '686172db625bed42d2fd2b63c6fa43b6fa22322e4f019bae4ef9679537c7521f'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_ test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure[charlotte-signature] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +admitted = {'times': {'issued_at': '2026-11-04T16:43:22.059033+00:00', 'expires_at': '2026-11-04T16:45:32.059033+00:00'}, 'produc...37a632b0bc2cc89575a4571a9e31139d4612425916623ec584', 'verify': .verify at 0x10d1777e0>, ...} +fault = 'signature' + + @pytest.mark.parametrize('fault', ['signature','expired','revoked','replay','digest','unavailable']) + def test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure(policy_product, admitted, fault): + from dataclasses import replace + from dc_overview.release_broker import BrokerError, canonical, sha + from datetime import timedelta + host, service, owner = policy_product +> set_mode(service, 'follow-stable') + +tests/test_release_policy.py:182: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '7f0ed032b41772c6aa18c81f0a70d8a2509ebffa8a2d579e9b660fd003f98b69'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_ test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure[charlotte-expired] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +admitted = {'times': {'issued_at': '2026-11-04T16:43:22.092303+00:00', 'expires_at': '2026-11-04T16:45:32.092303+00:00'}, 'produc...d11acd1fd142402645c8de42aad6b610044aaefcc7f6eb9123', 'verify': .verify at 0x10d1b6480>, ...} +fault = 'expired' + + @pytest.mark.parametrize('fault', ['signature','expired','revoked','replay','digest','unavailable']) + def test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure(policy_product, admitted, fault): + from dataclasses import replace + from dc_overview.release_broker import BrokerError, canonical, sha + from datetime import timedelta + host, service, owner = policy_product +> set_mode(service, 'follow-stable') + +tests/test_release_policy.py:182: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '7f0ed032b41772c6aa18c81f0a70d8a2509ebffa8a2d579e9b660fd003f98b69'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_ test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure[charlotte-revoked] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +admitted = {'times': {'issued_at': '2026-11-04T16:43:22.125729+00:00', 'expires_at': '2026-11-04T16:45:32.125729+00:00'}, 'produc...05391a621c787266c323955d1b08cef542c5c9a81174d18d96', 'verify': .verify at 0x10d176fc0>, ...} +fault = 'revoked' + + @pytest.mark.parametrize('fault', ['signature','expired','revoked','replay','digest','unavailable']) + def test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure(policy_product, admitted, fault): + from dataclasses import replace + from dc_overview.release_broker import BrokerError, canonical, sha + from datetime import timedelta + host, service, owner = policy_product +> set_mode(service, 'follow-stable') + +tests/test_release_policy.py:182: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '7f0ed032b41772c6aa18c81f0a70d8a2509ebffa8a2d579e9b660fd003f98b69'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_ test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure[charlotte-replay] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +admitted = {'times': {'issued_at': '2026-11-04T16:43:22.158994+00:00', 'expires_at': '2026-11-04T16:45:32.158994+00:00'}, 'produc...cd14d8d0497bf4e3cbad90315e8954ac7dca0fd55a3f4bc69b', 'verify': .verify at 0x10d2825c0>, ...} +fault = 'replay' + + @pytest.mark.parametrize('fault', ['signature','expired','revoked','replay','digest','unavailable']) + def test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure(policy_product, admitted, fault): + from dataclasses import replace + from dc_overview.release_broker import BrokerError, canonical, sha + from datetime import timedelta + host, service, owner = policy_product +> set_mode(service, 'follow-stable') + +tests/test_release_policy.py:182: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '7f0ed032b41772c6aa18c81f0a70d8a2509ebffa8a2d579e9b660fd003f98b69'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_ test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure[charlotte-digest] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +admitted = {'times': {'issued_at': '2026-11-04T16:43:22.192113+00:00', 'expires_at': '2026-11-04T16:45:32.192113+00:00'}, 'produc...8fd28dd4e500b67cb843e241aaa427cb83d5e21aa65805512f', 'verify': .verify at 0x10d2814e0>, ...} +fault = 'digest' + + @pytest.mark.parametrize('fault', ['signature','expired','revoked','replay','digest','unavailable']) + def test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure(policy_product, admitted, fault): + from dataclasses import replace + from dc_overview.release_broker import BrokerError, canonical, sha + from datetime import timedelta + host, service, owner = policy_product +> set_mode(service, 'follow-stable') + +tests/test_release_policy.py:182: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '7f0ed032b41772c6aa18c81f0a70d8a2509ebffa8a2d579e9b660fd003f98b69'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_ test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure[charlotte-unavailable] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +admitted = {'times': {'issued_at': '2026-11-04T16:43:22.225401+00:00', 'expires_at': '2026-11-04T16:45:32.225401+00:00'}, 'produc...19dd2160e673131aaf1ac09b2e4b619269b8690ee71c0fd4d5', 'verify': .verify at 0x10d283880>, ...} +fault = 'unavailable' + + @pytest.mark.parametrize('fault', ['signature','expired','revoked','replay','digest','unavailable']) + def test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure(policy_product, admitted, fault): + from dataclasses import replace + from dc_overview.release_broker import BrokerError, canonical, sha + from datetime import timedelta + host, service, owner = policy_product +> set_mode(service, 'follow-stable') + +tests/test_release_policy.py:182: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '7f0ed032b41772c6aa18c81f0a70d8a2509ebffa8a2d579e9b660fd003f98b69'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_____ test_repeated_check_never_downgrades_an_already_pending_target[ltx] ______ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +admitted = {'times': {'issued_at': '2026-11-04T16:43:22.254523+00:00', 'expires_at': '2026-11-04T16:45:32.254523+00:00'}, 'produc...172894edfaa01181ac363d6b7b5068617d792e5d7b173d9ea6', 'verify': .verify at 0x10d1d4900>, ...} + + def test_repeated_check_never_downgrades_an_already_pending_target(policy_product, admitted): + host, service, owner = policy_product +> set_mode(service,'follow-stable') + +tests/test_release_policy.py:206: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '686172db625bed42d2fd2b63c6fa43b6fa22322e4f019bae4ef9679537c7521f'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +__ test_repeated_check_never_downgrades_an_already_pending_target[charlotte] ___ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +admitted = {'times': {'issued_at': '2026-11-04T16:43:22.275634+00:00', 'expires_at': '2026-11-04T16:45:32.275634+00:00'}, 'produc...a2852a83bb4aa329d088aa6f8f9974a50cdc4ef182852c9bdd', 'verify': .verify at 0x10d1d5da0>, ...} + + def test_repeated_check_never_downgrades_an_already_pending_target(policy_product, admitted): + host, service, owner = policy_product +> set_mode(service,'follow-stable') + +tests/test_release_policy.py:206: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '7f0ed032b41772c6aa18c81f0a70d8a2509ebffa8a2d579e9b660fd003f98b69'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_ test_interrupted_policy_publication_restarts_to_a_coherent_state[ltx-journal] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x10d1c5940> +boundary = 'journal' + + @pytest.mark.parametrize('boundary', ['journal','selection','public','policy','finish']) + def test_interrupted_policy_publication_restarts_to_a_coherent_state(policy_product, monkeypatch, boundary): + import dc_overview.release_policy as policy + from dc_overview.release_broker import ReleaseBroker + from dc_overview.cli import load_config_from_file + from pathlib import Path + host, service, owner = policy_product + before = snapshot(host, service) +> original_write = policy.private_write + ^^^^^^^^^^^^^^^^^^^^ +E AttributeError: module 'dc_overview.release_policy' has no attribute 'private_write' + +tests/test_release_policy.py:224: AttributeError +_ test_interrupted_policy_publication_restarts_to_a_coherent_state[ltx-selection] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x10d335e80> +boundary = 'selection' + + @pytest.mark.parametrize('boundary', ['journal','selection','public','policy','finish']) + def test_interrupted_policy_publication_restarts_to_a_coherent_state(policy_product, monkeypatch, boundary): + import dc_overview.release_policy as policy + from dc_overview.release_broker import ReleaseBroker + from dc_overview.cli import load_config_from_file + from pathlib import Path + host, service, owner = policy_product + before = snapshot(host, service) +> original_write = policy.private_write + ^^^^^^^^^^^^^^^^^^^^ +E AttributeError: module 'dc_overview.release_policy' has no attribute 'private_write' + +tests/test_release_policy.py:224: AttributeError +_ test_interrupted_policy_publication_restarts_to_a_coherent_state[ltx-public] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x10d209f10> +boundary = 'public' + + @pytest.mark.parametrize('boundary', ['journal','selection','public','policy','finish']) + def test_interrupted_policy_publication_restarts_to_a_coherent_state(policy_product, monkeypatch, boundary): + import dc_overview.release_policy as policy + from dc_overview.release_broker import ReleaseBroker + from dc_overview.cli import load_config_from_file + from pathlib import Path + host, service, owner = policy_product + before = snapshot(host, service) +> original_write = policy.private_write + ^^^^^^^^^^^^^^^^^^^^ +E AttributeError: module 'dc_overview.release_policy' has no attribute 'private_write' + +tests/test_release_policy.py:224: AttributeError +_ test_interrupted_policy_publication_restarts_to_a_coherent_state[ltx-policy] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x10d3373e0> +boundary = 'policy' + + @pytest.mark.parametrize('boundary', ['journal','selection','public','policy','finish']) + def test_interrupted_policy_publication_restarts_to_a_coherent_state(policy_product, monkeypatch, boundary): + import dc_overview.release_policy as policy + from dc_overview.release_broker import ReleaseBroker + from dc_overview.cli import load_config_from_file + from pathlib import Path + host, service, owner = policy_product + before = snapshot(host, service) +> original_write = policy.private_write + ^^^^^^^^^^^^^^^^^^^^ +E AttributeError: module 'dc_overview.release_policy' has no attribute 'private_write' + +tests/test_release_policy.py:224: AttributeError +_ test_interrupted_policy_publication_restarts_to_a_coherent_state[ltx-finish] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x10d438da0> +boundary = 'finish' + + @pytest.mark.parametrize('boundary', ['journal','selection','public','policy','finish']) + def test_interrupted_policy_publication_restarts_to_a_coherent_state(policy_product, monkeypatch, boundary): + import dc_overview.release_policy as policy + from dc_overview.release_broker import ReleaseBroker + from dc_overview.cli import load_config_from_file + from pathlib import Path + host, service, owner = policy_product + before = snapshot(host, service) +> original_write = policy.private_write + ^^^^^^^^^^^^^^^^^^^^ +E AttributeError: module 'dc_overview.release_policy' has no attribute 'private_write' + +tests/test_release_policy.py:224: AttributeError +_ test_interrupted_policy_publication_restarts_to_a_coherent_state[charlotte-journal] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x10d438ef0> +boundary = 'journal' + + @pytest.mark.parametrize('boundary', ['journal','selection','public','policy','finish']) + def test_interrupted_policy_publication_restarts_to_a_coherent_state(policy_product, monkeypatch, boundary): + import dc_overview.release_policy as policy + from dc_overview.release_broker import ReleaseBroker + from dc_overview.cli import load_config_from_file + from pathlib import Path + host, service, owner = policy_product + before = snapshot(host, service) +> original_write = policy.private_write + ^^^^^^^^^^^^^^^^^^^^ +E AttributeError: module 'dc_overview.release_policy' has no attribute 'private_write' + +tests/test_release_policy.py:224: AttributeError +_ test_interrupted_policy_publication_restarts_to_a_coherent_state[charlotte-selection] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x10d45f230> +boundary = 'selection' + + @pytest.mark.parametrize('boundary', ['journal','selection','public','policy','finish']) + def test_interrupted_policy_publication_restarts_to_a_coherent_state(policy_product, monkeypatch, boundary): + import dc_overview.release_policy as policy + from dc_overview.release_broker import ReleaseBroker + from dc_overview.cli import load_config_from_file + from pathlib import Path + host, service, owner = policy_product + before = snapshot(host, service) +> original_write = policy.private_write + ^^^^^^^^^^^^^^^^^^^^ +E AttributeError: module 'dc_overview.release_policy' has no attribute 'private_write' + +tests/test_release_policy.py:224: AttributeError +_ test_interrupted_policy_publication_restarts_to_a_coherent_state[charlotte-public] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x10d1c5be0> +boundary = 'public' + + @pytest.mark.parametrize('boundary', ['journal','selection','public','policy','finish']) + def test_interrupted_policy_publication_restarts_to_a_coherent_state(policy_product, monkeypatch, boundary): + import dc_overview.release_policy as policy + from dc_overview.release_broker import ReleaseBroker + from dc_overview.cli import load_config_from_file + from pathlib import Path + host, service, owner = policy_product + before = snapshot(host, service) +> original_write = policy.private_write + ^^^^^^^^^^^^^^^^^^^^ +E AttributeError: module 'dc_overview.release_policy' has no attribute 'private_write' + +tests/test_release_policy.py:224: AttributeError +_ test_interrupted_policy_publication_restarts_to_a_coherent_state[charlotte-policy] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x10d2013a0> +boundary = 'policy' + + @pytest.mark.parametrize('boundary', ['journal','selection','public','policy','finish']) + def test_interrupted_policy_publication_restarts_to_a_coherent_state(policy_product, monkeypatch, boundary): + import dc_overview.release_policy as policy + from dc_overview.release_broker import ReleaseBroker + from dc_overview.cli import load_config_from_file + from pathlib import Path + host, service, owner = policy_product + before = snapshot(host, service) +> original_write = policy.private_write + ^^^^^^^^^^^^^^^^^^^^ +E AttributeError: module 'dc_overview.release_policy' has no attribute 'private_write' + +tests/test_release_policy.py:224: AttributeError +_ test_interrupted_policy_publication_restarts_to_a_coherent_state[charlotte-finish] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x10d299e80> +boundary = 'finish' + + @pytest.mark.parametrize('boundary', ['journal','selection','public','policy','finish']) + def test_interrupted_policy_publication_restarts_to_a_coherent_state(policy_product, monkeypatch, boundary): + import dc_overview.release_policy as policy + from dc_overview.release_broker import ReleaseBroker + from dc_overview.cli import load_config_from_file + from pathlib import Path + host, service, owner = policy_product + before = snapshot(host, service) +> original_write = policy.private_write + ^^^^^^^^^^^^^^^^^^^^ +E AttributeError: module 'dc_overview.release_policy' has no attribute 'private_write' + +tests/test_release_policy.py:224: AttributeError +___ test_refresh_and_repin_are_serialized_and_stale_refresh_cannot_win[ltx] ____ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +admitted = {'times': {'issued_at': '2026-11-04T16:43:22.521231+00:00', 'expires_at': '2026-11-04T16:45:32.521231+00:00'}, 'produc...5f78aa83378151c915c9893f6e83c8258e612cf0e812a92f97', 'verify': .verify at 0x10d1b5940>, ...} + + def test_refresh_and_repin_are_serialized_and_stale_refresh_cannot_win(policy_product, admitted): + import threading + from dc_overview.release_broker import ReleaseBroker,BrokerError + from dc_overview.cli import load_config_from_file + host, service, owner = policy_product +> set_mode(service,'follow-stable') + +tests/test_release_policy.py:269: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '686172db625bed42d2fd2b63c6fa43b6fa22322e4f019bae4ef9679537c7521f'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_ test_refresh_and_repin_are_serialized_and_stale_refresh_cannot_win[charlotte] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +admitted = {'times': {'issued_at': '2026-11-04T16:43:22.542786+00:00', 'expires_at': '2026-11-04T16:45:32.542786+00:00'}, 'produc...cb2fee2eedeaaf59ab9521073f14ebb4afed359708d54d28ca', 'verify': .verify at 0x10d282e80>, ...} + + def test_refresh_and_repin_are_serialized_and_stale_refresh_cannot_win(policy_product, admitted): + import threading + from dc_overview.release_broker import ReleaseBroker,BrokerError + from dc_overview.cli import load_config_from_file + host, service, owner = policy_product +> set_mode(service,'follow-stable') + +tests/test_release_policy.py:269: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +tests/test_release_policy.py:86: in set_mode + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_broker.py:521: in dispatch + validate_params(action, params) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'old', 'expected_selection_sha256': '7f0ed032b41772c6aa18c81f0a70d8a2509ebffa8a2d579e9b660fd003f98b69'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +___ test_installed_pin_requires_exact_known_component_artifact[ltx-missing] ____ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +fault = 'missing' + + @pytest.mark.parametrize('fault',['missing','wrong-component','version-conflict','unregistered-image']) + def test_installed_pin_requires_exact_known_component_artifact(policy_product,fault): + host,service,owner=policy_product + current=host.store.load();reference=current.targets['grafana']['reference'] + image={'Id':'sha256:'+'e'*64,'Os':'linux','Architecture':'amd64', + 'RepoDigests':[reference], 'Config':{'Labels':{'org.opencontainers.image.version':'1.4.0'}}} + live={'Id':'d'*64,'Image':image['Id'],'State':{'Running':True},'Config':{'Image':reference}} + if fault=='missing': live['State']['Running']=False + if fault=='wrong-component': image['RepoDigests']=['prom/prometheus@sha256:'+'a'*64] + if fault=='version-conflict': image['Config']['Labels']['org.opencontainers.image.version']='1.9.0' + if fault=='unregistered-image': image['RepoDigests']=['grafana/grafana@sha256:'+'f'*64] + inspect=lambda name:live if name=='grafana' else image +> assert policy_module().installed_component(current,'grafana',host.store,inspect) is None + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +E AttributeError: module 'dc_overview.release_policy' has no attribute 'installed_component' + +tests/test_release_policy.py:305: AttributeError +_ test_installed_pin_requires_exact_known_component_artifact[ltx-wrong-component] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +fault = 'wrong-component' + + @pytest.mark.parametrize('fault',['missing','wrong-component','version-conflict','unregistered-image']) + def test_installed_pin_requires_exact_known_component_artifact(policy_product,fault): + host,service,owner=policy_product + current=host.store.load();reference=current.targets['grafana']['reference'] + image={'Id':'sha256:'+'e'*64,'Os':'linux','Architecture':'amd64', + 'RepoDigests':[reference], 'Config':{'Labels':{'org.opencontainers.image.version':'1.4.0'}}} + live={'Id':'d'*64,'Image':image['Id'],'State':{'Running':True},'Config':{'Image':reference}} + if fault=='missing': live['State']['Running']=False + if fault=='wrong-component': image['RepoDigests']=['prom/prometheus@sha256:'+'a'*64] + if fault=='version-conflict': image['Config']['Labels']['org.opencontainers.image.version']='1.9.0' + if fault=='unregistered-image': image['RepoDigests']=['grafana/grafana@sha256:'+'f'*64] + inspect=lambda name:live if name=='grafana' else image +> assert policy_module().installed_component(current,'grafana',host.store,inspect) is None + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +E AttributeError: module 'dc_overview.release_policy' has no attribute 'installed_component' + +tests/test_release_policy.py:305: AttributeError +_ test_installed_pin_requires_exact_known_component_artifact[ltx-version-conflict] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +fault = 'version-conflict' + + @pytest.mark.parametrize('fault',['missing','wrong-component','version-conflict','unregistered-image']) + def test_installed_pin_requires_exact_known_component_artifact(policy_product,fault): + host,service,owner=policy_product + current=host.store.load();reference=current.targets['grafana']['reference'] + image={'Id':'sha256:'+'e'*64,'Os':'linux','Architecture':'amd64', + 'RepoDigests':[reference], 'Config':{'Labels':{'org.opencontainers.image.version':'1.4.0'}}} + live={'Id':'d'*64,'Image':image['Id'],'State':{'Running':True},'Config':{'Image':reference}} + if fault=='missing': live['State']['Running']=False + if fault=='wrong-component': image['RepoDigests']=['prom/prometheus@sha256:'+'a'*64] + if fault=='version-conflict': image['Config']['Labels']['org.opencontainers.image.version']='1.9.0' + if fault=='unregistered-image': image['RepoDigests']=['grafana/grafana@sha256:'+'f'*64] + inspect=lambda name:live if name=='grafana' else image +> assert policy_module().installed_component(current,'grafana',host.store,inspect) is None + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +E AttributeError: module 'dc_overview.release_policy' has no attribute 'installed_component' + +tests/test_release_policy.py:305: AttributeError +_ test_installed_pin_requires_exact_known_component_artifact[ltx-unregistered-image] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +fault = 'unregistered-image' + + @pytest.mark.parametrize('fault',['missing','wrong-component','version-conflict','unregistered-image']) + def test_installed_pin_requires_exact_known_component_artifact(policy_product,fault): + host,service,owner=policy_product + current=host.store.load();reference=current.targets['grafana']['reference'] + image={'Id':'sha256:'+'e'*64,'Os':'linux','Architecture':'amd64', + 'RepoDigests':[reference], 'Config':{'Labels':{'org.opencontainers.image.version':'1.4.0'}}} + live={'Id':'d'*64,'Image':image['Id'],'State':{'Running':True},'Config':{'Image':reference}} + if fault=='missing': live['State']['Running']=False + if fault=='wrong-component': image['RepoDigests']=['prom/prometheus@sha256:'+'a'*64] + if fault=='version-conflict': image['Config']['Labels']['org.opencontainers.image.version']='1.9.0' + if fault=='unregistered-image': image['RepoDigests']=['grafana/grafana@sha256:'+'f'*64] + inspect=lambda name:live if name=='grafana' else image +> assert policy_module().installed_component(current,'grafana',host.store,inspect) is None + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +E AttributeError: module 'dc_overview.release_policy' has no attribute 'installed_component' + +tests/test_release_policy.py:305: AttributeError +_ test_installed_pin_requires_exact_known_component_artifact[charlotte-missing] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +fault = 'missing' + + @pytest.mark.parametrize('fault',['missing','wrong-component','version-conflict','unregistered-image']) + def test_installed_pin_requires_exact_known_component_artifact(policy_product,fault): + host,service,owner=policy_product + current=host.store.load();reference=current.targets['grafana']['reference'] + image={'Id':'sha256:'+'e'*64,'Os':'linux','Architecture':'amd64', + 'RepoDigests':[reference], 'Config':{'Labels':{'org.opencontainers.image.version':'1.4.0'}}} + live={'Id':'d'*64,'Image':image['Id'],'State':{'Running':True},'Config':{'Image':reference}} + if fault=='missing': live['State']['Running']=False + if fault=='wrong-component': image['RepoDigests']=['prom/prometheus@sha256:'+'a'*64] + if fault=='version-conflict': image['Config']['Labels']['org.opencontainers.image.version']='1.9.0' + if fault=='unregistered-image': image['RepoDigests']=['grafana/grafana@sha256:'+'f'*64] + inspect=lambda name:live if name=='grafana' else image +> assert policy_module().installed_component(current,'grafana',host.store,inspect) is None + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +E AttributeError: module 'dc_overview.release_policy' has no attribute 'installed_component' + +tests/test_release_policy.py:305: AttributeError +_ test_installed_pin_requires_exact_known_component_artifact[charlotte-wrong-component] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +fault = 'wrong-component' + + @pytest.mark.parametrize('fault',['missing','wrong-component','version-conflict','unregistered-image']) + def test_installed_pin_requires_exact_known_component_artifact(policy_product,fault): + host,service,owner=policy_product + current=host.store.load();reference=current.targets['grafana']['reference'] + image={'Id':'sha256:'+'e'*64,'Os':'linux','Architecture':'amd64', + 'RepoDigests':[reference], 'Config':{'Labels':{'org.opencontainers.image.version':'1.4.0'}}} + live={'Id':'d'*64,'Image':image['Id'],'State':{'Running':True},'Config':{'Image':reference}} + if fault=='missing': live['State']['Running']=False + if fault=='wrong-component': image['RepoDigests']=['prom/prometheus@sha256:'+'a'*64] + if fault=='version-conflict': image['Config']['Labels']['org.opencontainers.image.version']='1.9.0' + if fault=='unregistered-image': image['RepoDigests']=['grafana/grafana@sha256:'+'f'*64] + inspect=lambda name:live if name=='grafana' else image +> assert policy_module().installed_component(current,'grafana',host.store,inspect) is None + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +E AttributeError: module 'dc_overview.release_policy' has no attribute 'installed_component' + +tests/test_release_policy.py:305: AttributeError +_ test_installed_pin_requires_exact_known_component_artifact[charlotte-version-conflict] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +fault = 'version-conflict' + + @pytest.mark.parametrize('fault',['missing','wrong-component','version-conflict','unregistered-image']) + def test_installed_pin_requires_exact_known_component_artifact(policy_product,fault): + host,service,owner=policy_product + current=host.store.load();reference=current.targets['grafana']['reference'] + image={'Id':'sha256:'+'e'*64,'Os':'linux','Architecture':'amd64', + 'RepoDigests':[reference], 'Config':{'Labels':{'org.opencontainers.image.version':'1.4.0'}}} + live={'Id':'d'*64,'Image':image['Id'],'State':{'Running':True},'Config':{'Image':reference}} + if fault=='missing': live['State']['Running']=False + if fault=='wrong-component': image['RepoDigests']=['prom/prometheus@sha256:'+'a'*64] + if fault=='version-conflict': image['Config']['Labels']['org.opencontainers.image.version']='1.9.0' + if fault=='unregistered-image': image['RepoDigests']=['grafana/grafana@sha256:'+'f'*64] + inspect=lambda name:live if name=='grafana' else image +> assert policy_module().installed_component(current,'grafana',host.store,inspect) is None + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +E AttributeError: module 'dc_overview.release_policy' has no attribute 'installed_component' + +tests/test_release_policy.py:305: AttributeError +_ test_installed_pin_requires_exact_known_component_artifact[charlotte-unregistered-image] _ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +fault = 'unregistered-image' + + @pytest.mark.parametrize('fault',['missing','wrong-component','version-conflict','unregistered-image']) + def test_installed_pin_requires_exact_known_component_artifact(policy_product,fault): + host,service,owner=policy_product + current=host.store.load();reference=current.targets['grafana']['reference'] + image={'Id':'sha256:'+'e'*64,'Os':'linux','Architecture':'amd64', + 'RepoDigests':[reference], 'Config':{'Labels':{'org.opencontainers.image.version':'1.4.0'}}} + live={'Id':'d'*64,'Image':image['Id'],'State':{'Running':True},'Config':{'Image':reference}} + if fault=='missing': live['State']['Running']=False + if fault=='wrong-component': image['RepoDigests']=['prom/prometheus@sha256:'+'a'*64] + if fault=='version-conflict': image['Config']['Labels']['org.opencontainers.image.version']='1.9.0' + if fault=='unregistered-image': image['RepoDigests']=['grafana/grafana@sha256:'+'f'*64] + inspect=lambda name:live if name=='grafana' else image +> assert policy_module().installed_component(current,'grafana',host.store,inspect) is None + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +E AttributeError: module 'dc_overview.release_policy' has no attribute 'installed_component' + +tests/test_release_policy.py:305: AttributeError +___________ test_native_policy_cli_uses_the_same_owner_contract[ltx] ___________ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x10d14a420> + + def test_native_policy_cli_uses_the_same_owner_contract(policy_product,monkeypatch): + from click.testing import CliRunner + from dc_overview.cli import main + from dc_overview import release_broker_service + host,service,owner=policy_product;calls=[] + monkeypatch.setattr(release_broker_service,'request',lambda action,params:calls.append((action,params)) or {'components':{}}) + runner=CliRunner() + result=runner.invoke(main,['release','policy-set','--component','grafana','--mode','follow-stable', + '--expected-selection-id','fixture','--expected-selection-sha256','a'*64]) +> assert result.exit_code==0,result.output +E AssertionError: Usage: main release [OPTIONS] COMMAND [ARGS]... +E Try 'main release --help' for help. +E +E Error: No such command 'policy-set'. +E +E assert 2 == 0 +E + where 2 = .exit_code + +tests/test_release_policy.py:317: AssertionError +________ test_native_policy_cli_uses_the_same_owner_contract[charlotte] ________ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x10d438830> + + def test_native_policy_cli_uses_the_same_owner_contract(policy_product,monkeypatch): + from click.testing import CliRunner + from dc_overview.cli import main + from dc_overview import release_broker_service + host,service,owner=policy_product;calls=[] + monkeypatch.setattr(release_broker_service,'request',lambda action,params:calls.append((action,params)) or {'components':{}}) + runner=CliRunner() + result=runner.invoke(main,['release','policy-set','--component','grafana','--mode','follow-stable', + '--expected-selection-id','fixture','--expected-selection-sha256','a'*64]) +> assert result.exit_code==0,result.output +E AssertionError: Usage: main release [OPTIONS] COMMAND [ARGS]... +E Try 'main release --help' for help. +E +E Error: No such command 'policy-set'. +E +E assert 2 == 0 +E + where 2 = .exit_code + +tests/test_release_policy.py:317: AssertionError +_______ test_broker_policy_params_are_strict_supported_actions[change0] ________ + +change = {'mode': True} + + @pytest.mark.parametrize('change',[{'mode':True},{'mode':'latest'},{'component':'../ipmi-monitor'}, + {'expected_selection_sha256':'a'}, {'path':'/etc/passwd'}, {'actor':{'kind':'host-peer','uid':0}}]) + def test_broker_policy_params_are_strict_supported_actions(change): + from dc_overview.release_broker import validate_params + body={'component':'grafana','mode':'follow-stable','expected_selection_id':'fixture','expected_selection_sha256':'a'*64} +> validate_params('policy-set',body) # Positive control prevents an unknown-action false pass. + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +tests/test_release_policy.py:326: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'fixture', 'expected_selection_sha256': 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_______ test_broker_policy_params_are_strict_supported_actions[change1] ________ + +change = {'mode': 'latest'} + + @pytest.mark.parametrize('change',[{'mode':True},{'mode':'latest'},{'component':'../ipmi-monitor'}, + {'expected_selection_sha256':'a'}, {'path':'/etc/passwd'}, {'actor':{'kind':'host-peer','uid':0}}]) + def test_broker_policy_params_are_strict_supported_actions(change): + from dc_overview.release_broker import validate_params + body={'component':'grafana','mode':'follow-stable','expected_selection_id':'fixture','expected_selection_sha256':'a'*64} +> validate_params('policy-set',body) # Positive control prevents an unknown-action false pass. + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +tests/test_release_policy.py:326: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'fixture', 'expected_selection_sha256': 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_______ test_broker_policy_params_are_strict_supported_actions[change2] ________ + +change = {'component': '../ipmi-monitor'} + + @pytest.mark.parametrize('change',[{'mode':True},{'mode':'latest'},{'component':'../ipmi-monitor'}, + {'expected_selection_sha256':'a'}, {'path':'/etc/passwd'}, {'actor':{'kind':'host-peer','uid':0}}]) + def test_broker_policy_params_are_strict_supported_actions(change): + from dc_overview.release_broker import validate_params + body={'component':'grafana','mode':'follow-stable','expected_selection_id':'fixture','expected_selection_sha256':'a'*64} +> validate_params('policy-set',body) # Positive control prevents an unknown-action false pass. + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +tests/test_release_policy.py:326: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'fixture', 'expected_selection_sha256': 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_______ test_broker_policy_params_are_strict_supported_actions[change3] ________ + +change = {'expected_selection_sha256': 'a'} + + @pytest.mark.parametrize('change',[{'mode':True},{'mode':'latest'},{'component':'../ipmi-monitor'}, + {'expected_selection_sha256':'a'}, {'path':'/etc/passwd'}, {'actor':{'kind':'host-peer','uid':0}}]) + def test_broker_policy_params_are_strict_supported_actions(change): + from dc_overview.release_broker import validate_params + body={'component':'grafana','mode':'follow-stable','expected_selection_id':'fixture','expected_selection_sha256':'a'*64} +> validate_params('policy-set',body) # Positive control prevents an unknown-action false pass. + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +tests/test_release_policy.py:326: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'fixture', 'expected_selection_sha256': 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_______ test_broker_policy_params_are_strict_supported_actions[change4] ________ + +change = {'path': '/etc/passwd'} + + @pytest.mark.parametrize('change',[{'mode':True},{'mode':'latest'},{'component':'../ipmi-monitor'}, + {'expected_selection_sha256':'a'}, {'path':'/etc/passwd'}, {'actor':{'kind':'host-peer','uid':0}}]) + def test_broker_policy_params_are_strict_supported_actions(change): + from dc_overview.release_broker import validate_params + body={'component':'grafana','mode':'follow-stable','expected_selection_id':'fixture','expected_selection_sha256':'a'*64} +> validate_params('policy-set',body) # Positive control prevents an unknown-action false pass. + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +tests/test_release_policy.py:326: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'fixture', 'expected_selection_sha256': 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_______ test_broker_policy_params_are_strict_supported_actions[change5] ________ + +change = {'actor': {'kind': 'host-peer', 'uid': 0}} + + @pytest.mark.parametrize('change',[{'mode':True},{'mode':'latest'},{'component':'../ipmi-monitor'}, + {'expected_selection_sha256':'a'}, {'path':'/etc/passwd'}, {'actor':{'kind':'host-peer','uid':0}}]) + def test_broker_policy_params_are_strict_supported_actions(change): + from dc_overview.release_broker import validate_params + body={'component':'grafana','mode':'follow-stable','expected_selection_id':'fixture','expected_selection_sha256':'a'*64} +> validate_params('policy-set',body) # Positive control prevents an unknown-action false pass. + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +tests/test_release_policy.py:326: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +action = 'policy-set' +params = {'component': 'grafana', 'mode': 'follow-stable', 'expected_selection_id': 'fixture', 'expected_selection_sha256': 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'} + + def validate_params(action, params): + fields = { + "list": {"channel"}, + "preview": { + "candidate_ids", + "components", + "expected_selection_id", + "expected_selection_sha256", + "operation_kind", + }, + "apply": { + "operation_id", + "preview_id", + "preview_sha256", + "expected_selection_id", + "expected_selection_sha256", + }, + "status": {"operation_id"}, + "recover": {"operation_id"}, + } + if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: +> raise ValueError("invalid release request fields") +E ValueError: invalid release request fields + +src/dc_overview/release_broker.py:93: ValueError +_________ test_daily_timer_install_uses_only_fixed_packaged_units[ltx] _________ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +tmp_path = PosixPath('/private/var/folders/2f/ntb_0p9558v4wfcwr5_64dg00000gn/T/pytest-of-hanneszietsman/pytest-10193/test_daily_timer_install_uses_0') +monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x10d22cc80> + + def test_daily_timer_install_uses_only_fixed_packaged_units(policy_product,tmp_path,monkeypatch): + from pathlib import Path + policy=policy_module();calls=[] +> monkeypatch.setattr(policy,'SYSTEMD_DIR',tmp_path/'units') +E AttributeError: has no attribute 'SYSTEMD_DIR' + +tests/test_release_policy.py:345: AttributeError +______ test_daily_timer_install_uses_only_fixed_packaged_units[charlotte] ______ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +tmp_path = PosixPath('/private/var/folders/2f/ntb_0p9558v4wfcwr5_64dg00000gn/T/pytest-of-hanneszietsman/pytest-10193/test_daily_timer_install_uses_1') +monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x10d43a1e0> + + def test_daily_timer_install_uses_only_fixed_packaged_units(policy_product,tmp_path,monkeypatch): + from pathlib import Path + policy=policy_module();calls=[] +> monkeypatch.setattr(policy,'SYSTEMD_DIR',tmp_path/'units') +E AttributeError: has no attribute 'SYSTEMD_DIR' + +tests/test_release_policy.py:345: AttributeError +_________ test_cli_and_packaging_include_the_daily_policy_only_refresh _________ + + def test_cli_and_packaging_include_the_daily_policy_only_refresh(): + from pathlib import Path + root = Path(__file__).resolve().parents[1] +> timer = (root / "src/dc_overview/templates/systemd/dc-overview-release-refresh.timer").read_text() + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +tests/test_release_policy.py:358: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +/Users/hanneszietsman/.local/share/uv/python/cpython-3.12.12-macos-aarch64-none/lib/python3.12/pathlib.py:1027: in read_text + with self.open(mode='r', encoding=encoding, errors=errors) as f: + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +self = PosixPath('/private/tmp/ltx-auto-advance-20261104/dc-overview/src/dc_overview/templates/systemd/dc-overview-release-refresh.timer') +mode = 'r', buffering = -1, encoding = 'locale', errors = None, newline = None + + def open(self, mode='r', buffering=-1, encoding=None, + errors=None, newline=None): + """ + Open the file pointed to by this path and return a file object, as + the built-in open() function does. + """ + if "b" not in mode: + encoding = io.text_encoding(encoding) +> return io.open(self, mode, buffering, encoding, errors, newline) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +E FileNotFoundError: [Errno 2] No such file or directory: '/private/tmp/ltx-auto-advance-20261104/dc-overview/src/dc_overview/templates/systemd/dc-overview-release-refresh.timer' + +/Users/hanneszietsman/.local/share/uv/python/cpython-3.12.12-macos-aarch64-none/lib/python3.12/pathlib.py:1013: FileNotFoundError +=========================== short test summary info ============================ +FAILED tests/test_release_policy.py::test_existing_components_default_pinned_with_no_implicit_follow[ltx] +FAILED tests/test_release_policy.py::test_existing_components_default_pinned_with_no_implicit_follow[charlotte] +FAILED tests/test_release_policy.py::test_unpin_survives_restart_and_changes_only_one_policy_without_install[ltx] +FAILED tests/test_release_policy.py::test_unpin_survives_restart_and_changes_only_one_policy_without_install[charlotte] +FAILED tests/test_release_policy.py::test_refresh_only_advances_opted_in_service_and_repin_installed_freezes_it[ltx] +FAILED tests/test_release_policy.py::test_refresh_only_advances_opted_in_service_and_repin_installed_freezes_it[charlotte] +FAILED tests/test_release_policy.py::test_mode_failure_has_no_partial_policy_or_selection_change[ltx-stale] +FAILED tests/test_release_policy.py::test_mode_failure_has_no_partial_policy_or_selection_change[ltx-busy] +FAILED tests/test_release_policy.py::test_mode_failure_has_no_partial_policy_or_selection_change[ltx-disabled] +FAILED tests/test_release_policy.py::test_mode_failure_has_no_partial_policy_or_selection_change[ltx-unproven-installed] +FAILED tests/test_release_policy.py::test_mode_failure_has_no_partial_policy_or_selection_change[charlotte-stale] +FAILED tests/test_release_policy.py::test_mode_failure_has_no_partial_policy_or_selection_change[charlotte-busy] +FAILED tests/test_release_policy.py::test_mode_failure_has_no_partial_policy_or_selection_change[charlotte-disabled] +FAILED tests/test_release_policy.py::test_mode_failure_has_no_partial_policy_or_selection_change[charlotte-unproven-installed] +FAILED tests/test_release_policy.py::test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure[ltx-signature] +FAILED tests/test_release_policy.py::test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure[ltx-expired] +FAILED tests/test_release_policy.py::test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure[ltx-revoked] +FAILED tests/test_release_policy.py::test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure[ltx-replay] +FAILED tests/test_release_policy.py::test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure[ltx-digest] +FAILED tests/test_release_policy.py::test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure[ltx-unavailable] +FAILED tests/test_release_policy.py::test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure[charlotte-signature] +FAILED tests/test_release_policy.py::test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure[charlotte-expired] +FAILED tests/test_release_policy.py::test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure[charlotte-revoked] +FAILED tests/test_release_policy.py::test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure[charlotte-replay] +FAILED tests/test_release_policy.py::test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure[charlotte-digest] +FAILED tests/test_release_policy.py::test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure[charlotte-unavailable] +FAILED tests/test_release_policy.py::test_repeated_check_never_downgrades_an_already_pending_target[ltx] +FAILED tests/test_release_policy.py::test_repeated_check_never_downgrades_an_already_pending_target[charlotte] +FAILED tests/test_release_policy.py::test_interrupted_policy_publication_restarts_to_a_coherent_state[ltx-journal] +FAILED tests/test_release_policy.py::test_interrupted_policy_publication_restarts_to_a_coherent_state[ltx-selection] +FAILED tests/test_release_policy.py::test_interrupted_policy_publication_restarts_to_a_coherent_state[ltx-public] +FAILED tests/test_release_policy.py::test_interrupted_policy_publication_restarts_to_a_coherent_state[ltx-policy] +FAILED tests/test_release_policy.py::test_interrupted_policy_publication_restarts_to_a_coherent_state[ltx-finish] +FAILED tests/test_release_policy.py::test_interrupted_policy_publication_restarts_to_a_coherent_state[charlotte-journal] +FAILED tests/test_release_policy.py::test_interrupted_policy_publication_restarts_to_a_coherent_state[charlotte-selection] +FAILED tests/test_release_policy.py::test_interrupted_policy_publication_restarts_to_a_coherent_state[charlotte-public] +FAILED tests/test_release_policy.py::test_interrupted_policy_publication_restarts_to_a_coherent_state[charlotte-policy] +FAILED tests/test_release_policy.py::test_interrupted_policy_publication_restarts_to_a_coherent_state[charlotte-finish] +FAILED tests/test_release_policy.py::test_refresh_and_repin_are_serialized_and_stale_refresh_cannot_win[ltx] +FAILED tests/test_release_policy.py::test_refresh_and_repin_are_serialized_and_stale_refresh_cannot_win[charlotte] +FAILED tests/test_release_policy.py::test_installed_pin_requires_exact_known_component_artifact[ltx-missing] +FAILED tests/test_release_policy.py::test_installed_pin_requires_exact_known_component_artifact[ltx-wrong-component] +FAILED tests/test_release_policy.py::test_installed_pin_requires_exact_known_component_artifact[ltx-version-conflict] +FAILED tests/test_release_policy.py::test_installed_pin_requires_exact_known_component_artifact[ltx-unregistered-image] +FAILED tests/test_release_policy.py::test_installed_pin_requires_exact_known_component_artifact[charlotte-missing] +FAILED tests/test_release_policy.py::test_installed_pin_requires_exact_known_component_artifact[charlotte-wrong-component] +FAILED tests/test_release_policy.py::test_installed_pin_requires_exact_known_component_artifact[charlotte-version-conflict] +FAILED tests/test_release_policy.py::test_installed_pin_requires_exact_known_component_artifact[charlotte-unregistered-image] +FAILED tests/test_release_policy.py::test_native_policy_cli_uses_the_same_owner_contract[ltx] +FAILED tests/test_release_policy.py::test_native_policy_cli_uses_the_same_owner_contract[charlotte] +FAILED tests/test_release_policy.py::test_broker_policy_params_are_strict_supported_actions[change0] +FAILED tests/test_release_policy.py::test_broker_policy_params_are_strict_supported_actions[change1] +FAILED tests/test_release_policy.py::test_broker_policy_params_are_strict_supported_actions[change2] +FAILED tests/test_release_policy.py::test_broker_policy_params_are_strict_supported_actions[change3] +FAILED tests/test_release_policy.py::test_broker_policy_params_are_strict_supported_actions[change4] +FAILED tests/test_release_policy.py::test_broker_policy_params_are_strict_supported_actions[change5] +FAILED tests/test_release_policy.py::test_daily_timer_install_uses_only_fixed_packaged_units[ltx] +FAILED tests/test_release_policy.py::test_daily_timer_install_uses_only_fixed_packaged_units[charlotte] +FAILED tests/test_release_policy.py::test_cli_and_packaging_include_the_daily_policy_only_refresh +59 failed, 16 passed in 1.60s diff --git a/.traceweaver/auto-advance-20261104/red-precommit.log b/.traceweaver/auto-advance-20261104/red-precommit.log new file mode 100644 index 0000000..350cf60 --- /dev/null +++ b/.traceweaver/auto-advance-20261104/red-precommit.log @@ -0,0 +1,156 @@ +FFFF.. [100%] +=================================== FAILURES =================================== +______ test_policy_refresh_revalidates_admission_at_native_precommit[ltx] ______ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +admitted = {'times': {'issued_at': '2026-11-04T16:54:49.555038+00:00', 'expires_at': '2026-11-04T16:56:59.555038+00:00'}, 'produc...6524a39e7fdbf60671ceee163092ef364a73c8aa68ba5ba02b', 'verify': .verify at 0x10b4447c0>, ...} +monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x10b481ee0> + + def test_policy_refresh_revalidates_admission_at_native_precommit(policy_product,admitted,monkeypatch): + import dc_overview.release_policy as policy + from dc_overview import fleet_upgrade + host,service,owner=policy_product + set_mode(service,'follow-stable');before=snapshot(host,service) + service.discovery=lambda:[admitted_version(admitted,'1.5.0')] + original=fleet_upgrade.select_release_components;verified=[] + def expire_at_precommit(*args,**kwargs): + check=kwargs.get('precommit_check') + assert callable(check), 'publication must carry a freshness and policy-intent check' + def expired(*args,**kwargs): + verified.append(True);raise ValueError('admission expired before publication') + with monkeypatch.context() as m: + m.setattr(policy,'verify_candidate',expired) + return original(*args,**kwargs) + monkeypatch.setattr(fleet_upgrade,'select_release_components',expire_at_precommit) +> with pytest.raises(ValueError): service.dispatch('policy-refresh',expected(service),actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +tests/test_release_policy.py:390: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +src/dc_overview/release_broker.py:539: in dispatch + return PolicyManager(self).dispatch(action, params) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_policy.py:236: in dispatch + self._publish(current, state, state, changes, {n: {"origin": "baseline", "enabled": True} for n in changes}) +src/dc_overview/release_policy.py:257: in _publish + select_release_components(self.broker.config, path, tuple(changes), platform=current.platform, +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +args = (FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=ComponentConfig(dc_o...nneszietsman/pytest-10201/test_policy_refresh_revalidate0/config/releases/broker/policy-candidate.json'), ('grafana',)) +kwargs = {'platform': 'linux/amd64', 'expected_selection_id': 'policy-11a4f6b2bc5e41eab86eaa57a36bd8a0', 'expected_selection_sh...ef29144784a78497195b40c7494f87bc5d9cdd9ea3ba5ce9187a5a80', 'operation_id': '4b4813d3-b72a-4a77-adb5-3df17f6b141a', ...} + + def expire_at_precommit(*args,**kwargs): + check=kwargs.get('precommit_check') +> assert callable(check), 'publication must carry a freshness and policy-intent check' +E AssertionError: publication must carry a freshness and policy-intent check +E assert False +E + where False = callable(None) + +tests/test_release_policy.py:383: AssertionError +___ test_policy_refresh_revalidates_admission_at_native_precommit[charlotte] ___ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +admitted = {'times': {'issued_at': '2026-11-04T16:54:49.618309+00:00', 'expires_at': '2026-11-04T16:56:59.618309+00:00'}, 'produc...f98c0d5a333aaca9d3dd8efcbadc904684bfad8f771ed23bee', 'verify': .verify at 0x10b522f20>, ...} +monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x10b44fa70> + + def test_policy_refresh_revalidates_admission_at_native_precommit(policy_product,admitted,monkeypatch): + import dc_overview.release_policy as policy + from dc_overview import fleet_upgrade + host,service,owner=policy_product + set_mode(service,'follow-stable');before=snapshot(host,service) + service.discovery=lambda:[admitted_version(admitted,'1.5.0')] + original=fleet_upgrade.select_release_components;verified=[] + def expire_at_precommit(*args,**kwargs): + check=kwargs.get('precommit_check') + assert callable(check), 'publication must carry a freshness and policy-intent check' + def expired(*args,**kwargs): + verified.append(True);raise ValueError('admission expired before publication') + with monkeypatch.context() as m: + m.setattr(policy,'verify_candidate',expired) + return original(*args,**kwargs) + monkeypatch.setattr(fleet_upgrade,'select_release_components',expire_at_precommit) +> with pytest.raises(ValueError): service.dispatch('policy-refresh',expected(service),actor=ACTOR) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +tests/test_release_policy.py:390: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +src/dc_overview/release_broker.py:539: in dispatch + return PolicyManager(self).dispatch(action, params) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +src/dc_overview/release_policy.py:236: in dispatch + self._publish(current, state, state, changes, {n: {"origin": "baseline", "enabled": True} for n in changes}) +src/dc_overview/release_policy.py:257: in _publish + select_release_components(self.broker.config, path, tuple(changes), platform=current.platform, +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +args = (FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=ComponentConfig(dc_o...nneszietsman/pytest-10201/test_policy_refresh_revalidate1/config/releases/broker/policy-candidate.json'), ('grafana',)) +kwargs = {'platform': 'linux/amd64', 'expected_selection_id': 'policy-cc147656b7134980948ed822dde2f2ab', 'expected_selection_sh...563c7f1458cf71babbb354278a08564822ae0cef590d76bb1cf0e70d', 'operation_id': '4ce6c4f5-def2-493a-8a9d-b6e008e70c0b', ...} + + def expire_at_precommit(*args,**kwargs): + check=kwargs.get('precommit_check') +> assert callable(check), 'publication must carry a freshness and policy-intent check' +E AssertionError: publication must carry a freshness and policy-intent check +E assert False +E + where False = callable(None) + +tests/test_release_policy.py:383: AssertionError +______ test_unfinished_policy_publication_blocks_other_release_paths[ltx] ______ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x10b4f3d10> + + def test_unfinished_policy_publication_blocks_other_release_paths(policy_product,monkeypatch): + import dc_overview.release_policy as policy + from dc_overview import fleet_upgrade + from dc_overview.release_broker import BrokerError + host,service,owner=policy_product;write=policy.private_write + def fail(path,value): + if path.name=='policy-state.json':raise OSError('interrupted policy write') + return write(path,value) + with monkeypatch.context() as m: + m.setattr(policy,'private_write',fail) + with pytest.raises(OSError):set_mode(service,'follow-stable') + before=host.store.load().selection_raw + with pytest.raises(BrokerError) as error: + service.dispatch('preview',{'candidate_ids':['fixture'],'components':['grafana'], + 'operation_kind':'services-update',**expected(service)},actor=ACTOR) +> assert error.value.code=='recovery-required' +E AssertionError: assert 'unavailable' == 'recovery-required' +E +E - recovery-required +E + unavailable + +tests/test_release_policy.py:409: AssertionError +___ test_unfinished_policy_publication_blocks_other_release_paths[charlotte] ___ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x10b4f2d80> + + def test_unfinished_policy_publication_blocks_other_release_paths(policy_product,monkeypatch): + import dc_overview.release_policy as policy + from dc_overview import fleet_upgrade + from dc_overview.release_broker import BrokerError + host,service,owner=policy_product;write=policy.private_write + def fail(path,value): + if path.name=='policy-state.json':raise OSError('interrupted policy write') + return write(path,value) + with monkeypatch.context() as m: + m.setattr(policy,'private_write',fail) + with pytest.raises(OSError):set_mode(service,'follow-stable') + before=host.store.load().selection_raw + with pytest.raises(BrokerError) as error: + service.dispatch('preview',{'candidate_ids':['fixture'],'components':['grafana'], + 'operation_kind':'services-update',**expected(service)},actor=ACTOR) +> assert error.value.code=='recovery-required' +E AssertionError: assert 'unavailable' == 'recovery-required' +E +E - recovery-required +E + unavailable + +tests/test_release_policy.py:409: AssertionError +=========================== short test summary info ============================ +FAILED tests/test_release_policy.py::test_policy_refresh_revalidates_admission_at_native_precommit[ltx] +FAILED tests/test_release_policy.py::test_policy_refresh_revalidates_admission_at_native_precommit[charlotte] +FAILED tests/test_release_policy.py::test_unfinished_policy_publication_blocks_other_release_paths[ltx] +FAILED tests/test_release_policy.py::test_unfinished_policy_publication_blocks_other_release_paths[charlotte] +4 failed, 2 passed, 79 deselected in 0.58s diff --git a/.traceweaver/auto-advance-20261104/red-review-findings.log b/.traceweaver/auto-advance-20261104/red-review-findings.log new file mode 100644 index 0000000..4ccc53b --- /dev/null +++ b/.traceweaver/auto-advance-20261104/red-review-findings.log @@ -0,0 +1,152 @@ +FFFFFF [100%] +=================================== FAILURES =================================== +_____ test_native_writer_wins_before_journal_without_orphaning_policy[ltx] _____ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x10af9ffb0> + + def test_native_writer_wins_before_journal_without_orphaning_policy(policy_product,monkeypatch): + from dc_overview import fleet_upgrade + from dc_overview.release_broker import BrokerError + policy=policy_module();host,service,owner=policy_product;write=policy.private_write;fired=[] + data=copy.deepcopy(host.store.load().manifest.data);data['baseline_id']='competing-native-writer' + path=host.config.config_dir/'competing.json';path.write_text(json.dumps(data)) + def competing_write(target,value): + if target.name=='policy-candidate.json' and not fired: + fired.append(True) + fleet_upgrade.select_release_components(host.config,path,['grafana'],platform='linux/amd64') + return write(target,value) + with monkeypatch.context() as change: + change.setattr(policy,'private_write',competing_write) + with pytest.raises((BrokerError,RuntimeError,ValueError)):set_mode(service,'follow-stable') + assert fired and host.store.load().selection['selection_id']=='competing-native-writer' +> assert not (service.root/'policy-publication.json').exists() +E AssertionError: assert not True +E + where True = exists() +E + where exists = (PosixPath('/private/var/folders/2f/ntb_0p9558v4wfcwr5_64dg00000gn/T/pytest-of-hanneszietsman/pytest-10208/test_native_writer_wins_before0/config/releases/broker') / 'policy-publication.json').exists +E + where PosixPath('/private/var/folders/2f/ntb_0p9558v4wfcwr5_64dg00000gn/T/pytest-of-hanneszietsman/pytest-10208/test_native_writer_wins_before0/config/releases/broker') = .root + +tests/test_release_policy.py:442: AssertionError +__ test_native_writer_wins_before_journal_without_orphaning_policy[charlotte] __ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x10b01f110> + + def test_native_writer_wins_before_journal_without_orphaning_policy(policy_product,monkeypatch): + from dc_overview import fleet_upgrade + from dc_overview.release_broker import BrokerError + policy=policy_module();host,service,owner=policy_product;write=policy.private_write;fired=[] + data=copy.deepcopy(host.store.load().manifest.data);data['baseline_id']='competing-native-writer' + path=host.config.config_dir/'competing.json';path.write_text(json.dumps(data)) + def competing_write(target,value): + if target.name=='policy-candidate.json' and not fired: + fired.append(True) + fleet_upgrade.select_release_components(host.config,path,['grafana'],platform='linux/amd64') + return write(target,value) + with monkeypatch.context() as change: + change.setattr(policy,'private_write',competing_write) + with pytest.raises((BrokerError,RuntimeError,ValueError)):set_mode(service,'follow-stable') + assert fired and host.store.load().selection['selection_id']=='competing-native-writer' +> assert not (service.root/'policy-publication.json').exists() +E AssertionError: assert not True +E + where True = exists() +E + where exists = (PosixPath('/private/var/folders/2f/ntb_0p9558v4wfcwr5_64dg00000gn/T/pytest-of-hanneszietsman/pytest-10208/test_native_writer_wins_before1/config/releases/broker') / 'policy-publication.json').exists +E + where PosixPath('/private/var/folders/2f/ntb_0p9558v4wfcwr5_64dg00000gn/T/pytest-of-hanneszietsman/pytest-10208/test_native_writer_wins_before1/config/releases/broker') = .root + +tests/test_release_policy.py:442: AssertionError +___________ test_follow_tracks_a_new_explicitly_installed_major[ltx] ___________ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +admitted = {'times': {'issued_at': '2026-11-04T17:00:34.548302+00:00', 'expires_at': '2026-11-04T17:02:44.548302+00:00'}, 'produc...dd8ee15ec28a201af54bec951ec8ade3cc986c7a90e9e4d87f', 'verify': .verify at 0x10b063f60>, ...} + + def test_follow_tracks_a_new_explicitly_installed_major(policy_product,admitted): + from dc_overview import fleet_upgrade + host,service,owner=policy_product;set_mode(service,'follow-stable') + data=copy.deepcopy(host.store.load().manifest.data);data['baseline_id']='explicit-major-two' + new=copy.deepcopy(data['components']['grafana']);new['release']='2.0.0' + new['artifacts']['linux/amd64']['reference']='grafana/grafana@sha256:'+'c'*64 + data['components']['grafana']=new;path=host.config.config_dir/'explicit-major.json';path.write_text(json.dumps(data)) + fleet_upgrade.select_release_components(host.config,path,['grafana'],platform='linux/amd64') + owner.installed_component=lambda current,name:copy.deepcopy(new) if name=='grafana' else None + service.discovery=lambda:[admitted_version(admitted,'2.1.0',identity='d')] + result=service.dispatch('policy-refresh',expected(service),actor=ACTOR) +> assert result['advanced']==['grafana'] and result['components']['grafana']['major']==2 +E AssertionError: assert ([] == ['grafana'] +E +E Right contains one more item: 'grafana' +E Use -v to get more diff) + +tests/test_release_policy.py:457: AssertionError +________ test_follow_tracks_a_new_explicitly_installed_major[charlotte] ________ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +admitted = {'times': {'issued_at': '2026-11-04T17:00:34.591546+00:00', 'expires_at': '2026-11-04T17:02:44.591546+00:00'}, 'produc...4154b77f9a9c822d13117ae0ee803fc5ba56135bca1c9148bc', 'verify': .verify at 0x10af6c400>, ...} + + def test_follow_tracks_a_new_explicitly_installed_major(policy_product,admitted): + from dc_overview import fleet_upgrade + host,service,owner=policy_product;set_mode(service,'follow-stable') + data=copy.deepcopy(host.store.load().manifest.data);data['baseline_id']='explicit-major-two' + new=copy.deepcopy(data['components']['grafana']);new['release']='2.0.0' + new['artifacts']['linux/amd64']['reference']='grafana/grafana@sha256:'+'c'*64 + data['components']['grafana']=new;path=host.config.config_dir/'explicit-major.json';path.write_text(json.dumps(data)) + fleet_upgrade.select_release_components(host.config,path,['grafana'],platform='linux/amd64') + owner.installed_component=lambda current,name:copy.deepcopy(new) if name=='grafana' else None + service.discovery=lambda:[admitted_version(admitted,'2.1.0',identity='d')] + result=service.dispatch('policy-refresh',expected(service),actor=ACTOR) +> assert result['advanced']==['grafana'] and result['components']['grafana']['major']==2 +E AssertionError: assert ([] == ['grafana'] +E +E Right contains one more item: 'grafana' +E Use -v to get more diff) + +tests/test_release_policy.py:457: AssertionError +______ test_repin_revalidates_installed_identity_inside_native_locks[ltx] ______ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x1091c72f0> + + def test_repin_revalidates_installed_identity_inside_native_locks(policy_product,monkeypatch): + from dc_overview.release_broker import BrokerError + policy=policy_module();host,service,owner=policy_product;set_mode(service,'follow-stable') + before=snapshot(host,service);write=policy.private_write;fired=[] + def change_installed(path,value): + if path.name=='policy-candidate.json' and not fired: + fired.append(True) + owner.installed_component=lambda *a:None + return write(path,value) + with monkeypatch.context() as change: + change.setattr(policy,'private_write',change_installed) +> with pytest.raises(BrokerError) as error:set_mode(service,'pinned') + ^^^^^^^^^^^^^^^^^^^^^^^^^^ +E Failed: DID NOT RAISE BrokerError + +tests/test_release_policy.py:473: Failed +___ test_repin_revalidates_installed_identity_inside_native_locks[charlotte] ___ + +policy_product = (namespace(config=FleetConfig(site_name='DC Overview', fleet_admin_user='admin', fleet_admin_pass=None, components=Com...), , ) +monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x10b0efe90> + + def test_repin_revalidates_installed_identity_inside_native_locks(policy_product,monkeypatch): + from dc_overview.release_broker import BrokerError + policy=policy_module();host,service,owner=policy_product;set_mode(service,'follow-stable') + before=snapshot(host,service);write=policy.private_write;fired=[] + def change_installed(path,value): + if path.name=='policy-candidate.json' and not fired: + fired.append(True) + owner.installed_component=lambda *a:None + return write(path,value) + with monkeypatch.context() as change: + change.setattr(policy,'private_write',change_installed) +> with pytest.raises(BrokerError) as error:set_mode(service,'pinned') + ^^^^^^^^^^^^^^^^^^^^^^^^^^ +E Failed: DID NOT RAISE BrokerError + +tests/test_release_policy.py:473: Failed +=========================== short test summary info ============================ +FAILED tests/test_release_policy.py::test_native_writer_wins_before_journal_without_orphaning_policy[ltx] +FAILED tests/test_release_policy.py::test_native_writer_wins_before_journal_without_orphaning_policy[charlotte] +FAILED tests/test_release_policy.py::test_follow_tracks_a_new_explicitly_installed_major[ltx] +FAILED tests/test_release_policy.py::test_follow_tracks_a_new_explicitly_installed_major[charlotte] +FAILED tests/test_release_policy.py::test_repin_revalidates_installed_identity_inside_native_locks[ltx] +FAILED tests/test_release_policy.py::test_repin_revalidates_installed_identity_inside_native_locks[charlotte] +6 failed, 85 deselected in 1.65s diff --git a/.traceweaver/auto-advance-20261104/review-correctness.json b/.traceweaver/auto-advance-20261104/review-correctness.json new file mode 100644 index 0000000..44d6e88 --- /dev/null +++ b/.traceweaver/auto-advance-20261104/review-correctness.json @@ -0,0 +1,16 @@ +{ + "reviewer": "advance_vv_correctness", + "findings": [], + "scope": "correctness/concurrency/recovery", + "closed_findings": [ + "policy journal created after native CAS under lifecycle/updater locks; postcommit policy state written before locks release", + "installed major derived from verified running image and advanced only after explicit major installation" + ], + "independent_tests": "91 policy tests passed", + "status": "passed within source scope", + "production_acceptance": false, + "held": [ + "trusted publisher/installed broker prerequisite", + "native and production acceptance separately required" + ] +} diff --git a/.traceweaver/auto-advance-20261104/review-definition.json b/.traceweaver/auto-advance-20261104/review-definition.json new file mode 100644 index 0000000..ac878f9 --- /dev/null +++ b/.traceweaver/auto-advance-20261104/review-definition.json @@ -0,0 +1,18 @@ +{ + "utc": "2026-11-04T16:45:13.521023+00:00", + "status": "passed", + "reviewers": [ + "advance_vv_correctness", + "advance_vv_security" + ], + "scope": "expanded pre-implementation tests/V&V + validationdefinition againstapproved C1-C8", + "source_results": "DC59failed16pass;Proxy16failed4pass beforeproductionintegration;selector12passfromearlierTDDslice", + "residual_gates": [ + "Linuxpeer/rootcustody", + "abruptprocesscrashrecovery", + "actualtimer", + "actualbrowser", + "existingpublisherandbridgeacceptance" + ], + "followups_in_tests": "positiveinstalledcase,specificfaultactivation,modeonlyCAS,validclientcontrol added before relatedproductionimplementation" +} diff --git a/.traceweaver/auto-advance-20261104/review-route-request.json b/.traceweaver/auto-advance-20261104/review-route-request.json new file mode 100644 index 0000000..bc18804 --- /dev/null +++ b/.traceweaver/auto-advance-20261104/review-route-request.json @@ -0,0 +1,17 @@ +{ + "schema_version": "tw-review-route/1", + "accepted": { + "semantic_authority_digest": "94b783d925834004cd3f111dd2437f8ae531850f0184aaa29c52f89f84267795", + "behavior_digest": "8f50eef6db9ad1a5a2df1ae1de80199adbdb5deaf53f6b87ca0fbb83337a6541", + "verification_digest": "df55095ce3a2c33863a8d86086153a7508fdaa006febed748e6b1e746e319c00", + "bookkeeping_digest": "before-annotations-and-receipts", + "session_id": "independent-backend-review" + }, + "candidate": { + "semantic_authority_digest": "94b783d925834004cd3f111dd2437f8ae531850f0184aaa29c52f89f84267795", + "behavior_digest": "8f50eef6db9ad1a5a2df1ae1de80199adbdb5deaf53f6b87ca0fbb83337a6541", + "verification_digest": "df55095ce3a2c33863a8d86086153a7508fdaa006febed748e6b1e746e319c00", + "bookkeeping_digest": "7142035a1d3e0b0a49ff4ead58e1212a9053b1f0ce03e8f961842a0e8f6cbf2f", + "session_id": "source-publication-preparation" + } +} diff --git a/.traceweaver/auto-advance-20261104/review-route-result.json b/.traceweaver/auto-advance-20261104/review-route-result.json new file mode 100644 index 0000000..aca3396 --- /dev/null +++ b/.traceweaver/auto-advance-20261104/review-route-result.json @@ -0,0 +1 @@ +{"schema_version":"tw-review-route-result/1","route":"mechanical_closure","reason":"bookkeeping_only_changed","changed_fields":["bookkeeping_digest","session_id"],"reviewer_dispatch_count":0,"new_review_required":false} diff --git a/.traceweaver/auto-advance-20261104/review-security.json b/.traceweaver/auto-advance-20261104/review-security.json new file mode 100644 index 0000000..4547d89 --- /dev/null +++ b/.traceweaver/auto-advance-20261104/review-security.json @@ -0,0 +1,15 @@ +{ + "reviewer": "advance_vv_security", + "findings": [], + "scope": "security/API/auth/trust", + "closed_findings": [ + "installed provenance rechecked under lifecycle/updater locks before policy journal creation" + ], + "reviewed_tests": "350 affected tests passed", + "status": "passed within source scope", + "production_acceptance": false, + "held": [ + "trusted publisher/installed broker prerequisite", + "native and production acceptance separately required" + ] +} diff --git a/.traceweaver/auto-advance-20261104/source-hashes.json b/.traceweaver/auto-advance-20261104/source-hashes.json new file mode 100644 index 0000000..d95955b --- /dev/null +++ b/.traceweaver/auto-advance-20261104/source-hashes.json @@ -0,0 +1,10 @@ +{ + "pyproject.toml": "49ca02f1f3a894f44a1ef1c61d2a0c978bf6161a4df763a936e980b8721a9365", + "src/dc_overview/cli.py": "63501cf00a6cb238d8f386b16f8f2393342344c5c69493cbf6fcb37a20e9276e", + "src/dc_overview/fleet_upgrade.py": "a2d9cf730de5b0d68b1071d4329dd9e4b2af1bf285f1857b5d6abd52f205674e", + "src/dc_overview/release_broker.py": "5916872d5ec87a2e9b69529c2c8a16f9a871667d9ff0ae27a0f1691fcaa296b7", + "src/dc_overview/release_policy.py": "0061e5a66b4f5495fe7bc83e8426b085983a1c42c12bb25cfdf853c33dc06b7b", + "src/dc_overview/templates/systemd/dc-overview-release-refresh.service": "b21ecf63d9ab5ce9a39ed84aeedb706a8064a38485bb22f85c3bdfbc0ed9dd2e", + "src/dc_overview/templates/systemd/dc-overview-release-refresh.timer": "1bfcb7323a7e29f240c923e6e9d2f75f41717e2fd0ee385e4232d0fd34dfd3ca", + "tests/test_release_policy.py": "250a769e20d831a42f730ec790c0225207504221664ec3349ecf17ffd19e821b" +} diff --git a/.traceweaver/auto-advance-20261104/validation.md b/.traceweaver/auto-advance-20261104/validation.md new file mode 100644 index 0000000..b7dffa7 --- /dev/null +++ b/.traceweaver/auto-advance-20261104/validation.md @@ -0,0 +1,3 @@ +Validation definition for VAL-AUTOADVANCE-001 through -008 + +Owner/rater: Hannes Zietsman, requesting Fleet administrator, independent of implementation. Scenario and observable criteria are exact approvedplan C1-C8 and Validationsection. In native staging a signed synthetic newerstable release exercises unpin -> auto selection withoutrestart -> manualUpdate -> healthy -> repin -> noadvance, failure/concurrency/restart/CSRFcases. On LTX verify correctcurrentversion, persistentmode choice, dailytimer and unchangedotherroles/history/accounts. Localfrontendfixtures prove onlyrequest/rendercontracts; do notrepresentLinuxrootcustody oractualupgrades. Evidence includes exactsourcehash, UI screenshots/requestreceipts, nativepolicy/selectionhashes, unchangedruntimeIDs andhealth. Noacceptanceclaimuntilobserved. Newpublisher/bridge dependencies stayhelduntilindependentlyverified. diff --git a/.traceweaver/auto-advance-20261104/verification.json b/.traceweaver/auto-advance-20261104/verification.json new file mode 100644 index 0000000..acd7275 --- /dev/null +++ b/.traceweaver/auto-advance-20261104/verification.json @@ -0,0 +1,41 @@ +{ + "scope": "source verification; production and future genuine release acceptance held", + "full_regression": { + "passed": 2121, + "skipped": 0, + "log": "full-tests-final.log" + }, + "final_focus": { + "passed": 91, + "log": "final-anchors-policy-tests.log" + }, + "log_hashes": { + "red-review-findings.log": "85e242055967b20475c3e26b65303b6e42a467ab2d118ed51d22b7a0447963eb", + "review-repair-focused.log": "3ba5d449a0040443296454ad5eb2f83ae93bcb77da6f82870aed7334e416c2d9", + "red-integration.log": "cd1cca35102928a5fbe6760b93205e3a733ca6c214cdc06e8385a413af9dea1b", + "red-precommit.log": "4e1a30d48dc45ada913c41341353fbdd642ff9585deed15554c4681266657927", + "final-anchors-policy-tests.log": "06429b830c4fe583fb1a5a3705b274b4a2cb0f6f87956fd90f75489d5e699fb8", + "full-tests-final.log": "ba32ff5b6b0bd0b8d620851d3c36dcc44f2ebd9ff0e6c7f17b50a4c6f1b53811", + "red-tests.log": "dc1a48171d0fa9be38e1b0a4f32e0b0f0eb1c999c14628e884b067d9851d7c79" + }, + "native": { + "passed_cases": 11, + "receipt_sha256": "06ceabc99113de2f13d90ac7013a64e16c2a79b66f656a69ed6f0f9c7a546158", + "scope": "real Linux root/Docker inspection/locks/crash recovery/socket/CLI/systemd; synthetic signed admissions and idle app containers", + "application_installation_health": false, + "negative_cases": "native-negative.log: bad signature and real SO_PEERCRED rejection passed" + }, + "browser": { + "passed": true, + "scope": "actual candidate page in Chrome, synthetic API; pin/follow/check/reload/repin, no install calls", + "receipt_sha256": "c1d146fa4d93014eeb743cc586ef620ad38e47770b7c993dcc93d4427f3c990b" + }, + "live_activation_blockers": [ + "trusted current-pack discovery is404; production issuer custody/publisher unaccepted", + "existing Fleet PR34 native scoped-select recovery continuity gate failed; do not bypass" + ], + "independent_review": [ + "review-correctness.json", + "review-security.json" + ] +} diff --git a/.traceweaver/auto-advance-20261104/vv-capsule.json b/.traceweaver/auto-advance-20261104/vv-capsule.json new file mode 100644 index 0000000..dabe364 --- /dev/null +++ b/.traceweaver/auto-advance-20261104/vv-capsule.json @@ -0,0 +1,148 @@ +{ + "schema_version": "tw-vv-capsule/1", + "workflow_profile": "L3", + "work_item_id": "AUTOADVANCE-20261104", + "plan_ref": ".traceweaver/auto-advance-20261104/plan.md", + "high_risk_controls": { + "rollback": "Unpublishedlocalchangesreversible; policyjournalmustreconcileprior/newselectionandmode atomically; LTXactivationusesnativeexistingownerwithhealth/recovery andpreservationevidence. Nojournalclearingorcredentialreset.", + "owner_decision": "Exact userapproval owner-approval.json; same-majorverifiedstablefollow,manualinstallation;completeexistingacceptanceprerequisitesbeforeactivation." + }, + "requirements": [ + { + "req_id": "REQ-AUTOADVANCE-001", + "trace_id": "TRACE-AUTOADVANCE-001", + "ver_id": "VER-AUTOADVANCE-001", + "val_id": "VAL-AUTOADVANCE-001", + "verification_artifact": "tests/test_release_policy.py", + "red_evidence": ".traceweaver/auto-advance-20261104/red-integration.log", + "validation_artifact": ".traceweaver/auto-advance-20261104/validation.md", + "reviews": [ + { + "gate": "tw-code-review / tw-doc-review", + "id": "AUTOADVANCE-VV-REVIEW", + "status": "passed", + "evidence_path": ".traceweaver/auto-advance-20261104/review-definition.json" + } + ] + }, + { + "req_id": "REQ-AUTOADVANCE-002", + "trace_id": "TRACE-AUTOADVANCE-002", + "ver_id": "VER-AUTOADVANCE-002", + "val_id": "VAL-AUTOADVANCE-002", + "verification_artifact": "tests/test_release_policy.py", + "red_evidence": ".traceweaver/auto-advance-20261104/red-integration.log", + "validation_artifact": ".traceweaver/auto-advance-20261104/validation.md", + "reviews": [ + { + "gate": "tw-code-review / tw-doc-review", + "id": "AUTOADVANCE-VV-REVIEW", + "status": "passed", + "evidence_path": ".traceweaver/auto-advance-20261104/review-definition.json" + } + ] + }, + { + "req_id": "REQ-AUTOADVANCE-003", + "trace_id": "TRACE-AUTOADVANCE-003", + "ver_id": "VER-AUTOADVANCE-003", + "val_id": "VAL-AUTOADVANCE-003", + "verification_artifact": "tests/test_release_policy.py", + "red_evidence": ".traceweaver/auto-advance-20261104/red-integration.log", + "validation_artifact": ".traceweaver/auto-advance-20261104/validation.md", + "reviews": [ + { + "gate": "tw-code-review / tw-doc-review", + "id": "AUTOADVANCE-VV-REVIEW", + "status": "passed", + "evidence_path": ".traceweaver/auto-advance-20261104/review-definition.json" + } + ] + }, + { + "req_id": "REQ-AUTOADVANCE-004", + "trace_id": "TRACE-AUTOADVANCE-004", + "ver_id": "VER-AUTOADVANCE-004", + "val_id": "VAL-AUTOADVANCE-004", + "verification_artifact": "tests/test_release_policy.py", + "red_evidence": ".traceweaver/auto-advance-20261104/red-integration.log", + "validation_artifact": ".traceweaver/auto-advance-20261104/validation.md", + "reviews": [ + { + "gate": "tw-code-review / tw-doc-review", + "id": "AUTOADVANCE-VV-REVIEW", + "status": "passed", + "evidence_path": ".traceweaver/auto-advance-20261104/review-definition.json" + } + ] + }, + { + "req_id": "REQ-AUTOADVANCE-005", + "trace_id": "TRACE-AUTOADVANCE-005", + "ver_id": "VER-AUTOADVANCE-005", + "val_id": "VAL-AUTOADVANCE-005", + "verification_artifact": "tests/test_release_policy.py", + "red_evidence": ".traceweaver/auto-advance-20261104/red-integration.log", + "validation_artifact": ".traceweaver/auto-advance-20261104/validation.md", + "reviews": [ + { + "gate": "tw-code-review / tw-doc-review", + "id": "AUTOADVANCE-VV-REVIEW", + "status": "passed", + "evidence_path": ".traceweaver/auto-advance-20261104/review-definition.json" + } + ] + }, + { + "req_id": "REQ-AUTOADVANCE-006", + "trace_id": "TRACE-AUTOADVANCE-006", + "ver_id": "VER-AUTOADVANCE-006", + "val_id": "VAL-AUTOADVANCE-006", + "verification_artifact": "tests/test_release_policy.py", + "red_evidence": ".traceweaver/auto-advance-20261104/red-integration.log", + "validation_artifact": ".traceweaver/auto-advance-20261104/validation.md", + "reviews": [ + { + "gate": "tw-code-review / tw-doc-review", + "id": "AUTOADVANCE-VV-REVIEW", + "status": "passed", + "evidence_path": ".traceweaver/auto-advance-20261104/review-definition.json" + } + ] + }, + { + "req_id": "REQ-AUTOADVANCE-007", + "trace_id": "TRACE-AUTOADVANCE-007", + "ver_id": "VER-AUTOADVANCE-007", + "val_id": "VAL-AUTOADVANCE-007", + "verification_artifact": "tests/test_release_policy.py", + "red_evidence": ".traceweaver/auto-advance-20261104/red-integration.log", + "validation_artifact": ".traceweaver/auto-advance-20261104/validation.md", + "reviews": [ + { + "gate": "tw-code-review / tw-doc-review", + "id": "AUTOADVANCE-VV-REVIEW", + "status": "passed", + "evidence_path": ".traceweaver/auto-advance-20261104/review-definition.json" + } + ] + }, + { + "req_id": "REQ-AUTOADVANCE-008", + "trace_id": "TRACE-AUTOADVANCE-008", + "ver_id": "VER-AUTOADVANCE-008", + "val_id": "VAL-AUTOADVANCE-008", + "verification_artifact": "tests/test_release_policy.py", + "red_evidence": ".traceweaver/auto-advance-20261104/red-integration.log", + "validation_artifact": ".traceweaver/auto-advance-20261104/validation.md", + "reviews": [ + { + "gate": "tw-code-review / tw-doc-review", + "id": "AUTOADVANCE-VV-REVIEW", + "status": "passed", + "evidence_path": ".traceweaver/auto-advance-20261104/review-definition.json" + } + ] + } + ] +} diff --git a/.traceweaver/intent-contract.yml b/.traceweaver/intent-contract.yml index 0b1eeb3..ac3c851 100644 --- a/.traceweaver/intent-contract.yml +++ b/.traceweaver/intent-contract.yml @@ -45,6 +45,23 @@ native_fixture_pin_repair: native_acceptance: held publisher_enforcement: held +service_recovery_amendment_projection: + date: 2026-11-02 + authority_plan: ../../artifacts/ipmi-readiness-20261026/fleet-ui-20261102/architecture/continuation-amendment.json + plan_sha256: 159af8421e4dde61e4ecc4f47849a1ddd7f07cd6fb158d247256f0bb36ed316e + owner_approval: ../../artifacts/ipmi-readiness-20261026/fleet-ui-20261102/owner-approval.json + implementation_contract_sha256: 91b873c548da7d10a113c8fbb74f09540559ba51339514c738e081d0dc75cf01 + authority_gate: ../../artifacts/ipmi-readiness-20261026/fleet-ui-20261102/execution/go/recovery-source-go.json + reviewed_vv: ../../artifacts/ipmi-readiness-20261026/fleet-ui-20261102/execution/go/recovery-vv-root-reviewed.json + requirement: REQ-FLEETUPDATE-001 + trace: TRACE-FLEETUPDATE-001 + verification: VER-FLEETUPDATE-001 + validation: VAL-FLEETUPDATE-001 + source_only: true + native_acceptance: held + production_writes: disabled + publication: held + central_telemetry_monitoring_policy: contract_id: TW-IC-MON-20261104-001 baseline_id: REQ-BASELINE-MON-20261104-001 @@ -67,6 +84,13 @@ central_telemetry_monitoring_policy: production_acceptance: pending held_claims: [production_deployment, notification_delivery, unrelated_fleet_acceptance] +auto_advance_20261104: + authority: .traceweaver/auto-advance-20261104/authority.json + approved_plan_sha256: 94b783d925834004cd3f111dd2437f8ae531850f0184aaa29c52f89f84267795 + owner_approval: .traceweaver/auto-advance-20261104/owner-approval.json + scope: per-servicepinremoval/stable-following/manualinstall + runtime_acceptance: pending + gpu_alert_quality_20261104: owner_instruction: Approve and deploy to both sights approved_sites: [LTX, Charlotte] diff --git a/docs/fleet-release-native-qa.md b/docs/fleet-release-native-qa.md index c0ed132..71246db 100644 --- a/docs/fleet-release-native-qa.md +++ b/docs/fleet-release-native-qa.md @@ -5,20 +5,23 @@ The `Fleet release native verification` pull request workflow runs one sequentia integration flow in the existing `ci-build-public-ephemeral` Linux VM route for repository `1133295682`. It requires a same-repository PR into `dev`, a read-only job token, the exact DC PR head, and an explicitly reviewed, published proxy commit. -The proxy input is the reviewed published commit -`5db15086c26095179f2af56bfa434c85426a6699`, with frozen runtime hashes from the -accepted source manifest. The source guard rejects an unresolved placeholder -before the proxy checkout or guest changes. +Root binds the recovery input to the exact reviewed protected `dev` merge +commit, refreshes every changed runtime hash in `FROZEN_PRODUCT_HASHES`, and +sets `RECOVERY_INPUTS_FROZEN = True` only after exact source review. The workflow +uses that immutable commit as `PROXY_SOURCE_SHA`. The source pin and recovery +input guards reject unresolved inputs before the proxy checkout or guest changes. This test integration is not +execution or publication approval. -The four public image inputs in `scripts/verify_fleet_release_native.py` are +The five public image inputs in `scripts/verify_fleet_release_native.py` are immutable digests. Registry and Nginx use pinned official Linux amd64 manifests; IPMI uses the previously approved old and new public releases. The retained primary registry metadata readback accompanies the implementation evidence. No registry login or publishing credential is needed. -Inside that individual fresh guest, the workflow builds and installs both wheels, -checks installed package bytes against the frozen product hashes, and builds two -proxy images from the same reviewed application source with different metadata. +Inside that individual fresh guest, the workflow builds and installs both +compatible wheels, checks installed bytes against frozen source hashes, and +builds two compatible proxy images from the same reviewed application source +with different metadata. These images do not stand in for legacy-runtime proof. It first checks the vanilla packaged systemd unit with writes disabled and no trust fixture. It then adds an explicit test-only systemd discovery adapter. The adapter supplies locally signed synthetic admission assets to the installed @@ -90,6 +93,49 @@ command output is retained. The original failure and cleanup still run; this metadata adds no retry, probe or behavior repair. All remaining native and release acceptance limits below continue to apply. +For a failed `fixture` phase, `bootstrap_failure` adds one bounded object while +the outer line, kind and fixture aliases retain their existing meaning. Its +only fields are `bootstrap_step`, `code_label`, `source_line`, `guard_line`, +`error_kind`, `command_outcome` and `command_returncode`. The step comes from +fixed lexical markers in the original bootstrap/seed bytecode, selected by the +trusted traceback instruction offset. The collector does not read frame locals. +Steps distinguish the existing legacy inspect/updater/capabilities probes, +synthetic seed/read/custody/protection, failed-job seed, compatible installation, +owner refusal, reconciliation/replay, selection, proxy plan/adoption and health. +Untrusted or missing boundaries retain `unknown` and null values. + +The code labels are `legacy-bootstrap`, `synthetic-seed`, `synthetic-helper`, +`native-command` or `unknown`. Module load captures original verifier code +objects. The helper remains byte-for-byte pinned by `PROTECTION_SHA`; its +diagnostic registration first verifies those exact bytes and complete loaded +callable code before capturing the actual callable and nested code identities. +Every traceback lookup uses exact code-object identity. A matching filename or +callable name grants no identity. The inner source line must occur in that +original code object's line table. A helper `need()` failure retains the numeric +trusted caller line as `guard_line`, rather than exporting its error text. +Interpret verifier coordinates against the exact preflight source head, and +helper coordinates against the unchanged retained helper hash. + +The checked command wrapper owns an immutable pair of bounded diagnostic facts. +`command_outcome` is `nonzero-exit`, `timeout`, `spawn-error`, `none` or `unknown`; +`command_returncode` is an exact integer from -255 through 255, or null. Booleans +and out-of-range values are rejected. Only the original owned exception type +with an original command-wrapper traceback can supply command facts to the +inner object; arbitrary exception properties cannot. Command failure messages +are fixed literals, with no executable name derived from arguments. Exception +propagation and chaining remain available; only the owned facts are immutable. +Construction and collection accept exact built-in strings and return fixed +canonical outcomes; string subclasses become `unknown`. Ordinary assignment, +deletion and constructor reinitialization cannot change the owned facts. +Arbitrary Python reflection is outside this immutability promise. + +No exception string or representation, argv, captured output, environment, +configuration, database content or helper private receipt is exported by this +object. Collection is best effort and cannot replace the original failed gate +or skip cleanup. These coordinates locate an observed failure boundary; they +do not prove a root cause, repair bootstrap behavior, add a retry or authorize +another native run. Full native, release and customer-site gates remain held. + At each existing broker kill boundary (`service_update` and `interrupted_adoption`), the fixture records the auth layout, fixed phase, actual numeric kill exit code, and before/after `systemctl show` observations of @@ -181,7 +227,10 @@ endpoint. Root commands, the Docker socket, systemd units and `/etc` changes are confined to the disposable guest. The proxy uses isolated external ports 18080 and 18443, preserving those bindings through adoption. -For both a named auth volume and a bind-mounted auth directory, the flow checks: +The new recovery/bootstrap check uses a named auth volume. After that sequence +adopts the compatible proxy, the retained flow checks the cases below. The +existing separate bind-layout compatible fixture and its interruption checks +also remain in the same sequential job; they do not stand in for legacy proof. 1. Real peer rejection, malformed framing, root-policy reload and native CLI use. 2. A scoped IPMI update, a dropped HTTPS reply and broker restart, durable owner @@ -209,11 +258,82 @@ mapped job must have a terminal result. A prelaunch mapping alone cannot satisfy that observation. Subprocess timeouts fail with a generic error and suppressed exception chaining, while retaining the failed outcome and cleanup. -The bind case interrupts a real adoption -after the owner has retained its plan, restarts the broker and records the -observed terminal or visibly held recovery state. Timing is observed rather than -claimed to hit an exact instruction boundary. No fake Engine substitutes or -forced successful operation states are used. +The bind case interrupts real compatible proxy adoption after the owner retains +its plan and observes recovery after broker restart. It does not constitute a +second legacy bootstrap check. No exact Engine crash instruction boundary or +lost Engine reply is claimed. + +## Packaged legacy recovery before selection and adoption + +The workflow downloads the actual released DC1.8.0 and proxy1.5.4 wheels through +their immutable public HTTPS release URLs, bounds each download to 120 seconds, +and checks these SHA256 values before use: + +- DC1.8.0: `72fcf2fde1d765cdfebfd2e4071261e3ff28d202f7ffb1975340e9d362969304`. +- Proxy1.5.4: `5e64f0ae59d38ebcf4885d8aa60822bc3187d5a63f9abb8bdd11927d1ffd2b47`. + +It installs/imports the old pair in one guest host-tool venv, invokes old DC +release help, and creates synthetic auth data through the old proxy package. +It starts the actual serving legacy proxy image +`ghcr.io/cryptolabsza/cryptolabs-proxy@sha256:bff38744e774875287e60e1e14995b19c7eb3afbe531d07f5921d06d9b76a1fd` +without a broker socket mount. The image's stale OCI version strings are not +version proof. Both proxy fixture layouts set `PYTHONPATH=/app/src`, the copied +application source path required by their Python module probes. The pinned legacy +image does not declare that environment setting itself. +Actual updater module bytes must match the exact old wheel; +actual live capabilities must lack the new broker/recovery capabilities. +DC1.8.0 here is the host CLI/package plane; a separate old DC service OCI +container is not started or certified by this fixture. + +The original IPMI service uses real 1.3.1 image +`sha256:738f11f7b432c4d9d8409154c9ca3f531a1e069999eb639a9d86433e84ac279d`. +The selected failed target is real 1.3.2 image +`sha256:dfa8a56159aab545d128b14bfb7d91cad17cac7de4f706307de508086fc56db9`. +The later successful scoped target is real 1.3.3 image +`sha256:1d616479a3842f5101615b6d97552f732de73fd424fcb844a9c643e92abc8bb1`. + +The verification-only selected-state producer in +`scripts/fixtures/legacy-selected-state-protection.py` retains the bounded +selected-table/config roundtrip algorithms and records their source provenance. +All historical site PINS, customer identity values and the operational CLI +entrypoint are removed. It requires an explicit synthetic binding and creates +only a synthetic guest continuity bundle. Sync stays OFF; a deliberately +synthetic health timestamp exercises the freshness predicate. This does not +prove a real collector, customer data continuity or whole-database disaster +recovery. No production DB snapshot is taken. + +The failed native record is constructed by actual old `submit_job`, using real +read-only Engine observations and the real selected snapshot/targets/sources. +Only helper create/start are intercepted during this seed step, so no seeded +update runs. The resulting job is explicitly marked failed/recovery_required as +synthetic setup. No historical ID or missing phase-success evidence is supplied, +and no incident cause or incident reproduction is claimed. + +The exact compatible built wheels then replace the old pair in that same +host-tool venv. To exercise real pip provenance and the production GitHub HTTPS +origin contract, the fixture temporarily serves those exact bytes through a TLS +guest-loopback wheel mirror at 127.0.0.2:443 for `github.com`. It uses a generated +fixture certificate and genuine pip download/installation; it never edits +`direct_url.json`. This synthetic transport proves no public release or issuer +acceptance. The owned listener and exact hosts preimage are cleaned up within +the existing isolated VM; no external GitHub endpoint is changed. + +With the old proxy still serving, production `InstalledOwner.capabilities` +must reject its legacy capabilities. The actual fixed host CLI then runs +`release reconcile-service --service ipmi-monitor --job `. +The receipt must be the only new updater-store entry; every previous file's +bytes/inode, failed job, active pointer, selection and public configuration must +remain unchanged. Receipt job/active hashes bind actual raw bytes. Discarding +the first CLI reply and repeating must retain identical receipt bytes. + +Only afterward does the actual host CLI perform scoped proxy selection with +`--record-cli`. Normal `StandardAdoption` must replace the proxy and add the +existing root0600 broker socket while customer writes remain disabled. The +failed native history survives. The subsequent real signed-fixture scoped +update must bind `recovery_predecessor` to that old job and receipt; the retained +one-helper mapping, dropped HTTPS response, broker main kill/restart and real +failed-health rollback assertions still run. The real worker is not replaced by +the seed adapter. A passing run accepts only these observed fixture boundaries. Local checks, which do not execute the guest flow: @@ -236,3 +356,403 @@ issuer authority, real current admissions and live GitHub discovery, a genuine future-version migration, unobserved crash windows, desktop/mobile browser acceptance and the remaining release gates stay held. The synthetic producer key and the same-source A/B images do not establish those claims. + + +The broker child also installs a test-only observation wrapper around the original +`release_broker.private_write`. It calls the original once with unchanged arguments, +returns its exact result, and observes only after a successful handled save. The +original exception and functional failure remain unchanged. Product source and +wheel bytes remain pinned, but the test process binding, timing and bounded +diagnostic I/O change: this is the original behavior under an observation wrapper, +not an unmodified runtime or a discovery-only adapter. + +If the existing 90-second mapping wait fails, one passive +`owner-mapping-observation` event is attempted before normal cleanup and the same +failure is raised. It projects only closed operation/mapping states, checked store +identity/equality, and an optional exact-UUID correlated three-field failure +coordinate. It never calls status to observe progression. The private retained-inode +4096-byte slot is reset at fixture lifecycle setup; stale, partial, contended or +unavailable observations remain unknown. Captures are not guaranteed. + +The fixed inspect command captures at most 1 MiB plus one overflow byte, with +four seconds for capture and the fifth second reserved for the exact child's +kill/reap, including spawn elapsed time. Regular files have explicit bounded reads; +regular-file I/O and kernel process operations have no unconditional real-time +guarantee. Raw inspect data, paths, record contents and exception strings are never +retained. A coordinate can identify only a recognized caller boundary; the actual +cause of the previous failure remains unproven. This local source work granted no +native attempt. The preceding observation's two-of-three-spent, one-held account +is historical: the original initial allowance of one and original additional +allowance of three are now fully spent. The separate current continuation cap is +described below; historical counters are unchanged. + +### Scoped selection output observation + +The existing bootstrap `release select` command opts into a bounded diagnostic. +If that same checked subprocess fails, `bootstrap_failure.scoped_select_diagnostic` +contains one of fifteen fixed output categories or `unknown`. Classification +requires an exact built-in integer exit code of 1, empty built-in bytes stdout, +and built-in bytes stderr of at most 512 bytes matching one complete reviewed +message, including its prefix and newline. Other output, types, line endings, +extra text and private stdout remain `unknown`. No captured output is attached to +the diagnostic slots or emitted metadata; existing subprocess capture behavior is +unchanged. Other command calls default to `unknown`; success, +unchecked calls, timeout and spawn outcomes retain their previous behavior. + +The category describes observed child output. It does not identify an executed +product guard or establish a root cause. For example, `cli-provenance-rejected` +combines version and provenance checks, `recovery-required` occurs at several +sites, and the public-reference categories have repeated raise sites. Capability +refusal also combines checks. Unknown messages, import failures, tracebacks and +transitive failures may remain `unknown`; useful classification is not guaranteed. +Existing `source_line` and `guard_line` keep their caller-coordinate meanings; +this observation adds no child guard coordinate. + +Projection requires the original command exception and run code frame within a +trusted scoped-select bootstrap step. The immutable slot exports only a canonical +category. Collector errors fall back to `unknown` and preserve the original +command failure and cleanup. No retry, extra subprocess, owner/status request or +product-state change is added. + +The 3 November observation preparation authorizes zero native or publication +actions. Run 41573017934 attempt 1 failed at scoped selection with exit 1; its +cause remains undetermined and this change cannot diagnose that terminated run +retroactively. The current continuation cap is three, with one spent and two +unused slots held by the unknown-cause stop condition. Historical counters stay +unchanged. Observation preparation is not a diagnosed compatibility repair, and +local source tests do not establish native, release, security or client acceptance. + +### Fixture-only inner recovery observation + +The scoped selector now runs its original installed console script once inside +a fixture wrapper in the same host Python environment. Original arguments, +environment, stdin, captured stdout/stderr, exit status and timeout are retained. +Only that subprocess inherits one anonymous nonblocking diagnostic pipe. The +wrapper calls the original `service_recovery_dependency` once per normal call, +returns its exact result, rethrows the same exception and restores the original +module binding in `finally`. Production packages and recovery algorithms remain +unchanged; the test-process binding and bounded diagnostic I/O change. + +Before a dependency exception reaches its original caller, the observer removes +only its own exact invocation frame and bare-rethrows the same exception. At the +outermost fixture dispatch, a captured contiguous prefix identifies that exact +dispatch, child and runpy invocation. Only those frame nodes are removed; original +application nodes and application-owned runpy invocations remain intact. The +interpreter renders the same exception with its current hook. The fixture never +replaces or calls `sys.excepthook`, formats exceptions itself, filters output text +or substitutes an exit code. Cause, context and suppression remain unchanged. + +`bootstrap_failure.scoped_select_inner_diagnostic` contains exactly `guards`, +`condition`, `require_capability` and `continuity_equal`. A guard has only a fixed `source` ID, +fixed `guard` ID and numeric `line`. The two facts are strict booleans or +`unknown`; they come only from the recognized `require(condition)` and +`service_recovery_dependency(..., require_capability=...)` frames. No messages, +exception arguments, traceback text, paths, hashes, record data or broad locals +are exported. The existing fifteen output categories keep their meanings. + +`continuity_equal` is either the literal `unknown` or exactly twelve strict +booleans: `runtime_config_sha256`, `host_config_sha256`, `mounts_sha256`, +`network_sha256`, `schema_sha256`, `settings_sha256`, `stable_cloud_sha256`, +`stable_inventory_sha256`, `saved_identity_sha256`, `declared_config_sha256`, +`database_device` and `database_inode`. `true` means the already captured +receipt and observation values agree; `false` identifies a differing field. +No underlying values, digests or device/inode numbers leave the child. + +This projection requires one exact trusted `validate_original_restored` frame +at the frozen Proxy guard line 228, its actual bytecode location, and a false +`require` condition. The loaded function/global bindings, continuity schema, +genuine frozen dataclass shape and exact observation class must agree. Both +the current class global and observation type must match the class identity +captured in the trusted context after wheel/source qualification, before the +original dependency executes once. A later same-shape replacement is unknown; +unbound function tuples cannot qualify a continuity field observation. Both +sixteen-field continuity dictionaries must contain only the required primitive +types and schema constants before any field comparison. No validator or +observer is called again. Foreign objects, changed globals/classes, malformed +state, multiple contexts/qualifying frames or an inconsistent all-equal result +leave the whole field `unknown`. The existing immutable exception facts and +bounded private record carry only the copied boolean map. + +Qualification checks both exact supplied wheel bytes and the frozen module +bytes at the installed distribution location, then compares full compiled function +structure before retaining loaded code-object identities. Traversal is +limited to eight exception contexts and 32 frames per exception. Foreign raise +sites or types, source/code drift, cycles, overflow, ambiguous/recovered failures +and observer faults stay unknown. A candidate is usable only when the failing +console exception retains that one dependency failure in its context chain. +Success and other output categories do not export an inner failure. + +The child attempts one private record of at most 8192 bytes. A partial write, +duplicate fields, extra record, oversized/invalid input or collection failure +cannot replace the original command outcome. Both pipe endpoints are closed on +all terminal paths. No additional Engine, Docker, SQL, HTTP or CLI probe is +made. A coordinate identifies an observed trusted guard; it does not by itself +establish a unique root cause or justify changing a denial/integrity check. + +Local output verification compares an actual executable directly with its wrapped +execution for uncaught RuntimeError, missing import, implicit context, explicit +cause, suppressed context and an application-owned runpy call. Byte comparisons +and interpreter versions are retained separately. A source scan of the frozen +product trees and source-qualified imports in the retained offline environment +show no product-installed custom exception hook. A real target hook or terminal +state dependency requiring broader handling stops this repair for re-planning; +the fixture is not a general interpreter or custom-hook emulator. + +The separate local qualified-dependency proof uses a generated console shim and +manually assembled/extracted source-derived fixture wheels. It substitutes +`FleetConfig.load`, `select_release_components` dispatch and `UpdateEngine`. +It exercises real `CLI.main`, `_scoped_idle` and the protected dependency/private +validators, but bypasses full selector construction, lifecycle/updater locks and +earlier selector preflights. It does not attest released/native wheel artifacts +or the complete consumer path. Earlier frozen records are retained with this +successor clarification; local evidence does not establish the native cause. + +The earlier three-slot accounts above are historical. The explicit owner-approved +4 November continuation has a total automatic cap of five, with two spent. +Ordinal three is one reviewed inner diagnostic; ordinals four and five require +concretely diagnosed, tested and reviewed repairs. Unknown after the diagnostic +stops progression. Source verification grants no native/publication action, +reservation, release acceptance or LTX update authority by itself. + +The 5 November synthetic-fixture candidate initializes the named-volume layout +before starting old IPMI. It verifies the immutable old image and revision, +fresh owned empty volume, root path custody, empty configuration and absence of +other runtime/mount users. An exact owned one-shot is registered for cleanup +before create, inspected before start, and run with network `none` and only the +data volume plus readonly empty server configuration. One absolute 60-second +deadline covers its lifecycle; only an inspected terminal exit zero permits +runtime startup. Cleanup revalidates name, ID, label, image, command, environment +and mounts before removing its exact ID, including uncertain create outcomes. + +The literal initializer checks old app source bytes before import, uses actual +import-time database initialization and ORM commit, and verifies every typed +cloud row field after two calls to the real site getter. It forbids network, +process and thread starts, unregisters shutdown reporting, and never calls +`create_app`. The later old runtime gets the same synthetic `SITE_NAME`. SQL +seeding verifies the singleton site identity before any write and never writes +site fields. The bind layout and original protection observer, strict continuity +equality, locks/history and root custody remain unchanged. + +Portable route tests exercise real orchestration with Engine and root-only +filesystem boundary substitutes. A separate bounded local proof extracts the +exact initializer literal and uses the retained old ORM source with all 135 +input hashes checked before/after. Neither establishes Docker/native acceptance +or identifies the native-four historical writer. The approved continuation cap +is seven automatic native attempts, five spent and two conditional remaining, +with zero manual attempts. This first functional slot permits one initial +candidate and at most two separately diagnosed, root-allocated corrections. +Source validation grants no native, publication or release authority. + +Both initializer writer inventories use `docker ps -aq --no-trunc` and require +each emitted ID to match the full lowercase 64-hex grammar before comparison +or inspection. After full initializer custody validation, only exact equality +with its created ID excludes that one-shot from the second writer scan. A +different full ID sharing its first twelve characters still undergoes the +unchanged foreign-name and owned-volume mount checks. + +The portable Engine boundary returns twelve-character IDs by default and full +IDs only for `--no-trunc`, while inspect resolves either representation. Its +failure-first regression reproduces the self-as-writer rejection, and checks +that truncated or malformed output despite `--no-trunc` holds before start in +either inventory. This correction leaves the initializer literal unchanged; +the retained actual old-ORM proof is reused without another Docker lifecycle +or ORM execution. Native attempt five exposed an assertion at outer fixture +callsite 2975; its exact inner assertion remains unknown. The local source +contract reproduction does not establish that historical inner frame. Native +execution, exact-owned terminal cleanup and external VM destruction evidence +remain necessary. This work item's initial candidate and both root-allocated +source corrections are spent; remaining native attempts grant no new source +correction allowance. + +Named-volume IPMI data creation first inventories exact volume names and rejects +any preexisting name, even empty or carrying the same run label. A fresh +per-creation nonce label and root mountpoint chain/inode custody must be +positively verified while empty before cleanup registration. A create +timeout/failure or uncertain custody remains a pending intent outside the +deletion list; reset holds and requires external VM destruction rather than +deleting unknown data. Reset rechecks the retained name, run/nonce labels, local +driver, mountpoint/root chain/inode and creation metadata immediately before +checked, non-force removal of this resource. Other layouts and existing +product/protection contracts are unchanged. + +Inventory and compare-before-remove are point-in-time custody checks under the +admitted exclusive fresh VM/trusted Engine. They do not provide atomic exclusion +against another privileged actor. The initializer's shared 60-second +command/verification deadline remains distinct from normal cleanup: a timed-out +container is not proven dead at that deadline; exact-owned terminal cleanup and +external VM destruction evidence remain required. Existing auth/anonymous-volume +handling is unchanged and is not newly certified by this repair. + +## Bounded selector observation — owner-approved 5 November 2026 + +Owner choice B (`e35a413f…` packet, `5fb2e27b…` approval) permits one new +selector-observation source candidate and at most two diagnosed corrections in +the verifier, existing route tests and this note. The original synthetic +initializer candidate and both of its corrections remain spent. The canonical +DC ledger now has cap eight, six consumed, two remaining and zero manual runs. +Ordinal seven is exactly one qualified selector diagnostic from a normal +exact-head PR synchronize, attempt one. Ordinal eight is only a conditional +actual-cause repair proof: it requires a proven current cause, a genuinely +remaining functional item, a concrete reviewed repair, predicate RED/GREEN, +two fresh independent reviews, exact root GO and complete prior cleanup. It +cannot become a second diagnostic or blind retry. The separate functional cap +three/spent one/remaining two and all G2 allowances are unchanged. + +The existing `private_write` observation hook executes the original writer +once with identical argument objects, observes only after successful +persistence while the original handled exception is available, returns the +same result, and restores the original binding on exit. It never replaces the +selector, changes an interpreter or calls an owner/selector API to collect +evidence. The first selector exception at the pinned broker callsite is the +only selector context collected. Original operation state, exception and exit +outcomes remain authoritative when collection fails. + +Original source hashes and exact loaded code objects qualify a separate +13-role table, keeping the original 19-role literal byte-identical. The total +ceiling is 32 code objects, 32 traversed traceback frames and 16 exported +`{role,line}` entries. Decorated and nested roles bind only their reviewed +original code constants. Discovery inspects already loaded modules under the +current child prefix; it does not import or execute product functions. An +unmapped innermost frame remains UNKNOWN; a recognized outer frame is never +promoted to a selector cause. The old eight DC product files, all frozen Proxy +files and the 27 protected literal assignments are unchanged. + +The operation producer is versionless. Projection now validates the exact +`_preview`/`_apply`/`save` field inventory, strict types, UUID, preview/request +fingerprints, selection identities and bounded manifest hash, without adding +`schema_version` to product records. Duplicate JSON keys, unknown fields, +boolean integers, foreign correlations and custody drift refuse the projection. +The parent reads its fixed private operation record at most once, with a +1 MiB bound, and compares it to its captured apply body, preview, expected +selection/manifest and known native administrator username. A closed +`operation_qualification` explains refusal; existing projected fields retain +their shape. Only initial absence beneath verified unchanged parents is ABSENT. + +The sudo parent qualifies the producer against only the current wheel's fixed +`/opt/fleet-native-qa/venv/lib/python3.12/site-packages/dc_overview/release_broker.py`. +Its interpreter prefix and POSIX purelib must match that exact native Python 3.12 +venv; the source must retain its admitted frozen SHA and the same descriptor +custody checks. The unchanged workflow installs and root-owns this wheel before +launch. The runner-owned `--dc-source` checkout is not a custody source for this +projection. Prefix/path/hash drift refuses source qualification; unsafe installed +file custody refuses the read, with no alternate path or checkout fallback. + +The actor subject is derived inside the server from a private authentication +secret and is not independently present in parent memory. Fingerprint +recomputation using the strictly validated stored actor is producer/custody-bound +correlation. It is neither an independent subject-origin measurement nor a +cryptographic authentication claim. No authentication secret, account state or +frame local is read, and no actor identity is exported. + +For a qualified original selector failure, the current broker child reads only +its fixed `dc_overview-1.6.4.dist-info/METADATA` and `direct_url.json`, each at +most 65,536 bytes plus one overflow sentinel. The basename is bound to retained +admitted wheel inventory; the next exact candidate wheel must independently +retain that inventory before native GO. There is no directory scan or fallback +distribution search. Module paths and both metadata files must match the current child's exact +`sysconfig` POSIX purelib location beneath that admitted Linux prefix; another directory +under the prefix is refused too. The observer compares the same module version, +distribution version, URL and hash used by `verify_running_cli`, in memory, +without replaying that predicate. It exports only booleans/null and the closed +actual/expected interpreter roles. Paths, URLs, hashes, metadata, exception +text, locals, actor data and new device/inode values are never exported. + +Descriptor ownership, regular-file type, safe ancestry, link count, mode and +before/after path/descriptor identities bound every new read. A monotonic +one-second budget is checked before/after reads and projection; expiration +refuses the observation. This does not interrupt a kernel-stalled filesystem +call. No signal, background collector, delay or retry is added. One closed +failure packet stays within the existing retained private inode and 4,096-byte +bound. Metadata is a post-failure sample, not atomic observation of the original +predicate operands; attribution beyond a qualified guard still needs accepted +source/local proof and no unresolved drift. + +Portable regressions execute the exact pinned producer expressions and original +CLI predicate with real temporary distribution metadata. They retain the real +predicate refusal and matching-metadata success control, while existing broker +tests protect original handled-save behavior. They do not identify native-six's +historical inner guard, which remains UNKNOWN, or establish native acceptance. +The 60-second initializer and 90-second mapping wait are unchanged. Root must +bind actual run/attempt/job/runner/UUID and live source/image custody at launch, +observe normal Docker/Python/Pages siblings, and retain internal cleanup plus +external VM, disk, active-record and runner absence for all four allocations. +Terminal absence cannot repair missing launch lineage. Inconclusive collection +stops the sequence; no release, customer or fleet-readiness claim follows from +this diagnostic source change. + +### Selected host environment in the named-volume fixture + +After installing the selected compatible wheels over the fixture's HTTPS mirror, +the native verifier starts an isolated interpreter from `legacy-host-venv` and +checks its actual prefix and purelib path. It qualifies the complete, unchanged +installed selector against the frozen source hash and calls the original +`verify_running_cli` URL/hash predicate. This proof reports only the interpreter +role and two success booleans; it does not change distribution metadata. The +named-volume broker's systemd drop-in then uses that same interpreter. The bind +layout keeps the original native interpreter. Matching versions or hashes alone +never substitute for matching the selected wheel's HTTPS URL. + +Selector failure packets also contain `source_stage`, a closed label for the +last attempted diagnostic check: `unknown`, `broker-source`, +`selector-discovery`, `proxy-discovery`, `selector-required` or `failure-sample`. +This label does not identify the failed product guard or authorize a retry. +Source or custody refusal retains unknown guard details and null comparisons. +The original deadlines, byte bounds, exception behavior and cleanup gates stay +in force. Earlier native attempts remain failed or unknown as recorded. + +### Named-volume proxy adoption failure observation + +The proxy adoption check opts into one diagnostic if its existing `finish` +call fails. The original status call records only a closed branch, success +boolean and owner state in memory. Socket errors still follow the original +wait loop and 420-second deadline. The diagnostic never polls again, reapplies +an operation or changes accepted terminal states. Collector and evidence-write +failures leave the original exception and traceback intact. + +After failure, the parent reads its fixed installed broker source and its own +retained operation, then the existing private child observation slot. Source, +custody, request, preview, operation fingerprint and manifest checks must pass +before state, phase, closed reason and plan comparisons are reported. The +public preview does not expose the declaration; that comparison remains null +unless the retained preview was independently supplied to the portable test. +No plan, declaration, path, digest, actor, exception text or frame local is +exported. The same one-second, 1 MiB input and 4 KiB output bounds apply. + +The child has a separate ten-role adoption code set, retaining the original +thirteen selector roles and 32-object ceiling. It uses naturally loaded code +qualified against the exact installed source; it neither imports nor calls +product code for discovery. Only a recognized innermost original frame can +identify an adoption guard. Refusal or an unknown inner frame retains unknown +attribution. The wrapper runs after the original successful operation save and +uses one adoption exception context. Portable tests execute the unchanged +adoption guard through the actual wrapper, private slot and parent projection. +These checks establish diagnostic behavior; native-eight's historical cause +remains unknown until a new qualified native result exists. + + +## Native Follow stable policy verification + +The native procedure now exercises the policy API around the existing manual +upgrade in both layouts. Its unchanged IPMI inputs map to real source versions +1.3.1 and 1.3.3; the procedure checks package metadata inside each exact running +container, immutable image identity and source revision. It retains the actual +old manifest before the legacy desired selection, keeping those identities +separate. + +Policy checks cover mode persistence after broker restart, invalid and missing +signed discovery, a real lifecycle flock, two authenticated CAS competitors, +selection without a container restart, and re-pinning after the original healthy +manual update. All container identities, start times and unrelated selections +are compared. The original dropped response, broker interruption, idempotent +replay, continuity, adoption, rollback and interrupted-adoption cases remain. + +The packaged daily timer is enabled while pinned to control Persistent catch-up, +then disabled and quiesced before Follow stable. The exact packaged one-shot is +started without an HTTP refresh to test its headless command. This checks the +configured daily schedule and command path; it does not claim that a daily wall +clock trigger elapsed. Newly created units require positive file custody before +cleanup; uncertainty holds the native result for external VM teardown. + +These are fixture procedures, not deployment evidence. The guest-only issuer +remains synthetic. Actual native CI, trusted production publication and both-site +browser acceptance require separate retained results. diff --git a/docs/native-service-recovery.md b/docs/native-service-recovery.md new file mode 100644 index 0000000..6b78289 --- /dev/null +++ b/docs/native-service-recovery.md @@ -0,0 +1,42 @@ + +# Native IPMI service restoration evidence + +Install the reviewed exact DC Overview and CryptoLabs Proxy host wheels into +the same existing CLI environment. Keep the original proxy serving. Before +`release select --record-cli` or controller adoption, run locally as Linux root: + +```sh +dc-overview release reconcile-service --service ipmi-monitor --job +``` + +The command accepts only this service and a 32-character lowercase hex native +job ID. It accepts no path, image, script, force flag or caller observation. It +resolves the serving proxy's local writable `/data/auth` mount, then holds Fleet +lifecycle, dispatch and operation exclusion in that order. It does not invoke +status, replay a worker, stop a container, clear a marker or edit job history. + +It verifies exactly one trusted retained pre-job bundle below the fixed +`/var/backups/cryptolabs/ipmi132` root, its private artifact hashes, original +container/image/runtime/config/network identity, terminal helper, fresh `/health` +and read-only stable SQLite/account/link/inventory fingerprints. Missing, +ambiguous or changed evidence holds. It creates no new baseline or DB copy. + +The only new durable updater record is a private `service-recovery-JOB.json` +receipt. The old desired deployment remains failed. Retry revalidates current +evidence and returns the same receipt without changing its timestamp. Private +fingerprints and configuration values never appear in the command response. + +After separately approved compatible selection and proxy adoption, new native +submits require the live `native_service_recovery: 1` capability and carry the +job/receipt hash binding into their worker. Workers check before pulls and again +before the first lifecycle effect. Blocked successors retain the dependency. +Only a verified successful IPMI update retires that original dependency; archived +receipts are retained without permanently pinning future runtimes. + +New jobs persist bounded intent/completion diagnostics around Engine effects. +Unknown outcomes retain only safe categories and re-observe owned IDs before +restoration. No historical phases or incident cause are synthesized. + +Local source tests are not operational clearance. Exact packaged legacy +bootstrap, protected release, fresh target custody, actual signed admission and +site/browser acceptance are separate gates. diff --git a/pyproject.toml b/pyproject.toml index 48a7763..d4ce896 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -84,6 +84,7 @@ dc_overview = [ "templates/*.conf", "templates/systemd/*.service", "templates/systemd/*.socket", + "templates/systemd/*.timer", "templates/grafana/**/*.yml", "templates/grafana/**/*.yaml", "web_templates/*.html", diff --git a/requirements.md b/requirements.md index 64a1464..0409d7b 100644 --- a/requirements.md +++ b/requirements.md @@ -44,6 +44,25 @@ The parser, tests and source authority note retain their reviewed bytes. Native acceptance awaits the automatic check on the updated PR head; no manual native dispatch or production acceptance follows from this source repair. + +## 2 November 2026 native service recovery amendment + +The existing administrative REQ/TRACE/VER/VAL-FLEETUPDATE-001 labels also +project the exact owner-approved [continuation amendment](../artifacts/ipmi-readiness-20261026/fleet-ui-20261102/architecture/continuation-amendment.json), +SHA256 `159af8421e4dde61e4ecc4f47849a1ddd7f07cd6fb158d247256f0bb36ed316e`, +and its [owner receipt](../artifacts/ipmi-readiness-20261026/fleet-ui-20261102/owner-approval.json). The frozen implementation +contract is [contract.json](../artifacts/ipmi-readiness-20261026/fleet-ui-20261102/execution/contract/contract.json), SHA256 +`91b873c548da7d10a113c8fbb74f09540559ba51339514c738e081d0dc75cf01`. +This is a linked projection, not a new approval or requirement identity. + +The fixed root host command verifies retained pre-job evidence and the exact +original service before publishing a private job-bound `original_restored` +receipt. The failed job and active pointer stay intact. Selector, native submit +and worker revalidate restoration and retain predecessor dependencies through +blocked successors. New-job phase diagnostics contain only allowlisted facts. +Source tests do not establish actual Linux bootstrap, release, target or browser +acceptance; those gates and publication remain held. + ## Central telemetry monitoring policy — approved 4 November 2026 This portable record registers the three application requirements from the @@ -100,6 +119,42 @@ through a real Prometheus scrape and the separately owned expressions in 13 scenarios. These results establish local behavior; they do not claim production deployment, notification delivery or acceptance of unrelated Fleet work. +## Owner-approved per-service stable following (4 November2026) + +Exact authority: `.traceweaver/auto-advance-20261104/plan.md`, SHA256 `94b783d925834004cd3f111dd2437f8ae531850f0184aaa29c52f89f84267795`; receipt `owner-approval.json`. Administrative REQ/TRACE/VER/VAL-AUTOADVANCE-001 through -008 map one-to-one to approved C1-C8 without changing their meaning. Source and verification may proceed; publication/runtime claims require their own current checks. Existing Fleet dependency holds remain. + +### REQ-AUTOADVANCE-001 — approved C1 + +An authenticated Fleet administrator can switch one supported managed service between Pinned and Follow stable; the visible installed/selected version and mode remain distinct. + +### REQ-AUTOADVANCE-002 — approved C2 + +Removing a pin opts only that service into verified stable candidates. Existing pins remain pinned by default. Pin current version freezes the verified installed digest; if its identity/provenance cannot be established, the operation fails without changing policy. + +### REQ-AUTOADVANCE-003 — approved C3 + +Follow stable selects the newest admitted compatible non-prerelease version within the installed major version. No downgrade; a major upgrade requires explicit selection. No usable newer candidate leaves the current selection intact and reports why. + +### REQ-AUTOADVANCE-004 — approved C4 + +Selection refresh occurs on Check Updates and a daily host-side check, including when no browser is open. It changes only opted-in services. Mode changes and refresh never install or restart containers. The existing Update action handles installation. + +### REQ-AUTOADVANCE-005 — approved C5 + +Policy mutation uses the existing host owner boundary, authenticated administrator/session/CSRF/origin checks, explicit service scope, bounded fields, selection compare-and-swap, and existing lifecycle locks. A native CLI exposes the same choices. Failed persistence, stale requests, active operations, unavailable discovery or failed trust verification preserve prior selections and modes. + +### REQ-AUTOADVANCE-006 — approved C6 + +Use verified published release/admission metadata, fixed trusted repository/channel sources and exact immutable digests. Do not replace digests with mutable :latest tags or loosen publisher/signature checks. External-owned services retain their owning lifecycle workflow; unsupported services show an explanation rather than pretending the change succeeded. + +### REQ-AUTOADVANCE-007 — approved C7 + +Show current mode, installed version, selected target and clear failure/progress states; refreshes cannot silently re-pin or cross major versions. Re-pinning prevents a concurrent scheduled refresh from advancing afterward. + +### REQ-AUTOADVANCE-008 — approved C8 + +TDD, independent correctness/security review, native Linux lifecycle/policy verification and real-browser checks precede release. Existing LTX data/accounts/settings and unrelated pins/runtimes remain preserved. + ## GPU alert quality — approved 4 November 2026 Owner instruction: “Approve and deploy to both sights”, approving the prior concise Telegram and collector/dashboard triage plan for LTX and Charlotte. Administrative identifiers below label that approved scope. Publication/deployment require fresh remote identity, tests, review, official CI/release artifacts and native site acceptance. This record is not evidence of deployment. No hardware operations, rental changes, credential changes or extra synthetic Telegram sends are authorized. diff --git a/scripts/fixtures/legacy-selected-state-protection.py b/scripts/fixtures/legacy-selected-state-protection.py new file mode 100644 index 0000000..c36b070 --- /dev/null +++ b/scripts/fixtures/legacy-selected-state-protection.py @@ -0,0 +1,305 @@ +#!/usr/bin/env python3 +# TRACEWEAVER: file-role=native-verification; req=REQ-FLEETUPDATE-001; trace=TRACE-FLEETUPDATE-001; ver=VER-FLEETUPDATE-001 +# TRACEWEAVER: verifies=VER-FLEETUPDATE-001; req=REQ-FLEETUPDATE-001; trace=TRACE-FLEETUPDATE-001 +# TRACEWEAVER: file-role=native-verification; req=REQ-FLEETUPDATE-001; trace=TRACE-FLEETUPDATE-001; ver=VER-FLEETUPDATE-001 + +"""Synthetic-only selected-table fixture producer; never a customer installer. +Adapted from retained bounded protection helper SHA256 7b4977a162e1787d4a5c957efad1b95d8c488ab484383567c643e74e6ebc5fc4. +Historical site PINS and operational entrypoint deliberately excluded. +""" + +import base64 + +import datetime + +import hashlib + +import json + +import os + +from pathlib import Path + +import signal + +import socket + +import sqlite3 + +import stat + +import subprocess + + +import time + +import uuid + +PINS = {} # populated only with newly created synthetic guest objects + +BASE = Path('/var/backups/cryptolabs/ipmi132') + +SECONDS = 180 + +MAX_STATE = 8*1024**2 + +FLOOR = 1024**3 + +MAX_WAL_GROWTH = 256*1024**2 + +HISTORY = ('ai_result','alert_history','ipmi_event','power_reading','recovery_action_log','recovery_log','sensor_reading','ssh_logs') + +INTERNAL = ('sqlite_sequence',) + +SELECTED = ('account_link_attempt','admin_config','alert_rule','cloud_sync','ecc_error_tracker','inventory_binding','maintenance_task','notification_config','o_auth_link_state','recovery_permissions','server','server_config','server_inventory','server_status','server_uptime','ssh_key','system_settings','user') + +IDENTITY_KEYS = ('ai_link_email','ai_link_user_id','ai_link_customer_id','ai_link_linked_at','ai_link_key_digest') + +def canonical_mounts(records): + destinations = [m['Destination'] for m in records] + assert len(destinations) == len(set(destinations)), 'Duplicate mount Destination' + return sorted(records, key=lambda m: (str(m.get('Destination','')), str(m.get('Source','')), + json.dumps(m,sort_keys=True,separators=(',',':')))) + +def identity_contract(saved, credential, sync_enabled, site): + assert site == 'ltx' + assert set(saved) == set(IDENTITY_KEYS) + count = len(saved) + assert all(saved.values()), 'Empty saved identity value' + assert isinstance(credential,str) and credential, 'Existing credential required' + matches = saved['ai_link_key_digest'] == hashlib.sha256(credential.encode()).hexdigest() + assert matches, 'Existing stored credential digest mismatch' + assert not sync_enabled, 'Synthetic recovery sync must remain off' + return {'saved_identity_field_count':count,'saved_identity_complete':count==5, + 'identity_mode':'saved_sso', + 'stored_key_digest_matches':matches,'expected_email_matches':None, + 'credential_present':True,'credential_sha256':hashlib.sha256(credential.encode()).hexdigest(), + 'sync_enabled':bool(sync_enabled)} + + +def need(value, category): + if not value: raise RuntimeError(category) + +def encoded(value): + return json.dumps(value,sort_keys=True,separators=(',',':'),allow_nan=False, + default=lambda v: {'sqlite_blob_base64':base64.b64encode(v).decode()} if isinstance(v,bytes) else str(v)).encode() + +def fingerprint(value): return hashlib.sha256(encoded(value)).hexdigest() + +def check_time(deadline): need(time.monotonic()<=deadline,'deadline') + +def metadata(path): + s=path.lstat() + return {'path':str(path),'device':s.st_dev,'inode':s.st_ino,'bytes':s.st_size, + 'uid':s.st_uid,'gid':s.st_gid,'mode':oct(stat.S_IMODE(s.st_mode)), + 'symlink':stat.S_ISLNK(s.st_mode),'mtime_ns':s.st_mtime_ns} + +def safe_chain(path): + for p in reversed((path,*path.parents)): + s=p.lstat();need(not stat.S_ISLNK(s.st_mode) and s.st_uid==0 and not s.st_mode&0o022,'root-custody-chain') + return path.lstat() + +def exclusive(path): + fd=os.open(path,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600) + os.fchmod(fd,0o600);return fd + +def write_private(path,value): + raw=encoded(value)+b'\n' + with os.fdopen(exclusive(path),'wb') as f:f.write(raw);f.flush();os.fsync(f.fileno()) + before=metadata(path) + fd=os.open(path,os.O_RDONLY|os.O_NOFOLLOW) + with os.fdopen(fd,'rb') as f: + opened=os.fstat(f.fileno()) + need(stat.S_ISREG(opened.st_mode) and opened.st_uid==os.getuid() and stat.S_IMODE(opened.st_mode)==0o600,'private-readback-custody') + need((opened.st_dev,opened.st_ino)==(before['device'],before['inode']),'private-readback-identity') + actual=f.read(len(raw)+1) + need(metadata(path)==before and actual==raw,'private-readback-bytes') + need(json.loads(actual)==value,'private-readback-parsed-content') + return dict(before,sha256=hashlib.sha256(actual).hexdigest(),independent_readback=True) + +def digest_file(path,deadline): + h=hashlib.sha256() + with os.fdopen(os.open(path,os.O_RDONLY|os.O_NOFOLLOW),'rb') as f: + for block in iter(lambda:f.read(1024**2),b''):check_time(deadline);h.update(block) + return h.hexdigest() + +def free(path): + s=os.statvfs(path);return s.f_bavail*s.f_frsize,s.f_favail + +def space_guard(path,required): + available,inodes=free(path);need(available>=required and inodes>=32,'capacity-and-inodes') + return {'free_bytes':available,'free_inodes':inodes,'required_bytes':required} + +def quote(name):return '"'+name.replace('"','""')+'"' + +def open_ro(path,deadline): + c=sqlite3.connect(path.as_uri()+'?mode=ro',uri=True,timeout=2) + c.set_progress_handler(lambda:int(time.monotonic()>deadline),1000) + c.execute('PRAGMA query_only=ON');need(c.execute('PRAGMA query_only').fetchone()[0]==1,'query-only');return c + +def sidecars(db,mode): + out={} + for suffix in ('-wal','-shm','-journal'): + p=Path(str(db)+suffix) + try:s=p.lstat() + except FileNotFoundError:out[suffix]={'exists':False};continue + need(stat.S_ISREG(s.st_mode),'sidecar-regular-no-symlink');out[suffix]=dict(metadata(p),exists=True) + need(out['-journal'].get('bytes',0)==0,'hot-rollback-journal') + if mode=='delete':need(all(not out[s].get('exists') for s in ('-wal','-shm')),'rollback-sidecar-drift') + return out + +def table_snapshot(c,names): + result={};used=0 + for name in sorted(names): + sql=c.execute('SELECT sql FROM sqlite_master WHERE type=\'table\' AND name=?',(name,)).fetchone() + need(sql and sql[0] and not sql[0].lstrip().upper().startswith('CREATE VIRTUAL TABLE'),'ordinary-table-schema') + info=c.execute('PRAGMA table_xinfo('+quote(name)+')').fetchall() + need(info and all(r[6]==0 for r in info),'generated-or-hidden-column') + columns=[r[1] for r in info];pk=[r[1] for r in sorted(info,key=lambda r:r[5]) if r[5]] + order=','.join(quote(k) for k in pk) if pk else 'rowid' + rows=[] + for row in c.execute('SELECT '+','.join(map(quote,columns))+' FROM '+quote(name)+' ORDER BY '+order): + used+=len(encoded(row));need(used<=MAX_STATE,'selected-state-size');rows.append(row) + result[name]={'create_sql':sql[0],'columns':columns,'rows':rows} + used+=len(encoded([name,sql[0],columns]));need(used<=MAX_STATE,'selected-state-size') + return result + +def state_aggregate(state,site): + need({'system_settings','cloud_sync','server'}<=set(state),'required-state-tables') + settings=state['system_settings'];records=[dict(zip(settings['columns'],r)) for r in settings['rows']] + saved={r['key']:r['value'] for r in records if r['key'] in IDENTITY_KEYS} + cloud=state['cloud_sync'];need(len(cloud['rows'])==1,'cloud-row-count');row=dict(zip(cloud['columns'],cloud['rows'][0])) + link=identity_contract(saved,row.get('license_key'),row.get('sync_enabled'),site) + cloud_volatile=('last_sync','last_sync_status','last_sync_message','updated_at') + stable_cloud_columns=[n for n in cloud['columns'] if n not in cloud_volatile] + stable_cloud_rows=[tuple(dict(zip(cloud['columns'],r))[n] for n in stable_cloud_columns) for r in cloud['rows']] + inventory=state['server'];inventory_volatile=('status','updated_at') + stable_inventory_columns=[n for n in inventory['columns'] if n not in inventory_volatile] + stable_inventory_rows=[tuple(dict(zip(inventory['columns'],r))[n] for n in stable_inventory_columns) for r in inventory['rows']] + settings_pairs=sorted((r['key'],r['value']) for r in records) + return {'state_sha256':fingerprint(state),'counts':{n:len(v['rows']) for n,v in state.items()}, + 'table_sha256':{n:fingerprint(v) for n,v in state.items()},'saved_identity_sha256':fingerprint(saved), + 'stable_cloud_sha256':fingerprint([stable_cloud_columns,stable_cloud_rows]), + 'settings_sha256':fingerprint(settings_pairs), + 'stable_inventory_sha256':fingerprint([stable_inventory_columns,stable_inventory_rows]), + 'cached_subscription_valid':bool(row.get('subscription_valid')),**link} + +def baseline_guard(baseline,pin): + for key in ('stable_cloud_sha256','settings_sha256','stable_inventory_sha256','cached_subscription_valid'): + need(baseline[key]==pin['protection_baseline'][key],'stable-protection-baseline') + need(baseline['cached_subscription_valid'] is True,'cached-valid-predicate') + need(set(baseline['counts'])==set(pin['selected_count_bounds']),'selected-count-coverage') + for name,count in baseline['counts'].items(): + low,high=pin['selected_count_bounds'][name] + need(low<=count<=high,'selected-table-count-bound') + +def roundtrip_selected(state,path,site,deadline,guard): + fd=exclusive(path);identity=os.fstat(fd);os.close(fd) + dest=sqlite3.connect(str(path),timeout=2) + dest.set_progress_handler(lambda:int(time.monotonic()>deadline),1000) + try: + dest.execute('PRAGMA foreign_keys=OFF') # Isolated partial-schema verification only; never production DB. + dest.execute('BEGIN') + for name,table in state.items(): + check_time(deadline);guard();dest.execute(table['create_sql']) + columns=table['columns'];statement='INSERT INTO '+quote(name)+' ('+','.join(map(quote,columns))+') VALUES ('+','.join('?' for _ in columns)+')' + for start in range(0,len(table['rows']),256): + check_time(deadline);guard();dest.executemany(statement,table['rows'][start:start+256]) + dest.commit() + finally:dest.close() + actual=path.lstat();need((actual.st_dev,actual.st_ino)==(identity.st_dev,identity.st_ino) and stat.S_IMODE(actual.st_mode)==0o600,'destination-identity') + verify=open_ro(path,deadline) + try: + need(verify.execute('PRAGMA quick_check').fetchall()==[('ok',)],'isolated-selected-quick-check') + readback=table_snapshot(verify,state.keys()) + need(encoded(readback)==encoded(state),'isolated-selected-roundtrip') + need(state_aggregate(readback,site)==state_aggregate(state,site),'selected-aggregate-roundtrip') + finally:verify.close() + need(not any(Path(str(path)+s).exists() for s in ('-wal','-shm','-journal')),'destination-sidecars') + with os.fdopen(os.open(path,os.O_RDONLY|os.O_NOFOLLOW),'rb') as f:os.fsync(f.fileno()) + return dict(metadata(path),sha256=digest_file(path,deadline),quick_check='ok',selected_state_roundtrip=True) + +def runtime(pin): + q=json.loads(subprocess.check_output(['/usr/bin/docker','container','inspect','ipmi-monitor'],timeout=15,stderr=subprocess.PIPE))[0] + need(q['Id']==pin['container_id'] and q['Image']==pin['image_id'] and q['State']['Running'],'runtime-identity') + need(canonical_mounts(q['Mounts'])==canonical_mounts(pin['mounts']),'runtime-full-mount-records') + return q + +def main(site): + need(site in PINS and bool(PINS[site]) and os.geteuid()==0,'bound-site-and-root') + pin=PINS[site];need(pin.get('synthetic_fixture_only') is True,'synthetic-only-binding');need(socket.gethostname()==pin['hostname'],'hostname') + deadline=time.monotonic()+SECONDS + def alarm(signum,frame):raise RuntimeError('deadline') + signal.signal(signal.SIGALRM,alarm);signal.alarm(SECONDS);os.umask(0o077) + q=runtime(pin);mount=[m for m in q['Mounts'] if m['Destination']=='/app/data'] + need(len(mount)==1 and mount[0].get('Name')==pin.get('data_volume_name') and + isinstance(pin.get('data_volume_name'),str) and bool(pin['data_volume_name']) and + mount[0]['Type']=='volume','data-mount') + db=Path(mount[0]['Source'])/'ipmi_events.db';s=safe_chain(db);need(stat.S_ISREG(s.st_mode),'source-regular') + need((s.st_dev,s.st_ino)==(pin['database_device'],pin['database_inode']),'source-identity') + with db.open('rb') as f:header=f.read(100) + need(header[:16]==b'SQLite format 3\0' and list(header[18:20])==pin['journal_header_bytes'],'source-header') + mode={b'\x01\x01':'delete',b'\x02\x02':'wal'}[header[18:20]] + need(mode!='wal' or sqlite3.sqlite_version_info>=(3,22,0),'sqlite-ro-wal-version');before_sidecars=sidecars(db,mode) + secret_metadata=[] + for expected in pin['secret_mount_metadata']: + observed=metadata(Path(expected['path']));need(observed==expected,'readonly-secret-mount-custody');secret_metadata.append(observed) + safe_chain(Path('/var/backups'));capacity=space_guard(Path('/var/backups'),FLOOR+4*MAX_STATE);space_guard(db.parent,FLOOR+MAX_WAL_GROWTH) + c=open_ro(db,deadline);operation=None + try: + need(c.execute('PRAGMA journal_mode').fetchone()[0]==mode,'journal-mode');c.execute('BEGIN') + snapshot_started_at=datetime.datetime.now(datetime.timezone.utc).isoformat() + schema=c.execute('SELECT type,name,tbl_name,sql FROM sqlite_master ORDER BY type,name').fetchall() + need(fingerprint(schema)==pin['schema_sha256'],'schema-pin') + names={r[0] for r in c.execute("SELECT name FROM sqlite_master WHERE type='table'")} + need(names==set(pin['table_names']) and names<=set(SELECTED+HISTORY+INTERNAL),'exact-table-inventory') + selected=names&set(SELECTED);state=table_snapshot(c,selected);baseline=state_aggregate(state,site) + for k,v in pin['link_baseline'].items():need(baseline[k]==v,'link-baseline-continuity') + baseline_guard(baseline,pin) + pinned_sidecars=sidecars(db,mode) + for directory in (BASE.parent,BASE): + try:directory.mkdir(mode=0o700) + except FileExistsError:pass + s=safe_chain(directory);need(stat.S_ISDIR(s.st_mode) and stat.S_IMODE(s.st_mode)==0o700,'backup-parent-private') + operation=BASE/(site+'-'+datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ-')+uuid.uuid4().hex) + operation.mkdir(mode=0o700);safe_chain(operation) + def guard(): + check_time(deadline);space_guard(operation,FLOOR);space_guard(db.parent,FLOOR) + s=db.lstat();need((s.st_dev,s.st_ino)==(pin['database_device'],pin['database_inode']),'source-inode-drift') + current=sidecars(db,mode) + need(current['-wal'].get('bytes',0)-pinned_sidecars['-wal'].get('bytes',0)<=MAX_WAL_GROWTH,'wal-growth') + artifacts=[write_private(operation/'runtime-config.private.json',{k:q[k] for k in ('Id','Image','Config','HostConfig','Mounts','NetworkSettings')})] + configs={};config_mount=[m for m in q['Mounts'] if m['Destination']=='/app/config/servers.yaml'] + need(len(config_mount)==1 and config_mount[0]['Type']=='bind','config-mount') + for index,(name,path) in enumerate(sorted({'/app/config/servers.yaml':Path(config_mount[0]['Source']),'/app/data/servers.json':db.parent/'servers.json'}.items())): + expected=pin['declared_config'][name] + if not path.exists() and not path.is_symlink():need(not expected['present'],'config-presence');configs[name]={'present':False};continue + s=safe_chain(path);need(stat.S_ISREG(s.st_mode) and s.st_size<=MAX_STATE,'config-source-custody') + before=metadata(path) + with os.fdopen(os.open(path,os.O_RDONLY|os.O_NOFOLLOW),'rb') as f:raw=f.read(MAX_STATE+1) + need(len(raw)<=MAX_STATE and metadata(path)==before,'config-coherence');need(expected['present'] and hashlib.sha256(raw).hexdigest()==expected['sha256'],'config-pin') + target=operation/('config-'+str(index)+'.private') + with os.fdopen(exclusive(target),'wb') as f:f.write(raw);f.flush();os.fsync(f.fileno()) + copied=dict(metadata(target),sha256=digest_file(target,deadline));need(copied['sha256']==expected['sha256'],'config-copy-usability') + configs[name]={'present':True,'source':before,'backup':copied};artifacts.append(copied) + artifacts.append(roundtrip_selected(state,operation/'selected-state.private.sqlite',site,deadline,guard));guard() + finally:c.rollback();c.close() + need(runtime(pin)['Config']==q['Config'],'runtime-config-drift') + need([metadata(Path(m['path'])) for m in secret_metadata]==secret_metadata,'readonly-secret-final-custody') + for name,receipt in configs.items(): + p=Path(config_mount[0]['Source']) if name=='/app/config/servers.yaml' else db.parent/'servers.json' + need((p.exists() or p.is_symlink())==receipt['present'],'config-final-presence') + if receipt['present']:need(metadata(p)==receipt['source'] and digest_file(p,deadline)==receipt['backup']['sha256'],'config-final-drift') + with db.open('rb') as f:need(f.read(20)[18:20]==header[18:20],'source-final-header') + result={'status':'verified-bounded-selected-state-protection','site':site,'hostname':socket.gethostname(),'utc':datetime.datetime.now(datetime.timezone.utc).isoformat(), + 'operation_dir':str(operation),'source':{'path':str(db),'device':pin['database_device'],'inode':pin['database_inode'],'schema_sha256':pin['schema_sha256']}, + 'source_snapshot_started_at':snapshot_started_at,'source_sql_read_only':True,'source_journal_mode':mode,'source_sidecars_before':before_sidecars,'source_sidecars_after':sidecars(db,mode), + 'baseline':baseline,'selected_tables':sorted(selected),'excluded_history_tables':sorted(names&set(HISTORY)),'excluded_internal_tables':sorted(names&set(INTERNAL)), + 'artifacts':artifacts,'declared_config':configs,'readonly_secret_mount_custody':secret_metadata,'capacity':capacity,'deadline_seconds':SECONDS,'elapsed_seconds':round(SECONDS-(deadline-time.monotonic()),3), + 'private_key_directories_traversed_or_copied':False,'new_full_database_snapshot':False,'production_database_restore':False, + 'recovery_scope':'Isolated selected-table typed-row roundtrip and current declared-config copies only. Primary recovery is intact shared original database plus exact old image/native rollback. Remaining history, internal allocator state and filesystem secret mounts remain in place. This is not whole-database disaster/history restore or a production restore test.'} + receipt=write_private(operation/'receipt.json',result) + fd=os.open(operation,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW) + try:os.fsync(fd) + finally:os.close(fd) + check_time(deadline);signal.alarm(0);print(json.dumps(dict(result,receipt=receipt),sort_keys=True)) diff --git a/scripts/verify_fleet_release_native.py b/scripts/verify_fleet_release_native.py index 641aa31..8c8ca4c 100644 --- a/scripts/verify_fleet_release_native.py +++ b/scripts/verify_fleet_release_native.py @@ -3,6 +3,12 @@ """One sequential, guest-only integration proof. This is never a production installer.""" import argparse +import copy +import base64 +import contextlib +import selectors +import threading +import dis import hashlib import importlib import importlib.metadata @@ -16,15 +22,19 @@ import stat import subprocess import sys +import sysconfig import time import tomllib +import types import uuid +import zipfile +from dataclasses import dataclass from pathlib import Path REGISTRY_IMAGE = "registry@sha256:1290056e2357eceb0c047cb60ae9abb370305a218e2df650eb8d3ea021b1c151" NGINX_BASE = "nginx@sha256:2db7d28517d1fba17c2da3210395f7be11a11b419246ad0da2edf782af72f367" -IPMI_OLD = "ghcr.io/cryptolabsza/ipmi-monitor@sha256:14774a0784787d95b32a6c94e28de84accc88f0c28f17e3b30e984f2c2f17fa5" -IPMI_NEW = "ghcr.io/cryptolabsza/ipmi-monitor@sha256:84563cf838bd34c12cc83239c06c44f9a69c01b9dfff570e35ca913ef1825dac" +IPMI_OLD = "ghcr.io/cryptolabsza/ipmi-monitor@sha256:738f11f7b432c4d9d8409154c9ca3f531a1e069999eb639a9d86433e84ac279d" +IPMI_NEW = "ghcr.io/cryptolabsza/ipmi-monitor@sha256:1d616479a3842f5101615b6d97552f732de73fd424fcb844a9c643e92abc8bb1" ROOT = Path("/var/lib/fleet-native-qa") CONFIG = Path("/etc/dc-overview") PROXY_CONFIG = Path("/etc/cryptolabs-proxy") @@ -35,32 +45,113 @@ SERVICE = "dc-overview-release-broker.service" SOCKET_UNIT = "dc-overview-release-broker.socket" ORIGIN = "https://127.0.0.1:18443" +# Fixed public OCI revision/project-version evidence is retained with native QA. +# Runtime package metadata must independently match before and after installation. +IPMI_POLICY_PROOFS = { + 'ipmi-old': {'version': '1.3.1', 'reference': IPMI_OLD, + 'source_revision': 'a5cfd4ea0d6e43c6346f641693fcb6eef449433b'}, + 'ipmi-new': {'version': '1.3.3', 'reference': IPMI_NEW, + 'source_revision': 'cf79b1258e9b6c0daed8c9c998218e4fb48cc0db'}, +} +POLICY_REFRESH_SYSTEMD = Path('/etc/systemd/system') +POLICY_REFRESH_UNITS = ('dc-overview-release-refresh.service', 'dc-overview-release-refresh.timer') +# The exact reviewed body is also extracted, never reimplemented, by local V&V. +SYNTHETIC_SITE_INITIALIZER = """\ +# Proposed literal body to embed once in verifier; NOT EXECUTED by definition. +# Local driver executes the candidate verifier literal byte-for-byte after source GO. +import atexit +import hashlib +import importlib +import importlib.util +import os +from pathlib import Path +import socket +import subprocess +import threading +import urllib.request +import requests + +def denied(*args, **kwargs): + raise RuntimeError('synthetic initializer forbidden transport/background') + +# A network-none container is mandatory in addition to these local sentinels. +subprocess.run = denied +subprocess.Popen = denied +socket.socket.connect = denied +socket.socket.connect_ex = denied +urllib.request.urlopen = denied +requests.sessions.Session.request = denied +threading.Thread.start = denied +assert os.environ['SITE_NAME'] == 'SYNTHETIC Fleet native fixture' +# Native DATA_DIR must equal /app/data; local driver substitutes one fresh temp directory. +assert Path(os.environ['DATA_DIR']).is_dir() +spec = importlib.util.find_spec('ipmi_monitor.app') +assert spec is not None and spec.origin is not None +assert hashlib.sha256(Path(spec.origin).read_bytes()).hexdigest() == 'e3e569fc0c98e3247f525b0ed5cc54da36a8ba9334b0d532322cc23dbd7b22a8' +module = importlib.import_module('ipmi_monitor.app') +atexit.unregister(module.report_shutdown) +assert module._background_started is False +assert Path(module.DATA_DIR).resolve() == Path(os.environ['DATA_DIR']).resolve() +assert Path(module.__file__).resolve() == Path(spec.origin).resolve() +expected_columns = ('id','license_key','sync_enabled','sync_interval','last_sync', + 'last_sync_status','last_sync_message','subscription_tier','subscription_valid', + 'max_servers','features','site_id','site_name','site_location','created_at','updated_at') +with module.app.app_context(): + assert module.Server.query.count() == module.ServerInventory.query.count() == 0 + assert module.ServerStatus.query.count() == 0 + assert tuple(column.name for column in module.CloudSync.__table__.columns) == expected_columns + assert module.CloudSync.query.count() == 0 + config = module.CloudSync.get_config() + assert module.CloudSync.query.count() == 1 and config.id == 1 + assert config.site_id is None and config.site_name is None + config.site_id = 'synthetic-fleet-native-site' + config.site_name = 'SYNTHETIC Fleet native fixture' + module.db.session.commit() + def all_rows(): + module.db.session.expire_all() + return tuple(tuple(getattr(row, name) for name in expected_columns) + for row in module.CloudSync.query.order_by(module.CloudSync.id).all()) + baseline = all_rows() + assert len(baseline) == 1 + for _ in range(2): + assert module.get_or_create_site_id() == ('synthetic-fleet-native-site', 'SYNTHETIC Fleet native fixture') + assert all_rows() == baseline + assert module._background_started is False + assert module.Server.query.count() == module.ServerInventory.query.count() == 0 +# No row values/hashes or imported module exception payload are exported. +""" # Filled from the accepted frozen source manifests, never from an untrusted runtime response. +# TRACEWEAVER: verifies=VER-AUTOADVANCE-008; req=REQ-AUTOADVANCE-008; trace=TRACE-AUTOADVANCE-008 FROZEN_PRODUCT_HASHES = { "dc": { - "src/dc_overview/cli.py": "39ec1edbf04d91293eed13a63f7fd8cc7d6f1a3f2d4f83017829cfe3b7c83b7f", - "src/dc_overview/fleet_upgrade.py": "5f4504f38f64c59d00ca90b13cf94eb905c5fe3fe5ebd3fa49b28561f0d8cc14", - "src/dc_overview/release_broker.py": "137c990c00ba4d59ade7c8490b9fd9b574709f73c0d072466bbc41e253fbb33b", + "src/dc_overview/cli.py": "6740c70dd03366317f245d73096277341c080cb3a5f2cdf48eb389280a7abc2f", + "src/dc_overview/fleet_upgrade.py": "ac7d1e55de5707130b2acbf6e92b861ec960413a8fea4d6ff0097984111b8934", + "src/dc_overview/release_broker.py": "5916872d5ec87a2e9b69529c2c8a16f9a871667d9ff0ae27a0f1691fcaa296b7", "src/dc_overview/release_broker_service.py": "92dbdf0d83c2aa3ef74a518947599102077c58ee85a95589690087052d115d08", "src/dc_overview/release_candidates.py": "bf8bd9145005901817cb4bbaa24726dbee20e7555e782e7383722e24df1d41a3", "src/dc_overview/release_catalog.py": "21d4cf4731226c4ca9498cd4999bec1ec90bb9d3628faa615e13f20ccd9a29f6", "src/dc_overview/templates/systemd/dc-overview-release-broker.service": "6128bf4553bd87458c680377e1b4490fc157b6f092072271bc77bd21b18c4612", "src/dc_overview/templates/systemd/dc-overview-release-broker.socket": "67994e4c1d4b2ac9fa4b44de9e8ba60db2b087424993fce77656c0618272c559", + "src/dc_overview/release_policy.py": "0061e5a66b4f5495fe7bc83e8426b085983a1c42c12bb25cfdf853c33dc06b7b", + "src/dc_overview/templates/systemd/dc-overview-release-refresh.service": "b21ecf63d9ab5ce9a39ed84aeedb706a8064a38485bb22f85c3bdfbc0ed9dd2e", + "src/dc_overview/templates/systemd/dc-overview-release-refresh.timer": "1bfcb7323a7e29f240c923e6e9d2f75f41717e2fd0ee385e4232d0fd34dfd3ca", }, "proxy": { + "src/cryptolabs_proxy/update_recovery.py": "0063848821dd41d8f600e936a432bee10c80f9851ce0b99a00aea8aa43f29316", "src/cryptolabs_proxy/account_link.py": "c9f921e25ee0341c3b191064f1a57c94919310d5d4e08ec2c2c3030b964ea634", - "landing-page/index.html": "20061e8140c5132b68f0bdc5a7ebfd48023534cf6f1ea7f2921ea6d04530ff37", + "landing-page/index.html": "1d88cf658c71b58af29d501837e876c0f48c0e7d5083a0f90fab4ba8e6774552", "nginx/nginx.conf": "5a6f8bbd6c9121fb0b1a2fd4884205b996f52c332ae2e0ea9b026fc5a748ed7d", "scripts/health-api.py": "cc70687058e964b1afce202fed0117f8fee511cdece637f853eee2f25684e6d3", - "src/cryptolabs_proxy/auth.py": "e9bda16030012f4045364ea4fa6929c6d42e6da5d4e1392259298fbcff3fb679", + "src/cryptolabs_proxy/auth.py": "dd0149b619ee37aced86cd8de4829e3487b476217cd0733a570c727bff1be08d", "src/cryptolabs_proxy/config.py": "cb921e11d4cf316df013c53bd36c7de89b0a8e5cb66df6dd3131f7425d15cf3f", - "src/cryptolabs_proxy/release_client.py": "d3ed1dd31ea3a54f07a17772fefdbbb1bc9105880ab7b0d563f17d73a4332c25", + "src/cryptolabs_proxy/release_client.py": "dd496ad4d007cb98039e5ba8bdf899398dc576d2448e199be6e875b7c1d75fec", "src/cryptolabs_proxy/release_selection.py": "b56a4dac88c8ef0c03500430ab1054bcf142e4bfaeef7edce67fce0f27f5b5d4", - "src/cryptolabs_proxy/standard_adoption.py": "46f7bd6d889d00d41f632e6246f9269ea9a1833626482383acbfd30454d079a2", + "src/cryptolabs_proxy/standard_adoption.py": "dbb9cbc33727efabf6b267a8c909d7fb0269d4aba97cb0dd7178379bcea15e08", "src/cryptolabs_proxy/templates/docker-compose.yml.j2": "ec923fb17e99c649bb0aacd95eb8aeee465cfc9dbc6c65b721461cbf094a8856", "src/cryptolabs_proxy/templates/nginx.conf.j2": "d14273f48d5370f480870068b8bcf1ebb2a84a868979079ff97549ef8fcdd7ed", "src/cryptolabs_proxy/templates/previous-standard-nginx-444d7c0.conf.j2": "f12e2b9800cbaa0e49e685506cfaad38eb7e568fa6d239fa15277af59073d8de", - "src/cryptolabs_proxy/updates.py": "cdb0958893eb6a11dc2764c4384ea784bf4b9632418a0871c3cee35bde3d00b6", + "src/cryptolabs_proxy/templates/previous-standard-nginx-8e2b421.conf.j2": "05828b78143c5d6cd7cbe60700cfc54b627cb4efff9a7af43439fdb56e25edab", + "src/cryptolabs_proxy/updates.py": "c1b800399824f05af8dfcd764ac32639b4ed7d428545282f080e4386fc571fe2", }, } @@ -159,18 +250,590 @@ def write(path, value, mode=0o600): os.replace(temporary, path) -def run(*args, input_bytes=None, timeout=180, check=True, env=None): +# Whole child-output observations only; repeated literals never identify an executed guard. +SCOPED_SELECT_MESSAGES = ( + (b'Error: requires_cli_upgrade: install the verified exact wheel from the selected manifest using the documented package-manager step, then rerun this command\n', 'cli-provenance-rejected'), + (b'Error: native_service_recovery_required\n', 'recovery-required'), + (b'Error: updater is busy; retry scoped selection after it finishes\n', 'updater-busy'), + (b'Error: updater custody changed during scoped selection\n', 'updater-custody-changed'), + (b'Error: updater store changed during scoped selection\n', 'updater-store-changed'), + (b'Error: updater lock changed during scoped selection\n', 'updater-lock-changed'), + (b'Error: public configuration/selection snapshot is stale\n', 'public-reference-stale'), + (b'Error: public configuration changed after release preflight\n', 'public-reference-changed'), + (b'Error: running proxy identity is required for scoped selection\n', 'proxy-identity-required'), + (b'Error: proxy changed during scoped selection\n', 'proxy-identity-changed'), + (b'Error: proxy read-only release mount prerequisite\n', 'proxy-release-mount-required'), + (b'Error: updater mount changed during scoped selection\n', 'updater-mount-changed'), + (b'Error: manifest changed during scoped preparation\n', 'manifest-changed'), + (b'Error: scoped runtime changed during selection\n', 'runtime-changed'), + (b'Error: Proxy updater authority prerequisite: install the compatible published cryptolabs-proxy package, then use cryptolabs-proxy configuration plan and cryptolabs-proxy configuration adopt to migrate the existing proxy before retrying. The running updater must advertise selection contract 1 and proxy_replacement_policy=host-adoption-required-v1; no update was submitted or release changes applied.\n', 'proxy-authority-required'), +) + + +def scoped_select_category(value, categories=tuple(category for _, category in SCOPED_SELECT_MESSAGES)): + if type(value) is not str: + return "unknown" + return next((category for category in categories if value == category), "unknown") + + +def classify_scoped_select_output(returncode, stdout, stderr, messages=SCOPED_SELECT_MESSAGES): + """Project exact bounded built-in buffers into one fixed public category.""" + if (type(returncode) is not int or returncode != 1 or type(stdout) is not bytes + or stdout != b"" or type(stderr) is not bytes or len(stderr) > 512): + return "unknown" + return next((category for literal, category in messages if stderr == literal), "unknown") + + +INNER_GUARDS = { + "proxy-updates": ("service_recovery_dependency", "_validate_predecessor", "observe_original", + "_require_terminated_helper", "_require_recovery_capability", + "_needs_service_receipt", "_retains_predecessor"), + "proxy-recovery": ("hold", "require", "strict_json", "_pairs", "_finite_float", "_pattern", + "validate_continuity", "validate_receipt", "_private", "open_existing_directory", + "read_private", "validate_job", "load_bound_job", "validate_original_restored", + "runtime_fingerprints", "_timestamp"), +} +_SCOPED_SELECT_DISPATCH_FRAME = None +_SCOPED_SELECT_TRACEBACK = None + + +CONTINUITY_FIELDS = ( + "runtime_config_sha256", "host_config_sha256", "mounts_sha256", "network_sha256", + "schema_sha256", "settings_sha256", "stable_cloud_sha256", "stable_inventory_sha256", + "saved_identity_sha256", "declared_config_sha256", "database_device", "database_inode", +) +_OBSERVATION_FIELDS = ("container_id", "image_id", "helper_terminated", "healthy", "continuity") + + +@dataclass(frozen=True) +class _ContinuityObservationShape: + container_id: str + image_id: str + helper_terminated: bool + healthy: bool + continuity: dict + + +@dataclass(frozen=True, slots=True) +class _InnerTrustedContext: + codes: tuple + recovery_globals: dict + observation_class: type + + def __iter__(self): + return iter(self.codes) + + def __bool__(self): + return bool(self.codes) + + +def bind_inner_trusted_context(codes, recovery): + """Capture class identity after source qualification, before original execution.""" + if type(codes) is not tuple or type(recovery) is not types.ModuleType: + return () + namespace = vars(recovery) + cls = namespace.get("OriginalObservation") + if not continuity_class_valid(namespace, cls): + return codes # Guard coordinates remain useful; field facts stay unbound. + return _InnerTrustedContext(codes, namespace, cls) + + +def inner_unknown(): + return {"guards": [], "condition": "unknown", "require_capability": "unknown", + "continuity_equal": "unknown"} + + +def continuity_equal_record(value): + if (type(value) is not dict or any(type(k) is not str for k in value) + or set(value) != set(CONTINUITY_FIELDS) + or any(type(v) is not bool for v in value.values()) or all(value.values())): + return "unknown" + return {key: value[key] for key in CONTINUITY_FIELDS} + + +def continuity_values_valid(value): + """Check primitives before comparing; never invoke a foreign equality method.""" + fixed = {"projection", "saved_identity_field_count", "stored_key_digest_matches", "sync_enabled"} + if (type(value) is not dict or any(type(k) is not str for k in value) + or set(value) != set(CONTINUITY_FIELDS) | fixed): + return False + for key in CONTINUITY_FIELDS[:10]: + if type(value[key]) is not str or re.fullmatch("[0-9a-f]{64}", value[key]) is None: + return False + return (type(value["projection"]) is str and value["projection"] == "ipmi-original-continuity-v1" + and type(value["database_device"]) is int and value["database_device"] >= 0 + and type(value["database_inode"]) is int and value["database_inode"] > 0 + and type(value["saved_identity_field_count"]) is int and value["saved_identity_field_count"] == 5 + and value["stored_key_digest_matches"] is True and value["sync_enabled"] is False) + + +def continuity_class_valid(namespace, cls): + if type(cls) is not type: + return False + attributes = vars(cls) + if (type(attributes.get("__module__")) is not str or type(namespace.get("__name__")) is not str + or attributes["__module__"] != namespace["__name__"] + or cls.__name__ != "OriginalObservation" or cls.__qualname__ != "OriginalObservation" + or type(attributes.get("__match_args__")) is not tuple + or any(type(k) is not str for k in attributes["__match_args__"]) + or attributes["__match_args__"] != _OBSERVATION_FIELDS + or "__getattribute__" in attributes or "__getattr__" in attributes + or any(name in attributes for name in _OBSERVATION_FIELDS)): + return False + for name in ("__init__", "__eq__", "__setattr__", "__delattr__", "__hash__"): + method = attributes.get(name) + if (type(method) is not types.FunctionType or method.__globals__ is not namespace + or len(method.__code__.co_consts) > 16 + or any(not (type(c) in (str, int, bool, type(None)) or + (type(c) in (tuple, frozenset) and len(c) <= 8 + and all(type(k) is str for k in c))) for c in method.__code__.co_consts) + or not helper_code_matches(method.__code__, vars(_ContinuityObservationShape)[name].__code__)): + return False + descriptor = attributes.get("__dict__") + if type(descriptor) is not types.GetSetDescriptorType or descriptor.__objclass__ is not cls: + return False + return True + + +def project_continuity_frame(frame, trusted): + """Use the already captured exact guard frame, never rerun any observer/validator.""" + namespace, local = frame.f_globals, frame.f_locals + if type(trusted) is not _InnerTrustedContext or trusted.recovery_globals is not namespace: + return "unknown" + observation, receipt = local.get("observation"), local.get("value") + cls = trusted.observation_class + if (namespace.get("OriginalObservation") is not cls or type(observation) is not cls + or not continuity_class_valid(namespace, cls)): + return "unknown" + for name in ("validate_original_restored", "validate_receipt", "validate_job", "validate_continuity", "require", "hold", "_pattern"): + function = namespace.get(name) + if (type(function) is not types.FunctionType or function.__globals__ is not namespace + or not any(code is function.__code__ and source == "proxy-recovery" and guard == name + for code, source, guard in trusted)): + return "unknown" + hashes, keys = namespace.get("HASH_KEYS"), namespace.get("CONTINUITY_KEYS") + if (type(hashes) is not set or any(type(k) is not str for k in hashes) + or hashes != set(CONTINUITY_FIELDS[:10]) or type(keys) is not set + or any(type(k) is not str for k in keys) + or keys != set(CONTINUITY_FIELDS) | {"projection", "saved_identity_field_count", "stored_key_digest_matches", "sync_enabled"}): + return "unknown" + descriptor = vars(cls)["__dict__"] + state = descriptor.__get__(observation, cls) + if (type(state) is not dict or any(type(k) is not str for k in state) + or set(state) != set(_OBSERVATION_FIELDS) + or state["helper_terminated"] is not True or state["healthy"] is not True + or type(state["container_id"]) is not str or re.fullmatch("[0-9a-f]{64}", state["container_id"]) is None + or type(state["image_id"]) is not str or re.fullmatch("sha256:[0-9a-f]{64}", state["image_id"]) is None + or type(receipt) is not dict or any(type(k) is not str for k in receipt) + or "continuity" not in receipt): + return "unknown" + before, after = receipt["continuity"], state["continuity"] + if not continuity_values_valid(before) or not continuity_values_valid(after): + return "unknown" + return continuity_equal_record({key: before[key] == after[key] for key in CONTINUITY_FIELDS}) + + +def inner_record(value): + """Closed value schema; never coerce foreign objects or retain mutable input.""" + unknown = inner_unknown() + if (type(value) is not dict or any(type(k) is not str for k in value) + or set(value) != set(unknown)): + return unknown + guards = value["guards"] + if type(guards) is not list or len(guards) > 256: + return unknown + result = inner_unknown() + for row in guards: + if (type(row) is not dict or any(type(k) is not str for k in row) + or set(row) != {"source", "guard", "line"}): + return unknown + source, guard, line = row["source"], row["guard"], row["line"] + if (type(source) is not str or source not in INNER_GUARDS or type(guard) is not str + or guard not in INNER_GUARDS[source] or type(line) is not int or not 0 < line < 65536): + return unknown + result["guards"].append({"source": source, "guard": guard, "line": line}) + for key in ("condition", "require_capability"): + fact = value[key] + if type(fact) is not bool and not (type(fact) is str and fact == "unknown"): + return unknown + result[key] = fact + equality = value["continuity_equal"] + result["continuity_equal"] = continuity_equal_record(equality) + if result["continuity_equal"] != "unknown" and (result["condition"] is not False + or sum(g == {"source": "proxy-recovery", "guard": "validate_original_restored", "line": 228} + for g in result["guards"]) != 1): + return unknown + if result["continuity_equal"] == "unknown" and not (type(equality) is str and equality == "unknown"): + return unknown + if not guards and result != unknown: + return unknown + return result + + +def inner_contexts(error): + contexts, seen = [], set() + while error is not None: + if id(error) in seen or len(contexts) == 8: + return None + seen.add(id(error)) + contexts.append(error) + error = BaseException.__context__.__get__(error, type(error)) + return contexts + + +def project_inner_failure(error, trusted): + """Read selected strict booleans only after exact loaded-code qualification.""" + contexts = inner_contexts(error) + if contexts is None: + return inner_unknown() + result = inner_unknown() + facts = {"condition": set(), "require_capability": set()} + seen = set() + continuity = [] + for context in contexts: + if type(context) not in (ValueError, RuntimeError, TypeError, KeyError, OSError, + FileNotFoundError, PermissionError): + return inner_unknown() + trace = BaseException.__traceback__.__get__(context, type(context)) + count, leaf = 0, None + while trace is not None: + if count == 32: + return inner_unknown() + count += 1 + code, line = trace.tb_frame.f_code, trace.tb_lineno + leaf = next((row for row in trusted if row[0] is code), None) + if leaf is not None: + if type(line) is not int or line not in {n for _, _, n in code.co_lines()}: + return inner_unknown() + _, source, guard = leaf + coordinate = (source, guard, line) + if coordinate not in seen: + result["guards"].append(dict(source=source, guard=guard, line=line)) + seen.add(coordinate) + key = ("condition" if (source, guard) == ("proxy-recovery", "require") else + "require_capability" if (source, guard) == ("proxy-updates", "service_recovery_dependency") else None) + if key is not None: + value = trace.tb_frame.f_locals.get(key) + facts[key].add(value if type(value) is bool else "unknown") + if (source, guard, line) == ("proxy-recovery", "validate_original_restored", 228): + try: + actual_line = next((n for start, end, n in code.co_lines() + if start <= trace.tb_lasti < end), None) + continuity.append(project_continuity_frame(trace.tb_frame, trusted) + if actual_line == 228 else "unknown") + except BaseException: + continuity.append("unknown") + trace = trace.tb_next + # An untrusted raise site cannot become a qualified failure merely + # because an outer frame happened to be a recognized caller. + if leaf is None: + return inner_unknown() + for key, values in facts.items(): + if len(values) == 1: + result[key] = next(iter(values)) + if len(contexts) == 1 and len(continuity) == 1 and result["condition"] is False: + result["continuity_equal"] = continuity[0] + value = inner_record(result) + return value if len(encoded(value)) <= 8192 else inner_unknown() + + +def inner_trusted_codes(wheels): + """Bind installed functions to exact wheel bytes and frozen source bytes.""" + if type(wheels) is not list or len(wheels) != 2: + return () + wheel_members = {} + for row in wheels: + if type(row) is not list or len(row) != 3 or any(type(v) is not str for v in row): + return () + name, path, checksum = row + if name not in ("dc-overview", "cryptolabs-proxy") or name in wheel_members: + return () + raw = Path(path).read_bytes() + if type(checksum) is not str or digest(raw) != checksum: + return () + with zipfile.ZipFile(__import__("io").BytesIO(raw)) as archive: + wheel_members[name] = {n: archive.read(n) for n in archive.namelist() if n.endswith(".py")} + trusted = [] + for module_name, distribution, product, source_id in ( + ("dc_overview.fleet_upgrade", "dc-overview", "dc", None), + ("cryptolabs_proxy.updates", "cryptolabs-proxy", "proxy", "proxy-updates"), + ("cryptolabs_proxy.update_recovery", "cryptolabs-proxy", "proxy", "proxy-recovery"), + ): + module = importlib.import_module(module_name) + member = module_name.replace(".", "/") + ".py" + source = wheel_members[distribution][member] + expected = FROZEN_PRODUCT_HASHES[product]["src/" + member] + installed = importlib.metadata.distribution(distribution).locate_file(member).resolve() + if (Path(module.__file__).resolve() != installed or digest(source) != expected + or installed.read_bytes() != source): + return () + compiled = compile(source, str(installed), "exec") + definitions = {c.co_name: c for c in compiled.co_consts if type(c) is types.CodeType} + for name in INNER_GUARDS.get(source_id, ()): + function = vars(module).get(name) + if name == "open_existing_directory" and type(function) is types.FunctionType: + function = function.__dict__.get("__wrapped__") + if (type(function) is not types.FunctionType + or not helper_code_matches(function.__code__, definitions[name])): + return () + trusted.append((function.__code__, source_id, name)) + return bind_inner_trusted_context(tuple(trusted), module) + + +def scoped_select_child(descriptor, wheels, argv): + """Execute the original console once under a bounded observation binding.""" + global _SCOPED_SELECT_TRACEBACK + import runpy + _SCOPED_SELECT_TRACEBACK = None + invocation = sys._getframe() + caller = invocation.f_back + dispatch = (_SCOPED_SELECT_DISPATCH_FRAME, caller, invocation) + runpy_codes = tuple(f.__code__ if type(f) is types.FunctionType else None + for f in (runpy.run_path, runpy._run_module_code, runpy._run_code)) + original, module, failures, trusted = None, None, [], () try: - result = subprocess.run( - [str(a) for a in args], input=input_bytes, capture_output=True, timeout=timeout, env=env - ) + trusted = inner_trusted_codes(wheels) + if trusted: + module = importlib.import_module("cryptolabs_proxy.updates") + original = module.service_recovery_dependency + except BaseException: + pass # Diagnostic setup never substitutes for the original console. + def observed(*args, **kwargs): + observer_invocation = sys._getframe() + try: + return original(*args, **kwargs) + except BaseException as error: + try: + value = project_inner_failure(error, trusted) + except BaseException: + value = inner_unknown() + # Multiple recovered failures cannot uniquely bind this observation. + if len(failures) < 2: + failures.append((error, value)) + try: + trace = BaseException.__traceback__.__get__(error, type(error)) + if (trace is not None and trace.tb_frame is observer_invocation + and trace.tb_frame.f_code is observer_code): + # Remove our one invocation before the original caller can + # catch/contextualize it. Preserve every original node. + BaseException.__traceback__.__set__(error, trace.tb_next) + except BaseException: + pass # A filtering fault must never replace the exception. + raise + observer_code = observed.__code__ + if original is not None: + module.service_recovery_dependency = observed + previous_argv, previous_path = sys.argv, sys.path[:] + value = inner_unknown() + try: + sys.argv = argv + sys.path[0] = str(Path(argv[0]).parent) + runpy.run_path(argv[0], run_name="__main__") + except BaseException as error: + try: + contexts = inner_contexts(error) + if contexts is not None and len(failures) == 1 and any(e is failures[0][0] for e in contexts): + value = failures[0][1] + except BaseException: + pass + try: + trace = BaseException.__traceback__.__get__(error, type(error)) + if (dispatch[0] is not None and caller.f_code is main.__code__ + and caller.f_back is dispatch[0] and trace is not None + and trace.tb_frame is invocation): + trace = trace.tb_next + previous, scaffold = invocation, [] + for code in runpy_codes: + if (code is None or trace is None or trace.tb_frame.f_code is not code + or trace.tb_frame.f_back is not previous): + break + scaffold.append(trace.tb_frame) + previous, trace = trace.tb_frame, trace.tb_next + else: + if trace is not None and trace.tb_frame.f_back is previous: + # Actual frame identities bind this single invocation + # prefix. Application-owned runpy calls follow it and + # are never searched or removed. + _SCOPED_SELECT_TRACEBACK = (error, (*dispatch, *scaffold), trace) + except BaseException: + pass + raise + finally: + if original is not None: + module.service_recovery_dependency = original + sys.argv, sys.path[:] = previous_argv, previous_path + try: + raw = encoded(inner_record(value)) + if len(raw) <= 8192: + os.write(descriptor, raw) # One nonblocking write; partial means unknown. + except BaseException: + pass + finally: + try: + os.close(descriptor) + except OSError: + pass + + +def scoped_select_subprocess(command, kwargs, wheels): + """Private pipe only; no output readback extension or extra CLI invocation.""" + descriptors = [] + try: + configuration = [[name, str(value[0]), value[2]] for name, value in wheels.items()] + reader, writer = os.pipe() + descriptors.extend((reader, writer)) + os.set_blocking(reader, False) + os.set_blocking(writer, False) + child = [str(Path(command[0]).parent / "python"), "-B", str(Path(__file__).resolve()), + "--scoped-select-child", str(writer), json.dumps(configuration), *command] + except BaseException: + for fd in descriptors: + try: + os.close(fd) + except OSError: + pass + return subprocess.run(command, **kwargs), inner_unknown() + try: + result = subprocess.run(child, pass_fds=(writer,), **kwargs) + try: + os.close(writer) + descriptors.remove(writer) + except OSError: + pass + raw = b"" + try: + while len(raw) <= 8192: + chunk = os.read(reader, 8193 - len(raw)) + if not chunk: + break + raw += chunk + def unique(pairs): + result = {} + for key, item in pairs: + if key in result: + raise ValueError() + result[key] = item + return result + value = inner_record(json.loads(raw, object_pairs_hook=unique)) if 0 < len(raw) <= 8192 else inner_unknown() + except BaseException: + value = inner_unknown() + return result, value + finally: + for fd in descriptors: + try: + os.close(fd) + except OSError: + pass + + +class NativeCommandFailure(RuntimeError): + """Owned, bounded command facts; never retain arguments or captured output.""" + __slots__ = ("_command_outcome", "_command_returncode", "_scoped_select_diagnostic", "_scoped_select_inner_diagnostic") + + def __init__(self, outcome, returncode=None, scoped_select_diagnostic="unknown", inner=None): + if hasattr(self, "_command_outcome") or hasattr(self, "_command_returncode"): + raise AttributeError("command diagnostics are immutable") + outcomes = {"nonzero-exit": "nonzero-exit", "timeout": "timeout", "spawn-error": "spawn-error"} + outcome = outcomes.get(outcome, "unknown") if type(outcome) is str else "unknown" + returncode = returncode if type(returncode) is int and -255 <= returncode <= 255 else None + object.__setattr__(self, "_command_outcome", outcome) + object.__setattr__(self, "_command_returncode", returncode) + object.__setattr__(self, "_scoped_select_diagnostic", scoped_select_category(scoped_select_diagnostic)) + value = inner_record(inner) + object.__setattr__(self, "_scoped_select_inner_diagnostic", + (tuple((g['source'], g['guard'], g['line']) for g in value['guards']), + value['condition'], value['require_capability'], + tuple(value['continuity_equal'].items()) if type(value['continuity_equal']) is dict else 'unknown')) + message = "native command timed out; native gate held" if outcome == "timeout" else "native command failed; native gate held" + RuntimeError.__init__(self, message) + + def __setattr__(self, name, value): + if name in NativeCommandFailure.__slots__: + raise AttributeError("command diagnostics are immutable") + # Exception propagation/context managers must still manage traceback + # and chaining attributes. Only the owned command facts are immutable. + BaseException.__setattr__(self, name, value) + + def __delattr__(self, name): + if name in NativeCommandFailure.__slots__: + raise AttributeError("command diagnostics are immutable") + BaseException.__delattr__(self, name) + + +def command_failure_facts( + error, + command_type=NativeCommandFailure, + outcome_slot=NativeCommandFailure.__dict__["_command_outcome"], + returncode_slot=NativeCommandFailure.__dict__["_command_returncode"], +): + if type(error) is not command_type: + return "unknown", None + outcome = outcome_slot.__get__(error, command_type) + returncode = returncode_slot.__get__(error, command_type) + outcomes = {"nonzero-exit": "nonzero-exit", "timeout": "timeout", "spawn-error": "spawn-error"} + return (outcomes.get(outcome, "unknown") if type(outcome) is str else "unknown", + returncode if type(returncode) is int and -255 <= returncode <= 255 else None) + + +def scoped_select_failure_fact( + error, + command_type=NativeCommandFailure, + diagnostic_slot=NativeCommandFailure.__dict__["_scoped_select_diagnostic"], +): + if type(error) is not command_type: + return "unknown" + try: + return scoped_select_category(diagnostic_slot.__get__(error, command_type)) + except AttributeError: + return "unknown" + + +def scoped_select_inner_fact(error, command_type=NativeCommandFailure, + slot=NativeCommandFailure.__dict__["_scoped_select_inner_diagnostic"]): + if type(error) is not command_type: + return inner_unknown() + try: + guards, condition, capability, equality = slot.__get__(error, command_type) + if type(guards) is not tuple or any(type(g) is not tuple or len(g) != 3 for g in guards): + return inner_unknown() + if type(equality) is tuple: + if (len(equality) != len(CONTINUITY_FIELDS) + or any(type(row) is not tuple or len(row) != 2 or type(row[0]) is not str + or type(row[1]) is not bool for row in equality) + or set(key for key, _ in equality) != set(CONTINUITY_FIELDS)): + return inner_unknown() + equality = dict(equality) + return inner_record({'guards': [dict(source=s, guard=g, line=n) for s, g, n in guards], + 'condition': condition, 'require_capability': capability, + 'continuity_equal': equality}) + except BaseException: + return inner_unknown() + + +def run(*args, input_bytes=None, timeout=180, check=True, env=None, scoped_select_diagnostic=False, + scoped_select_wheels=None): + inner = inner_unknown() + try: + command = [str(a) for a in args] + kwargs = dict(input=input_bytes, capture_output=True, timeout=timeout, env=env) + if scoped_select_diagnostic is True and scoped_select_wheels is not None: + result, inner = scoped_select_subprocess(command, kwargs, scoped_select_wheels) + else: + result = subprocess.run(command, **kwargs) except subprocess.TimeoutExpired: - raise RuntimeError("native command timed out; native gate held") from None + raise NativeCommandFailure("timeout") from None + except OSError: + raise NativeCommandFailure("spawn-error") from None if check and result.returncode: # Never expose inspected environments, auth files, command arguments or private snapshots. - raise RuntimeError( - f"{Path(str(args[0])).name} failed (exit {result.returncode}); native gate held" - ) + diagnostic = "unknown" + if scoped_select_diagnostic is True: + try: + diagnostic = classify_scoped_select_output(result.returncode, result.stdout, result.stderr) + except Exception: + pass # Collection must never replace the original checked command failure. + raise NativeCommandFailure("nonzero-exit", result.returncode, diagnostic, + inner if diagnostic == 'recovery-required' else None) from None return result @@ -276,10 +939,50 @@ def raw_request(action="list", params=None, *, actor=None, payload=None): BROKER_CODE_LABELS = ( "broker-serve", "broker-connection", "broker-response", "broker-init", "broker-policy", "broker-dispatch", "broker-reconcile", "broker-operation", + "installed-owner-capabilities", "installed-owner-identity", "installed-owner-submit", "installed-owner-status", + "proxy-submit-job", "proxy-submit-locked", "proxy-helper-request", "proxy-write-json", + "proxy-installed-selection", "proxy-selection-plan", "proxy-require-selected-updater", +) +# Separate from the 27 preserved baseline literals. These 13 original code +# objects plus the existing 19 roles form the closed 32-object ceiling. +SELECTOR_CODE_SPECS = ( + ('dc-scoped-selector', 'dc_overview.fleet_upgrade', ('select_release_components',)), + ('dc-running-cli', 'dc_overview.fleet_upgrade', ('verify_running_cli',)), + ('dc-release-store', 'dc_overview.fleet_upgrade', ('release_store',)), + ('dc-scoped-proxy', 'dc_overview.fleet_upgrade', ('_scoped_proxy',)), + ('dc-updater-directory', 'dc_overview.fleet_upgrade', ('_scoped_updater_directory',)), + ('dc-updater-guard', 'dc_overview.fleet_upgrade', ('_scoped_updater_guard',)), + ('dc-updater-idle', 'dc_overview.fleet_upgrade', ('_scoped_updater_guard', 'check')), + ('dc-selector-precommit', 'dc_overview.fleet_upgrade', ('select_release_components', 'precommit')), + ('catalog-root', 'dc_overview.release_catalog', ('_require_root',)), + ('catalog-manifest', 'dc_overview.release_catalog', ('Manifest', 'from_bytes')), + ('catalog-store-load', 'dc_overview.release_catalog', ('ReleaseStore', 'load')), + ('catalog-recover-publication', 'dc_overview.release_catalog', ('ReleaseStore', 'recover_publication')), + ('proxy-recovery-require', 'cryptolabs_proxy.update_recovery', ('require',)), +) +# A separate lane: never combine these with the 13 selector roles. Together +# with the existing 19 broker/owner roles this stays below the 32-object cap. +ADOPTION_CODE_SPECS = ( + ('adoption-owner', 'dc_overview.release_broker', ('InstalledOwner', 'adopt')), + ('adoption-settings', 'dc_overview.release_broker', ('InstalledOwner', 'adoption')), + ('adoption-owner-recover', 'dc_overview.release_broker', ('InstalledOwner', 'recover')), + ('adoption-operation', 'dc_overview.release_broker', ('ReleaseBroker', 'run_operation')), + ('adoption-fresh', 'dc_overview.release_broker', ('ReleaseBroker', '_fresh')), + ('adoption-plan', 'cryptolabs_proxy.standard_adoption', ('StandardAdoption', 'plan')), + ('adoption-apply', 'cryptolabs_proxy.standard_adoption', ('StandardAdoption', 'adopt')), + ('adoption-recover', 'cryptolabs_proxy.standard_adoption', ('StandardAdoption', 'recover_adoption')), + ('adoption-declaration', 'cryptolabs_proxy.standard_adoption', ('_declaration',)), + ('adoption-require', 'cryptolabs_proxy.update_recovery', ('require',)), ) ERROR_KINDS = ( "assertion-error", "file-not-found", "permission-error", "os-error", "runtime-error", "unknown", ) + + +def _diagnostic_error_kind(error): + return {AssertionError: 'assertion-error', FileNotFoundError: 'file-not-found', + PermissionError: 'permission-error', OSError: 'os-error', + RuntimeError: 'runtime-error'}.get(type(error), 'unknown') SERVICE_ENUMS = { "ActiveState": ("active", "reloading", "inactive", "failed", "activating", "deactivating", "maintenance", "refreshing"), "SubState": ("dead", "condition", "start-pre", "start", "start-post", "running", "exited", "reload", "reload-signal", "reload-notify", "stop", "stop-watchdog", "stop-sigterm", "stop-sigkill", "stop-post", "final-watchdog", "final-sigterm", "final-sigkill", "failed", "auto-restart", "auto-restart-queued", "cleaning"), @@ -345,14 +1048,27 @@ def process_identity(pid): def broker_failure_metadata(error, code_objects): result = {"code_label": None, "source_line": None, "error_kind": "unknown"} frame = error.__traceback__ + selector_seen = False + terminal_known = False + count = 0 while frame is not None: + count += 1 + if count > 32: + return {"code_label": None, "source_line": None, "error_kind": "unknown"} + terminal_known = False for label, code in code_objects: - if label in BROKER_CODE_LABELS and frame.tb_frame.f_code is code: + if (label in BROKER_CODE_LABELS or label in {item[0] for item in (*SELECTOR_CODE_SPECS, *ADOPTION_CODE_SPECS)}) and frame.tb_frame.f_code is code: + terminal_known = True + selector_seen |= label in {item[0] for item in (*SELECTOR_CODE_SPECS, *ADOPTION_CODE_SPECS)} metadata = fixture_failure_metadata(error, fixture_code=code) if metadata["fixture_line"] is not None: result = {"code_label": label, "source_line": metadata["fixture_line"], "error_kind": metadata["fixture_error_kind"]} frame = frame.tb_next + if selector_seen and not terminal_known: + # The last recognized outer frame is not the cause of an unknown inner + # failure. Legacy owner-only coordinates retain their original shape. + return {"code_label": None, "source_line": None, "error_kind": "unknown"} return result @@ -381,8 +1097,784 @@ def write_broker_failure(value): stream.truncate() +def inspect_owner_mounts_bounded(): + """One owned pipe, 1 MiB capture, four-second capture/five-second cleanup budget.""" + child = selector = None + data = bytearray() + captured = cleaned = False + start = time.monotonic() + try: + child = subprocess.Popen( + ["docker", "inspect", "cryptolabs-proxy"], shell=False, + stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, + bufsize=0, close_fds=True, + ) + descriptor = child.stdout.fileno() + os.set_blocking(descriptor, False) + selector = selectors.DefaultSelector() + selector.register(child.stdout, selectors.EVENT_READ) + while len(data) <= 1048576: + remaining = start + 4 - time.monotonic() + if remaining <= 0: + break + if not selector.select(remaining): + continue + if time.monotonic() >= start + 4: + break + try: + chunk = os.read(descriptor, min(65536, 1048577 - len(data))) + except BlockingIOError: + continue + data.extend(chunk) + if len(data) > 1048576: + break + if not chunk: + remaining = start + 4 - time.monotonic() + if remaining > 0: + captured = child.wait(timeout=remaining) == 0 + break + except Exception: + captured = False + finally: + resources_closed = True + if selector is not None: + try: + if child is not None: + selector.unregister(child.stdout) + except Exception: + pass + try: + selector.close() + except Exception: + resources_closed = False + if child is not None: + try: + child.stdout.close() + except Exception: + resources_closed = False + try: + if child.poll() is None: + child.kill() + remaining = start + 5 - time.monotonic() + if remaining > 0: + child.wait(timeout=remaining) + cleaned = resources_closed + except Exception: + cleaned = False + if captured and cleaned: + try: + return json.loads(data) + except Exception: + pass + return None + + +def observation_uuid(value): + try: + return type(value) is str and str(uuid.UUID(value)) == value + except ValueError: + return False + + +def observation_directories(path, *, private=True): + """No-follow ancestry plus exact producer custody at the selected directory.""" + path = Path(path) + if not path.is_absolute() or '..' in path.parts: + raise ValueError() + identities = [] + for parent in (*reversed(path.parents), path): + info = parent.lstat() + # macOS exposes its OS-owned temporary tree through this fixed alias. + # This portable fixture accommodation is never active in the Linux lane. + if (platform.system() == 'Darwin' and parent == Path('/var') + and stat.S_ISLNK(info.st_mode) and info.st_uid == 0 + and os.readlink(parent) == 'private/var'): + info = Path('/private/var').lstat() + if not stat.S_ISDIR(info.st_mode) or info.st_uid not in (0, os.geteuid()): + raise ValueError() + # Portable local tests use the OS temporary ancestor. The native Linux + # fixture never allows writable ancestry, including sticky directories. + if info.st_mode & 0o022 and not (platform.system() != 'Linux' and info.st_mode & stat.S_ISVTX): + raise ValueError() + identities.append((parent, trust_identity(info))) + info = path.lstat() + if private and (info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) != 0o700): + raise ValueError() + return identities + + +class ObservationAbsent(FileNotFoundError): + """Initial open found no file under the same verified parent directories.""" + + +class ObservationRefused(ValueError): + """Closed diagnostic reason; no inspected text becomes an error message.""" + + +def observation_json(raw): + def pairs(values): + result = {} + for key, value in values: + if key in result: + raise ValueError() + result[key] = value + return result + return json.loads(raw, object_pairs_hook=pairs, + parse_constant=lambda value: (_ for _ in ()).throw(ValueError())) + + +def observation_deadline(deadline): + if time.monotonic() >= deadline: + raise ObservationRefused('deadline') + + +def observation_read(path, limit, *, identity=None): + """At most limit+1 returned bytes; reject replacement rather than infer absence.""" + path = Path(path) + parents = observation_directories(path.parent) + try: + descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + except FileNotFoundError: + if observation_directories(path.parent) != parents: + raise ValueError() from None + raise ObservationAbsent() from None + try: + info = os.fstat(descriptor) + if (not stat.S_ISREG(info.st_mode) or info.st_uid != os.geteuid() + or stat.S_IMODE(info.st_mode) != 0o600 or info.st_nlink != 1 + or (identity is not None and trust_identity(info) != identity) + or trust_identity(path.lstat()) != trust_identity(info)): + raise ObservationRefused('custody-refused') + if info.st_size > limit: + raise ObservationRefused('overflow') + raw = bytearray() + while len(raw) <= limit: + chunk = os.read(descriptor, min(65536, limit + 1 - len(raw))) + raw.extend(chunk) + if not chunk or len(raw) > limit: + break + after = os.fstat(descriptor) + if len(raw) > limit: + raise ObservationRefused('overflow') + if (trust_identity(path.lstat()) != trust_identity(info) + or trust_metadata(after) != trust_metadata(info) or after.st_size != info.st_size + or observation_directories(path.parent) != parents): + raise ObservationRefused('custody-refused') + try: + return observation_json(raw) + except (ValueError, UnicodeError, RecursionError): + raise ObservationRefused('parse-refused') from None + except FileNotFoundError: + # Once opened, a lost pathname or ancestor is a custody race, not absence. + raise ValueError() from None + finally: + os.close(descriptor) + + +def selector_operation(record, operation_id): + """Pinned versionless _preview/_apply/save shape; never call the producer.""" + required = {'preview_id', 'actor', 'request', 'manifest', 'selection_sha256', 'selection_id', + 'manifest_sha256', 'generation', 'owner_plan', 'owner_declaration', 'public_sha256', + 'owner_identity', 'policy_sha256', 'channel', 'preview_sha256', 'operation_id', + 'expected_selection_id', 'expected_selection_sha256', 'request_fingerprint', + 'state', 'components', 'operation_kind', 'phase'} + optional = {'reason', 'job_id', 'observed_selection_id', 'observed_selection_sha256'} + if type(record) is not dict or not required <= set(record) or set(record) - required - optional: + raise ObservationRefused('schema-refused') + identifier = lambda value, maximum=80: type(value) is str and re.fullmatch( + r'[A-Za-z0-9][A-Za-z0-9_.-]{0,' + str(maximum - 1) + '}', value) is not None + checksum = lambda value: type(value) is str and re.fullmatch('[0-9a-f]{64}', value) is not None + if record['operation_id'] != operation_id or not observation_uuid(record['operation_id']): + raise ObservationRefused('identity-refused') + if not observation_uuid(record['preview_id']): + raise ObservationRefused('schema-refused') + for key in ('preview_sha256', 'selection_sha256', 'manifest_sha256', 'public_sha256', + 'policy_sha256', 'expected_selection_sha256', 'request_fingerprint'): + if not checksum(record[key]): + raise ObservationRefused('schema-refused') + if not all(identifier(record[key]) for key in ('selection_id', 'expected_selection_id')): + raise ObservationRefused('schema-refused') + if (type(record['generation']) is not int or record['generation'] < 0 + or type(record['channel']) is not str or record['channel'] not in ('main', 'dev') + or type(record['state']) is not str or record['state'] not in ( + 'prepared', 'selecting', 'pending-submit', 'updating', 'adopting', 'recovery-required', + 'selection-conflict', 'completed', 'failed-restored') + or type(record['phase']) is not str or record['phase'] not in ('selection', 'owner')): + raise ObservationRefused('schema-refused') + actor = record['actor'] + if type(actor) is not dict: + raise ObservationRefused('schema-refused') + if actor.get('kind') == 'fleet-admin': + if set(actor) != {'kind', 'username', 'subject'} or any( + type(actor[k]) is not str or not 1 <= len(actor[k]) <= 128 + or any(ord(c) < 32 for c in actor[k]) for k in ('username', 'subject')): + raise ObservationRefused('schema-refused') + elif actor.get('kind') == 'host-peer': + if set(actor) != {'kind', 'uid'} or type(actor['uid']) is not int or actor['uid'] < 0: + raise ObservationRefused('schema-refused') + else: + raise ObservationRefused('schema-refused') + request = record['request'] + if type(request) is not dict or set(request) != { + 'candidate_ids', 'components', 'expected_selection_id', 'expected_selection_sha256', 'operation_kind'}: + raise ObservationRefused('schema-refused') + components = ('cryptolabs-proxy', 'dc-overview', 'ipmi-monitor', 'prometheus', 'grafana', + 'vastai-exporter', 'runpod-exporter', 'vast-price-manager', 'dc-overview-cli', + 'node-exporter', 'dc-watchdog-agent') + for key in ('candidate_ids', 'components'): + values = request[key] + if (type(values) is not list or not 1 <= len(values) <= 32 + or any(not identifier(v, 128) for v in values) or len(set(values)) != len(values) + or (key == 'components' and any(v not in components for v in values))): + raise ObservationRefused('schema-refused') + if (type(record['components']) is not list or record['components'] != request['components'] + or type(record['operation_kind']) is not str or record['operation_kind'] not in ('services-update', 'proxy-adopt') + or request['operation_kind'] != record['operation_kind'] + or any(request[key] != record[key] for key in ('expected_selection_id', 'expected_selection_sha256'))): + raise ObservationRefused('identity-refused') + owner = record['owner_identity'] + if (type(owner) is not dict or set(owner) != { + 'updater_directory', 'device', 'inode', 'proxy_config_dir', 'declaration_path'} + or any(type(owner[k]) is not int or owner[k] < 0 for k in ('device', 'inode')) + or any(type(owner[k]) is not str or not 1 <= len(owner[k]) <= 4096 + or not Path(owner[k]).is_absolute() or '..' in Path(owner[k]).parts + for k in ('updater_directory', 'proxy_config_dir', 'declaration_path'))): + raise ObservationRefused('schema-refused') + if any(record[k] is not None and type(record[k]) is not dict for k in ('owner_plan', 'owner_declaration')): + raise ObservationRefused('schema-refused') + if record['operation_kind'] == 'services-update' and any(record[k] is not None for k in ('owner_plan', 'owner_declaration')): + raise ObservationRefused('schema-refused') + if 'reason' in record and (type(record['reason']) is not str or len(record['reason']) > 65536): + raise ObservationRefused('schema-refused') + if 'job_id' in record and (type(record['job_id']) is not str or not re.fullmatch('[0-9a-f]{32}', record['job_id'])): + raise ObservationRefused('schema-refused') + if ('observed_selection_id' in record) != ('observed_selection_sha256' in record): + raise ObservationRefused('schema-refused') + if 'observed_selection_id' in record and (not identifier(record['observed_selection_id']) or not checksum(record['observed_selection_sha256'])): + raise ObservationRefused('schema-refused') + # This is producer/custody-bound correlation, not an independent measurement + # of the server's secret-derived actor subject. Never read its auth secret. + canonical = lambda value: json.dumps(value, sort_keys=True, separators=(',', ':'), allow_nan=False).encode() + if len(canonical(record)) > 1048576: + raise ObservationRefused('overflow') + apply = {key: record[key] for key in ('operation_id', 'preview_id', 'preview_sha256', + 'expected_selection_id', 'expected_selection_sha256')} + if digest(canonical({'params': apply, 'actor': actor})) != record['request_fingerprint']: + raise ObservationRefused('identity-refused') + preview = {key: record[key] for key in ('preview_id', 'actor', 'request', 'manifest', 'selection_sha256', + 'selection_id', 'manifest_sha256', 'generation', 'owner_plan', 'owner_declaration', + 'public_sha256', 'owner_identity', 'policy_sha256', 'channel')} + if len(canonical(preview)) > 900000: + raise ObservationRefused('overflow') + if digest(canonical(preview)) != record['preview_sha256']: + raise ObservationRefused('identity-refused') + if type(record['manifest']) is not str or len(record['manifest']) > 1200000: + raise ObservationRefused('overflow') + try: + raw = base64.b64decode(record['manifest'], validate=True) + except (ValueError, UnicodeError, RecursionError): + raise ObservationRefused('schema-refused') from None + if len(raw) > 900000: + raise ObservationRefused('overflow') + if digest(raw) != record['manifest_sha256']: + raise ObservationRefused('identity-refused') + try: + manifest = observation_json(raw) + except (ValueError, UnicodeError, RecursionError): + raise ObservationRefused('parse-refused') from None + if type(manifest) is not dict or type(manifest.get('components')) is not dict: + raise ObservationRefused('schema-refused') + return manifest + + +def selector_read_bytes(path, limit, deadline): + """Read one fixed installed source/metadata file, with descriptor custody.""" + observation_deadline(deadline) + path = Path(path) + try: + parents = observation_directories(path.parent, private=False) + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + except (OSError, ValueError): + raise ObservationRefused('custody-refused') from None + try: + before = os.fstat(fd) + if (not stat.S_ISREG(before.st_mode) or before.st_uid not in (0, os.geteuid()) + or before.st_mode & 0o022 or before.st_nlink != 1 + or trust_identity(path.lstat()) != trust_identity(before)): + raise ObservationRefused('custody-refused') + if before.st_size > limit: + raise ObservationRefused('overflow') + raw = bytearray() + while len(raw) <= limit: + observation_deadline(deadline) + chunk = os.read(fd, min(65536, limit + 1 - len(raw))) + raw.extend(chunk) + if not chunk or len(raw) > limit: + break + after = os.fstat(fd) + observation_deadline(deadline) + if len(raw) > limit: + raise ObservationRefused('overflow') + if (trust_metadata(after) != trust_metadata(before) or after.st_size != before.st_size + or trust_identity(path.lstat()) != trust_identity(before) + or observation_directories(path.parent, private=False) != parents): + raise ObservationRefused('custody-refused') + return bytes(raw) + finally: + os.close(fd) + + +def naturally_loaded_selector_codes(deadline): + return _naturally_loaded_codes(deadline, SELECTOR_CODE_SPECS) + + +def naturally_loaded_adoption_codes(deadline): + return _naturally_loaded_codes(deadline, ADOPTION_CODE_SPECS) + + +def _naturally_loaded_codes(deadline, specs): + """No import/discovery calls: bind only reviewed, naturally loaded code.""" + result, sources = [], {} + site = Path(sysconfig.get_path('purelib', scheme='posix_prefix', + vars={'base': sys.prefix, 'platbase': sys.prefix})) + if not site.is_relative_to(Path(sys.prefix)): + raise ObservationRefused('source-refused') + for label, module_name, ancestry in specs: + module = sys.modules.get(module_name) + if type(module) is not types.ModuleType: + continue + if module_name not in sources: + role = 'proxy' if module_name.startswith('cryptolabs_proxy.') else 'dc' + relative = 'src/' + module_name.replace('.', '/') + '.py' + path = Path(vars(module).get('__file__', '')) + if path != site / (module_name.replace('.', '/') + '.py'): + continue + raw = selector_read_bytes(path, 1048576, deadline) + if digest(raw) != FROZEN_PRODUCT_HASHES[role][relative]: + continue + sources[module_name] = compile(raw, str(path), 'exec') + expected = sources[module_name] + actual = module + parent_code = None + for index, name in enumerate(ancestry): + choices = [c for c in expected.co_consts if type(c) is types.CodeType and c.co_name == name] + if len(choices) != 1: + actual = None + break + expected = choices[0] + if parent_code is not None: + choices = [c for c in parent_code.co_consts if type(c) is types.CodeType and c.co_name == name] + actual = choices[0] if len(choices) == 1 else None + else: + actual = vars(actual).get(name) if type(actual) in (types.ModuleType, type) else None + if type(actual) is classmethod: + actual = actual.__func__ + if type(actual) is types.FunctionType and name == '_scoped_updater_guard': + actual = vars(actual).get('__wrapped__') + if type(actual) is types.FunctionType: + actual = actual.__code__ + if type(actual) is types.CodeType: + parent_code = actual + elif index == len(ancestry) - 1: + actual = None + observation_deadline(deadline) + if type(actual) is types.CodeType and helper_code_matches(actual, expected): + result.append((label, actual)) + return tuple(result) + + +def selector_failure_details(error, codes, manifest, deadline): + """One post-failure sample, never a replay or atomic guard-operand claim.""" + result = {'qualification': 'innermost-unknown', 'source_stage': 'failure-sample', 'frames': [], 'actual_interpreter': 'unknown', + 'expected_interpreter': 'compatible-host-venv', 'module_version_match': None, + 'distribution_version_match': None, 'url_match': None, 'hash_match': None} + frame = error.__traceback__ + count, inner_known = 0, False + while frame is not None: + observation_deadline(deadline) + count += 1 + if count > 32: + result['qualification'] = 'overflow' + return result + matches = [(role, code) for role, code in codes if frame.tb_frame.f_code is code] + inner_known = len(matches) == 1 + if inner_known: + if len(result['frames']) == 16: + result['qualification'] = 'overflow' + return result + result['frames'].append({'role': matches[0][0], 'line': frame.tb_lineno}) + frame = frame.tb_next + if inner_known: + result['qualification'] = 'qualified' + else: + return result + prefix = Path(sys.prefix) + if prefix == Path('/opt/fleet-native-qa/venv'): + result['actual_interpreter'] = 'original-native-venv' + elif prefix == ROOT / 'legacy-host-venv': + result['actual_interpreter'] = 'compatible-host-venv' + else: + result['qualification'] = 'source-refused' + return result + target = manifest['components'].get('dc-overview-cli') + if (type(target) is not dict or set(target) != {'owner', 'release', 'artifacts'} + or target['owner'] != 'host-cli' or type(target['release']) is not str + or not 1 <= len(target['release']) <= 128 or type(target['artifacts']) is not dict + or set(target['artifacts']) != {'any'} or type(target['artifacts']['any']) is not dict): + return result + selected = target['artifacts']['any'] + if (set(selected) != {'kind', 'url', 'sha256'} or selected['kind'] != 'wheel' + or type(selected['url']) is not str or not 1 <= len(selected['url']) <= 4096 + or type(selected['sha256']) is not str or not re.fullmatch('[0-9a-f]{64}', selected['sha256'])): + return result + package = sys.modules.get('dc_overview') + if type(package) is not types.ModuleType: + result['qualification'] = 'source-refused' + return result + package_path = Path(vars(package).get('__file__', '')) + site = Path(sysconfig.get_path('purelib', scheme='posix_prefix', + vars={'base': sys.prefix, 'platbase': sys.prefix})) + if not site.is_relative_to(prefix) or package_path != site / 'dc_overview/__init__.py': + result['qualification'] = 'source-refused' + return result + # Exactly this admitted basename; no distribution scan or directory listing. + distribution = package_path.parent.parent / 'dc_overview-1.6.4.dist-info' + metadata = selector_read_bytes(distribution / 'METADATA', 65536, deadline) + provenance = selector_read_bytes(distribution / 'direct_url.json', 65536, deadline) + from email.parser import BytesParser + installed = BytesParser().parsebytes(metadata) + try: + value = observation_json(provenance) + except (ValueError, UnicodeError, RecursionError): + raise ObservationRefused('parse-refused') from None + if (installed.get_all('Name') != ['dc-overview'] or len(installed.get_all('Version', [])) != 1 + or type(value) is not dict): + result['qualification'] = 'schema-refused' + return result + version = vars(package).get('__version__') + result['module_version_match'] = version == target['release'] if type(version) is str else None + result['distribution_version_match'] = installed['Version'] == target['release'] + result['url_match'] = value.get('url') == selected['url'] + archive = value.get('archive_info', {}) + hashes = archive.get('hashes', {}) if type(archive) is dict else None + result['hash_match'] = hashes.get('sha256') == selected['sha256'] if type(hashes) is dict else None + observation_deadline(deadline) + return result + + +def observation_failure_valid(value): + if (type(value) is not dict or set(value) not in ( + {'code_label', 'source_line', 'error_kind'}, {'code_label', 'source_line', 'error_kind', 'selector'}, + {'code_label', 'source_line', 'error_kind', 'adoption'}) + or type(value['error_kind']) is not str or value['error_kind'] not in ERROR_KINDS): + return False + if 'selector' in value and not selector_details_valid(value['selector']): + return False + if 'adoption' in value: + detail = value['adoption'] + if not adoption_details_valid(detail): + return False + if detail['qualification'] == 'qualified': + if (not detail['frames'] or value['code_label'] != detail['frames'][-1]['role'] + or value['source_line'] != detail['frames'][-1]['line']): + return False + elif value['code_label'] is not None or value['source_line'] is not None or value['error_kind'] != 'unknown': + return False + if value['code_label'] is None: + return value['source_line'] is None and value['error_kind'] == 'unknown' + return (type(value['code_label']) is str and value['code_label'] in ( + *BROKER_CODE_LABELS, *(item[0] for item in SELECTOR_CODE_SPECS), + *(item[0] for item in ADOPTION_CODE_SPECS if 'adoption' in value)) + and type(value['source_line']) is int and 1 <= value['source_line'] <= 1000000) + + +def adoption_details_valid(value): + if (type(value) is not dict or set(value) != {'qualification', 'source_stage', 'frames'} + or type(value['qualification']) is not str or value['qualification'] not in ( + 'qualified', 'innermost-unknown', 'source-refused', 'schema-refused', 'identity-refused', + 'custody-refused', 'parse-refused', 'overflow', 'deadline', 'unknown') + or type(value['source_stage']) is not str or value['source_stage'] not in ( + 'unknown', 'operation', 'broker-source', 'adoption-discovery', 'failure-sample') + or type(value['frames']) is not list or len(value['frames']) > 16): + return False + roles = {item[0] for item in ADOPTION_CODE_SPECS} + return all(type(frame) is dict and set(frame) == {'role', 'line'} + and type(frame['role']) is str and frame['role'] in roles + and type(frame['line']) is int and 1 <= frame['line'] <= 1000000 + for frame in value['frames']) + + +def adoption_failure_details(error, codes, deadline): + result = {'qualification': 'innermost-unknown', 'source_stage': 'failure-sample', 'frames': []} + frame, count, inner_known = error.__traceback__, 0, False + while frame is not None: + observation_deadline(deadline) + count += 1 + if count > 32: + return {**result, 'qualification': 'overflow', 'frames': []} + matches = [role for role, code in codes if frame.tb_frame.f_code is code] + inner_known = len(matches) == 1 + if inner_known: + if len(result['frames']) == 16: + return {**result, 'qualification': 'overflow', 'frames': []} + result['frames'].append({'role': matches[0], 'line': frame.tb_lineno}) + frame = frame.tb_next + if inner_known: + result['qualification'] = 'qualified' + return result + + +def selector_details_valid(value): + if type(value) is not dict or set(value) != { + 'qualification', 'source_stage', 'frames', 'actual_interpreter', 'expected_interpreter', + 'module_version_match', 'distribution_version_match', 'url_match', 'hash_match'}: + return False + if (type(value['source_stage']) is not str or value['source_stage'] not in ( + 'unknown', 'broker-source', 'selector-discovery', 'proxy-discovery', + 'selector-required', 'failure-sample')): + return False + if (type(value['qualification']) is not str or value['qualification'] not in ( + 'qualified', 'innermost-unknown', 'source-refused', 'schema-refused', 'identity-refused', + 'custody-refused', 'parse-refused', 'overflow', 'deadline', 'unknown') + or type(value['frames']) is not list or len(value['frames']) > 16): + return False + for frame in value['frames']: + if (type(frame) is not dict or set(frame) != {'role', 'line'} + or type(frame['role']) is not str or frame['role'] not in ( + *BROKER_CODE_LABELS, *(item[0] for item in SELECTOR_CODE_SPECS)) + or type(frame['line']) is not int or not 1 <= frame['line'] <= 1000000): + return False + if any(value[k] is not None and type(value[k]) is not bool for k in ( + 'module_version_match', 'distribution_version_match', 'url_match', 'hash_match')): + return False + return (type(value['actual_interpreter']) is str and value['actual_interpreter'] in ( + 'original-native-venv', 'compatible-host-venv', 'unknown') + and type(value['expected_interpreter']) is str and value['expected_interpreter'] == 'compatible-host-venv') + + +_owner_observation_lock = threading.Lock() +_owner_observation_identity = None + + +def owner_observation_file(flags): + observation_directories(ROOT) + path = ROOT / 'broker-owner-observation.json' + descriptor = os.open(path, flags | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600) + try: + info = os.fstat(descriptor) + if (not stat.S_ISREG(info.st_mode) or info.st_uid != os.geteuid() + or stat.S_IMODE(info.st_mode) != 0o600 or info.st_nlink != 1 + or trust_identity(path.lstat()) != trust_identity(info)): + raise ValueError() + return descriptor, info + except Exception: + os.close(descriptor) + raise + + +def write_owner_observation(operation_id, failure): + if not _owner_observation_lock.acquire(blocking=False): + return + try: + if not observation_uuid(operation_id) or not observation_failure_valid(failure): + return + raw = encoded({'schema_version': 1, 'operation_id': operation_id, 'failure': failure}) + if len(raw) > 4096 or _owner_observation_identity is None: + return + descriptor, info = owner_observation_file(os.O_WRONLY) + try: + if trust_identity(info) != _owner_observation_identity: + return + # A partial/interrupted diagnostic is unavailable; no journal/fsync. + os.ftruncate(descriptor, 0) + if os.write(descriptor, raw) != len(raw): + return + finally: + os.close(descriptor) + except Exception: + pass + finally: + _owner_observation_lock.release() + + +def naturally_loaded_proxy_codes(): + """Only the naturally loaded, installed pinned module; no import or discovery.""" + module = sys.modules.get('cryptolabs_proxy.updates') + if type(module) is not types.ModuleType: + return () + path = Path(module.__file__) + if (not path.is_relative_to(Path(sys.prefix)) or path.parts[-2:] != ('cryptolabs_proxy', 'updates.py')): + return () + observation_directories(path.parent, private=False) + descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + try: + info = os.fstat(descriptor) + if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or info.st_mode & 0o022 or info.st_size > 1048576: + return () + raw = bytearray() + while len(raw) <= 1048576: + chunk = os.read(descriptor, min(65536, 1048577 - len(raw))) + raw.extend(chunk) + if not chunk or len(raw) > 1048576: + break + if (len(raw) > 1048576 or trust_identity(path.lstat()) != trust_identity(info) + or trust_metadata(os.fstat(descriptor)) != trust_metadata(info) + or digest(raw) != FROZEN_PRODUCT_HASHES['proxy']['src/cryptolabs_proxy/updates.py']): + return () + finally: + os.close(descriptor) + return tuple((label, function.__code__) for label, function in ( + ('proxy-submit-job', module.submit_job), ('proxy-submit-locked', module._submit_job_locked), + ('proxy-helper-request', module.helper_request), ('proxy-write-json', module._write_json), + ('proxy-installed-selection', module.installed_selection), ('proxy-selection-plan', module._selection_plan), + ('proxy-require-selected-updater', module._require_selected_updater), + ) if type(function) is types.FunctionType) + + +@contextlib.contextmanager +def observe_broker_owner_failures(broker_module, operation_root, code_objects): + original = broker_module.private_write + codes = tuple(code_objects) + proxy_codes = None + selector_operation_id = None + adoption_operation_id = None + def observed(*args, **kwargs): + nonlocal proxy_codes, selector_operation_id, adoption_operation_id + result = original(*args, **kwargs) + # Nothing diagnostic executes before a successful original write. + try: + error = sys.exception() + if error is None or not args or type(args[0]) is not type(Path()): + return result + path = args[0] + identity = path.stem + if path != Path(operation_root) / (identity + '.json') or not observation_uuid(identity): + return result + frame = error.__traceback__ + eligible = selector_call = False + frame_count = 0 + while frame is not None: + frame_count += 1 + if frame_count > 32: + return result + if any(label == 'broker-operation' and frame.tb_frame.f_code is code for label, code in codes): + eligible = True + selector_call |= frame.tb_lineno == 918 + frame = frame.tb_next + if eligible: + # The other admitted layout retains its existing owner observer; + # it cannot acquire the named-volume selector diagnostic purpose. + persisted = args[1] if len(args) > 1 and type(args[1]) is dict else {} + owner_identity = persisted.get('owner_identity') + adoption_call = (persisted.get('operation_kind') == 'proxy-adopt' + and type(owner_identity) is dict + and type(owner_identity.get('updater_directory')) is str + and owner_identity['updater_directory'] != str(ROOT / 'bind/auth/update-jobs')) + if adoption_call: + if adoption_operation_id is not None: + return result + adoption_operation_id = identity + details = {'qualification': 'unknown', 'source_stage': 'operation', 'frames': []} + failure = {'code_label': None, 'source_line': None, 'error_kind': 'unknown'} + try: + deadline = time.monotonic() + 1 + selector_operation(persisted, identity) + details['source_stage'] = 'broker-source' + path = Path(vars(broker_module).get('__file__', '')) + if (not path.is_relative_to(Path(sys.prefix)) + or digest(selector_read_bytes(path, 1048576, deadline)) + != FROZEN_PRODUCT_HASHES['dc']['src/dc_overview/release_broker.py']): + raise ObservationRefused('source-refused') + details['source_stage'] = 'adoption-discovery' + adoption_codes = naturally_loaded_adoption_codes(deadline) + if len(codes) + len(adoption_codes) > 32: + raise ObservationRefused('overflow') + details = adoption_failure_details(error, adoption_codes, deadline) + if details['qualification'] == 'qualified': + failure = broker_failure_metadata(error, adoption_codes) + observation_deadline(deadline) + except Exception as refused: + reason = refused.args[0] if type(refused) is ObservationRefused and refused.args else 'unknown' + details = {**details, 'qualification': reason if type(reason) is str and reason in ( + 'source-refused', 'schema-refused', 'identity-refused', 'custody-refused', + 'parse-refused', 'overflow', 'deadline') else 'unknown', 'frames': []} + failure = {'code_label': None, 'source_line': None, 'error_kind': 'unknown'} + write_owner_observation(identity, {**failure, 'adoption': details}) + return result + if selector_operation_id is not None: + return result # One selector exception context/operation, no retry. + if (type(owner_identity) is dict + and type(owner_identity.get('updater_directory')) is str + and owner_identity['updater_directory'] == str(ROOT / 'bind/auth/update-jobs')): + selector_call = False + if type(persisted.get('operation_kind')) is str and persisted['operation_kind'] != 'services-update': + selector_call = False + if selector_call: + selector_operation_id = identity + details = {'qualification': 'unknown', 'source_stage': 'unknown', 'frames': [], 'actual_interpreter': 'unknown', + 'expected_interpreter': 'compatible-host-venv', 'module_version_match': None, + 'distribution_version_match': None, 'url_match': None, 'hash_match': None} + failure = {'code_label': None, 'source_line': None, 'error_kind': 'unknown'} + try: + deadline = time.monotonic() + 1 + if len(args) < 2 or type(args[1]) is not dict: + raise ObservationRefused('schema-refused') + manifest = selector_operation(args[1], identity) + if args[1]['operation_kind'] != 'services-update': + raise ObservationRefused('identity-refused') + # The producer namespace is pinned too; selector discovery + # never calls/imports product functions or reads frame locals. + details['source_stage'] = 'broker-source' + path = Path(vars(broker_module).get('__file__', '')) + if (not path.is_relative_to(Path(sys.prefix)) + or digest(selector_read_bytes(path, 1048576, deadline)) + != FROZEN_PRODUCT_HASHES['dc']['src/dc_overview/release_broker.py']): + raise ObservationRefused('source-refused') + details['source_stage'] = 'selector-discovery' + selector_codes = naturally_loaded_selector_codes(deadline) + if proxy_codes is None: + details['source_stage'] = 'proxy-discovery' + proxy_codes = naturally_loaded_proxy_codes() + observation_deadline(deadline) + qualified = codes + (proxy_codes or ()) + selector_codes + if len(qualified) > 32: + raise ObservationRefused('overflow') + details['source_stage'] = 'selector-required' + if not any(role == 'dc-scoped-selector' for role, code in selector_codes): + raise ObservationRefused('source-refused') + failure = broker_failure_metadata(error, qualified) + details['source_stage'] = 'failure-sample' + details = selector_failure_details(error, qualified, manifest, deadline) + observation_deadline(deadline) + except Exception as refused: + reason = refused.args[0] if type(refused) is ObservationRefused and refused.args else 'unknown' + details['qualification'] = reason if type(reason) is str and reason in ( + 'source-refused', 'schema-refused', 'identity-refused', 'custody-refused', + 'parse-refused', 'overflow', 'deadline') else 'unknown' + # Keep no partly sampled comparisons after a failed read. + for key in ('module_version_match', 'distribution_version_match', 'url_match', 'hash_match'): + details[key] = None + if details['qualification'] != 'qualified': + failure = {'code_label': None, 'source_line': None, 'error_kind': 'unknown'} + write_owner_observation(identity, {**failure, 'selector': details}) + return result + if proxy_codes is None: + found = naturally_loaded_proxy_codes() + if found: + proxy_codes = found + write_owner_observation(identity, broker_failure_metadata(error, codes + (proxy_codes or ()))) + except Exception: + pass + return result + broker_module.private_write = observed + try: + yield + finally: + broker_module.private_write = original + + def broker_child(): - """Accepted test-input adapter: replace discovery data only, preserve installed owners.""" + """Test discovery adapter plus handled-save observation; installed source bytes retained.""" if os.geteuid() or platform.system() != "Linux": raise RuntimeError("fixture broker child is only for the disposable Linux guest") from dc_overview.fleet_config import FleetConfig @@ -407,15 +1899,32 @@ def fixture_assets(): ("broker-policy", ReleaseBroker._reload_policy), ("broker-dispatch", ReleaseBroker.dispatch), ("broker-reconcile", ReleaseBroker.reconcile), ("broker-operation", ReleaseBroker.run_operation), )) + broker_module = sys.modules['dc_overview.release_broker'] + observer = contextlib.nullcontext() + if type(broker_module) is types.ModuleType: + owner = broker_module.InstalledOwner + codes += tuple((label, function.__code__) for label, function in ( + ('installed-owner-capabilities', owner.capabilities), ('installed-owner-identity', owner.identity), + ('installed-owner-submit', owner.submit), ('installed-owner-status', owner.status), + )) + try: + global _owner_observation_identity + descriptor, info = owner_observation_file(os.O_WRONLY) + _owner_observation_identity = trust_identity(info) + os.close(descriptor) + except Exception: + pass + observer = observe_broker_owner_failures(broker_module, CONFIG / 'releases/broker/operations', codes) try: - serve( - ReleaseBroker( - FleetConfig.load(CONFIG), - load_policy(), - discovery=fixture_assets, - policy_loader=load_policy, + with observer: + serve( + ReleaseBroker( + FleetConfig.load(CONFIG), + load_policy(), + discovery=fixture_assets, + policy_loader=load_policy, + ) ) - ) except Exception as error: try: write_broker_failure(broker_failure_metadata(error, codes)) @@ -465,6 +1974,464 @@ def certificate(directory, hostname): ) + +"""Guest-only additions to the retained NativeQA lane. Never a host installer. + +This file is composed into a COPY of the exact retained verifier. It does not +import source checkouts as product code and never edits package provenance. +""" +import contextlib +import http.server +import io +import ssl +import threading +import zipfile + +LEGACY_PROXY = "ghcr.io/cryptolabsza/cryptolabs-proxy@sha256:bff38744e774875287e60e1e14995b19c7eb3afbe531d07f5921d06d9b76a1fd" +LEGACY_DESIRED = "ghcr.io/cryptolabsza/ipmi-monitor@sha256:dfa8a56159aab545d128b14bfb7d91cad17cac7de4f706307de508086fc56db9" +LEGACY_WHEELS = { + "dc-overview": ("1.8.0", "72fcf2fde1d765cdfebfd2e4071261e3ff28d202f7ffb1975340e9d362969304"), + "cryptolabs-proxy": ("1.5.4", "5e64f0ae59d38ebcf4885d8aa60822bc3187d5a63f9abb8bdd11927d1ffd2b47"), +} +PROTECTION_SHA = "c1bb469da0e7eaa1d733c6904f685e82aa9f33a5fd2cb7df947af67198697102" +RECOVERY_INPUTS_FROZEN = True # root fills only after final exact source/pin review + + +def check_recovery_inputs(proxy_sha): + check_source_pin(proxy_sha) + if RECOVERY_INPUTS_FROZEN is not True: + raise RuntimeError('reviewed final recovery inputs are unresolved; native gate held') + + +def recovery_store_snapshot(directory): + return {path.name: (path.read_bytes(), path.stat().st_ino) + for path in directory.iterdir() if path.is_file()} + + +def verify_recovery_store(directory, before, job_id, original_id): + receipt_name = 'service-recovery-' + job_id + '.json' + assert {p.name for p in directory.iterdir()} == set(before) | {receipt_name} + for name, (raw, inode) in before.items(): + path = directory / name + assert path.read_bytes() == raw and path.stat().st_ino == inode + receipt_path = directory / receipt_name + info = receipt_path.lstat() + assert stat.S_ISREG(info.st_mode) and stat.S_IMODE(info.st_mode) == 0o600 + assert info.st_uid == os.geteuid() and info.st_nlink == 1 + receipt = receipt_path.read_bytes() + assert len(receipt) <= 16384 + parsed = json.loads(receipt) + assert parsed['job_sha256'] == digest(before[job_id + '.json'][0]) + assert parsed['active_sha256'] == digest(before['active.json'][0]) + assert parsed['original_container_id'] == original_id + return receipt + + +def wheel_info(path): + from email.parser import BytesParser + with zipfile.ZipFile(path) as archive: + names = [n for n in archive.namelist() if n.endswith('.dist-info/METADATA')] + if len(names) != 1: + raise RuntimeError('wheel metadata ambiguity') + info = BytesParser().parsebytes(archive.read(names[0])) + return info['Name'].replace('_', '-'), info['Version'] + + +class LegacyRecoveryFixture: + def __init__(self, qa): + self.qa = qa + self.server = None + self.thread = None + self.github_hosts = None + self.host_env = ROOT / 'legacy-host-venv' + self.backup_root = Path('/var/backups/cryptolabs/ipmi132') + self.backup_root_identity = None + self.backups = [] + self.legacy = {} + self.current = {} + + def validate_inputs(self): + for directory, destination in ((self.qa.args.legacy_wheel_dir, self.legacy), + (self.qa.args.wheel_dir, self.current)): + for path in directory.glob('*.whl'): + name, version = wheel_info(path) + if name not in LEGACY_WHEELS: + continue + if name in destination: + raise RuntimeError('duplicate fixture product wheel') + destination[name] = (path.resolve(), version, digest(path.read_bytes())) + if set(self.legacy) != set(LEGACY_WHEELS) or set(self.current) != set(LEGACY_WHEELS): + raise RuntimeError('exact legacy and compatible wheel pairs required') + for name, (version, checksum) in LEGACY_WHEELS.items(): + if self.legacy[name][1:] != (version, checksum): + raise RuntimeError('legacy immutable wheel differs') + if digest(self.qa.args.protection_helper.read_bytes()) != PROTECTION_SHA: + raise RuntimeError('retained synthetic protection helper differs') + for path in (self.host_env, self.backup_root): + if path.exists() or path.is_symlink(): + raise RuntimeError('fresh disposable guest fixture path occupied') + + def install_old_host(self): + self.validate_inputs() + run(sys.executable, '-m', 'venv', '--system-site-packages', self.host_env) + run(self.host_env / 'bin/python', '-m', 'pip', 'install', '--disable-pip-version-check', + *[str(value[0]) for value in self.legacy.values()], timeout=300) + self.assert_host_versions({name: v[0] for name, v in LEGACY_WHEELS.items()}) + help_text = run(self.host_env / 'bin/dc-overview', 'release', '--help').stdout + assert b'reconcile-service' not in help_text + run(self.host_env / 'bin/python', '-I', '-c', + 'import dc_overview, cryptolabs_proxy; from cryptolabs_proxy.updates import submit_job') + self.qa.record('actual-legacy-host-pair', result='passed', + installed_versions={name: v[0] for name, v in LEGACY_WHEELS.items()}, + wheel_sha256={name: value[2] for name, value in self.legacy.items()}) + + def assert_host_versions(self, expected): + source = 'import importlib.metadata as m,json;print(json.dumps({n:m.version(n) for n in ' + repr(list(expected)) + '}))' + found = json.loads(run(self.host_env / 'bin/python', '-I', '-c', source).stdout) + assert found == expected + + def wheel_mirror(self): + """Actual pip HTTPS provenance in the isolated guest; no dist-info editing. + + github.com is guest-loopback only, as ghcr.io already is in this lane. + This is explicitly synthetic transport, never public release acceptance. + """ + certificate(ROOT / 'wheel-certs', 'github.com') + routes = {} + self.urls = {} + for name, (path, version, checksum) in self.current.items(): + route = '/cryptolabsza/' + name + '/releases/download/native-fixture/' + path.name + routes[route] = path.read_bytes() + self.urls[name] = 'https://github.com' + route + class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + payload = routes.get(self.path) + if payload is None: + self.send_error(404) + return + self.send_response(200) + self.send_header('Content-Length', str(len(payload))) + self.end_headers() + self.wfile.write(payload) + def log_message(self, *args): + pass + hosts = Path('/etc/hosts').read_bytes() + if any('github.com' in line.split('#')[0].split()[1:] for line in hosts.decode().splitlines()): + raise RuntimeError('github fixture host mapping occupied') + self.server = http.server.ThreadingHTTPServer(('127.0.0.2', 443), Handler) + tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + tls.load_cert_chain(ROOT / 'wheel-certs/server.crt', ROOT / 'wheel-certs/server.key') + self.server.socket = tls.wrap_socket(self.server.socket, server_side=True) + self.github_hosts = hosts + Path('/etc/hosts').write_bytes(self.github_hosts + b'\n127.0.0.2 github.com # fleet-native-owned-wheel-mirror\n') + self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) + self.thread.start() + + def install_compatible_host(self): + self.wheel_mirror() + env = {k: v for k, v in os.environ.items() if k not in ('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', + 'http_proxy', 'https_proxy', 'all_proxy', 'PIP_INDEX_URL', 'PIP_EXTRA_INDEX_URL')} + env['NO_PROXY'] = 'github.com,127.0.0.2' + run(self.host_env / 'bin/python', '-m', 'pip', 'install', '--no-deps', '--force-reinstall', + '--cert', ROOT / 'wheel-certs/server.crt', + *[self.urls[name] + '#sha256=' + value[2] for name, value in self.current.items()], + env=env, timeout=180) + self.assert_host_versions({name: value[1] for name, value in self.current.items()}) + # Full import checks the actual proxy __init__/setup/Jinja2 dependency closure. + run(self.host_env / 'bin/python', '-I', '-c', + 'import dc_overview, cryptolabs_proxy; from dc_overview.fleet_upgrade import reconcile_service') + installed_layout_proof = '''\ +import importlib.util, json, sys, sysconfig +from pathlib import Path +import dc_overview +from dc_overview.fleet_upgrade import verify_running_cli, select_release_components +prefix, native_root, verifier, target = sys.argv[1:] +assert Path(sys.prefix) == Path(prefix) +site = Path(sysconfig.get_path('purelib', scheme='posix_prefix', vars={'base': sys.prefix, 'platbase': sys.prefix})) +assert site.is_relative_to(Path(prefix)) +assert Path(dc_overview.__file__) == site / 'dc_overview/__init__.py' +spec = importlib.util.spec_from_file_location('selected_host_native_proof', verifier) +module = importlib.util.module_from_spec(spec) +spec.loader.exec_module(module) +module.ROOT = Path(native_root) +codes = module.naturally_loaded_selector_codes(module.time.monotonic() + 1) +selectors = [code for role, code in codes if role == 'dc-scoped-selector'] +assert len(selectors) == 1 and selectors[0] is select_release_components.__code__ +assert verify_running_cli(json.loads(target))['state'] == 'verified' +print(json.dumps({'interpreter': 'compatible-host-venv', 'selector_source': True, 'cli_provenance': True})) +''' + selected_cli = {'release': self.current['dc-overview'][1], 'url': self.urls['dc-overview'], + 'sha256': self.current['dc-overview'][2]} + proof = json.loads(run(self.host_env / 'bin/python', '-I', '-c', installed_layout_proof, + self.host_env, ROOT, Path(__file__), json.dumps(selected_cli), timeout=30).stdout) + assert proof == {'interpreter': 'compatible-host-venv', 'selector_source': True, 'cli_provenance': True} + self.qa.record('selected-host-installed-layout', result='passed', **proof) + link = Path('/usr/local/bin/dc-overview') + assert link.is_symlink() and link.resolve() == Path(sys.executable).parent / 'dc-overview' + link.unlink() + link.symlink_to(self.host_env / 'bin/dc-overview') + + def seed_synthetic_selected_state(self): + """Only owned synthetic DB. No network credentials or real collection claim.""" + _bootstrap_step = "synthetic-runtime-inspect" + qa = self.qa + original = inspect('ipmi-monitor') + mounts = [m for m in original['Mounts'] if m['Destination'] == '/app/data'] + assert len(mounts) == 1 + assert mounts[0]['Type'] == 'volume' and mounts[0].get('Name') in qa.volumes + database = Path(mounts[0]['Source']) / 'ipmi_events.db' + import sqlite3 + from datetime import datetime, timezone + _bootstrap_step = "synthetic-db-seed" + with sqlite3.connect(database) as db: + # Verify initialization before *any* seed write; never repair site fields here. + assert db.execute('SELECT id,site_id,site_name FROM cloud_sync').fetchall() == [ + (1, 'synthetic-fleet-native-site', 'SYNTHETIC Fleet native fixture')] + credential = 'SYNTHETIC-NONSECRET-NOT-A-CREDENTIAL' + fields = {'ai_link_email': 'fixture@example.invalid', 'ai_link_user_id': 'fixture-user', + 'ai_link_customer_id': 'fixture-customer', 'ai_link_linked_at': '2026-11-02T00:00:00Z', + 'ai_link_key_digest': digest(credential.encode())} + for key, value in fields.items(): + db.execute('DELETE FROM system_settings WHERE key=?', (key,)) + db.execute('INSERT INTO system_settings(key,value) VALUES (?,?)', (key, value)) + db.execute('UPDATE cloud_sync SET license_key=?,sync_enabled=0,subscription_valid=1', (credential,)) + sampled_at = datetime.now(timezone.utc).replace(tzinfo=None).isoformat() + db.execute("INSERT OR REPLACE INTO server_status(bmc_ip,server_name,last_check) VALUES ('192.0.2.254','SYNTHETIC-no-collector',?)", (sampled_at,)) + # Import only retained verification code, never product checkout modules. + _bootstrap_step = "synthetic-read-aggregate" + import importlib.util + spec = importlib.util.spec_from_file_location('synthetic_protection', qa.args.protection_helper) + helper = importlib.util.module_from_spec(spec) + try: + helper_source = qa.args.protection_helper.read_bytes() + except Exception: + helper_source = None # Diagnostics never add a new bootstrap gate. + spec.loader.exec_module(helper) + try: + capture_helper_diagnostics(helper, helper_source, str(qa.args.protection_helper)) + except Exception: + pass # Unavailable diagnostic identity must not alter the helper. + deadline = time.monotonic() + 30 + ro = helper.open_ro(database, deadline) + try: + names = {row[0] for row in ro.execute("SELECT name FROM sqlite_master WHERE type='table'")} + state = helper.table_snapshot(ro, names & set(helper.SELECTED)) + baseline = helper.state_aggregate(state, 'ltx') + schema = helper.fingerprint(ro.execute('SELECT type,name,tbl_name,sql FROM sqlite_master ORDER BY type,name').fetchall()) + finally: + ro.close() + declared = {} + for name in ('/app/config/servers.yaml', '/app/data/servers.json'): + path = (Path(next(m['Source'] for m in original['Mounts'] if m['Destination'] == name)) + if name.endswith('servers.yaml') else database.parent / 'servers.json') + declared[name] = {'present': path.exists()} + if path.exists(): + declared[name]['sha256'] = digest(path.read_bytes()) + with database.open('rb') as file: + header = list(file.read(20)[18:20]) + helper.PINS = {'ltx': {'synthetic_fixture_only': True, 'data_volume_name': mounts[0]['Name'], + 'hostname': socket.gethostname(), 'container_id': original['Id'], + 'image_id': original['Image'], 'mounts': original['Mounts'], + 'database_device': database.stat().st_dev, 'database_inode': database.stat().st_ino, + 'journal_header_bytes': header, 'table_names': sorted(names), 'secret_mount_metadata': [], + 'declared_config': declared, + 'link_baseline': {key: baseline[key] for key in ('saved_identity_sha256', 'saved_identity_field_count', + 'saved_identity_complete', 'identity_mode', 'credential_present', 'credential_sha256', + 'stored_key_digest_matches', 'expected_email_matches', 'sync_enabled')}, + 'schema_sha256': schema, + 'protection_baseline': {key: baseline[key] for key in ('stable_cloud_sha256', 'settings_sha256', + 'stable_inventory_sha256', 'cached_subscription_valid')}, + 'selected_count_bounds': {key: [value, value] for key, value in baseline['counts'].items()}}} + capture = io.StringIO() + _bootstrap_step = "synthetic-root-custody" + self.backup_root.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + helper.safe_chain(self.backup_root.parent) + self.claim_backup_root() + _bootstrap_step = "synthetic-protection-helper" + with contextlib.redirect_stdout(capture): + helper.main('ltx') + result = json.loads(capture.getvalue()) + self.backups.append(Path(result['operation_dir'])) + qa.record('synthetic-continuity-baseline', result='passed', + receipt_sha256=result['receipt']['sha256'], + synthetic_health_timestamp=True, actual_collector_acceptance=False, + full_database_snapshot=False) + + def seed_failed_job(self): + """Use real old submit constructor, intercept helper launch only. + + The terminal result is intentional fixture state; no historical phases + are supplied, no real update is claimed to have failed in this setup. + """ + code = ''' +import json +from pathlib import Path +from cryptolabs_proxy import updates as u +class SeedEngine(u.UpdateEngine): + def create(self, name, request): + assert name.startswith('cryptolabs-update-') + assert request['Config']['Image'] == self.inspect('cryptolabs-proxy')['Image'] + def start(self, name): + assert name.startswith('cryptolabs-update-') +d=Path('/data/auth/update-jobs') +j=u.submit_job('ipmi-monitor','main','update',directory=d,engine=SeedEngine(),selection_directory='/etc/cryptolabs/releases') +assert {'id','helper','sources','targets','selection_snapshot','selection_sha256','manifest_sha256'} <= set(j) +j.update(state='failed',success=False,results={'ipmi-monitor':{'state':'recovery_required','success':False,'reason':'replacement_failed','desired':j['targets']['ipmi-monitor']['reference'],'observed':None,'owner':'proxy-updater','origin':j['targets']['ipmi-monitor']['origin'],'rollback_container':'ipmi-monitor'}}) +u.write_job(d,j) +print(json.dumps({'id':j['id']})) +''' + result = docker('exec', 'cryptolabs-proxy', 'python3', '-c', code) + return json.loads(result.stdout)['id'] + + def bootstrap(self): + _bootstrap_step = "legacy-runtime-inspect" + qa = self.qa + old_proxy = inspect('cryptolabs-proxy') + assert old_proxy['Image'] == inspect(LEGACY_PROXY, image=True)['Id'] + # Released images copy source; their stale OCI/__version__ strings are + # not installed wheel metadata. Compare real updater bytes to old wheel. + _bootstrap_step = "legacy-updater-probe" + with zipfile.ZipFile(self.legacy['cryptolabs-proxy'][0]) as archive: + expected_updater = digest(archive.read('cryptolabs_proxy/updates.py')) + observed_updater = docker('exec', 'cryptolabs-proxy', 'python3', '-c', + 'import hashlib,pathlib;from cryptolabs_proxy import updates;print(hashlib.sha256(pathlib.Path(updates.__file__).read_bytes()).hexdigest())').stdout.decode().strip() + assert observed_updater == expected_updater + _bootstrap_step = "legacy-capabilities-probe" + caps = json.loads(docker('exec', 'cryptolabs-proxy', 'python3', '-m', + 'cryptolabs_proxy.updates', 'capabilities').stdout) + assert caps.get('release_components') != 1 and caps.get('native_service_recovery') != 1 + _bootstrap_step = "synthetic-runtime-inspect" + self.seed_synthetic_selected_state() + _bootstrap_step = "legacy-job-seed" + job_id = self.seed_failed_job() + qa.legacy_job_id = job_id + before = recovery_store_snapshot(qa.jobs) + self.failed_job_raw = before[job_id + '.json'][0] + selected_before = (qa.store.root / 'selection.json').read_bytes() + public_before = (CONFIG / 'fleet-config.yaml').read_bytes() + _bootstrap_step = "compatible-wheel-install" + self.install_compatible_host() + assert (qa.store.root / 'selection.json').read_bytes() == selected_before + assert (CONFIG / 'fleet-config.yaml').read_bytes() == public_before + # New broker owner must refuse actual legacy capabilities, even with + # compatible host packages and valid synthetic admission installed. + _bootstrap_step = "legacy-owner-rejection" + from dc_overview.release_broker import InstalledOwner + from dc_overview.fleet_config import FleetConfig + try: + InstalledOwner(FleetConfig.load(CONFIG), qa.policy).capabilities(1) + except Exception as error: + assert getattr(error, 'code', None) == 'owner-maintenance' + else: + raise AssertionError('legacy live owner unexpectedly accepted') + cli = self.host_env / 'bin/dc-overview' + arguments = ('release', 'reconcile-service', '--service', 'ipmi-monitor', '--job', job_id) + _bootstrap_step = "legacy-reconcile" + first = run(cli, *arguments, timeout=130) + reply = json.loads(first.stdout) + assert set(reply) == {'job_id', 'service', 'outcome', 'resolution_available', 'reason'} + assert reply['job_id'] == job_id and reply['service'] == 'ipmi-monitor' + assert reply['outcome'] == 'original_restored' + receipt_name = 'service-recovery-' + job_id + '.json' + receipt = verify_recovery_store(qa.jobs, before, job_id, inspect('ipmi-monitor')['Id']) + parsed = json.loads(receipt) + assert inspect('cryptolabs-proxy')['Id'] == old_proxy['Id'] + # Simulated lost CLI acknowledgement: disregard first reply, retry + # the actual command; exact durable receipt and timestamp must survive. + _bootstrap_step = "legacy-reconcile-replay" + run(cli, *arguments, timeout=130) + assert verify_recovery_store(qa.jobs, before, job_id, parsed['original_container_id']) == receipt + assert (qa.store.root / 'selection.json').read_bytes() == selected_before + assert (CONFIG / 'fleet-config.yaml').read_bytes() == public_before + qa.record('legacy-reconcile-before-selection', result='passed', job_id=job_id, + proxy_image=LEGACY_PROXY, failed_job_sha256=parsed['job_sha256'], + active_sha256=parsed['active_sha256'], receipt_sha256=digest(receipt), + only_new_durable_file=receipt_name, lost_cli_ack_replay='same receipt bytes', + historical_phase_evidence='not fabricated') + _bootstrap_step = "scoped-select" + manifest = json.loads(qa.store.load(platform='linux/amd64').manifest.raw) + manifest['baseline_id'] = 'native-compatible-bootstrap' + manifest['components']['cryptolabs-proxy'] = qa.component('proxy-a') + path, version, checksum = self.current['dc-overview'] + manifest['components']['dc-overview-cli'] = {'owner': 'host-cli', 'release': version, + 'artifacts': {'any': {'kind': 'wheel', 'url': self.urls['dc-overview'], 'sha256': checksum}}} + candidate = qa.data / 'compatible-bootstrap.json' + write(candidate, manifest) + run(cli, 'release', 'select', '--release-manifest', candidate, + '--component', 'cryptolabs-proxy', '--record-cli', scoped_select_diagnostic=True, + scoped_select_wheels=self.current) + assert (qa.jobs / (job_id + '.json')).read_bytes() == self.failed_job_raw + assert (qa.jobs / 'active.json').read_bytes() == before['active.json'][0] + _bootstrap_step = "proxy-plan" + from cryptolabs_proxy.standard_adoption import StandardAdoption + owner = StandardAdoption(PROXY_CONFIG) + plan = owner.plan(qa.declaration) + qa.owner_plans.add(plan['plan_id']) + _bootstrap_step = "proxy-adopt" + result = owner.adopt(qa.declaration, plan['plan_id']) + assert result['state'] == 'adopted' + assert inspect('cryptolabs-proxy')['Id'] != old_proxy['Id'] + assert inspect('cryptolabs-proxy')['Image'] == inspect(qa.refs['proxy-a'], image=True)['Id'] + assert (qa.jobs / (job_id + '.json')).read_bytes() == self.failed_job_raw + assert (qa.jobs / 'active.json').read_bytes() == before['active.json'][0] + assert any(m['Destination'] == SOCKET and not m['RW'] for m in inspect('cryptolabs-proxy')['Mounts']) + assert qa.policy['writes_enabled'] is False + _bootstrap_step = "proxy-health" + qa.wait_healthy('cryptolabs-proxy') + qa.record('legacy-host-select-socket-adopt', result='passed', old_proxy_id=old_proxy['Id'], + new_proxy_id=inspect('cryptolabs-proxy')['Id'], writes_enabled=False, + old_job_still_failed=True, new_durable_receipt_retained=True) + + def verify_successor(self, job_id): + qa = self.qa + successor = json.loads((qa.jobs / (job_id + '.json')).read_bytes()) + predecessor = successor['recovery_predecessor'] + assert predecessor['job_id'] == qa.legacy_job_id + assert (qa.jobs / (qa.legacy_job_id + '.json')).read_bytes() == self.failed_job_raw + receipt = (qa.jobs / ('service-recovery-' + qa.legacy_job_id + '.json')).read_bytes() + assert predecessor['receipt_sha256'] == digest(receipt) + qa.record('legacy-recovery-scoped-successor', result='passed', job_id=job_id, + predecessor_id=qa.legacy_job_id, original_failed_history_retained=True) + + def claim_backup_root(self): + parent = self.backup_root.parent.lstat() + assert stat.S_ISDIR(parent.st_mode) and parent.st_uid == os.geteuid() and not parent.st_mode & 0o022 + self.backup_root.mkdir(mode=0o700) # exclusive; never adopt a preexisting root + info = self.backup_root.lstat() + assert stat.S_ISDIR(info.st_mode) and stat.S_IMODE(info.st_mode) == 0o700 and info.st_uid == os.geteuid() + self.backup_root_identity = (info.st_dev, info.st_ino, info.st_uid) + + def reset(self): + # Called after normal owned containers quiesce; retain on custody doubt. + if self.backup_root_identity is not None: + info = self.backup_root.lstat() + assert stat.S_ISDIR(info.st_mode) and stat.S_IMODE(info.st_mode) == 0o700 + assert (info.st_dev, info.st_ino, info.st_uid) == self.backup_root_identity and info.st_uid == os.geteuid() + for directory in self.backups: + assert directory.parent == self.backup_root and directory.is_dir() and not directory.is_symlink() + shutil.rmtree(directory) + self.backups.clear() + self.backup_root.rmdir() + self.backup_root_identity = None + else: + assert not self.backups + if self.server is not None: + self.server.shutdown() + self.server.server_close() + self.thread.join(timeout=5) + assert not self.thread.is_alive() + self.server = None + if self.github_hosts is not None: + expected = self.github_hosts + b'\n127.0.0.2 github.com # fleet-native-owned-wheel-mirror\n' + assert Path('/etc/hosts').read_bytes() == expected + Path('/etc/hosts').write_bytes(self.github_hosts) + self.github_hosts = None + link = Path('/usr/local/bin/dc-overview') + if link.is_symlink() and link.resolve() == self.host_env / 'bin/dc-overview': + link.unlink() + link.symlink_to(Path(sys.executable).parent / 'dc-overview') + + class NativeQA: def __init__(self, args): self.args = args @@ -474,7 +2441,12 @@ def __init__(self, args): self.label = "io.cryptolabs.native-qa.run=" + os.environ.get("FLEET_NATIVE_RUN_ID", "") self.hosts = None self.units = [] + self.policy_timer_attempted = False + self.policy_timer_record = None + self.policy_timer_quiesced = False self.volumes = [] + self.synthetic_ipmi_volume = None + self.site_initializers = {} self.networks = [] self.session = None self.cookie = None @@ -492,6 +2464,232 @@ def __init__(self, args): self.registry_trust = None self.fixture_owned = False self.child_failure_identity = None + self.owner_observation_identity = None + self.recovery = LegacyRecoveryFixture(self) + + def reset_owner_observation(self): + global _owner_observation_identity + flags = os.O_RDWR + if self.owner_observation_identity is None: + flags |= os.O_CREAT | os.O_EXCL + descriptor, info = owner_observation_file(flags) + try: + if (self.owner_observation_identity is not None + and trust_identity(info) != self.owner_observation_identity): + raise ValueError('owner observation custody held') + os.ftruncate(descriptor, 0) + self.owner_observation_identity = trust_identity(info) + _owner_observation_identity = self.owner_observation_identity + finally: + os.close(descriptor) + + def read_owner_observation(self, operation_id): + try: + if self.owner_observation_identity is None or not observation_uuid(operation_id): + return None + value = observation_read(ROOT / 'broker-owner-observation.json', 4096, + identity=self.owner_observation_identity) + if (type(value) is dict and set(value) == {'schema_version', 'operation_id', 'failure'} + and type(value['schema_version']) is int and value['schema_version'] == 1 + and value['operation_id'] == operation_id and observation_failure_valid(value['failure'])): + return value['failure'] + except Exception: + pass + return None + + def proxy_adoption_observation(self, operation_id, expected): + """One fixed operation and private child record, without owner calls.""" + unknown = {'qualification': 'unknown', 'operation_state': 'unknown', + 'operation_phase': 'unknown', 'reason_category': 'unknown', + 'owner_plan_matches_preview': None, 'owner_declaration_matches_preview': None, + 'failure': None} + try: + deadline = time.monotonic() + 1 + observation_deadline(deadline) + if self.layout != 'named-volume' or not observation_uuid(operation_id): + raise ObservationRefused('identity-refused') + prefix = Path('/opt/fleet-native-qa/venv') + site = prefix / 'lib/python3.12/site-packages' + if (Path(sys.prefix) != prefix + or Path(sysconfig.get_path('purelib', scheme='posix_prefix', + vars={'base': sys.prefix, 'platbase': sys.prefix})) != site): + raise ObservationRefused('source-refused') + if digest(selector_read_bytes(site / 'dc_overview/release_broker.py', 1048576, deadline)) != FROZEN_PRODUCT_HASHES['dc']['src/dc_overview/release_broker.py']: + raise ObservationRefused('source-refused') + record = observation_read(self.store.root / 'broker/operations' / (operation_id + '.json'), 1048576) + observation_deadline(deadline) + selector_operation(record, operation_id) + if (type(expected) is not dict or set(expected) != {'apply', 'request', 'preview'} + or any(type(expected[k]) is not dict for k in expected) + or record['operation_kind'] != 'proxy-adopt' + or record['request'] != expected['request'] + or any(record.get(k) != v for k, v in expected['apply'].items()) + or any(record.get(k) != expected['preview'].get(k) for k in ( + 'preview_id', 'preview_sha256', 'selection_id', 'selection_sha256', 'manifest_sha256')) + or (record['actor'] != expected['preview']['actor'] if 'actor' in expected['preview'] else + record['actor'].get('kind') != 'fleet-admin' or record['actor'].get('username') != 'native-admin')): + raise ObservationRefused('identity-refused') + result = {**unknown, 'qualification': 'valid', 'operation_state': record['state'], + 'operation_phase': record['phase'], + 'owner_plan_matches_preview': record['owner_plan'] == expected['preview'].get('owner_plan'), + 'owner_declaration_matches_preview': (record['owner_declaration'] == expected['preview']['owner_declaration'] + if 'owner_declaration' in expected['preview'] else None)} + reasons = { + 'Proxy source or declaration changed after preview': 'proxy-preview-plan-changed', + 'Owner operation interrupted; reconcile retained operation before retry': 'owner-interrupted', + 'Installed owner recovery verification required': 'owner-recovery-required', + 'Selected release changed before owner dispatch': 'selection-conflict', + 'Resulting selection differs from preview': 'selection-conflict', + } + result['reason_category'] = reasons.get(record.get('reason'), 'unknown') + failure = self.read_owner_observation(operation_id) + if type(failure) is dict and 'adoption' in failure: + result['failure'] = failure + observation_deadline(deadline) + if len(encoded(result)) > 4096: + raise ObservationRefused('overflow') + return result + except Exception as refused: + reason = refused.args[0] if type(refused) is ObservationRefused and refused.args else 'unknown' + return {**unknown, 'qualification': reason if type(reason) is str and reason in ( + 'source-refused', 'schema-refused', 'identity-refused', 'custody-refused', + 'parse-refused', 'overflow', 'deadline') else 'unknown'} + + def owner_mapping_observation(self, operation_id): + unknown = {'observation': 'unknown', 'job_id_present': None} + result = {'operation': {**unknown, 'state': 'unknown', 'phase': 'unknown', 'reason_category': 'unknown'}, + 'fixture_mapping': dict(unknown), 'current_mapping': dict(unknown), + 'owner_store': {'observation': 'unknown', 'mount_type': 'unknown', + 'auth_equal': None, 'jobs_equal': None}, 'failure': None} + result['operation_qualification'] = 'unknown' + try: + if not observation_uuid(operation_id): + return result + except Exception: + return result + + try: + result['failure'] = self.read_owner_observation(operation_id) + if (type(result['failure']) is dict and 'selector' in result['failure'] + and self.layout != 'named-volume'): + result['failure'] = None + except Exception: + pass + + def project(directory, operation=False): + value = dict(result['operation'] if operation else unknown) + try: + deadline = time.monotonic() + 1 if operation else None + observation_directories(directory) + try: + record = observation_read(directory / (operation_id + '.json'), 1048576) + except ObservationAbsent: + # Absence only follows a trusted, still present parent lookup. + observation_directories(directory) + value['observation'] = 'absent' + if operation: + observation_deadline(deadline) + result['operation_qualification'] = 'absent-after-trusted-parent' + return value + if type(record) is not dict or record.get('operation_id') != operation_id: + if operation: + result['operation_qualification'] = 'identity-refused' + return value + if operation: + observation_deadline(deadline) + # The sudo parent cannot trust runner-owned checkout ancestry. + # Use only the current wheel installed by this native route. + prefix = Path('/opt/fleet-native-qa/venv') + site = prefix / 'lib/python3.12/site-packages' + if (Path(sys.prefix) != prefix + or Path(sysconfig.get_path('purelib', scheme='posix_prefix', + vars={'base': sys.prefix, 'platbase': sys.prefix})) != site): + raise ObservationRefused('source-refused') + source = site / 'dc_overview/release_broker.py' + if digest(selector_read_bytes(source, 1048576, deadline)) != FROZEN_PRODUCT_HASHES['dc']['src/dc_overview/release_broker.py']: + raise ObservationRefused('source-refused') + selector_operation(record, operation_id) + expected = getattr(self, 'owner_mapping_expected', None) + if expected is not None: + if (any(record.get(k) != v for k, v in expected['apply'].items()) + or record['request'] != expected['request'] + or any(record.get(k) != expected['preview'].get(k) for k in ( + 'preview_id', 'preview_sha256', 'selection_id', 'selection_sha256', 'manifest_sha256')) + or record['actor'].get('kind') != 'fleet-admin' + or record['actor'].get('username') != 'native-admin'): + raise ObservationRefused('identity-refused') + elif self.layout == 'named-volume': + raise ObservationRefused('identity-refused') + observation_deadline(deadline) + result['operation_qualification'] = 'valid' + value['observation'] = 'present' + job = record.get('job_id') + value['job_id_present'] = (False if 'job_id' not in record else + True if type(job) is str and re.fullmatch('[0-9a-f]{32}', job) else None) + if operation: + states = ('prepared', 'selecting', 'pending-submit', 'updating', 'adopting', + 'recovery-required', 'selection-conflict', 'completed', 'failed-restored') + state, phase = record.get('state'), record.get('phase') + value['state'] = state if type(state) is str and state in states else 'unknown' + value['phase'] = phase if type(phase) is str and phase in ('selection', 'owner') else 'unknown' + reasons = { + 'Owner operation interrupted; reconcile retained operation before retry': 'owner-interrupted', + 'Owner update did not verify; inspect retained owner result': 'owner-unverified', + 'Installed owner recovery verification required': 'owner-recovery-required', + 'Selected release changed before owner dispatch': 'selection-conflict', + 'Resulting selection differs from preview': 'selection-conflict', + } + reason = record.get('reason') + value['reason_category'] = reasons.get(reason, 'unknown') if type(reason) is str else 'unknown' + observation_deadline(deadline) + return value + except Exception as refused: + if operation: + reason = refused.args[0] if type(refused) is ObservationRefused and refused.args else 'custody-refused' + result['operation_qualification'] = reason if type(reason) is str and reason in ( + 'identity-refused', 'schema-refused', 'source-refused', 'parse-refused', + 'custody-refused', 'overflow', 'deadline') else 'unknown' + return dict(result['operation']) + return value + + try: + result['operation'] = project(self.store.root / 'broker/operations', operation=True) + # Verify the independently constructed fixture store before using any + # mount-derived source. Never authorize a new path from inspect alone. + fixture_auth = observation_directories(self.auth) + fixture_jobs = observation_directories(self.jobs) + if self.jobs != self.auth / 'update-jobs': + return result + result['fixture_mapping'] = project(self.jobs / 'operations') + inspected = inspect_owner_mounts_bounded() + if type(inspected) is not list or len(inspected) != 1 or type(inspected[0]) is not dict: + return result + mounts = inspected[0].get('Mounts') + if type(mounts) is not list or any(type(m) is not dict for m in mounts): + return result + auth = [m for m in mounts if m.get('Destination') == '/data/auth'] + if (len(auth) != 1 or auth[0].get('RW') is not True + or auth[0].get('Type') not in ('bind', 'volume') + or any(type(m.get('Destination')) is not str or m['Destination'].startswith('/data/auth/') for m in mounts)): + return result + mount = auth[0] + if type(mount.get('Source')) is not str: + return result + source = Path(mount['Source']) + if not source.is_absolute() or '..' in source.parts or source != self.auth: + result['owner_store']['observation'] = 'foreign' + return result + if observation_directories(self.auth) != fixture_auth or observation_directories(self.jobs) != fixture_jobs: + return result + auth_info, jobs_info = self.auth.lstat(), self.jobs.lstat() + result['owner_store'] = {'observation': 'same', 'mount_type': mount['Type'], + 'auth_equal': True, 'jobs_equal': True, + 'auth_device': auth_info.st_dev, 'auth_inode': auth_info.st_ino, + 'jobs_device': jobs_info.st_dev, 'jobs_inode': jobs_info.st_ino} + result['current_mapping'] = dict(result['fixture_mapping']) + except Exception: + pass + return result def reset_child_failure(self): try: @@ -883,6 +3081,7 @@ def _record_event(self, event): ) def preflight(self): + check_recovery_inputs(self.args.proxy_sha) check_source_pin(self.args.proxy_sha) if not re.fullmatch("[0-9a-f]{40}", self.args.dc_sha or ""): raise RuntimeError("exact reviewed DC event head required") @@ -952,6 +3151,7 @@ def preflight(self): raise RuntimeError("fixture container name already occupied") ROOT.mkdir(mode=0o700) self.fixture_owned = True + self.recovery.install_old_host() (ROOT / "docker-client").mkdir(mode=0o700) os.environ["DOCKER_CONFIG"] = str(ROOT / "docker-client") write(ROOT / "docker-client/config.json", {"auths": {}}) @@ -997,6 +3197,8 @@ def push_fixture(self, key, tag): return result def images(self): + docker("pull", "--platform", "linux/amd64", LEGACY_PROXY, timeout=900) + assert LEGACY_PROXY in inspect(LEGACY_PROXY, image=True)["RepoDigests"] for ref in (REGISTRY_IMAGE, NGINX_BASE, IPMI_OLD, IPMI_NEW): docker("pull", "--platform", "linux/amd64", ref, timeout=900) data = inspect(ref, image=True) @@ -1126,6 +3328,9 @@ def units_install(self): import dc_overview package = Path(dc_overview.__file__).parent + for name in POLICY_REFRESH_UNITS: + destination = POLICY_REFRESH_SYSTEMD / name + assert not destination.exists() and not destination.is_symlink(), 'native refresh unit collision' for name in (SERVICE, SOCKET_UNIT): destination = Path("/etc/systemd/system") / name if destination.exists(): @@ -1138,6 +3343,143 @@ def units_install(self): run("systemd-analyze", "verify", *self.units) run("systemctl", "daemon-reload") + def synthetic_ipmi_volume_custody(self, *, require_empty=False, timeout=60): + """Only the named-volume fixture's positively created IPMI resource.""" + expected = self.synthetic_ipmi_volume + assert expected is not None + info = json.loads(docker('volume', 'inspect', expected['name'], timeout=timeout).stdout)[0] + key, label = self.label.split('=', 1) + assert info['Name'] == expected['name'] and info.get('Labels', {}).get(key) == label + assert info.get('Labels', {}).get('io.cryptolabs.native-qa.volume') == expected['nonce'] + assert info['Driver'] == 'local' and not info.get('Options') + path = Path(info['Mountpoint']) + assert path.is_absolute() and path.resolve() == path + chain = trust_directories(path) + if require_empty: + assert not list(path.iterdir()) + return str(path), chain, info.get('CreatedAt') + + def site_initializer_custody(self, value, expected): + """An exact stopped/started one-shot record, never just a matching name.""" + assert re.fullmatch(r"[0-9a-f]{64}", value['Id']) + assert expected['id'] is None or value['Id'] == expected['id'] + assert value['Name'] == '/' + expected['name'] + key, label = self.label.split('=', 1) + config, host = value['Config'], value['HostConfig'] + assert config.get('Labels', {}).get(key) == label + assert value['Image'] == expected['image'] and config['Image'] == expected['image'] + assert config['Entrypoint'] == ['python3'] + assert config['Cmd'] == ['-c', SYNTHETIC_SITE_INITIALIZER] + assert host['NetworkMode'] == 'none' and host['Privileged'] is False + assert not any(host.get(k) for k in ('Binds', 'Devices', 'CapAdd', 'PidMode', 'VolumesFrom')) + env = config['Env'] + for entry in ('DATA_DIR=/app/data', 'SITE_NAME=SYNTHETIC Fleet native fixture'): + assert [item for item in env if item.split('=', 1)[0] == entry.split('=', 1)[0]] == [entry] + assert len(value['Mounts']) == 2 + mounts = {mount['Destination']: mount for mount in value['Mounts']} + data, empty = mounts['/app/data'], mounts['/app/config/servers.yaml'] + assert data['Type'] == 'volume' and data['Name'] == expected['volume'] + assert data['Source'] == expected['mountpoint'] and data['RW'] is True + assert empty['Type'] == 'bind' and empty['Source'] == expected['config'] and empty['RW'] is False + + # TRACEWEAVER: entrypoint=initialize_synthetic_site; req=REQ-FLEETUPDATE-001; trace=TRACE-FLEETUPDATE-001; ver=VER-FLEETUPDATE-001 + def initialize_synthetic_site(self, volume, empty, network): + """One offline initialization, before any old runtime or continuity baseline.""" + deadline = time.monotonic() + 60 + + def remaining(): + left = deadline - time.monotonic() + if left <= 0: + raise NativeCommandFailure('timeout') + return left + + def engine(*args): + return docker(*args, timeout=remaining()) + + def image(ref): + return json.loads(engine('image', 'inspect', ref).stdout)[0] + + old = image(IPMI_OLD) + assert IPMI_OLD in old['RepoDigests'] + assert old['Os'] == 'linux' and old['Architecture'] == 'amd64' + assert old['Config']['Labels']['org.opencontainers.image.revision'] == 'a5cfd4ea0d6e43c6346f641693fcb6eef449433b' + image_id = old['Id'] + assert re.fullmatch(r'sha256:[0-9a-f]{64}', image_id) + assert re.fullmatch(r'ghcr\.io/cryptolabsza/ipmi-monitor@sha256:[0-9a-f]{64}', self.refs['ipmi-old']) + mirror = image(self.refs['ipmi-old']) + assert mirror['Id'] == image_id and self.refs['ipmi-old'] in mirror['RepoDigests'] + assert volume in self.volumes and volume == network + '-data' + assert re.fullmatch(r'native-fleet-named-volume-[1-9][0-9]*', network) + assert self.label == 'io.cryptolabs.native-qa.run=' + network.rsplit('-', 1)[1] + name = network + '-site-init' + + def filesystem(*, require_empty): + info = json.loads(engine('volume', 'inspect', volume).stdout)[0] + key, label = self.label.split('=', 1) + assert info['Name'] == volume and info.get('Labels', {}).get(key) == label + assert info['Driver'] == 'local' and not info.get('Options') + assert self.synthetic_ipmi_volume['name'] == volume + assert self.synthetic_ipmi_volume_custody(timeout=remaining()) == self.synthetic_ipmi_volume['custody'] + mountpoint = Path(info['Mountpoint']) + assert mountpoint.is_absolute() and mountpoint.resolve() == mountpoint + directories = trust_directories(mountpoint) + assert empty.is_absolute() and empty.resolve() == empty + config_chain = trust_directories(empty.parent) + config_bytes, config_info = trust_read(empty) + assert config_bytes == b'servers: []\n' + if require_empty: + assert not list(mountpoint.iterdir()) + return (str(mountpoint), directories, config_chain, + trust_identity(config_info), trust_metadata(config_info)) + + custody = filesystem(require_empty=True) + + def no_other_writer(): + for identity in engine('ps', '-aq', '--no-trunc').stdout.decode().split(): + assert re.fullmatch(r'[0-9a-f]{64}', identity) + value = json.loads(engine('inspect', identity).stdout)[0] + assert value['Name'] not in ('/ipmi-monitor', '/' + name) + assert not any(m.get('Name') == volume or m.get('Source') == custody[0] + for m in value.get('Mounts', [])) + + no_other_writer() + expected = dict(name=name, image=image_id, volume=volume, + mountpoint=custody[0], config=str(empty), id=None) + assert name not in self.site_initializers + # Before Engine can create/start anything, normal cleanup knows exact ownership. + self.site_initializers[name] = expected + created = engine('create', '--name', name, '--label', self.label, '--network', 'none', + '--entrypoint', 'python3', '--mount', f'type=volume,src={volume},dst=/app/data', + '--mount', f'type=bind,src={empty},dst=/app/config/servers.yaml,readonly', + '-e', 'DATA_DIR=/app/data', '-e', 'SITE_NAME=SYNTHETIC Fleet native fixture', + image_id, '-c', SYNTHETIC_SITE_INITIALIZER).stdout.decode().strip() + assert re.fullmatch(r'[0-9a-f]{64}', created) + expected['id'] = created + value = json.loads(engine('inspect', created).stdout)[0] + self.site_initializer_custody(value, expected) + assert value['State']['Running'] is False and value['State']['Status'] == 'created' + assert filesystem(require_empty=True) == custody + # Recheck all other mounts immediately before start; allow only this exact one-shot. + for identity in engine('ps', '-aq', '--no-trunc').stdout.decode().split(): + assert re.fullmatch(r'[0-9a-f]{64}', identity) + if identity != created: + other = json.loads(engine('inspect', identity).stdout)[0] + assert other['Name'] != '/ipmi-monitor' + assert not any(m.get('Name') == volume or m.get('Source') == custody[0] + for m in other.get('Mounts', [])) + engine('start', created) + assert engine('wait', created).stdout.strip() == b'0' + value = json.loads(engine('inspect', created).stdout)[0] + self.site_initializer_custody(value, expected) + state = value['State'] + assert state['Running'] is False and state['Status'] == 'exited' + assert type(state['ExitCode']) is int and state['ExitCode'] == 0 + assert not state.get('OOMKilled') and not state.get('Error') + assert filesystem(require_empty=False) == custody + remaining() + # Retain this stopped exact ID in normal cleanup ownership until reset. + return image_id + def fixture(self, layout): import yaml from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey @@ -1149,6 +3491,7 @@ def fixture(self, layout): self.layout = layout CONFIG.mkdir(mode=0o755) + write(CONFIG / ".lifecycle-config.lock", b"") PROXY_CONFIG.mkdir(mode=0o700) network = "native-fleet-" + layout + "-" + os.environ["FLEET_NATIVE_RUN_ID"] docker("network", "create", "--label", self.label, network) @@ -1181,7 +3524,7 @@ def fixture(self, layout): "QA_USER_PASS": self.password, } run( - sys.executable, + self.recovery.host_env / 'bin/python' if layout == 'named-volume' else sys.executable, "-c", "from cryptolabs_proxy.auth import create_user; import os; assert create_user('native-admin',os.environ['QA_USER_PASS'],'admin')", env=env, @@ -1191,8 +3534,8 @@ def fixture(self, layout): "selection_contract": 1, "baseline_id": "native-baseline", "components": { - "cryptolabs-proxy": self.component("proxy-a"), - "ipmi-monitor": self.component("ipmi-old"), + "cryptolabs-proxy": ({"owner": "proxy-updater", "release": "1.5.4", "artifacts": {"linux/amd64": {"kind": "oci", "reference": LEGACY_PROXY}}} if layout == 'named-volume' else self.component("proxy-a")), + "ipmi-monitor": ({"owner": "proxy-updater", "release": "1.3.2", "artifacts": {"linux/amd64": {"kind": "oci", "reference": LEGACY_DESIRED}}} if layout == 'named-volume' else self.component("ipmi-old")), "grafana": { "owner": "proxy-updater", "release": "untouched-pin", @@ -1229,6 +3572,7 @@ def fixture(self, layout): "vast-price-manager": {"origin": "unmanaged", "enabled": False}, } self.store = ReleaseStore(CONFIG / "releases") + self.policy_retain_installed_manifest(manifest, policies) prepared = self.store.prepare(source, platform="linux/amd64", policies=policies) self.store.commit(prepared) config = FleetConfig(config_dir=CONFIG) @@ -1262,6 +3606,7 @@ def fixture(self, layout): } write(POLICY, self.policy) self.reset_child_failure() + self.reset_owner_observation() run("systemctl", "start", SOCKET_UNIT) denied = raw_request() assert denied["ok"] is False and denied["error"]["status"] == 503 @@ -1292,7 +3637,7 @@ def fixture(self, layout): dropin, ( "[Service]\nExecStart=\nExecStart=" - + sys.executable + + str(self.recovery.host_env / 'bin/python' if layout == 'named-volume' else sys.executable) + " /opt/fleet-native-qa/verify_fleet_release_native.py --broker-child\n" ).encode(), 0o644, @@ -1316,8 +3661,26 @@ def fixture(self, layout): empty = self.data / "servers.yaml" write(empty, b"servers: []\n", 0o644) ipmi_data = network + "-data" - docker("volume", "create", "--label", self.label, ipmi_data) - self.volumes.append(ipmi_data) + if layout == 'named-volume': + # Engine create is idempotent. Reject occupied names before any intent + # registration; the fresh nonce also rejects a collision after inventory. + assert ipmi_data not in docker('volume', 'ls', '--format', '{{.Name}}').stdout.decode().splitlines() + assert self.synthetic_ipmi_volume is None + self.synthetic_ipmi_volume = dict(name=ipmi_data, nonce=secrets.token_hex(16), custody=None) + docker('volume', 'create', '--label', self.label, '--label', + 'io.cryptolabs.native-qa.volume=' + self.synthetic_ipmi_volume['nonce'], ipmi_data) + # An ambiguous create or failed custody read leaves only a pending intent. + # It never enters the deletion list; cleanup holds for external VM teardown. + self.synthetic_ipmi_volume['custody'] = self.synthetic_ipmi_volume_custody(require_empty=True) + self.volumes.append(ipmi_data) + else: + docker("volume", "create", "--label", self.label, ipmi_data) + self.volumes.append(ipmi_data) + old_ipmi = self.refs["ipmi-old"] + site_environment = () + if layout == "named-volume": + old_ipmi = self.initialize_synthetic_site(ipmi_data, empty, network) + site_environment = ("-e", "SITE_NAME=SYNTHETIC Fleet native fixture") docker( "run", "-d", @@ -1331,8 +3694,10 @@ def fixture(self, layout): f"type=volume,src={ipmi_data},dst=/app/data", "--mount", f"type=bind,src={empty},dst=/app/config/servers.yaml,readonly", - self.refs["ipmi-old"], + *site_environment, + old_ipmi, ) + socket_mount = ("--mount", f"type=bind,src={SOCKET},dst={SOCKET},readonly") if layout == 'bind' else () docker( "run", "-d", @@ -1354,8 +3719,7 @@ def fixture(self, layout): f"type=bind,src={self.data}/ssl,dst=/etc/nginx/ssl,readonly", "--mount", f"type=bind,src={self.store.root},dst=/etc/cryptolabs/releases,readonly", - "--mount", - f"type=bind,src={SOCKET},dst={SOCKET},readonly", + *socket_mount, "--mount", "type=bind,src=/var/run/docker.sock,dst=/var/run/docker.sock", "-e", @@ -1363,13 +3727,17 @@ def fixture(self, layout): "-e", "FLEET_ADMIN_PASS=", "-e", + "PYTHONPATH=/app/src", + "-e", "FLEET_PUBLIC_ORIGIN=" + ORIGIN, "-e", "RELEASE_SELECTION_REQUIRED=true", - self.refs["proxy-a"], + LEGACY_PROXY if layout == 'named-volume' else self.refs["proxy-a"], ) self.wait_healthy("ipmi-monitor") self.wait_healthy("cryptolabs-proxy") + if layout == 'named-volume': + self.recovery.bootstrap() for name in ("ipmi-monitor", "cryptolabs-proxy"): for mount in inspect(name).get("Mounts", []): if mount.get("Type") == "volume" and mount.get("Name") not in self.volumes: @@ -1432,10 +3800,314 @@ def fixture(self, layout): kernel_peer="root allowed then excluded by reloaded UID policy; nobody denied by socket mode", ) + def policy_installed_version(self, key): + proof = IPMI_POLICY_PROOFS[key] + before = inspect('ipmi-monitor') + assert before['State']['Running'] is True, 'policy package probe requires running IPMI' + label, value = self.label.split('=', 1) + assert before['Config']['Labels'].get(label) == value, 'policy package probe ownership' + image = inspect(before['Image'], image=True) + assert image['Id'] == before['Image'], 'policy package image identity' + assert (image['Os'], image['Architecture']) == ('linux', 'amd64'), 'policy package platform' + assert proof['reference'] in image.get('RepoDigests', []), 'policy package immutable reference' + assert image['Config']['Labels'].get('org.opencontainers.image.revision') == proof['source_revision'], 'policy package source' + code = 'import importlib.metadata; print(importlib.metadata.version("ipmi-monitor"))' + result = docker('exec', before['Id'], 'python3', '-I', '-B', '-c', code, timeout=30) + assert len(result.stdout) <= 64, 'policy package version bound' + version = result.stdout.decode('ascii').strip() + assert version == proof['version'], 'policy actual package version mismatch' + after = inspect('ipmi-monitor') + assert (after['Id'], after['Image'], after['State']['Running']) == (before['Id'], before['Image'], True), 'policy package container raced' + return version + + def policy_state_snapshot(self): + current = self.selection() + raw = docker('ps', '-aq', '--no-trunc', timeout=15).stdout + assert len(raw) <= 64 * 65 + 1, 'policy inventory byte bound' + identities = raw.decode('ascii').splitlines() + assert len(identities) <= 64 and len(set(identities)) == len(identities), 'policy inventory count/uniqueness' + assert all(re.fullmatch('[0-9a-f]{64}', identity) for identity in identities), 'policy inventory identities' + runtime = {} + for identity in identities: + container = inspect(identity) + assert container['Id'] == identity, 'policy inventory inspection raced' + name = container['Name'] + assert name.startswith('/') and re.fullmatch('[A-Za-z0-9_.-]{1,128}', name[1:]), 'policy container name' + name = name[1:] + assert name not in runtime, 'policy duplicate container name' + state = container['State'] + assert type(state['Running']) is bool and isinstance(state['StartedAt'], str) and len(state['StartedAt']) <= 64, 'policy runtime state' + runtime[name] = {'id': identity, 'image': container['Image'], + 'running': state['Running'], 'started': state['StartedAt']} + assert all(runtime.get(name, {}).get('running') is True for name in ('ipmi-monitor', 'cryptolabs-proxy')), 'policy application runtime unavailable' + path = self.store.root / 'broker/policy-state.json' + policy = None + if path.exists(): + data = path.read_bytes() + assert len(data) <= 65536, 'policy intent byte bound' + policy = digest(data) + return {'selection': current.selection_sha256, 'policy': policy, 'runtime': runtime, + 'unrelated': {'manifest': copy.deepcopy({name: value for name, value in current.manifest.data['components'].items() if name != 'ipmi-monitor'}), + 'selection': copy.deepcopy({name: value for name, value in current.selection['components'].items() if name != 'ipmi-monitor'})}} + + def policy_listing(self): + response = self.http('GET', '/api/releases/policies') + assert response.status_code == 200, 'native policy listing refused' + value = response.json() + assert isinstance(value, dict) and isinstance(value.get('components'), dict), 'native policy listing shape' + assert value['components']['ipmi-monitor']['supported'] is True, 'native IPMI policy unsupported' + return value + + def policy_set_mode(self, mode): + assert mode in ('pinned', 'follow-stable'), 'native policy mode' + current = self.policy_listing() + response = self.http('POST', '/api/releases/policy-set', body={ + 'component': 'ipmi-monitor', 'mode': mode, + 'expected_selection_id': current['selection_id'], + 'expected_selection_sha256': current['selection_sha256']}) + assert response.status_code == 200, 'native policy mode mutation refused' + after = self.policy_listing() + assert after['components']['ipmi-monitor']['mode'] == mode, 'native policy mode did not persist' + assert after['selection_id'] != current['selection_id'], 'native policy mutation did not advance CAS' + return after + + def policy_retain_installed_manifest(self, manifest, policies): + installed = copy.deepcopy(manifest) + installed['baseline_id'] = 'native-installed-ipmi' + installed['components']['ipmi-monitor'] = self.component('ipmi-old') + path = self.data / 'installed-baseline.json' + write(path, installed) + prepared = self.store.prepare(path, platform='linux/amd64', policies=policies) + self.store.commit(prepared) + + def policy_discovery_refusals(self): + before = self.policy_state_snapshot() + current = self.policy_listing() + params = {'expected_selection_id': current['selection_id'], + 'expected_selection_sha256': current['selection_sha256']} + signature = ROOT / 'admission/admission-index.sig' + index = ROOT / 'admission/admission-index.json' + original_signature, original_index = signature.read_bytes(), index.read_bytes() + assert original_signature and original_index, 'native discovery fixture absent' + for fault in ('invalid-signature', 'unavailable'): + try: + if fault == 'invalid-signature': + write(signature, bytes([original_signature[0] ^ 1]) + original_signature[1:], 0o644) + else: + index.unlink() + response = self.http('POST', '/api/releases/policy-refresh', body=params) + assert response.status_code == 503, 'native untrusted discovery was accepted' + assert self.policy_state_snapshot() == before, 'native discovery failure changed state' + self.record('native-policy-discovery-refusal', fault=fault, status=503, result='passed') + finally: + write(signature, original_signature, 0o644) + write(index, original_index, 0o644) + assert self.policy_state_snapshot() == before, 'native discovery restore changed state' + + def policy_lock_refusal(self): + import fcntl + current = self.policy_listing() + before = self.policy_state_snapshot() + descriptor = os.open(CONFIG / '.lifecycle-config.lock', os.O_RDONLY | os.O_NOFOLLOW) + try: + info = os.fstat(descriptor) + assert stat.S_ISREG(info.st_mode) and info.st_uid == 0 and info.st_nlink == 1 and stat.S_IMODE(info.st_mode) == 0o600, 'native policy lock custody' + fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB) + response = self.http('POST', '/api/releases/policy-set', body={ + 'component': 'ipmi-monitor', 'mode': 'pinned', + 'expected_selection_id': current['selection_id'], + 'expected_selection_sha256': current['selection_sha256']}) + assert response.status_code == 409, 'native lifecycle lock was bypassed' + assert self.policy_state_snapshot() == before, 'native busy policy mutation changed state' + finally: + os.close(descriptor) + self.record('native-policy-kernel-lock', result='passed', status=409) + +# TRACEWEAVER: entrypoint=policy_cas_race; req=REQ-AUTOADVANCE-008; trace=TRACE-AUTOADVANCE-008; ver=VER-AUTOADVANCE-008 + def policy_cas_race(self, current): + import requests + from concurrent.futures import ThreadPoolExecutor + barrier = threading.Barrier(2) + expected = {'expected_selection_id': current['selection_id'], + 'expected_selection_sha256': current['selection_sha256']} + clients = [] + try: + for _ in range(2): + client = requests.Session() + clients.append(client) + client.cookies.update(self.session.cookies) + client.verify = self.session.verify + def competing(role, client): + session = client.get(ORIGIN + '/api/releases/session', timeout=15) + assert session.status_code == 200, 'native race session unavailable' + token = session.json()['csrf_token'] + assert isinstance(token, str) and 0 < len(token) <= 512, 'native race CSRF shape' + body = dict(expected) + path = '/api/releases/policy-refresh' + if role == 'pin': + body.update(component='ipmi-monitor', mode='pinned') + path = '/api/releases/policy-set' + barrier.wait(timeout=10) + response = client.request('POST', ORIGIN + path, json=body, + headers={'Origin': ORIGIN, 'X-CSRF-Token': token}, timeout=15) + return response.status_code + with ThreadPoolExecutor(max_workers=2) as pool: + futures = [pool.submit(competing, role, client) for role, client in zip(('pin', 'refresh'), clients)] + statuses = [future.result(timeout=45) for future in futures] + assert sorted(statuses) == [200, 409], 'native policy race did not establish one CAS winner' + winner = 'pin' if statuses[0] == 200 else 'refresh' + self.record('native-policy-cas-race', result='passed', winner=winner, + pin_status=statuses[0], refresh_status=statuses[1]) + return winner + finally: + for client in clients: + client.close() + + def _policy_timer_files(self): + files = {} + for name in POLICY_REFRESH_UNITS: + path = POLICY_REFRESH_SYSTEMD / name + before = os.lstat(path) + assert stat.S_ISREG(before.st_mode) and before.st_uid == before.st_gid == 0 and before.st_nlink == 1 and stat.S_IMODE(before.st_mode) == 0o600, 'native refresh unit custody' + descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + try: + info = os.fstat(descriptor) + assert (info.st_dev, info.st_ino) == (before.st_dev, before.st_ino), 'native refresh unit open raced' + raw = os.read(descriptor, 65537) + assert len(raw) <= 65536, 'native refresh unit size' + after = os.lstat(path) + assert (after.st_dev, after.st_ino) == (info.st_dev, info.st_ino), 'native refresh unit path raced' + files[str(path)] = {'sha256': digest(raw), 'device': info.st_dev, 'inode': info.st_ino} + finally: + os.close(descriptor) + return {'files': files} + +# TRACEWEAVER: entrypoint=policy_timer_quiesce; req=REQ-AUTOADVANCE-008; trace=TRACE-AUTOADVANCE-008; ver=VER-AUTOADVANCE-008 + def policy_timer_quiesce(self): + if not getattr(self, 'policy_timer_attempted', False): + return + self.policy_timer_quiesced = False + record = getattr(self, 'policy_timer_record', None) + assert record is not None and self._policy_timer_files() == record, 'native refresh unit ownership unproven' + service, timer = POLICY_REFRESH_UNITS + run('systemctl', 'disable', '--now', timer) + run('systemctl', 'stop', service) + for name in (timer, service): + state = run('systemctl', 'is-active', name, check=False).stdout.strip() + assert state in (b'inactive', b'failed'), 'native refresh unit did not quiesce' + enabled = run('systemctl', 'is-enabled', timer, check=False).stdout.strip() + assert enabled == b'disabled', 'native refresh timer remains enabled' + self.policy_timer_quiesced = True + +# TRACEWEAVER: entrypoint=policy_timer_prepare; req=REQ-AUTOADVANCE-008; trace=TRACE-AUTOADVANCE-008; ver=VER-AUTOADVANCE-008 + def policy_timer_prepare(self): + assert self.policy_listing()['components']['ipmi-monitor']['mode'] == 'pinned', 'native Persistent timer must be enabled while pinned' + before = self.policy_state_snapshot() + paths = [POLICY_REFRESH_SYSTEMD / name for name in POLICY_REFRESH_UNITS] + if getattr(self, 'policy_timer_attempted', False): + assert self._policy_timer_files() == self.policy_timer_record, 'native prior refresh ownership changed' + else: + assert all(not path.exists() and not path.is_symlink() for path in paths), 'native refresh unit collision' + cli = str(Path(sys.executable).parent / 'dc-overview') + templates = self.args.dc_source / 'src/dc_overview/templates/systemd' + expected = {str(path): digest((templates / path.name).read_text().replace('@RELEASE_CLI@', cli).encode()) for path in paths} + self.policy_timer_attempted = True + self.policy_timer_record = None + self.policy_timer_quiesced = False + run(cli, 'release', 'policy-install-timer', timeout=60) + record = self._policy_timer_files() + assert {path: value['sha256'] for path, value in record['files'].items()} == expected, 'native installed refresh template mismatch' + self.policy_timer_record = record + for path in paths: + if path not in self.units: + self.units.append(path) + response = run('systemctl', 'show', POLICY_REFRESH_UNITS[1], + '--property=ActiveState,UnitFileState,Persistent,NextElapseUSecRealtime') + properties = dict(line.split('=', 1) for line in response.stdout.decode().splitlines()) + assert properties.get('ActiveState') == 'active' and properties.get('UnitFileState') == 'enabled' and properties.get('Persistent') == 'yes', 'native daily timer configuration' + assert properties.get('NextElapseUSecRealtime') not in (None, '', 'n/a', '0'), 'native daily timer lacks next event' + assert self.policy_state_snapshot() == before, 'native Persistent catch-up changed a pin' + self.policy_timer_quiesce() + self.record('native-policy-daily-timer', result='passed', persistent=True, + configured_daily=True, elapsed_daily_trigger=False, catch_up_control='pinned then quiesced') + +# TRACEWEAVER: entrypoint=policy_timer_refresh; req=REQ-AUTOADVANCE-008; trace=TRACE-AUTOADVANCE-008; ver=VER-AUTOADVANCE-008 + def policy_timer_refresh(self): + self.policy_timer_quiesce() + service = POLICY_REFRESH_UNITS[0] + self.policy_timer_quiesced = False + run('systemctl', 'start', service, timeout=60) + response = run('systemctl', 'show', service, + '--property=Id,ActiveState,SubState,MainPID,Result,ExecMainStatus') + properties = dict(line.split('=', 1) for line in response.stdout.decode().splitlines()) + expected = {'Id': service, 'ActiveState': 'inactive', 'SubState': 'dead', + 'MainPID': '0', 'Result': 'success', 'ExecMainStatus': '0'} + assert all(properties.get(name) == value for name, value in expected.items()), 'native packaged refresh command did not complete' + self.policy_timer_quiesced = True + self.record('native-policy-packaged-refresh', result='passed', command='fixed systemd oneshot', browser_refresh=False) + +# TRACEWEAVER: entrypoint=policy_timer_remove; req=REQ-AUTOADVANCE-008; trace=TRACE-AUTOADVANCE-008; ver=VER-AUTOADVANCE-008 + def policy_timer_remove(self): + paths = [POLICY_REFRESH_SYSTEMD / name for name in POLICY_REFRESH_UNITS] + if not getattr(self, 'policy_timer_attempted', False): + assert not any(path in self.units for path in paths), 'untracked native refresh files' + return + assert getattr(self, 'policy_timer_quiesced', False) is True, 'native refresh quiescence is unproven' + record = getattr(self, 'policy_timer_record', None) + assert record is not None and self._policy_timer_files() == record, 'native refresh removal custody changed' + for path in paths: + path.unlink() + +# TRACEWEAVER: entrypoint=policy_before_update; req=REQ-AUTOADVANCE-008; trace=TRACE-AUTOADVANCE-008; ver=VER-AUTOADVANCE-008 + def policy_before_update(self): + assert self.policy_installed_version('ipmi-old') == IPMI_POLICY_PROOFS['ipmi-old']['version'], 'native policy original version' + baseline = self.policy_state_snapshot() + def preserved(): + current = self.policy_state_snapshot() + assert current['runtime'] == baseline['runtime'] and current['unrelated'] == baseline['unrelated'], 'native policy changed runtime or unrelated scope' + pinned = self.policy_set_mode('pinned') + assert pinned['components']['ipmi-monitor']['selected_release'] == '1.3.1', 'native pin did not bind installed version' + preserved() + self.policy_set_mode('follow-stable') + run('systemctl', 'restart', SERVICE) + durable = self.policy_listing()['components']['ipmi-monitor'] + assert (durable['mode'], durable['installed_release'], durable['selected_release']) == ('follow-stable', '1.3.1', '1.3.1'), 'native policy restart persistence' + preserved() + self.policy_discovery_refusals() + self.policy_lock_refusal() + winner = self.policy_cas_race(self.policy_listing()) + observed = self.policy_listing()['components']['ipmi-monitor'] + assert (observed['mode'], observed['selected_release']) == (('pinned', '1.3.1') if winner == 'pin' else ('follow-stable', '1.3.3')), 'native policy race outcome incoherent' + preserved() + self.policy_set_mode('pinned') + self.policy_timer_prepare() + self.policy_set_mode('follow-stable') + assert self.policy_listing()['components']['ipmi-monitor']['selected_release'] == '1.3.1', 'native refresh advanced before explicit oneshot' + self.policy_timer_refresh() + selected = self.policy_listing()['components']['ipmi-monitor'] + assert (selected['mode'], selected['installed_release'], selected['selected_release']) == ('follow-stable', '1.3.1', '1.3.3'), 'native stable selection did not advance independently of install' + preserved() + self.record('native-policy-follow-before-manual-update', result='passed', layout=self.layout, + installed='1.3.1', selected='1.3.3', runtime_unchanged=True, unrelated_pins_unchanged=True) + +# TRACEWEAVER: entrypoint=policy_after_update; req=REQ-AUTOADVANCE-008; trace=TRACE-AUTOADVANCE-008; ver=VER-AUTOADVANCE-008 + def policy_after_update(self): + assert self.policy_installed_version('ipmi-new') == IPMI_POLICY_PROOFS['ipmi-new']['version'], 'native policy upgraded package version' + before = self.policy_state_snapshot() + pinned = self.policy_set_mode('pinned')['components']['ipmi-monitor'] + assert (pinned['mode'], pinned['installed_release'], pinned['selected_release']) == ('pinned', '1.3.3', '1.3.3'), 'native repin did not bind actual upgraded image' + frozen = self.policy_state_snapshot() + assert frozen['runtime'] == before['runtime'] and frozen['unrelated'] == before['unrelated'], 'native repin changed unrelated runtime or pins' + self.policy_timer_refresh() + assert self.policy_state_snapshot() == frozen, 'native pinned selection advanced after packaged refresh' + assert self.policy_listing()['components']['ipmi-monitor']['mode'] == 'pinned', 'native repin did not survive reload' + self.record('native-policy-repin-after-manual-update', result='passed', layout=self.layout, + installed='1.3.3', selected='1.3.3', next_refresh='pinned unchanged') + def component(self, key): return { "owner": "proxy-updater", - "release": "native-" + key, + "release": IPMI_POLICY_PROOFS[key]["version"] if key in IPMI_POLICY_PROOFS else "native-" + key, "artifacts": {"linux/amd64": {"kind": "oci", "reference": self.refs[key]}}, } @@ -1618,25 +4290,65 @@ def apply(self, params, preview, *, lose_reply=False): def status(self, identity): value = raw_request("status", {"operation_id": identity}) + observed = getattr(self, '_adoption_finish_observation', None) + if type(observed) is dict: + observed['status_ok'] = value.get('ok') if type(value.get('ok')) is bool else None + if not value.get('ok'): + observed['finish_branch'] = 'status-rejected' if not value.get("ok"): raise RuntimeError("installed status unavailable") return value["result"] - def finish(self, identity, states=("completed",)): + def finish(self, identity, states=("completed",), *, adoption_expected=None): + observed = None + previous = getattr(self, '_adoption_finish_observation', None) + if adoption_expected is not None and self.layout == 'named-volume': + observed = {'finish_branch': 'waiting', 'status_ok': None, 'owner_state': 'unknown', + 'status_error_kind': 'unknown'} + self._adoption_finish_observation = observed def final(): - value = self.status(identity) + if observed is not None: + observed.update(finish_branch='status-call', status_ok=None, status_error_kind='unknown', owner_state='unknown') + try: + value = self.status(identity) + except Exception as error: + if observed is not None: + observed['status_error_kind'] = _diagnostic_error_kind(error) + raise + if observed is not None: + state = value.get('state') if type(value) is dict else None + observed['owner_state'] = state if type(state) is str and state in ( + 'prepared', 'selecting', 'pending-submit', 'updating', 'adopting', + 'completed', 'failed-restored', 'recovery-required', 'selection-conflict') else 'unknown' + observed['finish_branch'] = 'waiting' if value["state"] in ( "completed", "failed-restored", "recovery-required", "selection-conflict", ): + if observed is not None: + observed['finish_branch'] = 'terminal-state' if value["state"] not in states: raise RuntimeError("owner operation held: " + value["state"]) return value return None - return wait(final, timeout=420, message="actual owner operation did not finish") + try: + return wait(final, timeout=420, message="actual owner operation did not finish") + except Exception as error: + if observed is not None: + try: + projection = self.proxy_adoption_observation(identity, adoption_expected) + packet = {**observed, 'error_kind': _diagnostic_error_kind(error), 'operation': projection} + if len(encoded(packet)) <= 4096: + self.record('proxy-adoption-observation', **packet) + except Exception: + pass + raise + finally: + if observed is not None: + self._adoption_finish_observation = previous def wait_mapped_worker(self, mapped): job_id = mapped["job_id"] @@ -1679,13 +4391,25 @@ def launched(): def service_update(self): before_proxy = inspect("cryptolabs-proxy")["Id"] - old = self.selection() self.policy["writes_enabled"] = True write(POLICY, self.policy) + self.policy_before_update() + old = self.selection() params, p = self.preview("ipmi-new") identity, body = self.apply(params, p, lose_reply=True) + # Captured request/preview identities are independent of the later file + # read. The stored actor subject/fingerprint remain producer/custody-bound. + self.owner_mapping_expected = {'apply': dict(body), 'request': dict(params), 'preview': dict(p)} mapping = self.jobs / "operations" / (identity + ".json") - wait(mapping.exists, timeout=90, message="actual owner mapping was not created") + try: + wait(mapping.exists, timeout=90, message="actual owner mapping was not created") + except Exception: + try: + self.record('owner-mapping-observation', layout=self.layout, + operation_id=identity, **self.owner_mapping_observation(identity)) + except Exception: + pass + raise mapped = json.loads(mapping.read_bytes()) job_id = mapped["job_id"] self.job_ids.add(job_id) @@ -1694,6 +4418,8 @@ def service_update(self): run("systemctl", "start", SERVICE) self.wait_fresh_broker(old_main) final = self.finish(identity) + if self.layout == 'named-volume': + self.recovery.verify_successor(job_id) replay = self.http("POST", "/api/releases/apply", body=body) assert replay.status_code == 200 and replay.json()["operation_id"] == identity after = json.loads(mapping.read_bytes()) @@ -1731,6 +4457,7 @@ def service_update(self): unscoped_proxy_id=before_proxy, replay="same terminal mapping after dropped HTTPS response and broker restart", ) + self.policy_after_update() # New root floor and live policy disable must prevent a fresh old-generation preview. self.policy["minimum_generation"] = self.generation + 1 write(POLICY, self.policy) @@ -1770,8 +4497,9 @@ def proxy_adopt(self): users = digest((self.auth / "users.json").read_bytes()) params, p = self.preview("proxy-b") assert p["disconnect_expected"] is True - identity, _ = self.apply(params, p) - final = self.finish(identity) + identity, body = self.apply(params, p) + final = self.finish(identity, adoption_expected={'apply': body, 'request': params, 'preview': p} + if self.layout == 'named-volume' else None) assert final["state"] == "completed" after = inspect("cryptolabs-proxy") assert ( @@ -1867,9 +4595,22 @@ def owner_started(): ) def reset_fixture(self): + self.policy_timer_quiesce() self.consume_child_failure() run("systemctl", "stop", SERVICE, check=False) run("systemctl", "stop", SOCKET_UNIT, check=False) + if self.synthetic_ipmi_volume is not None and self.synthetic_ipmi_volume['custody'] is None: + raise RuntimeError('synthetic volume creation custody uncertain; cleanup held') + # Registered before create: a timed-out create may have reached Engine. + # A name alone never authorizes removal; revalidate the full owned record. + for name, expected in list(self.site_initializers.items()): + found = docker("ps", "-aq", "--filter", "name=^/" + name + "$").stdout.split() + if found: + assert len(found) == 1 + value = inspect(found[0].decode()) + self.site_initializer_custody(value, expected) + docker("rm", "-f", value["Id"]) + del self.site_initializers[name] # Only exact helpers created by this fixture's retained operation IDs. for key in self.job_ids: name = "cryptolabs-update-" + key @@ -1898,11 +4639,18 @@ def reset_fixture(self): if value.get("Name") != "/native-fleet-registry": docker("rm", "-f", identity) for name in self.volumes: - docker("volume", "rm", name, check=False) + if self.synthetic_ipmi_volume is not None and name == self.synthetic_ipmi_volume['name']: + assert self.synthetic_ipmi_volume_custody() == self.synthetic_ipmi_volume['custody'] + docker('volume', 'rm', name) # checked, non-force; an attached volume must hold + self.synthetic_ipmi_volume = None + else: + docker("volume", "rm", name, check=False) + assert self.synthetic_ipmi_volume is None self.volumes = [] for name in self.networks: docker("network", "rm", name, check=False) self.networks = [] + self.recovery.reset() shutil.rmtree(CONFIG, ignore_errors=True) shutil.rmtree(PROXY_CONFIG, ignore_errors=True) shutil.rmtree(Path("/etc/systemd/system") / (SERVICE + ".d"), ignore_errors=True) @@ -1920,7 +4668,7 @@ def verify_quiesced(): if docker("ps", "-aq", "--filter", "label=" + self.label).stdout.strip(): raise RuntimeError("fixture consumers remain; cleanup held") if self.units: - for name in (SERVICE, SOCKET_UNIT): + for name in (SERVICE, SOCKET_UNIT) + (POLICY_REFRESH_UNITS if getattr(self, 'policy_timer_attempted', False) else ()): if run("systemctl", "is-active", name, check=False).stdout.strip() not in ( b"inactive", b"failed", @@ -1955,7 +4703,14 @@ def verify_quiesced(): failed = True # Independent fixture cleanup continues. Preserve private custody and referenced # CA on uncertainty, pending the separately required external VM destruction. + try: + self.policy_timer_remove() + except Exception: + failed = True + refresh_paths = {POLICY_REFRESH_SYSTEMD / name for name in POLICY_REFRESH_UNITS} for unit in self.units: + if unit in refresh_paths: + continue # Only fresh paired custody can authorize these removals. try: unit.unlink(missing_ok=True) except Exception: @@ -2007,16 +4762,30 @@ def execute(self): self.record( "native-flow", result="passed", + legacy_bootstrap_layout="named-volume", + old_dc_service_oci=False, + actual_collector_proof=False, + engine_reply_loss_proof=False, production_enablement=False, external_vm_cleanup="parent must independently retain coordinator destruction receipt", ) except Exception as error: failed = True - if isinstance(error, RuntimeError) and str(error) in ( - "native command timed out; native gate held", - "fixture registry push timed out; native gate held", - ): - message = str(error) + # Only owned numeric command facts or exact builtin fixed messages; + # arbitrary exceptions must never supply text or properties here. + try: + command_outcome, _ = command_failure_facts(error) + except Exception: + command_outcome = "unknown" + if command_outcome == "timeout": + message = "native command timed out; native gate held" + elif type(error) is RuntimeError: + arguments = BaseException.args.__get__(error, type(error)) + if (len(arguments) == 1 and type(arguments[0]) is str and arguments[0] in ( + "native command timed out; native gate held", + "fixture registry push timed out; native gate held", + )): + message = arguments[0] diagnostics = {"source_line": None, "error_kind": "unknown"} try: diagnostics = native_phase_failure_metadata(error, phase) @@ -2086,6 +4855,136 @@ def fixture_failure_metadata(error, fixture_code=NativeQA.fixture.__code__): return {"fixture_line": line, "fixture_error_kind": kind} +BOOTSTRAP_STEPS = ( + "legacy-runtime-inspect", "legacy-updater-probe", "legacy-capabilities-probe", + "synthetic-runtime-inspect", "synthetic-db-seed", "synthetic-read-aggregate", + "synthetic-root-custody", "synthetic-protection-helper", "legacy-job-seed", + "compatible-wheel-install", "legacy-owner-rejection", "legacy-reconcile", + "legacy-reconcile-replay", "scoped-select", "proxy-plan", "proxy-adopt", "proxy-health", +) +HELPER_DIAGNOSTIC_CODES = () + + +def bootstrap_step_offsets(code): + """Read fixed lexical markers from original bytecode, never frame locals.""" + markers = [] + previous = None + for instruction in dis.get_instructions(code): + if (instruction.opname == "STORE_FAST" and instruction.argval == "_bootstrap_step" + and previous is not None and previous.opname == "LOAD_CONST" + and type(previous.argval) is str and previous.argval in BOOTSTRAP_STEPS): + markers.append((instruction.offset, previous.argval)) + previous = instruction + return tuple(markers) + + +def helper_code_matches(actual, expected): + if type(actual) is not types.CodeType or type(expected) is not types.CodeType: + return False + for field in ("co_argcount", "co_posonlyargcount", "co_kwonlyargcount", "co_nlocals", + "co_stacksize", "co_flags", "co_code", "co_names", "co_varnames", + "co_filename", "co_name", "co_qualname", "co_firstlineno", "co_linetable", + "co_exceptiontable", "co_freevars", "co_cellvars"): + if getattr(actual, field) != getattr(expected, field): + return False + if len(actual.co_consts) != len(expected.co_consts): + return False + for observed, wanted in zip(actual.co_consts, expected.co_consts): + if type(wanted) is types.CodeType: + if not helper_code_matches(observed, wanted): + return False + elif type(observed) is not type(wanted) or observed != wanted: + return False + return True + + +def capture_helper_diagnostics(helper, source, filename): + """Bind loaded helper code to the exact retained bytes before trusting it.""" + global HELPER_DIAGNOSTIC_CODES + if type(source) is not bytes or digest(source) != PROTECTION_SHA: + return + expected = compile(source, filename, "exec") + entries = [] + def capture(code, need=False): + entries.append((code, need)) + for constant in code.co_consts: + if type(constant) is types.CodeType: + capture(constant) + for code in expected.co_consts: + if type(code) is not types.CodeType: + continue + function = vars(helper).get(code.co_name) + if type(function) is types.FunctionType: + actual = function.__code__ + # Full compiled structure, including nested bodies and coordinates; + # after capture every traceback comparison uses exact `is`. + if helper_code_matches(actual, code): + capture(actual, code.co_name == "need") + HELPER_DIAGNOSTIC_CODES = (*HELPER_DIAGNOSTIC_CODES, *entries)[-128:] + + +def bootstrap_failure_metadata( + error, + codes=tuple( + (function.__code__, label, bootstrap_step_offsets(function.__code__)) + for function, label in ( + (LegacyRecoveryFixture.bootstrap, "legacy-bootstrap"), + (LegacyRecoveryFixture.seed_synthetic_selected_state, "synthetic-seed"), + (LegacyRecoveryFixture.seed_failed_job, "legacy-bootstrap"), + (LegacyRecoveryFixture.install_compatible_host, "legacy-bootstrap"), + (LegacyRecoveryFixture.wheel_mirror, "legacy-bootstrap"), + (LegacyRecoveryFixture.assert_host_versions, "legacy-bootstrap"), + (run, "native-command"), (docker, "native-command"), (inspect, "native-command"), + ) + ), + bootstrap_codes=(LegacyRecoveryFixture.bootstrap.__code__, LegacyRecoveryFixture.seed_synthetic_selected_state.__code__), + command_code=run.__code__, + command_type=NativeCommandFailure, +): + result = {"bootstrap_step": "unknown", "code_label": "unknown", "source_line": None, + "guard_line": None, "error_kind": "unknown", "command_outcome": "unknown", "command_returncode": None, + "scoped_select_diagnostic": "unknown", "scoped_select_inner_diagnostic": inner_unknown()} + frames = [] + frame = BaseException.__traceback__.__get__(error, type(error)) + while frame is not None: + frames.append(frame) + frame = frame.tb_next + if not any(any(frame.tb_frame.f_code is code for code in bootstrap_codes) for frame in frames): + return result + result["command_outcome"] = "none" + helper_line = None + need_seen = False + for frame in frames: + code = frame.tb_frame.f_code + line = frame.tb_lineno + if type(line) is not int or line not in {value for _, _, value in code.co_lines()}: + continue + trusted = next((entry for entry in codes if code is entry[0]), None) + helper = next((entry for entry in HELPER_DIAGNOSTIC_CODES if code is entry[0]), None) + if trusted is not None: + _, label, markers = trusted + for offset, step in markers: + if offset <= frame.tb_lasti: + result["bootstrap_step"] = step + result.update(code_label=label, source_line=line, + error_kind=fixture_failure_metadata(error, code)["fixture_error_kind"]) + elif helper is not None: + if helper[1]: + need_seen = True # Skip need() trampoline; retain its trusted caller. + continue + helper_line = line + result.update(code_label="synthetic-helper", source_line=line, + error_kind=fixture_failure_metadata(error, code)["fixture_error_kind"]) + if need_seen: + result["guard_line"] = helper_line + if type(error) is command_type and any(frame.tb_frame.f_code is command_code for frame in frames): + result["command_outcome"], result["command_returncode"] = command_failure_facts(error) + if result["bootstrap_step"] == "scoped-select": + result["scoped_select_diagnostic"] = scoped_select_failure_fact(error) + result["scoped_select_inner_diagnostic"] = scoped_select_inner_fact(error) + return result + + def native_phase_failure_metadata( error, phase, @@ -2107,7 +5006,13 @@ def native_phase_failure_metadata( if code is None: return {"source_line": None, "error_kind": "unknown"} metadata = fixture_failure_metadata(error, fixture_code=code) - return {"source_line": metadata["fixture_line"], "error_kind": metadata["fixture_error_kind"]} + result = {"source_line": metadata["fixture_line"], "error_kind": metadata["fixture_error_kind"]} + if phase == "fixture": + try: + result["bootstrap_failure"] = bootstrap_failure_metadata(error) + except Exception: + pass # Keep original phase evidence and lifecycle even without inner facts. + return result def inspect_volume(name): @@ -2116,6 +5021,9 @@ def inspect_volume(name): # TRACEWEAVER: entrypoint=main; req=REQ-FLEETUPDATE-001; trace=TRACE-FLEETUPDATE-001; ver=VER-FLEETUPDATE-001 def main(): + if len(sys.argv) >= 5 and sys.argv[1] == '--scoped-select-child': + scoped_select_child(int(sys.argv[2]), json.loads(sys.argv[3]), sys.argv[4:]) + return parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--check-inputs-only", action="store_true") parser.add_argument("--broker-child", action="store_true") @@ -2124,6 +5032,8 @@ def main(): parser.add_argument("--proxy-source", type=Path) parser.add_argument("--proxy-sha") parser.add_argument("--wheel-dir", type=Path) + parser.add_argument("--legacy-wheel-dir", type=Path) + parser.add_argument("--protection-helper", type=Path) parser.add_argument("--evidence-dir", type=Path) args = parser.parse_args() if args.broker_child: @@ -2131,14 +5041,32 @@ def main(): return check_source_pin(args.proxy_sha) if args.check_inputs_only: + check_recovery_inputs(args.proxy_sha) return if any( getattr(args, key) is None - for key in ("dc_source", "dc_sha", "proxy_source", "wheel_dir", "evidence_dir") + for key in ("dc_source", "dc_sha", "proxy_source", "wheel_dir", "evidence_dir", "legacy_wheel_dir", "protection_helper") ): parser.error("exact sources, SHAs, wheel and evidence directories are required") NativeQA(args).execute() if __name__ == "__main__": - main() + _SCOPED_SELECT_DISPATCH_FRAME = sys._getframe() + try: + main() + except BaseException as error: + try: + captured = _SCOPED_SELECT_TRACEBACK + if captured is not None and captured[0] is error: + trace = BaseException.__traceback__.__get__(error, type(error)) + for frame in captured[1]: + if trace is None or trace.tb_frame is not frame: + break + trace = trace.tb_next + else: + if trace is captured[2]: + BaseException.__traceback__.__set__(error, trace) + except BaseException: + pass + raise # The same exception, rendered by the interpreter's current hook. diff --git a/src/dc_overview/cli.py b/src/dc_overview/cli.py index e67f219..9854940 100644 --- a/src/dc_overview/cli.py +++ b/src/dc_overview/cli.py @@ -76,6 +76,21 @@ def release(): """Manage explicit release selections independently of deployment.""" +@release.command('reconcile-service') +@click.option('--service', required=True, type=click.Choice(['ipmi-monitor'])) +@click.option('--job', 'job_id', required=True) +# TRACEWEAVER: entrypoint=release_reconcile_service; req=REQ-FLEETUPDATE-001; trace=TRACE-FLEETUPDATE-001; ver=VER-FLEETUPDATE-001 +def release_reconcile_service(service, job_id): + """Verify an exact failed native job's restored original; no lifecycle change.""" + import json + from .fleet_upgrade import reconcile_service + try: + result = reconcile_service(FleetConfig.load(DOCKER_CONFIG_DIR), service, job_id) + except Exception: + raise click.ClickException('native_service_recovery_required') from None + click.echo(json.dumps(result, sort_keys=True)) + + @release.command('select') @click.option('--release-manifest', required=True, type=click.Path(exists=True, dir_okay=False, path_type=Path)) @click.option('--component', 'components', multiple=True, required=True, help='Explicit installed proxy-updater component; repeat for each target.') @@ -122,6 +137,48 @@ def release_candidates(channel): _release_request('list', {'channel': channel}) +@release.command('policies') +def release_policies(): + """Show pinned/follow-stable intent independently of installed versions.""" + _release_request('policy-list', {}) + + +@release.command('policy-set') +@click.option('--component', required=True) +@click.option('--mode', type=click.Choice(['pinned', 'follow-stable']), required=True) +@click.option('--expected-selection-id', required=True) +@click.option('--expected-selection-sha256', required=True) +def release_policy_set(component, mode, expected_selection_id, expected_selection_sha256): + """Change one service policy without installing or restarting it.""" + _release_request('policy-set', dict(component=component, mode=mode, + expected_selection_id=expected_selection_id, expected_selection_sha256=expected_selection_sha256)) + + +@release.command('policy-refresh') +# TRACEWEAVER: entrypoint=release_policy_refresh; req=REQ-AUTOADVANCE-004; trace=TRACE-AUTOADVANCE-004; ver=VER-AUTOADVANCE-004 +def release_policy_refresh(): + """Advance opted-in stable selections only; never install updates.""" + from .release_broker_service import request + import json + try: + current = request('policy-list', {}) + result = request('policy-refresh', {'expected_selection_id': current['selection_id'], + 'expected_selection_sha256': current['selection_sha256']}) + click.echo(json.dumps(result, sort_keys=True)) + except (ValueError, RuntimeError, OSError, KeyError) as error: + raise click.ClickException(str(error)) from None + + +@release.command('policy-install-timer') +def release_policy_install_timer(): + """Install the packaged daily selection-only check on this host.""" + from .release_policy import install_timer + try: + install_timer() + except (ValueError, RuntimeError, OSError) as error: + raise click.ClickException(str(error)) from None + + @release.command('preview') @click.option('--candidate', 'candidate_ids', multiple=True, required=True) @click.option('--component', 'components', multiple=True, required=True) diff --git a/src/dc_overview/fleet_upgrade.py b/src/dc_overview/fleet_upgrade.py index 62ea61d..1e5be38 100644 --- a/src/dc_overview/fleet_upgrade.py +++ b/src/dc_overview/fleet_upgrade.py @@ -264,9 +264,11 @@ def preflight_release(config, manifest_path=None, *, platform=None, fresh_setup= return plan -def commit_release(config, plan, *, selection_only=False, precommit=None, _locked=False): +def commit_release(config, plan, *, selection_only=False, precommit=None, _locked=False, policy_operation_id=None): from .controller_adoption import ensure_mutation_allowed ensure_mutation_allowed(config.config_dir) + from .release_policy import guard_publication + guard_publication(config, policy_operation_id) public_path = config.config_dir / 'fleet-config.yaml' previous = getattr(config, '_lifecycle_public_snapshot', public_path.read_bytes() if public_path.exists() else b'') with nullcontext() if _locked else config.lifecycle_lock(): @@ -343,6 +345,8 @@ def _scoped_updater_directory(proxy): mounts = [m for m in proxy['Mounts'] if m.get('Destination') == '/data/auth' and m.get('RW') is True] if len(mounts) != 1 or mounts[0].get('Type') not in ('bind', 'volume'): raise ValueError() + if any(m.get('Destination', '').startswith('/data/auth/') for m in proxy['Mounts']): + raise ValueError() source = Path(mounts[0]['Source']) if not source.is_absolute() or not source.is_dir(): raise ValueError() @@ -381,16 +385,21 @@ def _scoped_idle(directory): path = directory / (job_id + '.json') _scoped_private(path) job = _json(path.read_bytes()) - if (job.get('id') != job_id or job.get('state') not in ('completed', 'failed', 'blocked') - or any(r.get('state') == 'recovery_required' for r in job.get('results', {}).values())): + if job.get('id') != job_id or job.get('state') not in ('completed', 'failed', 'blocked'): raise RuntimeError('updater active/recovery work must finish before scoped selection') + from cryptolabs_proxy.updates import service_recovery_dependency, UpdateEngine + try: + service_recovery_dependency(directory, job, UpdateEngine(), require_capability=False) + except Exception: + raise RuntimeError('native_service_recovery_required') from None @contextmanager -def _scoped_updater_guard(directory): +def _scoped_updater_guard(directory, *, predicate=None): """Hold the same inodes/order as dispatch and worker execution; fail busy.""" import fcntl - _scoped_private(directory, directory=True) + directory_before = _scoped_private(directory, directory=True) + predicate = _scoped_idle if predicate is None else predicate descriptors = [] try: for name in ('dispatch.lock', 'operation.lock'): @@ -406,11 +415,14 @@ def _scoped_updater_guard(directory): except BlockingIOError: raise RuntimeError('updater is busy; retry scoped selection after it finishes') from None def check(): + current_directory = _scoped_private(directory, directory=True) + if (current_directory.st_dev, current_directory.st_ino) != (directory_before.st_dev, directory_before.st_ino): + raise RuntimeError('updater store changed during scoped selection') for path, descriptor, before in descriptors: actual = _scoped_private(path) if (before.st_dev, before.st_ino) != (actual.st_dev, actual.st_ino): raise RuntimeError('updater lock changed during scoped selection') - _scoped_idle(directory) + predicate(directory) check() yield check finally: @@ -418,6 +430,107 @@ def check(): os.close(descriptor) +def _require_recovery_root(): + import platform + if os.geteuid() != 0 or platform.system() != 'Linux': + raise RuntimeError('service reconciliation requires local Linux root') + + +@contextmanager +def _recovery_time_limit(): + """The fixed local CLI gets one hard wall-clock budget including IO.""" + import signal + previous = signal.getsignal(signal.SIGALRM) + remaining = signal.getitimer(signal.ITIMER_REAL) + if remaining != (0.0, 0.0): + raise RuntimeError('native_service_recovery_required') + def expired(signum, frame): + raise TimeoutError('native_service_recovery_required') + signal.signal(signal.SIGALRM, expired) + signal.setitimer(signal.ITIMER_REAL, 120) + try: + yield + finally: + signal.setitimer(signal.ITIMER_REAL, 0) + signal.signal(signal.SIGALRM, previous) + + +# TRACEWEAVER: entrypoint=reconcile_service; req=REQ-FLEETUPDATE-001; trace=TRACE-FLEETUPDATE-001; ver=VER-FLEETUPDATE-001 +def reconcile_service(config, service, job_id): + """Bounded fixed host orchestration; never supplied observations or paths.""" + with _recovery_time_limit(): + return _reconcile_service(config, service, job_id) + + +def _reconcile_service(config, service, job_id): + """Record exact original restoration before selecting/adopting a new proxy.""" + from cryptolabs_proxy import update_recovery as recovery + from cryptolabs_proxy import updates + _require_recovery_root() + recovery.require(service == 'ipmi-monitor' and recovery._pattern(job_id, '[0-9a-f]{32}')) + recovery.require(updates.get_capabilities().get('native_service_recovery') == 1) + lifecycle_path = config.config_dir / '.lifecycle-config.lock' + lifecycle_before = _scoped_private(lifecycle_path) + # This host entrypoint deliberately uses the installed observer and does not + # ask the old serving proxy to advertise code it cannot yet contain. + proxy = _scoped_inspect('cryptolabs-proxy') + recovery.require(recovery._pattern(proxy.get('Id'), '[0-9a-f]{64}') and + proxy.get('State', {}).get('Running') is True) + directory = _scoped_updater_directory(proxy) + started = time.monotonic() + with config.lifecycle_lock(): + lifecycle_current = _scoped_private(lifecycle_path) + recovery.require((lifecycle_current.st_dev, lifecycle_current.st_ino) == + (lifecycle_before.st_dev, lifecycle_before.st_ino)) + with recovery.open_existing_directory(directory, root=True) as fd: + initial = os.fstat(fd) + def predicate(path): + lifecycle_current = _scoped_private(lifecycle_path) + recovery.require((lifecycle_current.st_dev, lifecycle_current.st_ino) == + (lifecycle_before.st_dev, lifecycle_before.st_ino)) + recovery.require(time.monotonic() - started <= 120) + recovery.require(not os.path.lexists(path / 'controller-adoption.json')) + current = _scoped_inspect('cryptolabs-proxy') + recovery.require(current['Id'] == proxy['Id'] and current['Image'] == proxy['Image'] and + current.get('State', {}).get('Running') is True and + _scoped_updater_directory(current) == directory) + actual = os.stat(directory, follow_symlinks=False) + recovery.require((actual.st_dev, actual.st_ino) == (initial.st_dev, initial.st_ino)) + with _scoped_updater_guard(directory, predicate=predicate) as check: + job_raw, active_raw = recovery.load_bound_job(fd, job_id) + job = recovery.validate_job(job_raw, job_id) + engine = updates.UpdateEngine() + observation = updates.observe_original(engine, job) + baseline = recovery.discover_baseline(job, engine.inspect('ipmi-monitor'), observation.continuity, + deadline=started + 120) + name = 'service-recovery-' + job_id + '.json' + try: + existing = recovery.read_private(fd, name) + except FileNotFoundError: + existing = None + if existing is None: + receipt = dict(schema_version=1, kind='native-service-original-restored', service=service, + job_id=job_id, job_sha256=recovery.sha256(job_raw), active_sha256=recovery.sha256(active_raw), + selection_id=job['selection_id'], selection_sha256=job['selection_sha256'], + manifest_sha256=job['manifest_sha256'], original_container_id=observation.container_id, + original_image_id=observation.image_id, helper_name=job['helper'], + baseline_receipt_sha256=baseline, continuity=observation.continuity, + outcome='original_restored', verified_at=recovery.datetime.now(recovery.timezone.utc).isoformat().replace('+00:00', 'Z')) + else: + receipt = recovery.validate_original_restored(job_raw, existing, observation) + recovery.require(receipt['baseline_receipt_sha256'] == baseline and + receipt['active_sha256'] == recovery.sha256(active_raw)) + # Final observation and raw/custody CAS immediately before the + # sole durable publication. No status, job or marker writes. + final_observation = updates.observe_original(engine, job) + recovery.validate_original_restored(job_raw, recovery.encoded(receipt), final_observation) + check() + recovery.require(recovery.load_bound_job(fd, job_id) == (job_raw, active_raw)) + recovery.publish_original_restored(fd, receipt) + return {'job_id': job_id, 'service': service, 'outcome': 'original_restored', + 'resolution_available': True, 'reason': 'original_restoration_verified'} + + def _scoped_proxy(config, proxy_id=None): proxy = _scoped_inspect('cryptolabs-proxy') if (not isinstance(proxy.get('Id'), str) or not re.fullmatch('[0-9a-f]{64}', proxy['Id']) @@ -466,7 +579,8 @@ def _scoped_runtime(config, plan, components, source_images, proxy_id=None): # TRACEWEAVER: entrypoint=select_release_components; req=REQ-FLEETUPDATE-001; trace=TRACE-FLEETUPDATE-001; ver=VER-FLEETUPDATE-001 def select_release_components(config, manifest_path, components, *, record_cli=False, adopt_existing_selection=False, source_images=(), platform=None, - expected_selection_id=None, expected_selection_sha256=None, operation_id=None): + expected_selection_id=None, expected_selection_sha256=None, operation_id=None, + policy_updates=None, precommit_check=None, postcommit=None): """Select explicit installed roles, preserving all other roles and intent.""" from .controller_adoption import ensure_mutation_allowed from .release_catalog import COMPONENTS, Manifest, artifact_identity, _require_root @@ -475,6 +589,11 @@ def select_release_components(config, manifest_path, components, *, record_cli=F if (not components or len(set(components)) != len(components) or any(name not in COMPONENTS or COMPONENTS[name][0] != 'proxy-updater' for name in components)): raise ValueError('scoped selection requires explicit unique proxy-updater components') + policy_updates = {} if policy_updates is None else policy_updates + if not isinstance(policy_updates, dict) or set(policy_updates) - set(components): + raise ValueError('policy changes require an explicit component scope') + from .release_policy import guard_publication + guard_publication(config, operation_id if policy_updates else None) expected_sources = {} for entry in source_images: if not isinstance(entry, str) or '=' not in entry: @@ -570,6 +689,12 @@ def select_release_components(config, manifest_path, components, *, record_cli=F if artifact is None: raise ValueError('missing scoped artifact platform') policy[name]['pin'] = artifact_identity(artifact) + for name, update in policy_updates.items(): + if (not isinstance(update, dict) or set(update) not in ({'origin', 'enabled'}, {'origin', 'enabled', 'pin'}) + or update.get('enabled') is not policy[name]['enabled'] + or update.get('origin') not in ('baseline', 'customer-pin')): + raise ValueError('policy update must preserve enabled service ownership') + policy[name] = copy.deepcopy(update) plan = store.prepare(manifest_path, platform=previous.platform, policies=policy, enabled_components=()) if plan.manifest.raw != manifest.raw: raise RuntimeError('manifest changed during scoped preparation') @@ -585,8 +710,13 @@ def precommit(): raise RuntimeError('scoped runtime changed during selection') if cli_target is not None: verify_running_cli(cli_target) + if precommit_check is not None: + precommit_check() config._release_operation_id = operation_id - commit_release(config, plan, selection_only=True, precommit=precommit, _locked=True) + commit_release(config, plan, selection_only=True, precommit=precommit, _locked=True, + policy_operation_id=operation_id if policy_updates else None) + if postcommit is not None: + postcommit() return {'state': 'pending-deployment', 'scope': list(components), 'tooling_recorded': bool(record_cli), 'reference_adopted': adopting, 'local_only_sources': local_only, 'suite_complete': False, 'selection_id': plan.selection['selection_id'], diff --git a/src/dc_overview/release_broker.py b/src/dc_overview/release_broker.py index 045c24d..47cd709 100644 --- a/src/dc_overview/release_broker.py +++ b/src/dc_overview/release_broker.py @@ -69,6 +69,7 @@ def validate_actor(actor): raise ValueError("invalid authenticated actor") +# TRACEWEAVER: entrypoint=validate_params; req=REQ-AUTOADVANCE-005; trace=TRACE-AUTOADVANCE-005; ver=VER-AUTOADVANCE-005 def validate_params(action, params): fields = { "list": {"channel"}, @@ -88,11 +89,20 @@ def validate_params(action, params): }, "status": {"operation_id"}, "recover": {"operation_id"}, + "policy-list": set(), + "policy-set": {"component", "mode", "expected_selection_id", "expected_selection_sha256"}, + "policy-refresh": {"expected_selection_id", "expected_selection_sha256"}, } if action not in fields or not isinstance(params, dict) or set(params) != fields[action]: raise ValueError("invalid release request fields") for key, value in params.items(): - if key in ("components", "candidate_ids"): + if key == "component": + if not isinstance(value, str) or value not in catalog.COMPONENTS: + raise ValueError("invalid release component") + elif key == "mode": + if value not in ("pinned", "follow-stable"): + raise ValueError("invalid release follow policy") + elif key in ("components", "candidate_ids"): if ( not isinstance(value, list) or not 1 <= len(value) <= 32 @@ -196,6 +206,11 @@ def __init__(self, config, policy): self.config = config self.policy = policy + def installed_component(self, current, name): + from .release_policy import installed_component + from .fleet_upgrade import _scoped_inspect + return installed_component(current, name, catalog.ReleaseStore(self.config.config_dir / "releases"), _scoped_inspect) + def capabilities(self, contract): from cryptolabs_proxy import updates @@ -519,6 +534,10 @@ def dispatch(self, action, params, *, actor): self._reload_policy() validate_actor(actor) validate_params(action, params) + if action in ("policy-list", "policy-set", "policy-refresh"): + from .release_policy import PolicyManager + with self._lock(): + return PolicyManager(self).dispatch(action, params) if action == "list": with self._lock(): candidates = self._candidates() @@ -582,9 +601,13 @@ def dispatch(self, action, params, *, actor): } if action == "preview": with self._lock(): + from .release_policy import guard_publication + guard_publication(self.config) return self._preview(params, actor) if action == "apply": with self._lock(): + from .release_policy import guard_publication + guard_publication(self.config) return self._apply(params, actor) self._ensure() path = self.root / "operations" / (params["operation_id"] + ".json") diff --git a/src/dc_overview/release_policy.py b/src/dc_overview/release_policy.py new file mode 100644 index 0000000..7bb9492 --- /dev/null +++ b/src/dc_overview/release_policy.py @@ -0,0 +1,356 @@ +# TRACEWEAVER: file-role=stable-release-policy; req=REQ-AUTOADVANCE-003; trace=TRACE-AUTOADVANCE-003; ver=VER-AUTOADVANCE-003 +"""Explicit pin/follow intent; candidate selection never installs software.""" +import re +import copy +import json +import os +from pathlib import Path +import subprocess +import sys +import uuid + +from . import release_catalog as catalog +from .release_catalog import COMPONENTS, artifact_identity +from .release_candidates import require_compatible, verify_candidate +from .release_broker import BrokerError, canonical, private_write, sha + + +def guard_publication(config, operation_id=None): + path = config.config_dir / 'releases' / 'broker' / 'policy-publication.json' + if os.path.lexists(path): + from .release_broker import _private + _private(path) + value = catalog._json(path.read_bytes()) + if operation_id is None or value.get('operation_id') != operation_id: + raise BrokerError('recovery-required', 'Reconcile the pending update policy before another release change') + + +def remove_journal(path): + path.unlink() + descriptor = os.open(path.parent, os.O_RDONLY) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + +_VERSION = re.compile(r"v?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?\Z") + + +def stable_version(value): + if not isinstance(value, str) or len(value) > 128: + return None + match = _VERSION.fullmatch(value) + return tuple(int(v) for v in match.groups()) if match else None + + +def supported(name): + return name in COMPONENTS and COMPONENTS[name][0] == "proxy-updater" and name != "cryptolabs-proxy" + + +# TRACEWEAVER: entrypoint=choose_candidate; req=REQ-AUTOADVANCE-003; trace=TRACE-AUTOADVANCE-003; ver=VER-AUTOADVANCE-003 +def choose_candidate(name, selected_release, major, candidates, capabilities, platform): + """Choose only one unambiguous, compatible, admitted stable advancement. + + The broker supplies candidates after signature/revocation/high-water checks. + The selected version is the floor, including a not-yet-installed target. + """ + floor = stable_version(selected_release) + if not supported(name) or type(major) is not int or not floor or floor[0] != major: + return None + eligible = [] + for candidate in candidates: + try: + component = candidate.manifest.data["components"][name] + version = stable_version(component["release"]) + if not version or version[0] != major or version <= floor: + continue + entries = require_compatible([candidate], [name], capabilities, platform, "services-update") + entry = entries[name] + artifact = component["artifacts"].get(platform, component["artifacts"].get("any")) + if (component["owner"] != COMPONENTS[name][0] or entry["channel"] != "main" + or artifact is None or artifact_identity(artifact) != entry["identity"]): + continue + eligible.append((version, entry["identity"], candidate)) + except (KeyError, ValueError, TypeError): + continue + if not eligible: + return None + newest = max(value[0] for value in eligible) + choices = [value for value in eligible if value[0] == newest] + if len({value[1] for value in choices}) != 1: + return None + return choices[0][2] + + +def installed_component(current, name, store, inspect): + """Bind a running immutable image to retained, root-custodied release bytes.""" + if not supported(name): + return None + try: + live = inspect(name) + if live.get("State", {}).get("Running") is not True: + return None + image = inspect(live["Image"]) + if image.get("Id") != live["Image"] or image.get("Os", "") + "/" + image.get("Architecture", "") != current.platform: + return None + references = image.get("RepoDigests") + if not isinstance(references, list): + return None + known = [current.manifest] + paths = list((store.root / "manifests").glob("*.json")) + if len(paths) > 1024: + return None + for path in paths: + if not catalog.HEX.fullmatch(path.stem): + continue + catalog._check_root_path(path) + if path.stat().st_size > 1024 * 1024: + return None + raw = path.read_bytes() + if sha(raw) != path.stem: + return None + known.append(catalog.Manifest.from_bytes(raw)) + matches = [] + for manifest in known: + item = manifest.data["components"].get(name) + if not item or item["owner"] != COMPONENTS[name][0] or not stable_version(item["release"]): + continue + artifact = item["artifacts"].get(current.platform) + if artifact and artifact_identity(artifact) in references: + matches.append(item) + if not matches or len({stable_version(item["release"]) for item in matches}) != 1: + return None + item = matches[0] + labels = image.get("Config", {}).get("Labels") or {} + declared = labels.get("org.opencontainers.image.version") + if declared and stable_version(declared) and stable_version(declared) != stable_version(item["release"]): + return None + again = inspect(name) + if any(again.get(k) != live.get(k) for k in ("Id", "Image")) or again.get("State", {}).get("Running") is not True: + return None + return copy.deepcopy(item) + except (OSError, RuntimeError, ValueError, KeyError, TypeError): + return None + + +class PolicyManager: + """Selection-only operations under the broker's dispatch lock. + + Every mode mutation also changes selection identity. A private forward + recovery record joins policy intent to the existing selection/public-config + transaction. No method submits an update or creates/restarts a container. + """ + def __init__(self, broker): + self.broker = broker + self.store = broker.store + self.path = broker.root / "policy-state.json" + self.journal = broker.root / "policy-publication.json" + + def _state(self): + value = self.broker._read(self.path) if self.path.exists() else {"schema_version": 1, "components": {}} + if not isinstance(value, dict) or set(value) != {"schema_version", "components"} or type(value["schema_version"]) is not int or value["schema_version"] != 1: + raise BrokerError("policy-unavailable", "Installed update policy is invalid", 503) + if not isinstance(value["components"], dict) or len(value["components"]) > len(COMPONENTS): + raise BrokerError("policy-unavailable", "Installed update policy is invalid", 503) + for name, item in value["components"].items(): + if (not supported(name) or not isinstance(item, dict) or set(item) != {"mode", "major"} + or item["mode"] not in ("pinned", "follow-stable") + or (item["mode"] == "pinned" and item["major"] is not None) + or (item["mode"] == "follow-stable" and (type(item["major"]) is not int or item["major"] < 0))): + raise BrokerError("policy-unavailable", "Installed update policy is invalid", 503) + return value + + def _recover(self): + if not self.journal.exists(): + return + if self.broker.policy.get("writes_enabled") is not True: + raise BrokerError("recovery-required", "Update policy publication needs its installed owner", 503) + record = self.broker._read(self.journal) + if (not isinstance(record, dict) or set(record) != {"before_selection", "after_selection", "before_policy", "after_policy", "operation_id"} + or any(not isinstance(record[k], str) or not catalog.HEX.fullmatch(record[k]) for k in ("before_selection", "after_selection"))): + raise BrokerError("recovery-required", "Update policy recovery record is invalid", 503) + from .fleet_upgrade import reconcile_release_operation + reconcile_release_operation(self.broker.config, record["operation_id"]) + current = self.store.load() + policy = self._state() + if policy not in (record["before_policy"], record["after_policy"]): + raise BrokerError("recovery-required", "Update policy changed during publication", 409) + if current.selection_sha256 == record["after_selection"]: + import yaml + public = yaml.safe_load((self.broker.config.config_dir / "fleet-config.yaml").read_bytes()) + if public.get("release_selection", {}).get("selection_sha256") != current.selection_sha256: + raise BrokerError("recovery-required", "Release public reference must be reconciled first", 409) + private_write(self.path, record["after_policy"]) + elif current.selection_sha256 == record["before_selection"] and policy == record["before_policy"]: + pass + else: + raise BrokerError("recovery-required", "Release selection changed during policy publication", 409) + remove_journal(self.journal) + + def _mutable(self): + if self.broker.policy.get("writes_enabled") is not True: + raise BrokerError("disabled", "Release writes are disabled", 503) + for path in (self.broker.root / "operations").glob("*.json"): + from .release_broker import TERMINAL + if self.broker._read(path)["state"] not in TERMINAL: + raise BrokerError("busy", "Reconcile the existing release operation first") + + def listing(self, current=None, state=None): + current = current or self.store.load() + state = state or self._state() + components = {} + for name, selected in current.selection["components"].items(): + enabled = supported(name) and selected["enabled"] and name in current.targets + installed = self.broker.owner.installed_component(current, name) if enabled else None + intent = state["components"].get(name, {"mode": "pinned", "major": None}) + components[name] = {**intent, "supported": bool(enabled and installed), + "installed_release": installed["release"] if installed else None, + "selected_release": current.manifest.data["components"][name]["release"], + "reason": None if enabled and installed else "Installed release identity unavailable" if enabled else "Managed by its existing lifecycle owner"} + return {"selection_id": current.selection["selection_id"], "selection_sha256": current.selection_sha256, + "components": components, "writes_enabled": self.broker.policy.get("writes_enabled") is True} + +# TRACEWEAVER: entrypoint=dispatch; req=REQ-AUTOADVANCE-002; trace=TRACE-AUTOADVANCE-002; ver=VER-AUTOADVANCE-002 + def dispatch(self, action, params): + self._recover() + current = self.store.load() + state = self._state() + if action == "policy-list": + return self.listing(current, state) + self._mutable() + self.broker._check_expected(current, params) + if action == "policy-set": + name = params["component"] + if not supported(name) or name not in current.targets: + raise BrokerError("unsupported", "This service retains its existing lifecycle owner", 400) + installed = self.broker.owner.installed_component(current, name) + if installed is None or stable_version(installed["release"]) is None: + raise BrokerError("installed-unverified", "Installed immutable release identity is unavailable", 409) + after = copy.deepcopy(state) + mode = params["mode"] + after["components"][name] = {"mode": mode, "major": stable_version(installed["release"])[0] if mode == "follow-stable" else None} + component = installed if mode == "pinned" else current.manifest.data["components"][name] + policy = {"origin": "customer-pin" if mode == "pinned" else "baseline", "enabled": True} + if mode == "pinned": + policy["pin"] = artifact_identity(component["artifacts"][current.platform]) + self._publish(current, state, after, {name: component}, {name: policy}, installed_proofs={name: installed}) + return self.listing() + following = {n: item for n, item in state["components"].items() if item["mode"] == "follow-stable" and n in current.targets} + if not following: + return {**self.listing(current, state), "advanced": [], "reasons": {}} + try: + candidates = list(self.broker._candidates().values()) + capabilities = self.broker.owner.capabilities(max(c.manifest.data["selection_contract"] for c in candidates)) + except (ValueError, OSError, RuntimeError) as error: + if isinstance(error, BrokerError): + raise + raise BrokerError("unavailable", "Verified stable discovery is unavailable", 503) from None + changes, reasons, proofs, installed_proofs = {}, {}, [], {} + after = copy.deepcopy(state) + for name, intent in following.items(): + installed = self.broker.owner.installed_component(current, name) + version = stable_version(installed['release']) if installed else None + if version is None: + reasons[name] = 'Installed immutable release identity is unavailable' + continue + installed_proofs[name] = installed + major = version[0] + after['components'][name]['major'] = major + chosen = choose_candidate(name, current.manifest.data["components"][name]["release"], major, candidates, capabilities, current.platform) + if chosen is None: + reasons[name] = "No newer compatible stable release within the installed major version" + else: + changes[name] = chosen.manifest.data["components"][name] + proofs.append(chosen) + advanced = sorted(changes) + for name in following: + if after['components'][name] != state['components'][name] and name not in changes: + changes[name] = current.manifest.data['components'][name] + if changes: + self._publish(current, state, after, changes, {n: {"origin": "baseline", "enabled": True} for n in changes}, proofs=proofs, installed_proofs=installed_proofs) + return {**self.listing(), "advanced": advanced, "reasons": reasons} + + def _publish(self, current, before, after, changes, policies, proofs=(), installed_proofs=None): + data = copy.deepcopy(current.manifest.data) + data["baseline_id"] = "policy-" + uuid.uuid4().hex + for name, component in changes.items(): + data["components"][name] = copy.deepcopy(component) + if name in data.get('component_channels', {}): + data['component_channels'][name] = 'main' + manifest = catalog.Manifest.from_bytes(canonical(data)) + chosen = copy.deepcopy(current.selection["components"]) + chosen.update(policies) + selection = {"schema_version": 1, "selection_id": data["baseline_id"], "manifest_sha256": manifest.sha256, "components": chosen} + raw = canonical(selection) + b"\n" + operation = str(uuid.uuid4()) + record = {"before_selection": current.selection_sha256, "after_selection": sha(raw), + "before_policy": before, "after_policy": after, "operation_id": operation} + path = self.broker.root / "policy-candidate.json" + private_write(path, data) + from .fleet_upgrade import select_release_components + def precommit(): + self.broker._reload_policy() + self._mutable() + if self._state() != before: + raise BrokerError('policy-conflict', 'Update policy changed before release publication') + for name, installed in (installed_proofs or {}).items(): + if self.broker.owner.installed_component(current, name) != installed: + raise BrokerError('installed-unverified', 'Installed release changed before policy publication') + if proofs: + watermark = self.broker._read(self.broker.root / 'high-water.json') + for candidate in proofs: + verified = verify_candidate(candidate.manifest_raw, candidate.admission_raw, candidate.signature, + candidate.index_raw, candidate.index_signature, self.broker.policy, + highest_generation=max(watermark['generation'], self.broker.policy['minimum_generation'])) + if verified.index_raw != candidate.index_raw: + raise BrokerError('unavailable', 'Admission changed before release publication', 503) + # The native lifecycle and updater locks are held here. A losing + # CAS never creates an orphan policy journal, and a supported native + # writer cannot replace the installed image across this boundary. + private_write(self.journal, record) + def finish(): + private_write(self.path, after) + remove_journal(self.journal) + try: + select_release_components(self.broker.config, path, tuple(changes), platform=current.platform, + expected_selection_id=current.selection["selection_id"], expected_selection_sha256=current.selection_sha256, + operation_id=operation, policy_updates=policies, precommit_check=precommit, postcommit=finish) + except BaseException as error: + # A native preflight/compensated failure may leave the prior state. + # A committed candidate retains this record for forward recovery. + if (self.store.root / "selection.json").read_bytes() == current.selection_raw and self._state() == before: + if self.journal.exists(): + remove_journal(self.journal) + if isinstance(error, RuntimeError) and not isinstance(error, BrokerError): + raise BrokerError("busy", "Release publication is held; reconcile before retry") from None + raise + + +SYSTEMD_DIR = Path("/etc/systemd/system") + + +def release_cli(): + path = Path(sys.executable).parent / "dc-overview" + if not re.fullmatch(r"/[A-Za-z0-9/_.-]+", str(path)): + raise PermissionError("installed release CLI path is unsupported") + for entry in (path, *path.parents): + info = entry.lstat() + if entry.is_symlink() or info.st_uid != 0 or info.st_mode & 0o022: + raise PermissionError("release timer requires a root-custodied installed CLI") + return str(path) + + +# TRACEWEAVER: entrypoint=install_timer; req=REQ-AUTOADVANCE-004; trace=TRACE-AUTOADVANCE-004; ver=VER-AUTOADVANCE-004 +def install_timer(): + """Install the fixed packaged selection-refresh timer from the installed CLI.""" + catalog._require_root() + cli = release_cli() + SYSTEMD_DIR.mkdir(mode=0o755, parents=True, exist_ok=True) + catalog._check_root_path(SYSTEMD_DIR, directory=True) + templates = Path(__file__).parent / "templates" / "systemd" + for suffix in ("service", "timer"): + name = "dc-overview-release-refresh." + suffix + raw = (templates / name).read_text().replace("@RELEASE_CLI@", cli).encode() + catalog._atomic_write(SYSTEMD_DIR / name, raw) + subprocess.run(["systemctl", "daemon-reload"], check=True, timeout=30) + subprocess.run(["systemctl", "enable", "--now", "dc-overview-release-refresh.timer"], check=True, timeout=30) diff --git a/src/dc_overview/templates/systemd/dc-overview-release-refresh.service b/src/dc_overview/templates/systemd/dc-overview-release-refresh.service new file mode 100644 index 0000000..c1c9b8e --- /dev/null +++ b/src/dc_overview/templates/systemd/dc-overview-release-refresh.service @@ -0,0 +1,15 @@ +[Unit] +Description=Advance opted-in verified stable selections without installation +Requires=dc-overview-release-broker.socket +After=dc-overview-release-broker.socket +ConditionPathExists=/etc/dc-overview/releases/broker-policy.json + +[Service] +Type=oneshot +User=root +Group=root +UMask=0077 +ExecStart=@RELEASE_CLI@ release policy-refresh +NoNewPrivileges=true +PrivateTmp=true +ProtectHome=true diff --git a/src/dc_overview/templates/systemd/dc-overview-release-refresh.timer b/src/dc_overview/templates/systemd/dc-overview-release-refresh.timer new file mode 100644 index 0000000..1bff366 --- /dev/null +++ b/src/dc_overview/templates/systemd/dc-overview-release-refresh.timer @@ -0,0 +1,11 @@ +[Unit] +Description=Daily verified stable release selection refresh + +[Timer] +OnCalendar=daily +Persistent=true +RandomizedDelaySec=15m +Unit=dc-overview-release-refresh.service + +[Install] +WantedBy=timers.target diff --git a/tests/test_release_broker.py b/tests/test_release_broker.py index 95d5998..f1efa21 100644 --- a/tests/test_release_broker.py +++ b/tests/test_release_broker.py @@ -4,8 +4,12 @@ """Exercise strict requests and durable operation replay against real selection store.""" import copy +import importlib.util import json +import sys import uuid +from contextlib import nullcontext +from pathlib import Path import pytest from test_release_candidates import admitted as _admitted @@ -200,6 +204,174 @@ def test_durable_lost_response_and_terminal_replay(product): ) +def native_observation_module(): + path = Path(__file__).resolve().parents[1] / "scripts/verify_fleet_release_native.py" + spec = importlib.util.spec_from_file_location("native_broker_observation", path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_handled_owner_failure_retains_correlated_coordinate_without_changing_product(product, monkeypatch, tmp_path): + """Actual producer RED: the handled save succeeds but loses its error coordinate.""" + native = native_observation_module() + host, service, owner, _ = product + schedule = [] + service.schedule = lambda *args: schedule.append(args) + accepted = apply(product, preview(product)) + method_calls = [] + for name in ("capabilities", "identity", "status", "submit"): + original_method = getattr(owner, name) + def observed_method(*args, _name=name, _method=original_method, **kwargs): + method_calls.append(_name) + return _method(*args, **kwargs) + monkeypatch.setattr(owner, name, observed_method) + identity = accepted["operation_id"] + path = service.root / "operations" / (identity + ".json") + prepared = path.read_bytes() + fixture = tmp_path / "diagnostic-fixture" + fixture.mkdir(mode=0o700) + monkeypatch.setattr(native, "ROOT", fixture) + guest = native.NativeQA(type("Args", (), {"evidence_dir": tmp_path / "evidence"})()) + guest.layout = "bind" + original_write = broker.private_write + results = [] + for observed in (False, True): + path.write_bytes(prepared) + owner.mapping.clear() + owner.calls.clear() + method_calls.clear() + # Reuse the real existing lost-response boundary, including its secret text. + owner.fail_response = True + if observed and hasattr(guest, "reset_owner_observation"): + guest.reset_owner_observation() + observer = getattr(native, "observe_broker_owner_failures", None) + # Baseline must reach the real caught save, rather than fail on a missing API. + context = observer(broker, path.parent, (("broker-operation", service.run_operation.__func__.__code__),)) if observed and observer else nullcontext() + with context: + outcome = service.run_operation(identity) + results.append((path.read_bytes(), outcome, list(schedule), list(owner.calls), list(method_calls))) + assert broker.private_write is original_write + assert results[0] == results[1] + retained = json.loads(results[1][0]) + assert retained["state"] == "recovery-required" and retained["phase"] == "owner" + assert retained["reason"] == "Owner operation interrupted; reconcile retained operation before retry" + assert len(schedule) == 1 and owner.calls == [identity] + diagnostic = fixture / "broker-owner-observation.json" + assert diagnostic.is_file(), "real handled owner failure saved only generic reason; correlated coordinate is missing" + raw = diagnostic.read_bytes() + assert len(raw) <= 4096 and b"lost reply after durable updater submit" not in raw + value = json.loads(raw) + assert set(value) == {"schema_version", "operation_id", "failure"} + assert value["schema_version"] == 1 and value["operation_id"] == identity + failure = value["failure"] + assert set(failure) == {"code_label", "source_line", "error_kind"} + assert failure["code_label"] == "broker-operation" and failure["error_kind"] == "os-error" + code = service.run_operation.__func__.__code__ + assert type(failure["source_line"]) is int + assert failure["source_line"] in {line for _, _, line in code.co_lines() if line is not None} + assert guest.read_owner_observation(identity) == failure + + +@pytest.mark.parametrize("original_fails", [False, True]) +def test_owner_observer_preserves_original_write_objects_return_exception_and_binding(product, monkeypatch, tmp_path, original_fails): + native = native_observation_module() + _, service, _, _ = product + accepted = apply(product, preview(product)) + path = service.root / "operations" / (accepted["operation_id"] + ".json") + value = json.loads(path.read_bytes()) + before = path.read_bytes() + original = broker.private_write + sentinel, failure = object(), OSError("PRIVATE_ORIGINAL_WRITE") + calls = [] + def tracked(*args, **kwargs): + calls.append((args, kwargs)) + if original_fails: + raise failure + original(*args, **kwargs) + return sentinel + monkeypatch.setattr(broker, "private_write", tracked) + diagnostic_calls = [] + def diagnostic_failure(*args): + diagnostic_calls.append(args) + raise RuntimeError("PRIVATE_DIAGNOSTIC") + monkeypatch.setattr(native, "write_owner_observation", diagnostic_failure) + with native.observe_broker_owner_failures(broker, path.parent, (("broker-operation", service.run_operation.__func__.__code__),)): + if original_fails: + with pytest.raises(OSError) as caught: + broker.private_write(path, value) + assert caught.value is failure + else: + assert broker.private_write(path, value) is sentinel + assert broker.private_write is tracked + assert len(calls) == 1 and calls[0][0][0] is path and calls[0][0][1] is value + assert calls[0][1] == {} and path.read_bytes() == before + assert diagnostic_calls == [], "outside-handler writes cannot be attributed to an operation failure" + + +@pytest.mark.parametrize("original_save_fails", [False, True]) +def test_real_handled_save_survives_diagnostic_failure(product, monkeypatch, tmp_path, original_save_fails): + native = native_observation_module() + fixture = tmp_path / "observer-fixture" + fixture.mkdir(mode=0o700) + monkeypatch.setattr(native, "ROOT", fixture) + slot = fixture / "broker-owner-observation.json" + slot.touch(mode=0o600) + _, service, owner, _ = product + scheduled = [] + service.schedule = lambda *args: scheduled.append(args) + identity = apply(product, preview(product))["operation_id"] + path = service.root / "operations" / (identity + ".json") + owner.fail_response = True + original = broker.private_write + sentinel = PermissionError("PRIVATE_ORIGINAL_HANDLED_SAVE") + original_calls, caller_arguments, prior = [], [], [] + def eligible(args): + return (args[0] == path and args[1].get("reason") == + "Owner operation interrupted; reconcile retained operation before retry") + def original_boundary(*args, **kwargs): + if eligible(args): + original_calls.append((args, kwargs, sys.exception())) + prior.append(path.read_bytes()) + if original_save_fails: + raise sentinel + return original(*args, **kwargs) + monkeypatch.setattr(broker, "private_write", original_boundary) + diagnostic_calls = [] + def broken(*args): + diagnostic_calls.append(args) + raise OSError("PRIVATE_DIAGNOSTIC_IO") + monkeypatch.setattr(native, "write_owner_observation", broken) + with native.observe_broker_owner_failures(broker, path.parent, (("broker-operation", service.run_operation.__func__.__code__),)): + installed_wrapper = broker.private_write + def caller_boundary(*args, **kwargs): + if eligible(args): + caller_arguments.append((args, kwargs)) + return installed_wrapper(*args, **kwargs) + monkeypatch.setattr(broker, "private_write", caller_boundary) + if original_save_fails: + with pytest.raises(PermissionError) as caught: + service.run_operation(identity) + assert caught.value is sentinel + else: + assert service.run_operation(identity) is None + assert broker.private_write is original_boundary + assert len(original_calls) == len(caller_arguments) == 1 + args, kwargs, active_owner_error = original_calls[0] + assert isinstance(active_owner_error, OSError) and active_owner_error is not sentinel + assert str(active_owner_error) == "lost reply after durable updater submit" + assert args[0] is caller_arguments[0][0][0] and args[1] is caller_arguments[0][0][1] + assert kwargs == caller_arguments[0][1] == {} + assert len(diagnostic_calls) == (0 if original_save_fails else 1) + assert slot.read_bytes() == b"" + if original_save_fails: + assert path.read_bytes() == prior[0] + else: + assert json.loads(path.read_bytes())["reason"] == "Owner operation interrupted; reconcile retained operation before retry" + assert len(scheduled) == 1 + assert owner.calls == [identity] + + def test_selection_cas_and_id_conflict(product): host, service, *_ = product p = preview(product) diff --git a/tests/test_release_policy.py b/tests/test_release_policy.py new file mode 100644 index 0000000..5079e43 --- /dev/null +++ b/tests/test_release_policy.py @@ -0,0 +1,488 @@ +# TRACEWEAVER: file-role=policy-regression; req=REQ-AUTOADVANCE-008; trace=TRACE-AUTOADVANCE-008; ver=VER-AUTOADVANCE-008 +# TRACEWEAVER: verifies=VER-AUTOADVANCE-008; req=REQ-AUTOADVANCE-008; trace=TRACE-AUTOADVANCE-008 +# TRACEWEAVER: file-role=policy-regression; req=REQ-AUTOADVANCE-008; trace=TRACE-AUTOADVANCE-008; ver=VER-AUTOADVANCE-008 +"""Approved C1-C8: policy-only pin/follow changes against the real selection store.""" +import copy +import importlib +import json +from types import SimpleNamespace + +import pytest +import yaml + +from test_release_broker import admitted, product, selected_host +from dc_overview import release_catalog as catalog +from dc_overview import release_candidates + +ACTOR = {"kind": "fleet-admin", "username": "fixture", "subject": "policy-session"} + + +def policy_module(): + return importlib.import_module("dc_overview.release_policy") + + +def candidate(version, *, identity="b", channel="main", platform="linux/amd64"): + component = {"owner": "proxy-updater", "release": version, "artifacts": { + platform: {"kind": "oci", "reference": "grafana/grafana@sha256:" + identity * 64}}} + return SimpleNamespace(candidate_id=version + identity, manifest=SimpleNamespace(data={ + "schema_version": 1, "selection_contract": 1, "baseline_id": "fixture", + "components": {"grafana": component}}), admission={"component_admissions": [{ + "component": "grafana", "channel": channel, "platform": platform, + "identity": component["artifacts"][platform]["reference"], + "required_capabilities": {"release_components": 1}, + "independently_replaceable": True, "dependency_group": []}]}) + + +@pytest.mark.parametrize("version", ["latest", "dev", "1.5.0-rc.1", "01.5.0", "1.5", "2.0.0", "1.3.9"]) +def test_follow_never_chooses_unstable_major_or_downgrade(version): + chosen = policy_module().choose_candidate("grafana", "1.4.0", 1, + [candidate(version)], {"release_components": 1}, "linux/amd64") + assert chosen is None + + +def test_stable_order_is_numeric_not_lexical_and_ignores_dev(): + older, newest = candidate("1.9.0"), candidate("1.10.0") + assert policy_module().choose_candidate("grafana", "1.4.0", 1, + [newest, candidate("1.99.0", channel="dev"), older], + {"release_components": 1}, "linux/amd64") is newest + + +@pytest.mark.parametrize("fault", ["platform", "capability", "dependency", "ambiguous"]) +def test_follow_requires_compatible_unambiguous_independent_admission(fault): + c = candidate("1.5.0", platform="linux/arm64" if fault == "platform" else "linux/amd64") + values = [c] + caps = {"release_components": 0 if fault == "capability" else 1} + if fault == "dependency": + c.admission["component_admissions"][0].update(independently_replaceable=False, dependency_group=["grafana", "prometheus"]) + if fault == "ambiguous": + values.append(candidate("1.5.0", identity="c")) + assert policy_module().choose_candidate("grafana", "1.4.0", 1, values, caps, "linux/amd64") is None + + +@pytest.fixture +def policy_product(product): + host, service, owner, _ = product + data = copy.deepcopy(host.previous.manifest.data) + data["components"]["grafana"]["release"] = "1.4.0" + path = host.config.config_dir / "test-current.json" + path.write_text(json.dumps(data)) + host.previous = host.store.prepare(path, policies=host.previous.selection["components"], platform="linux/amd64") + host.store.commit(host.previous) + host.config.release_selection.selection_id = host.previous.selection["selection_id"] + host.config.release_selection.selection_sha256 = host.previous.selection_sha256 + host.config.release_selection.components = host.previous.selection["components"] + public = yaml.safe_load((host.config.config_dir / "fleet-config.yaml").read_bytes()) + public["release_selection"] = host.config._to_dict(include_secrets=False)["release_selection"] + (host.config.config_dir / "fleet-config.yaml").write_text(yaml.safe_dump(public)) + installed = copy.deepcopy(data["components"]["grafana"]) + owner.installed_component = lambda current, name: copy.deepcopy(installed) if name == "grafana" else None + return host, service, owner + + +def expected(service): + current = service.store.load() + return {"expected_selection_id": current.selection["selection_id"], + "expected_selection_sha256": current.selection_sha256} + + +def set_mode(service, mode): + return service.dispatch("policy-set", {"component": "grafana", "mode": mode, **expected(service)}, actor=ACTOR) + + +def admitted_version(admitted, version, identity="b", generation=5): + manifest = json.loads(admitted["manifest"]) + component = manifest["components"]["grafana"] + component["release"] = version + component["artifacts"]["linux/amd64"]["reference"] = "grafana/grafana@sha256:" + identity * 64 + raw = catalog._canonical(manifest) if hasattr(catalog, "_canonical") else json.dumps(manifest, sort_keys=True, separators=(",", ":")).encode() + envelope = copy.deepcopy(admitted["envelope"]) + envelope['generation'] = generation + envelope["manifest_sha256"] = __import__("hashlib").sha256(raw).hexdigest() + envelope["component_admissions"][0]["identity"] = component["artifacts"]["linux/amd64"]["reference"] + admission = json.dumps(envelope, sort_keys=True, separators=(",", ":")).encode() + digest = __import__("hashlib").sha256(admission).hexdigest() + index = {**admitted["index"], "generation":generation, "candidates": {digest: digest}} + index_raw = json.dumps(index, sort_keys=True, separators=(",", ":")).encode() + return release_candidates.verify_candidate(raw, admission, admitted["key"].sign(admission), + index_raw, admitted["key"].sign(index_raw), admitted["policy"], now=admitted["now"]) + + +def test_existing_components_default_pinned_with_no_implicit_follow(policy_product): + host, service, owner = policy_product + before = host.store.load().selection_raw + listing = service.dispatch("policy-list", {}, actor=ACTOR) + assert all(c["mode"] == "pinned" for c in listing["components"].values()) + assert listing["components"]["vast-price-manager"]["supported"] is False + assert host.store.load().selection_raw == before + assert owner.calls == [] + + +def test_unpin_survives_restart_and_changes_only_one_policy_without_install(policy_product): + host, service, owner = policy_product + before = host.store.load() + result = set_mode(service, "follow-stable") + assert result["components"]["grafana"]["mode"] == "follow-stable" + current = host.store.load() + assert current.selection["components"]["grafana"] == {"origin": "baseline", "enabled": True} + for name in before.selection["components"]: + if name != "grafana": + assert current.selection["components"][name] == before.selection["components"][name] + assert current.manifest.data["components"][name] == before.manifest.data["components"][name] + restarted = type(service)(host.config, service.policy, discovery=service.discovery, owner=owner, schedule=lambda *a: None) + assert restarted.dispatch("policy-list", {}, actor=ACTOR)["components"]["grafana"]["mode"] == "follow-stable" + assert owner.calls == [] + + +def test_refresh_only_advances_opted_in_service_and_repin_installed_freezes_it(policy_product, admitted): + host, service, owner = policy_product + set_mode(service, "follow-stable") + c = admitted_version(admitted, "1.5.0") + service.discovery = lambda: [c] + result = service.dispatch("policy-refresh", expected(service), actor=ACTOR) + assert result["advanced"] == ["grafana"] + assert host.store.load().manifest.data["components"]["grafana"]["release"] == "1.5.0" + set_mode(service, "pinned") + frozen = host.store.load() + assert frozen.manifest.data["components"]["grafana"]["release"] == "1.4.0" + assert frozen.selection["components"]["grafana"]["origin"] == "customer-pin" + result = service.dispatch("policy-refresh", expected(service), actor=ACTOR) + assert result["advanced"] == [] and host.store.load().selection_raw == frozen.selection_raw + assert owner.calls == [] + + +@pytest.mark.parametrize("fault", ["stale", "busy", "disabled", "unproven-installed"]) +def test_mode_failure_has_no_partial_policy_or_selection_change(policy_product, fault): + host, service, owner = policy_product + from dc_overview.release_broker import BrokerError + set_mode(service, "follow-stable") + before = snapshot(host, service) + params = {"component": "grafana", "mode": "pinned", **expected(service)} + if fault == "stale": params["expected_selection_sha256"] = "0" * 64 + if fault == "busy": + for path,value in [(host.jobs/'active.json',{'id':'e'*32}),(host.jobs/('e'*32+'.json'),{'id':'e'*32,'state':'running'})]: + path.write_text(json.dumps(value));path.chmod(0o600) + if fault == "disabled": service.policy["writes_enabled"] = False + if fault == "unproven-installed": owner.installed_component = lambda *a: None + codes = {'stale':'selection-conflict', 'busy':'busy', 'disabled':'disabled', 'unproven-installed':'installed-unverified'} + with pytest.raises(BrokerError) as error: + service.dispatch("policy-set", params, actor=ACTOR) + assert error.value.code == codes[fault] + assert snapshot(host, service) == before + assert owner.calls == [] + + +def snapshot(host, service): + mode = service.root / 'policy-state.json' + current = host.store.load() + return (current.selection_raw, current.manifest.raw, + (host.config.config_dir / 'fleet-config.yaml').read_bytes(), + mode.read_bytes() if mode.exists() else None) + + +@pytest.mark.parametrize('fault', ['signature','expired','revoked','replay','digest','unavailable']) +def test_refresh_uses_actual_signed_admission_and_preserves_policy_on_failure(policy_product, admitted, fault): + from dataclasses import replace + from dc_overview.release_broker import BrokerError, canonical, sha + from datetime import timedelta + host, service, owner = policy_product + set_mode(service, 'follow-stable') + before = snapshot(host, service) + c = admitted_version(admitted, '1.5.0') + if fault == 'signature': c = replace(c, signature=b'0'*64) + elif fault == 'digest': c = replace(c, manifest_raw=c.manifest_raw+b' ') + elif fault in ('expired','revoked','replay'): + index = copy.deepcopy(c.index) + if fault == 'expired': index['expires_at'] = (admitted['now']-timedelta(seconds=1)).isoformat() + elif fault == 'revoked': index['revoked'] = [c.candidate_id] + else: index['generation'] = 4 + raw = canonical(index) + c = replace(c,index_raw=raw,index_signature=admitted['key'].sign(raw)) + def discover(): + if fault == 'unavailable': raise OSError('offline fixture') + return [c] + service.discovery = discover + with pytest.raises(BrokerError) as error: + service.dispatch('policy-refresh',expected(service),actor=ACTOR) + assert error.value.code == 'unavailable' + assert snapshot(host,service) == before and owner.calls == [] + + +def test_repeated_check_never_downgrades_an_already_pending_target(policy_product, admitted): + host, service, owner = policy_product + set_mode(service,'follow-stable') + service.discovery = lambda:[admitted_version(admitted,'1.8.0')] + service.dispatch('policy-refresh',expected(service),actor=ACTOR) + before = snapshot(host,service) + service.discovery = lambda:[admitted_version(admitted,'1.5.0',generation=6)] + result = service.dispatch('policy-refresh',expected(service),actor=ACTOR) + assert result['advanced'] == [] and result['reasons']['grafana'] + assert snapshot(host,service) == before and owner.calls == [] + + +@pytest.mark.parametrize('boundary', ['journal','selection','public','policy','finish']) +def test_interrupted_policy_publication_restarts_to_a_coherent_state(policy_product, monkeypatch, boundary): + import dc_overview.release_policy as policy + from dc_overview.release_broker import ReleaseBroker + from dc_overview.fleet_config import FleetConfig + from pathlib import Path + host, service, owner = policy_product + before = snapshot(host, service) + original_write = policy.private_write + original_atomic = catalog._atomic_write + original_unlink = Path.unlink + fired = [] + def write(path, value): + if not fired and ((boundary=='journal' and path.name=='policy-publication.json') or + (boundary=='policy' and path.name=='policy-state.json')): + fired.append(True); raise OSError('fixture publication interruption') + return original_write(path,value) + def atomic(path,*args,**kwargs): + if boundary=='selection' and path.name=='selection.json' and not fired: + fired.append(True); raise OSError('fixture selection interruption') + return original_atomic(path,*args,**kwargs) + def unlink(path,*args,**kwargs): + if boundary=='finish' and path.name=='policy-publication.json' and not fired: + fired.append(True); raise OSError('fixture cleanup interruption') + return original_unlink(path,*args,**kwargs) + with monkeypatch.context() as change: + change.setattr(policy,'private_write',write) + change.setattr(catalog,'_atomic_write',atomic) + change.setattr(Path,'unlink',unlink) + if boundary=='public': + def fail_public(**kw): + fired.append(True);raise OSError('public interruption') + change.setattr(host.config,'persist_lifecycle',fail_public) + with pytest.raises((OSError,RuntimeError,ValueError)): + set_mode(service,'follow-stable') + assert fired, 'test never reached its intended publication boundary' + # Recreate configuration from persisted public data, not the original Python object. + config = FleetConfig.load(host.config.config_dir) + restarted = ReleaseBroker(config,service.policy,discovery=service.discovery,owner=owner,schedule=lambda *a:None) + listing = restarted.dispatch('policy-list',{},actor=ACTOR) + current = host.store.load() + if boundary in ('journal','selection','public'): + assert snapshot(host,service)==before + assert listing['components']['grafana']['mode']=='pinned' + else: + assert current.selection['components']['grafana']['origin']=='baseline' + assert listing['components']['grafana']['mode']=='follow-stable' + public = yaml.safe_load((host.config.config_dir/'fleet-config.yaml').read_bytes()) + assert public['release_selection']['selection_sha256']==current.selection_sha256 + assert not (service.root/'policy-publication.json').exists() and owner.calls==[] + + +def test_refresh_and_repin_are_serialized_and_stale_refresh_cannot_win(policy_product, admitted): + import threading + from dc_overview.release_broker import ReleaseBroker,BrokerError + from dc_overview.fleet_config import FleetConfig + host, service, owner = policy_product + set_mode(service,'follow-stable') + started, resume = threading.Event(),threading.Event() + def discovery(): + started.set(); assert resume.wait(5) + return [admitted_version(admitted,'1.5.0')] + service.discovery=discovery + prior=expected(service); failures=[] + def refresh(): + try: service.dispatch('policy-refresh',prior,actor=ACTOR) + except BaseException as e: failures.append(e) + thread=threading.Thread(target=refresh);thread.start();assert started.wait(5) + try: + config=FleetConfig.load(host.config.config_dir) + peer=ReleaseBroker(config,service.policy,owner=owner,schedule=lambda *a:None) + with pytest.raises(BrokerError) as error: set_mode(peer,'pinned') + assert error.value.code=='busy' + finally: resume.set();thread.join(5) + assert not thread.is_alive() and not failures + set_mode(service,'pinned'); frozen=snapshot(host,service) + with pytest.raises(BrokerError) as error: service.dispatch('policy-refresh',prior,actor=ACTOR) + assert error.value.code=='selection-conflict' and snapshot(host,service)==frozen + assert owner.calls==[] + + +@pytest.mark.parametrize('fault',[None,'missing','wrong-component','version-conflict','unregistered-image']) +def test_installed_pin_requires_exact_known_component_artifact(policy_product,fault): + host,service,owner=policy_product + current=host.store.load();reference=current.targets['grafana']['reference'] + image={'Id':'sha256:'+'e'*64,'Os':'linux','Architecture':'amd64', + 'RepoDigests':[reference], 'Config':{'Labels':{'org.opencontainers.image.version':'1.4.0'}}} + live={'Id':'d'*64,'Image':image['Id'],'State':{'Running':True},'Config':{'Image':reference}} + if fault=='missing': live['State']['Running']=False + if fault=='wrong-component': image['RepoDigests']=['prom/prometheus@sha256:'+'a'*64] + if fault=='version-conflict': image['Config']['Labels']['org.opencontainers.image.version']='1.9.0' + if fault=='unregistered-image': image['RepoDigests']=['grafana/grafana@sha256:'+'f'*64] + inspect=lambda name:live if name=='grafana' else image + result=policy_module().installed_component(current,'grafana',host.store,inspect) + assert result == (current.manifest.data['components']['grafana'] if fault is None else None) + + +def test_policy_only_change_advances_cas_even_when_digest_is_unchanged(policy_product): + from dc_overview.release_broker import BrokerError + host,service,owner=policy_product;prior=expected(service);target=host.store.load().targets['grafana']['reference'] + set_mode(service,'follow-stable') + assert host.store.load().targets['grafana']['reference']==target + assert expected(service)!=prior + with pytest.raises(BrokerError) as error: + service.dispatch('policy-set',{'component':'grafana','mode':'pinned',**prior},actor=ACTOR) + assert error.value.code=='selection-conflict' and owner.calls==[] + + +def test_native_policy_cli_uses_the_same_owner_contract(policy_product,monkeypatch): + from click.testing import CliRunner + from dc_overview.cli import main + from dc_overview import release_broker_service + host,service,owner=policy_product;calls=[] + monkeypatch.setattr(release_broker_service,'request',lambda action,params:calls.append((action,params)) or {'components':{}}) + runner=CliRunner() + result=runner.invoke(main,['release','policy-set','--component','grafana','--mode','follow-stable', + '--expected-selection-id','fixture','--expected-selection-sha256','a'*64]) + assert result.exit_code==0,result.output + assert calls[-1]==('policy-set',{'component':'grafana','mode':'follow-stable','expected_selection_id':'fixture','expected_selection_sha256':'a'*64}) + + +@pytest.mark.parametrize('change',[{'mode':True},{'mode':'latest'},{'component':'../ipmi-monitor'}, + {'expected_selection_sha256':'a'}, {'path':'/etc/passwd'}, {'actor':{'kind':'host-peer','uid':0}}]) +def test_broker_policy_params_are_strict_supported_actions(change): + from dc_overview.release_broker import validate_params + body={'component':'grafana','mode':'follow-stable','expected_selection_id':'fixture','expected_selection_sha256':'a'*64} + validate_params('policy-set',body) # Positive control prevents an unknown-action false pass. + body.update(change) + with pytest.raises(ValueError):validate_params('policy-set',body) + + +@pytest.mark.parametrize('kind',['fleet-admin','host-peer']) +def test_policy_socket_does_not_trust_an_unapproved_peer_claim(policy_product,kind): + from dc_overview.release_broker_service import response + host,service,owner=policy_product;service.policy['allowed_uids']=[0] + actor=ACTOR if kind=='fleet-admin' else {'kind':'host-peer','uid':0} + raw=json.dumps({'schema_version':1,'action':'policy-set','params':{ + 'component':'grafana','mode':'follow-stable',**expected(service)},'actor':actor}).encode()+b'\n' + result=json.loads(response(service,raw,1001)) + assert result['ok'] is False and result['error']['code']=='forbidden' and owner.calls==[] + + +def test_daily_timer_install_uses_only_fixed_packaged_units(policy_product,tmp_path,monkeypatch): + from pathlib import Path + policy=policy_module();calls=[] + monkeypatch.setattr(policy,'SYSTEMD_DIR',tmp_path/'units') + monkeypatch.setattr(policy,'release_cli',lambda:'/opt/verified/bin/dc-overview') + monkeypatch.setattr(policy.subprocess,'run',lambda args,**kw:calls.append(args) or SimpleNamespace(returncode=0)) + policy.install_timer() + assert calls==[['systemctl','daemon-reload'],['systemctl','enable','--now','dc-overview-release-refresh.timer']] + service=(tmp_path/'units/dc-overview-release-refresh.service').read_text() + assert '/opt/verified/bin/dc-overview release policy-refresh' in service + assert (tmp_path/'units/dc-overview-release-refresh.timer').exists() + + +def test_policy_refresh_revalidates_admission_at_native_precommit(policy_product,admitted,monkeypatch): + import dc_overview.release_policy as policy + from dc_overview import fleet_upgrade + host,service,owner=policy_product + set_mode(service,'follow-stable');before=snapshot(host,service) + service.discovery=lambda:[admitted_version(admitted,'1.5.0')] + original=fleet_upgrade.select_release_components;verified=[] + def expire_at_precommit(*args,**kwargs): + check=kwargs.get('precommit_check') + assert callable(check), 'publication must carry a freshness and policy-intent check' + def expired(*args,**kwargs): + verified.append(True);raise ValueError('admission expired before publication') + with monkeypatch.context() as m: + m.setattr(policy,'verify_candidate',expired) + return original(*args,**kwargs) + monkeypatch.setattr(fleet_upgrade,'select_release_components',expire_at_precommit) + with pytest.raises(ValueError): service.dispatch('policy-refresh',expected(service),actor=ACTOR) + assert verified and snapshot(host,service)==before and owner.calls==[] + + +def test_unfinished_policy_publication_blocks_other_release_paths(policy_product,monkeypatch): + import dc_overview.release_policy as policy + from dc_overview import fleet_upgrade + from dc_overview.release_broker import BrokerError + host,service,owner=policy_product;write=policy.private_write + def fail(path,value): + if path.name=='policy-state.json':raise OSError('interrupted policy write') + return write(path,value) + with monkeypatch.context() as m: + m.setattr(policy,'private_write',fail) + with pytest.raises(OSError):set_mode(service,'follow-stable') + before=host.store.load().selection_raw + with pytest.raises(BrokerError) as error: + service.dispatch('preview',{'candidate_ids':['fixture'],'components':['grafana'], + 'operation_kind':'services-update',**expected(service)},actor=ACTOR) + assert error.value.code=='recovery-required' + with pytest.raises((RuntimeError,ValueError)): + fleet_upgrade.select_release_components(host.config,host.manifest,['grafana'],platform='linux/amd64') + assert host.store.load().selection_raw==before + + +def test_retained_installed_provenance_is_found_when_newer_selection_is_pending(policy_product,admitted): + host,service,owner=policy_product;old=host.store.load();component=old.manifest.data['components']['grafana'] + reference=old.targets['grafana']['reference'] + set_mode(service,'follow-stable');service.discovery=lambda:[admitted_version(admitted,'1.5.0')] + service.dispatch('policy-refresh',expected(service),actor=ACTOR) + image={'Id':'sha256:'+'e'*64,'Os':'linux','Architecture':'amd64','RepoDigests':[reference], + 'Config':{'Labels':{'org.opencontainers.image.version':'1.4.0'}}} + live={'Id':'d'*64,'Image':image['Id'],'State':{'Running':True},'Config':{'Image':reference}} + assert policy_module().installed_component(host.store.load(),'grafana',host.store, + lambda name:live if name=='grafana' else image)==component + + +def test_native_writer_wins_before_journal_without_orphaning_policy(policy_product,monkeypatch): + from dc_overview import fleet_upgrade + from dc_overview.release_broker import BrokerError + policy=policy_module();host,service,owner=policy_product;write=policy.private_write;fired=[] + data=copy.deepcopy(host.store.load().manifest.data);data['baseline_id']='competing-native-writer' + path=host.config.config_dir/'competing.json';path.write_text(json.dumps(data)) + def competing_write(target,value): + if target.name=='policy-candidate.json' and not fired: + fired.append(True) + fleet_upgrade.select_release_components(host.config,path,['grafana'],platform='linux/amd64') + return write(target,value) + with monkeypatch.context() as change: + change.setattr(policy,'private_write',competing_write) + with pytest.raises((BrokerError,RuntimeError,ValueError)):set_mode(service,'follow-stable') + assert fired and host.store.load().selection['selection_id']=='competing-native-writer' + assert not (service.root/'policy-publication.json').exists() + assert service.dispatch('policy-list',{},actor=ACTOR)['components']['grafana']['mode']=='pinned' + + +def test_follow_tracks_a_new_explicitly_installed_major(policy_product,admitted): + from dc_overview import fleet_upgrade + host,service,owner=policy_product;set_mode(service,'follow-stable') + data=copy.deepcopy(host.store.load().manifest.data);data['baseline_id']='explicit-major-two' + new=copy.deepcopy(data['components']['grafana']);new['release']='2.0.0' + new['artifacts']['linux/amd64']['reference']='grafana/grafana@sha256:'+'c'*64 + data['components']['grafana']=new;path=host.config.config_dir/'explicit-major.json';path.write_text(json.dumps(data)) + fleet_upgrade.select_release_components(host.config,path,['grafana'],platform='linux/amd64') + owner.installed_component=lambda current,name:copy.deepcopy(new) if name=='grafana' else None + service.discovery=lambda:[admitted_version(admitted,'2.1.0',identity='d')] + result=service.dispatch('policy-refresh',expected(service),actor=ACTOR) + assert result['advanced']==['grafana'] and result['components']['grafana']['major']==2 + assert host.store.load().manifest.data['components']['grafana']['release']=='2.1.0' + assert owner.calls==[] + + +def test_repin_revalidates_installed_identity_inside_native_locks(policy_product,monkeypatch): + from dc_overview.release_broker import BrokerError + policy=policy_module();host,service,owner=policy_product;set_mode(service,'follow-stable') + before=snapshot(host,service);write=policy.private_write;fired=[] + def change_installed(path,value): + if path.name=='policy-candidate.json' and not fired: + fired.append(True) + owner.installed_component=lambda *a:None + return write(path,value) + with monkeypatch.context() as change: + change.setattr(policy,'private_write',change_installed) + with pytest.raises(BrokerError) as error:set_mode(service,'pinned') + assert error.value.code=='installed-unverified' and fired and snapshot(host,service)==before + + +def test_cli_and_packaging_include_the_daily_policy_only_refresh(): + from pathlib import Path + root = Path(__file__).resolve().parents[1] + timer = (root / "src/dc_overview/templates/systemd/dc-overview-release-refresh.timer").read_text() + service = (root / "src/dc_overview/templates/systemd/dc-overview-release-refresh.service").read_text() + assert "OnCalendar=daily" in timer and "Persistent=true" in timer + assert "release policy-refresh" in service and "--install" not in service + assert '"templates/systemd/*.timer"' in (root / "pyproject.toml").read_text() + diff --git a/tests/test_scoped_release_selection.py b/tests/test_scoped_release_selection.py index f50ca1d..f79918a 100644 --- a/tests/test_scoped_release_selection.py +++ b/tests/test_scoped_release_selection.py @@ -1,3 +1,5 @@ +# TRACEWEAVER: file-role=release-verification; req=REQ-FLEETUPDATE-001; trace=TRACE-FLEETUPDATE-001; ver=VER-FLEETUPDATE-001 +# TRACEWEAVER: verifies=VER-FLEETUPDATE-001; req=REQ-FLEETUPDATE-001; trace=TRACE-FLEETUPDATE-001 """Synthetic selected hosts; real publication/CAS, no live Docker mutations.""" import copy import hashlib @@ -479,3 +481,119 @@ def test_adopted_reference_publication_failure_rolls_back_and_retries(selected_h assert not (host.store.root/'.lifecycle-publication.json').exists() monkeypatch.setattr(host.config, 'persist_lifecycle', original) assert select(host, adopt_existing_selection=True)['reference_adopted'] is True + + +@pytest.fixture +def unresolved_service(selected_host, monkeypatch): + from cryptolabs_proxy import updates, update_recovery as recovery, release_selection + host=selected_host + (host.config.config_dir/'.lifecycle-config.lock').touch(mode=0o600) + snapshot=release_selection.validate(host.previous.selection_raw,host.previous.manifest.raw) + job_id='1'*32 + job={'id':job_id,'helper':'cryptolabs-update-'+job_id,'service':'ipmi-monitor','branch':'main', + 'action':'update','state':'failed','success':False,'created_at':2000, + 'results':{'ipmi-monitor':{'state':'recovery_required','success':False}}, + 'sources':{'ipmi-monitor':{'container_id':'2'*64,'image_id':'sha256:'+'3'*64}}, + 'selection_id':snapshot['selection_id'],'selection_sha256':snapshot['selection_sha256'], + 'manifest_sha256':snapshot['manifest_sha256'],'selection_snapshot':snapshot, + 'targets':release_selection.targets(snapshot,'linux/amd64')} + updates.write_job(host.jobs,job);updates._write_json(host.jobs/'active.json',{'id':job_id}) + continuity={k:'4'*64 for k in recovery.HASH_KEYS} + continuity.update(projection='ipmi-original-continuity-v1',database_device=1,database_inode=2, + saved_identity_field_count=5,stored_key_digest_matches=True,sync_enabled=False) + observation=recovery.OriginalObservation('2'*64,'sha256:'+'3'*64,True,True,continuity) + class Engine: + def inspect(self,name):return {'Id':'2'*64,'Image':'sha256:'+'3'*64} + monkeypatch.setattr(updates,'UpdateEngine',Engine) + monkeypatch.setattr(updates,'observe_original',lambda *a:observation) + monkeypatch.setattr(recovery,'discover_baseline',lambda *a,**kw:'5'*64) + # Keep actual filesystem locks/bytes/CAS. Only root ancestry and platform + # admission are adapted for the unprivileged macOS fixture. + original_open=recovery.open_existing_directory + monkeypatch.setattr(recovery,'open_existing_directory',lambda path,**kw:original_open(path)) + monkeypatch.setattr(upgrade,'_require_recovery_root',lambda:None,raising=False) + return host,job,observation + + +def test_host_reconcile_before_record_cli_writes_only_receipt_and_selector_revalidates(unresolved_service,monkeypatch): + from cryptolabs_proxy import updates + host,job,observation=unresolved_service + # No installed/current CLI observation is needed during reconciliation. + monkeypatch.setattr(upgrade,'verify_running_cli',lambda *a:pytest.fail('record-cli before reconcile')) + before={p.name:p.read_bytes() for p in host.jobs.iterdir()} + result=upgrade.reconcile_service(host.config,'ipmi-monitor',job['id']) + assert result=={'job_id':job['id'],'service':'ipmi-monitor','outcome':'original_restored', + 'resolution_available':True,'reason':'original_restoration_verified'} + assert {p.name:p.read_bytes() for p in host.jobs.iterdir() if p.name in before}==before + assert {p.name for p in host.jobs.iterdir()}-before.keys()=={'service-recovery-'+job['id']+'.json'} + saved=(host.jobs/('service-recovery-'+job['id']+'.json')).read_bytes() + assert upgrade.reconcile_service(host.config,'ipmi-monitor',job['id'])==result + assert (host.jobs/('service-recovery-'+job['id']+'.json')).read_bytes()==saved + # Receipt allows only the idle predicate; selector still runs its normal CAS. + assert select(host)['state']=='pending-deployment' + from dataclasses import replace + monkeypatch.setattr(updates,'observe_original',lambda *a:replace(observation,healthy=False)) + with pytest.raises((RuntimeError,ValueError)): + upgrade._scoped_idle(host.jobs) + + +@pytest.mark.parametrize('drift',['raw','helper','lock','busy']) +def test_host_reconcile_late_drift_and_real_flock_hold_without_receipt(unresolved_service,monkeypatch,drift): + from cryptolabs_proxy import updates, update_recovery as recovery + host,job,observation=unresolved_service + import fcntl + held=None + if drift=='busy': + held=os.open(host.jobs/'operation.lock',os.O_RDWR);fcntl.flock(held,fcntl.LOCK_EX|fcntl.LOCK_NB) + original=updates.observe_original;calls=[] + def observe(*a): + calls.append(True) + if len(calls)==2: + if drift=='raw':(host.jobs/(job['id']+'.json')).write_bytes((host.jobs/(job['id']+'.json')).read_bytes()+b' ') + if drift=='lock': + (host.jobs/'operation.lock').unlink();(host.jobs/'operation.lock').touch(mode=0o600) + if drift=='helper':recovery.hold() + return original(*a) + monkeypatch.setattr(updates,'observe_original',observe) + try: + with pytest.raises((RuntimeError,ValueError)): + upgrade.reconcile_service(host.config,'ipmi-monitor',job['id']) + finally: + if held is not None:os.close(held) + assert not (host.jobs/('service-recovery-'+job['id']+'.json')).exists() + + +def test_fixed_reconcile_command_rejects_widened_arguments(selected_host,monkeypatch): + from click.testing import CliRunner + from dc_overview.cli import main + monkeypatch.setattr(FleetConfig,'load',lambda *a:selected_host.config) + monkeypatch.setattr(upgrade,'reconcile_service',lambda config,service,job_id:{'service':service,'job_id':job_id,'outcome':'original_restored'}) + result=CliRunner().invoke(main,['release','reconcile-service','--service','ipmi-monitor','--job','a'*32]) + assert result.exit_code==0 and json.loads(result.output)['outcome']=='original_restored' + for extra in (['--force'],['--path','/tmp/anything'],['--service','grafana']): + assert CliRunner().invoke(main,['release','reconcile-service','--service','ipmi-monitor','--job','a'*32,*extra]).exit_code!=0 + + +@pytest.mark.parametrize('bad',['shadow','duplicate','remote']) +def test_recovery_store_resolution_rejects_shadow_mounts_and_remote_engine(tmp_path,monkeypatch,bad): + import platform + monkeypatch.setattr(platform,'system',lambda:'Linux') + monkeypatch.delenv('DOCKER_HOST',raising=False);monkeypatch.delenv('DOCKER_CONTEXT',raising=False) + source=tmp_path/'auth';source.mkdir(mode=0o700) + proxy={'Mounts':[{'Type':'bind','Source':str(source),'Destination':'/data/auth','RW':True}]} + if bad=='shadow':proxy['Mounts'].append({'Type':'bind','Source':str(tmp_path),'Destination':'/data/auth/update-jobs','RW':True}) + if bad=='duplicate':proxy['Mounts'].append(dict(proxy['Mounts'][0])) + endpoint='tcp://192.0.2.1:2375' if bad=='remote' else 'unix:///var/run/docker.sock' + monkeypatch.setattr(upgrade.subprocess,'run',lambda *a,**kw:SimpleNamespace(returncode=0,stdout=json.dumps(endpoint))) + with pytest.raises(RuntimeError):upgrade._scoped_updater_directory(proxy) + + +def test_host_reconciliation_does_not_create_missing_lifecycle_lock(unresolved_service): + host,job,observation=unresolved_service + lock=host.config.config_dir/'.lifecycle-config.lock';lock.unlink() + before={str(p):p.read_bytes() for p in host.config.config_dir.rglob('*') if p.is_file()} + with pytest.raises((RuntimeError,ValueError,OSError)): + upgrade.reconcile_service(host.config,'ipmi-monitor',job['id']) + assert {str(p):p.read_bytes() for p in host.config.config_dir.rglob('*') if p.is_file()}==before + assert not lock.exists() + assert not (host.jobs/('service-recovery-'+job['id']+'.json')).exists() diff --git a/traceability-matrix.md b/traceability-matrix.md index 548f45c..82a16ff 100644 --- a/traceability-matrix.md +++ b/traceability-matrix.md @@ -23,6 +23,17 @@ Canonical reviewed authority and frozen profile: ../artifacts/ipmi-readiness-202 | TRACE-FLEETUPDATE-001 | REQ-FLEETUPDATE-001 | `.github/tests/test_fleet_native_route.py` | VER-FLEETUPDATE-001 | VAL-FLEETUPDATE-001 | approved | | TRACE-FLEETUPDATE-001 | REQ-FLEETUPDATE-001 | `scripts/verify_fleet_release_native.py` | VER-FLEETUPDATE-001 | VAL-FLEETUPDATE-001 | v3 source pin corrected; automatic native recheck pending | | TRACE-FLEETUPDATE-001 | REQ-FLEETUPDATE-001 | `docs/fleet-release-native-qa.md` | VER-FLEETUPDATE-001 | VAL-FLEETUPDATE-001 | approved | +| TRACE-FLEETUPDATE-001 | REQ-FLEETUPDATE-001 | `tests/test_scoped_release_selection.py` | VER-FLEETUPDATE-001 | VAL-FLEETUPDATE-001 | Approved recovery source scope; actual native/site acceptance held | +| TRACE-FLEETUPDATE-001 | REQ-FLEETUPDATE-001 | `docs/native-service-recovery.md` | VER-FLEETUPDATE-001 | VAL-FLEETUPDATE-001 | Approved recovery operations documentation | +| TRACE-FLEETUPDATE-001 | REQ-FLEETUPDATE-001 | `scripts/fixtures/legacy-selected-state-protection.py` | VER-FLEETUPDATE-001 | VAL-FLEETUPDATE-001 | approved source authority | + +The synthetic native fixture helper row projects only the approved source scope +under amendment `159af842…` and the root-reviewed native test integration GO. +Local15-check verification and independent frozen-body reviews are retained in +`../artifacts/ipmi-readiness-20261026/fleet-ui-20261102/execution/native-fixture/repair2/`. +Actual native execution, collector proof, public admission, customer/site +acceptance, external VM destruction and publication remain held; the source +authority status does not certify those outcomes. ## Unsupported format evidence @@ -38,6 +49,16 @@ The root-reviewed native preflight repair is limited to the `release_candidates. | Artifact Path | Requirement | Trace | Verification | Anchor Type | Role | | --- | --- | --- | --- | --- | --- | +| src/dc_overview/release_policy.py | REQ-AUTOADVANCE-003 | TRACE-AUTOADVANCE-003 | VER-AUTOADVANCE-003 | file-role | stable-release-policy | +| tests/test_release_policy.py | REQ-AUTOADVANCE-008 | TRACE-AUTOADVANCE-008 | VER-AUTOADVANCE-008 | file-role | policy-regression | +| tests/test_release_policy.py | REQ-AUTOADVANCE-008 | TRACE-AUTOADVANCE-008 | VER-AUTOADVANCE-008 | verifies | policy-regression | +| src/dc_overview/release_policy.py | REQ-AUTOADVANCE-002 | TRACE-AUTOADVANCE-002 | VER-AUTOADVANCE-002 | entrypoint | policy-entrypoint | +| src/dc_overview/release_policy.py | REQ-AUTOADVANCE-004 | TRACE-AUTOADVANCE-004 | VER-AUTOADVANCE-004 | entrypoint | policy-entrypoint | +| src/dc_overview/release_broker.py | REQ-AUTOADVANCE-005 | TRACE-AUTOADVANCE-005 | VER-AUTOADVANCE-005 | entrypoint | policy-entrypoint | +| src/dc_overview/cli.py | REQ-AUTOADVANCE-004 | TRACE-AUTOADVANCE-004 | VER-AUTOADVANCE-004 | entrypoint | policy-entrypoint | + +| Artifact Path | Requirement | Trace | Verification | Anchor Type | Role | +| --- | --- | --- | --- | --- | --- | --- | | src/dc_overview/cli.py | REQ-FLEETUPDATE-001 | TRACE-FLEETUPDATE-001 | VER-FLEETUPDATE-001 | file-role | release-owner | | src/dc_overview/cli.py | REQ-FLEETUPDATE-001 | TRACE-FLEETUPDATE-001 | VER-FLEETUPDATE-001 | entrypoint | release-owner | | src/dc_overview/fleet_upgrade.py | REQ-FLEETUPDATE-001 | TRACE-FLEETUPDATE-001 | VER-FLEETUPDATE-001 | file-role | release-owner | @@ -61,6 +82,19 @@ The root-reviewed native preflight repair is limited to the `release_candidates. | .github/workflows/fleet-release-native-qa.yml | REQ-FLEETUPDATE-001 | TRACE-FLEETUPDATE-001 | VER-FLEETUPDATE-001 | file-role | native-route-workflow | | docs/fleet-release-native-qa.md | REQ-FLEETUPDATE-001 | TRACE-FLEETUPDATE-001 | VER-FLEETUPDATE-001 | file-role | native-qa-documentation | | docs/fleet-suite-authority.md | REQ-FLEETUPDATE-001 | TRACE-FLEETUPDATE-001 | VER-FLEETUPDATE-001 | file-role | release-operations-documentation | +| tests/test_scoped_release_selection.py | REQ-FLEETUPDATE-001 | TRACE-FLEETUPDATE-001 | VER-FLEETUPDATE-001 | verifies | release-verification | +| docs/native-service-recovery.md | REQ-FLEETUPDATE-001 | TRACE-FLEETUPDATE-001 | VER-FLEETUPDATE-001 | file-role | recovery-operations-documentation | +| scripts/fixtures/legacy-selected-state-protection.py | REQ-FLEETUPDATE-001 | TRACE-FLEETUPDATE-001 | VER-FLEETUPDATE-001 | verifies | native-verification | + + +## Recovery amendment source evidence (2 November 2026) + +Authority is the exact approved amendment `159af842…` and frozen contract +`91b873c5…` linked from requirements.md. Focused RED/GREEN and candidate +hashes are retained at `../artifacts/ipmi-readiness-20261026/fleet-ui-20261102/execution/build/manifest.json`. +Shared pre-code V&V is `../artifacts/ipmi-readiness-20261026/fleet-ui-20261102/execution/go/recovery-vv-root-reviewed.json`. +Native installed-wheel bootstrap, source publication, production reconciliation, +site continuity, signed admission and UI acceptance remain held. ## Central telemetry monitoring policy mapping @@ -95,6 +129,37 @@ review metadata, not a substitute for fresh CI on the published head. | tests/test_http_inventory.py | REQ-MON-002 | TRACE-MON-002 | VER-MON-002 | verifies | policy-metric-regression | | tests/test_http_inventory.py | REQ-MON-003 | TRACE-MON-003 | VER-MON-003 | verifies | application-scrape-regression | +## Approved auto-advance work-item mapping + +| Trace | Requirement | Implementation | Verification | Validation | Status | +| --- | --- | --- | --- | --- | --- | --- | +| TRACE-AUTOADVANCE-001 | REQ-AUTOADVANCE-001 | approved plan step1-5; file anchors added as implemented | VER-AUTOADVANCE-001 | VAL-AUTOADVANCE-001 | owner-approved / verification pending | +| TRACE-AUTOADVANCE-002 | REQ-AUTOADVANCE-002 | approved plan step1-5; file anchors added as implemented | VER-AUTOADVANCE-002 | VAL-AUTOADVANCE-002 | owner-approved / verification pending | +| TRACE-AUTOADVANCE-003 | REQ-AUTOADVANCE-003 | approved plan step1-5; file anchors added as implemented | VER-AUTOADVANCE-003 | VAL-AUTOADVANCE-003 | owner-approved / verification pending | +| TRACE-AUTOADVANCE-004 | REQ-AUTOADVANCE-004 | approved plan step1-5; file anchors added as implemented | VER-AUTOADVANCE-004 | VAL-AUTOADVANCE-004 | owner-approved / verification pending | +| TRACE-AUTOADVANCE-005 | REQ-AUTOADVANCE-005 | approved plan step1-5; file anchors added as implemented | VER-AUTOADVANCE-005 | VAL-AUTOADVANCE-005 | owner-approved / verification pending | +| TRACE-AUTOADVANCE-006 | REQ-AUTOADVANCE-006 | approved plan step1-5; file anchors added as implemented | VER-AUTOADVANCE-006 | VAL-AUTOADVANCE-006 | owner-approved / verification pending | +| TRACE-AUTOADVANCE-007 | REQ-AUTOADVANCE-007 | approved plan step1-5; file anchors added as implemented | VER-AUTOADVANCE-007 | VAL-AUTOADVANCE-007 | owner-approved / verification pending | +| TRACE-AUTOADVANCE-008 | REQ-AUTOADVANCE-008 | approved plan step1-5; file anchors added as implemented | VER-AUTOADVANCE-008 | VAL-AUTOADVANCE-008 | owner-approved / verification pending | + +## Traceability Matrix + +| Implementation | Requirement | Trace | Verification | Validation | Status | +| --- | --- | --- | --- | --- | --- | +| src/dc_overview/release_policy.py | REQ-AUTOADVANCE-002 | TRACE-AUTOADVANCE-002 | VER-AUTOADVANCE-002 | VAL-AUTOADVANCE-002 | owner-approved | +| src/dc_overview/release_broker.py | REQ-AUTOADVANCE-002 | TRACE-AUTOADVANCE-002 | VER-AUTOADVANCE-002 | VAL-AUTOADVANCE-002 | owner-approved | +| src/dc_overview/fleet_upgrade.py | REQ-AUTOADVANCE-002 | TRACE-AUTOADVANCE-002 | VER-AUTOADVANCE-002 | VAL-AUTOADVANCE-002 | owner-approved | +| src/dc_overview/cli.py | REQ-AUTOADVANCE-002 | TRACE-AUTOADVANCE-002 | VER-AUTOADVANCE-002 | VAL-AUTOADVANCE-002 | owner-approved | +| src/dc_overview/release_policy.py | REQ-AUTOADVANCE-003 | TRACE-AUTOADVANCE-003 | VER-AUTOADVANCE-003 | VAL-AUTOADVANCE-003 | owner-approved | +| src/dc_overview/release_policy.py | REQ-AUTOADVANCE-004 | TRACE-AUTOADVANCE-004 | VER-AUTOADVANCE-004 | VAL-AUTOADVANCE-004 | owner-approved | +| src/dc_overview/cli.py | REQ-AUTOADVANCE-004 | TRACE-AUTOADVANCE-004 | VER-AUTOADVANCE-004 | VAL-AUTOADVANCE-004 | owner-approved | +| src/dc_overview/templates/systemd/dc-overview-release-refresh.service | REQ-AUTOADVANCE-004 | TRACE-AUTOADVANCE-004 | VER-AUTOADVANCE-004 | VAL-AUTOADVANCE-004 | owner-approved | +| src/dc_overview/templates/systemd/dc-overview-release-refresh.timer | REQ-AUTOADVANCE-004 | TRACE-AUTOADVANCE-004 | VER-AUTOADVANCE-004 | VAL-AUTOADVANCE-004 | owner-approved | +| src/dc_overview/release_policy.py | REQ-AUTOADVANCE-005 | TRACE-AUTOADVANCE-005 | VER-AUTOADVANCE-005 | VAL-AUTOADVANCE-005 | owner-approved | +| src/dc_overview/release_broker.py | REQ-AUTOADVANCE-005 | TRACE-AUTOADVANCE-005 | VER-AUTOADVANCE-005 | VAL-AUTOADVANCE-005 | owner-approved | +| src/dc_overview/fleet_upgrade.py | REQ-AUTOADVANCE-005 | TRACE-AUTOADVANCE-005 | VER-AUTOADVANCE-005 | VAL-AUTOADVANCE-005 | owner-approved | +| tests/test_release_policy.py | REQ-AUTOADVANCE-008 | TRACE-AUTOADVANCE-008 | VER-AUTOADVANCE-008 | VAL-AUTOADVANCE-008 | owner-approved | + ## GPU alert quality mapping | Requirement | Trace | Verification | Validation | Implementation | Status |