diff --git a/.claude/.gitignore b/.claude/.gitignore new file mode 100644 index 0000000000..5f7c701958 --- /dev/null +++ b/.claude/.gitignore @@ -0,0 +1,3 @@ +launch.json +routines +workflows diff --git a/.github/workflows/cleanup-stale.yml b/.github/workflows/cleanup-stale.yml index f70268a104..865d4ac29d 100644 --- a/.github/workflows/cleanup-stale.yml +++ b/.github/workflows/cleanup-stale.yml @@ -50,7 +50,7 @@ jobs: steps: - name: 🌿 Delete branches inactive for 360 days - uses: crs-k/stale-branches@v9.0.1 + uses: crs-k/stale-branches@e876b957ab08f0bad43c8cc271a22cdd7604bd09 # v9.0.1 with: repo-token: ${{ secrets.GITHUB_TOKEN }} days-before-stale: 350 diff --git a/cli/administration/deploy/development/build.py b/cli/administration/deploy/development/build.py index f687b362d9..3ec0913d0c 100644 --- a/cli/administration/deploy/development/build.py +++ b/cli/administration/deploy/development/build.py @@ -5,7 +5,7 @@ import subprocess from typing import TYPE_CHECKING from . import PROJECT_ROOT -from .common import resolve_distro +from .env import resolve_distro if TYPE_CHECKING: import argparse diff --git a/cli/administration/deploy/development/common.py b/cli/administration/deploy/development/common.py index 25b03a46e4..6271e88d6f 100644 --- a/cli/administration/deploy/development/common.py +++ b/cli/administration/deploy/development/common.py @@ -5,6 +5,7 @@ from typing import TYPE_CHECKING from . import PROJECT_ROOT from .deps import apps_with_deps, resolve_run_after +from .env import resolve_distro if TYPE_CHECKING: from .compose import Compose @@ -17,36 +18,6 @@ DEV_INVENTORY_VARS_FILE: str = ( ) -VALID_DISTROS: tuple[str, ...] = ("arch", "debian", "ubuntu", "fedora", "centos") - - -def compose_file_args() -> list[str]: - """Compose `-f` flags shared by up and down flows.""" - from .profile import Profile - - out = ["-f", "compose.yml"] - if Profile().registry_cache_active(): - out += ["-f", "compose/cache.override.yml"] - return out - - -def resolve_distro() -> str: - """Return INFINITO_DISTRO; raise SystemExit if missing or invalid.""" - distro = os.environ["INFINITO_DISTRO"].strip() - if not distro: - raise SystemExit( - "INFINITO_DISTRO is not set. Run 'make dotenv' (or source scripts/meta/env/load.sh) " - "or export INFINITO_DISTRO= " - "before invoking cli.administration.deploy.development." - ) - if distro not in VALID_DISTROS: - raise SystemExit( - f"INFINITO_DISTRO={distro!r} is not a valid distro. " - f"Valid: {', '.join(VALID_DISTROS)}." - ) - return distro - - def resolve_container() -> str: """Return INFINITO_CONTAINER; raise SystemExit if unset.""" container = os.environ["INFINITO_CONTAINER"].strip() diff --git a/cli/administration/deploy/development/compose.py b/cli/administration/deploy/development/compose.py index 3758f41114..755d821f45 100644 --- a/cli/administration/deploy/development/compose.py +++ b/cli/administration/deploy/development/compose.py @@ -5,8 +5,8 @@ import subprocess import time from typing import TYPE_CHECKING -from .common import compose_file_args from .coredns import CoreDNSCorefileRenderer +from .env import compose_file_args from .network import detect_outer_network_mtu from .proc import run_streaming from .profile import Profile diff --git a/cli/administration/deploy/development/down.py b/cli/administration/deploy/development/down.py index 7390a28fd6..d6f1755b45 100644 --- a/cli/administration/deploy/development/down.py +++ b/cli/administration/deploy/development/down.py @@ -7,7 +7,7 @@ from pathlib import Path from typing import TYPE_CHECKING from . import PROJECT_ROOT -from .common import compose_file_args, resolve_distro +from .env import compose_file_args, resolve_distro if TYPE_CHECKING: import argparse diff --git a/cli/administration/deploy/development/env.py b/cli/administration/deploy/development/env.py new file mode 100644 index 0000000000..09b85664d2 --- /dev/null +++ b/cli/administration/deploy/development/env.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +import os + +VALID_DISTROS: tuple[str, ...] = ("arch", "debian", "ubuntu", "fedora", "centos") + + +def compose_file_args() -> list[str]: + """Compose `-f` flags shared by up and down flows.""" + from .profile import Profile + + out = ["-f", "compose.yml"] + if Profile().registry_cache_active(): + out += ["-f", "compose/cache.override.yml"] + return out + + +def resolve_distro() -> str: + """Return INFINITO_DISTRO; raise SystemExit if missing or invalid.""" + distro = os.environ["INFINITO_DISTRO"].strip() + if not distro: + raise SystemExit( + "INFINITO_DISTRO is not set. Run 'make dotenv' (or source scripts/meta/env/load.sh) " + "or export INFINITO_DISTRO= " + "before invoking cli.administration.deploy.development." + ) + if distro not in VALID_DISTROS: + raise SystemExit( + f"INFINITO_DISTRO={distro!r} is not a valid distro. " + f"Valid: {', '.join(VALID_DISTROS)}." + ) + return distro diff --git a/cli/build/include/__main__.py b/cli/build/include/__main__.py index 650de6ee62..41ec6862ce 100644 --- a/cli/build/include/__main__.py +++ b/cli/build/include/__main__.py @@ -224,7 +224,7 @@ def main(): try: os.unlink(args.output) except OSError: - pass + pass # best-effort: proceed to open(); a real failure surfaces there with open(args.output, 'w') as f: f.write(output) print(f"Playbook entries written to {args.output}") diff --git a/cli/contributing/network/diagnose/probes.py b/cli/contributing/network/diagnose/probes.py index 4af2d03be0..ae651827a2 100644 --- a/cli/contributing/network/diagnose/probes.py +++ b/cli/contributing/network/diagnose/probes.py @@ -53,6 +53,7 @@ def tls_handshake( host: str, addr: str, family: int, port: int = 443, timeout: float = 8.0 ) -> tuple[bool, str]: ctx = ssl.create_default_context() + ctx.minimum_version = ssl.TLSVersion.TLSv1_2 start = time.monotonic() try: s = socket.socket(family, socket.SOCK_STREAM) diff --git a/cli/contributing/network/diagnose/report.py b/cli/contributing/network/diagnose/report.py index d8d9da21a0..91a176e3d3 100644 --- a/cli/contributing/network/diagnose/report.py +++ b/cli/contributing/network/diagnose/report.py @@ -110,5 +110,5 @@ def has_ipv6_default_route() -> bool: if len(parts) >= 10 and parts[0] == "0" * 32 and parts[-1] != "lo": return True except OSError: - pass + pass # best-effort: treat unreadable /proc/net/ipv6_route as no default route return False diff --git a/cli/contributing/network/diagnose/tools.py b/cli/contributing/network/diagnose/tools.py index 5637cef544..aa16b51e08 100644 --- a/cli/contributing/network/diagnose/tools.py +++ b/cli/contributing/network/diagnose/tools.py @@ -19,7 +19,7 @@ def detect_distro_id(*, os_release_path: str = "/etc/os-release") -> str: if raw.startswith("ID="): return raw.split("=", 1)[1].strip().strip('"').lower() except OSError: - pass + pass # best-effort: return empty distro id when /etc/os-release is unreadable return "" diff --git a/plugins/lookup/playwright_workers.py b/plugins/lookup/playwright_workers.py index 7c2e4cf257..ce4322a2fb 100644 --- a/plugins/lookup/playwright_workers.py +++ b/plugins/lookup/playwright_workers.py @@ -33,7 +33,7 @@ def _ram_gb() -> float: if line.startswith("MemTotal:"): return int(line.split()[1]) / (1024.0 * 1024.0) except (OSError, ValueError, IndexError): - pass + pass # best-effort: fall back to default when /proc/meminfo is unreadable/malformed return 4.0 # conservative fallback when /proc/meminfo is unreadable diff --git a/plugins/lookup/rbac_group_path.py b/plugins/lookup/rbac_group_path.py index e2e069a4c7..946c7aa8ea 100644 --- a/plugins/lookup/rbac_group_path.py +++ b/plugins/lookup/rbac_group_path.py @@ -38,12 +38,6 @@ from ansible.plugins.lookup import LookupBase from utils.cache.applications import get_merged_applications -try: - from ansible.utils.display import Display -except Exception: # pragma: no cover - Display = None - - _IMPLICIT_ADMIN_ROLE = "administrator" _TENANCY_AXIS_NONE = "none" _TENANCY_AXIS_DOMAIN = "domain" diff --git a/pyproject.toml b/pyproject.toml index 6abd3b3a0f..71090bad4a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -26,6 +26,7 @@ dependencies = [ [project.optional-dependencies] dev = [ "ruff", + "import-linter", "pre-commit", "git-maintainer-tools", ] @@ -108,6 +109,7 @@ exclude = [ # - `TRY004` — type-check failures must `raise TypeError`, not `ValueError` # - `TRY300` — put the success-path under `else:` so `except:` only sees the dangerous bit # - `TRY301` — don't `raise` inside `try:` for an exception caught by the same `except:` +# - `BLE001` (flake8-blind-except) — catch-all `except Exception:`/bare `except:` (ratchet; see per-file-ignores) select = [ "E", "F", "I", "B", "UP", "RUF", "SIM", "C4", "PERF", "RET", "PIE", "T10", "PGH", "EXE", "RSE", "ICN", "DTZ", @@ -121,6 +123,7 @@ select = [ "PLW1510", "PLW2901", "PLW0108", "PLW0603", "PLR5501", "PLC0207", "PLR1722", "PLR1714", "TRY002", "TRY004", "TRY300", "TRY301", + "BLE001", ] # `ruff format` (run via `make autoformat`) reflows whatever it can. @@ -171,7 +174,9 @@ ignore = [ # - S105/S106 (hardcoded passwords) appear in fixtures / dummy creds. # - S108 (hardcoded /tmp paths) appears in tempdir fixtures. # - S110/S112 (try/except pass/continue) appear in cleanup helpers. -"tests/**" = ["S101", "S102", "S105", "S106", "S108", "S110", "S112"] +# - BLE001 (broad `except Exception`) is idiomatic in test fixtures / +# cleanup helpers that must never abort the suite on teardown. +"tests/**" = ["S101", "S102", "S105", "S106", "S108", "S110", "S112", "BLE001"] # Standalone scripts under ``roles/*/files/`` and ``utils/cert_utils.py`` # are exercised by test fixtures that monkey-patch the legacy ``os.*`` @@ -181,7 +186,58 @@ ignore = [ # test in lockstep — out of scope for the use-pathlib pass. "roles/sys-ctl-rpr-container-hard/files/script.py" = ["PTH"] "roles/sys-ctl-rpr-container-soft/files/script.py" = ["PTH"] -"utils/cert_utils.py" = ["PTH"] + +# BLE001 (flake8-blind-except) ratchet. +# Broad `except Exception:` is now selected project-wide so NEW code is +# gated. Standalone role scripts under ``roles/*/files/`` legitimately +# swallow-and-continue for resilience, so the whole tree is exempt. The +# production modules below predate the rule and are grandfathered pending +# a focused burn-down; they should shrink, not grow. New production files +# are gated. CodeQL (`py/empty-except`) still covers the empty-body case +# everywhere, including the exempt paths. +"roles/**" = ["BLE001"] +"cli/administration/deploy/container/command.py" = ["BLE001"] +"cli/administration/deploy/dedicated/apps.py" = ["BLE001"] +"cli/administration/deploy/dedicated/command.py" = ["BLE001"] +"cli/administration/deploy/development/inventory/legacy_resolver.py" = ["BLE001"] +"cli/administration/deploy/development/proc.py" = ["BLE001"] +"cli/administration/inventory/credentials/vault.py" = ["BLE001"] +"cli/administration/inventory/devices/command.py" = ["BLE001"] +"cli/administration/inventory/provision/cli.py" = ["BLE001"] +"cli/administration/inventory/provision/credentials_generator.py" = ["BLE001"] +"cli/administration/inventory/provision/host_vars.py" = ["BLE001"] +"cli/administration/inventory/provision/services_disabler.py" = ["BLE001"] +"cli/administration/inventory/validate/loaders.py" = ["BLE001"] +"cli/contributing/mirror/sync/__main__.py" = ["BLE001"] +"cli/core/help.py" = ["BLE001"] +"cli/meta/j2/compiler/__main__.py" = ["BLE001"] +"cli/meta/roles/applications/all/__main__.py" = ["BLE001"] +"cli/meta/roles/applications/in_group_deps/__main__.py" = ["BLE001"] +"cli/meta/roles/applications/invokable/__main__.py" = ["BLE001"] +"cli/meta/roles/applications/type/__main__.py" = ["BLE001"] +"cli/meta/roles/lifecycle/__main__.py" = ["BLE001"] +"cli/meta/roles/services/called/__init__.py" = ["BLE001"] +"library/docker_bridge_gateway.py" = ["BLE001"] +"plugins/filter/active_docker.py" = ["BLE001"] +"plugins/filter/docker_service_enabled.py" = ["BLE001"] +"plugins/filter/get_all_application_ids.py" = ["BLE001"] +"plugins/filter/role_path_by_app_id.py" = ["BLE001"] +"plugins/filter/split_postgres_connections.py" = ["BLE001"] +"plugins/lookup/addon_env_flags.py" = ["BLE001"] +"plugins/lookup/applications_current_play.py" = ["BLE001"] +"plugins/lookup/email.py" = ["BLE001"] +"plugins/lookup/prometheus_integration_active.py" = ["BLE001"] +"plugins/lookup/version.py" = ["BLE001"] +"utils/cache/base.py" = ["BLE001"] +"utils/github/variant_bundles.py" = ["BLE001"] +"utils/nexus/list_apt_proxy_repos.py" = ["BLE001"] +"utils/roles/applications/in_group_deps.py" = ["BLE001"] +"utils/roles/applications/services/resources.py" = ["BLE001"] +"utils/roles/dependency_resolver.py" = ["BLE001"] +"utils/roles/validation/invokable.py" = ["BLE001"] +"utils/roles/validation/resources.py" = ["BLE001"] +"utils/templating/ansible.py" = ["BLE001"] +"utils/cert_utils.py" = ["PTH", "BLE001"] # N999 (invalid module name) on Ansible-invoked role-level scripts # whose filenames contain hyphens. Renaming to snake_case would break @@ -202,3 +258,31 @@ ignore = [ # rebinds the imported class inside the function. PEP 8 keeps the # UpperCamelCase form for class identifiers, including local re-binds. "plugins/filter/value_generator.py" = ["N806"] + +# --------------------------------------------------------------------------- +# import-linter — architectural import contracts (run via `lint-imports`, +# enforced by tests/lint/filesystem/python/test_import_contracts.py). +# --------------------------------------------------------------------------- +[tool.importlinter] +root_package = "cli" + +[[tool.importlinter.contracts]] +# The dev/CI deploy package was repeatedly hit by CodeQL +# `py/unsafe-cyclic-import`. The fix split the env/arg helpers into the +# leaf module `env`, giving the load-time DAG compose -> common -> deps +# -> env. This layers contract locks that order in: a lower layer +# importing a higher one (i.e. a new cycle) breaks the build. +name = "cli.administration.deploy.development stays acyclic (compose -> common -> deps -> env)" +type = "layers" +layers = [ + "cli.administration.deploy.development.compose", + "cli.administration.deploy.development.common", + "cli.administration.deploy.development.deps", + "cli.administration.deploy.development.env", +] +# Type-checking-only / lazily-deferred back-references to `compose` do +# not run at import time, so they cannot form a load-time cycle. +ignore_imports = [ + "cli.administration.deploy.development.common -> cli.administration.deploy.development.compose", + "cli.administration.deploy.development.deps -> cli.administration.deploy.development.compose", +] diff --git a/roles/sys-front-inj-all/filter_plugins/inj_snippets.py b/roles/sys-front-inj-all/filter_plugins/inj_snippets.py index 38276a0517..5249766fa3 100644 --- a/roles/sys-front-inj-all/filter_plugins/inj_snippets.py +++ b/roles/sys-front-inj-all/filter_plugins/inj_snippets.py @@ -18,8 +18,6 @@ from pathlib import Path # Role-bundled plugin: Ansible loads this file by file path with no # package context, so `from . import PROJECT_ROOT` cannot resolve here. # nocheck: project-root-import -_ROLE_DIR = str(Path(__file__).resolve().parents[1]) -# nocheck: project-root-import _ROLES_DIR = str(Path(__file__).resolve().parents[2]) diff --git a/roles/sys-service/tasks/03_lockdown.yml b/roles/sys-service/tasks/03_lockdown.yml index e9442f3b66..a12baed70a 100644 --- a/roles/sys-service/tasks/03_lockdown.yml +++ b/roles/sys-service/tasks/03_lockdown.yml @@ -47,6 +47,10 @@ ansible.builtin.systemd: name: "{{ item }}" state: stopped + register: deploy_stop_service + retries: 5 + delay: 3 + until: deploy_stop_service is success loop: "{{ deploy_services }}" when: deploy_services | length > 0 diff --git a/roles/sys-svc-compose/handlers/main.yml b/roles/sys-svc-compose/handlers/main.yml index 8d9ca62da8..c736c2dce3 100644 --- a/roles/sys-svc-compose/handlers/main.yml +++ b/roles/sys-svc-compose/handlers/main.yml @@ -73,6 +73,9 @@ register: dc_up changed_when: true timeout: 1800 + retries: 5 + delay: 10 + until: dc_up is succeeded environment: COMPOSE_PARALLEL_LIMIT: "{{ '4' if (DOCKER_IN_CONTAINER | bool) else omit }}" args: diff --git a/roles/web-app-baserow/files/sso/infinito_sso.py b/roles/web-app-baserow/files/sso/infinito_sso.py index a17e8a058a..da1b369f76 100644 --- a/roles/web-app-baserow/files/sso/infinito_sso.py +++ b/roles/web-app-baserow/files/sso/infinito_sso.py @@ -227,10 +227,13 @@ def _login_payload(request): def _safe_next_url(request): next_url = request.GET.get("next") or "/" + next_url = next_url.replace("\\", "/") parsed = urlsplit(next_url) - if parsed.scheme or parsed.netloc or not next_url.startswith("/"): + if parsed.scheme or parsed.netloc: return "/" - return next_url + if not next_url.startswith("/") or next_url.startswith("//"): + return "/" + return parsed.path + (f"?{parsed.query}" if parsed.query else "") class ProxyHeaderTokenView(APIView): diff --git a/roles/web-app-bluesky/files/login-broker/server.js b/roles/web-app-bluesky/files/login-broker/server.js index d121513c4a..edd885c6e0 100644 --- a/roles/web-app-bluesky/files/login-broker/server.js +++ b/roles/web-app-bluesky/files/login-broker/server.js @@ -160,8 +160,8 @@ function fetchJson(method, urlString, opts = {}) { function sanitiseHandle(username) { if (!username) return "kc-user"; - const lower = username.toLowerCase(); - const mapped = lower.replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, ""); + const lower = username.toLowerCase().slice(0, 256); + const mapped = lower.replace(/[^a-z0-9-]+/g, "-").replace(/^-+/, "").replace(/-+$/, ""); // PDS reserves common service handles ("administrator", "admin", "api", // "support", "www", "bsky", "atproto", etc.) and rejects createAccount // with `HandleNotAvailable: Reserved handle`. Always prefix with `kc-` @@ -290,14 +290,30 @@ async function ensurePdsSession({ kcUsername, kcEmail }) { // --- HTTP server ---------------------------------------------------- +function logSafe(v) { + // eslint-disable-next-line no-control-regex -- intentional: strip control chars to prevent log injection + return String(v).replace(/[\r\n]+/g, " ").replace(/[\x00-\x1f\x7f]/g, ""); +} + +function escapeHtml(v) { + return String(v) + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); +} + function parseCookies(req) { - const out = {}; + const out = Object.create(null); const header = req.headers["cookie"]; if (!header) return out; for (const part of header.split(";")) { const i = part.indexOf("="); if (i < 0) continue; - out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim()); + const key = part.slice(0, i).trim(); + if (key === "__proto__" || key === "prototype" || key === "constructor") continue; + out[key] = decodeURIComponent(part.slice(i + 1).trim()); } return out; } @@ -404,7 +420,7 @@ function proxyToSocialApp(req, res) { upstreamRes.pipe(res); }); upstreamReq.on("error", (err) => { - endText(res, 502, `social-app upstream error: ${err.message}`); + endText(res, 502, `social-app upstream error: ${escapeHtml(err.message)}`); }); req.pipe(upstreamReq); } @@ -412,7 +428,7 @@ function proxyToSocialApp(req, res) { const server = http.createServer(async (req, res) => { const reqId = Math.random().toString(36).slice(2, 8); const reqStart = Date.now(); - console.log(`[broker:${reqId}] ${req.method} ${req.url} from=${req.headers["x-forwarded-for"] || "?"} fwd-user=${req.headers["x-forwarded-user"] || req.headers["x-forwarded-preferred-username"] || "-"}`); + console.log(`[broker:${reqId}] ${logSafe(req.method)} ${logSafe(req.url)} from=${logSafe(req.headers["x-forwarded-for"] || "?")} fwd-user=${logSafe(req.headers["x-forwarded-user"] || req.headers["x-forwarded-preferred-username"] || "-")}`); try { const requestUrl = new URL(req.url, "http://internal"); const path = requestUrl.pathname; @@ -451,13 +467,13 @@ const server = http.createServer(async (req, res) => { } const session = await ensurePdsSession({ kcUsername, kcEmail }); - console.log(`[broker:${reqId}] PDS session ready did=${session.did} handle=${session.handle} hasAccessJwt=${!!session.accessJwt} (${Date.now() - reqStart}ms)`); + console.log(`[broker:${reqId}] PDS session ready did=${logSafe(session.did)} handle=${logSafe(session.handle)} hasAccessJwt=${!!session.accessJwt} (${Date.now() - reqStart}ms)`); const html = renderHandoff(session, requestUrl.pathname + (requestUrl.search || "")); endHtml(res, 200, html); console.log(`[broker:${reqId}] handoff HTML sent (${Date.now() - reqStart}ms)`); } catch (err) { console.error(`[broker:${reqId}] error:`, err.stack || err.message); - endText(res, 500, `Broker error: ${err.message}`); + endText(res, 500, `Broker error: ${escapeHtml(err.message)}`); } }); diff --git a/roles/web-app-decidim/files/patch.py b/roles/web-app-decidim/files/patch.py index dd8fda0879..5461fafd4b 100644 --- a/roles/web-app-decidim/files/patch.py +++ b/roles/web-app-decidim/files/patch.py @@ -101,7 +101,7 @@ def patch_storage_yml(content: str) -> str: if "force_path_style" in content: return content return re.sub( - r"(^s3:\n(?:[ \t]+.*\n)*?[ \t]+service: S3\n)", + r"(^s3:\n[\s\S]*?^[ \t]+service: S3\n)", r"\1 force_path_style: true\n", content, count=1, diff --git a/roles/web-app-nextcloud/files/gitlab/provision_oauth_app.rb b/roles/web-app-nextcloud/files/gitlab/provision_oauth_app.rb index 697fadc293..331eb5e949 100644 --- a/roles/web-app-nextcloud/files/gitlab/provision_oauth_app.rb +++ b/roles/web-app-nextcloud/files/gitlab/provision_oauth_app.rb @@ -1,6 +1,9 @@ -org = (Organizations::Organization.default_organization rescue nil) || (Organizations::Organization.first rescue nil) -raise "GitLab: no organization available to own the Nextcloud OAuth application" unless org -::Current.organization = org if defined?(::Current) && ::Current.respond_to?(:organization=) +org = (Organizations::Organization.default_organization rescue nil) || + (Organizations::Organization.first rescue nil) +if org.nil? && defined?(Organizations::Organization) + org = (Organizations::Organization.find_or_create_by!(path: "default") { |o| o.name = "Default" } rescue nil) +end +::Current.organization = org if org && defined?(::Current) && ::Current.respond_to?(:organization=) base = ENV.fetch("NC_BASE_URL").sub(%r{/\z}, "") path = ENV.fetch("NC_REDIRECT_PATH") @@ -11,8 +14,10 @@ was_new = app.new_record? app.redirect_uri = redirect_uris app.scopes = "api read_user" if app.respond_to?(:scopes=) app.confidential = true if app.respond_to?(:confidential=) -app.organization = org if app.respond_to?(:organization=) -app.organization_id = org.id if app.respond_to?(:organization_id=) +if org + app.organization = org if app.respond_to?(:organization=) + app.organization_id = org.id if app.respond_to?(:organization_id=) +end app.save! secret = nil diff --git a/roles/web-app-nextcloud/files/playwright/addons/integration_github.spec.js b/roles/web-app-nextcloud/files/playwright/addons/integration_github.spec.js index ae3757917a..e036f770eb 100644 --- a/roles/web-app-nextcloud/files/playwright/addons/integration_github.spec.js +++ b/roles/web-app-nextcloud/files/playwright/addons/integration_github.spec.js @@ -28,14 +28,14 @@ test("integration integration_github: per-user OAuth connect reaches github.com/ await Promise.all([ page - .waitForURL((u) => /github\.com\/login\/oauth\/authorize/i.test(u), { timeout: 60_000 }) + .waitForURL((u) => /^https?:\/\/github\.com\/login\/oauth\/authorize(?:[/?#]|$)/i.test(u), { timeout: 60_000 }) .catch(() => {}), connect.first().click(), ]); await expect .poll(() => page.url(), { timeout: 60_000 }) - .toMatch(/github\.com\/login\/oauth\/authorize/i); + .toMatch(/^https?:\/\/github\.com\/login\/oauth\/authorize(?:[/?#]|$)/i); const authorize = new URL(page.url()); expect( diff --git a/roles/web-app-nextcloud/files/playwright/addons/integration_google.spec.js b/roles/web-app-nextcloud/files/playwright/addons/integration_google.spec.js index cdbcddf62a..819a746ab7 100644 --- a/roles/web-app-nextcloud/files/playwright/addons/integration_google.spec.js +++ b/roles/web-app-nextcloud/files/playwright/addons/integration_google.spec.js @@ -39,7 +39,7 @@ test("integration integration_google: per-user OAuth connect reaches the Google const popupPromise = context.waitForEvent("page", { timeout: 15_000 }).catch(() => null); await Promise.all([ page - .waitForURL((u) => /accounts\.google\.com/i.test(new URL(u).host), { timeout: 60_000 }) + .waitForURL((u) => /^accounts\.google\.com$/i.test(new URL(u).host), { timeout: 60_000 }) .catch(() => {}), connect.first().click(), ]); diff --git a/roles/web-app-nextcloud/files/playwright/addons/integration_jira.spec.js b/roles/web-app-nextcloud/files/playwright/addons/integration_jira.spec.js index 5de1d58e17..1b5955e648 100644 --- a/roles/web-app-nextcloud/files/playwright/addons/integration_jira.spec.js +++ b/roles/web-app-nextcloud/files/playwright/addons/integration_jira.spec.js @@ -49,7 +49,7 @@ test("integration integration_jira: per-user OAuth connect reaches the Atlassian const popupPromise = context.waitForEvent("page", { timeout: 15_000 }).catch(() => null); await Promise.all([ page - .waitForURL((u) => /auth\.atlassian\.com/i.test(String(u)), { timeout: 60_000 }) + .waitForURL((u) => /^https?:\/\/auth\.atlassian\.com(?:[:/?#]|$)/i.test(String(u)), { timeout: 60_000 }) .catch(() => {}), connect.click(), ]); @@ -59,7 +59,7 @@ test("integration integration_jira: per-user OAuth connect reaches the Atlassian await target.waitForLoadState("domcontentloaded", { timeout: 30_000 }).catch(() => {}); await expect .poll(() => target.url(), { timeout: 60_000 }) - .toMatch(/auth\.atlassian\.com\/authorize/i); + .toMatch(/^https?:\/\/auth\.atlassian\.com\/authorize(?:[?#/]|$)/i); const authorize = new URL(target.url()); expect( diff --git a/roles/web-app-nextcloud/files/playwright/addons/integration_openproject.spec.js b/roles/web-app-nextcloud/files/playwright/addons/integration_openproject.spec.js index 7897108c8a..2e6cec5983 100644 --- a/roles/web-app-nextcloud/files/playwright/addons/integration_openproject.spec.js +++ b/roles/web-app-nextcloud/files/playwright/addons/integration_openproject.spec.js @@ -50,7 +50,7 @@ test("integration integration_openproject: two-way OAuth coupling provisioned an (await adminConfig.inputValue().catch(() => "")) || (await adminConfig.getAttribute("value").catch(() => "")) || ""; - let decoded = raw; + let decoded; try { decoded = Buffer.from(raw, "base64").toString("utf8"); } catch { diff --git a/roles/web-app-nextcloud/files/playwright/addons/spreed.spec.js b/roles/web-app-nextcloud/files/playwright/addons/spreed.spec.js index aecf144fe9..d0b0379ea1 100644 --- a/roles/web-app-nextcloud/files/playwright/addons/spreed.spec.js +++ b/roles/web-app-nextcloud/files/playwright/addons/spreed.spec.js @@ -89,7 +89,7 @@ test("spreed addon: Talk HPB signaling/turn backends are configured and coupled" } if (expectedSignalingUrl) { - let signalingNeedle = expectedSignalingUrl; + let signalingNeedle; try { signalingNeedle = new URL(expectedSignalingUrl).host; } catch { diff --git a/roles/web-app-nextcloud/tasks/addons/integration_gitlab_provision.yml b/roles/web-app-nextcloud/tasks/addons/integration_gitlab_provision.yml index 9a806e1d8e..7e4a32c71f 100644 --- a/roles/web-app-nextcloud/tasks/addons/integration_gitlab_provision.yml +++ b/roles/web-app-nextcloud/tasks/addons/integration_gitlab_provision.yml @@ -18,6 +18,9 @@ stdin: "{{ lookup('file', 'gitlab/provision_oauth_app.rb') }}" register: nextcloud_gl_provision changed_when: "'CLIENT_ID=' in nextcloud_gl_provision.stdout" + retries: 12 + delay: 5 + until: nextcloud_gl_provision.rc == 0 and 'CLIENT_ID=' in nextcloud_gl_provision.stdout no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - name: Parse the GitLab OAuth client id diff --git a/roles/web-app-odoo/files/playwright/addons/sale_management.spec.js b/roles/web-app-odoo/files/playwright/addons/sale_management.spec.js index 8adf28c8be..ecf460e9ed 100644 --- a/roles/web-app-odoo/files/playwright/addons/sale_management.spec.js +++ b/roles/web-app-odoo/files/playwright/addons/sale_management.spec.js @@ -21,7 +21,7 @@ test("addon sale_management: Sales module is installed and serves its quotations .locator(".o_menu_brand, .o_navbar .o_menu_sections, .o_control_panel") .getByText(/sales|quotations|orders/i) .first(); - const salesIdentity = breadcrumb.or(appTitle); + const salesIdentity = breadcrumb.or(appTitle).first(); await expect( salesIdentity, "the Sales app identity (breadcrumb/title naming Sales/Quotations/Orders) must render — when sale_management is enabled but the module failed to install, /odoo/sales falls back to the generic home shell and this is absent, so the test MUST fail here, not pass on the bare web client" diff --git a/roles/web-app-wordpress/files/playwright/addons/activitypub.spec.js b/roles/web-app-wordpress/files/playwright/addons/activitypub.spec.js index 407479d5d5..91770c012a 100644 --- a/roles/web-app-wordpress/files/playwright/addons/activitypub.spec.js +++ b/roles/web-app-wordpress/files/playwright/addons/activitypub.spec.js @@ -95,7 +95,7 @@ test("addon activitypub: WordPress is a discoverable Fediverse actor (WebFinger .concat(actor["@context"] || []) .map((c) => (typeof c === "string" ? c : (c && c["@vocab"]) || "")); expect( - contextValues.some((c) => /www\.w3\.org\/ns\/activitystreams/i.test(c)), + contextValues.some((c) => /^https?:\/\/www\.w3\.org\/ns\/activitystreams$/i.test(c)), "the actor JSON-LD must declare the ActivityStreams @context (proves it is a real federation object)" ).toBeTruthy(); diff --git a/tests/integration/ansible/lookups/config/test_literal_paths.py b/tests/integration/ansible/lookups/config/test_literal_paths.py index 0f6874e3e5..838c6d5c4f 100644 --- a/tests/integration/ansible/lookups/config/test_literal_paths.py +++ b/tests/integration/ansible/lookups/config/test_literal_paths.py @@ -56,7 +56,7 @@ class TestLiteralPaths(unittest.TestCase): except ConfigEntryNotSetError: continue except Exception: - pass + pass # best-effort: tolerate other get() errors, validation is checked below try: validate_app_path( ctx.application_defaults, diff --git a/tests/integration/ansible/vars/test_uppercase_constants_unique.py b/tests/integration/ansible/vars/test_uppercase_constants_unique.py index 26bf196c2d..fa02f96d30 100755 --- a/tests/integration/ansible/vars/test_uppercase_constants_unique.py +++ b/tests/integration/ansible/vars/test_uppercase_constants_unique.py @@ -24,14 +24,6 @@ from pathlib import Path from utils.cache.yaml import load_yaml_all -try: - pass -except Exception as e: # pragma: no cover - raise SystemExit( - "PyYAML is required for this test. Install with: pip install pyyaml" - ) from e - - UPPER_CONST_RE = re.compile(r"^[A-Z0-9_]+$") diff --git a/tests/integration/iam/sso/rbac/test_group_path_role_declarations.py b/tests/integration/iam/sso/rbac/test_group_path_role_declarations.py index f2d5ee8e81..fb1ce541a2 100644 --- a/tests/integration/iam/sso/rbac/test_group_path_role_declarations.py +++ b/tests/integration/iam/sso/rbac/test_group_path_role_declarations.py @@ -261,10 +261,7 @@ class TestRbacGroupPathRoleDeclarations(unittest.TestCase): # contributor sees what this static check could not verify. if offenders: msg_lines = [ - "rbac_group_path callsites reference roles that are not " - "declared in the target application's meta/rbac.yml. This " - "is the static counterpart of the runtime AnsibleError raised " - "by plugins/lookup/rbac_group_path.py.", + "rbac_group_path callsites reference roles that are not declared in the target application's meta/rbac.yml. This is the static counterpart of the runtime AnsibleError raised by plugins/lookup/rbac_group_path.py.", "", "Offenders:", *(f" - {item}" for item in offenders), @@ -272,8 +269,7 @@ class TestRbacGroupPathRoleDeclarations(unittest.TestCase): if unresolved: msg_lines += [ "", - "Note — the following callsites were skipped by the " - "static check (non-literal kwargs); verify them manually:", + "Note — the following callsites were skipped by the static check (non-literal kwargs); verify them manually:", *(f" - {item}" for item in unresolved), ] self.fail("\n".join(msg_lines)) diff --git a/tests/integration/infrastructure/compose/test_templates_require_image.py b/tests/integration/infrastructure/compose/test_templates_require_image.py index 3b812a80d1..9c7e7f6e7d 100644 --- a/tests/integration/infrastructure/compose/test_templates_require_image.py +++ b/tests/integration/infrastructure/compose/test_templates_require_image.py @@ -177,8 +177,7 @@ class TestComposeBuildRequiresImage(unittest.TestCase): if all_findings: # Pretty error output msg_lines = [ - "Some sys-svc-compose templates/files contain a `build:` key but are missing an `image:` key " - "at the same indentation level (same YAML mapping level).", + "Some sys-svc-compose templates/files contain a `build:` key but are missing an `image:` key at the same indentation level (same YAML mapping level).", "", "Offenders:", ] diff --git a/tests/lint/ansible/roles/test_readme.py b/tests/lint/ansible/roles/test_readme.py index 3ca387b9db..8c397b284c 100644 --- a/tests/lint/ansible/roles/test_readme.py +++ b/tests/lint/ansible/roles/test_readme.py @@ -48,7 +48,7 @@ ROLES_DIR = PROJECT_ROOT / "roles" _HEADING_RE = re.compile(r"^(#{1,6})\s+(.*?)\s*$", re.MULTILINE) _EMOJI_RE = re.compile( - "[\U0001f300-\U0001faff\U00002600-\U000027bf\U0001f000-\U0001f2ff]" + "[\U00002600-\U000027bf\U0001f000-\U0001f2ff\U0001f300-\U0001faff]" ) _REQUIRED_H2_ORDER: tuple[str, ...] = ("Description", "Overview", "Features") diff --git a/tests/lint/ansible/roles/web-app/playwright/persona/test_strict_mode.py b/tests/lint/ansible/roles/web-app/playwright/persona/test_strict_mode.py index 387eae3fd7..373c51a46f 100644 --- a/tests/lint/ansible/roles/web-app/playwright/persona/test_strict_mode.py +++ b/tests/lint/ansible/roles/web-app/playwright/persona/test_strict_mode.py @@ -51,7 +51,6 @@ _FLOW_FILES: tuple[str, ...] = ("biber.js", "admin.js", "guest.js") _DENY_HELPER_FILES: tuple[str, ...] = ("prometheus.js", "matomo.js") _TEST_SKIP_RE = re.compile(r"\btest\.skip\s*\(", re.MULTILINE) -_IF_HEAD_RE = re.compile(r"\bif\s*\(", re.MULTILINE) _STATUS_200_RE = re.compile(r"\b(?:status\s*===\s*200|=== 200|status\s*==\s*200)\b") _ALLOWED_SKIP_GUARDS: tuple[str, ...] = ( diff --git a/tests/lint/ansible/shell/test_no_sh_pipefail_in_ansible_tasks.py b/tests/lint/ansible/shell/test_no_sh_pipefail_in_ansible_tasks.py index e601402bd2..2afa63d8d9 100644 --- a/tests/lint/ansible/shell/test_no_sh_pipefail_in_ansible_tasks.py +++ b/tests/lint/ansible/shell/test_no_sh_pipefail_in_ansible_tasks.py @@ -6,10 +6,7 @@ from typing import TYPE_CHECKING, Any import yaml -from utils.cache.files import ( # noqa: F401 read_text retained for parity with other lint helpers - iter_project_files_with_content, - read_text, -) +from utils.cache.files import iter_project_files_with_content from utils.cache.yaml import load_yaml_all_str, load_yaml_any from . import PROJECT_ROOT diff --git a/tests/lint/docker/dockerfile/test_apt_update_purge_lists.py b/tests/lint/docker/dockerfile/test_apt_update_purge_lists.py index a135d5b252..e2d5bd6ff7 100644 --- a/tests/lint/docker/dockerfile/test_apt_update_purge_lists.py +++ b/tests/lint/docker/dockerfile/test_apt_update_purge_lists.py @@ -62,7 +62,7 @@ _RUN_START_RE = re.compile(r"^\s*RUN\b", re.IGNORECASE) # in between, but not arbitrary words (so `apt-get install update` does # NOT match). _APT_UPDATE_RE = re.compile( - r"\bapt-get\b(?:\s+(?:-[^\s]+|-o\s+[^\s]+))*\s+update\b", + r"\bapt-get\b(?:\s+-\S+(?:\s+[^-\s]\S*)?)*\s+update\b", re.IGNORECASE, ) _RM_LISTS_RE = re.compile(r"\brm\s+-[rRfv]*r[rRfv]*f?[rRfv]*\s+/var/lib/apt/lists/\*") diff --git a/tests/lint/filesystem/env/test_default_env_keys_handled.py b/tests/lint/filesystem/env/test_default_env_keys_handled.py index fb4a7f3097..f13287a772 100644 --- a/tests/lint/filesystem/env/test_default_env_keys_handled.py +++ b/tests/lint/filesystem/env/test_default_env_keys_handled.py @@ -64,11 +64,7 @@ class TestDefaultEnvKeysHandled(unittest.TestCase): f"INFINITO_* keys in default.env are not wired through any handler " f"({len(missing)} unhandled):", "", - "default.env is the SPOT for static defaults; each key MUST be " - "applied via setdefault by a handler in utils/env/handlers/ " - "(typically the static-passthrough handler). Add the key to the " - "handler's STATIC_KEYS / KEY constant so `make dotenv` materialises " - "the default into the generated .env.", + "default.env is the SPOT for static defaults; each key MUST be applied via setdefault by a handler in utils/env/handlers/ (typically the static-passthrough handler). Add the key to the handler's STATIC_KEYS / KEY constant so `make dotenv` materialises the default into the generated .env.", "", "Unhandled keys:", ] diff --git a/tests/lint/filesystem/env/test_infinito_prefix.py b/tests/lint/filesystem/env/test_infinito_prefix.py index 205279a120..2211bd1c79 100644 --- a/tests/lint/filesystem/env/test_infinito_prefix.py +++ b/tests/lint/filesystem/env/test_infinito_prefix.py @@ -66,11 +66,7 @@ class TestEnvFilesInfinitoPrefix(unittest.TestCase): f"default.env keys without the INFINITO_ prefix " f"({len(violations)} violations):", "", - "Every key in default.env must start with INFINITO_ so it cannot " - "collide with generic shell or Ansible-role variables of the " - "same short name. Rename the key to INFINITO_ (and update " - "callers) or move it out of default.env if it is not part of " - "the project's INFINITO_* namespace.", + "Every key in default.env must start with INFINITO_ so it cannot collide with generic shell or Ansible-role variables of the same short name. Rename the key to INFINITO_ (and update callers) or move it out of default.env if it is not part of the project's INFINITO_* namespace.", "", "Offenders:", ] diff --git a/tests/lint/filesystem/env/test_no_ansible_env_lookups.py b/tests/lint/filesystem/env/test_no_ansible_env_lookups.py index c1e9266796..aec51d470e 100644 --- a/tests/lint/filesystem/env/test_no_ansible_env_lookups.py +++ b/tests/lint/filesystem/env/test_no_ansible_env_lookups.py @@ -90,12 +90,7 @@ class TestNoAnsibleEnvLookupsForDefaultEnvKeys(unittest.TestCase): f"Ansible internals reference {len(violations)} default.env " f"key(s) via lookup('env', ...):", "", - "default.env is the dev/CI env contract; pulling those keys " - "directly inside group_vars / tasks / roles / playbook.yml " - "couples deployment-agnostic Ansible code to a deployment-" - "specific source. Inject the value via the inventory " - "vars-file instead. For dev/CI this is " - "`inventories/development/default.yml`:", + "default.env is the dev/CI env contract; pulling those keys directly inside group_vars / tasks / roles / playbook.yml couples deployment-agnostic Ansible code to a deployment-specific source. Inject the value via the inventory vars-file instead. For dev/CI this is `inventories/development/default.yml`:", "", " # inventories/development/default.yml", " networks:", @@ -104,10 +99,7 @@ class TestNoAnsibleEnvLookupsForDefaultEnvKeys(unittest.TestCase): " ip6: \"{{ lookup('env', 'INFINITO_IP6') | default('::1', true) }}\"", " dns: \"{{ lookup('env', 'INFINITO_DNS_IP') | default('') }}\"", "", - "Production / bundle inventories carry literal values " - "without the env lookup. Suppress per line with a same-line " - "`# nocheck: ` marker only when the reference is " - "genuinely required.", + "Production / bundle inventories carry literal values without the env lookup. Suppress per line with a same-line `# nocheck: ` marker only when the reference is genuinely required.", "", "Offenders:", ] diff --git a/tests/lint/filesystem/env/test_single_line_comments.py b/tests/lint/filesystem/env/test_single_line_comments.py index 0a16a8bca2..8f987c03b6 100644 --- a/tests/lint/filesystem/env/test_single_line_comments.py +++ b/tests/lint/filesystem/env/test_single_line_comments.py @@ -83,9 +83,7 @@ class TestEnvSingleLineComments(unittest.TestCase): f"Env entries with multi-line comment block " f"({len(violations)} violations across {len(grouped)} file(s)):", "", - "Env entries (`KEY=value`) must be preceded by AT MOST one `# ...` comment " - "line on the immediately preceding line. Collapse multi-line blocks to a " - "single one-line WHY comment.", + "Env entries (`KEY=value`) must be preceded by AT MOST one `# ...` comment line on the immediately preceding line. Collapse multi-line blocks to a single one-line WHY comment.", "", "Offenders:", ] diff --git a/tests/lint/filesystem/env/test_used_keys_declared.py b/tests/lint/filesystem/env/test_used_keys_declared.py index 24a5493dc0..056504bc5f 100644 --- a/tests/lint/filesystem/env/test_used_keys_declared.py +++ b/tests/lint/filesystem/env/test_used_keys_declared.py @@ -158,11 +158,7 @@ class TestUsedKeysDeclared(unittest.TestCase): f"INFINITO_* keys referenced in code without a registry entry " f"({len(unique_keys)} unknown key(s) across {len(violations)} use site(s)):", "", - "Add a default to default.env (and to the static-passthrough handler's " - "STATIC_KEYS) for static values, or write a dedicated handler under " - "utils/env/handlers/ that sets the key via eb.setdefault. " - "Suppress per line with `# nocheck: ` when the key legitimately " - "stays registry-less.", + "Add a default to default.env (and to the static-passthrough handler's STATIC_KEYS) for static values, or write a dedicated handler under utils/env/handlers/ that sets the key via eb.setdefault. Suppress per line with `# nocheck: ` when the key legitimately stays registry-less.", "", "Unregistered keys:", ] diff --git a/tests/lint/filesystem/makefile/test_single_line_comments.py b/tests/lint/filesystem/makefile/test_single_line_comments.py index 62475abc4f..53bf8b7ce5 100644 --- a/tests/lint/filesystem/makefile/test_single_line_comments.py +++ b/tests/lint/filesystem/makefile/test_single_line_comments.py @@ -116,9 +116,7 @@ class TestMakefileCommentSchema(unittest.TestCase): f"Makefile targets with comment-block schema violations " f"({len(violations)} offences):", "", - "Each target's comment block MUST be: one description line " - "(free text, no marker) followed by zero or more schema lines " - "marked `Usage:`, `Example:`, `Note:`, or `Param :`.", + "Each target's comment block MUST be: one description line (free text, no marker) followed by zero or more schema lines marked `Usage:`, `Example:`, `Note:`, or `Param :`.", "", "Offenders:", ] diff --git a/tests/lint/filesystem/python/test_import_contracts.py b/tests/lint/filesystem/python/test_import_contracts.py new file mode 100644 index 0000000000..a021a35583 --- /dev/null +++ b/tests/lint/filesystem/python/test_import_contracts.py @@ -0,0 +1,62 @@ +"""Lint guard: import-linter architectural contracts MUST hold. + +Background +========== +CodeQL ``py/unsafe-cyclic-import`` repeatedly flagged the dev/CI deploy +package ``cli.administration.deploy.development`` (compose <-> common <-> +deps). Static linters (ruff) do not model the module-import graph, so +they cannot catch a re-introduced cycle. import-linter does. + +The contracts live in ``[tool.importlinter]`` in ``pyproject.toml``; this +test runs them so a cycle regression fails CI rather than only surfacing +later in a CodeQL scan. Run them directly with ``lint-imports``. + +Skip behaviour +============== +import-linter is a dev dependency (``pip install .[dev]`` / +``make install-python-dev``). Where it is absent the test skips rather +than fails, so a minimal runtime-only environment is not blocked; CI +installs the dev extra and therefore enforces the contracts. +""" + +from __future__ import annotations + +import os +import shutil +import subprocess +import unittest + +from . import PROJECT_ROOT + +_LINT_IMPORTS = shutil.which("lint-imports") + + +class TestImportContracts(unittest.TestCase): + """The ``[tool.importlinter]`` contracts in ``pyproject.toml`` hold.""" + + @unittest.skipUnless( + _LINT_IMPORTS, + "import-linter not installed; run `make install-python-dev`", + ) + def test_import_linter_contracts_hold(self) -> None: + env = dict(os.environ) + env["PYTHONPATH"] = os.pathsep.join( + p for p in (str(PROJECT_ROOT), env.get("PYTHONPATH", "")) if p + ) + result = subprocess.run( + [_LINT_IMPORTS], + cwd=str(PROJECT_ROOT), + env=env, + capture_output=True, + text=True, + check=False, + ) + self.assertEqual( + result.returncode, + 0, + msg="import-linter contracts broken:\n" + result.stdout + result.stderr, + ) + + +if __name__ == "__main__": # pragma: no cover + unittest.main() diff --git a/tests/lint/filesystem/python/test_no_infinito_get_defaults.py b/tests/lint/filesystem/python/test_no_infinito_get_defaults.py index 6219ce2c5a..af2aac3782 100644 --- a/tests/lint/filesystem/python/test_no_infinito_get_defaults.py +++ b/tests/lint/filesystem/python/test_no_infinito_get_defaults.py @@ -123,12 +123,7 @@ class TestPythonNoInfinitoGetDefaults(unittest.TestCase): f"INFINITO_* defaults declared in `.get(KEY, default)` " f"({len(violations)} violations across {len(grouped)} file(s)):", "", - "INFINITO_* defaults belong in default.env (SPOT); the " - "handler builders in utils/env/handlers/ then apply them via " - "setdefault. Use `os.environ.get(KEY)` (None when unset) or " - "`os.environ[KEY]` (loud KeyError) instead -- the empty-string " - "fallback is also forbidden because it silently masks an unset " - "key. Suppress per line with `# nocheck: `.", + "INFINITO_* defaults belong in default.env (SPOT); the handler builders in utils/env/handlers/ then apply them via setdefault. Use `os.environ.get(KEY)` (None when unset) or `os.environ[KEY]` (loud KeyError) instead -- the empty-string fallback is also forbidden because it silently masks an unset key. Suppress per line with `# nocheck: `.", "", "Offenders:", ] diff --git a/tests/lint/filesystem/python/test_noqa_only_ruff_codes.py b/tests/lint/filesystem/python/test_noqa_only_ruff_codes.py index d0e27b0aa1..0114a810d3 100644 --- a/tests/lint/filesystem/python/test_noqa_only_ruff_codes.py +++ b/tests/lint/filesystem/python/test_noqa_only_ruff_codes.py @@ -120,10 +120,7 @@ class TestNoqaOnlyRuffCodes(unittest.TestCase): rel = lambda p: p.relative_to(PROJECT_ROOT).as_posix() # noqa: E731 lines = [ - f"{len(offenders)} file(s) carry ``# noqa: `` markers " - "with non-ruff codes. Switch project rule keys to " - "``# nocheck: ``; reserve ``# noqa:`` for real " - "ruff/flake8 codes (E402, F401, …).", + f"{len(offenders)} file(s) carry ``# noqa: `` markers with non-ruff codes. Switch project rule keys to ``# nocheck: ``; reserve ``# noqa:`` for real ruff/flake8 codes (E402, F401, …).", "", "Catalog of project rules: " "docs/contributing/actions/testing/suppression.md", diff --git a/tests/lint/filesystem/python/test_security_noqa_justified.py b/tests/lint/filesystem/python/test_security_noqa_justified.py new file mode 100644 index 0000000000..7bf78b9529 --- /dev/null +++ b/tests/lint/filesystem/python/test_security_noqa_justified.py @@ -0,0 +1,142 @@ +"""Lint guard: ``# noqa`` for a bandit (``S###``) finding MUST be justified. + +Background +========== +Ruff's ``S`` rules (flake8-bandit) flag security-relevant patterns: +tar extraction (``S202``), ``urlopen`` of attacker-influenceable URLs +(``S310``), ``subprocess(..., shell=True)`` (``S602``), and similar. +Suppressing one with a bare ``# noqa: S202`` silently disables the only +local signal that the line was reviewed — exactly the situation that let +``py/tarslip`` reach CodeQL. + +CodeQL ignores ruff ``# noqa`` markers, so a suppressed ``S###`` keeps +producing code-scanning alerts anyway. The cheap, durable fix is to +require every security suppression to carry an inline justification, so a +reviewer (and the next reader) can see *why* it is safe. + +Convention enforced here +======================== +Any ``# noqa:`` marker whose code list contains a bandit ``S###`` code +MUST be followed by free-text justification on the same line, e.g.:: + + tar.extractall(tmpdir) # noqa: S202 - members validated for path traversal + +A bare ``# noqa: S310`` with nothing after the code is rejected. + +Ratchet +======= +Files in ``_BASELINE`` predate the rule and carry unjustified security +suppressions today; they are grandfathered so the guard can land green. +The set MUST only shrink: justify the marker (or fix the finding), then +delete the path here. New security suppressions anywhere else fail. + +Caching +======= +File walk and content reads route through ``utils.cache.files``. +""" + +from __future__ import annotations + +import re +import unittest +from pathlib import Path + +from utils.cache.files import iter_project_files, read_text + +from . import PROJECT_ROOT + +# Match ``(#|//) noqa: `` and capture the comma-separated code list. +_NOQA_RE = re.compile( + r"(?:#|//)\s*noqa\s*:\s*" + r"(?P[A-Za-z][A-Za-z0-9\-]*(?:\s*,\s*[A-Za-z][A-Za-z0-9\-]*)*)", + re.IGNORECASE, +) + +# A bandit security code: ``S`` followed by digits (S101, S202, S310, …). +_SECURITY_CODE_RE = re.compile(r"^S\d+$") + + +# Files that still carry an unjustified security suppression today. Burn-down +# only: justify or fix, then remove the entry. Do NOT add to this set. +_BASELINE: frozenset[str] = frozenset( + { + "cli/administration/deploy/dedicated/runner.py", + "cli/administration/deploy/development/deploy.py", + "cli/administration/deploy/development/proc.py", + "cli/contributing/mirror/cleanup/__main__.py", + "plugins/lookup/nginx.py", + "roles/svc-bkp-remote-2-local/files/pull_specific_host.py", + "roles/svc-opt-ssd-hdd/files/script.py", + "roles/sys-ctl-cln-bkps/files/script.py", + "roles/sys-ctl-rpr-container-soft/files/script.py", + "roles/sys-svc-compose-ca/files/compose_ca.py", + "roles/sys-svc-compose/files/compose.py", + "roles/sys-svc-container/files/container.py", + "roles/web-app-erpnext/files/scripts/apply_oidc_settings.py", + "roles/web-app-keycloak/library/keycloak_kcadm_update.py", + "utils/github/playwright_summary.py", + "utils/update/docker.py", + } +) + + +def _file_offenders(path: Path) -> list[tuple[int, str]]: + """Return ``[(lineno, marker), ...]`` for unjustified security + suppressions on this file's lines.""" + try: + text = read_text(str(path)) + except (OSError, UnicodeDecodeError): + return [] + + findings: list[tuple[int, str]] = [] + for lineno, line in enumerate(text.splitlines(), start=1): + for match in _NOQA_RE.finditer(line): + codes = [c.strip() for c in match.group("codes").split(",")] + if not any(_SECURITY_CODE_RE.match(c) for c in codes): + continue + # Justification = any non-whitespace text after the code list. + if not line[match.end() :].strip(): + findings.append((lineno, match.group(0))) + return findings + + +class TestSecurityNoqaJustified(unittest.TestCase): + """Every bandit (``S###``) ``noqa`` suppression MUST carry a reason.""" + + def test_security_noqa_markers_are_justified(self) -> None: + offenders: dict[Path, list[tuple[int, str]]] = {} + + for path_str in iter_project_files(extensions=(".py",)): + path = Path(path_str) + try: + rel = path.relative_to(PROJECT_ROOT).as_posix() + except ValueError: + continue + if rel in _BASELINE: + continue + issues = _file_offenders(path) + if issues: + offenders[path] = issues + + if not offenders: + return + + def rel(p: Path) -> str: + return p.relative_to(PROJECT_ROOT).as_posix() + + lines = [ + f"{len(offenders)} file(s) suppress a bandit (S###) finding with an " + "unjustified ``# noqa``. Append an inline reason, e.g. " + "``# noqa: S202 - members validated for path traversal``, or fix the " + "finding. Security suppressions must never be silent.", + "", + ] + for path, issues in sorted(offenders.items()): + lines.append(f" - {rel(path)}:") + for lineno, marker in issues: + lines.append(f" * line {lineno}: {marker}") + self.fail("\n".join(lines)) + + +if __name__ == "__main__": # pragma: no cover + unittest.main() diff --git a/tests/lint/filesystem/shell/test_no_infinito_defaults.py b/tests/lint/filesystem/shell/test_no_infinito_defaults.py index dec783b386..db2026afb1 100644 --- a/tests/lint/filesystem/shell/test_no_infinito_defaults.py +++ b/tests/lint/filesystem/shell/test_no_infinito_defaults.py @@ -145,12 +145,7 @@ class TestShellNoInfinitoDefaults(unittest.TestCase): f"({len(all_violations)} violations across " f"{len(grouped)} file(s)):", "", - "INFINITO_* defaults belong in default.env (SPOT); the " - "generated .env then carries them. Shell-side defaults are " - "a second source that drifts silently. Read bare " - "${INFINITO_VAR} or use ${INFINITO_VAR:?msg}; the empty-form " - "${INFINITO_VAR:-} stays allowed for `set -u` safety. " - "Suppress per line with `# nocheck: `.", + "INFINITO_* defaults belong in default.env (SPOT); the generated .env then carries them. Shell-side defaults are a second source that drifts silently. Read bare ${INFINITO_VAR} or use ${INFINITO_VAR:?msg}; the empty-form ${INFINITO_VAR:-} stays allowed for `set -u` safety. Suppress per line with `# nocheck: `.", "", "Offenders:", ] diff --git a/tests/lint/repository/network/test_domain_primary_spot.py b/tests/lint/repository/network/test_domain_primary_spot.py index d90d245931..9b148d4bc3 100644 --- a/tests/lint/repository/network/test_domain_primary_spot.py +++ b/tests/lint/repository/network/test_domain_primary_spot.py @@ -62,8 +62,6 @@ _PATTERN: re.Pattern[str] = re.compile( ROLES_DIR = PROJECT_ROOT / "roles" -_DOMAIN_LIST_KEYS: frozenset[str] = frozenset({"canonical", "aliases"}) - @lru_cache(maxsize=4096) def _exempt_lines_for_lists(path: Path) -> frozenset[int]: diff --git a/tests/unit/cli/administration/inventory/credentials/test_overrides.py b/tests/unit/cli/administration/inventory/credentials/test_overrides.py index d067bbbf67..6642da8e01 100644 --- a/tests/unit/cli/administration/inventory/credentials/test_overrides.py +++ b/tests/unit/cli/administration/inventory/credentials/test_overrides.py @@ -34,9 +34,6 @@ class TestParseOverrides(unittest.TestCase): class TestOverrideFor(unittest.TestCase): def test_application_qualified_form(self): - overrides = {"applications.web-app-x.credentials.key=Z": "Z"} - # The dict above uses literal '=' in the key (no separate value); - # use the canonical parsed form instead: overrides = {"applications.web-app-x.credentials.key": "Z"} self.assertEqual( override_for("web-app-x", "key", overrides, is_primary=False), diff --git a/tests/unit/utils/cleanup/test_nginx_vhosts.py b/tests/unit/utils/cleanup/test_nginx_vhosts.py index ed685a2a9d..8a4328a8b2 100644 --- a/tests/unit/utils/cleanup/test_nginx_vhosts.py +++ b/tests/unit/utils/cleanup/test_nginx_vhosts.py @@ -11,8 +11,8 @@ from contextlib import redirect_stderr, redirect_stdout from pathlib import Path from unittest.mock import patch -import utils.cleanup.nginx_vhosts as mod from utils.cache.yaml import _reset_cache_for_tests, dump_yaml +from utils.cleanup import nginx_vhosts as mod from utils.cleanup.nginx_vhosts import ( iter_vhost_files_for_entity, main, diff --git a/tests/unit/utils/install/lint/test_main.py b/tests/unit/utils/install/lint/test_main.py index ce3fb25a8d..ef18ea76dc 100644 --- a/tests/unit/utils/install/lint/test_main.py +++ b/tests/unit/utils/install/lint/test_main.py @@ -5,9 +5,9 @@ from __future__ import annotations import os import time import unittest +import unittest.mock as mock from pathlib import Path from tempfile import TemporaryDirectory -from unittest import mock from utils.install.lint import __main__ as cli diff --git a/tests/unit/utils/install/test_github_release.py b/tests/unit/utils/install/test_github_release.py index f0a458e237..ca0a109333 100644 --- a/tests/unit/utils/install/test_github_release.py +++ b/tests/unit/utils/install/test_github_release.py @@ -3,7 +3,7 @@ from __future__ import annotations import unittest -from unittest import mock +import unittest.mock as mock from utils.install import github_release as gr diff --git a/tests/unit/utils/install/test_npm.py b/tests/unit/utils/install/test_npm.py index 9588a74ec1..9f3cb45246 100644 --- a/tests/unit/utils/install/test_npm.py +++ b/tests/unit/utils/install/test_npm.py @@ -4,7 +4,7 @@ from __future__ import annotations import subprocess import unittest -from unittest import mock +import unittest.mock as mock from utils.install import npm as npm_mod diff --git a/tests/unit/utils/install/test_pip.py b/tests/unit/utils/install/test_pip.py index 5091085f13..be00db965d 100644 --- a/tests/unit/utils/install/test_pip.py +++ b/tests/unit/utils/install/test_pip.py @@ -4,7 +4,7 @@ from __future__ import annotations import subprocess import unittest -from unittest import mock +import unittest.mock as mock from utils.install import pip as pip_mod diff --git a/tests/unit/utils/install/test_primitives.py b/tests/unit/utils/install/test_primitives.py index 6b0f7d4960..fa9084ebfa 100644 --- a/tests/unit/utils/install/test_primitives.py +++ b/tests/unit/utils/install/test_primitives.py @@ -4,7 +4,7 @@ from __future__ import annotations import os import unittest -from unittest import mock +import unittest.mock as mock from utils.install import primitives diff --git a/tests/unit/utils/install/test_system_pkg.py b/tests/unit/utils/install/test_system_pkg.py index 69e7c5e2f5..b69ae11960 100644 --- a/tests/unit/utils/install/test_system_pkg.py +++ b/tests/unit/utils/install/test_system_pkg.py @@ -4,7 +4,7 @@ from __future__ import annotations import subprocess import unittest -from unittest import mock +import unittest.mock as mock from utils.install import system_pkg diff --git a/utils/cache/base.py b/utils/cache/base.py index 9eb0944580..c300b55c56 100644 --- a/utils/cache/base.py +++ b/utils/cache/base.py @@ -21,12 +21,6 @@ from collections.abc import Mapping from pathlib import Path from typing import TYPE_CHECKING, Any -# `merge_with_defaults` is a pure-Python helper with no `ansible` dependency, -# so it stays at module scope. -from plugins.filter.merge_with_defaults import ( - merge_with_defaults, # noqa: F401 re-exported -) - from . import PROJECT_ROOT, ROLES_DIR # noqa: F401 if TYPE_CHECKING: diff --git a/utils/install/lint/actionlint.py b/utils/install/lint/actionlint.py index bf4658d94f..d976db9fac 100644 --- a/utils/install/lint/actionlint.py +++ b/utils/install/lint/actionlint.py @@ -73,7 +73,14 @@ def _install_binary() -> None: download_release_asset(url, str(archive_path)) with tarfile.open(archive_path) as tar: - tar.extractall(tmpdir) # noqa: S202 - controlled github asset + dest_root = tmp_path.resolve() + for member in tar.getmembers(): + member_path = (tmp_path / member.name).resolve() + if not member_path.is_relative_to(dest_root): + raise RuntimeError( + f"Archive {archive_name} contains an unsafe path: {member.name}" + ) + tar.extractall(tmpdir) # noqa: S202 - members validated for path traversal binary_src = tmp_path / "actionlint" if not binary_src.is_file():