diff --git a/.gitea/scripts/build-release.sh b/.gitea/scripts/build-release.sh new file mode 100644 index 0000000..4eaa262 --- /dev/null +++ b/.gitea/scripts/build-release.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# CI, job `release`: build the server for Linux x86_64 on Ubuntu 22.04 (so +# glibc 2.35 or newer runs it), with the release version and the commit in +# its --version, and pack it under a name without the version: +# dist/visa-linux-x86_64.tar.gz bin/visa, VERSION, COMMIT +# cnx01 installs it (cnx-network-clan modules/visa) after the job's next step +# has signed it (.gitea/scripts/sign-release.sh), and checks that VERSION is +# the release's name. +# bash .gitea/scripts/build-release.sh 2026.11.0 +set -euo pipefail +version=${1:?version, e.g. 2026.11.0} +commit=$(git rev-parse HEAD) + +# The tag is the source of truth: CI writes it into Cargo.toml (the committed +# one keeps a placeholder) and the lock file follows. +sed -i -E "/^\[package\]/,/^\[/ s/^version = \"[^\"]*\"/version = \"$version\"/" Cargo.toml +cargo update --workspace --quiet + +# the footer's and /version's commit (build.rs) +VISA_COMMIT=$commit cargo build --release --locked --bin visa + +got=$(target/release/visa --version) +if [ "$got" != "visa $version ($commit)" ]; then + echo "visa --version says '$got', expected 'visa $version ($commit)'" >&2 + exit 1 +fi + +rm -rf dist +pack=dist/visa +mkdir -p "$pack/bin" +cp target/release/visa "$pack/bin/" +printf '%s\n' "$version" >"$pack/VERSION" +printf '%s\n' "$commit" >"$pack/COMMIT" +tar -C "$pack" --owner=0 --group=0 --numeric-owner -czf dist/visa-linux-x86_64.tar.gz bin VERSION COMMIT +rm -rf "$pack" +ls -l dist diff --git a/.gitea/scripts/release.py b/.gitea/scripts/release.py new file mode 100644 index 0000000..80bf703 --- /dev/null +++ b/.gitea/scripts/release.py @@ -0,0 +1,316 @@ +#!/usr/bin/env python3 +"""Release the pushed commit as the next CalVer version (job `release` in .gitea/workflows/ci.yml). + + python3 .gitea/scripts/release.py reserve # version= and release_id= to $GITHUB_OUTPUT + python3 .gitea/scripts/release.py publish dist/* # attach the files, then publish + python3 .gitea/scripts/release.py discard # after a failure: delete the draft + +The version is YYYY.M.MICRO in Bangkok time, MICRO counting the month's releases from 0 +(2026.11.0, 2026.11.1, 2026.12.0), and the tag has the same name. `reserve` holds the number with +a draft release on the commit, so two runs never take the same one and the build can carry it. +`publish` waits until no older draft of a live run is left, so releases go out in version order +and the newest one is always Gitea's latest: releases/download/latest/ then fetches its +files. A commit that already has a release keeps it (a re-run replaces the files); a commit that a +newer release or draft already contains gets none. + +Reads GITHUB_SERVER_URL, GITHUB_REPOSITORY, GITHUB_SHA and GITHUB_RUN_ID as Gitea Actions sets +them, and TOKEN (the job token). Needs git and a checkout with history and tags. +""" + +import datetime as dt +import hashlib +import json +import os +import re +import subprocess +import sys +import time +import urllib.error +import urllib.parse +import urllib.request +import uuid +from pathlib import Path + +TOOL = "visa" +CALVER = re.compile(r"^(\d{4})\.([1-9]\d?)\.(0|[1-9]\d*)$") +BANGKOK = dt.timezone(dt.timedelta(hours=7)) # Thailand has no daylight saving time +# A draft older than this belongs to a run that is gone: the release job times out sooner. +STALE = dt.timedelta(minutes=95) +# Publish anyway after waiting this long for older drafts; the next release puts the order right. +WAIT_LIMIT = dt.timedelta(minutes=float(os.environ.get("RELEASE_WAIT_MINUTES", "40"))) +MARK = re.compile(r"") +WEB = "visa-linux-x86_64.tar.gz" +PLATFORMS = { + WEB: "Linux x86_64, glibc 2.35 or newer: the server", + WEB + ".sig": "the server's signature by this repository's CI", +} +MAX_COMMITS = 50 +POLL = float(os.environ.get("RELEASE_POLL_SECONDS", "20")) + + +def vkey(tag): + m = CALVER.match(tag or "") + return tuple(int(x) for x in m.groups()) if m else None + + +def git(*args, check=True): + r = subprocess.run(["git", *args], capture_output=True, text=True, encoding="utf-8") + if check and r.returncode: + sys.exit(f"git {' '.join(args)}: {r.stderr.strip()}") + return r + + +def remote_tags(): + """CalVer tags on the server and the commit each points at.""" + tags = {} + for line in git("ls-remote", "--tags", "origin").stdout.splitlines(): + sha, ref = line.split("\t") + name = ref.removeprefix("refs/tags/") + peeled = name.endswith("^{}") + name = name.removesuffix("^{}") + if vkey(name) and (peeled or name not in tags): + tags[name] = sha + return tags + + +def contains(newer, older): + """True when commit `older` is `newer` or one of its ancestors.""" + return git("merge-base", "--is-ancestor", older, newer, check=False).returncode == 0 + + +def now(): + return dt.datetime.now(BANGKOK) + + +def parse_time(text): + return dt.datetime.fromisoformat(text.replace("Z", "+00:00")) + + +class Gitea: + def __init__(self, server, repo, token): + self.api = f"{server.rstrip('/')}/api/v1/repos/{repo}" + self.web = f"{server.rstrip('/')}/{repo}" + self.auth = {"Authorization": f"token {token}"} + + def call(self, method, path, body=None, ctype="application/json"): + data = json.dumps(body).encode() if isinstance(body, dict) else body + req = urllib.request.Request( + self.api + path, + data=data, + method=method, + headers={**self.auth, "Content-Type": ctype, "Accept": "application/json"}, + ) + with urllib.request.urlopen(req, timeout=300) as r: + raw = r.read() + return json.loads(raw) if raw.strip() else None + + def get(self, path): + """GET, or None on 404.""" + try: + return self.call("GET", path) + except urllib.error.HTTPError as e: + if e.code == 404: + return None + raise + + def drafts(self): + out, page = [], 1 + while True: + batch = self.call("GET", f"/releases?draft=true&limit=50&page={page}") or [] + out += [r for r in batch if r.get("draft")] + if len(batch) < 50: + return out + page += 1 + + def create_draft(self, tag, sha, run_id): + return self.call( + "POST", + "/releases", + { + "tag_name": tag, + "target_commitish": sha, + "name": f"{TOOL} {tag}", + "body": f"\nBuilding {sha[:10]} ...", + "draft": True, + "prerelease": False, + }, + ) + + def upload(self, rel_id, name, data): + b = uuid.uuid4().hex + head = ( + f'--{b}\r\nContent-Disposition: form-data; name="attachment"; filename="{name}"\r\n' + "Content-Type: application/octet-stream\r\n\r\n" + ).encode() + body = head + data + f"\r\n--{b}--\r\n".encode() + self.call( + "POST", + f"/releases/{rel_id}/assets?name={urllib.parse.quote(name)}", + body, + f"multipart/form-data; boundary={b}", + ) + + def alive(self, draft): + """Whether the run that reserved `draft` may still publish it.""" + if now() - parse_time(draft["created_at"]) > STALE: + return False + m = MARK.search(draft.get("body") or "") + if m: + try: + run = self.call("GET", f"/actions/runs/{m.group(1)}") + if run and run.get("status") == "completed": + return False + except urllib.error.HTTPError as e: + print(f" (run {m.group(1)}: HTTP {e.code}; the draft's age decides)") + return True + + +def output(**values): + path = os.environ.get("GITHUB_OUTPUT") + lines = "".join(f"{k}={v}\n" for k, v in values.items()) + if path: + with open(path, "a", encoding="utf-8") as f: + f.write(lines) + print(lines, end="") + + +def reserve(g, sha, run_id): + # branches and tags pushed since the checkout, for the ancestry checks below + git("fetch", "-q", "origin", "+refs/heads/*:refs/remotes/origin/*", "+refs/tags/*:refs/tags/*") + tags = remote_tags() + mine = sorted((t for t, s in tags.items() if s == sha), key=vkey) + if mine: + tag = mine[-1] + rel = g.get(f"/releases/tags/{urllib.parse.quote(tag, safe='')}") + if rel is None: # a tag without a release + rel = g.create_draft(tag, sha, run_id) + print(f"{sha[:10]} is already {tag}: release {rel['id']} gets the new files") + return rel + drafts = g.drafts() + for d in drafts: + if d.get("target_commitish") == sha: + g.call("PATCH", f"/releases/{d['id']}", {"body": f"\nBuilding {sha[:10]} ..."}) + print(f"{sha[:10]} already holds {d['tag_name']} (draft {d['id']} of an earlier attempt)") + return d + others = list(tags.items()) + [(d["tag_name"], d.get("target_commitish", "")) for d in drafts] + for name, other in others: + if other and other != sha and contains(other, sha): + print(f"{name} ({other[:10]}) already contains {sha[:10]}: no release of its own") + return None + for _ in range(10): + t = now() + taken = set(tags) | {d["tag_name"] for d in drafts} + micro = 1 + max((vkey(x)[2] for x in taken if vkey(x) and vkey(x)[:2] == (t.year, t.month)), default=-1) + tag = f"{t.year}.{t.month}.{micro}" + try: + rel = g.create_draft(tag, sha, run_id) + print(f"reserved {tag} for {sha[:10]} (draft {rel['id']})") + return rel + except urllib.error.HTTPError as e: + if e.code != 409: + raise + print(f"{tag} was taken meanwhile") + time.sleep(2) + tags, drafts = remote_tags(), g.drafts() + sys.exit("no free version after 10 attempts") + + +def notes(tag, sha, files): + tags = remote_tags() + older = [t for t, s in tags.items() if t != tag and s != sha and contains(sha, s)] + prev = max(older, key=vkey, default=None) + log = git("log", "--no-merges", "--format=- %s (%h)", f"{tags[prev]}..{sha}" if prev else sha).stdout + log = log.splitlines() + if len(log) > MAX_COMMITS: + log = log[:MAX_COMMITS] + [f"- and {len(log) - MAX_COMMITS} earlier commits"] + t = now() + rows = "\n".join( + f"| `{p.name}` | {PLATFORMS.get(p.name, '')} | `{hashlib.sha256(p.read_bytes()).hexdigest()}` |" + for p in files + ) + head = f"Changes since {prev}:" if prev else "Commits in this first release:" + held = ( + f"`{WEB}` holds the server `bin/visa`; cnx01 installs it as visa.buildfor.life only with " + "its signature beside it (`release/allowed-signers`)." + ) + return ( + f"Built by CI from {sha[:10]} on main, {t:%B} {t.day}, {t.year}. {held}\n\n" + f"| File | Platform | SHA-256 |\n|---|---|---|\n{rows}\n\n" + f"{head}\n\n" + ("\n".join(log) or "- (no new commits)") + "\n" + ) + + +def publish(g, rel_id, sha, files): + rel = g.call("GET", f"/releases/{rel_id}") + tag = rel["tag_name"] + old = {a["name"]: a["id"] for a in rel.get("assets") or []} + for p in files: + if p.name in old: + g.call("DELETE", f"/releases/{rel_id}/assets/{old[p.name]}") + data = p.read_bytes() + g.upload(rel_id, p.name, data) + print(f" {'replaced' if p.name in old else 'attached'} {p.name} ({len(data):,} bytes)") + if rel["draft"]: + wait_for_older(g, rel) + g.call("PATCH", f"/releases/{rel_id}", {"body": notes(tag, sha, files), "draft": False}) + got = remote_tags().get(tag) + if got != sha: + sys.exit(f"tag {tag} points at {got}, not at {sha}") + print(f"published {g.web}/releases/tag/{tag}") + + +def wait_for_older(g, rel): + """Publish in version order: wait while an older draft of a live run exists.""" + me = vkey(rel["tag_name"]) + give_up = time.monotonic() + WAIT_LIMIT.total_seconds() + while True: + older = [d for d in g.drafts() if d["id"] != rel["id"] and vkey(d["tag_name"]) and vkey(d["tag_name"]) < me] + alive = [] + for d in older: + if g.alive(d): + alive.append(d) + else: + g.call("DELETE", f"/releases/{d['id']}") + print(f"deleted {d['tag_name']}, a draft whose run is gone") + if not alive: + return + waiting = ", ".join(d["tag_name"] for d in alive) + if time.monotonic() > give_up: + print(f"warning: {waiting} still unpublished after {WAIT_LIMIT}; publishing {rel['tag_name']} first") + return + print(f"waiting for {waiting} to be published first") + time.sleep(POLL) + + +def discard(g, rel_id): + rel = g.get(f"/releases/{rel_id}") if rel_id else None + if rel and rel["draft"]: + g.call("DELETE", f"/releases/{rel_id}") + print(f"deleted draft {rel['tag_name']}: the number is free again") + + +def main(): + if len(sys.argv) < 2 or sys.argv[1] not in ("reserve", "publish", "discard"): + sys.exit(__doc__) + names = ("GITHUB_SERVER_URL", "GITHUB_REPOSITORY", "GITHUB_SHA", "GITHUB_RUN_ID", "TOKEN") + env = {k: os.environ.get(k, "") for k in names} + missing = [k for k, v in env.items() if not v] + if missing: + sys.exit(f"missing environment: {', '.join(missing)}") + g = Gitea(env["GITHUB_SERVER_URL"], env["GITHUB_REPOSITORY"], env["TOKEN"]) + sha = env["GITHUB_SHA"] + cmd, args = sys.argv[1], sys.argv[2:] + if cmd == "reserve": + rel = reserve(g, sha, env["GITHUB_RUN_ID"]) + output(version=rel["tag_name"] if rel else "", release_id=rel["id"] if rel else "") + elif cmd == "publish": + files = [Path(p) for p in args[1:]] + if not args or not files: + sys.exit("publish ...") + publish(g, int(args[0]), sha, files) + else: + discard(g, args[0] if args else "") + + +if __name__ == "__main__": + main() diff --git a/.gitea/scripts/sign-release.sh b/.gitea/scripts/sign-release.sh new file mode 100644 index 0000000..a0594a2 --- /dev/null +++ b/.gitea/scripts/sign-release.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# CI, job `release`: sign the server's archive, which cnx01 installs only +# with this signature (cnx-network-clan modules/visa). The key is the +# repository secret RELEASE_SIGNING_KEY, the base64 of an OpenSSH ed25519 +# key that exists nowhere else; its public half is release/allowed-signers +# (principal visa-ci, namespace visa-release), the same line as the fleet's +# modules/visa/allowed-signers: change both together. The signature is +# checked against that file before it is published, so a secret that does +# not match fails the release here instead of on cnx01. +# RELEASE_SIGNING_KEY=... bash .gitea/scripts/sign-release.sh dist/visa-linux-x86_64.tar.gz +# SIGNERS names another allowed-signers file (the tests). +set -euo pipefail +file=${1:?the archive to sign} +signers=${SIGNERS:-release/allowed-signers} +if [ -z "${RELEASE_SIGNING_KEY:-}" ]; then + echo "the repository secret RELEASE_SIGNING_KEY is not set: no signed release for cnx01" >&2 + exit 1 +fi +key=$(mktemp) +trap 'rm -f "$key"' EXIT +printf '%s' "$RELEASE_SIGNING_KEY" | base64 -d >"$key" +rm -f "$file.sig" +ssh-keygen -q -Y sign -n visa-release -f "$key" "$file" +ssh-keygen -Y verify -f "$signers" -I visa-ci -n visa-release -s "$file.sig" <"$file" diff --git a/.gitea/scripts/test_release.py b/.gitea/scripts/test_release.py new file mode 100644 index 0000000..4b91ff8 --- /dev/null +++ b/.gitea/scripts/test_release.py @@ -0,0 +1,374 @@ +#!/usr/bin/env python3 +"""Tests of release.py against a stub of the Gitea release API and a local origin repository. + + python3 .gitea/scripts/test_release.py + +The stub keeps releases, drafts and assets like Gitea: a draft has no tag, publishing creates the +tag at target_commitish, a second release with the same tag name is refused with 409. +""" + +import base64 +import datetime as dt +import importlib.util +import json +import os +import re +import shutil +import subprocess +import tempfile +import threading +import time +import unittest +import urllib.parse +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +HERE = Path(__file__).resolve().parent +spec = importlib.util.spec_from_file_location("release", HERE / "release.py") +release = importlib.util.module_from_spec(spec) +spec.loader.exec_module(release) + +GIT_ENV = { + "GIT_AUTHOR_NAME": "test", + "GIT_AUTHOR_EMAIL": "test@example.com", + "GIT_COMMITTER_NAME": "test", + "GIT_COMMITTER_EMAIL": "test@example.com", + "GIT_CONFIG_NOSYSTEM": "1", +} +NOVEMBER = dt.datetime(2026, 11, 16, 12, 0, tzinfo=release.BANGKOK) + + +def run(*args, cwd): + r = subprocess.run(args, cwd=cwd, capture_output=True, text=True, env={**os.environ, **GIT_ENV}) + if r.returncode: + raise RuntimeError(f"{args}: {r.stderr}") + return r.stdout.strip() + + +class Stub: + """The release API of one repository; `origin` is the bare repository behind it.""" + + def __init__(self, origin): + self.origin = origin + self.releases = {} + self.ids = iter(range(1, 10**6)) + self.runs = {} # run id -> status; unknown runs answer 403 + self.race = set() # tag names another run takes just before our POST + self.published = [] # tag names in publish order + self.lock = threading.Lock() + + def tag_exists(self, tag): + return bool(run("git", "tag", "-l", tag, cwd=self.origin)) + + def make_tag(self, rel): + if not self.tag_exists(rel["tag_name"]): + run("git", "tag", rel["tag_name"], rel["target_commitish"], cwd=self.origin) + self.published.append(rel["tag_name"]) + + def handle(self, method, path, query, body): + with self.lock: + m = re.fullmatch(r"/api/v1/repos/o/r(/.*)", path) + p = m.group(1) + if p == "/releases" and method == "GET": + rels = sorted(self.releases.values(), key=lambda r: -r["id"]) + if query.get("draft") == "true": + rels = [r for r in rels if r["draft"]] + limit, page = int(query.get("limit", 30)), int(query.get("page", 1)) + return 200, rels[(page - 1) * limit : page * limit] + if p == "/releases" and method == "POST": + form = json.loads(body) + tag = form["tag_name"] + if tag in self.race: + self.race.discard(tag) + self.new(tag, "0" * 40, draft=True, body="") + return 409, {"message": "release exists"} + if any(r["tag_name"] == tag for r in self.releases.values()): + return 409, {"message": "Release is has no Tag"} + rel = self.new(tag, form["target_commitish"], form["draft"], form["body"], form["name"]) + if not rel["draft"]: + self.make_tag(rel) + return 201, rel + m = re.fullmatch(r"/releases/tags/(.+)", p) + if m and method == "GET": + tag = urllib.parse.unquote(m.group(1)) + rel = next((r for r in self.releases.values() if r["tag_name"] == tag), None) + return (200, rel) if rel else (404, {}) + m = re.fullmatch(r"/releases/(\d+)", p) + if m: + rel = self.releases.get(int(m.group(1))) + if rel is None: + return 404, {} + if method == "GET": + return 200, rel + if method == "DELETE": + del self.releases[rel["id"]] + return 204, None + if method == "PATCH": + form = json.loads(body) + rel.update({k: v for k, v in form.items() if k in ("body", "name", "draft")}) + if form.get("draft") is False and rel["tag_name"] not in self.published: + self.make_tag(rel) + return 200, rel + m = re.fullmatch(r"/releases/(\d+)/assets", p) + if m and method == "POST": + rel = self.releases[int(m.group(1))] + name = query["name"] + assert f'filename="{name}"'.encode() in body + rel["assets"].append({"id": next(self.ids), "name": name, "size": len(body)}) + return 201, rel["assets"][-1] + m = re.fullmatch(r"/releases/(\d+)/assets/(\d+)", p) + if m and method == "DELETE": + rel = self.releases[int(m.group(1))] + rel["assets"] = [a for a in rel["assets"] if a["id"] != int(m.group(2))] + return 204, None + m = re.fullmatch(r"/actions/runs/(\d+)", p) + if m and method == "GET": + status = self.runs.get(m.group(1)) + return (200, {"id": int(m.group(1)), "status": status}) if status else (403, {}) + return 404, {"message": f"no route {method} {p}"} + + def new(self, tag, target, draft, body="", name=""): + rel = { + "id": next(self.ids), + "tag_name": tag, + "target_commitish": target, + "name": name, + "body": body, + "draft": draft, + "prerelease": False, + "created_at": dt.datetime.now(dt.timezone.utc).isoformat(), + "assets": [], + } + self.releases[rel["id"]] = rel + return rel + + +def serve(stub): + class Handler(BaseHTTPRequestHandler): + def do(self): + url = urllib.parse.urlsplit(self.path) + query = dict(urllib.parse.parse_qsl(url.query)) + body = self.rfile.read(int(self.headers.get("Content-Length") or 0)) + code, obj = stub.handle(self.command, url.path, query, body) + data = b"" if obj is None else json.dumps(obj).encode() + self.send_response(code) + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + do_GET = do_POST = do_PATCH = do_DELETE = do + + def log_message(self, *args): + pass + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + return server + + +class ReleaseTest(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp()) + self.origin = self.tmp / "origin.git" + self.work = self.tmp / "work" + run("git", "init", "-q", "--bare", "-b", "main", str(self.origin), cwd=self.tmp) + run("git", "clone", "-q", str(self.origin), str(self.work), cwd=self.tmp) + run("git", "checkout", "-q", "-b", "main", cwd=self.work) + self.first = self.commit("first commit") + self.stub = Stub(self.origin) + self.server = serve(self.stub) + self.g = release.Gitea(f"http://127.0.0.1:{self.server.server_port}", "o/r", "secret") + self.cwd = os.getcwd() + os.chdir(self.work) + self.clock = NOVEMBER + release.now = lambda: self.clock + release.POLL = 0.05 + self.files = [] + for name, content in ( + ("visa-linux-x86_64.tar.gz", b"web"), + ("visa-linux-x86_64.tar.gz.sig", b"sig"), + ): + (self.tmp / name).write_bytes(content) + self.files.append(self.tmp / name) + + def tearDown(self): + os.chdir(self.cwd) + self.server.shutdown() + shutil.rmtree(self.tmp, ignore_errors=True) + + def commit(self, subject): + (self.work / "f.txt").write_text(subject) + run("git", "add", "f.txt", cwd=self.work) + run("git", "commit", "-q", "-m", subject, cwd=self.work) + run("git", "push", "-q", "origin", "main", cwd=self.work) + return run("git", "rev-parse", "HEAD", cwd=self.work) + + def release_of(self, sha, run_id="1"): + rel = release.reserve(self.g, sha, run_id) + release.publish(self.g, rel["id"], sha, self.files) + return self.stub.releases[rel["id"]] + + def tag_commit(self, tag): + return run("git", "rev-parse", f"{tag}^{{commit}}", cwd=self.origin) + + def test_first_and_next_release(self): + rel = self.release_of(self.first) + self.assertEqual(rel["tag_name"], "2026.11.0") + self.assertFalse(rel["draft"]) + self.assertEqual(rel["name"], "visa 2026.11.0") + self.assertEqual(self.tag_commit("2026.11.0"), self.first) + self.assertEqual(sorted(a["name"] for a in rel["assets"]), sorted(p.name for p in self.files)) + self.assertIn("Commits in this first release:", rel["body"]) + self.assertIn("- first commit (", rel["body"]) + self.assertIn(release.hashlib.sha256(b"web").hexdigest(), rel["body"]) + self.assertIn("cnx01 installs it as visa.buildfor.life only with its signature", rel["body"]) + self.assertIn("| `visa-linux-x86_64.tar.gz.sig` | the server's signature", rel["body"]) + self.assertIn("November 16, 2026", rel["body"]) + self.assertNotIn("ci-run", rel["body"]) + + second = self.commit("second commit") + rel = self.release_of(second) + self.assertEqual(rel["tag_name"], "2026.11.1") + self.assertEqual(self.tag_commit("2026.11.1"), second) + self.assertIn("Changes since 2026.11.0:", rel["body"]) + self.assertIn("- second commit (", rel["body"]) + self.assertNotIn("first commit", rel["body"]) + + def test_rerun_keeps_the_version_and_replaces_the_files(self): + rel = self.release_of(self.first) + ids = {a["id"] for a in rel["assets"]} + again = self.release_of(self.first, run_id="2") + self.assertEqual(again["id"], rel["id"]) + self.assertEqual(len(self.stub.releases), 1) + self.assertEqual(len(again["assets"]), len(self.files)) + self.assertFalse(ids & {a["id"] for a in again["assets"]}) + + def test_draft_of_an_earlier_attempt_is_reused(self): + rel = release.reserve(self.g, self.first, "5") + again = release.reserve(self.g, self.first, "6") + self.assertEqual(again["id"], rel["id"]) + self.assertIn("ci-run 6", self.stub.releases[rel["id"]]["body"]) + + def test_months_count_separately_and_annotated_tags_count(self): + run("git", "tag", "-a", "-m", "old", "2026.10.7", self.first, cwd=self.origin) + self.assertEqual(release.remote_tags(), {"2026.10.7": self.first}) + second = self.commit("second commit") + self.assertEqual(self.release_of(second)["tag_name"], "2026.11.0") + self.clock = dt.datetime(2026, 12, 1, 0, 30, tzinfo=release.BANGKOK) + third = self.commit("third commit") + self.assertEqual(self.release_of(third)["tag_name"], "2026.12.0") + + def test_a_commit_that_a_newer_draft_contains_gets_no_release(self): + older = self.commit("older") + newer = self.commit("newer") + self.assertEqual(release.reserve(self.g, newer, "1")["tag_name"], "2026.11.0") + self.assertIsNone(release.reserve(self.g, older, "2")) + + def test_overlapping_runs_publish_in_version_order(self): + a = self.commit("a") + b = self.commit("b") + ra = release.reserve(self.g, a, "10") + rb = release.reserve(self.g, b, "11") + self.assertEqual((ra["tag_name"], rb["tag_name"]), ("2026.11.0", "2026.11.1")) + self.stub.runs["10"] = "in_progress" + later = threading.Thread(target=release.publish, args=(self.g, rb["id"], b, self.files)) + later.start() + time.sleep(0.5) + self.assertTrue(self.stub.releases[rb["id"]]["draft"], "the newer release must wait for the older draft") + release.publish(self.g, ra["id"], a, self.files) + later.join(10) + self.assertEqual(self.stub.published, ["2026.11.0", "2026.11.1"]) + + def test_drafts_of_finished_runs_are_deleted(self): + a = self.commit("a") + b = self.commit("b") + ra = release.reserve(self.g, a, "20") + rb = release.reserve(self.g, b, "21") + self.stub.runs["20"] = "completed" + release.publish(self.g, rb["id"], b, self.files) + self.assertNotIn(ra["id"], self.stub.releases) + self.assertEqual(self.stub.published, ["2026.11.1"]) + + def test_old_drafts_are_deleted_and_waiting_has_a_limit(self): + a = self.commit("a") + b = self.commit("b") + ra = release.reserve(self.g, a, "30") # run 30 unknown: the age decides + rb = release.reserve(self.g, b, "31") + release.WAIT_LIMIT = dt.timedelta(seconds=0.3) + try: + release.publish(self.g, rb["id"], b, self.files) # gives up waiting + finally: + release.WAIT_LIMIT = dt.timedelta(minutes=40) + self.assertEqual(self.stub.published, ["2026.11.1"]) + self.stub.releases[ra["id"]]["created_at"] = "2026-01-01T00:00:00Z" + self.assertFalse(self.g.alive(self.stub.releases[ra["id"]])) + + def test_a_number_taken_meanwhile_is_skipped(self): + self.stub.race.add("2026.11.0") + rel = release.reserve(self.g, self.first, "1") + self.assertEqual(rel["tag_name"], "2026.11.1") + + def test_discard_deletes_drafts_only(self): + rel = release.reserve(self.g, self.first, "1") + release.discard(self.g, str(rel["id"])) + self.assertEqual(self.stub.releases, {}) + rel = self.release_of(self.first) + release.discard(self.g, str(rel["id"])) + self.assertIn(rel["id"], self.stub.releases) + release.discard(self.g, "") + + + +SIGN = Path(__file__).with_name("sign-release.sh") + + +@unittest.skipUnless(shutil.which("ssh-keygen") and shutil.which("bash"), "needs ssh-keygen and bash") +class SignTest(unittest.TestCase): + """sign-release.sh signs with the secret and checks the signature against + the allowed signers before anything is published.""" + + def setUp(self): + self.tmp = Path(tempfile.mkdtemp()) + self.archive = self.tmp / "visa-linux-x86_64.tar.gz" + self.archive.write_bytes(b"the web server") + self.secret = {} + for name in ("ci", "other"): + key = self.tmp / name + subprocess.run(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", name, "-f", str(key)], check=True) + pub = key.with_suffix(".pub").read_text().strip() + (self.tmp / f"{name}.signers").write_text(f'visa-ci namespaces="visa-release" {pub}\n') + self.secret[name] = base64.b64encode(key.read_bytes()).decode() + + def tearDown(self): + shutil.rmtree(self.tmp, ignore_errors=True) + + def sign(self, secret, signers): + env = {**os.environ, "SIGNERS": str(self.tmp / signers)} + env.pop("RELEASE_SIGNING_KEY", None) + if secret is not None: + env["RELEASE_SIGNING_KEY"] = secret + return subprocess.run(["bash", str(SIGN), str(self.archive)], env=env, capture_output=True, text=True) + + def test_the_secret_signs_and_the_allowed_signer_checks_it(self): + r = self.sign(self.secret["ci"], "ci.signers") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn('Good "visa-release" signature for visa-ci', r.stdout + r.stderr) + self.assertTrue(self.archive.with_name(self.archive.name + ".sig").exists()) + + def test_a_secret_that_is_not_the_allowed_signer_fails(self): + r = self.sign(self.secret["other"], "ci.signers") + self.assertNotEqual(r.returncode, 0, r.stdout + r.stderr) + + def test_no_secret_no_release(self): + r = self.sign(None, "ci.signers") + self.assertEqual(r.returncode, 1) + self.assertIn("RELEASE_SIGNING_KEY is not set", r.stderr) + self.assertFalse(self.archive.with_name(self.archive.name + ".sig").exists()) + + def test_the_committed_signer_is_visa_ci_for_visa_releases(self): + line = (Path(__file__).parents[2] / "release" / "allowed-signers").read_text().strip() + self.assertRegex(line, r'^visa-ci namespaces="visa-release" ssh-ed25519 AAAA[0-9A-Za-z+/]+=* visa-ci$') + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index c6f036e..242dd4f 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -5,8 +5,18 @@ # request trigger covers AGit pull requests, whose commits arrive # without a branch push. The pre-commit hook in .githooks/ scans the # staged changes before they leave a computer. -# check: cargo fmt, clippy and the tests against a throwaway PostgreSQL 18, -# the version on cnx01 (each #[sqlx::test] creates its own database). +# check: cargo fmt, clippy and the tests against a throwaway PostgreSQL 18, +# the version on cnx01 (each #[sqlx::test] creates its own +# database), and the release scripts' own tests. +# release: once both pass on a push to main (or a manual run on main), the +# commit becomes the next CalVer release, YYYY.M.MICRO in Bangkok +# time (.gitea/scripts/release.py). The server is built for Linux +# x86_64 on Ubuntu 22.04 (glibc 2.35; .gitea/scripts/build-release.sh) +# and signed with the repository secret RELEASE_SIGNING_KEY +# (.gitea/scripts/sign-release.sh). cnx01 installs each release +# with that signature only, within 15 minutes, and restarts the app +# on it (cnx-network-clan modules/visa): a push to main is a deploy. +# A commit message with [skip ci] skips the whole workflow. name: CI on: @@ -58,6 +68,15 @@ jobs: steps: - uses: actions/checkout@v4 + - name: Release script tests + run: | + if ! command -v python3 >/dev/null || ! command -v ssh-keygen >/dev/null; then + SUDO=$(command -v sudo || true) + $SUDO apt-get update -qq + $SUDO apt-get install -y -qq python3 openssh-client + fi + python3 .gitea/scripts/test_release.py + - name: Rust toolchain run: bash .gitea/scripts/rust-toolchain.sh "$RUST_TOOLCHAIN" @@ -79,3 +98,65 @@ jobs: - name: Tests run: cargo test --locked + + release: + name: release + needs: [leaks, check] + if: github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') + runs-on: ubuntu-22.04 + timeout-minutes: 60 + permissions: + contents: write + actions: read + env: + TOKEN: ${{ secrets.GITEA_TOKEN }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: System packages + run: | + SUDO=$(command -v sudo || true) + $SUDO apt-get update -qq + $SUDO apt-get install -y -qq python3 openssh-client + + # Holds the next version with a draft release on this commit; empty when + # a newer release already contains the commit. + - name: Version + id: version + run: python3 .gitea/scripts/release.py reserve + + - name: Rust toolchain + if: steps.version.outputs.version != '' + run: bash .gitea/scripts/rust-toolchain.sh "$RUST_TOOLCHAIN" + + - uses: actions/cache@v4 + if: steps.version.outputs.version != '' + with: + path: | + ~/.cargo/registry/index + ~/.cargo/registry/cache + ~/.cargo/git/db + target + key: release-${{ runner.os }}-${{ env.RUST_TOOLCHAIN }}-${{ hashFiles('Cargo.lock') }} + restore-keys: release-${{ runner.os }}-${{ env.RUST_TOOLCHAIN }}- + + - name: Build + if: steps.version.outputs.version != '' + run: bash .gitea/scripts/build-release.sh "${{ steps.version.outputs.version }}" + + # cnx01 installs the server only with this signature + - name: Sign + if: steps.version.outputs.version != '' + env: + RELEASE_SIGNING_KEY: ${{ secrets.RELEASE_SIGNING_KEY }} + run: bash .gitea/scripts/sign-release.sh dist/visa-linux-x86_64.tar.gz + + - name: Publish + if: steps.version.outputs.version != '' + run: python3 .gitea/scripts/release.py publish "${{ steps.version.outputs.release_id }}" dist/* + + - name: Discard the draft + if: (failure() || cancelled()) && steps.version.outputs.release_id != '' + run: python3 .gitea/scripts/release.py discard "${{ steps.version.outputs.release_id }}" diff --git a/AGENTS.md b/AGENTS.md index 24bff21..923f860 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -31,6 +31,10 @@ visa.buildfor.life holds passport data of real people. Read this file and - **No inline script or style.** The Content Security Policy refuses them; `tests/pages.rs` checks the templates. - **Migrations** are never edited once they are on `main`; add a new file. +- **`main` is live.** Every push to `main` that passes CI becomes a signed + release that cnx01 installs and restarts on within 15 minutes, migrations + included. Push only whole, working steps to `main`; unfinished work stays + on a branch or uncommitted. - **A new kind of record** for a stay is a migration and one `Kind` in `src/records.rs`; the routes, the form, the Stay tab and the audit entries follow from it. A reference to another record is a selection (`Input:: @@ -76,6 +80,7 @@ and dark, at desktop and phone width, with `scripts/dev.sh` running. | `src/documents.rs` | documents of people and companies: kinds, records, SQL, `files-check`, `files-migrate` | | `src/papers/` | the Immigration Bureau's forms filled in (`layout.rs` is generated by `scripts/gen_layout.py`) | | `src/pack/` | the extension pack: its rules as a pure function (`assess`), and the pack as one PDF (`pdf.rs`) | +| `.gitea/scripts/` | CI: toolchain, gitleaks, and the release (`release.py` + `test_release.py`, `build-release.sh`, `sign-release.sh`; key `release/allowed-signers`) | | `static/mrz-photo.js` | the passport photo reader in the browser (camera view, Tesseract.js from `static/vendor/tesseract/`, see its README.txt); the server's half is `mrz::from_ocr` | | `src/web/` | routes, the login gate, pages | | `templates/` | minijinja templates, compiled in by `build.rs` | diff --git a/README.md b/README.md index 527c9f1..1030ec6 100644 --- a/README.md +++ b/README.md @@ -156,13 +156,22 @@ servers. The fleet's module is `modules/visa` in cnx-network-clan, with its runbook in `docs/src/visa.md` there. Only members of the Kanidm group `visa` get in; members are set in the fleet's `identity/people.nix`. -A release is a push to `main` here, then `nix flake update visa` in -cnx-network-clan and a deploy of cnx01. The fleet's VM test `checks.visa` -signs in through a fake provider, adds a person and checks the audit log on -the real PostgreSQL module. +A push to `main` is a release, as for thukthuk and lampbench-web: once the +checks pass, CI builds the server on Ubuntu 22.04, signs it with a key only +CI holds (the repository secret `RELEASE_SIGNING_KEY`; its public half is +`release/allowed-signers`) and publishes it as the next release, named by +date (2026.11.0, 2026.11.1, ...). cnx01 looks every 15 minutes, installs a +release only with that signature, and restarts the app on it; migrations +run at that start. So `main` must stay deployable. On cnx01, +`visa-releases status` shows what runs, and `visa-releases rollback` goes +back one release and holds it until `visa-releases unpin`; a rollback does +not undo a migration. The fleet's VM test `checks.visa` signs in through a +fake provider, adds a person and checks the audit log on the real +PostgreSQL module. Which commit runs: every page's footer names it, with a link to it, and https://visa.buildfor.life/version answers with the full hash, without a login, so `curl https://visa.buildfor.life/version` tells whether a release -is live. A Nix build takes the commit from the flake's source; a build in a -checkout asks git. +is live, and `visa --version` prints the release and the commit. A Nix +build takes the commit from the flake's source, CI from `VISA_COMMIT`, a +build in a checkout from git. diff --git a/docs/PLAN.md b/docs/PLAN.md index 38ba42f..985cc6b 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -28,6 +28,7 @@ The first round of questions was answered on November 17, 2026. | Question | Decision | | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Where it runs | cnx01, installed on the host like proplan and lampbench: database `visa` on cnx01's PostgreSQL, documents in its Garage, encrypted by the app, borg backups to juliet | +| Releases (Nov 20) | as thukthuk and lampbench-web: every push to main that passes CI becomes a signed release (CalVer), which cnx01 fetches and restarts on within 15 minutes; no fleet PR per release | | Documents in Garage | bucket `visa-documents` on cnx01's Garage, 10 GB (Nov 19, 2026); the app encrypts each file before it leaves the app, so Garage holds no key; Garage's SSE-C is off | | How it is published | bkk01 publishes `visa.buildfor.life` through a `modules/web-sites` app entry | | Login | Kanidm at id.cnx.network, OAuth2 client `visa-web`, group `visa` with grabowski and oltmanns | diff --git a/release/allowed-signers b/release/allowed-signers new file mode 100644 index 0000000..f34c7fb --- /dev/null +++ b/release/allowed-signers @@ -0,0 +1 @@ +visa-ci namespaces="visa-release" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILZh7em+/cYUfdT48U3juzHgeRv4r26h/GuFknJH/t95 visa-ci diff --git a/src/main.rs b/src/main.rs index c721239..0d43537 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,4 @@ -//! `visa [serve|migrate|seed-demo|files-check|files-migrate|files-mirror|help]`: +//! `visa [serve|migrate|seed-demo|files-check|files-migrate|files-mirror|version|help]`: //! the server and its admin commands. use std::path::PathBuf; @@ -29,6 +29,7 @@ Commands: files-mirror --to DIR make DIR hold exactly the store's files, still encrypted, for the backups + version print the version and the commit it is built from (also --version) help show this text Settings come from the environment; see src/config.rs or README.md."; @@ -70,6 +71,15 @@ fn store(cfg: &Config) -> Result { async fn run(cmd: &str) -> Result<()> { match cmd { "serve" => serve().await, + // CI checks it, and cnx01 runs it before it installs a release + "version" | "--version" => { + println!( + "visa {} ({})", + env!("CARGO_PKG_VERSION"), + visa::embedded::COMMIT + ); + Ok(()) + } "migrate" => { let cfg = Config::from_env()?; let pool = db::connect(&cfg).await?;