From 93a858fc36b4e69d87d8f0beb07895ab9a07f90b Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 12 Nov 2026 16:53:16 +0000 Subject: [PATCH 01/25] fix(security): re-own the vulnerability database without following symlinks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit hand_over runs as root after a refresh and gives the shared database directory back to its owner. The engine containers can write below that directory, so a symlink they plant must never lead the root run outside it. Listed paths that are symlinks are skipped; the walk uses os.fwalk with follow_symlinks=False and re-owns every entry relative to its open parent directory (dir_fd), so a directory swapped for a symlink mid-walk is skipped instead of followed. Tests: a planted symlink is re-owned itself, never its target; a listed symlink is skipped; a directory swapped for a symlink during the walk re-owns nothing outside the root. Negative control: the swap test fails on the old os.walk version. Residuals, tracked as cluster/security-db-writable-root-residuals: the lock lives inside the writable root, fetch_databases follows a symlinked root/, hardlinks. 🎯 Fix: 94 % 💥 Break: 2 % 💸 Cost: – ⏱️ Time: – 🛡️ Security: 100 % 🏆 Score: 92 🚦 Gate: ✅ 90/5, cost and time <= 100, security 100 % Co-Authored-By: Claude Opus 5.5 --- .../python/utils/security/test_database.py | 87 ++++++++++++++++--- utils/security/database.py | 21 +++-- 2 files changed, 87 insertions(+), 21 deletions(-) diff --git a/tests/unit/python/utils/security/test_database.py b/tests/unit/python/utils/security/test_database.py index ca38ff0b66..c404e6196c 100644 --- a/tests/unit/python/utils/security/test_database.py +++ b/tests/unit/python/utils/security/test_database.py @@ -154,31 +154,92 @@ class TestRefresh(_Root): class TestHandOver(_Root): - def _hand_over(self, euid): - _touch(self.root / "osv" / "osv-scalibr" / "Ubuntu" / "all.zip", 60) - owner = self.root.stat() + def _outside(self) -> Path: + other = tempfile.TemporaryDirectory() + self.addCleanup(other.cleanup) + return Path(other.name) + + def _owned(self, euid=0, swap_at=None, swap=None): + """Run hand_over with a recording chown and return what it re-owned. + + Args: + euid: the effective uid hand_over sees. + swap_at: the entry name whose re-owning triggers *swap*. + swap: called at *swap_at* to change the tree mid-walk. + + Returns: + ``(real path, (uid, gid))`` per call, every path component but the + last resolved. + """ + owned = [] + + def chown(name, uid, gid, *, dir_fd=None, follow_symlinks=True): + self.assertIs(follow_symlinks, False) + if dir_fd is None: + parent = Path(os.path.realpath(Path(name).parent)) + else: + parent = Path(f"/proc/self/fd/{dir_fd}").readlink() + owned.append((parent / Path(name).name, (uid, gid))) + if swap and Path(name).name == swap_at: + swap() + with ( mock.patch.object(database.os, "geteuid", return_value=euid), - mock.patch.object(database.os, "chown") as chown, + mock.patch.object(database.os, "chown", side_effect=chown), ): database.hand_over(self.root, [self.root / "osv"]) - return chown, (owner.st_uid, owner.st_gid) + return owned + + def _real(self, *parts: str) -> Path: + return Path(os.path.realpath(self.root)).joinpath(*parts) def test_a_root_refresh_gives_every_file_to_the_directory_owner(self): - chown, owner = self._hand_over(0) + _touch(self.root / "osv" / "osv-scalibr" / "Ubuntu" / "all.zip", 60) + owner = self.root.stat() + owner = (owner.st_uid, owner.st_gid) self.assertEqual( - {(Path(call.args[0]), call.args[1:]) for call in chown.call_args_list}, + set(self._owned()), { - (self.root / "osv", owner), - (self.root / "osv" / "osv-scalibr", owner), - (self.root / "osv" / "osv-scalibr" / "Ubuntu", owner), - (self.root / "osv" / "osv-scalibr" / "Ubuntu" / "all.zip", owner), + (self._real("osv"), owner), + (self._real("osv", "osv-scalibr"), owner), + (self._real("osv", "osv-scalibr", "Ubuntu"), owner), + (self._real("osv", "osv-scalibr", "Ubuntu", "all.zip"), owner), }, ) + def test_a_planted_symlink_is_changed_itself_never_its_target(self): + outside = self._outside() + (outside / "passwd").write_text("x", encoding="utf-8") + (self.root / "osv").mkdir(parents=True) + (self.root / "osv" / "link").symlink_to(outside / "passwd") + paths = [path for path, _owner in self._owned()] + self.assertIn(self._real("osv", "link"), paths) + self.assertNotIn(Path(os.path.realpath(outside)) / "passwd", paths) + + def test_a_listed_path_that_is_a_symlink_is_skipped(self): + outside = self._outside() + _touch(outside / "secret", 60) + (self.root / "osv").symlink_to(outside, target_is_directory=True) + self.assertEqual(self._owned(), []) + + def test_a_directory_swapped_for_a_symlink_mid_walk_is_not_followed(self): + outside = self._outside() + _touch(outside / "e" / "f", 60) + _touch(self.root / "osv" / "d" / "e" / "f", 60) + + def swap(): + (self.root / "osv" / "d").rename(self.root / "osv" / "d2") + (self.root / "osv" / "d").symlink_to(outside, target_is_directory=True) + + owned = self._owned(swap_at="e", swap=swap) + escaped = Path(os.path.realpath(outside)) + self.assertTrue(owned) + for path, _owner in owned: + self.assertFalse(path.is_relative_to(escaped), path) + def test_an_unprivileged_refresh_changes_no_owner(self): - chown, _owner = self._hand_over(1000) - chown.assert_not_called() + _touch(self.root / "osv" / "osv-scalibr" / "Ubuntu" / "all.zip", 60) + self.assertEqual(self._owned(euid=1000), []) def test_a_root_refresh_that_wrote_no_database_hands_over_the_lock(self): with ( diff --git a/utils/security/database.py b/utils/security/database.py index 56c0e5b7e0..a3c7e386a2 100644 --- a/utils/security/database.py +++ b/utils/security/database.py @@ -9,13 +9,13 @@ import shutil import time import urllib.parse import urllib.request -from pathlib import Path from typing import TYPE_CHECKING from utils.security.pipeline import engine_image, pipeline, role_services, user_runtime if TYPE_CHECKING: from collections.abc import Callable, Sequence + from pathlib import Path from types import ModuleType OSV_BUCKET = "https://osv-vulnerabilities.storage.googleapis.com" @@ -112,18 +112,23 @@ def hand_over(root: Path, paths: Sequence[Path]) -> None: Args: root: the shared database directory. - paths: what this process may have written below *root*; a path it - did not create is skipped. + paths: what this process may have written below *root*; a missing + path or a symlink is skipped. """ if os.geteuid() != 0: return owner = root.stat() - for path in (path for path in paths if path.exists()): - os.chown(path, owner.st_uid, owner.st_gid) - tree = os.walk(path) # nocheck: project-walk - not the repository - for directory, dirs, files in tree: + for path in (path for path in paths if path.exists() and not path.is_symlink()): + os.chown(path, owner.st_uid, owner.st_gid, follow_symlinks=False) + for _directory, dirs, files, parent in os.fwalk(path, follow_symlinks=False): for name in (*dirs, *files): - os.chown(Path(directory) / name, owner.st_uid, owner.st_gid) + os.chown( + name, + owner.st_uid, + owner.st_gid, + dir_fd=parent, + follow_symlinks=False, + ) def refresh( From 9a61a1b3c22d831060ab44a1bd43af9135a1107a Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 12 Nov 2026 16:56:23 +0000 Subject: [PATCH 02/25] fix(registry): accept only well-formed sha256 and sha512 digests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit platform_digest and manifest_digest passed the digest a registry returned straight to their callers, which name files and scratch directories after it. A digest such as ../../etc or one with a trailing newline therefore reached the filesystem (CodeQL path traversal). valid_digest now admits only sha256: or sha512: followed by lowercase hex of the matching length; platform_digest falls through to the next manifest entry on a malformed one, and manifest_digest reports it as indeterminate. Tests: TestValidDigest covers well-formed sha256 and sha512 and rejects traversal, uppercase, a trailing newline, md5, empty, None and 42; a malformed Docker-Content-Digest is indeterminate; a malformed platform entry falls through to a valid one. The fixtures now use well-formed digests. Negative control: the new tests fail on the old code. Security score 0 % comes from 13 MEDUSA findings on unchanged lines of the existing registry HTTP client (WEB-SSRF, MEDUSA-ACP-SCAN-028, B310); committed on the operator word, the findings get their own review task. 🎯 Fix: 92 % 💥 Break: 2 % 💸 Cost: – ⏱️ Time: – 🛡️ Security: 0 % 🏆 Score: 0 🚦 Gate: ⚠️ security 0 % < 100: ask the operator before the commit Co-Authored-By: Claude Opus 5.5 --- .../python/utils/docker/test_image_config.py | 9 +-- .../unit/python/utils/docker/test_registry.py | 74 +++++++++++++++---- utils/docker/registry.py | 22 +++++- 3 files changed, 81 insertions(+), 24 deletions(-) diff --git a/tests/unit/python/utils/docker/test_image_config.py b/tests/unit/python/utils/docker/test_image_config.py index 985b093dbf..708e00b003 100644 --- a/tests/unit/python/utils/docker/test_image_config.py +++ b/tests/unit/python/utils/docker/test_image_config.py @@ -16,11 +16,10 @@ from pathlib import Path from utils.docker import registry from utils.docker.image import config +AMD = "sha256:" + "b" * 64 MANIFEST = {"config": {"digest": "sha256:cfg"}, "layers": [{"size": 1}]} INDEX = { - "manifests": [ - {"platform": {"os": "linux", "architecture": "amd64"}, "digest": "sha256:amd"} - ] + "manifests": [{"platform": {"os": "linux", "architecture": "amd64"}, "digest": AMD}] } PROBE = {"Test": ["CMD-SHELL", "dig @127.0.0.1 || exit 1"]} VOLUMES = {"/opt/ejabberd": {}} @@ -73,12 +72,12 @@ class TestImageHealthcheck(_Isolated, unittest.TestCase): {}, json.dumps({"config": {"Healthcheck": PROBE}}).encode(), ) - body = MANIFEST if "sha256%3Aamd" in url else INDEX + body = MANIFEST if AMD.replace(":", "%3A") in url else INDEX return (200, {}, json.dumps(body).encode()) with mock.patch.object(registry, "_request", side_effect=_request): self.assertEqual(config.image_healthcheck("redis", "alpine"), PROBE) - self.assertTrue(any("sha256%3Aamd" in url for url in seen)) + self.assertTrue(any(AMD.replace(":", "%3A") in url for url in seen)) def test_an_index_without_the_platform_is_indeterminate(self) -> None: with ( diff --git a/tests/unit/python/utils/docker/test_registry.py b/tests/unit/python/utils/docker/test_registry.py index f5724fdd2a..c08b842f98 100644 --- a/tests/unit/python/utils/docker/test_registry.py +++ b/tests/unit/python/utils/docker/test_registry.py @@ -11,6 +11,12 @@ from pathlib import Path from utils.docker import registry +ARM = "sha256:" + "a" * 64 +AMD = "sha256:" + "b" * 64 +ATT = "sha256:" + "c" * 64 +HEAD = "sha256:" + "d" * 64 +SINGLE = "sha256:" + "e" * 64 + class _IsolatedProbeCache(unittest.TestCase): """Give each test its own probe cache and no mirror.""" @@ -94,17 +100,47 @@ class TestManifestExists(_IsolatedProbeCache): self.assertEqual(url, "https://quay.io/v2/keycloak/keycloak/manifests/26.6.3") +class TestValidDigest(unittest.TestCase): + def test_well_formed_sha256_and_sha512_pass(self) -> None: + sha512 = "sha512:" + "f" * 128 + self.assertEqual(registry.valid_digest(HEAD), HEAD) + self.assertEqual(registry.valid_digest(sha512), sha512) + + def test_anything_that_could_name_another_path_is_dropped(self) -> None: + for value in ( + "sha256:/../../etc", + "sha256:" + "d" * 63 + "/", + "sha256:" + "D" * 64, + "sha256:" + "d" * 64 + "\n", + "md5:" + "d" * 32, + "", + None, + 42, + ): + with self.subTest(value=value): + self.assertIsNone(registry.valid_digest(value)) + + class TestManifestDigest(unittest.TestCase): - def test_returns_the_content_digest_of_a_head_request(self) -> None: + def test_a_malformed_content_digest_is_indeterminate(self) -> None: with mock.patch.object( registry.urllib.request, "urlopen", return_value=_Resp( - status=200, headers={"Docker-Content-Digest": "sha256:abc"} + status=200, headers={"Docker-Content-Digest": "sha256:/../../x"} ), + ): + digest = registry.manifest_digest("roundcube/roundcubemail", "1.7.5-apache") + self.assertIsNone(digest) + + def test_returns_the_content_digest_of_a_head_request(self) -> None: + with mock.patch.object( + registry.urllib.request, + "urlopen", + return_value=_Resp(status=200, headers={"Docker-Content-Digest": HEAD}), ) as opened: digest = registry.manifest_digest("roundcube/roundcubemail", "1.7.5-apache") - self.assertEqual(digest, "sha256:abc") + self.assertEqual(digest, HEAD) request = opened.call_args.args[0] self.assertEqual(request.get_method(), "HEAD") self.assertIn( @@ -201,10 +237,10 @@ _SINGLE = { } _INDEX = { "manifests": [ - {"digest": "sha256:arm", "platform": {"os": "linux", "architecture": "arm64"}}, - {"digest": "sha256:amd", "platform": {"os": "linux", "architecture": "amd64"}}, + {"digest": ARM, "platform": {"os": "linux", "architecture": "arm64"}}, + {"digest": AMD, "platform": {"os": "linux", "architecture": "amd64"}}, { - "digest": "sha256:att", + "digest": ATT, "platform": {"os": "unknown", "architecture": "unknown"}, }, ] @@ -221,7 +257,7 @@ class TestManifestTransferSize(_IsolatedProbeCache): registry, "fetch_manifest", side_effect=[_INDEX, _SINGLE] ) as fetched: self.assertEqual(registry.manifest_transfer_size("img", "1"), 2_000) - self.assertEqual(fetched.call_args_list[1].args, ("img", "sha256:amd")) + self.assertEqual(fetched.call_args_list[1].args, ("img", AMD)) def test_index_without_the_platform_is_indeterminate(self) -> None: with mock.patch.object(registry, "fetch_manifest", return_value=_INDEX): @@ -319,8 +355,8 @@ class TestFetchManifest(unittest.TestCase): _PLATFORMS = ( - {"digest": "sha256:arm", "platform": {"os": "linux", "architecture": "arm64"}}, - {"digest": "sha256:amd", "platform": {"os": "linux", "architecture": "amd64"}}, + {"digest": ARM, "platform": {"os": "linux", "architecture": "arm64"}}, + {"digest": AMD, "platform": {"os": "linux", "architecture": "amd64"}}, ) @@ -334,17 +370,23 @@ class TestImagePlatformDigest(unittest.TestCase): "ghcr.io/o/r", "1", os_name="linux", architecture="amd64" ) + def test_a_malformed_platform_entry_falls_through_to_a_valid_one(self) -> None: + manifests = [ + { + "digest": "sha256:../x", + "platform": {"os": "linux", "architecture": "amd64"}, + }, + *_PLATFORMS, + ] + self.assertEqual(self._digest({"manifests": manifests}, None), AMD) + def test_an_index_resolves_to_the_platform_manifest(self) -> None: - self.assertEqual( - self._digest({"manifests": list(_PLATFORMS)}, None), "sha256:amd" - ) + self.assertEqual(self._digest({"manifests": list(_PLATFORMS)}, None), AMD) def test_a_single_manifest_answers_with_its_content_digest(self) -> None: headers = Message() - headers["Docker-Content-Digest"] = "sha256:single" - self.assertEqual( - self._digest({"layers": []}, (200, headers, None)), "sha256:single" - ) + headers["Docker-Content-Digest"] = SINGLE + self.assertEqual(self._digest({"layers": []}, (200, headers, None)), SINGLE) def test_an_unreachable_registry_is_indeterminate(self) -> None: self.assertIsNone(self._digest(None, None)) diff --git a/utils/docker/registry.py b/utils/docker/registry.py index 99a8e33a82..253241c983 100644 --- a/utils/docker/registry.py +++ b/utils/docker/registry.py @@ -34,6 +34,7 @@ _UNKNOWN_PLATFORM = "unknown" _CACHE_ROOT = Path(tempfile.gettempdir()) / "infinito-registry-probe" _LINK_NEXT_RE = re.compile(r'<([^>]+)>\s*;\s*rel="next"', re.IGNORECASE) _CHALLENGE_PARAM_RE = re.compile(r'(\w+)="([^"]*)"') +_DIGEST_RE = re.compile(r"sha256:[0-9a-f]{64}|sha512:[0-9a-f]{128}") _MANIFEST_ACCEPT = ( "application/vnd.oci.image.index.v1+json, " "application/vnd.oci.image.manifest.v1+json, " @@ -217,6 +218,21 @@ def probe_order(image: str) -> list[str]: return [mirrored, image] +def valid_digest(value: object) -> str | None: + """Return a registry-supplied digest only when it is well formed. + + Args: + value: a ``digest`` field or ``Docker-Content-Digest`` header. + + Returns: + ``value`` when it is ``sha256:`` or ``sha512:`` with lowercase hex of + the matching length, else ``None``. + """ + if isinstance(value, str) and _DIGEST_RE.fullmatch(value): + return value + return None + + def platform_digest(manifests: list, os_name: str, architecture: str) -> str | None: for entry in manifests: if not isinstance(entry, dict): @@ -226,8 +242,8 @@ def platform_digest(manifests: list, os_name: str, architecture: str) -> str | N platform.get("os") == os_name and platform.get("architecture") == architecture ): - digest = entry.get("digest") - if isinstance(digest, str) and digest: + digest = valid_digest(entry.get("digest")) + if digest: return digest return None @@ -464,7 +480,7 @@ def manifest_digest(image: str, reference: str) -> str | None: result = _request(url, repo, method="HEAD", accept=_MANIFEST_ACCEPT) if result is None or result[0] != 200: return None - return result[1].get("Docker-Content-Digest") or None + return valid_digest(result[1].get("Docker-Content-Digest")) def manifest_exists(image: str, reference: str) -> bool | None: From 03ac9ce02b613f2517704274657a05f604bd333a Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:41:05 +0000 Subject: [PATCH 03/25] update(repos): bump git refs to latest tags and commits (web-app-bridgy-fed) --- roles/web-app-bridgy-fed/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-bridgy-fed/meta/services.yml b/roles/web-app-bridgy-fed/meta/services.yml index f6648a6ee7..0b0a13f888 100644 --- a/roles/web-app-bridgy-fed/meta/services.yml +++ b/roles/web-app-bridgy-fed/meta/services.yml @@ -53,7 +53,7 @@ bridgy-fed: version: 3.14-slim name: web-app-bridgy-fed repository: https://github.com/snarfed/bridgy-fed.git - ref: 187d21635727ea92e5689b953d9054de12fc7602 + ref: d340cd2cba1ca089bf919dbfcca9644dc99e11be ports: local: http: 8053 From 925d805c0a2446e459b883aa746b1d5434ccd2d5 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:12:57 +0000 Subject: [PATCH 04/25] update(versions): update pins with a declared source (dsk-gnt-claude) --- roles/dsk-gnt-claude/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/dsk-gnt-claude/meta/services.yml b/roles/dsk-gnt-claude/meta/services.yml index 2bffddfe3e..9773dd0e17 100644 --- a/roles/dsk-gnt-claude/meta/services.yml +++ b/roles/dsk-gnt-claude/meta/services.yml @@ -9,7 +9,7 @@ claude: host: enabled: true lifecycle: alpha - npm_version: 2.1.322 + npm_version: 2.1.323 update: key: npm_version type: npm From 9d982a7fd1ca3bd65257ac2d3999bda059ae44ac Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 12 Nov 2026 21:54:20 +0000 Subject: [PATCH 05/25] fix(update): drop image_tag suppressions when a version source moves the tag MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The docker updater drops the image_tag CVE suppressions of every service it moves to another version. The version-sources updater did not, so each bump left suppressions that named the old tag, and TestCveSuppressions rejected the pull request: PR 1707 moved bigbluebutton from v3.0.39 to v4.0.2 and failed on 10 stale entries. apply_updates now drops them for every service whose version moved. The drop runs after every pin of the file moved, because the pins are addressed by their collected line and the drop removes lines. Replaying PR 1707's bumps on main's bigbluebutton file moves the same 11 pins and leaves no TestCveSuppressions problem. Accepted security finding (unchanged): B603 on utils/update/source.py, reviewed 2026-11-07. 🎯 Fix: 95 % 💥 Break: 2 % 💸 Cost: – ⏱️ Time: – 🛡️ Security: 100 % 🏆 Score: 93 🚦 Gate: ✅ 90/5, cost and time <= 100, security 100 % Co-Authored-By: Claude Opus 5.5 --- tests/unit/python/utils/update/test_source.py | 55 +++++++++++++++++++ utils/update/source.py | 11 ++++ 2 files changed, 66 insertions(+) diff --git a/tests/unit/python/utils/update/test_source.py b/tests/unit/python/utils/update/test_source.py index f5ba65c76a..e9bbeeadf6 100644 --- a/tests/unit/python/utils/update/test_source.py +++ b/tests/unit/python/utils/update/test_source.py @@ -110,6 +110,35 @@ bundle: pattern: 'part (v[0-9.]+-v[0-9.]+)' """ +SUPPRESSED = """\ +--- +first: + image: example/first + version: "v1.0.0" + update: + type: npm + package: first + security: + suppressions: + # nocheck: cve stale tag + - image_tag: "v1.0.0" + until: 2026-11-30 + # nocheck: cve accepted + - id: CVE-2026-1234 + until: 2026-11-30 +second: + image: example/second + version: "v2.0.0" + update: + type: npm + package: second + security: + suppressions: + # nocheck: cve stale tag + - image_tag: "v2.0.0" + until: 2026-11-30 +""" + def _repo(services: str = SERVICES) -> Path: tmp = Path(tempfile.mkdtemp()) @@ -198,6 +227,32 @@ class TestOutdated(unittest.TestCase): self.assertEqual(module.outdated([self._entry(root)], root), []) +class TestSuppressions(unittest.TestCase): + def test_a_moved_version_drops_its_image_tag_suppressions_and_every_pin_moves( + self, + ) -> None: + root = _repo(SUPPRESSED) + latest = {"first": "v1.1.0", "second": "v2.1.0"} + with ( + mock.patch.object(module, "manifest_exists", return_value=True), + mock.patch.object( + module, + "candidates", + side_effect=lambda entry, _: [latest[entry.entity]], + ), + ): + updates = module.outdated(module.collect_entries(root), root) + module.apply_updates(updates) + + config = root / "roles" / "web-app-example" / ROLE_FILE_META_SERVICES + written = config.read_text() # nocheck: cache-read just rewritten here + self.assertIn('version: "v1.1.0"', written) + self.assertIn('version: "v2.1.0"', written) + self.assertNotIn("image_tag", written) + self.assertIn("id: CVE-2026-1234", written) + self.assertEqual(written.count("security:"), 1) + + class TestTemplate(unittest.TestCase): def _outdated(self, services: str, upstream: str) -> list[str]: root = _repo(services) diff --git a/utils/update/source.py b/utils/update/source.py index c8eabb8949..409edc2c4f 100644 --- a/utils/update/source.py +++ b/utils/update/source.py @@ -42,6 +42,7 @@ from utils.cache.files import read_text from utils.cache.yaml import load_yaml from utils.docker.registry import manifest_exists from utils.roles.mapping import ROLE_FILE_META_SERVICES +from utils.security.suppressions import drop_image_tag_entries from utils.update import checksum from utils.update.addons import GITHUB_RELEASES_CATALOG, iter_addon_files from utils.update.base import ( @@ -475,6 +476,7 @@ def bump_archive(line: str, current: str, latest: str) -> str: def apply_updates(updates: Iterable[VersionSourceUpdate]) -> list[Path]: """Rewrite every pin to its newer version and return the changed files.""" changed: list[Path] = [] + moved: dict[Path, list[str]] = {} for update in updates: path = update.entry.config_path lines = path.read_text( # nocheck: cache-read read-modify-write: a cached read serves the pre-write content when two pins of one file are bumped in the same run @@ -496,4 +498,13 @@ def apply_updates(updates: Iterable[VersionSourceUpdate]) -> list[Path]: path.write_text("".join(lines), encoding="utf-8") if path not in changed: changed.append(path) + if not update.entry.addon and update.entry.key == DEFAULT_KEY: + moved.setdefault(path, []).append(update.entry.entity) + for path, services in moved.items(): + lines = path.read_text( # nocheck: cache-read read-modify-write of the file the loop above just rewrote + encoding="utf-8" + ).splitlines(keepends=True) + for service in services: + lines = drop_image_tag_entries(lines, service) + path.write_text("".join(lines), encoding="utf-8") return changed From a1b88db3f1a81576c69c4379025f1de23729166d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 02:14:16 +0000 Subject: [PATCH 06/25] build(deps): Bump odoo-addon-fs-attachment in /roles/web-app-odoo/files Bumps [odoo-addon-fs-attachment](https://github.com/OCA/storage) from 19.0.1.1.4 to 19.0.1.1.7. - [Commits](https://github.com/OCA/storage/commits) --- updated-dependencies: - dependency-name: odoo-addon-fs-attachment dependency-version: 19.0.1.1.7 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- roles/web-app-odoo/files/pip/requirements-no-deps.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-odoo/files/pip/requirements-no-deps.txt b/roles/web-app-odoo/files/pip/requirements-no-deps.txt index 81b3ccf645..6986342ca0 100644 --- a/roles/web-app-odoo/files/pip/requirements-no-deps.txt +++ b/roles/web-app-odoo/files/pip/requirements-no-deps.txt @@ -1,3 +1,3 @@ odoo-addon-fs_storage==19.0.1.1.3.5 -odoo-addon-fs_attachment==19.0.1.1.4 +odoo-addon-fs_attachment==19.0.1.1.7 odoo-addon-fs_attachment_s3==19.0.1.2.1.4 From c1e017e8e647d60c0b54ceec30a324084e9aefa4 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 02:21:01 +0000 Subject: [PATCH 07/25] build(deps): Bump odoo-addon-fs-attachment Bumps [odoo-addon-fs-attachment](https://github.com/OCA/storage) from 19.0.1.1.4 to 19.0.1.1.7. - [Commits](https://github.com/OCA/storage/commits) --- updated-dependencies: - dependency-name: odoo-addon-fs-attachment dependency-version: 19.0.1.1.7 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- roles/web-app-odoo/files/pip/requirements-no-deps.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-odoo/files/pip/requirements-no-deps.txt b/roles/web-app-odoo/files/pip/requirements-no-deps.txt index 81b3ccf645..6986342ca0 100644 --- a/roles/web-app-odoo/files/pip/requirements-no-deps.txt +++ b/roles/web-app-odoo/files/pip/requirements-no-deps.txt @@ -1,3 +1,3 @@ odoo-addon-fs_storage==19.0.1.1.3.5 -odoo-addon-fs_attachment==19.0.1.1.4 +odoo-addon-fs_attachment==19.0.1.1.7 odoo-addon-fs_attachment_s3==19.0.1.2.1.4 From 4dcf43a5631c68b1615d834ebf16c59a17c31afd Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 06:53:06 +0000 Subject: [PATCH 08/25] update(versions): update pins with a declared source (dsk-gnt-codex) --- roles/dsk-gnt-codex/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/dsk-gnt-codex/meta/services.yml b/roles/dsk-gnt-codex/meta/services.yml index 068ed00b7a..ea3cb1e14f 100644 --- a/roles/dsk-gnt-codex/meta/services.yml +++ b/roles/dsk-gnt-codex/meta/services.yml @@ -9,7 +9,7 @@ codex: host: enabled: true lifecycle: alpha - npm_version: 0.167.2 + npm_version: 0.168.0 update: key: npm_version type: npm From 543abdbde24896e05f2b914655b992ef8525e282 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Fri, 13 Nov 2026 09:17:52 +0000 Subject: [PATCH 09/25] fix(web-app-jenkins): pin the Mattermost plugin to the last Java 21 release MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit mattermost 3.2.0 is built for Java 25, while the controller image runs Java 21, so Jenkins refuses the plugin and the partner Mattermost spec fails (main run 43288523728 Jenkins#1 and Mattermost#1, PR 1708 Jenkins#1). Pin 3.1.3 and add a test that renders the plugin list and rejects any plugin release newer than the controller's Java. Hosts already deployed keep 3.2.0 in jenkins_home until plugins/mattermost.jpi* is removed there. 🎯 Fix: 92 % 💥 Break: 3 % 💸 Cost: 100 % ⏱️ Time: 100 % 🛡️ Security: 100 % 🏆 Score: 89 🚦 Gate: ✅ 90/5, cost and time <= 100, security 100 % Co-Authored-By: Claude Opus 5.5 --- .../meta/addons/mattermost.yml | 3 +- .../templates/test_plugins_java_runtime.py | 68 +++++++++++++++++++ 2 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 tests/unit/python/roles/web-app-jenkins/templates/test_plugins_java_runtime.py diff --git a/roles/web-app-jenkins/meta/addons/mattermost.yml b/roles/web-app-jenkins/meta/addons/mattermost.yml index 9f8bec1d6b..688064ce32 100644 --- a/roles/web-app-jenkins/meta/addons/mattermost.yml +++ b/roles/web-app-jenkins/meta/addons/mattermost.yml @@ -3,7 +3,8 @@ enabled: "{{ lookup('config', 'web-app-jenkins', 'services.mattermost.enabled') required: true mechanism: plugin source: upstream -version: "latest" +# nocheck: unwatched-version Reason: mattermost 3.2.0 and later ship Java 25 bytecode, so on the Java 21 runtime of the jenkins/jenkins LTS image their descriptors fail with UnsupportedClassVersionError and the plugin's global section vanishes; move the pin only together with a Java 25 controller image +version: "3.1.3" bridges: - mattermost config: diff --git a/tests/unit/python/roles/web-app-jenkins/templates/test_plugins_java_runtime.py b/tests/unit/python/roles/web-app-jenkins/templates/test_plugins_java_runtime.py new file mode 100644 index 0000000000..266b99adca --- /dev/null +++ b/tests/unit/python/roles/web-app-jenkins/templates/test_plugins_java_runtime.py @@ -0,0 +1,68 @@ +from __future__ import annotations + +import re +import unittest + +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape + +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_DIR_META_ADDONS, ROLE_FILE_META_SERVICES +from utils.update.base import is_semver, version_key + +from . import PROJECT_ROOT + +ROLE = PROJECT_ROOT / "roles" / "web-app-jenkins" +PLUGINS = "roles/web-app-jenkins/templates/plugins.txt.j2" +IMAGE_DEFAULT_JAVA = 21 +JAVA_FLOORS = {"mattermost": ("3.2.0", 25)} + + +def controller_java() -> int: + services = load_yaml_any(str(ROLE / ROLE_FILE_META_SERVICES)) + match = re.search(r"-jdk(\d+)", str(services["jenkins"]["version"])) + return int(match.group(1)) if match else IMAGE_DEFAULT_JAVA + + +def rendered_plugins() -> dict[str, str]: + addons = [ + {"key": path.stem, "value": load_yaml_any(str(path))} + for path in sorted((ROLE / ROLE_DIR_META_ADDONS).glob("*.yml")) + ] + env = Environment( + loader=FileSystemLoader(str(PROJECT_ROOT)), + undefined=StrictUndefined, + autoescape=select_autoescape(), + ) + text = env.get_template(PLUGINS).render(JENKINS_PLUGIN_ADDONS=addons) + return dict(line.split(":", 1) for line in text.splitlines() if line.strip()) + + +def java_violations(plugins: dict[str, str], java: int) -> list[str]: + found: list[str] = [] + for plugin, (floor, required) in JAVA_FLOORS.items(): + if plugin not in plugins or java >= required: + continue + version = plugins[plugin] + if not is_semver(version) or version_key(version) >= version_key(floor): + found.append( + f"{plugin}:{version} resolves to a release built for Java " + f"{required} (from {floor} on), the controller runs Java {java}" + ) + return found + + +class TestPluginsRunOnControllerJava(unittest.TestCase): + def test_rendered_plugin_list_fits_the_controller_java(self) -> None: + self.assertEqual(java_violations(rendered_plugins(), controller_java()), []) + + def test_a_moving_or_newer_release_is_refused_on_an_older_java(self) -> None: + for version in ("latest", "3.2.0"): + with self.subTest(version=version): + self.assertTrue(java_violations({"mattermost": version}, 21)) + + def test_a_controller_on_the_required_java_takes_the_newer_release(self) -> None: + self.assertEqual(java_violations({"mattermost": "3.2.0"}, 25), []) + + +if __name__ == "__main__": + unittest.main() From 7ebe3639f902f41d6fd039c913df7eb476c13c9a Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Fri, 13 Nov 2026 09:18:12 +0000 Subject: [PATCH 10/25] fix(web-app-nextcloud): render the Redis memcache in both modes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit nextcloud-taskprocessing and the cron container get no env_file, so they kept the pass-1 Redis block of memcache.config.php with the retired password and failed after the rotation (main run 43288523728 Nextcloud#12, Nextcloud#9, OpenProject#3). Render the Redis settings unconditionally and test the rendered config for both modes. 🎯 Fix: 92 % 💥 Break: 3 % 💸 Cost: 100 % ⏱️ Time: 100 % 🛡️ Security: 100 % 🏆 Score: 89 🚦 Gate: ✅ 90/5, cost and time <= 100, security 100 % Co-Authored-By: Claude Opus 5.5 --- .../templates/config/memcache.config.php.j2 | 6 -- .../web-app-nextcloud/test_memcache_config.py | 93 +++++++++++++++++++ 2 files changed, 93 insertions(+), 6 deletions(-) create mode 100644 tests/unit/python/roles/web-app-nextcloud/test_memcache_config.py diff --git a/roles/web-app-nextcloud/templates/config/memcache.config.php.j2 b/roles/web-app-nextcloud/templates/config/memcache.config.php.j2 index 2e81c4695b..aa2cb7b1f6 100644 --- a/roles/web-app-nextcloud/templates/config/memcache.config.php.j2 +++ b/roles/web-app-nextcloud/templates/config/memcache.config.php.j2 @@ -1,9 +1,4 @@ '\\OC\\Memcache\\APCu', -]; -{% else %} {% set _redis_user = lookup('engine', 'redis', application_id, 'username') %} {% set _redis_password = lookup('engine', 'redis', application_id, 'password') %} return [ @@ -21,4 +16,3 @@ return [ {% endif %} ], ]; -{% endif %} diff --git a/tests/unit/python/roles/web-app-nextcloud/test_memcache_config.py b/tests/unit/python/roles/web-app-nextcloud/test_memcache_config.py new file mode 100644 index 0000000000..2ef9683d21 --- /dev/null +++ b/tests/unit/python/roles/web-app-nextcloud/test_memcache_config.py @@ -0,0 +1,93 @@ +from __future__ import annotations + +import unittest + +from jinja2 import ChainableUndefined, Environment, select_autoescape + +from plugins.lookup.container_volumes import container_volumes +from utils.cache.files import PROJECT_ROOT, read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_VARS_MAIN + +ROLE = "roles/web-app-nextcloud" +APPLICATION_ID = "web-app-nextcloud" +SERVICES = load_yaml_any(str(PROJECT_ROOT / ROLE / ROLE_FILE_META_SERVICES)) +VARS = load_yaml_any(str(PROJECT_ROOT / ROLE / ROLE_FILE_VARS_MAIN)) +MEMCACHE_TEMPLATE = read_text( + str(PROJECT_ROOT / ROLE / "templates" / "config" / "memcache.config.php.j2") +) +LOADER_TARGET = "/var/www/infinito/" +REDIS = { + "host": "redis", + "port": 6379, + "username": "default", + "password": "current-secret", +} + + +def _render_memcache(compose_mode: bool, redis: dict) -> str: + env = Environment( + undefined=ChainableUndefined, + autoescape=select_autoescape(default_for_string=False), + ) + env.globals["lookup"] = lambda name, engine, app, key: redis[key] + return env.from_string(MEMCACHE_TEMPLATE).render( + IS_COMPOSE_MODE=compose_mode, + IS_SWARM_MODE=not compose_mode, + application_id=APPLICATION_ID, + ) + + +def _render_jinja(expression: str) -> str: + env = Environment( + undefined=ChainableUndefined, + autoescape=select_autoescape(default_for_string=False), + ) + env.globals["lookup"] = lambda name, *args, **kwargs: f"<{name} {args!r}>" + env.filters["path_join"] = lambda parts: "/".join(str(part) for part in parts) + return env.from_string(expression).render() + + +def _mounts(service: str) -> str: + return container_volumes( + {APPLICATION_ID: {"services": SERVICES}}, + APPLICATION_ID, + service, + render_jinja=_render_jinja, + ) + + +class TestMemcacheConfig(unittest.TestCase): + def test_compose_mode_renders_the_current_redis_connection(self): + rendered = _render_memcache(True, REDIS) + self.assertIn(r"'memcache.distributed' => '\\OC\\Memcache\\Redis'", rendered) + self.assertIn(r"'memcache.locking' => '\\OC\\Memcache\\Redis'", rendered) + self.assertIn("'host' => 'redis'", rendered) + self.assertIn("'user' => 'default'", rendered) + self.assertIn("'password' => 'current-secret'", rendered) + + def test_both_modes_render_the_same_config(self): + self.assertEqual(_render_memcache(True, REDIS), _render_memcache(False, REDIS)) + + def test_a_redis_without_auth_renders_no_credentials(self): + rendered = _render_memcache(True, {**REDIS, "username": "", "password": ""}) + self.assertIn("'host' => 'redis'", rendered) + self.assertNotIn("'user'", rendered) + self.assertNotIn("'password'", rendered) + + def test_password_quotes_and_backslashes_stay_inside_the_php_string(self): + rendered = _render_memcache(True, {**REDIS, "password": "a'b\\c"}) + self.assertIn("'password' => 'a\\'b\\\\c'", rendered) + + def test_every_php_service_mounts_the_loader_that_carries_the_connection(self): + for service in ( + "nextcloud", + VARS["NEXTCLOUD_CRON_SERVICE"], + VARS["NEXTCLOUD_TASKPROCESSING_SERVICE"], + ): + with self.subTest(service=service): + self.assertIn(LOADER_TARGET, _mounts(service)) + + +if __name__ == "__main__": + unittest.main() From 08264657c0f62522782d48368bbd861aed3ad6a8 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Fri, 13 Nov 2026 09:18:39 +0000 Subject: [PATCH 11/25] fix(sys-ctl-hlth-runtime): run socket-mounting scanners under runc MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit svc-virt-kata makes runsc the default runtime on nodes without kata, and gVisor refuses the bind-mounted docker.sock, so syft exits 1 on every container target and the hlth-runtime unit fails the swarm deploy (main run 43288523728 Moodle#1, WordPress#3; PR 1719 Matrix#1). Pass --runtime runc to the scanner runs that mount the socket, and test the argv for both socket and socket-free runs. Accepted MEDUSA findings (reviewed false positives, pre-existing on main): MEDUSA-INF-SCAN-2056, -2447 and -2744 on script.py lines 1537 and 1785, the rmtree cleanups of the root-only 0700 scan cache. 🎯 Fix: 90 % 💥 Break: 3 % 💸 Cost: 100 % ⏱️ Time: 100 % 🛡️ Security: 100 % 🏆 Score: 87 🚦 Gate: ✅ 90/5, cost and time <= 100, security 100 % Co-Authored-By: Claude Opus 5.5 --- roles/sys-ctl-hlth-runtime/README.md | 1 + .../files/python/script.py | 11 ++- .../sys-ctl-hlth-runtime/files/test_script.py | 77 +++++++++++++++++++ 3 files changed, 86 insertions(+), 3 deletions(-) diff --git a/roles/sys-ctl-hlth-runtime/README.md b/roles/sys-ctl-hlth-runtime/README.md index c4c9fa73c6..8b0fd93533 100644 --- a/roles/sys-ctl-hlth-runtime/README.md +++ b/roles/sys-ctl-hlth-runtime/README.md @@ -28,6 +28,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. +- **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. - **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. - **Threshold:** `severity` maps each reported severity to `fail` or `warn`, `{CRITICAL: fail, HIGH: warn}` by default and in production. The development inventory that `INFINITO_INVENTORY_VARS_FILE` names maps `CRITICAL` to `warn`, so a CI or development deploy reports a CRITICAL finding as a `⚠️` line and a `warn` record without failing, and the daily mirror scan tracks it as a `vulnerability` issue. A severity the mapping does not name is not reported, and `fixed_only` limits the report to findings with a fixed version. The list form of `severity` is rejected. diff --git a/roles/sys-ctl-hlth-runtime/files/python/script.py b/roles/sys-ctl-hlth-runtime/files/python/script.py index 582bab3251..f824cbd626 100755 --- a/roles/sys-ctl-hlth-runtime/files/python/script.py +++ b/roles/sys-ctl-hlth-runtime/files/python/script.py @@ -62,6 +62,7 @@ WORK = "/work" SBOM = "/sbom" CACHE = "/cache" DOCKER_SOCKET = "/var/run/docker.sock" +SOCKET_RUNTIME = "runc" JOB_TIMEOUT_SECONDS = 4 * 3600 EXPORT_SLOTS = 1 RUN_PREFIX = "run-" @@ -1220,20 +1221,24 @@ def run_argv( image: the engine image. args: the engine's arguments. target: the target, which picks the host or Docker socket mount; - ``None`` for a run that reads neither. + ``None`` for a run that reads neither. A run with the Docker + socket runs on :data:`SOCKET_RUNTIME`, every other run on the + daemon's default runtime. extra_env: environment on top of the engine's own. scratch: :attr:`Step.scratch` of the run, its ``TMPDIR`` under :data:`WORK`. """ + options = ["--rm"] mounts = ["-v", f"{layout.sbom}:{SBOM}", "-v", f"{layout.work}:{WORK}"] if engine in SCANNERS: mounts += ["-v", f"{layout.databases / engine}:{CACHE}"] if target is not None and target.kind == "host": mounts += ["-v", f"/:{HOST_ROOT}:ro"] if target is not None and target.kind == "container": + options += ["--runtime", SOCKET_RUNTIME] mounts += ["-v", f"{DOCKER_SOCKET}:{DOCKER_SOCKET}:ro"] environment = {"TMPDIR": f"{WORK}/{scratch}", **ENGINE_ENV[engine], **extra_env} - return (*layout.runtime, "--rm", *mounts, *_env(environment), image, *args) + return (*layout.runtime, *options, *mounts, *_env(environment), image, *args) def scratch_of(engine: str, subject: str) -> str: @@ -1385,7 +1390,7 @@ def grype_step(layout: Layout, image: str, target: Target, config: ScanConfig) - "grype", image, args, - target=target, + target=None if config.reads_sbom("grype") else target, extra_env={"GRYPE_DB_AUTO_UPDATE": "false"}, scratch=scratch, ), 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 56051338f7..c1fadcf170 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 @@ -1403,6 +1403,73 @@ class TestScratch(TestCase): self.assertTrue(keep.is_file()) +class SandboxNodeEngines(FakeEngines): + SOCKET = f"{SCRIPT.DOCKER_SOCKET}:{SCRIPT.DOCKER_SOCKET}:ro" + + def __call__(self, argv): + argv = list(argv) + runtime = argv[argv.index("--runtime") + 1] if "--runtime" in argv else "runsc" + if ( + argv[:2] == ["container", "run"] + and self.SOCKET in argv + and runtime != "runc" + ): + with self.lock: + self.calls.append(argv) + return SimpleNamespace(returncode=1, stdout="", stderr="") + return super().__call__(argv) + + +class TestSandboxNode(TestCase): + def _check(self, containers): + runner = SandboxNodeEngines(None, {}) + real_scan = SCRIPT.scan + + def scan(targets, config, images, layout, engines): + engines.layout = layout + return real_scan(targets, config, images, layout, engines) + + with tempfile.TemporaryDirectory() as tmp: + cache = Path(tmp) / "cache" + with ( + mock.patch.object( + SCRIPT, "docker_root", return_value="/var/lib/docker" + ), + mock.patch.object(SCRIPT, "scan", side_effect=scan), + mock.patch.object(SCRIPT, "pause"), + ): + _targets, _judged, errors = SCRIPT.vulnerability_check( + containers, + _config(), + {engine: f"{engine}:1" for engine in SCRIPT.ENGINES}, + _suppressions(), + cache, + cache / "db", + [], + runner, + SCRIPT.Run("id", dt.datetime.now(tz=dt.UTC), "node", "test"), + ) + return runner, errors + + def test_container_scans_pass_where_the_daemon_defaults_to_the_sandbox(self): + runner, errors = self._check([_container("a", image="sha256:a")]) + self.assertEqual(errors, []) + self.assertTrue(any(SandboxNodeEngines.SOCKET in call for call in runner.calls)) + + def test_only_runs_with_the_docker_socket_leave_the_sandbox(self): + runner, _errors = self._check([_container("a", image="sha256:a")]) + runs = [call for call in runner.calls if call[:2] == ["container", "run"]] + socket = [call for call in runs if SandboxNodeEngines.SOCKET in call] + others = [call for call in runs if SandboxNodeEngines.SOCKET not in call] + self.assertTrue(socket) + self.assertTrue(any("/:/host:ro" in call for call in others)) + for call in socket: + self.assertIn("--runtime", call) + self.assertEqual(call[call.index("--runtime") + 1], "runc") + for call in others: + self.assertNotIn("--runtime", call) + + class TestCommands(TestCase): def setUp(self): self.layout = SCRIPT.Layout( @@ -1514,6 +1581,16 @@ class TestCommands(TestCase): step = SCRIPT.grype_step(self.layout, "grype:1", self.container, _config()) self.assertIn("sbom:/sbom/abc.syft.json", step.argv) + def test_grype_reading_the_sbom_gets_neither_the_socket_nor_the_host(self): + for target in (self.container, self.host): + with self.subTest(kind=target.kind): + step = SCRIPT.grype_step(self.layout, "grype:1", target, _config()) + self.assertNotIn( + "/var/run/docker.sock:/var/run/docker.sock:ro", step.argv + ) + self.assertNotIn("/:/host:ro", step.argv) + self.assertNotIn("--runtime", step.argv) + def test_grype_reads_the_image_without_syft(self): step = SCRIPT.grype_step( self.layout, From 1d91fb2ed8f8b4105c045c12c4659d4b63414f88 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Fri, 13 Nov 2026 09:19:00 +0000 Subject: [PATCH 12/25] fix(web-app-penpot): follow the ?screen= routing of Penpot 2.19 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Penpot 2.19 (penpot#10700) routes with a ?screen= query instead of #/ hash routes, and a first OIDC sign-in lands on auth-register-validate. The Playwright helpers, both specs, the design suite and design.js only knew #/ routes, so every login check timed out (main run 43288523728 Penpot#0). Read the screen from the query, answer the first sign-in form, keep the #/auth/ fallback in design.js, and add node tests for the helpers, the design URLs and design.js. The form labels, flags and route names were checked against the upstream 2.19.1 source; the first sign-in form itself has not run in CI yet. 🎯 Fix: 90 % 💥 Break: 4 % 💸 Cost: 100 % ⏱️ Time: 100 % 🛡️ Security: 100 % 🏆 Score: 86 🚦 Gate: ✅ 90/5, cost and time <= 100, security 100 % Co-Authored-By: Claude Opus 5.5 --- .../files/playwright/_shared.js | 36 +++- .../files/playwright/playwright.spec.js | 4 +- .../files/playwright/test-design.js | 100 +++++------ .../files/playwright/test-seaweedfs.js | 4 +- roles/web-app-penpot/templates/design.js | 2 +- .../templates/playwright.env.j2 | 2 +- .../files/playwright/_shared.test.js | 155 ++++++++++++++++++ .../files/playwright/test-design.test.js | 39 +++++ .../web-app-penpot/templates/design.test.js | 61 +++++++ 9 files changed, 342 insertions(+), 61 deletions(-) create mode 100644 tests/unit/javascript/roles/web-app-penpot/files/playwright/_shared.test.js create mode 100644 tests/unit/javascript/roles/web-app-penpot/files/playwright/test-design.test.js create mode 100644 tests/unit/javascript/roles/web-app-penpot/templates/design.test.js diff --git a/roles/web-app-penpot/files/playwright/_shared.js b/roles/web-app-penpot/files/playwright/_shared.js index deaef6c22a..50d60483de 100644 --- a/roles/web-app-penpot/files/playwright/_shared.js +++ b/roles/web-app-penpot/files/playwright/_shared.js @@ -83,21 +83,41 @@ const env = { biberEmail: decodeDotenvQuotedValue(process.env.BIBER_EMAIL), }; -const loginRoute = (base) => `${base.replace(/\/$/, "")}/#/auth/login`; +const screenRoute = (base, screen) => `${base.replace(/\/$/, "")}/?screen=${screen}`; +const loginRoute = (base) => screenRoute(base, "auth-login"); +const screenOf = (url) => new URL(url).searchParams.get("screen") || ""; async function assertAuthenticated(page) { await expect - .poll(() => page.url(), { timeout: resolveTimeout(60_000), message: "expected to leave the login route after sign-in" }) - .not.toContain("/auth/login"); - await expect - .poll(() => page.url(), { timeout: resolveTimeout(60_000), message: "expected the SPA to reach a #/ route after sign-in" }) - .toContain("#/"); + .poll(() => screenOf(page.url()), { timeout: resolveTimeout(60_000), message: "expected the SPA to reach a dashboard screen after sign-in" }) + .toMatch(/^dashboard-/); await expect( page.locator("[data-testid='dashboard-sidebar']"), "Expected the Penpot dashboard shell, not a gateway error page", ).toBeVisible({ timeout: resolveTimeout(60_000) }); } +/** + * Args: + * page: Playwright page that has just come back from the Keycloak login form. + * fullname: name entered when Penpot's first sign-in form arrives without one. + */ +async function confirmFirstOidcSignIn(page, fullname) { + await expect + .poll(() => screenOf(page.url()), { + timeout: resolveTimeout(60_000), + message: "expected Penpot to answer the OIDC callback with the dashboard or its first sign-in form", + }) + .toMatch(/^(dashboard-|auth-register-validate$)/); + if (screenOf(page.url()) !== "auth-register-validate") return; + const nameField = page.getByLabel(/full ?name/i); + await expect(nameField, "Expected the first sign-in form to ask for the full name").toBeVisible({ timeout: resolveTimeout(30_000) }); + if (!(await nameField.inputValue())) await nameField.fill(fullname); + const createAccount = page.getByRole("button", { name: /^create an account$/i }); + await expect(createAccount, "Expected the first sign-in form to enable its submit button").toBeEnabled({ timeout: resolveTimeout(30_000) }); + await createAccount.click({ timeout: resolveTimeout(30_000) }); +} + // In-app OIDC (flavor: oidc): the login page renders an "OpenID" provider entry // (clickable text, not a role=button) that redirects to Keycloak. async function penpotOidcLogin(page, username, password) { @@ -110,6 +130,7 @@ async function penpotOidcLogin(page, username, password) { .poll(() => page.url(), { timeout: resolveTimeout(60_000), message: `expected redirect to ${expectedAuth}` }) .toContain(expectedAuth); await performKeycloakLoginForm(page, username, password); + await confirmFirstOidcSignIn(page, username); await assertAuthenticated(page); } @@ -132,7 +153,7 @@ async function penpotLdapLogin(page, email, password) { // two-step form: email/password, then full name). SMTP-off deployments activate // the profile immediately (no verification), landing on the dashboard. async function penpotRegister(page, fullname, email, password) { - await gotoOnion(page, `${env.baseUrl.replace(/\/$/, "")}/#/auth/register`); + await gotoOnion(page, screenRoute(env.baseUrl, "auth-register")); const emailField = page.getByLabel(/work email|^email$/i).first(); const passwordField = page.getByLabel(/^password$/i).first(); await expect(emailField, "Expected the Penpot register form").toBeVisible({ timeout: resolveTimeout(60_000) }); @@ -183,6 +204,7 @@ module.exports = { runGuestFlow, env, loginRoute, + screenOf, penpotOidcLogin, penpotLdapLogin, penpotNativeLogin, diff --git a/roles/web-app-penpot/files/playwright/playwright.spec.js b/roles/web-app-penpot/files/playwright/playwright.spec.js index 9bdadb1724..50ae94b48d 100644 --- a/roles/web-app-penpot/files/playwright/playwright.spec.js +++ b/roles/web-app-penpot/files/playwright/playwright.spec.js @@ -63,8 +63,8 @@ test("asset: administrator uploads an image asset into a design file", async ({ const newFile = page.getByText(/\+\s*New File/i).first(); await expect(newFile, "Expected a create-file control in Drafts").toBeVisible({ timeout: resolveTimeout(60_000) }); await newFile.click({ timeout: resolveTimeout(30_000) }); - await expect.poll(() => page.url(), { timeout: resolveTimeout(90_000), message: "expected to enter the Penpot workspace editor" }) - .toContain("/workspace"); + await expect.poll(() => shared.screenOf(page.url()), { timeout: resolveTimeout(90_000), message: "expected to enter the Penpot workspace editor" }) + .toBe("workspace"); const validPng = shared.validImagePng(); const fileInput = page.locator("#image-upload"); diff --git a/roles/web-app-penpot/files/playwright/test-design.js b/roles/web-app-penpot/files/playwright/test-design.js index 3ce02e79dd..0bac747c2a 100644 --- a/roles/web-app-penpot/files/playwright/test-design.js +++ b/roles/web-app-penpot/files/playwright/test-design.js @@ -85,21 +85,25 @@ async function rpc(page, method, params) { ); } +/** + * Args: + * base: Penpot base URL without a trailing slash. + * name: marker that makes the document URL unique, so two views of the same screen each load a document of their own. + * screen: Penpot screen as its route id, optionally followed by "?" and that screen's query parameters, e.g. "dashboard-recent?team-id=…"; empty for the app root. + * + * Returns: + * The query-routed URL Penpot 2.19 resolves that screen from. + */ +function screenUrl(base, name, screen) { + const [id, params] = screen.split("?"); + const query = [id && `screen=${id}`, params, `design-view=${name}`].filter(Boolean); + return `${base}/?${query.join("&")}`; +} + exports.register = function (shared) { const { test, expect, skipUnlessServiceEnabled, isServiceEnabled, env } = shared; const base = env.baseUrl.replace(/\/$/, ""); - - /** - * Args: - * name: marker that makes the document URL unique. Every Penpot route is a hash route, so without it two routes share one document and a navigation between them requests none. - * route: hash route of the app, starting with a slash. - * - * Returns: - * The URL of that route. - */ - function url(name, route) { - return `${base}/?design-view=${name}#${route}`; - } + const url = (name, screen) => screenUrl(base, name, screen); async function animationsSettled(page) { await expect @@ -167,7 +171,7 @@ exports.register = function (shared) { async function signIn(page) { if (session) { await page.context().addCookies(session); - await gotoOnion(page, url("session", "/")); + await gotoOnion(page, url("session", "")); } else if (isServiceEnabled("sso")) { await shared.penpotOidcLogin(page, env.adminUsername, env.adminPassword); } else if (isServiceEnabled("ldap")) { @@ -247,10 +251,10 @@ exports.register = function (shared) { function visitorViews() { return [ - { name: "sign-in", url: url("sign-in", "/auth/login"), prepare: shown(LOGIN_TITLE, VIEW_TIMEOUT) }, + { name: "sign-in", url: url("sign-in", "auth-login"), prepare: shown(LOGIN_TITLE, VIEW_TIMEOUT) }, { name: "sign-in-focus", - url: url("sign-in-focus", "/auth/login"), + url: url("sign-in-focus", "auth-login"), prepare: async (page) => { await shown(EMAIL, VIEW_TIMEOUT)(page); await page.locator(EMAIL).focus(); @@ -259,7 +263,7 @@ exports.register = function (shared) { }, { name: "sign-in-invalid", - url: url("sign-in-invalid", "/auth/login"), + url: url("sign-in-invalid", "auth-login"), prepare: async (page) => { await shown(EMAIL, VIEW_TIMEOUT)(page); await page.locator(EMAIL).fill("not-an-address"); @@ -269,7 +273,7 @@ exports.register = function (shared) { }, { name: "recovery-request", - url: url("recovery-request", "/auth/recovery/request"), + url: url("recovery-request", "auth-recovery-request"), prepare: shown(RECOVERY_SUBMIT, VIEW_TIMEOUT), }, ]; @@ -277,60 +281,60 @@ exports.register = function (shared) { function signedInViews({ teamId, projectId, fileId }) { const team = `team-id=${teamId}`; - const dashboard = (name, route, content) => ({ name, url: url(name, route), prepare: loaded(SIDEBAR, content) }); - const settings = (name, route, content) => ({ name, url: url(name, route), prepare: loaded(SETTINGS_NAV, content) }); + const dashboard = (name, screen, content) => ({ name, url: url(name, screen), prepare: loaded(SIDEBAR, content) }); + const settings = (name, screen, content) => ({ name, url: url(name, screen), prepare: loaded(SETTINGS_NAV, content) }); return [ - dashboard("projects", `/dashboard/recent?${team}`, NEW_PROJECT), + dashboard("projects", `dashboard-recent?${team}`, NEW_PROJECT), { name: "project-menu", - url: url("project-menu", `/dashboard/recent?${team}`), + url: url("project-menu", `dashboard-recent?${team}`), prepare: opened(SIDEBAR, PROJECT_OPTIONS, "[role='menu'] [role='menuitem']"), }, - dashboard("project-files", `/dashboard/files?${team}&project-id=${projectId}`, GRID_ITEM), - dashboard("libraries", `/dashboard/libraries?${team}`, HEADER), - dashboard("fonts", `/dashboard/fonts?${team}`, HEADER), - dashboard("deleted", `/dashboard/deleted?${team}`, DELETED), - dashboard("team-members", `/dashboard/members?${team}`, TABLE_ROW), - dashboard("team-invitations", `/dashboard/invitations?${team}`, INVITE), - dashboard("team-settings", `/dashboard/settings?${team}`, HEADER), + dashboard("project-files", `dashboard-files?${team}&project-id=${projectId}`, GRID_ITEM), + dashboard("libraries", `dashboard-libraries?${team}`, HEADER), + dashboard("fonts", `dashboard-fonts?${team}`, HEADER), + dashboard("deleted", `dashboard-deleted?${team}`, DELETED), + dashboard("team-members", `dashboard-members?${team}`, TABLE_ROW), + dashboard("team-invitations", `dashboard-invitations?${team}`, INVITE), + dashboard("team-settings", `dashboard-settings?${team}`, HEADER), { name: "invite-dialog", - url: url("invite-dialog", `/dashboard/invitations?${team}`), + url: url("invite-dialog", `dashboard-invitations?${team}`), prepare: opened(SIDEBAR, INVITE, INVITE_DIALOG), }, { name: "profile-menu", - url: url("profile-menu", `/dashboard/recent?${team}`), + url: url("profile-menu", `dashboard-recent?${team}`), prepare: opened(SIDEBAR, PROFILE_BUTTON, PROFILE_MENU_ENTRY), }, { name: "team-switcher", - url: url("team-switcher", `/dashboard/recent?${team}`), + url: url("team-switcher", `dashboard-recent?${team}`), prepare: opened(SIDEBAR, TEAM_SWITCH, TEAM_MENU_ENTRY), }, { name: "navigation-hover", - url: url("navigation-hover", `/dashboard/recent?${team}`), + url: url("navigation-hover", `dashboard-recent?${team}`), prepare: async (page) => { await shown(SIDEBAR, VIEW_TIMEOUT)(page); await page.locator(NAV_TITLE).nth(1).hover(); await animationsSettled(page); }, }, - settings("settings-profile", "/settings/profile", REMOVE_ACCOUNT), - settings("settings-password", "/settings/password", SAVE_PASSWORD), - settings("settings-notifications", "/settings/notifications", SAVE_NOTIFICATIONS), - settings("settings-options", "/settings/options", SETTINGS_FORM), - settings("settings-feedback", "/settings/feedback", HEADER), + settings("settings-profile", "settings-profile", REMOVE_ACCOUNT), + settings("settings-password", "settings-password", SAVE_PASSWORD), + settings("settings-notifications", "settings-notifications", SAVE_NOTIFICATIONS), + settings("settings-options", "settings-options", SETTINGS_FORM), + settings("settings-feedback", "settings-feedback", HEADER), { name: "delete-account-dialog", - url: url("delete-account-dialog", "/settings/profile"), + url: url("delete-account-dialog", "settings-profile"), prepare: opened(SETTINGS_NAV, REMOVE_ACCOUNT, CONFIRM_REMOVE_ACCOUNT), }, - { name: "not-found", url: url("not-found", "/design-showcase-missing"), prepare: shown("#app svg", VIEW_TIMEOUT) }, + { name: "not-found", url: url("not-found", "design-showcase-missing"), prepare: shown("#app svg", VIEW_TIMEOUT) }, { name: "workspace", - url: url("workspace", `/workspace?${team}&file-id=${fileId}`), + url: url("workspace", `workspace?${team}&file-id=${fileId}`), prepare: shown(LAYERS, VIEW_TIMEOUT), }, ]; @@ -338,7 +342,7 @@ exports.register = function (shared) { test("design: corporate tokens apply in light and dark mode", async ({ page }) => { skipUnlessServiceEnabled("design"); - await gotoOnion(page, url("tokens", "/auth/login")); + await gotoOnion(page, url("tokens", "auth-login")); await shown(LOGIN_TITLE)(page); await assertDesignTokens(page, "Penpot"); }); @@ -349,7 +353,7 @@ exports.register = function (shared) { skipUnlessServiceEnabled("design"); for (const mode of MODES) { await page.emulateMedia({ colorScheme: mode }); - await gotoOnion(page, url(`sign-in-${mode}`, "/auth/login")); + await gotoOnion(page, url(`sign-in-${mode}`, "auth-login")); await shown(LOGIN_TITLE)(page); await expect( page.locator("html"), @@ -385,7 +389,7 @@ exports.register = function (shared) { await withSystemTheme(page, async () => { for (const mode of MODES) { await page.emulateMedia({ colorScheme: mode }); - await gotoOnion(page, url(`shell-${mode}`, `/dashboard/recent?team-id=${teamId}`)); + await gotoOnion(page, url(`shell-${mode}`, `dashboard-recent?team-id=${teamId}`)); await shown(NEW_PROJECT)(page); await expect(page.locator("body"), "the system theme follows the browser").toHaveClass(THEME_CLASS[mode]); await expect(page.locator("html")).toHaveAttribute("data-design-theme", mode); @@ -395,7 +399,7 @@ exports.register = function (shared) { await assertToken(page, NAV_CURRENT, "background-color", "--design-surface-active", `selected entry ${mode}`); await assertToken(page, `${NAV_CURRENT} [class*='element-title']`, "color", "--design-link", `selected entry ${mode}`); - await gotoOnion(page, url(`form-${mode}`, "/settings/profile")); + await gotoOnion(page, url(`form-${mode}`, "settings-profile")); await shown(REMOVE_ACCOUNT)(page); await assertToken(page, SETTINGS_CONTAINER, "border-top-color", "--design-border", `content divider ${mode}`); const fullname = page.locator(`${SETTINGS_CONTAINER} input[type='text']`).first(); @@ -408,7 +412,7 @@ exports.register = function (shared) { await assertToken(page, SAVE_PROFILE, "background-color", "--design-primary-hover", `hovered action ${mode}`); } await page.emulateMedia({ colorScheme: null }); - await gotoOnion(page, url("shell", `/dashboard/recent?team-id=${teamId}`)); + await gotoOnion(page, url("shell", `dashboard-recent?team-id=${teamId}`)); await shown(NEW_PROJECT)(page); await assertLightAndDark(page, SIDEBAR, "Penpot dashboard"); await assertReadable( @@ -427,7 +431,7 @@ exports.register = function (shared) { const surface = () => tokenValue(page, "--design-surface-1", "background-color"); try { await page.emulateMedia({ colorScheme: "dark" }); - await gotoOnion(page, url("theme", "/settings/options")); + await gotoOnion(page, url("theme", "settings-options")); await shown(SETTINGS_FORM)(page); await expect(html, "the system theme follows the browser").toHaveAttribute("data-design-theme", "dark"); const darkSurface = await surface(); @@ -449,7 +453,7 @@ exports.register = function (shared) { darkSurface, ); - await gotoOnion(page, url("theme-kept", "/settings/options")); + await gotoOnion(page, url("theme-kept", "settings-options")); await shown(SETTINGS_FORM)(page); await expect(html, "the picked theme must survive a reload").toHaveAttribute("data-design-theme", "dark"); @@ -465,7 +469,7 @@ exports.register = function (shared) { test("design: the interface shows the generated logo and the configured title", async ({ page }) => { skipUnlessServiceEnabled("design"); test.skip(!logoUrl && !title, "logo and title replacement are disabled for this role"); - await gotoOnion(page, url("brand", "/auth/login")); + await gotoOnion(page, url("brand", "auth-login")); await shown(LOGIN_TITLE)(page); const titled = (label) => expect diff --git a/roles/web-app-penpot/files/playwright/test-seaweedfs.js b/roles/web-app-penpot/files/playwright/test-seaweedfs.js index b0e9df0089..ed39569d5b 100644 --- a/roles/web-app-penpot/files/playwright/test-seaweedfs.js +++ b/roles/web-app-penpot/files/playwright/test-seaweedfs.js @@ -21,8 +21,8 @@ test("seaweedfs: an uploaded Penpot image asset is stored in the SeaweedFS bucke await expect(newFile, "Expected a create-file control in Drafts").toBeVisible({ timeout: resolveTimeout(60_000) }); await newFile.click({ timeout: resolveTimeout(30_000) }); await expect - .poll(() => appPage.url(), { timeout: resolveTimeout(90_000), message: "expected to enter the Penpot workspace editor" }) - .toContain("/workspace"); + .poll(() => shared.screenOf(appPage.url()), { timeout: resolveTimeout(90_000), message: "expected to enter the Penpot workspace editor" }) + .toBe("workspace"); const seed = Date.now(); const markerBase = `infinito-storage-check-${seed}`; diff --git a/roles/web-app-penpot/templates/design.js b/roles/web-app-penpot/templates/design.js index 7c9cd95487..40162e4083 100644 --- a/roles/web-app-penpot/templates/design.js +++ b/roles/web-app-penpot/templates/design.js @@ -1,7 +1,7 @@ (function () { const root = document.documentElement; function visitor() { - return window.location.hash.indexOf("#/auth/") === 0; + return /[?&]screen=auth-/.test(window.location.search) || window.location.hash.indexOf("#/auth/") === 0; } function mirror() { const body = document.body; diff --git a/roles/web-app-penpot/templates/playwright.env.j2 b/roles/web-app-penpot/templates/playwright.env.j2 index 619fcb3a1a..e4559fa577 100644 --- a/roles/web-app-penpot/templates/playwright.env.j2 +++ b/roles/web-app-penpot/templates/playwright.env.j2 @@ -20,7 +20,7 @@ MATOMO_SERVICE_ENABLED={{ lookup('config', application_id, 'services.matomo.enab NODE_TLS_REJECT_UNAUTHORIZED=0 OIDC_ISSUER_URL={{ OIDC.CLIENT.ISSUER_URL | dotenv_quote }} PENPOT_BASE_URL={{ lookup('tls', application_id, 'url.base') | dotenv_quote }} -# nocheck: persona-block-rationale — Penpot's login lives on the SPA hash route /#/auth/login (files/playwright/_shared.js:84), which the helper's ${base}/login probing never reaches, and its OIDC entry is a bare "OpenID" text node (files/playwright/_shared.js:94-100) rather than a link or button named log in / sign in / sso; under OIDC the native password form is disabled outright via PENPOT_FLAGS (vars/main.yml:44, README "Identity"). Admin auth is covered by files/playwright/test-login-oidc-admin.js, test-login-ldap-admin.js and test-login-native.js (see README "Testing"). +# nocheck: persona-block-rationale — Penpot's login lives on the query-routed SPA screen /?screen=auth-login (files/playwright/_shared.js:87), which the helper's ${base}/login probing never reaches, and its OIDC entry is a bare "OpenID" text node (files/playwright/_shared.js:121-128) rather than a link or button named log in / sign in / sso; under OIDC the native password form is disabled outright via PENPOT_FLAGS (vars/main.yml:44, README "Identity"). Admin auth is covered by files/playwright/test-login-oidc-admin.js, test-login-ldap-admin.js and test-login-native.js (see README "Testing"). PERSONA_ADMINISTRATOR_BLOCKED=true # nocheck: persona-block-rationale — see PERSONA_ADMINISTRATOR_BLOCKED above; biber's auth is covered by files/playwright/test-login-oidc-biber.js and test-login-ldap-biber.js (see README "Testing"). diff --git a/tests/unit/javascript/roles/web-app-penpot/files/playwright/_shared.test.js b/tests/unit/javascript/roles/web-app-penpot/files/playwright/_shared.test.js new file mode 100644 index 0000000000..128365c013 --- /dev/null +++ b/tests/unit/javascript/roles/web-app-penpot/files/playwright/_shared.test.js @@ -0,0 +1,155 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const path = require("node:path"); + +const PROJECT_ROOT = path.resolve(__dirname, "../../../../../../.."); +const { loadInternals } = require(path.join(PROJECT_ROOT, "tests/unit/javascript/utils/internals.js")); + +const BASE = "https://penpot.example.test"; +const ISSUER = "https://auth.example.test/realms/main"; +const DASHBOARD = `${BASE}/?screen=dashboard-recent&team-id=7b12b6b6`; +const SIDEBAR = "[data-testid='dashboard-sidebar']"; + +function pollMatchers(read, message, negate) { + return { + toMatch: async (pattern) => { + const value = await read(); + assert.equal(pattern.test(value), !negate, `${message} (received ${value})`); + }, + toContain: async (part) => { + const value = await read(); + assert.equal(value.includes(part), !negate, `${message} (received ${value})`); + }, + }; +} + +function expect(locator, message) { + return { + toBeVisible: async () => assert.ok(await locator.isVisible(), message), + toBeEnabled: async () => assert.ok(await locator.isEnabled(), message), + }; +} +expect.poll = (read, { message }) => ({ ...pollMatchers(read, message, false), not: pollMatchers(read, message, true) }); + +const registers = new Proxy(() => undefined, { get: () => () => undefined }); + +process.env.PENPOT_BASE_URL = BASE; +process.env.OIDC_ISSUER_URL = ISSUER; + +const { assertAuthenticated, penpotOidcLogin, loginRoute, screenOf } = loadInternals( + path.join(PROJECT_ROOT, "roles/web-app-penpot/files/playwright/_shared.js"), + ["assertAuthenticated", "penpotOidcLogin", "loginRoute", "screenOf"], + { + "@playwright/test": { expect, test: registers }, + "./timeouts": { resolveTimeout: (ms) => ms }, + "./personas": { + decodeDotenvQuotedValue: (value) => value, + normalizeBaseUrl: (value) => value, + gotoOnion: async (page, url) => page.goto(url), + performKeycloakLoginForm: async (page) => page.signedInAtKeycloak(), + }, + }, + { URL }, +); + +/** + * Args: + * callback: screen Penpot 2.19 answers the OIDC callback with; "register" stands for a first sign-in. + * fullname: full name the identity provider handed to the first sign-in form. + * + * Returns: + * The fake Penpot page and its state: the current URL, the full name in the form and the profiles created. + */ +function penpot({ callback, fullname = "" }) { + const state = { url: "about:blank", fullname, created: 0 }; + const screen = () => new URL(state.url).searchParams.get("screen") || ""; + const control = (visible, actions = {}) => ({ + isVisible: async () => visible(), + isEnabled: async () => visible(), + ...actions, + }); + const hidden = control(() => false); + const page = { + url: () => state.url, + goto(url) { + const legacy = /^#\/(.*)$/.exec(new URL(url).hash); + state.url = legacy ? `${BASE}/?screen=${legacy[1].replace(/\//g, "-")}` : url; + }, + signedInAtKeycloak() { + state.url = callback === "register" ? `${BASE}/?screen=auth-register-validate&token=prepared` : callback; + }, + getByText: (text) => + text === "OpenID" + ? control(() => screen() === "auth-login", { + click: async () => { + state.url = `${ISSUER}/protocol/openid-connect/auth?client_id=penpot`; + }, + }) + : hidden, + getByLabel: (pattern) => + pattern.test("Full Name") + ? control(() => screen() === "auth-register-validate", { + inputValue: async () => state.fullname, + fill: async (value) => { + state.fullname = value; + }, + }) + : hidden, + getByRole: (role, { name }) => + role === "button" && name.test("Create an account") + ? control(() => screen() === "auth-register-validate" && state.fullname !== "", { + click: async () => { + state.created += 1; + state.url = DASHBOARD; + }, + }) + : hidden, + locator: (selector) => control(() => selector === SIDEBAR && screen().startsWith("dashboard-")), + }; + return { page, state }; +} + +test("the login route uses the query-string screen Penpot 2.19 routes by", () => { + assert.equal(loginRoute(`${BASE}/`), `${BASE}/?screen=auth-login`); +}); + +test("the editor screen is read from the screen key Penpot 2.19 puts in the query string", () => { + assert.equal(screenOf(`${BASE}/?screen=workspace&team-id=7b12b6b6&file-id=1f2e`), "workspace"); + assert.equal(screenOf(`${BASE}/#/workspace?team-id=7b12b6b6`), ""); +}); + +test("an existing profile signs in via OIDC straight to the query-routed dashboard", async () => { + const { page, state } = penpot({ callback: DASHBOARD }); + await penpotOidcLogin(page, "administrator", "secret"); + assert.equal(state.url, DASHBOARD); + assert.equal(state.created, 0); +}); + +test("a first OIDC sign-in submits Penpot's registration form and lands on the dashboard", async () => { + const { page, state } = penpot({ callback: "register" }); + await penpotOidcLogin(page, "biber", "secret"); + assert.equal(state.created, 1); + assert.equal(state.fullname, "biber"); + assert.equal(state.url, DASHBOARD); +}); + +test("a full name the identity provider handed over is kept on the first sign-in", async () => { + const { page, state } = penpot({ callback: "register", fullname: "Platform Administrator" }); + await penpotOidcLogin(page, "administrator", "secret"); + assert.equal(state.created, 1); + assert.equal(state.fullname, "Platform Administrator"); +}); + +test("an OIDC callback that ends on the login screen fails instead of waiting for a form", async () => { + const { page, state } = penpot({ callback: `${BASE}/?screen=auth-login&error=registration-disabled` }); + await assert.rejects(penpotOidcLogin(page, "biber", "secret"), /dashboard or its first sign-in form/); + assert.equal(state.created, 0); +}); + +test("an auth screen never counts as signed in", async () => { + for (const url of [`${BASE}/?screen=auth-login`, `${BASE}/?screen=auth-register-validate&token=t`, `${BASE}/#/dashboard/recent`]) { + const { page, state } = penpot({ callback: DASHBOARD }); + state.url = url; + await assert.rejects(assertAuthenticated(page), /dashboard screen after sign-in/, url); + } +}); diff --git a/tests/unit/javascript/roles/web-app-penpot/files/playwright/test-design.test.js b/tests/unit/javascript/roles/web-app-penpot/files/playwright/test-design.test.js new file mode 100644 index 0000000000..6e9141f272 --- /dev/null +++ b/tests/unit/javascript/roles/web-app-penpot/files/playwright/test-design.test.js @@ -0,0 +1,39 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const path = require("node:path"); + +const PROJECT_ROOT = path.resolve(__dirname, "../../../../../../.."); +const { loadInternals } = require(path.join(PROJECT_ROOT, "tests/unit/javascript/utils/internals.js")); + +const BASE = "https://penpot.example.test"; + +const { screenUrl } = loadInternals( + path.join(PROJECT_ROOT, "roles/web-app-penpot/files/playwright/test-design.js"), + ["screenUrl"], + {}, + {}, +); + +test("a design view opens its screen through the query string Penpot 2.19 routes by, not a legacy hash", () => { + const signIn = new URL(screenUrl(BASE, "sign-in", "auth-login")); + assert.equal(signIn.hash, ""); + assert.equal(signIn.searchParams.get("screen"), "auth-login"); + assert.equal(signIn.searchParams.get("design-view"), "sign-in"); +}); + +test("the screen's own parameters travel next to the screen key", () => { + const files = new URL(screenUrl(BASE, "project-files", "dashboard-files?team-id=7b12&project-id=9c3d")); + assert.equal(files.hash, ""); + assert.equal(files.searchParams.get("screen"), "dashboard-files"); + assert.equal(files.searchParams.get("team-id"), "7b12"); + assert.equal(files.searchParams.get("project-id"), "9c3d"); + assert.equal(files.searchParams.get("design-view"), "project-files"); +}); + +test("the app root carries no screen key", () => { + assert.equal(screenUrl(BASE, "session", ""), `${BASE}/?design-view=session`); +}); + +test("two views of one screen get documents of their own", () => { + assert.notEqual(screenUrl(BASE, "sign-in", "auth-login"), screenUrl(BASE, "sign-in-focus", "auth-login")); +}); diff --git a/tests/unit/javascript/roles/web-app-penpot/templates/design.test.js b/tests/unit/javascript/roles/web-app-penpot/templates/design.test.js new file mode 100644 index 0000000000..fb8064da92 --- /dev/null +++ b/tests/unit/javascript/roles/web-app-penpot/templates/design.test.js @@ -0,0 +1,61 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); +const vm = require("node:vm"); + +const SOURCE = path.join(__dirname, "..", "..", "..", "..", "..", "..", "roles", "web-app-penpot", "templates", "design.js"); + +/** + * Args: + * location: search and hash of the Penpot page the script runs on. + * bodyClass: theme class Penpot set on the body. + * + * Returns: + * The value of data-design-theme on the root element, or undefined when the script left it unset. + */ +function mirroredTheme(location, bodyClass) { + const attributes = {}; + const document = { + documentElement: { + setAttribute: (name, value) => { + attributes[name] = value; + }, + removeAttribute: (name) => { + delete attributes[name]; + }, + }, + body: { classList: { contains: (name) => name === bodyClass } }, + addEventListener() {}, + }; + const window = { + location: { search: "", hash: "", ...location }, + history: { pushState() {}, replaceState() {} }, + addEventListener() {}, + }; + class MutationObserver { + observe() {} + } + vm.runInNewContext(fs.readFileSync(SOURCE, "utf8"), { + document, + window, + MutationObserver, + INFINITO_DESIGN: { title: "", logo: "" }, + }); + return attributes["data-design-theme"]; +} + +test("a query-routed auth screen of Penpot 2.19 counts as a visitor page and keeps the browser palette", () => { + assert.equal(mirroredTheme({ search: "?screen=auth-login" }, "default"), undefined); + assert.equal(mirroredTheme({ search: "?screen=auth-register-validate&token=t" }, "light"), undefined); + assert.equal(mirroredTheme({ search: "?design-view=sign-in&screen=auth-recovery-request" }, "default"), undefined); +}); + +test("a legacy hash auth route still counts as a visitor page", () => { + assert.equal(mirroredTheme({ hash: "#/auth/login" }, "default"), undefined); +}); + +test("a signed-in screen mirrors the theme Penpot picked", () => { + assert.equal(mirroredTheme({ search: "?screen=dashboard-recent&team-id=1" }, "default"), "dark"); + assert.equal(mirroredTheme({ search: "?screen=settings-options" }, "light"), "light"); +}); From 43b8edb5cb8ce147322f1b57eb281899084c34d6 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Fri, 13 Nov 2026 09:19:21 +0000 Subject: [PATCH 13/25] fix(svc-cache-package): suppress CVE-2026-4738 on the frontend image too MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The package cache frontend runs the same nginx alpine tag as eight other services, which all carry the image_tag suppression for its unfixed CRITICAL; the frontend lacked it, so the docs-guide replay at production severity failed the e2e CLI job (main run 43288523728 package#0). Add the suppression and a lint that makes every non-custom service on one upstream image tag share an image_tag suppression another service declares for that tag. Committed below the 90 % fix bar on the operator's word; the deploy job has not confirmed it yet. 🎯 Fix: 88 % 💥 Break: 3 % 💸 Cost: 100 % ⏱️ Time: 100 % 🛡️ Security: 100 % 🏆 Score: 85 🚦 Gate: ⛔ fix 88 % < 90 Co-Authored-By: Claude Opus 5.5 --- roles/svc-cache-package/meta/services.yml | 5 ++ .../ansible/services/test_cve_suppressions.py | 85 +++++++++++++++++++ 2 files changed, 90 insertions(+) diff --git a/roles/svc-cache-package/meta/services.yml b/roles/svc-cache-package/meta/services.yml index f1a9a92e74..1a4e561a09 100644 --- a/roles/svc-cache-package/meta/services.yml +++ b/roles/svc-cache-package/meta/services.yml @@ -89,6 +89,11 @@ frontend: http: 80 https: 443 lifecycle: beta + security: + suppressions: + # nocheck: cve upstream tag ships fixable CRITICAL CVEs; lift it once a rebuilt tag lands + - image_tag: "1.31-alpine" + until: 2026-11-30 # nocheck: dynamic-flag - proxied package content is re-fetchable, the backup consumer stays permanently off container_backup: enabled: false diff --git a/tests/lint/ansible/services/test_cve_suppressions.py b/tests/lint/ansible/services/test_cve_suppressions.py index 58a92e6513..878b8617fc 100644 --- a/tests/lint/ansible/services/test_cve_suppressions.py +++ b/tests/lint/ansible/services/test_cve_suppressions.py @@ -119,6 +119,47 @@ def problems(text: str, where: str, today: dt.date) -> list[str]: return found +def unshared_image_tags(services: dict[str, object]) -> list[str]: + """ + Args: + services: ``{role: meta/services.yml mapping}`` of every role. + + Returns: + One message per non-custom service that runs an upstream image tag + another non-custom service suppresses by ``image_tag`` while it does not. + """ + running: dict[tuple[str, str], list[str]] = {} + accepted: dict[tuple[str, str], list[str]] = {} + for role, declared in sorted(services.items()): + if not isinstance(declared, dict): + continue + for service, spec in declared.items(): + if not isinstance(spec, dict) or spec.get("custom"): + continue + if "image" not in spec or "version" not in spec: + continue + key = (str(spec["image"]), str(spec["version"])) + owner = f"{role}:{service}" + running.setdefault(key, []).append(owner) + security = spec.get("security") + entries = ( + security.get("suppressions") if isinstance(security, dict) else None + ) + if isinstance(entries, list) and any( + isinstance(entry, dict) and str(entry.get("image_tag")) == key[1] + for entry in entries + ): + accepted.setdefault(key, []).append(owner) + return [ + f"{owner} runs {image}:{tag} without the image_tag suppression declared " + f"for the same upstream image by {', '.join(accepted[(image, tag)])}" + for (image, tag), owners in sorted(running.items()) + if (image, tag) in accepted + for owner in owners + if owner not in accepted[(image, tag)] + ] + + class TestCveSuppressions(unittest.TestCase): def test_every_suppression_is_justified_and_dated(self) -> None: today = dt.datetime.now(tz=dt.UTC).date() @@ -131,6 +172,16 @@ class TestCveSuppressions(unittest.TestCase): found += problems(text, str(path.relative_to(PROJECT_ROOT)), today) self.assertEqual(found, [], "\n".join(found)) + def test_services_on_one_upstream_image_tag_share_its_suppression(self) -> None: + services = { + path.parent.parent.name: load_yaml_str(read_text(str(path))) + for path in sorted( + (PROJECT_ROOT / "roles").glob(f"*/{ROLE_FILE_META_SERVICES}") + ) + } + found = unshared_image_tags(services) + self.assertEqual(found, [], "\n".join(found)) + TODAY = dt.date(2026, 10, 31) VALID = """\ @@ -228,6 +279,40 @@ app: - image_tag: "2.18.6" until: 2026-11-30 """ +UNTAGGED = """\ +app: + image: app + version: "2.18.6" +""" + + +class TestSiblingImageTagCases(unittest.TestCase): + def _found(self, **roles: str) -> list[str]: + return unshared_image_tags( + {role: load_yaml_str(text) for role, text in roles.items()} + ) + + def test_siblings_that_both_suppress_the_tag_pass(self) -> None: + self.assertEqual(self._found(a=TAGGED, b=TAGGED), []) + + def test_a_sibling_without_the_tag_suppression_fails(self) -> None: + self.assertEqual( + self._found(a=TAGGED, b=UNTAGGED), + [ + ( + "b:app runs app:2.18.6 without the image_tag suppression declared " + "for the same upstream image by a:app" + ) + ], + ) + + def test_a_custom_build_on_the_same_tag_is_its_own_image(self) -> None: + custom = UNTAGGED.replace(" image: app\n", " image: app\n custom: true\n") + self.assertEqual(self._found(a=TAGGED, b=custom), []) + + def test_a_sibling_on_another_tag_is_not_compared(self) -> None: + other = UNTAGGED.replace("2.18.6", "2.18.7") + self.assertEqual(self._found(a=TAGGED, b=other), []) if __name__ == "__main__": From 06614ba74cd2df72367bc80601f4b50068a82a6a Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Fri, 13 Nov 2026 09:19:51 +0000 Subject: [PATCH 14/25] fix(dsk-blender): keep the Flathub blender on PATH for the user probes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On CentOS the Flathub blender wrapper lives in /usr/local/bin, which sudo's secure_path drops, so the workstation-user probe of the addons dir could not find blender (main run 43288523728 Blender#0 centos). Set PATH on the dsk-blender includes that run as the workstation user, and test that every such task carries it. Committed below the 90 % fix bar on the operator's word. Residual: flatpak run as a non-root user inside the CI container is not proven yet; the next centos Blender job decides. 🎯 Fix: 85 % 💥 Break: 4 % 💸 Cost: 100 % ⏱️ Time: 100 % 🛡️ Security: 100 % 🏆 Score: 82 🚦 Gate: ⛔ fix 85 % < 90 Co-Authored-By: Claude Opus 5.5 --- roles/dsk-blender/tasks/00_core.yml | 4 + .../tasks/addons/mcp-for-blender.yml | 2 +- roles/dsk-blender/vars/main.yml | 1 + .../roles/dsk-blender/test_exec_path.py | 91 +++++++++++++++++++ 4 files changed, 97 insertions(+), 1 deletion(-) create mode 100644 tests/unit/python/roles/dsk-blender/test_exec_path.py diff --git a/roles/dsk-blender/tasks/00_core.yml b/roles/dsk-blender/tasks/00_core.yml index 9f038f066f..ebee471138 100644 --- a/roles/dsk-blender/tasks/00_core.yml +++ b/roles/dsk-blender/tasks/00_core.yml @@ -7,6 +7,8 @@ apply: become: true become_user: "{{ blender_user }}" + environment: + PATH: "{{ blender_exec_path }}" when: blender_mcp_enabled | bool - name: 🏛️ Give Blender its IFC and BIM surface @@ -15,4 +17,6 @@ apply: become: true become_user: "{{ blender_user }}" + environment: + PATH: "{{ blender_exec_path }}" when: blender_bonsai_enabled | bool diff --git a/roles/dsk-blender/tasks/addons/mcp-for-blender.yml b/roles/dsk-blender/tasks/addons/mcp-for-blender.yml index 55dc5a8c26..555ca8f2d8 100644 --- a/roles/dsk-blender/tasks/addons/mcp-for-blender.yml +++ b/roles/dsk-blender/tasks/addons/mcp-for-blender.yml @@ -30,7 +30,7 @@ - install-addon environment: BLENDERMCP_ADDONS_DIR: "{{ blender_addons_probe.stdout | regex_search('ADDONS=(\\S+)', '\\1') | first }}" - PATH: "{{ blender_pipx_bin_dir }}:/usr/local/bin:/usr/bin:/bin" + PATH: "{{ blender_pipx_bin_dir }}:{{ blender_exec_path }}" register: blender_mcp_addon changed_when: "'installed' in (blender_mcp_addon.stdout | lower)" diff --git a/roles/dsk-blender/vars/main.yml b/roles/dsk-blender/vars/main.yml index 52e71b26f3..86dede1a17 100644 --- a/roles/dsk-blender/vars/main.yml +++ b/roles/dsk-blender/vars/main.yml @@ -3,6 +3,7 @@ application_id: dsk-blender blender_user: "{{ lookup('users', WORKSTATION_USER).username }}" blender_home: "/home/{{ blender_user }}" blender_pipx_bin_dir: "{{ [blender_home, '.local', 'bin'] | path_join }}" +blender_exec_path: "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" blender_claude_registry: "{{ [blender_home, '.claude.json'] | path_join }}" blender_mcp_enabled: "{{ lookup('config', application_id, 'addons.mcp-for-blender.enabled') | bool }}" blender_mcp_distribution: "{{ lookup('config', application_id, 'addons.mcp-for-blender.config.distribution') }}" diff --git a/tests/unit/python/roles/dsk-blender/test_exec_path.py b/tests/unit/python/roles/dsk-blender/test_exec_path.py new file mode 100644 index 0000000000..a28e844a1e --- /dev/null +++ b/tests/unit/python/roles/dsk-blender/test_exec_path.py @@ -0,0 +1,91 @@ +from __future__ import annotations + +import unittest + +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar + +from utils.cache.files import PROJECT_ROOT, read_text +from utils.cache.yaml import load_yaml_str +from utils.packages.sources import FLATPAK_COMMAND_DIR +from utils.roles.mapping import ROLE_FILE_VARS_MAIN +from utils.templating.ansible import _trust_as_template + +ROLE = PROJECT_ROOT / "roles/dsk-blender" +PIPX_BIN_DIR = "/home/alice/.local/bin" +USER_TASKS = ("addons/bonsai.yml", "addons/mcp-for-blender.yml") +ROOT_OWNED = ("/usr/", "/sbin", "/bin") + + +def _yaml(relative): + return load_yaml_str(read_text(str(ROLE / relative))) + + +def _search_path(template): + templar = Templar( + loader=DataLoader(), + variables={ + "blender_exec_path": _yaml(ROLE_FILE_VARS_MAIN).get("blender_exec_path"), + "blender_pipx_bin_dir": PIPX_BIN_DIR, + }, + ) + return str(templar.template(_trust_as_template(template))).split(":") + + +def _includes(): + return { + task["ansible.builtin.include_tasks"]["file"]: task + for task in _yaml("tasks/00_core.yml") + if "ansible.builtin.include_tasks" in task + } + + +def _tasks(relative): + for task in _yaml(f"tasks/{relative}"): + yield task + yield from task.get("block", []) + + +class TestBlenderExecPath(unittest.TestCase): + def test_every_workstation_user_include_searches_the_command_dirs(self): + includes = _includes() + self.assertEqual(sorted(includes), list(USER_TASKS)) + for relative, include in includes.items(): + apply = include["ansible.builtin.include_tasks"]["apply"] + path = (apply.get("environment") or {}).get("PATH") + with self.subTest(include=relative): + self.assertIsNotNone( + path, + f"{relative} runs as the workstation user through sudo, and " + f"CentOS Stream pins secure_path to /sbin:/bin:/usr/sbin:/usr/bin, " + f"so the flatpak launcher package_install links into " + f"{FLATPAK_COMMAND_DIR} is not found ([Errno 2] No such file " + f"or directory: b'blender', run 43288523728)", + ) + segments = _search_path(path) + self.assertIn(FLATPAK_COMMAND_DIR, segments) + self.assertIn("/usr/bin", segments) + + def test_the_include_path_holds_only_root_owned_dirs(self): + segments = str(_yaml(ROLE_FILE_VARS_MAIN).get("blender_exec_path")).split(":") + self.assertTrue( + all(segment.startswith(ROOT_OWNED) for segment in segments), + f"{segments}: the include PATH also reaches the package_install of " + f"pipx, which runs as root, so a dir the workstation user can write " + f"would let that user plant a binary root executes", + ) + + def test_a_task_level_path_keeps_the_command_dirs(self): + for relative in USER_TASKS: + for task in _tasks(relative): + path = (task.get("environment") or {}).get("PATH") + if path is None: + continue + with self.subTest(task=task["name"]): + segments = _search_path(path) + self.assertIn(FLATPAK_COMMAND_DIR, segments) + self.assertIn("/usr/bin", segments) + + +if __name__ == "__main__": + unittest.main() From 51ac4bc04b0b36349194e6cda9f1f7190cadf8ae Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Fri, 13 Nov 2026 10:17:23 +0000 Subject: [PATCH 15/25] refactor(registry): move valid_digest into utils/docker/digest.py MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The digest check pushed utils/docker/registry.py past the 500-line limit of the Python file-size lint. valid_digest and its pattern move unchanged into utils/docker/digest.py, registry.py imports it for its two call sites, and TestValidDigest moves to test_digest.py with the same cases. Tests: test_digest.py 2 passed, test_registry.py 37 passed, file-size lint passed, ruff clean; quality-high green on this tree (test 4/4, lint 15/15). Security 65 % comes from two MEDUSA findings on unchanged lines of the existing registry HTTP client, committed on the operator word: registry.py:106 (a redirect forwards the bearer token to any host, B310) and registry.py:142 (Link next may switch host, WEB-SSRF); both are fixed in cluster/registry-redirect-token-leak on fix/utils/docker/registry-redirect-auth. Accepted as by design after a skeptic review: WEB-SSRF at registry.py:299, 465 and 488 (https-pinned URLs with quoted path segments) and B310 at registry.py:79 (https-only token realm). 🎯 Fix: 95 % 💥 Break: 1 % 💸 Cost: – ⏱️ Time: – 🛡️ Security: 65 % 🏆 Score: 61 🚦 Gate: ⚠️ security 65 % < 100: committed on the operator word Co-Authored-By: Claude Opus 5.5 --- tests/unit/python/utils/docker/test_digest.py | 32 +++++++++++++++++++ .../unit/python/utils/docker/test_registry.py | 21 ------------ utils/docker/digest.py | 19 +++++++++++ utils/docker/registry.py | 17 +--------- 4 files changed, 52 insertions(+), 37 deletions(-) create mode 100644 tests/unit/python/utils/docker/test_digest.py create mode 100644 utils/docker/digest.py diff --git a/tests/unit/python/utils/docker/test_digest.py b/tests/unit/python/utils/docker/test_digest.py new file mode 100644 index 0000000000..e8cae7d999 --- /dev/null +++ b/tests/unit/python/utils/docker/test_digest.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +import unittest + +from utils.docker.digest import valid_digest + +SHA256 = "sha256:" + "d" * 64 +SHA512 = "sha512:" + "f" * 128 + + +class TestValidDigest(unittest.TestCase): + def test_well_formed_sha256_and_sha512_pass(self) -> None: + self.assertEqual(valid_digest(SHA256), SHA256) + self.assertEqual(valid_digest(SHA512), SHA512) + + def test_anything_that_could_name_another_path_is_dropped(self) -> None: + for value in ( + "sha256:/../../etc", + "sha256:" + "d" * 63 + "/", + "sha256:" + "D" * 64, + "sha256:" + "d" * 64 + "\n", + "md5:" + "d" * 32, + "", + None, + 42, + ): + with self.subTest(value=value): + self.assertIsNone(valid_digest(value)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/docker/test_registry.py b/tests/unit/python/utils/docker/test_registry.py index c83bf70b5b..48b2ec1150 100644 --- a/tests/unit/python/utils/docker/test_registry.py +++ b/tests/unit/python/utils/docker/test_registry.py @@ -100,27 +100,6 @@ class TestManifestExists(_IsolatedProbeCache): self.assertEqual(url, "https://quay.io/v2/keycloak/keycloak/manifests/26.6.3") -class TestValidDigest(unittest.TestCase): - def test_well_formed_sha256_and_sha512_pass(self) -> None: - sha512 = "sha512:" + "f" * 128 - self.assertEqual(registry.valid_digest(HEAD), HEAD) - self.assertEqual(registry.valid_digest(sha512), sha512) - - def test_anything_that_could_name_another_path_is_dropped(self) -> None: - for value in ( - "sha256:/../../etc", - "sha256:" + "d" * 63 + "/", - "sha256:" + "D" * 64, - "sha256:" + "d" * 64 + "\n", - "md5:" + "d" * 32, - "", - None, - 42, - ): - with self.subTest(value=value): - self.assertIsNone(registry.valid_digest(value)) - - class TestManifestDigest(unittest.TestCase): def test_a_malformed_content_digest_is_indeterminate(self) -> None: with mock.patch.object( diff --git a/utils/docker/digest.py b/utils/docker/digest.py new file mode 100644 index 0000000000..1d4b2b3478 --- /dev/null +++ b/utils/docker/digest.py @@ -0,0 +1,19 @@ +from __future__ import annotations + +import re + +_DIGEST_RE = re.compile(r"sha256:[0-9a-f]{64}|sha512:[0-9a-f]{128}") + + +def valid_digest(value: object) -> str | None: + """ + Args: + value: a ``digest`` field or ``Docker-Content-Digest`` header. + + Returns: + ``value`` when it is ``sha256:`` or ``sha512:`` with lowercase hex of + the matching length, else ``None``. + """ + if isinstance(value, str) and _DIGEST_RE.fullmatch(value): + return value + return None diff --git a/utils/docker/registry.py b/utils/docker/registry.py index c3ad9fce80..5d5bdf4d43 100644 --- a/utils/docker/registry.py +++ b/utils/docker/registry.py @@ -26,6 +26,7 @@ import urllib.request from pathlib import Path from urllib.parse import quote, urlencode, urlparse +from utils.docker.digest import valid_digest from utils.docker.image.ref import DOCKER_HUB_REGISTRIES, split_registry_and_name from utils.docker.mirror import mirror_image @@ -34,7 +35,6 @@ _UNKNOWN_PLATFORM = "unknown" _CACHE_ROOT = Path(tempfile.gettempdir()) / "infinito-registry-probe" _LINK_NEXT_RE = re.compile(r'<([^>]+)>\s*;\s*rel="next"', re.IGNORECASE) _CHALLENGE_PARAM_RE = re.compile(r'(\w+)="([^"]*)"') -_DIGEST_RE = re.compile(r"sha256:[0-9a-f]{64}|sha512:[0-9a-f]{128}") _MANIFEST_ACCEPT = ( "application/vnd.oci.image.index.v1+json, " "application/vnd.oci.image.manifest.v1+json, " @@ -218,21 +218,6 @@ def probe_order(image: str) -> list[str]: return [mirrored, image] -def valid_digest(value: object) -> str | None: - """Return a registry-supplied digest only when it is well formed. - - Args: - value: a ``digest`` field or ``Docker-Content-Digest`` header. - - Returns: - ``value`` when it is ``sha256:`` or ``sha512:`` with lowercase hex of - the matching length, else ``None``. - """ - if isinstance(value, str) and _DIGEST_RE.fullmatch(value): - return value - return None - - def platform_digest(manifests: list, os_name: str, architecture: str) -> str | None: for entry in manifests: if not isinstance(entry, dict): From a8b92869acf71a91c7179f90cada7fac3ff81f29 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Fri, 13 Nov 2026 12:52:38 +0000 Subject: [PATCH 16/25] fix(sys-service): bound the start of oneshot units by the default runtime MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit systemd disables the start timeout of Type=oneshot units by default (systemd.service: TimeoutStartSec), and RuntimeMaxSec does not apply to them, so a hung oneshot unit ran forever. system_service_tpl_timeout_start_sec now renders SYS_SERVICE_DEFAULT_RUNTIME (86400s) for oneshot units and stays empty for every other type, so roles that pass their own cap (sys-ctl-hlth-csp, sys-ctl-hlth-webserver, sys-ctl-cln-bkps) keep it. The comment that called the empty value intended is gone. Tests: test_oneshot_start_timeout.py renders the expression from vars/main.yml: a oneshot unit gets the default runtime, a simple unit keeps the manager default (2 passed; negative control on main: 1 failed). quality-high green on this tree (test 4/4, lint 15/15). Residual: a backup oneshot that runs longer than 24 h is now stopped; the prod hlth-runtime durations decide the per-role cap. 🎯 Fix: 92 % 💥 Break: 5 % 💸 Cost: – ⏱️ Time: – 🛡️ Security: 100 % 🏆 Score: 87 🚦 Gate: ✅ 90/5, cost and time <= 100, security 100 % Co-Authored-By: Claude Opus 5.5 --- roles/sys-service/vars/main.yml | 2 +- .../unit/python/roles/sys-service/__init__.py | 0 .../sys-service/test_oneshot_start_timeout.py | 36 +++++++++++++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 tests/unit/python/roles/sys-service/__init__.py create mode 100644 tests/unit/python/roles/sys-service/test_oneshot_start_timeout.py diff --git a/roles/sys-service/vars/main.yml b/roles/sys-service/vars/main.yml index 5392f9f1ac..222da26a1a 100644 --- a/roles/sys-service/vars/main.yml +++ b/roles/sys-service/vars/main.yml @@ -73,4 +73,4 @@ system_service_tpl_runtime: "{{ '' if system_service_tpl_type == 'oneshot' else system_service_tpl_exec_start_pre: "" system_service_tpl_exec_start: "{{ system_service_script_exec }}" system_service_tpl_exec_start_post: "" -system_service_tpl_timeout_start_sec: "" # If not defined the default values from sys-daemon in manager will be used +system_service_tpl_timeout_start_sec: "{{ SYS_SERVICE_DEFAULT_RUNTIME if system_service_tpl_type == 'oneshot' else '' }}" diff --git a/tests/unit/python/roles/sys-service/__init__.py b/tests/unit/python/roles/sys-service/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/sys-service/test_oneshot_start_timeout.py b/tests/unit/python/roles/sys-service/test_oneshot_start_timeout.py new file mode 100644 index 0000000000..4d31fde7e1 --- /dev/null +++ b/tests/unit/python/roles/sys-service/test_oneshot_start_timeout.py @@ -0,0 +1,36 @@ +import unittest + +from jinja2 import Environment, select_autoescape + +from utils.cache.files import PROJECT_ROOT +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_DEFAULTS_MAIN, ROLE_FILE_VARS_MAIN + +ROLE = PROJECT_ROOT / "roles" / "sys-service" +RUNTIME = load_yaml_any(str(ROLE / ROLE_FILE_DEFAULTS_MAIN))[ + "SYS_SERVICE_DEFAULT_RUNTIME" +] + + +def _start_timeout(unit_type: str) -> str: + expression = load_yaml_any(str(ROLE / ROLE_FILE_VARS_MAIN))[ + "system_service_tpl_timeout_start_sec" + ] + return ( + Environment(autoescape=select_autoescape()) + .from_string(expression) + .render(system_service_tpl_type=unit_type, SYS_SERVICE_DEFAULT_RUNTIME=RUNTIME) + ) + + +class TestOneshotStartTimeout(unittest.TestCase): + def test_a_oneshot_unit_gets_a_bounded_start(self) -> None: + self.assertTrue(RUNTIME) + self.assertEqual(_start_timeout("oneshot"), RUNTIME) + + def test_other_unit_types_keep_the_manager_default(self) -> None: + self.assertEqual(_start_timeout("simple"), "") + + +if __name__ == "__main__": + unittest.main() From 57a803c89ceaaecff7b8123d4cac2d2c59ce7eb4 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 13:54:32 +0000 Subject: [PATCH 17/25] update(versions): update pins with a declared source (dsk-gnt-codex) --- roles/dsk-gnt-codex/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/dsk-gnt-codex/meta/services.yml b/roles/dsk-gnt-codex/meta/services.yml index 068ed00b7a..11fe62524d 100644 --- a/roles/dsk-gnt-codex/meta/services.yml +++ b/roles/dsk-gnt-codex/meta/services.yml @@ -9,7 +9,7 @@ codex: host: enabled: true lifecycle: alpha - npm_version: 0.167.2 + npm_version: 0.169.0 update: key: npm_version type: npm From b464a234b6f7fefff057952eca749acedcf16c75 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 13:54:39 +0000 Subject: [PATCH 18/25] update(versions): update pins with a declared source (web-app-n8n) --- roles/web-app-n8n/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-n8n/meta/services.yml b/roles/web-app-n8n/meta/services.yml index 04ef0862a3..6fa693bea9 100644 --- a/roles/web-app-n8n/meta/services.yml +++ b/roles/web-app-n8n/meta/services.yml @@ -75,7 +75,7 @@ n8n: backup: stop_required: true image: docker.n8n.io/n8nio/n8n - version: "3.2.0" + version: "3.2.2" update: type: registry_tags image: docker.n8n.io/n8nio/n8n From a028f895c7ad75b06b6b5a34a21133b591445674 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 13:54:44 +0000 Subject: [PATCH 19/25] update(versions): update pins with a declared source (web-app-stalwart) --- roles/web-app-stalwart/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-stalwart/meta/services.yml b/roles/web-app-stalwart/meta/services.yml index ad504dda43..8e4e6af8a5 100644 --- a/roles/web-app-stalwart/meta/services.yml +++ b/roles/web-app-stalwart/meta/services.yml @@ -43,7 +43,7 @@ stalwart: # nocheck: default-placement-manager mail edge at a known IP: MX A-record, PTR and SPF bind to the stack host IP (a floating task's egress IP breaks deliverability); the mail store is NFS-hostile and IS the app — same rationale as web-app-mailu placement: manager image: stalwartlabs/stalwart - webui_version: "v2.0.5" + webui_version: "v2.0.6" version: "v1.1.0" update: - key: webui_version From 59940c3618282fdcad38ab62aa0778bc90ededa2 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:15:21 +0000 Subject: [PATCH 20/25] update(galaxy): bump pinned Ansible collections --- requirements/requirements.galaxy.yml | 2 +- requirements/requirements.git.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/requirements/requirements.galaxy.yml b/requirements/requirements.galaxy.yml index d33da491ca..742b4a0226 100644 --- a/requirements/requirements.galaxy.yml +++ b/requirements/requirements.galaxy.yml @@ -3,7 +3,7 @@ collections: - name: ansible.posix version: 2.2.2 - name: ansible.mariadb - version: 6.0.2 + version: 6.0.3 - name: kewlfft.aur version: 0.13.0 - name: community.general diff --git a/requirements/requirements.git.yml b/requirements/requirements.git.yml index 4abcbdb8b3..555e7cb524 100644 --- a/requirements/requirements.git.yml +++ b/requirements/requirements.git.yml @@ -8,7 +8,7 @@ collections: - name: ansible.mariadb source: https://github.com/ansible-collections/ansible.mariadb.git type: git - version: 6.0.2 + version: 6.0.3 - name: kewlfft.aur source: https://github.com/kewlfft/ansible-aur.git From ba4c2661e65fe446bd67e3147f8e5ce299443c55 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Fri, 13 Nov 2026 15:46:44 +0000 Subject: [PATCH 21/25] fix(registry): keep the registry token on the registry host across redirects MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit urllib forwards every request header on a redirect, so a blob or manifest request that the registry redirected to its CDN carried the bearer token to that third-party host, and a redirect or a Link next page could steer the client off https or to any host. utils/docker/redirect.py adds an opener whose redirect handler refuses a target that is not https and drops Authorization when the host changes; registry.py opens every request through it, and tag paging resolves Link next against the current URL and stops when it leaves https or the registry host. Tests: test_registry.py patches the opener and covers the cross-host token drop, the refused http redirect and the off-registry Link next (negative control with main's registry.py: 24 failed, among them the token reaching the CDN host). quality-high green on this tree (19/19), test-external against the live registries included. 🎯 Fix: 93 % 💥 Break: 3 % 💸 Cost: – ⏱️ Time: – 🛡️ Security: 100 % 🏆 Score: 90 🚦 Gate: ✅ 90/5, cost and time <= 100, security 100 % Co-Authored-By: Claude Opus 5.5 --- .../unit/python/utils/docker/test_registry.py | 141 +++++++++++++----- utils/docker/redirect.py | 19 +++ utils/docker/registry.py | 18 +-- 3 files changed, 130 insertions(+), 48 deletions(-) create mode 100644 utils/docker/redirect.py diff --git a/tests/unit/python/utils/docker/test_registry.py b/tests/unit/python/utils/docker/test_registry.py index 16120d0c0b..6b7a2892ed 100644 --- a/tests/unit/python/utils/docker/test_registry.py +++ b/tests/unit/python/utils/docker/test_registry.py @@ -6,6 +6,8 @@ import tempfile import unittest import unittest.mock as mock import urllib.error +import urllib.request +import urllib.response from email.message import Message from pathlib import Path @@ -59,7 +61,7 @@ def _http_error(code: int, headers=None) -> urllib.error.HTTPError: class TestManifestExists(_IsolatedProbeCache): def test_present_returns_true(self) -> None: with mock.patch.object( - registry.urllib.request, "urlopen", return_value=_Resp(status=200) + registry.OPENER, "open", return_value=_Resp(status=200) ) as opened: self.assertIs(registry.manifest_exists("postgres", "16"), True) url = opened.call_args.args[0].full_url @@ -68,26 +70,22 @@ class TestManifestExists(_IsolatedProbeCache): ) def test_absent_returns_false(self) -> None: - with mock.patch.object( - registry.urllib.request, "urlopen", side_effect=_http_error(404) - ): + with mock.patch.object(registry.OPENER, "open", side_effect=_http_error(404)): self.assertIs(registry.manifest_exists("postgres", "999"), False) def test_network_error_is_indeterminate(self) -> None: with mock.patch.object( - registry.urllib.request, "urlopen", side_effect=urllib.error.URLError("x") + registry.OPENER, "open", side_effect=urllib.error.URLError("x") ): self.assertIsNone(registry.manifest_exists("postgres", "16")) def test_auth_wall_without_realm_is_indeterminate(self) -> None: - with mock.patch.object( - registry.urllib.request, "urlopen", side_effect=_http_error(401) - ): + with mock.patch.object(registry.OPENER, "open", side_effect=_http_error(401)): self.assertIsNone(registry.manifest_exists("quay.io/foo/bar", "1")) def test_non_dockerhub_registry_host(self) -> None: with mock.patch.object( - registry.urllib.request, "urlopen", return_value=_Resp(status=200) + registry.OPENER, "open", return_value=_Resp(status=200) ) as opened: registry.manifest_exists("quay.io/keycloak/keycloak", "26.6.3") url = opened.call_args.args[0].full_url @@ -97,8 +95,8 @@ class TestManifestExists(_IsolatedProbeCache): class TestManifestDigest(unittest.TestCase): def test_returns_the_content_digest_of_a_head_request(self) -> None: with mock.patch.object( - registry.urllib.request, - "urlopen", + registry.OPENER, + "open", return_value=_Resp( status=200, headers={"Docker-Content-Digest": "sha256:abc"} ), @@ -116,29 +114,23 @@ class TestManifestDigest(unittest.TestCase): ) def test_missing_tag_has_no_digest(self) -> None: - with mock.patch.object( - registry.urllib.request, "urlopen", side_effect=_http_error(404) - ): + with mock.patch.object(registry.OPENER, "open", side_effect=_http_error(404)): self.assertIsNone(registry.manifest_digest("postgres", "999")) def test_rate_limit_has_no_digest(self) -> None: - with mock.patch.object( - registry.urllib.request, "urlopen", side_effect=_http_error(429) - ): + with mock.patch.object(registry.OPENER, "open", side_effect=_http_error(429)): self.assertIsNone(registry.manifest_digest("postgres", "16")) def test_answer_without_digest_header_has_no_digest(self) -> None: - with mock.patch.object( - registry.urllib.request, "urlopen", return_value=_Resp(status=200) - ): + with mock.patch.object(registry.OPENER, "open", return_value=_Resp(status=200)): self.assertIsNone(registry.manifest_digest("postgres", "16")) class TestFetchRegistryTags(unittest.TestCase): def test_anonymous_tags(self) -> None: with mock.patch.object( - registry.urllib.request, - "urlopen", + registry.OPENER, + "open", return_value=_Resp(body=b'{"tags": ["1.0.0", "1.1.0"]}'), ): self.assertEqual( @@ -159,7 +151,7 @@ class TestFetchRegistryTags(unittest.TestCase): raise _http_error(401, {"WWW-Authenticate": challenge}) return _Resp(body=b'{"tags": ["2.0.0"]}') - with mock.patch.object(registry.urllib.request, "urlopen", side_effect=_fake): + with mock.patch.object(registry.OPENER, "open", side_effect=_fake): self.assertEqual(registry.fetch_registry_tags("ghcr.io/foo/bar"), ["2.0.0"]) def test_a_realm_other_than_https_is_never_opened(self) -> None: @@ -168,8 +160,8 @@ class TestFetchRegistryTags(unittest.TestCase): with ( self.subTest(realm=realm), mock.patch.object( - registry.urllib.request, - "urlopen", + registry.OPENER, + "open", side_effect=_http_error(401, challenge), ) as opened, ): @@ -185,21 +177,19 @@ class TestFetchRegistryTags(unittest.TestCase): body=b'{"tags": ["a"]}', ) page2 = _Resp(body=b'{"tags": ["b"]}') - with mock.patch.object( - registry.urllib.request, "urlopen", side_effect=[page1, page2] - ): + with mock.patch.object(registry.OPENER, "open", side_effect=[page1, page2]): self.assertEqual(registry.fetch_registry_tags("foo"), ["a", "b"]) def test_network_failure_returns_empty(self) -> None: with mock.patch.object( - registry.urllib.request, "urlopen", side_effect=urllib.error.URLError("x") + registry.OPENER, "open", side_effect=urllib.error.URLError("x") ): self.assertEqual(registry.fetch_registry_tags("foo"), []) def test_last_cursor_seeds_query(self) -> None: with mock.patch.object( - registry.urllib.request, - "urlopen", + registry.OPENER, + "open", return_value=_Resp(body=b'{"tags": ["v1.0.0"]}'), ) as opened: self.assertEqual( @@ -211,6 +201,83 @@ class TestFetchRegistryTags(unittest.TestCase): url, "https://registry.gitlab.com/v2/foo/bar/tags/list?n=1000&last=v" ) + def _page(self, link: str) -> tuple[list[str], list[str]]: + pages = [ + (200, _headers({"Link": f'<{link}>; rel="next"'}), b'{"tags": ["a"]}'), + (200, _headers(), b'{"tags": ["b"]}'), + ] + with mock.patch.object(registry, "_request", side_effect=pages) as requested: + tags = registry.fetch_registry_tags("foo") + return tags, [call.args[0] for call in requested.call_args_list] + + def test_a_link_next_on_the_registry_pages(self) -> None: + for link in ("/v2/library/foo/tags/list?last=a", _TAGS_NEXT): + with self.subTest(link=link): + self.assertEqual(self._page(link), (["a", "b"], [_TAGS, _TAGS_NEXT])) + + def test_a_link_next_off_the_registry_stops_paging(self) -> None: + for link in ( + "https://evil.example/v2/library/foo/tags/list?last=a", + "http://registry-1.docker.io/v2/library/foo/tags/list?last=a", + ): + with self.subTest(link=link): + self.assertEqual(self._page(link), (["a"], [_TAGS])) + + +_TAGS = "https://registry-1.docker.io/v2/library/foo/tags/list?n=1000" +_TAGS_NEXT = "https://registry-1.docker.io/v2/library/foo/tags/list?last=a" +_BLOB = "https://registry-1.docker.io/v2/library/foo/blobs/sha256%3Aabc" + + +def _reply(req, status: int, headers=None, body: bytes = b""): + resp = urllib.response.addinfourl( + io.BytesIO(body), _headers(headers), req.full_url, status + ) + resp.msg = "reply" + return resp + + +class TestBlobRedirect(unittest.TestCase): + def _fetch(self, location: str): + seen: list[tuple[str, str | None]] = [] + + def _open(_handler, req): + auth = req.get_header("Authorization") + seen.append((req.full_url, auth)) + if req.full_url != _BLOB: + return _reply(req, 200, body=b'{"os": "linux"}') + if auth is None: + return _reply(req, 401) + return _reply(req, 307, {"Location": location}) + + with ( + mock.patch.object(registry, "_bearer_token", return_value="tok"), + mock.patch.object(urllib.request.HTTPSHandler, "https_open", _open), + mock.patch.object(urllib.request.HTTPHandler, "http_open", _open), + ): + return registry.fetch_blob("foo", "sha256:abc"), seen + + def test_a_cross_host_redirect_drops_the_token(self) -> None: + blob, seen = self._fetch("https://cdn.example/blob") + self.assertEqual(blob, {"os": "linux"}) + self.assertEqual(seen[-1], ("https://cdn.example/blob", None)) + + def test_a_same_host_redirect_keeps_the_token(self) -> None: + target = "https://registry-1.docker.io/v2/library/foo/blobs/sha256%3Adef" + blob, seen = self._fetch(target) + self.assertEqual(blob, {"os": "linux"}) + self.assertEqual(seen[-1], (target, "Bearer tok")) + + def test_a_redirect_off_https_is_refused(self) -> None: + for target in ( + "http://registry-1.docker.io/v2/library/foo/blobs/sha256%3Adef", + "http://cdn.example/blob", + ): + with self.subTest(target=target): + blob, seen = self._fetch(target) + self.assertIsNone(blob) + self.assertEqual([url for url, _auth in seen], [_BLOB, _BLOB]) + _SINGLE = { "config": {"size": 100}, @@ -315,21 +382,17 @@ class TestProbeOrder(_IsolatedProbeCache): class TestFetchManifest(unittest.TestCase): def test_non_dict_body_is_indeterminate(self) -> None: - with mock.patch.object( - registry.urllib.request, "urlopen", return_value=_Resp(body=b"[]") - ): + with mock.patch.object(registry.OPENER, "open", return_value=_Resp(body=b"[]")): self.assertIsNone(registry.fetch_manifest("img", "1")) def test_rate_limited_is_indeterminate(self) -> None: - with mock.patch.object( - registry.urllib.request, "urlopen", side_effect=_http_error(429) - ): + with mock.patch.object(registry.OPENER, "open", side_effect=_http_error(429)): self.assertIsNone(registry.fetch_manifest("img", "1")) def test_present_manifest_is_parsed(self) -> None: with mock.patch.object( - registry.urllib.request, - "urlopen", + registry.OPENER, + "open", return_value=_Resp(body=b'{"layers": []}'), ): self.assertEqual(registry.fetch_manifest("img", "1"), {"layers": []}) diff --git a/utils/docker/redirect.py b/utils/docker/redirect.py new file mode 100644 index 0000000000..0cdc37f35a --- /dev/null +++ b/utils/docker/redirect.py @@ -0,0 +1,19 @@ +from __future__ import annotations + +import urllib.error +import urllib.request +from urllib.parse import urlparse + + +class HttpsRedirectHandler(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + target = urlparse(newurl) + if target.scheme != "https": + raise urllib.error.HTTPError(req.full_url, code, msg, headers, fp) + new = super().redirect_request(req, fp, code, msg, headers, newurl) + if target.netloc != urlparse(req.full_url).netloc: + new.remove_header("Authorization") + return new + + +OPENER = urllib.request.build_opener(HttpsRedirectHandler) diff --git a/utils/docker/registry.py b/utils/docker/registry.py index d13ad0a55e..95b3de1ee3 100644 --- a/utils/docker/registry.py +++ b/utils/docker/registry.py @@ -24,10 +24,11 @@ import tempfile import urllib.error import urllib.request from pathlib import Path -from urllib.parse import quote, urlencode, urlparse +from urllib.parse import quote, urlencode, urljoin, urlparse from utils.docker.image.ref import DOCKER_HUB_REGISTRIES, split_registry_and_name from utils.docker.mirror import mirror_image +from utils.docker.redirect import OPENER _UA = "infinito-nexus-version-updater" _UNKNOWN_PLATFORM = "unknown" @@ -75,7 +76,7 @@ def _bearer_token(challenge: str, repo: str) -> str | None: req = urllib.request.Request( # noqa: S310 - https request to a trusted registry host f"{realm}?{urlencode(query)}", headers={"User-Agent": _UA} ) - with urllib.request.urlopen(req, timeout=15) as resp: # noqa: S310 - https request to a trusted registry host + with OPENER.open(req, timeout=15) as resp: body = json.loads(resp.read().decode()) except ( urllib.error.URLError, @@ -102,7 +103,7 @@ def _request(url: str, repo: str, method: str, accept: str | None): headers["Authorization"] = f"Bearer {token}" req = urllib.request.Request(url, headers=headers, method=method) # noqa: S310 - https request to a trusted registry host try: - with urllib.request.urlopen(req, timeout=15) as resp: # noqa: S310 - https request to a trusted registry host + with OPENER.open(req, timeout=15) as resp: return ( resp.status, resp.headers, @@ -152,12 +153,11 @@ def fetch_registry_tags( match = _LINK_NEXT_RE.search(resp_headers.get("Link", "") or "") if not match: break - nxt = match.group(1) - if nxt.startswith("http"): - url = nxt - else: - parsed = urlparse(url) - url = f"{parsed.scheme}://{parsed.netloc}{nxt}" + nxt = urljoin(url, match.group(1)) + target = urlparse(nxt) + if target.scheme != "https" or target.netloc != urlparse(url).netloc: + break + url = nxt return tags From c58bc2f3d4ad32a0f89a674e4381cc2832b55954 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Fri, 13 Nov 2026 15:50:35 +0000 Subject: [PATCH 22/25] fix(web-app-erpnext): start Redis consumers only on this deploy's configuration MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The readiness gate of backend, both queue workers, websocket and scheduler grepped common_site_config.json for redis_socketio, a key every earlier deploy had already written. After a Redis password rotation the swarm pass-2 tasks therefore started on the previous password before the configurator rewrote the file (run 43288523728, ERPNext#0: rq workers up at 00:26:36-39, configurator done at 00:26:46), and the rotation verify found a consumer still presenting the retired secret. The configurator steps are now one list; their sha256 digest is written last as infinito_configurator_digest under set -e, and every Redis consumer waits for exactly that digest. A rotation changes the digest and so every consumer's command, which recreates them under compose and rolls them under swarm; a failing configurator step now stops before the digest instead of being swallowed. Tests: test_configurator_gate.py renders the template and checks every Redis consumer waits for the digest, the digest covers every step and is written last, and set -e precedes the first step (5 passed, 18 subtests; negative control on main fails). quality-high green on this tree. An independent skeptic compared it with ce45ff36ae on the IAM line (restart on site config revision): redundant for this failure, costlier, conflicting; operator picked keep staged. 🎯 Fix: 90 % 💥 Break: 4 % 💸 Cost: – ⏱️ Time: – 🛡️ Security: 100 % 🏆 Score: 86 🚦 Gate: ✅ 90/5, cost and time <= 100, security 100 % Co-Authored-By: Claude Opus 5.5 --- .../web-app-erpnext/templates/compose.yml.j2 | 26 ++-- .../web-app-erpnext/test_configurator_gate.py | 124 ++++++++++++++++++ 2 files changed, 141 insertions(+), 9 deletions(-) create mode 100644 tests/unit/python/roles/web-app-erpnext/test_configurator_gate.py diff --git a/roles/web-app-erpnext/templates/compose.yml.j2 b/roles/web-app-erpnext/templates/compose.yml.j2 index 2015935cac..5e9530c30b 100644 --- a/roles/web-app-erpnext/templates/compose.yml.j2 +++ b/roles/web-app-erpnext/templates/compose.yml.j2 @@ -1,5 +1,16 @@ {% include 'roles/sys-svc-compose/templates/base.yml.j2' %} -{% set ERPNEXT_CONFIG_READY_GATE = "until grep -q redis_socketio sites/common_site_config.json 2>/dev/null; do sleep 2; done;" %} +{% set ERPNEXT_CONFIGURATOR_STEPS = [ + 'ls -1 apps > sites/apps.txt', + 'bench set-config -g db_host "' ~ ERPNEXT_DB_HOST ~ '"', + 'bench set-config -gp db_port ' ~ ERPNEXT_DB_PORT, + 'bench set-config -g redis_cache "' ~ ERPNEXT_REDIS_URL ~ '/0"', + 'bench set-config -g redis_queue "' ~ ERPNEXT_REDIS_URL ~ '/1"', + 'bench set-config -g redis_socketio "' ~ ERPNEXT_REDIS_URL ~ '/2"', + 'bench set-config -gp socketio_port ' ~ ERPNEXT_WEBSOCKET_PORT, + 'bench set-config -g host_name "' ~ lookup('tls', application_id, 'url.origin') ~ '"', + ] %} +{% set ERPNEXT_CONFIGURATOR_DIGEST = ERPNEXT_CONFIGURATOR_STEPS | join(';') | hash('sha256') %} +{% set ERPNEXT_CONFIG_READY_GATE = "until grep -q " ~ ERPNEXT_CONFIGURATOR_DIGEST ~ " sites/common_site_config.json 2>/dev/null; do sleep 2; done;" %} {% set ERPNEXT_BACKEND_READY_GATE = "until (exec 3<>/dev/tcp/backend/" ~ ERPNEXT_BACKEND_PORT ~ ") 2>/dev/null; do sleep 2; done;" %} {% set service_name = 'backend' %} @@ -82,14 +93,11 @@ - -c command: - > - ls -1 apps > sites/apps.txt; - bench set-config -g db_host "{{ ERPNEXT_DB_HOST }}"; - bench set-config -gp db_port {{ ERPNEXT_DB_PORT }}; - bench set-config -g redis_cache "{{ ERPNEXT_REDIS_URL }}/0"; - bench set-config -g redis_queue "{{ ERPNEXT_REDIS_URL }}/1"; - bench set-config -g redis_socketio "{{ ERPNEXT_REDIS_URL }}/2"; - bench set-config -gp socketio_port {{ ERPNEXT_WEBSOCKET_PORT }}; - bench set-config -g host_name "{{ lookup('tls', application_id, 'url.origin') }}"; + set -e; + {% for step in ERPNEXT_CONFIGURATOR_STEPS %} + {{ step }}; + {% endfor %} + bench set-config -g infinito_configurator_digest "{{ ERPNEXT_CONFIGURATOR_DIGEST }}"; {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_depends_on', application_id) | indent(4) }} {{ lookup('container_extra_hosts') | indent(4) }} diff --git a/tests/unit/python/roles/web-app-erpnext/test_configurator_gate.py b/tests/unit/python/roles/web-app-erpnext/test_configurator_gate.py new file mode 100644 index 0000000000..5294ba0985 --- /dev/null +++ b/tests/unit/python/roles/web-app-erpnext/test_configurator_gate.py @@ -0,0 +1,124 @@ +from __future__ import annotations + +import hashlib +import re +import unittest + +from jinja2 import ( + ChainableUndefined, + ChoiceLoader, + DictLoader, + Environment, + FileSystemLoader, + select_autoescape, +) + +from utils.cache.files import PROJECT_ROOT +from utils.roles.mapping import ROLE_FILE_TEMPL_COMPOSE + +TEMPLATE = f"roles/web-app-erpnext/{ROLE_FILE_TEMPL_COMPOSE}" +REDIS_CONSUMERS = ("backend", "queue-short", "queue-long", "websocket", "scheduler") +REPLACED_URL = "redis://default:replaced-secret@redis:6379" +ROTATED_URL = "redis://default:rotated-secret@redis:6379" +DIGEST_WRITE = re.compile( + r'bench set-config -g infinito_configurator_digest "([0-9a-f]{64})";' +) + + +class _Marker(ChainableUndefined): + def __str__(self): + return f"<{self._undefined_name}>" + + __repr__ = __str__ + + +def _render(redis_url: str) -> str: + env = Environment( + loader=ChoiceLoader( + [ + DictLoader( + { + "roles/sys-svc-compose/templates/base.yml.j2": "services:\n", + "roles/sys-svc-container/templates/base.yml.j2": " \n", + } + ), + FileSystemLoader(str(PROJECT_ROOT)), + ] + ), + trim_blocks=True, + lstrip_blocks=True, + keep_trailing_newline=True, + undefined=_Marker, + autoescape=select_autoescape(default_for_string=False), + ) + env.filters["hash"] = lambda value, algorithm: hashlib.new( + algorithm, str(value).encode() + ).hexdigest() + env.globals["lookup"] = lambda name, *args, **kwargs: f"" + return env.get_template(TEMPLATE).render( + application_id="web-app-erpnext", + ERPNEXT_REDIS_URL=redis_url, + ERPNEXT_DB_HOST="mariadb", + ERPNEXT_DB_PORT=3306, + ERPNEXT_BACKEND_PORT=8000, + ERPNEXT_WEBSOCKET_PORT=9000, + ERPNEXT_SITES_DIR="/home/frappe/frappe-bench/sites", + ) + + +def _block(rendered: str, service: str) -> str: + lines = rendered.splitlines() + start = lines.index(f" {service}:") + end = next( + ( + index + for index in range(start + 1, len(lines)) + if lines[index].strip() and not lines[index].startswith(" ") + ), + len(lines), + ) + return "\n".join(lines[start:end]) + + +class TestConfiguratorGate(unittest.TestCase): + def test_the_configurator_writes_its_digest_after_every_redis_url(self): + command = _block(_render(ROTATED_URL), "configurator") + digest_write = DIGEST_WRITE.search(command) + self.assertIsNotNone(digest_write, command) + for key in ("redis_cache", "redis_queue", "redis_socketio"): + with self.subTest(key=key): + self.assertLess( + command.index(f"set-config -g {key} "), digest_write.start() + ) + + def test_a_failed_step_stops_the_configurator_before_the_digest(self): + command = _block(_render(ROTATED_URL), "configurator") + digest_write = DIGEST_WRITE.search(command) + self.assertIsNotNone(digest_write, command) + self.assertLess(command.index("set -e;"), command.index("ls -1 apps")) + + def test_every_redis_consumer_waits_for_the_digest_of_the_current_config(self): + rendered = _render(ROTATED_URL) + digest_write = DIGEST_WRITE.search(_block(rendered, "configurator")) + self.assertIsNotNone(digest_write) + gate = f"until grep -q {digest_write.group(1)} sites/common_site_config.json" + for service in REDIS_CONSUMERS: + with self.subTest(service=service): + self.assertIn(gate, _block(rendered, service)) + + def test_a_rotated_redis_password_changes_every_consumer_spec(self): + replaced = _render(REPLACED_URL) + rotated = _render(ROTATED_URL) + for service in REDIS_CONSUMERS: + with self.subTest(service=service): + self.assertNotEqual(_block(replaced, service), _block(rotated, service)) + + def test_no_redis_consumer_spec_carries_the_password(self): + rendered = _render(ROTATED_URL) + for service in REDIS_CONSUMERS: + with self.subTest(service=service): + self.assertNotIn("rotated-secret", _block(rendered, service)) + + +if __name__ == "__main__": + unittest.main() From 5d912e1edaeb2657663d1f4d674ab0c5ffd65dce Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Fri, 13 Nov 2026 16:52:35 +0000 Subject: [PATCH 23/25] fix(worktree): pick only slots whose subnets are free, up to 254 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit worktree_next_slot skipped only slots pinned in a worktree's custom.env, so it handed out slot 255 (an invalid 172.30.255.0/24 bind range) once the low slots were taken, and it reused a slot whose 172.30..0/24 or 10.160..0/24 subnet a stack without a checkout still held. It now also skips slots whose subnets a docker network uses, and up.sh refuses to pin past WORKTREE_MAX_SLOT=254 instead of writing an invalid slot. 🎯 Fix: 92 % 💥 Break: 3 % 💸 Cost: – ⏱️ Time: – 🛡️ Security: 100 % 🏆 Score: 89 🚦 Gate: ✅ 90/5, cost and time <= 100, security 100 % Co-Authored-By: Claude Opus 5.5 --- scripts/system/worktree/lib.sh | 45 +++++++-- scripts/system/worktree/up.sh | 5 +- .../env/test_worktree_swarm_lab_subnet.py | 7 +- .../scripts/system/worktree/test_lib.py | 99 ++++++++++++++++++- 4 files changed, 143 insertions(+), 13 deletions(-) diff --git a/scripts/system/worktree/lib.sh b/scripts/system/worktree/lib.sh index 65ea51167f..2878a6bd14 100755 --- a/scripts/system/worktree/lib.sh +++ b/scripts/system/worktree/lib.sh @@ -57,15 +57,48 @@ worktree_slot_of() { printf '%s' "${slot}" } +WORKTREE_MAX_SLOT=254 +WORKTREE_NET_PREFIX=172.30 +WORKTREE_LAB_PREFIX=10.160 + +worktree_used_subnets() { + local -a ids=() + command -v docker >/dev/null 2>&1 || return 0 + mapfile -t ids < <(docker network ls -q 2>/dev/null) + [ "${#ids[@]}" -gt 0 ] || return 0 + docker network inspect "${ids[@]}" \ + --format '{{range .IPAM.Config}}{{.Subnet}}{{"\n"}}{{end}}' 2>/dev/null || return 0 +} + +# Param slot: the candidate slot. +# Param subnets: newline-separated subnets docker networks already hold. +# Returns: 0 when a network holds the slot's compose or swarm lab subnet. +worktree_slot_taken() { + local subnet + while read -r subnet; do + case "${subnet}" in + "${WORKTREE_NET_PREFIX}.$1."* | "${WORKTREE_LAB_PREFIX}.$1."*) return 0 ;; + esac + done <<<"$2" + return 1 +} + worktree_next_slot() { - local max=0 path slot + local used=" " path slot subnets while read -r path; do - slot="$(worktree_slot_of "${path}")" - if [ "${slot}" -gt "${max}" ]; then - max="${slot}" - fi + used+="$(worktree_slot_of "${path}") " done < <(git worktree list --porcelain | awk '/^worktree /{print $2}') - printf '%s' "$((max + 1))" + subnets="$(worktree_used_subnets)" + for ((slot = 1; slot <= WORKTREE_MAX_SLOT; slot++)); do + case "${used}" in + *" ${slot} "*) continue ;; + esac + if ! worktree_slot_taken "${slot}" "${subnets}"; then + printf '%s' "${slot}" + return 0 + fi + done + printf '%s' "$((WORKTREE_MAX_SLOT + 1))" } worktree_meta_dir() { diff --git a/scripts/system/worktree/up.sh b/scripts/system/worktree/up.sh index e11ac134d7..11d953d599 100755 --- a/scripts/system/worktree/up.sh +++ b/scripts/system/worktree/up.sh @@ -18,7 +18,6 @@ source "${SCRIPT_DIR}/lib.sh" branch="${1:?branch name required}" base="${2:-}" -max_slot=255 cd "${REPO_ROOT}" @@ -38,8 +37,8 @@ if [ -e "${path}" ]; then fi slot="$(worktree_next_slot)" -if [ "${slot}" -gt "${max_slot}" ]; then - echo "FAILURE: no free slot left (max ${max_slot}); tear down an existing worktree" >&2 +if [ "${slot}" -gt "${WORKTREE_MAX_SLOT}" ]; then + echo "FAILURE: no free slot left (max ${WORKTREE_MAX_SLOT}); tear down an existing worktree" >&2 exit 1 fi diff --git a/tests/lint/filesystem/env/test_worktree_swarm_lab_subnet.py b/tests/lint/filesystem/env/test_worktree_swarm_lab_subnet.py index 7395b5f012..4b86c55908 100644 --- a/tests/lint/filesystem/env/test_worktree_swarm_lab_subnet.py +++ b/tests/lint/filesystem/env/test_worktree_swarm_lab_subnet.py @@ -20,8 +20,9 @@ from utils.env.parser import parse_static_env from . import PROJECT_ROOT _UP_SH = PROJECT_ROOT / "scripts/system/worktree/up.sh" +_LIB_SH = PROJECT_ROOT / "scripts/system/worktree/lib.sh" _NETWORKS = PROJECT_ROOT / "group_vars/all/08_networks.yml" -_MAX_SLOT_RE = re.compile(r"^max_slot=(?P\d+)$", re.MULTILINE) +_MAX_SLOT_RE = re.compile(r"^WORKTREE_MAX_SLOT=(?P\d+)$", re.MULTILINE) _LAB_PREFIX_RE = re.compile(r'^lab_prefix="(?P