| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336 |
- #!/usr/bin/env python3
- """Unzip-directory self-verify for an hth-platform review package.
- --mode offline: SHA, MANIFEST, permissions, L0 offline (buf missing = PARTIAL).
- --mode release: same plus buf lint+breaking required. Missing tools/logs FAIL.
- """
- from __future__ import annotations
- import argparse
- import hashlib
- import json
- import os
- import subprocess
- import sys
- import tempfile
- from pathlib import Path
- LEGACY_REQUIRED_REVIEWS = (
- "01-scope-architecture.md",
- "02-watchdog-protocol-truth.md",
- "03-actor-action-lifecycle.md",
- "04-sdk-replay-deployment.md",
- "05-evidence-artifact-release.md",
- )
- def verify_6400_contract(root: Path, host: Path) -> list[str]:
- errors: list[str] = []
- paths = {
- "identity": root / "PACKAGE_IDENTITY.json",
- "contract": root / "evidence" / "6400" / "host-contract.json",
- "contract_sums": root / "evidence" / "6400" / "SHA256SUMS",
- "import_source": root / "evidence" / "6400" / "import-source.json",
- "control_profile": root / "evidence" / "6400" / "profiles" / "6400-control.json",
- "identification_profile": root / "evidence" / "6400" / "profiles" / "6400-identification.json",
- }
- missing = [name for name, path in paths.items() if not path.is_file()]
- if missing:
- return ["missing 6400 evidence: " + ", ".join(missing)]
- identity = json.loads(paths["identity"].read_text(encoding="utf-8"))
- contract = json.loads(paths["contract"].read_text(encoding="utf-8"))
- imported = json.loads(paths["import_source"].read_text(encoding="utf-8"))
- control = json.loads(paths["control_profile"].read_text(encoding="utf-8"))
- identification = json.loads(paths["identification_profile"].read_text(encoding="utf-8"))
- contract_id = contract.get("contract_sha256")
- contract_file_sha = hashlib.sha256(paths["contract"].read_bytes()).hexdigest()
- def expect(value: object, wanted: object, label: str) -> None:
- if value != wanted:
- errors.append(f"{label}: got {value!r}, expected {wanted!r}")
- expect(identity.get("product"), "6400-front-rear-v1", "identity product")
- expect(identity.get("profile_ids"), ["6400-control", "6400-identification"], "identity profiles")
- expect(identity.get("protocol_contract_sha256"), contract_id, "identity contract")
- expect(contract.get("schema"), "prod2u-6400-host-contract-v2", "contract schema")
- expect(imported.get("contract_sha256"), contract_id, "import contract")
- expect(imported.get("source_contract_file_sha256"), contract_file_sha, "import contract file")
- wire = contract.get("wire") or {}
- responses = wire.get("responses") or {}
- order = wire.get("host_response_order") or {}
- expected_responses = {
- "SET_TARGET_ACK": (0x81, 0),
- "GET_SNAPSHOT_ACK": (0x82, 0),
- "SET_STIMULUS_ACK": (0x83, 0),
- "SNAPSHOT_DATA": (0x42, None),
- }
- for name, (frame_type, payload_length) in expected_responses.items():
- response = responses.get(name) or {}
- expect(response.get("type"), frame_type, f"{name} type")
- if payload_length is not None:
- expect(response.get("payload_length"), payload_length, f"{name} payload length")
- expect(order.get("SET_TARGET"), ["SET_TARGET_ACK"], "SET_TARGET response order")
- expect(order.get("GET_SNAPSHOT"), ["GET_SNAPSHOT_ACK", "SNAPSHOT_DATA"], "GET_SNAPSHOT response order")
- expect(order.get("SET_STIMULUS"), ["SET_STIMULUS_ACK"], "SET_STIMULUS response order")
- expect((contract.get("snapshot") or {}).get("payload_length"), 193, "snapshot payload length")
- profile_expectations = (
- (
- control,
- "6400-control",
- ["SET_TARGET", "GET_SNAPSHOT"],
- True,
- False,
- ),
- (
- identification,
- "6400-identification",
- ["SET_TARGET", "GET_SNAPSHOT", "SET_STIMULUS"],
- False,
- True,
- ),
- )
- for profile, profile_id, commands, production, stimulus in profile_expectations:
- expect(profile.get("profile_id"), profile_id, f"{profile_id} id")
- expect(profile.get("contract_sha256"), contract_id, f"{profile_id} contract")
- expect(profile.get("source_contract_file_sha256"), contract_file_sha, f"{profile_id} contract file")
- expect(profile.get("allowed_commands"), commands, f"{profile_id} commands")
- expect(profile.get("production"), production, f"{profile_id} production")
- expect(profile.get("stimulus"), stimulus, f"{profile_id} stimulus")
- sums_fields = paths["contract_sums"].read_text(encoding="utf-8").split()
- if len(sums_fields) < 2 or sums_fields[0] != contract_file_sha or sums_fields[1] != "host-contract.json":
- errors.append("6400 contract SHA256SUMS does not bind host-contract.json")
- mirrors = {
- host / "contracts" / "6400" / "host-contract.json": paths["contract"],
- host / "profiles" / "6400-control" / "profile.json": paths["control_profile"],
- host / "profiles" / "6400-identification" / "profile.json": paths["identification_profile"],
- }
- for packaged, evidence_path in mirrors.items():
- if not packaged.is_file() or packaged.read_bytes() != evidence_path.read_bytes():
- errors.append(f"packaged source does not match 6400 evidence: {packaged.relative_to(root)}")
- forbidden = (
- host / "RELEASE.zh-CN.md",
- host / "REQUIREMENTS_TRACEABILITY.md",
- host / "contracts" / "evidence",
- host / "profiles" / "prod2u-door-temp",
- host / "profiles" / "6400-sim-debug",
- root / "reviews" / "02-watchdog-protocol-truth.md",
- )
- for path in forbidden:
- if path.exists():
- errors.append(f"legacy or non-release profile entered 6400 package: {path.relative_to(root)}")
- return errors
- def main() -> int:
- ap = argparse.ArgumentParser()
- ap.add_argument("root", nargs="?", default=".")
- ap.add_argument("--mode", choices=("offline", "release"), default="offline")
- ap.add_argument("--full", action="store_true", help="also go build and pip wheel --no-deps")
- args = ap.parse_args()
- root = Path(args.root).resolve()
- sums = root / "SHA256SUMS"
- manifest = root / "MANIFEST"
- if not sums.is_file() or not manifest.is_file():
- print("FAIL missing SHA256SUMS or MANIFEST", file=sys.stderr)
- return 1
- rc = 0
- man_set: set[str] = set()
- for line in manifest.read_text(encoding="utf-8").splitlines():
- if not line.strip():
- continue
- if line.startswith("/") or ".." in Path(line).parts:
- print("FAIL path", line, file=sys.stderr)
- rc = 1
- man_set.add(line.strip())
- sum_set: set[str] = set()
- for line in sums.read_text(encoding="utf-8").splitlines():
- if not line.strip():
- continue
- digest, name = line.split(None, 1)
- name = name.strip()
- sum_set.add(name)
- path = root / name
- if not path.is_file():
- print("FAIL missing", name, file=sys.stderr)
- rc = 1
- continue
- got = hashlib.sha256(path.read_bytes()).hexdigest()
- if got != digest:
- print("FAIL sha256", name, file=sys.stderr)
- rc = 1
- mode = path.stat().st_mode & 0o777
- if mode == 0o777:
- print("FAIL 0777", name, file=sys.stderr)
- rc = 1
- if path.suffix == ".sh" or (path.suffix == ".py" and path.read_bytes()[:2] == b"#!" and path.parent.name == "tools"):
- if mode != 0o755:
- print("FAIL expected 0755", name, oct(mode), file=sys.stderr)
- rc = 1
- if man_set != sum_set:
- print("FAIL MANIFEST and SHA256SUMS file sets differ", file=sys.stderr)
- print("only_manifest", sorted(man_set - sum_set)[:20], file=sys.stderr)
- print("only_sums", sorted(sum_set - man_set)[:20], file=sys.stderr)
- rc = 1
- identity_path = root / "PACKAGE_IDENTITY.json"
- identity = json.loads(identity_path.read_text(encoding="utf-8")) if identity_path.is_file() else {}
- is_6400 = identity.get("product") == "6400-front-rear-v1"
- golden = root / "evidence" / "golden-vectors.json"
- if not is_6400 and not golden.is_file():
- print("FAIL missing evidence/golden-vectors.json", file=sys.stderr)
- rc = 1
- host = root / "host"
- if not (host / "go.mod").is_file():
- print("FAIL host/go.mod missing", file=sys.stderr)
- return 1
- required_reviews = ("6400-migration.md",) if is_6400 else LEGACY_REQUIRED_REVIEWS
- for name in required_reviews:
- if (root / "reviews" / name).is_file():
- continue
- if (host / "reviews" / name).is_file():
- continue
- print("FAIL missing review", name, file=sys.stderr)
- rc = 1
- run_dir = root / "run"
- man_json = run_dir / "run-manifest.json"
- if man_json.is_file():
- payload = json.loads(man_json.read_text(encoding="utf-8"))
- commits = {payload.get("git_commit")}
- trees = {payload.get("git_tree")}
- dirties = {payload.get("git_dirty_state")}
- times: set[str] = set()
- for cmd in payload.get("commands") or []:
- log = cmd.get("log") or ""
- if log:
- lp = run_dir / Path(log).name
- if not lp.is_file():
- print("FAIL missing run log", log, file=sys.stderr)
- rc = 1
- elif cmd.get("log_sha256"):
- got = hashlib.sha256(lp.read_bytes()).hexdigest()
- if got != cmd["log_sha256"]:
- print("FAIL log sha", log, file=sys.stderr)
- rc = 1
- elif args.mode == "release":
- print("FAIL missing log_sha256", cmd.get("name"), file=sys.stderr)
- rc = 1
- st = (cmd.get("status") or "").upper()
- name = cmd.get("name") or ""
- if st in {"NOT RUN", "NOT_RUN"}:
- if not cmd.get("not_run_reason_sha256") and not cmd.get("command") and not cmd.get("not_run_reason"):
- print("FAIL NOT RUN missing reason", name, file=sys.stderr)
- rc = 1
- continue
- if st == "PASS" and (not log or not cmd.get("log_sha256")):
- print("FAIL PASS without raw log/sha", name, file=sys.stderr)
- rc = 1
- if "NOT RUN" in st and "PASS" in (cmd.get("matrix") or ""):
- print("FAIL NOT RUN marked PASS", name, file=sys.stderr)
- rc = 1
- times.add(cmd.get("start_utc") or "")
- times.add(cmd.get("end_utc") or "")
- if payload.get("git_dirty") and payload.get("git_dirty_state") == "clean":
- print("FAIL dirty flag vs dirty_state", file=sys.stderr)
- rc = 1
- if len([t for t in times if t]) == 1 and len(payload.get("commands") or []) > 3:
- print("FAIL all commands share one timestamp (forged window)", file=sys.stderr)
- rc = 1
- _ = commits, trees, dirties
- elif args.mode == "release":
- print("FAIL missing run/run-manifest.json", file=sys.stderr)
- rc = 1
- env = os.environ.copy()
- if is_6400:
- for error in verify_6400_contract(root, host):
- print("FAIL 6400 contract", error, file=sys.stderr)
- rc = 1
- if args.mode == "release":
- descriptor = host / "api" / "proto" / "hth.api.v1.desc.prev"
- try:
- buf_commands = [
- ["buf", "lint"],
- ["buf", "breaking", "--against", f"{descriptor}#format=binpb"],
- ]
- for command in buf_commands:
- check = subprocess.run(command, cwd=str(host), env=env)
- if check.returncode != 0:
- print("FAIL", " ".join(command), file=sys.stderr)
- rc = 1
- except FileNotFoundError:
- print("FAIL buf is required in release mode", file=sys.stderr)
- rc = 1
- else:
- l0 = subprocess.run(
- [
- sys.executable,
- str(host / "tools" / "l0_contract_check.py"),
- "--repo-root",
- str(root),
- "--evidence-root",
- str(root / "evidence"),
- "--mode",
- args.mode,
- ],
- cwd=str(host),
- env=env,
- )
- if l0.returncode != 0:
- print("FAIL l0", args.mode, file=sys.stderr)
- rc = 1
- oracle = host / "tools" / "protocol_oracle.py"
- if oracle.is_file() and golden.is_file():
- por = subprocess.run(
- [
- sys.executable,
- str(oracle),
- "--golden",
- str(golden),
- "--min-positive",
- "8",
- "--min-negative",
- "2",
- "--min-frames",
- "6",
- ],
- cwd=str(root),
- env=env,
- )
- if por.returncode != 0:
- print("FAIL protocol_oracle", file=sys.stderr)
- rc = 1
- if args.full:
- with tempfile.TemporaryDirectory(prefix="hth-verify-hthd-") as td:
- out_bin = Path(td) / "hthd"
- build = subprocess.run(["go", "build", "-o", str(out_bin), "./cmd/hthd"], cwd=str(host), env=env)
- if build.returncode != 0:
- print("FAIL go build", file=sys.stderr)
- rc = 1
- sdk = host / "sdk" / "python"
- if (sdk / "pyproject.toml").is_file():
- with tempfile.TemporaryDirectory(prefix="hth-verify-wheels-") as td:
- wheel_dir = Path(td)
- whl = subprocess.run(
- [sys.executable, "-m", "pip", "wheel", "--no-deps", "-q", "-w", str(wheel_dir), str(sdk)],
- env=env,
- )
- if whl.returncode != 0:
- print("FAIL python wheel --no-deps", file=sys.stderr)
- rc = 1
- else:
- print("python_wheel_ok", list(wheel_dir.glob("hth_sdk-*.whl")))
- if rc == 0:
- if args.mode == "release":
- print("RELEASE_CONTRACT_GATE_PASS")
- else:
- print("OFFLINE_EVIDENCE_CHECK_PASS")
- print("PACKAGE_SELF_VERIFY_PASS")
- return rc
- if __name__ == "__main__":
- raise SystemExit(main())
|