diff --git a/.github/workflows/call-test-deploy.yml b/.github/workflows/call-test-deploy.yml index 2d8ff9a3fa..30f05ece8f 100644 --- a/.github/workflows/call-test-deploy.yml +++ b/.github/workflows/call-test-deploy.yml @@ -265,8 +265,6 @@ jobs: name: ๐Ÿ”ฌ Vulnerability databases runs-on: ubuntu-26.04 timeout-minutes: 60 - outputs: - day: ${{ steps.day.outputs.day }} steps: - uses: actions/checkout@v7.0.0 @@ -298,7 +296,7 @@ jobs: uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: build/vulnerability-db/osv - key: vulnerability-db-osv-${{ steps.day.outputs.day }} + key: vulnerability-db-osv-${{ steps.day.outputs.day }}-${{ hashFiles('roles/sys-ctl-hlth-runtime/meta/services.yml') }} - name: ๐Ÿ”ง Set up Python if: ${{ !env.ACT && (steps.trivy.outputs.cache-hit != 'true' || steps.grype.outputs.cache-hit != 'true' || steps.osv.outputs.cache-hit != 'true') }} @@ -322,6 +320,36 @@ jobs: # shellcheck disable=SC2086 python -m cli.contributing.security.database --dir build/vulnerability-db --engines ${MISSING} + - name: ๐Ÿ“ค Hand the Trivy database to this run's deploy jobs + if: ${{ !env.ACT }} + uses: actions/upload-artifact@v7.0.1 + with: + name: vulnerability-db-${{ inputs.index }}-trivy + path: build/vulnerability-db/trivy + if-no-files-found: error + retention-days: 3 + overwrite: true + + - name: ๐Ÿ“ค Hand the Grype database to this run's deploy jobs + if: ${{ !env.ACT }} + uses: actions/upload-artifact@v7.0.1 + with: + name: vulnerability-db-${{ inputs.index }}-grype + path: build/vulnerability-db/grype + if-no-files-found: error + retention-days: 3 + overwrite: true + + - name: ๐Ÿ“ค Hand the OSV database to this run's deploy jobs + if: ${{ !env.ACT }} + uses: actions/upload-artifact@v7.0.1 + with: + name: vulnerability-db-${{ inputs.index }}-osv + path: build/vulnerability-db/osv + if-no-files-found: error + retention-days: 3 + overwrite: true + deploy: name: "${{ matrix.label }}" if: needs.discover.outputs.apps != '' && needs.discover.outputs.apps != '[]' @@ -386,19 +414,17 @@ jobs: - name: "๐Ÿ‡ Restore the Grype database" if: ${{ !env.ACT && matrix.engine != '' }} - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + uses: actions/download-artifact@v8 with: + name: vulnerability-db-${{ inputs.index }}-grype path: build/vulnerability-db/grype - key: vulnerability-db-grype-${{ needs.vulnerability-db.outputs.day }} - fail-on-cache-miss: true - name: "๐Ÿ”ฌ Restore the ${{ matrix.engine }} database" if: ${{ !env.ACT && matrix.engine != '' && matrix.engine != 'grype' }} - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + uses: actions/download-artifact@v8 with: + name: vulnerability-db-${{ inputs.index }}-${{ matrix.engine }} path: build/vulnerability-db/${{ matrix.engine }} - key: vulnerability-db-${{ matrix.engine }}-${{ needs.vulnerability-db.outputs.day }} - fail-on-cache-miss: true - name: "๐Ÿ”ฌ Pin the deploy to the restored databases" if: ${{ !env.ACT }} diff --git a/cli/contributing/security/README.md b/cli/contributing/security/README.md index 7736b4c723..58a3aa7957 100644 --- a/cli/contributing/security/README.md +++ b/cli/contributing/security/README.md @@ -4,7 +4,7 @@ Repository-side vulnerability tooling over the pinned role images, built on the | Command | What it does | |---|---| -| `make test-security` | Runs `scan`: Syft builds an SBOM of every pinned image straight from the GHCR mirror, cached by digest under `build/security/sbom`, and Trivy, Grype and OSV scan that SBOM tree with the role's threshold and suppressions. Every finding at the threshold goes to `build/test-reports/security.json`, a suppressed one with its `suppressed_until` day; the scan fails only on the unsuppressed ones. | +| `make test-security` | Runs `scan`: Syft builds an SBOM of every pinned image straight from the GHCR mirror, cached by digest under `build/security/sbom`, and Trivy, Grype and OSV scan that SBOM tree with the role's threshold and suppressions. Every finding at the threshold goes to `build/test-reports/security.json`, a suppressed one with its `suppressed_until` day. The scan fails only on an engine or mirror error; the unsuppressed findings reach the vulnerability issues instead. | | `python -m cli.contributing.security.database --dir --engines ...` | Downloads the Trivy, Grype and OSV databases a CI deploy reads. | | `python -m cli.contributing.security.summary --report --counts --summary ` | Counts the failing findings of the report per image and per CVE, plus the suppressed total, into a JSON file and appends the tables to a Markdown summary. | | `python -m cli.contributing.security.issues --report --repo ` | Opens one `vulnerability` issue per image of the report that lists its CVEs, suppressed ones with their `suppressed_until` day, updates it while it stays, and closes it once no engine reports a CVE for the image. The head line counts the CVEs per severity. | diff --git a/cli/contributing/security/scan/__main__.py b/cli/contributing/security/scan/__main__.py index b77a7c4ff8..b17b06fb10 100755 --- a/cli/contributing/security/scan/__main__.py +++ b/cli/contributing/security/scan/__main__.py @@ -124,7 +124,7 @@ def sbom_step(p: ModuleType, layout, target, source: str): ) -def trivy_step(p: ModuleType, layout, target): +def trivy_step(p: ModuleType, layout, target, os_args: Sequence[str]): args = [ "sbom", *p.TRIVY_COMMON, @@ -134,6 +134,7 @@ def trivy_step(p: ModuleType, layout, target): "memory", "--scanners", "vuln", + *os_args, "--format", "json", "--output", @@ -221,9 +222,11 @@ def scan_tree( ready = [target for target in targets if target.key not in failed] lanes = [] + today = dt.datetime.now(tz=dt.UTC).date() for target in ready: if "trivy" in scanners: - lanes.append([trivy_step(p, layout, target)]) + os_args = p.trivy_os_args(layout, target, scanners, config, today) + lanes.append([trivy_step(p, layout, target, os_args)]) if "grype" in scanners: lanes.append([grype_step(p, layout, target)]) if "osv" in scanners and ready: @@ -312,7 +315,8 @@ def failing(rows: Sequence[Mapping[str, Any]]) -> list[Mapping[str, Any]]: def scan_config(p: ModuleType, workers: int): - runtime = role_services()["runtime"] + services = role_services() + runtime = services["runtime"] return p.scan_config( { "targets": ["container"], @@ -321,6 +325,7 @@ def scan_config(p: ModuleType, workers: int): "fixed_only": runtime["fixed_only"], "workers": workers, "db_update": True, + "trivy_unmatched_os": services["trivy"]["unmatched_os"], } ) @@ -401,7 +406,7 @@ def main(argv=None) -> int: f"{len(failures)} failing and {len(rows) - len(failures)} suppressed " f"finding(s), {len(errors)} error(s)" ) - return 1 if failures or errors else 0 + return 1 if errors else 0 if __name__ == "__main__": diff --git a/cli/contributing/update/README.md b/cli/contributing/update/README.md index dd6fa1823c..7e8f2f564c 100644 --- a/cli/contributing/update/README.md +++ b/cli/contributing/update/README.md @@ -48,8 +48,15 @@ it. Types: on Docker Hub), `strip: true` removes it again so a pin without the upstream's `v` stays without it. +A pin whose asset is fetched by digest names its companion checksum beside the +type (`checksum_key`, `checksum_url`), see +[checksum.py](../../../utils/update/checksum.py). + A `repository` + `ref` pin that declares a source with `key: ref` is bumped -from that source alone, the repository updater skips it. +from that source alone, the repository updater skips it. A bump to a name the +repository lists as neither branch nor tag +(`git ls-remote refs/heads/ refs/tags/`), or one that +lookup cannot confirm, is withheld and reported on stderr. An `http_regex` source with a `template` fills it with the pattern's named groups instead of taking the first group, for a tag built from several upstream @@ -60,7 +67,7 @@ freeswitch: version: "v1.10.12-v3.0.23" update: type: http_regex - url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + url: https://raw.githubusercontent.com/bigbluebutton/docker/main/repos/tags pattern: 'repos/bigbluebutton (?Pv[0-9.]+)\nrepos/freeswitch (?Pv[0-9.]+)' template: "{freeswitch}-{bbb}" ``` diff --git a/default.env b/default.env index 60b1af7dae..48ce2bb018 100644 --- a/default.env +++ b/default.env @@ -58,6 +58,9 @@ INFINITO_BUILD=1 # `1` keeps BuildKit on (default); `0` forces the compose wrapper to use the legacy builder. INFINITO_BUILDKIT_ENABLED=1 +# Cap of the host Docker build cache; every image build ends with a builder prune that keeps at most this much. +INFINITO_BUILD_CACHE_MAX_SIZE=20g + # Pacman cache an arch stack mounts read-only at the same path; from pacman-conf on a host whose os-release ID is arch, else empty. INFINITO_CACHE_HOST_PACMAN_PATH= diff --git a/docs/contributing/actions/testing/suppression.md b/docs/contributing/actions/testing/suppression.md index 1c86d0d4b2..c677c7ec09 100644 --- a/docs/contributing/actions/testing/suppression.md +++ b/docs/contributing/actions/testing/suppression.md @@ -44,7 +44,7 @@ The placement rule is per check. The catalog "Position" column uses these labels | Rule | Position | Affected test | Effect | | --------------------------- | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `url` | same or above, `entry block` in `.po` | [test_urls_reachable.py](../../../../tests/external/repository/test_urls_reachable.py) | Skips probing the literal HTTP(S) URL. Use for CDN roots and API base URLs that 4xx without a path. | +| `url` | same or above, `entry block` in `.po` | [test_urls_reachable.py](../../../../tests/external/repository/test_urls_reachable.py) | Skips probing the literal HTTP(S) URL. Use for CDN roots and API base URLs that 4xx without a path. A `.po` catalog is generated from the sources and cannot carry their markers, so a catalog occurrence of a URL is skipped too when a line outside the catalogs suppresses it. | | `onion-flag` | same or above | [test_onion_port_flag.py](../../../../tests/lint/ansible/services/test_onion_port_flag.py) | Accepts a `false` under `ports.onion`. The marker MUST carry a reason naming why that port stays off the node onion; a bare marker is rejected. | | `network-reachability` | same or above | [test_network_reachability.py](../../../../tests/lint/ansible/roles/meta/test_network_reachability.py) | Accepts `reachability.single_mode: true`, `reachability.handover: true`, or a `reachability.modes` list below every network, in `meta/networks.yml`. The marker MUST carry a reason naming why the role is not served on every network; a bare marker is rejected. | | `inventory-open-subtree` | same line, or a comment line directly above the key | [applications.py](../../../../cli/administration/inventory/validate/applications.py), [test_inventory_open_subtree.py](../../../../tests/lint/ansible/services/test_inventory_open_subtree.py) | Lets the inventory validator accept any child key the inventory sets under the marked `meta/services.yml` mapping key; every other key stays checked against the role defaults. The marker MUST carry a reason of at least 10 characters; a bare marker, a marker on a scalar, inside a list or on no key opens nothing and is rejected by the lint. The role MUST validate the opened values itself at deploy time. | diff --git a/docs/requirements/070-hlth-runtime-vulnerability-engines.md b/docs/requirements/070-hlth-runtime-vulnerability-engines.md index f2cf64d608..d7a9a272e6 100644 --- a/docs/requirements/070-hlth-runtime-vulnerability-engines.md +++ b/docs/requirements/070-hlth-runtime-vulnerability-engines.md @@ -2,7 +2,7 @@ ## User Story -As an operator, I want every node to scan its host and its running container images with Trivy, Grype and OSV-Scanner over a Syft SBOM, so that a real, fixable vulnerability is reported, and the daily mirror scan fails on it, instead of a deploy failing on a distribution build whose upstream version number looks old. +As an operator, I want every node to scan its host and its running container images with Trivy, Grype and OSV-Scanner over a Syft SBOM, so that a real, fixable vulnerability is reported, and the daily mirror scan tracks it as an issue, instead of a deploy failing on a distribution build whose upstream version number looks old. Issue: [#1324](https://github.com/infinito-nexus/core/issues/1324). @@ -19,7 +19,7 @@ Issue: [#1324](https://github.com/infinito-nexus/core/issues/1324). - [ ] A runtime built from source, such as PHP 8.4.26 in an official `php` image, fails the scan with the CRITICAL CVE-2026-109618 and warns on the HIGH CVE-2026-109619, both fixed in 8.4.27: only Grype sees it, through the CPE of Syft's binary classifier, so with `syft` in `engines` and `grype` not, Grype still scans the binary-classified packages of every SBOM, and a configuration with neither `grype` nor `syft` is rejected. - [ ] Targets times engines run in parallel, bounded by `workers`; Trivy runs one target at a time and OSV-Scanner reads every SBOM in one run. - [ ] Each engine's JSON becomes findings of engine, target, image or host, package, installed version, fixed version, vulnerability ids and severity; OSV maps the group's CVSS score to a severity and takes the fixed version from the affected ranges of the same package. -- [ ] An unsuppressed finding whose severity maps to `fail` is a `โŒ` line naming engine, target and CVE and fails `sys-ctl-hlth-runtime.service`, the deploy through `sys-service-terminator` and the OnFailure alert; one that maps to `warn` is a `โš ๏ธ` line and does not fail the service; a suppressed one is an `โ„น๏ธ` line. Production keeps the shipped mapping. The development inventory that `INFINITO_INVENTORY_VARS_FILE` names, which every CI and local development deploy provisions, maps `CRITICAL` to `warn` under `applications.sys-ctl-hlth-runtime.services.runtime.severity`, so there a CRITICAL finding is a `โš ๏ธ` line and a `warn` record, fails neither the service nor the deploy, and reaches a `vulnerability` issue through the daily mirror scan below; no deploy variant overrides the mapping. An engine error, a missing database or a PHP hardening violation fails the service too. The daily `scan` job of `cron-images-mirror-all.yml` fails on every unsuppressed mapped finding, `fail` and `warn` alike. +- [ ] An unsuppressed finding whose severity maps to `fail` is a `โŒ` line naming engine, target and CVE and fails `sys-ctl-hlth-runtime.service`, the deploy through `sys-service-terminator` and the OnFailure alert; one that maps to `warn` is a `โš ๏ธ` line and does not fail the service; a suppressed one is an `โ„น๏ธ` line. Production keeps the shipped mapping. The development inventory that `INFINITO_INVENTORY_VARS_FILE` names, which every CI and local development deploy provisions, maps `CRITICAL` to `warn` under `applications.sys-ctl-hlth-runtime.services.runtime.severity`, so there a CRITICAL finding is a `โš ๏ธ` line and a `warn` record, fails neither the service nor the deploy, and reaches a `vulnerability` issue through the daily mirror scan below; no deploy variant overrides the mapping. An engine error, a missing database or a PHP hardening violation fails the service too. The daily `scan` job of `cron-images-mirror-all.yml` reports every unsuppressed mapped finding, `fail` and `warn` alike, as a `vulnerability` issue and fails only on an engine or mirror error. - [ ] Every finding at the threshold becomes one record per owner with `run_id`, `timestamp` (RFC 3339, UTC), `host`, `environment`, `target`, `kind`, `image` (`@` for a container, the host name for the host), `scanner`, `id`, `severity`, `package`, `installed_version`, `fixed_version`, `suppressed`, `suppressed_until` and `verdict` (`fail`, `warn` or `suppressed`), and the four outputs below are built from these records. - [ ] `report.json` in `DIR_HEALTH_RUNTIME_REPORT` (`/var/lib/infinito/hlth-runtime`) holds the summary and the records of the last run and is replaced atomically. - [ ] `findings.jsonl` in `DIR_HEALTH_RUNTIME_LOG` (`/var/log/infinito/hlth-runtime`) gets one JSON line per record on every run, appended; the role installs logrotate and a drop-in that rotates it weekly, keeps 12 compressed generations and skips a missing or empty file. @@ -37,7 +37,7 @@ Issue: [#1324](https://github.com/infinito-nexus/core/issues/1324). - [ ] A local development deploy (`make compose-deploy`, swarm through act or `make swarm-zombie`) draws one engine at random, runs it behind Syft plus the Grype runtime pass, refreshes the databases it reads once in the shared host directory `INFINITO_VULNERABILITY_DB_HOST_PATH`, and every stack and swarm node reads that directory read-only at `INFINITO_VULNERABILITY_DB_DIR`; no stack and no node downloads a database. - [ ] Production hosts run every engine of the list and refresh their databases daily in their own cache. - [ ] The deploy-time run fails on its first failure: `sys-service-terminator` does not retry a unit that sets `system_service_run_once`, and only the database refresh inside the scan is retried, three attempts 30 s apart. -- [ ] The threshold is strict from the first run: in production a CRITICAL with a fix fails the check and a HIGH with a fix warns, a development or CI deploy warns on both, and both fail the daily mirror scan, which tracks them as `vulnerability` issues. +- [ ] The threshold is strict from the first run: in production a CRITICAL with a fix fails the check and a HIGH with a fix warns, a development or CI deploy warns on both, and the daily mirror scan tracks both as `vulnerability` issues. - [ ] `make test-security` builds a Syft SBOM of every pinned image of all roles straight from the GHCR mirror refs, cached by image digest, and scans that SBOM tree with Trivy, Grype and OSV at the same threshold and suppressions; it is not part of `make test`, and the alias `i8seru` runs it. - [ ] The `scan` job of `cron-images-mirror-all.yml` runs after `sync`, runs `make test-security`, keeps exactly one open `vulnerability` issue per image that lists its CVEs (unsuppressed first, then CRITICAL first, suppressed ones with their `suppressed_until` day so the issue stays open while a suppression runs, capped below GitHub's body limit with a pointer to the artifact) and closes any further open one as a duplicate, comments the still unresolved CVEs into it and updates its body whenever the image's CVE table changed, leaves it alone while the table is unchanged, closes it once no engine reports any CVE for it, holds `issues: write` only on that job and pins its actions like the existing jobs. - [ ] Every run of that job writes the failing findings per image and per CVE into the job summary and the `vulnerability-findings` artifact, and the `workflow_dispatch` input `issues: false` makes it a dry run without issue changes; the schedule keeps the issues on. diff --git a/meta/packages.yml b/meta/packages.yml index 9b41831722..4712a5ae22 100644 --- a/meta/packages.yml +++ b/meta/packages.yml @@ -28,7 +28,10 @@ blender: Archlinux: - - blender + names: + - blender + architectures: + - amd64 Debian: - blender centos: diff --git a/roles/dsk-gnt-claude/meta/services.yml b/roles/dsk-gnt-claude/meta/services.yml index 8fd339ea04..f77c6df408 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.324 + npm_version: 2.1.325 update: key: npm_version type: npm diff --git a/roles/dsk-gnt-cursor/README.md b/roles/dsk-gnt-cursor/README.md index dedbb438f1..1a03e3c367 100644 --- a/roles/dsk-gnt-cursor/README.md +++ b/roles/dsk-gnt-cursor/README.md @@ -13,4 +13,5 @@ The role therefore installs the editor and leaves the endpoint override to the o ## Features - **Installed, not faked:** the editor is provisioned; the endpoint override stays a documented operator step. -- **Arch today:** the vendor ships neither a Debian nor an RPM repository, so only the Arch build is wired up. +- **Pinned on every distribution:** Arch installs the AUR build; Debian and RedHat install the vendor's pinned `.deb` or `.rpm` by checksum. +- **No vendor repository left behind:** both packages register the vendor's APT or DNF repository on install; the role removes it again, so system updates never depend on it and never move Cursor past the pin. diff --git a/roles/dsk-gnt-cursor/meta/packages.yml b/roles/dsk-gnt-cursor/meta/packages.yml index f64756824d..01953a2f19 100644 --- a/roles/dsk-gnt-cursor/meta/packages.yml +++ b/roles/dsk-gnt-cursor/meta/packages.yml @@ -11,6 +11,9 @@ cursor: download: url: https://downloads.cursor.com/production/f7119520544accb8dcf6d27119b9f1963d8ee5ae/linux/x64/deb/amd64/deb/cursor_3.27.6_amd64.deb checksum: sha256:cf5f443556a5ac5cbf308eeae8f33e44ea34e5421a6910b1c34f977c2541e67f + repo_files: + - /etc/apt/sources.list.d/cursor.list + - /etc/apt/sources.list.d/cursor.sources RedHat: source: download names: @@ -18,3 +21,5 @@ cursor: download: url: https://downloads.cursor.com/production/f7119520544accb8dcf6d27119b9f1963d8ee5ae/linux/x64/rpm/x86_64/cursor-3.27.6.el8.x86_64.rpm checksum: sha256:f06d4f18f16a843fb94f9124692745857bc2e52ae8d33f26491fbf81b4072d02 + repo_files: + - /etc/yum.repos.d/cursor.repo diff --git a/roles/dsk-virtualbox/meta/info.yml b/roles/dsk-virtualbox/meta/info.yml index 779bc05578..b4ed922e02 100644 --- a/roles/dsk-virtualbox/meta/info.yml +++ b/roles/dsk-virtualbox/meta/info.yml @@ -1,3 +1,3 @@ --- -homepage: https://www.virtualbox.org/ +homepage: https://www.virtualbox.org/ # nocheck: url Reason: Oracle answers GitHub runner IPs with HTTP 410; the page answers 200 directly video: https://www.youtube.com/watch?v=RvlfEKRkQfM diff --git a/roles/dsk-virtualbox/meta/license.yml b/roles/dsk-virtualbox/meta/license.yml index f90972b496..7111fcc950 100644 --- a/roles/dsk-virtualbox/meta/license.yml +++ b/roles/dsk-virtualbox/meta/license.yml @@ -1,6 +1,6 @@ --- spdx: LicenseRef-Oracle-VirtualBox-PUEL -url: https://www.virtualbox.org/wiki/VirtualBox_PUEL +url: https://www.virtualbox.org/wiki/VirtualBox_PUEL # nocheck: url Reason: Oracle answers GitHub runner IPs with HTTP 410; the page answers 200 directly rights: commercial_use: false modifications: false diff --git a/roles/pkgmgr/meta/services.yml b/roles/pkgmgr/meta/services.yml index f075a1e92e..1f8a1c08a7 100644 --- a/roles/pkgmgr/meta/services.yml +++ b/roles/pkgmgr/meta/services.yml @@ -3,4 +3,4 @@ pkgmgr: lifecycle: beta repository: https://github.com/kevinveenbirkenbach/package-manager.git - ref: v2.4.0 + ref: v2.5.0 diff --git a/roles/svc-ai-lmstudio/meta/services.yml b/roles/svc-ai-lmstudio/meta/services.yml index a128bfa0a6..03d6dbd02b 100644 --- a/roles/svc-ai-lmstudio/meta/services.yml +++ b/roles/svc-ai-lmstudio/meta/services.yml @@ -14,7 +14,7 @@ lmstudio: backup: stop_required: false image: ubuntu - version: "22.04" + version: "26.10" custom: true app_version: 0.0.27-1 update: diff --git a/roles/sys-ctl-hlth-runtime/README.md b/roles/sys-ctl-hlth-runtime/README.md index 8b0fd93533..4a4217e449 100644 --- a/roles/sys-ctl-hlth-runtime/README.md +++ b/roles/sys-ctl-hlth-runtime/README.md @@ -6,7 +6,7 @@ This role scans the node it runs on for known vulnerabilities with [Trivy](https ## Overview -The role installs a check script with a `systemd` service and a timer at 00:00 UTC, and the deploy runs it once at its end. `severity` maps each reported severity to `fail` or `warn`: an unsuppressed finding mapped to `fail` fails the check, one mapped to `warn` is a `โš ๏ธ` line, a suppressed one an `โ„น๏ธ` line. The check also fails, and the failure notifier from [`sys-ctl-alm-compose`](../sys-ctl-alm-compose/README.md) alerts, when an engine or its database fails, or when a service that declares `php_hardening` in its `meta/volumes.yml` still reports `expose_php` or `session.upload_progress.enabled` as on. The daily mirror scan of `cron-images-mirror-all.yml` fails on every mapped finding, `fail` and `warn` alike, and tracks them as issues; the findings of every `main` deploy become `vulnerability-runtime` issues, see [README.md](../../cli/contributing/security/README.md). The scan configuration and the engine pins live in [services.yml](./meta/services.yml). +The role installs a check script with a `systemd` service and a timer at 00:00 UTC, and the deploy runs it once at its end. `severity` maps each reported severity to `fail` or `warn`: an unsuppressed finding mapped to `fail` fails the check, one mapped to `warn` is a `โš ๏ธ` line, a suppressed one an `โ„น๏ธ` line. The check also fails, and the failure notifier from [`sys-ctl-alm-compose`](../sys-ctl-alm-compose/README.md) alerts, when an engine or its database fails, or when a service that declares `php_hardening` in its `meta/volumes.yml` still reports `expose_php` or `session.upload_progress.enabled` as on. The daily mirror scan of `cron-images-mirror-all.yml` tracks every mapped finding, `fail` and `warn` alike, as issues and fails only on an engine or mirror error; the findings of every `main` deploy become `vulnerability-runtime` issues, see [README.md](../../cli/contributing/security/README.md). The scan configuration and the engine pins live in [services.yml](./meta/services.yml). ## Cosmos @@ -29,7 +29,7 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( - **Targets:** `container` scans the image of every running container through the read-only Docker socket, `host` scans the host root filesystem mounted read-only. In swarm every node scans itself. - **Engine runtime:** An engine run that reads the host Docker socket runs on `runc`, also on a swarm worker that [`svc-virt-kata`](../svc-virt-kata/README.md) defaults to gVisor or Kata, because those runtimes refuse the bind-mounted socket and every container scan would fail there. Every other engine run, the host scan included, keeps the node's default runtime. -- **Engines:** Syft builds one SBOM per target, Grype and OSV-Scanner read it, Trivy reads the target itself. Without `syft` in `engines`, Grype and OSV-Scanner read the target directly; `osv` then scans containers only. +- **Engines:** Syft builds one SBOM per target, Grype and OSV-Scanner read it, Trivy reads the target itself. Without `syft` in `engines`, Grype and OSV-Scanner read the target directly; `osv` then scans containers only. While Grype runs, Trivy leaves the OS packages of every OS release listed under `trivy.unmatched_os` to Grype until the entry's `until`, because Trivy matches no Red Hat advisory for CentOS Stream 10 and Red Hat Enterprise Linux 10 yet and fails with `unable to find CPE indices`, see [aquasecurity/trivy-db#435](https://github.com/aquasecurity/trivy-db/issues/435) and [aquasecurity/trivy#7452](https://github.com/aquasecurity/trivy/issues/7452). - **Source-built runtimes:** A runtime compiled into the image, such as the PHP of the official `php` images, is matched by Grype only. With `syft` but without `grype` in `engines`, Grype still scans the binary-classified packages of every SBOM. - **Threshold:** `severity` maps each reported severity to `fail` or `warn`, `{CRITICAL: fail, HIGH: warn}` by default and in production. The development inventory that `INFINITO_INVENTORY_VARS_FILE` names maps `CRITICAL` to `warn`, so a CI or development deploy reports a CRITICAL finding as a `โš ๏ธ` line and a `warn` record without failing, and the daily mirror scan tracks it as a `vulnerability` issue. A severity the mapping does not name is not reported, and `fixed_only` limits the report to findings with a fixed version. The list form of `severity` is rejected. - **Finding records:** Every output is built from the same records, one per finding and owner: `run_id`, `timestamp` (RFC 3339, UTC), `host`, `environment`, `target` (`/` or the host name), `kind`, `image` (`@` or the host name), `scanner`, `id`, `severity`, `package`, `installed_version`, `fixed_version`, `suppressed`, `suppressed_until` and `verdict` (`fail`, `warn` or `suppressed`). diff --git a/roles/sys-ctl-hlth-runtime/files/python/script.py b/roles/sys-ctl-hlth-runtime/files/python/script.py index f824cbd626..e95a65413b 100755 --- a/roles/sys-ctl-hlth-runtime/files/python/script.py +++ b/roles/sys-ctl-hlth-runtime/files/python/script.py @@ -57,6 +57,7 @@ SUCCESS = frozenset({0}) OSV_ACCEPTED_EXIT_CODES = frozenset({0, 1, 128}) OSV_SOURCE_PURL_TYPES = ("deb", "apk") UPSTREAM_QUALIFIER = re.compile(r"([?&])upstream=([^&#]+)") +MAJOR_VERSION = re.compile(r"[0-9]+") HOST_ROOT = "/host" WORK = "/work" SBOM = "/sbom" @@ -98,6 +99,21 @@ class ConfigError(ValueError): pass +@dataclass(frozen=True) +class OsRelease: + """ + Args: + name: the ``operating-system`` component name of a Syft CycloneDX + SBOM, the ``ID`` of ``/etc/os-release``. + version: its major version. + until: the last day Grype alone scans its OS packages. + """ + + name: str + version: str + until: dt.date + + @dataclass(frozen=True) class ScanConfig: """What the vulnerability scan covers and when it fails. @@ -111,6 +127,8 @@ class ScanConfig: workers: parallel engine runs. db_update: download and refresh the databases; ``False`` reads databases that were provided and fails when one is missing. + trivy_unmatched_os: the OS releases whose OS packages Trivy leaves + to Grype. """ targets: tuple[str, ...] @@ -119,6 +137,7 @@ class ScanConfig: fixed_only: bool workers: int db_update: bool + trivy_unmatched_os: tuple[OsRelease, ...] def scanners(self) -> tuple[str, ...]: return tuple(engine for engine in SCANNERS if engine in self.engines) @@ -280,7 +299,10 @@ def parse_args(argv=None): parser.add_argument( "--scan", required=True, - help="JSON: targets, engines, severity, fixed_only, workers, db_update", + help=( + "JSON: targets, engines, severity, fixed_only, workers, db_update, " + "trivy_unmatched_os" + ), ) parser.add_argument( "--images", @@ -508,17 +530,59 @@ def severity_actions(raw) -> dict[str, str]: return {severity: raw[severity] for severity in SEVERITIES if severity in raw} +def os_releases(raw) -> tuple[OsRelease, ...]: + """ + Args: + raw: ``[{name, version, until}]`` with ``version`` a bare major + version and ``until`` as ``YYYY-MM-DD``. + + Raises: + ConfigError: *raw* is no list, an entry lacks a field or its version + is no bare major version. + """ + if not isinstance(raw, list): + raise ConfigError("trivy_unmatched_os must be a list") + try: + releases = tuple( + OsRelease( + name=str(item["name"]), + version=str(item["version"]), + until=dt.date.fromisoformat(str(item["until"])), + ) + for item in raw + ) + except (KeyError, TypeError, ValueError) as exc: + raise ConfigError( + f"trivy_unmatched_os entries need name, version and until: {exc}" + ) from exc + for release in releases: + if not MAJOR_VERSION.fullmatch(release.version): + raise ConfigError( + f"trivy_unmatched_os version {release.version!r} of {release.name} " + "is no bare major version" + ) + return releases + + def scan_config(raw: Mapping) -> ScanConfig: """Validate the scan configuration. Args: raw: ``targets``, ``engines``, ``severity``, ``fixed_only``, - ``workers`` and ``db_update``. + ``workers``, ``db_update`` and ``trivy_unmatched_os``. Raises: ConfigError: a value is missing, unknown or contradictory. """ - required = {"targets", "engines", "severity", "fixed_only", "workers", "db_update"} + required = { + "targets", + "engines", + "severity", + "fixed_only", + "workers", + "db_update", + "trivy_unmatched_os", + } missing = sorted(required - set(raw)) if missing: raise ConfigError(f"scan config lacks {', '.join(missing)}") @@ -547,6 +611,7 @@ def scan_config(raw: Mapping) -> ScanConfig: fixed_only=raw["fixed_only"], workers=workers, db_update=raw["db_update"], + trivy_unmatched_os=os_releases(raw["trivy_unmatched_os"]), ) if not config.scanners(): raise ConfigError( @@ -1337,7 +1402,60 @@ def sbom_step(layout: Layout, image: str, target: Target) -> Step: ) -def trivy_step(layout: Layout, image: str, target: Target, config: ScanConfig) -> Step: +def sbom_os(cyclonedx: Mapping) -> tuple[str, str] | None: + """ + Returns: + ``(name, major version)`` of a CycloneDX SBOM's ``operating-system`` + component, ``None`` when it names none. + """ + for component in cyclonedx.get("components") or []: + if component.get("type") == "operating-system": + version = str(component.get("version") or "") + return str(component.get("name") or ""), version.partition(".")[0] + return None + + +def trivy_os_args( + layout: Layout, + target: Target, + scanners: Sequence[str], + config: ScanConfig, + today: dt.date, +) -> list[str]: + """ + Args: + layout: where the run keeps its files, the target's SBOM among them. + target: the target. + scanners: the scanners that run. + config: the scan configuration. + today: the day an entry's ``until`` must not lie before. + + Returns: + ``["--pkg-types", "library"]`` when Grype runs and the target's SBOM + names an OS release of :attr:`ScanConfig.trivy_unmatched_os` whose + ``until`` has not passed, else ``[]``. + """ + cyclonedx = sbom_paths(layout, target)[1] + if "grype" not in scanners or not cyclonedx.is_file(): + return [] + release = sbom_os(_read_json(cyclonedx)) + for entry in config.trivy_unmatched_os: + if (entry.name, entry.version) == release and today <= entry.until: + print( + f"โ„น๏ธ trivy {target.label}: OS packages of {entry.name} " + f"{entry.version} left to grype until {entry.until}" + ) + return ["--pkg-types", "library"] + return [] + + +def trivy_step( + layout: Layout, + image: str, + target: Target, + config: ScanConfig, + os_args: Sequence[str], +) -> Step: args = [ "rootfs" if target.kind == "host" else "image", *TRIVY_COMMON, @@ -1345,6 +1463,7 @@ def trivy_step(layout: Layout, image: str, target: Target, config: ScanConfig) - "--skip-java-db-update", "--scanners", "vuln", + *os_args, "--format", "json", "--output", @@ -1681,9 +1800,21 @@ def scan( sbom_ready = [target for target in targets if target.key not in failed] lanes: list[list[Step]] = [] + today = dt.datetime.now(tz=dt.UTC).date() if "trivy" in scanners: lanes.append( - [trivy_step(layout, images["trivy"], target, config) for target in targets] + [ + 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 + ] ) if "grype" in scanners: lanes.extend( diff --git a/roles/sys-ctl-hlth-runtime/meta/services.yml b/roles/sys-ctl-hlth-runtime/meta/services.yml index 8637627f22..4f41734ef8 100644 --- a/roles/sys-ctl-hlth-runtime/meta/services.yml +++ b/roles/sys-ctl-hlth-runtime/meta/services.yml @@ -20,6 +20,13 @@ runtime: trivy: image: ghcr.io/aquasecurity/trivy version: "0.76.1" + unmatched_os: + - name: centos + version: "10" + until: 2026-11-30 + - name: rhel + version: "10" + until: 2026-11-30 security: suppressions: # nocheck: cve golang.org/x/net below 0.60.0 sits in the newest docker-ce and containerd.io packages diff --git a/roles/sys-ctl-hlth-runtime/vars/main.yml b/roles/sys-ctl-hlth-runtime/vars/main.yml index 0de209c490..98578e0f06 100644 --- a/roles/sys-ctl-hlth-runtime/vars/main.yml +++ b/roles/sys-ctl-hlth-runtime/vars/main.yml @@ -10,6 +10,7 @@ HEALTH_RUNTIME_SCAN: fixed_only: "{{ lookup('config', 'sys-ctl-hlth-runtime', 'services.runtime.fixed_only') | bool }}" workers: "{{ lookup('config', 'sys-ctl-hlth-runtime', 'services.runtime.workers') | int }}" db_update: "{{ lookup('config', 'sys-ctl-hlth-runtime', 'services.runtime.db_update') | bool }}" + trivy_unmatched_os: "{{ lookup('config', 'sys-ctl-hlth-runtime', 'services.trivy.unmatched_os') }}" HEALTH_RUNTIME_IMAGES: trivy: "{{ lookup('config', 'sys-ctl-hlth-runtime', 'services.trivy.image') }}:{{ lookup('config', 'sys-ctl-hlth-runtime', 'services.trivy.version') }}" grype: "{{ lookup('config', 'sys-ctl-hlth-runtime', 'services.grype.image') }}:{{ lookup('config', 'sys-ctl-hlth-runtime', 'services.grype.version') }}" diff --git a/roles/test-e2e-playwright/meta/services.yml b/roles/test-e2e-playwright/meta/services.yml index e9e63e4b3a..01a18651bb 100644 --- a/roles/test-e2e-playwright/meta/services.yml +++ b/roles/test-e2e-playwright/meta/services.yml @@ -5,7 +5,7 @@ test-e2e-playwright: # nocheck: image-healthcheck spec runner started as `container run --rm` by tasks/02_run_one.yml, it exits with the run; the role renders no compose service to carry a probe playwright: image: mcr.microsoft.com/playwright - version: "v1.65.0-noble" + version: "v1.65.1-noble" axe_version: 4.14.0 update: - key: axe_version diff --git a/roles/update/tasks/fedora.yml b/roles/update/tasks/fedora.yml index a7ad389c9f..6a61659851 100644 --- a/roles/update/tasks/fedora.yml +++ b/roles/update/tasks/fedora.yml @@ -11,7 +11,7 @@ - name: "๐Ÿ”„ update (dnf) | re-fetch the metadata of every enabled repository" become: true ansible.builtin.command: - argv: [dnf, makecache, --refresh] + argv: [dnf, makecache, --refresh, -y] changed_when: false - name: "๐Ÿ”„ update (dnf) | upgrade all installed packages" diff --git a/roles/web-app-baserow/meta/services.yml b/roles/web-app-baserow/meta/services.yml index b034792f11..a8f2f1bcd3 100644 --- a/roles/web-app-baserow/meta/services.yml +++ b/roles/web-app-baserow/meta/services.yml @@ -66,7 +66,7 @@ baserow: backup: stop_required: false image: baserow/baserow - version: 2.4.2 + version: 2.4.3 custom: true name: baserow min_storage: 785MB diff --git a/roles/web-app-bigbluebutton/meta/services.yml b/roles/web-app-bigbluebutton/meta/services.yml index a6a59e48dc..68e67bdab0 100644 --- a/roles/web-app-bigbluebutton/meta/services.yml +++ b/roles/web-app-bigbluebutton/meta/services.yml @@ -43,7 +43,7 @@ bigbluebutton: update: key: ref type: http_regex - url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + url: https://raw.githubusercontent.com/bigbluebutton/docker/main/repos/tags pattern: "repos/bigbluebutton (v[0-9.]+)" recording: enabled: false @@ -119,7 +119,7 @@ bbb-web: version: "v3.0.39" update: type: http_regex - url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + url: https://raw.githubusercontent.com/bigbluebutton/docker/main/repos/tags pattern: "repos/bigbluebutton (v[0-9.]+)" enabled: false security: @@ -136,7 +136,7 @@ freeswitch: version: "v1.11.3-v3.0.39" update: type: http_regex - url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + url: https://raw.githubusercontent.com/bigbluebutton/docker/main/repos/tags pattern: "repos/bigbluebutton (?Pv[0-9.]+)\\nrepos/freeswitch (?Pv[0-9.]+)" template: "{freeswitch}-{bbb}" enabled: false @@ -155,8 +155,8 @@ nginx: update: type: http_regex url: - - https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags - - https://raw.githubusercontent.com/bigbluebutton/docker/develop/docker-compose.tmpl.yml + - https://raw.githubusercontent.com/bigbluebutton/docker/main/repos/tags + - https://raw.githubusercontent.com/bigbluebutton/docker/main/docker-compose.tmpl.yml pattern: "repos/bbb-playback (?Pv[0-9.]+)\\n(?:.*\\n)*?repos/bigbluebutton (?Pv[0-9.]+)\\n(?:.*\\n)*?.*bbb-docker-nginx:.*-(?P[0-9.]+)\\n" template: "{bbb}-{playback}-{base}" enabled: false @@ -172,7 +172,7 @@ bbb-shared-notes-server: version: "v3.0.39" update: type: http_regex - url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + url: https://raw.githubusercontent.com/bigbluebutton/docker/main/repos/tags pattern: "repos/bigbluebutton (v[0-9.]+)" enabled: false security: @@ -189,7 +189,7 @@ bbb-export-annotations: version: "v3.0.39" update: type: http_regex - url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + url: https://raw.githubusercontent.com/bigbluebutton/docker/main/repos/tags pattern: "repos/bigbluebutton (v[0-9.]+)" enabled: false security: @@ -206,7 +206,7 @@ webrtc-sfu: version: "v2.24.0" update: type: http_regex - url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + url: https://raw.githubusercontent.com/bigbluebutton/docker/main/repos/tags pattern: "repos/bbb-webrtc-sfu (v[0-9.]+)" enabled: false security: @@ -221,7 +221,7 @@ fsesl-akka: version: "v3.0.39" update: type: http_regex - url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + url: https://raw.githubusercontent.com/bigbluebutton/docker/main/repos/tags pattern: "repos/bigbluebutton (v[0-9.]+)" enabled: false security: @@ -238,7 +238,7 @@ apps-akka: version: "v3.0.39" update: type: http_regex - url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + url: https://raw.githubusercontent.com/bigbluebutton/docker/main/repos/tags pattern: "repos/bigbluebutton (v[0-9.]+)" enabled: false security: @@ -258,7 +258,7 @@ bbb-graphql-server: version: "v3.0.39" update: type: http_regex - url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + url: https://raw.githubusercontent.com/bigbluebutton/docker/main/repos/tags pattern: "repos/bigbluebutton (v[0-9.]+)" enabled: false security: @@ -273,7 +273,7 @@ bbb-graphql-actions: version: "v3.0.39" update: type: http_regex - url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + url: https://raw.githubusercontent.com/bigbluebutton/docker/main/repos/tags pattern: "repos/bigbluebutton (v[0-9.]+)" enabled: false security: @@ -288,7 +288,7 @@ bbb-graphql-middleware: version: "v3.0.39" update: type: http_regex - url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + url: https://raw.githubusercontent.com/bigbluebutton/docker/main/repos/tags pattern: "repos/bigbluebutton (v[0-9.]+)" enabled: false security: @@ -305,7 +305,7 @@ periodic: version: "v3.0.0" update: type: http_regex - url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/docker-compose.tmpl.yml + url: https://raw.githubusercontent.com/bigbluebutton/docker/main/docker-compose.tmpl.yml pattern: "bbb-docker-periodic:(v[0-9.]+)" enabled: false security: @@ -322,7 +322,7 @@ recordings: version: "v3.0.39" update: type: http_regex - url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + url: https://raw.githubusercontent.com/bigbluebutton/docker/main/repos/tags pattern: "repos/bigbluebutton (v[0-9.]+)" enabled: false security: @@ -337,7 +337,7 @@ bbb-webrtc-recorder: version: "v0.14.0" update: type: http_regex - url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + url: https://raw.githubusercontent.com/bigbluebutton/docker/main/repos/tags pattern: "repos/bbb-webrtc-recorder (v[0-9.]+)" enabled: false security: diff --git a/roles/web-app-bridgy-fed/meta/services.yml b/roles/web-app-bridgy-fed/meta/services.yml index 0b0a13f888..b5151749d9 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: d340cd2cba1ca089bf919dbfcca9644dc99e11be + ref: 4bbcca226a04a253afef0c503729674ff8aa2b8b ports: local: http: 8053 diff --git a/roles/web-app-docs/files/test/README.md b/roles/web-app-docs/files/test/README.md index ca0a9e43dc..acd9741f04 100644 --- a/roles/web-app-docs/files/test/README.md +++ b/roles/web-app-docs/files/test/README.md @@ -81,6 +81,7 @@ flowchart TD | 1๏ธโƒฃ | ๐Ÿงช `test.sh` starts on the stack host | returns early unless the deployment mode is compose | | 2๏ธโƒฃ | ๐Ÿ“– `extract.py` writes `block.sh` | fetches the role's page over `DOCS_TEST_BASE_URL`; an empty block fails the test, and `bash -n` parses it before anything runs it | | ๐Ÿชž | the GHCR mirror is attached | `mirror.sh` rewrites the block's provision call to write `mirrors.yml` and pass `--mirror`, so the replay pulls every application image from the mirror instead of the upstream registry. Outside CI the two GitHub variables are empty and the block is left exactly as published | +| ๐Ÿฉบ | the stack's runtime severity is carried over | `hlth_runtime.py` puts `applications.sys-ctl-hlth-runtime.services.runtime.severity` with the stack host's own mapping into the block's provision `--vars`, so `sys-ctl-hlth-runtime` in the target acts on findings as the stack host does. It fails when the block's `--vars` already set `applications` | | ๐Ÿ“ | the stack's disc-space limit is carried over | `disc_space.sh` puts `SIZE_PERCENT_CLEANUP_DISC_SPACE` with the stack host's own value into the block's provision `--vars`, so `sys-ctl-hlth-disc-space` in the target uses the stack host's limit | | 3๏ธโƒฃ | ๐Ÿ”‘ key pair and placeholders | an ed25519 pair per run under `DOCS_TEST_WORK`; every placeholder except `HOST` is substituted | | 4๏ธโƒฃ | ๐Ÿšœ `machine.sh` brings the target up | `compose up machine`, on the default bridge | @@ -103,6 +104,7 @@ flowchart TD | `DOCS_TEST_ROLE` | `templates/test.env.j2` | role whose page carries the instructions; names the compose project | | `DOCS_TEST_MODE` | `templates/test.env.j2` | deployment mode; the test runs only for compose | | `DOCS_TEST_DISC_SPACE_PERCENT` | `templates/test.env.j2` | the stack host's `SIZE_PERCENT_CLEANUP_DISC_SPACE`, written into the replayed deploy's host vars by `disc_space.sh` | +| `DOCS_TEST_HLTH_RUNTIME_SEVERITY` | `templates/test.env.j2` | the stack host's `sys-ctl-hlth-runtime` severity as JSON, written into the replayed deploy's host vars by `hlth_runtime.py` | | `DOCS_TEST_DOMAIN` | `templates/test.env.j2` | fills ``; the zone the resolver answers with the target's bridge address | | `DOCS_TEST_DNS` | `templates/test.env.j2` | fills `` | | `DOCS_TEST_SRC_DIR` | `templates/test.env.j2` | checkout holding the generated `.env`; mounted into the target at the same path, where a host install replays from it | @@ -121,6 +123,7 @@ flowchart TD | `test.sh` | entry point; extraction, key pair, placeholder fill | | `extract.py` | pulls the Production block off the live documentation site | | `mirror.sh` | points the extracted block's provision call at the GHCR image mirror when CI configured one | +| `hlth_runtime.py` | hands the extracted block's provision call the stack host's runtime severity | | `disc_space.sh` | hands the extracted block's provision call the stack host's disc-space limit | | `machine.sh` | target lifecycle, wildcard resolution, `HOST` fill, guard, local image build, replay, failed-unit report, teardown | | `compose.yml` | the target service on the default bridge with a named volume at `/var/lib/docker`, and the resolver service in the target's network namespace | diff --git a/roles/web-app-docs/files/test/hlth_runtime.py b/roles/web-app-docs/files/test/hlth_runtime.py new file mode 100644 index 0000000000..8270e2229d --- /dev/null +++ b/roles/web-app-docs/files/test/hlth_runtime.py @@ -0,0 +1,65 @@ +""" +Args: + block the extracted production block, rewritten in place + +Env (test.env): + DOCS_TEST_HLTH_RUNTIME_SEVERITY the stack host's sys-ctl-hlth-runtime severity, as JSON +""" + +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path + +ROLE = "sys-ctl-hlth-runtime" +VARS = '--vars "{' +APPLICATIONS = '\\"applications\\":' +DOUBLE_QUOTED = str.maketrans({"\\": "\\\\", '"': '\\"', "$": "\\$", "`": "\\`"}) + + +def entry(severity: dict[str, str]) -> str: + """ + Args: + severity: ``{severity: action}`` of the stack host's ``sys-ctl-hlth-runtime``. + + Raises: + ValueError: ``severity`` holds a single quote. + """ + override = { + "applications": {ROLE: {"services": {"runtime": {"severity": severity}}}} + } + text = json.dumps(override)[1:-1] + if "'" in text: + raise ValueError(f"{text} holds a single quote") + return text.translate(DOUBLE_QUOTED) + ", " + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser() + parser.add_argument("block", type=Path) + args = parser.parse_args(argv) + + block = args.block.read_text(encoding="utf-8") + if block.count(VARS) != 1: + raise SystemExit( + "the block hands provision no single --vars object, " + "so the hlth-runtime severity has nothing to attach to" + ) + if APPLICATIONS in block: + raise SystemExit( + f"the block's provision --vars already carry {APPLICATIONS}, " + "and a second one would replace it" + ) + + severity = json.loads(os.environ["DOCS_TEST_HLTH_RUNTIME_SEVERITY"]) + print( + f"=== Judging the target's runtime scan by the stack host's {json.dumps(severity)} ===" + ) + args.block.write_text(block.replace(VARS, VARS + entry(severity)), encoding="utf-8") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/roles/web-app-docs/files/test/test.sh b/roles/web-app-docs/files/test/test.sh index d9fdca39de..bc253fe9c9 100644 --- a/roles/web-app-docs/files/test/test.sh +++ b/roles/web-app-docs/files/test/test.sh @@ -45,6 +45,7 @@ if [ ! -s "${BLOCK}" ]; then fi bash "${STAGE}/mirror.sh" "${BLOCK}" +python3 "${STAGE}/hlth_runtime.py" "${BLOCK}" bash "${STAGE}/disc_space.sh" "${BLOCK}" echo "=== Checking they parse as bash ===" diff --git a/roles/web-app-docs/templates/test.env.j2 b/roles/web-app-docs/templates/test.env.j2 index c012824310..02bb622114 100644 --- a/roles/web-app-docs/templates/test.env.j2 +++ b/roles/web-app-docs/templates/test.env.j2 @@ -3,6 +3,7 @@ DOCS_TEST_COUNTRY=Germany DOCS_TEST_DISC_SPACE_PERCENT={{ SIZE_PERCENT_CLEANUP_DISC_SPACE }} DOCS_TEST_DNS={{ networks.internet.dns }} DOCS_TEST_DOMAIN={{ DOMAIN_PRIMARY }} +DOCS_TEST_HLTH_RUNTIME_SEVERITY={{ lookup('config', 'sys-ctl-hlth-runtime', 'services.runtime.severity') | to_json | quote }} DOCS_TEST_MODE={{ DEPLOYMENT_MODE }} DOCS_TEST_ROLE={{ lookup('guide_role', application_id) }} DOCS_TEST_SRC_DIR={{ lookup('path_absolute') }} diff --git a/roles/web-app-funkwhale/meta/services.yml b/roles/web-app-funkwhale/meta/services.yml index 88b2a6c87b..068850de07 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.13 + version: 2.0.14 min_storage: 224MB ports: internal: @@ -34,11 +34,6 @@ funkwhale: mem_reservation: 1g mem_limit: 2g pids_limit: 1024 - security: - suppressions: - # nocheck: cve upstream tag ships fixable CRITICAL CVEs; lift it once a rebuilt tag lands - - image_tag: "2.0.13" - until: 2026-11-30 api: backup: stop_required: false @@ -48,7 +43,7 @@ api: name: funkwhale-api image: funkwhale/api ca_client: true - version: 2.0.13 + version: 2.0.14 min_storage: 588MB ports: internal: @@ -57,11 +52,6 @@ api: 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: "2.0.13" - until: 2026-11-30 migrate: # nocheck: single-replica run-once schema bootstrap; concurrent `funkwhale-manage migrate` races the migration graph replicas: 1 diff --git a/roles/web-app-mattermost/meta/addons/mattermost-plugin-alertmanager.yml b/roles/web-app-mattermost/meta/addons/mattermost-plugin-alertmanager.yml index bc6b6ddd4d..325f5a498e 100644 --- a/roles/web-app-mattermost/meta/addons/mattermost-plugin-alertmanager.yml +++ b/roles/web-app-mattermost/meta/addons/mattermost-plugin-alertmanager.yml @@ -3,7 +3,7 @@ enabled: false required: false mechanism: plugin source: upstream -version: "v0.4.0" +version: "v0.5.0" bridges: - prometheus update: @@ -12,6 +12,6 @@ update: upstream_id: cpanato/mattermost-plugin-alertmanager config: plugin_id: alertmanager - archive: https://github.com/cpanato/mattermost-plugin-alertmanager/releases/download/v0.4.0/alertmanager-0.4.0.tar.gz + archive: https://github.com/cpanato/mattermost-plugin-alertmanager/releases/download/v0.5.0/alertmanager-0.5.0.tar.gz partner_host: "{{ lookup('container_address', 'web-app-prometheus', 'alertmanager') }}" partner_port: "{{ lookup('config', 'web-app-prometheus', 'services.alertmanager.ports.internal.http') }}" diff --git a/roles/web-app-mattermost/meta/addons/mattermost-plugin-jira.yml b/roles/web-app-mattermost/meta/addons/mattermost-plugin-jira.yml index 124f995ab3..402382a048 100644 --- a/roles/web-app-mattermost/meta/addons/mattermost-plugin-jira.yml +++ b/roles/web-app-mattermost/meta/addons/mattermost-plugin-jira.yml @@ -3,7 +3,7 @@ enabled: "{{ lookup('config', 'web-app-mattermost', 'services.jira.enabled') | b required: false mechanism: plugin source: upstream -version: "v5.0.0" +version: "v4.8.3" bridges: - jira update: diff --git a/roles/web-app-mattermost/meta/services.yml b/roles/web-app-mattermost/meta/services.yml index 5debe61afb..947be002df 100644 --- a/roles/web-app-mattermost/meta/services.yml +++ b/roles/web-app-mattermost/meta/services.yml @@ -50,7 +50,7 @@ mattermost: version: 13.7-slim custom: true repository: https://github.com/mattermost/mattermost.git - ref: v11.11.1 + ref: v11.11.4 min_storage: 659MB backup: stop_required: false diff --git a/roles/web-app-nextcloud/docs/Administration.md b/roles/web-app-nextcloud/docs/Administration.md index cef6371e7a..12b9463059 100644 --- a/roles/web-app-nextcloud/docs/Administration.md +++ b/roles/web-app-nextcloud/docs/Administration.md @@ -52,6 +52,8 @@ How the services connect: `credentials.talk_signaling_secret`, `credentials.talk_internal_secret` and `credentials.talk_recording_secret` reach the services only through the rendered files. The signaling session keys are derived from `credentials.talk_signaling_secret`, so they stay stable across deploys. `talk_signaling` runs as UID 850, `talk` as UID 1000, `talk_nats` as UID 65534 and `talk_recording` as UID 122, each with one swarm replica. In swarm mode all four join the stack network and share no network namespace, so swarm may schedule them on different nodes. +`talk_recording` may use 70 % of the host's CPUs (`cpus: "70%"`) and encodes video with the upstream default `outputvideo` plus `-threads:v 4`. Without that bound libvpx starts one busy-waiting encoder thread per host core, so the former fixed 2-CPU cap was used up early in every 100 ms scheduler period, the whole container stalled and video recordings fell to about 4 frames per second. The share stays below 100 % because Ansible's `processor_vcpus` can overcount a hybrid CPU by up to 4/3, and Docker refuses a CPU limit above the real CPU count. + ### Version updates 1. The `cron-update` workflow runs `python3 -m cli.contributing.update.docker`, which raises `services.talk_signaling.version` and `services.talk_nats.version` from their registries together with the base images `services.talk.version` and `services.talk_recording.version`, and opens an update pull request. diff --git a/roles/web-app-nextcloud/meta/services.yml b/roles/web-app-nextcloud/meta/services.yml index 01cc91afb3..2ec7a0c399 100644 --- a/roles/web-app-nextcloud/meta/services.yml +++ b/roles/web-app-nextcloud/meta/services.yml @@ -347,7 +347,7 @@ talk_recording: ref: v0.3.1 # nocheck: single-replica Talk starts and stops a recording on the server it reached; a second replica behind the VIP would receive half of the stop requests replicas: 1 - cpus: "2.0" + cpus: "70%" mem_reservation: 1g mem_limit: 3g pids_limit: 1024 diff --git a/roles/web-app-nextcloud/templates/recording.conf.j2 b/roles/web-app-nextcloud/templates/recording.conf.j2 index 5549758113..19a6da0916 100644 --- a/roles/web-app-nextcloud/templates/recording.conf.j2 +++ b/roles/web-app-nextcloud/templates/recording.conf.j2 @@ -27,6 +27,7 @@ url = {{ NEXTCLOUD_HPB_BACKEND_URL }}{{ NEXTCLOUD_HPB_SIGNALING_LOCATION }} internalsecret = {{ NEXTCLOUD_HPB_INTERNAL_SECRET }} [ffmpeg] +outputvideo = -c:v libvpx -deadline:v realtime -crf 10 -b:v 1M -threads:v 4 extensionaudio = .ogg extensionvideo = .webm diff --git a/roles/web-app-pihole/README.md b/roles/web-app-pihole/README.md index 8a4c64ae56..3e03907314 100644 --- a/roles/web-app-pihole/README.md +++ b/roles/web-app-pihole/README.md @@ -16,7 +16,7 @@ This role deploys Pi-hole as a containerized service within the Infinito.Nexus p - **RBAC** โ€” only users in the `web-app-pihole-administrator` group can access the dashboard - **OpenLDAP integration** for group synchronization - **Logout button** injected into the Pi-hole admin navbar via JavaScript -- **Auto-redirect** from Pi-hole root 403 page to `/admin/` +- **Auto-redirect** from Pi-hole's 403 page (body class `page-error403`) to `/admin/`, never from `/admin/` itself - **Redis** session storage for oauth2-proxy - **Prometheus** metrics support @@ -25,6 +25,8 @@ This role deploys Pi-hole as a containerized service within the Infinito.Nexus p After deployment, Pi-hole is available at: `https://pihole./admin/` +The onion sibling hands every request over to that clearnet URL (`reachability.handover` in `meta/networks.yml`): with SSO on, FTL runs without a password, and its DNS-rebinding guard answers 403 to every Host but `webserver.domain`. + Access is protected by SSO. Users must be members of the `web-app-pihole-administrator` group in Keycloak/LDAP. ## Dependencies diff --git a/roles/web-app-pihole/TODO.md b/roles/web-app-pihole/TODO.md deleted file mode 100644 index 6c13565db2..0000000000 --- a/roles/web-app-pihole/TODO.md +++ /dev/null @@ -1,3 +0,0 @@ -# TODO - -- `templates/javascript.js.j2:4` sends every page whose visible text contains "your Pi-hole" to `/admin/`. With `services.javascript` enabled the Clients page (`/admin/groups/clients`), the Pi-hole diagnosis page (`/admin/messages`) and the Teleporter settings (`/admin/settings/teleporter`) therefore open the dashboard instead of their own content (measured on the compose stack with `javascript` on and `sso` off: the browser ends on `/admin/` and shows the dashboard tiles; the templates of all three pages carry the phrase in their help texts). Cause: `redirectIfAccessDenied` matches a phrase of the 403 page that upstream also uses on regular pages. Options: match the 403 page by its own markup (`h2.error-headline`, body class `page-error403`) instead of by a phrase; return early when `document.body.classList.contains("logged-in")`; or drop the redirect, because the app answers `/` with its own 308 to `/admin/` once the request host equals `webserver.domain`. diff --git a/roles/web-app-pihole/meta/networks.yml b/roles/web-app-pihole/meta/networks.yml index 3b8a9c8a8f..9818bfee66 100644 --- a/roles/web-app-pihole/meta/networks.yml +++ b/roles/web-app-pihole/meta/networks.yml @@ -2,3 +2,5 @@ meshes: [] local: subnet: 192.168.52.0/24 +reachability: + handover: true # nocheck: network-reachability with SSO on FTL runs passwordless, and its DNS-rebinding guard answers 403 to every Host but webserver.domain, so the onion sibling only ever hands over to clearnet diff --git a/roles/web-app-pihole/meta/services.yml b/roles/web-app-pihole/meta/services.yml index c6cc49ceb0..e49c2c0a40 100644 --- a/roles/web-app-pihole/meta/services.yml +++ b/roles/web-app-pihole/meta/services.yml @@ -69,7 +69,7 @@ pihole: swarm: enabled: false image: pihole/pihole - version: "2026.10.1" + version: "2026.11.0" upstream_dns: "{{ NETWORK_PUBLIC_DNS_RESOLVERS }}" cpus: "0.5" mem_reservation: "128m" diff --git a/roles/web-app-pihole/templates/javascript.js.j2 b/roles/web-app-pihole/templates/javascript.js.j2 index 3049682607..d8ad0b02af 100644 --- a/roles/web-app-pihole/templates/javascript.js.j2 +++ b/roles/web-app-pihole/templates/javascript.js.j2 @@ -1,8 +1,11 @@ {% raw %} (function () { + var HOME = "/admin/"; + function redirectIfAccessDenied() { - if (document.querySelector('p') && document.body.innerText.includes("your Pi-hole")) { - window.location.replace("/admin/"); + if (window.location.pathname === HOME) return; + if (document.body && document.body.classList.contains("page-error403")) { + window.location.replace(HOME); } } diff --git a/roles/web-app-xwiki/meta/addons/oidc-authenticator.yml b/roles/web-app-xwiki/meta/addons/oidc-authenticator.yml index c4c0021e48..6e45c5b8b8 100644 --- a/roles/web-app-xwiki/meta/addons/oidc-authenticator.yml +++ b/roles/web-app-xwiki/meta/addons/oidc-authenticator.yml @@ -5,7 +5,7 @@ mechanism: extension source: upstream bridges: - sso -version: "2.30.0" +version: "2.30.1" update: type: http_regex url: https://maven.xwiki.org/releases/org/xwiki/contrib/oidc/oidc-authenticator/maven-metadata.xml diff --git a/roles/web-svc-coturn/meta/services.yml b/roles/web-svc-coturn/meta/services.yml index 2e9fb21303..dfc8806c49 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.18.0 + version: 4.19.0 min_storage: 246MB user_auth_enabled: false total_quota: 2000 @@ -32,11 +32,6 @@ coturn: start: 20000 end: 39999 lifecycle: beta - security: - suppressions: - # nocheck: cve upstream tag ships fixable CRITICAL CVEs; lift it once a rebuilt tag lands - - image_tag: "4.18.0" - until: 2026-11-30 gateway: image: nginx version: 1.31.8-alpine diff --git a/scripts/image/build.sh b/scripts/image/build.sh index af443b2483..e7032eece8 100755 --- a/scripts/image/build.sh +++ b/scripts/image/build.sh @@ -157,7 +157,7 @@ if [[ -n "${REPO_PREFIX}" ]]; then fi if [[ -n "${OWNER}" || -n "${GITHUB_REPOSITORY_OWNER:-}" || -n "${GITHUB_REPOSITORY:-}" ]]; then - OWNER="$(OWNER="${OWNER}" GITHUB_REPOSITORY_OWNER="${GITHUB_REPOSITORY_OWNER:-}" GITHUB_REPOSITORY="${GITHUB_REPOSITORY:-}" scripts/meta/resolve/repository/owner.sh)" + OWNER="$(OWNER="${OWNER}" GITHUB_REPOSITORY_OWNER="${GITHUB_REPOSITORY_OWNER:-}" GITHUB_REPOSITORY="${GITHUB_REPOSITORY:-}" "${_build_script_dir}/../meta/resolve/repository/owner.sh")" fi if [[ -z "${TARGET}" ]]; then @@ -324,3 +324,5 @@ else echo "[build] Running: ${local_args[*]}" "${local_args[@]}" fi + +bash "${_build_script_dir}/prune.sh" diff --git a/scripts/image/prune.sh b/scripts/image/prune.sh new file mode 100755 index 0000000000..fd80495a7c --- /dev/null +++ b/scripts/image/prune.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +set -euo pipefail + +: "${INFINITO_BUILD_CACHE_MAX_SIZE:?Run 'make dotenv' to generate the .env single source of truth}" + +prune_help="$(docker builder prune --help)" +if grep -q -- '--max-used-space' <<<"${prune_help}"; then + keep_flag="--max-used-space" +elif grep -q -- '--keep-storage' <<<"${prune_help}"; then + keep_flag="--keep-storage" +else + echo "[build] ERROR: 'docker builder prune' accepts neither --max-used-space nor --keep-storage; cannot cap the build cache at INFINITO_BUILD_CACHE_MAX_SIZE=${INFINITO_BUILD_CACHE_MAX_SIZE}" >&2 + exit 1 +fi + +echo "[build] Pruning the build cache to INFINITO_BUILD_CACHE_MAX_SIZE=${INFINITO_BUILD_CACHE_MAX_SIZE} (${keep_flag})" +docker builder prune --force "${keep_flag}" "${INFINITO_BUILD_CACHE_MAX_SIZE}" diff --git a/tests/external/repository/test_urls_reachable.py b/tests/external/repository/test_urls_reachable.py index 441069faba..49b72592e3 100644 --- a/tests/external/repository/test_urls_reachable.py +++ b/tests/external/repository/test_urls_reachable.py @@ -117,12 +117,14 @@ _MAX_WORKERS = int(os.environ["INFINITO_WORKER_FETCH"]) _MAX_REQUESTS_PER_HOST = 4 _GLOBAL_DEADLINE_SECONDS = 5 * 3600 + 30 * 60 _PROGRESS_INTERVAL = 50 +_CATALOG_SUFFIX = ".po" class UrlOccurrence(NamedTuple): file: Path line: int url: str + suppressed: bool = False class ProbeOutcome(NamedTuple): @@ -264,7 +266,7 @@ def _is_live_literal_url(url: str) -> bool: def _extract_urls(path: Path) -> list[UrlOccurrence]: - """Return URL occurrences from *path* that should be probed live.""" + """Return URL occurrences from *path*, flagged where a marker exempts them.""" if not _is_probably_text_file(path): return [] @@ -273,15 +275,14 @@ def _extract_urls(path: Path) -> list[UrlOccurrence]: except (OSError, UnicodeDecodeError): return [] - placement = "block-above" if path.suffix == ".po" else "same-or-above" + placement = "block-above" if path.suffix == _CATALOG_SUFFIX else "same-or-above" occurrences: list[UrlOccurrence] = [] for line_no, line in enumerate(lines, start=1): - if is_suppressed_at(lines, line_no, "url", mode=placement): - continue + suppressed = is_suppressed_at(lines, line_no, "url", mode=placement) for match in _URL_RE.finditer(line): url = _normalize_url(match.group(0)) if _is_live_literal_url(url): - occurrences.append(UrlOccurrence(path, line_no, url)) + occurrences.append(UrlOccurrence(path, line_no, url, suppressed)) return occurrences @@ -341,10 +342,18 @@ def _probe_with_retry(url: str) -> ProbeOutcome: def _collect_occurrences(root: Path) -> dict[str, list[UrlOccurrence]]: """Collect probe-worthy URLs from all non-ignored repository files.""" + found = [occ for path in _repo_files(root) for occ in _extract_urls(path)] + exempt_at_source = { + _probe_key(occ.url) + for occ in found + if occ.suppressed and occ.file.suffix != _CATALOG_SUFFIX + } by_url: dict[str, list[UrlOccurrence]] = defaultdict(list) - for path in _repo_files(root): - for occurrence in _extract_urls(path): - by_url[_probe_key(occurrence.url)].append(occurrence) + for occ in found: + key = _probe_key(occ.url) + inherited = occ.file.suffix == _CATALOG_SUFFIX and key in exempt_at_source + if not occ.suppressed and not inherited: + by_url[key].append(occ) return dict(by_url) diff --git a/tests/lint/ansible/services/test_cve_suppressions.py b/tests/lint/ansible/services/test_cve_suppressions.py index 878b8617fc..f8f4c1a301 100644 --- a/tests/lint/ansible/services/test_cve_suppressions.py +++ b/tests/lint/ansible/services/test_cve_suppressions.py @@ -27,6 +27,7 @@ import unittest from utils.cache.files import read_text from utils.cache.yaml import load_yaml_str from utils.roles.mapping import ROLE_FILE_META_SERVICES +from utils.security.pipeline import pipeline from utils.security.suppressions import RULE, SuppressionError, parse_entries from . import PROJECT_ROOT @@ -70,6 +71,40 @@ def _marker_problem(lines: list[str], index: int) -> str | None: return None +def _until_problems( + where: str, subject: str, until: dt.date, today: dt.date +) -> list[str]: + found = [] + if until < today: + found.append(f"{where}: {subject} expired on {until}") + if until > LATEST_UNTIL: + found.append( + f"{where}: {subject} until {until} lies after the latest allowed day " + f"{LATEST_UNTIL}" + ) + return found + + +def _unmatched_os_problems( + raw: object, where: str, service: str, today: dt.date +) -> list[str]: + p = pipeline() + try: + releases = p.os_releases(raw) + except p.ConfigError as exc: + return [f"{where}: {service} {exc}"] + return [ + problem + for release in releases + for problem in _until_problems( + where, + f"{service} unmatched_os {release.name} {release.version}", + release.until, + today, + ) + ] + + def problems(text: str, where: str, today: dt.date) -> list[str]: """Return every rule one ``meta/services.yml`` breaks. @@ -88,7 +123,11 @@ def problems(text: str, where: str, today: dt.date) -> list[str]: if not isinstance(services, dict): return found for service, spec in services.items(): - if not isinstance(spec, dict) or "security" not in spec: + if not isinstance(spec, dict): + continue + if "unmatched_os" in spec: + found += _unmatched_os_problems(spec["unmatched_os"], where, service, today) + if "security" not in spec: continue security = spec["security"] entries = security.get("suppressions") if isinstance(security, dict) else None @@ -101,15 +140,12 @@ def problems(text: str, where: str, today: dt.date) -> list[str]: except SuppressionError as exc: found.append(str(exc)) continue - if parsed.until < today: - found.append( - f"{where}: {service} suppression of {parsed.subject} expired on {parsed.until}" - ) - if parsed.until > LATEST_UNTIL: - found.append( - f"{where}: {service} suppression of {parsed.subject} until " - f"{parsed.until} lies after the latest allowed day {LATEST_UNTIL}" - ) + found += _until_problems( + where, + f"{service} suppression of {parsed.subject}", + parsed.until, + today, + ) version = spec.get("version") if parsed.image_tag is not None and parsed.image_tag != str(version): found.append( @@ -168,7 +204,7 @@ class TestCveSuppressions(unittest.TestCase): (PROJECT_ROOT / "roles").glob(f"*/{ROLE_FILE_META_SERVICES}") ): text = read_text(str(path)) - if "suppressions:" in text: + if "suppressions:" in text or "unmatched_os:" in text: found += problems(text, str(path.relative_to(PROJECT_ROOT)), today) self.assertEqual(found, [], "\n".join(found)) @@ -268,6 +304,32 @@ class TestCheckerCases(unittest.TestCase): text = TAGGED.replace("2026-11-30", "2026-10-30") self.assertIn("image tag 2.18.6 expired on 2026-10-30", self._problems(text)[0]) + def test_a_dated_unmatched_os_entry_passes(self) -> None: + self.assertEqual(self._problems(UNMATCHED), []) + + def test_an_expired_unmatched_os_entry_fails(self) -> None: + text = UNMATCHED.replace("2026-11-30", "2026-10-30") + self.assertEqual( + self._problems(text), + [f"{UNMATCHED_SUBJECT} expired on 2026-10-30"], + ) + + def test_an_unmatched_os_entry_after_the_latest_allowed_day_fails(self) -> None: + text = UNMATCHED.replace("2026-11-30", "2026-12-01") + late = "until 2026-12-01 lies after the latest allowed day 2026-11-30" + self.assertEqual(self._problems(text), [f"{UNMATCHED_SUBJECT} {late}"]) + + +UNMATCHED = """\ +trivy: + image: trivy + unmatched_os: + - name: centos + version: "10" + until: 2026-11-30 +""" +UNMATCHED_SUBJECT = f"roles/r/{ROLE_FILE_META_SERVICES}: trivy unmatched_os centos 10" + TAGGED = """\ app: diff --git a/tests/lint/ansible/tasks/test_dnf_commands_assume_yes.py b/tests/lint/ansible/tasks/test_dnf_commands_assume_yes.py new file mode 100644 index 0000000000..111c1b1e90 --- /dev/null +++ b/tests/lint/ansible/tasks/test_dnf_commands_assume_yes.py @@ -0,0 +1,160 @@ +from __future__ import annotations + +import shlex +import unittest +from pathlib import Path + +import yaml + +from utils.cache.files import iter_project_files_with_content + +from . import PROJECT_ROOT + +_COMMAND_MODULES = frozenset( + {"ansible.builtin.command", "command", "ansible.builtin.shell", "shell"} +) +_DNF = frozenset({"dnf", "dnf5", "yum", "microdnf"}) +_ASSUME_YES = frozenset({"-y", "--assumeyes"}) +_READ_ONLY = frozenset( + { + "check-update", + "clean", + "info", + "list", + "provides", + "repolist", + "repoquery", + "search", + } +) + + +def _words(value: yaml.Node) -> list[str]: + if isinstance(value, yaml.ScalarNode): + try: + return shlex.split(value.value) + except ValueError: + return [] + if not isinstance(value, yaml.MappingNode): + return [] + items = {k.value: v for k, v in value.value if isinstance(k, yaml.ScalarNode)} + argv = items.get("argv") + if isinstance(argv, yaml.SequenceNode): + return [n.value for n in argv.value if isinstance(n, yaml.ScalarNode)] + cmd = items.get("cmd") + return _words(cmd) if isinstance(cmd, yaml.ScalarNode) else [] + + +def prompts(words: list[str]) -> bool: + """ + Args: + words: the argv of one command. + + Returns: + Whether the words run a dnf subcommand that may ask a question + without ``-y`` to answer it. + """ + if words[:1] == ["sudo"]: + words = words[1:] + if not words or Path(words[0]).name not in _DNF: + return False + flags = set(words[1:]) + subcommand = next((w for w in words[1:] if not w.startswith("-")), "") + return subcommand not in _READ_ONLY and not flags & _ASSUME_YES + + +def offending_lines(node: yaml.Node) -> list[int]: + """ + Args: + node: a composed YAML node of an Ansible file. + + Returns: + The lines of every command task that runs a prompting dnf call. + """ + if isinstance(node, yaml.SequenceNode): + return [line for child in node.value for line in offending_lines(child)] + if not isinstance(node, yaml.MappingNode): + return [] + found = [] + for key, value in node.value: + if not isinstance(key, yaml.ScalarNode): + continue + if key.value in _COMMAND_MODULES and prompts(_words(value)): + found.append(key.start_mark.line + 1) + found += offending_lines(value) + return found + + +def offenders(rel: str, content: str) -> list[str]: + """ + Args: + rel: the file's path relative to the repository root. + content: the file's text. + + Returns: + ``:`` for every prompting dnf call in ``content``. + """ + try: + docs = list(yaml.compose_all(content, Loader=yaml.SafeLoader)) + except yaml.YAMLError: + return [] + return [f"{rel}:{line}" for doc in docs for line in offending_lines(doc)] + + +def _ansible_files(): + for path, content in iter_project_files_with_content( + extensions=(".yml", ".yaml"), exclude_tests=True + ): + rel = Path(path).relative_to(PROJECT_ROOT).as_posix() + if any(name in content for name in _DNF) and rel.startswith( + ("roles/", "tasks/", "playbooks/") + ): + yield rel, content + + +class TestDnfCommandsAssumeYes(unittest.TestCase): + def test_every_prompting_dnf_command_passes_assume_yes(self) -> None: + found = sorted( + entry + for rel, content in _ansible_files() + for entry in offenders(rel, content) + ) + if found: + self.fail( + "A dnf call without `-y` that can ask a question (a repository " + "key import, a transaction) reads no answer under Ansible and " + "declines it; `dnf makecache --refresh` failed so with " + "`repomd.xml GPG signature verification error: Signing key not " + "found`. Add `-y`:\n" + "\n".join(f" - {entry}" for entry in found) + ) + + def test_makecache_without_assume_yes_is_found(self) -> None: + text = "- ansible.builtin.command:\n argv: [dnf, makecache, --refresh]\n" + self.assertEqual(offenders("x.yml", text), ["x.yml:1"]) + + def test_makecache_with_assume_yes_passes(self) -> None: + text = "- ansible.builtin.command:\n argv: [dnf, makecache, --refresh, -y]\n" + self.assertEqual(offenders("x.yml", text), []) + + def test_a_read_only_subcommand_passes(self) -> None: + text = "- ansible.builtin.command:\n argv: [dnf, clean, metadata]\n" + self.assertEqual(offenders("x.yml", text), []) + + def test_a_shell_string_is_split(self) -> None: + text = "- ansible.builtin.shell: sudo /usr/bin/dnf install foo\n" + self.assertEqual(offenders("x.yml", text), ["x.yml:1"]) + + def test_a_cmd_key_inside_a_block_is_found(self) -> None: + text = ( + "- block:\n - command:\n cmd: yum --assumeyes upgrade\n" + " - command:\n cmd: microdnf upgrade\n" + ) + self.assertEqual(offenders("x.yml", text), ["x.yml:4"]) + + def test_another_program_is_ignored(self) -> None: + text = "- command:\n argv: [apt-get, update]\n" + self.assertEqual(offenders("x.yml", text), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/repository/test_deploy_vulnerability_databases.py b/tests/lint/repository/test_deploy_vulnerability_databases.py index 49b9900199..115b8eb26b 100644 --- a/tests/lint/repository/test_deploy_vulnerability_databases.py +++ b/tests/lint/repository/test_deploy_vulnerability_databases.py @@ -9,11 +9,14 @@ from pathlib import Path from tests.utils import PROJECT_ROOT from utils.cache.files import read_text from utils.cache.yaml import load_yaml_any +from utils.security.engine import ROLE, SCANNERS WORKFLOWS = PROJECT_ROOT / ".github" / "workflows" ENGINE = "INFINITO_VULNERABILITY_ENGINE" DB_HOST_PATH = "INFINITO_VULNERABILITY_DB_HOST_PATH" GITHUB_ONLY = "${{ !env.ACT }}" +DB_PATH = "build/vulnerability-db" +HANDOVER = "vulnerability-db-${{ inputs.index }}-" def steps(workflow: str, job: str) -> list[dict]: @@ -79,6 +82,54 @@ class TestDeployJob(unittest.TestCase): ) +class TestDatabaseHandover(unittest.TestCase): + def setUp(self) -> None: + self.jobs = load_yaml_any(str(WORKFLOWS / "call-test-deploy.yml"))["jobs"] + + def _with(self, job: str, action: str) -> list[dict]: + return [ + step.get("with", {}) + for step in self.jobs[job]["steps"] + if step.get("uses", "").startswith(f"actions/{action}") + ] + + def test_no_deploy_job_reads_a_database_from_the_evictable_cache(self) -> None: + self.assertEqual( + [ + args["path"] + for args in self._with("deploy", "cache") + if args.get("path", "").startswith(DB_PATH) + ], + [], + ) + + def test_every_engine_is_handed_over_per_chunk(self) -> None: + self.assertEqual( + sorted(args["name"] for args in self._with("vulnerability-db", "upload")), + sorted(f"{HANDOVER}{engine}" for engine in SCANNERS), + ) + + def test_a_deploy_downloads_what_the_run_handed_over(self) -> None: + self.assertEqual( + sorted( + args["name"] + for args in self._with("deploy", "download") + if args.get("name", "").startswith(HANDOVER) + ), + [f"{HANDOVER}${{{{ matrix.engine }}}}", f"{HANDOVER}grype"], + ) + + def test_the_osv_cache_key_follows_the_ecosystem_list(self) -> None: + osv = next( + step + for step in self.jobs["vulnerability-db"]["steps"] + if step.get("id") == "osv" + ) + self.assertIn( + f"hashFiles('roles/{ROLE}/meta/services.yml')", osv["with"]["key"] + ) + + class TestWorkspaceJob(unittest.TestCase): def setUp(self) -> None: script = next( diff --git a/tests/unit/python/cli/contributing/security/test_scan.py b/tests/unit/python/cli/contributing/security/test_scan.py index 7fa1f90edb..e29b2b1bcf 100644 --- a/tests/unit/python/cli/contributing/security/test_scan.py +++ b/tests/unit/python/cli/contributing/security/test_scan.py @@ -1,6 +1,8 @@ from __future__ import annotations +import contextlib import datetime as dt +import io import json import tempfile from pathlib import Path @@ -118,7 +120,7 @@ class TestSteps(TestCase): self.assertNotIn("/var/run/docker.sock:/var/run/docker.sock:ro", step.argv) def test_trivy_reads_the_sbom_tree(self): - step = scan_main.trivy_step(P, self.layout, self.target) + step = scan_main.trivy_step(P, self.layout, self.target, []) self.assertEqual(step.argv[step.argv.index("sbom") :][-1], "/sbom/abc.cdx.json") @@ -190,7 +192,7 @@ class TestReport(TestCase): [("r", "s", "CVE-2026-109618")], ) - def test_a_finding_the_role_only_warns_on_still_fails_the_mirror_scan(self): + def test_a_finding_the_role_only_warns_on_is_still_reported(self): verdict = P.Verdict( self._finding("HIGH"), self.target, ("r", "s"), None, False, "warn" ) @@ -202,8 +204,59 @@ class TestReport(TestCase): self.assertLessEqual(set(config.severity.values()), set(P.ACTIONS)) +class TestExitCode(TestCase): + def _run(self, errors): + finding = P.Finding( + "grype", + "abc", + "php-cli", + "8.4.26", + "8.4.27", + ("CVE-2026-109618",), + "CRITICAL", + ) + p = mock.MagicMock() + p.verdicts.return_value = [ + P.Verdict(finding, TestReport.target, ("r", "s"), None, False, "fail") + ] + with ( + tempfile.TemporaryDirectory() as tmp, + mock.patch.object(scan_main, "pipeline", return_value=p), + mock.patch.object( + scan_main, "scan_config", return_value=SimpleNamespace(workers=1) + ), + mock.patch.object(scan_main, "iter_role_images", return_value=[]), + mock.patch.object( + scan_main, + "resolve_digests", + return_value=({}, MIRROR_SOURCES, list(errors)), + ), + mock.patch.object(scan_main, "targets_of", return_value=[]), + mock.patch.object(scan_main, "user_runtime", return_value=("docker",)), + mock.patch.object(scan_main, "scan_tree", return_value=([], [])), + mock.patch.object(scan_main, "suppressions_of", return_value={}), + mock.patch("builtins.print"), + ): + return scan_main.main( + [ + "--cache-dir", + f"{tmp}/cache", + "--report", + f"{tmp}/report.json", + "--workers", + "1", + ] + ) + + def test_an_unsuppressed_finding_alone_passes(self): + self.assertEqual(self._run([]), 0) + + def test_an_engine_error_fails(self): + self.assertEqual(self._run(["trivy img: exited 1"]), 1) + + class TestScanTree(TestCase): - def test_a_cached_sbom_is_not_rebuilt(self): + def _scan_tree(self, cyclonedx, config): with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) for name in ("db", "sbom", "run"): @@ -225,7 +278,7 @@ class TestScanTree(TestCase): ) (root / "sbom" / "abc.syft.json").write_text("{}", encoding="utf-8") (root / "sbom" / "abc.cdx.json").write_text( - json.dumps({"components": []}), encoding="utf-8" + json.dumps(cyclonedx), encoding="utf-8" ) calls = [] @@ -233,14 +286,41 @@ class TestScanTree(TestCase): calls.append(list(argv)) return SimpleNamespace(returncode=0, stdout="", stderr="") - config = scan_main.scan_config(P, 1) - scan_main.scan_tree( - P, [target], {"sha256:abc": "m"}, config, layout, runner - ) + with contextlib.redirect_stdout(io.StringIO()): + scan_main.scan_tree( + P, [target], {"sha256:abc": "m"}, config, layout, runner + ) + return calls + + def test_a_cached_sbom_is_not_rebuilt(self): + calls = self._scan_tree({"components": []}, scan_main.scan_config(P, 1)) self.assertFalse( any(any(arg.startswith("registry:") for arg in call) for call in calls) ) + def test_a_centos_10_sbom_runs_trivy_on_its_library_packages_only(self): + config = P.scan_config( + { + "targets": ["container"], + "engines": ["trivy", "grype", "osv", "syft"], + "severity": {"CRITICAL": "fail"}, + "fixed_only": True, + "workers": 1, + "db_update": True, + "trivy_unmatched_os": [ + {"name": "centos", "version": "10", "until": "9999-12-31"} + ], + } + ) + cyclonedx = { + "components": [ + {"type": "operating-system", "name": "centos", "version": "10"} + ] + } + calls = self._scan_tree(cyclonedx, config) + (trivy,) = [call for call in calls if "/sbom/abc.cdx.json" in call] + self.assertEqual(trivy[trivy.index("--pkg-types") + 1], "library") + if __name__ == "__main__": main() diff --git a/tests/unit/python/roles/dsk-blender/test_architectures.py b/tests/unit/python/roles/dsk-blender/test_architectures.py index e616ebd78b..6b9518f959 100644 --- a/tests/unit/python/roles/dsk-blender/test_architectures.py +++ b/tests/unit/python/roles/dsk-blender/test_architectures.py @@ -6,7 +6,7 @@ from utils.github.variant.pins import draw_pair, row_architectures, row_pairs from utils.github.variant.pools import ARCHITECTURES, DISTROS ROLE = "dsk-blender" -UNPUBLISHED = ("centos", "arm64") +UNPUBLISHED = {"centos", "arch"} def _drawn() -> set[tuple[str, str]]: @@ -31,9 +31,18 @@ class TestBlenderArchitectures(unittest.TestCase): def test_the_role_keeps_every_architecture(self) -> None: self.assertEqual(row_architectures(ROLE, ARCHITECTURES), ARCHITECTURES) + def test_the_matrix_never_plans_arch_on_arm64(self) -> None: + self.assertNotIn( + ("arch", "arm64"), + _drawn(), + "Arch Linux ARM carries no blender package " + "(http://mirror.archlinuxarm.org/aarch64/extra/), so pacman aborts " + "with 'could not find or read package'", + ) + def test_the_matrix_never_plans_centos_on_arm64(self) -> None: self.assertNotIn( - UNPUBLISHED, + ("centos", "arm64"), _drawn(), "centos installs org.blender.Blender from Flathub, which publishes " "it for x86_64 only " @@ -45,7 +54,7 @@ class TestBlenderArchitectures(unittest.TestCase): def test_every_other_distro_still_runs_on_arm64(self) -> None: self.assertEqual( {distro for distro, architecture in _drawn() if architecture == "arm64"}, - set(DISTROS) - {"centos"}, + set(DISTROS) - UNPUBLISHED, ) diff --git a/tests/unit/python/roles/dsk-gnt-cursor/__init__.py b/tests/unit/python/roles/dsk-gnt-cursor/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/dsk-gnt-cursor/test_vendor_repository.py b/tests/unit/python/roles/dsk-gnt-cursor/test_vendor_repository.py new file mode 100644 index 0000000000..4e28d571de --- /dev/null +++ b/tests/unit/python/roles/dsk-gnt-cursor/test_vendor_repository.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +import unittest + +from utils.cache.files import PROJECT_ROOT +from utils.packages.calls import STATE_PRESENT +from utils.packages.plan import build_plan +from utils.packages.registry import build_registry, resolve + +PACKAGE_ID = "cursor" +APT_SOURCES = [ + "/etc/apt/sources.list.d/cursor.list", + "/etc/apt/sources.list.d/cursor.sources", +] +YUM_REPO = ["/etc/yum.repos.d/cursor.repo"] +VENDOR_REPO_FILES: dict[str, list[str]] = { + "centos": YUM_REPO, + "debian": APT_SOURCES, + "fedora": YUM_REPO, + "ubuntu": APT_SOURCES, +} +LOCAL_INSTALL_MODULES = frozenset({"ansible.builtin.apt", "ansible.builtin.dnf"}) + + +def _removed_after_install(distro: str) -> list[str]: + spec = resolve(build_registry(PROJECT_ROOT)[PACKAGE_ID], distro) + plan = build_plan(spec, STATE_PRESENT) + install = next( + index for index, call in enumerate(plan) if call.module in LOCAL_INSTALL_MODULES + ) + return [ + call.args["path"] + for call in plan[install + 1 : -1] + if call.module == "ansible.builtin.file" and call.args.get("state") == "absent" + ] + + +class TestCursorVendorRepository(unittest.TestCase): + def test_the_repository_the_artefact_registers_is_removed(self) -> None: + for distro, repo_files in VENDOR_REPO_FILES.items(): + with self.subTest(distro=distro): + self.assertEqual( + _removed_after_install(distro), + repo_files, + "the pinned cursor rpm's %post writes /etc/yum.repos.d/" + "cursor.repo (repo_gpgcheck=1) and the deb's postinst " + "writes cursor.list or cursor.sources under " + "/etc/apt/sources.list.d; left in place, every " + "roles/update run depends on the vendor repository and " + "its full upgrade moves cursor past the pinned artefact", + ) + + +if __name__ == "__main__": + unittest.main() 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 c1fadcf170..76d23ec951 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 @@ -358,6 +358,30 @@ CYCLONEDX = { } +def _os_sbom(name, version): + return { + "bomFormat": "CycloneDX", + "components": [ + {"type": "operating-system", "name": name, "version": version}, + ], + } + + +CENTOS_10 = _os_sbom("centos", "10") +CENTOS_TARGET = SCRIPT.Target( + "abc", + "container", + "sha256:abc", + "quay.io/centos/centos:stream10", + (("sys-os", "centos"),), + (), +) +UNMATCHED_OS = [ + {"name": "centos", "version": "10", "until": "2026-11-30"}, + {"name": "rhel", "version": "10", "until": "2026-11-30"}, +] + + SEVERITY = {"CRITICAL": "fail", "HIGH": "warn"} STRICT = {"CRITICAL": "fail", "HIGH": "fail"} @@ -370,6 +394,7 @@ def _config(**overrides): "fixed_only": True, "workers": 2, "db_update": True, + "trivy_unmatched_os": [], } raw.update(overrides) return SCRIPT.scan_config(raw) @@ -610,6 +635,69 @@ class TestScanConfig(TestCase): with self.assertRaisesRegex(SCRIPT.ConfigError, "workers"): _config(workers=0) + def test_an_unmatched_os_entry_without_until_is_rejected(self): + with self.assertRaisesRegex(SCRIPT.ConfigError, "until"): + _config(trivy_unmatched_os=[{"name": "centos", "version": "10"}]) + + def test_an_unmatched_os_version_with_a_minor_part_is_rejected(self): + with self.assertRaisesRegex(SCRIPT.ConfigError, "'10.0' of rhel is no bare"): + _config( + trivy_unmatched_os=[ + {"name": "rhel", "version": "10.0", "until": "2026-11-30"} + ] + ) + + +class TestTrivyOsArgs(TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + root = Path(self.tmp.name) + self.layout = SCRIPT.Layout( + runtime=("container", "run"), + databases=root, + sbom=root, + work=root, + excludes=(), + ) + self.target = CENTOS_TARGET + + def tearDown(self): + self.tmp.cleanup() + + def _args(self, sbom, *, scanners=SCRIPT.SCANNERS, today=TODAY): + SCRIPT.sbom_paths(self.layout, self.target)[1].write_text( + json.dumps(sbom), encoding="utf-8" + ) + config = _config(trivy_unmatched_os=UNMATCHED_OS) + with contextlib.redirect_stdout(io.StringIO()) as out: + args = SCRIPT.trivy_os_args( + self.layout, self.target, scanners, config, today + ) + return args, out.getvalue() + + def test_a_centos_10_sbom_leaves_its_os_packages_to_grype(self): + info = ( + "โ„น๏ธ trivy quay.io/centos/centos:stream10: OS packages of centos 10 " + "left to grype until 2026-11-30\n" + ) + self.assertEqual(self._args(CENTOS_10), (["--pkg-types", "library"], info)) + + def test_a_rhel_10_minor_release_matches_its_major_version(self): + self.assertEqual( + self._args(_os_sbom("rhel", "10.0"))[0], ["--pkg-types", "library"] + ) + + def test_debian_and_ubi_9_sboms_keep_the_os_packages_in_trivy(self): + for sbom in (_os_sbom("debian", "13"), _os_sbom("rhel", "9.6")): + with self.subTest(sbom=sbom["components"][0]): + self.assertEqual(self._args(sbom), ([], "")) + + def test_an_expired_entry_keeps_the_os_packages_in_trivy(self): + self.assertEqual(self._args(CENTOS_10, today=dt.date(2026, 12, 1)), ([], "")) + + def test_without_grype_trivy_keeps_the_os_packages(self): + self.assertEqual(self._args(CENTOS_10, scanners=("trivy", "osv")), ([], "")) + class TestParsers(TestCase): def test_trivy_reads_package_versions_and_severity(self): @@ -1186,9 +1274,46 @@ class TestScan(TestCase): "trivy:1", self.targets[0], _config(db_update=False, engines=["syft", "trivy"]), + [], ) self.assertIn("memory", step.argv) + def test_a_centos_10_image_runs_trivy_on_its_library_packages_only(self): + self.targets = [CENTOS_TARGET] + for path, document in zip( + SCRIPT.sbom_paths(self.layout, CENTOS_TARGET), + (SYFT_PHP_IMAGE, CENTOS_10), + strict=True, + ): + path.write_text(json.dumps(document), encoding="utf-8") + unmatched = [ + {**entry, "until": dt.date.max.isoformat()} for entry in UNMATCHED_OS + ] + with contextlib.redirect_stdout(io.StringIO()): + _findings, errors, runner = self._scan( + _config(targets=["container"], trivy_unmatched_os=unmatched), {} + ) + (trivy,) = [call for call in runner.calls if "--image-src" in call] + self.assertEqual( + (errors, trivy[trivy.index("--pkg-types") + 1]), ([], "library") + ) + + def test_a_target_whose_sbom_failed_keeps_its_os_packages_in_trivy(self): + self.targets = [CENTOS_TARGET] + SCRIPT.sbom_paths(self.layout, CENTOS_TARGET)[1].write_text( + '{"components": [', encoding="utf-8" + ) + _findings, errors, runner = self._scan( + _config(targets=["container"], trivy_unmatched_os=UNMATCHED_OS), + {}, + fail=("docker:sha256:abc",), + ) + (trivy,) = [call for call in runner.calls if "--image-src" in call] + self.assertEqual( + (errors, "--pkg-types" in trivy), + (["syft container quay.io/centos/centos:stream10: exited 2: boom"], False), + ) + def test_a_failed_sbom_skips_the_sbom_readers_of_that_target(self): _findings, errors, runner = self._scan( _config(targets=["host"], engines=["syft", "grype"]), @@ -1490,7 +1615,7 @@ class TestCommands(TestCase): ) def test_the_host_is_mounted_read_only(self): - step = SCRIPT.trivy_step(self.layout, "trivy:1", self.host, _config()) + step = SCRIPT.trivy_step(self.layout, "trivy:1", self.host, _config(), []) self.assertIn("/:/host:ro", step.argv) def test_every_engine_writes_its_temp_files_to_its_scratch_in_the_work_mount(self): @@ -1515,7 +1640,7 @@ class TestCommands(TestCase): def test_parallel_engine_runs_never_share_a_scratch(self): steps = [ SCRIPT.sbom_step(self.layout, "syft:1", self.container), - SCRIPT.trivy_step(self.layout, "trivy:1", self.container, _config()), + SCRIPT.trivy_step(self.layout, "trivy:1", self.container, _config(), []), SCRIPT.grype_step(self.layout, "grype:1", self.container, _config()), SCRIPT.runtime_step(self.layout, "grype:1", self.container), SCRIPT.osv_sbom_step(self.layout, "osv:1", [self.container], _config()), @@ -1530,10 +1655,10 @@ class TestCommands(TestCase): "syft container": SCRIPT.sbom_step(self.layout, "syft:1", self.container), "syft host": SCRIPT.sbom_step(self.layout, "syft:1", self.host), "trivy container": SCRIPT.trivy_step( - self.layout, "trivy:1", self.container, _config() + self.layout, "trivy:1", self.container, _config(), [] ), "trivy host": SCRIPT.trivy_step( - self.layout, "trivy:1", self.host, _config() + self.layout, "trivy:1", self.host, _config(), [] ), "grype sbom": SCRIPT.grype_step( self.layout, "grype:1", self.container, _config() @@ -1565,11 +1690,11 @@ class TestCommands(TestCase): self.assertIn(f"/work/{scan.scratch}/image.tar", scan.argv) def test_a_container_scan_reads_the_docker_socket_read_only(self): - step = SCRIPT.trivy_step(self.layout, "trivy:1", self.container, _config()) + step = SCRIPT.trivy_step(self.layout, "trivy:1", self.container, _config(), []) self.assertIn("/var/run/docker.sock:/var/run/docker.sock:ro", step.argv) def test_the_host_scan_skips_the_excluded_paths(self): - step = SCRIPT.trivy_step(self.layout, "trivy:1", self.host, _config()) + step = SCRIPT.trivy_step(self.layout, "trivy:1", self.host, _config(), []) self.assertIn("/host/proc,/host/var/lib/docker", step.argv) def test_syft_scans_the_host_with_the_image_catalogers(self): @@ -2051,6 +2176,7 @@ MAIN_SCAN = { "fixed_only": True, "workers": 1, "db_update": True, + "trivy_unmatched_os": [], } SHIPPED_SCAN = { **MAIN_SCAN, diff --git a/tests/unit/python/roles/web-app-docs/files/test/test_hlth_runtime.py b/tests/unit/python/roles/web-app-docs/files/test/test_hlth_runtime.py new file mode 100644 index 0000000000..e3d7301126 --- /dev/null +++ b/tests/unit/python/roles/web-app-docs/files/test/test_hlth_runtime.py @@ -0,0 +1,113 @@ +from __future__ import annotations + +import json +import os +import subprocess +import sys +import unittest +from pathlib import Path +from tempfile import TemporaryDirectory + +from plugins.filter.merge.with_defaults import merge_with_defaults +from utils.cache.applications import get_application_defaults +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any + +from . import PROJECT_ROOT +from .test_disc_space import _provisioned_vars +from .test_mirror import _block + +HLTH_RUNTIME = ( + PROJECT_ROOT / "roles" / "web-app-docs" / "files" / "test" / "hlth_runtime.py" +) +ROLE = "sys-ctl-hlth-runtime" +DEVELOPMENT_INVENTORY = next( + line.partition("=")[2] + for line in read_text(str(PROJECT_ROOT / "default.env")).splitlines() + if line.startswith("INFINITO_INVENTORY_VARS_FILE=") +) +DEVELOPMENT = load_yaml_any(str(PROJECT_ROOT / DEVELOPMENT_INVENTORY))["applications"][ + ROLE +] +DEFAULTS = get_application_defaults(roles_dir=str(PROJECT_ROOT / "roles")) + + +def _severity(overrides: dict) -> dict: + merged = merge_with_defaults({ROLE: DEFAULTS[ROLE]}, overrides) + return merged[ROLE]["services"]["runtime"]["severity"] + + +STACK = _severity({ROLE: DEVELOPMENT}) +STACK_ENV = {"DOCS_TEST_HLTH_RUNTIME_SEVERITY": json.dumps(STACK)} + + +def _inject(block: str, environment: dict[str, str]) -> str: + with TemporaryDirectory() as directory: + path = Path(directory) / "block.sh" + path.write_text(block, encoding="utf-8") + subprocess.run( + [sys.executable, str(HLTH_RUNTIME), str(path)], + check=True, + capture_output=True, + env={"PATH": os.environ["PATH"], **environment}, + text=True, + ) + return path.read_text( + encoding="utf-8" + ) # nocheck: cache-read -- hlth_runtime.py rewrote this tempfile in the same flow + + +class TestHlthRuntime(unittest.TestCase): + def test_the_replay_provisions_the_stack_severity(self) -> None: + for is_host in (False, True): + with self.subTest(is_host=is_host): + published = _block(is_host=is_host) + provisioned = _provisioned_vars(_inject(published, STACK_ENV)) + carried = provisioned["applications"][ROLE]["services"]["runtime"] + self.assertEqual(carried["severity"], STACK) + for severity, action in DEVELOPMENT["services"]["runtime"][ + "severity" + ].items(): + self.assertEqual(carried["severity"][severity], action) + self.assertEqual( + provisioned, + { + **_provisioned_vars(published), + "applications": {ROLE: {"services": {"runtime": carried}}}, + }, + ) + + def test_the_target_judges_critical_findings_like_the_development_inventory( + self, + ) -> None: + provisioned = _provisioned_vars(_inject(_block(is_host=False), STACK_ENV)) + critical = _severity(provisioned["applications"])["CRITICAL"] + self.assertEqual( + critical, DEVELOPMENT["services"]["runtime"]["severity"]["CRITICAL"] + ) + self.assertNotEqual(critical, _severity({})["CRITICAL"]) + + def test_both_shapes_still_parse_as_bash(self) -> None: + for is_host in (False, True): + with self.subTest(is_host=is_host): + injected = _inject(_block(is_host=is_host), STACK_ENV) + subprocess.run(["bash", "-n"], input=injected, check=True, text=True) + + def test_vars_that_already_set_applications_are_a_failure(self) -> None: + block = _block(is_host=False).replace( + '--vars "{', '--vars "{\\"applications\\": {}, ', 1 + ) + with self.assertRaises(subprocess.CalledProcessError) as raised: + _inject(block, STACK_ENV) + self.assertEqual(raised.exception.returncode, 1) + self.assertIn("already carry", raised.exception.stderr) + + def test_a_block_without_vars_is_a_failure(self) -> None: + with self.assertRaises(subprocess.CalledProcessError) as raised: + _inject("echo nothing to provision\n", STACK_ENV) + self.assertEqual(raised.exception.returncode, 1) + self.assertIn("no single --vars object", raised.exception.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-nextcloud/test_talk_configs.py b/tests/unit/python/roles/web-app-nextcloud/test_talk_configs.py index 7353fcc49d..b734358302 100644 --- a/tests/unit/python/roles/web-app-nextcloud/test_talk_configs.py +++ b/tests/unit/python/roles/web-app-nextcloud/test_talk_configs.py @@ -9,9 +9,10 @@ from typing import ClassVar from jinja2 import Environment, StrictUndefined, select_autoescape +from plugins.filter.resource_filter import resolve_cpus from utils.cache.files import PROJECT_ROOT, read_text from utils.cache.yaml import load_yaml -from utils.roles.mapping import ROLE_FILE_VARS_MAIN +from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_VARS_MAIN ROLE = PROJECT_ROOT / "roles" / "web-app-nextcloud" TEMPLATES = ROLE / "templates" @@ -110,6 +111,20 @@ AIO_RECORDING = { }, } +UPSTREAM_OUTPUT_VIDEO = "-c:v libvpx -deadline:v realtime -crf 10 -b:v 1M" +UPSTREAM_OUTPUT_VIDEO_REF = "v0.3.1" + +RECORDING = { + **AIO_RECORDING, + "ffmpeg": { + **AIO_RECORDING["ffmpeg"], + "outputvideo": f"{UPSTREAM_OUTPUT_VIDEO} -threads:v 4", + }, +} + +ANSIBLE_WORST_VCPU_OVERCOUNT = 4 / 3 +DOCKER_CEILING_MARGIN = 0.95 + STOCK_JANUS = [ "general:{", 'configs_folder="/usr/local/etc/janus"', @@ -210,6 +225,20 @@ def _settings(text: str) -> list[str]: return [joined for line in text.splitlines() if (joined := "".join(line.split()))] +def _recorder() -> dict: + return load_yaml(ROLE / ROLE_FILE_META_SERVICES)["talk_recording"] + + +def _encoder_threads() -> int: + recording = _ini(_render(_template("recording.conf.j2"))) + options = recording["ffmpeg"]["outputvideo"].split() + return int(options[options.index("-threads:v") + 1]) + + +def _cap(cpus, host_cpus) -> float: + return float(resolve_cpus(cpus, host_cpus)) + + class TestSignalingConfig(unittest.TestCase): def test_matches_what_the_aio_start_script_wrote_apart_from_the_split(self): rendered = _ini(_render(_template("signaling.conf.j2"))) @@ -328,13 +357,48 @@ class TestSignalingNetworkBackends(unittest.TestCase): class TestRecordingConfig(unittest.TestCase): - def test_matches_what_the_aio_start_script_wrote(self): - self.assertEqual(_ini(_render(_template("recording.conf.j2"))), AIO_RECORDING) + def test_matches_aio_apart_from_the_encoder_threads(self): + self.assertEqual(_ini(_render(_template("recording.conf.j2"))), RECORDING) + + def test_the_copied_encoder_default_belongs_to_the_pinned_release(self): + self.assertEqual( + _recorder()["ref"], + UPSTREAM_OUTPUT_VIDEO_REF, + "services.talk_recording.ref moved: compare [ffmpeg] outputvideo in " + "server.conf.in of the new ref with UPSTREAM_OUTPUT_VIDEO, update " + "recording.conf.j2 if it changed, then raise UPSTREAM_OUTPUT_VIDEO_REF", + ) def test_negative_control_a_dropped_setting_breaks_parity(self): drifted = _template("recording.conf.j2").replace("maxmessagesize = 1024\n", "") self.assertNotEqual(drifted, _template("recording.conf.j2")) - self.assertNotEqual(_ini(_render(drifted)), AIO_RECORDING) + self.assertNotEqual(_ini(_render(drifted)), RECORDING) + + +class TestRecordingCpus(unittest.TestCase): + HOSTS: ClassVar[tuple[int, ...]] = (4, 8, 11, 16, 24, 32) + + def test_the_cap_scales_with_the_host(self): + cpus = _recorder()["cpus"] + self.assertLess(_cap(cpus, 8), _cap(cpus, 16)) + + def test_the_cap_leaves_the_browser_a_cpu_beside_the_encoder_threads(self): + self.assertGreaterEqual(_cap(_recorder()["cpus"], 8), _encoder_threads() + 1) + + def test_the_cap_stays_below_the_docker_ceiling_when_ansible_overcounts(self): + cpus = _recorder()["cpus"] + for real in self.HOSTS: + with self.subTest(real=real): + reported = real * ANSIBLE_WORST_VCPU_OVERCOUNT + self.assertLessEqual(_cap(cpus, reported), DOCKER_CEILING_MARGIN * real) + + def test_negative_control_the_old_fixed_cap_neither_scales_nor_fits(self): + self.assertEqual(_cap("2.0", 8), _cap("2.0", 16)) + self.assertLess(_cap("2.0", 8), _encoder_threads() + 1) + + def test_negative_control_the_whole_host_crosses_the_docker_ceiling(self): + reported = 24 * ANSIBLE_WORST_VCPU_OVERCOUNT + self.assertGreater(_cap("100%", reported), DOCKER_CEILING_MARGIN * 24) class TestJanusConfig(unittest.TestCase): diff --git a/tests/unit/python/roles/web-app-pihole/__init__.py b/tests/unit/python/roles/web-app-pihole/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-pihole/test_access_denied_redirect.py b/tests/unit/python/roles/web-app-pihole/test_access_denied_redirect.py new file mode 100644 index 0000000000..6a00d05cd2 --- /dev/null +++ b/tests/unit/python/roles/web-app-pihole/test_access_denied_redirect.py @@ -0,0 +1,145 @@ +from __future__ import annotations + +import shutil +import subprocess +import tempfile +import textwrap +import unittest +from pathlib import Path +from unittest import mock + +from ansible.plugins.lookup import LookupBase +from jinja2 import Environment + +import plugins.lookup.network_handover as network_handover +from plugins.filter.text_filters import to_one_liner +from utils.cache.applications import get_application_defaults +from utils.cache.files import PROJECT_ROOT, read_text +from utils.domains.default_primary import default_domain_primary +from utils.roles.applications.config import get + +ROLE = PROJECT_ROOT / "roles" / "web-app-pihole" +SCRIPT = ROLE / "templates" / "javascript.js.j2" +CLEARNET_DOMAIN = f"pihole.{default_domain_primary()}" +ONION_DOMAIN = "pihole." + "a" * 56 + ".onion" + +DRIVER = textwrap.dedent( + """ + const assert = require("assert"); + const script = require("fs").readFileSync(process.argv[2], "utf8"); + const DENIED = "You don't have permission to access this URL." + + " Did you mean to go to your Pi-hole's dashboard instead?"; + + function load(opts) { + const replaced = []; + const ready = []; + global.document = { + readyState: opts.readyState || "complete", + body: { + classList: { contains: (name) => (opts.bodyClasses || []).includes(name) }, + innerText: opts.text || "", + }, + documentElement: {}, + querySelector: (selector) => (selector === "p" && opts.text ? {} : null), + getElementById: () => null, + addEventListener(type, fn) { if (type === "DOMContentLoaded") { ready.push(fn); } }, + }; + global.window = { + location: { pathname: opts.path, replace: (url) => { replaced.push(url); } }, + }; + global.MutationObserver = class { observe() {} }; + eval(script); + return { replaced, domReady() { ready.forEach((fn) => fn()); } }; + } + + (function deniedPageOutsideHomeGoesHome() { + const page = load({ path: "/", bodyClasses: ["login-page", "page-error403"], text: DENIED }); + assert.deepStrictEqual(page.replaced, ["/admin/"]); + })(); + + (function deniedHomeNeverReloadsItself() { + const page = load({ path: "/admin/", bodyClasses: ["login-page", "page-error403"], text: DENIED }); + assert.deepStrictEqual(page.replaced, [], "a 403 on /admin/ itself reloads /admin/ forever"); + })(); + + (function regularPageNamingYourPiholeStays() { + const page = load({ + path: "/admin/groups/clients", + bodyClasses: ["hold-transition", "sidebar-mini", "logged-in"], + text: "Clients that are not assigned to a group use your Pi-hole's default group.", + }); + assert.deepStrictEqual(page.replaced, [], "a help text phrase is no access denial"); + })(); + + (function waitsForTheDomWhenInjectedIntoHead() { + const page = load({ path: "/", readyState: "loading", bodyClasses: ["page-error403"], text: DENIED }); + assert.deepStrictEqual(page.replaced, []); + page.domReady(); + assert.deepStrictEqual(page.replaced, ["/admin/"]); + })(); + + console.log("OK"); + """ +) + + +def _served_script() -> str: + template = Environment(autoescape=True).from_string(read_text(str(SCRIPT))) + return to_one_liner(template.render()) + + +def _have_node() -> bool: + return shutil.which("node") is not None + + +@unittest.skipUnless(_have_node(), "node is not available in PATH") +class TestAccessDeniedRedirect(unittest.TestCase): + def test_only_the_403_page_outside_home_redirects_home(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + script = Path(tmp) / "javascript.js" + script.write_text(_served_script()) + driver = Path(tmp) / "driver.js" + driver.write_text(DRIVER) + proc = subprocess.run( + ["node", str(driver), str(script)], + capture_output=True, + text=True, + check=False, + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertIn("OK", proc.stdout) + + +class _Answer(LookupBase): + def __init__(self, answer): + super().__init__() + self._answer = answer + + def run(self, terms, variables=None, **kwargs): + return [self._answer(*terms)] + + +def _vhost_hands_over(domain: str) -> bool: + applications = get_application_defaults() + + def _config(app, path, default): + return get(applications, app, path, strict=False, default=default) + + answers = {"config": _config, "domain": lambda _app: CLEARNET_DOMAIN} + loader = mock.MagicMock() + loader.get.side_effect = lambda name, **_kwargs: _Answer(answers[name]) + lookup = network_handover.LookupModule() + with mock.patch.object(network_handover, "lookup_loader", loader): + return lookup.run([ROLE.name, domain], variables={"domain": domain})[0] + + +class TestOnionHandover(unittest.TestCase): + def test_the_onion_vhost_hands_over_to_the_one_ftl_webserver_domain(self) -> None: + self.assertIs(_vhost_hands_over(ONION_DOMAIN), True) + + def test_the_clearnet_vhost_keeps_serving(self) -> None: + self.assertIs(_vhost_hands_over(CLEARNET_DOMAIN), False) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/scripts/image/__init__.py b/tests/unit/python/scripts/image/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/scripts/image/test_build_cache_prune.py b/tests/unit/python/scripts/image/test_build_cache_prune.py new file mode 100644 index 0000000000..1866dfbedb --- /dev/null +++ b/tests/unit/python/scripts/image/test_build_cache_prune.py @@ -0,0 +1,107 @@ +from __future__ import annotations + +import os +import subprocess +import tempfile +import unittest +from pathlib import Path + +from utils import PROJECT_ROOT +from utils.cache.files import read_text + +SCRIPT = PROJECT_ROOT / "scripts" / "image" / "build.sh" + +DOCKER_STUB = """#!/usr/bin/env bash +printf '%s\\n' "$*" >>"${STUB_LOG}" +if [ "$1 $2" = "image inspect" ]; then +\texit 1 +fi +if [ "$1 $2 $3" = "builder prune --help" ]; then +\tprintf '%s\\n' "${STUB_PRUNE_HELP}" +fi +""" + +MAX_USED = " --max-used-space bytes Maximum amount of disk space allowed to keep for cache" +KEEP_STORAGE = " --keep-storage bytes Amount of disk space to keep for cache" +NEITHER = " -a, --all Remove all unused build cache, not just dangling ones" + + +def _build(prune_help: str, cap: str) -> tuple[int, list[str], str]: + """Args: + prune_help: what `docker builder prune --help` prints on the stubbed engine. + cap: the INFINITO_BUILD_CACHE_MAX_SIZE of the build. + + Returns: + The exit code, every docker call and the combined output. + """ + with tempfile.TemporaryDirectory() as tmp: + bin_dir = Path(tmp) / "bin" + bin_dir.mkdir() + stub = bin_dir / "docker" + stub.write_text(DOCKER_STUB) + stub.chmod(0o755) + log = Path(tmp) / "calls" + env = dict(os.environ) + env.update( + { + "PATH": f"{bin_dir}{os.pathsep}{env['PATH']}", + "HOME": tmp, + "STUB_LOG": str(log), + "STUB_PRUNE_HELP": prune_help, + "INFINITO_DISTRO": "debian", + "INFINITO_PARENT_IMAGE": "debian:stable", + "INFINITO_IMAGE_REPOSITORY": "probe", + "INFINITO_SRC_DIR": "/opt/src/infinito", + "INFINITO_VENV_DIR": "/opt/venvs/infinito", + "INFINITO_PACKAGE_INSTALL_SCRIPT": "package.sh", + "INFINITO_PYTHON_INSTALL_SCRIPT": "python.sh", + "INFINITO_DOCKER_CLI_INSTALL_SCRIPT": "docker-cli.sh", + "INFINITO_BUILD_CACHE_MAX_SIZE": cap, + "GITHUB_REPOSITORY_OWNER": "probe-owner", + } + ) + for key in ("GITHUB_REPOSITORY", "OWNER"): + env.pop(key, None) + done = subprocess.run( + ["bash", str(SCRIPT), "--tag", "probe/debian:dev-1"], + cwd=tmp, + env=env, + capture_output=True, + text=True, + check=False, + ) + calls = read_text(str(log)).splitlines() if log.exists() else [] + return done.returncode, calls, done.stdout + done.stderr + + +class TestBuildCachePrune(unittest.TestCase): + def test_a_build_ends_with_a_prune_down_to_the_cap(self) -> None: + code, calls, _ = _build(MAX_USED, "20g") + self.assertEqual(code, 0) + builds = [i for i, call in enumerate(calls) if call.startswith("build ")] + self.assertEqual(len(builds), 1) + self.assertEqual(calls[-1], "builder prune --force --max-used-space 20g") + self.assertGreater(len(calls) - 1, builds[0]) + + def test_an_older_engine_prunes_with_keep_storage(self) -> None: + code, calls, _ = _build(KEEP_STORAGE, "20g") + self.assertEqual(code, 0) + self.assertEqual(calls[-1], "builder prune --force --keep-storage 20g") + + def test_the_prune_follows_the_cap(self) -> None: + _, calls, _ = _build(MAX_USED, "7g") + self.assertEqual(calls[-1], "builder prune --force --max-used-space 7g") + + def test_an_engine_without_a_keep_flag_fails_the_build_loudly(self) -> None: + code, calls, output = _build(NEITHER, "20g") + self.assertNotEqual(code, 0) + self.assertFalse( + any(call.startswith("builder prune --force") for call in calls) + ) + self.assertIn("--max-used-space", output) + self.assertIn("--keep-storage", output) + self.assertIn("INFINITO_BUILD_CACHE_MAX_SIZE", output) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/tests/external/__init__.py b/tests/unit/python/tests/external/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/tests/external/repository/__init__.py b/tests/unit/python/tests/external/repository/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/tests/external/repository/test_urls_reachable.py b/tests/unit/python/tests/external/repository/test_urls_reachable.py new file mode 100644 index 0000000000..f36b6d5a3c --- /dev/null +++ b/tests/unit/python/tests/external/repository/test_urls_reachable.py @@ -0,0 +1,66 @@ +from __future__ import annotations + +import os +import tempfile +import unittest +import unittest.mock as mock +from pathlib import Path + +from utils.cache.yaml import load_yaml_any +from utils.licensing.roles import declared +from utils.roles.mapping import ROLE_FILE_META_INFO, ROLE_FILE_META_LICENSE + +with mock.patch.dict(os.environ, {"INFINITO_WORKER_FETCH": "1"}): + from tests.external.repository import test_urls_reachable as urls + +ROLE = urls._REPO_ROOT / "roles" / "dsk-virtualbox" +INFO = ROLE / ROLE_FILE_META_INFO +HOMEPAGE = load_yaml_any(str(INFO))["homepage"] +LICENCE = declared(ROLE).url +MUTED = "https://muted.infinito.nexus/page" # nocheck: url +KEPT = "https://kept.infinito.nexus/page" # nocheck: url + + +def _collect(*paths: Path) -> dict[str, list]: + with mock.patch.object(urls, "_repo_files", return_value=list(paths)): + return urls._collect_occurrences(urls._REPO_ROOT) + + +def _write(path: Path, text: str) -> Path: + path.write_text(text, encoding="utf-8") + return path + + +class TestSourceMarkerCoversCatalogs(unittest.TestCase): + def test_virtualbox_catalog_entry_inherits_the_role_markers(self) -> None: + self.assertTrue(all(map(urls._is_live_literal_url, (HOMEPAGE, LICENCE)))) + with tempfile.TemporaryDirectory() as scratch: + catalog = _write( + Path(scratch) / "docs.po", + f'msgid "[a]({LICENCE}) and [b]({KEPT})"\nmsgstr ""\n', + ) + + collected = _collect(INFO, ROLE / ROLE_FILE_META_LICENSE, catalog) + + self.assertIsNone(collected.get(HOMEPAGE)) + self.assertIsNone(collected.get(LICENCE)) + self.assertEqual([occ.file for occ in collected[KEPT]], [catalog]) + + def test_an_unmarked_source_line_keeps_its_url_probed(self) -> None: + with tempfile.TemporaryDirectory() as scratch: + root = Path(scratch) + marked = _write(root / "meta.yml", f"url: {MUTED} # nocheck: url\n") + readme = _write(root / "README.md", f"See {MUTED}.\n") + catalog = _write( + root / "docs.po", f'# nocheck: url\nmsgid "{KEPT}"\nmsgstr ""\n' + ) + notes = _write(root / "NOTES.md", f"See {KEPT}.\n") + + collected = _collect(marked, readme, catalog, notes) + + self.assertEqual([occ.file for occ in collected[MUTED]], [readme]) + self.assertEqual([occ.file for occ in collected[KEPT]], [notes]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/env/test_runtime.py b/tests/unit/python/utils/env/test_runtime.py index b1d94cf97c..7dbd0bed65 100644 --- a/tests/unit/python/utils/env/test_runtime.py +++ b/tests/unit/python/utils/env/test_runtime.py @@ -25,7 +25,7 @@ from utils.env.runtime import ( mem_available_mb, mem_stall_pct, run_helper, - uninterruptible_procs, + uninterruptible_switches, ) _PRESSURE = ( @@ -222,47 +222,70 @@ class TestPressureStalls(unittest.TestCase): self.assertEqual(io_stall_pct(), 0.0) -class TestUninterruptibleProcs(unittest.TestCase): +_STATUS = "Name:\tx\nvoluntary_ctxt_switches:\t{vol}\nnonvoluntary_ctxt_switches:\t2\n" + + +class TestUninterruptibleSwitches(unittest.TestCase): """A wedged mount leaves processes in D state; the count is the trace.""" - def _run(self, entries: list[str], stats: dict[str, str]) -> int: + def _run( + self, + entries: list[str], + stats: dict[str, str], + statuses: dict[str, str] | None = None, + ) -> dict[str, int]: + if statuses is None: + statuses = {pid: _STATUS.format(vol=pid) for pid in stats} files = {f"/proc/{pid}/stat": text for pid, text in stats.items()} + files |= {f"/proc/{pid}/status": text for pid, text in statuses.items()} with ( patch("utils.env.runtime.os.listdir", return_value=entries), patch("utils.env.runtime.Path", _fake_proc(files)), ): - return uninterruptible_procs() + return uninterruptible_switches() - def test_counts_only_the_d_state(self) -> None: + def test_keeps_only_the_d_state(self) -> None: stats = { "1": "1 (systemd) S 0 1 1 0 -1 4194560 1 2 3", "2": "2 (rsync) D 1 2 2 0 -1 1077936128 4 5 6", "3": "3 (mount.nfs) D 1 3 3 0 -1 1077936128 7 8 9", "4": "4 (python3) R 1 4 4 0 -1 4194304 1 1 1", } - self.assertEqual(self._run(["1", "2", "3", "4"], stats), 2) + self.assertEqual(sorted(self._run(["1", "2", "3", "4"], stats)), ["2", "3"]) + + def test_sums_voluntary_and_involuntary_switches(self) -> None: + stats = {"40": "40 (rsync) D 1 40 40 0 -1 0 0 0 0"} + self.assertEqual(self._run(["40"], stats), {"40": 42}) def test_a_comm_with_spaces_and_parens_does_not_shift_the_state(self) -> None: stats = {"7": "7 (weird )name( here) D 1 7 7 0 -1 0 0 0 0"} - self.assertEqual(self._run(["7"], stats), 1) + self.assertEqual(sorted(self._run(["7"], stats)), ["7"]) def test_non_numeric_proc_entries_are_skipped(self) -> None: stats = {"5": "5 (bash) D 1 5 5 0 -1 0 0 0 0"} self.assertEqual( - self._run(["self", "meminfo", "cpuinfo", "5"], stats), - 1, + sorted(self._run(["self", "meminfo", "cpuinfo", "5"], stats)), + ["5"], ) def test_a_process_vanishing_mid_scan_is_tolerated(self) -> None: stats = {"9": "9 (bash) D 1 9 9 0 -1 0 0 0 0"} - self.assertEqual(self._run(["8", "9"], stats), 1) + self.assertEqual(sorted(self._run(["8", "9"], stats)), ["9"]) - def test_unreadable_proc_returns_zero(self) -> None: + def test_a_d_task_whose_status_vanished_is_skipped(self) -> None: + stats = {"9": "9 (bash) D 1 9 9 0 -1 0 0 0 0"} + self.assertEqual(self._run(["9"], stats, statuses={}), {}) + + def test_a_status_without_the_counters_is_skipped(self) -> None: + stats = {"9": "9 (bash) D 1 9 9 0 -1 0 0 0 0"} + self.assertEqual(self._run(["9"], stats, statuses={"9": "Name:\tx\n"}), {}) + + def test_unreadable_proc_returns_empty(self) -> None: with patch("utils.env.runtime.os.listdir", side_effect=OSError): - self.assertEqual(uninterruptible_procs(), 0) + self.assertEqual(uninterruptible_switches(), {}) def test_empty_stat_is_tolerated(self) -> None: - self.assertEqual(self._run(["11"], {"11": ""}), 0) + self.assertEqual(self._run(["11"], {"11": ""}), {}) class TestIsWsl2(unittest.TestCase): diff --git a/tests/unit/python/utils/packages/test_plan.py b/tests/unit/python/utils/packages/test_plan.py index 2b5ecd01be..a3884a0f6c 100644 --- a/tests/unit/python/utils/packages/test_plan.py +++ b/tests/unit/python/utils/packages/test_plan.py @@ -293,6 +293,28 @@ class TestDownloadSource(unittest.TestCase): self.assertEqual(install.args["state"], STATE_PRESENT) self.assertEqual(confirm.args["name"], ["editor"]) + def test_declared_repo_files_are_removed_before_the_confirm(self): + repo_file = "/etc/yum.repos.d/editor.repo" + plan = build_plan( + PackageSpec( + ("editor",), + source=SOURCE_DOWNLOAD, + download={**_RPM, "repo_files": [repo_file]}, + ), + STATE_PRESENT, + ) + self.assertEqual( + _modules(plan), + [ + "ansible.builtin.file", + "ansible.builtin.get_url", + "ansible.builtin.dnf", + "ansible.builtin.file", + "ansible.builtin.package", + ], + ) + self.assertEqual(plan[3].args, {"path": repo_file, "state": "absent"}) + def test_an_unsupported_artefact_is_refused(self): spec = PackageSpec( ("editor",), diff --git a/tests/unit/python/utils/packages/test_registry.py b/tests/unit/python/utils/packages/test_registry.py index 7ecb27b51d..e1e235460f 100644 --- a/tests/unit/python/utils/packages/test_registry.py +++ b/tests/unit/python/utils/packages/test_registry.py @@ -257,6 +257,43 @@ class TestRegistry(unittest.TestCase): self.assertEqual(spec.source, "download") self.assertEqual(spec.download["url"], "https://vendor.example/editor.deb") + def _download_repo_files(self, repo_files): + _write_role( + self.root, + "role-a", + { + "editor": { + "RedHat": { + "names": ["editor"], + "source": "download", + "download": { + "url": "https://vendor.example/editor.rpm", + "checksum": "sha256:" + "a" * 64, + "repo_files": repo_files, + }, + } + } + }, + ) + return resolve(self._declaration("editor"), "fedora") + + def test_download_repo_files_under_a_repo_dir_resolve(self): + spec = self._download_repo_files(["/etc/yum.repos.d/editor.repo"]) + self.assertEqual(spec.download["repo_files"], ["/etc/yum.repos.d/editor.repo"]) + + def test_download_repo_files_outside_a_repo_dir_raise(self): + for repo_files in ( + ["/etc/passwd"], + ["/etc/yum.repos.d/../shadow"], + ["/etc/yum.repos.d"], + ["etc/yum.repos.d/editor.repo"], + "/etc/yum.repos.d/editor.repo", + ): + with self.subTest(repo_files=repo_files): + with self.assertRaises(PackagesShapeError) as ctx: + self._download_repo_files(repo_files) + self.assertIn("repo_files", str(ctx.exception)) + def _architectures(self, value): entry = {"names": ["org.example.App"], "source": "flatpak"} if value is not None: diff --git a/tests/unit/python/utils/security/test_deploy.py b/tests/unit/python/utils/security/test_deploy.py index eedbec8074..1a819e68e5 100644 --- a/tests/unit/python/utils/security/test_deploy.py +++ b/tests/unit/python/utils/security/test_deploy.py @@ -3,12 +3,15 @@ from __future__ import annotations import contextlib import io import random +import re import tempfile from pathlib import Path from unittest import TestCase, main, mock from utils.security import deploy +from utils.security.database import database_files from utils.security.engine import ENGINE_ENV, ROLE, databases_for +from utils.security.pipeline import pipeline class TestInventoryOverrides(TestCase): @@ -66,19 +69,31 @@ class TestInventoryOverrides(TestCase): with self.assertRaisesRegex(SystemExit, "no network"): self._overrides("", errors=["grype database: no network"]) + def _provide(self, name, skip=0): + files = database_files(pipeline(), self.root, name) + for path in files[: len(files) - skip]: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("x", encoding="utf-8") + return files + def test_a_pinned_engine_never_downloads(self): for name in ("trivy", "grype"): - (self.root / name).mkdir() - (self.root / name / "db").write_text("x", encoding="utf-8") + self._provide(name) self.assertEqual( self._runtime(self._overrides("trivy"))["engines"], ["syft", "trivy"] ) self.assertEqual(self.refreshed, []) def test_a_pinned_engine_without_its_databases_fails(self): - (self.root / "grype").mkdir() - (self.root / "grype" / "db").write_text("x", encoding="utf-8") - with self.assertRaisesRegex(SystemExit, "no osv database"): + self._provide("grype") + first = database_files(pipeline(), self.root, "osv")[0] + with self.assertRaisesRegex(SystemExit, re.escape(str(first))): + self._overrides("osv") + + def test_an_osv_database_without_one_ecosystem_fails(self): + self._provide("grype") + missing = self._provide("osv", skip=1)[-1] + with self.assertRaisesRegex(SystemExit, re.escape(str(missing))): self._overrides("osv") diff --git a/tests/unit/python/utils/security/test_engine.py b/tests/unit/python/utils/security/test_engine.py index cfd809c110..cacb4bc390 100644 --- a/tests/unit/python/utils/security/test_engine.py +++ b/tests/unit/python/utils/security/test_engine.py @@ -36,6 +36,7 @@ class TestEnginesFor(TestCase): "fixed_only": True, "workers": 2, "db_update": False, + "trivy_unmatched_os": [], } ) self.assertEqual(list(config.databases()), engine.databases_for(name)) diff --git a/tests/unit/python/utils/security/test_pipeline.py b/tests/unit/python/utils/security/test_pipeline.py index 0e21e21bd6..e46f2f36f0 100644 --- a/tests/unit/python/utils/security/test_pipeline.py +++ b/tests/unit/python/utils/security/test_pipeline.py @@ -23,9 +23,15 @@ class TestPipeline(TestCase): self.assertEqual(pipeline.user_runtime()[-1], f"{os.getuid()}:{os.getgid()}") def test_the_role_default_is_a_valid_scan_config(self): - runtime = pipeline.role_services()["runtime"] + services = pipeline.role_services() + runtime = services["runtime"] keys = ("targets", "engines", "severity", "fixed_only", "workers", "db_update") - config = pipeline.pipeline().scan_config({key: runtime[key] for key in keys}) + config = pipeline.pipeline().scan_config( + { + **{key: runtime[key] for key in keys}, + "trivy_unmatched_os": services["trivy"]["unmatched_os"], + } + ) self.assertLessEqual( set(config.severity.values()), set(pipeline.pipeline().ACTIONS) ) diff --git a/tests/unit/python/utils/tests/swarm/test_run_storage_roots.py b/tests/unit/python/utils/tests/swarm/test_run_storage_roots.py index b5a19287df..5af97fedf7 100644 --- a/tests/unit/python/utils/tests/swarm/test_run_storage_roots.py +++ b/tests/unit/python/utils/tests/swarm/test_run_storage_roots.py @@ -86,7 +86,7 @@ def watch( mock.patch.object(watchdog, "mem_stall_pct", return_value=0.0), mock.patch.object(watchdog, "io_stall_pct", return_value=0.0), mock.patch.object(watchdog, "cpu_stall_pct", return_value=0.0), - mock.patch.object(watchdog, "uninterruptible_procs", return_value=0), + mock.patch.object(watchdog, "uninterruptible_switches", return_value={}), mock.patch("builtins.print", printed), ): rc = watchdog.run_watched(["step"], env={}) diff --git a/tests/unit/python/utils/tests/swarm/test_watchdog.py b/tests/unit/python/utils/tests/swarm/test_watchdog.py index b93b6741da..f133436227 100644 --- a/tests/unit/python/utils/tests/swarm/test_watchdog.py +++ b/tests/unit/python/utils/tests/swarm/test_watchdog.py @@ -11,13 +11,38 @@ the sampling cadence that decides how stale the last sample is. import contextlib import io +import itertools import signal import subprocess import unittest import unittest.mock as mock +from collections.abc import Callable from utils.tests.swarm import watchdog +_HUNG_SAMPLES = watchdog.HUNG_TASK_S // watchdog.SAMPLE_INTERVAL_S +_STUCK_DISK = {"101": 0, "102": 0, "103": 0} +_BUSY_DISK = {str(pid): 1 for pid in range(201, 209)} +_STALE_NFS = {"301": 0, "302": 0} | _BUSY_DISK + + +def _switches(periods: dict[str, int]) -> Callable[[], dict[str, int]]: + """ + Args: + periods: per D-state pid the samples between two of its context + switches; 0 for a task that never switches. + + Returns: + An uninterruptible_switches() stand-in advancing on every call. + """ + calls = itertools.count() + + def sample() -> dict[str, int]: + n = next(calls) + return {pid: n // period if period else 0 for pid, period in periods.items()} + + return sample + class _FakeProc: pid = 4242 @@ -51,6 +76,7 @@ class TestSampleLine(unittest.TestCase): "io_stall": 0.0, "cpu_stall": 0.0, "dstate": 0, + "hung": 0, } fields.update(overrides) return watchdog.sample_line(**fields) # type: ignore[arg-type] @@ -68,6 +94,9 @@ class TestSampleLine(unittest.TestCase): self.assertIn("cpu60 13.5%", line) self.assertIn("dstate 4", line) + def test_it_carries_the_hung_task_count(self) -> None: + self.assertIn("dstate 9, hung 2 ===", self._render(dstate=9, hung=2)) + def test_it_stays_one_greppable_banner(self) -> None: line = self._render() self.assertTrue(line.startswith("=== swarm-matrix: host mem ")) @@ -92,7 +121,7 @@ class TestRunWatched(unittest.TestCase): avail: int = 9324, total: int = 15947, free_mb: int = 38948, - dstate: int = 3, + blocked: dict[str, int] = _STUCK_DISK, ) -> tuple[int, str, _FakeProc]: proc = _FakeProc(timeouts=timeouts, rc=rc) buffer = io.StringIO() @@ -117,7 +146,9 @@ class TestRunWatched(unittest.TestCase): mock.patch.object(watchdog, "mem_stall_pct", return_value=0.0), mock.patch.object(watchdog, "io_stall_pct", return_value=io_stall), mock.patch.object(watchdog, "cpu_stall_pct", return_value=11.0), - mock.patch.object(watchdog, "uninterruptible_procs", return_value=dstate), + mock.patch.object( + watchdog, "uninterruptible_switches", side_effect=_switches(blocked) + ), contextlib.redirect_stdout(buffer), ): returned = watchdog.run_watched(["true"], env={}) @@ -153,7 +184,51 @@ class TestRunWatched(unittest.TestCase): def test_a_busy_disk_with_nothing_blocked_is_not_a_wedge(self) -> None: returned, output, proc = self._watch( - timeouts=_WEDGE_SAMPLES, rc=0, io_stall=99.0, dstate=0 + timeouts=_WEDGE_SAMPLES, rc=0, io_stall=99.0, blocked={} + ) + self.assertEqual(returned, 0) + self.assertFalse(proc.terminated) + self.assertNotIn("I/O WEDGE", output) + + def test_a_busy_local_disk_whose_d_tasks_keep_waking_is_not_a_wedge( + self, + ) -> None: + returned, output, proc = self._watch( + timeouts=_WEDGE_SAMPLES * 2, rc=0, io_stall=99.0, blocked=_BUSY_DISK + ) + self.assertEqual(returned, 0) + self.assertFalse(proc.terminated) + self.assertNotIn("I/O WEDGE", output) + self.assertIn("dstate 8, hung 0 ===", output) + + def test_a_stuck_local_disk_is_a_wedge(self) -> None: + returned, output, proc = self._watch( + timeouts=_WEDGE_SAMPLES, rc=0, io_stall=99.0, blocked=_STUCK_DISK + ) + self.assertEqual(returned, watchdog.ABORT_RC) + self.assertTrue(proc.terminated) + self.assertIn( + f"3 task(s) in D state, 3 hung for {watchdog.HUNG_TASK_S}s+", output + ) + + def test_a_stale_nfs_mount_beside_a_busy_local_disk_is_a_wedge(self) -> None: + returned, output, proc = self._watch( + timeouts=_WEDGE_SAMPLES, rc=0, io_stall=99.0, blocked=_STALE_NFS + ) + self.assertEqual(returned, watchdog.ABORT_RC) + self.assertTrue(proc.terminated) + self.assertIn( + f"10 task(s) in D state, 2 hung for {watchdog.HUNG_TASK_S}s+", output + ) + + def test_a_task_blocked_shorter_than_the_hung_threshold_is_not_a_wedge( + self, + ) -> None: + returned, output, proc = self._watch( + timeouts=_WEDGE_SAMPLES * 2, + rc=0, + io_stall=99.0, + blocked={"401": _HUNG_SAMPLES}, ) self.assertEqual(returned, 0) self.assertFalse(proc.terminated) @@ -218,5 +293,25 @@ class TestRunWatched(unittest.TestCase): self.assertEqual(touched, sorted([signal.SIGINT, signal.SIGTERM] * 2)) +class TestBlockedStreaks(unittest.TestCase): + def test_a_task_without_a_context_switch_extends_its_streak(self) -> None: + streaks = watchdog.blocked_streaks({"7": (40, 2)}, {"7": 40}) + self.assertEqual(streaks, {"7": (40, 3)}) + + def test_a_context_switch_resets_the_streak(self) -> None: + streaks = watchdog.blocked_streaks({"7": (40, 2)}, {"7": 41}) + self.assertEqual(streaks, {"7": (41, 0)}) + + def test_a_task_new_to_d_starts_at_zero_and_a_woken_one_is_dropped( + self, + ) -> None: + streaks = watchdog.blocked_streaks({"7": (40, 2)}, {"8": 0}) + self.assertEqual(streaks, {"8": (0, 0)}) + + def test_only_streaks_spanning_the_hung_threshold_count(self) -> None: + streaks = {"1": (0, _HUNG_SAMPLES), "2": (0, _HUNG_SAMPLES - 1)} + self.assertEqual(watchdog.hung_tasks(streaks), 1) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/utils/update/test_repository.py b/tests/unit/python/utils/update/test_repository.py index fc433c782b..f72183249d 100644 --- a/tests/unit/python/utils/update/test_repository.py +++ b/tests/unit/python/utils/update/test_repository.py @@ -16,6 +16,7 @@ from utils.update.repository import ( collect_entries, find_outdated_updates, git_ls_remote_head, + git_ref_resolves, is_commit_sha, suppressed_ref_lines, update_config_refs, @@ -441,6 +442,54 @@ class TestGitLsRemoteHead(unittest.TestCase): self.assertIsNone(git_ls_remote_head(SHA_REPO)) +class TestGitRefResolves(unittest.TestCase): + def _resolves( + self, stdout: str, returncode: int = 0 + ) -> tuple[bool | None, list[list[str]]]: + calls: list[list[str]] = [] + + def run(argv: list[str], **_kwargs) -> subprocess.CompletedProcess: + calls.append(argv) + return subprocess.CompletedProcess(argv, returncode, stdout, "") + + with mock.patch.object(module.subprocess, "run", side_effect=run): + return git_ref_resolves(TAG_REPO, "v4.0.2"), calls + + def test_a_branch_or_a_peeled_tag_of_that_name_resolves(self) -> None: + for stdout in ( + f"{TIP_SHA}\trefs/heads/v4.0.2\n", + f"{TIP_SHA}\trefs/tags/v4.0.2^{{}}\n", + ): + with self.subTest(stdout=stdout): + resolved, calls = self._resolves(stdout) + self.assertIs(resolved, True) + self.assertEqual( + calls, + [ + [ + "git", + "ls-remote", + TAG_REPO, + "refs/heads/v4.0.2", + "refs/tags/v4.0.2", + ] + ], + ) + + def test_a_name_listed_only_elsewhere_does_not_resolve(self) -> None: + for stdout in ( + "", + f"{TIP_SHA}\trefs/heads/release/v4.0.2\n", + f"{TIP_SHA}\trefs/pull/7/head\n", + ): + with self.subTest(stdout=stdout): + self.assertIs(self._resolves(stdout)[0], False) + + def test_a_failed_lookup_is_indeterminate(self) -> None: + resolved, _calls = self._resolves(f"{TIP_SHA}\trefs/heads/v4.0.2\n", 128) + self.assertIsNone(resolved) + + class TestCommitShaPins(unittest.TestCase): def test_an_outdated_sha_is_rewritten_to_the_tip(self) -> None: with tempfile.TemporaryDirectory() as tmpdir: diff --git a/tests/unit/python/utils/update/test_source.py b/tests/unit/python/utils/update/test_source.py index e9bbeeadf6..9cd20463d4 100644 --- a/tests/unit/python/utils/update/test_source.py +++ b/tests/unit/python/utils/update/test_source.py @@ -1,6 +1,8 @@ from __future__ import annotations +import contextlib import io +import subprocess import tempfile import unittest import unittest.mock as mock @@ -9,6 +11,7 @@ from email.message import Message from pathlib import Path from utils.roles.mapping import ROLE_DIR_META_ADDONS, ROLE_FILE_META_SERVICES +from utils.update import repository from utils.update import source as module SERVICES = """\ @@ -139,6 +142,20 @@ second: until: 2026-11-30 """ +STACK = "https://example.test/stack.git" + +REF_PINNED = f"""\ +--- +stack: + repository: {STACK} + ref: v3.0.39 + update: + key: ref + type: http_regex + url: https://example.test/tags + pattern: 'core (v[0-9.]+)' +""" + def _repo(services: str = SERVICES) -> Path: tmp = Path(tempfile.mkdtemp()) @@ -311,6 +328,75 @@ class TestPulledImage(unittest.TestCase): self.assertEqual(entries, {"app_version": "", "version": "example"}) +class TestCheckedOutRef(unittest.TestCase): + def _outdated( + self, services: str, listed: str, returncode: int = 0 + ) -> tuple[list[str], list[list[str]], str]: + root = _repo(services) + calls: list[list[str]] = [] + + def ls_remote(argv: list[str], **_kwargs) -> subprocess.CompletedProcess: + calls.append(argv) + return subprocess.CompletedProcess(argv, returncode, listed, "") + + stderr = io.StringIO() + with ( + mock.patch.object(module, "documents", return_value="core v4.0.2\n"), + mock.patch.object(repository.subprocess, "run", side_effect=ls_remote), + contextlib.redirect_stderr(stderr), + ): + updates = module.outdated(module.collect_entries(root), root) + return [update.latest for update in updates], calls, stderr.getvalue() + + def test_a_ref_the_repository_lists_as_branch_or_tag_is_proposed(self) -> None: + for listed in ( + f"{'1' * 40}\trefs/heads/v4.0.2\n", + f"{'1' * 40}\trefs/tags/v4.0.2\n{'2' * 40}\trefs/tags/v4.0.2^{{}}\n", + ): + with self.subTest(listed=listed): + latest, calls, stderr = self._outdated(REF_PINNED, listed) + self.assertEqual(latest, ["v4.0.2"]) + self.assertEqual(stderr, "") + self.assertEqual( + calls, + [ + [ + "git", + "ls-remote", + STACK, + "refs/heads/v4.0.2", + "refs/tags/v4.0.2", + ] + ], + ) + + def test_a_ref_the_repository_does_not_list_is_withheld_and_reported( + self, + ) -> None: + latest, _calls, stderr = self._outdated( + REF_PINNED, f"{'1' * 40}\trefs/heads/develop\n" + ) + self.assertEqual(latest, []) + self.assertIn("WARN web-app-example/stack.ref", stderr) + self.assertIn("lists no branch or tag of that name", stderr) + self.assertIn("withholding v3.0.39 -> v4.0.2", stderr) + + def test_a_failed_lookup_withholds_the_ref(self) -> None: + latest, _calls, stderr = self._outdated( + REF_PINNED, f"{'1' * 40}\trefs/heads/v4.0.2\n", returncode=128 + ) + self.assertEqual(latest, []) + self.assertIn("could not be queried", stderr) + + def test_a_pin_other_than_the_ref_never_queries_the_repository(self) -> None: + services = REF_PINNED.replace("ref: v3.0.39", 'version: "v3.0.39"').replace( + "key: ref", "key: version" + ) + latest, calls, _stderr = self._outdated(services, "") + self.assertEqual(latest, ["v4.0.2"]) + self.assertEqual(calls, []) + + class TestAddons(unittest.TestCase): def test_only_a_declared_or_github_released_addon_pin_is_collected(self) -> None: entries = module.collect_entries(_addon_repo()) diff --git a/utils/env/handlers/passthrough.py b/utils/env/handlers/passthrough.py index 3b8c3d62b4..6ae3e617ee 100644 --- a/utils/env/handlers/passthrough.py +++ b/utils/env/handlers/passthrough.py @@ -157,6 +157,7 @@ STATIC_KEYS = ( "INFINITO_CACHE_PACKAGE_NPMRC", "INFINITO_CACHE_PACKAGE_PIP_CONF", "INFINITO_CACHE_REGISTRY_PROXY_CONF", + "INFINITO_BUILD_CACHE_MAX_SIZE", "INFINITO_IMAGE_TAG", "INFINITO_VARS_PAYLOAD", "INFINITO_APP_VARIANTS", diff --git a/utils/env/runtime.py b/utils/env/runtime.py index c409cd7000..37819d5acf 100644 --- a/utils/env/runtime.py +++ b/utils/env/runtime.py @@ -131,8 +131,32 @@ def cpu_stall_pct() -> float: return _pressure_pct("cpu", "some") -def uninterruptible_procs() -> int: - """Count the processes in uninterruptible (`D`) state via /proc//stat. +def _context_switches(pid: str) -> int | None: + """ + Args: + pid: process whose /proc//status is read. + + Returns: + Its voluntary plus involuntary context switches so far, None when the + status is unreadable or carries neither counter. + """ + try: + text = Path( + f"/proc/{pid}/status" + ).read_text() # nocheck: cache-read -- live kernel pseudo-file + except OSError: + return None + counts = [ + int(value) + for key, _, value in (line.partition(":") for line in text.splitlines()) + if key in ("voluntary_ctxt_switches", "nonvoluntary_ctxt_switches") + and value.strip().isdigit() + ] + return sum(counts) if counts else None + + +def uninterruptible_switches() -> dict[str, int]: + """Map the processes in uninterruptible (`D`) state via /proc//stat. A process stuck in `D` cannot be killed and is the host-visible trace of a wedged mount. Only the state field is evaluated; the command name is @@ -141,13 +165,14 @@ def uninterruptible_procs() -> int: state is read after the last closing parenthesis rather than by index. Returns: - The number of `D`-state processes, 0 when /proc is unreadable. + The context switches so far of every `D`-state process, keyed by pid; + empty when /proc is unreadable. """ try: entries = os.listdir("/proc") except OSError: - return 0 - count = 0 + return {} + switches: dict[str, int] = {} for entry in entries: if not entry.isdigit(): continue @@ -158,9 +183,12 @@ def uninterruptible_procs() -> int: except OSError: continue fields = stat.rpartition(")")[2].split() - if fields and fields[0] == "D": - count += 1 - return count + if not fields or fields[0] != "D": + continue + count = _context_switches(entry) + if count is not None: + switches[entry] = count + return switches def is_wsl2() -> bool: diff --git a/utils/packages/schema.py b/utils/packages/schema.py index c1ef7a673e..c294fc8279 100644 --- a/utils/packages/schema.py +++ b/utils/packages/schema.py @@ -78,6 +78,15 @@ the package manager. ``checksum`` is mandatory: the URL alone would install whatever the vendor serves today, and a mismatch must abort the fetch rather than reach the package manager. +``download.repo_files`` lists the repository definitions the artefact's +install script registers, each a file directly under one of +:data:`VENDOR_REPO_DIRS`; they are removed right after the install:: + + download: + url: https://downloads.cursor.com/.../cursor-3.27.6.el8.x86_64.rpm + checksum: sha256:f06d4f... + repo_files: [/etc/yum.repos.d/cursor.repo] + A bare list is shorthand for ``{names: [...], source: repo}``. An empty list states that the package is deliberately not installed on that family, which counts as covered; a *missing* key is a coverage gap. @@ -110,6 +119,7 @@ file, so the batch knows to install it with the role:: from __future__ import annotations from dataclasses import dataclass +from pathlib import PurePosixPath from typing import TYPE_CHECKING, Any from utils.distros import distro_family @@ -156,6 +166,8 @@ DOWNLOAD_CHECKSUM_PREFIXES: tuple[str, ...] = ("sha256:", "sha512:") """Digest algorithms strong enough to pin a vendor artefact. ``get_url`` also accepts md5 and sha1, which a prefix check must keep out.""" +VENDOR_REPO_DIRS: tuple[str, ...] = ("/etc/apt/sources.list.d", "/etc/yum.repos.d") + REPO_KEYS: frozenset[str] = frozenset( { "baseurl", @@ -285,6 +297,22 @@ def _validate_download( f"{sorted(DOWNLOAD_CHECKSUM_PREFIXES)} followed by the digest; " "without it the URL installs whatever the vendor serves today." ) + _validate_repo_files(package_id, key, download.get("repo_files", []), path) + + +def _validate_repo_files( + package_id: str, key: str, repo_files: Any, path: Path +) -> None: + if not isinstance(repo_files, list) or any( + not isinstance(repo_file, str) + or PurePosixPath(repo_file).parent.as_posix() not in VENDOR_REPO_DIRS + for repo_file in repo_files + ): + raise PackagesShapeError( + f"{path}: {package_id}.{key}.download.repo_files must list files " + f"directly under {sorted(VENDOR_REPO_DIRS)}, got {repo_files!r}; " + "each one is removed as root after the install." + ) def _validate_flatpak( diff --git a/utils/packages/sources.py b/utils/packages/sources.py index a0e0c290cc..8939717070 100644 --- a/utils/packages/sources.py +++ b/utils/packages/sources.py @@ -165,6 +165,10 @@ def download_calls(names: list[str], download: dict[str, Any]) -> list[ModuleCal retry=EXTERNAL_FETCH, ), install, + *( + ModuleCall("ansible.builtin.file", {"path": repo_file, "state": "absent"}) + for repo_file in download.get("repo_files", []) + ), package_call(names, STATE_PRESENT), ] diff --git a/utils/security/deploy.py b/utils/security/deploy.py index fc72b4f1fc..6130fc46e6 100644 --- a/utils/security/deploy.py +++ b/utils/security/deploy.py @@ -7,7 +7,7 @@ import random from pathlib import Path from typing import TYPE_CHECKING -from utils.security.database import fetch_url, refresh +from utils.security.database import database_files, fetch_url, refresh from utils.security.engine import ( ENGINE_ENV, databases_for, @@ -30,13 +30,18 @@ def provided_databases(root: Path, engine: str) -> None: Raises: SystemExit: a database was not provided. """ - for name in databases_for(engine): - path = root / name - if not path.is_dir() or not any(path.iterdir()): - raise SystemExit( - f"{ENGINE_ENV}={engine} but no {name} database at {path}; " - "provide it before the deploy" - ) + p = pipeline() + missing = [ + str(path) + for name in databases_for(engine) + for path in database_files(p, root, name) + if not path.is_file() + ] + if missing: + raise SystemExit( + f"{ENGINE_ENV}={engine} but {', '.join(missing)} is missing; " + "provide it before the deploy" + ) def inventory_overrides( diff --git a/utils/tests/swarm/watchdog.py b/utils/tests/swarm/watchdog.py index 5c0b5de6a1..c7ff227940 100644 --- a/utils/tests/swarm/watchdog.py +++ b/utils/tests/swarm/watchdog.py @@ -29,7 +29,7 @@ from utils.env.runtime import ( mem_available_mb, mem_stall_pct, mem_total_mb, - uninterruptible_procs, + uninterruptible_switches, ) if TYPE_CHECKING: @@ -41,6 +41,7 @@ MEM_FLOOR_RATIO = 0.06 IO_STALL_CEILING_PCT = 50.0 SAMPLE_INTERVAL_S = 10 STALL_WINDOW_S = 60 +HUNG_TASK_S = 30 WEDGE_SAMPLES = 2 ABORT_RC = 75 _FORWARDED_SIGNALS = (signal.SIGINT, signal.SIGTERM) @@ -88,6 +89,39 @@ def lowest_free_mb() -> tuple[int, str]: ) +def blocked_streaks( + previous: dict[str, tuple[int, int]], switches: dict[str, int] +) -> dict[str, tuple[int, int]]: + """ + Args: + previous: blocked_streaks() of the previous sample. + switches: uninterruptible_switches() of this sample. + + Returns: + Per `D`-state pid its context switches and the number of samples in a + row it has stayed in `D` without a single one. + """ + streaks: dict[str, tuple[int, int]] = {} + for pid, count in switches.items(): + seen, streak = previous.get(pid, (-1, -1)) + streaks[pid] = (count, streak + 1 if seen == count else 0) + return streaks + + +def hung_tasks(streaks: dict[str, tuple[int, int]]) -> int: + """ + Args: + streaks: blocked_streaks() of this sample. + + Returns: + The number of tasks blocked in `D` without a context switch for at + least HUNG_TASK_S. + """ + return sum( + 1 for _, streak in streaks.values() if streak * SAMPLE_INTERVAL_S >= HUNG_TASK_S + ) + + def sample_line( *, avail: int, @@ -98,6 +132,7 @@ def sample_line( io_stall: float, cpu_stall: float, dstate: int, + hung: int, ) -> str: """Render one host-health sample for the step log. @@ -110,6 +145,8 @@ def sample_line( io_stall: `full avg60` I/O pressure in percent. cpu_stall: `some avg60` CPU pressure in percent. dstate: number of processes in uninterruptible state. + hung: how many of them sat in D without a context switch for at + least HUNG_TASK_S. Returns: The banner line, carrying the three resources a lost runner can be @@ -119,7 +156,8 @@ def sample_line( return ( f"=== swarm-matrix: host mem {avail}M/{total}M available, " f"disk {free_mb}M free on {root}, stall60 {mem_stall:.1f}%, " - f"io60 {io_stall:.1f}%, cpu60 {cpu_stall:.1f}%, dstate {dstate} ===" + f"io60 {io_stall:.1f}%, cpu60 {cpu_stall:.1f}%, dstate {dstate}, " + f"hung {hung} ===" ) @@ -153,6 +191,7 @@ def run_watched(cmd: list[str], *, env: dict[str, str]) -> int: def _watch(proc: subprocess.Popen[bytes]) -> int: samples = 0 wedged = 0 + streaks: dict[str, tuple[int, int]] = {} while True: try: return int(proc.wait(timeout=SAMPLE_INTERVAL_S)) @@ -169,7 +208,9 @@ def _watch(proc: subprocess.Popen[bytes]) -> int: avail = mem_available_mb() total = mem_total_mb() io_stall = io_stall_pct() - dstate = uninterruptible_procs() + streaks = blocked_streaks(streaks, uninterruptible_switches()) + dstate = len(streaks) + hung = hung_tasks(streaks) print( sample_line( avail=avail, @@ -180,6 +221,7 @@ def _watch(proc: subprocess.Popen[bytes]) -> int: io_stall=io_stall, cpu_stall=cpu_stall_pct(), dstate=dstate, + hung=hung, ), flush=True, ) @@ -192,14 +234,14 @@ def _watch(proc: subprocess.Popen[bytes]) -> int: ["free", "-m"], ) owns_window = samples * SAMPLE_INTERVAL_S >= STALL_WINDOW_S - breached = io_stall >= IO_STALL_CEILING_PCT and dstate > 0 + breached = io_stall >= IO_STALL_CEILING_PCT and hung > 0 wedged = wedged + 1 if owns_window and breached else 0 if wedged >= WEDGE_SAMPLES: return _abort( proc, "=== swarm-matrix: I/O WEDGE " f"({io_stall:.1f}% full stall60 with {dstate} task(s) in D " - f"state, {wedged} samples at or above " - f"{IO_STALL_CEILING_PCT:.0f}%) - aborting step ===", + f"state, {hung} hung for {HUNG_TASK_S}s+, {wedged} samples " + f"at or above {IO_STALL_CEILING_PCT:.0f}%) - aborting step ===", ["cat", "/proc/pressure/io"], ) diff --git a/utils/update/repository.py b/utils/update/repository.py index af597d22ff..5cff7aad24 100644 --- a/utils/update/repository.py +++ b/utils/update/repository.py @@ -173,6 +173,26 @@ def git_ls_remote_tags(url: str) -> list[str]: return sorted(tags) +def git_ref_resolves(url: str, ref: str) -> bool | None: + """ + Args: + url: repository to query. + ref: branch or tag name a pin would check out. + + Returns: + Whether ``git ls-remote`` lists ``refs/heads/`` or + ``refs/tags/``, ``None`` when the lookup fails. + """ + wanted = (f"refs/heads/{ref}", f"refs/tags/{ref}") + stdout = _ls_remote(url, *wanted) + if stdout is None: + return None + return any( + line.partition("\t")[2].removesuffix("^{}") in wanted + for line in stdout.splitlines() + ) + + def _ref_lines(lines: list[str]) -> list[tuple[int, str]]: """Return ``(1-indexed line number, ref value)`` for every `ref:` declaration in *lines*.""" diff --git a/utils/update/source.py b/utils/update/source.py index b72e2a015a..72de0aa844 100644 --- a/utils/update/source.py +++ b/utils/update/source.py @@ -1,37 +1,9 @@ -"""Resolve version pins that declare their own upstream source. - -The Docker updater watches ``image`` plus ``version``, the repository updater -``repository`` plus ``ref``. A pin outside both - an ``app_version``, a -``release``, a tag in a registry neither updater speaks - declares where its -upstream lives:: - - stalwart: - webui_version: "v1.0.5" - update: - key: webui_version - type: git_tags - repository: https://github.com/stalwartlabs/webui.git - -``key`` names the pinned key and defaults to ``version``; an entity with -several pins declares a list of such blocks. The types are -``git_tags`` (repository), ``registry_tags`` (image), ``npm`` (package), -``http_regex`` (one url or several, pattern, optionally a template over the -pattern's named groups) and ``script`` (path, run with the current version and -printing the latest one). A pin whose asset is fetched by digest names its -companion checksum beside the type; see :mod:`utils.update.checksum`. - -An addon in ``meta/addons/.yml`` declares the same fields in its -``update:`` block, beside ``monitored``, ``catalog`` and ``upstream_id``. A -monitored addon of the ``github-releases`` catalog needs no ``type``: its -``upstream_id`` already names the repository whose tags are its versions. An -addon's ``config.archive`` URL carries the pinned version and moves with it. -""" - from __future__ import annotations import json import re import subprocess +import sys import urllib.error from dataclasses import dataclass from typing import TYPE_CHECKING, Any @@ -62,7 +34,7 @@ from utils.update.docker import ( ) from utils.update.fetch import TIMEOUT_SECONDS, documents, get from utils.update.pins import archive_index, bump_archive, key_line, top_level_line -from utils.update.repository import git_ls_remote_tags +from utils.update.repository import git_ls_remote_tags, git_ref_resolves if TYPE_CHECKING: from collections.abc import Iterable @@ -72,6 +44,7 @@ NOCHECK_MARKER = "version-source" UNWATCHED_MARKER = "unwatched-version" UPDATE_KEY = "update" DEFAULT_KEY = "version" +REF_KEY = "ref" TYPES = ("git_tags", "registry_tags", "npm", "http_regex", "script") @@ -92,6 +65,9 @@ class VersionSourceEntry: directly or as the base of a ``custom`` build; a bump to a tag its registry answers 404 for is withheld, an indeterminate answer does not block it. + repository: repository the pin checks out when it is the entity's + ``ref``; a bump to a name it lists as neither branch nor tag, or + one the lookup cannot confirm, is withheld. """ role: str @@ -103,6 +79,7 @@ class VersionSourceEntry: line: int addon: bool = False image: str = "" + repository: str = "" @dataclass(frozen=True) @@ -424,11 +401,30 @@ def collect_entries(repo_root: Path) -> list[VersionSourceEntry]: config_path=config_path, line=line, image=config.get("image", "") if key == DEFAULT_KEY else "", + repository=str(config.get("repository", "")) + if key == REF_KEY + else "", ) ) return entries + _addon_entries(repo_root) +def _ref_resolves(entry: VersionSourceEntry, ref: str) -> bool: + resolved = git_ref_resolves(entry.repository, ref) + if not resolved: + answer = ( + "lists no branch or tag of that name" + if resolved is False + else "could not be queried" + ) + print( + f"[source] WARN {entry.role}/{entry.entity}.{entry.key}: " + f"{entry.repository} {answer}; withholding {entry.current} -> {ref}", + file=sys.stderr, + ) + return bool(resolved) + + def outdated( entries: Iterable[VersionSourceEntry], repo_root: Path ) -> list[VersionSourceUpdate]: @@ -444,6 +440,8 @@ def outdated( continue if entry.image and manifest_exists(entry.image, newest) is False: continue + if entry.repository and not _ref_resolves(entry, newest): + continue updates.append(VersionSourceUpdate(entry=entry, latest=newest)) return updates