diff --git a/README.md b/README.md index cd1c800..13fefb3 100644 --- a/README.md +++ b/README.md @@ -164,6 +164,19 @@ dashboard_app.py http://127.0.0.1:5000/ ``` +`python dashboard_app.py` uses `create_reviewer_app()`, bound to +`127.0.0.1:5000` with `debug=False`. Reviewer = no HTTP command execution +route: `/commands//run` is not registered, including for valid +command IDs. GET displays, HEAD, and Flask's automatic OPTIONS remain +available; request parameters, cookies, headers, and bodies cannot switch +factories. + +Legacy `create_app(reports_dir=None, execution_logs_dir=None)` retains its +existing fixed-command registry and POST execution route for compatibility. +It is outside the interview Reviewer entry point. The repository still has +CLI and legacy execution capabilities; this change does not grant live access. +Both factories share the same GET handlers and evidence presentation. + Its current public review surfaces include: | Route | Current purpose | diff --git a/dashboard_app.py b/dashboard_app.py index 23f892c..f1c3542 100644 --- a/dashboard_app.py +++ b/dashboard_app.py @@ -1847,6 +1847,24 @@ def ai_intent_safety_boundaries() -> List[str]: def create_app( reports_dir: Optional[Path] = None, execution_logs_dir: Optional[Path] = None, +) -> Flask: + """Legacy dashboard with the existing fixed-command execution route.""" + return _create_dashboard_app(reports_dir, execution_logs_dir, reviewer_only=False) + + +def create_reviewer_app( + reports_dir: Optional[Path] = None, + execution_logs_dir: Optional[Path] = None, +) -> Flask: + """Display-only dashboard; HTTP command execution is not registered.""" + return _create_dashboard_app(reports_dir, execution_logs_dir, reviewer_only=True) + + +def _create_dashboard_app( + reports_dir: Optional[Path], + execution_logs_dir: Optional[Path], + *, + reviewer_only: bool, ) -> Flask: if Flask is None: raise RuntimeError( @@ -1941,18 +1959,19 @@ def commands(): recent_logs=logs[:5], ) - @app.post("/commands//run") - def run_command(command_id: str): - registry = build_command_registry(PROJECT_ROOT) - try: - log = execute_registered_command( - registry, - command_id, - app.config["EXECUTION_LOGS_DIR"], - ) - except (KeyError, CommandUnavailableError): - abort(404) - return redirect(url_for("command_log_detail", log_id=log["log_id"])) + if not reviewer_only: + @app.post("/commands//run") + def run_command(command_id: str): + registry = build_command_registry(PROJECT_ROOT) + try: + log = execute_registered_command( + registry, + command_id, + app.config["EXECUTION_LOGS_DIR"], + ) + except (KeyError, CommandUnavailableError): + abort(404) + return redirect(url_for("command_log_detail", log_id=log["log_id"])) @app.route("/commands/logs") def command_logs(): @@ -2072,4 +2091,4 @@ def inject_helpers(): if __name__ == "__main__": - create_app().run(host="127.0.0.1", port=5000, debug=False) + create_reviewer_app().run(host="127.0.0.1", port=5000, debug=False) diff --git a/tests/test_dashboard_app.py b/tests/test_dashboard_app.py index 044c58e..44ef891 100644 --- a/tests/test_dashboard_app.py +++ b/tests/test_dashboard_app.py @@ -1442,3 +1442,115 @@ def test_flask_routes_are_available(tmp_path): assert html_response.status_code == 200 json_response = client.get("/reports/json/router1/day9_performance_regression_report.json") assert json_response.status_code == 200 + + +@pytest.fixture +def reviewer_surface(tmp_path): + reports_dir = tmp_path / "reports" + write_json(reports_dir / "router1" / "sample.json", {"result": "PASS", "fixture": "reviewer-evidence"}) + (reports_dir / "router1" / "sample.html").write_text("reviewer-evidence", encoding="utf-8") + logs_dir = tmp_path / "execution_logs" + app = dashboard.create_reviewer_app(reports_dir, logs_dir) + app.testing = True + return app, tmp_path, reports_dir, logs_dir + + +def test_reviewer_route_inventory_preserves_shared_get_handlers(reviewer_surface): + reviewer, _, reports_dir, logs_dir = reviewer_surface + legacy = dashboard.create_app(reports_dir, logs_dir) + legacy_get = {rule.rule: rule.endpoint for rule in legacy.url_map.iter_rules() if "GET" in rule.methods} + reviewer_get = {rule.rule: rule.endpoint for rule in reviewer.url_map.iter_rules()} + assert reviewer_get == legacy_get + assert "run_command" not in reviewer.view_functions + assert all(rule.methods <= {"GET", "HEAD", "OPTIONS"} for rule in reviewer.url_map.iter_rules()) + for endpoint in legacy_get.values(): + assert reviewer.view_functions[endpoint].__code__ is legacy.view_functions[endpoint].__code__ + assert any(rule.rule == "/commands//run" and "POST" in rule.methods for rule in legacy.url_map.iter_rules()) + + +@pytest.mark.parametrize("method", ["POST", "PUT", "PATCH", "DELETE"]) +def test_reviewer_rejects_requests_without_execution_or_writes(reviewer_surface, monkeypatch, method): + import subprocess + from unittest.mock import Mock + + import dashboard_command_runner as runner + import network_lab + + app, root, _, logs_dir = reviewer_surface + client = app.test_client() + client.set_cookie("reviewer_only", "false") + before = {p.relative_to(root): p.read_bytes() for p in root.rglob("*") if p.is_file()} + guards = {name: Mock(side_effect=AssertionError(name)) for name in ( + "runner", "subprocess", "execution_log", "report_rebuild", "file_write", + )} + with monkeypatch.context() as patch: + patch.setattr(dashboard, "execute_registered_command", guards["runner"]) + patch.setattr(runner, "execute_registered_command", guards["runner"]) + patch.setattr(runner, "execute_command", guards["runner"]) + patch.setattr(subprocess, "run", guards["subprocess"]) + patch.setattr(subprocess, "Popen", guards["subprocess"]) + patch.setattr(runner, "_write_log", guards["execution_log"]) + patch.setattr(network_lab, "write_report_index_html", guards["report_rebuild"]) + for name in ("write_text", "write_bytes", "mkdir", "touch"): + patch.setattr(Path, name, guards["file_write"]) + for command_id in ("pytest_all", "topology_summary", "not_allowed"): + response = client.open( + f"/commands/{command_id}/run?reviewer_only=false&mode=legacy", + method=method, + headers={"X-Reviewer-Only": "false", "X-HTTP-Method-Override": "POST"}, + data={"reviewer_only": "false", "mode": "legacy"}, + ) + assert response.status_code == 404 + for route in ("/", "/reports", "/commands", "/commands/logs", "/ai-checklist", "/ai-intent-reviewer"): + assert client.open(route, method=method).status_code == 405 + for guard in guards.values(): + guard.assert_not_called() + assert not logs_dir.exists() + assert {p.relative_to(root): p.read_bytes() for p in root.rglob("*") if p.is_file()} == before + + +def test_reviewer_get_head_options_and_evidence_remain_display_only(reviewer_surface, monkeypatch): + from unittest.mock import Mock + + app, _, _, _ = reviewer_surface + execution = Mock(side_effect=AssertionError("Reviewer display invoked runner")) + monkeypatch.setattr(dashboard, "execute_registered_command", execution) + client = app.test_client() + routes = ( + "/", "/reports", "/commands", "/commands/logs", "/ai-checklist", "/ai-intent-reviewer", + "/reports/json/router1/sample.json", "/reports/open/router1/sample.html", + "/reports/evidence/reports/router1/sample.html", + ) + for route in routes: + with client.get(route) as response: + assert response.status_code == 200 + if "sample" in route: + assert b"reviewer-evidence" in response.data + with client.head(route) as response: + assert response.status_code == 200 + assert response.data == b"" + with client.options(route) as response: + assert response.status_code == 200 + assert set(response.allow) == {"GET", "HEAD", "OPTIONS"} + for method in ("GET", "HEAD", "OPTIONS"): + assert client.open("/commands/pytest_all/run", method=method).status_code == 404 + assert client.get("/reports/open/../outside.html").status_code == 404 + execution.assert_not_called() + + +def test_legacy_fixed_command_post_contract_remains_compatible(tmp_path, monkeypatch): + from unittest.mock import Mock + + execution = Mock(return_value={"log_id": "synthetic_legacy_result"}) + monkeypatch.setattr(dashboard, "execute_registered_command", execution) + logs_dir = tmp_path / "execution_logs" + app = dashboard.create_app(tmp_path / "reports", logs_dir) + response = app.test_client().post("/commands/topology_summary/run") + assert response.status_code == 302 + assert response.headers["Location"] == "/commands/logs/synthetic_legacy_result" + execution.assert_called_once() + registry, command_id, actual_logs_dir = execution.call_args.args + assert command_id == "topology_summary" + assert registry[command_id].enabled + assert actual_logs_dir == logs_dir + assert not logs_dir.exists() diff --git a/tests/test_phase_2n_02_canonical_flask_demo_smoke.py b/tests/test_phase_2n_02_canonical_flask_demo_smoke.py index 25ff403..eb25ad9 100644 --- a/tests/test_phase_2n_02_canonical_flask_demo_smoke.py +++ b/tests/test_phase_2n_02_canonical_flask_demo_smoke.py @@ -3,7 +3,8 @@ from __future__ import annotations import ctypes -from dataclasses import dataclass +import hashlib +from dataclasses import asdict, dataclass import json import ntpath import os @@ -49,6 +50,16 @@ class ChildProcessClassification: unexpected_children: tuple[ChildProcessIdentity, ...] +@dataclass +class LifecycleProgress: + sampling_started: bool = False + sampling_completed: bool = False + classification_completed: bool = False + cleanup_completed: bool = False + post_cleanup_check_completed: bool = False + port_check_completed: bool = False + + def _port_is_listening() -> bool: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe: probe.settimeout(0.25) @@ -339,16 +350,39 @@ def _build_runtime_evidence( process_exit_code: int | None, process_exited: bool, statuses: dict[str, int], + http_requests: list[dict[str, object]], + lifecycle: LifecycleProgress, child_identities: list[ChildProcessIdentity], classification: ChildProcessClassification, post_cleanup_live_child_ids: list[int], unexpected_live_child_ids: list[int], bridge_exited_automatically: bool, port_closed: bool, + report_files_unchanged: bool | None = None, ) -> dict[str, object]: - runtime_bridge_detected = classification.runtime_bridge is not None + methods = sorted({request["method"] for request in http_requests}) + command_posts = [ + request for request in http_requests + if request["method"] == "POST" + and str(request["path"]).startswith("/commands/") + and str(request["path"]).endswith("/run") + ] + classification_verified = lifecycle.sampling_completed and lifecycle.classification_completed + exit_verified = lifecycle.sampling_completed and lifecycle.post_cleanup_check_completed + classification_failed = classification_verified and classification.unexpected_children != () + exit_failed = exit_verified and post_cleanup_live_child_ids != [] + if classification_failed or exit_failed: + identity_status = "FAIL" + elif not (classification_verified and exit_verified and lifecycle.cleanup_completed): + identity_status = "NOT_VERIFIED" + else: + identity_status = "PASS" if bridge_exited_automatically else "FAIL" + exit_status = ("FAIL" if exit_failed else "PASS") if exit_verified else "NOT_VERIFIED" + runtime_bridge_detected = classification_verified and classification.runtime_bridge is not None return { "interpreter_classification": ( + "NOT_VERIFIED" if not classification_verified else + "unexpected_or_unclassified" if classification_failed else "environment_runtime_bridge" if runtime_bridge_detected else "direct_runtime" @@ -361,8 +395,17 @@ def _build_runtime_evidence( "port": PORT, "startup_timeout_seconds": STARTUP_TIMEOUT_SECONDS, "http_statuses": statuses, - "request_method": "GET", - "command_run_post_performed": False, + # Retain the legacy summary keys, but describe actual HTTP attempts. + "request_method": methods[0] if len(methods) == 1 else ("MIXED" if methods else "NOT_ATTEMPTED"), + "request_methods": methods, + "http_requests": http_requests, + "command_run_post_performed": bool(command_posts), + "command_run_post_attempts": command_posts, + "command_execution": { + "status": "NOT_INDEPENDENTLY_MEASURED", + "scope": "Child-process runner/subprocess calls are not instrumented; HTTP rejection alone does not measure execution side effects.", + }, + "report_files_unchanged": report_files_unchanged, "non_local_network_contact_performed": False, "child_process_ids": [child.pid for child in child_identities], "pre_cleanup_child_identities": _generic_child_identity_evidence( @@ -380,16 +423,17 @@ def _build_runtime_evidence( "alive": child.pid in post_cleanup_live_child_ids, } for child in child_identities - ], + ] if exit_verified else [], "unexpected_live_children": unexpected_live_child_ids, - "identity_aware_contract_result": ( - classification.unexpected_children == () - and bridge_exited_automatically - and unexpected_live_child_ids == [] - ), + "lifecycle_progress": asdict(lifecycle), + "cleanup_scope": "Exact spawned parent and stdout; captured-child exit is verified separately.", + "lifecycle_result_semantics": "False with NOT_VERIFIED means unverified, not an observed failure.", + "identity_aware_contract_result": identity_status == "PASS", + "identity_aware_contract_status": identity_status, "process_exit_code": process_exit_code, "process_exited": process_exited, - "child_processes_exited": post_cleanup_live_child_ids == [], + "child_processes_exited": exit_status == "PASS", + "child_processes_exit_status": exit_status, "port_closed": port_closed, } @@ -413,7 +457,34 @@ def _json_string_values( return [] -def _wait_for_get(path: str, process: subprocess.Popen[str]) -> tuple[int, str]: +def _observed_urlopen( + request: Request, + http_requests: list[dict[str, object]], + *, + timeout: float, +): + # Record dispatch attempts, not pre-planned requests or inferred execution. + # None means no HTTP response was observed, including transport failures. + observation = { + "method": request.get_method(), + "path": urlparse(request.full_url).path, + "response_status": None, + } + http_requests.append(observation) + try: + response = urlopen(request, timeout=timeout) + except HTTPError as exc: + observation["response_status"] = exc.code + raise + observation["response_status"] = response.status + return response + + +def _wait_for_get( + path: str, + process: subprocess.Popen[str], + http_requests: list[dict[str, object]], +) -> tuple[int, str]: deadline = time.monotonic() + STARTUP_TIMEOUT_SECONDS last_error = "no response" url = f"{BASE_URL}{path}" @@ -423,7 +494,7 @@ def _wait_for_get(path: str, process: subprocess.Popen[str]) -> tuple[int, str]: pytest.fail(f"Flask exited during startup with code {process.returncode}") try: request = Request(url, method="GET") - with urlopen(request, timeout=1.0) as response: + with _observed_urlopen(request, http_requests, timeout=1.0) as response: return response.status, response.read().decode("utf-8", errors="replace") except (HTTPError, URLError, TimeoutError, ConnectionError, OSError) as exc: last_error = str(exc) @@ -433,12 +504,44 @@ def _wait_for_get(path: str, process: subprocess.Popen[str]) -> tuple[int, str]: ) +def _report_file_hashes() -> dict[str, str]: + return { + path.relative_to(PROJECT_ROOT).as_posix(): hashlib.sha256(path.read_bytes()).hexdigest() + for path in (PROJECT_ROOT / "reports").rglob("*") + if path.is_file() + } + + +def _assert_canonical_reviewer_http_boundary(http_requests: list[dict[str, object]]) -> None: + command_paths = [f"/commands/{key}/run" for key in ("pytest_all", "topology_summary", "not_allowed")] + # Fail before sending any POST if the real entry point accidentally uses Legacy. + for path in command_paths: + with pytest.raises(HTTPError) as rejected: + _observed_urlopen(Request(f"{BASE_URL}{path}", method="OPTIONS"), http_requests, timeout=2) + assert rejected.value.code == 404 + rejected.value.close() + for method, path in [("POST", path) for path in command_paths] + [ + (method, command_paths[1]) for method in ("PUT", "PATCH", "DELETE") + ]: + with pytest.raises(HTTPError) as rejected: + _observed_urlopen(Request(f"{BASE_URL}{path}", data=b"mode=legacy", method=method), http_requests, timeout=2) + assert rejected.value.code == 404 + rejected.value.close() + with _observed_urlopen(Request(f"{BASE_URL}/", method="HEAD"), http_requests, timeout=2) as response: + assert response.status == 200 + assert response.read() == b"" + with _observed_urlopen(Request(f"{BASE_URL}/", method="OPTIONS"), http_requests, timeout=2) as response: + assert response.status == 200 + assert {item.strip() for item in response.headers["Allow"].split(",")} == {"GET", "HEAD", "OPTIONS"} + + def test_canonical_flask_process_lifecycle_and_get_only_routes() -> None: assert not _port_is_listening(), ( "Canonical port 127.0.0.1:5000 is already occupied; the smoke test will " "not terminate an unrelated process or substitute another port." ) _assert_port_can_be_bound() + reports_before = _report_file_hashes() process = subprocess.Popen( [sys.executable, "dashboard_app.py"], @@ -449,24 +552,34 @@ def test_canonical_flask_process_lifecycle_and_get_only_routes() -> None: text=True, ) statuses: dict[str, int] = {} + http_requests: list[dict[str, object]] = [] + report_files_unchanged = None child_identities: list[ChildProcessIdentity] = [] classification = ChildProcessClassification(None, ()) post_cleanup_live_child_ids: list[int] = [] unexpected_live_child_ids: list[int] = [] - bridge_exited_automatically = True + bridge_exited_automatically = False + lifecycle = LifecycleProgress() + process_exited = False + port_closed = False server_output = "" try: - landing_status, landing_html = _wait_for_get("/", process) + landing_status, landing_html = _wait_for_get("/", process, http_requests) statuses["/"] = landing_status assert landing_status == 200 assert "Network Automation Lab - Portfolio Demo" in landing_html for route in GET_ROUTES[1:]: - status, _ = _wait_for_get(route, process) + status, _ = _wait_for_get(route, process, http_requests) statuses[route] = status assert statuses == {route: 200 for route in GET_ROUTES} + _assert_canonical_reviewer_http_boundary(http_requests) + report_files_unchanged = _report_file_hashes() == reports_before + assert report_files_unchanged + lifecycle.sampling_started = True child_identities = _child_process_identities(process.pid) + lifecycle.sampling_completed = True classification = _classify_child_processes( child_identities, parent_pid=process.pid, @@ -474,41 +587,66 @@ def test_canonical_flask_process_lifecycle_and_get_only_routes() -> None: executable=sys.executable, base_executable=getattr(sys, "_base_executable", None), ) + lifecycle.classification_completed = True assert classification.unexpected_children == (), ( "The canonical debug=False Flask entry point unexpectedly spawned " "unclassified child processes: " f"{[child.pid for child in classification.unexpected_children]}" ) finally: - if process.poll() is None: - process.terminate() - try: - process.wait(timeout=5) - except subprocess.TimeoutExpired: - process.kill() - process.wait(timeout=5) - captured_child_ids = [child.pid for child in child_identities] - post_cleanup_live_child_ids = _wait_for_captured_processes_exit( - captured_child_ids - ) - unexpected_live_child_ids = _unexpected_live_child_ids( - captured_child_ids, - post_cleanup_live_child_ids, - ) - bridge_exited_automatically = ( - classification.runtime_bridge is None - or classification.runtime_bridge.pid not in post_cleanup_live_child_ids - ) - if process.stdout is not None: - server_output = process.stdout.read() - process.stdout.close() + original_failure = sys.exc_info()[1] + cleanup_errors: list[Exception] = [] + try: + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + process_exited = process.poll() is not None + except Exception as exc: + cleanup_errors.append(exc) + # An empty captured set is meaningful only after a completed sample. + try: + if lifecycle.sampling_completed: + captured_child_ids = [child.pid for child in child_identities] + post_cleanup_live_child_ids = _wait_for_captured_processes_exit(captured_child_ids) + lifecycle.post_cleanup_check_completed = True + unexpected_live_child_ids = _unexpected_live_child_ids( + captured_child_ids, post_cleanup_live_child_ids, + ) + if lifecycle.classification_completed: + bridge_exited_automatically = ( + classification.runtime_bridge is None + or classification.runtime_bridge.pid not in post_cleanup_live_child_ids + ) + except Exception as exc: + cleanup_errors.append(exc) + try: + if process.stdout is not None: + try: + if process_exited: + server_output = process.stdout.read() + finally: + process.stdout.close() + lifecycle.cleanup_completed = process_exited + except Exception as exc: + cleanup_errors.append(exc) - port_closed = _wait_for_port_closed() + try: + port_closed = _wait_for_port_closed() + lifecycle.port_check_completed = True + except Exception as exc: + cleanup_errors.append(exc) evidence = _build_runtime_evidence( process_pid=process.pid, process_exit_code=process.returncode, - process_exited=process.poll() is not None, + process_exited=process_exited, statuses=statuses, + http_requests=http_requests, + lifecycle=lifecycle, + report_files_unchanged=report_files_unchanged, child_identities=child_identities, classification=classification, post_cleanup_live_child_ids=post_cleanup_live_child_ids, @@ -516,22 +654,45 @@ def test_canonical_flask_process_lifecycle_and_get_only_routes() -> None: bridge_exited_automatically=bridge_exited_automatically, port_closed=port_closed, ) + evidence["cleanup_error_types"] = [type(exc).__name__ for exc in cleanup_errors] print("PHASE_2N_02_RUNTIME_EVIDENCE=" + json.dumps(evidence, sort_keys=True)) - assert process.poll() is not None, "The exact spawned Flask process did not exit" - assert classification.unexpected_children == (), ( - "Unexpected Flask child processes remained unclassified" - ) - assert bridge_exited_automatically, ( - "The accepted Windows environment runtime bridge did not exit automatically" - ) - assert unexpected_live_child_ids == [], ( - "Captured child processes remained alive after exact parent cleanup: " - f"{unexpected_live_child_ids}" - ) - assert port_closed, "Canonical port 127.0.0.1:5000 remained open after shutdown" + if cleanup_errors: + if original_failure is None: + raise cleanup_errors[0] + original_failure.add_note( + "Lifecycle cleanup/observation also failed: " + + ", ".join(evidence["cleanup_error_types"]) + ) + + # Do not replace an earlier failure with a cleanup assertion. + assert process.poll() is not None, "The exact spawned Flask process did not exit" + assert classification.unexpected_children == (), ( + "Unexpected Flask child processes remained unclassified" + ) + assert bridge_exited_automatically, ( + "The accepted Windows environment runtime bridge did not exit automatically" + ) + assert unexpected_live_child_ids == [], ( + "Captured child processes remained alive after exact parent cleanup: " + f"{unexpected_live_child_ids}" + ) + assert port_closed, "Canonical port 127.0.0.1:5000 remained open after shutdown" assert process.returncode is not None assert "Running on http://127.0.0.1:5000" in server_output + assert evidence["identity_aware_contract_result"] is True + assert evidence["identity_aware_contract_status"] == "PASS" + assert evidence["child_processes_exited"] is True + assert evidence["child_processes_exit_status"] == "PASS" + assert evidence["command_run_post_performed"] is True + assert evidence["command_run_post_attempts"] == [ + {"method": "POST", "path": f"/commands/{key}/run", "response_status": 404} + for key in ("pytest_all", "topology_summary", "not_allowed") + ] + assert evidence["request_method"] == "MIXED" + assert evidence["request_methods"] == ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"] + assert evidence["report_files_unchanged"] is True + assert evidence["command_execution"]["status"] == "NOT_INDEPENDENTLY_MEASURED" SYNTHETIC_PARENT_PID = 100 @@ -568,6 +729,7 @@ def _synthetic_classification( def _synthetic_runtime_evidence( child: ChildProcessIdentity, + http_requests: list[dict[str, object]] | None = None, ) -> dict[str, object]: classification = _synthetic_classification([child]) return _build_runtime_evidence( @@ -575,6 +737,11 @@ def _synthetic_runtime_evidence( process_exit_code=0, process_exited=True, statuses={route: 200 for route in GET_ROUTES}, + http_requests=http_requests if http_requests is not None else [], + lifecycle=LifecycleProgress( + sampling_started=True, sampling_completed=True, classification_completed=True, + cleanup_completed=True, post_cleanup_check_completed=True, port_check_completed=True, + ), child_identities=[child], classification=classification, post_cleanup_live_child_ids=[], @@ -616,6 +783,11 @@ def test_runtime_evidence_redacts_supplied_private_path_values() -> None: unexpected_live_child_ids=[], bridge_exited_automatically=True, port_closed=True, + http_requests=[], + lifecycle=LifecycleProgress( + sampling_started=True, sampling_completed=True, classification_completed=True, + cleanup_completed=True, post_cleanup_check_completed=True, port_check_completed=True, + ), ) assert "interpreter" not in evidence @@ -630,6 +802,58 @@ def test_runtime_evidence_redacts_supplied_private_path_values() -> None: ) +def test_runtime_evidence_before_http_does_not_claim_post_or_execution() -> None: + evidence = _synthetic_runtime_evidence(_synthetic_child()) + assert evidence["command_run_post_performed"] is False + assert evidence["command_run_post_attempts"] == [] + assert evidence["request_method"] == "NOT_ATTEMPTED" + assert evidence["request_methods"] == [] + assert evidence["report_files_unchanged"] is None + assert evidence["command_execution"]["status"] == "NOT_INDEPENDENTLY_MEASURED" + + +@pytest.mark.parametrize( + "failure_method,failure_status,post_count", + [("OPTIONS", 405, 0), ("POST", 503, 2), ("POST", None, 2)], +) +def test_runtime_evidence_preserves_partial_http_attempts( + monkeypatch, failure_method, failure_status, post_count, +) -> None: + calls = [] + observations = [] + + def fake_urlopen(request, *, timeout): + method = request.get_method() + calls.append(method) + failing = method == failure_method and ( + method == "OPTIONS" or calls.count("POST") == 2 + ) + if failing and failure_status is None: + raise URLError("synthetic transport failure") + raise HTTPError( + request.full_url, failure_status if failing else 404, + "synthetic rejection", {}, None, + ) + + monkeypatch.setattr(sys.modules[__name__], "urlopen", fake_urlopen) + expected_error = URLError if failure_status is None else AssertionError + with pytest.raises(expected_error): + _assert_canonical_reviewer_http_boundary(observations) + + evidence = _synthetic_runtime_evidence(_synthetic_child(), observations) + assert calls.count("POST") == post_count + assert evidence["command_run_post_performed"] is (post_count > 0) + assert evidence["command_run_post_attempts"] == [ + {"method": "POST", "path": f"/commands/{key}/run", "response_status": status} + for key, status in zip(("pytest_all", "topology_summary"), (404, failure_status)) + ][:post_count] + assert evidence["http_requests"][-1]["response_status"] == failure_status + assert evidence["request_methods"] == sorted(set(calls)) + assert evidence["request_method"] == ("MIXED" if post_count else "OPTIONS") + assert evidence["report_files_unchanged"] is None + assert evidence["command_execution"]["status"] == "NOT_INDEPENDENTLY_MEASURED" + + def test_runtime_evidence_exposes_generic_bridge_classification() -> None: evidence = _synthetic_runtime_evidence(_synthetic_child()) @@ -639,6 +863,200 @@ def test_runtime_evidence_exposes_generic_bridge_classification() -> None: assert evidence["executable_paths_redacted"] is True +@pytest.fixture +def mocked_canonical_lifecycle(monkeypatch): + from types import SimpleNamespace + from unittest.mock import MagicMock, Mock + + module = sys.modules[__name__] + process = Mock(pid=SYNTHETIC_PARENT_PID, returncode=None) + process.poll.side_effect = lambda: process.returncode + process.terminate.side_effect = lambda: setattr(process, "returncode", 1) + process.stdout.read.return_value = "Running on http://127.0.0.1:5000" + state = SimpleNamespace( + html=b"Network Automation Lab - Portfolio Demo", options_status=404, + process=process, popen=Mock(return_value=process), + hashes=Mock(side_effect=[{"fixture": "same"}, {"fixture": "same"}]), + sample=Mock(return_value=[]), classify=Mock(wraps=_classify_child_processes), + exit_check=Mock(return_value=[]), port_check=Mock(return_value=True), + ) + + def fake_urlopen(request, *, timeout): + method = request.get_method() + if urlparse(request.full_url).path.startswith("/commands/"): + raise HTTPError( + request.full_url, state.options_status if method == "OPTIONS" else 404, + "synthetic rejection", {}, None, + ) + response = MagicMock(status=200, headers={"Allow": "GET, HEAD, OPTIONS"}) + response.__enter__.return_value = response + response.read.return_value = b"" if method == "HEAD" else state.html + return response + + monkeypatch.setattr(module, "urlopen", fake_urlopen) + monkeypatch.setattr(subprocess, "Popen", state.popen) + monkeypatch.setattr(socket, "socket", Mock(side_effect=AssertionError("Unexpected real socket"))) + monkeypatch.setattr(module, "_port_is_listening", Mock(return_value=False)) + monkeypatch.setattr(module, "_assert_port_can_be_bound", Mock()) + monkeypatch.setattr(module, "_report_file_hashes", state.hashes) + monkeypatch.setattr(module, "_child_process_identities", state.sample) + monkeypatch.setattr(module, "_classify_child_processes", state.classify) + monkeypatch.setattr(module, "_wait_for_captured_processes_exit", state.exit_check) + monkeypatch.setattr(module, "_wait_for_port_closed", state.port_check) + return state + + +def _captured_runtime_receipt(capsys) -> dict[str, object]: + prefix = "PHASE_2N_02_RUNTIME_EVIDENCE=" + receipts = [line[len(prefix):] for line in capsys.readouterr().out.splitlines() if line.startswith(prefix)] + assert len(receipts) == 1 + return json.loads(receipts[0]) + + +@pytest.mark.parametrize("failure_stage", ["GET", "OPTIONS", "HASH"]) +def test_lifecycle_early_failure_receipt_is_unverified( + mocked_canonical_lifecycle, capsys, failure_stage, +) -> None: + runtime = mocked_canonical_lifecycle + if failure_stage == "GET": + runtime.html = b"Unexpected landing page" + elif failure_stage == "OPTIONS": + runtime.options_status = 405 + else: + runtime.hashes.side_effect = [{"fixture": "before"}, {"fixture": "after"}] + + with pytest.raises(AssertionError) as failure: + test_canonical_flask_process_lifecycle_and_get_only_routes() + expected_origin = ( + "_assert_canonical_reviewer_http_boundary" if failure_stage == "OPTIONS" + else "test_canonical_flask_process_lifecycle_and_get_only_routes" + ) + assert failure.traceback[-1].name == expected_origin + evidence = _captured_runtime_receipt(capsys) + assert evidence["lifecycle_progress"] == { + "sampling_started": False, "sampling_completed": False, + "classification_completed": False, "cleanup_completed": True, + "post_cleanup_check_completed": False, "port_check_completed": True, + } + assert evidence["identity_aware_contract_result"] is False + assert evidence["identity_aware_contract_status"] == "NOT_VERIFIED" + assert evidence["child_processes_exited"] is False + assert evidence["child_processes_exit_status"] == "NOT_VERIFIED" + assert evidence["interpreter_classification"] == "NOT_VERIFIED" + assert evidence["process_exited"] is True + assert evidence["port_closed"] is True + assert evidence["cleanup_error_types"] == [] + assert evidence["command_run_post_performed"] is (failure_stage == "HASH") + assert len(evidence["command_run_post_attempts"]) == (3 if failure_stage == "HASH" else 0) + assert all(item["response_status"] == 404 for item in evidence["command_run_post_attempts"]) + assert evidence["report_files_unchanged"] is (False if failure_stage == "HASH" else None) + runtime.sample.assert_not_called() + runtime.classify.assert_not_called() + runtime.exit_check.assert_not_called() + runtime.process.terminate.assert_called_once() + runtime.process.stdout.close.assert_called_once() + + +@pytest.mark.parametrize("unexpected,still_alive", [(False, False), (True, False), (True, True)]) +def test_lifecycle_completed_observations_keep_independent_results( + mocked_canonical_lifecycle, capsys, unexpected, still_alive, +) -> None: + runtime = mocked_canonical_lifecycle + if unexpected: + runtime.sample.return_value = [_synthetic_child(filename="unknown.exe", full_image_path=None)] + if still_alive: + runtime.exit_check.return_value = [SYNTHETIC_CHILD_PID] + if unexpected: + with pytest.raises(AssertionError, match="unexpectedly spawned unclassified child processes"): + test_canonical_flask_process_lifecycle_and_get_only_routes() + else: + test_canonical_flask_process_lifecycle_and_get_only_routes() + evidence = _captured_runtime_receipt(capsys) + assert all(evidence["lifecycle_progress"].values()) + assert evidence["identity_aware_contract_result"] is (not unexpected) + assert evidence["identity_aware_contract_status"] == ("FAIL" if unexpected else "PASS") + assert evidence["child_processes_exited"] is (not still_alive) + assert evidence["child_processes_exit_status"] == ("FAIL" if still_alive else "PASS") + assert evidence["command_run_post_performed"] is True + assert len(evidence["command_run_post_attempts"]) == 3 + assert evidence["process_exited"] is True + runtime.sample.assert_called_once_with(SYNTHETIC_PARENT_PID) + runtime.exit_check.assert_called_once_with([SYNTHETIC_CHILD_PID] if unexpected else []) + + +@pytest.mark.parametrize("failure_stage", ["sampling", "classification"]) +def test_lifecycle_incomplete_observation_preserves_original_error( + mocked_canonical_lifecycle, capsys, failure_stage, +) -> None: + runtime = mocked_canonical_lifecycle + original = OSError("Synthetic observation failure") + (runtime.sample if failure_stage == "sampling" else runtime.classify).side_effect = original + with pytest.raises(OSError) as failure: + test_canonical_flask_process_lifecycle_and_get_only_routes() + assert failure.value is original + evidence = _captured_runtime_receipt(capsys) + sampled = failure_stage == "classification" + assert evidence["lifecycle_progress"]["sampling_started"] is True + assert evidence["lifecycle_progress"]["sampling_completed"] is sampled + assert evidence["lifecycle_progress"]["classification_completed"] is False + assert evidence["lifecycle_progress"]["post_cleanup_check_completed"] is sampled + assert evidence["identity_aware_contract_status"] == "NOT_VERIFIED" + assert evidence["identity_aware_contract_result"] is False + assert evidence["child_processes_exited"] is sampled + assert evidence["child_processes_exit_status"] == ("PASS" if sampled else "NOT_VERIFIED") + assert evidence["interpreter_classification"] == "NOT_VERIFIED" + assert evidence["process_exited"] is True + + +@pytest.mark.parametrize("failed_cleanup", ["stdout", "port"]) +def test_lifecycle_cleanup_error_does_not_mask_get_failure( + mocked_canonical_lifecycle, capsys, failed_cleanup, +) -> None: + runtime = mocked_canonical_lifecycle + runtime.html = b"Unexpected landing page" + operation = runtime.process.stdout.close if failed_cleanup == "stdout" else runtime.port_check + operation.side_effect = OSError("Synthetic cleanup failure") + with pytest.raises(AssertionError, match="Network Automation Lab - Portfolio Demo") as failure: + test_canonical_flask_process_lifecycle_and_get_only_routes() + assert failure.traceback[-1].name == "test_canonical_flask_process_lifecycle_and_get_only_routes" + evidence = _captured_runtime_receipt(capsys) + assert evidence["cleanup_error_types"] == ["OSError"] + assert evidence["lifecycle_progress"]["cleanup_completed"] is (failed_cleanup != "stdout") + assert evidence["lifecycle_progress"]["port_check_completed"] is (failed_cleanup != "port") + assert evidence["identity_aware_contract_status"] == "NOT_VERIFIED" + assert evidence["child_processes_exit_status"] == "NOT_VERIFIED" + assert evidence["process_exited"] is True + runtime.process.terminate.assert_called_once() + runtime.process.stdout.close.assert_called_once() + + +@pytest.mark.parametrize("unexpected", [False, True]) +def test_lifecycle_failed_exit_inspection_cannot_claim_children_exited( + mocked_canonical_lifecycle, capsys, unexpected, +) -> None: + runtime = mocked_canonical_lifecycle + original = OSError("Synthetic exit inspection failure") + runtime.exit_check.side_effect = original + if unexpected: + runtime.sample.return_value = [_synthetic_child(filename="unknown.exe", full_image_path=None)] + with pytest.raises(AssertionError, match="unexpectedly spawned unclassified child processes"): + test_canonical_flask_process_lifecycle_and_get_only_routes() + else: + with pytest.raises(OSError) as failure: + test_canonical_flask_process_lifecycle_and_get_only_routes() + assert failure.value is original + evidence = _captured_runtime_receipt(capsys) + assert evidence["lifecycle_progress"]["sampling_completed"] is True + assert evidence["lifecycle_progress"]["classification_completed"] is True + assert evidence["lifecycle_progress"]["post_cleanup_check_completed"] is False + assert evidence["identity_aware_contract_status"] == ("FAIL" if unexpected else "NOT_VERIFIED") + assert evidence["identity_aware_contract_result"] is False + assert evidence["child_processes_exit_status"] == "NOT_VERIFIED" + assert evidence["child_processes_exited"] is False + assert evidence["post_cleanup_child_state"] == [] + assert evidence["cleanup_error_types"] == ["OSError"] + + def test_runtime_bridge_classifier_accepts_exact_single_base_executable() -> None: classification = _synthetic_classification([_synthetic_child()]) assert classification.runtime_bridge == _synthetic_child()