diff --git a/package-lock.json b/package-lock.json index ac4155e375..b36c9388e2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -413,6 +413,13 @@ "url": "https://github.com/sponsors/nzakas" } }, + "node_modules/@isaacs/nonrecursive-glob-match": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.0.3.tgz", + "integrity": "sha512-SI7kyKHq4XXDRozw+r9GlRZkia1ZkFrpLW98r2IC2Bpr8YkFGE3fvjzmxCG0x78A++69HmDNrDvSMYBZmHGpKA==", + "dev": true, + "license": "BlueOak-1.0.0" + }, "node_modules/@keyv/bigmap": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/@keyv/bigmap/-/bigmap-1.3.1.tgz", @@ -1140,16 +1147,17 @@ "license": "CC0-1.0" }, "node_modules/minimatch": { - "version": "10.2.6", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", - "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "version": "11.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.4.tgz", + "integrity": "sha512-/UJ1dEoVQTjPNDh6SGlUo+ueLMmoHTas4q+8yaAR/5t6nLAIiBDJtoYUh20IYleix7ehiQkgczb84PE3uzHkxg==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { - "brace-expansion": "^5.0.8" + "@isaacs/nonrecursive-glob-match": "^1.0.3", + "brace-expansion": "^5.0.12" }, "engines": { - "node": "18 || 20 || >=22" + "node": "20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" diff --git a/package.json b/package.json index 5e9a21a71b..f833ac10ac 100644 --- a/package.json +++ b/package.json @@ -17,6 +17,7 @@ "stylelint": "^18.0.0" }, "overrides": { - "brace-expansion": "^5.0.12" + "brace-expansion": "^5.0.12", + "minimatch": "^11.0.1" } } diff --git a/roles/web-app-hugo/files/playwright/test-design.js b/roles/web-app-hugo/files/playwright/test-design.js index 0d1a9c8860..9b9eb131a3 100644 --- a/roles/web-app-hugo/files/playwright/test-design.js +++ b/roles/web-app-hugo/files/playwright/test-design.js @@ -118,9 +118,17 @@ async function freshSettings(page) { async function stubSearch(page) { await page.addInitScript((rows) => { const original = window.fetch.bind(window); + const isAlgolia = (url) => { + try { + const { hostname } = new URL(url); + return hostname === "algolia.net" || hostname.endsWith(".algolia.net"); + } catch { + return false; + } + }; window.fetch = (input, init) => { const url = typeof input === "string" ? input : input.url; - if (!/algolia\.net\//.test(url)) return original(input, init); + if (!isAlgolia(url)) return original(input, init); const hits = rows.map(([lvl0, lvl1, lvl2, lvl3, path], index) => ({ objectID: `fixture-${index}`, url: path, diff --git a/roles/web-app-litellm/files/playwright/test-design.js b/roles/web-app-litellm/files/playwright/test-design.js index 2c03f8a4e2..7f5b7bcc7a 100644 --- a/roles/web-app-litellm/files/playwright/test-design.js +++ b/roles/web-app-litellm/files/playwright/test-design.js @@ -9,7 +9,7 @@ const { galleryEnabled, tokenValue, } = require("./design"); -const { apiFetchOnion, apiGetOnion, decodeDotenvQuotedValue, gotoOnion } = require("./personas"); +const { apiFetchOnion, apiGetOnion, decodeDotenvQuotedValue, escapeRegex, gotoOnion } = require("./personas"); const { skipUnlessServiceEnabled } = require("./service-gating"); const { resolveTimeout } = require("./timeouts"); @@ -335,7 +335,7 @@ exports.register = function (shared) { await page.emulateMedia({ colorScheme: mode }); await gotoOnion(page, `${base}/ui/?page=new_usage`); await ready(page); - const outline = (await tokenValue(page, "--design-border", "color")).replace(/[()]/g, "\\$&"); + const outline = escapeRegex(await tokenValue(page, "--design-border", "color")); await expect( page.locator(CARD).first(), `card ${mode}: the outline ring must take --design-border`, diff --git a/roles/web-app-shopware/files/playwright/test-design.js b/roles/web-app-shopware/files/playwright/test-design.js index ec2aa35729..ce51388113 100644 --- a/roles/web-app-shopware/files/playwright/test-design.js +++ b/roles/web-app-shopware/files/playwright/test-design.js @@ -41,7 +41,7 @@ const SHOWCASE = { { id: "d0000000000000000000000000000013", number: "DESIGN-3", name: "Design showcase table", gross: 476 }, ], customerEmail: `design-showcase@${canonicalDomain}`, - customerPassword: crypto.createHash("sha256").update(`design-showcase:${adminPassword}`).digest("hex"), + customerPassword: crypto.randomBytes(32).toString("hex"), }; const THEME_FIELDS = [ ["sw-color-brand-primary", "--design-primary"], diff --git a/roles/web-app-wordpress/files/playwright/test-design.js b/roles/web-app-wordpress/files/playwright/test-design.js index 007bd6ede1..c64e680ade 100644 --- a/roles/web-app-wordpress/files/playwright/test-design.js +++ b/roles/web-app-wordpress/files/playwright/test-design.js @@ -9,7 +9,7 @@ const { galleryEnabled, tokenValue, } = require("./design"); -const { apiFetchOnion, apiGetOnion, decodeDotenvQuotedValue, gotoOnion, requireDotenvValue } = require("./personas"); +const { apiFetchOnion, apiGetOnion, decodeDotenvQuotedValue, escapeRegex, gotoOnion, requireDotenvValue } = require("./personas"); const { isServiceEnabled, skipUnlessServiceEnabled } = require("./service-gating"); const { resolveTimeout } = require("./timeouts"); @@ -150,7 +150,7 @@ exports.register = function (shared) { await expect(page.locator("body"), "the account is on the corporate admin color scheme").toHaveClass(new RegExp(`admin-color-${SCHEME}`)); await expect(page.locator("#colors-css"), "the color scheme loads its stylesheet from WordPress").toHaveAttribute( "href", - new RegExp(SCHEME_SHEET.replace(/[.]/g, "\\.")), + new RegExp(escapeRegex(SCHEME_SHEET)), ); for (const sheet of LATE_SHEETS) { await expect(page.locator(`head link[href*='${sheet}']`), `the scheme links ${sheet} at the end of the head`).toHaveCount(1); diff --git a/tests/lint/docker/dockerfile/test_pip_no_version_pins.py b/tests/lint/docker/dockerfile/test_pip_no_version_pins.py index 2e49bf8e37..813f60341d 100644 --- a/tests/lint/docker/dockerfile/test_pip_no_version_pins.py +++ b/tests/lint/docker/dockerfile/test_pip_no_version_pins.py @@ -28,6 +28,7 @@ from __future__ import annotations import re import tempfile +import time import unittest from pathlib import Path from typing import ClassVar @@ -45,7 +46,7 @@ _ROLES_ROOT = _REPO_ROOT / "roles" _J2_CTRL_RE = re.compile(r"\{%-?.*?-?%\}") _COMMENT_RE = re.compile(r"^\s*#") _SEPARATOR_RE = re.compile(r"&&|\|\||;|\|") -_PIP_INSTALL_RE = re.compile(r"\bpip3?(?:\s+--?[\w.=/-]+)*\s+install\b") +_PIP_INSTALL_RE = re.compile(r"\bpip3?(?:\s+-[\w.=/-]+)*\s+install\b") _PIN_RE = re.compile( r"(?[A-Za-z0-9][A-Za-z0-9._-]*)" r"(?P\[[A-Za-z0-9,._-]+\])?==" @@ -187,6 +188,17 @@ class TestPinnedInstallsDetector(unittest.TestCase): with self.subTest(name): self.assertEqual([], self._scan(body), f"{name!r} must not fire") + def test_an_option_run_without_install_is_scanned_in_linear_time(self) -> None: + started = time.monotonic() + self.assertEqual([], self._scan("RUN pip" + " --a" * 26 + " x\n")) + self.assertLess( + time.monotonic() - started, + 1.0, + "every option before `install` must match exactly one way; an " + "option prefix that overlaps the option character class backtracks " + "exponentially and needs tens of seconds for this line", + ) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/javascript/roles/web-app-shopware/files/playwright/test-design.test.js b/tests/unit/javascript/roles/web-app-shopware/files/playwright/test-design.test.js new file mode 100644 index 0000000000..559d78a9ad --- /dev/null +++ b/tests/unit/javascript/roles/web-app-shopware/files/playwright/test-design.test.js @@ -0,0 +1,72 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const crypto = require("node:crypto"); +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://shop.example"; +const DOTENV = { + APP_BASE_URL: BASE, + ADMIN_USERNAME: "administrator", + ADMIN_PASSWORD: "administrator-secret", + CANONICAL_DOMAIN: "shop.example", +}; +const RESPONSES = { + "/api/oauth/token": { access_token: "token" }, + "/api/search/sales-channel": { data: [{ id: "channel", domains: [{ url: BASE }] }] }, + "/api/search/tax": { data: [{ id: "tax", taxRate: 19 }] }, + "/api/search/theme": { data: [{ id: "theme" }] }, + "/api/search/salutation": { data: [{ id: "salutation" }] }, + "/api/_action/sync": {}, +}; +const passes = new Proxy( + {}, + { + get: (_, matcher) => { + if (matcher === "then") return undefined; + return matcher === "not" ? passes : async () => undefined; + }, + }, +); + +const synced = []; +const { seedShowcase, signInCustomer } = loadInternals( + path.join(PROJECT_ROOT, "roles/web-app-shopware/files/playwright/test-design.js"), + ["seedShowcase", "signInCustomer"], + { + "node:crypto": { ...crypto, randomBytes: (size) => Buffer.alloc(size, 0x5a) }, + "@playwright/test": { test: () => undefined, expect: () => passes }, + "./personas": { + apiFetchOnion: async (_request, url, options) => { + const route = url.slice(BASE.length); + if (route === "/api/_action/sync") synced.push(options.data); + return { status: () => 200, json: async () => RESPONSES[route] }; + }, + decodeDotenvQuotedValue: (value) => value, + gotoOnion: async () => undefined, + normalizeBaseUrl: (value) => value, + requireDotenvValue: (_value, name) => DOTENV[name], + }, + "./timeouts": { resolveTimeout: (ms) => ms }, + }, + {}, +); + +test("the showcase customer signs in with a password drawn from node:crypto, not derived from the administrator's", async () => { + await seedShowcase({}); + const filled = {}; + const locator = (selector) => ({ + fill: async (value) => { + filled[selector] = value; + }, + locator, + press: async () => undefined, + }); + await signInCustomer({ locator }); + + const seeded = synced[0]["design-showcase-customer"].payload[0].password; + assert.match(seeded, /^(?:5a){16,}$/); + assert.equal(filled["input[name='password']"], seeded); +}); diff --git a/tests/unit/python/plugins/lookup/test_email.py b/tests/unit/python/plugins/lookup/test_email.py index 9845c2998d..a1191449af 100644 --- a/tests/unit/python/plugins/lookup/test_email.py +++ b/tests/unit/python/plugins/lookup/test_email.py @@ -807,6 +807,13 @@ class _RawGetHostvars(dict): super().__init__(templated) self._raw = raw + def __eq__(self, other: object) -> bool: + return ( + isinstance(other, _RawGetHostvars) + and dict.__eq__(self, other) + and self._raw == other._raw + ) + def raw_get(self, host: str) -> dict: return self._raw[host] diff --git a/tests/unit/python/plugins/lookup/test_requires_python.py b/tests/unit/python/plugins/lookup/test_requires_python.py index 478e8be4b7..c09d9ed996 100644 --- a/tests/unit/python/plugins/lookup/test_requires_python.py +++ b/tests/unit/python/plugins/lookup/test_requires_python.py @@ -2,8 +2,8 @@ from __future__ import annotations import tempfile import unittest +import unittest.mock from pathlib import Path -from unittest import mock from ansible.errors import AnsibleError @@ -17,7 +17,7 @@ class TestRequiresPythonLookup(unittest.TestCase): '[project]\nname = "demo"\nrequires-python = ">=3.12,<3.14"\n', encoding="utf-8", ) - with mock.patch.object(plugin, "PROJECT_ROOT", Path(tmp)): + with unittest.mock.patch.object(plugin, "PROJECT_ROOT", Path(tmp)): self.assertEqual(plugin.LookupModule().run([]), [">=3.12,<3.14"]) def test_the_lookup_takes_no_terms(self) -> None: diff --git a/tests/unit/python/plugins/lookup/test_resource.py b/tests/unit/python/plugins/lookup/test_resource.py index 0a9ef0b64f..1110ad204f 100644 --- a/tests/unit/python/plugins/lookup/test_resource.py +++ b/tests/unit/python/plugins/lookup/test_resource.py @@ -200,6 +200,13 @@ class TestResourceApplicationsAccess(unittest.TestCase): self.read = True return super().get(key, default) + def __eq__(self, other: object) -> bool: + return ( + isinstance(other, type(self)) + and dict.__eq__(self, other) + and self.read == other.read + ) + def _scope(self): scope = self._Tripwire() scope.update(_vars()) diff --git a/tests/unit/python/roles/test-e2e-playwright/files/test_run_parallel.py b/tests/unit/python/roles/test-e2e-playwright/files/test_run_parallel.py index 08f9aa6379..3193422b52 100644 --- a/tests/unit/python/roles/test-e2e-playwright/files/test_run_parallel.py +++ b/tests/unit/python/roles/test-e2e-playwright/files/test_run_parallel.py @@ -518,7 +518,7 @@ class TestRun(unittest.TestCase): def test_an_onion_job_waits_while_tor_is_being_recreated(self): self._job(0, "onion", 0.1, tor=True) self._job(1, "clear", 0.1) - writer = os.open(self.tor_lock, os.O_RDWR | os.O_CREAT, 0o644) + writer = os.open(self.tor_lock, os.O_RDWR | os.O_CREAT, 0o600) fcntl.flock(writer, fcntl.LOCK_EX) (self.jobs / rp.SEALED).touch() runner = threading.Thread(target=self._run, args=(2,)) @@ -722,7 +722,7 @@ class TestTorRecreateWaitsForOnionRuns(unittest.TestCase): the exit code, stderr, and whether the pending marker existed while the script waited. """ - reader = os.open(self.lock, os.O_RDONLY | os.O_CREAT, 0o644) + reader = os.open(self.lock, os.O_RDONLY | os.O_CREAT, 0o600) fcntl.flock(reader, fcntl.LOCK_SH) proc = self.start(script, str(self.lock)) began = time.monotonic() diff --git a/tests/unit/python/roles/web-app-funkwhale/files/same_origin/test_urls.py b/tests/unit/python/roles/web-app-funkwhale/files/same_origin/test_urls.py index 952293b096..7a5bfd4648 100644 --- a/tests/unit/python/roles/web-app-funkwhale/files/same_origin/test_urls.py +++ b/tests/unit/python/roles/web-app-funkwhale/files/same_origin/test_urls.py @@ -34,6 +34,13 @@ class _HttpResponse(dict): super().__init__() self.content_type = content_type + def __eq__(self, other: object) -> bool: + return ( + isinstance(other, _HttpResponse) + and dict.__eq__(self, other) + and self.content_type == other.content_type + ) + def funkwhale_get_file_path(audio_file) -> bytes: """ diff --git a/tests/unit/python/roles/web-app-funkwhale/files/test_design_preferences.py b/tests/unit/python/roles/web-app-funkwhale/files/test_design_preferences.py index e8d837d503..2329adfd24 100644 --- a/tests/unit/python/roles/web-app-funkwhale/files/test_design_preferences.py +++ b/tests/unit/python/roles/web-app-funkwhale/files/test_design_preferences.py @@ -38,6 +38,13 @@ class _Manager(dict): self.writes.append(key) super().__setitem__(key, value) + def __eq__(self, other: object) -> bool: + return ( + isinstance(other, _Manager) + and dict.__eq__(self, other) + and self.writes == other.writes + ) + def _fake_modules(manager: _Manager) -> dict[str, ModuleType]: registries = ModuleType("dynamic_preferences.registries") diff --git a/tests/unit/python/utils/docker/test_registry.py b/tests/unit/python/utils/docker/test_registry.py index c08b842f98..c83bf70b5b 100644 --- a/tests/unit/python/utils/docker/test_registry.py +++ b/tests/unit/python/utils/docker/test_registry.py @@ -198,6 +198,23 @@ class TestFetchRegistryTags(unittest.TestCase): with mock.patch.object(registry.urllib.request, "urlopen", 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: + for realm in ("file:///tmp/token.json", "http://169.254.169.254/token"): + challenge = {"WWW-Authenticate": f'Bearer realm="{realm}",service="reg"'} + with ( + self.subTest(realm=realm), + mock.patch.object( + registry.urllib.request, + "urlopen", + side_effect=_http_error(401, challenge), + ) as opened, + ): + self.assertEqual(registry.fetch_registry_tags("ghcr.io/foo/bar"), []) + self.assertEqual( + [call.args[0].full_url for call in opened.call_args_list], + ["https://ghcr.io/v2/foo/bar/tags/list?n=1000"], + ) + def test_pagination_follows_link(self) -> None: page1 = _Resp( headers={"Link": '; rel="next"'}, diff --git a/tests/unit/python/utils/inventory/test_tools_render.py b/tests/unit/python/utils/inventory/test_tools_render.py new file mode 100644 index 0000000000..0c3ac9dd19 --- /dev/null +++ b/tests/unit/python/utils/inventory/test_tools_render.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +from utils.cache.files import read_text +from utils.inventory import tools + +MARKUP = "/models/\"" +TEMPLATE = ( + 'models: "[[ models_dir ]]"\n' + "languages: [[ load_only | join(',') ]]\n" + "key: [[ s1_api_key ]]\n" + "[% raw %]{{ ansible_expression }}[% endraw %]\n" +) + + +class TestRender(unittest.TestCase): + def test_the_yaml_lane_renders_without_html_escaping(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + template = root / tools.TEMPLATE + template.parent.mkdir(parents=True) + template.write_text(TEMPLATE, encoding="utf-8") + with patch.object(tools, "models_dir", return_value=MARKUP): + rendered = read_text(str(tools.render(root, ["en", "de"]))) + self.assertIn(f'models: "{MARKUP}"', rendered) + self.assertIn("languages: de,en", rendered) + self.assertIn(f"key: {tools.API_KEY}", rendered) + self.assertIn("{{ ansible_expression }}", rendered) + self.assertNotIn("<", rendered) + self.assertNotIn("&", rendered) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/update/test_source.py b/tests/unit/python/utils/update/test_source.py index 8d74851e5d..f5ba65c76a 100644 --- a/tests/unit/python/utils/update/test_source.py +++ b/tests/unit/python/utils/update/test_source.py @@ -1,8 +1,11 @@ from __future__ import annotations +import io import tempfile import unittest import unittest.mock as mock +import urllib.error +from email.message import Message from pathlib import Path from utils.roles.mapping import ROLE_DIR_META_ADDONS, ROLE_FILE_META_SERVICES @@ -150,6 +153,25 @@ class TestCandidates(unittest.TestCase): self.assertEqual(module.candidates(entry, root), ["2.1.0"]) +class TestRegistryV2Tags(unittest.TestCase): + def test_a_realm_other_than_https_is_never_read(self) -> None: + for realm in ("file:///tmp/token.json", "http://169.254.169.254/token"): + headers = Message() + headers["WWW-Authenticate"] = f'Bearer realm="{realm}",service="reg"' + denied = urllib.error.HTTPError( + "https://reg.example/v2", 401, "err", headers, io.BytesIO(b"") + ) + with ( + self.subTest(realm=realm), + mock.patch.object(module, "get", side_effect=denied) as get, + ): + self.assertEqual(module.registry_v2_tags("reg.example/foo/bar"), []) + self.assertEqual( + [call.args[0] for call in get.call_args_list], + ["https://reg.example/v2/foo/bar/tags/list"], + ) + + class TestOutdated(unittest.TestCase): def _entry(self, root: Path): return next(e for e in module.collect_entries(root) if e.key == "app_version") diff --git a/utils/docker/registry.py b/utils/docker/registry.py index 253241c983..c3ad9fce80 100644 --- a/utils/docker/registry.py +++ b/utils/docker/registry.py @@ -67,7 +67,7 @@ def _resolve(image: str) -> tuple[str, str] | None: def _bearer_token(challenge: str, repo: str) -> str | None: params = dict(_CHALLENGE_PARAM_RE.findall(challenge or "")) realm = params.get("realm") - if not realm: + if not realm or urlparse(realm).scheme != "https": return None query = {"scope": params.get("scope") or f"repository:{repo}:pull"} if params.get("service"): diff --git a/utils/inventory/tools.py b/utils/inventory/tools.py index 01d3962ef1..ea07e6f0c1 100644 --- a/utils/inventory/tools.py +++ b/utils/inventory/tools.py @@ -46,7 +46,7 @@ import os import subprocess from pathlib import Path -from jinja2 import Environment, FileSystemLoader, StrictUndefined +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape from utils.cache.yaml import load_yaml from utils.roles.mapping import ROLE_FILE_META_SERVICES @@ -357,7 +357,7 @@ def render(root: Path, load_only: list[str]) -> Path: variable_end_string="]]", block_start_string="[%", block_end_string="%]", - autoescape=False, # noqa: S701 - YAML output, HTML escaping would corrupt it + autoescape=select_autoescape(default_for_string=False), ) body = env.get_template(template_path.name).render( load_only=sorted(load_only), diff --git a/utils/update/source.py b/utils/update/source.py index b99926aab8..c8eabb8949 100644 --- a/utils/update/source.py +++ b/utils/update/source.py @@ -35,7 +35,7 @@ import subprocess import urllib.error from dataclasses import dataclass from typing import TYPE_CHECKING, Any -from urllib.parse import urlencode +from urllib.parse import urlencode, urlparse from utils.annotations.suppress import is_suppressed_at from utils.cache.files import read_text @@ -156,7 +156,7 @@ def registry_v2_tags(image: str, match: str = "") -> list[str]: return [] fields = dict(re.findall(r'(\w+)="([^"]*)"', challenge)) realm = fields.pop("realm", "") - if not realm: + if not realm or urlparse(realm).scheme != "https": return [] query = "&".join(f"{name}={value}" for name, value in fields.items()) try: