#!/usr/bin/env python3 """Run Knowledge's real Analysis checks against an exact published CLI.""" import argparse import hashlib import json import os import re import subprocess import sys import tarfile import tempfile import urllib.error import urllib.request from pathlib import Path, PurePosixPath ROOT = Path(__file__).resolve().parents[2] FORGE = "https://git.cflmy.cn" REPO = "cflmy/marqdo-cli" TARGET = "x86_64-unknown-linux-gnu" MAX_ARCHIVE = 64 * 1024 * 1024 MAX_EXPANDED = 256 * 1024 * 1024 class VerificationError(Exception): pass class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, request, fp, code, message, headers, newurl): return None def require(condition, message): if not condition: raise VerificationError(message) def copy_verified(stream, output, digest): actual = hashlib.sha256() size = 0 with output.open("wb") as destination: while chunk := stream.read(1024 * 1024): size += len(chunk) require(size <= MAX_ARCHIVE, "CLI archive exceeds the size limit") actual.update(chunk) destination.write(chunk) require(actual.hexdigest() == digest, "CLI archive SHA-256 does not match the candidate") def unpack(archive, output, top): seen = set() total = 0 with tarfile.open(archive, "r:gz") as tar: for member in tar: path = PurePosixPath(member.name) require(path.parts and path.parts[0] == top and ".." not in path.parts and "\\" not in member.name and path not in seen and (member.isfile() or member.isdir()), "unexpected CLI archive entry") seen.add(path) total += member.size require(len(seen) <= 2048 and total <= MAX_EXPANDED, "CLI archive expansion exceeds limits") tar.extractall(output, filter="data") return output / top def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--tag", required=True) parser.add_argument("--source-sha", required=True) parser.add_argument("--archive-sha256", required=True) parser.add_argument("--archive", type=Path, help="use already downloaded bytes") args = parser.parse_args() if not (re.fullmatch(r"v[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?", args.tag) and re.fullmatch(r"[0-9a-f]{40}", args.source_sha) and re.fullmatch(r"[0-9a-f]{64}", args.archive_sha256)): parser.error("expected an exact tag, source SHA and Linux archive SHA-256") opener = urllib.request.build_opener(NoRedirect()) top = f"marqdo-{args.tag[1:]}-{TARGET}" try: consumer = subprocess.check_output(["git", "-C", ROOT, "rev-parse", "HEAD"], text=True).strip() require(not subprocess.check_output(["git", "-C", ROOT, "status", "--porcelain"], text=True), "consumer checkout has uncommitted changes") with opener.open(f"{FORGE}/api/v1/repos/{REPO}/tags/{args.tag}", timeout=30) as response: tag = json.loads(response.read(1024 * 1024)) require(tag["name"] == args.tag and tag["commit"]["sha"] == args.source_sha, "authoritative CLI tag does not match the candidate") with tempfile.TemporaryDirectory(prefix="marqdo-knowledge-upstream-") as temporary: work = Path(temporary) archive = work / (top + ".tar.gz") source = (args.archive.open("rb") if args.archive else opener.open( f"{FORGE}/{REPO}/releases/download/{args.tag}/{archive.name}", timeout=45)) with source: copy_verified(source, archive, args.archive_sha256) release = unpack(archive, work, top) metadata = json.loads((release / "RELEASE_INFO.json").read_text(encoding="utf-8")) sha = (release / "SOURCE_SHA").read_text(encoding="utf-8").strip() require(sha == args.source_sha == metadata["source_sha"] and metadata["target_triple"] == TARGET, "CLI release identity or target does not match") binary = release / "marqdo" bundle = release / "stdlib" require(binary.is_file() and os.access(binary, os.X_OK) and (bundle / "stdlib.json").is_file(), "CLI archive lacks its executable or installed Bundle") env = dict(os.environ, MARQDO_BIN=str(binary), MARQDO_STDLIB_DIR=str(bundle)) subprocess.run([ROOT / "scripts/ci.sh", "core"], cwd=ROOT, env=env, check=True) require(subprocess.check_output(["git", "-C", ROOT, "rev-parse", "HEAD"], text=True).strip() == consumer, "consumer identity changed during validation") print(json.dumps({"consumer_sha": consumer, "cli_tag": args.tag, "cli_source_sha": sha, "archive_sha256": args.archive_sha256, "target": TARGET, "status": "passed"}, sort_keys=True)) except (VerificationError, OSError, ValueError, KeyError, TypeError, tarfile.TarError, subprocess.CalledProcessError) as error: print(f"upstream verification: {error}", file=sys.stderr) return 1 return 0 if __name__ == "__main__": sys.exit(main())