From 8c8360c942ccb5ff360dd2de4ecff0a4787a9adb Mon Sep 17 00:00:00 2001 From: cflmy Date: Fri, 27 Nov 2026 22:05:58 +0800 Subject: [PATCH 1/2] ci: read verified Knowledge upstream tasks by their issue number --- .woodpecker/upstream.yml | 10 +++++ docs/ci.md | 5 +++ tools/ci/verify-upstream.py | 89 ++++++++++++++++++++++++++++++++----- 3 files changed, 92 insertions(+), 12 deletions(-) create mode 100644 .woodpecker/upstream.yml diff --git a/.woodpecker/upstream.yml b/.woodpecker/upstream.yml new file mode 100644 index 0000000..a97a98a --- /dev/null +++ b/.woodpecker/upstream.yml @@ -0,0 +1,10 @@ +when: + - event: manual + branch: master + evaluate: 'MARQDO_UPSTREAM_ISSUE != nil && MARQDO_UPSTREAM_ISSUE != ""' + +steps: + verify: + image: git.cflmy.cn/cflmy/marqdo-ci-rust:3.0.0-rc.5@sha256:73481a35339157b1a3f3b23076517e96e302fbb5158e6ffcb1582acf22c6af94 + commands: + - python3 tools/ci/verify-upstream.py --issue "$MARQDO_UPSTREAM_ISSUE" diff --git a/docs/ci.md b/docs/ci.md index 4fa5b66..7d6d457 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -41,6 +41,11 @@ Pass `--archive` to reuse locally staged bytes. The gate checks the Gitea tag, artifact digest and installed Bundle before running the existing `core` lane. Its output records the actual consumer commit and CLI identities for review. +The `upstream` Woodpecker workflow accepts `MARQDO_UPSTREAM_ISSUE` as the +Knowledge issue number and uses the protected root baseline, recorded input +digests and authorized forge account to resolve the candidate. This workflow +needs read access to public issues and release assets. + ## Gates executed by CI | Gate | Command | diff --git a/tools/ci/verify-upstream.py b/tools/ci/verify-upstream.py index 190fb6e..eb0c480 100644 --- a/tools/ci/verify-upstream.py +++ b/tools/ci/verify-upstream.py @@ -17,6 +17,9 @@ 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 @@ -36,6 +39,64 @@ def require(condition, message): 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"", 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"" + and f"" 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""] + and any(f"" 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 @@ -66,24 +127,28 @@ def unpack(archive, 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("--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 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") + 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()) - 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)) + 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: @@ -106,10 +171,10 @@ def main(): 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, + 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, TypeError, + except (VerificationError, OSError, ValueError, KeyError, IndexError, TypeError, tarfile.TarError, subprocess.CalledProcessError) as error: print(f"upstream verification: {error}", file=sys.stderr) return 1 -- 2.54.1 From 3cc477de60632bfe10acb83fdf8979729f74e28e Mon Sep 17 00:00:00 2001 From: cflmy Date: Fri, 27 Nov 2026 22:07:41 +0800 Subject: [PATCH 2/2] test: verify the source of upstream issue inputs --- .woodpecker/ci.yml | 1 + tools/ci/test_verify_upstream.py | 69 ++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 tools/ci/test_verify_upstream.py diff --git a/.woodpecker/ci.yml b/.woodpecker/ci.yml index be21ae7..26fb2a1 100644 --- a/.woodpecker/ci.yml +++ b/.woodpecker/ci.yml @@ -19,6 +19,7 @@ steps: commands: - python3 tools/ci/test_release_metadata.py - python3 tools/ci/test_publish_gitea.py + - python3 tools/ci/test_verify_upstream.py - cargo fmt --all -- --check - cargo clippy --workspace --all-targets --locked -- -D warnings - cargo test --workspace --locked diff --git a/tools/ci/test_verify_upstream.py b/tools/ci/test_verify_upstream.py new file mode 100644 index 0000000..7e7684d --- /dev/null +++ b/tools/ci/test_verify_upstream.py @@ -0,0 +1,69 @@ +"""Regression tests for the root task and Knowledge verification boundary.""" +import hashlib +import importlib.util +import json +import unittest +from pathlib import Path +from unittest.mock import patch + +spec = importlib.util.spec_from_file_location("upstream", Path(__file__).with_name("verify-upstream.py")) +upstream = importlib.util.module_from_spec(spec) +spec.loader.exec_module(upstream) + + +def digest(value): + return hashlib.sha256(value.encode()).hexdigest() + + +class UpstreamTaskTest(unittest.TestCase): + def setUp(self): + self.source, self.consumer, self.root, self.index, self.asset = (c * n for c, n in + (("a", 40), ("b", 40), ("c", 40), ("d", 64), ("e", 64))) + self.tag = "v3.0.0-rc.6" + key = digest(f"{upstream.REPO}\n{self.tag}\n{self.source}") + inputs = {"consumer": {"id": "knowledge", "source_sha": self.consumer}, + "accepted_dependencies": [], + "release": {"repository": upstream.REPO, "tag": self.tag, "source_sha": self.source, + "index_sha256": self.index, "dependencies": [], + "assets": [{"name": f"marqdo-{self.tag[1:]}-{upstream.TARGET}.tar.gz", + "sha256": self.asset, "target": upstream.TARGET, "size": 9}]}} + value = digest(json.dumps(inputs, sort_keys=True, separators=(",", ":"))) + task = digest(f"{key}\nknowledge\n{value}") + user = {"login": upstream.COORDINATOR} + fence = chr(96) * 3 + self.issue = {"state": "open", "user": user, "body": + f"\n" + f"\n" + f"- Root tracking issue: {upstream.FORGE}/{upstream.ROOT_REPO}/issues/11\n" + f"- Root candidate: {self.root}\n- Input digest: {value}\n- State: pending\n" + f"\n{fence}json\n{json.dumps(inputs)}\n{fence}"} + self.tracker = {"state": "open", "user": user, "body": + f"\n" + f""} + self.branch = {"protected": True, "commit": {"id": self.root}} + + def forge(self, opener, path): + if "comments?" in path: + return [] + return {f"/repos/{upstream.CONSUMER}/issues/12": self.issue, + f"/repos/{upstream.ROOT_REPO}/branches/main": self.branch, + f"/repos/{upstream.ROOT_REPO}/issues/11": self.tracker}[path] + + def run_verify(self): + with patch.object(upstream, "forge_json", self.forge): + return upstream.issue_input(None, 12, self.consumer) + + def test_current_authorized_task_resolves_to_exact_cli(self): + self.assertEqual(self.run_verify(), (self.tag, self.source, self.asset)) + + def test_stale_root_and_wrong_task_author_are_rejected(self): + self.branch["commit"]["id"] = "f" * 40 + with self.assertRaisesRegex(upstream.VerificationError, "stale"): + self.run_verify() + self.issue["user"] = {"login": "untrusted"} + with self.assertRaisesRegex(upstream.VerificationError, "reconcile account"): + self.run_verify() + + +if __name__ == "__main__": + unittest.main() -- 2.54.1