The gitea role accepts a release only when it carries a valid signature by gitea_gpg_key_id or one of its subkeys, so an expired, revoked or replaced Gitea release key makes every install and update fail closed, without warning, on the day it happens. scripts/check_gitea_release_key.py reads the pins from the role defaults, fetches the release key into a throwaway keyring and only the .asc of the pinned release (never the binary), and fails when the primary key or a signing subkey expires within 60 days, is revoked or expired, or when a signature in the .asc is not by a valid signing key of the pinned key. Its docstring says what to do on a failure. The Gitea release key workflow runs it weekly, by hand, and on pull requests that change the role defaults or the check, so a gitea_version bump is checked against the new release's signature. It runs in the ci image at the pin of lint.yml; that image has gpgv but not gpg, so the job installs gpg and gpg-agent from the Ubuntu archive per run instead of making the check an image input. The tests that make keys skip without gpg, so the Lint job's unittest run (no gpg) still covers the parsing and rendering tests. The workflow pins the ci image, so it joins the pin consumers of check_image_versions.py and check_bot_pr_diff.py: Renovate's pin follow-up edits every workflow, and the bot-diff gate would otherwise refuse that pull request. The new workflow and script are on the molecule selector's IGNORED list, since no scenario reads them. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm
338 lines
13 KiB
Python
338 lines
13 KiB
Python
# SPDX-FileCopyrightText: Defame1297 and contributors
|
|
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
"""Test scripts/check_gitea_release_key.py offline, with throwaway keys made by gpg in a temp dir.
|
|
|
|
Run with: python3 -m unittest discover -s tests/scripts
|
|
|
|
The tests that make keys need gpg and gpg-agent and are skipped without them (the ci image has
|
|
neither; the Gitea release key workflow installs them and runs this file); no network. The key
|
|
and signature reach the script as file:// URLs. Revocation is tested on parsed key listings,
|
|
since gpg cannot revoke a subkey in batch mode without the interactive key editor.
|
|
"""
|
|
|
|
import importlib.util
|
|
import pathlib
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
import unittest
|
|
|
|
sys.dont_write_bytecode = True # loading the script must not leave a .pyc to commit
|
|
|
|
REPO = pathlib.Path(__file__).resolve().parents[2]
|
|
SCRIPT = REPO / "scripts" / "check_gitea_release_key.py"
|
|
SPEC = importlib.util.spec_from_file_location("relkey", SCRIPT)
|
|
relkey = importlib.util.module_from_spec(SPEC)
|
|
SPEC.loader.exec_module(relkey)
|
|
HAVE_GPG = all(shutil.which(tool) for tool in ("gpg", "gpg-agent", "gpgconf"))
|
|
|
|
PAST = "20200101T000000!" # gpg --faked-system-time, frozen: a key made then has long expired
|
|
|
|
|
|
class Keyring:
|
|
"""A throwaway GNUPGHOME that makes keys and signatures."""
|
|
|
|
def __init__(self, case):
|
|
self.home = pathlib.Path(tempfile.mkdtemp(prefix="relkey-test."))
|
|
case.addCleanup(self.close)
|
|
|
|
def close(self):
|
|
subprocess.run(
|
|
["gpgconf", "--homedir", str(self.home), "--kill", "all"],
|
|
capture_output=True,
|
|
check=False,
|
|
)
|
|
shutil.rmtree(self.home, ignore_errors=True)
|
|
|
|
def gpg(self, *args, faked=None):
|
|
cmd = [
|
|
"gpg",
|
|
"--homedir",
|
|
str(self.home),
|
|
"--batch",
|
|
"--pinentry-mode",
|
|
"loopback",
|
|
"--passphrase",
|
|
"",
|
|
]
|
|
if faked:
|
|
cmd += ["--faked-system-time", faked]
|
|
return subprocess.run(
|
|
cmd + list(args), capture_output=True, text=True, check=True
|
|
).stdout
|
|
|
|
def key(self, primary_expire="2y", sub_expire="2y", faked=None):
|
|
"""(primary fpr, signing subkey fpr): a certify-only primary and an ed25519 signing subkey."""
|
|
uid = f"t{time.monotonic_ns()} <[email protected]>"
|
|
self.gpg("--quick-gen-key", uid, "ed25519", "cert", primary_expire, faked=faked)
|
|
primary = self.fprs(uid)[0]
|
|
self.gpg("--quick-add-key", primary, "ed25519", "sign", sub_expire, faked=faked)
|
|
return primary, self.fprs(uid)[1]
|
|
|
|
def fprs(self, uid):
|
|
out = self.gpg("--with-colons", "--fixed-list-mode", "--list-keys", uid)
|
|
return [
|
|
line.split(":")[9] for line in out.splitlines() if line.startswith("fpr:")
|
|
]
|
|
|
|
def export(self, name, *fprs):
|
|
path = self.home / name
|
|
path.write_text(self.gpg("--armor", "--export", *fprs))
|
|
return path.as_uri()
|
|
|
|
def sign(self, name, *signers, faked=None):
|
|
"""A detached signature file with one signature per signer (gpg makes one per --local-user)."""
|
|
data = self.home / "payload"
|
|
data.write_bytes(b"not a gitea binary\n")
|
|
path = self.home / name
|
|
users = [arg for signer in signers for arg in ("--local-user", f"{signer}!")]
|
|
self.gpg(
|
|
"--armor",
|
|
"--detach-sign",
|
|
*users,
|
|
"--output",
|
|
str(path),
|
|
str(data),
|
|
faked=faked,
|
|
)
|
|
return path.as_uri()
|
|
|
|
|
|
@unittest.skipUnless(HAVE_GPG, "needs gpg, gpg-agent and gpgconf")
|
|
class Gpg(unittest.TestCase):
|
|
def setUp(self):
|
|
self.ring = Keyring(self)
|
|
|
|
def check(self, key_url, fpr, sig_url, window=60):
|
|
errors, warnings, _unused = relkey.run(key_url, fpr, sig_url, window)
|
|
return errors, warnings
|
|
|
|
def test_valid_key_and_signature_pass(self):
|
|
primary, sub = self.ring.key()
|
|
errors, warnings = self.check(
|
|
self.ring.export("k", primary), primary, self.ring.sign("s", sub)
|
|
)
|
|
self.assertEqual(errors, [])
|
|
self.assertEqual(warnings, [])
|
|
|
|
def test_primary_expiring_within_window_fails(self):
|
|
primary, sub = self.ring.key(primary_expire="30d", sub_expire="20d")
|
|
key, sig = self.ring.export("k", primary), self.ring.sign("s", sub)
|
|
errors, _unused = self.check(key, primary, sig)
|
|
self.assertTrue(
|
|
any("primary key" in e and "within 60 days" in e for e in errors), errors
|
|
)
|
|
self.assertEqual(self.check(key, primary, sig, window=10)[0], [])
|
|
|
|
def test_subkey_expiring_within_window_fails(self):
|
|
primary, sub = self.ring.key(sub_expire="30d")
|
|
errors, _unused = self.check(
|
|
self.ring.export("k", primary), primary, self.ring.sign("s", sub)
|
|
)
|
|
self.assertTrue(any(sub in e and "expires" in e for e in errors), errors)
|
|
self.assertFalse(any("primary key" in e for e in errors), errors)
|
|
|
|
def test_signature_by_another_key_fails(self):
|
|
primary, _unused = self.ring.key()
|
|
_unused, other_sub = self.ring.key()
|
|
errors, _unused = self.check(
|
|
self.ring.export("k", primary), primary, self.ring.sign("s", other_sub)
|
|
)
|
|
self.assertTrue(any("not the key" in e for e in errors), errors)
|
|
|
|
def test_several_signatures_by_the_pinned_key_pass(self):
|
|
primary, sub = self.ring.key()
|
|
self.ring.gpg("--quick-add-key", primary, "ed25519", "sign", "2y")
|
|
sub2 = next(f for f in self.ring.fprs(primary) if f not in (primary, sub))
|
|
errors, _unused = self.check(
|
|
self.ring.export("k", primary), primary, self.ring.sign("s", sub, sub2)
|
|
)
|
|
self.assertEqual(errors, [])
|
|
|
|
def test_one_foreign_signature_among_several_fails(self):
|
|
primary, sub = self.ring.key()
|
|
_unused, other_sub = self.ring.key()
|
|
errors, _unused = self.check(
|
|
self.ring.export("k", primary), primary, self.ring.sign("s", sub, other_sub)
|
|
)
|
|
self.assertEqual(len(errors), 1, errors)
|
|
self.assertIn(other_sub, errors[0])
|
|
|
|
def test_key_url_without_the_pinned_key_fails(self):
|
|
primary, sub = self.ring.key()
|
|
other, _unused = self.ring.key()
|
|
errors, _unused = self.check(
|
|
self.ring.export("k", other), primary, self.ring.sign("s", sub)
|
|
)
|
|
self.assertTrue(
|
|
any("did not provide the pinned key" in e for e in errors), errors
|
|
)
|
|
|
|
def test_expired_signer_fails(self):
|
|
primary, sub = self.ring.key(
|
|
primary_expire="never", sub_expire="1y", faked=PAST
|
|
)
|
|
sig = self.ring.sign("s", sub, faked=PAST)
|
|
# a current signing subkey too, so only the signer's expiry can fail the check
|
|
self.ring.gpg("--quick-add-key", primary, "ed25519", "sign", "2y")
|
|
errors, _unused = self.check(self.ring.export("k", primary), primary, sig)
|
|
self.assertTrue(any(sub in e and "expired" in e for e in errors), errors)
|
|
|
|
def test_cli_exit_codes(self):
|
|
primary, sub = self.ring.key()
|
|
key, sig = self.ring.export("k", primary), self.ring.sign("s", sub)
|
|
base = [
|
|
sys.executable,
|
|
str(SCRIPT),
|
|
"--key-url",
|
|
key,
|
|
"--fingerprint",
|
|
primary,
|
|
"--signature-url",
|
|
sig,
|
|
]
|
|
ok = subprocess.run(base, capture_output=True, text=True, check=False)
|
|
self.assertEqual(ok.returncode, 0, ok.stdout)
|
|
late = subprocess.run(
|
|
base + ["--window-days", "1000"],
|
|
capture_output=True,
|
|
text=True,
|
|
check=False,
|
|
)
|
|
self.assertEqual(late.returncode, 1, late.stdout)
|
|
self.assertIn("::error::", late.stdout)
|
|
broken = subprocess.run(
|
|
base[:-1] + [key + ".missing"], capture_output=True, text=True, check=False
|
|
)
|
|
self.assertEqual(broken.returncode, 2, broken.stdout)
|
|
|
|
|
|
PRIMARY = "A" * 40
|
|
SUB = "B" * 40
|
|
|
|
|
|
def listing(sub_validity="-", sub_caps="s", sub_expires=""):
|
|
return (
|
|
f"pub:-:255:22:{PRIMARY[-16:]}:1:::-:::cSC::::::23::0:\nfpr:::::::::{PRIMARY}:\n"
|
|
f"sub:{sub_validity}:255:22:{SUB[-16:]}:1:{sub_expires}:::::{sub_caps}::::::23:\nfpr:::::::::{SUB}:\n"
|
|
)
|
|
|
|
|
|
class Parsed(unittest.TestCase):
|
|
NOW = 1_800_000_000
|
|
|
|
def test_revoked_signer_fails(self):
|
|
keys = relkey.parse_keys(listing(sub_validity="r"))
|
|
packets = f":signature packet: algo 22, keyid {SUB[-16:]}\n\thashed subpkt 33 len 21 (issuer fpr v4 {SUB})\n"
|
|
errors, _unused, _unused2 = relkey.check_signature(
|
|
packets, keys, PRIMARY, self.NOW
|
|
)
|
|
self.assertTrue(any("revoked" in e for e in errors), errors)
|
|
|
|
def test_revoked_subkey_leaves_no_signing_key(self):
|
|
errors, _unused, _unused2 = relkey.check_key(
|
|
relkey.parse_keys(listing(sub_validity="r")), PRIMARY, 60, self.NOW
|
|
)
|
|
# the primary in the listing is certify-only (cSC: no lowercase s), so nothing can sign
|
|
self.assertTrue(any("no valid signing-capable" in e for e in errors), errors)
|
|
|
|
def test_keyid_only_issuer_matches_with_a_warning(self):
|
|
keys = relkey.parse_keys(listing())
|
|
packets = f":signature packet: algo 22, keyid {SUB[-16:]}\n\tsubpkt 16 len 8 (issuer key ID {SUB[-16:]})\n"
|
|
errors, warnings, _unused = relkey.check_signature(
|
|
packets, keys, PRIMARY, self.NOW
|
|
)
|
|
self.assertEqual(errors, [])
|
|
self.assertTrue(warnings)
|
|
|
|
def packets(self, *issuers):
|
|
return "".join(
|
|
f"# off=0 ctb=89 tag=2\n:signature packet: algo 22, keyid {i[-16:]}\n"
|
|
f"\thashed subpkt 33 len 21 (issuer fpr v4 {i})\n"
|
|
for i in issuers
|
|
)
|
|
|
|
def test_every_signature_must_be_by_the_pinned_key(self):
|
|
keys = relkey.parse_keys(listing())
|
|
self.assertEqual(
|
|
relkey.check_signature(self.packets(SUB, SUB), keys, PRIMARY, self.NOW)[0],
|
|
[],
|
|
)
|
|
errors = relkey.check_signature(
|
|
self.packets(SUB, "C" * 40), keys, PRIMARY, self.NOW
|
|
)[0]
|
|
self.assertEqual(len(errors), 1, errors)
|
|
self.assertIn("C" * 40, errors[0])
|
|
|
|
def test_no_signature_fails(self):
|
|
errors = relkey.check_signature(
|
|
"# off=0 ctb=99 tag=6\n:public key packet:\n",
|
|
relkey.parse_keys(listing()),
|
|
PRIMARY,
|
|
self.NOW,
|
|
)[0]
|
|
self.assertTrue(any("no signature" in e for e in errors), errors)
|
|
|
|
|
|
class Render(unittest.TestCase):
|
|
def test_renders_the_role_defaults(self):
|
|
key_url, fpr, sig_url, version = relkey.inputs_from_defaults(relkey.DEFAULTS)
|
|
self.assertTrue(key_url.endswith(fpr))
|
|
self.assertIn(f"/{version}/", sig_url)
|
|
self.assertTrue(sig_url.endswith(".asc"))
|
|
|
|
def test_upper_and_nesting(self):
|
|
values = {
|
|
"v": "1.2",
|
|
"u": "https://x/{{ v }}/f-{{v}}",
|
|
"s": "{{ u }}.asc",
|
|
"k": "ab",
|
|
"ku": "{{ k | upper }}",
|
|
}
|
|
self.assertEqual(relkey.render("s", values), "https://x/1.2/f-1.2.asc")
|
|
self.assertEqual(relkey.render("ku", values), "AB")
|
|
|
|
def test_fingerprint_override_reaches_the_key_url(self):
|
|
key_url, fpr, _unused, _unused2 = relkey.inputs_from_defaults(
|
|
relkey.DEFAULTS, {"gitea_gpg_key_id": "ab" * 20}
|
|
)
|
|
self.assertEqual(fpr, "ab" * 20)
|
|
self.assertTrue(key_url.endswith("AB" * 20), key_url)
|
|
key_url = relkey.inputs_from_defaults(
|
|
relkey.DEFAULTS,
|
|
{"gitea_gpg_key_id": "ab" * 20, "gitea_gpg_key_url": "file:///k"},
|
|
)[0]
|
|
self.assertEqual(key_url, "file:///k")
|
|
|
|
def test_comment_in_a_default_exits_2(self):
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
defaults = pathlib.Path(tmp) / "main.yml"
|
|
defaults.write_text(
|
|
'gitea_version: "1"\ngitea_gpg_key_id: "' + "A" * 40 + '"\n'
|
|
'gitea_gpg_key_url: "https://k/{# x #}"\ngitea_signature_url: "file:///s"\n'
|
|
)
|
|
res = subprocess.run(
|
|
[sys.executable, str(SCRIPT), "--defaults", str(defaults)],
|
|
capture_output=True,
|
|
text=True,
|
|
check=False,
|
|
)
|
|
self.assertEqual(res.returncode, 2, res.stdout)
|
|
self.assertIn("does not render", res.stdout)
|
|
|
|
def test_unknown_template_fails(self):
|
|
for value in (
|
|
"{{ v | lower }}",
|
|
"{% if v %}x{% endif %}",
|
|
"{# c #}",
|
|
"{{ missing }}",
|
|
):
|
|
with self.assertRaises(relkey.CheckError):
|
|
relkey.render("x", {"x": value, "v": "1"})
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main(verbosity=2)
|