diff --git a/.github/dependabot.yml b/.github/dependabot.yml index f4e2da25b6..b51f38680d 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -15,6 +15,7 @@ updates: rebase-strategy: "auto" labels: - "dependencies" + - "update" - "python" # ------------------------------------------------------------ @@ -29,6 +30,7 @@ updates: time: "00:00" labels: - "dependencies" + - "update" - "ci" # ------------------------------------------------------------ @@ -43,6 +45,7 @@ updates: time: "00:00" labels: - "dependencies" + - "update" - "docker" # ------------------------------------------------------------ @@ -57,6 +60,7 @@ updates: time: "00:00" labels: - "dependencies" + - "update" - "docker" # ------------------------------------------------------------ @@ -75,6 +79,7 @@ updates: time: "00:00" labels: - "dependencies" + - "update" - "ci" # ------------------------------------------------------------ @@ -90,6 +95,7 @@ updates: time: "00:00" labels: - "dependencies" + - "update" - "javascript" # ------------------------------------------------------------ @@ -104,6 +110,7 @@ updates: time: "00:00" labels: - "dependencies" + - "update" - "php" # ------------------------------------------------------------ @@ -188,6 +195,7 @@ updates: time: "00:00" labels: - "dependencies" + - "update" - "ruby" # cargo: no Cargo.toml found diff --git a/.github/workflows/README.md b/.github/workflows/README.md index 3afca0f735..bff53e3419 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -86,6 +86,14 @@ can outlast it — so the estimate can only overshoot the real drain time. With the current constants that is 4 waves of 20 runners, so 80 rows per chunk, and the last job of a chunk starts around t=18h, well inside the 24h window. +The repository variable `INFINITO_CI_CONCURRENCY` overrides the `default.env` +value; unset or empty keeps it. `call-validation.yml` and `call-test-deploy.yml` +forward it in their workflow-level `env:`, so the batch count and every chunk's +cut use the same size. An account that runs 500 jobs at once (GitHub +Enterprise) gets a chunk larger than `available` below, so a sweep needs one +chunk, two with a priority line, and only the run's job cap bounds it. See +[configuration.md](../../docs/contributing/tools/github/actions/configuration.md). + ### How many chunks a sweep spends The run's 256-job cap is the second ceiling. `slots` counts every non-deploy diff --git a/.github/workflows/call-images-build-ci.yml b/.github/workflows/call-images-build-ci.yml index e375c6af30..a445630d43 100644 --- a/.github/workflows/call-images-build-ci.yml +++ b/.github/workflows/call-images-build-ci.yml @@ -78,6 +78,8 @@ jobs: permissions: contents: read packages: write + env: + FORK_TARGET_BUILD: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.head.repo.full_name != github.repository }} steps: - name: ⬇️ Checkout trusted workflow repo (helpers) @@ -158,7 +160,8 @@ jobs: INFINITO_DISTROS: ${{ join(fromJson(needs.pools.outputs.matrix), ' ') }} IMAGE_ARCH: ${{ matrix.architecture }} IMAGE_DIGEST_DIR: build/image-digests - USE_NIX_TOKEN: ${{ !(github.event_name == 'pull_request_target' && github.event.pull_request.head.repo.full_name != github.repository) }} + USE_NIX_TOKEN: ${{ env.FORK_TARGET_BUILD != 'true' }} + EXPORT_BUILD_CACHE: ${{ env.FORK_TARGET_BUILD != 'true' }} NIX_GITHUB_TOKEN: ${{ github.token }} MAX_ATTEMPTS: "7" RETRY_DELAY_SECONDS: "20" diff --git a/.github/workflows/call-images-mirror-missing.yml b/.github/workflows/call-images-mirror-missing.yml index 9d95329996..7f70bdec8a 100644 --- a/.github/workflows/call-images-mirror-missing.yml +++ b/.github/workflows/call-images-mirror-missing.yml @@ -91,6 +91,8 @@ jobs: steps: - name: ⬇️ Checkout uses: actions/checkout@v7.0.0 + with: + persist-credentials: false - name: 🔍 Resolve GHCR namespace and repository id: vars @@ -99,6 +101,10 @@ jobs: GHCR_NAMESPACE_INPUT: ${{ inputs.ghcr_namespace || '' }} run: bash scripts/meta/resolve/ghcr/namespace_and_repository.sh + - name: 🔗 Check symlinks out as plain files (optional) + if: ${{ inputs.source_repository != '' && inputs.source_ref != '' }} + run: git config --global core.symlinks false + - name: ⬇️ Checkout source repo for scan (optional) if: ${{ inputs.source_repository != '' && inputs.source_ref != '' }} uses: actions/checkout@v7.0.0 @@ -110,6 +116,12 @@ jobs: persist-credentials: false allow-unsafe-pr-checkout: ${{ inputs.allow_unsafe_checkout }} + - name: 🔗 Refuse symlinks in the scanned source (optional) + if: ${{ inputs.source_repository != '' && inputs.source_ref != '' }} + env: + SOURCE_PATH: ${{ inputs.source_path }} + run: bash scripts/github/gate/no_symlinks.sh "${SOURCE_PATH}" + - name: 🔧 Setup Python uses: actions/setup-python@v6 with: diff --git a/.github/workflows/call-orchestrator.yml b/.github/workflows/call-orchestrator.yml index 04da142767..cc1ac3fff9 100644 --- a/.github/workflows/call-orchestrator.yml +++ b/.github/workflows/call-orchestrator.yml @@ -398,7 +398,7 @@ jobs: if: ${{ !cancelled() }} run: grep '^INFINITO_GHCR_MIRROR_PREFIX=' default.env >> "$GITHUB_ENV" - name: 🛡️ Open, update and close the runtime vulnerability issues - if: ${{ !cancelled() }} + if: ${{ !cancelled() && (contains(needs.*.result, 'success') || contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled')) }} env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: python3 -m cli.meta.ci.runtime_vulnerabilities --run-id "${{ github.run_id }}" --repo "${{ github.repository }}" --ref "${GITHUB_REF}" --dir "${RUNNER_TEMP}/rescue-diagnostics" diff --git a/.github/workflows/call-test-deploy.yml b/.github/workflows/call-test-deploy.yml index b2ee79e5c7..d9cb405b8d 100644 --- a/.github/workflows/call-test-deploy.yml +++ b/.github/workflows/call-test-deploy.yml @@ -170,6 +170,7 @@ env: INFINITO_ARCHITECTURES: ${{ inputs.architectures }} INFINITO_LIFECYCLES: ${{ inputs.lifecycles }} INFINITO_DISCOVERY_SEED: ${{ github.run_id }} + INFINITO_CI_CONCURRENCY: ${{ vars.INFINITO_CI_CONCURRENCY }} jobs: discover: diff --git a/.github/workflows/call-validation.yml b/.github/workflows/call-validation.yml index 9171c80a82..0129e213d7 100644 --- a/.github/workflows/call-validation.yml +++ b/.github/workflows/call-validation.yml @@ -105,6 +105,9 @@ on: permissions: contents: read +env: + INFINITO_CI_CONCURRENCY: ${{ vars.INFINITO_CI_CONCURRENCY }} + jobs: validation: name: ✅ Validation diff --git a/.github/workflows/cron-update.yml b/.github/workflows/cron-update.yml index 479e3a900c..9be204fb75 100644 --- a/.github/workflows/cron-update.yml +++ b/.github/workflows/cron-update.yml @@ -249,7 +249,7 @@ jobs: UPDATE_BRANCH_PREFIX: update/repository-refs UPDATE_COMMIT_MESSAGE: "update(repos): bump git refs to latest tags and commits" UPDATE_PR_TITLE: "update(repos): bump git refs to latest tags and commits" - UPDATE_PR_BODY: "Automated update of git `ref:` values in `roles/*/meta/services.yml` and `roles/*/meta/addons/*.yml`. A semver ref moves to the latest upstream tag (`git ls-remote --tags`), a commit SHA to the tip of the default branch (`git ls-remote HEAD`)." + UPDATE_PR_BODY: "Automated update of git `ref:` values in `roles/*/meta/services.yml` and `roles/*/meta/addons/*.yml`. A semver ref moves to the latest upstream tag (`git ls-remote --tags`), a commit SHA to the newest release tag that contains it, or to the tip of the default branch (`git ls-remote HEAD`) when no release does." UPDATE_BASE_BRANCH: main run: bash scripts/github/update/open/role_prs.sh roles diff --git a/.github/workflows/entry-pr-change-dependabot-label.yml b/.github/workflows/entry-pr-change-dependabot-label.yml new file mode 100644 index 0000000000..8acf9116bc --- /dev/null +++ b/.github/workflows/entry-pr-change-dependabot-label.yml @@ -0,0 +1,40 @@ +name: "🔄 Dependabot: Label update level" + +on: + pull_request_target: + types: [opened, reopened, synchronize] + +permissions: {} + +jobs: + label: + name: 🏷️ Label the Dependabot PR + if: github.event.pull_request.user.login == 'dependabot[bot]' && vars.CI_ENABLE_AUTO_UPDATES == 'true' + runs-on: ubuntu-26.04 + timeout-minutes: 10 + permissions: + contents: read + pull-requests: write + steps: + - name: 🔎 Read Dependabot metadata + id: metadata + uses: dependabot/fetch-metadata@25dd0e34f4fe68f24cc83900b1fe3fe149efef98 # v3.1.0 + + - name: ⬇️ Checkout the base branch + uses: actions/checkout@v7.0.0 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + + - name: 🔧 Set up Python + uses: actions/setup-python@v6 + with: + python-version: "3.12" + + - name: 🏷️ Label update and semver level + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + REPOSITORY: ${{ github.repository }} + PR_NUMBER: ${{ github.event.pull_request.number }} + UPDATE_TYPE: ${{ steps.metadata.outputs.update-type }} + run: python3 -m cli.contributing.update.label --repo "$REPOSITORY" --pr "$PR_NUMBER" --update-type "$UPDATE_TYPE" diff --git a/.github/workflows/entry-pr-change-orchestrate.yml b/.github/workflows/entry-pr-change-orchestrate.yml index 0a3c46f036..4f2921e911 100644 --- a/.github/workflows/entry-pr-change-orchestrate.yml +++ b/.github/workflows/entry-pr-change-orchestrate.yml @@ -140,8 +140,27 @@ jobs: PR_MERGE_SHA: ${{ github.event.pull_request.merge_commit_sha || '' }} run: ./scripts/meta/resolve/pr/merge_ref.sh - build-ci-images-fork: + fork-trust-gate: + name: 🛡️ Gate fork trust needs: prepare-fork-merge-ref + runs-on: ubuntu-26.04 + steps: + - name: ⬇️ Checkout + uses: actions/checkout@v7.0.0 + with: + persist-credentials: false + + - name: 🛡️ Require the maintainer Trusted label + shell: bash + env: + TRUSTED: ${{ needs.prepare-fork-merge-ref.outputs.trusted }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: bash scripts/github/gate/trusted_label.sh + + build-ci-images-fork: + needs: + - prepare-fork-merge-ref + - fork-trust-gate permissions: contents: read packages: write @@ -155,7 +174,9 @@ jobs: allow_unsafe_checkout: true images-mirror-missing-fork: - needs: prepare-fork-merge-ref + needs: + - prepare-fork-merge-ref + - fork-trust-gate permissions: contents: read packages: write diff --git a/.github/workflows/entry-pr-green-update-merge.yml b/.github/workflows/entry-pr-green-update-merge.yml new file mode 100644 index 0000000000..9091ebb92b --- /dev/null +++ b/.github/workflows/entry-pr-green-update-merge.yml @@ -0,0 +1,69 @@ +name: "🔄 Update: Merge proven PRs" +run-name: "🔄 Merge check for ${{ github.event.workflow_run.head_branch }}" + +on: + workflow_run: + workflows: ["🔀 Pull Request"] + types: [completed] + +permissions: {} + +jobs: + merge: + name: 🔀 Merge a proven update PR + if: >- + vars.CI_ENABLE_AUTO_UPDATES == 'true' + && github.event.workflow_run.event == 'pull_request' + && github.event.workflow_run.conclusion == 'success' + && (startsWith(github.event.workflow_run.head_branch, 'update/') + || startsWith(github.event.workflow_run.head_branch, 'dependabot/')) + runs-on: ubuntu-26.04 + timeout-minutes: 15 + permissions: + actions: read + checks: read + contents: read + pull-requests: read + statuses: read + steps: + - name: ⬇️ Checkout + uses: actions/checkout@v7.0.0 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + + - name: 🔧 Set up Python + uses: actions/setup-python@v6 + with: + python-version: "3.12" + + - name: 🔎 Check the merge gate + id: gate + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + REPOSITORY: ${{ github.repository }} + HEAD_SHA: ${{ github.event.workflow_run.head_sha }} + RUN_ID: ${{ github.event.workflow_run.id }} + OWN_RUN_ID: ${{ github.run_id }} + BASE_BRANCH: ${{ github.event.repository.default_branch }} + run: >- + python3 -m cli.contributing.update.merge + --repo "$REPOSITORY" --sha "$HEAD_SHA" --run-id "$RUN_ID" + --own-run-id "$OWN_RUN_ID" --base "$BASE_BRANCH" --output "$GITHUB_OUTPUT" + + - name: ⚙️ Generate app token + if: steps.gate.outputs.merge == 'true' + id: app-token + uses: actions/create-github-app-token@v3 + with: + client-id: ${{ secrets.BOT_APP_CLIENT_ID }} + private-key: ${{ secrets.BOT_APP_PRIVATE_KEY }} + + - name: 🔀 Merge the update PR at its tested head + if: steps.gate.outputs.merge == 'true' + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + REPOSITORY: ${{ github.repository }} + PR_NUMBER: ${{ steps.gate.outputs.pr }} + HEAD_SHA: ${{ steps.gate.outputs.sha }} + run: gh api --method PUT "repos/${REPOSITORY}/pulls/${PR_NUMBER}/merge" -f merge_method=merge -f sha="${HEAD_SHA}" diff --git a/cli/contributing/update/README.md b/cli/contributing/update/README.md index 7e8f2f564c..8d2d2f9fa5 100644 --- a/cli/contributing/update/README.md +++ b/cli/contributing/update/README.md @@ -10,12 +10,15 @@ Every role-scoped updater (`docker`, `source`, `pip`, `repository`) and the addo `python -m cli.contributing.update.repository` bumps every `ref:` that sits next to a `repository:` in `roles/*/meta/services.yml` or `roles/*/meta/addons/*.yml`, at any depth, an addon's `config` included: -| `ref:` | Moves to | Reads | -| ---------------------- | ------------------------------------------- | ----------------------------------- | -| semver, e.g. `v0.8.5` | the latest tag of the same depth and flavor | `git ls-remote --tags ` | -| full 40-hex commit SHA | the tip of the default branch | `git ls-remote HEAD` | +| `ref:` | Moves to | Reads | +| ---------------------- | ------------------------------------------- | -------------------------------------------- | +| semver, e.g. `v0.8.5` | the latest tag of the same depth and flavor | `git ls-remote --tags ` | +| full 40-hex commit SHA | the newest release tag that contains it | `git ls-remote --tags`, treeless `git fetch` | +| same, no such release | the tip of the default branch | `git ls-remote HEAD` | -A branch name and a short SHA stay as they are. `# nocheck: repository-version` on the line above `ref:` freezes a pin. Each repository is queried once per run and lookup, and a failed query leaves its pins untouched. The `update-repository-refs` job of `.github/workflows/cron-update.yml` opens one PR per changed role, and `tests/external/update/repository/` warns about pending bumps. +A branch name and a short SHA stay as they are. `# nocheck: repository-version` on the line above `ref:` freezes a pin. Each repository is queried once per run and lookup, and a failed query leaves its pins untouched. The `update-repository-refs` job of `.github/workflows/cron-update.yml` opens one PR per changed role, and `tests/external/update/repository/` warns about pending bumps and fails on a commit SHA that a release tag already contains. A pin newer than the newest release keeps following the tip, so no pin moves back to an older release. + +Every update PR carries the label `update` and one of `major`, `minor` or `patch`: the highest step among its changed versions, read by [level.py](../../../utils/update/level.py). A change that is no number step (a commit SHA, a SHA moving to a tag) counts as `major`. ## Declared version sources diff --git a/cli/contributing/update/label/__init__.py b/cli/contributing/update/label/__init__.py new file mode 100644 index 0000000000..ead172a6cf --- /dev/null +++ b/cli/contributing/update/label/__init__.py @@ -0,0 +1,30 @@ +"""Labels an update pull request carries: ``update`` plus its semver level.""" + +from __future__ import annotations + +from typing import NamedTuple + + +class Label(NamedTuple): + """One repository label. + + Args: + name: the label name. + color: the six-digit hex colour, without ``#``. + description: the text the repository's label list shows. + """ + + name: str + color: str + description: str + + +UPDATE = Label("update", "0366D6", "Automated dependency or version update") +MAJOR = Label( + "major", "B60205", "Update raises a major version, or one of unknown reach" +) +MINOR = Label("minor", "FBCA04", "Update raises a minor version") +PATCH = Label("patch", "0E8A16", "Update raises a patch version") +LEVELS = (MAJOR, MINOR, PATCH) + +__all__ = ["LEVELS", "MAJOR", "MINOR", "PATCH", "UPDATE", "Label"] diff --git a/cli/contributing/update/label/__main__.py b/cli/contributing/update/label/__main__.py new file mode 100755 index 0000000000..460c355ccb --- /dev/null +++ b/cli/contributing/update/label/__main__.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import subprocess +from typing import TYPE_CHECKING +from urllib.parse import quote + +from . import LEVELS, MAJOR, MINOR, PATCH, UPDATE + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Sequence + + from . import Label + +GH_TIMEOUT_SECONDS = 120 +_LEVEL_OF_UPDATE_TYPE = { + "version-update:semver-major": MAJOR, + "version-update:semver-minor": MINOR, + "version-update:semver-patch": PATCH, +} + + +def level(update_type: str) -> Label: + """The semver label of a Dependabot update. + + Args: + update_type: the ``update-type`` output of ``dependabot/fetch-metadata``. + + Returns: + ``minor`` or ``patch`` for those semver levels, ``major`` for everything + else, so an update of unknown reach is never filed as a small one. + """ + return _LEVEL_OF_UPDATE_TYPE.get(update_type.strip(), MAJOR) + + +def run_gh(args: Sequence[str]) -> str: + return subprocess.run( + ["gh", *args], + capture_output=True, + text=True, + check=True, + timeout=GH_TIMEOUT_SECONDS, + ).stdout + + +def names(gh: Callable[[Sequence[str]], str], path: str) -> set[str]: + """The ``name`` of every label a paginated REST list returns. + + Args: + gh: runs ``gh`` with the given arguments and returns its stdout. + path: the REST path listing the labels. + + Returns: + the label names. + """ + out = gh(["api", "--paginate", path, "--jq", ".[].name"]) + return {line for line in out.splitlines() if line} + + +def ensure_labels( + gh: Callable[[Sequence[str]], str], repo: str, labels: Iterable[Label] +) -> list[str]: + """Create the labels the repository lacks, leaving existing ones untouched. + + Args: + gh: runs ``gh`` with the given arguments and returns its stdout. + repo: ``owner/name``. + labels: the labels that must exist. + + Returns: + the names created. A create that fails because a parallel run created + the label first counts as done; any other failure raises. + """ + existing = names(gh, f"repos/{repo}/labels") + created: list[str] = [] + for label in labels: + if label.name in existing: + continue + try: + gh( + [ + "label", + "create", + label.name, + "--repo", + repo, + "--color", + label.color, + "--description", + label.description, + ] + ) + except subprocess.CalledProcessError: + if label.name not in names(gh, f"repos/{repo}/labels"): + raise + continue + created.append(label.name) + return created + + +def sync( + gh: Callable[[Sequence[str]], str], repo: str, pr: int, update_type: str +) -> list[str]: + """Leave *pr* carrying ``update`` and exactly one semver label. + + Args: + gh: runs ``gh`` with the given arguments and returns its stdout. + repo: ``owner/name``. + pr: the pull request number. + update_type: the ``update-type`` output of ``dependabot/fetch-metadata``. + + Returns: + what was done, one line per action. A label the pull request already + carries is not added again: a ``labeled`` event restarts its CI run. + """ + wanted = (UPDATE, level(update_type)) + actions = [f"created label {name}" for name in ensure_labels(gh, repo, wanted)] + current = names(gh, f"repos/{repo}/issues/{pr}/labels") + for stale in LEVELS: + if stale not in wanted and stale.name in current: + gh( + [ + "api", + "--method", + "DELETE", + f"repos/{repo}/issues/{pr}/labels/{quote(stale.name)}", + ] + ) + actions.append(f"removed {stale.name}") + missing = [label.name for label in wanted if label.name not in current] + if missing: + args = ["api", "--method", "POST", f"repos/{repo}/issues/{pr}/labels"] + for name in missing: + args += ["-f", f"labels[]={name}"] + gh(args) + actions.append(f"added {', '.join(missing)}") + return actions + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description=( + "Label a Dependabot pull request `update` plus exactly one of " + "`major`, `minor` and `patch`, creating labels the repository lacks." + ) + ) + parser.add_argument("--repo", required=True, help="owner/name") + parser.add_argument( + "--ensure-only", + action="store_true", + help="Only create the update labels the repository lacks", + ) + parser.add_argument("--pr", type=int, help="Pull request number") + parser.add_argument( + "--update-type", + help="update-type output of dependabot/fetch-metadata, possibly empty", + ) + args = parser.parse_args(argv) + if args.ensure_only: + for name in ensure_labels(run_gh, args.repo, (UPDATE, *LEVELS)): + print(f"created label {name}") + return 0 + if args.pr is None or args.update_type is None: + parser.error("--pr and --update-type are required without --ensure-only") + actions = sync(run_gh, args.repo, args.pr, args.update_type) + for line in actions or [f"#{args.pr} already carries its labels"]: + print(line) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/cli/contributing/update/merge/__init__.py b/cli/contributing/update/merge/__init__.py new file mode 100644 index 0000000000..cad4397f40 --- /dev/null +++ b/cli/contributing/update/merge/__init__.py @@ -0,0 +1 @@ +"""Merge gate of update pull requests: green checks plus a deploy of every changed role.""" diff --git a/cli/contributing/update/merge/__main__.py b/cli/contributing/update/merge/__main__.py new file mode 100755 index 0000000000..3733277479 --- /dev/null +++ b/cli/contributing/update/merge/__main__.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import re +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from . import gate, github + +if TYPE_CHECKING: + from collections.abc import Sequence + + from .github import Gh + +_SHA = re.compile(r"[0-9a-f]{40}") + + +def evaluate( + gh: Gh, repo: str, sha: str, run_id: int, own_run_id: int, base: str +) -> tuple[dict[str, Any] | None, list[str]]: + """Judge the update pull request whose CI run *run_id* went green on *sha*. + + Args: + gh: runs ``gh`` with the given arguments and returns its stdout. + repo: ``owner/name``. + sha: the head commit the run tested. + run_id: the green ``🔀 Pull Request`` run of that commit. + own_run_id: the run deciding the merge. + base: the branch an update pull request must target. + + Returns: + the pull request, ``None`` unless exactly one open pull request has + that head, and the reasons refusing the merge, empty when it may + merge. The stages run in order and stop at the first that refuses: + pull request, checks, deployed roles. + """ + prs = github.open_pull_requests(gh, repo, sha) + if len(prs) != 1: + return None, [f"{len(prs)} open pull requests have head {sha}, not one"] + pr = prs[0] + refusals = gate.pull_request_refusals(pr, repo, base) + if refusals: + return pr, refusals + refusals = gate.check_refusals( + github.check_runs(gh, repo, sha), github.statuses(gh, repo, sha), own_run_id + ) + if refusals: + return pr, refusals + changed = gate.changed_roles(github.changed_paths(gh, repo, pr["number"])) + csv_texts = github.role_runtime_csvs(gh, repo, run_id) if changed else [] + return pr, gate.role_refusals(changed, csv_texts) + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description=( + "Decide whether an update pull request merges itself: a bot opened " + "it, it carries the update label, every check on its head is green " + "and CI deployed every role it changes." + ) + ) + parser.add_argument("--repo", required=True, help="owner/name") + parser.add_argument("--sha", required=True, help="Head commit the CI run tested") + parser.add_argument("--run-id", required=True, type=int, help="Green CI run id") + parser.add_argument( + "--own-run-id", required=True, type=int, help="Run id deciding the merge" + ) + parser.add_argument("--base", required=True, help="Branch the PR must target") + parser.add_argument( + "--output", + required=True, + type=Path, + help="File the merge, pr and sha step outputs are appended to", + ) + args = parser.parse_args(argv) + if not _SHA.fullmatch(args.sha): + parser.error(f"--sha is no full commit SHA: {args.sha!r}") + + pr, refusals = evaluate( + github.run_gh, args.repo, args.sha, args.run_id, args.own_run_id, args.base + ) + merge = pr is not None and not refusals + label = f"#{pr['number']}" if pr is not None else args.sha + if merge: + print(f"{label} merges: checks green, every changed role deployed.") + else: + print(f"{label} stays open for a manual merge:") + for reason in refusals: + print(f"- {reason}") + with args.output.open("a", encoding="utf-8") as handle: + handle.write(f"merge={'true' if merge else 'false'}\n") + if merge: + handle.write(f"pr={pr['number']}\nsha={args.sha}\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/cli/contributing/update/merge/gate.py b/cli/contributing/update/merge/gate.py new file mode 100644 index 0000000000..7bc0051116 --- /dev/null +++ b/cli/contributing/update/merge/gate.py @@ -0,0 +1,154 @@ +"""Decide whether an update pull request has earned an automatic merge. + +Each check returns the reasons that refuse the merge; an empty list passes it. +""" + +from __future__ import annotations + +import csv +import io +import re +from typing import TYPE_CHECKING, Any + +from cli.contributing.update.label import UPDATE + +if TYPE_CHECKING: + from collections.abc import Iterable, Mapping + +BOT_BRANCH_PREFIXES = { + "infinito-nexus-updater[bot]": "update/", + "dependabot[bot]": "dependabot/", +} +GREEN_CONCLUSIONS = frozenset({"success", "skipped", "neutral"}) +ROLE_COLUMN = "role" +_ROLE_PATH = re.compile(r"^roles/(?P[^/]+)/") + + +def pull_request_refusals(pr: Mapping[str, Any], repo: str, base: str) -> list[str]: + """Why *pr* is no update pull request a bot may merge. + + Args: + pr: the pull request as the REST API returns it. + repo: ``owner/name`` the head branch must live in. + base: the branch the pull request must target. + + Returns: + one line per unmet condition: an author outside the update bots, a + head branch outside that bot's prefix or repository, a draft, another + base branch, a missing ``update`` label. + """ + refusals: list[str] = [] + author = pr["user"]["login"] + head = pr["head"]["ref"] + prefix = BOT_BRANCH_PREFIXES.get(author) + if prefix is None: + refusals.append(f"author {author} is no update bot") + elif not head.startswith(prefix): + refusals.append(f"branch {head} lacks the {prefix} prefix of {author}") + head_repo = pr["head"]["repo"] + if head_repo is None or head_repo["full_name"] != repo: + refusals.append(f"head branch {head} lives outside {repo}") + if pr["draft"]: + refusals.append("pull request is a draft") + if pr["base"]["ref"] != base: + refusals.append(f"base branch is {pr['base']['ref']}, not {base}") + if UPDATE.name not in {label["name"] for label in pr["labels"]}: + refusals.append(f"label {UPDATE.name} is missing") + return refusals + + +def check_refusals( + check_runs: Iterable[Mapping[str, Any]], + statuses: Iterable[Mapping[str, Any]], + own_run_id: int, +) -> list[str]: + """Why the checks on the head commit are not all green. + + Args: + check_runs: the commit's latest check runs, each with ``name``, + ``status``, ``conclusion`` and ``details_url``. + statuses: the commit's latest status per context, each with + ``context`` and ``state``. + own_run_id: the run deciding the merge; its own check runs are still + in progress and do not count. + + Returns: + one line per check run that has not completed as success, skipped or + neutral, one per status that is not success, and one when no check + run is left to judge. + """ + own = f"/actions/runs/{own_run_id}/" + refusals: list[str] = [] + judged = 0 + for run in check_runs: + if own in (run["details_url"] or ""): + continue + judged += 1 + if run["status"] != "completed": + refusals.append(f"check {run['name']} is {run['status']}") + elif run["conclusion"] not in GREEN_CONCLUSIONS: + refusals.append(f"check {run['name']} concluded {run['conclusion']}") + if not judged: + refusals.append("no check run on the head commit") + refusals.extend( + f"status {status['context']} is {status['state']}" + for status in statuses + if status["state"] != "success" + ) + return refusals + + +def changed_roles(paths: Iterable[str]) -> set[str]: + """The roles whose files *paths* touch. + + Args: + paths: repository-relative paths, old names of renamed files included. + + Returns: + ```` of every ``roles//...`` path. + """ + return {match["role"] for path in paths if (match := _ROLE_PATH.match(path))} + + +def deployed_roles(csv_texts: Iterable[str]) -> set[str]: + """The roles the deploy rows ran, read from ``role-runtimes-*`` CSVs. + + The CSVs come out of a pull request's CI run, so they are parsed as data + and their values only ever compared, never executed or used as paths. + + Args: + csv_texts: the text of each CSV ``cli.meta.ci.roles.runtime`` wrote. + + Returns: + every non-empty value of the ``role`` column, dependencies included. + """ + roles: set[str] = set() + for text in csv_texts: + for row in csv.DictReader(io.StringIO(text)): + role = (row.get(ROLE_COLUMN) or "").strip() + if role: + roles.add(role) + return roles + + +def role_refusals(changed: set[str], csv_texts: list[str]) -> list[str]: + """Why the deploy rows do not prove every changed role. + + Args: + changed: the roles the pull request changes. + csv_texts: the ``role-runtimes-*`` CSVs of the pull request's CI run. + + Returns: + nothing when no role changed; one line when no CSV was uploaded, + since an upload that found no file is silent; otherwise one line per + changed role no deploy row ran. + """ + if not changed: + return [] + if not csv_texts: + return [f"no role-runtimes artifact proves {', '.join(sorted(changed))}"] + deployed = deployed_roles(csv_texts) + return [ + f"role {role} changed, but no deploy row ran it" + for role in sorted(changed - deployed) + ] diff --git a/cli/contributing/update/merge/github.py b/cli/contributing/update/merge/github.py new file mode 100644 index 0000000000..b8fba0b6b2 --- /dev/null +++ b/cli/contributing/update/merge/github.py @@ -0,0 +1,137 @@ +"""Read what the merge gate judges from the GitHub REST API through ``gh``.""" + +from __future__ import annotations + +import io +import json +import subprocess +import zipfile +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + Gh = Callable[[Sequence[str]], bytes] + +GH_TIMEOUT_SECONDS = 120 +ROLE_RUNTIMES_PREFIX = "role-runtimes-" +MAX_ARTIFACT_BYTES = 16 * 1024 * 1024 +MAX_CSV_BYTES = 4 * 1024 * 1024 + + +def run_gh(args: Sequence[str]) -> bytes: + return subprocess.run( + ["gh", *args], + capture_output=True, + check=True, + timeout=GH_TIMEOUT_SECONDS, + ).stdout + + +def items(gh: Gh, path: str, jq: str) -> list[dict[str, Any]]: + """Every object a paginated REST list yields through *jq*. + + Args: + gh: runs ``gh`` with the given arguments and returns its stdout. + path: the REST path, query string included. + jq: a filter emitting one JSON object per item. + + Returns: + the objects, across all pages. + """ + out = gh(["api", "--paginate", path, "--jq", jq]).decode("utf-8") + return [json.loads(line) for line in out.splitlines() if line.strip()] + + +def open_pull_requests(gh: Gh, repo: str, sha: str) -> list[dict[str, Any]]: + """The open pull requests whose head commit is *sha*.""" + return [ + pr + for pr in items(gh, f"repos/{repo}/commits/{sha}/pulls?per_page=100", ".[]") + if pr["state"] == "open" and pr["head"]["sha"] == sha + ] + + +def check_runs(gh: Gh, repo: str, sha: str) -> list[dict[str, Any]]: + """The latest check run per name on *sha*.""" + return items( + gh, + f"repos/{repo}/commits/{sha}/check-runs?filter=latest&per_page=100", + ".check_runs[] | {name, status, conclusion, details_url}", + ) + + +def statuses(gh: Gh, repo: str, sha: str) -> list[dict[str, Any]]: + """The latest commit status per context on *sha*.""" + return items( + gh, + f"repos/{repo}/commits/{sha}/status?per_page=100", + ".statuses[] | {context, state}", + ) + + +def changed_paths(gh: Gh, repo: str, number: int) -> list[str]: + """Every path pull request *number* touches, old names of renamed files included.""" + paths: list[str] = [] + for entry in items( + gh, + f"repos/{repo}/pulls/{number}/files?per_page=100", + ".[] | {filename, previous_filename}", + ): + paths.append(entry["filename"]) + if entry["previous_filename"]: + paths.append(entry["previous_filename"]) + return paths + + +def csv_members(blob: bytes) -> list[str]: + """The CSV files inside an artifact zip, read in memory. + + The zip is never extracted to disk, so its member names cannot reach a + path, and a member larger than ``MAX_CSV_BYTES`` is left out. + + Args: + blob: the artifact zip as the REST API serves it. + + Returns: + the text of each ``*.csv`` member. + """ + texts: list[str] = [] + with zipfile.ZipFile(io.BytesIO(blob)) as archive: + for member in archive.infolist(): + if member.is_dir() or not member.filename.endswith(".csv"): + continue + if member.file_size > MAX_CSV_BYTES: + continue + with archive.open(member) as handle: + data = handle.read(MAX_CSV_BYTES + 1) + if len(data) <= MAX_CSV_BYTES: + texts.append(data.decode("utf-8", errors="replace")) + return texts + + +def role_runtime_csvs(gh: Gh, repo: str, run_id: int) -> list[str]: + """The ``role-runtimes-*`` CSVs workflow run *run_id* uploaded. + + Args: + gh: runs ``gh`` with the given arguments and returns its stdout. + repo: ``owner/name``. + run_id: the pull request run whose deploy rows uploaded them. + + Returns: + the text of every CSV in every unexpired ``role-runtimes-*`` artifact + of at most ``MAX_ARTIFACT_BYTES``. + """ + texts: list[str] = [] + for artifact in items( + gh, + f"repos/{repo}/actions/runs/{run_id}/artifacts?per_page=100", + ".artifacts[] | {id, name, expired, size_in_bytes}", + ): + if not artifact["name"].startswith(ROLE_RUNTIMES_PREFIX): + continue + if artifact["expired"] or artifact["size_in_bytes"] > MAX_ARTIFACT_BYTES: + continue + blob = gh(["api", f"repos/{repo}/actions/artifacts/{artifact['id']}/zip"]) + texts.extend(csv_members(blob)) + return texts diff --git a/cli/meta/env/__main__.py b/cli/meta/env/__main__.py index d1abfe9c6f..dfba6f91fe 100644 --- a/cli/meta/env/__main__.py +++ b/cli/meta/env/__main__.py @@ -13,7 +13,7 @@ from utils.env.writer import write_dotenv from . import PROJECT_ROOT as REPO_ROOT -HOST_OWNED_KEY = "INFINITO_DOTENV_HOST_OWNED" # nocheck: dotenv-host-owned-marker Reason: set only by compose.yml inside the runner container; not a configuration key, a .env entry could freeze the host .env +HOST_OWNED_KEY = "INFINITO_DOTENV_HOST_OWNED" # nocheck: dotenv-host-owned-marker Reason: set only by compose.yml inside the runner container and by the act wrapper when it binds the checkout; not a configuration key, a .env entry could freeze the host .env def main(argv: list[str] | None = None) -> int: diff --git a/default.env b/default.env index 9bf1183b89..de48167700 100644 --- a/default.env +++ b/default.env @@ -139,7 +139,7 @@ INFINITO_CI_CHUNK=0 # Rows one deploy chunk holds, overriding the concurrency-times-waves derivation; 0 derives it. INFINITO_CI_CHUNK_SIZE=0 -# Runner slots a deploy chunk may assume are free; with the job timeout it sizes a chunk in cli.meta.ci.slots. +# Runner slots a deploy chunk may assume are free (cli.meta.ci.slots); a set repository variable of this name overrides it in CI. INFINITO_CI_CONCURRENCY=20 # Budget distros.sh spends before skipping the rest; stays under the 350-min step cap, which stays under the 355-min job cap. diff --git a/docs/contributing/artefact/git/pipeline.md b/docs/contributing/artefact/git/pipeline.md index e69ee1385d..865aebd255 100644 --- a/docs/contributing/artefact/git/pipeline.md +++ b/docs/contributing/artefact/git/pipeline.md @@ -32,7 +32,7 @@ The orchestrator runs the following stages in order: ### 1. Fork Prerequisites ⏳ -For fork PRs, CI waits for privileged images built by the `pull_request_target` event before proceeding. For an untrusted fork that build runs from the safe base merge ref **without organization secrets** (only the per-job `GITHUB_TOKEN`); a maintainer-applied `🛡️ Trusted` label switches the build source to the PR head, unlocks the mirror credentials, and skips the wait — see [Trusted fork PRs](#trusted-fork-prs-). +For fork PRs, CI waits for privileged images built by the `pull_request_target` event before proceeding. That build and the mirror producer run only for a fork PR that carries the maintainer-applied `🛡️ Trusted` label; for an untrusted fork the `🛡️ Gate fork trust` job fails instead, and the waiting `pull_request` run fails fast with it. The label also switches the build source to the PR head and skips the wait — see [Trusted fork PRs](#trusted-fork-prs-). ### 2. Security 🛡️ @@ -62,7 +62,7 @@ The `code-quality-gate` requires linting, code tests, and security checks to all [call-images-mirror-missing.yml](../../../../.github/workflows/call-images-mirror-missing.yml) mirrors any missing upstream images in parallel with the DNS tests so later deploy jobs pull from GHCR instead of Docker Hub, MCR, or other external registries. This shields CI from upstream rate limits, geo-blocking, and transient registry outages. -Fork PRs cannot publish mirror packages directly, so their runs wait for the `pull_request_target` mirror producer before continuing. The producer mirrors with the Docker Hub credentials only for trusted PRs ([🛡️ Trusted](#trusted-fork-prs-)); untrusted forks mirror anonymously (no organization secrets). See [mirror.md](../image/mirror.md) for the mirroring architecture and naming convention. +Fork PRs cannot publish mirror packages directly, so their runs wait for the `pull_request_target` mirror producer before continuing. The producer runs only for trusted PRs ([🛡️ Trusted](#trusted-fork-prs-)) and is the only fork-facing job that receives the Docker Hub credentials. It checks the fork tree out with `core.symlinks=false` and refuses any symlink left in it, so the scan reads the tree's own files and nothing outside it. See [mirror.md](../image/mirror.md) for the mirroring architecture and naming convention. GHCR publication uses the workflow `GITHUB_TOKEN`; optional Docker Hub secrets are used only to reduce source-side Docker Hub rate limits while mirroring. See [authentication.md](../../tools/ghcr/authentication.md). @@ -127,6 +127,8 @@ The `test-workspace` stage runs the workspace workflow listed in the `Infrastruc The final `done` job aggregates all deploy, install, and development gates. CI is considered green only when this job succeeds. +A green `done` does not prove a deploy, since a skipped chunk passes it too. For an update PR the green run therefore hands over to [entry-pr-green-update-merge.yml](../../../../.github/workflows/entry-pr-green-update-merge.yml), which merges only when the run's `role-runtimes-*` artifacts list every role the PR changes; see the automatic merge section of [configuration.md](../../tools/github/actions/configuration.md). + ## Concurrency 🔀 - PR pipelines use `cancel-in-progress: true` so only the newest run per PR and event type is active. The group does not always reap a long orchestrator sweep, which then leaves the newer run parked on `pending`; [entry-cancel-superseded.yml](../../../../.github/workflows/entry-cancel-superseded.yml) cancels those leftovers through the API, see [cancel/README.md](../../../../scripts/github/cancel/README.md). @@ -139,7 +141,7 @@ See [configuration.md](../../tools/github/actions/configuration.md) for all repo Fork PRs run under the `pull_request` event without write permissions. Privileged steps (image builds, package writes) run via `pull_request_target`. The fork CI waits for those privileged images before proceeding. See [pull-request.md](pull-request.md) for the contributor-facing fork workflow. -By default — for an **untrusted** fork PR — the privileged `pull_request_target` build checks out the **base merge ref** (`refs/pull//merge`) from the base repository: the PR's changes merged onto base, with all workflow and build-orchestration scripts coming from base, never from the fork. Because `actions/checkout` otherwise refuses to fetch a PR ref under `pull_request_target`, the source checkout sets `allow-unsafe-pr-checkout: true`. The untrusted build runs **without organization secrets** — `secrets: inherit` is not passed and it authenticates to GHCR with the per-job `GITHUB_TOKEN` only, so a malicious fork cannot read repository/organization secrets. (The `pull_request_target` token still carries `packages: write`, so the `🛡️ Trusted` label remains the real trust boundary for anything beyond image publication.) +For an **untrusted** fork PR the privileged `pull_request_target` jobs stop at the `🛡️ Gate fork trust` job: it fails, so neither the image build nor the mirror producer runs fork content next to the `packages: write` token, and the fork's `pull_request` run fails its prerequisite wait as soon as that run ends. The merge-ref expressions in `build-ci-images-fork` stay as a fallback only. Because `actions/checkout` otherwise refuses to fetch a PR ref under `pull_request_target`, the source checkouts set `allow-unsafe-pr-checkout: true`; the lint `tests/lint/repository/test_workflow_fork_checkout_gated.py` fails any `pull_request_target` job with such a checkout that does not need the gate. ### Trusted fork PRs 🔓 @@ -147,12 +149,13 @@ When a maintainer applies the `🛡️ Trusted` label, the fork PR is treated as - The orchestrator's `wait-fork-prereq-run` job **skips the wait** for the privileged fork images. - The privileged `pull_request_target` build switches its **build source** from the base merge ref to the **raw PR head** (`head.repo.full_name` @ `head.sha`). -- The trusted build additionally receives the Docker Hub mirror credentials (passed only when the label is present); untrusted builds mirror anonymously. +- The trusted mirror producer receives the Docker Hub mirror credentials; untrusted fork PRs get no privileged job at all. +- A fork-sourced build imports the shared `buildcache-` registry cache but never exports to it, so only base-sourced builds write the cache every trusted build reads. - The built image **keeps the merge-SHA tag** (`ci-`) so the `pull_request` orchestrator finds it unchanged — no consumer workflow has to know about the label. Security gates: -- The `🛡️ Trusted` label flips the build source to the PR head and unlocks the Docker Hub credentials; without it the safe base merge ref is built with no organization secrets. Restrict who may set the label via repository label permissions / branch protection so only maintainers can grant it. +- The `🛡️ Trusted` label is the only way a fork PR reaches the privileged build and mirror. Restrict who may set the label via repository label permissions / branch protection so only maintainers can grant it. The label stays on the PR across later pushes, so review every new head before CI uses it, or remove the label first. - Build-orchestration scripts (`scripts/image/push.sh` and the helper checkout) always come from the base repo at `github.sha`; only the Docker build **context** (`_src`) is the fork head. `persist-credentials: false` keeps the token out of the source checkout, and `USE_NIX_TOKEN` stays disabled for fork-sourced builds. - Fork `pull_request` runs always receive a read-only token (GitHub-enforced); the label never grants write tokens or secrets to the untrusted event. diff --git a/docs/contributing/tools/github/actions/configuration.md b/docs/contributing/tools/github/actions/configuration.md index 18fd9633bd..9e0f1d2eb5 100644 --- a/docs/contributing/tools/github/actions/configuration.md +++ b/docs/contributing/tools/github/actions/configuration.md @@ -10,7 +10,7 @@ Repository variables are set under **Settings → Secrets and variables → Acti |---|---|---|---| | `CI_SYNC_MAIN_SOURCE_REPOSITORY` | [entry-push-latest.yml](../../../../../.github/workflows/entry-push-latest.yml) | Syncs `main` from `infinito-nexus/core` before CI scope discovery | `/` to use another source, or `false`, empty, or the current repository to skip | | `CI_RUN_ON_MAIN` | [entry-push-latest.yml](../../../../../.github/workflows/entry-push-latest.yml) | Pushes to `main` skip CI | `true` to run CI on `main` pushes too | -| `CI_ENABLE_AUTO_UPDATES` | [cron-update.yml](../../../../../.github/workflows/cron-update.yml), [entry-pr-open-dependabot-close.yml](../../../../../.github/workflows/entry-pr-open-dependabot-close.yml) | Update jobs skipped; Dependabot PRs auto-closed | `true` to allow update PRs (workflow-driven and Dependabot) | +| `CI_ENABLE_AUTO_UPDATES` | [cron-update.yml](../../../../../.github/workflows/cron-update.yml), [entry-pr-open-dependabot-close.yml](../../../../../.github/workflows/entry-pr-open-dependabot-close.yml), [entry-pr-change-dependabot-label.yml](../../../../../.github/workflows/entry-pr-change-dependabot-label.yml), [entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml) | Update jobs skipped; Dependabot PRs auto-closed; no update PR is labelled or merged automatically | `true` to allow update PRs (workflow-driven and Dependabot) and their automatic merge | | `CI_ENABLE_AUTO_TRANSLATIONS` | [entry-pr-translate.yml](../../../../../.github/workflows/entry-pr-translate.yml) | Pull requests against `main` open no translation PRs | `true` to machine-translate the entries a PR leaves empty or fuzzy, one PR per language | | `PLAYWRIGHT_KEEP_ALL` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | Playwright keeps trace, screenshot and video only when a test fails | `true` to keep them for every test (passing runs included); the workflow forwards it as `INFINITO_PLAYWRIGHT_KEEP` | | `API_OPENAI_KEY` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | The gateway publishes no `openai/*` model, and the CLI test asserts their absence | An OpenAI key, to deploy and test the route | @@ -18,6 +18,7 @@ Repository variables are set under **Settings → Secrets and variables → Acti | `API_OPENROUTER_KEY` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | The gateway publishes no `openrouter/auto` model | An OpenRouter key | | `INFINITO_MAIL_PRODUCTION_HOST` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | The read-only production mail assertions are skipped, because the task that runs them is gated on this host being set | The public hostname of a deployed mail server, to assert its MX, SPF, DKIM, DMARC and PTR records and its SMTP greeting after a deploy; nothing is sent and nothing is mutated | | `INFINITO_MAIL_PRODUCTION_RESOLVER` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | Those assertions resolve through the runner's own resolver | A DNS server address, to resolve the records against it instead; ignored while `INFINITO_MAIL_PRODUCTION_HOST` is unset | +| `INFINITO_CI_CONCURRENCY` | [call-validation.yml](../../../../../.github/workflows/call-validation.yml), [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | Deploy chunks are sized from the runner slots [default.env](../../../../../default.env) declares | The jobs the account runs at once, e.g. `500` on GitHub Enterprise; once the derived chunk size exceeds the run's job budget, a sweep needs one chunk (two with a priority line) and only `INFINITO_CI_JOB_LIMIT` bounds it. Both workflows forward it, so the batch count and every chunk's cut agree | ## Provider keys: variable or secret? 🔑 @@ -160,6 +161,19 @@ Dependabot cannot read repository variables itself, so [entry-pr-open-dependabot | `true` | Run ✓ | Stay open ✓ | | any other value | Skipped ✓ | Auto-closed on open ✓ | +The same guard sits on [entry-pr-change-dependabot-label.yml](../../../../../.github/workflows/entry-pr-change-dependabot-label.yml), which labels Dependabot PRs `update` plus `major`, `minor` or `patch`, and on [entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml), which merges an update PR once CI proved it. With the variable unset, neither labels nor merges anything. + +### Automatic merge 🔀 + +An update PR merges itself only when all of these hold; otherwise the job prints the failing condition and the PR waits for a manual merge: + +1. Its `🔀 Pull Request` run of the `pull_request` event concluded `success`. +2. `infinito-nexus-updater[bot]` opened it from `update/*`, or `dependabot[bot]` from `dependabot/*`, in this repository, against the default branch, not as a draft, and it carries the `update` label. +3. Every latest check run on its head commit completed as `success`, `skipped` or `neutral`, and every commit status is `success`. A check still running counts as not green; no later run retries the merge. +4. Every role under `roles//` the PR changes appears in the `role` column of a `role-runtimes-*` artifact of that run. A PR that changes no role needs no artifact; a missing artifact proves nothing. + +The merge goes through `PUT /repos/{owner}/{repo}/pulls/{number}/merge` with `merge_method=merge` and the tested head `sha`, so a commit pushed after the run makes it fail instead of merging untested code. `gh pr merge` is not used because it refuses a PR the ruleset still blocks before the server can apply the App's bypass. The App MUST be a bypass actor of the `Main` ruleset in `pull_request` mode; without that the merge step fails and the PR stays open. + ## `INFINITO_PLAYWRIGHT_KEEP` 🎬 Controls whether Playwright keeps trace, screenshot, and video for every test or only for failing tests in the deploy-test workflow ([call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml)). diff --git a/docs/contributing/tools/github/actions/secrets.md b/docs/contributing/tools/github/actions/secrets.md index 25a0d0398a..816df5a001 100644 --- a/docs/contributing/tools/github/actions/secrets.md +++ b/docs/contributing/tools/github/actions/secrets.md @@ -8,8 +8,8 @@ Repository secrets MUST be set under **Settings → Secrets and variables → Ac | Secret | Workflow | Purpose | Required when | |---|---|---|---| -| `BOT_APP_CLIENT_ID` | [cron-update.yml](../../../../../.github/workflows/cron-update.yml) | GitHub App Client ID (OAuth-style `Iv…` identifier shown on the App's General page) used to mint a short-lived installation token for the update PR. | `CI_ENABLE_AUTO_UPDATES == 'true'` | -| `BOT_APP_PRIVATE_KEY` | [cron-update.yml](../../../../../.github/workflows/cron-update.yml) | PEM-encoded private key of the same GitHub App. Used to sign the JWT that exchanges for the installation token. | `CI_ENABLE_AUTO_UPDATES == 'true'` | +| `BOT_APP_CLIENT_ID` | [cron-update.yml](../../../../../.github/workflows/cron-update.yml), [entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml) | GitHub App Client ID (OAuth-style `Iv…` identifier shown on the App's General page) used to mint a short-lived installation token for the update PR and for its automatic merge. | `CI_ENABLE_AUTO_UPDATES == 'true'` | +| `BOT_APP_PRIVATE_KEY` | [cron-update.yml](../../../../../.github/workflows/cron-update.yml), [entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml) | PEM-encoded private key of the same GitHub App. Used to sign the JWT that exchanges for the installation token. | `CI_ENABLE_AUTO_UPDATES == 'true'` | | `API_OPENAI_KEY` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | Publishes the `openai/*` models on the LiteLLM gateway and lets the CLI test exercise the route. | Never. Unset leaves the route unpublished. | | `API_ANTHROPIC_KEY` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | Publishes the `anthropic/*` models. | Never. | | `API_OPENROUTER_KEY` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | Publishes `openrouter/auto`. | Never. | @@ -99,6 +99,8 @@ A classic personal access token MAY be used as a fallback for unrelated automati Each PR-opening job in [cron-update.yml](../../../../../.github/workflows/cron-update.yml) runs an `actions/create-github-app-token@v2` step gated on `steps.diff.outputs.changed == 'true'`, then forwards the minted token as `GH_TOKEN` and the resolved `APP_SLUG` to the subsequent PR step. The job's `permissions:` block keeps the workflow-provided `GITHUB_TOKEN` read-only; write access is provided exclusively by the App token, scoped to the App's repository permissions. +[entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml) mints the App token only after its merge gate passed, and uses it for the merge call alone; the gate itself reads with the read-only `GITHUB_TOKEN`. Merging needs the App's `Contents` and `Pull requests` write permissions plus a bypass of the `Main` ruleset; a PR that changes `.github/workflows/` additionally needs `Workflows`: **Read and write**, or its merge fails and it stays open. + ### Commit identity propagation 🪪 [pr.sh](../../../../../scripts/github/update/open/pr.sh) reads `APP_SLUG` from the environment and resolves the App's bot user via `gh api /users/[bot]`. The resolved login and numeric user ID are written into `git config user.name` and `git config user.email` in the `+[bot]@users.noreply.github.com` form that GitHub accepts for verified commits. When `APP_SLUG` is unset, the script falls back to the `github-actions[bot]` identity. That branch is reached only when the script is invoked outside the workflow, for example a local smoke test where the caller has set `GH_TOKEN` to something other than an App token. diff --git a/docs/contributing/tools/github/actions/workflows.md b/docs/contributing/tools/github/actions/workflows.md index 5a826a3a23..d3063aa350 100644 --- a/docs/contributing/tools/github/actions/workflows.md +++ b/docs/contributing/tools/github/actions/workflows.md @@ -86,6 +86,8 @@ Trigger column legend: **auto** = fires automatically (push, pull_request, sched | [cron-update.yml](../../../../../.github/workflows/cron-update.yml): `🔄 Update versions` | Updates Docker image versions and other pinned dependencies; opens an update PR via a GitHub App installation token so PR-lifecycle events fire on the resulting PR. Both jobs are gated behind the `CI_ENABLE_AUTO_UPDATES` repository variable, see [configuration.md](configuration.md). Requires the `BOT_APP_CLIENT_ID` and `BOT_APP_PRIVATE_KEY` repository secrets, see [secrets.md](secrets.md). | auto (`push` to `main`, `schedule`: daily 00:30 UTC), manual | none | | [entry-pr-translate.yml](../../../../../.github/workflows/entry-pr-translate.yml): `🌐 Translate catalogs` | Merges the source strings of the `core` and `docs` domains into `locale/`, then machine-translates what a pull request leaves empty or fuzzy, one runner per language LibreTranslate supports. Each runner opens its own PR against the head branch of the triggering PR. Gated behind the `CI_ENABLE_AUTO_TRANSLATIONS` repository variable, see [configuration.md](configuration.md); pull requests from a fork are skipped. Requires the `BOT_APP_CLIENT_ID` and `BOT_APP_PRIVATE_KEY` repository secrets, see [secrets.md](secrets.md). | auto (`pull_request` against `main`: opened, synchronize, reopened) | none | | [entry-pr-open-dependabot-close.yml](../../../../../.github/workflows/entry-pr-open-dependabot-close.yml): `🚫 Dependabot: Close while auto-updates disabled` | Auto-closes Dependabot PRs while `CI_ENABLE_AUTO_UPDATES` is not set to `true`, so Dependabot honours the same gate as the workflow-driven update jobs. See [configuration.md](configuration.md). | auto (`pull_request_target`: opened, reopened) | none | +| [entry-pr-change-dependabot-label.yml](../../../../../.github/workflows/entry-pr-change-dependabot-label.yml): `🔄 Dependabot: Label update level` | Labels every Dependabot PR `update` plus exactly one of `major`, `minor` and `patch`, read from the `update-type` of `dependabot/fetch-metadata`; a type that names no semver level counts as `major`. Creates a missing label, adds only labels the PR lacks and checks out the base branch only. Gated behind `CI_ENABLE_AUTO_UPDATES`, see [configuration.md](configuration.md). | auto (`pull_request_target`: opened, reopened, synchronize) | none | +| [entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml): `🔄 Update: Merge proven PRs` | Runs when a `🔀 Pull Request` run of the `pull_request` event succeeds on an `update/*` or `dependabot/*` branch. [cli.contributing.update.merge](../../../../../cli/contributing/update/merge/__main__.py) merges the PR only when the `infinito-nexus-updater[bot]` App or `dependabot[bot]` opened it, it carries `update`, every check run and commit status on its head is green, and the run's `role-runtimes-*` artifacts list every role the PR changes. Otherwise it prints why and the PR stays open for a manual merge. The merge pins the tested head and uses the App token, so the App MUST be a bypass actor of the `Main` ruleset. Gated behind `CI_ENABLE_AUTO_UPDATES`, see [configuration.md](configuration.md); requires the `BOT_APP_CLIENT_ID` and `BOT_APP_PRIVATE_KEY` repository secrets, see [secrets.md](secrets.md). | auto (`workflow_run` of `🔀 Pull Request`: completed) | none | ## Changing workflows ✍️ diff --git a/group_vars/all/04_webserver.yml b/group_vars/all/04_webserver.yml index a5e31a48d9..c31c81bec9 100644 --- a/group_vars/all/04_webserver.yml +++ b/group_vars/all/04_webserver.yml @@ -24,6 +24,9 @@ WEBSERVER_PROXY_WORKER_CONNECTIONS: "{{ lookup('config', 'svc-prx-openresty', 's WEBSERVER_PROXY_WORKER_RLIMIT_NOFILE: "{{ (WEBSERVER_PROXY_WORKER_CONNECTIONS | int) * 2 }}" +# HTTP/2 on every TLS vhost. Off because OpenResty 1.31.8.x bundles nginx 1.31.8, which CVE-2026-123007 and CVE-2026-123633 hit only with HTTP/2 on; set true once OpenResty ships nginx >= 1.31.9. +WEBSERVER_HTTP2_ENABLED: false + # Response security headers of every vhost; an app overrides any key under `security_headers` in its meta/server.yml. WEBSERVER_SECURITY_HEADERS: nosniff: false # X-Content-Type-Options: nosniff diff --git a/roles/dsk-gnt-claude/meta/services.yml b/roles/dsk-gnt-claude/meta/services.yml index 595bfb9f96..03be74f17d 100644 --- a/roles/dsk-gnt-claude/meta/services.yml +++ b/roles/dsk-gnt-claude/meta/services.yml @@ -9,7 +9,7 @@ claude: host: enabled: true lifecycle: alpha - npm_version: 2.1.327 + npm_version: 2.1.330 update: key: npm_version type: npm diff --git a/roles/dsk-gnt-codex/meta/services.yml b/roles/dsk-gnt-codex/meta/services.yml index 4badeb9453..ccefe60850 100644 --- a/roles/dsk-gnt-codex/meta/services.yml +++ b/roles/dsk-gnt-codex/meta/services.yml @@ -9,7 +9,7 @@ codex: host: enabled: true lifecycle: alpha - npm_version: 0.170.0 + npm_version: 0.171.0 update: key: npm_version type: npm diff --git a/roles/dsk-gnt-pi/meta/services.yml b/roles/dsk-gnt-pi/meta/services.yml index 739567b37b..77f36b0fb1 100644 --- a/roles/dsk-gnt-pi/meta/services.yml +++ b/roles/dsk-gnt-pi/meta/services.yml @@ -9,7 +9,7 @@ pi: host: enabled: true lifecycle: alpha - npm_version: 1.5.2 + npm_version: 1.6.0 update: key: npm_version type: npm diff --git a/roles/svc-ai-ltengine/meta/services.yml b/roles/svc-ai-ltengine/meta/services.yml index 9b8091c72a..b2e2662f64 100644 --- a/roles/svc-ai-ltengine/meta/services.yml +++ b/roles/svc-ai-ltengine/meta/services.yml @@ -36,7 +36,7 @@ ltengine: custom: true gpu: true repository: https://github.com/LibreTranslate/LTEngine - ref: 3fa19f8b6d3eecbacbdbf79406e0f877ebe11e26 + ref: v0.1.1 # nocheck: min-storage-headroom Reason: the CUDA runtime base the binary is built on, plus the GGUF weights the server downloads into its models volume on first start min_storage: 5GB model: gemma3-1b diff --git a/roles/svc-ai-mcp-adapter/README.md b/roles/svc-ai-mcp-adapter/README.md index fa2eda928f..789559fb58 100644 --- a/roles/svc-ai-mcp-adapter/README.md +++ b/roles/svc-ai-mcp-adapter/README.md @@ -47,6 +47,8 @@ The deployment renders one `ADAPTER_CONTRACT` JSON document per instance: `files/python/policy.py` validates it at startup. A contract missing a limit, carrying an empty allowlist, naming a wildcard path or lacking a pinned schema hash is refused before the process serves anything. +An optional `upstream_host` is sent as the `Host` header of every upstream request, for a provider that answers only its canonical domain; without it the request carries the host of `upstream_url`. + ## Endpoints | Path | Method | Purpose | diff --git a/roles/svc-ai-mcp-adapter/files/python/policy.py b/roles/svc-ai-mcp-adapter/files/python/policy.py index b527da2b6c..d9f606be43 100644 --- a/roles/svc-ai-mcp-adapter/files/python/policy.py +++ b/roles/svc-ai-mcp-adapter/files/python/policy.py @@ -63,6 +63,8 @@ DURATION_UNITS = { READ_METHODS = frozenset({"GET", "HEAD"}) +HOST_PATTERN = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?(?::[0-9]{1,5})?") + class ContractError(ValueError): """The rendered contract is not one this adapter may serve.""" @@ -92,6 +94,30 @@ def upstream_url(base: str, path_key: str = "", path_suffix: str = "") -> str: return "/".join(parts) +def upstream_host(contract: Mapping[str, Any]) -> str: + """ + Args: + contract: the loaded contract. + + Returns: + ``upstream_host`` as declared, or "" when the contract declares none + and the request keeps the host of ``upstream_url``. + + Raises: + ContractError: ``upstream_host`` is declared but is not a host name, + optionally followed by a port. + """ + host = contract.get("upstream_host") + if host is None: + return "" + if not isinstance(host, str) or not HOST_PATTERN.fullmatch(host): + raise ContractError( + f"contract upstream_host {host!r} must be a host name, " + f"optionally followed by a port" + ) + return host + + def load_contract(raw: str) -> dict[str, Any]: """Return the validated adapter contract. @@ -146,6 +172,8 @@ def load_contract(raw: str) -> dict[str, Any]: if not str(contract.get("schema_sha256") or "").startswith(SHA256_PREFIX): raise ContractError("contract must pin tools.schema_sha256") + upstream_host(contract) + return contract @@ -363,6 +391,23 @@ def authorize_call( return method, str(spec["path"]) +def request_length(header: str | None) -> int: + """ + Args: + header: the raw ``Content-Length`` value, ``None`` when the client sent + none. + + Returns: + the announced body size in bytes; ``0`` without a header, since RFC 9112 + reads such a request as bodiless; a negative number when the value is + negative or no integer. + """ + try: + return int(header or 0) + except ValueError: + return -1 + + def clamp_page(contract: Mapping[str, Any], requested: Any) -> int: """Return a page size no larger than the contract allows. diff --git a/roles/svc-ai-mcp-adapter/files/python/server.py b/roles/svc-ai-mcp-adapter/files/python/server.py index b3b1d01468..420070bd88 100644 --- a/roles/svc-ai-mcp-adapter/files/python/server.py +++ b/roles/svc-ai-mcp-adapter/files/python/server.py @@ -61,6 +61,7 @@ UPSTREAM_URL = policy.upstream_url( os.environ.get("ADAPTER_UPSTREAM_PATH_KEY", ""), os.environ.get("ADAPTER_UPSTREAM_PATH_SUFFIX", ""), ) +UPSTREAM_HOST = policy.upstream_host(CONTRACT) PORT = int(os.environ["ADAPTER_PORT"]) policy.assert_no_drift(CONTRACT) @@ -82,6 +83,30 @@ def log(event): sys.stdout.flush() +def upstream_headers(): + """ + Returns: + ``Host`` when the contract declares ``upstream_host``, then the + credential header when ``ADAPTER_UPSTREAM_KEY`` is set, in that order. + """ + headers = {} + if UPSTREAM_HOST: + headers["Host"] = UPSTREAM_HOST + if UPSTREAM_KEY: + headers[UPSTREAM_AUTH_HEADER] = UPSTREAM_AUTH_FORMAT.format(key=UPSTREAM_KEY) + return headers + + +def add_upstream_headers(request): + """ + Args: + request: the ``urllib.request.Request`` that receives + :func:`upstream_headers`. + """ + for name, value in upstream_headers().items(): + request.add_header(name, value) + + def call_upstream(method, path, arguments): """Return the upstream response body for one authorised tool call. @@ -107,10 +132,7 @@ def call_upstream(method, path, arguments): f"{UPSTREAM_URL}{resolved}", method=method ) request.add_header("Accept", "application/json") - if UPSTREAM_KEY: - request.add_header( - UPSTREAM_AUTH_HEADER, UPSTREAM_AUTH_FORMAT.format(key=UPSTREAM_KEY) - ) + add_upstream_headers(request) with OPENER.open( request, timeout=CONTRACT["limits"]["timeout_seconds"] @@ -147,10 +169,7 @@ def post_upstream(envelope): request.add_header("MCP-Protocol-Version", PROTOCOL_VERSION) if UPSTREAM_SESSION["id"]: request.add_header(SESSION_HEADER, UPSTREAM_SESSION["id"]) - if UPSTREAM_KEY: - request.add_header( - UPSTREAM_AUTH_HEADER, UPSTREAM_AUTH_FORMAT.format(key=UPSTREAM_KEY) - ) + add_upstream_headers(request) with OPENER.open( request, timeout=CONTRACT["limits"]["timeout_seconds"] @@ -174,14 +193,9 @@ def sse_session(): adapter rather than being reopened per call. """ if SSE["session"] is None: - headers = {} - if UPSTREAM_KEY: - headers[UPSTREAM_AUTH_HEADER] = UPSTREAM_AUTH_FORMAT.format( - key=UPSTREAM_KEY - ) SSE["session"] = sse.SseSession( UPSTREAM_URL, - headers=headers, + headers=upstream_headers(), timeout=CONTRACT["limits"]["timeout_seconds"], ).open() return SSE["session"] @@ -399,7 +413,10 @@ class Handler(BaseHTTPRequestHandler): self._respond(401, {"error": policy.DENY_UNAUTHENTICATED}) return - length = int(self.headers.get("Content-Length") or 0) + length = policy.request_length(self.headers.get("Content-Length")) + if length < 0: + self._respond(400, {"error": "invalid_content_length"}) + return if length > CONTRACT["limits"]["request_bytes"]: self._respond(413, {"error": policy.DENY_REQUEST_TOO_LARGE}) return diff --git a/roles/svc-cache-package/meta/services.yml b/roles/svc-cache-package/meta/services.yml index a0dc4ed913..ea71b5814f 100644 --- a/roles/svc-cache-package/meta/services.yml +++ b/roles/svc-cache-package/meta/services.yml @@ -20,7 +20,7 @@ package: shared: true bond: 1 image: sonatype/nexus3 - version: 3.98.2-ubi + version: 3.98.3-ubi name: package-cache # nocheck: min-storage-headroom Reason: the image transfers 0.373 GiB, but the service is the blobstore itself and fills up to blobstore_max (40g); sizing the host to the image alone would let the deploy prune a cache it has no room to refill min_storage: 4GB diff --git a/roles/svc-cache-package/templates/upstreams.conf.j2 b/roles/svc-cache-package/templates/upstreams.conf.j2 index 1e8127131a..0328b9045e 100644 --- a/roles/svc-cache-package/templates/upstreams.conf.j2 +++ b/roles/svc-cache-package/templates/upstreams.conf.j2 @@ -27,6 +27,9 @@ server { listen {{ listener.port }}{{ ' ssl' if listener.tls else '' }}; server_name {{ host.host }}; {% if listener.tls %} +{% if WEBSERVER_HTTP2_ENABLED | string | lower in ['true', 'yes', 'on', '1'] %} + http2 on; +{% endif %} ssl_certificate {{ CACHE_PACKAGE_CERTS_DIR }}/{{ host.host }}.crt; ssl_certificate_key {{ CACHE_PACKAGE_CERTS_DIR }}/{{ host.host }}.key; {% set repo = CACHE_PACKAGE_REPOS[host.repo] %} diff --git a/roles/svc-runner/meta/services.yml b/roles/svc-runner/meta/services.yml index 8fd11aec9d..43330b4c93 100644 --- a/roles/svc-runner/meta/services.yml +++ b/roles/svc-runner/meta/services.yml @@ -29,7 +29,7 @@ buildkit: enabled: false shared: false image: moby/buildkit - version: "v0.35.0" + version: "v0.35.1" # nocheck: dynamic-flag act-runner: enabled: false diff --git a/roles/sys-ctl-hlth-runtime/README.md b/roles/sys-ctl-hlth-runtime/README.md index 6b8c6a393f..b8c0a520c8 100644 --- a/roles/sys-ctl-hlth-runtime/README.md +++ b/roles/sys-ctl-hlth-runtime/README.md @@ -39,6 +39,7 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( - **Metrics:** While `web-app-prometheus` is deployed, the check replaces `infinito_hlth_runtime.prom` in `DIR_METRICS_TEXTFILE` atomically with the gauges `infinito_hlth_runtime_findings{target,kind,image,severity,scanner,verdict}`, `infinito_hlth_runtime_last_run_timestamp_seconds`, `infinito_hlth_runtime_last_run_success` and `infinito_hlth_runtime_scanner_errors{scanner}`. No series carries a CVE id. - **Suppressions:** A role accepts findings for its own containers under `.security.suppressions` of its `meta/services.yml`, each entry `id` (one CVE) or `image_tag` (every finding of the image while it runs that tag, which MUST equal the service's `version`) plus `until` below a `# nocheck: cve ` marker, see [suppression.md](../../docs/contributing/actions/testing/suppression.md). Host suppressions are the `id` entries under the engine entries of this role and cover that engine's host findings; an `image_tag` entry there covers the engine's own image. - **Databases:** With `db_update` the engines refresh their databases under `database_dir` before each run, three attempts 30 s apart; without it the databases MUST already be there, and a missing one fails the run. SBOMs of running images are cached under `cache_dir` by image id. +- **Run bound:** Every engine run ends after `JOB_TIMEOUT_SECONDS` of [script.py](./files/python/script.py), 4 h, and then fails the check. Trivy gets the same bound as its `--timeout`, because its own default of 5 minutes failed the scan of the 4.5 GB `local_discourse/discourse` image on a busy swarm node with `context deadline exceeded`. - **Scratch:** Every engine run gets its own temporary directory in the run's work directory under `cache_dir`, removed as soon as the run ends, also when the engine fails, times out or crashes. Engine runs that export an image take turns, whatever `workers` is: each holds a lock on `database_dir` from creating its scratch directory until it has removed it, and on a timeout or crash also its container. The lock spans every scan that reads the same `database_dir`, so the swarm lab nodes and the local stacks of every worktree, which all share the host directory `INFINITO_VULNERABILITY_DB_HOST_PATH` of `default.env`, take turns on their one host disk. The other engine runs keep running in parallel. A run killed mid-scan leaves its work directory to the next run, which removes it first. - **Deploy-time run:** The deploy runs the check once at its end and fails on its first failure, without the retries `sys-service-terminator` gives other units. - **Development and CI deploys:** A CI row pins one engine and restores its databases; a local deploy draws one engine and refreshes the shared host directory `INFINITO_VULNERABILITY_DB_HOST_PATH`. Both run it behind Syft plus the Grype runtime pass and read the databases read-only at `INFINITO_VULNERABILITY_DB_DIR`. Production hosts run every engine. diff --git a/roles/sys-ctl-hlth-runtime/files/python/script.py b/roles/sys-ctl-hlth-runtime/files/python/script.py index 27761cdd63..0be60119ab 100755 --- a/roles/sys-ctl-hlth-runtime/files/python/script.py +++ b/roles/sys-ctl-hlth-runtime/files/python/script.py @@ -1255,6 +1255,8 @@ ENGINE_ENV = { TRIVY_COMMON = ( "--cache-dir", CACHE, + "--timeout", + f"{JOB_TIMEOUT_SECONDS}s", "--disable-telemetry", "--skip-version-check", "--quiet", diff --git a/roles/sys-front-tls/templates/nginx_ssl_header.j2 b/roles/sys-front-tls/templates/nginx_ssl_header.j2 index 54c1c8079d..4d70c4970e 100644 --- a/roles/sys-front-tls/templates/nginx_ssl_header.j2 +++ b/roles/sys-front-tls/templates/nginx_ssl_header.j2 @@ -1,7 +1,9 @@ {% if lookup('tls', domain, 'enabled') | bool %} listen {{ lookup('tls', domain, 'ports.web') }} ssl; listen [::]:{{ lookup('tls', domain, 'ports.web') }} ssl; +{% if WEBSERVER_HTTP2_ENABLED | bool %} http2 on; +{% endif %} ssl_protocols TLSv1.2 TLSv1.3; ssl_ecdh_curve X25519:P-256; diff --git a/roles/web-app-bluesky/meta/services.yml b/roles/web-app-bluesky/meta/services.yml index 26509e77ea..d139646c4a 100644 --- a/roles/web-app-bluesky/meta/services.yml +++ b/roles/web-app-bluesky/meta/services.yml @@ -65,7 +65,7 @@ view: domains: - view repository: https://github.com/bluesky-social/social-app.git - ref: "1.137.0" + ref: "1.138.0" ports: local: http: 8051 diff --git a/roles/web-app-bridgy-fed/meta/services.yml b/roles/web-app-bridgy-fed/meta/services.yml index 240605b6fb..52ce0a8acc 100644 --- a/roles/web-app-bridgy-fed/meta/services.yml +++ b/roles/web-app-bridgy-fed/meta/services.yml @@ -53,7 +53,7 @@ bridgy-fed: version: 3.14-slim name: web-app-bridgy-fed repository: https://github.com/snarfed/bridgy-fed.git - ref: e0345507a58c34c1eca4b3906935b4bbca89196a + ref: 9dc7d38c5597e37162b1774816e0c4715a199adc ports: local: http: 8053 diff --git a/roles/web-app-discourse/meta/addons/discourse-activity-pub.yml b/roles/web-app-discourse/meta/addons/discourse-activity-pub.yml index 5e0c01dc53..4b562f4960 100644 --- a/roles/web-app-discourse/meta/addons/discourse-activity-pub.yml +++ b/roles/web-app-discourse/meta/addons/discourse-activity-pub.yml @@ -12,4 +12,4 @@ update: upstream_id: discourse-activity-pub config: repository: https://github.com/discourse/discourse-activity-pub.git - ref: d89d1b0131bbce4dc4102b1409f797be39b41961 + ref: bc08202aa94cdb74159c0aec1e3d2c47b88a8f66 diff --git a/roles/web-app-discourse/meta/services.yml b/roles/web-app-discourse/meta/services.yml index a8e3fc787e..2841f67f2f 100644 --- a/roles/web-app-discourse/meta/services.yml +++ b/roles/web-app-discourse/meta/services.yml @@ -66,12 +66,12 @@ discourse: shared: true enabled: true # nocheck: dynamic-flag name: discourse - ref: 0ba1841d589e77df3bc923774abca2720a320ec2 + ref: 93c8e629ea2b0960a4261b69a405e7d10f61a1ea min_storage: 15GB repository: https://github.com/discourse/discourse_docker.git application: repository: https://github.com/discourse/discourse.git - ref: v2026.10.1 + ref: v2026.10.2 ports: local: http: 8020 diff --git a/roles/web-app-erpnext/files/playwright/test-design.js b/roles/web-app-erpnext/files/playwright/test-design.js index 118746f294..2c6ff66efb 100644 --- a/roles/web-app-erpnext/files/playwright/test-design.js +++ b/roles/web-app-erpnext/files/playwright/test-design.js @@ -33,7 +33,7 @@ const LOGIN_ERROR = `${LOGIN_SECTION} .login-error-banner`; const LOGIN_ERROR_ICON = `${LOGIN_ERROR} > svg`; const LOGIN_ERROR_TITLE = `${LOGIN_ERROR} .es-alert__title`; const FOLDER_TILE = ".desktop-container .folder-icon"; -const ACTIVE_FILTER = ".btn.filter-button.btn-primary-light"; +const ACTIVE_FILTER = ".es-button.filter-button:has(> .filter-label:not(.hidden))"; const PAGE_HEAD = ".page-head"; const PAGE_TITLE = ".page-head .es-breadcrumbs li:last-child .es-breadcrumbs__item"; const SIDEBAR = ".body-sidebar"; diff --git a/roles/web-app-erpnext/files/python/apply/email_account.py b/roles/web-app-erpnext/files/python/apply/email_account.py index f97769cb2d..846e62ee30 100644 --- a/roles/web-app-erpnext/files/python/apply/email_account.py +++ b/roles/web-app-erpnext/files/python/apply/email_account.py @@ -1,5 +1,3 @@ -# nocheck: mirrored-unit-test - imports frappe at module level and runs inside `bench -# execute`; the framework is not installable outside the ERPNext image import os import frappe @@ -9,6 +7,9 @@ MAIL_FROM_NAME = os.environ["MAIL_FROM_NAME"] MAIL_FROM_ADDRESS = os.environ["MAIL_FROM_ADDRESS"] SMTP_HOST = os.environ["SMTP_HOST"] SMTP_PORT = int(os.environ["SMTP_PORT"]) +SMTP_TLS = os.environ["SMTP_TLS"] == "true" +SMTP_START_TLS = os.environ["SMTP_START_TLS"] == "true" +SMTP_AUTH = os.environ["SMTP_AUTH"] == "true" SMTP_USER = os.environ["SMTP_USER"] SMTP_PASS = os.environ["SMTP_PASS"] @@ -27,7 +28,8 @@ def upsert_outbound_account(): ea.enable_incoming = 0 ea.smtp_server = SMTP_HOST ea.smtp_port = SMTP_PORT - ea.use_tls = 1 + ea.use_ssl_for_outgoing = int(SMTP_TLS and not SMTP_START_TLS) + ea.use_tls = int(SMTP_TLS and SMTP_START_TLS) ea.login_id_is_different = 1 ea.login_id = SMTP_USER ea.password = SMTP_PASS @@ -35,7 +37,7 @@ def upsert_outbound_account(): ea.flags.ignore_permissions = True ea.flags.ignore_validate = True ea.flags.no_check_in_db = True - ea.no_smtp_authentication = 0 + ea.no_smtp_authentication = int(not SMTP_AUTH) ea.flags.ignore_links = True ea.flags.ignore_mandatory = True try: diff --git a/roles/web-app-erpnext/files/theme.css b/roles/web-app-erpnext/files/theme.css index be7d96e37d..0b63eb04c2 100644 --- a/roles/web-app-erpnext/files/theme.css +++ b/roles/web-app-erpnext/files/theme.css @@ -265,6 +265,22 @@ html .es-button[data-theme="red"] { --bt-disabled-border: var(--design-border); } +html .es-alert[data-theme="red"]:not([data-variant="outline"]) { + background: var(--design-danger-subtle); +} + +html .es-alert[data-theme="yellow"]:not([data-variant="outline"]) { + background: var(--design-warning-subtle); +} + +html .es-alert[data-theme="blue"]:not([data-variant="outline"]) { + background: var(--design-info-subtle); +} + +html .es-alert[data-theme="green"]:not([data-variant="outline"]) { + background: var(--design-success-subtle); +} + html .body-sidebar .standard-sidebar-item:not(.active-sidebar):has(a:not(.section-break)):hover { background-color: var(--design-surface-hover); } @@ -287,6 +303,10 @@ html .btn.btn-primary-light:hover { color: var(--design-text); } +html .es-button.filter-button:has(> .filter-label:not(.hidden)) { + --bt-fill-bg: var(--design-surface-active); +} + html .btn.btn-danger { background-color: var(--design-danger); color: var(--design-on-danger); diff --git a/roles/web-app-erpnext/tasks/addons/email_account.yml b/roles/web-app-erpnext/tasks/addons/email_account.yml index 5b7b64db86..91eb8cc1fe 100644 --- a/roles/web-app-erpnext/tasks/addons/email_account.yml +++ b/roles/web-app-erpnext/tasks/addons/email_account.yml @@ -5,7 +5,7 @@ cmd: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node container exec -i -e SITE_NAME -e MAIL_FROM_NAME -e MAIL_FROM_ADDRESS - -e SMTP_HOST -e SMTP_PORT -e SMTP_USER -e SMTP_PASS + -e SMTP_HOST -e SMTP_PORT -e SMTP_TLS -e SMTP_START_TLS -e SMTP_AUTH -e SMTP_USER -e SMTP_PASS {{ ERPNEXT_BACKEND_LOCAL_CID | quote }} {{ ERPNEXT_BENCH_PYTHON }} stdin: "{{ lookup('ansible.builtin.file', role_path ~ '/files/python/apply/email_account.py') }}" @@ -16,6 +16,9 @@ MAIL_FROM_ADDRESS: "{{ ERPNEXT_MAIL.username | default('') }}" SMTP_HOST: "{{ ERPNEXT_MAIL.host | default('') }}" SMTP_PORT: "{{ ERPNEXT_MAIL.port | default(587) }}" + SMTP_TLS: "{{ ERPNEXT_MAIL.tls | bool | string | lower }}" + SMTP_START_TLS: "{{ ERPNEXT_MAIL.start_tls | bool | string | lower }}" + SMTP_AUTH: "{{ ERPNEXT_MAIL.auth | bool | string | lower }}" SMTP_USER: "{{ ERPNEXT_MAIL.username | default('') }}" SMTP_PASS: "{{ ERPNEXT_MAIL.password | default('') }}" when: ERPNEXT_MAIL.host is defined and (ERPNEXT_MAIL.host | length > 0) diff --git a/roles/web-app-espocrm/meta/services.yml b/roles/web-app-espocrm/meta/services.yml index 60f35be54e..f8ee319dad 100644 --- a/roles/web-app-espocrm/meta/services.yml +++ b/roles/web-app-espocrm/meta/services.yml @@ -38,7 +38,7 @@ espocrm: swarm: enabled: true image: espocrm/espocrm - version: "10.1.3" + version: "10.1.4" custom: true name: espocrm min_storage: 470MB diff --git a/roles/web-app-funkwhale/meta/services.yml b/roles/web-app-funkwhale/meta/services.yml index 739cbafa41..7b1d2bae45 100644 --- a/roles/web-app-funkwhale/meta/services.yml +++ b/roles/web-app-funkwhale/meta/services.yml @@ -13,7 +13,7 @@ funkwhale: # nocheck: default-placement-manager embedded typesense index; node-local in swarm placement: manager image: funkwhale/front - version: 2.0.15 + version: 2.0.16 min_storage: 224MB ports: internal: @@ -43,7 +43,7 @@ api: name: funkwhale-api image: funkwhale/api ca_client: true - version: 2.0.15 + version: 2.0.16 min_storage: 588MB ports: internal: diff --git a/roles/web-app-gitlab/meta/services.yml b/roles/web-app-gitlab/meta/services.yml index f567d0da3a..cf4fc8fa72 100644 --- a/roles/web-app-gitlab/meta/services.yml +++ b/roles/web-app-gitlab/meta/services.yml @@ -78,7 +78,7 @@ webservice: backup: stop_required: false image: registry.gitlab.com/gitlab-org/build/cng/gitlab-webservice-ce - version: v19.5.6 + version: v19.6.1 name: gitlab-webservice healthcheck: test: ["CMD", "/scripts/healthcheck"] @@ -99,7 +99,7 @@ sidekiq: flavor: tcp path: liveness image: registry.gitlab.com/gitlab-org/build/cng/gitlab-sidekiq-ce - version: v19.5.6 + version: v19.6.1 name: gitlab-sidekiq cpus: "1.0" mem_reservation: 2g @@ -112,7 +112,7 @@ workhorse: backup: stop_required: false image: registry.gitlab.com/gitlab-org/build/cng/gitlab-workhorse-ce - version: v19.5.6 + version: v19.6.1 name: gitlab-workhorse healthcheck: test: ["CMD", "/scripts/healthcheck"] @@ -128,7 +128,7 @@ gitaly: # nocheck: default-placement-manager the repositories live on a node-local volume (meta/volumes.yml nfs: false, gitaly does not support NFS), which a reschedule leaves behind on the old node placement: manager image: registry.gitlab.com/gitlab-org/build/cng/gitaly - version: v19.5.6 + version: v19.6.1 healthcheck: test: ["CMD", "/scripts/healthcheck"] name: gitlab-gitaly @@ -143,7 +143,7 @@ shell: backup: stop_required: false image: registry.gitlab.com/gitlab-org/build/cng/gitlab-shell - version: v19.5.6 + version: v19.6.1 name: gitlab-shell ports: internal: @@ -158,7 +158,7 @@ migrations: # nocheck: single-replica replicas: 1 image: registry.gitlab.com/gitlab-org/build/cng/gitlab-rails-ce - version: v19.5.6 + version: v19.6.1 name: gitlab-migrations cpus: "1.0" mem_reservation: 1g diff --git a/roles/web-app-joomla/files/Dockerfile b/roles/web-app-joomla/files/Dockerfile index 73e682fc6b..fb0c128619 100644 --- a/roles/web-app-joomla/files/Dockerfile +++ b/roles/web-app-joomla/files/Dockerfile @@ -16,5 +16,6 @@ COPY ${JOOMLA_ENTRYPOINT_SCRIPT_HOST_REL} ${JOOMLA_ENTRYPOINT_SCRIPT_DOCKER} RUN chmod +x "${JOOMLA_ENTRYPOINT_SCRIPT_DOCKER}" \ && ln -sf "${JOOMLA_ENTRYPOINT_SCRIPT_DOCKER}" /usr/local/bin/entrypoint-joomla +ENV JOOMLA_STOCK_ENTRYPOINT=/entrypoint.sh ENTRYPOINT ["/usr/local/bin/entrypoint-joomla"] CMD ["apache2-foreground"] diff --git a/roles/web-app-joomla/files/shell/docker-entrypoint-joomla.sh b/roles/web-app-joomla/files/shell/docker-entrypoint-joomla.sh index 49a9d03bbb..ed909dae1f 100644 --- a/roles/web-app-joomla/files/shell/docker-entrypoint-joomla.sh +++ b/roles/web-app-joomla/files/shell/docker-entrypoint-joomla.sh @@ -1,30 +1,124 @@ #!/bin/bash -# Serialize the stock image's first-boot copy+auto-install across replicas that -# share the /var/www/html NFS volume (mkdir is atomic on NFS: one leader runs it, -# the rest block on the ready marker). The setup only runs when $1 is apache2*/ -# php-fpm, so the leader must drive it with `apache2 -v` (returns after setup) — -# a plain `true` skips the whole setup block and copies nothing. - -target="/var/www/html" -lock="${target}/.infinito-init.lock" +webroot="${JOOMLA_WEBROOT:?JOOMLA_WEBROOT must be set}" +stock="${JOOMLA_STOCK_ENTRYPOINT:?JOOMLA_STOCK_ENTRYPOINT must be set}" ready="${JOOMLA_INIT_READY_FILE:?JOOMLA_INIT_READY_FILE must be set}" +stale_after="${JOOMLA_INIT_LOCK_STALE_SECONDS:?JOOMLA_INIT_LOCK_STALE_SECONDS must be set}" +lock="${webroot}/.infinito-init.lock" +owner="${lock}/owner" +marker="${webroot}/.joomla-initializing" +pending="${webroot}/.infinito-init.cleanup" +config="${webroot}/configuration.php" +token="${HOSTNAME}.$$.$(date +%s%N)" +beat=$((stale_after / 4 + 1)) +heartbeat_pid="" -if [ ! -e "${ready}" ] && [ ! -e "${target}/configuration.php" ]; then - if mkdir "${lock}" 2>/dev/null; then - /entrypoint.sh apache2 -v || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error - if [ -e "${target}/configuration.php" ]; then - chown -R www-data:www-data \ - "${target}/administrator/cache" "${target}/administrator/logs" \ - "${target}/cache" "${target}/tmp" 2>/dev/null || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error - touch "${ready}" - fi - else - tries=0 - while [ ! -e "${ready}" ] && [ ! -e "${target}/configuration.php" ] && [ "${tries}" -lt 300 ]; do - sleep 2 - tries=$((tries + 1)) - done +trap 'exit 143' TERM +trap 'exit 130' INT + +log_error() { + printf '[ERROR] %s\n' "$1" >&2 +} + +initialized() { + [ -e "${ready}" ] || { [ -s "${config}" ] && [ ! -e "${marker}" ]; } +} + +stale() { + local stamp + stamp="$(stat -c %Y "$1/owner" 2>/dev/null)" || + stamp="$(stat -c %Y "$1" 2>/dev/null)" || + return 1 + [ $(($(date +%s) - stamp)) -gt "${stale_after}" ] +} + +take_over_stale() { + local moved="${lock}.stale.${token}" + stale "${lock}" || return 1 + mv -T "${lock}" "${moved}" 2>/dev/null || return 1 + if stale "${moved}"; then + rm -rf "${moved}" + return 0 fi -fi + mv -T "${moved}" "${lock}" + return 1 +} -exec /entrypoint.sh "$@" +heartbeat() { + while sleep "${beat}"; do + touch "${owner}" + done +} + +release() { + if [ -n "${heartbeat_pid}" ]; then + kill "${heartbeat_pid}" 2>/dev/null + fi + heartbeat_pid="" + if [ "$(cat "${owner}" 2>/dev/null)" = "${token}" ]; then + rm -rf "${lock}" + fi +} + +run_setup() { + local log + log="$(mktemp)" + { "${stock}" apache2 -l 2>&1 | tee "${log}"; } & + wait "$!" + if [ -s "${config}" ] && [ -d "${marker}" ] && + grep -q 'Unable to delete installation folder' "${log}" && + ! grep -qE 'Failed to (correct ownership|restore configuration)|Refusing to change permissions' "${log}"; then + touch "${pending}" + fi + rm -f "${log}" +} + +finish_cleanup() { + rm -rf "${webroot}/installation" || return 1 + rm -f "${webroot}/joomla.xml" || return 1 + if [ ! -e "${webroot}/robots.txt" ] && [ -e "${webroot}/robots.txt.dist" ]; then + mv "${webroot}/robots.txt.dist" "${webroot}/robots.txt" || return 1 + fi + rmdir "${marker}" || return 1 + rm -f "${pending}" +} + +recover() { + if [ ! -e "${marker}" ]; then + run_setup + fi + if [ -e "${marker}" ] && [ -e "${pending}" ] && ! finish_cleanup; then + log_error "Finishing Joomla's installer cleanup in ${webroot} failed; ${pending} stays, so the next start retries it." + return 1 + fi + if initialized; then + touch "${ready}" + return 0 + fi + if [ -e "${marker}" ]; then + log_error "${marker} remains from an unfinished Joomla setup. If that setup stopped at 'Unable to delete installation folder!', run 'touch ${pending}' and restart; otherwise restore the site and database, then remove ${marker}." + fi + return 1 +} + +lead() { + local status + printf '%s\n' "${token}" > "${owner}" + trap release EXIT + heartbeat & + heartbeat_pid=$! + recover + status=$? + release + trap - EXIT + return "${status}" +} + +until initialized; do + if mkdir "${lock}" 2>/dev/null; then + lead || exit 1 + elif ! take_over_stale; then + sleep 2 + fi +done + +exec "${stock}" "$@" diff --git a/roles/web-app-joomla/templates/env.j2 b/roles/web-app-joomla/templates/env.j2 index 0fdedc5d0f..14dd382f92 100644 --- a/roles/web-app-joomla/templates/env.j2 +++ b/roles/web-app-joomla/templates/env.j2 @@ -1,6 +1,8 @@ {% include 'roles/sys-svc-container/templates/env.j2' %} +JOOMLA_INIT_LOCK_STALE_SECONDS={{ JOOMLA_INIT_LOCK_STALE_SECONDS }} JOOMLA_INIT_READY_FILE={{ JOOMLA_INIT_READY_FILE }} +JOOMLA_WEBROOT={{ JOOMLA_DOCROOT }} JOOMLA_SITE_NAME={{ JOOMLA_SITE_NAME }} JOOMLA_ADMIN_USER={{ JOOMLA_USER }} JOOMLA_ADMIN_USERNAME={{ JOOMLA_USER_NAME }} diff --git a/roles/web-app-joomla/vars/main.yml b/roles/web-app-joomla/vars/main.yml index fd24e7d44d..c4744ff5c5 100644 --- a/roles/web-app-joomla/vars/main.yml +++ b/roles/web-app-joomla/vars/main.yml @@ -13,6 +13,7 @@ JOOMLA_CONFIG_FILE: "/var/www/html/configuration.php" JOOMLA_INSTALLER_CLI_FILE: "/var/www/html/installation/joomla.php" JOOMLA_CLI_FILE: "/var/www/html/cli/joomla.php" JOOMLA_INIT_READY_FILE: "/var/www/html/.infinito-init.ready" +JOOMLA_INIT_LOCK_STALE_SECONDS: 180 JOOMLA_CLI_EXTENSION_ENABLE_SINCE: "6.1.0" JOOMLA_DOCROOT: "{{ lookup('volume', application_id, 'data').target }}" diff --git a/roles/web-app-mattermost/files/playwright/test-design.js b/roles/web-app-mattermost/files/playwright/test-design.js index 2403418d9f..070eee6866 100644 --- a/roles/web-app-mattermost/files/playwright/test-design.js +++ b/roles/web-app-mattermost/files/playwright/test-design.js @@ -31,7 +31,9 @@ const POSTS = "#post-list"; const POST = `${POSTS} .post:not(.post--system)`; const CONTENT = "#app-content"; const HEADER = "#global-header"; -const HEADER_LOGO = `${HEADER} [aria-controls='product-switcher-menu'] > span > svg`; +const PRODUCT_MENU_BUTTON = "#switchProductMenuButton"; +const PRODUCT_MENU = "#switchProductMenu"; +const HEADER_LOGO = `${HEADER} ${PRODUCT_MENU_BUTTON} > span > svg`; const SIDEBAR = "#SidebarContainer"; const SETTINGS = "#accountSettingsModal"; const THEMES = "#premadeThemesSection"; @@ -278,8 +280,8 @@ exports.register = function (shared) { await page.locator("#navbar .navbar-toggle").first().click(); await settled(page, SIDEBAR); } else { - await page.locator("#product_switch_menu").click(); - await settled(page, "#product-switcher-menu-dropdown"); + await page.locator(PRODUCT_MENU_BUTTON).click(); + await settled(page, PRODUCT_MENU); } }), view("settings-notifications", showcase, openSettings), @@ -390,7 +392,7 @@ exports.register = function (shared) { await loaded(EDITOR)(page); const onFrame = await tokenValue(page, "--design-on-frame", "color"); const seen = []; - await page.locator(`${HEADER} #product_switch_menu`).focus(); + await page.locator(`${HEADER} ${PRODUCT_MENU_BUTTON}`).focus(); for (let step = 0; step < 24; step += 1) { await page.keyboard.press("Tab"); const stop = await page.evaluate( diff --git a/roles/web-app-mattermost/meta/services.yml b/roles/web-app-mattermost/meta/services.yml index 947be002df..c7eb89313e 100644 --- a/roles/web-app-mattermost/meta/services.yml +++ b/roles/web-app-mattermost/meta/services.yml @@ -50,7 +50,7 @@ mattermost: version: 13.7-slim custom: true repository: https://github.com/mattermost/mattermost.git - ref: v11.11.4 + ref: v12.1.0 min_storage: 659MB backup: stop_required: false diff --git a/roles/web-app-mattermost/templates/style.css.j2 b/roles/web-app-mattermost/templates/style.css.j2 index 0ac08d079c..4298f5460e 100644 --- a/roles/web-app-mattermost/templates/style.css.j2 +++ b/roles/web-app-mattermost/templates/style.css.j2 @@ -4595,9 +4595,6 @@ html:not([data-design-app-theme="custom"]) .Menu .dropdown-menu li a { html:not([data-design-app-theme="custom"]) .Menu .styleSelectableItem .sorting-menu-checkbox i { color: var(--button-bg); } -html:not([data-design-app-theme="custom"]) .Menu>.product-switcher-menu .MenuItem a .icon { - color: rgba(var(--center-channel-color-rgb), 0.64); -} @media screen and (max-width: 768px) { html:not([data-design-app-theme="custom"]) #submenuModal .mobile-sub-menu .modal-content .modal-body .MenuWrapper .Menu.dropdown-menu .MenuGroup.menu-divider { background-color: var(--design-surface-2); @@ -9029,7 +9026,7 @@ html:not([data-design-app-theme="custom"]) body .header-footer-route .header-foo } {% if design.logo is string %} -html:not([data-design-app-theme="custom"]) body #global-header [aria-controls="product-switcher-menu"] > span > svg { +html:not([data-design-app-theme="custom"]) body #global-header #switchProductMenuButton > span > svg { width: {{ (24 * design.slots['logo-frame'].width / design.slots['logo-frame'].height) | round | int }}px; height: 24px; background: url("{{ design.urls['logo-frame'].svg }}") left center / contain no-repeat; @@ -9041,7 +9038,7 @@ body .hfroute-header .header-main .header-logo-link > svg { background: url("{{ design.urls.logo.svg }}") left center / contain no-repeat; } -html:not([data-design-app-theme="custom"]) body #global-header [aria-controls="product-switcher-menu"] > span > svg > *, +html:not([data-design-app-theme="custom"]) body #global-header #switchProductMenuButton > span > svg > *, body .hfroute-header .header-logo-link > svg > * { visibility: hidden; } diff --git a/roles/web-app-mediawiki/templates/oidc.php.j2 b/roles/web-app-mediawiki/templates/oidc.php.j2 index 7ce2059aa1..c4904c4993 100644 --- a/roles/web-app-mediawiki/templates/oidc.php.j2 +++ b/roles/web-app-mediawiki/templates/oidc.php.j2 @@ -5,8 +5,9 @@ $pa = "$IP/extensions/PluggableAuth/extension.json"; $oidc = "$IP/extensions/OpenIDConnect/extension.json"; +$oidcVendor = "$IP/extensions/OpenIDConnect/vendor/autoload.php"; -if ( file_exists( $pa ) && file_exists( $oidc ) ) { +if ( file_exists( $pa ) && file_exists( $oidc ) && file_exists( $oidcVendor ) ) { {% if 'web-svc-logout' in CURRENT_PLAY_APPLICATIONS %} $wgPasswordAttemptThrottle = []; diff --git a/roles/web-app-meta/meta/services.yml b/roles/web-app-meta/meta/services.yml index 398fca83e1..44062a07fc 100644 --- a/roles/web-app-meta/meta/services.yml +++ b/roles/web-app-meta/meta/services.yml @@ -36,7 +36,7 @@ meta: swarm: enabled: true image: ghcr.io/infinito-nexus/meta - version: v2.0.4 + version: 2.2.0 name: meta min_storage: 1040MB ports: diff --git a/roles/web-app-moodle/files/build/config.php b/roles/web-app-moodle/files/build/config.php index 3ac7ee66a2..a2c2bb9305 100644 --- a/roles/web-app-moodle/files/build/config.php +++ b/roles/web-app-moodle/files/build/config.php @@ -1,5 +1,4 @@ admin = 'admin'; $CFG->directorypermissions = 02770; $CFG->routerconfigured = true; +$CFG->session_handler_class = '\core\session\database'; + $CFG->reverseproxy = moodle_env_bool('MOODLE_REVERSEPROXY'); $CFG->sslproxy = moodle_env_bool('MOODLE_SSLPROXY'); diff --git a/roles/web-app-openbao/meta/services.yml b/roles/web-app-openbao/meta/services.yml index 2835707517..f6bee3d856 100644 --- a/roles/web-app-openbao/meta/services.yml +++ b/roles/web-app-openbao/meta/services.yml @@ -60,7 +60,7 @@ openbao: pids_limit: 512 min_storage: 60MB image: openbao/openbao - version: "2.7.2" + version: "2.7.3" custom: true backup: stop_required: true diff --git a/roles/web-app-opencloud/files/playwright/test-design.js b/roles/web-app-opencloud/files/playwright/test-design.js index f7f877a754..8d99e4915f 100644 --- a/roles/web-app-opencloud/files/playwright/test-design.js +++ b/roles/web-app-opencloud/files/playwright/test-design.js @@ -17,6 +17,7 @@ const { adminPassword, adminUsername, baseUrl, ssoLoginAndAssertUsername } = req const SHOWCASE_FOLDER = "design-showcase"; const SHOWCASE_SPACE = "Design Showcase"; const SHOWCASE_GROUP = "design-showcase"; +const ACCESS_DENIED_TEXTS = ["#exitAnchor", "#opencloud .oc-card h2"]; const base = baseUrl.replace(/\/$/, ""); const idmUsername = decodeDotenvQuotedValue(process.env.IDM_ADMIN_USERNAME); @@ -449,7 +450,7 @@ test("design: a primary-filled control takes the primary color and its on-color" await assertToken(page, "#exitAnchor", "background-color", "--design-primary", `opencloud ${mode}`); await assertToken(page, "#exitAnchor", "color", "--design-on-primary", `opencloud ${mode}`); }); - await assertReadable(page, ["#exitAnchor", ".oc-login .oc-card h2"], "opencloud access denied"); + await assertReadable(page, ACCESS_DENIED_TEXTS, "opencloud access denied"); await expect( page.locator('img[alt="OpenCloud emblem"]'), "the upstream emblem must not show on the corporate frame", diff --git a/roles/web-app-opencloud/meta/services.yml b/roles/web-app-opencloud/meta/services.yml index 991d2e03a4..04d5cefbd1 100644 --- a/roles/web-app-opencloud/meta/services.yml +++ b/roles/web-app-opencloud/meta/services.yml @@ -38,7 +38,7 @@ opencloud: replicas: 1 name: opencloud image: opencloudeu/opencloud - version: 7.2.5 + version: 9.1.1 min_storage: 276MB # nocheck: default-placement-manager opencloud_data holds NFS-hostile engine state: NATS JetStream store (events, micro registry, posixfs id cache), bleve search index, idm.boltdb, posixfs xattr metadata; upstream says search cannot scale, so the volume must stay node-local placement: manager diff --git a/roles/web-app-opencloud/templates/style.css.j2 b/roles/web-app-opencloud/templates/style.css.j2 index c1c3ff354e..0c5dbc575c 100644 --- a/roles/web-app-opencloud/templates/style.css.j2 +++ b/roles/web-app-opencloud/templates/style.css.j2 @@ -28,14 +28,26 @@ background-color: var(--design-surface-active); } -.oc-button-primary-filled:hover:not([disabled], .no-hover) { +#exitAnchor { + --oc-button-color: var(--design-primary); + --oc-button-on-color: var(--design-on-primary); +} +:is(.oc-button-primary-filled, #exitAnchor):hover:not([disabled], .no-hover) { filter: none; background-color: var(--design-primary-hover); } -.oc-button-primary-filled:active:not([disabled]) { +:is(.oc-button-primary-filled, #exitAnchor):active:not([disabled]) { background-color: var(--design-primary-active); } +.oc-checkbox:checked:not(:disabled) { + border-color: var(--design-primary); + background-color: var(--design-primary); +} +.oc-checkbox[type="checkbox"]:is(:checked, :indeterminate):not(:disabled)::before { + background-color: var(--design-on-primary); +} + #oc-topbar { --design-focus: var(--design-on-frame); } diff --git a/roles/web-app-pretix/meta/services.yml b/roles/web-app-pretix/meta/services.yml index 158ec18ba7..8986698c27 100644 --- a/roles/web-app-pretix/meta/services.yml +++ b/roles/web-app-pretix/meta/services.yml @@ -56,7 +56,7 @@ pretix: # nocheck: docker-version runtime base of the source build, not the served application version: "3.13" source_repository: https://github.com/pretix/pretix.git - source_version: v2026.9.2 + source_version: v2026.9.3 update: - key: source_version type: git_tags diff --git a/roles/web-app-prometheus/meta/services.yml b/roles/web-app-prometheus/meta/services.yml index 344d2ca04b..b48d9e58b1 100644 --- a/roles/web-app-prometheus/meta/services.yml +++ b/roles/web-app-prometheus/meta/services.yml @@ -136,7 +136,7 @@ node-exporter: flavor: wget path: metrics image: prom/node-exporter - version: v1.12.1 + version: v1.13.1 name: prometheus-node-exporter cpus: "0.1" mem_reservation: 32m @@ -146,11 +146,6 @@ node-exporter: ports: internal: http: 9100 - security: - suppressions: - # nocheck: cve upstream tag ships fixable CRITICAL CVEs; lift it once a rebuilt tag lands - - image_tag: "v1.12.1" - until: 2026-11-30 # nocheck: playwright-service-flag # nocheck: variants-coverage — sso-variant-tor requires the onion on in every variant, so the false polarity has no variant left to live in diff --git a/roles/web-app-shopware/files/Dockerfile b/roles/web-app-shopware/files/Dockerfile index 092232bc4f..55ccd9f9dc 100644 --- a/roles/web-app-shopware/files/Dockerfile +++ b/roles/web-app-shopware/files/Dockerfile @@ -26,6 +26,7 @@ RUN set -eux; \ --no-scripts \ --ignore-platform-req=ext-gd \ --ignore-platform-req=ext-intl \ + --ignore-platform-req=ext-mbstring \ --ignore-platform-req=ext-pdo_mysql; \ composer require symfony/redis-messenger:^7.4 league/flysystem-async-aws-s3:^3.0 \ heptacom/shopware-platform-admin-open-auth:^9.0 \ @@ -35,6 +36,7 @@ RUN set -eux; \ --update-no-dev \ --ignore-platform-req=ext-gd \ --ignore-platform-req=ext-intl \ + --ignore-platform-req=ext-mbstring \ --ignore-platform-req=ext-pdo_mysql \ --ignore-platform-req=ext-redis diff --git a/roles/web-app-snipe-it/files/custom_css.css b/roles/web-app-snipe-it/files/custom_css.css deleted file mode 100644 index 77fb1f7306..0000000000 --- a/roles/web-app-snipe-it/files/custom_css.css +++ /dev/null @@ -1,50 +0,0 @@ -html[data-theme] { - --color-bg: var(--design-surface-1); - --color-fg: var(--design-text); - --header-color: var(--design-text); - --box-bg: var(--design-surface-2); - --table-stripe-bg: var(--design-surface-2); - --table-stripe-bg-alt: var(--design-surface-3); - --input-group-bg: var(--design-surface-3); - --input-group-fg: var(--design-text); - --callout-bg-color: var(--design-surface-3); - --callout-left-border: var(--design-border-strong); - --main-footer-bg-color: var(--design-surface-2); - --main-footer-text-color: var(--design-text-muted); - --main-footer-top-border-color: var(--design-border); - --text-help: var(--design-text-muted); - --text-legend-help: var(--design-text-muted); - --text-danger: var(--design-danger); - --text-info: var(--design-info); - --text-success: var(--design-success); - --text-warning: var(--design-warning); - --link-hover: var(--design-link); - --table-border-row-color: var(--design-border); - --table-border-row-top: 1px solid var(--design-border); - --table-border-row: 1px solid var(--design-border); - --box-header-bottom-border-color: var(--design-border); - --box-header-bottom-border: 1px solid var(--design-border); - --box-header-top-border-color: var(--design-border); - --box-header-top-border: 3px solid var(--design-border); - --tab-bottom-border: 1px solid var(--design-border); - --default-label-link-bg: var(--design-surface-1); - --default-label-link-border: 1px solid var(--design-border); - --input-border-color: var(--design-border-strong); - --search-highlight: var(--design-warning-subtle); - --main-theme-color: var(--design-frame); - --main-theme-hover: var(--design-frame-hover); - --btn-theme-base: var(--design-frame); - --btn-theme-border: var(--design-frame-active); - --btn-theme-hover: var(--design-frame-hover); - --sidenav-hover-color-bg: var(--design-frame-active); - --sidenav-text-hover-color: var(--design-on-frame); - --sidenav-text-nohover-color: var(--design-on-frame); -} -html[data-theme] .fc { - --fc-border-color: var(--design-border); - --fc-page-bg-color: var(--design-surface-2); - --fc-neutral-bg-color: var(--design-surface-3); - --fc-neutral-text-color: var(--design-text); - --fc-list-event-hover-bg-color: var(--design-surface-hover); - --fc-today-bg-color: var(--design-surface-active); -} diff --git a/roles/web-app-snipe-it/files/php/apply/design_config.php b/roles/web-app-snipe-it/files/php/apply/design_config.php index f3ef6349b0..8b17e99c22 100644 --- a/roles/web-app-snipe-it/files/php/apply/design_config.php +++ b/roles/web-app-snipe-it/files/php/apply/design_config.php @@ -40,7 +40,7 @@ if ($wanted !== []) { $target[$field] = $name; } $block = OPEN . " infinito-design:" . base64_encode(json_encode($previous)) . " " . CLOSE . "\n" - . $wanted["custom_css"] . "\n" . OPEN . " /infinito-design " . CLOSE . "\n"; + . OPEN . " /infinito-design " . CLOSE . "\n"; } $target["custom_css"] = $block . $foreign === "" ? null : $block . $foreign; diff --git a/roles/web-app-snipe-it/files/php/provision_mcp_identity.php b/roles/web-app-snipe-it/files/php/provision_mcp_identity.php index 18feec12ca..95a8f4d454 100644 --- a/roles/web-app-snipe-it/files/php/provision_mcp_identity.php +++ b/roles/web-app-snipe-it/files/php/provision_mcp_identity.php @@ -18,6 +18,7 @@ * MCP_PASSWORD: password to pin on it. * MCP_TOKEN_NAME: personal access token name to converge. * MCP_CURRENT_TOKEN: token the adapter holds today, or "" for none. + * MCP_API_HOST: APP_URL host the loopback API probe sends as Host. */ // nocheck: mirrored-unit-test - boots Snipe-IT's Laravel kernel through @@ -35,6 +36,11 @@ $username = getenv("MCP_USER"); $password = getenv("MCP_PASSWORD"); $tokenName = getenv("MCP_TOKEN_NAME"); $currentToken = trim((string) getenv("MCP_CURRENT_TOKEN")); +$apiHost = trim((string) getenv("MCP_API_HOST")); +if ($apiHost === "") { + fwrite(STDERR, "MCP_API_HOST is not set\n"); + exit(1); +} $permissions = json_encode([ "self.api" => "1", @@ -42,12 +48,13 @@ $permissions = json_encode([ "licenses.view" => "1", ]); -function apiStatus(string $token): int +function apiStatus(string $token, string $host): int { $probe = curl_init("http://127.0.0.1/api/v1/hardware?limit=1"); curl_setopt_array($probe, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ + "Host: " . $host, "Authorization: Bearer " . $token, "Accept: application/json", ], @@ -57,7 +64,7 @@ function apiStatus(string $token): int return (int) curl_getinfo($probe, CURLINFO_HTTP_CODE); } -if ($currentToken !== "" && apiStatus($currentToken) === 200) { +if ($currentToken !== "" && apiStatus($currentToken, $apiHost) === 200) { echo "UNCHANGED\n"; echo $currentToken . "\n"; exit(0); @@ -118,7 +125,7 @@ $changed = $changed || $revoked > 0; $token = $user->createToken($tokenName)->accessToken; -$status = apiStatus($token); +$status = apiStatus($token, $apiHost); if ($status !== 200) { fwrite(STDERR, "Snipe-IT's own API answered {$status} to the token it just minted\n"); exit(1); diff --git a/roles/web-app-snipe-it/files/style.css b/roles/web-app-snipe-it/files/style.css index 72826e5ca9..bc7a0b7b2e 100644 --- a/roles/web-app-snipe-it/files/style.css +++ b/roles/web-app-snipe-it/files/style.css @@ -1,3 +1,53 @@ +html[data-theme] { + --color-bg: var(--design-surface-1); + --color-fg: var(--design-text); + --header-color: var(--design-text); + --box-bg: var(--design-surface-2); + --table-stripe-bg: var(--design-surface-2); + --table-stripe-bg-alt: var(--design-surface-3); + --input-group-bg: var(--design-surface-3); + --input-group-fg: var(--design-text); + --callout-bg-color: var(--design-surface-3); + --callout-left-border: var(--design-border-strong); + --main-footer-bg-color: var(--design-surface-2); + --main-footer-text-color: var(--design-text-muted); + --main-footer-top-border-color: var(--design-border); + --text-help: var(--design-text-muted); + --text-legend-help: var(--design-text-muted); + --text-danger: var(--design-danger); + --text-info: var(--design-info); + --text-success: var(--design-success); + --text-warning: var(--design-warning); + --link-hover: var(--design-link); + --table-border-row-color: var(--design-border); + --table-border-row-top: 1px solid var(--design-border); + --table-border-row: 1px solid var(--design-border); + --box-header-bottom-border-color: var(--design-border); + --box-header-bottom-border: 1px solid var(--design-border); + --box-header-top-border-color: var(--design-border); + --box-header-top-border: 3px solid var(--design-border); + --tab-bottom-border: 1px solid var(--design-border); + --default-label-link-bg: var(--design-surface-1); + --default-label-link-border: 1px solid var(--design-border); + --input-border-color: var(--design-border-strong); + --search-highlight: var(--design-warning-subtle); + --main-theme-color: var(--design-frame); + --main-theme-hover: var(--design-frame-hover); + --btn-theme-base: var(--design-frame); + --btn-theme-border: var(--design-frame-active); + --btn-theme-hover: var(--design-frame-hover); + --sidenav-hover-color-bg: var(--design-frame-active); + --sidenav-text-hover-color: var(--design-on-frame); + --sidenav-text-nohover-color: var(--design-on-frame); +} +html[data-theme] .fc { + --fc-border-color: var(--design-border); + --fc-page-bg-color: var(--design-surface-2); + --fc-neutral-bg-color: var(--design-surface-3); + --fc-neutral-text-color: var(--design-text); + --fc-list-event-hover-bg-color: var(--design-surface-hover); + --fc-today-bg-color: var(--design-surface-active); +} .main-header, .main-sidebar, .basic-page-header { diff --git a/roles/web-app-snipe-it/meta/services.yml b/roles/web-app-snipe-it/meta/services.yml index 4ac02548e6..09ff84b6b2 100644 --- a/roles/web-app-snipe-it/meta/services.yml +++ b/roles/web-app-snipe-it/meta/services.yml @@ -51,7 +51,7 @@ snipe-it: backup: stop_required: false healthcheck: - test: ["CMD", "wget", "-q", "-O-", "http://localhost/health"] + test: ["CMD", "wget", "-q", "-O-", "--header", "Host: {{ lookup('domain', 'web-app-snipe-it') }}", "http://localhost/health"] retries: 12 enabled: true shared: true @@ -61,7 +61,7 @@ snipe-it: enabled: true swarm: enabled: true - version: v8.8.3-alpine + version: v8.8.4-alpine custom: true name: snipe-it image: snipe/snipe-it @@ -85,11 +85,6 @@ snipe-it: - web-app-stalwart - web-app-mailu lifecycle: beta - security: - suppressions: - # nocheck: cve upstream tag ships fixable CRITICAL CVEs; lift it once a rebuilt tag lands - - image_tag: "v8.8.3-alpine" - until: 2026-11-30 sso: bond: 1 enabled: "{{ 'web-app-keycloak' in group_names }}" diff --git a/roles/web-app-snipe-it/tasks/04_sso.yml b/roles/web-app-snipe-it/tasks/04_sso.yml index 033ed7dd06..1b93fbf3f8 100644 --- a/roles/web-app-snipe-it/tasks/04_sso.yml +++ b/roles/web-app-snipe-it/tasks/04_sso.yml @@ -31,8 +31,8 @@ ansible.builtin.shell: cmd: >- container exec {{ SNIPE_IT_CONTAINER_ADDRESS }} sh -c - '{{ 30 | curl }} -s -o /dev/null -w "%{http_code}" -H "X-Forwarded-Preferred-Username: $1" {{ item.proxy_header }} http://localhost/login' - _ {{ lookup('users', IAM_PLATFORM_ADMIN_USER_KEY).username | quote }} + '{{ 30 | curl }} -s -o /dev/null -w "%{http_code}" -H "Host: $2" -H "X-Forwarded-Preferred-Username: $1" {{ item.proxy_header }} http://localhost/login' + _ {{ lookup('users', IAM_PLATFORM_ADMIN_USER_KEY).username | quote }} {{ SNIPE_IT_DOMAIN | quote }} loop: - { label: "forged header without the proxy secret", proxy_header: "", expected: "200" } - { label: "header with the proxy secret", proxy_header: '-H "{{ SNIPE_IT_SSO_PROXY_HEADER }}: $INFINITO_SSO_PROXY_SECRET"', expected: "302" } diff --git a/roles/web-app-snipe-it/tasks/utils/mcp_mint.yml b/roles/web-app-snipe-it/tasks/utils/mcp_mint.yml index c0768af954..73ba388374 100644 --- a/roles/web-app-snipe-it/tasks/utils/mcp_mint.yml +++ b/roles/web-app-snipe-it/tasks/utils/mcp_mint.yml @@ -37,6 +37,8 @@ - -e - "MCP_TOKEN_NAME={{ SNIPEIT_MCP_UPSTREAM_TOKEN_NAME }}" - -e + - "MCP_API_HOST={{ SNIPE_IT_DOMAIN }}" + - -e - MCP_CURRENT_TOKEN - "{{ SNIPEIT_IDENTITY_LOCAL_CID }}" # nocheck: container-exec-resolver - php diff --git a/roles/web-app-snipe-it/vars/main.yml b/roles/web-app-snipe-it/vars/main.yml index 34449e0f5b..285e293a11 100644 --- a/roles/web-app-snipe-it/vars/main.yml +++ b/roles/web-app-snipe-it/vars/main.yml @@ -7,6 +7,7 @@ swarm_stack_converge_retries: 600 database_password: "{{ lookup('config', application_id, 'secrets.credentials.database_password') }}" # nocheck: lookup-config-path SNIPE_IT_URL: "{{ lookup('tls', application_id, 'url.base') }}" +SNIPE_IT_DOMAIN: "{{ lookup('domain', application_id) }}" SNIPE_IT_CONTAINER: "{{ lookup('config', application_id, 'services.snipe-it.name') }}" SNIPE_IT_IMAGE: "{{ lookup('config', application_id, 'services.snipe-it.image') }}" SNIPE_IT_VERSION: "{{ lookup('config', application_id, 'services.snipe-it.version') }}" @@ -47,7 +48,6 @@ SNIPE_IT_DESIGN_COLORS: nav_link_color: "{{ SNIPE_IT_DESIGN_PALETTE.light['--design-on-frame'] }}" link_light_color: "{{ SNIPE_IT_DESIGN_PALETTE.light['--design-link'] }}" link_dark_color: "{{ SNIPE_IT_DESIGN_PALETTE.dark['--design-link'] }}" - custom_css: "{{ lookup('file', 'custom_css.css', rstrip=False) }}" SNIPE_IT_DESIGN_SETTINGS: >- {{ SNIPE_IT_DESIGN_COLORS @@ -70,6 +70,7 @@ SNIPEIT_MCP_UPSTREAM_URL: "http://{{ SNIPEIT_MCP_UPSTREAM_HOST }}:{{ SNIPEIT_MCP SNIPEIT_MCP_CONTRACT: provider: "{{ application_id }}" upstream_url: "{{ SNIPEIT_MCP_UPSTREAM_URL }}" + upstream_host: "{{ SNIPE_IT_DOMAIN }}" auth_subject: "{{ lookup('config', application_id, 'mcp.auth_subject') }}" mutating_tools_enabled: "{{ lookup('config', application_id, 'mcp.tools.mutating_tools_enabled') | bool }}" tools: "{{ lookup('file', 'mcp/tools.json') | from_json }}" diff --git a/roles/web-app-socialhome/meta/services.yml b/roles/web-app-socialhome/meta/services.yml index ecf1917f2b..0706f5342a 100644 --- a/roles/web-app-socialhome/meta/services.yml +++ b/roles/web-app-socialhome/meta/services.yml @@ -16,7 +16,7 @@ socialhome: placement: manager name: socialhome image: ghcr.io/social-home-io/socialhome - version: "2026.11.7" + version: "2026.11.21" ports: local: http: 8089 diff --git a/roles/web-app-stalwart/meta/services.yml b/roles/web-app-stalwart/meta/services.yml index d71345c571..61b9b64764 100644 --- a/roles/web-app-stalwart/meta/services.yml +++ b/roles/web-app-stalwart/meta/services.yml @@ -140,7 +140,7 @@ clamav: enabled: true shared: false image: clamav/clamav-debian - version: "1.5.4" + version: "1.5.5" ports: internal: milter: 7357 diff --git a/roles/web-app-weblate/README.md b/roles/web-app-weblate/README.md index 37d4d8a16e..aff89d0995 100644 --- a/roles/web-app-weblate/README.md +++ b/roles/web-app-weblate/README.md @@ -17,7 +17,7 @@ In this deployment Weblate is the memory behind the translation gateway. [`web-s ## Administration -The container's entrypoint provisions the administrator as the Weblate user `admin`; `WEBLATE_ADMIN_NAME` is its display name only. The role reads that account's API token out of Weblate's own database after the deploy and writes it to `sys-token-store` under `administrator` / `web-app-weblate`. +The container's entrypoint provisions the administrator as the Weblate user `admin`; `WEBLATE_ADMIN_NAME` is its display name only. The role reads that account's API token out of Weblate's own database after the deploy and writes it to `sys-token-store` under `administrator` / `web-app-weblate`. With SSO on, [`files/python/adopt_admin.py`](files/python/adopt_admin.py) binds that account to the administrator's Keycloak user id, the `sub` claim, because Weblate 2026.11 refuses to link a signed-out OIDC sign-in to an existing account by e-mail unless `REGISTRATION_REBIND` is on. ## Networks diff --git a/roles/web-app-weblate/files/python/adopt_admin.py b/roles/web-app-weblate/files/python/adopt_admin.py index 42e94e825b..317f84fad3 100644 --- a/roles/web-app-weblate/files/python/adopt_admin.py +++ b/roles/web-app-weblate/files/python/adopt_admin.py @@ -1,32 +1,45 @@ -# nocheck: mirrored-unit-test - imports weblate.auth.models at module level and runs -# inside `weblate shell`; the models are not importable outside the Weblate image -"""Give the superuser Weblate bootstrapped the platform administrator's name. +"""Give the superuser Weblate bootstrapped the platform administrator's name and SSO identity. Upstream's entrypoint calls ``createadmin`` without ``--username``, so the superuser is always named ``admin`` while carrying the platform -administrator's e-mail. That is one human with two accounts, and it breaks -the OIDC login: ``associate_by_email`` matches the local account, then -``reauthenticate`` sees a usable password and parks an ``@partial`` on -``/accounts/confirm/`` asking for it. The partial is sticky, so every retry -returns to the same page. +administrator's e-mail. Renaming keeps the account, and with it the API +token the deploy reads back; creating a second superuser would leave that +token behind. -Renaming keeps the account, and with it the API token the deploy reads back; -creating a second superuser would leave that token behind. +Since Weblate 2026.11 ``weblate.accounts.pipeline.associate_by_email`` +refuses a signed-out OIDC sign-in whose e-mail already belongs to a local +account (``email_in_use``) unless ``REGISTRATION_REBIND`` is on, and that +setting would let every Keycloak user take over any account by e-mail. So +the administrator is bound to exactly its own Keycloak user instead: a +``social_django`` association for provider ``oidc`` whose ``uid`` is the +Keycloak user id, which Keycloak sends as the ``sub`` claim. +``social_user`` then finds the administrator before any e-mail check runs. +An association with that id held by another account is moved to the +administrator. An administrator already bound to another subject stops the +run, so a foreign identity is never overwritten silently. The password is only dropped while SSO is on. Without SSO it is the only way -in, and ``playwright.env.j2`` hands it to the native-login round. +in, and ``playwright.env.j2`` hands it to the native-login round. With SSO it +also keeps ``reauthenticate`` from parking a sticky ``@partial`` on +``/accounts/confirm/`` should the association ever be missing. Fed to ``weblate shell`` on stdin. Every value arrives in the environment and none has a default: a missing one is a deploy bug and must stop the run. +``WEBLATE_ADMIN_OIDC_SUBJECT`` is empty while SSO is off. """ import os +from social_django.models import UserSocialAuth from weblate.auth.models import User +OIDC_PROVIDER = "oidc" +OIDC_ID_KEY = "sub" + bootstrap = os.environ["WEBLATE_ADMIN_BOOTSTRAP_USERNAME"] target = os.environ["WEBLATE_ADMIN_USERNAME"] sso_enabled = os.environ["WEBLATE_OIDC_ENABLED"] == "true" +subject = os.environ["WEBLATE_ADMIN_OIDC_SUBJECT"] changed = False @@ -39,6 +52,32 @@ if bootstrap != target: admin = User.objects.get(username=target) +if sso_enabled: + if not subject: + raise SystemExit( + f"ADOPT_REFUSED: SSO is on but no Keycloak subject arrived for '{target}'" + ) + foreign = UserSocialAuth.objects.filter(user=admin, provider=OIDC_PROVIDER).exclude( + uid=subject + ) + if foreign.exists(): + raise SystemExit( + f"ADOPT_REFUSED: '{target}' is already bound to another OIDC subject; check " + "which Keycloak user it belongs to and delete that row from " + "social_auth_usersocialauth before deploying again" + ) + binding = UserSocialAuth.objects.filter(provider=OIDC_PROVIDER, uid=subject).first() + if binding is None: + UserSocialAuth.objects.create( + user=admin, provider=OIDC_PROVIDER, uid=subject, id_key=OIDC_ID_KEY + ) + changed = True + elif binding.user_id != admin.pk or binding.id_key != OIDC_ID_KEY: + binding.user = admin + binding.id_key = OIDC_ID_KEY + binding.save(update_fields=["user", "id_key"]) + changed = True + if sso_enabled and admin.has_usable_password(): admin.set_unusable_password() admin.save(update_fields=["password"]) diff --git a/roles/web-app-weblate/meta/services.yml b/roles/web-app-weblate/meta/services.yml index 7cea6c5629..a672dbabd9 100644 --- a/roles/web-app-weblate/meta/services.yml +++ b/roles/web-app-weblate/meta/services.yml @@ -58,7 +58,7 @@ weblate: host: enabled: false image: weblate/weblate - version: "2026.9" + version: "2026.11" min_storage: 1GB ports: local: @@ -86,7 +86,7 @@ beat: host: enabled: false image: weblate/weblate - version: "2026.9" + version: "2026.11" min_storage: 1GB lifecycle: beta # nocheck: single-replica weblate-beat. It is the only task upstream lets run Django's migrate, and the beat scheduler itself must stay singular or every periodic task fires once per replica. @@ -109,7 +109,7 @@ worker: host: enabled: false image: weblate/weblate - version: "2026.9" + version: "2026.11" min_storage: 1GB lifecycle: beta cpus: "1.0" diff --git a/roles/web-app-weblate/tasks/utils/admin_oidc_subject.yml b/roles/web-app-weblate/tasks/utils/admin_oidc_subject.yml new file mode 100644 index 0000000000..448ea6e9a1 --- /dev/null +++ b/roles/web-app-weblate/tasks/utils/admin_oidc_subject.yml @@ -0,0 +1,57 @@ +--- +# include-gated: when: WEBLATE_OIDC_ENABLED | bool +- name: "🛡️ Assert Weblate signs in against the local Keycloak the bind reads" + ansible.builtin.assert: + that: + - OIDC.CLIENT.ISSUER_URL == weblate_oidc_local_issuer + fail_msg: >- + Weblate signs in against {{ OIDC.CLIENT.ISSUER_URL }}, not the local + Keycloak {{ weblate_oidc_local_issuer }}. The administrator bind reads its + user id from the local Keycloak, so another issuer sends a different sub and + locks the administrator out. Drop OIDC_OVERRIDE.URL and the OIDC_OVERRIDE.CLIENT + issuer override, or disable SSO for Weblate. + quiet: true + vars: + weblate_oidc_local_issuer: "{{ lookup('tls', 'web-app-keycloak', 'url.origin') ~ '/realms/' ~ OIDC.CLIENT.REALM }}" + +- name: "🔍 Resolve the Keycloak hosting node and container id" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" + vars: + resolve_service_key: keycloak + resolve_service_name: "{{ lookup('container_service', 'web-app-keycloak', 'keycloak') }}" + resolve_output_prefix: WEBLATE_KEYCLOAK + resolve_compose_cid: "{{ WEBLATE_KEYCLOAK_CONTAINER_ADDRESS }}" + resolve_converge_retries: 60 + resolve_converge_delay: 5 + resolve_cid_filters: "--filter health=healthy" + +- name: "🔍 Read the Keycloak user of the administrator" + ansible.builtin.shell: >- # nocheck: container-exec-resolver WEBLATE_KEYCLOAK_LOCAL_CID resolved at delegate_to runtime; container_address would return a manager-only subshell + container exec -i {{ WEBLATE_KEYCLOAK_LOCAL_CID | quote }} sh -c ' + /opt/keycloak/bin/kcadm.sh config credentials --server http://127.0.0.1:8080 --realm master + --user "$KEYCLOAK_PERMANENT_ADMIN_USERNAME" --password "$KEYCLOAK_PERMANENT_ADMIN_PASSWORD" >&2 + && exec /opt/keycloak/bin/kcadm.sh get users -r "$1" -q username="$2" -q exact=true + --fields id,username --format csv --noquotes' _ + {{ OIDC.CLIENT.REALM | quote }} {{ WEBLATE_ADMIN_USERNAME | quote }} + register: weblate_keycloak_admin_users + changed_when: false + retries: 6 + delay: 10 + until: weblate_keycloak_admin_users.rc == 0 + delegate_to: "{{ WEBLATE_KEYCLOAK_HOST_NODE }}" + run_once: true + +- name: "🔗 Pick the Keycloak user id of the administrator" + ansible.builtin.set_fact: + weblate_admin_oidc_subjects: "{{ weblate_keycloak_admin_users.stdout_lines | map('trim') | select('match', '[^,]+,' ~ (WEBLATE_ADMIN_USERNAME | lower | regex_escape) + ~ '$') | map('regex_replace', ',.*$', '') | list }}" + +- name: "🛑 Refuse anything but exactly one Keycloak user for the administrator" + ansible.builtin.assert: + that: + - weblate_admin_oidc_subjects | length == 1 + fail_msg: >- + Keycloak realm {{ OIDC.CLIENT.REALM }} returned {{ weblate_admin_oidc_subjects | length }} + users named '{{ WEBLATE_ADMIN_USERNAME }}', so the administrator cannot be bound + to its single sign-on identity and Weblate would refuse its login as email_in_use. + quiet: true diff --git a/roles/web-app-weblate/tasks/utils/token.yml b/roles/web-app-weblate/tasks/utils/token.yml index ff9b00edf8..3b5b7e0d7d 100644 --- a/roles/web-app-weblate/tasks/utils/token.yml +++ b/roles/web-app-weblate/tasks/utils/token.yml @@ -6,11 +6,16 @@ resolve_output_prefix: WEBLATE resolve_compose_cid: "{{ WEBLATE_CONTAINER }}" +- name: "🔗 Look up the Keycloak user the administrator signs in as" + when: WEBLATE_OIDC_ENABLED | bool + ansible.builtin.include_tasks: utils/admin_oidc_subject.yml + - name: "👤 Let the platform administrator own the superuser Weblate bootstrapped" ansible.builtin.shell: # nocheck: container-exec-resolver only Weblate's own management shell can reach its user table cmd: > container exec -i -e WEBLATE_ADMIN_BOOTSTRAP_USERNAME -e WEBLATE_ADMIN_USERNAME -e WEBLATE_OIDC_ENABLED + -e WEBLATE_ADMIN_OIDC_SUBJECT {{ WEBLATE_LOCAL_CID | quote }} weblate shell stdin: "{{ lookup('file', 'python/adopt_admin.py') }}" @@ -18,10 +23,11 @@ WEBLATE_ADMIN_BOOTSTRAP_USERNAME: "{{ WEBLATE_ADMIN_BOOTSTRAP_USERNAME }}" WEBLATE_ADMIN_USERNAME: "{{ WEBLATE_ADMIN_USERNAME }}" WEBLATE_OIDC_ENABLED: "{{ WEBLATE_OIDC_ENABLED | bool | lower }}" + WEBLATE_ADMIN_OIDC_SUBJECT: "{{ (weblate_admin_oidc_subjects | first) if (WEBLATE_OIDC_ENABLED | bool) else '' }}" register: weblate_admin_adopt retries: 30 delay: 10 - until: weblate_admin_adopt.rc == 0 + until: weblate_admin_adopt.rc == 0 or 'ADOPT_REFUSED' in weblate_admin_adopt.stderr changed_when: "'ADOPTED=1' in weblate_admin_adopt.stdout" no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" delegate_to: "{{ WEBLATE_HOST_NODE }}" diff --git a/roles/web-app-weblate/vars/main.yml b/roles/web-app-weblate/vars/main.yml index 5bf31b1aa2..7acffe1303 100644 --- a/roles/web-app-weblate/vars/main.yml +++ b/roles/web-app-weblate/vars/main.yml @@ -18,6 +18,7 @@ WEBLATE_ADMIN_PASSWORD: "{{ lookup('users', 'platform_administrator').password } WEBLATE_ADMIN_BOOTSTRAP_USERNAME: admin WEBLATE_ADMIN_USERNAME: "{{ lookup('users', 'platform_administrator').username }}" +WEBLATE_KEYCLOAK_CONTAINER_ADDRESS: "{{ lookup('container_address', 'web-app-keycloak', 'keycloak') }}" WEBLATE_TOKEN_MIN_LENGTH: 40 WEBLATE_DATABASE_NAME: "{{ lookup('database', application_id, 'name') }}" diff --git a/roles/web-app-wordpress/meta/addons/mcp-adapter.yml b/roles/web-app-wordpress/meta/addons/mcp-adapter.yml index 3116fb74d6..e41612358a 100644 --- a/roles/web-app-wordpress/meta/addons/mcp-adapter.yml +++ b/roles/web-app-wordpress/meta/addons/mcp-adapter.yml @@ -3,7 +3,7 @@ enabled: "{{ lookup('config', 'web-app-wordpress', 'mcp.enabled') | bool }}" required: true mechanism: plugin source: upstream -version: v0.7.1 +version: v0.7.2 update: monitored: true catalog: github-releases diff --git a/roles/web-svc-collabora/meta/services.yml b/roles/web-svc-collabora/meta/services.yml index 3867c2486e..b281a5812e 100644 --- a/roles/web-svc-collabora/meta/services.yml +++ b/roles/web-svc-collabora/meta/services.yml @@ -25,7 +25,7 @@ collabora: enabled: true shared: true image: collabora/code - version: "26.04.6.1.1" + version: "26.04.6.2.1" name: collabora min_storage: 734MB cpus: 2 @@ -40,11 +40,6 @@ collabora: proxy: service_key: collabora lifecycle: beta - security: - suppressions: - # nocheck: cve upstream tag ships fixable CRITICAL CVEs; lift it once a rebuilt tag lands - - image_tag: "26.04.6.1.1" - until: 2026-11-30 # nocheck: dynamic-flag # nocheck: design-off Reason: '/' answers a plain OK, the admin console is off and the editor opens only as a POST from the WOPI host (Nextcloud) design: diff --git a/roles/web-svc-coturn/meta/services.yml b/roles/web-svc-coturn/meta/services.yml index 85cb8b539e..402ae2227b 100644 --- a/roles/web-svc-coturn/meta/services.yml +++ b/roles/web-svc-coturn/meta/services.yml @@ -11,7 +11,7 @@ coturn: enabled: true shared: true image: coturn/coturn - version: 4.19.1 + version: 4.19.2 min_storage: 246MB user_auth_enabled: false total_quota: 2000 diff --git a/roles/web-svc-translate/files/requirements.txt b/roles/web-svc-translate/files/requirements.txt index 10d8ffa36a..8633c9f554 100644 --- a/roles/web-svc-translate/files/requirements.txt +++ b/roles/web-svc-translate/files/requirements.txt @@ -1,4 +1,4 @@ fastapi==0.163.1 -python-multipart==0.0.33 +python-multipart==0.0.34 uvicorn[standard]==0.54.0 asyncpg==0.32.0 diff --git a/scripts/github/cancel/pull_request_runs.sh b/scripts/github/cancel/pull_request_runs.sh index 8abc9d7cc2..35ca10bb86 100755 --- a/scripts/github/cancel/pull_request_runs.sh +++ b/scripts/github/cancel/pull_request_runs.sh @@ -24,7 +24,8 @@ validate_force_cancel_after # A fork PR's runs carry an empty `pull_requests` array, so the branch matcher # is all that is left — and it cannot tell two pull requests apart that share a # head repository and head branch. Rather than cancel the wrong one, drop the -# matcher for as long as the head is ambiguous. +# branch and head-sha matchers for as long as the head is ambiguous: anyone may +# open a pull request from another fork's branch and close it to cancel its runs. disable_ambiguous_branch_fallback() { local rivals local -a query @@ -55,6 +56,7 @@ disable_ambiguous_branch_fallback() { if [[ "${rivals}" != "0" ]]; then echo "Branch fallback disabled: ${rivals} other open pull request(s) share ${PR_HEAD_REPOSITORY%%/*}:${PR_HEAD_REF}" PR_HEAD_REF="" + PR_HEAD_SHA="" fi } @@ -88,7 +90,15 @@ run_ids="$( | select(.event == "pull_request" or .event == "pull_request_target") | select( any(.pull_requests[]?; (.number // -1) == $pr_number) - or ($pr_head_sha != "" and (.head_sha // "") == $pr_head_sha) + or ( + $pr_head_sha != "" + and (.head_sha // "") == $pr_head_sha + and all(.pull_requests[]?; (.number // $pr_number) == $pr_number) + and ( + (.head_repository.full_name // "") == $pr_head_repository + or ((.display_title // "") | test("PR #\($pr_number)( |$)")) + ) + ) or ( $pr_head_ref != "" and all(.pull_requests[]?; (.number // $pr_number) == $pr_number) diff --git a/scripts/github/gate/no_symlinks.sh b/scripts/github/gate/no_symlinks.sh new file mode 100755 index 0000000000..738e0aa091 --- /dev/null +++ b/scripts/github/gate/no_symlinks.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# +# Usage: no_symlinks.sh +# a directory checked out from an untrusted ref; the script fails +# when it holds a symlink, which would let a later read leave it. + +set -euo pipefail + +tree="${1:?Usage: no_symlinks.sh }" + +mapfile -t links < <(find "${tree}" -type l -print) + +if ((${#links[@]} > 0)); then + echo "Refusing ${tree}: ${#links[@]} symlink(s) survived core.symlinks=false." >&2 + printf ' - %q\n' "${links[@]:0:20}" >&2 + exit 1 +fi +echo "No symlinks under ${tree}." diff --git a/scripts/github/gate/trusted_label.sh b/scripts/github/gate/trusted_label.sh new file mode 100755 index 0000000000..642025c24b --- /dev/null +++ b/scripts/github/gate/trusted_label.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# +# Inputs via env: +# TRUSTED "true" when the fork PR carries the maintainer '🛡️ Trusted' label. +# PR_NUMBER the pull request number, named in the refusal. + +set -euo pipefail + +: "${TRUSTED:?}" +: "${PR_NUMBER:?}" + +if [[ "${TRUSTED}" != "true" ]]; then + echo "Fork PR #${PR_NUMBER} is not labelled '🛡️ Trusted'. The privileged image build and mirror run fork content with a packages:write token, so they start only after a maintainer reviewed the head and applied the label." >&2 + exit 1 +fi +echo "Fork PR #${PR_NUMBER} carries '🛡️ Trusted'; the privileged image build and mirror may run." diff --git a/scripts/github/update/open/pr.sh b/scripts/github/update/open/pr.sh index c99fa9170f..d59abbc00d 100755 --- a/scripts/github/update/open/pr.sh +++ b/scripts/github/update/open/pr.sh @@ -44,6 +44,9 @@ fi git commit -m "${UPDATE_COMMIT_MESSAGE}" +UPDATE_LEVEL="$(python3 -m utils.update.level HEAD~1 HEAD)" +echo "Update level: ${UPDATE_LEVEL}" + fingerprint_ref() { local ref="$1" shift @@ -115,6 +118,8 @@ git push --force \ "https://x-access-token:${GH_TOKEN}@github.com/${REPO}.git" \ "HEAD:refs/heads/${BRANCH}" +python3 -m cli.contributing.update.label --repo "${REPO}" --ensure-only + PR_NUMBER="$( gh pr list \ --repo "${REPO}" \ @@ -129,7 +134,9 @@ if [[ -n "${PR_NUMBER}" ]]; then gh pr edit "${PR_NUMBER}" \ --repo "${REPO}" \ --title "${UPDATE_PR_TITLE}" \ - --body "${UPDATE_PR_BODY}" + --body "${UPDATE_PR_BODY}" \ + --add-label update \ + --add-label "${UPDATE_LEVEL}" else echo "Creating PR for ${BRANCH}" PR_URL="$( @@ -138,7 +145,9 @@ else --title "${UPDATE_PR_TITLE}" \ --body "${UPDATE_PR_BODY}" \ --base "${UPDATE_BASE_BRANCH}" \ - --head "${OWNER}:${BRANCH}" + --head "${OWNER}:${BRANCH}" \ + --label update \ + --label "${UPDATE_LEVEL}" )" PR_NUMBER="${PR_URL##*/}" echo "Created PR #${PR_NUMBER}: ${PR_URL}" diff --git a/scripts/image/push.sh b/scripts/image/push.sh index 4bb1299b7d..f2e54aa88e 100755 --- a/scripts/image/push.sh +++ b/scripts/image/push.sh @@ -17,6 +17,7 @@ export INFINITO_PARENT_IMAGE : "${IMAGE_DIGEST_DIR:?Missing IMAGE_DIGEST_DIR}" : "${GITHUB_REPOSITORY:?Missing GITHUB_REPOSITORY}" : "${USE_NIX_TOKEN:?Missing USE_NIX_TOKEN}" +: "${EXPORT_BUILD_CACHE:?Missing EXPORT_BUILD_CACHE}" : "${INFINITO_PARENT_IMAGE:?Missing INFINITO_PARENT_IMAGE; source scripts/meta/env/load.sh}" : "${INFINITO_SRC_DIR:?Missing INFINITO_SRC_DIR; source scripts/meta/env/load.sh}" : "${INFINITO_VENV_DIR:?Missing INFINITO_VENV_DIR; source scripts/meta/env/load.sh}" @@ -39,6 +40,13 @@ else echo "pull_request_target on fork detected: skipping NIX_CONFIG token build-arg." fi +cache_to_arg=() +if [[ "${EXPORT_BUILD_CACHE}" == "true" ]]; then + cache_to_arg=(--cache-to "type=registry,mode=max,ref=${cache_ref}") +else + echo "Fork-sourced build: importing ${cache_ref} without exporting to it." +fi + while true; do echo "=== Build & push attempt ${attempt}/${max_attempts} ===" @@ -56,7 +64,7 @@ while true; do --build-arg "INFINITO_DOCKER_CLI_INSTALL_SCRIPT=${INFINITO_DOCKER_CLI_INSTALL_SCRIPT:?source scripts/meta/env/load.sh}" \ "${nix_arg[@]}" \ --cache-from "type=registry,ref=${cache_ref}" \ - --cache-to "type=registry,mode=max,ref=${cache_ref}" \ + "${cache_to_arg[@]}" \ "${BUILD_CONTEXT_DIR}"; then echo "Build & push succeeded on attempt ${attempt}/${max_attempts}." break diff --git a/scripts/tests/deploy/act/README.md b/scripts/tests/deploy/act/README.md index ee3794a2ed..09524ef219 100644 --- a/scripts/tests/deploy/act/README.md +++ b/scripts/tests/deploy/act/README.md @@ -9,4 +9,4 @@ For the canonical Make target index that invokes these helpers, see [make.md](.. | Command | What it does | Notes | |---|---|---| -| `workflow.sh` | Runs any workflow file through `act`. | Supports custom job, matrix, container, network, and image settings. Binds `INFINITO_VULNERABILITY_DB_HOST_PATH` into the job container at the same path. Invoked via `make act-workflow ACT_WORKFLOW=`. | +| `workflow.sh` | Runs any workflow file through `act`. | Supports custom job, matrix, container, network, and image settings. Binds `INFINITO_VULNERABILITY_DB_HOST_PATH` into the job container at the same path. A bound checkout (`ACT_BIND=true`, or pulled `roles/web-app-cst-*`) passes `INFINITO_DOTENV_HOST_OWNED=true`, so the job's `make dotenv` keeps the host `.env`. Invoked via `make act-workflow ACT_WORKFLOW=`. | diff --git a/scripts/tests/deploy/act/workflow.sh b/scripts/tests/deploy/act/workflow.sh index 93d09a2e33..762974734f 100755 --- a/scripts/tests/deploy/act/workflow.sh +++ b/scripts/tests/deploy/act/workflow.sh @@ -105,6 +105,7 @@ if [[ "${ACT_BIND}" != "true" ]] && compgen -G "${_act_repo_root}/roles/web-app- fi if [[ "${ACT_BIND}" == "true" ]]; then cmd+=(--bind) + cmd+=(--env "INFINITO_DOTENV_HOST_OWNED=true") fi "${cmd[@]}" diff --git a/scripts/tests/deploy/utils/filesystem/docker_dataroot.sh b/scripts/tests/deploy/utils/filesystem/docker_dataroot.sh index f3759350d4..19b45842ed 100755 --- a/scripts/tests/deploy/utils/filesystem/docker_dataroot.sh +++ b/scripts/tests/deploy/utils/filesystem/docker_dataroot.sh @@ -281,7 +281,7 @@ while [ -z "${LOOP}" ] && [ "${attempt}" -lt 16 ]; do if [ -n "${candidate}" ] && [ ! -b "${candidate}" ]; then mknod "${candidate}" b 7 "${candidate#/dev/loop}" 2>/dev/null || candidate="" fi - if attached="$(losetup --find --show "${IMAGE}" 2>/dev/null)"; then + if attached="$(losetup --direct-io=on --find --show "${IMAGE}" 2>/dev/null)"; then LOOP="${attached}" fi done diff --git a/tests/external/update/repository/test_sha_pins_follow_tags.py b/tests/external/update/repository/test_sha_pins_follow_tags.py new file mode 100644 index 0000000000..78c6084cda --- /dev/null +++ b/tests/external/update/repository/test_sha_pins_follow_tags.py @@ -0,0 +1,32 @@ +"""Fail when a `ref:` pins a commit SHA that its upstream's newest release +tag contains. + +A failed ``git ls-remote`` or ``git fetch`` counts as no such release, so an +unreachable remote never fails it. + +Suppress a check by placing ``# nocheck: repository-version`` on the line +directly above the ``ref:`` key. +""" + +from __future__ import annotations + +import unittest + +from utils.update.repository import find_outdated_updates, is_commit_sha + +from . import PROJECT_ROOT + + +class TestShaPinsFollowTags(unittest.TestCase): + def test_no_sha_pin_where_the_upstream_publishes_a_release(self) -> None: + offenders = [ + f"{u.entry.config_path.relative_to(PROJECT_ROOT)}:{u.entry.line}: " + f"{u.entry.repository} pins {u.entry.ref}, use the tag {u.latest}" + for u in find_outdated_updates(PROJECT_ROOT) + if is_commit_sha(u.entry.ref) and not is_commit_sha(u.latest) + ] + self.assertEqual(offenders, [], "\n".join(offenders)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/integration/meta/workflows/test_cancel_runs.py b/tests/integration/meta/workflows/test_cancel_runs.py index 3e9f6a2d5f..d2ea4c875e 100644 --- a/tests/integration/meta/workflows/test_cancel_runs.py +++ b/tests/integration/meta/workflows/test_cancel_runs.py @@ -237,6 +237,7 @@ class TestCancelPullRequestRuns(CancelScriptMixin, unittest.TestCase): { "id": 299, "event": "pull_request_target", + "display_title": "pull_request_target / PR #106 / synchronize / AlejandroRomanIbanez:feature/makefile-wsl2", "head_sha": "deadbeef", "head_branch": "unexpected-branch-name", "head_repository": {"full_name": "base-repo/core"}, @@ -249,6 +250,71 @@ class TestCancelPullRequestRuns(CancelScriptMixin, unittest.TestCase): ) self.assertEqual(cancelled, ["299"]) + def test_head_sha_never_cancels_another_pull_requests_runs(self): + in_progress_runs = """\ +{"workflow_runs":[ + { + "id": 340, + "event": "pull_request", + "head_sha": "deadbeef", + "head_branch": "fix/victim", + "head_repository": {"full_name": "base-repo/core"}, + "pull_requests": [{"number": 107}] + }, + { + "id": 341, + "event": "pull_request_target", + "display_title": "pull_request_target / PR #1061 / synchronize / victim:fix/victim", + "head_sha": "deadbeef", + "head_branch": "main", + "head_repository": {"full_name": "base-repo/core"}, + "pull_requests": [] + }, + { + "id": 342, + "event": "pull_request", + "head_sha": "deadbeef", + "head_branch": "fix/victim", + "head_repository": {"full_name": "victim/core"}, + "pull_requests": [] + }, + { + "id": 343, + "event": "pull_request", + "head_sha": "deadbeef", + "head_branch": "other-branch", + "head_repository": {"full_name": "AlejandroRomanIbanez/core"}, + "pull_requests": [] + } +]} +""" + _, cancelled = self._run_script( + runs_by_status={"in_progress": in_progress_runs} + ) + self.assertEqual(cancelled, ["343"]) + + def test_head_sha_never_cancels_a_rival_pull_request_on_the_same_head(self): + in_progress_runs = """\ +{"workflow_runs":[ + { + "id": 344, + "event": "pull_request", + "head_sha": "deadbeef", + "head_branch": "feature/makefile-wsl2", + "head_repository": {"full_name": "AlejandroRomanIbanez/core"}, + "pull_requests": [] + } +]} +""" + result, cancelled = self._run_script( + runs_by_status={ + "in_progress": in_progress_runs, + "pulls": '[{"number": 107, "head": {"ref": "feature/makefile-wsl2"}}]\n', + }, + ) + self.assertEqual(cancelled, []) + self.assertIn("Branch fallback disabled", result.stdout) + NEWEST_PER_GROUP_RUNS = """\ {"workflow_runs":[ { diff --git a/tests/integration/meta/workflows/test_ci_concurrency_variable_forwarded.py b/tests/integration/meta/workflows/test_ci_concurrency_variable_forwarded.py new file mode 100644 index 0000000000..252b16551c --- /dev/null +++ b/tests/integration/meta/workflows/test_ci_concurrency_variable_forwarded.py @@ -0,0 +1,70 @@ +"""Every workflow that sizes deploy chunks forwards the runner-slot variable. + +The validation job counts the priority batches and every chunk's discover job +cuts its rows from the same ``cli.meta.ci.slots`` arithmetic. A workflow that +sizes chunks without ``vars.INFINITO_CI_CONCURRENCY`` cuts a different plan +than its siblings, so rows are skipped or deployed twice. +""" + +from __future__ import annotations + +import unittest +from typing import TYPE_CHECKING + +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any + +from . import PROJECT_ROOT + +if TYPE_CHECKING: + from pathlib import Path + +WORKFLOWS = PROJECT_ROOT / ".github" / "workflows" +KEY = "INFINITO_CI_CONCURRENCY" +FORWARD = "${{ vars.INFINITO_CI_CONCURRENCY }}" +_SIZERS = ( + "cli.meta.ci.matrix", + "cli.meta.ci.plan", + "cli.meta.ci.slots", + "scripts/github/resolve/output_apps.sh", + "scripts/github/resolve/priority_batches.sh", +) + + +def _sizing_workflows() -> list[Path]: + return [ + path + for path in sorted(WORKFLOWS.glob("*.yml")) + if any(marker in read_text(str(path)) for marker in _SIZERS) + ] + + +def _forwarded(path: Path) -> str | None: + workflow = load_yaml_any(str(path), default_if_missing={}) or {} + env = workflow.get("env") if isinstance(workflow, dict) else None + return env.get(KEY) if isinstance(env, dict) else None + + +class TestCiConcurrencyVariableForwarded(unittest.TestCase): + def test_every_chunk_sizing_workflow_forwards_the_variable(self) -> None: + offenders = [ + path.name for path in _sizing_workflows() if _forwarded(path) != FORWARD + ] + self.assertEqual( + offenders, + [], + f"declare `{KEY}: {FORWARD}` in the workflow-level env of every " + "workflow that sizes deploy chunks", + ) + + def test_the_guard_finds_the_chunk_sizing_workflows(self) -> None: + self.assertGreaterEqual( + len(_sizing_workflows()), + 2, + "the validation and deploy workflows both size chunks; finding " + "fewer means the markers drifted and the guard passes vacuously", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/repository/test_workflow_fork_checkout_gated.py b/tests/lint/repository/test_workflow_fork_checkout_gated.py new file mode 100644 index 0000000000..7e77cb1d7f --- /dev/null +++ b/tests/lint/repository/test_workflow_fork_checkout_gated.py @@ -0,0 +1,77 @@ +from __future__ import annotations + +import re +import unittest + +from utils.cache.yaml import load_yaml_any + +from . import PROJECT_ROOT + +_WORKFLOWS_DIR = PROJECT_ROOT / ".github" / "workflows" +_GATE_JOB = "fork-trust-gate" +_UNSAFE_CALL_INPUT = "allow_unsafe_checkout" +_UNSAFE_STEP_INPUT = "allow-unsafe-pr-checkout" +_GATE_BYPASS = re.compile(r"\b(?:always|cancelled|failure)\(\s*\)") + + +def _listens_to_pull_request_target(document) -> bool: + triggers = document.get("on") or document.get(True) or {} + if isinstance(triggers, str): + return triggers == "pull_request_target" + return "pull_request_target" in triggers + + +def _enabled(value) -> bool: + return value not in (None, False, "false") + + +def _checks_out_pull_request_code(job: dict) -> bool: + if _enabled((job.get("with") or {}).get(_UNSAFE_CALL_INPUT)): + return True + return any( + _enabled((step.get("with") or {}).get(_UNSAFE_STEP_INPUT)) + for step in job.get("steps") or [] + if isinstance(step, dict) + ) + + +def _needs(job: dict) -> list[str]: + needs = job.get("needs") or [] + return [needs] if isinstance(needs, str) else list(needs) + + +def _offenders(name: str, document) -> list[str]: + offenders: list[str] = [] + for job_id, job in (document.get("jobs") or {}).items(): + if not isinstance(job, dict) or not _checks_out_pull_request_code(job): + continue + if _GATE_JOB not in _needs(job): + offenders.append(f"{name}: {job_id}: does not need it") + elif _GATE_BYPASS.search(str(job.get("if", ""))): + offenders.append(f"{name}: {job_id}: runs past a failed gate") + return offenders + + +class TestWorkflowForkCheckoutGated(unittest.TestCase): + def test_pull_request_checkouts_under_pull_request_target_need_the_gate( + self, + ) -> None: + offenders: list[str] = [] + for path in sorted(_WORKFLOWS_DIR.glob("*.y*ml")): + document = load_yaml_any(str(path), default_if_missing={}) or {} + if _listens_to_pull_request_target(document): + offenders.extend(_offenders(path.name, document)) + + if offenders: + self.fail( + f"{len(offenders)} pull_request_target job(s) check out pull " + f"request code without depending on a green '{_GATE_JOB}'. Such " + "a job runs fork content next to a write-scoped token, so it " + "must wait for the gate that refuses fork PRs lacking the " + "maintainer '🛡️ Trusted' label, and its if: must not use " + "always(), cancelled() or failure().\n" + "\n".join(offenders) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/javascript/roles/web-app-opencloud/files/playwright/test-design.test.js b/tests/unit/javascript/roles/web-app-opencloud/files/playwright/test-design.test.js new file mode 100644 index 0000000000..4606ba6255 --- /dev/null +++ b/tests/unit/javascript/roles/web-app-opencloud/files/playwright/test-design.test.js @@ -0,0 +1,82 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); + +const PROJECT_ROOT = path.resolve(__dirname, "../../../../../../.."); +const { loadInternals } = require(path.join(PROJECT_ROOT, "tests/unit/javascript/utils/internals.js")); + +const STYLESHEET = fs.readFileSync(path.join(PROJECT_ROOT, "roles/web-app-opencloud/templates/style.css.j2"), "utf8"); +const FILLED_CONTROLS = ":is(.oc-button-primary-filled, #exitAnchor)"; + +const noop = () => undefined; +const { ACCESS_DENIED_TEXTS } = loadInternals( + path.join(PROJECT_ROOT, "roles/web-app-opencloud/files/playwright/test-design.js"), + ["ACCESS_DENIED_TEXTS"], + { + "./onion-test": { test: Object.assign(noop, { use: noop, skip: noop }), expect: noop }, + "./_shared": { baseUrl: "https://opencloud.example.test/" }, + }, + {}, +); + +/** + * Args: + * css: role stylesheet template. + * selector: selector list of a rule that starts a line of the stylesheet. + * + * Returns: + * The declarations of that rule as a property to value map, or null when no rule has exactly this selector list. + */ +function declarations(css, selector) { + const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const rule = new RegExp(`(?:^|\\n)${escaped} \\{([^}]*)\\}`).exec(css); + if (!rule) return null; + return Object.fromEntries( + rule[1] + .split(";") + .map((declaration) => declaration.trim()) + .filter(Boolean) + .map((declaration) => declaration.split(/:\s*/, 2)), + ); +} + +test("the sign-in call to action of the access-denied page, secondary-filled since OpenCloud Web 8, takes the primary color and its on-color", () => { + assert.deepEqual(declarations(STYLESHEET, "#exitAnchor"), { + "--oc-button-color": "var(--design-primary)", + "--oc-button-on-color": "var(--design-on-primary)", + }); +}); + +test("the hovered or pressed call to action takes the hover and active shade of the primary color", () => { + assert.equal( + declarations(STYLESHEET, `${FILLED_CONTROLS}:hover:not([disabled], .no-hover)`)?.["background-color"], + "var(--design-primary-hover)", + ); + assert.equal( + declarations(STYLESHEET, `${FILLED_CONTROLS}:active:not([disabled])`)?.["background-color"], + "var(--design-primary-active)", + ); +}); + +test("a checked checkbox, which OpenCloud Web 8 fills with the secondary role, takes the primary color", () => { + assert.deepEqual(declarations(STYLESHEET, ".oc-checkbox:checked:not(:disabled)"), { + "border-color": "var(--design-primary)", + "background-color": "var(--design-primary)", + }); +}); + +test("the check and dash marks of a checkbox take the on-primary color without touching its focus outline", () => { + assert.equal( + declarations(STYLESHEET, '.oc-checkbox[type="checkbox"]:is(:checked, :indeterminate):not(:disabled)::before')?.[ + "background-color" + ], + "var(--design-on-primary)", + ); + assert.ok(!/--oc-role-on-secondary\s*:/.test(STYLESHEET)); +}); + +test("the access-denied readability check reads the card title inside the app, past the hidden browser-support card", () => { + assert.deepEqual([...ACCESS_DENIED_TEXTS], ["#exitAnchor", "#opencloud .oc-card h2"]); + assert.ok(ACCESS_DENIED_TEXTS.every((selector) => !selector.includes(".oc-login"))); +}); diff --git a/tests/unit/php/roles/web-app-moodle/files/build/ConfigTest.php b/tests/unit/php/roles/web-app-moodle/files/build/ConfigTest.php new file mode 100644 index 0000000000..74c5fca9b8 --- /dev/null +++ b/tests/unit/php/roles/web-app-moodle/files/build/ConfigTest.php @@ -0,0 +1,61 @@ + 'mariadb', + 'MOODLE_DB_HOST' => 'mariadb', + 'MOODLE_DB_NAME' => 'moodle', + 'MOODLE_DB_USER' => 'moodle', + 'MOODLE_DB_PASS' => 'secret', + 'MOODLE_DB_PREFIX' => 'mdl_', + 'MOODLE_DB_PORT' => '3306', + 'MOODLE_WWWROOT' => 'https://academy.example.test', + 'MOODLE_DATAROOT' => '/var/www/moodledata', + 'MOODLE_LOCALCACHEDIR' => '/var/cache/moodle', + 'MOODLE_REVERSEPROXY' => 'false', + 'MOODLE_SSLPROXY' => 'true', + 'MOODLE_EGRESS_BLOCKED_HOSTS' => '10.0.0.0/8', + 'MOODLE_EGRESS_ALLOWED_PORTS' => '443', + 'MOODLE_INTERNAL_HOST' => 'moodle', + 'MOODLE_OBJECTFS_ENABLED' => 'false', + ]; + + private string $root; + + protected function setUp(): void + { + $this->root = sys_get_temp_dir() . '/mdlconfig' . bin2hex(random_bytes(6)); + mkdir($this->root . '/lib', 0700, true); + copy(dirname(__DIR__, 7) . '/roles/web-app-moodle/files/build/config.php', $this->root . '/config.php'); + file_put_contents($this->root . '/lib/setup.php', "root . '/lib/setup.php'); + unlink($this->root . '/config.php'); + rmdir($this->root . '/lib'); + rmdir($this->root); + } + + public function testEveryReplicaReadsSessionsFromTheSharedDatabase(): void + { + $process = proc_open( + [PHP_BINARY, '-r', 'require $argv[1]; echo $CFG->session_handler_class ?? "";', $this->root . '/config.php'], + [1 => ['pipe', 'w'], 2 => ['redirect', 1]], + $pipes, + null, + self::ENV + ['PATH' => (string) getenv('PATH')] + ); + $output = (string) stream_get_contents($pipes[1]); + fclose($pipes[1]); + + $this->assertSame(0, proc_close($process), $output); + $this->assertSame('\core\session\database', $output); + } +} diff --git a/tests/unit/python/cli/contributing/update/__init__.py b/tests/unit/python/cli/contributing/update/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/cli/contributing/update/label/__init__.py b/tests/unit/python/cli/contributing/update/label/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/cli/contributing/update/label/test_main.py b/tests/unit/python/cli/contributing/update/label/test_main.py new file mode 100644 index 0000000000..4d9327e77f --- /dev/null +++ b/tests/unit/python/cli/contributing/update/label/test_main.py @@ -0,0 +1,137 @@ +from __future__ import annotations + +import io +import subprocess +import unittest +from contextlib import redirect_stdout +from unittest.mock import patch + +import cli.contributing.update.label.__main__ as label_main + +REPO = "infinito-nexus/core" + + +class FakeGh: + """Answers the label reads and records every write. + + Args: + repository: label names the repository has. + pull_request: label names pull request 4 carries. + racing: names whose create fails because a parallel run made them. + """ + + def __init__(self, repository, pull_request, racing=()): + self.repository = set(repository) + self.pull_request = set(pull_request) + self.racing = set(racing) + self.writes = [] + + def __call__(self, args): + if args[:2] == ["api", "--paginate"]: + names = self.pull_request if "/issues/" in args[2] else self.repository + return "".join(f"{name}\n" for name in sorted(names)) + self.writes.append(list(args)) + if args[:2] == ["label", "create"] and args[2] in self.racing: + self.repository.add(args[2]) + raise subprocess.CalledProcessError(1, ["gh", *args]) + return "" + + +class TestLevel(unittest.TestCase): + def test_semver_levels_map_to_their_label(self): + self.assertEqual( + [ + label_main.level(f"version-update:semver-{name}").name + for name in ("major", "minor", "patch") + ], + ["major", "minor", "patch"], + ) + + def test_an_unknown_or_empty_type_counts_as_major(self): + self.assertEqual( + {label_main.level(kind).name for kind in ("", "security", "semver-minor")}, + {"major"}, + ) + + +class TestSync(unittest.TestCase): + def test_a_bare_pull_request_gets_update_and_its_level(self): + gh = FakeGh({"update", "minor"}, set()) + actions = label_main.sync(gh, REPO, 4, "version-update:semver-minor") + self.assertEqual(actions, ["added update, minor"]) + self.assertEqual( + gh.writes, + [ + [ + "api", + "--method", + "POST", + f"repos/{REPO}/issues/4/labels", + "-f", + "labels[]=update", + "-f", + "labels[]=minor", + ] + ], + ) + + def test_labels_already_present_cause_no_write(self): + gh = FakeGh({"update", "patch"}, {"update", "patch", "dependencies"}) + self.assertEqual( + label_main.sync(gh, REPO, 4, "version-update:semver-patch"), [] + ) + self.assertEqual(gh.writes, []) + + def test_a_stale_level_is_removed(self): + gh = FakeGh({"update", "major", "minor"}, {"update", "minor"}) + actions = label_main.sync(gh, REPO, 4, "version-update:semver-major") + self.assertEqual(actions, ["removed minor", "added major"]) + + def test_missing_repository_labels_are_created_first(self): + gh = FakeGh(set(), set()) + label_main.sync(gh, REPO, 4, "version-update:semver-patch") + created = [write[2] for write in gh.writes if write[:2] == ["label", "create"]] + self.assertEqual(created, ["update", "patch"]) + + def test_a_label_a_parallel_run_created_counts_as_done(self): + gh = FakeGh({"patch"}, set(), racing={"update"}) + actions = label_main.sync(gh, REPO, 4, "version-update:semver-patch") + self.assertEqual(actions, ["added update, patch"]) + + def test_a_create_failure_that_leaves_the_label_missing_raises(self): + gh = FakeGh(set(), set()) + + def failing(args): + if args[:2] == ["label", "create"]: + raise subprocess.CalledProcessError(1, ["gh", *args]) + return gh(args) + + with self.assertRaises(subprocess.CalledProcessError): + label_main.sync(failing, REPO, 4, "") + + +class TestMain(unittest.TestCase): + def test_main_reports_when_nothing_changes(self): + gh = FakeGh({"update", "major"}, {"update", "major"}) + out = io.StringIO() + with patch.object(label_main, "run_gh", gh), redirect_stdout(out): + code = label_main.main(["--repo", REPO, "--pr", "4", "--update-type", ""]) + self.assertEqual((code, out.getvalue()), (0, "#4 already carries its labels\n")) + + def test_ensure_only_creates_the_missing_labels_and_touches_no_pr(self): + gh = FakeGh({"update", "minor"}, set()) + out = io.StringIO() + with patch.object(label_main, "run_gh", gh), redirect_stdout(out): + code = label_main.main(["--repo", REPO, "--ensure-only"]) + created = [w[2] for w in gh.writes if w[:2] == ["label", "create"]] + self.assertEqual((code, created), (0, ["major", "patch"])) + self.assertEqual(len(gh.writes), 2) + + def test_without_ensure_only_the_pr_and_type_are_required(self): + with self.assertRaises(SystemExit) as raised, redirect_stdout(io.StringIO()): + label_main.main(["--repo", REPO, "--pr", "4"]) + self.assertEqual(raised.exception.code, 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/contributing/update/merge/__init__.py b/tests/unit/python/cli/contributing/update/merge/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/cli/contributing/update/merge/test_gate.py b/tests/unit/python/cli/contributing/update/merge/test_gate.py new file mode 100644 index 0000000000..826aa062d0 --- /dev/null +++ b/tests/unit/python/cli/contributing/update/merge/test_gate.py @@ -0,0 +1,131 @@ +from __future__ import annotations + +import unittest + +from cli.contributing.update.merge import gate +from utils.roles.mapping import ROLE_FILE_META_SERVICES + +REPO = "infinito-nexus/core" + + +def pull_request(**overrides): + pr = { + "draft": False, + "user": {"login": "dependabot[bot]"}, + "head": {"ref": "dependabot/npm/left-pad-1.3.0", "repo": {"full_name": REPO}}, + "base": {"ref": "main"}, + "labels": [{"name": "update"}], + } + pr.update(overrides) + return pr + + +def check(**overrides): + run = { + "name": "🧹 Lint", + "status": "completed", + "conclusion": "success", + "details_url": "https://github.example/o/r/actions/runs/1/job/2", + } + run.update(overrides) + return run + + +class TestPullRequestRefusals(unittest.TestCase): + def test_an_update_bot_pull_request_passes(self): + self.assertEqual(gate.pull_request_refusals(pull_request(), REPO, "main"), []) + + def test_a_bot_outside_its_branch_prefix_is_refused(self): + head = {"ref": "update/sneaky", "repo": {"full_name": REPO}} + self.assertEqual( + gate.pull_request_refusals(pull_request(head=head), REPO, "main"), + ["branch update/sneaky lacks the dependabot/ prefix of dependabot[bot]"], + ) + + def test_a_head_in_another_repository_is_refused(self): + head = {"ref": "dependabot/npm/x", "repo": {"full_name": "fork/core"}} + refusals = gate.pull_request_refusals(pull_request(head=head), REPO, "main") + self.assertEqual( + refusals, [f"head branch dependabot/npm/x lives outside {REPO}"] + ) + + def test_a_deleted_head_repository_is_refused(self): + head = {"ref": "dependabot/npm/x", "repo": None} + refusals = gate.pull_request_refusals(pull_request(head=head), REPO, "main") + self.assertEqual(len(refusals), 1) + + def test_a_draft_is_refused(self): + refusals = gate.pull_request_refusals(pull_request(draft=True), REPO, "main") + self.assertEqual(refusals, ["pull request is a draft"]) + + def test_another_base_branch_is_refused(self): + base = {"ref": "release"} + refusals = gate.pull_request_refusals(pull_request(base=base), REPO, "main") + self.assertEqual(refusals, ["base branch is release, not main"]) + + +class TestCheckRefusals(unittest.TestCase): + def test_skipped_and_neutral_count_as_green(self): + runs = [check(conclusion="skipped"), check(conclusion="neutral")] + self.assertEqual(gate.check_refusals(runs, [], own_run_id=9), []) + + def test_no_check_run_at_all_refuses(self): + self.assertEqual( + gate.check_refusals([], [], own_run_id=9), + ["no check run on the head commit"], + ) + + def test_only_the_own_run_left_refuses(self): + own = check(details_url="https://github.example/o/r/actions/runs/9/job/3") + self.assertEqual( + gate.check_refusals([own], [], own_run_id=9), + ["no check run on the head commit"], + ) + + def test_a_pending_status_refuses(self): + statuses = [{"context": "ci/external", "state": "pending"}] + self.assertEqual( + gate.check_refusals([check()], statuses, own_run_id=9), + ["status ci/external is pending"], + ) + + +class TestRoles(unittest.TestCase): + def test_changed_roles_reads_the_role_directory(self): + paths = [ + f"roles/web-app-nextcloud/{ROLE_FILE_META_SERVICES}", + f"roles/sys-lint/{ROLE_FILE_META_SERVICES}", + "pyproject.toml", + "docs/roles/web-app-matomo.md", + ] + self.assertEqual(gate.changed_roles(paths), {"web-app-nextcloud", "sys-lint"}) + + def test_deployed_roles_unions_the_role_column(self): + first = "role,seconds\nweb-app-nextcloud,3.0\nsvc-db-postgres,1.0\n" + second = "round,role,seconds\n1,web-app-matomo,2.0\n1,,0.5\n" + self.assertEqual( + gate.deployed_roles([first, second]), + {"web-app-nextcloud", "svc-db-postgres", "web-app-matomo"}, + ) + + def test_a_csv_without_a_role_column_proves_nothing(self): + self.assertEqual(gate.deployed_roles(["name,seconds\nweb-app-x,1\n"]), set()) + + def test_no_changed_role_needs_no_proof(self): + self.assertEqual(gate.role_refusals(set(), []), []) + + def test_every_missing_role_is_named(self): + csv_text = "role,seconds\nweb-app-nextcloud,1.0\n" + self.assertEqual( + gate.role_refusals( + {"web-app-nextcloud", "web-app-a", "web-app-b"}, [csv_text] + ), + [ + "role web-app-a changed, but no deploy row ran it", + "role web-app-b changed, but no deploy row ran it", + ], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/contributing/update/merge/test_github.py b/tests/unit/python/cli/contributing/update/merge/test_github.py new file mode 100644 index 0000000000..effd757495 --- /dev/null +++ b/tests/unit/python/cli/contributing/update/merge/test_github.py @@ -0,0 +1,119 @@ +from __future__ import annotations + +import io +import json +import unittest +import zipfile +from unittest.mock import Mock + +from cli.contributing.update.merge import github +from utils.roles.mapping import ROLE_FILE_META_MAIN + +REPO = "infinito-nexus/core" +SHA = "b" * 40 + + +def lines(*objects): + return "\n".join(json.dumps(item) for item in objects).encode() + + +def archive(members): + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w") as zipped: + for name, data in members.items(): + zipped.writestr(name, data) + return buffer.getvalue() + + +class TestReads(unittest.TestCase): + def test_items_paginates_and_parses_one_object_per_line(self): + gh = Mock(return_value=lines({"a": 1}, {"a": 2}) + b"\n") + self.assertEqual(github.items(gh, "repos/x", ".[]"), [{"a": 1}, {"a": 2}]) + gh.assert_called_once_with(["api", "--paginate", "repos/x", "--jq", ".[]"]) + + def test_open_pull_requests_drop_closed_ones_and_other_heads(self): + prs = [ + {"number": 1, "state": "open", "head": {"sha": SHA}}, + {"number": 2, "state": "closed", "head": {"sha": SHA}}, + {"number": 3, "state": "open", "head": {"sha": "c" * 40}}, + ] + gh = Mock(return_value=lines(*prs)) + found = github.open_pull_requests(gh, REPO, SHA) + self.assertEqual([pr["number"] for pr in found], [1]) + + def test_changed_paths_keep_the_old_name_of_a_rename(self): + files = [ + { + "filename": f"roles/web-app-new/{ROLE_FILE_META_MAIN}", + "previous_filename": f"roles/web-app-old/{ROLE_FILE_META_MAIN}", + }, + {"filename": "pyproject.toml", "previous_filename": None}, + ] + gh = Mock(return_value=lines(*files)) + self.assertEqual( + github.changed_paths(gh, REPO, 5), + [ + f"roles/web-app-new/{ROLE_FILE_META_MAIN}", + f"roles/web-app-old/{ROLE_FILE_META_MAIN}", + "pyproject.toml", + ], + ) + + +class TestCsvMembers(unittest.TestCase): + def test_only_csv_members_are_read(self): + blob = archive({"a.csv": "role\nx\n", "notes.txt": "role\ny\n"}) + self.assertEqual(github.csv_members(blob), ["role\nx\n"]) + + def test_an_oversized_member_is_left_out(self): + big = "role\n" + "x" * (github.MAX_CSV_BYTES + 1) + blob = archive({"big.csv": big, "small.csv": "role\nx\n"}) + self.assertEqual(github.csv_members(blob), ["role\nx\n"]) + + def test_a_traversing_member_name_is_only_read_in_memory(self): + blob = archive({"../../etc/evil.csv": "role\nx\n"}) + self.assertEqual(github.csv_members(blob), ["role\nx\n"]) + + +class TestRoleRuntimeCsvs(unittest.TestCase): + def test_only_unexpired_role_runtimes_artifacts_are_downloaded(self): + artifacts = [ + { + "id": 1, + "name": "role-runtimes-web-app-a", + "expired": False, + "size_in_bytes": 10, + }, + { + "id": 2, + "name": "role-runtimes-web-app-b", + "expired": True, + "size_in_bytes": 10, + }, + { + "id": 3, + "name": "inventory-web-app-a", + "expired": False, + "size_in_bytes": 10, + }, + { + "id": 4, + "name": "role-runtimes-web-app-c", + "expired": False, + "size_in_bytes": github.MAX_ARTIFACT_BYTES + 1, + }, + ] + downloads = [] + + def gh(args): + if args[1] == "--paginate": + return lines(*artifacts) + downloads.append(args[1]) + return archive({"r.csv": "role\nweb-app-a\n"}) + + self.assertEqual(github.role_runtime_csvs(gh, REPO, 77), ["role\nweb-app-a\n"]) + self.assertEqual(downloads, [f"repos/{REPO}/actions/artifacts/1/zip"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/contributing/update/merge/test_main.py b/tests/unit/python/cli/contributing/update/merge/test_main.py new file mode 100644 index 0000000000..4a2522c5ac --- /dev/null +++ b/tests/unit/python/cli/contributing/update/merge/test_main.py @@ -0,0 +1,234 @@ +from __future__ import annotations + +import io +import json +import tempfile +import unittest +import zipfile +from contextlib import redirect_stderr, redirect_stdout +from pathlib import Path +from unittest.mock import patch + +import cli.contributing.update.merge.__main__ as merge_main +from cli.contributing.update.merge import github +from utils.roles.mapping import ROLE_FILE_META_SERVICES + +REPO = "infinito-nexus/core" +SHA = "a" * 40 +RUN_ID = 111 +OWN_RUN_ID = 222 +CSV_HEADER = "round,rounds_total,pass,pass_mode,role,seconds,hosts\n" + + +def pull_request(**overrides): + pr = { + "number": 7, + "state": "open", + "draft": False, + "user": {"login": "infinito-nexus-updater[bot]"}, + "head": { + "sha": SHA, + "ref": "update/docker-image-versions-20261121-abc1234", + "repo": {"full_name": REPO}, + }, + "base": {"ref": "main"}, + "labels": [{"name": "update"}, {"name": "minor"}], + } + pr.update(overrides) + return pr + + +def check(name="🔀 Pull Request / 🏁 Finish pipeline", **overrides): + run = { + "name": name, + "status": "completed", + "conclusion": "success", + "details_url": f"https://github.com/{REPO}/actions/runs/{RUN_ID}/job/1", + } + run.update(overrides) + return run + + +def role_runtimes(*roles): + rows = "".join(f",,,,{role},1.00,localhost=executed\n" for role in roles) + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w") as archive: + archive.writestr("role-runtimes-web-app-nextcloud.csv", CSV_HEADER + rows) + return buffer.getvalue() + + +class FakeGh: + """Answers the REST paths the merge gate reads, recording every call. + + Args: + prs: pull requests associated with ``SHA``. + checks: check runs on ``SHA``. + statuses: commit statuses on ``SHA``. + files: ``filename`` paths the pull request touches. + artifacts: ``{name: zip bytes}`` of the CI run's artifacts. + """ + + def __init__(self, prs, checks, statuses, files, artifacts): + self.routes = { + f"repos/{REPO}/commits/{SHA}/pulls": prs, + f"repos/{REPO}/commits/{SHA}/check-runs": checks, + f"repos/{REPO}/commits/{SHA}/status": statuses, + f"repos/{REPO}/pulls/7/files": [ + {"filename": path, "previous_filename": None} for path in files + ], + f"repos/{REPO}/actions/runs/{RUN_ID}/artifacts": [ + {"id": index, "name": name, "expired": False, "size_in_bytes": 512} + for index, name in enumerate(artifacts) + ], + } + self.blobs = dict(enumerate(artifacts.values())) + self.calls = [] + + def __call__(self, args): + self.calls.append(list(args)) + if args[1] == "--paginate": + route = args[2].split("?")[0] + return "\n".join(json.dumps(item) for item in self.routes[route]).encode() + artifact_id = int(args[1].split("/")[-2]) + return self.blobs[artifact_id] + + +def green_gh(**overrides): + fields = { + "prs": [pull_request()], + "checks": [check()], + "statuses": [{"context": "codecov", "state": "success"}], + "files": [f"roles/web-app-nextcloud/{ROLE_FILE_META_SERVICES}"], + "artifacts": { + "role-runtimes-web-app-nextcloud": role_runtimes( + "web-app-nextcloud", "svc-db-postgres" + ) + }, + } + fields.update(overrides) + return FakeGh(**fields) + + +def evaluate(gh): + return merge_main.evaluate(gh, REPO, SHA, RUN_ID, OWN_RUN_ID, "main") + + +class TestEvaluate(unittest.TestCase): + def test_all_green_and_every_changed_role_deployed_merges(self): + pr, refusals = evaluate(green_gh()) + self.assertEqual((pr["number"], refusals), (7, [])) + + def test_a_dependabot_pull_request_merges_like_the_updater(self): + dependabot = pull_request( + user={"login": "dependabot[bot]"}, + head={ + "sha": SHA, + "ref": "dependabot/pip/roles/web-app-nextcloud/files/requests-2.32.0", + "repo": {"full_name": REPO}, + }, + ) + self.assertEqual(evaluate(green_gh(prs=[dependabot]))[1], []) + + def test_a_non_bot_author_is_refused(self): + human = pull_request(user={"login": "octocat"}) + refusals = evaluate(green_gh(prs=[human]))[1] + self.assertEqual(refusals, ["author octocat is no update bot"]) + + def test_a_missing_update_label_is_refused(self): + unlabeled = pull_request(labels=[{"name": "minor"}]) + refusals = evaluate(green_gh(prs=[unlabeled]))[1] + self.assertEqual(refusals, ["label update is missing"]) + + def test_a_pending_check_refuses(self): + pending = check("🌐 Translate catalogs", status="in_progress", conclusion=None) + refusals = evaluate(green_gh(checks=[check(), pending]))[1] + self.assertEqual(refusals, ["check 🌐 Translate catalogs is in_progress"]) + + def test_a_failed_check_refuses(self): + failed = check("🔐 CodeQL", conclusion="failure") + refusals = evaluate(green_gh(checks=[check(), failed]))[1] + self.assertEqual(refusals, ["check 🔐 CodeQL concluded failure"]) + + def test_a_failed_commit_status_refuses(self): + statuses = [{"context": "codecov", "state": "failure"}] + refusals = evaluate(green_gh(statuses=statuses))[1] + self.assertEqual(refusals, ["status codecov is failure"]) + + def test_the_deciding_run_own_check_does_not_count(self): + own = check( + "🔀 Merge a proven update PR", + status="in_progress", + conclusion=None, + details_url=f"https://github.com/{REPO}/actions/runs/{OWN_RUN_ID}/job/9", + ) + self.assertEqual(evaluate(green_gh(checks=[check(), own]))[1], []) + + def test_a_changed_role_absent_from_role_runtimes_refuses(self): + artifacts = {"role-runtimes-web-app-matomo": role_runtimes("web-app-matomo")} + refusals = evaluate(green_gh(artifacts=artifacts))[1] + self.assertEqual( + refusals, ["role web-app-nextcloud changed, but no deploy row ran it"] + ) + + def test_no_role_runtimes_artifact_refuses(self): + artifacts = {"inventory-web-app-nextcloud": role_runtimes("web-app-nextcloud")} + refusals = evaluate(green_gh(artifacts=artifacts))[1] + self.assertEqual( + refusals, ["no role-runtimes artifact proves web-app-nextcloud"] + ) + + def test_a_pull_request_touching_no_role_needs_no_artifact(self): + gh = green_gh(files=[".github/workflows/call-lint.yml"], artifacts={}) + self.assertEqual(evaluate(gh)[1], []) + self.assertFalse(any("artifacts" in " ".join(call) for call in gh.calls)) + + def test_no_open_pull_request_for_the_head_refuses(self): + closed = pull_request(state="closed") + pr, refusals = evaluate(green_gh(prs=[closed])) + self.assertIsNone(pr) + self.assertEqual(refusals, [f"0 open pull requests have head {SHA}, not one"]) + + +class TestMain(unittest.TestCase): + def run_main(self, gh, sha=SHA): + with tempfile.TemporaryDirectory() as tmp: + output = Path(tmp) / "github_output" + argv = [ + "--repo", + REPO, + "--sha", + sha, + "--run-id", + str(RUN_ID), + "--own-run-id", + str(OWN_RUN_ID), + "--base", + "main", + "--output", + str(output), + ] + stdout = io.StringIO() + with patch.object(github, "run_gh", gh), redirect_stdout(stdout): + code = merge_main.main(argv) + with output.open(encoding="utf-8") as handle: + return code, handle.read(), stdout.getvalue() + + def test_a_merge_verdict_writes_pr_and_sha(self): + code, outputs, _ = self.run_main(green_gh()) + self.assertEqual((code, outputs), (0, f"merge=true\npr=7\nsha={SHA}\n")) + + def test_a_refusal_writes_merge_false_and_exits_zero(self): + gh = green_gh(checks=[check(conclusion="cancelled")]) + code, outputs, printed = self.run_main(gh) + self.assertEqual((code, outputs), (0, "merge=false\n")) + self.assertIn("stays open for a manual merge", printed) + + def test_a_short_sha_is_rejected_before_any_call(self): + gh = green_gh() + with self.assertRaises(SystemExit), redirect_stderr(io.StringIO()): + self.run_main(gh, sha="abc1234") + self.assertEqual(gh.calls, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/gha/test_split_runner_apps.py b/tests/unit/python/cli/gha/test_split_runner_apps.py index a3762f029f..a3ea8b7910 100644 --- a/tests/unit/python/cli/gha/test_split_runner_apps.py +++ b/tests/unit/python/cli/gha/test_split_runner_apps.py @@ -12,11 +12,25 @@ from . import PROJECT_ROOT SCRIPT = PROJECT_ROOT / "scripts" / "github" / "split_runner_apps.sh" -def _run(apps: list, self_hosted_count: int) -> dict: +def _fresh_step_env(**values: str) -> dict[str, str]: + """The environment of a new CI step: nothing the env loader exported. + + Args: + values: keys the step sets itself, as a workflow ``env:`` would. + + Returns: + The process environment without ``INFINITO_*`` keys, plus *values*. + """ + env = {k: v for k, v in os.environ.items() if not k.startswith("INFINITO_")} + env.update(values) + return env + + +def _run(apps: list, self_hosted_count: int, env: dict[str, str] | None = None) -> dict: with tempfile.NamedTemporaryFile(mode="r", suffix=".env", delete=False) as out_f: out_path = out_f.name try: - env = os.environ.copy() + env = os.environ.copy() if env is None else dict(env) env["APPS_JSON"] = json.dumps(apps) env["CI_SELF_HOSTED_RUNNER_COUNT"] = str(self_hosted_count) env["GITHUB_OUTPUT"] = out_path @@ -60,6 +74,17 @@ class TestSplitRunnerApps(unittest.TestCase): combined = out["apps_github"] + out["apps_self_hosted"] self.assertEqual(combined, ["only-app"]) + def test_an_empty_concurrency_splits_like_an_unset_one(self): + apps = list(range(40)) + self.assertEqual( + _run(apps, 20, _fresh_step_env(INFINITO_CI_CONCURRENCY="")), + _run(apps, 20, _fresh_step_env()), + ) + + def test_a_set_concurrency_drives_the_split(self): + out = _run(list(range(40)), 20, _fresh_step_env(INFINITO_CI_CONCURRENCY="500")) + self.assertEqual(len(out["apps_github"]), 40 * 500 // (500 + 20)) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/cli/meta/ci/test_chunks.py b/tests/unit/python/cli/meta/ci/test_chunks.py index e35b73192b..8317250209 100644 --- a/tests/unit/python/cli/meta/ci/test_chunks.py +++ b/tests/unit/python/cli/meta/ci/test_chunks.py @@ -102,5 +102,24 @@ class TestPlan(unittest.TestCase): self.assertEqual(chunks.plan([], [], size=80, blocks=3, budget=211), []) +class TestChunkBeyondTheBudget(unittest.TestCase): + def test_the_whole_budget_goes_into_one_regular_chunk(self) -> None: + plan = chunks.plan([], list(range(500)), size=2000, blocks=4, budget=203) + self.assertEqual([len(c) for c in plan], [203]) + + def test_a_short_priority_chunk_strands_no_row_of_the_budget(self) -> None: + plan = chunks.plan( + list(range(7)), list(range(100, 600)), size=2000, blocks=4, budget=203 + ) + self.assertEqual([len(c) for c in plan], [7, 196]) + self.assertEqual(plan[0], list(range(7))) + + def test_priority_beyond_the_budget_fills_one_chunk_up_to_the_cap(self) -> None: + plan = chunks.plan( + list(range(300)), list(range(50)), size=2000, blocks=4, budget=203 + ) + self.assertEqual([len(c) for c in plan], [203]) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/cli/meta/ci/test_runtime_vulnerabilities.py b/tests/unit/python/cli/meta/ci/test_runtime_vulnerabilities.py index 7299a44aaf..fbb5d54ea4 100644 --- a/tests/unit/python/cli/meta/ci/test_runtime_vulnerabilities.py +++ b/tests/unit/python/cli/meta/ci/test_runtime_vulnerabilities.py @@ -2,6 +2,7 @@ from __future__ import annotations import datetime as dt import json +import re import tempfile import unittest from pathlib import Path @@ -370,23 +371,47 @@ class TestMainGuard(unittest.TestCase): self.assertEqual(gh.calls[0][:2], ["run", "download"]) self.assertIn(f"opened {NGINX_TITLE}", actions) - def guarded(self, job): - step = next( + @staticmethod + def report_job(): + workflow = PROJECT_ROOT / ".github" / "workflows" / "call-orchestrator.yml" + return load_yaml(str(workflow))["jobs"]["report-main-failures"] + + @staticmethod + def sync_step(job): + return next( step for step in job["steps"] if "runtime_vulnerabilities" in step.get("run", "") ) + + def guarded(self, job): return ( "github.ref == 'refs/heads/main'" in job["if"] - and '--ref "${GITHUB_REF}"' in step["run"] + and '--ref "${GITHUB_REF}"' in self.sync_step(job)["run"] ) def test_the_workflow_job_runs_only_on_main_and_hands_the_ref_on(self): - workflow = PROJECT_ROOT / ".github" / "workflows" / "call-orchestrator.yml" - job = load_yaml(str(workflow))["jobs"]["report-main-failures"] + job = self.report_job() self.assertTrue(self.guarded(job)) self.assertFalse(self.guarded({**job, "if": "${{ always() }}"})) + @staticmethod + def sync_runs(condition, results): + wanted = re.findall(r"contains\(needs\.\*\.result, '(\w+)'\)", condition) + return not wanted or any(result in wanted for result in results) + + def test_the_sync_runs_only_after_a_deploy_chunk_ran(self): + job = self.report_job() + condition = self.sync_step(job)["if"] + skipped = ["skipped"] * len(job["needs"]) + self.assertFalse(self.sync_runs(condition, skipped)) + for result in ("success", "failure", "cancelled"): + self.assertTrue(self.sync_runs(condition, [result, *skipped[1:]])) + + def test_negative_control_an_unguarded_sync_runs_without_any_deploy(self): + skipped = ["skipped"] * len(self.report_job()["needs"]) + self.assertTrue(self.sync_runs("${{ !cancelled() }}", skipped)) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/cli/meta/ci/test_slots.py b/tests/unit/python/cli/meta/ci/test_slots.py index 6beeff7b76..4097b64377 100644 --- a/tests/unit/python/cli/meta/ci/test_slots.py +++ b/tests/unit/python/cli/meta/ci/test_slots.py @@ -8,6 +8,8 @@ from pathlib import Path from tempfile import TemporaryDirectory from cli.meta.ci import slots +from utils.cache.files import PROJECT_ROOT +from utils.env.parser import parse_static_env _SETTINGS = { "INFINITO_CI_JOB_LIMIT": "256", @@ -185,6 +187,42 @@ class TestChunkArithmetic(unittest.TestCase): root = Path(tmp) self.assertLessEqual(slots.rows_per_sweep(root), slots.available(root)) + def test_enterprise_concurrency_leaves_the_job_cap_as_the_only_limit( + self, + ) -> None: + with ( + _tree() as tmp, + mock.patch.dict( + "os.environ", + { + **_SETTINGS, + "INFINITO_CI_CONCURRENCY": "500", + "INFINITO_CI_CHUNK_SIZE": "0", + }, + ), + ): + root = Path(tmp) + self.assertGreater(slots.chunk_size(root), slots.available(root)) + self.assertEqual(slots.chunk_count(root), 1) + self.assertEqual(slots.rows_per_sweep(root), slots.available(root)) + + +class TestConcurrencySetting(unittest.TestCase): + def test_an_empty_or_blank_value_falls_back_to_default_env(self) -> None: + declared = int( + parse_static_env(PROJECT_ROOT / "default.env")["INFINITO_CI_CONCURRENCY"] + ) + for raw in ("", " "): + with ( + self.subTest(raw=raw), + mock.patch.dict("os.environ", {"INFINITO_CI_CONCURRENCY": raw}), + ): + self.assertEqual(slots.setting("INFINITO_CI_CONCURRENCY"), declared) + + def test_a_set_value_wins_over_default_env(self) -> None: + with mock.patch.dict("os.environ", {"INFINITO_CI_CONCURRENCY": "500"}): + self.assertEqual(slots.setting("INFINITO_CI_CONCURRENCY"), 500) + class TestRenderMatrix(unittest.TestCase): def test_table_lists_every_job_and_the_chunk_arithmetic(self) -> None: diff --git a/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_policy.py b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_policy.py index c04c092e7a..6c25e26256 100644 --- a/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_policy.py +++ b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_policy.py @@ -111,6 +111,28 @@ class TestLoadContract(unittest.TestCase): ) +class TestUpstreamHost(unittest.TestCase): + def test_an_undeclared_host_keeps_the_url_host(self): + self.assertEqual("", policy.upstream_host(contract())) + + def test_a_declared_host_is_returned(self): + loaded = policy.load_contract( + json.dumps(contract(upstream_host="assets.example.org")) + ) + self.assertEqual("assets.example.org", policy.upstream_host(loaded)) + + def test_a_host_with_a_port_is_accepted(self): + self.assertEqual( + "assets.example.org:8443", + policy.upstream_host(contract(upstream_host="assets.example.org:8443")), + ) + + def test_a_malformed_host_is_refused_at_startup(self): + for host in ("", "assets.example.org\r\nX-Injected: 1", "a.org/path", 7): + with self.subTest(host=host), self.assertRaises(policy.ContractError): + policy.load_contract(json.dumps(contract(upstream_host=host))) + + class TestDrift(unittest.TestCase): def test_a_matching_hash_passes(self): policy.assert_no_drift(contract()) @@ -190,6 +212,17 @@ class TestLimits(unittest.TestCase): self.assertEqual(5, len(policy.truncate_results(contract(), list(range(50))))) +class TestRequestLength(unittest.TestCase): + def test_a_missing_header_announces_no_body(self): + self.assertEqual(policy.request_length(None), 0) + + def test_a_numeric_header_is_the_byte_count(self): + self.assertEqual(policy.request_length("12"), 12) + + def test_a_non_numeric_header_is_negative(self): + self.assertLess(policy.request_length("abc"), 0) + + class TestDeclaredArguments(unittest.TestCase): """A published input schema is enforced, not merely advertised. diff --git a/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_server.py b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_server.py index 5d767bbd8f..3fc0a71c94 100644 --- a/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_server.py +++ b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_server.py @@ -29,11 +29,14 @@ LIMITS = { } -def load(): +def load(**overrides): """Import the adapter server the way the image lays it out. ``server.py`` imports ``policy`` as a sibling, so its own directory has to be importable before the module body runs. + + Args: + overrides: contract keys added to or replacing the default contract. """ spec = importlib.util.spec_from_file_location("adapter_server", MODULE_PATH) module = importlib.util.module_from_spec(spec) @@ -48,6 +51,7 @@ def load(): "tools": TOOLS, "limits": LIMITS, "schema_sha256": policy.schema_digest(TOOLS), + **overrides, } env = { "ADAPTER_CONTRACT": json.dumps(contract), @@ -180,6 +184,33 @@ class TestFixedTarget(unittest.TestCase): ) +class TestUpstreamHost(unittest.TestCase): + def _sent(self, module): + seen = {} + + def fake_open(request, **_kwargs): + seen["host"] = request.get_header("Host") + seen["url"] = request.full_url + return FakeResponse() + + spec = module.CONTRACT["tools"]["example_list"] + with patch.object(module.OPENER, "open", fake_open): + module.call_upstream(spec["method"], spec["path"], {}) + return seen + + def test_a_declared_upstream_host_is_sent_as_the_host_header(self): + seen = self._sent(load(upstream_host="assets.example.org")) + self.assertEqual("assets.example.org", seen["host"]) + self.assertEqual("http://example:80/api/things", seen["url"]) + + def test_without_upstream_host_no_host_header_is_forced(self): + self.assertIsNone(self._sent(load())["host"]) + + def test_a_malformed_upstream_host_refuses_to_start(self): + with self.assertRaises(ValueError): + load(upstream_host="assets.example.org\r\nX-Injected: 1") + + class TestConcurrencyCeiling(unittest.TestCase): """The declared ``concurrent_requests`` is refused past, not just declared. @@ -257,5 +288,35 @@ class TestConcurrencyCeiling(unittest.TestCase): self.assertEqual(200, recorder.status) +class TestContentLength(unittest.TestCase): + def setUp(self): + self.module = load() + + def _handle(self, content_length): + handler = self.module.Handler.__new__(self.module.Handler) + recorder = Recorder() + handler.send_response = recorder.send_response + handler.send_header = recorder.send_header + handler.end_headers = recorder.end_headers + handler.wfile = type("W", (), {"write": lambda _s, _data: None})() + handler.path = self.module.ENDPOINT + reads = [] + handler.rfile = type( + "R", (), {"read": lambda _s, n: reads.append(n) or b"{}"} + )() + handler.headers = { + "Content-Length": content_length, + "Authorization": "Bearer real", + } + handler.do_POST() + return recorder.status, reads + + def test_a_negative_length_is_refused_before_any_read(self): + self.assertEqual(self._handle("-1"), (400, [])) + + def test_a_non_numeric_length_is_refused_before_any_read(self): + self.assertEqual(self._handle("abc"), (400, [])) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/roles/svc-opt-ssd-hdd/test_storage_optimizer.py b/tests/unit/python/roles/svc-opt-ssd-hdd/test_storage_optimizer.py index 7b9c2942a1..cb47632431 100644 --- a/tests/unit/python/roles/svc-opt-ssd-hdd/test_storage_optimizer.py +++ b/tests/unit/python/roles/svc-opt-ssd-hdd/test_storage_optimizer.py @@ -1,5 +1,6 @@ import importlib.util import sys +import time import unittest from unittest.mock import patch @@ -28,8 +29,8 @@ storage_optimizer = load_optimizer_module() class TestHealthCheckLogic(unittest.TestCase): def setUp(self): patcher = patch("storage_optimizer.time.sleep", return_value=None) - self.sleep_patcher = patcher.start() - self.addCleanup(self.sleep_patcher.stop) + patcher.start() + self.addCleanup(patcher.stop) @patch("storage_optimizer.run_command") def test_has_healthcheck_true(self, mock_run): @@ -84,5 +85,12 @@ class TestIsDatabase(unittest.TestCase): ) +class TestSleepPatchEndsWithItsTest(unittest.TestCase): + def test_time_sleep_is_real_again_after_a_health_check_test(self): + real_sleep = time.sleep + TestHealthCheckLogic("test_has_healthcheck_true").run() + self.assertIs(time.sleep, real_sleep) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py b/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py index 3d9ffff556..1c6c0d4605 100644 --- a/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py +++ b/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py @@ -1944,6 +1944,20 @@ class TestCommands(TestCase): step = SCRIPT.trivy_step(self.layout, "trivy:1", self.container, _config(), []) self.assertIn("/var/run/docker.sock:/var/run/docker.sock:ro", step.argv) + def test_every_trivy_run_ends_only_at_the_job_bound(self): + steps = [ + SCRIPT.trivy_step(self.layout, "trivy:1", self.container, _config(), []), + SCRIPT.trivy_step(self.layout, "trivy:1", self.host, _config(), []), + *SCRIPT.db_steps("trivy", self.layout, "trivy:1"), + ] + for step in steps: + with self.subTest(step=step.label): + self.assertIn("--timeout", step.argv) + self.assertEqual( + step.argv[step.argv.index("--timeout") + 1], + f"{SCRIPT.JOB_TIMEOUT_SECONDS}s", + ) + def test_the_host_scan_skips_the_excluded_paths(self): step = SCRIPT.trivy_step(self.layout, "trivy:1", self.host, _config(), []) self.assertEqual( diff --git a/tests/unit/python/roles/sys-front-tls/templates/test_nginx_ssl_header.py b/tests/unit/python/roles/sys-front-tls/templates/test_nginx_ssl_header.py index e0b710bfe1..16bf355c39 100644 --- a/tests/unit/python/roles/sys-front-tls/templates/test_nginx_ssl_header.py +++ b/tests/unit/python/roles/sys-front-tls/templates/test_nginx_ssl_header.py @@ -6,6 +6,7 @@ import unittest from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape from plugins.filter.security_headers import FilterModule +from utils.cache.yaml import load_yaml from utils.tls_common import resolve_enabled from . import PROJECT_ROOT @@ -26,12 +27,13 @@ PRIMARY_DOMAINS = { } -def render(application_id: str, override: dict) -> str: +def render(application_id: str, override: dict, http2: bool = False) -> str: """Return the TLS server header of one vhost. Args: application_id: the app the vhost belongs to, or a redirect domain. override: the app's ``server.security_headers`` block. + http2: the value of ``WEBSERVER_HTTP2_ENABLED``. """ applications = { app: {"server": {"security_headers": override}} @@ -65,6 +67,7 @@ def render(application_id: str, override: dict) -> str: domain=PRIMARY_DOMAINS[application_id], lookup=lookup, WEBSERVER_SECURITY_HEADERS=PLATFORM, + WEBSERVER_HTTP2_ENABLED=http2, ) @@ -110,5 +113,17 @@ class TestCookieFlags(unittest.TestCase): self.assertNotIn("proxy_cookie_flags", render("web-app-x", {})) +class TestHttp2(unittest.TestCase): + def test_a_tls_vhost_serves_no_http2_while_the_switch_is_off(self): + self.assertNotIn("http2", render("web-app-x", {})) + + def test_a_tls_vhost_serves_http2_once_the_switch_is_on(self): + self.assertIn("\nhttp2 on;\n", render("web-app-x", {}, http2=True)) + + def test_the_platform_default_keeps_http2_off(self): + defaults = load_yaml(PROJECT_ROOT / "group_vars/all/04_webserver.yml") + self.assertIs(defaults["WEBSERVER_HTTP2_ENABLED"], False) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/roles/web-app-erpnext/files/apply/_fake_frappe.py b/tests/unit/python/roles/web-app-erpnext/files/apply/_fake_frappe.py index e2f2b6bbde..5837207a3f 100644 --- a/tests/unit/python/roles/web-app-erpnext/files/apply/_fake_frappe.py +++ b/tests/unit/python/roles/web-app-erpnext/files/apply/_fake_frappe.py @@ -24,6 +24,7 @@ CHILD_TABLES = {"Fiscal Year": ("companies",), "User": ("roles",)} NAME_FIELDS = { "Company": "company_name", "Customer Group": "customer_group_name", + "Email Account": "email_account_name", "Fiscal Year": "year", "Item Group": "item_group_name", "Price List": "price_list_name", @@ -101,6 +102,17 @@ class FakeDoc: self._values["name"] = self._frappe.insert(self.doctype, self._values) return self + def is_new(self): + return not self._values.get("name") + + def db_insert(self): + return self.insert() + + def db_update(self): + self._frappe.records[self.doctype][self._values["name"]] = copy.deepcopy( + self._values + ) + def save(self, ignore_permissions=False): if self._single: self._frappe.singles[self.doctype] = copy.deepcopy(self._values) diff --git a/tests/unit/python/roles/web-app-erpnext/files/apply/test_email_account.py b/tests/unit/python/roles/web-app-erpnext/files/apply/test_email_account.py new file mode 100644 index 0000000000..ce1c1b8a11 --- /dev/null +++ b/tests/unit/python/roles/web-app-erpnext/files/apply/test_email_account.py @@ -0,0 +1,94 @@ +from __future__ import annotations + +import unittest + +from . import PROJECT_ROOT +from ._fake_frappe import FakeFrappe, run_script + +SCRIPT = PROJECT_ROOT / "roles/web-app-erpnext/files/python/apply/email_account.py" +ACCOUNT = "Email Account" +NAME = "ERPNext Outbound" + + +def _env(*, port, tls, start_tls, auth): + return { + "SITE_NAME": "next.erp.infinito.example", + "MAIL_FROM_NAME": "Infinito ERPNext", + "MAIL_FROM_ADDRESS": "no-reply@infinito.example", + "SMTP_HOST": "mail.infinito.example", + "SMTP_PORT": str(port), + "SMTP_TLS": str(tls).lower(), + "SMTP_START_TLS": str(start_tls).lower(), + "SMTP_AUTH": str(auth).lower(), + "SMTP_USER": "no-reply@infinito.example", + "SMTP_PASS": "submission-token", + } + + +class TestEmailAccount(unittest.TestCase): + def setUp(self) -> None: + self.frappe = FakeFrappe() + + def _account(self, **transport): + run_script(SCRIPT, self.frappe, _env(**transport)) + return self.frappe.records[ACCOUNT][NAME] + + def _run(self, **transport): + account = self._account(**transport) + return ( + account.get("smtp_port"), + account.get("use_ssl_for_outgoing"), + account.get("use_tls"), + ) + + def test_an_implicit_tls_relay_opens_the_session_inside_tls(self) -> None: + self.assertEqual( + (465, 1, 0), self._run(port=465, tls=True, start_tls=False, auth=True) + ) + + def test_a_starttls_relay_upgrades_a_plain_session(self) -> None: + self.assertEqual( + (587, 0, 1), self._run(port=587, tls=True, start_tls=True, auth=True) + ) + + def test_a_relay_without_tls_speaks_plain_smtp(self) -> None: + self.assertEqual( + (25, 0, 0), self._run(port=25, tls=False, start_tls=False, auth=False) + ) + + def test_a_relay_that_takes_no_login_is_sent_to_without_smtp_auth(self) -> None: + account = self._account(port=25, tls=False, start_tls=False, auth=False) + + self.assertEqual(1, account.get("no_smtp_authentication")) + + def test_a_relay_that_takes_a_login_is_sent_to_with_smtp_auth(self) -> None: + account = self._account(port=465, tls=True, start_tls=False, auth=True) + + self.assertEqual(0, account.get("no_smtp_authentication")) + + def test_an_account_left_on_starttls_converges_to_the_relay_transport( + self, + ) -> None: + self.frappe.seed( + ACCOUNT, + NAME, + email_account_name=NAME, + smtp_port=465, + use_ssl_for_outgoing=0, + use_tls=1, + ) + + transport = self._run(port=465, tls=True, start_tls=False, auth=True) + + self.assertEqual((465, 1, 0), transport) + self.assertEqual([NAME], list(self.frappe.records[ACCOUNT])) + + def test_the_account_is_committed_and_the_site_closed(self) -> None: + self._run(port=465, tls=True, start_tls=False, auth=True) + + self.assertTrue(self.frappe.db.committed) + self.assertEqual(("destroy",), self.frappe.calls[-1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-joomla/files/__init__.py b/tests/unit/python/roles/web-app-joomla/files/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-joomla/files/shell/__init__.py b/tests/unit/python/roles/web-app-joomla/files/shell/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-joomla/files/shell/test_docker_entrypoint_joomla.py b/tests/unit/python/roles/web-app-joomla/files/shell/test_docker_entrypoint_joomla.py new file mode 100644 index 0000000000..411f8b2ee9 --- /dev/null +++ b/tests/unit/python/roles/web-app-joomla/files/shell/test_docker_entrypoint_joomla.py @@ -0,0 +1,255 @@ +import contextlib +import os +import signal +import subprocess +import tempfile +import time +import unittest +from pathlib import Path + +from utils import PROJECT_ROOT + +SHELL_DIR = PROJECT_ROOT / "roles/web-app-joomla/files/shell" +ENTRYPOINT = SHELL_DIR / "docker-entrypoint-joomla.sh" +SERVE = "serve apache2-foreground" + +STOCK_STUB = """#!/usr/bin/env bash +printf 'call %s\\n' "$*" >> "${STUB_CALLS}" +case "$1" in apache2*) ;; *) exit 0 ;; esac +case "${2-}" in -v | -V | -h | -t | -T) exit 0 ;; esac +cd "${JOOMLA_WEBROOT}" || exit 9 +if [ -e .joomla-initializing ]; then + echo '[ERROR] Initialization is incomplete or another initializer is active.' >&2 + exit 1 +fi +if [ ! -s configuration.php ]; then + if [ "${STUB_DB}" != up ]; then + echo '[ERROR] Database initialization failed (exit 1).' >&2 + exit 1 + fi + mkdir .joomla-initializing + printf 'init\\n' >> "${STUB_CALLS}" + mkdir -p installation + touch index.php installation/joomla.php joomla.xml robots.txt.dist + sleep "${STUB_SETUP_DELAY}" + if [ "${STUB_INSTALL}" = broken ]; then + echo '[ERROR] Automatic Joomla installation failed (exit 1).' >&2 + exit 1 + fi + echo ' configuration.php + sleep "${STUB_FINISH_DELAY}" + case "${STUB_INSTALL}" in + crash) + echo '[ERROR] Automatic Joomla installation failed (exit 255).' >&2 + exit 1 ;; + nfs) + echo ' [ERROR] Unable to delete installation folder!' + exit 1 ;; + nfs-unowned) + echo ' [ERROR] Unable to delete installation folder!' + echo '[ERROR] Failed to correct ownership after initialization.' >&2 + exit 1 ;; + esac + rm -rf installation joomla.xml + mv robots.txt.dist robots.txt + rmdir .joomla-initializing +fi +printf 'serve %s\\n' "$*" >> "${STUB_CALLS}" +""" + +RM_STUB = """#!/usr/bin/env bash +if [ "${STUB_RM_FAIL}" = 1 ]; then + case "$*" in *installation*) echo 'rm: Device or resource busy' >&2; exit 1 ;; esac +fi +PATH="${STUB_REAL_PATH}" exec rm "$@" +""" + + +class TestJoomlaEntrypoint(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.webroot = self.root / "html" + self.webroot.mkdir() + bin_dir = self.root / "bin" + bin_dir.mkdir() + self.stock = self.root / "entrypoint.sh" + for path, body in {self.stock: STOCK_STUB, bin_dir / "rm": RM_STUB}.items(): + path.write_text(body) + path.chmod(0o755) + self.ready = self.webroot / ".infinito-init.ready" + self.marker = self.webroot / ".joomla-initializing" + self.lock = self.webroot / ".infinito-init.lock" + self.pending = self.webroot / ".infinito-init.cleanup" + self.env = { + **os.environ, + "PATH": f"{bin_dir}{os.pathsep}{os.environ['PATH']}", + "STUB_REAL_PATH": os.environ["PATH"], + "JOOMLA_WEBROOT": str(self.webroot), + "JOOMLA_STOCK_ENTRYPOINT": str(self.stock), + "JOOMLA_INIT_READY_FILE": str(self.ready), + "JOOMLA_INIT_LOCK_STALE_SECONDS": "60", + "STUB_DB": "up", + "STUB_INSTALL": "ok", + "STUB_SETUP_DELAY": "0", + "STUB_FINISH_DELAY": "0", + "STUB_RM_FAIL": "0", + } + + def spawn(self, name, **env): + log = self.root / f"{name}.log" + log.touch() + with (self.root / f"{name}.err").open("a") as err: + process = subprocess.Popen( + ["bash", str(ENTRYPOINT), "apache2-foreground"], + env={**self.env, "STUB_CALLS": str(log), **env}, + stdout=subprocess.DEVNULL, + stderr=err, + start_new_session=True, + ) + self.addCleanup(self.kill_group, process) + return process + + def kill_group(self, process): + with contextlib.suppress(ProcessLookupError, PermissionError): + os.killpg(process.pid, signal.SIGKILL) + process.wait() + + def run_entrypoint(self, **env): + return self.spawn("calls", **env).wait(timeout=60) + + def text(self, name): + path = self.root / name + return path.read_text(encoding="utf-8") # nocheck: cache-read tempdir + + def calls(self, name): + return self.text(f"{name}.log").splitlines() + + def wait_for(self, path): + deadline = time.monotonic() + 30 + while not path.exists() and time.monotonic() < deadline: + time.sleep(0.1) + self.assertTrue(path.exists()) + + def leave_stuck_volume(self): + for name in ("installation", ".joomla-initializing", ".infinito-init.lock"): + (self.webroot / name).mkdir() + (self.webroot / "configuration.php").write_text(" dict[str, str]: + """ + Args: + template: file name of a PHP template under the role's templates/. + + Returns: + every extension the template loads, mapped to the conditions of the + blocks around its wfLoadExtension call, with the template's string + variables written out. + """ + php = JINJA.sub("", read_text(str(ROLE / "templates" / template))) + variables = dict(ASSIGNMENT.findall(php)) + loads: dict[str, str] = {} + headers: list[str] = [] + start = 0 + for match in SYNTAX.finditer(php): + symbol = match.group(0) + if match.group(1): + loads[match.group(1)] = " ".join(headers) + continue + if symbol == "{": + headers.append(php[start : match.start()]) + elif symbol == "}": + headers.pop() + start = match.end() + for name, value in variables.items(): + pattern = re.compile(re.escape(name) + r"(?!\w)") + loads = { + ext: pattern.sub(lambda _match, value=value: f'"{value}"', guard) + for ext, guard in loads.items() + } + return loads + + +class TestComposerAutoloaderGate(unittest.TestCase): + def test_composer_autoloaded_extensions_wait_for_their_vendor_tree(self) -> None: + for extension, template in COMPOSER_AUTOLOADED.items(): + with self.subTest(extension=extension): + guard = _guards(template)[extension] + self.assertRegex( + guard, + rf'file_exists\(\s*"\$IP/extensions/{extension}/vendor/autoload\.php"\s*\)', + f"{extension} declares load_composer_autoloader, and MediaWiki's " + "ExtensionRegistry caches per replica for a day whether its " + "vendor/autoload.php existed when the extension was first queued, " + "so loading it before composer finished leaves that replica " + "without the extension's composer classes", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-weblate/files/test_adopt_admin.py b/tests/unit/python/roles/web-app-weblate/files/test_adopt_admin.py new file mode 100644 index 0000000000..25dc820c64 --- /dev/null +++ b/tests/unit/python/roles/web-app-weblate/files/test_adopt_admin.py @@ -0,0 +1,370 @@ +from __future__ import annotations + +import contextlib +import io +import os +import runpy +import sys +import unittest +import unittest.mock +from types import ModuleType + +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar + +from utils.cache.files import PROJECT_ROOT +from utils.cache.yaml import load_yaml_any +from utils.templating.ansible import _trust_as_template + +SCRIPT = PROJECT_ROOT / "roles/web-app-weblate/files/python/adopt_admin.py" +TOKEN_TASKS = PROJECT_ROOT / "roles/web-app-weblate/tasks/utils/token.yml" +SUBJECT_INCLUDE = "utils/admin_oidc_subject.yml" +SUBJECT_TASKS = PROJECT_ROOT / "roles/web-app-weblate/tasks" / SUBJECT_INCLUDE +SUBJECT_FACT = "weblate_admin_oidc_subjects" +STOP_MARKER = "ADOPT_REFUSED" +ADMIN = "platformadmin" +SUBJECT = "4f1c2b8e-9d3a-4e57-8a61-0c2d5e7f9b10" +OTHER_SUBJECT = "a0b1c2d3-e4f5-4a6b-8c7d-9e0f1a2b3c4d" +JVM_NOISE = ( + "[0.001s][warning][os,container] Cgroup memory controller path at " + "'/sys/fs/cgroup' seems to have moved, detected limits won't be accurate" +) + + +def _matches(row, lookups: dict) -> bool: + return all(getattr(row, key) == value for key, value in lookups.items()) + + +class FakeQuerySet: + """The QuerySet calls ``adopt_admin.py`` makes. + + Args: + rows: the model instances the queryset holds. + """ + + def __init__(self, rows): + self._rows = list(rows) + + def filter(self, **lookups) -> FakeQuerySet: + return FakeQuerySet(row for row in self._rows if _matches(row, lookups)) + + def exclude(self, **lookups) -> FakeQuerySet: + return FakeQuerySet(row for row in self._rows if not _matches(row, lookups)) + + def first(self): + return self._rows[0] if self._rows else None + + def exists(self) -> bool: + return bool(self._rows) + + def get(self, **lookups): + found = self.filter(**lookups)._rows + if len(found) != 1: + raise LookupError(f"{len(found)} rows match {lookups}") + return found[0] + + +class FakeManager: + """A model manager over an in-memory table. + + Args: + model: the class ``create`` instantiates. + unique: field names that must be unique together, as ``unique_together``. + """ + + def __init__(self, model, unique: tuple[str, ...] = ()): + self.model = model + self.unique = unique + self.rows: list = [] + + def filter(self, **lookups) -> FakeQuerySet: + return FakeQuerySet(self.rows).filter(**lookups) + + def get(self, **lookups): + return FakeQuerySet(self.rows).get(**lookups) + + def create(self, **fields): + key = {name: fields[name] for name in self.unique} + if self.unique and FakeQuerySet(self.rows).filter(**key).exists(): + raise ValueError(f"unique constraint violated for {key}") + row = self.model(**fields) + self.rows.append(row) + return row + + +class FakeUser: + """``weblate.auth.models.User`` reduced to what the adoption touches. + + Args: + pk: primary key. + username: login name. + usable_password: whether ``has_usable_password`` answers True. + """ + + objects: FakeManager + + def __init__(self, pk: int, username: str, *, usable_password: bool = True): + self.pk = pk + self.username = username + self.usable_password = usable_password + + def save(self, update_fields) -> None: + self.saved = tuple(update_fields) + + def has_usable_password(self) -> bool: + return self.usable_password + + def set_unusable_password(self) -> None: + self.usable_password = False + + +class FakeSocial: + """``social_django.models.UserSocialAuth`` of social-auth-app-django 7.2. + + Args: + user: the owning account. + provider: backend name. + uid: the identifier the backend reports. + id_key: the claim ``uid`` was read from; ``social_user`` filters on it. + """ + + objects: FakeManager + + def __init__(self, user, provider: str, uid: str, id_key: str = ""): + self.user = user + self.provider = provider + self.uid = uid + self.id_key = id_key + + @property + def user_id(self) -> int: + return self.user.pk + + def save(self, update_fields) -> None: + self.saved = tuple(update_fields) + + +class Database: + """Fresh model classes and tables, one per test.""" + + def __init__(self): + self.User = type("User", (FakeUser,), {}) + self.User.objects = FakeManager(self.User) + self.UserSocialAuth = type("UserSocialAuth", (FakeSocial,), {}) + self.UserSocialAuth.objects = FakeManager( + self.UserSocialAuth, unique=("provider", "uid") + ) + + def user(self, pk: int, username: str, **kwargs): + return self.User.objects.create(pk=pk, username=username, **kwargs) + + def social(self, user, uid: str, id_key: str = "sub", provider: str = "oidc"): + return self.UserSocialAuth.objects.create( + user=user, provider=provider, uid=uid, id_key=id_key + ) + + def modules(self) -> dict[str, ModuleType]: + auth_models = ModuleType("weblate.auth.models") + auth_models.User = self.User + social_models = ModuleType("social_django.models") + social_models.UserSocialAuth = self.UserSocialAuth + return { + "weblate": ModuleType("weblate"), + "weblate.auth": ModuleType("weblate.auth"), + "weblate.auth.models": auth_models, + "social_django": ModuleType("social_django"), + "social_django.models": social_models, + } + + +def adopt(db: Database, *, sso: bool = True, subject: str = SUBJECT) -> str: + """Run the shipped script the way ``weblate shell`` does and return its stdout. + + Args: + db: the tables the script reads and writes. + sso: the value of ``WEBLATE_OIDC_ENABLED``. + subject: the value of ``WEBLATE_ADMIN_OIDC_SUBJECT``. + """ + env = { + "WEBLATE_ADMIN_BOOTSTRAP_USERNAME": "admin", + "WEBLATE_ADMIN_USERNAME": ADMIN, + "WEBLATE_OIDC_ENABLED": "true" if sso else "false", + "WEBLATE_ADMIN_OIDC_SUBJECT": subject, + } + out = io.StringIO() + with ( + unittest.mock.patch.dict(sys.modules, db.modules()), + unittest.mock.patch.dict(os.environ, env), + contextlib.redirect_stdout(out), + ): + runpy.run_path(str(SCRIPT), run_name="__weblate_shell__") + return out.getvalue() + + +def bindings(db: Database) -> list[tuple[str, str, str, str]]: + return [ + (row.user.username, row.provider, row.uid, row.id_key) + for row in db.UserSocialAuth.objects.rows + ] + + +class TestAdministratorSubjectBinding(unittest.TestCase): + def test_the_bootstrapped_superuser_is_bound_to_the_keycloak_subject(self): + db = Database() + admin = db.user(1, "admin") + self.assertIn("ADOPTED=1", adopt(db)) + self.assertEqual(admin.username, ADMIN) + self.assertEqual( + bindings(db), + [(ADMIN, "oidc", SUBJECT, "sub")], + "Weblate 2026.11 refuses to link the OIDC sign-in to the local " + "administrator by e-mail (email_in_use); social_user must find it " + "through an oidc association on the Keycloak sub instead", + ) + self.assertFalse(admin.usable_password) + + def test_a_second_run_changes_nothing(self): + db = Database() + db.user(1, ADMIN, usable_password=False) + adopt(db) + self.assertIn("ADOPTED=0", adopt(db)) + self.assertEqual(bindings(db), [(ADMIN, "oidc", SUBJECT, "sub")]) + + def test_an_unkeyed_legacy_row_for_the_subject_is_keyed_in_place(self): + db = Database() + admin = db.user(1, ADMIN, usable_password=False) + db.social(admin, SUBJECT, id_key="") + self.assertIn("ADOPTED=1", adopt(db)) + self.assertEqual(bindings(db), [(ADMIN, "oidc", SUBJECT, "sub")]) + + def test_another_account_holding_the_subject_loses_it(self): + db = Database() + db.user(1, ADMIN, usable_password=False) + stray = db.user(2, "platformadmin-old") + db.social(stray, SUBJECT) + self.assertIn("ADOPTED=1", adopt(db)) + self.assertEqual(bindings(db), [(ADMIN, "oidc", SUBJECT, "sub")]) + + def test_a_foreign_subject_on_the_administrator_stops_the_run(self): + db = Database() + admin = db.user(1, ADMIN, usable_password=False) + db.social(admin, OTHER_SUBJECT) + with self.assertRaises(SystemExit) as stop: + adopt(db) + self.assertTrue(str(stop.exception.code).startswith(f"{STOP_MARKER}:")) + self.assertEqual(bindings(db), [(ADMIN, "oidc", OTHER_SUBJECT, "sub")]) + + def test_other_providers_on_the_administrator_are_left_alone(self): + db = Database() + admin = db.user(1, ADMIN, usable_password=False) + db.social(admin, "admin@example.com", id_key="", provider="email") + adopt(db) + self.assertEqual( + sorted(bindings(db)), + [ + (ADMIN, "email", "admin@example.com", ""), + (ADMIN, "oidc", SUBJECT, "sub"), + ], + ) + + def test_sso_without_a_subject_stops_the_run(self): + db = Database() + db.user(1, ADMIN) + with self.assertRaises(SystemExit) as stop: + adopt(db, subject="") + self.assertTrue(str(stop.exception.code).startswith(f"{STOP_MARKER}:")) + self.assertEqual(bindings(db), []) + + def test_without_sso_nothing_is_bound_and_the_password_stays(self): + db = Database() + admin = db.user(1, "admin") + self.assertIn("ADOPTED=1", adopt(db, sso=False, subject="")) + self.assertEqual(bindings(db), []) + self.assertTrue(admin.usable_password) + + +def _tasks(path) -> list[dict]: + return load_yaml_any(str(path), default_if_missing=[]) + + +def _subject_expression() -> str: + for task in _tasks(SUBJECT_TASKS): + if SUBJECT_FACT in task.get("ansible.builtin.set_fact", {}): + return task["ansible.builtin.set_fact"][SUBJECT_FACT] + raise AssertionError(f"no task sets {SUBJECT_FACT}") + + +def pick_subjects(stdout_lines: list[str], username: str = ADMIN) -> list[str]: + templar = Templar( + loader=DataLoader(), + variables={ + "weblate_keycloak_admin_users": {"stdout_lines": stdout_lines}, + "WEBLATE_ADMIN_USERNAME": username, + }, + ) + return templar.template(_trust_as_template(_subject_expression())) + + +class TestKeycloakSubjectSelection(unittest.TestCase): + def test_jvm_warnings_before_the_csv_are_skipped(self): + self.assertEqual( + pick_subjects([JVM_NOISE, f"{SUBJECT},{ADMIN}"]), + [SUBJECT], + ) + + def test_the_administrator_name_is_matched_case_insensitively(self): + self.assertEqual( + pick_subjects([f"{SUBJECT},{ADMIN}"], "PlatformAdmin"), [SUBJECT] + ) + + def test_only_the_exact_username_matches(self): + self.assertEqual( + pick_subjects( + [ + f"{OTHER_SUBJECT},{ADMIN}2", + f"{OTHER_SUBJECT},x{ADMIN}", + f"{OTHER_SUBJECT},other,{ADMIN}", + ] + ), + [], + ) + + def test_the_username_is_not_read_as_a_pattern(self): + self.assertEqual( + pick_subjects([f"{OTHER_SUBJECT},platformXadmin"], "platform.admin"), [] + ) + + def test_two_matches_are_both_reported_for_the_assert(self): + self.assertEqual( + pick_subjects([f"{SUBJECT},{ADMIN}", f"{OTHER_SUBJECT},{ADMIN}"]), + [SUBJECT, OTHER_SUBJECT], + ) + + +class TestSubjectReachesTheShell(unittest.TestCase): + def test_the_keycloak_lookup_is_included_only_with_sso(self): + include = next( + task + for task in _tasks(TOKEN_TASKS) + if task.get("ansible.builtin.include_tasks") == SUBJECT_INCLUDE + ) + self.assertEqual(include["when"], "WEBLATE_OIDC_ENABLED | bool") + self.assertTrue(SUBJECT_TASKS.is_file()) + + def test_the_adopt_task_forwards_the_subject_into_the_container(self): + adopt_task = next( + task + for task in _tasks(TOKEN_TASKS) + if "adopt_admin.py" in str(task.get("ansible.builtin.shell", {})) + ) + self.assertIn( + "-e WEBLATE_ADMIN_OIDC_SUBJECT", adopt_task["ansible.builtin.shell"]["cmd"] + ) + self.assertIn("WEBLATE_ADMIN_OIDC_SUBJECT", adopt_task["environment"]) + self.assertIn( + f"'{STOP_MARKER}' in weblate_admin_adopt.stderr", adopt_task["until"] + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/scripts/tests/deploy/act/test_workflow.py b/tests/unit/python/scripts/tests/deploy/act/test_workflow.py index e5e6c86555..d433a565dc 100644 --- a/tests/unit/python/scripts/tests/deploy/act/test_workflow.py +++ b/tests/unit/python/scripts/tests/deploy/act/test_workflow.py @@ -7,11 +7,13 @@ import tempfile import unittest from pathlib import Path +from cli.meta.env.__main__ import HOST_OWNED_KEY from utils.cache.files import PROJECT_ROOT SCRIPT = PROJECT_ROOT / "scripts" / "tests" / "deploy" / "act" / "workflow.sh" ACT_STUB = '#!/usr/bin/env bash\nprintf \'%s\\0\' "$@" >"${STUB_LOG}"\n' DB_ENV = "INFINITO_VULNERABILITY_DB_HOST_PATH" +HOST_OWNED = f"{HOST_OWNED_KEY}=true" EXTRA_VARS = json.dumps( { "applications": { @@ -23,7 +25,11 @@ EXTRA_VARS = json.dumps( def run_act( - db_host_path: str | None, act_env: str = "" + db_host_path: str | None, + act_env: str = "", + *, + act_bind: str | None = None, + custom_role: bool = False, ) -> tuple[subprocess.CompletedProcess, list[str], Path, bool]: """Run the wrapper against an ``act`` stub that records its argv. @@ -31,6 +37,9 @@ def run_act( db_host_path: value of ``INFINITO_VULNERABILITY_DB_HOST_PATH`` below a scratch directory, or None to leave it unset. act_env: value of ``ACT_ENV``. + act_bind: value of ``ACT_BIND``, or None to leave it unset. + custom_role: run the wrapper from a scratch checkout that holds a + pulled ``roles/web-app-cst-*`` role instead of this repository. Returns: The finished process, the argv act received (one list item per @@ -38,6 +47,14 @@ def run_act( whether it existed afterwards. """ with tempfile.TemporaryDirectory() as tmp: + script = SCRIPT + if custom_role: + root = Path(tmp) / "repo" + (root / "roles" / "web-app-cst-demo").mkdir(parents=True) + (root / ".github" / "workflows").mkdir(parents=True) + script = root / "scripts" / "tests" / "deploy" / "act" / "workflow.sh" + script.parent.mkdir(parents=True) + script.symlink_to(SCRIPT) stub = Path(tmp) / "act" stub.write_text(ACT_STUB) stub.chmod(0o755) @@ -48,8 +65,10 @@ def run_act( env = { k: v for k, v in os.environ.items() - if k not in ("BASH_ENV", DB_ENV, "ACT_CONTAINER_OPTIONS") + if k not in ("BASH_ENV", DB_ENV, "ACT_CONTAINER_OPTIONS", "ACT_BIND") } + if act_bind is not None: + env["ACT_BIND"] = act_bind env.update( PATH=f"{tmp}{os.pathsep}{os.environ['PATH']}", STUB_LOG=str(log), @@ -63,7 +82,7 @@ def run_act( if db_host_path is not None: env[DB_ENV] = str(shared) done = subprocess.run( - ["bash", str(SCRIPT)], + ["bash", str(script)], env=env, capture_output=True, text=True, @@ -99,10 +118,12 @@ def env_items(argv: list[str]) -> list[str]: Returns: Every ``--env`` value in order, without the wrapper's own - ``INFINITO_VULNERABILITY_DB_HOST_PATH`` pin. + ``INFINITO_VULNERABILITY_DB_HOST_PATH`` and host-owned ``.env`` pins. """ return [ - value for value in option(argv, "--env") if not value.startswith(f"{DB_ENV}=") + value + for value in option(argv, "--env") + if not value.startswith(f"{DB_ENV}=") and value != HOST_OWNED ] @@ -165,5 +186,24 @@ class TestActWorkflowEnv(unittest.TestCase): self.assertEqual(items, ["INFINITO_INVENTORY_EXTRA_VARS=", "disable=css"]) +class TestBoundCheckoutKeepsTheHostDotenv(unittest.TestCase): + def test_an_explicit_bind_keeps_the_host_dotenv(self) -> None: + done, argv, _shared, _created = run_act("vulnerability-db", act_bind="true") + self.assertEqual(done.returncode, 0, done.stderr) + self.assertIn("--bind", argv) + self.assertIn(HOST_OWNED, option(argv, "--env")) + + def test_a_bind_for_pulled_custom_roles_keeps_the_host_dotenv(self) -> None: + done, argv, _shared, _created = run_act("vulnerability-db", custom_role=True) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertIn("--bind", argv) + self.assertIn(HOST_OWNED, option(argv, "--env")) + + def test_the_marker_travels_only_with_the_bind(self) -> None: + done, argv, _shared, _created = run_act("vulnerability-db", act_bind="false") + self.assertEqual(done.returncode, 0, done.stderr) + self.assertEqual("--bind" in argv, HOST_OWNED in option(argv, "--env")) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/scripts/tests/deploy/utils/filesystem/test_docker_dataroot.py b/tests/unit/python/scripts/tests/deploy/utils/filesystem/test_docker_dataroot.py index 2a2aa707e4..154227d6c9 100644 --- a/tests/unit/python/scripts/tests/deploy/utils/filesystem/test_docker_dataroot.py +++ b/tests/unit/python/scripts/tests/deploy/utils/filesystem/test_docker_dataroot.py @@ -122,5 +122,17 @@ class TestDockerDatarootLoopMount(unittest.TestCase): self.assertIn(("-o", option), list(pairwise(mounts[0]))) +class TestDockerDatarootLoopAttach(unittest.TestCase): + def test_the_loop_bypasses_the_page_cache_of_its_backing_image(self) -> None: + for fstype in (*DISCARD, "zfs"): + with self.subTest(fstype=fstype): + _, calls = apply(fstype) + attaches = [ + argv for argv in calls if argv[0] == "losetup" and "--show" in argv + ] + self.assertEqual(len(attaches), 1, calls) + self.assertIn("--direct-io=on", attaches[0]) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/utils/cache/test_render.py b/tests/unit/python/utils/cache/test_render.py index 559c25f7f0..58290c3ec0 100644 --- a/tests/unit/python/utils/cache/test_render.py +++ b/tests/unit/python/utils/cache/test_render.py @@ -10,6 +10,7 @@ from __future__ import annotations import stat import tempfile import unittest +import unittest.mock as mock from pathlib import Path from utils.cache.hosts import host_records @@ -88,5 +89,42 @@ class TestOllamaRegistry(unittest.TestCase): self.assertNotIn("location /v2/", block) +def _servers(http2: bool | str) -> tuple[list[str], list[str]]: + """Return the TLS and the plain server blocks of the rendered frontend. + + Args: + http2: the value ``WEBSERVER_HTTP2_ENABLED`` is rendered with. + """ + with mock.patch("utils.cache.render._webserver_http2", return_value=http2): + blocks = upstreams_conf().split("server {")[1:] + tls = [block for block in blocks if " ssl;" in block] + return tls, [block for block in blocks if " ssl;" not in block] + + +class TestHttp2(unittest.TestCase): + def test_no_listener_serves_http2_while_the_switch_is_off(self) -> None: + tls, plain = _servers(False) + + self.assertTrue(tls) + self.assertFalse([block for block in tls + plain if "http2" in block]) + + def test_every_tls_listener_serves_http2_once_the_switch_is_on(self) -> None: + tls, _plain = _servers(True) + + self.assertTrue(tls) + self.assertEqual([block for block in tls if "\n\thttp2 on;\n" not in block], []) + + def test_a_string_false_from_extra_vars_keeps_http2_off(self) -> None: + tls, _plain = _servers("false") + + self.assertFalse([block for block in tls if "http2" in block]) + + def test_a_plain_listener_never_serves_http2(self) -> None: + _tls, plain = _servers(True) + + self.assertTrue(plain) + self.assertFalse([block for block in plain if "http2" in block]) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/utils/env/handlers/test_nix_config.py b/tests/unit/python/utils/env/handlers/test_nix_config.py new file mode 100644 index 0000000000..2ea254aee7 --- /dev/null +++ b/tests/unit/python/utils/env/handlers/test_nix_config.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +import os +import unittest +from pathlib import Path +from unittest.mock import patch + +from utils.env.context import BuildContext, EnvBuilder +from utils.env.handlers import nix_config as handler + +_TOKENS_LINE = "access-tokens = github.com=placeholder-not-a-token" +_CALLER = {handler.KEY: f"{_TOKENS_LINE}\naccept-flake-config = true\n"} + + +def _ctx(*, on_gha: bool = False, on_act: bool = False) -> BuildContext: + return BuildContext( + static={}, + static_comments={}, + repo_root=Path("/repo"), + on_gha=on_gha, + on_act=on_act, + ) + + +def _apply(ctx: BuildContext) -> dict[str, str]: + eb = EnvBuilder() + handler.apply(eb, ctx) + return eb.values + + +class TestNixConfigTokenStaysOffTheHost(unittest.TestCase): + @patch.dict(os.environ, _CALLER, clear=False) + def test_a_github_runner_keeps_only_the_access_tokens_line(self) -> None: + self.assertEqual(_apply(_ctx(on_gha=True)), {handler.KEY: _TOKENS_LINE}) + + @patch.dict(os.environ, _CALLER, clear=False) + def test_act_never_writes_the_token(self) -> None: + self.assertNotIn(handler.KEY, _apply(_ctx(on_act=True))) + + @patch.dict(os.environ, _CALLER, clear=False) + def test_a_developer_machine_never_writes_the_token(self) -> None: + self.assertNotIn(handler.KEY, _apply(_ctx())) + + +if __name__ == "__main__": # pragma: no cover + unittest.main() diff --git a/tests/unit/python/utils/update/test_level.py b/tests/unit/python/utils/update/test_level.py new file mode 100644 index 0000000000..e90e0f7c6e --- /dev/null +++ b/tests/unit/python/utils/update/test_level.py @@ -0,0 +1,68 @@ +from __future__ import annotations + +import unittest + +from utils.update.level import bump_level, diff_level, line_level + +SHA_A = "3fa19f8b6d3eecbacbdbf79406e0f877ebe11e26" +SHA_B = "dc95a4d7e7e5531b1fdaa59528121afcffb8b3f0" + + +class TestBumpLevel(unittest.TestCase): + def test_the_first_changed_number_sets_the_level(self) -> None: + self.assertEqual(bump_level("1.2.3", "2.0.0"), "major") + self.assertEqual(bump_level("v8.8.3-alpine", "v8.9.0-alpine"), "minor") + self.assertEqual(bump_level("6.8.0", "6.8.1"), "patch") + self.assertEqual(bump_level("2026.05.18.0", "2026.05.18.1"), "patch") + self.assertEqual(bump_level("24.04", "26.04"), "major") + + def test_a_sha_or_a_numberless_side_is_major(self) -> None: + self.assertEqual(bump_level(SHA_A, SHA_B), "major") + self.assertEqual(bump_level(SHA_A, "v0.1.1"), "major") + self.assertEqual(bump_level("latest", "1.0.0"), "major") + + def test_a_longer_version_with_the_same_prefix_is_patch(self) -> None: + self.assertEqual(bump_level("1.2", "1.2.1"), "patch") + + +class TestLineLevel(unittest.TestCase): + def test_the_first_differing_token_decides(self) -> None: + self.assertEqual( + line_level(' version: "1.2.3"', ' version: "1.3.0"'), "minor" + ) + self.assertEqual(line_level("pkg==4.0.1", "pkg==4.0.2"), "patch") + self.assertEqual( + line_level(" runs-on: ubuntu-24.04", " runs-on: ubuntu-26.04"), + "major", + ) + self.assertEqual(line_level(f" ref: {SHA_A}", " ref: v0.1.1"), "major") + + def test_unpaired_tokens_are_major(self) -> None: + self.assertEqual(line_level("ref: main", "ref: v1.0.0"), "major") + + +class TestDiffLevel(unittest.TestCase): + def test_the_highest_level_of_every_hunk_wins(self) -> None: + diff = ( + "diff --git a/roles/a/meta/services.yml b/roles/a/meta/services.yml\n" + "--- a/roles/a/meta/services.yml\n" + "+++ b/roles/a/meta/services.yml\n" + "@@ -3 +3 @@\n" + '- version: "1.2.3"\n' + '+ version: "1.2.4"\n' + "@@ -9 +9 @@\n" + '- version: "4.1.0"\n' + '+ version: "4.2.0"\n' + ) + self.assertEqual(diff_level(diff), "minor") + + def test_a_hunk_with_unequal_sides_is_major(self) -> None: + diff = "@@ -3 +3,2 @@\n- version: 1.0.0\n+ version: 1.0.1\n+ extra: 1\n" + self.assertEqual(diff_level(diff), "major") + + def test_an_empty_diff_is_major(self) -> None: + self.assertEqual(diff_level(""), "major") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/update/test_repository.py b/tests/unit/python/utils/update/test_repository.py index 56e5e380f4..5a042c2e47 100644 --- a/tests/unit/python/utils/update/test_repository.py +++ b/tests/unit/python/utils/update/test_repository.py @@ -1,5 +1,6 @@ from __future__ import annotations +import os import subprocess import tempfile import unittest @@ -18,6 +19,8 @@ from utils.update.repository import ( git_ls_remote_head, git_ref_resolves, is_commit_sha, + latest_release, + release_contains, suppressed_ref_lines, update_config_refs, walk_repo_ref_pairs, @@ -373,10 +376,41 @@ def _write_role( return config -def _find(root: Path, ls_remote: _LsRemote) -> list[RepositoryRefUpdate]: +class _Contains: + """Stand-in for :func:`release_contains`. + + Args: + answer: what every call reports; ``None`` fails any call. + """ + + def __init__(self, answer: bool | None) -> None: + self.answer = answer + self.calls: list[tuple[str, str, str]] = [] + + def __call__(self, url: str, sha: str, tag: str) -> bool: + if self.answer is None: + raise AssertionError(f"release_contains({url}, {sha}, {tag}) called") + self.calls.append((url, sha, tag)) + return self.answer + + +def _find( + root: Path, ls_remote: _LsRemote, contains: _Contains | None = None +) -> list[RepositoryRefUpdate]: + """Run :func:`find_outdated_updates` against stand-ins. + + Args: + root: the repository root holding ``roles/``. + ls_remote: answers every ``git ls-remote``. + contains: answers :func:`release_contains`; ``None`` asserts it is + never called. + """ + if contains is None: + contains = _Contains(answer=None) with ( unittest.mock.patch.object(module, "resolve_max_fetch_workers", return_value=2), unittest.mock.patch.object(module.subprocess, "run", side_effect=ls_remote), + unittest.mock.patch.object(module, "release_contains", side_effect=contains), ): return find_outdated_updates(root) @@ -412,6 +446,69 @@ class TestIsCommitSha(unittest.TestCase): self.assertFalse(is_commit_sha("v1.0.0")) +class TestLatestRelease(unittest.TestCase): + def test_the_newest_unflavored_semver_tag_wins(self) -> None: + self.assertEqual( + latest_release(["v0.1.0", "v0.1.1", "v0.2.0-rc.1", "nightly"]), "v0.1.1" + ) + self.assertEqual(latest_release(["6.8.0", "6.9.0", "6.10.0"]), "6.10.0") + + def test_no_release_tag_yields_none(self) -> None: + self.assertIsNone(latest_release([])) + self.assertIsNone(latest_release(["v1.0.0-rc.1", "nightly"])) + + +_ISOLATED_GIT = {"GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1"} + + +class TestReleaseContains(unittest.TestCase): + def setUp(self) -> None: + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + upstream = Path(tmp.name) / "upstream" + upstream.mkdir() + self.env = { + **{k: v for k, v in os.environ.items() if not k.startswith("GIT_")}, + **_ISOLATED_GIT, + "GIT_AUTHOR_NAME": "test", + "GIT_AUTHOR_EMAIL": "test@example.invalid", + "GIT_COMMITTER_NAME": "test", + "GIT_COMMITTER_EMAIL": "test@example.invalid", + } + self._git(upstream, "init", "--quiet") + self.released = self._commit(upstream, "released") + self._git(upstream, "tag", "-a", "v1.0.0", "-m", "v1.0.0") + self.unreleased = self._commit(upstream, "after the release") + self.url = upstream.as_uri() + + def _git(self, cwd: Path, *args: str) -> str: + return subprocess.run( + ["git", *args], + cwd=cwd, + env=self.env, + capture_output=True, + text=True, + check=True, + ).stdout.strip() + + def _commit(self, repo: Path, message: str) -> str: + self._git(repo, "commit", "--quiet", "--allow-empty", "-m", message) + return self._git(repo, "rev-parse", "HEAD") + + def _contains(self, sha: str, tag: str) -> bool: + with unittest.mock.patch.dict(os.environ, _ISOLATED_GIT): + return release_contains(self.url, sha, tag) + + def test_a_commit_the_release_carries_is_contained(self) -> None: + self.assertTrue(self._contains(self.released, "v1.0.0")) + + def test_a_commit_after_the_release_is_not_contained(self) -> None: + self.assertFalse(self._contains(self.unreleased, "v1.0.0")) + + def test_a_missing_tag_proves_nothing(self) -> None: + self.assertFalse(self._contains(self.released, "v9.9.9")) + + class TestGitLsRemoteHead(unittest.TestCase): def test_returns_the_head_commit(self) -> None: ls_remote = _LsRemote(heads={SHA_REPO: TIP_SHA}) @@ -508,6 +605,54 @@ class TestCommitShaPins(unittest.TestCase): written, SHA_PINNED.replace(f'"{OLD_SHA}"', f'"{TIP_SHA}"') ) + def test_a_sha_contained_in_the_newest_release_moves_to_that_tag( + self, + ) -> None: + with tempfile.TemporaryDirectory() as tmpdir: + root = Path(tmpdir) + config = _write_role(root, SHA_PINNED) + ls_remote = _LsRemote( + heads={SHA_REPO: TIP_SHA}, + tags={SHA_REPO: ["v1.0.0", "v1.2.0", "v2.0.0-rc.1"]}, + ) + contains = _Contains(answer=True) + + updates = _find(root, ls_remote, contains) + + self.assertEqual([u.latest for u in updates], ["v1.2.0"]) + self.assertEqual(contains.calls, [(SHA_REPO, OLD_SHA, "v1.2.0")]) + self.assertEqual(ls_remote.calls, [("--tags", SHA_REPO)]) + apply_updates(updates) + written = config.read_text() # nocheck: cache-read just rewritten here + self.assertIn('ref: "v1.2.0"', written) + + def test_a_sha_newer_than_the_newest_release_follows_the_tip(self) -> None: + with tempfile.TemporaryDirectory() as tmpdir: + root = Path(tmpdir) + _write_role(root, SHA_PINNED) + ls_remote = _LsRemote( + heads={SHA_REPO: TIP_SHA}, tags={SHA_REPO: ["v1.0.0", "v1.2.0"]} + ) + + updates = _find(root, ls_remote, _Contains(answer=False)) + + self.assertEqual([u.latest for u in updates], [TIP_SHA]) + self.assertEqual( + sorted(ls_remote.calls), [("--tags", SHA_REPO), (SHA_REPO, "HEAD")] + ) + + def test_a_sha_whose_upstream_has_only_flavored_tags_follows_the_tip( + self, + ) -> None: + with tempfile.TemporaryDirectory() as tmpdir: + root = Path(tmpdir) + _write_role(root, SHA_PINNED) + ls_remote = _LsRemote( + heads={SHA_REPO: TIP_SHA}, tags={SHA_REPO: ["v2.0.0-rc.1"]} + ) + + self.assertEqual([u.latest for u in _find(root, ls_remote)], [TIP_SHA]) + def test_a_current_sha_is_left_alone(self) -> None: with tempfile.TemporaryDirectory() as tmpdir: root = Path(tmpdir) @@ -576,7 +721,7 @@ class TestCommitShaPins(unittest.TestCase): ) self.assertEqual(_find(root, ls_remote), []) - self.assertEqual(len(ls_remote.calls), 2) + self.assertEqual(len(ls_remote.calls), 3) def test_each_repository_is_queried_once_per_lookup_kind(self) -> None: with tempfile.TemporaryDirectory() as tmpdir: @@ -595,7 +740,7 @@ class TestCommitShaPins(unittest.TestCase): self.assertEqual( sorted(ls_remote.calls), - [("--tags", TAG_REPO), (SHA_REPO, "HEAD")], + [("--tags", TAG_REPO), ("--tags", SHA_REPO), (SHA_REPO, "HEAD")], ) self.assertEqual( sorted((u.entry.entity_path, u.latest) for u in updates), diff --git a/utils/cache/render.py b/utils/cache/render.py index 8e041f6737..e8e888f917 100644 --- a/utils/cache/render.py +++ b/utils/cache/render.py @@ -33,6 +33,7 @@ if TYPE_CHECKING: ROLE = "svc-cache-package" ROLE_DIR = PROJECT_ROOT / "roles" / ROLE ROLE_VARS = ROLE_DIR / ROLE_FILE_VARS_MAIN +WEBSERVER_VARS = PROJECT_ROOT / "group_vars" / "all" / "04_webserver.yml" TEMPLATE_DIRS = (ROLE_DIR / "templates", PROJECT_ROOT / "compose" / "templates") UPSTREAMS_TEMPLATE = "upstreams.conf.j2" CONSUMER_TEMPLATE = "cache-consumer.yml.jinja" @@ -92,10 +93,15 @@ def _render(template: str, **context) -> str: return env.get_template(template).render(**context) +def _webserver_http2() -> bool: + return load_yaml_any(str(WEBSERVER_VARS))["WEBSERVER_HTTP2_ENABLED"] + + def upstreams_conf() -> str: """Return the nginx frontend configuration the declarations produce.""" return _render( UPSTREAMS_TEMPLATE, + WEBSERVER_HTTP2_ENABLED=_webserver_http2(), CACHE_PACKAGE_UPSTREAMS=list(host_records().values()), CACHE_PACKAGE_REPOS=repo_records(), CACHE_PACKAGE_BACKEND=BACKEND, diff --git a/utils/env/handlers/nix_config.py b/utils/env/handlers/nix_config.py index a56d12f4c7..07df642a86 100644 --- a/utils/env/handlers/nix_config.py +++ b/utils/env/handlers/nix_config.py @@ -1,10 +1,15 @@ -"""NIX_CONFIG: pass-through of the caller's access-tokens line, when present. +"""NIX_CONFIG: pass-through of the caller's access-tokens line on a GitHub runner. `.env` is consumed by bash `source` and docker-compose `--env-file`, neither of which round-trips multi-line values; the writer therefore rejects them. Other NIX_CONFIG settings (`accept-flake-config`, `experimental-features`, …) belong in `/etc/nix/nix.conf` (Dockerfile injects them inside the dev container; host operators set them once in `~/.config/nix/nix.conf`). + +Only a GitHub Actions runner gets the line: there the token is the job's +short-lived GITHUB_TOKEN. Under act or on a developer machine it is the +operator's own long-lived token, and `.env` would keep it in plaintext in the +host checkout. """ from __future__ import annotations @@ -16,10 +21,12 @@ if TYPE_CHECKING: from utils.env.context import BuildContext, EnvBuilder KEY = "NIX_CONFIG" -COMMENT = "Pass-through of the caller's NIX_CONFIG access-tokens line, when present." +COMMENT = "The caller's NIX_CONFIG access-tokens line, on a GitHub runner only." def apply(eb: EnvBuilder, ctx: BuildContext) -> None: + if not ctx.on_gha: + return nix_config = os.environ.get("NIX_CONFIG", "") access_tokens_line = next( ( diff --git a/utils/update/level.py b/utils/update/level.py new file mode 100644 index 0000000000..2af98890af --- /dev/null +++ b/utils/update/level.py @@ -0,0 +1,122 @@ +"""Classify the version step an update commit makes as major, minor or patch. + +Standard library only: the runner-label update job installs no dependencies. + +Usage: ``python3 -m utils.update.level `` prints the highest +level of every version changed between the two revisions. +""" + +from __future__ import annotations + +import re +import subprocess +import sys + +LEVELS = ("patch", "minor", "major") +_SHA_RE = re.compile(r"[0-9a-f]{40}") +_VERSION_TOKEN_RE = re.compile(r"[0-9a-f]{40}|\d+(?:\.\d+)*") + + +def bump_level(old: str, new: str) -> str: + """Return the level of the step between two versions. + + Args: + old: version before the update. + new: version after it. + + Returns: + ``major`` when the first number changes or either side is a commit + SHA or carries no number, ``minor`` when the second changes, else + ``patch``. + """ + if _SHA_RE.fullmatch(old) or _SHA_RE.fullmatch(new): + return "major" + old_parts = re.findall(r"\d+", old) + new_parts = re.findall(r"\d+", new) + if not old_parts or not new_parts: + return "major" + for index, (before, after) in enumerate(zip(old_parts, new_parts, strict=False)): + if int(before) != int(after): + return LEVELS[max(0, 2 - index)] + return "patch" + + +def line_level(old: str, new: str) -> str: + """Return the level of one rewritten line. + + Args: + old: the line before the update. + new: the line after it. + + Returns: + The level of the first version token that differs; ``major`` when + the lines carry a different number of version tokens or none differs. + """ + old_tokens = _VERSION_TOKEN_RE.findall(old) + new_tokens = _VERSION_TOKEN_RE.findall(new) + if len(old_tokens) != len(new_tokens): + return "major" + for before, after in zip(old_tokens, new_tokens, strict=True): + if before != after: + return bump_level(before, after) + return "major" + + +def diff_level(diff: str) -> str: + """Return the highest level of every line pair a ``-U0`` diff rewrites. + + Args: + diff: output of ``git diff -U0``. + + Returns: + The highest level; ``major`` when a hunk removes and adds a different + number of lines or the diff rewrites nothing. + """ + levels: list[str] = [] + removed: list[str] = [] + added: list[str] = [] + + def flush() -> None: + if len(removed) != len(added): + levels.append("major") + levels.extend(line_level(o, n) for o, n in zip(removed, added, strict=False)) + removed.clear() + added.clear() + + for line in diff.splitlines(): + if line.startswith(("--- ", "+++ ")): + continue + if line.startswith("@@"): + flush() + elif line.startswith("-"): + removed.append(line[1:]) + elif line.startswith("+"): + added.append(line[1:]) + flush() + return max(levels, key=LEVELS.index, default="major") + + +def main(argv: list[str]) -> int: + """Print the level of the update between two revisions. + + Args: + argv: ``[base, head]`` revisions passed to ``git diff``. + + Returns: + Exit status 0, or 2 on a usage error. + """ + if len(argv) != 2: + print("usage: python3 -m utils.update.level ", file=sys.stderr) + return 2 + diff = subprocess.run( + ["git", "diff", "-U0", argv[0], argv[1]], + capture_output=True, + text=True, + check=True, + ).stdout + print(diff_level(diff)) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/utils/update/repository.py b/utils/update/repository.py index 5cff7aad24..327c31f839 100644 --- a/utils/update/repository.py +++ b/utils/update/repository.py @@ -12,8 +12,10 @@ sub-entity, plugin map, an addon's ``config``, ...) that declares BOTH - a semver ref moves to the newest tag of the same depth and flavor, read with ``git ls-remote --tags ``; -- a full 40-hex commit SHA moves to the tip of the repository's default - branch, read with ``git ls-remote HEAD``. +- a full 40-hex commit SHA moves to the newest release tag when that tag + contains it, else to the tip of the repository's default branch, read + with ``git ls-remote HEAD``; a pin never moves back to an + older release. Branches (`master`, `main`, `stable`) and short SHAs are skipped. @@ -33,6 +35,7 @@ from __future__ import annotations import concurrent.futures import re import subprocess +import tempfile from dataclasses import dataclass from typing import TYPE_CHECKING @@ -58,6 +61,7 @@ if TYPE_CHECKING: _NOCHECK_MARKER = "repository-version" _COMMIT_SHA_RE = re.compile(r"^[0-9a-f]{40}$") +_FETCH_TIMEOUT_SECONDS = 120 _REF_VALUE_RE = re.compile( r"^(?P\s*ref\s*:\s*)" @@ -141,6 +145,64 @@ def _ls_remote(*args: str) -> str | None: return proc.stdout +def latest_release(tags: list[str]) -> str | None: + """Return the newest unflavored semver tag, so ``-rc.1`` never wins. + + Args: + tags: tag names of one repository. + """ + return max( + (tag for tag in tags if is_semver(tag) and not version_flavor(tag)), + key=version_key, + default=None, + ) + + +def _git_succeeds(git_dir: str, *args: str) -> bool: + try: + proc = subprocess.run( + ["git", *args], + cwd=git_dir, + capture_output=True, + text=True, + timeout=_FETCH_TIMEOUT_SECONDS, + check=False, + ) + except (FileNotFoundError, subprocess.TimeoutExpired): + return False + return proc.returncode == 0 + + +def release_contains(url: str, sha: str, tag: str) -> bool: + """Report whether release *tag* of *url* contains commit *sha*, so a pin + never moves back to a release older than itself. + + Args: + url: the upstream repository. + sha: the pinned commit. + tag: the release tag the pin would move to. + + Returns: + ``True`` only when a treeless fetch of the tag proves *sha* its + ancestor; a failed fetch proves nothing and yields ``False``. + """ + ref = f"refs/tags/{tag}" + with tempfile.TemporaryDirectory() as git_dir: + return ( + _git_succeeds(git_dir, "init", "--bare", "--quiet") + and _git_succeeds( + git_dir, + "fetch", + "--quiet", + "--no-tags", + "--filter=tree:0", + url, + f"{ref}:{ref}", + ) + and _git_succeeds(git_dir, "merge-base", "--is-ancestor", sha, ref) + ) + + def git_ls_remote_head(url: str) -> str | None: """Return the commit the remote's ``HEAD`` (its default branch) points at, or ``None`` when the lookup fails.""" @@ -294,6 +356,7 @@ def _target_ref( entry: RepositoryRefEntry, repo_tags: dict[str, list[str]], repo_heads: dict[str, str | None], + released: dict[tuple[str, str], str], ) -> str | None: """Return the ref *entry* should move to, or ``None`` when it stays. @@ -302,8 +365,13 @@ def _target_ref( repo_tags: tag names per repository, empty when the lookup failed. repo_heads: default-branch tip per repository, ``None`` when the lookup failed. + released: the newest release tag per ``(repository, sha)`` pin that + the tag contains. """ if is_commit_sha(entry.ref): + release = released.get((entry.repository, entry.ref)) + if release: + return release tip = repo_heads.get(entry.repository) return tip if tip and tip != entry.ref else None tags = repo_tags.get(entry.repository, []) @@ -322,23 +390,44 @@ def _target_ref( def find_outdated_updates(repo_root: Path) -> list[RepositoryRefUpdate]: """Cross-reference every collected entry against its upstream and return the entries that are behind: a semver ref older than the latest - tag with the same depth and flavor (``git ls-remote --tags``), or a - commit SHA that is not the default branch's tip - (``git ls-remote HEAD``).""" + tag with the same depth and flavor (``git ls-remote --tags``), a commit + SHA contained in its upstream's newest release tag + (:func:`release_contains`), or any other commit SHA that is not the + default branch's tip (``git ls-remote HEAD``).""" entries = collect_entries(repo_root) - sha_repos = sorted({e.repository for e in entries if is_commit_sha(e.ref)}) - tag_repos = sorted({e.repository for e in entries if not is_commit_sha(e.ref)}) + repos = sorted({e.repository for e in entries}) with concurrent.futures.ThreadPoolExecutor( max_workers=resolve_max_fetch_workers() ) as pool: - tags = pool.map(git_ls_remote_tags, tag_repos) + tags = pool.map(git_ls_remote_tags, repos) + repo_tags: dict[str, list[str]] = dict(zip(repos, tags, strict=True)) + candidates = sorted( + { + (e.repository, e.ref, release) + for e in entries + if is_commit_sha(e.ref) + and (release := latest_release(repo_tags[e.repository])) + } + ) + contained = pool.map(lambda c: release_contains(*c), candidates) + released = { + (repo, sha): tag + for (repo, sha, tag), ok in zip(candidates, contained, strict=True) + if ok + } + sha_repos = sorted( + { + e.repository + for e in entries + if is_commit_sha(e.ref) and (e.repository, e.ref) not in released + } + ) heads = pool.map(git_ls_remote_head, sha_repos) - repo_tags: dict[str, list[str]] = dict(zip(tag_repos, tags, strict=True)) repo_heads: dict[str, str | None] = dict(zip(sha_repos, heads, strict=True)) updates: list[RepositoryRefUpdate] = [] for entry in entries: - target = _target_ref(entry, repo_tags, repo_heads) + target = _target_ref(entry, repo_tags, repo_heads, released) if target: updates.append(RepositoryRefUpdate(entry=entry, latest=target)) return updates