Author SHA1 Message Date
cflmy ed86796d6b Bind CLI release index to verified archive and Bundle inputs
ci/woodpecker/pr/main Pipeline was successful
ci/woodpecker/push/main Pipeline was successful
2026-11-27 22:17:56 +08:00
5 changed files with 271 additions and 33 deletions

No files matched your search

+5 -2
View File
@@ -16,7 +16,9 @@ steps:
- apt-get install -y --no-install-recommends ca-certificates git python3 python3-jsonschema
- cargo build --locked -p marqdo-cli -p marqdo-provider-worker
- python3 tools/ci/check_dependency_boundaries.py
- python3 tools/ci/fetch_ecosystem_bundle.py --out target/ecosystem-stdlib
# The contract and test steps share a mutable submodule checkout.
- mkdir -p target
- flock target/ecosystem-bundle.lock python3 tools/ci/fetch_ecosystem_bundle.py --out target/ecosystem-stdlib
- MARQDO_TEST_STDLIB_BUNDLE="$PWD/target/ecosystem-stdlib" bash tools/ci/contract_lane.sh
test:
@@ -27,7 +29,8 @@ steps:
- apt-get install -y --no-install-recommends curl ca-certificates git python3 python3-jsonschema build-essential gcc-mingw-w64-x86-64
- curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
- apt-get install -y --no-install-recommends nodejs
- python3 tools/ci/fetch_ecosystem_bundle.py --out target/ecosystem-stdlib
- mkdir -p target
- flock target/ecosystem-bundle.lock python3 tools/ci/fetch_ecosystem_bundle.py --out target/ecosystem-stdlib
- python3 tools/stdlib/bundle.py --stdlib-dir target/ecosystem-stdlib
- cargo fmt --all -- --check
- cargo clippy --workspace --all-targets -- -D warnings
+31 -20
View File
@@ -221,8 +221,25 @@ git tag -a "v${version}" -m "Marqdo CLI v${version}" "$sha"
git push origin "v${version}"
```
Then create the Gitea release for the tag with `prerelease: true`, attach the
tarball and its `.sha256`, and include the release notes. The notes must state:
Before publication, use the existing Bundle producer and the exact Woodpecker
pipeline number to create the ecosystem release index. Build and cold-test the
archive with the `--bundle-pin` and Bundle directory below, as in sections 3–4.
The receipt is the root producer's build summary and stays with the release
evidence.
```bash
python3 tools/ci/fetch_ecosystem_bundle.py --out target/ecosystem-stdlib \
--receipt target/ecosystem-stdlib.receipt.json
# Run the existing package and smoke commands with that Bundle.
archive="dist/marqdo-${version}-x86_64-unknown-linux-gnu.tar.gz"
python3 tools/release/release_index.py --archive "$archive" \
--bundle-receipt target/ecosystem-stdlib.receipt.json \
--pipeline "$pipeline_number" > dist/release-evidence.json.tmp
mv dist/release-evidence.json.tmp dist/release-evidence.json
```
Create a Gitea draft for the tag with `prerelease: true` and attach the tarball,
its `.sha256`, and `release-evidence.json`. The notes must state:
* prerelease status, support lifetime and the Linux x86_64 platform scope;
* the breaking RFC-LANG-0002 language change and no legacy path;
@@ -232,21 +249,16 @@ tarball and its `.sha256`, and include the release notes. The notes must state:
* the checksum-integrity-not-signature caveat and the known-limitations file;
* the exact source SHA and links to the evidence manifest.
Example Gitea API shape (token with repository release permission; never commit
the token):
Download the draft's assets from Gitea and verify their sizes and digests against
the index. Compare the downloaded index to the local copy and verify the remote
tag points at the tested SHA. Publish the complete draft, then confirm the
public tag and asset set again. Resume an interrupted draft only for the same
tag, commit and matching assets. For an already published release, verify the
existing bytes and send any outstanding notification. Report a mismatch to the
release owner and stop. A failed notification is retried independently through
the root reconcile workflow, with its cron as the recovery path.
```bash
curl -X POST -H "Authorization: token $MARQDO_GIT_TOKEN" \
-H 'Content-Type: application/json' \
https://git.cflmy.cn/api/v1/repos/cflmy/marqdo-cli/releases \
-d '{"tag_name":"v3.0.0-beta.1","name":"Marqdo CLI 3.0.0-beta.1",
"prerelease":true,"draft":false,"body":"..."}'
curl -X POST -H "Authorization: token $MARQDO_GIT_TOKEN" \
-F "attachment=@dist/marqdo-3.0.0-beta.1-x86_64-unknown-linux-gnu.tar.gz" \
https://git.cflmy.cn/api/v1/repos/cflmy/marqdo-cli/releases/<id>/assets
```
The tag points at the tested SHA. Evidence files and the final STATUS update
Evidence files and the final STATUS update
may land in a **post-release docs commit** that references the tagged SHA, so
that the evidence never has to claim a SHA it cannot contain. Do not force-push,
do not tag a red commit, and do not upload macOS/Windows binaries unless those
@@ -254,10 +266,9 @@ platform lanes actually passed.
## 7. Rollback
- Missing/mismatched gate discovered after tagging: mark the release withdrawn,
delete the assets, keep the tag only if source/tag integrity is unaffected,
and ship a corrected prerelease (for example `3.0.0-beta.2`). Never delete a
failing test.
- Missing or mismatched gate discovered after tagging: record the withdrawal
in an issue, retain the published tag and assets for traceability, and ship
a corrected prerelease with a new tag (for example `3.0.0-beta.2`).
- Platform regression: remove that platform from `COMPATIBILITY.md`, the
release notes and the archive, then fix and re-run the gate.
- Security regression: set strict back to fail-closed/unsupported, publish a
+13 -11
View File
@@ -109,17 +109,16 @@ def fetch_root(pin: dict, cache: Path) -> Path:
return cache
def build_bundle(root: Path, out: Path) -> Path:
def build_bundle(root: Path, out: Path) -> str:
"""Build the Bundle; an existing output is reused only after verification.
CI jobs share one workspace, so a parallel or earlier job may already have
materialized the same pinned Bundle. The output is built in a temporary
sibling and moved into place atomically; a mismatch is rebuilt, never used.
The caller serializes jobs that share a worktree. The output is built
in a temporary sibling and moved into place.
"""
temp = out.with_name(out.name + ".partial-" + str(os.getpid()))
if temp.exists():
shutil.rmtree(temp)
run(
receipt = run(
[
sys.executable,
str(root / "scripts" / "build-stdlib.py"),
@@ -131,7 +130,7 @@ def build_bundle(root: Path, out: Path) -> Path:
if out.exists():
shutil.rmtree(out)
temp.rename(out)
return out
return receipt
def verify(pin: dict, bundle: Path) -> dict:
@@ -158,12 +157,13 @@ def main(argv: list[str]) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--out", default=str(ROOT / "target" / "ecosystem-stdlib"))
parser.add_argument("--cache", default=str(ROOT / "target" / "ecosystem-root"))
parser.add_argument("--receipt", type=Path, help="save the pinned producer's JSON summary")
args = parser.parse_args(argv)
out = Path(args.out).resolve()
cache = Path(args.cache).resolve()
try:
pin = load_pin()
if out.is_dir():
if out.is_dir() and args.receipt is None:
try:
verify(pin, out)
except (FetchError, OSError, json.JSONDecodeError):
@@ -172,12 +172,14 @@ def main(argv: list[str]) -> int:
print(out)
return 0
root = fetch_root(pin, cache)
bundle = build_bundle(root, out)
verify(pin, bundle)
except FetchError as error:
receipt = build_bundle(root, out)
verify(pin, out)
if args.receipt is not None:
args.receipt.write_text(receipt, encoding="utf-8")
except (FetchError, OSError, json.JSONDecodeError) as error:
print(f"fetch-ecosystem-bundle: error: {error}", file=sys.stderr)
return 1
print(bundle)
print(out)
return 0
+80
View File
@@ -0,0 +1,80 @@
"""Release index ties an archive and the producer receipt to authoritative CI."""
import io
import json
import sys
import tarfile
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "release"))
import release_index
class ReleaseIndexTest(unittest.TestCase):
def setUp(self):
directory = tempfile.TemporaryDirectory()
self.addCleanup(directory.cleanup)
self.archive = Path(directory.name) / "marqdo-3.0.0-rc.6-x86_64-unknown-linux-gnu.tar.gz"
self.sha = "9" * 40
self.bundle = {"name": "marqdo-stdlib", "version": "0.2.0",
"tree_digest": "sha256:" + "1" * 64,
"aliases_digest": "sha256:" + "2" * 64}
self.receipt = {**self.bundle, "root_commit": "8" * 40,
"components": [{"id": "std-io", "revision": "7" * 40}]}
self.info = {
"schema": "marqdo.release-info", "schema_version": 1, "product": "marqdo-cli",
"build_profile": "release", "product_version": "3.0.0-rc.6",
"target_triple": "x86_64-unknown-linux-gnu", "source_sha": self.sha,
"stdlib": {**self.bundle, "source": {"kind": "ecosystem",
"repository": "cflmy/marqdo", "commit": self.receipt["root_commit"]}},
}
steps = [{"name": name, "type": "commands", "state": "success"}
for name in sorted(release_index.REQUIRED_STEPS)]
self.pipeline = {"number": 3, "commit": self.sha, "status": "success", "event": "push",
"workflows": [{"name": "main", "state": "success", "children": steps}]}
self.repo = {"id": 2, "forge_remote_id": "19", "full_name": release_index.REPOSITORY}
with tarfile.open(self.archive, "w:gz") as output:
top = self.archive.name.removesuffix(".tar.gz")
for name, data in (("RELEASE_INFO.json", json.dumps(self.info)), ("SOURCE_SHA", self.sha)):
member = tarfile.TarInfo(f"{top}/{name}")
contents = data.encode()
member.size = len(contents)
output.addfile(member, io.BytesIO(contents))
self.checksum = self.archive.with_name(self.archive.name + ".sha256")
self.digest = release_index.sha256_file(self.archive)
self.checksum.write_text(f"{self.digest} {self.archive.name}\n", encoding="utf-8")
def test_assets_and_dependencies_are_derived_from_the_inputs(self):
with patch.object(release_index, "read_json", side_effect=[{"id": 19}, self.repo, self.pipeline]):
index = release_index.evidence(self.archive, self.receipt, 3)
self.assertEqual(index["ci"], {"pipeline_number": 3, "source_sha": self.sha,
"url": f"{release_index.CI}/repos/2/pipeline/3"})
self.assertEqual(index["assets"][0], {"name": self.archive.name, "sha256": self.digest,
"size": self.archive.stat().st_size,
"target": self.info["target_triple"]})
self.assertEqual(index["dependencies"], [{"id": "std-io", "source_sha": "7" * 40}])
def test_index_rejects_green_pipeline_without_exact_sha_and_gates(self):
wrong_commit = {**self.pipeline, "commit": "0" * 40}
skipped_gate = {**self.pipeline["workflows"][0]}
skipped_gate["children"] = skipped_gate["children"][1:]
for pipeline in (wrong_commit, {**self.pipeline, "workflows": [skipped_gate]}):
with (patch.object(release_index, "read_json", side_effect=[{"id": 19}, self.repo, pipeline]),
self.assertRaisesRegex(ValueError, "exact SHA")):
release_index.evidence(self.archive, self.receipt, 3)
def test_index_rejects_mismatched_receipt_or_archive_checksum(self):
receipt = {**self.receipt, "root_commit": "0" * 40}
with self.assertRaisesRegex(ValueError, "mismatches the Bundle"):
release_index.evidence(self.archive, receipt, 3)
self.checksum.write_text(f"{'0' * 64} {self.archive.name}\n", encoding="utf-8")
with self.assertRaisesRegex(ValueError, "checksum disagrees"):
release_index.evidence(self.archive, self.receipt, 3)
if __name__ == "__main__":
unittest.main()
+142
View File
@@ -0,0 +1,142 @@
#!/usr/bin/env python3
"""Generate the ecosystem release index for a cold-tested CLI archive."""
from __future__ import annotations
import argparse
import json
import re
import tarfile
import urllib.request
from pathlib import Path
from package import sha256_file
REPOSITORY = "cflmy/marqdo-cli"
FORGE = "https://git.cflmy.cn"
CI = "https://ci.cflmy.cn"
LIMIT = 1024 * 1024
SHA = re.compile(r"[0-9a-f]{40}")
COMPONENT_ID = re.compile(r"[a-z][a-z0-9-]*")
REQUIRED_STEPS = {"contract", "test", "independent-build", "minimum-rust", "build"}
def read_json(url: str) -> dict:
with urllib.request.urlopen(url, timeout=20) as response:
data = response.read(LIMIT + 1)
if response.geturl() != url or len(data) > LIMIT:
raise ValueError("unexpected CI or forge response")
return json.loads(data)
def verify_ci(source_sha: str, number: int) -> dict:
if number < 1:
raise ValueError("pipeline number must be positive")
forge = read_json(f"{FORGE}/api/v1/repos/{REPOSITORY}")
repo = read_json(f"{CI}/api/repos/lookup/{REPOSITORY}")
repo_id = repo.get("id")
if (type(forge.get("id")) is not int or type(repo_id) is not int or repo_id < 1
or repo.get("full_name") != REPOSITORY
or repo.get("forge_remote_id") != str(forge["id"])):
raise ValueError("Woodpecker does not identify the canonical CLI repository")
pipeline = read_json(f"{CI}/api/repos/{repo_id}/pipelines/{number}")
successful = {
step["name"]
for workflow in pipeline.get("workflows", [])
if workflow.get("name") == "main" and workflow.get("state") == "success"
for step in workflow.get("children", [])
if step.get("state") == "success" and step.get("type") == "commands"
}
if (pipeline.get("number") != number or pipeline.get("commit") != source_sha
or pipeline.get("status") != "success"
or pipeline.get("event") not in {"push", "pull_request"}
or not REQUIRED_STEPS <= successful):
raise ValueError("pipeline did not pass the CLI gates for the archive's exact SHA")
return {"pipeline_number": number, "url": f"{CI}/repos/{repo_id}/pipeline/{number}",
"source_sha": source_sha}
def archive_info(archive: Path) -> dict:
top = archive.name.removesuffix(".tar.gz")
names = {f"{top}/RELEASE_INFO.json", f"{top}/SOURCE_SHA"}
metadata = {}
# Read the two fixed paths without extracting the archive.
with tarfile.open(archive, "r|gz") as product:
for member in product:
if member.name not in names:
continue
if member.name in metadata or not member.isfile() or member.size > LIMIT:
raise ValueError("invalid archive metadata entry")
with product.extractfile(member) as file:
metadata[member.name] = file.read()
if metadata.keys() != names:
raise ValueError("archive is missing release metadata")
info = json.loads(metadata[f"{top}/RELEASE_INFO.json"])
sha = metadata[f"{top}/SOURCE_SHA"].decode("ascii").strip()
if (info.get("schema") != "marqdo.release-info" or info.get("schema_version") != 1
or info.get("product") != "marqdo-cli" or not SHA.fullmatch(sha)
or info.get("source_sha") != sha or info.get("build_profile") != "release"
or archive.name != f"marqdo-{info['product_version']}-{info['target_triple']}.tar.gz"):
raise ValueError("archive identity disagrees with RELEASE_INFO or SOURCE_SHA")
return info
def bundle_dependencies(info: dict, receipt: dict) -> list[dict]:
bundle = info["stdlib"]
source = bundle.get("source", {})
if (source.get("kind") != "ecosystem" or source.get("repository") != "cflmy/marqdo"
or not SHA.fullmatch(source.get("commit", ""))
or receipt.get("root_commit") != source["commit"]
or any(receipt.get(field) != bundle[field]
for field in ("name", "version", "tree_digest", "aliases_digest"))):
raise ValueError("producer receipt mismatches the Bundle in the archive")
components = receipt["components"]
if not isinstance(components, list) or not 1 <= len(components) <= 256:
raise ValueError("Bundle receipt must identify its contributing components")
dependencies = {}
for component in components:
name, revision = component["id"], component["revision"]
if not COMPONENT_ID.fullmatch(name) or name == "cli" or not SHA.fullmatch(revision) or name in dependencies:
raise ValueError("invalid or duplicate Bundle component identity")
dependencies[name] = revision
return [{"id": name, "source_sha": sha} for name, sha in sorted(dependencies.items())]
def evidence(archive: Path, receipt: dict, number: int) -> dict:
info = archive_info(archive)
dependencies = bundle_dependencies(info, receipt)
checksum = archive.with_name(archive.name + ".sha256")
digest = sha256_file(archive)
if checksum.stat().st_size > LIMIT or checksum.read_text().split() != [digest, archive.name]:
raise ValueError("archive checksum disagrees with the release asset")
return {
"component_id": "cli", "repository": REPOSITORY, "tag": f"v{info['product_version']}",
"source_sha": info["source_sha"], "ci": verify_ci(info["source_sha"], number),
"assets": [
{"name": path.name, "target": info["target_triple"], "size": path.stat().st_size,
"sha256": sha}
for path, sha in ((archive, digest), (checksum, sha256_file(checksum)))
],
"dependencies": dependencies,
}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--archive", type=Path, required=True)
parser.add_argument("--bundle-receipt", type=Path, required=True)
parser.add_argument("--pipeline", type=int, required=True)
args = parser.parse_args()
try:
with args.bundle_receipt.open("rb") as file:
data = file.read(LIMIT + 1)
if len(data) > LIMIT:
raise ValueError("Bundle receipt exceeds size limit")
index = evidence(args.archive, json.loads(data), args.pipeline)
except (OSError, ValueError, TypeError, KeyError, AttributeError, tarfile.TarError) as error:
parser.exit(1, f"release-index: {error}\n")
print(json.dumps(index, indent=2))
if __name__ == "__main__":
main()