Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3cc477de60 | ||
|
|
8c8360c942 | ||
|
|
351f13e04a |
No files matched your search
@@ -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
|
||||
|
||||
@@ -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"
|
||||
+17
@@ -29,6 +29,23 @@ compatibility step also builds the existing `3.0.0-rc.4` core pin
|
||||
Changing the historical pin requires rerunning the tamper fixtures and
|
||||
recording the new Analysis fixture evidence.
|
||||
|
||||
For a verified upstream task, run the consumer gate from the clean Knowledge
|
||||
candidate using the tag, source SHA and Linux archive digest from the task.
|
||||
|
||||
```sh
|
||||
python3 tools/ci/verify-upstream.py --tag "$cli_tag" \
|
||||
--source-sha "$cli_source_sha" --archive-sha256 "$cli_archive_sha256"
|
||||
```
|
||||
|
||||
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 |
|
||||
|
||||
@@ -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"<!-- marqdo:upstream release={key} consumer=knowledge -->\n"
|
||||
f"<!-- marqdo:candidate-inputs {task} -->\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"<!-- marqdo:release-reconcile repository={upstream.REPO} tag={self.tag} -->\n"
|
||||
f"<!-- marqdo:verified-release {self.source} {self.index} -->"}
|
||||
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()
|
||||
@@ -0,0 +1,185 @@
|
||||
#!/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())
|
||||
Reference in new issue
Block a user