From bfaa834f29fff1a16ec355ff64f0bdc6d02c39e3 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 14 Oct 2026 13:34:52 +0200 Subject: [PATCH 01/13] fix(web-app-nextcloud): write onlyoffice's server URL last and recheck it The role writes onlyoffice's settings with one occ call per key, DocumentServerUrl first and jwt_secret fourth. Nextcloud loads app config once per process, so a cron.php that starts inside that batch runs onlyoffice's EditorsCheck job, registered when the app was enabled, with the document server URL but without the secret. The document server answers "Invalid token", EditorsCheck stores it in settings_error, and onlyoffice stops loading its Files integration; EditorsCheck itself skips every later run while that error is set. Seen in run 38455782184 (Nextcloud#4, swarm): cron.php started at 06:50:00 inside the batch that ran from 06:49:59 to 06:50:04, logged "Invalid token" at 06:50:22, and both Playwright passes found .docx files offered for download only. DocumentServerUrl is now written last, so a process that cached the config before the batch ended sees no URL and EditorsCheck returns early. After the batch, `occ onlyoffice:documentserver --check` sets settings_error from a fresh check: a redeploy clears an error latched earlier, and a document server that stays unreachable fails the deploy. A unit test keeps the URL last. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../meta/addons/onlyoffice.yml | 6 ++--- .../tasks/addons/onlyoffice.yml | 8 +++++++ .../test_onlyoffice_configuration_order.py | 24 +++++++++++++++++++ 3 files changed, 35 insertions(+), 3 deletions(-) create mode 100644 tests/unit/python/roles/web-app-nextcloud/test_onlyoffice_configuration_order.py diff --git a/roles/web-app-nextcloud/meta/addons/onlyoffice.yml b/roles/web-app-nextcloud/meta/addons/onlyoffice.yml index e1ee56880b..ba5d4aa6b6 100644 --- a/roles/web-app-nextcloud/meta/addons/onlyoffice.yml +++ b/roles/web-app-nextcloud/meta/addons/onlyoffice.yml @@ -16,9 +16,6 @@ config: - richdocuments - fileslibreofficeedit plugin_configuration: - - appid: "onlyoffice" - configkey: "DocumentServerUrl" - configvalue: "{{ NEXTCLOUD_ONLYOFFICE_URL }}" - appid: "onlyoffice" configkey: "DocumentServerInternalUrl" configvalue: "{{ NEXTCLOUD_ONLYOFFICE_URL }}" @@ -34,3 +31,6 @@ config: - appid: "onlyoffice" configkey: "verify_peer_off" configvalue: "false" + - appid: "onlyoffice" + configkey: "DocumentServerUrl" + configvalue: "{{ NEXTCLOUD_ONLYOFFICE_URL }}" diff --git a/roles/web-app-nextcloud/tasks/addons/onlyoffice.yml b/roles/web-app-nextcloud/tasks/addons/onlyoffice.yml index ed97d539c0..54763fb5c3 100644 --- a/roles/web-app-nextcloud/tasks/addons/onlyoffice.yml +++ b/roles/web-app-nextcloud/tasks/addons/onlyoffice.yml @@ -1 +1,9 @@ --- +- name: "🔎 Check the document server round trip and reset onlyoffice's settings_error" + shell: > + {{ NEXTCLOUD_DOCKER_EXEC_OCC }} onlyoffice:documentserver --check + register: nextcloud_onlyoffice_check + until: nextcloud_onlyoffice_check.rc == 0 + retries: 30 + delay: 10 + changed_when: false diff --git a/tests/unit/python/roles/web-app-nextcloud/test_onlyoffice_configuration_order.py b/tests/unit/python/roles/web-app-nextcloud/test_onlyoffice_configuration_order.py new file mode 100644 index 0000000000..46842ce58f --- /dev/null +++ b/tests/unit/python/roles/web-app-nextcloud/test_onlyoffice_configuration_order.py @@ -0,0 +1,24 @@ +from __future__ import annotations + +import unittest + +from utils.cache.files import PROJECT_ROOT, read_text +from utils.cache.yaml import load_yaml_str + +ADDON = PROJECT_ROOT / "roles/web-app-nextcloud/meta/addons/onlyoffice.yml" + + +class TestOnlyofficeConfigurationOrder(unittest.TestCase): + def test_the_document_server_url_is_written_last(self) -> None: + config = load_yaml_str(read_text(str(ADDON)))["config"]["plugin_configuration"] + self.assertEqual( + config[-1]["configkey"], + "DocumentServerUrl", + "a cron.php that caches app config before the last write must see no " + "DocumentServerUrl, or onlyoffice's EditorsCheck runs without jwt_secret " + "and latches settings_error", + ) + + +if __name__ == "__main__": + unittest.main() From 7e68dc4c61e8e062e6de54db490f403f0858e546 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 15 Oct 2026 00:59:39 +0200 Subject: [PATCH 02/13] fix(web-app-bluesky): read the PDS admin password and clear the restore timer - Administration.md: the createAccount example reads PDS_ADMIN_PASSWORD from the PDS container before calling curl and unsets it afterwards. The operator shell had no value, so curl sent empty Basic Auth credentials. - _appview.js: restorePreferences clears its deadline timer once the race settles, so a Playwright worker no longer stays alive until the 45 s timer fires. Addresses the CodeRabbit review on #917. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-bluesky/Administration.md | 2 ++ roles/web-app-bluesky/files/playwright/_appview.js | 7 +++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/roles/web-app-bluesky/Administration.md b/roles/web-app-bluesky/Administration.md index a610f909dd..e3bffc970d 100644 --- a/roles/web-app-bluesky/Administration.md +++ b/roles/web-app-bluesky/Administration.md @@ -3,6 +3,7 @@ ## Create a user via POST ```bash +PDS_ADMIN_PASSWORD="$(compose exec -T pds printenv PDS_ADMIN_PASSWORD)" curl -X POST https://your-pds-domain/xrpc/com.atproto.server.createAccount \ --user "admin:${PDS_ADMIN_PASSWORD}" \ -H "Content-Type: application/json" \ @@ -12,6 +13,7 @@ curl -X POST https://your-pds-domain/xrpc/com.atproto.server.createAccount \ "password": "securepassword123", "inviteCode": "optional-invite-code" }' +unset PDS_ADMIN_PASSWORD ``` ## Use pdsadmin diff --git a/roles/web-app-bluesky/files/playwright/_appview.js b/roles/web-app-bluesky/files/playwright/_appview.js index d5e89d07e9..590297b66c 100644 --- a/roles/web-app-bluesky/files/playwright/_appview.js +++ b/roles/web-app-bluesky/files/playwright/_appview.js @@ -56,10 +56,13 @@ async function restorePreferences(request, pdsBaseUrl, accessJwt, preferences) { }).then((response) => { if (response.status() !== 200) throw new Error(`putPreferences answered ${response.status()}`); }); + let timer; const deadline = new Promise((_, reject) => { - setTimeout(() => reject(new Error("putPreferences timed out")), resolveTimeout(45_000)); + timer = setTimeout(() => reject(new Error("putPreferences timed out")), resolveTimeout(45_000)); }); - await Promise.race([restore, deadline]).catch((err) => console.warn(`bluesky: preferences not restored: ${err.message}`)); + await Promise.race([restore, deadline]) + .catch((err) => console.warn(`bluesky: preferences not restored: ${err.message}`)) + .finally(() => clearTimeout(timer)); } function collectAppViewResponses(page) { From 28a90a16341671f3c3345b29094021ac4e2a9a4e Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 15 Oct 2026 03:21:23 +0200 Subject: [PATCH 03/13] fix(sys-ctl-hlth-csp): crawl redirect sources whose target this node serves HEALTH_CSP_SKIP_DOMAINS skipped every CURRENT_PLAY_REDIRECT_DOMAINS source: the DOMAIN_PRIMARY apex, the node onion apex, inventory redirect mappings and per-app aliases. The skip dates from when the checker judged the 301 itself; since csp-checker 3.0.0 it follows the redirect chain and judges the document it lands on. So a broken or unserved alias target, and a redirect leaving its network, were never loaded. A redirect source now stays skipped only when its target is not among CURRENT_PLAY_DOMAINS_ALL, i.e. lies off this node, like SOFTWARE_DOMAIN for the apex without web-app-dashboard. Every other source is crawled. Closes #929 Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/sys-ctl-hlth-csp/vars/main.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/roles/sys-ctl-hlth-csp/vars/main.yml b/roles/sys-ctl-hlth-csp/vars/main.yml index ea8d4a0ce0..9e20db80a0 100644 --- a/roles/sys-ctl-hlth-csp/vars/main.yml +++ b/roles/sys-ctl-hlth-csp/vars/main.yml @@ -8,5 +8,6 @@ HEALTH_CSP_SKIP_DOMAINS: >- {{ ( lookup('csp_skip_domains', group_names=lookup('deployment').deployed) + (CURRENT_PLAY_REDIRECT_DOMAINS | default([]) + | rejectattr('target', 'in', CURRENT_PLAY_DOMAINS_ALL) | map(attribute='source') | list) ) | unique }} From cce4373abdbfb963ced7f4a66db633d73b936517 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 15 Oct 2026 04:04:33 +0200 Subject: [PATCH 04/13] fix(web-app-nextcloud): bound the onlyoffice check by a wall-clock deadline `retries: 30` with `delay: 10` only bounded the wait while each `occ onlyoffice:documentserver --check` failed fast. onlyoffice v10.2.1 gives the health check and the version command 60 s each and the conversion 120 s, so a document server that accepts connections but does not answer held the deploy for up to two hours before it failed. The retries now also stop once a deadline of `lookup('timeout', 300)` seconds, set right before the check, has passed. A per-attempt `timeout:` would not bound the total: ansible-core 2.21 leaves the `until` loop on the first timed-out attempt, so only a limit below onlyoffice's 60 s would end a hanging server's loop. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../tasks/addons/onlyoffice.yml | 8 +++++- .../test_onlyoffice_check_deadline.py | 28 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 tests/unit/python/roles/web-app-nextcloud/test_onlyoffice_check_deadline.py diff --git a/roles/web-app-nextcloud/tasks/addons/onlyoffice.yml b/roles/web-app-nextcloud/tasks/addons/onlyoffice.yml index 54763fb5c3..3b10115fd5 100644 --- a/roles/web-app-nextcloud/tasks/addons/onlyoffice.yml +++ b/roles/web-app-nextcloud/tasks/addons/onlyoffice.yml @@ -1,9 +1,15 @@ --- +- name: "⏱️ Set the deadline for the document server check" + set_fact: + nextcloud_onlyoffice_check_deadline: "{{ now(utc=true).timestamp() + (lookup('timeout', 300) | int) }}" + - name: "🔎 Check the document server round trip and reset onlyoffice's settings_error" shell: > {{ NEXTCLOUD_DOCKER_EXEC_OCC }} onlyoffice:documentserver --check register: nextcloud_onlyoffice_check - until: nextcloud_onlyoffice_check.rc == 0 + until: >- + nextcloud_onlyoffice_check.rc == 0 + or now(utc=true).timestamp() > nextcloud_onlyoffice_check_deadline | float retries: 30 delay: 10 changed_when: false diff --git a/tests/unit/python/roles/web-app-nextcloud/test_onlyoffice_check_deadline.py b/tests/unit/python/roles/web-app-nextcloud/test_onlyoffice_check_deadline.py new file mode 100644 index 0000000000..5ca872e41f --- /dev/null +++ b/tests/unit/python/roles/web-app-nextcloud/test_onlyoffice_check_deadline.py @@ -0,0 +1,28 @@ +from __future__ import annotations + +import unittest + +from utils.cache.files import PROJECT_ROOT, read_text +from utils.cache.yaml import load_yaml_str + +TASKS = PROJECT_ROOT / "roles/web-app-nextcloud/tasks/addons/onlyoffice.yml" + + +class TestOnlyofficeCheckDeadline(unittest.TestCase): + def setUp(self) -> None: + self.tasks = load_yaml_str(read_text(str(TASKS))) + + def test_the_deadline_is_set_before_the_check(self) -> None: + deadline, check = self.tasks + self.assertIn("nextcloud_onlyoffice_check_deadline", deadline["set_fact"]) + self.assertIn("lookup('timeout'", deadline["set_fact"]["nextcloud_onlyoffice_check_deadline"]) + self.assertEqual(check["register"], "nextcloud_onlyoffice_check") + + def test_the_retries_stop_at_the_deadline(self) -> None: + until = self.tasks[1]["until"] + self.assertIn("nextcloud_onlyoffice_check.rc == 0", until) + self.assertIn("now(utc=true).timestamp() > nextcloud_onlyoffice_check_deadline", until) + + +if __name__ == "__main__": + unittest.main() From 3c53fde46a9b2181a424b1ef7e74cf4840c68e12 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 15 Oct 2026 15:23:03 +0200 Subject: [PATCH 05/13] docs(web-app-bluesky): keep the PDS admin password out of curl's argv The createAccount example expanded the password into `--user`, where any local user can read it from the process list while the request runs. The password now goes from `printenv` in the pds container through `sed` into `curl --config -` on stdin, so it is never a shell variable or a command-line argument. Addresses the CodeRabbit review on #961. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-bluesky/Administration.md | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/roles/web-app-bluesky/Administration.md b/roles/web-app-bluesky/Administration.md index e3bffc970d..42b196cc73 100644 --- a/roles/web-app-bluesky/Administration.md +++ b/roles/web-app-bluesky/Administration.md @@ -3,17 +3,16 @@ ## Create a user via POST ```bash -PDS_ADMIN_PASSWORD="$(compose exec -T pds printenv PDS_ADMIN_PASSWORD)" -curl -X POST https://your-pds-domain/xrpc/com.atproto.server.createAccount \ - --user "admin:${PDS_ADMIN_PASSWORD}" \ - -H "Content-Type: application/json" \ - -d '{ - "email": "user@example.com", - "handle": "username", - "password": "securepassword123", - "inviteCode": "optional-invite-code" - }' -unset PDS_ADMIN_PASSWORD +compose exec -T pds printenv PDS_ADMIN_PASSWORD \ + | sed 's/.*/user = "admin:&"/' \ + | curl --config - -X POST https://your-pds-domain/xrpc/com.atproto.server.createAccount \ + -H "Content-Type: application/json" \ + -d '{ + "email": "user@example.com", + "handle": "username", + "password": "securepassword123", + "inviteCode": "optional-invite-code" + }' ``` ## Use pdsadmin From 279aae5713c2287c601c97d0960f78ff67f1078f Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Thu, 15 Oct 2026 19:54:46 +0000 Subject: [PATCH 06/13] update(versions): update pins with a declared source (web-app-xwiki) --- roles/web-app-xwiki/meta/addons/oidc-authenticator.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-xwiki/meta/addons/oidc-authenticator.yml b/roles/web-app-xwiki/meta/addons/oidc-authenticator.yml index 16f95f37ce..c0513c6e50 100644 --- a/roles/web-app-xwiki/meta/addons/oidc-authenticator.yml +++ b/roles/web-app-xwiki/meta/addons/oidc-authenticator.yml @@ -5,7 +5,7 @@ mechanism: extension source: upstream bridges: - sso -version: "2.28.1" +version: "2.29.0" update: type: http_regex url: https://maven.xwiki.org/releases/org/xwiki/contrib/oidc/oidc-authenticator/maven-metadata.xml From 284961aa2b2c2a5f3f38ba28e7787f2e4a0eb17e Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Thu, 15 Oct 2026 20:00:54 +0000 Subject: [PATCH 07/13] update(images): update Docker image versions (svc-ai-ollama) --- roles/svc-ai-ollama/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/svc-ai-ollama/meta/services.yml b/roles/svc-ai-ollama/meta/services.yml index 84f50e6450..d8c4807895 100644 --- a/roles/svc-ai-ollama/meta/services.yml +++ b/roles/svc-ai-ollama/meta/services.yml @@ -13,7 +13,7 @@ ollama: backup: no_stop_required: true image: ollama/ollama - version: 0.40.4 + version: 0.40.5 name: ollama min_storage: 3473MB cpus: "4.0" From 5b1c04ccb670ae3528e6b7dd332ee62c7e9f32a9 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Thu, 15 Oct 2026 20:01:00 +0000 Subject: [PATCH 08/13] update(images): update Docker image versions (web-app-erpnext) --- roles/web-app-erpnext/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-erpnext/meta/services.yml b/roles/web-app-erpnext/meta/services.yml index aeadaa0b54..dd03db4544 100644 --- a/roles/web-app-erpnext/meta/services.yml +++ b/roles/web-app-erpnext/meta/services.yml @@ -65,7 +65,7 @@ erpnext: enabled: true shared: true image: frappe/erpnext - version: "v16.51.0" + version: "v16.51.1" name: erpnext min_storage: 1017MB ports: From a59eb5d34701cbd2b87800ef8d17db5d784d680b Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 15 Oct 2026 22:56:20 +0200 Subject: [PATCH 09/13] docs(web-app-bluesky): escape the PDS admin password for curl's config curl reads backslash escapes inside a quoted config value, so a password with `"` or `\` reached the PDS altered (`a"b` as `admin:a`, `a\b` as `admin:ab`). The sed step now escapes both characters before it builds the `user` line. Addresses the CodeRabbit review on #961. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-bluesky/Administration.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-bluesky/Administration.md b/roles/web-app-bluesky/Administration.md index 42b196cc73..82fdc48a2f 100644 --- a/roles/web-app-bluesky/Administration.md +++ b/roles/web-app-bluesky/Administration.md @@ -4,7 +4,7 @@ ```bash compose exec -T pds printenv PDS_ADMIN_PASSWORD \ - | sed 's/.*/user = "admin:&"/' \ + | sed 's/[\\"]/\\&/g; s/.*/user = "admin:&"/' \ | curl --config - -X POST https://your-pds-domain/xrpc/com.atproto.server.createAccount \ -H "Content-Type: application/json" \ -d '{ From 2756fd56f1d9fb350e95a739757b041fa6689ccb Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 15 Oct 2026 23:45:53 +0200 Subject: [PATCH 10/13] fix(cache): install CA anchors where every update-ca-trust family reads them The Fedora and CentOS Stream workspace jobs failed TLS to pypi.org, registry.npmjs.org and repo.packagist.org (CERTIFICATE_VERIFY_FAILED, curl error 7). package-frontend/ca.sh put the frontend CA into the Arch anchor dir /etc/ca-certificates/trust-source/anchors, which p11-kit on the RedHat family never reads. Probing for the anchor dir does not fix it: with-ca-trust.sh creates both /etc/pki/ca-trust/source/anchors and /etc/ca-certificates/trust-source/anchors on every update-ca-trust host, so the probe in registry-ca.sh already picks the RedHat dir on a reused Arch runner. Both scripts now install into both dirs, rebuild only when one of them changed, and take CA_ROOT so unit tests run them against a fake root. Co-Authored-By: Claude Opus 5.5 (1M context) --- scripts/docker/cache/package-frontend/ca.sh | 28 +++-- scripts/docker/cache/registry-ca.sh | 38 +++--- tests/unit/python/scripts/docker/__init__.py | 0 .../python/scripts/docker/cache/__init__.py | 0 .../docker/cache/package-frontend/__init__.py | 0 .../docker/cache/package-frontend/test_ca.py | 115 +++++++++++++++++ .../scripts/docker/cache/test_registry_ca.py | 119 ++++++++++++++++++ 7 files changed, 277 insertions(+), 23 deletions(-) create mode 100644 tests/unit/python/scripts/docker/__init__.py create mode 100644 tests/unit/python/scripts/docker/cache/__init__.py create mode 100644 tests/unit/python/scripts/docker/cache/package-frontend/__init__.py create mode 100644 tests/unit/python/scripts/docker/cache/package-frontend/test_ca.py create mode 100644 tests/unit/python/scripts/docker/cache/test_registry_ca.py diff --git a/scripts/docker/cache/package-frontend/ca.sh b/scripts/docker/cache/package-frontend/ca.sh index e8bf5a3d44..f03bfe7519 100755 --- a/scripts/docker/cache/package-frontend/ca.sh +++ b/scripts/docker/cache/package-frontend/ca.sh @@ -1,15 +1,22 @@ #!/usr/bin/env bash # Install the frontend CA into the runner's trust store. Idempotent. # See docs/contributing/environment/cache.md. +# Param: CA_ROOT prefix for every absolute path below; empty in production. set -eu -CA_SRC="/opt/package-frontend-ca.crt" +CA_ROOT="${CA_ROOT:-}" +CA_SRC="${CA_ROOT}/opt/package-frontend-ca.crt" +CA_NAME="infinito-package-frontend.crt" if command -v update-ca-certificates >/dev/null 2>&1; then - CA_DST="/usr/local/share/ca-certificates/infinito-package-frontend.crt" + CA_DSTS=("${CA_ROOT}/usr/local/share/ca-certificates/${CA_NAME}") CA_REBUILD=(update-ca-certificates) elif command -v update-ca-trust >/dev/null 2>&1; then - CA_DST="/etc/ca-certificates/trust-source/anchors/infinito-package-frontend.crt" + # Exception: Arch and the RedHat family both run update-ca-trust but read different anchor dirs, and with-ca-trust.sh creates both dirs on both families, so the anchor goes into each instead of a probed one. + CA_DSTS=( + "${CA_ROOT}/etc/pki/ca-trust/source/anchors/${CA_NAME}" + "${CA_ROOT}/etc/ca-certificates/trust-source/anchors/${CA_NAME}" + ) CA_REBUILD=(update-ca-trust extract) else echo "[package-frontend-ca] no supported CA trust tool" >&2 @@ -21,11 +28,18 @@ if [ ! -s "${CA_SRC}" ]; then exit 0 fi -if cmp -s "${CA_SRC}" "${CA_DST}" 2>/dev/null; then +changed=0 +for dst in "${CA_DSTS[@]}"; do + if ! cmp -s "${CA_SRC}" "${dst}" 2>/dev/null; then + install -d -m 0755 "$(dirname "${dst}")" + install -m 0644 "${CA_SRC}" "${dst}" + changed=1 + fi +done + +if [ "${changed}" -eq 0 ]; then exit 0 fi -install -d -m 0755 "$(dirname "${CA_DST}")" -install -m 0644 "${CA_SRC}" "${CA_DST}" "${CA_REBUILD[@]}" >/dev/null 2>&1 -echo "[package-frontend-ca] installed ${CA_DST}" >&2 +echo "[package-frontend-ca] installed ${CA_DSTS[*]}" >&2 diff --git a/scripts/docker/cache/registry-ca.sh b/scripts/docker/cache/registry-ca.sh index 8d06beeacf..672002c51f 100755 --- a/scripts/docker/cache/registry-ca.sh +++ b/scripts/docker/cache/registry-ca.sh @@ -19,25 +19,24 @@ # * Debian/Ubuntu: /usr/local/share/ca-certificates (name must end in .crt), # rebuilt by `update-ca-certificates`. # * Arch and Fedora/CentOS both rebuild with `update-ca-trust extract` but -# read different anchor dirs -- Arch has no /etc/pki, the RedHat family -# has no /etc/ca-certificates -- so the dir is probed, not assumed. +# read different anchor dirs, and with-ca-trust.sh creates both dirs on +# both families, so the anchor goes into each. +# Param: CA_ROOT prefix for every absolute path below; empty in production. set -eu -CA_DIR="/opt/registry-cache-ca" +CA_ROOT="${CA_ROOT:-}" +CA_DIR="${CA_ROOT}/opt/registry-cache-ca" CA_SRC="${CA_DIR}/ca.crt" +CA_NAME="infinito-registry-cache.crt" if command -v update-ca-certificates >/dev/null 2>&1; then - CA_DST="/usr/local/share/ca-certificates/infinito-registry-cache.crt" + CA_DSTS=("${CA_ROOT}/usr/local/share/ca-certificates/${CA_NAME}") CA_REBUILD=(update-ca-certificates) elif command -v update-ca-trust >/dev/null 2>&1; then - if [ -d /etc/pki/ca-trust/source/anchors ]; then - CA_DST="/etc/pki/ca-trust/source/anchors/infinito-registry-cache.crt" - elif [ -d /etc/ca-certificates/trust-source/anchors ]; then - CA_DST="/etc/ca-certificates/trust-source/anchors/infinito-registry-cache.crt" - else - echo "[registry-cache-ca] update-ca-trust present but no known anchor dir (/etc/pki/ca-trust/source/anchors, /etc/ca-certificates/trust-source/anchors)" >&2 - exit 1 - fi + CA_DSTS=( + "${CA_ROOT}/etc/pki/ca-trust/source/anchors/${CA_NAME}" + "${CA_ROOT}/etc/ca-certificates/trust-source/anchors/${CA_NAME}" + ) CA_REBUILD=(update-ca-trust extract) else echo "[registry-cache-ca] no supported CA trust tool (update-ca-certificates or update-ca-trust)" >&2 @@ -56,11 +55,18 @@ if [ ! -s "${CA_SRC}" ]; then exit 1 fi -if cmp -s "${CA_SRC}" "${CA_DST}" 2>/dev/null; then +changed=0 +for dst in "${CA_DSTS[@]}"; do + if ! cmp -s "${CA_SRC}" "${dst}" 2>/dev/null; then + install -d -m 0755 "$(dirname "${dst}")" + install -m 0644 "${CA_SRC}" "${dst}" + changed=1 + fi +done + +if [ "${changed}" -eq 0 ]; then exit 0 fi -install -d -m 0755 "$(dirname "${CA_DST}")" -install -m 0644 "${CA_SRC}" "${CA_DST}" "${CA_REBUILD[@]}" >/dev/null -echo "[registry-cache-ca] installed ${CA_DST}" >&2 +echo "[registry-cache-ca] installed ${CA_DSTS[*]}" >&2 diff --git a/tests/unit/python/scripts/docker/__init__.py b/tests/unit/python/scripts/docker/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/scripts/docker/cache/__init__.py b/tests/unit/python/scripts/docker/cache/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/scripts/docker/cache/package-frontend/__init__.py b/tests/unit/python/scripts/docker/cache/package-frontend/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/scripts/docker/cache/package-frontend/test_ca.py b/tests/unit/python/scripts/docker/cache/package-frontend/test_ca.py new file mode 100644 index 0000000000..3083d70407 --- /dev/null +++ b/tests/unit/python/scripts/docker/cache/package-frontend/test_ca.py @@ -0,0 +1,115 @@ +from __future__ import annotations + +import os +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +from utils.cache.files import PROJECT_ROOT + +SCRIPT = PROJECT_ROOT / "scripts" / "docker" / "cache" / "package-frontend" / "ca.sh" +NAME = "infinito-package-frontend.crt" +STUB = '#!/usr/bin/env bash\nprintf "%s\\n" "$0 $*" >>"${STUB_LOG}"\n' +PKI = "etc/pki/ca-trust/source/anchors" +ARCH = "etc/ca-certificates/trust-source/anchors" +TOOLS = ("bash", "cmp", "dirname", "install") + + +class TestPackageFrontendCa(unittest.TestCase): + def fake_root(self, tool: str, anchor_dirs: tuple[str, ...]) -> Path: + """Build a fake root that offers one trust tool and a frontend CA. + + Args: + tool: the trust rebuild command the fake system provides. + anchor_dirs: anchor directories that already exist in the fake root. + + Returns: + The fake root. + """ + root = Path(self.enterContext(tempfile.TemporaryDirectory())) + (root / "opt").mkdir() + (root / "opt" / "package-frontend-ca.crt").write_text("CA\n", encoding="utf-8") + for anchor in anchor_dirs: + (root / anchor).mkdir(parents=True) + (root / "bin").mkdir() + for needed in TOOLS: + (root / "bin" / needed).symlink_to(shutil.which(needed)) + (root / "bin" / tool).write_text(STUB, encoding="utf-8") + (root / "bin" / tool).chmod(0o755) + return root + + def run_script(self, root: Path) -> subprocess.CompletedProcess: + """Run ca.sh against a fake root. + + Args: + root: fake root from ``fake_root``. + + Returns: + The finished process. + """ + env = {k: v for k, v in os.environ.items() if k not in ("BASH_ENV", "CA_ROOT")} + env.update( + CA_ROOT=str(root), + PATH=str(root / "bin"), + STUB_LOG=str(root / "stub.log"), + ) + return subprocess.run( + [str(root / "bin" / "bash"), str(SCRIPT)], + env=env, + capture_output=True, + text=True, + check=False, + ) + + def rebuilds(self, root: Path) -> int: + log = root / "stub.log" + if not log.exists(): + return 0 + text = log.read_text(encoding="utf-8") # nocheck: cache-read per-run tempdir + return len(text.splitlines()) + + def test_the_redhat_family_gets_the_pki_anchor(self) -> None: + root = self.fake_root("update-ca-trust", (PKI,)) + done = self.run_script(root) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertTrue((root / PKI / NAME).is_file()) + self.assertEqual(self.rebuilds(root), 1) + + def test_arch_with_both_anchor_dirs_gets_its_trust_source_anchor(self) -> None: + root = self.fake_root("update-ca-trust", (PKI, ARCH)) + done = self.run_script(root) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertTrue((root / ARCH / NAME).is_file()) + + def test_a_fresh_update_ca_trust_root_gets_both_anchors(self) -> None: + root = self.fake_root("update-ca-trust", ()) + done = self.run_script(root) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertTrue((root / PKI / NAME).is_file()) + self.assertTrue((root / ARCH / NAME).is_file()) + + def test_debian_uses_update_ca_certificates(self) -> None: + root = self.fake_root("update-ca-certificates", ()) + done = self.run_script(root) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertTrue((root / "usr/local/share/ca-certificates" / NAME).is_file()) + self.assertFalse((root / "etc").exists()) + + def test_a_second_run_does_not_rebuild(self) -> None: + root = self.fake_root("update-ca-trust", (PKI,)) + self.run_script(root) + done = self.run_script(root) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertEqual(self.rebuilds(root), 1) + + def test_no_trust_tool_fails_loudly(self) -> None: + root = self.fake_root("unrelated-tool", ()) + done = self.run_script(root) + self.assertNotEqual(done.returncode, 0) + self.assertFalse(any(root.glob(f"**/{NAME}"))) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/scripts/docker/cache/test_registry_ca.py b/tests/unit/python/scripts/docker/cache/test_registry_ca.py new file mode 100644 index 0000000000..7a3a77f391 --- /dev/null +++ b/tests/unit/python/scripts/docker/cache/test_registry_ca.py @@ -0,0 +1,119 @@ +from __future__ import annotations + +import os +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +from utils.cache.files import PROJECT_ROOT + +SCRIPT = PROJECT_ROOT / "scripts" / "docker" / "cache" / "registry-ca.sh" +NAME = "infinito-registry-cache.crt" +STUB = '#!/usr/bin/env bash\nprintf "%s\\n" "$0 $*" >>"${STUB_LOG}"\n' +PKI = "etc/pki/ca-trust/source/anchors" +ARCH = "etc/ca-certificates/trust-source/anchors" +TOOLS = ("bash", "cmp", "dirname", "install") + + +class TestRegistryCacheCa(unittest.TestCase): + def fake_root( + self, tool: str, anchor_dirs: tuple[str, ...], ca: str | None + ) -> Path: + """Build a fake root that offers one trust tool. + + Args: + tool: the trust rebuild command the fake system provides. + anchor_dirs: anchor directories that already exist in the fake root. + ca: content of the mounted ``ca.crt``; ``None`` leaves the CA dir unmounted. + + Returns: + The fake root. + """ + root = Path(self.enterContext(tempfile.TemporaryDirectory())) + if ca is not None: + (root / "opt" / "registry-cache-ca").mkdir(parents=True) + (root / "opt" / "registry-cache-ca" / "ca.crt").write_text( + ca, encoding="utf-8" + ) + for anchor in anchor_dirs: + (root / anchor).mkdir(parents=True) + (root / "bin").mkdir() + for needed in TOOLS: + (root / "bin" / needed).symlink_to(shutil.which(needed)) + (root / "bin" / tool).write_text(STUB, encoding="utf-8") + (root / "bin" / tool).chmod(0o755) + return root + + def run_script(self, root: Path) -> subprocess.CompletedProcess: + """Run registry-ca.sh against a fake root. + + Args: + root: fake root from ``fake_root``. + + Returns: + The finished process. + """ + env = {k: v for k, v in os.environ.items() if k not in ("BASH_ENV", "CA_ROOT")} + env.update( + CA_ROOT=str(root), + PATH=str(root / "bin"), + STUB_LOG=str(root / "stub.log"), + ) + return subprocess.run( + [str(root / "bin" / "bash"), str(SCRIPT)], + env=env, + capture_output=True, + text=True, + check=False, + ) + + def rebuilds(self, root: Path) -> int: + log = root / "stub.log" + if not log.exists(): + return 0 + text = log.read_text(encoding="utf-8") # nocheck: cache-read per-run tempdir + return len(text.splitlines()) + + def test_the_redhat_family_gets_the_pki_anchor(self) -> None: + root = self.fake_root("update-ca-trust", (PKI,), "CA\n") + done = self.run_script(root) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertTrue((root / PKI / NAME).is_file()) + self.assertEqual(self.rebuilds(root), 1) + + def test_arch_with_both_anchor_dirs_gets_its_trust_source_anchor(self) -> None: + root = self.fake_root("update-ca-trust", (PKI, ARCH), "CA\n") + done = self.run_script(root) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertTrue((root / ARCH / NAME).is_file()) + + def test_debian_uses_update_ca_certificates(self) -> None: + root = self.fake_root("update-ca-certificates", (), "CA\n") + done = self.run_script(root) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertTrue((root / "usr/local/share/ca-certificates" / NAME).is_file()) + + def test_a_second_run_does_not_rebuild(self) -> None: + root = self.fake_root("update-ca-trust", (ARCH,), "CA\n") + self.run_script(root) + done = self.run_script(root) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertEqual(self.rebuilds(root), 1) + + def test_an_unmounted_ca_dir_is_skipped(self) -> None: + root = self.fake_root("update-ca-trust", (PKI,), None) + done = self.run_script(root) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertEqual(self.rebuilds(root), 0) + + def test_a_mounted_dir_without_ca_is_refused(self) -> None: + root = self.fake_root("update-ca-trust", (PKI,), "") + done = self.run_script(root) + self.assertNotEqual(done.returncode, 0) + self.assertFalse(any(root.glob(f"**/{NAME}"))) + + +if __name__ == "__main__": + unittest.main() From e6f552ca0adb5cc04acfb83bb17ee2e4e59cf2b5 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 15 Oct 2026 23:45:54 +0200 Subject: [PATCH 11/13] fix(install): provision minitest next to ruby on Arch and the RedHat family The Manjaro workspace job failed test-unit-ruby with "cannot load such file -- minitest". Debian vendors minitest in libruby, but Arch ships it as ruby-minitest and Fedora and CentOS Stream as rubygem-minitest, none of which ruby pulls in. ensure_ruby_present now probes `require "minitest"` and installs the distro package when the probe fails, then fails loudly if minitest is still missing. Co-Authored-By: Claude Opus 5.5 (1M context) --- Makefile | 2 +- scripts/tests/unit/ruby.sh | 2 +- tests/unit/python/utils/install/test_ruby.py | 62 +++++++++++++++++++- utils/install/ruby.py | 57 +++++++++++++++++- 4 files changed, 115 insertions(+), 8 deletions(-) diff --git a/Makefile b/Makefile index da8401d38d..0d1abe19e0 100644 --- a/Makefile +++ b/Makefile @@ -893,7 +893,7 @@ test-unit-python: install bash scripts/tests/code/wrapper.sh scripts/tests/code/run.sh .PHONY: test-unit-ruby -# Run the Ruby unit test suite (minitest, stdlib). +# Run the Ruby unit test suite (minitest). test-unit-ruby: @INFINITO_TEST_TYPE="unit-ruby" \ bash scripts/tests/code/wrapper.sh scripts/tests/unit/ruby.sh diff --git a/scripts/tests/unit/ruby.sh b/scripts/tests/unit/ruby.sh index 6de951b307..e0b6466678 100755 --- a/scripts/tests/unit/ruby.sh +++ b/scripts/tests/unit/ruby.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # shellcheck shell=bash # -# Runs the Ruby unit suite through minitest, which ships with Ruby itself. +# Runs the Ruby unit suite through minitest, which scripts/install/ruby.sh provisions. set -euo pipefail diff --git a/tests/unit/python/utils/install/test_ruby.py b/tests/unit/python/utils/install/test_ruby.py index e0c57e07f5..ee69858086 100644 --- a/tests/unit/python/utils/install/test_ruby.py +++ b/tests/unit/python/utils/install/test_ruby.py @@ -9,19 +9,75 @@ from utils.install import ruby as ruby_mod class TestEnsureRubyPresent(unittest.TestCase): - def test_delegates_to_the_shared_provisioner(self) -> None: - with mock.patch.object(ruby_mod, "ensure_command_present") as ensure: + def test_provisions_ruby_then_minitest(self) -> None: + calls = mock.Mock() + with ( + mock.patch.object(ruby_mod, "ensure_command_present", calls.ruby), + mock.patch.object(ruby_mod, "ensure_minitest_present", calls.minitest), + ): ruby_mod.ensure_ruby_present() - ensure.assert_called_once_with("ruby") + self.assertEqual( + calls.mock_calls, [mock.call.ruby("ruby"), mock.call.minitest()] + ) def test_propagates_the_hard_failure(self) -> None: with ( mock.patch.object( ruby_mod, "ensure_command_present", side_effect=RuntimeError("boom") ), + mock.patch.object(ruby_mod, "ensure_minitest_present") as minitest, self.assertRaises(RuntimeError), ): ruby_mod.ensure_ruby_present() + minitest.assert_not_called() + + +class TestEnsureMinitestPresent(unittest.TestCase): + def run_with(self, *, loadable: list[bool], manager: str) -> mock.Mock: + """Run ``ensure_minitest_present`` with stubbed probe and installer. + + Args: + loadable: successive results of the minitest probe. + manager: package manager the host reports. + + Returns: + The stubbed ``install_package_candidates``. + """ + with ( + mock.patch.object(ruby_mod, "minitest_loadable", side_effect=loadable), + mock.patch.object(ruby_mod, "detect_package_manager", return_value=manager), + mock.patch.object(ruby_mod, "install_package_candidates") as install, + mock.patch.object(ruby_mod, "log"), + ): + ruby_mod.ensure_minitest_present() + return install + + def test_a_loadable_minitest_installs_nothing(self) -> None: + install = self.run_with(loadable=[True], manager="pacman") + install.assert_not_called() + + def test_arch_installs_ruby_minitest(self) -> None: + install = self.run_with(loadable=[False, True], manager="pacman") + install.assert_called_once_with("pacman", ["ruby-minitest"]) + + def test_the_redhat_family_installs_rubygem_minitest(self) -> None: + install = self.run_with(loadable=[False, True], manager="dnf") + install.assert_called_once_with("dnf", ["rubygem-minitest"]) + + def test_still_missing_after_the_install_fails_loudly(self) -> None: + with self.assertRaises(RuntimeError): + self.run_with(loadable=[False, False], manager="pacman") + + def test_an_unmapped_manager_fails_without_installing(self) -> None: + with ( + mock.patch.object(ruby_mod, "minitest_loadable", return_value=False), + mock.patch.object(ruby_mod, "detect_package_manager", return_value="brew"), + mock.patch.object(ruby_mod, "install_package_candidates") as install, + mock.patch.object(ruby_mod, "log"), + self.assertRaises(RuntimeError), + ): + ruby_mod.ensure_minitest_present() + install.assert_not_called() if __name__ == "__main__": diff --git a/utils/install/ruby.py b/utils/install/ruby.py index 99db87f5b2..16c28d451d 100644 --- a/utils/install/ruby.py +++ b/utils/install/ruby.py @@ -2,16 +2,67 @@ from __future__ import annotations -from utils.install.system_pkg import ensure_command_present +import subprocess + +from utils.install.primitives import log +from utils.install.system_pkg import ( + detect_package_manager, + ensure_command_present, + install_package_candidates, +) + +_MINITEST_PACKAGES: dict[str, list[str]] = { + "pacman": ["ruby-minitest"], + "dnf": ["rubygem-minitest"], + "yum": ["rubygem-minitest"], + "apt-get": ["ruby-minitest"], +} + + +def minitest_loadable() -> bool: + """Return whether the installed ruby can require minitest. + + Returns: + ``True`` when ``ruby -e 'require "minitest"'`` exits 0. + """ + probe = subprocess.run( + ["ruby", "-e", 'require "minitest"'], capture_output=True, check=False + ) + return probe.returncode == 0 + + +def ensure_minitest_present() -> None: + """Make minitest loadable, installing its package if ruby lacks it. + + Raises: + RuntimeError: no package mapping for the detected package manager, or + minitest is still not loadable after the install. + """ + if minitest_loadable(): + return + + manager = detect_package_manager() + packages = _MINITEST_PACKAGES.get(manager) + if packages is None: + raise RuntimeError(f"No installer mapping defined for minitest on '{manager}'.") + + log(f"Ruby cannot load minitest. Attempting installation via {manager}.") + install_package_candidates(manager, packages) + + if not minitest_loadable(): + raise RuntimeError( + f"minitest still not loadable after installing {packages} via {manager}" + ) def ensure_ruby_present() -> None: - """Install the Ruby interpreter through the system package manager. + """Install the Ruby interpreter and minitest through the system package manager. Raises: - RuntimeError: ruby is still absent after the install attempt. + RuntimeError: ruby or minitest is still absent after the install attempt. """ ensure_command_present("ruby") + ensure_minitest_present() if __name__ == "__main__": From fad0c60e5287bc5d5ae75d33e08beb3a1fa1a85d Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 15 Oct 2026 23:45:54 +0200 Subject: [PATCH 12/13] fix(lint): provision mmdc's browser libraries off apt and fail hard On the Fedora, CentOS Stream and Manjaro workspace jobs install-lint ran `puppeteer browsers install chrome-headless-shell --install-deps` as root, and puppeteer rejected it with "apt-get does not seem to be available". The installer only warned ("optional lint tool"), so install-lint passed while mmdc had no browser. --install-deps is now passed only where apt-get exists. Everywhere else the libraries `ldd` reports missing are installed by soname: dnf and yum through the RPM provide `()(64bit)`, pacman through the first package `pacman -F usr/lib/` names (libgbm.so.1 is owned by both mesa and mesa-amber, which conflict). browser_installed() also requires every library to resolve, so the install-lint stamp stays stale until the browser can actually load. A failed npm install, a missing mmdc, a failed or timed-out browser download and unresolved libraries now raise instead of warning. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../utils/install/lint/test_mermaid_cli.py | 239 ++++++++++++++---- utils/install/lint/mermaid_cli.py | 167 +++++++++--- 2 files changed, 320 insertions(+), 86 deletions(-) diff --git a/tests/unit/python/utils/install/lint/test_mermaid_cli.py b/tests/unit/python/utils/install/lint/test_mermaid_cli.py index 5b66791177..7a2f226d28 100644 --- a/tests/unit/python/utils/install/lint/test_mermaid_cli.py +++ b/tests/unit/python/utils/install/lint/test_mermaid_cli.py @@ -17,10 +17,17 @@ if TYPE_CHECKING: from collections.abc import Iterator REVISION = "155.0.8059.39" +LDD = ( + "\tlinux-vdso.so.1 (0x00007f5999895000)\n" + "\tlibnss3.so => not found\n" + "\tlibglib-2.0.so.0 => /usr/lib/libglib-2.0.so.0 (0x00007f598d09d000)\n" + "\tlibgbm.so.1 => not found\n" + "\tlibnss3.so => not found\n" +) -def _done(returncode: int) -> subprocess.CompletedProcess[str]: - return subprocess.CompletedProcess([], returncode, stdout="out\n", stderr="err\n") +def _done(returncode: int, stdout: str = "out\n") -> subprocess.CompletedProcess[str]: + return subprocess.CompletedProcess([], returncode, stdout=stdout, stderr="err\n") def _write_core(node_modules: Path, revision: str) -> None: @@ -64,10 +71,12 @@ def _fake_mmdc( return mmdc -def _install_browser(cache: Path, revision: str) -> None: +def _install_browser(cache: Path, revision: str) -> Path: build = cache / "chrome-headless-shell" / f"linux-{revision}" / "linux64" - build.mkdir(parents=True) - (build / "chrome-headless-shell").write_text("", encoding="utf-8") + build.mkdir(parents=True, exist_ok=True) + executable = build / "chrome-headless-shell" + executable.write_text("", encoding="utf-8") + return executable @contextlib.contextmanager @@ -89,45 +98,64 @@ def _environment( mock.patch.dict(os.environ, {"PUPPETEER_CACHE_DIR": cache}), mock.patch.object(mermaid_cli, "which", return_value=True), mock.patch.object(mermaid_cli.shutil, "which", return_value=str(mmdc)), + mock.patch.object(mermaid_cli, "missing_libraries", return_value=[]), ): yield Path(prefix), Path(cache) class TestBrowserProvisioning(unittest.TestCase): - def provision(self, *, euid: int, results: list[int]) -> tuple[list, list[str]]: + def provision( + self, *, euid: int, results: list[int], apt: bool = True + ) -> list[mock._Call]: """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. + results: exit codes the successive puppeteer calls return; a 0 + lays the pinned browser into the cache. + apt: whether apt-get is on the PATH. Returns: - The recorded subprocess calls and the warnings emitted. + The recorded subprocess calls. """ - warnings: list[str] = [] - with ( - _environment(), - 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 + calls: list[mock._Call] = [] + codes = iter(results) + with _environment() as (_, cache): - def test_root_installs_the_browser_with_its_libraries(self) -> None: - calls, warnings = self.provision(euid=0, results=[0]) + def run(*args, **kwargs): + calls.append(mock.call(*args, **kwargs)) + code = next(codes) + if code == 0: + _install_browser(cache, REVISION) + return _done(code) + + with ( + mock.patch.object(mermaid_cli.os, "geteuid", return_value=euid), + mock.patch.object( + mermaid_cli, + "which", + side_effect=lambda cmd: apt or cmd != "apt-get", + ), + mock.patch.object(mermaid_cli.subprocess, "run", side_effect=run), + ): + mermaid_cli.ensure() + return calls + + def test_root_on_apt_installs_the_browser_with_its_libraries(self) -> None: + calls = 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_root_without_apt_leaves_the_libraries_to_the_soname_install( + self, + ) -> None: + calls = self.provision(euid=0, results=[0], apt=False) + self.assertNotIn("--install-deps", calls[0].args[0]) def test_the_browser_comes_from_the_puppeteer_next_to_mmdc(self) -> None: - calls, _ = self.provision(euid=0, results=[0]) + calls = self.provision(euid=0, results=[0]) self.assertTrue( calls[0] .args[0][0] @@ -135,12 +163,12 @@ class TestBrowserProvisioning(unittest.TestCase): ) def test_a_user_installs_the_browser_without_libraries(self) -> None: - calls, _ = self.provision(euid=1000, results=[0]) + 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]) + calls = self.provision(euid=0, results=[0]) self.assertNotIn("PUPPETEER_SKIP_DOWNLOAD", calls[0].kwargs["env"]) def test_a_failed_install_clears_its_revision_and_retries_once(self) -> None: @@ -153,17 +181,18 @@ class TestBrowserProvisioning(unittest.TestCase): def run(*_args, **_kwargs): seen.append((partial.exists(), other.exists())) - return _done(1 if len(seen) == 1 else 0) + if len(seen) == 1: + return _done(1) + _install_browser(cache, REVISION) + return _done(0) with mock.patch.object(mermaid_cli.subprocess, "run", side_effect=run): mermaid_cli.ensure() self.assertEqual(seen, [(True, True), (False, True)]) - 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_a_second_failure_raises_with_puppeteers_output(self) -> None: + with self.assertRaisesRegex(RuntimeError, "out\nerr\n"): + self.provision(euid=0, results=[1, 1]) def test_the_pinned_browser_is_not_provisioned_again(self) -> None: with _environment() as (_, cache): @@ -175,23 +204,35 @@ class TestBrowserProvisioning(unittest.TestCase): def test_a_browser_of_another_revision_is_replaced(self) -> None: with _environment() as (_, cache): _install_browser(cache, "155.0.8059.79") - with mock.patch.object( - mermaid_cli.subprocess, "run", return_value=_done(0) - ) as run: - mermaid_cli.ensure() - run.assert_called_once() - def test_mmdc_without_its_own_puppeteer_warns(self) -> None: + def run(*_args, **_kwargs): + _install_browser(cache, REVISION) + return _done(0) + + with mock.patch.object( + mermaid_cli.subprocess, "run", side_effect=run + ) as stub: + mermaid_cli.ensure() + stub.assert_called_once() + + def test_a_reported_success_without_the_browser_raises(self) -> None: + with ( + _environment(), + mock.patch.object(mermaid_cli.subprocess, "run", return_value=_done(0)), + self.assertRaisesRegex(RuntimeError, "still missing"), + ): + mermaid_cli.ensure() + + def test_mmdc_without_its_own_puppeteer_raises(self) -> None: with ( _environment(revision=None), - mock.patch.object(mermaid_cli, "warn") as warn, mock.patch.object(mermaid_cli.subprocess, "run") as run, + self.assertRaisesRegex(RuntimeError, "no puppeteer next to mmdc"), ): mermaid_cli.ensure() run.assert_not_called() - warn.assert_called_once() - def test_a_timeout_warns_instead_of_raising(self) -> None: + def test_a_timeout_propagates(self) -> None: with ( _environment(), mock.patch.object( @@ -199,10 +240,112 @@ class TestBrowserProvisioning(unittest.TestCase): "run", side_effect=subprocess.TimeoutExpired("puppeteer", 900), ), - mock.patch.object(mermaid_cli, "warn") as warn, + self.assertRaises(subprocess.TimeoutExpired), ): mermaid_cli.ensure() - warn.assert_called_once() + + +class TestMmdcInstall(unittest.TestCase): + def test_a_failed_npm_install_propagates(self) -> None: + with ( + mock.patch.object(mermaid_cli, "which", return_value=False), + mock.patch.object(mermaid_cli, "install_command_via_pkg"), + mock.patch.object( + mermaid_cli, "npm_install_global", side_effect=RuntimeError("npm") + ), + mock.patch.object(mermaid_cli, "_ensure_browser") as browser, + self.assertRaisesRegex(RuntimeError, "npm"), + ): + mermaid_cli.ensure() + browser.assert_not_called() + + def test_mmdc_still_missing_after_npm_raises(self) -> None: + with ( + mock.patch.object(mermaid_cli, "which", return_value=False), + mock.patch.object(mermaid_cli, "install_command_via_pkg"), + mock.patch.object(mermaid_cli, "npm_install_global"), + mock.patch.object(mermaid_cli, "_ensure_browser") as browser, + self.assertRaisesRegex(RuntimeError, "mmdc"), + ): + mermaid_cli.ensure() + browser.assert_not_called() + + +class TestBrowserLibraries(unittest.TestCase): + def test_ldd_not_found_lines_become_sorted_sonames(self) -> None: + with mock.patch.object( + mermaid_cli.subprocess, "run", return_value=_done(0, LDD) + ) as run: + missing = mermaid_cli.missing_libraries(Path("/opt/chs")) + self.assertEqual(missing, ["libgbm.so.1", "libnss3.so"]) + self.assertEqual(run.call_args.args[0], ["ldd", "/opt/chs"]) + + def ensure_libraries( + self, *, manager: str, missing: list[list[str]], files: dict[str, str] + ) -> mock.Mock: + """Run the library step with stubbed ldd, package manager and file DB. + + Args: + manager: the package manager the host reports. + missing: successive ``missing_libraries`` results. + files: ``pacman -Fq`` stdout per queried path. + + Returns: + The stubbed ``run_privileged``. + """ + + def query(argv, **_kwargs): + return _done(0, files.get(argv[-1], "")) + + with ( + mock.patch.object(mermaid_cli, "missing_libraries", side_effect=missing), + mock.patch.object( + mermaid_cli, "detect_package_manager", return_value=manager + ), + mock.patch.object(mermaid_cli.subprocess, "run", side_effect=query), + mock.patch.object(mermaid_cli, "run_privileged") as privileged, + ): + mermaid_cli._ensure_browser_libraries(Path("/opt/chs")) + return privileged + + def test_resolved_libraries_install_nothing(self) -> None: + privileged = self.ensure_libraries(manager="dnf", missing=[[]], files={}) + privileged.assert_not_called() + + def test_the_redhat_family_installs_by_soname_provide(self) -> None: + privileged = self.ensure_libraries( + manager="dnf", missing=[["libgbm.so.1", "libnss3.so"], []], files={} + ) + privileged.assert_called_once_with( + ["dnf", "-y", "install", "libgbm.so.1()(64bit)", "libnss3.so()(64bit)"] + ) + + def test_arch_takes_the_first_package_owning_each_soname(self) -> None: + privileged = self.ensure_libraries( + manager="pacman", + missing=[["libgbm.so.1", "libnss3.so"], []], + files={ + "usr/lib/libgbm.so.1": "extra/mesa\nextra/mesa-amber\n", + "usr/lib/libnss3.so": "core/nss\n", + }, + ) + self.assertEqual( + privileged.call_args_list, + [ + mock.call(["pacman", "-Fy"]), + mock.call(["pacman", "-Syu", "--noconfirm", "--needed", "mesa", "nss"]), + ], + ) + + def test_apt_without_libraries_fails_without_installing(self) -> None: + with self.assertRaisesRegex(RuntimeError, "--install-deps"): + self.ensure_libraries(manager="apt-get", missing=[["libnss3.so"]], files={}) + + def test_libraries_still_missing_after_the_install_raise(self) -> None: + with self.assertRaisesRegex(RuntimeError, "still lacks libnss3.so"): + self.ensure_libraries( + manager="dnf", missing=[["libnss3.so"], ["libnss3.so"]], files={} + ) class TestBrowserInstalled(unittest.TestCase): @@ -213,6 +356,14 @@ class TestBrowserInstalled(unittest.TestCase): _install_browser(cache, REVISION) self.assertTrue(mermaid_cli.browser_installed()) + def test_a_browser_with_missing_libraries_is_not_installed(self) -> None: + with _environment() as (_, cache): + _install_browser(cache, REVISION) + with mock.patch.object( + mermaid_cli, "missing_libraries", return_value=["libnss3.so"] + ): + self.assertFalse(mermaid_cli.browser_installed()) + def test_the_revision_is_read_from_mmdcs_puppeteer_core(self) -> None: with _environment(): self.assertEqual(mermaid_cli.browser_revision(), REVISION) diff --git a/utils/install/lint/mermaid_cli.py b/utils/install/lint/mermaid_cli.py index f1782e0d3a..7e08f66216 100644 --- a/utils/install/lint/mermaid_cli.py +++ b/utils/install/lint/mermaid_cli.py @@ -2,34 +2,38 @@ mmdc comes from npm with ``PUPPETEER_SKIP_DOWNLOAD`` set; the browser is provisioned afterwards through the puppeteer that npm installed next to mmdc, -at the revision its puppeteer-core pins, 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. +at the revision its puppeteer-core pins. ``unzip`` is ensured first because +puppeteer extracts the browser with it. Puppeteer installs the browser's +shared libraries only through apt-get (``--install-deps``); on dnf, yum and +pacman the libraries ``ldd`` reports missing are installed by soname. Every +failure aborts ``install-lint``. """ from __future__ import annotations -import contextlib import os import re import shutil import subprocess +import sys 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 +from utils.install.primitives import log, run_privileged, which +from utils.install.system_pkg import detect_package_manager, install_command_via_pkg BROWSER = "chrome-headless-shell" PROVISION_TIMEOUT_S = 900 +_INSTALL_ARGV = { + "dnf": ["dnf", "-y", "install"], + "yum": ["yum", "-y", "install"], + "pacman": ["pacman", "-Syu", "--noconfirm", "--needed"], +} + def _ensure_unzip() -> None: - if which("unzip"): - return - with contextlib.suppress(Exception): + if not which("unzip"): install_command_via_pkg("unzip") @@ -75,15 +79,42 @@ def browser_revision() -> str | None: return match.group(1) if match else None -def browser_installed() -> bool: +def browser_executable() -> Path | None: revision = browser_revision() if revision is None: - return False - return any( - path.is_file() for path in browser_cache().glob(f"*-{revision}/*/{BROWSER}") + return None + return next( + ( + path + for path in browser_cache().glob(f"*-{revision}/*/{BROWSER}") + if path.is_file() + ), + None, ) +def missing_libraries(executable: Path) -> list[str]: + """Return the shared libraries the dynamic loader cannot resolve. + + Args: + executable: the browser binary. + + Returns: + Sorted sonames ``ldd`` reports as ``not found``. + """ + done = subprocess.run( + ["ldd", str(executable)], capture_output=True, text=True, check=False + ) + return sorted( + {line.split()[0] for line in done.stdout.splitlines() if "=> not found" in line} + ) + + +def browser_installed() -> bool: + executable = browser_executable() + return executable is not None and not missing_libraries(executable) + + def _provision_browser(puppeteer: Path) -> subprocess.CompletedProcess[str]: argv = [ str(puppeteer.parent / ".bin" / "puppeteer"), @@ -91,7 +122,7 @@ def _provision_browser(puppeteer: Path) -> subprocess.CompletedProcess[str]: "install", BROWSER, ] - if os.geteuid() == 0: + if os.geteuid() == 0 and which("apt-get"): argv.append("--install-deps") env = {k: v for k, v in os.environ.items() if k != "PUPPETEER_SKIP_DOWNLOAD"} return subprocess.run( @@ -104,43 +135,95 @@ def _provision_browser(puppeteer: Path) -> subprocess.CompletedProcess[str]: ) -def _ensure_browser() -> None: - if browser_installed(): - return +def _download_browser() -> None: puppeteer = _mmdc_puppeteer() if puppeteer is None: - warn(f"{BROWSER} provisioning skipped: no puppeteer next to mmdc") - return + raise RuntimeError(f"Cannot provision {BROWSER}: no puppeteer next to mmdc.") log(f"Provisioning {BROWSER} for mmdc via its own puppeteer.") - try: - done = _provision_browser(puppeteer) - if done.returncode != 0: - revision = browser_revision() - if revision is not None: - for partial in browser_cache().glob(f"*-{revision}"): - shutil.rmtree(partial, ignore_errors=True) - done = _provision_browser(puppeteer) - except (OSError, subprocess.TimeoutExpired) as exc: - warn(f"{BROWSER} provisioning skipped (optional lint tool): {exc}") - return + done = _provision_browser(puppeteer) if done.returncode != 0: - warn( - f"{BROWSER} provisioning failed (optional lint tool):\n" - f"{done.stdout}{done.stderr}" + revision = browser_revision() + if revision is not None: + for partial in browser_cache().glob(f"*-{revision}"): + shutil.rmtree(partial, ignore_errors=True) + done = _provision_browser(puppeteer) + if done.returncode != 0: + raise RuntimeError( + f"{BROWSER} provisioning failed:\n{done.stdout}{done.stderr}" ) +def _library_packages(manager: str, sonames: list[str]) -> list[str]: + """Map sonames to what the package manager installs them by. + + Args: + manager: the detected package manager. + sonames: libraries the browser cannot resolve. + + Returns: + Install arguments for ``manager``. + + Raises: + RuntimeError: the manager cannot install by soname. + """ + if manager in ("dnf", "yum"): + suffix = "()(64bit)" if sys.maxsize > 2**32 else "" + return [f"{soname}{suffix}" for soname in sonames] + if manager == "pacman": + run_privileged(["pacman", "-Fy"]) + packages: set[str] = set() + for soname in sonames: + found = subprocess.run( + ["pacman", "-Fq", f"usr/lib/{soname}"], + capture_output=True, + text=True, + check=False, + ).stdout.split() + if found: + packages.add(found[0].rsplit("/", 1)[-1]) + return sorted(packages) + raise RuntimeError( + f"{BROWSER} lacks {', '.join(sonames)} and {manager} cannot install " + f"libraries by soname; on apt-get they come from --install-deps, which " + f"needs root." + ) + + +def _ensure_browser_libraries(executable: Path) -> None: + missing = missing_libraries(executable) + if not missing: + return + manager = detect_package_manager() + packages = _library_packages(manager, missing) + log(f"Installing {BROWSER} libraries via {manager}: {', '.join(packages)}") + if packages: + run_privileged([*_INSTALL_ARGV[manager], *packages]) + missing = missing_libraries(executable) + if missing: + raise RuntimeError( + f"{BROWSER} still lacks {', '.join(missing)} after installing " + f"{packages} via {manager}." + ) + + +def _ensure_browser() -> None: + executable = browser_executable() + if executable is None: + _download_browser() + executable = browser_executable() + if executable is None: + raise RuntimeError(f"{BROWSER} is still missing after provisioning.") + _ensure_browser_libraries(executable) + + def ensure() -> None: _ensure_unzip() if not which("mmdc"): 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 + npm_install_global("@mermaid-js/mermaid-cli") if not which("mmdc"): - warn("Command 'mmdc' is still unavailable after installation.") - return + raise RuntimeError( + "Command 'mmdc' is still unavailable after installation." + ) _ensure_browser() From 1c35cdef91a4c82af2ec8de7da8872755d418b97 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Fri, 16 Oct 2026 01:35:21 +0200 Subject: [PATCH 13/13] style: apply the autoformat output main drifted from `make quality-high` on main (fea6f31d9f) rewrote two files in its autoformat step: - roles/sys-service/handlers/refresh_systemctl_service.yml: the handler's `when` was wrapped by hand; the formatter wraps it at line width. Both forms parse to the same YAML. - tests/unit/python/roles/web-app-nextcloud/test_onlyoffice_check_deadline.py: two over-long assertIn calls that ruff format splits. A second autoformat run leaves the tree unchanged, so main is stable under the formatter again. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/sys-service/handlers/refresh_systemctl_service.yml | 5 ++--- .../web-app-nextcloud/test_onlyoffice_check_deadline.py | 9 +++++++-- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/roles/sys-service/handlers/refresh_systemctl_service.yml b/roles/sys-service/handlers/refresh_systemctl_service.yml index 6c8fb43bca..111fcf6bdf 100644 --- a/roles/sys-service/handlers/refresh_systemctl_service.yml +++ b/roles/sys-service/handlers/refresh_systemctl_service.yml @@ -53,6 +53,5 @@ Unable to start service {{ system_service_name }}. See shared service diagnostics above. when: - not (system_service_suppress_flush | bool) - - (systemd_set_state.failed | default(false) | bool) or (system_service_state != omit and ( - (system_service_result.stdout | default('') | trim) not in ['success', ''] or - (system_service_exec_status.stdout | default('') | trim) not in ['0', ''])) + - (systemd_set_state.failed | default(false) | bool) or (system_service_state != omit and ( (system_service_result.stdout | default('') | trim) not in + ['success', ''] or (system_service_exec_status.stdout | default('') | trim) not in ['0', ''])) diff --git a/tests/unit/python/roles/web-app-nextcloud/test_onlyoffice_check_deadline.py b/tests/unit/python/roles/web-app-nextcloud/test_onlyoffice_check_deadline.py index 5ca872e41f..990e1b697e 100644 --- a/tests/unit/python/roles/web-app-nextcloud/test_onlyoffice_check_deadline.py +++ b/tests/unit/python/roles/web-app-nextcloud/test_onlyoffice_check_deadline.py @@ -15,13 +15,18 @@ class TestOnlyofficeCheckDeadline(unittest.TestCase): def test_the_deadline_is_set_before_the_check(self) -> None: deadline, check = self.tasks self.assertIn("nextcloud_onlyoffice_check_deadline", deadline["set_fact"]) - self.assertIn("lookup('timeout'", deadline["set_fact"]["nextcloud_onlyoffice_check_deadline"]) + self.assertIn( + "lookup('timeout'", + deadline["set_fact"]["nextcloud_onlyoffice_check_deadline"], + ) self.assertEqual(check["register"], "nextcloud_onlyoffice_check") def test_the_retries_stop_at_the_deadline(self) -> None: until = self.tasks[1]["until"] self.assertIn("nextcloud_onlyoffice_check.rc == 0", until) - self.assertIn("now(utc=true).timestamp() > nextcloud_onlyoffice_check_deadline", until) + self.assertIn( + "now(utc=true).timestamp() > nextcloud_onlyoffice_check_deadline", until + ) if __name__ == "__main__":