From 2e2b42c9b304696545bd0f558d814c051d12ca56 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Mon, 5 Oct 2026 19:20:16 +0000 Subject: [PATCH 01/53] update(versions): update pins with a declared source (web-app-gitea) --- roles/web-app-gitea/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-gitea/meta/services.yml b/roles/web-app-gitea/meta/services.yml index bf0b9f8563..7b494ca53d 100644 --- a/roles/web-app-gitea/meta/services.yml +++ b/roles/web-app-gitea/meta/services.yml @@ -112,7 +112,7 @@ giteamcpupstream: enabled: "{{ lookup('config', 'web-app-gitea', 'mcp.enabled') | bool }}" shared: false image: docker.gitea.com/gitea-mcp-server - version: "1.6.0" + version: "1.8.0" update: type: registry_tags image: docker.gitea.com/gitea-mcp-server From 9b746233f9db9b99109484799a1a68864a896f57 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Mon, 5 Oct 2026 19:20:21 +0000 Subject: [PATCH 02/53] update(versions): update pins with a declared source (web-app-hugo) --- roles/web-app-hugo/meta/services.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/roles/web-app-hugo/meta/services.yml b/roles/web-app-hugo/meta/services.yml index 836b451aa7..e2374b3056 100644 --- a/roles/web-app-hugo/meta/services.yml +++ b/roles/web-app-hugo/meta/services.yml @@ -35,9 +35,9 @@ hugo: version: 1.31-alpine custom: true builder_image: hugomods/hugo - builder_version: exts-0.148.0 + builder_version: exts-0.154.5 source_repository: https://github.com/gohugoio/hugoDocs.git - source_version: v0.148.0 + source_version: v0.165.0 update: - key: builder_version type: registry_tags From 2da51d1b785227db39923354dd9d7004e5f885ab Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Mon, 5 Oct 2026 19:20:27 +0000 Subject: [PATCH 03/53] update(versions): update pins with a declared source (web-app-moodle) --- roles/web-app-moodle/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-moodle/meta/services.yml b/roles/web-app-moodle/meta/services.yml index 70f66d0f48..52a781d37f 100644 --- a/roles/web-app-moodle/meta/services.yml +++ b/roles/web-app-moodle/meta/services.yml @@ -45,7 +45,7 @@ moodle: bond: 1 enabled: true # nocheck: dynamic-flag shared: true - app_version: 4.5.11 + app_version: 5.3.0 update: key: app_version type: git_tags From 4c699f9f7c6d86bd603d93ecc1e057b97071e302 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Mon, 5 Oct 2026 19:20:31 +0000 Subject: [PATCH 04/53] update(versions): update pins with a declared source (web-app-n8n) --- roles/web-app-n8n/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-n8n/meta/services.yml b/roles/web-app-n8n/meta/services.yml index a7ad1c3b40..156c60abc5 100644 --- a/roles/web-app-n8n/meta/services.yml +++ b/roles/web-app-n8n/meta/services.yml @@ -67,7 +67,7 @@ n8n: backup: no_stop_required: false image: docker.n8n.io/n8nio/n8n - version: "1.100.1" + version: "2.42.3" update: type: registry_tags image: docker.n8n.io/n8nio/n8n From 9e1392fc445474f725bdda6c14d394613f5a9661 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Mon, 5 Oct 2026 19:20:40 +0000 Subject: [PATCH 05/53] update(versions): update pins with a declared source (web-app-stalwart) --- roles/web-app-stalwart/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-stalwart/meta/services.yml b/roles/web-app-stalwart/meta/services.yml index e9edc177cb..9f0b082711 100644 --- a/roles/web-app-stalwart/meta/services.yml +++ b/roles/web-app-stalwart/meta/services.yml @@ -44,7 +44,7 @@ stalwart: placement: manager image: stalwartlabs/stalwart version: "v0.16.25" - webui_version: "v1.0.5" + webui_version: "v1.0.11" update: key: webui_version type: git_tags From a86eae8740eae4f02fe1a611bc14001b3c6ce778 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Mon, 5 Oct 2026 19:20:50 +0000 Subject: [PATCH 06/53] update(versions): update pins with a declared source (web-app-wordpress) --- roles/web-app-wordpress/meta/addons/mcp-adapter.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-wordpress/meta/addons/mcp-adapter.yml b/roles/web-app-wordpress/meta/addons/mcp-adapter.yml index 60fd5c6322..a56aa4270f 100644 --- a/roles/web-app-wordpress/meta/addons/mcp-adapter.yml +++ b/roles/web-app-wordpress/meta/addons/mcp-adapter.yml @@ -3,7 +3,7 @@ enabled: "{{ lookup('config', 'web-app-wordpress', 'mcp.enabled') | bool }}" required: true mechanism: plugin source: upstream -version: v0.5.0 +version: v0.7.0 update: monitored: true catalog: github-releases From ac6bd94bc60d844635a9abd6573f7b2bd2a1cede Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Mon, 5 Oct 2026 19:20:51 +0000 Subject: [PATCH 07/53] update(galaxy): bump pinned Ansible collections --- requirements/requirements.galaxy.yml | 4 ++-- requirements/requirements.git.yml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/requirements/requirements.galaxy.yml b/requirements/requirements.galaxy.yml index 0a1db299fb..ef98c31538 100644 --- a/requirements/requirements.galaxy.yml +++ b/requirements/requirements.galaxy.yml @@ -7,10 +7,10 @@ collections: - name: kewlfft.aur version: 0.13.0 - name: community.general - version: 13.4.0 + version: 13.5.0 - name: community.docker version: 5.4.0 - name: community.library_inventory_filtering_v1 version: 1.1.5 - name: hetzner.hcloud - version: 7.1.0 + version: 7.2.0 diff --git a/requirements/requirements.git.yml b/requirements/requirements.git.yml index eef6cbd713..58808ee14c 100644 --- a/requirements/requirements.git.yml +++ b/requirements/requirements.git.yml @@ -18,7 +18,7 @@ collections: - name: community.general source: https://github.com/ansible-collections/community.general.git type: git - version: 13.4.0 + version: 13.5.0 - name: community.docker source: https://github.com/ansible-collections/community.docker.git @@ -33,4 +33,4 @@ collections: - name: hetzner.hcloud source: https://github.com/ansible-collections/hetzner.hcloud.git type: git - version: 7.1.0 + version: 7.2.0 From d827b0575f313a30772fe6aa0667b815329ea374 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Mon, 5 Oct 2026 19:20:55 +0000 Subject: [PATCH 08/53] update(versions): update pins with a declared source (web-app-xwiki) --- roles/web-app-xwiki/meta/addons/ai-llm.yml | 2 +- roles/web-app-xwiki/meta/addons/ldap-authenticator.yml | 2 +- roles/web-app-xwiki/meta/addons/oidc-authenticator.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/roles/web-app-xwiki/meta/addons/ai-llm.yml b/roles/web-app-xwiki/meta/addons/ai-llm.yml index 18e7bdec6c..5fa3d267ec 100644 --- a/roles/web-app-xwiki/meta/addons/ai-llm.yml +++ b/roles/web-app-xwiki/meta/addons/ai-llm.yml @@ -5,7 +5,7 @@ mechanism: extension source: upstream bridges: - litellm -version: "0.7" +version: "0.10" update: type: http_regex url: https://maven.xwiki.org/releases/org/xwiki/contrib/llm/application-ai-llm-models-ui/maven-metadata.xml diff --git a/roles/web-app-xwiki/meta/addons/ldap-authenticator.yml b/roles/web-app-xwiki/meta/addons/ldap-authenticator.yml index 3a6372c637..89c20d8112 100644 --- a/roles/web-app-xwiki/meta/addons/ldap-authenticator.yml +++ b/roles/web-app-xwiki/meta/addons/ldap-authenticator.yml @@ -5,7 +5,7 @@ mechanism: extension source: upstream bridges: - ldap -version: "9.15.7" +version: "9.16.6" update: type: http_regex url: https://maven.xwiki.org/releases/org/xwiki/contrib/ldap/ldap-authenticator/maven-metadata.xml diff --git a/roles/web-app-xwiki/meta/addons/oidc-authenticator.yml b/roles/web-app-xwiki/meta/addons/oidc-authenticator.yml index e80ea23ca7..16f95f37ce 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.19.6" +version: "2.28.1" update: type: http_regex url: https://maven.xwiki.org/releases/org/xwiki/contrib/oidc/oidc-authenticator/maven-metadata.xml From 33fdcd1d65f208997274c1378e65a8b4a1682ed5 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Mon, 5 Oct 2026 20:56:14 +0000 Subject: [PATCH 09/53] update(images): update Docker image versions (svc-db-qdrant) --- roles/svc-db-qdrant/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/svc-db-qdrant/meta/services.yml b/roles/svc-db-qdrant/meta/services.yml index 50a5a5fb7c..7b363b9248 100644 --- a/roles/svc-db-qdrant/meta/services.yml +++ b/roles/svc-db-qdrant/meta/services.yml @@ -12,7 +12,7 @@ qdrant: bond: 1 image: qdrant/qdrant name: qdrant - version: v1.19.1 + version: v1.19.2 min_storage: 270MB backup: database_routine: true From e07f617f0f2a9313244dad8cb5006e28c07f8c96 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Mon, 5 Oct 2026 20:56:20 +0000 Subject: [PATCH 10/53] update(images): update Docker image versions (web-app-jira) --- roles/web-app-jira/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-jira/meta/services.yml b/roles/web-app-jira/meta/services.yml index e45dcd4d71..e9237405fb 100644 --- a/roles/web-app-jira/meta/services.yml +++ b/roles/web-app-jira/meta/services.yml @@ -37,7 +37,7 @@ jira: swarm: enabled: true image: atlassian/jira-software - version: 11.3.11 + version: 11.3.12 custom: true name: jira min_storage: 1027MB From 39f2bfb87c48bdeadc6669798b6b46350e509e24 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 6 Oct 2026 00:38:12 +0000 Subject: [PATCH 11/53] chore(deps-dev): bump eslint from 10.10.0 to 10.12.0 Bumps [eslint](https://github.com/eslint/eslint) from 10.10.0 to 10.12.0. - [Release notes](https://github.com/eslint/eslint/releases) - [Commits](https://github.com/eslint/eslint/compare/v10.10.0...v10.12.0) --- updated-dependencies: - dependency-name: eslint dependency-version: 10.12.0 dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- package-lock.json | 8 ++++---- package.json | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/package-lock.json b/package-lock.json index 219614de7d..dec3a469ef 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,7 +10,7 @@ "devDependencies": { "@eslint/js": "^10.0.1", "@playwright/test": "^1.63.0", - "eslint": "^10.9.1", + "eslint": "^10.12.0", "eslint-plugin-playwright": "^2.10.5", "globals": "^17.13.0", "stylelint": "^17.16.0" @@ -848,9 +848,9 @@ } }, "node_modules/eslint": { - "version": "10.10.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.10.0.tgz", - "integrity": "sha512-NPXn6r5zl4uET1DAVPaOwzX3rut4c0wcmw3dWJAfOsTM5+TogXo0DDjz8pwm/hL8cyVNpHqeK4JpN0NjnyFFNw==", + "version": "10.12.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.12.0.tgz", + "integrity": "sha512-npHjrHb2o4ehH3mE+YuxABR+0gyb0aVWCIolgJDArwCiHEIsonBm3ZKjel5b0U5+a+MbEvIyRCGCzD3eKKK2NA==", "dev": true, "license": "MIT", "workspaces": [ diff --git a/package.json b/package.json index d07df50441..799548eab2 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "devDependencies": { "@eslint/js": "^10.0.1", "@playwright/test": "^1.63.0", - "eslint": "^10.9.1", + "eslint": "^10.12.0", "eslint-plugin-playwright": "^2.10.5", "globals": "^17.13.0", "stylelint": "^17.16.0" From e142d07f97ec6e1b50313bc6e80761f603785418 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 6 Oct 2026 08:14:14 +0200 Subject: [PATCH 12/53] fix(web-app-xwiki): upgrade an add-on that is not on its pinned version The extension installer returned as soon as an add-on was installed, in whatever version. A new pin in meta/addons/ therefore reached a fresh wiki only, and an existing wiki kept the version it was first deployed with. The installer now skips an add-on only when the installed version equals the pin. Otherwise it calls install(id, version, namespace), which the Extension Manager resolves as an upgrade, and it reports an error when the add-on is not on the pin afterwards. The check that follows the installer compared presence only. It takes the pin as well, so a deploy fails when an add-on is installed in another version. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../files/extension_installer_b64.groovy | 6 +-- .../filter_plugins/xwiki_filters.py | 9 ++-- roles/web-app-xwiki/tasks/04_extensions.yml | 5 ++- .../tasks/_check_extension_via_groovy.yml | 2 +- .../python/roles/web-app-xwiki/__init__.py | 0 .../web-app-xwiki/filter_plugins/__init__.py | 0 .../filter_plugins/test_xwiki_filters.py | 42 +++++++++++++++++++ 7 files changed, 54 insertions(+), 10 deletions(-) create mode 100644 tests/unit/python/roles/web-app-xwiki/__init__.py create mode 100644 tests/unit/python/roles/web-app-xwiki/filter_plugins/__init__.py create mode 100644 tests/unit/python/roles/web-app-xwiki/filter_plugins/test_xwiki_filters.py diff --git a/roles/web-app-xwiki/files/extension_installer_b64.groovy b/roles/web-app-xwiki/files/extension_installer_b64.groovy index 631b51497c..4d6e1d45c9 100644 --- a/roles/web-app-xwiki/files/extension_installer_b64.groovy +++ b/roles/web-app-xwiki/files/extension_installer_b64.groovy @@ -20,7 +20,7 @@ wanted.each { e -> if (!id) { println "ERROR::::Empty extension id in wanted list"; return } def already = ext.getInstalledExtension(id, ns) - if (already) { println "ALREADY_INSTALLED::${id}::${already.id?.version}"; return } + if (already && (!ver || already.id?.version?.toString() == ver)) { println "ALREADY_INSTALLED::${id}::${already.id?.version}"; return } println "INSTALL_START::${id}::${ver ? ver : 'latest'}" def job = null @@ -39,7 +39,7 @@ wanted.each { e -> def errMsg = err ? (err?.message ?: err?.toString()) : null def now = ext.getInstalledExtension(id, ns) - if (now) { + if (now && (!ver || now.id?.version?.toString() == ver)) { // Race-safe: Extension Manager can report "Failed to create install plan" // while the extension gets installed by the concurrent distribution job. if (caughtErr) println "WARN::${id}::${caughtErr}" @@ -51,6 +51,6 @@ wanted.each { e -> if (!caughtErr && !errMsg && st && st != 'FINISHED') { println "ERROR::${id}::Unexpected install state ${st}" } - println "INSTALLED_MISSING::${id}" + println now ? "ERROR::${id}::Still on ${now.id?.version}, wanted ${ver}" : "INSTALLED_MISSING::${id}" } } diff --git a/roles/web-app-xwiki/filter_plugins/xwiki_filters.py b/roles/web-app-xwiki/filter_plugins/xwiki_filters.py index 0a914d474d..4b7eea5c69 100644 --- a/roles/web-app-xwiki/filter_plugins/xwiki_filters.py +++ b/roles/web-app-xwiki/filter_plugins/xwiki_filters.py @@ -3,18 +3,18 @@ from __future__ import annotations import re -def xwiki_extension_status(raw: str) -> int: +def xwiki_extension_status(raw: str, version: str = "") -> int: """ Parse the output of the Groovy CheckExtension page. - Strips HTML tags and entities ( ) - - Returns 200 if extension is INSTALLED, otherwise 404 Args: raw: Raw HTTP body from the checker page. + version: The pinned version; empty accepts any installed version. Returns: - 200 if installed, 404 if missing/unknown. + 200 if installed in the pinned version, otherwise 404. """ if raw is None: return 404 @@ -23,7 +23,8 @@ def xwiki_extension_status(raw: str) -> int: text = text.replace(" ", " ").replace("\u00a0", " ") text = text.strip() - if text.startswith("INSTALLED::"): + suffix = f"::{version}" if version else "" + if text.startswith("INSTALLED::") and text.endswith(suffix): return 200 return 404 diff --git a/roles/web-app-xwiki/tasks/04_extensions.yml b/roles/web-app-xwiki/tasks/04_extensions.yml index f93d0eea3d..75d9d8a3be 100644 --- a/roles/web-app-xwiki/tasks/04_extensions.yml +++ b/roles/web-app-xwiki/tasks/04_extensions.yml @@ -72,6 +72,7 @@ label: "{{ plugin.id }}" vars: ext_id: "{{ plugin.id }}" + ext_version: "{{ plugin.version }}" result_var: "probe_{{ plugin.id | regex_replace('[^A-Za-z0-9_]', '_') }}" - name: "📊 XWIKI | Collect probe results" @@ -83,11 +84,11 @@ loop_var: plugin changed_when: false -- name: "✅ XWIKI | Assert all requested extensions are installed" +- name: "✅ XWIKI | Assert all requested extensions are on their pinned version" vars: missing: "{{ (_xwiki_probe_results | default([])) | selectattr('status','equalto',404) | map(attribute='id') | list }}" fail: - msg: "Missing extensions: {{ missing | join(', ') }}" + msg: "Extensions missing or not on their pinned version: {{ missing | join(', ') }}" when: missing | length > 0 - name: "🗑️ XWIKI | Delete installer page" diff --git a/roles/web-app-xwiki/tasks/_check_extension_via_groovy.yml b/roles/web-app-xwiki/tasks/_check_extension_via_groovy.yml index 5e81389e0c..cbbd210660 100644 --- a/roles/web-app-xwiki/tasks/_check_extension_via_groovy.yml +++ b/roles/web-app-xwiki/tasks/_check_extension_via_groovy.yml @@ -32,7 +32,7 @@ - name: "💾 XWIKI | Save Groovy check result for {{ ext_id }}" set_fact: "{{ result_var }}": - status: "{{ _check_output.content | xwiki_extension_status }}" + status: "{{ _check_output.content | xwiki_extension_status(ext_version) }}" raw: "{{ _check_output.content }}" - name: "🗑️ XWIKI | Delete checker page" diff --git a/tests/unit/python/roles/web-app-xwiki/__init__.py b/tests/unit/python/roles/web-app-xwiki/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-xwiki/filter_plugins/__init__.py b/tests/unit/python/roles/web-app-xwiki/filter_plugins/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-xwiki/filter_plugins/test_xwiki_filters.py b/tests/unit/python/roles/web-app-xwiki/filter_plugins/test_xwiki_filters.py new file mode 100644 index 0000000000..87142501ea --- /dev/null +++ b/tests/unit/python/roles/web-app-xwiki/filter_plugins/test_xwiki_filters.py @@ -0,0 +1,42 @@ +import importlib.util +import unittest + +from utils import PROJECT_ROOT + +_spec = importlib.util.spec_from_file_location( + "xwiki_filters", + PROJECT_ROOT / "roles/web-app-xwiki/filter_plugins/xwiki_filters.py", +) +_mod = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(_mod) +xwiki_extension_status = _mod.xwiki_extension_status + +EXTENSION = "org.xwiki.contrib.oidc:oidc-authenticator" + + +class TestExtensionStatus(unittest.TestCase): + def test_the_pinned_version_counts_as_installed(self): + page = f"

INSTALLED::{EXTENSION}::2.28.1

" + self.assertEqual(xwiki_extension_status(page, "2.28.1"), 200) + + def test_another_installed_version_is_not_the_pinned_one(self): + page = f"INSTALLED::{EXTENSION}::2.19.6" + self.assertEqual(xwiki_extension_status(page, "2.28.1"), 404) + + def test_a_version_does_not_pass_for_one_it_only_starts_or_ends_like(self): + self.assertEqual( + xwiki_extension_status(f"INSTALLED::{EXTENSION}::0.10", "0.1"), 404 + ) + self.assertEqual( + xwiki_extension_status(f"INSTALLED::{EXTENSION}::10.1", "0.1"), 404 + ) + + def test_no_pin_accepts_any_installed_version(self): + self.assertEqual(xwiki_extension_status(f"INSTALLED::{EXTENSION}::2.19.6"), 200) + + def test_a_missing_extension_is_not_installed(self): + self.assertEqual(xwiki_extension_status(f"MISSING::{EXTENSION}", "2.28.1"), 404) + + +if __name__ == "__main__": + unittest.main() From 5494fbad48150a79c3e555bb962298ba039cf597 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 6 Oct 2026 00:30:55 +0200 Subject: [PATCH 13/53] fix(web-app-penpot): make the frontend wait for its backend by absolute name nginx resolves its upstreams once, at start, so the frontend starts through a guard that waits until `backend` and `exporter` resolve. A container resolves with a search domain, and the zone of a deployment answers every name with the address of the ingress. A service that Docker's DNS did not know yet therefore resolved anyway, as `backend.`. The guard let nginx start at once and nginx pinned the ingress as its backend. Every API call then failed with 502 and the SPA showed "Bad Gateway" instead of the login form, until the container was restarted. The guard now asks for the absolute names, `backend.` and `exporter.`. The search domain is not applied to those, so the lookup fails until the services themselves resolve. Closes #806 Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-penpot/templates/compose.yml.j2 | 2 +- .../python/roles/web-app-penpot/__init__.py | 0 .../test_frontend_start_guard.py | 90 +++++++++++++++++++ 3 files changed, 91 insertions(+), 1 deletion(-) create mode 100644 tests/unit/python/roles/web-app-penpot/__init__.py create mode 100644 tests/unit/python/roles/web-app-penpot/test_frontend_start_guard.py diff --git a/roles/web-app-penpot/templates/compose.yml.j2 b/roles/web-app-penpot/templates/compose.yml.j2 index e04f73a5ce..2e27c07ec1 100644 --- a/roles/web-app-penpot/templates/compose.yml.j2 +++ b/roles/web-app-penpot/templates/compose.yml.j2 @@ -8,7 +8,7 @@ command: - /bin/bash - -c - - 'until getent hosts {{ PENPOT_BACKEND_SERVICE }} >/dev/null 2>&1 && getent hosts {{ PENPOT_EXPORTER_SERVICE }} >/dev/null 2>&1; do sleep 1; done; exec nginx -g "daemon off;"' + - 'until getent hosts {{ PENPOT_BACKEND_SERVICE }}. >/dev/null 2>&1 && getent hosts {{ PENPOT_EXPORTER_SERVICE }}. >/dev/null 2>&1; do sleep 1; done; exec nginx -g "daemon off;"' {{ lookup('container_ports', ['penpot', 'http', DOCKER_BIND_HOST]) | indent(4) }} {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_healthcheck', 'penpot') | indent(4) }} diff --git a/tests/unit/python/roles/web-app-penpot/__init__.py b/tests/unit/python/roles/web-app-penpot/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-penpot/test_frontend_start_guard.py b/tests/unit/python/roles/web-app-penpot/test_frontend_start_guard.py new file mode 100644 index 0000000000..66be48898e --- /dev/null +++ b/tests/unit/python/roles/web-app-penpot/test_frontend_start_guard.py @@ -0,0 +1,90 @@ +import os +import re +import subprocess +import tempfile +import unittest +from pathlib import Path + +from jinja2 import Environment, StrictUndefined, select_autoescape + +from utils import PROJECT_ROOT +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml +from utils.roles.mapping import ROLE_FILE_TEMPL_COMPOSE, ROLE_FILE_VARS_MAIN + +ROLE_DIR = PROJECT_ROOT / "roles/web-app-penpot" + +GETENT_STUB = """#!/usr/bin/env bash +name="${2:-}" +if [[ "${name}" != *. ]]; then +\techo "172.30.0.10 ${name}.infinito.test" +\texit 0 +fi +lookups=$(( $(cat "${STUB_DIR}/absolute-lookups" 2>/dev/null || echo 0) + 1 )) +echo "${lookups}" >"${STUB_DIR}/absolute-lookups" +if [ "${lookups}" -le "${STUB_UNKNOWN_LOOKUPS}" ]; then +\texit 2 +fi +echo "192.168.48.5 ${name%.}" +""" + +NGINX_STUB = """#!/usr/bin/env bash +cat "${STUB_DIR}/absolute-lookups" 2>/dev/null || echo 0 +""" + +QUIET_STUB = """#!/usr/bin/env bash +exit 0 +""" + + +def start_guard() -> str: + template = read_text(str(ROLE_DIR / ROLE_FILE_TEMPL_COMPOSE)) + guard = re.search(r"^\s+- '(until getent hosts .+)'$", template, re.MULTILINE) + names = load_yaml(str(ROLE_DIR / ROLE_FILE_VARS_MAIN)) + env = Environment( + undefined=StrictUndefined, + autoescape=select_autoescape(default_for_string=False), + ) + return env.from_string(guard.group(1)).render( + PENPOT_BACKEND_SERVICE=names["PENPOT_BACKEND_SERVICE"], + PENPOT_EXPORTER_SERVICE=names["PENPOT_EXPORTER_SERVICE"], + ) + + +class TestFrontendStartGuard(unittest.TestCase): + def absolute_lookups_until_nginx_starts(self, failing_absolute_lookups: int) -> int: + with tempfile.TemporaryDirectory() as tmp: + bin_dir = Path(tmp) + stubs = ( + ("getent", GETENT_STUB), + ("nginx", NGINX_STUB), + ("sleep", QUIET_STUB), + ) + for name, body in stubs: + stub = bin_dir / name + stub.write_text(body) + stub.chmod(0o755) + env = {k: v for k, v in os.environ.items() if k != "BASH_ENV"} + env["PATH"] = f"{bin_dir}{os.pathsep}{env['PATH']}" + env["STUB_DIR"] = tmp + env["STUB_UNKNOWN_LOOKUPS"] = str(failing_absolute_lookups) + done = subprocess.run( + ["bash", "-c", start_guard()], + env=env, + capture_output=True, + text=True, + check=False, + timeout=30, + ) + self.assertEqual(done.returncode, 0, done.stderr) + return int(done.stdout) + + def test_nginx_waits_until_the_services_resolve_without_the_search_domain(self): + self.assertEqual(self.absolute_lookups_until_nginx_starts(3), 5) + + def test_nginx_starts_at_once_when_the_services_are_known(self): + self.assertEqual(self.absolute_lookups_until_nginx_starts(0), 2) + + +if __name__ == "__main__": + unittest.main() From 30084f986cd98a822870b0ab75d785f7d919a6a5 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 6 Oct 2026 01:39:19 +0200 Subject: [PATCH 14/53] fix(web-app-keycloak): keep concurrent kcadm jobs from losing the config lock In the async pass the role runs kcadm jobs side by side. Every kcadm call in the Keycloak container shares one config file. kcadm rewrites that file when it refreshes the access token, about every 55 seconds, takes the file lock with tryLock() and gives up at once when another kcadm process holds it. One of two overlapping declared-client jobs then failed with "Failed to get lock on /opt/keycloak/.keycloak/kcadm.config", and the deploy with it. keycloak_kcadm_update now repeats a call that lost the lock, up to ten times one second apart. The call fails while it refreshes its token, before it sends its own request, so repeating it is safe. Every other error still ends the call at once. That covers the module only, so the async jobs are reduced to the ones that go through it: - The default-scope assignment was an async shell task. It ran beside the shell tasks that follow it, and neither side repeats a lost lock. It runs in line now. - The two mail-settings jobs were async without a register, so nothing reaped them and a failure was never seen. They run in line now. The client job and the declared-client jobs stay async. A test fails when an async kcadm task does not use the module or is not registered for the reap. A config file of its own per call was the other option. It does not work by itself, because the admin session lives only in the shared file. Closes #805 Co-Authored-By: Claude Opus 5.5 (1M context) --- library/keycloak_kcadm_update.py | 8 ++- .../tasks/03_manager_ops/update_routines.yml | 4 +- .../tasks/update/02_mail_realm.yml | 3 - .../tasks/update/03_mail_master.yml | 3 - .../tasks/update/04_rbac_client_scope.yml | 4 -- .../web-app-keycloak/test_async_kcadm_jobs.py | 57 +++++++++++++++++++ .../test_library_keycloak_kcadm_update.py | 44 ++++++++++++++ 7 files changed, 109 insertions(+), 14 deletions(-) create mode 100644 tests/unit/python/roles/web-app-keycloak/test_async_kcadm_jobs.py diff --git a/library/keycloak_kcadm_update.py b/library/keycloak_kcadm_update.py index 3913e0ec17..863c67aca3 100755 --- a/library/keycloak_kcadm_update.py +++ b/library/keycloak_kcadm_update.py @@ -14,6 +14,9 @@ from ansible.module_utils.keycloak_scopes import converge_client_scope_lists NO_SUCH_CONTAINER_RE = re.compile(r"no such container", re.IGNORECASE) DEAD_CID_MAX_RETRIES = 80 DEAD_CID_RETRY_DELAY = 3 +CONFIG_LOCK_RE = re.compile(r"Failed to get lock on") +CONFIG_LOCK_MAX_RETRIES = 10 +CONFIG_LOCK_RETRY_DELAY = 1 DOCUMENTATION = r""" --- @@ -119,7 +122,7 @@ result: """ -def _shell(cmd, check): +def _shell(cmd, check, lock_retries=CONFIG_LOCK_MAX_RETRIES): rc = subprocess.run( # noqa: S602 - host-trusted argv; kcadm wrapper needs shell pipes/&& cmd, shell=True, @@ -128,6 +131,9 @@ def _shell(cmd, check): ) stdout = rc.stdout.decode("utf-8", errors="replace").strip() stderr = rc.stderr.decode("utf-8", errors="replace").strip() + if rc.returncode != 0 and lock_retries and CONFIG_LOCK_RE.search(stderr): + time.sleep(CONFIG_LOCK_RETRY_DELAY) + return _shell(cmd, check, lock_retries - 1) return rc.returncode, stdout, stderr diff --git a/roles/web-app-keycloak/tasks/03_manager_ops/update_routines.yml b/roles/web-app-keycloak/tasks/03_manager_ops/update_routines.yml index 2eb7d792cd..51d773280a 100644 --- a/roles/web-app-keycloak/tasks/03_manager_ops/update_routines.yml +++ b/roles/web-app-keycloak/tasks/03_manager_ops/update_routines.yml @@ -61,8 +61,6 @@ - name: "⏳ Reap the remaining Keycloak update jobs" ansible.builtin.include_tasks: utils/async/reap.yml vars: - async_reap_jobs: >- - {{ (kc_rbac_default.results | default([kc_rbac_default] if kc_rbac_default is defined else [])) - + (kc_declared_client_jobs | default([])) }} + async_reap_jobs: "{{ kc_declared_client_jobs | default([]) }}" async_reap_label: "Keycloak realm updates" async_reap_tolerate: [] diff --git a/roles/web-app-keycloak/tasks/update/02_mail_realm.yml b/roles/web-app-keycloak/tasks/update/02_mail_realm.yml index f5484e1888..073fa710df 100644 --- a/roles/web-app-keycloak/tasks/update/02_mail_realm.yml +++ b/roles/web-app-keycloak/tasks/update/02_mail_realm.yml @@ -10,6 +10,3 @@ kcadm_exec: "{{ KEYCLOAK_EXEC_KCADM }}" assert_mode: "{{ MODE_ASSERT }}" no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - # rationale: async; smtpServer is written here and never read back anywhere - async: "{{ ASYNC_TIME if ASYNC_ENABLED | bool else omit }}" - poll: "{{ ASYNC_POLL if ASYNC_ENABLED | bool else omit }}" diff --git a/roles/web-app-keycloak/tasks/update/03_mail_master.yml b/roles/web-app-keycloak/tasks/update/03_mail_master.yml index 71d80a3d89..7340996078 100644 --- a/roles/web-app-keycloak/tasks/update/03_mail_master.yml +++ b/roles/web-app-keycloak/tasks/update/03_mail_master.yml @@ -10,6 +10,3 @@ kcadm_exec: "{{ KEYCLOAK_EXEC_KCADM }}" assert_mode: "{{ MODE_ASSERT }}" no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - # rationale: async; writes the master realm smtpServer, which nothing reads back - async: "{{ ASYNC_TIME if ASYNC_ENABLED | bool else omit }}" - poll: "{{ ASYNC_POLL if ASYNC_ENABLED | bool else omit }}" diff --git a/roles/web-app-keycloak/tasks/update/04_rbac_client_scope.yml b/roles/web-app-keycloak/tasks/update/04_rbac_client_scope.yml index a849f9fb31..9d6ee571b9 100644 --- a/roles/web-app-keycloak/tasks/update/04_rbac_client_scope.yml +++ b/roles/web-app-keycloak/tasks/update/04_rbac_client_scope.yml @@ -92,8 +92,4 @@ {{ KEYCLOAK_EXEC_KCADM }} update clients/{{ app_client_id }}/default-client-scopes/{{ scope_id_rbac }} -r {{ KEYCLOAK_REALM }} - register: kc_rbac_default changed_when: true - # rationale: async; no task in the chain reads the scope back, reaped at the end of update_routines.yml - async: "{{ ASYNC_TIME if ASYNC_ENABLED | bool else omit }}" - poll: "{{ ASYNC_POLL if ASYNC_ENABLED | bool else omit }}" diff --git a/tests/unit/python/roles/web-app-keycloak/test_async_kcadm_jobs.py b/tests/unit/python/roles/web-app-keycloak/test_async_kcadm_jobs.py new file mode 100644 index 0000000000..f953e61abb --- /dev/null +++ b/tests/unit/python/roles/web-app-keycloak/test_async_kcadm_jobs.py @@ -0,0 +1,57 @@ +from __future__ import annotations + +import unittest + +from utils.cache.files import PROJECT_ROOT, iter_project_files +from utils.cache.yaml import load_yaml_any + +TASKS_DIR = str(PROJECT_ROOT / "roles/web-app-keycloak/tasks") + "/" +LOCK_RETRYING_MODULE = "keycloak_kcadm_update" + + +def tasks_of(node): + for task in node or []: + if not isinstance(task, dict): + continue + yield task + for nested in ("block", "rescue", "always"): + yield from tasks_of(task.get(nested)) + + +def async_kcadm_jobs(): + for path in iter_project_files(extensions=(".yml",)): + if not path.startswith(TASKS_DIR): + continue + for task in tasks_of(load_yaml_any(path)): + if "async" in task and "kcadm" in str(task).lower(): + yield f"{path[len(TASKS_DIR) :]}: {task.get('name')}", task + + +class TestAsyncKcadmJobs(unittest.TestCase): + def test_the_role_runs_kcadm_jobs_async(self): + self.assertTrue(list(async_kcadm_jobs())) + + def test_every_async_kcadm_job_goes_through_the_lock_retrying_module(self): + for label, task in async_kcadm_jobs(): + with self.subTest(task=label): + self.assertIn( + LOCK_RETRYING_MODULE, + task, + "kcadm gives up its config lock to a concurrent kcadm at once; " + "only keycloak_kcadm_update repeats such a call, so no other " + "kcadm task may run async", + ) + + def test_every_async_kcadm_job_is_registered_for_the_reap(self): + for label, task in async_kcadm_jobs(): + with self.subTest(task=label): + self.assertIn( + "register", + task, + "an async job without a register cannot be reaped, so nobody " + "sees it fail", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web_app_keycloak/test_library_keycloak_kcadm_update.py b/tests/unit/python/roles/web_app_keycloak/test_library_keycloak_kcadm_update.py index f1e9195b3a..920e3bfc44 100644 --- a/tests/unit/python/roles/web_app_keycloak/test_library_keycloak_kcadm_update.py +++ b/tests/unit/python/roles/web_app_keycloak/test_library_keycloak_kcadm_update.py @@ -15,6 +15,10 @@ if TYPE_CHECKING: ROLE_DIR = PROJECT_ROOT / "roles" / "web-app-keycloak" LIB_PATH = PROJECT_ROOT / "library" / "keycloak_kcadm_update.py" MODUTILS_PATH = PROJECT_ROOT / "utils" / "kcadm_json.py" +LOCK_ERROR = ( + "Failed to refresh access token - " + "Failed to get lock on /opt/keycloak/.keycloak/kcadm.config" +) def _load_py_module(name: str, path: Path): @@ -214,6 +218,46 @@ class TestKeycloakKcadmUpdate(unittest.TestCase): self.assertEqual(rc, 1) self.assertEqual(len(calls), 1) + def test_run_kcadm_repeats_a_call_that_lost_the_config_lock(self): + m = self.mod + outcomes = [ + DummyCompleted(1, "", LOCK_ERROR), + DummyCompleted(1, "", LOCK_ERROR), + DummyCompleted(0, "[]", ""), + ] + calls = [] + + def fake_run(cmd, **kwargs): + calls.append(cmd) + return outcomes[len(calls) - 1] + + with ( + patch.object(m.subprocess, "run", side_effect=fake_run), + patch.object(m.time, "sleep", return_value=None) as sleep, + ): + rc, out, _err = m.run_kcadm(DummyModule(), "kcadm get clients") + + self.assertEqual((rc, out), (0, "[]")) + self.assertEqual(calls, ["kcadm get clients"] * 3) + self.assertEqual(sleep.call_count, 2) + + def test_run_kcadm_gives_up_on_a_config_lock_that_never_frees(self): + m = self.mod + calls = [] + + def fake_run(cmd, **kwargs): + calls.append(cmd) + return DummyCompleted(1, "", LOCK_ERROR) + + with ( + patch.object(m.subprocess, "run", side_effect=fake_run), + patch.object(m.time, "sleep", return_value=None), + self.assertRaises(m.subprocess.CalledProcessError), + ): + m.run_kcadm(DummyModule(), "kcadm get clients") + + self.assertEqual(len(calls), m.CONFIG_LOCK_MAX_RETRIES + 1) + def test_get_current_object_parses_noisy(self): m = self.mod dummy = DummyModule() From 3610e7b9ef8cabdb1b28aa6099988ba147f13790 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 5 Oct 2026 22:27:22 +0200 Subject: [PATCH 15/53] fix(code-scanning): resolve the alerts that describe real code Of the 76 open code scanning alerts, 39 point at code that can change. svc-ai-mcp-adapter: - A path argument that is empty or made only of dots is refused. Percent-encoding keeps a separator inside its segment, but "." and ".." need none, so an upstream that resolves dot segments could answer from a path the contract does not name. - parse_duration splits on the units. The pattern it used before rescanned a long run of digits from every start position. Tests and the README generators: - Every Jinja environment built with autoescape=False and a "noqa: S701" uses select_autoescape now, as six test modules and utils/templating/jinja.py already did. It escapes templates named *.html, *.htm and *.xml, which none of these call sites loads. - Dead code goes: a doubled "rel" block in the email lint, an unread _SKIP_DIRS, and a module that _resolve returned to no caller. - Two "except ...: pass" blocks become contextlib.suppress and assertRaises. - Nine test modules import unittest.mock one way instead of two, and one lookup test imports its module once. Closes #807 Co-Authored-By: Claude Opus 5.5 (1M context) --- cli/build/docs/readme/generate.py | 3 +- cli/build/docs/readme/schema.py | 3 +- roles/svc-ai-mcp-adapter/README.md | 1 + .../svc-ai-mcp-adapter/files/python/policy.py | 23 ++++++++++-- .../test-e2e-cli/files/shared/mcp/contract.py | 30 +++++++-------- .../test_ssh_wrapper_rsync_e2e.py | 7 +++- .../svc-net-tor/test_container_dns_wiring.py | 8 ++-- .../jinja/test_shell_templates_are_valid.py | 2 +- .../roles/meta/test_role_subnet_pool.py | 4 +- .../roles/meta/test_sso_access_token_optin.py | 1 - .../roles/web-app/integration/test_email.py | 6 --- .../plugins/filter/test_dotenv_quote.py | 4 +- .../plugins/lookup/test_alert_rule_roles.py | 3 +- .../lookup/test_compose_volumes_realign.py | 4 +- .../plugins/lookup/test_mcp_client_bearer.py | 5 +-- .../plugins/lookup/test_mcp_credential.py | 5 +-- .../plugins/lookup/test_redirect_uris.py | 2 +- .../roles/agents/test_mcp_tool_filter.py | 6 ++- .../agents/test_openclaw_model_provider.py | 6 ++- .../templates/test_config_model_list.py | 7 +++- .../svc-ai-mcp-adapter/files/test_policy.py | 37 +++++++++++++++++++ .../roles/svc-net-firewall/test_fragments.py | 2 +- .../files/test_tor_smtp_gateway.py | 2 +- .../roles/svc-net-tor/test_egress_clients.py | 6 ++- .../roles/svc-net-tor/test_extra_ports.py | 2 +- .../test_msmtprc_ca_trust.py | 4 +- .../templates/test_mcp_edge_limits.py | 4 +- .../templates/test_mcp_vhost_exposure.py | 4 +- .../test_readiness_until.py | 8 ++-- .../web-app-gitlab/test_smtp_settings.py | 4 +- .../templates/test_realm_import_json.py | 4 +- .../test_credential_rotation.py | 4 +- .../files/test_provision_mcp_grants.py | 13 +++---- .../files/test_production_facts.py | 2 +- .../web-app-stalwart/test_onion_route.py | 4 +- .../test_roundcube_oauth_scheme.py | 4 +- tests/unit/python/utils/roles/test_guide.py | 2 +- .../tests/swarm/test_matrix_run_reporting.py | 2 +- 38 files changed, 151 insertions(+), 87 deletions(-) diff --git a/cli/build/docs/readme/generate.py b/cli/build/docs/readme/generate.py index 201362567f..40b6b7c780 100644 --- a/cli/build/docs/readme/generate.py +++ b/cli/build/docs/readme/generate.py @@ -44,9 +44,10 @@ def _is_invokable(role_name: str) -> bool: def _render_template(ctx: dict) -> str: - env = jinja2.Environment( # noqa: S701 — renders Markdown, not HTML; escaping would corrupt it + env = jinja2.Environment( loader=jinja2.FileSystemLoader(str(schema.TEMPLATE_DIR)), keep_trailing_newline=True, + autoescape=jinja2.select_autoescape(), ) return env.get_template(schema.TEMPLATE_NAME).render(**ctx) diff --git a/cli/build/docs/readme/schema.py b/cli/build/docs/readme/schema.py index dc66b8ea89..ca7a3b3c47 100644 --- a/cli/build/docs/readme/schema.py +++ b/cli/build/docs/readme/schema.py @@ -42,9 +42,10 @@ _OPTIONAL_CTX: dict = { def _render(ctx: dict) -> str: - env = jinja2.Environment( # noqa: S701 — renders Markdown, not HTML; escaping would corrupt it + env = jinja2.Environment( loader=jinja2.FileSystemLoader(str(TEMPLATE_DIR)), keep_trailing_newline=True, + autoescape=jinja2.select_autoescape(), ) return env.get_template(TEMPLATE_NAME).render(**ctx) diff --git a/roles/svc-ai-mcp-adapter/README.md b/roles/svc-ai-mcp-adapter/README.md index cfd9b2bf62..2d0d4d4bc3 100644 --- a/roles/svc-ai-mcp-adapter/README.md +++ b/roles/svc-ai-mcp-adapter/README.md @@ -26,6 +26,7 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( - **Client-facing authentication:** The adapter issues its own bearer. The upstream credential authenticates the adapter to the provider and says nothing about who called the adapter, which is the gap the project-owned MCP sidecars leave open. - **Allowlist on `tools/call`:** Filtering only `tools/list` would leave every unlisted operation callable by name. - **Read-only by default:** A non-`GET`/`HEAD` operation is refused unless `mutating_tools_enabled` is explicitly true. +- **Path arguments stay in their segment:** A value that fills a `{placeholder}` of the contracted path is percent-encoded, and an empty value or one made only of dots is refused, so a call cannot resolve to a path the contract does not name. - **Enforced ceilings:** Request size, response size, timeout, concurrency, page size and result count come from the contract and are applied, not merely declared. - **Bounded ranges:** A tool whose schema declares `start`, `end` and `step` has its point count checked against `result_items` and is refused with the smallest step that fits, so the upstream never scans a range whose result the adapter would discard. - **Fail-closed on drift:** A tool contract whose hash no longer matches its pinned `schema_sha256` refuses to start. diff --git a/roles/svc-ai-mcp-adapter/files/python/policy.py b/roles/svc-ai-mcp-adapter/files/python/policy.py index fc4ed18be2..b527da2b6c 100644 --- a/roles/svc-ai-mcp-adapter/files/python/policy.py +++ b/roles/svc-ai-mcp-adapter/files/python/policy.py @@ -47,6 +47,7 @@ DENY_TOO_MANY_REQUESTS = "too_many_concurrent_requests" DENY_UNKNOWN_ARGUMENT = "undeclared_argument" DENY_MISSING_ARGUMENT = "missing_required_argument" DENY_RANGE_TOO_WIDE = "range_too_wide" +DENY_PATH_ARGUMENT = "path_argument_not_a_segment" RANGE_ARGUMENTS = ("start", "end", "step") @@ -189,6 +190,17 @@ def assert_arguments( raise PermissionError(f"{DENY_MISSING_ARGUMENT}: {name!r} requires {missing}") +def assert_path_arguments( + spec: Mapping[str, Any], name: str, arguments: Mapping[str, Any] | None +) -> None: + path = str(spec["path"]) + for key, value in (arguments or {}).items(): + if "{" + key + "}" in path and not str(value).strip("."): + raise PermissionError( + f"{DENY_PATH_ARGUMENT}: {name!r} takes no {str(value)!r} as {key!r}" + ) + + def parse_instant(value: Any) -> float: """Return a range boundary in unix seconds. @@ -217,10 +229,14 @@ def parse_duration(value: Any) -> float: return float(text) except ValueError: pass - parts = re.findall(r"(\d+)(ms|[smhdwy])", text) - if not parts or "".join(n + u for n, u in parts) != text: + *tokens, rest = re.split(r"(ms|[smhdwy])", text) + numbers, units = tokens[::2], tokens[1::2] + if rest or not numbers or not all(number.isdecimal() for number in numbers): raise ValueError(f"not a duration: {text!r}") - return sum(int(n) * DURATION_UNITS[u] for n, u in parts) + return sum( + int(number) * DURATION_UNITS[unit] + for number, unit in zip(numbers, units, strict=True) + ) def assert_range( @@ -341,6 +357,7 @@ def authorize_call( ) assert_arguments(spec, name, arguments) + assert_path_arguments(spec, name, arguments) assert_range(spec, name, arguments, contract["limits"]["result_items"]) return method, str(spec["path"]) diff --git a/roles/test-e2e-cli/files/shared/mcp/contract.py b/roles/test-e2e-cli/files/shared/mcp/contract.py index 4af0b34781..1458b04248 100644 --- a/roles/test-e2e-cli/files/shared/mcp/contract.py +++ b/roles/test-e2e-cli/files/shared/mcp/contract.py @@ -45,6 +45,7 @@ Environment: from __future__ import annotations +import contextlib import json import os import queue @@ -320,21 +321,20 @@ class SseSession: self.content_type = self._response.headers.get("Content-Type", "") event = None try: - for raw in self._response: - line = raw.decode(errors="replace").rstrip("\r\n") - if line.startswith("event:"): - event = line.split(":", 1)[1].strip() - elif line.startswith("data:"): - data = line.split(":", 1)[1].strip() - if event == "endpoint": - self.endpoint = urllib.parse.urljoin(self.url, data) - self._announced.set() - else: - self._messages.put(data) - elif not line: - event = None - except (OSError, ValueError): - pass + with contextlib.suppress(OSError, ValueError): + for raw in self._response: + line = raw.decode(errors="replace").rstrip("\r\n") + if line.startswith("event:"): + event = line.split(":", 1)[1].strip() + elif line.startswith("data:"): + data = line.split(":", 1)[1].strip() + if event == "endpoint": + self.endpoint = urllib.parse.urljoin(self.url, data) + self._announced.set() + else: + self._messages.put(data) + elif not line: + event = None finally: self._announced.set() diff --git a/tests/integration/roles/svc-bkp-remote-2-local/test_ssh_wrapper_rsync_e2e.py b/tests/integration/roles/svc-bkp-remote-2-local/test_ssh_wrapper_rsync_e2e.py index f7269a5a3c..e97744353b 100644 --- a/tests/integration/roles/svc-bkp-remote-2-local/test_ssh_wrapper_rsync_e2e.py +++ b/tests/integration/roles/svc-bkp-remote-2-local/test_ssh_wrapper_rsync_e2e.py @@ -22,7 +22,7 @@ import tempfile import unittest from pathlib import Path -from jinja2 import Template +from jinja2 import Template, select_autoescape from utils.cache.files import read_text @@ -62,7 +62,10 @@ class TestSshWrapperRsyncE2E(unittest.TestCase): (self.version_dir / "data" / "file2.txt").write_text("second") self.wrapper = self.work / "wrapper.sh" - rendered = Template(read_text(str(WRAPPER_TEMPLATE))).render( + rendered = Template( + read_text(str(WRAPPER_TEMPLATE)), + autoescape=select_autoescape(default_for_string=False), + ).render( DIR_BACKUPS=str(self.backups), BACKUP_REPOSITORIES=[BACKUP_TYPE], ) diff --git a/tests/integration/roles/svc-net-tor/test_container_dns_wiring.py b/tests/integration/roles/svc-net-tor/test_container_dns_wiring.py index 4ed72e9dd0..e69326de26 100644 --- a/tests/integration/roles/svc-net-tor/test_container_dns_wiring.py +++ b/tests/integration/roles/svc-net-tor/test_container_dns_wiring.py @@ -1,7 +1,7 @@ import unittest from ansible.module_utils.parsing.convert_bool import boolean as ansible_boolean -from jinja2 import Environment, FileSystemLoader +from jinja2 import Environment, FileSystemLoader, select_autoescape from tests.integration.roles import PROJECT_ROOT from utils.cache.files import read_text @@ -37,7 +37,7 @@ def _render_dnsmasq(**overrides): variables.update(overrides) env = Environment( loader=FileSystemLoader(str(PROJECT_ROOT)), - autoescape=False, # noqa: S701 - dnsmasq config, html escaping would corrupt it + autoescape=select_autoescape(), ) template = env.get_template("roles/svc-net-tor/templates/dnsmasq-tor-onion.conf.j2") return template.render(**variables) @@ -146,7 +146,7 @@ class TestStaticBindSurvivesBoot(unittest.TestCase): self.assertLess(names.index(DROPIN_BLOCK), names.index(START_TASK)) reload_expression = start["ansible.builtin.systemd"]["daemon_reload"] - env = Environment(autoescape=False) # noqa: S701 - renders a boolean, not markup + env = Environment(autoescape=select_autoescape(default_for_string=False)) env.filters["bool"] = ansible_boolean env.tests["changed"] = lambda result: bool(result.get("changed", False)) @@ -192,7 +192,7 @@ class TestHostResolver(unittest.TestCase): task = next(t for t in tasks if t.get("name") == RESOLV_TASK) env = Environment( loader=FileSystemLoader(str(PROJECT_ROOT)), - autoescape=False, # noqa: S701 - resolv.conf, html escaping would corrupt it + autoescape=select_autoescape(), ) template = env.get_template( f"roles/svc-net-tor/templates/{task['ansible.builtin.template']['src']}" diff --git a/tests/lint/ansible/jinja/test_shell_templates_are_valid.py b/tests/lint/ansible/jinja/test_shell_templates_are_valid.py index 921e159c9e..be0ac4d734 100644 --- a/tests/lint/ansible/jinja/test_shell_templates_are_valid.py +++ b/tests/lint/ansible/jinja/test_shell_templates_are_valid.py @@ -100,7 +100,7 @@ class TestShellTemplatesAreValid(unittest.TestCase): environment = jinja2.Environment( undefined=_Placeholder, keep_trailing_newline=True, - autoescape=False, # noqa: S701 shell, not markup + autoescape=jinja2.select_autoescape(default_for_string=False), ) environment.filters = _PassthroughFilters(environment.filters) environment.filters["quote"] = shlex.quote diff --git a/tests/lint/ansible/roles/meta/test_role_subnet_pool.py b/tests/lint/ansible/roles/meta/test_role_subnet_pool.py index b18f584947..d45f12251f 100644 --- a/tests/lint/ansible/roles/meta/test_role_subnet_pool.py +++ b/tests/lint/ansible/roles/meta/test_role_subnet_pool.py @@ -37,7 +37,9 @@ def _declared_space() -> tuple[list[ipaddress.IPv4Network], list[str]]: data = load_yaml_any(str(NETWORKS_FILE), default_if_missing={}) or {} pool = data.get("NETWORK_ROLE_SUBNET_POOL") if isinstance(pool, str) and "{{" in pool: - pool = jinja2.Template(pool).render(**data) + pool = jinja2.Template( + pool, autoescape=jinja2.select_autoescape(default_for_string=False) + ).render(**data) roles = data.get("NETWORK_ROLE_SUBNET_EXCEPTION_ROLES") or [] if not isinstance(pool, str) or not isinstance(roles, list): raise TypeError( diff --git a/tests/lint/ansible/roles/meta/test_sso_access_token_optin.py b/tests/lint/ansible/roles/meta/test_sso_access_token_optin.py index 4ad33f9029..f2778df020 100644 --- a/tests/lint/ansible/roles/meta/test_sso_access_token_optin.py +++ b/tests/lint/ansible/roles/meta/test_sso_access_token_optin.py @@ -45,7 +45,6 @@ GATE = PROJECT_ROOT / ( ) _HEADER_RE = re.compile(r"x[-_]forwarded[-_]access[-_]token", re.IGNORECASE) _EMITS_RE = re.compile(r"proxy_set_header|auth_request_set") -_SKIP_DIRS = {".git", "node_modules", "__pycache__"} _TEXT_SUFFIXES = { ".js", ".mjs", diff --git a/tests/lint/ansible/roles/web-app/integration/test_email.py b/tests/lint/ansible/roles/web-app/integration/test_email.py index c5d3e7e2c1..7197c8451b 100644 --- a/tests/lint/ansible/roles/web-app/integration/test_email.py +++ b/tests/lint/ansible/roles/web-app/integration/test_email.py @@ -168,12 +168,6 @@ class TestWebAppRolesIntegrateEmail(unittest.TestCase): missing.append("enabled: true") if not is_explicit_truth(svc.get("shared")): missing.append("shared: true") - if missing: - rel = ( - config.relative_to(root).as_posix() - if config.is_file() - else role_path.relative_to(root).as_posix() - ) if not _role_pins_the_mail_relay(role_path): errors.append( f"[{role_path.name}]: calls lookup('email', ...) but no " diff --git a/tests/unit/python/plugins/filter/test_dotenv_quote.py b/tests/unit/python/plugins/filter/test_dotenv_quote.py index 9d61bddbdd..f05d3e37da 100644 --- a/tests/unit/python/plugins/filter/test_dotenv_quote.py +++ b/tests/unit/python/plugins/filter/test_dotenv_quote.py @@ -68,7 +68,9 @@ class TestDotenvQuoteModeAware(unittest.TestCase): """ def setUp(self): - env = jinja2.Environment(autoescape=False) # noqa: S701 - test renders a .env value, not HTML + env = jinja2.Environment( + autoescape=jinja2.select_autoescape(default_for_string=False) + ) env.filters["dotenv_quote"] = FilterModule().filters()["dotenv_quote"] self.env = env diff --git a/tests/unit/python/plugins/lookup/test_alert_rule_roles.py b/tests/unit/python/plugins/lookup/test_alert_rule_roles.py index 09953d117e..92cf702dbb 100644 --- a/tests/unit/python/plugins/lookup/test_alert_rule_roles.py +++ b/tests/unit/python/plugins/lookup/test_alert_rule_roles.py @@ -17,7 +17,6 @@ import unittest.mock as mock from pathlib import Path import plugins.lookup.alert_rule_roles as module -from plugins.lookup.alert_rule_roles import LookupModule class _Templar: @@ -29,7 +28,7 @@ class _Templar: def _make_lookup(vars_=None): - lm = LookupModule() + lm = module.LookupModule() lm._templar = _Templar(vars_ or {}) lm._loader = mock.MagicMock() return lm diff --git a/tests/unit/python/plugins/lookup/test_compose_volumes_realign.py b/tests/unit/python/plugins/lookup/test_compose_volumes_realign.py index 4cb4765aca..28a633ccec 100644 --- a/tests/unit/python/plugins/lookup/test_compose_volumes_realign.py +++ b/tests/unit/python/plugins/lookup/test_compose_volumes_realign.py @@ -40,7 +40,9 @@ def _render(**answers) -> str: def _lookup(_plugin, _app, key): return values[key] - env = jinja2.Environment(autoescape=False) # noqa: S701 - renders SQL, HTML escaping would corrupt the literals + env = jinja2.Environment( + autoescape=jinja2.select_autoescape(default_for_string=False) + ) return env.from_string(read_text(str(_TEMPLATE))).render( lookup=_lookup, application_id="web-app-x" ) diff --git a/tests/unit/python/plugins/lookup/test_mcp_client_bearer.py b/tests/unit/python/plugins/lookup/test_mcp_client_bearer.py index cfbc4d0e3a..72afc969bf 100644 --- a/tests/unit/python/plugins/lookup/test_mcp_client_bearer.py +++ b/tests/unit/python/plugins/lookup/test_mcp_client_bearer.py @@ -10,8 +10,7 @@ from __future__ import annotations import importlib.util import unittest -from unittest import mock -from unittest.mock import patch +from unittest.mock import MagicMock, patch from ansible.errors import AnsibleError @@ -40,7 +39,7 @@ class TestMcpClientBearerLookup(unittest.TestCase): def _run(self, terms, credential, role_credentials=None, users=None): lookup = self.mod.LookupModule() lookup._templar = _DummyTemplar() - lookup._loader = mock.MagicMock() + lookup._loader = MagicMock() class _StubConfig: def run(self, terms_, variables=None, **kwargs): diff --git a/tests/unit/python/plugins/lookup/test_mcp_credential.py b/tests/unit/python/plugins/lookup/test_mcp_credential.py index fc67f6fb62..4c1b83d4b3 100644 --- a/tests/unit/python/plugins/lookup/test_mcp_credential.py +++ b/tests/unit/python/plugins/lookup/test_mcp_credential.py @@ -9,8 +9,7 @@ from __future__ import annotations import importlib.util import unittest -from unittest import mock -from unittest.mock import patch +from unittest.mock import MagicMock, patch from ansible.errors import AnsibleError @@ -39,7 +38,7 @@ class TestMcpCredentialLookup(unittest.TestCase): def _run(self, terms, owner="mcp-web-app-gitea", users=None): lookup = self.mod.LookupModule() lookup._templar = _DummyTemplar() - lookup._loader = mock.MagicMock() + lookup._loader = MagicMock() class _StubConfig: def run(self, terms_, variables=None, **kwargs): diff --git a/tests/unit/python/plugins/lookup/test_redirect_uris.py b/tests/unit/python/plugins/lookup/test_redirect_uris.py index 9a4772ea9a..ec7d98dc24 100644 --- a/tests/unit/python/plugins/lookup/test_redirect_uris.py +++ b/tests/unit/python/plugins/lookup/test_redirect_uris.py @@ -1,7 +1,7 @@ from __future__ import annotations import unittest -from unittest import mock +import unittest.mock as mock from ansible.errors import AnsibleError diff --git a/tests/unit/python/roles/agents/test_mcp_tool_filter.py b/tests/unit/python/roles/agents/test_mcp_tool_filter.py index d4d8fa0149..4a09f37952 100644 --- a/tests/unit/python/roles/agents/test_mcp_tool_filter.py +++ b/tests/unit/python/roles/agents/test_mcp_tool_filter.py @@ -20,7 +20,7 @@ import json import unittest import yaml -from jinja2 import Environment, FileSystemLoader +from jinja2 import Environment, FileSystemLoader, select_autoescape from . import PROJECT_ROOT @@ -82,7 +82,9 @@ def _yaml(text: str): def _render(directory, name, **context) -> str: - env = Environment(loader=FileSystemLoader(str(directory)), autoescape=False) # noqa: S701 - renders configuration, not markup + env = Environment( + loader=FileSystemLoader(str(directory)), autoescape=select_autoescape() + ) env.filters.update(_filters()) return env.get_template(name).render(**context) diff --git a/tests/unit/python/roles/agents/test_openclaw_model_provider.py b/tests/unit/python/roles/agents/test_openclaw_model_provider.py index d7939d8710..4ce39d8ee8 100644 --- a/tests/unit/python/roles/agents/test_openclaw_model_provider.py +++ b/tests/unit/python/roles/agents/test_openclaw_model_provider.py @@ -16,7 +16,7 @@ import importlib.util import json import unittest -from jinja2 import Environment, FileSystemLoader +from jinja2 import Environment, FileSystemLoader, select_autoescape from . import PROJECT_ROOT @@ -51,7 +51,9 @@ def _render(**overrides) -> dict: Args: overrides: context values replacing the defaults. """ - env = Environment(loader=FileSystemLoader(str(OPENCLAW)), autoescape=False) # noqa: S701 - renders configuration, not markup + env = Environment( + loader=FileSystemLoader(str(OPENCLAW)), autoescape=select_autoescape() + ) env.filters.update(_filters()) return json.loads( env.get_template("openclaw.json.j2").render(**{**CONTEXT, **overrides}) diff --git a/tests/unit/python/roles/svc-ai-litellm/templates/test_config_model_list.py b/tests/unit/python/roles/svc-ai-litellm/templates/test_config_model_list.py index e1728d0e72..3f21f05fe5 100644 --- a/tests/unit/python/roles/svc-ai-litellm/templates/test_config_model_list.py +++ b/tests/unit/python/roles/svc-ai-litellm/templates/test_config_model_list.py @@ -12,7 +12,7 @@ from __future__ import annotations import unittest import yaml -from jinja2 import Environment, StrictUndefined +from jinja2 import Environment, StrictUndefined, select_autoescape from utils.cache.files import read_text @@ -72,7 +72,10 @@ def render(*, ollama=(), lmstudio=(), keys=None): lmstudio: preload entries svc-ai-lmstudio declares; empty means not deployed. keys: env-name -> provider key for the remote backends. """ - env = Environment(undefined=StrictUndefined, autoescape=False) # noqa: S701 - YAML, not markup + env = Environment( + undefined=StrictUndefined, + autoescape=select_autoescape(default_for_string=False), + ) env.filters["bool"] = _ansible_bool rendered = env.from_string(read_text(str(TEMPLATE))).render( LITELLM_OLLAMA_BACKEND=str(bool(ollama)), diff --git a/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_policy.py b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_policy.py index 376ac03ab3..c04c092e7a 100644 --- a/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_policy.py +++ b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_policy.py @@ -4,6 +4,7 @@ from __future__ import annotations import importlib.util import json +import time import unittest from . import PROJECT_ROOT @@ -234,6 +235,26 @@ class TestDeclaredArguments(unittest.TestCase): self.assertEqual("GET", method) +class TestPathArguments(unittest.TestCase): + def call(self, **arguments): + return policy.authorize_call(contract(), "checkmk_get_host_status", arguments) + + def test_a_value_made_only_of_dots_is_refused(self): + for dots in range(4): + with self.subTest(dots=dots): + with self.assertRaises(PermissionError) as caught: + self.call(host="." * dots) + self.assertIn(policy.DENY_PATH_ARGUMENT, str(caught.exception)) + + def test_dots_inside_a_segment_pass(self): + for value in ("web-01.example", "..web", "web.."): + with self.subTest(value=value): + self.call(host=value) + + def test_a_query_argument_may_be_made_only_of_dots(self): + self.call(host="web-01", columns="." * 2) + + RANGE_TOOLS = { "prometheus_query_range": { "method": "GET", @@ -326,6 +347,22 @@ class TestDurationGrammar(unittest.TestCase): with self.assertRaises(ValueError): policy.parse_duration("1h30") + def test_anything_but_number_unit_pairs_is_refused(self): + for text in ("", "h", "1hh", "1.5h", "-1h", "1 h", "1sm", "abc"): + with self.subTest(text=text), self.assertRaises(ValueError): + policy.parse_duration(text) + + def test_a_long_digit_run_is_refused_in_linear_time(self): + started = time.monotonic() + with self.assertRaises(ValueError): + policy.parse_duration("0" * 20_000 + "!") + self.assertLess( + time.monotonic() - started, + 1.0, + "parsing must not rescan the digit run from every start position; " + "a backtracking pattern needs several seconds for this input", + ) + class TestAudit(unittest.TestCase): def test_the_event_names_both_sides_and_the_outcome(self): diff --git a/tests/unit/python/roles/svc-net-firewall/test_fragments.py b/tests/unit/python/roles/svc-net-firewall/test_fragments.py index 99152196b5..ecadb860ef 100644 --- a/tests/unit/python/roles/svc-net-firewall/test_fragments.py +++ b/tests/unit/python/roles/svc-net-firewall/test_fragments.py @@ -129,7 +129,7 @@ def _render(path: str, mode: str = "swarm") -> str: environment = jinja2.Environment( keep_trailing_newline=True, trim_blocks=True, - autoescape=False, # noqa: S701 nftables, not markup + autoescape=jinja2.select_autoescape(default_for_string=False), ) return environment.from_string(read_text(path)).render( DEPLOYMENT_MODE=mode, **COMMON diff --git a/tests/unit/python/roles/svc-net-tor-smtp/files/test_tor_smtp_gateway.py b/tests/unit/python/roles/svc-net-tor-smtp/files/test_tor_smtp_gateway.py index 67634ed302..a64c68528e 100644 --- a/tests/unit/python/roles/svc-net-tor-smtp/files/test_tor_smtp_gateway.py +++ b/tests/unit/python/roles/svc-net-tor-smtp/files/test_tor_smtp_gateway.py @@ -14,7 +14,7 @@ import os import sys import types import unittest -from unittest import mock +import unittest.mock as mock from . import PROJECT_ROOT diff --git a/tests/unit/python/roles/svc-net-tor/test_egress_clients.py b/tests/unit/python/roles/svc-net-tor/test_egress_clients.py index 52a558a9a9..7b04c193dd 100644 --- a/tests/unit/python/roles/svc-net-tor/test_egress_clients.py +++ b/tests/unit/python/roles/svc-net-tor/test_egress_clients.py @@ -16,7 +16,7 @@ from __future__ import annotations import importlib.util import sys import unittest -from unittest import mock +import unittest.mock as mock import jinja2 @@ -46,7 +46,9 @@ class _Templar: def template(self, value): return ( - jinja2.Environment(autoescape=False) # noqa: S701 - renders CIDRs, not markup + jinja2.Environment( + autoescape=jinja2.select_autoescape(default_for_string=False) + ) .from_string(str(value)) .render(**self.available_variables) ) diff --git a/tests/unit/python/roles/svc-net-tor/test_extra_ports.py b/tests/unit/python/roles/svc-net-tor/test_extra_ports.py index 4deb747de1..98528445a8 100644 --- a/tests/unit/python/roles/svc-net-tor/test_extra_ports.py +++ b/tests/unit/python/roles/svc-net-tor/test_extra_ports.py @@ -16,8 +16,8 @@ from __future__ import annotations import importlib.util import sys import unittest +import unittest.mock as mock from typing import Any -from unittest import mock from ansible.errors import AnsibleError diff --git a/tests/unit/python/roles/sys-svc-mail-msmtp/test_msmtprc_ca_trust.py b/tests/unit/python/roles/sys-svc-mail-msmtp/test_msmtprc_ca_trust.py index 3e7e435f11..43acfc794f 100644 --- a/tests/unit/python/roles/sys-svc-mail-msmtp/test_msmtprc_ca_trust.py +++ b/tests/unit/python/roles/sys-svc-mail-msmtp/test_msmtprc_ca_trust.py @@ -18,7 +18,7 @@ import re import unittest from typing import Any, ClassVar -from jinja2 import Environment, StrictUndefined +from jinja2 import Environment, StrictUndefined, select_autoescape from utils.cache.files import read_text @@ -46,7 +46,7 @@ def _env() -> Environment: trim_blocks=True, lstrip_blocks=True, undefined=StrictUndefined, - autoescape=False, # noqa: S701 - a config file, and Ansible's templar does not escape either + autoescape=select_autoescape(default_for_string=False), ) env.filters["bool"] = bool env.filters["on_off"] = lambda value: "on" if value else "off" diff --git a/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_edge_limits.py b/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_edge_limits.py index 8c6880baec..ee2610af0a 100644 --- a/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_edge_limits.py +++ b/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_edge_limits.py @@ -12,7 +12,7 @@ from __future__ import annotations import unittest -from jinja2 import Environment, FileSystemLoader, StrictUndefined +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape from utils.cache.applications import get_application_defaults from utils.cache.yaml import load_yaml @@ -44,7 +44,7 @@ def render(name: str, **context) -> str: env = Environment( loader=FileSystemLoader(str(TEMPLATE_DIR)), undefined=StrictUndefined, - autoescape=False, # noqa: S701 - nginx config, not markup; Ansible renders it the same way and HTML-escaping `$binary_remote_addr` would break it + autoescape=select_autoescape(), ) return env.get_template(name).render(**context) diff --git a/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_vhost_exposure.py b/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_vhost_exposure.py index cc2eaea1c3..7d2a7611e6 100644 --- a/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_vhost_exposure.py +++ b/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_vhost_exposure.py @@ -22,7 +22,7 @@ from __future__ import annotations import re import unittest -from jinja2 import Environment, FileSystemLoader, StrictUndefined +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape from utils.cache.yaml import load_yaml from utils.roles.mapping import ROLE_FILE_META_MCP @@ -80,7 +80,7 @@ def render(role: str, *, exposure: str, sso_gated: bool = False) -> str: env = Environment( loader=FileSystemLoader(str(TEMPLATE_DIR)), undefined=StrictUndefined, - autoescape=False, # noqa: S701 - nginx config, not markup; HTML-escaping would corrupt the directives + autoescape=select_autoescape(), ) env.filters["regex_replace"] = lambda value, pattern, repl="": re.sub( pattern, repl, value diff --git a/tests/unit/python/roles/test-e2e-playwright/test_readiness_until.py b/tests/unit/python/roles/test-e2e-playwright/test_readiness_until.py index 4fb7076704..d924d3c71b 100644 --- a/tests/unit/python/roles/test-e2e-playwright/test_readiness_until.py +++ b/tests/unit/python/roles/test-e2e-playwright/test_readiness_until.py @@ -2,7 +2,7 @@ from __future__ import annotations import unittest -from jinja2 import Environment +from jinja2 import Environment, select_autoescape from utils.cache.yaml import load_yaml_any @@ -21,9 +21,9 @@ def until_expression() -> str: def settles(result: dict) -> bool: - template = Environment(autoescape=False).from_string( # noqa: S701 - ansible condition, not markup - "{{ " + until_expression() + " }}" - ) + template = Environment( + autoescape=select_autoescape(default_for_string=False) + ).from_string("{{ " + until_expression() + " }}") return template.render(_wait_result=result) == "True" diff --git a/tests/unit/python/roles/web-app-gitlab/test_smtp_settings.py b/tests/unit/python/roles/web-app-gitlab/test_smtp_settings.py index 4198036cc3..ac76ffb055 100644 --- a/tests/unit/python/roles/web-app-gitlab/test_smtp_settings.py +++ b/tests/unit/python/roles/web-app-gitlab/test_smtp_settings.py @@ -17,7 +17,7 @@ from __future__ import annotations import re import unittest -from jinja2 import Environment, StrictUndefined +from jinja2 import Environment, StrictUndefined, select_autoescape from utils.cache.files import read_text @@ -50,7 +50,7 @@ def _render(email: dict, ca_file: str = "") -> str: trim_blocks=True, lstrip_blocks=True, undefined=StrictUndefined, - autoescape=False, # noqa: S701 - a Ruby config file, and Ansible's templar does not escape either + autoescape=select_autoescape(default_for_string=False), ) env.filters["bool"] = bool env.filters["ruby_dq"] = lambda value: '"' + str(value).replace('"', '\\"') + '"' diff --git a/tests/unit/python/roles/web-app-keycloak/templates/test_realm_import_json.py b/tests/unit/python/roles/web-app-keycloak/templates/test_realm_import_json.py index 008a48bd8f..249189de47 100644 --- a/tests/unit/python/roles/web-app-keycloak/templates/test_realm_import_json.py +++ b/tests/unit/python/roles/web-app-keycloak/templates/test_realm_import_json.py @@ -5,7 +5,7 @@ import json import re import unittest -from jinja2 import Environment, FileSystemLoader, StrictUndefined +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape from . import PROJECT_ROOT @@ -102,7 +102,7 @@ def render(saml_apps: list[str], client_apps: list[str] | None = None) -> str: trim_blocks=True, keep_trailing_newline=True, undefined=StrictUndefined, - autoescape=False, # noqa: S701 - renders JSON, where HTML escaping corrupts the value + autoescape=select_autoescape(), ) env.filters["path_join"] = path_join env.filters["to_json"] = json.dumps diff --git a/tests/unit/python/roles/web-app-openbao/test_credential_rotation.py b/tests/unit/python/roles/web-app-openbao/test_credential_rotation.py index 4beccfb7b3..582607a82d 100644 --- a/tests/unit/python/roles/web-app-openbao/test_credential_rotation.py +++ b/tests/unit/python/roles/web-app-openbao/test_credential_rotation.py @@ -12,7 +12,7 @@ from __future__ import annotations import unittest -from jinja2 import Environment, FileSystemLoader, StrictUndefined +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape from utils.cache.files import read_text from utils.cache.yaml import load_yaml_any @@ -44,7 +44,7 @@ def jinja_env(searchpath) -> Environment: env = Environment( loader=FileSystemLoader(str(searchpath)), undefined=StrictUndefined, - autoescape=False, # noqa: S701 - renders HCL and dotenv, not markup + autoescape=select_autoescape(default_for_string=False), ) env.filters["bool"] = bool env.filters["dotenv_quote"] = lambda value: f'"{value}"' diff --git a/tests/unit/python/roles/web-app-openwebui/files/test_provision_mcp_grants.py b/tests/unit/python/roles/web-app-openwebui/files/test_provision_mcp_grants.py index 65304f0539..97205be309 100644 --- a/tests/unit/python/roles/web-app-openwebui/files/test_provision_mcp_grants.py +++ b/tests/unit/python/roles/web-app-openwebui/files/test_provision_mcp_grants.py @@ -465,7 +465,7 @@ class TestResolveApiKey(unittest.TestCase): modules = {} backend.install(modules) with patch.dict("sys.modules", modules): - return module, asyncio.run(module.resolve_api_key()) + return asyncio.run(module.resolve_api_key()) def test_an_existing_administrator_key_is_reused_and_kept(self) -> None: backend = FakeBackend( @@ -473,7 +473,7 @@ class TestResolveApiKey(unittest.TestCase): keys={"admin1": "sk-operator"}, ) - _module, (user_id, key, minted) = self._resolve(backend) + user_id, key, minted = self._resolve(backend) self.assertEqual("admin1", user_id) self.assertEqual("sk-operator", key) @@ -483,7 +483,7 @@ class TestResolveApiKey(unittest.TestCase): def test_a_missing_key_is_minted_and_marked_for_removal(self) -> None: backend = FakeBackend([FakeUser("admin1", "admin")]) - _module, (user_id, key, minted) = self._resolve(backend) + user_id, key, minted = self._resolve(backend) self.assertEqual("admin1", user_id) self.assertTrue(key.startswith("sk-")) @@ -493,7 +493,7 @@ class TestResolveApiKey(unittest.TestCase): def test_an_instance_without_users_gets_one_administrator(self) -> None: backend = FakeBackend([]) - _module, (user_id, _key, minted) = self._resolve(backend) + user_id, _key, minted = self._resolve(backend) self.assertEqual(["admin"], [user.role for user in backend.created]) self.assertEqual(backend.created[0].id, user_id) @@ -512,9 +512,8 @@ class TestResolveApiKey(unittest.TestCase): admin_id, _key, minted = asyncio.run(module.resolve_api_key()) self.assertTrue(minted) try: - exploding_grant(_key) - except RuntimeError: - pass + with self.assertRaises(RuntimeError): + exploding_grant(_key) finally: asyncio.run(module.drop_api_key(admin_id)) diff --git a/tests/unit/python/roles/web-app-stalwart/files/test_production_facts.py b/tests/unit/python/roles/web-app-stalwart/files/test_production_facts.py index 3c57b00f2e..1ef49c2119 100644 --- a/tests/unit/python/roles/web-app-stalwart/files/test_production_facts.py +++ b/tests/unit/python/roles/web-app-stalwart/files/test_production_facts.py @@ -5,8 +5,8 @@ import struct import sys import tempfile import unittest +import unittest.mock as mock from pathlib import Path -from unittest import mock from . import PROJECT_ROOT diff --git a/tests/unit/python/roles/web-app-stalwart/test_onion_route.py b/tests/unit/python/roles/web-app-stalwart/test_onion_route.py index cf6ad49854..296133e61b 100644 --- a/tests/unit/python/roles/web-app-stalwart/test_onion_route.py +++ b/tests/unit/python/roles/web-app-stalwart/test_onion_route.py @@ -12,7 +12,7 @@ from __future__ import annotations import json import unittest -from jinja2 import Environment, StrictUndefined +from jinja2 import Environment, StrictUndefined, select_autoescape from utils.cache.files import read_text from utils.cache.yaml import load_yaml_any @@ -34,7 +34,7 @@ def _render(template_path, **variables) -> str: trim_blocks=True, lstrip_blocks=True, undefined=StrictUndefined, - autoescape=False, # noqa: S701 - JMAP request bodies, never HTML + autoescape=select_autoescape(default_for_string=False), ) env.filters["to_json"] = json.dumps env.filters["int"] = int diff --git a/tests/unit/python/roles/web-app-stalwart/test_roundcube_oauth_scheme.py b/tests/unit/python/roles/web-app-stalwart/test_roundcube_oauth_scheme.py index 164ce94b0c..8261829975 100644 --- a/tests/unit/python/roles/web-app-stalwart/test_roundcube_oauth_scheme.py +++ b/tests/unit/python/roles/web-app-stalwart/test_roundcube_oauth_scheme.py @@ -16,7 +16,7 @@ from __future__ import annotations import unittest -from jinja2 import Environment, StrictUndefined +from jinja2 import Environment, StrictUndefined, select_autoescape from utils.cache.files import read_text @@ -41,7 +41,7 @@ def _render(base_url: str, *, sso_enabled: bool = True, socks_proxy: str = "") - trim_blocks=True, lstrip_blocks=True, undefined=StrictUndefined, - autoescape=False, # noqa: S701 - a PHP config file, and Ansible's templar does not escape either + autoescape=select_autoescape(default_for_string=False), ) env.filters["bool"] = bool return env.from_string(read_text(TEMPLATE)).render( diff --git a/tests/unit/python/utils/roles/test_guide.py b/tests/unit/python/utils/roles/test_guide.py index 49c3bcf1de..387edc71fd 100644 --- a/tests/unit/python/utils/roles/test_guide.py +++ b/tests/unit/python/utils/roles/test_guide.py @@ -1,6 +1,6 @@ import unittest +import unittest.mock as mock from typing import ClassVar -from unittest import mock from utils.cache.applications import get_variants from utils.roles.guide import guide_deployable, guide_variant, smallest_variant diff --git a/tests/unit/python/utils/tests/swarm/test_matrix_run_reporting.py b/tests/unit/python/utils/tests/swarm/test_matrix_run_reporting.py index 4f27992dcb..b0773bf61e 100644 --- a/tests/unit/python/utils/tests/swarm/test_matrix_run_reporting.py +++ b/tests/unit/python/utils/tests/swarm/test_matrix_run_reporting.py @@ -1,7 +1,7 @@ import contextlib import io import unittest -from unittest import mock +import unittest.mock as mock from utils.tests.swarm import matrix From 8dce5b3caa3c1fd24ee999d5290c22b658973015 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 5 Oct 2026 20:25:25 +0200 Subject: [PATCH 16/53] fix(web-svc-collabora): name the WOPI host and follow the vhost's TLS state The role restricted the WOPI hosts with `domain` and with `--o:net.wopi_allowed_hosts`. The distroless image that #775 brought in applies neither. `domain` was translated by the start script of the older image, which this one does not have, and coolwsd knows no setting called `net.wopi_allowed_hosts`. Its startup log listed that key among the overrides and no trusted WOPI host, so the server ran with the policy the image ships instead of the one the role declares. The allowlist now goes through `aliasgroup1`, the variable coolwsd reads itself. It carries the origin of the Nextcloud domain as the deployment resolves it, with scheme and port, so it also holds in a Tor variant. The old expression was built from DOMAIN_PRIMARY and would not have matched an onion address. No spec opened a document, which is why this went unnoticed. The richdocuments spec now uploads a document, opens it and waits for the `status:` frame on the editor websocket. Its first run on the Tor variant found a second defect. `ssl.termination` was fixed to true, so coolwsd advertised https URLs in its discovery while an onion vhost only serves http, and the browser never reached the editor. The setting now follows the TLS state of the Collabora vhost. Closes #802 Co-Authored-By: Claude Opus 5.5 (1M context) --- .../files/playwright/_shared.js | 3 + .../playwright/addons/onlyoffice.spec.js | 5 +- .../playwright/addons/richdocuments.spec.js | 62 +++++++++++++++++++ roles/web-svc-collabora/README.md | 2 +- roles/web-svc-collabora/templates/env.j2 | 4 +- roles/web-svc-collabora/vars/main.yml | 4 +- 6 files changed, 71 insertions(+), 9 deletions(-) diff --git a/roles/web-app-nextcloud/files/playwright/_shared.js b/roles/web-app-nextcloud/files/playwright/_shared.js index 06dd40577f..e154b3e2f1 100644 --- a/roles/web-app-nextcloud/files/playwright/_shared.js +++ b/roles/web-app-nextcloud/files/playwright/_shared.js @@ -22,6 +22,8 @@ const mastodonBaseUrl = decodeDotenvQuotedValue(process.env.MASTODON_BASE_URL); const moodleBaseUrl = decodeDotenvQuotedValue(process.env.MOODLE_BASE_URL); const peertubeBaseUrl = decodeDotenvQuotedValue(process.env.PEERTUBE_BASE_URL); const xwikiBaseUrl = decodeDotenvQuotedValue(process.env.XWIKI_BASE_URL); +const MINIMAL_DOCX_BASE64 = + "UEsDBBQAAAAIAEq201x5bjPX6AAAAK0BAAATAAAAW0NvbnRlbnRfVHlwZXNdLnhtbH1QyU7DMBD9FWuuKHHggBCK0wPLETiUDxjZk8SqN3nc0v49Tlt6QIXjzFv1+tXeO7GjzDYGBbdtB4KCjsaGScHn+rV5AMEFg0EXAyk4EMNq6NeHRCyqNrCCuZT0KCXrmTxyGxOFiowxeyz1zJNMqDc4kbzrunupYygUSlMWDxj6Zxpx64p42df3qUcmxyCeTsQlSwGm5KzGUnG5C+ZXSnNOaKvyyOHZJr6pBJBXExbk74Cz7r0Ok60h8YG5vKGvLPkVs5Em6q2vyvZ/mys94zhaTRf94pZy1MRcF/euvSAebfjpL49zD99QSwMECgAAAAAASrbTXAAAAAAAAAAAAAAAAAYAAABfcmVscy9QSwMEFAAAAAgASrbTXJv9N+qtAAAAKQEAAAsAAABfcmVscy8ucmVsc43POw7CMAwG4KtE3mlaBoRQ0y4IqSsqB7ASN61oHkrCo7cnAwNFDIy2f3+W6/ZpZnanECdnBVRFCYysdGqyWsClP232wGJCq3B2lgQsFKFt6jPNmPJKHCcfWTZsFDCm5A+cRzmSwVg4TzZPBhcMplwGzT3KK2ri27Lc8fBpwNpknRIQOlUB6xdP/9huGCZJRydvhmz6ceIrkWUMmpKAhwuKq3e7yCzwpuarF5sXUEsDBAoAAAAAAEq201wAAAAAAAAAAAAAAAAFAAAAd29yZC9QSwMEFAAAAAgASrbTXC5rweurAAAA6wAAABEAAAB3b3JkL2RvY3VtZW50LnhtbEWOQQ7CIBBFr0LYW6oLY5q27jyBHgBhaIkwQ4Bae3uhLty8n8lM3p/++vGOvSEmSzjwY9NyBqhIW5wG/rjfDhfOUpaopSOEgW+Q+HXs106TWjxgZkWAqVsHPuccOiGSmsHL1FAALDtD0ctcxjiJlaIOkRSkVPzeiVPbnoWXFnlVPklvNUNFrMijRWPRZmKEbiNjrAKmaAmuCFhpUq9e1LvKuDPs/LnE/8/xC1BLAQIeAxQAAAAIAEq201x5bjPX6AAAAK0BAAATAAAAAAAAAAEAAACkgQAAAABbQ29udGVudF9UeXBlc10ueG1sUEsBAh4DCgAAAAAASrbTXAAAAAAAAAAAAAAAAAYAAAAAAAAAAAAQAO1BGQEAAF9yZWxzL1BLAQIeAxQAAAAIAEq201yb/TfqrQAAACkBAAALAAAAAAAAAAEAAACkgT0BAABfcmVscy8ucmVsc1BLAQIeAwoAAAAAAEq201wAAAAAAAAAAAAAAAAFAAAAAAAAAAAAEADtQRMCAAB3b3JkL1BLAQIeAxQAAAAIAEq201wua8HrqwAAAOsAAAARAAAAAAAAAAEAAACkgTYCAAB3b3JkL2RvY3VtZW50LnhtbFBLBQYAAAAABQAFACABAAAQAwAAAAA="; const nextcloudUsernameFieldPattern = /account name(?: or email)?|username(?: or email)?/i; const nextcloudCredentialSubmitPattern = /^(sign in|log in)$/i; @@ -205,6 +207,7 @@ function beforeEach() { } module.exports = { + MINIMAL_DOCX_BASE64, env: { loginUsername, loginPassword, diff --git a/roles/web-app-nextcloud/files/playwright/addons/onlyoffice.spec.js b/roles/web-app-nextcloud/files/playwright/addons/onlyoffice.spec.js index 56333e0a42..a16e0a87e9 100644 --- a/roles/web-app-nextcloud/files/playwright/addons/onlyoffice.spec.js +++ b/roles/web-app-nextcloud/files/playwright/addons/onlyoffice.spec.js @@ -6,9 +6,6 @@ const { gotoOnion } = require("../personas"); test.use({ ignoreHTTPSErrors: true }); -const MINIMAL_DOCX_BASE64 = - "UEsDBBQAAAAIAEq201x5bjPX6AAAAK0BAAATAAAAW0NvbnRlbnRfVHlwZXNdLnhtbH1QyU7DMBD9FWuuKHHggBCK0wPLETiUDxjZk8SqN3nc0v49Tlt6QIXjzFv1+tXeO7GjzDYGBbdtB4KCjsaGScHn+rV5AMEFg0EXAyk4EMNq6NeHRCyqNrCCuZT0KCXrmTxyGxOFiowxeyz1zJNMqDc4kbzrunupYygUSlMWDxj6Zxpx64p42df3qUcmxyCeTsQlSwGm5KzGUnG5C+ZXSnNOaKvyyOHZJr6pBJBXExbk74Cz7r0Ok60h8YG5vKGvLPkVs5Em6q2vyvZ/mys94zhaTRf94pZy1MRcF/euvSAebfjpL49zD99QSwMECgAAAAAASrbTXAAAAAAAAAAAAAAAAAYAAABfcmVscy9QSwMEFAAAAAgASrbTXJv9N+qtAAAAKQEAAAsAAABfcmVscy8ucmVsc43POw7CMAwG4KtE3mlaBoRQ0y4IqSsqB7ASN61oHkrCo7cnAwNFDIy2f3+W6/ZpZnanECdnBVRFCYysdGqyWsClP232wGJCq3B2lgQsFKFt6jPNmPJKHCcfWTZsFDCm5A+cRzmSwVg4TzZPBhcMplwGzT3KK2ri27Lc8fBpwNpknRIQOlUB6xdP/9huGCZJRydvhmz6ceIrkWUMmpKAhwuKq3e7yCzwpuarF5sXUEsDBAoAAAAAAEq201wAAAAAAAAAAAAAAAAFAAAAd29yZC9QSwMEFAAAAAgASrbTXC5rweurAAAA6wAAABEAAAB3b3JkL2RvY3VtZW50LnhtbEWOQQ7CIBBFr0LYW6oLY5q27jyBHgBhaIkwQ4Bae3uhLty8n8lM3p/++vGOvSEmSzjwY9NyBqhIW5wG/rjfDhfOUpaopSOEgW+Q+HXs106TWjxgZkWAqVsHPuccOiGSmsHL1FAALDtD0ctcxjiJlaIOkRSkVPzeiVPbnoWXFnlVPklvNUNFrMijRWPRZmKEbiNjrAKmaAmuCFhpUq9e1LvKuDPs/LnE/8/xC1BLAQIeAxQAAAAIAEq201x5bjPX6AAAAK0BAAATAAAAAAAAAAEAAACkgQAAAABbQ29udGVudF9UeXBlc10ueG1sUEsBAh4DCgAAAAAASrbTXAAAAAAAAAAAAAAAAAYAAAAAAAAAAAAQAO1BGQEAAF9yZWxzL1BLAQIeAxQAAAAIAEq201yb/TfqrQAAACkBAAALAAAAAAAAAAEAAACkgT0BAABfcmVscy8ucmVsc1BLAQIeAwoAAAAAAEq201wAAAAAAAAAAAAAAAAFAAAAAAAAAAAAEADtQRMCAAB3b3JkL1BLAQIeAxQAAAAIAEq201wua8HrqwAAAOsAAAARAAAAAAAAAAEAAACkgTYCAAB3b3JkL2RvY3VtZW50LnhtbFBLBQYAAAAABQAFACABAAAQAwAAAAA="; - test("onlyoffice addon: opening a document loads the partner document-server editor", async ({ browser }) => { skipUnlessAddonEnabled("onlyoffice"); test.setTimeout(resolveTimeout(180_000)); @@ -39,7 +36,7 @@ test("onlyoffice addon: opening a document loads the partner document-server edi .setInputFiles({ name: docName, mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", - buffer: Buffer.from(MINIMAL_DOCX_BASE64, "base64"), + buffer: Buffer.from(shared.MINIMAL_DOCX_BASE64, "base64"), }); const docBasename = docName.replace(/\.docx$/, ""); diff --git a/roles/web-app-nextcloud/files/playwright/addons/richdocuments.spec.js b/roles/web-app-nextcloud/files/playwright/addons/richdocuments.spec.js index 516ee5f251..a70ee3f1b9 100644 --- a/roles/web-app-nextcloud/files/playwright/addons/richdocuments.spec.js +++ b/roles/web-app-nextcloud/files/playwright/addons/richdocuments.spec.js @@ -57,3 +57,65 @@ test("richdocuments addon: Collabora connector wired to the partner WOPI server" await context.close().catch(() => {}); } }); + +test("richdocuments addon: opening a document loads it through the partner WOPI server", async ({ browser }) => { + skipUnlessAddonEnabled("richdocuments"); + test.setTimeout(resolveTimeout(240_000)); + + const context = await browser.newContext({ ignoreHTTPSErrors: true }); + const page = await context.newPage(); + const editorReplies = []; + page.on("websocket", (socket) => { + if (!/\/cool\/(?:.+\/)?ws(?:\?|$)/.test(socket.url())) { + return; + } + socket.on("framereceived", ({ payload }) => { + const reply = payload.toString().slice(0, 120); + if (/^(status|error):/.test(reply)) { + editorReplies.push(reply); + } + }); + }); + + try { + await shared.loginToStandaloneNextcloud(page); + + const filesUrl = new URL("apps/files/", shared.env.nextcloudBaseUrl).toString(); + await gotoOnion(page, filesUrl, { waitUntil: "domcontentloaded", timeout: resolveTimeout(60_000) }); + await shared.dismissBlockingNextcloudModals(page, page); + + const docBasename = `infinito-collabora-${Date.now()}`; + await page + .locator('input[type="file"]') + .first() + .setInputFiles({ + name: `${docBasename}.docx`, + mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + buffer: Buffer.from(shared.MINIMAL_DOCX_BASE64, "base64"), + }); + + const uploadedRow = page.getByText(docBasename, { exact: false }).first(); + await expect( + uploadedRow, + `the uploaded document '${docBasename}.docx' must appear in the Files listing before it can be opened in Collabora` + ).toBeVisible({ timeout: resolveTimeout(60_000) }); + + await shared.dismissBlockingNextcloudModals(page, page); + await uploadedRow.click(); + + await expect + .poll(() => editorReplies.length, { + message: + "opening the document must make Collabora answer on its editor websocket (/cool/ws) with a 'status:' or an 'error:' frame; silence means the browser never reached the editor that the discovery of web-svc-collabora advertises", + timeout: resolveTimeout(180_000), + }) + .toBeGreaterThan(0); + expect( + editorReplies[0], + "Collabora must answer the document load with a 'status:' frame; 'error: cmd=internal kind=unauthorized' means it refused the WOPI host (aliasgroup1 of web-svc-collabora) or its CheckFileInfo call to Nextcloud failed, and the Collabora log names which" + ).toMatch(/^status:/); + } finally { + await page.close().catch(() => {}); + await context.close().catch(() => {}); + } +}); diff --git a/roles/web-svc-collabora/README.md b/roles/web-svc-collabora/README.md index 45b628790e..11d6af36e0 100644 --- a/roles/web-svc-collabora/README.md +++ b/roles/web-svc-collabora/README.md @@ -9,7 +9,7 @@ This Ansible role deploys Collabora Online (CODE) in Docker to enable real-time, * **Dockerized Collabora CODE:** Uses the official `collabora/code` image. * **NGINX Reverse Proxy:** Configures a public-facing proxy with TLS termination and WebSocket support for `/cool/` paths. * **Docker Network Management:** Creates an isolated `/28` subnet for Collabora and connects containers securely. -* **Environment Configuration:** Generates a `.env` file with domain, credentials, and extra parameters for Collabora's WOPI server. +* **Environment Configuration:** Generates a `.env` file that names the Nextcloud origin as the only allowed WOPI host (`aliasgroup1`) and passes the extra parameters to coolwsd. ## Cosmos diff --git a/roles/web-svc-collabora/templates/env.j2 b/roles/web-svc-collabora/templates/env.j2 index f696c1518b..81817edc81 100644 --- a/roles/web-svc-collabora/templates/env.j2 +++ b/roles/web-svc-collabora/templates/env.j2 @@ -1,4 +1,4 @@ {% include 'roles/sys-svc-container/templates/env.j2' %} -domain={{ COLLABORA_ALLOWED_DOMAINS }} -extra_params=--o:ssl.enable=false --o:ssl.termination=true --o:net.service_root=/ --o:net.wopi_allowed_hosts={{ COLLABORA_ALLOWED_HOSTS }} --o:net.post_allow.host[99]={{ networks.internet.ip4 }}/32 +aliasgroup1={{ COLLABORA_WOPI_HOST }} +extra_params=--o:ssl.enable=false --o:ssl.termination={{ lookup('tls', application_id, 'enabled') | lower }} --o:net.service_root=/ --o:net.post_allow.host[99]={{ networks.internet.ip4 }}/32 diff --git a/roles/web-svc-collabora/vars/main.yml b/roles/web-svc-collabora/vars/main.yml index 3def230487..d37eddc25f 100644 --- a/roles/web-svc-collabora/vars/main.yml +++ b/roles/web-svc-collabora/vars/main.yml @@ -6,6 +6,6 @@ domain: "{{ lookup('domain',application_id) }}" http_port: "{{ lookup('config', application_id, 'services.collabora.ports.local.http') }}" COLLABORA_CONTAINER: "{{ lookup('config', application_id, 'services.collabora.name') }}" -COLLABORA_ALLOWED_DOMAINS: "(.*\\.|){{ DOMAIN_PRIMARY | regex_replace('\\.', '\\\\.') }}" -COLLABORA_ALLOWED_HOSTS: "{{ lookup('domain','web-app-nextcloud') }}" +COLLABORA_WOPI_HOST: "{{ lookup('tls', 'web-app-nextcloud', 'protocols.web') }}://{{ lookup('domain', 'web-app-nextcloud') }}:{{ lookup('tls', 'web-app-nextcloud', + 'ports.web') }}" COLLABORA_DISCOVERY_PATH: "/hosting/discovery" From 1560824ed5ed60a25704bc09222733fddba65389 Mon Sep 17 00:00:00 2001 From: evangelostsak Date: Tue, 6 Oct 2026 09:38:19 +0200 Subject: [PATCH 17/53] fix(web-app-pihole): drop the unused shared redis dependency --- roles/web-app-pihole/meta/services.yml | 6 ------ 1 file changed, 6 deletions(-) diff --git a/roles/web-app-pihole/meta/services.yml b/roles/web-app-pihole/meta/services.yml index e30e2bd67c..c85d8ff8a9 100644 --- a/roles/web-app-pihole/meta/services.yml +++ b/roles/web-app-pihole/meta/services.yml @@ -21,12 +21,6 @@ email: shared: false # nocheck: dynamic-flag # nocheck: playwright-service-flag -redis: - bond: 1 - enabled: true - shared: true -# nocheck: dynamic-flag -# nocheck: playwright-service-flag javascript: bond: 1 enabled: "{{ 'web-app-keycloak' in group_names }}" From c35f2409a4b044efcaa44d5cda542664f8949569 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 6 Oct 2026 10:50:20 +0200 Subject: [PATCH 18/53] fix(web-app-odoo): make the OAuth addon work on Odoo 20 Nobody could sign in to Odoo through Keycloak. Odoo sent an http redirect URI, and Keycloak refused it as "Invalid parameter: redirect_uri". The addon auth_oauth_https builds that URI from web.base.url. Two things kept it from doing so after the image moved to Odoo 20. Its manifest declared version 19.0.1.8.0, and Odoo marks a module whose version names another series as not installable. It only warns about that, so the install task stayed green and the addon was missing. The manifest now declares 1.8.0, which Odoo prefixes with its own series. Once installed, the addon read the parameter with get_param, which Odoo 20 replaced by typed getters. The call raised AttributeError, a broad except logged it and fell back to the URL of the request, which is http behind the proxy. The addon reads the parameter with get_str now and no longer catches the error. A deploy now fails when the addon is not installed afterwards. The check reads ir_module_module, because the output of "odoo -i" does not tell an installed module from a skipped one. The spec logged out by navigating to /web/session/logout. Odoo 20 accepts POST only on that route and answered 405, so both SSO tests failed after a successful login. The spec logs out through the user menu now. A host that runs the suite with several workers still failed it. Odoo computes the session token of an account from its OAuth access token, so every new sign-in ends the other sessions of that account, and the spec files share the administrator. The role caps its suite at one worker with PLAYWRIGHT_MAX_WORKERS, which the central config now honours, and the spec asserts the cap. Closes #822 Co-Authored-By: Claude Opus 5.5 (1M context) --- .../files/role/playwright.specs.js.md | 2 + .../files/playwright.config.js | 5 ++- roles/web-app-odoo/README.md | 2 +- .../addons/auth_oauth_https/__manifest__.py | 2 +- .../auth_oauth_https/controllers/main.py | 20 +++------ .../files/playwright/playwright.spec.js | 26 +++++------ .../files/sql/select/installed-module.sql | 1 + .../tasks/03_install_modules/module_ops.yml | 12 ++++++ .../web-app-odoo/templates/playwright.env.j2 | 6 ++- .../python/roles/web-app-odoo/__init__.py | 0 .../test_addon_manifest_version.py | 43 +++++++++++++++++++ 11 files changed, 87 insertions(+), 32 deletions(-) create mode 100644 roles/web-app-odoo/files/sql/select/installed-module.sql create mode 100644 tests/unit/python/roles/web-app-odoo/__init__.py create mode 100644 tests/unit/python/roles/web-app-odoo/test_addon_manifest_version.py diff --git a/docs/contributing/artefact/files/role/playwright.specs.js.md b/docs/contributing/artefact/files/role/playwright.specs.js.md index be19d1f763..cbb0404262 100644 --- a/docs/contributing/artefact/files/role/playwright.specs.js.md +++ b/docs/contributing/artefact/files/role/playwright.specs.js.md @@ -308,6 +308,8 @@ The teardown MUST: Specs MUST decode quoted values before building URLs or typing credentials. The recurring helpers `decodeDotenvQuotedValue(value)` and `normalizeBaseUrl(value)` live in [`personas/utils/dotenv.js`](../../../../../roles/test-e2e-playwright/files/personas/utils/dotenv.js) and are re-exported through `require("./personas")`. Specs that need them MUST import from `./personas`; inline copies are forbidden and caught at review. +- A role whose spec files cannot run in parallel MUST set `PLAYWRIGHT_MAX_WORKERS` in `templates/playwright.env.j2`. + The central `playwright.config.js` runs the suite on the smaller of that value and the worker count the harness computed. ## Service gating contract 🔒 diff --git a/roles/test-e2e-playwright/files/playwright.config.js b/roles/test-e2e-playwright/files/playwright.config.js index 0587e22fcb..34ea0b334f 100644 --- a/roles/test-e2e-playwright/files/playwright.config.js +++ b/roles/test-e2e-playwright/files/playwright.config.js @@ -48,7 +48,10 @@ module.exports = defineConfig({ expect: { timeout: requiredTimeout("PLAYWRIGHT_EXPECT_TIMEOUT") }, ...(globalTimeout > 0 ? { globalTimeout } : {}), retries: 2, - workers: Number(process.env.PLAYWRIGHT_WORKERS) || 1, + workers: Math.min( + Number(process.env.PLAYWRIGHT_WORKERS) || 1, + Number(process.env.PLAYWRIGHT_MAX_WORKERS) || Infinity + ), fullyParallel: (process.env.PLAYWRIGHT_FULLY_PARALLEL || "").toLowerCase() === "true", outputDir: "/reports/test-results", reporter: [ diff --git a/roles/web-app-odoo/README.md b/roles/web-app-odoo/README.md index 62e7a4d9b5..c9904b6e56 100644 --- a/roles/web-app-odoo/README.md +++ b/roles/web-app-odoo/README.md @@ -216,7 +216,7 @@ docker logs odoo -f ## Persona contract opt-outs -The shared `biber` and `administrator` persona helpers are declared blocked in [templates/playwright.env.j2](./templates/playwright.env.j2). Odoo renders its SSO provider link only on `/web/login` inside the `.o_login_auth` container, not on the site root the persona helper starts from, and it exposes no in-app logout control — signing out means navigating to `/web/session/logout`. The full Keycloak round trip for both users is covered by the role's own `odoo: admin sso login, verify ui, logout` and `odoo: biber sso login, verify ui, logout` scenarios in [files/playwright/playwright.spec.js](./files/playwright/playwright.spec.js). +The shared `biber` and `administrator` persona helpers are declared blocked in [templates/playwright.env.j2](./templates/playwright.env.j2). Odoo renders its SSO provider link only on `/web/login` inside the `.o_login_auth` container, not on the site root the persona helper starts from, and its logout sits behind the user menu. The full Keycloak round trip for both users is covered by the role's own `odoo: admin sso login, verify ui, logout` and `odoo: biber sso login, verify ui, logout` scenarios in [files/playwright/playwright.spec.js](./files/playwright/playwright.spec.js). ## Credits diff --git a/roles/web-app-odoo/files/addons/auth_oauth_https/__manifest__.py b/roles/web-app-odoo/files/addons/auth_oauth_https/__manifest__.py index 5a042e03b9..70528d4956 100644 --- a/roles/web-app-odoo/files/addons/auth_oauth_https/__manifest__.py +++ b/roles/web-app-odoo/files/addons/auth_oauth_https/__manifest__.py @@ -1,7 +1,7 @@ # nocheck: mirrored-unit-test - an Odoo addon manifest, a bare dict literal the registry reads; there is no behaviour to exercise { # noqa: B018 Odoo addon manifests are bare dict expressions at module level by design "name": "OAuth HTTPS & Configurable UID", - "version": "19.0.1.8.0", + "version": "1.8.0", "category": "Authentication", "summary": "Force HTTPS redirect URIs and configurable OIDC UID field for OAuth", "description": """ diff --git a/roles/web-app-odoo/files/addons/auth_oauth_https/controllers/main.py b/roles/web-app-odoo/files/addons/auth_oauth_https/controllers/main.py index 0995cf2eb8..c637e3d3fe 100644 --- a/roles/web-app-odoo/files/addons/auth_oauth_https/controllers/main.py +++ b/roles/web-app-odoo/files/addons/auth_oauth_https/controllers/main.py @@ -2,14 +2,11 @@ # Part of Infinito.Nexus. See LICENSE file for full copyright and licensing details. import json -import logging import werkzeug.urls from odoo.addons.auth_oauth.controllers.main import OAuthLogin from odoo.http import request -_logger = logging.getLogger(__name__) - class OAuthLoginHTTPS(OAuthLogin): """ @@ -30,18 +27,11 @@ class OAuthLoginHTTPS(OAuthLogin): Returns the configured web.base.url, or falls back to request.httprequest.url_root if not set. """ - try: - base_url = ( - request.env["ir.config_parameter"].sudo().get_param("web.base.url") - ) - if base_url: - if not base_url.endswith("/"): - base_url += "/" - return base_url - except Exception: - _logger.exception( - "Failed to read 'web.base.url' from ir.config_parameter; falling back to request URL root." - ) + base_url = request.env["ir.config_parameter"].sudo().get_str("web.base.url") + if base_url: + if not base_url.endswith("/"): + base_url += "/" + return base_url return request.httprequest.url_root def list_providers(self): diff --git a/roles/web-app-odoo/files/playwright/playwright.spec.js b/roles/web-app-odoo/files/playwright/playwright.spec.js index bf7aeb77a2..f0dc42b44e 100644 --- a/roles/web-app-odoo/files/playwright/playwright.spec.js +++ b/roles/web-app-odoo/files/playwright/playwright.spec.js @@ -74,14 +74,9 @@ async function isOdooAuthenticated(locator) { } } -// Perform logout from Odoo by navigating directly to the logout URL. -async function performOdooLogout(page, odooBaseUrl) { - const logoutUrl = `${odooBaseUrl.replace(/\/$/, "")}/web/session/logout`; - - await gotoOnion(page, logoutUrl); - - // Give the logout a moment to process - await page.waitForTimeout(resolveTimeout(2_000)); +async function logOutThroughTheUserMenu(page) { + await page.locator("button.o_user_menu").first().click({ timeout: resolveTimeout(30_000) }); + await page.locator('[data-menu="logout"]').first().click({ timeout: resolveTimeout(30_000) }); } test.beforeEach(() => { @@ -93,6 +88,13 @@ test.beforeEach(() => { expect(biberPassword, "BIBER_PASSWORD must be set in the Playwright env file").toBeTruthy(); }); +test("odoo: the suite runs on one worker", async () => { + expect( + test.info().config.workers, + "an OAuth sign-in ends every other session of the same account, so PLAYWRIGHT_MAX_WORKERS must keep the spec files that share the administrator on one worker" + ).toBe(1); +}); + // Scenario I: Odoo → SSO login as admin → verify authenticated → logout // (dashboard-iframe mechanics covered by web-app-dashboard SPOT) test("odoo: admin sso login, verify ui, logout", async ({ page }) => { @@ -137,8 +139,8 @@ test("odoo: admin sso login, verify ui, logout", async ({ page }) => { ) .toBe(true); - // 7. Perform logout from Odoo by navigating to the logout URL - await performOdooLogout(page, odooBaseUrl); + // 7. Log out through the user menu + await logOutThroughTheUserMenu(page); // 8. Verify we're back on the login page (provider list visible again) await expect @@ -198,8 +200,8 @@ test("odoo: biber sso login, verify ui, logout", async ({ page }) => { ) .toBe(true); - // 7. Perform logout from Odoo - await performOdooLogout(page, odooBaseUrl); + // 7. Log out through the user menu + await logOutThroughTheUserMenu(page); // 8. Verify we're back on the login page await expect diff --git a/roles/web-app-odoo/files/sql/select/installed-module.sql b/roles/web-app-odoo/files/sql/select/installed-module.sql new file mode 100644 index 0000000000..0d0dde252d --- /dev/null +++ b/roles/web-app-odoo/files/sql/select/installed-module.sql @@ -0,0 +1 @@ +SELECT name FROM ir_module_module WHERE name = %(module)s AND state = 'installed'; diff --git a/roles/web-app-odoo/tasks/03_install_modules/module_ops.yml b/roles/web-app-odoo/tasks/03_install_modules/module_ops.yml index 7829592d9a..6e216510b5 100644 --- a/roles/web-app-odoo/tasks/03_install_modules/module_ops.yml +++ b/roles/web-app-odoo/tasks/03_install_modules/module_ops.yml @@ -79,6 +79,18 @@ auth_oauth_https_install.rc != 0 or 'invalid module names' in (auth_oauth_https_install.stdout ~ auth_oauth_https_install.stderr) +- name: "🛑 Fail when Odoo did not install the auth_oauth_https module" + database_query: + mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + config: "{{ lookup('database', application_id) }}" + query_file: "{{ role_path }}/files/sql/select/installed-module.sql" + named_args: + module: "auth_oauth_https" + expect_rows: true + register: auth_oauth_https_installed + failed_when: auth_oauth_https_installed.rows | length == 0 + when: ODOO_OIDC_ENABLED | bool + - name: "📦 Install auth_ldap module for LDAP support" no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node diff --git a/roles/web-app-odoo/templates/playwright.env.j2 b/roles/web-app-odoo/templates/playwright.env.j2 index fc973b9455..ba10af4e05 100644 --- a/roles/web-app-odoo/templates/playwright.env.j2 +++ b/roles/web-app-odoo/templates/playwright.env.j2 @@ -28,12 +28,14 @@ ODOO_BASE_URL={{ lookup('tls', application_id, 'url.base') | dotenv_quote }} OIDC_ISSUER_URL={{ OIDC.CLIENT.ISSUER_URL | dotenv_quote }} -# nocheck: persona-block-rationale — Odoo's SSO entry is an auth_oauth provider link that only renders inside .o_login_auth on /web/login (files/playwright/playwright.spec.js:25-44), not on the APP_BASE_URL root the persona helper starts from, and Odoo offers no in-app logout control — the role logs out by navigating to /web/session/logout (files/playwright/playwright.spec.js:77-84); the admin chain is covered by "odoo: admin sso login, verify ui, logout" (see README "Persona contract opt-outs"). +# nocheck: persona-block-rationale — Odoo's SSO entry is an auth_oauth provider link that only renders inside .o_login_auth on /web/login (files/playwright/playwright.spec.js:26-45), not on the APP_BASE_URL root the persona helper starts from, and its logout sits behind the user menu (files/playwright/playwright.spec.js:77-80); the admin chain is covered by "odoo: admin sso login, verify ui, logout" (see README "Persona contract opt-outs"). PERSONA_ADMINISTRATOR_BLOCKED=true -# nocheck: persona-block-rationale — see PERSONA_ADMINISTRATOR_BLOCKED above; biber's chain is covered by "odoo: biber sso login, verify ui, logout" (files/playwright/playwright.spec.js:159). +# nocheck: persona-block-rationale — see PERSONA_ADMINISTRATOR_BLOCKED above; biber's chain is covered by "odoo: biber sso login, verify ui, logout" (files/playwright/playwright.spec.js:162). PERSONA_BIBER_BLOCKED=true +PLAYWRIGHT_MAX_WORKERS=1 + SSO_SERVICE_ENABLED={{ lookup('config', application_id, 'services.sso.enabled') | string | lower }} {{ lookup('addon_env_flags', application_id) }} diff --git a/tests/unit/python/roles/web-app-odoo/__init__.py b/tests/unit/python/roles/web-app-odoo/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-odoo/test_addon_manifest_version.py b/tests/unit/python/roles/web-app-odoo/test_addon_manifest_version.py new file mode 100644 index 0000000000..e379a4ed49 --- /dev/null +++ b/tests/unit/python/roles/web-app-odoo/test_addon_manifest_version.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +import ast +import unittest + +from utils.cache.files import PROJECT_ROOT, read_text + +MANIFEST = ( + PROJECT_ROOT / "roles/web-app-odoo/files/addons/auth_oauth_https/__manifest__.py" +) + + +def manifest_version() -> str: + return ast.literal_eval(read_text(str(MANIFEST)))["version"] + + +def installable_on(series: str, version: str) -> bool: + parts = version.split(".") + if not 2 <= len(parts) <= 5 or not all(part.isdigit() for part in parts): + return False + if len(parts) <= 3 and not version.startswith(series): + version = f"{series}.{version}" + return version.startswith(series + ".") + + +class TestAddonManifestVersion(unittest.TestCase): + def test_odoo_installs_the_addon_on_every_series(self): + for series in ("19.0", "20.0", "21.0"): + with self.subTest(series=series): + self.assertTrue( + installable_on(series, manifest_version()), + f"Odoo {series} marks a module whose version names another " + "series as not installable and only warns about it; keep the " + "version in the form x.y.z so Odoo prefixes its own series", + ) + + def test_a_version_that_names_a_series_is_refused_by_the_next_one(self): + self.assertTrue(installable_on("19.0", "19.0.1.8.0")) + self.assertFalse(installable_on("20.0", "19.0.1.8.0")) + + +if __name__ == "__main__": + unittest.main() From 7968b47cf0570a2289b094d6c027e78fbb0077c3 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 6 Oct 2026 11:02:31 +0200 Subject: [PATCH 19/53] fix(svc-net-tor): give every chutney node one worker thread Tor starts its worker threads by the number of CPU cores it detects, and the cpus limit of the container does not change that number. On a host with 20 cores every node of the private chutney network ran 21 threads and grew to about 0.6 GB. The seven relays and authorities filled the 2g limit and its swap within ten minutes, the kernel killed them one by one, and no circuit could be built any more. The entrypoint now writes NumCPUs 1 into the torrc of every chutney node before it starts the network. Measured on that host over ten minutes: the nodes run 3 threads and stay at 65 to 86 MB, the container at 0.47 GB without swap, where it had filled 2 GB plus 2 GB of swap before. The CLI test of the role fails when a chutney node runs without the limit. Closes #824 Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/svc-net-tor/files/shell/entrypoint.sh | 3 +++ roles/svc-net-tor/files/test/test.sh | 16 ++++++++++++++++ roles/svc-net-tor/templates/test.env.j2 | 2 ++ .../roles/svc-net-tor/test_test_env_sourcing.py | 3 +++ 4 files changed, 24 insertions(+) diff --git a/roles/svc-net-tor/files/shell/entrypoint.sh b/roles/svc-net-tor/files/shell/entrypoint.sh index ccf615aad1..27fe61bc7d 100644 --- a/roles/svc-net-tor/files/shell/entrypoint.sh +++ b/roles/svc-net-tor/files/shell/entrypoint.sh @@ -21,6 +21,9 @@ if [ "${TOR_FLAVOR}" = "chutney" ]; then CHUTNEY_LISTEN_ADDRESS=127.0.0.1 \ ./chutney init --net "${net}" ./chutney configure + for torrc in net/nodes/*/torrc; do + echo "NumCPUs 1" >>"${torrc}" + done ./chutney start ./chutney wait_for_bootstrap diff --git a/roles/svc-net-tor/files/test/test.sh b/roles/svc-net-tor/files/test/test.sh index 68677e034b..07a74906f8 100755 --- a/roles/svc-net-tor/files/test/test.sh +++ b/roles/svc-net-tor/files/test/test.sh @@ -18,6 +18,8 @@ # SLEEP_SECONDS wait between attempts # TOR_DNSMASQ_CONF the dnsmasq drop-in path; its directory is scanned for # upstreams when a probe fails +# TOR_CONTAINER address of the tor container +# TOR_FLAVOR public or chutney set -uo pipefail @@ -26,6 +28,8 @@ NGINX_SERVERS_DIR="${NGINX_SERVERS_DIR:?pass NGINX_SERVERS_DIR as env (the deplo RETRIES="${RETRIES:?pass RETRIES as env (attempts per domain, from svc-net-tor test.env)}" SLEEP_SECONDS="${SLEEP_SECONDS:?pass SLEEP_SECONDS as env (wait between attempts, from svc-net-tor test.env)}" TOR_DNSMASQ_CONF="${TOR_DNSMASQ_CONF:?pass TOR_DNSMASQ_CONF as env (the dnsmasq drop-in path, from svc-net-tor vars)}" +TOR_CONTAINER="${TOR_CONTAINER:?pass TOR_CONTAINER as env (address of the tor container, from svc-net-tor test.env)}" +TOR_FLAVOR="${TOR_FLAVOR:?pass TOR_FLAVOR as env (public or chutney, from svc-net-tor test.env)}" discover_domains() { find "${NGINX_SERVERS_DIR}/http" "${NGINX_SERVERS_DIR}/https" \ @@ -102,4 +106,16 @@ echo "[INFO] ${#domains[@]} probed, ${failed} failed" "$(dirname "${BASH_SOURCE[0]}")/onion_ports.py" || failed=$((failed + 1)) +if [[ "${TOR_FLAVOR}" == "chutney" ]]; then + if ! unbounded="$(container exec "${TOR_CONTAINER}" sh -c 'grep -L "^NumCPUs 1$" /opt/chutney/net/nodes/*/torrc; true')"; then + echo "[FAIL] cannot read the chutney node torrcs in ${TOR_CONTAINER}" + failed=$((failed + 1)) + elif [[ -n "${unbounded}" ]]; then + echo "[FAIL] chutney nodes without NumCPUs 1 start one worker per host core: ${unbounded//$'\n'/ }" + failed=$((failed + 1)) + else + echo "[OK] every chutney node runs one worker" + fi +fi + [[ "${failed}" -eq 0 ]] diff --git a/roles/svc-net-tor/templates/test.env.j2 b/roles/svc-net-tor/templates/test.env.j2 index 6e0bec9054..51288356b2 100644 --- a/roles/svc-net-tor/templates/test.env.j2 +++ b/roles/svc-net-tor/templates/test.env.j2 @@ -5,5 +5,7 @@ ONION_PORT_RETRIES=2 ONION_PORT_TIMEOUT=60 RETRIES=5 SLEEP_SECONDS=10 +TOR_CONTAINER={{ lookup('container_address', application_id, 'tor') }} TOR_DNSMASQ_CONF={{ TOR_DNSMASQ_CONF }} +TOR_FLAVOR={{ TOR_FLAVOR }} TOR_SOCKS={{ lookup('tor_socks') }} diff --git a/tests/unit/python/roles/svc-net-tor/test_test_env_sourcing.py b/tests/unit/python/roles/svc-net-tor/test_test_env_sourcing.py index e0a3f8ed8c..ddb45113bd 100644 --- a/tests/unit/python/roles/svc-net-tor/test_test_env_sourcing.py +++ b/tests/unit/python/roles/svc-net-tor/test_test_env_sourcing.py @@ -26,6 +26,7 @@ PORTS = [25, 80, 587] def _lookup(name: str, *_args: str) -> object: return { "config": "example.onion", + "container_address": "tor", "nginx": "/etc/nginx/conf.d/servers", "tor_ports": [ {"onion_port": port, "target": f"127.0.0.1:{port}"} for port in PORTS @@ -42,8 +43,10 @@ def _render(mode: str) -> str: env.filters.update(FilterModule().filters()) return env.from_string(read_text(str(TEMPLATE))).render( lookup=_lookup, + application_id="svc-net-tor", DEPLOYMENT_MODE=mode, TOR_DNSMASQ_CONF="/etc/dnsmasq.d/tor-onion.conf", + TOR_FLAVOR="chutney", ) From a7ca03d86d6577eed4ca05e208dbb465502293d5 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:54:32 +0000 Subject: [PATCH 20/53] update(versions): update pins with a declared source (web-app-zammad) --- roles/web-app-zammad/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-zammad/meta/services.yml b/roles/web-app-zammad/meta/services.yml index 47ccf4032e..bceafa4e8b 100644 --- a/roles/web-app-zammad/meta/services.yml +++ b/roles/web-app-zammad/meta/services.yml @@ -115,7 +115,7 @@ websocket: # nocheck: playwright-service-flag - internal sub-component (bundled search) search: image: docker.elastic.co/elasticsearch/elasticsearch - version: "8.13.4" + version: "9.5.5" update: type: registry_tags image: docker.elastic.co/elasticsearch/elasticsearch From ddb565dd2d6ebe0b179fc45ed1ebe9d6376b103b Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 6 Oct 2026 13:22:35 +0200 Subject: [PATCH 21/53] docs(web-app-pihole): regenerate the READMEs without the redis dependency 1560824ed5 dropped the unused shared redis dependency of web-app-pihole without a make docs run. This is the generator output for the current tree: the pihole cosmos loses the redis node and edge, and the root role table no longer lists Redis for Pi-hole. Co-Authored-By: Claude Opus 5.5 (1M context) --- README.md | 2 +- roles/web-app-pihole/README.md | 5 +---- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 4997f9f7b1..ae2daf2654 100644 --- a/README.md +++ b/README.md @@ -182,7 +182,7 @@ Every invokable role in the tested lifecycle envelope, with its upstream homepag | [Typesense](roles/svc-db-typesense/) | beta | Central Dockerized search engine shared by multiple apps with per-consumer scoped API keys | [🌐](https://typesense.org/) [🛠️](roles/svc-db-typesense/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Tor Onion Service](roles/svc-net-tor/) | | [Unbound](roles/svc-dns-unbound/) | beta | Central recursive/forwarding DNSSEC resolver on a static IP for consumer stacks to target as their DNS | [🌐](https://nlnetlabs.nl/projects/unbound/about/) [🛠️](roles/svc-dns-unbound/README.md#quick-setup) | | | [Universal Logout](roles/web-svc-logout/) | beta | Central logout proxy for single-action sign-out across all OIDC-connected apps, with Nginx snippets and a live status UI | [🛠️](roles/web-svc-logout/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | -| [web-app-pihole](roles/web-app-pihole/) | beta | Network-wide DNS sinkhole for blocking ads and trackers across all devices, with DHCP and a web admin dashboard | [🌐](https://pi-hole.net/) [🎬](https://youtu.be/KBXTnrD_Zs4) [🛠️](roles/web-app-pihole/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Content Delivery Network](roles/web-svc-cdn/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [web-app-pihole](roles/web-app-pihole/) | beta | Network-wide DNS sinkhole for blocking ads and trackers across all devices, with DHCP and a web admin dashboard | [🌐](https://pi-hole.net/) [🎬](https://youtu.be/KBXTnrD_Zs4) [🛠️](roles/web-app-pihole/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Content Delivery Network](roles/web-svc-cdn/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Wireguard](roles/svc-net-wireguard-core/) | alpha | Host-level WireGuard VPN service with wg-quick config, package install, and IP-forwarding sysctl for secure tunnels | [🌐](https://www.wireguard.com/) [🛠️](roles/svc-net-wireguard-core/README.md#quick-setup) | | | [Wireguard Client](roles/svc-net-wireguard-plain/) | alpha | Client-side WireGuard VPN role for stable connectivity with a systemd service and script that tune interface MTU | [🌐](https://www.wireguard.com/) [🛠️](roles/svc-net-wireguard-plain/README.md#quick-setup) | | | [WireGuard Client behind NAT](roles/svc-net-wireguard-firewalled/) | alpha | Networking helper for iptables forwarding and NAT masquerading of a WireGuard client running behind NAT or a firewall | [🛠️](roles/svc-net-wireguard-firewalled/README.md#quick-setup) | | diff --git a/roles/web-app-pihole/README.md b/roles/web-app-pihole/README.md index 1f3b88fe90..c192fda89f 100644 --- a/roles/web-app-pihole/README.md +++ b/roles/web-app-pihole/README.md @@ -18,7 +18,6 @@ The diagram places web-app-pihole in the Infinito.Nexus cosmos: the components i flowchart LR subgraph deps [Dependencies] dep_svc_bkp_volume_2_local["svc-bkp-volume-2-local 💻"] - dep_svc_db_redis["svc-db-redis 🐳🐝"] dep_svc_net_tor["svc-net-tor 🐳🐝"] dep_web_app_dashboard["web-app-dashboard 🐳🐝"] dep_web_app_keycloak["web-app-keycloak 🐳🐝"] @@ -33,7 +32,6 @@ flowchart LR svc_dashboard["dashboard"] svc_matomo["matomo"] svc_email["email ❌"] - svc_redis["redis"] svc_javascript["javascript"] svc_prometheus["prometheus"] svc_tor["tor"] @@ -43,7 +41,6 @@ flowchart LR svc_container_backup["container_backup"] end dep_svc_bkp_volume_2_local -. "0..1" .-> svc_container_backup - dep_svc_db_redis -- "1:1" --> svc_redis dep_svc_net_tor -. "0..1" .-> svc_tor dep_web_app_dashboard -. "0..1" .-> svc_dashboard dep_web_app_keycloak -. "0..1" .-> svc_javascript @@ -53,7 +50,7 @@ flowchart LR dep_web_app_stalwart -- "0..0" --> svc_email dep_web_svc_css -. "0..1" .-> svc_css dep_web_svc_logout -. "0..1" .-> svc_logout - linkStyle 8 stroke:red; + linkStyle 7 stroke:red; ``` Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. From baaa5e61a1eed0adbd8cd1fd12088305769ff80f Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Tue, 6 Oct 2026 12:23:13 +0000 Subject: [PATCH 22/53] update(images): update Docker image versions (web-app-opentalk) --- roles/web-app-opentalk/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-opentalk/meta/services.yml b/roles/web-app-opentalk/meta/services.yml index 41d2c1e836..5509c681aa 100644 --- a/roles/web-app-opentalk/meta/services.yml +++ b/roles/web-app-opentalk/meta/services.yml @@ -96,7 +96,7 @@ controller: livekit: name: opentalk-livekit image: livekit/livekit-server - version: v1.13.7 + version: v1.13.8 min_storage: 238MB cpus: "2.0" mem_reservation: 512m From 4f8c1f00f1de3ac359ac828f489ff7fbf3678cbe Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 6 Oct 2026 13:47:17 +0200 Subject: [PATCH 23/53] fix(svc-net-tor): fail the worker check when no torrc can be read The check listed the torrcs without the limit through "grep -L ...; true". With no torrc under /opt/chutney/net/nodes, or with one that cannot be read, grep printed nothing, the trailing true turned its error into success, and the test reported that every node runs one worker. The check now counts the limit per file with "grep -cH" and reads the exit status. A status above 1 or an empty answer fails the test, and a file with a count of 0 is named as before. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/svc-net-tor/files/test/test.sh | 5 +- .../svc-net-tor/test_chutney_worker_check.py | 107 ++++++++++++++++++ 2 files changed, 111 insertions(+), 1 deletion(-) create mode 100644 tests/unit/python/roles/svc-net-tor/test_chutney_worker_check.py diff --git a/roles/svc-net-tor/files/test/test.sh b/roles/svc-net-tor/files/test/test.sh index 07a74906f8..f3a8989df7 100755 --- a/roles/svc-net-tor/files/test/test.sh +++ b/roles/svc-net-tor/files/test/test.sh @@ -107,7 +107,10 @@ echo "[INFO] ${#domains[@]} probed, ${failed} failed" "$(dirname "${BASH_SOURCE[0]}")/onion_ports.py" || failed=$((failed + 1)) if [[ "${TOR_FLAVOR}" == "chutney" ]]; then - if ! unbounded="$(container exec "${TOR_CONTAINER}" sh -c 'grep -L "^NumCPUs 1$" /opt/chutney/net/nodes/*/torrc; true')"; then + status=0 + workers="$(container exec "${TOR_CONTAINER}" sh -c 'grep -cH "^NumCPUs 1$" /opt/chutney/net/nodes/*/torrc')" || status=$? + unbounded="$(sed -n 's/:0$//p' <<<"${workers}")" + if [[ "${status}" -gt 1 || -z "${workers}" ]]; then echo "[FAIL] cannot read the chutney node torrcs in ${TOR_CONTAINER}" failed=$((failed + 1)) elif [[ -n "${unbounded}" ]]; then diff --git a/tests/unit/python/roles/svc-net-tor/test_chutney_worker_check.py b/tests/unit/python/roles/svc-net-tor/test_chutney_worker_check.py new file mode 100644 index 0000000000..b520ffe58e --- /dev/null +++ b/tests/unit/python/roles/svc-net-tor/test_chutney_worker_check.py @@ -0,0 +1,107 @@ +from __future__ import annotations + +import os +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +from . import PROJECT_ROOT + +TEST_SH = PROJECT_ROOT / "roles" / "svc-net-tor" / "files" / "test" / "test.sh" +BOUNDED = "DataDirectory /data\nNumCPUs 1\n" +UNBOUNDED = "DataDirectory /data\n" +CONTAINER_STUB = """\ +in_container=/opt/chutney/net/nodes +exec sh -c "${5//"${in_container}"/"${NODES_DIR}"}" +""" + + +def _stub(path: Path, body: str) -> None: + path.write_text(f"#!/usr/bin/env bash\n{body}\n", encoding="utf-8") + path.chmod(0o755) + + +def _run( + torrcs: dict[str, str], flavor: str = "chutney", unreadable: str = "" +) -> subprocess.CompletedProcess[str]: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + nodes = root / "nodes" + nodes.mkdir() + for node, torrc in torrcs.items(): + (nodes / node).mkdir() + (nodes / node / "torrc").write_text(torrc, encoding="utf-8") + if unreadable: + (nodes / unreadable / "torrc").mkdir(parents=True) + shutil.copy(TEST_SH, root / "test.sh") + _stub(root / "onion_ports.py", "exit 0") + bin_dir = root / "bin" + bin_dir.mkdir() + _stub(bin_dir / "curl", "printf 200") + _stub(bin_dir / "container", CONTAINER_STUB) + return subprocess.run( + ["bash", str(root / "test.sh"), "example.onion"], + env={ + "PATH": f"{bin_dir}{os.pathsep}{os.environ['PATH']}", + "NODES_DIR": str(nodes), + "TOR_SOCKS": "127.0.0.1:9050", + "NGINX_SERVERS_DIR": str(root), + "RETRIES": "1", + "SLEEP_SECONDS": "0", + "TOR_DNSMASQ_CONF": str(root / "tor-onion.conf"), + "TOR_CONTAINER": "tor", + "TOR_FLAVOR": flavor, + }, + capture_output=True, + text=True, + check=False, + ) + + +def _verdict(result: subprocess.CompletedProcess[str]) -> str: + return result.stdout.splitlines()[-1] + + +class TestChutneyWorkerCheck(unittest.TestCase): + def test_nodes_that_all_carry_the_limit_pass(self) -> None: + result = _run({"000a": BOUNDED, "001a": BOUNDED}) + self.assertEqual(_verdict(result), "[OK] every chutney node runs one worker") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_a_node_without_the_limit_is_named_and_fails(self) -> None: + result = _run({"000a": BOUNDED, "001a": UNBOUNDED}) + self.assertIn("start one worker per host core", _verdict(result)) + self.assertTrue(_verdict(result).endswith("/001a/torrc"), _verdict(result)) + self.assertNotIn("000a", _verdict(result)) + self.assertEqual(result.returncode, 1) + + def test_nodes_that_all_lack_the_limit_fail(self) -> None: + result = _run({"000a": UNBOUNDED, "001a": UNBOUNDED}) + self.assertIn("/000a/torrc", _verdict(result)) + self.assertIn("/001a/torrc", _verdict(result)) + self.assertEqual(result.returncode, 1) + + def test_no_torrc_to_inspect_fails(self) -> None: + result = _run({}) + self.assertEqual( + _verdict(result), "[FAIL] cannot read the chutney node torrcs in tor" + ) + self.assertEqual(result.returncode, 1) + + def test_a_torrc_that_cannot_be_read_fails_beside_bounded_nodes(self) -> None: + result = _run({"000a": BOUNDED}, unreadable="001a") + self.assertEqual( + _verdict(result), "[FAIL] cannot read the chutney node torrcs in tor" + ) + self.assertEqual(result.returncode, 1) + + def test_the_public_flavor_does_not_run_the_check(self) -> None: + result = _run({}, flavor="public") + self.assertEqual(_verdict(result), "[INFO] 1 probed, 0 failed") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + +if __name__ == "__main__": + unittest.main() From f9e25b0387b696ac49ab4c9df63732ba3afd3ad2 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 6 Oct 2026 12:58:13 +0200 Subject: [PATCH 24/53] fix(web-app-hugo): build with the official Hugo image The update moved the documentation source to v0.165.0 and the builder to hugomods/hugo:exts-0.154.5. That is the newest tag hugomods publishes, and the source of v0.165.0 does not render with it. The image build ended with "can't evaluate field Locale in type *langs.Language" in layouts/baseof.html. The builder is now ghcr.io/gohugoio/hugo, which Hugo publishes for every release, pinned to v0.165.0 like the source. That image runs as an unprivileged user, so the build stage switches to root for the steps that write to /src and /public. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-hugo/Administration.md | 4 ++-- roles/web-app-hugo/README.md | 4 ++-- roles/web-app-hugo/files/Dockerfile | 1 + roles/web-app-hugo/meta/services.yml | 8 ++++---- 4 files changed, 9 insertions(+), 8 deletions(-) diff --git a/roles/web-app-hugo/Administration.md b/roles/web-app-hugo/Administration.md index aa4b507021..e03fbf1527 100644 --- a/roles/web-app-hugo/Administration.md +++ b/roles/web-app-hugo/Administration.md @@ -42,9 +42,9 @@ make compose-exec cmd="docker compose -f /opt/docker/web-app-hugo/docker-compose Common causes: - **`hugo` reports unknown content / module errors**: the upstream repository moved a directory or a Hugo Module. Pin to a known-good tag in `source_version`. -- **`hugo` reports template execution errors**: the theme's templates are incompatible with the bundled Hugo binary. Bump `services.hugo.builder_version` (e.g. to a newer `exts-` tag) or pin the source repo to a tag known to build with the current Hugo. +- **`hugo` reports template execution errors**: the theme's templates are incompatible with the bundled Hugo binary. Bump `services.hugo.builder_version` (e.g. to a newer `v` tag) or pin the source repo to a tag known to build with the current Hugo. - **Module fetch fails (`go.mod` resolution)**: Hugo modules pull from `proxy.golang.org`. Network egress to that host must be allowed by the local firewall / proxy. ## Rotating the Hugo binary -To upgrade the extended Hugo binary independently of the content repo, edit `services.hugo.builder_version` in `meta/services.yml` (e.g. `exts-0.149.0`). The change invalidates only the builder layer, not the cloned repo, so the next `compose build` reuses the same content but with the new binary. +To upgrade the extended Hugo binary independently of the content repo, edit `services.hugo.builder_version` in `meta/services.yml` (e.g. `v0.166.0`). The change invalidates only the builder layer, not the cloned repo, so the next `compose build` reuses the same content but with the new binary. diff --git a/roles/web-app-hugo/README.md b/roles/web-app-hugo/README.md index f40499e847..bbbbb383c7 100644 --- a/roles/web-app-hugo/README.md +++ b/roles/web-app-hugo/README.md @@ -8,7 +8,7 @@ The role uses a multi-stage Dockerfile: -1. **Builder stage:** pinned `hugomods/hugo:exts-` (extended Hugo) clones the configured content repository and runs `hugo --minify -e -b ` to render the site to `/public`. +1. **Builder stage:** pinned `ghcr.io/gohugoio/hugo:v` (the official extended Hugo image) clones the configured content repository and runs `hugo --minify -e -b ` to render the site to `/public`. 2. **Serve stage:** pinned `nginx:-alpine` ships the rendered `/public` from the builder stage as `/usr/share/nginx/html`. `compose build` re-bakes the static output whenever the cloned content changes, so deploys are content-driven without any runtime build step. @@ -125,7 +125,7 @@ V1 supports **exactly one canonical domain** per role deploy. The play asserts t - [Hugo official site](https://gohugo.io/) - [Hugo documentation source: gohugoio/hugoDocs](https://github.com/gohugoio/hugoDocs) -- [hugomods/hugo Docker images](https://hub.docker.com/r/hugomods/hugo) +- [Official Hugo container image](https://github.com/gohugoio/hugo/pkgs/container/hugo) ## Persona contract opt-outs diff --git a/roles/web-app-hugo/files/Dockerfile b/roles/web-app-hugo/files/Dockerfile index b610e36e1d..0dac73278d 100644 --- a/roles/web-app-hugo/files/Dockerfile +++ b/roles/web-app-hugo/files/Dockerfile @@ -10,6 +10,7 @@ ARG HUGO_NGINX_IMAGE ARG HUGO_NGINX_VERSION FROM ${HUGO_BUILDER_IMAGE}:${HUGO_BUILDER_VERSION} AS builder +USER root ARG HUGO_BASE_URL ARG HUGO_ENVIRONMENT diff --git a/roles/web-app-hugo/meta/services.yml b/roles/web-app-hugo/meta/services.yml index e2374b3056..6c4954e98d 100644 --- a/roles/web-app-hugo/meta/services.yml +++ b/roles/web-app-hugo/meta/services.yml @@ -34,15 +34,15 @@ hugo: image: nginx version: 1.31-alpine custom: true - builder_image: hugomods/hugo - builder_version: exts-0.154.5 + builder_image: ghcr.io/gohugoio/hugo + builder_version: v0.165.0 source_repository: https://github.com/gohugoio/hugoDocs.git source_version: v0.165.0 update: - key: builder_version type: registry_tags - image: hugomods/hugo - match: "exts-" + image: ghcr.io/gohugoio/hugo + match: "v" - key: source_version type: git_tags repository: https://github.com/gohugoio/hugoDocs.git From 8834cc124ac52d3334017f3110109282e13b0654 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 6 Oct 2026 15:27:34 +0200 Subject: [PATCH 25/53] fix(web-svc-collabora): build the WOPI host from Nextcloud's own domain COLLABORA_WOPI_HOST read the scheme and the port with lookup('tls', 'web-app-nextcloud', ...) and the host with lookup('domain', 'web-app-nextcloud'). The tls lookup aligns an app term to its consumer: for a clearnet Collabora it answers for the clearnet sibling of an onion-primary Nextcloud, while the domain lookup keeps the onion name. Such a deployment renders https://:443, an origin Nextcloud does not use, so the allowlist does not match its WOPI calls. Nextcloud pins overwritehost and overwriteprotocol to its primary domain, so the allowlist now asks the tls lookup for that domain instead of for the app. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-svc-collabora/vars/main.yml | 4 +- .../roles/web-svc-collabora/__init__.py | 0 .../roles/web-svc-collabora/test_wopi_host.py | 92 +++++++++++++++++++ 3 files changed, 94 insertions(+), 2 deletions(-) create mode 100644 tests/unit/python/roles/web-svc-collabora/__init__.py create mode 100644 tests/unit/python/roles/web-svc-collabora/test_wopi_host.py diff --git a/roles/web-svc-collabora/vars/main.yml b/roles/web-svc-collabora/vars/main.yml index d37eddc25f..da503f54e2 100644 --- a/roles/web-svc-collabora/vars/main.yml +++ b/roles/web-svc-collabora/vars/main.yml @@ -6,6 +6,6 @@ domain: "{{ lookup('domain',application_id) }}" http_port: "{{ lookup('config', application_id, 'services.collabora.ports.local.http') }}" COLLABORA_CONTAINER: "{{ lookup('config', application_id, 'services.collabora.name') }}" -COLLABORA_WOPI_HOST: "{{ lookup('tls', 'web-app-nextcloud', 'protocols.web') }}://{{ lookup('domain', 'web-app-nextcloud') }}:{{ lookup('tls', 'web-app-nextcloud', - 'ports.web') }}" +COLLABORA_WOPI_HOST: "{{ lookup('tls', lookup('domain', 'web-app-nextcloud'), 'protocols.web') }}://{{ lookup('domain', 'web-app-nextcloud') }}:{{ lookup('tls', lookup('domain', + 'web-app-nextcloud'), 'ports.web') }}" COLLABORA_DISCOVERY_PATH: "/hosting/discovery" diff --git a/tests/unit/python/roles/web-svc-collabora/__init__.py b/tests/unit/python/roles/web-svc-collabora/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-svc-collabora/test_wopi_host.py b/tests/unit/python/roles/web-svc-collabora/test_wopi_host.py new file mode 100644 index 0000000000..1751e10d67 --- /dev/null +++ b/tests/unit/python/roles/web-svc-collabora/test_wopi_host.py @@ -0,0 +1,92 @@ +from __future__ import annotations + +import sys +import unittest +import unittest.mock as mock +from unittest.mock import patch + +from jinja2 import Environment, StrictUndefined, select_autoescape + +import utils.tls_common as _tls_common +from plugins.lookup.tls import LookupModule +from utils.cache.files import PROJECT_ROOT, read_text +from utils.cache.yaml import load_yaml_str +from utils.roles.mapping import ROLE_FILE_VARS_MAIN + +sys.modules.setdefault("ansible.module_utils.tls_common", _tls_common) + +VARS = PROJECT_ROOT / "roles/web-svc-collabora" / ROLE_FILE_VARS_MAIN +NEXTCLOUD_ONION = "next.cloud." + "a" * 56 + ".onion" +COLLABORA_ONION = "collabora." + "a" * 56 + ".onion" + + +def wopi_host(domains: dict[str, list[str]]) -> str: + variables = { + "domains": domains, + "applications": {}, + "TLS_ENABLED": True, + "TLS_MODE": "letsencrypt", + "application_id": "web-svc-collabora", + } + tls = LookupModule() + tls._loader = mock.MagicMock() + + def _get(name, *_args, **_kwargs): + return mock.MagicMock( + run=lambda _terms, variables=None, **_: [(variables or {}).get(name, {})] + ) + + def lookup(name, *terms): + if name == "domain": + return domains[terms[0]][0] + if name == "tls": + return tls.run(list(terms), variables=variables)[0] + raise AssertionError(f"the expression calls an unexpected lookup: {name!r}") + + expression = load_yaml_str(read_text(str(VARS)))["COLLABORA_WOPI_HOST"] + env = Environment( + undefined=StrictUndefined, + autoescape=select_autoescape(default_for_string=False), + ) + with patch("plugins.lookup.tls.lookup_loader") as loader: + loader.get.side_effect = _get + return env.from_string(expression).render(lookup=lookup) + + +class TestWopiHost(unittest.TestCase): + def test_an_onion_primary_nextcloud_beside_a_clearnet_collabora(self): + self.assertEqual( + wopi_host( + { + "web-app-nextcloud": [NEXTCLOUD_ONION, "next.cloud.example"], + "web-svc-collabora": ["collabora.example"], + } + ), + f"http://{NEXTCLOUD_ONION}:80", + ) + + def test_both_apps_behind_tor(self): + self.assertEqual( + wopi_host( + { + "web-app-nextcloud": [NEXTCLOUD_ONION], + "web-svc-collabora": [COLLABORA_ONION], + } + ), + f"http://{NEXTCLOUD_ONION}:80", + ) + + def test_both_apps_on_clearnet(self): + self.assertEqual( + wopi_host( + { + "web-app-nextcloud": ["next.cloud.example"], + "web-svc-collabora": ["collabora.example"], + } + ), + "https://next.cloud.example:443", + ) + + +if __name__ == "__main__": + unittest.main() From 601b21a8f431ebb22085f2130acca0c0593e8bea Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 6 Oct 2026 15:27:48 +0200 Subject: [PATCH 26/53] test(web-app-penpot): require both service names in the start guard The stub answered every absolute name, so a guard that asked for the backend twice and never for the exporter passed both tests. The stub now records the names it is asked for, and the tests require the backend and the exporter. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../roles/web-app-penpot/test_frontend_start_guard.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/unit/python/roles/web-app-penpot/test_frontend_start_guard.py b/tests/unit/python/roles/web-app-penpot/test_frontend_start_guard.py index 66be48898e..bd8eb4c67d 100644 --- a/tests/unit/python/roles/web-app-penpot/test_frontend_start_guard.py +++ b/tests/unit/python/roles/web-app-penpot/test_frontend_start_guard.py @@ -20,6 +20,7 @@ if [[ "${name}" != *. ]]; then \techo "172.30.0.10 ${name}.infinito.test" \texit 0 fi +echo "${name}" >>"${STUB_DIR}/absolute-names" lookups=$(( $(cat "${STUB_DIR}/absolute-lookups" 2>/dev/null || echo 0) + 1 )) echo "${lookups}" >"${STUB_DIR}/absolute-lookups" if [ "${lookups}" -le "${STUB_UNKNOWN_LOOKUPS}" ]; then @@ -77,6 +78,14 @@ class TestFrontendStartGuard(unittest.TestCase): timeout=30, ) self.assertEqual(done.returncode, 0, done.stderr) + names = load_yaml(str(ROLE_DIR / ROLE_FILE_VARS_MAIN)) + self.assertEqual( + set(read_text(str(bin_dir / "absolute-names")).split()), + { + f"{names['PENPOT_BACKEND_SERVICE']}.", + f"{names['PENPOT_EXPORTER_SERVICE']}.", + }, + ) return int(done.stdout) def test_nginx_waits_until_the_services_resolve_without_the_search_domain(self): From c73bc0ca853a38ae3da59b6e4b312e625733507d Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 6 Oct 2026 15:28:37 +0200 Subject: [PATCH 27/53] test(web-app-keycloak): follow every async kcadm result to its reap The guard required a register on every async kcadm job and nothing more. A result that is registered but no longer handed to async_reap_jobs, directly or through the list it is collected into, passed it, although the reap then neither polls that job nor sees it fail. The test now follows each registered result to an async_reap_jobs expression, by variable name with word boundaries, so kc_declared_client does not pass for kc_declared_client_jobs. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../web-app-keycloak/test_async_kcadm_jobs.py | 76 +++++++++++++++++-- 1 file changed, 70 insertions(+), 6 deletions(-) diff --git a/tests/unit/python/roles/web-app-keycloak/test_async_kcadm_jobs.py b/tests/unit/python/roles/web-app-keycloak/test_async_kcadm_jobs.py index f953e61abb..927e3ff774 100644 --- a/tests/unit/python/roles/web-app-keycloak/test_async_kcadm_jobs.py +++ b/tests/unit/python/roles/web-app-keycloak/test_async_kcadm_jobs.py @@ -1,5 +1,6 @@ from __future__ import annotations +import re import unittest from utils.cache.files import PROJECT_ROOT, iter_project_files @@ -7,6 +8,7 @@ from utils.cache.yaml import load_yaml_any TASKS_DIR = str(PROJECT_ROOT / "roles/web-app-keycloak/tasks") + "/" LOCK_RETRYING_MODULE = "keycloak_kcadm_update" +SET_FACT_MODULES = ("set_fact", "ansible.builtin.set_fact") def tasks_of(node): @@ -18,13 +20,48 @@ def tasks_of(node): yield from tasks_of(task.get(nested)) -def async_kcadm_jobs(): +def role_tasks(): for path in iter_project_files(extensions=(".yml",)): - if not path.startswith(TASKS_DIR): - continue - for task in tasks_of(load_yaml_any(path)): - if "async" in task and "kcadm" in str(task).lower(): - yield f"{path[len(TASKS_DIR) :]}: {task.get('name')}", task + if path.startswith(TASKS_DIR): + for task in tasks_of(load_yaml_any(path)): + yield path[len(TASKS_DIR) :], task + + +def async_kcadm_jobs(): + for path, task in role_tasks(): + if "async" in task and "kcadm" in str(task).lower(): + yield f"{path}: {task.get('name')}", task + + +def reaped_expressions() -> list[str]: + return [ + str(task["vars"]["async_reap_jobs"]) + for _path, task in role_tasks() + if "async_reap_jobs" in (task.get("vars") or {}) + ] + + +def collected_facts() -> dict[str, str]: + facts: dict[str, str] = {} + for _path, task in role_tasks(): + for module in SET_FACT_MODULES: + for name, value in (task.get(module) or {}).items(): + facts[name] = str(value) + return facts + + +def names(variable: str, expression: str) -> bool: + return re.search(rf"\b{re.escape(variable)}\b", expression) is not None + + +def reaches_a_reap(result: str, facts: dict[str, str], reaped: list[str]) -> bool: + carriers = [ + result, + *(fact for fact, source in facts.items() if names(result, source)), + ] + return any( + names(carrier, expression) for carrier in carriers for expression in reaped + ) class TestAsyncKcadmJobs(unittest.TestCase): @@ -52,6 +89,33 @@ class TestAsyncKcadmJobs(unittest.TestCase): "sees it fail", ) + def test_every_registered_async_kcadm_result_reaches_a_reap(self): + reaped = reaped_expressions() + facts = collected_facts() + for label, task in async_kcadm_jobs(): + with self.subTest(task=label): + self.assertTrue( + reaches_a_reap(task["register"], facts, reaped), + f"'{task['register']}' is registered and never handed to " + "async_reap_jobs, directly or through a collected list, so the " + "reap neither polls the job nor sees it fail", + ) + + def test_a_result_that_is_never_collected_does_not_reach_the_reap(self): + reaped = ["{{ kc_declared_client_jobs | default([]) }}"] + self.assertFalse(reaches_a_reap("kc_declared_client", {}, reaped)) + self.assertTrue( + reaches_a_reap( + "kc_declared_client", + {"kc_declared_client_jobs": "{{ [kc_declared_client] }}"}, + reaped, + ) + ) + + def test_a_collected_list_that_no_reap_consumes_does_not_count(self): + facts = {"kc_declared_client_jobs": "{{ [kc_declared_client] }}"} + self.assertFalse(reaches_a_reap("kc_declared_client", facts, [])) + if __name__ == "__main__": unittest.main() From 02354506e73c80477f2261b630d8b0830ba03ca4 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 6 Oct 2026 20:45:06 +0200 Subject: [PATCH 28/53] fix(web-app-hugo): build as the image's own user The builder stage switched to root for everything, so npm lifecycle scripts of the site's dependencies and the Hugo build ran as root. The official image runs as hugo and ships Node and npm. Root now only creates /src and /public for that user. npm install and the build run as hugo, and the apk install of nodejs and npm is gone. The README no longer repeats the pinned source tag, which the updater moves in meta/services.yml only. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-hugo/README.md | 8 +------- roles/web-app-hugo/files/Dockerfile | 8 +++++--- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/roles/web-app-hugo/README.md b/roles/web-app-hugo/README.md index bbbbb383c7..9d3a9390a5 100644 --- a/roles/web-app-hugo/README.md +++ b/roles/web-app-hugo/README.md @@ -96,13 +96,7 @@ docker run --rm -it \ ## Configuration -The default configuration in `meta/services.yml` builds the Hugo documentation: - -```yaml -hugo: - source_repository: https://github.com/gohugoio/hugoDocs.git - source_version: v0.148.0 -``` +The default configuration in `meta/services.yml` builds the Hugo documentation from `https://github.com/gohugoio/hugoDocs.git` at the tag pinned as `services.hugo.source_version`. To host your own Hugo site, override `services.hugo.source_repository` and `services.hugo.source_version` in your inventory. Example: diff --git a/roles/web-app-hugo/files/Dockerfile b/roles/web-app-hugo/files/Dockerfile index 0dac73278d..a6ed6eeb13 100644 --- a/roles/web-app-hugo/files/Dockerfile +++ b/roles/web-app-hugo/files/Dockerfile @@ -10,16 +10,18 @@ ARG HUGO_NGINX_IMAGE ARG HUGO_NGINX_VERSION FROM ${HUGO_BUILDER_IMAGE}:${HUGO_BUILDER_VERSION} AS builder -USER root ARG HUGO_BASE_URL ARG HUGO_ENVIRONMENT ARG HUGO_MINIFY +USER root +RUN install -d -o hugo -g hugo /src /public +USER hugo:hugo + WORKDIR /src -COPY ./services/repository/ /src/ +COPY --chown=hugo:hugo ./services/repository/ /src/ -RUN apk add --no-cache nodejs npm RUN set -eu; \ if [ -f package.json ]; then \ npm install --no-audit --no-fund --no-progress; \ From 74193d7152738448f8aafb7550495275940b1395 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 6 Oct 2026 18:45:54 +0200 Subject: [PATCH 29/53] fix(web-app-zammad): keep the search index per Elasticsearch major Elasticsearch 9 does not start on a data directory written by 8.13. It accepts one from 8.19 only. On a deployment that already ran 8.13.4 the new pin left the search container in a restart loop ("cannot upgrade a node from version [8.13.4] directly to version [9.5.5]"), zammad-init kept waiting for it and Zammad did not come up. The index is derived data. zammad-init rebuilds it from the database whenever it is missing. path.data now points to a directory named after the Elasticsearch major inside the zammad_search volume, so a new major starts on an empty directory and the same deploy rebuilds the index. The data of the previous major stays in the volume. The REST ticket test of the spec now also requires the search to return the ticket it has just created. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-zammad/README.md | 1 + .../playwright/test-rest-api-ticket-create.js | 18 +++++++++++++++++- roles/web-app-zammad/templates/compose.yml.j2 | 1 + roles/web-app-zammad/vars/main.yml | 2 ++ 4 files changed, 21 insertions(+), 1 deletion(-) diff --git a/roles/web-app-zammad/README.md b/roles/web-app-zammad/README.md index 164a05ae8d..eb01babf80 100644 --- a/roles/web-app-zammad/README.md +++ b/roles/web-app-zammad/README.md @@ -95,6 +95,7 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( - **Mail-to-ticket:** When `web-app-stalwart` is present, the `helpdesk` mailbox is auto-provisioned and Zammad polls it to create tickets from incoming mail. - **Server-name alias:** `zammad.helpdesk.{{ DOMAIN_PRIMARY }}` is a true vhost alias of `helpdesk.{{ DOMAIN_PRIMARY }}` (not a 301 redirect). - **Bundled Elasticsearch:** Search engine ships with the role until a central `svc-db-elasticsearch` exists. +- **Search index per Elasticsearch major:** The index lives in a directory named after the Elasticsearch major inside the `zammad_search` volume. A new major starts on an empty directory and `zammad-init` rebuilds the index from the database on the same deploy. - **Wizard bypass:** First deploy seeds `auto_wizard.json` so no manual setup UI step is required. ## Quick Setup diff --git a/roles/web-app-zammad/files/playwright/test-rest-api-ticket-create.js b/roles/web-app-zammad/files/playwright/test-rest-api-ticket-create.js index ab1c9b92cd..c103b66368 100644 --- a/roles/web-app-zammad/files/playwright/test-rest-api-ticket-create.js +++ b/roles/web-app-zammad/files/playwright/test-rest-api-ticket-create.js @@ -1,7 +1,8 @@ const { test, expect, request } = require("@playwright/test"); +const { resolveTimeout } = require("./timeouts"); exports.register = function (shared) { - test("administrator: REST API POST /api/v1/tickets creates a ticket", async () => { + test("administrator: REST API POST /api/v1/tickets creates a ticket the search finds", async () => { shared.skipUnlessServiceEnabled("sso"); expect(shared.env.adminApiUsername, "ADMIN_USERNAME must be set").toBeTruthy(); expect(shared.env.adminApiPassword, "ADMIN_PASSWORD must be set").toBeTruthy(); @@ -44,6 +45,21 @@ exports.register = function (shared) { const getResp = await api.get(`${shared.env.zammadBaseUrl}/api/v1/tickets/${created.id}`); expect(getResp.status(), "Created ticket must be GETtable").toBeLessThan(300); + const searchUrl = `${shared.env.zammadBaseUrl}/api/v1/tickets/search?query=${encodeURIComponent(subject)}&limit=5`; + await expect + .poll( + async () => { + const found = await api.get(searchUrl); + const body = found.ok() ? await found.json() : []; + return Array.isArray(body) ? body.map((ticket) => ticket.id) : body.tickets || []; + }, + { + timeout: resolveTimeout(120_000), + message: "the search index must return the ticket that was just created", + }, + ) + .toContain(created.id); + await api.dispose(); }); }; diff --git a/roles/web-app-zammad/templates/compose.yml.j2 b/roles/web-app-zammad/templates/compose.yml.j2 index bc0dc5169e..344af9b7ff 100644 --- a/roles/web-app-zammad/templates/compose.yml.j2 +++ b/roles/web-app-zammad/templates/compose.yml.j2 @@ -55,6 +55,7 @@ - discovery.type=single-node - xpack.security.enabled=false - ES_JAVA_OPTS=-Xms512m -Xmx512m + - path.data={{ ZAMMAD_SEARCH_DATA_DIR }} {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_extra_hosts') | indent(4) }} {{ lookup('container_networks') | indent(4) }} diff --git a/roles/web-app-zammad/vars/main.yml b/roles/web-app-zammad/vars/main.yml index ad45a8f4c8..5edd2392dd 100644 --- a/roles/web-app-zammad/vars/main.yml +++ b/roles/web-app-zammad/vars/main.yml @@ -22,6 +22,8 @@ ZAMMAD_MEMCACHED_CONTAINER: "{{ lookup('engine', 'memcached', application_id, 'c ZAMMAD_RAILS_PORT: "{{ lookup('config', application_id, 'services.' ~ ZAMMAD_RAILS_SERVICE ~ '.ports.internal.http') }}" ZAMMAD_WEBSOCKET_PORT: "{{ lookup('config', application_id, 'services.' ~ ZAMMAD_WEBSOCKET_SERVICE ~ '.ports.internal.http') }}" ZAMMAD_SEARCH_PORT: "{{ lookup('config', application_id, 'services.' ~ ZAMMAD_SEARCH_SERVICE ~ '.ports.internal.http') }}" +ZAMMAD_SEARCH_MAJOR: "{{ (lookup('config', application_id, 'services.search.version') | string).split('.') | first }}" +ZAMMAD_SEARCH_DATA_DIR: "{{ [lookup('volume', application_id, 'zammad_search').target, ZAMMAD_SEARCH_MAJOR] | path_join }}" # Exception: env.j2 must never set DATABASE_URL. The image's config/pre_initializers/database_url.rb # builds it from POSTGRESQL_* only while DATABASE_URL is blank, so presetting it drops From a6a6b783938758bfb4643fa5564f77b57bca1d7d Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Tue, 6 Oct 2026 19:16:07 +0000 Subject: [PATCH 30/53] 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 676af6a455..b60dc775cc 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.35.1 + version: 0.40.0 name: ollama min_storage: 3473MB cpus: "4.0" From bafe9aaecc6311357ca1c86614eb579415eb2a1d Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Tue, 6 Oct 2026 19:16:14 +0000 Subject: [PATCH 31/53] 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 be86d8e07e..cc24f369e8 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.37.0" + version: "v16.50.0" name: erpnext min_storage: 1017MB ports: From f2196a48c0eb2e4782973650affe4ebdcd885e21 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Tue, 6 Oct 2026 19:16:21 +0000 Subject: [PATCH 32/53] update(images): update Docker image versions (web-app-penpot) --- roles/web-app-penpot/meta/services.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/roles/web-app-penpot/meta/services.yml b/roles/web-app-penpot/meta/services.yml index c75856a556..9f9f4ccb1e 100644 --- a/roles/web-app-penpot/meta/services.yml +++ b/roles/web-app-penpot/meta/services.yml @@ -79,7 +79,7 @@ penpot: lifecycle: beta frontend: image: penpotapp/frontend - version: "2.18.1" + version: "2.18.3" name: penpot-frontend cpus: "0.5" mem_reservation: 256m @@ -87,7 +87,7 @@ frontend: pids_limit: 256 backend: image: penpotapp/backend - version: "2.18.1" + version: "2.18.3" name: penpot-backend cpus: "1.0" mem_reservation: 1g @@ -100,7 +100,7 @@ backend: http: 6060 exporter: image: penpotapp/exporter - version: "2.18.1" + version: "2.18.3" name: penpot-exporter cpus: "0.5" mem_reservation: 512m From 9e39388502f3230db54b5a81f14bae02889fcdd6 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Tue, 6 Oct 2026 19:16:31 +0000 Subject: [PATCH 33/53] update(images): update Docker image versions (web-app-socialhome) --- roles/web-app-socialhome/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-socialhome/meta/services.yml b/roles/web-app-socialhome/meta/services.yml index 7992c0a1d8..b2252ea28f 100644 --- a/roles/web-app-socialhome/meta/services.yml +++ b/roles/web-app-socialhome/meta/services.yml @@ -13,7 +13,7 @@ socialhome: # nocheck: default-placement-manager embedded sqlite in a node-local volume; no clustered storage placement: manager image: ghcr.io/social-home-io/socialhome - version: "2026.10.4" + version: "2026.10.6" ports: local: http: 8089 From f60b7ec448fb0f97724734970c2164f09463e308 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Tue, 6 Oct 2026 19:57:10 +0000 Subject: [PATCH 34/53] update(versions): update pins with a declared source (web-app-hugo) --- roles/web-app-hugo/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-hugo/meta/services.yml b/roles/web-app-hugo/meta/services.yml index 6c4954e98d..f2b70dadc4 100644 --- a/roles/web-app-hugo/meta/services.yml +++ b/roles/web-app-hugo/meta/services.yml @@ -35,7 +35,7 @@ hugo: version: 1.31-alpine custom: true builder_image: ghcr.io/gohugoio/hugo - builder_version: v0.165.0 + builder_version: v0.167.0 source_repository: https://github.com/gohugoio/hugoDocs.git source_version: v0.165.0 update: From e203d6f7ab60034a8a2ed3bf67fe7389b62bcf65 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 6 Oct 2026 23:05:26 +0200 Subject: [PATCH 35/53] feat(plugins): size memory parameters from the container limit with one lookup lookup('service_memory_mb', application_id, service_name, share) returns a share of a service's mem_limit in whole MiB. It resolves the limit the way sys-svc-container resolves the container's own: the named service, then the role's primary entity, then RESOURCE_MEM_LIMIT. It replaces the three filters of memory_filters, each with its own unit parser and its own idea of the limit: Redis maxmemory at 0.8 of the limit, and the Confluence and Jira heap at 0.7 and 0.35. The central Redis (409 MiB), Confluence (5734/2867) and Jira (4300/2150) keep their values. A Redis sidecar without a mem_limit of its own does not: the filter fell back to a fixed 256m, which gave 204 MiB, while the lookup takes the limit that container really runs with, the primary entity's. That moves 25 roles to between 409 and 3276 MiB. The heap clamps of the old filters are gone: the 1024 MiB floor, limit minus 1024, the 12288 cap and Xms bounded by mem_reservation. Co-Authored-By: Claude Opus 5.5 (1M context) --- plugins/filter/memory_filters.py | 184 -------------- plugins/lookup/service_memory_mb.py | 106 ++++++++ roles/svc-db-redis/templates/compose.yml.j2 | 2 +- roles/svc-db-redis/templates/service.yml.j2 | 2 +- roles/web-app-confluence/vars/main.yml | 4 +- roles/web-app-jira/vars/main.yml | 4 +- .../plugins/filter/test_memory_filters.py | 234 ------------------ .../plugins/lookup/test_service_memory_mb.py | 101 ++++++++ 8 files changed, 213 insertions(+), 424 deletions(-) delete mode 100644 plugins/filter/memory_filters.py create mode 100644 plugins/lookup/service_memory_mb.py delete mode 100644 tests/unit/python/plugins/filter/test_memory_filters.py create mode 100644 tests/unit/python/plugins/lookup/test_service_memory_mb.py diff --git a/plugins/filter/memory_filters.py b/plugins/filter/memory_filters.py deleted file mode 100644 index e62cdc5df2..0000000000 --- a/plugins/filter/memory_filters.py +++ /dev/null @@ -1,184 +0,0 @@ -from __future__ import annotations - -import re - -from ansible.errors import AnsibleFilterError - -from utils.roles.applications.config import get -from utils.roles.entity.name import get_entity_name - -_UNIT_RE = re.compile(r"^\s*(\d+(?:\.\d+)?)\s*([kKmMgGtT]?[bB]?)?\s*$") -_FACTORS = { - "": 1, - "b": 1, - "k": 1024, - "kb": 1024, - "m": 1024**2, - "mb": 1024**2, - "g": 1024**3, - "gb": 1024**3, - "t": 1024**4, - "tb": 1024**4, -} - -# ------------------------------------------------------ -# Helpers: unit conversion -# ------------------------------------------------------ - - -def _to_bytes(v: str) -> int: - """Convert a human-readable size string (e.g., '2g', '512m') to bytes.""" - if v is None: - raise AnsibleFilterError("memory_filters: size value is None") - - s = str(v).strip() - m = _UNIT_RE.match(s) - if not m: - raise AnsibleFilterError(f"memory_filters: invalid size '{v}'") - - num, unit = m.group(1), (m.group(2) or "").lower() - - try: - val = float(num) - except ValueError as e: - raise AnsibleFilterError(f"memory_filters: invalid numeric size '{v}'") from e - - factor = _FACTORS.get(unit) - if factor is None: - raise AnsibleFilterError(f"memory_filters: unknown unit in '{v}'") - - return int(val * factor) - - -def _to_mb(v: str) -> int: - """Convert human-readable size to megabytes.""" - return max(0, _to_bytes(v) // (1024 * 1024)) - - -# ------------------------------------------------------ -# JVM-specific helpers -# ------------------------------------------------------ - - -def _svc(app_id: str) -> str: - """Resolve the internal service name for JVM-based applications.""" - return get_entity_name(app_id) - - -def _mem_limit_mb(apps: dict, app_id: str) -> int: - """Resolve mem_limit for the JVM service of the given application.""" - svc = _svc(app_id) - raw = get(apps, app_id, f"services.{svc}.mem_limit") - mb = _to_mb(raw) - - if mb <= 0: - raise AnsibleFilterError( - f"memory_filters: mem_limit for '{svc}' must be > 0 MB (got '{raw}')" - ) - return mb - - -def _mem_res_mb(apps: dict, app_id: str) -> int: - """Resolve mem_reservation for the JVM service of the given application.""" - svc = _svc(app_id) - raw = get(apps, app_id, f"services.{svc}.mem_reservation") - mb = _to_mb(raw) - - if mb <= 0: - raise AnsibleFilterError( - f"memory_filters: mem_reservation for '{svc}' must be > 0 MB (got '{raw}')" - ) - return mb - - -def jvm_max_mb(apps: dict, app_id: str) -> int: - """ - Compute recommended JVM Xmx in MB using: - Xmx = min( - floor(0.7 * mem_limit), - mem_limit - 1024, - 12288 - ) - with a lower bound of 1024 MB. - """ - limit_mb = _mem_limit_mb(apps, app_id) - c1 = (limit_mb * 7) // 10 - c2 = max(0, limit_mb - 1024) - c3 = 12288 - - return max(1024, min(c1, c2, c3)) - - -def jvm_min_mb(apps: dict, app_id: str) -> int: - """ - Compute recommended JVM Xms in MB using: - Xms = min( - floor(Xmx / 2), - mem_reservation, - Xmx - ) - with a lower bound of 512 MB. - """ - xmx = jvm_max_mb(apps, app_id) - res = _mem_res_mb(apps, app_id) - - return max(512, min(xmx // 2, res, xmx)) - - -# ------------------------------------------------------ -# Redis-specific helpers (always service name "redis") -# ------------------------------------------------------ - - -def _redis_mem_limit_mb(apps: dict, app_id: str, default_mb: int = 256) -> int: - """ - Resolve mem_limit for the Redis service of an application. - Unlike JVM-based services, Redis always uses the service name "redis". - - If no mem_limit is defined, fall back to default_mb. - """ - raw = get( - apps, - app_id, - "services.redis.mem_limit", - strict=False, - default=f"{default_mb}m", - ) - - mb = _to_mb(raw) - - if mb <= 0: - raise AnsibleFilterError( - f"memory_filters: mem_limit for 'redis' must be > 0 MB (got '{raw}')" - ) - - return mb - - -def redis_maxmemory_mb( - apps: dict, app_id: str, factor: float = 0.8, min_mb: int = 64 -) -> int: - """ - Compute recommended Redis `maxmemory` in MB. - - * factor: fraction of allowed memory used for Redis data (default 0.8) - * min_mb: minimum floor value (default 64 MB) - - maxmemory = max(min_mb, floor(factor * mem_limit)) - """ - limit_mb = _redis_mem_limit_mb(apps, app_id) - return max(min_mb, int(limit_mb * factor)) - - -# ------------------------------------------------------ -# Filter module -# ------------------------------------------------------ - - -class FilterModule: - def filters(self): - return { - "jvm_max_mb": jvm_max_mb, - "jvm_min_mb": jvm_min_mb, - "redis_maxmemory_mb": redis_maxmemory_mb, - } diff --git a/plugins/lookup/service_memory_mb.py b/plugins/lookup/service_memory_mb.py new file mode 100644 index 0000000000..2d2f82786e --- /dev/null +++ b/plugins/lookup/service_memory_mb.py @@ -0,0 +1,106 @@ +"""Derive a memory parameter in MiB from the memory limit of a service's container. + + -Xmx{{ lookup('service_memory_mb', application_id, 'search', 0.5) }}m + memory_limit = {{ lookup('service_memory_mb', application_id, entity_name, 0.5) }}M + +The limit is resolved the way ``sys-svc-container`` resolves the container's own +``mem_limit``: ``services..mem_limit``, then the role's primary entity, +then ``RESOURCE_MEM_LIMIT``. ``share`` is the fraction of that limit the +parameter may claim, so a heap, a cache or a per-request limit follows the +container instead of a literal that drifts away from it. + +Sizes are read like Docker reads them: ``k``, ``m`` and ``g`` are binary, a bare +number is bytes. The result is whole MiB, the unit ``-Xmxm``, PHP ``M``, +``memcached -m``, Redis ``mb`` and PostgreSQL ``MB`` all share. +""" + +from __future__ import annotations + +import re +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +from plugins.filter.resource_filter import resource_filter + +_SIZE = re.compile(r"^\s*(\d+(?:\.\d+)?)\s*([bkmg]?)b?\s*$", re.IGNORECASE) +_FACTOR = {"": 1, "b": 1, "k": 1024, "m": 1024**2, "g": 1024**3} +_MEBIBYTE = 1024**2 +_HOST_DEFAULT = "RESOURCE_MEM_LIMIT" +_UNDECLARED = object() + + +def docker_bytes(size: Any) -> int: + """Return a Docker memory size in bytes. + + Args: + size: a size such as ``2g``, ``1.5g``, ``512m`` or a byte count. + + Raises: + AnsibleError: the size is not a number with an optional b/k/m/g unit. + """ + match = _SIZE.match(str(size)) + if match is None: + raise AnsibleError(f"lookup('service_memory_mb'): unreadable size {size!r}") + return int(float(match.group(1)) * _FACTOR[match.group(2).lower()]) + + +def share_mb(mem_limit: Any, share: Any) -> int: + """Return ``share`` of ``mem_limit`` in whole MiB. + + Args: + mem_limit: Docker size of the container limit, e.g. ``2g`` or ``512m``. + share: fraction of the limit, above 0 and at most 1. + + Raises: + AnsibleError: the share is no fraction in that range, the size is + unreadable, or the result is below 1 MiB. + """ + try: + fraction = float(share) + except (TypeError, ValueError) as exc: + raise AnsibleError( + f"lookup('service_memory_mb'): share {share!r} is not a number" + ) from exc + if not 0 < fraction <= 1: + raise AnsibleError( + f"lookup('service_memory_mb'): share {share!r} must be above 0 and at most 1" + ) + megabytes = int(docker_bytes(mem_limit) * fraction) // _MEBIBYTE + if megabytes < 1: + raise AnsibleError( + f"lookup('service_memory_mb'): {share!r} of {mem_limit!r} is below 1 MiB" + ) + return megabytes + + +class LookupModule(LookupBase): + """lookup('service_memory_mb', application_id, service_name, share)""" + + def run(self, terms, variables: dict[str, Any] | None = None, **kwargs): + if len(terms) != 3: + raise AnsibleError( + "lookup('service_memory_mb', application_id, service_name, share) " + "expects exactly 3 positional terms." + ) + application_id, service_name, share = terms + + templar = self._templar + variables = variables or templar.available_variables + applications = lookup_loader.get( + "applications", loader=self._loader, templar=templar + ).run([], variables=variables)[0] + + mem_limit = resource_filter( + applications, application_id, "mem_limit", service_name, _UNDECLARED + ) + if mem_limit is _UNDECLARED: + if _HOST_DEFAULT not in variables: + raise AnsibleError( + f"lookup('service_memory_mb'): '{application_id}' declares no " + f"mem_limit for '{service_name}' and {_HOST_DEFAULT} is unset" + ) + mem_limit = templar.template(variables[_HOST_DEFAULT]) + return [share_mb(mem_limit, share)] diff --git a/roles/svc-db-redis/templates/compose.yml.j2 b/roles/svc-db-redis/templates/compose.yml.j2 index efdbf2ef51..ce32003147 100644 --- a/roles/svc-db-redis/templates/compose.yml.j2 +++ b/roles/svc-db-redis/templates/compose.yml.j2 @@ -10,7 +10,7 @@ exec redis-server --requirepass {{ REDIS_PASSWORD | quote }} --appendonly yes - --maxmemory {{ lookup('applications') | redis_maxmemory_mb(application_id, 0.8, RESOURCE_MEM_LIMIT | int) }}mb + --maxmemory {{ lookup('service_memory_mb', application_id, service_name, 0.8) }}mb --maxmemory-policy allkeys-lru {% include 'roles/sys-svc-container/templates/base.yml.j2' %} diff --git a/roles/svc-db-redis/templates/service.yml.j2 b/roles/svc-db-redis/templates/service.yml.j2 index e678ee590e..d95e5e21e7 100644 --- a/roles/svc-db-redis/templates/service.yml.j2 +++ b/roles/svc-db-redis/templates/service.yml.j2 @@ -13,7 +13,7 @@ - "no" - --save - "" - - --maxmemory {{ lookup('applications') | redis_maxmemory_mb(application_id, 0.8, RESOURCE_MEM_LIMIT | int ) }}mb + - --maxmemory {{ lookup('service_memory_mb', application_id, 'redis', 0.8) }}mb - --maxmemory-policy - "allkeys-lru" # nocheck: container-healthcheck-literal probes every second, so the SPOT's 5s start cadence would report healthy later than this block already does diff --git a/roles/web-app-confluence/vars/main.yml b/roles/web-app-confluence/vars/main.yml index 2ce263f096..180441ce0b 100644 --- a/roles/web-app-confluence/vars/main.yml +++ b/roles/web-app-confluence/vars/main.yml @@ -25,7 +25,7 @@ CONFLUENCE_VERSION: "{{ lookup('config', application_id, 'services.' ~ entity_na CONFLUENCE_IMAGE: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.image') }}" CONFLUENCE_CONTAINER: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.name') }}" -CONFLUENCE_JVM_MAX: "{{ lookup('applications') | jvm_max_mb(application_id) }}m" -CONFLUENCE_JVM_MIN: "{{ lookup('applications') | jvm_min_mb(application_id) }}m" +CONFLUENCE_JVM_MAX: "{{ lookup('service_memory_mb', application_id, entity_name, 0.7) }}m" +CONFLUENCE_JVM_MIN: "{{ lookup('service_memory_mb', application_id, entity_name, 0.35) }}m" CONFLUENCE_TRUST_STORE_ENABLED: "{{ lookup('config', application_id, 'services.confluence.truststore_enabled') }}" diff --git a/roles/web-app-jira/vars/main.yml b/roles/web-app-jira/vars/main.yml index 1e5fbc3de4..820d9117fb 100644 --- a/roles/web-app-jira/vars/main.yml +++ b/roles/web-app-jira/vars/main.yml @@ -25,5 +25,5 @@ JIRA_VERSION: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ ' JIRA_IMAGE: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.image') }}" JIRA_CONTAINER: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.name') }}" -JIRA_JVM_MAX: "{{ lookup('applications') | jvm_max_mb(application_id) }}m" -JIRA_JVM_MIN: "{{ lookup('applications') | jvm_min_mb(application_id) }}m" +JIRA_JVM_MAX: "{{ lookup('service_memory_mb', application_id, entity_name, 0.7) }}m" +JIRA_JVM_MIN: "{{ lookup('service_memory_mb', application_id, entity_name, 0.35) }}m" diff --git a/tests/unit/python/plugins/filter/test_memory_filters.py b/tests/unit/python/plugins/filter/test_memory_filters.py deleted file mode 100644 index 002eecd3fd..0000000000 --- a/tests/unit/python/plugins/filter/test_memory_filters.py +++ /dev/null @@ -1,234 +0,0 @@ -import importlib -import unittest -from unittest.mock import patch - -memory_filters = importlib.import_module("plugins.filter.memory_filters") - - -class TestMemoryFilters(unittest.TestCase): - def setUp(self): - self.apps = {"whatever": True} - self.app_id = "web-app-confluence" # entity_name will be mocked - - # ----------------------------- - # Helpers - # ----------------------------- - def _with_conf(self, mem_limit: str, mem_res: str): - """ - Patch get/get_entity_name so that mem_limit and mem_reservation - can be controlled in tests. - """ - patches = [ - patch( - "plugins.filter.memory_filters.get_entity_name", - return_value="confluence", - ), - patch( - "plugins.filter.memory_filters.get", - side_effect=lambda apps, app_id, key, required=True, **kwargs: ( - mem_limit - if key.endswith(".mem_limit") - else mem_res - if key.endswith(".mem_reservation") - else None - ), - ), - ] - mocks = [p.start() for p in patches] - self.addCleanup(lambda: [p.stop() for p in patches]) - return mocks - - # ----------------------------- - # Tests: jvm_max_mb / jvm_min_mb sizing - # ----------------------------- - def test_sizing_8g_limit_6g_reservation(self): - self._with_conf("8g", "6g") - xmx = memory_filters.jvm_max_mb(self.apps, self.app_id) - xms = memory_filters.jvm_min_mb(self.apps, self.app_id) - self.assertEqual(xmx, 5734) - self.assertEqual(xms, 2867) - - def test_sizing_6g_limit_4g_reservation(self): - self._with_conf("6g", "4g") - xmx = memory_filters.jvm_max_mb(self.apps, self.app_id) - xms = memory_filters.jvm_min_mb(self.apps, self.app_id) - self.assertEqual(xmx, 4300) - self.assertEqual(xms, 2150) - - def test_sizing_16g_limit_12g_reservation_cap_12288(self): - self._with_conf("16g", "12g") - xmx = memory_filters.jvm_max_mb(self.apps, self.app_id) - xms = memory_filters.jvm_min_mb(self.apps, self.app_id) - self.assertEqual(xmx, 11468) - self.assertEqual(xms, 5734) - - def test_floor_small_limit_results_in_min_1024(self): - self._with_conf("1g", "512m") - xmx = memory_filters.jvm_max_mb(self.apps, self.app_id) - self.assertEqual(xmx, 1024) - - def test_floor_small_reservation_results_in_min_512(self): - self._with_conf("4g", "128m") - xms = memory_filters.jvm_min_mb(self.apps, self.app_id) - self.assertEqual(xms, 512) - - # ----------------------------- - # Tests: JVM failure cases / validation - # ----------------------------- - def test_invalid_unit_raises(self): - with ( - patch( - "plugins.filter.memory_filters.get_entity_name", - return_value="confluence", - ), - patch( - "plugins.filter.memory_filters.get", - side_effect=lambda apps, app_id, key, required=True, **kwargs: ( - "8Q" if key.endswith(".mem_limit") else "4g" - ), - ), - self.assertRaises(memory_filters.AnsibleFilterError), - ): - memory_filters.jvm_max_mb(self.apps, self.app_id) - - def test_zero_limit_raises(self): - with ( - patch( - "plugins.filter.memory_filters.get_entity_name", - return_value="confluence", - ), - patch( - "plugins.filter.memory_filters.get", - side_effect=lambda apps, app_id, key, required=True, **kwargs: ( - "0" if key.endswith(".mem_limit") else "4g" - ), - ), - self.assertRaises(memory_filters.AnsibleFilterError), - ): - memory_filters.jvm_max_mb(self.apps, self.app_id) - - def test_zero_reservation_raises(self): - with ( - patch( - "plugins.filter.memory_filters.get_entity_name", - return_value="confluence", - ), - patch( - "plugins.filter.memory_filters.get", - side_effect=lambda apps, app_id, key, required=True, **kwargs: ( - "8g" if key.endswith(".mem_limit") else "0" - ), - ), - self.assertRaises(memory_filters.AnsibleFilterError), - ): - memory_filters.jvm_min_mb(self.apps, self.app_id) - - def test_entity_name_is_derived_not_passed(self): - """ - Ensure get_entity_name() is called internally and the app_id is not - passed around manually from the template. - """ - with ( - patch( - "plugins.filter.memory_filters.get_entity_name", - return_value="confluence", - ) as mock_entity, - patch( - "plugins.filter.memory_filters.get", - side_effect=lambda apps, app_id, key, required=True, **kwargs: ( - "8g" if key.endswith(".mem_limit") else "6g" - ), - ), - ): - xmx = memory_filters.jvm_max_mb(self.apps, self.app_id) - xms = memory_filters.jvm_min_mb(self.apps, self.app_id) - self.assertGreater(xmx, 0) - self.assertGreater(xms, 0) - self.assertEqual(mock_entity.call_count, 3) - for call in mock_entity.call_args_list: - self.assertEqual(call.args[0], self.app_id) - - # ----------------------------- - # Tests: redis_maxmemory_mb - # ----------------------------- - def test_redis_maxmemory_default_factor_uses_80_percent_of_limit(self): - self._with_conf("1g", "512m") - maxmem = memory_filters.redis_maxmemory_mb(self.apps, self.app_id) - self.assertEqual(maxmem, 819) - - def test_redis_maxmemory_custom_factor_and_min_mb(self): - self._with_conf("1g", "512m") - maxmem = memory_filters.redis_maxmemory_mb( - self.apps, - self.app_id, - factor=0.5, - min_mb=128, - ) - self.assertEqual(maxmem, 512) - - def test_redis_maxmemory_honors_minimum_floor(self): - self._with_conf("32m", "16m") - maxmem = memory_filters.redis_maxmemory_mb(self.apps, self.app_id) - self.assertEqual(maxmem, 64) - - def test_redis_maxmemory_zero_limit_raises(self): - self._with_conf("0", "512m") - with self.assertRaises(memory_filters.AnsibleFilterError): - memory_filters.redis_maxmemory_mb(self.apps, self.app_id) - - def test_redis_maxmemory_invalid_unit_raises(self): - self._with_conf("8Q", "512m") - with self.assertRaises(memory_filters.AnsibleFilterError): - memory_filters.redis_maxmemory_mb(self.apps, self.app_id) - - def test_redis_maxmemory_does_not_call_get_entity_name(self): - """ - Ensure redis_maxmemory_mb does NOT rely on entity name resolution - (it should always use the hard-coded 'redis' service name). - """ - patches = [ - patch("plugins.filter.memory_filters.get_entity_name"), - patch( - "plugins.filter.memory_filters.get", - side_effect=lambda apps, app_id, key, required=True, **kwargs: ( - "4g" if key.endswith(".mem_limit") else "2g" - ), - ), - ] - mocks = [p.start() for p in patches] - self.addCleanup(lambda: [p.stop() for p in patches]) - - entity_mock = mocks[0] - - maxmem = memory_filters.redis_maxmemory_mb(self.apps, self.app_id) - self.assertEqual(maxmem, 3276) - entity_mock.assert_not_called() - - def test_redis_maxmemory_uses_default_when_mem_limit_missing(self): - """ - When services.redis.mem_limit is not configured, the filter - should fall back to its internal default (256m). - """ - - def fake_get(apps, app_id, key, required=True, **kwargs): - if key.endswith(".mem_limit"): - return kwargs.get("default") - return None - - with ( - patch( - "plugins.filter.memory_filters.get", - side_effect=fake_get, - ), - patch( - "plugins.filter.memory_filters.get_entity_name", - return_value="confluence", - ), - ): - maxmem = memory_filters.redis_maxmemory_mb(self.apps, self.app_id) - - self.assertEqual(maxmem, 204) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_service_memory_mb.py b/tests/unit/python/plugins/lookup/test_service_memory_mb.py new file mode 100644 index 0000000000..d8277c6c11 --- /dev/null +++ b/tests/unit/python/plugins/lookup/test_service_memory_mb.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +import unittest +from unittest.mock import MagicMock, patch + +from ansible.errors import AnsibleError + +from plugins.lookup.service_memory_mb import LookupModule, docker_bytes, share_mb + +_APP = "web-app-demo" + + +class TestDockerBytes(unittest.TestCase): + def test_suffixes_are_binary(self) -> None: + self.assertEqual(docker_bytes("512m"), 512 * 1024**2) + self.assertEqual(docker_bytes("2g"), 2 * 1024**3) + self.assertEqual(docker_bytes("1.5g"), 1536 * 1024**2) + self.assertEqual(docker_bytes("64K"), 64 * 1024) + self.assertEqual(docker_bytes("1gb"), 1024**3) + + def test_a_bare_number_is_bytes(self) -> None: + self.assertEqual(docker_bytes(1048576), 1024**2) + self.assertEqual(docker_bytes("2048"), 2048) + + def test_an_unreadable_size_raises(self) -> None: + for size in ("", "lots", "2x", "-1g", None): + with self.subTest(size=size), self.assertRaises(AnsibleError): + docker_bytes(size) + + +class TestShareMb(unittest.TestCase): + def test_share_of_the_limit_in_whole_mebibytes(self) -> None: + cases = ( + ("2g", 0.5, 1024), + ("4g", 0.5, 2048), + ("8g", 0.7, 5734), + ("8g", 0.35, 2867), + ("6g", 0.7, 4300), + ("512m", 0.8, 409), + ("256m", 0.75, 192), + ("1.5g", 0.5, 768), + ("1g", 1, 1024), + ) + for mem_limit, share, expected in cases: + with self.subTest(mem_limit=mem_limit, share=share): + self.assertEqual(share_mb(mem_limit, share), expected) + + def test_a_share_outside_the_limit_raises(self) -> None: + for share in (0, -0.5, 1.01, "half", None): + with self.subTest(share=share), self.assertRaises(AnsibleError): + share_mb("2g", share) + + def test_a_result_below_one_mebibyte_raises(self) -> None: + with self.assertRaises(AnsibleError): + share_mb("1m", 0.5) + + +class TestLookupResolvesTheContainerLimit(unittest.TestCase): + def _run(self, services: dict, variables: dict, terms: list) -> int: + templar = MagicMock() + templar.available_variables = variables + templar.template.side_effect = lambda value: {"{{ HOST }}": "1.5g"}.get( + value, value + ) + applications = MagicMock() + applications.run.return_value = [{_APP: {"services": services}}] + lookup = LookupModule(loader=None, templar=templar) + with patch( + "plugins.lookup.service_memory_mb.lookup_loader.get", + return_value=applications, + ): + return lookup.run(terms, variables=variables)[0] + + def test_the_named_service_wins(self) -> None: + services = {"search": {"mem_limit": "2g"}, "demo": {"mem_limit": "8g"}} + + self.assertEqual(self._run(services, {}, [_APP, "search", 0.5]), 1024) + + def test_the_primary_entity_backs_an_undeclared_service(self) -> None: + services = {"search": {}, "demo": {"mem_limit": "8g"}} + + self.assertEqual(self._run(services, {}, [_APP, "search", 0.5]), 4096) + + def test_the_host_default_backs_an_undeclared_role(self) -> None: + variables = {"RESOURCE_MEM_LIMIT": "{{ HOST }}"} + + self.assertEqual( + self._run({"search": {}}, variables, [_APP, "search", 0.5]), 768 + ) + + def test_no_limit_anywhere_raises(self) -> None: + with self.assertRaises(AnsibleError): + self._run({"search": {}}, {}, [_APP, "search", 0.5]) + + def test_the_term_count_is_checked(self) -> None: + with self.assertRaises(AnsibleError): + self._run({"search": {"mem_limit": "2g"}}, {}, [_APP, "search"]) + + +if __name__ == "__main__": + unittest.main() From 0f7fb92e1270807d77b9976ad0dc874927094bae Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 6 Oct 2026 23:24:22 +0200 Subject: [PATCH 36/53] refactor(roles): take seven roles' memory parameters from the container limit Memcached, Joomla, Moodle, Odoo, Shopware, Snipe-IT and SuiteCRM set their cache size, PHP memory_limit, OPcache, worker limits and search heap as literals next to a mem_limit they never read. They now ask lookup('service_memory_mb') for a share of that limit. The shares are chosen so every rendered value stays what it was. Where the parameter lives in a file that cannot hold a template, the value is handed in: Shopware's init script reads INIT_PHP_MEMORY_LIMIT and refuses to start without it, SuiteCRM's image takes it as a build argument. Shopware's worker gets --memory-limit as a command appended to its entrypoint, and Moodle's OPcache size moves from the static ini into the rendered one. The performance.php.memory_limit keys of Joomla and Moodle are gone from services.yml; nothing else read them. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/svc-db-memcached/templates/compose.yml.j2 | 5 +---- roles/svc-db-memcached/vars/main.yml | 2 +- roles/web-app-joomla/meta/services.yml | 3 --- roles/web-app-joomla/tasks/08_oidc_plugin.yml | 8 ++++---- roles/web-app-joomla/vars/main.yml | 2 +- .../files/build/php-conf/opcache-recommended.ini | 1 - roles/web-app-moodle/meta/services.yml | 1 - .../templates/build/php-conf/moodle-runtime.ini.j2 | 1 + roles/web-app-moodle/vars/main.yml | 2 +- roles/web-app-odoo/templates/odoo.conf.j2 | 4 ++-- roles/web-app-shopware/files/shell/init.sh | 9 +++++---- roles/web-app-shopware/meta/services.yml | 1 - roles/web-app-shopware/templates/compose.yml.j2 | 5 ++++- roles/web-app-shopware/vars/main.yml | 2 +- roles/web-app-snipe-it/tasks/01_install.yml | 2 +- roles/web-app-suitecrm/files/Dockerfile | 5 +++-- roles/web-app-suitecrm/templates/compose.yml.j2 | 1 + roles/web-app-suitecrm/vars/main.yml | 1 + 18 files changed, 27 insertions(+), 28 deletions(-) diff --git a/roles/svc-db-memcached/templates/compose.yml.j2 b/roles/svc-db-memcached/templates/compose.yml.j2 index 1b3883ec84..687ed7e2b7 100644 --- a/roles/svc-db-memcached/templates/compose.yml.j2 +++ b/roles/svc-db-memcached/templates/compose.yml.j2 @@ -3,10 +3,7 @@ {{ service_name }}: {{ lookup('compose_only', 'container_name', MEMCACHED_CONTAINER) }} {{ lookup('container_image', application_id, 'memcached') }} - command: - - "memcached" - - "-m" - - "{{ MEMCACHED_MEMORY_LIMIT_MB }}" + command: ["memcached", "-m", "{{ MEMCACHED_MEMORY_LIMIT_MB }}"] {% include 'roles/sys-svc-container/templates/base.yml.j2' %} {% if MEMCACHED_EXPOSE_LOCAL %} diff --git a/roles/svc-db-memcached/vars/main.yml b/roles/svc-db-memcached/vars/main.yml index 3066f45915..9294151ce2 100644 --- a/roles/svc-db-memcached/vars/main.yml +++ b/roles/svc-db-memcached/vars/main.yml @@ -10,6 +10,6 @@ MEMCACHED_EXPOSE_LOCAL: true MEMCACHED_LOCAL_HOST: "127.0.0.1" MEMCACHED_RETRIES: 5 MEMCACHED_DELAY: 5 -MEMCACHED_MEMORY_LIMIT_MB: 192 +MEMCACHED_MEMORY_LIMIT_MB: "{{ lookup('service_memory_mb', application_id, entity_name, 0.75) }}" MEMCACHED_EXEC_SHELL: "container exec {{ MEMCACHED_CONTAINER_ADDRESS }} sh -lc" MEMCACHED_PROBE: "printf \"version\\r\\n\" | nc -w 1 {{ MEMCACHED_LOCAL_HOST }} 11211 | grep -q VERSION" diff --git a/roles/web-app-joomla/meta/services.yml b/roles/web-app-joomla/meta/services.yml index 46483ce2ee..282f2caffb 100644 --- a/roles/web-app-joomla/meta/services.yml +++ b/roles/web-app-joomla/meta/services.yml @@ -51,9 +51,6 @@ joomla: no_stop_required: true upload: size_mb: 100 - performance: - php: - memory_limit: 512M autocreate_users: true ports: local: diff --git a/roles/web-app-joomla/tasks/08_oidc_plugin.yml b/roles/web-app-joomla/tasks/08_oidc_plugin.yml index 9c04694812..037239a96c 100644 --- a/roles/web-app-joomla/tasks/08_oidc_plugin.yml +++ b/roles/web-app-joomla/tasks/08_oidc_plugin.yml @@ -53,7 +53,7 @@ - name: "📦 Install plg_system_keycloak via Joomla CLI" ansible.builtin.shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node container exec --user {{ JOOMLA_WEB_USER | quote }} {{ JOOMLA_LOCAL_CID | quote }} - php -d memory_limit=512M {{ JOOMLA_CLI_FILE | quote }} + php -d memory_limit={{ JOOMLA_PHP_MEMORY_LIMIT }} {{ JOOMLA_CLI_FILE | quote }} extension:install --path={{ JOOMLA_OIDC_PLUGIN_ZIP | quote }} register: plugin_install changed_when: "'Extension installed successfully' in plugin_install.stdout" @@ -63,8 +63,8 @@ delegate_to: "{{ JOOMLA_HOST_NODE }}" - name: "🔍 Resolve plg_system_keycloak extension ID" # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node - ansible.builtin.shell: "container exec --user {{ JOOMLA_WEB_USER }} {{ JOOMLA_LOCAL_CID | quote }} php -d memory_limit=512M {{ JOOMLA_CLI_FILE }} extension:list - | awk '/plg_system_keycloak/ {print $2; exit}'" + ansible.builtin.shell: "container exec --user {{ JOOMLA_WEB_USER }} {{ JOOMLA_LOCAL_CID | quote }} php -d memory_limit={{ JOOMLA_PHP_MEMORY_LIMIT }} {{ JOOMLA_CLI_FILE + }} extension:list | awk '/plg_system_keycloak/ {print $2; exit}'" register: plugin_id_lookup changed_when: false failed_when: plugin_id_lookup.stdout | trim | length == 0 @@ -73,7 +73,7 @@ - name: "🟢 Enable plg_system_keycloak via Joomla CLI" ansible.builtin.shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node container exec --user {{ JOOMLA_WEB_USER | quote }} {{ JOOMLA_LOCAL_CID | quote }} - php -d memory_limit=512M {{ JOOMLA_CLI_FILE | quote }} + php -d memory_limit={{ JOOMLA_PHP_MEMORY_LIMIT }} {{ JOOMLA_CLI_FILE | quote }} extension:enable {{ plugin_id_lookup.stdout | trim | quote }} register: plugin_enable changed_when: "'has been enabled' in plugin_enable.stdout or 'enabled successfully' in plugin_enable.stdout" diff --git a/roles/web-app-joomla/vars/main.yml b/roles/web-app-joomla/vars/main.yml index c7d2ddee5a..a8b0f5d4ae 100644 --- a/roles/web-app-joomla/vars/main.yml +++ b/roles/web-app-joomla/vars/main.yml @@ -23,7 +23,7 @@ JOOMLA_UPLOAD_CONFIG: "{{ [ lookup('container', application_id, 'directories.ins JOOMLA_UPLOAD_SIZE: "{{ lookup('config', application_id, 'services.joomla.upload.size_mb') }}" JOOMLA_UPLOAD_MAX_FILESIZE: "{{ (JOOMLA_UPLOAD_SIZE | int) }}M" JOOMLA_POST_MAX_SIZE: "{{ ((JOOMLA_UPLOAD_SIZE | int) * 12 // 10) }}M" -JOOMLA_PHP_MEMORY_LIMIT: "{{ lookup('config', application_id, 'services.joomla.performance.php.memory_limit') }}" +JOOMLA_PHP_MEMORY_LIMIT: "{{ lookup('service_memory_mb', application_id, entity_name, 0.5) }}M" JOOMLA_USER_NAME: "{{ lookup('users', 'administrator').username }}" JOOMLA_USER: "{{ JOOMLA_USER_NAME | capitalize }}" diff --git a/roles/web-app-moodle/files/build/php-conf/opcache-recommended.ini b/roles/web-app-moodle/files/build/php-conf/opcache-recommended.ini index be3fc9f5dc..6271cf8344 100644 --- a/roles/web-app-moodle/files/build/php-conf/opcache-recommended.ini +++ b/roles/web-app-moodle/files/build/php-conf/opcache-recommended.ini @@ -1,4 +1,3 @@ -opcache.memory_consumption=256 opcache.interned_strings_buffer=16 opcache.max_accelerated_files=20000 opcache.revalidate_freq=60 diff --git a/roles/web-app-moodle/meta/services.yml b/roles/web-app-moodle/meta/services.yml index 70f66d0f48..908536fd0f 100644 --- a/roles/web-app-moodle/meta/services.yml +++ b/roles/web-app-moodle/meta/services.yml @@ -65,7 +65,6 @@ moodle: site_titel: Academy on {{ DOMAIN_PRIMARY }} performance: php: - memory_limit: 512M upload_max_filesize: 256M post_max_size: 256M ports: diff --git a/roles/web-app-moodle/templates/build/php-conf/moodle-runtime.ini.j2 b/roles/web-app-moodle/templates/build/php-conf/moodle-runtime.ini.j2 index 2b8afa62a3..8eb37db7bc 100644 --- a/roles/web-app-moodle/templates/build/php-conf/moodle-runtime.ini.j2 +++ b/roles/web-app-moodle/templates/build/php-conf/moodle-runtime.ini.j2 @@ -1,4 +1,5 @@ memory_limit={{ MOODLE_PHP_MEMORY_LIMIT }} +opcache.memory_consumption={{ lookup('service_memory_mb', application_id, 'moodle', 0.125) }} upload_max_filesize={{ MOODLE_PHP_UPLOAD_MAX_FILESIZE }} post_max_size={{ MOODLE_PHP_POST_MAX_SIZE }} max_execution_time={{ MOODLE_PHP_MAX_EXECUTION_TIME }} diff --git a/roles/web-app-moodle/vars/main.yml b/roles/web-app-moodle/vars/main.yml index 786edc0c15..75cfd20cbc 100644 --- a/roles/web-app-moodle/vars/main.yml +++ b/roles/web-app-moodle/vars/main.yml @@ -130,7 +130,7 @@ MOODLE_SITE_TITLE: "{{ lookup('config', application_id, 'services.moodle.site_ti MOODLE_FPM_PORT: "{{ lookup('config', application_id, 'services.moodle.ports.internal.fpm') }}" MOODLE_NGINX_PORT: "{{ lookup('config', application_id, 'services.moodle.ports.internal.http') }}" -MOODLE_PHP_MEMORY_LIMIT: "{{ lookup('config', application_id, 'services.moodle.performance.php.memory_limit') }}" +MOODLE_PHP_MEMORY_LIMIT: "{{ lookup('service_memory_mb', application_id, 'moodle', 0.25) }}M" MOODLE_PHP_UPLOAD_MAX_FILESIZE: "{{ lookup('config', application_id, 'services.moodle.performance.php.upload_max_filesize') }}" MOODLE_PHP_POST_MAX_SIZE: "{{ lookup('config', application_id, 'services.moodle.performance.php.post_max_size') }}" MOODLE_PHP_MAX_EXECUTION_TIME: "300" diff --git a/roles/web-app-odoo/templates/odoo.conf.j2 b/roles/web-app-odoo/templates/odoo.conf.j2 index f1d2487621..71f4837ed4 100644 --- a/roles/web-app-odoo/templates/odoo.conf.j2 +++ b/roles/web-app-odoo/templates/odoo.conf.j2 @@ -28,8 +28,8 @@ gevent_port = {{ container_websocket_port }} proxy_mode = True workers = 4 max_cron_threads = 2 -limit_memory_hard = 2684354560 -limit_memory_soft = 2147483648 +limit_memory_hard = {{ (lookup('service_memory_mb', application_id, 'odoo', 0.625) | int) * 1048576 }} +limit_memory_soft = {{ (lookup('service_memory_mb', application_id, 'odoo', 0.5) | int) * 1048576 }} limit_time_cpu = 600 limit_time_real = 1200 limit_time_real_cron = 600 diff --git a/roles/web-app-shopware/files/shell/init.sh b/roles/web-app-shopware/files/shell/init.sh index 4a7383182a..f758352a92 100644 --- a/roles/web-app-shopware/files/shell/init.sh +++ b/roles/web-app-shopware/files/shell/init.sh @@ -11,6 +11,7 @@ APP_ROOT="/var/www/html" MARKER="$APP_ROOT/.infinito/installed" LOG_PREFIX="[INIT]" PHP_BIN="php" +PHP_MEMORY_LIMIT="${INIT_PHP_MEMORY_LIMIT:?INIT_PHP_MEMORY_LIMIT must be set}" log() { printf "%s %s\n" "$LOG_PREFIX" "$1"; } fail() { printf "%s [ERROR] %s\n" "$LOG_PREFIX" "$1" >&2; exit 1; } @@ -104,18 +105,18 @@ fi if [ "$FIRST_INSTALL" -eq 1 ]; then log "Performing first-time Shopware installation..." - $PHP_BIN -d memory_limit=1024M bin/console system:install --basic-setup --create-database + $PHP_BIN -d memory_limit="$PHP_MEMORY_LIMIT" bin/console system:install --basic-setup --create-database log "Locking the 'admin' account that --basic-setup creates with the published default password..." DEFAULT_ADMIN_PASSWORD="$($PHP_BIN -r 'echo bin2hex(random_bytes(32));')" - $PHP_BIN -d memory_limit=1024M bin/console user:change-password admin \ + $PHP_BIN -d memory_limit="$PHP_MEMORY_LIMIT" bin/console user:change-password admin \ --password="$DEFAULT_ADMIN_PASSWORD" mkdir -p "$(dirname "$MARKER")" : > "$MARKER" fi log "Running database migrations..." -$PHP_BIN -d memory_limit=1024M bin/console database:migrate --all -$PHP_BIN -d memory_limit=1024M bin/console database:migrate-destructive --all +$PHP_BIN -d memory_limit="$PHP_MEMORY_LIMIT" bin/console database:migrate --all +$PHP_BIN -d memory_limit="$PHP_MEMORY_LIMIT" bin/console database:migrate-destructive --all log "Rebuilding caches and assets..." $PHP_BIN bin/console cache:clear diff --git a/roles/web-app-shopware/meta/services.yml b/roles/web-app-shopware/meta/services.yml index 6aeca33839..2e31a7bd76 100644 --- a/roles/web-app-shopware/meta/services.yml +++ b/roles/web-app-shopware/meta/services.yml @@ -99,7 +99,6 @@ worker: - async - low_priority - --time-limit=300 - - --memory-limit=512M cpus: 1.0 mem_reservation: 1g mem_limit: 2g diff --git a/roles/web-app-shopware/templates/compose.yml.j2 b/roles/web-app-shopware/templates/compose.yml.j2 index 7ee84b255d..2f4f6a2497 100644 --- a/roles/web-app-shopware/templates/compose.yml.j2 +++ b/roles/web-app-shopware/templates/compose.yml.j2 @@ -12,6 +12,8 @@ x-environment: &shopware {{ lookup('compose_only', 'container_name', SHOPWARE_INIT_CONTAINER) }} entrypoint: [ "sh", "{{ SHOPWARE_INIT_DOCKER }}" ] user: "0:0" + environment: + INIT_PHP_MEMORY_LIMIT: "{{ lookup('service_memory_mb', application_id, service_name, 0.5) }}M" {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_networks') | indent(4) }} @@ -53,6 +55,7 @@ x-environment: &shopware <<: *shopware {{ lookup('compose_only', 'container_name', SHOPWARE_WORKER_CONTAINER) }} entrypoint: {{ SHOPWARE_WORKER_ENTRYPOINT }} + command: ["--memory-limit={{ lookup('service_memory_mb', application_id, service_name, 0.25) }}M"] {{ lookup('depends_on', {'init': 'service_completed_successfully'}) }} {{ lookup('container_healthcheck', service_name) | indent(4) }} {{ lookup('container_volumes', service_name) | indent(4) }} @@ -82,7 +85,7 @@ x-environment: &shopware - discovery.type=single-node - plugins.security.disabled=true - bootstrap.memory_lock=true - - OPENSEARCH_JAVA_OPTS=-Xms{{ SHOPWARE_OPENSEARCH_MEM_RESERVATION }} -Xmx{{ SHOPWARE_OPENSEARCH_MEM_RESERVATION }} + - OPENSEARCH_JAVA_OPTS=-Xms{{ SHOPWARE_OPENSEARCH_HEAP_MB }}m -Xmx{{ SHOPWARE_OPENSEARCH_HEAP_MB }}m ulimits: memlock: { soft: -1, hard: -1 } {{ lookup('depends_on', {'init': 'service_completed_successfully'}) }} diff --git a/roles/web-app-shopware/vars/main.yml b/roles/web-app-shopware/vars/main.yml index a60d6a404d..3a5fedff4a 100644 --- a/roles/web-app-shopware/vars/main.yml +++ b/roles/web-app-shopware/vars/main.yml @@ -44,7 +44,7 @@ SHOPWARE_REDIS_URL: "{{ lookup('engine', 'redis', application_id, 'url') }}" SHOPWARE_OPENSEARCH_PORT: "{{ lookup('config', application_id, 'services.opensearch.ports.internal.http') }}" SHOPWARE_OPENSEARCH_ENABLED: "{{ lookup('config', application_id, 'services.opensearch.enabled') }}" SHOPWARE_OPENSEARCH_CONTAINER: "{{ lookup('config', application_id, 'services.opensearch.name') }}" -SHOPWARE_OPENSEARCH_MEM_RESERVATION: "{{ lookup('config', application_id, 'services.opensearch.mem_reservation') }}" +SHOPWARE_OPENSEARCH_HEAP_MB: "{{ lookup('service_memory_mb', application_id, 'opensearch', 0.5) }}" SHOPWARE_OPENSEARCH_INITIAL_ADMIN_PASSWORD: "{{ lookup('config', application_id, 'secrets.credentials.opensearch_initial_admin_password') }}" swarm_stack_fatal_grace: 600 diff --git a/roles/web-app-snipe-it/tasks/01_install.yml b/roles/web-app-snipe-it/tasks/01_install.yml index e7dad621e8..ffe2af0b82 100644 --- a/roles/web-app-snipe-it/tasks/01_install.yml +++ b/roles/web-app-snipe-it/tasks/01_install.yml @@ -41,7 +41,7 @@ -e APP_KEY="{{ SNIPE_IT_APP_KEY }}" -e XDG_CONFIG_HOME=/tmp {{ SNIPE_IT_CONTAINER_ADDRESS }} - php -d memory_limit=512M artisan db:seed --force + php -d memory_limit={{ lookup('service_memory_mb', application_id, SNIPE_IT_SERVICE, 0.25) }}M artisan db:seed --force register: snipeit_seed changed_when: "'Seeding:' in snipeit_seed.stdout" failed_when: snipeit_seed.rc != 0 diff --git a/roles/web-app-suitecrm/files/Dockerfile b/roles/web-app-suitecrm/files/Dockerfile index cab3b11d0f..681672774b 100644 --- a/roles/web-app-suitecrm/files/Dockerfile +++ b/roles/web-app-suitecrm/files/Dockerfile @@ -4,6 +4,7 @@ ARG SUITECRM_BASE_VERSION FROM ${SUITECRM_BASE_IMAGE}:${SUITECRM_BASE_VERSION} AS base ARG SUITECRM_APP_DIR +ARG SUITECRM_PHP_MEMORY_LIMIT RUN rm -rf /var/lib/apt/lists/* \ && apt-get -o Acquire::Retries=3 update && apt-get -o Acquire::Retries=3 install -y \ @@ -31,11 +32,11 @@ RUN rm -rf /var/lib/apt/lists/* \ ldap \ && rm -rf /var/lib/apt/lists/* -RUN { \ +RUN : "${SUITECRM_PHP_MEMORY_LIMIT:?}" && { \ echo 'file_uploads = On'; \ echo 'upload_max_filesize = 32M'; \ echo 'post_max_size = 32M'; \ - echo 'memory_limit = 512M'; \ + echo "memory_limit = ${SUITECRM_PHP_MEMORY_LIMIT}"; \ } > /usr/local/etc/php/conf.d/suitecrm-upload.ini RUN a2enmod rewrite headers diff --git a/roles/web-app-suitecrm/templates/compose.yml.j2 b/roles/web-app-suitecrm/templates/compose.yml.j2 index d0ce7a9b64..62057023e5 100644 --- a/roles/web-app-suitecrm/templates/compose.yml.j2 +++ b/roles/web-app-suitecrm/templates/compose.yml.j2 @@ -10,6 +10,7 @@ SUITECRM_ENTRYPOINT_SCRIPT_DOCKER: "{{ SUITECRM_ENTRYPOINT_SCRIPT_DOCKER }}" SUITECRM_LDAP_EXTENSION_DIR: "{{ SUITECRM_LDAP_EXTENSION_DIR }}" SUITECRM_APP_DIR: "{{ SUITECRM_APP_DIR }}" + SUITECRM_PHP_MEMORY_LIMIT: "{{ SUITECRM_PHP_MEMORY_LIMIT }}" SUITECRM_SEED_DIR: "{{ SUITECRM_SEED_DIR }}" SUITECRM_WEB_USER: "{{ SUITECRM_WEB_USER }}" SUITECRM_WEB_GROUP: "{{ SUITECRM_WEB_GROUP }}" diff --git a/roles/web-app-suitecrm/vars/main.yml b/roles/web-app-suitecrm/vars/main.yml index f87c7b5368..fca35e9cd1 100644 --- a/roles/web-app-suitecrm/vars/main.yml +++ b/roles/web-app-suitecrm/vars/main.yml @@ -39,3 +39,4 @@ SUITECRM_ENTRYPOINT_SCRIPT_HOST_REL: "volumes/{{ SUITECRM_ENTRYPOINT_SCRIPT_FILE SUITECRM_ENTRYPOINT_SCRIPT_DOCKER: "{{ [ '/usr/local/bin/', SUITECRM_ENTRYPOINT_SCRIPT_FILE ] | path_join }}" SUITECRM_MAX_OLD_SPACE_SIZE: "{{ lookup('node_max_old_space_size', application_id, entity_name) }}" +SUITECRM_PHP_MEMORY_LIMIT: "{{ lookup('service_memory_mb', application_id, entity_name, 0.25) }}M" From a7db89ac0b33677acc956338126f817ffd4d2ae6 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 6 Oct 2026 23:31:14 +0200 Subject: [PATCH 37/53] fix(search): give the search engines half of their container as heap The central Elasticsearch, Zammad's Elasticsearch and Magento's OpenSearch ran with a literal heap beside a mem_limit four times its size: 1g in 4g, 512m in 2g and 512m in 2g. The heap is now half of the limit through lookup('service_memory_mb'), which makes it 2048, 1024 and 1024 MiB and lets it follow the limit when that changes. Xms equals Xmx, so these containers hold that much more memory from the start. Zammad's memcached size and Magento's PHP_MEMORY_LIMIT take the same lookup and keep their values, 256 and 768M. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/svc-db-elasticsearch/templates/env.j2 | 2 +- roles/svc-db-elasticsearch/vars/main.yml | 1 + roles/web-app-magento/templates/compose.yml.j2 | 2 +- roles/web-app-magento/templates/env.j2 | 2 +- roles/web-app-magento/vars/main.yml | 1 + roles/web-app-zammad/templates/compose.yml.j2 | 4 ++-- roles/web-app-zammad/vars/main.yml | 1 + 7 files changed, 8 insertions(+), 5 deletions(-) diff --git a/roles/svc-db-elasticsearch/templates/env.j2 b/roles/svc-db-elasticsearch/templates/env.j2 index 40b5ca2cc8..e3160aa57f 100644 --- a/roles/svc-db-elasticsearch/templates/env.j2 +++ b/roles/svc-db-elasticsearch/templates/env.j2 @@ -6,4 +6,4 @@ xpack.security.enabled=true xpack.security.http.ssl.enabled=false xpack.security.transport.ssl.enabled=false bootstrap.memory_lock=true -ES_JAVA_OPTS=-Xms1g -Xmx1g +ES_JAVA_OPTS=-Xms{{ ELASTICSEARCH_HEAP_MB }}m -Xmx{{ ELASTICSEARCH_HEAP_MB }}m diff --git a/roles/svc-db-elasticsearch/vars/main.yml b/roles/svc-db-elasticsearch/vars/main.yml index af2430a228..874f6021e9 100644 --- a/roles/svc-db-elasticsearch/vars/main.yml +++ b/roles/svc-db-elasticsearch/vars/main.yml @@ -10,6 +10,7 @@ ELASTICSEARCH_PASSWORD: "{{ lookup('config', application_id, 'secrets.credential ELASTICSEARCH_EXPOSE_LOCAL: true ELASTICSEARCH_LOCAL_HOST: "127.0.0.1" ELASTICSEARCH_INTERNAL_PORT: "{{ lookup('config', application_id, 'services.elasticsearch.ports.internal.elasticsearch') }}" +ELASTICSEARCH_HEAP_MB: "{{ lookup('service_memory_mb', application_id, entity_name, 0.5) }}" ELASTICSEARCH_RETRIES: 5 ELASTICSEARCH_DELAY: 2 ELASTICSEARCH_API_BASE: "http://{{ ELASTICSEARCH_LOCAL_HOST }}:{{ ELASTICSEARCH_INTERNAL_PORT }}" diff --git a/roles/web-app-magento/templates/compose.yml.j2 b/roles/web-app-magento/templates/compose.yml.j2 index 8ab9ce649d..74e909bc1e 100644 --- a/roles/web-app-magento/templates/compose.yml.j2 +++ b/roles/web-app-magento/templates/compose.yml.j2 @@ -39,7 +39,7 @@ environment: - discovery.type=single-node - plugins.security.disabled=true - - OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m + - OPENSEARCH_JAVA_OPTS=-Xms{{ MAGENTO_SEARCH_HEAP_MB }}m -Xmx{{ MAGENTO_SEARCH_HEAP_MB }}m {{ lookup('container_healthcheck', service_name) | indent(4) }} {{ lookup('container_extra_hosts') | indent(4) }} {{ lookup('container_networks') | indent(4) }} diff --git a/roles/web-app-magento/templates/env.j2 b/roles/web-app-magento/templates/env.j2 index 2de3c20154..e75d1eeab5 100644 --- a/roles/web-app-magento/templates/env.j2 +++ b/roles/web-app-magento/templates/env.j2 @@ -41,6 +41,6 @@ MAGENTO_REMOTE_STORAGE_REGION={{ lookup('objstore', application_id, 'region') }} MAGENTO_REMOTE_STORAGE_PATH_STYLE=1 {% endif %} -PHP_MEMORY_LIMIT=768M +PHP_MEMORY_LIMIT={{ lookup('service_memory_mb', application_id, 'php', 0.75) }}M APACHE_SERVERNAME={{ MAGENTO_DOMAIN }} diff --git a/roles/web-app-magento/vars/main.yml b/roles/web-app-magento/vars/main.yml index d420819050..b251597964 100644 --- a/roles/web-app-magento/vars/main.yml +++ b/roles/web-app-magento/vars/main.yml @@ -19,6 +19,7 @@ MAGENTO_PHP_FPM_CONF_PATH: "{{ [ lookup('container', application_id, 'directorie MAGENTO_OBJSTORE_ENABLED: "{{ lookup('objstore', application_id, 'enabled') }}" MAGENTO_SEARCH_CONTAINER: "{{ lookup('config', application_id, 'services.search.name') }}" +MAGENTO_SEARCH_HEAP_MB: "{{ lookup('service_memory_mb', application_id, 'search', 0.5) }}" MAGENTO_PHP_CONTAINER: "{{ lookup('config', application_id, 'services.php.name') }}" MAGENTO_PHP_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, 'php') }}" diff --git a/roles/web-app-zammad/templates/compose.yml.j2 b/roles/web-app-zammad/templates/compose.yml.j2 index bc0dc5169e..0f22322e40 100644 --- a/roles/web-app-zammad/templates/compose.yml.j2 +++ b/roles/web-app-zammad/templates/compose.yml.j2 @@ -54,7 +54,7 @@ environment: - discovery.type=single-node - xpack.security.enabled=false - - ES_JAVA_OPTS=-Xms512m -Xmx512m + - ES_JAVA_OPTS=-Xms{{ ZAMMAD_SEARCH_HEAP_MB }}m -Xmx{{ ZAMMAD_SEARCH_HEAP_MB }}m {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_extra_hosts') | indent(4) }} {{ lookup('container_networks') | indent(4) }} @@ -65,7 +65,7 @@ {{ lookup('container_image', 'svc-db-memcached', 'memcached') }} {{ lookup('compose_only', 'container_name', ZAMMAD_MEMCACHED_CONTAINER) }} {% include 'roles/sys-svc-container/templates/base.yml.j2' %} - command: ["memcached", "-m", "256"] + command: ["memcached", "-m", "{{ lookup('service_memory_mb', application_id, service_name, 0.125) }}"] {{ lookup('container_extra_hosts') | indent(4) }} {{ lookup('container_networks') | indent(4) }} {% endif %} diff --git a/roles/web-app-zammad/vars/main.yml b/roles/web-app-zammad/vars/main.yml index ad45a8f4c8..e7fbc345d1 100644 --- a/roles/web-app-zammad/vars/main.yml +++ b/roles/web-app-zammad/vars/main.yml @@ -22,6 +22,7 @@ ZAMMAD_MEMCACHED_CONTAINER: "{{ lookup('engine', 'memcached', application_id, 'c ZAMMAD_RAILS_PORT: "{{ lookup('config', application_id, 'services.' ~ ZAMMAD_RAILS_SERVICE ~ '.ports.internal.http') }}" ZAMMAD_WEBSOCKET_PORT: "{{ lookup('config', application_id, 'services.' ~ ZAMMAD_WEBSOCKET_SERVICE ~ '.ports.internal.http') }}" ZAMMAD_SEARCH_PORT: "{{ lookup('config', application_id, 'services.' ~ ZAMMAD_SEARCH_SERVICE ~ '.ports.internal.http') }}" +ZAMMAD_SEARCH_HEAP_MB: "{{ lookup('service_memory_mb', application_id, ZAMMAD_SEARCH_SERVICE, 0.5) }}" # Exception: env.j2 must never set DATABASE_URL. The image's config/pre_initializers/database_url.rb # builds it from POSTGRESQL_* only while DATABASE_URL is blank, so presetting it drops From e6be88bf9714bb768d3c7b406e02476cb5d24ca8 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 7 Oct 2026 01:28:43 +0200 Subject: [PATCH 38/53] fix(postgres): size the buffers from the Postgres container, in its own role shared_buffers, work_mem and maintenance_work_mem were a quarter, half and a twentieth of the host's RAM, while the Postgres container is limited to 6g. On a 64 GB host that asked for 15997 MB of shared buffers inside it. They are now the same shares of the container's mem_limit through lookup('service_memory_mb'): 1536 MB, 3072 MB divided by max_connections, and 307 MB. The three variables move from group_vars/all/17_resource.yml into the role's vars. They no longer describe the host, and only the role's compose template reads them. Their *_MB helpers and POSTGRES_TOTAL_RAM_MB had no other reader and are gone. An inventory can no longer override the three values; the knob is services.postgres.mem_limit. Discourse's db_shared_buffers was a literal 4096MB, all of the 4g the role declares. It becomes a quarter of that limit, 1024MB. It only applies when Discourse runs its bundled database. Co-Authored-By: Claude Opus 5.5 (1M context) --- group_vars/all/17_resource.yml | 7 ------- roles/svc-db-postgres/vars/main.yml | 3 +++ roles/web-app-discourse/templates/config.yml.j2 | 2 +- 3 files changed, 4 insertions(+), 8 deletions(-) diff --git a/group_vars/all/17_resource.yml b/group_vars/all/17_resource.yml index 281b5eff75..4392f54ade 100644 --- a/group_vars/all/17_resource.yml +++ b/group_vars/all/17_resource.yml @@ -43,16 +43,9 @@ RESOURCE_MEM_LIMIT: "{{ RESOURCE_MEM_LIMIT_NUM }}g" RESOURCE_PIDS_LIMIT: 512 POSTGRES_VCPUS: "{{ ansible_facts['processor_vcpus'] | int }}" -POSTGRES_TOTAL_RAM_MB: "{{ ansible_facts['memtotal_mb'] | int }}" POSTGRES_MAX_CONNECTIONS: "{{ [ ((POSTGRES_VCPUS | int) * 30 + 50), 400 ] | min }}" POSTGRES_ALLOWED_AVG_CONNECTIONS: "{{ (POSTGRES_MAX_CONNECTIONS | split_postgres_connections(lookup('path_absolute', 'roles'))) | int }}" POSTGRES_SUPERUSER_RESERVED_CONNECTIONS: 3 -POSTGRES_SHARED_BUFFERS_MB: "{{ ((POSTGRES_TOTAL_RAM_MB | int) * 25) // 100 }}" -POSTGRES_SHARED_BUFFERS: "{{ POSTGRES_SHARED_BUFFERS_MB ~ 'MB' }}" -POSTGRES_WORK_MEM_MB: "{{ [ ( (POSTGRES_TOTAL_RAM_MB | int) // ( [ (POSTGRES_MAX_CONNECTIONS | int), 1 ] | max ) // 2 ), 1 ] | max }}" -POSTGRES_WORK_MEM: "{{ POSTGRES_WORK_MEM_MB ~ 'MB' }}" -POSTGRES_MAINTENANCE_WORK_MEM_MB: "{{ [ (((POSTGRES_TOTAL_RAM_MB | int) * 5) // 100), 64 ] | max }}" -POSTGRES_MAINTENANCE_WORK_MEM: "{{ POSTGRES_MAINTENANCE_WORK_MEM_MB ~ 'MB' }}" POSTGRES_MAX_LOCKS_PER_TRANSACTION: 256 POSTGRES_DELAY: 2 diff --git a/roles/svc-db-postgres/vars/main.yml b/roles/svc-db-postgres/vars/main.yml index ab4253a155..b1ff5e62c5 100644 --- a/roles/svc-db-postgres/vars/main.yml +++ b/roles/svc-db-postgres/vars/main.yml @@ -15,3 +15,6 @@ POSTGRES_EXPOSE_LOCAL: true POSTGRES_LOCAL_HOST: "127.0.0.1" POSTGRES_LIBRARIES: "{{ lookup('postgres_libraries', lookup('service_extensions', 'postgres').values() | sum(start=[]) | unique | list) }}" POSTGRES_RETRIES: 5 +POSTGRES_SHARED_BUFFERS: "{{ lookup('service_memory_mb', application_id, entity_name, 0.25) }}MB" +POSTGRES_WORK_MEM: "{{ [ (lookup('service_memory_mb', application_id, entity_name, 0.5) | int) // ([ POSTGRES_MAX_CONNECTIONS | int, 1 ] | max), 1 ] | max }}MB" +POSTGRES_MAINTENANCE_WORK_MEM: "{{ [ lookup('service_memory_mb', application_id, entity_name, 0.05) | int, 64 ] | max }}MB" diff --git a/roles/web-app-discourse/templates/config.yml.j2 b/roles/web-app-discourse/templates/config.yml.j2 index 884d949e89..c72c6c1adc 100644 --- a/roles/web-app-discourse/templates/config.yml.j2 +++ b/roles/web-app-discourse/templates/config.yml.j2 @@ -22,7 +22,7 @@ params: ## Set db_shared_buffers to a max of 25% of the total memory. ## will be set automatically by bootstrap based on detected RAM, or you can override - db_shared_buffers: "4096MB" + db_shared_buffers: "{{ lookup('service_memory_mb', application_id, 'discourse', 0.25) }}MB" ## can improve sorting performance, but adds memory usage per-connection #db_work_mem: "40MB" From 45d956e5eabb6e207a8cdb6a01abb627cf547d51 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 7 Oct 2026 01:30:01 +0200 Subject: [PATCH 39/53] fix(sidecars): cap an engine's sidecar at its provider's size A Redis sidecar whose consumer declares no services.redis.mem_limit runs in a container that inherits the consumer's primary entity limit. Since the lookup replaced the old filter, maxmemory followed that limit and rose from 204 MiB to between 819 and 3276 MiB in 17 roles. lookup('service_memory_mb', ..., provider=) caps the result at the same share of the provider's own limit when the application does not declare one for that service. A declared limit is not capped, and a container smaller than the provider keeps its own share. The Redis sidecar passes provider='svc-db-redis': those 17 roles get 409 MiB, the seven with a 256 MiB container stay at 204. The lookup now rejects unknown options and a provider that is no role or declares no limit for the service, so a misspelled option fails instead of silently lifting the cap. The memcached sidecar's literal -m 64 takes the same lookup and keeps its value. Co-Authored-By: Claude Opus 5.5 (1M context) --- plugins/lookup/service_memory_mb.py | 49 +++++++++- .../svc-db-memcached/templates/service.yml.j2 | 5 +- roles/svc-db-redis/README.md | 2 +- roles/svc-db-redis/templates/service.yml.j2 | 2 +- .../plugins/lookup/test_service_memory_mb.py | 95 ++++++++++++++++++- 5 files changed, 140 insertions(+), 13 deletions(-) diff --git a/plugins/lookup/service_memory_mb.py b/plugins/lookup/service_memory_mb.py index 2d2f82786e..bc7ab9975c 100644 --- a/plugins/lookup/service_memory_mb.py +++ b/plugins/lookup/service_memory_mb.py @@ -1,6 +1,6 @@ """Derive a memory parameter in MiB from the memory limit of a service's container. - -Xmx{{ lookup('service_memory_mb', application_id, 'search', 0.5) }}m + -Xmx{{ lookup('service_memory_mb', application_id, 'search', 0.25) }}m memory_limit = {{ lookup('service_memory_mb', application_id, entity_name, 0.5) }}M The limit is resolved the way ``sys-svc-container`` resolves the container's own @@ -9,6 +9,15 @@ then ``RESOURCE_MEM_LIMIT``. ``share`` is the fraction of that limit the parameter may claim, so a heap, a cache or a per-request limit follows the container instead of a literal that drifts away from it. +A sidecar that a provider role ships into other stacks passes ``provider``: + + --maxmemory {{ lookup('service_memory_mb', application_id, 'redis', 0.8, provider='svc-db-redis') }}mb + +An application that declares no ``mem_limit`` for that service lets its container +inherit the primary entity's, which is sized for the application and not for the +engine beside it. The result is then capped at the same share of the provider's +own limit. An application that declares the limit itself is not capped. + Sizes are read like Docker reads them: ``k``, ``m`` and ``g`` are binary, a bare number is bytes. The result is whole MiB, the unit ``-Xmxm``, PHP ``M``, ``memcached -m``, Redis ``mb`` and PostgreSQL ``MB`` all share. @@ -24,6 +33,11 @@ from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase from plugins.filter.resource_filter import resource_filter +from utils.roles.applications.config import ( + AppConfigKeyError, + ConfigEntryNotSetError, + get, +) _SIZE = re.compile(r"^\s*(\d+(?:\.\d+)?)\s*([bkmg]?)b?\s*$", re.IGNORECASE) _FACTOR = {"": 1, "b": 1, "k": 1024, "m": 1024**2, "g": 1024**3} @@ -77,7 +91,7 @@ def share_mb(mem_limit: Any, share: Any) -> int: class LookupModule(LookupBase): - """lookup('service_memory_mb', application_id, service_name, share)""" + """lookup('service_memory_mb', application_id, service_name, share[, provider=role])""" def run(self, terms, variables: dict[str, Any] | None = None, **kwargs): if len(terms) != 3: @@ -86,6 +100,12 @@ class LookupModule(LookupBase): "expects exactly 3 positional terms." ) application_id, service_name, share = terms + unknown = sorted(set(kwargs) - {"provider"}) + if unknown: + raise AnsibleError( + f"lookup('service_memory_mb'): unknown option(s) {unknown}; " + "the only option is provider=" + ) templar = self._templar variables = variables or templar.available_variables @@ -103,4 +123,27 @@ class LookupModule(LookupBase): f"mem_limit for '{service_name}' and {_HOST_DEFAULT} is unset" ) mem_limit = templar.template(variables[_HOST_DEFAULT]) - return [share_mb(mem_limit, share)] + megabytes = share_mb(mem_limit, share) + + if "provider" in kwargs: + if not kwargs["provider"] or not isinstance(kwargs["provider"], str): + raise AnsibleError( + "lookup('service_memory_mb'): provider must name a role" + ) + own = f"services.{service_name}.mem_limit" + try: + ceiling = get(applications, kwargs["provider"], own, False, _UNDECLARED) + inherited = ( + get(applications, application_id, own, False, _UNDECLARED) + is _UNDECLARED + ) + except (AppConfigKeyError, ConfigEntryNotSetError) as exc: + raise AnsibleError(f"lookup('service_memory_mb'): {exc}") from exc + if ceiling is _UNDECLARED: + raise AnsibleError( + f"lookup('service_memory_mb'): provider {kwargs['provider']!r} " + f"declares no mem_limit for '{service_name}'" + ) + if inherited: + megabytes = min(megabytes, share_mb(ceiling, share)) + return [megabytes] diff --git a/roles/svc-db-memcached/templates/service.yml.j2 b/roles/svc-db-memcached/templates/service.yml.j2 index cf91ec5014..257b24f783 100644 --- a/roles/svc-db-memcached/templates/service.yml.j2 +++ b/roles/svc-db-memcached/templates/service.yml.j2 @@ -5,10 +5,7 @@ {{ lookup('compose_restart') }} logging: driver: journald - command: - - memcached - - -m - - "64" + command: ["memcached", "-m", "{{ lookup('service_memory_mb', application_id, 'memcached', 0.25, provider='svc-db-memcached') }}"] # nocheck: container-healthcheck-literal probes every second, so the SPOT's 5s start cadence would report healthy later than this block already does healthcheck: # nocheck: healthcheck-timing-override, healthcheck-start-period-covers-interval a swarm-init gate that must clear in seconds, so it runs without a start window rather than inside one test: ["CMD-SHELL", "printf 'version\\r\\n' | nc -w 1 127.0.0.1 11211 | grep -q VERSION"] diff --git a/roles/svc-db-redis/README.md b/roles/svc-db-redis/README.md index 6a4f203290..70b1588070 100644 --- a/roles/svc-db-redis/README.md +++ b/roles/svc-db-redis/README.md @@ -18,7 +18,7 @@ The central stack (`templates/compose.yml.j2`) runs `redis:alpine` with: Per-consumer provisioning (`tasks/01_init.yml`) runs with `application_id=svc-db-redis` and `database_consumer_id=`; it resolves the consumer's username, password and key-prefix via `lookup('engine', 'redis', , ...)` and reconciles an idempotent `ACL SETUSER` restricted to `~{entity}:*`. The ACL users are recreated by the consumer's `01_init` on every deploy, so a container restart that drops the in-memory ACL set is healed on the next run. -The embedded snippet (`templates/service.yml.j2`) keeps the previous single-host behaviour: an unauthenticated in-memory Redis attached to the consumer stack's default network. +The embedded snippet (`templates/service.yml.j2`) keeps the previous single-host behaviour: an unauthenticated in-memory Redis attached to the consumer stack's default network. Its `maxmemory` is 80 % of the consumer's `services.redis.mem_limit`; a consumer that declares none gets 80 % of the limit its container inherits, at most 80 % of this role's own `mem_limit`. ## Cosmos diff --git a/roles/svc-db-redis/templates/service.yml.j2 b/roles/svc-db-redis/templates/service.yml.j2 index d95e5e21e7..8bc3775856 100644 --- a/roles/svc-db-redis/templates/service.yml.j2 +++ b/roles/svc-db-redis/templates/service.yml.j2 @@ -13,7 +13,7 @@ - "no" - --save - "" - - --maxmemory {{ lookup('service_memory_mb', application_id, 'redis', 0.8) }}mb + - --maxmemory {{ lookup('service_memory_mb', application_id, 'redis', 0.8, provider='svc-db-redis') }}mb - --maxmemory-policy - "allkeys-lru" # nocheck: container-healthcheck-literal probes every second, so the SPOT's 5s start cadence would report healthy later than this block already does diff --git a/tests/unit/python/plugins/lookup/test_service_memory_mb.py b/tests/unit/python/plugins/lookup/test_service_memory_mb.py index d8277c6c11..152eba62ed 100644 --- a/tests/unit/python/plugins/lookup/test_service_memory_mb.py +++ b/tests/unit/python/plugins/lookup/test_service_memory_mb.py @@ -8,6 +8,7 @@ from ansible.errors import AnsibleError from plugins.lookup.service_memory_mb import LookupModule, docker_bytes, share_mb _APP = "web-app-demo" +_PROVIDER = "svc-db-cache" class TestDockerBytes(unittest.TestCase): @@ -55,22 +56,36 @@ class TestShareMb(unittest.TestCase): share_mb("1m", 0.5) -class TestLookupResolvesTheContainerLimit(unittest.TestCase): - def _run(self, services: dict, variables: dict, terms: list) -> int: +class _LookupCase(unittest.TestCase): + def _run( + self, + services: dict, + variables: dict, + terms: list, + provided: dict | None = None, + **kwargs, + ) -> int: templar = MagicMock() templar.available_variables = variables templar.template.side_effect = lambda value: {"{{ HOST }}": "1.5g"}.get( value, value ) applications = MagicMock() - applications.run.return_value = [{_APP: {"services": services}}] + applications.run.return_value = [ + { + _APP: {"services": services}, + _PROVIDER: {"services": provided or {}}, + } + ] lookup = LookupModule(loader=None, templar=templar) with patch( "plugins.lookup.service_memory_mb.lookup_loader.get", return_value=applications, ): - return lookup.run(terms, variables=variables)[0] + return lookup.run(terms, variables=variables, **kwargs)[0] + +class TestLookupResolvesTheContainerLimit(_LookupCase): def test_the_named_service_wins(self) -> None: services = {"search": {"mem_limit": "2g"}, "demo": {"mem_limit": "8g"}} @@ -97,5 +112,77 @@ class TestLookupResolvesTheContainerLimit(unittest.TestCase): self._run({"search": {"mem_limit": "2g"}}, {}, [_APP, "search"]) +class TestProviderCapsAnInheritedLimit(_LookupCase): + def _sidecar( + self, + services: dict, + provided: dict | None = None, + share: float = 0.8, + variables: dict | None = None, + **kwargs, + ) -> int: + if provided is None: + provided = {"cache": {"mem_limit": "512m"}} + return self._run( + services, + variables or {}, + [_APP, "cache", share], + provided=provided, + **(kwargs or {"provider": _PROVIDER}), + ) + + def test_an_inherited_limit_is_capped_at_the_providers(self) -> None: + for inherited, expected in (("4g", 409), ("1g", 409), ("512m", 409)): + with self.subTest(inherited=inherited): + self.assertEqual( + self._sidecar({"demo": {"mem_limit": inherited}}), expected + ) + + def test_a_small_inherited_limit_stays_below_its_own_container(self) -> None: + self.assertEqual(self._sidecar({"demo": {"mem_limit": "256m"}}), 204) + + def test_the_cap_uses_the_share_of_the_call(self) -> None: + self.assertEqual(self._sidecar({"demo": {"mem_limit": "4g"}}, share=0.25), 128) + + def test_the_host_default_is_capped_as_well(self) -> None: + variables = {"RESOURCE_MEM_LIMIT": "{{ HOST }}"} + + self.assertEqual(self._sidecar({}, variables=variables), 409) + + def test_a_declared_limit_is_not_capped(self) -> None: + services = {"cache": {"mem_limit": "1g"}, "demo": {"mem_limit": "4g"}} + + self.assertEqual(self._sidecar(services), 819) + + def test_a_provider_without_a_limit_raises_even_when_nothing_is_capped( + self, + ) -> None: + for services in ( + {"demo": {"mem_limit": "4g"}}, + {"cache": {"mem_limit": "1g"}}, + ): + with self.subTest(services=services), self.assertRaises(AnsibleError): + self._sidecar(services, provided={"cache": {}}) + + def test_only_the_providers_limit_for_that_very_service_counts(self) -> None: + with self.assertRaises(AnsibleError): + self._run( + {"demo": {"mem_limit": "4g"}}, + {}, + [_APP, "store", 0.8], + provided={"cache": {"mem_limit": "512m"}}, + provider=_PROVIDER, + ) + + def test_a_provider_that_is_no_role_raises(self) -> None: + for provider in ("", None, "svc-db-missing"): + with self.subTest(provider=provider), self.assertRaises(AnsibleError): + self._sidecar({"cache": {"mem_limit": "1g"}}, provider=provider) + + def test_a_misspelled_option_raises(self) -> None: + with self.assertRaises(AnsibleError): + self._sidecar({"demo": {"mem_limit": "4g"}}, providr=_PROVIDER) + + if __name__ == "__main__": unittest.main() From 3fb237a1432ee56b1d88d03eb480f0cc384e960f Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 7 Oct 2026 01:32:05 +0200 Subject: [PATCH 40/53] fix(search): keep the search heaps at the size they had The heaps of the central Elasticsearch, Zammad's Elasticsearch and Magento's OpenSearch follow their container through the lookup, so far at half of the limit. That doubled them to 2048, 1024 and 1024 MiB. Xms equals Xmx, so each container claims that heap from its start, and the central one locks it in memory. A quarter of the limit gives 1024, 512 and 512 MiB, the sizes these engines ran with before. The heap still follows the limit. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/svc-db-elasticsearch/vars/main.yml | 2 +- roles/web-app-magento/vars/main.yml | 2 +- roles/web-app-zammad/vars/main.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/roles/svc-db-elasticsearch/vars/main.yml b/roles/svc-db-elasticsearch/vars/main.yml index 874f6021e9..39e44dc3c0 100644 --- a/roles/svc-db-elasticsearch/vars/main.yml +++ b/roles/svc-db-elasticsearch/vars/main.yml @@ -10,7 +10,7 @@ ELASTICSEARCH_PASSWORD: "{{ lookup('config', application_id, 'secrets.credential ELASTICSEARCH_EXPOSE_LOCAL: true ELASTICSEARCH_LOCAL_HOST: "127.0.0.1" ELASTICSEARCH_INTERNAL_PORT: "{{ lookup('config', application_id, 'services.elasticsearch.ports.internal.elasticsearch') }}" -ELASTICSEARCH_HEAP_MB: "{{ lookup('service_memory_mb', application_id, entity_name, 0.5) }}" +ELASTICSEARCH_HEAP_MB: "{{ lookup('service_memory_mb', application_id, entity_name, 0.25) }}" ELASTICSEARCH_RETRIES: 5 ELASTICSEARCH_DELAY: 2 ELASTICSEARCH_API_BASE: "http://{{ ELASTICSEARCH_LOCAL_HOST }}:{{ ELASTICSEARCH_INTERNAL_PORT }}" diff --git a/roles/web-app-magento/vars/main.yml b/roles/web-app-magento/vars/main.yml index b251597964..ce391fede0 100644 --- a/roles/web-app-magento/vars/main.yml +++ b/roles/web-app-magento/vars/main.yml @@ -19,7 +19,7 @@ MAGENTO_PHP_FPM_CONF_PATH: "{{ [ lookup('container', application_id, 'directorie MAGENTO_OBJSTORE_ENABLED: "{{ lookup('objstore', application_id, 'enabled') }}" MAGENTO_SEARCH_CONTAINER: "{{ lookup('config', application_id, 'services.search.name') }}" -MAGENTO_SEARCH_HEAP_MB: "{{ lookup('service_memory_mb', application_id, 'search', 0.5) }}" +MAGENTO_SEARCH_HEAP_MB: "{{ lookup('service_memory_mb', application_id, 'search', 0.25) }}" MAGENTO_PHP_CONTAINER: "{{ lookup('config', application_id, 'services.php.name') }}" MAGENTO_PHP_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, 'php') }}" diff --git a/roles/web-app-zammad/vars/main.yml b/roles/web-app-zammad/vars/main.yml index e7fbc345d1..c74ff2bb10 100644 --- a/roles/web-app-zammad/vars/main.yml +++ b/roles/web-app-zammad/vars/main.yml @@ -22,7 +22,7 @@ ZAMMAD_MEMCACHED_CONTAINER: "{{ lookup('engine', 'memcached', application_id, 'c ZAMMAD_RAILS_PORT: "{{ lookup('config', application_id, 'services.' ~ ZAMMAD_RAILS_SERVICE ~ '.ports.internal.http') }}" ZAMMAD_WEBSOCKET_PORT: "{{ lookup('config', application_id, 'services.' ~ ZAMMAD_WEBSOCKET_SERVICE ~ '.ports.internal.http') }}" ZAMMAD_SEARCH_PORT: "{{ lookup('config', application_id, 'services.' ~ ZAMMAD_SEARCH_SERVICE ~ '.ports.internal.http') }}" -ZAMMAD_SEARCH_HEAP_MB: "{{ lookup('service_memory_mb', application_id, ZAMMAD_SEARCH_SERVICE, 0.5) }}" +ZAMMAD_SEARCH_HEAP_MB: "{{ lookup('service_memory_mb', application_id, ZAMMAD_SEARCH_SERVICE, 0.25) }}" # Exception: env.j2 must never set DATABASE_URL. The image's config/pre_initializers/database_url.rb # builds it from POSTGRESQL_* only while DATABASE_URL is blank, so presetting it drops From 333c9fe6d784bc47b74450b8ad5ffadf33e16d9e Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 7 Oct 2026 01:32:57 +0200 Subject: [PATCH 41/53] fix(web-app-snipe-it): take LDAP_MEM_LIM from the container limit LDAP_MEM_LIM was a literal 500M beside a 2g container. It is now a quarter of the service's mem_limit through lookup('service_memory_mb'), the share the seed command of this role already uses. That renders 512M. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-snipe-it/templates/env.j2 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-snipe-it/templates/env.j2 b/roles/web-app-snipe-it/templates/env.j2 index 4814df58e9..a725042808 100644 --- a/roles/web-app-snipe-it/templates/env.j2 +++ b/roles/web-app-snipe-it/templates/env.j2 @@ -148,5 +148,5 @@ APP_LOCKED=false APP_CIPHER=AES-256-CBC APP_FORCE_TLS={{ lookup('tls', application_id, 'enabled') | string | lower }} GOOGLE_MAPS_API= -LDAP_MEM_LIM=500M +LDAP_MEM_LIM={{ lookup('service_memory_mb', application_id, SNIPE_IT_SERVICE, 0.25) }}M LDAP_TIME_LIM=600 From 462bc4ccf013dbb100f40ca8af2923846fea0d53 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 7 Oct 2026 01:37:17 +0200 Subject: [PATCH 42/53] fix(web-app-shopware): keep the init memory limit in the role's env file The init service received INIT_PHP_MEMORY_LIMIT through an inline environment block in the compose template. It moves to templates/env.j2, which the container base hands to every Shopware container as env_file. Only files/shell/init.sh reads the variable, behind a `:?` guard, so the other containers seeing it changes nothing. The lookup names 'init' instead of service_name, which is bound in the compose template but not in env.j2. The value stays 1024M. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-shopware/templates/compose.yml.j2 | 2 -- roles/web-app-shopware/templates/env.j2 | 1 + 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/roles/web-app-shopware/templates/compose.yml.j2 b/roles/web-app-shopware/templates/compose.yml.j2 index 2f4f6a2497..e3867b9f80 100644 --- a/roles/web-app-shopware/templates/compose.yml.j2 +++ b/roles/web-app-shopware/templates/compose.yml.j2 @@ -12,8 +12,6 @@ x-environment: &shopware {{ lookup('compose_only', 'container_name', SHOPWARE_INIT_CONTAINER) }} entrypoint: [ "sh", "{{ SHOPWARE_INIT_DOCKER }}" ] user: "0:0" - environment: - INIT_PHP_MEMORY_LIMIT: "{{ lookup('service_memory_mb', application_id, service_name, 0.5) }}M" {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_networks') | indent(4) }} diff --git a/roles/web-app-shopware/templates/env.j2 b/roles/web-app-shopware/templates/env.j2 index f0cbf7103c..99b6e59b08 100644 --- a/roles/web-app-shopware/templates/env.j2 +++ b/roles/web-app-shopware/templates/env.j2 @@ -11,6 +11,7 @@ TRUSTED_PROXIES={{ ([networks.internet.values() | select | list, NETWORK_TRUSTED TRUSTED_HOSTS={{ SHOPWARE_DOMAIN }} DATABASE_URL=mysql://{{ lookup('database', application_id, 'username') }}:{{ lookup('database', application_id, 'password') }}@{{ lookup('database', application_id, 'host') }}:{{ lookup('database', application_id, 'port') }}/{{ lookup('database', application_id, 'name') }} +INIT_PHP_MEMORY_LIMIT={{ lookup('service_memory_mb', application_id, 'init', 0.5) }}M {% if SHOPWARE_REDIS_ENABLED | bool %} REDIS_URL={{ SHOPWARE_REDIS_URL }}/0 From ba5c4b0060c17413a924c031ce2c561c1b2c0fc8 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 7 Oct 2026 01:38:12 +0200 Subject: [PATCH 43/53] docs(atlassian): describe the heap as a share of the container limit The Confluence and Jira READMEs said the JVM heap was derived from host RAM with safe caps. It is 70 % of the service's mem_limit for JVM_MAXIMUM_MEMORY and 35 % for JVM_MINIMUM_MEMORY, and the caps of the old filter no longer exist. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-confluence/README.md | 4 ++-- roles/web-app-jira/README.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/roles/web-app-confluence/README.md b/roles/web-app-confluence/README.md index 390ac319d6..d92f4d1a65 100644 --- a/roles/web-app-confluence/README.md +++ b/roles/web-app-confluence/README.md @@ -6,7 +6,7 @@ Confluence is Atlassian’s enterprise wiki and collaboration platform. This rol ## Overview -The role builds a minimal custom image on top of the official Confluence image, prepares persistent volumes, and exposes the app behind your reverse proxy. Configuration is driven by variables (image, version, volumes, domains, OIDC). JVM heap sizing is auto-derived from host RAM with safe caps to avoid `Xms > Xmx`. +The role builds a minimal custom image on top of the official Confluence image, prepares persistent volumes, and exposes the app behind your reverse proxy. Configuration is driven by variables (image, version, volumes, domains, OIDC). JVM heap sizing follows the container's `mem_limit`: `JVM_MAXIMUM_MEMORY` is 70 % of it and `JVM_MINIMUM_MEMORY` 35 %. ## Cosmos @@ -60,7 +60,7 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( * **Reverse-Proxy Ready:** Sets `ATL_PROXY_NAME/PORT/SCHEME/SECURE` so Confluence generates correct external URLs behind HTTPS. * **OIDC SSO (Optional):** Pre-templated vars for issuer, client, scopes, JWKS; compatible with Atlassian DC SSO/OIDC marketplace apps. * **Central Database:** PostgreSQL integration (local or central DB) with bootstrap credentials from role vars. -* **JVM Auto-Tuning:** `JVM_MINIMUM_MEMORY` / `JVM_MAXIMUM_MEMORY` computed from host memory with upper bounds. +* **JVM Auto-Tuning:** `JVM_MINIMUM_MEMORY` / `JVM_MAXIMUM_MEMORY` are 35 % and 70 % of the service `mem_limit`. * **Health Checks:** Curl-based container healthcheck for early failure detection. * **CSP & Canonical Domains:** Hooks into platform CSP/SSL/domain management to keep policies strict and URLs stable. * **Backup Friendly:** Data isolated under `{{ CONFLUENCE_HOME }}`. diff --git a/roles/web-app-jira/README.md b/roles/web-app-jira/README.md index 0614a6a212..552a6756be 100644 --- a/roles/web-app-jira/README.md +++ b/roles/web-app-jira/README.md @@ -6,7 +6,7 @@ ## Overview -The role builds a lean custom image on top of the official Jira Software image, provisions persistent volumes, and exposes the app behind your reverse proxy. Variables control image/version/volumes/domains/SSO. JVM heap sizing is auto-derived from host RAM with safe caps to prevent `Xms > Xmx`. +The role builds a lean custom image on top of the official Jira Software image, provisions persistent volumes, and exposes the app behind your reverse proxy. Variables control image/version/volumes/domains/SSO. JVM heap sizing follows the container's `mem_limit`: `JVM_MAXIMUM_MEMORY` is 70 % of it and `JVM_MINIMUM_MEMORY` 35 %. ## Cosmos @@ -60,7 +60,7 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( * **Reverse-Proxy/HTTPS Ready:** Preconfigured Atlassian Tomcat proxy envs so Jira respects external scheme/host/port. * **OIDC SSO (Optional):** Pre-templated vars for issuer, client, endpoints, scopes; compatible with Atlassian DC SSO/OIDC marketplace apps. * **Central Database:** PostgreSQL integration (local or central) with credentials sourced from role configuration. -* **JVM Auto-Tuning:** Safe calculation of `JVM_MINIMUM_MEMORY` / `JVM_MAXIMUM_MEMORY` with caps to avoid VM init errors. +* **JVM Auto-Tuning:** `JVM_MINIMUM_MEMORY` / `JVM_MAXIMUM_MEMORY` are 35 % and 70 % of the service `mem_limit`. * **Health Checks:** Container healthcheck for quicker failure detection and stable automation. * **CSP & Canonical Domains:** Integrates with platform CSP and domain management. * **Backup Ready:** Persistent data under `{{ JIRA_STORAGE_PATH }}`. From b56b0551aaf8c97d1d4ecbc7fb593e3631988d48 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 7 Oct 2026 01:40:20 +0200 Subject: [PATCH 44/53] fix(web-app-wordpress): size PHP's memory_limit from the container, not the upload upload.ini set memory_limit to WORDPRESS_MAX_UPLOAD_SIZE, the same 256M as upload_max_filesize and post_max_size, so the memory a request may use depended on how large an upload may be. It is now a quarter of the service's mem_limit through lookup('service_memory_mb'), which renders 384M beside the 1.5g container. The upload sizes keep their variable. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-wordpress/templates/upload.ini.j2 | 2 +- roles/web-app-wordpress/vars/main.yml | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/roles/web-app-wordpress/templates/upload.ini.j2 b/roles/web-app-wordpress/templates/upload.ini.j2 index a14ff008b0..e02d303ec0 100644 --- a/roles/web-app-wordpress/templates/upload.ini.j2 +++ b/roles/web-app-wordpress/templates/upload.ini.j2 @@ -1,5 +1,5 @@ file_uploads = On -memory_limit = {{ WORDPRESS_MAX_UPLOAD_SIZE }} +memory_limit = {{ WORDPRESS_PHP_MEMORY_LIMIT }} upload_max_filesize = {{ WORDPRESS_MAX_UPLOAD_SIZE }} post_max_size = {{ WORDPRESS_MAX_UPLOAD_SIZE }} max_execution_time = 300 diff --git a/roles/web-app-wordpress/vars/main.yml b/roles/web-app-wordpress/vars/main.yml index eac46649e7..8e384834a0 100644 --- a/roles/web-app-wordpress/vars/main.yml +++ b/roles/web-app-wordpress/vars/main.yml @@ -5,6 +5,7 @@ entity_name: "{{ application_id | get_entity_name }}" WORDPRESS_URL: "{{ lookup('tls', application_id, 'url.base') }}" WORDPRESS_TITLE: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.title') }}" WORDPRESS_MAX_UPLOAD_SIZE: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.max_upload_size') }}" +WORDPRESS_PHP_MEMORY_LIMIT: "{{ lookup('service_memory_mb', application_id, entity_name, 0.25) }}M" WORDPRESS_DOCKER_HTML_PATH: "{{ lookup('volume', 'web-app-wordpress', 'data').target }}" WORDPRESS_DOCKER_CONF_PATH: "{{ WORDPRESS_CONFIG_PATH }}" WORDPRESS_VERSION: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.version') }}" From 1f72f59ec15616aa63bde9d915db69af6c93f5bb Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 7 Oct 2026 01:41:55 +0200 Subject: [PATCH 45/53] fix(web-app-nextcloud): size PHP's memory from the container, not the host PHP_MEMORY_LIMIT and PHP_OPCACHE_MEMORY_CONSUMPTION were both the host's RAM divided by 30, read from two keys in meta/services.yml: 533M on a 16 GB host, 2133M on a 64 GB one, beside a container limited to 3g either way. They are now half and an eighth of that limit through lookup('service_memory_mb'), which renders 1536M and 384M on every host. The lookup sits in env.j2 and the two meta keys are gone. It reads the applications payload, and meta/services.yml is part of that payload, so a call from there would run back into the render that asked for it. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-nextcloud/meta/services.yml | 2 -- roles/web-app-nextcloud/templates/env.j2 | 4 ++-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/roles/web-app-nextcloud/meta/services.yml b/roles/web-app-nextcloud/meta/services.yml index 13f7f4b47e..6e0d032d02 100644 --- a/roles/web-app-nextcloud/meta/services.yml +++ b/roles/web-app-nextcloud/meta/services.yml @@ -84,9 +84,7 @@ nextcloud: enabled: "{{ not (lookup('config', 'web-app-nextcloud', 'services.sso.enabled') | bool) }}" performance: php: - memory_limit: "{{ ((ansible_facts['memtotal_mb'] | int) / 30) | int }}M" upload_limit: 5G - opcache_memory_consumption: "{{ ((ansible_facts['memtotal_mb'] | int) / 30) | int }}M" fpm: max_children: 16 start_servers: 4 diff --git a/roles/web-app-nextcloud/templates/env.j2 b/roles/web-app-nextcloud/templates/env.j2 index e63e181507..523629cb98 100644 --- a/roles/web-app-nextcloud/templates/env.j2 +++ b/roles/web-app-nextcloud/templates/env.j2 @@ -5,9 +5,9 @@ MYSQL_USER={{ lookup('database', application_id, 'username') }} MYSQL_PASSWORD={{ lookup('database', application_id, 'password') | dotenv_quote }} MYSQL_HOST={{ lookup('database', application_id, 'host') }}:{{ lookup('database', application_id, 'port') }} -PHP_MEMORY_LIMIT={{ lookup('config', application_id, 'services.nextcloud.performance.php.memory_limit') }} +PHP_MEMORY_LIMIT={{ lookup('service_memory_mb', application_id, 'nextcloud', 0.5) }}M PHP_UPLOAD_LIMIT={{ lookup('config', application_id, 'services.nextcloud.performance.php.upload_limit') }} -PHP_OPCACHE_MEMORY_CONSUMPTION={{ lookup('config', application_id, 'services.nextcloud.performance.php.opcache_memory_consumption') }} +PHP_OPCACHE_MEMORY_CONSUMPTION={{ lookup('service_memory_mb', application_id, 'nextcloud', 0.125) }}M {% set email = lookup('email', application_id) %} {% if email.enabled | bool %} From f4b5b7be252fbf578bd971cca35cc9ee839b1796 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 7 Oct 2026 01:43:25 +0200 Subject: [PATCH 46/53] test(lint): require memory parameters to follow the container limit A heap, a cache size or a PHP limit written as a literal drifts away from the mem_limit its service declares. The lint scans roles/ and group_vars/ for the known spellings of such parameters and requires each value to reach lookup('service_memory_mb'), or the Node lookup for the V8 heap, on its own line or through the variables it reads. It follows names inside {{ }} and $NAME through the definitions of the role and of group_vars, reads a command list, a folded scalar and a wrapped expression as one line, and counts a literal fallback as a literal. A sidecar snippet has to name its own role as provider. It knows a list of spellings and layouts. A parameter written another way is not seen. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../test_memory_parameters_use_lookup.py | 546 ++++++++++++++++++ 1 file changed, 546 insertions(+) create mode 100644 tests/lint/ansible/services/test_memory_parameters_use_lookup.py diff --git a/tests/lint/ansible/services/test_memory_parameters_use_lookup.py b/tests/lint/ansible/services/test_memory_parameters_use_lookup.py new file mode 100644 index 0000000000..70a725928d --- /dev/null +++ b/tests/lint/ansible/services/test_memory_parameters_use_lookup.py @@ -0,0 +1,546 @@ +"""Lint guard: a known memory parameter MUST follow the container's memory limit. + +A heap, a cache size or a per-request limit written as a literal drifts away +from the ``mem_limit`` its service declares in ``meta/services.yml``: raising +the limit leaves the parameter behind, lowering it lets the process outgrow its +container. Every parameter in ``PARAMETERS`` therefore has to reach +``lookup('service_memory_mb', ...)``, or ``lookup('node_max_old_space_size', ...)`` +for the V8 heap. + +The lookup may sit on the parameter's own line or behind the variables its value +reads. A value reads the names inside its ``{{ }}`` expressions, apart from string +literals, attribute access and filters, and its ``$NAME`` / ``${NAME}`` shell +references. Indirection is followed inside the role and ``group_vars``: a name +counts when one of its definitions (``NAME: value``, ``NAME=value``, +``{% set NAME = value %}``) reaches the lookup, however many names lie between. +A value that keeps a literal fallback (``${NAME:-512M}``, ``... else 512``, +``default(512)``) does not count. + +Only a value that starts like a size is a parameter: a digit, ``{{`` or ``$``. +That leaves prose, probes and the unlimited markers ``-1`` and ``0`` alone. A +block list under ``command:``, ``entrypoint:``, ``argv:``, ``args:`` or ``cmd:``, +a folded scalar, a backslash continuation and an expression wrapped over several +lines are each read as one line, so a flag and its value may be apart. + +A sidecar snippet (``roles//templates/service.yml.j2``) runs in another +role's stack. Its lookups MUST pass ``provider=''``, which keeps the size of +an engine from following the limit of the application it sits beside. + +The scan knows the spellings in ``PARAMETERS`` and the layouts above. A parameter +written another way is not seen; add its spelling when a role introduces one. +""" + +from __future__ import annotations + +import re +import subprocess +import unittest +from bisect import bisect_right +from collections import defaultdict +from functools import cache +from typing import TYPE_CHECKING, ClassVar + +from utils.cache.files import read_text +from utils.roles.mapping import ROLE_FILE_TEMPL_COMPOSE + +from . import PROJECT_ROOT + +if TYPE_CHECKING: + from collections.abc import Iterator, Mapping, Sequence + +_SEPARATOR = r"""[\]"']*\s*(?:=>?|:|,)?\s*(?:>[+-]?\s+)?(?:value:\s*)?["'\s]*""" +PARAMETERS = ( + r"-Xm[snx]", + r"-XX:(?:Max|Initial)HeapSize=", + r"-XX:MaxDirectMemorySize=", + r"\b\w*HEAP_SIZE" + _SEPARATOR, + r"\b\w*M(?:AX|IN)(?:IMUM)?_MEMORY" + _SEPARATOR, + r"(?i:memory[-_]limit)" + _SEPARATOR, + r"\bwgMemoryLimit" + _SEPARATOR, + r"(?i:memory_consumption)" + _SEPARATOR, + r"\bLDAP_MEM_LIM" + _SEPARATOR, + r"\blimit[-_]memory[-_](?:hard|soft)" + _SEPARATOR, + r"\bmaxmemory" + _SEPARATOR, + r"\bmemcached\b[^&|;]*?[\s\"']-m" + _SEPARATOR, + r"(?(?=\d|\{\{|\$)(?:\{\{.*?\}\}|\$\{[^}]*\}|\S)+)" +) +_UNLIMITED = re.compile(r"0(?![\w.])") +_LOOKUP = re.compile( + r"(?:lookup|query)\(\s*['\"](?:service_memory_mb|node_max_old_space_size)['\"]" +) +_FALLBACK = re.compile(r"\$\{\w+:-\s*[\"']?\d|\belse\s+[\"']?\d|\bdefault\(\s*[\"']?\d") +_EXPRESSION = re.compile(r"\{\{(.*?)\}\}", re.DOTALL) +_NOT_A_NAME = re.compile(r"'[^']*'|\"[^\"]*\"|\.\s*[A-Za-z_]\w*|\|\s*[A-Za-z_]\w*") +_NAME = re.compile(r"[A-Za-z_]\w*") +_SHELL_NAME = re.compile(r"\$\{?([A-Za-z_]\w*)") +_DEFINITION = re.compile( + r"^\s*(?:-\s+)?(?:(?:export|local|readonly|ARG|ENV)\s+)?" + r"[\"']?([A-Za-z_]\w*)[\"']?\s*(?::(?=\s|$)|=)(.*)$" +) +_JINJA_SET = re.compile(r"\{%-?\s*set\s+(\w+)\s*=(.*?)-?%\}") +_BLOCK_SCALAR = re.compile(r"[>|][+-]?\d*") +_ARGV_KEY = re.compile(r"^\s*(?:-\s+)?(?:command|entrypoint|argv|args|cmd)\s*:\s*$") +_FOLDED = re.compile(r":\s*>[+-]?\d*\s*$") +_ITEM = re.compile(r"^\s*-\s+") +_TRAILING_COMMENT = re.compile(r"\s#.*$") +_SIDECAR = re.compile(r"roles/([^/]+)/templates/service\.yml\.j2") +_SIZING = re.compile(r"lookup\(\s*['\"]service_memory_mb['\"][^)]*\)") +_COMMENT = ("#", ";", "//", "{#") +_SHARED_SCOPE = "group_vars" +_WRAP = 20 + + +def _indent(line: str) -> int: + return len(line) - len(line.lstrip()) + + +def _code(lines: Sequence[str]) -> list[str]: + return [_TRAILING_COMMENT.sub("", line) for line in lines] + + +def _open(lines: Sequence[str]) -> bool: + return sum(line.count("{{") for line in lines) > sum( + line.count("}}") for line in lines + ) + + +def _block_end(lines: Sequence[str], start: int) -> int: + end = start + 1 + while end < len(lines) and ( + not lines[end].strip() or _indent(lines[end]) > _indent(lines[start]) + ): + end += 1 + return end + + +def definitions(lines: Sequence[str]) -> Iterator[tuple[str, str]]: + """Yield every ``(name, value)`` a file defines. + + Args: + lines: the file's lines. Trailing comments are cut. A value continues over + the deeper indented lines below its key when it is a YAML block scalar + or leaves a ``{{`` open. + """ + lines = _code(lines) + for number, line in enumerate(lines): + for name, expression in _JINJA_SET.findall(line): + yield name, "{{" + expression + "}}" + match = _DEFINITION.match(line) + if not match: + continue + value = match[2] + if _BLOCK_SCALAR.fullmatch(value.strip()) or _open([value]): + value = " ".join([value, *lines[number + 1 : _block_end(lines, number)]]) + yield match[1], value + + +def references(value: str) -> set[str]: + """Return the names *value* reads. + + Args: + value: text that is rendered later. Names inside ``{{ }}`` and shell + references count; bare words, string literals, attributes and + filters do not. + """ + names = set(_SHELL_NAME.findall(value)) + for expression in _EXPRESSION.findall(value): + names.update(_NAME.findall(_NOT_A_NAME.sub(" ", expression))) + return names + + +def reaches_lookup(value: str, known: Mapping[str, Sequence[str]]) -> bool: + """Whether *value* calls the lookup itself or reads a variable that does. + + Args: + value: the expression a parameter is set to. + known: variable name to every value it is defined with. + """ + pending, seen = [value], set() + while pending: + current = pending.pop() + if _FALLBACK.search(current): + continue + if _LOOKUP.search(current): + return True + for name in references(current) - seen: + seen.add(name) + pending.extend(known.get(name, ())) + return False + + +def _logical_lines(lines: Sequence[str]) -> Iterator[tuple[str, list[int], list[int]]]: + """Yield ``(text, offsets, numbers)``: one logical line and where each source line starts in it. + + Args: + lines: the file's lines, trailing comments already cut. + """ + index = 0 + while index < len(lines): + end = index + 1 + if _ARGV_KEY.match(lines[index]) or _FOLDED.search(lines[index]): + end = _block_end(lines, index) + while ( + end < len(lines) + and end - index < _WRAP + and (lines[end - 1].rstrip().endswith("\\") or _open(lines[index:end])) + ): + end += 1 + text, offsets, numbers = "", [], [] + for number in range(index, end): + piece = lines[number] + if number > index: + piece = _ITEM.sub("", piece).strip() + if piece.startswith(_COMMENT): + continue + offsets.append(len(text)) + numbers.append(number + 1) + text += piece.rstrip("\\") + " " + yield text, offsets, numbers + index = end + + +def parameters(text: str) -> list[tuple[int, str, str]]: + """Return ``(line number, parameter with value, value)`` per known parameter. + + Args: + text: a file's content. Comments and the unlimited marker ``0`` are skipped. + """ + found = [] + for line, offsets, numbers in _logical_lines(_code(text.splitlines())): + if line.lstrip().startswith(_COMMENT): + continue + for match in _PARAMETER.finditer(line): + if not _UNLIMITED.match(match.group("value")): + number = numbers[bisect_right(offsets, match.start()) - 1] + found.append((number, match.group(0), match.group("value"))) + return found + + +def detached(text: str, known: Mapping[str, Sequence[str]]) -> list[tuple[int, str]]: + """Return ``(line number, parameter with value)`` for every parameter that never reaches the lookup. + + Args: + text: a file's content. + known: variable name to every value it is defined with. + """ + return [ + (number, parameter) + for number, parameter, value in parameters(text) + if not reaches_lookup(value, known) + ] + + +def unprovided(rel: str, text: str) -> list[int]: + """Return the lines of a sidecar snippet whose lookup does not name its own role as provider. + + Args: + rel: repository-relative path of the file. + text: its content. + """ + sidecar = _SIDECAR.fullmatch(rel) + if not sidecar: + return [] + provider = re.compile(rf"provider\s*=\s*['\"]{re.escape(sidecar[1])}['\"]") + return [ + number + for number, line in enumerate(text.splitlines(), 1) + for call in _SIZING.findall(line) + if not provider.search(call) + ] + + +def merged(*scopes: Mapping[str, Sequence[str]]) -> dict[str, list[str]]: + """Return one name-to-values map holding every definition of every scope. + + Args: + scopes: name-to-values maps; a name defined in several keeps all its values. + """ + union: dict[str, list[str]] = defaultdict(list) + for scope in scopes: + for name, values in scope.items(): + union[name].extend(values) + return union + + +def _scope(rel: str) -> str: + parts = rel.split("/") + return "/".join(parts[:2]) if parts[0] == "roles" else _SHARED_SCOPE + + +@cache +def _tracked_texts() -> dict[str, str]: + out = subprocess.check_output( + [ + "git", + "-c", + "safe.directory=*", + "-C", + str(PROJECT_ROOT), + "ls-files", + "roles", + _SHARED_SCOPE, + ], + text=True, + ) + texts: dict[str, str] = {} + for rel in out.splitlines(): + if rel.endswith(".md"): + continue + try: + texts[rel] = read_text(str(PROJECT_ROOT / rel)) + except (OSError, UnicodeDecodeError): + continue + return texts + + +class TestMemoryParametersUseLookup(unittest.TestCase): + def test_every_memory_parameter_follows_the_container_limit(self) -> None: + texts = _tracked_texts() + index: dict[str, dict[str, list[str]]] = defaultdict(lambda: defaultdict(list)) + for rel, text in texts.items(): + for name, value in definitions(text.splitlines()): + index[_scope(rel)][name].append(value) + known = { + scope: merged(*(index[name] for name in {_SHARED_SCOPE, scope})) + for scope in list(index) + } + + seen = 0 + offenders: list[str] = [] + for rel, text in sorted(texts.items()): + seen += len(parameters(text)) + offenders.extend( + f" {rel}:{number}: {parameter}" + for number, parameter in detached(text, known.get(_scope(rel), {})) + ) + + self.assertGreater(seen, 0, "the scan matched no memory parameter at all") + self.assertFalse( + offenders, + "Memory parameters that do not follow their container's mem_limit " + f"({len(offenders)}):\n" + + "\n".join(offenders) + + "\n\nSet the value with lookup('service_memory_mb', application_id, " + ", ), directly or through a variable of the role.", + ) + + def test_every_sidecar_lookup_names_its_provider(self) -> None: + texts = _tracked_texts() + sized = sum( + len(_SIZING.findall(text)) + for rel, text in texts.items() + if _SIDECAR.fullmatch(rel) + ) + offenders = [ + f" {rel}:{number}" + for rel, text in sorted(texts.items()) + for number in unprovided(rel, text) + ] + + self.assertGreater(sized, 0, "no sidecar snippet sizes memory with the lookup") + self.assertFalse( + offenders, + "Sidecar lookups without provider='':\n" + "\n".join(offenders), + ) + + +class TestResolution(unittest.TestCase): + _SIZED: ClassVar[str] = "{{ lookup('service_memory_mb', 'app', 'php', 0.5) }}" + + def test_literal_is_reported(self) -> None: + self.assertEqual( + detached("ES_JAVA_OPTS=-Xms512m -Xmx512m", {}), + [(1, "-Xms512m"), (1, "-Xmx512m")], + ) + + def test_literal_next_to_a_resolved_value_is_still_reported(self) -> None: + self.assertEqual( + detached("ES_JAVA_OPTS=-Xms512m -Xmx{{ HEAP }}m", {"HEAP": [self._SIZED]}), + [(1, "-Xms512m")], + ) + + def test_direct_lookup_passes(self) -> None: + self.assertEqual(detached(f"memory_limit = {self._SIZED}M", {}), []) + + def test_chain_of_variables_passes(self) -> None: + known = dict( + definitions( + [ + 'PHP_LIMIT="${INIT_LIMIT:?INIT_LIMIT must be set}"', + " INIT_LIMIT: \"{{ ROLE_LIMIT ~ 'M' }}\"", + "ROLE_LIMIT: >-", + " {{ lookup('service_memory_mb', application_id, 'init', 0.5) }}", + ] + ) + ) + self.assertEqual( + detached( + 'php -d memory_limit="$PHP_LIMIT" bin/console', + {k: [v] for k, v in known.items()}, + ), + [], + ) + + def test_variable_that_never_reaches_the_lookup_is_reported(self) -> None: + known = {"A": ["{{ B }}"], "B": ["{{ A }}"], "OTHER": ["512M"]} + self.assertEqual( + detached("--maxmemory {{ A }}mb\nshared_buffers={{ OTHER }}", known), + [(1, "maxmemory {{ A }}mb"), (2, "shared_buffers={{ OTHER }}")], + ) + + def test_a_name_inside_a_string_literal_is_not_followed(self) -> None: + sized = [self._SIZED] + known = {"config": sized, "limit": sized, "int": sized, "item": ["512M"]} + value = "{{ lookup('config', item.limit, 'php.limit') | int }}" + self.assertEqual( + detached(f"PHP_MEMORY_LIMIT={value}", known), + [(1, f"MEMORY_LIMIT={value}")], + ) + + def test_a_literal_fallback_does_not_count(self) -> None: + known = {"INIT": [self._SIZED]} + for line in ( + 'PHP_MEMORY_LIMIT="${INIT:-1024M}"', + "-Xmx{{ INIT if swarm else 512 }}m", + "memory_limit = {{ INIT | default(512) }}M", + ): + with self.subTest(line=line): + self.assertEqual(len(detached(line, known)), 1) + + def test_a_lookup_named_in_a_comment_does_not_count(self) -> None: + known = { + name: [value] + for name, value in definitions( + ["HEAP: 1024 # lookup('service_memory_mb', ...) rounds too low"] + ) + } + self.assertEqual(detached("-Xmx{{ HEAP }}m", known), [(1, "-Xmx{{ HEAP }}m")]) + + def test_a_role_definition_does_not_hide_the_shared_one(self) -> None: + known = merged({"SIZE": [self._SIZED]}, {"SIZE": ["{{ SIZE }}"]}) + self.assertEqual(detached("work_mem={{ SIZE }}", known), []) + + def test_flag_and_value_apart_are_one_parameter(self) -> None: + sized = {"SIZE": [self._SIZED]} + for block, line in ( + ( + ' command:\n - memcached\n - -m\n - "{{ SIZE }}"\n image: x', + 2, + ), + ( + ' argv:\n - redis-server\n - "--maxmemory"\n - "{{ SIZE }}mb"', + 3, + ), + ('command: ["redis-server", "--maxmemory", "{{ SIZE }}mb"]', 1), + ("shell: >-\n redis-server\n --maxmemory\n {{ SIZE }}mb", 3), + ("exec memcached \\\n -m {{ SIZE }} \\\n -p 11211", 1), + ): + with self.subTest(block=block): + self.assertEqual(detached(block, sized), []) + self.assertEqual( + [number for number, _ in detached(block, {"SIZE": ["64"]})], [line] + ) + + def test_a_value_wrapped_over_lines_is_one_value(self) -> None: + wrapped = ( + "X_MEMORY_LIMIT: \"{{ [ (lookup('service_memory_mb', application_id,\n" + " 'php', 0.5) | int), 64 ] | max }}M\"" + ) + for text in (wrapped, f"X_MEMORY_LIMIT: >-\n {self._SIZED}M"): + with self.subTest(text=text): + self.assertEqual(len(parameters(text)), 1) + self.assertEqual(detached(text, {}), []) + self.assertEqual(len(detached("X_MEMORY_LIMIT: >-\n 512M", {})), 1) + + def test_every_spelling_of_a_parameter_is_known(self) -> None: + for line in ( + "php_admin_value[memory_limit] = 1G", + "php_value memory_limit 512M", + "@ini_set('memory_limit', '512M');", + "'memory_limit' => '512M',", + '"memory_limit": "512M",', + '- { key: "WP_MEMORY_LIMIT", value: "256M" }', + '$wgMemoryLimit = "512M";', + "JVM_MAXIMUM_MEMORY: 4096m", + "JICOFO_MAX_MEMORY=3072m", + "ES_HEAP_SIZE=1g", + "JAVA_OPTS=-XX:MaxHeapSize=7g", + "JAVA_OPTS=-Xmn256m", + "LDAP_MEM_LIM=500M", + " - --memory-limit=512M", + 'command: ["--memory-limit", "512M"]', + "opcache.memory_consumption=256", + "limit_memory_hard = 2684354560", + "odoo --limit-memory-hard 2684354560", + ' db_shared_buffers: "4096MB"', + ' - "effective_cache_size=4GB"', + ' - "--innodb-buffer-pool-size=1G"', + "NODE_OPTIONS=--max-old-space-size=4096", + ): + with self.subTest(line=line): + self.assertEqual(len(detached(line, {})), 1) + + def test_unrelated_lines_are_ignored(self) -> None: + for line in ( + " # -Xmx512m", + "; memory_limit = 512M", + "- --maxmemory-policy allkeys-lru", + "- --maxmemory 0", + 'RUN : "${PHP_MEMORY_LIMIT:?}"', + "bootstrap.memory_lock=true", + "mem_limit: 2g", + "network_mem: 512", + "php -d memory_limit=-1 artisan migrate", + "RUN COMPOSER_MEMORY_LIMIT=-1 composer install", + ' - "autovacuum_work_mem=-1"', + "retries: 3 # was php -d memory_limit=512M", + "retries: 3 #was php -d memory_limit=512M", + '- name: "Tune the JVM heap (-Xms/-Xmx)"', + "php -i | grep -E '^memory_limit => '", + 'f"--max-old-space-size={megabytes}"', + "memcached && install -m 0755 /src /dst", + ): + with self.subTest(line=line): + self.assertEqual(detached(line, {}), []) + + +class TestSidecarProvider(unittest.TestCase): + _SNIPPET: ClassVar[str] = "roles/svc-db-redis/templates/service.yml.j2" + + def _line(self, options: str) -> str: + return ( + " - --maxmemory {{ lookup('service_memory_mb', application_id, " + f"'redis', 0.8{options}) }}}}mb" + ) + + def test_a_sidecar_lookup_without_its_own_provider_is_reported(self) -> None: + for options in ( + "", + ", provider='svc-db-memcached'", + ", providr='svc-db-redis'", + ): + with self.subTest(options=options): + self.assertEqual(unprovided(self._SNIPPET, self._line(options)), [1]) + + def test_a_sidecar_lookup_naming_its_role_passes(self) -> None: + line = self._line(", provider='svc-db-redis'") + + self.assertEqual(unprovided(self._SNIPPET, line), []) + + def test_other_files_are_not_sidecars(self) -> None: + path = f"roles/svc-db-redis/{ROLE_FILE_TEMPL_COMPOSE}" + + self.assertEqual(unprovided(path, self._line("")), []) + + +if __name__ == "__main__": + unittest.main() From d1eee3e26f16c2807a75a9b0694e4970e8a338ed Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 7 Oct 2026 01:26:41 +0200 Subject: [PATCH 47/53] fix(web-app-moodle): run Moodle 5.3 and upgrade existing sites to it The pin moved from 4.5.11 to 5.3.0, and the role fitted neither a new install nor an existing one. Moodle 5 serves from public/ and routes every other path through r.php. nginx now uses public/ as its root, hands unknown paths to the router and passes PATH_INFO for scripts with slash arguments, and config.php declares the router as configured. The paths the role checks and writes (version.php, auth, webservice, the OIDC plugin) moved below public/, the URL of the OIDC plugin stays auth/oidc. The source archive no longer contains vendor/, so the image installs the Composer dependencies it declares. The OIDC plugin is pinned to v5.2.1, the newest release. An existing site kept its old code: the entrypoint filled the code volume once and never again. It now records the release it copied and replaces the tree when the image carries another one, and a new task runs admin/cli/upgrade.php. Plugins that were installed through the web interface are not carried over, the README says how to ship them. A site installed with 5.3 forces login by default, which 4.5 did not, so its start page answers 303 to the login page and the webserver health check refused it. The role declares 200 and 303 as the codes that check accepts: 200 is what an upgraded site keeps answering. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-moodle/README.md | 10 +- roles/web-app-moodle/files/Dockerfile | 2 + roles/web-app-moodle/files/build/config.php | 1 + .../files/build/install/moodle-source.sh | 2 + .../files/build/moodle-entrypoint.sh | 18 +-- .../web-app-moodle/meta/addons/auth_oidc.yml | 4 +- roles/web-app-moodle/meta/server.yml | 5 + roles/web-app-moodle/tasks/01_manager_ops.yml | 7 ++ roles/web-app-moodle/tasks/04_oidc.yml | 2 +- .../templates/nginx-moodle.conf.j2 | 13 ++- roles/web-app-moodle/vars/main.yml | 11 +- .../python/roles/web-app-moodle/__init__.py | 0 .../roles/web-app-moodle/files/__init__.py | 0 .../web-app-moodle/files/build/__init__.py | 0 .../files/build/test_moodle_entrypoint.py | 104 ++++++++++++++++++ 15 files changed, 158 insertions(+), 21 deletions(-) create mode 100644 roles/web-app-moodle/meta/server.yml create mode 100644 tests/unit/python/roles/web-app-moodle/__init__.py create mode 100644 tests/unit/python/roles/web-app-moodle/files/__init__.py create mode 100644 tests/unit/python/roles/web-app-moodle/files/build/__init__.py create mode 100644 tests/unit/python/roles/web-app-moodle/files/build/test_moodle_entrypoint.py diff --git a/roles/web-app-moodle/README.md b/roles/web-app-moodle/README.md index a0a39431e2..26abc2b719 100644 --- a/roles/web-app-moodle/README.md +++ b/roles/web-app-moodle/README.md @@ -121,7 +121,7 @@ docker run --rm -it \ ## MCP server -The role exposes a Model Context Protocol surface through the `webservice_mcp` protocol plugin, baked into the image at `webservice/mcp` and served by the NGINX sidecar. +The role exposes a Model Context Protocol surface through the `webservice_mcp` protocol plugin, baked into the image at `public/webservice/mcp` and served by the NGINX sidecar. | Property | Value | | --- | --- | @@ -173,7 +173,13 @@ This is an accepted trade-off, not an oversight. Moodle offers no allowlist, so ## Image source -This role builds its own Moodle image from upstream Moodle source on top of the official `php:8.3-fpm` base. +This role builds its own Moodle image from upstream Moodle source on top of the official `php:8.3-fpm` base and installs the Composer dependencies that source declares. The NGINX sidecar serves the `public` directory of the code volume and hands every other path to Moodle's router. + +## Updates + +The image carries the Moodle release pinned as `services.moodle.app_version` in `meta/services.yml`. On start the entrypoint compares that release with the one recorded in the code volume and replaces the volume's tree with the image's when they differ. `tasks/01_manager_ops.yml` then runs `admin/cli/upgrade.php`, which migrates the database. + +Plugins installed through the web interface live only in the code volume and are not carried over to the next release. Declare a plugin under `meta/addons/` so the image ships it. ## Further Resources diff --git a/roles/web-app-moodle/files/Dockerfile b/roles/web-app-moodle/files/Dockerfile index dc36c5be3a..f6aa1f92c2 100644 --- a/roles/web-app-moodle/files/Dockerfile +++ b/roles/web-app-moodle/files/Dockerfile @@ -96,6 +96,8 @@ COPY build/php-conf/opcache-recommended.ini /usr/local/etc/php/conf.d/opcache-re COPY build/php-conf/moodle-runtime.ini /usr/local/etc/php/conf.d/moodle-runtime.ini COPY build/php-conf/zz-moodle-pool.conf /usr/local/etc/php-fpm.d/zz-moodle-pool.conf +COPY --from=composer:2 /usr/bin/composer /usr/bin/composer + COPY build/install/moodle-source.sh /tmp/install-moodle-source.sh RUN bash /tmp/install-moodle-source.sh && rm /tmp/install-moodle-source.sh diff --git a/roles/web-app-moodle/files/build/config.php b/roles/web-app-moodle/files/build/config.php index 5434affc26..5e66fb1fcd 100644 --- a/roles/web-app-moodle/files/build/config.php +++ b/roles/web-app-moodle/files/build/config.php @@ -40,6 +40,7 @@ $CFG->dataroot = moodle_env('MOODLE_DATAROOT'); $CFG->localcachedir = moodle_env('MOODLE_LOCALCACHEDIR'); $CFG->admin = 'admin'; $CFG->directorypermissions = 02770; +$CFG->routerconfigured = true; $CFG->reverseproxy = moodle_env_bool('MOODLE_REVERSEPROXY'); $CFG->sslproxy = moodle_env_bool('MOODLE_SSLPROXY'); diff --git a/roles/web-app-moodle/files/build/install/moodle-source.sh b/roles/web-app-moodle/files/build/install/moodle-source.sh index 8674cbc69f..17e5fa8df1 100644 --- a/roles/web-app-moodle/files/build/install/moodle-source.sh +++ b/roles/web-app-moodle/files/build/install/moodle-source.sh @@ -26,6 +26,8 @@ tar -xzf "${TARBALL_PATH}" --strip-components=1 -C "${MOODLE_SOURCE_DIR}" test -d "${MOODLE_SOURCE_DIR}/${MOODLE_AUTH_SUBDIR}" test -f "${MOODLE_SOURCE_DIR}/${MOODLE_VERSION_FILE}" +COMPOSER_ALLOW_SUPERUSER=1 composer install --no-dev --classmap-authoritative --no-interaction --working-dir="${MOODLE_SOURCE_DIR}" + mkdir -p "${MOODLE_CODE_DIR}" "${MOODLE_DATA_DIR}" chown -R "${MOODLE_RUNTIME_USER}:${MOODLE_RUNTIME_USER}" \ "${MOODLE_SOURCE_DIR}" "${MOODLE_CODE_DIR}" "${MOODLE_DATA_DIR}" diff --git a/roles/web-app-moodle/files/build/moodle-entrypoint.sh b/roles/web-app-moodle/files/build/moodle-entrypoint.sh index 8474a21407..7db4d61cb2 100644 --- a/roles/web-app-moodle/files/build/moodle-entrypoint.sh +++ b/roles/web-app-moodle/files/build/moodle-entrypoint.sh @@ -1,6 +1,6 @@ #!/bin/bash # Moodle container entrypoint. Bootstrap the persistent code volume -# from ${MOODLE_SOURCE_DIR} on first start, ensure ownership on the +# from ${MOODLE_SOURCE_DIR}, ensure ownership on the # data dir, then drop privileges (unless launching php-fpm — its # master process must keep root so the FPM error log can write to # /proc/self/fd/2; workers fork to ${MOODLE_RUNTIME_USER} per the pool). @@ -14,6 +14,7 @@ set -euo pipefail : "${MOODLE_SOURCE_DIR:?required}" : "${MOODLE_RUNTIME_USER:?required}" : "${MOODLE_VERSION_FILE:?required}" +: "${MOODLE_RELEASE:?required}" MOODLE_BOOTSTRAP_SENTINEL="${MOODLE_CODE_DIR}/.bootstrap.done" MOODLE_BOOTSTRAP_LOCK="${MOODLE_CODE_DIR}/.bootstrap.lock" @@ -26,17 +27,20 @@ if [ "$(id -u)" -eq 0 ]; then chown -R "${MOODLE_RUNTIME_USER}:${MOODLE_RUNTIME_USER}" "${MOODLE_LOCAL_CACHE_DIR}" fi +moodle_code_dir_is_current() { + [ "$(cat "${MOODLE_BOOTSTRAP_SENTINEL}" 2>/dev/null)" = "${MOODLE_RELEASE}" ] +} + moodle_bootstrap_code_dir() { - if [ -f "${MOODLE_BOOTSTRAP_SENTINEL}" ]; then + if moodle_code_dir_is_current; then return 0 fi - if [ -d "${MOODLE_SOURCE_DIR}" ]; then - cp -an "${MOODLE_SOURCE_DIR}/." "${MOODLE_CODE_DIR}/" || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error - fi + find "${MOODLE_CODE_DIR}" -mindepth 1 -maxdepth 1 ! -name "${MOODLE_BOOTSTRAP_LOCK##*/}" -exec rm -rf {} + + cp -a "${MOODLE_SOURCE_DIR}/." "${MOODLE_CODE_DIR}/" chown -R "${MOODLE_RUNTIME_USER}:${MOODLE_RUNTIME_USER}" "${MOODLE_CODE_DIR}" || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error find "${MOODLE_CODE_DIR}" -type d -exec chmod 0755 {} + || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error find "${MOODLE_CODE_DIR}" -type f -exec chmod 0644 {} + || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error - touch "${MOODLE_BOOTSTRAP_SENTINEL}" + printf '%s' "${MOODLE_RELEASE}" > "${MOODLE_BOOTSTRAP_SENTINEL}" } moodle_refresh_config() { @@ -51,7 +55,7 @@ moodle_refresh_config() { } mkdir -p "${MOODLE_CODE_DIR}" -while [ ! -f "${MOODLE_BOOTSTRAP_SENTINEL}" ]; do +until moodle_code_dir_is_current; do exec 9>>"${MOODLE_BOOTSTRAP_LOCK}" if flock -w 30 9; then moodle_bootstrap_code_dir diff --git a/roles/web-app-moodle/meta/addons/auth_oidc.yml b/roles/web-app-moodle/meta/addons/auth_oidc.yml index 1e33ee4776..5d68112121 100644 --- a/roles/web-app-moodle/meta/addons/auth_oidc.yml +++ b/roles/web-app-moodle/meta/addons/auth_oidc.yml @@ -3,11 +3,11 @@ enabled: "{{ lookup('config', 'web-app-moodle', 'services.sso.enabled') | bool } required: false mechanism: plugin source: upstream -version: "v4.5.8" +version: "v5.2.1" bridges: - sso update: monitored: true catalog: github-releases upstream_id: microsoft/moodle-auth_oidc - match: "v4.5." + match: "v" diff --git a/roles/web-app-moodle/meta/server.yml b/roles/web-app-moodle/meta/server.yml new file mode 100644 index 0000000000..f365eb8102 --- /dev/null +++ b/roles/web-app-moodle/meta/server.yml @@ -0,0 +1,5 @@ +--- +status_codes: + default: + - 200 + - 303 diff --git a/roles/web-app-moodle/tasks/01_manager_ops.yml b/roles/web-app-moodle/tasks/01_manager_ops.yml index 078f32c1ca..af4f17a537 100644 --- a/roles/web-app-moodle/tasks/01_manager_ops.yml +++ b/roles/web-app-moodle/tasks/01_manager_ops.yml @@ -48,6 +48,13 @@ - "'Database tables already present' not in moodle_install.stderr" no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" +- name: "⬆️ Upgrade the Moodle database to the release in the code volume" + shell: > + container exec --user {{ MOODLE_RUNTIME_USER }} {{ MOODLE_CONTAINER_ADDRESS }} + php {{ MOODLE_CLI_DIR }}/upgrade.php --non-interactive + register: moodle_upgrade + changed_when: "'No upgrade needed' not in moodle_upgrade.stdout" + - name: "🔑 Realign the administrator password Moodle persisted at install" when: not (MOODLE_OIDC_ENABLED | bool) # nocheck: password-quote the token is upstream's CLI filename, not a credential diff --git a/roles/web-app-moodle/tasks/04_oidc.yml b/roles/web-app-moodle/tasks/04_oidc.yml index e150b4d5ed..2166ccec42 100644 --- a/roles/web-app-moodle/tasks/04_oidc.yml +++ b/roles/web-app-moodle/tasks/04_oidc.yml @@ -93,7 +93,7 @@ - { name: "field_map_lastnamephonetic", value: "name_phonetic_family" } - { name: "field_lock_lastnamephonetic", value: "locked" } - { name: "field_updatelocal_lastnamephonetic", value: "oneveryloginupdate" } - - { name: "alternateloginurl", value: "{{ lookup('tls', application_id, 'url.base') }}{{ MOODLE_OIDC_PLUGIN_RELPATH }}/" } + - { name: "alternateloginurl", value: "{{ lookup('tls', application_id, 'url.base') }}{{ MOODLE_OIDC_PLUGIN_URL_PATH }}/" } loop_control: label: "{{ item.name }}" shell: > diff --git a/roles/web-app-moodle/templates/nginx-moodle.conf.j2 b/roles/web-app-moodle/templates/nginx-moodle.conf.j2 index 477b89cd1f..ca7b6a2a03 100644 --- a/roles/web-app-moodle/templates/nginx-moodle.conf.j2 +++ b/roles/web-app-moodle/templates/nginx-moodle.conf.j2 @@ -7,7 +7,7 @@ server { listen [::]:{{ MOODLE_NGINX_PORT }}; server_name _; - root {{ MOODLE_CODE_DIR }}; + root {{ MOODLE_PUBLIC_DIR }}; index index.php; client_max_body_size 256M; @@ -16,16 +16,19 @@ server { set $moodle_upstream {{ MOODLE_CONTAINER }}; location / { - try_files $uri $uri/ /index.php?$query_string; + try_files $uri $uri/ /r.php$is_args$args; } location ~ [^/]\.php(/|$) { - fastcgi_split_path_info ^(.+\.php)(/.+)$; + fastcgi_split_path_info ^(.+\.php)(/.*)?$; + set $path_info $fastcgi_path_info; + try_files $fastcgi_script_name $fastcgi_script_name/ /r.php$is_args$args; fastcgi_index index.php; fastcgi_pass $moodle_upstream:{{ MOODLE_FPM_PORT }}; include fastcgi_params; - fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; - fastcgi_param PATH_INFO $fastcgi_path_info; + fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name; + fastcgi_param DOCUMENT_ROOT $realpath_root; + fastcgi_param PATH_INFO $path_info; fastcgi_param HTTP_PROXY ""; fastcgi_read_timeout 300; } diff --git a/roles/web-app-moodle/vars/main.yml b/roles/web-app-moodle/vars/main.yml index 786edc0c15..59dba7cb1c 100644 --- a/roles/web-app-moodle/vars/main.yml +++ b/roles/web-app-moodle/vars/main.yml @@ -19,15 +19,18 @@ MOODLE_BUILD_FILES: opcache_ini: "php-conf/opcache-recommended.ini" runtime_ini: "php-conf/moodle-runtime.ini" fpm_pool: "php-conf/zz-moodle-pool.conf" -MOODLE_VERSION_FILE: "version.php" # bootstrap-detection sentinel -MOODLE_AUTH_SUBDIR: "auth" # top-level auth/ tree -MOODLE_WEBSERVICE_SUBDIR: "webservice" +MOODLE_PUBLIC_SUBDIR: "public" +MOODLE_PUBLIC_DIR: "{{ [MOODLE_CODE_DIR, MOODLE_PUBLIC_SUBDIR] | path_join }}" +MOODLE_VERSION_FILE: "{{ [MOODLE_PUBLIC_SUBDIR, 'version.php'] | path_join }}" +MOODLE_AUTH_SUBDIR: "{{ [MOODLE_PUBLIC_SUBDIR, 'auth'] | path_join }}" +MOODLE_WEBSERVICE_SUBDIR: "{{ [MOODLE_PUBLIC_SUBDIR, 'webservice'] | path_join }}" MOODLE_CLI_RELPATH: "admin/cli" # admin CLI script dir MOODLE_OIDC_PLUGIN_VERSION: "{{ lookup('config', application_id, 'addons.auth_oidc.version') }}" MOODLE_OIDC_PLUGIN_UPSTREAM: "{{ lookup('config', application_id, 'addons.auth_oidc.update.upstream_id') }}" MOODLE_OIDC_PLUGIN_ARCHIVE_URL: "https://github.com/{{ MOODLE_OIDC_PLUGIN_UPSTREAM }}/archive/refs/tags/{{ MOODLE_OIDC_PLUGIN_VERSION }}.zip" -MOODLE_OIDC_PLUGIN_RELPATH: "{{ [MOODLE_AUTH_SUBDIR, 'oidc'] | path_join }}" +MOODLE_OIDC_PLUGIN_URL_PATH: "auth/oidc" +MOODLE_OIDC_PLUGIN_RELPATH: "{{ [MOODLE_PUBLIC_SUBDIR, MOODLE_OIDC_PLUGIN_URL_PATH] | path_join }}" MOODLE_OIDC_PLUGIN_DIR: "{{ [MOODLE_CODE_DIR, MOODLE_OIDC_PLUGIN_RELPATH] | path_join }}" MOODLE_CLI_DIR: "{{ [MOODLE_CODE_DIR, MOODLE_CLI_RELPATH] | path_join }}" MOODLE_CONFIG: "{{ [MOODLE_CODE_DIR, 'config.php'] | path_join }}" diff --git a/tests/unit/python/roles/web-app-moodle/__init__.py b/tests/unit/python/roles/web-app-moodle/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-moodle/files/__init__.py b/tests/unit/python/roles/web-app-moodle/files/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-moodle/files/build/__init__.py b/tests/unit/python/roles/web-app-moodle/files/build/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-moodle/files/build/test_moodle_entrypoint.py b/tests/unit/python/roles/web-app-moodle/files/build/test_moodle_entrypoint.py new file mode 100644 index 0000000000..3ba63ebb1e --- /dev/null +++ b/tests/unit/python/roles/web-app-moodle/files/build/test_moodle_entrypoint.py @@ -0,0 +1,104 @@ +import os +import pwd +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +from utils import PROJECT_ROOT + +ENTRYPOINT = PROJECT_ROOT / "roles/web-app-moodle/files/build/moodle-entrypoint.sh" + +FPM_STUB = "#!/usr/bin/env bash\nexit 0\n" + +LAYOUT_4 = {"version.php": "4.5.11", "auth/oidc/version.php": "4.5.8"} +LAYOUT_5 = {"public/version.php": "5.3.0", "public/auth/oidc/version.php": "5.2.1"} + + +class TestMoodleEntrypoint(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.source = self.root / "source" + self.code = self.root / "code" + bin_dir = self.root / "bin" + bin_dir.mkdir() + stub = bin_dir / "php-fpm" + stub.write_text(FPM_STUB) + stub.chmod(0o755) + self.env = dict(os.environ) + self.env.update( + PATH=f"{bin_dir}{os.pathsep}{self.env['PATH']}", + MOODLE_CODE_DIR=str(self.code), + MOODLE_DATA_DIR=str(self.root / "data"), + MOODLE_LOCAL_CACHE_DIR=str(self.root / "localcache"), + MOODLE_SOURCE_DIR=str(self.source), + MOODLE_RUNTIME_USER=pwd.getpwuid(os.getuid()).pw_name, + MOODLE_VERSION_FILE="public/version.php", + ) + + def write(self, tree, files): + for name, content in files.items(): + path = tree / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content) + + def ship(self, files): + shutil.rmtree(self.source, ignore_errors=True) + self.write(self.source, files) + + def run_entrypoint(self, release): + return subprocess.run( + ["bash", str(ENTRYPOINT), "php-fpm"], + env={**self.env, "MOODLE_RELEASE": release}, + capture_output=True, + text=True, + check=False, + ) + + def start(self, release): + done = self.run_entrypoint(release) + self.assertEqual(done.returncode, 0, done.stderr) + + def shipped_files_in_the_volume(self): + return { + name for name in {*LAYOUT_4, *LAYOUT_5} if (self.code / name).is_file() + } + + def test_the_first_start_fills_the_code_volume(self): + self.ship(LAYOUT_5) + self.start("5.3.0") + self.assertEqual(self.shipped_files_in_the_volume(), set(LAYOUT_5)) + + def test_a_restart_on_the_same_release_keeps_what_the_volume_holds(self): + self.ship(LAYOUT_5) + self.start("5.3.0") + added = {"public/local/extra/version.php": "added after the bootstrap"} + self.write(self.code, added) + self.start("5.3.0") + self.assertTrue((self.code / "public/local/extra/version.php").is_file()) + + def test_another_release_replaces_the_tree_and_drops_what_it_no_longer_ships(self): + self.ship(LAYOUT_4) + self.start("4.5.11") + self.ship(LAYOUT_5) + self.start("5.3.0") + self.assertEqual(self.shipped_files_in_the_volume(), set(LAYOUT_5)) + + def test_a_volume_the_previous_entrypoint_marked_done_is_replaced(self): + self.write(self.code, LAYOUT_4) + (self.code / ".bootstrap.done").touch() + self.ship(LAYOUT_5) + self.start("5.3.0") + self.assertEqual(self.shipped_files_in_the_volume(), set(LAYOUT_5)) + + def test_a_missing_source_tree_fails_and_leaves_the_volume_unmarked(self): + done = self.run_entrypoint("5.3.0") + self.assertNotEqual(done.returncode, 0) + self.assertFalse((self.code / ".bootstrap.done").exists()) + + +if __name__ == "__main__": + unittest.main() From 9413aeba0894a1d2bb19b2124ee8f570ba26397f Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 7 Oct 2026 01:50:21 +0200 Subject: [PATCH 48/53] fix(web-app-gitea): give the MCP sidecar a healthcheck that can run gitea-mcp-server 1.8.0 is the first release that ships a HEALTHCHECK, and it is written in shell form for an image that has no shell. Every probe ends in 'exec: "/bin/sh": no such file or directory', the container turns unhealthy after three attempts, and Swarm replaces the task about every 72 seconds, so the service never converges. The role now declares the probe itself, in exec form and with the port the sidecar listens on: without it the probe asks 8080 whatever the server uses. The command took that port from the adapter's entry, it now reads the sidecar's own. The adapter waits for a healthy sidecar, so a probe that cannot pass fails a compose deploy as well and not only a Swarm one. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-gitea/meta/services.yml | 7 +++++++ roles/web-app-gitea/templates/compose.yml.j2 | 2 ++ roles/web-app-gitea/vars/main.yml | 2 +- 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/roles/web-app-gitea/meta/services.yml b/roles/web-app-gitea/meta/services.yml index 7b494ca53d..9b353e76c4 100644 --- a/roles/web-app-gitea/meta/services.yml +++ b/roles/web-app-gitea/meta/services.yml @@ -117,6 +117,13 @@ giteamcpupstream: type: registry_tags image: docker.gitea.com/gitea-mcp-server name: gitea-mcp + healthcheck: + test: + - "CMD" + - "/app/gitea-mcp" + - "-healthcheck" + - "--port" + - "{{ lookup('config', 'web-app-gitea', 'services.giteamcpupstream.ports.internal.http') | string }}" cpus: 0.25 mem_reservation: 0.1g mem_limit: 0.25g diff --git a/roles/web-app-gitea/templates/compose.yml.j2 b/roles/web-app-gitea/templates/compose.yml.j2 index 2e56345b14..8ebf840c08 100644 --- a/roles/web-app-gitea/templates/compose.yml.j2 +++ b/roles/web-app-gitea/templates/compose.yml.j2 @@ -28,6 +28,7 @@ GITEA_HOST: "{{ GITEA_MCP_UPSTREAM_URL }}" GITEA_SCOPES: "{{ GITEA_MCP_TOOL_SCOPES }}" GITEA_READONLY: "true" + {{ lookup('container_healthcheck', service_name) | indent(4) }} networks: # nocheck: networks-literal the sidecar authenticates nobody, so it joins the private upstream net and nothing else {{ GITEA_MCP_UPSTREAM_NETWORK }}: {{ lookup('depends_on', {'gitea': 'service_healthy'}) }} @@ -55,6 +56,7 @@ ADAPTER_PORT: "{{ GITEA_MCP_PORT }}" expose: - "{{ GITEA_MCP_PORT }}" + {{ lookup('depends_on', {GITEA_MCP_SIDECAR_SERVICE_KEY: 'service_healthy'}) }} {{ lookup('container_healthcheck', 'giteamcp') | indent(4) }} {{ lookup('container_networks', own_network_only=True, provider_self_alias=False) | indent(4) }} {{ GITEA_MCP_UPSTREAM_NETWORK }}: diff --git a/roles/web-app-gitea/vars/main.yml b/roles/web-app-gitea/vars/main.yml index 50fb563bdf..7b36c9e8e4 100644 --- a/roles/web-app-gitea/vars/main.yml +++ b/roles/web-app-gitea/vars/main.yml @@ -62,7 +62,7 @@ GITEA_MCP_COMMAND: - "-t" - "http" - "--port" - - "{{ GITEA_MCP_PORT | string }}" + - "{{ GITEA_MCP_SIDECAR_PORT | string }}" - "-r" GITEA_MCP_INITIALIZE_PAYLOAD: jsonrpc: "2.0" From 426ab1ea2a2e81617cb0e43881c18693f45a9113 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Wed, 7 Oct 2026 00:16:03 +0000 Subject: [PATCH 49/53] update(images): update Docker image versions (svc-db-elasticsearch) --- roles/svc-db-elasticsearch/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/svc-db-elasticsearch/meta/services.yml b/roles/svc-db-elasticsearch/meta/services.yml index 6f13b566e6..d40ab5fa1d 100644 --- a/roles/svc-db-elasticsearch/meta/services.yml +++ b/roles/svc-db-elasticsearch/meta/services.yml @@ -12,7 +12,7 @@ elasticsearch: bond: 1 image: elasticsearch name: elasticsearch - version: "9.5.3" + version: "9.5.5" min_storage: 1066MB backup: database_routine: true From eecdeecb9f5d174d60b252a2123f36e363d12f63 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Wed, 7 Oct 2026 00:16:10 +0000 Subject: [PATCH 50/53] update(images): update Docker image versions (web-app-gitea) --- roles/web-app-gitea/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-gitea/meta/services.yml b/roles/web-app-gitea/meta/services.yml index bf0b9f8563..5700465d75 100644 --- a/roles/web-app-gitea/meta/services.yml +++ b/roles/web-app-gitea/meta/services.yml @@ -49,7 +49,7 @@ gitea: shared: true provides: gitea image: gitea/gitea - version: 28.0.0 + version: 28.1.0 replicas: 1 # nocheck: single-replica single-writer app state on swarm-shared NFS; concurrent multi-node writers corrupt app.ini min_storage: 270MB backup: From d0ec38017ad12ad41d3acaa26c3608cc27a7383b Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 7 Oct 2026 02:30:44 +0200 Subject: [PATCH 51/53] fix(test-e2e-cli): name the negotiated MCP protocol version on requests MCP Adapter 0.7.0 for WordPress refuses a request that follows initialize without the MCP-Protocol-Version header: 'Invalid Request: MCP-Protocol-Version header is required for a 2025-06-18 session'. The contract probe never sent it, so the CLI test of web-app-wordpress failed at tools/list. The probe now keeps the version the server answers initialize with and sends it on every later request of the streamable HTTP transport, which the specification asks of a client since 2025-06-18. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../test-e2e-cli/files/shared/mcp/contract.py | 6 +- .../files/shared/mcp/test_contract.py | 74 +++++++++++++++++++ 2 files changed, 79 insertions(+), 1 deletion(-) diff --git a/roles/test-e2e-cli/files/shared/mcp/contract.py b/roles/test-e2e-cli/files/shared/mcp/contract.py index 4af0b34781..2d7010a175 100644 --- a/roles/test-e2e-cli/files/shared/mcp/contract.py +++ b/roles/test-e2e-cli/files/shared/mcp/contract.py @@ -76,7 +76,7 @@ SESSION_TIMEOUT = 20 WRONG_CREDENTIAL = "Bearer " + "0" * 40 SESSION_HEADER = "Mcp-Session-Id" -SESSION = {"id": ""} +SESSION = {"id": "", "protocol": ""} def unguarded_url(): @@ -120,6 +120,8 @@ def rpc(method, params=None, authorization=None, url=None, notification=False): request.add_header("Authorization", authorization) if SESSION["id"]: request.add_header(SESSION_HEADER, SESSION["id"]) + if SESSION["protocol"]: + request.add_header("MCP-Protocol-Version", SESSION["protocol"]) try: with urllib.request.urlopen(request, timeout=TIMEOUT) as response: # noqa: S310 fixed internal http origin session = response.headers.get(SESSION_HEADER) @@ -463,6 +465,8 @@ def main(): if status != 200: reject(f"authenticated initialize answered {status}: {body[:200]}") reject_error("authenticated initialize", rpc_error(body)) + result = json.loads(body).get("result") or {} + SESSION["protocol"] = result.get("protocolVersion", "") rpc("notifications/initialized", authorization=AUTH, notification=True) diff --git a/tests/unit/python/roles/test-e2e-cli/files/shared/mcp/test_contract.py b/tests/unit/python/roles/test-e2e-cli/files/shared/mcp/test_contract.py index f4fdf6163f..70086add9d 100644 --- a/tests/unit/python/roles/test-e2e-cli/files/shared/mcp/test_contract.py +++ b/tests/unit/python/roles/test-e2e-cli/files/shared/mcp/test_contract.py @@ -659,5 +659,79 @@ class TestSseSessionProbe(unittest.TestCase): self.assertIn("absent from the probed URL", stderr.getvalue()) +NEGOTIATED = "2025-03-26" + + +class StrictProvider: + def __init__(self): + self.seen = [] + self._server = ThreadingHTTPServer(("127.0.0.1", 0), self._handler()) + threading.Thread(target=self._server.serve_forever, daemon=True).start() + + @property + def url(self): + host, port = self._server.server_address[:2] + return f"http://{host}:{port}/mcp" + + def stop(self): + self._server.shutdown() + self._server.server_close() + + def _handler(self): + provider = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_POST(self): + length = int(self.headers.get("Content-Length", "0")) + payload = json.loads(self.rfile.read(length) or b"{}") + method = payload.get("method") + version = self.headers.get("MCP-Protocol-Version") + status, answer = 200, {"jsonrpc": "2.0", "id": payload.get("id")} + if self.headers.get("Authorization") != "Bearer real": + status, answer["error"] = 401, {"code": -32001, "message": "no"} + elif method == "initialize": + answer["result"] = {"protocolVersion": NEGOTIATED} + elif version != NEGOTIATED: + status = 400 + answer["error"] = { + "code": -32600, + "message": "MCP-Protocol-Version header is required", + } + elif method == "tools/list": + answer["result"] = { + "tools": [{"name": "a_get"}, {"name": "a_list"}] + } + else: + answer["result"] = {"isError": False, "content": []} + if method != "initialize": + provider.seen.append((method, version)) + body = json.dumps(answer).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + return Handler + + +class TestProtocolVersionHeader(unittest.TestCase): + def test_every_request_after_initialize_names_the_negotiated_version(self): + provider = StrictProvider() + self.addCleanup(provider.stop) + load({"MCP_URL": provider.url}).main() + self.assertEqual( + provider.seen, + [ + ("notifications/initialized", NEGOTIATED), + ("tools/list", NEGOTIATED), + ("tools/call", NEGOTIATED), + ], + ) + + if __name__ == "__main__": unittest.main() From 0c748f74ed6215cc6d7820f5277c93a316e17826 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 7 Oct 2026 10:40:42 +0200 Subject: [PATCH 52/53] fix(web-app-moodle): swap the code tree only after a complete copy The entrypoint removed the old tree before it copied the new one. A copy that failed left the volume without a working Moodle, and every restart removed again instead of recovering. It now copies into a staging directory inside the volume and swaps the trees once the copy is complete, so a failed copy leaves the old tree in place. An image that ships an older release than the volume records no longer replaces it and exits with a message instead. Two instances on different releases would otherwise overwrite each other's tree. upgrade.php reports "No upgrade needed" on stderr, so the task counted every run on a current site as a change. It reads stderr now. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-moodle/README.md | 2 +- .../files/build/moodle-entrypoint.sh | 21 +++++++++++++++++-- roles/web-app-moodle/tasks/01_manager_ops.yml | 2 +- .../files/build/test_moodle_entrypoint.py | 20 ++++++++++++++++++ 4 files changed, 41 insertions(+), 4 deletions(-) diff --git a/roles/web-app-moodle/README.md b/roles/web-app-moodle/README.md index 26abc2b719..fd795b0944 100644 --- a/roles/web-app-moodle/README.md +++ b/roles/web-app-moodle/README.md @@ -177,7 +177,7 @@ This role builds its own Moodle image from upstream Moodle source on top of the ## Updates -The image carries the Moodle release pinned as `services.moodle.app_version` in `meta/services.yml`. On start the entrypoint compares that release with the one recorded in the code volume and replaces the volume's tree with the image's when they differ. `tasks/01_manager_ops.yml` then runs `admin/cli/upgrade.php`, which migrates the database. +The image carries the Moodle release pinned as `services.moodle.app_version` in `meta/services.yml`. On start the entrypoint compares that release with the one recorded in the code volume. When the image is newer, it copies the image's tree next to the old one and swaps them once the copy is complete. An image that is older than the recorded release refuses to start. `tasks/01_manager_ops.yml` then runs `admin/cli/upgrade.php`, which migrates the database. Plugins installed through the web interface live only in the code volume and are not carried over to the next release. Declare a plugin under `meta/addons/` so the image ships it. diff --git a/roles/web-app-moodle/files/build/moodle-entrypoint.sh b/roles/web-app-moodle/files/build/moodle-entrypoint.sh index 7db4d61cb2..30083ff2ff 100644 --- a/roles/web-app-moodle/files/build/moodle-entrypoint.sh +++ b/roles/web-app-moodle/files/build/moodle-entrypoint.sh @@ -18,6 +18,7 @@ set -euo pipefail MOODLE_BOOTSTRAP_SENTINEL="${MOODLE_CODE_DIR}/.bootstrap.done" MOODLE_BOOTSTRAP_LOCK="${MOODLE_CODE_DIR}/.bootstrap.lock" +MOODLE_BOOTSTRAP_STAGE="${MOODLE_CODE_DIR}/.bootstrap.stage" mkdir -p "${MOODLE_DATA_DIR}" chown -R "${MOODLE_RUNTIME_USER}:${MOODLE_RUNTIME_USER}" "${MOODLE_DATA_DIR}" || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error @@ -31,12 +32,28 @@ moodle_code_dir_is_current() { [ "$(cat "${MOODLE_BOOTSTRAP_SENTINEL}" 2>/dev/null)" = "${MOODLE_RELEASE}" ] } +moodle_code_dir_is_newer() { + local recorded newest + recorded="$(cat "${MOODLE_BOOTSTRAP_SENTINEL}" 2>/dev/null)" || return 1 + [ -n "${recorded}" ] || return 1 + newest="$(printf '%s\n' "${recorded}" "${MOODLE_RELEASE}" | sort -V | tail -n 1)" + [ "${newest}" = "${recorded}" ] && [ "${recorded}" != "${MOODLE_RELEASE}" ] +} + moodle_bootstrap_code_dir() { if moodle_code_dir_is_current; then return 0 fi - find "${MOODLE_CODE_DIR}" -mindepth 1 -maxdepth 1 ! -name "${MOODLE_BOOTSTRAP_LOCK##*/}" -exec rm -rf {} + - cp -a "${MOODLE_SOURCE_DIR}/." "${MOODLE_CODE_DIR}/" + if moodle_code_dir_is_newer; then + echo "The code volume holds Moodle $(cat "${MOODLE_BOOTSTRAP_SENTINEL}"), this image ships the older ${MOODLE_RELEASE}; refusing to replace it." >&2 + exit 1 + fi + rm -rf "${MOODLE_BOOTSTRAP_STAGE}" + mkdir "${MOODLE_BOOTSTRAP_STAGE}" + cp -a "${MOODLE_SOURCE_DIR}/." "${MOODLE_BOOTSTRAP_STAGE}/" + find "${MOODLE_CODE_DIR}" -mindepth 1 -maxdepth 1 ! -name "${MOODLE_BOOTSTRAP_LOCK##*/}" ! -name "${MOODLE_BOOTSTRAP_STAGE##*/}" -exec rm -rf {} + + find "${MOODLE_BOOTSTRAP_STAGE}" -mindepth 1 -maxdepth 1 -exec mv -t "${MOODLE_CODE_DIR}" {} + + rmdir "${MOODLE_BOOTSTRAP_STAGE}" chown -R "${MOODLE_RUNTIME_USER}:${MOODLE_RUNTIME_USER}" "${MOODLE_CODE_DIR}" || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error find "${MOODLE_CODE_DIR}" -type d -exec chmod 0755 {} + || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error find "${MOODLE_CODE_DIR}" -type f -exec chmod 0644 {} + || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error diff --git a/roles/web-app-moodle/tasks/01_manager_ops.yml b/roles/web-app-moodle/tasks/01_manager_ops.yml index af4f17a537..93cd1d5e97 100644 --- a/roles/web-app-moodle/tasks/01_manager_ops.yml +++ b/roles/web-app-moodle/tasks/01_manager_ops.yml @@ -53,7 +53,7 @@ container exec --user {{ MOODLE_RUNTIME_USER }} {{ MOODLE_CONTAINER_ADDRESS }} php {{ MOODLE_CLI_DIR }}/upgrade.php --non-interactive register: moodle_upgrade - changed_when: "'No upgrade needed' not in moodle_upgrade.stdout" + changed_when: "'No upgrade needed' not in moodle_upgrade.stderr" - name: "🔑 Realign the administrator password Moodle persisted at install" when: not (MOODLE_OIDC_ENABLED | bool) diff --git a/tests/unit/python/roles/web-app-moodle/files/build/test_moodle_entrypoint.py b/tests/unit/python/roles/web-app-moodle/files/build/test_moodle_entrypoint.py index 3ba63ebb1e..9ed0c5bcb0 100644 --- a/tests/unit/python/roles/web-app-moodle/files/build/test_moodle_entrypoint.py +++ b/tests/unit/python/roles/web-app-moodle/files/build/test_moodle_entrypoint.py @@ -7,6 +7,7 @@ import unittest from pathlib import Path from utils import PROJECT_ROOT +from utils.cache.files import read_text ENTRYPOINT = PROJECT_ROOT / "roles/web-app-moodle/files/build/moodle-entrypoint.sh" @@ -99,6 +100,25 @@ class TestMoodleEntrypoint(unittest.TestCase): self.assertNotEqual(done.returncode, 0) self.assertFalse((self.code / ".bootstrap.done").exists()) + def test_a_failed_copy_keeps_the_tree_the_volume_held(self): + self.ship(LAYOUT_4) + self.start("4.5.11") + shutil.rmtree(self.source) + done = self.run_entrypoint("5.3.0") + self.assertNotEqual(done.returncode, 0) + self.assertEqual(self.shipped_files_in_the_volume(), set(LAYOUT_4)) + self.assertEqual(read_text(str(self.code / ".bootstrap.done")), "4.5.11") + + def test_an_image_older_than_the_recorded_release_refuses_to_replace_it(self): + self.ship(LAYOUT_5) + self.start("5.10.0") + self.ship(LAYOUT_4) + done = self.run_entrypoint("5.9.2") + self.assertNotEqual(done.returncode, 0) + self.assertIn("5.10.0", done.stderr) + self.assertEqual(self.shipped_files_in_the_volume(), set(LAYOUT_5)) + self.assertEqual(read_text(str(self.code / ".bootstrap.done")), "5.10.0") + if __name__ == "__main__": unittest.main() From 1d5e7f76e1ba67ef541c44c86f9c0f6df5e08d3f Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 7 Oct 2026 12:24:23 +0200 Subject: [PATCH 53/53] fix(web-app-n8n): resolve the SSO hook's modules and roles as n8n 2 does n8n 2 installs its dependencies as a strict pnpm tree, so the hook's require('router/lib/layer') and require('bcryptjs') no longer resolve from the hook file. The n8n.ready hook failed with "Cannot find module 'router/lib/layer'", n8n exited, and the deploy ran into the timeout of the readiness check. The hook now resolves both through n8n's own module, the router by way of express. A user's role is a relation in n8n 2. The hook loads it together with the user, since the role check refuses an account without it, and creates a new account with the role as an object, the shape n8n's own SSO code passes. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-n8n/files/javascript/hooks.js | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/roles/web-app-n8n/files/javascript/hooks.js b/roles/web-app-n8n/files/javascript/hooks.js index 9b70bddff5..80e3f06db6 100644 --- a/roles/web-app-n8n/files/javascript/hooks.js +++ b/roles/web-app-n8n/files/javascript/hooks.js @@ -48,10 +48,12 @@ module.exports = { this.logger?.info(`SSO middleware initializing with header: ${headerName}`); - const Layer = require('router/lib/layer'); + const { createRequire } = require('module'); const { dirname, resolve } = require('path'); const { randomBytes } = require('crypto'); - const { hash } = require('bcryptjs'); + const n8nRequire = createRequire(require.resolve('n8n')); + const Layer = createRequire(n8nRequire.resolve('express'))('router/lib/layer'); + const { hash } = n8nRequire('bcryptjs'); const { issueCookie } = require(resolve(dirname(require.resolve('n8n')), 'auth/jwt')); // Trust the proxy for correct X-Forwarded-* handling and rate limiting @@ -114,18 +116,17 @@ module.exports = { this.logger?.info(`SSO auto-login attempt for email: ${userEmail}`); - // 1) Try to fetch the user (n8n 1.95.3 stores 'role' as a plain string column) let user = await UserRepo.findOne({ where: { email: userEmail }, + relations: ['role'], }); - // 2) If not found — create the user (with 'global:member' role) and a project if (!user) { const hashed = await hash(randomBytes(16).toString('hex'), 10); const userData = { email: userEmail, - role: 'global:member', // string-based role is valid for createUserWithProject + role: { slug: 'global:member' }, password: hashed, }; if (userFirstName) userData.firstName = userFirstName; @@ -136,7 +137,6 @@ module.exports = { this.logger?.info(`Created new user: ${userEmail} (${userFirstName} ${userLastName}) via SSO`); } else { - // 3) Update first/last name if they changed upstream let changed = false; if (userFirstName && user.firstName !== userFirstName) { user.firstName = userFirstName; @@ -154,7 +154,6 @@ module.exports = { } } - // 4) Ensure 'user.role' exists (plain string column, e.g. 'global:member') if (!user.role) { this.logger?.error(`User ${userEmail} has no valid role; cannot issue cookie.`); res.statusCode = 401; @@ -162,10 +161,8 @@ module.exports = { return; } - // 5) Issue n8n auth cookie issueCookie(res, user); - // 6) Attach context for downstream middleware/routes req.user = user; req.userId = user.id;