From 9e7c62a119b6adc075b2dc4e23f42d17cf27bb5f Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Fri, 9 Oct 2026 17:12:24 +0200 Subject: [PATCH] fix(network): let every proxied role reach its object store directly A role that exports an outbound proxy for one purpose applies it to every HTTP call the app makes, so an internal dependency reached by name is proxied too. web-app-pixelfed exported the Tor SOCKS proxy container-wide for its onion OIDC issuer and its S3 client then failed with cURL error 97: cannot complete SOCKS5 connection to seaweedfs for six minutes per attempt, until sixty retries had consumed the whole suite budget and the job was killed. web-app-espocrm ships a byte-identical proxy block and configures its S3 endpoint from the same lookup. web-app-nextcloud sets the proxy globally in proxy.config.php and listed two internal hosts in proxyexclude, neither of them the object store it reaches by hostname. 9d91fbea83 had tried to retire the per-app proxies in favour of onion routing over DNS, and 20ddda8c1c restored them for the OIDC issuer, so a broad proxy is the current design and the exemption list is load-bearing. lookup('proxy_excluded_hosts', application_id) is now that list: the loopback forms plus the object store host when the role stores objects. It is a lookup and not a group_vars value because no group_vars file resolves application_id, so a global would have depended on which role happened to be running. Nextcloud keeps its hand-written list of public hosts; only the internal half is derived. The lint gained a second rule for the class rather than the symptom: the nextcloud list named no loopback literal at all, so the literal rule could never have fired on it. A variable whose name marks it a proxy exclusion list must render the lookup, unless it only composes other exclusion variables, and a ..._PUBLIC_... list is exempt because it names no internal service. Co-Authored-By: Claude Opus 5 (1M context) --- plugins/lookup/proxy_excluded_hosts.py | 81 +++++++++++++++++++ roles/web-app-espocrm/templates/env.j2 | 2 +- roles/web-app-nextcloud/vars/main.yml | 4 +- roles/web-app-pixelfed/templates/env.j2 | 2 +- .../network/test_loopback_hosts_spot.py | 75 +++++++++++++++++ .../lookup/test_proxy_excluded_hosts.py | 33 ++++++++ 6 files changed, 192 insertions(+), 5 deletions(-) create mode 100644 plugins/lookup/proxy_excluded_hosts.py create mode 100644 tests/unit/python/plugins/lookup/test_proxy_excluded_hosts.py diff --git a/plugins/lookup/proxy_excluded_hosts.py b/plugins/lookup/proxy_excluded_hosts.py new file mode 100644 index 0000000000..8ddacdde2b --- /dev/null +++ b/plugins/lookup/proxy_excluded_hosts.py @@ -0,0 +1,81 @@ +from __future__ import annotations + +import contextlib +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + + +def merge_excluded(loopback: list[str], objstore_host: str) -> list[str]: + """Return the hosts a proxied client must reach directly, in order. + + Args: + loopback: the loopback spellings, from ``NETWORK_LOOPBACK_HOSTS``. + objstore_host: object store host, empty when the role stores no + objects or no engine is active. + + Returns: + Loopback first, then the object store, without duplicates. + """ + hosts = list(loopback) + if objstore_host and objstore_host not in hosts: + hosts.append(objstore_host) + return hosts + + +class LookupModule(LookupBase): + """ + Usage: + {{ lookup('proxy_excluded_hosts', application_id) }} + -> ['127.0.0.1', '::1', 'localhost', 'seaweedfs'] + + Single spot for the internal hosts a role's HTTP client must reach without + its proxy. A role that exports an outbound proxy for one purpose applies it + to every HTTP call the app makes, so an internal dependency reached by name + is proxied too and fails; enumerating the exemptions per role is what left + the object store out of them. + """ + + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[list[str]]: + if not terms or len(terms) != 1: + raise AnsibleError( + "lookup('proxy_excluded_hosts') expects exactly one term: " + "the application_id." + ) + application_id = str(terms[0]).strip() + variables = variables or getattr(self._templar, "available_variables", {}) or {} + + loopback = variables.get("NETWORK_LOOPBACK_HOSTS") + templar = getattr(self, "_templar", None) + if templar is not None and isinstance(loopback, str): + with contextlib.suppress(Exception): + loopback = templar.template(loopback) + if not isinstance(loopback, list) or not loopback: + raise AnsibleError( + "lookup('proxy_excluded_hosts') needs NETWORK_LOOPBACK_HOSTS " + "from group_vars/all/08_networks.yml; it resolved to " + f"{loopback!r}." + ) + + objstore = lookup_loader.get( + "objstore", + loader=getattr(self, "_loader", None), + templar=templar, + ) + enabled = objstore.run( + [application_id, "enabled"], variables=variables, **kwargs + )[0] + host = "" + if str(enabled).strip().lower() in {"true", "yes", "on", "1"}: + host = str( + objstore.run([application_id, "host"], variables=variables, **kwargs)[0] + ).strip() + + return [merge_excluded([str(entry) for entry in loopback], host)] diff --git a/roles/web-app-espocrm/templates/env.j2 b/roles/web-app-espocrm/templates/env.j2 index 60bdf927c1..af6b0d23d0 100644 --- a/roles/web-app-espocrm/templates/env.j2 +++ b/roles/web-app-espocrm/templates/env.j2 @@ -72,7 +72,7 @@ ESPOCRM_CONFIG_OIDC_USERNAME_CLAIM={{ OIDC.ATTRIBUTES.USERNAME }} http_proxy={{ ESPOCRM_OIDC_SOCKS_PROXY }} https_proxy={{ ESPOCRM_OIDC_SOCKS_PROXY }} -no_proxy={{ NETWORK_LOOPBACK_HOSTS | join(',') }} +no_proxy={{ lookup('proxy_excluded_hosts', application_id) | join(',') }} {% endif %} {% endif %} diff --git a/roles/web-app-nextcloud/vars/main.yml b/roles/web-app-nextcloud/vars/main.yml index 14568dfc9a..9103547955 100644 --- a/roles/web-app-nextcloud/vars/main.yml +++ b/roles/web-app-nextcloud/vars/main.yml @@ -72,9 +72,7 @@ NEXTCLOUD_PROXY_EXCLUDED_PUBLIC_HOSTS: - codeberg.org - gitlab.com -NEXTCLOUD_PROXY_EXCLUDED_INTERNAL_HOSTS: - - "{{ NEXTCLOUD_PROXY_DNS_NAME }}" - - "{{ NEXTCLOUD_CONTEXT_AGENT_DNS_NAME }}" +NEXTCLOUD_PROXY_EXCLUDED_INTERNAL_HOSTS: "{{ lookup('proxy_excluded_hosts', application_id) + [NEXTCLOUD_PROXY_DNS_NAME, NEXTCLOUD_CONTEXT_AGENT_DNS_NAME] }}" NEXTCLOUD_PROXY_SERVICE: "proxy" NEXTCLOUD_PROXY_CONTAINER: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_PROXY_SERVICE ~ '.name') }}" diff --git a/roles/web-app-pixelfed/templates/env.j2 b/roles/web-app-pixelfed/templates/env.j2 index 3145fb48dc..238e1ef43b 100644 --- a/roles/web-app-pixelfed/templates/env.j2 +++ b/roles/web-app-pixelfed/templates/env.j2 @@ -156,7 +156,7 @@ PF_OIDC_SCOPES="openid profile email" http_proxy={{ PIXELFED_OIDC_SOCKS_PROXY }} https_proxy={{ PIXELFED_OIDC_SOCKS_PROXY }} -no_proxy={{ NETWORK_LOOPBACK_HOSTS | join(',') }} +no_proxy={{ lookup('proxy_excluded_hosts', application_id) | join(',') }} {% endif %} {% endif %} diff --git a/tests/lint/repository/network/test_loopback_hosts_spot.py b/tests/lint/repository/network/test_loopback_hosts_spot.py index 39b2e57a8e..cc20e9cc5c 100644 --- a/tests/lint/repository/network/test_loopback_hosts_spot.py +++ b/tests/lint/repository/network/test_loopback_hosts_spot.py @@ -40,6 +40,11 @@ _COMMENT = re.compile(r"\s+#.*$") _HOST_LIST = re.compile( r"(?i)^[\s\-]*[\w.]*(?:no_proxy|allowed_hosts)\s*[:=]\s*(?P.+)$" ) +_LOOKUP = "proxy_excluded_hosts" +_INTERNAL_EXCLUSION = re.compile( + r"^(?P[A-Z][A-Z0-9_]*PROXY[A-Z0-9_]*(?:EXCLUDED|BYPASS)[A-Z0-9_]*)\s*:" +) +_COMPOSITION = re.compile(r"[A-Z][A-Z0-9_]*PROXY[A-Z0-9_]*(?:EXCLUDED|BYPASS)") def forms_in(text: str) -> set[str]: @@ -96,6 +101,45 @@ class TestLoopbackHostsSpot(unittest.TestCase): f"Offending lines:\n{formatted}" ) + def test_internal_proxy_exclusions_come_from_the_lookup(self) -> None: + findings: list[tuple[str, int, str]] = [] + for path_str, content in iter_project_files_with_content( + extensions=(".yml",), + exclude_tests=True, + ): + rel = Path(path_str).relative_to(PROJECT_ROOT).as_posix() + lines = content.splitlines() + for idx, line in enumerate(lines): + stripped = _COMMENT.sub("", line).strip() + match = _INTERNAL_EXCLUSION.match(stripped) + if not match or "PUBLIC" in match.group("key"): + continue + block = "\n".join(lines[idx : idx + 6]) + if _LOOKUP in block: + continue + value = stripped[len(match.group(0)) :] + if _COMPOSITION.search(value): + continue + if is_suppressed_at(lines, idx + 1, _RULE, mode="same-or-above"): + continue + findings.append((rel, idx + 1, match.group("key"))) + + if findings: + formatted = "\n".join( + f"- {p}:{n}: {k}" + for p, n, k in sorted(set(findings), key=lambda i: (i[0], i[1])) + ) + self.fail( + "Found proxy-exclusion lists that name their internal hosts by " + "hand. A role exporting a proxy applies it to every HTTP call " + "the app makes, so an internal dependency left off the list is " + "proxied and fails.\n\n" + f"Fix: render `lookup('{_LOOKUP}', application_id)` and " + "concatenate the role's own extra hosts. A list of public " + "hosts belongs in a separate `..._PUBLIC_...` variable.\n\n" + f"Offending variables:\n{formatted}" + ) + def test_the_scan_detects_host_lists_and_not_their_near_misses(self) -> None: caught = ( "no_proxy=localhost,127.0.0.1", @@ -129,6 +173,37 @@ class TestLoopbackHostsSpot(unittest.TestCase): "every form must be detectable, or the rule passes vacuously", ) + def test_the_exclusion_scan_separates_enumeration_from_composition(self) -> None: + enumerating = 'ROLE_PROXY_EXCLUDED_INTERNAL_HOSTS: ["db", "cache"]' + match = _INTERNAL_EXCLUSION.match(enumerating) + self.assertIsNotNone(match, "an internal exclusion list must be recognised") + self.assertNotIn("PUBLIC", match.group("key")) + value = enumerating[len(match.group(0)) :] + self.assertIsNone( + _COMPOSITION.search(value), + "a hand-written list must not look like a composition", + ) + + composed = ( + "ROLE_PROXY_EXCLUDED_HOSTS: " + '"{{ ROLE_PROXY_EXCLUDED_PUBLIC_HOSTS + ROLE_PROXY_EXCLUDED_INTERNAL_HOSTS }}"' + ) + composed_match = _INTERNAL_EXCLUSION.match(composed) + self.assertIsNotNone(composed_match) + self.assertIsNotNone( + _COMPOSITION.search(composed[len(composed_match.group(0)) :]), + "a concatenation of other exclusion vars must count as composition", + ) + + public = 'ROLE_PROXY_EXCLUDED_PUBLIC_HOSTS: ["github.com"]' + public_match = _INTERNAL_EXCLUSION.match(public) + self.assertIsNotNone(public_match) + self.assertIn( + "PUBLIC", + public_match.group("key"), + "a public host list must be exempt; it names no internal service", + ) + def test_the_spot_covers_every_loopback_form(self) -> None: spot = read_text(str(PROJECT_ROOT / _SPOT_FILE)) declared = [ diff --git a/tests/unit/python/plugins/lookup/test_proxy_excluded_hosts.py b/tests/unit/python/plugins/lookup/test_proxy_excluded_hosts.py new file mode 100644 index 0000000000..adefb61142 --- /dev/null +++ b/tests/unit/python/plugins/lookup/test_proxy_excluded_hosts.py @@ -0,0 +1,33 @@ +import unittest + +from plugins.lookup.proxy_excluded_hosts import merge_excluded + +LOOPBACK = ["127.0.0.1", "::1", "localhost"] + + +class TestMergeExcluded(unittest.TestCase): + def test_the_object_store_follows_the_loopback_forms(self) -> None: + self.assertEqual( + ["127.0.0.1", "::1", "localhost", "seaweedfs"], + merge_excluded(LOOPBACK, "seaweedfs"), + ) + + def test_no_object_store_leaves_the_loopback_forms_alone(self) -> None: + self.assertEqual(LOOPBACK, merge_excluded(LOOPBACK, "")) + + def test_every_loopback_form_survives(self) -> None: + for form in LOOPBACK: + with self.subTest(form=form): + self.assertIn(form, merge_excluded(LOOPBACK, "seaweedfs")) + + def test_an_object_store_named_like_loopback_is_not_duplicated(self) -> None: + self.assertEqual(LOOPBACK, merge_excluded(LOOPBACK, "localhost")) + + def test_the_caller_list_is_not_mutated(self) -> None: + original = list(LOOPBACK) + merge_excluded(original, "seaweedfs") + self.assertEqual(LOOPBACK, original) + + +if __name__ == "__main__": # pragma: no cover + unittest.main()