diff --git a/Dockerfile b/Dockerfile index ab7e98093f..a2213d53d8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -56,6 +56,7 @@ RUN set -euo pipefail; \ /bin/bash "${INFINITO_SRC_DIR}/${INFINITO_DOCKER_CLI_INSTALL_SCRIPT:?}"; \ /bin/bash "${INFINITO_SRC_DIR}/${INFINITO_PACKAGE_INSTALL_SCRIPT:?}"; \ /bin/bash "${INFINITO_SRC_DIR}/${INFINITO_FILESYSTEM_INSTALL_SCRIPT:?}"; \ + /bin/bash "${INFINITO_SRC_DIR}/roles/update/files/shell/centos_mirror.sh"; \ /bin/bash "${INFINITO_SRC_DIR}/${INFINITO_INTERPRETERS_INSTALL_SCRIPT:?}" RUN set -euo pipefail; \ 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/library/database_query.py b/library/database_query.py index 5cf6971b15..30ec772d6b 100755 --- a/library/database_query.py +++ b/library/database_query.py @@ -109,7 +109,7 @@ _ENGINES: dict[str, dict[str, object]] = { "user_flag": "-U", "db_flag": "-d", "shared_flags": ["-v", "ON_ERROR_STOP=1"], - "rows_flags": ["-tA"], + "rows_flags": ["-qtA"], "row_separator": "|", "password_env": "PGPASSWORD", "string_quote": "'", 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-opt-ssd-hdd/files/python/script.py b/roles/svc-opt-ssd-hdd/files/python/script.py index ba59e5caa3..91a12bb98e 100644 --- a/roles/svc-opt-ssd-hdd/files/python/script.py +++ b/roles/svc-opt-ssd-hdd/files/python/script.py @@ -38,10 +38,34 @@ def start_containers(containers): run_command(f"container start {container_list}") +DATABASE_IMAGES = { + "elasticsearch", + "mariadb", + "memcached", + "mongo", + "mysql", + "openldap", + "opensearch", + "postgis", + "postgres", + "qdrant", + "rabbitmq", + "redis", + "typesense", + "valkey", +} + + def is_database(image): - databases = {"postgres", "mariadb", "redis", "memcached", "mongo"} - prefix = image.split(":")[0] - return prefix in databases + """Tell whether an image reference names a database engine. + + Args: + image: reference as the container's `.Config.Image` reports it, with + optional registry, namespace, tag and digest; a locally built + `_custom` image counts as its engine. + """ + name = image.rsplit("/", 1)[-1].split("@")[0].split(":")[0] + return name.removesuffix("_custom") in DATABASE_IMAGES def is_symbolic_link(file_path): 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/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/update/README.md b/roles/update/README.md index c05361eee9..17001c37cd 100644 --- a/roles/update/README.md +++ b/roles/update/README.md @@ -26,7 +26,7 @@ message when a host runs a distribution that this role does not yet cover. | `CentOS` | `centos.yml` | `ansible.builtin.dnf` | | anything else | `unsupported.yml` | `ansible.builtin.fail` | -`centos.yml` first runs [centos_mirror.sh](files/shell/centos_mirror.sh), which replaces every `metalink=` of the CentOS Stream repo files with a `baseurl=` on `mirror.stream.centos.org`, and then includes `fedora.yml`. The [Dockerfile](../../Dockerfile) runs the same script before its first `dnf` call, so the CentOS dev and swarm-node images resolve against the same source. +`centos.yml` first runs [centos_mirror.sh](files/shell/centos_mirror.sh), which replaces every `metalink=` of the CentOS Stream repo files with a `baseurl=` on `mirror.stream.centos.org` and every `metalink=` of the EPEL repo files with the file's own `baseurl` template on `dl.fedoraproject.org`, and then includes `fedora.yml`. The [Dockerfile](../../Dockerfile) runs the same script before its first `dnf` call, so the CentOS dev and swarm-node images resolve against the same source. ## Cosmos diff --git a/roles/update/files/shell/centos_mirror.sh b/roles/update/files/shell/centos_mirror.sh index d44cbc66aa..0c69851241 100755 --- a/roles/update/files/shell/centos_mirror.sh +++ b/roles/update/files/shell/centos_mirror.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Param: none. Rewrites the CentOS Stream repo files in /etc/yum.repos.d in place and prints the metalink repo of every section it pinned; prints nothing when there is nothing left to pin. +# Param: none. Rewrites the CentOS Stream and EPEL repo files in /etc/yum.repos.d in place and prints the metalink repo or EPEL file of everything it pinned; prints nothing when there is nothing left to pin, exits 1 on an EPEL file whose metalinks lack their baseurl template. set -euo pipefail master="https://mirror.stream.centos.org" @@ -36,3 +36,24 @@ done pin "centos-extras-sig-extras-common-[\$]stream" "SIGs/\$stream/extras/\$basearch/extras-common" pin "centos-extras-sig-extras-common-source-[\$]stream" "SIGs/\$stream/extras/source/extras-common" + +pin_epel() { + local file="$1" metalinks templates + metalinks="$(awk '/^metalink=https:\/\/mirrors\.fedoraproject\.org\// { n++ } END { print n + 0 }' "${file}")" + templates="$(awk '/^#baseurl=https:\/\/download\.example\/pub\/epel\// { n++ } END { print n + 0 }' "${file}")" + [[ "${metalinks}" -gt 0 ]] || return 0 + if [[ "${templates}" -ne "${metalinks}" ]]; then + echo "ERROR: ${file} has ${metalinks} Fedora metalinks but ${templates} download.example baseurl templates" >&2 + exit 1 + fi + sed -i -E \ + -e 's|^#baseurl=https://download\.example/pub/epel/|baseurl=https://dl.fedoraproject.org/pub/epel/|' \ + -e '/^metalink=https:\/\/mirrors\.fedoraproject\.org\//d' \ + "${file}" + echo "${file##*/}" +} + +for file in "${repo_dir}"/epel*.repo; do + [[ -f "${file}" ]] || continue + pin_epel "${file}" +done diff --git a/roles/update/tasks/centos.yml b/roles/update/tasks/centos.yml index 2908c2ddc5..f09165b328 100644 --- a/roles/update/tasks/centos.yml +++ b/roles/update/tasks/centos.yml @@ -1,5 +1,5 @@ --- -- name: "📌 update (dnf) | pin the CentOS Stream repos to mirror.stream.centos.org" +- name: "📌 update (dnf) | pin the CentOS Stream and EPEL repos to their master mirrors" become: true ansible.builtin.script: shell/centos_mirror.sh register: update_centos_pinned diff --git a/roles/web-app-erpnext/meta/services.yml b/roles/web-app-erpnext/meta/services.yml index d3d44d058f..58af583995 100644 --- a/roles/web-app-erpnext/meta/services.yml +++ b/roles/web-app-erpnext/meta/services.yml @@ -65,7 +65,7 @@ erpnext: enabled: true shared: true image: frappe/erpnext - version: "v16.52.0" + version: "v16.52.1" name: erpnext min_storage: 1017MB ports: diff --git a/roles/web-app-matrix/meta/services.yml b/roles/web-app-matrix/meta/services.yml index fa85923ccf..065d550cac 100644 --- a/roles/web-app-matrix/meta/services.yml +++ b/roles/web-app-matrix/meta/services.yml @@ -43,7 +43,7 @@ postgres: synapse: healthcheck: flavor: curl - version: v1.163.0 + version: v1.163.1 image: matrixdotorg/synapse name: matrix-synapse backup: diff --git a/roles/web-app-n8n/meta/services.yml b/roles/web-app-n8n/meta/services.yml index a5037d316e..c9c11adacd 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.1" + version: "2.45.2" update: type: registry_tags image: docker.n8n.io/n8nio/n8n diff --git a/roles/web-app-peertube/files/sql/check-application/defaults.sql b/roles/web-app-peertube/files/sql/check-application/defaults.sql new file mode 100644 index 0000000000..023a3dd811 --- /dev/null +++ b/roles/web-app-peertube/files/sql/check-application/defaults.sql @@ -0,0 +1,6 @@ +SELECT column_name +FROM information_schema.columns +WHERE table_schema = 'public' + AND table_name = 'application' + AND column_name IN ('nodeVersion', 'nodeABIVersion') + AND column_default IS NULL; diff --git a/roles/web-app-peertube/files/sql/check-application-table.sql b/roles/web-app-peertube/files/sql/check-application/table.sql similarity index 100% rename from roles/web-app-peertube/files/sql/check-application-table.sql rename to roles/web-app-peertube/files/sql/check-application/table.sql diff --git a/roles/web-app-peertube/tasks/02_fix-application-schema.yml b/roles/web-app-peertube/tasks/02_fix-application-schema.yml index 26d958c07d..785885b584 100644 --- a/roles/web-app-peertube/tasks/02_fix-application-schema.yml +++ b/roles/web-app-peertube/tasks/02_fix-application-schema.yml @@ -31,7 +31,7 @@ database_query: mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" config: "{{ lookup('database', application_id) }}" - query: "{{ lookup('file', role_path ~ '/files/sql/check-application-table.sql') }}" # nocheck: database-query-raw controller-read so the SQL travels to the remote swarm host that lacks the repo files + query: "{{ lookup('file', role_path ~ '/files/sql/check-application/table.sql') }}" # nocheck: database-query-raw controller-read so the SQL travels to the remote swarm host that lacks the repo files expect_rows: true register: _peertube_app_table_check retries: 60 @@ -42,12 +42,21 @@ and (_peertube_app_table_check.rows[0][0] | default('')) == 'application' changed_when: false +- name: "🔍 PEERTUBE | Find the bootstrap columns that still lack a default" + database_query: + mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + config: "{{ lookup('database', application_id) }}" + query: "{{ lookup('file', role_path ~ '/files/sql/check-application/defaults.sql') }}" # nocheck: database-query-raw controller-read so the SQL travels to the remote swarm host that lacks the repo files + expect_rows: true + register: _peertube_app_defaults_missing + changed_when: false + - name: "🔧 PEERTUBE | Back-fill column defaults so bootstrap INSERT keeps NOT NULL" database_query: mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" config: "{{ lookup('database', application_id) }}" query: "{{ lookup('file', role_path ~ '/files/sql/backfill-application-defaults.sql') }}" # nocheck: database-query-raw controller-read so the SQL travels to the remote swarm host that lacks the repo files - register: _peertube_app_defaults + when: _peertube_app_defaults_missing.rows | length > 0 notify: compose-up - name: "🔍 Resolve {{ application_id }} hosting node + container id" diff --git a/scripts/tests/deploy/swarm/utils/unmount/nfs_mounts.sh b/scripts/tests/deploy/swarm/utils/unmount/nfs_mounts.sh index 426d3d1502..c3a5e5d1bf 100755 --- a/scripts/tests/deploy/swarm/utils/unmount/nfs_mounts.sh +++ b/scripts/tests/deploy/swarm/utils/unmount/nfs_mounts.sh @@ -16,7 +16,7 @@ for container in "$@"; do docker inspect "${container}" >/dev/null 2>&1 || continue echo ">>> swarm-cleanup: detach NFS mounts inside ${container}" - if ! timeout "${NFS_CONTAINER_TIMEOUT}" docker exec -e NFS_UNMOUNT_TIMEOUT="${NFS_UNMOUNT_TIMEOUT}" "${container}" sh -s <<'SH'; then + if ! timeout "${NFS_CONTAINER_TIMEOUT}" docker exec -e NFS_UNMOUNT_TIMEOUT="${NFS_UNMOUNT_TIMEOUT}" "${container}" sh -s <<'SH' set -eu mounts="$( @@ -62,6 +62,7 @@ printf '%s\n' "${mounts}" | while IFS= read -r mount_point; do fi done SH + then echo "WARNING: could not inspect/unmount NFS mounts inside ${container} (gave up after ${NFS_CONTAINER_TIMEOUT})" >&2 fi done diff --git a/tests/unit/python/library/test_database_query.py b/tests/unit/python/library/test_database_query.py index 83ae8969d8..2f9d53e125 100644 --- a/tests/unit/python/library/test_database_query.py +++ b/tests/unit/python/library/test_database_query.py @@ -93,13 +93,13 @@ class BuildCmdPostgresTests(unittest.TestCase): self.assertIn("ON_ERROR_STOP=1", cmd) self.assertNotIn("s3cret", cmd) - def test_postgres_expect_rows_adds_tuples_only_flag(self): + def test_postgres_expect_rows_adds_quiet_tuples_only_flag(self): cmd, _ = _DB_MOD._build_cmd(_BASE_CONFIG, expect_rows=True) - self.assertIn("-tA", cmd) + self.assertIn("-qtA", cmd) def test_postgres_no_rows_omits_tuples_only_flag(self): cmd, _ = _DB_MOD._build_cmd(_BASE_CONFIG, expect_rows=False) - self.assertNotIn("-tA", cmd) + self.assertNotIn("-qtA", cmd) class BuildCmdMariadbTests(unittest.TestCase): 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") diff --git a/tests/unit/python/roles/svc-opt-ssd-hdd/test_storage_optimizer.py b/tests/unit/python/roles/svc-opt-ssd-hdd/test_storage_optimizer.py index d7ea8b8b90..e9c72826dd 100644 --- a/tests/unit/python/roles/svc-opt-ssd-hdd/test_storage_optimizer.py +++ b/tests/unit/python/roles/svc-opt-ssd-hdd/test_storage_optimizer.py @@ -54,5 +54,31 @@ class TestHealthCheckLogic(unittest.TestCase): ) +class TestIsDatabase(unittest.TestCase): + def test_classification(self): + test_cases = [ + ("postgres_custom:18", True), + ("openldap_custom:13.7-slim", True), + ("mariadb_custom:11.8", True), + ("postgis/postgis:17-3.5", True), + ("valkey/valkey:8", True), + ("docker.io/library/postgres:18", True), + ("ghcr.io/infinito-nexus/mirror/docker.io/library/postgres:18", True), + ("registry.infinito.test:5000/openldap_custom:13.7-slim", True), + ("postgres@sha256:" + "0" * 64, True), + ("docker.elastic.co/elasticsearch/elasticsearch:9.1.0", True), + ("bigbluebutton_custom:v3.0.39", False), + ("registry.infinito.test:5000/nextcloud:31", False), + ("ghcr.io/ldapaccountmanager/lam:9", False), + ("phpldapadmin/phpldapadmin:2", False), + ] + for image_name, expected in test_cases: + self.assertEqual( + storage_optimizer.is_database(image_name), + expected, + f"Image {image_name} expected {expected}", + ) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/utils/install/lint/test_main.py b/tests/unit/python/utils/install/lint/test_main.py index 1ac3539ca8..be096bf743 100644 --- a/tests/unit/python/utils/install/lint/test_main.py +++ b/tests/unit/python/utils/install/lint/test_main.py @@ -17,6 +17,8 @@ def _make_repo_root(tmp: str, *, stamp_age_offset: float | None = None) -> Path: (root / "scripts" / "install").mkdir(parents=True) (root / "scripts" / "install" / "lint.sh").write_text("#\n", encoding="utf-8") (root / "pyproject.toml").write_text("[project]\n", encoding="utf-8") + (root / cli._PINS).parent.mkdir(parents=True) + (root / cli._PINS).write_text("---\n", encoding="utf-8") if stamp_age_offset is not None: stamp = root / cli._STAMP stamp.parent.mkdir(parents=True, exist_ok=True) @@ -86,6 +88,24 @@ class TestStampLogic(unittest.TestCase): inst.assert_called_once() self.assertTrue((root / cli._STAMP).exists()) + def test_a_newer_release_pin_triggers_install(self) -> None: + with TemporaryDirectory() as tmp: + root = _make_repo_root(tmp, stamp_age_offset=60.0) + pins = root / cli._PINS + later = time.time() + 120.0 + os.utime(pins, (later, later)) + with ( + mock.patch.object(cli, "PROJECT_ROOT", root), + mock.patch.object(cli.shutil, "which", return_value="/usr/bin/x"), + mock.patch.object( + cli.mermaid_cli, "browser_installed", return_value=True + ), + mock.patch.object(cli, "_install_all") as inst, + ): + rc = cli.main([]) + self.assertEqual(rc, 0) + inst.assert_called_once() + def test_no_stamp_triggers_install_and_touches(self) -> None: with TemporaryDirectory() as tmp: root = _make_repo_root(tmp) diff --git a/tests/unit/python/utils/install/lint/test_shfmt.py b/tests/unit/python/utils/install/lint/test_shfmt.py new file mode 100644 index 0000000000..95b63997a5 --- /dev/null +++ b/tests/unit/python/utils/install/lint/test_shfmt.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +import subprocess +import unittest +import unittest.mock as mock + +from utils.install.lint import shfmt + +_WANT = shfmt.resolve_release("shfmt")[1] + + +def _ensure(*versions: str | None) -> mock.MagicMock: + with ( + mock.patch.object(shfmt, "_installed_version", side_effect=list(versions)), + mock.patch.object(shfmt, "_install_binary") as install, + ): + shfmt.ensure() + return install + + +class TestEnsure(unittest.TestCase): + def test_the_pinned_release_stays(self) -> None: + _ensure(_WANT).assert_not_called() + + def test_a_distribution_release_is_replaced(self) -> None: + _ensure("3.8.0", _WANT).assert_called_once() + + def test_a_missing_shfmt_is_installed(self) -> None: + _ensure(None, _WANT).assert_called_once() + + def test_a_shadowed_install_fails_loudly(self) -> None: + with self.assertRaisesRegex(RuntimeError, "must precede"): + _ensure("3.8.0", "3.8.0") + + +class TestInstalledVersion(unittest.TestCase): + def _version(self, **run: object) -> str | None: + with mock.patch.object(shfmt.subprocess, "run", **run): + return shfmt._installed_version() + + def test_a_release_binary_drops_its_v(self) -> None: + done = subprocess.CompletedProcess([], 0, stdout="v3.14.1\n", stderr="") + self.assertEqual(self._version(return_value=done), "3.14.1") + + def test_a_distribution_build_reads_as_is(self) -> None: + done = subprocess.CompletedProcess([], 0, stdout="3.8.0\n", stderr="") + self.assertEqual(self._version(return_value=done), "3.8.0") + + def test_a_missing_binary_reads_as_none(self) -> None: + self.assertIsNone(self._version(side_effect=FileNotFoundError("shfmt"))) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/install/lint/__main__.py b/utils/install/lint/__main__.py index 9fed403e4b..432167f92a 100644 --- a/utils/install/lint/__main__.py +++ b/utils/install/lint/__main__.py @@ -37,12 +37,15 @@ from utils.install.lint.ansible import collections as ansible_collections from utils.install.lint.ansible import commands as ansible_commands from utils.install.lint.ansible import lint as ansible_lint from utils.install.primitives import warn +from utils.roles.mapping import ROLE_FILE_META_SERVICES _STAMP_KEY = hashlib.sha256(sys.executable.encode("utf-8")).hexdigest()[:8] _STAMP = f"build/install-lint-{_STAMP_KEY}.stamp" +_PINS = f"roles/sys-lint/{ROLE_FILE_META_SERVICES}" _STAMP_DEPS = ( "scripts/install/lint.sh", "pyproject.toml", + _PINS, ) _STAMP_TOOLS = ( diff --git a/utils/install/lint/shfmt.py b/utils/install/lint/shfmt.py index 1200af7537..16038fb137 100644 --- a/utils/install/lint/shfmt.py +++ b/utils/install/lint/shfmt.py @@ -1,9 +1,10 @@ -"""Install shfmt: system-pkg first, GitHub release fallback.""" +"""Install shfmt via GitHub-release prebuilt binary.""" from __future__ import annotations import os import platform +import subprocess import tempfile from pathlib import Path @@ -13,9 +14,7 @@ from utils.install.primitives import ( ensure_dir_on_path, install_with_optional_sudo, log, - which, ) -from utils.install.system_pkg import detect_package_manager, install_command_via_pkg _DEFAULT_INSTALL_DIR = os.environ.get("SHFMT_INSTALL_DIR", "/usr/local/bin") @@ -62,27 +61,29 @@ def _install_binary() -> None: ensure_dir_on_path(_DEFAULT_INSTALL_DIR) -def ensure() -> None: - if which("shfmt"): - return - - log("Missing command 'shfmt'. Attempting system package installation.") +def _installed_version() -> str | None: try: - manager = detect_package_manager() - try: - install_command_via_pkg("shfmt") - except RuntimeError as exc: - log(f"System package install failed for 'shfmt' via {manager}: {exc}") - except RuntimeError: - log( - "No supported package manager found; falling back to GitHub release binary." + proc = subprocess.run( + ["shfmt", "--version"], capture_output=True, text=True, check=True ) + except (OSError, subprocess.CalledProcessError): + return None + return proc.stdout.strip().lstrip("v") or None - if which("shfmt"): + +def ensure() -> None: + _slug, want = resolve_release("shfmt") + found = _installed_version() + if found == want: return - log("Falling back to official shfmt binary.") + log(f"Installing shfmt v{want} (found {found or 'no shfmt'}).") _install_binary() - if not which("shfmt"): - raise RuntimeError("Command 'shfmt' is still unavailable after installation.") + found = _installed_version() + if found != want: + raise RuntimeError( + f"Command 'shfmt' reports {found or 'nothing'} after installing " + f"v{want} into {_DEFAULT_INSTALL_DIR}; that directory must precede " + "any other shfmt on PATH." + )