From 1f8fc336e645d8c52a214b892c83be5a59a6426c Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 28 Oct 2026 21:38:38 +0100 Subject: [PATCH 01/42] feat(proxy): per-app nosniff, Referrer-Policy, Permissions-Policy and HSTS directives #1115 raised HSTS to one year but set no X-Content-Type-Options, Referrer-Policy, Permissions-Policy or HSTS includeSubDomains/preload, because none of them is safe globally: nosniff lets ORB block no-cors responses typed text/html, includeSubDomains on the apex covers hosts the platform does not serve, and a server-level add_header is dropped in every location that sets its own. WEBSERVER_SECURITY_HEADERS (group_vars/all/04_webserver.yml) now holds the platform values, all opt-in: nosniff false, no Referrer-Policy, no Permissions-Policy, HSTS max-age one year without includeSubDomains or preload. A role overrides any key under security_headers in its meta/server.yml, an inventory under applications..server.security_headers. The new security_headers filter merges both, rejects unknown keys, wrong types, unknown Referrer-Policy tokens, non-printable header values and preload without includeSubDomains or below a one-year max-age, and composes the HSTS value. - nosniff, Referrer-Policy and Permissions-Policy are set in the Lua header filter of content_security_policy.conf.j2, next to CSP, so a location's own add_header cannot drop them. Referrer-Policy is only set when the upstream sends none; Permissions-Policy only on HTML documents. - HSTS stays the single server-level add_header in nginx_ssl_header.j2, now with the per-app value. A second emitter in Lua would duplicate the header. It stays inside the TLS branch, which onion vhosts never enter, so an onion vhost gets no HSTS even when its app opts in. No role opts in yet, so rendered vhosts are unchanged. Closes #1123 Co-Authored-By: Claude Opus 5.5 --- group_vars/all/04_webserver.yml | 10 ++ plugins/filter/security_headers.py | 10 ++ .../templates/nginx_ssl_header.j2 | 2 +- roles/sys-svc-proxy/README.md | 26 ++- .../headers/content_security_policy.conf.j2 | 2 + .../templates/headers/security_headers.lua.j2 | 14 ++ .../plugins/filter/test_security_headers.py | 153 ++++++++++++++++ .../python/roles/sys-front-tls/__init__.py | 3 + .../roles/sys-front-tls/templates/__init__.py | 5 + .../templates/test_nginx_ssl_header.py | 103 +++++++++++ .../templates/test_security_headers_lua.py | 117 ++++++++++++ utils/roles/applications/security_headers.py | 168 ++++++++++++++++++ 12 files changed, 611 insertions(+), 2 deletions(-) create mode 100644 plugins/filter/security_headers.py create mode 100644 roles/sys-svc-proxy/templates/headers/security_headers.lua.j2 create mode 100644 tests/unit/python/plugins/filter/test_security_headers.py create mode 100644 tests/unit/python/roles/sys-front-tls/__init__.py create mode 100644 tests/unit/python/roles/sys-front-tls/templates/__init__.py create mode 100644 tests/unit/python/roles/sys-front-tls/templates/test_nginx_ssl_header.py create mode 100644 tests/unit/python/roles/sys-svc-proxy/templates/test_security_headers_lua.py create mode 100644 utils/roles/applications/security_headers.py diff --git a/group_vars/all/04_webserver.yml b/group_vars/all/04_webserver.yml index b0af51f9eb..5168689cb9 100644 --- a/group_vars/all/04_webserver.yml +++ b/group_vars/all/04_webserver.yml @@ -24,3 +24,13 @@ WEBSERVER_WORKER_CONNECTIONS: >- (lookup('applications') | resource_filter(application_id, 'pids_limit', service_name | default(''), RESOURCE_PIDS_LIMIT)) | int ] | min }} + +# Response security headers of every vhost; an app overrides any key under `security_headers` in its meta/server.yml. +WEBSERVER_SECURITY_HEADERS: + nosniff: false # X-Content-Type-Options: nosniff + referrer_policy: "" # Referrer-Policy, sent only when the upstream sends none; "" sends none + permissions_policy: "" # Permissions-Policy on HTML documents; "" sends none + hsts: + max_age: 31536000 # Strict-Transport-Security max-age in seconds + include_subdomains: false # adds includeSubDomains, which covers every subdomain of the vhost + preload: false # adds preload; requires include_subdomains and a max_age of one year diff --git a/plugins/filter/security_headers.py b/plugins/filter/security_headers.py new file mode 100644 index 0000000000..78af696964 --- /dev/null +++ b/plugins/filter/security_headers.py @@ -0,0 +1,10 @@ +"""Expose the response security headers of one application to templates.""" + +from __future__ import annotations + +from utils.roles.applications.security_headers import security_headers + + +class FilterModule: + def filters(self): + return {"security_headers": security_headers} diff --git a/roles/sys-front-tls/templates/nginx_ssl_header.j2 b/roles/sys-front-tls/templates/nginx_ssl_header.j2 index 6fc4b4f1a7..00526b0318 100644 --- a/roles/sys-front-tls/templates/nginx_ssl_header.j2 +++ b/roles/sys-front-tls/templates/nginx_ssl_header.j2 @@ -11,7 +11,7 @@ ssl_session_timeout 1d; ssl_session_cache shared:SSL:50m; ssl_session_tickets on; -add_header Strict-Transport-Security max-age=31536000 always; +add_header Strict-Transport-Security "{{ (lookup('applications') | security_headers(application_id, WEBSERVER_SECURITY_HEADERS)).hsts }}" always; ssl_stapling on; ssl_stapling_verify on; diff --git a/roles/sys-svc-proxy/README.md b/roles/sys-svc-proxy/README.md index 65120388ba..d284cf5588 100644 --- a/roles/sys-svc-proxy/README.md +++ b/roles/sys-svc-proxy/README.md @@ -31,11 +31,35 @@ The goal of this role is to deliver a **hassle-free, production-ready reverse pr - **Automatic TLS & HSTS**: integrates with the *sys-svc-webserver-https* role for certificate management. - **Flexible vHost templates**: *basic* and *ws_generic* flavours cover standard HTTP and WebSocket applications. -- **Security headers**: sensible defaults plus optional X-Frame-Options / CSP based on application settings. +- **Security headers**: CSP from each role's `meta/csp.yml`, plus the per-role headers described in [Security Headers](#security-headers). - **WebSocket & HTTP/2 aware**: upgrades, keep-alive tuning, and gzip already configured. - **OAuth2 gating**: drop-in support when *web-app-keycloak's SSO-proxy sidecar* is present. - **Modular includes**: headers, locations, and global snippets are factored for easy extension. +## Security Headers + +`WEBSERVER_SECURITY_HEADERS` in [04_webserver.yml](../../group_vars/all/04_webserver.yml) holds the platform values. A role overrides any key under `security_headers` in its `meta/server.yml`; an inventory overrides it at `applications..server.security_headers`. + +```yaml +# roles//meta/server.yml +security_headers: + nosniff: true + referrer_policy: strict-origin-when-cross-origin + permissions_policy: 'camera=(self "https://meet.example.org"), microphone=(self)' + hsts: + include_subdomains: true + preload: true +``` + +| Key | Header | Where it is rendered | +|---|---|---| +| `nosniff` | `X-Content-Type-Options: nosniff` | every response of a location that includes [content_security_policy.conf.j2](templates/headers/content_security_policy.conf.j2) | +| `referrer_policy` | `Referrer-Policy` | the same locations, only when the upstream sends none | +| `permissions_policy` | `Permissions-Policy` | HTML documents of the same locations | +| `hsts.*` | `Strict-Transport-Security` | the server block of every TLS vhost, via [nginx_ssl_header.j2](../sys-front-tls/templates/nginx_ssl_header.j2); an onion vhost has no TLS and gets none | + +The `security_headers` filter rejects unknown keys, wrong types, unknown `Referrer-Policy` tokens, and `preload` without `include_subdomains` or below a one-year `max_age`. + ## Credits Implemented by **[Kevin Veen-Birkenbach](https://www.veen.world)**. diff --git a/roles/sys-svc-proxy/templates/headers/content_security_policy.conf.j2 b/roles/sys-svc-proxy/templates/headers/content_security_policy.conf.j2 index 80d3b05a73..e1aeca87e3 100644 --- a/roles/sys-svc-proxy/templates/headers/content_security_policy.conf.j2 +++ b/roles/sys-svc-proxy/templates/headers/content_security_policy.conf.j2 @@ -19,6 +19,8 @@ header_filter_by_lua_block { ngx.header["Content-Security-Policy-Report-Only"] = nil end +{% include 'roles/sys-svc-proxy/templates/headers/security_headers.lua.j2' %} + -- If you'll modify the body later, drop Content-Length on HTML if is_html then ngx.ctx.is_html = true diff --git a/roles/sys-svc-proxy/templates/headers/security_headers.lua.j2 b/roles/sys-svc-proxy/templates/headers/security_headers.lua.j2 new file mode 100644 index 0000000000..58dd96ed17 --- /dev/null +++ b/roles/sys-svc-proxy/templates/headers/security_headers.lua.j2 @@ -0,0 +1,14 @@ +{% set _security_headers = lookup('applications') | security_headers(application_id, WEBSERVER_SECURITY_HEADERS) %} +{% if _security_headers.nosniff %} + ngx.header["X-Content-Type-Options"] = "nosniff" +{% endif %} +{% if _security_headers.referrer_policy %} + if not ngx.header["Referrer-Policy"] then + ngx.header["Referrer-Policy"] = {{ _security_headers.referrer_policy | to_json }} + end +{% endif %} +{% if _security_headers.permissions_policy %} + if is_html then + ngx.header["Permissions-Policy"] = {{ _security_headers.permissions_policy | to_json }} + end +{% endif %} diff --git a/tests/unit/python/plugins/filter/test_security_headers.py b/tests/unit/python/plugins/filter/test_security_headers.py new file mode 100644 index 0000000000..797f9e5f88 --- /dev/null +++ b/tests/unit/python/plugins/filter/test_security_headers.py @@ -0,0 +1,153 @@ +import copy +import unittest + +from plugins.filter.security_headers import FilterModule +from utils.cache.yaml import load_yaml +from utils.roles.applications.security_headers import security_headers + +from . import PROJECT_ROOT + +PLATFORM = { + "nosniff": False, + "referrer_policy": "", + "permissions_policy": "", + "hsts": {"max_age": 31536000, "include_subdomains": False, "preload": False}, +} + + +def apps_with(override): + """Return an applications map whose one app declares *override*. + + Args: + override: the app's ``server.security_headers`` block. + """ + return {"web-app-x": {"server": {"security_headers": override}}} + + +class TestPlatformValues(unittest.TestCase): + def test_an_app_without_a_block_gets_the_platform_values(self): + apps = {"web-app-plain": {"server": {"status_codes": {"default": [200]}}}} + self.assertEqual( + security_headers(apps, "web-app-plain", PLATFORM), + { + "nosniff": False, + "referrer_policy": "", + "permissions_policy": "", + "hsts": "max-age=31536000", + }, + ) + + def test_a_redirect_vhost_passes_its_domain_and_gets_the_platform_values(self): + result = security_headers(apps_with({"nosniff": True}), "old.example", PLATFORM) + self.assertFalse(result["nosniff"]) + self.assertEqual(result["hsts"], "max-age=31536000") + + def test_the_repository_platform_values_are_valid(self): + platform = load_yaml(PROJECT_ROOT / "group_vars/all/04_webserver.yml")[ + "WEBSERVER_SECURITY_HEADERS" + ] + self.assertEqual( + security_headers({}, "web-app-plain", platform)["hsts"], + "max-age=31536000", + ) + + def test_an_incomplete_platform_block_fails(self): + platform = copy.deepcopy(PLATFORM) + del platform["hsts"]["preload"] + with self.assertRaisesRegex(ValueError, "preload"): + security_headers({}, "web-app-plain", platform) + + def test_the_platform_block_is_not_mutated(self): + platform = copy.deepcopy(PLATFORM) + security_headers( + apps_with({"hsts": {"include_subdomains": True}}), "web-app-x", platform + ) + self.assertEqual(platform, PLATFORM) + + +class TestOverrides(unittest.TestCase): + def test_an_override_replaces_only_its_own_keys(self): + result = security_headers( + apps_with({"nosniff": True, "hsts": {"include_subdomains": True}}), + "web-app-x", + PLATFORM, + ) + self.assertTrue(result["nosniff"]) + self.assertEqual(result["referrer_policy"], "") + self.assertEqual(result["hsts"], "max-age=31536000; includeSubDomains") + + def test_preload_follows_include_subdomains(self): + result = security_headers( + apps_with({"hsts": {"include_subdomains": True, "preload": True}}), + "web-app-x", + PLATFORM, + ) + self.assertEqual(result["hsts"], "max-age=31536000; includeSubDomains; preload") + + def test_a_referrer_policy_list_is_accepted(self): + value = "no-referrer, strict-origin-when-cross-origin" + result = security_headers( + apps_with({"referrer_policy": value}), "web-app-x", PLATFORM + ) + self.assertEqual(result["referrer_policy"], value) + + def test_a_permissions_policy_keeps_its_quoted_origins(self): + value = 'camera=(self "https://meet.example.org"), microphone=(self)' + result = security_headers( + apps_with({"permissions_policy": value}), "web-app-x", PLATFORM + ) + self.assertEqual(result["permissions_policy"], value) + + +class TestRejections(unittest.TestCase): + def assert_rejected(self, override, pattern, error=ValueError): + with self.assertRaisesRegex(error, pattern): + security_headers(apps_with(override), "web-app-x", PLATFORM) + + def test_an_unknown_key_fails(self): + self.assert_rejected({"nosnif": True}, "unknown keys") + + def test_an_unknown_hsts_key_fails(self): + self.assert_rejected({"hsts": {"subdomains": True}}, "unknown keys") + + def test_a_non_mapping_block_fails(self): + self.assert_rejected(None, "must be a mapping", TypeError) + + def test_a_string_flag_fails(self): + self.assert_rejected({"nosniff": "yes"}, "must be bool", TypeError) + + def test_a_boolean_max_age_fails(self): + self.assert_rejected({"hsts": {"max_age": True}}, "must be int", TypeError) + + def test_a_negative_max_age_fails(self): + self.assert_rejected({"hsts": {"max_age": -1}}, "negative") + + def test_preload_without_include_subdomains_fails(self): + self.assert_rejected({"hsts": {"preload": True}}, "requires include_subdomains") + + def test_preload_with_a_short_max_age_fails(self): + self.assert_rejected( + {"hsts": {"max_age": 86400, "include_subdomains": True, "preload": True}}, + "at least 31536000", + ) + + def test_an_unknown_referrer_policy_token_fails(self): + self.assert_rejected( + {"referrer_policy": "strict-origin-when-cross-orgin"}, + "unknown policy tokens", + ) + + def test_a_line_break_in_a_header_value_fails(self): + self.assert_rejected( + {"permissions_policy": "camera=()\r\nSet-Cookie: x=1"}, + "printable ASCII", + ) + + +class TestFilterModule(unittest.TestCase): + def test_filter_is_registered(self): + self.assertIs(FilterModule().filters()["security_headers"], security_headers) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/sys-front-tls/__init__.py b/tests/unit/python/roles/sys-front-tls/__init__.py new file mode 100644 index 0000000000..8ee16d7567 --- /dev/null +++ b/tests/unit/python/roles/sys-front-tls/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] diff --git a/tests/unit/python/roles/sys-front-tls/templates/__init__.py b/tests/unit/python/roles/sys-front-tls/templates/__init__.py new file mode 100644 index 0000000000..087c384b57 --- /dev/null +++ b/tests/unit/python/roles/sys-front-tls/templates/__init__.py @@ -0,0 +1,5 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/sys-front-tls/templates/test_nginx_ssl_header.py b/tests/unit/python/roles/sys-front-tls/templates/test_nginx_ssl_header.py new file mode 100644 index 0000000000..851cbed1b7 --- /dev/null +++ b/tests/unit/python/roles/sys-front-tls/templates/test_nginx_ssl_header.py @@ -0,0 +1,103 @@ +from __future__ import annotations + +import re +import unittest + +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape + +from plugins.filter.security_headers import FilterModule +from utils.tls_common import resolve_enabled + +from . import PROJECT_ROOT + +TEMPLATE = "roles/sys-front-tls/templates/nginx_ssl_header.j2" + +PLATFORM = { + "nosniff": False, + "referrer_policy": "", + "permissions_policy": "", + "hsts": {"max_age": 31536000, "include_subdomains": False, "preload": False}, +} + +PRIMARY_DOMAINS = { + "web-app-x": "x.example.org", + "web-app-onion": "x.abcdefghijklmnop.onion", + "old.example.org": "old.example.org", +} + + +def render(application_id: str, override: dict) -> str: + """Return the TLS server header of one vhost. + + Args: + application_id: the app the vhost belongs to, or a redirect domain. + override: the app's ``server.security_headers`` block. + """ + applications = { + app: {"server": {"security_headers": override}} + for app in ("web-app-x", "web-app-onion") + } + + def lookup(kind, *args, **_kw): + if kind == "applications": + return applications + if kind == "tls": + term, want = args + enabled = resolve_enabled( + applications.get(term, {}), True, primary_domain=PRIMARY_DOMAINS[term] + ) + return {"enabled": enabled, "ports.web": 443 if enabled else 80}[want] + if kind == "cert": + return f"/etc/certs/{args[0]}/{args[1]}" + raise AssertionError(f"unexpected lookup {kind!r}") + + env = Environment( + loader=FileSystemLoader(str(PROJECT_ROOT)), + undefined=StrictUndefined, + autoescape=select_autoescape(), + ) + env.filters.update(FilterModule().filters()) + env.filters["bool"] = bool + return env.get_template(TEMPLATE).render( + application_id=application_id, + lookup=lookup, + WEBSERVER_SECURITY_HEADERS=PLATFORM, + ) + + +def hsts(rendered: str) -> list[str]: + """Return every Strict-Transport-Security value the header adds. + + Args: + rendered: the rendered TLS server header. + """ + return re.findall( + r'^add_header Strict-Transport-Security "([^"]*)" always;$', + rendered, + re.MULTILINE, + ) + + +class TestHsts(unittest.TestCase): + def test_the_platform_value_is_one_year_without_subdomains(self): + self.assertEqual(hsts(render("web-app-x", {})), ["max-age=31536000"]) + + def test_include_subdomains_and_preload_are_opt_in_per_app(self): + rendered = render( + "web-app-x", {"hsts": {"include_subdomains": True, "preload": True}} + ) + self.assertEqual( + hsts(rendered), ["max-age=31536000; includeSubDomains; preload"] + ) + + def test_a_redirect_vhost_sends_the_platform_value(self): + self.assertEqual(hsts(render("old.example.org", {})), ["max-age=31536000"]) + + def test_an_onion_vhost_sends_no_hsts_even_when_opted_in(self): + rendered = render("web-app-onion", {"hsts": {"include_subdomains": True}}) + self.assertNotIn("Strict-Transport-Security", rendered) + self.assertNotIn("ssl", rendered) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/sys-svc-proxy/templates/test_security_headers_lua.py b/tests/unit/python/roles/sys-svc-proxy/templates/test_security_headers_lua.py new file mode 100644 index 0000000000..3baee51efc --- /dev/null +++ b/tests/unit/python/roles/sys-svc-proxy/templates/test_security_headers_lua.py @@ -0,0 +1,117 @@ +"""Exception: a location with its own ``add_header`` drops every server-level one, +so these headers live in the Lua header filter of ``content_security_policy.conf.j2``. +""" + +from __future__ import annotations + +import json +import re +import unittest + +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape + +from plugins.filter.security_headers import FilterModule +from utils.cache.files import read_text + +from . import PROJECT_ROOT + +SNIPPET = "roles/sys-svc-proxy/templates/headers/security_headers.lua.j2" +CSP_TEMPLATE = "roles/sys-svc-proxy/templates/headers/content_security_policy.conf.j2" + +PLATFORM = { + "nosniff": False, + "referrer_policy": "", + "permissions_policy": "", + "hsts": {"max_age": 31536000, "include_subdomains": False, "preload": False}, +} + + +def render(override: dict) -> str: + """Return the Lua snippet for an app declaring *override*. + + Args: + override: the app's ``server.security_headers`` block. + """ + applications = {"web-app-x": {"server": {"security_headers": override}}} + + def lookup(kind, *_args, **_kw): + if kind == "applications": + return applications + raise AssertionError(f"unexpected lookup {kind!r}") + + env = Environment( + loader=FileSystemLoader(str(PROJECT_ROOT)), + undefined=StrictUndefined, + autoescape=select_autoescape(), + ) + env.filters.update(FilterModule().filters()) + env.filters["to_json"] = json.dumps + return env.get_template(SNIPPET).render( + application_id="web-app-x", + lookup=lookup, + WEBSERVER_SECURITY_HEADERS=PLATFORM, + ) + + +def assignment(rendered: str, header: str) -> str: + """Return the Lua literal assigned to *header*, or an empty string. + + Args: + rendered: the rendered snippet. + header: the response header name. + """ + match = re.search( + rf'ngx\.header\["{re.escape(header)}"\] = (".*")$', rendered, re.MULTILINE + ) + return match.group(1) if match else "" + + +class TestSecurityHeadersSnippet(unittest.TestCase): + def test_the_platform_values_send_nothing(self): + self.assertNotIn("ngx.header", render({})) + + def test_nosniff_is_sent_when_opted_in(self): + rendered = render({"nosniff": True}) + self.assertEqual( + json.loads(assignment(rendered, "X-Content-Type-Options")), "nosniff" + ) + + def test_the_referrer_policy_never_replaces_the_upstream_one(self): + rendered = render({"referrer_policy": "strict-origin-when-cross-origin"}) + self.assertRegex( + rendered, + r'if not ngx\.header\["Referrer-Policy"\] then\s+' + r'ngx\.header\["Referrer-Policy"\] = "strict-origin-when-cross-origin"\s+end', + ) + + def test_the_permissions_policy_is_sent_on_documents_only(self): + rendered = render({"permissions_policy": "camera=(self)"}) + self.assertRegex( + rendered, + r'if is_html then\s+ngx\.header\["Permissions-Policy"\] = "camera=\(self\)"\s+end', + ) + + def test_quoted_origins_stay_one_lua_string(self): + value = 'camera=(self "https://meet.example.org"), microphone=(self)' + rendered = render({"permissions_policy": value}) + self.assertEqual(json.loads(assignment(rendered, "Permissions-Policy")), value) + + def test_hsts_is_left_to_the_server_level_header(self): + rendered = render({"hsts": {"include_subdomains": True}}) + self.assertNotIn("Strict-Transport-Security", rendered) + + +class TestSnippetPlacement(unittest.TestCase): + def test_the_snippet_runs_inside_the_csp_header_filter_after_is_html(self): + text = read_text(str(PROJECT_ROOT / CSP_TEMPLATE)) + block = text.index("header_filter_by_lua_block {") + is_html = text.index("local is_html") + include = text.index(f"{{% include '{SNIPPET}' %}}") + block_end = text.index("\n}\n", block) + self.assertLess(block, is_html) + self.assertLess(is_html, include) + self.assertLess(include, block_end) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/roles/applications/security_headers.py b/utils/roles/applications/security_headers.py new file mode 100644 index 0000000000..f350bcc626 --- /dev/null +++ b/utils/roles/applications/security_headers.py @@ -0,0 +1,168 @@ +"""Response security headers the front proxy adds for one application. + +``WEBSERVER_SECURITY_HEADERS`` holds the platform values. An application +overrides any of them under ``security_headers`` in its ``meta/server.yml``. +""" + +from __future__ import annotations + +import re +from collections.abc import Mapping +from typing import Any + +from utils.roles.applications.config import get + +HSTS_PRELOAD_MIN_MAX_AGE = 31536000 + +REFERRER_POLICY_TOKENS = frozenset( + { + "no-referrer", + "no-referrer-when-downgrade", + "origin", + "origin-when-cross-origin", + "same-origin", + "strict-origin", + "strict-origin-when-cross-origin", + "unsafe-url", + } +) + +SCHEMA: dict[str, Any] = { + "nosniff": bool, + "referrer_policy": str, + "permissions_policy": str, + "hsts": { + "max_age": int, + "include_subdomains": bool, + "preload": bool, + }, +} + +_FIELD_VALUE = re.compile(r"[\x20-\x7e]*") + + +def _check_type(value: Any, expected: type, where: str) -> None: + if expected is int: + valid = isinstance(value, int) and not isinstance(value, bool) + else: + valid = isinstance(value, expected) + if not valid: + raise TypeError( + f"{where} must be {expected.__name__}, got {type(value).__name__} {value!r}" + ) + + +def _resolve( + schema: Mapping[str, Any], base: Any, override: Any, where: str +) -> dict[str, Any]: + """Validate *override* against *schema* and lay it over *base*. + + Args: + schema: the expected keys and their types. + base: the complete mapping the override applies to, ``None`` when + *override* is the complete mapping itself. + override: the mapping to validate; partial when *base* is given. + where: dotted origin of *override*, for error messages. + + Returns: + A complete mapping with every key of *schema*. + """ + if not isinstance(override, Mapping): + raise TypeError(f"{where} must be a mapping, got {override!r}") + unknown = sorted(set(override) - set(schema)) + if unknown: + raise ValueError(f"{where} has unknown keys {unknown}, known: {sorted(schema)}") + if base is None: + missing = sorted(set(schema) - set(override)) + if missing: + raise ValueError(f"{where} lacks the keys {missing}") + + resolved: dict[str, Any] = {} + for key, expected in schema.items(): + path = f"{where}.{key}" + if key not in override: + resolved[key] = base[key] + elif isinstance(expected, Mapping): + resolved[key] = _resolve( + expected, None if base is None else base[key], override[key], path + ) + else: + _check_type(override[key], expected, path) + resolved[key] = override[key] + return resolved + + +def _field_value(value: str, where: str) -> str: + if not _FIELD_VALUE.fullmatch(value): + raise ValueError(f"{where} must be printable ASCII, got {value!r}") + return value + + +def _referrer_policy(value: str, where: str) -> str: + _field_value(value, where) + if not value: + return value + unknown = [ + token + for token in (part.strip() for part in value.split(",")) + if token not in REFERRER_POLICY_TOKENS + ] + if unknown: + raise ValueError(f"{where} has unknown policy tokens {unknown}") + return value + + +def _hsts(hsts: Mapping[str, Any], where: str) -> str: + if hsts["max_age"] < 0: + raise ValueError(f"{where}.max_age must not be negative") + if hsts["preload"] and not hsts["include_subdomains"]: + raise ValueError(f"{where}.preload requires include_subdomains") + if hsts["preload"] and hsts["max_age"] < HSTS_PRELOAD_MIN_MAX_AGE: + raise ValueError( + f"{where}.preload requires a max_age of at least {HSTS_PRELOAD_MIN_MAX_AGE}" + ) + directives = [f"max-age={hsts['max_age']}"] + if hsts["include_subdomains"]: + directives.append("includeSubDomains") + if hsts["preload"]: + directives.append("preload") + return "; ".join(directives) + + +def security_headers( + applications: Mapping[str, Any], application_id: str, platform: Mapping[str, Any] +) -> dict[str, Any]: + """Return the security header values the proxy sends for *application_id*. + + Args: + applications: the applications SPOT. + application_id: the role whose vhost is rendered; a redirect vhost + passes its domain, which owns no override. + platform: ``WEBSERVER_SECURITY_HEADERS``. + + Returns: + ``nosniff`` as a bool, ``referrer_policy`` and ``permissions_policy`` + as header values (empty when not sent) and ``hsts`` as the complete + ``Strict-Transport-Security`` value. + """ + base = _resolve(SCHEMA, None, platform, "WEBSERVER_SECURITY_HEADERS") + where = f"applications[{application_id!r}].server.security_headers" + override = get( + applications, + application_id, + "server.security_headers", + strict=False, + default={}, + skip_missing_app=True, + ) + resolved = _resolve(SCHEMA, base, override, where) + return { + "nosniff": resolved["nosniff"], + "referrer_policy": _referrer_policy( + resolved["referrer_policy"], f"{where}.referrer_policy" + ), + "permissions_policy": _field_value( + resolved["permissions_policy"], f"{where}.permissions_policy" + ), + "hsts": _hsts(resolved["hsts"], f"{where}.hsts"), + } From e3d2a24bcd5ed38979f0542b680bf6344da9a9f0 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 28 Oct 2026 22:39:07 +0100 Subject: [PATCH 02/42] fix(sys-svc-compose-php): scope memory_limit -1 to unpatched images The interim CVE-2026-109618 mitigation lived in the shared hardening.ini, so every PHP role ran without a memory limit until the last image was patched, and no role's service_memory_mb share applied. Registry metadata of the images pinned on main shows that 16 of the 20 consumers already ship PHP 8.2.35, 8.3.36, 8.4.27 or 8.5.12 (or the Alpine/Debian build of it). Four predate the fix: markoshust/magento-php:8.4-fpm (8.4.21), ghcr.io/heviat/webmail:2024.06 (the Mailu OIDC flavor, built 2025-04-04), phpldapadmin/phpldapadmin:2.3.11 (built 2026-05-15) and ghcr.io/shopware/docker-base:8.3 (8.3.25). - Move memory_limit = -1 into its own content-addressed ini (FILE_PHP_MEMORY_UNLIMITED_INI) and mount it only in magento, mailu, phpldapadmin and shopware. - hardening.ini keeps expose_php, session.upload_progress.enabled and fatal_error_backtraces as permanent hardening. - Joomla's php-upload.ini loads as conf.d/uploads.ini again: no -1 has to be outranked anymore. - The root TODO names the four images that still need the override. Refs #1126 Co-Authored-By: Claude Opus 5.5 --- TODO.md | 2 +- group_vars/all/05_paths.yml | 2 ++ roles/sys-svc-compose-php/README.md | 12 ++++++++---- roles/sys-svc-compose-php/files/hardening.ini | 1 - roles/sys-svc-compose-php/files/memory-unlimited.ini | 1 + roles/sys-svc-compose-php/tasks/00_core.yml | 9 +++++++++ roles/web-app-joomla/meta/volumes.yml | 2 +- roles/web-app-magento/meta/volumes.yml | 8 ++++++++ roles/web-app-mailu/meta/volumes.yml | 7 +++++++ roles/web-app-phpldapadmin/meta/volumes.yml | 8 ++++++++ roles/web-app-shopware/meta/volumes.yml | 8 ++++++++ 11 files changed, 53 insertions(+), 7 deletions(-) create mode 100644 roles/sys-svc-compose-php/files/memory-unlimited.ini diff --git a/TODO.md b/TODO.md index e5edb52ecf..273e3021a6 100644 --- a/TODO.md +++ b/TODO.md @@ -4,7 +4,7 @@ - Implement rbac administration interface - Enable IP6 for docker. - backup docker to local für ca optimieren -- Drop `memory_limit = -1` from [hardening.ini](roles/sys-svc-compose-php/files/hardening.ini) once every PHP image ships PHP 8.2.35, 8.3.36, 8.4.27, 8.5.12 or later. It is the interim mitigation for CVE-2026-109618 and overrides the per-role `service_memory_mb` share, so a single request can exhaust the container instead of hitting a PHP limit. `web-app-joomla` keeps its own `memory_limit` because its media API compares uploads against it, and `web-app-magento` keeps the 756M its `nginx.conf.sample` (`PHP_VALUE`) and `pub/.user.ini` set; both keep `post_max_size` below a quarter of that limit. While the override is in place, `web-app-nextcloud` (`upload_limit` 5G at 3g) accepts POST bodies above a quarter of its container memory, `web-app-friendica` caps account imports at 64 MiB instead of half the memory limit, EspoCRM's System Requirements page flags `memory_limit` as failed, and Pixelfed (`InstanceService`), phpMyAdmin (import and export) and Snipe-IT (imports and LDAP sync) set a finite limit again via `ini_set` after the request has started. +- Drop the `php_memory_unlimited` mount ([memory-unlimited.ini](roles/sys-svc-compose-php/files/memory-unlimited.ini), `memory_limit = -1`) from each role whose image ships PHP 8.2.35, 8.3.36, 8.4.27, 8.5.12 or later, and the file, its install task and `FILE_PHP_MEMORY_UNLIMITED_INI` once no role mounts it. It is the interim mitigation for CVE-2026-109618 and overrides the per-role `service_memory_mb` share, so a single request can exhaust the container instead of hitting a PHP limit. Still mounted by `web-app-magento` (`markoshust/magento-php:8.4-fpm`, PHP 8.4.21), `web-app-mailu` (`ghcr.io/heviat/webmail:2024.06`, the OIDC flavor, built 2025-04-04), `web-app-phpldapadmin` (`phpldapadmin/phpldapadmin:2.3.11`, built 2026-05-15) and `web-app-shopware` (`ghcr.io/shopware/docker-base:8.3`, PHP 8.3.25). `web-app-magento` keeps the 756M its `nginx.conf.sample` (`PHP_VALUE`) and `pub/.user.ini` set and keeps `post_max_size` below a quarter of that limit. - Fork [rpardini/docker-registry-proxy](https://github.com/rpardini/docker-registry-proxy) and teach the bundled nginx to handle GCP Artifact Registry redirect URLs (`/artifacts-downloads/namespaces//repositories//downloads/`). Currently `gcr.io` blob pulls are bypassed via `NO_PROXY=…,gcr.io,storage.googleapis.com,googleusercontent.com` in [compose/registry-cache/proxy.conf](compose/registry-cache/proxy.conf), which is a workaround that disables caching for those registries. Long-term: rebase upstream's `proxy.conf` / `sub_filter` rules to recognise the new redirect shape, ship the fix in our fork, point `compose/registry-cache/Dockerfile` (or its image tag) at the fork, and drop the `NO_PROXY` bypass. ## Testing diff --git a/group_vars/all/05_paths.yml b/group_vars/all/05_paths.yml index 9683796ccf..50b755f85e 100644 --- a/group_vars/all/05_paths.yml +++ b/group_vars/all/05_paths.yml @@ -31,8 +31,10 @@ DIR_METRICS_TEXTFILE: "{{ [DIR_VAR_LIB, 'metrics'] | path_join }}" DIR_PHP_HARDENING: "/etc/{{ SOFTWARE_DOMAIN }}/php" PHP_HARDENING_INI_DIGEST: "{{ (lookup('file', lookup('path_absolute', 'roles/sys-svc-compose-php/files/hardening.ini')) | hash('sha1'))[:8] }}" +PHP_MEMORY_UNLIMITED_INI_DIGEST: "{{ (lookup('file', lookup('path_absolute', 'roles/sys-svc-compose-php/files/memory-unlimited.ini')) | hash('sha1'))[:8] }}" PHP_FPM_HARDENING_CONF_DIGEST: "{{ (lookup('template', lookup('path_absolute', 'roles/sys-svc-compose-php/templates/fpm-hardening.conf.j2')) | hash('sha1'))[:8] }}" FILE_PHP_HARDENING_INI: "{{ [DIR_PHP_HARDENING, 'hardening-' ~ PHP_HARDENING_INI_DIGEST ~ '.ini'] | path_join }}" +FILE_PHP_MEMORY_UNLIMITED_INI: "{{ [DIR_PHP_HARDENING, 'memory-unlimited-' ~ PHP_MEMORY_UNLIMITED_INI_DIGEST ~ '.ini'] | path_join }}" FILE_PHP_FPM_HARDENING_CONF: "{{ [DIR_PHP_HARDENING, 'fpm-hardening-' ~ PHP_FPM_HARDENING_CONF_DIGEST ~ '.conf'] | path_join }}" DIR_RESCUE_DIAGNOSTICS: "/tmp/infinito-rescue-diagnostics" diff --git a/roles/sys-svc-compose-php/README.md b/roles/sys-svc-compose-php/README.md index c908bc9196..bef096f408 100644 --- a/roles/sys-svc-compose-php/README.md +++ b/roles/sys-svc-compose-php/README.md @@ -8,11 +8,14 @@ configs from their own `meta/volumes.yml`. ## Overview -This role installs one PHP ini (`FILE_PHP_HARDENING_INI`) and one PHP-FPM pool -drop-in (`FILE_PHP_FPM_HARDENING_CONF`). A PHP role opts in by declaring a +This role installs one PHP ini (`FILE_PHP_HARDENING_INI`), one interim PHP ini +(`FILE_PHP_MEMORY_UNLIMITED_INI`) and one PHP-FPM pool drop-in +(`FILE_PHP_FPM_HARDENING_CONF`). A PHP role opts in by declaring a `type: config` entry with that file as `source` and a file inside the scan dir of its image as `target`, e.g. `conf.d/zz-infinito-hardening.ini` or, for the -pool, `php-fpm.d/zz-infinito-hardening.conf`. +pool, `php-fpm.d/zz-infinito-hardening.conf`. Only roles whose image still +ships a PHP release without the CVE-2026-109618 fix also mount +`FILE_PHP_MEMORY_UNLIMITED_INI`, as `conf.d/zz-infinito-memory-unlimited.ini`. ## Cosmos @@ -29,7 +32,8 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( ## Features -- **PHP ini hardening:** `expose_php` off; `session.upload_progress.enabled = 0` and, on PHP 8.5 only, `fatal_error_backtraces = 0` against CVE-2026-109619; the interim `memory_limit = -1` against CVE-2026-109618. +- **PHP ini hardening:** `expose_php` off; `session.upload_progress.enabled = 0` and, on PHP 8.5 only, `fatal_error_backtraces = 0` against CVE-2026-109619. +- **Interim CVE-2026-109618 mitigation:** `memory_limit = -1` for images that predate PHP 8.2.35, 8.3.36, 8.4.27 and 8.5.12. - **PHP-FPM worker recycling:** `pm.max_requests` from `PHP_FPM_MAX_REQUESTS` for images whose `[www]` pool reads `php-fpm.d/*.conf`. ## Credits diff --git a/roles/sys-svc-compose-php/files/hardening.ini b/roles/sys-svc-compose-php/files/hardening.ini index 2e5a25ec09..20ac81b037 100644 --- a/roles/sys-svc-compose-php/files/hardening.ini +++ b/roles/sys-svc-compose-php/files/hardening.ini @@ -1,4 +1,3 @@ expose_php = Off session.upload_progress.enabled = 0 fatal_error_backtraces = 0 -memory_limit = -1 diff --git a/roles/sys-svc-compose-php/files/memory-unlimited.ini b/roles/sys-svc-compose-php/files/memory-unlimited.ini new file mode 100644 index 0000000000..7999e96156 --- /dev/null +++ b/roles/sys-svc-compose-php/files/memory-unlimited.ini @@ -0,0 +1 @@ +memory_limit = -1 diff --git a/roles/sys-svc-compose-php/tasks/00_core.yml b/roles/sys-svc-compose-php/tasks/00_core.yml index c974b5eee9..fb69a45693 100644 --- a/roles/sys-svc-compose-php/tasks/00_core.yml +++ b/roles/sys-svc-compose-php/tasks/00_core.yml @@ -17,6 +17,15 @@ owner: root group: root +- name: "šŸ›”ļø PHP hardening | install interim memory ini" + become: true + stack_host_copy: + src: "memory-unlimited.ini" + dest: "{{ FILE_PHP_MEMORY_UNLIMITED_INI }}" + mode: "0444" + owner: root + group: root + - name: "šŸ›”ļø PHP hardening | render FPM pool" become: true stack_host_template: diff --git a/roles/web-app-joomla/meta/volumes.yml b/roles/web-app-joomla/meta/volumes.yml index f9bbb1d80c..d9c14bc427 100644 --- a/roles/web-app-joomla/meta/volumes.yml +++ b/roles/web-app-joomla/meta/volumes.yml @@ -12,7 +12,7 @@ php_upload: mode: "0444" mounts: - service: joomla - target: /usr/local/etc/php/conf.d/zzz-joomla-uploads.ini + target: /usr/local/etc/php/conf.d/uploads.ini php_hardening: type: config diff --git a/roles/web-app-magento/meta/volumes.yml b/roles/web-app-magento/meta/volumes.yml index 8fceecaa8a..541ceefd0d 100644 --- a/roles/web-app-magento/meta/volumes.yml +++ b/roles/web-app-magento/meta/volumes.yml @@ -31,3 +31,11 @@ php_hardening: mounts: - service: php target: /usr/local/etc/php/conf.d/zz-infinito-hardening.ini + +php_memory_unlimited: + type: config + source: "{{ FILE_PHP_MEMORY_UNLIMITED_INI }}" + mode: "0444" + mounts: + - service: php + target: /usr/local/etc/php/conf.d/zz-infinito-memory-unlimited.ini diff --git a/roles/web-app-mailu/meta/volumes.yml b/roles/web-app-mailu/meta/volumes.yml index 8616ec60f4..163df1c462 100644 --- a/roles/web-app-mailu/meta/volumes.yml +++ b/roles/web-app-mailu/meta/volumes.yml @@ -90,3 +90,10 @@ php_hardening: mounts: - service: webmail target: /etc/php83/conf.d/zz-infinito-hardening.ini +php_memory_unlimited: + type: config + source: "{{ FILE_PHP_MEMORY_UNLIMITED_INI }}" + mode: "0444" + mounts: + - service: webmail + target: /etc/php83/conf.d/zz-infinito-memory-unlimited.ini diff --git a/roles/web-app-phpldapadmin/meta/volumes.yml b/roles/web-app-phpldapadmin/meta/volumes.yml index df9e69ec7e..d5c7b46468 100644 --- a/roles/web-app-phpldapadmin/meta/volumes.yml +++ b/roles/web-app-phpldapadmin/meta/volumes.yml @@ -6,3 +6,11 @@ php_hardening: mounts: - service: phpldapadmin target: /usr/local/etc/php/conf.d/zz-infinito-hardening.ini + +php_memory_unlimited: + type: config + source: "{{ FILE_PHP_MEMORY_UNLIMITED_INI }}" + mode: "0444" + mounts: + - service: phpldapadmin + target: /usr/local/etc/php/conf.d/zz-infinito-memory-unlimited.ini diff --git a/roles/web-app-shopware/meta/volumes.yml b/roles/web-app-shopware/meta/volumes.yml index 021a1a0809..44cfe23ed8 100644 --- a/roles/web-app-shopware/meta/volumes.yml +++ b/roles/web-app-shopware/meta/volumes.yml @@ -131,6 +131,14 @@ php_hardening: - service: web target: /usr/local/etc/php/conf.d/zz-infinito-hardening.ini +php_memory_unlimited: + type: config + source: "{{ FILE_PHP_MEMORY_UNLIMITED_INI }}" + mode: "0444" + mounts: + - service: web + target: /usr/local/etc/php/conf.d/zz-infinito-memory-unlimited.ini + php_fpm_hardening: type: config source: "{{ FILE_PHP_FPM_HARDENING_CONF }}" From c59e2838d6c567eb1f002f4b08cc9507dc49ec57 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 00:01:20 +0100 Subject: [PATCH 03/42] fix(swarm): reach gitea, shopware and fider from inside their containers In swarm, `docker stack deploy` drops the host IP of a short port mapping, so a `127.0.0.1:` publish lands on the ingress routing mesh on every node. The provisioning of these three roles only worked because the mesh answered on the host: - web-app-gitea waited for `DOCKER_REACH_HOST:` with wait_for and polled `/api/v1/version` there with uri_retry. - web-app-shopware waited for `DOCKER_REACH_HOST:`. - web-app-fider bootstrapped its first tenant in swarm by POSTing to `127.0.0.1:` on the hosting node. As long as these calls depend on the mesh, container_ports cannot stop publishing loopback ports in swarm. The probes now run inside the service's own container through the resolved `_LOCAL_CID` on `_HOST_NODE`, against the internal port: - Gitea uses the curl it ships. The first wait accepts any HTTP answer, as wait_for did. The post-migration wait still requires 200. - Shopware runs the wget probe its compose healthcheck already uses. - Fider ships no HTTP client, so bash writes the tenant POST to /dev/tcp. The body comes in on stdin and the status line is checked for 200/201. Fider's compose path is unchanged. The compose render of all three roles is unchanged. The host-side ingress guard from svc-swarm-node stays in place until the remaining host-side consumers are moved. Refs #1089 Co-Authored-By: Claude Opus 5.5 --- roles/web-app-fider/tasks/01_setup_oidc.yml | 20 ++++++++----- roles/web-app-fider/vars/main.yml | 3 +- roles/web-app-gitea/tasks/01_manager_ops.yml | 30 +++++++++++-------- roles/web-app-gitea/vars/main.yml | 1 + .../web-app-shopware/tasks/02_manager_ops.yml | 18 ++++++----- 5 files changed, 44 insertions(+), 28 deletions(-) diff --git a/roles/web-app-fider/tasks/01_setup_oidc.yml b/roles/web-app-fider/tasks/01_setup_oidc.yml index 2985fc2793..ef2cd8981d 100644 --- a/roles/web-app-fider/tasks/01_setup_oidc.yml +++ b/roles/web-app-fider/tasks/01_setup_oidc.yml @@ -45,15 +45,21 @@ - DEPLOYMENT_MODE == 'compose' - (fider_tenant_count.rows[0][0] | int) == 0 -- name: "🄾 Fider | Bootstrap initial tenant via API (swarm, routing-mesh port)" - uri_retry: - url: "http://127.0.0.1:{{ lookup('config', application_id, 'services.fider.ports.local.http') }}/_api/tenants" - method: POST - body_format: json - body: "{{ FIDER_TENANT_BOOTSTRAP_BODY }}" - status_code: [200, 201] +- name: "🄾 Fider | Bootstrap initial tenant via API (swarm in-container)" + ansible.builtin.shell: + cmd: >- # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container exec -i {{ FIDER_LOCAL_CID | quote }} bash -c + 'set -e; body=$(cat); length=$(printf %s "$body" | wc -c); + exec 3<>"/dev/tcp/127.0.0.1/$1"; + printf "POST /_api/tenants HTTP/1.0\r\nContent-Type: application/json\r\nContent-Length: %d\r\n\r\n%s" "$length" "$body" >&3; + head -n1 <&3 | cut -d" " -f2' _ {{ FIDER_INTERNAL_PORT | quote }} + stdin: "{{ FIDER_TENANT_BOOTSTRAP_BODY | to_json }}" register: fider_tenant_bootstrap changed_when: true + failed_when: (fider_tenant_bootstrap.stdout | trim) not in ['200', '201'] + retries: 30 + delay: 2 + until: fider_tenant_bootstrap.rc == 0 delegate_to: "{{ FIDER_HOST_NODE }}" when: - DEPLOYMENT_MODE == 'swarm' diff --git a/roles/web-app-fider/vars/main.yml b/roles/web-app-fider/vars/main.yml index 3cd44bb98f..2297ea2a8e 100644 --- a/roles/web-app-fider/vars/main.yml +++ b/roles/web-app-fider/vars/main.yml @@ -3,6 +3,7 @@ application_id: "web-app-fider" FIDER_CONTAINER: "{{ lookup('config', application_id, 'services.fider.name') }}" +FIDER_INTERNAL_PORT: "{{ lookup('config', application_id, 'services.fider.ports.internal.http') }}" FIDER_OIDC_ENABLED: "{{ lookup('config', application_id, 'services.sso.enabled') }}" @@ -20,7 +21,7 @@ FIDER_MCP_PORT: "{{ lookup('config', application_id, 'services.fidermcp.ports.in FIDER_MCP_BEARER: "{{ lookup('config', application_id, 'secrets.credentials.mcp_bearer') }}" FIDER_MCP_INSTANCE_DIR: "{{ [lookup('container', application_id, 'directories.instance'), 'mcp'] | path_join }}" FIDER_MCP_UPSTREAM_HOST: "{{ lookup('config', application_id, 'services.fider.name') }}" -FIDER_MCP_UPSTREAM_PORT: "{{ lookup('config', application_id, 'services.fider.ports.internal.http') }}" +FIDER_MCP_UPSTREAM_PORT: "{{ FIDER_INTERNAL_PORT }}" FIDER_MCP_UPSTREAM_URL: "http://{{ FIDER_MCP_UPSTREAM_HOST }}:{{ FIDER_MCP_UPSTREAM_PORT }}" FIDER_MCP_CONTRACT: provider: "{{ application_id }}" diff --git a/roles/web-app-gitea/tasks/01_manager_ops.yml b/roles/web-app-gitea/tasks/01_manager_ops.yml index 2eb113d931..f04d4aacc6 100644 --- a/roles/web-app-gitea/tasks/01_manager_ops.yml +++ b/roles/web-app-gitea/tasks/01_manager_ops.yml @@ -1,11 +1,4 @@ --- -- name: ā³ Wait for Gitea HTTP endpoint - wait_for: - host: "{{ DOCKER_REACH_HOST }}" - port: "{{ lookup('config', application_id, 'services.gitea.ports.local.http') }}" - delay: 5 - timeout: "{{ lookup('timeout', 300) | int }}" - - name: "šŸ” Resolve {{ application_id }} hosting node + container id" ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" vars: @@ -13,6 +6,17 @@ resolve_output_prefix: GITEA resolve_compose_cid: "{{ GITEA_CONTAINER_ADDRESS }}" +- name: ā³ Wait for Gitea HTTP endpoint + ansible.builtin.shell: >- # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container exec {{ GITEA_LOCAL_CID | quote }} + {{ 10 | curl(retries=0) }} -S -o /dev/null {{ GITEA_LOOPBACK_VERSION_URL | quote }} + delegate_to: "{{ GITEA_HOST_NODE }}" + register: gitea_http_ready + changed_when: false + retries: 60 + delay: 5 + until: gitea_http_ready.rc == 0 + - name: "ā³ Wait for Gitea app.ini to be present after redeploy" shell: | # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node container exec -i --user {{ GITEA_USER }} {{ GITEA_LOCAL_CID | quote }} \ @@ -48,13 +52,13 @@ failed_when: create_admin.rc != 0 and 'user already exists' not in create_admin.stderr - name: "ā³ Wait until Gitea setup and migrations are ready" - uri_retry: - url: "http://{{ DOCKER_REACH_HOST }}:{{ lookup('config', application_id, 'services.gitea.ports.local.http') }}/api/v1/version" - method: GET - status_code: 200 - return_content: false + ansible.builtin.shell: >- # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container exec {{ GITEA_LOCAL_CID | quote }} + {{ 10 | curl(retries=0) }} -fS -o /dev/null {{ GITEA_LOOPBACK_VERSION_URL | quote }} + delegate_to: "{{ GITEA_HOST_NODE }}" register: gitea_ready - until: gitea_ready.status == 200 + changed_when: false + until: gitea_ready.rc == 0 retries: 20 delay: 5 when: (GITEA_OIDC_ENABLED | bool) or (GITEA_LDAP_ENABLED | bool) diff --git a/roles/web-app-gitea/vars/main.yml b/roles/web-app-gitea/vars/main.yml index 7b36c9e8e4..9282a3dc5f 100644 --- a/roles/web-app-gitea/vars/main.yml +++ b/roles/web-app-gitea/vars/main.yml @@ -22,6 +22,7 @@ GITEA_CONTAINER: "{{ lookup('config', application_id, 'services.gitea.name') }}" GITEA_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, entity_name) }}" GITEA_USER: "git" GITEA_CONFIG: "/data/gitea/conf/app.ini" +GITEA_LOOPBACK_VERSION_URL: "http://127.0.0.1:{{ lookup('config', application_id, 'services.gitea.ports.internal.http') }}/api/v1/version" GITEA_REDIS_ENABLED: "{{ lookup('config', application_id, 'services.redis.enabled') }}" GITEA_REDIS_ADDRESS: "{{ lookup('engine', 'redis', application_id, 'host') }}:{{ lookup('engine', 'redis', application_id, 'port') }}" diff --git a/roles/web-app-shopware/tasks/02_manager_ops.yml b/roles/web-app-shopware/tasks/02_manager_ops.yml index b8b9040167..d8ed62617a 100644 --- a/roles/web-app-shopware/tasks/02_manager_ops.yml +++ b/roles/web-app-shopware/tasks/02_manager_ops.yml @@ -37,13 +37,6 @@ - name: "🚿 Flush compose handlers" meta: flush_handlers -- name: ā³ Wait for Shopware HTTP endpoint - wait_for: - host: "{{ DOCKER_REACH_HOST }}" - port: "{{ lookup('config', application_id, 'services.shopware.ports.local.http') }}" - delay: 5 - timeout: "{{ lookup('timeout', 300) | int }}" - - name: "šŸ” Resolve Shopware web hosting node + container id" ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" vars: @@ -53,6 +46,17 @@ resolve_converge_retries: 120 resolve_converge_delay: 5 +- name: ā³ Wait for Shopware HTTP endpoint + ansible.builtin.shell: >- # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container exec {{ SHOPWARE_WEB_LOCAL_CID | quote }} + sh -c 'wget -q --spider "$1/robots.txt" || wget -q --spider "$1/"' _ {{ SHOPWARE_API_BASE | quote }} + delegate_to: "{{ SHOPWARE_WEB_HOST_NODE }}" + register: shopware_http_ready + changed_when: false + retries: 60 + delay: 5 + until: shopware_http_ready.rc == 0 + - name: "āœ… Ensure admin user exists with correct password" ansible.builtin.include_tasks: file: 01_admin.yml From d721e887a52cd1f088064086d70eafbf0c8c08a5 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 00:27:49 +0100 Subject: [PATCH 04/42] fix(web-app-dashboard): run inline scripts by hash instead of 'unsafe-inline' The dashboard sent script-src 'unsafe-inline' from two sources. Its own meta/csp.yml granted it to script-src-attr, and build_csp_header adds it to script-src-elem and script-src-attr for every app with services.logout.enabled. Both reach script-src through the family union, and the token in script-src-elem also closes the hash gate, so the hashes that sys-front-inj-javascript, -dashboard, -logout and -matomo register for their inline snippets were discarded. build_csp_header now skips the logout grant on a directive whose meta/csp.yml sets unsafe-inline: false. Only web-app-dashboard sets it: on script-src and script-src-elem. Its injected snippets now run by hash and the logout one-liner is hashed like the others. A render of build_csp_header for every role, variant, logout on/off and tor on/off (1712 headers) differs from origin/main only in the 8 web-app-dashboard headers; the 86 other roles that declare a logout service render byte-identical policies. script-src-attr keeps 'unsafe-inline': port-ui 2.2.2 still renders inline event handlers (menu onclick entries, openDynamicPopup, closeAllModals, the card image onerror). It goes once the port-ui release without inline handlers is pinned and header.yml.j2 moves from onclick to action. The dashboard Playwright spec asserts that script-src and script-src-elem carry no 'unsafe-inline' on the landing page, next to its existing check for CSP violations. Refs #1122 Co-Authored-By: Claude Opus 5.5 --- plugins/filter/README.md | 5 ++- plugins/filter/csp_filters.py | 9 ++-- .../playwright/test-csp-canonical-domain.js | 6 +++ roles/web-app-dashboard/meta/csp.yml | 6 ++- .../test_toggles_desktop_logout.py | 41 +++++++++++++++++++ 5 files changed, 60 insertions(+), 7 deletions(-) diff --git a/plugins/filter/README.md b/plugins/filter/README.md index 7312a1d39a..ccea48bcfe 100644 --- a/plugins/filter/README.md +++ b/plugins/filter/README.md @@ -33,13 +33,14 @@ flowchart TD grant["csp_filters.py:354
logout grant"] wl["csp_filters.py:123
get_csp_whitelist"] inj["sys-front-inj-dashboard,
-javascript, -matomo, -logout
add_csp_hash"] - gate["csp_filters.py:365
hash gate"] + gate["csp_filters.py:366
hash gate"] build["csp_filters.py:203
build_csp_header"] header["set $csp
nginx vhost"] decl -->|"1. flags read by"| flags flags -->|"2. tokens"| build svc -->|"3. read by"| grant + decl -->|"3a. unsafe-inline: false
on -elem or -attr vetoes"| grant grant -->|"4. adds 'unsafe-inline'
to script-src-elem and -attr"| build decl -->|"5. whitelist read by"| wl wl -->|"6. tokens"| build @@ -52,7 +53,7 @@ flowchart TD grant -.->|"TRIP-WIRE: absent from the
smart-defaults docstring, which
names logout only for frame-ancestors"| build ``` -Styles carry `'unsafe-inline'` by default; scripts do not. The logout grant is the only path that puts it into a script directive. +Styles carry `'unsafe-inline'` by default; scripts do not. The logout grant is the only implicit path that puts it into a script directive. An application keeps it out of `script-src-elem` or `script-src-attr` by setting `unsafe-inline: false` on that directive in its `meta/csp.yml`. ## Further Reading diff --git a/plugins/filter/csp_filters.py b/plugins/filter/csp_filters.py index 3ff788bb42..aa1111722d 100644 --- a/plugins/filter/csp_filters.py +++ b/plugins/filter/csp_filters.py @@ -351,10 +351,11 @@ class FilterModule: ) ) - if directive in ( - "script-src-attr", - "script-src-elem", - ) and self.is_feature_enabled(applications, "logout", application_id): + if ( + directive in ("script-src-attr", "script-src-elem") + and self.is_feature_enabled(applications, "logout", application_id) + and explicit_flags.get("unsafe-inline") is not False + ): tokens.append("'unsafe-inline'") tokens += self.get_csp_whitelist( diff --git a/roles/web-app-dashboard/files/playwright/test-csp-canonical-domain.js b/roles/web-app-dashboard/files/playwright/test-csp-canonical-domain.js index 3edfdebcaf..63f1448081 100644 --- a/roles/web-app-dashboard/files/playwright/test-csp-canonical-domain.js +++ b/roles/web-app-dashboard/files/playwright/test-csp-canonical-domain.js @@ -23,6 +23,12 @@ exports.register = function (shared) { const directives = assertCspResponseHeader(response, "dashboard landing"); await assertCspMetaParity(page, directives, "dashboard landing"); + for (const directive of ["script-src", "script-src-elem"]) { + expect( + directives[directive], + `dashboard landing: ${directive} MUST NOT carry 'unsafe-inline', inline scripts run by hash` + ).not.toContain("'unsafe-inline'"); + } const documentHtml = await response.text(); const documentUrl = response.url(); diff --git a/roles/web-app-dashboard/meta/csp.yml b/roles/web-app-dashboard/meta/csp.yml index 71a188495c..a93a209457 100644 --- a/roles/web-app-dashboard/meta/csp.yml +++ b/roles/web-app-dashboard/meta/csp.yml @@ -15,5 +15,9 @@ whitelist: frame-src: - "*.{{ DOMAIN_PRIMARY }}" flags: + script-src: + unsafe-inline: false + script-src-elem: + unsafe-inline: false script-src-attr: - unsafe-inline: true # nocheck: csp-unsafe Reason: historical, TODO: re-verify it is really required and does not open attack surface + unsafe-inline: true # nocheck: csp-unsafe Reason: port-ui 2.2.2 renders inline event handlers (menu onclick entries, openDynamicPopup, closeAllModals, card image onerror) diff --git a/tests/unit/python/plugins/filter/test_csp_filters/test_toggles_desktop_logout.py b/tests/unit/python/plugins/filter/test_csp_filters/test_toggles_desktop_logout.py index 87563c8582..7d3ed0923d 100644 --- a/tests/unit/python/plugins/filter/test_csp_filters/test_toggles_desktop_logout.py +++ b/tests/unit/python/plugins/filter/test_csp_filters/test_toggles_desktop_logout.py @@ -89,6 +89,47 @@ class TestCspTogglesDashboardLogout(unittest.TestCase): self.assertIn("'unsafe-inline'", attr) self.assertIn("'unsafe-inline'", elem) + def test_logout_respects_explicit_disable_on_elem_directive(self): + apps = copy.deepcopy(self.apps) + apps["app1"]["csp"]["flags"]["script-src-elem"] = {"unsafe-inline": False} + self._set_service_enabled(apps, "logout", True) + + header = self.filter.build_csp_header( + apps, + "app1", + self.domains, + "https", + extra_hashes={"script-src-elem": ["console.log('logout');"]}, + ) + elem = self._get_directive_tokens(header, "script-src-elem") + attr = self._get_directive_tokens(header, "script-src-attr") + expected_hash = self.filter.get_csp_hash("console.log('logout');") + + self.assertNotIn("'unsafe-inline'", elem) + self.assertIn(expected_hash, elem) + self.assertIn("'unsafe-inline'", attr) + + def test_logout_respects_explicit_disable_on_whole_script_family(self): + apps = copy.deepcopy(self.apps) + for directive in ("script-src", "script-src-elem", "script-src-attr"): + apps["app1"]["csp"]["flags"][directive] = {"unsafe-inline": False} + self._set_service_enabled(apps, "logout", True) + + header = self.filter.build_csp_header( + apps, + "app1", + self.domains, + "https", + extra_hashes={"script-src-elem": ["console.log('logout');"]}, + ) + expected_hash = self.filter.get_csp_hash("console.log('logout');") + + for directive in ("script-src", "script-src-elem", "script-src-attr"): + self.assertNotIn( + "'unsafe-inline'", self._get_directive_tokens(header, directive) + ) + self.assertIn(expected_hash, self._get_directive_tokens(header, "script-src")) + def test_logout_propagates_to_base_when_not_explicitly_disabled(self): apps = copy.deepcopy(self.apps) apps["app1"].setdefault("csp", {}).setdefault("flags", {}) From c2577560f8e0cef696327b412628f16cd107bd24 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 01:41:55 +0100 Subject: [PATCH 05/42] fix(swarm): bound the in-container probes and retry only safe fider POSTs Review follow-up on the in-container probes of gitea, shopware and fider. - fider: the tenant POST over /dev/tcp waited on `head` without a bound, so a peer that accepts and stays silent blocked the task for good. It now runs under `timeout` (TIMEOUT_FACTOR-scaled 30 s, the old uri socket timeout) and reads the status line with the `read` builtin, so the bound kills the whole probe. Only outcomes Fider never committed are retried: a refused connect and a 5xx (Fider rolls the request transaction back on a handler error). A timeout or a closed socket after the request was sent fails the task instead of resending the POST; the next run's tenant count decides again. - fider: both bootstrap tasks get `no_log` behind MASK_CREDENTIALS_IN_LOGS, as the body carries the administrator's name and email. - shopware: each wget probe runs under `timeout`, as busybox wget waits 900 s per read by default. - shopware, gitea: the first readiness wait derives its retries from lookup('timeout', 300) again, the budget of the wait_for it replaced, so TIMEOUT_FACTOR scales it. Refs #1089 Co-Authored-By: Claude Opus 5.5 --- roles/web-app-fider/tasks/01_setup_oidc.yml | 14 +++++++++----- roles/web-app-gitea/tasks/01_manager_ops.yml | 2 +- roles/web-app-shopware/tasks/02_manager_ops.yml | 5 +++-- 3 files changed, 13 insertions(+), 8 deletions(-) diff --git a/roles/web-app-fider/tasks/01_setup_oidc.yml b/roles/web-app-fider/tasks/01_setup_oidc.yml index ef2cd8981d..fe5cc89d09 100644 --- a/roles/web-app-fider/tasks/01_setup_oidc.yml +++ b/roles/web-app-fider/tasks/01_setup_oidc.yml @@ -41,6 +41,7 @@ body_format: json body: "{{ FIDER_TENANT_BOOTSTRAP_BODY }}" status_code: [200, 201] + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" when: - DEPLOYMENT_MODE == 'compose' - (fider_tenant_count.rows[0][0] | int) == 0 @@ -48,18 +49,21 @@ - name: "🄾 Fider | Bootstrap initial tenant via API (swarm in-container)" ansible.builtin.shell: cmd: >- # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node - container exec -i {{ FIDER_LOCAL_CID | quote }} bash -c + container exec -i {{ FIDER_LOCAL_CID | quote }} + timeout {{ lookup('timeout', 30) | int }} bash -c 'set -e; body=$(cat); length=$(printf %s "$body" | wc -c); - exec 3<>"/dev/tcp/127.0.0.1/$1"; + exec 3<>"/dev/tcp/127.0.0.1/$1" || exit 75; printf "POST /_api/tenants HTTP/1.0\r\nContent-Type: application/json\r\nContent-Length: %d\r\n\r\n%s" "$length" "$body" >&3; - head -n1 <&3 | cut -d" " -f2' _ {{ FIDER_INTERNAL_PORT | quote }} + read -r _ status _ <&3; printf %s "$status"; + case $status in 5*) exit 75;; esac' _ {{ FIDER_INTERNAL_PORT | quote }} stdin: "{{ FIDER_TENANT_BOOTSTRAP_BODY | to_json }}" register: fider_tenant_bootstrap changed_when: true - failed_when: (fider_tenant_bootstrap.stdout | trim) not in ['200', '201'] + failed_when: fider_tenant_bootstrap.rc != 0 or (fider_tenant_bootstrap.stdout | trim) not in ['200', '201'] retries: 30 delay: 2 - until: fider_tenant_bootstrap.rc == 0 + until: fider_tenant_bootstrap.rc != 75 + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" delegate_to: "{{ FIDER_HOST_NODE }}" when: - DEPLOYMENT_MODE == 'swarm' diff --git a/roles/web-app-gitea/tasks/01_manager_ops.yml b/roles/web-app-gitea/tasks/01_manager_ops.yml index f04d4aacc6..9c4754fe17 100644 --- a/roles/web-app-gitea/tasks/01_manager_ops.yml +++ b/roles/web-app-gitea/tasks/01_manager_ops.yml @@ -13,7 +13,7 @@ delegate_to: "{{ GITEA_HOST_NODE }}" register: gitea_http_ready changed_when: false - retries: 60 + retries: "{{ ((lookup('timeout', 300) | int) / 5) | round(0, 'ceil') | int }}" delay: 5 until: gitea_http_ready.rc == 0 diff --git a/roles/web-app-shopware/tasks/02_manager_ops.yml b/roles/web-app-shopware/tasks/02_manager_ops.yml index d8ed62617a..d49edced27 100644 --- a/roles/web-app-shopware/tasks/02_manager_ops.yml +++ b/roles/web-app-shopware/tasks/02_manager_ops.yml @@ -49,11 +49,12 @@ - name: ā³ Wait for Shopware HTTP endpoint ansible.builtin.shell: >- # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node container exec {{ SHOPWARE_WEB_LOCAL_CID | quote }} - sh -c 'wget -q --spider "$1/robots.txt" || wget -q --spider "$1/"' _ {{ SHOPWARE_API_BASE | quote }} + sh -c 'timeout "$2" wget -q --spider "$1/robots.txt" || timeout "$2" wget -q --spider "$1/"' + _ {{ SHOPWARE_API_BASE | quote }} {{ lookup('timeout', 10) | int }} delegate_to: "{{ SHOPWARE_WEB_HOST_NODE }}" register: shopware_http_ready changed_when: false - retries: 60 + retries: "{{ ((lookup('timeout', 300) | int) / 5) | round(0, 'ceil') | int }}" delay: 5 until: shopware_http_ready.rc == 0 From 033401c5844918e6a40b402bf6415be9f5f638ce Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Thu, 29 Oct 2026 07:19:52 +0000 Subject: [PATCH 06/42] 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 2d1238bd0b..4f9f1999bd 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.27" + version: "2026.10.29" ports: local: http: 8089 From 618a640d4a7abee05fc031f1ccc888901094edac Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 12:29:08 +0100 Subject: [PATCH 07/42] fix(lint): make mbake format the Makefile the same on every machine The repository installs mbake unpinned and shipped no .bake.toml, so the Makefile's final newline depended on the mbake version: - mbake 1.4.6 (e.g. the pkgmgr venv that wins on a host PATH) defaults to ensure_final_newline = false: `mbake format` strips the newline and `mbake format --check` accepts the stripped file. - mbake 1.5.0 (what pip installs today) rejects the same file with "Missing final newline", which is what CI reported on PR #1255. So a local `make autoformat` could strip the newline, the local lint-makefile stayed green, and CI failed; 6f653ce633 and #1262 had to restore the newline by hand. The tracked .bake.toml sets only ensure_final_newline = true, so every other formatter rule keeps its default. autoformat.sh and makefile.sh pass it with --config, so the result no longer depends on the version or on the directory mbake runs from. Checked with both versions: main's Makefile passes `--check --config .bake.toml`, and a copy without the final newline fails it with "Missing final newline". Co-Authored-By: Claude Opus 5.5 --- .bake.toml | 2 ++ scripts/lint/autoformat.sh | 4 ++-- scripts/lint/makefile.sh | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) create mode 100644 .bake.toml diff --git a/.bake.toml b/.bake.toml new file mode 100644 index 0000000000..2adc00dfd2 --- /dev/null +++ b/.bake.toml @@ -0,0 +1,2 @@ +[formatter] +ensure_final_newline = true diff --git a/scripts/lint/autoformat.sh b/scripts/lint/autoformat.sh index 907e51eaee..1a4fa210a3 100755 --- a/scripts/lint/autoformat.sh +++ b/scripts/lint/autoformat.sh @@ -139,8 +139,8 @@ run_mbake() { return 0 fi local rc=0 - mbake format Makefile >/dev/null 2>&1 || rc=$? - [[ $rc -eq 0 ]] && { mbake format Makefile >/dev/null 2>&1 || rc=$?; } + mbake format --config .bake.toml Makefile >/dev/null 2>&1 || rc=$? + [[ $rc -eq 0 ]] && { mbake format --config .bake.toml Makefile >/dev/null 2>&1 || rc=$?; } if [[ $rc -eq 0 ]]; then write_status mbake OK else diff --git a/scripts/lint/makefile.sh b/scripts/lint/makefile.sh index 84e3b27f7e..07819375df 100755 --- a/scripts/lint/makefile.sh +++ b/scripts/lint/makefile.sh @@ -17,4 +17,4 @@ if ! command -v mbake >/dev/null 2>&1; then exit 127 fi -mbake format --check Makefile +mbake format --check --config .bake.toml Makefile From 0292751a27aa90fb1d4950346ae900e894b15e2f Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 15:41:20 +0100 Subject: [PATCH 08/42] test(lookup): restore sys.modules after loading the sso plugins fresh test_sso.py, test_sso_oidc_plugin.py and test_sso_proxy_consumers.py evict utils.cache.applications, utils.cache and the roles packages from sys.modules to import their plugin against fresh modules, and never put the originals back. A later test module in the same worker then held two copies of utils.cache.applications: plugins.lookup.applications, imported earlier, kept calling the old one, while test_email patched and reset the new one, so its carrier tests counted 0 renders and failed depending only on which modules xdist placed in one worker. _load_module now runs inside mock.patch.dict(sys.modules): the plugin keeps the fresh modules it was built against, and sys.modules returns to its prior state afterwards. `pytest test_sso.py test_email.py` failed test_worker_reads_the_provider_view_from_the_provider_carrier and test_worker_renders_when_the_provider_carrier_key_differs before; the three SSO modules followed by test_email.py now pass 66/66. Same patch-id as feature/store-i18n ec0fde6561. Co-Authored-By: Claude Opus 5.5 (1M context) --- tests/unit/python/plugins/lookup/test_sso.py | 37 ++++++++++--------- .../plugins/lookup/test_sso_oidc_plugin.py | 31 ++++++++-------- .../lookup/test_sso_proxy_consumers.py | 37 ++++++++++--------- 3 files changed, 54 insertions(+), 51 deletions(-) diff --git a/tests/unit/python/plugins/lookup/test_sso.py b/tests/unit/python/plugins/lookup/test_sso.py index 050fd488b0..9f01f26824 100644 --- a/tests/unit/python/plugins/lookup/test_sso.py +++ b/tests/unit/python/plugins/lookup/test_sso.py @@ -19,25 +19,26 @@ from . import PROJECT_ROOT def _load_module(rel_path: str, name: str): - for key in ( - "utils.roles.applications.config", - "utils.roles.applications", - "utils", - "utils.cache.applications", - "utils.cache", - "utils.roles.applications.services.sso", - "utils.roles.applications.services", - ): - sys.modules.pop(key, None) - importlib.import_module("utils.roles.applications.config") - importlib.import_module("utils.cache.applications") - importlib.import_module("utils.roles.applications.services.sso") + with mock.patch.dict(sys.modules): + for key in ( + "utils.roles.applications.config", + "utils.roles.applications", + "utils", + "utils.cache.applications", + "utils.cache", + "utils.roles.applications.services.sso", + "utils.roles.applications.services", + ): + sys.modules.pop(key, None) + importlib.import_module("utils.roles.applications.config") + importlib.import_module("utils.cache.applications") + importlib.import_module("utils.roles.applications.services.sso") - path = PROJECT_ROOT / rel_path - spec = importlib.util.spec_from_file_location(name, str(path)) - mod = importlib.util.module_from_spec(spec) - assert spec and spec.loader - spec.loader.exec_module(mod) + path = PROJECT_ROOT / rel_path + spec = importlib.util.spec_from_file_location(name, str(path)) + mod = importlib.util.module_from_spec(spec) + assert spec and spec.loader + spec.loader.exec_module(mod) return mod diff --git a/tests/unit/python/plugins/lookup/test_sso_oidc_plugin.py b/tests/unit/python/plugins/lookup/test_sso_oidc_plugin.py index af94622a39..30eb3ec8e3 100644 --- a/tests/unit/python/plugins/lookup/test_sso_oidc_plugin.py +++ b/tests/unit/python/plugins/lookup/test_sso_oidc_plugin.py @@ -13,22 +13,23 @@ def _load_module(rel_path: str, name: str): """Import ``rel_path`` fresh, evicting sibling-test stubs of ``utils.roles.applications.config`` from ``sys.modules`` first. """ - for key in ( - "utils.roles.applications.config", - "utils.roles.applications", - "utils", - "utils.cache.applications", - "utils.cache", - ): - sys.modules.pop(key, None) - importlib.import_module("utils.roles.applications.config") - importlib.import_module("utils.cache.applications") + with mock.patch.dict(sys.modules): + for key in ( + "utils.roles.applications.config", + "utils.roles.applications", + "utils", + "utils.cache.applications", + "utils.cache", + ): + sys.modules.pop(key, None) + importlib.import_module("utils.roles.applications.config") + importlib.import_module("utils.cache.applications") - path = PROJECT_ROOT / rel_path - spec = importlib.util.spec_from_file_location(name, str(path)) - mod = importlib.util.module_from_spec(spec) - assert spec and spec.loader - spec.loader.exec_module(mod) + path = PROJECT_ROOT / rel_path + spec = importlib.util.spec_from_file_location(name, str(path)) + mod = importlib.util.module_from_spec(spec) + assert spec and spec.loader + spec.loader.exec_module(mod) return mod diff --git a/tests/unit/python/plugins/lookup/test_sso_proxy_consumers.py b/tests/unit/python/plugins/lookup/test_sso_proxy_consumers.py index 3fd055e309..7d17a9d5ae 100644 --- a/tests/unit/python/plugins/lookup/test_sso_proxy_consumers.py +++ b/tests/unit/python/plugins/lookup/test_sso_proxy_consumers.py @@ -19,25 +19,26 @@ from . import PROJECT_ROOT def _load_module(rel_path: str, name: str): - for key in ( - "utils.roles.applications.config", - "utils.roles.applications", - "utils", - "utils.cache.applications", - "utils.cache", - "utils.roles.applications.services.sso", - "utils.roles.applications.services", - ): - sys.modules.pop(key, None) - importlib.import_module("utils.roles.applications.config") - importlib.import_module("utils.cache.applications") - importlib.import_module("utils.roles.applications.services.sso") + with mock.patch.dict(sys.modules): + for key in ( + "utils.roles.applications.config", + "utils.roles.applications", + "utils", + "utils.cache.applications", + "utils.cache", + "utils.roles.applications.services.sso", + "utils.roles.applications.services", + ): + sys.modules.pop(key, None) + importlib.import_module("utils.roles.applications.config") + importlib.import_module("utils.cache.applications") + importlib.import_module("utils.roles.applications.services.sso") - path = PROJECT_ROOT / rel_path - spec = importlib.util.spec_from_file_location(name, str(path)) - mod = importlib.util.module_from_spec(spec) - assert spec and spec.loader - spec.loader.exec_module(mod) + path = PROJECT_ROOT / rel_path + spec = importlib.util.spec_from_file_location(name, str(path)) + mod = importlib.util.module_from_spec(spec) + assert spec and spec.loader + spec.loader.exec_module(mod) return mod From 928ca6bf2d25253ccbea2071a5b86e67863df183 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 15:43:27 +0100 Subject: [PATCH 09/42] fix(web-app-matrix): declare the synapse listener resources once templates/flavor/ansible/vars.yml.j2 carried `matrix_synapse_http_listener_resource_names: ["client", "federation"]` twice, after the secret keys and again in the reverse-proxy block. main declares it once, in the reverse-proxy block next to `matrix_playbook_reverse_proxy_type`. YAML lets the last key win, so the rendered value was the same, but a duplicate top-level key turns a later edit to only one copy into a silent override. The copy after the secret keys goes, so the file matches main for this key; same patch-id as feature/store-i18n 61d2b9ef64. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-matrix/templates/flavor/ansible/vars.yml.j2 | 2 -- 1 file changed, 2 deletions(-) diff --git a/roles/web-app-matrix/templates/flavor/ansible/vars.yml.j2 b/roles/web-app-matrix/templates/flavor/ansible/vars.yml.j2 index aeae7dcefd..13592c1dc9 100644 --- a/roles/web-app-matrix/templates/flavor/ansible/vars.yml.j2 +++ b/roles/web-app-matrix/templates/flavor/ansible/vars.yml.j2 @@ -12,8 +12,6 @@ matrix_user_gid: {{ MATRIX_SYNAPSE_GID }} matrix_synapse_macaroon_secret_key: "{{ lookup('config', application_id, 'secrets.credentials.macaroon_secret_key') }}" matrix_homeserver_generic_secret_key: "{{ lookup('config', application_id, 'secrets.credentials.macaroon_secret_key') }}" -matrix_synapse_http_listener_resource_names: ["client", "federation"] - matrix_synapse_rc_login: address: per_second: 1 From 5689812fbe390511e64988665aa1195a61f35a87 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 15:49:50 +0100 Subject: [PATCH 10/42] perf(sys-svc-compose): build with --pull in the build handlers so they hit pull.py's cache A Dockerfile change notifies compose-up and compose-build in one flush. The compose pull handler (pull.py) builds every buildable service with `compose build --pull`, and the Build compose handler right after it built again with plain `compose build`. BuildKit keys a --pull build and a plain build differently, so the second build missed the first build's cache and ran every RUN layer again; in the stalwart compose roundtrip that was 233 s for tor, 129 s for openldap and 62 s for simpleicons, about 420 s per fresh compose deploy. It also overwrote pull.py's image, built on the freshly resolved base, with one from the plain-build cache: in pass 2 the --pull build of openldap ran its RUN layer again (34.5 s) while the plain build right after it was fully CACHED. Both build handlers now run `compose build --pull` and fall back to a plain `compose build` when that fails, as pull.py does, so the second build of a flush is a cache hit and a lone-service rebuild keys like the flush builds. Without a reachable registry the fallback builds from the local base exactly as before. A scratch compose project in the stack's daemon showed the cache behaviour: --pull after --pull CACHED, plain after --pull ran the RUN layer again. The new handler test fails on the old plain `compose build`. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/sys-svc-compose/handlers/compose.yml | 4 ++-- .../roles/sys-svc-compose/files/test_pull.py | 20 +++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/roles/sys-svc-compose/handlers/compose.yml b/roles/sys-svc-compose/handlers/compose.yml index 307c0171c9..0041460714 100644 --- a/roles/sys-svc-compose/handlers/compose.yml +++ b/roles/sys-svc-compose/handlers/compose.yml @@ -33,7 +33,7 @@ - name: šŸ”Ø Build compose ansible.builtin.shell: | set -euo pipefail - compose build + compose build --pull || compose build args: chdir: "{{ lookup('container', application_id, 'directories.instance') }}" executable: /bin/bash @@ -129,7 +129,7 @@ - name: šŸ”Ø Build the services queued for a lone recreate ansible.builtin.shell: | set -euo pipefail - compose build {{ compose_service_up_targets | map('quote') | join(' ') }} + compose build --pull {{ compose_service_up_targets | map('quote') | join(' ') }} || compose build {{ compose_service_up_targets | map('quote') | join(' ') }} args: chdir: "{{ lookup('container', application_id, 'directories.instance') }}" executable: /bin/bash diff --git a/tests/unit/python/roles/sys-svc-compose/files/test_pull.py b/tests/unit/python/roles/sys-svc-compose/files/test_pull.py index b6822313c7..c294ba9e03 100644 --- a/tests/unit/python/roles/sys-svc-compose/files/test_pull.py +++ b/tests/unit/python/roles/sys-svc-compose/files/test_pull.py @@ -6,6 +6,8 @@ from pathlib import Path from types import ModuleType from unittest.mock import patch +from utils.cache.yaml import load_yaml_any + from . import PROJECT_ROOT @@ -400,5 +402,23 @@ services: self.assertIn("missing locally", str(ctx.exception)) +class TestBuildHandlersSharePullCache(unittest.TestCase): + def test_build_handlers_build_with_pull_and_fall_back_like_pull_py(self) -> None: + handlers = { + handler["name"]: handler.get("ansible.builtin.shell", "") + for handler in load_yaml_any( + str(PROJECT_ROOT / "roles/sys-svc-compose/handlers/compose.yml") + ) + } + for name in ( + "šŸ”Ø Build compose", + "šŸ”Ø Build the services queued for a lone recreate", + ): + with self.subTest(handler=name): + self.assertRegex( + handlers[name], r"compose build --pull\b.*\|\| compose build\b" + ) + + if __name__ == "__main__": unittest.main() From 91f29d332ea70b33183ea9ce4eb6dc7c2aef13c1 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 15:53:34 +0100 Subject: [PATCH 11/42] perf(spot): carry the rendered users next to the applications Ansible forks a fresh worker per task, so every lookup('users') in a forked worker re-rendered the whole user catalogue (298 users, 0.3 to 0.5 s locally and about 1 s on the runner, 1 s locally once a users password is vaulted): _MERGED_USERS_CACHE lives in the process and had no carrier fact. applications_carrier now also parks lookup('users', carrier=True) in _INFINITO_USERS_RENDERED at the same park points, and clear drops both facts. get_merged_users serves the fact to templated reads when its key matches: the applications carrier key (roles dir, applications, users, DOMAIN_PRIMARY, SYSTEM_EMAIL_DOMAIN, group_names, token store digest) plus inventory_hostname, so a carrier a run_once park broadcasts never answers another host with its become password. A park whose users carrier still matches leaves it in place instead of returning 119 KB again, so parks cost what they cost before. Real ansible-playbook harness on 2.20.6 and 2.21.5 with the real roles tree: users renders per users-reading task after a park 1 -> 0, task 0.56 -> 0.08 s (vaulted 1.21 -> 0.17 s); a rotated token, a rotated inventory password, a cleared carrier and another host's carrier all re-render; 32 of 32 probe digests equal HEAD's. Removing the carrier check fails three unit tests. The stalwart swarm roundtrip pass 1 and its DR drill ran green with it on all nodes, with no 401 from JMAP, msmtp or LDAP. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../files/plugins/lookup/applications.md | 3 +- .../artefact/files/plugins/lookup/users.md | 12 +- plugins/action/applications_carrier.py | 60 ++++--- plugins/lookup/users.py | 27 +++- .../action/test_applications_carrier.py | 144 +++++++++++++---- .../unit/python/plugins/lookup/test_users.py | 41 +++++ .../python/utils/cache/users/test_module.py | 147 ++++++++++++++++++ utils/cache/README.md | 6 +- utils/cache/carrier.py | 79 ++++++++-- utils/cache/users/__init__.py | 10 ++ 10 files changed, 460 insertions(+), 69 deletions(-) diff --git a/docs/contributing/artefact/files/plugins/lookup/applications.md b/docs/contributing/artefact/files/plugins/lookup/applications.md index ac13d7e6e1..93b468d4dc 100644 --- a/docs/contributing/artefact/files/plugins/lookup/applications.md +++ b/docs/contributing/artefact/files/plugins/lookup/applications.md @@ -40,7 +40,8 @@ The constructor stage renders once through the [applications_carrier](../../../. - The action renders with `application_id` removed from its variables, so the carried tree holds the play-scope result of every consumer-aligned `lookup('tls', ...)`, whichever role parks it. - The token store enters the key as the SHA-256 of exactly the tokens the users are hydrated from: the controller's tokens file until `sys-token-store` loads, the `sys_token_store_users` fact after. Both sources key alike when they hold the same tokens, so loading an unchanged store keeps the carrier, and a touch keeps the key. The carrier action opens the file before it computes the key, so an NFS client keys on revalidated attributes. - The action masks its own result: the fact is the whole rendered tree with every application's credentials, so it never reaches a log regardless of `MASK_CREDENTIALS_IN_LOGS`. -- User records inside the payload are the token store's state at render time. Readers of tokens captured later in the play MUST go through `lookup('users', ...)` or `lookup('config', , 'users....')`, both of which read the users cache fresh. +- User records inside the payload are the token store's state at render time. Readers of tokens captured later in the play MUST go through `lookup('users', ...)` or `lookup('config', , 'users....')`, both of which key the users on the current token store. +- The action parks the users carrier `_INFINITO_USERS_RENDERED` at the same points, after the applications render; `clear: true` drops both. See [users.md](users.md). - The carrier is private to the lookup. Consumers MUST NOT read `_INFINITO_APPLICATIONS_RENDERED`; they keep going through `lookup('applications')`, which is what makes the carrier transparent. - The carrier is the only materialised merged view a play MAY hold. The rule against a top-level `applications` fact above is unchanged. diff --git a/docs/contributing/artefact/files/plugins/lookup/users.md b/docs/contributing/artefact/files/plugins/lookup/users.md index c3ab7ffcb9..22fdab26b2 100644 --- a/docs/contributing/artefact/files/plugins/lookup/users.md +++ b/docs/contributing/artefact/files/plugins/lookup/users.md @@ -18,6 +18,15 @@ The `users` lookup is the ONLY supported runtime entry point for merged user con | `lookup('users')` | Full merged mapping keyed by the canonical user key. | | `lookup('users', '')` | Merged entry for that user. Raises when missing. | | `lookup('users', '', default_value)` | Merged entry, or `default_value` when the entry is missing. | +| `lookup('users', carrier=True)` | `{"key": [...], "users": {...}}`: the full mapping plus the cache key it is valid under. Reserved for the `applications_carrier` action (see below). | + +## Play-Scoped Carrier 🧊 + +The [applications_carrier](../../../../../../plugins/action/applications_carrier.py) action parks the rendered users next to the applications in the host fact `_INFINITO_USERS_RENDERED`, at every point listed in [applications.md](applications.md), and `clear: true` drops both facts. `get_merged_users` serves the fact to a templated read when its key matches and renders otherwise. + +- The key is the applications carrier key plus `inventory_hostname`: a changed `applications`, `users`, `DOMAIN_PRIMARY`, `SYSTEM_EMAIL_DOMAIN`, `group_names`, token store or host rejects the carrier. +- A read without a templar (the raw users inside an applications render) never takes the carrier. +- The carrier is private to the lookup. Consumers MUST NOT read `_INFINITO_USERS_RENDERED`; they keep going through `lookup('users')` or `lookup('config', , 'users....')`. ## Data Sources šŸ“š @@ -26,7 +35,7 @@ The lookup merges exactly two sources: 1. **Defaults** discovered from every `roles/*/meta/users.yml` in the repository (file root IS the users map; no `users:` wrapper). 2. **Overrides** supplied through the normal Ansible variable `users` in inventory, group vars, host vars, or role vars. -No intermediate merged `users` fact exists. No other source is consulted. +No intermediate merged `users` fact exists besides the carrier above. No other source is consulted. ## Canonical User Key šŸ”‘ @@ -82,6 +91,7 @@ users: |---|---| | [users.py](../../../../../../plugins/lookup/users.py) | Runtime entry point for the `users` lookup. | | [users/ (cache)](../../../../../../utils/cache/users/) | Shared aggregation helper package that builds and caches defaults, handles reserved users, UID/GID allocation, and uniqueness validation. Placeholder substitution (DOMAIN_PRIMARY / ORGANIZATION / SOFTWARE_NAME) lives in [users/placeholders.py](../../../../../../utils/cache/users/placeholders.py). | +| [carrier.py](../../../../../../utils/cache/carrier.py) | The play-scoped carrier: fact name, `merged_users_cache_key`, and the reader that serves the carried payload. | | [test_users.py](../../../../../../tests/unit/python/plugins/lookup/test_users.py) | Unit tests covering the full-dict, single-entry, override, strict missing, and non-strict missing cases. | For the related applications pattern see [applications.md](applications.md). diff --git a/plugins/action/applications_carrier.py b/plugins/action/applications_carrier.py index d7da126d30..5ad3fbf84c 100644 --- a/plugins/action/applications_carrier.py +++ b/plugins/action/applications_carrier.py @@ -1,11 +1,13 @@ -"""Render the applications SPOT once and park it as the play-scoped carrier fact. +"""Render the applications and users SPOTs once and park them as play-scoped carrier facts. -Ansible forks a fresh worker per task, so the in-process render cache of -``lookup('applications')`` is cold in every task until something renders in -a place all later workers inherit. This action renders in the worker of one -constructor task and returns the payload as a host fact; every later worker -inherits that fact at fork time and ``get_merged_applications`` serves it -instead of rendering:: +Ansible forks a fresh worker per task, so the in-process render caches of +``lookup('applications')`` and ``lookup('users')`` are cold in every task +until something renders in a place all later workers inherit. This action +renders in the worker of one constructor task and returns both payloads as +host facts; every later worker inherits them at fork time and +``get_merged_applications`` / ``get_merged_users`` serve them instead of +rendering. The users carrier is keyed like the applications carrier plus +``inventory_hostname``:: - name: 🧊 Render the applications SPOT once and carry it into every task's worker applications_carrier: {} @@ -26,14 +28,16 @@ rejected and the reader renders afresh:: ``tasks/utils/setup/role.yml`` parks one after every role, ``tasks/utils/load/app.yml`` one after every nested application load and ``roles/sys-token-store/tasks/write_many.yml`` one after every store write; -where the key still matches they serve the carried payload without rendering. +where the key still matches they serve the carried payload without rendering, +and a users carrier that still matches is left in place instead of being +returned again. -The result is masked by the action itself: the fact is the whole rendered -tree, about 0.4 MB with every application's credentials, and printing it at -``-v`` is neither credential debugging nor readable. +The result is masked by the action itself: the facts are the whole rendered +trees, about 0.4 MB with every application's and user's credentials, and +printing them at ``-v`` is neither credential debugging nor readable. Args: - clear: drop the carrier fact instead of rendering. Defaults to false. + clear: drop both carrier facts instead of rendering. Defaults to false. Any other argument is an error. """ @@ -46,7 +50,12 @@ from ansible.module_utils.parsing.convert_bool import boolean from ansible.plugins.action import ActionBase from ansible.plugins.loader import lookup_loader -from utils.cache.carrier import APPLICATIONS_RENDERED_FACT, revalidate_tokens_file +from utils.cache.carrier import ( + APPLICATIONS_RENDERED_FACT, + USERS_RENDERED_FACT, + _carried_users, + revalidate_tokens_file, +) class ActionModule(ActionBase): @@ -67,7 +76,11 @@ class ActionModule(ActionBase): if boolean(args.get("clear", False)): result.update( - changed=False, ansible_facts={APPLICATIONS_RENDERED_FACT: None} + changed=False, + ansible_facts={ + APPLICATIONS_RENDERED_FACT: None, + USERS_RENDERED_FACT: None, + }, ) return result @@ -77,16 +90,25 @@ class ActionModule(ActionBase): previous = self._templar.available_variables self._templar.available_variables = render_vars try: - lookup = lookup_loader.get( - "applications", loader=self._loader, templar=self._templar - ) - carrier = lookup.run([], variables=render_vars, carrier=True)[0] + carriers = { + fact: lookup_loader.get( + name, loader=self._loader, templar=self._templar + ).run([], variables=render_vars, carrier=True)[0] + for fact, name in ( + (APPLICATIONS_RENDERED_FACT, "applications"), + (USERS_RENDERED_FACT, "users"), + ) + } finally: self._templar.available_variables = previous + users_key = carriers[USERS_RENDERED_FACT]["key"] + if _carried_users(task_vars, (users_key[0], tuple(users_key[1]))) is not None: + del carriers[USERS_RENDERED_FACT] + result.update( changed=False, - ansible_facts={APPLICATIONS_RENDERED_FACT: carrier}, + ansible_facts=carriers, _ansible_no_log=True, ) return result diff --git a/plugins/lookup/users.py b/plugins/lookup/users.py index 099110bcba..cedcf6516a 100644 --- a/plugins/lookup/users.py +++ b/plugins/lookup/users.py @@ -6,6 +6,7 @@ from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase from utils.cache import _reset_cache_for_tests as _reset_runtime_lookup_cache +from utils.cache.carrier import merged_users_cache_key # nocheck: lookup-cache-import (this lookup IS the users SPOT provider) from utils.cache.users import get_merged_users @@ -22,21 +23,39 @@ class LookupModule(LookupBase): variables: dict[str, Any] | None = None, **kwargs: Any, ) -> list[Any]: + """ + Terms: + 0) full merged mapping + 1) canonical_user_key + 2) canonical_user_key, default value + + Keyword arguments: + roles_dir: roles tree to build from (defaults to the repository's) + carrier: with no terms, return ``{"key": [...], "users": {...}}`` + for the constructor to park in `_INFINITO_USERS_RENDERED` + """ terms = terms or [] if len(terms) > 2: raise AnsibleError( "users: expected 0, 1, or 2 terms: " "lookup('users'[, canonical_user_key[, default]])" ) + carrier = bool(kwargs.get("carrier", False)) + if carrier and terms: + raise AnsibleError("users: carrier=True takes no terms") + variables = variables or getattr(self._templar, "available_variables", {}) or {} + roles_dir = kwargs.get("roles_dir") users = get_merged_users( - variables=variables - or getattr(self._templar, "available_variables", {}) - or {}, - roles_dir=kwargs.get("roles_dir"), + variables=variables, + roles_dir=roles_dir, templar=getattr(self, "_templar", None), ) + if carrier: + key = merged_users_cache_key(variables, roles_dir=roles_dir) + return [{"key": [key[0], list(key[1])], "users": users}] + if len(terms) == 0: return [users] diff --git a/tests/unit/python/plugins/action/test_applications_carrier.py b/tests/unit/python/plugins/action/test_applications_carrier.py index 4e0c8d213e..95f8cc355b 100644 --- a/tests/unit/python/plugins/action/test_applications_carrier.py +++ b/tests/unit/python/plugins/action/test_applications_carrier.py @@ -4,7 +4,7 @@ from unittest.mock import patch from ansible.errors import AnsibleActionFail from plugins.action.applications_carrier import ActionModule -from utils.cache.carrier import APPLICATIONS_RENDERED_FACT +from utils.cache.carrier import APPLICATIONS_RENDERED_FACT, USERS_RENDERED_FACT class _FakeTask: @@ -31,6 +31,16 @@ class _FakeLookup: return [self.carrier] +class _FakeLoader: + def __init__(self, applications, users): + self.lookups = {"applications": applications, "users": users} + self.order = [] + + def get(self, name, loader=None, templar=None): + self.order.append(name) + return self.lookups[name] + + def _make_action(task: _FakeTask, templar=None) -> ActionModule: action = object.__new__(ActionModule) action._task = task @@ -39,10 +49,19 @@ def _make_action(task: _FakeTask, templar=None) -> ActionModule: return action +def _lookups(templar=None): + applications = _FakeLookup( + {"key": ["roles", ["a", "b", "c", "d"]], "applications": {"x": {}}}, templar + ) + users = _FakeLookup( + {"key": ["roles", ["a", "b", "c", "d", "h"]], "users": {"u": {}}}, templar + ) + return applications, users, _FakeLoader(applications, users) + + class TestApplicationsCarrierActionPlugin(unittest.TestCase): - def test_parks_the_carrier_as_a_masked_fact(self): - carrier = {"key": ["roles", ["a", "b", "c", "d"]], "applications": {"x": {}}} - lookup = _FakeLookup(carrier) + def test_parks_both_carriers_as_masked_facts(self): + applications, users, loader = _lookups() action = _make_action(_FakeTask()) with ( patch( @@ -52,23 +71,78 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase): ), patch( "plugins.action.applications_carrier.lookup_loader.get", - return_value=lookup, + side_effect=loader.get, ), ): result = action.run(task_vars={"applications": {}}) - self.assertIs(result["ansible_facts"][APPLICATIONS_RENDERED_FACT], carrier) + self.assertIs( + result["ansible_facts"][APPLICATIONS_RENDERED_FACT], applications.carrier + ) + self.assertIs(result["ansible_facts"][USERS_RENDERED_FACT], users.carrier) self.assertTrue(result["_ansible_no_log"]) self.assertFalse(result["changed"]) - terms, variables, kwargs = lookup.calls[0] - self.assertEqual(terms, []) - self.assertEqual(variables, {"applications": {}}) - self.assertTrue(kwargs["carrier"]) + for lookup in (applications, users): + terms, variables, kwargs = lookup.calls[0] + self.assertEqual(terms, []) + self.assertEqual(variables, {"applications": {}}) + self.assertTrue(kwargs["carrier"]) + + def _park(self, task_vars): + applications, users, loader = _lookups() + action = _make_action(_FakeTask()) + with ( + patch( + "plugins.action.applications_carrier.ActionBase.run", + autospec=True, + return_value={}, + ), + patch( + "plugins.action.applications_carrier.lookup_loader.get", + side_effect=loader.get, + ), + patch("plugins.action.applications_carrier.revalidate_tokens_file"), + ): + return action.run(task_vars=task_vars), applications, users + + def test_a_users_carrier_that_still_matches_stays_in_place(self): + parked = {"key": ["roles", ["a", "b", "c", "d", "h"]], "users": {"u": {}}} + result, applications, _ = self._park({USERS_RENDERED_FACT: parked}) + + self.assertNotIn(USERS_RENDERED_FACT, result["ansible_facts"]) + self.assertIs( + result["ansible_facts"][APPLICATIONS_RENDERED_FACT], applications.carrier + ) + + def test_a_stale_users_carrier_is_replaced(self): + parked = {"key": ["roles", ["a", "b", "c", "d", "h2"]], "users": {"u": {}}} + result, _, users = self._park({USERS_RENDERED_FACT: parked}) + + self.assertIs(result["ansible_facts"][USERS_RENDERED_FACT], users.carrier) + + def test_renders_the_applications_before_the_users(self): + _, _, loader = _lookups() + action = _make_action(_FakeTask()) + with ( + patch( + "plugins.action.applications_carrier.ActionBase.run", + autospec=True, + return_value={}, + ), + patch( + "plugins.action.applications_carrier.lookup_loader.get", + side_effect=loader.get, + ), + patch("plugins.action.applications_carrier.revalidate_tokens_file"), + ): + action.run(task_vars={}) + + self.assertEqual(loader.order, ["applications", "users"]) def test_renders_without_the_callers_application_id(self): task_vars = {"applications": {}, "application_id": "web-app-bluesky"} templar = _FakeTemplar(task_vars) - lookup = _FakeLookup({"key": ["roles", []], "applications": {}}, templar) + applications, users, loader = _lookups(templar) action = _make_action(_FakeTask(), templar) with ( patch( @@ -78,22 +152,26 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase): ), patch( "plugins.action.applications_carrier.lookup_loader.get", - return_value=lookup, + side_effect=loader.get, ), patch("plugins.action.applications_carrier.revalidate_tokens_file"), ): action.run(task_vars=task_vars) - _, variables, _ = lookup.calls[0] - self.assertEqual(variables, {"applications": {}}) - self.assertEqual(lookup.templar_variables, [{"applications": {}}]) + for lookup in (applications, users): + _, variables, _ = lookup.calls[0] + self.assertEqual(variables, {"applications": {}}) + self.assertEqual(lookup.templar_variables, [{"applications": {}}]) self.assertIs(templar.available_variables, task_vars) self.assertEqual(task_vars["application_id"], "web-app-bluesky") def test_revalidates_the_tokens_file_before_rendering(self): order = [] - lookup = _FakeLookup({"key": ["roles", []], "applications": {}}) - lookup.run = lambda *args, **kwargs: order.append("render") or [{}] + applications, users, loader = _lookups() + applications.run = lambda *args, **kwargs: ( + order.append("applications") or [applications.carrier] + ) + users.run = lambda *args, **kwargs: order.append("users") or [users.carrier] action = _make_action(_FakeTask()) with ( patch( @@ -103,7 +181,7 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase): ), patch( "plugins.action.applications_carrier.lookup_loader.get", - return_value=lookup, + side_effect=loader.get, ), patch( "plugins.action.applications_carrier.revalidate_tokens_file", @@ -113,7 +191,8 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase): action.run(task_vars={"FILE_TOKENS": "/x/tokens.yml"}) self.assertEqual( - order, [("revalidate", {"FILE_TOKENS": "/x/tokens.yml"}), "render"] + order, + [("revalidate", {"FILE_TOKENS": "/x/tokens.yml"}), "applications", "users"], ) def test_clear_does_not_revalidate(self): @@ -144,8 +223,8 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase): ): action.run(task_vars={}) - def test_clear_drops_the_fact_without_rendering(self): - lookup = _FakeLookup({"key": ["roles", []], "applications": {}}) + def test_clear_drops_both_facts_without_rendering(self): + applications, users, loader = _lookups() action = _make_action(_FakeTask(args={"clear": True})) with ( patch( @@ -155,18 +234,21 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase): ), patch( "plugins.action.applications_carrier.lookup_loader.get", - return_value=lookup, + side_effect=loader.get, ), ): result = action.run(task_vars={"applications": {}}) - self.assertIsNone(result["ansible_facts"][APPLICATIONS_RENDERED_FACT]) + self.assertEqual( + result["ansible_facts"], + {APPLICATIONS_RENDERED_FACT: None, USERS_RENDERED_FACT: None}, + ) self.assertFalse(result["changed"]) - self.assertEqual(lookup.calls, []) + self.assertEqual(applications.calls, []) + self.assertEqual(users.calls, []) def test_clear_false_still_renders(self): - carrier = {"key": ["roles", ["a", "b", "c", "d"]], "applications": {"x": {}}} - lookup = _FakeLookup(carrier) + applications, users, loader = _lookups() action = _make_action(_FakeTask(args={"clear": "no"})) with ( patch( @@ -176,13 +258,17 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase): ), patch( "plugins.action.applications_carrier.lookup_loader.get", - return_value=lookup, + side_effect=loader.get, ), ): result = action.run(task_vars={"applications": {}}) - self.assertIs(result["ansible_facts"][APPLICATIONS_RENDERED_FACT], carrier) - self.assertEqual(len(lookup.calls), 1) + self.assertIs( + result["ansible_facts"][APPLICATIONS_RENDERED_FACT], applications.carrier + ) + self.assertIs(result["ansible_facts"][USERS_RENDERED_FACT], users.carrier) + self.assertEqual(len(applications.calls), 1) + self.assertEqual(len(users.calls), 1) if __name__ == "__main__": diff --git a/tests/unit/python/plugins/lookup/test_users.py b/tests/unit/python/plugins/lookup/test_users.py index 19f83592c5..b4d5c293f8 100644 --- a/tests/unit/python/plugins/lookup/test_users.py +++ b/tests/unit/python/plugins/lookup/test_users.py @@ -10,6 +10,7 @@ from ansible.errors import AnsibleError from plugins.lookup.users import LookupModule, _reset_cache_for_tests from utils.cache import base as runtime_data_base +from utils.cache.carrier import USERS_RENDERED_FACT, merged_users_cache_key from utils.cache.yaml import dump_yaml_str from utils.paths import FILE_TOKENS from utils.roles.mapping import ROLE_FILE_META_USERS @@ -303,6 +304,46 @@ class TestUsersLookup(unittest.TestCase): self.assertEqual(result["tokens"]["web-app-mailu"], "token-from-default-path") + def test_carrier_returns_the_users_with_the_key_they_are_valid_under( + self, + ) -> None: + roles = str(self._tmp / "roles") + variables = {"inventory_hostname": "h1"} + result = self.lookup.run( + [], variables=variables, roles_dir=roles, carrier=True + )[0] + key = merged_users_cache_key(variables, roles_dir=roles) + self.assertEqual(result["key"], [key[0], list(key[1])]) + self.assertEqual( + result["users"], + self.lookup.run([], variables=variables, roles_dir=roles)[0], + ) + + def test_carrier_takes_no_terms(self) -> None: + with self.assertRaises(AnsibleError): + self.lookup.run( + ["alice"], + variables={}, + roles_dir=str(self._tmp / "roles"), + carrier=True, + ) + + def test_a_parked_carrier_answers_a_fresh_worker_without_rendering(self) -> None: + roles = str(self._tmp / "roles") + self.lookup._templar = _DummyTemplar({"SYSTEM_EMAIL_DOMAIN": "example.org"}) + variables = {"inventory_hostname": "h1", "SYSTEM_EMAIL_DOMAIN": "example.org"} + parked = self.lookup.run( + [], variables=variables, roles_dir=roles, carrier=True + )[0] + _reset_cache_for_tests() + variables[USERS_RENDERED_FACT] = parked + with patch( + "utils.cache.users._render_with_templar", + side_effect=AssertionError("rendered"), + ): + result = self.lookup.run(["alice"], variables=variables, roles_dir=roles)[0] + self.assertIs(result, parked["users"]["alice"]) + class _DummyTemplar: def __init__(self, variables: dict[str, str]) -> None: diff --git a/tests/unit/python/utils/cache/users/test_module.py b/tests/unit/python/utils/cache/users/test_module.py index 0dc951ed81..ee1ce655d2 100644 --- a/tests/unit/python/utils/cache/users/test_module.py +++ b/tests/unit/python/utils/cache/users/test_module.py @@ -14,12 +14,14 @@ from __future__ import annotations import tempfile import textwrap import unittest +import unittest.mock as mock from collections import OrderedDict from pathlib import Path from utils.cache import _reset_cache_for_tests from utils.cache import base as cache_base from utils.cache import users as cache_users +from utils.cache.carrier import USERS_RENDERED_FACT, merged_users_cache_key from utils.cache.users import store as cache_users_store from utils.cache.yaml import dump_yaml_str from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_META_USERS @@ -415,6 +417,151 @@ class TestGetMergedUsersTokenSource(unittest.TestCase): self.assertEqual(after["foo"]["tokens"]["web-app-foo"], "minted") +class _Templar: + def __init__(self) -> None: + self.available_variables: dict = {} + + def template(self, value, fail_on_undefined=False): + return value + + +class TestGetMergedUsersCarrierFact(unittest.TestCase): + def setUp(self) -> None: + _reset_cache_for_tests() + + @staticmethod + def _variables(host: str = "h1") -> dict: + return { + "inventory_hostname": host, + "users": {"foo": {"email": "foo@example.org"}}, + cache_users_store.STORE_FACT: { + "foo": {"tokens": {"web-app-foo": "minted"}} + }, + } + + @staticmethod + def _park(roles: Path, variables: dict, payload: dict) -> dict: + key = merged_users_cache_key(variables, roles_dir=roles) + variables[USERS_RENDERED_FACT] = { + "key": [key[0], list(key[1])], + "users": payload, + } + return payload + + @staticmethod + def _merged(roles: Path, variables: dict, templar=None) -> tuple: + with mock.patch.object( + cache_users, + "_render_with_templar", + side_effect=lambda value, **_: {"rendered": value}, + ) as render: + merged = cache_users.get_merged_users( + variables=variables, + roles_dir=roles, + templar=_Templar() if templar is None else templar, + ) + return merged, render.call_count + + def test_matching_key_serves_the_carried_payload_without_rendering(self): + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_user_role(Path(tmp)) + variables = self._variables() + carried = self._park(roles, variables, {"foo": {"carried": True}}) + merged, renders = self._merged(roles, variables) + self.assertIs(merged, carried) + self.assertEqual(renders, 0) + + def test_the_carried_payload_answers_the_rest_of_the_process(self): + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_user_role(Path(tmp)) + variables = self._variables() + carried = self._park(roles, variables, {"foo": {"carried": True}}) + self._merged(roles, variables) + del variables[USERS_RENDERED_FACT] + merged, renders = self._merged(roles, variables) + self.assertIs(merged, carried) + self.assertEqual(renders, 0) + + def test_stale_key_falls_back_to_a_fresh_render(self): + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_user_role(Path(tmp)) + variables = self._variables() + key = merged_users_cache_key(variables, roles_dir=roles) + variables[USERS_RENDERED_FACT] = { + "key": [key[0], ["stale"] * len(key[1])], + "users": {"foo": {"carried": True}}, + } + merged, renders = self._merged(roles, variables) + self.assertEqual(renders, 1) + self.assertEqual(merged["rendered"]["foo"]["email"], "foo@example.org") + + def test_another_hosts_carrier_is_rejected(self): + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_user_role(Path(tmp)) + variables = self._variables("h1") + self._park(roles, variables, {"foo": {"carried": True}}) + variables["inventory_hostname"] = "h2" + merged, renders = self._merged(roles, variables) + self.assertEqual(renders, 1) + self.assertNotIn("carried", merged["rendered"]["foo"]) + + def test_a_rotated_store_token_rejects_the_carrier(self): + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_user_role(Path(tmp)) + variables = self._variables() + self._park(roles, variables, {"foo": {"carried": True}}) + variables[cache_users_store.STORE_FACT] = { + "foo": {"tokens": {"web-app-foo": "rotated"}} + } + merged, renders = self._merged(roles, variables) + self.assertEqual(renders, 1) + self.assertEqual( + merged["rendered"]["foo"]["tokens"]["web-app-foo"], "rotated" + ) + + def test_a_rotated_inventory_password_rejects_the_carrier(self): + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_user_role(Path(tmp)) + variables = self._variables() + variables["users"]["foo"]["password"] = "before" + self._park(roles, variables, {"foo": {"carried": True}}) + variables["users"] = {"foo": {"password": "after"}} + merged, renders = self._merged(roles, variables) + self.assertEqual(renders, 1) + self.assertEqual(merged["rendered"]["foo"]["password"], "after") + + def test_without_a_templar_the_carrier_is_ignored(self): + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_user_role(Path(tmp)) + variables = self._variables() + self._park(roles, variables, {"foo": {"carried": True}}) + merged = cache_users.get_merged_users( + variables=variables, roles_dir=roles, templar=None + ) + self.assertNotIn("carried", merged["foo"]) + self.assertEqual(merged["foo"]["email"], "foo@example.org") + + def test_malformed_carrier_is_ignored(self): + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_user_role(Path(tmp)) + key = merged_users_cache_key(self._variables(), roles_dir=roles) + for carrier in ( + "not-a-mapping", + {"key": "x", "users": {}}, + {"key": [key[0], list(key[1])], "users": "not-a-mapping"}, + {}, + ): + with self.subTest(carrier=carrier): + _reset_cache_for_tests() + variables = self._variables() + variables[USERS_RENDERED_FACT] = carrier + merged, renders = self._merged(roles, variables) + self.assertEqual(renders, 1) + self.assertEqual( + merged["rendered"]["foo"]["email"], "foo@example.org" + ) + + class TestStoreSignature(unittest.TestCase): def setUp(self) -> None: _reset_cache_for_tests() diff --git a/utils/cache/README.md b/utils/cache/README.md index 3be16f4ee2..2ecbb1ccb5 100644 --- a/utils/cache/README.md +++ b/utils/cache/README.md @@ -10,7 +10,7 @@ This package contains the in-process cache layers Infinito.Nexus uses to keep CL | [files.py](files.py) | The project tree's full path list (one walk per process) and per-file UTF-8 contents (`read_text`). Used by lint/integration tests and CLI tools that scan the repo. | | [base.py](base.py) | Cross-cutting helpers: filesystem constants (`PROJECT_ROOT`, `ROLES_DIR`, `DEFAULT_TOKENS_FILE`), `_deep_merge`, cache-key + content-fingerprint signatures, the cross-domain re-entry guard, and the templar-render machinery. The only ansible-coupled symbol is `_render_with_templar`, which lazy-imports its dependency. | | [applications.py](applications.py) | Per-app variants + defaults + `get_merged_applications`. **Strictly ansible-free at import time** so the GitHub Actions runner-host CLI path (`cli.administration.deploy.development.init` → `plan_dev_inventory_matrix` → `get_variants`) keeps working without ansible installed. | -| [carrier.py](carrier.py) | The play-scoped carrier of the rendered applications payload: the fact name `_INFINITO_APPLICATIONS_RENDERED`, `merged_applications_cache_key`, and the reader `get_merged_applications` consults before it renders. | +| [carrier.py](carrier.py) | The play-scoped carriers of the rendered applications and users payloads: the fact names `_INFINITO_APPLICATIONS_RENDERED` and `_INFINITO_USERS_RENDERED`, `merged_applications_cache_key`, `merged_users_cache_key`, and the readers `get_merged_applications` and `get_merged_users` consult before they render. | | [users/](users/) | User definitions, token store hydration, alias materialization, `get_user_defaults`, `get_merged_users` (package; `users/placeholders.py` substitutes `DOMAIN_PRIMARY` / `ORGANIZATION` / `SOFTWARE_NAME` ahead of the templar render pass; `users/store.py` reads the `sys_token_store_users` fact and digests the tokens the users are hydrated from, the digest the users and carrier keys share). | | [domains.py](domains.py) | Canonical-domains map derived from the merged applications view: `get_merged_domains`. A read issued while the applications render is in progress (the re-entry guard is set) sees the unrendered view, so it is cached under its own key and never answers a later read. | | [`__init__.py`](__init__.py) | Owns the package-level `_reset_cache_for_tests()` orchestrator that clears every cache plus the shared fingerprint memo in one call. | @@ -26,7 +26,7 @@ The layers are orthogonal: `yaml.py` caches "this file's parsed root", the `appl Both layers are process-wide in-process caches. They intentionally do NOT track on-disk file mtimes; CLI tools are short-lived and the assumption "the on-disk file does not change while my process runs" holds. The single exception is `utils.cache.yaml.dump_yaml`, which writes through and evicts the cached entry for the path it just wrote so a tool that edits a file mid-run sees the new content on the next read. -Inside a play the process boundary is the task: Ansible forks a fresh worker per task, so `_MERGED_APPLICATIONS_CACHE` starts empty in every worker. `get_merged_applications` therefore also accepts the play-scoped carrier fact `_INFINITO_APPLICATIONS_RENDERED` (payload plus cache key, parked by the constructor stage and again after every role, every nested application load and every persisted token) and serves it when the key matches. See [applications.md](../../docs/contributing/artefact/files/plugins/lookup/applications.md) for the contract. +Inside a play the process boundary is the task: Ansible forks a fresh worker per task, so `_MERGED_APPLICATIONS_CACHE` and `_MERGED_USERS_CACHE` start empty in every worker. `get_merged_applications` therefore also accepts the play-scoped carrier fact `_INFINITO_APPLICATIONS_RENDERED` (payload plus cache key, parked by the constructor stage and again after every role, every nested application load and every persisted token) and serves it when the key matches. The same action parks `_INFINITO_USERS_RENDERED`, which `get_merged_users` serves to templated reads under the applications key plus `inventory_hostname`. See [applications.md](../../docs/contributing/artefact/files/plugins/lookup/applications.md) and [users.md](../../docs/contributing/artefact/files/plugins/lookup/users.md) for the contract. While one render runs, the re-entry guard also holds that render's unrendered view and its cache key. A nested `get_merged_applications` call from a lookup inside a role template (`config`, `tls`, `domain`, ...) with the same key returns that view instead of copying and merging the role defaults again. The view is shared by every nested call of the render, so callers MUST NOT mutate it. The guard drops it when the render ends. @@ -84,7 +84,7 @@ flowchart TD proc -.->|"TRIP-WIRE: read BEFORE the
host's own fact, so an inherited
entry outranks it"| fact render -.->|"TRIP-WIRE: main process renders
task names for one host; forked
workers inherit that entry"| proc - key -.->|"TRIP-WIRE: carrier.py:68 stringifies
only one side, so a non-scalar key
part silently never matches again"| fact + key -.->|"TRIP-WIRE: carrier.py:118 stringifies
only one side, so a non-scalar key
part silently never matches again"| fact ``` The key covers `group_names`. `domains.py` derives from the applications view and shares that dependency; `users` reads `group_names` nowhere. diff --git a/utils/cache/carrier.py b/utils/cache/carrier.py index 989a0c2fc2..23f7972e70 100644 --- a/utils/cache/carrier.py +++ b/utils/cache/carrier.py @@ -1,11 +1,12 @@ -"""Play-scoped carrier of the rendered applications payload. +"""Play-scoped carriers of the rendered applications and users payloads. Ansible forks a fresh worker process per task, so the in-process -`_MERGED_APPLICATIONS_CACHE` starts empty in every worker. The constructor -stage renders once and parks the payload plus its cache key in the host fact -named by `APPLICATIONS_RENDERED_FACT`; every later worker inherits that fact -at fork time and `get_merged_applications` serves it instead of rendering. -Ansible-free at import time like the rest of the package. +`_MERGED_APPLICATIONS_CACHE` and `_MERGED_USERS_CACHE` start empty in every +worker. The constructor stage renders once and parks each payload plus its +cache key in the host facts named by `APPLICATIONS_RENDERED_FACT` and +`USERS_RENDERED_FACT`; every later worker inherits those facts at fork time +and `get_merged_applications` / `get_merged_users` serve them instead of +rendering. Ansible-free at import time like the rest of the package. """ from __future__ import annotations @@ -24,6 +25,7 @@ if TYPE_CHECKING: import os APPLICATIONS_RENDERED_FACT = "_INFINITO_APPLICATIONS_RENDERED" +USERS_RENDERED_FACT = "_INFINITO_USERS_RENDERED" def merged_applications_cache_key( @@ -53,6 +55,28 @@ def merged_applications_cache_key( ) +def merged_users_cache_key( + variables: Mapping[str, Any] | None, + *, + roles_dir: str | os.PathLike[str] | None = None, +) -> tuple[str, tuple]: + """Key under which one rendered users payload stays valid. + + Args: + variables: The play's variable scope. The applications key's inputs + plus ``inventory_hostname`` influence the key. + roles_dir: Roles tree the payload is built from; defaults to the + repository's `roles/`. + + Returns: + ``(resolved roles dir, applications key signature extended by the + host the payload was rendered for)``. + """ + roles_key, signature = merged_applications_cache_key(variables, roles_dir=roles_dir) + host = (variables or {}).get("inventory_hostname") + return (roles_key, (*signature, str(host or ""))) + + def revalidate_tokens_file(variables: Mapping[str, Any] | None) -> None: """Refresh an NFS client's attributes of the tokens file before a carrier is keyed. @@ -64,21 +88,26 @@ def revalidate_tokens_file(variables: Mapping[str, Any] | None) -> None: _revalidate_tokens_file(_resolve_tokens_file(variables)) -def _carried_applications( - variables: Mapping[str, Any], cache_key: tuple[str, tuple] +def _carried( + variables: Mapping[str, Any], + fact: str, + field: str, + cache_key: tuple[str, tuple], ) -> dict[str, Any] | None: - """Return the payload carried in `APPLICATIONS_RENDERED_FACT` when its - key equals *cache_key*, else ``None``. + """Return the payload carried in *fact* when its key equals *cache_key*, + else ``None``. Args: variables: The play's variable scope, read for the carrier fact. + fact: The carrier fact's name. + field: The carrier's payload field. cache_key: The key the caller would render under. """ - carrier = variables.get(APPLICATIONS_RENDERED_FACT) + carrier = variables.get(fact) if not isinstance(carrier, Mapping): return None key = carrier.get("key") - payload = carrier.get("applications") + payload = carrier.get(field) if ( not isinstance(payload, Mapping) or not isinstance(key, (list, tuple)) @@ -92,3 +121,29 @@ def _carried_applications( ]: return None return payload + + +def _carried_applications( + variables: Mapping[str, Any], cache_key: tuple[str, tuple] +) -> dict[str, Any] | None: + """Return the payload carried in `APPLICATIONS_RENDERED_FACT` when its + key equals *cache_key*, else ``None``. + + Args: + variables: The play's variable scope, read for the carrier fact. + cache_key: The key the caller would render under. + """ + return _carried(variables, APPLICATIONS_RENDERED_FACT, "applications", cache_key) + + +def _carried_users( + variables: Mapping[str, Any], cache_key: tuple[str, tuple] +) -> dict[str, Any] | None: + """Return the payload carried in `USERS_RENDERED_FACT` when its key + equals *cache_key*, else ``None``. + + Args: + variables: The play's variable scope, read for the carrier fact. + cache_key: The key the caller would render under. + """ + return _carried(variables, USERS_RENDERED_FACT, "users", cache_key) diff --git a/utils/cache/users/__init__.py b/utils/cache/users/__init__.py index a7a1a59527..79be183bc3 100644 --- a/utils/cache/users/__init__.py +++ b/utils/cache/users/__init__.py @@ -27,6 +27,7 @@ from utils.cache.base import ( _resolve_roles_dir, _stable_variables_signature, ) +from utils.cache.carrier import _carried_users, merged_users_cache_key from utils.cache.users import store as _store from utils.cache.users.placeholders import ( substitute_primary_domain_placeholder as _substitute_primary_domain_placeholder, @@ -442,6 +443,15 @@ def get_merged_users( if cached is not None: return cached + if templar is not None and source_variables: + carried = _carried_users( + source_variables, + merged_users_cache_key(source_variables, roles_dir=resolved_roles_dir), + ) + if carried is not None: + _MERGED_USERS_CACHE[cache_key] = carried + return carried + defaults = get_user_defaults(roles_dir=roles_dir) overrides = _resolve_override_mapping(variables, "users", templar=templar) From 96ebefb9db0b6cc5da227fa05c1e23de45d08623 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 15:56:08 +0100 Subject: [PATCH 12/42] perf(spot): re-render only the users SPOT after a token store write A token store write re-rendered the whole applications SPOT: merged_applications_cache_key carried the token store digest, so the applications_carrier park in sys-token-store/tasks/write_many.yml missed its key and rendered all 269 applications again (stalwart compose roundtrip 18.3 s and 10.2 s per pass, swarm pass 1 12.2 s and 12.6 s). Rendered from the real roles tree under an empty, a realistic and an exhaustive token store (298 users x 269 applications), the applications tree differs only under .users..tokens (28783 leaves in 46 applications, 0 elsewhere); the 69 password leaves that also differ change between two renders of the same store. No code reads a token through the applications tree: every reader goes through lookup('users'), lookup('config', , 'users....') (served from get_merged_users), lookup('email') or the sys_token_store_users fact, and the users carrier keys on the store. The token digest therefore moves from merged_applications_cache_key into merged_users_cache_key, whose value stays the same. A store write keeps the applications carrier and the write_many park re-renders the users alone; the task is renamed to match. applications.md now says that user records inside the payload can predate every store write and that application config must not derive a value from a token. Real ansible-playbook harness on 2.20.6 with the real roles, group_vars and write_many.yml: the re-park after a first mint and after a rotation drops from 4.0 s to 0.55 s on one host (applications renders 1 -> 0), and every token probe (users, config users path, email password, stalwart_users) equals the old code in compose and swarm mode. Dropping the digest from the users key as well leaves those probes stale, which the harness and two unit tests catch. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../files/plugins/lookup/applications.md | 6 +-- .../artefact/files/plugins/lookup/users.md | 3 +- plugins/action/applications_carrier.py | 15 +++---- roles/sys-token-store/README.md | 4 +- roles/sys-token-store/tasks/write_many.yml | 2 +- .../roles/sys-token-store/test_write_many.py | 2 +- .../python/utils/cache/test_applications.py | 22 +++++----- .../python/utils/cache/users/test_module.py | 40 +++++++++++++++++++ utils/cache/README.md | 6 +-- utils/cache/carrier.py | 27 +++++++------ 10 files changed, 88 insertions(+), 39 deletions(-) diff --git a/docs/contributing/artefact/files/plugins/lookup/applications.md b/docs/contributing/artefact/files/plugins/lookup/applications.md index 93b468d4dc..f00cd885c1 100644 --- a/docs/contributing/artefact/files/plugins/lookup/applications.md +++ b/docs/contributing/artefact/files/plugins/lookup/applications.md @@ -33,14 +33,14 @@ No other source is consulted. Ansible forks a fresh worker process for every task. The in-process cache inside `get_merged_applications` therefore never survives from one task to the next, and every task that touches the lookup would render the full tree again (about 16 to 23 seconds per task on a CI runner, measured on the workspace jobs). -The constructor stage renders once through the [applications_carrier](../../../../../../plugins/action/applications_carrier.py) action and parks the result together with its cache key in the host fact `_INFINITO_APPLICATIONS_RENDERED` (the action calls `lookup('applications', carrier=True)`). Every later worker inherits that fact at fork time; `get_merged_applications` serves it whenever the key still matches and renders only when it does not (a changed `applications`, `users`, `DOMAIN_PRIMARY`, `SYSTEM_EMAIL_DOMAIN` or `group_names`, or changed tokens in the store the users are hydrated from). +The constructor stage renders once through the [applications_carrier](../../../../../../plugins/action/applications_carrier.py) action and parks the result together with its cache key in the host fact `_INFINITO_APPLICATIONS_RENDERED` (the action calls `lookup('applications', carrier=True)`). Every later worker inherits that fact at fork time; `get_merged_applications` serves it whenever the key still matches and renders only when it does not (a changed `applications`, `users`, `DOMAIN_PRIMARY`, `SYSTEM_EMAIL_DOMAIN` or `group_names`). - The stage-wide task sits in `tasks/stages/01_constructor.yml` after the `networks`, `design` and `service_provider` merges, after the `add_host` placements and after the token store, so the payload renders with the same `group_names`, `groups` and user records a role would see. Moving it earlier bakes stale values into the play. - The carrier is parked again after every role in `tasks/utils/setup/role.yml`, after every nested application load in `tasks/utils/load/app.yml`, and after every store write in `roles/sys-token-store/tasks/write_many.yml`, which `write.yml` runs for a single token. The first two run on every host of the include, also on hosts the loaded role skips. A re-park whose key still matches serves the carried payload without rendering. - The action renders with `application_id` removed from its variables, so the carried tree holds the play-scope result of every consumer-aligned `lookup('tls', ...)`, whichever role parks it. -- The token store enters the key as the SHA-256 of exactly the tokens the users are hydrated from: the controller's tokens file until `sys-token-store` loads, the `sys_token_store_users` fact after. Both sources key alike when they hold the same tokens, so loading an unchanged store keeps the carrier, and a touch keeps the key. The carrier action opens the file before it computes the key, so an NFS client keys on revalidated attributes. +- The token store is not part of the key: a store write keeps the applications carrier and re-renders only the users carrier (see [users.md](users.md)). - The action masks its own result: the fact is the whole rendered tree with every application's credentials, so it never reaches a log regardless of `MASK_CREDENTIALS_IN_LOGS`. -- User records inside the payload are the token store's state at render time. Readers of tokens captured later in the play MUST go through `lookup('users', ...)` or `lookup('config', , 'users....')`, both of which key the users on the current token store. +- User records inside the payload are the token store's state at render time, which can predate every store write of the play. Readers of tokens MUST go through `lookup('users', ...)` or `lookup('config', , 'users....')`, both of which key the users on the current token store. Application config MUST NOT derive a value from a token. - The action parks the users carrier `_INFINITO_USERS_RENDERED` at the same points, after the applications render; `clear: true` drops both. See [users.md](users.md). - The carrier is private to the lookup. Consumers MUST NOT read `_INFINITO_APPLICATIONS_RENDERED`; they keep going through `lookup('applications')`, which is what makes the carrier transparent. - The carrier is the only materialised merged view a play MAY hold. The rule against a top-level `applications` fact above is unchanged. diff --git a/docs/contributing/artefact/files/plugins/lookup/users.md b/docs/contributing/artefact/files/plugins/lookup/users.md index 22fdab26b2..43f866b0ce 100644 --- a/docs/contributing/artefact/files/plugins/lookup/users.md +++ b/docs/contributing/artefact/files/plugins/lookup/users.md @@ -24,7 +24,8 @@ The `users` lookup is the ONLY supported runtime entry point for merged user con The [applications_carrier](../../../../../../plugins/action/applications_carrier.py) action parks the rendered users next to the applications in the host fact `_INFINITO_USERS_RENDERED`, at every point listed in [applications.md](applications.md), and `clear: true` drops both facts. `get_merged_users` serves the fact to a templated read when its key matches and renders otherwise. -- The key is the applications carrier key plus `inventory_hostname`: a changed `applications`, `users`, `DOMAIN_PRIMARY`, `SYSTEM_EMAIL_DOMAIN`, `group_names`, token store or host rejects the carrier. +- The key is the applications carrier key plus the token store and `inventory_hostname`: a changed `applications`, `users`, `DOMAIN_PRIMARY`, `SYSTEM_EMAIL_DOMAIN`, `group_names`, token store or host rejects the carrier. +- The token store enters the key as the SHA-256 of exactly the tokens the users are hydrated from: the controller's tokens file until `sys-token-store` loads, the `sys_token_store_users` fact after. Both sources key alike when they hold the same tokens, so loading an unchanged store keeps the carrier, and a touch keeps the key. The carrier action opens the file before it computes the key, so an NFS client keys on revalidated attributes. - A read without a templar (the raw users inside an applications render) never takes the carrier. - The carrier is private to the lookup. Consumers MUST NOT read `_INFINITO_USERS_RENDERED`; they keep going through `lookup('users')` or `lookup('config', , 'users....')`. diff --git a/plugins/action/applications_carrier.py b/plugins/action/applications_carrier.py index 5ad3fbf84c..39cae6ed84 100644 --- a/plugins/action/applications_carrier.py +++ b/plugins/action/applications_carrier.py @@ -7,7 +7,7 @@ renders in the worker of one constructor task and returns both payloads as host facts; every later worker inherits them at fork time and ``get_merged_applications`` / ``get_merged_users`` serve them instead of rendering. The users carrier is keyed like the applications carrier plus -``inventory_hostname``:: +the token store digest and ``inventory_hostname``:: - name: 🧊 Render the applications SPOT once and carry it into every task's worker applications_carrier: {} @@ -15,11 +15,12 @@ rendering. The users carrier is keyed like the applications carrier plus ``tasks/stages/01_constructor.yml`` parks three of them: a block-scoped one for the merge block, which it drops again at the block's end, one after the ``add_host`` tasks for the swarm bootstrap roles, parked only when -``DEPLOYMENT_MODE`` is ``swarm``, and the stage-wide one after the token store. ``merged_applications_cache_key`` reads ``group_names`` and a -digest of the tokens the users are hydrated from (the tokens file, or the -``sys_token_store_users`` fact once the token store loaded; both key alike for -the same tokens), so a carrier whose groups or tokens no longer match is -rejected and the reader renders afresh:: +``DEPLOYMENT_MODE`` is ``swarm``, and the stage-wide one after the token store. ``merged_applications_cache_key`` reads ``group_names``, so a +carrier whose groups no longer match is rejected and the reader renders +afresh. ``merged_users_cache_key`` adds a digest of the tokens the users are +hydrated from (the tokens file, or the ``sys_token_store_users`` fact once the +token store loaded; both key alike for the same tokens), so changed tokens +reject the users carrier only:: - name: 🧊 Drop the merge-block carrier so later stages re-render applications_carrier: @@ -30,7 +31,7 @@ rejected and the reader renders afresh:: ``roles/sys-token-store/tasks/write_many.yml`` one after every store write; where the key still matches they serve the carried payload without rendering, and a users carrier that still matches is left in place instead of being -returned again. +returned again. A store write therefore re-renders the users alone. The result is masked by the action itself: the facts are the whole rendered trees, about 0.4 MB with every application's and user's credentials, and diff --git a/roles/sys-token-store/README.md b/roles/sys-token-store/README.md index 8a83ec3aba..b8d2695cc8 100644 --- a/roles/sys-token-store/README.md +++ b/roles/sys-token-store/README.md @@ -103,7 +103,7 @@ Empty tokens are rejected explicitly. `write.yml` hands its token to `write_many ### `write_many.yml` -Persists several tokens with one store write and at most one re-render of the applications SPOT. +Persists several tokens with one store write and at most one re-render of the users SPOT. **Input** @@ -112,7 +112,7 @@ Persists several tokens with one store write and at most one re-render of the ap **Effects** - Merges every entry into the store in list order, so a later entry for the same user and app wins -- Writes the store file and re-renders the applications SPOT once, and only when the merged store differs from the loaded one +- Writes the store file and re-renders the users SPOT once, and only when the merged store differs from the loaded one --- diff --git a/roles/sys-token-store/tasks/write_many.yml b/roles/sys-token-store/tasks/write_many.yml index 458e08225c..4ff2e901c2 100644 --- a/roles/sys-token-store/tasks/write_many.yml +++ b/roles/sys-token-store/tasks/write_many.yml @@ -61,6 +61,6 @@ when: sys_token_store_users_merged != sys_token_store_users no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" -- name: 🧊 Re-render the applications SPOT the new tokens invalidated +- name: 🧊 Re-render the users SPOT the new tokens invalidated applications_carrier: {} when: sys_token_store_persisted is changed or sys_token_store_mirrored is changed diff --git a/tests/unit/python/roles/sys-token-store/test_write_many.py b/tests/unit/python/roles/sys-token-store/test_write_many.py index 728eabea4d..a02668d216 100644 --- a/tests/unit/python/roles/sys-token-store/test_write_many.py +++ b/tests/unit/python/roles/sys-token-store/test_write_many.py @@ -15,7 +15,7 @@ EMPTY = "šŸ›‘ Abort if a token is empty (do not persist empties)" PERSIST = "šŸ’¾ Persist store (idempotent, single-writer via STACK_HOST)" MIRROR = "šŸŖž Mirror the store onto the controller, where every users lookup reads" HAND_OVER = "šŸ”„ Hand the written store to the lookups of the rest of the play" -RERENDER = "🧊 Re-render the applications SPOT the new tokens invalidated" +RERENDER = "🧊 Re-render the users SPOT the new tokens invalidated" USERS = { "alice": {"tokens": {"web-app-a": "old-a"}, "note": "kept"}, diff --git a/tests/unit/python/utils/cache/test_applications.py b/tests/unit/python/utils/cache/test_applications.py index ba829a0a67..071e47d5fe 100644 --- a/tests/unit/python/utils/cache/test_applications.py +++ b/tests/unit/python/utils/cache/test_applications.py @@ -390,7 +390,7 @@ class TestGetMergedApplicationsCarrierFact(unittest.TestCase): merged["web-app-foo"]["services"]["foo"]["image"], "override" ) - def test_a_changed_tokens_file_rejects_the_carrier(self): + def test_a_changed_tokens_file_keeps_the_carrier(self): with tempfile.TemporaryDirectory() as tmp: roles = _seed_minimal_roles(Path(tmp)) tokens = Path(tmp) / "tokens.yml" @@ -398,9 +398,10 @@ class TestGetMergedApplicationsCarrierFact(unittest.TestCase): variables = self._variables() variables["FILE_TOKENS"] = str(tokens) key = merged_applications_cache_key(variables, roles_dir=roles) + carried = {"web-app-foo": {"carried": True}} variables[APPLICATIONS_RENDERED_FACT] = { "key": [key[0], list(key[1])], - "applications": {"web-app-foo": {"carried": True}}, + "applications": carried, } tokens.write_text( "users: {no-reply: {tokens: {web-app-stalwart: minted}}}\n", @@ -409,7 +410,7 @@ class TestGetMergedApplicationsCarrierFact(unittest.TestCase): merged = cache_apps.get_merged_applications( variables=variables, roles_dir=roles, templar=None ) - self.assertNotIn("carried", merged["web-app-foo"]) + self.assertIs(merged, carried) def _park_from_the_tokens_file(self, tmp: Path, token: str) -> tuple: roles = _seed_minimal_roles(tmp) @@ -441,28 +442,31 @@ class TestGetMergedApplicationsCarrierFact(unittest.TestCase): ) self.assertIs(merged, carried) - def test_the_store_fact_with_other_tokens_than_the_file_rejects_the_carrier( + def test_the_store_fact_with_other_tokens_than_the_file_keeps_the_carrier( self, ): with tempfile.TemporaryDirectory() as tmp: - roles, variables, _ = self._park_from_the_tokens_file(Path(tmp), "minted") + roles, variables, carried = self._park_from_the_tokens_file( + Path(tmp), "minted" + ) variables["sys_token_store_users"] = { "no-reply": {"tokens": {"web-app-stalwart": "rotated"}} } merged = cache_apps.get_merged_applications( variables=variables, roles_dir=roles, templar=None ) - self.assertNotIn("carried", merged["web-app-foo"]) + self.assertIs(merged, carried) - def test_a_changed_store_fact_rejects_the_carrier(self): + def test_a_changed_store_fact_keeps_the_carrier(self): with tempfile.TemporaryDirectory() as tmp: roles = _seed_minimal_roles(Path(tmp)) variables = self._variables() variables["sys_token_store_users"] = {} key = merged_applications_cache_key(variables, roles_dir=roles) + carried = {"web-app-foo": {"carried": True}} variables[APPLICATIONS_RENDERED_FACT] = { "key": [key[0], list(key[1])], - "applications": {"web-app-foo": {"carried": True}}, + "applications": carried, } variables["sys_token_store_users"] = { "no-reply": {"tokens": {"web-app-stalwart": "minted"}} @@ -470,7 +474,7 @@ class TestGetMergedApplicationsCarrierFact(unittest.TestCase): merged = cache_apps.get_merged_applications( variables=variables, roles_dir=roles, templar=None ) - self.assertNotIn("carried", merged["web-app-foo"]) + self.assertIs(merged, carried) def test_malformed_carrier_is_ignored(self): with tempfile.TemporaryDirectory() as tmp: diff --git a/tests/unit/python/utils/cache/users/test_module.py b/tests/unit/python/utils/cache/users/test_module.py index ee1ce655d2..a73dce394e 100644 --- a/tests/unit/python/utils/cache/users/test_module.py +++ b/tests/unit/python/utils/cache/users/test_module.py @@ -519,6 +519,46 @@ class TestGetMergedUsersCarrierFact(unittest.TestCase): merged["rendered"]["foo"]["tokens"]["web-app-foo"], "rotated" ) + def _park_from_the_tokens_file(self, tmp: Path, token: str) -> tuple: + roles = _seed_minimal_user_role(tmp) + tokens = tmp / "tokens.yml" + tokens.write_text( + f"users: {{foo: {{tokens: {{web-app-foo: {token}}}}}}}\n", + encoding="utf-8", + ) + variables = self._variables() + del variables[cache_users_store.STORE_FACT] + variables["FILE_TOKENS"] = str(tokens) + carried = self._park(roles, variables, {"foo": {"carried": True}}) + return roles, variables, tokens, carried + + def test_a_changed_tokens_file_rejects_the_carrier(self): + with tempfile.TemporaryDirectory() as tmp: + roles, variables, tokens, _ = self._park_from_the_tokens_file( + Path(tmp), "minted" + ) + tokens.write_text( + "users: {foo: {tokens: {web-app-foo: rotated-token}}}\n", + encoding="utf-8", + ) + merged, renders = self._merged(roles, variables) + self.assertEqual(renders, 1) + self.assertEqual( + merged["rendered"]["foo"]["tokens"]["web-app-foo"], "rotated-token" + ) + + def test_the_store_fact_with_the_file_tokens_keeps_the_carrier(self): + with tempfile.TemporaryDirectory() as tmp: + roles, variables, _, carried = self._park_from_the_tokens_file( + Path(tmp), "minted" + ) + variables[cache_users_store.STORE_FACT] = { + "foo": {"tokens": {"web-app-foo": "minted"}} + } + merged, renders = self._merged(roles, variables) + self.assertIs(merged, carried) + self.assertEqual(renders, 0) + def test_a_rotated_inventory_password_rejects_the_carrier(self): with tempfile.TemporaryDirectory() as tmp: roles = _seed_minimal_user_role(Path(tmp)) diff --git a/utils/cache/README.md b/utils/cache/README.md index 2ecbb1ccb5..6e81076853 100644 --- a/utils/cache/README.md +++ b/utils/cache/README.md @@ -11,7 +11,7 @@ This package contains the in-process cache layers Infinito.Nexus uses to keep CL | [base.py](base.py) | Cross-cutting helpers: filesystem constants (`PROJECT_ROOT`, `ROLES_DIR`, `DEFAULT_TOKENS_FILE`), `_deep_merge`, cache-key + content-fingerprint signatures, the cross-domain re-entry guard, and the templar-render machinery. The only ansible-coupled symbol is `_render_with_templar`, which lazy-imports its dependency. | | [applications.py](applications.py) | Per-app variants + defaults + `get_merged_applications`. **Strictly ansible-free at import time** so the GitHub Actions runner-host CLI path (`cli.administration.deploy.development.init` → `plan_dev_inventory_matrix` → `get_variants`) keeps working without ansible installed. | | [carrier.py](carrier.py) | The play-scoped carriers of the rendered applications and users payloads: the fact names `_INFINITO_APPLICATIONS_RENDERED` and `_INFINITO_USERS_RENDERED`, `merged_applications_cache_key`, `merged_users_cache_key`, and the readers `get_merged_applications` and `get_merged_users` consult before they render. | -| [users/](users/) | User definitions, token store hydration, alias materialization, `get_user_defaults`, `get_merged_users` (package; `users/placeholders.py` substitutes `DOMAIN_PRIMARY` / `ORGANIZATION` / `SOFTWARE_NAME` ahead of the templar render pass; `users/store.py` reads the `sys_token_store_users` fact and digests the tokens the users are hydrated from, the digest the users and carrier keys share). | +| [users/](users/) | User definitions, token store hydration, alias materialization, `get_user_defaults`, `get_merged_users` (package; `users/placeholders.py` substitutes `DOMAIN_PRIMARY` / `ORGANIZATION` / `SOFTWARE_NAME` ahead of the templar render pass; `users/store.py` reads the `sys_token_store_users` fact and digests the tokens the users are hydrated from, the digest the users cache and users carrier keys share). | | [domains.py](domains.py) | Canonical-domains map derived from the merged applications view: `get_merged_domains`. A read issued while the applications render is in progress (the re-entry guard is set) sees the unrendered view, so it is cached under its own key and never answers a later read. | | [`__init__.py`](__init__.py) | Owns the package-level `_reset_cache_for_tests()` orchestrator that clears every cache plus the shared fingerprint memo in one call. | @@ -26,7 +26,7 @@ The layers are orthogonal: `yaml.py` caches "this file's parsed root", the `appl Both layers are process-wide in-process caches. They intentionally do NOT track on-disk file mtimes; CLI tools are short-lived and the assumption "the on-disk file does not change while my process runs" holds. The single exception is `utils.cache.yaml.dump_yaml`, which writes through and evicts the cached entry for the path it just wrote so a tool that edits a file mid-run sees the new content on the next read. -Inside a play the process boundary is the task: Ansible forks a fresh worker per task, so `_MERGED_APPLICATIONS_CACHE` and `_MERGED_USERS_CACHE` start empty in every worker. `get_merged_applications` therefore also accepts the play-scoped carrier fact `_INFINITO_APPLICATIONS_RENDERED` (payload plus cache key, parked by the constructor stage and again after every role, every nested application load and every persisted token) and serves it when the key matches. The same action parks `_INFINITO_USERS_RENDERED`, which `get_merged_users` serves to templated reads under the applications key plus `inventory_hostname`. See [applications.md](../../docs/contributing/artefact/files/plugins/lookup/applications.md) and [users.md](../../docs/contributing/artefact/files/plugins/lookup/users.md) for the contract. +Inside a play the process boundary is the task: Ansible forks a fresh worker per task, so `_MERGED_APPLICATIONS_CACHE` and `_MERGED_USERS_CACHE` start empty in every worker. `get_merged_applications` therefore also accepts the play-scoped carrier fact `_INFINITO_APPLICATIONS_RENDERED` (payload plus cache key, parked by the constructor stage and again after every role, every nested application load and every persisted token) and serves it when the key matches. The same action parks `_INFINITO_USERS_RENDERED`, which `get_merged_users` serves to templated reads under the applications key plus the token store digest and `inventory_hostname`. See [applications.md](../../docs/contributing/artefact/files/plugins/lookup/applications.md) and [users.md](../../docs/contributing/artefact/files/plugins/lookup/users.md) for the contract. While one render runs, the re-entry guard also holds that render's unrendered view and its cache key. A nested `get_merged_applications` call from a lookup inside a role template (`config`, `tls`, `domain`, ...) with the same key returns that view instead of copying and merging the role defaults again. The view is shared by every nested call of the render, so callers MUST NOT mutate it. The guard drops it when the render ends. @@ -84,7 +84,7 @@ flowchart TD proc -.->|"TRIP-WIRE: read BEFORE the
host's own fact, so an inherited
entry outranks it"| fact render -.->|"TRIP-WIRE: main process renders
task names for one host; forked
workers inherit that entry"| proc - key -.->|"TRIP-WIRE: carrier.py:118 stringifies
only one side, so a non-scalar key
part silently never matches again"| fact + key -.->|"TRIP-WIRE: carrier.py:121 stringifies
only one side, so a non-scalar key
part silently never matches again"| fact ``` The key covers `group_names`. `domains.py` derives from the applications view and shares that dependency; `users` reads `group_names` nowhere. diff --git a/utils/cache/carrier.py b/utils/cache/carrier.py index 23f7972e70..b8fdf5e1d8 100644 --- a/utils/cache/carrier.py +++ b/utils/cache/carrier.py @@ -37,21 +37,17 @@ def merged_applications_cache_key( Args: variables: The play's variable scope. Only the subset that - `_stable_variables_signature` reads, and the token store the users - are hydrated from, influence the key. + `_stable_variables_signature` reads influences the key; the token + store keys the users carrier instead (`merged_users_cache_key`). roles_dir: Roles tree the payload is built from; defaults to the repository's `roles/`. Returns: - ``(resolved roles dir, stable variables signature extended by the - token store signature)``. + ``(resolved roles dir, stable variables signature)``. """ - from .users import _resolve_tokens_file, _store_signature - - tokens = _store_signature(variables, _resolve_tokens_file(variables)) return ( _cache_key(_resolve_roles_dir(roles_dir=roles_dir)), - (*_stable_variables_signature(variables), *(str(part) for part in tokens)), + _stable_variables_signature(variables), ) @@ -63,18 +59,25 @@ def merged_users_cache_key( """Key under which one rendered users payload stays valid. Args: - variables: The play's variable scope. The applications key's inputs - plus ``inventory_hostname`` influence the key. + variables: The play's variable scope. The applications key's inputs, + the token store the users are hydrated from and + ``inventory_hostname`` influence the key. roles_dir: Roles tree the payload is built from; defaults to the repository's `roles/`. Returns: ``(resolved roles dir, applications key signature extended by the - host the payload was rendered for)``. + token store signature and the host the payload was rendered for)``. """ + from .users import _resolve_tokens_file, _store_signature + roles_key, signature = merged_applications_cache_key(variables, roles_dir=roles_dir) + tokens = _store_signature(variables, _resolve_tokens_file(variables)) host = (variables or {}).get("inventory_hostname") - return (roles_key, (*signature, str(host or ""))) + return ( + roles_key, + (*signature, *(str(part) for part in tokens), str(host or "")), + ) def revalidate_tokens_file(variables: Mapping[str, Any] | None) -> None: From 612dfa838a4a05f737ee128ea322065af9f52fec Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 16:34:23 +0100 Subject: [PATCH 13/42] perf(svc-prx-openresty): drop the swarm docker.sock group-add the root poller no longer needs The swarm-only task ran `container service update --group-add ` on every deploy with changed_when: true, a rolling restart of the edge proxy (16.7 s in the stalwart swarm roundtrip) right before the force-redeploy handler restarted it again (16.5 s). The group existed for the docker-health poller to read /var/run/docker.sock. Since 79318da622 the poller runs in the OpenResty privileged agent, which keeps the master's root identity, while the workers run as nobody and drop supplementary groups through initgroups anyway; compose never set a group_add. Evidence on the running compose stack: `ps` shows the privileged agent as root:root and the workers as nobody:nobody, and the web-app-prometheus /metricz spec, which requires nginx_docker_health_entries > 0, passed in both compose passes without any group. The stat of the host socket and the OPENRESTY_DOCKER_SOCK_GID fact had no other reader and go with the task; the docker.sock bind mount stays. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/svc-prx-openresty/tasks/00_core.yml | 24 ----------------------- 1 file changed, 24 deletions(-) diff --git a/roles/svc-prx-openresty/tasks/00_core.yml b/roles/svc-prx-openresty/tasks/00_core.yml index 074a3e9cf0..3949a903ad 100644 --- a/roles/svc-prx-openresty/tasks/00_core.yml +++ b/roles/svc-prx-openresty/tasks/00_core.yml @@ -1,19 +1,6 @@ --- - include_tasks: utils/once/flag.yml -- when: DEPLOYMENT_MODE == 'swarm' - block: - - name: "šŸ”Ž Stat the docker socket so the swarm openresty worker can be group-added to it" - ansible.builtin.stat: - # nocheck: volumes-path-single-spot this stats the socket on the HOST; it only happens to spell the same string as the container mount target - path: /var/run/docker.sock - register: _openresty_docker_sock - - - name: "šŸ”§ Set OPENRESTY_DOCKER_SOCK_GID from the live socket gid" - ansible.builtin.set_fact: - OPENRESTY_DOCKER_SOCK_GID: "{{ _openresty_docker_sock.stat.gid }}" - when: _openresty_docker_sock.stat.exists | default(false) - - name: "āœ… Ensure the full openresty config tree exists before any http-include writer" directory_batch: entries: >- @@ -49,17 +36,6 @@ vars: compose_handlers_flush: true -- name: "šŸ”§ Add openresty to docker.sock group for swarm (stack deploy rejects group_add)" - ansible.builtin.command: >- - container service update --detach=false - --group-add {{ OPENRESTY_DOCKER_SOCK_GID | quote }} - {{ lookup('container_service', application_id, 'openresty') | quote }} - changed_when: true - delegate_to: "{{ STACK_HOST }}" - when: - - DEPLOYMENT_MODE == 'swarm' - - OPENRESTY_DOCKER_SOCK_GID is defined - - name: "āœ… Verify that '{{ role_name }}' works" include_tasks: 01_assert.yml when: MODE_ASSERT_LOCAL | bool From 6ec97a09b4dfc8a7d202b06212631adfceb713f3 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Thu, 29 Oct 2026 15:56:32 +0000 Subject: [PATCH 14/42] update(images): update Docker image versions (web-app-gitlab) --- roles/web-app-gitlab/meta/services.yml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/roles/web-app-gitlab/meta/services.yml b/roles/web-app-gitlab/meta/services.yml index 9c7cd70687..111272749a 100644 --- a/roles/web-app-gitlab/meta/services.yml +++ b/roles/web-app-gitlab/meta/services.yml @@ -76,7 +76,7 @@ gitlab: lifecycle: beta webservice: image: registry.gitlab.com/gitlab-org/build/cng/gitlab-webservice-ce - version: v19.5.1 + version: v19.5.3 name: gitlab-webservice healthcheck: test: ["CMD", "/scripts/healthcheck"] @@ -95,7 +95,7 @@ sidekiq: flavor: tcp path: liveness image: registry.gitlab.com/gitlab-org/build/cng/gitlab-sidekiq-ce - version: v19.5.1 + version: v19.5.3 name: gitlab-sidekiq cpus: "1.0" mem_reservation: 2g @@ -106,7 +106,7 @@ sidekiq: http: 3808 workhorse: image: registry.gitlab.com/gitlab-org/build/cng/gitlab-workhorse-ce - version: v19.5.1 + version: v19.5.3 name: gitlab-workhorse healthcheck: test: ["CMD", "/scripts/healthcheck"] @@ -118,7 +118,7 @@ gitaly: # nocheck: single-replica replicas: 1 image: registry.gitlab.com/gitlab-org/build/cng/gitaly - version: v19.5.1 + version: v19.5.3 healthcheck: test: ["CMD", "/scripts/healthcheck"] name: gitlab-gitaly @@ -131,7 +131,7 @@ gitaly: pids_limit: 1024 shell: image: registry.gitlab.com/gitlab-org/build/cng/gitlab-shell - version: v19.5.1 + version: v19.5.3 name: gitlab-shell ports: internal: @@ -144,7 +144,7 @@ migrations: # nocheck: single-replica replicas: 1 image: registry.gitlab.com/gitlab-org/build/cng/gitlab-rails-ce - version: v19.5.1 + version: v19.5.3 name: gitlab-migrations cpus: "1.0" mem_reservation: 1g From bbd54e0077f561892371efdafd2fec829fdad286 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Thu, 29 Oct 2026 15:56:37 +0000 Subject: [PATCH 15/42] update(images): update Docker image versions (web-app-pgadmin) --- roles/web-app-pgadmin/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-pgadmin/meta/services.yml b/roles/web-app-pgadmin/meta/services.yml index 4184791bf4..263a62428e 100644 --- a/roles/web-app-pgadmin/meta/services.yml +++ b/roles/web-app-pgadmin/meta/services.yml @@ -11,7 +11,7 @@ pgadmin: # nocheck: default-placement-manager embedded sqlite config db; node-local in swarm placement: manager image: dpage/pgadmin4 - version: "9.18" + version: "9.19" min_storage: 378MB server_mode: false master_password_required: true From 3bbc7ca205087def2a7c048c8352dd4289429e97 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Thu, 29 Oct 2026 15:56:47 +0000 Subject: [PATCH 16/42] update(images): update Docker image versions (web-app-prometheus) --- roles/web-app-prometheus/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-prometheus/meta/services.yml b/roles/web-app-prometheus/meta/services.yml index fd8f536f5b..3efbe50131 100644 --- a/roles/web-app-prometheus/meta/services.yml +++ b/roles/web-app-prometheus/meta/services.yml @@ -79,7 +79,7 @@ alertmanager: flavor: wget path: -/healthy image: prom/alertmanager # nocheck: volumes-path-single-spot: the repository path of an image name, not a mount target - version: v0.34.1 + version: v0.34.2 name: prometheus-alertmanager cpus: "0.25" mem_reservation: 64m From eebb50d82a8f445be046487a673c556b511e6566 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Thu, 29 Oct 2026 15:56:53 +0000 Subject: [PATCH 17/42] update(images): update Docker image versions (web-app-wazuh) --- roles/web-app-wazuh/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-wazuh/meta/services.yml b/roles/web-app-wazuh/meta/services.yml index d38e9054c9..224974902e 100644 --- a/roles/web-app-wazuh/meta/services.yml +++ b/roles/web-app-wazuh/meta/services.yml @@ -60,7 +60,7 @@ wazuh: lifecycle: beta certs_generator: image: wazuh/wazuh-certs-generator - version: "0.0.4" + version: "0.0.5" name: wazuh-certs-generator cpus: "0.2" mem_reservation: 64m From 2c6c7e146433bf338ea1a2c0a5321fa430aa1408 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 17:07:57 +0100 Subject: [PATCH 18/42] fix(web-app-nextcloud): trust the real reverse-proxy hop so Nextcloud sees client IPs trusted_proxies held the host's public addresses, but OpenResty reaches Nextcloud through the published port, which Docker forwards from the gateway of one of the container's networks (192.168.201.1, the central MariaDB network, on production). Nextcloud therefore ignored X-Forwarded-For, attributed every request to that gateway and brute-force throttled it. The TRUSTED_PROXIES env var was joined with commas while the image's reverse-proxy.config.php splits it on spaces, which produced the single malformed entry the admin overview rejects, and the occ value reached config:system:set as a Python repr instead of JSON, so config.php got null. Add the proxy_hops lookup next to resolve_upstream in utils/networks/proxy.py: under compose it returns the gateway of every network the application joins, under swarm the subnets of the overlays it shares with svc-prx-openresty, both derived from the service registry and role_subnets. NEXTCLOUD_TRUSTED_PROXIES now uses it, env.j2 joins the list with spaces and system.yml passes it through to_json. Rendered with the real roles and group_vars for the galaxyserver layout: compose trusts 192.168.41.1, 192.168.201.1 and 192.168.202.1, swarm 192.168.107.0/24; unit and integration tests cover both modes, and two mutations of proxy_hops fail them. Co-Authored-By: Claude Opus 5.5 (1M context) --- plugins/lookup/proxy_hops.py | 61 ++++++++++ roles/web-app-nextcloud/templates/env.j2 | 2 +- roles/web-app-nextcloud/vars/main.yml | 2 +- roles/web-app-nextcloud/vars/system.yml | 2 +- .../ansible/lookups/test_proxy_hops.py | 109 ++++++++++++++++++ .../python/plugins/lookup/test_proxy_hops.py | 101 ++++++++++++++++ .../unit/python/utils/networks/test_proxy.py | 88 +++++++++++++- utils/networks/proxy.py | 49 +++++++- 8 files changed, 407 insertions(+), 7 deletions(-) create mode 100644 plugins/lookup/proxy_hops.py create mode 100644 tests/integration/ansible/lookups/test_proxy_hops.py create mode 100644 tests/unit/python/plugins/lookup/test_proxy_hops.py diff --git a/plugins/lookup/proxy_hops.py b/plugins/lookup/proxy_hops.py new file mode 100644 index 0000000000..b1de021516 --- /dev/null +++ b/plugins/lookup/proxy_hops.py @@ -0,0 +1,61 @@ +"""Lookup ``proxy_hops``: the addresses the reverse proxy's requests reach an +application from, for that application's trusted-proxy list. + +Usage: + + {{ lookup('proxy_hops', application_id) }} # compose: ['192.168.41.1', '192.168.201.1'] + # swarm: ['192.168.107.0/24'] + +Returns what :func:`utils.networks.proxy.proxy_hops` derives from the networks +the service_registry attaches. +""" + +from __future__ import annotations + +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +from utils.networks.lookup_context import build_context, resolve_var +from utils.networks.proxy import proxy_hops +from utils.networks.render import compute_external_network_roles + + +class LookupModule(LookupBase): + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[Any]: + if not terms or len(terms) != 1: + raise AnsibleError( + "proxy_hops lookup requires exactly one term: application_id" + ) + + ctx = build_context(self, variables) + application_id = str(resolve_var(ctx.templar, terms[0])) + role_subnets = lookup_loader.get( + "role_subnets", loader=self._loader, templar=ctx.templar + ) + + def network_roles(role: str) -> list[str]: + return compute_external_network_roles( + application_id=role, + deployment_mode=ctx.deployment_mode, + registry=ctx.registry, + lookup_config=ctx.lookup_config, + lookup_database=ctx.lookup_database, + ) + + def subnets(roles: list[str]) -> list[str]: + return role_subnets.run([roles], variables=ctx.vars)[0] + + try: + return [ + proxy_hops(application_id, ctx.deployment_mode, network_roles, subnets) + ] + except ValueError as exc: + raise AnsibleError(f"proxy_hops: {exc}") from exc diff --git a/roles/web-app-nextcloud/templates/env.j2 b/roles/web-app-nextcloud/templates/env.j2 index 523629cb98..2f47434e48 100644 --- a/roles/web-app-nextcloud/templates/env.j2 +++ b/roles/web-app-nextcloud/templates/env.j2 @@ -27,7 +27,7 @@ NEXTCLOUD_ADMIN_PASSWORD={{ NEXTCLOUD_ADMINISTRATOR_PASSWORD | dotenv_quote }} NEXTCLOUD_INIT_GATE_USER={{ NEXTCLOUD_DOCKER_USER }} NEXTCLOUD_TRUSTED_DOMAINS={{ NEXTCLOUD_DOMAIN }} -TRUSTED_PROXIES={{ NEXTCLOUD_TRUSTED_PROXIES | join(',') }} +TRUSTED_PROXIES={{ NEXTCLOUD_TRUSTED_PROXIES | join(' ') }} OVERWRITECLIURL={{ NEXTCLOUD_URL }} OVERWRITEPROTOCOL={{ NEXTCLOUD_PROTOCOL }} diff --git a/roles/web-app-nextcloud/vars/main.yml b/roles/web-app-nextcloud/vars/main.yml index e50c07f331..e30e3c6673 100644 --- a/roles/web-app-nextcloud/vars/main.yml +++ b/roles/web-app-nextcloud/vars/main.yml @@ -11,7 +11,7 @@ NEXTCLOUD_DOMAIN: "{{ lookup('domain',application_id) }}" NEXTCLOUD_PORT: "{{ lookup('config', application_id, 'services.nextcloud.ports.local.http') }}" NEXTCLOUD_URL: "{{ lookup('tls', application_id, 'url.base') }}" NEXTCLOUD_PROTOCOL: "{{ lookup('tls', application_id, 'protocols.web') }}" -NEXTCLOUD_TRUSTED_PROXIES: "{{ networks.internet.values() | select }}" +NEXTCLOUD_TRUSTED_PROXIES: "{{ lookup('proxy_hops', application_id) }}" NEXTCLOUD_SSO_ENABLED: "{{ lookup('config', application_id, 'services.sso.enabled') | bool }}" NEXTCLOUD_OIDC_HOST: "{{ lookup('tls', 'web-app-keycloak', 'domain') }}" diff --git a/roles/web-app-nextcloud/vars/system.yml b/roles/web-app-nextcloud/vars/system.yml index b18d7954ed..3a5734d256 100644 --- a/roles/web-app-nextcloud/vars/system.yml +++ b/roles/web-app-nextcloud/vars/system.yml @@ -39,7 +39,7 @@ nextcloud_system_config: - parameter: "trusted_proxies" type: "json" - value: "{{ NEXTCLOUD_TRUSTED_PROXIES }}" + value: "{{ NEXTCLOUD_TRUSTED_PROXIES | to_json }}" - parameter: "log_type" value: "errorlog" diff --git a/tests/integration/ansible/lookups/test_proxy_hops.py b/tests/integration/ansible/lookups/test_proxy_hops.py new file mode 100644 index 0000000000..71a4b14a75 --- /dev/null +++ b/tests/integration/ansible/lookups/test_proxy_hops.py @@ -0,0 +1,109 @@ +"""Integration test: proxy_hops for web-app-nextcloud against the real role tree.""" + +from __future__ import annotations + +import unittest + +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar + +from plugins.lookup.applications import ( + LookupModule as ApplicationsLookup, +) +from plugins.lookup.applications import ( + _reset_cache_for_tests, +) +from plugins.lookup.proxy_hops import LookupModule as ProxyHopsLookup +from utils.cache.yaml import load_yaml +from utils.networks.address import subnet_gateway +from utils.networks.proxy import REVERSE_PROXY_APPLICATION_ID +from utils.roles.mapping import ROLE_FILE_META_NETWORKS + +from . import PROJECT_ROOT + +ROLES_DIR = PROJECT_ROOT / "roles" +APP = "web-app-nextcloud" +CENTRAL_DATABASE = "svc-db-mariadb" +DIRECTORY = "svc-db-openldap" +GROUP_NAMES = [APP, CENTRAL_DATABASE, DIRECTORY, REVERSE_PROXY_APPLICATION_ID] +PUBLIC_ADDRESSES = ["198.51.100.7", "2001:db8:1::2"] + + +def _subnet(role: str) -> str: + return load_yaml(str(ROLES_DIR / role / ROLE_FILE_META_NETWORKS))["local"]["subnet"] + + +def _variables(applications: dict, mode: str) -> dict: + return { + "applications": applications, + "users": {}, + "DOMAIN_PRIMARY": "infinito.test", + "SYSTEM_EMAIL_DOMAIN": "infinito.test", + "DIR_COMPOSITIONS": "/opt/compose/", + "group_names": list(GROUP_NAMES), + "DEPLOYMENT_MODE": mode, + "application_id": APP, + "networks": { + "internet": { + "ip4": PUBLIC_ADDRESSES[0], + "ip6": PUBLIC_ADDRESSES[1], + "dns": "", + } + }, + } + + +def _hops(applications: dict, mode: str) -> list[str]: + lookup = ProxyHopsLookup() + lookup._loader = DataLoader() + lookup._templar = Templar(loader=lookup._loader) + return lookup.run([APP], variables=_variables(applications, mode))[0] + + +class TestProxyHopsIntegration(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + _reset_cache_for_tests() + applications = ApplicationsLookup() + applications._templar = Templar(loader=DataLoader()) + merged = applications.run( + [], variables=_variables({}, "compose"), roles_dir=str(ROLES_DIR) + )[0] + cls.compose = _hops(merged, "compose") + cls.swarm = _hops(merged, "swarm") + + @classmethod + def tearDownClass(cls) -> None: + _reset_cache_for_tests() + + def test_compose_trusts_the_gateway_of_every_network_the_proxy_service_joins( + self, + ) -> None: + self.assertEqual( + sorted(self.compose), + sorted( + subnet_gateway(_subnet(role)) + for role in (APP, CENTRAL_DATABASE, DIRECTORY) + ), + "Openresty reaches the published port from the host, and Docker " + "forwards it from the gateway of whichever of these networks it " + "routes the container through; production saw the central " + "database's gateway.", + ) + + def test_swarm_trusts_the_openresty_overlay(self) -> None: + self.assertEqual(self.swarm, [_subnet(REVERSE_PROXY_APPLICATION_ID)]) + + def test_swarm_does_not_trust_overlays_openresty_is_not_on(self) -> None: + for role in (APP, CENTRAL_DATABASE, DIRECTORY): + with self.subTest(role=role): + self.assertNotIn(_subnet(role), self.swarm) + + def test_public_host_addresses_are_not_proxy_hops(self) -> None: + for mode, hops in (("compose", self.compose), ("swarm", self.swarm)): + with self.subTest(mode=mode): + self.assertFalse(set(PUBLIC_ADDRESSES) & set(hops)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_proxy_hops.py b/tests/unit/python/plugins/lookup/test_proxy_hops.py new file mode 100644 index 0000000000..1027e0cba1 --- /dev/null +++ b/tests/unit/python/plugins/lookup/test_proxy_hops.py @@ -0,0 +1,101 @@ +"""Unit tests for plugins/lookup/proxy_hops.py.""" + +from __future__ import annotations + +import unittest +import unittest.mock as mock + +from ansible.errors import AnsibleError + +from plugins.lookup.proxy_hops import LookupModule + +_SUBNETS = { + "web-app-nextcloud": "192.168.41.0/24", + "svc-db-mariadb": "192.168.201.0/24", + "svc-prx-openresty": "192.168.107.0/24", +} + + +class _Templar: + def __init__(self, vars_=None): + self.available_variables = vars_ or {} + + def template(self, value, **_): + return value + + +def _make_lookup(vars_): + lm = LookupModule() + lm._templar = _Templar(vars_) + lm._loader = mock.MagicMock() + return lm + + +def _role_subnets(): + return mock.MagicMock( + run=lambda terms, **_: [[_SUBNETS[role] for role in terms[0]]] + ) + + +def _joined(application_id, deployment_mode, **_): + if application_id == "svc-prx-openresty": + return ["svc-prx-openresty"] if deployment_mode == "swarm" else [] + if deployment_mode == "swarm": + return ["svc-db-mariadb", "svc-prx-openresty", application_id] + return ["svc-db-mariadb", application_id] + + +def _run(mode, terms=("web-app-nextcloud",), joined=_joined): + vars_ = {"application_id": "web-app-nextcloud", "DEPLOYMENT_MODE": mode} + lm = _make_lookup(vars_) + with ( + mock.patch( + "utils.networks.lookup_context.build_service_registry_from_applications", + return_value={}, + ), + mock.patch("utils.networks.lookup_context.lookup_loader") as context_loader, + mock.patch("plugins.lookup.proxy_hops.lookup_loader") as plugin_loader, + mock.patch( + "plugins.lookup.proxy_hops.compute_external_network_roles", + side_effect=lambda **kwargs: joined( + kwargs["application_id"], kwargs["deployment_mode"] + ), + ) as roles_mock, + ): + context_loader.get.return_value = mock.MagicMock(run=lambda *_a, **_k: [""]) + plugin_loader.get.return_value = _role_subnets() + result = lm.run(list(terms), variables=vars_) + return result, roles_mock + + +class TestProxyHopsLookup(unittest.TestCase): + def test_raises_without_application_id_term(self): + lm = _make_lookup({"DEPLOYMENT_MODE": "compose"}) + with self.assertRaises(AnsibleError): + lm.run([], variables={}) + + def test_raises_on_extra_terms(self): + lm = _make_lookup({"DEPLOYMENT_MODE": "compose"}) + with self.assertRaises(AnsibleError): + lm.run(["web-app-nextcloud", "extra"], variables={}) + + def test_compose_returns_gateways_of_the_joined_networks(self): + result, _ = _run("compose") + self.assertEqual(result, [["192.168.41.1", "192.168.201.1"]]) + + def test_swarm_returns_the_overlay_shared_with_openresty(self): + result, roles_mock = _run("swarm") + self.assertEqual(result, [["192.168.107.0/24"]]) + asked = {call.kwargs["application_id"] for call in roles_mock.call_args_list} + self.assertEqual(asked, {"web-app-nextcloud", "svc-prx-openresty"}) + + def test_missing_shared_overlay_surfaces_as_ansible_error(self): + def isolated(application_id, deployment_mode): + return [application_id] + + with self.assertRaises(AnsibleError): + _run("swarm", joined=isolated) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/networks/test_proxy.py b/tests/unit/python/utils/networks/test_proxy.py index 7afce429f8..a8eb7ae899 100644 --- a/tests/unit/python/utils/networks/test_proxy.py +++ b/tests/unit/python/utils/networks/test_proxy.py @@ -1,10 +1,54 @@ -"""Tests for utils.networks.proxy: resolve_upstream + render_proxy_pass.""" +"""Tests for utils.networks.proxy: resolve_upstream, render_proxy_pass, proxy_hops.""" from __future__ import annotations import unittest -from utils.networks.proxy import render_proxy_pass, resolve_upstream +from utils.networks.proxy import ( + REVERSE_PROXY_APPLICATION_ID, + proxy_hops, + render_proxy_pass, + resolve_upstream, +) + +_APP = "web-app-nextcloud" +_SUBNETS = { + _APP: "192.168.41.0/24", + "svc-db-mariadb": "192.168.201.0/24", + "svc-db-openldap": "192.168.202.0/24", + REVERSE_PROXY_APPLICATION_ID: "192.168.107.0/24", +} +_JOINED = { + "compose": { + _APP: ["svc-db-mariadb", "svc-db-openldap", _APP], + REVERSE_PROXY_APPLICATION_ID: [], + }, + "swarm": { + _APP: [ + "svc-db-mariadb", + "svc-db-openldap", + REVERSE_PROXY_APPLICATION_ID, + _APP, + ], + REVERSE_PROXY_APPLICATION_ID: [REVERSE_PROXY_APPLICATION_ID], + }, +} + + +def _hops(mode: str, joined: dict[str, list[str]] | None = None) -> list[str]: + """``proxy_hops`` over the fixture topology. + + Args: + mode: ``compose`` or ``swarm``. + joined: role id to the networks it joins; ``None`` means ``_JOINED[mode]``. + """ + networks = _JOINED[mode] if joined is None else joined + return proxy_hops( + _APP, + mode, + lambda role: list(networks[role]), + lambda roles: [_SUBNETS[role] for role in roles], + ) def _apps(): @@ -194,5 +238,45 @@ class TestRenderProxyPassGuards(unittest.TestCase): render_proxy_pass("", "swarm") +class TestProxyHopsCompose(unittest.TestCase): + def test_gateway_of_every_network_the_app_joins(self): + self.assertEqual( + _hops("compose"), + ["192.168.41.1", "192.168.201.1", "192.168.202.1"], + ) + + def test_own_network_counts_when_the_app_provides_no_shared_net(self): + joined = {_APP: ["svc-db-mariadb"], REVERSE_PROXY_APPLICATION_ID: []} + self.assertEqual(_hops("compose", joined), ["192.168.41.1", "192.168.201.1"]) + + def test_network_the_app_does_not_join_is_not_trusted(self): + joined = {_APP: [_APP], REVERSE_PROXY_APPLICATION_ID: []} + self.assertEqual(_hops("compose", joined), ["192.168.41.1"]) + + def test_whole_subnets_are_not_trusted(self): + for hop in _hops("compose"): + with self.subTest(hop=hop): + self.assertNotIn("/", hop) + + +class TestProxyHopsSwarm(unittest.TestCase): + def test_subnet_of_the_overlay_shared_with_the_proxy(self): + self.assertEqual(_hops("swarm"), ["192.168.107.0/24"]) + + def test_overlay_only_the_app_joins_is_not_trusted(self): + hops = _hops("swarm") + for role in ("svc-db-mariadb", "svc-db-openldap", _APP): + with self.subTest(role=role): + self.assertNotIn(_SUBNETS[role], hops) + + def test_no_shared_overlay_raises(self): + joined = { + _APP: ["svc-db-mariadb", _APP], + REVERSE_PROXY_APPLICATION_ID: [REVERSE_PROXY_APPLICATION_ID], + } + with self.assertRaises(ValueError): + _hops("swarm", joined) + + if __name__ == "__main__": unittest.main() diff --git a/utils/networks/proxy.py b/utils/networks/proxy.py index 53dfe08bc2..8d0a55c51c 100644 --- a/utils/networks/proxy.py +++ b/utils/networks/proxy.py @@ -1,4 +1,5 @@ -"""Mode-aware nginx ``proxy_pass`` directive renderer (compose/swarm), SPOT. +"""Mode-aware nginx ``proxy_pass`` directive renderer and the addresses its +requests reach an application from (compose/swarm), SPOT. Trip-wire: the swarm oauth2 endpoint must forward ``$uri$is_args$args``, not ``$request_uri`` — during the ``error_page 401 = @oauth2_start`` jump the original @@ -8,14 +9,19 @@ Trip-wire: the swarm oauth2 endpoint must forward ``$uri$is_args$args``, not from __future__ import annotations import re -from typing import Any +from typing import TYPE_CHECKING, Any +from utils.networks.address import subnet_gateway from utils.roles.applications.config import get from utils.roles.entity.name import get_entity_name +if TYPE_CHECKING: + from collections.abc import Callable + _REGEX_OR_NAMED_LOCATION = re.compile(r"^[@~]") _LOCATION_MODIFIER = re.compile(r"^(?:=|\^~)\s*") _UPSTREAM_VAR = "proxy_pass_upstream" +REVERSE_PROXY_APPLICATION_ID = "svc-prx-openresty" def _as_str(value: Any) -> str: @@ -132,3 +138,42 @@ def render_proxy_pass( f" proxy_pass http://${_UPSTREAM_VAR}{_swarm_tail(tail)};" ) return f"proxy_pass http://{authority}{_compose_suffix(tail, location)};" + + +def proxy_hops( + application_id: str, + deployment_mode: str, + network_roles: Callable[[str], list[str]], + subnets: Callable[[list[str]], list[str]], +) -> list[str]: + """Addresses the reverse proxy's requests reach ``application_id`` from. + + Args: + application_id: the proxied application. + deployment_mode: ``compose`` or ``swarm``, after any per-role override. + network_roles: role id to the provider roles whose networks it joins. + subnets: role ids to their ``networks.local.subnet``, in order. + + Returns: + Under compose the gateway of the application's own network and of + every network it joins: the proxy runs on the host network and reaches + a published port, which Docker forwards from the gateway of whichever + of those networks it routes the container through. Under swarm the + subnets of the overlays the application shares with the proxy, which + reaches it from its task address there. + + Raises: + ValueError: under swarm the application shares no overlay with the + proxy. + """ + if deployment_mode != "swarm": + roles = list(dict.fromkeys([application_id, *network_roles(application_id)])) + return list(dict.fromkeys(subnet_gateway(subnet) for subnet in subnets(roles))) + proxy_networks = network_roles(REVERSE_PROXY_APPLICATION_ID) + shared = [role for role in network_roles(application_id) if role in proxy_networks] + if not shared: + raise ValueError( + f"{application_id} shares no overlay with " + f"{REVERSE_PROXY_APPLICATION_ID}, so no address carries its proxied requests" + ) + return list(dict.fromkeys(subnets(shared))) From b4329d60441fd27a443cc7a5a698bd0203e0492c Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 17:14:30 +0100 Subject: [PATCH 19/42] feat(web-app-nextcloud): run a dedicated Task Processing worker Nextcloud 34 flags "Task Processing worker status: never run" because only occ taskprocessing:worker records core/ai.taskprocessing_worker_last_iteration, and the role ran background jobs through the cron container alone; since 32.0.7 the worker command is taskprocessing:worker, so background-job:worker would never clear the check. Add a taskprocessing service that reuses the cron image, mounts, healthcheck, restart policy and networks and runs occ taskprocessing:worker -t 60 in an in-container restart loop that backs off while Nextcloud is not yet installed, so swarm neither replaces the task every minute nor marks the stack fatal on a fresh install. It scales with the swarm topology, since task claims use FOR UPDATE SKIP LOCKED. Rendered compose and swarm stacks only gain the taskprocessing service and validate against the compose schema; the new unit tests fail when the worker mount is dropped or background-job:worker is used instead. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-nextcloud/meta/services.yml | 6 ++ roles/web-app-nextcloud/meta/volumes.yml | 4 + .../templates/compose.yml.j2 | 25 ++++++ roles/web-app-nextcloud/vars/main.yml | 3 + .../test_talk_direct_media.py | 1 + .../test_taskprocessing_worker.py | 77 +++++++++++++++++++ 6 files changed, 116 insertions(+) create mode 100644 tests/unit/python/roles/web-app-nextcloud/test_taskprocessing_worker.py diff --git a/roles/web-app-nextcloud/meta/services.yml b/roles/web-app-nextcloud/meta/services.yml index bab4709cd9..5fd355f302 100644 --- a/roles/web-app-nextcloud/meta/services.yml +++ b/roles/web-app-nextcloud/meta/services.yml @@ -188,6 +188,12 @@ cron: mem_limit: 512m pids_limit: 256 min_storage: 1GB +taskprocessing: + name: nextcloud-taskprocessing + cpus: "0.5" + mem_reservation: 128m + mem_limit: 1g + pids_limit: 256 # nocheck: dynamic-flag # nocheck: playwright-service-flag: infrastructural sub-component (real-time communication) talk: diff --git a/roles/web-app-nextcloud/meta/volumes.yml b/roles/web-app-nextcloud/meta/volumes.yml index 599520cdcf..71472549cb 100644 --- a/roles/web-app-nextcloud/meta/volumes.yml +++ b/roles/web-app-nextcloud/meta/volumes.yml @@ -7,6 +7,8 @@ data: target: &var_www_html_target /var/www/html/ - service: cron target: *var_www_html_target + - service: taskprocessing + target: *var_www_html_target - service: proxy target: *var_www_html_target read_only: true @@ -60,6 +62,8 @@ infinito_conf: target: &var_www_infinito_target /var/www/infinito/ - service: cron target: *var_www_infinito_target + - service: taskprocessing + target: *var_www_infinito_target janus_conf: type: config diff --git a/roles/web-app-nextcloud/templates/compose.yml.j2 b/roles/web-app-nextcloud/templates/compose.yml.j2 index 3d17c31bd4..bdc5da2bf0 100644 --- a/roles/web-app-nextcloud/templates/compose.yml.j2 +++ b/roles/web-app-nextcloud/templates/compose.yml.j2 @@ -151,6 +151,31 @@ {{ lookup('container_depends_on', application_id) | indent(4) }} {{ lookup('container_networks', provider_self_alias=False) | indent(4) }} + {% set service_name = NEXTCLOUD_TASKPROCESSING_SERVICE %} + {{ service_name }}: + {% include 'roles/sys-svc-container/templates/deploy.yml.j2' %} + {{ lookup('compose_only', 'container_name', NEXTCLOUD_TASKPROCESSING_CONTAINER) }} + {{ lookup('container_image', application_id, 'nextcloud') }} + {{ lookup('compose_restart') }} + logging: + driver: journald + {{ lookup('container_volumes', service_name) | indent(4) }} + entrypoint: ["su", "{{ NEXTCLOUD_DOCKER_USER }}", "-s", "/bin/sh", "-c", "while true; do php {{ NEXTCLOUD_INTERNAL_OCC_COMMAND }} taskprocessing:worker -t 60 || sleep 10; done"] + sysctls: + net.ipv6.conf.all.disable_ipv6: "{{ (not NETWORK_IPV6_ENABLED | bool) | int }}" + healthcheck: + test: ["CMD", "su", "{{ NEXTCLOUD_DOCKER_USER }}", "-s", "/bin/sh", "-c", "php {{ NEXTCLOUD_INTERNAL_OCC_COMMAND }} status"] + # nocheck: healthcheck-timing-override occ boots the whole Nextcloud stack per probe, so it stays off a 30s loop + interval: 1m + # nocheck: healthcheck-timing-override occ regularly needs more than the 5s default to answer + timeout: 30s + retries: 10 + # nocheck: healthcheck-timing-override a role variable the linter cannot compare, tuned per deployment size + start_period: {{ container_healthcheck_start_period }} + start_interval: 5s + {{ lookup('container_depends_on', application_id) | indent(4) }} + {{ lookup('container_networks', provider_self_alias=False) | indent(4) }} + {% if NEXTCLOUD_RECORDING_ENABLED | bool %} {% set service_name = 'talk_recording' %} {{ service_name }}: diff --git a/roles/web-app-nextcloud/vars/main.yml b/roles/web-app-nextcloud/vars/main.yml index e30e3c6673..e480248c67 100644 --- a/roles/web-app-nextcloud/vars/main.yml +++ b/roles/web-app-nextcloud/vars/main.yml @@ -148,6 +148,9 @@ NEXTCLOUD_CONTEXT_AGENT_JSON_INFO: >- NEXTCLOUD_CRON_SERVICE: "cron" NEXTCLOUD_CRON_CONTAINER: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_CRON_SERVICE ~ '.name') }}" +NEXTCLOUD_TASKPROCESSING_SERVICE: "taskprocessing" +NEXTCLOUD_TASKPROCESSING_CONTAINER: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_TASKPROCESSING_SERVICE ~ '.name') }}" + NEXTCLOUD_HPB_SERVICE: "talk" NEXTCLOUD_HPB_CONTAINER: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.name') }}" NEXTCLOUD_HPB_NETWORK_MODE: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.network_mode') }}" diff --git a/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py b/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py index 9d3ddb3211..40eaa4c4c3 100644 --- a/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py +++ b/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py @@ -114,6 +114,7 @@ def _render( "NEXTCLOUD_PROXY_SERVICE": "proxy", "NEXTCLOUD_SERVICE": "nextcloud", "NEXTCLOUD_CRON_SERVICE": "cron", + "NEXTCLOUD_TASKPROCESSING_SERVICE": "taskprocessing", "DEPLOYMENT_MODE": mode, "NEXTCLOUD_HPB_SIGNALING_ENABLED": True, "NEXTCLOUD_HPB_SERVICE": "talk", diff --git a/tests/unit/python/roles/web-app-nextcloud/test_taskprocessing_worker.py b/tests/unit/python/roles/web-app-nextcloud/test_taskprocessing_worker.py new file mode 100644 index 0000000000..a17656b30e --- /dev/null +++ b/tests/unit/python/roles/web-app-nextcloud/test_taskprocessing_worker.py @@ -0,0 +1,77 @@ +from __future__ import annotations + +import re +import unittest + +from jinja2 import ChainableUndefined, Environment, select_autoescape + +from plugins.lookup.container_volumes import container_volumes +from utils.cache.files import PROJECT_ROOT, read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ( + ROLE_FILE_META_SERVICES, + ROLE_FILE_TEMPL_COMPOSE, + ROLE_FILE_VARS_MAIN, +) + +ROLE = "roles/web-app-nextcloud" +APPLICATION_ID = "web-app-nextcloud" +SERVICES = load_yaml_any(str(PROJECT_ROOT / ROLE / ROLE_FILE_META_SERVICES)) +VARS = load_yaml_any(str(PROJECT_ROOT / ROLE / ROLE_FILE_VARS_MAIN)) +TEMPLATE = read_text(str(PROJECT_ROOT / ROLE / ROLE_FILE_TEMPL_COMPOSE)) + + +def _render_jinja(expression: str) -> str: + env = Environment( + undefined=ChainableUndefined, + autoescape=select_autoescape(default_for_string=False), + ) + env.globals["lookup"] = lambda name, *args, **kwargs: f"<{name} {args!r}>" + env.filters["path_join"] = lambda parts: "/".join(str(part) for part in parts) + return env.from_string(expression).render() + + +def _mounts(service: str) -> str: + return container_volumes( + {APPLICATION_ID: {"services": SERVICES}}, + APPLICATION_ID, + service, + render_jinja=_render_jinja, + ) + + +def _service_block(service_var: str) -> str: + start = TEMPLATE.index(f"{{% set service_name = {service_var} %}}") + following = re.search(r"\{% (set service_name|if|endif)\b", TEMPLATE[start + 1 :]) + end = start + 1 + following.start() if following else len(TEMPLATE) + return TEMPLATE[start:end] + + +class TestTaskProcessingWorker(unittest.TestCase): + def test_service_key_matches_the_vars_spot(self): + self.assertIn(VARS["NEXTCLOUD_TASKPROCESSING_SERVICE"], SERVICES) + + def test_worker_mounts_exactly_what_cron_mounts(self): + cron = _mounts(VARS["NEXTCLOUD_CRON_SERVICE"]) + self.assertIn("/var/www/html/", cron) + self.assertEqual(_mounts(VARS["NEXTCLOUD_TASKPROCESSING_SERVICE"]), cron) + + def test_worker_scales_with_the_swarm_topology(self): + self.assertNotIn("replicas", SERVICES[VARS["NEXTCLOUD_TASKPROCESSING_SERVICE"]]) + + def test_worker_runs_the_command_that_records_its_heartbeat(self): + block = _service_block("NEXTCLOUD_TASKPROCESSING_SERVICE") + self.assertIn("taskprocessing:worker -t 60", block) + self.assertNotIn("background-job:worker", block) + + def test_worker_runs_the_cron_image_as_the_occ_owner(self): + worker = _service_block("NEXTCLOUD_TASKPROCESSING_SERVICE") + cron = _service_block("NEXTCLOUD_CRON_SERVICE") + image = "{{ lookup('container_image', application_id, 'nextcloud') }}" + self.assertIn(image, cron) + self.assertIn(image, worker) + self.assertIn('"su", "{{ NEXTCLOUD_DOCKER_USER }}"', worker) + + +if __name__ == "__main__": + unittest.main() From b0c622ab4421e2d20a9eef8d3c9b36a28c59cbf6 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 17:24:17 +0100 Subject: [PATCH 20/42] fix(web-app-nextcloud): give each PHP server its own NC_serverid The admin overview reported that no server identifier is configured. Nextcloud 34 accepts 1 to 511, treats values below 1 as unset and asks for one NC_serverid per server when config.php is shared, which it is between nextcloud, cron, the task processing worker and the swarm replicas. A single serverid in config.php would let them mint identical Snowflake IDs in the same millisecond. The nextcloud service now carries NC_serverid 1 in compose and its task slot in swarm, so the check passes and replicas never share an id; the other services keep the hostname fallback. A unit test renders the service environment in both modes and fails when the compose id leaves the accepted range. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../templates/compose.yml.j2 | 7 +++- .../roles/web-app-nextcloud/test_server_id.py | 40 +++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) create mode 100644 tests/unit/python/roles/web-app-nextcloud/test_server_id.py diff --git a/roles/web-app-nextcloud/templates/compose.yml.j2 b/roles/web-app-nextcloud/templates/compose.yml.j2 index bdc5da2bf0..efa411aa9b 100644 --- a/roles/web-app-nextcloud/templates/compose.yml.j2 +++ b/roles/web-app-nextcloud/templates/compose.yml.j2 @@ -23,10 +23,13 @@ {{ lookup('template', 'roles/sys-svc-container/templates/build.yml.j2') | indent(4) }} {{ lookup('container_volumes', service_name) | indent(4) }} - {% if DEPLOYMENT_MODE == 'swarm' %} environment: + {% if DEPLOYMENT_MODE == 'swarm' %} TASK_SLOT: "{% raw %}{{.Task.Slot}}{% endraw %}" - {% endif %} + NC_serverid: "{% raw %}{{.Task.Slot}}{% endraw %}" + {% else %} + NC_serverid: "1" + {% endif %} sysctls: net.ipv6.conf.all.disable_ipv6: "{{ (not NETWORK_IPV6_ENABLED | bool) | int }}" healthcheck: diff --git a/tests/unit/python/roles/web-app-nextcloud/test_server_id.py b/tests/unit/python/roles/web-app-nextcloud/test_server_id.py new file mode 100644 index 0000000000..5cdb15db49 --- /dev/null +++ b/tests/unit/python/roles/web-app-nextcloud/test_server_id.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +import unittest + +from jinja2 import Environment, select_autoescape + +from utils.cache.files import PROJECT_ROOT, read_text +from utils.cache.yaml import load_yaml_str +from utils.roles.mapping import ROLE_FILE_TEMPL_COMPOSE + +TEMPLATE = read_text( + str(PROJECT_ROOT / "roles/web-app-nextcloud" / ROLE_FILE_TEMPL_COMPOSE) +) + + +def _environment(deployment_mode: str) -> dict: + start = TEMPLATE.index(" environment:\n") + end = TEMPLATE.index(" sysctls:", start) + rendered = ( + Environment(autoescape=select_autoescape(default_for_string=False)) + .from_string(TEMPLATE[start:end]) + .render(DEPLOYMENT_MODE=deployment_mode) + ) + return load_yaml_str(rendered)["environment"] + + +class TestServerId(unittest.TestCase): + def test_compose_pins_a_server_id_nextcloud_accepts(self): + server_id = int(_environment("compose")["NC_serverid"]) + self.assertGreaterEqual(server_id, 1) + self.assertLessEqual(server_id, 511) + + def test_swarm_gives_every_replica_its_task_slot(self): + environment = _environment("swarm") + self.assertEqual(environment["NC_serverid"], "{{.Task.Slot}}") + self.assertEqual(environment["TASK_SLOT"], "{{.Task.Slot}}") + + +if __name__ == "__main__": + unittest.main() From a0242cc8f8a21f15c9448b51b66e0d3e25ab0c16 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 17:34:50 +0100 Subject: [PATCH 21/42] fix(web-app-nextcloud): disable logreader while the log goes to stderr log_type stays errorlog (a0e5710018) so exceptions reach docker logs and the CI rescue artifacts. logreader reads only the file log type and turned that into an "Errors in the log" notice in the admin overview. The role now declares logreader as a disabled addon, so the plugin plan switches it off on every deploy; the addon spec required for every addon only runs when the addon is enabled. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-nextcloud/README.md | 1 + .../files/playwright/addons/logreader.spec.js | 41 +++++++++++++++++++ .../meta/addons/logreader.yml | 5 +++ 3 files changed, 47 insertions(+) create mode 100644 roles/web-app-nextcloud/files/playwright/addons/logreader.spec.js create mode 100644 roles/web-app-nextcloud/meta/addons/logreader.yml diff --git a/roles/web-app-nextcloud/README.md b/roles/web-app-nextcloud/README.md index 456d925c78..861961280c 100644 --- a/roles/web-app-nextcloud/README.md +++ b/roles/web-app-nextcloud/README.md @@ -190,6 +190,7 @@ The enable-only appstore apps stay under `nextcloud.plugins` in [`meta/services. | `spreed` | `plugin` | enabled with the `talk` service | `talk`, `coturn` | | `whiteboard` | `plugin` | `required` (always installed) | none (self-hosted backend) | | `xwiki` | `plugin` | enabled with the `xwiki` partner | `xwiki` → `web-app-xwiki` | +| `logreader` | `plugin` | disabled, `log_type` is `errorlog` | none | The SSO (`sociallogin`) and LDAP (`user_ldap`) login surfaces are covered by the OIDC/LDAP Playwright specs (requirements 017/018). diff --git a/roles/web-app-nextcloud/files/playwright/addons/logreader.spec.js b/roles/web-app-nextcloud/files/playwright/addons/logreader.spec.js new file mode 100644 index 0000000000..28ffbfb66b --- /dev/null +++ b/roles/web-app-nextcloud/files/playwright/addons/logreader.spec.js @@ -0,0 +1,41 @@ +const { test, expect } = require("@playwright/test"); +const { resolveTimeout } = require("../timeouts"); +const { skipUnlessAddonEnabled } = require("../addon-gating"); +const shared = require("../_shared"); +const { gotoOnion } = require("../personas"); + +test.use({ ignoreHTTPSErrors: true }); + +test("logreader addon: the log reader app is enabled for the logged-in user", async ({ browser }) => { + skipUnlessAddonEnabled("logreader"); + test.setTimeout(resolveTimeout(120_000)); + + const context = await browser.newContext({ ignoreHTTPSErrors: true }); + const page = await context.newPage(); + + 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); + + await expect( + page.locator("#app-content, #app-content-vue, #app-navigation-vue").first(), + "the Nextcloud Files app shell must render before reading the enabled apps", + ).toBeVisible({ timeout: resolveTimeout(60_000) }); + + const logreaderEnabled = await page.evaluate(() => { + const oc = window.OC || {}; + const webroots = oc.appswebroots || (oc.appConfig && oc.appConfig.appswebroots) || {}; + return Object.prototype.hasOwnProperty.call(webroots, "logreader"); + }); + expect( + logreaderEnabled, + "logreader must be listed in OC.appswebroots, which Nextcloud fills with the enabled apps only", + ).toBe(true); + } finally { + await page.close().catch(() => {}); + await context.close().catch(() => {}); + } +}); diff --git a/roles/web-app-nextcloud/meta/addons/logreader.yml b/roles/web-app-nextcloud/meta/addons/logreader.yml new file mode 100644 index 0000000000..29609554ac --- /dev/null +++ b/roles/web-app-nextcloud/meta/addons/logreader.yml @@ -0,0 +1,5 @@ +--- +enabled: false +required: false +mechanism: plugin +source: upstream From 8d767239e398127af853a57b7a9832f1cc469fc2 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 17:37:20 +0100 Subject: [PATCH 22/42] fix(web-app-nextcloud): disable app_api while no MCP client uses it app_api only serves the context_agent ExApp behind the MCP surface. With mcp.enabled false it stayed enabled anyway and the admin overview asked for a default deploy daemon. The app_api addon now follows mcp.enabled like the context_agent service, so instances without an MCP client drop the notice and MCP rounds keep or re-enable the app before the ExApp is registered. Making the manual_install daemon the default instead would turn the notice into a "not accessible" error, because AppAPI then pings it as a Docker API. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-nextcloud/README.md | 3 +- .../files/playwright/addons/app_api.spec.js | 41 +++++++++++++++++++ .../web-app-nextcloud/meta/addons/app_api.yml | 5 +++ 3 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 roles/web-app-nextcloud/files/playwright/addons/app_api.spec.js create mode 100644 roles/web-app-nextcloud/meta/addons/app_api.yml diff --git a/roles/web-app-nextcloud/README.md b/roles/web-app-nextcloud/README.md index 861961280c..e6933744f2 100644 --- a/roles/web-app-nextcloud/README.md +++ b/roles/web-app-nextcloud/README.md @@ -190,6 +190,7 @@ The enable-only appstore apps stay under `nextcloud.plugins` in [`meta/services. | `spreed` | `plugin` | enabled with the `talk` service | `talk`, `coturn` | | `whiteboard` | `plugin` | `required` (always installed) | none (self-hosted backend) | | `xwiki` | `plugin` | enabled with the `xwiki` partner | `xwiki` → `web-app-xwiki` | +| `app_api` | `plugin` | enabled while `mcp.enabled` is true, disabled otherwise | none | | `logreader` | `plugin` | disabled, `log_type` is `errorlog` | none | The SSO (`sociallogin`) and LDAP (`user_ldap`) login surfaces are covered by the OIDC/LDAP Playwright specs (requirements 017/018). @@ -294,7 +295,7 @@ Off. `mcp.enabled` is true only while `web-app-hermes`, `web-app-openclaw` or `w ### How to disable -Remove the MCP client roles, or pin `mcp.enabled: false` for this role. The `context_agent` service is then not rendered, the ExApp is not registered with AppAPI, and no app password is minted. +Remove the MCP client roles, or pin `mcp.enabled: false` for this role. The `context_agent` service is then not rendered, the ExApp is not registered with AppAPI, no app password is minted, and the `app_api` app is disabled. ## Documentation diff --git a/roles/web-app-nextcloud/files/playwright/addons/app_api.spec.js b/roles/web-app-nextcloud/files/playwright/addons/app_api.spec.js new file mode 100644 index 0000000000..5682a8c912 --- /dev/null +++ b/roles/web-app-nextcloud/files/playwright/addons/app_api.spec.js @@ -0,0 +1,41 @@ +const { test, expect } = require("@playwright/test"); +const { resolveTimeout } = require("../timeouts"); +const { skipUnlessAddonEnabled } = require("../addon-gating"); +const shared = require("../_shared"); +const { gotoOnion } = require("../personas"); + +test.use({ ignoreHTTPSErrors: true }); + +test("app_api addon: the AppAPI app is enabled for the logged-in user", async ({ browser }) => { + skipUnlessAddonEnabled("app_api"); + test.setTimeout(resolveTimeout(120_000)); + + const context = await browser.newContext({ ignoreHTTPSErrors: true }); + const page = await context.newPage(); + + 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); + + await expect( + page.locator("#app-content, #app-content-vue, #app-navigation-vue").first(), + "the Nextcloud Files app shell must render before reading the enabled apps", + ).toBeVisible({ timeout: resolveTimeout(60_000) }); + + const appApiEnabled = await page.evaluate(() => { + const oc = window.OC || {}; + const webroots = oc.appswebroots || (oc.appConfig && oc.appConfig.appswebroots) || {}; + return Object.prototype.hasOwnProperty.call(webroots, "app_api"); + }); + expect( + appApiEnabled, + "app_api must be listed in OC.appswebroots, which Nextcloud fills with the enabled apps only: the MCP surface proxies through AppAPI, so the role keeps it enabled while mcp.enabled is true", + ).toBe(true); + } finally { + await page.close().catch(() => {}); + await context.close().catch(() => {}); + } +}); diff --git a/roles/web-app-nextcloud/meta/addons/app_api.yml b/roles/web-app-nextcloud/meta/addons/app_api.yml new file mode 100644 index 0000000000..38ec085ecc --- /dev/null +++ b/roles/web-app-nextcloud/meta/addons/app_api.yml @@ -0,0 +1,5 @@ +--- +enabled: "{{ lookup('config', 'web-app-nextcloud', 'mcp.enabled') | bool }}" +required: false +mechanism: plugin +source: upstream From abee135c538014e9ff0642b21a28c30eede70d96 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 17:42:59 +0100 Subject: [PATCH 23/42] fix(web-app-nextcloud): replace a pinned app directory instead of overlaying its archive The pinned onlyoffice archive was unpacked with tar over custom_apps/onlyoffice on every deploy, so files that a newer release no longer ships stayed behind. On cloud.veen.world that left the 52 files of onlyoffice 9.15.1 (NC32 line) inside the 10.2.1 tree, and the integrity check reported them as EXTRA_FILE; the 52 equal exactly the 9.15.1 files absent from 10.2.1. replace_pinned_app.sh now unpacks the release beside the app, keeps the app when diff -rq finds it identical, and otherwise swaps the whole directory, so the next deploy heals the drifted tree and later deploys report ok. A broken archive fails before the live app is touched. The real install task, run through ansible-playbook against a reproduced 9.15.1 plus 10.2.1 tree, changed it once to a tree identical to a clean 10.2.1 and stayed unchanged on the rerun; eleven unit cases cover identical, drifted, missing and broken inputs under sh and dash. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../files/shell/utils/replace_pinned_app.sh | 33 ++++ .../02_manager_ops/06_plugin/02_install.yml | 8 +- .../tasks/02_manager_ops/06_plugin/README.md | 10 ++ .../test_replace_pinned_app.py | 150 ++++++++++++++++++ 4 files changed, 198 insertions(+), 3 deletions(-) create mode 100644 roles/web-app-nextcloud/files/shell/utils/replace_pinned_app.sh create mode 100644 tests/unit/python/roles/web-app-nextcloud/test_replace_pinned_app.py diff --git a/roles/web-app-nextcloud/files/shell/utils/replace_pinned_app.sh b/roles/web-app-nextcloud/files/shell/utils/replace_pinned_app.sh new file mode 100644 index 0000000000..df1d4af6bf --- /dev/null +++ b/roles/web-app-nextcloud/files/shell/utils/replace_pinned_app.sh @@ -0,0 +1,33 @@ +#!/bin/sh +set -eu + +# Usage: +# replace_pinned_app.sh < +# stdin: the release archive, holding the app under /. +# +# Exit: 0, with [CHANGED] on stdout when / was replaced +# by the release; non-zero when the archive does not unpack or lacks +# /appinfo/info.xml, with / left untouched. + +apps_dir="$1" +app_id="$2" +live="$apps_dir/$app_id" +stage="$apps_dir/.$app_id.stage" +old="$apps_dir/.$app_id.old" + +rm -rf "$stage" "$old" +mkdir "$stage" +tar -xzf - -C "$stage" +test -f "$stage/$app_id/appinfo/info.xml" + +if [ -d "$live" ] && diff -rq "$live" "$stage/$app_id" >/dev/null; then + rm -rf "$stage" + exit 0 +fi + +if [ -d "$live" ]; then + mv "$live" "$old" +fi +mv "$stage/$app_id" "$live" +rm -rf "$stage" "$old" +echo "[CHANGED] $live now holds exactly the files of the pinned $app_id release." diff --git a/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/02_install.yml b/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/02_install.yml index a3d9c15aea..38355134f1 100644 --- a/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/02_install.yml +++ b/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/02_install.yml @@ -14,15 +14,17 @@ mode: "0644" when: plugin_archive | length > 0 -- name: "šŸ“¦ Unpack the pinned {{ plugin_key }} release so occ finds it installed" +- name: "šŸ“¦ Replace {{ plugin_key }} with the pinned release when any of its files differ" ansible.builtin.shell: >- cat /tmp/nextcloud-plugin-{{ plugin_key }}.tar.gz | {{ NEXTCLOUD_DOCKER_EXEC_INTERACTIVE }} - tar -xzf - -C {{ NEXTCLOUD_APPS_DIRECTORY | quote }} + sh -c {{ lookup('file', 'shell/utils/replace_pinned_app.sh') | quote }} + replace_pinned_app.sh {{ NEXTCLOUD_APPS_DIRECTORY | quote }} {{ plugin_key | quote }} args: executable: /bin/bash + register: nextcloud_plugin_archive_replace when: plugin_archive | length > 0 - changed_when: false + changed_when: "'[CHANGED]' in nextcloud_plugin_archive_replace.stdout" - name: "šŸ”“ Disable incompatible plugins for {{ plugin_key }} (batched shell, no async)" ansible.builtin.shell: | diff --git a/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/README.md b/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/README.md index 5844edeffb..e8fb82f362 100644 --- a/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/README.md +++ b/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/README.md @@ -52,6 +52,16 @@ Each `tasks/02_manager_ops/06_plugin/.yml` file owns exactly one OCC stage | [03_enable.yml](./03_enable.yml) | enable | `occ app:enable` | enable result is not flagged `incompatible`; the plugin is then queued for the configure stage | | [04_configure.yml](./04_configure.yml) | configure | one `occ config:list`, then `occ config:app:set` for the values that differ, plus optional hook | (terminal stage) | +## Pinned archives + +An addon MAY pin a release through `config.archive`. Before `occ app:install`, [02_install.yml](./02_install.yml) stages the archive on the node and pipes it into [files/shell/utils/replace_pinned_app.sh](../../../files/shell/utils/replace_pinned_app.sh) inside the container: + +1. The script unpacks the archive into `custom_apps/..stage`, a directory Nextcloud skips because of its leading dot, and fails without touching the installed app when the archive lacks `/appinfo/info.xml`. +2. When `diff -rq` finds the installed app identical to the release, it removes the stage and the task reports no change. +3. Otherwise it renames the installed app to `custom_apps/..old`, moves the release into its place and removes both, so the app directory holds exactly the files of the release and the task reports a change. + +`occ app:install` then answers `already installed`. + ## Configure stage [04_configure.yml](./04_configure.yml) runs once for every queued plugin: first the plugins the install loop enabled, then the background installs, then those the enable loop enabled, then those of the `configure` plan list. diff --git a/tests/unit/python/roles/web-app-nextcloud/test_replace_pinned_app.py b/tests/unit/python/roles/web-app-nextcloud/test_replace_pinned_app.py new file mode 100644 index 0000000000..d01272bb56 --- /dev/null +++ b/tests/unit/python/roles/web-app-nextcloud/test_replace_pinned_app.py @@ -0,0 +1,150 @@ +from __future__ import annotations + +import io +import subprocess +import tarfile +import tempfile +import unittest +from pathlib import Path + +from utils.cache.files import PROJECT_ROOT + +SCRIPT = ( + PROJECT_ROOT / "roles/web-app-nextcloud/files/shell/utils/replace_pinned_app.sh" +) +APP = "onlyoffice" +INFO = "appinfo/info.xml" + + +def _archive(files: dict[str, str]) -> bytes: + """Return a gzipped tar that holds each file under ``/``. + + Args: + files: archive member path mapped to its text content. + """ + buffer = io.BytesIO() + with tarfile.open(fileobj=buffer, mode="w:gz") as tar: + for name, content in files.items(): + data = content.encode() + member = tarfile.TarInfo(name) + member.size = len(data) + tar.addfile(member, io.BytesIO(data)) + return buffer.getvalue() + + +def _release(version: str, *extra: str) -> dict[str, str]: + files = { + f"{APP}/{INFO}": f"{version}", + f"{APP}/lib/Migration/Version{version}.php": version, + } + files.update({f"{APP}/{name}": version for name in extra}) + return files + + +def _tree(root: Path) -> dict[str, str]: + return { + path.relative_to(root).as_posix(): path.read_text() # nocheck: cache-read + for path in sorted(root.rglob("*")) # nocheck: project-walk + if path.is_file() + } + + +class TestReplacePinnedApp(unittest.TestCase): + def setUp(self): + self._tmp = tempfile.TemporaryDirectory() + self.apps = Path(self._tmp.name) / "custom_apps" + self.apps.mkdir() + self.live = self.apps / APP + + def tearDown(self): + self._tmp.cleanup() + + def _run(self, files: dict[str, str]) -> subprocess.CompletedProcess: + return subprocess.run( + ["sh", str(SCRIPT), str(self.apps), APP], + input=_archive(files), + capture_output=True, + check=False, + ) + + def _install(self, files: dict[str, str]) -> None: + self.assertEqual(self._run(files).returncode, 0) + + def _expected(self, files: dict[str, str]) -> dict[str, str]: + return {name.removeprefix(f"{APP}/"): text for name, text in files.items()} + + def test_a_fresh_install_places_the_release(self): + release = _release("100201") + result = self._run(release) + self.assertEqual(result.returncode, 0) + self.assertEqual(_tree(self.live), self._expected(release)) + + def test_a_fresh_install_reports_a_change(self): + self.assertIn(b"[CHANGED]", self._run(_release("100201")).stdout) + + def test_an_identical_tree_reports_no_change(self): + release = _release("100201") + self._install(release) + result = self._run(release) + self.assertEqual(result.returncode, 0) + self.assertNotIn(b"[CHANGED]", result.stdout) + + def test_files_of_an_earlier_release_are_removed(self): + self._install(_release("091501", "js/old.chunk.mjs")) + release = _release("100201", "js/new.chunk.mjs") + result = self._run(release) + self.assertIn(b"[CHANGED]", result.stdout) + self.assertEqual(_tree(self.live), self._expected(release)) + + def test_an_overlaid_tree_with_leftovers_is_healed(self): + release = _release("100201") + self._install(release) + (self.live / "js").mkdir() + (self.live / "js/leftover.chunk.mjs").write_text("091501") + result = self._run(release) + self.assertIn(b"[CHANGED]", result.stdout) + self.assertEqual(_tree(self.live), self._expected(release)) + + def test_a_changed_file_is_replaced(self): + release = _release("100201") + self._install(release) + (self.live / INFO).write_text("patched") + self.assertIn(b"[CHANGED]", self._run(release).stdout) + self.assertEqual(_tree(self.live), self._expected(release)) + + def test_an_archive_without_the_app_fails(self): + result = self._run({"other/appinfo/info.xml": "x"}) + self.assertNotEqual(result.returncode, 0) + + def test_an_archive_without_the_app_keeps_the_installed_app(self): + release = _release("100201") + self._install(release) + self._run({"other/appinfo/info.xml": "x"}) + self.assertEqual(_tree(self.live), self._expected(release)) + + def test_a_corrupt_archive_keeps_the_installed_app(self): + release = _release("100201") + self._install(release) + result = subprocess.run( + ["sh", str(SCRIPT), str(self.apps), APP], + input=b"not a tarball", + capture_output=True, + check=False, + ) + self.assertNotEqual(result.returncode, 0) + self.assertEqual(_tree(self.live), self._expected(release)) + + def test_leftovers_of_an_interrupted_run_are_cleared(self): + (self.apps / f".{APP}.stage/{APP}").mkdir(parents=True) + (self.apps / f".{APP}.old/js").mkdir(parents=True) + self._install(_release("100201")) + self.assertEqual(sorted(p.name for p in self.apps.iterdir()), [APP]) + + def test_the_apps_directory_holds_only_the_app_after_a_replace(self): + self._install(_release("091501")) + self._install(_release("100201")) + self.assertEqual(sorted(p.name for p in self.apps.iterdir()), [APP]) + + +if __name__ == "__main__": + unittest.main() From 3ef937a9d8cdcd716536250c93c5771ab0aeb8ac Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 17:46:03 +0100 Subject: [PATCH 24/42] feat(web-app-dashboard): move the tile switch to services.dashboard.display The dashboard read `display` from the role's meta/info.yml, which no inventory can override, so a host could not hide a tile. docker_cards now skips a card when `services.dashboard.display` in the merged applications is false, and absent still means shown; a non-bool value fails loudly. roles_with_service drops the same role from the dashboard tile-reachability targets so the Playwright spec does not wait for a hidden tile, and the inventory validator accepts `services.dashboard.display` for every role that declares `services.dashboard`, since no role default carries it. `display` leaves the meta/info.yml allowlist, web-app-jellyfin drops its redundant `display: true`, and base.md and layout.md document the new switch. Real lookups with web-app-gitea set to display false render the Dashboard and Jellyfin cards and only jellyfin as a tile target, and all three without the override; the nine tests for the new behaviour fail against the old code. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../inventory/validate/applications.py | 11 ++- .../contributing/design/role/services/base.md | 19 ++++ .../design/role/services/layout.md | 16 ++-- plugins/lookup/roles_with_service.py | 12 ++- .../lookup_plugins/docker_cards.py | 26 ++--- roles/web-app-jellyfin/meta/info.yml | 1 - tests/lint/ansible/roles/meta/test_info.py | 16 +--- .../inventory/validate/test_applications.py | 27 ++++++ .../plugins/lookup/test_docker_cards.py | 94 +++++++++++++++++++ .../plugins/lookup/test_roles_with_service.py | 31 ++++++ .../roles/applications/test_dashboard.py | 20 +++- utils/roles/applications/dashboard.py | 32 ++++++- 12 files changed, 269 insertions(+), 36 deletions(-) diff --git a/cli/administration/inventory/validate/applications.py b/cli/administration/inventory/validate/applications.py index 8d3a3d1ed6..f3d6672b0a 100644 --- a/cli/administration/inventory/validate/applications.py +++ b/cli/administration/inventory/validate/applications.py @@ -3,10 +3,13 @@ from __future__ import annotations from utils.manager.credential_key import OVERRIDE_SECTION, SECRETS_KEY +from utils.roles.applications.dashboard import DASHBOARD_SERVICE, DISPLAY_PATH from utils.roles.custom import CUSTOM_KEY, SOURCE_KEY, is_custom from .keys import recursive_keys +_DASHBOARD_PATH = f"services.{DASHBOARD_SERVICE}" + def _declares_custom_role(app_id: str, key: str) -> bool: return is_custom(app_id) and key.split(".", 1)[0] in (CUSTOM_KEY, SOURCE_KEY) @@ -22,7 +25,11 @@ def compare_application_keys(applications, application_defaults, source, variant ``custom`` and ``source`` of a custom role are the inventory's declaration of where the role comes from, not role settings, so no - role default carries them.""" + role default carries them. + + ``services.dashboard.display`` is legal wherever the role contract + declares ``services.dashboard``: absent means shown, so no role + default carries it.""" variants = variants or {} errs: list[str] = [] for app_id, conf in applications.items(): @@ -32,6 +39,8 @@ def compare_application_keys(applications, application_defaults, source, variant legal_keys = recursive_keys(application_defaults[app_id]) for variant in variants.get(app_id, []): legal_keys |= recursive_keys(variant) + if _DASHBOARD_PATH in legal_keys: + legal_keys.add(DISPLAY_PATH) for key in recursive_keys(conf): if key == SECRETS_KEY or key.startswith(OVERRIDE_SECTION): continue diff --git a/docs/contributing/design/role/services/base.md b/docs/contributing/design/role/services/base.md index 1a0acaf229..e9f3351c7b 100644 --- a/docs/contributing/design/role/services/base.md +++ b/docs/contributing/design/role/services/base.md @@ -74,6 +74,25 @@ Rules: - `card:` MUST be a key of the role's `canonical` mapping in `meta/domains.yml`; the card URL is `lookup('canonical_url', , )`. - Without `card:` the card targets the primary domain via `lookup('tls', , 'url.base')`. +## Dashboard Card Display šŸ‘€ + +`display: false` on a consumer's `dashboard` binding drops its dashboard card, its Apps menu entry and its tile-reachability target. +The switch is read from the merged applications, so an inventory MAY set it per host without touching the role: + +```yaml +applications: + web-app-gitea: + services: + dashboard: + display: false +``` + +Rules: + +- `display:` MUST be a bool; any other value fails the card lookup. +- Without `display:` the card is shown, so a role does not declare `display: true`. +- The inventory validator accepts `services.dashboard.display` for every role whose contract declares `services.dashboard`. + ## Service Discovery šŸ” Service discovery is built from role configs, not from a central registry file. diff --git a/docs/contributing/design/role/services/layout.md b/docs/contributing/design/role/services/layout.md index 59df2b1f7b..e24ead744f 100644 --- a/docs/contributing/design/role/services/layout.md +++ b/docs/contributing/design/role/services/layout.md @@ -7,7 +7,7 @@ All role-owned metadata lives under `roles//meta/.yml`. | File | Contents | |--------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------| -| `meta/main.yml` | Ansible Galaxy metadata + Ansible `dependencies:`. No project-internal `run_after:` / `lifecycle:` keys, no `logo:` / `homepage:` / `video:` / `display:`. | +| `meta/main.yml` | Ansible Galaxy metadata + Ansible `dependencies:`. No project-internal `run_after:` / `lifecycle:` keys, no `logo:` / `homepage:` / `video:`. | | `meta/services.yml` | Per-entity service config. **File root IS the services map** keyed by ``. No `compose:` and no `services:` wrapper. | | `meta/server.yml` | CSP, `domains`, `status_codes`, plus per-role `networks.local.{subnet,dns_resolver}`. File root IS `applications..server`. | | `meta/rbac.yml` | RBAC declarations. File root IS `applications..rbac`. | @@ -15,7 +15,7 @@ All role-owned metadata lives under `roles//meta/.yml`. | `meta/addons/.yml` | Optional. One file per addon (file root IS the addon spec; filename stem = addon id). See [Unified Addons](#unified-addons-metaaddons-) below. | | `meta/users.yml` | Role-local user definitions. File root IS the users map (no `users:` wrapper). | | `meta/secrets.yml` | Credential schema definitions and runtime credential values. | -| `meta/info.yml` | Optional. Descriptive role-level metadata (`logo`, `homepage`, `video`, `display`). File root IS `applications..info` (no `info:` wrapper). | +| `meta/info.yml` | Optional. Descriptive role-level metadata (`logo`, `homepage`, `video`). File root IS `applications..info` (no `info:` wrapper). | | `meta/variants.yml` | Optional. Variant overrides deep-merged over the assembled application payload (used by `svc-ai-ollama`, `web-app-phpmyadmin`). | Ansible only auto-loads `meta/main.yml`. @@ -359,7 +359,7 @@ The helper returns `[]` / `None` gracefully when `meta/services.yml` is absent o ## Descriptive Role-Level Metadata: `meta/info.yml` šŸ“ -Project-internal descriptive metadata (icon, upstream homepage, demo video, dashboard display flag) lives in an OPTIONAL `meta/info.yml`, not nested inside `galaxy_info:`. +Project-internal descriptive metadata (icon, upstream homepage, demo video) lives in an OPTIONAL `meta/info.yml`, not nested inside `galaxy_info:`. The file-root convention applies: there is no wrapping `info:` key, and the file content IS `applications..info`. ```yaml @@ -377,23 +377,23 @@ video: https://youtu.be/3jcYJGQgenI?si=FDmoMSrAb9_WvviC | `logo` | map | UI icon descriptor. Today only `class:` (FontAwesome). Future fields (`source:`, `svg:`) require an explicit allowlist update in the lint. | | `homepage` | string | Upstream project URL: the canonical landing page of the software the role deploys. | | `video` | string | Upstream demo / overview video URL. | -| `display` | bool | Default `true`. `false` opts the role out of dashboards / cards / apps grids. | The lint (`tests/lint/ansible/roles/meta/test_info.py`) rejects any other top-level key so the file does not become a dumping ground. +Whether the dashboard shows the role's card is not set here but in `services.dashboard.display`, see [Dashboard Card Display](base.md#dashboard-card-display-). ### Optionality `meta/info.yml` is OPTIONAL. -A role with none of the four fields does not grow the file. -Consumers MUST treat a missing file or missing field as absent / default, and `display` defaults to `true`. +A role with none of the three fields does not grow the file. +Consumers MUST treat a missing file or missing field as absent / default. ### Materialised Path ``` -applications..info.{logo,homepage,video,display} +applications..info.{logo,homepage,video} ``` -The dashboard's `web-app-dashboard/lookup_plugins/docker_cards.py` reads `logo.class` and `display` from this location, while `description` and `galaxy_tags` continue to come from `galaxy_info` (Galaxy-spec fields). +The dashboard's `web-app-dashboard/lookup_plugins/docker_cards.py` reads `logo.class` from this location, while `description` and `galaxy_tags` continue to come from `galaxy_info` (Galaxy-spec fields). ## Unified Addons: `meta/addons/` 🧩 diff --git a/plugins/lookup/roles_with_service.py b/plugins/lookup/roles_with_service.py index 979c2877f0..980af57963 100644 --- a/plugins/lookup/roles_with_service.py +++ b/plugins/lookup/roles_with_service.py @@ -9,7 +9,9 @@ can tell embeddable cards from those that must open in a new tab. For the ``dashboard`` service a role MAY name ``services.dashboard.card: ``; its entry then carries ``domains.canonical.`` and ``lookup('canonical_url', , )`` instead of the primary domain, so -the tile target matches the card ``docker_cards`` renders. +the tile target matches the card ``docker_cards`` renders. A role whose +``services.dashboard.display`` is false renders no card, so it is no tile +target either. A role keeps declaring the service for inventory completeness but can opt out of this consumer-target list by setting @@ -50,7 +52,11 @@ from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase from utils.domains.primary_domain import get_primary_domain -from utils.roles.applications.dashboard import DASHBOARD_SERVICE, card_target_key +from utils.roles.applications.dashboard import ( + DASHBOARD_SERVICE, + card_is_displayed, + card_target_key, +) from utils.roles.applications.mcp import ( DEFAULT_MCP_TRANSPORT, derive_allowed_consumers, @@ -202,6 +208,8 @@ class LookupModule(LookupBase): continue if get_entity_name(str(role_id)) == service_name: continue + if lists_dashboard_cards and not card_is_displayed(str(role_id), block): + continue canonical = _resolve_canonical_domain(str(role_id), app_config) if not canonical and direction is None: continue diff --git a/roles/web-app-dashboard/lookup_plugins/docker_cards.py b/roles/web-app-dashboard/lookup_plugins/docker_cards.py index 5d08d82b0c..2620bf3e8e 100644 --- a/roles/web-app-dashboard/lookup_plugins/docker_cards.py +++ b/roles/web-app-dashboard/lookup_plugins/docker_cards.py @@ -9,7 +9,11 @@ from ansible.plugins.lookup import LookupBase from utils.cache.files import read_text from utils.cache.yaml import load_yaml_any from utils.roles.applications.config import get -from utils.roles.applications.dashboard import DASHBOARD_SERVICE, card_target_key +from utils.roles.applications.dashboard import ( + DASHBOARD_SERVICE, + card_is_displayed, + card_target_key, +) from utils.roles.mapping import ( ROLE_FILE_META_INFO, ROLE_FILE_META_MAIN, @@ -27,7 +31,8 @@ class LookupModule(LookupBase): - Reads the title from the role's README.md (the first H1 line) - Retrieves the description from galaxy_info.description in meta/main.yml - Retrieves the icon class from meta/info.yml.logo.class - - Retrieves the display flag from meta/info.yml.display + - Skips the role when services.dashboard.display in applications + is false - Retrieves the tags from galaxy_info.galaxy_tags - Builds the URL from the primary domain, or from the domains.canonical key named by services.dashboard.card @@ -114,7 +119,14 @@ class LookupModule(LookupBase): except Exception as e: raise AnsibleError(f"Error reading '{info_path}': {e}") from e - if not info_data.get("display", True): + dashboard_cfg = get( + applications, + application_id, + f"services.{DASHBOARD_SERVICE}", + strict=False, + default={}, + ) + if not card_is_displayed(application_id, dashboard_cfg): continue logo = info_data.get("logo") or {} @@ -134,14 +146,6 @@ class LookupModule(LookupBase): self._templar.template(domain_url).strip() if domain_url else "" ) - dashboard_cfg = get( - applications, - application_id, - f"services.{DASHBOARD_SERVICE}", - strict=False, - default={}, - ) - url = "" if domain_url: card_key = card_target_key(application_id, dashboard_cfg) diff --git a/roles/web-app-jellyfin/meta/info.yml b/roles/web-app-jellyfin/meta/info.yml index 6bf73058fe..093292613b 100644 --- a/roles/web-app-jellyfin/meta/info.yml +++ b/roles/web-app-jellyfin/meta/info.yml @@ -3,4 +3,3 @@ logo: class: fa-solid fa-film homepage: https://jellyfin.org/ video: https://www.youtube.com/watch?v=0t3lSJL3B_Q -display: true diff --git a/tests/lint/ansible/roles/meta/test_info.py b/tests/lint/ansible/roles/meta/test_info.py index e574b68e1d..7a9a2a97b1 100644 --- a/tests/lint/ansible/roles/meta/test_info.py +++ b/tests/lint/ansible/roles/meta/test_info.py @@ -6,11 +6,10 @@ with no upstream homepage or demo video to name; * file-root convention: the file's content IS the value of ``applications..info`` — there is NO wrapping ``info:`` key; - * allowed top-level keys: ``logo``, ``homepage``, ``video``, ``display``; + * allowed top-level keys: ``logo``, ``homepage``, ``video``; * ``logo`` is a mapping with at least a string ``class:`` field; * ``homepage`` and ``video`` are non-empty strings; - * ``display`` is a bool; - * none of these four fields may reappear under + * none of these three fields may reappear under ``meta/main.yml.galaxy_info``. Caching: parsed YAML comes through the shared process-wide @@ -35,13 +34,11 @@ if TYPE_CHECKING: ROLES_DIR = PROJECT_ROOT / "roles" -_ALLOWED_INFO_KEYS: frozenset[str] = frozenset({"logo", "homepage", "video", "display"}) +_ALLOWED_INFO_KEYS: frozenset[str] = frozenset({"logo", "homepage", "video"}) _INFO_MEDIA_RULE = "info-media" -_FORBIDDEN_GALAXY_INFO_KEYS: frozenset[str] = frozenset( - {"logo", "homepage", "video", "display"} -) +_FORBIDDEN_GALAXY_INFO_KEYS: frozenset[str] = frozenset({"logo", "homepage", "video"}) def _meta_main_paths() -> list[Path]: @@ -105,9 +102,6 @@ def _validate_meta_info(path: Path) -> list[str]: if not isinstance(value, str) or not value.strip(): problems.append(f"`{str_field}` must be a non-empty string") - if "display" in parsed and not isinstance(parsed["display"], bool): - problems.append("`display` must be a bool (true/false)") - return problems @@ -153,7 +147,7 @@ class TestMetaInfoShape(unittest.TestCase): class TestMetaMainHasNoMigratedFields(unittest.TestCase): - """galaxy_info MUST NOT carry the four fields after.""" + """galaxy_info MUST NOT carry the three meta/info.yml fields.""" def test_no_forbidden_keys_in_galaxy_info(self) -> None: offenders: dict[Path, list[str]] = {} diff --git a/tests/unit/python/cli/administration/inventory/validate/test_applications.py b/tests/unit/python/cli/administration/inventory/validate/test_applications.py index 3f9ed263c2..625357bab1 100644 --- a/tests/unit/python/cli/administration/inventory/validate/test_applications.py +++ b/tests/unit/python/cli/administration/inventory/validate/test_applications.py @@ -105,6 +105,33 @@ class TestCompareApplicationKeys(unittest.TestCase): defaults = {"web-app-cst-demo": {"services": {"port": 8080}}} self.assertEqual(compare_application_keys(apps, defaults, "src"), []) + def test_dashboard_display_is_legal_where_dashboard_is_declared(self): + apps = {"app1": {"services": {"dashboard": {"display": False}}}} + defaults = {"app1": {"services": {"dashboard": {"enabled": False}}}} + self.assertEqual(compare_application_keys(apps, defaults, "src"), []) + + def test_dashboard_display_is_legal_where_a_variant_declares_dashboard(self): + apps = {"app1": {"services": {"dashboard": {"display": False}}}} + defaults = {"app1": {"services": {}}} + variants = {"app1": [{"services": {"dashboard": {"enabled": True}}}]} + self.assertEqual(compare_application_keys(apps, defaults, "src", variants), []) + + def test_dashboard_display_without_a_dashboard_binding_is_flagged(self): + apps = {"app1": {"services": {"dashboard": {"display": False}}}} + defaults = {"app1": {"services": {"port": 8080}}} + result = compare_application_keys(apps, defaults, "src") + self.assertEqual( + sorted(err.rsplit(": ", 1)[1] for err in result), + ["services.dashboard", "services.dashboard.display"], + ) + + def test_other_undeclared_dashboard_keys_stay_flagged(self): + apps = {"app1": {"services": {"dashboard": {"dispaly": False}}}} + defaults = {"app1": {"services": {"dashboard": {"enabled": False}}}} + result = compare_application_keys(apps, defaults, "src") + self.assertEqual(len(result), 1) + self.assertIn("services.dashboard.dispaly", result[0]) + def test_declaration_keys_on_an_in_tree_role_are_flagged(self): apps = {"app1": {"custom": True, "source": {"url": "https://x/y.git"}}} defaults = {"app1": {"services": {}}} diff --git a/tests/unit/python/plugins/lookup/test_docker_cards.py b/tests/unit/python/plugins/lookup/test_docker_cards.py index 5a981df409..d28ee70528 100644 --- a/tests/unit/python/plugins/lookup/test_docker_cards.py +++ b/tests/unit/python/plugins/lookup/test_docker_cards.py @@ -359,6 +359,100 @@ logo: with self.assertRaisesRegex(AnsibleError, "nope"): self._run_lookup(LookupModule(), fake_variables) + def _add_role(self, role_name, application_id, info_yaml): + role_dir = Path(self.test_roles_dir) / role_name + (role_dir / "meta").mkdir(parents=True) + (role_dir / "vars").mkdir(parents=True) + (role_dir / ROLE_FILE_VARS_MAIN).write_text( + f"application_id: {application_id}\n", encoding="utf-8" + ) + (role_dir / "README.md").write_text(f"# {role_name}\n", encoding="utf-8") + (role_dir / ROLE_FILE_META_MAIN).write_text( + 'galaxy_info:\n description: "Second role."\n', encoding="utf-8" + ) + (role_dir / ROLE_FILE_META_INFO).write_text(info_yaml, encoding="utf-8") + + def _two_role_variables(self): + self._add_role("web-app-other", "other", "logo:\n class: fa-solid fa-cube\n") + fake_variables = self._base_fake_variables() + fake_variables["domains"]["other"] = "other.example.com" + fake_variables["applications"]["other"] = { + "services": {"dashboard": {"enabled": True}} + } + fake_variables["group_names"] = ["portfolio", "other"] + return fake_variables + + def test_display_false_skips_the_card(self): + fake_variables = self._base_fake_variables() + fake_variables["applications"]["portfolio"]["services"]["dashboard"][ + "display" + ] = False + + result = self._run_lookup(LookupModule(), fake_variables) + + self.assertEqual(result, [[]]) + + def test_absent_display_shows_the_card(self): + fake_variables = self._base_fake_variables() + self.assertNotIn( + "display", + fake_variables["applications"]["portfolio"]["services"]["dashboard"], + ) + + result = self._run_lookup(LookupModule(), fake_variables) + + self.assertEqual([c["title"] for c in result[0]], ["Portfolio Application"]) + + def test_display_true_shows_the_card(self): + fake_variables = self._base_fake_variables() + fake_variables["applications"]["portfolio"]["services"]["dashboard"][ + "display" + ] = True + + result = self._run_lookup(LookupModule(), fake_variables) + + self.assertEqual([c["title"] for c in result[0]], ["Portfolio Application"]) + + def test_display_false_hides_only_its_own_card(self): + fake_variables = self._two_role_variables() + fake_variables["applications"]["other"]["services"]["dashboard"]["display"] = ( + False + ) + + result = self._run_lookup(LookupModule(), fake_variables) + + self.assertEqual([c["title"] for c in result[0]], ["Portfolio Application"]) + + def test_both_cards_render_without_display(self): + fake_variables = self._two_role_variables() + + result = self._run_lookup(LookupModule(), fake_variables) + + self.assertEqual( + [c["title"] for c in result[0]], + ["Portfolio Application", "web-app-other"], + ) + + def test_info_display_false_no_longer_hides_the_card(self): + meta_info_path = Path(self.role_dir) / ROLE_FILE_META_INFO + meta_info_path.write_text( + "logo:\n class: fa-solid fa-briefcase\ndisplay: false\n", + encoding="utf-8", + ) + + result = self._run_lookup(LookupModule(), self._base_fake_variables()) + + self.assertEqual([c["title"] for c in result[0]], ["Portfolio Application"]) + + def test_non_bool_display_fails_loudly(self): + fake_variables = self._base_fake_variables() + fake_variables["applications"]["portfolio"]["services"]["dashboard"][ + "display" + ] = "false" + + with self.assertRaisesRegex(AnsibleError, "portfolio"): + self._run_lookup(LookupModule(), fake_variables) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_roles_with_service.py b/tests/unit/python/plugins/lookup/test_roles_with_service.py index d75c1fc3c0..c4ac664f07 100644 --- a/tests/unit/python/plugins/lookup/test_roles_with_service.py +++ b/tests/unit/python/plugins/lookup/test_roles_with_service.py @@ -613,6 +613,37 @@ class RolesWithServiceLookupTests(unittest.TestCase): ("matrix.example.com", "https://web-app-chat.example.com"), ) + def test_dashboard_display_false_drops_the_tile_target(self): + applications = { + "web-app-hidden": { + "services": { + "dashboard": {"enabled": True, "shared": True, "display": False} + }, + "domains": {"canonical": ["hidden.example.com"]}, + }, + "web-app-shown": { + "services": {"dashboard": {"enabled": True, "shared": True}}, + "domains": {"canonical": ["shown.example.com"]}, + }, + } + result = self._run(["dashboard"], applications)[0] + self.assertEqual([r["id"] for r in result], ["web-app-shown"]) + + def test_dashboard_display_true_keeps_the_tile_target(self): + applications = self._card_target_role("dashboard", display=True) + result = self._run(["dashboard"], applications)[0] + self.assertEqual([r["id"] for r in result], ["web-app-chat"]) + + def test_dashboard_non_bool_display_fails_loudly(self): + applications = self._card_target_role("dashboard", display="false") + with self.assertRaisesRegex(AnsibleError, "web-app-chat"): + self._run(["dashboard"], applications) + + def test_other_services_ignore_a_display_key(self): + applications = self._card_target_role("prometheus", display=False) + result = self._run(["prometheus"], applications)[0] + self.assertEqual([r["id"] for r in result], ["web-app-chat"]) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/utils/roles/applications/test_dashboard.py b/tests/unit/python/utils/roles/applications/test_dashboard.py index 77a6b601a0..d397ea338f 100644 --- a/tests/unit/python/utils/roles/applications/test_dashboard.py +++ b/tests/unit/python/utils/roles/applications/test_dashboard.py @@ -6,7 +6,7 @@ import unittest from ansible.errors import AnsibleError -from utils.roles.applications.dashboard import card_target_key +from utils.roles.applications.dashboard import card_is_displayed, card_target_key class TestCardTargetKey(unittest.TestCase): @@ -42,5 +42,23 @@ class TestCardTargetKey(unittest.TestCase): card_target_key("web-app-foo", {"card": ["element"]}) +class TestCardIsDisplayed(unittest.TestCase): + def test_a_binding_without_the_key_is_displayed(self): + self.assertTrue(card_is_displayed("web-app-foo", {"enabled": True})) + + def test_a_missing_binding_is_displayed(self): + self.assertTrue(card_is_displayed("web-app-foo", None)) + + def test_display_false_hides_the_card(self): + self.assertFalse(card_is_displayed("web-app-foo", {"display": False})) + + def test_display_true_shows_the_card(self): + self.assertTrue(card_is_displayed("web-app-foo", {"display": True})) + + def test_a_string_flag_fails_loudly(self): + with self.assertRaisesRegex(AnsibleError, "web-app-foo"): + card_is_displayed("web-app-foo", {"display": "false"}) + + if __name__ == "__main__": unittest.main() diff --git a/utils/roles/applications/dashboard.py b/utils/roles/applications/dashboard.py index 403df776e5..a18163d2b0 100644 --- a/utils/roles/applications/dashboard.py +++ b/utils/roles/applications/dashboard.py @@ -1,9 +1,12 @@ -"""Target of an application's dashboard card. +"""Target and visibility of an application's dashboard card. A role's ``services.dashboard`` binding MAY name ``card: ``, a key of its ``domains.canonical`` mapping. The card, the Apps menu entry and the dashboard tile-reachability target then point at that domain instead of the role's primary domain. + +``display: false`` on the same binding drops the card, the Apps menu entry and +the tile-reachability target. """ from __future__ import annotations @@ -14,6 +17,33 @@ from ansible.errors import AnsibleError DASHBOARD_SERVICE = "dashboard" CARD_TARGET_KEY = "card" +DISPLAY_KEY = "display" +DISPLAY_PATH = f"services.{DASHBOARD_SERVICE}.{DISPLAY_KEY}" + + +def card_is_displayed(application_id: str, dashboard: Any) -> bool: + """Return whether the application's dashboard card is shown. + + Args: + application_id: the role whose binding is read, named in the error. + dashboard: the role's ``services.dashboard`` binding from the merged + applications. + + Returns: + The ``display`` flag, or ``True`` when the binding sets none. + + Raises: + AnsibleError: the binding sets ``display`` to something other than a + bool. + """ + if not isinstance(dashboard, dict) or DISPLAY_KEY not in dashboard: + return True + display = dashboard[DISPLAY_KEY] + if not isinstance(display, bool): + raise AnsibleError( + f"{application_id}: {DISPLAY_PATH} must be a bool, got {display!r}" + ) + return display def card_target_key(application_id: str, dashboard: Any) -> str: From ae7f2bbcb2e7fc352a019bf127ae2109f164b398 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 17:56:13 +0100 Subject: [PATCH 25/42] fix(web-app-nextcloud): pin the Talk HPB to AIO stamp 20260409_094910 Docker Hub froze nextcloud/aio-talk:latest at 20250325_084656, so the high-performance backend kept running signaling 2.0.2 and Talk reported chat-relay as missing. AIO publishes only build stamps now. 20260409_094910 is the newest one that ships signaling 2.1.1 and still starts Janus with /usr/local/etc/janus/janus.jcfg; from 2026-04-17 on, AIO generates /conf/janus.jcfg and rewrites the nat block, which the role's Janus guard rejects, and stamps before 20260218 still carry signaling 2.0.x. aio-talk-recording moves to the same stamp. The stamp ships Janus 1.4.0, which dropped nice_debug, so janus.jcfg.j2 is re-derived from the image and the role's janus_config_drift filter returns no drift on the digest-checked image files again. min_storage follows the measured image sizes plus 200MB. changed-users stays missing until upstream releases it. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-nextcloud/meta/services.yml | 12 ++++++------ roles/web-app-nextcloud/templates/janus.jcfg.j2 | 1 - 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/roles/web-app-nextcloud/meta/services.yml b/roles/web-app-nextcloud/meta/services.yml index 5fd355f302..0336be4564 100644 --- a/roles/web-app-nextcloud/meta/services.yml +++ b/roles/web-app-nextcloud/meta/services.yml @@ -202,8 +202,8 @@ talk: shared: "{{ 'web-svc-coturn' in group_names }}" name: nextcloud-talk image: nextcloud/aio-talk - # nocheck: docker-version -- all 174 tags upstream publishes are AIO build stamps, none is a version - version: latest + # nocheck: docker-version -- upstream publishes only AIO build stamps and froze latest at 20250325_084656; later stamps start Janus from a generated /conf/janus.jcfg that the janus_conf mount cannot replace + version: "20260409_094910" backup: no_stop_required: false turn_server: @@ -220,7 +220,7 @@ talk: mem_reservation: 1g mem_limit: 2g pids_limit: 1024 - min_storage: 274MB + min_storage: 279MB ports: internal: signaling: 8081 @@ -287,15 +287,15 @@ talk_recording: shared: false name: nextcloud-talk-recording image: nextcloud/aio-talk-recording - # nocheck: docker-version -- all 104 tags upstream publishes are AIO build stamps, none is a version - version: latest + # nocheck: docker-version -- upstream publishes only AIO build stamps and froze latest at 20250325_084656; stays on the AIO release of services.talk.version + version: "20260409_094910" backup: no_stop_required: true cpus: "2.0" mem_reservation: 1g mem_limit: 3g pids_limit: 1024 - min_storage: 507MB + min_storage: 993MB ports: internal: recording: 1234 diff --git a/roles/web-app-nextcloud/templates/janus.jcfg.j2 b/roles/web-app-nextcloud/templates/janus.jcfg.j2 index 983506ab06..65019cf2ef 100644 --- a/roles/web-app-nextcloud/templates/janus.jcfg.j2 +++ b/roles/web-app-nextcloud/templates/janus.jcfg.j2 @@ -38,7 +38,6 @@ media: { } nat: { - nice_debug = false nat_1_1_mapping = "{{ NEXTCLOUD_HPB_MEDIA_PUBLIC_IP }}" keep_private_host = true ice_ignore_list = "vmnet" From c855efc30a4bb1eeb29780a9c5b3cc2d7e85e82f Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 19:00:46 +0100 Subject: [PATCH 26/42] refactor(web-app-dashboard): hide a tile through services.dashboard.enabled instead of display services.dashboard.enabled already says whether a role takes part in the dashboard: roles_with_service lists only roles with enabled and shared as tile-reachability targets, the CSP filter adds the dashboard to frame-ancestors only when it is set, and docker_cards uses it as the card's iframe flag. A separate display key duplicated that switch and left a role with enabled false still rendering a card. docker_cards now skips the card when services.dashboard.enabled is false (a role without a dashboard binding keeps its card, and a value that is not a boolean fails loudly), so display, its validator exception and its roles_with_service filter go again; base.md documents enabled as the per-host switch. An inventory hides a tile with applications..services.dashboard.enabled: false, which also drops the dashboard framing of that role. Unit tests cover false, true, a missing binding, a rendered string and a non-boolean; forcing the helper to always show the card fails four of them. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../inventory/validate/applications.py | 11 +------ .../contributing/design/role/services/base.md | 11 +++---- .../design/role/services/layout.md | 2 +- plugins/lookup/roles_with_service.py | 12 ++----- .../lookup_plugins/docker_cards.py | 2 +- .../inventory/validate/test_applications.py | 27 ---------------- .../plugins/lookup/test_docker_cards.py | 28 +++++++---------- .../plugins/lookup/test_roles_with_service.py | 31 ------------------- .../roles/applications/test_dashboard.py | 17 +++++----- utils/roles/applications/dashboard.py | 30 ++++++++++-------- 10 files changed, 48 insertions(+), 123 deletions(-) diff --git a/cli/administration/inventory/validate/applications.py b/cli/administration/inventory/validate/applications.py index f3d6672b0a..8d3a3d1ed6 100644 --- a/cli/administration/inventory/validate/applications.py +++ b/cli/administration/inventory/validate/applications.py @@ -3,13 +3,10 @@ from __future__ import annotations from utils.manager.credential_key import OVERRIDE_SECTION, SECRETS_KEY -from utils.roles.applications.dashboard import DASHBOARD_SERVICE, DISPLAY_PATH from utils.roles.custom import CUSTOM_KEY, SOURCE_KEY, is_custom from .keys import recursive_keys -_DASHBOARD_PATH = f"services.{DASHBOARD_SERVICE}" - def _declares_custom_role(app_id: str, key: str) -> bool: return is_custom(app_id) and key.split(".", 1)[0] in (CUSTOM_KEY, SOURCE_KEY) @@ -25,11 +22,7 @@ def compare_application_keys(applications, application_defaults, source, variant ``custom`` and ``source`` of a custom role are the inventory's declaration of where the role comes from, not role settings, so no - role default carries them. - - ``services.dashboard.display`` is legal wherever the role contract - declares ``services.dashboard``: absent means shown, so no role - default carries it.""" + role default carries them.""" variants = variants or {} errs: list[str] = [] for app_id, conf in applications.items(): @@ -39,8 +32,6 @@ def compare_application_keys(applications, application_defaults, source, variant legal_keys = recursive_keys(application_defaults[app_id]) for variant in variants.get(app_id, []): legal_keys |= recursive_keys(variant) - if _DASHBOARD_PATH in legal_keys: - legal_keys.add(DISPLAY_PATH) for key in recursive_keys(conf): if key == SECRETS_KEY or key.startswith(OVERRIDE_SECTION): continue diff --git a/docs/contributing/design/role/services/base.md b/docs/contributing/design/role/services/base.md index e9f3351c7b..037f65dd4c 100644 --- a/docs/contributing/design/role/services/base.md +++ b/docs/contributing/design/role/services/base.md @@ -76,22 +76,21 @@ Rules: ## Dashboard Card Display šŸ‘€ -`display: false` on a consumer's `dashboard` binding drops its dashboard card, its Apps menu entry and its tile-reachability target. -The switch is read from the merged applications, so an inventory MAY set it per host without touching the role: +`enabled: false` on a consumer's `dashboard` binding takes the role out of the dashboard: no card, no Apps menu entry, no tile-reachability target and no dashboard origin in its CSP `frame-ancestors`. +The flag is read from the merged applications, so an inventory MAY set it per host without touching the role: ```yaml applications: web-app-gitea: services: dashboard: - display: false + enabled: false ``` Rules: -- `display:` MUST be a bool; any other value fails the card lookup. -- Without `display:` the card is shown, so a role does not declare `display: true`. -- The inventory validator accepts `services.dashboard.display` for every role whose contract declares `services.dashboard`. +- `enabled:` MUST render to a boolean; any other value fails the card lookup. +- A `web-app-*` role without a `dashboard` binding still gets a card. ## Service Discovery šŸ” diff --git a/docs/contributing/design/role/services/layout.md b/docs/contributing/design/role/services/layout.md index e24ead744f..2305c63c54 100644 --- a/docs/contributing/design/role/services/layout.md +++ b/docs/contributing/design/role/services/layout.md @@ -379,7 +379,7 @@ video: https://youtu.be/3jcYJGQgenI?si=FDmoMSrAb9_WvviC | `video` | string | Upstream demo / overview video URL. | The lint (`tests/lint/ansible/roles/meta/test_info.py`) rejects any other top-level key so the file does not become a dumping ground. -Whether the dashboard shows the role's card is not set here but in `services.dashboard.display`, see [Dashboard Card Display](base.md#dashboard-card-display-). +Whether the dashboard shows the role's card is not set here but in `services.dashboard.enabled`, see [Dashboard Card Display](base.md#dashboard-card-display-). ### Optionality diff --git a/plugins/lookup/roles_with_service.py b/plugins/lookup/roles_with_service.py index 980af57963..979c2877f0 100644 --- a/plugins/lookup/roles_with_service.py +++ b/plugins/lookup/roles_with_service.py @@ -9,9 +9,7 @@ can tell embeddable cards from those that must open in a new tab. For the ``dashboard`` service a role MAY name ``services.dashboard.card: ``; its entry then carries ``domains.canonical.`` and ``lookup('canonical_url', , )`` instead of the primary domain, so -the tile target matches the card ``docker_cards`` renders. A role whose -``services.dashboard.display`` is false renders no card, so it is no tile -target either. +the tile target matches the card ``docker_cards`` renders. A role keeps declaring the service for inventory completeness but can opt out of this consumer-target list by setting @@ -52,11 +50,7 @@ from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase from utils.domains.primary_domain import get_primary_domain -from utils.roles.applications.dashboard import ( - DASHBOARD_SERVICE, - card_is_displayed, - card_target_key, -) +from utils.roles.applications.dashboard import DASHBOARD_SERVICE, card_target_key from utils.roles.applications.mcp import ( DEFAULT_MCP_TRANSPORT, derive_allowed_consumers, @@ -208,8 +202,6 @@ class LookupModule(LookupBase): continue if get_entity_name(str(role_id)) == service_name: continue - if lists_dashboard_cards and not card_is_displayed(str(role_id), block): - continue canonical = _resolve_canonical_domain(str(role_id), app_config) if not canonical and direction is None: continue diff --git a/roles/web-app-dashboard/lookup_plugins/docker_cards.py b/roles/web-app-dashboard/lookup_plugins/docker_cards.py index 2620bf3e8e..a0d9a83d36 100644 --- a/roles/web-app-dashboard/lookup_plugins/docker_cards.py +++ b/roles/web-app-dashboard/lookup_plugins/docker_cards.py @@ -31,7 +31,7 @@ class LookupModule(LookupBase): - Reads the title from the role's README.md (the first H1 line) - Retrieves the description from galaxy_info.description in meta/main.yml - Retrieves the icon class from meta/info.yml.logo.class - - Skips the role when services.dashboard.display in applications + - Skips the role when services.dashboard.enabled in applications is false - Retrieves the tags from galaxy_info.galaxy_tags - Builds the URL from the primary domain, or from the domains.canonical diff --git a/tests/unit/python/cli/administration/inventory/validate/test_applications.py b/tests/unit/python/cli/administration/inventory/validate/test_applications.py index 625357bab1..3f9ed263c2 100644 --- a/tests/unit/python/cli/administration/inventory/validate/test_applications.py +++ b/tests/unit/python/cli/administration/inventory/validate/test_applications.py @@ -105,33 +105,6 @@ class TestCompareApplicationKeys(unittest.TestCase): defaults = {"web-app-cst-demo": {"services": {"port": 8080}}} self.assertEqual(compare_application_keys(apps, defaults, "src"), []) - def test_dashboard_display_is_legal_where_dashboard_is_declared(self): - apps = {"app1": {"services": {"dashboard": {"display": False}}}} - defaults = {"app1": {"services": {"dashboard": {"enabled": False}}}} - self.assertEqual(compare_application_keys(apps, defaults, "src"), []) - - def test_dashboard_display_is_legal_where_a_variant_declares_dashboard(self): - apps = {"app1": {"services": {"dashboard": {"display": False}}}} - defaults = {"app1": {"services": {}}} - variants = {"app1": [{"services": {"dashboard": {"enabled": True}}}]} - self.assertEqual(compare_application_keys(apps, defaults, "src", variants), []) - - def test_dashboard_display_without_a_dashboard_binding_is_flagged(self): - apps = {"app1": {"services": {"dashboard": {"display": False}}}} - defaults = {"app1": {"services": {"port": 8080}}} - result = compare_application_keys(apps, defaults, "src") - self.assertEqual( - sorted(err.rsplit(": ", 1)[1] for err in result), - ["services.dashboard", "services.dashboard.display"], - ) - - def test_other_undeclared_dashboard_keys_stay_flagged(self): - apps = {"app1": {"services": {"dashboard": {"dispaly": False}}}} - defaults = {"app1": {"services": {"dashboard": {"enabled": False}}}} - result = compare_application_keys(apps, defaults, "src") - self.assertEqual(len(result), 1) - self.assertIn("services.dashboard.dispaly", result[0]) - def test_declaration_keys_on_an_in_tree_role_are_flagged(self): apps = {"app1": {"custom": True, "source": {"url": "https://x/y.git"}}} defaults = {"app1": {"services": {}}} diff --git a/tests/unit/python/plugins/lookup/test_docker_cards.py b/tests/unit/python/plugins/lookup/test_docker_cards.py index d28ee70528..f6620d8695 100644 --- a/tests/unit/python/plugins/lookup/test_docker_cards.py +++ b/tests/unit/python/plugins/lookup/test_docker_cards.py @@ -382,40 +382,34 @@ logo: fake_variables["group_names"] = ["portfolio", "other"] return fake_variables - def test_display_false_skips_the_card(self): + def test_enabled_false_skips_the_card(self): fake_variables = self._base_fake_variables() fake_variables["applications"]["portfolio"]["services"]["dashboard"][ - "display" + "enabled" ] = False result = self._run_lookup(LookupModule(), fake_variables) self.assertEqual(result, [[]]) - def test_absent_display_shows_the_card(self): + def test_a_role_without_a_dashboard_binding_shows_the_card(self): fake_variables = self._base_fake_variables() - self.assertNotIn( - "display", - fake_variables["applications"]["portfolio"]["services"]["dashboard"], - ) + fake_variables["applications"]["portfolio"]["services"] = {} result = self._run_lookup(LookupModule(), fake_variables) self.assertEqual([c["title"] for c in result[0]], ["Portfolio Application"]) - def test_display_true_shows_the_card(self): + def test_enabled_true_shows_the_card(self): fake_variables = self._base_fake_variables() - fake_variables["applications"]["portfolio"]["services"]["dashboard"][ - "display" - ] = True result = self._run_lookup(LookupModule(), fake_variables) self.assertEqual([c["title"] for c in result[0]], ["Portfolio Application"]) - def test_display_false_hides_only_its_own_card(self): + def test_enabled_false_hides_only_its_own_card(self): fake_variables = self._two_role_variables() - fake_variables["applications"]["other"]["services"]["dashboard"]["display"] = ( + fake_variables["applications"]["other"]["services"]["dashboard"]["enabled"] = ( False ) @@ -423,7 +417,7 @@ logo: self.assertEqual([c["title"] for c in result[0]], ["Portfolio Application"]) - def test_both_cards_render_without_display(self): + def test_both_cards_render_when_both_are_enabled(self): fake_variables = self._two_role_variables() result = self._run_lookup(LookupModule(), fake_variables) @@ -444,11 +438,11 @@ logo: self.assertEqual([c["title"] for c in result[0]], ["Portfolio Application"]) - def test_non_bool_display_fails_loudly(self): + def test_non_boolean_enabled_fails_loudly(self): fake_variables = self._base_fake_variables() fake_variables["applications"]["portfolio"]["services"]["dashboard"][ - "display" - ] = "false" + "enabled" + ] = "maybe" with self.assertRaisesRegex(AnsibleError, "portfolio"): self._run_lookup(LookupModule(), fake_variables) diff --git a/tests/unit/python/plugins/lookup/test_roles_with_service.py b/tests/unit/python/plugins/lookup/test_roles_with_service.py index c4ac664f07..d75c1fc3c0 100644 --- a/tests/unit/python/plugins/lookup/test_roles_with_service.py +++ b/tests/unit/python/plugins/lookup/test_roles_with_service.py @@ -613,37 +613,6 @@ class RolesWithServiceLookupTests(unittest.TestCase): ("matrix.example.com", "https://web-app-chat.example.com"), ) - def test_dashboard_display_false_drops_the_tile_target(self): - applications = { - "web-app-hidden": { - "services": { - "dashboard": {"enabled": True, "shared": True, "display": False} - }, - "domains": {"canonical": ["hidden.example.com"]}, - }, - "web-app-shown": { - "services": {"dashboard": {"enabled": True, "shared": True}}, - "domains": {"canonical": ["shown.example.com"]}, - }, - } - result = self._run(["dashboard"], applications)[0] - self.assertEqual([r["id"] for r in result], ["web-app-shown"]) - - def test_dashboard_display_true_keeps_the_tile_target(self): - applications = self._card_target_role("dashboard", display=True) - result = self._run(["dashboard"], applications)[0] - self.assertEqual([r["id"] for r in result], ["web-app-chat"]) - - def test_dashboard_non_bool_display_fails_loudly(self): - applications = self._card_target_role("dashboard", display="false") - with self.assertRaisesRegex(AnsibleError, "web-app-chat"): - self._run(["dashboard"], applications) - - def test_other_services_ignore_a_display_key(self): - applications = self._card_target_role("prometheus", display=False) - result = self._run(["prometheus"], applications)[0] - self.assertEqual([r["id"] for r in result], ["web-app-chat"]) - if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/utils/roles/applications/test_dashboard.py b/tests/unit/python/utils/roles/applications/test_dashboard.py index d397ea338f..4b5d942040 100644 --- a/tests/unit/python/utils/roles/applications/test_dashboard.py +++ b/tests/unit/python/utils/roles/applications/test_dashboard.py @@ -44,20 +44,23 @@ class TestCardTargetKey(unittest.TestCase): class TestCardIsDisplayed(unittest.TestCase): def test_a_binding_without_the_key_is_displayed(self): - self.assertTrue(card_is_displayed("web-app-foo", {"enabled": True})) + self.assertTrue(card_is_displayed("web-app-foo", {"shared": True})) def test_a_missing_binding_is_displayed(self): self.assertTrue(card_is_displayed("web-app-foo", None)) - def test_display_false_hides_the_card(self): - self.assertFalse(card_is_displayed("web-app-foo", {"display": False})) + def test_enabled_false_hides_the_card(self): + self.assertFalse(card_is_displayed("web-app-foo", {"enabled": False})) - def test_display_true_shows_the_card(self): - self.assertTrue(card_is_displayed("web-app-foo", {"display": True})) + def test_enabled_true_shows_the_card(self): + self.assertTrue(card_is_displayed("web-app-foo", {"enabled": True})) - def test_a_string_flag_fails_loudly(self): + def test_a_rendered_string_flag_is_read_as_a_boolean(self): + self.assertFalse(card_is_displayed("web-app-foo", {"enabled": "False"})) + + def test_a_non_boolean_flag_fails_loudly(self): with self.assertRaisesRegex(AnsibleError, "web-app-foo"): - card_is_displayed("web-app-foo", {"display": "false"}) + card_is_displayed("web-app-foo", {"enabled": "maybe"}) if __name__ == "__main__": diff --git a/utils/roles/applications/dashboard.py b/utils/roles/applications/dashboard.py index a18163d2b0..a2e31b01d8 100644 --- a/utils/roles/applications/dashboard.py +++ b/utils/roles/applications/dashboard.py @@ -5,8 +5,9 @@ A role's ``services.dashboard`` binding MAY name ``card: ``, a key of its tile-reachability target then point at that domain instead of the role's primary domain. -``display: false`` on the same binding drops the card, the Apps menu entry and -the tile-reachability target. +``enabled: false`` on the same binding takes the application out of the +dashboard: no card and no Apps menu entry, and the tile-reachability targets +and the CSP frame-ancestors already follow the same flag. """ from __future__ import annotations @@ -14,11 +15,12 @@ from __future__ import annotations from typing import Any from ansible.errors import AnsibleError +from ansible.module_utils.parsing.convert_bool import boolean DASHBOARD_SERVICE = "dashboard" CARD_TARGET_KEY = "card" -DISPLAY_KEY = "display" -DISPLAY_PATH = f"services.{DASHBOARD_SERVICE}.{DISPLAY_KEY}" +ENABLED_KEY = "enabled" +ENABLED_PATH = f"services.{DASHBOARD_SERVICE}.{ENABLED_KEY}" def card_is_displayed(application_id: str, dashboard: Any) -> bool: @@ -30,20 +32,22 @@ def card_is_displayed(application_id: str, dashboard: Any) -> bool: applications. Returns: - The ``display`` flag, or ``True`` when the binding sets none. + The ``enabled`` flag, or ``True`` when the role declares no binding or + the binding sets none. Raises: - AnsibleError: the binding sets ``display`` to something other than a - bool. + AnsibleError: the binding sets ``enabled`` to something that is not a + boolean. """ - if not isinstance(dashboard, dict) or DISPLAY_KEY not in dashboard: + if not isinstance(dashboard, dict) or ENABLED_KEY not in dashboard: return True - display = dashboard[DISPLAY_KEY] - if not isinstance(display, bool): + enabled = dashboard[ENABLED_KEY] + try: + return boolean(enabled, strict=True) + except TypeError as exc: raise AnsibleError( - f"{application_id}: {DISPLAY_PATH} must be a bool, got {display!r}" - ) - return display + f"{application_id}: {ENABLED_PATH} must be a boolean, got {enabled!r}" + ) from exc def card_target_key(application_id: str, dashboard: Any) -> str: From efd72474a6ff6c8adbd3ef3fb9c7239859a26274 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 20:16:22 +0100 Subject: [PATCH 27/42] feat(networks): extend the local http port band to 8107 PORT_BANDS.local.http (8001-8099) has no free port left: `cli contributing network ports suggest --scope local --category http --count 2` reports 0 free, so the custom web-app-cst-store role cannot take a host-bound port without colliding with web-app-hermes (8092) and web-app-openbao (8093). 8100-8107 are free as host-bound ports (web-app-bluesky uses 8100 only as an internal container port) and 8108 starts the typesense band, so the band now ends at 8107, the highest port that stays clear of it. Co-Authored-By: Claude Opus 5.5 (1M context) --- group_vars/all/08_networks.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/group_vars/all/08_networks.yml b/group_vars/all/08_networks.yml index 8dcadeb7f0..5ee7fde6eb 100644 --- a/group_vars/all/08_networks.yml +++ b/group_vars/all/08_networks.yml @@ -37,7 +37,7 @@ PORT_BANDS: # nocheck: unused-var # consumed by the port-allocation plugin outs local: http: start: 8001 - end: 8099 + end: 8107 agent: start: 8500 end: 8599 From 1e31913d93fc98360c5329ac6e90fccbf6d1f30c Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 20:19:56 +0100 Subject: [PATCH 28/42] fix(web-app-nextcloud): read the OpenProject coupling on the stack host In swarm, 02_manager_ops.yml applies `delegate_to: NEXTCLOUD_HOST_NODE` to the plugin setup, so the OpenProject state tasks run on the node that hosts the Nextcloud container. The database_query against OpenProject's database resolves its container through lookup('database'), which only answers on a swarm manager and falls back to the bare name `postgres` elsewhere. CI run 40877408319 (Nextcloud#3) failed on that with "No such container: postgres" on web-app-nextcloud-swarm-wrk-02. The query now runs on STACK_HOST. In compose STACK_HOST is the inventory host, so nothing changes there. A probe playbook confirms that a task's own delegate_to overrides the include's `apply: delegate_to` while its sibling tasks keep the applied delegation. The line matches store-i18n's 8a1f48953e. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../tasks/addons/integration_openproject_state.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/roles/web-app-nextcloud/tasks/addons/integration_openproject_state.yml b/roles/web-app-nextcloud/tasks/addons/integration_openproject_state.yml index fe34d08cc9..14185d10e5 100644 --- a/roles/web-app-nextcloud/tasks/addons/integration_openproject_state.yml +++ b/roles/web-app-nextcloud/tasks/addons/integration_openproject_state.yml @@ -36,6 +36,7 @@ delay: 5 changed_when: false no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + delegate_to: "{{ STACK_HOST }}" when: IS_STACK_HOST | bool - name: 🧮 Digest the provisioning sources, inputs and coupling state From a7b1e04edec502b3a5f6f82196bcb677947fd9a2 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 20:26:36 +0100 Subject: [PATCH 29/42] refactor(web-app-nextcloud): build the Nextcloud and Whiteboard images from plain Dockerfiles templates/Dockerfile.j2 and templates/Dockerfiles/Whiteboard.j2 become files/Dockerfile and files/Dockerfiles/Whiteboard/Dockerfile. Their Jinja values arrive as ARGs without defaults from the compose build args: image and version for both, plus NEXTCLOUD_ONLYOFFICE_ENABLED and NEXTCLOUD_INIT_GATE_FILE for Nextcloud. The OnlyOffice block turns into a case on the ARG that fails the build on anything but true or false, and the init gate keeps its in-image path /usr/local/bin/init-gate.sh, because an exec-form ENTRYPOINT cannot expand an ARG. sys-svc-compose already deploys files/Dockerfile into the instance directory, so the main image needs no task of its own. The Whiteboard Dockerfile is copied instead of rendered and builds from its own service directory; it copies nothing from the context, so the narrower context changes nothing it reads. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-nextcloud/files/Dockerfile | 16 ++++++++++++++++ .../Dockerfiles/Whiteboard/Dockerfile} | 4 +++- roles/web-app-nextcloud/tasks/01_fullstack.yml | 4 ++-- roles/web-app-nextcloud/templates/Dockerfile.j2 | 9 --------- roles/web-app-nextcloud/templates/compose.yml.j2 | 12 ++++++++++-- 5 files changed, 31 insertions(+), 14 deletions(-) create mode 100644 roles/web-app-nextcloud/files/Dockerfile rename roles/web-app-nextcloud/{templates/Dockerfiles/Whiteboard.j2 => files/Dockerfiles/Whiteboard/Dockerfile} (82%) delete mode 100644 roles/web-app-nextcloud/templates/Dockerfile.j2 diff --git a/roles/web-app-nextcloud/files/Dockerfile b/roles/web-app-nextcloud/files/Dockerfile new file mode 100644 index 0000000000..b5a360fbff --- /dev/null +++ b/roles/web-app-nextcloud/files/Dockerfile @@ -0,0 +1,16 @@ +ARG NEXTCLOUD_IMAGE +ARG NEXTCLOUD_VERSION +FROM ${NEXTCLOUD_IMAGE}:${NEXTCLOUD_VERSION} +ARG NEXTCLOUD_ONLYOFFICE_ENABLED +ARG NEXTCLOUD_INIT_GATE_FILE + +RUN case "${NEXTCLOUD_ONLYOFFICE_ENABLED}" in \ + true) apk add --no-cache ca-certificates && update-ca-certificates ;; \ + false) ;; \ + *) echo "NEXTCLOUD_ONLYOFFICE_ENABLED must be true or false, got '${NEXTCLOUD_ONLYOFFICE_ENABLED}'" >&2; exit 1 ;; \ + esac + +COPY ${NEXTCLOUD_INIT_GATE_FILE} /usr/local/bin/init-gate.sh +RUN chmod 0755 /usr/local/bin/init-gate.sh +ENTRYPOINT ["/usr/local/bin/init-gate.sh"] +CMD ["php-fpm"] diff --git a/roles/web-app-nextcloud/templates/Dockerfiles/Whiteboard.j2 b/roles/web-app-nextcloud/files/Dockerfiles/Whiteboard/Dockerfile similarity index 82% rename from roles/web-app-nextcloud/templates/Dockerfiles/Whiteboard.j2 rename to roles/web-app-nextcloud/files/Dockerfiles/Whiteboard/Dockerfile index ec05bc4b40..cc95fa0c51 100644 --- a/roles/web-app-nextcloud/templates/Dockerfiles/Whiteboard.j2 +++ b/roles/web-app-nextcloud/files/Dockerfiles/Whiteboard/Dockerfile @@ -1,4 +1,6 @@ -FROM {{ NEXTCLOUD_WHITEBOARD_IMAGE }}:{{ NEXTCLOUD_WHITEBOARD_VERSION }} +ARG WHITEBOARD_IMAGE +ARG WHITEBOARD_VERSION +FROM ${WHITEBOARD_IMAGE}:${WHITEBOARD_VERSION} USER 0 diff --git a/roles/web-app-nextcloud/tasks/01_fullstack.yml b/roles/web-app-nextcloud/tasks/01_fullstack.yml index 26fba72a2d..9c3107de5f 100644 --- a/roles/web-app-nextcloud/tasks/01_fullstack.yml +++ b/roles/web-app-nextcloud/tasks/01_fullstack.yml @@ -73,8 +73,8 @@ mode: "0755" - name: "šŸ“„ Deploy Whiteboard Dockerfile to {{ NEXTCLOUD_WHITEBOARD_SERVICE_DOCKERFILE }}" - stack_host_template: - src: "Dockerfiles/Whiteboard.j2" + stack_host_copy: + src: "Dockerfiles/Whiteboard/Dockerfile" dest: "{{ NEXTCLOUD_WHITEBOARD_SERVICE_DOCKERFILE }}" notify: - compose-build diff --git a/roles/web-app-nextcloud/templates/Dockerfile.j2 b/roles/web-app-nextcloud/templates/Dockerfile.j2 deleted file mode 100644 index 62bf81e348..0000000000 --- a/roles/web-app-nextcloud/templates/Dockerfile.j2 +++ /dev/null @@ -1,9 +0,0 @@ -FROM {{ NEXTCLOUD_IMAGE }}:{{ NEXTCLOUD_VERSION }} -{% if NEXTCLOUD_ONLYOFFICE_ENABLED | bool %} -RUN apk add --no-cache ca-certificates && update-ca-certificates -{% endif %} - -COPY {{ NEXTCLOUD_INIT_GATE_FILE }} /usr/local/bin/{{ NEXTCLOUD_INIT_GATE_FILE }} -RUN chmod 0755 /usr/local/bin/{{ NEXTCLOUD_INIT_GATE_FILE }} -ENTRYPOINT ["/usr/local/bin/{{ NEXTCLOUD_INIT_GATE_FILE }}"] -CMD ["php-fpm"] diff --git a/roles/web-app-nextcloud/templates/compose.yml.j2 b/roles/web-app-nextcloud/templates/compose.yml.j2 index efa411aa9b..789ea62e3e 100644 --- a/roles/web-app-nextcloud/templates/compose.yml.j2 +++ b/roles/web-app-nextcloud/templates/compose.yml.j2 @@ -21,6 +21,11 @@ {{ lookup('container_image', application_id, 'nextcloud') }} {{ lookup('compose_only', 'container_name', NEXTCLOUD_CONTAINER) }} {{ lookup('template', 'roles/sys-svc-container/templates/build.yml.j2') | indent(4) }} + args: + NEXTCLOUD_IMAGE: "{{ NEXTCLOUD_IMAGE }}" + NEXTCLOUD_VERSION: "{{ NEXTCLOUD_VERSION }}" + NEXTCLOUD_ONLYOFFICE_ENABLED: "{{ NEXTCLOUD_ONLYOFFICE_ENABLED | bool | lower }}" + NEXTCLOUD_INIT_GATE_FILE: "{{ NEXTCLOUD_INIT_GATE_FILE }}" {{ lookup('container_volumes', service_name) | indent(4) }} environment: @@ -112,8 +117,11 @@ {{ service_name }}: {% include 'roles/sys-svc-container/templates/base.yml.j2' %} build: - context: . - dockerfile: {{ NEXTCLOUD_WHITEBOARD_SERVICE_DOCKERFILE }} + context: {{ NEXTCLOUD_WHITEBOARD_SERVICE_DIRECTORY }} + dockerfile: Dockerfile + args: + WHITEBOARD_IMAGE: "{{ NEXTCLOUD_WHITEBOARD_IMAGE }}" + WHITEBOARD_VERSION: "{{ NEXTCLOUD_WHITEBOARD_VERSION }}" {{ lookup('compose_only', 'pull_policy', 'never') }} {{ lookup('container_image', application_id, 'whiteboard') }} {{ lookup('container_healthcheck', service_name) | indent(4) }} From 8d4c03b863ea062e9aadd036101217b5cfbd77ad Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Thu, 29 Oct 2026 20:43:06 +0000 Subject: [PATCH 30/42] update(repos): bump git refs to latest semver tags (pkgmgr) --- roles/pkgmgr/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/pkgmgr/meta/services.yml b/roles/pkgmgr/meta/services.yml index 079f44d0e8..ea3a8c7739 100644 --- a/roles/pkgmgr/meta/services.yml +++ b/roles/pkgmgr/meta/services.yml @@ -3,4 +3,4 @@ pkgmgr: lifecycle: beta repository: https://github.com/kevinveenbirkenbach/package-manager.git - ref: v2.0.4 + ref: v2.0.5 From 2517b20f15fee0f07fff9b6e08a0e4a389d2d565 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Thu, 29 Oct 2026 20:43:11 +0000 Subject: [PATCH 31/42] update(repos): bump git refs to latest semver tags (web-app-bookwyrm) --- roles/web-app-bookwyrm/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-bookwyrm/meta/services.yml b/roles/web-app-bookwyrm/meta/services.yml index fcee76585f..544d79cf7c 100644 --- a/roles/web-app-bookwyrm/meta/services.yml +++ b/roles/web-app-bookwyrm/meta/services.yml @@ -62,7 +62,7 @@ bookwyrm: version: 3.11-slim custom: true repository: https://github.com/bookwyrm-social/bookwyrm.git - ref: v0.9.3 + ref: v0.9.4 min_storage: 579MB registration_open: false allow_invite_request: false From f557e3973ad5fb5602325e0d937121033af89d37 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 21:55:25 +0100 Subject: [PATCH 32/42] fix(web-app-nextcloud): keep app_api enabled while the context agent runs 8d767239e3 tied the app_api addon to mcp.enabled, but the MCP provisioning registers the Context Agent ExApp whenever services.context_agent.enabled is true. An inventory that enables the context agent directly, as the generated development inventory does, left mcp.enabled false: the plugin step disabled app_api, and the registration then died on `occ app_api:daemon:list` with "There are no commands defined in the app_api:daemon namespace". app_api now follows services.context_agent.enabled, the same switch as the provisioning. Without an override that switch still resolves to mcp.enabled, so inventories that set neither key keep their state. A render against the live development inventory gives app_api true where it gave false before. The addon also gets the empty tasks hook the service-coupled addon lint asks for. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-nextcloud/README.md | 2 +- roles/web-app-nextcloud/files/playwright/addons/app_api.spec.js | 2 +- roles/web-app-nextcloud/meta/addons/app_api.yml | 2 +- roles/web-app-nextcloud/tasks/addons/app_api.yml | 1 + 4 files changed, 4 insertions(+), 3 deletions(-) create mode 100644 roles/web-app-nextcloud/tasks/addons/app_api.yml diff --git a/roles/web-app-nextcloud/README.md b/roles/web-app-nextcloud/README.md index e6933744f2..7125a4e23c 100644 --- a/roles/web-app-nextcloud/README.md +++ b/roles/web-app-nextcloud/README.md @@ -190,7 +190,7 @@ The enable-only appstore apps stay under `nextcloud.plugins` in [`meta/services. | `spreed` | `plugin` | enabled with the `talk` service | `talk`, `coturn` | | `whiteboard` | `plugin` | `required` (always installed) | none (self-hosted backend) | | `xwiki` | `plugin` | enabled with the `xwiki` partner | `xwiki` → `web-app-xwiki` | -| `app_api` | `plugin` | enabled while `mcp.enabled` is true, disabled otherwise | none | +| `app_api` | `plugin` | enabled while `services.context_agent.enabled` is true (it follows `mcp.enabled` unless the inventory sets it), disabled otherwise | none | | `logreader` | `plugin` | disabled, `log_type` is `errorlog` | none | The SSO (`sociallogin`) and LDAP (`user_ldap`) login surfaces are covered by the OIDC/LDAP Playwright specs (requirements 017/018). diff --git a/roles/web-app-nextcloud/files/playwright/addons/app_api.spec.js b/roles/web-app-nextcloud/files/playwright/addons/app_api.spec.js index 5682a8c912..cc812f76cc 100644 --- a/roles/web-app-nextcloud/files/playwright/addons/app_api.spec.js +++ b/roles/web-app-nextcloud/files/playwright/addons/app_api.spec.js @@ -32,7 +32,7 @@ test("app_api addon: the AppAPI app is enabled for the logged-in user", async ({ }); expect( appApiEnabled, - "app_api must be listed in OC.appswebroots, which Nextcloud fills with the enabled apps only: the MCP surface proxies through AppAPI, so the role keeps it enabled while mcp.enabled is true", + "app_api must be listed in OC.appswebroots, which Nextcloud fills with the enabled apps only: the MCP surface proxies through AppAPI, so the role keeps it enabled while the context_agent service runs", ).toBe(true); } finally { await page.close().catch(() => {}); diff --git a/roles/web-app-nextcloud/meta/addons/app_api.yml b/roles/web-app-nextcloud/meta/addons/app_api.yml index 38ec085ecc..a3bfb12408 100644 --- a/roles/web-app-nextcloud/meta/addons/app_api.yml +++ b/roles/web-app-nextcloud/meta/addons/app_api.yml @@ -1,5 +1,5 @@ --- -enabled: "{{ lookup('config', 'web-app-nextcloud', 'mcp.enabled') | bool }}" +enabled: "{{ lookup('config', 'web-app-nextcloud', 'services.context_agent.enabled') | bool }}" required: false mechanism: plugin source: upstream diff --git a/roles/web-app-nextcloud/tasks/addons/app_api.yml b/roles/web-app-nextcloud/tasks/addons/app_api.yml new file mode 100644 index 0000000000..ed97d539c0 --- /dev/null +++ b/roles/web-app-nextcloud/tasks/addons/app_api.yml @@ -0,0 +1 @@ +--- From 6d44e1e28ac9f838dbb4ff1c63a1d65cc818d198 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 22:10:45 +0100 Subject: [PATCH 33/42] fix(ci): check the PR head against the main it was tested with The Validation step "Assert the base branch is fully merged into the PR head" ran main_merged.sh, which fetches the live tip of main when the job starts. PR runs wait in the queue for hours while image-update PRs land on main several times an hour, so nearly every queued run failed Validation on start and had to be re-pushed after another main merge (PR #1265: behind_by=0 at push, behind_by=9 while its run still queued). main_merged.sh takes a new INFINITO_MAIN_COMMIT override: when set, it fetches that full commit SHA from the remote and requires HEAD to contain it instead of the live tip; a set but malformed or empty value exits 2. The Validation step passes github.event.pull_request.base.sha, the main tip at event time, which the step's pull_request-only guard always provides. The run tests the merge against that base, so the gate still guarantees the tested tree contains it. The local pre-push hook (make test-main-merged) leaves the override unset and keeps checking the live tip: a push happens right now, so lagging the current main is the real defect there. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/call-validation.yml | 3 +- scripts/git/assert/main_merged.sh | 24 +++- tests/unit/python/scripts/git/__init__.py | 0 .../python/scripts/git/assert/__init__.py | 0 .../scripts/git/assert/test_main_merged.py | 134 ++++++++++++++++++ 5 files changed, 155 insertions(+), 6 deletions(-) create mode 100644 tests/unit/python/scripts/git/__init__.py create mode 100644 tests/unit/python/scripts/git/assert/__init__.py create mode 100644 tests/unit/python/scripts/git/assert/test_main_merged.py diff --git a/.github/workflows/call-validation.yml b/.github/workflows/call-validation.yml index 05e395339b..79155629e2 100644 --- a/.github/workflows/call-validation.yml +++ b/.github/workflows/call-validation.yml @@ -109,12 +109,13 @@ jobs: PR_SCOPE: ${{ inputs.pr_scope }} run: ./scripts/meta/resolve/pr/branch_prefix.sh - - name: šŸ”€ Assert the base branch is fully merged into the PR head + - name: šŸ”€ Assert the event's base commit is merged into the PR head if: ${{ github.event_name == 'pull_request' && inputs.pr_scope != '' }} working-directory: pr-head env: INFINITO_MAIN_REMOTE: origin INFINITO_MAIN_BRANCH: ${{ github.event.pull_request.base.ref }} + INFINITO_MAIN_COMMIT: ${{ github.event.pull_request.base.sha }} run: bash "${GITHUB_WORKSPACE}/.base-tooling/scripts/git/assert/main_merged.sh" - name: šŸ”§ Set up Python diff --git a/scripts/git/assert/main_merged.sh b/scripts/git/assert/main_merged.sh index bb63e43b46..ac7471884d 100755 --- a/scripts/git/assert/main_merged.sh +++ b/scripts/git/assert/main_merged.sh @@ -4,23 +4,37 @@ # from the current tip, so a branch can never be pushed while it lags main. # # Env overrides: INFINITO_MAIN_REMOTE (default origin), INFINITO_MAIN_BRANCH -# (default main). +# (default main), INFINITO_MAIN_COMMIT (unset: check the live branch tip; set: +# fetch and check this full commit SHA of that branch instead, e.g. the base +# SHA a CI event carries). set -euo pipefail remote="${INFINITO_MAIN_REMOTE:-origin}" # nocheck: git maintainer tooling knob, not a deployment env key branch="${INFINITO_MAIN_BRANCH:-main}" # nocheck: git maintainer tooling knob, not a deployment env key +if [[ -v INFINITO_MAIN_COMMIT ]]; then + target="${INFINITO_MAIN_COMMIT}" # nocheck: git maintainer tooling knob, not a deployment env key + if [[ ! "$target" =~ ^[0-9a-f]{40}([0-9a-f]{24})?$ ]]; then + echo "āŒ assert-main-merged: INFINITO_MAIN_COMMIT must be a full commit SHA, got '${target}'." >&2 + exit 2 + fi + label="${remote}/${branch}@${target}" +else + target="$branch" + label="${remote}/${branch}" +fi + cd "$(git rev-parse --show-toplevel)" -echo "assert-main-merged: fetching ${remote}/${branch} ..." >&2 -git fetch --quiet "$remote" "$branch" +echo "assert-main-merged: fetching ${label} ..." >&2 +git fetch --quiet "$remote" "$target" if git merge-base --is-ancestor FETCH_HEAD HEAD; then - echo "āœ… assert-main-merged: ${remote}/${branch} is fully merged into HEAD." >&2 + echo "āœ… assert-main-merged: ${label} is fully merged into HEAD." >&2 exit 0 fi behind="$(git rev-list --count HEAD..FETCH_HEAD)" -echo "āŒ assert-main-merged: ${remote}/${branch} has ${behind} commit(s) not merged into HEAD." >&2 +echo "āŒ assert-main-merged: ${label} has ${behind} commit(s) not merged into HEAD." >&2 echo " Merge upstream main first, e.g.: git pull ${remote} ${branch}" >&2 exit 1 diff --git a/tests/unit/python/scripts/git/__init__.py b/tests/unit/python/scripts/git/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/scripts/git/assert/__init__.py b/tests/unit/python/scripts/git/assert/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/scripts/git/assert/test_main_merged.py b/tests/unit/python/scripts/git/assert/test_main_merged.py new file mode 100644 index 0000000000..5a41470cb1 --- /dev/null +++ b/tests/unit/python/scripts/git/assert/test_main_merged.py @@ -0,0 +1,134 @@ +from __future__ import annotations + +import os +import subprocess +import tempfile +import unittest +from pathlib import Path + +from utils.cache.files import PROJECT_ROOT + +SCRIPT = PROJECT_ROOT / "scripts" / "git" / "assert" / "main_merged.sh" +MAIN_COMMIT_ENV = "INFINITO_MAIN_COMMIT" # nocheck: git maintainer tooling knob, not a deployment env key + + +class MainMergedFixture: + """A bare ``origin`` whose ``main`` moved on after ``head`` branched off it. + + Args: + tmp: directory that holds the bare remote and its two clones. + """ + + def __init__(self, tmp: str) -> None: + root = Path(tmp) + inherited = { + k: v + for k, v in os.environ.items() + if not k.startswith(("GIT_", "INFINITO_")) + } + self.env = { + **inherited, + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_AUTHOR_NAME": "test", + "GIT_AUTHOR_EMAIL": "test@example.invalid", + "GIT_COMMITTER_NAME": "test", + "GIT_COMMITTER_EMAIL": "test@example.invalid", + } + origin = root / "origin.git" + maintainer = root / "maintainer" + self.head = root / "head" + self.git(root, "init", "--bare", "-b", "main", str(origin)) + self.git(root, "init", "-b", "main", str(maintainer)) + self.git(maintainer, "remote", "add", "origin", str(origin)) + self.base = self.commit(maintainer, "base") + self.git(maintainer, "push", "origin", "main") + self.git(root, "clone", str(origin), str(self.head)) + self.git(self.head, "switch", "-c", "feature") + self.commit(self.head, "feature") + self.main_tip = self.commit(maintainer, "main moved on") + self.git(maintainer, "push", "origin", "main") + + def git(self, cwd: Path, *args: str) -> str: + return subprocess.run( + ["git", *args], + cwd=cwd, + env=self.env, + capture_output=True, + text=True, + check=True, + ).stdout.strip() + + def commit(self, repo: Path, message: str) -> str: + self.git(repo, "commit", "--allow-empty", "-m", message) + return self.git(repo, "rev-parse", "HEAD") + + def merge_main(self) -> None: + self.git(self.head, "pull", "--no-rebase", "--no-edit", "origin", "main") + + def run_script(self, main_commit: str | None) -> subprocess.CompletedProcess: + """Run the script in ``head``. + + Args: + main_commit: value of the main-commit override; ``None`` leaves it unset. + """ + env = dict(self.env) + if main_commit is not None: + env[MAIN_COMMIT_ENV] = main_commit + return subprocess.run( + ["bash", str(SCRIPT)], + cwd=self.head, + env=env, + capture_output=True, + text=True, + check=False, + ) + + +class TestMainMergedPinnedCommit(unittest.TestCase): + def test_contained_commit_passes_after_main_moved_on(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + fixture = MainMergedFixture(tmp) + result = fixture.run_script(fixture.base) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn(f"origin/main@{fixture.base} is fully merged", result.stderr) + + def test_commit_missing_from_head_fails(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + fixture = MainMergedFixture(tmp) + result = fixture.run_script(fixture.main_tip) + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn( + f"origin/main@{fixture.main_tip} has 1 commit(s) not merged into HEAD", + result.stderr, + ) + + def test_empty_commit_fails_loudly(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + fixture = MainMergedFixture(tmp) + result = fixture.run_script("") + self.assertEqual(result.returncode, 2, result.stderr) + self.assertIn("must be a full commit SHA", result.stderr) + + +class TestMainMergedLiveTip(unittest.TestCase): + def test_live_tip_missing_from_head_fails(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + fixture = MainMergedFixture(tmp) + result = fixture.run_script(None) + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn( + "origin/main has 1 commit(s) not merged into HEAD", result.stderr + ) + + def test_merged_live_tip_passes(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + fixture = MainMergedFixture(tmp) + fixture.merge_main() + result = fixture.run_script(None) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("origin/main is fully merged into HEAD", result.stderr) + + +if __name__ == "__main__": + unittest.main() From 7a3f27fc6392fa0aee473c505de42b9df8837146 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 22:10:46 +0100 Subject: [PATCH 34/42] style(lint): apply ruff format to the worktree swarm lab subnet lint tests/lint/filesystem/env/test_worktree_swarm_lab_subnet.py landed on main with lines ruff format wraps, so every `make autoformat` rewrites it and leaves an unstaged change behind. Formatter output only. Co-Authored-By: Claude Opus 5.5 --- .../filesystem/env/test_worktree_swarm_lab_subnet.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/tests/lint/filesystem/env/test_worktree_swarm_lab_subnet.py b/tests/lint/filesystem/env/test_worktree_swarm_lab_subnet.py index 16c42ed62b..7395b5f012 100644 --- a/tests/lint/filesystem/env/test_worktree_swarm_lab_subnet.py +++ b/tests/lint/filesystem/env/test_worktree_swarm_lab_subnet.py @@ -71,10 +71,16 @@ class TestWorktreeSwarmLabSubnet(unittest.TestCase): with self.subTest(slot=slot): subnet = self._subnet(slot) clashes = sorted( - name for name, network in self.reserved.items() if subnet.overlaps(network) + name + for name, network in self.reserved.items() + if subnet.overlaps(network) + ) + self.assertEqual( + clashes, [], f"slot {slot} lab {subnet} overlaps {clashes}" + ) + self.assertNotIn( + subnet, seen, f"slot {slot} repeats slot {seen.get(subnet)}" ) - self.assertEqual(clashes, [], f"slot {slot} lab {subnet} overlaps {clashes}") - self.assertNotIn(subnet, seen, f"slot {slot} repeats slot {seen.get(subnet)}") seen[subnet] = slot From ded61d53ee14bb5f19d738a00ab79583beddb915 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 22:55:45 +0100 Subject: [PATCH 35/42] fix(cache): leave tracked files deleted in the worktree out of repository_files repository_files() listed every path `git ls-files` returns, including tracked files the worktree has already deleted. Every content scan that reads the listing then reported "[Errno 2] No such file or directory" as a finding: in a worktree that removed roles/web-app-nextcloud/filter_plugins/nextcloud_janus.py and its test but had not committed the removal yet, test_no_rsync_backup_flag failed on exactly those two paths and turned the whole lint target red. No scan can read such a file until the deletion is committed. The listing now subtracts `git ls-files --deleted`. A clean checkout, as in CI, has no deleted entries, so the listing there is unchanged. The rsync lint is green again on the same worktree. The unit tests stub the extra git call and cover a file deleted in the worktree. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../python/tests/test_untracked_files_in_scope.py | 2 ++ tests/unit/python/utils/cache/test_files.py | 14 ++++++++++---- utils/cache/files.py | 8 ++++---- 3 files changed, 16 insertions(+), 8 deletions(-) diff --git a/tests/unit/python/tests/test_untracked_files_in_scope.py b/tests/unit/python/tests/test_untracked_files_in_scope.py index ef85777c49..661e576ebb 100644 --- a/tests/unit/python/tests/test_untracked_files_in_scope.py +++ b/tests/unit/python/tests/test_untracked_files_in_scope.py @@ -43,6 +43,8 @@ class _ListingFixture: def git(self, tracked: bytes | Exception, untracked: bytes | Exception): def run(args, **_kwargs): + if "--deleted" in args: + return SimpleNamespace(stdout=b"") listing = untracked if "--others" in args else tracked if isinstance(listing, Exception): raise listing diff --git a/tests/unit/python/utils/cache/test_files.py b/tests/unit/python/utils/cache/test_files.py index 76b2eab7e8..08851cd066 100644 --- a/tests/unit/python/utils/cache/test_files.py +++ b/tests/unit/python/utils/cache/test_files.py @@ -194,7 +194,7 @@ class TestRepositoryFiles(_ProjectRootFixture, unittest.TestCase): _touch(self.root / self.TRACKED, "- y") _touch(self.root / self.CUSTOM, "- x") _touch(self.root / "roles/web-app-cst-demo/__pycache__/x.pyc", "") - with self._git(f"{self.TRACKED}\0".encode()): + with self._git(f"{self.TRACKED}\0".encode(), b""): self.assertEqual( (self.CUSTOM, self.TRACKED), files_module.repository_files(), @@ -203,18 +203,24 @@ class TestRepositoryFiles(_ProjectRootFixture, unittest.TestCase): def test_lists_only_the_tracked_files_without_placed_custom_roles(self) -> None: _touch(self.root / self.TRACKED, "- y") _touch(self.root / "build/install.stamp", "") - with self._git(f"{self.TRACKED}\0".encode()): + with self._git(f"{self.TRACKED}\0".encode(), b""): self.assertEqual((self.TRACKED,), files_module.repository_files()) + def test_leaves_out_a_tracked_file_deleted_in_the_worktree(self) -> None: + gone = "roles/web-app-nextcloud/filter_plugins/gone.py" + with self._git(f"{self.TRACKED}\0{gone}\0".encode(), f"{gone}\0".encode()) as run: + self.assertEqual((self.TRACKED,), files_module.repository_files()) + self.assertEqual(["--deleted"], run.call_args_list[1].args[0][-1:]) + def test_untracked_adds_the_files_gitignore_does_not_exclude(self) -> None: - with self._git(f"{self.TRACKED}\0".encode(), b"new.py\0") as run: + with self._git(f"{self.TRACKED}\0".encode(), b"", b"new.py\0") as run: self.assertEqual( ("new.py", self.TRACKED), files_module.repository_files(untracked=True), ) self.assertEqual( ["--others", "--exclude-standard"], - run.call_args_list[1].args[0][-2:], + run.call_args_list[2].args[0][-2:], ) def test_a_git_failure_propagates(self) -> None: diff --git a/utils/cache/files.py b/utils/cache/files.py index 68a2d2c497..4b54edcddb 100644 --- a/utils/cache/files.py +++ b/utils/cache/files.py @@ -203,9 +203,9 @@ def iter_non_ignored_files( def repository_files(*, untracked: bool = False) -> tuple[str, ...]: """Repository-relative POSIX paths of every file ``git ls-files`` lists. - Git ignores the custom roles an inventory pulls into ``roles/``, yet - every scan checks them like in-tree roles, so their files are listed - as well. + A tracked file deleted in the worktree is left out. Git ignores the custom + roles an inventory pulls into ``roles/``, yet every scan checks them like + in-tree roles, so their files are listed as well. Args: untracked: also list the untracked files ``.gitignore`` does not exclude. @@ -215,7 +215,7 @@ def repository_files(*, untracked: bool = False) -> tuple[str, ...]: subprocess.CalledProcessError: git cannot list the files. """ root = str(PROJECT_ROOT) - rels = _git_files() + rels = _git_files() - _git_files("--deleted") if untracked: rels.update(untracked_files()) rels.update( From 16975a1e14461864a7d486f99c6b53efc797acb9 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 23:07:39 +0100 Subject: [PATCH 36/42] perf(sys-svc-container): publish ports through the kernel instead of a docker-proxy per port With the userland proxy on, Docker starts one docker-proxy process for every published port. A published range pays that per port: Janus's direct-media range showed 74 proxies for 64 UDP ports plus the other published ports in the development stack, at about 1.7 MB unique memory (PSS) each, which projects to roughly 1.7 GB for the default 1000-port range and the same again for OpenTalk's. daemon.json now sets "userland-proxy": false, so iptables/nftables forwards every published port, which the CIS Docker Benchmark (2.16) also asks for. Traffic from outside already took that path, so client addresses are unchanged. Host-local traffic to ports published on 127.0.0.1 now runs through route_localnet and the loopback DNAT Docker installs. From Docker 28.0 on, Docker keeps hosts on the same L2 segment off those loopback ports; every install path of this role ships 29.x. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../templates/daemon.json.j2 | 1 + .../sys-svc-container/test_userland_proxy.py | 61 +++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 tests/unit/python/roles/sys-svc-container/test_userland_proxy.py diff --git a/roles/sys-svc-container/templates/daemon.json.j2 b/roles/sys-svc-container/templates/daemon.json.j2 index 5fcda85fe7..761c0ea560 100644 --- a/roles/sys-svc-container/templates/daemon.json.j2 +++ b/roles/sys-svc-container/templates/daemon.json.j2 @@ -19,6 +19,7 @@ "dns-search": ["{{ DOMAIN_PRIMARY }}"], "dns-opts": ["ndots:0"], "default-address-pools": {{ NETWORK_DOCKER_ADDRESS_POOLS | tojson }}, + "userland-proxy": false, "log-driver": "json-file", "log-opts": {"max-size": "10m", "max-file": "2"} {% if DOCKER_IN_CONTAINER | bool %}, diff --git a/tests/unit/python/roles/sys-svc-container/test_userland_proxy.py b/tests/unit/python/roles/sys-svc-container/test_userland_proxy.py new file mode 100644 index 0000000000..463c7bdbe9 --- /dev/null +++ b/tests/unit/python/roles/sys-svc-container/test_userland_proxy.py @@ -0,0 +1,61 @@ +import json +import unittest +from pathlib import Path +from types import SimpleNamespace + +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape + +from utils import PROJECT_ROOT + +TEMPLATES = Path(PROJECT_ROOT) / "roles" / "sys-svc-container" / "templates" + + +def _shim(exists): + return SimpleNamespace(stat=SimpleNamespace(exists=exists)) + + +def _daemon_json(**overrides): + env = Environment( + loader=FileSystemLoader(str(TEMPLATES)), + trim_blocks=True, + undefined=StrictUndefined, + autoescape=select_autoescape(), + ) + env.filters["bool"] = lambda value: value is True or str(value).lower() == "true" + env.filters["to_json"] = json.dumps + env.globals["lookup"] = lambda name, *_a, **_k: [] + variables = { + "DEPLOYMENT_MODE": "compose", + "IS_STACK_HOST": True, + "DOCKER_IN_CONTAINER": False, + "DOMAIN_PRIMARY": "infinito.test", + "KATA_SHIM_BINARY": "/usr/bin/containerd-shim-kata-v2", + "RUNSC_SHIM_BINARY": "/usr/local/bin/runsc", + "SANDBOX_RUNTIME": "runsc", + "SYS_SVC_CONTAINER_DATA_ROOT": "", + "swarm": {"registry": {"host": "", "port": 5000}}, + "groups": {"svc-registry-cache": []}, + "ansible_facts": {"os_family": "Debian"}, + "SYS_SVC_CONTAINER_DOCKER_FIREWALL_BACKEND_BY_OS_FAMILY": {"Debian": "iptables"}, + "NETWORK_DOCKER_ADDRESS_POOLS": [{"base": "10.208.0.0/12", "size": 24}], + "sys_svc_container_kvm": _shim(False), + "sys_svc_container_kata_shim": _shim(False), + "sys_svc_container_runsc_shim": _shim(False), + **overrides, + } + return json.loads(env.get_template("daemon.json.j2").render(variables)) + + +class TestUserlandProxy(unittest.TestCase): + def test_the_daemon_publishes_ports_without_the_userland_proxy(self): + self.assertIs(_daemon_json()["userland-proxy"], False) + + def test_swarm_and_docker_in_docker_keep_it_off(self): + parsed = _daemon_json( + DEPLOYMENT_MODE="swarm", IS_STACK_HOST=False, DOCKER_IN_CONTAINER=True + ) + self.assertIs(parsed["userland-proxy"], False) + + +if __name__ == "__main__": + unittest.main() From 4a14a49da9d4f67e174f7ce20f9c4b234cbfcad7 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 23:37:29 +0100 Subject: [PATCH 37/42] fix(web-app-nextcloud): decide Talk direct media in the role and keep it opt-in services.talk.direct_media was an expression in meta/services.yml that read ansible_facts['all_ipv4_addresses'] and nested config lookups. lookup('config') renders it where the applications are merged without host facts; the render fails there, the lookup hands back the raw expression and `| bool` coerces it to False with a deprecation warning. Direct media therefore never switched on: both the first requirement-061 deploy and CI run 40877408319 logged the coercion, and a render in the development container returned the raw string without facts and true with them. meta/services.yml keeps only the inventory switch, now `direct_media: false`, so every Talk stream goes through web-svc-coturn unless an operator opts a host in. That is the behaviour the bug produced everywhere, so no host changes on deploy, and it keeps Janus off the public network by default. vars/main.yml decides in task context from the switch, Talk, standalone TURN, the bridged network, compose mode and NEXTCLOUD_HPB_HOST_ADDRESSES, which reads the facts the way web-svc-coturn does. The flag tests render that chain against the merged applications: off by default, on for an opted-in compose host with coturn and an owned address, off for host networking, a foreign or loopback address, swarm, onboard TURN and missing facts. Administration.md documents the opt-in. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../web-app-nextcloud/docs/Administration.md | 2 +- roles/web-app-nextcloud/meta/services.yml | 7 +- roles/web-app-nextcloud/vars/main.yml | 10 ++- .../test_talk_direct_media.py | 77 +++++++++++++++---- 4 files changed, 74 insertions(+), 22 deletions(-) diff --git a/roles/web-app-nextcloud/docs/Administration.md b/roles/web-app-nextcloud/docs/Administration.md index 61e65dd23e..020ab86bea 100644 --- a/roles/web-app-nextcloud/docs/Administration.md +++ b/roles/web-app-nextcloud/docs/Administration.md @@ -34,7 +34,7 @@ Check these admin URLs after deployment: ## Talk media -With `services.talk.direct_media` true, the Janus media server inside the `talk` container announces `networks.internet.ip4` and publishes `services.talk.ports.public.relay` (UDP, default 61000-61999) on that address, so clients send their media to Janus directly and only fall back to `web-svc-coturn` when UDP to that range is blocked. The flag is on in compose mode with a bridged `talk` service that uses `web-svc-coturn` for TURN, and only while `networks.internet.ip4` is an address of the host itself. Set it to `false` in the inventory to send every stream through TURN again. +By default every Talk stream goes through `web-svc-coturn`, and the `talk` container publishes no media port. Set `services.talk.direct_media` to `true` in the inventory to let clients send their media to the Janus media server inside the `talk` container directly: Janus then announces `networks.internet.ip4` and publishes `services.talk.ports.public.relay` (UDP, default 61000-61999) on that address, and clients fall back to `web-svc-coturn` only when UDP to that range is blocked. The setting takes effect in compose mode with a bridged `talk` service that uses `web-svc-coturn` for TURN, and only while `networks.internet.ip4` is an address of the host itself. Open the range for UDP in any firewall in front of the host. Each participant of a call holds one peer connection per participant, so all calls together get at most as many peer connections as the range has ports, and a call of N participants needs N² of them. Janus refuses a new peer connection once the range is used up. Docker starts one `docker-proxy` process per published port. diff --git a/roles/web-app-nextcloud/meta/services.yml b/roles/web-app-nextcloud/meta/services.yml index 0336be4564..57c7f03b91 100644 --- a/roles/web-app-nextcloud/meta/services.yml +++ b/roles/web-app-nextcloud/meta/services.yml @@ -210,12 +210,7 @@ talk: onboard_enabled: "{{ not ( 'web-svc-coturn' in group_names ) }}" standalone_enabled: "{{ 'web-svc-coturn' in group_names }}" network_mode: bridge - direct_media: >- - {{ (lookup('config', 'web-app-nextcloud', 'services.talk.enabled') | bool) - and (lookup('config', 'web-app-nextcloud', 'services.talk.turn_server.standalone_enabled') | bool) - and (lookup('config', 'web-app-nextcloud', 'services.talk.network_mode') == 'bridge') - and (DEPLOYMENT_MODE == 'compose') - and (networks.internet.ip4 in ansible_facts['all_ipv4_addresses']) }} + direct_media: false cpus: "2.0" mem_reservation: 1g mem_limit: 2g diff --git a/roles/web-app-nextcloud/vars/main.yml b/roles/web-app-nextcloud/vars/main.yml index e480248c67..f20054cbb1 100644 --- a/roles/web-app-nextcloud/vars/main.yml +++ b/roles/web-app-nextcloud/vars/main.yml @@ -158,7 +158,15 @@ NEXTCLOUD_HPB_PLUGIN_ENABLED: "{{ lookup('config', application_id, 'addons.spree NEXTCLOUD_HPB_INTERNAL_SECRET: "{{ lookup('config', application_id, 'secrets.credentials.talk_internal_secret') }}" NEXTCLOUD_HPB_DOMAIN: "{{ NEXTCLOUD_DOMAIN }}" -NEXTCLOUD_HPB_MEDIA_DIRECT: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.direct_media') | bool }}" +# nocheck: host-local-fact read only in compose mode, where the host rendering this file is the host Janus publishes its media ports on; Ansible omits the key on a host without the ip binary, which leaves the media on TURN +NEXTCLOUD_HPB_HOST_ADDRESSES: "{{ ansible_facts['all_ipv4_addresses'] | default([]) }}" +NEXTCLOUD_HPB_MEDIA_DIRECT: >- + {{ (lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.direct_media') | bool) + and (NEXTCLOUD_HPB_SIGNALING_ENABLED | bool) + and (NEXTCLOUD_HPB_TURN_STANDALONE_ENABLED | bool) + and (lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.network_mode') == 'bridge') + and (DEPLOYMENT_MODE == 'compose') + and (networks.internet.ip4 in NEXTCLOUD_HPB_HOST_ADDRESSES) }} NEXTCLOUD_HPB_MEDIA_PUBLIC_IP: "{{ networks.internet.ip4 }}" NEXTCLOUD_HPB_MEDIA_PORT_START: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.ports.public.relay.start') }}" NEXTCLOUD_HPB_MEDIA_PORT_END: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.ports.public.relay.end') }}" diff --git a/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py b/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py index 40eaa4c4c3..e16d9d6e7d 100644 --- a/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py +++ b/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py @@ -18,7 +18,11 @@ from plugins.lookup.container_volumes import container_volumes from utils.cache import _reset_cache_for_tests from utils.cache.files import PROJECT_ROOT, read_text from utils.cache.yaml import load_yaml_any -from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_TEMPL_COMPOSE +from utils.roles.mapping import ( + ROLE_FILE_META_SERVICES, + ROLE_FILE_TEMPL_COMPOSE, + ROLE_FILE_VARS_MAIN, +) ROLE = "roles/web-app-nextcloud" TEMPLATE = f"{ROLE}/{ROLE_FILE_TEMPL_COMPOSE}" @@ -236,49 +240,94 @@ class TestTalkComposeBlock(unittest.TestCase): self.assertNotEqual(_talk_block(rendered), _legacy(cell)) -def _direct_media(group_names, *, mode="compose", ip4=PUBLIC_IP, applications=None): - from ansible.parsing.dataloader import DataLoader - from ansible.template import Templar +ROLE_VARS = load_yaml_any(str(PROJECT_ROOT / ROLE / ROLE_FILE_VARS_MAIN)) +DIRECT_MEDIA_CHAIN = ( + "NEXTCLOUD_HPB_PLUGIN_ENABLED", + "NEXTCLOUD_HPB_SIGNALING_ENABLED", + "NEXTCLOUD_HPB_TURN_STANDALONE_ENABLED", + "NEXTCLOUD_HPB_HOST_ADDRESSES", +) - from utils.cache.applications import get_merged_applications + +def _direct_media( + group_names, *, mode="compose", ip4=PUBLIC_IP, applications=None, facts=True +): + from ansible.parsing.dataloader import DataLoader + from ansible.template import Templar, trust_as_template variables = { "group_names": group_names, "applications": applications or {}, + "application_id": "web-app-nextcloud", + "NEXTCLOUD_HPB_SERVICE": "talk", "DEPLOYMENT_MODE": mode, "networks": {"internet": {"ip4": ip4, "ip6": "::1"}}, - "ansible_facts": {"all_ipv4_addresses": [PUBLIC_IP, "10.208.0.1"]}, + **{name: trust_as_template(ROLE_VARS[name]) for name in DIRECT_MEDIA_CHAIN}, } + if facts: + variables["ansible_facts"] = {"all_ipv4_addresses": [PUBLIC_IP, "10.208.0.1"]} templar = Templar(loader=DataLoader(), variables=dict(variables)) templar.available_variables = dict(variables) _reset_cache_for_tests() try: - merged = get_merged_applications(variables=variables, templar=templar) + return templar.template( + trust_as_template(ROLE_VARS["NEXTCLOUD_HPB_MEDIA_DIRECT"]) + ) finally: _reset_cache_for_tests() - return merged["web-app-nextcloud"]["services"]["talk"]["direct_media"] STANDALONE_TURN = ("web-app-nextcloud", "web-svc-coturn") +def _talk(**talk): + return {"web-app-nextcloud": {"services": {"talk": talk}}} + + +OPTED_IN = _talk(direct_media=True) + + class TestDirectMediaFlag(unittest.TestCase): - def test_compose_with_standalone_turn_and_an_owned_address_turns_it_on(self): - self.assertIs(_direct_media(list(STANDALONE_TURN)), True) + def test_by_default_every_stream_goes_through_turn(self): + self.assertIs(_direct_media(list(STANDALONE_TURN)), False) + + def test_opting_in_with_standalone_turn_and_an_owned_address_turns_it_on(self): + self.assertIs(_direct_media(list(STANDALONE_TURN), applications=OPTED_IN), True) + + def test_host_networking_keeps_it_off(self): + host = _talk(direct_media=True, network_mode="host") + self.assertIs(_direct_media(list(STANDALONE_TURN), applications=host), False) def test_an_address_the_host_does_not_own_keeps_it_off(self): - self.assertIs(_direct_media(list(STANDALONE_TURN), ip4="198.51.100.9"), False) + self.assertIs( + _direct_media( + list(STANDALONE_TURN), ip4="198.51.100.9", applications=OPTED_IN + ), + False, + ) def test_the_loopback_placeholder_keeps_it_off(self): - self.assertIs(_direct_media(list(STANDALONE_TURN), ip4="127.0.0.1"), False) + self.assertIs( + _direct_media(list(STANDALONE_TURN), ip4="127.0.0.1", applications=OPTED_IN), + False, + ) def test_swarm_keeps_it_off(self): - self.assertIs(_direct_media(list(STANDALONE_TURN), mode="swarm"), False) + self.assertIs( + _direct_media(list(STANDALONE_TURN), mode="swarm", applications=OPTED_IN), + False, + ) def test_onboard_turn_keeps_it_off(self): - forced = {"web-app-nextcloud": {"services": {"talk": {"enabled": True}}}} + forced = _talk(enabled=True, direct_media=True) self.assertIs(_direct_media(["web-app-nextcloud"], applications=forced), False) + def test_missing_host_facts_render_false_instead_of_a_raw_expression(self): + self.assertIs( + _direct_media(list(STANDALONE_TURN), facts=False, applications=OPTED_IN), + False, + ) + if __name__ == "__main__": unittest.main() From 5728502a1954e0775722b4646a123d22984b6e06 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 23:42:04 +0100 Subject: [PATCH 38/42] feat(web-app-nextcloud): run the Talk backend from pinned upstream components nextcloud/aio-talk bundled signaling, Janus, NATS and an onboard TURN server behind a start script that rewrote their configs, and AIO publishes only build stamps, so the updaters could not raise it and the role had to guard Janus against config drift. The backend now runs as talk (Janus built from a meetecho/janus-gateway tag, files/Dockerfiles/Janus), talk_signaling (upstream strukturag/nextcloud-spreed-signaling image), talk_nats (official nats image) and talk_recording (built from a nextcloud-talk-recording release tag, files/Dockerfiles/Recording), each semver-pinned, single-replica, healthchecked and resource-limited. The Dockerfiles take every value as a build arg from compose, and Janus and the recording server get their config path through `command:`. The role renders janus.jcfg, the signaling server.conf and the recording server.conf; they match what AIO stamp 20260409_094910 generated apart from the service addresses and the session keys, which are now derived from the signaling secret. Secrets reach the services only through those files. Janus may join the host network in compose mode, which keeps direct media available there, and an assert refuses host mode in swarm. talk and talk_recording keep their keys, so one deploy replaces the AIO containers in place. The onboard TURN server is gone with its ports, vars and credential, so Talk uses web-svc-coturn only, and the deploy now stops when Talk is enabled without it instead of handing out no STUN or TURN server. The recording image installs the injected root CA as a Firefox policy when the CA is mounted, so recordings work against self-signed TLS, and the recording scratch volume stays off NFS. The Janus drift guard and the janus_config_drift filter are removed. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../files/Dockerfiles/Janus/Dockerfile | 61 +++ .../files/Dockerfiles/Recording/Dockerfile | 50 +++ .../playwright/test-talk-admin-settings.js | 48 +-- .../filter_plugins/nextcloud_janus.py | 121 ------ .../web-app-nextcloud/meta/addons/spreed.yml | 2 - roles/web-app-nextcloud/meta/secrets.yml | 6 +- roles/web-app-nextcloud/meta/services.yml | 94 +++-- roles/web-app-nextcloud/meta/volumes.yml | 23 +- .../web-app-nextcloud/tasks/01_fullstack.yml | 115 +++--- .../templates/compose.yml.j2 | 104 +++-- .../templates/docker.conf.j2 | 6 +- roles/web-app-nextcloud/templates/env.j2 | 13 - .../web-app-nextcloud/templates/janus.jcfg.j2 | 4 + .../templates/playwright.env.j2 | 6 +- .../templates/recording.conf.j2 | 36 ++ .../templates/signaling.conf.j2 | 34 ++ roles/web-app-nextcloud/vars/main.yml | 87 ++-- .../filter_plugins/test_nextcloud_janus.py | 138 ------- .../web-app-nextcloud/test_talk_configs.py | 381 ++++++++++++++++++ .../test_talk_direct_media.py | 274 ++++++++----- .../test_talk_version_pins.py | 137 +++++++ 21 files changed, 1160 insertions(+), 580 deletions(-) create mode 100644 roles/web-app-nextcloud/files/Dockerfiles/Janus/Dockerfile create mode 100644 roles/web-app-nextcloud/files/Dockerfiles/Recording/Dockerfile delete mode 100644 roles/web-app-nextcloud/filter_plugins/nextcloud_janus.py create mode 100644 roles/web-app-nextcloud/templates/recording.conf.j2 create mode 100644 roles/web-app-nextcloud/templates/signaling.conf.j2 delete mode 100644 tests/unit/python/roles/web-app-nextcloud/filter_plugins/test_nextcloud_janus.py create mode 100644 tests/unit/python/roles/web-app-nextcloud/test_talk_configs.py create mode 100644 tests/unit/python/roles/web-app-nextcloud/test_talk_version_pins.py diff --git a/roles/web-app-nextcloud/files/Dockerfiles/Janus/Dockerfile b/roles/web-app-nextcloud/files/Dockerfiles/Janus/Dockerfile new file mode 100644 index 0000000000..e2479cbab6 --- /dev/null +++ b/roles/web-app-nextcloud/files/Dockerfiles/Janus/Dockerfile @@ -0,0 +1,61 @@ +ARG JANUS_BASE_IMAGE +ARG JANUS_BASE_VERSION +FROM ${JANUS_BASE_IMAGE}:${JANUS_BASE_VERSION} AS build +ARG JANUS_REPOSITORY +ARG JANUS_REF + +WORKDIR /src +RUN set -ex; \ + apk upgrade --no-cache -a; \ + apk add --no-cache \ + ca-certificates \ + git \ + autoconf \ + automake \ + build-base \ + pkgconfig \ + libtool \ + util-linux \ + glib-dev \ + zlib-dev \ + openssl-dev \ + jansson-dev \ + libnice-dev \ + libconfig-dev \ + libsrtp-dev \ + libusrsctp-dev \ + gengetopt-dev \ + libwebsockets-dev; \ + git clone --recursive "${JANUS_REPOSITORY}" --depth=1 --single-branch --branch "${JANUS_REF}" /src; \ + /src/autogen.sh; \ + /src/configure --disable-rabbitmq --disable-mqtt --disable-boringssl; \ + make; \ + make install; \ + make configs; \ + rename -v ".jcfg.sample" ".jcfg" /usr/local/etc/janus/*.jcfg.sample + +FROM ${JANUS_BASE_IMAGE}:${JANUS_BASE_VERSION} + +COPY --from=build /usr/local /usr/local + +RUN set -ex; \ + apk upgrade --no-cache -a; \ + apk add --no-cache \ + ca-certificates \ + tzdata \ + netcat-openbsd \ + glib \ + zlib \ + libssl3 \ + libcrypto3 \ + jansson \ + libnice \ + libconfig \ + libsrtp \ + libusrsctp \ + libwebsockets; \ + mkdir -p /usr/local/lib/janus/loggers; \ + adduser -D -H -u 1000 janus + +USER janus +ENTRYPOINT ["janus", "--disable-colors", "--log-stdout", "--full-trickle", "--debug-level", "3"] diff --git a/roles/web-app-nextcloud/files/Dockerfiles/Recording/Dockerfile b/roles/web-app-nextcloud/files/Dockerfiles/Recording/Dockerfile new file mode 100644 index 0000000000..c64cd5e1f5 --- /dev/null +++ b/roles/web-app-nextcloud/files/Dockerfiles/Recording/Dockerfile @@ -0,0 +1,50 @@ +ARG RECORDING_BASE_IMAGE +ARG RECORDING_BASE_VERSION +FROM ${RECORDING_BASE_IMAGE}:${RECORDING_BASE_VERSION} +ARG RECORDING_REPOSITORY +ARG RECORDING_REF +ARG RECORDING_USER_ID +ARG RECORDING_DIRECTORY +ARG RECORDING_CONFIG_DIRECTORY + +RUN set -ex; \ + apk upgrade --no-cache -a; \ + apk add --no-cache \ + ca-certificates \ + tzdata \ + bash \ + xvfb \ + ffmpeg \ + firefox \ + font-noto-all \ + font-noto-cjk \ + font-noto-cjk-extra \ + bind-tools \ + netcat-openbsd \ + git \ + shadow \ + pulseaudio \ + build-base \ + linux-headers \ + geckodriver; \ + useradd -d "${RECORDING_DIRECTORY}" --system recording -u "${RECORDING_USER_ID}"; \ + git clone --recursive "${RECORDING_REPOSITORY}" --depth=1 --single-branch --branch "${RECORDING_REF}" /src; \ + python3 -m pip install --no-cache-dir /src; \ + rm -rf /src; \ + mkdir -p "${RECORDING_CONFIG_DIRECTORY}"; \ + chown recording:recording -R "${RECORDING_DIRECTORY}"; \ + apk del --no-cache \ + git \ + shadow \ + build-base \ + linux-headers + +ARG RECORDING_CA_CERT +RUN if [ -n "${RECORDING_CA_CERT}" ]; then \ + mkdir -p /etc/firefox/policies \ + && printf '{"policies":{"Certificates":{"Install":["%s"]}}}\n' "${RECORDING_CA_CERT}" > /etc/firefox/policies/policies.json; \ + fi + +WORKDIR ${RECORDING_DIRECTORY} +USER ${RECORDING_USER_ID} +ENTRYPOINT ["python", "-m", "nextcloud.talk.recording"] diff --git a/roles/web-app-nextcloud/files/playwright/test-talk-admin-settings.js b/roles/web-app-nextcloud/files/playwright/test-talk-admin-settings.js index c69b579bd0..ebafbfcdae 100644 --- a/roles/web-app-nextcloud/files/playwright/test-talk-admin-settings.js +++ b/roles/web-app-nextcloud/files/playwright/test-talk-admin-settings.js @@ -13,8 +13,7 @@ const nextcloudTalkSettingsUrl = decodeDotenvQuotedValue(process.env.NEXTCLOUD_T const nextcloudTalkExpectedSignalingUrl = decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_EXPECTED_SIGNALING_URL); const nextcloudTalkExpectedStunServer = decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_EXPECTED_STUN_SERVER); const nextcloudTalkExpectedTurnServer = decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_EXPECTED_TURN_SERVER); -const nextcloudTalkUnexpectedStunServer = decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_UNEXPECTED_STUN_SERVER); -const nextcloudTalkUnexpectedTurnServer = decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_UNEXPECTED_TURN_SERVER); +const nextcloudTalkExpectedSignalingVersion = decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_EXPECTED_SIGNALING_VERSION); // Error strings emitted by the spreed admin UI when a signaling / STUN / TURN // test button reports a failure. Kept in one place so the list stays easy to @@ -43,8 +42,8 @@ const talkTestServerRequiredOkPattern = /OK:\s*Running version:\s*\S+/i; // Talk admin settings are partly rendered as plain text and partly as // `` fields. `innerText()` alone would miss the input -// values, so collect both text and form values before asserting presence or -// absence of configured / legacy endpoints. +// values, so collect both text and form values before asserting the +// configured endpoints. async function collectNextcloudSettingsText(target) { const bodyText = await target.locator("body").innerText().catch(() => ""); const formValues = await target.locator("input, textarea, select").evaluateAll((elements) => { @@ -80,18 +79,6 @@ async function expectNextcloudSettingValue(page, expectedValue, label) { .toContain(expectedValue); } -async function expectNextcloudSettingAbsent(page, unexpectedValue, label) { - await expect - .poll( - async () => collectNextcloudSettingsText(page), - { - timeout: resolveTimeout(30_000), - message: `Expected ${label} to stay absent in the Nextcloud Talk admin settings: ${unexpectedValue}` - } - ) - .not.toContain(unexpectedValue); -} - async function clickAllTalkTestServerButtonsAndVerify(page) { // Spreed renders the test result inside `` // and the explicit re-test button (icon-only NcButton with @@ -154,6 +141,25 @@ async function clickAllTalkTestServerButtonsAndVerify(page) { } } +function runningVersionPattern(version) { + const escaped = version.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + return new RegExp(`Running version:\\s*${escaped}(?:~[^;\\s]*)?(?=;|\\s|$)`, "i"); +} + +async function expectPinnedSignalingVersion(page) { + const connectionSpans = page.locator("span.test-connection"); + await expect + .poll(async () => connectionSpans.allInnerTexts().catch(() => []), { + timeout: resolveTimeout(60_000), + message: `Expected the HPB signaling row to report the pinned version ${nextcloudTalkExpectedSignalingVersion} as its running version`, + }) + .toEqual(expect.arrayContaining([expect.stringMatching(runningVersionPattern(nextcloudTalkExpectedSignalingVersion))])); + + for (const text of await connectionSpans.allInnerTexts()) { + expect(text, `The HPB signaling server reports chat-relay as missing: ${text}`).not.toMatch(/missing features:[^\n]*\bchat-relay\b/i); + } +} + exports.register = function (shared) { test("nextcloud talk admin settings", async ({ browser }) => { test.skip(!nextcloudTalkSettingsCheckEnabled, "Talk admin checks are disabled in the current Playwright env"); @@ -163,6 +169,7 @@ exports.register = function (shared) { expect(nextcloudTalkExpectedSignalingUrl, "NEXTCLOUD_TALK_EXPECTED_SIGNALING_URL must be set when Talk admin checks are enabled").toBeTruthy(); expect(nextcloudTalkExpectedStunServer, "NEXTCLOUD_TALK_EXPECTED_STUN_SERVER must be set when Talk admin checks are enabled").toBeTruthy(); expect(nextcloudTalkExpectedTurnServer, "NEXTCLOUD_TALK_EXPECTED_TURN_SERVER must be set when Talk admin checks are enabled").toBeTruthy(); + expect(nextcloudTalkExpectedSignalingVersion, "NEXTCLOUD_TALK_EXPECTED_SIGNALING_VERSION must be set when Talk admin checks are enabled").toBeTruthy(); const browserContext = await browser.newContext({ ignoreHTTPSErrors: true @@ -203,15 +210,8 @@ exports.register = function (shared) { await expectNextcloudSettingValue(adminPage, nextcloudTalkExpectedStunServer, "Talk STUN server"); await expectNextcloudSettingValue(adminPage, nextcloudTalkExpectedTurnServer, "Talk TURN server"); - if (nextcloudTalkUnexpectedStunServer) { - await expectNextcloudSettingAbsent(adminPage, nextcloudTalkUnexpectedStunServer, "legacy Talk STUN server"); - } - - if (nextcloudTalkUnexpectedTurnServer) { - await expectNextcloudSettingAbsent(adminPage, nextcloudTalkUnexpectedTurnServer, "legacy Talk TURN server"); - } - await clickAllTalkTestServerButtonsAndVerify(adminPage); + await expectPinnedSignalingVersion(adminPage); } finally { await adminPage.close().catch(() => {}); } diff --git a/roles/web-app-nextcloud/filter_plugins/nextcloud_janus.py b/roles/web-app-nextcloud/filter_plugins/nextcloud_janus.py deleted file mode 100644 index ea7398fa7b..0000000000 --- a/roles/web-app-nextcloud/filter_plugins/nextcloud_janus.py +++ /dev/null @@ -1,121 +0,0 @@ -from __future__ import annotations - -import re - - -def _strip_comments(content): - out = [] - in_string = in_block = False - index = 0 - while index < len(content): - char = content[index] - if in_block: - if content.startswith("*/", index): - in_block = False - index += 1 - elif char == "\n": - out.append(char) - elif in_string: - out.append(char) - if char == "\\" and index + 1 < len(content): - out.append(content[index + 1]) - index += 1 - elif char == '"': - in_string = False - elif char == '"': - in_string = True - out.append(char) - elif content.startswith("/*", index): - in_block = True - index += 1 - elif char == "#" or content.startswith("//", index): - while index + 1 < len(content) and content[index + 1] != "\n": - index += 1 - else: - out.append(char) - index += 1 - return "".join(out) - - -def _without_blanks(line): - out = [] - in_string = False - for index, char in enumerate(line): - if char == '"' and (index == 0 or line[index - 1] != "\\"): - in_string = not in_string - if in_string or not char.isspace(): - out.append(char) - return "".join(out).rstrip(";") - - -def _key(setting): - for index, char in enumerate(setting): - if char in "=:": - return setting[:index] - if char == '"': - return "" - return "" - - -def janus_settings(content, overrides): - """Return the settings a Janus ``.jcfg`` file declares, one per line. - - Args: - content: text of a Janus libconfig file. - overrides: setting names to leave out, the ones a deployment sets on - top of the stock file; empty to keep every setting. - - Returns: - Every line that holds more than comments and blanks, with the comments, - a trailing ``;`` and the whitespace outside quoted strings removed, in - file order. - """ - dropped = {str(name) for name in overrides} - settings = [] - for raw in _strip_comments(str(content)).splitlines(): - setting = _without_blanks(raw) - if setting and _key(setting) not in dropped: - settings.append(setting) - return settings - - -def janus_config_drift(template, stock, overrides, launcher, target): - """Return why a rendered Janus config may not replace an image's own. - - Args: - template: the rendered config that is mounted over ``target``. - stock: the image's own file at ``target``. - overrides: setting names the template adds to the stock settings. - launcher: the image's process manager config that starts Janus. - target: the path the template is mounted at. - - Returns: - One message per problem; empty when Janus reads ``target`` and the - template without ``overrides`` declares exactly the stock settings. - """ - problems = [] - started_with = re.compile(rf"--config={re.escape(str(target))}( |$)", re.MULTILINE) - if not started_with.search(str(launcher)): - problems.append(f"Janus is not started with --config={target}") - expected = janus_settings(stock, []) - rendered = janus_settings(template, overrides) - if expected != rendered: - first = next( - ( - f"{index}: image {theirs!r}, template {ours!r}" - for index, (theirs, ours) in enumerate( - zip(expected, rendered, strict=False) - ) - if theirs != ours - ), - f"{len(expected)} settings in the image, {len(rendered)} in the template", - ) - problems.append(f"the stock settings differ at setting {first}") - return problems - - -class FilterModule: - def filters(self): - return { - "janus_config_drift": janus_config_drift, - } diff --git a/roles/web-app-nextcloud/meta/addons/spreed.yml b/roles/web-app-nextcloud/meta/addons/spreed.yml index 31f088c09f..7b8965e665 100644 --- a/roles/web-app-nextcloud/meta/addons/spreed.yml +++ b/roles/web-app-nextcloud/meta/addons/spreed.yml @@ -22,7 +22,6 @@ config: configvalue: >- {{ [ - NEXTCLOUD_HPB_STUN_ONBOARD_CONFIG if NEXTCLOUD_HPB_TURN_ONBOARD_ENABLED else none, NEXTCLOUD_HPB_STUN_STANDALONE_CONFIG if NEXTCLOUD_HPB_TURN_STANDALONE_ENABLED else none ] | select @@ -35,7 +34,6 @@ config: configvalue: >- {{ [ - NEXTCLOUD_HPB_TURN_ONBOARD_CONFIG if NEXTCLOUD_HPB_TURN_ONBOARD_ENABLED else none, NEXTCLOUD_HPB_TURN_STANDALONE_CONFIG if NEXTCLOUD_HPB_TURN_STANDALONE_ENABLED else none ] | select diff --git a/roles/web-app-nextcloud/meta/secrets.yml b/roles/web-app-nextcloud/meta/secrets.yml index 3d9e46fd81..2df50071dd 100644 --- a/roles/web-app-nextcloud/meta/secrets.yml +++ b/roles/web-app-nextcloud/meta/secrets.yml @@ -17,16 +17,12 @@ credentials: description: Initial password for the Nextcloud administrator (change immediately and enable 2FA) algorithm: sha256 validation: ^[a-f0-9]{64}$ - talk_turn_secret: - description: TURN REST secret for the optional onboard Talk TURN server - algorithm: base64_prefixed_32 - validation: ^base64:[A-Za-z0-9+/]{43}=$ talk_signaling_secret: description: Secret for Talk signaling algorithm: base64_prefixed_32 validation: ^base64:[A-Za-z0-9+/]{43}=$ talk_internal_secret: - description: Internal secret for AIO Talk + description: Secret internal clients such as the Talk recording server present to the signaling server algorithm: base64_prefixed_32 validation: ^base64:[A-Za-z0-9+/]{43}=$ context_agent_app_secret: diff --git a/roles/web-app-nextcloud/meta/services.yml b/roles/web-app-nextcloud/meta/services.yml index 57c7f03b91..3b60d8a425 100644 --- a/roles/web-app-nextcloud/meta/services.yml +++ b/roles/web-app-nextcloud/meta/services.yml @@ -101,12 +101,6 @@ nextcloud: internal: http: 80 fpm: 9000 - public: - stun_turn: 3480 - stun_turn_tls: 5350 - relay: - start: 50000 - end: 59999 run_after: - web-app-keycloak - web-app-matomo @@ -200,34 +194,79 @@ talk: bond: 1 enabled: "{{ 'web-svc-coturn' in group_names }}" shared: "{{ 'web-svc-coturn' in group_names }}" - name: nextcloud-talk - image: nextcloud/aio-talk - # nocheck: docker-version -- upstream publishes only AIO build stamps and froze latest at 20250325_084656; later stamps start Janus from a generated /conf/janus.jcfg that the janus_conf mount cannot replace - version: "20260409_094910" - backup: - no_stop_required: false + name: nextcloud-talk-janus + image: alpine + version: 3.23.3 + custom: nextcloud-talk-janus + repository: https://github.com/meetecho/janus-gateway.git + ref: v1.4.0 + # nocheck: single-replica the signaling server addresses exactly one Janus by URL and keeps every media session on it + replicas: 1 turn_server: - onboard_enabled: "{{ not ( 'web-svc-coturn' in group_names ) }}" standalone_enabled: "{{ 'web-svc-coturn' in group_names }}" network_mode: bridge direct_media: false cpus: "2.0" - mem_reservation: 1g - mem_limit: 2g + mem_reservation: 512m + mem_limit: 1g pids_limit: 1024 - min_storage: 279MB + min_storage: 600MB ports: internal: - signaling: 8081 + websocket: 8188 public: relay: start: 61000 end: 61999 healthcheck: - flavor: tcp + flavor: nc + port_key: websocket +# nocheck: playwright-service-flag the signaling server is part of the Talk deployment, covered by the Talk admin settings spec +# nocheck: dynamic-flag the signaling server is part of the Talk deployment, so it follows the talk entry rather than a role's presence +talk_signaling: + enabled: "{{ lookup('config', 'web-app-nextcloud', 'services.talk.enabled') | bool }}" + shared: false + name: nextcloud-talk-signaling + image: strukturag/nextcloud-spreed-signaling + version: 2.1.1 + # nocheck: single-replica sessions live in this process; a second replica behind the VIP would split one call across servers + replicas: 1 + max_stream_bitrate: 1048576 + max_screen_bitrate: 2097152 + cpus: "1.0" + mem_reservation: 128m + mem_limit: 512m + pids_limit: 256 + min_storage: 223MB + ports: + internal: + signaling: 8081 + healthcheck: + flavor: http_status port_key: signaling - # nocheck: healthcheck-timing-override a sidecar of a stack whose main service alone takes minutes; the value predates this default and has not been measured against it - start_period: 20m + path: api/v1/welcome +# nocheck: playwright-service-flag internal message bus, reachable only from the Talk signaling server +# nocheck: dynamic-flag the message bus is part of the Talk deployment, so it follows the talk entry rather than a role's presence +talk_nats: + enabled: "{{ lookup('config', 'web-app-nextcloud', 'services.talk.enabled') | bool }}" + shared: false + name: nextcloud-talk-nats + image: nats + version: 2.12.6-alpine + # nocheck: single-replica an unclustered NATS server; the signaling server connects to exactly one + replicas: 1 + cpus: "0.5" + mem_reservation: 32m + mem_limit: 256m + pids_limit: 128 + min_storage: 211MB + ports: + internal: + nats: 4222 + http: 8222 + healthcheck: + flavor: http + path: healthz whiteboard: name: nextcloud-whiteboard image: ghcr.io/nextcloud-releases/whiteboard @@ -281,11 +320,13 @@ talk_recording: enabled: "{{ lookup('config', 'web-app-nextcloud', 'services.talk.enabled') | bool }}" shared: false name: nextcloud-talk-recording - image: nextcloud/aio-talk-recording - # nocheck: docker-version -- upstream publishes only AIO build stamps and froze latest at 20250325_084656; stays on the AIO release of services.talk.version - version: "20260409_094910" - backup: - no_stop_required: true + image: python + version: 3.14.3-alpine3.23 + custom: nextcloud-talk-recording + repository: https://github.com/nextcloud/nextcloud-talk-recording.git + ref: v0.2.1 + # nocheck: single-replica Talk starts and stops a recording on the server it reached; a second replica behind the VIP would receive half of the stop requests + replicas: 1 cpus: "2.0" mem_reservation: 1g mem_limit: 3g @@ -294,6 +335,9 @@ talk_recording: ports: internal: recording: 1234 + healthcheck: + flavor: nc + port_key: recording # nocheck: playwright-service-flag: verified by web-svc-css provider spec css: bond: 1 diff --git a/roles/web-app-nextcloud/meta/volumes.yml b/roles/web-app-nextcloud/meta/volumes.yml index 71472549cb..fd4dd9d89f 100644 --- a/roles/web-app-nextcloud/meta/volumes.yml +++ b/roles/web-app-nextcloud/meta/volumes.yml @@ -33,6 +33,8 @@ talk_recording_tmp: name: nextcloud_talk_recording_tmp type: volume backup: false + # nocheck: nfs-false-data-loss Reason: scratch for Xvfb sockets, the Firefox profile and the ffmpeg output before its upload; single replica, nothing persists. + nfs: false mounts: - service: talk_recording target: *tmp_target @@ -68,10 +70,29 @@ infinito_conf: janus_conf: type: config source: "{{ [ lookup('container', 'web-app-nextcloud', 'directories.volumes'), 'janus.jcfg' ] | path_join }}" + mode: "0444" mounts: - service: talk target: /usr/local/etc/janus/janus.jcfg - when: "{{ lookup('config', 'web-app-nextcloud', 'services.talk.direct_media') | bool }}" + when: "{{ lookup('config', 'web-app-nextcloud', 'services.talk.enabled') | bool }}" + +talk_signaling_conf: + type: secret + source: "{{ [ lookup('container', 'web-app-nextcloud', 'directories.volumes'), 'signaling.conf' ] | path_join }}" + mode: "0444" + mounts: + - service: talk_signaling + target: /config/server.conf + when: "{{ lookup('config', 'web-app-nextcloud', 'services.talk.enabled') | bool }}" + +talk_recording_conf: + type: secret + source: "{{ [ lookup('container', 'web-app-nextcloud', 'directories.volumes'), 'recording.conf' ] | path_join }}" + mode: "0444" + mounts: + - service: talk_recording + target: /conf/recording.conf + when: "{{ lookup('config', 'web-app-nextcloud', 'services.talk.enabled') | bool }}" php_hardening: type: config diff --git a/roles/web-app-nextcloud/tasks/01_fullstack.yml b/roles/web-app-nextcloud/tasks/01_fullstack.yml index 9c3107de5f..0eb802761e 100644 --- a/roles/web-app-nextcloud/tasks/01_fullstack.yml +++ b/roles/web-app-nextcloud/tasks/01_fullstack.yml @@ -1,4 +1,25 @@ --- +- name: "šŸ›‘ Assert Janus joins the host network only in compose mode" + ansible.builtin.assert: + that: DEPLOYMENT_MODE == 'compose' + fail_msg: >- + services.talk.network_mode host gives Janus the host network namespace, + which docker stack deploy cannot provide. Use bridge in swarm mode. + quiet: true + when: + - NEXTCLOUD_HPB_SIGNALING_ENABLED | bool + - NEXTCLOUD_HPB_JANUS_HOST_NETWORK | bool + +- name: "šŸ›‘ Assert Talk has the TURN server its calls relay through" + ansible.builtin.assert: + that: NEXTCLOUD_HPB_TURN_ACTIVE_SERVER | length > 0 + fail_msg: >- + services.talk.enabled is true, but {{ NEXTCLOUD_HPB_TURN_STANDALONE_ROLE }} is not deployed + on this host, so Talk would hand out no STUN or TURN server and calls behind NAT would carry + no media. Deploy {{ NEXTCLOUD_HPB_TURN_STANDALONE_ROLE }} or set services.talk.enabled to false. + quiet: true + when: NEXTCLOUD_HPB_SIGNALING_ENABLED | bool + - name: "🧩 load docker, db and proxy for {{ application_id }}" include_role: name: sys-stk-full @@ -7,51 +28,6 @@ application_id: web-app-nextcloud webserver_client_max_body_size: 10G -- name: "šŸ” Read the Janus launcher and config from {{ NEXTCLOUD_HPB_IMAGE }}" - ansible.builtin.command: - argv: - - container - - run - - --rm - - --pull - - always - - --entrypoint - - cat - - "{{ NEXTCLOUD_HPB_IMAGE }}" - - "{{ item }}" - environment: - CA_CONTAINER_ENABLED: "0" - loop: - - "{{ NEXTCLOUD_HPB_JANUS_LAUNCHER }}" - - "{{ NEXTCLOUD_HPB_JANUS_CONFIG_TARGET }}" - register: nextcloud_janus_image_files - changed_when: false - retries: 3 - delay: 30 - until: nextcloud_janus_image_files is succeeded - when: - - NEXTCLOUD_HPB_MEDIA_DIRECT | bool - - IS_STACK_HOST | bool - -- name: "šŸ›‘ Assert Janus reads the mounted config and the image's copy still matches" - ansible.builtin.assert: - that: nextcloud_janus_drift | length == 0 - fail_msg: >- - templates/janus.jcfg.j2 cannot replace {{ NEXTCLOUD_HPB_JANUS_CONFIG_TARGET }} - of {{ NEXTCLOUD_HPB_IMAGE }}: {{ nextcloud_janus_drift | join('; ') }}. - Re-derive the template from the new image before deploying. - quiet: true - vars: - nextcloud_janus_drift: >- - {{ lookup('template', 'janus.jcfg.j2') - | janus_config_drift(nextcloud_janus_image_files.results[1].stdout, - NEXTCLOUD_HPB_JANUS_OVERRIDES, - nextcloud_janus_image_files.results[0].stdout, - NEXTCLOUD_HPB_JANUS_CONFIG_TARGET) }} - when: - - NEXTCLOUD_HPB_MEDIA_DIRECT | bool - - IS_STACK_HOST | bool - - name: "šŸ“„ Deploy '{{ NEXTCLOUD_INIT_GATE_HOST }}'" copy: src: "{{ NEXTCLOUD_INIT_GATE_SRC }}" @@ -124,12 +100,43 @@ - src: "fpm-pool.conf.j2" dest: "{{ NEXTCLOUD_HOST_FPM_POOL_PATH }}" -- name: "šŸ“„ Render the Janus config that publishes Talk media directly" - ansible.builtin.include_tasks: - file: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/render_replicated_templates.yml') }}" - vars: - role_templates: - - src: "janus.jcfg.j2" - dest: "{{ NEXTCLOUD_HPB_JANUS_CONFIG_HOST }}" - mode: "0644" - when: NEXTCLOUD_HPB_MEDIA_DIRECT | bool +- when: NEXTCLOUD_HPB_SIGNALING_ENABLED | bool + block: + - name: "šŸ“ Create the Talk build directories" + ansible.builtin.file: + path: "{{ item }}" + state: directory + mode: "0755" + loop: + - "{{ NEXTCLOUD_HPB_JANUS_BUILD_DIRECTORY }}" + - "{{ NEXTCLOUD_RECORDING_BUILD_DIRECTORY }}" + + - name: "šŸ“„ Deploy the Talk Dockerfiles that build Janus and the recording server" + stack_host_copy: + src: "{{ item.src }}" + dest: "{{ item.dest }}" + loop: + - { src: "Dockerfiles/Janus/Dockerfile", dest: "{{ NEXTCLOUD_HPB_JANUS_DOCKERFILE }}" } + - { src: "Dockerfiles/Recording/Dockerfile", dest: "{{ NEXTCLOUD_RECORDING_DOCKERFILE }}" } + notify: + - compose-build + - compose-up + + - name: "šŸ“„ Render the Janus, signaling and recording configs (local + swarm peers)" + ansible.builtin.include_tasks: + file: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/render_replicated_templates.yml') }}" + vars: + role_templates: + - src: "janus.jcfg.j2" + dest: "{{ NEXTCLOUD_HPB_JANUS_CONFIG_HOST }}" + mode: "0644" + - src: "signaling.conf.j2" + dest: "{{ NEXTCLOUD_HPB_SIGNALING_CONFIG_HOST }}" + owner: "{{ NEXTCLOUD_HPB_SIGNALING_USER_ID }}" + group: "{{ NEXTCLOUD_HPB_SIGNALING_USER_ID }}" + mode: "0400" + - src: "recording.conf.j2" + dest: "{{ NEXTCLOUD_RECORDING_CONFIG_HOST }}" + owner: "{{ NEXTCLOUD_RECORDING_USER_ID }}" + group: "{{ NEXTCLOUD_RECORDING_USER_ID }}" + mode: "0400" diff --git a/roles/web-app-nextcloud/templates/compose.yml.j2 b/roles/web-app-nextcloud/templates/compose.yml.j2 index 789ea62e3e..4c353b9171 100644 --- a/roles/web-app-nextcloud/templates/compose.yml.j2 +++ b/roles/web-app-nextcloud/templates/compose.yml.j2 @@ -11,9 +11,7 @@ {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_healthcheck', service_name, samples=(groups[application_id] | default([]) | length) if DEPLOYMENT_MODE == 'swarm' else 1) | indent(4) }} {{ lookup('container_networks') | indent(4) }} - {{ lookup('container_extra_hosts', extra_hosts=( - ['host.docker.internal:host-gateway'] if NEXTCLOUD_HPB_NETWORK_MODE == 'host' else [] - )) | indent(4) }} + {{ lookup('container_extra_hosts') | indent(4) }} {% set service_name = NEXTCLOUD_SERVICE %} {% set container_healthcheck_start_period = '20m' %} @@ -74,41 +72,62 @@ {% if NEXTCLOUD_HPB_SIGNALING_ENABLED | bool %} {% set service_name = NEXTCLOUD_HPB_SERVICE %} - {% set container_port = NEXTCLOUD_HPB_SIGNALING_PORT %} {{ service_name }}: {% include 'roles/sys-svc-container/templates/base.yml.j2' %} - {{ lookup('container_healthcheck', service_name) | indent(4) }} - {{ lookup('container_image', application_id, 'talk') }} + build: + context: {{ NEXTCLOUD_HPB_JANUS_BUILD_DIRECTORY }} + dockerfile: Dockerfile + args: + JANUS_BASE_IMAGE: "{{ NEXTCLOUD_HPB_JANUS_BASE_IMAGE }}" + JANUS_BASE_VERSION: "{{ NEXTCLOUD_HPB_JANUS_BASE_VERSION }}" + JANUS_REPOSITORY: "{{ NEXTCLOUD_HPB_JANUS_REPOSITORY }}" + JANUS_REF: "{{ NEXTCLOUD_HPB_JANUS_REF }}" + {{ lookup('compose_only', 'pull_policy', 'never') }} + {{ lookup('container_image', application_id, service_name, version=NEXTCLOUD_HPB_JANUS_TAG) }} {{ lookup('compose_only', 'container_name', NEXTCLOUD_HPB_CONTAINER) }} + command: ["--config={{ NEXTCLOUD_HPB_JANUS_CONFIG_TARGET }}"] init: true - {% if NEXTCLOUD_HPB_NETWORK_MODE == 'bridge' %} - {% set _talk_ports = [] %} - {% if NEXTCLOUD_HPB_TURN_ONBOARD_ENABLED | bool and NEXTCLOUD_HPB_TURN_ONBOARD_PUBLISH_PORTS | bool %} - {% set _ = _talk_ports.extend([ - {'service': 'nextcloud', 'protocol': 'stun_turn', - 'ip': NEXTCLOUD_HPB_TURN_ONBOARD_BIND_HOST, - 'transport': ['tcp', 'udp'], 'container': 'same'}, - {'service': 'nextcloud', 'protocol': 'relay', - 'ip': NEXTCLOUD_HPB_TURN_ONBOARD_BIND_HOST, - 'transport': ['udp', 'tcp'], 'container': 'same'}, - ]) %} - {% endif %} - {% if NEXTCLOUD_HPB_MEDIA_DIRECT | bool %} + {{ lookup('container_healthcheck', service_name) | indent(4) }} {{ lookup('container_volumes', service_name) | indent(4) }} - {% set _ = _talk_ports.append( - {'service': 'talk', 'protocol': 'relay', - 'ip': NEXTCLOUD_HPB_MEDIA_PUBLIC_IP, - 'transport': 'udp', 'container': 'same'}) %} - {% endif %} - {% if _talk_ports %} - {{ lookup('container_ports', *_talk_ports) | indent(4) }} + {% if DEPLOYMENT_MODE == 'compose' and NEXTCLOUD_HPB_JANUS_HOST_NETWORK | bool %} + network_mode: host + {% else %} + {% if NEXTCLOUD_HPB_MEDIA_DIRECT | bool %} + {{ lookup('container_ports', + {'service': service_name, 'protocol': 'relay', + 'ip': NEXTCLOUD_HPB_MEDIA_PUBLIC_IP, + 'transport': 'udp', 'container': 'same'}) | indent(4) }} {% endif %} expose: - - "{{ container_port }}" - {{ lookup('container_networks', provider_self_alias=False) | indent(4) }} - {% else %} - network_mode: {{ NEXTCLOUD_HPB_NETWORK_MODE }} + - "{{ NEXTCLOUD_HPB_JANUS_PORT }}" + {{ lookup('container_networks', own_network_only=True, provider_self_alias=False) | indent(4) }} {% endif %} + + {% set service_name = NEXTCLOUD_HPB_SIGNALING_SERVICE %} + {{ service_name }}: + {% include 'roles/sys-svc-container/templates/base.yml.j2' %} + {{ lookup('container_image', application_id, service_name) }} + {{ lookup('compose_only', 'container_name', NEXTCLOUD_HPB_SIGNALING_CONTAINER) }} + user: "{{ NEXTCLOUD_HPB_SIGNALING_USER_ID }}:{{ NEXTCLOUD_HPB_SIGNALING_USER_ID }}" + command: ["{{ NEXTCLOUD_HPB_SIGNALING_BINARY }}", "-config", "{{ NEXTCLOUD_HPB_SIGNALING_CONFIG_TARGET }}"] + {{ lookup('container_healthcheck', service_name) | indent(4) }} + {{ lookup('container_volumes', service_name) | indent(4) }} + expose: + - "{{ NEXTCLOUD_HPB_SIGNALING_PORT }}" + {{ lookup('container_extra_hosts', host_alias=NEXTCLOUD_HPB_JANUS_HOST_NETWORK) | indent(4) }} + {{ lookup('container_networks', provider_self_alias=False) | indent(4) }} + + {% set service_name = NEXTCLOUD_HPB_NATS_SERVICE %} + {{ service_name }}: + {% include 'roles/sys-svc-container/templates/base.yml.j2' %} + {{ lookup('container_image', application_id, service_name) }} + {{ lookup('compose_only', 'container_name', NEXTCLOUD_HPB_NATS_CONTAINER) }} + user: "{{ NEXTCLOUD_HPB_NATS_USER_ID }}:{{ NEXTCLOUD_HPB_NATS_USER_ID }}" + command: ["nats-server", "--addr", "0.0.0.0", "--port", "{{ NEXTCLOUD_HPB_NATS_PORT }}", "--http_port", "{{ NEXTCLOUD_HPB_NATS_MONITOR_PORT }}"] + {{ lookup('container_healthcheck', service_name) | indent(4) }} + expose: + - "{{ NEXTCLOUD_HPB_NATS_PORT }}" + {{ lookup('container_networks', own_network_only=True, provider_self_alias=False) | indent(4) }} {% endif %} {% if NEXTCLOUD_WHITEBOARD_ENABLED %} @@ -188,17 +207,28 @@ {{ lookup('container_networks', provider_self_alias=False) | indent(4) }} {% if NEXTCLOUD_RECORDING_ENABLED | bool %} - {% set service_name = 'talk_recording' %} + {% set service_name = NEXTCLOUD_RECORDING_SERVICE %} {{ service_name }}: {% include 'roles/sys-svc-container/templates/base.yml.j2' %} - {{ lookup('container_image', application_id, 'talk_recording') }} + build: + context: {{ NEXTCLOUD_RECORDING_BUILD_DIRECTORY }} + dockerfile: Dockerfile + args: + RECORDING_BASE_IMAGE: "{{ NEXTCLOUD_RECORDING_BASE_IMAGE }}" + RECORDING_BASE_VERSION: "{{ NEXTCLOUD_RECORDING_BASE_VERSION }}" + RECORDING_REPOSITORY: "{{ NEXTCLOUD_RECORDING_REPOSITORY }}" + RECORDING_REF: "{{ NEXTCLOUD_RECORDING_REF }}" + RECORDING_USER_ID: "{{ NEXTCLOUD_RECORDING_USER_ID }}" + RECORDING_DIRECTORY: "{{ NEXTCLOUD_RECORDING_DIRECTORY }}" + RECORDING_CONFIG_DIRECTORY: "{{ NEXTCLOUD_RECORDING_CONFIG_TARGET | dirname }}" + RECORDING_CA_CERT: "{{ NEXTCLOUD_RECORDING_CA_CERT }}" + {{ lookup('compose_only', 'pull_policy', 'never') }} + {{ lookup('container_image', application_id, service_name, version=NEXTCLOUD_RECORDING_TAG) }} {{ lookup('compose_only', 'container_name', NEXTCLOUD_RECORDING_CONTAINER) }} + command: ["--config", "{{ NEXTCLOUD_RECORDING_CONFIG_TARGET }}"] environment: - - HPB_DOMAIN={{ NEXTCLOUD_HPB_DOMAIN }} - - NC_DOMAIN={{ NEXTCLOUD_DOMAIN }} - - RECORDING_SECRET={{ NEXTCLOUD_RECORDING_SECRET }} - - INTERNAL_SECRET={{ NEXTCLOUD_HPB_INTERNAL_SECRET }} - - TZ={{ HOST_TIMEZONE }} + TZ: "{{ HOST_TIMEZONE }}" + {{ lookup('container_healthcheck', service_name) | indent(4) }} expose: - "{{ NEXTCLOUD_RECORDING_PORT }}" {{ lookup('container_networks', provider_self_alias=False) | indent(4) }} diff --git a/roles/web-app-nextcloud/templates/docker.conf.j2 b/roles/web-app-nextcloud/templates/docker.conf.j2 index e474d2a137..5c2da5064d 100644 --- a/roles/web-app-nextcloud/templates/docker.conf.j2 +++ b/roles/web-app-nextcloud/templates/docker.conf.j2 @@ -114,13 +114,9 @@ http { } {% if NEXTCLOUD_HPB_SIGNALING_ENABLED | bool %} location {{ NEXTCLOUD_HPB_SIGNALING_LOCATION }} { -{% if NEXTCLOUD_HPB_NETWORK_MODE == 'host' %} - proxy_pass http://host.docker.internal:{{ NEXTCLOUD_HPB_SIGNALING_PORT }}/; -{% else %} - set $upstream_nextcloud_talk http://talk:{{ NEXTCLOUD_HPB_SIGNALING_PORT }}; + set $upstream_nextcloud_talk http://{{ NEXTCLOUD_HPB_SIGNALING_SERVICE }}:{{ NEXTCLOUD_HPB_SIGNALING_PORT }}; rewrite ^{{ NEXTCLOUD_HPB_SIGNALING_LOCATION }}(.*)$ /$1 break; proxy_pass $upstream_nextcloud_talk; -{% endif %} proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header Upgrade $http_upgrade; diff --git a/roles/web-app-nextcloud/templates/env.j2 b/roles/web-app-nextcloud/templates/env.j2 index 2f47434e48..3b18b34e2b 100644 --- a/roles/web-app-nextcloud/templates/env.j2 +++ b/roles/web-app-nextcloud/templates/env.j2 @@ -54,19 +54,6 @@ OBJECTSTORE_S3_SECRET={{ lookup('objstore', application_id, 'secret_key') | dote OBJECTSTORE_S3_AUTOCREATE=false {% endif %} -{% if NEXTCLOUD_HPB_PLUGIN_ENABLED %} -NC_DOMAIN={{ NEXTCLOUD_DOMAIN }} -TALK_HOST={{ NEXTCLOUD_HPB_DOMAIN }} -SIGNALING_SECRET={{ NEXTCLOUD_HPB_SIGNALING_SECRET }} -INTERNAL_SECRET={{ NEXTCLOUD_HPB_INTERNAL_SECRET }} -TURN_SECRET={{ NEXTCLOUD_HPB_TURN_ONBOARD_SECRET }} -TALK_PORT={{ NEXTCLOUD_HPB_TURN_ONBOARD_PORT }} -TURN_MIN_PORT={{ NEXTCLOUD_HPB_TURN_ONBOARD_RELAY_PORT_START }} -TURN_MAX_PORT={{ NEXTCLOUD_HPB_TURN_ONBOARD_RELAY_PORT_END }} -COTURN_MIN_PORT={{ NEXTCLOUD_HPB_TURN_ONBOARD_RELAY_PORT_START }} -COTURN_MAX_PORT={{ NEXTCLOUD_HPB_TURN_ONBOARD_RELAY_PORT_END }} -{% endif %} - {% if NEXTCLOUD_WHITEBOARD_ENABLED %} NEXTCLOUD_URL={{ NEXTCLOUD_URL }} JWT_SECRET_KEY={{ NEXTCLOUD_WHITEBOARD_JWT }} diff --git a/roles/web-app-nextcloud/templates/janus.jcfg.j2 b/roles/web-app-nextcloud/templates/janus.jcfg.j2 index 65019cf2ef..956b422048 100644 --- a/roles/web-app-nextcloud/templates/janus.jcfg.j2 +++ b/roles/web-app-nextcloud/templates/janus.jcfg.j2 @@ -34,12 +34,16 @@ certificates: { } media: { +{% if NEXTCLOUD_HPB_MEDIA_DIRECT | bool %} rtp_port_range = "{{ NEXTCLOUD_HPB_MEDIA_PORT_START }}-{{ NEXTCLOUD_HPB_MEDIA_PORT_END }}" +{% endif %} } nat: { +{% if NEXTCLOUD_HPB_MEDIA_DIRECT | bool %} nat_1_1_mapping = "{{ NEXTCLOUD_HPB_MEDIA_PUBLIC_IP }}" keep_private_host = true +{% endif %} ice_ignore_list = "vmnet" } diff --git a/roles/web-app-nextcloud/templates/playwright.env.j2 b/roles/web-app-nextcloud/templates/playwright.env.j2 index ff669499e3..e62bc24403 100644 --- a/roles/web-app-nextcloud/templates/playwright.env.j2 +++ b/roles/web-app-nextcloud/templates/playwright.env.j2 @@ -51,6 +51,8 @@ NEXTCLOUD_TALK_DIRECT_MEDIA_PORT_START={{ NEXTCLOUD_HPB_MEDIA_PORT_START }} NEXTCLOUD_TALK_EXPECTED_SIGNALING_URL={{ NEXTCLOUD_HPB_SIGNALING_URL | dotenv_quote }} +NEXTCLOUD_TALK_EXPECTED_SIGNALING_VERSION={{ NEXTCLOUD_HPB_SIGNALING_VERSION | dotenv_quote }} + NEXTCLOUD_TALK_EXPECTED_STUN_SERVER={{ NEXTCLOUD_HPB_STUN_ACTIVE_CONFIG | dotenv_quote }} NEXTCLOUD_TALK_EXPECTED_TURN_SERVER={{ NEXTCLOUD_HPB_TURN_ACTIVE_SERVER | dotenv_quote }} @@ -59,10 +61,6 @@ NEXTCLOUD_TALK_SETTINGS_CHECK_ENABLED={{ NEXTCLOUD_HPB_PLUGIN_ENABLED | string | NEXTCLOUD_TALK_SETTINGS_URL={{ NEXTCLOUD_TALK_ADMIN_URL | dotenv_quote }} -NEXTCLOUD_TALK_UNEXPECTED_STUN_SERVER={{ (NEXTCLOUD_HPB_STUN_ONBOARD_CONFIG if NEXTCLOUD_HPB_TURN_STANDALONE_ENABLED | bool else '') | dotenv_quote }} - -NEXTCLOUD_TALK_UNEXPECTED_TURN_SERVER={{ (NEXTCLOUD_HPB_TURN_ONBOARD_CONFIG.server | default('') if NEXTCLOUD_HPB_TURN_STANDALONE_ENABLED | bool else '') | dotenv_quote }} - OIDC_ISSUER_URL={{ OIDC.CLIENT.ISSUER_URL | dotenv_quote }} OPENPROJECT_BASE_URL={{ (lookup('tls', 'web-app-openproject', 'url.base') if (lookup('config', application_id, 'services.openproject.enabled') | bool) else '') | dotenv_quote }} diff --git a/roles/web-app-nextcloud/templates/recording.conf.j2 b/roles/web-app-nextcloud/templates/recording.conf.j2 new file mode 100644 index 0000000000..5549758113 --- /dev/null +++ b/roles/web-app-nextcloud/templates/recording.conf.j2 @@ -0,0 +1,36 @@ +[logs] +level = 30 + +[http] +listen = 0.0.0.0:{{ NEXTCLOUD_RECORDING_PORT }} + +[backend] +allowall = false +secret = {{ NEXTCLOUD_RECORDING_SECRET }} +backends = backend-1 +skipverify = false +maxmessagesize = 1024 +videowidth = 1920 +videoheight = 1080 +directory = {{ NEXTCLOUD_RECORDING_DIRECTORY }} + +[backend-1] +url = {{ NEXTCLOUD_HPB_BACKEND_URL }} +secret = {{ NEXTCLOUD_RECORDING_SECRET }} +skipverify = false + +[signaling] +signalings = signaling-1 + +[signaling-1] +url = {{ NEXTCLOUD_HPB_BACKEND_URL }}{{ NEXTCLOUD_HPB_SIGNALING_LOCATION }} +internalsecret = {{ NEXTCLOUD_HPB_INTERNAL_SECRET }} + +[ffmpeg] +extensionaudio = .ogg +extensionvideo = .webm + +[recording] +browser = firefox +driverPath = /usr/bin/geckodriver +browserPath = /usr/bin/firefox diff --git a/roles/web-app-nextcloud/templates/signaling.conf.j2 b/roles/web-app-nextcloud/templates/signaling.conf.j2 new file mode 100644 index 0000000000..09e513caa4 --- /dev/null +++ b/roles/web-app-nextcloud/templates/signaling.conf.j2 @@ -0,0 +1,34 @@ +[http] +listen = 0.0.0.0:{{ NEXTCLOUD_HPB_SIGNALING_PORT }} + +[app] +debug = false + +[sessions] +hashkey = {{ ((NEXTCLOUD_HPB_SIGNALING_SECRET ~ '/sessions/hashkey') | hash('sha256'))[:32] }} +blockkey = {{ ((NEXTCLOUD_HPB_SIGNALING_SECRET ~ '/sessions/blockkey') | hash('sha256'))[:32] }} + +[clients] +internalsecret = {{ NEXTCLOUD_HPB_INTERNAL_SECRET }} + +[backend] +backends = backend-1 +allowall = false +timeout = 10 +connectionsperhost = 8 +skipverify = false + +[backend-1] +urls = {{ NEXTCLOUD_HPB_BACKEND_URL }} +secret = {{ NEXTCLOUD_HPB_SIGNALING_SECRET }} +maxstreambitrate = {{ NEXTCLOUD_HPB_SIGNALING_MAX_STREAM_BITRATE }} +maxscreenbitrate = {{ NEXTCLOUD_HPB_SIGNALING_MAX_SCREEN_BITRATE }} + +[nats] +url = {{ NEXTCLOUD_HPB_NATS_URL }} + +[mcu] +type = janus +url = {{ NEXTCLOUD_HPB_JANUS_URL }} +maxstreambitrate = {{ NEXTCLOUD_HPB_SIGNALING_MAX_STREAM_BITRATE }} +maxscreenbitrate = {{ NEXTCLOUD_HPB_SIGNALING_MAX_SCREEN_BITRATE }} diff --git a/roles/web-app-nextcloud/vars/main.yml b/roles/web-app-nextcloud/vars/main.yml index f20054cbb1..e18c9ea95e 100644 --- a/roles/web-app-nextcloud/vars/main.yml +++ b/roles/web-app-nextcloud/vars/main.yml @@ -157,6 +157,7 @@ NEXTCLOUD_HPB_NETWORK_MODE: "{{ lookup('config', application_id, 'services.' ~ N NEXTCLOUD_HPB_PLUGIN_ENABLED: "{{ lookup('config', application_id, 'addons.spreed.enabled') }}" NEXTCLOUD_HPB_INTERNAL_SECRET: "{{ lookup('config', application_id, 'secrets.credentials.talk_internal_secret') }}" NEXTCLOUD_HPB_DOMAIN: "{{ NEXTCLOUD_DOMAIN }}" +NEXTCLOUD_HPB_BACKEND_URL: "{{ NEXTCLOUD_PROTOCOL }}://{{ NEXTCLOUD_HPB_DOMAIN }}" # nocheck: host-local-fact read only in compose mode, where the host rendering this file is the host Janus publishes its media ports on; Ansible omits the key on a host without the ip binary, which leaves the media on TURN NEXTCLOUD_HPB_HOST_ADDRESSES: "{{ ansible_facts['all_ipv4_addresses'] | default([]) }}" @@ -164,7 +165,6 @@ NEXTCLOUD_HPB_MEDIA_DIRECT: >- {{ (lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.direct_media') | bool) and (NEXTCLOUD_HPB_SIGNALING_ENABLED | bool) and (NEXTCLOUD_HPB_TURN_STANDALONE_ENABLED | bool) - and (lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.network_mode') == 'bridge') and (DEPLOYMENT_MODE == 'compose') and (networks.internet.ip4 in NEXTCLOUD_HPB_HOST_ADDRESSES) }} NEXTCLOUD_HPB_MEDIA_PUBLIC_IP: "{{ networks.internet.ip4 }}" @@ -172,38 +172,39 @@ NEXTCLOUD_HPB_MEDIA_PORT_START: "{{ lookup('config', application_id, 'services.' NEXTCLOUD_HPB_MEDIA_PORT_END: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.ports.public.relay.end') }}" NEXTCLOUD_HPB_JANUS_CONFIG_HOST: "{{ [ lookup('container', application_id, 'directories.volumes'), 'janus.jcfg' ] | path_join }}" NEXTCLOUD_HPB_JANUS_CONFIG_TARGET: "{{ lookup('volume', application_id, 'janus_conf').target }}" -NEXTCLOUD_HPB_JANUS_LAUNCHER: "/supervisord.conf" -NEXTCLOUD_HPB_JANUS_OVERRIDES: - - rtp_port_range - - nat_1_1_mapping - - keep_private_host -NEXTCLOUD_HPB_IMAGE: "{{ lookup('image', application_id, NEXTCLOUD_HPB_SERVICE) }}" +NEXTCLOUD_HPB_JANUS_PORT: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.ports.internal.websocket') }}" +NEXTCLOUD_HPB_JANUS_HOST_NETWORK: "{{ NEXTCLOUD_HPB_NETWORK_MODE == 'host' }}" +NEXTCLOUD_HPB_JANUS_URL: "ws://{{ 'host.docker.internal' if NEXTCLOUD_HPB_JANUS_HOST_NETWORK | bool else NEXTCLOUD_HPB_SERVICE }}:{{ NEXTCLOUD_HPB_JANUS_PORT }}" +NEXTCLOUD_HPB_JANUS_REPOSITORY: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.repository') }}" +NEXTCLOUD_HPB_JANUS_REF: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.ref') }}" +NEXTCLOUD_HPB_JANUS_BASE_IMAGE: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.image') }}" +NEXTCLOUD_HPB_JANUS_BASE_VERSION: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.version') }}" +NEXTCLOUD_HPB_JANUS_TAG: "{{ NEXTCLOUD_HPB_JANUS_REF }}-{{ NEXTCLOUD_HPB_JANUS_BASE_VERSION }}" +NEXTCLOUD_HPB_JANUS_BUILD_DIRECTORY: "{{ [ lookup('container', application_id, 'directories.services'), 'talk-janus' ] | path_join }}" +NEXTCLOUD_HPB_JANUS_DOCKERFILE: "{{ [ NEXTCLOUD_HPB_JANUS_BUILD_DIRECTORY, 'Dockerfile' ] | path_join }}" +NEXTCLOUD_HPB_SIGNALING_SERVICE: "talk_signaling" +NEXTCLOUD_HPB_SIGNALING_CONTAINER: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SIGNALING_SERVICE ~ '.name') }}" +NEXTCLOUD_HPB_SIGNALING_VERSION: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SIGNALING_SERVICE ~ '.version') }}" NEXTCLOUD_HPB_SIGNALING_SECRET: "{{ lookup('config', application_id, 'secrets.credentials.talk_signaling_secret') }}" NEXTCLOUD_HPB_SIGNALING_LOCATION: "/standalone-signaling/" -NEXTCLOUD_HPB_SIGNALING_PORT: "{{ lookup('config', application_id, 'services.talk.ports.internal.signaling') }}" +NEXTCLOUD_HPB_SIGNALING_PORT: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SIGNALING_SERVICE ~ '.ports.internal.signaling') }}" NEXTCLOUD_HPB_SIGNALING_URL: "{{ [ NEXTCLOUD_URL, NEXTCLOUD_HPB_SIGNALING_LOCATION ] | url_join }}" NEXTCLOUD_HPB_SIGNALING_ENABLED: "{{ NEXTCLOUD_HPB_PLUGIN_ENABLED }}" +NEXTCLOUD_HPB_SIGNALING_MAX_STREAM_BITRATE: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SIGNALING_SERVICE ~ '.max_stream_bitrate') }}" +NEXTCLOUD_HPB_SIGNALING_MAX_SCREEN_BITRATE: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SIGNALING_SERVICE ~ '.max_screen_bitrate') }}" +NEXTCLOUD_HPB_SIGNALING_USER_ID: 850 +NEXTCLOUD_HPB_SIGNALING_BINARY: "/usr/bin/nextcloud-spreed-signaling" +NEXTCLOUD_HPB_SIGNALING_CONFIG_HOST: "{{ [ lookup('container', application_id, 'directories.volumes'), 'signaling.conf' ] | path_join }}" +NEXTCLOUD_HPB_SIGNALING_CONFIG_TARGET: "{{ lookup('volume', application_id, 'talk_signaling_conf').target }}" NEXTCLOUD_TALK_ADMIN_URL: "{{ [ NEXTCLOUD_URL, 'settings/admin/talk' ] | url_join }}" -NEXTCLOUD_HPB_TURN_ONBOARD_PORT: "{{ lookup('config', application_id, 'services.nextcloud.ports.public.stun_turn') }}" -NEXTCLOUD_HPB_TURN_ONBOARD_BIND_HOST: "{{ DOCKER_PUBLIC_BIND_HOST }}" -NEXTCLOUD_HPB_TURN_ONBOARD_ENABLED: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.turn_server.onboard_enabled') if NEXTCLOUD_HPB_PLUGIN_ENABLED - else false }}" -NEXTCLOUD_HPB_TURN_ONBOARD_SECRET: "{{ lookup('config', application_id, 'secrets.credentials.talk_turn_secret') }}" -NEXTCLOUD_HPB_TURN_ONBOARD_PUBLISH_PORTS: "{{ not DOCKER_IN_CONTAINER | bool }}" -NEXTCLOUD_HPB_TURN_ONBOARD_RELAY_PORT_START: "{{ lookup('config', application_id, 'services.nextcloud.ports.public.relay.start') }}" -NEXTCLOUD_HPB_TURN_ONBOARD_RELAY_PORT_END: "{{ lookup('config', application_id, 'services.nextcloud.ports.public.relay.end') }}" -NEXTCLOUD_HPB_STUN_ONBOARD_CONFIG: "{{ NEXTCLOUD_HPB_DOMAIN }}:{{ NEXTCLOUD_HPB_TURN_ONBOARD_PORT }}" -NEXTCLOUD_HPB_TURN_ONBOARD_CONFIG: >- - {{ - { - 'server': NEXTCLOUD_HPB_DOMAIN ~ ':' ~ NEXTCLOUD_HPB_TURN_ONBOARD_PORT, - 'secret': NEXTCLOUD_HPB_TURN_ONBOARD_SECRET, - 'ttl': 86400, - 'protocols': 'udp,tcp' - } - }} +NEXTCLOUD_HPB_NATS_SERVICE: "talk_nats" +NEXTCLOUD_HPB_NATS_CONTAINER: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_NATS_SERVICE ~ '.name') }}" +NEXTCLOUD_HPB_NATS_PORT: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_NATS_SERVICE ~ '.ports.internal.nats') }}" +NEXTCLOUD_HPB_NATS_MONITOR_PORT: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_NATS_SERVICE ~ '.ports.internal.http') }}" +NEXTCLOUD_HPB_NATS_URL: "nats://{{ NEXTCLOUD_HPB_NATS_SERVICE }}:{{ NEXTCLOUD_HPB_NATS_PORT }}" +NEXTCLOUD_HPB_NATS_USER_ID: 65534 NEXTCLOUD_HPB_TURN_STANDALONE_ROLE: "web-svc-coturn" NEXTCLOUD_HPB_TURN_STANDALONE_PORT: "{{ lookup('config', NEXTCLOUD_HPB_TURN_STANDALONE_ROLE, 'services.coturn.ports.public.stun_turn') }}" @@ -221,26 +222,8 @@ NEXTCLOUD_HPB_TURN_STANDALONE_CONFIG: >- 'protocols': 'udp,tcp' } }} -NEXTCLOUD_HPB_STUN_ACTIVE_CONFIG: >- - {{ - NEXTCLOUD_HPB_STUN_STANDALONE_CONFIG - if NEXTCLOUD_HPB_TURN_STANDALONE_ENABLED | bool - else ( - NEXTCLOUD_HPB_STUN_ONBOARD_CONFIG - if NEXTCLOUD_HPB_TURN_ONBOARD_ENABLED | bool - else '' - ) - }} -NEXTCLOUD_HPB_TURN_ACTIVE_CONFIG: >- - {{ - NEXTCLOUD_HPB_TURN_STANDALONE_CONFIG - if NEXTCLOUD_HPB_TURN_STANDALONE_ENABLED | bool - else ( - NEXTCLOUD_HPB_TURN_ONBOARD_CONFIG - if NEXTCLOUD_HPB_TURN_ONBOARD_ENABLED | bool - else {} - ) - }} +NEXTCLOUD_HPB_STUN_ACTIVE_CONFIG: "{{ NEXTCLOUD_HPB_STUN_STANDALONE_CONFIG if NEXTCLOUD_HPB_TURN_STANDALONE_ENABLED | bool else '' }}" +NEXTCLOUD_HPB_TURN_ACTIVE_CONFIG: "{{ NEXTCLOUD_HPB_TURN_STANDALONE_CONFIG if NEXTCLOUD_HPB_TURN_STANDALONE_ENABLED | bool else {} }}" NEXTCLOUD_HPB_TURN_ACTIVE_SERVER: "{{ NEXTCLOUD_HPB_TURN_ACTIVE_CONFIG.server | default('') }}" NEXTCLOUD_WHITEBOARD_SERVICE: "whiteboard" @@ -261,6 +244,18 @@ NEXTCLOUD_RECORDING_CONTAINER: "{{ lookup('config', application_id, 'services.' NEXTCLOUD_RECORDING_ENABLED: "{{ NEXTCLOUD_HPB_PLUGIN_ENABLED }}" NEXTCLOUD_RECORDING_PORT: "{{ lookup('config', application_id, 'services.talk_recording.ports.internal.recording') }}" NEXTCLOUD_RECORDING_SECRET: "{{ lookup('config', application_id, 'secrets.credentials.talk_recording_secret') }}" +NEXTCLOUD_RECORDING_REPOSITORY: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_RECORDING_SERVICE ~ '.repository') }}" +NEXTCLOUD_RECORDING_REF: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_RECORDING_SERVICE ~ '.ref') }}" +NEXTCLOUD_RECORDING_BASE_IMAGE: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_RECORDING_SERVICE ~ '.image') }}" +NEXTCLOUD_RECORDING_BASE_VERSION: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_RECORDING_SERVICE ~ '.version') }}" +NEXTCLOUD_RECORDING_TAG: "{{ NEXTCLOUD_RECORDING_REF }}-{{ NEXTCLOUD_RECORDING_BASE_VERSION }}" +NEXTCLOUD_RECORDING_BUILD_DIRECTORY: "{{ [ lookup('container', application_id, 'directories.services'), 'talk-recording' ] | path_join }}" +NEXTCLOUD_RECORDING_DOCKERFILE: "{{ [ NEXTCLOUD_RECORDING_BUILD_DIRECTORY, 'Dockerfile' ] | path_join }}" +NEXTCLOUD_RECORDING_USER_ID: 122 +NEXTCLOUD_RECORDING_CONFIG_HOST: "{{ [ lookup('container', application_id, 'directories.volumes'), 'recording.conf' ] | path_join }}" +NEXTCLOUD_RECORDING_CONFIG_TARGET: "{{ lookup('volume', application_id, 'talk_recording_conf').target }}" +NEXTCLOUD_RECORDING_DIRECTORY: "{{ lookup('volume', application_id, 'talk_recording_tmp').target }}" +NEXTCLOUD_RECORDING_CA_CERT: "{{ CA_TRUST.inject_cert_container if lookup('ca_injected', application_id) else '' }}" NEXTCLOUD_COLLABORA_URL: "{{ lookup('tls', 'web-svc-collabora', 'url.base') }}" diff --git a/tests/unit/python/roles/web-app-nextcloud/filter_plugins/test_nextcloud_janus.py b/tests/unit/python/roles/web-app-nextcloud/filter_plugins/test_nextcloud_janus.py deleted file mode 100644 index 1b0d72af21..0000000000 --- a/tests/unit/python/roles/web-app-nextcloud/filter_plugins/test_nextcloud_janus.py +++ /dev/null @@ -1,138 +0,0 @@ -from __future__ import annotations - -import importlib.util -import sys -import unittest - -from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape - -from . import PROJECT_ROOT - -OVERRIDES = ("rtp_port_range", "nat_1_1_mapping", "keep_private_host") -TARGET = "/usr/local/etc/janus/janus.jcfg" -LAUNCHER = ( - "[program:janus]\n" - "command=janus --config=/usr/local/etc/janus/janus.jcfg --disable-colors" - " --log-stdout --full-trickle --debug-level 3\n" -) - - -def _load_module(rel_path: str, name: str): - path = PROJECT_ROOT / rel_path - spec = importlib.util.spec_from_file_location(name, str(path)) - mod = importlib.util.module_from_spec(spec) - assert spec and spec.loader - sys.modules[name] = mod - spec.loader.exec_module(mod) - return mod - - -MODULE = _load_module( - "roles/web-app-nextcloud/filter_plugins/nextcloud_janus.py", "nextcloud_janus" -) - - -def _rendered_template() -> str: - env = Environment( - loader=FileSystemLoader( - str(PROJECT_ROOT / "roles/web-app-nextcloud/templates") - ), - undefined=StrictUndefined, - keep_trailing_newline=True, - autoescape=select_autoescape(default_for_string=False), - ) - return env.get_template("janus.jcfg.j2").render( - NEXTCLOUD_HPB_MEDIA_PORT_START=61000, - NEXTCLOUD_HPB_MEDIA_PORT_END=61999, - NEXTCLOUD_HPB_MEDIA_PUBLIC_IP="203.0.113.7", - ) - - -def _stock_like() -> str: - lines = ["/* a block comment the image ships", " over two lines */"] - for line in _rendered_template().splitlines(): - if line.strip().split(" ", 1)[0] in OVERRIDES: - lines.append("\t#" + line.strip() + "\t\t# commented out upstream") - continue - lines.append("\t\t# a comment line the image ships") - lines.append(line.replace(" = ", " = ") + "\t// trailing remark") - return "\n".join(lines) + "\n" - - -def _drift(stock: str, launcher: str = LAUNCHER) -> list[str]: - return MODULE.janus_config_drift( - _rendered_template(), stock, OVERRIDES, launcher, TARGET - ) - - -class TestJanusSettings(unittest.TestCase): - def test_comments_and_blank_lines_are_dropped(self): - content = "# head\n\ngeneral: {\n\tdebug_level = 4\t\t# level\n}\n" - self.assertEqual( - MODULE.janus_settings(content, []), ["general:{", "debug_level=4", "}"] - ) - - def test_block_comments_and_a_trailing_semicolon_are_dropped(self): - content = "/* head\n tail */\ndebug_level = 4; /* level */\n" - self.assertEqual(MODULE.janus_settings(content, []), ["debug_level=4"]) - - def test_a_hash_inside_a_quoted_value_is_kept(self): - content = 'log_prefix = "[janus] #1" # prefix\n' - self.assertEqual( - MODULE.janus_settings(content, []), ['log_prefix="[janus] #1"'] - ) - - def test_named_overrides_are_left_out(self): - content = 'nat: {\n\tnat_1_1_mapping = "1.2.3.4"\n\tnice_debug = false\n}\n' - self.assertEqual( - MODULE.janus_settings(content, ["nat_1_1_mapping"]), - ["nat:{", "nice_debug=false", "}"], - ) - - def test_the_template_sets_every_override_once(self): - keys = [ - setting.split("=", 1)[0] - for setting in MODULE.janus_settings(_rendered_template(), []) - ] - for override in OVERRIDES: - self.assertEqual(keys.count(override), 1, override) - - -class TestJanusConfigDrift(unittest.TestCase): - def test_a_stock_file_that_differs_only_in_comments_and_layout_passes(self): - self.assertEqual(_drift(_stock_like()), []) - - def test_a_moved_plugin_folder_stops_the_deploy(self): - stock = _stock_like().replace( - '"/usr/local/lib/janus/plugins"', '"/usr/lib/janus/plugins"' - ) - self.assertEqual(len(_drift(stock)), 1) - - def test_an_upstream_value_for_a_masked_key_stops_the_deploy(self): - stock = _stock_like().replace("\t#rtp_port_range", "\trtp_port_range", 1) - self.assertEqual(len(_drift(stock)), 1) - - def test_a_setting_upstream_added_stops_the_deploy(self): - stock = _stock_like().replace("nat: {", "nat: {\n\tice_tcp = true", 1) - self.assertEqual(len(_drift(stock)), 1) - - def test_an_empty_read_stops_the_deploy(self): - self.assertEqual(len(_drift("")), 1) - - def test_janus_reading_a_generated_config_stops_the_deploy(self): - launcher = LAUNCHER.replace(TARGET, "/conf/janus.jcfg") - self.assertEqual( - _drift(_stock_like(), launcher), - [f"Janus is not started with --config={TARGET}"], - ) - - def test_a_config_path_that_only_shares_the_prefix_stops_the_deploy(self): - launcher = LAUNCHER.replace(f"{TARGET} ", f"{TARGET}.generated ") - self.assertEqual(len(_drift(_stock_like(), launcher)), 1) - - def test_a_launcher_without_janus_stops_the_deploy(self): - self.assertEqual(len(_drift(_stock_like(), "")), 1) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/unit/python/roles/web-app-nextcloud/test_talk_configs.py b/tests/unit/python/roles/web-app-nextcloud/test_talk_configs.py new file mode 100644 index 0000000000..5c99d89ba0 --- /dev/null +++ b/tests/unit/python/roles/web-app-nextcloud/test_talk_configs.py @@ -0,0 +1,381 @@ +from __future__ import annotations + +import configparser +import hashlib +import posixpath +import re +import unittest +from typing import ClassVar + +from jinja2 import Environment, StrictUndefined, select_autoescape + +from utils.cache.files import PROJECT_ROOT, read_text + +TEMPLATES = PROJECT_ROOT / "roles" / "web-app-nextcloud" / "templates" +FILES = PROJECT_ROOT / "roles" / "web-app-nextcloud" / "files" + +SIGNALING_SECRET = "base64:signaling-fixture-secret" +INTERNAL_SECRET = "base64:internal-fixture-secret" +RECORDING_SECRET = "recording-fixture-secret" + +VARIABLES = { + "NEXTCLOUD_HPB_SIGNALING_PORT": 8081, + "NEXTCLOUD_HPB_SIGNALING_SECRET": SIGNALING_SECRET, + "NEXTCLOUD_HPB_INTERNAL_SECRET": INTERNAL_SECRET, + "NEXTCLOUD_HPB_BACKEND_URL": "https://next.example.org", + "NEXTCLOUD_HPB_SIGNALING_LOCATION": "/standalone-signaling/", + "NEXTCLOUD_HPB_SIGNALING_MAX_STREAM_BITRATE": 1048576, + "NEXTCLOUD_HPB_SIGNALING_MAX_SCREEN_BITRATE": 2097152, + "NEXTCLOUD_HPB_NATS_URL": "nats://talk_nats:4222", + "NEXTCLOUD_HPB_JANUS_URL": "ws://talk:8188", + "NEXTCLOUD_RECORDING_PORT": 1234, + "NEXTCLOUD_RECORDING_SECRET": RECORDING_SECRET, + "NEXTCLOUD_RECORDING_DIRECTORY": "/tmp", + "NEXTCLOUD_HPB_MEDIA_PORT_START": 61000, + "NEXTCLOUD_HPB_MEDIA_PORT_END": 61999, + "NEXTCLOUD_HPB_MEDIA_PUBLIC_IP": "203.0.113.7", + "NEXTCLOUD_HPB_JANUS_BASE_IMAGE": "alpine", + "NEXTCLOUD_HPB_JANUS_BASE_VERSION": "3.23.3", + "NEXTCLOUD_HPB_JANUS_REPOSITORY": "https://github.com/meetecho/janus-gateway.git", + "NEXTCLOUD_HPB_JANUS_REF": "v1.4.0", + "NEXTCLOUD_HPB_JANUS_CONFIG_TARGET": "/usr/local/etc/janus/janus.jcfg", + "NEXTCLOUD_RECORDING_BASE_IMAGE": "python", + "NEXTCLOUD_RECORDING_BASE_VERSION": "3.14.3-alpine3.23", + "NEXTCLOUD_RECORDING_REPOSITORY": "https://github.com/nextcloud/nextcloud-talk-recording.git", + "NEXTCLOUD_RECORDING_REF": "v0.2.1", + "NEXTCLOUD_RECORDING_USER_ID": 122, + "NEXTCLOUD_RECORDING_CONFIG_TARGET": "/conf/recording.conf", + "NEXTCLOUD_RECORDING_CA_CERT": "/tmp/infinito/ca/root-ca.crt", +} + +AIO_SIGNALING = { + "http": {"listen": "0.0.0.0:8081"}, + "app": {"debug": "false"}, + "clients": {"internalsecret": INTERNAL_SECRET}, + "backend": { + "backends": "backend-1", + "allowall": "false", + "timeout": "10", + "connectionsperhost": "8", + "skipverify": "false", + }, + "backend-1": { + "urls": "https://next.example.org", + "secret": SIGNALING_SECRET, + "maxstreambitrate": "1048576", + "maxscreenbitrate": "2097152", + }, + "nats": {"url": "nats://127.0.0.1:4222"}, + "mcu": { + "type": "janus", + "url": "ws://127.0.0.1:8188", + "maxstreambitrate": "1048576", + "maxscreenbitrate": "2097152", + }, +} + +AIO_RECORDING = { + "logs": {"level": "30"}, + "http": {"listen": "0.0.0.0:1234"}, + "backend": { + "allowall": "false", + "secret": RECORDING_SECRET, + "backends": "backend-1", + "skipverify": "false", + "maxmessagesize": "1024", + "videowidth": "1920", + "videoheight": "1080", + "directory": "/tmp", + }, + "backend-1": { + "url": "https://next.example.org", + "secret": RECORDING_SECRET, + "skipverify": "false", + }, + "signaling": {"signalings": "signaling-1"}, + "signaling-1": { + "url": "https://next.example.org/standalone-signaling/", + "internalsecret": INTERNAL_SECRET, + }, + "ffmpeg": {"extensionaudio": ".ogg", "extensionvideo": ".webm"}, + "recording": { + "browser": "firefox", + "driverPath": "/usr/bin/geckodriver", + "browserPath": "/usr/bin/firefox", + }, +} + +STOCK_JANUS = [ + "general:{", + 'configs_folder="/usr/local/etc/janus"', + 'plugins_folder="/usr/local/lib/janus/plugins"', + 'transports_folder="/usr/local/lib/janus/transports"', + 'events_folder="/usr/local/lib/janus/events"', + 'loggers_folder="/usr/local/lib/janus/loggers"', + "debug_level=4", + 'admin_secret="janusoverlord"', + "protected_folders=[", + *[ + f'"{folder}",' + for folder in ( + "/bin", + "/boot", + "/dev", + "/etc", + "/initrd", + "/lib", + "/lib32", + "/lib64", + "/proc", + "/sbin", + "/sys", + "/usr", + "/var", + "/opt/janus/bin", + "/opt/janus/etc", + "/opt/janus/include", + "/opt/janus/lib", + "/opt/janus/lib32", + "/opt/janus/lib64", + ) + ], + '"/opt/janus/sbin"', + "]", + "}", + "certificates:{", + "}", + "media:{", + "}", + "nat:{", + 'ice_ignore_list="vmnet"', + "}", + "plugins:{", + "}", + "transports:{", + "}", + "loggers:{", + "}", + "events:{", + "}", +] + + +def _render(source: str, **overrides) -> str: + env = Environment( + trim_blocks=True, + keep_trailing_newline=True, + undefined=StrictUndefined, + autoescape=select_autoescape(default_for_string=False), + ) + env.filters["hash"] = lambda value, algorithm: hashlib.new( + algorithm, str(value).encode() + ).hexdigest() + env.filters["bool"] = bool + env.filters["dirname"] = posixpath.dirname + return env.from_string(source).render({**VARIABLES, **overrides}) + + +def _template(name: str) -> str: + return read_text(str(TEMPLATES / name)) + + +def _build_args(dockerfile: str) -> str: + compose = _template("compose.yml.j2") + args: dict[str, str] = {} + for arg in re.findall(r"^ARG (\w+)$", dockerfile, re.MULTILINE): + passed = re.search(rf'^\s+{arg}: "(.*)"$', compose, re.MULTILINE) + if passed is None: + raise AssertionError(f"compose.yml.j2 passes no build arg {arg}") + args[arg] = _render(passed.group(1)) + return re.sub(r"\$\{(\w+)\}", lambda match: args[match.group(1)], dockerfile) + + +def _build(name: str) -> str: + return _build_args(read_text(str(FILES / "Dockerfiles" / name / "Dockerfile"))) + + +def _ini(text: str) -> dict[str, dict[str, str]]: + parser = configparser.ConfigParser(interpolation=None, strict=True) + parser.optionxform = str + parser.read_string(text) + return {section: dict(parser[section]) for section in parser.sections()} + + +def _settings(text: str) -> list[str]: + return [joined for line in text.splitlines() if (joined := "".join(line.split()))] + + +class TestSignalingConfig(unittest.TestCase): + def test_matches_what_the_aio_start_script_wrote_apart_from_the_split(self): + rendered = _ini(_render(_template("signaling.conf.j2"))) + sessions = rendered.pop("sessions") + expected = { + **AIO_SIGNALING, + "nats": {"url": "nats://talk_nats:4222"}, + "mcu": {**AIO_SIGNALING["mcu"], "url": "ws://talk:8188"}, + } + self.assertEqual(rendered, expected) + self.assertEqual(sorted(sessions), ["blockkey", "hashkey"]) + + def test_session_keys_have_the_shape_aio_generated_and_stay_stable(self): + first = _ini(_render(_template("signaling.conf.j2")))["sessions"] + second = _ini(_render(_template("signaling.conf.j2")))["sessions"] + self.assertEqual(first, second) + for key in ("hashkey", "blockkey"): + self.assertRegex(first[key], r"^[0-9a-f]{32}$") + self.assertNotEqual(first["hashkey"], first["blockkey"]) + self.assertNotIn(first["hashkey"], SIGNALING_SECRET) + + def test_negative_control_another_signaling_secret_changes_the_keys(self): + first = _ini(_render(_template("signaling.conf.j2")))["sessions"] + other = _ini( + _render( + _template("signaling.conf.j2"), + NEXTCLOUD_HPB_SIGNALING_SECRET="base64:another-secret", + ) + )["sessions"] + self.assertNotEqual(first["hashkey"], other["hashkey"]) + self.assertNotEqual(first["blockkey"], other["blockkey"]) + + def test_negative_control_a_changed_setting_breaks_parity(self): + drifted = _template("signaling.conf.j2").replace( + "allowall = false", "allowall = true" + ) + self.assertNotEqual(drifted, _template("signaling.conf.j2")) + rendered = _ini(_render(drifted)) + rendered.pop("sessions") + self.assertNotEqual(rendered["backend"], AIO_SIGNALING["backend"]) + + +class TestRecordingConfig(unittest.TestCase): + def test_matches_what_the_aio_start_script_wrote(self): + self.assertEqual(_ini(_render(_template("recording.conf.j2"))), AIO_RECORDING) + + def test_negative_control_a_dropped_setting_breaks_parity(self): + drifted = _template("recording.conf.j2").replace("maxmessagesize = 1024\n", "") + self.assertNotEqual(drifted, _template("recording.conf.j2")) + self.assertNotEqual(_ini(_render(drifted)), AIO_RECORDING) + + +class TestJanusConfig(unittest.TestCase): + def test_without_direct_media_it_equals_the_stock_janus_config(self): + rendered = _render(_template("janus.jcfg.j2"), NEXTCLOUD_HPB_MEDIA_DIRECT=False) + self.assertEqual(_settings(rendered), STOCK_JANUS) + + def test_direct_media_adds_exactly_the_three_overrides(self): + rendered = _settings( + _render(_template("janus.jcfg.j2"), NEXTCLOUD_HPB_MEDIA_DIRECT=True) + ) + expected = list(STOCK_JANUS) + expected.insert(expected.index("media:{") + 1, 'rtp_port_range="61000-61999"') + expected.insert(expected.index("nat:{") + 1, 'nat_1_1_mapping="203.0.113.7"') + expected.insert(expected.index("nat:{") + 2, "keep_private_host=true") + self.assertEqual(rendered, expected) + + def test_negative_control_an_unguarded_override_breaks_the_stock_config(self): + drifted = _template("janus.jcfg.j2").replace( + "{% if NEXTCLOUD_HPB_MEDIA_DIRECT | bool %}\n\trtp_port_range", + "{% if true %}\n\trtp_port_range", + ) + self.assertNotEqual(drifted, _template("janus.jcfg.j2")) + rendered = _render(drifted, NEXTCLOUD_HPB_MEDIA_DIRECT=False) + self.assertNotEqual(_settings(rendered), STOCK_JANUS) + + +class TestTalkDockerfiles(unittest.TestCase): + AIO_JANUS_BUILD_PACKAGES: ClassVar[list[str]] = [ + "ca-certificates", + "git", + "autoconf", + "automake", + "build-base", + "pkgconfig", + "libtool", + "util-linux", + "glib-dev", + "zlib-dev", + "openssl-dev", + "jansson-dev", + "libnice-dev", + "libconfig-dev", + "libsrtp-dev", + "libusrsctp-dev", + "gengetopt-dev", + "libwebsockets-dev", + ] + + def test_janus_builds_the_pinned_tag_on_the_pinned_base(self): + rendered = _build("Janus") + self.assertEqual( + re.findall(r"^FROM (\S+)", rendered, re.MULTILINE), + ["alpine:3.23.3", "alpine:3.23.3"], + ) + self.assertIn( + 'git clone --recursive "https://github.com/meetecho/janus-gateway.git" ' + '--depth=1 --single-branch --branch "v1.4.0" /src', + rendered, + ) + self.assertIn( + "/src/configure --disable-rabbitmq --disable-mqtt --disable-boringssl", + rendered, + ) + build_stage = rendered.split("\nFROM ")[1] + for package in self.AIO_JANUS_BUILD_PACKAGES: + with self.subTest(package=package): + self.assertRegex(build_stage, rf"\n\s+{re.escape(package)}( \\|;)") + self.assertIn( + 'ENTRYPOINT ["janus", "--disable-colors", "--log-stdout", ' + '"--full-trickle", "--debug-level", "3"]', + rendered, + ) + + def test_recording_installs_the_pinned_release_on_the_pinned_base(self): + rendered = _build("Recording") + self.assertEqual( + re.findall(r"^FROM (\S+)", rendered, re.MULTILINE), + ["python:3.14.3-alpine3.23"], + ) + self.assertIn( + 'git clone --recursive "https://github.com/nextcloud/nextcloud-talk-recording.git" ' + '--depth=1 --single-branch --branch "v0.2.1" /src', + rendered, + ) + self.assertIn('useradd -d "/tmp" --system recording -u "122"', rendered) + self.assertIn('mkdir -p "/conf"', rendered) + self.assertIn( + """printf '{"policies":{"Certificates":{"Install":["%s"]}}}\\n' """ + '"/tmp/infinito/ca/root-ca.crt" > /etc/firefox/policies/policies.json', + rendered, + ) + self.assertIn("USER 122", rendered) + self.assertIn( + 'ENTRYPOINT ["python", "-m", "nextcloud.talk.recording"]', rendered + ) + + def test_the_compose_command_points_each_binary_at_its_rendered_config(self): + compose = _template("compose.yml.j2") + self.assertIn( + 'command: ["--config={{ NEXTCLOUD_HPB_JANUS_CONFIG_TARGET }}"]', compose + ) + self.assertIn( + 'command: ["--config", "{{ NEXTCLOUD_RECORDING_CONFIG_TARGET }}"]', compose + ) + + def test_no_image_ships_a_start_script_that_writes_its_config(self): + for name in ("Janus", "Recording"): + with self.subTest(dockerfile=name): + rendered = _build(name) + self.assertNotRegex(rendered, r"ENTRYPOINT \[\"[^\"]*\.sh\"") + self.assertNotIn( + "COPY", + rendered.split("\nFROM ")[-1].replace("COPY --from=build", ""), + ) + self.assertNotIn("SECRET", rendered) + + def test_negative_control_an_arg_compose_does_not_pass_fails_the_build(self): + with self.assertRaisesRegex(AssertionError, "JANUS_UNPASSED"): + _build_args("ARG JANUS_UNPASSED\nFROM ${JANUS_UNPASSED}\n") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py b/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py index e16d9d6e7d..0c8dae4f7a 100644 --- a/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py +++ b/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py @@ -28,48 +28,100 @@ ROLE = "roles/web-app-nextcloud" TEMPLATE = f"{ROLE}/{ROLE_FILE_TEMPL_COMPOSE}" PUBLIC_IP = "203.0.113.7" SERVICES = load_yaml_any(str(PROJECT_ROOT / ROLE / ROLE_FILE_META_SERVICES)) +TALK_SERVICES = ("talk", "talk_signaling", "talk_nats", "talk_recording") -LEGACY_BRIDGE_ONBOARD = """ talk: +JANUS_HEAD = """ talk: - - + build: + context: + dockerfile: Dockerfile + args: + JANUS_BASE_IMAGE: "" + JANUS_BASE_VERSION: "" + JANUS_REPOSITORY: "" + JANUS_REF: "" + + }> )> + command: ["--config="] init: true - ports: - - "203.0.113.7:3480:3480/tcp" - - "203.0.113.7:3480:3480/udp" - - "203.0.113.7:50000-59999:50000-59999/udp" - - "203.0.113.7:50000-59999:50000-59999/tcp" + + \n configs: + - source: janus_conf + target: /usr/local/etc/janus/janus.jcfg + mode: 292""" + +JANUS_HOST = JANUS_HEAD + "\n network_mode: host" + +JANUS_BRIDGE = ( + JANUS_HEAD + + """ expose: - - "8081" - """ - -LEGACY_BRIDGE = """ talk: - - - - )> - init: true - expose: - - "8081" - """ - -LEGACY_HOST = """ talk: - - - - )> - init: true - network_mode: host""" - -DIRECT_MOUNT = ( - " \n" - " configs:\n" - " - source: janus_conf\n" - " target: /usr/local/etc/janus/janus.jcfg" + - "" + """ ) -DIRECT_PORT = ' - "203.0.113.7:61000-61999:61000-61999/udp"' +DIRECT_PORT = ( + ' ports:\n - "203.0.113.7:61000-61999:61000-61999/udp"\n expose:' +) + +SIGNALING = """ talk_signaling: + + + )> + user: ":" + command: ["", "-config", ""] + + \n secrets: + - source: talk_signaling_conf + target: /config/server.conf + mode: 292 + expose: + - "" + + """ + +NATS = """ talk_nats: + + + )> + user: ":" + command: ["nats-server", "--addr", "0.0.0.0", "--port", "", "--http_port", ""] + + expose: + - "" + """ + +RECORDING = """ talk_recording: + + build: + context: + dockerfile: Dockerfile + args: + RECORDING_BASE_IMAGE: "" + RECORDING_BASE_VERSION: "" + RECORDING_REPOSITORY: "" + RECORDING_REF: "" + RECORDING_USER_ID: "" + RECORDING_DIRECTORY: "" + RECORDING_CONFIG_DIRECTORY: ">" + RECORDING_CA_CERT: "" + + }> + )> + command: ["--config", ""] + environment: + TZ: "" + + expose: + - "" + + \n volumes: + - talk_recording_tmp:/tmp + secrets: + - source: talk_recording_conf + target: /conf/recording.conf + mode: 292""" class _Marker(ChainableUndefined): @@ -87,9 +139,7 @@ def _bool(value): return str(value).strip().lower() in {"y", "yes", "true", "on", "1"} -def _render( - template_text: str, *, onboard: bool, direct: bool, mode: str, network: str -) -> str: +def _render(template_text: str, *, direct: bool, mode: str, network: str) -> str: applications = {"web-app-nextcloud": {"services": SERVICES}} env = Environment( loader=ChoiceLoader( @@ -113,6 +163,7 @@ def _render( ) env.filters["bool"] = _bool env.filters["path_join"] = lambda parts: "/".join(str(part) for part in parts) + env.filters["dirname"] = lambda value: f"" variables = { "application_id": "web-app-nextcloud", "NEXTCLOUD_PROXY_SERVICE": "proxy", @@ -122,11 +173,12 @@ def _render( "DEPLOYMENT_MODE": mode, "NEXTCLOUD_HPB_SIGNALING_ENABLED": True, "NEXTCLOUD_HPB_SERVICE": "talk", - "NEXTCLOUD_HPB_SIGNALING_PORT": 8081, + "NEXTCLOUD_HPB_SIGNALING_SERVICE": "talk_signaling", + "NEXTCLOUD_HPB_NATS_SERVICE": "talk_nats", + "NEXTCLOUD_RECORDING_SERVICE": "talk_recording", + "NEXTCLOUD_RECORDING_ENABLED": True, "NEXTCLOUD_HPB_NETWORK_MODE": network, - "NEXTCLOUD_HPB_TURN_ONBOARD_ENABLED": onboard, - "NEXTCLOUD_HPB_TURN_ONBOARD_PUBLISH_PORTS": True, - "NEXTCLOUD_HPB_TURN_ONBOARD_BIND_HOST": PUBLIC_IP, + "NEXTCLOUD_HPB_JANUS_HOST_NETWORK": network == "host", "NEXTCLOUD_HPB_MEDIA_DIRECT": direct, "NEXTCLOUD_HPB_MEDIA_PUBLIC_IP": PUBLIC_IP, } @@ -144,7 +196,10 @@ def _render( def lookup(name, *args, **kwargs): if name == "config": - return {"services.talk.direct_media": direct}[args[1]] + return { + "services.talk.direct_media": direct, + "services.talk.enabled": True, + }[args[1]] if name == "container_ports": with mock.patch.object(container_ports_lookup, "lookup_loader", _Loader()): return container_ports_lookup.LookupModule().run( @@ -155,15 +210,16 @@ def _render( applications, "web-app-nextcloud", args[0], render_jinja=render_jinja ) return "\n" + block if block else block - return f"" + suffix = f" {dict(sorted(kwargs.items()))!r}" if kwargs else "" + return f"" env.globals["lookup"] = lookup return env.get_template("compose.yml.j2").render(variables) -def _talk_block(rendered: str) -> str: +def _block(rendered: str, service: str) -> str: lines = rendered.splitlines() - start = lines.index(" talk:") + start = lines.index(f" {service}:") end = next( index for index in range(start + 1, len(lines)) @@ -172,72 +228,80 @@ def _talk_block(rendered: str) -> str: return "\n".join(lines[start:end]).rstrip() -def _cells(direct: bool): - for onboard, mode, network in itertools.product( +def _cells(): + for direct, mode, network in itertools.product( (True, False), ("compose", "swarm"), ("bridge", "host") ): - yield {"onboard": onboard, "direct": direct, "mode": mode, "network": network} + yield {"direct": direct, "mode": mode, "network": network} -def _legacy(cell) -> str: - if cell["network"] == "host": - return LEGACY_HOST - return LEGACY_BRIDGE_ONBOARD if cell["onboard"] else LEGACY_BRIDGE +def _expected_janus(cell) -> str: + if cell["mode"] == "compose" and cell["network"] == "host": + return JANUS_HOST + if cell["direct"]: + return JANUS_BRIDGE.replace(" expose:", DIRECT_PORT) + return JANUS_BRIDGE -class TestTalkComposeBlock(unittest.TestCase): - def test_every_cell_without_direct_media_renders_the_legacy_block(self): - template = read_text(str(PROJECT_ROOT / TEMPLATE)) - for cell in _cells(direct=False): +def _template() -> str: + return read_text(str(PROJECT_ROOT / TEMPLATE)) + + +class TestTalkComposeBlocks(unittest.TestCase): + def test_janus_block_follows_network_mode_and_direct_media(self): + for cell in _cells(): with self.subTest(**cell): - self.assertEqual(_talk_block(_render(template, **cell)), _legacy(cell)) - - def test_host_networking_ignores_direct_media(self): - template = read_text(str(PROJECT_ROOT / TEMPLATE)) - for cell in _cells(direct=True): - if cell["network"] == "host": - with self.subTest(**cell): - self.assertEqual( - _talk_block(_render(template, **cell)), LEGACY_HOST - ) - - def test_direct_media_adds_only_the_janus_mount_and_the_udp_range(self): - template = read_text(str(PROJECT_ROOT / TEMPLATE)) - for cell in _cells(direct=True): - if cell["network"] != "bridge": - continue - with self.subTest(**cell): - block = _talk_block(_render(template, **cell)) - legacy = _legacy(cell) - expected = legacy.replace( - " init: true", " init: true\n" + DIRECT_MOUNT + self.assertEqual( + _block(_render(_template(), **cell), "talk"), _expected_janus(cell) ) - if cell["onboard"]: - expected = expected.replace( - " expose:", DIRECT_PORT + "\n expose:" - ) - else: - expected = expected.replace( - " expose:", " ports:\n" + DIRECT_PORT + "\n expose:" - ) - self.assertEqual(block, expected) - def test_negative_control_an_unguarded_mount_breaks_the_legacy_block(self): - template = read_text(str(PROJECT_ROOT / TEMPLATE)).replace( - " {% if NEXTCLOUD_HPB_MEDIA_DIRECT | bool %}\n" - " {{ lookup('container_volumes', service_name) | indent(4) }}\n", - " {{ lookup('container_volumes', service_name) | indent(4) }}\n" - " {% if NEXTCLOUD_HPB_MEDIA_DIRECT | bool %}\n", + def test_signaling_block_is_the_same_in_every_cell(self): + for cell in _cells(): + with self.subTest(**cell): + expected = SIGNALING.replace( + "{host_alias}", str(cell["network"] == "host") + ) + self.assertEqual( + _block(_render(_template(), **cell), "talk_signaling"), expected + ) + + def test_nats_and_recording_blocks_are_the_same_in_every_cell(self): + for cell in _cells(): + with self.subTest(**cell): + rendered = _render(_template(), **cell) + self.assertEqual(_block(rendered, "talk_nats"), NATS) + self.assertEqual(_block(rendered, "talk_recording"), RECORDING) + + def test_no_talk_service_passes_a_secret_through_compose(self): + for cell in _cells(): + rendered = _render(_template(), **cell) + for service in TALK_SERVICES: + with self.subTest(service=service, **cell): + self.assertNotIn("SECRET", _block(rendered, service)) + + def test_negative_control_an_ungated_host_network_reaches_swarm(self): + template = _template().replace( + "{% if DEPLOYMENT_MODE == 'compose' and NEXTCLOUD_HPB_JANUS_HOST_NETWORK | bool %}", + "{% if NEXTCLOUD_HPB_JANUS_HOST_NETWORK | bool %}", ) - cell = { - "onboard": False, - "direct": False, - "mode": "compose", - "network": "bridge", - } - rendered = _render(template, **cell) - self.assertNotIn("janus_conf", rendered) - self.assertNotEqual(_talk_block(rendered), _legacy(cell)) + cell = {"direct": False, "mode": "swarm", "network": "host"} + self.assertNotEqual(template, _template()) + block = _block(_render(template, **cell), "talk") + self.assertIn("network_mode: host", block) + self.assertNotEqual(block, _expected_janus(cell)) + + def test_negative_control_a_secret_in_the_environment_is_caught(self): + template = _template().replace( + ' TZ: "{{ HOST_TIMEZONE }}"', + ' TZ: "{{ HOST_TIMEZONE }}"\n' + ' RECORDING_SECRET: "{{ NEXTCLOUD_RECORDING_SECRET }}"', + ) + self.assertNotEqual(template, _template()) + block = _block( + _render(template, direct=False, mode="compose", network="bridge"), + "talk_recording", + ) + self.assertIn("SECRET", block) ROLE_VARS = load_yaml_any(str(PROJECT_ROOT / ROLE / ROLE_FILE_VARS_MAIN)) @@ -294,9 +358,9 @@ class TestDirectMediaFlag(unittest.TestCase): def test_opting_in_with_standalone_turn_and_an_owned_address_turns_it_on(self): self.assertIs(_direct_media(list(STANDALONE_TURN), applications=OPTED_IN), True) - def test_host_networking_keeps_it_off(self): + def test_host_networking_keeps_it_on(self): host = _talk(direct_media=True, network_mode="host") - self.assertIs(_direct_media(list(STANDALONE_TURN), applications=host), False) + self.assertIs(_direct_media(list(STANDALONE_TURN), applications=host), True) def test_an_address_the_host_does_not_own_keeps_it_off(self): self.assertIs( @@ -318,7 +382,7 @@ class TestDirectMediaFlag(unittest.TestCase): False, ) - def test_onboard_turn_keeps_it_off(self): + def test_talk_without_coturn_keeps_it_off(self): forced = _talk(enabled=True, direct_media=True) self.assertIs(_direct_media(["web-app-nextcloud"], applications=forced), False) diff --git a/tests/unit/python/roles/web-app-nextcloud/test_talk_version_pins.py b/tests/unit/python/roles/web-app-nextcloud/test_talk_version_pins.py new file mode 100644 index 0000000000..fddc1a2e78 --- /dev/null +++ b/tests/unit/python/roles/web-app-nextcloud/test_talk_version_pins.py @@ -0,0 +1,137 @@ +from __future__ import annotations + +import os +import re +import unittest +import unittest.mock as mock +from typing import ClassVar + +from utils.cache.files import PROJECT_ROOT, read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_SERVICES +from utils.update import docker, repository + +ROLE = "web-app-nextcloud" +SERVICES_FILE = PROJECT_ROOT / "roles" / ROLE / ROLE_FILE_META_SERVICES +JANUS = "https://github.com/meetecho/janus-gateway.git" +RECORDING = "https://github.com/nextcloud/nextcloud-talk-recording.git" + + +def _pinned(service: str, key: str) -> str: + return str(load_yaml_any(str(SERVICES_FILE))[service][key]) + + +class TestTalkPinsAreWatched(unittest.TestCase): + IMAGES: ClassVar[dict[str, str]] = { + "talk_signaling": "strukturag/nextcloud-spreed-signaling", + "talk_nats": "nats", + "talk": "alpine", + "talk_recording": "python", + } + REFS: ClassVar[dict[str, str]] = {"talk": JANUS, "talk_recording": RECORDING} + + def test_the_docker_updater_watches_every_talk_image(self): + entries = { + (entry.service, entry.image): entry.version + for entry in docker.collect_entries(PROJECT_ROOT) + if entry.role == ROLE + } + for service, image in self.IMAGES.items(): + with self.subTest(service=service): + self.assertEqual( + entries.get((service, image)), _pinned(service, "version") + ) + + def test_the_repository_updater_watches_both_built_sources(self): + entries = { + entry.entity_path: (entry.repository, entry.ref) + for entry in repository.collect_entries(PROJECT_ROOT) + if entry.role == ROLE + } + for service, url in self.REFS.items(): + with self.subTest(service=service): + self.assertEqual( + entries.get((service,)), (url, _pinned(service, "ref")) + ) + + def test_no_talk_pin_opts_out_of_the_updaters(self): + lines = read_text(str(SERVICES_FILE)).splitlines() + owner = None + for number, line in enumerate(lines): + if match := re.match(r"^([a-z_]+):", line): + owner = match.group(1) + if owner in self.IMAGES and re.match(r"^\s+(version|ref):", line): + with self.subTest(service=owner, line=number + 1): + self.assertNotIn("nocheck", lines[number - 1]) + self.assertNotIn("nocheck", line) + + def test_a_newer_upstream_release_is_reported_for_every_pin(self): + newer = { + "strukturag/nextcloud-spreed-signaling": ["2.1.1", "9.0.0", "9.0.0-proxy"], + "nats": ["2.12.6-alpine", "9.0.0-alpine", "9.1.0"], + "alpine": ["3.23.3", "9.0.0"], + "python": ["3.14.3-alpine3.23", "3.14.9-alpine3.23", "3.15.0-slim"], + } + tags = {JANUS: ["v1.4.0", "v9.0.0"], RECORDING: ["v0.2.1", "v9.0.0"]} + with ( + mock.patch.dict(os.environ, {"INFINITO_WORKER_FETCH": "2"}), + mock.patch.object( + docker, "fetch_dockerhub_tags", lambda image: newer.get(image, []) + ), + mock.patch.object(docker, "fetch_ghcr_tags", lambda image: []), + mock.patch.object(docker, "fetch_mcr_tags", lambda image: []), + mock.patch.object( + docker, "fetch_registry_tags", lambda image, last=None: [] + ), + mock.patch.object( + repository, "git_ls_remote_tags", lambda url: tags.get(url, []) + ), + ): + images = { + (update.entry.service, update.latest) + for update in docker.find_outdated_updates(PROJECT_ROOT) + if update.entry.role == ROLE + } + refs = { + (update.entry.entity_path, update.latest) + for update in repository.find_outdated_updates(PROJECT_ROOT) + if update.entry.role == ROLE + } + self.assertTrue( + { + ("talk_signaling", "9.0.0"), + ("talk_nats", "9.0.0-alpine"), + ("talk", "9.0.0"), + ("talk_recording", "3.14.9-alpine3.23"), + } + <= images, + images, + ) + self.assertEqual(refs, {(("talk",), "v9.0.0"), (("talk_recording",), "v9.0.0")}) + + def test_negative_control_current_tags_report_nothing(self): + current = { + image: [_pinned(service, "version")] + for service, image in self.IMAGES.items() + } + with ( + mock.patch.dict(os.environ, {"INFINITO_WORKER_FETCH": "2"}), + mock.patch.object( + docker, "fetch_dockerhub_tags", lambda image: current.get(image, []) + ), + mock.patch.object(docker, "fetch_ghcr_tags", lambda image: []), + mock.patch.object(docker, "fetch_mcr_tags", lambda image: []), + mock.patch.object( + docker, "fetch_registry_tags", lambda image, last=None: [] + ), + ): + reported = { + update.entry.service + for update in docker.find_outdated_updates(PROJECT_ROOT) + if update.entry.role == ROLE + } + self.assertFalse(reported & set(self.IMAGES), reported) + + +if __name__ == "__main__": + unittest.main() From 7f67052caf41c4fd2a984a5cb6e5fcd2f7119bfe Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 23:48:32 +0100 Subject: [PATCH 39/42] test(web-app-nextcloud): record a Talk call through the recording server A guest joins a public call with fake media, the administrator starts an audio recording through the OCS API and stops it after fifteen seconds, and the spec waits for the stored-recording notification and checks that the uploaded file is not empty. test-talk-call-capacity.js exports its OCS headers and its room and guest helpers so the recording spec reuses them, and playwright.spec.js registers it. Like the other Talk realtime specs it skips on an onion target. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../files/playwright/playwright.spec.js | 1 + .../playwright/test-talk-call-capacity.js | 4 + .../files/playwright/test-talk-recording.js | 115 ++++++++++++++++++ 3 files changed, 120 insertions(+) create mode 100644 roles/web-app-nextcloud/files/playwright/test-talk-recording.js diff --git a/roles/web-app-nextcloud/files/playwright/playwright.spec.js b/roles/web-app-nextcloud/files/playwright/playwright.spec.js index ff114cd6d8..3920d622f3 100644 --- a/roles/web-app-nextcloud/files/playwright/playwright.spec.js +++ b/roles/web-app-nextcloud/files/playwright/playwright.spec.js @@ -20,6 +20,7 @@ test.beforeEach(shared.beforeEach); require("./test-talk-admin-settings").register(shared); require("./test-talk-call-capacity").register(shared); +require("./test-talk-recording").register(shared); require("./test-login-admin-oidc").register(shared); require("./test-login-admin-native").register(shared); require("./test-login-biber-oidc").register(shared); diff --git a/roles/web-app-nextcloud/files/playwright/test-talk-call-capacity.js b/roles/web-app-nextcloud/files/playwright/test-talk-call-capacity.js index e1d3a7eb73..082d276789 100644 --- a/roles/web-app-nextcloud/files/playwright/test-talk-call-capacity.js +++ b/roles/web-app-nextcloud/files/playwright/test-talk-call-capacity.js @@ -119,6 +119,10 @@ async function joinCallAsGuest(browser, roomUrl, name) { return { name, page, context }; } +exports.ocsHeaders = ocsHeaders; +exports.createPublicRoom = createPublicRoom; +exports.joinCallAsGuest = joinCallAsGuest; + exports.register = function (shared) { test("nextcloud talk call holds more than five participants", async ({ browser }) => { test.skip(!talkEnabled, "Talk is disabled in the current Playwright env"); diff --git a/roles/web-app-nextcloud/files/playwright/test-talk-recording.js b/roles/web-app-nextcloud/files/playwright/test-talk-recording.js new file mode 100644 index 0000000000..a3e33f86e0 --- /dev/null +++ b/roles/web-app-nextcloud/files/playwright/test-talk-recording.js @@ -0,0 +1,115 @@ +const { test, expect, chromium } = require("@playwright/test"); +const { resolveTimeout, isOnionTarget } = require("./timeouts"); +const { decodeDotenvQuotedValue } = require("./personas"); +const { ocsHeaders, createPublicRoom, joinCallAsGuest } = require("./test-talk-call-capacity"); + +const talkEnabled = decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_SETTINGS_CHECK_ENABLED) === "true"; +const recordingAudio = 2; +const recordingFailed = 5; +const recordingDurationMs = 15_000; + +async function ocs(page, method, url) { + const response = await page.request.fetch(url, { method, headers: ocsHeaders }); + const body = await response.json().catch(() => ({})); + return { status: response.status(), data: body?.ocs?.data }; +} + +async function readCallRecording(page, baseUrl, token) { + const { data } = await ocs(page, "GET", new URL(`ocs/v2.php/apps/spreed/api/v4/room/${token}`, baseUrl).toString()); + return data?.callRecording; +} + +async function findStoredRecording(page, baseUrl, token) { + const { data } = await ocs(page, "GET", new URL("ocs/v2.php/apps/notifications/api/v2/notifications", baseUrl).toString()); + const stored = (Array.isArray(data) ? data : []).find( + (notification) => + notification.app === "spreed" && + notification.object_type === "recording" && + notification.object_id === token && + notification.messageRichParameters?.file?.path, + ); + return stored ? stored.messageRichParameters.file : null; +} + +function readFileSize(page, path) { + return page.evaluate(async (relativePath) => { + const user = window.OC.getCurrentUser().uid; + const encoded = relativePath.split("/").filter(Boolean).map(encodeURIComponent).join("/"); + const response = await fetch(`${window.OC.getRootPath()}/remote.php/dav/files/${encodeURIComponent(user)}/${encoded}`, { + method: "PROPFIND", + headers: { Depth: "0", requesttoken: window.OC.requestToken, "Content-Type": "application/xml" }, + body: '', + }); + if (response.status !== 207) { + return -response.status; + } + const length = new DOMParser() + .parseFromString(await response.text(), "application/xml") + .getElementsByTagNameNS("DAV:", "getcontentlength")[0]; + return length ? Number(length.textContent) : 0; + }, path); +} + +exports.register = function (shared) { + test("nextcloud talk recording server stores a recording of a call", async ({ browser }) => { + test.skip(!talkEnabled, "Talk is disabled in the current Playwright env"); + test.skip(isOnionTarget(), "Nextcloud Talk realtime (HPB signaling + recording) is WebRTC; not reachable over Tor"); + test.setTimeout(resolveTimeout(10 * 60_000)); + + const baseUrl = shared.env.nextcloudBaseUrl; + const adminContext = await browser.newContext({ ignoreHTTPSErrors: true }); + const adminPage = await adminContext.newPage(); + const mediaBrowser = await chromium.launch({ + args: ["--use-fake-ui-for-media-stream", "--use-fake-device-for-media-stream"], + }); + let token = ""; + + try { + await shared.loginToStandaloneNextcloud(adminPage); + token = await createPublicRoom(adminPage, baseUrl); + await joinCallAsGuest(mediaBrowser, new URL(`call/${token}`, baseUrl).toString(), "Playwright recording guest"); + + const recordingUrl = new URL(`ocs/v2.php/apps/spreed/api/v1/recording/${token}`, baseUrl).toString(); + const start = await adminPage.request.post(recordingUrl, { headers: ocsHeaders, data: { status: recordingAudio } }); + expect(start.ok(), `starting the call recording answered HTTP ${start.status()}: ${await start.text()}`).toBeTruthy(); + + await expect + .poll(async () => readCallRecording(adminPage, baseUrl, token), { + timeout: resolveTimeout(180_000), + message: "the recording server must join the call and report the audio recording as running", + }) + .toBe(recordingAudio); + + await adminPage.waitForTimeout(recordingDurationMs); + + const stop = await ocs(adminPage, "DELETE", recordingUrl); + expect(stop.status, "stopping the call recording must succeed").toBe(200); + expect(await readCallRecording(adminPage, baseUrl, token), "the recording must not end as failed").not.toBe(recordingFailed); + + let stored = null; + await expect + .poll( + async () => { + stored = await findStoredRecording(adminPage, baseUrl, token); + return Boolean(stored); + }, + { + timeout: resolveTimeout(300_000), + message: "the recording server must upload the recording and Talk must notify the moderator that it is stored", + }, + ) + .toBe(true); + + await adminPage.goto(new URL("apps/files/", baseUrl).toString(), { waitUntil: "domcontentloaded", timeout: resolveTimeout(60_000) }); + expect(await readFileSize(adminPage, stored.path), `the stored recording ${stored.path} must not be empty`).toBeGreaterThan(0); + } finally { + await mediaBrowser.close().catch(() => {}); + if (token) { + await adminPage.request + .delete(new URL(`ocs/v2.php/apps/spreed/api/v4/room/${token}`, baseUrl).toString(), { headers: ocsHeaders }) + .catch(() => {}); + } + await adminContext.close().catch(() => {}); + } + }); +}; From 73b21eef98e8a04689d16279b1cccb1f4df39320 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 23:55:01 +0100 Subject: [PATCH 40/42] fix(web-app-fider): bootstrap the tenant without SSO 00_core.yml included 01_setup_oidc.yml only when services.sso.enabled was true, but that file carried the whole tenant bootstrap: wait for HTTP, count tenants, POST /_api/tenants, create the admin user and activate the tenant. Only its last task configured the Keycloak provider. With SSO off no tenant was ever created. Fider's RequireTenant middleware then answers every tenant route, /api/v1/tags included, with 307 to /signup, and /signup is open to any visitor, who can claim the fresh installation and become its administrator. The MCP read fider_list_tags got that 307 in the swarm SSO-off matrix row. The tenant bootstrap moves unchanged into tasks/01_tenant.yml, which 00_core.yml includes on the stack host regardless of SSO. The OIDC file becomes tasks/02_setup_oidc.yml and keeps only the provider upsert, still gated on services.sso.enabled. The README states which bootstrap steps run without SSO. A unit test evaluates the include and task guards for every SSO, stack-host and deploy-mode state: a fresh stack host posts exactly one tenant with and without SSO, an existing tenant is never posted again, the Keycloak provider is written only with SSO, and a non-stack host runs none of it. The compose matrix row with SSO off stayed green because nothing there read a tenant route. Co-Authored-By: Claude Opus 5.5 --- roles/web-app-fider/README.md | 2 +- roles/web-app-fider/tasks/00_core.yml | 6 +- .../{01_setup_oidc.yml => 01_tenant.yml} | 14 --- roles/web-app-fider/tasks/02_setup_oidc.yml | 14 +++ .../python/roles/web-app-fider/__init__.py | 3 + .../test_tenant_bootstrap_gate.py | 101 ++++++++++++++++++ 6 files changed, 124 insertions(+), 16 deletions(-) rename roles/web-app-fider/tasks/{01_setup_oidc.yml => 01_tenant.yml} (86%) create mode 100644 roles/web-app-fider/tasks/02_setup_oidc.yml create mode 100644 tests/unit/python/roles/web-app-fider/__init__.py create mode 100644 tests/unit/python/roles/web-app-fider/test_tenant_bootstrap_gate.py diff --git a/roles/web-app-fider/README.md b/roles/web-app-fider/README.md index e88980fe4e..d2c3c56ec3 100644 --- a/roles/web-app-fider/README.md +++ b/roles/web-app-fider/README.md @@ -8,7 +8,7 @@ This role deploys Fider as part of the Infinito.Nexus stack using a single Docker Compose container backed by PostgreSQL. It configures SSO via Keycloak automatically on first deploy, optional email notifications via Mailu, and HTTPS via NGINX reverse proxy. -The setup tasks handle the full first-deploy bootstrap automatically: +The setup tasks handle the full first-deploy bootstrap automatically. Steps 1 to 3 run on every deploy, with or without SSO; step 4 runs only when `services.sso.enabled` is `true`: 1. **Tenant bootstrap:** calls Fider's `POST /_api/tenants` API to create the initial tenant. 2. **Admin user creation:** inserts the admin user directly into the `users` table, bypassing email verification. Idempotent via `WHERE NOT EXISTS`. diff --git a/roles/web-app-fider/tasks/00_core.yml b/roles/web-app-fider/tasks/00_core.yml index b50ce78c4c..890de3447d 100644 --- a/roles/web-app-fider/tasks/00_core.yml +++ b/roles/web-app-fider/tasks/00_core.yml @@ -20,8 +20,12 @@ - name: "🚿 Flush compose handlers for {{ application_id }}" ansible.builtin.meta: flush_handlers +- name: "🄾 Fider | Tenant bootstrap" + include_tasks: 01_tenant.yml + when: IS_STACK_HOST | bool + - name: "šŸ”§ Fider | OIDC setup" - include_tasks: 01_setup_oidc.yml + include_tasks: 02_setup_oidc.yml when: - FIDER_OIDC_ENABLED | bool - IS_STACK_HOST | bool diff --git a/roles/web-app-fider/tasks/01_setup_oidc.yml b/roles/web-app-fider/tasks/01_tenant.yml similarity index 86% rename from roles/web-app-fider/tasks/01_setup_oidc.yml rename to roles/web-app-fider/tasks/01_tenant.yml index fe5cc89d09..68cd7f47a8 100644 --- a/roles/web-app-fider/tasks/01_setup_oidc.yml +++ b/roles/web-app-fider/tasks/01_tenant.yml @@ -85,17 +85,3 @@ query_file: "{{ role_path }}/files/sql/activate-tenants.sql" mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" changed_when: true - -- name: "šŸ”§ Fider | Configure Keycloak as OIDC provider in database" - database_query: - config: "{{ lookup('database', application_id) }}" - query_file: "{{ role_path }}/files/sql/configure-oidc-provider.sql" - named_args: - display_name: "{{ SOFTWARE_NAME }} SSO" - client_id: "{{ OIDC.CLIENT.ID }}" - client_secret: "{{ OIDC.CLIENT.SECRET }}" - authorize_url: "{{ OIDC.CLIENT.AUTHORIZE_URL }}" - token_url: "{{ OIDC.CLIENT.TOKEN_URL }}" - profile_url: "{{ OIDC.CLIENT.USER_INFO_URL }}" - mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - changed_when: true diff --git a/roles/web-app-fider/tasks/02_setup_oidc.yml b/roles/web-app-fider/tasks/02_setup_oidc.yml new file mode 100644 index 0000000000..d8327ba53f --- /dev/null +++ b/roles/web-app-fider/tasks/02_setup_oidc.yml @@ -0,0 +1,14 @@ +--- +- name: "šŸ”§ Fider | Configure Keycloak as OIDC provider in database" + database_query: + config: "{{ lookup('database', application_id) }}" + query_file: "{{ role_path }}/files/sql/configure-oidc-provider.sql" + named_args: + display_name: "{{ SOFTWARE_NAME }} SSO" + client_id: "{{ OIDC.CLIENT.ID }}" + client_secret: "{{ OIDC.CLIENT.SECRET }}" + authorize_url: "{{ OIDC.CLIENT.AUTHORIZE_URL }}" + token_url: "{{ OIDC.CLIENT.TOKEN_URL }}" + profile_url: "{{ OIDC.CLIENT.USER_INFO_URL }}" + mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + changed_when: true diff --git a/tests/unit/python/roles/web-app-fider/__init__.py b/tests/unit/python/roles/web-app-fider/__init__.py new file mode 100644 index 0000000000..8ee16d7567 --- /dev/null +++ b/tests/unit/python/roles/web-app-fider/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] diff --git a/tests/unit/python/roles/web-app-fider/test_tenant_bootstrap_gate.py b/tests/unit/python/roles/web-app-fider/test_tenant_bootstrap_gate.py new file mode 100644 index 0000000000..7dace21cc7 --- /dev/null +++ b/tests/unit/python/roles/web-app-fider/test_tenant_bootstrap_gate.py @@ -0,0 +1,101 @@ +import unittest + +from jinja2 import Environment + +from utils.cache.yaml import load_yaml_any + +from . import PROJECT_ROOT + +TASKS = PROJECT_ROOT / "roles" / "web-app-fider" / "tasks" +MODES = ("compose", "swarm") + +_TRUTHY = frozenset({"1", "true", "yes", "y", "on"}) + + +def _to_bool(value): + if isinstance(value, bool): + return value + return str(value).strip().lower() in _TRUTHY + + +def _guard_holds(task, context) -> bool: + when = task.get("when", []) + guards = when if isinstance(when, list) else [when] + env = Environment(autoescape=True) + env.filters["bool"] = _to_bool + return all(bool(env.compile_expression(expr)(**context)) for expr in guards) + + +def _run_tasks(*, sso: bool, stack_host: bool, mode: str, tenants: int) -> list: + context = { + "FIDER_OIDC_ENABLED": sso, + "FIDER_MCP_ENABLED": False, + "IS_STACK_HOST": stack_host, + "DEPLOYMENT_MODE": mode, + "fider_tenant_count": {"rows": [[tenants]]}, + } + executed: list = [] + for include in load_yaml_any(str(TASKS / "00_core.yml")): + target = include.get("include_tasks") + if not isinstance(target, str) or not (TASKS / target).is_file(): + continue + if not _guard_holds(include, context): + continue + executed.extend( + task + for task in load_yaml_any(str(TASKS / target)) + if _guard_holds(task, context) + ) + return executed + + +def _tenant_posts(tasks: list) -> list: + return [ + task + for task in tasks + if str(task.get("uri_retry", {}).get("url", "")).endswith("/_api/tenants") + or "POST /_api/tenants" in str(task.get("ansible.builtin.shell", "")) + ] + + +def _configures_keycloak(tasks: list) -> bool: + return any( + str(task.get("database_query", {}).get("query_file", "")).endswith( + "configure-oidc-provider.sql" + ) + for task in tasks + ) + + +class TestTenantBootstrapGate(unittest.TestCase): + def test_fresh_stack_host_posts_one_tenant_with_and_without_sso(self): + for sso in (True, False): + for mode in MODES: + with self.subTest(sso=sso, mode=mode): + tasks = _run_tasks(sso=sso, stack_host=True, mode=mode, tenants=0) + self.assertEqual(len(_tenant_posts(tasks)), 1) + + def test_existing_tenant_is_not_posted_again(self): + for sso in (True, False): + for mode in MODES: + with self.subTest(sso=sso, mode=mode): + tasks = _run_tasks(sso=sso, stack_host=True, mode=mode, tenants=1) + self.assertEqual(_tenant_posts(tasks), []) + + def test_keycloak_provider_is_configured_only_with_sso(self): + for sso in (True, False): + for mode in MODES: + with self.subTest(sso=sso, mode=mode): + tasks = _run_tasks(sso=sso, stack_host=True, mode=mode, tenants=1) + self.assertEqual(_configures_keycloak(tasks), sso) + + def test_non_stack_host_runs_no_bootstrap(self): + for sso in (True, False): + for mode in MODES: + with self.subTest(sso=sso, mode=mode): + tasks = _run_tasks(sso=sso, stack_host=False, mode=mode, tenants=0) + self.assertEqual(tasks, []) + + +if __name__ == "__main__": + unittest.main() From b5d4391272382f6c3300bec1b3d7294efa1e0de6 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 23:55:02 +0100 Subject: [PATCH 41/42] style(lint): apply ruff format to the worktree swarm lab subnet lint tests/lint/filesystem/env/test_worktree_swarm_lab_subnet.py landed on main with lines ruff format wraps, so every `make autoformat` rewrites it and leaves an unstaged change behind. Formatter output only. Co-Authored-By: Claude Opus 5.5 --- .../filesystem/env/test_worktree_swarm_lab_subnet.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/tests/lint/filesystem/env/test_worktree_swarm_lab_subnet.py b/tests/lint/filesystem/env/test_worktree_swarm_lab_subnet.py index 16c42ed62b..7395b5f012 100644 --- a/tests/lint/filesystem/env/test_worktree_swarm_lab_subnet.py +++ b/tests/lint/filesystem/env/test_worktree_swarm_lab_subnet.py @@ -71,10 +71,16 @@ class TestWorktreeSwarmLabSubnet(unittest.TestCase): with self.subTest(slot=slot): subnet = self._subnet(slot) clashes = sorted( - name for name, network in self.reserved.items() if subnet.overlaps(network) + name + for name, network in self.reserved.items() + if subnet.overlaps(network) + ) + self.assertEqual( + clashes, [], f"slot {slot} lab {subnet} overlaps {clashes}" + ) + self.assertNotIn( + subnet, seen, f"slot {slot} repeats slot {seen.get(subnet)}" ) - self.assertEqual(clashes, [], f"slot {slot} lab {subnet} overlaps {clashes}") - self.assertNotIn(subnet, seen, f"slot {slot} repeats slot {seen.get(subnet)}") seen[subnet] = slot From f131f5797857471a614fb280f02ea4475cf0c669 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 23:56:01 +0100 Subject: [PATCH 42/42] docs(web-app-nextcloud): describe the decoupled Talk backend README and Administration list the four Talk services, their sources, how they connect, how a version update reaches them and how the first deploy replaces nextcloud/aio-talk. Requirement 061 is added. Its criteria for the code shape are checked, and those for the four services running as their own services from their pinned or role-built images with role-rendered configs are checked from a compose deploy, where all four were healthy and each started with the config file the role mounted. The criteria for the Talk specs, swarm, the updater and the migration of an existing installation stay open. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../061-nextcloud-talk-hpb-decoupled.md | 24 +++++++++ roles/web-app-nextcloud/README.md | 16 ++++++ .../web-app-nextcloud/docs/Administration.md | 51 +++++++++++++++++-- 3 files changed, 87 insertions(+), 4 deletions(-) create mode 100644 docs/requirements/061-nextcloud-talk-hpb-decoupled.md diff --git a/docs/requirements/061-nextcloud-talk-hpb-decoupled.md b/docs/requirements/061-nextcloud-talk-hpb-decoupled.md new file mode 100644 index 0000000000..15f3a66cdc --- /dev/null +++ b/docs/requirements/061-nextcloud-talk-hpb-decoupled.md @@ -0,0 +1,24 @@ +# 061 - Nextcloud Talk high-performance backend from pinned upstream components + +## User Story + +As an operator, I want the Nextcloud Talk high-performance backend and recording server to run as separate services built from semver-pinned upstream sources, with every configuration file rendered by `web-app-nextcloud`, so that the updater can raise their versions automatically and no upstream start script can overwrite the role's configuration. + +## Acceptance Criteria + +- [x] `roles/web-app-nextcloud/meta/services.yml` no longer references `nextcloud/aio-talk` or `nextcloud/aio-talk-recording`. +- [x] The signaling server runs as its own service from the upstream `nextcloud-spreed-signaling` project, pinned to a semver version without a `# nocheck: docker-version` marker. +- [x] Janus runs as its own service from an image the role builds from a semver git tag of `meetecho/janus-gateway`. +- [x] NATS runs as its own service from the official `nats` image pinned to a semver version. +- [x] The recording server runs as its own service from an image the role builds from a semver release tag of `nextcloud/nextcloud-talk-recording`. +- [x] The role renders the signaling `server.conf`, `janus.jcfg` and the recording `server.conf`; no file inside an image regenerates or overwrites them at container start. +- [x] The Janus config drift guard in `tasks/01_fullstack.yml` and the `janus_config_drift` filter are removed together with their tests. +- [ ] `utils/update` reports a newer upstream version for each of the four pins, and `tests/lint/ansible/services/test_version_pins_are_watched` passes for them. +- [ ] The public signaling endpoint stays `/standalone-signaling/`, and the Talk admin settings show the pinned signaling version as "Running version" with `chat-relay` not listed as missing. +- [ ] Direct media keeps working: with `services.talk.network_mode: host`, `nat_1_1_mapping` carries the public IP and `test-talk-call-capacity.js` passes. +- [ ] A recording started from a Talk call through the recording server produces a file, verified by a Playwright or CLI test. +- [ ] Each new service has its own healthcheck and resource limits, and in swarm the services Janus shares a network namespace with are placed on the same node. +- [ ] Deploying over an existing `aio-talk` installation removes the old container or swarm service and starts the new services with the existing signaling, TURN and recording secrets in one deploy. +- [x] No secret of the new services appears in a container's argv; secrets reach them through config files or environment. +- [ ] `web-app-nextcloud` with Talk enabled is green in a compose and a swarm roundtrip, including the Talk Playwright specs. +- [x] `roles/web-app-nextcloud/README.md` and `docs/Administration.md` describe the four services, their sources and how a version update reaches them. diff --git a/roles/web-app-nextcloud/README.md b/roles/web-app-nextcloud/README.md index 7125a4e23c..0d7cdbd0a8 100644 --- a/roles/web-app-nextcloud/README.md +++ b/roles/web-app-nextcloud/README.md @@ -61,7 +61,10 @@ flowchart LR svc_context_agent["context_agent"] svc_contextagentmcp["contextagentmcp"] svc_cron["cron"] + svc_taskprocessing["taskprocessing"] svc_talk["talk"] + svc_talk_signaling["talk_signaling"] + svc_talk_nats["talk_nats"] svc_whiteboard["whiteboard"] svc_onlyoffice["onlyoffice"] svc_collabora["collabora"] @@ -230,6 +233,19 @@ A redeploy of an unchanged version includes [`03_upgrade/02_cached_updates.yml`] An app the background job has not checked yet is not updated until its next run. +## Talk + +While `services.talk.enabled` is true, the role runs the Talk high-performance backend and the recording server as four services: + +| Service | Component | Source | +|---------|-----------|--------| +| `talk_signaling` | signaling server | upstream image `strukturag/nextcloud-spreed-signaling`, semver pin | +| `talk` | Janus media server | image the role builds from a semver tag of `meetecho/janus-gateway` | +| `talk_nats` | NATS message bus | official image `nats`, semver pin | +| `talk_recording` | recording server | image the role builds from a semver release tag of `nextcloud/nextcloud-talk-recording` | + +The role renders the signaling `server.conf`, `janus.jcfg` and the recording `server.conf` from [`templates/`](./templates/), and the version updaters raise every pin. [docs/Administration.md](docs/Administration.md#talk-high-performance-backend) describes how the services connect, how a version update reaches them and how the first deploy replaces `nextcloud/aio-talk`. + ## MCP Server Nextcloud serves a Model Context Protocol endpoint through the AppAPI proxy of the `context_agent` ExApp. diff --git a/roles/web-app-nextcloud/docs/Administration.md b/roles/web-app-nextcloud/docs/Administration.md index 020ab86bea..cef6371e7a 100644 --- a/roles/web-app-nextcloud/docs/Administration.md +++ b/roles/web-app-nextcloud/docs/Administration.md @@ -24,7 +24,7 @@ The logs you will find here on the host: **/var/lib/docker/volumes/nextcloud_dat ## Talk TURN and STUN -When `services.talk.enabled` is true, Nextcloud Talk MUST use the dedicated `web-svc-coturn` service for STUN and TURN instead of the HPB port exposed by `web-app-nextcloud`. +When `services.talk.enabled` is true, Nextcloud Talk uses the dedicated `web-svc-coturn` service for STUN and TURN. `web-app-nextcloud` runs no TURN server of its own. Check these admin URLs after deployment: @@ -32,10 +32,53 @@ Check these admin URLs after deployment: - `/settings/admin/talk#stun_server` - `/settings/admin/talk#turn_server` +## Talk high-performance backend + +The high-performance backend and the recording server run as four services of the `web-app-nextcloud` stack. Each one is pinned in `meta/services.yml`, and the role renders every configuration file they read. + +| Service | Component | Source | Configuration | +|---|---|---|---| +| `talk_signaling` | [nextcloud-spreed-signaling](https://github.com/strukturag/nextcloud-spreed-signaling) | upstream image `strukturag/nextcloud-spreed-signaling` at `services.talk_signaling.version` | `templates/signaling.conf.j2`, mounted as a secret at `/config/server.conf` | +| `talk` | [Janus](https://github.com/meetecho/janus-gateway) | built by the role from `services.talk.repository` at the tag `services.talk.ref` on `services.talk.image:services.talk.version`, see `files/Dockerfiles/Janus/Dockerfile` | `templates/janus.jcfg.j2`, mounted as a config at `/usr/local/etc/janus/janus.jcfg` | +| `talk_nats` | [NATS](https://nats.io) | official image `nats` at `services.talk_nats.version` | command line only | +| `talk_recording` | [nextcloud-talk-recording](https://github.com/nextcloud/nextcloud-talk-recording) | built by the role from `services.talk_recording.repository` at the tag `services.talk_recording.ref` on `services.talk_recording.image:services.talk_recording.version`, see `files/Dockerfiles/Recording/Dockerfile` | `templates/recording.conf.j2`, mounted as a secret at `/conf/recording.conf` | + +How the services connect: + +- The `proxy` service forwards `/standalone-signaling/` to `talk_signaling` on `services.talk_signaling.ports.internal.signaling`. +- `talk_signaling` reaches `talk_nats` at `nats://talk_nats:4222` and Janus at `ws://talk:8188`, or at `ws://host.docker.internal:8188` while Janus uses the host network. +- `talk_signaling` and `talk_recording` reach Nextcloud at its public URL, and `talk_recording` joins calls through the public `/standalone-signaling/` endpoint. +- Nextcloud reaches the recording server at `http://talk_recording:1234/`. + +`credentials.talk_signaling_secret`, `credentials.talk_internal_secret` and `credentials.talk_recording_secret` reach the services only through the rendered files. The signaling session keys are derived from `credentials.talk_signaling_secret`, so they stay stable across deploys. `talk_signaling` runs as UID 850, `talk` as UID 1000, `talk_nats` as UID 65534 and `talk_recording` as UID 122, each with one swarm replica. In swarm mode all four join the stack network and share no network namespace, so swarm may schedule them on different nodes. + +### Version updates + +1. The `cron-update` workflow runs `python3 -m cli.contributing.update.docker`, which raises `services.talk_signaling.version` and `services.talk_nats.version` from their registries together with the base images `services.talk.version` and `services.talk_recording.version`, and opens an update pull request. +2. The same workflow runs `python3 -m cli.contributing.update.repository`, which raises `services.talk.ref` and `services.talk_recording.ref` to the newest semver tag of their git repositories. +3. A new `ref` or base `version` changes the build arguments in `templates/compose.yml.j2` and the image tag `-`, so the next deploy rebuilds the image and replaces the container in compose mode or the task in swarm mode. +4. A new upstream release that changes its configuration format needs a change to the matching template, because no start script inside an image writes or rewrites these files. + +### Switching from nextcloud/aio-talk + +The first deploy of this layout replaces the `nextcloud/aio-talk` and `nextcloud/aio-talk-recording` containers: + +- In compose mode `compose up --force-recreate --remove-orphans` recreates the `talk` and `talk_recording` services with the new images and starts `talk_signaling` and `talk_nats`. +- In swarm mode `docker stack deploy --prune` updates `nextcloud_talk` and `nextcloud_talk_recording` in place and creates the two new services. +- The signaling, internal and recording secrets keep their inventory values, so Nextcloud needs no reconfiguration. Calls drop while the containers are replaced. +- The TURN server bundled in `nextcloud/aio-talk` is gone together with `credentials.talk_turn_secret`, `services.talk.turn_server.onboard_enabled` and the `stun_turn`, `stun_turn_tls` and `relay` ports of `services.nextcloud`. Remove those keys from inventories that set them. + ## Talk media -By default every Talk stream goes through `web-svc-coturn`, and the `talk` container publishes no media port. Set `services.talk.direct_media` to `true` in the inventory to let clients send their media to the Janus media server inside the `talk` container directly: Janus then announces `networks.internet.ip4` and publishes `services.talk.ports.public.relay` (UDP, default 61000-61999) on that address, and clients fall back to `web-svc-coturn` only when UDP to that range is blocked. The setting takes effect in compose mode with a bridged `talk` service that uses `web-svc-coturn` for TURN, and only while `networks.internet.ip4` is an address of the host itself. +By default every Talk stream goes through `web-svc-coturn`, and Janus publishes no port. Set `services.talk.direct_media` to `true` in the inventory to let clients send their media to Janus directly: Janus then announces `networks.internet.ip4` as `nat_1_1_mapping`, takes its media ports from `services.talk.ports.public.relay` (UDP, default 61000-61999) and publishes them on that address, and clients fall back to `web-svc-coturn` only when UDP to that range is blocked. The setting takes effect in compose mode when `web-svc-coturn` provides TURN and `networks.internet.ip4` is an address of the host itself. -Open the range for UDP in any firewall in front of the host. Each participant of a call holds one peer connection per participant, so all calls together get at most as many peer connections as the range has ports, and a call of N participants needs N² of them. Janus refuses a new peer connection once the range is used up. Docker starts one `docker-proxy` process per published port. +`services.talk.network_mode` decides how Janus reaches that range: -`templates/janus.jcfg.j2` replaces the `janus.jcfg` of the `nextcloud/aio-talk` image. Before every deploy the role reads `/supervisord.conf` and that file from the image and stops unless Janus is started with that file and its settings equal the template without `rtp_port_range`, `nat_1_1_mapping` and `keep_private_host`. Re-derive the template from the new image when that happens. +| Value | Janus | +|---|---| +| `bridge` | runs on the stack network and publishes the range on `networks.internet.ip4` | +| `host` | runs in the host network namespace and binds the range itself; compose mode only, the deploy stops in swarm mode | + +With `host`, Janus also answers its websocket API on port 8188 of every host interface. Block that port in any firewall in front of the host. + +Open the media range for UDP in any firewall in front of the host. Each participant of a call holds one peer connection per participant, so all calls together get at most as many peer connections as the range has ports, and a call of N participants needs N² of them. Janus refuses a new peer connection once the range is used up. With `bridge`, Docker starts one `docker-proxy` process per published port.