From 55c95e6960bcc4c3ce1d9a4923924ed23c8a4d41 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Fri, 16 Oct 2026 12:37:16 +0200 Subject: [PATCH] feat(networks): hand a role's non-canonical siblings over to its canonical URL Some servers build every absolute URL from one site URL, so a second network cannot be answered under its own origin. reachability.handover keeps the siblings but turns each one outside the canonical network into a 302 to the same path on the canonical URL (basic and ws_generic vhosts). The redirect target comes from the canonical domain, not the application id, because lookup('tls', application_id) follows the network of the vhost being rendered and would point the sibling at itself. The flag also drops Onion-Location for the role (Tor Browser would bounce between the two), skips those siblings in the CSP crawl, expects 302 from the webserver health check and keeps Playwright on the canonical domain. The key needs a nocheck reason like single_mode. Mattermost opts in: it builds every OAuth callback from its one SiteURL, so an onion login came back on the clearnet callback and failed with 400. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../actions/testing/suppression.md | 2 +- docs/contributing/design/network_modes.md | 4 +- .../lookup_plugins/csp_skip_domains.py | 49 ++++++++++++++----- .../filter_plugins/web_health_expectations.py | 19 ++++++- .../headers/content_security_policy.conf.j2 | 2 +- .../templates/vhost/basic.conf.j2 | 5 ++ .../templates/vhost/ws_generic.conf.j2 | 6 +++ .../test-e2e-playwright/tasks/02_run_one.yml | 4 +- roles/web-app-mattermost/meta/networks.yml | 2 + .../roles/meta/test_network_reachability.py | 17 +++++-- .../lookup_plugins/test_csp_skip_domains.py | 18 +++++-- .../test_web_health_expectations.py | 12 ++++- .../utils/networks/test_reachability.py | 9 ++++ utils/networks/reachability.py | 21 ++++++++ 14 files changed, 143 insertions(+), 27 deletions(-) diff --git a/docs/contributing/actions/testing/suppression.md b/docs/contributing/actions/testing/suppression.md index 5f333af503..4b324db113 100644 --- a/docs/contributing/actions/testing/suppression.md +++ b/docs/contributing/actions/testing/suppression.md @@ -45,7 +45,7 @@ The placement rule is per check. The catalog "Position" column uses these labels | --------------------------- | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `url` | same or above | [test_urls_reachable.py](../../../../tests/external/repository/test_urls_reachable.py) | Skips probing the literal HTTP(S) URL. Use for CDN roots and API base URLs that 4xx without a path. | | `onion-flag` | same or above | [test_onion_port_flag.py](../../../../tests/lint/ansible/services/test_onion_port_flag.py) | Accepts a `false` under `ports.onion`. The marker MUST carry a reason naming why that port stays off the node onion; a bare marker is rejected. | -| `network-reachability` | same or above | [test_network_reachability.py](../../../../tests/lint/ansible/roles/meta/test_network_reachability.py) | Accepts `reachability.single_mode: true`, or a `reachability.modes` list below every network, in `meta/networks.yml`. The marker MUST carry a reason naming why the role is not served on every network; a bare marker is rejected. | +| `network-reachability` | same or above | [test_network_reachability.py](../../../../tests/lint/ansible/roles/meta/test_network_reachability.py) | Accepts `reachability.single_mode: true`, `reachability.handover: true`, or a `reachability.modes` list below every network, in `meta/networks.yml`. The marker MUST carry a reason naming why the role is not served on every network; a bare marker is rejected. | | `docker-version` | same or above | [test_image_versions.py](../../../../tests/external/update/docker/test_image_versions.py), [test_semver_pinning.py](../../../../tests/lint/ansible/services/test_semver_pinning.py) | Skips both the live version-update warning and the non-semver-pin lint for that image's `version:` key. | | `repository-version` | same or above | [test_repository_versions.py](../../../../tests/external/update/repository/test_repository_versions.py), [test_semver_pinning.py](../../../../tests/lint/ansible/services/test_semver_pinning.py) | Skips both the live ref-update warning and the non-semver-pin lint for that entity's `ref:` key. | | `version-source` | same or above | [test_version_sources.py](../../../../tests/external/update/source/test_version_sources.py) | Skips the live update warning for a pin that declares its upstream in an `update:` block. | diff --git a/docs/contributing/design/network_modes.md b/docs/contributing/design/network_modes.md index 1fde924c97..1fd688f48f 100644 --- a/docs/contributing/design/network_modes.md +++ b/docs/contributing/design/network_modes.md @@ -35,11 +35,13 @@ A node runs in one `NETWORK_MODE`: reachability: modes: [clearnet, tor] single_mode: true # nocheck: network-reachability + handover: true # nocheck: network-reachability ``` - `modes` lists networks from the registry. An empty list or no key means every network. `multi` is a node mode, not a list value. - `single_mode: true` serves the role on `tor` when the node runs Tor and on `clearnet` otherwise, never on both. -- `single_mode: true` and a `modes` list below every network each carry `# nocheck: network-reachability` plus a reason on or directly above their line ([suppression.md](../actions/testing/suppression.md)). +- `handover: true` keeps every network sibling, but each sibling outside the canonical network answers `302` to the same path on the canonical URL and advertises no `Onion-Location`. The webserver health check expects that `302`, the CSP crawl skips those siblings and Playwright tests only the canonical domain. +- `single_mode: true`, `handover: true` and a `modes` list below every network each carry `# nocheck: network-reachability` plus a reason on or directly above their line ([suppression.md](../actions/testing/suppression.md)). [test_network_reachability.py](../../../tests/lint/ansible/roles/meta/test_network_reachability.py) enforces the schema and the marker. `meta/services.yml` keeps only the Tor service bond (`bond`, `enabled`, `shared`). diff --git a/roles/sys-ctl-hlth-csp/lookup_plugins/csp_skip_domains.py b/roles/sys-ctl-hlth-csp/lookup_plugins/csp_skip_domains.py index 16af34bded..5a655cdf93 100644 --- a/roles/sys-ctl-hlth-csp/lookup_plugins/csp_skip_domains.py +++ b/roles/sys-ctl-hlth-csp/lookup_plugins/csp_skip_domains.py @@ -6,7 +6,9 @@ from typing import Any from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase +from utils.networks.reachability import network_of, role_handover from utils.roles.applications.config import get +from utils.tls_common import iter_domains def _to_list(x: Any) -> list[str]: @@ -47,7 +49,8 @@ class LookupModule(LookupBase): service entry may declare ``domains: [, ...]``; when its ``enabled`` resolves falsy those canonicals get no vhost (e.g. the seaweedfs filer/master frontend on an onion node), so probing them can - only fail. + only fail. Also skips the siblings of a ``reachability.handover`` role + outside its canonical network. """ def _service_disabled_domains(self, applications: Mapping, app_id: str) -> set[str]: @@ -75,14 +78,9 @@ class LookupModule(LookupBase): skip.add(domain) return skip - def run( - self, - terms: list[Any] | None, - variables: dict[str, Any] | None = None, - **kwargs: Any, - ) -> list[list[str]]: - applications = lookup_loader.get( - "applications", + def _lookup(self, name: str, variables: dict[str, Any] | None) -> Any: + return lookup_loader.get( + name, loader=self._loader, templar=getattr(self, "_templar", None), ).run( @@ -92,14 +90,41 @@ class LookupModule(LookupBase): or {}, )[0] + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[list[str]]: + applications = self._lookup("applications", variables) + if not isinstance(applications, Mapping): return [[]] selection = _selection_from(kwargs.get("group_names")) + selected = [app for app in applications if not selection or app in selection] skip: set[str] = set() - for app_id in applications: - if not selection or app_id in selection: - skip |= self._service_disabled_domains(applications, app_id) + for app_id in selected: + skip |= self._service_disabled_domains(applications, app_id) + + handover = [ + app + for app in selected + if role_handover( + { + "networks": get( + applications, app, "networks", strict=False, default={} + ) + }, + app=app, + ) + ] + domains = self._lookup("domains", variables) if handover else {} + for app_id in handover: + names = list(iter_domains(domains.get(app_id))) + if names: + canonical = network_of(names[0]) + skip.update(name for name in names if network_of(name) != canonical) return [sorted(skip)] diff --git a/roles/sys-ctl-hlth-webserver/filter_plugins/web_health_expectations.py b/roles/sys-ctl-hlth-webserver/filter_plugins/web_health_expectations.py index 215ec60d04..0d2a1420ab 100644 --- a/roles/sys-ctl-hlth-webserver/filter_plugins/web_health_expectations.py +++ b/roles/sys-ctl-hlth-webserver/filter_plugins/web_health_expectations.py @@ -4,7 +4,13 @@ from pathlib import Path from ansible.errors import AnsibleError -from utils.networks.reachability import CLEARNET, network, network_of, sibling_domain +from utils.networks.reachability import ( + CLEARNET, + network, + network_of, + role_handover, + sibling_domain, +) from utils.roles.applications.config import get from utils.roles.applications.status_codes import DEFAULT_OK, codes_by_key from utils.tls_common import resolve_enabled, resolve_term @@ -144,7 +150,9 @@ def web_health_expectations( - If `www_enabled`: add and/or force www.* -> [301] for all domains. - Served view: with `served_domains` (the host's `lookup('domains')`) every app's canonical domains become the ones the node serves, each - inheriting the codes of its clearnet sibling via `node_onion`. + inheriting the codes of its clearnet sibling via `node_onion`; the + siblings of a `reachability.handover` app outside its canonical + network expect [302]. """ if not isinstance(applications, Mapping): return {} @@ -210,6 +218,13 @@ def web_health_expectations( _apply_served_view(per_app, served_domains, primary_domain, node_onion) + for app_id, app_exp in per_app.items(): + names = list(app_exp) + networks = get(applications, app_id, "networks", strict=False, default={}) + if names and role_handover({"networks": networks}, app=app_id): + canonical = network_of(names[0]) + app_exp.update({d: [302] for d in names if network_of(d) != canonical}) + expectations = {} for app_id, app_exp in per_app.items(): expectations.update(app_exp) 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 e60ad697b7..f134d1a2b2 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 @@ -21,7 +21,7 @@ header_filter_by_lua_block { if is_html then ngx.ctx.is_html = true ngx.header.content_length = nil -{% if _network == 'clearnet' and _onion.host and domain != (OIDC.URL | urlsplit('hostname')) %} +{% if _network == 'clearnet' and _onion.host and domain != (OIDC.URL | urlsplit('hostname')) and not lookup('config', application_id, 'networks.reachability.handover', False) %} ngx.header["Onion-Location"] = "{{ lookup('tls', _onion.host, 'url.base') | regex_replace('/+$', '') }}" .. ngx.var.request_uri {% endif %} else diff --git a/roles/sys-svc-proxy/templates/vhost/basic.conf.j2 b/roles/sys-svc-proxy/templates/vhost/basic.conf.j2 index 083ca42a67..89ff23408d 100644 --- a/roles/sys-svc-proxy/templates/vhost/basic.conf.j2 +++ b/roles/sys-svc-proxy/templates/vhost/basic.conf.j2 @@ -23,6 +23,11 @@ server return 302 {{ OIDC.URL }}$request_uri; } + {% elif lookup('config', application_id, 'networks.reachability.handover', False) and (domain | network_of) != (lookup('domain', application_id) | network_of) %} + location / { + return 302 {{ lookup('tls', lookup('domain', application_id), 'url.base') | regex_replace('/+$', '') }}$request_uri; + } + {% elif lookup('sso', application_id, 'is_proxy_gated') %} {% set acl = lookup('sso', application_id, 'oauth2_acl') %} diff --git a/roles/sys-svc-proxy/templates/vhost/ws_generic.conf.j2 b/roles/sys-svc-proxy/templates/vhost/ws_generic.conf.j2 index 0d8e2bbd64..2b1fa221cf 100644 --- a/roles/sys-svc-proxy/templates/vhost/ws_generic.conf.j2 +++ b/roles/sys-svc-proxy/templates/vhost/ws_generic.conf.j2 @@ -17,11 +17,17 @@ server { gzip_buffers 16 8k; gzip_http_version 1.1; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; + {% if lookup('config', application_id, 'networks.reachability.handover', False) and (domain | network_of) != (lookup('domain', application_id) | network_of) %} + location / { + return 302 {{ lookup('tls', lookup('domain', application_id), 'url.base') | regex_replace('/+$', '') }}$request_uri; + } + {% else %} {% include 'roles/sys-svc-proxy/templates/location/html.conf.j2' %} {% if webserver_websocket_location | default(false) %} {% include 'roles/sys-svc-proxy/templates/location/ws.conf.j2' %} {% endif %} + {% endif %} error_page 500 501 502 503 504 /500.html; {% include 'roles/web-app-prometheus/templates/nginx/locations.conf.j2' %} diff --git a/roles/test-e2e-playwright/tasks/02_run_one.yml b/roles/test-e2e-playwright/tasks/02_run_one.yml index 386307d930..c2e04e2849 100644 --- a/roles/test-e2e-playwright/tasks/02_run_one.yml +++ b/roles/test-e2e-playwright/tasks/02_run_one.yml @@ -168,7 +168,9 @@ ansible.builtin.set_fact: _playwright_network_picks: >- {{ _playwright_network_picks - | combine({application_id: lookup('network_siblings', lookup('domain', application_id)) | random}) }} + | combine({application_id: lookup('domain', application_id) + if lookup('config', application_id, 'networks.reachability.handover', False) + else lookup('network_siblings', lookup('domain', application_id)) | random}) }} when: application_id not in _playwright_network_picks - name: 🌈 Run Playwright on the picked network diff --git a/roles/web-app-mattermost/meta/networks.yml b/roles/web-app-mattermost/meta/networks.yml index 2cad14c791..f9003fa385 100644 --- a/roles/web-app-mattermost/meta/networks.yml +++ b/roles/web-app-mattermost/meta/networks.yml @@ -6,3 +6,5 @@ overlay: topology: shared_net consumer: kind: mcp_client +reachability: + handover: true # nocheck: network-reachability Mattermost builds every OAuth callback from its one SiteURL diff --git a/tests/lint/ansible/roles/meta/test_network_reachability.py b/tests/lint/ansible/roles/meta/test_network_reachability.py index 268842fa12..1cd7ceec31 100644 --- a/tests/lint/ansible/roles/meta/test_network_reachability.py +++ b/tests/lint/ansible/roles/meta/test_network_reachability.py @@ -2,11 +2,13 @@ ``meta/networks.yml`` ``reachability`` decides which networks a role is served on: ``modes`` lists them (empty or absent means every network) and -``single_mode`` keeps the role under one domain. The Tor service entry in +``single_mode`` keeps the role under one domain and ``handover`` sends every +non-canonical sibling to the canonical URL. The Tor service entry in ``meta/services.yml`` stays the dependency edge only, so ``exclusive`` and ``primary`` there would be a second source for the same decision. -A ``single_mode: true`` or a ``modes`` list below every network carries +A ``single_mode: true``, a ``handover: true`` or a ``modes`` list below every +network carries ``# nocheck: network-reachability`` plus a reason, on or directly above that line, so the next reader learns why the role is not served everywhere before widening it. @@ -20,14 +22,14 @@ import unittest from utils.annotations.suppress import line_has_rule from utils.cache.files import read_text from utils.cache.yaml import load_yaml_any -from utils.networks.reachability import NETWORKS, role_reachability +from utils.networks.reachability import NETWORKS, role_handover, role_reachability from utils.roles.mapping import ROLE_FILE_META_NETWORKS, ROLE_FILE_META_SERVICES from . import PROJECT_ROOT ROLES_DIR = PROJECT_ROOT / "roles" RETIRED_TOR_KEYS = ("exclusive", "primary") -REACHABILITY_KEYS = frozenset({"modes", "single_mode"}) +REACHABILITY_KEYS = frozenset({"handover", "modes", "single_mode"}) _RULE = "network-reachability" _MIN_REASON_CHARS = 10 @@ -83,6 +85,7 @@ class TestNetworkReachability(unittest.TestCase): modes, single_mode = role_reachability( {"networks": networks}, app=role_dir.name ) + handover = role_handover({"networks": networks}, app=role_dir.name) except (TypeError, ValueError) as exc: problems.append(str(exc)) continue @@ -93,7 +96,11 @@ class TestNetworkReachability(unittest.TestCase): ) lines = read_text(str(path)).splitlines() restricted = bool(modes) and set(modes) != set(NETWORKS) - for key, narrows in (("single_mode", single_mode), ("modes", restricted)): + for key, narrows in ( + ("single_mode", single_mode), + ("modes", restricted), + ("handover", handover), + ): if not narrows: continue line_no = _reachability_key_line(lines, key) diff --git a/tests/unit/python/roles/sys-ctl-hlth-csp/lookup_plugins/test_csp_skip_domains.py b/tests/unit/python/roles/sys-ctl-hlth-csp/lookup_plugins/test_csp_skip_domains.py index 8fcc53d0c1..5590a2144d 100644 --- a/tests/unit/python/roles/sys-ctl-hlth-csp/lookup_plugins/test_csp_skip_domains.py +++ b/tests/unit/python/roles/sys-ctl-hlth-csp/lookup_plugins/test_csp_skip_domains.py @@ -39,16 +39,28 @@ class CspSkipDomainsLookupTests(unittest.TestCase): "csp_skip_domains_lookup", ) - def _run(self, applications, **kwargs): + def _run(self, applications, domains=None, **kwargs): lm = self.module.LookupModule() lm._templar = _DummyTemplar() lm._loader = mock.MagicMock() + results = {"applications": applications, "domains": domains or {}} with patch.object(self.module, "lookup_loader") as loader_mock: - loader_mock.get.return_value = mock.MagicMock( - run=lambda *_a, **_k: [applications] + loader_mock.get.side_effect = lambda name, **_k: mock.MagicMock( + run=lambda *_a, **_kw: [results[name]] ) return lm.run(terms=[], variables={}, **kwargs)[0] + def test_a_handover_role_skips_its_siblings_outside_the_canonical_network(self): + apps = { + "web-app-chat": {"networks": {"reachability": {"handover": True}}}, + "web-app-wiki": {}, + } + domains = { + "web-app-chat": ["chat.example.com", "chat.node.onion"], + "web-app-wiki": ["wiki.example.com", "wiki.node.onion"], + } + self.assertEqual(self._run(apps, domains), ["chat.node.onion"]) + def test_empty_applications_returns_empty_list(self): self.assertEqual(self._run({}), []) diff --git a/tests/unit/python/roles/sys-ctl-hlth-webserver/filter_plugins/test_web_health_expectations.py b/tests/unit/python/roles/sys-ctl-hlth-webserver/filter_plugins/test_web_health_expectations.py index d0e282adea..7c4af078b0 100644 --- a/tests/unit/python/roles/sys-ctl-hlth-webserver/filter_plugins/test_web_health_expectations.py +++ b/tests/unit/python/roles/sys-ctl-hlth-webserver/filter_plugins/test_web_health_expectations.py @@ -563,7 +563,7 @@ class TestWebHealthExpectationsFilter(unittest.TestCase): ONION = "abc123def456ghij789klmno000pqrstuvwx111yz222abc333def444gh.onion" - def _app_a(self, canonical=None, status_codes=None, aliases=None): + def _app_a(self, canonical=None, status_codes=None, aliases=None, networks=None): returns = { ("app-a", "domains.canonical"): ( [f"a.{DOMAIN}"] if canonical is None else canonical @@ -573,6 +573,8 @@ class TestWebHealthExpectationsFilter(unittest.TestCase): returns[("app-a", "server.status_codes")] = status_codes if aliases is not None: returns[("app-a", "domains.aliases")] = aliases + if networks is not None: + returns[("app-a", "networks")] = networks self._configure_returns(returns) return {"app-a": {}} @@ -625,6 +627,14 @@ class TestWebHealthExpectationsFilter(unittest.TestCase): {f"a.{self.ONION}": [200, 302, 301], f"old.{DOMAIN}": [301]}, ) + def test_handover_siblings_outside_the_canonical_network_expect_302(self): + apps = self._app_a( + status_codes={"default": [200, 301]}, + networks={"reachability": {"handover": True}}, + ) + out = self._served(apps, {"app-a": [f"a.{DOMAIN}", f"a.{self.ONION}"]}) + self.assertEqual(out, {f"a.{DOMAIN}": [200, 301], f"a.{self.ONION}": [302]}) + def test_app_missing_from_served_keeps_declared_domains(self): out = self._served(self._app_a(), {}) self.assertEqual(out, {f"a.{DOMAIN}": [200, 302, 301]}) diff --git a/tests/unit/python/utils/networks/test_reachability.py b/tests/unit/python/utils/networks/test_reachability.py index 099bbc3637..20e34b068c 100644 --- a/tests/unit/python/utils/networks/test_reachability.py +++ b/tests/unit/python/utils/networks/test_reachability.py @@ -16,6 +16,7 @@ from utils.networks.reachability import ( network, network_of, resolve_node_mode, + role_handover, role_reachability, sibling_domain, ) @@ -130,6 +131,14 @@ class TestRoleReachability(unittest.TestCase): with self.assertRaises(TypeError): role_reachability(_cfg(single_mode="yes")) + def test_handover_defaults_to_false(self) -> None: + self.assertFalse(role_handover({})) + self.assertTrue(role_handover(_cfg(handover=True))) + + def test_handover_must_be_boolean(self) -> None: + with self.assertRaises(TypeError): + role_handover(_cfg(handover="yes")) + def test_tor_disabled_role_loses_tor(self) -> None: self.assertEqual(allowed_networks({}, tor_enabled=False), ((CLEARNET,), False)) diff --git a/utils/networks/reachability.py b/utils/networks/reachability.py index d8bf3357e3..537d4068a1 100644 --- a/utils/networks/reachability.py +++ b/utils/networks/reachability.py @@ -243,6 +243,27 @@ def role_reachability( return tuple(dict.fromkeys(modes)), single +def role_handover(app_config: Any, *, app: str = "") -> bool: + """Read ``networks.reachability.handover`` of one application. + + Args: + app_config: the application's merged config. + app: application id, for error messages. + + Returns: + The declared flag; False when absent. + + Raises: + TypeError: ``handover`` is not a boolean. + """ + networks = app_config.get("networks") if isinstance(app_config, Mapping) else None + reach = networks.get("reachability") if isinstance(networks, Mapping) else None + handover = reach.get("handover", False) if isinstance(reach, Mapping) else False + if not isinstance(handover, bool): + raise TypeError(f"{app}: networks.reachability.handover must be a boolean") + return handover + + def allowed_networks( app_config: Any, *, tor_enabled: bool, app: str = "" ) -> tuple[tuple[str, ...], bool]: