From 5b2b44f94a982c24775428f04444cda09014bc0e Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 17 Nov 2026 09:54:43 +0000 Subject: [PATCH 1/2] fix(sys-ctl-hlth-runtime): skip network mounts in the host scan MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Root cause: on PR 2009 (run 43802337071, swarm job odoo#1) the sys-ctl-hlth-runtime unit failed because the Trivy rootfs scan of a swarm node hit its 5 minute timeout. The wrk-02 journal shows the walk stuck in /var/lib/infinito, which on a swarm node with storage.backend nfs is the NFS mount of the cluster-shared volumes. The host metrics of the same window rule out load. Every node walked the whole shared state over NFS, plus the node-local backup store bound over it. Fix: - The check reads /proc/self/mountinfo when it scans the host and skips every mount other than / whose type is a network or automount filesystem (nfs, nfs4, cifs, sshfs, ceph, glusterfs, autofs and the other types in NETWORK_FSTYPES). It prints one info line per skipped mount. Mount points are octal-unescaped and read with surrogateescape. The printed line escapes undecodable bytes, so a strict UTF-8 stdout cannot crash the check, and every non-printable character, so a mount point holding a newline cannot forge journal lines or JSON events. - The static DIR_VAR_LIB exclude is not needed: swarm nodes and the controller mount it as nfs or nfs4, which the detection catches, and a compose host scans it again as before. The new group path DIR_BACKUPS_NODE replaces the client role's private backup dir var and is excluded statically, since it is a local tree. - Trivy gets one --skip-dirs per path, each value CSV-quoted: Trivy parses every value as CSV, so an unquoted comma splits a path even when it stands alone (checked on trivy 0.76.1). - Every skip path is glob-escaped for Trivy, Syft and Grype, which all match with doublestar v4. One unbalanced [ in a skip path made Trivy 0.76.1 drop every skip path sorted after it, which would bring back the walk of the Docker data root and the NFS state. An unescaped * also skipped sibling directories. - README: the host scan does not see software on a network-mounted /opt, /home, /usr/local or /var (with /var also the package database), and volume content is scanned in neither compose nor swarm mode. That covers runtime installs and the image content Docker copies into an empty named volume on first mount, such as hermes_data at /opt/data, which stays at its first version after image upgrades. Evidence: - 10 files changed, 565 insertions, 12 deletions. - test_network_mounts 10 passed, test_script 163 passed, test_host_excludes 3 passed, each file run alone; ruff and the repository comment lint are clean on every staged file. - Negative controls, all red: no report lines, no wiring of the mounts into the scan, Syft or Grype excludes dropped, no glob escaping, no CSV quoting, no surrogateescape, raw print of an undecodable path, no host-target guard, no nfs type, no DIR_BACKUPS_NODE exclude, and test_script without its fixed mount list (15 failures). - A mount point /srv/a\012forged prints as one line ending in /srv/a\nforged; without the escape the line splits and "forged" stands alone (negative control red). - Trivy 0.76.1 on test trees: unescaped skips walked x[y and z and skipped sa by mistake; escaped skips leave only sa. - Three review rounds; the last independent re-check confirmed the escaping on trivy 0.76.1 and doublestar v4 in Syft v1.55.0 and Grype v0.121.0. - MEDUSA scan of the 10 files against e0f751eb4e, rerun after the escape fix: security 100, 0 critical, 0 new findings. - Quality gate: pending, CI. The local quality-high run was cancelled by operator order before it started; the 90/5 below covers fix and break only. đŸŽ¯ Fix: 92 % đŸ’Ĩ Break: 4 % 💸 Tokens: – âąī¸ Velocity: – đŸ›Ąī¸ Security: 100 % 🏆 Score: 88 đŸšĻ Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Co-Authored-By: Claude Opus 5.5 --- group_vars/all/05_paths.yml | 1 + roles/svc-storage-nfs-client/tasks/main.yml | 4 +- roles/svc-storage-nfs-client/vars/main.yml | 1 - roles/sys-ctl-hlth-runtime/README.md | 2 +- .../files/python/script.py | 99 +++++- roles/sys-ctl-hlth-runtime/vars/main.yml | 1 + .../files/test_network_mounts.py | 301 ++++++++++++++++++ .../sys-ctl-hlth-runtime/files/test_script.py | 10 +- .../sys-ctl-hlth-runtime/vars/__init__.py | 5 + .../vars/test_host_excludes.py | 153 +++++++++ 10 files changed, 565 insertions(+), 12 deletions(-) create mode 100644 tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_network_mounts.py create mode 100644 tests/unit/python/roles/sys-ctl-hlth-runtime/vars/__init__.py create mode 100644 tests/unit/python/roles/sys-ctl-hlth-runtime/vars/test_host_excludes.py diff --git a/group_vars/all/05_paths.yml b/group_vars/all/05_paths.yml index 697b5770a7..202b446536 100644 --- a/group_vars/all/05_paths.yml +++ b/group_vars/all/05_paths.yml @@ -21,6 +21,7 @@ DIR_CACHE: "/var/cache/infinito/core/cache" DIR_VAR_LIB: "/var/lib/infinito" DIR_BACKUPS: "{{ [DIR_VAR_LIB, 'backup'] | path_join }}" +DIR_BACKUPS_NODE: "{{ DIR_VAR_LIB ~ '-backup' }}" BACKUP_REPOSITORIES: - backup-docker-to-local - backup-nfs-to-local diff --git a/roles/svc-storage-nfs-client/tasks/main.yml b/roles/svc-storage-nfs-client/tasks/main.yml index 9ded755d41..1ecc87aeb7 100644 --- a/roles/svc-storage-nfs-client/tasks/main.yml +++ b/roles/svc-storage-nfs-client/tasks/main.yml @@ -124,14 +124,14 @@ - name: "✅ Ensure the node-local backup store exists" ansible.builtin.file: - path: "{{ SVC_STORAGE_NFS_CLIENT_BACKUPS_DIR }}" + path: "{{ DIR_BACKUPS_NODE }}" state: directory mode: "0755" - name: "🔗 Keep {{ DIR_BACKUPS }} node-local over the shared state" ansible.posix.mount: path: "{{ DIR_BACKUPS }}" - src: "{{ SVC_STORAGE_NFS_CLIENT_BACKUPS_DIR }}" + src: "{{ DIR_BACKUPS_NODE }}" fstype: none opts: bind,_netdev state: mounted diff --git a/roles/svc-storage-nfs-client/vars/main.yml b/roles/svc-storage-nfs-client/vars/main.yml index 3879d84323..6c5434024e 100644 --- a/roles/svc-storage-nfs-client/vars/main.yml +++ b/roles/svc-storage-nfs-client/vars/main.yml @@ -2,4 +2,3 @@ application_id: "svc-storage-nfs-client" SVC_STORAGE_NFS_CLIENT_PROBE_DIR: /run/svc-storage-nfs-client/probe -SVC_STORAGE_NFS_CLIENT_BACKUPS_DIR: "{{ DIR_VAR_LIB ~ '-backup' }}" diff --git a/roles/sys-ctl-hlth-runtime/README.md b/roles/sys-ctl-hlth-runtime/README.md index 4a4217e449..bd0cc7457a 100644 --- a/roles/sys-ctl-hlth-runtime/README.md +++ b/roles/sys-ctl-hlth-runtime/README.md @@ -27,7 +27,7 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( ## Features -- **Targets:** `container` scans the image of every running container through the read-only Docker socket, `host` scans the host root filesystem mounted read-only. In swarm every node scans itself. +- **Targets:** `container` scans the image of every running container through the read-only Docker socket, `host` scans the host root filesystem mounted read-only. In swarm every node scans itself. The host scan skips the paths in `HEALTH_RUNTIME_HOST_EXCLUDES` of [vars/main.yml](./vars/main.yml): kernel and temporary filesystems, the container engine's data root, removable media, the backups including the node-local store `DIR_BACKUPS_NODE`, and the NFS export base. It also skips every mount other than `/` whose type is one of the network or automount filesystem types listed in `NETWORK_FSTYPES` of [script.py](./files/python/script.py), read from `/proc/self/mountinfo`, so a slow or dead remote server cannot stall it, and prints one `â„šī¸` line per skipped mount. The `autofs` type also covers local automounts, such as a systemd automount of `/boot` or `/efi`. Software on such a mount is not scanned: a host that mounts `/opt`, `/home`, `/usr/local` or `/var` from NFS, CIFS or sshfs loses the findings there, and a remote `/var` also hides the dpkg, pacman or rpm package database under `/var/lib`. On a swarm node with `storage.backend` `nfs`, `DIR_VAR_LIB` is such a mount and holds the cluster-shared volumes; a compose host keeps its volumes in the skipped Docker data root. Volume content is therefore scanned in neither compose nor swarm mode, and the container scan covers only the image. That leaves out software a service installs into a volume at runtime, such as Nextcloud apps, Odoo addons or agent packages, and the image content Docker copies into an empty named volume on its first mount, such as `hermes_data` at `/opt/data` of [web-app-hermes](../web-app-hermes/meta/volumes.yml): that copy stays at its first version after every image upgrade, and no image scan sees it. - **Engine runtime:** An engine run that reads the host Docker socket runs on `runc`, also on a swarm worker that [`svc-virt-kata`](../svc-virt-kata/README.md) defaults to gVisor or Kata, because those runtimes refuse the bind-mounted socket and every container scan would fail there. Every other engine run, the host scan included, keeps the node's default runtime. - **Engines:** Syft builds one SBOM per target, Grype and OSV-Scanner read it, Trivy reads the target itself. Without `syft` in `engines`, Grype and OSV-Scanner read the target directly; `osv` then scans containers only. While Grype runs, Trivy leaves the OS packages of every OS release listed under `trivy.unmatched_os` to Grype until the entry's `until`, because Trivy matches no Red Hat advisory for CentOS Stream 10 and Red Hat Enterprise Linux 10 yet and fails with `unable to find CPE indices`, see [aquasecurity/trivy-db#435](https://github.com/aquasecurity/trivy-db/issues/435) and [aquasecurity/trivy#7452](https://github.com/aquasecurity/trivy/issues/7452). - **Source-built runtimes:** A runtime compiled into the image, such as the PHP of the official `php` images, is matched by Grype only. With `syft` but without `grype` in `engines`, Grype still scans the binary-classified packages of every SBOM. diff --git a/roles/sys-ctl-hlth-runtime/files/python/script.py b/roles/sys-ctl-hlth-runtime/files/python/script.py index e95a65413b..5a69f3625d 100755 --- a/roles/sys-ctl-hlth-runtime/files/python/script.py +++ b/roles/sys-ctl-hlth-runtime/files/python/script.py @@ -1316,8 +1316,22 @@ def scratch_of(engine: str, subject: str) -> str: return f"tmp-{engine}-{subject}" +GLOB_SPECIAL = re.compile(r"([\\*?\[\]{}])") + + +def glob_literal(path: str) -> str: + """ + Args: + path: a path to hand to Trivy, Syft or Grype as a skip pattern. + + Returns: + The doublestar pattern that matches exactly ``path``. + """ + return GLOB_SPECIAL.sub(r"\\\1", path) + + def _relative_excludes(layout: Layout) -> list[str]: - return [f"./{path.strip('/')}" for path in layout.excludes] + return [f"./{glob_literal(path.strip('/'))}" for path in layout.excludes] def db_steps(engine: str, layout: Layout, image: str) -> list[Step]: @@ -1472,11 +1486,10 @@ def trivy_step( if not config.db_update: args += ["--cache-backend", "memory"] if target.kind == "host": - args += [ - "--skip-dirs", - ",".join(f"{HOST_ROOT}{path}" for path in layout.excludes), - HOST_ROOT, - ] + for path in layout.excludes: + quoted = glob_literal(f"{HOST_ROOT}{path}").replace('"', '""') + args += ["--skip-dirs", f'"{quoted}"'] + args.append(HOST_ROOT) else: args += ["--image-src", "docker", target.ref] scratch = scratch_of("trivy", target.key) @@ -1888,6 +1901,73 @@ def docker_root() -> str: ).stdout.strip() +MOUNTINFO = Path("/proc/self/mountinfo") +NETWORK_FSTYPES = frozenset( + { + "nfs", + "nfs4", + "cifs", + "smb3", + "smbfs", + "ceph", + "fuse.ceph-fuse", + "glusterfs", + "fuse.glusterfs", + "fuse.sshfs", + "fuse.s3fs", + "fuse.rclone", + "afs", + "lustre", + "autofs", + "davfs", + "fuse.gcsfuse", + "fuse.juicefs", + } +) +MOUNTINFO_ESCAPE = re.compile(r"\\([0-7]{3})") + + +def network_mounts(mountinfo: str) -> list[str]: + """ + Args: + mountinfo: the text of a ``/proc//mountinfo``. + + Returns: + The mount points of every network filesystem in it, sorted, except + ``/``: a host whose root is remote still scans its root. + """ + points = set() + for line in mountinfo.splitlines(): + fields = line.split(" ") + if "-" not in fields[6:]: + continue + fstype = fields[fields.index("-", 6) + 1] + point = MOUNTINFO_ESCAPE.sub(lambda m: chr(int(m.group(1), 8)), fields[4]) + if fstype in NETWORK_FSTYPES and point != "/": + points.add(point) + return sorted(points) + + +def host_network_mounts() -> list[str]: + return network_mounts( + MOUNTINFO.read_text(encoding="utf-8", errors="surrogateescape") + ) + + +def printable(path: str) -> str: + """ + Args: + path: a mount point as decoded from mountinfo. + + Returns: + ``path`` with every undecodable byte as ``\\xNN`` and every other + non-printable character in its Python escape form, so it prints as + exactly one line. + """ + text = os.fsencode(path).decode(errors="backslashreplace") + return "".join(char if char.isprintable() else ascii(char)[1:-1] for char in text) + + def vulnerability_check( containers: Sequence[Container], config: ScanConfig, @@ -1961,6 +2041,11 @@ def main(argv=None) -> int: print(f"❌ listing the running containers failed: {exc}") return 1 failures, infos = check(containers, hardened, probe_php) + remote = host_network_mounts() if "host" in config.targets else [] + infos += [ + f"host scan skips the network or automounted filesystem at {printable(point)}" + for point in remote + ] targets, judged, errors = vulnerability_check( containers, config, @@ -1968,7 +2053,7 @@ def main(argv=None) -> int: suppressions_from_json(json.loads(args.suppressions)), Path(args.cache_dir), Path(args.database_dir), - json.loads(args.host_excludes), + [*json.loads(args.host_excludes), *remote], default_runner, run, ) diff --git a/roles/sys-ctl-hlth-runtime/vars/main.yml b/roles/sys-ctl-hlth-runtime/vars/main.yml index 98578e0f06..aee9827517 100644 --- a/roles/sys-ctl-hlth-runtime/vars/main.yml +++ b/roles/sys-ctl-hlth-runtime/vars/main.yml @@ -33,4 +33,5 @@ HEALTH_RUNTIME_HOST_EXCLUDES: - /mnt - /media - "{{ DIR_BACKUPS }}" + - "{{ DIR_BACKUPS_NODE }}" - "{{ lookup('nfs_export_base') }}" diff --git a/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_network_mounts.py b/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_network_mounts.py new file mode 100644 index 0000000000..dc5a5a1a90 --- /dev/null +++ b/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_network_mounts.py @@ -0,0 +1,301 @@ +from __future__ import annotations + +import contextlib +import csv +import io +import json +import os +import tempfile +from pathlib import Path +from unittest import TestCase, main, mock + +from utils.storage.nfs import fstype + +from .test_script import MAIN_SCAN, NO_SUPPRESSIONS, SCRIPT, _config + +MOUNTINFO_FIELDS = ( + ("22", "1", "0:21", "/", "/", "rw", "shared:1", "-", "overlay", "overlay", "rw"), + ("25", "22", "0:5", "/", "/proc", "rw", "shared:12", "-", "proc", "proc", "rw"), + ("30", "22", "0:31", "/", "/mnt/docker-fs", "rw", "-", "zfs", "pool/node", "rw"), + ( + "310", + "22", + "0:60", + "/", + "/var/lib/infinito", + "rw,relatime", + "shared:150", + "-", + "nfs4", + "10.100.1.11:/srv/nfs/infinito-state", + "rw,vers=4.2,soft,timeo=50,retrans=3", + ), + ( + "311", + "310", + "0:31", + "/var/lib/infinito-backup", + "/var/lib/infinito/backup", + "rw", + "shared:1", + "-", + "zfs", + "pool/node", + "rw", + ), + ( + "312", + "30", + "0:61", + "/", + "/mnt/docker-fs/docker/volumes/hermes_redis/_data", + "rw", + "-", + "nfs4", + "10.100.1.11:/srv/nfs/infinito-state/hermes_redis", + "rw", + ), + ( + "313", + "22", + "0:62", + "/", + "/srv/team\\040share", + "rw", + "shared:160", + "master:3", + "-", + "cifs", + "//files/team", + "rw", + ), + ( + "314", + "22", + "0:63", + "/", + "/home/admin/remote", + "rw,nosuid", + "-", + "fuse.sshfs", + "admin@backup:", + "rw", + ), + ("315", "22", "0:64", "/", "/run/user/1000", "rw", "-", "tmpfs", "tmpfs", "rw"), + ("316", "22", "0:65", "/", "/srv/a,b", "rw", "-", "cifs", "//files/ab", "rw"), +) +SWARM_NODE_MOUNTINFO = "\n".join(" ".join(fields) for fields in MOUNTINFO_FIELDS) +REMOTE = [ + "/home/admin/remote", + "/mnt/docker-fs/docker/volumes/hermes_redis/_data", + "/srv/a,b", + "/srv/team share", + "/var/lib/infinito", +] +NOT_UTF8_MOUNTINFO = b"1 0 0:20 / /srv/caf\xe9 rw - nfs4 server:/cafe rw\n" +GLOB_MOUNTS = ("/srv/q{a,b}]?*\\w", "/srv/x[y", "/var/lib/docker") + + +def _values(argv, flag): + return [argv[index + 1] for index, arg in enumerate(argv) if arg == flag] + + +def _literal(pattern): + """ + Args: + pattern: a doublestar pattern as Trivy, Syft and Grype match it. + + Returns: + The one path the pattern matches, or None while it holds an unescaped + glob character or ends in a lone backslash. + """ + chars = iter(pattern) + path = [] + for char in chars: + if char == "\\": + escaped = next(chars, None) + if escaped is None: + return None + path.append(escaped) + elif char in "*?[]{}": + return None + else: + path.append(char) + return "".join(path) + + +def _layout(*excludes): + return SCRIPT.Layout( + runtime=("container", "run"), + databases=Path("/var/cache/v/db"), + sbom=Path("/var/cache/v/sbom"), + work=Path("/var/cache/v/run"), + excludes=excludes, + ) + + +def _main(mountinfo, targets): + """ + Args: + mountinfo: the bytes of the host's mountinfo, or None for no file. + targets: the scan targets. + + Returns: + ``(output, layouts)``: what the check printed and the layout of every + scan it started. + """ + layouts = [] + + def scan(targets, config, images, layout, runner): + layouts.append(layout) + return [], [] + + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + for name in ("report", "log"): + (root / name).mkdir() + if mountinfo is not None: + (root / "mountinfo").write_bytes(mountinfo) + argv = [ + "--scan", + json.dumps({**MAIN_SCAN, "targets": targets}), + "--hardened", + "{}", + "--images", + "{}", + "--suppressions", + json.dumps(NO_SUPPRESSIONS), + "--cache-dir", + str(root / "cache"), + "--database-dir", + str(root / "cache" / "db"), + "--host-excludes", + '["/proc"]', + "--environment", + "production", + "--report-dir", + str(root / "report"), + "--log-dir", + str(root / "log"), + ] + with ( + mock.patch.object(SCRIPT, "MOUNTINFO", root / "mountinfo"), + mock.patch.object(SCRIPT, "running_containers", return_value=[]), + mock.patch.object(SCRIPT, "check", return_value=([], [])), + mock.patch.object(SCRIPT, "docker_root", return_value="/var/lib/docker"), + mock.patch.object(SCRIPT, "scan", side_effect=scan), + mock.patch.object(SCRIPT.socket, "gethostname", return_value="node"), + contextlib.redirect_stdout(io.StringIO()) as out, + ): + SCRIPT.main(argv) + return out.getvalue(), layouts + + +def _engine_skips(layout): + host = SCRIPT.host_target("node") + trivy = SCRIPT.trivy_step(layout, "trivy:1", host, _config(), []) + syft = SCRIPT.sbom_step(layout, "syft:1", host) + grype = SCRIPT.grype_step(layout, "grype:1", host, _config(engines=["grype"])) + return { + "trivy": [ + _literal(pattern) + for value in _values(trivy.argv, "--skip-dirs") + for pattern in next(csv.reader([value])) + ], + "syft": [_literal(pattern) for pattern in _values(syft.argv, "--exclude")], + "grype": [_literal(pattern) for pattern in _values(grype.argv, "--exclude")], + } + + +def _expected_skips(point): + return { + "trivy": f"{SCRIPT.HOST_ROOT}{point}", + "syft": f"./{point.strip('/')}", + "grype": f"./{point.strip('/')}", + } + + +class TestNetworkMounts(TestCase): + def test_every_network_filesystem_is_found_with_its_escaped_path(self): + self.assertEqual(SCRIPT.network_mounts(SWARM_NODE_MOUNTINFO), REMOTE) + + def test_local_filesystems_and_binds_of_local_trees_are_kept(self): + found = SCRIPT.network_mounts(SWARM_NODE_MOUNTINFO) + for point in ("/", "/proc", "/mnt/docker-fs", "/var/lib/infinito/backup"): + with self.subTest(point=point): + self.assertNotIn(point, found) + + def test_a_network_root_is_still_scanned(self): + self.assertEqual( + SCRIPT.network_mounts("1 0 0:20 / / rw - nfs4 server:/root rw"), [] + ) + + def test_the_shared_state_mount_of_every_nfs_version_is_found(self): + for version in (3, 4): + with self.subTest(version=version): + self.assertIn(fstype(version), SCRIPT.NETWORK_FSTYPES) + + +class TestSkipPatterns(TestCase): + def test_a_mount_point_with_a_comma_stays_one_skip_dir(self): + self.assertEqual( + _engine_skips(_layout("/srv/a,b"))["trivy"], + [f"{SCRIPT.HOST_ROOT}/srv/a,b"], + ) + + def test_a_mount_point_with_glob_characters_matches_only_itself(self): + skips = _engine_skips(_layout(*GLOB_MOUNTS)) + for engine in ("trivy", "syft", "grype"): + with self.subTest(engine=engine): + self.assertEqual( + skips[engine], + [_expected_skips(point)[engine] for point in GLOB_MOUNTS], + ) + + +class TestHostScanSkipsNetworkMounts(TestCase): + def test_every_engine_skips_each_network_mount_and_the_check_reports_it(self): + output, layouts = _main(SWARM_NODE_MOUNTINFO.encode(), ["host"]) + skips = _engine_skips(layouts[0]) + for point in REMOTE: + with self.subTest(point=point): + self.assertIn( + f"â„šī¸ host scan skips the network or automounted filesystem at {point}", + output.splitlines(), + ) + for engine, path in _expected_skips(point).items(): + self.assertIn(path, skips[engine], engine) + for engine, path in _expected_skips("/mnt/docker-fs").items(): + self.assertNotIn(path, skips[engine], engine) + + def test_a_mount_point_that_is_not_utf8_is_skipped_and_printed_escaped(self): + output, layouts = _main(NOT_UTF8_MOUNTINFO, ["host"]) + point = os.fsdecode(b"/srv/caf\xe9") + skips = _engine_skips(layouts[0]) + for engine, path in _expected_skips(point).items(): + self.assertIn(path, skips[engine], engine) + self.assertIn( + "â„šī¸ host scan skips the network or automounted filesystem at /srv/caf\\xe9", + output.splitlines(), + ) + output.encode("utf-8") + + def test_a_mount_point_with_a_newline_prints_as_one_escaped_line(self): + output, _layouts = _main( + b"1 0 0:20 / /srv/a\\012forged rw - nfs4 server:/a rw\n", ["host"] + ) + lines = output.splitlines() + self.assertIn( + "â„šī¸ host scan skips the network or automounted filesystem at " + "/srv/a\\nforged", + lines, + ) + self.assertNotIn("forged", [line.strip() for line in lines]) + + def test_a_scan_without_the_host_reads_and_reports_no_mount(self): + output, _layouts = _main(None, ["container"]) + self.assertNotIn("host scan skips", output) + + +if __name__ == "__main__": + main() 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 76d23ec951..15077ccd0a 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 @@ -1695,7 +1695,14 @@ class TestCommands(TestCase): def test_the_host_scan_skips_the_excluded_paths(self): step = SCRIPT.trivy_step(self.layout, "trivy:1", self.host, _config(), []) - self.assertIn("/host/proc,/host/var/lib/docker", step.argv) + self.assertEqual( + [ + step.argv[i + 1] + for i, arg in enumerate(step.argv) + if arg == "--skip-dirs" + ], + ['"/host/proc"', '"/host/var/lib/docker"'], + ) def test_syft_scans_the_host_with_the_image_catalogers(self): step = SCRIPT.sbom_step(self.layout, "syft:1", self.host) @@ -2255,6 +2262,7 @@ class TestMain(TestCase): mock.patch.object(SCRIPT, "running_containers", return_value=[]), mock.patch.object(SCRIPT, "check", return_value=([], [])), mock.patch.object(SCRIPT, "docker_root", return_value="/var/lib/docker"), + mock.patch.object(SCRIPT, "host_network_mounts", return_value=[]), mock.patch.object( SCRIPT, "scan", return_value=(list(findings), list(errors)) ), diff --git a/tests/unit/python/roles/sys-ctl-hlth-runtime/vars/__init__.py b/tests/unit/python/roles/sys-ctl-hlth-runtime/vars/__init__.py new file mode 100644 index 0000000000..087c384b57 --- /dev/null +++ b/tests/unit/python/roles/sys-ctl-hlth-runtime/vars/__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/vars/test_host_excludes.py b/tests/unit/python/roles/sys-ctl-hlth-runtime/vars/test_host_excludes.py new file mode 100644 index 0000000000..897eabe9df --- /dev/null +++ b/tests/unit/python/roles/sys-ctl-hlth-runtime/vars/test_host_excludes.py @@ -0,0 +1,153 @@ +from __future__ import annotations + +import posixpath +import unittest +from collections.abc import Iterator, Mapping +from pathlib import PurePosixPath +from typing import Any + +from jinja2 import Environment, StrictUndefined, select_autoescape + +from utils.cache.yaml import load_yaml, load_yaml_any +from utils.roles.mapping import ROLE_FILE_VARS_MAIN +from utils.storage.nfs import get_export_base + +from . import PROJECT_ROOT + +_ROLES = PROJECT_ROOT / "roles" +_GROUP_PATHS = PROJECT_ROOT / "group_vars" / "all" / "05_paths.yml" +_GROUP_PATH_KEYS = ("DIR_VAR_LIB", "DIR_BACKUPS", "DIR_BACKUPS_NODE") +_NFS_CLIENT = "svc-storage-nfs-client" +_NFS_MOUNT_ROLES = (_NFS_CLIENT, "svc-storage-nfs-server") +_NFS_FSTYPE = "{{ STORAGE_NFS_FSTYPE }}" +_INSTALLED_SOFTWARE = ( + "/usr", + "/etc", + "/opt", + "/var/lib/dpkg", + "/var/lib/pacman", + "/var/lib/rpm", + "/usr/lib/sysimage/rpm", + "/lib/apk/db", +) + + +def _lookup(name: str) -> str: + if name == "nfs_export_base": + return get_export_base() + raise KeyError(f"no stub for lookup({name!r})") + + +def _render(template: str, context: Mapping[str, Any]) -> str: + env = Environment( + undefined=StrictUndefined, + autoescape=select_autoescape(default_for_string=False), + ) + env.filters["path_join"] = lambda parts: posixpath.join(*parts) + env.globals["lookup"] = _lookup + return env.from_string(template).render(**context) + + +def _context() -> dict[str, str]: + paths = load_yaml(str(_GROUP_PATHS)) + context: dict[str, str] = {} + for key in _GROUP_PATH_KEYS: + context[key] = _render(paths[key], context) + for role in _NFS_MOUNT_ROLES: + role_vars = load_yaml(str(_ROLES / role / ROLE_FILE_VARS_MAIN)) + context.update( + (key, value) + for key, value in role_vars.items() + if isinstance(value, str) and "{{" not in value + ) + return context + + +def _tasks(node: Any) -> Iterator[Mapping[str, Any]]: + if isinstance(node, list): + for item in node: + yield from _tasks(item) + elif isinstance(node, Mapping): + yield node + for key in ("block", "rescue", "always"): + yield from _tasks(node.get(key)) + + +def _mounts(role: str) -> Iterator[Mapping[str, Any]]: + for task_file in sorted((_ROLES / role / "tasks").rglob("*.yml")): + for task in _tasks(load_yaml_any(str(task_file))): + mount = task.get("ansible.posix.mount") + if isinstance(mount, Mapping) and mount.get("state") != "unmounted": + yield mount + + +def _nfs_mount_paths(context: Mapping[str, Any]) -> list[str]: + """ + Returns: + Every host path, rendered, where the NFS roles mount the shared state. + """ + return [ + _render(mount["path"], context) + for role in _NFS_MOUNT_ROLES + for mount in _mounts(role) + if mount.get("fstype") == _NFS_FSTYPE + ] + + +def _local_bind_paths(context: Mapping[str, Any]) -> list[str]: + """ + Returns: + Every host path, rendered, where the NFS client binds a node-local + tree over the shared state, with that tree. + """ + return [ + _render(mount[key], context) + for mount in _mounts(_NFS_CLIENT) + if "bind" in str(mount.get("opts", "")).split(",") + for key in ("path", "src") + ] + + +def _host_excludes(context: Mapping[str, Any]) -> list[PurePosixPath]: + declared = load_yaml(str(_ROLES / "sys-ctl-hlth-runtime" / ROLE_FILE_VARS_MAIN))[ + "HEALTH_RUNTIME_HOST_EXCLUDES" + ] + return [PurePosixPath(_render(str(entry), context)) for entry in declared] + + +def _skipped(path: str, excludes: list[PurePosixPath]) -> bool: + candidate = PurePosixPath(path) + return any( + candidate == exclude or exclude in candidate.parents for exclude in excludes + ) + + +class TestHostScanExcludes(unittest.TestCase): + def setUp(self) -> None: + self.context = _context() + self.excludes = _host_excludes(self.context) + + def test_the_shared_state_and_the_node_backup_store_are_found(self) -> None: + self.assertIn(self.context["DIR_VAR_LIB"], _nfs_mount_paths(self.context)) + self.assertIn(self.context["DIR_BACKUPS_NODE"], _local_bind_paths(self.context)) + + def test_the_host_scan_skips_the_node_local_backup_store(self) -> None: + for path in _local_bind_paths(self.context): + with self.subTest(path=path): + self.assertTrue( + _skipped(path, self.excludes), + f"the host scan walks {path} on every swarm node: a local " + "tree the network mount detection does not see", + ) + + def test_the_host_scan_keeps_installed_software(self) -> None: + for path in _INSTALLED_SOFTWARE: + with self.subTest(path=path): + self.assertFalse( + _skipped(path, self.excludes), + f"{path} holds installed packages the host scan must read", + ) + + +if __name__ == "__main__": + unittest.main() From b98f3ce40da9aa37534e7843c880cd5e6bc7bdf9 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 17 Nov 2026 21:19:19 +0000 Subject: [PATCH 2/2] fix(tests): list the sys-ctl-hlth-runtime task files through iter_project_files MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit test_host_excludes walked the role's tasks dir with a raw rglob, which the no-raw-project-walk lint rejects (red lint on #2095). It now filters iter_project_files to that dir, identical to IAM d438521a2e; what the test asserts is unchanged. đŸŽ¯ Fix: 95 % đŸ’Ĩ Break: 1 % 💸 Tokens: – âąī¸ Velocity: – đŸ›Ąī¸ Security: 100 % 🏆 Score: 94 đŸšĻ Gate: pending, CI on #2095 Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- .../sys-ctl-hlth-runtime/vars/test_host_excludes.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/tests/unit/python/roles/sys-ctl-hlth-runtime/vars/test_host_excludes.py b/tests/unit/python/roles/sys-ctl-hlth-runtime/vars/test_host_excludes.py index 897eabe9df..db9033e248 100644 --- a/tests/unit/python/roles/sys-ctl-hlth-runtime/vars/test_host_excludes.py +++ b/tests/unit/python/roles/sys-ctl-hlth-runtime/vars/test_host_excludes.py @@ -1,5 +1,6 @@ from __future__ import annotations +import os import posixpath import unittest from collections.abc import Iterator, Mapping @@ -8,6 +9,7 @@ from typing import Any from jinja2 import Environment, StrictUndefined, select_autoescape +from utils.cache.files import iter_project_files from utils.cache.yaml import load_yaml, load_yaml_any from utils.roles.mapping import ROLE_FILE_VARS_MAIN from utils.storage.nfs import get_export_base @@ -74,8 +76,14 @@ def _tasks(node: Any) -> Iterator[Mapping[str, Any]]: def _mounts(role: str) -> Iterator[Mapping[str, Any]]: - for task_file in sorted((_ROLES / role / "tasks").rglob("*.yml")): - for task in _tasks(load_yaml_any(str(task_file))): + tasks_dir = f"{_ROLES / role / 'tasks'}{os.sep}" + task_files = ( + path + for path in iter_project_files(extensions=(".yml",)) + if path.startswith(tasks_dir) + ) + for task_file in sorted(task_files): + for task in _tasks(load_yaml_any(task_file)): mount = task.get("ansible.posix.mount") if isinstance(mount, Mapping) and mount.get("state") != "unmounted": yield mount