From c8c3f96bf9680ce2a1ea20ba3855b8f579d32566 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 28 Oct 2026 23:06:21 +0100 Subject: [PATCH 01/13] feat(web-app-keycloak): serve /admin only to declared source networks The Keycloak vhost proxied every path to Keycloak, so the admin console and the admin REST API under /admin/realms answered any client on the internet (observed on auth.veen.world and auth.infinito.nexus), and sys-svc-proxy had no way to limit a path by source address. services.keycloak.admin.allowed_networks now takes the networks the operator declares in the inventory. When the list is non-empty, the vhost gets its own `location ^~ /admin`, rendered through the shared html.conf.j2 like `/`, with one `allow` per entry and `deny all`. The `^~` modifier keeps a regex location from taking an admin path over. The OIDC endpoints under /realms/ and the assets under /resources/ stay public. The role ships the list empty and adds no network of its own, so an inventory that declares nothing renders today's vhost unchanged. kc_admin_networks rejects anything but a list of addresses or CIDR blocks without host bits, so a typo fails the render instead of the nginx reload. The deploy's own admin calls do not cross the vhost: every kcadm.sh login, including web-app-opentalk's and web-app-mattermost's, runs inside the Keycloak container against a loopback URL, and a unit test now pins that. The README names the callers that do cross it (the OpenTalk controller's user search, onion visitors, the Playwright suites) and so need an entry. The TODO.md item is dropped. Closes #1121 Co-Authored-By: Claude Opus 5.5 --- roles/web-app-keycloak/README.md | 23 ++ roles/web-app-keycloak/TODO.md | 1 - .../filter_plugins/admin_networks.py | 55 ++++ roles/web-app-keycloak/meta/services.yml | 2 + roles/web-app-keycloak/tasks/00_core.yml | 1 + .../templates/nginx/admin_allowlist.conf.j2 | 14 + .../templates/test_admin_allowlist.py | 268 ++++++++++++++++++ 7 files changed, 363 insertions(+), 1 deletion(-) create mode 100644 roles/web-app-keycloak/filter_plugins/admin_networks.py create mode 100644 roles/web-app-keycloak/templates/nginx/admin_allowlist.conf.j2 create mode 100644 tests/unit/python/roles/web-app-keycloak/templates/test_admin_allowlist.py diff --git a/roles/web-app-keycloak/README.md b/roles/web-app-keycloak/README.md index 23426a8542..9a65a58afe 100644 --- a/roles/web-app-keycloak/README.md +++ b/roles/web-app-keycloak/README.md @@ -132,6 +132,29 @@ docker run --rm -it \ For the OIDC variable tree, claim rules, and the policy that app-specific protocol mappers belong in per-client scope files (not in the shared `clients/default.json.j2`), see [oidc.md](../../docs/contributing/design/iam/oidc.md). +## Admin Console Access + +`services.keycloak.admin.allowed_networks` limits every path under `/admin`, which carries the admin console and the admin REST API under `/admin/realms`, to the listed source networks. Each entry is an IPv4 or IPv6 address or a CIDR block. The vhost renders one `allow` per entry followed by `deny all`, so any other client gets `403`. The list ships empty, and an empty list leaves `/admin` open. Declare it in the inventory: + +```yaml +applications: + web-app-keycloak: + services: + keycloak: + admin: + allowed_networks: + - 203.0.113.0/24 + - 2001:db8::/48 +``` + +The OIDC endpoints under `/realms/` and the static assets under `/resources/` stay public. + +The deploy itself needs no entry: every `kcadm.sh` login, including the ones `web-app-opentalk` and `web-app-mattermost` make, runs inside the Keycloak container against `KEYCLOAK_SERVER_INTERNAL_URL`. Clients that call `/admin` through the public URL need their source network in the list: + +- The OpenTalk controller's user search calls the admin REST API from its container, so the vhost sees the container's Docker network address. `NETWORK_INTERNAL_CIDRS` covers the loopback and private ranges those addresses come from. +- Onion visitors reach the vhost from the Tor daemon's address. +- The Playwright suites of several roles read and change realm groups through the admin REST API. + ## Further Resources - [Keycloak Official Website](https://www.keycloak.org/) diff --git a/roles/web-app-keycloak/TODO.md b/roles/web-app-keycloak/TODO.md index ca648c8906..52760911f6 100644 --- a/roles/web-app-keycloak/TODO.md +++ b/roles/web-app-keycloak/TODO.md @@ -2,7 +2,6 @@ - Implement working logout for all applications - Implement general logout button -- Restrict the admin console. `https://auth./` redirects to `/admin/`, which any client on the internet can reach. Add a source-network allowlist for `/admin` in the proxy vhost. ## Req 019 rollout: deploy gate diff --git a/roles/web-app-keycloak/filter_plugins/admin_networks.py b/roles/web-app-keycloak/filter_plugins/admin_networks.py new file mode 100644 index 0000000000..84c5ed2f8b --- /dev/null +++ b/roles/web-app-keycloak/filter_plugins/admin_networks.py @@ -0,0 +1,55 @@ +"""Source networks the Keycloak vhost serves its admin paths to.""" + +from __future__ import annotations + +import ipaddress +from typing import Any + +from ansible.errors import AnsibleFilterError + +CONFIG_PATH = "services.keycloak.admin.allowed_networks" + + +def kc_admin_networks(networks: Any) -> list[str]: + """Return the declared admin networks as nginx ``allow`` operands. + + Args: + networks: the value of ``services.keycloak.admin.allowed_networks``, a + list of IPv4 or IPv6 addresses and CIDR blocks. + + Returns: + Each entry in CIDR notation, in declared order and without duplicates. + An empty list leaves the admin paths unrestricted. + + Raises: + AnsibleFilterError: the value is not a list, or an entry is not an + address or a CIDR block without host bits. + """ + if not isinstance(networks, (list, tuple)): + raise AnsibleFilterError( + f"kc_admin_networks: {CONFIG_PATH} must be a list of addresses or " + f"CIDR blocks, got {type(networks).__name__}: {networks!r}" + ) + + resolved: list[str] = [] + for entry in networks: + if not isinstance(entry, str) or not entry.strip(): + raise AnsibleFilterError( + f"kc_admin_networks: {CONFIG_PATH} entry {entry!r} is not an " + "address or a CIDR block" + ) + try: + network = str(ipaddress.ip_network(entry.strip(), strict=True)) + except ValueError as exc: + raise AnsibleFilterError( + f"kc_admin_networks: {CONFIG_PATH} entry {entry!r} is not an " + f"address or a CIDR block without host bits: {exc}" + ) from exc + if network not in resolved: + resolved.append(network) + return resolved + + +class FilterModule: + def filters(self) -> dict[str, Any]: + return {"kc_admin_networks": kc_admin_networks} diff --git a/roles/web-app-keycloak/meta/services.yml b/roles/web-app-keycloak/meta/services.yml index 379394b130..86d2f2f0af 100644 --- a/roles/web-app-keycloak/meta/services.yml +++ b/roles/web-app-keycloak/meta/services.yml @@ -71,6 +71,8 @@ keycloak: username: administrator system: username: "{{ SOFTWARE_NAME | replace('.', '_') | lower }}" + admin: + allowed_networks: [] ports: local: http: 8032 diff --git a/roles/web-app-keycloak/tasks/00_core.yml b/roles/web-app-keycloak/tasks/00_core.yml index 30bf94335a..da3d36d4b1 100644 --- a/roles/web-app-keycloak/tasks/00_core.yml +++ b/roles/web-app-keycloak/tasks/00_core.yml @@ -23,6 +23,7 @@ compose_handlers_flush: true webserver_extra_configuration: >- {{ lookup('template', 'nginx/helper_iframes.conf.j2') + ~ lookup('template', 'nginx/admin_allowlist.conf.j2') ~ (lookup('template', 'nginx/logout_panel.conf.j2') if KEYCLOAK_LOGOUT_PANEL_ENABLED | bool else '') }} - name: "👔 Keycloak manager-side operations (file deploys + container exec)" diff --git a/roles/web-app-keycloak/templates/nginx/admin_allowlist.conf.j2 b/roles/web-app-keycloak/templates/nginx/admin_allowlist.conf.j2 new file mode 100644 index 0000000000..25d808eb4d --- /dev/null +++ b/roles/web-app-keycloak/templates/nginx/admin_allowlist.conf.j2 @@ -0,0 +1,14 @@ +{% set admin_networks = lookup('config', application_id, 'services.keycloak.admin.allowed_networks') | kc_admin_networks %} +{% if admin_networks %} +{% set sso_proxy_enabled = false %} +{% set http_port = lookup('config', application_id, 'services.keycloak.ports.local.http') %} +{% set proxy_service_key = 'keycloak' %} +{% set location = '^~ /admin' %} +{% set webserver_location_extra_configuration %} +{% for network in admin_networks %} + allow {{ network }}; +{% endfor %} + deny all; +{% endset %} +{% include 'roles/sys-svc-proxy/templates/location/html.conf.j2' %} +{% endif %} diff --git a/tests/unit/python/roles/web-app-keycloak/templates/test_admin_allowlist.py b/tests/unit/python/roles/web-app-keycloak/templates/test_admin_allowlist.py new file mode 100644 index 0000000000..5609b2217c --- /dev/null +++ b/tests/unit/python/roles/web-app-keycloak/templates/test_admin_allowlist.py @@ -0,0 +1,268 @@ +from __future__ import annotations + +import importlib.util +import re +import unittest + +from ansible.errors import AnsibleFilterError +from jinja2 import ( + ChoiceLoader, + DictLoader, + Environment, + FileSystemLoader, + StrictUndefined, + select_autoescape, +) + +from utils.cache.files import iter_project_files_with_content, read_text +from utils.cache.yaml import load_yaml +from utils.networks.proxy import render_proxy_pass +from utils.roles.mapping import ROLE_FILE_META_SERVICES + +from . import PROJECT_ROOT + +ROLE_DIR = PROJECT_ROOT / "roles/web-app-keycloak" +TEMPLATE = "roles/web-app-keycloak/templates/nginx/admin_allowlist.conf.j2" +CONFIG_PATH = "services.keycloak.admin.allowed_networks" +LOCAL_HTTP_PORT = 8032 +NETWORKS = ("203.0.113.0/24", "2001:db8::/48", "198.51.100.7") + +STUBBED_INCLUDES = { + "roles/web-app-keycloak/templates/sso_proxy/following_directives.conf.j2": "SSO_GATE\n", + "roles/sys-svc-proxy/templates/headers/content_security_policy.conf.j2": "", + "roles/sys-svc-proxy/templates/headers/access_control_allow.conf.j2": "", + "roles/sys-svc-proxy/templates/headers/forwarded.conf.j2": "", + "roles/sys-svc-proxy/templates/headers/untrusted_identity_strips.conf.j2": "", + "roles/sys-front-inj-all/templates/location.lua.j2": "", +} + + +def role_filters() -> dict: + spec = importlib.util.spec_from_file_location( + "keycloak_admin_networks", ROLE_DIR / "filter_plugins/admin_networks.py" + ) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module.FilterModule().filters() + + +def render(networks, deployment_mode: str = "compose") -> str: + """Render the allowlist fragment the Keycloak vhost carries. + + Args: + networks: the value under `services.keycloak.admin.allowed_networks`. + deployment_mode: the mode `proxy_pass` renders for. + """ + config = { + CONFIG_PATH: networks, + "services.keycloak.ports.local.http": LOCAL_HTTP_PORT, + } + + def lookup(kind, *args, **kwargs): + if kind == "config": + if args[1] in config: + return config[args[1]] + return args[2] + if kind == "proxy_pass": + return render_proxy_pass( + f"127.0.0.1:{kwargs['local_port']}", + deployment_mode, + tail=kwargs["tail"], + location=kwargs["location"], + ) + raise AssertionError(f"unexpected lookup({kind!r}, ...)") + + env = Environment( + loader=ChoiceLoader( + [DictLoader(STUBBED_INCLUDES), FileSystemLoader(str(PROJECT_ROOT))] + ), + undefined=StrictUndefined, + autoescape=select_autoescape(), + ) + env.filters.update(role_filters()) + env.filters["bool"] = lambda value: ( + value + if isinstance(value, bool) + else str(value).strip().lower() in {"true", "1", "yes", "on"} + ) + env.filters["get_entity_name"] = lambda value: value.rsplit("-", 1)[-1] + return env.get_template(TEMPLATE).render( + application_id="web-app-keycloak", lookup=lookup + ) + + +def location_block(rendered: str) -> tuple[str, list[str]]: + """Return the location's matcher and its directives, one per line. + + Args: + rendered: the rendered fragment. + """ + match = re.search(r"location\s+([^{]+?)\s*\{(.*)\}\s*$", rendered, re.DOTALL) + if match is None: + raise AssertionError(f"no location block rendered:\n{rendered}") + directives = [ + line.strip() + for line in match.group(2).splitlines() + if line.strip() and not line.strip().startswith("#") + ] + return match.group(1).strip(), directives + + +def covers(matcher: str, path: str) -> bool: + """Return whether an nginx prefix matcher selects a request path. + + Args: + matcher: the location matcher, modifier included. + path: the normalised request path. + """ + return path.startswith(re.sub(r"^\^~\s*", "", matcher)) + + +class TestShippedValue(unittest.TestCase): + def test_the_role_ships_no_implicit_allowlist(self): + services = load_yaml(ROLE_DIR / ROLE_FILE_META_SERVICES) + self.assertEqual(services["keycloak"]["admin"]["allowed_networks"], []) + + def test_an_empty_list_renders_nothing(self): + self.assertEqual(render([]).strip(), "") + + def test_the_keycloak_vhost_carries_the_fragment(self): + self.assertIn( + "lookup('template', 'nginx/admin_allowlist.conf.j2')", + read_text(str(ROLE_DIR / "tasks/00_core.yml")), + ) + + +class TestRestrictedLocation(unittest.TestCase): + def test_every_network_is_allowed_before_the_rest_is_denied(self): + _, directives = location_block(render(list(NETWORKS))) + access = [d for d in directives if d.startswith(("allow ", "deny "))] + self.assertEqual( + access, + [ + "allow 203.0.113.0/24;", + "allow 2001:db8::/48;", + "allow 198.51.100.7/32;", + "deny all;", + ], + ) + + def test_the_admin_console_and_rest_api_are_covered(self): + matcher, _ = location_block(render(list(NETWORKS))) + for path in ( + "/admin", + "/admin/", + "/admin/master/console/", + "/admin/realms/infinito/users", + "/admin/serverinfo", + ): + with self.subTest(path=path): + self.assertTrue(covers(matcher, path)) + + def test_the_oidc_endpoints_stay_public(self): + matcher, _ = location_block(render(list(NETWORKS))) + for path in ( + "/", + "/realms/infinito/protocol/openid-connect/token", + "/realms/infinito/.well-known/openid-configuration", + "/realms/infinito/account/", + "/resources/abc/admin/keycloak.v2/main.js", + ): + with self.subTest(path=path): + self.assertFalse(covers(matcher, path)) + + def test_no_regex_location_can_take_an_admin_path_over(self): + matcher, _ = location_block(render(list(NETWORKS))) + self.assertTrue( + matcher.startswith("^~ "), + f"'{matcher}' lets a regex location win over the allowlist", + ) + + def test_compose_passes_the_request_path_unchanged(self): + _, directives = location_block(render(list(NETWORKS))) + self.assertIn( + f"proxy_pass http://127.0.0.1:{LOCAL_HTTP_PORT}/admin;", directives + ) + + def test_swarm_passes_the_raw_request_uri(self): + _, directives = location_block(render(list(NETWORKS), "swarm")) + self.assertIn("proxy_pass http://$proxy_pass_upstream$request_uri;", directives) + + def test_the_location_strips_forged_identity_headers(self): + rendered = render(list(NETWORKS)) + self.assertIn('proxy_set_header X-Forwarded-User "";', rendered) + self.assertNotIn("SSO_GATE", rendered) + + +class TestDeclaredValues(unittest.TestCase): + def test_spellings_of_one_network_render_one_allow(self): + _, directives = location_block( + render(["2001:db8::1", "2001:0db8::1/128", " 2001:db8::1 "]) + ) + self.assertEqual( + [d for d in directives if d.startswith("allow ")], + ["allow 2001:db8::1/128;"], + ) + + def test_malformed_values_fail_the_render(self): + for value in ( + "203.0.113.0/24", + None, + ["all"], + ["203.0.113.7/24"], + ["auth.example.com"], + [""], + [42], + ): + with self.subTest(value=value), self.assertRaises(AnsibleFilterError): + render(value) + + +class TestDeployAdminCallsBypassTheVhost(unittest.TestCase): + LOGIN = re.compile( + r"config credentials[\s\\]*--server\s+(\"[^\"]*\"|\{\{.*?\}\}|\S+)", re.DOTALL + ) + INTERNAL_URL_DEFINITION = re.compile( + r"^\s*KEYCLOAK_SERVER_INTERNAL_URL:\s*\"([^\"]+)\"", re.MULTILINE + ) + LOOPBACK = re.compile(r"^http://(127\.0\.0\.1|localhost|\[::1\]):\d+$") + + def _role_sources(self) -> dict[str, str]: + return { + path: text + for path, text in iter_project_files_with_content( + extensions=(".yml", ".sh", ".j2"), exclude_tests=True + ) + if "/roles/" in path + } + + def test_every_kcadm_login_targets_the_container_loopback(self): + servers = [ + (name, match.group(1).strip('"')) + for name, text in self._role_sources().items() + for match in self.LOGIN.finditer(text) + ] + self.assertTrue(servers, "no kcadm login found, the scan is vacuous") + for name, server in servers: + with self.subTest(source=name, server=server): + self.assertTrue( + server == "{{ KEYCLOAK_SERVER_INTERNAL_URL }}" + or self.LOOPBACK.match(server), + f"{name} logs kcadm in through {server}, which crosses the " + "public vhost and its admin allowlist", + ) + + def test_the_internal_url_is_loopback_wherever_it_is_defined(self): + definitions = [ + (name, match.group(1)) + for name, text in self._role_sources().items() + for match in self.INTERNAL_URL_DEFINITION.finditer(text) + ] + self.assertTrue(definitions, "KEYCLOAK_SERVER_INTERNAL_URL is defined nowhere") + for name, url in definitions: + with self.subTest(source=name): + self.assertRegex(url, self.LOOPBACK) + + +if __name__ == "__main__": + unittest.main() From 3c743736a8cd49539fc570f4645eddf48f23a6e8 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 00:12:25 +0100 Subject: [PATCH 02/13] feat(sys-ctl-hlth-runtime): alert on EOL or unpatched PHP and missing PHP hardening Answering "which deployed containers run a vulnerable PHP?" after CVE-2026-109618/109619 took a manual inventory of registry metadata, and nothing noticed a hardening ini that an image never loads. - New role sys-ctl-hlth-runtime, routed through sys-svc-compose next to sys-ctl-hlth-container. A daily timer runs `php` in every running container and fails, alerting through sys-ctl-alm-compose, when PHP is below the floor of its line or on a line older than every floor (7.4, 8.1). Every service that mounts php_hardening in meta/volumes.yml fails while expose_php or session.upload_progress.enabled is on; other PHP containers of such a stack are listed as info. Compose and swarm containers are matched by their project/stack and service labels. The check is not run at deploy time, so a finding never fails a deploy. - The floors (8.2.35, 8.3.36, 8.4.27, 8.5.12) live once, in HEALTH_RUNTIME_FLOORS of the role's vars/main.yml. - `make security-runtimes` lists the PHP of every pinned role image without pulling: Docker Hub tags through the Hub API, which no pull rate limit meters, other registries through the OCI config blob (new registry.config_blob, which the healthcheck probe now reuses). PHP_VERSION, distro PHP packages and a PHP_BASE build argument count. It exits 1 on an image below its floor or one the registry did not answer. Today it flags nfrastack/fusiondirectory:1.5 (line 7.4) and shopware/docker-base:8.3 (8.3.25). The role TODO.md keeps the follow-ups: further runtimes, the split web SAPI of web-app-lam, a scheduled CI run of the report and the CVE scan. Refs #1127 Co-Authored-By: Claude Opus 5.5 --- Makefile | 7 +- aliases | 1 + cli/contributing/security/README.md | 3 + cli/contributing/security/__init__.py | 0 .../security/runtimes/__init__.py | 5 + .../security/runtimes/__main__.py | 90 ++++++ group_vars/all/07_schedule.yml | 1 + roles/sys-ctl-hlth-runtime/README.md | 35 +++ roles/sys-ctl-hlth-runtime/TODO.md | 6 + .../files/python/script.py | 269 +++++++++++++++++ .../lookup_plugins/php_hardened_services.py | 70 +++++ roles/sys-ctl-hlth-runtime/meta/main.yml | 31 ++ roles/sys-ctl-hlth-runtime/meta/services.yml | 8 + roles/sys-ctl-hlth-runtime/tasks/00_core.yml | 19 ++ roles/sys-ctl-hlth-runtime/tasks/main.yml | 3 + roles/sys-ctl-hlth-runtime/vars/main.yml | 10 + roles/sys-svc-compose/tasks/main.yml | 1 + .../cli/contributing/security/__init__.py | 0 .../contributing/security/test_runtimes.py | 71 +++++ .../roles/sys-ctl-hlth-runtime/__init__.py | 0 .../sys-ctl-hlth-runtime/files/__init__.py | 5 + .../sys-ctl-hlth-runtime/files/test_script.py | 283 ++++++++++++++++++ .../lookup_plugins/__init__.py | 5 + .../test_php_hardened_services.py | 90 ++++++ .../python/utils/docker/test_image_runtime.py | 215 +++++++++++++ .../utils/docker/test_registry_healthcheck.py | 19 ++ utils/docker/image/runtime.py | 194 ++++++++++++ utils/docker/registry.py | 23 +- 28 files changed, 1461 insertions(+), 3 deletions(-) create mode 100644 cli/contributing/security/README.md create mode 100644 cli/contributing/security/__init__.py create mode 100644 cli/contributing/security/runtimes/__init__.py create mode 100755 cli/contributing/security/runtimes/__main__.py create mode 100644 roles/sys-ctl-hlth-runtime/README.md create mode 100644 roles/sys-ctl-hlth-runtime/TODO.md create mode 100755 roles/sys-ctl-hlth-runtime/files/python/script.py create mode 100644 roles/sys-ctl-hlth-runtime/lookup_plugins/php_hardened_services.py create mode 100644 roles/sys-ctl-hlth-runtime/meta/main.yml create mode 100644 roles/sys-ctl-hlth-runtime/meta/services.yml create mode 100644 roles/sys-ctl-hlth-runtime/tasks/00_core.yml create mode 100644 roles/sys-ctl-hlth-runtime/tasks/main.yml create mode 100644 roles/sys-ctl-hlth-runtime/vars/main.yml create mode 100644 tests/unit/python/cli/contributing/security/__init__.py create mode 100644 tests/unit/python/cli/contributing/security/test_runtimes.py create mode 100644 tests/unit/python/roles/sys-ctl-hlth-runtime/__init__.py create mode 100644 tests/unit/python/roles/sys-ctl-hlth-runtime/files/__init__.py create mode 100644 tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py create mode 100644 tests/unit/python/roles/sys-ctl-hlth-runtime/lookup_plugins/__init__.py create mode 100644 tests/unit/python/roles/sys-ctl-hlth-runtime/lookup_plugins/test_php_hardened_services.py create mode 100644 tests/unit/python/utils/docker/test_image_runtime.py create mode 100644 utils/docker/image/runtime.py diff --git a/Makefile b/Makefile index eb19a6e74b..e08a2a1888 100644 --- a/Makefile +++ b/Makefile @@ -701,6 +701,11 @@ security-apparmor-teardown: echo "[apparmor] AppArmor module is not loaded — skipping teardown"; \ fi +.PHONY: security-runtimes +# List the PHP runtime of every pinned role image from registry metadata, without pulling, and fail on one below its security floor. +security-runtimes: + @"$${PYTHON}" -m cli.contributing.security.runtimes + .PHONY: setup # Run the setup step after generating .dockerignore. setup: fix-dockerignore dotenv @@ -945,4 +950,4 @@ wsl2-systemd-check: .PHONY: wsl2-trust-windows # Trust Windows certificates in WSL2. wsl2-trust-windows: - @bash scripts/system/tls/trust/wsl2.sh \ No newline at end of file + @bash scripts/system/tls/trust/wsl2.sh diff --git a/aliases b/aliases index 00d47d37a3..306be72003 100644 --- a/aliases +++ b/aliases @@ -143,6 +143,7 @@ alias i8se2='m setup' alias i8sece='m setup-clean' alias i8sepa='m security-apparmor-teardown' alias i8sepu='m system-purge' +alias i8seru='m security-runtimes' alias i8source='source scripts/meta/env/load.sh' # load the project .env + venv python into the current shell alias i8ta='m autoformat' alias i8tare='m autoformat-restage' diff --git a/cli/contributing/security/README.md b/cli/contributing/security/README.md new file mode 100644 index 0000000000..8c43a9dbaf --- /dev/null +++ b/cli/contributing/security/README.md @@ -0,0 +1,3 @@ +# Security ðŸ›Ąïļ + +Repository-side security reports over the declared role artefacts, such as the language runtimes the pinned images ship, read from registry metadata without pulling. diff --git a/cli/contributing/security/__init__.py b/cli/contributing/security/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/cli/contributing/security/runtimes/__init__.py b/cli/contributing/security/runtimes/__init__.py new file mode 100644 index 0000000000..eec6d4835a --- /dev/null +++ b/cli/contributing/security/runtimes/__init__.py @@ -0,0 +1,5 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[4] + +__all__ = ["PROJECT_ROOT"] diff --git a/cli/contributing/security/runtimes/__main__.py b/cli/contributing/security/runtimes/__main__.py new file mode 100755 index 0000000000..f73d606881 --- /dev/null +++ b/cli/contributing/security/runtimes/__main__.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +from concurrent.futures import ThreadPoolExecutor + +from utils.docker.image.discovery import ImageRef, iter_role_images +from utils.docker.image.runtime import ( + build_instructions, + load_php_floors, + php_finding, + php_runtime, +) + +from . import PROJECT_ROOT + +WORKERS = 4 +OS_NAME = "linux" +ARCHITECTURE = "amd64" + + +def _instructions(ref: ImageRef) -> list[str] | None: + return build_instructions( + f"{ref.registry}/{ref.name}", + ref.version, + os_name=OS_NAME, + architecture=ARCHITECTURE, + ) + + +def report(refs: list[ImageRef], probed: list, floors: dict[str, str]) -> int: + """Print one line per image that ships PHP and return the exit code. + + Args: + refs: the pinned role images. + probed: :func:`build_instructions` result per ref, in the same order. + floors: see :func:`load_php_floors`. + + Returns: + ``1`` when an image is below its floor or the registry gave no answer + for one, ``0`` otherwise. + """ + findings = 0 + unknown = [] + with_php = 0 + for ref, instructions in zip(refs, probed, strict=True): + if instructions is None: + unknown.append(f"{ref.role}:{ref.service} ({ref.source})") + continue + runtime = php_runtime(instructions) + if runtime is None: + continue + with_php += 1 + php = runtime.version or f"line {', '.join(runtime.lines)}" + finding = php_finding(runtime, floors) + if finding: + findings += 1 + print(f"❌ {ref.role}:{ref.service} {ref.source} PHP {php}: {finding}") + elif runtime.version: + print(f"✅ {ref.role}:{ref.service} {ref.source} PHP {php}") + else: + print( + f"❔ {ref.role}:{ref.service} {ref.source} PHP {php}: " + "patch level not in the registry metadata" + ) + for entry in unknown: + print(f"⚠ïļ {entry}: the registry gave no answer") + print( + f"\n{len(refs)} image(s): {with_php} ship PHP, {findings} below the " + f"floor, {len(unknown)} unanswered" + ) + return 1 if findings or unknown else 0 + + +def main(argv=None) -> int: + argparse.ArgumentParser( + description=( + "List the PHP runtime of every pinned role image from registry " + "metadata, without pulling, and fail on one below its security floor." + ) + ).parse_args(argv) + floors = load_php_floors() + refs = sorted(iter_role_images(PROJECT_ROOT), key=lambda r: (r.role, r.service)) + with ThreadPoolExecutor(max_workers=WORKERS) as pool: + probed = list(pool.map(_instructions, refs)) + return report(refs, probed, floors) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/group_vars/all/07_schedule.yml b/group_vars/all/07_schedule.yml index 1f7238f106..94f7d98759 100644 --- a/group_vars/all/07_schedule.yml +++ b/group_vars/all/07_schedule.yml @@ -23,6 +23,7 @@ SYS_SCHEDULE_HEALTH_DOCKER_VOLUMES: "*-*-* {{ HOURS_SERVER_AWAKE }}:00:00" # Che SYS_SCHEDULE_HEALTH_CSP_CRAWLER: "*-*-* {{ HOURS_SERVER_AWAKE }}:00:00" # Check once per hour if all CSP are fullfilled available SYS_SCHEDULE_HEALTH_NGINX: "*-*-* {{ HOURS_SERVER_AWAKE }}:00:00" # Check once per hour if all webservices are available SYS_SCHEDULE_HEALTH_MSMTP: "*-*-* 00:00:00" # Check once per day SMTP Server +SYS_SCHEDULE_HEALTH_RUNTIME: "*-*-* 00:00:00" # Check once per day the PHP version and hardening of every running container SYS_SCHEDULE_CLEANUP_CERTS: "*-*-* 20:00" # Deletes and revokes unused certs once per day SYS_SCHEDULE_CLEANUP_BACKUPS: "*-*-* 21:00" # Cleanup backups once per day, MUST be called before disc space cleanup diff --git a/roles/sys-ctl-hlth-runtime/README.md b/roles/sys-ctl-hlth-runtime/README.md new file mode 100644 index 0000000000..f0721cbfda --- /dev/null +++ b/roles/sys-ctl-hlth-runtime/README.md @@ -0,0 +1,35 @@ +# Container Runtime Health Check + +## Description + +This role checks the language runtime inside every running Docker container. It reads the PHP version of each container that ships a `php` binary and the effective PHP hardening of each service that mounts the shared hardening ini from [`sys-svc-compose-php`](../sys-svc-compose-php/README.md). + +## Overview + +The role installs a check script with a `systemd` service and timer. The check fails, and the failure notifier from [`sys-ctl-alm-compose`](../sys-ctl-alm-compose/README.md) alerts, when a container runs PHP below the security floor of its release line or on an end-of-life line, or when a service that declares `php_hardening` in its `meta/volumes.yml` still reports `expose_php` or `session.upload_progress.enabled` as on. The floors live in `HEALTH_RUNTIME_FLOORS` in [main.yml](./vars/main.yml). + +## Cosmos + +The diagram places Container Runtime Health Check in the Infinito.Nexus cosmos: the components it deploys (capabilities), the central services it consumes (dependencies), and its outward reach (federation and bridged external networks). + +```mermaid +flowchart LR + subgraph role [sys-ctl-hlth-runtime ðŸ’ŧ] + svc_runtime["runtime"] + end +``` + +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (ðŸ’ŧ host, ðŸģ compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙ïļ an Ansible role dependency declared in `meta/main.yml`. + +## Features + +- **Runtime floor:** Fails for every running container whose PHP is below the floor of its `major.minor` line, or on a line older than every listed floor (end of life). A line newer than every floor passes. +- **Hardening verification:** Runs `php` inside every service that mounts `php_hardening` and fails while `expose_php` or `session.upload_progress.enabled` is on, which catches a wrong scan dir, a later ini that overrides the hardening, and an image change. +- **Sidecar report:** Lists other PHP containers of a hardened stack, such as cron or worker sidecars, as info without failing. +- **Registry report:** `make security-runtimes` lists the PHP runtime of every pinned image from registry metadata, without pulling, against the same floors. + +## Credits + +Implemented by **[Kevin Veen-Birkenbach](https://www.veen.world)**. +Part of the [Infinito.Nexus Project](https://s.infinito.nexus/code) and maintained by [Kevin Veen-Birkenbach](https://www.veen.world). +Licensed under the [Infinito.Nexus Community License (Non-Commercial)](https://s.infinito.nexus/license). diff --git a/roles/sys-ctl-hlth-runtime/TODO.md b/roles/sys-ctl-hlth-runtime/TODO.md new file mode 100644 index 0000000000..a249b5e35e --- /dev/null +++ b/roles/sys-ctl-hlth-runtime/TODO.md @@ -0,0 +1,6 @@ +# To-dos + +- Extend `HEALTH_RUNTIME_FLOORS`, the container probe and `make security-runtimes` to `node`, `python`, `ruby` and `java`. +- Verify the web SAPI where an image splits it from the CLI. `web-app-lam` mounts the hardening ini into `/etc/php/8.4/apache2/conf.d`, which the Debian CLI does not scan, so `php` in that container reads the CLI configuration instead of the one Apache loads. +- Run `make security-runtimes` in a scheduled CI workflow. +- Scan the pinned images for CVEs (Trivy or Grype) in the scheduled CI and report new criticals as issues. diff --git a/roles/sys-ctl-hlth-runtime/files/python/script.py b/roles/sys-ctl-hlth-runtime/files/python/script.py new file mode 100755 index 0000000000..c371209ea4 --- /dev/null +++ b/roles/sys-ctl-hlth-runtime/files/python/script.py @@ -0,0 +1,269 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import re +import subprocess +import sys +from dataclasses import dataclass + +PROBE_MARKER = "INFINITO-RUNTIME-PROBE" +HARDENED_SETTINGS = ("expose_php", "session.upload_progress.enabled") +PHP_PROBE = ( + f'echo "\\n{PROBE_MARKER}|", PHP_VERSION, "|", ini_get("expose_php"), "|", ' + 'ini_get("session.upload_progress.enabled"), "\\n";' +) +NO_BINARY_EXIT_CODES = frozenset({126, 127}) +EXEC_TIMEOUT_SECONDS = 60 +VERSION_PATTERN = re.compile(r"^(\d+)\.(\d+)\.(\d+)") +ENABLED_VALUES = frozenset({"1", "on", "yes", "true"}) + + +@dataclass(frozen=True) +class Container: + id: str + name: str + stack: str | None + service: str | None + + +@dataclass(frozen=True) +class PhpProbe: + version: str + settings: dict + + +class ProbeError(RuntimeError): + pass + + +def parse_args(argv=None): + parser = argparse.ArgumentParser( + description="Check PHP versions and hardening of running containers." + ) + parser.add_argument( + "--floors", + required=True, + help='JSON: {"php": {".": ""}}', + ) + parser.add_argument( + "--hardened", + required=True, + help='JSON: {"": ["", ...]}', + ) + return parser.parse_args(argv) + + +def identity(labels: dict | None) -> tuple[str | None, str | None]: + """Return the ``(stack, service)`` a container belongs to. + + Args: + labels: the container's ``Config.Labels``, ``None`` when it has none. + + Returns: + The swarm stack and service or the compose project and service; + ``(None, None)`` for a container started outside both. + """ + if not labels: + return None, None + stack = labels.get("com.docker.stack.namespace") + if stack: + service = labels["com.docker.swarm.service.name"] + return stack, service.removeprefix(f"{stack}_") + project = labels.get("com.docker.compose.project") + if project: + return project, labels["com.docker.compose.service"] + return None, None + + +def running_containers() -> list[Container]: + ids = subprocess.run( + ["container", "ps", "-q", "--no-trunc"], + capture_output=True, + text=True, + check=True, + ).stdout.split() + if not ids: + return [] + inspected = json.loads( + subprocess.run( + ["container", "inspect", "--type", "container", *ids], + capture_output=True, + text=True, + check=True, + ).stdout + ) + containers = [] + for entry in inspected: + stack, service = identity(entry["Config"]["Labels"]) + containers.append( + Container( + id=entry["Id"], + name=entry["Name"].lstrip("/"), + stack=stack, + service=service, + ) + ) + return containers + + +def parse_probe(stdout: str) -> PhpProbe: + """Read the probe line out of the ``php -r`` output. + + Args: + stdout: everything php printed, startup warnings included. + + Returns: + The PHP version and whether each of HARDENED_SETTINGS is on. + """ + for line in stdout.splitlines(): + if not line.startswith(f"{PROBE_MARKER}|"): + continue + fields = line.split("|")[1:] + if len(fields) != 1 + len(HARDENED_SETTINGS): + raise ProbeError(f"malformed probe line: {line!r}") + version, *values = fields + return PhpProbe( + version=version, + settings={ + name: value.strip().lower() in ENABLED_VALUES + for name, value in zip(HARDENED_SETTINGS, values, strict=True) + }, + ) + raise ProbeError(f"php printed no probe line: {stdout.strip()!r}") + + +def probe_php(container_id: str) -> PhpProbe | None: + """Run the PHP probe inside a container. + + Args: + container_id: the container to exec into. + + Returns: + The probe result, or ``None`` when the container has no ``php``. + """ + try: + result = subprocess.run( + ["container", "exec", container_id, "php", "-r", PHP_PROBE], + capture_output=True, + text=True, + check=False, + timeout=EXEC_TIMEOUT_SECONDS, + ) + except subprocess.TimeoutExpired as exc: + raise ProbeError(f"php did not answer within {exc.timeout}s") from exc + if result.returncode in NO_BINARY_EXIT_CODES: + return None + if result.returncode != 0: + output = result.stderr.strip() or result.stdout.strip() + raise ProbeError(f"php exited {result.returncode}: {output}") + return parse_probe(result.stdout) + + +def _version_tuple(version: str) -> tuple[int, int, int] | None: + match = VERSION_PATTERN.match(version) + if match is None: + return None + major, minor, patch = (int(part) for part in match.groups()) + return major, minor, patch + + +def _line_tuple(line: str) -> tuple[int, int]: + major, minor = line.split(".") + return int(major), int(minor) + + +def floor_violation(version: str, floors: dict) -> str | None: + """Judge a runtime version against the floors of its runtime. + + Args: + version: the version the runtime reports, e.g. ``8.3.12`` or + ``8.1.2-1ubuntu2.14``. + floors: ``{".": ""}``. + + Returns: + ``None`` when the version is at or above its line's floor or on a line + newer than every floor, otherwise the reason it fails. + """ + current = _version_tuple(version) + if current is None: + return f"unparsable version {version!r}" + line = f"{current[0]}.{current[1]}" + if line in floors: + floor = floors[line] + if current < _version_tuple(floor): + return f"{version} is below the security floor {floor}" + return None + if current[:2] > max(_line_tuple(key) for key in floors): + return None + return f"{version} runs the end-of-life line {line}" + + +def check( + containers: list[Container], + php_floors: dict, + hardened: dict, + probe, +) -> tuple[list[str], list[str]]: + """Evaluate every container. + + Args: + containers: the running containers. + php_floors: the PHP floors, see :func:`floor_violation`. + hardened: ``{stack: [service, ...]}`` that must run hardened PHP. + probe: callable returning a :class:`PhpProbe` or ``None`` per id. + + Returns: + ``(failures, infos)`` as printable lines. + """ + failures: list[str] = [] + infos: list[str] = [] + for container in sorted(containers, key=lambda c: c.name): + in_hardened_stack = container.stack in hardened + must_harden = ( + in_hardened_stack and container.service in hardened[container.stack] + ) + try: + result = probe(container.id) + except ProbeError as exc: + failures.append(f"{container.name}: {exc}") + continue + if result is None: + if must_harden: + failures.append( + f"{container.name}: declares php_hardening but has no php to verify it" + ) + continue + violation = floor_violation(result.version, php_floors) + if violation: + failures.append(f"{container.name}: PHP {violation}") + enabled = [name for name, on in result.settings.items() if on] + if not enabled: + continue + message = f"{container.name}: {', '.join(enabled)} on" + if must_harden: + failures.append(f"{message}, the php_hardening ini is not in effect") + elif in_hardened_stack: + infos.append(f"{message} (sidecar without php_hardening)") + return failures, infos + + +def main(argv=None) -> int: + args = parse_args(argv) + php_floors = json.loads(args.floors)["php"] + hardened = json.loads(args.hardened) + failures, infos = check(running_containers(), php_floors, hardened, probe_php) + for line in infos: + print(f"â„đïļ {line}") + for line in failures: + print(f"❌ {line}") + if failures: + print(f"ðŸšĻ {len(failures)} runtime finding(s).") + return 1 + print("✅ Every PHP runtime is at or above its floor and hardened where declared.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/roles/sys-ctl-hlth-runtime/lookup_plugins/php_hardened_services.py b/roles/sys-ctl-hlth-runtime/lookup_plugins/php_hardened_services.py new file mode 100644 index 0000000000..86357eeec7 --- /dev/null +++ b/roles/sys-ctl-hlth-runtime/lookup_plugins/php_hardened_services.py @@ -0,0 +1,70 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +from utils.roles.entity.name import get_entity_name + +HARDENING_VOLUME = "php_hardening" + + +def hardened_services(volumes: Any) -> list[str]: + """Return the services that mount the shared PHP hardening ini. + + Args: + volumes: the role's canonical ``meta/volumes.yml`` mapping. + + Returns: + The sorted service keys listed under ``php_hardening.mounts``. + """ + if not isinstance(volumes, Mapping): + return [] + entry = volumes.get(HARDENING_VOLUME) + if not isinstance(entry, Mapping): + return [] + return sorted( + { + str(mount["service"]) + for mount in entry.get("mounts") or [] + if isinstance(mount, Mapping) and mount.get("service") + } + ) + + +class LookupModule(LookupBase): + """``lookup('php_hardened_services', group_names=)``. + + Args: + group_names: the deployed role ids. + + Returns: + ``{entity: [service, ...]}`` for every role whose ``meta/volumes.yml`` + declares ``php_hardening``; the entity is the compose project and + swarm stack name. + """ + + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[dict[str, list[str]]]: + group_names = kwargs.get("group_names") + if not isinstance(group_names, (list, tuple)): + raise AnsibleError( + "php_hardened_services: group_names must be a list of role ids" + ) + + volume = lookup_loader.get( + "volume", loader=self._loader, templar=getattr(self, "_templar", None) + ) + result: dict[str, list[str]] = {} + for role_id in sorted({str(name) for name in group_names}): + services = hardened_services(volume.run([role_id], variables=variables)[0]) + if services: + result[get_entity_name(role_id)] = services + return [result] diff --git a/roles/sys-ctl-hlth-runtime/meta/main.yml b/roles/sys-ctl-hlth-runtime/meta/main.yml new file mode 100644 index 0000000000..a4656c3c54 --- /dev/null +++ b/roles/sys-ctl-hlth-runtime/meta/main.yml @@ -0,0 +1,31 @@ +--- +galaxy_info: + author: Kevin Veen-Birkenbach + description: Systemd-timed monitor for containers running PHP below its security floor or without the shared PHP hardening + company: | + Kevin Veen-Birkenbach + https://www.veen.world + license: Infinito.Nexus Community License (Non-Commercial) + min_ansible_version: "2.9" + platforms: + - name: ArchLinux + versions: + - all + - name: Debian + versions: + - all + - name: EL + versions: + - all + - name: Fedora + versions: + - all + - name: Ubuntu + versions: + - all + galaxy_tags: + - monitor + - docker + - php + - security + - systemd diff --git a/roles/sys-ctl-hlth-runtime/meta/services.yml b/roles/sys-ctl-hlth-runtime/meta/services.yml new file mode 100644 index 0000000000..754ea0ad3a --- /dev/null +++ b/roles/sys-ctl-hlth-runtime/meta/services.yml @@ -0,0 +1,8 @@ +--- +runtime: + lifecycle: beta + required_by: + compose: + categories: [web] + swarm: + categories: [web] diff --git a/roles/sys-ctl-hlth-runtime/tasks/00_core.yml b/roles/sys-ctl-hlth-runtime/tasks/00_core.yml new file mode 100644 index 0000000000..480b4fce3d --- /dev/null +++ b/roles/sys-ctl-hlth-runtime/tasks/00_core.yml @@ -0,0 +1,19 @@ +--- +- name: 📂 Include dependency 'sys-ctl-alm-compose' + include_role: + name: sys-ctl-alm-compose + when: run_once_sys_ctl_alm_compose is not defined + +- include_role: + name: sys-service + vars: + system_service_on_calendar: "{{ SYS_SCHEDULE_HEALTH_RUNTIME }}" + system_service_timer_enabled: true + system_service_tpl_on_failure: "{{ SYS_SERVICE_ON_FAILURE_COMPOSE }}" + system_service_tpl_exec_start: >- + {{ system_service_script_exec }} + --floors '{{ HEALTH_RUNTIME_FLOORS | to_json }}' + --hardened '{{ HEALTH_RUNTIME_PHP_HARDENED | to_json }}' + system_service_force_flush_final: false + +- include_tasks: utils/once/flag.yml diff --git a/roles/sys-ctl-hlth-runtime/tasks/main.yml b/roles/sys-ctl-hlth-runtime/tasks/main.yml new file mode 100644 index 0000000000..53fc6c85ca --- /dev/null +++ b/roles/sys-ctl-hlth-runtime/tasks/main.yml @@ -0,0 +1,3 @@ +--- +- include_tasks: 00_core.yml + when: run_once_sys_ctl_hlth_runtime is not defined diff --git a/roles/sys-ctl-hlth-runtime/vars/main.yml b/roles/sys-ctl-hlth-runtime/vars/main.yml new file mode 100644 index 0000000000..90c7f0fc1c --- /dev/null +++ b/roles/sys-ctl-hlth-runtime/vars/main.yml @@ -0,0 +1,10 @@ +--- +system_service_id: sys-ctl-hlth-runtime +# Lowest patched release per runtime line; a line older than every listed one is end of life +HEALTH_RUNTIME_FLOORS: + php: + "8.2": "8.2.35" + "8.3": "8.3.36" + "8.4": "8.4.27" + "8.5": "8.5.12" +HEALTH_RUNTIME_PHP_HARDENED: "{{ lookup('php_hardened_services', group_names=lookup('deployment').deployed) }}" diff --git a/roles/sys-svc-compose/tasks/main.yml b/roles/sys-svc-compose/tasks/main.yml index 6a69e41198..a836629fa9 100644 --- a/roles/sys-svc-compose/tasks/main.yml +++ b/roles/sys-svc-compose/tasks/main.yml @@ -10,6 +10,7 @@ list_or_shoot_roles: - sys-ctl-cln-docker - sys-ctl-hlth-container + - sys-ctl-hlth-runtime - sys-ctl-hlth-volumes - sys-ctl-rpr-container-hard diff --git a/tests/unit/python/cli/contributing/security/__init__.py b/tests/unit/python/cli/contributing/security/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/cli/contributing/security/test_runtimes.py b/tests/unit/python/cli/contributing/security/test_runtimes.py new file mode 100644 index 0000000000..5a7f913980 --- /dev/null +++ b/tests/unit/python/cli/contributing/security/test_runtimes.py @@ -0,0 +1,71 @@ +from __future__ import annotations + +import contextlib +import io +import unittest + +import cli.contributing.security.runtimes.__main__ as runtimes_main +from utils.docker.image.discovery import ImageRef + +FLOORS = {"8.2": "8.2.35", "8.3": "8.3.36", "8.4": "8.4.27", "8.5": "8.5.12"} + + +def _ref(role, service): + return ImageRef( + role=role, + service=service, + name=f"acme/{service}", + version="1.0", + source=f"docker.io/acme/{service}:1.0", + ) + + +class TestReport(unittest.TestCase): + def _report(self, refs, probed): + with contextlib.redirect_stdout(io.StringIO()) as out: + code = runtimes_main.report(refs, probed, FLOORS) + return code, out.getvalue() + + def test_an_eol_image_fails_the_report(self): + code, output = self._report( + [_ref("web-app-akaunting", "akaunting")], [["ENV PHP_VERSION=8.1.34"]] + ) + self.assertEqual(code, 1) + self.assertIn("runs the end-of-life line 8.1", output) + + def test_patched_images_and_images_without_php_pass(self): + code, _output = self._report( + [ + _ref("web-app-wordpress", "wordpress"), + _ref("svc-db-postgres", "postgres"), + ], + [["ENV PHP_VERSION=8.4.27"], ["ENV PG_VERSION=17.2"]], + ) + self.assertEqual(code, 0) + + def test_an_unanswered_image_fails_the_report(self): + code, output = self._report([_ref("web-app-lam", "lam")], [None]) + self.assertEqual(code, 1) + self.assertIn( + "web-app-lam:lam (docker.io/acme/lam:1.0): the registry gave no answer", + output, + ) + + def test_a_distro_line_without_patch_level_is_listed_but_passes(self): + code, output = self._report( + [_ref("web-app-lam", "lam")], [["RUN apt-get install -y php8.4-ldap"]] + ) + self.assertEqual(code, 0) + self.assertIn("PHP line 8.4: patch level not in the registry metadata", output) + + def test_an_eol_php_base_argument_fails_the_report(self): + code, output = self._report( + [_ref("web-app-fusiondirectory", "fusiondirectory")], + [["ARG PHP_BASE=7.4", "RUN |1 PHP_BASE=7.4 /bin/bash -c install"]], + ) + self.assertEqual(code, 1) + self.assertIn("PHP line 7.4: line 7.4 is end of life", output) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/sys-ctl-hlth-runtime/__init__.py b/tests/unit/python/roles/sys-ctl-hlth-runtime/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/sys-ctl-hlth-runtime/files/__init__.py b/tests/unit/python/roles/sys-ctl-hlth-runtime/files/__init__.py new file mode 100644 index 0000000000..087c384b57 --- /dev/null +++ b/tests/unit/python/roles/sys-ctl-hlth-runtime/files/__init__.py @@ -0,0 +1,5 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py b/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py new file mode 100644 index 0000000000..72782a207f --- /dev/null +++ b/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py @@ -0,0 +1,283 @@ +from __future__ import annotations + +import contextlib +import importlib.util +import io +import json +import subprocess +import sys +from types import SimpleNamespace +from unittest import TestCase, main, mock + +from . import PROJECT_ROOT + + +def _load_script(): + path = ( + PROJECT_ROOT + / "roles" + / "sys-ctl-hlth-runtime" + / "files" + / "python" + / "script.py" + ) + spec = importlib.util.spec_from_file_location("hlth_runtime_script", path) + module = importlib.util.module_from_spec(spec) + assert spec and spec.loader + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +SCRIPT = _load_script() +FLOORS = {"8.2": "8.2.35", "8.3": "8.3.36", "8.4": "8.4.27", "8.5": "8.5.12"} +MARKER = SCRIPT.PROBE_MARKER + + +def _container(name, stack=None, service=None): + return SCRIPT.Container(id=f"id-{name}", name=name, stack=stack, service=service) + + +def _probe(version, expose_php=False, upload_progress=False): + return SCRIPT.PhpProbe( + version=version, + settings={ + "expose_php": expose_php, + "session.upload_progress.enabled": upload_progress, + }, + ) + + +def _check(containers, probes, hardened=None): + return SCRIPT.check( + containers, FLOORS, hardened or {}, lambda container_id: probes[container_id] + ) + + +class TestFloorViolation(TestCase): + def test_a_version_at_its_floor_passes(self): + self.assertIsNone(SCRIPT.floor_violation("8.3.36", FLOORS)) + + def test_a_version_below_its_floor_fails(self): + self.assertIn( + "below the security floor 8.4.27", SCRIPT.floor_violation("8.4.26", FLOORS) + ) + + def test_php_8_1_is_end_of_life(self): + self.assertIn("end-of-life line 8.1", SCRIPT.floor_violation("8.1.34", FLOORS)) + + def test_php_7_4_is_end_of_life(self): + self.assertIn("end-of-life line 7.4", SCRIPT.floor_violation("7.4.33", FLOORS)) + + def test_a_line_newer_than_every_floor_passes(self): + self.assertIsNone(SCRIPT.floor_violation("8.6.0", FLOORS)) + + def test_a_distro_revision_suffix_is_ignored(self): + self.assertIsNone(SCRIPT.floor_violation("8.4.27-1+deb13u1", FLOORS)) + + def test_an_unparsable_version_fails(self): + self.assertIn("unparsable", SCRIPT.floor_violation("eight", FLOORS)) + + +class TestParseProbe(TestCase): + def test_startup_warnings_before_the_probe_line_are_skipped(self): + stdout = f"PHP Warning: Module 'redis' already loaded\n{MARKER}|8.3.36||0\n" + self.assertEqual(SCRIPT.parse_probe(stdout), _probe("8.3.36")) + + def test_enabled_settings_are_reported_on(self): + self.assertEqual( + SCRIPT.parse_probe(f"\n{MARKER}|8.4.27|1|1\n"), + _probe("8.4.27", expose_php=True, upload_progress=True), + ) + + def test_output_without_the_probe_line_raises(self): + with self.assertRaises(SCRIPT.ProbeError): + SCRIPT.parse_probe("Segmentation fault\n") + + def test_a_probe_line_with_missing_fields_raises(self): + with self.assertRaises(SCRIPT.ProbeError): + SCRIPT.parse_probe(f"{MARKER}|8.4.27\n") + + +class TestIdentity(TestCase): + def test_compose_labels_give_project_and_service(self): + labels = { + "com.docker.compose.project": "nextcloud", + "com.docker.compose.service": "cron", + } + self.assertEqual(SCRIPT.identity(labels), ("nextcloud", "cron")) + + def test_swarm_labels_strip_the_stack_prefix(self): + labels = { + "com.docker.stack.namespace": "nextcloud", + "com.docker.swarm.service.name": "nextcloud_nextcloud", + } + self.assertEqual(SCRIPT.identity(labels), ("nextcloud", "nextcloud")) + + def test_a_container_without_labels_has_no_identity(self): + self.assertEqual(SCRIPT.identity(None), (None, None)) + + +class TestCheck(TestCase): + def test_an_eol_runtime_outside_any_stack_fails(self): + failures, _infos = _check( + [_container("legacy")], {"id-legacy": _probe("8.1.34")} + ) + self.assertEqual(failures, ["legacy: PHP 8.1.34 runs the end-of-life line 8.1"]) + + def test_a_patched_runtime_passes(self): + self.assertEqual( + _check([_container("app")], {"id-app": _probe("8.5.12")}), ([], []) + ) + + def test_a_hardened_service_with_expose_php_on_fails(self): + failures, _infos = _check( + [_container("wp", "wordpress", "wordpress")], + {"id-wp": _probe("8.4.27", expose_php=True)}, + {"wordpress": ["wordpress"]}, + ) + self.assertEqual( + failures, ["wp: expose_php on, the php_hardening ini is not in effect"] + ) + + def test_a_hardened_service_with_both_settings_off_passes(self): + self.assertEqual( + _check( + [_container("wp", "wordpress", "wordpress")], + {"id-wp": _probe("8.4.27")}, + {"wordpress": ["wordpress"]}, + ), + ([], []), + ) + + def test_a_sidecar_of_a_hardened_stack_is_info_only(self): + failures, infos = _check( + [_container("nc-cron", "nextcloud", "cron")], + {"id-nc-cron": _probe("8.4.27", upload_progress=True)}, + {"nextcloud": ["nextcloud"]}, + ) + self.assertEqual(failures, []) + self.assertEqual( + infos, + [ + "nc-cron: session.upload_progress.enabled on (sidecar without php_hardening)" + ], + ) + + def test_a_container_outside_hardened_stacks_is_not_judged_on_settings(self): + self.assertEqual( + _check( + [_container("app", "other", "app")], + {"id-app": _probe("8.4.27", expose_php=True)}, + {"wordpress": ["wordpress"]}, + ), + ([], []), + ) + + def test_a_hardened_service_without_php_fails(self): + failures, _infos = _check( + [_container("wp", "wordpress", "wordpress")], + {"id-wp": None}, + {"wordpress": ["wordpress"]}, + ) + self.assertEqual( + failures, ["wp: declares php_hardening but has no php to verify it"] + ) + + def test_a_container_without_php_is_skipped(self): + self.assertEqual(_check([_container("db")], {"id-db": None}), ([], [])) + + def test_a_probe_error_is_a_failure(self): + def broken(_container_id): + raise SCRIPT.ProbeError("php exited 255: boom") + + failures, _infos = SCRIPT.check([_container("app")], FLOORS, {}, broken) + self.assertEqual(failures, ["app: php exited 255: boom"]) + + +class TestProbePhp(TestCase): + def _run(self, returncode, stdout="", stderr=""): + completed = SimpleNamespace(returncode=returncode, stdout=stdout, stderr=stderr) + with mock.patch.object(SCRIPT.subprocess, "run", return_value=completed): + return SCRIPT.probe_php("abc") + + def test_exit_127_means_no_php(self): + self.assertIsNone(self._run(127, stderr="executable file not found")) + + def test_exit_126_means_no_php(self): + self.assertIsNone(self._run(126, stderr="OCI runtime exec failed")) + + def test_another_non_zero_exit_raises(self): + with self.assertRaises(SCRIPT.ProbeError): + self._run(255, stderr="PHP Fatal error") + + def test_a_timeout_raises(self): + with ( + mock.patch.object( + SCRIPT.subprocess, + "run", + side_effect=subprocess.TimeoutExpired(cmd="php", timeout=60), + ), + self.assertRaises(SCRIPT.ProbeError), + ): + SCRIPT.probe_php("abc") + + +class TestMain(TestCase): + def _main(self, php_versions): + """Run main() against a fake engine. + + Args: + php_versions: ``{container name: PHP version or None}``. + """ + inspected = [ + { + "Id": f"id-{name}", + "Name": f"/{name}", + "Config": {"Labels": None}, + } + for name in php_versions + ] + + def fake_run(args, **_kwargs): + if args[:2] == ["container", "ps"]: + return SimpleNamespace( + returncode=0, + stdout="\n".join(i["Id"] for i in inspected), + stderr="", + ) + if args[:2] == ["container", "inspect"]: + return SimpleNamespace( + returncode=0, stdout=json.dumps(inspected), stderr="" + ) + if args[:2] == ["container", "exec"]: + version = php_versions[args[2].removeprefix("id-")] + if version is None: + return SimpleNamespace( + returncode=127, stdout="", stderr="not found" + ) + return SimpleNamespace( + returncode=0, stdout=f"\n{MARKER}|{version}||0\n", stderr="" + ) + raise AssertionError(f"unexpected command {args}") + + argv = ["--floors", json.dumps({"php": FLOORS}), "--hardened", "{}"] + with ( + mock.patch.object(SCRIPT.subprocess, "run", side_effect=fake_run), + contextlib.redirect_stdout(io.StringIO()) as out, + ): + code = SCRIPT.main(argv) + return code, out.getvalue() + + def test_main_fails_on_an_eol_runtime(self): + code, output = self._main({"akaunting": "8.1.34", "postgres": None}) + self.assertEqual(code, 1) + self.assertIn("akaunting: PHP 8.1.34 runs the end-of-life line 8.1", output) + + def test_main_passes_when_every_runtime_is_patched(self): + code, _output = self._main({"wordpress": "8.4.27", "postgres": None}) + self.assertEqual(code, 0) + + +if __name__ == "__main__": + main() diff --git a/tests/unit/python/roles/sys-ctl-hlth-runtime/lookup_plugins/__init__.py b/tests/unit/python/roles/sys-ctl-hlth-runtime/lookup_plugins/__init__.py new file mode 100644 index 0000000000..087c384b57 --- /dev/null +++ b/tests/unit/python/roles/sys-ctl-hlth-runtime/lookup_plugins/__init__.py @@ -0,0 +1,5 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/sys-ctl-hlth-runtime/lookup_plugins/test_php_hardened_services.py b/tests/unit/python/roles/sys-ctl-hlth-runtime/lookup_plugins/test_php_hardened_services.py new file mode 100644 index 0000000000..113c602e11 --- /dev/null +++ b/tests/unit/python/roles/sys-ctl-hlth-runtime/lookup_plugins/test_php_hardened_services.py @@ -0,0 +1,90 @@ +from __future__ import annotations + +import importlib.util +import sys +import unittest +from unittest import mock + +from ansible.errors import AnsibleError + +from . import PROJECT_ROOT + + +def _load_module(): + path = ( + PROJECT_ROOT + / "roles" + / "sys-ctl-hlth-runtime" + / "lookup_plugins" + / "php_hardened_services.py" + ) + spec = importlib.util.spec_from_file_location("php_hardened_services_lookup", path) + module = importlib.util.module_from_spec(spec) + assert spec and spec.loader + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +MODULE = _load_module() + +HARDENING = { + "type": "config", + "source": "{{ FILE_PHP_HARDENING_INI }}", + "mounts": [ + {"service": "nextcloud", "target": "/usr/local/etc/php/conf.d/zz.ini"}, + ], +} + + +class TestHardenedServices(unittest.TestCase): + def test_lists_every_mounting_service_once(self): + entry = dict( + HARDENING, + mounts=[ + {"service": "web", "target": "/a"}, + {"service": "php", "target": "/b"}, + {"service": "web", "target": "/c"}, + ], + ) + self.assertEqual( + MODULE.hardened_services({"php_hardening": entry}), ["php", "web"] + ) + + def test_a_role_without_php_hardening_has_none(self): + self.assertEqual(MODULE.hardened_services({"data": {"type": "volume"}}), []) + + def test_the_fpm_drop_in_does_not_count(self): + self.assertEqual(MODULE.hardened_services({"php_fpm_hardening": HARDENING}), []) + + +class TestLookup(unittest.TestCase): + def _run(self, volumes_by_role, **kwargs): + lookup = MODULE.LookupModule() + lookup._loader = mock.MagicMock() + lookup._templar = mock.MagicMock() + volume = mock.MagicMock() + volume.run.side_effect = lambda terms, **_kw: [volumes_by_role[terms[0]]] + with mock.patch.object(MODULE, "lookup_loader") as loader: + loader.get.return_value = volume + return lookup.run([], variables={}, **kwargs)[0] + + def test_maps_hardened_roles_to_their_entity(self): + result = self._run( + {"web-app-nextcloud": {"php_hardening": HARDENING}, "svc-db-postgres": {}}, + group_names=["web-app-nextcloud", "svc-db-postgres"], + ) + self.assertEqual(result, {"nextcloud": ["nextcloud"]}) + + def test_no_deployed_php_role_yields_an_empty_map(self): + self.assertEqual( + self._run({"svc-db-postgres": {}}, group_names=["svc-db-postgres"]), {} + ) + + def test_missing_group_names_raises(self): + with self.assertRaises(AnsibleError): + self._run({}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/docker/test_image_runtime.py b/tests/unit/python/utils/docker/test_image_runtime.py new file mode 100644 index 0000000000..74d9720a88 --- /dev/null +++ b/tests/unit/python/utils/docker/test_image_runtime.py @@ -0,0 +1,215 @@ +from __future__ import annotations + +import io +import json +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from utils.docker.image import runtime + +FLOORS = {"8.2": "8.2.35", "8.3": "8.3.36", "8.4": "8.4.27", "8.5": "8.5.12"} + + +def _php(version=None, lines=()): + return runtime.PhpRuntime(version=version, lines=tuple(lines)) + + +class TestPhpRuntime(unittest.TestCase): + def test_reads_php_version_from_an_env_instruction(self): + self.assertEqual( + runtime.php_runtime( + ["ENV PHP_INI_DIR=/usr/local/etc/php", "ENV PHP_VERSION=8.4.15"] + ), + _php("8.4.15"), + ) + + def test_the_last_php_version_wins(self): + self.assertEqual( + runtime.php_runtime( + ["ENV PHP_VERSION=8.3.1", "ENV PHP_VERSION=8.4.27"] + ).version, + "8.4.27", + ) + + def test_alpine_packages_name_their_line(self): + found = runtime.php_runtime( + ["RUN /bin/sh -c apk add php83 php83-fpm php83-ldap"] + ) + self.assertEqual(found, _php(lines=["8.3"])) + + def test_debian_packages_name_their_line(self): + found = runtime.php_runtime( + ["RUN apt-get install -y php8.4-cli libapache2-mod-php8.4 php8.4-ldap"] + ) + self.assertEqual(found, _php(lines=["8.4"])) + + def test_an_unversioned_alpine_php7_package_names_its_major(self): + self.assertEqual( + runtime.php_runtime(["RUN apk add php7 php7-fpm"]), _php(lines=["7"]) + ) + + def test_a_php_base_build_argument_names_its_line(self): + self.assertEqual( + runtime.php_runtime( + ["ARG PHP_BASE=7.4", "RUN |1 PHP_BASE=7.4 /bin/bash -c build"] + ), + _php(lines=["7.4"]), + ) + + def test_a_php_directory_outside_a_package_install_is_not_php(self): + self.assertIsNone( + runtime.php_runtime( + ["COPY /app/snuffleupagus.so /usr/lib/php83/modules/ # buildkit"] + ) + ) + + def test_a_pinned_alpine_package_names_its_line(self): + found = runtime.php_runtime(["RUN apk add --no-cache php84=8.4.27-r0 nginx;"]) + self.assertEqual(found, _php(lines=["8.4"])) + + def test_php_paths_are_not_packages(self): + self.assertIsNone( + runtime.php_runtime( + ['RUN mkdir -p "$PHP_INI_DIR/conf.d" /usr/local/etc/php'] + ) + ) + + def test_an_image_without_php_has_no_runtime(self): + self.assertIsNone( + runtime.php_runtime( + ["ENV PG_VERSION=17.2", "RUN apt-get install -y postgresql"] + ) + ) + + +class TestPhpFinding(unittest.TestCase): + def test_a_version_below_its_floor_is_a_finding(self): + self.assertIn( + "below the security floor 8.4.27", + runtime.php_finding(_php("8.4.15"), FLOORS), + ) + + def test_a_version_at_its_floor_is_fine(self): + self.assertIsNone(runtime.php_finding(_php("8.2.35"), FLOORS)) + + def test_php_8_1_is_end_of_life(self): + self.assertIn( + "end-of-life line 8.1", runtime.php_finding(_php("8.1.34"), FLOORS) + ) + + def test_a_line_newer_than_every_floor_is_fine(self): + self.assertIsNone(runtime.php_finding(_php("8.6.0"), FLOORS)) + + def test_a_distro_php7_is_end_of_life(self): + self.assertEqual( + runtime.php_finding(_php(lines=["7"]), FLOORS), "line 7 is end of life" + ) + + def test_a_distro_php_8_1_is_end_of_life(self): + self.assertEqual( + runtime.php_finding(_php(lines=["8.1"]), FLOORS), "line 8.1 is end of life" + ) + + def test_a_supported_distro_line_is_no_finding(self): + self.assertIsNone(runtime.php_finding(_php(lines=["8.3"]), FLOORS)) + + +class TestLoadPhpFloors(unittest.TestCase): + def test_reads_the_php_floors_from_the_vars_file(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "main.yml" + path.write_text( + "HEALTH_RUNTIME_FLOORS:\n php:\n '8.4': '8.4.27'\n", + encoding="utf-8", + ) + with mock.patch.object(runtime, "FLOORS_FILE", path): + self.assertEqual(runtime.load_php_floors(), {"8.4": "8.4.27"}) + + +class TestBuildInstructions(unittest.TestCase): + def test_a_docker_hub_tag_is_read_through_the_hub_api(self): + with ( + mock.patch.object( + runtime, "_hub_instructions", return_value=["ENV A=1"] + ) as hub, + mock.patch.object(runtime, "config_blob") as blob, + ): + found = runtime.build_instructions( + "docker.io/wordpress", "6.8", os_name="linux", architecture="amd64" + ) + self.assertEqual(found, ["ENV A=1"]) + hub.assert_called_once_with("library/wordpress", "6.8", "linux", "amd64") + blob.assert_not_called() + + def test_another_registry_is_read_through_the_config_blob(self): + blob = { + "history": [{"created_by": "RUN apk add php84"}], + "config": {"Env": ["PHP_VERSION=8.4.27"]}, + } + with mock.patch.object(runtime, "config_blob", return_value=blob): + found = runtime.build_instructions( + "ghcr.io/acme/app", "1.0", os_name="linux", architecture="amd64" + ) + self.assertEqual(found, ["RUN apk add php84", "ENV PHP_VERSION=8.4.27"]) + + def test_a_docker_hub_digest_pin_is_read_through_the_config_blob(self): + with ( + mock.patch.object(runtime, "_hub_instructions") as hub, + mock.patch.object(runtime, "config_blob", return_value=None), + ): + found = runtime.build_instructions( + "docker.io/acme/app", + "sha256:" + "a" * 64, + os_name="linux", + architecture="amd64", + ) + self.assertIsNone(found) + hub.assert_not_called() + + +class TestHubInstructions(unittest.TestCase): + def _respond(self, payload): + response = mock.MagicMock() + response.__enter__.return_value = io.BytesIO(json.dumps(payload).encode()) + return mock.patch.object( + runtime.urllib.request, "urlopen", return_value=response + ) + + def test_picks_the_layers_of_the_requested_platform(self): + payload = [ + { + "os": "linux", + "architecture": "arm64", + "layers": [{"instruction": "ENV PHP_VERSION=1"}], + }, + { + "os": "linux", + "architecture": "amd64", + "layers": [{"instruction": "ENV PHP_VERSION=2"}], + }, + ] + with self._respond(payload): + found = runtime._hub_instructions("library/php", "8.4", "linux", "amd64") + self.assertEqual(found, ["ENV PHP_VERSION=2"]) + + def test_a_tag_without_the_platform_is_unanswered(self): + with self._respond([{"os": "linux", "architecture": "arm64", "layers": []}]): + self.assertIsNone( + runtime._hub_instructions("library/php", "8.4", "linux", "amd64") + ) + + def test_a_network_error_is_unanswered(self): + with mock.patch.object( + runtime.urllib.request, + "urlopen", + side_effect=runtime.urllib.error.URLError("down"), + ): + self.assertIsNone( + runtime._hub_instructions("library/php", "8.4", "linux", "amd64") + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/docker/test_registry_healthcheck.py b/tests/unit/python/utils/docker/test_registry_healthcheck.py index c6175389ef..c01616f282 100644 --- a/tests/unit/python/utils/docker/test_registry_healthcheck.py +++ b/tests/unit/python/utils/docker/test_registry_healthcheck.py @@ -120,5 +120,24 @@ class TestProbeSource(_Isolated, unittest.TestCase): self.assertEqual(source, "none") +class TestConfigBlob(_Isolated, unittest.TestCase): + def test_the_whole_blob_comes_back_with_its_history(self) -> None: + blob = { + "config": {"Env": ["PHP_VERSION=8.4.27"]}, + "history": [{"created_by": "x"}], + } + with ( + self.serve(INDEX, blob), + mock.patch.object( + registry, "fetch_manifest", side_effect=[INDEX, MANIFEST] + ), + ): + self.assertEqual(registry.config_blob("php", "8.4", "linux", "amd64"), blob) + + def test_an_index_without_the_platform_is_indeterminate(self) -> None: + with self.serve(INDEX, {"config": {}}): + self.assertIsNone(registry.config_blob("php", "8.4", "linux", "riscv64")) + + if __name__ == "__main__": unittest.main() diff --git a/utils/docker/image/runtime.py b/utils/docker/image/runtime.py new file mode 100644 index 0000000000..bb0fc8d9c3 --- /dev/null +++ b/utils/docker/image/runtime.py @@ -0,0 +1,194 @@ +from __future__ import annotations + +import http.client +import json +import re +import urllib.error +import urllib.request +from dataclasses import dataclass +from urllib.parse import quote + +from utils.cache import PROJECT_ROOT +from utils.cache.yaml import load_yaml_any +from utils.docker.image.pin import is_digest +from utils.docker.image.ref import DOCKER_HUB_REGISTRIES, split_registry_and_name +from utils.docker.registry import config_blob +from utils.roles.mapping import ROLE_FILE_VARS_MAIN + +FLOORS_FILE = PROJECT_ROOT / "roles" / "sys-ctl-hlth-runtime" / ROLE_FILE_VARS_MAIN +FLOORS_KEY = "HEALTH_RUNTIME_FLOORS" +HUB_API = "https://hub.docker.com/v2" +USER_AGENT = "infinito-nexus-runtime-report" +PHP_VERSION_PATTERN = re.compile(r"\bPHP_VERSION=([0-9][^\s\"';]*)") +PHP_BASE_PATTERN = re.compile(r"\bPHP_BASE=(\d+\.\d+)(?![\d.])") +PACKAGE_INSTALL_PATTERN = re.compile( + r"\b(?:apk\s+add|(?:apt-get|apt|dnf|microdnf|yum)\s+(?:-\S+\s+)*install)\b" +) +PHP_PACKAGE_PATTERN = re.compile( + r"(? dict[str, str]: + """Return ``{".": ""}`` from the SPOT.""" + return load_yaml_any(str(FLOORS_FILE))[FLOORS_KEY]["php"] + + +def _hub_instructions( + repository: str, tag: str, os_name: str, architecture: str +) -> list[str] | None: + url = ( + f"{HUB_API}/repositories/{quote(repository, safe='/')}" + f"/tags/{quote(tag, safe='')}/images" + ) + request = urllib.request.Request( # noqa: S310 - https request to hub.docker.com + url, headers={"User-Agent": USER_AGENT, "Accept": "application/json"} + ) + try: + with urllib.request.urlopen(request, timeout=15) as response: # noqa: S310 - https request to hub.docker.com + images = json.loads(response.read().decode()) + except ( + urllib.error.URLError, + OSError, + http.client.HTTPException, + json.JSONDecodeError, + UnicodeDecodeError, + ): + return None + if not isinstance(images, list): + return None + for image in images: + if ( + isinstance(image, dict) + and image.get("os") == os_name + and image.get("architecture") == architecture + ): + return [ + str(layer.get("instruction") or "") + for layer in image.get("layers") or [] + if isinstance(layer, dict) + ] + return None + + +def _oci_instructions( + image: str, reference: str, os_name: str, architecture: str +) -> list[str] | None: + blob = config_blob(image, reference, os_name, architecture) + if blob is None: + return None + history = [ + str(step.get("created_by") or "") + for step in blob.get("history") or [] + if isinstance(step, dict) + ] + env = [f"ENV {item}" for item in (blob.get("config") or {}).get("Env") or []] + return history + env + + +def build_instructions( + image: str, + reference: str, + *, + os_name: str, + architecture: str, +) -> list[str] | None: + """Return the build instructions of ``image:reference`` without pulling it. + + Args: + image: image name, with or without registry host. + reference: tag or digest. + os_name: platform to resolve a multi-arch index to. + architecture: platform to resolve a multi-arch index to. + + Returns: + The image's history plus its final ``ENV`` lines, or ``None`` when the + registry gave no answer. A Docker Hub tag is read through the Hub API, + which a pull rate limit does not meter; every other image through its + OCI config blob. + """ + parsed = split_registry_and_name(image) + if parsed is None: + return None + registry, name = parsed + on_hub = registry is None or registry in DOCKER_HUB_REGISTRIES + if on_hub and not is_digest(reference): + repository = name if "/" in name else f"library/{name}" + return _hub_instructions(repository, reference, os_name, architecture) + return _oci_instructions(image, reference, os_name, architecture) + + +def php_runtime(instructions: list[str]) -> PhpRuntime | None: + """Read the PHP an image ships from its build instructions. + + Args: + instructions: see :func:`build_instructions`. + + Returns: + The last ``PHP_VERSION`` set and the lines of the distro PHP packages + and ``PHP_BASE`` arguments, or ``None`` when none of them appears. + """ + version = None + lines: set[str] = set() + for instruction in instructions: + for match in PHP_VERSION_PATTERN.finditer(instruction): + version = match.group(1) + lines.update(PHP_BASE_PATTERN.findall(instruction)) + if not PACKAGE_INSTALL_PATTERN.search(instruction): + continue + for major, minor in PHP_PACKAGE_PATTERN.findall(instruction): + lines.add(f"{major}.{minor}" if minor else major) + if version is None and not lines: + return None + return PhpRuntime(version=version, lines=tuple(sorted(lines))) + + +def _numbers(text: str) -> tuple[int, ...]: + return tuple(int(part) for part in text.split(".")) + + +def php_finding(runtime: PhpRuntime, floors: dict[str, str]) -> str | None: + """Judge an image's PHP against the floors. + + Args: + runtime: see :func:`php_runtime`. + floors: see :func:`load_php_floors`. + + Returns: + ``None`` when nothing is below its floor, otherwise the reason. A + version found only as a line is judged by that line. + """ + oldest = min(_numbers(line) for line in floors) + newest = max(_numbers(line) for line in floors) + if runtime.version is not None: + match = VERSION_PATTERN.match(runtime.version) + if match is None: + return f"unparsable PHP_VERSION {runtime.version!r}" + current = tuple(int(part) for part in match.groups()) + line = f"{current[0]}.{current[1]}" + if line in floors: + if current < _numbers(floors[line]): + return f"{runtime.version} is below the security floor {floors[line]}" + return None + if current[:2] > newest: + return None + return f"{runtime.version} runs the end-of-life line {line}" + eol = [line for line in runtime.lines if _numbers(line) < oldest] + if eol: + return f"line {', '.join(eol)} is end of life" + return None diff --git a/utils/docker/registry.py b/utils/docker/registry.py index 7827e546e0..5ddd2cd327 100644 --- a/utils/docker/registry.py +++ b/utils/docker/registry.py @@ -307,9 +307,22 @@ def _fetch_blob(image: str, digest: str) -> dict | None: return parsed if isinstance(parsed, dict) else None -def _healthcheck_at( +def config_blob( image: str, reference: str, os_name: str, architecture: str ) -> dict | None: + """Return the OCI config blob of ``image:reference`` from its registry. + + Args: + image: image name, with or without registry host. + reference: tag or digest. + os_name: platform to resolve a multi-arch index to. + architecture: platform to resolve a multi-arch index to. + + Returns: + The parsed blob with ``config`` and ``history``, or ``None`` on any + indeterminate outcome (see :func:`fetch_manifest`) and on an index + without a matching platform. + """ doc = fetch_manifest(image, reference) if doc is None: return None @@ -324,7 +337,13 @@ def _healthcheck_at( config_digest = (doc.get("config") or {}).get("digest") if not isinstance(config_digest, str) or not config_digest: return None - blob = _fetch_blob(image, config_digest) + return _fetch_blob(image, config_digest) + + +def _healthcheck_at( + image: str, reference: str, os_name: str, architecture: str +) -> dict | None: + blob = config_blob(image, reference, os_name, architecture) if blob is None: return None return (blob.get("config") or {}).get("Healthcheck") or {} From feac35a5ead59ff1945cdbc6db1175f893074a70 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 11:47:41 +0100 Subject: [PATCH 03/13] fix(sys-ctl-hlth-runtime): deploy only on container hosts and drop the bare Docker Hub API literal Two CI failures on PR #1265 (run 40834164415): - Chunk 0 / SuiteCRM#2 (swarm): the post-load flush included sys-ctl-hlth-runtime on every play host, the NFS server too, which never gets sys-svc-container and therefore has no `container` CLI. The unit died with FileNotFoundError: 'container'. The role entry now runs only where a container runtime exists: in compose mode, or on swarm nodes ('svc-swarm-node' in group_names), the same role-entry host scoping that sys-ctl-hlth-csp and sys-ctl-hlth-webserver use with IS_STACK_HOST. Workers stay covered because PHP replicas can run there. - Workspace (ubuntu): tests/external/repository/test_urls_reachable.py probed the literal "https://hub.docker.com/v2" from utils/docker/image/runtime.py:20 and got HTTP 404. The constant is gone; the endpoint is written as one f-string at the call site, the way utils/update/docker.py:104 and utils/update/source.py do, which the URL test skips as a template. With the scheme now visible in the literal, ruff reported the noqa: S310 on urllib.request.Request as unused. Both test files that imported unittest twice (CodeQL) now use one `from unittest import ...` form. The run_once queue leak that spreads the stack host's post-load queue to every host is fixed separately on the updater line (70ed8a2e98); when it meets main, sys-ctl-hlth-runtime moves into sys-svc-container's queue. Co-Authored-By: Claude Opus 5.5 --- roles/sys-ctl-hlth-runtime/tasks/main.yml | 4 +++- .../lookup_plugins/test_php_hardened_services.py | 9 ++++----- .../python/utils/docker/test_image_runtime.py | 15 +++++++-------- utils/docker/image/runtime.py | 5 ++--- 4 files changed, 16 insertions(+), 17 deletions(-) diff --git a/roles/sys-ctl-hlth-runtime/tasks/main.yml b/roles/sys-ctl-hlth-runtime/tasks/main.yml index 53fc6c85ca..573d6392e5 100644 --- a/roles/sys-ctl-hlth-runtime/tasks/main.yml +++ b/roles/sys-ctl-hlth-runtime/tasks/main.yml @@ -1,3 +1,5 @@ --- - include_tasks: 00_core.yml - when: run_once_sys_ctl_hlth_runtime is not defined + when: + - run_once_sys_ctl_hlth_runtime is not defined + - DEPLOYMENT_MODE == 'compose' or 'svc-swarm-node' in group_names diff --git a/tests/unit/python/roles/sys-ctl-hlth-runtime/lookup_plugins/test_php_hardened_services.py b/tests/unit/python/roles/sys-ctl-hlth-runtime/lookup_plugins/test_php_hardened_services.py index 113c602e11..6b85ad6a6a 100644 --- a/tests/unit/python/roles/sys-ctl-hlth-runtime/lookup_plugins/test_php_hardened_services.py +++ b/tests/unit/python/roles/sys-ctl-hlth-runtime/lookup_plugins/test_php_hardened_services.py @@ -2,8 +2,7 @@ from __future__ import annotations import importlib.util import sys -import unittest -from unittest import mock +from unittest import TestCase, main, mock from ansible.errors import AnsibleError @@ -37,7 +36,7 @@ HARDENING = { } -class TestHardenedServices(unittest.TestCase): +class TestHardenedServices(TestCase): def test_lists_every_mounting_service_once(self): entry = dict( HARDENING, @@ -58,7 +57,7 @@ class TestHardenedServices(unittest.TestCase): self.assertEqual(MODULE.hardened_services({"php_fpm_hardening": HARDENING}), []) -class TestLookup(unittest.TestCase): +class TestLookup(TestCase): def _run(self, volumes_by_role, **kwargs): lookup = MODULE.LookupModule() lookup._loader = mock.MagicMock() @@ -87,4 +86,4 @@ class TestLookup(unittest.TestCase): if __name__ == "__main__": - unittest.main() + main() diff --git a/tests/unit/python/utils/docker/test_image_runtime.py b/tests/unit/python/utils/docker/test_image_runtime.py index 74d9720a88..9b7c7e7489 100644 --- a/tests/unit/python/utils/docker/test_image_runtime.py +++ b/tests/unit/python/utils/docker/test_image_runtime.py @@ -3,9 +3,8 @@ from __future__ import annotations import io import json import tempfile -import unittest from pathlib import Path -from unittest import mock +from unittest import TestCase, main, mock from utils.docker.image import runtime @@ -16,7 +15,7 @@ def _php(version=None, lines=()): return runtime.PhpRuntime(version=version, lines=tuple(lines)) -class TestPhpRuntime(unittest.TestCase): +class TestPhpRuntime(TestCase): def test_reads_php_version_from_an_env_instruction(self): self.assertEqual( runtime.php_runtime( @@ -84,7 +83,7 @@ class TestPhpRuntime(unittest.TestCase): ) -class TestPhpFinding(unittest.TestCase): +class TestPhpFinding(TestCase): def test_a_version_below_its_floor_is_a_finding(self): self.assertIn( "below the security floor 8.4.27", @@ -116,7 +115,7 @@ class TestPhpFinding(unittest.TestCase): self.assertIsNone(runtime.php_finding(_php(lines=["8.3"]), FLOORS)) -class TestLoadPhpFloors(unittest.TestCase): +class TestLoadPhpFloors(TestCase): def test_reads_the_php_floors_from_the_vars_file(self): with tempfile.TemporaryDirectory() as tmp: path = Path(tmp) / "main.yml" @@ -128,7 +127,7 @@ class TestLoadPhpFloors(unittest.TestCase): self.assertEqual(runtime.load_php_floors(), {"8.4": "8.4.27"}) -class TestBuildInstructions(unittest.TestCase): +class TestBuildInstructions(TestCase): def test_a_docker_hub_tag_is_read_through_the_hub_api(self): with ( mock.patch.object( @@ -169,7 +168,7 @@ class TestBuildInstructions(unittest.TestCase): hub.assert_not_called() -class TestHubInstructions(unittest.TestCase): +class TestHubInstructions(TestCase): def _respond(self, payload): response = mock.MagicMock() response.__enter__.return_value = io.BytesIO(json.dumps(payload).encode()) @@ -212,4 +211,4 @@ class TestHubInstructions(unittest.TestCase): if __name__ == "__main__": - unittest.main() + main() diff --git a/utils/docker/image/runtime.py b/utils/docker/image/runtime.py index bb0fc8d9c3..9b564fe51a 100644 --- a/utils/docker/image/runtime.py +++ b/utils/docker/image/runtime.py @@ -17,7 +17,6 @@ from utils.roles.mapping import ROLE_FILE_VARS_MAIN FLOORS_FILE = PROJECT_ROOT / "roles" / "sys-ctl-hlth-runtime" / ROLE_FILE_VARS_MAIN FLOORS_KEY = "HEALTH_RUNTIME_FLOORS" -HUB_API = "https://hub.docker.com/v2" USER_AGENT = "infinito-nexus-runtime-report" PHP_VERSION_PATTERN = re.compile(r"\bPHP_VERSION=([0-9][^\s\"';]*)") PHP_BASE_PATTERN = re.compile(r"\bPHP_BASE=(\d+\.\d+)(?![\d.])") @@ -53,10 +52,10 @@ def _hub_instructions( repository: str, tag: str, os_name: str, architecture: str ) -> list[str] | None: url = ( - f"{HUB_API}/repositories/{quote(repository, safe='/')}" + f"https://hub.docker.com/v2/repositories/{quote(repository, safe='/')}" f"/tags/{quote(tag, safe='')}/images" ) - request = urllib.request.Request( # noqa: S310 - https request to hub.docker.com + request = urllib.request.Request( url, headers={"User-Agent": USER_AGENT, "Accept": "application/json"} ) try: From d116dde6598045795dc6558d0b997f8ec58a159e Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 15:32:57 +0100 Subject: [PATCH 04/13] fix(sys-ctl-hlth-runtime): bound the engine calls and catch hidden PHP runtimes Three CodeRabbit findings on PR #1265: - script.py listed the running containers with `container ps` and `container inspect` without a timeout, so a hung engine kept the daily unit active forever and blocked the next timer run. Both calls now use EXEC_TIMEOUT_SECONDS; main turns a timeout or engine error into a one-line failure and exit 1 instead of a traceback. - runtime.py's PHP_PACKAGE_PATTERN requires a digit after "php", so an image installing an unversioned interpreter package (`php-cli`) and setting no PHP_VERSION was reported as PHP-free. The interpreter packages php, php-cli, php-fpm, php-cgi, php-phpdbg and libapache2-mod-php are now recorded as PhpRuntime.packages and reported with an unknown patch level; extension and library packages (php-mysql, php-pear, php-common, phpmyadmin) and paths do not count. - php_finding returned early for a patched PHP_VERSION, so an end-of-life package line installed next to it (e.g. php7) was never reported. The version only returns a finding now; otherwise the lines are judged too. Every finding has unit tests that fail on the previous code. Co-Authored-By: Claude Opus 5.5 --- .../security/runtimes/__main__.py | 7 ++- .../files/python/script.py | 9 +++- .../contributing/security/test_runtimes.py | 18 +++++++ .../sys-ctl-hlth-runtime/files/test_script.py | 43 ++++++++++++++++ .../python/utils/docker/test_image_runtime.py | 50 ++++++++++++++++++- utils/docker/image/runtime.py | 40 ++++++++++----- 6 files changed, 150 insertions(+), 17 deletions(-) diff --git a/cli/contributing/security/runtimes/__main__.py b/cli/contributing/security/runtimes/__main__.py index f73d606881..7495c6b12d 100755 --- a/cli/contributing/security/runtimes/__main__.py +++ b/cli/contributing/security/runtimes/__main__.py @@ -51,7 +51,12 @@ def report(refs: list[ImageRef], probed: list, floors: dict[str, str]) -> int: if runtime is None: continue with_php += 1 - php = runtime.version or f"line {', '.join(runtime.lines)}" + if runtime.version: + php = runtime.version + elif runtime.lines: + php = f"line {', '.join(runtime.lines)}" + else: + php = f"package {', '.join(runtime.packages)}" finding = php_finding(runtime, floors) if finding: findings += 1 diff --git a/roles/sys-ctl-hlth-runtime/files/python/script.py b/roles/sys-ctl-hlth-runtime/files/python/script.py index c371209ea4..0e94150a13 100755 --- a/roles/sys-ctl-hlth-runtime/files/python/script.py +++ b/roles/sys-ctl-hlth-runtime/files/python/script.py @@ -83,6 +83,7 @@ def running_containers() -> list[Container]: capture_output=True, text=True, check=True, + timeout=EXEC_TIMEOUT_SECONDS, ).stdout.split() if not ids: return [] @@ -92,6 +93,7 @@ def running_containers() -> list[Container]: capture_output=True, text=True, check=True, + timeout=EXEC_TIMEOUT_SECONDS, ).stdout ) containers = [] @@ -253,7 +255,12 @@ def main(argv=None) -> int: args = parse_args(argv) php_floors = json.loads(args.floors)["php"] hardened = json.loads(args.hardened) - failures, infos = check(running_containers(), php_floors, hardened, probe_php) + try: + containers = running_containers() + except (subprocess.TimeoutExpired, subprocess.CalledProcessError) as exc: + print(f"❌ listing the running containers failed: {exc}") + return 1 + failures, infos = check(containers, php_floors, hardened, probe_php) for line in infos: print(f"â„đïļ {line}") for line in failures: diff --git a/tests/unit/python/cli/contributing/security/test_runtimes.py b/tests/unit/python/cli/contributing/security/test_runtimes.py index 5a7f913980..8df5ed2f83 100644 --- a/tests/unit/python/cli/contributing/security/test_runtimes.py +++ b/tests/unit/python/cli/contributing/security/test_runtimes.py @@ -58,6 +58,24 @@ class TestReport(unittest.TestCase): self.assertEqual(code, 0) self.assertIn("PHP line 8.4: patch level not in the registry metadata", output) + def test_an_unversioned_php_package_is_listed_with_unknown_patch_level(self): + code, output = self._report( + [_ref("web-app-lam", "lam")], [["RUN apt-get install -y php-cli"]] + ) + self.assertEqual(code, 0) + self.assertIn( + "PHP package php-cli: patch level not in the registry metadata", output + ) + self.assertIn("1 ship PHP", output) + + def test_an_eol_package_line_fails_next_to_a_patched_php_version(self): + code, output = self._report( + [_ref("web-app-lam", "lam")], + [["ENV PHP_VERSION=8.4.27", "RUN apk add php7 php7-fpm"]], + ) + self.assertEqual(code, 1) + self.assertIn("PHP 8.4.27: line 7 is end of life", output) + def test_an_eol_php_base_argument_fails_the_report(self): code, output = self._report( [_ref("web-app-fusiondirectory", "fusiondirectory")], diff --git a/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py b/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py index 72782a207f..e6adc4671c 100644 --- a/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py +++ b/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py @@ -223,6 +223,24 @@ class TestProbePhp(TestCase): SCRIPT.probe_php("abc") +class TestRunningContainers(TestCase): + def test_every_engine_call_is_bounded_by_a_timeout(self): + timeouts = [] + + def fake_run(args, **kwargs): + timeouts.append(kwargs.get("timeout")) + if args[:2] == ["container", "ps"]: + return SimpleNamespace(returncode=0, stdout="id-app\n", stderr="") + inspected = [{"Id": "id-app", "Name": "/app", "Config": {"Labels": None}}] + return SimpleNamespace( + returncode=0, stdout=json.dumps(inspected), stderr="" + ) + + with mock.patch.object(SCRIPT.subprocess, "run", side_effect=fake_run): + SCRIPT.running_containers() + self.assertEqual(timeouts, [SCRIPT.EXEC_TIMEOUT_SECONDS] * 2) + + class TestMain(TestCase): def _main(self, php_versions): """Run main() against a fake engine. @@ -278,6 +296,31 @@ class TestMain(TestCase): code, _output = self._main({"wordpress": "8.4.27", "postgres": None}) self.assertEqual(code, 0) + def _main_on_engine_error(self, error): + argv = ["--floors", json.dumps({"php": FLOORS}), "--hardened", "{}"] + with ( + mock.patch.object(SCRIPT.subprocess, "run", side_effect=error), + contextlib.redirect_stdout(io.StringIO()) as out, + ): + code = SCRIPT.main(argv) + return code, out.getvalue() + + def test_main_fails_with_one_line_on_a_hung_engine(self): + code, output = self._main_on_engine_error( + subprocess.TimeoutExpired(cmd=["container", "ps"], timeout=60) + ) + self.assertEqual(code, 1) + self.assertEqual(len(output.splitlines()), 1) + self.assertIn("timed out after 60 seconds", output) + + def test_main_fails_with_one_line_on_a_failing_engine(self): + code, output = self._main_on_engine_error( + subprocess.CalledProcessError(returncode=1, cmd=["container", "ps"]) + ) + self.assertEqual(code, 1) + self.assertEqual(len(output.splitlines()), 1) + self.assertIn("returned non-zero exit status 1", output) + if __name__ == "__main__": main() diff --git a/tests/unit/python/utils/docker/test_image_runtime.py b/tests/unit/python/utils/docker/test_image_runtime.py index 9b7c7e7489..150bb040d8 100644 --- a/tests/unit/python/utils/docker/test_image_runtime.py +++ b/tests/unit/python/utils/docker/test_image_runtime.py @@ -11,8 +11,10 @@ from utils.docker.image import runtime FLOORS = {"8.2": "8.2.35", "8.3": "8.3.36", "8.4": "8.4.27", "8.5": "8.5.12"} -def _php(version=None, lines=()): - return runtime.PhpRuntime(version=version, lines=tuple(lines)) +def _php(version=None, lines=(), packages=()): + return runtime.PhpRuntime( + version=version, lines=tuple(lines), packages=tuple(packages) + ) class TestPhpRuntime(TestCase): @@ -75,6 +77,35 @@ class TestPhpRuntime(TestCase): ) ) + def test_an_unversioned_debian_runtime_package_is_php(self): + self.assertEqual( + runtime.php_runtime(["RUN apt-get install -y php-cli"]), + _php(packages=["php-cli"]), + ) + + def test_unversioned_runtime_packages_are_php(self): + found = runtime.php_runtime( + [ + "RUN dnf install -y php php-fpm php-mysqlnd", + "RUN apt-get install -y libapache2-mod-php php-cgi=2:8.2+93 \\", + ] + ) + self.assertEqual( + found, _php(packages=["libapache2-mod-php", "php", "php-cgi", "php-fpm"]) + ) + + def test_php_libraries_extensions_and_paths_are_not_a_runtime(self): + self.assertIsNone( + runtime.php_runtime( + [ + ( + "RUN apt-get install -y php-common php-pear php-mysql phpmyadmin" + " && docker-php-ext-install gd && cp php-fpm.conf /etc/php-fpm.d/" + ) + ] + ) + ) + def test_an_image_without_php_has_no_runtime(self): self.assertIsNone( runtime.php_runtime( @@ -114,6 +145,21 @@ class TestPhpFinding(TestCase): def test_a_supported_distro_line_is_no_finding(self): self.assertIsNone(runtime.php_finding(_php(lines=["8.3"]), FLOORS)) + def test_an_eol_line_fails_next_to_a_patched_php_version(self): + self.assertEqual( + runtime.php_finding(_php("8.4.27", lines=["7"]), FLOORS), + "line 7 is end of life", + ) + + def test_a_php_version_below_its_floor_outranks_an_eol_line(self): + self.assertIn( + "below the security floor 8.4.27", + runtime.php_finding(_php("8.4.15", lines=["7"]), FLOORS), + ) + + def test_an_unversioned_package_alone_is_no_finding(self): + self.assertIsNone(runtime.php_finding(_php(packages=["php-cli"]), FLOORS)) + class TestLoadPhpFloors(TestCase): def test_reads_the_php_floors_from_the_vars_file(self): diff --git a/utils/docker/image/runtime.py b/utils/docker/image/runtime.py index 9b564fe51a..b582f7761e 100644 --- a/utils/docker/image/runtime.py +++ b/utils/docker/image/runtime.py @@ -26,6 +26,9 @@ PACKAGE_INSTALL_PATTERN = re.compile( PHP_PACKAGE_PATTERN = re.compile( r"(? dict[str, str]: @@ -139,11 +147,13 @@ def php_runtime(instructions: list[str]) -> PhpRuntime | None: instructions: see :func:`build_instructions`. Returns: - The last ``PHP_VERSION`` set and the lines of the distro PHP packages - and ``PHP_BASE`` arguments, or ``None`` when none of them appears. + The last ``PHP_VERSION`` set, the lines of the distro PHP packages + and ``PHP_BASE`` arguments, and the unversioned interpreter packages, + or ``None`` when none of them appears. """ version = None lines: set[str] = set() + packages: set[str] = set() for instruction in instructions: for match in PHP_VERSION_PATTERN.finditer(instruction): version = match.group(1) @@ -152,9 +162,14 @@ def php_runtime(instructions: list[str]) -> PhpRuntime | None: continue for major, minor in PHP_PACKAGE_PATTERN.findall(instruction): lines.add(f"{major}.{minor}" if minor else major) - if version is None and not lines: + packages.update(PHP_UNVERSIONED_PACKAGE_PATTERN.findall(instruction)) + if version is None and not lines and not packages: return None - return PhpRuntime(version=version, lines=tuple(sorted(lines))) + return PhpRuntime( + version=version, + lines=tuple(sorted(lines)), + packages=tuple(sorted(packages)), + ) def _numbers(text: str) -> tuple[int, ...]: @@ -169,8 +184,10 @@ def php_finding(runtime: PhpRuntime, floors: dict[str, str]) -> str | None: floors: see :func:`load_php_floors`. Returns: - ``None`` when nothing is below its floor, otherwise the reason. A - version found only as a line is judged by that line. + ``None`` when nothing is below its floor, otherwise the reason. The + lines are judged next to ``PHP_VERSION``, so an end-of-life package + line fails an image whose ``PHP_VERSION`` is patched. Unversioned + packages alone are no finding: their patch level is unknown. """ oldest = min(_numbers(line) for line in floors) newest = max(_numbers(line) for line in floors) @@ -180,13 +197,10 @@ def php_finding(runtime: PhpRuntime, floors: dict[str, str]) -> str | None: return f"unparsable PHP_VERSION {runtime.version!r}" current = tuple(int(part) for part in match.groups()) line = f"{current[0]}.{current[1]}" - if line in floors: - if current < _numbers(floors[line]): - return f"{runtime.version} is below the security floor {floors[line]}" - return None - if current[:2] > newest: - return None - return f"{runtime.version} runs the end-of-life line {line}" + if line in floors and current < _numbers(floors[line]): + return f"{runtime.version} is below the security floor {floors[line]}" + if line not in floors and current[:2] <= newest: + return f"{runtime.version} runs the end-of-life line {line}" eol = [line for line in runtime.lines if _numbers(line) < oldest] if eol: return f"line {', '.join(eol)} is end of life" From b358a8bb0021d1b80c47b7914839cc985e32dd8c Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Fri, 30 Oct 2026 08:57:11 +0100 Subject: [PATCH 05/13] fix(web-app-keycloak): append the admin allowlist only when networks are declared tasks/00_core.yml built webserver_extra_configuration by concatenating the helper iframes, the admin allowlist and the logout panel template lookups with `~`. With the shipped empty `services.keycloak.admin.allowed_networks` the allowlist template rendered no text, Ansible's template lookup returned None for it, and `~` wrote the word "None" into the auth vhost. OpenResty then refused `unknown directive "Nonelocation"` in front of the logout panel location and every deploy with Keycloak went red. The role now resolves the declared networks once in KEYCLOAK_ADMIN_NETWORKS and the task appends the allowlist template only when that list is not empty, the same guard the logout panel uses. The template renders the restricted /admin location unconditionally from KEYCLOAK_ADMIN_NETWORKS. With a list that did not contain the deploy host, the deploy still went red: Keycloak answers `/` with a redirect to `/admin/`, so the CSP health check and the front proxy probe, which request `/` from the host, got 403 and hlth-csp failed. While the allowlist is active, `location = /` now redirects to the account console of the platform realm instead, and the README no longer claims the deploy needs no entry for any reason. test_admin_allowlist.py rendered the template with plain Jinja, which yields '' for an empty template, so it could not see the None. It now evaluates the task's own webserver_extra_configuration expression through Ansible's Templar and real template lookup, which reproduces "HELPER_IFRAMES\nNoneLOGOUT_PANEL" on the old task, and covers the root redirect. Co-Authored-By: Claude Opus 5.5 --- roles/web-app-keycloak/README.md | 2 +- roles/web-app-keycloak/tasks/00_core.yml | 2 +- .../templates/nginx/admin_allowlist.conf.j2 | 12 +- roles/web-app-keycloak/vars/main.yml | 1 + .../templates/test_admin_allowlist.py | 169 ++++++++++++++---- 5 files changed, 148 insertions(+), 38 deletions(-) diff --git a/roles/web-app-keycloak/README.md b/roles/web-app-keycloak/README.md index 9a65a58afe..de01941b2e 100644 --- a/roles/web-app-keycloak/README.md +++ b/roles/web-app-keycloak/README.md @@ -149,7 +149,7 @@ applications: The OIDC endpoints under `/realms/` and the static assets under `/resources/` stay public. -The deploy itself needs no entry: every `kcadm.sh` login, including the ones `web-app-opentalk` and `web-app-mattermost` make, runs inside the Keycloak container against `KEYCLOAK_SERVER_INTERNAL_URL`. Clients that call `/admin` through the public URL need their source network in the list: +The deploy's `kcadm.sh` logins need no entry: every one, including the ones `web-app-opentalk` and `web-app-mattermost` make, runs inside the Keycloak container against `KEYCLOAK_SERVER_INTERNAL_URL`. While the list is set, `/` redirects to the account console of the platform realm instead of to `/admin/`, so the CSP health check and the proxy probe, which request `/` from the host itself, need no entry either. Clients that call `/admin` through the public URL need their source network in the list: - The OpenTalk controller's user search calls the admin REST API from its container, so the vhost sees the container's Docker network address. `NETWORK_INTERNAL_CIDRS` covers the loopback and private ranges those addresses come from. - Onion visitors reach the vhost from the Tor daemon's address. diff --git a/roles/web-app-keycloak/tasks/00_core.yml b/roles/web-app-keycloak/tasks/00_core.yml index da3d36d4b1..3d26fd1c0f 100644 --- a/roles/web-app-keycloak/tasks/00_core.yml +++ b/roles/web-app-keycloak/tasks/00_core.yml @@ -23,7 +23,7 @@ compose_handlers_flush: true webserver_extra_configuration: >- {{ lookup('template', 'nginx/helper_iframes.conf.j2') - ~ lookup('template', 'nginx/admin_allowlist.conf.j2') + ~ (lookup('template', 'nginx/admin_allowlist.conf.j2') if KEYCLOAK_ADMIN_NETWORKS | length > 0 else '') ~ (lookup('template', 'nginx/logout_panel.conf.j2') if KEYCLOAK_LOGOUT_PANEL_ENABLED | bool else '') }} - name: "👔 Keycloak manager-side operations (file deploys + container exec)" diff --git a/roles/web-app-keycloak/templates/nginx/admin_allowlist.conf.j2 b/roles/web-app-keycloak/templates/nginx/admin_allowlist.conf.j2 index 25d808eb4d..714312c0e2 100644 --- a/roles/web-app-keycloak/templates/nginx/admin_allowlist.conf.j2 +++ b/roles/web-app-keycloak/templates/nginx/admin_allowlist.conf.j2 @@ -1,14 +1,18 @@ -{% set admin_networks = lookup('config', application_id, 'services.keycloak.admin.allowed_networks') | kc_admin_networks %} -{% if admin_networks %} {% set sso_proxy_enabled = false %} {% set http_port = lookup('config', application_id, 'services.keycloak.ports.local.http') %} {% set proxy_service_key = 'keycloak' %} {% set location = '^~ /admin' %} {% set webserver_location_extra_configuration %} -{% for network in admin_networks %} +{% for network in KEYCLOAK_ADMIN_NETWORKS %} allow {{ network }}; {% endfor %} deny all; {% endset %} {% include 'roles/sys-svc-proxy/templates/location/html.conf.j2' %} -{% endif %} + +{% set proxy_lua_enabled = false %} +{% set location = '= /' %} +{% set webserver_location_extra_configuration %} + return 302 /realms/{{ KEYCLOAK_REALM }}/account/; +{% endset %} +{% include 'roles/sys-svc-proxy/templates/location/html.conf.j2' %} diff --git a/roles/web-app-keycloak/vars/main.yml b/roles/web-app-keycloak/vars/main.yml index 5bc713a975..21f29a7094 100644 --- a/roles/web-app-keycloak/vars/main.yml +++ b/roles/web-app-keycloak/vars/main.yml @@ -85,6 +85,7 @@ KEYCLOAK_DB_NETWORK_ARG: "{% if lookup('database', application_id, 'shared') | b KEYCLOAK_FRONTCHANNEL_LOGOUT_URL: "{{ lookup('tls', 'web-svc-logout', 'url.base') }}" KEYCLOAK_LOGOUT_PANEL_FILE: "{{ lookup('nginx', 'directories.configuration.lua') }}{{ application_id }}-logout-panel.js" KEYCLOAK_LOGOUT_PANEL_ENABLED: "{{ lookup('config', application_id, 'services.javascript.enabled') | bool }}" +KEYCLOAK_ADMIN_NETWORKS: "{{ lookup('config', application_id, 'services.keycloak.admin.allowed_networks') | kc_admin_networks }}" KEYCLOAK_REDIRECT_URIS: "{{ lookup('redirect_uris') }}" KEYCLOAK_SAML_APPS: >- {{ lookup('applications') | dict2items diff --git a/tests/unit/python/roles/web-app-keycloak/templates/test_admin_allowlist.py b/tests/unit/python/roles/web-app-keycloak/templates/test_admin_allowlist.py index 5609b2217c..d155a27c6d 100644 --- a/tests/unit/python/roles/web-app-keycloak/templates/test_admin_allowlist.py +++ b/tests/unit/python/roles/web-app-keycloak/templates/test_admin_allowlist.py @@ -2,9 +2,13 @@ from __future__ import annotations import importlib.util import re +import tempfile import unittest +from pathlib import Path from ansible.errors import AnsibleFilterError +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar, trust_as_template from jinja2 import ( ChoiceLoader, DictLoader, @@ -13,11 +17,12 @@ from jinja2 import ( StrictUndefined, select_autoescape, ) +from jinja2.nativetypes import NativeEnvironment -from utils.cache.files import iter_project_files_with_content, read_text -from utils.cache.yaml import load_yaml +from utils.cache.files import iter_project_files_with_content +from utils.cache.yaml import load_yaml, load_yaml_any from utils.networks.proxy import render_proxy_pass -from utils.roles.mapping import ROLE_FILE_META_SERVICES +from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_VARS_MAIN from . import PROJECT_ROOT @@ -26,6 +31,15 @@ TEMPLATE = "roles/web-app-keycloak/templates/nginx/admin_allowlist.conf.j2" CONFIG_PATH = "services.keycloak.admin.allowed_networks" LOCAL_HTTP_PORT = 8032 NETWORKS = ("203.0.113.0/24", "2001:db8::/48", "198.51.100.7") +REALM = "example.realm" + +STUBBED_FRAGMENTS = { + "helper_iframes.conf.j2": "HELPER_IFRAMES\n", + "admin_allowlist.conf.j2": ( + "{% for network in KEYCLOAK_ADMIN_NETWORKS %}allow {{ network }};\n{% endfor %}" + ), + "logout_panel.conf.j2": "LOGOUT_PANEL\n", +} STUBBED_INCLUDES = { "roles/web-app-keycloak/templates/sso_proxy/following_directives.conf.j2": "SSO_GATE\n", @@ -46,8 +60,8 @@ def role_filters() -> dict: return module.FilterModule().filters() -def render(networks, deployment_mode: str = "compose") -> str: - """Render the allowlist fragment the Keycloak vhost carries. +def stub_lookup(networks, deployment_mode: str = "compose"): + """Return a `lookup` that answers the role's config paths and `proxy_pass`. Args: networks: the value under `services.keycloak.admin.allowed_networks`. @@ -72,12 +86,37 @@ def render(networks, deployment_mode: str = "compose") -> str: ) raise AssertionError(f"unexpected lookup({kind!r}, ...)") + return lookup + + +def admin_networks(networks) -> list[str]: + """Evaluate the role's `KEYCLOAK_ADMIN_NETWORKS` for a declared value. + + Args: + networks: the value under `services.keycloak.admin.allowed_networks`. + """ + env = NativeEnvironment(undefined=StrictUndefined) + env.filters.update(role_filters()) + definition = load_yaml(ROLE_DIR / ROLE_FILE_VARS_MAIN)["KEYCLOAK_ADMIN_NETWORKS"] + return env.from_string(definition).render( + application_id="web-app-keycloak", lookup=stub_lookup(networks) + ) + + +def render(networks, deployment_mode: str = "compose") -> str: + """Render the allowlist fragment the Keycloak vhost carries. + + Args: + networks: the value under `services.keycloak.admin.allowed_networks`. + deployment_mode: the mode `proxy_pass` renders for. + """ env = Environment( loader=ChoiceLoader( [DictLoader(STUBBED_INCLUDES), FileSystemLoader(str(PROJECT_ROOT))] ), undefined=StrictUndefined, autoescape=select_autoescape(), + trim_blocks=True, ) env.filters.update(role_filters()) env.filters["bool"] = lambda value: ( @@ -87,25 +126,64 @@ def render(networks, deployment_mode: str = "compose") -> str: ) env.filters["get_entity_name"] = lambda value: value.rsplit("-", 1)[-1] return env.get_template(TEMPLATE).render( - application_id="web-app-keycloak", lookup=lookup + application_id="web-app-keycloak", + lookup=stub_lookup(networks, deployment_mode), + KEYCLOAK_ADMIN_NETWORKS=admin_networks(networks), + KEYCLOAK_REALM=REALM, ) -def location_block(rendered: str) -> tuple[str, list[str]]: - """Return the location's matcher and its directives, one per line. +def extra_configuration(networks: list[str], logout_panel_enabled: bool) -> str: + """Evaluate the vhost extras `tasks/00_core.yml` hands to `sys-stk-full`. + + Ansible's template lookup returns None for a fragment that renders no text, + and `~` writes it into the vhost as "None"; plain Jinja renders ''. + + Args: + networks: the resolved `KEYCLOAK_ADMIN_NETWORKS`. + logout_panel_enabled: the resolved `KEYCLOAK_LOGOUT_PANEL_ENABLED`. + """ + task = next( + task + for task in load_yaml_any(ROLE_DIR / "tasks/00_core.yml") + if "vars" in task and "webserver_extra_configuration" in task["vars"] + ) + with tempfile.TemporaryDirectory() as search_path: + fragments = Path(search_path, "templates", "nginx") + fragments.mkdir(parents=True) + for name, text in STUBBED_FRAGMENTS.items(): + (fragments / name).write_text(text, encoding="utf-8") + templar = Templar( + loader=DataLoader(), + variables={ + "ansible_search_path": [search_path], + "KEYCLOAK_ADMIN_NETWORKS": networks, + "KEYCLOAK_LOGOUT_PANEL_ENABLED": logout_panel_enabled, + }, + ) + return templar.template( + trust_as_template(task["vars"]["webserver_extra_configuration"]) + ) + + +def location_block(rendered: str, path: str) -> tuple[str, list[str]]: + """Return the matcher and the directives, one per line, of a location. Args: rendered: the rendered fragment. + path: the path the location's matcher names, modifier excluded. """ - match = re.search(r"location\s+([^{]+?)\s*\{(.*)\}\s*$", rendered, re.DOTALL) - if match is None: - raise AssertionError(f"no location block rendered:\n{rendered}") - directives = [ - line.strip() - for line in match.group(2).splitlines() - if line.strip() and not line.strip().startswith("#") - ] - return match.group(1).strip(), directives + for match in re.finditer( + r"^location\s+([^{\n]+?)\s*\{([^{}]*)\}", rendered, re.MULTILINE + ): + matcher = match.group(1).strip() + if matcher.split()[-1] == path: + return matcher, [ + line.strip() + for line in match.group(2).splitlines() + if line.strip() and not line.strip().startswith("#") + ] + raise AssertionError(f"no location for {path} rendered:\n{rendered}") def covers(matcher: str, path: str) -> bool: @@ -123,19 +201,29 @@ class TestShippedValue(unittest.TestCase): services = load_yaml(ROLE_DIR / ROLE_FILE_META_SERVICES) self.assertEqual(services["keycloak"]["admin"]["allowed_networks"], []) - def test_an_empty_list_renders_nothing(self): - self.assertEqual(render([]).strip(), "") + def test_an_empty_list_resolves_to_no_network(self): + self.assertEqual(admin_networks([]), []) - def test_the_keycloak_vhost_carries_the_fragment(self): - self.assertIn( - "lookup('template', 'nginx/admin_allowlist.conf.j2')", - read_text(str(ROLE_DIR / "tasks/00_core.yml")), + +class TestVhostExtras(unittest.TestCase): + def test_no_declared_network_adds_no_text(self): + for panel, expected in ( + (True, "HELPER_IFRAMES\nLOGOUT_PANEL\n"), + (False, "HELPER_IFRAMES\n"), + ): + with self.subTest(logout_panel_enabled=panel): + self.assertEqual(extra_configuration([], panel), expected) + + def test_declared_networks_sit_between_the_helpers_and_the_panel(self): + self.assertEqual( + extra_configuration(["203.0.113.0/24"], True), + "HELPER_IFRAMES\nallow 203.0.113.0/24;\nLOGOUT_PANEL\n", ) class TestRestrictedLocation(unittest.TestCase): def test_every_network_is_allowed_before_the_rest_is_denied(self): - _, directives = location_block(render(list(NETWORKS))) + _, directives = location_block(render(list(NETWORKS)), "/admin") access = [d for d in directives if d.startswith(("allow ", "deny "))] self.assertEqual( access, @@ -148,7 +236,7 @@ class TestRestrictedLocation(unittest.TestCase): ) def test_the_admin_console_and_rest_api_are_covered(self): - matcher, _ = location_block(render(list(NETWORKS))) + matcher, _ = location_block(render(list(NETWORKS)), "/admin") for path in ( "/admin", "/admin/", @@ -160,7 +248,7 @@ class TestRestrictedLocation(unittest.TestCase): self.assertTrue(covers(matcher, path)) def test_the_oidc_endpoints_stay_public(self): - matcher, _ = location_block(render(list(NETWORKS))) + matcher, _ = location_block(render(list(NETWORKS)), "/admin") for path in ( "/", "/realms/infinito/protocol/openid-connect/token", @@ -172,20 +260,20 @@ class TestRestrictedLocation(unittest.TestCase): self.assertFalse(covers(matcher, path)) def test_no_regex_location_can_take_an_admin_path_over(self): - matcher, _ = location_block(render(list(NETWORKS))) + matcher, _ = location_block(render(list(NETWORKS)), "/admin") self.assertTrue( matcher.startswith("^~ "), f"'{matcher}' lets a regex location win over the allowlist", ) def test_compose_passes_the_request_path_unchanged(self): - _, directives = location_block(render(list(NETWORKS))) + _, directives = location_block(render(list(NETWORKS)), "/admin") self.assertIn( f"proxy_pass http://127.0.0.1:{LOCAL_HTTP_PORT}/admin;", directives ) def test_swarm_passes_the_raw_request_uri(self): - _, directives = location_block(render(list(NETWORKS), "swarm")) + _, directives = location_block(render(list(NETWORKS), "swarm"), "/admin") self.assertIn("proxy_pass http://$proxy_pass_upstream$request_uri;", directives) def test_the_location_strips_forged_identity_headers(self): @@ -194,17 +282,34 @@ class TestRestrictedLocation(unittest.TestCase): self.assertNotIn("SSO_GATE", rendered) +class TestRootRedirect(unittest.TestCase): + def test_the_root_sends_visitors_to_the_realm_account_console(self): + matcher, directives = location_block(render(list(NETWORKS)), "/") + self.assertEqual(matcher, "= /") + self.assertIn(f"return 302 /realms/{REALM}/account/;", directives) + + def test_the_root_is_open_to_every_source(self): + _, directives = location_block(render(list(NETWORKS)), "/") + self.assertEqual( + [d for d in directives if d.startswith(("allow ", "deny "))], [] + ) + + def test_the_redirect_target_is_outside_the_restricted_location(self): + matcher, _ = location_block(render(list(NETWORKS)), "/admin") + self.assertFalse(covers(matcher, f"/realms/{REALM}/account/")) + + class TestDeclaredValues(unittest.TestCase): def test_spellings_of_one_network_render_one_allow(self): _, directives = location_block( - render(["2001:db8::1", "2001:0db8::1/128", " 2001:db8::1 "]) + render(["2001:db8::1", "2001:0db8::1/128", " 2001:db8::1 "]), "/admin" ) self.assertEqual( [d for d in directives if d.startswith("allow ")], ["allow 2001:db8::1/128;"], ) - def test_malformed_values_fail_the_render(self): + def test_malformed_values_fail_the_variable(self): for value in ( "203.0.113.0/24", None, @@ -215,7 +320,7 @@ class TestDeclaredValues(unittest.TestCase): [42], ): with self.subTest(value=value), self.assertRaises(AnsibleFilterError): - render(value) + admin_networks(value) class TestDeployAdminCallsBypassTheVhost(unittest.TestCase): From 284b0873dd28ffc8fa8db0e901a777babeac6be8 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Fri, 30 Oct 2026 08:57:21 +0100 Subject: [PATCH 06/13] fix(sys-ctl-hlth-runtime): harden LAM CLI, catch apk options, drop vars comment Addresses three CodeRabbit findings on PR #1265. 1. LAM hardening invisible to the probe (thread 4413764929): the runtime check probes PHP with `php -r`, the CLI SAPI. web-app-lam mounted the hardening ini only into /etc/php/8.4/apache2/conf.d, which the Debian CLI does not scan, so the probe read unhardened CLI settings and the check failed for LAM. The php_hardening entry now also mounts the ini into /etc/php/8.4/cli/conf.d. No other role mounts it into a Debian per-SAPI directory; the rest use the shared scan dir of the official image or of Alpine. The TODO entry now names the remaining gap: the probe reads only the CLI copy. 2. Explanatory comment above HEALTH_RUNTIME_FLOORS (thread 4413764949): removed. The README already states the end-of-life rule and now also defines a floor as the lowest patched release of each line. 3. `apk --no-cache add` missed (thread 4415018662): PACKAGE_INSTALL_PATTERN required `add` right after `apk`, so `RUN apk --no-cache add php7` passed as an image without PHP. The apk branch now accepts options before `add`, like the apt branch. New tests cover the option form and guard that `apk` in a path or a comment is no package install. Co-Authored-By: Claude Opus 5.5 --- roles/sys-ctl-hlth-runtime/README.md | 2 +- roles/sys-ctl-hlth-runtime/TODO.md | 2 +- roles/sys-ctl-hlth-runtime/vars/main.yml | 1 - roles/web-app-lam/meta/volumes.yml | 2 ++ .../unit/python/utils/docker/test_image_runtime.py | 14 ++++++++++++++ utils/docker/image/runtime.py | 2 +- 6 files changed, 19 insertions(+), 4 deletions(-) diff --git a/roles/sys-ctl-hlth-runtime/README.md b/roles/sys-ctl-hlth-runtime/README.md index f0721cbfda..f6125fa4ee 100644 --- a/roles/sys-ctl-hlth-runtime/README.md +++ b/roles/sys-ctl-hlth-runtime/README.md @@ -6,7 +6,7 @@ This role checks the language runtime inside every running Docker container. It ## Overview -The role installs a check script with a `systemd` service and timer. The check fails, and the failure notifier from [`sys-ctl-alm-compose`](../sys-ctl-alm-compose/README.md) alerts, when a container runs PHP below the security floor of its release line or on an end-of-life line, or when a service that declares `php_hardening` in its `meta/volumes.yml` still reports `expose_php` or `session.upload_progress.enabled` as on. The floors live in `HEALTH_RUNTIME_FLOORS` in [main.yml](./vars/main.yml). +The role installs a check script with a `systemd` service and timer. The check fails, and the failure notifier from [`sys-ctl-alm-compose`](../sys-ctl-alm-compose/README.md) alerts, when a container runs PHP below the security floor of its release line or on an end-of-life line, or when a service that declares `php_hardening` in its `meta/volumes.yml` still reports `expose_php` or `session.upload_progress.enabled` as on. The floors, the lowest patched release of each `major.minor` line, live in `HEALTH_RUNTIME_FLOORS` in [main.yml](./vars/main.yml). ## Cosmos diff --git a/roles/sys-ctl-hlth-runtime/TODO.md b/roles/sys-ctl-hlth-runtime/TODO.md index a249b5e35e..52d1d825ad 100644 --- a/roles/sys-ctl-hlth-runtime/TODO.md +++ b/roles/sys-ctl-hlth-runtime/TODO.md @@ -1,6 +1,6 @@ # To-dos - Extend `HEALTH_RUNTIME_FLOORS`, the container probe and `make security-runtimes` to `node`, `python`, `ruby` and `java`. -- Verify the web SAPI where an image splits it from the CLI. `web-app-lam` mounts the hardening ini into `/etc/php/8.4/apache2/conf.d`, which the Debian CLI does not scan, so `php` in that container reads the CLI configuration instead of the one Apache loads. +- Verify the web SAPI where an image splits it from the CLI. `web-app-lam` mounts the hardening ini into both `/etc/php/8.4/apache2/conf.d` and `/etc/php/8.4/cli/conf.d`, and the probe reads only the CLI copy, so a wrong Apache target would still pass. - Run `make security-runtimes` in a scheduled CI workflow. - Scan the pinned images for CVEs (Trivy or Grype) in the scheduled CI and report new criticals as issues. diff --git a/roles/sys-ctl-hlth-runtime/vars/main.yml b/roles/sys-ctl-hlth-runtime/vars/main.yml index 90c7f0fc1c..c0ca639b9c 100644 --- a/roles/sys-ctl-hlth-runtime/vars/main.yml +++ b/roles/sys-ctl-hlth-runtime/vars/main.yml @@ -1,6 +1,5 @@ --- system_service_id: sys-ctl-hlth-runtime -# Lowest patched release per runtime line; a line older than every listed one is end of life HEALTH_RUNTIME_FLOORS: php: "8.2": "8.2.35" diff --git a/roles/web-app-lam/meta/volumes.yml b/roles/web-app-lam/meta/volumes.yml index 15633aec53..a974fe8c68 100644 --- a/roles/web-app-lam/meta/volumes.yml +++ b/roles/web-app-lam/meta/volumes.yml @@ -6,3 +6,5 @@ php_hardening: mounts: - service: lam target: /etc/php/8.4/apache2/conf.d/zz-infinito-hardening.ini + - service: lam + target: /etc/php/8.4/cli/conf.d/zz-infinito-hardening.ini diff --git a/tests/unit/python/utils/docker/test_image_runtime.py b/tests/unit/python/utils/docker/test_image_runtime.py index 150bb040d8..077659ce38 100644 --- a/tests/unit/python/utils/docker/test_image_runtime.py +++ b/tests/unit/python/utils/docker/test_image_runtime.py @@ -66,6 +66,20 @@ class TestPhpRuntime(TestCase): ) ) + def test_apk_options_before_add_still_name_the_line(self): + self.assertEqual( + runtime.php_runtime(["RUN apk --no-cache add php7 php7-fpm"]), + _php(lines=["7"]), + ) + + def test_apk_in_a_path_or_comment_is_no_package_install(self): + for instruction in ( + "RUN rm -rf /var/cache/apk/* && cp php7 /srv/add", + "RUN echo php7 # apk cache: add nothing", + ): + with self.subTest(instruction=instruction): + self.assertIsNone(runtime.php_runtime([instruction])) + def test_a_pinned_alpine_package_names_its_line(self): found = runtime.php_runtime(["RUN apk add --no-cache php84=8.4.27-r0 nginx;"]) self.assertEqual(found, _php(lines=["8.4"])) diff --git a/utils/docker/image/runtime.py b/utils/docker/image/runtime.py index b582f7761e..e776388426 100644 --- a/utils/docker/image/runtime.py +++ b/utils/docker/image/runtime.py @@ -21,7 +21,7 @@ USER_AGENT = "infinito-nexus-runtime-report" PHP_VERSION_PATTERN = re.compile(r"\bPHP_VERSION=([0-9][^\s\"';]*)") PHP_BASE_PATTERN = re.compile(r"\bPHP_BASE=(\d+\.\d+)(?![\d.])") PACKAGE_INSTALL_PATTERN = re.compile( - r"\b(?:apk\s+add|(?:apt-get|apt|dnf|microdnf|yum)\s+(?:-\S+\s+)*install)\b" + r"\b(?:apk\s+(?:-\S+\s+)*add|(?:apt-get|apt|dnf|microdnf|yum)\s+(?:-\S+\s+)*install)\b" ) PHP_PACKAGE_PATTERN = re.compile( r"(? Date: Fri, 30 Oct 2026 11:13:55 +0100 Subject: [PATCH 07/13] fix(ci): merge the matrix row's disable tokens with the caller's list Both deploy steps set `disable: ${{ matrix.disable || inputs.disable }}`. A row carries tokens of its own whenever its network mode needs them (a clearnet row disables Tor), so the caller's list never reached the deploy. On feature/store-i18n (CI run 40979252521) the workspace swarm zombie for svc-db-mariadb/postgres deployed 19 apps instead of 7 on its clearnet row (fedora: 4h06 for one step, job cancelled at 345 min). main carries the same expression; it bites as soon as a caller's disable list meets a clearnet row. The steps now pass format('{0} {1}', matrix.disable, inputs.disable); every reader of `disable` splits on spaces and commas. Both input descriptions follow. test_deploy_disable_merge.py reads the live expressions; against the old fallback it fails two subtests. Ported from feature/store-i18n 57e574ac2d (store-i18n's extra `network:` step env stays there). Co-Authored-By: Claude Opus 5.5 --- .github/workflows/call-test-deploy.yml | 8 +- .../repository/test_deploy_disable_merge.py | 76 +++++++++++++++++++ 2 files changed, 80 insertions(+), 4 deletions(-) create mode 100644 tests/lint/repository/test_deploy_disable_merge.py diff --git a/.github/workflows/call-test-deploy.yml b/.github/workflows/call-test-deploy.yml index dc3e52ad1b..dcdf313fdc 100644 --- a/.github/workflows/call-test-deploy.yml +++ b/.github/workflows/call-test-deploy.yml @@ -70,7 +70,7 @@ on: type: string default: "" disable: - description: "Comma-separated provider keys removed from the test inventory; used when the matrix row carries none of its own." + description: "Comma-separated provider keys removed from the test inventory, on top of the matrix row's own tokens." required: false type: string default: "" @@ -134,7 +134,7 @@ on: type: string default: "" disable: - description: "ðŸšŦ Provider keys removed from the test inventory (comma-separated)" + description: "ðŸšŦ Provider keys removed on top of the row's own (comma-separated)" required: false type: string default: "" @@ -355,7 +355,7 @@ jobs: shell: bash env: variant: ${{ matrix.variant }} - disable: ${{ matrix.disable || inputs.disable }} + disable: ${{ format('{0} {1}', matrix.disable, inputs.disable) }} INFINITO_SWARM_VPN: ${{ matrix.vpn }} INFINITO_SWARM_MESHES: ${{ inputs.meshes }} run: ./scripts/tests/deploy/distros.sh "${{ env.SCRIPTS }}/00_one.sh" 2>&1 | tee "/tmp/ansible-${{ matrix.apps }}.log" @@ -367,7 +367,7 @@ jobs: env: apps: ${{ matrix.apps }} variant: ${{ matrix.variant }} - disable: ${{ matrix.disable || inputs.disable }} + disable: ${{ format('{0} {1}', matrix.disable, inputs.disable) }} ANSIBLE_LOG_PATH: /tmp/ansible-${{ matrix.apps }}.log run: ./scripts/tests/deploy/ci/all.sh 2>&1 | tee "/tmp/ansible-${{ matrix.apps }}.log" diff --git a/tests/lint/repository/test_deploy_disable_merge.py b/tests/lint/repository/test_deploy_disable_merge.py new file mode 100644 index 0000000000..9f165b67cf --- /dev/null +++ b/tests/lint/repository/test_deploy_disable_merge.py @@ -0,0 +1,76 @@ +from __future__ import annotations + +import re +import unittest + +from cli.administration.inventory.provision.services_disabler import ( + parse_services_disabled, +) +from tests.utils import PROJECT_ROOT +from utils.cache.files import read_text + +DEPLOY_WORKFLOW = PROJECT_ROOT / ".github" / "workflows" / "call-test-deploy.yml" + +_DISABLE_ENV = re.compile(r"^\s+disable:\s*\$\{\{\s*(.*?)\s*\}\}\s*$") +_FORMAT = re.compile( + r"format\('(?P