276 lines
13 KiB
Python
Executable File
276 lines
13 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Publish the reviewed Knowledge artifact to a protected Gitea tag."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import fnmatch
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
import uuid
|
|
from pathlib import Path
|
|
|
|
FORGE = "https://git.cflmy.cn"
|
|
CI = "https://ci.cflmy.cn"
|
|
REPO = "cflmy/marqdo-knowledge"
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
TAG = re.compile(r"v[0-9]+\.[0-9]+\.[0-9]+(?:-[A-Za-z0-9.-]+)?")
|
|
SHA = re.compile(r"[a-f0-9]{40}")
|
|
DIGEST = re.compile(r"[a-f0-9]{64}")
|
|
BASENAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._+-]{0,180}")
|
|
MAX_ASSET = 256 * 1024 * 1024
|
|
|
|
|
|
class PublicationError(Exception):
|
|
pass
|
|
|
|
|
|
def require(condition, reason):
|
|
if not condition:
|
|
raise PublicationError(reason)
|
|
|
|
|
|
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
return None
|
|
|
|
|
|
class Service:
|
|
def __init__(self, token):
|
|
self.token = token
|
|
self.opener = urllib.request.build_opener(NoRedirect())
|
|
|
|
def open(self, url, method="GET", data=None, content_type=None, authenticate=False):
|
|
headers = {"Accept": "application/json"}
|
|
if authenticate and self.token:
|
|
headers["Authorization"] = f"token {self.token}"
|
|
if content_type:
|
|
headers["Content-Type"] = content_type
|
|
request = urllib.request.Request(url, headers=headers, data=data, method=method)
|
|
return self.opener.open(request, timeout=45)
|
|
|
|
def json(self, path, method="GET", payload=None, *, missing_ok=False, ci=False, upload=None):
|
|
if upload is not None:
|
|
data, content_type = upload
|
|
elif payload is not None:
|
|
data, content_type = json.dumps(payload).encode(), "application/json"
|
|
else:
|
|
data, content_type = None, None
|
|
url = (CI + "/api" if ci else FORGE + "/api/v1") + path
|
|
try:
|
|
with self.open(url, method, data, content_type, authenticate=not ci) as response:
|
|
raw = response.read(2 * 1024 * 1024 + 1)
|
|
require(len(raw) <= 2 * 1024 * 1024, f"{method} {path}: response too large")
|
|
return json.loads(raw)
|
|
except urllib.error.HTTPError as error:
|
|
if missing_ok and error.code == 404:
|
|
return None
|
|
raise PublicationError(f"{method} {path}: HTTP {error.code}") from error
|
|
|
|
def digest_attachment(self, attachment, size):
|
|
identity = uuid.UUID(attachment["uuid"])
|
|
with self.open(f"{FORGE}/attachments/{identity}", authenticate=True) as response:
|
|
return consume(response, size)
|
|
|
|
|
|
def consume(stream, limit):
|
|
digest = hashlib.sha256()
|
|
size = 0
|
|
while block := stream.read(min(1024 * 1024, limit - size + 1)):
|
|
size += len(block)
|
|
require(size <= limit, "asset exceeds its recorded size")
|
|
digest.update(block)
|
|
require(size == limit, "asset size differs from its record")
|
|
return digest.hexdigest()
|
|
|
|
|
|
def asset_record(path, target):
|
|
require(path.is_file() and BASENAME.fullmatch(path.name), f"invalid asset {path}")
|
|
size = path.stat().st_size
|
|
require(0 < size <= MAX_ASSET, f"invalid size for {path.name}")
|
|
with path.open("rb") as stream:
|
|
return {"name": path.name, "target": target, "size": size,
|
|
"sha256": consume(stream, size)}
|
|
|
|
|
|
def ready_ci(service, head, number, repo):
|
|
repository = service.json(f"/repos/lookup/{REPO}", ci=True)
|
|
require(repository["full_name"] == REPO and repository["forge_remote_id"] == str(repo["id"]),
|
|
"Woodpecker repository identity differs from the forge")
|
|
ci_id = repository["id"]
|
|
run = service.json(f"/repos/{ci_id}/pipelines/{number}", ci=True)
|
|
require(run["number"] == number and run["commit"] == head and run["status"] == "success"
|
|
and run["ref"] == f"refs/heads/{repo['default_branch']}"
|
|
and run["event"] in {"push", "manual"} and not run.get("from_fork")
|
|
and any(w["name"] == "ci" and w["state"] == "success"
|
|
and any(s["name"] == "test" and s["state"] == "success" for s in w["children"])
|
|
for w in run["workflows"]),
|
|
"release requires successful default-branch component CI for this exact SHA")
|
|
return {"pipeline_number": number, "source_sha": head,
|
|
"url": f"{CI}/repos/{ci_id}/pipeline/{number}"}
|
|
|
|
|
|
def candidate(service, tag, pipeline, paths, *, publish):
|
|
repository = service.json(f"/repos/{REPO}")
|
|
branch = repository["default_branch"]
|
|
branch_info = service.json(f"/repos/{REPO}/branches/{urllib.parse.quote(branch, safe='')}")
|
|
head = subprocess.check_output(["git", "-C", ROOT, "rev-parse", "HEAD"], text=True).strip()
|
|
status = subprocess.check_output(["git", "-C", ROOT, "status", "--porcelain"], text=True)
|
|
require(not status and SHA.fullmatch(head), "release requires a clean checkout")
|
|
tag_info = service.json(f"/repos/{REPO}/tags/{urllib.parse.quote(tag, safe='')}")
|
|
branch_sha = branch_info["commit"]["id"]
|
|
require(tag_info["name"] == tag and tag_info["commit"]["sha"] == head
|
|
and SHA.fullmatch(branch_sha), "tag and checkout do not match")
|
|
ancestry = subprocess.run(["git", "-C", ROOT, "merge-base", "--is-ancestor", head, branch_sha],
|
|
capture_output=True, check=False)
|
|
require(ancestry.returncode == 0, "tag is outside the verified default-branch history; fetch first")
|
|
if publish:
|
|
actor = service.json("/user")
|
|
require(actor["login"] == "marqdo-publisher" and actor.get("is_admin") is False,
|
|
"publication requires the non-admin publisher account")
|
|
require(branch_info["protected"] is True, "default branch must be protected")
|
|
rules = service.json(f"/repos/{REPO}/tag_protections")
|
|
require(any(fnmatch.fnmatchcase(tag, rule["name_pattern"]) for rule in rules),
|
|
"tag requires an applicable protection rule")
|
|
ci = ready_ci(service, head, pipeline, repository)
|
|
|
|
archive = paths[0]
|
|
info = json.loads((archive.parent / "RELEASE_INFO.json").read_text())
|
|
smoke = json.loads((archive.parent / "smoke-evidence.json").read_text())
|
|
records = [asset_record(path, info["target"]) for path in paths]
|
|
core_sha = smoke.get("core_source_sha", "")
|
|
core_digest = smoke.get("core_binary_sha256", "")
|
|
require(info["product"] == "marqdo-knowledge" and info["source_sha"] == head
|
|
and f"v{info['product_version']}" == tag
|
|
and smoke["source_sha"] == head and smoke["version"] == info["product_version"]
|
|
and smoke["archive"] == archive.name and smoke["archive_sha256"] == records[0]["sha256"]
|
|
and SHA.fullmatch(core_sha) and DIGEST.fullmatch(core_digest),
|
|
"package or cold-install evidence does not match the candidate")
|
|
checksum = (archive.parent / f"{archive.name}.sha256").read_text().split()
|
|
require(checksum == [records[0]["sha256"], archive.name], "archive checksum sidecar mismatch")
|
|
return {"component_id": "knowledge", "repository": REPO, "tag": tag, "source_sha": head,
|
|
"ci": ci, "assets": records,
|
|
"dependencies": [{"id": "cli", "source_sha": core_sha, "asset_sha256": core_digest}]}
|
|
|
|
|
|
def inventory(service, release_path):
|
|
attachments = service.json(release_path + "/assets")
|
|
require(isinstance(attachments, list), "invalid attachment inventory")
|
|
by_name = {item["name"]: item for item in attachments}
|
|
require(len(by_name) == len(attachments), "duplicate names in the release")
|
|
return by_name
|
|
|
|
|
|
def check_assets(service, attachments, expected, complete):
|
|
require(attachments.keys() <= expected.keys(), "unexpected attachment in release")
|
|
require(not complete or attachments.keys() == expected.keys(), "incomplete release assets")
|
|
for name, remote in attachments.items():
|
|
_, record = expected[name]
|
|
require(remote["size"] == record["size"]
|
|
and service.digest_attachment(remote, record["size"]) == record["sha256"],
|
|
f"published bytes differ for {name}")
|
|
|
|
|
|
def upload(service, release_path, path, record):
|
|
with path.open("rb") as stream:
|
|
data = stream.read(record["size"] + 1)
|
|
require(len(data) == record["size"] and hashlib.sha256(data).hexdigest() == record["sha256"],
|
|
f"local asset changed: {path.name}")
|
|
boundary = uuid.uuid4().hex
|
|
header = (
|
|
f"--{boundary}\r\n"
|
|
f'Content-Disposition: form-data; name="attachment"; filename="{path.name}"\r\n'
|
|
"Content-Type: application/octet-stream\r\n\r\n"
|
|
).encode()
|
|
body = header + data + f"\r\n--{boundary}--\r\n".encode()
|
|
service.json(release_path + "/assets?" + urllib.parse.urlencode({"name": path.name}),
|
|
"POST", upload=(body, f"multipart/form-data; boundary={boundary}"))
|
|
|
|
|
|
def publish_release(service, tag, source, expected, notes):
|
|
releases = f"/repos/{REPO}/releases"
|
|
by_tag = releases + "/tags/" + urllib.parse.quote(tag, safe="")
|
|
release = service.json(by_tag, missing_ok=True)
|
|
if release is None:
|
|
release = service.json(releases, "POST", {
|
|
"tag_name": tag, "target_commitish": source, "name": f"marqdo-knowledge {tag[1:]}",
|
|
"body": notes, "prerelease": True, "draft": True,
|
|
})
|
|
require(release["draft"], "forge did not create a draft release")
|
|
require(release["tag_name"] == tag and release["prerelease"], "existing release identity differs")
|
|
release_path = f"{releases}/{release['id']}"
|
|
attachments = inventory(service, release_path)
|
|
check_assets(service, attachments, expected, complete=not release["draft"])
|
|
if release["draft"]:
|
|
for name, (path, record) in expected.items():
|
|
if name not in attachments:
|
|
upload(service, release_path, path, record)
|
|
check_assets(service, inventory(service, release_path), expected, complete=True)
|
|
tag_info = service.json(f"/repos/{REPO}/tags/{urllib.parse.quote(tag, safe='')}")
|
|
require(tag_info["commit"]["sha"] == source, "tag moved during draft publication")
|
|
service.json(release_path, "PATCH", {"draft": False})
|
|
confirmed = service.json(by_tag)
|
|
require(confirmed["id"] == release["id"] and not confirmed["draft"] and confirmed["prerelease"],
|
|
"public release identity changed")
|
|
check_assets(service, inventory(service, release_path), expected, complete=True)
|
|
return confirmed
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--tag", required=True)
|
|
parser.add_argument("--pipeline", type=int, required=True)
|
|
parser.add_argument("--archive", type=Path, required=True)
|
|
parser.add_argument("--files", nargs="*", type=Path, default=[])
|
|
parser.add_argument("--body-file", type=Path)
|
|
parser.add_argument("--prepare", action="store_true", help="write the evidence index without using a token")
|
|
parser.add_argument("--evidence-out", type=Path, default=Path("dist/gitea-release-evidence.json"))
|
|
args = parser.parse_args()
|
|
if not TAG.fullmatch(args.tag) or args.pipeline < 1:
|
|
parser.error("expected a release tag and a positive component CI pipeline number")
|
|
value = "" if args.prepare else os.environ.get("GITEA_TOKEN", "")
|
|
if not args.prepare and (not value or args.body_file is None):
|
|
parser.error("publication requires GITEA_TOKEN and --body-file")
|
|
try:
|
|
archive = args.archive.resolve()
|
|
folder = archive.parent
|
|
defaults = [folder / name for name in
|
|
(archive.name + ".sha256", "RELEASE_INFO.json", "FILES.sha256", "smoke-evidence.json")]
|
|
paths = list(dict.fromkeys([archive, *defaults, *(path.resolve() for path in args.files)]))
|
|
require(len(paths) <= 20, "too many release assets")
|
|
index = folder / "release-evidence.json"
|
|
require(index.name not in {path.name for path in paths}
|
|
and len({path.name for path in paths}) == len(paths), "duplicate release asset names")
|
|
service = Service(value)
|
|
proof = candidate(service, args.tag, args.pipeline, paths, publish=not args.prepare)
|
|
index.write_text(json.dumps(proof, sort_keys=True, indent=2) + "\n", encoding="utf-8")
|
|
if args.prepare:
|
|
print(index)
|
|
return 0
|
|
expected = {record["name"]: (path, record) for path, record in
|
|
zip(paths, proof["assets"], strict=True)}
|
|
expected[index.name] = (index, asset_record(index, proof["assets"][0]["target"]))
|
|
release = publish_release(service, args.tag, proof["source_sha"], expected,
|
|
args.body_file.read_text(encoding="utf-8"))
|
|
evidence = {"schema": "marqdo.knowledge.gitea-release", "schema_version": 1,
|
|
"tag": args.tag, "release_id": release["id"], "html_url": release["html_url"],
|
|
"prerelease": True, "assets": [record for _, record in expected.values()]}
|
|
args.evidence_out.parent.mkdir(parents=True, exist_ok=True)
|
|
args.evidence_out.write_text(json.dumps(evidence, sort_keys=True, indent=2) + "\n", encoding="utf-8")
|
|
print(f"release_url: {release['html_url']}")
|
|
except (OSError, ValueError, KeyError, TypeError, PublicationError, subprocess.CalledProcessError) as error:
|
|
print(f"publish-gitea: FAIL: {error}", file=sys.stderr)
|
|
return 1
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|