From 41ea801fd936e4a30aebeb15cc4dc37ef3918651 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Fri, 30 Oct 2026 18:00:24 +0100 Subject: [PATCH] feat(network): point logout and peer allowlists at every network a vhost serves CI run 40979252521 Nextcloud#0: on the onion pass the biber OIDC logout cleared only the clearnet session, because Keycloak holds one front-channel URL per client and the injected logout sent no post-logout target for the onion network; and Collabora's aliasgroup1 listed only the clearnet WOPI host. On a vhost outside the application's canonical network (and without an external issuer) the injected logout one-liner now adds client_id and post_logout_redirect_uri set to that network's logout conductor, and Keycloak registers every conductor sibling as post-logout redirect URI next to '+'. Collabora's aliasgroup1 lists the Nextcloud WOPI host of every network (one instance, union allowlist). network_modes.md gains a Network-Aligned Values table, and test_network_allowlist_sinks.py fails when a template names an allowlist sink without the sibling union. Rendering is covered by 14 tests; the full gate and the runtime acceptance of the '##' post-logout list by Keycloak and the comma aliasgroup by Collabora still need a gate on store-i18n and an onion deploy. Co-Authored-By: Claude Opus 5.5 --- docs/contributing/design/network_modes.md | 16 ++ .../templates/logout_one_liner.js.j2 | 6 +- roles/web-app-keycloak/vars/main.yml | 2 +- roles/web-svc-collabora/templates/env.j2 | 2 +- roles/web-svc-collabora/vars/main.yml | 7 +- .../roles/test_network_allowlist_sinks.py | 145 ++++++++++++++++++ .../roles/sys-front-inj-logout/__init__.py | 0 .../test_logout_one_liner.py | 75 +++++++++ .../roles/web-svc-collabora/test_wopi_host.py | 30 +++- 9 files changed, 276 insertions(+), 7 deletions(-) create mode 100644 tests/lint/ansible/roles/test_network_allowlist_sinks.py create mode 100644 tests/unit/python/roles/sys-front-inj-logout/__init__.py create mode 100644 tests/unit/python/roles/sys-front-inj-logout/test_logout_one_liner.py diff --git a/docs/contributing/design/network_modes.md b/docs/contributing/design/network_modes.md index 1fd688f48f..60d065690a 100644 --- a/docs/contributing/design/network_modes.md +++ b/docs/contributing/design/network_modes.md @@ -56,6 +56,22 @@ The effective networks of a role are the node's networks that the role allows, w 5. Injected snippets ([sys-front-inj-all](../../../roles/sys-front-inj-all/)) and the CSP header ([content_security_policy.conf.j2](../../../roles/sys-svc-proxy/templates/headers/content_security_policy.conf.j2)) are rendered per vhost. Clearnet vhosts of a role served on more than one network send `Onion-Location`. 6. Redirect vhosts redirect inside the network of their source domain. +## Network-Aligned Values 🧭 + +A value that names an own or peer host MUST point to the network of the vhost that serves it. Pick the form by how the value is consumed: + +| Value | Form | How | +|---|---|---| +| Allowlist a peer checks (OIDC redirect and post-logout URIs, web origins, Collabora `aliasgroupN`, trusted domains, CSP sources) | Union of every sibling, rendered once | `lookup('network_urls', url)` for a URL, a loop over `lookup('network_siblings', domain)` when each entry needs its own scheme or port | +| Asset a browser loads (logo, icon, manifest icon, CDN file) | Same-origin path | `lookup('design', ...).relative_urls`, `lookup('cdn', ...).relative_urls`; `/_infinito/cdn/` is served on every vhost | +| Pointer a browser follows from a snippet rendered per vhost (injected script, proxy config) | Rendered per vhost | `lookup('tls', '', 'url.base')` with `domain` in scope, which aligns the term to the vhost's network | +| Own public URL an application keeps in one server-side setting | Request-derived or one instance per network | Let the application read `X-Forwarded-Host` and `X-Forwarded-Proto`, which every vhost sends; otherwise run one instance per network as [web-svc-logout](../../../roles/web-svc-logout/templates/compose.yml.j2) does with `network_instances` | + +- A role MUST NOT write an onion host by hand or rewrite hosts in its own proxy config. +- The SSO issuer is the one host that stays canonical on every network. +- Logout: Keycloak holds one front-channel URL per client, the canonical logout conductor. On a vhost outside the canonical network the injected logout patch adds `client_id` and `post_logout_redirect_uri` set to that network's conductor, and Keycloak registers every conductor sibling as post-logout redirect URI next to `+`. An external issuer (`OIDC_OVERRIDE.URL`) keeps the bare logout URL. +- [test_network_allowlist_sinks.py](../../../tests/lint/ansible/roles/test_network_allowlist_sinks.py) fails when a role template names an allowlist sink without the sibling union. Suppress a single-network peer with `# nocheck: network-allowlist` and a reason. + ## Checks 🩺 - [sys-ctl-hlth-webserver](../../../roles/sys-ctl-hlth-webserver/) probes every vhost with that vhost's scheme. diff --git a/roles/sys-front-inj-logout/templates/logout_one_liner.js.j2 b/roles/sys-front-inj-logout/templates/logout_one_liner.js.j2 index c1ca1c90db..df2d7f90df 100644 --- a/roles/sys-front-inj-logout/templates/logout_one_liner.js.j2 +++ b/roles/sys-front-inj-logout/templates/logout_one_liner.js.j2 @@ -1,6 +1,10 @@ +{% set logout_target = OIDC.CLIENT.LOGOUT_URL %} +{% if (OIDC_OVERRIDE is not defined or OIDC_OVERRIDE.URL is not defined) and (domain | network_of) != (lookup('domain', application_id) | network_of) %} +{% set logout_target = logout_target ~ '?' ~ ({'client_id': OIDC.CLIENT.ID, 'post_logout_redirect_uri': lookup('tls', 'web-svc-logout', 'url.base')} | urlencode) %} +{% endif %} document.addEventListener('DOMContentLoaded', function() { initLogoutPatch( - '{{ OIDC.CLIENT.LOGOUT_URL }}', + '{{ logout_target }}', {{ MODE_DEBUG | lower }} ); }); diff --git a/roles/web-app-keycloak/vars/main.yml b/roles/web-app-keycloak/vars/main.yml index d5139f9184..82764a0748 100644 --- a/roles/web-app-keycloak/vars/main.yml +++ b/roles/web-app-keycloak/vars/main.yml @@ -121,7 +121,7 @@ KEYCLOAK_WEB_ORIGINS: >- | map('regex_search','^(https?://[^/]+)') | select('string') | list | unique }} -KEYCLOAK_POST_LOGOUT_URIS: "+" +KEYCLOAK_POST_LOGOUT_URIS: "{{ (['+'] + lookup('network_urls', KEYCLOAK_FRONTCHANNEL_LOGOUT_URL ~ '*')) | join('##') }}" KEYCLOAK_LDAP_ENABLED: "{{ lookup('config', application_id, 'services.ldap.enabled') }}" KEYCLOAK_LDAP_SHARED: "{{ lookup('config', application_id, 'services.ldap.shared') }}" diff --git a/roles/web-svc-collabora/templates/env.j2 b/roles/web-svc-collabora/templates/env.j2 index 81817edc81..c1cfd8b77d 100644 --- a/roles/web-svc-collabora/templates/env.j2 +++ b/roles/web-svc-collabora/templates/env.j2 @@ -1,4 +1,4 @@ {% include 'roles/sys-svc-container/templates/env.j2' %} -aliasgroup1={{ COLLABORA_WOPI_HOST }} +aliasgroup1={{ COLLABORA_WOPI_HOSTS }} extra_params=--o:ssl.enable=false --o:ssl.termination={{ lookup('tls', application_id, 'enabled') | lower }} --o:net.service_root=/ --o:net.post_allow.host[99]={{ networks.internet.ip4 }}/32 diff --git a/roles/web-svc-collabora/vars/main.yml b/roles/web-svc-collabora/vars/main.yml index d42d5fe956..2cd7979d59 100644 --- a/roles/web-svc-collabora/vars/main.yml +++ b/roles/web-svc-collabora/vars/main.yml @@ -6,6 +6,9 @@ domain: "{{ lookup('domain',application_id) }}" http_port: "{{ lookup('config', application_id, 'services.collabora.ports.local.http') }}" COLLABORA_CONTAINER: "{{ lookup('config', application_id, 'services.collabora.name') }}" -COLLABORA_WOPI_HOST: "{{ lookup('tls', lookup('domain', 'web-app-nextcloud'), 'protocols.web') }}://{{ lookup('domain', 'web-app-nextcloud') }}:{{ lookup('tls', lookup('domain', - 'web-app-nextcloud'), 'ports.web') }}" +COLLABORA_WOPI_HOSTS: >- + {% for wopi_domain in lookup('network_siblings', lookup('domain', 'web-app-nextcloud')) %} + {{- lookup('tls', wopi_domain, 'protocols.web') }}://{{ wopi_domain }}:{{ lookup('tls', wopi_domain, 'ports.web') }} + {{- '' if loop.last else ',' }} + {%- endfor %} COLLABORA_DISCOVERY_PATH: "/hosting/discovery" diff --git a/tests/lint/ansible/roles/test_network_allowlist_sinks.py b/tests/lint/ansible/roles/test_network_allowlist_sinks.py new file mode 100644 index 0000000000..2e4584845d --- /dev/null +++ b/tests/lint/ansible/roles/test_network_allowlist_sinks.py @@ -0,0 +1,145 @@ +"""Lint: a once-rendered allowlist names every network sibling of its hosts. + +A role template rendered outside the vhost loop cannot know which network +sibling will be asked, so a value that lists the hosts a peer accepts +(Collabora ``aliasgroupN=``, Keycloak ``redirectUris``, ``webOrigins`` and +``post.logout.redirect.uris``, ``trusted_domains``) MUST be the union of every +sibling. A sink line passes when its value, or a variable it reads (resolved +through ``{% set %}`` in the same file and the role's ``vars/main.yml``), +derives its hosts from ``network_urls``, ``network_siblings`` or +``redirect_uris``, or when it holds no host lookup at all. See +``docs/contributing/design/network_modes.md``. + +Suppress a genuine exception with ``# nocheck: network-allowlist`` on (or +above) the offending line. +""" + +from __future__ import annotations + +import re +import unittest +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import iter_project_files, read_text +from utils.cache.yaml import load_yaml_str +from utils.roles.mapping import ROLE_FILE_VARS_MAIN + +from . import PROJECT_ROOT + +RULE = "network-allowlist" +SINK = re.compile( + r"(aliasgroup\d+\s*=|\"(?:redirectUris|webOrigins|post\.logout\.redirect\.uris)\"\s*:|trusted_domains)(?P.*)$" +) +MECHANISM = re.compile(r"network_urls|network_siblings|redirect_uris") +HOST_LOOKUP = re.compile( + r"lookup\(\s*['\"](?:tls|domain|domains|canonical_url|landing_url)['\"]" +) +NAME = re.compile(r"\b([A-Za-z_][A-Za-z0-9_]*)\b") +SET = re.compile(r"{%-?\s*set\s+([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)-?%}") +MAX_DEPTH = 4 + + +def _definitions(text: str, role_vars: dict) -> dict[str, str]: + names = {key: str(value) for key, value in role_vars.items()} + names.update(dict(SET.findall(text))) + return names + + +def _verdict(value: str, names: dict[str, str], depth: int = 0) -> str: + """Return ``aligned``, ``hostless`` or ``unaligned`` for one expression. + + Args: + value: the Jinja expression or YAML value to classify. + names: variable name -> definition, from ``{% set %}`` and role vars. + depth: recursion depth through variable references. + """ + if MECHANISM.search(value): + return "aligned" + verdicts = {"unaligned"} if HOST_LOOKUP.search(value) else set() + if depth < MAX_DEPTH: + for name in set(NAME.findall(value)) & names.keys(): + verdicts.add(_verdict(names[name], names, depth + 1)) + if "aligned" in verdicts: + return "aligned" + return "unaligned" if "unaligned" in verdicts else "hostless" + + +def violations(text: str, role_vars: dict, rel: str) -> list[str]: + names = _definitions(text, role_vars) + lines = text.splitlines() + found = [] + for index, line in enumerate(lines): + match = SINK.search(line) + if not match or _verdict(match.group("value"), names) != "unaligned": + continue + if is_suppressed_at(lines, index, RULE): + continue + found.append(f"{rel}:{index + 1}: {line.strip()}") + return found + + +def _role_vars(role_dir) -> dict: + path = role_dir / ROLE_FILE_VARS_MAIN + if not path.is_file(): + return {} + return load_yaml_str(read_text(str(path))) or {} + + +class TestNetworkAllowlistSinks(unittest.TestCase): + def test_once_rendered_allowlists_name_every_network_sibling(self): + found = [] + for path in iter_project_files(extensions=(".j2",)): + rel = Path(path).relative_to(PROJECT_ROOT).as_posix() + parts = rel.split("/") + if len(parts) < 4 or parts[0] != "roles" or parts[2] != "templates": + continue + role_vars = _role_vars(PROJECT_ROOT / "roles" / parts[1]) + found.extend(violations(read_text(str(path)), role_vars, rel)) + self.assertEqual( + found, + [], + "Allowlists rendered once per role must list every network " + "sibling (lookup('network_urls', ...) or " + "lookup('network_siblings', ...)):\n" + "\n".join(found), + ) + + def test_a_single_canonical_host_is_reported(self): + role_vars = { + "WOPI": "{{ lookup('tls', lookup('domain', 'web-app-nextcloud'), 'url.origin') }}" + } + self.assertEqual( + violations("aliasgroup1={{ WOPI }}\n", role_vars, "env.j2"), + ["env.j2:1: aliasgroup1={{ WOPI }}"], + ) + + def test_a_sibling_union_passes(self): + role_vars = { + "WOPI": "{% for d in lookup('network_siblings', lookup('domain', 'x')) %}{{ d }}{% endfor %}" + } + self.assertEqual( + violations("aliasgroup1={{ WOPI }}\n", role_vars, "env.j2"), [] + ) + + def test_a_set_binding_through_network_urls_passes(self): + text = ( + "{% set web = lookup('network_urls', lookup('tls', 'x', 'url.origin')) %}\n" + '"webOrigins": {{ web | to_json }},\n' + ) + self.assertEqual(violations(text, {}, "c.json.j2"), []) + + def test_a_hostless_value_passes(self): + self.assertEqual( + violations('"post.logout.redirect.uris": "+",\n', {}, "r.json.j2"), [] + ) + + def test_the_marker_suppresses(self): + text = ( + "# nocheck: network-allowlist single-network peer\n" + "aliasgroup1={{ lookup('domain', 'x') }}\n" + ) + self.assertEqual(violations(text, {}, "env.j2"), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/sys-front-inj-logout/__init__.py b/tests/unit/python/roles/sys-front-inj-logout/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/sys-front-inj-logout/test_logout_one_liner.py b/tests/unit/python/roles/sys-front-inj-logout/test_logout_one_liner.py new file mode 100644 index 0000000000..419b60bdb7 --- /dev/null +++ b/tests/unit/python/roles/sys-front-inj-logout/test_logout_one_liner.py @@ -0,0 +1,75 @@ +from __future__ import annotations + +import unittest +from urllib.parse import parse_qs, urlsplit + +from jinja2 import Environment, StrictUndefined, select_autoescape + +from plugins.filter.network_of import network_of +from utils.cache.files import PROJECT_ROOT, read_text + +TEMPLATE = PROJECT_ROOT / "roles/sys-front-inj-logout/templates/logout_one_liner.js.j2" +ONION = "a" * 56 + ".onion" +LOGOUT_URL = "https://auth.example/realms/example/protocol/openid-connect/logout" +CONDUCTORS = {"clearnet": "https://logout.example/", "tor": f"http://logout.{ONION}/"} + + +def logout_target(domain: str, canonical: str, **extra) -> str: + def lookup(name, *terms): + if name == "domain": + return canonical + if name == "tls" and terms == ("web-svc-logout", "url.base"): + return CONDUCTORS[network_of(domain)] + raise AssertionError(f"unexpected lookup: {name!r} {terms!r}") + + env = Environment( + undefined=StrictUndefined, + autoescape=select_autoescape(default_for_string=False), + ) + env.filters["network_of"] = network_of + rendered = env.from_string(read_text(str(TEMPLATE))).render( + lookup=lookup, + domain=domain, + application_id="web-app-nextcloud", + MODE_DEBUG=False, + OIDC={"CLIENT": {"LOGOUT_URL": LOGOUT_URL, "ID": "example"}}, + **extra, + ) + return rendered.split("initLogoutPatch(")[1].split("'")[1] + + +class TestLogoutOneLiner(unittest.TestCase): + def test_the_canonical_vhost_keeps_the_bare_issuer_logout(self): + self.assertEqual( + logout_target("next.cloud.example", "next.cloud.example"), LOGOUT_URL + ) + + def test_the_onion_vhost_returns_to_the_onion_conductor(self): + target = urlsplit(logout_target(f"next.cloud.{ONION}", "next.cloud.example")) + self.assertEqual(f"{target.scheme}://{target.netloc}{target.path}", LOGOUT_URL) + self.assertEqual( + parse_qs(target.query), + { + "client_id": ["example"], + "post_logout_redirect_uri": [CONDUCTORS["tor"]], + }, + ) + + def test_an_onion_only_node_keeps_the_bare_issuer_logout(self): + self.assertEqual( + logout_target(f"next.cloud.{ONION}", f"next.cloud.{ONION}"), LOGOUT_URL + ) + + def test_an_external_issuer_keeps_the_bare_logout(self): + self.assertEqual( + logout_target( + f"next.cloud.{ONION}", + "next.cloud.example", + OIDC_OVERRIDE={"URL": "https://idp.example"}, + ), + LOGOUT_URL, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-svc-collabora/test_wopi_host.py b/tests/unit/python/roles/web-svc-collabora/test_wopi_host.py index 1751e10d67..d730492cf0 100644 --- a/tests/unit/python/roles/web-svc-collabora/test_wopi_host.py +++ b/tests/unit/python/roles/web-svc-collabora/test_wopi_host.py @@ -20,7 +20,18 @@ NEXTCLOUD_ONION = "next.cloud." + "a" * 56 + ".onion" COLLABORA_ONION = "collabora." + "a" * 56 + ".onion" -def wopi_host(domains: dict[str, list[str]]) -> str: +SINGLE_HOST_EXPRESSION = ( + "{{ lookup('tls', lookup('domain', 'web-app-nextcloud'), 'protocols.web') }}://" + "{{ lookup('domain', 'web-app-nextcloud') }}:" + "{{ lookup('tls', lookup('domain', 'web-app-nextcloud'), 'ports.web') }}" +) + + +def wopi_host( + domains: dict[str, list[str]], + siblings: dict[str, list[str]] | None = None, + expression: str | None = None, +) -> str: variables = { "domains": domains, "applications": {}, @@ -41,9 +52,12 @@ def wopi_host(domains: dict[str, list[str]]) -> str: return domains[terms[0]][0] if name == "tls": return tls.run(list(terms), variables=variables)[0] + if name == "network_siblings": + return (siblings or {}).get(terms[0], [terms[0]]) raise AssertionError(f"the expression calls an unexpected lookup: {name!r}") - expression = load_yaml_str(read_text(str(VARS)))["COLLABORA_WOPI_HOST"] + if expression is None: + expression = load_yaml_str(read_text(str(VARS)))["COLLABORA_WOPI_HOSTS"] env = Environment( undefined=StrictUndefined, autoescape=select_autoescape(default_for_string=False), @@ -87,6 +101,18 @@ class TestWopiHost(unittest.TestCase): "https://next.cloud.example:443", ) + def test_every_network_sibling_of_nextcloud_is_an_alias(self): + domains = { + "web-app-nextcloud": ["next.cloud.example", NEXTCLOUD_ONION], + "web-svc-collabora": ["collabora.example", COLLABORA_ONION], + } + siblings = {"next.cloud.example": ["next.cloud.example", NEXTCLOUD_ONION]} + expected = f"https://next.cloud.example:443,http://{NEXTCLOUD_ONION}:80" + self.assertEqual(wopi_host(domains, siblings), expected) + self.assertNotEqual( + wopi_host(domains, siblings, SINGLE_HOST_EXPRESSION), expected + ) + if __name__ == "__main__": unittest.main()