diff --git a/cli/contributing/mirror/resolver/__main__.py b/cli/contributing/mirror/resolver/__main__.py index 75523ebe7c..1428781cc8 100644 --- a/cli/contributing/mirror/resolver/__main__.py +++ b/cli/contributing/mirror/resolver/__main__.py @@ -12,8 +12,9 @@ from utils.docker.image.discovery import iter_role_images def main() -> int: parser = argparse.ArgumentParser( description=( - "Emit the mirrors.yml mapping that redirects every role-declared " - "image (applications.*.services.*) to its GHCR mirror URI." + "Emit the mirrors.yml mapping that redirects every image a " + "non-eol role declares (applications.*.services.*) to its GHCR " + "mirror URI." ), ) parser.add_argument("--repo-root", default=".") diff --git a/cli/contributing/mirror/sync/__main__.py b/cli/contributing/mirror/sync/__main__.py index 2212f332db..d453732b46 100644 --- a/cli/contributing/mirror/sync/__main__.py +++ b/cli/contributing/mirror/sync/__main__.py @@ -53,8 +53,8 @@ def _throttle_before_next_copy( def main() -> int: parser = argparse.ArgumentParser( description=( - "Mirror every role-declared image and every image the CI runner " - "pulls itself to the configured GHCR registry, " + "Mirror every image a non-eol role declares and every image the " + "CI runner pulls itself to the configured GHCR registry, " "optionally throttled and optionally skipping already-mirrored " "tags." ), diff --git a/cli/contributing/mirror/wait/__main__.py b/cli/contributing/mirror/wait/__main__.py index 85769b2f7c..0820284b5c 100644 --- a/cli/contributing/mirror/wait/__main__.py +++ b/cli/contributing/mirror/wait/__main__.py @@ -23,8 +23,8 @@ def _validate_positive_int(value: str) -> int: def main() -> int: parser = argparse.ArgumentParser( description=( - "Wait until every role-declared image and every image the CI runner " - "pulls itself has been mirrored to the " + "Wait until every image a non-eol role declares and every image " + "the CI runner pulls itself has been mirrored to the " "configured GHCR registry. Used on fork pull_request runs that depend " "on a pull_request_target mirror job populating the destination first." ), diff --git a/docs/contributing/artefact/image/mirror.md b/docs/contributing/artefact/image/mirror.md index a0a8af6a47..e2f97cf848 100644 --- a/docs/contributing/artefact/image/mirror.md +++ b/docs/contributing/artefact/image/mirror.md @@ -32,7 +32,7 @@ Example: `ghcr.io/kevinveenbirkenbach/infinito-nexus-core/mirror/docker.io/nextc ### Image Discovery 🔍 -`utils/docker/image/discovery.py` discovers all role images via `iter_role_images()`. See [origin.md](origin.md) for the declaration format and supported registries. +`utils/docker/image/discovery.py` discovers the role images via `iter_role_images()`. It leaves out every role whose lifecycle is `eol` (`is_maintained()` in `utils/update/base.py`), so neither the mirror nor `mirrors.yml` covers those images. See [origin.md](origin.md) for the declaration format and supported registries. ### GHCRProvider 🐳 diff --git a/roles/sys-svc-container/files/shell/apt_repo.sh b/roles/sys-svc-container/files/shell/apt_repo.sh index 2fbb3e696a..ce983387ee 100644 --- a/roles/sys-svc-container/files/shell/apt_repo.sh +++ b/roles/sys-svc-container/files/shell/apt_repo.sh @@ -1,14 +1,12 @@ #!/usr/bin/env bash set -euo pipefail -KEYRING_DIR="/etc/apt/keyrings" -LEGACY_KEY_PATH="${KEYRING_DIR}/docker.gpg" -KEY_PATH="${KEYRING_DIR}/docker.asc" +KEY_PATH="/etc/apt/keyrings/docker.asc" usage() { cat >&2 <<'EOF' Usage: - apt_repo.sh install-key + apt_repo.sh install-key [keyring-path] apt_repo.sh sanitize-sources [keep-canonical: 0|1] [keyring-path] apt_repo.sh ensure-key-and-sanitize [keep-canonical: 0|1] [keyring-path] @@ -62,33 +60,39 @@ PY install_key() { local distro_id="$1" + local key_path="$2" + local keyring_dir="" local changed=0 local tmp="" - if [[ ! -d "${KEYRING_DIR}" ]]; then + keyring_dir="$(dirname "${key_path}")" + if [[ ! -d "${keyring_dir}" ]]; then changed=1 - elif [[ "$(stat -c '%a' "${KEYRING_DIR}" 2>/dev/null || true)" != "755" ]]; then + elif [[ "$(stat -c '%a' "${keyring_dir}" 2>/dev/null || true)" != "755" ]]; then changed=1 fi - run_privileged install -m 0755 -d "${KEYRING_DIR}" + run_privileged install -m 0755 -d "${keyring_dir}" - if [[ -e "${LEGACY_KEY_PATH}" ]]; then - run_privileged rm -f "${LEGACY_KEY_PATH}" + if [[ -e "${keyring_dir}/docker.gpg" ]]; then + run_privileged rm -f "${keyring_dir}/docker.gpg" changed=1 fi tmp="$(mktemp)" trap 'rm -f "${tmp:-}"' EXIT if ! download_file "https://download.docker.com/linux/${distro_id}/gpg" "${tmp}" || [[ ! -s "${tmp}" ]]; then - echo "[ERROR] Failed to download the Docker GPG key from https://download.docker.com/linux/${distro_id}/gpg." >&2 - return 1 + if [[ ! -s "${key_path}" ]]; then + echo "[ERROR] Failed to download the Docker GPG key from https://download.docker.com/linux/${distro_id}/gpg." >&2 + return 1 + fi + echo "[WARN] Failed to refresh the Docker GPG key from https://download.docker.com/linux/${distro_id}/gpg; keeping ${key_path}." >&2 + elif [[ ! -f "${key_path}" ]] || ! cmp -s "${tmp}" "${key_path}"; then + run_privileged install -m 0644 "${tmp}" "${key_path}" + changed=1 fi - if [[ ! -f "${KEY_PATH}" ]] || ! cmp -s "${tmp}" "${KEY_PATH}"; then - run_privileged install -m 0644 "${tmp}" "${KEY_PATH}" - changed=1 - elif [[ "$(stat -c '%a' "${KEY_PATH}" 2>/dev/null || true)" != "644" ]]; then - run_privileged chmod 0644 "${KEY_PATH}" + if [[ "$(stat -c '%a' "${key_path}" 2>/dev/null || true)" != "644" ]]; then + run_privileged chmod 0644 "${key_path}" changed=1 fi @@ -175,7 +179,7 @@ ensure_key_and_sanitize() { local changed=0 local output="" - output="$(install_key "${distro_id}")" + output="$(install_key "${distro_id}" "${expected_keyring}")" if [[ "${output}" == *"changed=1"* ]]; then changed=1 fi @@ -197,7 +201,7 @@ case "${ACTION}" in usage exit 2 fi - install_key "${DISTRO_ID}" + install_key "${DISTRO_ID}" "${3:-${KEY_PATH}}" ;; sanitize-sources) DISTRO_ID="${2:-}" diff --git a/roles/web-app-n8n/files/playwright/test-litellm-gateway.js b/roles/web-app-n8n/files/playwright/test-litellm-gateway.js index 97d55b4d57..7a77fefaed 100644 --- a/roles/web-app-n8n/files/playwright/test-litellm-gateway.js +++ b/roles/web-app-n8n/files/playwright/test-litellm-gateway.js @@ -8,6 +8,7 @@ const gatewayModel = decodeDotenvQuotedValue(process.env.N8N_LITELLM_MODEL); const CREDENTIAL_TYPE = "openAiApi"; const PROBE_WORKFLOW = "infinito:litellm-probe"; +const TRIGGER_NODE = "Start"; const REQUEST_NODE = "Gateway"; const PROMPT = "Reply with exactly the word: pong"; const FINAL_STATUSES = new Set(["success", "error", "crashed", "canceled"]); @@ -158,7 +159,7 @@ function probeWorkflow(credentialId, endpoint) { nodes: [ { id: "infinito-litellm-start", - name: "Start", + name: TRIGGER_NODE, type: "n8n-nodes-base.manualTrigger", typeVersion: 1, position: [0, 0], @@ -188,7 +189,7 @@ function probeWorkflow(credentialId, endpoint) { credentials: { [CREDENTIAL_TYPE]: { id: credentialId, name: credentialName } }, }, ], - connections: { Start: { main: [[{ node: REQUEST_NODE, type: "main", index: 0 }]] } }, + connections: { [TRIGGER_NODE]: { main: [[{ node: REQUEST_NODE, type: "main", index: 0 }]] } }, }; } @@ -286,7 +287,7 @@ exports.register = function (shared) { try { const run = await rest("POST", `/rest/workflows/${workflowId}/run`, { - workflowData: { ...workflow, id: workflowId }, + triggerToStartFrom: { name: TRIGGER_NODE }, }); expect( run.status, diff --git a/roles/web-app-stalwart/README.md b/roles/web-app-stalwart/README.md index 86d690079e..e5c7cd04c2 100644 --- a/roles/web-app-stalwart/README.md +++ b/roles/web-app-stalwart/README.md @@ -120,6 +120,10 @@ account (or the Keycloak SSO token when SSO is enabled). (`templates/jmap/*.json.j2`). - **Under SSO, trusted internal networks relay without SMTP AUTH** — the no-reply bot has no password once the auth directory is OIDC. +- **Address bans expire after `services.stalwart.ban_period_seconds`** (one + hour by default). Without a period Stalwart keeps a ban forever, and the + reverse proxy, the published ports, Tor and the swarm ingress hand many + clients one address. ## Features diff --git a/roles/web-app-stalwart/meta/services.yml b/roles/web-app-stalwart/meta/services.yml index 5bf06fec96..830c2d9349 100644 --- a/roles/web-app-stalwart/meta/services.yml +++ b/roles/web-app-stalwart/meta/services.yml @@ -55,6 +55,7 @@ stalwart: project_hard_restart: true migration: import_mailu: false + ban_period_seconds: 3600 # nocheck: min-storage-headroom Reason: the mail store (maildir blobs, FTS index, queue) lives in this service's volumes and dwarfs the image transfer size min_storage: 20GB domain: "{{ lookup('email').domain }}" diff --git a/roles/web-app-stalwart/tasks/manager_ops.yml b/roles/web-app-stalwart/tasks/manager_ops.yml index 8280c65a68..6895fcfc9c 100644 --- a/roles/web-app-stalwart/tasks/manager_ops.yml +++ b/roles/web-app-stalwart/tasks/manager_ops.yml @@ -28,6 +28,9 @@ - name: "🔧 Point Stalwart's file tracer at a writable directory" include_tasks: tracing.yml +- name: "⏱️ Let Stalwart's address bans expire" + include_tasks: security.yml + - name: "⚙️ Provision the Stalwart WebUI (WebAdmin) bundle" include_tasks: 02_webadmin.yml diff --git a/roles/web-app-stalwart/tasks/security.yml b/roles/web-app-stalwart/tasks/security.yml new file mode 100644 index 0000000000..a311f8a242 --- /dev/null +++ b/roles/web-app-stalwart/tasks/security.yml @@ -0,0 +1,34 @@ +--- +- name: "📖 Read Stalwart's ban settings" + include_tasks: jmap_call.yml + vars: + stalwart_jmap_body: >- + {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], + 'methodCalls': [['x:Security/get', {'ids': ['singleton']}, 'c0']]} | to_json }} + +- name: "🔍 Resolve Stalwart's current ban periods" + ansible.builtin.set_fact: + stalwart_ban_periods_current: >- + {{ stalwart_jmap.methodResponses[0][1].list[0] + | dict2items | selectattr('key', 'in', STALWART_BAN_PERIODS) | items2dict }} + +- name: "⏱️ Let Stalwart's address bans expire" + when: stalwart_ban_periods_current != STALWART_BAN_PERIODS + block: + - name: "🔧 Set Stalwart's ban periods" + include_tasks: jmap_call.yml + vars: + stalwart_jmap_body: >- + {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], + 'methodCalls': [['x:Security/set', + {'update': {'singleton': STALWART_BAN_PERIODS}}, + 'c0']]} | to_json }} + + - name: "🔄 Reload Stalwart's settings" + include_tasks: jmap_call.yml + vars: + stalwart_jmap_body: >- + {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], + 'methodCalls': [['x:Action/set', + {'create': {'a': {'@type': 'ReloadSettings'}}}, + 'c0']]} | to_json }} diff --git a/roles/web-app-stalwart/vars/main.yml b/roles/web-app-stalwart/vars/main.yml index 9732ebc434..8fba15ebc8 100644 --- a/roles/web-app-stalwart/vars/main.yml +++ b/roles/web-app-stalwart/vars/main.yml @@ -70,6 +70,13 @@ STALWART_DMARC_RUF: "{{ lookup('config', application_id, 'users.platform_adminis STALWART_TRUSTED_NETWORKS: "{{ NETWORK_TRUSTED_PROXY_CIDRS }}" +STALWART_BAN_PERIOD_MS: "{{ (lookup('config', application_id, 'services.stalwart.ban_period_seconds') | int) * 1000 }}" +STALWART_BAN_PERIODS: + authBanPeriod: "{{ STALWART_BAN_PERIOD_MS | int }}" + abuseBanPeriod: "{{ STALWART_BAN_PERIOD_MS | int }}" + loiterBanPeriod: "{{ STALWART_BAN_PERIOD_MS | int }}" + scanBanPeriod: "{{ STALWART_BAN_PERIOD_MS | int }}" + STALWART_SSO_ENABLED: "{{ lookup('sso', application_id, 'is_enabled') | bool }}" STALWART_IMPORT_MAILU: "{{ lookup('config', application_id, 'services.stalwart.migration.import_mailu') | bool }}" diff --git a/scripts/lint/mermaid.sh b/scripts/lint/mermaid.sh index 5e81449af6..1f1a606485 100755 --- a/scripts/lint/mermaid.sh +++ b/scripts/lint/mermaid.sh @@ -20,27 +20,6 @@ if ! command -v mmdc >/dev/null 2>&1; then exit 127 fi -# Limitation: install-lint skips the puppeteer browser download so it stays -# sandbox-safe; mermaid-cli (puppeteer-core) bundles none, so provision the -# matching chrome-headless-shell here. --install-deps also pulls chrome's shared -# libs (libnspr4, libnss3, ...) on root Linux. Idempotent; needs network + unzip. -if command -v apt-get >/dev/null 2>&1; then - apt-get -o DPkg::Lock::Timeout=600 update >/dev/null 2>&1 || - echo "Warning: apt-get update failed; chrome's shared libs may stay unresolved." >&2 -fi - -provision_browser() { - timeout 900 npx --yes puppeteer browsers install chrome-headless-shell --install-deps 2>&1 -} - -if ! deps_output="$(provision_browser)"; then - rm -rf "${PUPPETEER_CACHE_DIR:-${HOME}/.cache/puppeteer}/chrome-headless-shell" - if ! deps_output="$(provision_browser)"; then - printf 'Warning: chrome-headless-shell provisioning failed; mermaid rendering may fail:\n%s\n' \ - "${deps_output}" >&2 - fi -fi - workdir="$(mktemp -d)" trap 'rm -rf "${workdir}"' EXIT @@ -54,6 +33,15 @@ if [[ ${#md_files[@]} -eq 0 ]]; then exit 0 fi +printf '%s\n' 'flowchart LR' ' a --> b' >"${workdir}/preflight.mmd" +if ! mmdc --puppeteerConfigFile "${puppeteer_cfg}" -i "${workdir}/preflight.mmd" \ + -o "${workdir}/preflight.svg" >"${workdir}/preflight.log" 2>&1; then + printf "mmdc cannot render a minimal diagram, so none of the %d Markdown file(s) was checked. 'make install-lint-force' provisions its browser:\n" \ + "${#md_files[@]}" >&2 + sed 's/^/ /' "${workdir}/preflight.log" >&2 + exit 1 +fi + : "${INFINITO_WORKER_CPU:?INFINITO_WORKER_CPU must be set (provided by default.env via the env loader)}" jobs="${INFINITO_WORKER_CPU}" diff --git a/scripts/meta/resolve/missing/highest_release_tag.sh b/scripts/meta/resolve/missing/highest_release_tag.sh index c4d50746cf..a7769f62e2 100755 --- a/scripts/meta/resolve/missing/highest_release_tag.sh +++ b/scripts/meta/resolve/missing/highest_release_tag.sh @@ -1,6 +1,11 @@ #!/usr/bin/env bash set -euo pipefail +# The backfill stops below v9.0.2: v9.0.1 cannot build its image from its own +# tree (`infinito: command not found`, fixed by c680be12ea in v9.0.2), and +# v9.0.0 has the same Dockerfile, Makefile and scripts/docker. +oldest_buildable_tag="v9.0.2" + : "${OWNER:?Missing OWNER}" : "${REGISTRY:?Missing REGISTRY}" : "${REPO_PREFIX:?Missing REPO_PREFIX}" @@ -48,6 +53,9 @@ fi for ((i = ${#tags[@]} - 1; i >= 0; i--)); do tag="${tags[$i]}" + if [[ "$(printf '%s\n' "${tag}" "${oldest_buildable_tag}" | sort -V | head -n 1)" != "${oldest_buildable_tag}" ]]; then + exit 0 + fi tag_missing="false" for distro in ${INFINITO_DISTROS}; do diff --git a/tests/unit/python/roles/sys-svc-container/files/test_apt_repo.py b/tests/unit/python/roles/sys-svc-container/files/test_apt_repo.py new file mode 100644 index 0000000000..66abd7521e --- /dev/null +++ b/tests/unit/python/roles/sys-svc-container/files/test_apt_repo.py @@ -0,0 +1,100 @@ +import os +import subprocess +import tempfile +import unittest +from pathlib import Path + +from utils import PROJECT_ROOT +from utils.cache.files import read_text + +SCRIPT = PROJECT_ROOT / "roles/sys-svc-container/files/shell/apt_repo.sh" + +CURL_STUB = """#!/bin/sh +dest="" +while [ "$#" -gt 0 ]; do +\tif [ "$1" = "-o" ]; then +\t\tdest="$2" +\t\tshift +\tfi +\tshift +done +if [ -z "$STUB_SERVED_KEY" ]; then +\techo "curl: (7) Failed to connect to download.docker.com port 443 after 0 ms" >&2 +\texit 7 +fi +cp "$STUB_SERVED_KEY" "$dest" +""" + +SUDO_STUB = '#!/bin/sh\nexec "$@"\n' + + +class TestAptRepoInstallKey(unittest.TestCase): + def run_install_key(self, *, installed, served): + """Run `apt_repo.sh install-key` against a stubbed key download. + + Args: + installed: content of the keyring before the run, or None when no + key is installed. + served: content the download returns, or None when the download + host refuses the connection. + + Returns: + Tuple of exit code, stdout, stderr and the keyring content after + the run (None when no keyring exists). + """ + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + bin_dir = root / "bin" + bin_dir.mkdir() + for name, body in (("curl", CURL_STUB), ("sudo", SUDO_STUB)): + stub = bin_dir / name + stub.write_text(body) + stub.chmod(0o755) + keyring_dir = root / "keyrings" + keyring_dir.mkdir() + keyring_dir.chmod(0o755) + key = keyring_dir / "docker.asc" + if installed is not None: + key.write_text(installed) + key.chmod(0o644) + env = dict(os.environ) + env["PATH"] = f"{bin_dir}{os.pathsep}{env['PATH']}" + env["STUB_SERVED_KEY"] = "" + if served is not None: + served_file = root / "served.asc" + served_file.write_text(served) + env["STUB_SERVED_KEY"] = str(served_file) + done = subprocess.run( + ["bash", str(SCRIPT), "install-key", "debian", str(key)], + env=env, + capture_output=True, + text=True, + check=False, + ) + after = read_text(str(key)) if key.exists() else None + return done.returncode, done.stdout, done.stderr, after + + def test_a_refused_download_keeps_the_installed_key(self): + code, out, err, after = self.run_install_key(installed="OLD KEY\n", served=None) + self.assertEqual(code, 0, err) + self.assertIn("changed=0", out) + self.assertIn("keeping", err) + self.assertEqual(after, "OLD KEY\n") + + def test_a_refused_download_without_a_key_fails(self): + code, _, err, after = self.run_install_key(installed=None, served=None) + self.assertEqual(code, 1) + self.assertIn("Failed to download the Docker GPG key", err) + self.assertIsNone(after) + + def test_a_new_key_replaces_the_installed_one(self): + code, out, err, after = self.run_install_key( + installed="OLD KEY\n", served="NEW KEY\n" + ) + self.assertEqual(code, 0, err) + self.assertIn("changed=1", out) + self.assertEqual(after, "NEW KEY\n") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/scripts/lint/__init__.py b/tests/unit/python/scripts/lint/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/scripts/lint/test_mermaid.py b/tests/unit/python/scripts/lint/test_mermaid.py new file mode 100644 index 0000000000..67d3099a2f --- /dev/null +++ b/tests/unit/python/scripts/lint/test_mermaid.py @@ -0,0 +1,62 @@ +"""``scripts/lint/mermaid.sh`` renders with the browser install-lint provisioned. + +``make lint`` runs its targets in parallel, so the script must not reach for a +package manager, and a browser that cannot start must fail the lint once with +its reason instead of once per Markdown file. +""" + +from __future__ import annotations + +import os +import subprocess +import tempfile +import unittest +from pathlib import Path + +from utils.cache.files import PROJECT_ROOT + +SCRIPT = Path(PROJECT_ROOT) / "scripts" / "lint" / "mermaid.sh" +LIBRARY_ERROR = ( + "chrome-headless-shell: error while loading shared libraries: libnspr4.so" +) +RECORDING_STUB = '#!/bin/sh\necho "$(basename "$0")" >> "$STUB_CALLS"\n' + + +class TestMermaidLint(unittest.TestCase): + def test_a_browser_that_cannot_start_fails_before_any_file_renders(self): + with tempfile.TemporaryDirectory() as tmp: + bin_dir = Path(tmp) + calls = bin_dir / "calls" + calls.touch() + for name in ("npx", "apt-get"): + (bin_dir / name).write_text(RECORDING_STUB) + (bin_dir / "mmdc").write_text( + f"{RECORDING_STUB}echo '{LIBRARY_ERROR}' >&2\nexit 1\n" + ) + for stub in bin_dir.iterdir(): + stub.chmod(0o755) + env = { + k: v + for k, v in os.environ.items() + if not k.startswith("INFINITO_") and k != "BASH_ENV" + } + env["PATH"] = f"{bin_dir}{os.pathsep}{env['PATH']}" + env["STUB_CALLS"] = str(calls) + proc = subprocess.run( + ["bash", str(SCRIPT)], + env=env, + capture_output=True, + text=True, + check=False, + ) + recorded = calls.read_text().split() # nocheck: cache-read stub call log + + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertIn("cannot render a minimal diagram", proc.stderr) + self.assertIn(LIBRARY_ERROR, proc.stderr) + self.assertNotIn("❌", proc.stdout) + self.assertEqual(recorded, ["mmdc"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/scripts/meta/resolve/missing/__init__.py b/tests/unit/python/scripts/meta/resolve/missing/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/scripts/meta/resolve/missing/test_highest_release_tag.py b/tests/unit/python/scripts/meta/resolve/missing/test_highest_release_tag.py new file mode 100644 index 0000000000..c9801bb119 --- /dev/null +++ b/tests/unit/python/scripts/meta/resolve/missing/test_highest_release_tag.py @@ -0,0 +1,66 @@ +from __future__ import annotations + +import os +import subprocess +import tempfile +import unittest +from pathlib import Path + +from utils.cache.files import PROJECT_ROOT + +SCRIPT = ( + PROJECT_ROOT / "scripts" / "meta" / "resolve" / "missing" / "highest_release_tag.sh" +) +TAGS = ("v9.0.0", "v9.0.1", "v9.0.2", "v14.1.0", "v15.0.0") +STUBS = { + "git": '#!/usr/bin/env bash\nprintf "%s\\n" ${STUB_TAGS}\n', + "docker": ( + "#!/usr/bin/env bash\n" + 'case " ${STUB_MISSING} " in *" ${3##*:} "*) exit 1 ;; esac\n' + ), +} + + +def pick(*missing: str) -> subprocess.CompletedProcess: + """Run the picker against stubbed ``git`` tags and ``docker`` manifests. + + Args: + missing: tags whose images the registry does not hold. + """ + with tempfile.TemporaryDirectory() as tmp: + for name, body in STUBS.items(): + stub = Path(tmp) / name + stub.write_text(body) + stub.chmod(0o755) + env = { + **{k: v for k, v in os.environ.items() if k != "BASH_ENV"}, + "PATH": f"{tmp}{os.pathsep}{os.environ['PATH']}", + "STUB_TAGS": " ".join(TAGS), + "STUB_MISSING": " ".join(missing), + "OWNER": "acme", + "REGISTRY": "ghcr.io", + "REPO_PREFIX": "core", + "INFINITO_DISTROS": "debian arch", + } + return subprocess.run( + ["bash", str(SCRIPT)], + env=env, + capture_output=True, + text=True, + check=True, + ) + + +class TestHighestReleaseTag(unittest.TestCase): + def test_tags_below_the_oldest_buildable_one_are_not_picked(self) -> None: + self.assertEqual("", pick("v9.0.1", "v9.0.0").stdout) + + def test_the_oldest_buildable_tag_is_picked(self) -> None: + self.assertEqual("v9.0.2\n", pick("v9.0.2", "v9.0.1").stdout) + + def test_the_highest_missing_tag_is_picked(self) -> None: + self.assertEqual("v14.1.0\n", pick("v14.1.0", "v9.0.1").stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/docker/test_image_discovery_lifecycle.py b/tests/unit/python/utils/docker/test_image_discovery_lifecycle.py index f7a0c60577..f9c333a2fc 100644 --- a/tests/unit/python/utils/docker/test_image_discovery_lifecycle.py +++ b/tests/unit/python/utils/docker/test_image_discovery_lifecycle.py @@ -1,5 +1,6 @@ from __future__ import annotations +import os import tempfile import unittest from pathlib import Path @@ -8,7 +9,7 @@ from utils.docker.image.discovery import iter_role_images, role_lifecycle from utils.roles.mapping import ROLE_FILE_META_SERVICES SUPPORTED = """--- -engine: +demo: image: libretranslate/libretranslate version: v1.9.6 lifecycle: stable @@ -18,7 +19,7 @@ helper: """ RETIRED = """--- -store: +demo: image: quay.io/minio/minio version: RELEASE.2025-09-07T16-13-09Z lifecycle: eol @@ -28,24 +29,31 @@ client: """ UNSTAGED = """--- -engine: +demo: image: libretranslate/libretranslate version: v1.9.6 """ class TestImageDiscoveryLifecycle(unittest.TestCase): - def _images(self, services_yaml: str) -> set[str]: + def _images(self, services_yaml: str, *, relative: bool = False) -> set[str]: + """Discover the images of one role written into a temporary repository. + + Args: + services_yaml: the role's ``meta/services.yml``. + relative: pass the repository root relative to the working directory. + """ with tempfile.TemporaryDirectory() as tmp: services = Path(tmp) / "roles" / "web-app-demo" / ROLE_FILE_META_SERVICES services.parent.mkdir(parents=True) services.write_text(services_yaml, encoding="utf-8") - return {ref.service for ref in iter_role_images(Path(tmp))} + root = Path(os.path.relpath(tmp)) if relative else Path(tmp) + return {ref.service for ref in iter_role_images(root)} def test_a_supported_role_yields_every_service(self) -> None: - self.assertEqual({"engine", "helper"}, self._images(SUPPORTED)) + self.assertEqual({"demo", "helper"}, self._images(SUPPORTED)) - def test_a_retired_role_yields_nothing(self) -> None: + def test_a_retired_role_yields_none_of_its_services(self) -> None: """Its upstream may withdraw the images; no deploy can reach them.""" self.assertEqual(set(), self._images(RETIRED)) @@ -54,7 +62,10 @@ class TestImageDiscoveryLifecycle(unittest.TestCase): self.assertNotIn("client", self._images(RETIRED)) def test_a_role_that_names_no_stage_is_kept(self) -> None: - self.assertEqual({"engine"}, self._images(UNSTAGED)) + self.assertEqual({"demo"}, self._images(UNSTAGED)) + + def test_a_relative_root_still_leaves_a_retired_role_out(self) -> None: + self.assertEqual(set(), self._images(RETIRED, relative=True)) class TestRoleLifecycle(unittest.TestCase): diff --git a/tests/unit/python/utils/install/lint/test_main.py b/tests/unit/python/utils/install/lint/test_main.py index c044c3afa9..1ac3539ca8 100644 --- a/tests/unit/python/utils/install/lint/test_main.py +++ b/tests/unit/python/utils/install/lint/test_main.py @@ -34,12 +34,30 @@ class TestStampLogic(unittest.TestCase): with ( mock.patch.object(cli, "PROJECT_ROOT", root), mock.patch.object(cli.shutil, "which", return_value="/usr/bin/x"), + mock.patch.object( + cli.mermaid_cli, "browser_installed", return_value=True + ), mock.patch.object(cli, "_install_all") as inst, ): rc = cli.main([]) self.assertEqual(rc, 0) inst.assert_not_called() + def test_missing_mermaid_browser_invalidates_stamp(self) -> None: + with TemporaryDirectory() as tmp: + root = _make_repo_root(tmp, stamp_age_offset=60.0) + with ( + mock.patch.object(cli, "PROJECT_ROOT", root), + mock.patch.object(cli.shutil, "which", return_value="/usr/bin/x"), + mock.patch.object( + cli.mermaid_cli, "browser_installed", return_value=False + ), + mock.patch.object(cli, "_install_all") as inst, + ): + rc = cli.main([]) + self.assertEqual(rc, 0) + inst.assert_called_once() + def test_missing_tool_invalidates_stamp(self) -> None: with TemporaryDirectory() as tmp: root = _make_repo_root(tmp, stamp_age_offset=60.0) @@ -81,9 +99,10 @@ class TestStampLogic(unittest.TestCase): self.assertTrue((root / cli._STAMP).exists()) def test_force_drops_stamp(self) -> None: - with TemporaryDirectory() as tmp: + with TemporaryDirectory() as tmp, TemporaryDirectory() as cache: root = _make_repo_root(tmp, stamp_age_offset=60.0) with ( + mock.patch.dict(os.environ, {"PUPPETEER_CACHE_DIR": cache}), mock.patch.object(cli, "PROJECT_ROOT", root), mock.patch.object(cli, "_install_all") as inst, ): @@ -91,6 +110,19 @@ class TestStampLogic(unittest.TestCase): self.assertEqual(rc, 0) inst.assert_called_once() + def test_force_drops_the_mermaid_browser(self) -> None: + with TemporaryDirectory() as tmp, TemporaryDirectory() as cache: + root = _make_repo_root(tmp, stamp_age_offset=60.0) + browser = Path(cache) / "chrome-headless-shell" / "linux-1" + browser.mkdir(parents=True) + with ( + mock.patch.dict(os.environ, {"PUPPETEER_CACHE_DIR": cache}), + mock.patch.object(cli, "PROJECT_ROOT", root), + mock.patch.object(cli, "_install_all"), + ): + cli.main(["--force"]) + self.assertFalse(browser.exists()) + class TestGroupDispatch(unittest.TestCase): def test_group_only_bypasses_stamp(self) -> None: diff --git a/tests/unit/python/utils/install/lint/test_mermaid_cli.py b/tests/unit/python/utils/install/lint/test_mermaid_cli.py new file mode 100644 index 0000000000..600879cf61 --- /dev/null +++ b/tests/unit/python/utils/install/lint/test_mermaid_cli.py @@ -0,0 +1,128 @@ +"""Unit tests for :mod:`utils.install.lint.mermaid_cli`.""" + +from __future__ import annotations + +import os +import subprocess +import unittest +import unittest.mock as mock +from pathlib import Path +from tempfile import TemporaryDirectory + +from utils.install.lint import mermaid_cli + + +def _done(returncode: int) -> subprocess.CompletedProcess[str]: + return subprocess.CompletedProcess([], returncode, stdout="out\n", stderr="err\n") + + +class TestBrowserProvisioning(unittest.TestCase): + def provision(self, *, euid: int, results: list[int]) -> tuple[list, list[str]]: + """Run ``ensure()`` with mmdc present and a stubbed puppeteer. + + Args: + euid: effective uid the run pretends to have. + results: exit codes the successive puppeteer calls return. + + Returns: + The recorded subprocess calls and the warnings emitted. + """ + warnings: list[str] = [] + with ( + TemporaryDirectory() as cache, + mock.patch.dict(os.environ, {"PUPPETEER_CACHE_DIR": cache}), + mock.patch.object(mermaid_cli, "which", return_value=True), + mock.patch.object(mermaid_cli.os, "geteuid", return_value=euid), + mock.patch.object(mermaid_cli, "warn", side_effect=warnings.append), + mock.patch.object( + mermaid_cli.subprocess, + "run", + side_effect=[_done(code) for code in results], + ) as run, + ): + mermaid_cli.ensure() + return run.call_args_list, warnings + + def test_root_installs_the_browser_with_its_libraries(self) -> None: + calls, warnings = self.provision(euid=0, results=[0]) + self.assertEqual(len(calls), 1) + self.assertEqual( + calls[0].args[0][-2:], ["chrome-headless-shell", "--install-deps"] + ) + self.assertEqual(warnings, []) + + def test_a_user_installs_the_browser_without_libraries(self) -> None: + calls, _ = self.provision(euid=1000, results=[0]) + self.assertNotIn("--install-deps", calls[0].args[0]) + + def test_the_browser_install_downloads_despite_the_mmdc_skip_flag(self) -> None: + with mock.patch.dict(os.environ, {"PUPPETEER_SKIP_DOWNLOAD": "1"}): + calls, _ = self.provision(euid=0, results=[0]) + self.assertNotIn("PUPPETEER_SKIP_DOWNLOAD", calls[0].kwargs["env"]) + + def test_a_failed_install_clears_the_browser_cache_and_retries_once(self) -> None: + with TemporaryDirectory() as cache: + folder = Path(cache) / "chrome-headless-shell" / "linux-1" + folder.mkdir(parents=True) + seen: list[bool] = [] + + def run(*_args, **_kwargs): + seen.append(folder.exists()) + return _done(1 if len(seen) == 1 else 0) + + with ( + mock.patch.dict(os.environ, {"PUPPETEER_CACHE_DIR": cache}), + mock.patch.object(mermaid_cli, "which", return_value=True), + mock.patch.object(mermaid_cli.subprocess, "run", side_effect=run), + ): + mermaid_cli.ensure() + self.assertEqual(seen, [True, False]) + + def test_a_second_failure_warns_with_puppeteers_output(self) -> None: + calls, warnings = self.provision(euid=0, results=[1, 1]) + self.assertEqual(len(calls), 2) + self.assertEqual(len(warnings), 1) + self.assertIn("out\nerr\n", warnings[0]) + + def test_an_installed_browser_is_not_provisioned_again(self) -> None: + with TemporaryDirectory() as cache: + build = Path(cache) / "chrome-headless-shell" / "linux-1" / "linux64" + build.mkdir(parents=True) + (build / "chrome-headless-shell").write_text("", encoding="utf-8") + with ( + mock.patch.dict(os.environ, {"PUPPETEER_CACHE_DIR": cache}), + mock.patch.object(mermaid_cli, "which", return_value=True), + mock.patch.object(mermaid_cli.subprocess, "run") as run, + ): + mermaid_cli.ensure() + run.assert_not_called() + + def test_a_timeout_warns_instead_of_raising(self) -> None: + with ( + TemporaryDirectory() as cache, + mock.patch.dict(os.environ, {"PUPPETEER_CACHE_DIR": cache}), + mock.patch.object(mermaid_cli, "which", return_value=True), + mock.patch.object( + mermaid_cli.subprocess, + "run", + side_effect=subprocess.TimeoutExpired("npx", 900), + ), + mock.patch.object(mermaid_cli, "warn") as warn, + ): + mermaid_cli.ensure() + warn.assert_called_once() + + +class TestBrowserInstalled(unittest.TestCase): + def test_the_executable_in_the_puppeteer_cache_counts(self) -> None: + with TemporaryDirectory() as cache: + build = Path(cache) / "chrome-headless-shell" / "linux-1" / "linux64" + build.mkdir(parents=True) + with mock.patch.dict(os.environ, {"PUPPETEER_CACHE_DIR": cache}): + self.assertFalse(mermaid_cli.browser_installed()) + (build / "chrome-headless-shell").write_text("", encoding="utf-8") + self.assertTrue(mermaid_cli.browser_installed()) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/docker/image/discovery.py b/utils/docker/image/discovery.py index b6f19a2238..f31d8f48ac 100644 --- a/utils/docker/image/discovery.py +++ b/utils/docker/image/discovery.py @@ -6,6 +6,7 @@ from typing import TYPE_CHECKING from utils.cache.yaml import load_yaml_any as _load_yaml_cached from utils.docker.image.pin import pull_reference from utils.roles.mapping import ROLE_FILE_META_SERVICES +from utils.update.base import is_maintained if TYPE_CHECKING: from collections.abc import Iterable @@ -219,18 +220,22 @@ def iter_role_images(repo_root: Path) -> Iterable[ImageRef]: function is the only enumeration the mirror sees and a tag it never emits can never be mirrored. - An ``eol`` role is left out entirely. It is outside the lifecycle envelope - ``default.env`` tests, so no deploy can reach its images, and a retired - role's upstream is free to withdraw them: MinIO's quay tags answer 401 to - anonymous pulls and exist nowhere else, which failed the mirror job on - every run while nothing could have consumed the result. + Two kinds of role are left out. One the updaters do not maintain + (``is_maintained``), and one whose lifecycle is ``eol``: a retired role sits + outside the lifecycle envelope ``default.env`` tests, so no deploy can reach + its images, and its upstream is free to withdraw them. MinIO's quay tags + answer 401 to anonymous pulls and exist nowhere else, which failed the + mirror job on every run while nothing could have consumed the result. See docs/contributing/artefact/image.md for the full format reference. """ - roles_dir = repo_root / "roles" + roles_dir = (repo_root / "roles").resolve() for services_file in roles_dir.glob(f"**/{ROLE_FILE_META_SERVICES}"): role_name = services_file.parent.parent.name + if not is_maintained(roles_dir, role_name): + continue + services = load_yaml(services_file) if not isinstance(services, dict): diff --git a/utils/install/lint/__main__.py b/utils/install/lint/__main__.py index 11fb1fc56a..9fed403e4b 100644 --- a/utils/install/lint/__main__.py +++ b/utils/install/lint/__main__.py @@ -2,7 +2,8 @@ Mirrors the prior ``scripts/install/lint.sh`` interface: no-arg / ``all`` runs every group + manages the stamp file; explicit groups bypass the -stamp; ``--force`` (as first arg) drops the stamp and reinstalls. +stamp; ``--force`` (as first arg) drops the stamp and mmdc's browser cache +and reinstalls. """ from __future__ import annotations @@ -177,7 +178,10 @@ def _stamp_is_fresh(repo_root: Path) -> bool: return False if dep_path.stat().st_mtime > stamp_mtime: return False - return all(shutil.which(tool) is not None for tool in _STAMP_TOOLS) + return ( + all(shutil.which(tool) is not None for tool in _STAMP_TOOLS) + and mermaid_cli.browser_installed() + ) def _touch_stamp(repo_root: Path) -> None: @@ -212,6 +216,7 @@ def main(argv: list[str] | None = None) -> int: stamp_path = repo_root / _STAMP if stamp_path.exists(): stamp_path.unlink() + shutil.rmtree(mermaid_cli.browser_cache(), ignore_errors=True) args = args[1:] if not args: diff --git a/utils/install/lint/mermaid_cli.py b/utils/install/lint/mermaid_cli.py index 099af21a4d..e60a96371a 100644 --- a/utils/install/lint/mermaid_cli.py +++ b/utils/install/lint/mermaid_cli.py @@ -1,24 +1,28 @@ -"""Install @mermaid-js/mermaid-cli (mmdc) via npm global. +"""Install @mermaid-js/mermaid-cli (mmdc) and the chrome-headless-shell it renders with. -Best-effort: the puppeteer browser is not downloaded here -(``PUPPETEER_SKIP_DOWNLOAD``) so ``install-lint`` stays sandbox-safe. mmdc only -needs a browser to RENDER, which ``scripts/lint/mermaid.sh`` provisions on demand -(``npx puppeteer browsers install chrome-headless-shell``) right before it -renders. That browser ships as a zip, so ``unzip`` is ensured here (puppeteer's -extractor needs it, else it leaves an empty version dir and mmdc reports the -browser missing). A failed install warns instead of aborting ``install-lint``, -so sandboxes without npm/browser access still get the rest of the lint toolchain. +mmdc comes from npm with ``PUPPETEER_SKIP_DOWNLOAD`` set; the browser is +provisioned through puppeteer afterwards, as root with its shared libraries +(``--install-deps``). ``unzip`` is ensured first because puppeteer extracts the +browser with it. A failed install warns instead of aborting ``install-lint``, so +sandboxes without npm or browser access still get the rest of the lint +toolchain. """ from __future__ import annotations import contextlib import os +import shutil +import subprocess +from pathlib import Path from utils.install.npm import npm_install_global from utils.install.primitives import log, warn, which from utils.install.system_pkg import install_command_via_pkg +BROWSER = "chrome-headless-shell" +PROVISION_TIMEOUT_S = 900 + def _ensure_unzip() -> None: if which("unzip"): @@ -27,16 +31,60 @@ def _ensure_unzip() -> None: install_command_via_pkg("unzip") +def browser_cache() -> Path: + base = os.environ.get("PUPPETEER_CACHE_DIR") or Path.home() / ".cache" / "puppeteer" + return Path(base) / BROWSER + + +def browser_installed() -> bool: + return any(path.is_file() for path in browser_cache().glob(f"*/*/{BROWSER}")) + + +def _provision_browser() -> subprocess.CompletedProcess[str]: + argv = ["npx", "--yes", "puppeteer", "browsers", "install", BROWSER] + if os.geteuid() == 0: + argv.append("--install-deps") + env = {k: v for k, v in os.environ.items() if k != "PUPPETEER_SKIP_DOWNLOAD"} + return subprocess.run( + argv, + env=env, + capture_output=True, + text=True, + timeout=PROVISION_TIMEOUT_S, + check=False, + ) + + +def _ensure_browser() -> None: + if browser_installed(): + return + log(f"Provisioning {BROWSER} for mmdc via puppeteer.") + try: + done = _provision_browser() + if done.returncode != 0: + shutil.rmtree(browser_cache(), ignore_errors=True) + done = _provision_browser() + except (OSError, subprocess.TimeoutExpired) as exc: + warn(f"{BROWSER} provisioning skipped (optional lint tool): {exc}") + return + if done.returncode != 0: + warn( + f"{BROWSER} provisioning failed (optional lint tool):\n" + f"{done.stdout}{done.stderr}" + ) + + def ensure() -> None: _ensure_unzip() - if which("mmdc"): - return - log("Missing command 'mmdc'. Installing @mermaid-js/mermaid-cli via npm.") - os.environ["PUPPETEER_SKIP_DOWNLOAD"] = "1" - try: - npm_install_global("@mermaid-js/mermaid-cli") - except Exception as exc: # noqa: BLE001 - best-effort optional lint tool - warn(f"mermaid-cli install skipped (optional lint tool): {exc}") - return if not which("mmdc"): - warn("Command 'mmdc' is still unavailable after installation.") + log("Missing command 'mmdc'. Installing @mermaid-js/mermaid-cli via npm.") + os.environ["PUPPETEER_SKIP_DOWNLOAD"] = "1" + try: + npm_install_global("@mermaid-js/mermaid-cli") + except Exception as exc: # noqa: BLE001 - best-effort optional lint tool + warn(f"mermaid-cli install skipped (optional lint tool): {exc}") + return + if not which("mmdc"): + warn("Command 'mmdc' is still unavailable after installation.") + return + _ensure_browser()