#!/usr/bin/env python3 """Validate packages and publish a resumable, commit-bound Gitea draft. Requires Python 3.11+, Git and Gitea >=1.26.2. Run from the tagged checkout. `check` is read-only; `publish` requires GITEA_TOKEN. Arguments default to the workflow's GITEA_API_URL, GITEA_REPOSITORY, RELEASE_TAG and RELEASE_COMMIT env. Serialize invocations for the same repository/tag (the workflow does this). HTTP is accepted only for loopback fixtures. API redirects are never followed; attachment redirects receive credentials only while they stay on the API origin. """ import argparse import hashlib import json import os from pathlib import Path import re import subprocess import sys import tomllib import urllib.error import urllib.parse import urllib.request import uuid NAME = "rusty-path-of-building" VERSION = r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)" CHUNK = 1024 * 1024 class ReleaseError(Exception): """A conflict or failed prerequisite; leave the release for inspection/retry.""" def require(condition, message): if not condition: raise ReleaseError(message) def expected_names(version, platform="all"): names = { "windows": [f"{NAME}-{version}-windows-x86_64.zip", f"{NAME}-{version}-windows-x86_64-setup.exe"], "linux": [f"{NAME}-{version}-linux-x86_64.tar.gz", f"{NAME}_{version}_amd64.deb"], } return names[platform] if platform != "all" else names["windows"] + names["linux"] def fingerprint(stream, limit=None): digest = hashlib.sha256() size = 0 while chunk := stream.read(CHUNK): size += len(chunk) require(limit is None or size <= limit, "Attachment exceeds expected size") digest.update(chunk) return size, digest.hexdigest() def local_assets(directory, names): require(directory.is_dir() and not directory.is_symlink(), "Asset directory is missing or a symlink") require({p.name for p in directory.iterdir()} == set(names), "Asset directory must contain exactly the expected filenames: " + ", ".join(names)) result = {} for name in names: path = directory / name require(path.is_file() and not path.is_symlink(), f"Not a regular asset: {name}") with path.open("rb") as stream: size, digest = fingerprint(stream) require(size > 0, f"Empty asset: {name}") result[name] = (path, size, digest) return result def local_identity(source, tag, revision): require(re.fullmatch("v" + VERSION, tag or ""), "Tag must be exactly vX.Y.Z") with (source / "Cargo.toml").open("rb") as stream: package = tomllib.load(stream)["package"] require(package["name"] == NAME, "Unexpected Cargo package name") require(tag == "v" + package["version"], "Tag does not match Cargo.toml version") require(re.fullmatch(r"(?:[0-9a-fA-F]{40}|[0-9a-fA-F]{64})", revision or ""), "Supply the full event commit/object SHA with --commit or RELEASE_COMMIT") def resolve(ref): completed = subprocess.run(["git", "-C", str(source), "rev-parse", "--verify", ref], capture_output=True, text=True) require(completed.returncode == 0, "Cannot resolve checkout/event commit") return completed.stdout.strip().lower() commit = resolve("HEAD^{commit}") require(commit == resolve(revision + "^{commit}"), "Checkout differs from event commit") return package["version"], commit def checked_url(url): parsed = urllib.parse.urlsplit(url) require(parsed.scheme == "https" or (parsed.scheme == "http" and parsed.hostname in {"localhost", "127.0.0.1", "::1"}), "Use HTTPS (HTTP is allowed only for a loopback fixture)") require(parsed.hostname and not parsed.username and not parsed.password and not parsed.fragment, "Invalid URL or embedded URL credentials") return parsed def origin(url): parsed = checked_url(url) return parsed.scheme, parsed.hostname, parsed.port or (443 if parsed.scheme == "https" else 80) class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): return None class Gitea: def __init__(self, api_url, token=""): self.api_url = api_url.rstrip("/") parsed = checked_url(self.api_url) require(parsed.path.endswith("/api/v1") and not parsed.query, "API URL must end in /api/v1") self.token = token self.opener = urllib.request.build_opener(NoRedirect()) def open(self, method, url, data=None, headers=None, authenticated=True): checked_url(url) headers = {"User-Agent": NAME + "-release", **(headers or {})} if authenticated and self.token: require(origin(url) == origin(self.api_url), "Refusing cross-origin credentials") headers["Authorization"] = "token " + self.token return self.opener.open(urllib.request.Request(url, data=data, headers=headers, method=method), timeout=120) def request(self, method, path, body=None, missing_ok=False, data=None, headers=None): headers = {"Accept": "application/json", **(headers or {})} if body is not None: data = json.dumps(body).encode() headers["Content-Type"] = "application/json" try: with self.open(method, self.api_url + path, data, headers) as response: payload = response.read() return json.loads(payload) if payload else None except urllib.error.HTTPError as error: error.close() if error.code == 404 and missing_ok: return None # Never echo response bodies, signed redirect URLs or headers containing credentials. raise ReleaseError(f"Gitea {method} request failed (HTTP {error.code})") from None def check_version(self): version = self.request("GET", "/version").get("version", "") match = re.fullmatch(r"v?(\d+)\.(\d+)\.(\d+)(?:\+[0-9A-Za-z.-]+)?", version) require(match and tuple(map(int, match.groups())) >= (1, 26, 2), "Gitea >=1.26.2 stable is required for release concurrency/artifact safety") return version def download_fingerprint(self, url, size): # A storage redirect may carry its own signed query, but never our token. authenticated = origin(url) == origin(self.api_url) for _ in range(6): try: with self.open("GET", url, authenticated=authenticated) as response: return fingerprint(response, limit=size) except urllib.error.HTTPError as error: location = error.headers.get("Location") code = error.code error.close() if code not in {301, 302, 303, 307, 308} or not location: raise ReleaseError(f"Attachment download failed (HTTP {code})") from None next_url = urllib.parse.urljoin(url, location) require(not (checked_url(url).scheme == "https" and checked_url(next_url).scheme != "https"), "Refusing attachment HTTPS downgrade") authenticated = authenticated and origin(next_url) == origin(self.api_url) url = next_url raise ReleaseError("Too many attachment redirects") def upload(self, path, asset): filename, size, _ = asset boundary = "release-" + uuid.uuid4().hex prefix = (f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; ' f'filename="{filename.name}"\r\nContent-Type: application/octet-stream\r\n\r\n').encode() suffix = f"\r\n--{boundary}--\r\n".encode() def chunks(): yield prefix with filename.open("rb") as stream: while chunk := stream.read(CHUNK): yield chunk yield suffix return self.request("POST", path, data=chunks(), headers={ "Content-Type": f"multipart/form-data; boundary={boundary}", "Content-Length": str(len(prefix) + size + len(suffix)), }) def release_notes(source, version): changelog = source / "CHANGELOG.md" if not changelog.is_file(): return f"Release v{version}" text = changelog.read_text(encoding="utf-8") match = re.search(r"^## \[" + re.escape(version) + r"\][^\n]*\n(.*?)(?=^## \[|\Z)", text, re.MULTILINE | re.DOTALL) return match.group(1).strip() if match else f"Release v{version}" class Publisher: def __init__(self, api, repository, tag, commit, assets): require(re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository or ""), "Repository must be owner/name") require(all(part not in {".", ".."} for part in repository.split("/")), "Invalid repository") self.api, self.tag, self.commit, self.assets = api, tag, commit, assets self.base = "/repos/" + repository self.marker = f"" def check_tag(self): tag = self.api.request("GET", self.base + "/tags/" + self.tag) require(tag.get("name") == self.tag and tag.get("commit", {}).get("sha") == self.commit, "Live tag does not point to the checked-out commit") def release(self): return self.api.request("GET", self.base + "/releases/tags/" + self.tag, missing_ok=True) def inspect(self, release): require(release and release.get("tag_name") == self.tag and release.get("target_commitish") == self.commit and release.get("body", "").splitlines().count(self.marker) == 1 and release.get("prerelease") is False and type(release.get("draft")) is bool, "Release is not an owned, commit-matching stable release; refusing changes") require(type(release.get("id")) is int and release["id"] > 0, "Invalid release ID") attachments = self.api.request("GET", self.base + f'/releases/{release["id"]}/assets') indexed = {} for attachment in attachments: name = attachment.get("name") require(name in self.assets and name not in indexed, "Unexpected or duplicate release attachment") require(type(attachment.get("id")) is int and attachment["id"] > 0 and type(attachment.get("size")) is int and attachment["size"] >= 0, "Invalid attachment metadata") # Download counters change during our own hash verification. indexed[name] = {key: attachment[key] for key in ("id", "name", "size", "browser_download_url")} return indexed def matches(self, attachment, asset): _, size, digest = asset if attachment["size"] != size: return False return self.api.download_fingerprint(attachment["browser_download_url"], size) == (size, digest) def verify_complete(self, attachments): require(set(attachments) == set(self.assets), "Release does not have exactly four expected attachments") for name, asset in self.assets.items(): require(self.matches(attachments[name], asset), f"Release attachment differs: {name}") def guard_draft(self, release_id): release = self.release() attachments = self.inspect(release) require(release["id"] == release_id and release["draft"], "Draft changed or became public; refusing mutation") self.check_tag() return attachments def publish(self, notes): self.check_tag() release = self.release() if release is None: self.check_tag() release = self.api.request("POST", self.base + "/releases", { "tag_name": self.tag, "target_commitish": self.commit, "name": self.tag, "body": notes + "\n\n" + self.marker, "draft": True, "prerelease": False, }) attachments = self.inspect(release) if not release["draft"]: self.verify_complete(attachments) self.check_tag() print("Published release already matches all four assets; no changes made.") return release_id = release["id"] path = self.base + f"/releases/{release_id}/assets" # Plan all conflicts before changing anything. Unknown attachments always fail closed. replace = [name for name, attachment in attachments.items() if not self.matches(attachment, self.assets[name])] for name, asset in self.assets.items(): if name in attachments and name not in replace: continue current = self.guard_draft(release_id) if name in current: require(name in replace and current[name]["id"] == attachments[name]["id"], "Attachment changed concurrently; rerun after inspection") self.api.request("DELETE", path + f'/{current[name]["id"]}') self.guard_draft(release_id) self.api.upload(path, asset) current = self.guard_draft(release_id) self.verify_complete(current) # Hashing can take time: check draft status and the live tag again immediately before PATCH. latest = self.guard_draft(release_id) require(set(latest) == set(current) and all( latest[name]["id"] == item["id"] and latest[name]["size"] == item["size"] for name, item in current.items() ), "Attachments changed during verification") self.api.request("PATCH", self.base + f"/releases/{release_id}", {"draft": False}) published = self.release() require(published and published.get("draft") is False, "Publication was not confirmed; rerun safely") self.verify_complete(self.inspect(published)) self.check_tag() print("Published release verified: four attachments with matching sizes and SHA-256.") def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("command", choices=["check", "publish"]) parser.add_argument("--source", type=Path, default=Path.cwd(), help="Tagged Git checkout (default: cwd)") parser.add_argument("--assets", type=Path, help="Directory containing only the expected packages") parser.add_argument("--platform", choices=["all", "windows", "linux"], default="all", help="check only") parser.add_argument("--tag", default=os.environ.get("RELEASE_TAG")) parser.add_argument("--commit", default=os.environ.get("RELEASE_COMMIT"), help="Full event SHA; peeled before comparison") parser.add_argument("--repository", default=os.environ.get("GITEA_REPOSITORY")) parser.add_argument("--api-url", default=os.environ.get("GITEA_API_URL"), help="Gitea API base, ending /api/v1") args = parser.parse_args(argv) try: version, commit = local_identity(args.source, args.tag, args.commit) require(args.command != "publish" or (args.assets and args.platform == "all"), "publish requires --assets with all four packages") assets = local_assets(args.assets, expected_names(version, args.platform)) if args.assets else None require(args.api_url, "Supply --api-url or GITEA_API_URL") token = os.environ.get("GITEA_TOKEN", "") if args.command == "publish" else "" require(args.command != "publish" or token, "publish requires GITEA_TOKEN") api = Gitea(args.api_url, token) server_version = api.check_version() if args.command == "check": print(f"Validated {args.tag} at {commit}; Gitea {server_version}; " f"{len(assets) if assets else 0} assets checked.") else: Publisher(api, args.repository, args.tag, commit, assets).publish(release_notes(args.source, version)) return 0 except (ReleaseError, OSError, ValueError, KeyError, TypeError, urllib.error.URLError) as error: # Network errors can embed signed URLs; report only their type. message = str(error) if isinstance(error, ReleaseError) else type(error).__name__ print("Release failed: " + message, file=sys.stderr) return 1 if __name__ == "__main__": sys.exit(main())