Files
marqdo-knowledge/tools/ci/verify-upstream.py
T

186 lines
9.1 KiB
Python

#!/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"
CONSUMER = "cflmy/marqdo-knowledge"
COORDINATOR = "marqdo-reconcile"
ROOT_REPO = "cflmy/marqdo"
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 forge_json(opener, path):
with opener.open(FORGE + "/api/v1" + path, timeout=30) as response:
body = response.read(2 * 1024 * 1024 + 1)
require(len(body) <= 2 * 1024 * 1024, "forge response exceeds the size limit")
return json.loads(body)
def coordinator_notes(opener, path):
issue = forge_json(opener, path)
require(issue["state"] == "open" and issue["user"]["login"] == COORDINATOR,
"expected an open task from the reconcile account")
notes = [issue["body"]]
for page in range(1, 11):
batch = forge_json(opener, f"{path}/comments?limit=50&page={page}")
notes.extend(item["body"] for item in batch if item["user"]["login"] == COORDINATOR)
if len(batch) < 50:
return notes
raise VerificationError("too many task comments to verify safely")
def issue_input(opener, number, consumer_sha):
notes = coordinator_notes(opener, f"/repos/{CONSUMER}/issues/{number}")
marker = notes[0].splitlines()[0]
require(re.fullmatch(r"<!-- marqdo:upstream release=[0-9a-f]{64} consumer=knowledge -->", marker),
"task does not have a verified release marker")
body = next(note for note in reversed(notes) if note.splitlines()[:1] == [marker])
start = "\n```json\n"
require(body.count(start) == 1 and body.endswith("\n```"), "task has no candidate input data")
header, _, encoded = body.partition(start)
inputs = json.loads(encoded.removesuffix("\n```"))
digest = hashlib.sha256(json.dumps(inputs, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
require(f"- Input digest: {digest}" in header.splitlines()
and "- State: pending" in header.splitlines(), "task input digest or state differs")
require(inputs["consumer"] == {"id": "knowledge", "source_sha": consumer_sha},
"task targets a different consumer commit")
release = inputs["release"]
tag, sha = release["tag"], release["source_sha"]
require(release["repository"] == REPO and release["index_sha256"], "task does not name a CLI release")
key = hashlib.sha256(f"{REPO}\n{tag}\n{sha}".encode()).hexdigest()
task_key = hashlib.sha256(f"{key}\nknowledge\n{digest}".encode()).hexdigest()
require(marker == f"<!-- marqdo:upstream release={key} consumer=knowledge -->"
and f"<!-- marqdo:candidate-inputs {task_key} -->" in header.splitlines(),
"task identity differs from the candidate input")
root_id = re.search(rf"(?m)^- Root tracking issue: {re.escape(FORGE)}/{ROOT_REPO}/issues/([1-9][0-9]*)$", header)
base = re.search(r"(?m)^- Root candidate: ([0-9a-f]{40})$", header)
require(root_id and base, "task lacks its root tracker or accepted baseline")
branch = forge_json(opener, f"/repos/{ROOT_REPO}/branches/main")
require(branch["protected"] and branch["commit"]["id"] == base[1], "task root baseline is stale")
tracker = coordinator_notes(opener, f"/repos/{ROOT_REPO}/issues/{root_id[1]}")
require(tracker[0].splitlines()[:1] == [f"<!-- marqdo:release-reconcile repository={REPO} tag={tag} -->"]
and any(f"<!-- marqdo:verified-release {sha} {release['index_sha256']} -->" in note.splitlines()
for note in tracker), "root tracker does not verify this producer release")
name = f"marqdo-{tag[1:]}-{TARGET}.tar.gz"
assets = [asset for asset in release["assets"] if asset["name"] == name and asset["target"] == TARGET]
require(len(assets) == 1, "task does not specify one Linux CLI archive")
return tag, sha, assets[0]["sha256"]
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("--issue", type=int, help="read an authoritative Knowledge propagation task")
parser.add_argument("--tag")
parser.add_argument("--source-sha")
parser.add_argument("--archive-sha256")
parser.add_argument("--archive", type=Path, help="use already downloaded bytes")
args = parser.parse_args()
if args.issue is not None and (args.issue < 1 or args.tag or args.source_sha or args.archive_sha256):
parser.error("--issue requires a positive number and supplies all candidate identities")
opener = urllib.request.build_opener(NoRedirect())
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")
if args.issue is not None:
args.tag, args.source_sha, args.archive_sha256 = issue_input(opener, args.issue, consumer)
require(re.fullmatch(r"v[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?", args.tag or "")
and re.fullmatch(r"[0-9a-f]{40}", args.source_sha or "")
and re.fullmatch(r"[0-9a-f]{64}", args.archive_sha256 or ""),
"expected an exact tag, source SHA and Linux archive SHA-256")
top = f"marqdo-{args.tag[1:]}-{TARGET}"
tag = forge_json(opener, f"/repos/{REPO}/tags/{args.tag}")
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, "task_issue": args.issue,
"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, IndexError, 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())