From 7e68dc4c61e8e062e6de54db490f403f0858e546 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 15 Oct 2026 00:59:39 +0200 Subject: [PATCH 1/8] 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 3c53fde46a9b2181a424b1ef7e74cf4840c68e12 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 15 Oct 2026 15:23:03 +0200 Subject: [PATCH 2/8] 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 a59eb5d34701cbd2b87800ef8d17db5d784d680b Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 15 Oct 2026 22:56:20 +0200 Subject: [PATCH 3/8] 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 4/8] 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 5/8] 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 6/8] 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 7/8] 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__": From 67f6c8d7e847d61c7a9b0cf986b46600fa2e1e65 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Fri, 16 Oct 2026 11:11:47 +0200 Subject: [PATCH 8/8] fix(cache): keep the applications carrier valid across token store writes Since 778c18fb23 the carrier key holds the tokens file's mtime and size. sys-token-store changed that stat on every inclusion (00_core.yml touched the file) and on every persisted token, and nothing re-parked a carrier afterwards. Every later task's fresh worker then rendered the applications SPOT cold, 30 to 80 s each. On main fea6f31d9f (run 38812964308) seven heavy jobs logged 194 to 287 such tasks and ran out of the 20400 s budget; the same jobs before 778c18fb23 logged 65 to 83, all of them real waits. - 00_core.yml touches the store with modification_time and access_time preserved, so it only creates a missing file. In swarm the controller sees the store over NFS with attribute caching, and the touch alone made the second pass go cold without any write. - write.yml re-parks the carrier when the persist or the controller mirror changed the store. Both run once, so every host that ran the include gets the same verdict. - tasks/utils/setup/role.yml re-parks after every role on every host, so hosts that did not run the writing role recover too. Where the key still matches this serves the carried payload; measured 0.1 s per role in a local compose deploy. - The tokens file enters the key as the SHA-256 of its content, memoised per inode, mtime and size, so a touch no longer changes the key. A stat that still matches serves the memo (1.67 us against 1.41 us for the old stat signature), and a stale stat keeps key and YAML cache on the same old content instead of pairing new content with an old key. - applications_carrier opens the tokens file before it computes the key, so on the NFS-mounted controller the parked key reflects the revalidated attributes rather than a cached stat that changes a minute later. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../files/plugins/lookup/applications.md | 8 ++- plugins/action/applications_carrier.py | 9 ++- roles/sys-token-store/tasks/00_core.yml | 2 + roles/sys-token-store/tasks/write.yml | 6 ++ tasks/utils/setup/role.yml | 3 + .../action/test_applications_carrier.py | 42 ++++++++++++++ tests/unit/python/utils/cache/test_base.py | 43 ++++++++++++-- utils/cache/README.md | 2 +- utils/cache/base.py | 57 ++++++++++++++----- utils/cache/carrier.py | 14 ++++- 10 files changed, 161 insertions(+), 25 deletions(-) diff --git a/docs/contributing/artefact/files/plugins/lookup/applications.md b/docs/contributing/artefact/files/plugins/lookup/applications.md index c051176c84..fdca9bd70f 100644 --- a/docs/contributing/artefact/files/plugins/lookup/applications.md +++ b/docs/contributing/artefact/files/plugins/lookup/applications.md @@ -18,7 +18,7 @@ The `applications` lookup is the ONLY supported runtime entry point for merged a | `lookup('applications')` | Full merged mapping keyed by `application_id`. | | `lookup('applications', '')` | Merged entry for that application. Raises when missing. | | `lookup('applications', '', default_value)` | Merged entry, or `default_value` when the entry is missing. | -| `lookup('applications', carrier=True)` | `{"key": [...], "applications": {...}}`: the full mapping plus the cache key it is valid under. Reserved for the constructor's carrier task (see below). | +| `lookup('applications', carrier=True)` | `{"key": [...], "applications": {...}}`: the full mapping plus the cache key it is valid under. Reserved for the `applications_carrier` action (see below). | ## Data Sources ๐Ÿ“š @@ -33,9 +33,11 @@ No other source is consulted. Ansible forks a fresh worker process for every task. The in-process cache inside `get_merged_applications` therefore never survives from one task to the next, and every task that touches the lookup would render the full tree again (about 16 to 23 seconds per task on a CI runner, measured on the workspace jobs). -The constructor stage renders once through the [applications_carrier](../../../../../../plugins/action/applications_carrier.py) action and parks the result together with its cache key in the host fact `_INFINITO_APPLICATIONS_RENDERED` (the action calls `lookup('applications', carrier=True)`). Every later worker inherits that fact at fork time; `get_merged_applications` serves it whenever the key still matches and renders only when it does not (a changed `applications`, `users`, `DOMAIN_PRIMARY` or `SYSTEM_EMAIL_DOMAIN`). +The constructor stage renders once through the [applications_carrier](../../../../../../plugins/action/applications_carrier.py) action and parks the result together with its cache key in the host fact `_INFINITO_APPLICATIONS_RENDERED` (the action calls `lookup('applications', carrier=True)`). Every later worker inherits that fact at fork time; `get_merged_applications` serves it whenever the key still matches and renders only when it does not (a changed `applications`, `users`, `DOMAIN_PRIMARY`, `SYSTEM_EMAIL_DOMAIN` or `group_names`, or a changed path or content of the tokens file). -- The task sits in `tasks/stages/01_constructor.yml` after the `networks`, `design` and `service_provider` merges, after the `add_host` placements and after the token store, so the payload renders with the same `group_names`, `groups` and user records a role would see. Moving it earlier bakes stale values into the play. +- The stage-wide task sits in `tasks/stages/01_constructor.yml` after the `networks`, `design` and `service_provider` merges, after the `add_host` placements and after the token store, so the payload renders with the same `group_names`, `groups` and user records a role would see. Moving it earlier bakes stale values into the play. +- The carrier is parked again after every role in `tasks/utils/setup/role.yml` and after every persisted token in `roles/sys-token-store/tasks/write.yml`. A re-park whose key still matches serves the carried payload without rendering. +- The tokens file enters the key as the SHA-256 of its content, memoised per inode, mtime and size, so a touch keeps the key. The carrier action opens the file before it computes the key, so an NFS client keys on revalidated attributes. - The action masks its own result: the fact is the whole rendered tree with every application's credentials, so it never reaches a log regardless of `MASK_CREDENTIALS_IN_LOGS`. - User records inside the payload are the token store's state at render time. Readers of tokens captured later in the play MUST go through `lookup('users', ...)` or `lookup('config', , 'users....')`, both of which read the users cache fresh. - The carrier is private to the lookup. Consumers MUST NOT read `_INFINITO_APPLICATIONS_RENDERED`; they keep going through `lookup('applications')`, which is what makes the carrier transparent. diff --git a/plugins/action/applications_carrier.py b/plugins/action/applications_carrier.py index ce05759532..93c479ff3d 100644 --- a/plugins/action/applications_carrier.py +++ b/plugins/action/applications_carrier.py @@ -14,13 +14,17 @@ instead of rendering:: for the merge block, which it drops again at the block's end, one after the ``add_host`` tasks for the swarm bootstrap roles, parked only when ``DEPLOYMENT_MODE`` is ``swarm``, and the stage-wide one after the token store. ``merged_applications_cache_key`` reads ``group_names`` and the -tokens file's path, mtime and size, so a carrier whose groups or tokens no +tokens file's path and content digest, so a carrier whose groups or tokens no longer match is rejected and the reader renders afresh:: - name: ๐ŸงŠ Drop the merge-block carrier so later stages re-render applications_carrier: clear: true +``tasks/utils/setup/role.yml`` parks one after every role and +``roles/sys-token-store/tasks/write.yml`` one after every persisted token; +where the key still matches they serve the carried payload without rendering. + The result is masked by the action itself: the fact is the whole rendered tree, about 0.4 MB with every application's credentials, and printing it at ``-v`` is neither credential debugging nor readable. @@ -39,7 +43,7 @@ from ansible.module_utils.parsing.convert_bool import boolean from ansible.plugins.action import ActionBase from ansible.plugins.loader import lookup_loader -from utils.cache.carrier import APPLICATIONS_RENDERED_FACT +from utils.cache.carrier import APPLICATIONS_RENDERED_FACT, revalidate_tokens_file class ActionModule(ActionBase): @@ -64,6 +68,7 @@ class ActionModule(ActionBase): ) return result + revalidate_tokens_file(task_vars) lookup = lookup_loader.get( "applications", loader=self._loader, templar=self._templar ) diff --git a/roles/sys-token-store/tasks/00_core.yml b/roles/sys-token-store/tasks/00_core.yml index 7f77bcb4c0..1d27b4468f 100644 --- a/roles/sys-token-store/tasks/00_core.yml +++ b/roles/sys-token-store/tasks/00_core.yml @@ -14,6 +14,8 @@ ansible.builtin.file: path: "{{ FILE_TOKENS }}" state: touch + modification_time: preserve + access_time: preserve owner: "{{ SYS_TOKEN_STORE_OWNER }}" group: "{{ SYS_TOKEN_STORE_GROUP }}" mode: "{{ SYS_TOKEN_STORE_FILE_MODE }}" diff --git a/roles/sys-token-store/tasks/write.yml b/roles/sys-token-store/tasks/write.yml index 51c6f5190f..6ee10926a5 100644 --- a/roles/sys-token-store/tasks/write.yml +++ b/roles/sys-token-store/tasks/write.yml @@ -51,6 +51,7 @@ run_once: true no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" become: true + register: sys_token_store_persisted - name: "๐Ÿชž Mirror the store onto the controller, where every users lookup reads" ansible.builtin.copy: @@ -63,3 +64,8 @@ delegate_to: localhost run_once: true no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + register: sys_token_store_mirrored + +- name: ๐ŸงŠ Re-render the applications SPOT the new token invalidated + applications_carrier: {} + when: sys_token_store_persisted is changed or sys_token_store_mirrored is changed diff --git a/tasks/utils/setup/role.yml b/tasks/utils/setup/role.yml index b618b6195d..34b31c5fb2 100644 --- a/tasks/utils/setup/role.yml +++ b/tasks/utils/setup/role.yml @@ -6,3 +6,6 @@ - name: "๐Ÿšฟ flush handlers after {{ role_entry.app }}" ansible.builtin.meta: flush_handlers + +- name: "๐ŸงŠ Carry the applications SPOT past {{ role_entry.app }}" + applications_carrier: {} diff --git a/tests/unit/python/plugins/action/test_applications_carrier.py b/tests/unit/python/plugins/action/test_applications_carrier.py index 841b2eea44..9f69c1d1d5 100644 --- a/tests/unit/python/plugins/action/test_applications_carrier.py +++ b/tests/unit/python/plugins/action/test_applications_carrier.py @@ -56,6 +56,48 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase): self.assertEqual(variables, {"applications": {}}) self.assertTrue(kwargs["carrier"]) + def test_revalidates_the_tokens_file_before_rendering(self): + order = [] + lookup = _FakeLookup({"key": ["roles", []], "applications": {}}) + lookup.run = lambda *args, **kwargs: order.append("render") or [{}] + action = _make_action(_FakeTask()) + with ( + patch( + "plugins.action.applications_carrier.ActionBase.run", + autospec=True, + return_value={}, + ), + patch( + "plugins.action.applications_carrier.lookup_loader.get", + return_value=lookup, + ), + patch( + "plugins.action.applications_carrier.revalidate_tokens_file", + side_effect=lambda variables: order.append(("revalidate", variables)), + ), + ): + action.run(task_vars={"FILE_TOKENS": "/x/tokens.yml"}) + + self.assertEqual( + order, [("revalidate", {"FILE_TOKENS": "/x/tokens.yml"}), "render"] + ) + + def test_clear_does_not_revalidate(self): + action = _make_action(_FakeTask(args={"clear": True})) + with ( + patch( + "plugins.action.applications_carrier.ActionBase.run", + autospec=True, + return_value={}, + ), + patch( + "plugins.action.applications_carrier.revalidate_tokens_file" + ) as revalidate, + ): + action.run(task_vars={}) + + revalidate.assert_not_called() + def test_rejects_arguments(self): action = _make_action(_FakeTask(args={"foo": 1})) with ( diff --git a/tests/unit/python/utils/cache/test_base.py b/tests/unit/python/utils/cache/test_base.py index 044cd168e9..657fbbd12d 100644 --- a/tests/unit/python/utils/cache/test_base.py +++ b/tests/unit/python/utils/cache/test_base.py @@ -10,9 +10,11 @@ files; this file pins the contract of base itself. from __future__ import annotations +import os import tempfile import textwrap import unittest +import unittest.mock as mock from pathlib import Path from utils.cache import _reset_cache_for_tests, base @@ -153,11 +155,13 @@ class TestStableVariablesSignature(unittest.TestCase): class TestTokensFileSignature(unittest.TestCase): - def test_missing_file_returns_zeroed_signature(self): + def setUp(self): + base._reset() + + def test_missing_file_returns_an_empty_digest(self): with tempfile.TemporaryDirectory() as tmp: - sig = base._tokens_file_signature(Path(tmp) / "absent.yml") - self.assertEqual(sig[1], 0) - self.assertEqual(sig[2], 0) + path = Path(tmp) / "absent.yml" + self.assertEqual(base._tokens_file_signature(path), (str(path), "")) def test_signature_changes_when_file_changes(self): with tempfile.TemporaryDirectory() as tmp: @@ -168,6 +172,37 @@ class TestTokensFileSignature(unittest.TestCase): sig_after = base._tokens_file_signature(path) self.assertNotEqual(sig_before, sig_after) + def test_a_touch_keeps_the_signature(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "tokens.yml" + path.write_text("a: 1\n", encoding="utf-8") + sig_before = base._tokens_file_signature(path) + later = path.stat().st_mtime_ns + 5_000_000_000 + os.utime(path, ns=(later, later)) + self.assertEqual(base._tokens_file_signature(path), sig_before) + + def test_an_unchanged_stat_serves_the_digest_without_reading(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "tokens.yml" + path.write_text("a: 1\n", encoding="utf-8") + sig_before = base._tokens_file_signature(path) + with mock.patch.object(Path, "open", side_effect=AssertionError): + self.assertEqual(base._tokens_file_signature(path), sig_before) + + +class TestRevalidateTokensFile(unittest.TestCase): + def test_opens_the_file(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "tokens.yml" + path.write_text("a: 1\n", encoding="utf-8") + with mock.patch.object(Path, "open", wraps=path.open) as opened: + base._revalidate_tokens_file(path) + opened.assert_called_once_with("rb") + + def test_a_missing_file_is_ignored(self): + with tempfile.TemporaryDirectory() as tmp: + base._revalidate_tokens_file(Path(tmp) / "absent.yml") + class TestRenderWithTemplar(unittest.TestCase): """`_render_with_templar` is the single ansible-coupled symbol in diff --git a/utils/cache/README.md b/utils/cache/README.md index a4d0080e34..7e42126045 100644 --- a/utils/cache/README.md +++ b/utils/cache/README.md @@ -26,7 +26,7 @@ The layers are orthogonal: `yaml.py` caches "this file's parsed root", the `appl Both layers are process-wide in-process caches. They intentionally do NOT track on-disk file mtimes; CLI tools are short-lived and the assumption "the on-disk file does not change while my process runs" holds. The single exception is `utils.cache.yaml.dump_yaml`, which writes through and evicts the cached entry for the path it just wrote so a tool that edits a file mid-run sees the new content on the next read. -Inside a play the process boundary is the task: Ansible forks a fresh worker per task, so `_MERGED_APPLICATIONS_CACHE` starts empty in every worker. `get_merged_applications` therefore also accepts the play-scoped carrier fact `_INFINITO_APPLICATIONS_RENDERED` (payload plus cache key, parked once by the constructor stage) and serves it when the key matches. See [applications.md](../../docs/contributing/artefact/files/plugins/lookup/applications.md) for the contract. +Inside a play the process boundary is the task: Ansible forks a fresh worker per task, so `_MERGED_APPLICATIONS_CACHE` starts empty in every worker. `get_merged_applications` therefore also accepts the play-scoped carrier fact `_INFINITO_APPLICATIONS_RENDERED` (payload plus cache key, parked by the constructor stage and again after every role and every persisted token) and serves it when the key matches. See [applications.md](../../docs/contributing/artefact/files/plugins/lookup/applications.md) for the contract. ## Test-Only Helpers ๐Ÿงช diff --git a/utils/cache/base.py b/utils/cache/base.py index f9c2d23276..27510d8941 100644 --- a/utils/cache/base.py +++ b/utils/cache/base.py @@ -16,10 +16,12 @@ only when actually invoked. from __future__ import annotations import copy +import hashlib +import os import threading from collections.abc import Mapping from pathlib import Path -from typing import TYPE_CHECKING, Any +from typing import Any from plugins.filter.merge.with_defaults import ( merge_with_defaults, # noqa: F401 re-exported @@ -28,8 +30,7 @@ from utils.paths import FILE_TOKENS from . import PROJECT_ROOT, ROLES_DIR # noqa: F401 -if TYPE_CHECKING: - import os +_TOKENS_DIGESTS: dict[tuple, str] = {} try: from ansible.parsing.vault import EncryptedString as _AnsibleEncryptedString @@ -125,18 +126,46 @@ def _stable_variables_signature(variables: Mapping[str, Any] | None) -> tuple: ) -def _tokens_file_signature(path: Path) -> tuple: - """Return a cheap stat-based signature for the tokens file. +def _stat_identity(st: os.stat_result) -> tuple: + return (st.st_ino, st.st_mtime_ns, st.st_size) - The merged-users cache must invalidate whenever sys-token-store persists a - new token โ€” otherwise downstream `lookup('users', ...)` returns stale tokens - within the same play. stat() is cheap and captures in-place writes. + +def _tokens_file_signature(path: Path) -> tuple: + """Return ``(path, sha256 of the content)`` for the tokens file. + + Args: + path: the tokens file. + + Returns: + ``(str(path), "")`` when the file cannot be read. """ try: - st = path.stat() - except (FileNotFoundError, OSError): - return (str(path), 0, 0) - return (str(path), st.st_mtime_ns, st.st_size) + identity = (str(path), *_stat_identity(path.stat())) + except OSError: + return (str(path), "") + digest = _TOKENS_DIGESTS.get(identity) + if digest is None: + try: + with path.open("rb") as handle: + identity = (str(path), *_stat_identity(os.fstat(handle.fileno()))) + digest = hashlib.sha256(handle.read()).hexdigest() + except OSError: + return (str(path), "") + _TOKENS_DIGESTS[identity] = digest + return (str(path), digest) + + +def _revalidate_tokens_file(path: Path) -> None: + """Open and close the tokens file so an NFS client refreshes its attributes. + + Args: + path: the tokens file. + """ + try: + with path.open("rb"): + pass + except OSError: + return def _deep_merge(base: Any, override: Any) -> Any: @@ -287,5 +316,5 @@ def _render_with_templar( def _reset() -> None: - """No-op kept so the `data._reset_cache_for_tests` facade can call every - domain module uniformly. This module owns no cache.""" + """Clear the tokens-file digest memo.""" + _TOKENS_DIGESTS.clear() diff --git a/utils/cache/carrier.py b/utils/cache/carrier.py index dfda350ae4..aafed31415 100644 --- a/utils/cache/carrier.py +++ b/utils/cache/carrier.py @@ -16,6 +16,7 @@ from typing import TYPE_CHECKING, Any from .base import ( _cache_key, _resolve_roles_dir, + _revalidate_tokens_file, _stable_variables_signature, _tokens_file_signature, ) @@ -42,7 +43,7 @@ def merged_applications_cache_key( Returns: ``(resolved roles dir, stable variables signature extended by the - tokens file's path, mtime and size)``. + tokens file's path and content digest)``. """ from .users import _resolve_tokens_file @@ -53,6 +54,17 @@ def merged_applications_cache_key( ) +def revalidate_tokens_file(variables: Mapping[str, Any] | None) -> None: + """Refresh an NFS client's attributes of the tokens file before a carrier is keyed. + + Args: + variables: The play's variable scope the tokens file resolves from. + """ + from .users import _resolve_tokens_file + + _revalidate_tokens_file(_resolve_tokens_file(variables)) + + def _carried_applications( variables: Mapping[str, Any], cache_key: tuple[str, tuple] ) -> dict[str, Any] | None: