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)))