Prepare Remote 0.1.0 test release and retain SSH-signed publishing
This commit is contained in:
1 parent
d7da6548e1
commit
346ec77c75
8 files changed
+450
-29
No files matched your search
+9
-4
@@ -31,8 +31,8 @@ def check_metadata(repoRoot):
|
||||
"Unsupported metadata format")
|
||||
require(repository["id"] == "storm.cthulhu-tentacles" and repository["name"],
|
||||
"Repository identity is missing")
|
||||
require([item["id"] for item in catalog["tentacles"]] == ["hello-world", "wormhole", "battery-status"],
|
||||
"Catalog must list Hello World, Wormhole, and Battery Status")
|
||||
require([item["id"] for item in catalog["tentacles"]] == ["hello-world", "wormhole", "battery-status", "remote"],
|
||||
"Catalog must list Hello World, Wormhole, Battery Status, and Remote")
|
||||
for item in catalog["tentacles"]:
|
||||
name = item["id"]
|
||||
require(item["manifest"] == f"{name}/tentacle.toml", "Manifest path must match ID")
|
||||
@@ -40,10 +40,15 @@ def check_metadata(repoRoot):
|
||||
require(manifest["format-version"] == 1 and manifest["id"] == name
|
||||
and manifest["name"] and manifest["version"] == ("0.1.2" if name == "wormhole" else "0.1.0"), "Invalid Tentacle metadata")
|
||||
expectedGrants = ["presentation"] + (["interaction"] if name in ("wormhole", "battery-status") else [])
|
||||
if name == "remote":
|
||||
expectedGrants = ["presentation", "interaction", "output-observe", "remote-present", "keyboard-capture",
|
||||
"keyboard-inject", "braille-stream", "clipboard-exchange"]
|
||||
expectedApis = (["commands", "session-events", "presentation", "interaction", "remote-access"]
|
||||
if name == "remote" else ["commands"] + expectedGrants)
|
||||
expectedProgram = "wormhole-tentacle" if name == "wormhole" else name
|
||||
require(manifest["entry-point"] == [f"bin/{expectedProgram}"]
|
||||
and manifest["capabilities"] == expectedGrants
|
||||
and manifest["apis"] == ["commands"] + expectedGrants,
|
||||
and manifest["apis"] == expectedApis,
|
||||
"Unexpected launch or grants")
|
||||
require((repoRoot / "LICENSE").is_file() and (repoRoot / name / "LICENSE").is_file()
|
||||
and (repoRoot / name / "README.md").is_file(), "License and help are required")
|
||||
@@ -156,7 +161,7 @@ def check_host(repoRoot, programPath, name):
|
||||
|
||||
|
||||
def check_remote_manifest(repoRoot, readerRoot):
|
||||
"""Remote is not in the catalog until a release is published and verified."""
|
||||
"""Check Remote's protocol and grants against the matching reader SDK."""
|
||||
manifest = read_toml(repoRoot / "remote/tentacle.toml")
|
||||
require(manifest["format-version"] == 1 and manifest["id"] == "remote" and manifest["name"] == "Remote"
|
||||
and manifest["runtime"] == "native" and manifest["platforms"] == ["linux"]
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
# 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()
|
||||
@@ -0,0 +1,98 @@
|
||||
# Copyright (c) 2026 Storm Dragon
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Offline checks for release authentication and publication guards."""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import io
|
||||
import re
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
import urllib.error
|
||||
|
||||
import paramiko
|
||||
|
||||
import publish
|
||||
|
||||
|
||||
class PublisherTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.signingKey = paramiko.RSAKey.generate(1024)
|
||||
|
||||
def make_publisher(self, response=b'{"id":1}'):
|
||||
publisher = publish.Publisher.__new__(publish.Publisher)
|
||||
publisher.key = self.signingKey
|
||||
publisher.fingerprint = publisher.key_fingerprint(self.signingKey)
|
||||
publisher.opener = SimpleNamespace(open=Mock(return_value=io.BytesIO(response)))
|
||||
return publisher
|
||||
|
||||
def test_upload_signature_authenticates_body_and_query(self):
|
||||
publisher = self.make_publisher()
|
||||
route = publish.REPO_API + "/releases/1/assets?name=example.tar.gz"
|
||||
body = b"example release content"
|
||||
with patch.object(publish.time, "time", return_value=1000):
|
||||
self.assertEqual(publisher.request("POST", route, body), {"id": 1})
|
||||
request = publisher.opener.open.call_args.args[0]
|
||||
fields = dict(re.findall(r'(\w+)="([^"]*)"', request.get_header("Signature")))
|
||||
digest = "SHA-512=" + base64.b64encode(hashlib.sha512(body).digest()).decode()
|
||||
expected = (f"(request-target): post {route}\n(created): 1000\n(expires): 1030\ndigest: {digest}").encode()
|
||||
signature = paramiko.Message()
|
||||
signature.add_string("rsa-sha2-256")
|
||||
signature.add_string(base64.b64decode(fields["signature"]))
|
||||
self.assertTrue(self.signingKey.verify_ssh_sig(expected, paramiko.Message(signature.asbytes())))
|
||||
self.assertFalse(self.signingKey.verify_ssh_sig(expected + b"changed", paramiko.Message(signature.asbytes())))
|
||||
self.assertEqual(request.data, body)
|
||||
self.assertEqual(request.get_header("Digest"), digest)
|
||||
self.assertEqual(fields["headers"], "(request-target) (created) (expires) digest")
|
||||
|
||||
def test_repository_boundary_rejects_requests_before_signing(self):
|
||||
publisher = self.make_publisher()
|
||||
for method, route in (("GET", "https://example.org/"), ("DELETE", publish.REPO_API),
|
||||
("POST", "/api/v1/user"), ("GET", publish.REPO_API + "-other"),
|
||||
("GET", publish.REPO_API + "/../other")):
|
||||
with self.subTest(method=method, route=route), self.assertRaises(RuntimeError):
|
||||
publisher.request(method, route)
|
||||
publisher.opener.open.assert_not_called()
|
||||
|
||||
def test_signed_requests_never_follow_redirects(self):
|
||||
with self.assertRaisesRegex(RuntimeError, "redirect"):
|
||||
publish.NoRedirect().redirect_request(None, None, 302, None, None, "https://example.org/")
|
||||
with self.assertRaisesRegex(RuntimeError, "HTTPS"):
|
||||
publish.HTTPSRedirect().redirect_request(None, None, 302, None, None, "http://example.org/")
|
||||
|
||||
def test_missing_release_is_distinct_from_failed_authentication(self):
|
||||
publisher = self.make_publisher()
|
||||
route = publish.REPO_API + "/releases/tags/example-v0.1.0"
|
||||
for status in (401, 403, 404):
|
||||
publisher.opener.open.side_effect = urllib.error.HTTPError(publish.ORIGIN + route, status, "", {}, None)
|
||||
if status == 404:
|
||||
self.assertIsNone(publisher.request("GET", route, allowMissing=True))
|
||||
else:
|
||||
with self.assertRaisesRegex(RuntimeError, f"HTTP {status}"):
|
||||
publisher.request("GET", route, allowMissing=True)
|
||||
|
||||
def test_ambiguous_agent_keys_require_explicit_selection(self):
|
||||
agent = Mock()
|
||||
agent.get_keys.return_value = [self.signingKey, self.signingKey]
|
||||
with patch.object(publish.paramiko, "Agent", return_value=agent):
|
||||
with self.assertRaisesRegex(RuntimeError, "select it"):
|
||||
publish.Publisher()
|
||||
agent.close.assert_called_once()
|
||||
|
||||
def test_existing_release_cannot_be_overwritten(self):
|
||||
publisher = self.make_publisher()
|
||||
publisher.request = Mock(return_value={"id": 1})
|
||||
notesPath = Mock()
|
||||
notesPath.read_text.return_value = "Example release notes"
|
||||
responses = [b"", "a" * 40, "a" * 40 + "\trefs/tags/example-v0.1.0\n"]
|
||||
with patch.object(publish.subprocess, "check_output", side_effect=responses):
|
||||
with self.assertRaisesRegex(RuntimeError, "already exists"):
|
||||
publish.publish(publisher, Mock(), {}, "example-v0.1.0", [], notesPath)
|
||||
self.assertEqual(publisher.request.call_count, 1)
|
||||
self.assertEqual(publisher.request.call_args.args[0], "GET")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user