| 1 | #!/usr/bin/env python3 |
| 2 | """Pinned DSH plugin acceptance driver and receipt validator (CW-7051). |
| 3 | |
| 4 | run drive one pinned row through lifecycle L against an installed Engine |
| 5 | validate check a receipt against the pins; the verdict is recomputed here |
| 6 | matrix combine validated receipts into the row x OS table |
| 7 | selftest prove the validator rejects a missing step and never infers PASS |
| 8 | |
| 9 | The driver only uses the Engine's own /v1/apps/plugins routes. It never loads |
| 10 | plugin code itself and never calls a model provider unless --allow-provider is |
| 11 | given. Verdicts: PASS, FAIL, UNAVAILABLE (a named platform, provider, desktop |
| 12 | or artifact is missing), BLOCKED (admission refused as pinned), INVALID. |
| 13 | """ |
| 14 | from __future__ import annotations |
| 15 | |
| 16 | import argparse |
| 17 | import copy |
| 18 | import hashlib |
| 19 | import json |
| 20 | import os |
| 21 | import platform |
| 22 | import shutil |
| 23 | import socket |
| 24 | import subprocess |
| 25 | import sys |
| 26 | import tarfile |
| 27 | import tempfile |
| 28 | import time |
| 29 | import urllib.error |
| 30 | import urllib.request |
| 31 | from pathlib import Path |
| 32 | |
| 33 | HERE = Path(__file__).resolve().parent |
| 34 | PINS_PATH = HERE.parents[1] / "crates/engine/tests/fixtures/dsh-plugin-acceptance/pins.json" |
| 35 | RECEIPT_SCHEMA = "codewhale.dsh-acceptance-receipt/1" |
| 36 | MATRIX_SCHEMA = "codewhale.dsh-acceptance-matrix/1" |
| 37 | OSES = ["macos", "linux", "windows"] |
| 38 | STATUSES = {"PASS", "FAIL", "UNAVAILABLE", "SKIPPED"} |
| 39 | UNAVAILABLE_KINDS = {"platform", "provider", "desktop", "artifact"} |
| 40 | LEVELS = {"source", "local", "installed", "provider", "desktop"} |
| 41 | |
| 42 | STEP_LEVEL = { |
| 43 | "pin.tarball_hash": "source", |
| 44 | "package.extract": "local", |
| 45 | "engine.identity": "installed", |
| 46 | "platform.identity": "installed", |
| 47 | "admission.preview": "installed", |
| 48 | "admission.refused": "installed", |
| 49 | "lifecycle.install": "installed", |
| 50 | "lifecycle.trust": "installed", |
| 51 | "lifecycle.enable": "installed", |
| 52 | "lifecycle.restart_retained": "installed", |
| 53 | "journey.core": "provider", |
| 54 | "journey.controls": "provider", |
| 55 | "client.seats_rendered": "desktop", |
| 56 | "lifecycle.revoke": "installed", |
| 57 | "lifecycle.uninstall": "installed", |
| 58 | "security.no_key_leak": "installed", |
| 59 | } |
| 60 | COMMON = ["pin.tarball_hash", "package.extract", "engine.identity", "platform.identity"] |
| 61 | ADMITTED_ROW = [ |
| 62 | "admission.preview", "lifecycle.install", "lifecycle.trust", "lifecycle.enable", |
| 63 | "journey.core", "journey.controls", "lifecycle.restart_retained", |
| 64 | "lifecycle.revoke", "lifecycle.uninstall", "security.no_key_leak", |
| 65 | ] |
| 66 | REFUSED_ROW = ["admission.refused"] |
| 67 | |
| 68 | |
| 69 | def os_name() -> str: |
| 70 | return {"darwin": "macos", "linux": "linux", "win32": "windows"}.get(sys.platform, sys.platform) |
| 71 | |
| 72 | |
| 73 | def load_pins(path: Path = PINS_PATH) -> dict: |
| 74 | pins = json.loads(path.read_text()) |
| 75 | if pins.get("schema") != "codewhale.dsh-acceptance-pins/1" or len(pins["rows"]) != 33: |
| 76 | raise SystemExit("pins file is not the ratified 33-row table") |
| 77 | return pins |
| 78 | |
| 79 | |
| 80 | def pin_for(pins: dict, row: int) -> dict: |
| 81 | for entry in pins["rows"]: |
| 82 | if entry["row"] == row: |
| 83 | return entry |
| 84 | raise SystemExit(f"row {row} is not in the pinned list") |
| 85 | |
| 86 | |
| 87 | def required_steps(pin: dict) -> list[str]: |
| 88 | if pin["admission"] != "admit": |
| 89 | return COMMON + REFUSED_ROW |
| 90 | steps = COMMON + ADMITTED_ROW |
| 91 | if pin["declares_client"]: |
| 92 | steps.insert(steps.index("lifecycle.restart_retained") + 1, "client.seats_rendered") |
| 93 | return steps |
| 94 | |
| 95 | |
| 96 | def sha256_file(path: Path) -> str: |
| 97 | digest = hashlib.sha256() |
| 98 | with path.open("rb") as handle: |
| 99 | for chunk in iter(lambda: handle.read(1 << 20), b""): |
| 100 | digest.update(chunk) |
| 101 | return digest.hexdigest() |
| 102 | |
| 103 | |
| 104 | def sha256_json(value) -> str: |
| 105 | return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest() |
| 106 | |
| 107 | |
| 108 | def refusal_needle(pin: dict) -> str: |
| 109 | refusal = pin["refusal"] |
| 110 | return f"{refusal['code']}: `{refusal['field']}` requires DSH `{refusal['range']}`" |
| 111 | |
| 112 | |
| 113 | def verdict_of(pin: dict, steps: list[dict]) -> str: |
| 114 | by_id = {step["id"]: step for step in steps} |
| 115 | statuses = [by_id[name]["status"] for name in required_steps(pin)] |
| 116 | if "FAIL" in statuses: |
| 117 | return "FAIL" |
| 118 | if all(status == "PASS" for status in statuses): |
| 119 | return "PASS" if pin["admission"] == "admit" else "BLOCKED" |
| 120 | if "UNAVAILABLE" in statuses: |
| 121 | return "UNAVAILABLE" |
| 122 | return "FAIL" |
| 123 | |
| 124 | |
| 125 | def validate_receipt(receipt: dict, pins: dict, allow_synthetic: bool = False) -> tuple[str, list[str]]: |
| 126 | problems: list[str] = [] |
| 127 | if receipt.get("schema") != RECEIPT_SCHEMA: |
| 128 | return "INVALID", ["schema is not " + RECEIPT_SCHEMA] |
| 129 | if receipt.get("synthetic") and not allow_synthetic: |
| 130 | return "INVALID", ["synthetic receipts cannot be accepted"] |
| 131 | try: |
| 132 | pin = pin_for(pins, receipt.get("row")) |
| 133 | except SystemExit as error: |
| 134 | return "INVALID", [str(error)] |
| 135 | for field in ("package", "version", "tarball_sha256"): |
| 136 | if receipt.get(field) != pin[field]: |
| 137 | problems.append(f"{field} does not match the pin") |
| 138 | if receipt.get("os") not in OSES: |
| 139 | problems.append("os is not one of " + ",".join(OSES)) |
| 140 | steps = receipt.get("steps") |
| 141 | if not isinstance(steps, list) or not steps: |
| 142 | return "INVALID", problems + ["no steps recorded"] |
| 143 | seen: dict[str, dict] = {} |
| 144 | for step in steps: |
| 145 | name = step.get("id") |
| 146 | if name not in STEP_LEVEL: |
| 147 | problems.append(f"unknown step {name}") |
| 148 | continue |
| 149 | if name in seen: |
| 150 | problems.append(f"duplicate step {name}") |
| 151 | continue |
| 152 | seen[name] = step |
| 153 | if step.get("status") not in STATUSES: |
| 154 | problems.append(f"{name}: bad status") |
| 155 | if step.get("level") != STEP_LEVEL[name]: |
| 156 | problems.append(f"{name}: level must be {STEP_LEVEL[name]}") |
| 157 | if step.get("status") == "PASS": |
| 158 | if not step.get("evidence"): |
| 159 | problems.append(f"{name}: PASS without evidence") |
| 160 | if step.get("count", 0) < 1: |
| 161 | problems.append(f"{name}: PASS with zero observed events") |
| 162 | if step.get("status") == "UNAVAILABLE" and step.get("unavailable") not in UNAVAILABLE_KINDS: |
| 163 | problems.append(f"{name}: UNAVAILABLE must name platform, provider, desktop or artifact") |
| 164 | for name in required_steps(pin): |
| 165 | if name not in seen: |
| 166 | problems.append(f"required step missing: {name}") |
| 167 | if pin["admission"] != "admit" and seen.get("admission.refused", {}).get("status") == "PASS": |
| 168 | message = (seen["admission.refused"].get("evidence") or {}).get("message", "") |
| 169 | if refusal_needle(pin) not in message: |
| 170 | problems.append("admission.refused: refusal reason does not match the pinned basis") |
| 171 | engine = receipt.get("engine") or {} |
| 172 | if not engine.get("sha256") or not engine.get("version"): |
| 173 | problems.append("engine identity is incomplete") |
| 174 | if problems: |
| 175 | return "INVALID", problems |
| 176 | verdict = verdict_of(pin, steps) |
| 177 | if verdict in ("PASS", "BLOCKED") and engine.get("kind") != "installed": |
| 178 | problems.append("an accepted row needs the installed Engine artifact, not a source build") |
| 179 | if verdict in ("PASS", "BLOCKED") and "(dev)" in str(engine.get("version")): |
| 180 | problems.append("an accepted row cannot come from a dev build") |
| 181 | if receipt.get("verdict") != verdict: |
| 182 | problems.append(f"claimed verdict {receipt.get('verdict')} differs from computed {verdict}") |
| 183 | if problems: |
| 184 | return "INVALID", problems |
| 185 | return verdict, [] |
| 186 | |
| 187 | |
| 188 | def step(name: str, status: str, detail: str, evidence=None, count: int = 0, unavailable: str | None = None) -> dict: |
| 189 | record = {"id": name, "level": STEP_LEVEL[name], "status": status, "detail": detail, "count": count, |
| 190 | "evidence": evidence or {}, "at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())} |
| 191 | if unavailable: |
| 192 | record["unavailable"] = unavailable |
| 193 | return record |
| 194 | |
| 195 | |
| 196 | class Engine: |
| 197 | def __init__(self, binary: Path, home: Path, workspace: Path, flags: list[str], token: str): |
| 198 | self.binary, self.home, self.workspace, self.flags, self.token = binary, home, workspace, flags, token |
| 199 | self.port = 0 |
| 200 | self.proc: subprocess.Popen | None = None |
| 201 | self.log = home.parent / "engine.log" |
| 202 | |
| 203 | def env(self) -> dict: |
| 204 | env = dict(os.environ) |
| 205 | env.update({"CODEWHALE_HOME": str(self.home), "HOME": str(self.home), "USERPROFILE": str(self.home), |
| 206 | "CODEWHALE_RUNTIME_TOKEN": self.token}) |
| 207 | return env |
| 208 | |
| 209 | def start(self) -> None: |
| 210 | with socket.socket() as probe: |
| 211 | probe.bind(("127.0.0.1", 0)) |
| 212 | self.port = probe.getsockname()[1] |
| 213 | out = self.log.open("ab") |
| 214 | command = [str(self.binary), "app-server", "--http", "--port", str(self.port)] |
| 215 | for flag in self.flags: |
| 216 | command += ["--enable", flag] |
| 217 | self.proc = subprocess.Popen(command, cwd=self.workspace, env=self.env(), stdout=out, stderr=subprocess.STDOUT) |
| 218 | deadline = time.time() + 90 |
| 219 | while time.time() < deadline: |
| 220 | if self.proc.poll() is not None: |
| 221 | raise RuntimeError(f"Engine exited with {self.proc.returncode} before listening") |
| 222 | if self.request("GET", "/v1/apps/plugins")[0] == 200: |
| 223 | return |
| 224 | time.sleep(0.5) |
| 225 | raise RuntimeError("Engine did not answer /v1/apps/plugins within 90 s") |
| 226 | |
| 227 | def stop(self) -> None: |
| 228 | if self.proc and self.proc.poll() is None: |
| 229 | self.proc.terminate() |
| 230 | try: |
| 231 | self.proc.wait(20) |
| 232 | except subprocess.TimeoutExpired: |
| 233 | self.proc.kill() |
| 234 | self.proc.wait() |
| 235 | |
| 236 | def request(self, method: str, path: str, body: dict | None = None) -> tuple[int, dict]: |
| 237 | data = json.dumps(body).encode() if body is not None else None |
| 238 | req = urllib.request.Request(f"http://127.0.0.1:{self.port}{path}", data=data, method=method) |
| 239 | req.add_header("Authorization", "Bearer " + self.token) |
| 240 | if data is not None: |
| 241 | req.add_header("Content-Type", "application/json") |
| 242 | try: |
| 243 | with urllib.request.urlopen(req, timeout=60) as response: |
| 244 | raw = response.read() |
| 245 | return response.status, (json.loads(raw) if raw else {}) |
| 246 | except urllib.error.HTTPError as error: |
| 247 | raw = error.read() |
| 248 | try: |
| 249 | return error.code, json.loads(raw) |
| 250 | except ValueError: |
| 251 | return error.code, {"raw": raw.decode("utf-8", "replace")[:500]} |
| 252 | except OSError: |
| 253 | return 0, {} |
| 254 | |
| 255 | |
| 256 | def extract_tarball(tarball: Path, target: Path) -> Path: |
| 257 | root = target.resolve() |
| 258 | with tarfile.open(tarball) as archive: |
| 259 | members = archive.getmembers() |
| 260 | for member in members: |
| 261 | destination = (root / member.name).resolve() |
| 262 | if not (destination == root or root in destination.parents) or member.issym() or member.islnk(): |
| 263 | raise ValueError(f"unsafe archive member {member.name}") |
| 264 | archive.extractall(root, members=members) |
| 265 | candidates = sorted(path.parent for path in root.glob("*/package.json")) |
| 266 | if len(candidates) != 1: |
| 267 | raise ValueError(f"expected one package directory, found {len(candidates)}") |
| 268 | return candidates[0] |
| 269 | |
| 270 | |
| 271 | def view(plugin: dict) -> dict: |
| 272 | keys = ("state", "enabled", "trust_status", "active", "compatibility", "content_hash", "capability_hash") |
| 273 | return {key: plugin.get(key) for key in keys} |
| 274 | |
| 275 | |
| 276 | def find_tarball(pin: dict, tarball_dir: Path) -> Path: |
| 277 | path = tarball_dir / pin["tarball"] |
| 278 | if not path.is_file(): |
| 279 | raise FileNotFoundError(f"pinned tarball not found: {path}") |
| 280 | return path |
| 281 | |
| 282 | |
| 283 | def run_row(args, pins: dict) -> dict: |
| 284 | pin = pin_for(pins, args.row) |
| 285 | binary = Path(args.engine).expanduser().resolve() |
| 286 | steps: list[dict] = [] |
| 287 | receipt = {"schema": RECEIPT_SCHEMA, "row": pin["row"], "package": pin["package"], "version": pin["version"], |
| 288 | "tarball_sha256": pin["tarball_sha256"], "os": os_name(), "arch": platform.machine().lower(), |
| 289 | "flags": list(args.enable), "network_allow": list(args.allow_host), "steps": steps, |
| 290 | "provider_calls_allowed": bool(args.allow_provider)} |
| 291 | version = subprocess.run([str(binary), "--version"], capture_output=True, text=True, timeout=60).stdout.strip() |
| 292 | receipt["engine"] = {"path": str(binary), "sha256": sha256_file(binary), "version": version, "kind": args.engine_kind} |
| 293 | steps.append(step("engine.identity", "PASS", version, {"sha256": receipt["engine"]["sha256"], "kind": args.engine_kind}, 1)) |
| 294 | steps.append(step("platform.identity", "PASS" if os_name() in OSES else "UNAVAILABLE", os_name(), |
| 295 | {"os": os_name(), "arch": receipt["arch"]}, 1, None if os_name() in OSES else "platform")) |
| 296 | failed: list[str] = [] |
| 297 | |
| 298 | def record(item: dict) -> bool: |
| 299 | steps.append(item) |
| 300 | if item["status"] == "FAIL": |
| 301 | failed.append(item["id"]) |
| 302 | return item["status"] == "PASS" |
| 303 | |
| 304 | work = Path(tempfile.mkdtemp(prefix="dsh-acceptance-", dir=args.work_dir)) |
| 305 | engine = None |
| 306 | try: |
| 307 | try: |
| 308 | tarball = find_tarball(pin, Path(args.tarballs)) |
| 309 | actual = sha256_file(tarball) |
| 310 | ok = actual == pin["tarball_sha256"] |
| 311 | record(step("pin.tarball_hash", "PASS" if ok else "FAIL", f"sha256 {actual}", {"sha256": actual, "pinned": pin["tarball_sha256"]}, 1)) |
| 312 | if not ok: |
| 313 | raise ValueError("tarball hash differs from the pin") |
| 314 | package = extract_tarball(tarball, work / "pkg") |
| 315 | files = sum(1 for path in package.rglob("*") if path.is_file()) |
| 316 | record(step("package.extract", "PASS" if files else "FAIL", f"{files} files", {"package_dir": package.name, "files": files}, files)) |
| 317 | except Exception as error: |
| 318 | if "pin.tarball_hash" not in [s["id"] for s in steps]: |
| 319 | record(step("pin.tarball_hash", "FAIL", str(error))) |
| 320 | if "package.extract" not in [s["id"] for s in steps]: |
| 321 | record(step("package.extract", "SKIPPED", "no verified package")) |
| 322 | raise |
| 323 | home, workspace = work / "home", work / "workspace" |
| 324 | home.mkdir() |
| 325 | workspace.mkdir() |
| 326 | engine = Engine(binary, home, workspace, list(args.enable), "dsh-acc-" + hashlib.sha256(os.urandom(16)).hexdigest()) |
| 327 | subprocess.run([str(binary), "config", "set", "telemetry", "false"], env=engine.env(), capture_output=True, timeout=60) |
| 328 | if args.allow_host: |
| 329 | with (home / "config.toml").open("a") as config: |
| 330 | config.write("\n[network]\nallow = " + json.dumps(args.allow_host) + "\n") |
| 331 | engine.start() |
| 332 | code, preview = engine.request("POST", "/v1/apps/plugins/import/dsh/preview", {"path": str(package)}) |
| 333 | if pin["admission"] != "admit": |
| 334 | message = str(preview.get("error", {}).get("message", "")) |
| 335 | refused = code == 400 and refusal_needle(pin) in message |
| 336 | record(step("admission.refused", "PASS" if refused else "FAIL", f"HTTP {code}", |
| 337 | {"http": code, "message": message[:600], "pinned_verdict": pin["admission"], "pinned_refusal": refusal_needle(pin)}, 1)) |
| 338 | return receipt |
| 339 | ok = code == 200 and preview.get("content_hash") |
| 340 | record(step("admission.preview", "PASS" if ok else "FAIL", f"HTTP {code}", |
| 341 | {"http": code, "review_hash": preview.get("content_hash"), "error": preview.get("error", {}).get("message", "")[:300], |
| 342 | "outcomes": preview.get("conversion", {}).get("outcomes", [])}, 1 if ok else 0)) |
| 343 | if not ok: |
| 344 | raise RuntimeError("Engine did not admit the pinned package") |
| 345 | name = preview["conversion"]["plugin_name"] |
| 346 | code, installed = engine.request("POST", "/v1/apps/plugins/install", |
| 347 | {"source": preview["install_source"], "expected_content_hash": preview["content_hash"]}) |
| 348 | plugin = installed.get("plugin", {}) |
| 349 | ok = code == 201 and plugin.get("state") == "disabled" and plugin.get("trust_status") == "not-reviewed" |
| 350 | record(step("lifecycle.install", "PASS" if ok else "FAIL", f"HTTP {code}, installed disabled and untrusted: {ok}", |
| 351 | {"http": code, "plugin": view(plugin)}, 1 if ok else 0)) |
| 352 | if not ok: |
| 353 | raise RuntimeError("install failed") |
| 354 | events = trust_and_enable(engine, name) |
| 355 | record(events[0]) |
| 356 | record(events[1]) |
| 357 | if failed: |
| 358 | raise RuntimeError("enable failed") |
| 359 | provider_unavailable = "provider calls are off; run with --allow-provider and a configured provider" |
| 360 | for journey in ("journey.core", "journey.controls"): |
| 361 | if args.allow_provider: |
| 362 | record(step(journey, "UNAVAILABLE", "no per-row scripted journey exists yet for this row", {}, 0, "artifact")) |
| 363 | else: |
| 364 | record(step(journey, "UNAVAILABLE", provider_unavailable, {}, 0, "provider")) |
| 365 | engine.stop() |
| 366 | engine.start() |
| 367 | code, after = engine.request("GET", f"/v1/apps/plugins/{name}") |
| 368 | ok = code == 200 and after.get("enabled") is True and after.get("trust_status") == "trusted" and after.get("content_hash") == plugin.get("content_hash") |
| 369 | record(step("lifecycle.restart_retained", "PASS" if ok else "FAIL", f"HTTP {code} after Engine restart", |
| 370 | {"http": code, "plugin": view(after), "installed": view(plugin)}, 1 if ok else 0)) |
| 371 | if pin["declares_client"]: |
| 372 | record(step("client.seats_rendered", "UNAVAILABLE", "the desktop slot-observation contract is not available to this driver; screenshots are not accepted", |
| 373 | {"declared_slot_keys": pin["declared_dsh_slot_keys"]}, 0, "desktop")) |
| 374 | code, _ = engine.request("POST", f"/v1/apps/plugins/{name}/disable") |
| 375 | code2, revoked = engine.request("POST", f"/v1/apps/plugins/{name}/revoke") |
| 376 | _, state = engine.request("GET", f"/v1/apps/plugins/{name}") |
| 377 | ok = code == 200 and code2 == 200 and state.get("active") is False and state.get("trust_status") != "trusted" |
| 378 | record(step("lifecycle.revoke", "PASS" if ok else "FAIL", f"disable HTTP {code}, revoke HTTP {code2}", |
| 379 | {"disable": code, "revoke": code2, "plugin": view(state)}, 1 if ok else 0)) |
| 380 | code, _ = engine.request("DELETE", f"/v1/apps/plugins/{name}") |
| 381 | code2, _ = engine.request("GET", f"/v1/apps/plugins/{name}") |
| 382 | record(step("lifecycle.uninstall", "PASS" if code == 200 and code2 == 404 else "FAIL", f"delete HTTP {code}, then GET HTTP {code2}", |
| 383 | {"delete": code, "get_after": code2}, 1 if code == 200 and code2 == 404 else 0)) |
| 384 | engine.stop() |
| 385 | hits, scanned = scan_for_secret(engine.token, [engine.log, home]) |
| 386 | record(step("security.no_key_leak", "PASS" if scanned and not hits else "FAIL", f"scanned {scanned} files, {len(hits)} hits", |
| 387 | {"files_scanned": scanned, "hits": hits[:5], "sentinel": "runtime bearer token"}, scanned)) |
| 388 | except Exception as error: |
| 389 | if "lifecycle.install" not in [s["id"] for s in steps] and pin["admission"] == "admit" and "admission.preview" in [s["id"] for s in steps]: |
| 390 | steps.append(step("lifecycle.install", "FAIL", f"driver stopped: {error}")) |
| 391 | receipt["driver_error"] = str(error) |
| 392 | finally: |
| 393 | if engine: |
| 394 | engine.stop() |
| 395 | have = {s["id"] for s in steps} |
| 396 | for name_ in required_steps(pin): |
| 397 | if name_ not in have: |
| 398 | steps.append(step(name_, "SKIPPED", "an earlier step failed or the driver stopped")) |
| 399 | shutil.rmtree(work, ignore_errors=True) |
| 400 | return receipt |
| 401 | |
| 402 | |
| 403 | def trust_and_enable(engine: Engine, name: str) -> list[dict]: |
| 404 | base = f"/v1/apps/plugins/{name}" |
| 405 | trusted = None |
| 406 | rounds = [] |
| 407 | for _ in range(3): |
| 408 | code, detail = engine.request("GET", base) |
| 409 | review = detail.get("review") or {} |
| 410 | token = review.get("token") |
| 411 | if code != 200 or not token: |
| 412 | return [step("lifecycle.trust", "FAIL", f"no review token, HTTP {code}", {"http": code}), |
| 413 | step("lifecycle.enable", "SKIPPED", "trust did not complete")] |
| 414 | payload = {"token": token} |
| 415 | hs_token = (review.get("host_services") or {}).get("token") |
| 416 | if hs_token: |
| 417 | payload["host_services_token"] = hs_token |
| 418 | code, answer = engine.request("POST", base + "/trust", payload) |
| 419 | rounds.append({"trust_http": code}) |
| 420 | if code != 200: |
| 421 | return [step("lifecycle.trust", "FAIL", f"trust HTTP {code}", {"http": code, "answer": answer}), |
| 422 | step("lifecycle.enable", "SKIPPED", "trust did not complete")] |
| 423 | trusted = step("lifecycle.trust", "PASS", "review token accepted", {"rounds": rounds}, len(rounds)) |
| 424 | code, answer = engine.request("POST", base + "/enable") |
| 425 | rounds[-1]["enable_http"] = code |
| 426 | if code == 409 and "capability review" in json.dumps(answer): |
| 427 | continue |
| 428 | _, state = engine.request("GET", base) |
| 429 | ok = code == 200 and state.get("active") is True |
| 430 | trusted["evidence"]["rounds"] = rounds |
| 431 | return [trusted, step("lifecycle.enable", "PASS" if ok else "FAIL", f"enable HTTP {code}, active={state.get('active')}", |
| 432 | {"http": code, "plugin": view(state), "answer": answer if code != 200 else {}}, 1 if ok else 0)] |
| 433 | return [trusted or step("lifecycle.trust", "FAIL", "review kept changing"), |
| 434 | step("lifecycle.enable", "FAIL", "capability review did not settle after three rounds", {"rounds": rounds})] |
| 435 | |
| 436 | |
| 437 | def scan_for_secret(secret: str, roots: list[Path]) -> tuple[list[str], int]: |
| 438 | needle = secret.encode() |
| 439 | hits, scanned = [], 0 |
| 440 | for root in roots: |
| 441 | paths = [root] if root.is_file() else [p for p in root.rglob("*") if p.is_file()] |
| 442 | for path in paths: |
| 443 | try: |
| 444 | if path.stat().st_size > 64 * 1024 * 1024: |
| 445 | continue |
| 446 | scanned += 1 |
| 447 | if needle in path.read_bytes(): |
| 448 | hits.append(str(path)) |
| 449 | except OSError: |
| 450 | continue |
| 451 | return hits, scanned |
| 452 | |
| 453 | |
| 454 | def synthetic_receipt(pins: dict, row: int, with_pass_everywhere: bool = True) -> dict: |
| 455 | pin = pin_for(pins, row) |
| 456 | steps = [] |
| 457 | for name in required_steps(pin): |
| 458 | evidence = {"synthetic": True} |
| 459 | if name == "admission.refused": |
| 460 | evidence["message"] = "DSH import refused: " + refusal_needle(pin) |
| 461 | steps.append(step(name, "PASS", "synthetic", evidence, 1)) |
| 462 | return {"schema": RECEIPT_SCHEMA, "synthetic": True, "row": pin["row"], "package": pin["package"], "version": pin["version"], |
| 463 | "tarball_sha256": pin["tarball_sha256"], "os": "macos", "arch": "arm64", |
| 464 | "engine": {"path": "/x", "sha256": "0" * 64, "version": "synthetic", "kind": "installed"}, |
| 465 | "steps": steps, "verdict": "BLOCKED" if pin["admission"] != "admit" else "PASS"} |
| 466 | |
| 467 | |
| 468 | def selftest(pins: dict) -> int: |
| 469 | results = [] |
| 470 | |
| 471 | def check(label: str, expected: str, receipt: dict, fix_claim: bool = True, synthetic_ok: bool = True) -> None: |
| 472 | if fix_claim and receipt.get("steps"): |
| 473 | pin = pin_for(pins, receipt["row"]) |
| 474 | ids = {s["id"] for s in receipt["steps"]} |
| 475 | if all(n in ids for n in required_steps(pin)): |
| 476 | receipt["verdict"] = verdict_of(pin, receipt["steps"]) |
| 477 | verdict, problems = validate_receipt(receipt, pins, allow_synthetic=synthetic_ok) |
| 478 | results.append((label, expected, verdict, problems[:2], verdict == expected)) |
| 479 | |
| 480 | base = synthetic_receipt(pins, 1) |
| 481 | check("all required steps pass", "PASS", copy.deepcopy(base)) |
| 482 | missing = copy.deepcopy(base) |
| 483 | missing["steps"] = [s for s in missing["steps"] if s["id"] != "lifecycle.revoke"] |
| 484 | check("one required event missing (lifecycle.revoke)", "INVALID", missing) |
| 485 | empty = copy.deepcopy(base) |
| 486 | empty["steps"][4]["count"] = 0 |
| 487 | check("PASS with zero observed events (empty selector)", "INVALID", empty) |
| 488 | bare = copy.deepcopy(base) |
| 489 | bare["steps"][4]["evidence"] = {} |
| 490 | check("PASS without evidence", "INVALID", bare) |
| 491 | provider = copy.deepcopy(base) |
| 492 | for item in provider["steps"]: |
| 493 | if item["id"] == "journey.core": |
| 494 | item.update(status="UNAVAILABLE", unavailable="provider", count=0, evidence={}) |
| 495 | check("provider unavailable is not PASS", "UNAVAILABLE", provider) |
| 496 | lying = copy.deepcopy(provider) |
| 497 | lying["verdict"] = "PASS" |
| 498 | check("claimed PASS over an unavailable step", "INVALID", lying, fix_claim=False) |
| 499 | failed = copy.deepcopy(base) |
| 500 | failed["steps"][5].update(status="FAIL") |
| 501 | check("a failed step is FAIL", "FAIL", failed) |
| 502 | unnamed = copy.deepcopy(provider) |
| 503 | for item in unnamed["steps"]: |
| 504 | item.pop("unavailable", None) |
| 505 | check("UNAVAILABLE must name what is missing", "INVALID", unnamed) |
| 506 | wrong = copy.deepcopy(base) |
| 507 | wrong["tarball_sha256"] = "f" * 64 |
| 508 | check("tarball hash differs from the pin", "INVALID", wrong) |
| 509 | source = copy.deepcopy(base) |
| 510 | source["engine"]["kind"] = "source-build" |
| 511 | check("source build cannot be accepted as installed", "INVALID", source) |
| 512 | check("synthetic receipt refused in real validation", "INVALID", copy.deepcopy(base), synthetic_ok=False) |
| 513 | check("refused row passes only as BLOCKED", "BLOCKED", synthetic_receipt(pins, 14)) |
| 514 | reason = synthetic_receipt(pins, 14) |
| 515 | for item in reason["steps"]: |
| 516 | if item["id"] == "admission.refused": |
| 517 | item["evidence"]["message"] = "DSH import refused: hidden file `.gitignore` is not allowed" |
| 518 | check("refusal for the wrong reason is not BLOCKED", "INVALID", reason) |
| 519 | dev = copy.deepcopy(base) |
| 520 | dev["engine"]["version"] = "codewhale 0.10.3 (dev)" |
| 521 | check("dev build cannot be accepted", "INVALID", dev) |
| 522 | client = synthetic_receipt(pins, 2) |
| 523 | client["steps"] = [s for s in client["steps"] if s["id"] != "client.seats_rendered"] |
| 524 | check("declared client seats cannot be skipped", "INVALID", client) |
| 525 | width = max(len(r[0]) for r in results) |
| 526 | bad = 0 |
| 527 | for label, expected, got, problems, ok in results: |
| 528 | bad += not ok |
| 529 | print(f"{'ok ' if ok else 'FAIL'} {label.ljust(width)} expected={expected} got={got} {problems if got == 'INVALID' else ''}") |
| 530 | print(f"selftest: {len(results) - bad} passed, {bad} failed, {len(results)} total") |
| 531 | return 1 if bad else 0 |
| 532 | |
| 533 | |
| 534 | def cmd_validate(args, pins: dict) -> int: |
| 535 | receipt = json.loads(Path(args.receipt).read_text()) |
| 536 | verdict, problems = validate_receipt(receipt, pins) |
| 537 | print(json.dumps({"verdict": verdict, "problems": problems, "row": receipt.get("row"), "os": receipt.get("os")}, indent=1)) |
| 538 | return 0 if verdict in ("PASS", "BLOCKED") else 1 |
| 539 | |
| 540 | |
| 541 | def cmd_matrix(args, pins: dict) -> int: |
| 542 | table: dict = {} |
| 543 | invalid = [] |
| 544 | for path in sorted(Path(args.receipts).glob("**/*.json")): |
| 545 | try: |
| 546 | receipt = json.loads(path.read_text()) |
| 547 | except ValueError: |
| 548 | continue |
| 549 | if not isinstance(receipt, dict) or receipt.get("schema") != RECEIPT_SCHEMA: |
| 550 | continue |
| 551 | verdict, problems = validate_receipt(receipt, pins) |
| 552 | if verdict == "INVALID": |
| 553 | invalid.append({"receipt": str(path), "problems": problems}) |
| 554 | continue |
| 555 | slot = table.setdefault(receipt["row"], {}) |
| 556 | previous = slot.get(receipt["os"]) |
| 557 | if previous is None or receipt.get("steps", [{}])[0].get("at", "") >= previous["at"]: |
| 558 | slot[receipt["os"]] = {"verdict": verdict, "receipt": str(path), "at": receipt["steps"][0].get("at", ""), |
| 559 | "engine": receipt["engine"]["sha256"]} |
| 560 | rows = [] |
| 561 | for pin in pins["rows"]: |
| 562 | per_os = {} |
| 563 | for name in OSES: |
| 564 | entry = table.get(pin["row"], {}).get(name) |
| 565 | per_os[name] = entry["verdict"] if entry else "UNAVAILABLE(no receipt)" |
| 566 | values = set(per_os.values()) |
| 567 | overall = "FAIL" if "FAIL" in values else "PASS" if values == {"PASS"} else "BLOCKED" if values == {"BLOCKED"} else "UNAVAILABLE" |
| 568 | rows.append({"row": pin["row"], "package": pin["package"], "verdict": overall, "os": per_os}) |
| 569 | summary = {} |
| 570 | for item in rows: |
| 571 | summary[item["verdict"]] = summary.get(item["verdict"], 0) + 1 |
| 572 | out = {"schema": MATRIX_SCHEMA, "rows": rows, "summary": summary, "invalid_receipts": invalid} |
| 573 | print(json.dumps(out, indent=1)) |
| 574 | return 0 if summary.get("PASS", 0) + summary.get("BLOCKED", 0) == len(rows) else 1 |
| 575 | |
| 576 | |
| 577 | def main() -> int: |
| 578 | parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) |
| 579 | sub = parser.add_subparsers(dest="command", required=True) |
| 580 | run = sub.add_parser("run", help="drive one pinned row against an installed Engine") |
| 581 | run.add_argument("--row", type=int, required=True) |
| 582 | run.add_argument("--engine", required=True, help="path to the installed codewhale binary") |
| 583 | run.add_argument("--engine-kind", choices=["installed", "source-build"], required=True) |
| 584 | run.add_argument("--tarballs", required=True, help="directory holding the pinned tarballs") |
| 585 | run.add_argument("--enable", action="append", default=[], help="Engine feature to enable (repeatable), e.g. extension_host") |
| 586 | run.add_argument("--allow-host", action="append", default=[], help="host the isolated Engine may reach without prompting (repeatable), e.g. registry.npmjs.org for npm dependencies") |
| 587 | run.add_argument("--allow-provider", action="store_true", help="permit model-provider calls (spend); off by default") |
| 588 | run.add_argument("--work-dir", default=None, help="scratch parent directory") |
| 589 | run.add_argument("--out", required=True, help="receipt path") |
| 590 | val = sub.add_parser("validate", help="validate one receipt") |
| 591 | val.add_argument("receipt") |
| 592 | mat = sub.add_parser("matrix", help="combine receipts into the row x OS table") |
| 593 | mat.add_argument("receipts") |
| 594 | sub.add_parser("selftest", help="negative controls for the validator") |
| 595 | sub.add_parser("pins", help="verify tarball hashes in a directory") |
| 596 | pins_cmd = sub.choices["pins"] |
| 597 | pins_cmd.add_argument("--tarballs", required=True) |
| 598 | args = parser.parse_args() |
| 599 | pins = load_pins() |
| 600 | if args.command == "selftest": |
| 601 | return selftest(pins) |
| 602 | if args.command == "validate": |
| 603 | return cmd_validate(args, pins) |
| 604 | if args.command == "matrix": |
| 605 | return cmd_matrix(args, pins) |
| 606 | if args.command == "pins": |
| 607 | bad = 0 |
| 608 | for pin in pins["rows"]: |
| 609 | path = Path(args.tarballs) / pin["tarball"] |
| 610 | ok = path.is_file() and sha256_file(path) == pin["tarball_sha256"] |
| 611 | if ok and "manifest_os" in pin: |
| 612 | with tarfile.open(path) as archive: |
| 613 | manifest = json.load(archive.extractfile("package/package.json")) |
| 614 | bundle = manifest["dsh"]["bundle"] |
| 615 | declared = {} |
| 616 | if "os" in manifest: |
| 617 | declared["os"] = manifest["os"] |
| 618 | if "platforms" in bundle: |
| 619 | declared["dsh.bundle.platforms"] = bundle["platforms"] |
| 620 | ok = (manifest["name"], manifest["version"], declared) == ( |
| 621 | pin["package"], pin["version"], pin["manifest_os"] |
| 622 | ) |
| 623 | bad += not ok |
| 624 | print(f"row {pin['row']:>2} {'ok ' if ok else 'FAIL'} {pin['package']}@{pin['version']}") |
| 625 | print(f"pins: {len(pins['rows']) - bad} ok, {bad} failed") |
| 626 | return 1 if bad else 0 |
| 627 | receipt = run_row(args, pins) |
| 628 | receipt["verdict"] = verdict_of(pin_for(pins, args.row), receipt["steps"]) |
| 629 | Path(args.out).write_text(json.dumps(receipt, indent=1)) |
| 630 | verdict, problems = validate_receipt(receipt, pins) |
| 631 | print(f"row {args.row} {receipt['package']}@{receipt['version']} on {receipt['os']}: driver verdict {receipt['verdict']}, validator {verdict} {problems}") |
| 632 | for item in receipt["steps"]: |
| 633 | print(f" {item['status']:<11} {item['id']:<28} {item['detail'][:110]}") |
| 634 | return 0 if verdict in ("PASS", "BLOCKED") else 1 |
| 635 | |
| 636 | |
| 637 | if __name__ == "__main__": |
| 638 | sys.exit(main()) |
| 639 |