From 5b1ac73dd9edaf8fd8ce80f10b4ebe6434bab537 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 15 Sep 2026 11:20:40 +0200 Subject: [PATCH] fix(domains): render the tor flags before the onion map reads them services.tor.enabled is Jinja in 99 of the 105 roles that declare it. A lookup('tls') or lookup('domains') inside a meta/*.yml value runs while the applications render is in flight, the re-entry guard hands it the unrendered tree, and _as_bool read the flag's own source text as False. The onion injection then did nothing for any app and the clearnet domain was returned. fa3797540a already described this and quarantined it: the render state joined the domains cache key so the poisoned map answers no later read. The value stayed wrong, which is enough until a call site bakes it into applications. roles/web-svc-asset/meta/services.yml:15 is the only one in the repo that does, and in run 34922994823 it froze https://file.infinito.test/assets into the payload while every vhost of that round was published under the node onion. web-app-dashboard then waited 60 times on a host openresty answers with ssl_reject_handshake, and the deploy died on TLSV1_UNRECOGNIZED_NAME. _resolved_flag renders enabled, exclusive and primary and raises when template text survives, the shape plugins/lookup/proxy_pass.py already uses. plugins/lookup/config.py and plugins/lookup/email.py render before coercing for the same reason; this module was the one that did not. Measured across the whole map: 44 of 12819 leaves change, none added, none removed, 17 roles. 42 are clearnet to onion. The two others are repairs as well: keycloak's csp frame-ancestors moves from https to http, which is what an onion node serves, and the nextcloud sociallogin provider name stops being a hostname and becomes the bounded name that test_sociallogin_provider_name.py documents. The new tests drive the same function with Jinja instead of the literal booleans the existing ones pass, which is why those never saw this. Three of the four fail without the fix. Co-Authored-By: Claude Opus 5 (1M context) --- tests/unit/python/utils/cache/test_domains.py | 66 ++++++++++++++ utils/cache/domains.py | 91 +++++++++++++++++-- 2 files changed, 150 insertions(+), 7 deletions(-) diff --git a/tests/unit/python/utils/cache/test_domains.py b/tests/unit/python/utils/cache/test_domains.py index ae7b2b7c35..c884e16db2 100644 --- a/tests/unit/python/utils/cache/test_domains.py +++ b/tests/unit/python/utils/cache/test_domains.py @@ -337,5 +337,71 @@ class TestOnionDomainInjection(unittest.TestCase): self.assertEqual(out["web-app-x"], ["infinito.test", self.ONION]) +class TestOnionFlagsAreRendered(unittest.TestCase): + """`services.tor.*` reaches this map as Jinja in 99 of the 105 roles that + declare it, and as its own source text whenever the applications render is + still in flight. Reading that text as a boolean answers False and drops the + onion domains for every app, which is what froze a clearnet asset URL into + the applications payload of run 34922994823. + """ + + ONION = TestOnionDomainInjection.ONION + JINJA_ON = "{{ 'svc-net-tor' in group_names }}" + + _apps = TestOnionDomainInjection._apps + + def _templar(self, **variables): + from ansible.parsing.dataloader import DataLoader + from ansible.template import Templar + + templar = Templar(loader=DataLoader(), variables=dict(variables)) + templar.available_variables = dict(variables) + return templar + + def _inject(self, apps, **variables): + return cache_domains._inject_onion_domains( + {"web-app-x": ["x.infinito.test"]}, + apps, + "infinito.test", + self.ONION, + templar=self._templar(**variables), + variables=dict(variables), + ) + + def test_a_templated_enabled_flag_still_injects_the_onion(self): + out = self._inject( + self._apps(enabled=self.JINJA_ON), + group_names=["svc-net-tor", "web-app-x"], + ) + + self.assertEqual(out["web-app-x"], ["x.infinito.test", f"x.{self.ONION}"]) + + def test_a_templated_flag_resolving_false_leaves_the_clearnet_domain(self): + out = self._inject(self._apps(enabled=self.JINJA_ON), group_names=["web-app-x"]) + + self.assertEqual(out["web-app-x"], ["x.infinito.test"]) + + def test_templated_exclusive_replaces_the_clearnet_domain(self): + out = self._inject( + self._apps(enabled=self.JINJA_ON, exclusive=self.JINJA_ON), + group_names=["svc-net-tor", "web-app-x"], + ) + + self.assertEqual(out["web-app-x"], [f"x.{self.ONION}"]) + + def test_a_flag_that_cannot_be_rendered_is_an_error(self): + """Without a templar the text cannot resolve, and answering False + would drop the onion domains without saying so.""" + with self.assertRaisesRegex(ValueError, "services.tor.enabled"): + cache_domains._inject_onion_domains( + {"web-app-x": ["x.infinito.test"]}, + self._apps(enabled=self.JINJA_ON), + "infinito.test", + self.ONION, + templar=None, + variables={"group_names": ["svc-net-tor"]}, + ) + + if __name__ == "__main__": unittest.main() diff --git a/utils/cache/domains.py b/utils/cache/domains.py index 93defc8919..ee4bd569a4 100644 --- a/utils/cache/domains.py +++ b/utils/cache/domains.py @@ -32,6 +32,54 @@ def _as_bool(value: Any) -> bool: return bool(value) +def _resolved_flag( + value: Any, + *, + app: str, + name: str, + templar: Any, + variables: Any, + apps: Any, +) -> bool: + """A tor service flag as a boolean, never as the text of its own template. + + ``services.tor.*`` is declared as Jinja in 99 of the 105 roles that carry + it. When this map is built from an applications tree that is still being + rendered (``utils.cache.applications`` returns the raw tree while its own + render is in flight) the flag arrives as its source text, which every + boolean coercion reads as False. The onion injection would then silently + not happen and the clearnet domain would be frozen into whatever value the + render was producing. + + Args: + value: the declared flag, rendered or not. + app: application id, for the error message. + name: flag name under ``services.tor``, for the error message. + templar: templar to render with; ``None`` renders nothing. + variables: scope the template resolves against. + apps: applications tree seeded into the nested render. + + Returns: + The flag as a boolean. + + Raises: + ValueError: the flag still carries template text after rendering. + """ + if isinstance(value, str) and ("{{" in value or "{%" in value): + from utils.cache.base import _render_with_templar + + value = _render_with_templar( + value, templar=templar, variables=variables, raw_applications=apps + ) + if isinstance(value, str) and ("{{" in value or "{%" in value): + raise ValueError( + f"get_merged_domains: '{app}' services.tor.{name} stayed template " + f"text ({value!r}). Reading it as a boolean would drop the onion " + "domains without saying so." + ) + return _as_bool(value) + + def _onion_of(domain: str, primary: str, node_onion: str) -> str | None: """Return ``domain`` with the clearnet ``primary`` suffix swapped for the node onion, or None when the domain is not under ``primary``.""" @@ -48,6 +96,9 @@ def _inject_onion_domains( apps: dict[str, Any], primary: str, node_onion: str, + *, + templar: Any = None, + variables: Any = None, ) -> dict[str, Any]: """Add ``.`` domains for apps opting into onion routing. @@ -63,21 +114,38 @@ def _inject_onion_domains( ) registry = build_service_registry_from_applications(apps) + + def _flag(value: Any, app: str, name: str) -> bool: + return _resolved_flag( + value, + app=app, + name=name, + templar=templar, + variables=variables, + apps=apps, + ) + out: dict[str, Any] = {} for app, domains in merged.items(): tor = ((apps.get(app) or {}).get("services") or {}).get("tor") or {} - if not isinstance(domains, (list, dict)) or not _as_bool(tor.get("enabled")): + if not isinstance(domains, (list, dict)) or not _flag( + tor.get("enabled"), app, "enabled" + ): out[app] = domains continue - exclusive = _as_bool( + exclusive = _flag( resolve_service_config( apps, app, "tor", "exclusive", default=False, service_registry=registry - ) + ), + app, + "exclusive", ) - is_primary = _as_bool( + is_primary = _flag( resolve_service_config( apps, app, "tor", "primary", default=False, service_registry=registry - ) + ), + app, + "primary", ) if isinstance(domains, dict): out[app] = _inject_onion_into_dict( @@ -141,7 +209,9 @@ def get_merged_domains( issued while the applications render is in progress sees the unrendered tree, whose service flags are still Jinja strings; its map is cached under its own key so the render's own call sites reuse it without it ever being - served as the finished map. + served as the finished map. The tor flags are rendered before they are + read (``_resolved_flag``), so that mid-render map carries the same onion + domains the finished one does. """ from plugins.filter.canonical_domains_map import ( FilterModule as _CanonicalDomainsFilter, @@ -200,7 +270,14 @@ def get_merged_domains( node_onion = str(_render_raw(node_raw or "", "services.tor.node") or "").strip() group_names = variables.get("group_names") or [] if node_onion and "svc-net-tor" in group_names: - merged = _inject_onion_domains(merged, apps, str(primary_domain), node_onion) + merged = _inject_onion_domains( + merged, + apps, + str(primary_domain), + node_onion, + templar=templar, + variables=variables, + ) _MERGED_DOMAINS_CACHE[cache_key] = merged return merged