235 lines
12 KiB
Python
235 lines
12 KiB
Python
# Copyright (c) 2026 Storm Dragon
|
|
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
"""Publish this repository's prepared releases using SSH-agent HTTP signatures.
|
|
|
|
Requires Paramiko and an RSA key registered with Gitea, loaded in ssh-agent.
|
|
No API token or private-key file is read or stored.
|
|
"""
|
|
|
|
import argparse
|
|
import base64
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import subprocess
|
|
import tarfile
|
|
import time
|
|
import tomllib
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
import uuid
|
|
|
|
import paramiko
|
|
|
|
|
|
ORIGIN = "https://git.stormux.org"
|
|
REPO_API = "/api/v1/repos/storm/cthulhu-tentacles"
|
|
|
|
|
|
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
def redirect_request(self, request, source, code, message, headers, newURL):
|
|
raise RuntimeError("Refusing to redirect an authenticated request")
|
|
|
|
|
|
class HTTPSRedirect(urllib.request.HTTPRedirectHandler):
|
|
def redirect_request(self, request, source, code, message, headers, newURL):
|
|
parsed = urllib.parse.urlsplit(newURL)
|
|
if parsed.scheme != "https" or parsed.username or parsed.password:
|
|
raise RuntimeError("Release download redirect must use HTTPS without credentials")
|
|
return super().redirect_request(request, source, code, message, headers, newURL)
|
|
|
|
|
|
class Publisher:
|
|
def __init__(self, fingerprint=None):
|
|
self.agent = paramiko.Agent()
|
|
keys = [key for key in self.agent.get_keys() if key.get_name() == "ssh-rsa"]
|
|
if fingerprint:
|
|
keys = [key for key in keys if self.key_fingerprint(key) == fingerprint]
|
|
if len(keys) != 1:
|
|
self.agent.close()
|
|
raise RuntimeError("Load one registered RSA key in ssh-agent, or select it with --ssh-key SHA256:...")
|
|
self.key = keys[0]
|
|
self.fingerprint = self.key_fingerprint(self.key)
|
|
self.opener = urllib.request.build_opener(NoRedirect())
|
|
|
|
@staticmethod
|
|
def key_fingerprint(key):
|
|
return "SHA256:" + base64.b64encode(hashlib.sha256(key.asbytes()).digest()).decode().rstrip("=")
|
|
|
|
def request(self, method, route, body=None, contentType=None, allowMissing=False):
|
|
parsed = urllib.parse.urlsplit(route)
|
|
if (method not in ("GET", "POST", "PATCH") or parsed.scheme or parsed.netloc
|
|
or parsed.fragment or ".." in parsed.path.split("/")
|
|
or not (method == "GET" and route == "/api/v1/user"
|
|
or parsed.path == REPO_API or parsed.path.startswith(REPO_API + "/"))):
|
|
raise RuntimeError("Request is outside this repository's release API")
|
|
created = int(time.time())
|
|
expires = created + 30
|
|
names = ["(request-target)", "(created)", "(expires)"]
|
|
lines = [f"(request-target): {method.lower()} {route}",
|
|
f"(created): {created}", f"(expires): {expires}"]
|
|
headers = {"Accept": "application/json"}
|
|
if body is not None:
|
|
digest = "SHA-512=" + base64.b64encode(hashlib.sha512(body).digest()).decode()
|
|
headers["Digest"] = digest
|
|
headers["Content-Type"] = contentType or "application/json"
|
|
names.append("digest")
|
|
lines.append("digest: " + digest)
|
|
signed = self.key.sign_ssh_data("\n".join(lines).encode(), algorithm="rsa-sha2-256")
|
|
wire = paramiko.Message(signed if isinstance(signed, bytes) else signed.asbytes())
|
|
if wire.get_text() != "rsa-sha2-256":
|
|
raise RuntimeError("Unexpected SSH signature algorithm")
|
|
signature = base64.b64encode(wire.get_binary()).decode()
|
|
headerNames = " ".join(names)
|
|
headers["Signature"] = (f'keyId="{self.fingerprint}",algorithm="hs2019",'
|
|
f'created={created},expires={expires},'
|
|
f'headers="{headerNames}",signature="{signature}"')
|
|
request = urllib.request.Request(ORIGIN + route, data=body, headers=headers, method=method)
|
|
try:
|
|
with self.opener.open(request, timeout=45) as response:
|
|
data = response.read((2 << 20) + 1)
|
|
if len(data) > 2 << 20:
|
|
raise RuntimeError("Release API response is too large")
|
|
return json.loads(data) if data else None
|
|
except urllib.error.HTTPError as error:
|
|
if allowMissing and method == "GET" and error.code == 404:
|
|
return None
|
|
raise RuntimeError(f"Git server rejected {method} {route}: HTTP {error.code}") from None
|
|
|
|
def authenticate(self):
|
|
account = self.request("GET", "/api/v1/user")
|
|
repository = self.request("GET", REPO_API)
|
|
if not repository.get("permissions", {}).get("push"):
|
|
raise RuntimeError("The signing account lacks repository write access")
|
|
print(f"SSH-signed authentication and repository write access verified for {account['login']}.", flush=True)
|
|
|
|
def close(self):
|
|
self.agent.close()
|
|
|
|
|
|
def release_artifacts(repoRoot, name):
|
|
catalog = tomllib.loads((repoRoot / "dist/catalog.toml").read_text())
|
|
matches = [entry for entry in catalog["tentacles"] if entry["id"] == name]
|
|
if len(matches) != 1:
|
|
raise RuntimeError("Select one Tentacle from the prepared catalog")
|
|
entry = matches[0]
|
|
if entry["manifest"] != f"{name}/tentacle.toml":
|
|
raise RuntimeError("Manifest path must match the Tentacle ID")
|
|
manifestBytes = (repoRoot / entry["manifest"]).read_bytes()
|
|
manifest = tomllib.loads(manifestBytes.decode())
|
|
version = manifest["version"]
|
|
tagName = f"{name}-v{version}"
|
|
prefix = f"{ORIGIN}/storm/cthulhu-tentacles/releases/download/{tagName}/"
|
|
artifacts = []
|
|
targets = set()
|
|
for release in entry.get("releases", []):
|
|
target = (release["platform"], release["architecture"])
|
|
filename = f"{name}-{version}-{target[0]}-{target[1]}.tar.gz"
|
|
if target in targets or target[0] != "linux" or target[1] not in ("amd64", "arm64"):
|
|
raise RuntimeError("Invalid or duplicate release architecture")
|
|
targets.add(target)
|
|
if release["url"] != prefix + filename:
|
|
raise RuntimeError("Prepared URL does not match this release")
|
|
artifactPath = repoRoot / "dist" / filename
|
|
digest = hashlib.sha256(artifactPath.read_bytes()).hexdigest()
|
|
if digest != release["sha256"]:
|
|
raise RuntimeError("Archive digest differs from the prepared catalog")
|
|
with tarfile.open(artifactPath) as archive:
|
|
if archive.extractfile("tentacle.toml").read() != manifestBytes:
|
|
raise RuntimeError("Archive manifest differs from the source")
|
|
for filename in ("README.md", "LICENSE"):
|
|
if archive.extractfile(filename).read() != (repoRoot / name / filename).read_bytes():
|
|
raise RuntimeError("Archive documentation differs from the source")
|
|
artifacts.append((artifactPath, release))
|
|
if not artifacts:
|
|
raise RuntimeError("No prepared release artifacts")
|
|
expectedSums = "".join(f"{release['sha256']} {path.name}\n" for path, release in artifacts)
|
|
if (repoRoot / "dist/SHA256SUMS").read_text() != expectedSums:
|
|
raise RuntimeError("SHA256SUMS must contain exactly the selected release artifacts")
|
|
return manifest, tagName, artifacts
|
|
|
|
|
|
def verify_downloads(repoRoot, artifacts, tagName):
|
|
opener = urllib.request.build_opener(HTTPSRedirect())
|
|
for artifactPath, release in artifacts:
|
|
with opener.open(release["url"], timeout=60) as response:
|
|
data = response.read((32 << 20) + 1)
|
|
if len(data) > 32 << 20 or hashlib.sha256(data).hexdigest() != release["sha256"]:
|
|
raise RuntimeError("Published download differs from the prepared archive")
|
|
print(f"Verified public download: {artifactPath.name}", flush=True)
|
|
url = f"{ORIGIN}/storm/cthulhu-tentacles/releases/download/{tagName}/SHA256SUMS"
|
|
with opener.open(url, timeout=45) as response:
|
|
if response.read(8193) != (repoRoot / "dist/SHA256SUMS").read_bytes():
|
|
raise RuntimeError("Published SHA256SUMS differs from the prepared file")
|
|
print("Public archives and SHA256SUMS verified.", flush=True)
|
|
|
|
|
|
def publish(publisher, repoRoot, manifest, tagName, artifacts, notesPath):
|
|
notes = notesPath.read_text()
|
|
if not notes.strip():
|
|
raise RuntimeError("Release notes are empty")
|
|
if subprocess.check_output(["git", "status", "--porcelain"], cwd=repoRoot):
|
|
raise RuntimeError("Commit and review source changes before publication")
|
|
commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repoRoot, text=True).strip()
|
|
refs = subprocess.check_output(["git", "ls-remote", "--tags", "origin", f"refs/tags/{tagName}",
|
|
f"refs/tags/{tagName}^{{}}"], cwd=repoRoot, text=True)
|
|
tagRefs = dict(line.split()[::-1] for line in refs.splitlines())
|
|
if tagRefs.get(f"refs/tags/{tagName}^{{}}", tagRefs.get(f"refs/tags/{tagName}")) != commit:
|
|
raise RuntimeError("Push the release tag at the reviewed source commit first")
|
|
existing = publisher.request("GET", REPO_API + f"/releases/tags/{tagName}", allowMissing=True)
|
|
if existing:
|
|
raise RuntimeError("Release already exists; inspect it before retrying")
|
|
release = publisher.request("POST", REPO_API + "/releases", json.dumps({
|
|
"tag_name": tagName, "target_commitish": commit,
|
|
"name": f"{manifest['name']} {manifest['version']} (experimental)",
|
|
"body": notes, "draft": True, "prerelease": True,
|
|
}).encode())
|
|
releaseID = release["id"]
|
|
print(f"Created draft release {releaseID}; upload failures leave it draft for inspection.", flush=True)
|
|
assetPaths = [path for path, _ in artifacts] + [repoRoot / "dist/SHA256SUMS"]
|
|
for artifactPath in assetPaths:
|
|
boundary = "TentacleUpload" + uuid.uuid4().hex
|
|
header = (f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; '
|
|
f'filename="{artifactPath.name}"\r\nContent-Type: application/octet-stream\r\n\r\n').encode()
|
|
body = header + artifactPath.read_bytes() + f"\r\n--{boundary}--\r\n".encode()
|
|
route = REPO_API + f"/releases/{releaseID}/assets?" + urllib.parse.urlencode({"name": artifactPath.name})
|
|
asset = publisher.request("POST", route, body, f"multipart/form-data; boundary={boundary}")
|
|
if asset["name"] != artifactPath.name or asset["size"] != artifactPath.stat().st_size:
|
|
raise RuntimeError("Uploaded asset identity or size differs")
|
|
print(f"Uploaded {artifactPath.name}", flush=True)
|
|
publisher.request("PATCH", REPO_API + f"/releases/{releaseID}", json.dumps({"draft": False}).encode())
|
|
verify_downloads(repoRoot, artifacts, tagName)
|
|
print(f"Published {ORIGIN}/storm/cthulhu-tentacles/releases/tag/{tagName}", flush=True)
|
|
print("Review and push the prepared catalog to the default branch after these download checks.")
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("action", choices=("auth", "publish", "verify"))
|
|
parser.add_argument("--tentacle", help="One prepared Tentacle ID")
|
|
parser.add_argument("--notes", type=Path, help="Reviewed release notes file")
|
|
parser.add_argument("--ssh-key", help="Select a loaded RSA key by its SHA256 fingerprint")
|
|
args = parser.parse_args()
|
|
if args.action != "auth" and (not args.tentacle or any(c not in "abcdefghijklmnopqrstuvwxyz0123456789.-" for c in args.tentacle)):
|
|
parser.error("Select a valid --tentacle ID")
|
|
if args.action == "publish" and not args.notes:
|
|
parser.error("Publication requires --notes")
|
|
repoRoot = Path(__file__).resolve().parents[1]
|
|
if args.action != "auth":
|
|
manifest, tagName, artifacts = release_artifacts(repoRoot, args.tentacle)
|
|
if args.action == "verify":
|
|
verify_downloads(repoRoot, artifacts, tagName)
|
|
return
|
|
publisher = Publisher(args.ssh_key)
|
|
try:
|
|
publisher.authenticate()
|
|
if args.action == "publish":
|
|
publish(publisher, repoRoot, manifest, tagName, artifacts, args.notes)
|
|
finally:
|
|
publisher.close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|