Merge remote-tracking branch 'origin/main' into docs/189-contributor-doc-split
Build / build (pull_request) Successful in 15s
Lint / lint (pull_request) Successful in 46s
Molecule / molecule (pull_request) Successful in 3s

# Conflicts:
#	CONTRIBUTING.md
This commit is contained in:
Defame1297 committed 2026-11-22 08:45:05 +00:00
commit 66f8a8e0f2
14 files changed
+869 -10

No files matched your search

+82
View File
@@ -0,0 +1,82 @@
name: Gitea release key
# Early warning for the signature check of the gitea role: roles/gitea/tasks/download.yml
# accepts a release only when it carries a valid signature by gitea_gpg_key_id (or a subkey),
# so an expired, revoked or replaced Gitea release key makes every install and update fail
# closed. scripts/check_gitea_release_key.py reads the pins from roles/gitea/defaults/main.yml,
# fetches the key and the pinned release's .asc (never the binary) and fails when a key expires
# within 60 days, is revoked or expired, or did not sign the release. It checks the issuers and
# the key, not the signature itself (no binary), so a corrupt .asc still fails only in the role.
# What to do on a failure is in the script's docstring.
#
# Weekly, by hand, and on pull requests that change the pins (a Renovate bump of gitea_version
# is checked against the new release's signature) or the check itself. Runs only on the
# Collection's own runner. Read-only; no org secret, the only credential is the job token
# (secrets.GITHUB_TOKEN), which is read-only for a fork pull request. No pull_request_target.
# Not a required check: it depends on the key source and dl.gitea.com being reachable.
on: # yamllint disable-line rule:truthy
schedule:
# Every Monday at 06:00 UTC
- cron: "0 6 * * 1"
workflow_dispatch: {}
pull_request:
branches:
- main
paths:
- roles/gitea/defaults/main.yml
- scripts/check_gitea_release_key.py
- tests/scripts/test_check_gitea_release_key.py
- .gitea/workflows/gitea-release-key.yml
permissions:
contents: read
# A newer push to the same pull request makes the running run obsolete; a scheduled or
# manual run on main keeps its own result.
concurrency:
group: gitea-release-key-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
check:
runs-on: kamino-docker
timeout-minutes: 10
# The ci image (images/ci, built by image.yml), at the pin of lint.yml: tag for the
# release, digest enforced. Only its /opt/venv Python (with PyYAML) is used here.
container:
image: git.rkdr.net/mortis/ci:0.2.32@sha256:3282337dd3ccb20172e519d11fa996bfad2df09f3f5de14e2706d9d368af9923
steps:
# The container has no Node, so JavaScript actions such as actions/checkout
# cannot run; clone with git and the job token.
- name: Checkout the commit under test
env:
GIT_CONFIG_COUNT: "1"
GIT_CONFIG_KEY_0: http.extraheader
GIT_CONFIG_VALUE_0: "AUTHORIZATION: bearer ${{ secrets.GITHUB_TOKEN }}"
SHA: ${{ github.event.pull_request.head.sha || github.sha }}
REF: ${{ github.ref }}
REPO_URL: ${{ github.server_url }}/${{ github.repository }}
run: |
git clone "$REPO_URL" .
# A clone has no refs/pull/*: fetch the run's ref when the sha is not on a branch.
git checkout "$SHA" || { git fetch origin "$REF" && git checkout "$SHA"; }
echo "Checked out $(git rev-parse HEAD)"
# The ci image has gpgv (apt's verifier) but not gpg: the check needs gpg to read the key
# and the signature packets, and the tests need gpg-agent to make throwaway keys. Installed
# per run from the image's own Ubuntu archive (apt verifies it) rather than baked in, so
# this check is not an input of the ci image. The tests skip their key cases without gpg,
# gpg-agent or gpgconf, so this step fails when any of the three is missing.
- name: Install gpg
run: |
apt-get update -qq
apt-get install -y -qq --no-install-recommends gpg gpg-agent
for c in gpg gpg-agent gpgconf; do command -v "$c" > /dev/null || { echo "::error::$c is missing"; exit 1; }; done
gpg --version | head -n1
# Offline, with throwaway keys: the check itself works before it judges the real key.
- name: Test the check
run: /opt/venv/bin/python3 -I tests/scripts/test_check_gitea_release_key.py
- name: Check the Gitea release key and the pinned release's signature
run: /opt/venv/bin/python3 -I scripts/check_gitea_release_key.py --window-days 60
+2 -1
View File
@@ -108,7 +108,8 @@ Single-context: `GLOSSARY.md` and `docs/adr/` at the root, both created lazily.
- `ansible-test sanity` ignores live in `tests/sanity/ignore-common.txt`; the Build job copies
it to the file name of the installed core version in its throwaway worktree (a committed
`ignore-<MAJOR.MINOR>.txt` is appended for findings of one version only).
- Consumers pin `image:<version>@sha256:<digest>` (`lint.yml`, `build.yml`, `molecule.yml`).
- Consumers pin `image:<version>@sha256:<digest>` (`lint.yml`, `build.yml`, `molecule.yml`,
`gitea-release-key.yml`).
A build prints the new digest; moving a pin is a reviewed edit, and every build has a new
digest.
- kaniko runs inside the job container and unpacks the image it builds over it, so each matrix entry names its
@@ -0,0 +1,6 @@
---
trivial:
- >-
gitea - A weekly CI check warns 60 days before the Gitea release key expires, and fails when the key is
revoked or expired or did not sign the pinned release; the role README points to it. No task or default
changes.
+2 -2
View File
@@ -105,8 +105,8 @@ Interim section: it moves to `images/AGENTS.md` and `scripts/AGENTS.md`.
*Reason:* a published image version is never rebuilt, so a changed input needs a new version.
*Held by:* control: the Lint check's `Check image versions were bumped` step.
- **After the merge builds the image on `main`, a second pull request moves the
`image:<version>@sha256:<digest>` pins in `lint.yml`, `build.yml` and `molecule.yml` to the printed
digest.** It touches no `image.yml` trigger path, so it rebuilds nothing.
`image:<version>@sha256:<digest>` pins in `lint.yml`, `build.yml`, `molecule.yml` and
`gitea-release-key.yml` to the printed digest.** It touches no `image.yml` trigger path, so it rebuilds nothing.
*Reason:* consumers run exactly the digest a reviewer saw.
*Held by:* review; Renovate opens these pull requests for the repository's own images.
- These tooling files are in `galaxy.yml` `build_ignore`, so their bumps change neither the
+4 -2
View File
@@ -60,13 +60,15 @@ jobs:
the checkout's `requirements-dev.txt`, `requirements-dev.lock`, `requirements.yml` and `.pre-commit-config.yaml` match, the baked tools and
collections are used as they are. When a pull request changes a pin the check fails and the job installs the pinned
tools and collections itself for that run
(slower, same result), until the image is rebuilt from `main`. `lint.yml` and `build.yml` are the real consumers.
(slower, same result), until the image is rebuilt from `main`. `lint.yml`, `build.yml` and `gitea-release-key.yml` are the
real consumers.
## Tags and pinning
- `<version>` is semver, independent of the Collection's version. A published version is never moved or
rebuilt, so one digest belongs to exactly one version. `latest` is the newest version, for looking only.
- Pin `ci:<version>@sha256:<digest>`; the digest is what is enforced. Consumers: `lint.yml` and `build.yml`.
- Pin `ci:<version>@sha256:<digest>`; the digest is what is enforced. Consumers: `lint.yml`, `build.yml` and
`gitea-release-key.yml`.
- Renovate is configured to move the pins to a new version after the image is built on `main` (the rule is in
`renovate.json`; the first pin of a brand-new image is made by hand).
+1 -1
View File
@@ -169,7 +169,7 @@
"automerge": false
},
{
"description": "Pin follow-up for our own images (git.rkdr.net/mortis/*): moves the image:<version>@sha256:<digest> pins of lint.yml, build.yml and molecule.yml to the newest published version and its digest, and automerges (PR 2 of the update loop). The pull request's own Lint and Build run in the new image before the merge, scripts/check_bot_pr_diff.py allows only these pin lines, and scripts/check_image_versions.py pins fails a pin that is newer than the matrix. The registry lists tags and digests anonymously, so no hostRules are needed. A major version stays manual (rule above).",
"description": "Pin follow-up for our own images (git.rkdr.net/mortis/*): moves the image:<version>@sha256:<digest> pins of lint.yml, build.yml, molecule.yml and gitea-release-key.yml to the newest published version and its digest, and automerges (PR 2 of the update loop). The pull request's own Lint and Build run in the new image before the merge, scripts/check_bot_pr_diff.py allows only these pin lines, and scripts/check_image_versions.py pins fails a pin that is newer than the matrix. The registry lists tags and digests anonymously, so no hostRules are needed. A major version stays manual (rule above).",
"matchPackageNames": [
"git.rkdr.net/mortis/**"
],
+1
View File
@@ -130,6 +130,7 @@ Update or remove: pass `-e gitea_update=true`, or `-e "gitea_remove=true gitea_r
- The role is not a state selector. `main.yml` runs prerequisites and configure unless `gitea_remove` is true; install runs only when the binary is absent; update only when `gitea_update` is true; remove only when `gitea_remove` is true, and then every other task in `main.yml` is skipped.
- Updates roll back the binary, not the database. Gitea migrates its database when the new version starts, so after a failure past that point the previous binary may refuse the newer schema and the service may not come back up (the failure message of `_binary_update` then says it did not). Back up the database before an update across releases; to recover, restore it or move forward to `gitea_version`.
- The signature check fails closed when Gitea's release key expires, is revoked or is replaced, so every install and update of the role stops. The `Gitea release key` workflow of this repository (`.gitea/workflows/gitea-release-key.yml`, running `scripts/check_gitea_release_key.py`) checks the key from `gitea_gpg_key_url` and the signature of the pinned `gitea_version` weekly and on changes to `defaults/main.yml`, and fails 60 days before the key expires; the script's docstring says what to do on a failure. Neither file ships in the Collection.
- `app.ini` is written with `no_log: true` and `diff: false` because it holds `SECRET_KEY`, `INTERNAL_TOKEN`, `JWT_SECRET` and, with the mailer on, the SMTP password. The admin-create, token-mint and key-upload tasks are `no_log` too.
- Gitea accepts the admin password only through `--password`, so it is in the command's argv: visible in `ps` for the life of the create command, and logged in full by sudo (`COMMAND=...`) to syslog, auth.log or journald, where it persists in the host logs. This happens only on the first run, when the user is missing. Run the role on a single-purpose host and restrict access to its logs.
- `app.ini` renders the listener from `gitea_http_addr` and `gitea_http_port`; it hard-codes SQLite, `DISABLE_REGISTRATION = true` (accounts are created by an admin only), `START_SSH_SERVER = false` and loopback as the only trusted proxy. None of these is a variable; `REVERSE_PROXY_LIMIT` comes from `gitea_reverse_proxy_limit`. A reverse proxy terminates TLS in front of it.
+2 -1
View File
@@ -18,7 +18,7 @@ When <head-ref> starts with `renovate/`, the diff of <base-ref>...HEAD may only
the `uv==<version>` token of a line that holds one;
* .gitea/workflows/image.yml: the matrix `version:` lines, and the tag and digest of the
job containers' `job_image: ubuntu:...@sha256:...` lines (the name stays);
* .gitea/workflows/{lint,build,molecule}.yml: the version and digest of a
* .gitea/workflows/{lint,build,molecule,gitea-release-key}.yml: the version and digest of a
`git.rkdr.net/mortis/<name>:<version>@sha256:<digest>` pin (the name stays), including
the MOLECULE_IMAGE value.
@@ -72,6 +72,7 @@ CONSUMERS = {
".gitea/workflows/lint.yml",
".gitea/workflows/build.yml",
".gitea/workflows/molecule.yml",
".gitea/workflows/gitea-release-key.yml",
}
+405
View File
@@ -0,0 +1,405 @@
# SPDX-FileCopyrightText: Defame1297 and contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Warn before the Gitea release signing key stops verifying Gitea releases.
roles/gitea/tasks/download.yml fetches the release key from gitea_gpg_key_url on every download,
requires the pinned primary fingerprint gitea_gpg_key_id and accepts only a valid signature by
that key or one of its subkeys. An expired or revoked key, or a release signed by another key,
makes every install and update fail closed. This script finds that out ahead of time, read-only:
1. it fetches the key into a throwaway GNUPGHOME (removed on exit) and requires the pinned
primary fingerprint;
2. it fails when the primary key, or a signing-capable subkey that is valid now, is revoked
or expired, or expires within the window (default 60 days), or when no valid
signing-capable key is left;
3. it downloads only the signature file (.asc) of the pinned release, never the binary, and
fails unless it holds at least one signature and the issuer of every signature in it is the
pinned key or one of its subkeys, valid and signing-capable (as the role requires).
It checks who signed the release and that the key is valid, not the signature itself: without
the binary there is nothing to verify it against, so a corrupt or bad .asc fails only in the
role. .gitea/workflows/gitea-release-key.yml (the `Gitea release key` workflow) runs it weekly,
on demand and on pull requests that change the role defaults or the check.
python3 -I scripts/check_gitea_release_key.py [--defaults roles/gitea/defaults/main.yml]
[--window-days 60] [--key-url URL] [--fingerprint FPR] [--signature-url URL]
The URLs and the fingerprint come from the role defaults, so the pins live in one place; the
options override the default of the same name before the templates are rendered, so
--fingerprint alone also changes the key URL built from it (a file:// URL works too, which the
tests use). The only templates rendered are `{{ name }}` and `{{ name | upper }}` of other
top-level defaults; anything else (filters, `{% %}`, `{# #}`) fails. Findings are printed as
::error:: / ::warning:: workflow annotations. Exit 0 when the key and the signature are fine,
1 on a finding, 2 when the check itself cannot run (bad input, network, gpg). Needs gpg and
PyYAML.
What to do on a failure:
* A key that expires within the window: if Gitea extends the expiry and republishes the
key, nothing changes in the role, because it fetches the key on every download; re-run
the check once the key source serves the new expiry. If Gitea moves to a new
key, verify the new fingerprint from Gitea's own announcement, then update
gitea_gpg_key_id (and gitea_gpg_key_url if the source changes) in the role defaults.
* A revoked or expired key, or a release signed by another key: the role refuses that
release, so installs and updates of it fail until gitea_gpg_key_id is updated as above.
Do not loosen the check in the role to get past it.
* Exit 2 (the check could not run): usually the network or the keyserver; re-run the
workflow before reading anything into it.
"""
import argparse
import datetime
import os
import pathlib
import re
import shutil
import signal
import subprocess
import sys
import tempfile
import time
import urllib.request
import yaml
DEFAULTS = pathlib.Path(__file__).resolve().parents[1] / "roles/gitea/defaults/main.yml"
TEMPLATE = re.compile(r"\{\{\s*([a-z_][a-z0-9_]*)\s*(\|\s*upper\s*)?\}\}")
FPR = re.compile(r"^[0-9A-F]{40}$")
ISSUER_FPR = re.compile(r"\(issuer fpr v4 ([0-9A-Fa-f]{40})\)")
ISSUER_KEYID = re.compile(r"\(issuer key ID ([0-9A-Fa-f]{16})\)")
SIG_PACKET = re.compile(r"^:signature packet:.*$", re.MULTILINE)
SIGNING = "s" # lowercase: the key's own capability (uppercase is the whole key's)
class CheckError(Exception):
"""The check could not run (input, network, gpg); not a finding about the key."""
def render(name, values, depth=0):
"""Value of the default `name` with its `{{ var }}` / `{{ var | upper }}` references filled in."""
if depth > 10:
raise CheckError(f"template recursion too deep while rendering {name}")
value = values.get(name)
if not isinstance(value, str):
raise CheckError(f"{name} is missing from the defaults or is not a string")
def sub(match):
out = render(match.group(1), values, depth + 1)
return out.upper() if match.group(2) else out
out = TEMPLATE.sub(sub, value)
if any(mark in out for mark in ("{{", "{%", "{#")):
raise CheckError(
f"{name} uses a template this script does not render: {value!r}"
)
return out
def inputs_from_defaults(path, overrides=None):
"""(key_url, fingerprint, signature_url, version) from the gitea role defaults.
overrides replace defaults of the same name before rendering, so a template that refers to
an overridden name (gitea_gpg_key_url to gitea_gpg_key_id) follows the override.
"""
try:
values = yaml.safe_load(pathlib.Path(path).read_text(encoding="utf-8"))
except (OSError, yaml.YAMLError) as exc:
raise CheckError(f"cannot read {path}: {exc}") from exc
if not isinstance(values, dict):
raise CheckError(f"{path} is not a mapping")
values.update({k: v for k, v in (overrides or {}).items() if v is not None})
return (
render("gitea_gpg_key_url", values),
render("gitea_gpg_key_id", values),
render("gitea_signature_url", values),
render("gitea_version", values),
)
def fetch(url, dest):
req = urllib.request.Request(url, headers={"User-Agent": "gitea-release-key-check"})
try:
with urllib.request.urlopen(
req, timeout=60
) as resp: # https, or file:// in the tests
data = resp.read(1024 * 1024)
except (OSError, ValueError) as exc:
raise CheckError(f"cannot fetch {url}: {exc}") from exc
if not data:
raise CheckError(f"{url} returned nothing")
dest.write_bytes(data)
def gpg(home, *args):
cmd = ["gpg", "--homedir", str(home), "--batch", "--no-autostart", *args]
try:
res = subprocess.run(cmd, capture_output=True, text=True, check=False)
except OSError as exc:
raise CheckError(f"cannot run gpg: {exc}") from exc
if res.returncode != 0:
raise CheckError(
f"{' '.join(cmd[4:])} failed (rc {res.returncode}): {res.stderr.strip()}"
)
return res.stdout
def parse_keys(colons):
"""{primary fpr: [key, ...]} from --with-colons --fixed-list-mode, the primary first.
Each key: {"fpr", "kind" (pub/sub), "validity", "expires" (epoch or None), "caps"}.
"""
keys, current, pending = {}, None, None
for line in colons.splitlines():
f = line.split(":")
if f[0] in ("pub", "sub"):
pending = {
"kind": f[0],
"validity": f[1],
"expires": int(f[6]) if f[6] else None,
"caps": f[11] if len(f) > 11 else "",
}
elif f[0] == "fpr" and pending is not None:
pending["fpr"] = f[9].upper()
if pending["kind"] == "pub":
current = pending["fpr"]
keys[current] = []
if current is not None:
keys[current].append(pending)
pending = None
return keys
def day(epoch):
return datetime.datetime.fromtimestamp(epoch, datetime.UTC).strftime("%Y-%m-%d")
def state(key, now):
"""'revoked', 'expired' or None (usable now)."""
if key["validity"] == "r":
return "revoked"
if key["validity"] == "e" or (key["expires"] is not None and key["expires"] <= now):
return "expired"
return None
def check_key(keys, fingerprint, window_days, now):
"""(errors, warnings, notes) about the pinned key and its signing-capable subkeys."""
errors, warnings, notes = [], [], []
horizon = now + window_days * 86400
primary = keys[fingerprint][0]
bad = state(primary, now)
if bad:
errors.append(
f"the primary key {fingerprint} is {bad}: every Gitea install and update fails"
)
return errors, warnings, notes
if primary["expires"] is not None and primary["expires"] <= horizon:
errors.append(
f"the primary key {fingerprint} expires on {day(primary['expires'])}, within {window_days} days: "
"if Gitea extends it, nothing changes here (the role fetches the key on every download); "
"if Gitea moves to a new key, update gitea_gpg_key_id"
)
else:
notes.append(
f"primary key {fingerprint}: valid, "
f"{'no expiry' if primary['expires'] is None else 'expires ' + day(primary['expires'])}"
)
usable = 0
for key in keys[fingerprint]:
if SIGNING not in key["caps"]:
continue
what = "primary key" if key["kind"] == "pub" else "signing subkey"
bad = state(key, now)
if bad:
notes.append(
f"{what} {key['fpr']} is {bad} (ignored unless it signed the release)"
)
continue
usable += 1
if key["kind"] == "sub":
if key["expires"] is not None and key["expires"] <= horizon:
errors.append(
f"the signing subkey {key['fpr']} expires on {day(key['expires'])}, within {window_days} days"
)
else:
notes.append(
f"signing subkey {key['fpr']}: valid, "
f"{'no expiry' if key['expires'] is None else 'expires ' + day(key['expires'])}"
)
if not usable:
errors.append(
f"the key {fingerprint} has no valid signing-capable key or subkey"
)
return errors, warnings, notes
def check_signature(packets, keys, fingerprint, now):
"""(errors, warnings, notes) about the issuers of the signatures in the release .asc.
Like the role: at least one signature, and every one by a valid signing key of the pinned key.
"""
errors, warnings, notes = [], [], []
starts = [m.start() for m in SIG_PACKET.finditer(packets)]
if not starts:
return ["the release signature file holds no signature"], warnings, notes
# A signature packet's subpackets follow its header line, up to the next packet ("# off=" or
# the next ":... packet:" line).
chunks = []
for start in starts:
rest = packets[start:]
nxt = re.search(r"^(?:#|:)", rest[1:], re.MULTILINE)
chunks.append(rest if nxt is None else rest[: nxt.start() + 1])
own = {k["fpr"]: k for k in keys[fingerprint]}
for chunk in chunks:
e, w, n = check_issuer(chunk, own, fingerprint, now)
errors += e
warnings += w
notes += n
return errors, warnings, notes
def check_issuer(chunk, own, fingerprint, now):
"""(errors, warnings, notes) about the issuer of one signature packet."""
errors, warnings, notes = [], [], []
match = ISSUER_FPR.search(chunk)
if match:
label = match.group(1).upper()
issuer = own.get(label)
else:
keyid = ISSUER_KEYID.search(chunk) or re.search(
r"keyid ([0-9A-Fa-f]{16})", chunk
)
if not keyid:
return ["a release signature names no issuer"], warnings, notes
label = keyid.group(1).upper()
hits = [k for f, k in own.items() if f.endswith(label)]
issuer = hits[0] if len(hits) == 1 else None
warnings.append(
f"a release signature has no issuer fingerprint, matched on the key ID {label} only"
)
if issuer is None:
errors.append(
f"the release is signed by {label}, which is not the key {fingerprint} or one of its subkeys: "
"the role rejects it"
)
return errors, warnings, notes
bad = state(issuer, now)
if bad:
errors.append(
f"the release is signed by {issuer['fpr']}, which is {bad}: the role rejects the signature"
)
elif SIGNING not in issuer["caps"]:
errors.append(
f"the release is signed by {issuer['fpr']}, which is not signing-capable"
)
else:
notes.append(
f"release signature issuer {issuer['fpr']}: a valid signing key of {fingerprint}"
)
return errors, warnings, notes
def run(key_url, fingerprint, signature_url, window_days, now=None):
"""(errors, warnings, notes); raises CheckError when the check cannot run."""
now = int(time.time()) if now is None else now
fingerprint = fingerprint.upper()
if not FPR.match(fingerprint):
raise CheckError(
f"the pinned fingerprint {fingerprint!r} is not a 40-hex-digit v4 fingerprint"
)
if window_days < 0:
raise CheckError("the window must not be negative")
home = pathlib.Path(tempfile.mkdtemp(prefix="gitea-key.")) # 0700, as gpg wants
try:
fetch(key_url, home / "key.asc")
fetch(signature_url, home / "release.asc")
gpg(home, "--import", str(home / "key.asc"))
keys = parse_keys(
gpg(home, "--with-colons", "--fixed-list-mode", "--list-keys")
)
if fingerprint not in keys:
return (
[
f"{key_url} did not provide the pinned key {fingerprint} (got: {', '.join(keys) or 'none'})"
],
[],
[],
)
errors, warnings, notes = check_key(keys, fingerprint, window_days, now)
e2, w2, n2 = check_signature(
gpg(home, "--list-packets", str(home / "release.asc")),
keys,
fingerprint,
now,
)
return errors + e2, warnings + w2, notes + n2
finally:
subprocess.run(
["gpgconf", "--homedir", str(home), "--kill", "all"],
capture_output=True,
check=False,
)
shutil.rmtree(home, ignore_errors=True)
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument(
"--defaults",
default=str(DEFAULTS),
help="gitea role defaults to read the pins from",
)
parser.add_argument(
"--window-days",
type=int,
default=60,
help="fail when a key expires within this many days",
)
parser.add_argument("--key-url", help="override gitea_gpg_key_url")
parser.add_argument("--fingerprint", help="override gitea_gpg_key_id")
parser.add_argument("--signature-url", help="override gitea_signature_url")
args = parser.parse_args(argv)
# SIGTERM (a cancelled job) must still run the cleanup in run()'s finally.
signal.signal(signal.SIGTERM, lambda *_: sys.exit(143))
try:
key_url, fingerprint, signature_url, version = inputs_from_defaults(
args.defaults,
{
"gitea_gpg_key_url": args.key_url,
"gitea_gpg_key_id": args.fingerprint,
"gitea_signature_url": args.signature_url,
},
)
print(
f"key: {key_url}\nfingerprint: {fingerprint}\nsignature: {signature_url}"
f"{f' (gitea {version})' if version else ''}\nwindow: {args.window_days} days"
)
errors, warnings, notes = run(
key_url, fingerprint, signature_url, args.window_days
)
except CheckError as exc:
print(f"::error::Gitea release key check could not run: {exc}")
return 2
for note in notes:
print(f"ok: {note}")
for warning in warnings:
print(f"::warning::{warning}")
for error in errors:
print(f"::error::{error}")
print(
"FAIL"
if errors
else "OK: the Gitea release key and the pinned release's signature pass"
)
summary = os.environ.get("GITHUB_STEP_SUMMARY")
if summary and (errors or warnings):
with open(summary, "a", encoding="utf-8") as fh:
fh.write(
"## Gitea release key\n\n"
+ "".join(f"- {m}\n" for m in errors + warnings)
)
return 1 if errors else 0
if __name__ == "__main__":
sys.exit(main())
+4 -3
View File
@@ -38,9 +38,9 @@ Known limits:
* Renaming an image in the matrix in the same PR skips the bump check for it (the new
name has no base entry); the pins check still catches a consumer pin left on the old
name, because that name is no longer in the matrix.
* Of the consumer files, only lint.yml is required (it runs this check); build.yml and
molecule.yml are skipped when absent, and the success line lists the files that were
actually checked, so a consumer that vanished is visible.
* Of the consumer files, only lint.yml is required (it runs this check); build.yml,
molecule.yml and gitea-release-key.yml are skipped when absent, and the success line
lists the files that were actually checked, so a consumer that vanished is visible.
* The matrix is read by a small block-style reader (the Renovate image has no PyYAML), not
a YAML parser: flow style, anchors, tags, block scalars and escapes are errors, and so is
a duplicate key inside an entry. Tests compare it with PyYAML on the real file.
@@ -65,6 +65,7 @@ CONSUMERS = [
REQUIRED_CONSUMER,
".gitea/workflows/build.yml",
".gitea/workflows/molecule.yml",
".gitea/workflows/gitea-release-key.yml",
]
PIN_RE = re.compile(
r"git\.rkdr\.net/mortis/(?P<name>[a-z0-9._-]+):(?P<version>[^@\s]+)@(?P<digest>sha256:[0-9a-f]{64})"
+2
View File
@@ -90,10 +90,12 @@ IGNORED = (
".gitea/workflows/build.yml",
".gitea/workflows/image.yml",
".gitea/workflows/renovate.yml",
".gitea/workflows/gitea-release-key.yml",
"scripts/bump_image_versions.py",
"scripts/check_bot_pr_diff.py",
"scripts/check_image_versions.py",
"scripts/check_tarball.py",
"scripts/check_gitea_release_key.py",
"scripts/ansible-lint.sh",
"scripts/ansible-test-sanity.sh",
"scripts/dev-setup.sh",
+10
View File
@@ -141,6 +141,11 @@ class RuleTest(unittest.TestCase):
f" git.rkdr.net/mortis/mol:0.1.0@{D1}",
f" git.rkdr.net/mortis/mol:0.1.1@{D2}",
),
(
".gitea/workflows/gitea-release-key.yml",
f" image: git.rkdr.net/mortis/ci:0.2.0@{D1}",
f" image: git.rkdr.net/mortis/ci:0.2.1@{D2}",
),
]
for path, old, new in cases:
self.assertIsNone(self.problem(path, old, new), (path, old, new))
@@ -208,6 +213,11 @@ class RuleTest(unittest.TestCase):
f" job_image: evil:1@{D1}",
),
(".gitea/workflows/lint.yml", "run: echo a", "run: echo b"),
(
".gitea/workflows/gitea-release-key.yml",
"run: echo a",
"run: echo b",
),
(
".gitea/workflows/lint.yml",
f" image: git.rkdr.net/mortis/ci:0.2.0@{D1}",
@@ -0,0 +1,337 @@
# 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)
@@ -141,6 +141,17 @@ class SelectTest(unittest.TestCase):
)
self.assertEqual(chosen, [])
def test_gitea_release_key_check_selects_nothing(self):
# The check reads roles/gitea/defaults/main.yml, but no scenario reads the check.
chosen, _reason = self.select(
[
".gitea/workflows/gitea-release-key.yml",
"scripts/check_gitea_release_key.py",
"tests/scripts/test_check_gitea_release_key.py",
],
)
self.assertEqual(chosen, [])
def test_role_rules_for_agents_select_nothing(self):
# roles/AGENTS.md is contributor guidance that no scenario reads (it is not shipped).
chosen, _reason = sel.select(ALL, ["roles/AGENTS.md"])