diff --git a/cli/meta/ci/variant_split/compare.py b/cli/meta/ci/variant_split/compare.py index 50f16140ae..aff350907a 100644 --- a/cli/meta/ci/variant_split/compare.py +++ b/cli/meta/ci/variant_split/compare.py @@ -159,7 +159,7 @@ def pin_check(before: Mapping[str, Any], after: Mapping[str, Any]) -> dict[str, p for p in new_pins if not isinstance(p["reciprocal"], int) - or (p["target"] != "reciprocal" and int(p["target"]) != p["reciprocal"]) + or (p["target"].isdigit() and int(p["target"]) != p["reciprocal"]) ] def faults(snap: Mapping[str, Any], field: str) -> set[str]: diff --git a/cli/meta/ci/variant_split/rounds.py b/cli/meta/ci/variant_split/rounds.py index 21880448e0..d23701ee70 100644 --- a/cli/meta/ci/variant_split/rounds.py +++ b/cli/meta/ci/variant_split/rounds.py @@ -19,8 +19,8 @@ from utils.roles.applications.topics import overridden_providers, provider_of from utils.roles.applications.variant_pins import ( PIN, VariantPinError, - _reciprocal_index, _service_key_lines, + intended_index, ) from utils.roles.mapping import ( ROLE_FILE_META_MCP, @@ -131,7 +131,7 @@ def pinned_keys(role: str, roles_dir: str) -> dict[int, dict[str, tuple[str, str def pin_findings( role: str, *, roles_dir: str, variants_per_app: Mapping[str, list] ) -> list[dict[str, Any]]: - """Every pin *role* declares, with the variant that reciprocates it. + """Every pin *role* declares, with the variant its target is written to select. Args: role: the carrier role. @@ -142,9 +142,10 @@ def pin_findings( for index, pins in sorted(pinned_keys(role, roles_dir).items()): for partner, (target, key) in sorted(pins.items()): try: - reciprocal: int | str = _reciprocal_index( + reciprocal: int | str = intended_index( partner, role, + target, roles_dir=roles_dir, variants_per_app=variants_per_app, ) diff --git a/cli/meta/env/__main__.py b/cli/meta/env/__main__.py index d1abfe9c6f..dfba6f91fe 100644 --- a/cli/meta/env/__main__.py +++ b/cli/meta/env/__main__.py @@ -13,7 +13,7 @@ from utils.env.writer import write_dotenv from . import PROJECT_ROOT as REPO_ROOT -HOST_OWNED_KEY = "INFINITO_DOTENV_HOST_OWNED" # nocheck: dotenv-host-owned-marker Reason: set only by compose.yml inside the runner container; not a configuration key, a .env entry could freeze the host .env +HOST_OWNED_KEY = "INFINITO_DOTENV_HOST_OWNED" # nocheck: dotenv-host-owned-marker Reason: set only by compose.yml inside the runner container and by the act wrapper when it binds the checkout; not a configuration key, a .env entry could freeze the host .env def main(argv: list[str] | None = None) -> int: diff --git a/docs/contributing/actions/testing/suppression.md b/docs/contributing/actions/testing/suppression.md index d43c429589..d46aae8437 100644 --- a/docs/contributing/actions/testing/suppression.md +++ b/docs/contributing/actions/testing/suppression.md @@ -153,6 +153,16 @@ Some Python files use Ruff-compatible uppercase `# noqa` codes. Ruff and related | `F401` | Imported but unused | Re-export modules or import-probe tests where import success is the assertion. | | `SLF001` | Private member access | Test-only introspection of parser or object internals when the public surface does not expose the needed state. | +## Addon-Carrier Variant 🧩 + +[test_addons_variant_pinning.py](../../../../tests/lint/ansible/services/test_addons_variant_pinning.py) makes every variant from 2 on alias variant 1's static-off addon set. One variant per role MAY keep the static addons on instead, for example when they move off variant 0 into their own round to fit the job budget. It carries `# nocheck: addons-variant-pinning ` on its own `addons:` line, the only line the lint reads the marker from, and is then exempt from that rule: + +```yaml + addons: {} # nocheck: addons-variant-pinning v15 carries the static addons moved off v0 for the job budget +``` + +The reason MUST be at least `MIN_REASON_CHARS` (10) characters long. The marker fails on variant 0 or 1, because variant 1 owns the static-off set; on a second marked variant in the same role; while variant 0 still installs the static addons, because variant 0 then carries them already; and on a variant that pins every static addon off, because such a carrier carries nothing. The per-addon opt-out in the head of `meta/addons/.yml` is a separate placement of the same key. + ## Adding a new rule 🆕 1. Pick a kebab-case `` identifier. diff --git a/docs/contributing/artefact/files/role/variants.md b/docs/contributing/artefact/files/role/variants.md index 2803c84c92..f6653341f1 100644 --- a/docs/contributing/artefact/files/role/variants.md +++ b/docs/contributing/artefact/files/role/variants.md @@ -49,6 +49,14 @@ The token follows the `role#variant` form used by the priority slots. `#reciproc # variant-pin: web-app-nextcloud#reciprocal ``` +`#without-` resolves to the partner's one variant whose `services..enabled` is the literal `false`. Use it to cut a transitive chain the carrier does not need, where the partner never gates on the carrier and `#reciprocal` therefore has nothing to find. It needs no reciprocity, only exactly one matching variant; none or several raise `VariantPinError`. Unlike a bare index it keeps working when the partner gains a variant: + +```yaml + # variant-pin: web-svc-mirror#without-prometheus + tor: + enabled: true +``` + The marker is a comment, so it never reaches the merged services map or `host_vars`. It applies only to the variant entry it stands in; the same role's other variants are unaffected. A primary app keeps the index the sweep assigned it and no pin overrides it. A pin is in force only while the role carrying it is part of the round's include and runs the variant the marker stands in. A pin in a role the round does not deploy changes nothing. The round starts every role on its clamped index and recomputes the include and the pins in force until the assignment no longer changes; pins that never settle raise `VariantPinError`. [test_variant_pin_fixed_point.py](../../../../../tests/integration/roles/meta/variants/test_variant_pin_fixed_point.py) settles every round the matrix plans (each role as the only primary, in each of its variants) and fails when a round raises `VariantPinError`, or when a pin in force stands above a service entry the carrier runs with `enabled: false` in that round. Place a pin only above an entry the variant keeps enabled: the guide host `docs` stays on for the primary app alone, so a pin above `docs` fails the guard in any round that pulls the role in as a dependency running that variant. @@ -83,7 +91,7 @@ flowchart LR outside -.->|pin: not in force| partner ``` -Two roles pinning the same partner to different variants in one round raises `VariantPinConflictError` before an inventory is written. An index that no longer points at the reciprocating variant is caught by [test_variant_pins.py](../../../../../tests/integration/roles/meta/variants/test_variant_pins.py); `#reciprocal` needs exactly one candidate variant on the partner or it raises. +Two roles pinning the same partner to different variants in one round raises `VariantPinConflictError` before an inventory is written. An index that no longer points at the reciprocating variant is caught by [test_variant_pins.py](../../../../../tests/integration/roles/meta/variants/test_variant_pins.py); `#reciprocal` and `#without-` each need exactly one candidate variant on the partner or they raise. ## Credentials Interaction 🔐 diff --git a/group_vars/all/04_webserver.yml b/group_vars/all/04_webserver.yml index a5e31a48d9..c31c81bec9 100644 --- a/group_vars/all/04_webserver.yml +++ b/group_vars/all/04_webserver.yml @@ -24,6 +24,9 @@ WEBSERVER_PROXY_WORKER_CONNECTIONS: "{{ lookup('config', 'svc-prx-openresty', 's WEBSERVER_PROXY_WORKER_RLIMIT_NOFILE: "{{ (WEBSERVER_PROXY_WORKER_CONNECTIONS | int) * 2 }}" +# HTTP/2 on every TLS vhost. Off because OpenResty 1.31.8.x bundles nginx 1.31.8, which CVE-2026-123007 and CVE-2026-123633 hit only with HTTP/2 on; set true once OpenResty ships nginx >= 1.31.9. +WEBSERVER_HTTP2_ENABLED: false + # Response security headers of every vhost; an app overrides any key under `security_headers` in its meta/server.yml. WEBSERVER_SECURITY_HEADERS: nosniff: false # X-Content-Type-Options: nosniff diff --git a/roles/dsk-gnt-claude/meta/services.yml b/roles/dsk-gnt-claude/meta/services.yml index 595bfb9f96..4b1a036aae 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.327 + npm_version: 2.1.329 update: key: npm_version type: npm diff --git a/roles/svc-cache-package/templates/upstreams.conf.j2 b/roles/svc-cache-package/templates/upstreams.conf.j2 index 1e8127131a..0328b9045e 100644 --- a/roles/svc-cache-package/templates/upstreams.conf.j2 +++ b/roles/svc-cache-package/templates/upstreams.conf.j2 @@ -27,6 +27,9 @@ server { listen {{ listener.port }}{{ ' ssl' if listener.tls else '' }}; server_name {{ host.host }}; {% if listener.tls %} +{% if WEBSERVER_HTTP2_ENABLED | string | lower in ['true', 'yes', 'on', '1'] %} + http2 on; +{% endif %} ssl_certificate {{ CACHE_PACKAGE_CERTS_DIR }}/{{ host.host }}.crt; ssl_certificate_key {{ CACHE_PACKAGE_CERTS_DIR }}/{{ host.host }}.key; {% set repo = CACHE_PACKAGE_REPOS[host.repo] %} diff --git a/roles/sys-ctl-hlth-runtime/files/python/script.py b/roles/sys-ctl-hlth-runtime/files/python/script.py index 2a212c458b..27761cdd63 100755 --- a/roles/sys-ctl-hlth-runtime/files/python/script.py +++ b/roles/sys-ctl-hlth-runtime/files/python/script.py @@ -6,6 +6,7 @@ import argparse import contextlib import datetime as dt import fcntl +import hashlib import itertools import json import os @@ -1484,6 +1485,14 @@ def trivy_step( config: ScanConfig, os_args: Sequence[str], ) -> Step: + return trivy_args_step( + layout, image, target, trivy_args(layout, target, config, os_args) + ) + + +def trivy_args( + layout: Layout, target: Target, config: ScanConfig, os_args: Sequence[str] +) -> list[str]: args = [ "rootfs" if target.kind == "host" else "image", *TRIVY_COMMON, @@ -1506,6 +1515,12 @@ def trivy_step( args.append(HOST_ROOT) else: args += ["--image-src", "docker", target.ref] + return args + + +def trivy_args_step( + layout: Layout, image: str, target: Target, args: Sequence[str] +) -> Step: scratch = scratch_of("trivy", target.key) return Step( f"trivy {target.kind} {target.label}", @@ -1518,6 +1533,78 @@ def trivy_step( ) +def engine_image_id(layout: Layout, image: str, runner: Runner) -> str | None: + """ + Args: + layout: where the run keeps its files, its runtime among them. + image: the engine image reference, a mutable tag. + runner: runs one command. + + Returns: + The local image id the reference resolves to, ``None`` when it does + not resolve. + """ + try: + result = runner( + (layout.runtime[0], "image", "inspect", "--format", "{{.Id}}", image) + ) + except subprocess.TimeoutExpired: + return None + resolved = result.stdout.strip() + return resolved if result.returncode == 0 and resolved else None + + +def trivy_fingerprint( + layout: Layout, image_id: str | None, args: Sequence[str] +) -> str | None: + """ + Args: + layout: where the run keeps its files, the Trivy database among them. + image_id: the resolved id of the Trivy image, see + :func:`engine_image_id`. + args: the Trivy arguments of one container target. + + Returns: + A digest of the engine image id, its arguments and the size and + modification time of every Trivy database file, ``None`` when the + image id or a database file is missing. + """ + if image_id is None: + return None + digest = hashlib.sha256(json.dumps([image_id, list(args)]).encode()) + for marker in DB_MARKERS["trivy"]: + path = layout.databases / "trivy" / marker + if not path.is_file(): + return None + stat = path.stat() + digest.update(f"{marker}:{stat.st_size}:{stat.st_mtime_ns}".encode()) + return digest.hexdigest() + + +def trivy_cache_path(layout: Layout, target: Target) -> Path: + return layout.sbom / f"{target.key}.trivy.json" + + +def cached_trivy_report( + layout: Layout, target: Target, fingerprint: str | None +) -> dict | None: + """ + Returns: + The Trivy report of an earlier run on the same image, arguments and + database, ``None`` when there is none. + """ + path = trivy_cache_path(layout, target) + if fingerprint is None or not path.is_file(): + return None + try: + cached = _read_json(path) + except (OSError, ValueError): + return None + if cached.get("fingerprint") != fingerprint: + return None + return cached.get("report") + + def grype_step(layout: Layout, image: str, target: Target, config: ScanConfig) -> Step: if config.reads_sbom("grype"): source = [f"sbom:{SBOM}/{target.key}.syft.json"] @@ -1896,21 +1983,48 @@ def scan( lanes: list[list[Step]] = [] today = dt.datetime.now(tz=dt.UTC).date() + trivy_fresh: dict[str, tuple[Target, str]] = {} + trivy_lane: int | None = None if "trivy" in scanners: - lanes.append( - [ - trivy_step( - layout, - images["trivy"], - target, - config, - trivy_os_args(layout, target, scanners, config, today) - if target in sbom_ready - else [], - ) - for target in targets - ] + steps = [] + reused = 0 + trivy_id = ( + engine_image_id(layout, images["trivy"], runner) + if any(target.kind == "container" for target in targets) + else None ) + for target in targets: + args = trivy_args( + layout, + target, + config, + trivy_os_args(layout, target, scanners, config, today) + if target in sbom_ready + else [], + ) + fingerprint = ( + trivy_fingerprint(layout, trivy_id, args) + if target.kind == "container" + else None + ) + report = cached_trivy_report(layout, target, fingerprint) + if report is not None: + (layout.work / f"{target.key}.trivy.json").write_text( + json.dumps(report), encoding="utf-8" + ) + reused += 1 + continue + if fingerprint is not None: + trivy_fresh[target.key] = (target, fingerprint) + steps.append(trivy_args_step(layout, images["trivy"], target, args)) + if reused: + print( + f"â„šī¸ trivy: {reused} report(s) of unchanged images reused " + "against the unchanged database" + ) + if steps: + trivy_lane = len(lanes) + lanes.append(steps) if "grype" in scanners: lanes.extend( [grype_step(layout, images["grype"], target, config)] @@ -1941,7 +2055,15 @@ def scan( for step in osv_image_steps(layout, images["osv"], target, config) ] ) - errors += _flat(run_lanes(lanes, runner, config.workers, layout)) + results = run_lanes(lanes, runner, config.workers, layout) + errors += _flat(results) + if trivy_lane is not None and not results[trivy_lane]: + for key, (target, fingerprint) in trivy_fresh.items(): + report = layout.work / f"{key}.trivy.json" + write_atomic( + trivy_cache_path(layout, target), + json.dumps({"fingerprint": fingerprint, "report": _read_json(report)}), + ) findings: list[Finding] = [] for target in targets: @@ -1967,7 +2089,11 @@ def scan( def prune_sboms(layout: Layout, targets: Iterable[Target]) -> None: """Drop the cached SBOMs of images no container runs any more.""" - keep = {path for target in targets for path in sbom_paths(layout, target)} + keep = { + path + for target in targets + for path in (*sbom_paths(layout, target), trivy_cache_path(layout, target)) + } for path in layout.sbom.glob("*.json"): if path not in keep: path.unlink() diff --git a/roles/sys-front-tls/templates/nginx_ssl_header.j2 b/roles/sys-front-tls/templates/nginx_ssl_header.j2 index 54c1c8079d..4d70c4970e 100644 --- a/roles/sys-front-tls/templates/nginx_ssl_header.j2 +++ b/roles/sys-front-tls/templates/nginx_ssl_header.j2 @@ -1,7 +1,9 @@ {% if lookup('tls', domain, 'enabled') | bool %} listen {{ lookup('tls', domain, 'ports.web') }} ssl; listen [::]:{{ lookup('tls', domain, 'ports.web') }} ssl; +{% if WEBSERVER_HTTP2_ENABLED | bool %} http2 on; +{% endif %} ssl_protocols TLSv1.2 TLSv1.3; ssl_ecdh_curve X25519:P-256; diff --git a/roles/web-app-bluesky/meta/services.yml b/roles/web-app-bluesky/meta/services.yml index 26509e77ea..d139646c4a 100644 --- a/roles/web-app-bluesky/meta/services.yml +++ b/roles/web-app-bluesky/meta/services.yml @@ -65,7 +65,7 @@ view: domains: - view repository: https://github.com/bluesky-social/social-app.git - ref: "1.137.0" + ref: "1.138.0" ports: local: http: 8051 diff --git a/roles/web-app-bridgy-fed/meta/services.yml b/roles/web-app-bridgy-fed/meta/services.yml index 8c5b633d25..52ce0a8acc 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: 52f66059f3485213b652420f9ef4c047666f8913 + ref: 9dc7d38c5597e37162b1774816e0c4715a199adc ports: local: http: 8053 diff --git a/roles/web-app-discourse/meta/services.yml b/roles/web-app-discourse/meta/services.yml index a8e3fc787e..761c475c6d 100644 --- a/roles/web-app-discourse/meta/services.yml +++ b/roles/web-app-discourse/meta/services.yml @@ -66,7 +66,7 @@ discourse: shared: true enabled: true # nocheck: dynamic-flag name: discourse - ref: 0ba1841d589e77df3bc923774abca2720a320ec2 + ref: 59dacaecae5797991783ab357a86a573bb82a222 min_storage: 15GB repository: https://github.com/discourse/discourse_docker.git application: diff --git a/roles/web-app-erpnext/meta/services.yml b/roles/web-app-erpnext/meta/services.yml index 562c152038..73c3d3b9c9 100644 --- a/roles/web-app-erpnext/meta/services.yml +++ b/roles/web-app-erpnext/meta/services.yml @@ -68,7 +68,7 @@ erpnext: enabled: true shared: true image: frappe/erpnext - version: "v16.55.0" + version: "v16.60.0" name: erpnext min_storage: 1017MB ports: diff --git a/roles/web-app-fediwall/meta/services.yml b/roles/web-app-fediwall/meta/services.yml index 05e32d6838..c1880b2c3a 100644 --- a/roles/web-app-fediwall/meta/services.yml +++ b/roles/web-app-fediwall/meta/services.yml @@ -56,7 +56,7 @@ fediwall: swarm: enabled: true image: nginx - version: 1.31.8-alpine + version: 1.31.9-alpine custom: true upstream: version: "1.4.0" @@ -101,11 +101,6 @@ fediwall: mem_reservation: 128m mem_limit: 256m pids_limit: 256 - security: - suppressions: - # nocheck: cve upstream tag ships fixable CRITICAL CVEs; lift it once a rebuilt tag lands - - image_tag: "1.31.8-alpine" - until: 2026-11-30 # nocheck: playwright-service-flag # nocheck: variants-coverage — sso-variant-tor requires the onion on in every variant, so the false polarity has no variant left to live in diff --git a/roles/web-app-funkwhale/meta/services.yml b/roles/web-app-funkwhale/meta/services.yml index 739cbafa41..7b1d2bae45 100644 --- a/roles/web-app-funkwhale/meta/services.yml +++ b/roles/web-app-funkwhale/meta/services.yml @@ -13,7 +13,7 @@ funkwhale: # nocheck: default-placement-manager embedded typesense index; node-local in swarm placement: manager image: funkwhale/front - version: 2.0.15 + version: 2.0.16 min_storage: 224MB ports: internal: @@ -43,7 +43,7 @@ api: name: funkwhale-api image: funkwhale/api ca_client: true - version: 2.0.15 + version: 2.0.16 min_storage: 588MB ports: internal: diff --git a/roles/web-app-gitlab/meta/services.yml b/roles/web-app-gitlab/meta/services.yml index f567d0da3a..b4cb1d6d72 100644 --- a/roles/web-app-gitlab/meta/services.yml +++ b/roles/web-app-gitlab/meta/services.yml @@ -78,7 +78,7 @@ webservice: backup: stop_required: false image: registry.gitlab.com/gitlab-org/build/cng/gitlab-webservice-ce - version: v19.5.6 + version: v19.6.0 name: gitlab-webservice healthcheck: test: ["CMD", "/scripts/healthcheck"] @@ -99,7 +99,7 @@ sidekiq: flavor: tcp path: liveness image: registry.gitlab.com/gitlab-org/build/cng/gitlab-sidekiq-ce - version: v19.5.6 + version: v19.6.0 name: gitlab-sidekiq cpus: "1.0" mem_reservation: 2g @@ -112,7 +112,7 @@ workhorse: backup: stop_required: false image: registry.gitlab.com/gitlab-org/build/cng/gitlab-workhorse-ce - version: v19.5.6 + version: v19.6.0 name: gitlab-workhorse healthcheck: test: ["CMD", "/scripts/healthcheck"] @@ -128,7 +128,7 @@ gitaly: # nocheck: default-placement-manager the repositories live on a node-local volume (meta/volumes.yml nfs: false, gitaly does not support NFS), which a reschedule leaves behind on the old node placement: manager image: registry.gitlab.com/gitlab-org/build/cng/gitaly - version: v19.5.6 + version: v19.6.0 healthcheck: test: ["CMD", "/scripts/healthcheck"] name: gitlab-gitaly @@ -143,7 +143,7 @@ shell: backup: stop_required: false image: registry.gitlab.com/gitlab-org/build/cng/gitlab-shell - version: v19.5.6 + version: v19.6.0 name: gitlab-shell ports: internal: @@ -158,7 +158,7 @@ migrations: # nocheck: single-replica replicas: 1 image: registry.gitlab.com/gitlab-org/build/cng/gitlab-rails-ce - version: v19.5.6 + version: v19.6.0 name: gitlab-migrations cpus: "1.0" mem_reservation: 1g diff --git a/roles/web-app-littlejs/meta/services.yml b/roles/web-app-littlejs/meta/services.yml index 3573c895dc..8bd9871630 100644 --- a/roles/web-app-littlejs/meta/services.yml +++ b/roles/web-app-littlejs/meta/services.yml @@ -47,7 +47,7 @@ littlejs: repository: https://github.com/KilledByAPixel/LittleJS.git ref: main image: nginx - version: 1.31.8-alpine + version: 1.31.9-alpine custom: true ports: local: @@ -62,11 +62,6 @@ littlejs: mem_reservation: 256m mem_limit: 1g pids_limit: 512 - security: - suppressions: - # nocheck: cve upstream tag ships fixable CRITICAL CVEs; lift it once a rebuilt tag lands - - image_tag: "1.31.8-alpine" - until: 2026-11-30 # nocheck: email # nocheck: dynamic-flag email: diff --git a/roles/web-app-meta/meta/services.yml b/roles/web-app-meta/meta/services.yml index 398fca83e1..58a824671b 100644 --- a/roles/web-app-meta/meta/services.yml +++ b/roles/web-app-meta/meta/services.yml @@ -36,7 +36,7 @@ meta: swarm: enabled: true image: ghcr.io/infinito-nexus/meta - version: v2.0.4 + version: 2.1.0 name: meta min_storage: 1040MB ports: diff --git a/roles/web-app-nextcloud/meta/services.yml b/roles/web-app-nextcloud/meta/services.yml index 2ec7a0c399..8372d84ce9 100644 --- a/roles/web-app-nextcloud/meta/services.yml +++ b/roles/web-app-nextcloud/meta/services.yml @@ -121,7 +121,7 @@ proxy: # nocheck: healthcheck-timing-override a sidecar of a stack whose main service alone takes minutes; the value predates this default and has not been measured against it start_period: 20m image: nginx - version: 1.31.8-alpine + version: 1.31.9-alpine backup: stop_required: false cpus: "0.5" @@ -132,11 +132,6 @@ proxy: ports: internal: http: 80 - security: - suppressions: - # nocheck: cve upstream tag ships fixable CRITICAL CVEs; lift it once a rebuilt tag lands - - image_tag: "1.31.8-alpine" - until: 2026-11-30 # nocheck: playwright-service-flag # nocheck: dynamic-flag the container serves this role's MCP surface, so it tracks the role's own mcp flag rather than one client's presence context_agent: diff --git a/roles/web-app-nextcloud/meta/variants.yml b/roles/web-app-nextcloud/meta/variants.yml index 79e6b5d169..ca9e6bb659 100644 --- a/roles/web-app-nextcloud/meta/variants.yml +++ b/roles/web-app-nextcloud/meta/variants.yml @@ -119,6 +119,51 @@ openclaw: enabled: false shared: false + addons: &addons_static_off + appointments: + enabled: false + calendar: + enabled: false + collectives: + enabled: false + contacts: + enabled: false + cospend: + enabled: false + drawio: + enabled: false + epubviewer: + enabled: false + event_update_notification: + enabled: false + external: + enabled: false + files_bpm: + enabled: false + forms: + enabled: false + gpxpod: + enabled: false + groupfolders: + enabled: false + mail: + enabled: false + metadata: + enabled: false + news: + enabled: false + phonetrack: + enabled: false + polls: + enabled: false + quota_warning: + enabled: false + recognize: + enabled: false + tables: + enabled: false + tasks: + enabled: false # Variant 1: minimal - SSO off, no partners - services: container_backup: @@ -215,51 +260,7 @@ openclaw: enabled: true shared: true - addons: &addons_static_off - appointments: - enabled: false - calendar: - enabled: false - collectives: - enabled: false - contacts: - enabled: false - cospend: - enabled: false - drawio: - enabled: false - epubviewer: - enabled: false - event_update_notification: - enabled: false - external: - enabled: false - files_bpm: - enabled: false - forms: - enabled: false - gpxpod: - enabled: false - groupfolders: - enabled: false - mail: - enabled: false - metadata: - enabled: false - news: - enabled: false - phonetrack: - enabled: false - polls: - enabled: false - quota_warning: - enabled: false - recognize: - enabled: false - tables: - enabled: false - tasks: - enabled: false + addons: *addons_static_off # Variant 2: openwebui - services: container_backup: @@ -1486,3 +1487,98 @@ enabled: false shared: false addons: *addons_static_off +# Variant 15: the static addons, moved off variant 0 because together with the baseline they outrun the job budget +- services: + container_backup: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + sso: + enabled: false + shared: false + coturn: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + logout: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + ldap: + enabled: false + shared: false + dashboard: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + matomo: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + email: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + mariadb: + shared: true + redis: + shared: true + talk: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + talk_recording: + enabled: false + onlyoffice: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + collabora: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + bigbluebutton: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + xwiki: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + seaweedfs: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + design: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + prometheus: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + openproject: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + gitlab: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + discourse: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + mattermost: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + matrix: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + zammad: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + openwebui: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + litellm: + enabled: false + mastodon: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + peertube: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + # variant-pin: web-svc-mirror#without-prometheus + tor: + enabled: true + hermes: + enabled: false + shared: false + openclaw: + enabled: false + shared: false + addons: {} # nocheck: addons-variant-pinning v15 carries the static addons moved off v0 for the job budget diff --git a/roles/web-app-opencloud/files/playwright/test-design.js b/roles/web-app-opencloud/files/playwright/test-design.js index f7f877a754..8d99e4915f 100644 --- a/roles/web-app-opencloud/files/playwright/test-design.js +++ b/roles/web-app-opencloud/files/playwright/test-design.js @@ -17,6 +17,7 @@ const { adminPassword, adminUsername, baseUrl, ssoLoginAndAssertUsername } = req const SHOWCASE_FOLDER = "design-showcase"; const SHOWCASE_SPACE = "Design Showcase"; const SHOWCASE_GROUP = "design-showcase"; +const ACCESS_DENIED_TEXTS = ["#exitAnchor", "#opencloud .oc-card h2"]; const base = baseUrl.replace(/\/$/, ""); const idmUsername = decodeDotenvQuotedValue(process.env.IDM_ADMIN_USERNAME); @@ -449,7 +450,7 @@ test("design: a primary-filled control takes the primary color and its on-color" await assertToken(page, "#exitAnchor", "background-color", "--design-primary", `opencloud ${mode}`); await assertToken(page, "#exitAnchor", "color", "--design-on-primary", `opencloud ${mode}`); }); - await assertReadable(page, ["#exitAnchor", ".oc-login .oc-card h2"], "opencloud access denied"); + await assertReadable(page, ACCESS_DENIED_TEXTS, "opencloud access denied"); await expect( page.locator('img[alt="OpenCloud emblem"]'), "the upstream emblem must not show on the corporate frame", diff --git a/roles/web-app-opencloud/meta/services.yml b/roles/web-app-opencloud/meta/services.yml index 991d2e03a4..04d5cefbd1 100644 --- a/roles/web-app-opencloud/meta/services.yml +++ b/roles/web-app-opencloud/meta/services.yml @@ -38,7 +38,7 @@ opencloud: replicas: 1 name: opencloud image: opencloudeu/opencloud - version: 7.2.5 + version: 9.1.1 min_storage: 276MB # nocheck: default-placement-manager opencloud_data holds NFS-hostile engine state: NATS JetStream store (events, micro registry, posixfs id cache), bleve search index, idm.boltdb, posixfs xattr metadata; upstream says search cannot scale, so the volume must stay node-local placement: manager diff --git a/roles/web-app-opencloud/templates/style.css.j2 b/roles/web-app-opencloud/templates/style.css.j2 index c1c3ff354e..0c5dbc575c 100644 --- a/roles/web-app-opencloud/templates/style.css.j2 +++ b/roles/web-app-opencloud/templates/style.css.j2 @@ -28,14 +28,26 @@ background-color: var(--design-surface-active); } -.oc-button-primary-filled:hover:not([disabled], .no-hover) { +#exitAnchor { + --oc-button-color: var(--design-primary); + --oc-button-on-color: var(--design-on-primary); +} +:is(.oc-button-primary-filled, #exitAnchor):hover:not([disabled], .no-hover) { filter: none; background-color: var(--design-primary-hover); } -.oc-button-primary-filled:active:not([disabled]) { +:is(.oc-button-primary-filled, #exitAnchor):active:not([disabled]) { background-color: var(--design-primary-active); } +.oc-checkbox:checked:not(:disabled) { + border-color: var(--design-primary); + background-color: var(--design-primary); +} +.oc-checkbox[type="checkbox"]:is(:checked, :indeterminate):not(:disabled)::before { + background-color: var(--design-on-primary); +} + #oc-topbar { --design-focus: var(--design-on-frame); } diff --git a/roles/web-app-prometheus/meta/services.yml b/roles/web-app-prometheus/meta/services.yml index a2395b66e4..b48d9e58b1 100644 --- a/roles/web-app-prometheus/meta/services.yml +++ b/roles/web-app-prometheus/meta/services.yml @@ -118,7 +118,7 @@ blackbox-exporter: http: 9115 cadvisor: image: ghcr.io/google/cadvisor - version: 0.61.0 + version: 0.61.1 update: type: registry_tags image: ghcr.io/google/cadvisor @@ -136,7 +136,7 @@ node-exporter: flavor: wget path: metrics image: prom/node-exporter - version: v1.12.1 + version: v1.13.1 name: prometheus-node-exporter cpus: "0.1" mem_reservation: 32m @@ -146,11 +146,6 @@ node-exporter: ports: internal: http: 9100 - security: - suppressions: - # nocheck: cve upstream tag ships fixable CRITICAL CVEs; lift it once a rebuilt tag lands - - image_tag: "v1.12.1" - until: 2026-11-30 # nocheck: playwright-service-flag # nocheck: variants-coverage — sso-variant-tor requires the onion on in every variant, so the false polarity has no variant left to live in diff --git a/roles/web-app-stalwart/meta/services.yml b/roles/web-app-stalwart/meta/services.yml index 5727336dc2..61b9b64764 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.6" + webui_version: "v2.1.0" version: "v1.1.1" update: - key: webui_version @@ -140,7 +140,7 @@ clamav: enabled: true shared: false image: clamav/clamav-debian - version: "1.5.4" + version: "1.5.5" ports: internal: milter: 7357 diff --git a/roles/web-app-taiga/meta/services.yml b/roles/web-app-taiga/meta/services.yml index 4f4f352d9e..d88e78b71c 100644 --- a/roles/web-app-taiga/meta/services.yml +++ b/roles/web-app-taiga/meta/services.yml @@ -98,16 +98,11 @@ gateway: internal: http: 80 image: nginx - version: 1.31.8-alpine + version: 1.31.9-alpine cpus: "0.3" mem_reservation: 256m mem_limit: 512m pids_limit: 256 - security: - suppressions: - # nocheck: cve upstream tag ships fixable CRITICAL CVEs; lift it once a rebuilt tag lands - - image_tag: "1.31.8-alpine" - until: 2026-11-30 events: healthcheck: test: ["CMD-SHELL", "nc -z 127.0.0.1 8888"] diff --git a/roles/web-app-weblate/README.md b/roles/web-app-weblate/README.md index 37d4d8a16e..aff89d0995 100644 --- a/roles/web-app-weblate/README.md +++ b/roles/web-app-weblate/README.md @@ -17,7 +17,7 @@ In this deployment Weblate is the memory behind the translation gateway. [`web-s ## Administration -The container's entrypoint provisions the administrator as the Weblate user `admin`; `WEBLATE_ADMIN_NAME` is its display name only. The role reads that account's API token out of Weblate's own database after the deploy and writes it to `sys-token-store` under `administrator` / `web-app-weblate`. +The container's entrypoint provisions the administrator as the Weblate user `admin`; `WEBLATE_ADMIN_NAME` is its display name only. The role reads that account's API token out of Weblate's own database after the deploy and writes it to `sys-token-store` under `administrator` / `web-app-weblate`. With SSO on, [`files/python/adopt_admin.py`](files/python/adopt_admin.py) binds that account to the administrator's Keycloak user id, the `sub` claim, because Weblate 2026.11 refuses to link a signed-out OIDC sign-in to an existing account by e-mail unless `REGISTRATION_REBIND` is on. ## Networks diff --git a/roles/web-app-weblate/files/python/adopt_admin.py b/roles/web-app-weblate/files/python/adopt_admin.py index 42e94e825b..317f84fad3 100644 --- a/roles/web-app-weblate/files/python/adopt_admin.py +++ b/roles/web-app-weblate/files/python/adopt_admin.py @@ -1,32 +1,45 @@ -# nocheck: mirrored-unit-test - imports weblate.auth.models at module level and runs -# inside `weblate shell`; the models are not importable outside the Weblate image -"""Give the superuser Weblate bootstrapped the platform administrator's name. +"""Give the superuser Weblate bootstrapped the platform administrator's name and SSO identity. Upstream's entrypoint calls ``createadmin`` without ``--username``, so the superuser is always named ``admin`` while carrying the platform -administrator's e-mail. That is one human with two accounts, and it breaks -the OIDC login: ``associate_by_email`` matches the local account, then -``reauthenticate`` sees a usable password and parks an ``@partial`` on -``/accounts/confirm/`` asking for it. The partial is sticky, so every retry -returns to the same page. +administrator's e-mail. Renaming keeps the account, and with it the API +token the deploy reads back; creating a second superuser would leave that +token behind. -Renaming keeps the account, and with it the API token the deploy reads back; -creating a second superuser would leave that token behind. +Since Weblate 2026.11 ``weblate.accounts.pipeline.associate_by_email`` +refuses a signed-out OIDC sign-in whose e-mail already belongs to a local +account (``email_in_use``) unless ``REGISTRATION_REBIND`` is on, and that +setting would let every Keycloak user take over any account by e-mail. So +the administrator is bound to exactly its own Keycloak user instead: a +``social_django`` association for provider ``oidc`` whose ``uid`` is the +Keycloak user id, which Keycloak sends as the ``sub`` claim. +``social_user`` then finds the administrator before any e-mail check runs. +An association with that id held by another account is moved to the +administrator. An administrator already bound to another subject stops the +run, so a foreign identity is never overwritten silently. The password is only dropped while SSO is on. Without SSO it is the only way -in, and ``playwright.env.j2`` hands it to the native-login round. +in, and ``playwright.env.j2`` hands it to the native-login round. With SSO it +also keeps ``reauthenticate`` from parking a sticky ``@partial`` on +``/accounts/confirm/`` should the association ever be missing. Fed to ``weblate shell`` on stdin. Every value arrives in the environment and none has a default: a missing one is a deploy bug and must stop the run. +``WEBLATE_ADMIN_OIDC_SUBJECT`` is empty while SSO is off. """ import os +from social_django.models import UserSocialAuth from weblate.auth.models import User +OIDC_PROVIDER = "oidc" +OIDC_ID_KEY = "sub" + bootstrap = os.environ["WEBLATE_ADMIN_BOOTSTRAP_USERNAME"] target = os.environ["WEBLATE_ADMIN_USERNAME"] sso_enabled = os.environ["WEBLATE_OIDC_ENABLED"] == "true" +subject = os.environ["WEBLATE_ADMIN_OIDC_SUBJECT"] changed = False @@ -39,6 +52,32 @@ if bootstrap != target: admin = User.objects.get(username=target) +if sso_enabled: + if not subject: + raise SystemExit( + f"ADOPT_REFUSED: SSO is on but no Keycloak subject arrived for '{target}'" + ) + foreign = UserSocialAuth.objects.filter(user=admin, provider=OIDC_PROVIDER).exclude( + uid=subject + ) + if foreign.exists(): + raise SystemExit( + f"ADOPT_REFUSED: '{target}' is already bound to another OIDC subject; check " + "which Keycloak user it belongs to and delete that row from " + "social_auth_usersocialauth before deploying again" + ) + binding = UserSocialAuth.objects.filter(provider=OIDC_PROVIDER, uid=subject).first() + if binding is None: + UserSocialAuth.objects.create( + user=admin, provider=OIDC_PROVIDER, uid=subject, id_key=OIDC_ID_KEY + ) + changed = True + elif binding.user_id != admin.pk or binding.id_key != OIDC_ID_KEY: + binding.user = admin + binding.id_key = OIDC_ID_KEY + binding.save(update_fields=["user", "id_key"]) + changed = True + if sso_enabled and admin.has_usable_password(): admin.set_unusable_password() admin.save(update_fields=["password"]) diff --git a/roles/web-app-weblate/meta/services.yml b/roles/web-app-weblate/meta/services.yml index 7cea6c5629..a672dbabd9 100644 --- a/roles/web-app-weblate/meta/services.yml +++ b/roles/web-app-weblate/meta/services.yml @@ -58,7 +58,7 @@ weblate: host: enabled: false image: weblate/weblate - version: "2026.9" + version: "2026.11" min_storage: 1GB ports: local: @@ -86,7 +86,7 @@ beat: host: enabled: false image: weblate/weblate - version: "2026.9" + version: "2026.11" min_storage: 1GB lifecycle: beta # nocheck: single-replica weblate-beat. It is the only task upstream lets run Django's migrate, and the beat scheduler itself must stay singular or every periodic task fires once per replica. @@ -109,7 +109,7 @@ worker: host: enabled: false image: weblate/weblate - version: "2026.9" + version: "2026.11" min_storage: 1GB lifecycle: beta cpus: "1.0" diff --git a/roles/web-app-weblate/tasks/utils/admin_oidc_subject.yml b/roles/web-app-weblate/tasks/utils/admin_oidc_subject.yml new file mode 100644 index 0000000000..448ea6e9a1 --- /dev/null +++ b/roles/web-app-weblate/tasks/utils/admin_oidc_subject.yml @@ -0,0 +1,57 @@ +--- +# include-gated: when: WEBLATE_OIDC_ENABLED | bool +- name: "đŸ›Ąī¸ Assert Weblate signs in against the local Keycloak the bind reads" + ansible.builtin.assert: + that: + - OIDC.CLIENT.ISSUER_URL == weblate_oidc_local_issuer + fail_msg: >- + Weblate signs in against {{ OIDC.CLIENT.ISSUER_URL }}, not the local + Keycloak {{ weblate_oidc_local_issuer }}. The administrator bind reads its + user id from the local Keycloak, so another issuer sends a different sub and + locks the administrator out. Drop OIDC_OVERRIDE.URL and the OIDC_OVERRIDE.CLIENT + issuer override, or disable SSO for Weblate. + quiet: true + vars: + weblate_oidc_local_issuer: "{{ lookup('tls', 'web-app-keycloak', 'url.origin') ~ '/realms/' ~ OIDC.CLIENT.REALM }}" + +- name: "🔍 Resolve the Keycloak hosting node and container id" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" + vars: + resolve_service_key: keycloak + resolve_service_name: "{{ lookup('container_service', 'web-app-keycloak', 'keycloak') }}" + resolve_output_prefix: WEBLATE_KEYCLOAK + resolve_compose_cid: "{{ WEBLATE_KEYCLOAK_CONTAINER_ADDRESS }}" + resolve_converge_retries: 60 + resolve_converge_delay: 5 + resolve_cid_filters: "--filter health=healthy" + +- name: "🔍 Read the Keycloak user of the administrator" + ansible.builtin.shell: >- # nocheck: container-exec-resolver WEBLATE_KEYCLOAK_LOCAL_CID resolved at delegate_to runtime; container_address would return a manager-only subshell + container exec -i {{ WEBLATE_KEYCLOAK_LOCAL_CID | quote }} sh -c ' + /opt/keycloak/bin/kcadm.sh config credentials --server http://127.0.0.1:8080 --realm master + --user "$KEYCLOAK_PERMANENT_ADMIN_USERNAME" --password "$KEYCLOAK_PERMANENT_ADMIN_PASSWORD" >&2 + && exec /opt/keycloak/bin/kcadm.sh get users -r "$1" -q username="$2" -q exact=true + --fields id,username --format csv --noquotes' _ + {{ OIDC.CLIENT.REALM | quote }} {{ WEBLATE_ADMIN_USERNAME | quote }} + register: weblate_keycloak_admin_users + changed_when: false + retries: 6 + delay: 10 + until: weblate_keycloak_admin_users.rc == 0 + delegate_to: "{{ WEBLATE_KEYCLOAK_HOST_NODE }}" + run_once: true + +- name: "🔗 Pick the Keycloak user id of the administrator" + ansible.builtin.set_fact: + weblate_admin_oidc_subjects: "{{ weblate_keycloak_admin_users.stdout_lines | map('trim') | select('match', '[^,]+,' ~ (WEBLATE_ADMIN_USERNAME | lower | regex_escape) + ~ '$') | map('regex_replace', ',.*$', '') | list }}" + +- name: "🛑 Refuse anything but exactly one Keycloak user for the administrator" + ansible.builtin.assert: + that: + - weblate_admin_oidc_subjects | length == 1 + fail_msg: >- + Keycloak realm {{ OIDC.CLIENT.REALM }} returned {{ weblate_admin_oidc_subjects | length }} + users named '{{ WEBLATE_ADMIN_USERNAME }}', so the administrator cannot be bound + to its single sign-on identity and Weblate would refuse its login as email_in_use. + quiet: true diff --git a/roles/web-app-weblate/tasks/utils/token.yml b/roles/web-app-weblate/tasks/utils/token.yml index ff9b00edf8..3b5b7e0d7d 100644 --- a/roles/web-app-weblate/tasks/utils/token.yml +++ b/roles/web-app-weblate/tasks/utils/token.yml @@ -6,11 +6,16 @@ resolve_output_prefix: WEBLATE resolve_compose_cid: "{{ WEBLATE_CONTAINER }}" +- name: "🔗 Look up the Keycloak user the administrator signs in as" + when: WEBLATE_OIDC_ENABLED | bool + ansible.builtin.include_tasks: utils/admin_oidc_subject.yml + - name: "👤 Let the platform administrator own the superuser Weblate bootstrapped" ansible.builtin.shell: # nocheck: container-exec-resolver only Weblate's own management shell can reach its user table cmd: > container exec -i -e WEBLATE_ADMIN_BOOTSTRAP_USERNAME -e WEBLATE_ADMIN_USERNAME -e WEBLATE_OIDC_ENABLED + -e WEBLATE_ADMIN_OIDC_SUBJECT {{ WEBLATE_LOCAL_CID | quote }} weblate shell stdin: "{{ lookup('file', 'python/adopt_admin.py') }}" @@ -18,10 +23,11 @@ WEBLATE_ADMIN_BOOTSTRAP_USERNAME: "{{ WEBLATE_ADMIN_BOOTSTRAP_USERNAME }}" WEBLATE_ADMIN_USERNAME: "{{ WEBLATE_ADMIN_USERNAME }}" WEBLATE_OIDC_ENABLED: "{{ WEBLATE_OIDC_ENABLED | bool | lower }}" + WEBLATE_ADMIN_OIDC_SUBJECT: "{{ (weblate_admin_oidc_subjects | first) if (WEBLATE_OIDC_ENABLED | bool) else '' }}" register: weblate_admin_adopt retries: 30 delay: 10 - until: weblate_admin_adopt.rc == 0 + until: weblate_admin_adopt.rc == 0 or 'ADOPT_REFUSED' in weblate_admin_adopt.stderr changed_when: "'ADOPTED=1' in weblate_admin_adopt.stdout" no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" delegate_to: "{{ WEBLATE_HOST_NODE }}" diff --git a/roles/web-app-weblate/vars/main.yml b/roles/web-app-weblate/vars/main.yml index 5bf31b1aa2..7acffe1303 100644 --- a/roles/web-app-weblate/vars/main.yml +++ b/roles/web-app-weblate/vars/main.yml @@ -18,6 +18,7 @@ WEBLATE_ADMIN_PASSWORD: "{{ lookup('users', 'platform_administrator').password } WEBLATE_ADMIN_BOOTSTRAP_USERNAME: admin WEBLATE_ADMIN_USERNAME: "{{ lookup('users', 'platform_administrator').username }}" +WEBLATE_KEYCLOAK_CONTAINER_ADDRESS: "{{ lookup('container_address', 'web-app-keycloak', 'keycloak') }}" WEBLATE_TOKEN_MIN_LENGTH: 40 WEBLATE_DATABASE_NAME: "{{ lookup('database', application_id, 'name') }}" diff --git a/roles/web-app-wordpress/meta/addons/mcp-adapter.yml b/roles/web-app-wordpress/meta/addons/mcp-adapter.yml index 3116fb74d6..e41612358a 100644 --- a/roles/web-app-wordpress/meta/addons/mcp-adapter.yml +++ b/roles/web-app-wordpress/meta/addons/mcp-adapter.yml @@ -3,7 +3,7 @@ enabled: "{{ lookup('config', 'web-app-wordpress', 'mcp.enabled') | bool }}" required: true mechanism: plugin source: upstream -version: v0.7.1 +version: v0.7.2 update: monitored: true catalog: github-releases diff --git a/roles/web-app-wordpress/meta/services.yml b/roles/web-app-wordpress/meta/services.yml index cef525af21..b4514c3f42 100644 --- a/roles/web-app-wordpress/meta/services.yml +++ b/roles/web-app-wordpress/meta/services.yml @@ -66,7 +66,7 @@ wordpress: enabled: true swarm: enabled: true - version: 7.1.4 + version: 7.1.5 image: wordpress custom: true name: wordpress diff --git a/roles/web-svc-coturn/meta/services.yml b/roles/web-svc-coturn/meta/services.yml index 2c7de5db0a..402ae2227b 100644 --- a/roles/web-svc-coturn/meta/services.yml +++ b/roles/web-svc-coturn/meta/services.yml @@ -11,7 +11,7 @@ coturn: enabled: true shared: true image: coturn/coturn - version: 4.19.1 + version: 4.19.2 min_storage: 246MB user_auth_enabled: false total_quota: 2000 @@ -34,16 +34,11 @@ coturn: lifecycle: beta gateway: image: nginx - version: 1.31.8-alpine + version: 1.31.9-alpine cpus: "0.3" mem_reservation: 256m mem_limit: 512m pids_limit: 256 - security: - suppressions: - # nocheck: cve upstream tag ships fixable CRITICAL CVEs; lift it once a rebuilt tag lands - - image_tag: "1.31.8-alpine" - until: 2026-11-30 # nocheck: dynamic-flag coturn runs with user_auth_enabled false, so it keeps no credential store to back; the entry stays literal until auth is switched on and no template references redis today. redis: backup: diff --git a/scripts/tests/deploy/act/README.md b/scripts/tests/deploy/act/README.md index ee3794a2ed..09524ef219 100644 --- a/scripts/tests/deploy/act/README.md +++ b/scripts/tests/deploy/act/README.md @@ -9,4 +9,4 @@ For the canonical Make target index that invokes these helpers, see [make.md](.. | Command | What it does | Notes | |---|---|---| -| `workflow.sh` | Runs any workflow file through `act`. | Supports custom job, matrix, container, network, and image settings. Binds `INFINITO_VULNERABILITY_DB_HOST_PATH` into the job container at the same path. Invoked via `make act-workflow ACT_WORKFLOW=`. | +| `workflow.sh` | Runs any workflow file through `act`. | Supports custom job, matrix, container, network, and image settings. Binds `INFINITO_VULNERABILITY_DB_HOST_PATH` into the job container at the same path. A bound checkout (`ACT_BIND=true`, or pulled `roles/web-app-cst-*`) passes `INFINITO_DOTENV_HOST_OWNED=true`, so the job's `make dotenv` keeps the host `.env`. Invoked via `make act-workflow ACT_WORKFLOW=`. | diff --git a/scripts/tests/deploy/act/workflow.sh b/scripts/tests/deploy/act/workflow.sh index 93d09a2e33..762974734f 100755 --- a/scripts/tests/deploy/act/workflow.sh +++ b/scripts/tests/deploy/act/workflow.sh @@ -105,6 +105,7 @@ if [[ "${ACT_BIND}" != "true" ]] && compgen -G "${_act_repo_root}/roles/web-app- fi if [[ "${ACT_BIND}" == "true" ]]; then cmd+=(--bind) + cmd+=(--env "INFINITO_DOTENV_HOST_OWNED=true") fi "${cmd[@]}" diff --git a/scripts/tests/deploy/utils/filesystem/docker_dataroot.sh b/scripts/tests/deploy/utils/filesystem/docker_dataroot.sh index c8fcedca05..19b45842ed 100755 --- a/scripts/tests/deploy/utils/filesystem/docker_dataroot.sh +++ b/scripts/tests/deploy/utils/filesystem/docker_dataroot.sh @@ -217,9 +217,11 @@ require_tool mountpoint util-linux || decline "mountpoint is unavailable" case "${FSTYPE}" in ext4) require_tool mkfs.ext4 e2fsprogs || decline "mkfs.ext4 is unavailable" + MOUNT_OPTIONS=discard ;; btrfs) require_tool mkfs.btrfs btrfs-progs || decline "btrfs-progs is unavailable" + MOUNT_OPTIONS=discard=async ;; zfs) require_tool zpool zfsutils-linux zfs zfs-utils || @@ -279,7 +281,7 @@ while [ -z "${LOOP}" ] && [ "${attempt}" -lt 16 ]; do if [ -n "${candidate}" ] && [ ! -b "${candidate}" ]; then mknod "${candidate}" b 7 "${candidate#/dev/loop}" 2>/dev/null || candidate="" fi - if attached="$(losetup --find --show "${IMAGE}" 2>/dev/null)"; then + if attached="$(losetup --direct-io=on --find --show "${IMAGE}" 2>/dev/null)"; then LOOP="${attached}" fi done @@ -295,7 +297,7 @@ if [ "${FSTYPE}" = zfs ]; then zfs create -o mountpoint="${MOUNT}/docker" "${POOL}/docker" else "mkfs.${FSTYPE}" -q "${LOOP}" - mount -t "${FSTYPE}" "${LOOP}" "${MOUNT}" + mount -t "${FSTYPE}" -o "${MOUNT_OPTIONS}" "${LOOP}" "${MOUNT}" arm_autoclear "${LOOP}" "${MOUNT}" if [ "${FSTYPE}" = btrfs ]; then btrfs subvolume create "${MOUNT}/docker" >/dev/null diff --git a/tests/integration/roles/meta/variants/test_variant_pin_required.py b/tests/integration/roles/meta/variants/test_variant_pin_required.py index ddf9dbdefb..626d149c09 100644 --- a/tests/integration/roles/meta/variants/test_variant_pin_required.py +++ b/tests/integration/roles/meta/variants/test_variant_pin_required.py @@ -35,10 +35,11 @@ from __future__ import annotations import functools import re import unittest +from unittest.mock import patch from utils.cache.files import read_text from utils.cache.yaml import load_yaml_any -from utils.roles.applications.variant_pins import pins_of +from utils.roles.applications.variant_pins import RECIPROCAL, pins_of from utils.roles.applications.variants import ( _resolve_round_include, services_overrides_for_round, @@ -120,7 +121,8 @@ def _exempt(role: str) -> bool: def _pins_partner(role: str, index: int, partner: str) -> bool: - return partner in pins_of(role, roles_dir=str(ROLES_DIR)).get(index, {}) + target = pins_of(role, roles_dir=str(ROLES_DIR)).get(index, {}).get(partner) + return target is not None and (target.isdigit() or target == RECIPROCAL) def mutual_pairs() -> list[tuple[str, str, str, str]]: @@ -182,5 +184,18 @@ class TestVariantPinRequired(unittest.TestCase): ) +class TestPinsPartner(unittest.TestCase): + def _pins(self, target: str) -> bool: + with patch(f"{__name__}.pins_of", return_value={0: {"web-app-b": target}}): + return _pins_partner("web-app-a", 0, "web-app-b") + + def test_an_index_or_reciprocal_pin_states_the_pairing(self) -> None: + self.assertTrue(self._pins("3")) + self.assertTrue(self._pins(RECIPROCAL)) + + def test_negative_control_a_without_pin_does_not_state_the_pairing(self) -> None: + self.assertFalse(self._pins("without-prometheus")) + + if __name__ == "__main__": unittest.main() diff --git a/tests/integration/roles/meta/variants/test_variant_pins.py b/tests/integration/roles/meta/variants/test_variant_pins.py index 673bd6527b..23bdac63c8 100644 --- a/tests/integration/roles/meta/variants/test_variant_pins.py +++ b/tests/integration/roles/meta/variants/test_variant_pins.py @@ -13,8 +13,9 @@ and the inventory is written without complaint. This guard checks the index still means what it was written to mean, by comparing it against the variant ``#reciprocal`` would have found. A pin -written as ``#reciprocal`` carries no index, so for those the guard only -confirms the symbolic form resolves to exactly one variant. +written as ``#reciprocal`` or ``#without-`` carries no index, so for +those the guard only confirms the symbolic form resolves to exactly one +variant; ``#without-`` needs no reciprocity. """ from __future__ import annotations @@ -25,7 +26,7 @@ from utils.cache.applications import get_variants from utils.roles.applications.variant_pins import ( RECIPROCAL, VariantPinError, - _reciprocal_index, + intended_index, pins_of, ) @@ -49,13 +50,17 @@ class TestVariantPins(unittest.TestCase): findings = [] for role, index, partner, target in _pinning_roles(): try: - reciprocal = _reciprocal_index( - partner, role, roles_dir=str(ROLES_DIR), variants_per_app=variants + reciprocal = intended_index( + partner, + role, + target, + roles_dir=str(ROLES_DIR), + variants_per_app=variants, ) except VariantPinError as exc: findings.append(f" - {role}#{index} -> {partner}#{target}: {exc}") continue - if target != RECIPROCAL and int(target) != reciprocal: + if target.isdigit() and int(target) != reciprocal: findings.append( f" - {role}#{index} pins {partner}#{target}, but the variant " f"that switches {role} back on is {partner}#{reciprocal}" @@ -68,7 +73,7 @@ class TestVariantPins(unittest.TestCase): "that leaves the pairing dark:\n" + "\n".join(findings) + "\n\nPoint the pin at the reciprocating variant, or write it as " - "'#reciprocal' so it follows the partner automatically.", + f"'#{RECIPROCAL}' so it follows the partner automatically.", ) def test_the_scan_reads_the_marker(self) -> None: diff --git a/tests/lint/ansible/services/test_addons_variant_pinning.py b/tests/lint/ansible/services/test_addons_variant_pinning.py index d9a40a7139..d50097646f 100644 --- a/tests/lint/ansible/services/test_addons_variant_pinning.py +++ b/tests/lint/ansible/services/test_addons_variant_pinning.py @@ -90,6 +90,126 @@ def _variants(role_dir: Path) -> list: return data if isinstance(data, list) else [] +def _pinned_enabled(variant, addon_id: str): + """ + Args: + variant: one entry of the variant list. + addon_id: the addon to look up. + + Returns: + The ``enabled`` value the variant pins for *addon_id*, None when it + pins none. + """ + entry = _pinned_addons(variant).get(addon_id) + return entry.get("enabled") if isinstance(entry, Mapping) else None + + +def _addons_line_reason(lines: list[str]) -> str | None: + """ + Args: + lines: the lines of one variant entry, its ``- `` line first. + + Returns: + The reason the marker on the entry's own ``addons:`` line states, + empty when it states none, None when that line carries no marker. + """ + from utils.annotations.suppress import marker_reason + + own = next( + ( + line + for line in lines + if line[:2] in ("- ", " ") and line[2:].startswith("addons:") + ), + None, + ) + return None if own is None else marker_reason(own, _RULE) + + +def _addon_carriers( + text: str, variants: list, required: list[str] +) -> tuple[set[int], list[str]]: + """ + Args: + text: the role's ``meta/variants.yml``. + variants: the parsed variant list of that file. + required: the ids of the role's statically enabled addons. + + Returns: + The indices of the variants whose own ``addons:`` line carries + ``# nocheck: addons-variant-pinning``, and one finding per marker on + variant 0 or 1, per reason shorter than ``MIN_REASON_CHARS``, per + carrier while variant 0 still installs the static addons, per carrier + that leaves none of them on, and for more than one marked variant. + """ + from cli.administration.inventory.validate.open_subtrees import ( + MIN_REASON_CHARS, + ) + + lines = text.splitlines() + starts = [n for n, line in enumerate(lines) if line.startswith("- ")] + baseline_off = all( + _pinned_enabled(variants[0] if variants else {}, a) is False for a in required + ) + carriers: set[int] = set() + findings: list[str] = [] + for index, (start, end) in enumerate( + zip(starts, [*starts[1:], len(lines)], strict=True) + ): + reason = _addons_line_reason(lines[start:end]) + if reason is None: + continue + carriers.add(index) + variant = variants[index] if index < len(variants) else {} + if index < 2: + findings.append( + f"variant {index} carries the marker, but variant 1 owns the " + "static-off set" + ) + if len(reason) < MIN_REASON_CHARS: + findings.append( + f"variant {index} carries the marker without a reason of at " + f"least {MIN_REASON_CHARS} characters" + ) + if not baseline_off: + findings.append( + f"variant {index} carries the marker, but v0 already carries the " + "static addons" + ) + if all(_pinned_enabled(variant, a) is False for a in required): + findings.append( + f"variant {index}: carrier marker on a variant that carries nothing" + ) + if len(carriers) > 1: + findings.append( + f"variants {sorted(carriers)} carry the marker; a role has at most " + "one addon-carrier variant" + ) + return carriers, findings + + +def _uncarried_static_addons( + variants: list, required: list[str], carriers: set[int] +) -> list[tuple[int, str, object]]: + """ + Args: + variants: the role's parsed variant list. + required: the ids of the statically enabled addons. + carriers: the addon-carrier variants, exempt from the check. + + Returns: + ``(variant index, addon id, pinned value)`` per variant from 2 on + that does not pin a statically enabled addon to ``false``. + """ + return [ + (index, addon_id, value) + for index in range(2, len(variants)) + if index not in carriers + for addon_id in required + if (value := _pinned_enabled(variants[index], addon_id)) is not False + ] + + def _pinned_addons(variant) -> Mapping: """Return a variant entry's ``addons`` map, empty when it declares none. @@ -156,17 +276,16 @@ class TestAddonsVariantPinning(unittest.TestCase): if len(variants) < 3: continue required = sorted(f.stem for f in addon_files if _base_enabled(f) is True) - for index in range(2, len(variants)): - pinned = _pinned_addons(variants[index]) - for addon_id in required: - entry = pinned.get(addon_id) - value = entry.get("enabled") if isinstance(entry, Mapping) else None - if value is False: - continue - findings.append( - f"- {role}/{ROLE_FILE_META_VARIANTS}: variant {index} pins " - f"{addon_id!r} as {value!r}, variant 1 disables it" - ) + carriers, _ = _addon_carriers( + read_text(str(role_dir / ROLE_FILE_META_VARIANTS)), variants, required + ) + findings.extend( + f"- {role}/{ROLE_FILE_META_VARIANTS}: variant {index} pins " + f"{addon_id!r} as {value!r}, variant 1 disables it" + for index, addon_id, value in _uncarried_static_addons( + variants, required, carriers + ) + ) if not findings: return @@ -181,9 +300,164 @@ class TestAddonsVariantPinning(unittest.TestCase): " enabled: false\n" " # variant 2 and later\n" " addons: *addons_static_off\n\n" + "\n".join(findings) + "\n\n" - f"Per-addon opt-out: `# nocheck: {_RULE}` with a reason." + f"Per-addon opt-out: `# nocheck: {_RULE}` with a reason. The role's " + f"one addon-carrier variant keeps them on with `# nocheck: {_RULE} " + "` on its `addons:` line." ) + def test_every_addon_carrier_marker_is_valid(self) -> None: + findings: list[str] = [] + for role, addon_files in sorted(self._roles().items()): + role_dir = PROJECT_ROOT / "roles" / role + path = role_dir / ROLE_FILE_META_VARIANTS + if not path.is_file(): + continue + required = sorted(f.stem for f in addon_files if _base_enabled(f) is True) + _, problems = _addon_carriers( + read_text(str(path)), _variants(role_dir), required + ) + findings.extend( + f"- {role}/{ROLE_FILE_META_VARIANTS}: {p}" for p in problems + ) + + if not findings: + return + + self.fail( + f"`# nocheck: {_RULE}` on a variant's own `addons:` line names the " + "role's one addon-carrier variant, which keeps the static addons on. " + "It needs a reason, marks one variant only and never variant 0 or 1, " + "requires variant 0 to keep the static addons off, and must leave at " + "least one of them on:\n\n" + "\n".join(findings) + ) + + def _carriers( + self, marked: Mapping[int, str], variants: list + ) -> tuple[set[int], list[str]]: + return _addon_carriers( + "".join(f"- addons: {{}}{marked.get(index, '')}\n" for index in range(5)), + variants, + ["calendar"], + ) + + def _five_variants(self) -> list: + off = {"calendar": {"enabled": False}} + return [ + {"addons": off}, + {"addons": off}, + {"addons": off}, + {"addons": {}}, + {"addons": off}, + ] + + def test_a_marked_carrier_keeps_the_static_addons(self) -> None: + carriers, problems = self._carriers( + {3: f" # nocheck: {_RULE} budget split"}, self._five_variants() + ) + self.assertEqual((carriers, problems), ({3}, [])) + self.assertEqual( + _uncarried_static_addons(self._five_variants(), ["calendar"], carriers), + [], + ) + + def test_negative_control_an_unmarked_carrier_fails(self) -> None: + carriers, _ = self._carriers({}, self._five_variants()) + self.assertEqual( + _uncarried_static_addons(self._five_variants(), ["calendar"], carriers), + [(3, "calendar", None)], + ) + + def test_negative_control_a_second_marked_variant_fails(self) -> None: + variants = self._five_variants() + variants[4] = {"addons": {}} + _, problems = self._carriers( + { + 3: f" # nocheck: {_RULE} budget split", + 4: f" # nocheck: {_RULE} another split", + }, + variants, + ) + self.assertEqual( + problems, + [ + ( + "variants [3, 4] carry the marker; a role has at most one " + "addon-carrier variant" + ) + ], + ) + + def test_negative_control_a_marker_without_a_reason_fails(self) -> None: + _, problems = self._carriers({3: f" # nocheck: {_RULE}"}, self._five_variants()) + self.assertEqual( + problems, + ["variant 3 carries the marker without a reason of at least 10 characters"], + ) + + def test_negative_control_a_too_short_reason_fails(self) -> None: + _, problems = self._carriers( + {3: f" # nocheck: {_RULE} split"}, self._five_variants() + ) + self.assertEqual( + problems, + ["variant 3 carries the marker without a reason of at least 10 characters"], + ) + + def test_negative_control_a_marker_on_variant_1_fails(self) -> None: + variants = self._five_variants() + variants[1] = {"addons": {}} + _, problems = self._carriers({1: f" # nocheck: {_RULE} owns the set"}, variants) + self.assertEqual( + problems, + ["variant 1 carries the marker, but variant 1 owns the static-off set"], + ) + + def test_negative_control_a_carrier_beside_a_static_on_baseline_fails( + self, + ) -> None: + variants = self._five_variants()[:3] + variants[0] = {} + variants[2] = {"addons": {}} + _, problems = self._carriers({2: f" # nocheck: {_RULE} budget split"}, variants) + self.assertEqual( + problems, + ["variant 2 carries the marker, but v0 already carries the static addons"], + ) + + def test_negative_control_a_stale_carrier_marker_fails(self) -> None: + _, problems = self._carriers( + {4: f" # nocheck: {_RULE} budget split"}, self._five_variants() + ) + self.assertEqual( + problems, + ["variant 4: carrier marker on a variant that carries nothing"], + ) + + def test_negative_control_a_marker_off_the_addons_line_counts_nothing( + self, + ) -> None: + text = ( + "- addons: {}\n- addons: {}\n- addons: {}\n" + f"# Variant 3: heading # nocheck: {_RULE} budget split\n" + "- services:\n" + f" tor: # nocheck: {_RULE} budget split\n" + " enabled: true\n" + " addons: {}\n" + ) + variants = self._five_variants()[:4] + self.assertEqual(_addon_carriers(text, variants, ["calendar"]), (set(), [])) + + def test_a_marker_on_a_block_variants_addons_line_counts(self) -> None: + text = ( + "- addons: {}\n- addons: {}\n- addons: {}\n" + "- services:\n" + " tor:\n" + " enabled: true\n" + f" addons: {{}} # nocheck: {_RULE} budget split\n" + ) + variants = self._five_variants()[:4] + self.assertEqual(_addon_carriers(text, variants, ["calendar"]), ({3}, [])) + def test_dynamic_addons_are_never_pinned_in_a_variant(self) -> None: findings: list[str] = [] for role, addon_files in sorted(self._roles().items()): diff --git a/tests/unit/javascript/roles/web-app-opencloud/files/playwright/test-design.test.js b/tests/unit/javascript/roles/web-app-opencloud/files/playwright/test-design.test.js new file mode 100644 index 0000000000..4606ba6255 --- /dev/null +++ b/tests/unit/javascript/roles/web-app-opencloud/files/playwright/test-design.test.js @@ -0,0 +1,82 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +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 STYLESHEET = fs.readFileSync(path.join(PROJECT_ROOT, "roles/web-app-opencloud/templates/style.css.j2"), "utf8"); +const FILLED_CONTROLS = ":is(.oc-button-primary-filled, #exitAnchor)"; + +const noop = () => undefined; +const { ACCESS_DENIED_TEXTS } = loadInternals( + path.join(PROJECT_ROOT, "roles/web-app-opencloud/files/playwright/test-design.js"), + ["ACCESS_DENIED_TEXTS"], + { + "./onion-test": { test: Object.assign(noop, { use: noop, skip: noop }), expect: noop }, + "./_shared": { baseUrl: "https://opencloud.example.test/" }, + }, + {}, +); + +/** + * Args: + * css: role stylesheet template. + * selector: selector list of a rule that starts a line of the stylesheet. + * + * Returns: + * The declarations of that rule as a property to value map, or null when no rule has exactly this selector list. + */ +function declarations(css, selector) { + const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const rule = new RegExp(`(?:^|\\n)${escaped} \\{([^}]*)\\}`).exec(css); + if (!rule) return null; + return Object.fromEntries( + rule[1] + .split(";") + .map((declaration) => declaration.trim()) + .filter(Boolean) + .map((declaration) => declaration.split(/:\s*/, 2)), + ); +} + +test("the sign-in call to action of the access-denied page, secondary-filled since OpenCloud Web 8, takes the primary color and its on-color", () => { + assert.deepEqual(declarations(STYLESHEET, "#exitAnchor"), { + "--oc-button-color": "var(--design-primary)", + "--oc-button-on-color": "var(--design-on-primary)", + }); +}); + +test("the hovered or pressed call to action takes the hover and active shade of the primary color", () => { + assert.equal( + declarations(STYLESHEET, `${FILLED_CONTROLS}:hover:not([disabled], .no-hover)`)?.["background-color"], + "var(--design-primary-hover)", + ); + assert.equal( + declarations(STYLESHEET, `${FILLED_CONTROLS}:active:not([disabled])`)?.["background-color"], + "var(--design-primary-active)", + ); +}); + +test("a checked checkbox, which OpenCloud Web 8 fills with the secondary role, takes the primary color", () => { + assert.deepEqual(declarations(STYLESHEET, ".oc-checkbox:checked:not(:disabled)"), { + "border-color": "var(--design-primary)", + "background-color": "var(--design-primary)", + }); +}); + +test("the check and dash marks of a checkbox take the on-primary color without touching its focus outline", () => { + assert.equal( + declarations(STYLESHEET, '.oc-checkbox[type="checkbox"]:is(:checked, :indeterminate):not(:disabled)::before')?.[ + "background-color" + ], + "var(--design-on-primary)", + ); + assert.ok(!/--oc-role-on-secondary\s*:/.test(STYLESHEET)); +}); + +test("the access-denied readability check reads the card title inside the app, past the hidden browser-support card", () => { + assert.deepEqual([...ACCESS_DENIED_TEXTS], ["#exitAnchor", "#opencloud .oc-card h2"]); + assert.ok(ACCESS_DENIED_TEXTS.every((selector) => !selector.includes(".oc-login"))); +}); diff --git a/tests/unit/python/cli/meta/ci/variant_split/test_compare.py b/tests/unit/python/cli/meta/ci/variant_split/test_compare.py index d230d72a51..b8d875e766 100644 --- a/tests/unit/python/cli/meta/ci/variant_split/test_compare.py +++ b/tests/unit/python/cli/meta/ci/variant_split/test_compare.py @@ -137,6 +137,19 @@ class TestVerdict(unittest.TestCase): ) self.assertEqual(result["pins"]["unreciprocated"], []) + def test_a_resolving_without_pin_passes(self) -> None: + pin = { + "carrier": "app#3", + "partner": "pa", + "target": "without-a", + "key": "a", + "reciprocal": 0, + } + result = compare.verdict( + _before(), _after(pin=pin), old=["app#0"], split=["app#0", "app#3"] + ) + self.assertEqual(result["pins"]["unreciprocated"], []) + def test_the_render_names_the_verdict(self) -> None: text = compare.render( compare.verdict( diff --git a/tests/unit/python/cli/meta/ci/variant_split/test_rounds.py b/tests/unit/python/cli/meta/ci/variant_split/test_rounds.py index db5eb45c58..1f2d334477 100644 --- a/tests/unit/python/cli/meta/ci/variant_split/test_rounds.py +++ b/tests/unit/python/cli/meta/ci/variant_split/test_rounds.py @@ -76,6 +76,15 @@ class TestPins(unittest.TestCase): ) self.assertTrue(str(finding["reciprocal"]).startswith("error:")) + def test_a_without_pin_names_the_variant_switching_the_key_off(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + [finding] = rounds.pin_findings( + "web-app-a", + roles_dir=_tree(tmp, "without-a", gate=False), + variants_per_app=VARIANTS, + ) + self.assertEqual((finding["target"], finding["reciprocal"]), ("without-a", 0)) + class TestToken(unittest.TestCase): def test_a_whole_role_row_is_variant_0(self) -> None: 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 ac0bb58618..3d9ffff556 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 @@ -1110,10 +1110,11 @@ EMPTY_REPORTS = { class FakeEngines: """A runner that answers every engine command with a fixture report.""" - def __init__(self, layout, reports, *, fail=()): + def __init__(self, layout, reports, *, fail=(), image_ids=None): self.layout = layout self.reports = {**EMPTY_REPORTS, **reports} self.fail = fail + self.image_ids = image_ids or {} self.calls = [] self.active = 0 self.peak = 0 @@ -1129,6 +1130,11 @@ class FakeEngines: for marker in self.fail: if marker in text: return SimpleNamespace(returncode=2, stdout="", stderr="boom") + if list(argv[1:3]) == ["image", "inspect"]: + resolved = self.image_ids.get(argv[-1], "") + return SimpleNamespace( + returncode=0 if resolved else 1, stdout=resolved, stderr="" + ) self._write(list(argv)) return SimpleNamespace(returncode=0, stdout="", stderr="") finally: @@ -1170,8 +1176,8 @@ class TestScan(TestCase): def tearDown(self): self.tmp.cleanup() - def _scan(self, config, reports, fail=()): - runner = FakeEngines(self.layout, reports, fail=fail) + def _scan(self, config, reports, fail=(), image_ids=None): + runner = FakeEngines(self.layout, reports, fail=fail, image_ids=image_ids) with mock.patch.object(SCRIPT, "pause") as self.pauses: findings, errors = SCRIPT.scan( self.targets, config, self.images, self.layout, runner @@ -1270,6 +1276,112 @@ class TestScan(TestCase): {("grype", "CVE-2026-109618"), ("grype", "CVE-2026-109619")}, ) + def _provide_trivy_database(self): + for engine in ("trivy", "grype"): + for marker in SCRIPT.DB_MARKERS[engine]: + path = self.layout.databases / engine / marker + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("db", encoding="utf-8") + + def _pinned_container_scan(self, trivy_id, fail=()): + for stale in self.layout.work.iterdir(): + stale.unlink() + with contextlib.redirect_stdout(io.StringIO()): + return self._scan( + _config( + targets=["container"], engines=["syft", "trivy"], db_update=False + ), + {"trivy.json": TRIVY_HOST}, + fail=fail, + image_ids={self.images["trivy"]: trivy_id}, + ) + + def _trivy_calls(self, runner): + return [call for call in runner.calls if "--image-src" in call] + + def test_an_unchanged_image_reuses_its_trivy_report_on_an_unchanged_database(self): + self.targets = [CENTOS_TARGET] + self._provide_trivy_database() + first, first_errors, first_runner = self._pinned_container_scan( + trivy_id="sha256:trivy-1" + ) + second, second_errors, second_runner = self._pinned_container_scan( + trivy_id="sha256:trivy-1" + ) + self.assertEqual( + ( + len(self._trivy_calls(first_runner)), + len(self._trivy_calls(second_runner)), + first_errors + second_errors, + ), + (1, 0, []), + ) + self.assertEqual(second, first) + self.assertTrue(any(f.engine == "trivy" for f in second)) + + def test_a_refreshed_trivy_database_scans_the_image_again(self): + self.targets = [CENTOS_TARGET] + self._provide_trivy_database() + self._pinned_container_scan(trivy_id="sha256:trivy-1") + database = self.layout.databases / "trivy" / SCRIPT.DB_MARKERS["trivy"][0] + database.write_text("refreshed db", encoding="utf-8") + _findings, errors, runner = self._pinned_container_scan( + trivy_id="sha256:trivy-1" + ) + self.assertEqual((len(self._trivy_calls(runner)), errors), (1, [])) + + def test_a_trivy_tag_moved_to_another_image_scans_the_image_again(self): + self.targets = [CENTOS_TARGET] + self._provide_trivy_database() + self._pinned_container_scan(trivy_id="sha256:trivy-1") + _findings, errors, runner = self._pinned_container_scan( + trivy_id="sha256:trivy-2" + ) + self.assertEqual((len(self._trivy_calls(runner)), errors), (1, [])) + + def test_an_unresolved_trivy_image_reuses_no_report(self): + self.targets = [CENTOS_TARGET] + self._provide_trivy_database() + self._pinned_container_scan(trivy_id="") + _findings, errors, runner = self._pinned_container_scan(trivy_id="") + self.assertEqual((len(self._trivy_calls(runner)), errors), (1, [])) + self.assertFalse(SCRIPT.trivy_cache_path(self.layout, CENTOS_TARGET).exists()) + + def test_a_failed_trivy_run_leaves_no_report_to_reuse(self): + self.targets = [CENTOS_TARGET] + self._provide_trivy_database() + _findings, errors, _runner = self._pinned_container_scan( + trivy_id="sha256:trivy-1", fail=("--image-src",) + ) + self.assertTrue(errors) + self.assertFalse(SCRIPT.trivy_cache_path(self.layout, CENTOS_TARGET).exists()) + _findings, _errors, runner = self._pinned_container_scan( + trivy_id="sha256:trivy-1" + ) + self.assertEqual(len(self._trivy_calls(runner)), 1) + + def test_the_host_is_scanned_by_trivy_on_every_run(self): + self._provide_trivy_database() + for _ in range(2): + for stale in self.layout.work.iterdir(): + stale.unlink() + _findings, _errors, runner = self._scan( + _config(targets=["host"], engines=["syft", "trivy"], db_update=False), + {}, + ) + self.assertEqual( + len([call for call in runner.calls if "rootfs" in call]), 1 + ) + + def test_the_reused_trivy_report_survives_the_sbom_prune(self): + self.targets = [CENTOS_TARGET] + self._provide_trivy_database() + self._pinned_container_scan(trivy_id="sha256:trivy-1") + SCRIPT.prune_sboms(self.layout, [CENTOS_TARGET]) + self.assertTrue(SCRIPT.trivy_cache_path(self.layout, CENTOS_TARGET).is_file()) + SCRIPT.prune_sboms(self.layout, []) + self.assertFalse(SCRIPT.trivy_cache_path(self.layout, CENTOS_TARGET).exists()) + def test_the_provided_trivy_database_is_read_from_memory_cache(self): step = SCRIPT.trivy_step( self.layout, diff --git a/tests/unit/python/roles/sys-front-tls/templates/test_nginx_ssl_header.py b/tests/unit/python/roles/sys-front-tls/templates/test_nginx_ssl_header.py index e0b710bfe1..16bf355c39 100644 --- a/tests/unit/python/roles/sys-front-tls/templates/test_nginx_ssl_header.py +++ b/tests/unit/python/roles/sys-front-tls/templates/test_nginx_ssl_header.py @@ -6,6 +6,7 @@ import unittest from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape from plugins.filter.security_headers import FilterModule +from utils.cache.yaml import load_yaml from utils.tls_common import resolve_enabled from . import PROJECT_ROOT @@ -26,12 +27,13 @@ PRIMARY_DOMAINS = { } -def render(application_id: str, override: dict) -> str: +def render(application_id: str, override: dict, http2: bool = False) -> str: """Return the TLS server header of one vhost. Args: application_id: the app the vhost belongs to, or a redirect domain. override: the app's ``server.security_headers`` block. + http2: the value of ``WEBSERVER_HTTP2_ENABLED``. """ applications = { app: {"server": {"security_headers": override}} @@ -65,6 +67,7 @@ def render(application_id: str, override: dict) -> str: domain=PRIMARY_DOMAINS[application_id], lookup=lookup, WEBSERVER_SECURITY_HEADERS=PLATFORM, + WEBSERVER_HTTP2_ENABLED=http2, ) @@ -110,5 +113,17 @@ class TestCookieFlags(unittest.TestCase): self.assertNotIn("proxy_cookie_flags", render("web-app-x", {})) +class TestHttp2(unittest.TestCase): + def test_a_tls_vhost_serves_no_http2_while_the_switch_is_off(self): + self.assertNotIn("http2", render("web-app-x", {})) + + def test_a_tls_vhost_serves_http2_once_the_switch_is_on(self): + self.assertIn("\nhttp2 on;\n", render("web-app-x", {}, http2=True)) + + def test_the_platform_default_keeps_http2_off(self): + defaults = load_yaml(PROJECT_ROOT / "group_vars/all/04_webserver.yml") + self.assertIs(defaults["WEBSERVER_HTTP2_ENABLED"], False) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/roles/web-app-weblate/files/test_adopt_admin.py b/tests/unit/python/roles/web-app-weblate/files/test_adopt_admin.py new file mode 100644 index 0000000000..25dc820c64 --- /dev/null +++ b/tests/unit/python/roles/web-app-weblate/files/test_adopt_admin.py @@ -0,0 +1,370 @@ +from __future__ import annotations + +import contextlib +import io +import os +import runpy +import sys +import unittest +import unittest.mock +from types import ModuleType + +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar + +from utils.cache.files import PROJECT_ROOT +from utils.cache.yaml import load_yaml_any +from utils.templating.ansible import _trust_as_template + +SCRIPT = PROJECT_ROOT / "roles/web-app-weblate/files/python/adopt_admin.py" +TOKEN_TASKS = PROJECT_ROOT / "roles/web-app-weblate/tasks/utils/token.yml" +SUBJECT_INCLUDE = "utils/admin_oidc_subject.yml" +SUBJECT_TASKS = PROJECT_ROOT / "roles/web-app-weblate/tasks" / SUBJECT_INCLUDE +SUBJECT_FACT = "weblate_admin_oidc_subjects" +STOP_MARKER = "ADOPT_REFUSED" +ADMIN = "platformadmin" +SUBJECT = "4f1c2b8e-9d3a-4e57-8a61-0c2d5e7f9b10" +OTHER_SUBJECT = "a0b1c2d3-e4f5-4a6b-8c7d-9e0f1a2b3c4d" +JVM_NOISE = ( + "[0.001s][warning][os,container] Cgroup memory controller path at " + "'/sys/fs/cgroup' seems to have moved, detected limits won't be accurate" +) + + +def _matches(row, lookups: dict) -> bool: + return all(getattr(row, key) == value for key, value in lookups.items()) + + +class FakeQuerySet: + """The QuerySet calls ``adopt_admin.py`` makes. + + Args: + rows: the model instances the queryset holds. + """ + + def __init__(self, rows): + self._rows = list(rows) + + def filter(self, **lookups) -> FakeQuerySet: + return FakeQuerySet(row for row in self._rows if _matches(row, lookups)) + + def exclude(self, **lookups) -> FakeQuerySet: + return FakeQuerySet(row for row in self._rows if not _matches(row, lookups)) + + def first(self): + return self._rows[0] if self._rows else None + + def exists(self) -> bool: + return bool(self._rows) + + def get(self, **lookups): + found = self.filter(**lookups)._rows + if len(found) != 1: + raise LookupError(f"{len(found)} rows match {lookups}") + return found[0] + + +class FakeManager: + """A model manager over an in-memory table. + + Args: + model: the class ``create`` instantiates. + unique: field names that must be unique together, as ``unique_together``. + """ + + def __init__(self, model, unique: tuple[str, ...] = ()): + self.model = model + self.unique = unique + self.rows: list = [] + + def filter(self, **lookups) -> FakeQuerySet: + return FakeQuerySet(self.rows).filter(**lookups) + + def get(self, **lookups): + return FakeQuerySet(self.rows).get(**lookups) + + def create(self, **fields): + key = {name: fields[name] for name in self.unique} + if self.unique and FakeQuerySet(self.rows).filter(**key).exists(): + raise ValueError(f"unique constraint violated for {key}") + row = self.model(**fields) + self.rows.append(row) + return row + + +class FakeUser: + """``weblate.auth.models.User`` reduced to what the adoption touches. + + Args: + pk: primary key. + username: login name. + usable_password: whether ``has_usable_password`` answers True. + """ + + objects: FakeManager + + def __init__(self, pk: int, username: str, *, usable_password: bool = True): + self.pk = pk + self.username = username + self.usable_password = usable_password + + def save(self, update_fields) -> None: + self.saved = tuple(update_fields) + + def has_usable_password(self) -> bool: + return self.usable_password + + def set_unusable_password(self) -> None: + self.usable_password = False + + +class FakeSocial: + """``social_django.models.UserSocialAuth`` of social-auth-app-django 7.2. + + Args: + user: the owning account. + provider: backend name. + uid: the identifier the backend reports. + id_key: the claim ``uid`` was read from; ``social_user`` filters on it. + """ + + objects: FakeManager + + def __init__(self, user, provider: str, uid: str, id_key: str = ""): + self.user = user + self.provider = provider + self.uid = uid + self.id_key = id_key + + @property + def user_id(self) -> int: + return self.user.pk + + def save(self, update_fields) -> None: + self.saved = tuple(update_fields) + + +class Database: + """Fresh model classes and tables, one per test.""" + + def __init__(self): + self.User = type("User", (FakeUser,), {}) + self.User.objects = FakeManager(self.User) + self.UserSocialAuth = type("UserSocialAuth", (FakeSocial,), {}) + self.UserSocialAuth.objects = FakeManager( + self.UserSocialAuth, unique=("provider", "uid") + ) + + def user(self, pk: int, username: str, **kwargs): + return self.User.objects.create(pk=pk, username=username, **kwargs) + + def social(self, user, uid: str, id_key: str = "sub", provider: str = "oidc"): + return self.UserSocialAuth.objects.create( + user=user, provider=provider, uid=uid, id_key=id_key + ) + + def modules(self) -> dict[str, ModuleType]: + auth_models = ModuleType("weblate.auth.models") + auth_models.User = self.User + social_models = ModuleType("social_django.models") + social_models.UserSocialAuth = self.UserSocialAuth + return { + "weblate": ModuleType("weblate"), + "weblate.auth": ModuleType("weblate.auth"), + "weblate.auth.models": auth_models, + "social_django": ModuleType("social_django"), + "social_django.models": social_models, + } + + +def adopt(db: Database, *, sso: bool = True, subject: str = SUBJECT) -> str: + """Run the shipped script the way ``weblate shell`` does and return its stdout. + + Args: + db: the tables the script reads and writes. + sso: the value of ``WEBLATE_OIDC_ENABLED``. + subject: the value of ``WEBLATE_ADMIN_OIDC_SUBJECT``. + """ + env = { + "WEBLATE_ADMIN_BOOTSTRAP_USERNAME": "admin", + "WEBLATE_ADMIN_USERNAME": ADMIN, + "WEBLATE_OIDC_ENABLED": "true" if sso else "false", + "WEBLATE_ADMIN_OIDC_SUBJECT": subject, + } + out = io.StringIO() + with ( + unittest.mock.patch.dict(sys.modules, db.modules()), + unittest.mock.patch.dict(os.environ, env), + contextlib.redirect_stdout(out), + ): + runpy.run_path(str(SCRIPT), run_name="__weblate_shell__") + return out.getvalue() + + +def bindings(db: Database) -> list[tuple[str, str, str, str]]: + return [ + (row.user.username, row.provider, row.uid, row.id_key) + for row in db.UserSocialAuth.objects.rows + ] + + +class TestAdministratorSubjectBinding(unittest.TestCase): + def test_the_bootstrapped_superuser_is_bound_to_the_keycloak_subject(self): + db = Database() + admin = db.user(1, "admin") + self.assertIn("ADOPTED=1", adopt(db)) + self.assertEqual(admin.username, ADMIN) + self.assertEqual( + bindings(db), + [(ADMIN, "oidc", SUBJECT, "sub")], + "Weblate 2026.11 refuses to link the OIDC sign-in to the local " + "administrator by e-mail (email_in_use); social_user must find it " + "through an oidc association on the Keycloak sub instead", + ) + self.assertFalse(admin.usable_password) + + def test_a_second_run_changes_nothing(self): + db = Database() + db.user(1, ADMIN, usable_password=False) + adopt(db) + self.assertIn("ADOPTED=0", adopt(db)) + self.assertEqual(bindings(db), [(ADMIN, "oidc", SUBJECT, "sub")]) + + def test_an_unkeyed_legacy_row_for_the_subject_is_keyed_in_place(self): + db = Database() + admin = db.user(1, ADMIN, usable_password=False) + db.social(admin, SUBJECT, id_key="") + self.assertIn("ADOPTED=1", adopt(db)) + self.assertEqual(bindings(db), [(ADMIN, "oidc", SUBJECT, "sub")]) + + def test_another_account_holding_the_subject_loses_it(self): + db = Database() + db.user(1, ADMIN, usable_password=False) + stray = db.user(2, "platformadmin-old") + db.social(stray, SUBJECT) + self.assertIn("ADOPTED=1", adopt(db)) + self.assertEqual(bindings(db), [(ADMIN, "oidc", SUBJECT, "sub")]) + + def test_a_foreign_subject_on_the_administrator_stops_the_run(self): + db = Database() + admin = db.user(1, ADMIN, usable_password=False) + db.social(admin, OTHER_SUBJECT) + with self.assertRaises(SystemExit) as stop: + adopt(db) + self.assertTrue(str(stop.exception.code).startswith(f"{STOP_MARKER}:")) + self.assertEqual(bindings(db), [(ADMIN, "oidc", OTHER_SUBJECT, "sub")]) + + def test_other_providers_on_the_administrator_are_left_alone(self): + db = Database() + admin = db.user(1, ADMIN, usable_password=False) + db.social(admin, "admin@example.com", id_key="", provider="email") + adopt(db) + self.assertEqual( + sorted(bindings(db)), + [ + (ADMIN, "email", "admin@example.com", ""), + (ADMIN, "oidc", SUBJECT, "sub"), + ], + ) + + def test_sso_without_a_subject_stops_the_run(self): + db = Database() + db.user(1, ADMIN) + with self.assertRaises(SystemExit) as stop: + adopt(db, subject="") + self.assertTrue(str(stop.exception.code).startswith(f"{STOP_MARKER}:")) + self.assertEqual(bindings(db), []) + + def test_without_sso_nothing_is_bound_and_the_password_stays(self): + db = Database() + admin = db.user(1, "admin") + self.assertIn("ADOPTED=1", adopt(db, sso=False, subject="")) + self.assertEqual(bindings(db), []) + self.assertTrue(admin.usable_password) + + +def _tasks(path) -> list[dict]: + return load_yaml_any(str(path), default_if_missing=[]) + + +def _subject_expression() -> str: + for task in _tasks(SUBJECT_TASKS): + if SUBJECT_FACT in task.get("ansible.builtin.set_fact", {}): + return task["ansible.builtin.set_fact"][SUBJECT_FACT] + raise AssertionError(f"no task sets {SUBJECT_FACT}") + + +def pick_subjects(stdout_lines: list[str], username: str = ADMIN) -> list[str]: + templar = Templar( + loader=DataLoader(), + variables={ + "weblate_keycloak_admin_users": {"stdout_lines": stdout_lines}, + "WEBLATE_ADMIN_USERNAME": username, + }, + ) + return templar.template(_trust_as_template(_subject_expression())) + + +class TestKeycloakSubjectSelection(unittest.TestCase): + def test_jvm_warnings_before_the_csv_are_skipped(self): + self.assertEqual( + pick_subjects([JVM_NOISE, f"{SUBJECT},{ADMIN}"]), + [SUBJECT], + ) + + def test_the_administrator_name_is_matched_case_insensitively(self): + self.assertEqual( + pick_subjects([f"{SUBJECT},{ADMIN}"], "PlatformAdmin"), [SUBJECT] + ) + + def test_only_the_exact_username_matches(self): + self.assertEqual( + pick_subjects( + [ + f"{OTHER_SUBJECT},{ADMIN}2", + f"{OTHER_SUBJECT},x{ADMIN}", + f"{OTHER_SUBJECT},other,{ADMIN}", + ] + ), + [], + ) + + def test_the_username_is_not_read_as_a_pattern(self): + self.assertEqual( + pick_subjects([f"{OTHER_SUBJECT},platformXadmin"], "platform.admin"), [] + ) + + def test_two_matches_are_both_reported_for_the_assert(self): + self.assertEqual( + pick_subjects([f"{SUBJECT},{ADMIN}", f"{OTHER_SUBJECT},{ADMIN}"]), + [SUBJECT, OTHER_SUBJECT], + ) + + +class TestSubjectReachesTheShell(unittest.TestCase): + def test_the_keycloak_lookup_is_included_only_with_sso(self): + include = next( + task + for task in _tasks(TOKEN_TASKS) + if task.get("ansible.builtin.include_tasks") == SUBJECT_INCLUDE + ) + self.assertEqual(include["when"], "WEBLATE_OIDC_ENABLED | bool") + self.assertTrue(SUBJECT_TASKS.is_file()) + + def test_the_adopt_task_forwards_the_subject_into_the_container(self): + adopt_task = next( + task + for task in _tasks(TOKEN_TASKS) + if "adopt_admin.py" in str(task.get("ansible.builtin.shell", {})) + ) + self.assertIn( + "-e WEBLATE_ADMIN_OIDC_SUBJECT", adopt_task["ansible.builtin.shell"]["cmd"] + ) + self.assertIn("WEBLATE_ADMIN_OIDC_SUBJECT", adopt_task["environment"]) + self.assertIn( + f"'{STOP_MARKER}' in weblate_admin_adopt.stderr", adopt_task["until"] + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/scripts/tests/deploy/act/test_workflow.py b/tests/unit/python/scripts/tests/deploy/act/test_workflow.py index e5e6c86555..d433a565dc 100644 --- a/tests/unit/python/scripts/tests/deploy/act/test_workflow.py +++ b/tests/unit/python/scripts/tests/deploy/act/test_workflow.py @@ -7,11 +7,13 @@ import tempfile import unittest from pathlib import Path +from cli.meta.env.__main__ import HOST_OWNED_KEY from utils.cache.files import PROJECT_ROOT SCRIPT = PROJECT_ROOT / "scripts" / "tests" / "deploy" / "act" / "workflow.sh" ACT_STUB = '#!/usr/bin/env bash\nprintf \'%s\\0\' "$@" >"${STUB_LOG}"\n' DB_ENV = "INFINITO_VULNERABILITY_DB_HOST_PATH" +HOST_OWNED = f"{HOST_OWNED_KEY}=true" EXTRA_VARS = json.dumps( { "applications": { @@ -23,7 +25,11 @@ EXTRA_VARS = json.dumps( def run_act( - db_host_path: str | None, act_env: str = "" + db_host_path: str | None, + act_env: str = "", + *, + act_bind: str | None = None, + custom_role: bool = False, ) -> tuple[subprocess.CompletedProcess, list[str], Path, bool]: """Run the wrapper against an ``act`` stub that records its argv. @@ -31,6 +37,9 @@ def run_act( db_host_path: value of ``INFINITO_VULNERABILITY_DB_HOST_PATH`` below a scratch directory, or None to leave it unset. act_env: value of ``ACT_ENV``. + act_bind: value of ``ACT_BIND``, or None to leave it unset. + custom_role: run the wrapper from a scratch checkout that holds a + pulled ``roles/web-app-cst-*`` role instead of this repository. Returns: The finished process, the argv act received (one list item per @@ -38,6 +47,14 @@ def run_act( whether it existed afterwards. """ with tempfile.TemporaryDirectory() as tmp: + script = SCRIPT + if custom_role: + root = Path(tmp) / "repo" + (root / "roles" / "web-app-cst-demo").mkdir(parents=True) + (root / ".github" / "workflows").mkdir(parents=True) + script = root / "scripts" / "tests" / "deploy" / "act" / "workflow.sh" + script.parent.mkdir(parents=True) + script.symlink_to(SCRIPT) stub = Path(tmp) / "act" stub.write_text(ACT_STUB) stub.chmod(0o755) @@ -48,8 +65,10 @@ def run_act( env = { k: v for k, v in os.environ.items() - if k not in ("BASH_ENV", DB_ENV, "ACT_CONTAINER_OPTIONS") + if k not in ("BASH_ENV", DB_ENV, "ACT_CONTAINER_OPTIONS", "ACT_BIND") } + if act_bind is not None: + env["ACT_BIND"] = act_bind env.update( PATH=f"{tmp}{os.pathsep}{os.environ['PATH']}", STUB_LOG=str(log), @@ -63,7 +82,7 @@ def run_act( if db_host_path is not None: env[DB_ENV] = str(shared) done = subprocess.run( - ["bash", str(SCRIPT)], + ["bash", str(script)], env=env, capture_output=True, text=True, @@ -99,10 +118,12 @@ def env_items(argv: list[str]) -> list[str]: Returns: Every ``--env`` value in order, without the wrapper's own - ``INFINITO_VULNERABILITY_DB_HOST_PATH`` pin. + ``INFINITO_VULNERABILITY_DB_HOST_PATH`` and host-owned ``.env`` pins. """ return [ - value for value in option(argv, "--env") if not value.startswith(f"{DB_ENV}=") + value + for value in option(argv, "--env") + if not value.startswith(f"{DB_ENV}=") and value != HOST_OWNED ] @@ -165,5 +186,24 @@ class TestActWorkflowEnv(unittest.TestCase): self.assertEqual(items, ["INFINITO_INVENTORY_EXTRA_VARS=", "disable=css"]) +class TestBoundCheckoutKeepsTheHostDotenv(unittest.TestCase): + def test_an_explicit_bind_keeps_the_host_dotenv(self) -> None: + done, argv, _shared, _created = run_act("vulnerability-db", act_bind="true") + self.assertEqual(done.returncode, 0, done.stderr) + self.assertIn("--bind", argv) + self.assertIn(HOST_OWNED, option(argv, "--env")) + + def test_a_bind_for_pulled_custom_roles_keeps_the_host_dotenv(self) -> None: + done, argv, _shared, _created = run_act("vulnerability-db", custom_role=True) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertIn("--bind", argv) + self.assertIn(HOST_OWNED, option(argv, "--env")) + + def test_the_marker_travels_only_with_the_bind(self) -> None: + done, argv, _shared, _created = run_act("vulnerability-db", act_bind="false") + self.assertEqual(done.returncode, 0, done.stderr) + self.assertEqual("--bind" in argv, HOST_OWNED in option(argv, "--env")) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/scripts/tests/deploy/utils/filesystem/test_docker_dataroot.py b/tests/unit/python/scripts/tests/deploy/utils/filesystem/test_docker_dataroot.py index 71e0efd9d5..154227d6c9 100644 --- a/tests/unit/python/scripts/tests/deploy/utils/filesystem/test_docker_dataroot.py +++ b/tests/unit/python/scripts/tests/deploy/utils/filesystem/test_docker_dataroot.py @@ -26,7 +26,8 @@ STUB = ( " id) echo 0 ;;\n" " awk) echo 10 ;;\n" " losetup) echo /dev/infinito-test-loop ;;\n" - " mountpoint) exit 1 ;;\n" + ' mount) touch "${STUB_LOG}.mounted" ;;\n' + ' mountpoint) [ "$2" = /mnt/docker-fs ] && [ -e "${STUB_LOG}.mounted" ] ;;\n' ' zpool) [ "$1" != list ] ;;\n' ' systemctl) [ "$1" != cat ] ;;\n' " python3) cat >/dev/null ;;\n" @@ -39,6 +40,10 @@ STUBBED = ( "mountpoint", "zpool", "zfs", + "mkfs.ext4", + "mkfs.btrfs", + "btrfs", + "mount", "systemctl", "python3", "modprobe", @@ -49,8 +54,10 @@ STUBBED = ( ) -def apply_zfs() -> tuple[subprocess.CompletedProcess, list[list[str]]]: - """Run the zfs path of docker_dataroot.sh against stubs of every host tool. +def apply(fstype: str) -> tuple[subprocess.CompletedProcess, list[list[str]]]: + """ + Args: + fstype: the filesystem the script is asked to put the data root on. Returns: The finished process and the argv of every stubbed call, tool first. @@ -71,7 +78,7 @@ def apply_zfs() -> tuple[subprocess.CompletedProcess, list[list[str]]]: } env.update(PATH=f"{bin_dir}{os.pathsep}{os.environ['PATH']}", STUB_LOG=str(log)) done = subprocess.run( - ["bash", str(SCRIPT), "zfs", "true", "30G", "unit-node"], + ["bash", str(SCRIPT), fstype, "true", "30G", "unit-node"], env=env, capture_output=True, text=True, @@ -83,16 +90,49 @@ def apply_zfs() -> tuple[subprocess.CompletedProcess, list[list[str]]]: class TestDockerDatarootZfs(unittest.TestCase): def test_the_stubbed_zfs_path_applies(self) -> None: - done, _ = apply_zfs() + done, _ = apply("zfs") self.assertEqual(done.returncode, 0, done.stdout + done.stderr) self.assertIn("status=applied-pending-docker", done.stdout) def test_the_pool_returns_freed_blocks_to_the_sparse_image(self) -> None: - _, calls = apply_zfs() + _, calls = apply("zfs") creates = [argv for argv in calls if argv[:2] == ["zpool", "create"]] self.assertEqual(len(creates), 1, calls) self.assertIn(("-o", "autotrim=on"), list(pairwise(creates[0]))) +DISCARD = {"ext4": "discard", "btrfs": "discard=async"} + + +class TestDockerDatarootLoopMount(unittest.TestCase): + def test_the_stubbed_mount_paths_apply(self) -> None: + for fstype in DISCARD: + with self.subTest(fstype=fstype): + done, _ = apply(fstype) + self.assertEqual(done.returncode, 0, done.stdout + done.stderr) + self.assertIn("status=applied-pending-docker", done.stdout) + + def test_the_mount_returns_freed_blocks_to_the_sparse_image(self) -> None: + for fstype, option in DISCARD.items(): + with self.subTest(fstype=fstype): + _, calls = apply(fstype) + mounts = [argv for argv in calls if argv[0] == "mount"] + self.assertEqual(len(mounts), 1, calls) + self.assertIn(("-t", fstype), list(pairwise(mounts[0]))) + self.assertIn(("-o", option), list(pairwise(mounts[0]))) + + +class TestDockerDatarootLoopAttach(unittest.TestCase): + def test_the_loop_bypasses_the_page_cache_of_its_backing_image(self) -> None: + for fstype in (*DISCARD, "zfs"): + with self.subTest(fstype=fstype): + _, calls = apply(fstype) + attaches = [ + argv for argv in calls if argv[0] == "losetup" and "--show" in argv + ] + self.assertEqual(len(attaches), 1, calls) + self.assertIn("--direct-io=on", attaches[0]) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/utils/cache/test_render.py b/tests/unit/python/utils/cache/test_render.py index 559c25f7f0..58290c3ec0 100644 --- a/tests/unit/python/utils/cache/test_render.py +++ b/tests/unit/python/utils/cache/test_render.py @@ -10,6 +10,7 @@ from __future__ import annotations import stat import tempfile import unittest +import unittest.mock as mock from pathlib import Path from utils.cache.hosts import host_records @@ -88,5 +89,42 @@ class TestOllamaRegistry(unittest.TestCase): self.assertNotIn("location /v2/", block) +def _servers(http2: bool | str) -> tuple[list[str], list[str]]: + """Return the TLS and the plain server blocks of the rendered frontend. + + Args: + http2: the value ``WEBSERVER_HTTP2_ENABLED`` is rendered with. + """ + with mock.patch("utils.cache.render._webserver_http2", return_value=http2): + blocks = upstreams_conf().split("server {")[1:] + tls = [block for block in blocks if " ssl;" in block] + return tls, [block for block in blocks if " ssl;" not in block] + + +class TestHttp2(unittest.TestCase): + def test_no_listener_serves_http2_while_the_switch_is_off(self) -> None: + tls, plain = _servers(False) + + self.assertTrue(tls) + self.assertFalse([block for block in tls + plain if "http2" in block]) + + def test_every_tls_listener_serves_http2_once_the_switch_is_on(self) -> None: + tls, _plain = _servers(True) + + self.assertTrue(tls) + self.assertEqual([block for block in tls if "\n\thttp2 on;\n" not in block], []) + + def test_a_string_false_from_extra_vars_keeps_http2_off(self) -> None: + tls, _plain = _servers("false") + + self.assertFalse([block for block in tls if "http2" in block]) + + def test_a_plain_listener_never_serves_http2(self) -> None: + _tls, plain = _servers(True) + + self.assertTrue(plain) + self.assertFalse([block for block in plain if "http2" in block]) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/utils/env/handlers/test_nix_config.py b/tests/unit/python/utils/env/handlers/test_nix_config.py new file mode 100644 index 0000000000..2ea254aee7 --- /dev/null +++ b/tests/unit/python/utils/env/handlers/test_nix_config.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +import os +import unittest +from pathlib import Path +from unittest.mock import patch + +from utils.env.context import BuildContext, EnvBuilder +from utils.env.handlers import nix_config as handler + +_TOKENS_LINE = "access-tokens = github.com=placeholder-not-a-token" +_CALLER = {handler.KEY: f"{_TOKENS_LINE}\naccept-flake-config = true\n"} + + +def _ctx(*, on_gha: bool = False, on_act: bool = False) -> BuildContext: + return BuildContext( + static={}, + static_comments={}, + repo_root=Path("/repo"), + on_gha=on_gha, + on_act=on_act, + ) + + +def _apply(ctx: BuildContext) -> dict[str, str]: + eb = EnvBuilder() + handler.apply(eb, ctx) + return eb.values + + +class TestNixConfigTokenStaysOffTheHost(unittest.TestCase): + @patch.dict(os.environ, _CALLER, clear=False) + def test_a_github_runner_keeps_only_the_access_tokens_line(self) -> None: + self.assertEqual(_apply(_ctx(on_gha=True)), {handler.KEY: _TOKENS_LINE}) + + @patch.dict(os.environ, _CALLER, clear=False) + def test_act_never_writes_the_token(self) -> None: + self.assertNotIn(handler.KEY, _apply(_ctx(on_act=True))) + + @patch.dict(os.environ, _CALLER, clear=False) + def test_a_developer_machine_never_writes_the_token(self) -> None: + self.assertNotIn(handler.KEY, _apply(_ctx())) + + +if __name__ == "__main__": # pragma: no cover + unittest.main() diff --git a/tests/unit/python/utils/roles/applications/test_variant_pins.py b/tests/unit/python/utils/roles/applications/test_variant_pins.py index 7620f24113..86b064d76a 100644 --- a/tests/unit/python/utils/roles/applications/test_variant_pins.py +++ b/tests/unit/python/utils/roles/applications/test_variant_pins.py @@ -180,6 +180,57 @@ class VariantPinTestCase(unittest.TestCase): {"web-app-nextcloud": 3}, ) + def switch_matomo_off(self, *indices: int) -> None: + for index in indices: + self.variants["web-app-nextcloud"][index]["services"]["matomo"] = { + "enabled": False + } + + def test_a_without_target_keeps_dashes_and_underscores(self) -> None: + self.pin_openproject("without-mail_relay-v2") + self.assertEqual( + pins_of("web-app-openproject", roles_dir=self.roles_dir), + {1: {"web-app-nextcloud": "without-mail_relay-v2"}}, + ) + + def test_without_finds_the_one_variant_switching_the_key_off(self) -> None: + self.pin_openproject("without-matomo") + self.switch_matomo_off(2) + self.assertEqual( + self.resolve({"web-app-openproject": 1}), {"web-app-nextcloud": 2} + ) + + def test_without_and_no_candidate_raises(self) -> None: + self.pin_openproject("without-matomo") + with self.assertRaises(VariantPinError) as caught: + self.resolve({"web-app-openproject": 1}) + self.assertIn( + "web-app-nextcloud pins services.matomo to literal false in 0 variants " + "(none)", + str(caught.exception), + ) + + def test_without_and_two_candidates_raises(self) -> None: + self.pin_openproject("without-matomo") + self.switch_matomo_off(1, 2) + with self.assertRaises(VariantPinError) as caught: + self.resolve({"web-app-openproject": 1}) + self.assertIn( + "web-app-nextcloud pins services.matomo to literal false in 2 variants " + "([1, 2])", + str(caught.exception), + ) + + def test_a_without_pin_conflicting_with_an_index_pin_raises(self) -> None: + self.pin_openproject("without-matomo") + self.switch_matomo_off(2) + self.pin_gitlab("3") + with self.assertRaises(VariantPinConflictError) as caught: + self.resolve({"web-app-openproject": 1, "web-app-gitlab": 0}) + self.assertIn( + "cannot deploy web-app-nextcloud in two variants", str(caught.exception) + ) + def test_an_index_pin_and_a_reciprocal_pin_agreeing_do_not_conflict(self) -> None: self.pin_openproject("reciprocal") self.pin_gitlab("3") diff --git a/utils/cache/render.py b/utils/cache/render.py index 8e041f6737..e8e888f917 100644 --- a/utils/cache/render.py +++ b/utils/cache/render.py @@ -33,6 +33,7 @@ if TYPE_CHECKING: ROLE = "svc-cache-package" ROLE_DIR = PROJECT_ROOT / "roles" / ROLE ROLE_VARS = ROLE_DIR / ROLE_FILE_VARS_MAIN +WEBSERVER_VARS = PROJECT_ROOT / "group_vars" / "all" / "04_webserver.yml" TEMPLATE_DIRS = (ROLE_DIR / "templates", PROJECT_ROOT / "compose" / "templates") UPSTREAMS_TEMPLATE = "upstreams.conf.j2" CONSUMER_TEMPLATE = "cache-consumer.yml.jinja" @@ -92,10 +93,15 @@ def _render(template: str, **context) -> str: return env.get_template(template).render(**context) +def _webserver_http2() -> bool: + return load_yaml_any(str(WEBSERVER_VARS))["WEBSERVER_HTTP2_ENABLED"] + + def upstreams_conf() -> str: """Return the nginx frontend configuration the declarations produce.""" return _render( UPSTREAMS_TEMPLATE, + WEBSERVER_HTTP2_ENABLED=_webserver_http2(), CACHE_PACKAGE_UPSTREAMS=list(host_records().values()), CACHE_PACKAGE_REPOS=repo_records(), CACHE_PACKAGE_BACKEND=BACKEND, diff --git a/utils/env/handlers/nix_config.py b/utils/env/handlers/nix_config.py index a56d12f4c7..07df642a86 100644 --- a/utils/env/handlers/nix_config.py +++ b/utils/env/handlers/nix_config.py @@ -1,10 +1,15 @@ -"""NIX_CONFIG: pass-through of the caller's access-tokens line, when present. +"""NIX_CONFIG: pass-through of the caller's access-tokens line on a GitHub runner. `.env` is consumed by bash `source` and docker-compose `--env-file`, neither of which round-trips multi-line values; the writer therefore rejects them. Other NIX_CONFIG settings (`accept-flake-config`, `experimental-features`, â€Ļ) belong in `/etc/nix/nix.conf` (Dockerfile injects them inside the dev container; host operators set them once in `~/.config/nix/nix.conf`). + +Only a GitHub Actions runner gets the line: there the token is the job's +short-lived GITHUB_TOKEN. Under act or on a developer machine it is the +operator's own long-lived token, and `.env` would keep it in plaintext in the +host checkout. """ from __future__ import annotations @@ -16,10 +21,12 @@ if TYPE_CHECKING: from utils.env.context import BuildContext, EnvBuilder KEY = "NIX_CONFIG" -COMMENT = "Pass-through of the caller's NIX_CONFIG access-tokens line, when present." +COMMENT = "The caller's NIX_CONFIG access-tokens line, on a GitHub runner only." def apply(eb: EnvBuilder, ctx: BuildContext) -> None: + if not ctx.on_gha: + return nix_config = os.environ.get("NIX_CONFIG", "") access_tokens_line = next( ( diff --git a/utils/roles/applications/variant_pins.py b/utils/roles/applications/variant_pins.py index 43eaef1fb5..31a0da7a27 100644 --- a/utils/roles/applications/variant_pins.py +++ b/utils/roles/applications/variant_pins.py @@ -1,4 +1,4 @@ -"""Variant pins: ``# variant-pin: #``. +"""Variant pins: ``# variant-pin: #>``. A matrix round hands every role the round index, clamping to variant 0 when the role has fewer entries (:func:`services_overrides_for_round`). A pairing @@ -40,12 +40,14 @@ from utils.cache.yaml import load_yaml_any from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_META_VARIANTS PIN = re.compile( - r"#\s*variant-pin:\s*([a-z0-9][a-z0-9-]*)\s*#\s*(\d+|reciprocal)\b", + r"#\s*variant-pin:\s*([a-z0-9][a-z0-9-]*)\s*#\s*" + r"(\d+|reciprocal|without-[a-z0-9_-]+)\b", re.IGNORECASE, ) _GROUP_MEMBERSHIP = re.compile(r"'([a-z0-9][a-z0-9-]*)'\s+in\s+group_names") RECIPROCAL = "reciprocal" +WITHOUT = "without-" class VariantPinError(ValueError): @@ -115,6 +117,18 @@ def _reciprocal_key(partner: str, role: str, *, roles_dir: str) -> str | None: return None +def _variants_setting( + partner: str, key: str, enabled: bool, *, variants_per_app: Mapping[str, list] +) -> list[int]: + return [ + index + for index, variant in enumerate(variants_per_app.get(partner) or []) + if isinstance(variant, Mapping) + and isinstance((variant.get("services") or {}).get(key), Mapping) + and (variant["services"][key]).get("enabled") is enabled + ] + + def _reciprocal_index( partner: str, role: str, @@ -128,13 +142,7 @@ def _reciprocal_index( f"{role} pins {partner}#reciprocal, but {partner}'s " f"{ROLE_FILE_META_SERVICES} declares no service gating on {role}" ) - hits = [ - index - for index, variant in enumerate(variants_per_app.get(partner) or []) - if isinstance(variant, Mapping) - and isinstance((variant.get("services") or {}).get(key), Mapping) - and (variant["services"][key]).get("enabled") is True - ] + hits = _variants_setting(partner, key, True, variants_per_app=variants_per_app) if len(hits) != 1: raise VariantPinError( f"{role} pins {partner}#reciprocal, but {partner} pins " @@ -144,6 +152,54 @@ def _reciprocal_index( return hits[0] +def _without_index( + partner: str, key: str, role: str, *, variants_per_app: Mapping[str, list] +) -> int: + hits = _variants_setting(partner, key, False, variants_per_app=variants_per_app) + if len(hits) != 1: + raise VariantPinError( + f"{role} pins {partner}#{WITHOUT}{key}, but {partner} pins " + f"services.{key} to literal false in {len(hits)} variants " + f"({hits or 'none'}); {WITHOUT} needs exactly one" + ) + return hits[0] + + +def intended_index( + partner: str, + role: str, + target: str, + *, + roles_dir: str, + variants_per_app: Mapping[str, list], +) -> int: + """ + Args: + partner: the pinned role. + role: the carrier role. + target: the pin target, an index, ``reciprocal`` or ``without-``. + roles_dir: the roles tree the partner's services are read from. + variants_per_app: parsed variants per role. + + Returns: + The single variant ``without-`` resolves to; for every other + target, the variant that switches *role* back on. + + Raises: + VariantPinError: the target resolves to no variant or to several. + """ + if target.startswith(WITHOUT): + return _without_index( + partner, + target.removeprefix(WITHOUT), + role, + variants_per_app=variants_per_app, + ) + return _reciprocal_index( + partner, role, roles_dir=roles_dir, variants_per_app=variants_per_app + ) + + def resolve_pins( active_index: Mapping[str, int], *, @@ -171,20 +227,21 @@ def resolve_pins( pins_of(role, roles_dir=roles_dir).get(index, {}).items() ): count = len(variants_per_app.get(partner) or []) - if target == RECIPROCAL: - wanted = _reciprocal_index( - partner, - role, - roles_dir=roles_dir, - variants_per_app=variants_per_app, - ) - else: + if target.isdigit(): wanted = int(target) if not 0 <= wanted < count: raise VariantPinError( f"{role}#{index} pins {partner}#{wanted}, but {partner} " f"declares {count} variant(s)" ) + else: + wanted = intended_index( + partner, + role, + target, + roles_dir=roles_dir, + variants_per_app=variants_per_app, + ) if partner in resolved and resolved[partner] != wanted: raise VariantPinConflictError( f"{source[partner]} pins {partner}#{resolved[partner]} while "