| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503 |
- #!/usr/bin/env python3
- """Validate Qt-clean v1 against a running backend; read-only unless requested.
- No firmware parameters or AMT/MT algorithms are submitted by this driver.
- --start explicitly authorizes one host start/reset. --drive-default-plan additionally
- continues UIP with CR and exits AMT, ending at the actual UEFI Shell prompt.
- Protocol PASS never means that memory tests passed.
- """
- from __future__ import annotations
- import argparse
- import asyncio
- import contextlib
- import datetime as dt
- import json
- import os
- from pathlib import Path
- import sys
- import time
- from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
- import uuid
- import aiohttp
- TERMINAL = {"succeeded", "failed", "interrupted", "cancelled"}
- STAGE_RANK = {"unknown": -1, "idle": -1, "boot": 0, "booting": 0,
- "uip": 1, "uip1": 1, "training": 2, "rmt": 3, "amt": 4,
- "uip2": 5, "post": 5, "uefi": 6, "mt": 7}
- PRIVATE_KEYS = {"password", "passwd", "secret", "authorization", "token",
- "firmware_settings", "boot_plan", "boot_execution", "raw_line",
- "raw_sol", "helper_argv", "traceback"}
- def timestamp():
- return dt.datetime.now(dt.timezone.utc).isoformat()
- def safe_url(url, view=None):
- p = urlsplit(url)
- host = p.hostname or ""
- if ":" in host:
- host = "[" + host + "]"
- if p.port:
- host += ":" + str(p.port)
- values = [(k, v) for k, v in parse_qsl(p.query) if k == "view"]
- if view is not None:
- values = [("view", view)]
- return urlunsplit((p.scheme, host, p.path or "/ws", urlencode(values), ""))
- def private_fields(value, path=""):
- found = []
- if isinstance(value, dict):
- for key, item in value.items():
- low = str(key).lower()
- here = path + "." + str(key)
- if low in PRIVATE_KEYS or low.endswith("_password") or low.endswith("_secret"):
- found.append(here)
- found.extend(private_fields(item, here))
- elif isinstance(value, list):
- for i, item in enumerate(value):
- found.extend(private_fields(item, f"{path}[{i}]"))
- return found
- def station_summary(station):
- return {key: station.get(key) for key in (
- "station_id", "connection", "power", "phase", "run_state",
- "started_unix_ms", "boot_id", "verdict", "input", "command")}
- class RpcFailure(RuntimeError):
- def __init__(self, method, error):
- self.method, self.error = method, error or {}
- super().__init__(f"{method}: {self.error.get('code', 'ERROR')}: "
- f"{self.error.get('message', '')}")
- class Evidence:
- def __init__(self, args):
- self.path = Path(args.output).expanduser().resolve()
- self.token = os.environ.get(args.token_env, "") if args.token_env else ""
- self.data = {
- "schema": "qt-clean-validation-v1", "started_utc": timestamp(),
- "endpoint": safe_url(args.url), "station_id": args.station,
- "requested": {"start": args.start, "drive_default_plan": args.drive_default_plan,
- "check_unconfigured": args.check_unconfigured,
- "grpc": bool(args.grpc_address)},
- "checks": [], "commands": [], "state_transitions": [], "logs": [],
- "protocol_verdict": "RUNNING", "memory_verdict": "NOT_TESTED",
- "memory_verdict_reason": "This driver does not run AMT or MT; reaching UEFI is not memory PASS.",
- }
- def save(self):
- self.path.parent.mkdir(parents=True, exist_ok=True)
- tmp = self.path.with_suffix(self.path.suffix + ".tmp")
- tmp.write_text(json.dumps(self._redacted(self.data), ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
- tmp.replace(self.path)
- def _redacted(self, value):
- if isinstance(value, dict):
- return {key: ("[REDACTED]" if str(key).lower() in PRIVATE_KEYS
- or str(key).lower().endswith(("_password", "_secret", "_token"))
- else self._redacted(item)) for key, item in value.items()}
- if isinstance(value, list):
- return [self._redacted(item) for item in value]
- if isinstance(value, str) and self.token:
- return value.replace(self.token, "[REDACTED]")
- return value
- def check(self, name, passed, detail=None, *, skipped=False):
- row = {"name": name, "status": "SKIP" if skipped else "PASS" if passed else "FAIL",
- "at_utc": timestamp()}
- if detail is not None:
- row["detail"] = detail
- self.data["checks"].append(row)
- print(json.dumps(self._redacted(row), ensure_ascii=False), flush=True)
- self.save()
- return bool(passed)
- def fail_count(self):
- return sum(row["status"] == "FAIL" for row in self.data["checks"])
- class WsClient:
- def __init__(self, session, url, evidence, token="", *, record_push=True):
- self.session, self.url, self.evidence = session, url, evidence
- self.headers = {"Authorization": "Bearer " + token} if token else {}
- self.record_push = record_push
- self.ws = self.reader = None
- self.pending = {}
- self.counter = 0
- self.state = None
- self.state_count = 0
- self.first_state = asyncio.Event()
- self.last_summary = {}
- self.protocol_errors = []
- async def __aenter__(self):
- self.ws = await self.session.ws_connect(self.url, heartbeat=20, headers=self.headers)
- self.reader = asyncio.create_task(self._read())
- return self
- async def __aexit__(self, *exc):
- await self.ws.close()
- self.reader.cancel()
- with contextlib.suppress(asyncio.CancelledError):
- await self.reader
- async def _read(self):
- try:
- async for message in self.ws:
- if message.type != aiohttp.WSMsgType.TEXT:
- if message.type == aiohttp.WSMsgType.ERROR:
- raise RuntimeError("WebSocket stream error")
- continue
- try:
- frame = json.loads(message.data)
- except (TypeError, ValueError):
- self.protocol_errors.append("non-JSON text response")
- continue
- if not isinstance(frame, dict):
- self.protocol_errors.append("response is not an object")
- continue
- request_id = frame.get("id")
- if request_id in self.pending:
- future = self.pending.pop(request_id)
- if not future.done():
- future.set_result(frame)
- elif frame.get("event") == "state":
- state = frame.get("result")
- if isinstance(state, dict):
- self.state = state
- self.state_count += 1
- self.first_state.set()
- if self.record_push:
- self._record_state(state)
- else:
- self.protocol_errors.append("state push result is not an object")
- elif frame.get("event") == "bios_uart" and self.record_push:
- result = frame.get("result", {})
- if isinstance(result, dict):
- self.evidence.data["logs"].append({"station_id": result.get("station_id"),
- "session_id": result.get("session_id"), "offset": result.get("offset"),
- "next_offset": result.get("next_offset"), "raw_bytes": len(result.get("data_base64", "")) * 3 // 4})
- self.evidence.data["logs"] = self.evidence.data["logs"][-4000:]
- elif request_id is not None:
- self.protocol_errors.append("unmatched response id")
- except Exception as exc:
- for future in self.pending.values():
- if not future.done():
- future.set_exception(RuntimeError(type(exc).__name__ + ": " + str(exc)))
- def _record_state(self, state):
- for station in state.get("stations", []):
- if not isinstance(station, dict):
- continue
- summary = station_summary(station)
- # Ignore naturally changing counters/timestamps unless the useful state changed.
- key = {k: summary.get(k) for k in ("connection", "power", "phase", "run_state",
- "boot_id", "verdict", "input", "command")}
- sid = station.get("station_id", "")
- if key != self.last_summary.get(sid):
- self.last_summary[sid] = key
- self.evidence.data["state_transitions"].append({"received_utc": timestamp(), **summary})
- self.evidence.data["state_transitions"] = self.evidence.data["state_transitions"][-4000:]
- if sid == self.evidence.data["station_id"]:
- print(json.dumps({"station": sid, "phase": summary.get("phase"),
- "run_state": summary.get("run_state"),
- "power": summary.get("power"),
- "input_stage": (summary.get("input") or {}).get("stage")},
- ensure_ascii=False), flush=True)
- async def raw_call(self, method, params=None, *, version=1, timeout=20):
- self.counter += 1
- request_id = f"verify-{self.counter}-{uuid.uuid4().hex[:8]}"
- frame = {"v": version, "id": request_id, "method": method,
- "params": {} if params is None else params}
- future = asyncio.get_running_loop().create_future()
- self.pending[request_id] = future
- await self.ws.send_json(frame)
- try:
- response = await asyncio.wait_for(future, timeout)
- finally:
- self.pending.pop(request_id, None)
- if response.get("id") != request_id or response.get("v") != 1:
- raise AssertionError("Invalid response request id or version")
- return response
- async def call(self, method, params=None, timeout=20):
- response = await self.raw_call(method, params, timeout=timeout)
- if response.get("ok") is not True:
- raise RpcFailure(method, response.get("error"))
- return response.get("result")
- async def get_state(self):
- state = await self.call("GetState")
- if not isinstance(state, dict):
- raise AssertionError("GetState result must be an object")
- self.state = state
- return state
- async def station(self, station_id):
- state = await self.get_state()
- return next(s for s in state.get("stations", []) if s.get("station_id") == station_id)
- async def wait_command(client, command_id, deadline):
- while time.monotonic() < deadline:
- result = await client.call("GetCommand", {"command_id": command_id})
- if result.get("state") in TERMINAL:
- return result
- await asyncio.sleep(.5)
- raise TimeoutError(f"Command {command_id} did not become terminal")
- async def reject_check(client, evidence, name, method, params, codes, **kwargs):
- frame = await client.raw_call(method, params, **kwargs)
- error = frame.get("error") or {}
- evidence.check(name, frame.get("ok") is False and error.get("code") in codes,
- {"code": error.get("code"), "message": error.get("message")})
- async def readonly_checks(client, evidence, args, session, token):
- try:
- await asyncio.wait_for(client.first_state.wait(), 12)
- evidence.check("automatic_initial_state_push", True,
- {"push_count_before_first_request": client.state_count})
- except TimeoutError:
- evidence.check("automatic_initial_state_push", False, "No unsolicited state within 12 seconds")
- state = await client.get_state()
- evidence.data["initial_state"] = state
- evidence.check("state_required_fields", all(k in state for k in
- ("version", "mode", "server_id", "stations")),
- {"version": state.get("version"), "mode": state.get("mode"),
- "server_id": state.get("server_id")})
- stations = state.get("stations", [])
- ids = [row.get("station_id") for row in stations]
- evidence.check("station_ids_unique_and_requested_present", args.station in ids and len(ids) == len(set(ids)), ids)
- required = {"station_id", "connection", "power", "phase", "run_state", "started_unix_ms",
- "boot_id", "verdict", "input", "command", "channels"}
- missing = {row.get("station_id", "?"): sorted(required - set(row)) for row in stations if required - set(row)}
- evidence.check("minimal_station_contract", not missing, missing)
- forbidden = private_fields(state)
- evidence.check("no_internal_or_secret_fields_in_clean_state", not forbidden, forbidden)
- await reject_check(client, evidence, "unknown_rpc_rejected", "NotARealQtMethod", {}, {"UNIMPLEMENTED", "INVALID_ARGUMENT"})
- await reject_check(client, evidence, "unknown_getstate_field_rejected", "GetState", {"unexpected": True}, {"INVALID_ARGUMENT"})
- await reject_check(client, evidence, "invalid_params_type_rejected", "GetState", "invalid", {"INVALID_ARGUMENT"})
- await reject_check(client, evidence, "unsupported_protocol_version_rejected", "GetState", {}, {"INVALID_ARGUMENT"}, version=9)
- await reject_check(client, evidence, "missing_command_rejected", "GetCommand", {"command_id": "verify-missing-" + uuid.uuid4().hex}, {"NOT_FOUND"})
- await reject_check(client, evidence, "event_log_not_in_qt_clean", "ReadEventQueue", {"station_id": args.station}, {"UNIMPLEMENTED"})
- await reject_check(client, evidence, "invalid_uart_offset_rejected", "ReadBiosUart", {"station_id": args.station, "offset": -1}, {"INVALID_ARGUMENT"})
- legacy = {}
- for view in ("full", "qt"):
- async with WsClient(session, safe_url(args.url, view), evidence, token, record_push=False) as old:
- info = await old.call("GetSystemInfo")
- legacy[view] = info
- evidence.check(f"legacy_{view}_GetSystemInfo", isinstance(info, dict) and bool(info.get("version")), info)
- if view == "full":
- listed = await old.call("ListStations")
- evidence.check("legacy_full_ListStations", isinstance(listed, dict) and isinstance(listed.get("stations"), list),
- {"station_count": len(listed.get("stations", []))})
- if args.check_unconfigured:
- ctl = await old.call("GetStationControl", {"station_id": args.check_unconfigured})
- evidence.data["unconfigured_capabilities"] = {
- "station_id": args.check_unconfigured, "capabilities": ctl.get("capabilities", {})}
- evidence.data["legacy_system_info"] = legacy
- evidence.check("legacy_and_clean_version_match", all(info.get("version") == state.get("version") for info in legacy.values()))
- # A second connection gets its own complete initial snapshot, independent of the first.
- async with WsClient(session, args.url, evidence, token, record_push=False) as other:
- await asyncio.wait_for(other.first_state.wait(), 12)
- evidence.check("second_client_gets_initial_snapshot", other.state.get("server_id") == state.get("server_id"))
- evidence.check("first_client_survives_second_disconnect", (await client.get_state()).get("server_id") == state.get("server_id"))
- async def grpc_check(args, evidence, token):
- if not args.grpc_address:
- return
- if args.backend_source:
- sys.path.insert(0, str(Path(args.backend_source).resolve() / "src"))
- try:
- import grpc
- from google.protobuf.empty_pb2 import Empty
- from stl_backend.generated import bench_pb2_grpc
- metadata = (("authorization", "Bearer " + token),) if token else ()
- async with grpc.aio.insecure_channel(args.grpc_address) as channel:
- stub = bench_pb2_grpc.BenchServiceStub(channel)
- info = await stub.GetSystemInfo(Empty(), timeout=15, metadata=metadata)
- stations = await stub.ListStations(Empty(), timeout=15, metadata=metadata)
- evidence.check("native_grpc_readonly_compatibility", bool(info.version) and bool(stations.stations),
- {"version": info.version, "mode": info.mode, "station_count": len(stations.stations)})
- except Exception as exc:
- evidence.check("native_grpc_readonly_compatibility", False, {"error": type(exc).__name__, "message": str(exc)[:500]})
- async def unconfigured_check(client, evidence, args):
- if not args.check_unconfigured:
- return
- caps = evidence.data.get("unconfigured_capabilities", {}).get("capabilities", {})
- if caps.get("bmc_power") is not False:
- evidence.check("unconfigured_station_has_no_power_capability", False,
- "Refused StartTest: full interface did not explicitly report bmc_power=false")
- return
- sid = args.check_unconfigured
- cid = "verify-unconfigured-" + uuid.uuid4().hex
- before = await client.station(sid)
- try:
- accepted = await client.call("StartTest", {"station_id": sid, "command_id": cid})
- result = accepted if accepted.get("state") in TERMINAL else await wait_command(client, cid, time.monotonic() + 45)
- error = result.get("error") or {}
- rejected = result.get("state") == "failed"
- except RpcFailure as exc:
- result, error, rejected = None, exc.error, True
- after = await client.station(sid)
- evidence.data["unconfigured_start"] = {"station_id": sid, "command_id": cid, "result": result, "error": error}
- evidence.check("unconfigured_start_rejected_without_boot", rejected and before.get("boot_id") == after.get("boot_id"),
- {"error": error, "before_power": before.get("power"), "after_power": after.get("power")})
- async def start_test(client, evidence, args):
- station = await client.station(args.station)
- before = station_summary(station)
- cid = "verify-start-" + uuid.uuid4().hex
- params = {"station_id": args.station, "command_id": cid}
- row = {"method": "StartTest", "params": params, "before": before, "sent_utc": timestamp()}
- evidence.data["commands"].append(row)
- evidence.save()
- accepted = await client.call("StartTest", params)
- row["accepted"] = accepted
- replay_pending = await client.call("StartTest", params)
- row["replay_while_pending"] = replay_pending
- evidence.check("start_same_id_pending_replay", accepted.get("command_id") == cid and replay_pending.get("command_id") == cid)
- done = await wait_command(client, cid, time.monotonic() + args.timeout)
- row["completed"] = done
- if not evidence.check("start_command_succeeded", done.get("state") == "succeeded", done):
- raise RuntimeError("Host start did not succeed")
- result = done.get("result") or {}
- expected = {"off": "host_on", "on": "host_reset"}.get(result.get("previous_power"))
- evidence.check("start_power_action_matches_live_power", expected is not None and result.get("power_action") == expected,
- {"previous_power": result.get("previous_power"), "power_action": result.get("power_action")})
- evidence.check("start_requires_new_bios_boot_evidence", result.get("boot_observed") is True and bool(result.get("boot_id"))
- and result.get("boot_id") != result.get("previous_boot_id"),
- {k: result.get(k) for k in ("previous_boot_id", "boot_id", "boot_observed", "started_unix_ms")})
- replay_done = await client.call("StartTest", params)
- row["replay_after_completion"] = replay_done
- evidence.check("start_same_id_completed_replay", replay_done.get("command_id") == cid
- and replay_done.get("state") == "succeeded"
- and (replay_done.get("result") or {}).get("boot_id") == result.get("boot_id"))
- now = await client.station(args.station)
- evidence.data["boot_evidence"] = result
- evidence.data["after_start"] = station_summary(now)
- evidence.check("state_agrees_with_completed_start", now.get("boot_id") == result.get("boot_id"))
- return result.get("boot_id")
- async def drive_plan(client, evidence, args, boot_id):
- deadline = time.monotonic() + args.timeout
- handled = set()
- rank, stages = -1, []
- while time.monotonic() < deadline:
- station = await client.station(args.station)
- if station.get("boot_id") != boot_id:
- raise RuntimeError("Unexpected new BIOS boot during local validation plan; no stage input replayed")
- phase = station.get("phase", "unknown")
- new_rank = STAGE_RANK.get(phase, -1)
- if new_rank >= 0 and new_rank < rank:
- evidence.check("overall_phase_never_regresses", False, {"previous_rank": rank, "phase": phase})
- raise RuntimeError("Overall phase regressed")
- rank = max(rank, new_rank)
- if not stages or stages[-1] != phase:
- stages.append(phase)
- evidence.data["default_plan_stages"] = stages
- evidence.save()
- point = station.get("input") or {}
- if point.get("ready") and point.get("stage") == "uefi":
- evidence.data["after_default_plan"] = station_summary(station)
- evidence.check("default_plan_reached_real_uefi_prompt", phase == "uefi", {"stages": stages, "input": point})
- evidence.check("overall_phase_never_regresses", True, stages)
- return
- stage = point.get("stage")
- action = "continue_uip" if stage in ("uip", "uip1", "uip2") else "skip_amt" if stage == "amt" else None
- key = point.get("id")
- if point.get("ready") and action and key and key not in handled:
- actions = point.get("actions") or []
- if action not in actions:
- await asyncio.sleep(.5)
- continue
- handled.add(key)
- cid = "verify-stage-" + uuid.uuid4().hex
- params = {"command_id": cid, "station_id": args.station,
- "input_id": key, "action": action}
- row = {"method": "StageAction", "params": params, "input": point, "sent_utc": timestamp()}
- evidence.data["commands"].append(row)
- evidence.save()
- row["accepted"] = await client.call("StageAction", params)
- done = await wait_command(client, cid, min(deadline, time.monotonic() + 90))
- row["completed"] = done
- evidence.check("stage_action_" + action + "_" + str(len(handled)), done.get("state") == "succeeded", done)
- if done.get("state") != "succeeded":
- raise RuntimeError("Stage action failed; not retrying hardware input")
- evidence.save()
- await asyncio.sleep(.5)
- raise TimeoutError("Default local validation plan did not reach UEFI before deadline")
- async def run(args, evidence):
- token = os.environ.get(args.token_env, "") if args.token_env else ""
- async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=30)) as session:
- async with WsClient(session, args.url, evidence, token) as client:
- await readonly_checks(client, evidence, args, session, token)
- await grpc_check(args, evidence, token)
- if evidence.fail_count():
- raise RuntimeError("Read-only contract checks failed; no hardware actions submitted")
- await unconfigured_check(client, evidence, args)
- if args.start:
- boot_id = await start_test(client, evidence, args)
- if args.drive_default_plan:
- await drive_plan(client, evidence, args, boot_id)
- evidence.data["final_state"] = await client.get_state()
- evidence.data["state_push_count"] = client.state_count
- evidence.check("websocket_frames_valid", not client.protocol_errors, client.protocol_errors)
- evidence.check("final_state_has_no_internal_or_secret_fields", not private_fields(evidence.data["final_state"]))
- def main():
- parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- parser.add_argument("--url", required=True, help="ws://HOST:8080/ws?view=qt-clean")
- parser.add_argument("--output", required=True, help="JSON evidence file")
- parser.add_argument("--station", default="S1")
- parser.add_argument("--timeout", type=float, default=900, help="Seconds per host start / local plan")
- parser.add_argument("--start", action="store_true", help="Actually start/reset the server host once")
- parser.add_argument("--drive-default-plan", action="store_true", help="With --start: CR at UIP; exit AMT; stop at UEFI")
- parser.add_argument("--check-unconfigured", metavar="STATION", help="Explicitly try StartTest on a station with bmc_power=false")
- parser.add_argument("--grpc-address", help="Optional native gRPC HOST:PORT read-only smoke test")
- parser.add_argument("--backend-source", help="Backend project root for generated gRPC modules")
- parser.add_argument("--token-env", help="Environment variable containing API bearer token; never written to evidence")
- args = parser.parse_args()
- if args.drive_default_plan and not args.start:
- parser.error("--drive-default-plan requires --start")
- if args.timeout <= 0:
- parser.error("--timeout must be positive")
- if dict(parse_qsl(urlsplit(args.url).query)).get("view") != "qt-clean":
- parser.error("--url must explicitly select view=qt-clean")
- evidence = Evidence(args)
- evidence.save()
- try:
- asyncio.run(run(args, evidence))
- except KeyboardInterrupt:
- evidence.check("validation_completed", False, "Interrupted; already accepted hardware commands may continue")
- except Exception as exc:
- evidence.check("validation_completed", False, {"error": type(exc).__name__, "message": str(exc)[:1200]})
- evidence.data["finished_utc"] = timestamp()
- evidence.data["protocol_verdict"] = "FAIL" if evidence.fail_count() else "PASS"
- evidence.save()
- print(json.dumps({"protocol_verdict": evidence.data["protocol_verdict"],
- "memory_verdict": evidence.data["memory_verdict"], "output": str(evidence.path)}, ensure_ascii=False))
- return 1 if evidence.fail_count() else 0
- if __name__ == "__main__":
- raise SystemExit(main())
|