diff --git a/cli/contributing/security/scan/__main__.py b/cli/contributing/security/scan/__main__.py index 1363d8290b..f4f2121f6c 100755 --- a/cli/contributing/security/scan/__main__.py +++ b/cli/contributing/security/scan/__main__.py @@ -88,6 +88,9 @@ def targets_of(p: ModuleType, grouped: Mapping[str, Sequence[ImageRef]]) -> list ref=digest, label=refs[0].source, owners=tuple(sorted({(ref.role, ref.service) for ref in refs})), + owner_tags=tuple( + sorted({((ref.role, ref.service), ref.version) for ref in refs}) + ), ) for digest, refs in sorted(grouped.items()) ] @@ -238,7 +241,10 @@ def suppressions_of(p: ModuleType, roles: Sequence[str]): containers={ role: { service: tuple( - p.Suppression(id=entry.id, until=entry.until) for entry in entries + p.Suppression( + id=entry.id, image_tag=entry.image_tag, until=entry.until + ) + for entry in entries ) for service, entries in role_suppressions( PROJECT_ROOT / "roles", role diff --git a/docs/contributing/actions/testing/suppression.md b/docs/contributing/actions/testing/suppression.md index 10fa075366..ef29523d65 100644 --- a/docs/contributing/actions/testing/suppression.md +++ b/docs/contributing/actions/testing/suppression.md @@ -48,7 +48,7 @@ The placement rule is per check. The catalog "Position" column uses these labels | `docker-version` | same or above | [test_image_versions.py](../../../../tests/external/update/docker/test_image_versions.py), [test_semver_pinning.py](../../../../tests/lint/ansible/services/test_semver_pinning.py) | Skips both the live version-update warning and the non-semver-pin lint for that image's `version:` key. | | `repository-version` | same or above | [test_repository_versions.py](../../../../tests/external/update/repository/test_repository_versions.py), [test_semver_pinning.py](../../../../tests/lint/ansible/services/test_semver_pinning.py) | Skips both the live ref-update warning and the non-semver-pin lint for that entity's `ref:` key. | | `version-source` | same or above | [test_version_sources.py](../../../../tests/external/update/source/test_version_sources.py) | Skips the live update warning for a pin that declares its upstream in an `update:` block. | -| `cve` | line above | [test_cve_suppressions.py](../../../../tests/lint/ansible/services/test_cve_suppressions.py), [script.py](../../../../roles/sys-ctl-hlth-runtime/files/python/script.py) | Accepts one CVE of a `.security.suppressions` entry (`id: CVE-YYYY-NNNN`, `until: YYYY-MM-DD`) in the owning role's `meta/services.yml`. The marker MUST carry the reason, and the vulnerability scan of `sys-ctl-hlth-runtime` and `make test-security` skip that CVE for that role's service until the date passes. Host suppressions sit under the engine entries of `sys-ctl-hlth-runtime`. | +| `cve` | line above | [test_cve_suppressions.py](../../../../tests/lint/ansible/services/test_cve_suppressions.py), [script.py](../../../../roles/sys-ctl-hlth-runtime/files/python/script.py) | Accepts one `.security.suppressions` entry plus `until: YYYY-MM-DD` in the owning role's `meta/services.yml`: `id: CVE-YYYY-NNNN` accepts that CVE, `image_tag` every finding of the service's image while it runs that tag, and the tag MUST equal the service's `version`; the image updater drops it when it moves the service to another version. The marker MUST carry the reason, and the vulnerability scan of `sys-ctl-hlth-runtime` and `make test-security` skip the entry's findings for that role's service until the date passes. Host suppressions are the `id` entries under the engine entries of `sys-ctl-hlth-runtime`; an `image_tag` entry there covers the engine's own image. | | `unwatched-version` | same or above | [test_version_pins_are_watched.py](../../../../tests/lint/repository/test_version_pins_are_watched.py) | Accepts a semver pin that no updater bumps. The marker MUST carry a reason naming why the version stays where it is. | | `dockerfile-arg-default` | same or above | [test_arg_without_default.py](../../../../tests/lint/docker/dockerfile/test_arg_without_default.py) | Allows the marked `ARG` to carry a default. The caller normally supplies every build argument so a missing one fails the build instead of selecting a base image nobody chose. | | `debian-codename` | same or above | [test_no_debian_codename_tags.py](../../../../tests/lint/repository/test_no_debian_codename_tags.py) | Allows an image reference whose tag names a Debian release by codename. Reserved for an upstream that publishes no numeric tag; the marker MUST name which upstream, because a codename pin can never be raised by the updater. | diff --git a/docs/requirements/070-hlth-runtime-vulnerability-engines.md b/docs/requirements/070-hlth-runtime-vulnerability-engines.md index f59fe957c4..87825ad652 100644 --- a/docs/requirements/070-hlth-runtime-vulnerability-engines.md +++ b/docs/requirements/070-hlth-runtime-vulnerability-engines.md @@ -27,10 +27,11 @@ Issue: [#1324](https://github.com/infinito-nexus/core/issues/1324). - [ ] While `web-app-prometheus` is deployed, the role passes `--metrics-file` and the check replaces `infinito_hlth_runtime.prom` in `DIR_METRICS_TEXTFILE` atomically with `infinito_hlth_runtime_findings{target,kind,image,severity,scanner,verdict}` (a count, no CVE label), `infinito_hlth_runtime_last_run_timestamp_seconds`, `infinito_hlth_runtime_last_run_success` (1 when the run did not fail) and `infinito_hlth_runtime_scanner_errors{scanner}`, each with `# HELP` and `# TYPE` and escaped label values; without the flag no textfile is written. - [ ] A database refresh or a provided database that is missing fails the service loudly, and OSV-Scanner reporting no database for an ecosystem is an error. - [ ] The timer runs daily at 00:00 UTC and the deploy-time run stays. -- [ ] A suppression is `services..security.suppressions` of the owning role, each entry `id: CVE-YYYY-NNNN` plus `until: YYYY-MM-DD` with a `# nocheck: cve ` marker directly above it. -- [ ] A role's suppressions apply only to the containers of its own stack or compose project and service; host suppressions sit under the engine entries of `sys-ctl-hlth-runtime` and apply to that engine's host findings. +- [ ] A suppression is `services..security.suppressions` of the owning role, each entry either `id: CVE-YYYY-NNNN` or a quoted `image_tag`, plus `until: YYYY-MM-DD`, with a `# nocheck: cve ` marker directly above it. +- [ ] An `id` entry suppresses that CVE; an `image_tag` entry suppresses every finding of the service's container while the scanned image runs that tag, and a container running any other tag is judged unsuppressed. The Docker image updater removes a service's `image_tag` entries, with their markers, when it moves that service to another version. +- [ ] A role's suppressions apply only to the containers of its own stack or compose project and service; host suppressions are the `id` entries under the engine entries of `sys-ctl-hlth-runtime` and apply to that engine's host findings, while an `image_tag` entry there covers the engine's own image. - [ ] `docs/contributing/actions/testing/suppression.md` lists the `cve` rule. -- [ ] The lint under `tests/lint/` rejects a marker without a reason, a malformed id, a missing or past `until` and an entry without a marker. +- [ ] The lint under `tests/lint/` rejects a marker without a reason, a malformed id, an entry with both or neither of `id` and `image_tag`, an `image_tag` that differs from the service's `version`, a missing or past `until` and an entry without a marker. - [ ] Each CI deploy job draws one engine (trivy, grype or osv) by rotation; its job name carries đŸ”ē, 🍇 or 🐙, the axis glyph is đŸ”Ŧ, and `utils/symbol_glossary.py` registers all four. - [ ] A CI deploy pins `engines` to `[syft, ]`, reads provided databases and never downloads one; the `vulnerability-db` job of `call-test-deploy.yml` downloads the Trivy, Grype and OSV databases once per day into the Actions cache, every deploy job restores the Grype database plus the drawn engine's, and a missing one fails the job. - [ ] A local development deploy (`make compose-deploy`, swarm through act or `make swarm-zombie`) draws one engine at random, runs it behind Syft plus the Grype runtime pass, refreshes the databases it reads once in the shared host directory `INFINITO_VULNERABILITY_DB_HOST_PATH`, and every stack and swarm node reads that directory read-only at `INFINITO_VULNERABILITY_DB_DIR`; no stack and no node downloads a database. diff --git a/roles/sys-ctl-hlth-runtime/README.md b/roles/sys-ctl-hlth-runtime/README.md index 7853db8f94..aa50a1db17 100644 --- a/roles/sys-ctl-hlth-runtime/README.md +++ b/roles/sys-ctl-hlth-runtime/README.md @@ -36,7 +36,7 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( - **Findings log:** `findings.jsonl` in `DIR_HEALTH_RUNTIME_LOG` gets one JSON line per record and run, for Wazuh. A logrotate drop-in rotates it weekly and keeps 12 compressed generations. - **Journal:** Besides the `â„šī¸`, `âš ī¸` and `❌` lines, the check prints one JSON line per target, `{"event": "hlth_runtime.target", "run_id", "target", "kind", "image", "counts", "verdict"}` with `verdict` `fail`, `warn` or `ok`, and last `{"event": "hlth_runtime.summary", "run_id", "counts", "errors", "verdict"}`, for Loki. - **Metrics:** While `web-app-prometheus` is deployed, the check replaces `infinito_hlth_runtime.prom` in `DIR_METRICS_TEXTFILE` atomically with the gauges `infinito_hlth_runtime_findings{target,kind,image,severity,scanner,verdict}`, `infinito_hlth_runtime_last_run_timestamp_seconds`, `infinito_hlth_runtime_last_run_success` and `infinito_hlth_runtime_scanner_errors{scanner}`. No series carries a CVE id. -- **Suppressions:** A role accepts a CVE for its own containers under `.security.suppressions` of its `meta/services.yml`, each entry `id` plus `until` below a `# nocheck: cve ` marker, see [suppression.md](../../docs/contributing/actions/testing/suppression.md). Host suppressions sit under the engine entries of this role and cover that engine's host findings. +- **Suppressions:** A role accepts findings for its own containers under `.security.suppressions` of its `meta/services.yml`, each entry `id` (one CVE) or `image_tag` (every finding of the image while it runs that tag, which MUST equal the service's `version`) plus `until` below a `# nocheck: cve ` marker, see [suppression.md](../../docs/contributing/actions/testing/suppression.md). Host suppressions are the `id` entries under the engine entries of this role and cover that engine's host findings; an `image_tag` entry there covers the engine's own image. - **Databases:** With `db_update` the engines refresh their databases under `database_dir` before each run, three attempts 30 s apart; without it the databases MUST already be there, and a missing one fails the run. SBOMs of running images are cached under `cache_dir` by image id. - **Deploy-time run:** The deploy runs the check once at its end and fails on its first failure, without the retries `sys-service-terminator` gives other units. - **Development and CI deploys:** A CI row pins one engine and restores its databases; a local deploy draws one engine and refreshes the shared host directory `INFINITO_VULNERABILITY_DB_HOST_PATH`. Both run it behind Syft plus the Grype runtime pass and read the databases read-only at `INFINITO_VULNERABILITY_DB_DIR`. Production hosts run every engine. diff --git a/roles/sys-ctl-hlth-runtime/files/python/script.py b/roles/sys-ctl-hlth-runtime/files/python/script.py index 64d74ddc34..11fd7c2966 100755 --- a/roles/sys-ctl-hlth-runtime/files/python/script.py +++ b/roles/sys-ctl-hlth-runtime/files/python/script.py @@ -148,6 +148,8 @@ class Target: ref: the image id, or :data:`HOST_ROOT`. label: the image name or the host name. owners: ``(stack, service)`` of every container running the image. + owner_tags: ``((stack, service), tag)`` pairs, the image tag each + owner runs the image under; empty for the host. """ key: str @@ -155,6 +157,10 @@ class Target: ref: str label: str owners: tuple[tuple[str | None, str | None], ...] + owner_tags: tuple[tuple[tuple[str | None, str | None], str], ...] + + def tag_of(self, owner: tuple[str | None, str | None]) -> str | None: + return dict(self.owner_tags).get(owner) @dataclass(frozen=True) @@ -186,9 +192,22 @@ class Finding: @dataclass(frozen=True) class Suppression: - id: str + """One accepted CVE, or every finding of one image tag. + + Args: + id: the CVE id, ``None`` for an image tag entry. + image_tag: the image tag, ``None`` for a CVE entry. + until: the last day the suppression applies. + """ + + id: str | None + image_tag: str | None until: dt.date + @property + def subject(self) -> str: + return self.id or f"image tag {self.image_tag}" + @dataclass(frozen=True) class Suppressions: @@ -538,7 +557,11 @@ def scan_config(raw: Mapping) -> ScanConfig: def suppressions_from_json(raw: Mapping) -> Suppressions: def entries(items: Iterable[Mapping]) -> tuple[Suppression, ...]: return tuple( - Suppression(id=item["id"], until=dt.date.fromisoformat(item["until"])) + Suppression( + id=item["id"], + image_tag=item["image_tag"], + until=dt.date.fromisoformat(item["until"]), + ) for item in items ) @@ -727,9 +750,37 @@ def threshold(finding: Finding, config: ScanConfig) -> str | None: return config.severity.get(finding.severity) -def matching(rules: Sequence[Suppression], finding: Finding) -> Suppression | None: - """Return the suppression naming one of the finding's ids, latest first.""" - hits = [rule for rule in rules if rule.id in finding.ids] +def image_tag(name: str) -> str: + """Return the tag of an image reference, ``latest`` when it names none. + + Args: + name: ``[registry/]repository[:tag][@digest]``. + """ + repository = name.split("@", 1)[0].rsplit("/", 1)[-1] + _, separator, tag = repository.partition(":") + return tag if separator else "latest" + + +def matching( + rules: Sequence[Suppression], finding: Finding, tag: str | None +) -> Suppression | None: + """Return the suppression covering the finding, latest first. + + Args: + rules: the suppressions of the finding's owner. + finding: the finding. + tag: the tag of the scanned image, ``None`` for the host, where no + image tag entry applies. + """ + hits = [ + rule + for rule in rules + if ( + rule.id in finding.ids + if rule.id + else tag is not None and rule.image_tag == tag + ) + ] return max(hits, key=lambda rule: rule.until) if hits else None @@ -807,7 +858,7 @@ def verdicts( rules = () else: rules = suppressions.containers.get(owner[0], {}).get(owner[1], ()) - rule = matching(rules, finding) + rule = matching(rules, finding, target.tag_of(owner)) judged.append( Verdict( finding, @@ -847,7 +898,7 @@ def report_lines( continue if verdict.rule is not None: infos.append( - f"{verdict.where()}: suppression of {verdict.rule.id} expired on {verdict.rule.until}" + f"{verdict.where()}: suppression of {verdict.rule.subject} expired on {verdict.rule.until}" ) (failures if verdict.action == "fail" else warnings).append(line) return failures, warnings, infos @@ -1080,13 +1131,24 @@ def container_targets(containers: Iterable[Container]) -> list[Target]: ref=image, label=members[0].image_name, owners=tuple((member.stack, member.service) for member in members), + owner_tags=tuple( + ((member.stack, member.service), image_tag(member.image_name)) + for member in members + ), ) ) return targets def host_target(hostname: str) -> Target: - return Target(key="host", kind="host", ref=HOST_ROOT, label=hostname, owners=()) + return Target( + key="host", + kind="host", + ref=HOST_ROOT, + label=hostname, + owners=(), + owner_tags=(), + ) def _env(pairs: Mapping[str, str]) -> list[str]: diff --git a/roles/sys-ctl-hlth-runtime/lookup_plugins/cve_suppressions.py b/roles/sys-ctl-hlth-runtime/lookup_plugins/cve_suppressions.py index 29618c7594..b2a894997f 100644 --- a/roles/sys-ctl-hlth-runtime/lookup_plugins/cve_suppressions.py +++ b/roles/sys-ctl-hlth-runtime/lookup_plugins/cve_suppressions.py @@ -21,9 +21,11 @@ def collect(group_names: list[str]) -> dict[str, dict]: Returns: ``{"containers": {entity: {service: [entry]}}, "host": {engine: - [entry]}}`` where an entry is ``{"id", "until"}``. The entity is the - compose project and swarm stack name, so a role's suppressions reach - only its own containers. + [entry]}}`` where an entry is ``{"id", "image_tag", "until"}``. The + entity is the compose project and swarm stack name, so a role's + suppressions reach only its own containers. The host takes the + ``id`` entries of the engine services only; their ``image_tag`` + entries cover the engine's own image. """ containers: dict[str, dict[str, list[dict[str, str]]]] = {} for role in sorted(set(group_names)): @@ -36,7 +38,7 @@ def collect(group_names: list[str]) -> dict[str, dict]: } own = role_suppressions(ROLES_DIR, ROLE) host = { - engine: [entry.as_json() for entry in entries] + engine: [entry.as_json() for entry in entries if entry.id] for engine, entries in own.items() if engine in SCANNERS } diff --git a/tests/lint/ansible/services/test_cve_suppressions.py b/tests/lint/ansible/services/test_cve_suppressions.py index 523edd83a7..e0d0927c31 100644 --- a/tests/lint/ansible/services/test_cve_suppressions.py +++ b/tests/lint/ansible/services/test_cve_suppressions.py @@ -1,15 +1,21 @@ """Lint: every CVE suppression in a role's ``meta/services.yml`` is justified and dated. -An entry under ``.security.suppressions`` needs ``id: CVE-YYYY-NNNN``, -an ``until: YYYY-MM-DD`` that has not passed, and a ``# nocheck: cve `` -marker on the line directly above it:: +An entry under ``.security.suppressions`` needs ``id: CVE-YYYY-NNNN`` +or an ``image_tag`` equal to the service's ``version``, an ``until: +YYYY-MM-DD`` that has not passed, and a ``# nocheck: cve `` marker on +the line directly above it:: checkmk: + image: checkmk/check-mk-raw + version: "2.4.0p39" security: suppressions: # nocheck: cve the vulnerable module is not loaded by the site - id: CVE-2026-1234 until: 2026-12-31 + # nocheck: cve upstream ships no rebuild with the fixed packages yet + - image_tag: "2.4.0p39" + until: 2026-12-31 """ from __future__ import annotations @@ -96,7 +102,13 @@ def problems(text: str, where: str, today: dt.date) -> list[str]: continue if parsed.until < today: found.append( - f"{where}: {service} suppression of {parsed.id} expired on {parsed.until}" + f"{where}: {service} suppression of {parsed.subject} expired on {parsed.until}" + ) + version = spec.get("version") + if parsed.image_tag is not None and parsed.image_tag != str(version): + found.append( + f"{where}: {service} suppression of {parsed.subject} does not " + f"match its version {version!r}" ) return found @@ -168,6 +180,42 @@ class TestCheckerCases(unittest.TestCase): text = VALID.replace("nocheck: cve", "nocheck: url") self.assertIn("has no # nocheck: cve marker", self._problems(text)[0]) + def test_an_image_tag_of_the_current_version_passes(self) -> None: + self.assertEqual(self._problems(TAGGED), []) + + def test_an_image_tag_of_an_older_version_fails(self) -> None: + text = TAGGED.replace('version: "2.18.6"', 'version: "2.18.7"') + self.assertIn( + "image tag 2.18.6 does not match its version '2.18.7'", + self._problems(text)[0], + ) + + def test_an_image_tag_without_a_version_fails(self) -> None: + text = TAGGED.replace(' version: "2.18.6"\n', "") + self.assertIn("does not match its version None", self._problems(text)[0]) + + def test_an_unmarked_image_tag_entry_fails(self) -> None: + text = TAGGED.replace( + " # nocheck: cve upstream ships no rebuild yet\n", "" + ) + self.assertIn("has no # nocheck: cve marker", self._problems(text)[0]) + + def test_an_expired_image_tag_entry_fails(self) -> None: + text = TAGGED.replace("2026-12-31", "2026-10-30") + self.assertIn("image tag 2.18.6 expired on 2026-10-30", self._problems(text)[0]) + + +TAGGED = """\ +app: + image: app + version: "2.18.6" + security: + suppressions: + # nocheck: cve upstream ships no rebuild yet + - image_tag: "2.18.6" + until: 2026-12-31 +""" + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/cli/contributing/security/test_scan.py b/tests/unit/python/cli/contributing/security/test_scan.py index 431904d2d2..b64dfae7a0 100644 --- a/tests/unit/python/cli/contributing/security/test_scan.py +++ b/tests/unit/python/cli/contributing/security/test_scan.py @@ -71,6 +71,24 @@ class TestTargets(TestCase): self.assertEqual(target.owners, (("web-app-a", "a"), ("web-app-b", "b"))) self.assertEqual(target.key, "abc") + def test_each_owner_keeps_its_own_pinned_tag(self): + target = scan_main.targets_of( + P, + { + "sha256:abc": [ + _ref("web-app-moodle", "nginx", "library/nginx", "1.31.8-alpine"), + _ref("web-app-hugo", "nginx", "library/nginx", "1.31-alpine"), + ] + }, + )[0] + self.assertEqual( + ( + target.tag_of(("web-app-hugo", "nginx")), + target.tag_of(("web-app-moodle", "nginx")), + ), + ("1.31-alpine", "1.31.8-alpine"), + ) + class TestSteps(TestCase): def setUp(self): @@ -87,6 +105,7 @@ class TestSteps(TestCase): "sha256:abc", "docker.io/library/php:8.4.26-cli", (("r", "s"),), + ((("r", "s"), "8.4.26-cli"),), ) def test_syft_reads_the_mirror_by_digest_without_a_daemon(self): @@ -113,6 +132,7 @@ class TestReport(TestCase): "sha256:abc", "docker.io/library/php:8.4.26-cli", (("r", "s"),), + ((("r", "s"), "8.4.26-cli"),), ) def _finding(self, severity): @@ -134,7 +154,7 @@ class TestReport(TestCase): finding, self.target, ("r", "t"), - P.Suppression("CVE-2026-109618", dt.date(2026, 12, 31)), + P.Suppression("CVE-2026-109618", None, dt.date(2026, 12, 31)), True, "fail", ), @@ -170,7 +190,14 @@ class TestScanTree(TestCase): work=root / "run", excludes=(), ) - target = P.Target("abc", "container", "sha256:abc", "img", (("r", "s"),)) + target = P.Target( + "abc", + "container", + "sha256:abc", + "img", + (("r", "s"),), + ((("r", "s"), "latest"),), + ) (root / "sbom" / "abc.syft.json").write_text("{}", encoding="utf-8") (root / "sbom" / "abc.cdx.json").write_text( json.dumps({"components": []}), encoding="utf-8" 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 22bd8e9f8e..4c0f7d2e54 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 @@ -388,7 +388,11 @@ def _suppressions(containers=None, host=None): def _rule(cve="CVE-2026-0001", until=TODAY): - return SCRIPT.Suppression(id=cve, until=until) + return SCRIPT.Suppression(id=cve, image_tag=None, until=until) + + +def _tag_rule(tag, until=TODAY): + return SCRIPT.Suppression(id=None, image_tag=tag, until=until) def _container(name, stack=None, service=None, image="sha256:img"): @@ -498,6 +502,7 @@ class TestSourceBuiltRuntime(TestCase): "sha256:img", "roundcube:1.7.5-apache", (("roundcube", "roundcube"),), + ((("roundcube", "roundcube"), "1.7.5-apache"),), ) return SCRIPT.evaluate( SCRIPT.parse_grype(GRYPE_PHP_RUNTIME, "img"), @@ -755,9 +760,14 @@ class TestVerdict(TestCase): class TestSuppressions(TestCase): - def _container_target(self, owners): + def _container_target(self, owners, tag="2.4.0p39"): return SCRIPT.Target( - "img", "container", "sha256:img", "checkmk/check-mk-raw:2.4.0p39", owners + "img", + "container", + "sha256:img", + "checkmk/check-mk-raw:2.4.0p39", + owners, + tuple((owner, tag) for owner in owners), ) def _evaluate(self, target, suppressions, finding=None): @@ -842,24 +852,140 @@ class TestSuppressions(TestCase): failures, _warnings, _infos = self._evaluate(target, _suppressions()) self.assertIn("unmanaged container", failures[0]) + def test_an_image_tag_suppression_silences_every_finding_of_that_tag(self): + target = self._container_target((("checkmk", "checkmk"),)) + failures, _warnings, infos = SCRIPT.evaluate( + [ + _finding(target="img", ids=("CVE-2026-0001",)), + _finding(target="img", ids=("CVE-2026-0002",), severity="CRITICAL"), + ], + {target.key: target}, + _config(severity=STRICT), + _suppressions({"checkmk": {"checkmk": (_tag_rule("2.4.0p39"),)}}), + TODAY, + ) + self.assertEqual((failures, len(infos)), ([], 2)) + + def test_an_image_tag_suppression_of_another_tag_does_not_apply(self): + target = self._container_target((("checkmk", "checkmk"),)) + failures, _warnings, infos = self._evaluate( + target, _suppressions({"checkmk": {"checkmk": (_tag_rule("2.4.0p38"),)}}) + ) + self.assertEqual((len(failures), infos), (1, [])) + + def test_an_expired_image_tag_suppression_fails_and_names_the_tag(self): + target = self._container_target((("checkmk", "checkmk"),)) + failures, _warnings, infos = self._evaluate( + target, + _suppressions( + { + "checkmk": { + "checkmk": ( + _tag_rule("2.4.0p39", TODAY - dt.timedelta(days=1)), + ) + } + } + ), + ) + self.assertEqual(len(failures), 1) + self.assertIn("image tag 2.4.0p39 expired on 2026-10-30", infos[0]) + + def test_each_owner_of_a_shared_image_is_judged_by_its_own_tag(self): + hugo, moodle = ("hugo", "nginx"), ("moodle", "nginx") + target = SCRIPT.Target( + "img", + "container", + "sha256:img", + "nginx:1.31.8-alpine", + (hugo, moodle), + ((hugo, "1.31-alpine"), (moodle, "1.31.8-alpine")), + ) + rule = (_tag_rule("1.31-alpine"),) + failures, _warnings, _infos = self._evaluate( + target, _suppressions({"hugo": {"nginx": rule}, "moodle": {"nginx": rule}}) + ) + self.assertEqual( + failures, + [ + "trivy container moodle/nginx nginx:1.31.8-alpine: CVE-2026-0001 HIGH openssl 1.0 (fixed in 1.1)" + ], + ) + + def test_an_image_tag_never_suppresses_the_host(self): + target = SCRIPT.host_target("latest") + failures, _warnings, _infos = SCRIPT.evaluate( + [_finding()], + {"host": target}, + _config(severity=STRICT), + _suppressions(host={"trivy": (_tag_rule("latest"),)}), + TODAY, + ) + self.assertEqual(len(failures), 1) + def test_suppressions_from_json(self): parsed = SCRIPT.suppressions_from_json( { "containers": { "checkmk": { - "checkmk": [{"id": "CVE-2026-1", "until": "2026-12-31"}] + "checkmk": [ + { + "id": "CVE-2026-1", + "image_tag": None, + "until": "2026-12-31", + }, + { + "id": None, + "image_tag": "2.4.0p39", + "until": "2026-12-31", + }, + ] } }, "host": {}, } ) self.assertEqual( - parsed.containers["checkmk"]["checkmk"][0].until, - dt.date(2026, 12, 31), + parsed.containers["checkmk"]["checkmk"], + ( + SCRIPT.Suppression("CVE-2026-1", None, dt.date(2026, 12, 31)), + SCRIPT.Suppression(None, "2.4.0p39", dt.date(2026, 12, 31)), + ), ) +class TestImageTag(TestCase): + def test_cases(self): + cases = { + "checkmk/check-mk-raw:2.4.0p39": "2.4.0p39", + "ghcr.io/infinito-nexus/core/mirror/docker.io/penpotapp/exporter:2.18.5": "2.18.5", + "penpotapp/exporter:2.18.5@sha256:abc": "2.18.5", + "registry.local:5000/app": "latest", + "registry.local:5000/app:1.2": "1.2", + "postgres@sha256:abc": "latest", + } + self.assertEqual({name: SCRIPT.image_tag(name) for name in cases}, cases) + + class TestContainerTargets(TestCase): + def test_each_owner_keeps_the_tag_its_container_runs(self): + first = _container("a", "hugo", "nginx") + second = SCRIPT.Container( + id="id-b", + name="b", + stack="moodle", + service="nginx", + image="sha256:img", + image_name="nginx:1.31.8-alpine@sha256:abc", + ) + (target,) = SCRIPT.container_targets([first, second]) + self.assertEqual( + (target.tag_of(("hugo", "nginx")), target.tag_of(("moodle", "nginx"))), + ("1", "1.31.8-alpine"), + ) + + def test_the_host_has_no_image_tag(self): + self.assertIsNone(SCRIPT.host_target("node").tag_of((None, None))) + def test_containers_of_one_image_share_a_target(self): targets = SCRIPT.container_targets( [ @@ -1109,7 +1235,12 @@ class TestCommands(TestCase): ) self.host = SCRIPT.host_target("node") self.container = SCRIPT.Target( - "abc", "container", "sha256:abc", "app:1", (("app", "app"),) + "abc", + "container", + "sha256:abc", + "app:1", + (("app", "app"),), + ((("app", "app"), "1"),), ) def test_the_host_is_mounted_read_only(self): @@ -1357,6 +1488,7 @@ NEXTCLOUD = SCRIPT.Target( "sha256:abc", "nextcloud:31", (("nextcloud", "nextcloud"), ("nextcloud", "cron")), + ((("nextcloud", "nextcloud"), "31"), (("nextcloud", "cron"), "31")), ) @@ -1573,7 +1705,12 @@ class TestMetrics(TestCase): def test_label_values_are_escaped(self): target = SCRIPT.Target( - "abc", "container", "sha256:abc", 'odd"\\name\n', ((None, None),) + "abc", + "container", + "sha256:abc", + 'odd"\\name\n', + ((None, None),), + (((None, None), "latest"),), ) text = _outcome([_verdict(target, (None, None), action="warn")]).metrics() self.assertIn('image="odd\\"\\\\name\\n@sha256:abc"', text) @@ -1701,7 +1838,11 @@ class TestMain(TestCase): def test_a_suppressed_finding_is_info_and_passes(self): suppressions = { "containers": {}, - "host": {"grype": [{"id": "CVE-2026-0001", "until": "2099-12-31"}]}, + "host": { + "grype": [ + {"id": "CVE-2026-0001", "image_tag": None, "until": "2099-12-31"} + ] + }, } code, output = self._main([CRITICAL_FINDING], suppressions=suppressions) self.assertEqual(code, 0) diff --git a/tests/unit/python/roles/sys-ctl-hlth-runtime/lookup_plugins/test_cve_suppressions.py b/tests/unit/python/roles/sys-ctl-hlth-runtime/lookup_plugins/test_cve_suppressions.py index c2e3d988bf..5f440c4d18 100644 --- a/tests/unit/python/roles/sys-ctl-hlth-runtime/lookup_plugins/test_cve_suppressions.py +++ b/tests/unit/python/roles/sys-ctl-hlth-runtime/lookup_plugins/test_cve_suppressions.py @@ -31,27 +31,41 @@ def _load_module(): MODULE = _load_module() UNTIL = dt.date(2026, 12, 31) DECLARED = { - "web-app-checkmk": {"checkmk": [Suppression("CVE-2026-1", UNTIL)]}, + "web-app-checkmk": { + "checkmk": [ + Suppression("CVE-2026-1", None, UNTIL), + Suppression(None, "2.4.0p39", UNTIL), + ] + }, "sys-ctl-hlth-runtime": { - "trivy": [Suppression("CVE-2026-2", UNTIL)], - "runtime": [Suppression("CVE-2026-3", UNTIL)], + "trivy": [Suppression("CVE-2026-2", None, UNTIL)], + "runtime": [Suppression("CVE-2026-3", None, UNTIL)], }, } -def _declared(_roles_dir, role): - return DECLARED.get(role, {}) +def _declared(declared): + return lambda _roles_dir, role: declared.get(role, {}) class TestCollect(TestCase): - def _collect(self, roles): - with mock.patch.object(MODULE, "role_suppressions", side_effect=_declared): + def _collect(self, roles, declared=DECLARED): + with mock.patch.object( + MODULE, "role_suppressions", side_effect=_declared(declared) + ): return MODULE.collect(roles) def test_a_role_is_keyed_by_its_stack_name(self): self.assertEqual( self._collect(["web-app-checkmk"])["containers"], - {"checkmk": {"checkmk": [{"id": "CVE-2026-1", "until": "2026-12-31"}]}}, + { + "checkmk": { + "checkmk": [ + {"id": "CVE-2026-1", "image_tag": None, "until": "2026-12-31"}, + {"id": None, "image_tag": "2.4.0p39", "until": "2026-12-31"}, + ] + } + }, ) def test_a_role_without_suppressions_is_left_out(self): @@ -60,7 +74,29 @@ class TestCollect(TestCase): def test_host_suppressions_come_from_the_engine_entries_only(self): self.assertEqual( self._collect([])["host"], - {"trivy": [{"id": "CVE-2026-2", "until": "2026-12-31"}]}, + {"trivy": [{"id": "CVE-2026-2", "image_tag": None, "until": "2026-12-31"}]}, + ) + + def test_an_engine_image_tag_entry_covers_its_image_not_the_host(self): + declared = { + "sys-ctl-hlth-runtime": { + "grype": [ + Suppression("CVE-2026-2", None, UNTIL), + Suppression(None, "v0.121.0", UNTIL), + ] + } + } + collected = self._collect(["sys-ctl-hlth-runtime"], declared) + self.assertEqual( + ( + [entry["image_tag"] for entry in collected["host"]["grype"]], + [ + entry["image_tag"] + for entries in collected["containers"].values() + for entry in entries["grype"] + ], + ), + ([None], [None, "v0.121.0"]), ) diff --git a/tests/unit/python/utils/security/test_suppressions.py b/tests/unit/python/utils/security/test_suppressions.py index a3196d413d..4bc9deb990 100644 --- a/tests/unit/python/utils/security/test_suppressions.py +++ b/tests/unit/python/utils/security/test_suppressions.py @@ -5,9 +5,11 @@ import tempfile from pathlib import Path from unittest import TestCase, main +from utils.cache.yaml import load_yaml_str from utils.security.suppressions import ( Suppression, SuppressionError, + drop_image_tag_entries, parse_entries, role_suppressions, service_suppressions, @@ -19,7 +21,42 @@ class TestParseEntries(TestCase): parsed = parse_entries( [{"id": "CVE-2026-1234", "until": dt.date(2026, 12, 31)}], "r:s" ) - self.assertEqual(parsed, [Suppression("CVE-2026-1234", dt.date(2026, 12, 31))]) + self.assertEqual( + parsed, [Suppression("CVE-2026-1234", None, dt.date(2026, 12, 31))] + ) + + def test_an_image_tag_entry_is_kept(self): + parsed = parse_entries([{"image_tag": "2.18.5", "until": "2026-12-31"}], "r:s") + self.assertEqual(parsed, [Suppression(None, "2.18.5", dt.date(2026, 12, 31))]) + + def test_an_entry_with_id_and_image_tag_is_rejected(self): + with self.assertRaisesRegex( + SuppressionError, "exactly one of id and image_tag" + ): + parse_entries( + [ + { + "id": "CVE-2026-1234", + "image_tag": "2.18.5", + "until": "2026-12-31", + } + ], + "r:s", + ) + + def test_an_entry_without_id_or_image_tag_is_rejected(self): + with self.assertRaisesRegex( + SuppressionError, "exactly one of id and image_tag" + ): + parse_entries([{"until": "2026-12-31"}], "r:s") + + def test_an_unquoted_numeric_image_tag_is_rejected(self): + with self.assertRaisesRegex(SuppressionError, "non-empty quoted string"): + parse_entries([{"image_tag": 1.1, "until": "2026-12-31"}], "r:s") + + def test_an_empty_image_tag_is_rejected(self): + with self.assertRaisesRegex(SuppressionError, "non-empty quoted string"): + parse_entries([{"image_tag": "", "until": "2026-12-31"}], "r:s") def test_a_quoted_until_is_parsed(self): parsed = parse_entries([{"id": "CVE-2026-1234", "until": "2026-12-31"}], "r:s") @@ -56,6 +93,92 @@ class TestParseEntries(TestCase): parse_entries({"id": "CVE-2026-1234"}, "r:s") +MIXED = """\ +app: + image: app + version: "1.2" + security: + suppressions: + # nocheck: cve the module is not built into the image + - id: CVE-2026-1234 + until: 2026-12-31 + + # nocheck: cve upstream ships no rebuild yet + - until: 2026-12-31 + image_tag: "1.2" + mem_limit: 1g +db: + image: postgres + version: "17" + security: + suppressions: + # nocheck: cve upstream ships no rebuild yet + - image_tag: "17" + until: 2026-12-31 +""" + + +def _drop(text, service): + return "".join(drop_image_tag_entries(text.splitlines(keepends=True), service)) + + +class TestDropImageTagEntries(TestCase): + def test_only_the_tag_entry_and_its_marker_leave(self): + self.assertEqual( + _drop(MIXED, "app"), + MIXED.replace( + "\n # nocheck: cve upstream ships no rebuild yet\n" + " - until: 2026-12-31\n" + ' image_tag: "1.2"\n', + "\n", + ), + ) + + def test_an_emptied_list_takes_suppressions_and_security_along(self): + self.assertEqual( + _drop(MIXED, "db"), + MIXED.replace( + ' version: "17"\n' + " security:\n" + " suppressions:\n" + " # nocheck: cve upstream ships no rebuild yet\n" + ' - image_tag: "17"\n' + " until: 2026-12-31\n", + ' version: "17"\n', + ), + ) + + def test_the_result_still_parses(self): + for service in ("app", "db"): + with self.subTest(service=service): + parsed = load_yaml_str(_drop(MIXED, service)) + self.assertEqual( + [ + entry.image_tag + for entries in service_suppressions(parsed, "r").values() + for entry in entries + ], + [None, "17"] if service == "app" else [None, "1.2"], + ) + + def test_a_sequence_at_the_key_indent_is_handled(self): + text = ( + "app:\n" + " security:\n" + " suppressions:\n" + " # nocheck: cve upstream ships no rebuild yet\n" + ' - image_tag: "1"\n' + " until: 2026-12-31\n" + " mem_limit: 1g\n" + ) + self.assertEqual(_drop(text, "app"), "app:\n mem_limit: 1g\n") + + def test_a_service_without_tag_entries_is_unchanged(self): + text = "app:\n image: app\n" + self.assertEqual(_drop(text, "app"), text) + self.assertEqual(_drop(text, "other"), text) + + class TestServiceSuppressions(TestCase): def test_services_without_security_are_left_out(self): services = { diff --git a/tests/unit/python/utils/update/test_docker.py b/tests/unit/python/utils/update/test_docker.py index b44f72ef2a..2bd497d720 100644 --- a/tests/unit/python/utils/update/test_docker.py +++ b/tests/unit/python/utils/update/test_docker.py @@ -77,6 +77,43 @@ nginx: self.assertIn("version: alpine", updated) self.assertNotIn('version: "4.5" # Keep comment', updated) + def test_a_bump_drops_the_image_tag_suppression_of_the_old_tag(self) -> None: + original = """penpot: + image: penpotapp/exporter + version: "2.18.5" + security: + suppressions: + # nocheck: cve upstream ships no rebuild yet + - image_tag: "2.18.5" + until: 2026-12-31 +# nocheck: shared +nginx: + image: nginx + version: "1.29" + security: + suppressions: + # nocheck: cve upstream ships no rebuild yet + - image_tag: "1.29" + until: 2026-12-31 +""" + expected = original.replace( + """ version: "2.18.5" + security: + suppressions: + # nocheck: cve upstream ships no rebuild yet + - image_tag: "2.18.5" + until: 2026-12-31 +""", + ' version: "2.18.6"\n', + ) + with tempfile.TemporaryDirectory() as tmpdir: + config_path = Path(tmpdir) / "main.yml" + config_path.write_text(original, encoding="utf-8") + + update_config_versions(config_path, {"penpot": "2.18.6"}) + + self.assertEqual(read_text(str(config_path)), expected) + if __name__ == "__main__": unittest.main() diff --git a/utils/security/suppressions.py b/utils/security/suppressions.py index e07344b382..7abe987a1b 100644 --- a/utils/security/suppressions.py +++ b/utils/security/suppressions.py @@ -8,6 +8,12 @@ Each service entry MAY carry:: # nocheck: cve - id: CVE-2026-1234 until: 2026-12-31 + # nocheck: cve + - image_tag: "2.18.5" + until: 2026-12-31 + +An ``id`` entry accepts one CVE, an ``image_tag`` entry every finding of the +service's image while it runs that tag. """ from __future__ import annotations @@ -26,7 +32,8 @@ if TYPE_CHECKING: RULE = "cve" CVE_PATTERN = re.compile(r"^CVE-\d{4}-\d{4,}$") -ENTRY_KEYS = frozenset({"id", "until"}) +ENTRY_KEYS = frozenset({"id", "image_tag", "until"}) +SUBJECT_KEYS = ("id", "image_tag") class SuppressionError(ValueError): @@ -35,18 +42,28 @@ class SuppressionError(ValueError): @dataclass(frozen=True) class Suppression: - """One accepted CVE of one service. + """One accepted CVE, or every finding of one image tag, of one service. Args: - id: the ``CVE-YYYY-NNNN`` id. + id: the ``CVE-YYYY-NNNN`` id, ``None`` for an image tag entry. + image_tag: the image tag, ``None`` for a CVE entry. until: the last day the suppression applies. """ - id: str + id: str | None + image_tag: str | None until: dt.date - def as_json(self) -> dict[str, str]: - return {"id": self.id, "until": self.until.isoformat()} + @property + def subject(self) -> str: + return self.id or f"image tag {self.image_tag}" + + def as_json(self) -> dict[str, str | None]: + return { + "id": self.id, + "image_tag": self.image_tag, + "until": self.until.isoformat(), + } def _until(value: Any, where: str) -> dt.date: @@ -83,14 +100,26 @@ def parse_entries(entries: Any, where: str) -> list[Suppression]: for index, entry in enumerate(entries): label = f"{where} suppression #{index}" if not isinstance(entry, Mapping): - raise SuppressionError(f"{label}: must be a mapping with id and until") + raise SuppressionError( + f"{label}: must be a mapping with id or image_tag and until" + ) unknown = sorted(set(entry) - ENTRY_KEYS) if unknown: raise SuppressionError(f"{label}: unknown key(s) {', '.join(unknown)}") + subjects = [key for key in SUBJECT_KEYS if key in entry] + if len(subjects) != 1: + raise SuppressionError(f"{label}: needs exactly one of id and image_tag") cve = entry.get("id") - if not isinstance(cve, str) or not CVE_PATTERN.match(cve): + tag = entry.get("image_tag") + if "id" in entry and (not isinstance(cve, str) or not CVE_PATTERN.match(cve)): raise SuppressionError(f"{label}: id {cve!r} is no CVE-YYYY-NNNN id") - parsed.append(Suppression(id=cve, until=_until(entry.get("until"), label))) + if "image_tag" in entry and (not isinstance(tag, str) or not tag): + raise SuppressionError( + f"{label}: image_tag {tag!r} must be a non-empty quoted string" + ) + parsed.append( + Suppression(id=cve, image_tag=tag, until=_until(entry.get("until"), label)) + ) return parsed @@ -136,3 +165,143 @@ def role_suppressions(roles_dir: Path, role: str) -> dict[str, list[Suppression] if not path.is_file(): return {} return service_suppressions(load_yaml_any(str(path)), role) + + +IMAGE_TAG_KEY = re.compile(r"^\s*(?:-\s+)?image_tag\s*:") + + +def _blank(line: str) -> bool: + return not line.strip() + + +def _indent(line: str) -> int: + return len(line) - len(line.lstrip(" ")) + + +def _item(line: str, indent: int) -> bool: + return _indent(line) == indent and line.lstrip().startswith("-") + + +def _span_end(lines: list[str], index: int) -> int: + """Return the index after the last line of the value under the key at *index*. + + A sequence written at the key's own indent belongs to the value too, with + the comments directly above its items. + """ + key = _indent(lines[index]) + end = index + 1 + cursor = index + 1 + while cursor < len(lines): + line = lines[cursor] + if _blank(line): + cursor += 1 + continue + if _indent(line) > key or _item(line, key): + cursor += 1 + end = cursor + continue + ahead = cursor + while ahead < len(lines) and ( + _blank(lines[ahead]) or lines[ahead].lstrip().startswith("#") + ): + ahead += 1 + if ahead < len(lines) and _item(lines[ahead], key): + cursor = ahead + continue + break + return end + + +def _kept_entries(region: list[str]) -> list[str]: + """Return the list *region* without its ``image_tag`` entries and their markers.""" + starts = [line for line in region if line.lstrip().startswith("-")] + if not starts: + return region + item_indent = min(_indent(line) for line in starts) + groups: list[list[str]] = [] + pending: list[str] = [] + for line in region: + if _item(line, item_indent): + groups.append([*pending, line]) + pending = [] + elif groups and not ( + line.lstrip().startswith("#") and _indent(line) <= item_indent + ): + groups[-1].append(line) + else: + pending.append(line) + kept = [ + line + for group in groups + if not any(IMAGE_TAG_KEY.match(line) for line in group) + for line in group + ] + return [*kept, *pending] + + +def _drop_in_body(body: list[str]) -> list[str]: + content = [line for line in body if not _blank(line)] + if not content: + return body + child = min(_indent(line) for line in content) + security = next( + ( + index + for index, line in enumerate(body) + if _indent(line) == child and re.match(r"^\s*security\s*:\s*$", line) + ), + None, + ) + if security is None: + return body + security_end = _span_end(body, security) + listing = next( + ( + index + for index in range(security + 1, security_end) + if re.match(r"^\s*suppressions\s*:\s*$", body[index]) + ), + None, + ) + if listing is None: + return body + listing_end = _span_end(body, listing) + kept = _kept_entries(body[listing + 1 : listing_end]) + if any(not _blank(line) and not line.lstrip().startswith("#") for line in kept): + return [*body[: listing + 1], *kept, *body[listing_end:]] + body = [*body[:listing], *body[listing_end:]] + security_end = _span_end(body, security) + if all(_blank(line) for line in body[security + 1 : security_end]): + body = [*body[:security], *body[security_end:]] + return body + + +def drop_image_tag_entries(lines: list[str], service: str) -> list[str]: + """Remove the ``image_tag`` suppressions of one top-level service. + + The image updater calls this when it moves the service to another + version, so a tag suppression never outlives its tag. Each entry leaves + with the marker comments above it; a list left empty takes its + ``suppressions:`` key along, and a ``security:`` key left empty its own. + + Args: + lines: the lines of a ``meta/services.yml``, line endings kept. + service: the top-level service key. + + Returns: + The lines without those entries; *lines* itself when there are none. + """ + header = re.compile(rf"^{re.escape(service)}\s*:") + start = next((i for i, line in enumerate(lines) if header.match(line)), None) + if start is None: + return lines + end = next( + ( + index + for index in range(start + 1, len(lines)) + if not _blank(lines[index]) and _indent(lines[index]) == 0 + ), + len(lines), + ) + body = _drop_in_body(lines[start + 1 : end]) + return [*lines[: start + 1], *body, *lines[end:]] diff --git a/utils/update/docker.py b/utils/update/docker.py index 7c44bed6bf..340f392d65 100644 --- a/utils/update/docker.py +++ b/utils/update/docker.py @@ -41,6 +41,7 @@ from utils.docker.image.ref import ( ) from utils.docker.registry import fetch_registry_tags from utils.roles.mapping import ROLE_FILE_META_SERVICES +from utils.security.suppressions import drop_image_tag_entries from utils.update.base import ( declares_source, is_maintained, @@ -421,12 +422,13 @@ def update_config_versions(config_path: Path, service_versions: dict[str, str]) The file root IS the services map (no ``services.`` wrapper), so the walker tracks one nesting level: top-level service keys and their - immediate ``version:`` field. + immediate ``version:`` field. A service that moves to another version + loses its ``image_tag`` CVE suppressions, which named the old tag. """ lines = config_path.read_text( # nocheck: cache-read — read-then-write of the same file; cached read would go stale encoding="utf-8" ).splitlines(keepends=True) - changed = False + moved: list[str] = [] services_indent: int = 0 current_service: str | None = None @@ -474,12 +476,14 @@ def update_config_versions(config_path: Path, service_versions: dict[str, str]) if line.endswith("\n"): new_line += "\n" lines[index] = new_line - changed = True + moved.append(current_service) - if changed: + for service in moved: + lines = drop_image_tag_entries(lines, service) + if moved: config_path.write_text("".join(lines), encoding="utf-8") - return changed + return bool(moved) def apply_updates(updates: list[DockerImageVersionUpdate]) -> list[Path]: