diff --git a/plugins/lookup/tor_ports.py b/plugins/lookup/tor_ports.py index ec24f33741..68f2bd9413 100644 --- a/plugins/lookup/tor_ports.py +++ b/plugins/lookup/tor_ports.py @@ -1,19 +1,18 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any - -if TYPE_CHECKING: - from pathlib import Path +from typing import Any from ansible.errors import AnsibleError from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase -from utils.cache.base import _resolve_roles_dir -from utils.cache.yaml import load_yaml_any -from utils.roles.mapping import ROLE_FILE_META_SERVICES +UDP_ONLY_CATEGORIES = frozenset({"relay", "media", "stun_turn", "stun_turn_tls"}) +"""Categories a hidden service cannot carry. -_UDP_ONLY_CATEGORIES = frozenset({"relay", "media"}) +``relay`` and ``media`` are UDP. ``stun_turn`` and its TLS variant do speak TCP, +but the allocation they hand out is a UDP relay address the onion client can +never receive on, so forwarding the signalling port buys nothing. +""" def _as_bool(value: object) -> bool: @@ -24,6 +23,10 @@ def _as_bool(value: object) -> bool: return bool(value) +def _mapping(value: object) -> dict[str, Any]: + return value if isinstance(value, dict) else {} + + def _collect_local_tcp_ports(port_categories: Any, into: set[int]) -> None: """Add single-int TCP ports of the loopback-published ``ports.local`` group only. An exposed service publishes just its local plaintext port to @@ -36,37 +39,57 @@ def _collect_local_tcp_ports(port_categories: Any, into: set[int]) -> None: if not isinstance(local, dict): return for category, value in local.items(): - if category in _UDP_ONLY_CATEGORIES: + if category in UDP_ONLY_CATEGORIES: continue if isinstance(value, int): into.add(value) -def collect_public_ports( +def collect_onion_ports( + applications: dict[str, Any], deployed_roles: list[str], - roles_dir: Path, ) -> list[int]: - """Single-int TCP ``ports.public`` entries of the deployed roles, sorted.""" + """Single-int TCP ports a deployed role asks for by name under ``ports.onion``. + + ``ports.onion`` is a category-keyed map of booleans alongside ``internal`` / + ``local`` / ``public``: it names which of a service's already-declared ports + should answer on the node onion, and nothing else. The port number comes + from ``ports.local`` when that category is declared there and from + ``ports.public`` otherwise, which is the precedence ``container_ports`` + publishes by, so the forward always targets the port the service is actually + reachable on. + + Naming the category is what makes this safe. Sweeping ``ports.public`` + wholesale forwards ports the deployment never publishes -- ldaps 636 is + declared next to ``network.public: false``, and Mailu's implicit-TLS ports + are dropped from the publish list whenever TLS is off, which an onion + deployment always is. + """ ports: set[int] = set() - for role in deployed_roles: - services_yml = roles_dir / role / ROLE_FILE_META_SERVICES - if not services_yml.is_file(): + deployed = set(deployed_roles) + if not isinstance(applications, dict): + return [] + for app_id, cfg in applications.items(): + if app_id not in deployed: continue - data = load_yaml_any(str(services_yml), default_if_missing={}) - if not isinstance(data, dict): + services = (cfg or {}).get("services") if isinstance(cfg, dict) else None + if not isinstance(services, dict): continue - tor = data.get("tor") - if not (isinstance(tor, dict) and _as_bool(tor.get("enabled"))): - continue - for entity in data.values(): + for entity in services.values(): if not isinstance(entity, dict): continue - public = (entity.get("ports") or {}).get("public") - if not isinstance(public, dict): + declared = entity.get("ports") + if not isinstance(declared, dict): continue - for category, value in public.items(): - if category in _UDP_ONLY_CATEGORIES: + wanted = declared.get("onion") + if not isinstance(wanted, dict): + continue + local = _mapping(declared.get("local")) + public = _mapping(declared.get("public")) + for category, flag in wanted.items(): + if category in UDP_ONLY_CATEGORIES or not _as_bool(flag): continue + value = local.get(category, public.get(category)) if isinstance(value, int): ports.add(value) return sorted(ports) @@ -111,16 +134,18 @@ class LookupModule(LookupBase): Returns the HiddenServicePort mappings for the roles in the current deploy (``group_names``): a list of ``{'onion_port': , 'target': - '127.0.0.1:'}`` dicts, sorted by port. Two sources are unioned: + '127.0.0.1:'}`` dicts, sorted by port. Two opt-ins are unioned: - * every ``ports.public`` TCP port of tor-enabled roles, and - * every port of a service that opts in with ``exposed: true`` (resolved - against the variant-merged applications view, so per-variant). + * every port a service names under ``ports.onion`` in meta/services.yml, + and + * every port of a service that opts in with ``exposed: true``. - Public/exposed ports bind the host interface, so the loopback target reaches - them from svc-net-tor's host-network container. Consumed by - ``TOR_ONION_EXTRA_PORTS`` (group_vars/all/19_tor.yml) and rendered as - ``HiddenServicePort`` lines in svc-net-tor's torrc. + Both are read from the variant-merged applications view, so a variant that + drops the opt-in drops the forward with it. The published port binds the + host interface, so the loopback target reaches it from svc-net-tor's + host-network container. Consumed by ``TOR_ONION_EXTRA_PORTS`` + (group_vars/all/19_tor.yml) and rendered as ``HiddenServicePort`` lines in + svc-net-tor's torrc. """ def run( @@ -138,17 +163,15 @@ class LookupModule(LookupBase): group_names = [] deployed = [str(g) for g in group_names] - roles_dir = _resolve_roles_dir(roles_dir=kwargs.get("roles_dir")) - ports = set(collect_public_ports(deployed, roles_dir)) - try: applications = lookup_loader.get( "applications", loader=getattr(self, "_loader", None), templar=getattr(self, "_templar", None), ).run([], variables=variables, roles_dir=kwargs.get("roles_dir"))[0] - except Exception: # noqa: BLE001 no merged view -> exposed ports simply unavailable + except Exception: # noqa: BLE001 no merged view -> no ports to forward applications = {} + ports = set(collect_onion_ports(applications, deployed)) ports.update(collect_exposed_ports(applications, deployed)) return [ diff --git a/tests/unit/python/plugins/lookup/test_tor_ports.py b/tests/unit/python/plugins/lookup/test_tor_ports.py index 5be68ffe0a..67b7a5ad72 100644 --- a/tests/unit/python/plugins/lookup/test_tor_ports.py +++ b/tests/unit/python/plugins/lookup/test_tor_ports.py @@ -9,7 +9,7 @@ from ansible.errors import AnsibleError from plugins.lookup.tor_ports import ( LookupModule, collect_exposed_ports, - collect_public_ports, + collect_onion_ports, ) from utils.cache import _reset_cache_for_tests from utils.cache.yaml import dump_yaml_str @@ -33,7 +33,15 @@ class TestTorPortsLookup(unittest.TestCase): _write_services( self.roles_dir, "web-app-gitea", - {"gitea": {"ports": {"public": {"ssh": 2201}, "local": {"http": 8002}}}}, + { + "gitea": { + "ports": { + "public": {"ssh": 2201}, + "local": {"http": 8002}, + "onion": {"ssh": True}, + } + } + }, ) _write_services( self.roles_dir, @@ -68,40 +76,159 @@ class TestTorPortsLookup(unittest.TestCase): _reset_cache_for_tests() self._tmpdir.cleanup() - def test_collects_public_single_ints_sorted(self) -> None: - ports = collect_public_ports( - ["web-app-gitea", "svc-db-openldap"], self.roles_dir + @staticmethod + def _apps(**roles: dict) -> dict: + """The variant-merged applications view for the given roles. + + Every entity keeps its own ``ports``; the top-level ``tor:`` block of + ``meta/services.yml`` merges in as one more entity alongside them. + """ + return {role: {"services": dict(entities)} for role, entities in roles.items()} + + def test_only_named_categories_are_forwarded_sorted(self) -> None: + apps = self._apps( + **{ + "web-app-gitea": { + "gitea": { + "ports": {"public": {"ssh": 2201}, "onion": {"ssh": True}} + } + }, + "web-app-mailu": { + "mailu": { + "ports": { + "public": {"smtp": 25, "smtps": 465, "imap": 143}, + "onion": {"smtp": True}, + } + } + }, + } ) - self.assertEqual(ports, [636, 2201]) - def test_relay_ranges_excluded(self) -> None: - ports = collect_public_ports(["web-svc-coturn"], self.roles_dir) - self.assertEqual(ports, [3481, 5351]) + ports = collect_onion_ports(apps, ["web-app-gitea", "web-app-mailu"]) - def test_media_category_excluded(self) -> None: - _write_services( - self.roles_dir, - "web-app-jitsi", - {"jitsi": {"ports": {"public": {"media": 10000}, "local": {"http": 8084}}}}, + self.assertEqual(ports, [25, 2201]) + + def test_local_wins_over_public_for_the_same_category(self) -> None: + """``container_ports`` publishes the local port when the category has + one, so the forward must target that and not the public alias.""" + apps = self._apps( + **{ + "web-app-x": { + "x": { + "ports": { + "local": {"http": 8080}, + "public": {"http": 80}, + "onion": {"http": True}, + } + } + } + } ) - self.assertEqual(collect_public_ports(["web-app-jitsi"], self.roles_dir), []) - def test_roles_without_public_ports_yield_nothing(self) -> None: - self.assertEqual(collect_public_ports(["web-app-hugo"], self.roles_dir), []) + self.assertEqual(collect_onion_ports(apps, ["web-app-x"]), [8080]) - def test_tor_disabled_role_excluded(self) -> None: - _write_services( - self.roles_dir, - "web-app-optout", - { - "optout": {"ports": {"public": {"ssh": 2299}}}, - "tor": {"enabled": False}, - }, + def test_a_falsy_or_unrendered_flag_forwards_nothing(self) -> None: + """The input must be the rendered view: template text left in the flag + is not quietly read as enabled.""" + apps = self._apps( + **{ + "web-app-a": { + "a": {"ports": {"public": {"ssh": 22}, "onion": {"ssh": False}}} + }, + "web-app-b": { + "b": { + "ports": { + "public": {"ssh": 23}, + "onion": {"ssh": "{{ 'svc-net-tor' in group_names }}"}, + } + } + }, + } ) - self.assertEqual(collect_public_ports(["web-app-optout"], self.roles_dir), []) - def test_unknown_role_ignored(self) -> None: - self.assertEqual(collect_public_ports(["web-app-nope"], self.roles_dir), []) + self.assertEqual(collect_onion_ports(apps, ["web-app-a", "web-app-b"]), []) + + def test_udp_only_categories_are_never_forwarded(self) -> None: + apps = self._apps( + **{ + "web-svc-coturn": { + "coturn": { + "ports": { + "public": { + "media": 10000, + "stun_turn": 3481, + "stun_turn_tls": 5351, + "ssh": 2299, + "relay": {"start": 20000, "end": 39999}, + }, + "onion": { + "media": True, + "relay": True, + "stun_turn": True, + "stun_turn_tls": True, + "ssh": True, + }, + } + } + } + } + ) + + self.assertEqual(collect_onion_ports(apps, ["web-svc-coturn"]), [2299]) + + def test_a_category_with_no_declared_port_is_skipped(self) -> None: + apps = self._apps( + **{ + "web-app-x": { + "x": {"ports": {"public": {"ssh": 2201}, "onion": {"typo": True}}} + } + } + ) + + self.assertEqual(collect_onion_ports(apps, ["web-app-x"]), []) + + def test_a_role_without_an_onion_block_forwards_nothing(self) -> None: + apps = self._apps( + **{"web-app-hugo": {"hugo": {"ports": {"local": {"http": 8008}}}}} + ) + + self.assertEqual(collect_onion_ports(apps, ["web-app-hugo"]), []) + + def test_the_port_flag_is_the_gate_not_the_tor_flag(self) -> None: + """``services.tor.enabled`` is the dependency edge onto svc-net-tor, not + the port forward; ``ports.onion`` alone decides what gets a + HiddenServicePort.""" + apps = self._apps( + **{ + "web-app-gitea": { + "tor": {"enabled": False}, + "gitea": { + "ports": {"public": {"ssh": 2201}, "onion": {"ssh": True}} + }, + } + } + ) + + self.assertEqual(collect_onion_ports(apps, ["web-app-gitea"]), [2201]) + + def test_role_outside_the_deploy_is_ignored(self) -> None: + apps = self._apps( + **{ + "web-app-gitea": { + "gitea": { + "ports": {"public": {"ssh": 2201}, "onion": {"ssh": True}} + } + } + } + ) + + self.assertEqual(collect_onion_ports(apps, ["web-app-nope"]), []) + + def test_collect_onion_ports_ignores_non_mappings(self) -> None: + self.assertEqual(collect_onion_ports({}, ["a"]), []) + self.assertEqual(collect_onion_ports(None, ["a"]), []) + apps = {"a": {"services": {"s": {"ports": {"onion": True}}}}} + self.assertEqual(collect_onion_ports(apps, ["a"]), []) def test_collect_exposed_ports_gated_and_deployed(self) -> None: apps = { @@ -151,6 +278,14 @@ class TestTorPortsLookup(unittest.TestCase): )[0] self.assertEqual(result, [{"onion_port": 2201, "target": "127.0.0.1:2201"}]) + def test_run_forwards_nothing_without_an_onion_opt_in(self) -> None: + result = self.lookup.run( + [], + variables={"group_names": ["svc-db-openldap", "web-svc-coturn"]}, + roles_dir=str(self.roles_dir), + )[0] + self.assertEqual(result, []) + def test_empty_group_names(self) -> None: result = self.lookup.run([], variables={}, roles_dir=str(self.roles_dir))[0] self.assertEqual(result, [])