diff --git a/docs/contributing/actions/testing/suppression.md b/docs/contributing/actions/testing/suppression.md index b0f3939497..e92e12658a 100644 --- a/docs/contributing/actions/testing/suppression.md +++ b/docs/contributing/actions/testing/suppression.md @@ -45,6 +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. | | `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. | | `dockerfile-arg-default` | same or above | [test_arg_without_default.py](../../../../tests/lint/docker/dockerfile/test_arg_without_default.py) | Allows the marked `ARG` to carry a default. The caller normally supplies every build argument so a missing one fails the build instead of selecting a base image nobody chose. | diff --git a/group_vars/all/08_networks.yml b/group_vars/all/08_networks.yml index f757e83a3e..94e8ec9042 100644 --- a/group_vars/all/08_networks.yml +++ b/group_vars/all/08_networks.yml @@ -1,4 +1,6 @@ --- +# clearnet | tor | multi; empty derives multi when svc-net-tor is deployed, else clearnet. +NETWORK_MODE: "" NETWORK_IPV6_ENABLED: false NETWORK_PUBLIC_DNS_RESOLVERS: - 1.1.1.1 # nocheck: hardcoded-dns-resolver diff --git a/plugins/filter/csp_filters.py b/plugins/filter/csp_filters.py index 3ff788bb42..4ba1c84b3d 100644 --- a/plugins/filter/csp_filters.py +++ b/plugins/filter/csp_filters.py @@ -5,25 +5,43 @@ import re from ansible.errors import AnsibleFilterError from utils.domains.primary_domain import get_domain +from utils.networks.reachability import TOR, network, network_of from utils.roles.applications.config import get -from utils.tls_common import align_domain_to_consumer, is_onion_domain +from utils.tls_common import align_domain_to_consumer, iter_domains, resolve_enabled -_ONION_PLAINTEXT = {"https": "http", "wss": "ws"} -_ONION_SCHEME = re.compile(r"^(https|wss)(?=://)") +_PLAINTEXT = {"https": "http", "wss": "ws"} +_TLS_SCHEME = re.compile(r"^(https|wss)(?=://)") -def _aligned_url(domains, application_id, target_id, protocol): - """Provider URL for CSP tokens, family-aligned to the consuming app. +def _aligned_url(applications, domains, application_id, target_id, protocol, vhost): + """Provider URL for CSP tokens, aligned to the vhost the header belongs to. - The scheme follows the ALIGNED host, not the consumer: onion targets are - plaintext-only (http), so a clearnet consumer falling back to an onion-only - provider gets a token that matches what the asset injection actually loads. + Args: + applications: merged applications tree. + domains: the host's merged domain map. + application_id: the consuming application. + target_id: the provider application. + protocol: scheme a provider on a TLS network answers on. + vhost: the vhost the header is rendered for; empty aligns to the + consumer's primary domain. + + Returns: + ``://`` with the host in the vhost's network and the + scheme of that host, so the token matches what the page loads. """ domain = align_domain_to_consumer( - domains, target_id, get_domain(domains, target_id), consumer=application_id + domains, + target_id, + get_domain(domains, target_id), + consumer=application_id, + variables={"domain": vhost} if vhost else None, ) - scheme = "http" if is_onion_domain(domain) else protocol - return f"{scheme}://{domain}" + enabled = resolve_enabled( + (applications or {}).get(target_id) or {}, + protocol == "https", + primary_domain=domain, + ) + return f"{'https' if enabled else 'http'}://{domain}" def _dedup_preserve(seq): @@ -209,10 +227,24 @@ class FilterModule: extra_whitelist=None, extra_hashes=None, domain_primary=None, + vhost_domain=None, ): """ Builds the Content-Security-Policy header value dynamically based on application settings. + Args: + applications: merged applications tree. + application_id: the application the header protects. + domains: the host's merged domain map. + web_protocol: scheme providers on a TLS network answer on. + extra_whitelist: extra sources per directive. + extra_hashes: extra inline snippets per directive. + domain_primary: the node's ``DOMAIN_PRIMARY``. + vhost_domain: the vhost the header is rendered for. Provider + sources follow its network; on a tor vhost, whitelist sources + under ``domain_primary`` move to the node onion. The SSO + issuer keeps its one URL. + Key points: - CSP3-aware: supports base/elem/attr for styles and scripts. - Safari/CSP2 fallback: base directives (style-src, script-src) always include @@ -256,6 +288,17 @@ class FilterModule: tokens_by_dir = {} explicit_flags_by_dir = {} + fixed_tokens = set() + + def provider(target_id): + return _aligned_url( + applications, + domains, + application_id, + target_id, + web_protocol, + vhost_domain, + ) for directive in directives: explicit_flags = get( @@ -278,11 +321,7 @@ class FilterModule: "style-src-elem", "style-src", ): - tokens.append( - _aligned_url( - domains, application_id, "web-svc-cdn", web_protocol - ) - ) + tokens.append(provider("web-svc-cdn")) if directive in ( "script-src-elem", @@ -292,30 +331,18 @@ class FilterModule: "font-src", "media-src", ) and self.is_feature_enabled(applications, "tor", application_id): - tokens.append( - _aligned_url( - domains, application_id, "web-svc-mirror", web_protocol - ) - ) + tokens.append(provider("web-svc-mirror")) if directive in ( "script-src-elem", "connect-src", ) and self.is_feature_enabled(applications, "matomo", application_id): - tokens.append( - _aligned_url( - domains, application_id, "web-app-matomo", web_protocol - ) - ) + tokens.append(provider("web-app-matomo")) if directive == "connect-src" and self.is_feature_enabled( applications, "simpleicons", application_id ): - tokens.append( - _aligned_url( - domains, application_id, "web-svc-simpleicons", web_protocol - ) - ) + tokens.append(provider("web-svc-simpleicons")) if self.is_feature_enabled( applications, "recaptcha", application_id @@ -334,22 +361,22 @@ class FilterModule: if self.is_feature_enabled( applications, "dashboard", application_id ): - domain = domains.get("web-app-dashboard")[0] - tokens.append(f"{domain}") - if self.is_feature_enabled(applications, "logout", application_id): tokens.append( - _aligned_url( - domains, application_id, "web-svc-logout", web_protocol - ) - ) - tokens.append( - _aligned_url( + align_domain_to_consumer( domains, - application_id, - "web-app-keycloak", - web_protocol, + "web-app-dashboard", + get_domain(domains, "web-app-dashboard"), + consumer=application_id, + variables={"domain": vhost_domain} + if vhost_domain + else None, ) ) + if self.is_feature_enabled(applications, "logout", application_id): + tokens.append(provider("web-svc-logout")) + issuer = provider("web-app-keycloak") + fixed_tokens.add(issuer) + tokens.append(issuer) if directive in ( "script-src-attr", @@ -406,38 +433,28 @@ class FilterModule: merge_family("style-src", "style-src-elem", "style-src-attr") merge_family("script-src", "script-src-elem", "script-src-attr") - _svc_tor = (applications or {}).get("svc-net-tor") - node_onion = "" - if isinstance(_svc_tor, dict): - node_onion = ((_svc_tor.get("services") or {}).get("tor") or {}).get( + _tor_provider = (applications or {}).get(network(TOR).provider) + node = "" + if isinstance(_tor_provider, dict): + node = ((_tor_provider.get("services") or {}).get("tor") or {}).get( "node" ) or "" - if node_onion and domain_primary and domain_primary != node_onion: - app_domains = [str(d) for d in (domains.get(application_id) or [])] - app_has_onion = any(node_onion in d for d in app_domains) - app_has_clearnet = any(domain_primary in d for d in app_domains) - if app_has_onion: - for directive in list(tokens_by_dir.keys()): - toks = tokens_by_dir[directive] - if app_has_clearnet: - siblings = [ - _ONION_SCHEME.sub( - lambda m: _ONION_PLAINTEXT[m.group(1)], - t.replace(domain_primary, node_onion), - ) - for t in toks - if domain_primary in t - ] - tokens_by_dir[directive] = _dedup_preserve(toks + siblings) - else: - tokens_by_dir[directive] = _dedup_preserve( - [ - t.replace(domain_primary, node_onion) - if domain_primary in t - else t - for t in toks - ] + served_on = network_of( + vhost_domain or next(iter_domains(domains.get(application_id)), "") + ) + if node and domain_primary and served_on == TOR: + for directive in list(tokens_by_dir.keys()): + tokens_by_dir[directive] = _dedup_preserve( + [ + _TLS_SCHEME.sub( + lambda m: _PLAINTEXT[m.group(1)], + t.replace(domain_primary, node), ) + if domain_primary in t and t not in fixed_tokens + else t + for t in tokens_by_dir[directive] + ] + ) for directive, toks in list(tokens_by_dir.items()): tokens_by_dir[directive] = _sort_tokens(toks) diff --git a/plugins/filter/mirror_filters.py b/plugins/filter/mirror_filters.py index 8ba34319ef..421fb3d4de 100644 --- a/plugins/filter/mirror_filters.py +++ b/plugins/filter/mirror_filters.py @@ -10,11 +10,13 @@ Only literal `https://` tokens count as external assets: - tokens containing unresolved Jinja (`{{ ... }}`) point at deployment-own domains and are skipped, - wildcard tokens (`*`) cannot be mirrored deterministically, - - hosts on the deployment's primary domain (or `.onion`) are already local. + - hosts on the deployment's primary domain or outside clearnet are already local. """ from urllib.parse import urlsplit +from utils.networks.reachability import CLEARNET, network_of + def _iter_whitelist_tokens(app_config): whitelist = ((app_config or {}).get("csp") or {}).get("whitelist", {}) or {} @@ -35,7 +37,7 @@ def _external_host(token, primary_domain): host = urlsplit(token).hostname or "" if not host or "." not in host: return None - if host.endswith(".onion"): + if network_of(host) != CLEARNET: return None if primary_domain and ( host == primary_domain or host.endswith("." + primary_domain) diff --git a/plugins/filter/network_of.py b/plugins/filter/network_of.py new file mode 100644 index 0000000000..b7bc9833f3 --- /dev/null +++ b/plugins/filter/network_of.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +from utils.networks.reachability import network, network_of, sibling_domain + + +def network_sibling(domain: str, name: str, primary: str, node: str) -> str: + """Return ``domain`` translated into the network ``name``, or ``""`` when + it has no name there (see ``utils.networks.reachability.sibling_domain``).""" + return sibling_domain(domain, name, primary, node) or "" + + +def network_suffix(name: str) -> str: + """Return the domain suffix of the network ``name``, ``""`` for clearnet.""" + return network(name).suffix or "" + + +def network_suffixes(names) -> dict[str, str]: + """Return ``{name: suffix}`` for every network in ``names`` that has one.""" + return {name: suffix for name in names if (suffix := network_suffix(name))} + + +def in_network(domains, name: str) -> list[str]: + """Return the entries of ``domains`` that belong to the network ``name``.""" + return [domain for domain in domains if network_of(domain) == name] + + +class FilterModule: + def filters(self): + return { + "network_of": network_of, + "network_sibling": network_sibling, + "network_suffix": network_suffix, + "network_suffixes": network_suffixes, + "in_network": in_network, + } diff --git a/plugins/filter/timeout_start_sec_for_domains.py b/plugins/filter/timeout_start_sec_for_domains.py index ed44d59779..07f80715a7 100644 --- a/plugins/filter/timeout_start_sec_for_domains.py +++ b/plugins/filter/timeout_start_sec_for_domains.py @@ -1,5 +1,7 @@ from ansible.errors import AnsibleFilterError +from utils.networks.reachability import TOR, network_of + class FilterModule: def filters(self): @@ -63,9 +65,7 @@ class FilterModule: flat.extend(www_variants) unique_domains = sorted(set(flat)) - onion_count = sum( - 1 for d in unique_domains if str(d).lower().endswith(".onion") - ) + onion_count = sum(1 for d in unique_domains if network_of(d) == TOR) clearnet_count = len(unique_domains) - onion_count onion_seconds = ( per_domain_seconds diff --git a/plugins/filter/url/to_onion.py b/plugins/filter/url/to_onion.py deleted file mode 100644 index 6de7445b7d..0000000000 --- a/plugins/filter/url/to_onion.py +++ /dev/null @@ -1,34 +0,0 @@ -from __future__ import annotations - -from urllib.parse import urlsplit, urlunsplit - - -def to_onion_url(url: str, tor_node: str, primary_domain: str) -> str: - """Rewrite a browser-facing clearnet URL to its ``.onion`` mirror. - - When ``tor_node`` is set (svc-net-tor deployed) and the URL's host is the - ``primary_domain`` or a subdomain of it, swap that suffix for ``tor_node`` - and force the ``http`` scheme (onion services are plaintext-only). Anything - else — empty inputs, a host not under ``primary_domain``, an unparseable - value — is returned unchanged, so the filter is a safe no-op on clearnet. - """ - if not url or not tor_node or not primary_domain: - return url - - parts = urlsplit(url if "://" in url else "//" + url) - host = parts.hostname or "" - suffix = "." + primary_domain - - if host == primary_domain: - onion_host = tor_node - elif host.endswith(suffix): - onion_host = host[: -len(primary_domain)] + tor_node - else: - return url - - return urlunsplit(("http", onion_host, parts.path, parts.query, parts.fragment)) - - -class FilterModule: - def filters(self): - return {"to_onion_url": to_onion_url} diff --git a/plugins/lookup/cert.py b/plugins/lookup/cert.py index 53afb3e3ef..0e5b71486b 100644 --- a/plugins/lookup/cert.py +++ b/plugins/lookup/cert.py @@ -14,6 +14,7 @@ from ansible.errors import AnsibleError from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase +from utils.networks.reachability import network, network_of from utils.templating.jinja import render_strict from utils.tls_common import ( AVAILABLE_FLAVORS, @@ -210,6 +211,8 @@ class LookupModule(LookupBase): else: raise AnsibleError(f"cert: unsupported mode '{mode}'") + san_domains = [d for d in san_domains if network(network_of(d)).tls] + resolved: dict[str, Any] = { "application_id": app_id, "domain": primary_domain, diff --git a/plugins/lookup/container_extra_hosts.py b/plugins/lookup/container_extra_hosts.py index 4ba17a12fd..8e0de6e8d5 100644 --- a/plugins/lookup/container_extra_hosts.py +++ b/plugins/lookup/container_extra_hosts.py @@ -73,6 +73,7 @@ from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase from utils.networks.lookup_context import resolve_var +from utils.networks.reachability import TOR, is_network HOST_GATEWAY = "host-gateway" DOCKER_INTERNAL_HOST = "host.docker.internal" @@ -135,7 +136,7 @@ class LookupModule(LookupBase): return [] provider_host = str(self._lookup("tls", SSO_PROVIDER, "domain") or "").strip() - if not provider_host.endswith(".onion"): + if not is_network(provider_host, TOR): return [] return [ diff --git a/plugins/lookup/email.py b/plugins/lookup/email.py index 09170e9b1e..843ca989ab 100644 --- a/plugins/lookup/email.py +++ b/plugins/lookup/email.py @@ -9,6 +9,7 @@ from ansible.plugins.lookup import LookupBase from plugins.lookup.applications import LookupModule as ApplicationsLookup from plugins.lookup.domain import LookupModule as DomainLookup from plugins.lookup.users import LookupModule as UsersLookup +from utils.networks.reachability import network, network_of SYSTEM_EMAIL_PREFIX = "SYSTEM_EMAIL_" @@ -152,7 +153,7 @@ class LookupModule(LookupBase): if not external: return False mail_host = str(resolved.get("host") or "").lower() - if mail_host.endswith(".onion"): + if not network(network_of(mail_host)).tls: return False return _as_bool(variables.get("TLS_ENABLED")) if short_key == "port": diff --git a/plugins/lookup/network_siblings.py b/plugins/lookup/network_siblings.py new file mode 100644 index 0000000000..e71430e7f6 --- /dev/null +++ b/plugins/lookup/network_siblings.py @@ -0,0 +1,72 @@ +"""The vhost domains one logical domain is served under on this host.""" + +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.reachability import NETWORKS, TOR, network, sibling_domain +from utils.tls_common import iter_domains, norm_domain + + +def served_siblings( + domain: str, domains: dict[str, Any], primary: str, node: str +) -> list[str]: + """Return the vhost domains ``domain`` is served under. + + Args: + domain: the domain a role asks to front. + domains: the host's merged domain map. + primary: the node's ``DOMAIN_PRIMARY``. + node: the node onion address, empty without Tor. + + Returns: + One domain per network the owning app is served on, canonical network + first; ``[]`` for a non-canonical sibling whose canonical twin renders + it; ``[domain]`` for a domain the map does not know. + """ + host = norm_domain(domain) + variants = [ + variant + for name in NETWORKS + if (variant := sibling_domain(host, name, primary, node)) + ] + for value in domains.values(): + served = [norm_domain(d) for d in iter_domains(value)] + found = [variant for variant in variants if variant in served] + if not found: + continue + if host in served and host != found[0]: + return [] + return found + return [host] + + +class LookupModule(LookupBase): + """ + Usage: + {{ lookup('network_siblings', domain) }} + """ + + def run(self, terms, variables: dict[str, Any] | None = None, **kwargs): + if not terms or len(terms) != 1 or not str(terms[0] or "").strip(): + raise AnsibleError("lookup('network_siblings', domain) expects one domain") + variables = variables or getattr(self._templar, "available_variables", {}) or {} + templar = getattr(self, "_templar", None) + + def _run(name: str, *args: str) -> Any: + return lookup_loader.get(name, loader=self._loader, templar=templar).run( + list(args), variables=variables + )[0] + + primary = variables.get("DOMAIN_PRIMARY") or "" + if templar is not None and isinstance(primary, str): + primary = templar.template(primary) + provider = network(TOR).provider + node = "" + if provider in (variables.get("group_names") or []): + node = str(_run("config", provider, "services.tor.node", "") or "").strip() + return [served_siblings(str(terms[0]), _run("domains"), str(primary), node)] diff --git a/plugins/lookup/playwright_workers.py b/plugins/lookup/playwright_workers.py index b4ce595db6..f176c82a59 100644 --- a/plugins/lookup/playwright_workers.py +++ b/plugins/lookup/playwright_workers.py @@ -3,11 +3,13 @@ from __future__ import annotations import contextlib import os from typing import Any +from urllib.parse import urlsplit from ansible.plugins.lookup import LookupBase from ansible.template import trust_as_template from utils.env.runtime import mem_available_mb, mem_total_mb +from utils.networks.reachability import TOR, network_of _PER_WORKER_GB = 1.5 _RAM_FRACTION = 0.5 @@ -123,7 +125,7 @@ class LookupModule(LookupBase): "{{ lookup('tls', " + repr(str(application_id)) + ", 'url.base') }}" ) ) - return ".onion" in str(base) + return network_of(urlsplit(str(base)).hostname or "") == TOR return False def run(self, terms, variables: dict[str, Any] | None = None, **kwargs): diff --git a/roles/svc-net-tor/files/test/test.sh b/roles/svc-net-tor/files/test/test.sh index 68677e034b..50011f7d6a 100755 --- a/roles/svc-net-tor/files/test/test.sh +++ b/roles/svc-net-tor/files/test/test.sh @@ -13,6 +13,7 @@ # Env (all required; the role's test.env carries them): # TOR_SOCKS SOCKS proxy for .onion (127.0.0.1:) +# ONION_SUFFIX host suffix of the tor network, from the network registry # NGINX_SERVERS_DIR the deployed OpenResty servers dir from the nginx lookup # RETRIES attempts per domain # SLEEP_SECONDS wait between attempts @@ -22,6 +23,7 @@ set -uo pipefail TOR_SOCKS="${TOR_SOCKS:?pass TOR_SOCKS as env (127.0.0.1:)}" +ONION_SUFFIX="${ONION_SUFFIX:?pass ONION_SUFFIX as env (the tor network suffix, from svc-net-tor test.env)}" NGINX_SERVERS_DIR="${NGINX_SERVERS_DIR:?pass NGINX_SERVERS_DIR as env (the deployed OpenResty vhost servers dir from the nginx lookup, e.g. /etc/nginx/conf.d/servers)}" RETRIES="${RETRIES:?pass RETRIES as env (attempts per domain, from svc-net-tor test.env)}" SLEEP_SECONDS="${SLEEP_SECONDS:?pass SLEEP_SECONDS as env (wait between attempts, from svc-net-tor test.env)}" @@ -49,7 +51,7 @@ echo "[INFO] probing ${#domains[@]} domain(s); onion via socks5://${TOR_SOCKS}" # Probe one domain with retries. Echoes the final HTTP code; returns 0 on success. probe() { local domain="$1" scheme curl_proxy=() attempt=1 code - if [[ "${domain}" == *.onion ]]; then + if [[ "${domain}" == *"${ONION_SUFFIX}" ]]; then scheme="http" curl_proxy=(--socks5-hostname "${TOR_SOCKS}") else diff --git a/roles/svc-net-tor/meta/services.yml b/roles/svc-net-tor/meta/services.yml index 8ea686d6c8..9ef6c822a8 100644 --- a/roles/svc-net-tor/meta/services.yml +++ b/roles/svc-net-tor/meta/services.yml @@ -17,8 +17,6 @@ tor: # nocheck: category-modes bond: 0.5 enabled: true shared: true - exclusive: true - primary: true image: debian version: 13.7-slim custom: true diff --git a/roles/svc-net-tor/templates/test.env.j2 b/roles/svc-net-tor/templates/test.env.j2 index 6e0bec9054..2922acbe87 100644 --- a/roles/svc-net-tor/templates/test.env.j2 +++ b/roles/svc-net-tor/templates/test.env.j2 @@ -3,6 +3,7 @@ ONION_HOST={{ lookup('config', 'svc-net-tor', 'services.tor.node') }} ONION_PORTS={{ lookup('tor_ports') | map(attribute='onion_port') | unique | sort | join(' ') | dotenv_quote }} ONION_PORT_RETRIES=2 ONION_PORT_TIMEOUT=60 +ONION_SUFFIX={{ 'tor' | network_suffix }} RETRIES=5 SLEEP_SECONDS=10 TOR_DNSMASQ_CONF={{ TOR_DNSMASQ_CONF }} diff --git a/roles/sys-ctl-hlth-csp/files/python/script.py b/roles/sys-ctl-hlth-csp/files/python/script.py index 7d085e23eb..5addba552e 100755 --- a/roles/sys-ctl-hlth-csp/files/python/script.py +++ b/roles/sys-ctl-hlth-csp/files/python/script.py @@ -35,50 +35,89 @@ def extract_domains_from_filenames(config_path: str) -> list[str] | None: return out -def split_onion_domains(domains: list[str]) -> tuple[list[str], list[str]]: - """Split into (clearnet, onion): onion vhosts need a SOCKS proxy to probe.""" - clearnet = [d for d in domains if not d.endswith(".onion")] - onion = [d for d in domains if d.endswith(".onion")] - return clearnet, onion +def collect_vhosts(servers_dir: str) -> dict[str, Path] | None: + """Map every served vhost domain to its conf across ``http`` and ``https``. + + Args: + servers_dir: the nginx ``servers`` directory holding ``http/`` and + ``https/``. + + Returns: + ``{domain: conf}``; a domain present in both keeps its ``https`` conf, + since its ``http`` one is only the redirect to it. ``None`` when + neither directory exists. + """ + vhosts: dict[str, Path] = {} + found = False + for protocol in ("http", "https"): + directory = Path(servers_dir) / protocol + if not directory.is_dir(): + continue + found = True + for domain in extract_domains_from_filenames(str(directory)) or []: + if protocol == "https" or domain not in vhosts: + vhosts[domain] = directory / f"{domain}.conf" + if not found: + print(f"Directory {servers_dir} holds no http/ or https/.", file=sys.stderr) + return None + return vhosts -def is_skipped_domain(domain: str, skip_set: set[str], skip_labels: set[str]) -> bool: +def split_proxied_domains( + domains: list[str], proxy_suffix: str +) -> tuple[list[str], list[str]]: + """Split into (direct, proxied): vhosts under ``proxy_suffix`` need the + network's proxy to be probed.""" + if not proxy_suffix: + return list(domains), [] + direct = [d for d in domains if not d.endswith(proxy_suffix)] + proxied = [d for d in domains if d.endswith(proxy_suffix)] + return direct, proxied + + +def is_skipped_domain( + domain: str, skip_set: set[str], skip_labels: set[str], proxy_suffix: str +) -> bool: """Whether a domain should be excluded from the CSP probe. A domain is skipped if it is listed explicitly in ``--skip-domain``, or if - it is the ``.onion`` sibling of a skipped clearnet vhost. Clearnet and onion - vhosts of the same app share the leftmost subdomain label (``mirror`` for - both ``mirror.`` and ``mirror..onion``), so a - ``--skip-domain mirror.`` also drops ``mirror..onion`` - — which serves the same 4xx at ``/`` and would otherwise fail the probe. + it is the proxied sibling of a skipped vhost. Siblings of the same app + share the leftmost subdomain label, so ``--skip-domain mirror.`` + also drops ``mirror.``, which serves the same 4xx at ``/``. """ if domain in skip_set: return True - return domain.endswith(".onion") and domain.split(".", 1)[0] in skip_labels + return ( + bool(proxy_suffix) + and domain.endswith(proxy_suffix) + and domain.split(".", 1)[0] in skip_labels + ) -def expand_accept_status(accept_status: list[str], domains: list[str]) -> list[str]: - """ACCEPT_STATUS plus the same codes for every ``.onion`` sibling it covers. +def expand_accept_status( + accept_status: list[str], domains: list[str], proxy_suffix: str +) -> list[str]: + """ACCEPT_STATUS plus the same codes for every proxied sibling it covers. - The checker matches accepted codes by hostname, and a clearnet vhost and - its onion twin share only the leftmost subdomain label, so a code declared - for ``mirror.`` never reaches ``mirror..onion`` — - which serves that same by-design status and would fail the probe. + The checker matches accepted codes by hostname, and a vhost and its + proxied twin share only the leftmost subdomain label, so a code declared + for ``mirror.`` never reaches ``mirror.`` on its own. Args: accept_status: ``=[,]`` entries as declared. - domains: every vhost the probe covers, clearnet and onion alike. + domains: every vhost the probe covers. + proxy_suffix: suffix of the network reached through the proxy. """ - onion = [d for d in domains if d.endswith(".onion")] + _, proxied = split_proxied_domains(domains, proxy_suffix) expanded = list(accept_status) for entry in accept_status: host, _, codes = entry.partition("=") - if not codes or host.endswith(".onion"): + if not codes or (proxy_suffix and host.endswith(proxy_suffix)): continue label = host.split(".", 1)[0] expanded.extend( f"{sibling}={codes}" - for sibling in onion + for sibling in proxied if sibling.split(".", 1)[0] == label ) return expanded @@ -127,15 +166,20 @@ def detect_scheme_from_conf(conf_path: Path) -> str | None: return None -def build_urls_from_nginx_confs(config_path: str, domains: list[str]) -> list[str]: +def build_urls_from_nginx_confs( + vhosts: dict[str, Path], domains: list[str] +) -> list[str]: """ Build full URLs (http:// or https://) for each domain by inspecting its .conf file. + + Args: + vhosts: ``collect_vhosts`` output. + domains: the domains to build URLs for. """ - base = Path(config_path) urls: list[str] = [] for domain in domains: - conf = base / f"{domain}.conf" + conf = vhosts[domain] scheme = detect_scheme_from_conf(conf) if scheme is None: @@ -242,7 +286,12 @@ def main() -> None: parser.add_argument( "--nginx-config-dir", required=True, - help="Directory containing NGINX .conf files", + help="NGINX servers directory holding the http/ and https/ vhost confs", + ) + parser.add_argument( + "--proxy-suffix", + required=True, + help="Domain suffix of the network whose vhosts are probed through --tor-proxy", ) parser.add_argument( "--image", @@ -314,22 +363,28 @@ def main() -> None: args = parser.parse_args() - domains = extract_domains_from_filenames(args.nginx_config_dir) - if domains is None: + vhosts = collect_vhosts(args.nginx_config_dir) + if vhosts is None: sys.exit(1) + domains = sorted(vhosts) if not domains: print("No domains found to check.") sys.exit(0) + proxy_suffix = args.proxy_suffix skip_set = {d for d in (args.skip_domain or []) if d} if skip_set: skip_labels = {d.split(".", 1)[0] for d in skip_set} skipped_present = sorted( - d for d in domains if is_skipped_domain(d, skip_set, skip_labels) + d + for d in domains + if is_skipped_domain(d, skip_set, skip_labels, proxy_suffix) ) domains = [ - d for d in domains if not is_skipped_domain(d, skip_set, skip_labels) + d + for d in domains + if not is_skipped_domain(d, skip_set, skip_labels, proxy_suffix) ] if skipped_present: print( @@ -337,12 +392,14 @@ def main() -> None: f"--skip-domain: {skipped_present}" ) - accept_status = expand_accept_status(list(args.accept_status or []), domains) + accept_status = expand_accept_status( + list(args.accept_status or []), domains, proxy_suffix + ) - clearnet_domains, onion_domains = split_onion_domains(domains) + clearnet_domains, onion_domains = split_proxied_domains(domains, proxy_suffix) if onion_domains and not args.tor_proxy: print( - f"Skipping {len(onion_domains)} .onion domain(s) — no --tor-proxy " + f"Skipping {len(onion_domains)} proxied domain(s), no --tor-proxy " f"given: {sorted(onion_domains)}" ) onion_domains = [] @@ -358,7 +415,7 @@ def main() -> None: ): if not batch_domains: continue - urls = build_urls_from_nginx_confs(args.nginx_config_dir, batch_domains) + urls = build_urls_from_nginx_confs(vhosts, batch_domains) if not urls: print(f"No URLs built to check for: {sorted(batch_domains)}") continue diff --git a/roles/sys-ctl-hlth-csp/tasks/00_core.yml b/roles/sys-ctl-hlth-csp/tasks/00_core.yml index 2d965b1a5c..b592a7239f 100644 --- a/roles/sys-ctl-hlth-csp/tasks/00_core.yml +++ b/roles/sys-ctl-hlth-csp/tasks/00_core.yml @@ -43,12 +43,8 @@ {{ [ system_service_script_exec, - '--nginx-config-dir=' ~ ( - [ - lookup('nginx','directories.configuration.servers'), - lookup('tls', DOMAIN_PRIMARY, 'protocols.web') - ] | path_join - ), + '--nginx-config-dir=' ~ lookup('nginx','directories.configuration.servers'), + '--proxy-suffix=' ~ ('tor' | network_suffix), '--image=' ~ HEALTH_CSP_IMAGE, '--short', (HEALTH_CSP_ALWAYS_PULL | bool) | ternary('--always-pull', ''), diff --git a/roles/sys-ctl-hlth-webserver/files/python/script.py b/roles/sys-ctl-hlth-webserver/files/python/script.py index c3c62c7de7..40d0fc8cb7 100755 --- a/roles/sys-ctl-hlth-webserver/files/python/script.py +++ b/roles/sys-ctl-hlth-webserver/files/python/script.py @@ -1,8 +1,9 @@ #!/usr/bin/env python3 """ -Ultra-thin checker: consume a JSON mapping of {domain: [expected_status_codes]} -and verify HTTP HEAD responses. All mapping logic is done in the filter -`web_health_expectations`. +Ultra-thin checker: consume a JSON mapping of +{domain: {"codes": [...], "scheme": "http"|"https", "timeout": seconds}} and +verify HTTP HEAD responses. All mapping logic is done in the filters +`web_health_expectations` and `web_health_targets`. """ import argparse @@ -16,48 +17,53 @@ import requests def parse_args(argv=None): p = argparse.ArgumentParser( - description="Web health checker (expects precomputed domain→codes mapping)." + description="Web health checker (expects precomputed per-domain targets)." ) p.add_argument( - "--web-protocol", - default="https", - choices=["http", "https"], - help="Protocol to use", - ) - p.add_argument( - "--expectations", required=True, help='JSON STRING: {"domain": [codes], ...}' + "--targets", + required=True, + help='JSON STRING: {"domain": {"codes": [...], "scheme": "https", "timeout": 10}}', ) return p.parse_args(argv) -def _protocol_for(domain: str, default_protocol: str) -> str: - """Onion services are plaintext-only (no TLS): probe them over http - regardless of the clearnet default. Everything else uses the default.""" - return "http" if domain.endswith(".onion") else default_protocol +def _codes(value) -> list[int]: + if not isinstance(value, list): + return [] + try: + return [int(x) for x in value] + except (TypeError, ValueError): + return [] -def _parse_json_mapping(name: str, value: str) -> dict[str, list[int]]: +def _parse_targets(value: str) -> dict[str, dict]: try: obj = json.loads(value) except json.JSONDecodeError as e: - raise SystemExit(f"--{name} must be a valid JSON string: {e}") from e + raise SystemExit(f"--targets must be a valid JSON string: {e}") from e if not isinstance(obj, dict): - raise SystemExit(f"--{name} must be a JSON object (mapping)") + raise SystemExit("--targets must be a JSON object (mapping)") clean = {} - for k, v in obj.items(): - if isinstance(v, list): - try: - clean[k] = [int(x) for x in v] - except Exception: - clean[k] = [] - else: - clean[k] = [] + for domain, target in obj.items(): + if not isinstance(target, dict): + raise SystemExit(f"--targets entry for {domain} must be a mapping") + scheme = target.get("scheme") + if scheme not in ("http", "https"): + raise SystemExit(f"--targets entry for {domain} has scheme {scheme!r}") + timeout = target.get("timeout") + if not isinstance(timeout, int) or timeout <= 0: + raise SystemExit(f"--targets entry for {domain} has timeout {timeout!r}") + clean[domain] = { + "codes": _codes(target.get("codes")), + "scheme": scheme, + "timeout": timeout, + } return clean def main(argv=None) -> int: args = parse_args(argv) - expectations = _parse_json_mapping("expectations", args.expectations) + targets = _parse_targets(args.targets) verify = True ca_trust_cert_host = os.environ.get("CA_TRUST_CERT_HOST", "").strip() if ca_trust_cert_host: @@ -69,14 +75,13 @@ def main(argv=None) -> int: verify = ca_trust_cert_host errors = 0 - for domain in sorted(expectations.keys()): - expected = expectations[domain] or [] - is_onion = domain.endswith(".onion") - url = f"{_protocol_for(domain, args.web_protocol)}://{domain}" - timeout = 30 if is_onion else 10 + for domain in sorted(targets.keys()): + target = targets[domain] + expected = target["codes"] + url = f"{target['scheme']}://{domain}" try: r = requests.head( - url, allow_redirects=False, timeout=timeout, verify=verify + url, allow_redirects=False, timeout=target["timeout"], verify=verify ) if expected and r.status_code in expected: print(f"{domain}: OK") 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 e8cd9b50f7..215ec60d04 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 @@ -2,8 +2,12 @@ import sys from collections.abc import Mapping from pathlib import Path +from ansible.errors import AnsibleError + +from utils.networks.reachability import CLEARNET, network, network_of, 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 # nocheck: project-root-import _BASE_DIR = str(Path(__file__).resolve().parents[3]) @@ -84,33 +88,36 @@ def _normalize_selection(group_names): return sel -def _apply_onion_deploy_view(per_app, applications, primary_domain, node_onion): - """Rewrite each app's expectation domains to what the current deploy serves: - for a ``services.tor.enabled`` app the onion domains replace (``exclusive``) - or accompany (dual) the clearnet ones, reusing ``_inject_onion_domains`` and - letting each onion domain inherit its clearnet source's status codes.""" - node = str(node_onion or "").strip() - primary = str(primary_domain or "").strip() - if not node or not primary: +def _apply_served_view(per_app, served_domains, primary_domain, node_onion): + """Rewrite each app's canonical expectations to the domains the node serves. + + Args: + per_app: expected codes per canonical domain, per application. + served_domains: ``lookup('domains')`` of this host. + primary_domain: the node's ``DOMAIN_PRIMARY``. + node_onion: the node onion address, empty without Tor. + + A served domain inherits the codes of its clearnet sibling; an app the + map does not list keeps its declared domains. + """ + if not isinstance(served_domains, Mapping): return - - from utils.cache.domains import _inject_onion_domains, _onion_of - - clearnet_lists = {app: list(exp.keys()) for app, exp in per_app.items()} - served = _inject_onion_domains(clearnet_lists, applications, primary, node) - + primary = str(primary_domain or "").strip() + node = str(node_onion or "").strip() for app_id, exp in per_app.items(): - onion_codes = {} - for d, codes in exp.items(): - o = _onion_of(str(d), primary, node) - if o: - onion_codes[o] = codes - served_list = served.get(app_id, list(exp.keys())) - per_app[app_id] = { - s: (exp[s] if s in exp else onion_codes[s]) - for s in served_list - if s in exp or s in onion_codes - } + served = _to_list(served_domains.get(app_id), allow_mapping=True) + if not served: + continue + view = {} + for domain in served: + source = ( + domain + if domain in exp + else sibling_domain(domain, CLEARNET, primary, node) + ) + if source in exp: + view[domain] = exp[source] + per_app[app_id] = view def web_health_expectations( @@ -120,6 +127,7 @@ def web_health_expectations( redirect_maps=None, primary_domain=None, node_onion=None, + served_domains=None, ): """Produce a **flat mapping**: domain -> [expected_status_codes]. @@ -134,10 +142,9 @@ def web_health_expectations( - No legacy fallbacks (ignore 'home'/'landingpage'). - `redirect_maps`: force -> [301] and override app-derived entries. - If `www_enabled`: add and/or force www.* -> [301] for all domains. - - Deploy-aware onion view: when `primary_domain` and `node_onion` are set - (svc-net-tor deployed), each `services.tor.enabled` app's clearnet - domains are swapped (exclusive) or extended (dual) with their onion - domains, so the probe checks exactly what the current deploy serves. + - 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`. """ if not isinstance(applications, Mapping): return {} @@ -145,6 +152,7 @@ def web_health_expectations( selection = _normalize_selection(group_names) per_app = {} + per_alias = {} for app_id in applications: if app_id not in selection: @@ -192,33 +200,30 @@ def web_health_expectations( codes = sc_map.get("default") app_exp[d] = list(codes) if codes else list(DEFAULT_OK) - for d in aliases: - if d: - app_exp[d] = [301] - per_app[app_id] = app_exp + per_alias[app_id] = {d: [301] for d in aliases if d} primary = str(primary_domain or "").strip() if primary and "web-opt-rdr-domains" not in selection: for app_exp in per_app.values(): app_exp.pop(primary, None) - _apply_onion_deploy_view(per_app, applications, primary_domain, node_onion) + _apply_served_view(per_app, served_domains, primary_domain, node_onion) expectations = {} - for app_exp in per_app.values(): + for app_id, app_exp in per_app.items(): expectations.update(app_exp) + expectations.update(per_alias[app_id]) for src in _extract_redirect_sources(redirect_maps): expectations[src] = [301] if www_enabled: - node = str(node_onion or "").strip() add = {} for d in expectations: if d.startswith("www."): continue - if node and d.endswith(node): + if network_of(d) != CLEARNET: continue add[f"www.{d}"] = [301] expectations.update(add) @@ -229,8 +234,45 @@ def web_health_expectations( return {k: expectations[k] for k in sorted(expectations.keys())} +def web_health_targets(expectations, applications, served_domains, tls_enabled): + """Attach the probe scheme and timeout to every expected domain. + + Args: + expectations: output of ``web_health_expectations``. + applications: merged applications tree. + served_domains: ``lookup('domains')`` of this host. + tls_enabled: ``TLS_ENABLED``. + + Returns: + ``{domain: {"codes": [...], "scheme": "http"|"https", "timeout": s}}``; + the scheme follows the same per-domain resolution as ``lookup('tls')`` + and the timeout comes from the domain's network. + """ + targets = {} + for domain, codes in (expectations or {}).items(): + try: + app_id, resolved = resolve_term( + domain, + domains=served_domains or {}, + applications=applications or {}, + forced_mode="domain", + err_prefix="web_health_targets", + ) + app = (applications or {}).get(app_id) or {} + except AnsibleError: + resolved, app = domain, {} + enabled = resolve_enabled(app, bool(tls_enabled), primary_domain=resolved) + targets[domain] = { + "codes": list(codes), + "scheme": "https" if enabled else "http", + "timeout": network(network_of(domain)).probe_timeout, + } + return targets + + class FilterModule: def filters(self): return { "web_health_expectations": web_health_expectations, + "web_health_targets": web_health_targets, } diff --git a/roles/sys-ctl-hlth-webserver/tasks/00_core.yml b/roles/sys-ctl-hlth-webserver/tasks/00_core.yml index 5da77cf140..a718925303 100644 --- a/roles/sys-ctl-hlth-webserver/tasks/00_core.yml +++ b/roles/sys-ctl-hlth-webserver/tasks/00_core.yml @@ -32,10 +32,9 @@ system_service_tpl_environment: "{{ CA_TRUST_SYSTEMD_ENV_SELFSIGNED }}" system_service_tpl_exec_start: > {{ system_service_script_exec }} - --web-protocol {{ lookup('tls', DOMAIN_PRIMARY, 'protocols.web') }} - --expectations '{{ lookup('applications') | web_health_expectations(www_enabled=WWW_REDIRECT_ENABLED | bool, group_names=lookup('deployment').deployed, primary_domain=DOMAIN_PRIMARY, - node_onion=lookup('config', 'svc-net-tor', 'services.tor.node', '')) | to_json - }}' + --targets '{{ lookup('applications') | web_health_expectations(www_enabled=WWW_REDIRECT_ENABLED | bool, group_names=lookup('deployment').deployed, primary_domain=DOMAIN_PRIMARY, + node_onion=lookup('config', 'svc-net-tor', 'services.tor.node', ''), served_domains=lookup('domains')) + | web_health_targets(lookup('applications'), lookup('domains'), TLS_ENABLED) | to_json }}' system_service_force_flush_final: true - include_tasks: utils/once/flag.yml diff --git a/roles/sys-front-inj-all/tasks/main.yml b/roles/sys-front-inj-all/tasks/main.yml index a23b9673ac..1399b1ce00 100644 --- a/roles/sys-front-inj-all/tasks/main.yml +++ b/roles/sys-front-inj-all/tasks/main.yml @@ -1,5 +1,5 @@ --- -# nocheck: run-once — per-application role: every invocation must (re)apply CDN dirs, inj-*, body_filter.lua for the current `application_id`. +# nocheck: run-once runs once per vhost: every invocation re-applies the CDN dirs, inj-* and the body_filter Lua for the current `domain`. - name: 📂 Include dependency 'sys-svc-webserver-core' include_role: name: sys-svc-webserver-core @@ -43,9 +43,9 @@ name: sys-front-inj-javascript when: inj_enabled.javascript -- name: "📄 Render body_filter Lua for '{{ application_id }}'" +- name: "📄 Render body_filter Lua for '{{ domain }}'" stack_host_template: src: body_filter.lua.j2 - dest: "{{ lookup('nginx', 'directories.configuration.lua') }}{{ application_id }}.lua" + dest: "{{ lookup('nginx', 'directories.configuration.lua') }}{{ domain }}.lua" mode: "0644" notify: reload-openresty diff --git a/roles/sys-front-inj-all/templates/body_filter.lua.j2 b/roles/sys-front-inj-all/templates/body_filter.lua.j2 index 479872e5bb..3e8523865e 100644 --- a/roles/sys-front-inj-all/templates/body_filter.lua.j2 +++ b/roles/sys-front-inj-all/templates/body_filter.lua.j2 @@ -1,4 +1,3 @@ -{# Jinja macro: expands feature snippets into Lua array pushes at render time #} {% macro push_snippets(list_name, features) -%} {% set kind = list_name | regex_replace('_snippets$','') %} {% for f in features if inj_enabled.get(f) -%} @@ -12,7 +11,6 @@ if not (ngx.ctx.is_html or ngx.ctx.is_css) then return end --- Buffer all chunks until EOF ngx.ctx.buf = ngx.ctx.buf or {} local chunk, eof = ngx.arg[1], ngx.arg[2] @@ -21,70 +19,41 @@ if chunk ~= "" then end if not eof then - -- Swallow intermediate chunks; emit once at EOF ngx.arg[1] = nil return end --- Concatenate the full HTML local whole = table.concat(ngx.ctx.buf) ngx.ctx.buf = nil -{% set _mirror_tor_enabled = lookup('config', application_id, 'services.tor.enabled', False) | bool %} -{% if _mirror_tor_enabled %} +{% if (lookup('config', application_id, 'services.tor.enabled', False) | bool) and (domain | network_of) == 'tor' %} {% set _mirror_origins = lookup('applications') | external_asset_origins(application_id, DOMAIN_PRIMARY) %} -{% set _mirror_tor_node = lookup('config', 'svc-net-tor', 'services.tor.node', '') %} -{% set _mirror_onion = lookup('tls', 'web-svc-mirror', 'url.base') | regex_replace('/+$', '') | to_onion_url(_mirror_tor_node, DOMAIN_PRIMARY) %} -{% if _mirror_origins %} --- Onion sessions: rewrite external asset origins to the local mirror (privacy proxy) -do - local host = ngx.var.http_host or "" - if host:sub(-6) == ".onion" then +{% set _mirror_base = lookup('tls', 'web-svc-mirror', 'url.base') | regex_replace('/+$', '') %} {% for origin in _mirror_origins %} - do - local pat = ([=[https://{{ origin }}]=]):gsub("([^%w])", "%%%1") - whole = (whole:gsub(pat, [=[{{ _mirror_onion }}/{{ origin }}]=])) - end -{% endfor %} - end +do + local pat = ([=[https://{{ origin }}]=]):gsub("([^%w])", "%%%1") + whole = (whole:gsub(pat, [=[{{ _mirror_base }}/{{ origin }}]=])) end -{% endif %} +{% endfor %} {% endif %} if ngx.ctx.is_css then ngx.arg[1] = whole return end -{% set _cdn_base = lookup('tls', 'web-svc-cdn', 'url.base') | regex_replace('/+$', '') %} -{% set _tor_node = lookup('config', 'svc-net-tor', 'services.tor.node', '') %} -{% set _cdn_onion = _cdn_base | to_onion_url(_tor_node, DOMAIN_PRIMARY) %} -local function onionize(s) -{% if _tor_node and _cdn_onion != _cdn_base %} - local host = ngx.var.http_host or "" - if host:sub(-6) == ".onion" then - local pat = ([=[{{ _cdn_base }}]=]):gsub("([^%w])", "%%%1") - s = (s:gsub(pat, [=[{{ _cdn_onion }}]=])) - end -{% endif %} - return s -end --- Remove inline CSP (case-insensitive) local meta_re = [[]+http-equiv=["']Content-Security-Policy["'][^>]*>\s*]] whole = ngx.re.gsub(whole, meta_re, "", "ijo") --- Build head snippets (rendered by Jinja at template time) local head_snippets = {} {{ push_snippets('head_snippets', inj_head_features) }} -local head_payload = onionize(table.concat(head_snippets, "\n")) .. "" +local head_payload = table.concat(head_snippets, "\n") .. "" --- Inject before (first occurrence) local function repl_head(_) return head_payload end local new, n, err = ngx.re.sub(whole, [[]], repl_head, "ijo") if new then whole = new else ngx.log(ngx.WARN, "No found; trying fallback: ", err or "nil") - -- Fallback: inject right AFTER the opening tag local body_open_re = [[]*>]] new, n, err = ngx.re.sub(whole, body_open_re, "$0\n" .. table.concat(head_snippets, "\n"), "ijo") if new then @@ -94,12 +63,10 @@ else end end --- Build body snippets (rendered by Jinja at template time) local body_snippets = {} {{ push_snippets('body_snippets', inj_body_features) }} -local body_payload = onionize(table.concat(body_snippets, "\n")) .. "" +local body_payload = table.concat(body_snippets, "\n") .. "" --- Inject before (first occurrence), or append if missing local function repl_body(_) return body_payload end new, n, err = ngx.re.sub(whole, [[]], repl_body, "ijo") if new then @@ -109,5 +76,4 @@ else whole = whole .. table.concat(body_snippets, "\n") end --- Emit the modified HTML ngx.arg[1] = whole or "" diff --git a/roles/sys-front-inj-all/templates/location.lua.j2 b/roles/sys-front-inj-all/templates/location.lua.j2 index b1dd587f3e..939dc0df33 100644 --- a/roles/sys-front-inj-all/templates/location.lua.j2 +++ b/roles/sys-front-inj-all/templates/location.lua.j2 @@ -1,3 +1,3 @@ lua_need_request_body on; -body_filter_by_lua_file {{ lookup('nginx', 'directories.configuration.lua') }}{{ application_id }}.lua; +body_filter_by_lua_file {{ lookup('nginx', 'directories.configuration.lua') }}{{ domain }}.lua; diff --git a/roles/sys-front-inj-dashboard/templates/iframe-handler.js.j2 b/roles/sys-front-inj-dashboard/templates/iframe-handler.js.j2 index 6920636a3f..39df8f0308 100644 --- a/roles/sys-front-inj-dashboard/templates/iframe-handler.js.j2 +++ b/roles/sys-front-inj-dashboard/templates/iframe-handler.js.j2 @@ -1,7 +1,7 @@ (function (global) { /** * Initializes the iframe sync & external link forcing logic. - * @param {string} primary_domain + * @param {string} primary_domain - DOMAIN_PRIMARY in the network of the vhost * @param {string} current_domain * @param {string} allowedOrigin - Parent origin for postMessage */ @@ -18,9 +18,7 @@ } function isInternalHost(hostname) { - if (hostname.endsWith(primary_domain) || hostname.endsWith(current_domain)) return true; - var onion = current_domain.match(/[a-z2-7]{56}\.onion$/); - return !!(onion && hostname.endsWith(onion[0])); + return hostname.endsWith(primary_domain) || hostname.endsWith(current_domain); } function forceExternalLinks() { diff --git a/roles/sys-front-inj-dashboard/templates/iframe/init_one_liner.js.j2 b/roles/sys-front-inj-dashboard/templates/iframe/init_one_liner.js.j2 index 5f775242bb..f3855e5107 100644 --- a/roles/sys-front-inj-dashboard/templates/iframe/init_one_liner.js.j2 +++ b/roles/sys-front-inj-dashboard/templates/iframe/init_one_liner.js.j2 @@ -1,10 +1,8 @@ +{% set _network_base = DOMAIN_PRIMARY | network_sibling(domain | network_of, DOMAIN_PRIMARY, lookup('config', 'svc-net-tor', 'services.tor.node', '')) %} document.addEventListener('DOMContentLoaded', function () { initIframeHandler( - '{{ DOMAIN_PRIMARY }}', + '{{ _network_base or DOMAIN_PRIMARY }}', '{{ domain }}', '{{ lookup("tls", "web-app-dashboard", "url.base") }}' ); }); -{% if MODE_DEBUG | bool %} -try { console.log("[iframe-sync] Sender for iframe messages is active."); } catch(e) {} -{% endif %} diff --git a/roles/sys-front-inj-matomo/vars/main.yml b/roles/sys-front-inj-matomo/vars/main.yml index ee9aad88f3..cf8ba18ba9 100644 --- a/roles/sys-front-inj-matomo/vars/main.yml +++ b/roles/sys-front-inj-matomo/vars/main.yml @@ -1,5 +1,5 @@ --- matomo_tracking_scope: "{{ lookup('config', 'web-app-matomo', 'services.matomo.tracking.scope') }}" matomo_site_domain: "{{ domain if matomo_tracking_scope == 'sub' else (domain | regex_replace('^(?:.*\\.)?(.+\\..+)$', '\\1')) }}" -matomo_site_url: "{{ lookup('tls', application_id, 'protocols.web') }}://{{ matomo_site_domain }}" -matomo_index_php_url: "{{ lookup('tls', 'web-app-matomo', 'url.base') }}index.php" +matomo_site_url: "{{ lookup('tls', domain, 'protocols.web') }}://{{ matomo_site_domain }}" +matomo_index_php_url: "{{ lookup('tls', lookup('domain', 'web-app-matomo'), 'url.base') }}index.php" diff --git a/roles/sys-front-tls/tasks/01_http.yml b/roles/sys-front-tls/tasks/01_http.yml index 83cb364628..e006088a5f 100644 --- a/roles/sys-front-tls/tasks/01_http.yml +++ b/roles/sys-front-tls/tasks/01_http.yml @@ -4,7 +4,7 @@ name: sys-ctl-mtn-cert-renew when: - run_once_sys_ctl_mtn_cert_renew is not defined - - lookup('tls', domain | default(application_id), 'mode') == 'letsencrypt' + - lookup('tls', domain, 'mode') == 'letsencrypt' - name: 📁 Create HTTP->HTTPS handler per domain stack_host_template: diff --git a/roles/sys-front-tls/tasks/main.yml b/roles/sys-front-tls/tasks/main.yml index 07738330bc..bc741aecd3 100644 --- a/roles/sys-front-tls/tasks/main.yml +++ b/roles/sys-front-tls/tasks/main.yml @@ -16,4 +16,4 @@ - name: "📂 Load http redirect routines" include_tasks: 01_http.yml - when: lookup('tls', domain | default(application_id), 'enabled') | bool + when: lookup('tls', domain, 'enabled') | bool diff --git a/roles/sys-front-tls/templates/nginx_ssl_header.j2 b/roles/sys-front-tls/templates/nginx_ssl_header.j2 index e22f82afc3..8cb738e17f 100644 --- a/roles/sys-front-tls/templates/nginx_ssl_header.j2 +++ b/roles/sys-front-tls/templates/nginx_ssl_header.j2 @@ -1,6 +1,6 @@ -{% if lookup('tls', domain | default(application_id), 'enabled') | bool %} -listen {{ lookup('tls', domain | default(application_id), 'ports.web') }} ssl; -listen [::]:{{ lookup('tls', domain | default(application_id), 'ports.web') }} ssl; +{% if lookup('tls', domain, 'enabled') | bool %} +listen {{ lookup('tls', domain, 'ports.web') }} ssl; +listen [::]:{{ lookup('tls', domain, 'ports.web') }} ssl; http2 on; ssl_protocols TLSv1.2 TLSv1.3; @@ -19,6 +19,6 @@ ssl_stapling_verify on; {% include 'roles/sys-front-tls/templates/ssl_credentials.j2' %} {% else %} -listen {{ lookup('tls', domain | default(application_id), 'ports.web') }}; -listen [::]:{{ lookup('tls', domain | default(application_id), 'ports.web') }}; +listen {{ lookup('tls', domain, 'ports.web') }}; +listen [::]:{{ lookup('tls', domain, 'ports.web') }}; {% endif %} diff --git a/roles/sys-front-tls/vars/main.yml b/roles/sys-front-tls/vars/main.yml index a9882e7ce3..4be94edd15 100644 --- a/roles/sys-front-tls/vars/main.yml +++ b/roles/sys-front-tls/vars/main.yml @@ -1,6 +1,2 @@ --- -# Exception: domain, not application_id — sys-stk-front-proxy re-includes this -# role once per vhost (e.g. a clearnet + onion pair for the same app); -# app-id-keyed TLS state would apply one domain's enabled/mode to every pass. -# Falls back to application_id for callers that never set domain. -tls_mode_effective: "{{ lookup('tls', domain | default(application_id), 'mode') }}" +tls_mode_effective: "{{ lookup('tls', domain, 'mode') }}" diff --git a/roles/sys-stk-front-proxy/tasks/main.yml b/roles/sys-stk-front-proxy/tasks/main.yml index 2ee080d001..2741d319a1 100644 --- a/roles/sys-stk-front-proxy/tasks/main.yml +++ b/roles/sys-stk-front-proxy/tasks/main.yml @@ -4,7 +4,7 @@ - name: 🧊 Freeze front proxy context before nested role loads ansible.builtin.set_fact: front_proxy_application_id: "{{ application_id }}" - front_proxy_domain: "{{ domain | default(lookup('domain', application_id)) }}" + front_proxy_vhost_domains: "{{ lookup('network_siblings', domain | default(lookup('domain', application_id))) }}" front_proxy_service_key: >- {{ webserver_proxy_service_key @@ -35,20 +35,6 @@ ) ) }} - front_proxy_domain_conf_dst_resolved: >- - {{ - lookup( - 'nginx', - 'files.domain', - (domain | default(lookup('domain', application_id))) - ) - }} - changed_when: false - -- name: 🧊 Freeze the probe target for this vhost - ansible.builtin.set_fact: - front_proxy_probe_url: "{{ lookup('tls', front_proxy_domain, 'url.base') }}" - front_proxy_status_codes: "{{ lookup('applications') | accepted_status_codes(front_proxy_application_id, lookup('tls', front_proxy_domain, 'domain')) }}" changed_when: false - name: 📂 Include dependencies @@ -60,95 +46,8 @@ ansible.builtin.include_role: name: sys-stk-front-base -- name: "📌 TLS | Apply tls layer" - include_role: - name: sys-front-tls - when: lookup('tls', front_proxy_application_id, 'enabled') | bool - vars: - application_id: "{{ front_proxy_application_id }}" - domain: "{{ front_proxy_domain }}" - -- name: "📌 CSP/INJ | Apply global injections for {{ front_proxy_domain }}" - ansible.builtin.include_role: - name: sys-front-inj-all - vars: - application_id: "{{ front_proxy_application_id }}" - domain: "{{ front_proxy_domain }}" - -- name: 🔍 Resolve application-specific front proxy template path - ansible.builtin.set_fact: - front_proxy_application_template: "{{ front_proxy_application_id | abs_role_path_by_application_id }}/templates/proxy.conf.j2" - -- name: 🔍 Resolve front proxy template source - ansible.builtin.set_fact: - front_proxy_template_src: >- - {{ - front_proxy_application_template - if ( - lookup('fileglob', front_proxy_application_template, wantlist=True) | length - ) > 0 - else "roles/sys-svc-proxy/templates/vhost/%s.conf.j2" | format(webserver_vhost_flavour) - }} - vars: - webserver_vhost_flavour: basic - -- name: "🚀 Deploy NGINX config for '{{ front_proxy_domain }}'" - stack_host_template: - src: "{{ front_proxy_template_src }}" - dest: "{{ front_proxy_domain_conf_dst_resolved }}" - vars: - application_id: "{{ front_proxy_application_id }}" - domain: "{{ front_proxy_domain }}" - http_port: "{{ front_proxy_http_port }}" - proxy_service_key: "{{ front_proxy_service_key }}" - proxy_internal_port: "{{ front_proxy_internal_port }}" - webserver_extra_configuration: "" - webserver_websocket_location: "" - webserver_client_max_body_size: "{{ lookup('config', front_proxy_application_id, 'server.client_max_body_size', '100m') }}" - register: nginx_conf - notify: reload-openresty - -- block: - - name: "🔍 Check if '{{ front_proxy_domain }}' is reachable" - uri_probe: - url: "{{ front_proxy_probe_url }}" - status_code: "{{ front_proxy_status_codes }}" - register: site_check - failed_when: false - changed_when: false - - - name: "🔄 Redeploy: site answered {{ site_check.status | default('none') }}" - ansible.builtin.command: - cmd: "true" - notify: restart-openresty - when: - - site_check.status | default(-1) not in front_proxy_status_codes - - site_check.status | default(-1) in front_proxy_stale_config_status_codes - when: not nginx_conf.changed - -- name: "🔄 Restart Webserver for '{{ front_proxy_domain_conf_dst_resolved }}'" - ansible.builtin.meta: flush_handlers - -- name: "🔍 Verify '{{ front_proxy_domain }}' is served after the reload" - uri_probe: - url: "{{ front_proxy_probe_url }}" - status_code: "{{ front_proxy_status_codes }}" - register: front_proxy_reload_check - failed_when: false - changed_when: false - when: nginx_conf.changed - -- name: "🔄 Redeploy: reload left {{ front_proxy_reload_check.status | default('none') }}" - ansible.builtin.command: - cmd: "true" - notify: restart-openresty - when: - - nginx_conf.changed - - front_proxy_reload_check.status | default(-1) not in front_proxy_status_codes - - >- - not openresty_reload.changed - or front_proxy_reload_check.status | default(-1) in front_proxy_stale_config_status_codes - -- name: "🔄 Flush the fallback redeploy for '{{ front_proxy_domain }}'" - ansible.builtin.meta: flush_handlers - when: nginx_conf.changed +- name: "🌐 Serve every network sibling of the vhost" + ansible.builtin.include_tasks: vhost.yml + loop: "{{ front_proxy_vhost_domains }}" + loop_control: + loop_var: front_proxy_domain diff --git a/roles/sys-stk-front-proxy/tasks/vhost.yml b/roles/sys-stk-front-proxy/tasks/vhost.yml new file mode 100644 index 0000000000..516c64320e --- /dev/null +++ b/roles/sys-stk-front-proxy/tasks/vhost.yml @@ -0,0 +1,100 @@ +--- +- name: "🧊 Freeze the probe target for '{{ front_proxy_domain }}'" + ansible.builtin.set_fact: + front_proxy_domain_conf_dst_resolved: "{{ lookup('nginx', 'files.domain', front_proxy_domain) }}" + front_proxy_probe_url: "{{ lookup('tls', front_proxy_domain, 'url.base') }}" + front_proxy_status_codes: "{{ lookup('applications') | accepted_status_codes(front_proxy_application_id, lookup('tls', front_proxy_domain, 'domain')) }}" + changed_when: false + +- name: "📌 TLS | Apply tls layer for '{{ front_proxy_domain }}'" + include_role: + name: sys-front-tls + when: lookup('tls', front_proxy_domain, 'enabled') | bool + vars: + application_id: "{{ front_proxy_application_id }}" + domain: "{{ front_proxy_domain }}" + +- name: "📌 CSP/INJ | Apply global injections for {{ front_proxy_domain }}" + ansible.builtin.include_role: + name: sys-front-inj-all + vars: + application_id: "{{ front_proxy_application_id }}" + domain: "{{ front_proxy_domain }}" + +- name: 🔍 Resolve application-specific front proxy template path + ansible.builtin.set_fact: + front_proxy_application_template: "{{ front_proxy_application_id | abs_role_path_by_application_id }}/templates/proxy.conf.j2" + +- name: 🔍 Resolve front proxy template source + ansible.builtin.set_fact: + front_proxy_template_src: >- + {{ + front_proxy_application_template + if ( + lookup('fileglob', front_proxy_application_template, wantlist=True) | length + ) > 0 + else "roles/sys-svc-proxy/templates/vhost/%s.conf.j2" | format(webserver_vhost_flavour) + }} + vars: + webserver_vhost_flavour: basic + +- name: "🚀 Deploy NGINX config for '{{ front_proxy_domain }}'" + stack_host_template: + src: "{{ front_proxy_template_src }}" + dest: "{{ front_proxy_domain_conf_dst_resolved }}" + vars: + application_id: "{{ front_proxy_application_id }}" + domain: "{{ front_proxy_domain }}" + http_port: "{{ front_proxy_http_port }}" + proxy_service_key: "{{ front_proxy_service_key }}" + proxy_internal_port: "{{ front_proxy_internal_port }}" + webserver_extra_configuration: "" + webserver_websocket_location: "" + webserver_client_max_body_size: "{{ lookup('config', front_proxy_application_id, 'server.client_max_body_size', '100m') }}" + register: nginx_conf + notify: reload-openresty + +- block: + - name: "🔍 Check if '{{ front_proxy_domain }}' is reachable" + uri_probe: + url: "{{ front_proxy_probe_url }}" + status_code: "{{ front_proxy_status_codes }}" + register: site_check + failed_when: false + changed_when: false + + - name: "🔄 Redeploy: site answered {{ site_check.status | default('none') }}" + ansible.builtin.command: + cmd: "true" + notify: restart-openresty + when: + - site_check.status | default(-1) not in front_proxy_status_codes + - site_check.status | default(-1) in front_proxy_stale_config_status_codes + when: not nginx_conf.changed + +- name: "🔄 Restart Webserver for '{{ front_proxy_domain_conf_dst_resolved }}'" + ansible.builtin.meta: flush_handlers + +- name: "🔍 Verify '{{ front_proxy_domain }}' is served after the reload" + uri_probe: + url: "{{ front_proxy_probe_url }}" + status_code: "{{ front_proxy_status_codes }}" + register: front_proxy_reload_check + failed_when: false + changed_when: false + when: nginx_conf.changed + +- name: "🔄 Redeploy: reload left {{ front_proxy_reload_check.status | default('none') }}" + ansible.builtin.command: + cmd: "true" + notify: restart-openresty + when: + - nginx_conf.changed + - front_proxy_reload_check.status | default(-1) not in front_proxy_status_codes + - >- + not openresty_reload.changed + or front_proxy_reload_check.status | default(-1) in front_proxy_stale_config_status_codes + +- name: "🔄 Flush the fallback redeploy for '{{ front_proxy_domain }}'" + ansible.builtin.meta: flush_handlers + when: nginx_conf.changed 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 80d3b05a73..72036226a6 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 @@ -1,9 +1,8 @@ -# ===== Content Security Policy: only for documents and workers (no locations needed) ===== +{% set _network = domain | network_of %} +{% set _onion = namespace(host='') %} +{% for _sibling in lookup('network_siblings', domain) if (_sibling | network_of) == 'tor' %}{% set _onion.host = _sibling %}{% endfor %} +set $csp "{{ lookup('applications') | build_csp_header(application_id, lookup('domains'), ('https' if TLS_ENABLED | bool else 'http'), (webserver_csp_whitelist_extra_by_app | default({})).get(application_id, {}), (webserver_csp_hashes_extra_by_app | default({})).get(application_id, {}), DOMAIN_PRIMARY, domain) | replace('\"','\\\"') }}"; -# 1) Define your CSP once (Jinja: escape double quotes to be safe) -set $csp "{{ lookup('applications') | build_csp_header(application_id, lookup('domains'), lookup('tls', application_id, 'protocols.web'), (webserver_csp_whitelist_extra_by_app | default({})).get(application_id, {}), (webserver_csp_hashes_extra_by_app | default({})).get(application_id, {}), DOMAIN_PRIMARY) | replace('\"','\\\"') }}"; - -# 2) Send CSP ONLY for document responses; also for workers via Sec-Fetch-Dest header_filter_by_lua_block { local ct = ngx.header.content_type or ngx.header["Content-Type"] or "" local dest = ngx.var.http_sec_fetch_dest or "" @@ -19,14 +18,16 @@ header_filter_by_lua_block { ngx.header["Content-Security-Policy-Report-Only"] = nil end - -- If you'll modify the body later, drop Content-Length on HTML if is_html then ngx.ctx.is_html = true ngx.header.content_length = nil +{% if _network == 'clearnet' and _onion.host %} + ngx.header["Onion-Location"] = "{{ lookup('tls', _onion.host, 'url.base') | regex_replace('/+$', '') }}" .. ngx.var.request_uri +{% endif %} else ngx.ctx.is_html = false -{% if (lookup('config', application_id, 'services.tor.enabled', False) | bool) and (lookup('applications') | external_asset_origins(application_id, DOMAIN_PRIMARY)) %} - if lct:find("^text/css") and (ngx.var.http_host or ""):sub(-6) == ".onion" then +{% if _network == 'tor' and (lookup('config', application_id, 'services.tor.enabled', False) | bool) and (lookup('applications') | external_asset_origins(application_id, DOMAIN_PRIMARY)) %} + if lct:find("^text/css") then ngx.ctx.is_css = true ngx.header.content_length = nil end diff --git a/roles/sys-svc-proxy/templates/location/html.conf.j2 b/roles/sys-svc-proxy/templates/location/html.conf.j2 index b910730594..330136afc1 100644 --- a/roles/sys-svc-proxy/templates/location/html.conf.j2 +++ b/roles/sys-svc-proxy/templates/location/html.conf.j2 @@ -23,9 +23,10 @@ location {{location}} proxy_set_header Authorization $http_authorization; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Proto {{ proxy_x_forwarded_proto | default('$scheme') }}; - proxy_set_header X-Forwarded-Port {{ lookup('tls', application_id, 'ports.web') }}; - proxy_set_header X-Forwarded-Ssl {{ lookup('tls', application_id, 'enabled') | on_off }}; + proxy_set_header X-Forwarded-Port {{ lookup('tls', domain, 'ports.web') }}; + proxy_set_header X-Forwarded-Ssl {{ lookup('tls', domain, 'enabled') | on_off }}; proxy_pass_request_headers on; {% include 'roles/sys-svc-proxy/templates/headers/upstream_strips.conf.j2' %} diff --git a/roles/web-app-dashboard/templates/javascript/oidc.js.j2 b/roles/web-app-dashboard/templates/javascript/oidc.js.j2 index 52b28a94a4..a7b44ee780 100644 --- a/roles/web-app-dashboard/templates/javascript/oidc.js.j2 +++ b/roles/web-app-dashboard/templates/javascript/oidc.js.j2 @@ -15,11 +15,8 @@ const KC_CONFIG = { silentCheckSsoRedirectUri: "{{ (DASHBOARD_APP_BASE_URL | regex_replace('/+$', '')) ~ DASHBOARD_LOCATION_SILENT_CHECK }}" }; -{% set _oidc_tor_enabled = lookup('config', application_id, 'services.tor.enabled', False) | bool %} -{% if _oidc_tor_enabled %} -{% set _oidc_tor_node = lookup('config', 'svc-net-tor', 'services.tor.node', '') %} -{% set _oidc_mirror_onion = lookup('tls', 'web-svc-mirror', 'url.base') | regex_replace('/+$', '') | to_onion_url(_oidc_tor_node, DOMAIN_PRIMARY) %} -const KC_MIRROR_BASE = "{{ _oidc_mirror_onion }}"; +{% if (lookup('config', application_id, 'services.tor.enabled', False) | bool) and (domain | network_of) == 'tor' %} +const KC_MIRROR_BASE = "{{ lookup('tls', 'web-svc-mirror', 'url.base') | regex_replace('/+$', '') }}"; {% else %} const KC_MIRROR_BASE = null; {% endif %} @@ -144,7 +141,7 @@ async function initAuthUI() { // Default UI state until we know better syncAuthMenuVisibility(false); - const kcJsUrl = (KC_MIRROR_BASE && window.location.hostname.endsWith(".onion") && KC_JS_ASSET_URL.startsWith("https://")) + const kcJsUrl = (KC_MIRROR_BASE && KC_JS_ASSET_URL.startsWith("https://")) ? KC_MIRROR_BASE + "/" + KC_JS_ASSET_URL.replace(/^https:\/\//, "") : KC_JS_ASSET_URL; let Keycloak; diff --git a/roles/web-app-espocrm/vars/main.yml b/roles/web-app-espocrm/vars/main.yml index d92600ffd1..6f2d7bfa67 100644 --- a/roles/web-app-espocrm/vars/main.yml +++ b/roles/web-app-espocrm/vars/main.yml @@ -28,7 +28,7 @@ ESPOCRM_LOG_DIR_RELATIVE: "data/logs" ESPOCRM_LOG_PATH_RELATIVE: "{{ [ ESPOCRM_LOG_DIR_RELATIVE, 'espo.log' ] | path_join }}" ESPOCRM_URL: "{{ lookup('tls', application_id, 'url.base') }}" ESPOCRM_OIDC_ENABLED: "{{ lookup('config', application_id, 'services.sso.enabled') }}" -ESPOCRM_OIDC_ONION_ISSUER: "{{ lookup('tls', 'web-app-keycloak', 'domain').endswith('.onion') }}" +ESPOCRM_OIDC_ONION_ISSUER: "{{ (lookup('tls', 'web-app-keycloak', 'domain') | network_of) == 'tor' }}" ESPOCRM_OIDC_SOCKS_PROXY: "{{ lookup('tor_socks_proxy') if ESPOCRM_OIDC_ONION_ISSUER | bool else '' }}" ESPOCRM_LDAP_ENABLED: "{{ lookup('config', application_id, 'services.ldap.enabled') }}" ESPOCRM_LDAP_AUTOCREATE: "{{ lookup('config', application_id, 'services.ldap.autocreate') }}" diff --git a/roles/web-app-joomla/templates/env.j2 b/roles/web-app-joomla/templates/env.j2 index a9d314c67f..0fdedc5d0f 100644 --- a/roles/web-app-joomla/templates/env.j2 +++ b/roles/web-app-joomla/templates/env.j2 @@ -21,7 +21,7 @@ JOOMLA_OIDC_ISSUER_URL={{ JOOMLA_OIDC.issuer_url }} JOOMLA_OIDC_CLIENT_ID={{ JOOMLA_OIDC.client_id }} JOOMLA_OIDC_CLIENT_SECRET={{ JOOMLA_OIDC.client_secret | dotenv_quote }} JOOMLA_OIDC_REDIRECT_URI={{ JOOMLA_OIDC.redirect_uri }} -{% if JOOMLA_OIDC.issuer_url is search('\.onion(/|:|$)') %} +{% if (JOOMLA_OIDC.issuer_url | urlsplit('hostname') | network_of) == 'tor' %} JOOMLA_OIDC_SOCKS_PROXY={{ lookup('tor_socks_proxy') }} {% endif %} JOOMLA_OIDC_END_SESSION_URL={{ JOOMLA_OIDC.end_session_url }} diff --git a/roles/web-app-keycloak/templates/sso_proxy/container.yml.j2 b/roles/web-app-keycloak/templates/sso_proxy/container.yml.j2 index 806fb3cd63..7fa75cbb4c 100644 --- a/roles/web-app-keycloak/templates/sso_proxy/container.yml.j2 +++ b/roles/web-app-keycloak/templates/sso_proxy/container.yml.j2 @@ -23,7 +23,7 @@ - node.role == manager {% endif %} {{ lookup('container_extra_hosts', extra_hosts=( - [] if lookup('domain', 'web-app-keycloak').endswith('.onion') + [] if (lookup('domain', 'web-app-keycloak') | network_of) == 'tor' else [lookup('domain', 'web-app-keycloak') ~ ':host-gateway'] )) | indent(4) }} # nocheck: container-healthcheck-literal per-consumer sidecar partial rendered for the consuming role's application_id, so the declaration has no single meta/services.yml to live in diff --git a/roles/web-app-keycloak/templates/sso_proxy/oauth2-proxy-keycloak.cfg.j2 b/roles/web-app-keycloak/templates/sso_proxy/oauth2-proxy-keycloak.cfg.j2 index bcaa888ff1..01b9e1d089 100644 --- a/roles/web-app-keycloak/templates/sso_proxy/oauth2-proxy-keycloak.cfg.j2 +++ b/roles/web-app-keycloak/templates/sso_proxy/oauth2-proxy-keycloak.cfg.j2 @@ -6,7 +6,7 @@ upstreams = "http://{{ ((sso_proxy_application_id | get_entity_n {% set _tor_node = lookup('config', 'svc-net-tor', 'services.tor.node', '') %} {% set _domain_list = lookup('domains', sso_proxy_application_id) | domain_strings %} {% set _has_onion = _tor_node != '' and (_domain_list | select('search', _tor_node) | list | length > 0) %} -{% set _clearnet_domains = _domain_list | reject('search', '\.onion$') | list %} +{% set _clearnet_domains = _domain_list | in_network('clearnet') %} {% set _has_clearnet = _clearnet_domains | length > 0 %} {% if _has_clearnet %} cookie_domains = ["{{ _clearnet_domains | common_dns_suffix }}", "{{ lookup('domain', 'web-app-keycloak') }}"] diff --git a/roles/web-app-mailu/lookup_plugins/mailu_extra_hosts.py b/roles/web-app-mailu/lookup_plugins/mailu_extra_hosts.py index 630a8b3236..5776bd8ea2 100644 --- a/roles/web-app-mailu/lookup_plugins/mailu_extra_hosts.py +++ b/roles/web-app-mailu/lookup_plugins/mailu_extra_hosts.py @@ -32,6 +32,7 @@ from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase from utils.networks.lookup_context import resolve_var +from utils.networks.reachability import TOR, is_network HOST_GATEWAY = "host-gateway" @@ -55,7 +56,7 @@ class LookupModule(LookupBase): if ( self._flag("DOCKER_IN_CONTAINER") and self._flag("MAILU_OIDC_ENABLED") - and not oidc_host.endswith(".onion") + and not is_network(oidc_host, TOR) ): pins.append(f"{oidc_host}:{HOST_GATEWAY}") diff --git a/roles/web-app-matomo/tasks/08_reinject_consumers.yml b/roles/web-app-matomo/tasks/08_reinject_consumers.yml index 0a83a510ea..102c135505 100644 --- a/roles/web-app-matomo/tasks/08_reinject_consumers.yml +++ b/roles/web-app-matomo/tasks/08_reinject_consumers.yml @@ -1,7 +1,7 @@ --- - name: "🔎 Matomo | Stat rendered body_filter Lua of candidate web-svc matomo consumers" ansible.builtin.stat: - path: "{{ lookup('nginx', 'directories.configuration.lua') }}{{ matomo_inj_consumer.id }}.lua" + path: "{{ lookup('nginx', 'directories.configuration.lua') }}{{ lookup('domain', matomo_inj_consumer.id) }}.lua" loop: "{{ lookup('roles_with_service', 'matomo', scope='all') | selectattr('id', 'match', '^web-svc-') | list }}" loop_control: loop_var: matomo_inj_consumer @@ -12,14 +12,9 @@ - matomo_token_value is defined - matomo_token_value | length > 0 -- name: "📄 Matomo | Re-render injection for deployed web-svc consumers" - ansible.builtin.include_role: - name: sys-front-inj-all - vars: - application_id: "{{ matomo_inj_dir.matomo_inj_consumer.id }}" - domain: "{{ lookup('domain', matomo_inj_dir.matomo_inj_consumer.id) }}" - matomo_token_override: "{{ matomo_token_value }}" - loop: "{{ matomo_inj_candidates.results | default([]) | selectattr('stat.exists', 'defined') | selectattr('stat.exists') | list }}" +- name: "📄 Matomo | Re-render injection for every vhost of the deployed web-svc consumers" + ansible.builtin.include_tasks: 08_reinject_consumers/vhosts.yml + loop: "{{ matomo_inj_candidates.results | selectattr('stat.exists', 'defined') | selectattr('stat.exists') | list }}" loop_control: loop_var: matomo_inj_dir label: "{{ matomo_inj_dir.matomo_inj_consumer.id }}" diff --git a/roles/web-app-matomo/tasks/08_reinject_consumers/vhosts.yml b/roles/web-app-matomo/tasks/08_reinject_consumers/vhosts.yml new file mode 100644 index 0000000000..f17bf5fdab --- /dev/null +++ b/roles/web-app-matomo/tasks/08_reinject_consumers/vhosts.yml @@ -0,0 +1,11 @@ +--- +- name: "📄 Matomo | Re-render injection on every vhost of one web-svc consumer" + ansible.builtin.include_role: + name: sys-front-inj-all + vars: + application_id: "{{ matomo_inj_dir.matomo_inj_consumer.id }}" + domain: "{{ matomo_inj_vhost }}" + matomo_token_override: "{{ matomo_token_value }}" + loop: "{{ lookup('network_siblings', lookup('domain', matomo_inj_dir.matomo_inj_consumer.id)) }}" + loop_control: + loop_var: matomo_inj_vhost diff --git a/roles/web-app-matrix/meta/networks.yml b/roles/web-app-matrix/meta/networks.yml index f03479fcb3..55117599d2 100644 --- a/roles/web-app-matrix/meta/networks.yml +++ b/roles/web-app-matrix/meta/networks.yml @@ -2,3 +2,5 @@ local: subnet: 192.168.32.0/24 force_bridge: "{{ lookup('config', 'web-app-matrix', 'services.matrix.flavor') == 'ansible' }}" +reachability: + single_mode: true # nocheck: network-reachability Synapse derives server_name and every MXID from one domain diff --git a/roles/web-app-matrix/meta/services.yml b/roles/web-app-matrix/meta/services.yml index 232a0b2a34..f729bd7771 100644 --- a/roles/web-app-matrix/meta/services.yml +++ b/roles/web-app-matrix/meta/services.yml @@ -174,7 +174,6 @@ tor: bond: 0.5 enabled: "{{ 'svc-net-tor' in group_names }}" shared: true # nocheck: dynamic-flag - exclusive: true # nocheck: playwright-service-flag, dynamic-flag infrastructure backup consumer container_backup: # nocheck: bond-baseline backup host joins outside the variant topology bond: 1 diff --git a/roles/web-app-matrix/templates/flavor/ansible/vars.yml.j2 b/roles/web-app-matrix/templates/flavor/ansible/vars.yml.j2 index 8185cfdfd2..2607ec01de 100644 --- a/roles/web-app-matrix/templates/flavor/ansible/vars.yml.j2 +++ b/roles/web-app-matrix/templates/flavor/ansible/vars.yml.j2 @@ -1,6 +1,6 @@ --- {% set _matrix_onion_node = lookup('config', 'svc-net-tor', 'services.tor.node', '') %} -{% set _matrix_is_onion = (_matrix_onion_node and lookup('domain', application_id) is search('\.onion$')) %} +{% set _matrix_is_onion = (_matrix_onion_node and (lookup('domain', application_id) | network_of) == 'tor') %} matrix_domain: {{ _matrix_onion_node if _matrix_is_onion else DOMAIN_PRIMARY }} matrix_playbook_ssl_enabled: {{ 'false' if _matrix_is_onion else 'true' }} matrix_homeserver_implementation: synapse diff --git a/roles/web-app-matrix/vars/main.yml b/roles/web-app-matrix/vars/main.yml index deea5c3e51..db7cc45dd4 100644 --- a/roles/web-app-matrix/vars/main.yml +++ b/roles/web-app-matrix/vars/main.yml @@ -6,7 +6,7 @@ compose_mode_force: "{{ 'compose' if lookup('config', application_id, 'services. location_upload: "~ ^/_matrix/media/v3/" MATRIX_ONION_NODE: "{{ lookup('config', 'svc-net-tor', 'services.tor.node', '') }}" -MATRIX_SERVER_NAME: "{{ MATRIX_ONION_NODE if (MATRIX_ONION_NODE and lookup('domain', application_id) is search('\\.onion$')) else lookup('config', application_id, +MATRIX_SERVER_NAME: "{{ MATRIX_ONION_NODE if (MATRIX_ONION_NODE and (lookup('domain', application_id) | network_of) == 'tor') else lookup('config', application_id, 'services.matrix.server_name') }}" MATRIX_ADMINISTRATOR_USERNAME: "{{ lookup('users', 'administrator').username }}" MATRIX_ADMINISTRATOR_PASSWORD: "{{ lookup('users', 'administrator').password }}" @@ -19,7 +19,7 @@ MATRIX_REGISTRATION_SHARED_SECRET: "{{ lookup('config', application_id, 'secrets MATRIX_FEDERATION_PORT: "{{ lookup('config', 'web-app-matrix', 'services.synapse.ports.public.federation') }}" MATRIX_OIDC_ENABLED: "{{ lookup('config', application_id, 'services.sso.enabled') }}" MATRIX_OIDC_HOST: "{{ lookup('tls', 'web-app-keycloak', 'domain') }}" -MATRIX_OIDC_HOST_IS_ONION: "{{ MATRIX_OIDC_HOST is search('\\.onion$') }}" +MATRIX_OIDC_HOST_IS_ONION: "{{ (MATRIX_OIDC_HOST | network_of) == 'tor' }}" MATRIX_BASE_URL: "{{ lookup('tls', application_id, 'protocols.web') }}://{{ DOMAIN_PRIMARY }}" MATRIX_LITELLM_ENABLED: "{{ lookup('config', application_id, 'services.litellm.enabled') | bool }}" diff --git a/roles/web-app-nextcloud/templates/config/proxy.config.php.j2 b/roles/web-app-nextcloud/templates/config/proxy.config.php.j2 index 4a910d3158..16414b6a9b 100644 --- a/roles/web-app-nextcloud/templates/config/proxy.config.php.j2 +++ b/roles/web-app-nextcloud/templates/config/proxy.config.php.j2 @@ -1,5 +1,5 @@ '{{ NEXTCLOUD_TOR_SOCKS_PROXY }}', 'proxyexclude' => [ diff --git a/roles/web-app-suitecrm/vars/main.yml b/roles/web-app-suitecrm/vars/main.yml index f87c7b5368..4e8110b091 100644 --- a/roles/web-app-suitecrm/vars/main.yml +++ b/roles/web-app-suitecrm/vars/main.yml @@ -25,7 +25,7 @@ SUITECRM_WEB_GROUP: www-data SUITECRM_SSO_ENABLED: "{{ lookup('sso', application_id, 'is_saml') }}" SUITECRM_SAML_IDP_DESCRIPTOR_URL: "{{ [OIDC.CLIENT.ISSUER_URL, 'protocol/saml/descriptor'] | path_join }}" SUITECRM_SAML_SP_ENTITY_ID: "{{ [SUITECRM_URL, 'saml/metadata'] | path_join }}" -SUITECRM_OIDC_ONION_ISSUER: "{{ lookup('tls', 'web-app-keycloak', 'domain').endswith('.onion') }}" +SUITECRM_OIDC_ONION_ISSUER: "{{ (lookup('tls', 'web-app-keycloak', 'domain') | network_of) == 'tor' }}" SUITECRM_OIDC_SOCKS_PROXY: "{{ lookup('tor_socks_proxy') if SUITECRM_OIDC_ONION_ISSUER | bool else '' }}" SUITECRM_LDAP_ENABLED: "{{ lookup('config', application_id, 'services.ldap.enabled') }}" diff --git a/roles/web-app-wazuh/templates/opensearch_dashboards.yml.j2 b/roles/web-app-wazuh/templates/opensearch_dashboards.yml.j2 index 2ec84f40e5..8e6b26c26e 100644 --- a/roles/web-app-wazuh/templates/opensearch_dashboards.yml.j2 +++ b/roles/web-app-wazuh/templates/opensearch_dashboards.yml.j2 @@ -16,7 +16,7 @@ opensearch_security.auth.type: "openid" opensearch_security.openid.connect_url: "{{ OIDC.CLIENT.DISCOVERY_DOCUMENT }}" opensearch_security.openid.client_id: "{{ OIDC.CLIENT.ID }}" opensearch_security.openid.client_secret: "{{ OIDC.CLIENT.SECRET }}" -opensearch_security.openid.base_redirect_url: "{{ lookup('tls', application_id, 'url.base') }}" +opensearch_security.openid.trust_dynamic_headers: true opensearch_security.openid.scope: "openid profile email groups" opensearch_security.openid.logout_url: "{{ OIDC.CLIENT.LOGOUT_URL }}" {% endif %} diff --git a/roles/web-app-wordpress/templates/env.j2 b/roles/web-app-wordpress/templates/env.j2 index 057e6c5163..8a409e6328 100644 --- a/roles/web-app-wordpress/templates/env.j2 +++ b/roles/web-app-wordpress/templates/env.j2 @@ -12,7 +12,7 @@ WORDPRESS_INTERNAL_HOST={{ WORDPRESS_MCP_SERVICE_KEY }} WP_DEBUG={{ MODE_DEBUG | lower }} WP_DEBUG_LOG={{ MODE_DEBUG | lower }} WP_DEBUG_DISPLAY={{ MODE_DEBUG | lower }} -{% if OIDC.CLIENT.ISSUER_URL is search('\.onion(/|:|$)') %} +{% if (OIDC.CLIENT.ISSUER_URL | urlsplit('hostname') | network_of) == 'tor' %} WORDPRESS_OIDC_SOCKS_PROXY={{ lookup('tor_socks_proxy') }} {% endif %} diff --git a/roles/web-opt-rdr-domains/templates/redirect-domain.conf.j2 b/roles/web-opt-rdr-domains/templates/redirect-domain.conf.j2 index 509eb90c54..d1a3c09d4c 100644 --- a/roles/web-opt-rdr-domains/templates/redirect-domain.conf.j2 +++ b/roles/web-opt-rdr-domains/templates/redirect-domain.conf.j2 @@ -1,4 +1,6 @@ {% set application_id = domain %} +{% set _target = namespace(host=target) %} +{% for _sibling in lookup('network_siblings', target) if (_sibling | network_of) == (domain | network_of) %}{% set _target.host = _sibling %}{% endfor %} server { server_name {{ domain }}; @@ -8,6 +10,6 @@ server { {% include 'roles/web-svc-logout/templates/logout-proxy.conf.j2' %} {% endif %} location / { - return 301 {{ lookup('tls', application_id, 'protocols.web') }}://{{ target }}$request_uri; + return 301 {{ lookup('tls', application_id, 'protocols.web') }}://{{ _target.host }}$request_uri; } } diff --git a/roles/web-svc-logout/filter_plugins/domain_filters.py b/roles/web-svc-logout/filter_plugins/domain_filters.py index b3b4a52fc3..605d64e42d 100644 --- a/roles/web-svc-logout/filter_plugins/domain_filters.py +++ b/roles/web-svc-logout/filter_plugins/domain_filters.py @@ -1,5 +1,6 @@ from ansible.errors import AnsibleError, AnsibleFilterError +from utils.networks.reachability import TOR, network from utils.roles.applications.config import get from utils.tls_common import is_onion_domain, resolve_primary_domain_from_app @@ -80,7 +81,8 @@ class FilterModule: v for k, v in domains_entry.items() if str(k) not in disabled - and str(k).removesuffix("_onion") not in disabled + and str(k).removesuffix(f"_{network(TOR).label}") + not in disabled ] elif isinstance(domains_entry, list): flattened = domains_entry diff --git a/tests/lint/ansible/roles/meta/test_network_reachability.py b/tests/lint/ansible/roles/meta/test_network_reachability.py new file mode 100644 index 0000000000..268842fa12 --- /dev/null +++ b/tests/lint/ansible/roles/meta/test_network_reachability.py @@ -0,0 +1,130 @@ +"""Lint: a role's network reachability is declared once, and narrowing it says why. + +``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 +``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 +``# 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. +""" + +from __future__ import annotations + +import re +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.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"}) +_RULE = "network-reachability" +_MIN_REASON_CHARS = 10 + +_MARKER_RE = re.compile( + r"(?:noqa|nocheck)\s*:\s*" + r"(?:[a-z0-9][a-z0-9\-]*)(?:\s*,\s*[a-z0-9][a-z0-9\-]*)*(.*)$", + re.IGNORECASE, +) + + +def _load(path) -> dict: + data = load_yaml_any(str(path), default_if_missing={}) or {} + return data if isinstance(data, dict) else {} + + +def _reachability_key_line(lines: list[str], key: str) -> int | None: + """The 1-based line declaring ``reachability.``, or None.""" + inside = False + for number, line in enumerate(lines, 1): + if line and not line[0].isspace(): + inside = line.startswith("reachability:") + continue + if inside and line.strip().startswith(f"{key}:"): + return number + return None + + +def _reason_for(lines: list[str], line_no: int) -> str | None: + """The suppression reason governing *line_no*, or None when unsuppressed.""" + candidates = [line_no - 1] + previous = line_no - 2 + while previous >= 0 and not lines[previous].strip(): + previous -= 1 + candidates.append(previous) + for index in candidates: + if index < 0 or not line_has_rule(lines[index], _RULE): + continue + match = _MARKER_RE.search(lines[index]) + return match.group(1).strip().lstrip("-:").strip() if match else "" + return None + + +class TestNetworkReachability(unittest.TestCase): + def test_reachability_is_valid_and_narrowing_carries_a_reason(self) -> None: + problems: list[str] = [] + for role_dir in sorted(ROLES_DIR.iterdir()): + path = role_dir / ROLE_FILE_META_NETWORKS + networks = _load(path) + reach = networks.get("reachability") + if reach is None: + continue + try: + modes, single_mode = role_reachability( + {"networks": networks}, app=role_dir.name + ) + except (TypeError, ValueError) as exc: + problems.append(str(exc)) + continue + problems.extend( + f"{role_dir.name}: {ROLE_FILE_META_NETWORKS} reachability.{key} " + f"is unknown; known: {', '.join(sorted(REACHABILITY_KEYS))}" + for key in sorted(set(reach) - REACHABILITY_KEYS) + ) + lines = read_text(str(path)).splitlines() + restricted = bool(modes) and set(modes) != set(NETWORKS) + for key, narrows in (("single_mode", single_mode), ("modes", restricted)): + if not narrows: + continue + line_no = _reachability_key_line(lines, key) + reason = _reason_for(lines, line_no) if line_no else None + if reason is None: + problems.append( + f"{role_dir.name}: {ROLE_FILE_META_NETWORKS} reachability." + f"{key} narrows the networks but carries no " + f"`# nocheck: {_RULE}` with a reason on or above it" + ) + elif len(reason) < _MIN_REASON_CHARS: + problems.append( + f"{role_dir.name}: {ROLE_FILE_META_NETWORKS} reachability." + f"{key}: `# nocheck: {_RULE}` states no reason" + ) + self.assertEqual(problems, [], "\n".join(problems)) + + def test_tor_service_carries_no_reachability_keys(self) -> None: + problems: list[str] = [] + for role_dir in sorted(ROLES_DIR.iterdir()): + tor = _load(role_dir / ROLE_FILE_META_SERVICES).get("tor") + if not isinstance(tor, dict): + continue + problems.extend( + f"{role_dir.name}: {ROLE_FILE_META_SERVICES} tor.{key} " + f"belongs in {ROLE_FILE_META_NETWORKS} reachability" + for key in RETIRED_TOR_KEYS + if key in tor + ) + self.assertEqual(problems, [], "\n".join(problems)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/filter/test_cookie_scope.py b/tests/unit/python/plugins/filter/test_cookie_scope.py index a3bdd1e5ee..e533ae2641 100644 --- a/tests/unit/python/plugins/filter/test_cookie_scope.py +++ b/tests/unit/python/plugins/filter/test_cookie_scope.py @@ -1,27 +1,9 @@ import unittest from plugins.filter.cookie_scope import common_dns_suffix, domain_strings -from utils.cache.files import PROJECT_ROOT, read_text class CommonDnsSuffixTests(unittest.TestCase): - def test_sso_template_normalizes_mapping_before_filtering(self): - template = read_text( - str( - PROJECT_ROOT - / "roles/web-app-keycloak/templates/sso_proxy/oauth2-proxy-keycloak.cfg.j2" - ) - ) - - normalization = "| domain_strings" - self.assertIn(normalization, template) - self.assertLess( - template.index(normalization), template.index("select('search'") - ) - self.assertLess( - template.index(normalization), template.index("reject('search'") - ) - def test_domain_pipeline_normalizes_every_supported_shape(self): mapping = { "filer": "filer.seaweedfs.s3.infinito.test", diff --git a/tests/unit/python/plugins/filter/test_csp_filters/test_family_alignment.py b/tests/unit/python/plugins/filter/test_csp_filters/test_family_alignment.py index dbc2fa8159..9525320332 100644 --- a/tests/unit/python/plugins/filter/test_csp_filters/test_family_alignment.py +++ b/tests/unit/python/plugins/filter/test_csp_filters/test_family_alignment.py @@ -18,10 +18,10 @@ class TestCspFamilyAlignment(unittest.TestCase): self.domains = { "web-app-bigbluebutton": ["bbb.example.org"], "web-app-dashboard": ["dash.abc.onion"], - "web-svc-cdn": ["cdn.abc.onion", "cdn.example.org"], - "web-app-matomo": ["matomo.abc.onion", "matomo.example.org"], - "web-svc-logout": ["logout.abc.onion", "logout.example.org"], - "web-app-keycloak": ["auth.abc.onion", "auth.example.org"], + "web-svc-cdn": ["cdn.example.org", "cdn.abc.onion"], + "web-app-matomo": ["matomo.example.org", "matomo.abc.onion"], + "web-svc-logout": ["logout.example.org", "logout.abc.onion"], + "web-app-keycloak": ["auth.example.org", "auth.abc.onion"], } def test_clearnet_consumer_gets_clearnet_provider_tokens(self): @@ -46,6 +46,21 @@ class TestCspFamilyAlignment(unittest.TestCase): self.assertNotIn("cdn.example.org", header) self.assertNotIn("matomo.example.org", header) + def test_onion_vhost_of_a_clearnet_consumer_gets_onion_tokens(self): + domains = dict(self.domains) + domains["web-app-bigbluebutton"] = ["bbb.example.org", "bbb.abc.onion"] + header = self.filter.build_csp_header( + self.apps, + "web-app-bigbluebutton", + domains, + "https", + vhost_domain="bbb.abc.onion", + ) + self.assertIn("http://cdn.abc.onion", header) + self.assertIn("http://matomo.abc.onion", header) + self.assertNotIn("cdn.example.org", header) + self.assertIn("https://auth.example.org", header) + def test_onion_only_provider_falls_back_for_clearnet_consumer(self): domains = dict(self.domains) domains["web-svc-cdn"] = ["cdn.abc.onion"] @@ -61,5 +76,5 @@ class TestCspFamilyAlignment(unittest.TestCase): header = self.filter.build_csp_header( self.apps, "web-app-bigbluebutton", domains, "https" ) - self.assertIn("http://cdn.abc.onion", header) - self.assertNotIn("https://cdn.abc.onion", header) + self.assertIn("https://cdn.example.org", header) + self.assertNotIn("cdn.abc.onion", header) diff --git a/tests/unit/python/plugins/filter/test_csp_filters/test_onion_mirror.py b/tests/unit/python/plugins/filter/test_csp_filters/test_onion_mirror.py index e0ab1f7e51..6125db9b4f 100644 --- a/tests/unit/python/plugins/filter/test_csp_filters/test_onion_mirror.py +++ b/tests/unit/python/plugins/filter/test_csp_filters/test_onion_mirror.py @@ -8,6 +8,8 @@ PRIMARY = "infinito.test" class TestCspOnionMirror(unittest.TestCase): + """Whitelist sources under DOMAIN_PRIMARY follow the vhost's network.""" + def setUp(self): self.filter = FilterModule() self.apps = { @@ -20,6 +22,10 @@ class TestCspOnionMirror(unittest.TestCase): }, "svc-net-tor": {"services": {"tor": {"node": NODE}}}, } + self.domains = { + "web-svc-cdn": ["cdn." + PRIMARY, "cdn." + NODE], + "app1": ["app1." + PRIMARY, "app1." + NODE], + } def _tokens(self, header, directive): for raw in header.split(";"): @@ -28,54 +34,40 @@ class TestCspOnionMirror(unittest.TestCase): return [t for t in part[len(directive) :].strip().split(" ") if t] return [] - def _header(self, app_domains): - domains = {"web-svc-cdn": ["cdn." + PRIMARY], **app_domains} + def _header(self, vhost, domains=None, apps=None): return self.filter.build_csp_header( - copy.deepcopy(self.apps), + copy.deepcopy(apps or self.apps), "app1", - domains, - "http", + domains or self.domains, + "https", domain_primary=PRIMARY, + vhost_domain=vhost, ) - def test_primary_keeps_clearnet_and_adds_onion(self): - frame = self._tokens( - self._header({"app1": ["app1." + NODE, "app1." + PRIMARY]}), "frame-src" - ) - self.assertIn("*." + PRIMARY, frame) - self.assertIn("*." + NODE, frame) + def test_clearnet_vhost_keeps_clearnet_sources(self): + header = self._header("app1." + PRIMARY) + self.assertEqual(self._tokens(header, "frame-src"), ["'self'", "*." + PRIMARY]) + self.assertIn("https://cdn." + PRIMARY, self._tokens(header, "connect-src")) + self.assertNotIn(".onion", header) - def test_onion_sibling_of_a_tls_token_is_plaintext(self): - domains = { - "web-svc-cdn": ["cdn." + PRIMARY], - "app1": ["app1." + PRIMARY, "app1." + NODE], - } - header = self.filter.build_csp_header( - copy.deepcopy(self.apps), "app1", domains, "https", domain_primary=PRIMARY - ) + def test_onion_vhost_moves_sources_to_the_node_in_plaintext(self): + header = self._header("app1." + NODE) + self.assertEqual(self._tokens(header, "frame-src"), ["'self'", "*." + NODE]) connect = self._tokens(header, "connect-src") - self.assertIn("https://cdn." + PRIMARY, connect) self.assertIn("http://cdn." + NODE, connect) - self.assertNotIn("https://cdn." + NODE, connect) + self.assertNotIn("https://cdn." + PRIMARY, connect) - def test_exclusive_replaces_clearnet_with_onion(self): - frame = self._tokens(self._header({"app1": ["app1." + NODE]}), "frame-src") + def test_tor_only_app_without_vhost_follows_its_primary(self): + domains = {"web-svc-cdn": ["cdn." + NODE], "app1": ["app1." + NODE]} + frame = self._tokens(self._header(None, domains=domains), "frame-src") self.assertIn("*." + NODE, frame) self.assertNotIn("*." + PRIMARY, frame) - def test_non_tor_app_unchanged(self): - frame = self._tokens(self._header({"app1": ["app1." + PRIMARY]}), "frame-src") - self.assertIn("*." + PRIMARY, frame) - self.assertFalse(any(".onion" in t for t in frame)) - - def test_no_mirror_without_node(self): + def test_no_translation_without_node(self): apps = copy.deepcopy(self.apps) del apps["svc-net-tor"] - domains = {"web-svc-cdn": ["cdn." + PRIMARY], "app1": ["app1." + NODE]} - header = self.filter.build_csp_header( - apps, "app1", domains, "http", domain_primary=PRIMARY - ) - self.assertFalse(any(".onion" in t for t in self._tokens(header, "frame-src"))) + frame = self._tokens(self._header("app1." + NODE, apps=apps), "frame-src") + self.assertEqual(frame, ["'self'", "*." + PRIMARY]) if __name__ == "__main__": diff --git a/tests/unit/python/plugins/filter/test_network_of.py b/tests/unit/python/plugins/filter/test_network_of.py new file mode 100644 index 0000000000..a413c189a8 --- /dev/null +++ b/tests/unit/python/plugins/filter/test_network_of.py @@ -0,0 +1,52 @@ +import unittest + +from plugins.filter.network_of import FilterModule + +ONION = "abc123def456ghij789klmno000pqrstuvwx111yz222abc333def444gh.onion" + + +class TestNetworkFilters(unittest.TestCase): + def setUp(self): + self.filters = FilterModule().filters() + + def test_network_of_is_the_registry_lookup(self): + self.assertEqual(self.filters["network_of"]("x.abc.onion"), "tor") + self.assertEqual(self.filters["network_of"]("x.infinito.test"), "clearnet") + + def test_network_sibling_translates_the_primary(self): + self.assertEqual( + self.filters["network_sibling"]( + "infinito.test", "tor", "infinito.test", ONION + ), + ONION, + ) + + def test_network_suffix_comes_from_the_registry(self): + self.assertEqual(self.filters["network_suffix"]("tor"), ".onion") + self.assertEqual(self.filters["network_suffix"]("clearnet"), "") + + def test_network_suffixes_maps_only_networks_with_a_suffix(self): + self.assertEqual( + self.filters["network_suffixes"](["clearnet", "tor"]), {"tor": ".onion"} + ) + self.assertEqual(self.filters["network_suffixes"](["clearnet"]), {}) + + def test_in_network_keeps_the_domains_of_one_network(self): + domains = ["a.infinito.test", f"a.{ONION}", "b.infinito.test"] + self.assertEqual( + self.filters["in_network"](domains, "clearnet"), + ["a.infinito.test", "b.infinito.test"], + ) + self.assertEqual(self.filters["in_network"](domains, "tor"), [f"a.{ONION}"]) + + def test_network_sibling_is_empty_without_a_node(self): + self.assertEqual( + self.filters["network_sibling"]( + "infinito.test", "tor", "infinito.test", "" + ), + "", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/filter/test_url_to_onion.py b/tests/unit/python/plugins/filter/test_url_to_onion.py deleted file mode 100644 index 46205d0bf3..0000000000 --- a/tests/unit/python/plugins/filter/test_url_to_onion.py +++ /dev/null @@ -1,45 +0,0 @@ -import unittest - -from plugins.filter.url.to_onion import to_onion_url - -NODE = "abc123def456ghij789klmno000pqrstuvwx111yz222abc333def444gh.onion" -PRIMARY = "infinito.test" - - -class TestToOnionUrl(unittest.TestCase): - def test_subdomain_swapped_and_forced_http(self): - self.assertEqual( - to_onion_url("https://auth.infinito.test/realms/x", NODE, PRIMARY), - f"http://auth.{NODE}/realms/x", - ) - - def test_bare_primary_becomes_node(self): - self.assertEqual( - to_onion_url("https://infinito.test/", NODE, PRIMARY), - f"http://{NODE}/", - ) - - def test_path_and_query_preserved(self): - self.assertEqual( - to_onion_url("https://cdn.infinito.test/a/b.js?v=3", NODE, PRIMARY), - f"http://cdn.{NODE}/a/b.js?v=3", - ) - - def test_host_not_under_primary_unchanged(self): - url = "https://example.org/foo" - self.assertEqual(to_onion_url(url, NODE, PRIMARY), url) - - def test_noop_without_tor_node(self): - url = "https://auth.infinito.test/" - self.assertEqual(to_onion_url(url, "", PRIMARY), url) - - def test_noop_on_empty_url(self): - self.assertEqual(to_onion_url("", NODE, PRIMARY), "") - - def test_already_onion_host_unchanged(self): - url = f"http://auth.{NODE}/" - self.assertEqual(to_onion_url(url, NODE, PRIMARY), url) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_cert.py b/tests/unit/python/plugins/lookup/test_cert.py index 8d6dc94372..b6376de286 100644 --- a/tests/unit/python/plugins/lookup/test_cert.py +++ b/tests/unit/python/plugins/lookup/test_cert.py @@ -84,6 +84,13 @@ class TestCertPlanLookup(unittest.TestCase): ) self.assertEqual(out["domains"]["san"], ["a.example"]) + def test_sans_leave_out_networks_without_tls(self): + v = dict(self.vars) + v["domains"] = dict(self.domains) + v["domains"]["web-app-a"] = ["a.example", "a.abc.onion"] + out = self.lookup.run(["web-app-a"], variables=v, mode="app")[0] + self.assertEqual(out["domains"]["san"], ["a.example"]) + def test_letsencrypt_plan_uses_cert_name_override(self): v = dict(self.vars) v["applications"] = dict(self.applications) diff --git a/tests/unit/python/plugins/lookup/test_network_siblings.py b/tests/unit/python/plugins/lookup/test_network_siblings.py new file mode 100644 index 0000000000..00c45d8ac9 --- /dev/null +++ b/tests/unit/python/plugins/lookup/test_network_siblings.py @@ -0,0 +1,68 @@ +"""Contract of ``lookup('network_siblings')``: every logical domain renders +once per network its app is served on, and exactly once overall.""" + +from __future__ import annotations + +import unittest + +from plugins.lookup.network_siblings import served_siblings + +ONION = "abc123def456ghij789klmno000pqrstuvwx111yz222abc333def444gh.onion" +PRIMARY = "infinito.test" + + +class TestServedSiblings(unittest.TestCase): + def test_multi_app_renders_both_networks_from_the_canonical_domain(self) -> None: + domains = {"web-app-x": ["x.infinito.test", f"x.{ONION}"]} + self.assertEqual( + served_siblings("x.infinito.test", domains, PRIMARY, ONION), + ["x.infinito.test", f"x.{ONION}"], + ) + + def test_multi_app_skips_the_non_canonical_sibling(self) -> None: + domains = {"web-app-x": ["x.infinito.test", f"x.{ONION}"]} + self.assertEqual(served_siblings(f"x.{ONION}", domains, PRIMARY, ONION), []) + + def test_tor_only_app_maps_a_raw_clearnet_domain_to_its_onion(self) -> None: + domains = {"web-app-x": [f"x.{ONION}"]} + self.assertEqual( + served_siblings("x.infinito.test", domains, PRIMARY, ONION), [f"x.{ONION}"] + ) + + def test_clearnet_only_app_renders_one_vhost(self) -> None: + domains = {"web-app-x": ["x.infinito.test"]} + self.assertEqual( + served_siblings("x.infinito.test", domains, PRIMARY, ONION), + ["x.infinito.test"], + ) + + def test_named_canonicals_fan_out_per_key(self) -> None: + domains = { + "web-app-x": { + "api": "api.infinito.test", + "web": "web.infinito.test", + "api_onion": f"api.{ONION}", + "web_onion": f"web.{ONION}", + } + } + self.assertEqual( + served_siblings("web.infinito.test", domains, PRIMARY, ONION), + ["web.infinito.test", f"web.{ONION}"], + ) + + def test_unknown_domain_renders_as_given(self) -> None: + self.assertEqual( + served_siblings("elsewhere.example", {}, PRIMARY, ONION), + ["elsewhere.example"], + ) + + def test_node_without_tor_renders_as_given(self) -> None: + domains = {"web-app-x": ["x.infinito.test"]} + self.assertEqual( + served_siblings("x.infinito.test", domains, PRIMARY, ""), + ["x.infinito.test"], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/svc-net-tor/test_test_env_sourcing.py b/tests/unit/python/roles/svc-net-tor/test_test_env_sourcing.py index e0a3f8ed8c..65a765b719 100644 --- a/tests/unit/python/roles/svc-net-tor/test_test_env_sourcing.py +++ b/tests/unit/python/roles/svc-net-tor/test_test_env_sourcing.py @@ -15,6 +15,7 @@ import unittest from jinja2 import Environment, StrictUndefined, select_autoescape from plugins.filter.dotenv import FilterModule +from plugins.filter.network_of import FilterModule as NetworkFilters from utils.cache.files import read_text from . import PROJECT_ROOT @@ -40,6 +41,7 @@ def _render(mode: str) -> str: autoescape=select_autoescape(default_for_string=False), ) env.filters.update(FilterModule().filters()) + env.filters.update(NetworkFilters().filters()) return env.from_string(read_text(str(TEMPLATE))).render( lookup=_lookup, DEPLOYMENT_MODE=mode, diff --git a/tests/unit/python/roles/sys-ctl-hlth-csp/files/test_script.py b/tests/unit/python/roles/sys-ctl-hlth-csp/files/test_script.py index 8d7e98aac8..00fb1422a6 100644 --- a/tests/unit/python/roles/sys-ctl-hlth-csp/files/test_script.py +++ b/tests/unit/python/roles/sys-ctl-hlth-csp/files/test_script.py @@ -54,71 +54,107 @@ class TestExtractDomainsFromFilenames(unittest.TestCase): self.assertIsNone(domains) -class TestSplitOnionDomains(unittest.TestCase): +SUFFIX = ".onion" + + +def _vhosts(*domains: str) -> dict[str, Path]: + return {d: Path("/etc/nginx/servers/http") / f"{d}.conf" for d in domains} + + +def _argv(*extra: str) -> list[str]: + return [ + "script.py", + "--nginx-config-dir", + "/etc/nginx/servers", + "--proxy-suffix", + SUFFIX, + "--image", + "img:tag", + *extra, + ] + + +class TestCollectVhosts(unittest.TestCase): + def test_https_conf_wins_over_the_http_redirect(self) -> None: + import tempfile + + with tempfile.TemporaryDirectory() as tmp: + for protocol, domain in ( + ("http", "app.infinito.test"), + ("https", "app.infinito.test"), + ("http", "app.abc123.onion"), + ): + (Path(tmp) / protocol).mkdir(exist_ok=True) + (Path(tmp) / protocol / f"{domain}.conf").write_text("") + + vhosts = script.collect_vhosts(tmp) + + self.assertEqual(vhosts["app.infinito.test"].parent.name, "https") + self.assertEqual(vhosts["app.abc123.onion"].parent.name, "http") + + def test_missing_directories_return_none(self) -> None: + with patch("sys.stderr"): + self.assertIsNone(script.collect_vhosts("/definitely/missing")) + + +class TestSplitProxiedDomains(unittest.TestCase): def test_splits_families(self) -> None: domains = [ "auth.abc123.onion", "app.infinito.test", "matomo.abc123.onion", ] - clearnet, onion = script.split_onion_domains(domains) + clearnet, onion = script.split_proxied_domains(domains, SUFFIX) self.assertEqual(clearnet, ["app.infinito.test"]) self.assertEqual(onion, ["auth.abc123.onion", "matomo.abc123.onion"]) def test_clearnet_only(self) -> None: domains = ["a.example", "b.example"] - self.assertEqual(script.split_onion_domains(domains), (domains, [])) + self.assertEqual(script.split_proxied_domains(domains, SUFFIX), (domains, [])) def test_empty_list(self) -> None: - self.assertEqual(script.split_onion_domains([]), ([], [])) + self.assertEqual(script.split_proxied_domains([], SUFFIX), ([], [])) + + def test_no_suffix_proxies_nothing(self) -> None: + domains = ["a.abc123.onion"] + self.assertEqual(script.split_proxied_domains(domains, ""), (domains, [])) class TestIsSkippedDomain(unittest.TestCase): - def test_explicit_clearnet_domain_is_skipped(self) -> None: + def _skipped(self, domain: str) -> bool: skip_set = {"mirror.infinito.test"} labels = {d.split(".", 1)[0] for d in skip_set} - self.assertTrue( - script.is_skipped_domain("mirror.infinito.test", skip_set, labels) - ) + return script.is_skipped_domain(domain, skip_set, labels, SUFFIX) + + def test_explicit_clearnet_domain_is_skipped(self) -> None: + self.assertTrue(self._skipped("mirror.infinito.test")) def test_onion_sibling_of_skipped_clearnet_is_skipped(self) -> None: - skip_set = {"mirror.infinito.test"} - labels = {d.split(".", 1)[0] for d in skip_set} - self.assertTrue( - script.is_skipped_domain("mirror.abc123.onion", skip_set, labels) - ) + self.assertTrue(self._skipped("mirror.abc123.onion")) def test_unrelated_onion_is_not_skipped(self) -> None: - skip_set = {"mirror.infinito.test"} - labels = {d.split(".", 1)[0] for d in skip_set} - self.assertFalse( - script.is_skipped_domain("auth.abc123.onion", skip_set, labels) - ) + self.assertFalse(self._skipped("auth.abc123.onion")) def test_unrelated_clearnet_is_not_skipped(self) -> None: - skip_set = {"mirror.infinito.test"} - labels = {d.split(".", 1)[0] for d in skip_set} - self.assertFalse( - script.is_skipped_domain("auth.infinito.test", skip_set, labels) - ) + self.assertFalse(self._skipped("auth.infinito.test")) class TestMainSkipsOnionSiblings(unittest.TestCase): @patch("script.run_checker") @patch("script.build_urls_from_nginx_confs") - @patch("script.extract_domains_from_filenames") + @patch("script.collect_vhosts") def test_onion_sibling_of_skip_domain_is_excluded( self, - mock_extract: MagicMock, + mock_collect: MagicMock, mock_build_urls: MagicMock, mock_run_checker: MagicMock, ) -> None: - mock_extract.return_value = [ + mock_collect.return_value = _vhosts( "mirror.infinito.test", "mirror.abc123.onion", "auth.abc123.onion", - ] - mock_build_urls.side_effect = lambda _dir, domains: [ + ) + mock_build_urls.side_effect = lambda _vhosts, domains: [ f"http://{d}/" for d in domains ] mock_run_checker.return_value = 0 @@ -127,17 +163,12 @@ class TestMainSkipsOnionSiblings(unittest.TestCase): patch.object( script.sys, "argv", - [ - "script.py", - "--nginx-config-dir", - "/etc/nginx", - "--image", - "img:tag", + _argv( "--skip-domain", "mirror.infinito.test", "--tor-proxy", "socks5://127.0.0.1:9050", - ], + ), ), self.assertRaises(SystemExit), ): @@ -210,15 +241,15 @@ class TestBuildDockerCmdTimeout(unittest.TestCase): class TestMainTimesOutOnionsOnly(unittest.TestCase): @patch("script.run_checker") @patch("script.build_urls_from_nginx_confs") - @patch("script.extract_domains_from_filenames") + @patch("script.collect_vhosts") def test_the_onion_batch_alone_carries_the_budget( self, - mock_extract: MagicMock, + mock_collect: MagicMock, mock_build_urls: MagicMock, mock_run_checker: MagicMock, ) -> None: - mock_extract.return_value = ["auth.infinito.test", "auth.abc123.onion"] - mock_build_urls.side_effect = lambda _dir, domains: [ + mock_collect.return_value = _vhosts("auth.infinito.test", "auth.abc123.onion") + mock_build_urls.side_effect = lambda _vhosts, domains: [ f"http://{d}/" for d in domains ] mock_run_checker.return_value = 0 @@ -227,17 +258,12 @@ class TestMainTimesOutOnionsOnly(unittest.TestCase): patch.object( script.sys, "argv", - [ - "script.py", - "--nginx-config-dir", - "/etc/nginx", - "--image", - "img:tag", + _argv( "--tor-proxy", "socks5://127.0.0.1:9050", "--onion-timeout", "100000", - ], + ), ), self.assertRaises(SystemExit), ): @@ -288,14 +314,18 @@ class TestBuildUrlsFromNginxConfs(unittest.TestCase): def test_build_urls_https_preferred(self, mock_detect: MagicMock) -> None: mock_detect.return_value = "https" - urls = script.build_urls_from_nginx_confs("/etc/nginx", ["example.com"]) + urls = script.build_urls_from_nginx_confs( + _vhosts("example.com"), ["example.com"] + ) self.assertEqual(urls, ["https://example.com/"]) @patch("script.detect_scheme_from_conf") def test_build_urls_http_when_http_detected(self, mock_detect: MagicMock) -> None: mock_detect.return_value = "http" - urls = script.build_urls_from_nginx_confs("/etc/nginx", ["example.com"]) + urls = script.build_urls_from_nginx_confs( + _vhosts("example.com"), ["example.com"] + ) self.assertEqual(urls, ["http://example.com/"]) @patch("script.detect_scheme_from_conf") @@ -305,7 +335,9 @@ class TestBuildUrlsFromNginxConfs(unittest.TestCase): mock_detect.return_value = None with patch("sys.stderr") as _stderr: - urls = script.build_urls_from_nginx_confs("/etc/nginx", ["example.com"]) + urls = script.build_urls_from_nginx_confs( + _vhosts("example.com"), ["example.com"] + ) self.assertEqual(urls, ["http://example.com/"]) @@ -444,20 +476,16 @@ class TestRunChecker(unittest.TestCase): class TestMain(unittest.TestCase): @patch("script.run_checker") - @patch("script.extract_domains_from_filenames") - def test_main_exits_1_when_extract_domains_returns_none( + @patch("script.collect_vhosts") + def test_main_exits_1_when_collect_vhosts_returns_none( self, - mock_extract: MagicMock, + mock_collect: MagicMock, mock_run_checker: MagicMock, ) -> None: - mock_extract.return_value = None + mock_collect.return_value = None with ( - patch.object( - script.sys, - "argv", - ["script.py", "--nginx-config-dir", "/missing", "--image", "img:tag"], - ), + patch.object(script.sys, "argv", _argv()), self.assertRaises(SystemExit) as cm, ): script.main() @@ -466,20 +494,16 @@ class TestMain(unittest.TestCase): mock_run_checker.assert_not_called() @patch("script.run_checker") - @patch("script.extract_domains_from_filenames") + @patch("script.collect_vhosts") def test_main_exits_0_when_no_domains_found( self, - mock_extract: MagicMock, + mock_collect: MagicMock, mock_run_checker: MagicMock, ) -> None: - mock_extract.return_value = [] + mock_collect.return_value = {} with ( - patch.object( - script.sys, - "argv", - ["script.py", "--nginx-config-dir", "/etc/nginx", "--image", "img:tag"], - ), + patch.object(script.sys, "argv", _argv()), self.assertRaises(SystemExit) as cm, ): script.main() @@ -489,14 +513,14 @@ class TestMain(unittest.TestCase): @patch("script.run_checker") @patch("script.build_urls_from_nginx_confs") - @patch("script.extract_domains_from_filenames") + @patch("script.collect_vhosts") def test_main_passes_defaults_and_exits_with_run_checker_rc( self, - mock_extract: MagicMock, + mock_collect: MagicMock, mock_build_urls: MagicMock, mock_run_checker: MagicMock, ) -> None: - mock_extract.return_value = ["example.com", "api.example.com"] + mock_collect.return_value = _vhosts("example.com", "api.example.com") mock_build_urls.return_value = [ "http://example.com/", "https://api.example.com/", @@ -507,17 +531,12 @@ class TestMain(unittest.TestCase): patch.object( script.sys, "argv", - [ - "script.py", - "--nginx-config-dir", - "/etc/nginx", - "--image", - "img:tag", + _argv( "--short", "--ignore-network-blocks-from", "pxscdn.com", "cdn.example.org", - ], + ), ), self.assertRaises(SystemExit) as cm, ): @@ -540,30 +559,19 @@ class TestMain(unittest.TestCase): @patch("script.run_checker") @patch("script.build_urls_from_nginx_confs") - @patch("script.extract_domains_from_filenames") + @patch("script.collect_vhosts") def test_main_no_host_network_flag_disables_host_network( self, - mock_extract: MagicMock, + mock_collect: MagicMock, mock_build_urls: MagicMock, mock_run_checker: MagicMock, ) -> None: - mock_extract.return_value = ["example.com"] + mock_collect.return_value = _vhosts("example.com") mock_build_urls.return_value = ["http://example.com/"] mock_run_checker.return_value = 0 with ( - patch.object( - script.sys, - "argv", - [ - "script.py", - "--nginx-config-dir", - "/etc/nginx", - "--image", - "img:tag", - "--no-host-network", - ], - ), + patch.object(script.sys, "argv", _argv("--no-host-network")), self.assertRaises(SystemExit) as cm, ): script.main() @@ -575,22 +583,18 @@ class TestMain(unittest.TestCase): @patch("script.run_checker") @patch("script.build_urls_from_nginx_confs") - @patch("script.extract_domains_from_filenames") + @patch("script.collect_vhosts") def test_main_exits_0_when_no_urls_built( self, - mock_extract: MagicMock, + mock_collect: MagicMock, mock_build_urls: MagicMock, mock_run_checker: MagicMock, ) -> None: - mock_extract.return_value = ["example.com"] + mock_collect.return_value = _vhosts("example.com") mock_build_urls.return_value = [] with ( - patch.object( - script.sys, - "argv", - ["script.py", "--nginx-config-dir", "/etc/nginx", "--image", "img:tag"], - ), + patch.object(script.sys, "argv", _argv()), self.assertRaises(SystemExit) as cm, ): script.main() diff --git a/tests/unit/python/roles/sys-ctl-hlth-csp/test_accept_status_reaches_onions.py b/tests/unit/python/roles/sys-ctl-hlth-csp/test_accept_status_reaches_onions.py index 770713510c..1224545c27 100644 --- a/tests/unit/python/roles/sys-ctl-hlth-csp/test_accept_status_reaches_onions.py +++ b/tests/unit/python/roles/sys-ctl-hlth-csp/test_accept_status_reaches_onions.py @@ -13,7 +13,7 @@ def _expand(accept_status, domains=None): module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module.expand_accept_status( - accept_status, DOMAINS if domains is None else domains + accept_status, DOMAINS if domains is None else domains, ".onion" ) diff --git a/tests/unit/python/roles/sys-ctl-hlth-csp/test_unit_flags_are_parsable.py b/tests/unit/python/roles/sys-ctl-hlth-csp/test_unit_flags_are_parsable.py index 759832c95a..0ca41dcc43 100644 --- a/tests/unit/python/roles/sys-ctl-hlth-csp/test_unit_flags_are_parsable.py +++ b/tests/unit/python/roles/sys-ctl-hlth-csp/test_unit_flags_are_parsable.py @@ -14,6 +14,7 @@ SCRIPT = ROLE / "files" / "python" / "script.py" _FLAG = re.compile(r"'\s*(--[a-z][a-z0-9-]*)") _VALUE = { "--nginx-config-dir": "/nonexistent", + "--proxy-suffix": ".onion", "--image": "img", "--tor-proxy": "socks5://127.0.0.1:9050", "--onion-timeout": "1000", @@ -35,12 +36,18 @@ def _invoke(flag: str) -> subprocess.CompletedProcess: str(SCRIPT), "--nginx-config-dir", "/nonexistent", + "--proxy-suffix", + ".onion", "--image", "img", ] if flag in _LIST_VALUE: argv.extend([flag, _LIST_VALUE[flag]]) - elif flag in _VALUE and flag not in ("--nginx-config-dir", "--image"): + elif flag in _VALUE and flag not in ( + "--nginx-config-dir", + "--proxy-suffix", + "--image", + ): argv.extend([flag, _VALUE[flag]]) elif flag not in _VALUE: argv.append(flag) diff --git a/tests/unit/python/roles/sys-ctl-hlth-webserver/files/test_script.py b/tests/unit/python/roles/sys-ctl-hlth-webserver/files/test_script.py index ac58907870..4259966002 100644 --- a/tests/unit/python/roles/sys-ctl-hlth-webserver/files/test_script.py +++ b/tests/unit/python/roles/sys-ctl-hlth-webserver/files/test_script.py @@ -1,5 +1,6 @@ import importlib.util import io +import json import unittest from contextlib import redirect_stdout from pathlib import Path @@ -14,6 +15,15 @@ def load_module_from_path(mod_name: str, path: str): return module +def _target(codes, scheme="https", timeout=10): + return {"codes": codes, "scheme": scheme, "timeout": timeout} + + +class _Response: + def __init__(self, status_code): + self.status_code = status_code + + class TestStandaloneCheckerScript(unittest.TestCase): @classmethod def setUpClass(cls): @@ -31,53 +41,41 @@ class TestStandaloneCheckerScript(unittest.TestCase): raise FileNotFoundError(f"Cannot find script.py at {cls.script_path}") cls.script = load_module_from_path("health_script", cls.script_path) - # ------------- JSON parsing ------------------ - def test_rejects_invalid_json(self): with self.assertRaises(SystemExit): - self.script.main( - [ - "--expectations", - '{"bad json": [200, 301]', - ] - ) + self.script.main(["--targets", '{"bad json": {']) def test_rejects_non_mapping_json(self): + with self.assertRaises(SystemExit): + self.script.main(["--targets", '["not", "a", "mapping"]']) + + def test_rejects_unknown_scheme(self): + with self.assertRaises(SystemExit): + self.script.main( + ["--targets", json.dumps({"a.example.org": _target([200], "ftp")})] + ) + + def test_rejects_missing_timeout(self): with self.assertRaises(SystemExit): self.script.main( [ - "--expectations", - '["not", "a", "mapping"]', + "--targets", + json.dumps({"a.example.org": {"codes": [200], "scheme": "https"}}), ] ) - # ------------- Happy path / mismatches ------- - @patch("requests.head") def test_all_ok_returns_zero(self, mock_head): - def head_side_effect(url, allow_redirects=False, timeout=10, verify=True): - class R: - pass + statuses = {"ok1.example.org": 200, "ok2.example.org": 301} + mock_head.side_effect = lambda url, **_: _Response( + statuses[url.split("://", 1)[1]] + ) - r = R() - domain = url.split("://", 1)[1] - mapping = {"ok1.example.org": 200, "ok2.example.org": 301} - r.status_code = mapping.get(domain, 200) - return r - - mock_head.side_effect = head_side_effect - - exp = { - "ok1.example.org": [200, 302, 301], - "ok2.example.org": [301], - } exit_code, output = self._run_main( - [ - "--web-protocol", - "https", - "--expectations", - self._to_json(exp), - ] + { + "ok1.example.org": _target([200, 302, 301]), + "ok2.example.org": _target([301]), + } ) self.assertEqual(exit_code, 0) self.assertIn("ok1.example.org: OK", output) @@ -85,110 +83,52 @@ class TestStandaloneCheckerScript(unittest.TestCase): @patch("requests.head") def test_mismatches_counted(self, mock_head): - def head_side_effect(url, allow_redirects=False, timeout=10, verify=True): - class R: - pass + mock_head.side_effect = lambda url, **_: _Response(200) - r = R() - domain = url.split("://", 1)[1] - mapping = {"bad.example.org": 200, "ok301.example.org": 301} - r.status_code = mapping.get(domain, 200) - return r - - mock_head.side_effect = head_side_effect - - exp = { - "bad.example.org": [404], - "ok301.example.org": [301], - "never.example.org": [200], - } exit_code, output = self._run_main( - [ - "--expectations", - self._to_json(exp), - ] + {"bad.example.org": _target([404]), "ok.example.org": _target([200])} ) self.assertEqual(exit_code, 1) self.assertIn("bad.example.org: ERROR: Expected [404]. Got 200.", output) @patch("requests.head") - def test_non_list_values_sanitize_to_empty_and_fail(self, mock_head): - # If a domain maps to a non-list, it becomes [] and is treated as a failure - def head_side_effect(url, allow_redirects=False, timeout=10, verify=True): - class R: - pass + def test_non_list_codes_sanitize_to_empty_and_fail(self, mock_head): + mock_head.side_effect = lambda url, **_: _Response(200) - r = R() - r.status_code = 200 - return r - - mock_head.side_effect = head_side_effect - - exp_json = '{"foo.example.org": "not-a-list", "bar.example.org": 200}' - exit_code, output = self._run_main( - [ - "--expectations", - exp_json, - ] - ) + exit_code, output = self._run_main({"foo.example.org": _target("not-a-list")}) self.assertEqual(exit_code, 1) self.assertIn( "foo.example.org: ERROR: No expectations provided. Got 200.", output ) - self.assertIn( - "bar.example.org: ERROR: No expectations provided. Got 200.", output - ) @patch("requests.head") - def test_onion_domains_probed_over_http_with_longer_timeout(self, mock_head): + def test_each_domain_uses_its_own_scheme_and_timeout(self, mock_head): seen = {} - def head_side_effect(url, allow_redirects=False, timeout=10, verify=True): - class R: - pass + def head(url, allow_redirects=False, timeout=None, verify=True): + seen[url.split("://", 1)[1]] = (url, timeout) + return _Response(200) - r = R() - domain = url.split("://", 1)[1] - seen[domain] = {"url": url, "timeout": timeout} - r.status_code = 200 - return r + mock_head.side_effect = head - mock_head.side_effect = head_side_effect - - exp = { - "clear.example.org": [200], - "svc.abcd1234efgh.onion": [200], - } exit_code, _ = self._run_main( - [ - "--web-protocol", - "https", - "--expectations", - self._to_json(exp), - ] + { + "clear.example.org": _target([200], "https", 10), + "svc.abcd1234efgh.onion": _target([200], "http", 30), + } ) self.assertEqual(exit_code, 0) self.assertEqual( - seen["svc.abcd1234efgh.onion"]["url"], "http://svc.abcd1234efgh.onion" + seen["svc.abcd1234efgh.onion"], ("http://svc.abcd1234efgh.onion", 30) ) - self.assertEqual(seen["svc.abcd1234efgh.onion"]["timeout"], 30) - self.assertEqual(seen["clear.example.org"]["url"], "https://clear.example.org") - self.assertEqual(seen["clear.example.org"]["timeout"], 10) + self.assertEqual(seen["clear.example.org"], ("https://clear.example.org", 10)) - # ------------- Helpers ----------------------- - - def _run_main(self, argv): + def _run_main(self, targets): buffer = io.StringIO() with redirect_stdout(buffer): - exit_code = self.script.main(argv) + exit_code = self.script.main(["--targets", json.dumps(targets)]) return exit_code, buffer.getvalue() - @staticmethod - def _to_json(obj) -> str: - import json - - return json.dumps(obj, separators=(",", ":")) - if __name__ == "__main__": unittest.main() 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 6ff7f937e6..9c8681f30c 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 @@ -559,7 +559,7 @@ class TestWebHealthExpectationsFilter(unittest.TestCase): ONION = "abc123def456ghij789klmno000pqrstuvwx111yz222abc333def444gh.onion" - def _tor_app(self, canonical=None, status_codes=None, **tor): + def _app_a(self, canonical=None, status_codes=None, aliases=None): returns = { ("app-a", "domains.canonical"): ( ["a.infinito.test"] if canonical is None else canonical @@ -567,26 +567,27 @@ class TestWebHealthExpectationsFilter(unittest.TestCase): } if status_codes is not None: returns[("app-a", "server.status_codes")] = status_codes + if aliases is not None: + returns[("app-a", "domains.aliases")] = aliases self._configure_returns(returns) - return {"app-a": {"services": {"tor": {"enabled": True, **tor}}}} + return {"app-a": {}} - def test_onion_exclusive_replaces_clearnet(self): - apps = self._tor_app(exclusive=True) - out = self.mod.web_health_expectations( + def _served(self, apps, served): + return self.mod.web_health_expectations( apps, - group_names=["app-a"], + group_names=list(apps), primary_domain="infinito.test", node_onion=self.ONION, + served_domains=served, ) + + def test_served_tor_only_replaces_clearnet(self): + out = self._served(self._app_a(), {"app-a": [f"a.{self.ONION}"]}) self.assertEqual(out, {f"a.{self.ONION}": [200, 302, 301]}) - def test_onion_dual_adds_onion_alongside_clearnet(self): - apps = self._tor_app(exclusive=False) - out = self.mod.web_health_expectations( - apps, - group_names=["app-a"], - primary_domain="infinito.test", - node_onion=self.ONION, + def test_served_multi_lists_both_networks(self): + out = self._served( + self._app_a(), {"app-a": ["a.infinito.test", f"a.{self.ONION}"]} ) self.assertEqual( out, @@ -596,49 +597,88 @@ class TestWebHealthExpectationsFilter(unittest.TestCase): }, ) - def test_onion_inherits_clearnet_status_codes(self): - apps = self._tor_app( - canonical={"default": ["a.infinito.test"]}, - status_codes={"default": [301, 200]}, - exclusive=True, + def test_served_onion_inherits_clearnet_status_codes(self): + out = self._served( + self._app_a( + canonical={"default": ["a.infinito.test"]}, + status_codes={"default": [301, 200]}, + ), + { + "app-a": { + "default": "a.infinito.test", + "default_onion": f"a.{self.ONION}", + } + }, ) + self.assertEqual( + out, {"a.infinito.test": [301, 200], f"a.{self.ONION}": [301, 200]} + ) + + def test_aliases_survive_the_served_view(self): + out = self._served( + self._app_a(aliases=["old.infinito.test"]), {"app-a": [f"a.{self.ONION}"]} + ) + self.assertEqual( + out, + {f"a.{self.ONION}": [200, 302, 301], "old.infinito.test": [301]}, + ) + + def test_app_missing_from_served_keeps_declared_domains(self): + out = self._served(self._app_a(), {}) + self.assertEqual(out, {"a.infinito.test": [200, 302, 301]}) + + def test_www_is_added_for_clearnet_only(self): + apps = self._app_a() out = self.mod.web_health_expectations( apps, + www_enabled=True, group_names=["app-a"], primary_domain="infinito.test", node_onion=self.ONION, + served_domains={"app-a": ["a.infinito.test", f"a.{self.ONION}"]}, ) - self.assertEqual(out, {f"a.{self.ONION}": [301, 200]}) + self.assertIn("www.a.infinito.test", out) + self.assertNotIn(f"www.a.{self.ONION}", out) - def test_onion_disabled_app_stays_clearnet(self): - self._configure_returns({("app-a", "domains.canonical"): ["a.infinito.test"]}) - apps = {"app-a": {"services": {"tor": {"enabled": False}}}} - out = self.mod.web_health_expectations( - apps, - group_names=["app-a"], - primary_domain="infinito.test", - node_onion=self.ONION, + def test_targets_use_the_per_domain_scheme_and_network_timeout(self): + served = {"app-a": ["a.infinito.test", f"a.{self.ONION}"]} + targets = self.mod.web_health_targets( + {"a.infinito.test": [200], f"a.{self.ONION}": [200]}, + {"app-a": {}}, + served, + True, + ) + self.assertEqual( + targets["a.infinito.test"], + {"codes": [200], "scheme": "https", "timeout": 10}, + ) + self.assertEqual( + targets[f"a.{self.ONION}"], + {"codes": [200], "scheme": "http", "timeout": 30}, ) - self.assertEqual(out, {"a.infinito.test": [200, 302, 301]}) - def test_onion_skipped_without_node_onion(self): - apps = self._tor_app(exclusive=True) - out = self.mod.web_health_expectations( - apps, - group_names=["app-a"], - primary_domain="infinito.test", - node_onion="", + def test_targets_follow_an_app_tls_override(self): + targets = self.mod.web_health_targets( + {"a.infinito.test": [200]}, + {"app-a": {"server": {"tls": {"enabled": False}}}}, + {"app-a": ["a.infinito.test"]}, + True, ) - self.assertEqual(out, {"a.infinito.test": [200, 302, 301]}) + self.assertEqual(targets["a.infinito.test"]["scheme"], "http") + + def test_targets_of_an_unknown_domain_use_the_global_default(self): + targets = self.mod.web_health_targets( + {"elsewhere.example": [301]}, {}, {}, True + ) + self.assertEqual(targets["elsewhere.example"]["scheme"], "https") # --------- Reverse-proxy bare apex gating --------- - def _proxy_apex_app(self, **tor): + def _proxy_apex_app(self): self._configure_returns( {("svc-prx-openresty", "domains.canonical"): ["infinito.test"]} ) - services = {"tor": {"enabled": True, **tor}} if tor else {} - return {"svc-prx-openresty": {"services": services}} + return {"svc-prx-openresty": {}} def test_apex_dropped_when_rdr_domains_not_deployed(self): out = self.mod.web_health_expectations( @@ -658,10 +698,11 @@ class TestWebHealthExpectationsFilter(unittest.TestCase): def test_onion_apex_dropped_when_rdr_domains_not_deployed(self): out = self.mod.web_health_expectations( - self._proxy_apex_app(exclusive=True), + self._proxy_apex_app(), group_names=["svc-prx-openresty"], primary_domain="infinito.test", node_onion=self.ONION, + served_domains={"svc-prx-openresty": ["infinito.test", self.ONION]}, ) self.assertEqual(out, {}) diff --git a/tests/unit/python/utils/cache/test_domains.py b/tests/unit/python/utils/cache/test_domains.py index c884e16db2..b9818c79fd 100644 --- a/tests/unit/python/utils/cache/test_domains.py +++ b/tests/unit/python/utils/cache/test_domains.py @@ -209,147 +209,123 @@ class TestImportableWithoutAnsible(unittest.TestCase): self.assertIn("OK", result.stdout) -class TestOnionDomainInjection(unittest.TestCase): +class TestNetworkSiblingInjection(unittest.TestCase): ONION = "abc123def456ghij789klmno000pqrstuvwx111yz222abc333def444gh.onion" - def _apps(self, **tor): - return { - "web-app-x": { - "services": { - "tor": { - "enabled": True, - "exclusive": False, - "primary": False, - **tor, - } - }, - } - } + def _apps(self, enabled=True, **reachability): + config = {"services": {"tor": {"enabled": enabled}}} + if reachability: + config["networks"] = {"reachability": reachability} + return {"web-app-x": config} - def test_dual_stack_appends_onion(self): - merged = {"web-app-x": ["x.infinito.test"]} - out = cache_domains._inject_onion_domains( - merged, self._apps(), "infinito.test", self.ONION - ) - self.assertEqual(out["web-app-x"], ["x.infinito.test", f"x.{self.ONION}"]) + def _inject(self, apps, node_mode, *, domains=None, deployed=("web-app-x",)): + return cache_domains._inject_network_siblings( + {"web-app-x": domains if domains is not None else ["x.infinito.test"]}, + apps, + "infinito.test", + self.ONION, + node_mode, + deployed=list(deployed), + )["web-app-x"] - def test_exclusive_replaces_clearnet(self): - merged = {"web-app-x": ["x.infinito.test"]} - out = cache_domains._inject_onion_domains( - merged, self._apps(exclusive=True), "infinito.test", self.ONION + def test_multi_appends_onion_after_clearnet(self): + self.assertEqual( + self._inject(self._apps(), "multi"), + ["x.infinito.test", f"x.{self.ONION}"], ) - self.assertEqual(out["web-app-x"], [f"x.{self.ONION}"]) - def test_primary_puts_onion_first(self): - merged = {"web-app-x": ["x.infinito.test"]} - out = cache_domains._inject_onion_domains( - merged, self._apps(primary=True), "infinito.test", self.ONION - ) - self.assertEqual(out["web-app-x"], [f"x.{self.ONION}", "x.infinito.test"]) + def test_tor_mode_replaces_clearnet(self): + self.assertEqual(self._inject(self._apps(), "tor"), [f"x.{self.ONION}"]) - def test_disabled_app_untouched(self): - merged = {"web-app-x": ["x.infinito.test"]} - apps = {"web-app-x": {"services": {"tor": {"enabled": False}}}} - out = cache_domains._inject_onion_domains( - merged, apps, "infinito.test", self.ONION + def test_clearnet_mode_is_untouched(self): + self.assertEqual( + self._inject(self._apps(enabled=False), "clearnet"), ["x.infinito.test"] ) - self.assertEqual(out["web-app-x"], ["x.infinito.test"]) - def test_exclusive_primary_default_from_provider(self): - """A consumer that omits exclusive/primary inherits the svc-net-tor - provider defaults (exclusive: true -> onion only).""" - merged = {"web-app-x": ["x.infinito.test"]} - apps = { - "web-app-x": {"services": {"tor": {"enabled": True, "shared": True}}}, - "svc-net-tor": { - "services": { - "tor": { - "enabled": True, - "shared": True, - "exclusive": True, - "primary": True, - } - } - }, - } - out = cache_domains._inject_onion_domains( - merged, apps, "infinito.test", self.ONION - ) - self.assertEqual(out["web-app-x"], [f"x.{self.ONION}"]) + def test_clearnet_mode_never_renders_the_tor_flag(self): + apps = self._apps(enabled="{{ 'svc-net-tor' in group_names }}") + self.assertEqual(self._inject(apps, "clearnet"), ["x.infinito.test"]) - def test_consumer_override_beats_provider_default(self): - """A consumer that pins exclusive: false overrides the provider's - exclusive: true and stays dual-stack.""" - merged = {"web-app-x": ["x.infinito.test"]} - apps = { - "web-app-x": { - "services": { - "tor": {"enabled": True, "shared": True, "exclusive": False} - } - }, - "svc-net-tor": { - "services": { - "tor": { - "enabled": True, - "shared": True, - "exclusive": True, - "primary": False, - } - } - }, - } - out = cache_domains._inject_onion_domains( - merged, apps, "infinito.test", self.ONION - ) - self.assertEqual(out["web-app-x"], ["x.infinito.test", f"x.{self.ONION}"]) + def test_tor_only_role_on_clearnet_node_fails_loudly(self): + with self.assertRaisesRegex(ValueError, "web-app-x"): + self._inject(self._apps(modes=["tor"]), "clearnet") - def test_consumer_exclusive_false_inherits_provider_primary_dual(self): - """A consumer pinning only exclusive: false inherits the provider's - primary: true and stays dual-stack, onion-first.""" - merged = {"web-app-x": ["x.infinito.test"]} - apps = { - "web-app-x": { - "services": { - "tor": {"enabled": True, "shared": True, "exclusive": False} - } - }, - "svc-net-tor": { - "services": { - "tor": { - "enabled": True, - "shared": True, - "exclusive": True, - "primary": True, - } - } - }, - } - out = cache_domains._inject_onion_domains( - merged, apps, "infinito.test", self.ONION + def test_single_mode_on_multi_serves_tor(self): + self.assertEqual( + self._inject(self._apps(single_mode=True), "multi"), [f"x.{self.ONION}"] + ) + + def test_clearnet_only_role_on_multi_stays_clearnet(self): + self.assertEqual( + self._inject(self._apps(modes=["clearnet"]), "multi"), ["x.infinito.test"] + ) + + def test_disabled_tor_bond_on_multi_stays_clearnet(self): + self.assertEqual( + self._inject(self._apps(enabled=False), "multi"), ["x.infinito.test"] + ) + + def test_role_without_tor_bond_is_exempt_on_tor_node(self): + apps = {"web-app-x": {"services": {}}} + self.assertEqual(self._inject(apps, "tor"), ["x.infinito.test"]) + + def test_deployed_mismatch_fails_loudly(self): + with self.assertRaisesRegex(ValueError, "web-app-x"): + self._inject(self._apps(modes=["clearnet"]), "tor") + + def test_undeployed_mismatch_keeps_domains(self): + self.assertEqual( + self._inject(self._apps(modes=["clearnet"]), "tor", deployed=()), + ["x.infinito.test"], ) - self.assertEqual(out["web-app-x"], [f"x.{self.ONION}", "x.infinito.test"]) def test_bare_primary_domain_maps_to_node_onion(self): - merged = {"web-app-x": ["infinito.test"]} - out = cache_domains._inject_onion_domains( - merged, self._apps(), "infinito.test", self.ONION + self.assertEqual( + self._inject(self._apps(), "multi", domains=["infinito.test"]), + ["infinito.test", self.ONION], + ) + + def test_named_canonicals_gain_onion_keys_after_clearnet(self): + self.assertEqual( + self._inject(self._apps(), "multi", domains={"api": "api.infinito.test"}), + {"api": "api.infinito.test", "api_onion": f"api.{self.ONION}"}, + ) + + def test_named_canonicals_in_tor_mode_swap_values(self): + self.assertEqual( + self._inject(self._apps(), "tor", domains={"api": "api.infinito.test"}), + {"api": f"api.{self.ONION}"}, ) - 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. +class TestNodeNetworkMode(unittest.TestCase): + def test_node_onion_requires_the_provider_on_the_host(self): + apps = {"svc-net-tor": {"services": {"tor": {"node": "n.onion"}}}} + self.assertEqual(cache_domains.node_onion_of(apps, {"group_names": []}), "") + self.assertEqual( + cache_domains.node_onion_of(apps, {"group_names": ["svc-net-tor"]}), + "n.onion", + ) + + def test_empty_mode_derives_from_the_node_onion(self): + self.assertEqual(cache_domains.node_network_mode({}, "n.onion"), "multi") + self.assertEqual(cache_domains.node_network_mode({}, ""), "clearnet") + + def test_declared_tor_mode_without_provider_fails(self): + with self.assertRaises(ValueError): + cache_domains.node_network_mode({"NETWORK_MODE": "tor"}, "") + + +class TestTorFlagsAreRendered(unittest.TestCase): + """`services.tor.enabled` reaches this map as Jinja in almost every role + that declares 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. """ - ONION = TestOnionDomainInjection.ONION + ONION = TestNetworkSiblingInjection.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 @@ -358,49 +334,34 @@ class TestOnionFlagsAreRendered(unittest.TestCase): templar.available_variables = dict(variables) return templar - def _inject(self, apps, **variables): - return cache_domains._inject_onion_domains( + def _inject(self, templar, **variables): + return cache_domains._inject_network_siblings( {"web-app-x": ["x.infinito.test"]}, - apps, + {"web-app-x": {"services": {"tor": {"enabled": self.JINJA_ON}}}}, "infinito.test", self.ONION, - templar=self._templar(**variables), + "multi", + templar=templar, variables=dict(variables), - ) + )["web-app-x"] 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"], + variables = {"group_names": ["svc-net-tor", "web-app-x"]} + self.assertEqual( + self._inject(self._templar(**variables), **variables), + ["x.infinito.test", f"x.{self.ONION}"], ) - 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"], + variables = {"group_names": ["web-app-x"]} + self.assertEqual( + self._inject(self._templar(**variables), **variables), + ["x.infinito.test"], ) - 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"]}, - ) + self._inject(None, group_names=["svc-net-tor"]) if __name__ == "__main__": diff --git a/tests/unit/python/utils/certs/test_tls_common.py b/tests/unit/python/utils/certs/test_tls_common.py index e51ef95881..cc5dad1483 100644 --- a/tests/unit/python/utils/certs/test_tls_common.py +++ b/tests/unit/python/utils/certs/test_tls_common.py @@ -133,38 +133,6 @@ class TestTlsCommon(unittest.TestCase): "x", domains=self.domains, forced_mode="invalid", err_prefix="t" ) - def test_resolve_term_clearnet_domain_swapped_to_onion_keeps_clearnet(self): - domains = {"svc-prx-openresty": ["abc.onion"]} - applications = { - "svc-prx-openresty": {"domains": {"canonical": ["infinito.test"]}} - } - app_id, primary = resolve_term( - "infinito.test", - domains=domains, - applications=applications, - forced_mode="auto", - err_prefix="t", - ) - self.assertEqual(app_id, "svc-prx-openresty") - self.assertEqual(primary, "infinito.test") - self.assertTrue(resolve_enabled({}, True, primary_domain=primary)) - - def test_resolve_term_alias_without_onion_swap_keeps_canonical(self): - domains = {"web-app-x": ["x.example"]} - applications = { - "web-app-x": { - "domains": {"canonical": ["x.example"], "aliases": ["old.example"]} - } - } - _, primary = resolve_term( - "old.example", - domains=domains, - applications=applications, - forced_mode="auto", - err_prefix="t", - ) - self.assertEqual(primary, "x.example") - def test_resolve_enabled_and_mode(self): app = {} self.assertTrue(resolve_enabled(app, True)) @@ -319,6 +287,81 @@ class TestTlsCommon(unittest.TestCase): "cdn.example", ) + def test_align_domain_to_consumer_onion_consumer_gets_onion_sibling(self): + domains = { + "web-svc-cdn": ["cdn.example", "cdn.abc.onion"], + "web-app-dashboard": ["dash.abc.onion"], + } + self.assertEqual( + align_domain_to_consumer( + domains, "web-svc-cdn", "cdn.example", consumer="web-app-dashboard" + ), + "cdn.abc.onion", + ) + + def test_align_domain_to_consumer_follows_the_rendered_vhost(self): + domains = { + "web-svc-cdn": ["cdn.example", "cdn.abc.onion"], + "web-app-wazuh": ["wazuh.example", "wazuh.abc.onion"], + } + variables = {"application_id": "web-app-wazuh", "domain": "wazuh.abc.onion"} + self.assertEqual( + align_domain_to_consumer( + domains, "web-svc-cdn", "cdn.example", variables=variables + ), + "cdn.abc.onion", + ) + + def test_align_domain_to_consumer_ignores_a_foreign_vhost(self): + domains = { + "web-svc-cdn": ["cdn.example", "cdn.abc.onion"], + "web-app-wazuh": ["wazuh.example", "wazuh.abc.onion"], + } + variables = {"application_id": "web-app-wazuh", "domain": "other.abc.onion"} + self.assertEqual( + align_domain_to_consumer( + domains, "web-svc-cdn", "cdn.example", variables=variables + ), + "cdn.example", + ) + + def test_align_domain_to_consumer_renders_a_templated_vhost(self): + class _FakeTemplar: + def template(self, value): + return {"{{ front_proxy_domain }}": "wazuh.abc.onion"}.get(value, value) + + domains = { + "web-svc-cdn": ["cdn.example", "cdn.abc.onion"], + "web-app-wazuh": ["wazuh.example", "wazuh.abc.onion"], + } + variables = { + "application_id": "web-app-wazuh", + "domain": "{{ front_proxy_domain }}", + } + self.assertEqual( + align_domain_to_consumer( + domains, + "web-svc-cdn", + "cdn.example", + variables=variables, + templar=_FakeTemplar(), + ), + "cdn.abc.onion", + ) + + def test_align_domain_to_consumer_never_moves_the_sso_issuer(self): + domains = { + "web-app-keycloak": ["auth.example", "auth.abc.onion"], + "web-app-wazuh": ["wazuh.example", "wazuh.abc.onion"], + } + variables = {"application_id": "web-app-wazuh", "domain": "wazuh.abc.onion"} + self.assertEqual( + align_domain_to_consumer( + domains, "web-app-keycloak", "auth.example", variables=variables + ), + "auth.example", + ) + def test_align_domain_to_consumer_dict_target_picks_clearnet_value(self): domains = { "web-app-matrix": { diff --git a/tests/unit/python/utils/networks/test_reachability.py b/tests/unit/python/utils/networks/test_reachability.py new file mode 100644 index 0000000000..26bd787767 --- /dev/null +++ b/tests/unit/python/utils/networks/test_reachability.py @@ -0,0 +1,171 @@ +"""Contract of the network registry and the per-role reachability resolution.""" + +from __future__ import annotations + +import unittest + +from utils.networks.reachability import ( + CLEARNET, + MULTI, + TOR, + allowed_networks, + effective_networks, + is_network, + network, + network_of, + resolve_node_mode, + role_reachability, + sibling_domain, +) + +ONION = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvw.onion" + + +def _cfg(**reachability) -> dict: + return {"networks": {"reachability": reachability}} if reachability else {} + + +class TestNetworkOf(unittest.TestCase): + def test_onion_suffix_is_tor(self) -> None: + self.assertEqual(network_of(f"wazuh.{ONION}"), TOR) + + def test_trailing_dot_and_case_are_ignored(self) -> None: + self.assertEqual(network_of(f"Wazuh.{ONION.upper()}."), TOR) + + def test_everything_else_is_clearnet(self) -> None: + self.assertEqual(network_of("wazuh.infinito.test"), CLEARNET) + + def test_is_network(self) -> None: + self.assertTrue(is_network(ONION, TOR)) + self.assertFalse(is_network("infinito.test", TOR)) + + def test_reserved_network_is_refused(self) -> None: + with self.assertRaises(ValueError): + network("handshake") + + def test_unknown_network_is_refused(self) -> None: + with self.assertRaises(ValueError): + network("i2p") + + +class TestSiblingDomain(unittest.TestCase): + def test_clearnet_subdomain_to_tor(self) -> None: + self.assertEqual( + sibling_domain("wazuh.infinito.test", TOR, "infinito.test", ONION), + f"wazuh.{ONION}", + ) + + def test_apex_to_tor_is_the_node_onion(self) -> None: + self.assertEqual( + sibling_domain("infinito.test", TOR, "infinito.test", ONION), ONION + ) + + def test_tor_subdomain_to_clearnet(self) -> None: + self.assertEqual( + sibling_domain(f"wazuh.{ONION}", CLEARNET, "infinito.test", ONION), + "wazuh.infinito.test", + ) + + def test_same_network_returns_itself(self) -> None: + self.assertEqual( + sibling_domain("wazuh.infinito.test", CLEARNET, "infinito.test", ONION), + "wazuh.infinito.test", + ) + + def test_foreign_domain_has_no_sibling(self) -> None: + self.assertIsNone(sibling_domain("example.org", TOR, "infinito.test", ONION)) + + def test_no_node_address_has_no_sibling(self) -> None: + self.assertIsNone( + sibling_domain("wazuh.infinito.test", TOR, "infinito.test", "") + ) + + +class TestResolveNodeMode(unittest.TestCase): + def test_empty_derives_multi_with_tor(self) -> None: + self.assertEqual(resolve_node_mode("", tor_provided=True), MULTI) + + def test_empty_derives_clearnet_without_tor(self) -> None: + self.assertEqual(resolve_node_mode(None, tor_provided=False), CLEARNET) + + def test_explicit_tor(self) -> None: + self.assertEqual(resolve_node_mode("tor", tor_provided=True), TOR) + + def test_tor_mode_without_provider_fails(self) -> None: + with self.assertRaises(ValueError): + resolve_node_mode("multi", tor_provided=False) + + def test_unknown_mode_fails(self) -> None: + with self.assertRaises(ValueError): + resolve_node_mode("dual", tor_provided=True) + + +class TestRoleReachability(unittest.TestCase): + def test_missing_means_every_network(self) -> None: + self.assertEqual(role_reachability({}), ((), False)) + + def test_empty_list_means_every_network(self) -> None: + self.assertEqual(role_reachability(_cfg(modes=[])), ((), False)) + + def test_multi_is_not_a_list_value(self) -> None: + with self.assertRaises(ValueError): + role_reachability(_cfg(modes=[CLEARNET, MULTI])) + + def test_single_mode_must_be_boolean(self) -> None: + with self.assertRaises(TypeError): + role_reachability(_cfg(single_mode="yes")) + + def test_tor_disabled_role_loses_tor(self) -> None: + self.assertEqual(allowed_networks({}, tor_enabled=False), ((CLEARNET,), False)) + + +class TestEffectiveNetworks(unittest.TestCase): + """Every combination of node mode, ``modes`` and ``single_mode``.""" + + CASES = ( + (CLEARNET, (), False, (CLEARNET,)), + (TOR, (), False, (TOR,)), + (MULTI, (), False, (CLEARNET, TOR)), + (CLEARNET, (), True, (CLEARNET,)), + (TOR, (), True, (TOR,)), + (MULTI, (), True, (TOR,)), + (CLEARNET, (CLEARNET,), False, (CLEARNET,)), + (MULTI, (CLEARNET,), False, (CLEARNET,)), + (MULTI, (CLEARNET,), True, (CLEARNET,)), + (TOR, (TOR,), False, (TOR,)), + (MULTI, (TOR,), False, (TOR,)), + (MULTI, (CLEARNET, TOR), False, (CLEARNET, TOR)), + (MULTI, (CLEARNET, TOR), True, (TOR,)), + ) + + FAILURES = ( + (TOR, (CLEARNET,), False), + (TOR, (CLEARNET,), True), + (CLEARNET, (TOR,), False), + (CLEARNET, (TOR,), True), + ) + + def test_served_networks(self) -> None: + for node_mode, modes, single, expected in self.CASES: + allowed, parsed_single = allowed_networks( + _cfg(modes=list(modes), single_mode=single), tor_enabled=True + ) + with self.subTest(node=node_mode, modes=modes, single=single): + self.assertEqual( + effective_networks(node_mode, allowed, parsed_single), expected + ) + + def test_mismatch_fails_loudly(self) -> None: + for node_mode, modes, single in self.FAILURES: + allowed, parsed_single = allowed_networks( + _cfg(modes=list(modes), single_mode=single), tor_enabled=True + ) + with ( + self.subTest(node=node_mode, modes=modes, single=single), + self.assertRaisesRegex(ValueError, "web-app-x"), + ): + effective_networks(node_mode, allowed, parsed_single, app="web-app-x") + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/cache/domains.py b/utils/cache/domains.py index ee4bd569a4..fa44458cfa 100644 --- a/utils/cache/domains.py +++ b/utils/cache/domains.py @@ -11,6 +11,17 @@ from __future__ import annotations from typing import TYPE_CHECKING, Any +from utils.networks.reachability import ( + CLEARNET, + NODE_MODES, + TOR, + allowed_networks, + effective_networks, + network, + resolve_node_mode, + sibling_domain, +) + from .base import ( _RENDER_GUARD, _cache_key, @@ -80,118 +91,149 @@ def _resolved_flag( 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``.""" - if domain == primary: - return node_onion - suffix = "." + primary - if domain.endswith(suffix): - return domain[: -len(primary)] + node_onion - return None +def _render_plain(raw: Any, name: str) -> Any: + from utils.templating.ansible import render_ansible_strict + + if isinstance(raw, str) and ("{{" in raw or "{%" in raw): + return render_ansible_strict( + templar=None, + raw=raw, + var_name=name, + err_prefix="get_merged_domains", + variables={}, + ) + return raw -def _inject_onion_domains( +def node_onion_of(apps: Any, variables: Any) -> str: + """Return the node onion address when this host runs ``svc-net-tor``. + + Args: + apps: merged applications tree. + variables: host variables carrying ``group_names``. + + Returns: + The address from ``svc-net-tor``'s ``services.tor.node``, or ``""`` + when the provider is not deployed on this host. + """ + if network(TOR).provider not in ((variables or {}).get("group_names") or []): + return "" + node_raw = ( + ((apps.get(network(TOR).provider) or {}).get("services") or {}).get("tor") or {} + ).get("node") + return str(_render_plain(node_raw or "", "services.tor.node") or "").strip() + + +def node_network_mode(variables: Any, node_onion: str) -> str: + """Return the resolved ``NETWORK_MODE`` of this host. + + Args: + variables: host variables carrying ``NETWORK_MODE``. + node_onion: the node onion address, empty without Tor. + """ + return resolve_node_mode( + _render_plain((variables or {}).get("NETWORK_MODE") or "", "NETWORK_MODE"), + tor_provided=bool(node_onion), + ) + + +def _serve_list( + domains: list[Any], networks: tuple[str, ...], primary: str, node_onion: str +) -> list[Any]: + if TOR not in networks: + return list(domains) + onion = [ + sibling + for d in domains + if (sibling := sibling_domain(str(d), TOR, primary, node_onion)) + ] + if CLEARNET not in networks: + return onion or list(domains) + return list(domains) + [o for o in onion if o not in domains] + + +def _serve_dict( + domains: dict[str, Any], networks: tuple[str, ...], primary: str, node_onion: str +) -> dict[str, Any]: + if TOR not in networks: + return dict(domains) + if CLEARNET not in networks: + return { + key: (sibling_domain(str(value), TOR, primary, node_onion) or value) + for key, value in domains.items() + } + label = network(TOR).label + siblings: dict[str, Any] = {} + for key, value in domains.items(): + sibling = sibling_domain(str(value), TOR, primary, node_onion) + if sibling and sibling != value: + siblings[f"{key}_{label}"] = sibling + return {**domains, **siblings} + + +def _inject_network_siblings( merged: dict[str, Any], apps: dict[str, Any], primary: str, node_onion: str, + node_mode: str, *, + deployed: Any = (), templar: Any = None, variables: Any = None, ) -> dict[str, Any]: - """Add ``.`` domains for apps opting into onion routing. + """Serve every application on the networks it resolves to on this node. - Driven by ``services.tor`` per app: ``enabled`` gates it (consumer-owned, - no provider fallback — an app without a tor block opts out). ``exclusive`` - replaces the clearnet domain (onion only), ``primary`` puts the onion - first; both resolve consumer-override -> ``svc-net-tor`` provider default - via :func:`resolve_service_config`. + Args: + merged: canonical domains per application. + apps: merged applications tree. + primary: the node's ``DOMAIN_PRIMARY``. + node_onion: the node onion address, empty on a node without Tor. + node_mode: the resolved ``NETWORK_MODE``. + deployed: application ids deployed on this host; only their mismatch + fails, the rest keep their domains. + templar: templar rendering the ``services.tor.enabled`` flags. + variables: scope those flags resolve against. + + Returns: + Domains per application with the canonical network first. A role + without a ``tor`` service keeps its domains on every node. + + Raises: + ValueError: a deployed role allows none of the node's networks. """ - from utils.roles.applications.services.config import resolve_service_config - from utils.roles.applications.services.registry import ( - build_service_registry_from_applications, - ) - - registry = build_service_registry_from_applications(apps) - - def _flag(value: Any, app: str, name: str) -> bool: - return _resolved_flag( - value, + out: dict[str, Any] = {} + for app, domains in merged.items(): + config = apps.get(app) or {} + tor = (config.get("services") or {}).get("tor") + if not isinstance(domains, (list, dict)) or not isinstance(tor, dict): + out[app] = domains + continue + tor_enabled = TOR in NODE_MODES[node_mode] and _resolved_flag( + tor.get("enabled"), app=app, - name=name, + name="enabled", 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 _flag( - tor.get("enabled"), app, "enabled" - ): + allowed, single_mode = allowed_networks( + config, tor_enabled=tor_enabled, app=app + ) + try: + networks = effective_networks(node_mode, allowed, single_mode, app=app) + except ValueError: + if app in deployed: + raise out[app] = domains continue - exclusive = _flag( - resolve_service_config( - apps, app, "tor", "exclusive", default=False, service_registry=registry - ), - app, - "exclusive", - ) - 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( - domains, primary, node_onion, exclusive, is_primary - ) - continue - onion = [o for d in domains if (o := _onion_of(str(d), primary, node_onion))] - if exclusive: - out[app] = onion or domains - elif is_primary: - out[app] = onion + [d for d in domains if d not in onion] + out[app] = _serve_dict(domains, networks, primary, node_onion) else: - out[app] = list(domains) + [o for o in onion if o not in domains] + out[app] = _serve_list(domains, networks, primary, node_onion) return out -def _inject_onion_into_dict( - domains: dict[str, Any], - primary: str, - node_onion: str, - exclusive: bool, - is_primary: bool, -) -> dict[str, Any]: - """Onionize a named-canonical dict (``{key: domain}``) while keeping every - value a plain string, so ``get_primary_domain`` still returns a string. - - ``exclusive`` swaps each value for its onion; otherwise the onion domains - are added under ``_onion`` siblings (before the clearnet keys when - ``primary`` is set) so ``generate_all_domains`` emits an onion vhost per - named canonical without changing which value is primary. - """ - if exclusive: - return { - key: (_onion_of(str(value), primary, node_onion) or value) - for key, value in domains.items() - } - onion_pairs: dict[str, Any] = {} - for key, value in domains.items(): - onion = _onion_of(str(value), primary, node_onion) - if onion and onion != value: - onion_pairs[f"{key}_onion"] = onion - if is_primary: - return {**onion_pairs, **domains} - return {**domains, **onion_pairs} - - def get_merged_domains( *, variables: dict[str, Any] | None = None, @@ -240,20 +282,7 @@ def get_merged_domains( "must be set in variables." ) - from utils.templating.ansible import render_ansible_strict - - def _render_raw(raw: Any, name: str) -> Any: - if isinstance(raw, str) and ("{{" in raw or "{%" in raw): - return render_ansible_strict( - templar=None, - raw=raw, - var_name=name, - err_prefix="get_merged_domains", - variables={}, - ) - return raw - - primary_domain = _render_raw(primary_domain, "DOMAIN_PRIMARY") + primary_domain = _render_plain(primary_domain, "DOMAIN_PRIMARY") apps = get_merged_applications( variables=variables, @@ -264,20 +293,18 @@ def get_merged_domains( filter_instance = _CanonicalDomainsFilter() merged = filter_instance.canonical_domains_map(apps, primary_domain) - node_raw = ( - ((apps.get("svc-net-tor") or {}).get("services") or {}).get("tor") or {} - ).get("node") - 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, - templar=templar, - variables=variables, - ) + node_onion = node_onion_of(apps, variables) + node_mode = node_network_mode(variables, node_onion) + merged = _inject_network_siblings( + merged, + apps, + str(primary_domain), + node_onion, + node_mode, + deployed=variables.get("group_names") or [], + templar=templar, + variables=variables, + ) _MERGED_DOMAINS_CACHE[cache_key] = merged return merged diff --git a/utils/cleanup/nginx_vhosts.py b/utils/cleanup/nginx_vhosts.py index fa787e21e9..8a454ff019 100644 --- a/utils/cleanup/nginx_vhosts.py +++ b/utils/cleanup/nginx_vhosts.py @@ -31,6 +31,7 @@ from typing import TYPE_CHECKING from utils.domains.application_domain_index import iter_app_domains from utils.domains.default_primary import default_domain_primary from utils.domains.list import ROLES_DIR, build_applications_from_roles +from utils.networks.reachability import TOR, sibling_domain from utils.roles.entity.apps import apps_for_entity from utils.tor_onion import identity_hs_dir @@ -69,17 +70,6 @@ def _read_node_onion(base_dir: Path) -> str: return "" -def _swap_to_onion(domain: str, primary: str, node_onion: str) -> str | None: - """Dual-stack: the onion vhost of a clearnet domain, with the primary - suffix swapped for the node onion. None when not under the primary.""" - if domain == primary: - return node_onion - suffix = "." + primary - if domain.endswith(suffix): - return domain[: -len(primary)] + node_onion - return None - - def iter_vhost_files_for_entity( entity: str, *, @@ -109,9 +99,7 @@ def iter_vhost_files_for_entity( domain_variants = [domain] if not domain.startswith("www."): domain_variants.append(f"www.{domain}") - if node_onion and ( - onion := _swap_to_onion(domain, domain_primary, node_onion) - ): + if onion := sibling_domain(domain, TOR, domain_primary, node_onion): domain_variants.append(onion) if not onion.startswith("www."): domain_variants.append(f"www.{onion}") diff --git a/utils/networks/reachability.py b/utils/networks/reachability.py new file mode 100644 index 0000000000..5f687550ba --- /dev/null +++ b/utils/networks/reachability.py @@ -0,0 +1,252 @@ +"""Networks an application is served on, and the registry that defines them. + +A node runs in one network mode (``clearnet``, ``tor`` or ``multi``) and a +role narrows it through ``reachability`` in its ``meta/networks.yml``. Every +other module asks this one which network a domain belongs to instead of +testing a suffix of its own. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass +from typing import Any + + +@dataclass(frozen=True) +class Network: + """One network a vhost can be served on. + + Args: + name: id used in ``reachability.modes`` and in ``NETWORK_MODE``. + label: suffix of the ``_