diff --git a/group_vars/all/18_swarm.yml b/group_vars/all/18_swarm.yml index 80b9d85d6b..8b41a6f57d 100644 --- a/group_vars/all/18_swarm.yml +++ b/group_vars/all/18_swarm.yml @@ -20,6 +20,10 @@ STACK_HOST: >- swarm_stack_fatal_grace: 180 +SWARM_INGRESS_GUARDED: "{{ swarm_ingress_endpoints.stdout_lines | swarm_ingress_published | swarm_ingress_guarded(lookup('applications') | swarm_public_ports) }}" + +SWARM_INGRESS_PEERS: "{{ swarm_ingress_nodes.stdout_lines | swarm_node_addresses }}" + swarm: manager: advertise_addr: >- diff --git a/plugins/filter/swarm_ingress_guard.py b/plugins/filter/swarm_ingress_guard.py new file mode 100644 index 0000000000..3786701b34 --- /dev/null +++ b/plugins/filter/swarm_ingress_guard.py @@ -0,0 +1,141 @@ +"""Ports the swarm ingress publishes on every node that no application declares public.""" + +from __future__ import annotations + +import ipaddress +import json +from collections.abc import Iterable, Mapping +from typing import Any + +from ansible.errors import AnsibleFilterError + +_PROTOCOLS = ("tcp", "udp") + + +def swarm_ingress_published(inspect_lines: Iterable[str]) -> list[dict[str, Any]]: + """Return every port the routing mesh publishes, one entry per protocol and port. + + Args: + inspect_lines: one ``docker service inspect --format '{{json .Endpoint.Ports}}'`` + document per service; ``null`` for a service that publishes nothing. + + Returns: + ``{"protocol": "tcp"|"udp", "port": int}`` for each ``ingress`` entry, + sorted and without duplicates; host-mode entries are left out. + + Raises: + AnsibleFilterError: a line is not JSON, or an entry names a protocol + other than tcp or udp. + """ + seen: set[tuple[str, int]] = set() + for line in inspect_lines: + text = str(line).strip() + if not text: + continue + try: + entries = json.loads(text) + except ValueError as exc: + raise AnsibleFilterError( + f"swarm_ingress_published: not JSON: {text!r}" + ) from exc + for entry in entries or []: + if entry.get("PublishMode") != "ingress": + continue + protocol = str(entry.get("Protocol", "")).lower() + if protocol not in _PROTOCOLS: + raise AnsibleFilterError( + f"swarm_ingress_published: unexpected protocol in {entry!r}" + ) + seen.add((protocol, int(entry["PublishedPort"]))) + return [{"protocol": protocol, "port": port} for protocol, port in sorted(seen)] + + +def _expand(value: Any) -> range: + if isinstance(value, Mapping): + return range(int(value["start"]), int(value["end"]) + 1) + return range(int(value), int(value) + 1) + + +def swarm_public_ports(applications: Mapping[str, Any]) -> list[int]: + """Return every port any application declares under ``services.*.ports.public``. + + Args: + applications: the merged ``lookup('applications')`` mapping. + + Returns: + The declared public ports, ``{start, end}`` ranges expanded, sorted and + without duplicates. + """ + ports: set[int] = set() + for application in applications.values(): + services = (application or {}).get("services") or {} + for service in services.values(): + public = (((service or {}).get("ports") or {}).get("public")) or {} + for value in public.values(): + if value in (None, ""): + continue + ports.update(_expand(value)) + return sorted(ports) + + +def swarm_ingress_guarded( + published: Iterable[Mapping[str, Any]], public: Iterable[int] +) -> list[dict[str, Any]]: + """Drop the ports that are public by declaration from the published ones. + + Args: + published: the output of ``swarm_ingress_published``. + public: the output of ``swarm_public_ports``. + + Returns: + The published entries whose port no application declares public. + """ + allowed = set(public) + return [dict(entry) for entry in published if int(entry["port"]) not in allowed] + + +def swarm_node_addresses(inspect_lines: Iterable[str]) -> dict[str, list[str]]: + """Return the addresses the swarm nodes reach each other from, split by family. + + Args: + inspect_lines: one ``docker node inspect --format '{{.Status.Addr}}'`` + line per node. + + Returns: + ``{"ipv4": [...], "ipv6": [...]}``, sorted and without duplicates; the + unspecified address a node may report is left out. + + Raises: + AnsibleFilterError: a line is not an IP address. + """ + families: dict[str, set[ipaddress.IPv4Address | ipaddress.IPv6Address]] = { + "ipv4": set(), + "ipv6": set(), + } + for line in inspect_lines: + text = str(line).strip() + if not text: + continue + try: + address = ipaddress.ip_address(text) + except ValueError as exc: + raise AnsibleFilterError( + f"swarm_node_addresses: not an IP address: {text!r}" + ) from exc + if address.is_unspecified: + continue + families[f"ipv{address.version}"].add(address) + return { + family: [str(address) for address in sorted(addresses)] + for family, addresses in families.items() + } + + +class FilterModule: + def filters(self) -> dict[str, Any]: + return { + "swarm_ingress_published": swarm_ingress_published, + "swarm_public_ports": swarm_public_ports, + "swarm_ingress_guarded": swarm_ingress_guarded, + "swarm_node_addresses": swarm_node_addresses, + } diff --git a/roles/svc-ai-ollama/meta/services.yml b/roles/svc-ai-ollama/meta/services.yml index b5c56f4140..dc7c55f338 100644 --- a/roles/svc-ai-ollama/meta/services.yml +++ b/roles/svc-ai-ollama/meta/services.yml @@ -13,7 +13,7 @@ ollama: backup: no_stop_required: true image: ollama/ollama - version: 0.40.8 + version: 0.40.9 name: ollama min_storage: 3473MB cpus: "4.0" diff --git a/roles/svc-opt-swapfile/meta/services.yml b/roles/svc-opt-swapfile/meta/services.yml index fb77736601..8cc1dcd7c1 100644 --- a/roles/svc-opt-swapfile/meta/services.yml +++ b/roles/svc-opt-swapfile/meta/services.yml @@ -4,7 +4,7 @@ swapfile: host: enabled: true repository: https://github.com/kevinveenbirkenbach/swap-forge.git - ref: v1.0.0 + ref: v1.0.1 swapfile_size: "{{ ansible_facts['memtotal_mb'] | int }}M" lifecycle: beta min_storage: "50MB" diff --git a/roles/svc-swarm-node/README.md b/roles/svc-swarm-node/README.md index 86923e7cec..6c342481c3 100644 --- a/roles/svc-swarm-node/README.md +++ b/roles/svc-swarm-node/README.md @@ -49,6 +49,11 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( inventory are applied to the joining node. - **Mode-selection trigger:** Membership in `svc-swarm-node` resolves `DEPLOYMENT_MODE = swarm` for every web-app role on that host. +- **Ingress guard:** An nftables table drops packets from outside the cluster + to every routing-mesh port no application declares under `ports.public`. + Loopback, the Docker bridges and the swarm nodes' own addresses stay + admitted. The table is loaded before a node joins and reloaded on every node + after the join and after each stack deploy. ## Quick Setup diff --git a/roles/svc-swarm-node/tasks/00_core.yml b/roles/svc-swarm-node/tasks/00_core.yml index a132a977de..4a878f11d5 100644 --- a/roles/svc-swarm-node/tasks/00_core.yml +++ b/roles/svc-swarm-node/tasks/00_core.yml @@ -4,8 +4,8 @@ - name: "๐Ÿ Swarm-only node setup (cluster bootstrap + shared CA anchor)" when: DEPLOYMENT_MODE == 'swarm' block: - - name: "๐Ÿฅพ Bootstrap docker swarm cluster" - ansible.builtin.include_tasks: 00_core/bootstrap_cluster.yml + - name: "๐Ÿฅพ Join the swarm behind the ingress guard" + ansible.builtin.include_tasks: 00_core/join.yml - name: "โœ… Ensure shared Root CA on every swarm node (manager mints, workers fetch)" ansible.builtin.include_role: diff --git a/roles/svc-swarm-node/tasks/00_core/ingress_guard.yml b/roles/svc-swarm-node/tasks/00_core/ingress_guard.yml new file mode 100644 index 0000000000..7daf07e429 --- /dev/null +++ b/roles/svc-swarm-node/tasks/00_core/ingress_guard.yml @@ -0,0 +1,15 @@ +--- +- name: "๐Ÿ”Ž Swarm ingress guard | Read the published ports before this node joins" + ansible.builtin.include_tasks: + file: "{{ lookup('path_absolute', 'roles/svc-swarm-node/tasks/utils/ingress_guard/read.yml') }}" + apply: + run_once: true + delegate_to: "{{ STACK_HOST }}" + +- name: "๐Ÿ›ก๏ธ Swarm ingress guard | Bound the non-public published ports" + ansible.builtin.include_role: + name: svc-net-firewall + vars: + FIREWALL_FRAGMENT_ROLE: svc-swarm-node + SWARM_INGRESS_GUARDED_PORTS: "{{ SWARM_INGRESS_GUARDED }}" + SWARM_INGRESS_PEER_ADDRESSES: "{{ SWARM_INGRESS_PEERS }}" diff --git a/roles/svc-swarm-node/tasks/00_core/join.yml b/roles/svc-swarm-node/tasks/00_core/join.yml new file mode 100644 index 0000000000..3133459549 --- /dev/null +++ b/roles/svc-swarm-node/tasks/00_core/join.yml @@ -0,0 +1,9 @@ +--- +- name: "๐Ÿ›ก๏ธ Bound the ports the routing mesh publishes before the node joins" + ansible.builtin.include_tasks: 00_core/ingress_guard.yml + +- name: "๐Ÿฅพ Bootstrap docker swarm cluster" + ansible.builtin.include_tasks: 00_core/bootstrap_cluster.yml + +- name: "๐Ÿ›ก๏ธ Admit the joined nodes to the bound on every node" + ansible.builtin.include_tasks: utils/ingress_guard/refresh.yml diff --git a/roles/svc-swarm-node/tasks/utils/ingress_guard/read.yml b/roles/svc-swarm-node/tasks/utils/ingress_guard/read.yml new file mode 100644 index 0000000000..052e41d04e --- /dev/null +++ b/roles/svc-swarm-node/tasks/utils/ingress_guard/read.yml @@ -0,0 +1,22 @@ +--- +- name: "๐Ÿ”Ž Swarm ingress guard | Read the ports the routing mesh publishes" + ansible.builtin.shell: | + set -euo pipefail + if [ "$(container info --format '{{ '{{.Swarm.ControlAvailable}}' }}')" = "true" ]; then + container service ls -q | xargs -r container service inspect --format '{{ '{{json .Endpoint.Ports}}' }}' + fi + args: + executable: /bin/bash + register: swarm_ingress_endpoints + changed_when: false + +- name: "๐Ÿ”Ž Swarm ingress guard | Read the addresses the swarm nodes reach each other from" + ansible.builtin.shell: | + set -euo pipefail + if [ "$(container info --format '{{ '{{.Swarm.ControlAvailable}}' }}')" = "true" ]; then + container node ls -q | xargs -r container node inspect --format '{{ '{{.Status.Addr}}' }}' + fi + args: + executable: /bin/bash + register: swarm_ingress_nodes + changed_when: false diff --git a/roles/svc-swarm-node/tasks/utils/ingress_guard/refresh.yml b/roles/svc-swarm-node/tasks/utils/ingress_guard/refresh.yml new file mode 100644 index 0000000000..9f92eb14e9 --- /dev/null +++ b/roles/svc-swarm-node/tasks/utils/ingress_guard/refresh.yml @@ -0,0 +1,30 @@ +--- +- name: "๐Ÿ”Ž Swarm ingress guard | Read the published ports and the swarm nodes" + ansible.builtin.include_tasks: + file: "{{ lookup('path_absolute', 'roles/svc-swarm-node/tasks/utils/ingress_guard/read.yml') }}" + apply: + run_once: true + delegate_to: "{{ STACK_HOST }}" + +- name: "๐Ÿ“„ Swarm ingress guard | Load the fragment naming of svc-net-firewall" + ansible.builtin.include_vars: + file: "{{ lookup('path_absolute', 'roles/svc-net-firewall/vars/main.yml') }}" + name: swarm_ingress_firewall + +- name: "๐Ÿ›ก๏ธ Swarm ingress guard | Reload the bound on every swarm node" + ansible.builtin.include_tasks: + file: "{{ lookup('path_absolute', 'roles/svc-net-firewall/tasks/02_fragment.yml') }}" + apply: + delegate_to: "{{ swarm_ingress_guard_node }}" + vars: + FIREWALL_FRAGMENT_ROLE: svc-swarm-node + FIREWALL_FRAGMENT_DIR: "{{ swarm_ingress_firewall.FIREWALL_FRAGMENT_DIR }}" + FIREWALL_FRAGMENT_SRC: "{{ swarm_ingress_firewall.FIREWALL_FRAGMENT_SRC }}" + FIREWALL_FRAGMENT_FILE: "{{ swarm_ingress_firewall.FIREWALL_FRAGMENT_FILE }}" + FIREWALL_TABLE: "{{ swarm_ingress_firewall.FIREWALL_TABLE }}" + SWARM_INGRESS_GUARDED_PORTS: "{{ SWARM_INGRESS_GUARDED }}" + SWARM_INGRESS_PEER_ADDRESSES: "{{ SWARM_INGRESS_PEERS }}" + loop: "{{ groups['svc-swarm-node'] }}" + loop_control: + loop_var: swarm_ingress_guard_node + run_once: true diff --git a/roles/svc-swarm-node/templates/nftables.conf.j2 b/roles/svc-swarm-node/templates/nftables.conf.j2 new file mode 100644 index 0000000000..1202007ea2 --- /dev/null +++ b/roles/svc-swarm-node/templates/nftables.conf.j2 @@ -0,0 +1,32 @@ +table inet {{ FIREWALL_TABLE }} +delete table inet {{ FIREWALL_TABLE }} +table inet {{ FIREWALL_TABLE }} { +{% for protocol in ['tcp', 'udp'] %} +{% set _ports = SWARM_INGRESS_GUARDED_PORTS | selectattr('protocol', 'equalto', protocol) | map(attribute='port') | list %} + set guarded_{{ protocol }} { + type inet_service +{% if _ports | length > 0 %} + elements = { {{ _ports | join(', ') }} } +{% endif %} + } + +{% endfor %} +{% for family in ['ipv4', 'ipv6'] %} +{% set _addresses = SWARM_INGRESS_PEER_ADDRESSES[family] %} + set peers_{{ family }} { + type {{ family }}_addr +{% if _addresses | length > 0 %} + elements = { {{ _addresses | join(', ') }} } +{% endif %} + } + +{% endfor %} + chain prerouting { + type filter hook prerouting priority -150; policy accept; +{% for family, match in [('ipv4', 'ip'), ('ipv6', 'ip6')] %} +{% for protocol in ['tcp', 'udp'] %} + iifname != { "lo", "docker0", "docker_gwbridge" } iifname != "br-*" {{ match }} saddr != @peers_{{ family }} fib daddr type local {{ protocol }} dport @guarded_{{ protocol }} drop +{% endfor %} +{% endfor %} + } +} diff --git a/roles/sys-svc-compose/handlers/compose.yml b/roles/sys-svc-compose/handlers/compose.yml index 97aa1f7421..eb9f6bce0d 100644 --- a/roles/sys-svc-compose/handlers/compose.yml +++ b/roles/sys-svc-compose/handlers/compose.yml @@ -115,3 +115,11 @@ listen: - compose-up - container-recreate + +- name: "๐Ÿงน Clear the pending compose up marker" + ansible.builtin.file: + path: "{{ COMPOSE_UP_PENDING_MARKER }}" + state: absent + listen: + - compose-up + - container-recreate diff --git a/roles/sys-svc-compose/handlers/swarm.yml b/roles/sys-svc-compose/handlers/swarm.yml index 20e8e3f08e..02d8cdd6fc 100644 --- a/roles/sys-svc-compose/handlers/swarm.yml +++ b/roles/sys-svc-compose/handlers/swarm.yml @@ -184,6 +184,12 @@ run_once: true delegate_to: "{{ STACK_HOST }}" +- name: "๐Ÿ›ก๏ธ swarm: bound the ports the routing mesh now publishes on every node" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/svc-swarm-node/tasks/utils/ingress_guard/refresh.yml') }}" + listen: + - compose-up + - swarm-deploy + - name: "๐Ÿ”„ swarm: force task recreation so in-container state is reloaded" ansible.builtin.shell: | set -euo pipefail diff --git a/roles/sys-svc-compose/tasks/04_files.yml b/roles/sys-svc-compose/tasks/04_files.yml index 5dba92ee83..fc6b9a1af8 100644 --- a/roles/sys-svc-compose/tasks/04_files.yml +++ b/roles/sys-svc-compose/tasks/04_files.yml @@ -22,6 +22,7 @@ notify: - compose-build - compose-up + register: dockerfile_template when: - dockerfile_src | default('') | length > 0 @@ -53,6 +54,7 @@ - "{{ application_id | abs_role_path_by_application_id }}/templates/compose.override.yml.j2" - "{{ application_id | abs_role_path_by_application_id }}/files/compose.override.yml" skip: true + register: compose_override_template - name: "๐Ÿ“ Create (optional) '{{ lookup('container', application_id, 'files.compose') }}'" stack_host_template: @@ -66,3 +68,13 @@ skip: true register: docker_compose_template notify: compose-up + +- name: "๐Ÿ“Œ Mark compose up pending for '{{ application_id }}' until it succeeds" + stack_host_copy: + content: "" + dest: "{{ COMPOSE_UP_PENDING_MARKER }}" + mode: "0640" + register: compose_up_marker + when: + - compose_mode == 'compose' + - dockerfile_template.changed or env_template.changed or compose_override_template.changed or docker_compose_template.changed diff --git a/roles/sys-svc-compose/tasks/utils/up.yml b/roles/sys-svc-compose/tasks/utils/up.yml index 39f22a3507..414120dd62 100644 --- a/roles/sys-svc-compose/tasks/utils/up.yml +++ b/roles/sys-svc-compose/tasks/utils/up.yml @@ -23,6 +23,24 @@ - compose_mode == 'compose' notify: compose-up +- name: "๐Ÿ” Check for a compose up a failed run left pending" + ansible.builtin.stat: + path: "{{ COMPOSE_UP_PENDING_MARKER }}" + register: compose_up_pending + when: compose_mode == 'compose' + +- name: "๐Ÿ”” Resume the compose up a failed run left pending" + ansible.builtin.debug: + msg: "{{ COMPOSE_UP_PENDING_MARKER }} is still present, so the last compose up never completed" + changed_when: true + notify: + - compose-build + - compose-up + when: + - compose_mode == 'compose' + - compose_up_pending.stat.exists + - compose_up_marker is not changed + - name: "๐Ÿ”” Notify swarm deploy (under DEPLOYMENT_MODE == swarm)" ansible.builtin.debug: msg: "Triggering swarm stack deploy for {{ application_id }}" diff --git a/roles/sys-svc-compose/vars/main.yml b/roles/sys-svc-compose/vars/main.yml index 4fc0c7038d..1cbe8600bf 100644 --- a/roles/sys-svc-compose/vars/main.yml +++ b/roles/sys-svc-compose/vars/main.yml @@ -2,3 +2,4 @@ COMPOSE_DOWN_ALL_PACKAGE: "docodol" COMPOSE_DOWN_ALL_REPO: "{{ lookup('config', 'sys-svc-compose', 'services.svc-compose.repository') }}" COMPOSE_DOWN_ALL_REF: "{{ lookup('config', 'sys-svc-compose', 'services.svc-compose.ref') }}" +COMPOSE_UP_PENDING_MARKER: "{{ [lookup('container', application_id, 'directories.instance'), '.compose-up-pending'] | path_join }}" diff --git a/roles/web-app-gitea/meta/services.yml b/roles/web-app-gitea/meta/services.yml index 1e593dc630..9b3ac2f003 100644 --- a/roles/web-app-gitea/meta/services.yml +++ b/roles/web-app-gitea/meta/services.yml @@ -112,7 +112,7 @@ giteamcpupstream: enabled: "{{ lookup('config', 'web-app-gitea', 'mcp.enabled') | bool }}" shared: false image: docker.gitea.com/gitea-mcp-server - version: "1.10.0" + version: "1.11.0" update: type: registry_tags image: docker.gitea.com/gitea-mcp-server diff --git a/roles/web-app-matomo/meta/services.yml b/roles/web-app-matomo/meta/services.yml index a9956ce907..153d762ae8 100644 --- a/roles/web-app-matomo/meta/services.yml +++ b/roles/web-app-matomo/meta/services.yml @@ -32,7 +32,7 @@ matomo: enabled: true # nocheck: dynamic-flag shared: true image: matomo - version: "5.14.0" + version: "5.14.2" custom: true name: matomo min_storage: 404MB diff --git a/roles/web-app-n8n/meta/services.yml b/roles/web-app-n8n/meta/services.yml index 5f9f5a454e..90afb54a81 100644 --- a/roles/web-app-n8n/meta/services.yml +++ b/roles/web-app-n8n/meta/services.yml @@ -67,7 +67,7 @@ n8n: backup: no_stop_required: false image: docker.n8n.io/n8nio/n8n - version: "2.45.2" + version: "2.45.3" update: type: registry_tags image: docker.n8n.io/n8nio/n8n diff --git a/tests/unit/python/plugins/filter/test_swarm_ingress_guard.py b/tests/unit/python/plugins/filter/test_swarm_ingress_guard.py new file mode 100644 index 0000000000..f51f3cf3a9 --- /dev/null +++ b/tests/unit/python/plugins/filter/test_swarm_ingress_guard.py @@ -0,0 +1,129 @@ +import ipaddress +import unittest + +from ansible.errors import AnsibleFilterError + +from plugins.filter.swarm_ingress_guard import ( + FilterModule, + swarm_ingress_guarded, + swarm_ingress_published, + swarm_node_addresses, + swarm_public_ports, +) + + +class TestSwarmIngressPublished(unittest.TestCase): + def test_keeps_ingress_entries_only(self): + lines = [ + '[{"Protocol":"tcp","TargetPort":5432,"PublishedPort":5432,"PublishMode":"ingress"}]', + '[{"Protocol":"tcp","TargetPort":80,"PublishedPort":80,"PublishMode":"host"}]', + "null", + ( + '[{"Protocol":"udp","TargetPort":3478,"PublishedPort":3478,"PublishMode":"ingress"},' + '{"Protocol":"tcp","TargetPort":5000,"PublishedPort":30001,"PublishMode":"ingress"}]' + ), + ] + self.assertEqual( + swarm_ingress_published(lines), + [ + {"protocol": "tcp", "port": 5432}, + {"protocol": "tcp", "port": 30001}, + {"protocol": "udp", "port": 3478}, + ], + ) + + def test_a_port_two_services_publish_appears_once(self): + line = '[{"Protocol":"tcp","TargetPort":1,"PublishedPort":8080,"PublishMode":"ingress"}]' + self.assertEqual( + swarm_ingress_published([line, line]), + [{"protocol": "tcp", "port": 8080}], + ) + + def test_no_output_means_no_published_port(self): + self.assertEqual(swarm_ingress_published([]), []) + + def test_refuses_a_line_that_is_not_json(self): + with self.assertRaises(AnsibleFilterError): + swarm_ingress_published(["Error: no such service"]) + + def test_refuses_an_unknown_protocol(self): + line = '[{"Protocol":"sctp","TargetPort":1,"PublishedPort":9,"PublishMode":"ingress"}]' + with self.assertRaises(AnsibleFilterError): + swarm_ingress_published([line]) + + +class TestSwarmPublicPorts(unittest.TestCase): + def test_collects_single_ports_and_expands_ranges(self): + applications = { + "web-app-gitea": { + "services": {"gitea": {"ports": {"public": {"ssh": 2201}}}} + }, + "web-svc-coturn": { + "services": { + "coturn": { + "ports": { + "public": { + "stun_turn": 3478, + "relay": {"start": 49160, "end": 49162}, + } + } + } + } + }, + "web-app-moodle": { + "services": {"moodle": {"ports": {"local": {"http": 8033}}}} + }, + "svc-empty": {"services": None}, + } + self.assertEqual( + swarm_public_ports(applications), + [2201, 3478, 49160, 49161, 49162], + ) + + +class TestSwarmIngressGuarded(unittest.TestCase): + def test_drops_the_ports_declared_public(self): + published = [ + {"protocol": "tcp", "port": 2201}, + {"protocol": "tcp", "port": 5432}, + {"protocol": "udp", "port": 3478}, + {"protocol": "tcp", "port": 30001}, + ] + self.assertEqual( + swarm_ingress_guarded(published, [2201, 3478]), + [{"protocol": "tcp", "port": 5432}, {"protocol": "tcp", "port": 30001}], + ) + + +class TestSwarmNodeAddresses(unittest.TestCase): + def test_splits_by_family_and_drops_the_unspecified_address(self): + unspecified = str(ipaddress.IPv4Address(0)) + lines = ["10.0.0.7", unspecified, "fd00::2", "10.0.0.3", "", "10.0.0.7"] + self.assertEqual( + swarm_node_addresses(lines), + {"ipv4": ["10.0.0.3", "10.0.0.7"], "ipv6": ["fd00::2"]}, + ) + + def test_no_output_means_no_peer(self): + self.assertEqual(swarm_node_addresses([]), {"ipv4": [], "ipv6": []}) + + def test_refuses_a_line_that_is_not_an_address(self): + with self.assertRaises(AnsibleFilterError): + swarm_node_addresses(["Error: This node is not a swarm manager."]) + + +class TestFilterModule(unittest.TestCase): + def test_registers_the_four_filters(self): + self.assertEqual( + set(FilterModule().filters()), + { + "swarm_ingress_published", + "swarm_public_ports", + "swarm_ingress_guarded", + "swarm_node_addresses", + }, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/svc-net-firewall/test_fragments.py b/tests/unit/python/roles/svc-net-firewall/test_fragments.py index ecadb860ef..3f3a0aad6d 100644 --- a/tests/unit/python/roles/svc-net-firewall/test_fragments.py +++ b/tests/unit/python/roles/svc-net-firewall/test_fragments.py @@ -31,6 +31,10 @@ from pathlib import Path import jinja2 +from plugins.filter.swarm_ingress_guard import ( + swarm_ingress_published, + swarm_node_addresses, +) from utils.cache.files import iter_project_files, read_text from utils.cache.yaml import load_yaml_any from utils.roles.mapping import ROLE_FILE_VARS_MAIN @@ -79,6 +83,15 @@ COMMON = { "172.16.0.0/12", "192.168.0.0/16", ], + "SWARM_INGRESS_GUARDED_PORTS": swarm_ingress_published( + [ + ( + '[{"Protocol":"tcp","TargetPort":5432,"PublishedPort":5432,"PublishMode":"ingress"},' + '{"Protocol":"udp","TargetPort":3478,"PublishedPort":3478,"PublishMode":"ingress"}]' + ) + ] + ), + "SWARM_INGRESS_PEER_ADDRESSES": swarm_node_addresses(["10.0.0.2"]), } MODES = ("compose", "swarm")