diff --git a/README.md b/README.md index fc0ab59c58..521ca9e5b2 100644 --- a/README.md +++ b/README.md @@ -174,7 +174,7 @@ Every invokable role in the tested lifecycle envelope, with its upstream homepag | [Sphinx](roles/web-app-sphinx/) | beta | Documentation generator that builds HTML from a source repository and serves it through a lightweight HTTP server | [🌐](https://www.sphinx-doc.org/) [🛠️](roles/web-app-sphinx/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | | [Stalwart Mail Server](roles/web-app-stalwart/) | beta | All-in-one Stalwart mail server with SMTP, IMAP, JMAP, POP3, ManageSieve, CalDAV, CardDAV and built-in spam filtering | [🌐](https://stalw.art/) [🛠️](roles/web-app-stalwart/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Tor SMTP Gateway (svc-net-tor-smtp)](roles/svc-net-tor-smtp/), [Universal Logout](roles/web-svc-logout/) | | [Storage Optimizer](roles/svc-opt-ssd-hdd/) | beta | Tiering role placing Docker volumes on SSD or HDD by workload type, with symlinks keeping paths consistent | [🛠️](roles/svc-opt-ssd-hdd/README.md#quick-setup) | | -| [SuiteCRM](roles/web-app-suitecrm/) | beta | Open-source CRM platform for sales, service, cases, and campaign management with workflow automation | [🌐](https://suitecrm.com/) [🎬](https://www.youtube.com/watch?v=pOAs_C3Fp_E) [🛠️](roles/web-app-suitecrm/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Stalwart Mail Server](roles/web-app-stalwart/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [SuiteCRM](roles/web-app-suitecrm/) | beta | Open-source CRM platform for sales, service, cases, and campaign management with workflow automation | [🌐](https://suitecrm.com/) [🎬](https://www.youtube.com/watch?v=pOAs_C3Fp_E) [🛠️](roles/web-app-suitecrm/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Stalwart Mail Server](roles/web-app-stalwart/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Swapfile](roles/svc-opt-swapfile/) | beta | On-target automation for creating and activating swap space via a cloned swapfile script | [🛠️](roles/svc-opt-swapfile/README.md#quick-setup) | | | [Taiga](roles/web-app-taiga/) | beta | Open-source agile project management platform for Scrum, Kanban, and hybrid team workflows | [🌐](https://taiga.io/) [🎬](https://www.youtube.com/watch?v=TYPX8nQEU5I) [🛠️](roles/web-app-taiga/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Stalwart Mail Server](roles/web-app-stalwart/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Tor Onion Service](roles/svc-net-tor/) | beta | Tor daemon publishing the node as a v3 onion service | [🛠️](roles/svc-net-tor/README.md#quick-setup) | [Asset Mirror (Privacy Proxy)](roles/web-svc-mirror/) | diff --git a/cli/build/docs/readme/generate.py b/cli/build/docs/readme/generate.py index 201362567f..40b6b7c780 100644 --- a/cli/build/docs/readme/generate.py +++ b/cli/build/docs/readme/generate.py @@ -44,9 +44,10 @@ def _is_invokable(role_name: str) -> bool: def _render_template(ctx: dict) -> str: - env = jinja2.Environment( # noqa: S701 — renders Markdown, not HTML; escaping would corrupt it + env = jinja2.Environment( loader=jinja2.FileSystemLoader(str(schema.TEMPLATE_DIR)), keep_trailing_newline=True, + autoescape=jinja2.select_autoescape(), ) return env.get_template(schema.TEMPLATE_NAME).render(**ctx) diff --git a/cli/build/docs/readme/schema.py b/cli/build/docs/readme/schema.py index dc66b8ea89..ca7a3b3c47 100644 --- a/cli/build/docs/readme/schema.py +++ b/cli/build/docs/readme/schema.py @@ -42,9 +42,10 @@ _OPTIONAL_CTX: dict = { def _render(ctx: dict) -> str: - env = jinja2.Environment( # noqa: S701 — renders Markdown, not HTML; escaping would corrupt it + env = jinja2.Environment( loader=jinja2.FileSystemLoader(str(TEMPLATE_DIR)), keep_trailing_newline=True, + autoescape=jinja2.select_autoescape(), ) return env.get_template(TEMPLATE_NAME).render(**ctx) diff --git a/cli/contributing/update/README.md b/cli/contributing/update/README.md index 00eff7b60f..f043866074 100644 --- a/cli/contributing/update/README.md +++ b/cli/contributing/update/README.md @@ -21,7 +21,9 @@ stalwart: ``` `key` names the pinned key and defaults to `version`; an entity with several -pins declares a list of such blocks. Types: +pins declares a list of such blocks. An `image` + `version` pin that declares a +source for `version` is bumped from that source alone, the Docker updater skips +it. Types: | `type` | Fields | Reads | | --------------- | --------------------- | -------------------------------------- | @@ -35,6 +37,29 @@ pins declares a list of such blocks. Types: on Docker Hub), `strip: true` removes it again so a pin without the upstream's `v` stays without it. +A `repository` + `ref` pin that declares a source with `key: ref` is bumped +from that source alone, the repository updater skips it. + +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 +values: + +```yaml +freeswitch: + version: "v1.10.12-v3.0.23" + update: + type: http_regex + url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + pattern: 'repos/bigbluebutton (?Pv[0-9.]+)\nrepos/freeswitch (?Pv[0-9.]+)' + template: "{freeswitch}-{bbb}" +``` + +A templated pin moves when the assembled value changes, its suffix included, and never to an older version. + +`url` takes a list when the values live in several documents. Their bodies are +searched as one text, in the listed order. Every document is fetched once per +run, so all pins that read it resolve against the same snapshot. + The pinned value is a semver such as `v1.0.5`, `26.04.4.2.1` or `2.4.0p32`. A moving tag behind an `update:` block, or as the `version` of a monitored addon, fails `tests/lint/ansible/services/test_version_keys.py`. diff --git a/compose.yml b/compose.yml index 5cc60f4415..3bb9f3e536 100644 --- a/compose.yml +++ b/compose.yml @@ -23,7 +23,6 @@ services: build: context: . dockerfile: Dockerfile - network: host args: INFINITO_PARENT_IMAGE: ${INFINITO_PARENT_IMAGE:?Run 'make dotenv' to generate the .env single source of truth} INFINITO_SRC_DIR: ${INFINITO_SRC_DIR:?Run 'make dotenv' to generate the .env single source of truth} diff --git a/docs/requirements/037-web-app-worldmonitor.md b/docs/requirements/037-web-app-worldmonitor.md new file mode 100644 index 0000000000..d2dea65f8f --- /dev/null +++ b/docs/requirements/037-web-app-worldmonitor.md @@ -0,0 +1,219 @@ +# 037 - World Monitor Role behind the oauth2-proxy SSO Gate + +## User Story + +As a platform administrator of Infinito.Nexus, I want [World Monitor](https://github.com/koala73/worldmonitor) integrated as a `web-app-worldmonitor` role behind the platform's Keycloak SSO (via the oauth2-proxy gate) so that users reach the real-time global intelligence dashboard with their existing Infinito.Nexus identity, in compose and in swarm, without a second login. + +## Background + +World Monitor is an AGPL-3.0 dashboard that aggregates public data feeds (earthquakes, conflicts, markets, vessel tracking and more) on a map. Upstream ships a self-hosted Docker stack of four services. + +### Upstream facts established by research + +Verified against upstream `main` and release `v2.10.0` (2026-09-08). + +| Topic | Finding | Source | +|---|---|---| +| Services | `worldmonitor` (nginx + Node API under supervisord, container port `8080`), `ais-relay` (port `3004`), `redis` (`redis:7-alpine`, `6379`), `redis-rest` (Upstash-compatible REST proxy, port `80`). | [docker-compose.yml](https://github.com/koala73/worldmonitor/blob/main/docker-compose.yml) | +| Published image | Only `ghcr.io/koala73/worldmonitor` is published (semver tags, `linux/amd64` + `linux/arm64`, built from `docker/Dockerfile`). `ais-relay` (`Dockerfile.relay`) and `redis-rest` (`docker/Dockerfile.redis-rest`) have no published image. | [docker-publish.yml](https://github.com/koala73/worldmonitor/blob/main/.github/workflows/docker-publish.yml) | +| User authentication | None in self-hosted mode. `LOCAL_API_MODE=docker` has no Clerk or Convex backend, no local user accounts and no OIDC. The app mints an anonymous `wms_` browser session signed with `WM_SESSION_SECRET`. | [SELF_HOSTING.md](https://github.com/koala73/worldmonitor/blob/main/SELF_HOSTING.md) | +| Mandatory secrets | `RELAY_SHARED_SECRET`, `REDIS_PASSWORD`, `REDIS_TOKEN`, `WM_SESSION_SECRET`. Each container exits on boot when its secret is missing. | SELF_HOSTING.md | +| Admin routes | `/api/local-*` return `403` in Docker mode. Operator settings change only through environment variables plus a container recreate. | SELF_HOSTING.md | +| Reverse proxy | `WM_TRUSTED_PROXY_CIDRS` must name the fronting proxy's network, otherwise `X-Forwarded-For` is ignored and the per-IP LLM cap (50 calls per UTC day) counts the proxy as one client. Invalid values stop the container. | SELF_HOSTING.md | +| CSP | The bundled nginx emits its own `script-src` policy without `'unsafe-inline'`. | SELF_HOSTING.md | +| Data seeding | Redis starts empty. Upstream seeds with `./scripts/run-seeders.sh` run **on the host** (Node 22) against the REST proxy published on `127.0.0.1:8079`, repeated by host cron. The relay runs additional in-container seed loops when `UPSTASH_ALLOW_INSECURE_HTTP=true`. | SELF_HOSTING.md | +| Persistence | One volume, `redis-data`. All content is re-fetchable cache and seed data. | docker-compose.yml | +| LLM | Any OpenAI-compatible endpoint through `LLM_API_URL` (full `/v1/chat/completions` URL), `LLM_API_KEY`, `LLM_MODEL`. | SELF_HOSTING.md | +| MCP | `/api/mcp`, authenticated with `X-WorldMonitor-Key` against `WORLDMONITOR_VALID_KEYS`. The OAuth path is hosted-only. | SELF_HOSTING.md | +| Swarm blockers in the upstream file | `container_name`, `depends_on`, `build:`, `mem_limit`, a host-bound `127.0.0.1:8079` publish. | docker-compose.yml | + +### In-repo analogues + +- **SSO flavor is `oauth2`** (oauth2-proxy sidecar against Keycloak), as in [`web-app-openclaw`](../../roles/web-app-openclaw/) and [`web-app-checkmk`](029-web-app-checkmk.md). The Keycloak client is provisioned by the platform for every role with `sso.enabled`. +- **Multi-service compose template with a role-built image**: [`web-app-moodle`](../../roles/web-app-moodle/templates/compose.yml.j2). Dockerfile placement and `ARG` wiring follow [dockerfile.md](../contributing/artefact/files/role/dockerfile.md). +- **Shared LiteLLM gateway consumer**: `litellm` service flag plus `secrets.credentials.litellm_api_key` in [`web-app-openclaw`](../../roles/web-app-openclaw/meta/services.yml). +- **Generated credentials**: `meta/secrets.yml` as in [`web-app-openclaw`](../../roles/web-app-openclaw/meta/secrets.yml). + +## Proposed Decisions + +The operator MUST confirm or change these before implementation starts. Once confirmed they are not re-litigated during implementation. + +| # | Decision | Rationale | +|---|---|---| +| 1 | Role `web-app-worldmonitor`, canonical hostname `worldmonitor.{{ DOMAIN_PRIMARY }}`. | Standard single-host convention. | +| 2 | SSO is the **oauth2-proxy gate only**. No native OIDC, no user mapping, no in-app accounts. | Upstream self-hosted mode has no user model to map onto. A later native OIDC switch is the existing `sso.flavor` field, so nothing extra is built for it now. | +| 3 | Every authenticated Keycloak user may enter. No `allowed_groups`, no `meta/rbac.yml`. | The dashboard has no per-user state or admin surface in Docker mode. | +| 4 | The upstream internal mechanisms stay as shipped: the anonymous `wms_` session, the relay shared secret, Redis `requirepass`, the REST proxy bearer token. | They protect service-to-service traffic and are independent of the user boundary. | +| 5 | `worldmonitor` uses the published GHCR image pinned to a concrete semver tag. `ais-relay` and `redis-rest` are built from the same pinned upstream tag. | Only one image is published. No fork is maintained. | +| 6 | Redis and the REST proxy run **inside the role stack** with their own generated credentials, not on the shared `svc-db-redis`. | The app speaks only the Upstash REST dialect through the bundled proxy, and upstream runs Redis with `allkeys-lru` eviction that must not apply to other consumers. | +| 7 | Seeding runs **inside the stack** as a periodic seeder service. No host Node, no host cron, no published REST proxy port. | The upstream host-side flow needs a host-bound port and a host runtime, which breaks in swarm and violates service isolation. | +| 8 | The Redis volume persists but is **excluded from backup**. | Content is re-fetchable cache. A restore is a re-seed. | +| 9 | The LLM is wired to the shared LiteLLM gateway when `LITELLM_USABLE`. `OPENROUTER_API_KEY` is not used. | One platform gateway instead of a per-app provider key. | +| 10 | External data-source API keys are optional operator-supplied inventory values, empty when unset. | Upstream degrades gracefully per feed. | +| 11 | `/api/mcp` is **not** registered as a platform MCP server in this requirement. It stays behind the gate and `WORLDMONITOR_VALID_KEYS` stays empty. | The MCP path authenticates with a static key, not with the platform identity. Tracked separately if wanted. | + +## Target Schema + +### Role layout + +``` +roles/web-app-worldmonitor/ +├── README.md +├── files/Dockerfile +├── files/playwright/{_shared,playwright.spec,test-guest,test-oidc-login,test-isolation}.js +├── meta/{main,info,domains,networks,csp,services,secrets,variants,volumes}.yml +├── tasks/{main,00_core}.yml +├── templates/{compose.yml.j2,env.j2,playwright.env.j2} +└── vars/main.yml +``` + +### `meta/services.yml` excerpt + +```yaml +worldmonitor: + modes: + compose: { enabled: true } + swarm: { enabled: true } + image: ghcr.io/koala73/worldmonitor + version: "X.Y.Z" + name: worldmonitor + ports: + internal: { http: 8080 } + local: { http: , sso: } + lifecycle: alpha +sso: + bond: 1 + enabled: "{{ 'web-app-keycloak' in group_names }}" + shared: "{{ 'web-app-keycloak' in group_names }}" + flavor: oauth2 + oauth2: + origin: { host: worldmonitor, port: 8080 } +litellm: + bond: 1 + enabled: "{{ LITELLM_USABLE }}" + shared: true +``` + +### `meta/secrets.yml` credentials + +`relay_shared_secret`, `redis_password`, `redis_token`, `session_secret`, `litellm_api_key`. + +## Acceptance Criteria + +### Role layout & images + +- [ ] `roles/web-app-worldmonitor/` exists per the [Target Schema](#role-layout) and all `meta/*.yml` pass the role-meta lint. +- [ ] `worldmonitor` runs `ghcr.io/koala73/worldmonitor` pinned to a concrete semver tag whose existence in GHCR was verified. No `:latest`. +- [ ] `ais-relay` and `redis-rest` are built from the same pinned upstream tag, with every external value passed as a Docker `ARG` per [dockerfile.md](../contributing/artefact/files/role/dockerfile.md). +- [ ] Every image used by the role is declared once in `meta/services.yml` and is found by the image discovery. + +### Compose + +- [ ] A compose deploy brings `worldmonitor`, `ais-relay`, `redis`, `redis-rest` and the seeder to a steady running state with no manual step. + +### Swarm + +- [ ] The same role deploys as a swarm stack and reaches the same steady state. +- [ ] The rendered swarm stack contains no `container_name`, no `mem_limit` and no host-bound port publish, and no service fails permanently when its dependencies start after it. +- [ ] The role-built images are available to every swarm node that may schedule the services. + +### Secrets + +- [ ] `RELAY_SHARED_SECRET`, `REDIS_PASSWORD`, `REDIS_TOKEN` and `WM_SESSION_SECRET` are generated through `meta/secrets.yml` and no literal secret value is committed. +- [ ] `I_UNDERSTAND_THIS_DISABLES_AUTH` and `ALLOW_UNAUTHENTICATED_RELAY` are not set anywhere in the role. +- [ ] Optional external API keys (`FINNHUB_API_KEY`, `ALPHA_VANTAGE_API_KEY`, `FRED_API_KEY`, `EIA_API_KEY`, `ACLED_*`, `NASA_FIRMS_API_KEY`, `AVIATIONSTACK_API`, `TRAVELPAYOUTS_API_TOKEN`, `AISSTREAM_API_KEY`, `CLOUDFLARE_API_TOKEN`) reach the containers that read them when the operator sets them, and the stack is healthy when all are empty. + +### Routing & TLS + +- [ ] `https://worldmonitor.{{ DOMAIN_PRIMARY }}/` resolves through `sys-svc-proxy` to the `worldmonitor` service and serves the dashboard SPA. +- [ ] `WM_TRUSTED_PROXY_CIDRS` is set to the network the fronting proxy reaches the container from, in compose and in swarm, and the app logs the real client address for a proxied request. +- [ ] The dashboard's live updates (the WebSocket and streaming endpoints it opens) work through the proxy with no console error. +- [ ] The canonical surface answers with exactly one `Content-Security-Policy` header, and the dashboard renders under it with no CSP violation in the browser console. + +### SSO (Decisions #2 to #4) + +- [ ] With SSO enabled, an unauthenticated request to any path, including `/api/*`, is redirected to the Keycloak login. +- [ ] After login the user lands on the dashboard with no further credential prompt. +- [ ] A user with an existing Keycloak session reaches the dashboard without an interactive login. +- [ ] After logout through the platform logout, a request to the dashboard is redirected to the Keycloak login again. +- [ ] With SSO disabled, the dashboard is reachable anonymously and the stack is otherwise unchanged. + +### Service isolation + +- [ ] Only the `worldmonitor` HTTP port is published, bound to the platform bind host. `redis`, `redis-rest` and `ais-relay` publish no port. +- [ ] From outside the role's network, `redis:6379`, `redis-rest:80` and `ais-relay:3004` are unreachable. +- [ ] Redis rejects an unauthenticated command, and `redis-rest` rejects a request without the bearer token. + +### Data seeding (Decision #7) + +- [ ] After a fresh deploy the dashboard shows seeded data from the key-free feeds with no command run on the host. +- [ ] Seeding repeats on a fixed interval inside the stack, and one hung feed does not block the others. + +### Persistence & backup (Decision #8) + +- [ ] Seeded data survives a recreate of every container in the stack, in compose and on the swarm storage layer. +- [ ] The Redis volume is excluded from the platform backup. + +### LLM (Decision #9) + +- [ ] When `LITELLM_USABLE` is true, `LLM_API_URL`, `LLM_API_KEY` and `LLM_MODEL` point at the shared LiteLLM gateway with the role's own virtual key, and an intelligence brief request returns generated text. +- [ ] When it is false, the three variables are empty and the stack is healthy. + +### Health checks + +- [ ] `worldmonitor` has a container healthcheck that fails when either nginx or the Node API is down. +- [ ] `redis` and `redis-rest` have container healthchecks, and the `redis-rest` check fails when Redis is unreachable. +- [ ] `ais-relay` has a container healthcheck. + +### Variants + +- [ ] `meta/variants.yml` covers SSO on and SSO off, and every variant deploys cleanly on a fresh host. + +### Playwright + +- [ ] `test-guest.js` asserts the redirect to Keycloak for the root path and for an `/api/` path. +- [ ] `test-oidc-login.js` logs in as `biber`, asserts the map renders, and ends logged out with the dashboard gated again. +- [ ] `test-isolation.js` asserts that no internal service answers on the canonical host. +- [ ] `templates/playwright.env.j2` exposes every environment variable the specs read, and `make compose-playwright role=web-app-worldmonitor` exits 0 with no stub test. +- [ ] The same specs pass against the swarm deploy. + +### Documentation & quality + +- [ ] `README.md` documents the gate-only SSO model, the retained internal secrets, the in-stack seeding, the optional API keys with their effect, the image pin and bump policy, and the AGPL-3.0 licence of the upstream. +- [ ] `make test` is green tree-wide. +- [ ] This requirement is cross-linked from the implementing PR. + +## Out of Scope + +- Native OIDC, user mapping and in-app roles (no upstream support in self-hosted mode). +- Registering `/api/mcp` as a platform MCP server. +- The hosted-only features (Clerk entitlements, premium routes, OAuth for MCP). + +## Validation Apps + +```bash +make compose-deploy apps=web-app-worldmonitor purge=true full_cycle=true +``` + +Cross-mode parity follows the [Roundtrip Loop](../agents/action/iteration/roundtrip.md). + +Smoke: visit `https://worldmonitor.{{ DOMAIN_PRIMARY }}/`, pass the Keycloak login, confirm the map shows seeded layers, log out, confirm the gate returns. + +## Prerequisites + +Before implementation, the agent MUST read [AGENTS.md](../../AGENTS.md), then [Compose Loop](../agents/action/iteration/compose.md) and the [Playwright contract](../contributing/artefact/files/role/playwright.specs.js.md). + +## Implementation Strategy + +Execute autonomously once the [Proposed Decisions](#proposed-decisions) are confirmed. Scaffold from [`roles/web-app-openclaw/`](../../roles/web-app-openclaw/) (oauth2 flavor, generated credentials, LiteLLM consumer) and take the multi-service compose shape from [`roles/web-app-moodle/`](../../roles/web-app-moodle/). Before claiming done, verify against the pinned upstream tag: the environment variable names, whether the published app image contains the seeder scripts, the health endpoint path, and the dashboard selectors used by the specs. + +## Commit Policy + +- No git commit until every Acceptance Criterion is checked off. +- When met and `make test` is green, instruct the operator to run `git-sign-push` outside the sandbox. The agent MUST NOT push. + +## Context + +- Upstream repo: +- Self-hosting guide: +- Closest in-repo analogues: [`roles/web-app-openclaw/`](../../roles/web-app-openclaw/), [`029-web-app-checkmk.md`](029-web-app-checkmk.md) diff --git a/package-lock.json b/package-lock.json index dec3a469ef..1d40cf4db5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,7 +11,7 @@ "@eslint/js": "^10.0.1", "@playwright/test": "^1.63.0", "eslint": "^10.12.0", - "eslint-plugin-playwright": "^2.10.5", + "eslint-plugin-playwright": "^2.12.1", "globals": "^17.13.0", "stylelint": "^17.16.0" } @@ -907,9 +907,9 @@ } }, "node_modules/eslint-plugin-playwright": { - "version": "2.10.5", - "resolved": "https://registry.npmjs.org/eslint-plugin-playwright/-/eslint-plugin-playwright-2.10.5.tgz", - "integrity": "sha512-4k+ml4cEd55kePUIW1WsCiOLDwZkAdPZPKMFulR83XpplCaVOTKHF6yvXLYixLtdVbkMjmKV5F3BaGuI3aH8aQ==", + "version": "2.12.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-playwright/-/eslint-plugin-playwright-2.12.1.tgz", + "integrity": "sha512-JhavNuYBIq7SE/Zg9Esf9RGHkXoDbzrEKS383cowzMyvZ4JMbmdNCN6CoW+RU1Cjzwcoea1tou0je58uXmT/9A==", "dev": true, "license": "MIT", "dependencies": { @@ -1902,9 +1902,9 @@ } }, "node_modules/postcss-selector-parser": { - "version": "7.1.5", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.5.tgz", - "integrity": "sha512-KvvtD7SrlBP7dlgkBghEE3r84CABm5SmV2aNcG4oCA+qDnJ/tvKonFVvwWAyyWUEwxuNawdfEAZKP9zM3oZ2Uw==", + "version": "7.1.6", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.6.tgz", + "integrity": "sha512-7qASPzhKF2l2KLboRZux8CCTRMdGiV08vWmyKzPz22qZ7ZjQBOeY7rNzNoCLSUiftJ7HUq0GERHmxw/t0dCdMw==", "dev": true, "license": "MIT", "dependencies": { @@ -2096,9 +2096,9 @@ } }, "node_modules/source-map-js": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", - "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", "dev": true, "license": "BSD-3-Clause", "engines": { diff --git a/package.json b/package.json index 799548eab2..d52cb43baa 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,7 @@ "@eslint/js": "^10.0.1", "@playwright/test": "^1.63.0", "eslint": "^10.12.0", - "eslint-plugin-playwright": "^2.10.5", + "eslint-plugin-playwright": "^2.12.1", "globals": "^17.13.0", "stylelint": "^17.16.0" }, diff --git a/plugins/filter/native_metrics_target.py b/plugins/filter/native_metrics_target.py deleted file mode 100644 index cade81dc24..0000000000 --- a/plugins/filter/native_metrics_target.py +++ /dev/null @@ -1,51 +0,0 @@ -from __future__ import annotations - -from ansible.errors import AnsibleFilterError - -from utils.roles.entity.name import get_entity_name - - -def native_metrics_target(app_id: str, applications: dict) -> str: - """Return the container-to-container Prometheus scrape target for a native-metrics app. - - Prometheus connects to the app's Docker network (declared in prometheus's - compose.yml.j2 via the native_metrics_apps loop) and scrapes by container - name and internal port — no host port binding required, no nginx/OAuth2 in - the path. - - Usage in a per-app prometheus.yml.j2 fragment: - targets: ["{{ native_prometheus_application_id | native_metrics_target(lookup('applications')) }}"] - - When the service key differs from the app's entity name (e.g. matrix - uses service key "synapse"), set services.prometheus.native_metrics.service_key - in the app's meta/services.yml to override. - """ - app_conf = applications.get(app_id, {}) - services = app_conf.get("services", {}) if isinstance(app_conf, dict) else {} - native_metrics_conf = ( - services.get("prometheus", {}) if isinstance(services, dict) else {} - ).get("native_metrics", {}) - service_key = native_metrics_conf.get("service_key") or get_entity_name(app_id) - - container = ( - services.get(service_key, {}).get("name") - if isinstance(services, dict) - else None - ) - if not container: - raise AnsibleFilterError( - f"native_metrics_target: no services.{service_key}.name for '{app_id}'" - ) - - port = native_metrics_conf.get("port") - if port is None: - raise AnsibleFilterError( - f"native_metrics_target: no services.prometheus.native_metrics.port for '{app_id}'" - ) - - return f"{container}:{port}" - - -class FilterModule: - def filters(self): - return {"native_metrics_target": native_metrics_target} diff --git a/plugins/lookup/engine.py b/plugins/lookup/engine.py index 5c769cc538..c428c9acdf 100644 --- a/plugins/lookup/engine.py +++ b/plugins/lookup/engine.py @@ -2,6 +2,7 @@ {{ lookup('engine', 'redis', application_id) }} # full dict {{ lookup('engine', 'redis', application_id, 'url') }} # one field + {{ lookup('engine', 'redis', application_id, 'session_path') }} # phpredis session.save_path Mirrors the ``database`` lookup but for the non-RDBMS engines registered in :data:`utils.roles.applications.services.engines.ENGINES` (redis, memcached, @@ -16,6 +17,7 @@ See ``docs/architecture/central-engines.md``. from __future__ import annotations from typing import Any +from urllib.parse import quote from ansible.errors import AnsibleError from ansible.plugins.loader import lookup_loader @@ -44,9 +46,31 @@ _FIELDS = ( "prefix", "url", "container", + "session_path", ) +def redis_session_path( + host: str, port: int, prefix: str, username: str, password: str +) -> str: + """Return the phpredis ``session.save_path`` of one consumer. + + Args: + host: redis host the consumer reaches. + port: redis port. + prefix: consumer prefix; session keys become ``:session:``. + username: ACL user, sent only together with a password. + password: redis password; empty for an embedded sidecar. + """ + path = f"tcp://{host}:{port}?prefix={quote(prefix, safe='')}:session:" + if password: + path += ( + f"&auth[user]={quote(username, safe='')}" + f"&auth[pass]={quote(password, safe='')}" + ) + return path + + def qdrant_consumer_key(applications: dict[str, Any], svc_id: str) -> str: """Return the engine-wide key a data-owning qdrant consumer presents. @@ -197,6 +221,17 @@ class LookupModule(LookupBase): "prefix": prefix, "url": url, "container": container, + "session_path": ( + redis_session_path( + host, + port, + prefix, + username if shared else "", + password if shared else "", + ) + if engine == "redis" + else "" + ), } if want == "all": return [resolved] diff --git a/plugins/lookup/native_metrics_apps.py b/plugins/lookup/native_metrics_apps.py index 6a186041d3..68bc93548f 100644 --- a/plugins/lookup/native_metrics_apps.py +++ b/plugins/lookup/native_metrics_apps.py @@ -1,12 +1,35 @@ from __future__ import annotations +from collections.abc import Mapping from typing import Any from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase from utils.cache import ROLES_DIR +from utils.cache.yaml import load_yaml_any from utils.roles.applications.config import get as get_app_conf +from utils.roles.mapping import ROLE_FILE_VARS_MAIN + + +def compose_mode_force(app_id: str) -> str: + """Return the role's own deploy-mode override. + + Args: + app_id: the role directory name. + + Returns: + The literal ``compose_mode_force`` from the role's vars, or ``""`` when + it is absent or a Jinja expression, which cannot be resolved from the + scraping role's variable scope and so leaves the override invisible here. + """ + path = ROLES_DIR / app_id / ROLE_FILE_VARS_MAIN + if not path.is_file(): + return "" + data = load_yaml_any(str(path), default_if_missing={}) + raw = data.get("compose_mode_force") if isinstance(data, Mapping) else None + value = "" if raw is None else str(raw).strip() + return "" if "{{" in value else value class LookupModule(LookupBase): @@ -16,8 +39,10 @@ class LookupModule(LookupBase): 2. a prometheus.yml.j2 template at roles//templates/ 3. reachable from this prometheus: NOT on a node-local force_bridge network under swarm, which a swarm prometheus can neither join nor - resolve. This is the single point that gates force_bridge apps out of - the native-metrics precreate + scrape. + resolve, and NOT pinned to compose by its own compose_mode_force while + the cluster runs swarm, which would make the scrape target name the + wrong object. This is the single point that gates unreachable apps out + of the native-metrics precreate + scrape. Used by web-app-prometheus/templates/configuration/prometheus.yml.j2 to auto-discover apps that expose a native /metrics endpoint without hardcoding each app name. @@ -78,6 +103,9 @@ class LookupModule(LookupBase): if is_swarm and bool(force_bridge): continue + if is_swarm and compose_mode_force(app_id) == "compose": + continue + result.append(app_id) return [result] diff --git a/plugins/lookup/native_metrics_target.py b/plugins/lookup/native_metrics_target.py new file mode 100644 index 0000000000..201f517f32 --- /dev/null +++ b/plugins/lookup/native_metrics_target.py @@ -0,0 +1,72 @@ +"""Lookup ``native_metrics_target``: scrape target for an app that exposes its +own metrics port. Reads ``services.prometheus.native_metrics`` for the service +key and port, then delegates host resolution to ``scrape_target`` so swarm and +compose stay on one implementation. + +Usage in a per-app prometheus.yml.j2 fragment: + targets: ["{{ lookup('native_metrics_target', native_prometheus_application_id) }}"] +""" + +from __future__ import annotations + +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +from utils.roles.applications.config import get +from utils.roles.entity.name import get_entity_name + + +class LookupModule(LookupBase): + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[str]: + if not terms: + raise AnsibleError( + "native_metrics_target lookup requires the application_id term" + ) + + application_id = str(terms[0]).strip() + if not application_id: + raise AnsibleError( + "native_metrics_target: application_id must be non-empty" + ) + + vars_ = variables or getattr(self._templar, "available_variables", {}) or {} + applications = lookup_loader.get( + "applications", loader=self._loader, templar=getattr(self, "_templar", None) + ).run([], variables=vars_)[0] + + def conf(key: str) -> str: + value = get( + applications=applications, + application_id=application_id, + config_path=f"services.prometheus.native_metrics.{key}", + strict=False, + default="", + ) + return "" if value is None else str(value).strip() + + port = conf("port") + if not port: + raise AnsibleError( + "native_metrics_target: no " + f"services.prometheus.native_metrics.port for {application_id!r}" + ) + + service_key = conf("service_key") or get_entity_name(application_id) + if not service_key: + raise AnsibleError( + f"native_metrics_target: cannot derive service key for {application_id!r}" + ) + + return lookup_loader.get( + "scrape_target", + loader=self._loader, + templar=getattr(self, "_templar", None), + ).run([application_id, service_key], variables=vars_, port=port) diff --git a/plugins/lookup/scrape_target.py b/plugins/lookup/scrape_target.py index d99674e8d7..06190f50be 100644 --- a/plugins/lookup/scrape_target.py +++ b/plugins/lookup/scrape_target.py @@ -1,6 +1,7 @@ """Lookup ``scrape_target``: mode-aware ``:`` for a Prometheus scrape target. Swarm resolves ``tasks._`` (per-task DNS); -compose uses ``compose_host`` or the service container name.""" +compose uses ``compose_host`` or the service container name. ``port`` overrides +the ``services..ports.internal.`` lookup.""" from __future__ import annotations @@ -37,12 +38,20 @@ class LookupModule(LookupBase): if not service_key: raise AnsibleError("scrape_target: service_key must be non-empty") - port_kind = ( + explicit_port_kind = ( _as_str(terms[2]) if len(terms) > 2 else _as_str(kwargs.get("port_kind")) - ) or "http" + ) + port_kind = explicit_port_kind or "http" compose_host = ( _as_str(terms[3]) if len(terms) > 3 else _as_str(kwargs.get("compose_host")) ) + port_override = _as_str(kwargs.get("port")) + if port_override and explicit_port_kind: + raise AnsibleError( + f"scrape_target: {application_id!r} passed both port={port_override!r} " + f"and port_kind={explicit_port_kind!r}; port wins and port_kind would be " + "silently dropped, so pass only one" + ) vars_ = variables or getattr(self._templar, "available_variables", {}) or {} templar = getattr(self, "_templar", None) @@ -57,7 +66,7 @@ class LookupModule(LookupBase): "applications", loader=self._loader, templar=getattr(self, "_templar", None) ).run([], variables=vars_)[0] - port = _as_str( + port = port_override or _as_str( get( applications=applications, application_id=application_id, diff --git a/roles/svc-ai-mcp-adapter/README.md b/roles/svc-ai-mcp-adapter/README.md index cfd9b2bf62..2d0d4d4bc3 100644 --- a/roles/svc-ai-mcp-adapter/README.md +++ b/roles/svc-ai-mcp-adapter/README.md @@ -26,6 +26,7 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( - **Client-facing authentication:** The adapter issues its own bearer. The upstream credential authenticates the adapter to the provider and says nothing about who called the adapter, which is the gap the project-owned MCP sidecars leave open. - **Allowlist on `tools/call`:** Filtering only `tools/list` would leave every unlisted operation callable by name. - **Read-only by default:** A non-`GET`/`HEAD` operation is refused unless `mutating_tools_enabled` is explicitly true. +- **Path arguments stay in their segment:** A value that fills a `{placeholder}` of the contracted path is percent-encoded, and an empty value or one made only of dots is refused, so a call cannot resolve to a path the contract does not name. - **Enforced ceilings:** Request size, response size, timeout, concurrency, page size and result count come from the contract and are applied, not merely declared. - **Bounded ranges:** A tool whose schema declares `start`, `end` and `step` has its point count checked against `result_items` and is refused with the smallest step that fits, so the upstream never scans a range whose result the adapter would discard. - **Fail-closed on drift:** A tool contract whose hash no longer matches its pinned `schema_sha256` refuses to start. diff --git a/roles/svc-ai-mcp-adapter/files/python/policy.py b/roles/svc-ai-mcp-adapter/files/python/policy.py index fc4ed18be2..b527da2b6c 100644 --- a/roles/svc-ai-mcp-adapter/files/python/policy.py +++ b/roles/svc-ai-mcp-adapter/files/python/policy.py @@ -47,6 +47,7 @@ DENY_TOO_MANY_REQUESTS = "too_many_concurrent_requests" DENY_UNKNOWN_ARGUMENT = "undeclared_argument" DENY_MISSING_ARGUMENT = "missing_required_argument" DENY_RANGE_TOO_WIDE = "range_too_wide" +DENY_PATH_ARGUMENT = "path_argument_not_a_segment" RANGE_ARGUMENTS = ("start", "end", "step") @@ -189,6 +190,17 @@ def assert_arguments( raise PermissionError(f"{DENY_MISSING_ARGUMENT}: {name!r} requires {missing}") +def assert_path_arguments( + spec: Mapping[str, Any], name: str, arguments: Mapping[str, Any] | None +) -> None: + path = str(spec["path"]) + for key, value in (arguments or {}).items(): + if "{" + key + "}" in path and not str(value).strip("."): + raise PermissionError( + f"{DENY_PATH_ARGUMENT}: {name!r} takes no {str(value)!r} as {key!r}" + ) + + def parse_instant(value: Any) -> float: """Return a range boundary in unix seconds. @@ -217,10 +229,14 @@ def parse_duration(value: Any) -> float: return float(text) except ValueError: pass - parts = re.findall(r"(\d+)(ms|[smhdwy])", text) - if not parts or "".join(n + u for n, u in parts) != text: + *tokens, rest = re.split(r"(ms|[smhdwy])", text) + numbers, units = tokens[::2], tokens[1::2] + if rest or not numbers or not all(number.isdecimal() for number in numbers): raise ValueError(f"not a duration: {text!r}") - return sum(int(n) * DURATION_UNITS[u] for n, u in parts) + return sum( + int(number) * DURATION_UNITS[unit] + for number, unit in zip(numbers, units, strict=True) + ) def assert_range( @@ -341,6 +357,7 @@ def authorize_call( ) assert_arguments(spec, name, arguments) + assert_path_arguments(spec, name, arguments) assert_range(spec, name, arguments, contract["limits"]["result_items"]) return method, str(spec["path"]) diff --git a/roles/svc-ai-ollama/meta/services.yml b/roles/svc-ai-ollama/meta/services.yml index b60dc775cc..cba1342a36 100644 --- a/roles/svc-ai-ollama/meta/services.yml +++ b/roles/svc-ai-ollama/meta/services.yml @@ -13,7 +13,7 @@ ollama: backup: no_stop_required: true image: ollama/ollama - version: 0.40.0 + version: 0.40.2 name: ollama min_storage: 3473MB cpus: "4.0" diff --git a/roles/svc-runner/meta/services.yml b/roles/svc-runner/meta/services.yml index 3307cb8781..17dddd36b2 100644 --- a/roles/svc-runner/meta/services.yml +++ b/roles/svc-runner/meta/services.yml @@ -30,7 +30,7 @@ buildkit: enabled: false shared: false image: moby/buildkit - version: "v0.33.1" + version: "v0.34.0" # nocheck: dynamic-flag act-runner: enabled: false diff --git a/roles/sys-svc-compose/handlers/compose.yml b/roles/sys-svc-compose/handlers/compose.yml index 416639c3e8..97aa1f7421 100644 --- a/roles/sys-svc-compose/handlers/compose.yml +++ b/roles/sys-svc-compose/handlers/compose.yml @@ -81,7 +81,11 @@ args: chdir: "{{ lookup('container', application_id, 'directories.instance') }}" executable: /bin/bash + register: compose_rebuild timeout: "{{ lookup('timeout', 3600) | int }}" + retries: 3 + delay: 30 + until: compose_rebuild is succeeded when: compose_build is failed listen: - compose-build diff --git a/roles/sys-svc-compose/handlers/swarm.yml b/roles/sys-svc-compose/handlers/swarm.yml index facdcd8727..20e8e3f08e 100644 --- a/roles/sys-svc-compose/handlers/swarm.yml +++ b/roles/sys-svc-compose/handlers/swarm.yml @@ -32,7 +32,11 @@ args: chdir: "{{ lookup('container', application_id, 'directories.instance') }}" executable: /bin/bash + register: _swarm_pre_deploy_rebuild timeout: "{{ lookup('timeout', 3600) | int }}" + retries: 3 + delay: 30 + until: _swarm_pre_deploy_rebuild is succeeded when: _swarm_pre_deploy_build is failed listen: - compose-up diff --git a/roles/test-e2e-cli/files/shared/mcp/contract.py b/roles/test-e2e-cli/files/shared/mcp/contract.py index 4af0b34781..f7997a1f7a 100644 --- a/roles/test-e2e-cli/files/shared/mcp/contract.py +++ b/roles/test-e2e-cli/files/shared/mcp/contract.py @@ -45,6 +45,7 @@ Environment: from __future__ import annotations +import contextlib import json import os import queue @@ -76,7 +77,7 @@ SESSION_TIMEOUT = 20 WRONG_CREDENTIAL = "Bearer " + "0" * 40 SESSION_HEADER = "Mcp-Session-Id" -SESSION = {"id": ""} +SESSION = {"id": "", "protocol": ""} def unguarded_url(): @@ -120,6 +121,8 @@ def rpc(method, params=None, authorization=None, url=None, notification=False): request.add_header("Authorization", authorization) if SESSION["id"]: request.add_header(SESSION_HEADER, SESSION["id"]) + if SESSION["protocol"]: + request.add_header("MCP-Protocol-Version", SESSION["protocol"]) try: with urllib.request.urlopen(request, timeout=TIMEOUT) as response: # noqa: S310 fixed internal http origin session = response.headers.get(SESSION_HEADER) @@ -320,21 +323,20 @@ class SseSession: self.content_type = self._response.headers.get("Content-Type", "") event = None try: - for raw in self._response: - line = raw.decode(errors="replace").rstrip("\r\n") - if line.startswith("event:"): - event = line.split(":", 1)[1].strip() - elif line.startswith("data:"): - data = line.split(":", 1)[1].strip() - if event == "endpoint": - self.endpoint = urllib.parse.urljoin(self.url, data) - self._announced.set() - else: - self._messages.put(data) - elif not line: - event = None - except (OSError, ValueError): - pass + with contextlib.suppress(OSError, ValueError): + for raw in self._response: + line = raw.decode(errors="replace").rstrip("\r\n") + if line.startswith("event:"): + event = line.split(":", 1)[1].strip() + elif line.startswith("data:"): + data = line.split(":", 1)[1].strip() + if event == "endpoint": + self.endpoint = urllib.parse.urljoin(self.url, data) + self._announced.set() + else: + self._messages.put(data) + elif not line: + event = None finally: self._announced.set() @@ -463,6 +465,8 @@ def main(): if status != 200: reject(f"authenticated initialize answered {status}: {body[:200]}") reject_error("authenticated initialize", rpc_error(body)) + result = json.loads(body).get("result") or {} + SESSION["protocol"] = result.get("protocolVersion", "") rpc("notifications/initialized", authorization=AUTH, notification=True) diff --git a/roles/test-e2e-playwright/meta/services.yml b/roles/test-e2e-playwright/meta/services.yml index 621cb432fd..893702e0a6 100644 --- a/roles/test-e2e-playwright/meta/services.yml +++ b/roles/test-e2e-playwright/meta/services.yml @@ -4,4 +4,4 @@ test-e2e-playwright: lifecycle: beta playwright: image: mcr.microsoft.com/playwright - version: "v1.63.0-noble" + version: "v1.64.0-noble" diff --git a/roles/web-app-bigbluebutton/meta/services.yml b/roles/web-app-bigbluebutton/meta/services.yml index a76a7ddfcf..1391350f6f 100644 --- a/roles/web-app-bigbluebutton/meta/services.yml +++ b/roles/web-app-bigbluebutton/meta/services.yml @@ -36,6 +36,11 @@ bigbluebutton: shared: true repository: https://github.com/bigbluebutton/docker.git ref: v3.0.23 + update: + key: ref + type: http_regex + url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + pattern: "repos/bigbluebutton (v[0-9.]+)" recording: enabled: false cleanup: true @@ -101,54 +106,97 @@ prometheus: bbb-web: image: alangecker/bbb-docker-web version: "v3.0.23" + update: + type: http_regex + url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + pattern: "repos/bigbluebutton (v[0-9.]+)" enabled: false # nocheck: playwright-service-flag: prebuilt upstream-compose image, mirror pre-pull only # nocheck: dynamic-flag: fixed upstream-compose sub-service, not group-gated freeswitch: image: alangecker/bbb-docker-freeswitch version: "v1.10.12-v3.0.23" + update: + type: http_regex + url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + pattern: "repos/bigbluebutton (?Pv[0-9.]+)\\nrepos/freeswitch (?Pv[0-9.]+)" + template: "{freeswitch}-{bbb}" enabled: false # nocheck: playwright-service-flag: prebuilt upstream-compose image, mirror pre-pull only # nocheck: dynamic-flag: fixed upstream-compose sub-service, not group-gated nginx: image: alangecker/bbb-docker-nginx version: "v3.0.23-v5.4.4-1.29" + 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 + 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 # nocheck: playwright-service-flag: prebuilt upstream-compose image, mirror pre-pull only # nocheck: dynamic-flag: fixed upstream-compose sub-service, not group-gated etherpad: image: alangecker/bbb-docker-etherpad version: "2.4.2-s8328b77-p88f3f6b" + 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 + pattern: "repos/bbb-etherpad-plugin (?P[0-9a-f]+)\\nrepos/bbb-etherpad-skin (?P[0-9a-f]+)\\n(?:.*\\n)*?.*bbb-docker-etherpad:(?P[0-9.]+)-s" + template: "{base}-s{skin}-p{plugin}" enabled: false # nocheck: playwright-service-flag: prebuilt upstream-compose image, mirror pre-pull only # nocheck: dynamic-flag: fixed upstream-compose sub-service, not group-gated bbb-pads: image: alangecker/bbb-docker-pads version: "v1.5.8" + update: + type: http_regex + url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + pattern: "repos/bbb-pads (v[0-9.]+)" enabled: false # nocheck: playwright-service-flag: prebuilt upstream-compose image, mirror pre-pull only # nocheck: dynamic-flag: fixed upstream-compose sub-service, not group-gated bbb-export-annotations: image: alangecker/bbb-docker-bbb-export-annotations version: "v3.0.23" + update: + type: http_regex + url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + pattern: "repos/bigbluebutton (v[0-9.]+)" enabled: false # nocheck: playwright-service-flag: prebuilt upstream-compose image, mirror pre-pull only # nocheck: dynamic-flag: fixed upstream-compose sub-service, not group-gated webrtc-sfu: image: alangecker/bbb-docker-webrtc-sfu version: "v2.22.0" + update: + type: http_regex + url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + pattern: "repos/bbb-webrtc-sfu (v[0-9.]+)" enabled: false # nocheck: playwright-service-flag: prebuilt upstream-compose image, mirror pre-pull only # nocheck: dynamic-flag: fixed upstream-compose sub-service, not group-gated fsesl-akka: image: alangecker/bbb-docker-fsesl-akka version: "v3.0.23" + update: + type: http_regex + url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + pattern: "repos/bigbluebutton (v[0-9.]+)" enabled: false # nocheck: playwright-service-flag: prebuilt upstream-compose image, mirror pre-pull only # nocheck: dynamic-flag: fixed upstream-compose sub-service, not group-gated apps-akka: image: alangecker/bbb-docker-apps-akka version: "v3.0.23" + update: + type: http_regex + url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + pattern: "repos/bigbluebutton (v[0-9.]+)" enabled: false # nocheck: playwright-service-flag: prebuilt upstream-compose image, mirror pre-pull only # nocheck: dynamic-flag: fixed upstream-compose sub-service, not group-gated @@ -160,36 +208,60 @@ bbb-graphql-server: retries: 5 image: alangecker/bbb-docker-graphql-server version: "v3.0.23" + update: + type: http_regex + url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + pattern: "repos/bigbluebutton (v[0-9.]+)" enabled: false # nocheck: playwright-service-flag: prebuilt upstream-compose image, mirror pre-pull only # nocheck: dynamic-flag: fixed upstream-compose sub-service, not group-gated bbb-graphql-actions: image: alangecker/bbb-docker-graphql-actions version: "v3.0.23" + update: + type: http_regex + url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + pattern: "repos/bigbluebutton (v[0-9.]+)" enabled: false # nocheck: playwright-service-flag: prebuilt upstream-compose image, mirror pre-pull only # nocheck: dynamic-flag: fixed upstream-compose sub-service, not group-gated bbb-graphql-middleware: image: alangecker/bbb-docker-graphql-middleware version: "v3.0.23" + update: + type: http_regex + url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + pattern: "repos/bigbluebutton (v[0-9.]+)" enabled: false # nocheck: playwright-service-flag: prebuilt upstream-compose image, mirror pre-pull only # nocheck: dynamic-flag: fixed upstream-compose sub-service, not group-gated periodic: image: alangecker/bbb-docker-periodic version: "v3.0.0" + update: + type: http_regex + url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/docker-compose.tmpl.yml + pattern: "bbb-docker-periodic:(v[0-9.]+)" enabled: false # nocheck: playwright-service-flag: prebuilt upstream-compose image, mirror pre-pull only # nocheck: dynamic-flag: fixed upstream-compose sub-service, not group-gated recordings: image: alangecker/bbb-docker-recordings version: "v3.0.23" + update: + type: http_regex + url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + pattern: "repos/bigbluebutton (v[0-9.]+)" enabled: false # nocheck: playwright-service-flag: prebuilt upstream-compose image, mirror pre-pull only # nocheck: dynamic-flag: fixed upstream-compose sub-service, not group-gated bbb-webrtc-recorder: image: alangecker/bbb-docker-webrtc-recorder version: "v0.14.0" + update: + type: http_regex + url: https://raw.githubusercontent.com/bigbluebutton/docker/develop/repos/tags + pattern: "repos/bbb-webrtc-recorder (v[0-9.]+)" enabled: false # nocheck: playwright-service-flag: script-time helper of upstream generate-compose, mirror pre-pull only # nocheck: dynamic-flag: fixed upstream-compose helper, not group-gated diff --git a/roles/web-app-bridgy-fed/meta/services.yml b/roles/web-app-bridgy-fed/meta/services.yml index 1678d4b203..175df25a2c 100644 --- a/roles/web-app-bridgy-fed/meta/services.yml +++ b/roles/web-app-bridgy-fed/meta/services.yml @@ -38,6 +38,7 @@ prometheus: bond: 1 enabled: "{{ 'web-app-prometheus' in group_names }}" shared: "{{ 'web-app-prometheus' in group_names }}" + ready_path: robots.txt bridgy-fed: healthcheck: flavor: tcp diff --git a/roles/web-app-chess/meta/services.yml b/roles/web-app-chess/meta/services.yml index dc6daa65c6..fd94f70819 100644 --- a/roles/web-app-chess/meta/services.yml +++ b/roles/web-app-chess/meta/services.yml @@ -31,7 +31,7 @@ chess: swarm: enabled: true image: ghcr.io/kevinveenbirkenbach/fedi-chess - version: v1.0.1 + version: v1.2.2 name: web-app-chess min_storage: 633MB backup: diff --git a/roles/web-app-flowise/meta/services.yml b/roles/web-app-flowise/meta/services.yml index 0a6448c40e..df6ccc0bd4 100644 --- a/roles/web-app-flowise/meta/services.yml +++ b/roles/web-app-flowise/meta/services.yml @@ -69,7 +69,7 @@ flowise: - key: sqlite_version type: npm package: better-sqlite3 - sqlite_version: 12.11.1 + sqlite_version: 13.0.3 custom: true name: flowise # nocheck: min-storage-headroom Reason: the deployed image is built here from node:24-slim and measures 4.8 GB, so the base image transfer is not its footprint diff --git a/roles/web-app-gitea/meta/services.yml b/roles/web-app-gitea/meta/services.yml index ac35951047..bd57ce9239 100644 --- a/roles/web-app-gitea/meta/services.yml +++ b/roles/web-app-gitea/meta/services.yml @@ -112,7 +112,7 @@ giteamcpupstream: enabled: "{{ lookup('config', 'web-app-gitea', 'mcp.enabled') | bool }}" shared: false image: docker.gitea.com/gitea-mcp-server - version: "1.8.0" + version: "1.8.1" update: type: registry_tags image: docker.gitea.com/gitea-mcp-server diff --git a/roles/web-app-gitea/templates/prometheus.yml.j2 b/roles/web-app-gitea/templates/prometheus.yml.j2 index 3583badebf..ba2fc8151c 100644 --- a/roles/web-app-gitea/templates/prometheus.yml.j2 +++ b/roles/web-app-gitea/templates/prometheus.yml.j2 @@ -9,6 +9,6 @@ bearer_token: "{{ _token }}" {% endif %} static_configs: - - targets: ["{{ native_prometheus_application_id | native_metrics_target(lookup('applications')) }}"] + - targets: ["{{ lookup('native_metrics_target', native_prometheus_application_id) }}"] labels: app: "{{ native_prometheus_application_id }}" diff --git a/roles/web-app-hermes/meta/services.yml b/roles/web-app-hermes/meta/services.yml index 52659b771f..7efb51a6a2 100644 --- a/roles/web-app-hermes/meta/services.yml +++ b/roles/web-app-hermes/meta/services.yml @@ -82,6 +82,7 @@ prometheus: bond: 1 enabled: "{{ 'web-app-prometheus' in group_names }}" shared: "{{ 'web-app-prometheus' in group_names }}" + ready_path: health # nocheck: playwright-service-flag # nocheck: variants-coverage — sso-variant-tor requires the onion on in every variant, so the false polarity has no variant left to live in diff --git a/roles/web-app-matomo/meta/csp.yml b/roles/web-app-matomo/meta/csp.yml index 356e418b88..2b7813bbfc 100644 --- a/roles/web-app-matomo/meta/csp.yml +++ b/roles/web-app-matomo/meta/csp.yml @@ -7,6 +7,7 @@ whitelist: flags: script-src-attr: unsafe-eval: true # nocheck: csp-unsafe Reason: historical, TODO: re-verify it is really required and does not open attack surface + unsafe-inline: true # nocheck: csp-unsafe Reason: Matomo core renders the top-bar "What's new" entry with an inline onclick (plugins/CoreAdminHome/Menu.php); logout-enabled deploys already grant it through the logout injector script-src-elem: unsafe-inline: true # nocheck: csp-unsafe Reason: historical, TODO: re-verify it is really required and does not open attack surface unsafe-eval: true # nocheck: csp-unsafe Reason: historical, TODO: re-verify it is really required and does not open attack surface diff --git a/roles/web-app-matrix/meta/services.yml b/roles/web-app-matrix/meta/services.yml index 1fcc023f32..5a59dbcf13 100644 --- a/roles/web-app-matrix/meta/services.yml +++ b/roles/web-app-matrix/meta/services.yml @@ -104,8 +104,8 @@ prometheus: shared: "{{ 'web-app-prometheus' in group_names }}" native_metrics: enabled: true - port: 9000 - service_key: synapse + port: "{{ 9000 if lookup('config', 'web-app-matrix', 'services.matrix.flavor') == 'compose' else 9100 }}" + service_key: "{{ 'synapse' if lookup('config', 'web-app-matrix', 'services.matrix.flavor') == 'compose' else 'matrix' }}" communication: channel: true # nocheck: playwright-service-flag: shared provider entity; the app itself is covered by this role's own Playwright spec diff --git a/roles/web-app-matrix/templates/flavor/ansible/vars.yml.j2 b/roles/web-app-matrix/templates/flavor/ansible/vars.yml.j2 index 8185cfdfd2..9db5433cae 100644 --- a/roles/web-app-matrix/templates/flavor/ansible/vars.yml.j2 +++ b/roles/web-app-matrix/templates/flavor/ansible/vars.yml.j2 @@ -153,5 +153,9 @@ matrix_bridge_mautrix_twitter_enabled: {{ MATRIX_BRIDGE.mautrix_twitter | string matrix_bridge_mautrix_whatsapp_enabled: {{ MATRIX_BRIDGE.mautrix_whatsapp | string | lower }} matrix_bridge_mautrix_gitter_enabled: {{ MATRIX_BRIDGE.gitter | string | lower }} +matrix_synapse_metrics_enabled: true +matrix_synapse_container_metrics_api_host_bind_port: "0.0.0.0:{{ MATRIX_SYNAPSE_METRICS_PORT }}" +matrix_synapse_metrics_port: {{ MATRIX_SYNAPSE_METRICS_PORT }} + jitsi_enabled: {{ MATRIX_CONFERENCING_JITSI | string | lower }} matrix_rtc_enabled: {{ MATRIX_CONFERENCING_ELEMENT_CALL | string | lower }} diff --git a/roles/web-app-matrix/templates/prometheus.yml.j2 b/roles/web-app-matrix/templates/prometheus.yml.j2 index 79e65ead8f..ac5712173f 100644 --- a/roles/web-app-matrix/templates/prometheus.yml.j2 +++ b/roles/web-app-matrix/templates/prometheus.yml.j2 @@ -1,12 +1,10 @@ # Matrix Synapse — server and federation metrics. # Requires enable_metrics: true in homeserver.yaml. # Enable via native_metrics.enabled: true in inventory. - # Scraped container-to-container: prometheus joins the matrix Docker network and - # reaches synapse directly at container_name:port — no host binding, no nginx/OAuth2. - job_name: "matrix-synapse" scheme: http metrics_path: /_synapse/metrics static_configs: - - targets: ["{{ native_prometheus_application_id | native_metrics_target(lookup('applications')) }}"] + - targets: ["{{ lookup('native_metrics_target', native_prometheus_application_id) }}"] labels: app: "{{ native_prometheus_application_id }}" diff --git a/roles/web-app-matrix/vars/main.yml b/roles/web-app-matrix/vars/main.yml index deea5c3e51..96f3e2daef 100644 --- a/roles/web-app-matrix/vars/main.yml +++ b/roles/web-app-matrix/vars/main.yml @@ -82,6 +82,7 @@ MATRIX_BRIDGE: "{{ lookup('config', application_id, 'services.matrix.plugins') } MATRIX_CONFERENCING_JITSI: "{{ lookup('config', application_id, 'services.matrix.conferencing.jitsi') | bool }}" MATRIX_CONFERENCING_ELEMENT_CALL: "{{ lookup('config', application_id, 'services.matrix.conferencing.element_call') | bool }}" +MATRIX_SYNAPSE_METRICS_PORT: "{{ lookup('config', application_id, 'services.prometheus.native_metrics.port') }}" MATRIX_LDAP_ENABLED: "{{ lookup('config', application_id, 'services.ldap.enabled') | bool }}" diff --git a/roles/web-app-mattermost/templates/prometheus.yml.j2 b/roles/web-app-mattermost/templates/prometheus.yml.j2 index a3b4a71621..67a7e7ae66 100644 --- a/roles/web-app-mattermost/templates/prometheus.yml.j2 +++ b/roles/web-app-mattermost/templates/prometheus.yml.j2 @@ -1,11 +1,9 @@ # Mattermost — application and Go runtime metrics. - # Scraped container-to-container: prometheus joins the mattermost Docker network and - # reaches the app directly at container_name:port — no host binding, no nginx/OAuth2. # Requires MM_METRICSSETTINGS_ENABLE=true and MM_METRICSSETTINGS_LISTENADDRESS (set in env.j2 when enabled). - job_name: "mattermost" scheme: http metrics_path: /metrics static_configs: - - targets: ["{{ native_prometheus_application_id | native_metrics_target(lookup('applications')) }}"] + - targets: ["{{ lookup('native_metrics_target', native_prometheus_application_id) }}"] labels: app: "{{ native_prometheus_application_id }}" diff --git a/roles/web-app-moodle/README.md b/roles/web-app-moodle/README.md index a0a39431e2..fd795b0944 100644 --- a/roles/web-app-moodle/README.md +++ b/roles/web-app-moodle/README.md @@ -121,7 +121,7 @@ docker run --rm -it \ ## MCP server -The role exposes a Model Context Protocol surface through the `webservice_mcp` protocol plugin, baked into the image at `webservice/mcp` and served by the NGINX sidecar. +The role exposes a Model Context Protocol surface through the `webservice_mcp` protocol plugin, baked into the image at `public/webservice/mcp` and served by the NGINX sidecar. | Property | Value | | --- | --- | @@ -173,7 +173,13 @@ This is an accepted trade-off, not an oversight. Moodle offers no allowlist, so ## Image source -This role builds its own Moodle image from upstream Moodle source on top of the official `php:8.3-fpm` base. +This role builds its own Moodle image from upstream Moodle source on top of the official `php:8.3-fpm` base and installs the Composer dependencies that source declares. The NGINX sidecar serves the `public` directory of the code volume and hands every other path to Moodle's router. + +## Updates + +The image carries the Moodle release pinned as `services.moodle.app_version` in `meta/services.yml`. On start the entrypoint compares that release with the one recorded in the code volume. When the image is newer, it copies the image's tree next to the old one and swaps them once the copy is complete. An image that is older than the recorded release refuses to start. `tasks/01_manager_ops.yml` then runs `admin/cli/upgrade.php`, which migrates the database. + +Plugins installed through the web interface live only in the code volume and are not carried over to the next release. Declare a plugin under `meta/addons/` so the image ships it. ## Further Resources diff --git a/roles/web-app-moodle/files/Dockerfile b/roles/web-app-moodle/files/Dockerfile index dc36c5be3a..f6aa1f92c2 100644 --- a/roles/web-app-moodle/files/Dockerfile +++ b/roles/web-app-moodle/files/Dockerfile @@ -96,6 +96,8 @@ COPY build/php-conf/opcache-recommended.ini /usr/local/etc/php/conf.d/opcache-re COPY build/php-conf/moodle-runtime.ini /usr/local/etc/php/conf.d/moodle-runtime.ini COPY build/php-conf/zz-moodle-pool.conf /usr/local/etc/php-fpm.d/zz-moodle-pool.conf +COPY --from=composer:2 /usr/bin/composer /usr/bin/composer + COPY build/install/moodle-source.sh /tmp/install-moodle-source.sh RUN bash /tmp/install-moodle-source.sh && rm /tmp/install-moodle-source.sh diff --git a/roles/web-app-moodle/files/build/config.php b/roles/web-app-moodle/files/build/config.php index 5434affc26..5e66fb1fcd 100644 --- a/roles/web-app-moodle/files/build/config.php +++ b/roles/web-app-moodle/files/build/config.php @@ -40,6 +40,7 @@ $CFG->dataroot = moodle_env('MOODLE_DATAROOT'); $CFG->localcachedir = moodle_env('MOODLE_LOCALCACHEDIR'); $CFG->admin = 'admin'; $CFG->directorypermissions = 02770; +$CFG->routerconfigured = true; $CFG->reverseproxy = moodle_env_bool('MOODLE_REVERSEPROXY'); $CFG->sslproxy = moodle_env_bool('MOODLE_SSLPROXY'); diff --git a/roles/web-app-moodle/files/build/install/moodle-source.sh b/roles/web-app-moodle/files/build/install/moodle-source.sh index 8674cbc69f..17e5fa8df1 100644 --- a/roles/web-app-moodle/files/build/install/moodle-source.sh +++ b/roles/web-app-moodle/files/build/install/moodle-source.sh @@ -26,6 +26,8 @@ tar -xzf "${TARBALL_PATH}" --strip-components=1 -C "${MOODLE_SOURCE_DIR}" test -d "${MOODLE_SOURCE_DIR}/${MOODLE_AUTH_SUBDIR}" test -f "${MOODLE_SOURCE_DIR}/${MOODLE_VERSION_FILE}" +COMPOSER_ALLOW_SUPERUSER=1 composer install --no-dev --classmap-authoritative --no-interaction --working-dir="${MOODLE_SOURCE_DIR}" + mkdir -p "${MOODLE_CODE_DIR}" "${MOODLE_DATA_DIR}" chown -R "${MOODLE_RUNTIME_USER}:${MOODLE_RUNTIME_USER}" \ "${MOODLE_SOURCE_DIR}" "${MOODLE_CODE_DIR}" "${MOODLE_DATA_DIR}" diff --git a/roles/web-app-moodle/files/build/moodle-entrypoint.sh b/roles/web-app-moodle/files/build/moodle-entrypoint.sh index 8474a21407..30083ff2ff 100644 --- a/roles/web-app-moodle/files/build/moodle-entrypoint.sh +++ b/roles/web-app-moodle/files/build/moodle-entrypoint.sh @@ -1,6 +1,6 @@ #!/bin/bash # Moodle container entrypoint. Bootstrap the persistent code volume -# from ${MOODLE_SOURCE_DIR} on first start, ensure ownership on the +# from ${MOODLE_SOURCE_DIR}, ensure ownership on the # data dir, then drop privileges (unless launching php-fpm — its # master process must keep root so the FPM error log can write to # /proc/self/fd/2; workers fork to ${MOODLE_RUNTIME_USER} per the pool). @@ -14,9 +14,11 @@ set -euo pipefail : "${MOODLE_SOURCE_DIR:?required}" : "${MOODLE_RUNTIME_USER:?required}" : "${MOODLE_VERSION_FILE:?required}" +: "${MOODLE_RELEASE:?required}" MOODLE_BOOTSTRAP_SENTINEL="${MOODLE_CODE_DIR}/.bootstrap.done" MOODLE_BOOTSTRAP_LOCK="${MOODLE_CODE_DIR}/.bootstrap.lock" +MOODLE_BOOTSTRAP_STAGE="${MOODLE_CODE_DIR}/.bootstrap.stage" mkdir -p "${MOODLE_DATA_DIR}" chown -R "${MOODLE_RUNTIME_USER}:${MOODLE_RUNTIME_USER}" "${MOODLE_DATA_DIR}" || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error @@ -26,17 +28,36 @@ if [ "$(id -u)" -eq 0 ]; then chown -R "${MOODLE_RUNTIME_USER}:${MOODLE_RUNTIME_USER}" "${MOODLE_LOCAL_CACHE_DIR}" fi +moodle_code_dir_is_current() { + [ "$(cat "${MOODLE_BOOTSTRAP_SENTINEL}" 2>/dev/null)" = "${MOODLE_RELEASE}" ] +} + +moodle_code_dir_is_newer() { + local recorded newest + recorded="$(cat "${MOODLE_BOOTSTRAP_SENTINEL}" 2>/dev/null)" || return 1 + [ -n "${recorded}" ] || return 1 + newest="$(printf '%s\n' "${recorded}" "${MOODLE_RELEASE}" | sort -V | tail -n 1)" + [ "${newest}" = "${recorded}" ] && [ "${recorded}" != "${MOODLE_RELEASE}" ] +} + moodle_bootstrap_code_dir() { - if [ -f "${MOODLE_BOOTSTRAP_SENTINEL}" ]; then + if moodle_code_dir_is_current; then return 0 fi - if [ -d "${MOODLE_SOURCE_DIR}" ]; then - cp -an "${MOODLE_SOURCE_DIR}/." "${MOODLE_CODE_DIR}/" || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error + if moodle_code_dir_is_newer; then + echo "The code volume holds Moodle $(cat "${MOODLE_BOOTSTRAP_SENTINEL}"), this image ships the older ${MOODLE_RELEASE}; refusing to replace it." >&2 + exit 1 fi + rm -rf "${MOODLE_BOOTSTRAP_STAGE}" + mkdir "${MOODLE_BOOTSTRAP_STAGE}" + cp -a "${MOODLE_SOURCE_DIR}/." "${MOODLE_BOOTSTRAP_STAGE}/" + find "${MOODLE_CODE_DIR}" -mindepth 1 -maxdepth 1 ! -name "${MOODLE_BOOTSTRAP_LOCK##*/}" ! -name "${MOODLE_BOOTSTRAP_STAGE##*/}" -exec rm -rf {} + + find "${MOODLE_BOOTSTRAP_STAGE}" -mindepth 1 -maxdepth 1 -exec mv -t "${MOODLE_CODE_DIR}" {} + + rmdir "${MOODLE_BOOTSTRAP_STAGE}" chown -R "${MOODLE_RUNTIME_USER}:${MOODLE_RUNTIME_USER}" "${MOODLE_CODE_DIR}" || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error find "${MOODLE_CODE_DIR}" -type d -exec chmod 0755 {} + || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error find "${MOODLE_CODE_DIR}" -type f -exec chmod 0644 {} + || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error - touch "${MOODLE_BOOTSTRAP_SENTINEL}" + printf '%s' "${MOODLE_RELEASE}" > "${MOODLE_BOOTSTRAP_SENTINEL}" } moodle_refresh_config() { @@ -51,7 +72,7 @@ moodle_refresh_config() { } mkdir -p "${MOODLE_CODE_DIR}" -while [ ! -f "${MOODLE_BOOTSTRAP_SENTINEL}" ]; do +until moodle_code_dir_is_current; do exec 9>>"${MOODLE_BOOTSTRAP_LOCK}" if flock -w 30 9; then moodle_bootstrap_code_dir diff --git a/roles/web-app-moodle/files/php/provision/ai_gateway.php b/roles/web-app-moodle/files/php/provision/ai_gateway.php new file mode 100644 index 0000000000..cfebaf1d8e --- /dev/null +++ b/roles/web-app-moodle/files/php/provision/ai_gateway.php @@ -0,0 +1,44 @@ +get_provider_instances(['provider' => $class, 'name' => $name]); +$provider = $instances + ? reset($instances) + : $manager->create_provider_instance(classname: $class, name: $name); + +$actionconfig = $provider->actionconfig; +foreach ($textactions as $action) { + $actionconfig[$action]['enabled'] = true; + $actionconfig[$action]['settings']['endpoint'] = (string) getenv('AI_CHAT_ENDPOINT'); + $actionconfig[$action]['settings']['model'] = (string) getenv('AI_CHAT_MODEL'); +} +$actionconfig[$imageaction]['enabled'] = false; +$actionconfig[$imageaction]['settings']['endpoint'] = (string) getenv('AI_IMAGE_ENDPOINT'); + +$provider = $manager->update_provider_instance( + provider: $provider, + config: array_merge($provider->config, ['apikey' => (string) getenv('AI_API_KEY')]), + actionconfig: $actionconfig, +); +$manager->enable_provider_instance($provider); + +$stored = $manager->get_provider_instances(['id' => $provider->id]); +echo json_encode([ + 'id' => (int) $provider->id, + 'endpoints' => array_map( + fn(array $action): string => (string) ($action['settings']['endpoint'] ?? ''), + reset($stored)->actionconfig, + ), +]), PHP_EOL; diff --git a/roles/web-app-moodle/files/php/provision_mcp.php b/roles/web-app-moodle/files/php/provision/mcp.php similarity index 100% rename from roles/web-app-moodle/files/php/provision_mcp.php rename to roles/web-app-moodle/files/php/provision/mcp.php diff --git a/roles/web-app-moodle/files/playwright/test-litellm-gateway.js b/roles/web-app-moodle/files/playwright/test-litellm-gateway.js index 038d3c3c70..6c7cec5be5 100644 --- a/roles/web-app-moodle/files/playwright/test-litellm-gateway.js +++ b/roles/web-app-moodle/files/playwright/test-litellm-gateway.js @@ -5,7 +5,10 @@ const { skipUnlessServiceEnabled } = require("./service-gating"); const adminNativePassword = decodeDotenvQuotedValue(process.env.ADMIN_NATIVE_PASSWORD || ""); -const ENDPOINT_FIELD = "#id_s_aiprovider_openai_action_generate_text_endpoint"; +const providerName = decodeDotenvQuotedValue(process.env.MOODLE_AI_PROVIDER_NAME || ""); + +const ENDPOINT_FIELD = "#id_endpoint"; +const GENERATE_TEXT_ACTION = "core_ai\\aiactions\\generate_text"; const USER_MENU = ".usermenu, [data-region='user-menu-toggle'], a[href*='profile.php']"; const GATEWAY_PROMPT = "Reply with the single word: pong"; @@ -80,22 +83,47 @@ exports.register = function (shared) { await loginAsSiteAdmin(page, shared); + expect( + providerName, + "MOODLE_AI_PROVIDER_NAME must name the provider instance the deploy creates; without it the test cannot tell that instance from one an administrator added", + ).toBeTruthy(); + + await gotoOnion(page, `${shared.env.moodleBaseUrl}/admin/settings.php?section=aiprovider`, { + waitUntil: "domcontentloaded", + timeout: resolveTimeout(60_000), + }); + + const providerLink = page + .locator("tr", { hasText: providerName }) + .locator("a[href*='/ai/configure.php']") + .first(); + await expect( + providerLink, + `the AI providers page must list the instance "${providerName}"; its absence means the deploy created no provider instance or the session lacks moodle/site:config`, + ).toBeVisible({ timeout: resolveTimeout(60_000) }); + + const providerId = new URL( + await providerLink.getAttribute("href"), + shared.env.moodleBaseUrl, + ).searchParams.get("id"); + await gotoOnion( page, - `${shared.env.moodleBaseUrl}/admin/settings.php?section=aiprovider_openai_generate_text`, + `${shared.env.moodleBaseUrl}/ai/configure_actions.php` + + `?provider=aiprovider_openai&action=${encodeURIComponent(GENERATE_TEXT_ACTION)}&providerid=${providerId}`, { waitUntil: "domcontentloaded", timeout: resolveTimeout(60_000) }, ); const endpointField = page.locator(ENDPOINT_FIELD); await expect( endpointField, - "the aiprovider_openai generate_text settings page must render its API endpoint field; its absence means the provider was never configured or the session lacks moodle/site:config", + "the generate_text settings page of the provider instance must render its API endpoint field; its absence means the instance carries no generate_text action", ).toBeVisible({ timeout: resolveTimeout(60_000) }); const configuredEndpoint = ((await endpointField.inputValue()) || "").trim(); expect( configuredEndpoint, - "aiprovider_openai/action_generate_text_endpoint must be an http(s) URL written by the deploy, not the upstream api.openai.com default", + "the generate_text endpoint of the provider instance must be an http(s) URL written by the deploy, not the upstream api.openai.com default", ).toMatch(/^https?:\/\/.+/i); const endpointHost = new URL(configuredEndpoint).hostname; diff --git a/roles/web-app-moodle/meta/addons/auth_oidc.yml b/roles/web-app-moodle/meta/addons/auth_oidc.yml index 1e33ee4776..5d68112121 100644 --- a/roles/web-app-moodle/meta/addons/auth_oidc.yml +++ b/roles/web-app-moodle/meta/addons/auth_oidc.yml @@ -3,11 +3,11 @@ enabled: "{{ lookup('config', 'web-app-moodle', 'services.sso.enabled') | bool } required: false mechanism: plugin source: upstream -version: "v4.5.8" +version: "v5.2.1" bridges: - sso update: monitored: true catalog: github-releases upstream_id: microsoft/moodle-auth_oidc - match: "v4.5." + match: "v" diff --git a/roles/web-app-moodle/meta/server.yml b/roles/web-app-moodle/meta/server.yml new file mode 100644 index 0000000000..f365eb8102 --- /dev/null +++ b/roles/web-app-moodle/meta/server.yml @@ -0,0 +1,5 @@ +--- +status_codes: + default: + - 200 + - 303 diff --git a/roles/web-app-moodle/meta/services.yml b/roles/web-app-moodle/meta/services.yml index 908536fd0f..9c89c98c08 100644 --- a/roles/web-app-moodle/meta/services.yml +++ b/roles/web-app-moodle/meta/services.yml @@ -45,7 +45,7 @@ moodle: bond: 1 enabled: true # nocheck: dynamic-flag shared: true - app_version: 4.5.11 + app_version: 5.3.0 update: key: app_version type: git_tags diff --git a/roles/web-app-moodle/tasks/01_manager_ops.yml b/roles/web-app-moodle/tasks/01_manager_ops.yml index 078f32c1ca..93cd1d5e97 100644 --- a/roles/web-app-moodle/tasks/01_manager_ops.yml +++ b/roles/web-app-moodle/tasks/01_manager_ops.yml @@ -48,6 +48,13 @@ - "'Database tables already present' not in moodle_install.stderr" no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" +- name: "⬆️ Upgrade the Moodle database to the release in the code volume" + shell: > + container exec --user {{ MOODLE_RUNTIME_USER }} {{ MOODLE_CONTAINER_ADDRESS }} + php {{ MOODLE_CLI_DIR }}/upgrade.php --non-interactive + register: moodle_upgrade + changed_when: "'No upgrade needed' not in moodle_upgrade.stderr" + - name: "🔑 Realign the administrator password Moodle persisted at install" when: not (MOODLE_OIDC_ENABLED | bool) # nocheck: password-quote the token is upstream's CLI filename, not a credential diff --git a/roles/web-app-moodle/tasks/04_oidc.yml b/roles/web-app-moodle/tasks/04_oidc.yml index e150b4d5ed..2166ccec42 100644 --- a/roles/web-app-moodle/tasks/04_oidc.yml +++ b/roles/web-app-moodle/tasks/04_oidc.yml @@ -93,7 +93,7 @@ - { name: "field_map_lastnamephonetic", value: "name_phonetic_family" } - { name: "field_lock_lastnamephonetic", value: "locked" } - { name: "field_updatelocal_lastnamephonetic", value: "oneveryloginupdate" } - - { name: "alternateloginurl", value: "{{ lookup('tls', application_id, 'url.base') }}{{ MOODLE_OIDC_PLUGIN_RELPATH }}/" } + - { name: "alternateloginurl", value: "{{ lookup('tls', application_id, 'url.base') }}{{ MOODLE_OIDC_PLUGIN_URL_PATH }}/" } loop_control: label: "{{ item.name }}" shell: > diff --git a/roles/web-app-moodle/tasks/utils/ai_gateway.yml b/roles/web-app-moodle/tasks/utils/ai_gateway.yml index ef74562a9b..55832a8079 100644 --- a/roles/web-app-moodle/tasks/utils/ai_gateway.yml +++ b/roles/web-app-moodle/tasks/utils/ai_gateway.yml @@ -2,18 +2,31 @@ - name: "🔐 Verify the gateway contract for {{ application_id }}" ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/svc-ai-litellm/tasks/utils/consumer_contract.yml') }}" -- name: "🤖 Point the Moodle AI subsystem at the platform gateway" +- name: "🤖 Point the Moodle AI provider instance at the platform gateway" + ansible.builtin.shell: > + container exec -i --user {{ MOODLE_RUNTIME_USER }} + -e MOODLE_CONFIG={{ MOODLE_CONFIG | quote }} + -e AI_PROVIDER_NAME={{ MOODLE_LITELLM_PROVIDER_NAME | quote }} + -e AI_API_KEY={{ MOODLE_LITELLM_API_KEY | quote }} + -e AI_CHAT_ENDPOINT={{ MOODLE_LITELLM_CHAT_ENDPOINT | quote }} + -e AI_CHAT_MODEL={{ LITELLM_CHAT_MODEL | quote }} + -e AI_IMAGE_ENDPOINT={{ MOODLE_LITELLM_IMAGE_ENDPOINT | quote }} + {{ MOODLE_CONTAINER_ADDRESS }} php + args: + stdin: "{{ lookup('file', 'php/provision/ai_gateway.php') }}" + register: moodle_ai_provider + changed_when: false + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "🤖 Enable the Moodle AI placements" ansible.builtin.shell: > container exec --user {{ MOODLE_RUNTIME_USER }} {{ MOODLE_CONTAINER_ADDRESS }} php {{ [MOODLE_CLI_DIR, 'cfg.php'] | path_join }} - --component={{ item.component | quote }} - --name={{ item.name | quote }} - --set={{ item.value | quote }} - loop: "{{ MOODLE_LITELLM_SETTINGS }}" - loop_control: - label: "{{ item.component }}/{{ item.name }}" + --component={{ item | quote }} + --name=enabled + --set=1 + loop: "{{ MOODLE_LITELLM_PLACEMENTS }}" changed_when: false - no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - name: "🧹 Purge Moodle caches so the provider picks up its endpoint" ansible.builtin.shell: > @@ -21,20 +34,14 @@ php {{ [MOODLE_CLI_DIR, 'purge_caches.php'] | path_join }} changed_when: false -- name: "🔎 Read back the configured chat endpoint" - ansible.builtin.shell: > - container exec --user {{ MOODLE_RUNTIME_USER }} {{ MOODLE_CONTAINER_ADDRESS }} - php {{ [MOODLE_CLI_DIR, 'cfg.php'] | path_join }} - --component=aiprovider_openai - --name=action_generate_text_endpoint - register: moodle_ai_endpoint - changed_when: false - - name: "🛑 Refuse a Moodle AI provider that does not answer through the gateway" ansible.builtin.assert: that: - - (moodle_ai_endpoint.stdout | trim) == MOODLE_LITELLM_CHAT_ENDPOINT + - moodle_ai_endpoints | length > 0 + - moodle_ai_endpoints | difference([MOODLE_LITELLM_CHAT_ENDPOINT, MOODLE_LITELLM_IMAGE_ENDPOINT]) | length == 0 fail_msg: >- - aiprovider_openai still resolves generate_text to - '{{ moodle_ai_endpoint.stdout | trim }}' instead of + The Moodle AI provider instance resolves actions to + {{ moodle_ai_endpoints | join(', ') }} instead of {{ MOODLE_LITELLM_CHAT_ENDPOINT }}, so prompts would leave the deployment. + vars: + moodle_ai_endpoints: "{{ (moodle_ai_provider.stdout_lines | last | from_json).endpoints.values() | unique | list }}" diff --git a/roles/web-app-moodle/tasks/utils/mcp/provision.yml b/roles/web-app-moodle/tasks/utils/mcp/provision.yml index 20ff563c06..725661b800 100644 --- a/roles/web-app-moodle/tasks/utils/mcp/provision.yml +++ b/roles/web-app-moodle/tasks/utils/mcp/provision.yml @@ -14,7 +14,7 @@ -e MCP_ROLE_CAPABILITIES={{ MOODLE_MCP_ROLE_CAPABILITIES | join(',') | quote }} \ {{ MOODLE_MCP_LOCAL_CID | quote }} php args: - stdin: "{{ lookup('file', 'php/provision_mcp.php') }}" + stdin: "{{ lookup('file', 'php/provision/mcp.php') }}" register: moodle_mcp_provision changed_when: false delegate_to: "{{ MOODLE_MCP_HOST_NODE }}" diff --git a/roles/web-app-moodle/templates/nginx-moodle.conf.j2 b/roles/web-app-moodle/templates/nginx-moodle.conf.j2 index 477b89cd1f..ca7b6a2a03 100644 --- a/roles/web-app-moodle/templates/nginx-moodle.conf.j2 +++ b/roles/web-app-moodle/templates/nginx-moodle.conf.j2 @@ -7,7 +7,7 @@ server { listen [::]:{{ MOODLE_NGINX_PORT }}; server_name _; - root {{ MOODLE_CODE_DIR }}; + root {{ MOODLE_PUBLIC_DIR }}; index index.php; client_max_body_size 256M; @@ -16,16 +16,19 @@ server { set $moodle_upstream {{ MOODLE_CONTAINER }}; location / { - try_files $uri $uri/ /index.php?$query_string; + try_files $uri $uri/ /r.php$is_args$args; } location ~ [^/]\.php(/|$) { - fastcgi_split_path_info ^(.+\.php)(/.+)$; + fastcgi_split_path_info ^(.+\.php)(/.*)?$; + set $path_info $fastcgi_path_info; + try_files $fastcgi_script_name $fastcgi_script_name/ /r.php$is_args$args; fastcgi_index index.php; fastcgi_pass $moodle_upstream:{{ MOODLE_FPM_PORT }}; include fastcgi_params; - fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; - fastcgi_param PATH_INFO $fastcgi_path_info; + fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name; + fastcgi_param DOCUMENT_ROOT $realpath_root; + fastcgi_param PATH_INFO $path_info; fastcgi_param HTTP_PROXY ""; fastcgi_read_timeout 300; } diff --git a/roles/web-app-moodle/templates/playwright.env.j2 b/roles/web-app-moodle/templates/playwright.env.j2 index 02eb6ebd3c..6fbea79405 100644 --- a/roles/web-app-moodle/templates/playwright.env.j2 +++ b/roles/web-app-moodle/templates/playwright.env.j2 @@ -21,6 +21,7 @@ PERSONA_ADMINISTRATOR_BLOCKED=true MATOMO_BASE_URL={{ lookup('tls', 'web-app-matomo', 'url.base') | dotenv_quote }} LITELLM_SERVICE_ENABLED={{ lookup('config', application_id, 'services.litellm.enabled') | string | lower }} +MOODLE_AI_PROVIDER_NAME={{ MOODLE_LITELLM_PROVIDER_NAME | dotenv_quote }} SSO_SERVICE_ENABLED={{ lookup('config', application_id, 'services.sso.enabled') | string | lower }} LOGOUT_SERVICE_ENABLED={{ lookup('config', application_id, 'services.logout.enabled') | string | lower }} MATOMO_SERVICE_ENABLED={{ lookup('config', application_id, 'services.matomo.enabled') | string | lower }} diff --git a/roles/web-app-moodle/vars/main.yml b/roles/web-app-moodle/vars/main.yml index 75cfd20cbc..fffdb5f0db 100644 --- a/roles/web-app-moodle/vars/main.yml +++ b/roles/web-app-moodle/vars/main.yml @@ -19,15 +19,18 @@ MOODLE_BUILD_FILES: opcache_ini: "php-conf/opcache-recommended.ini" runtime_ini: "php-conf/moodle-runtime.ini" fpm_pool: "php-conf/zz-moodle-pool.conf" -MOODLE_VERSION_FILE: "version.php" # bootstrap-detection sentinel -MOODLE_AUTH_SUBDIR: "auth" # top-level auth/ tree -MOODLE_WEBSERVICE_SUBDIR: "webservice" +MOODLE_PUBLIC_SUBDIR: "public" +MOODLE_PUBLIC_DIR: "{{ [MOODLE_CODE_DIR, MOODLE_PUBLIC_SUBDIR] | path_join }}" +MOODLE_VERSION_FILE: "{{ [MOODLE_PUBLIC_SUBDIR, 'version.php'] | path_join }}" +MOODLE_AUTH_SUBDIR: "{{ [MOODLE_PUBLIC_SUBDIR, 'auth'] | path_join }}" +MOODLE_WEBSERVICE_SUBDIR: "{{ [MOODLE_PUBLIC_SUBDIR, 'webservice'] | path_join }}" MOODLE_CLI_RELPATH: "admin/cli" # admin CLI script dir MOODLE_OIDC_PLUGIN_VERSION: "{{ lookup('config', application_id, 'addons.auth_oidc.version') }}" MOODLE_OIDC_PLUGIN_UPSTREAM: "{{ lookup('config', application_id, 'addons.auth_oidc.update.upstream_id') }}" MOODLE_OIDC_PLUGIN_ARCHIVE_URL: "https://github.com/{{ MOODLE_OIDC_PLUGIN_UPSTREAM }}/archive/refs/tags/{{ MOODLE_OIDC_PLUGIN_VERSION }}.zip" -MOODLE_OIDC_PLUGIN_RELPATH: "{{ [MOODLE_AUTH_SUBDIR, 'oidc'] | path_join }}" +MOODLE_OIDC_PLUGIN_URL_PATH: "auth/oidc" +MOODLE_OIDC_PLUGIN_RELPATH: "{{ [MOODLE_PUBLIC_SUBDIR, MOODLE_OIDC_PLUGIN_URL_PATH] | path_join }}" MOODLE_OIDC_PLUGIN_DIR: "{{ [MOODLE_CODE_DIR, MOODLE_OIDC_PLUGIN_RELPATH] | path_join }}" MOODLE_CLI_DIR: "{{ [MOODLE_CODE_DIR, MOODLE_CLI_RELPATH] | path_join }}" MOODLE_CONFIG: "{{ [MOODLE_CODE_DIR, 'config.php'] | path_join }}" @@ -60,17 +63,10 @@ MOODLE_LITELLM_ENABLED: "{{ lookup('config', application_id, 'services.litellm.e MOODLE_LITELLM_API_KEY: "{{ lookup('config', application_id, 'secrets.credentials.litellm_api_key') }}" MOODLE_LITELLM_CHAT_ENDPOINT: "{{ LITELLM_OPENAI_BASE_LOCAL_URL }}/chat/completions" MOODLE_LITELLM_IMAGE_ENDPOINT: "{{ LITELLM_OPENAI_BASE_LOCAL_URL }}/images/generations" -MOODLE_LITELLM_SETTINGS: - - { component: aiprovider_openai, name: enabled, value: "1" } - - { component: aiprovider_openai, name: apikey, value: "{{ MOODLE_LITELLM_API_KEY }}" } - - { component: aiprovider_openai, name: action_generate_text_endpoint, value: "{{ MOODLE_LITELLM_CHAT_ENDPOINT }}" } - - { component: aiprovider_openai, name: action_generate_text_model, value: "{{ LITELLM_CHAT_MODEL }}" } - - { component: aiprovider_openai, name: action_summarise_text_endpoint, value: "{{ MOODLE_LITELLM_CHAT_ENDPOINT }}" } - - { component: aiprovider_openai, name: action_summarise_text_model, value: "{{ LITELLM_CHAT_MODEL }}" } - - { component: aiprovider_openai, name: action_generate_image_endpoint, value: "{{ MOODLE_LITELLM_IMAGE_ENDPOINT }}" } - - { component: aiprovider_openai, name: generate_image, value: "0" } - - { component: aiplacement_courseassist, name: enabled, value: "1" } - - { component: aiplacement_editor, name: enabled, value: "1" } +MOODLE_LITELLM_PROVIDER_NAME: "LiteLLM gateway" +MOODLE_LITELLM_PLACEMENTS: + - aiplacement_courseassist + - aiplacement_editor MOODLE_EGRESS_BLOCKED_HOSTS: - "0.0.0.0" diff --git a/roles/web-app-n8n/files/javascript/hooks.js b/roles/web-app-n8n/files/javascript/hooks.js index 9b70bddff5..80e3f06db6 100644 --- a/roles/web-app-n8n/files/javascript/hooks.js +++ b/roles/web-app-n8n/files/javascript/hooks.js @@ -48,10 +48,12 @@ module.exports = { this.logger?.info(`SSO middleware initializing with header: ${headerName}`); - const Layer = require('router/lib/layer'); + const { createRequire } = require('module'); const { dirname, resolve } = require('path'); const { randomBytes } = require('crypto'); - const { hash } = require('bcryptjs'); + const n8nRequire = createRequire(require.resolve('n8n')); + const Layer = createRequire(n8nRequire.resolve('express'))('router/lib/layer'); + const { hash } = n8nRequire('bcryptjs'); const { issueCookie } = require(resolve(dirname(require.resolve('n8n')), 'auth/jwt')); // Trust the proxy for correct X-Forwarded-* handling and rate limiting @@ -114,18 +116,17 @@ module.exports = { this.logger?.info(`SSO auto-login attempt for email: ${userEmail}`); - // 1) Try to fetch the user (n8n 1.95.3 stores 'role' as a plain string column) let user = await UserRepo.findOne({ where: { email: userEmail }, + relations: ['role'], }); - // 2) If not found — create the user (with 'global:member' role) and a project if (!user) { const hashed = await hash(randomBytes(16).toString('hex'), 10); const userData = { email: userEmail, - role: 'global:member', // string-based role is valid for createUserWithProject + role: { slug: 'global:member' }, password: hashed, }; if (userFirstName) userData.firstName = userFirstName; @@ -136,7 +137,6 @@ module.exports = { this.logger?.info(`Created new user: ${userEmail} (${userFirstName} ${userLastName}) via SSO`); } else { - // 3) Update first/last name if they changed upstream let changed = false; if (userFirstName && user.firstName !== userFirstName) { user.firstName = userFirstName; @@ -154,7 +154,6 @@ module.exports = { } } - // 4) Ensure 'user.role' exists (plain string column, e.g. 'global:member') if (!user.role) { this.logger?.error(`User ${userEmail} has no valid role; cannot issue cookie.`); res.statusCode = 401; @@ -162,10 +161,8 @@ module.exports = { return; } - // 5) Issue n8n auth cookie issueCookie(res, user); - // 6) Attach context for downstream middleware/routes req.user = user; req.userId = user.id; diff --git a/roles/web-app-n8n/meta/services.yml b/roles/web-app-n8n/meta/services.yml index a7ad1c3b40..156c60abc5 100644 --- a/roles/web-app-n8n/meta/services.yml +++ b/roles/web-app-n8n/meta/services.yml @@ -67,7 +67,7 @@ n8n: backup: no_stop_required: false image: docker.n8n.io/n8nio/n8n - version: "1.100.1" + version: "2.42.3" update: type: registry_tags image: docker.n8n.io/n8nio/n8n diff --git a/roles/web-app-nextcloud/meta/variants.yml b/roles/web-app-nextcloud/meta/variants.yml index 5dad822253..60a096f8d3 100644 --- a/roles/web-app-nextcloud/meta/variants.yml +++ b/roles/web-app-nextcloud/meta/variants.yml @@ -1097,7 +1097,7 @@ enabled: false shared: false addons: *addons_static_off -# Variant 11: bigbluebutton +# Variant 11: bigbluebutton - clearnet, because bigbluebutton rides no node onion - services: container_backup: enabled: false @@ -1183,7 +1183,7 @@ enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true tor: - enabled: true + enabled: false hermes: enabled: false shared: false diff --git a/roles/web-app-openbao/templates/prometheus.yml.j2 b/roles/web-app-openbao/templates/prometheus.yml.j2 index 3dd99470c9..9eedd90c6f 100644 --- a/roles/web-app-openbao/templates/prometheus.yml.j2 +++ b/roles/web-app-openbao/templates/prometheus.yml.j2 @@ -4,6 +4,6 @@ params: format: ["prometheus"] static_configs: - - targets: ["{{ native_prometheus_application_id | native_metrics_target(lookup('applications')) }}"] + - targets: ["{{ lookup('native_metrics_target', native_prometheus_application_id) }}"] labels: app: "{{ native_prometheus_application_id }}" diff --git a/roles/web-app-opentalk/README.md b/roles/web-app-opentalk/README.md index a3e78e943d..412390e70c 100644 --- a/roles/web-app-opentalk/README.md +++ b/roles/web-app-opentalk/README.md @@ -76,7 +76,7 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( - **Single Sign-On:** Frontend and controller share one Keycloak client and realm. - **Federated User Lookup:** Invitee search resolves through the Keycloak admin Web API, so any user federated from OpenLDAP into Keycloak becomes findable inside OpenTalk. - **OpenCloud File Integration:** Pick files from OpenCloud in a meeting without re-authenticating when `web-app-opencloud` is deployed alongside. -- **Meeting Recordings:** A dedicated recorder consumes recording jobs from the RabbitMQ queue and stores MP4 archives in MinIO. +- **Meeting Recordings:** The controller starts recordings on a dedicated recorder over its REST API, and the recorder stores MP4 archives in MinIO. - **Shared Infrastructure:** Reuses `svc-db-postgres` for relational data and `web-svc-coturn` for STUN and TURN. ## Quick Setup diff --git a/roles/web-app-opentalk/meta/secrets.yml b/roles/web-app-opentalk/meta/secrets.yml index a36001f92f..5b251109a8 100644 --- a/roles/web-app-opentalk/meta/secrets.yml +++ b/roles/web-app-opentalk/meta/secrets.yml @@ -15,8 +15,9 @@ credentials: algorithm: alphanumeric validation: min_length: 32 - recorder_oidc_client_secret: - description: Client secret for the dedicated confidential Keycloak client (`opentalk-recorder`) the recorder uses to authenticate against the controller. + recorder_api_secret: + description: API key secret the controller signs its requests to the recorder with (`roomserver.modules.recording.api_key`, `http.api_keys` of the + recorder). algorithm: alphanumeric validation: min_length: 32 diff --git a/roles/web-app-opentalk/meta/services.yml b/roles/web-app-opentalk/meta/services.yml index 5509c681aa..4ceba7a5ba 100644 --- a/roles/web-app-opentalk/meta/services.yml +++ b/roles/web-app-opentalk/meta/services.yml @@ -61,7 +61,11 @@ opentalk: placement: manager name: opentalk image: registry.opencode.de/opentalk/web-frontend - version: v2.9.0 # nocheck: docker-version — component of the OpenTalk set; TODO: pin the set to a released bundle, then unpin + version: v2.9.2 + update: + type: http_regex + url: https://gitlab.opencode.de/opentalk/ot-setup/-/raw/main/docker-compose.yaml + pattern: "OT_FRONTEND_IMAGE_TAG:-(v[0-9.]+)\\}" min_storage: 234MB backup: no_stop_required: true @@ -80,7 +84,11 @@ opentalk: controller: name: opentalk-controller image: registry.opencode.de/opentalk/controller - version: v0.34.1 # nocheck: docker-version — component of the OpenTalk set; TODO: pin the set to a released bundle, then unpin + version: v0.34.5 + update: + type: http_regex + url: https://gitlab.opencode.de/opentalk/ot-setup/-/raw/main/docker-compose.yaml + pattern: "OPENTALK_CONTROLLER_IMAGE_TAG:-(v[0-9.]+)\\}" min_storage: 291MB backup: no_stop_required: true @@ -96,7 +104,7 @@ controller: livekit: name: opentalk-livekit image: livekit/livekit-server - version: v1.13.8 + version: v1.13.9 min_storage: 238MB cpus: "2.0" mem_reservation: 512m @@ -143,7 +151,14 @@ rabbit: recorder: name: opentalk-recorder image: registry.opencode.de/opentalk/recorder - version: v0.16.2 # nocheck: docker-version — v0.17 drops the rabbitmq transport and reshapes [controller]; TODO: migrate recorder.toml.j2, then unpin + version: v0.17.5 + update: + type: http_regex + url: https://gitlab.opencode.de/opentalk/ot-setup/-/raw/main/docker-compose.yaml + pattern: "RECORDER_IMAGE_TAG:-(v[0-9.]+)\\}" + ports: + internal: + http: 11511 min_storage: 775MB cpus: "1.5" mem_reservation: 512m diff --git a/roles/web-app-opentalk/tasks/02_keycloak_client.yml b/roles/web-app-opentalk/tasks/02_keycloak_client.yml index 1b319fcf94..331151333f 100644 --- a/roles/web-app-opentalk/tasks/02_keycloak_client.yml +++ b/roles/web-app-opentalk/tasks/02_keycloak_client.yml @@ -74,38 +74,6 @@ delegate_to: "{{ OPENTALK_KEYCLOAK_HOST_NODE }}" no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" -- name: "📝 Upsert dedicated confidential Keycloak client for the OpenTalk recorder" - keycloak_kcadm_update: - object_kind: "client" - lookup_value: "{{ OPENTALK_RECORDER_OIDC_CLIENT_ID }}" - desired: - clientId: "{{ OPENTALK_RECORDER_OIDC_CLIENT_ID }}" - name: "OpenTalk Recorder" - description: "Confidential service-account client used by the OpenTalk recorder to authenticate against the controller." - enabled: true - protocol: "openid-connect" - publicClient: false - bearerOnly: false - standardFlowEnabled: false - implicitFlowEnabled: false - directAccessGrantsEnabled: false - serviceAccountsEnabled: true - clientAuthenticatorType: "client-secret" - secret: "{{ OPENTALK_RECORDER_OIDC_CLIENT_SECRET }}" - attributes: - "client.secret.creation.time": "0" - "oauth2.device.authorization.grant.enabled": "false" - "use.refresh.tokens": "true" - force_attrs: - publicClient: false - serviceAccountsEnabled: true - secret: "{{ OPENTALK_RECORDER_OIDC_CLIENT_SECRET }}" - kcadm_exec: "container exec -i {{ OPENTALK_KEYCLOAK_LOCAL_CID }} /opt/keycloak/bin/kcadm.sh" # nocheck: container-exec-resolver OPENTALK_KEYCLOAK_LOCAL_CID resolved at delegate_to runtime - realm: "{{ OIDC.CLIENT.REALM }}" - assert_mode: "{{ MODE_ASSERT | bool }}" - delegate_to: "{{ OPENTALK_KEYCLOAK_HOST_NODE }}" - no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - - name: "🔐 Grant OpenTalk controller service account `view-users` role" ansible.builtin.shell: |- {{ KCEXEC }} sh -lc ' diff --git a/roles/web-app-opentalk/templates/compose.yml.j2 b/roles/web-app-opentalk/templates/compose.yml.j2 index 1f3b15103a..20c05159c8 100644 --- a/roles/web-app-opentalk/templates/compose.yml.j2 +++ b/roles/web-app-opentalk/templates/compose.yml.j2 @@ -56,7 +56,7 @@ {{ lookup('compose_restart') }} {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_networks') | indent(4) }} - {{ lookup('depends_on', {'rabbit': 'service_healthy', 'controller': 'service_started'}) }} + {{ lookup('depends_on', {'controller': 'service_started'}) }} logging: driver: journald diff --git a/roles/web-app-opentalk/templates/controller.toml.j2 b/roles/web-app-opentalk/templates/controller.toml.j2 index a628775876..69df4a30ed 100644 --- a/roles/web-app-opentalk/templates/controller.toml.j2 +++ b/roles/web-app-opentalk/templates/controller.toml.j2 @@ -6,7 +6,7 @@ base_url = "{{ OPENTALK_URL }}" [http] port = {{ OPENTALK_CTRL_INTERNAL_PORT }} -service_api_keys = [{ "id" = "controller", "secret" = "{{ lookup('config', application_id, 'secrets.credentials.service_api_secret') }}" }] +service_api_keys = [{ "id" = "{{ OPENTALK_CTRL_SERVICE_API_KEY_ID }}", "secret" = "{{ OPENTALK_CTRL_SERVICE_API_SECRET }}" }] [database] url = "postgres://{{ lookup('database', application_id, 'username') }}:{{ lookup('database', application_id, 'password') }}@{{ lookup('database', application_id, 'host') }}:{{ lookup('database', application_id, 'port') }}/{{ lookup('database', application_id, 'name') }}" @@ -38,6 +38,9 @@ public_url = "wss://{{ OPENTALK_DOMAIN }}/livekit" service_url = "http://livekit:{{ OPENTALK_LIVEKIT_HTTP_PORT }}" api_key = "{{ OPENTALK_LIVEKIT_API_KEY }}" api_secret = "{{ OPENTALK_LIVEKIT_API_SECRET }}" +[roomserver.modules.recording] +url = "http://recorder:{{ OPENTALK_RECORDER_HTTP_PORT }}" +api_key = { id = "{{ OPENTALK_RECORDER_API_KEY_ID }}", secret = "{{ OPENTALK_RECORDER_API_SECRET }}" } [roomserver.modules.echo] [roomserver.modules.chat] [roomserver.modules.polls] @@ -55,5 +58,4 @@ secret_key = "{{ lookup('objstore', application_id, 'secret_key') }}" [rabbit_mq] url = "amqp://guest:guest@rabbit/%2F" mail_task_queue = "opentalk_mailer" -recording_task_queue = "{{ OPENTALK_RABBIT_QUEUE }}" diff --git a/roles/web-app-opentalk/templates/recorder.toml.j2 b/roles/web-app-opentalk/templates/recorder.toml.j2 index 8927749a53..f6c538521f 100644 --- a/roles/web-app-opentalk/templates/recorder.toml.j2 +++ b/roles/web-app-opentalk/templates/recorder.toml.j2 @@ -1,14 +1,10 @@ # OpenTalk recorder configuration. # Reference: https://docs.opentalk.eu/admin/recorder/configuration/ -[auth] -issuer = "{{ OIDC.CLIENT.ISSUER_URL }}" -client_id = "{{ OPENTALK_RECORDER_OIDC_CLIENT_ID }}" -client_secret = "{{ OPENTALK_RECORDER_OIDC_CLIENT_SECRET }}" - [controller] -domain = "{{ OPENTALK_DOMAIN }}" +url = "http://controller:{{ OPENTALK_CTRL_INTERNAL_PORT }}" +api_key = { id = "{{ OPENTALK_CTRL_SERVICE_API_KEY_ID }}", secret = "{{ OPENTALK_CTRL_SERVICE_API_SECRET }}" } -[rabbitmq] -uri = "amqp://guest:guest@rabbit/%2F" -queue = "{{ OPENTALK_RABBIT_QUEUE }}" +[http] +port = {{ OPENTALK_RECORDER_HTTP_PORT }} +api_keys = [{ id = "{{ OPENTALK_RECORDER_API_KEY_ID }}", secret = "{{ OPENTALK_RECORDER_API_SECRET }}" }] diff --git a/roles/web-app-opentalk/vars/main.yml b/roles/web-app-opentalk/vars/main.yml index a4625936b4..4a9e652102 100644 --- a/roles/web-app-opentalk/vars/main.yml +++ b/roles/web-app-opentalk/vars/main.yml @@ -12,6 +12,8 @@ entity_name: "{{ application_id | get_entity_name }}" OPENTALK_CTRL_CONTAINER: "{{ lookup('config', application_id, 'services.controller.name') }}" OPENTALK_CTRL_HTTP_PORT: "{{ lookup('config', application_id, 'services.controller.ports.local.http') }}" OPENTALK_CTRL_INTERNAL_PORT: "{{ lookup('config', application_id, 'services.controller.ports.internal.http') }}" +OPENTALK_CTRL_SERVICE_API_KEY_ID: "controller" +OPENTALK_CTRL_SERVICE_API_SECRET: "{{ lookup('config', application_id, 'secrets.credentials.service_api_secret') }}" OPENTALK_FRONTEND_CONTAINER: "{{ lookup('config', application_id, 'services.opentalk.name') }}" OPENTALK_FRONTEND_HTTP_PORT: "{{ lookup('config', application_id, 'services.opentalk.ports.local.http') }}" @@ -34,11 +36,11 @@ OPENTALK_LIVEKIT_API_SECRET: "{{ lookup('config', application_id, 'secrets.crede OPENTALK_OBJSTORE_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, lookup('objstore', application_id, 'engine')) }}" OPENTALK_RABBIT_CONTAINER: "{{ lookup('config', application_id, 'services.rabbit.name') }}" -OPENTALK_RABBIT_QUEUE: "opentalk_recorder" OPENTALK_RECORDER_CONTAINER: "{{ lookup('config', application_id, 'services.recorder.name') }}" -OPENTALK_RECORDER_OIDC_CLIENT_ID: "opentalk-recorder" -OPENTALK_RECORDER_OIDC_CLIENT_SECRET: "{{ lookup('config', application_id, 'secrets.credentials.recorder_oidc_client_secret') }}" +OPENTALK_RECORDER_HTTP_PORT: "{{ lookup('config', application_id, 'services.recorder.ports.internal.http') }}" +OPENTALK_RECORDER_API_KEY_ID: "recorder" +OPENTALK_RECORDER_API_SECRET: "{{ lookup('config', application_id, 'secrets.credentials.recorder_api_secret') }}" OPENTALK_KEYCLOAK_BASE_URL: "{{ lookup('tls', 'web-app-keycloak', 'url.base') | regex_replace('/+$','') }}" OPENTALK_KEYCLOAK_CONTAINER_ADDRESS: "{{ lookup('container_address', 'web-app-keycloak', 'keycloak') }}" diff --git a/roles/web-app-peertube/templates/proxy.conf.j2 b/roles/web-app-peertube/templates/proxy.conf.j2 index 1049d7bfdb..b8a8a94803 100644 --- a/roles/web-app-peertube/templates/proxy.conf.j2 +++ b/roles/web-app-peertube/templates/proxy.conf.j2 @@ -51,4 +51,6 @@ server { try_files /dev/null {{ webserver_websocket_location }}; } + + {% include 'roles/web-app-prometheus/templates/nginx/locations.conf.j2' %} } \ No newline at end of file diff --git a/roles/web-app-pixelfed/meta/services.yml b/roles/web-app-pixelfed/meta/services.yml index 4bf143436b..10fa557e0a 100644 --- a/roles/web-app-pixelfed/meta/services.yml +++ b/roles/web-app-pixelfed/meta/services.yml @@ -49,7 +49,7 @@ pixelfed: shared: true enabled: true # nocheck: dynamic-flag image: zknt/pixelfed - version: "20260917" + version: "20261008" name: pixelfed min_storage: 588MB backup: diff --git a/roles/web-app-prometheus/files/playwright/playwright.spec.js b/roles/web-app-prometheus/files/playwright/playwright.spec.js index c3a8ecf077..8ed526e48c 100644 --- a/roles/web-app-prometheus/files/playwright/playwright.spec.js +++ b/roles/web-app-prometheus/files/playwright/playwright.spec.js @@ -211,7 +211,7 @@ test("prometheus: biber is denied access after sso login", async ({ browser }) = // ----------------------------------------------------------------------------- const prometheusTargetRoles = (() => { - const raw = process.env.PROMETHEUS_TARGET_ROLES_JSON || "[]"; + const raw = decodeDotenvQuotedValue(process.env.PROMETHEUS_TARGET_ROLES_JSON || "[]"); try { const parsed = JSON.parse(raw); return Array.isArray(parsed) ? parsed : []; @@ -220,7 +220,7 @@ const prometheusTargetRoles = (() => { } })(); -test("prometheus scrape: every consumer role reports up=1", async ({ page }) => { +test("prometheus scrape: every consumer role reports up=1 and passes its probe", async ({ page }) => { test.skip(prometheusTargetRoles.length === 0, "no prometheus consumer roles in inventory"); const expectedPrometheusBaseUrl = prometheusBaseUrl.replace(/\/$/, ""); @@ -279,6 +279,26 @@ test("prometheus scrape: every consumer role reports up=1", async ({ page }) => failures, `prometheus scrape failures:\n - ${failures.join("\n - ")}` ).toEqual([]); + + const probeUrl = `${expectedPrometheusBaseUrl}/api/v1/query?query=${encodeURIComponent('probe_success{job="blackbox-healthz"}')}`; + await expect + .poll( + async () => { + const response = await page.request.get(probeUrl, { ignoreHTTPSErrors: true }); + const probes = response.ok() ? (await response.json())?.data?.result || [] : []; + return prometheusTargetRoles + .filter((target) => { + const own = probes.filter((entry) => entry?.metric?.app === target.id); + return own.length === 0 || own.some((entry) => entry?.value?.[1] !== "1"); + }) + .map((target) => target.id); + }, + { + timeout: resolveTimeout(120_000), + message: "roles whose /healthz/ready probe is missing or failing (probe_success != 1)", + }, + ) + .toEqual([]); }); // Persona scenarios. diff --git a/roles/web-app-prometheus/meta/services.yml b/roles/web-app-prometheus/meta/services.yml index cc973d1273..462bb19bc7 100644 --- a/roles/web-app-prometheus/meta/services.yml +++ b/roles/web-app-prometheus/meta/services.yml @@ -94,7 +94,7 @@ blackbox-exporter: flavor: wget path: -/healthy image: prom/blackbox-exporter - version: v0.28.0 + version: v0.29.0 name: prometheus-blackbox cpus: "0.1" mem_reservation: 16m @@ -106,7 +106,7 @@ blackbox-exporter: http: 9115 cadvisor: image: gcr.io/cadvisor/cadvisor - version: v0.52.1 + version: v0.55.1 update: type: registry_tags image: gcr.io/cadvisor/cadvisor diff --git a/roles/web-app-prometheus/meta/volumes.yml b/roles/web-app-prometheus/meta/volumes.yml index 62de8fec3b..509b5cf68e 100644 --- a/roles/web-app-prometheus/meta/volumes.yml +++ b/roles/web-app-prometheus/meta/volumes.yml @@ -75,11 +75,11 @@ host_sys: host_var_lib_docker: type: bind - source: "/var/lib/docker/" + source: &docker_root "{{ prometheus_docker_info.stdout }}" read_only: true mounts: - service: cadvisor - target: /var/lib/docker + target: *docker_root host_dev_disk: type: bind diff --git a/roles/web-app-prometheus/tasks/00_core.yml b/roles/web-app-prometheus/tasks/00_core.yml index 1330796833..5ea27032c9 100644 --- a/roles/web-app-prometheus/tasks/00_core.yml +++ b/roles/web-app-prometheus/tasks/00_core.yml @@ -6,6 +6,19 @@ vars: mcp_adapter_instance_dir: "{{ PROMETHEUS_MCP_INSTANCE_DIR }}" when: PROMETHEUS_MCP_ENABLED | bool + +- name: "🧩 Load the container CLI the data root probe calls" + include_role: + name: sys-svc-container + public: false + when: run_once_sys_svc_container is not defined + +- name: "🔎 Read the docker data root cAdvisor has to bind" + ansible.builtin.command: container info --format '{{ "{{" }}.DockerRootDir{{ "}}" }}' + register: prometheus_docker_info + changed_when: false + delegate_to: "{{ STACK_HOST }}" + - name: "🧩 load docker and proxy for '{{ application_id }}'" include_role: name: sys-stk-backend diff --git a/roles/web-app-prometheus/templates/configuration/blackbox.yml.j2 b/roles/web-app-prometheus/templates/configuration/blackbox.yml.j2 index b8c78938dc..48147594e0 100644 --- a/roles/web-app-prometheus/templates/configuration/blackbox.yml.j2 +++ b/roles/web-app-prometheus/templates/configuration/blackbox.yml.j2 @@ -24,7 +24,7 @@ modules: method: GET follow_redirects: false fail_if_ssl: false - fail_if_not_ssl: {{ lookup('tls', application_id, 'enabled') | bool | lower }} + fail_if_not_ssl: false tls_config: - insecure_skip_verify: {{ not (lookup('tls', application_id, 'enabled') | bool) }} + insecure_skip_verify: {{ ((TLS_MODE | lower) == 'self_signed' and not lookup('ca_injected', application_id)) | lower }} preferred_ip_protocol: "ip4" diff --git a/roles/web-app-prometheus/templates/configuration/prometheus.yml.j2 b/roles/web-app-prometheus/templates/configuration/prometheus.yml.j2 index 35cd730a20..86ea8e71aa 100644 --- a/roles/web-app-prometheus/templates/configuration/prometheus.yml.j2 +++ b/roles/web-app-prometheus/templates/configuration/prometheus.yml.j2 @@ -41,20 +41,21 @@ scrape_configs: {% endfor %} -{% set canonical_map = lookup('applications') | canonical_domains_map(DOMAIN_PRIMARY) %} +{% set canonical_map = lookup('domains') %} +{% set probed_roles = lookup('roles_with_service', 'prometheus') | map(attribute='id') | list %} - job_name: "blackbox-healthz" metrics_path: /probe params: module: [http_ready] static_configs: {% for _application_id in CURRENT_PLAY_APPLICATIONS | list | sort %} -{% if _application_id != application_id %} +{% if _application_id in probed_roles %} {% set domains_raw = canonical_map.get(_application_id, []) %} {% set canonical_probe_domains = (domains_raw.values() | list) if (domains_raw is mapping) else domains_raw %} {% if canonical_probe_domains | length > 0 %} - targets: {% for domain in canonical_probe_domains %} - - "{{ lookup('tls', application_id, 'protocols.web') }}://{{ domain }}/healthz/ready" + - "{{ lookup('tls', domain, 'url.base') }}healthz/ready" {% endfor %} labels: app: "{{ _application_id }}" diff --git a/roles/web-app-prometheus/templates/nginx/healthz.conf.j2 b/roles/web-app-prometheus/templates/nginx/healthz.conf.j2 index 01e6864639..ef5282c46f 100644 --- a/roles/web-app-prometheus/templates/nginx/healthz.conf.j2 +++ b/roles/web-app-prometheus/templates/nginx/healthz.conf.j2 @@ -49,6 +49,7 @@ } {% set prometheus_backend = lookup('proxy_pass', application_id, proxy_service_key | default(application_id | get_entity_name), 'http', tail='/', local_port=http_port, internal_port=proxy_internal_port | default('')) %} +{% set prometheus_ready_backend = lookup('proxy_pass', application_id, proxy_service_key | default(application_id | get_entity_name), 'http', tail='/' ~ lookup('config', application_id, 'services.prometheus.ready_path', ''), local_port=http_port, internal_port=proxy_internal_port | default('')) %} location = /_live_probe { internal; {{ prometheus_backend }} @@ -60,7 +61,7 @@ location = /healthz/ready { access_log off; - {{ prometheus_backend }} + {{ prometheus_ready_backend }} proxy_set_header Host $host; proxy_connect_timeout 3s; proxy_read_timeout 5s; diff --git a/roles/web-app-seaweedfs/meta/services.yml b/roles/web-app-seaweedfs/meta/services.yml index 20906c4bb6..2ba8b58900 100644 --- a/roles/web-app-seaweedfs/meta/services.yml +++ b/roles/web-app-seaweedfs/meta/services.yml @@ -27,18 +27,24 @@ sso: ldap: enabled: false shared: false +# nocheck: variants-coverage — the onion gate is a hard invariant; no variant may force this consumer on a tor node. +# nocheck: bond-baseline — same reason: variant 0 must not pin this consumer on. logout: bond: 1 - enabled: "{{ 'web-svc-logout' in group_names }}" - shared: "{{ 'web-svc-logout' in group_names }}" + enabled: "{{ ('web-svc-logout' in group_names) and ('svc-net-tor' not in group_names) }}" + shared: "{{ ('web-svc-logout' in group_names) and ('svc-net-tor' not in group_names) }}" +# nocheck: variants-coverage — the onion gate is a hard invariant; no variant may force this consumer on a tor node. +# nocheck: bond-baseline — same reason: variant 0 must not pin this consumer on. dashboard: bond: 1 - enabled: "{{ 'web-app-dashboard' in group_names }}" - shared: "{{ 'web-app-dashboard' in group_names }}" + enabled: "{{ ('web-app-dashboard' in group_names) and ('svc-net-tor' not in group_names) }}" + shared: "{{ ('web-app-dashboard' in group_names) and ('svc-net-tor' not in group_names) }}" +# nocheck: variants-coverage — the onion gate is a hard invariant; no variant may force this consumer on a tor node. +# nocheck: bond-baseline — same reason: variant 0 must not pin this consumer on. prometheus: bond: 1 - enabled: "{{ 'web-app-prometheus' in group_names }}" - shared: "{{ 'web-app-prometheus' in group_names }}" + enabled: "{{ ('web-app-prometheus' in group_names) and ('svc-net-tor' not in group_names) }}" + shared: "{{ ('web-app-prometheus' in group_names) and ('svc-net-tor' not in group_names) }}" # nocheck: playwright-service-flag — central object-store provider entity seaweedfs: healthcheck: diff --git a/roles/web-app-seaweedfs/meta/variants.yml b/roles/web-app-seaweedfs/meta/variants.yml index 77e2c251f1..678afaac86 100644 --- a/roles/web-app-seaweedfs/meta/variants.yml +++ b/roles/web-app-seaweedfs/meta/variants.yml @@ -9,14 +9,14 @@ enabled: true shared: true logout: - enabled: true - shared: true + enabled: "{{ 'svc-net-tor' not in group_names }}" + shared: "{{ 'svc-net-tor' not in group_names }}" dashboard: - enabled: true - shared: true + enabled: "{{ 'svc-net-tor' not in group_names }}" + shared: "{{ 'svc-net-tor' not in group_names }}" prometheus: - enabled: true - shared: true + enabled: "{{ 'svc-net-tor' not in group_names }}" + shared: "{{ 'svc-net-tor' not in group_names }}" - services: container_backup: enabled: false diff --git a/roles/web-app-semaphore/meta/services.yml b/roles/web-app-semaphore/meta/services.yml index f12e6790d8..523e6513bc 100644 --- a/roles/web-app-semaphore/meta/services.yml +++ b/roles/web-app-semaphore/meta/services.yml @@ -55,7 +55,7 @@ semaphore: pids_limit: 1024 min_storage: 530MB image: semaphoreui/semaphore - version: "v2.19.14" + version: "v2.19.16" backup: no_stop_required: true name: semaphore diff --git a/roles/web-app-socialhome/meta/services.yml b/roles/web-app-socialhome/meta/services.yml index b2252ea28f..43f68c9d7a 100644 --- a/roles/web-app-socialhome/meta/services.yml +++ b/roles/web-app-socialhome/meta/services.yml @@ -13,7 +13,7 @@ socialhome: # nocheck: default-placement-manager embedded sqlite in a node-local volume; no clustered storage placement: manager image: ghcr.io/social-home-io/socialhome - version: "2026.10.6" + version: "2026.10.8" ports: local: http: 8089 diff --git a/roles/web-app-suitecrm/README.md b/roles/web-app-suitecrm/README.md index 70fc57dce9..8091a52906 100644 --- a/roles/web-app-suitecrm/README.md +++ b/roles/web-app-suitecrm/README.md @@ -27,6 +27,7 @@ flowchart LR dep_svc_bkp_volume_2_local["svc-bkp-volume-2-local 💻"] dep_svc_db_mariadb["svc-db-mariadb 🐳🐝"] dep_svc_db_openldap["svc-db-openldap 🐳🐝"] + dep_svc_db_redis["svc-db-redis 🐳🐝"] dep_svc_net_tor["svc-net-tor 🐳🐝"] dep_web_app_dashboard["web-app-dashboard 🐳🐝"] dep_web_app_keycloak["web-app-keycloak 🐳🐝"] @@ -44,6 +45,7 @@ flowchart LR svc_matomo["matomo"] svc_email["email"] svc_mariadb["mariadb"] + svc_redis["redis"] svc_suitecrm["suitecrm"] svc_css["css"] svc_prometheus["prometheus"] @@ -53,6 +55,7 @@ flowchart LR dep_svc_bkp_volume_2_local -. "0..1" .-> svc_container_backup dep_svc_db_mariadb -. "0..1" .-> svc_mariadb dep_svc_db_openldap -. "0..1" .-> svc_ldap + dep_svc_db_redis -. "0..1" .-> svc_redis dep_svc_net_tor -. "0..1" .-> svc_tor dep_web_app_dashboard -. "0..1" .-> svc_dashboard dep_web_app_keycloak -. "0..1" .-> svc_sso diff --git a/roles/web-app-suitecrm/files/Dockerfile b/roles/web-app-suitecrm/files/Dockerfile index 681672774b..08c8f95e71 100644 --- a/roles/web-app-suitecrm/files/Dockerfile +++ b/roles/web-app-suitecrm/files/Dockerfile @@ -5,6 +5,7 @@ FROM ${SUITECRM_BASE_IMAGE}:${SUITECRM_BASE_VERSION} AS base ARG SUITECRM_APP_DIR ARG SUITECRM_PHP_MEMORY_LIMIT +ARG SUITECRM_PHPREDIS_VERSION RUN rm -rf /var/lib/apt/lists/* \ && apt-get -o Acquire::Retries=3 update && apt-get -o Acquire::Retries=3 install -y \ @@ -32,6 +33,10 @@ RUN rm -rf /var/lib/apt/lists/* \ ldap \ && rm -rf /var/lib/apt/lists/* +RUN : "${SUITECRM_PHPREDIS_VERSION:?}" \ + && pecl install "redis-${SUITECRM_PHPREDIS_VERSION}" \ + && docker-php-ext-enable redis + RUN : "${SUITECRM_PHP_MEMORY_LIMIT:?}" && { \ echo 'file_uploads = On'; \ echo 'upload_max_filesize = 32M'; \ diff --git a/roles/web-app-suitecrm/files/shell/docker-entrypoint.sh b/roles/web-app-suitecrm/files/shell/docker-entrypoint.sh index 32fc38fdd1..2c2d5c954a 100644 --- a/roles/web-app-suitecrm/files/shell/docker-entrypoint.sh +++ b/roles/web-app-suitecrm/files/shell/docker-entrypoint.sh @@ -129,6 +129,8 @@ if [ "$_have_lock" = "1" ]; then # cannot write into root-owned cache dirs -> permanent 500 without this. chown -R "$WEB_USER:$WEB_GROUP" "${APP_DIR}/cache" "${APP_DIR}/public/legacy/cache" 2>/dev/null || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error + chown -R "$WEB_USER:$WEB_GROUP" "${APP_DIR}/logs" + rmdir "$BOOT_LOCK" 2>/dev/null || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error trap - EXIT TERM INT else diff --git a/roles/web-app-suitecrm/meta/services.yml b/roles/web-app-suitecrm/meta/services.yml index 68c73b211d..042eb5b315 100644 --- a/roles/web-app-suitecrm/meta/services.yml +++ b/roles/web-app-suitecrm/meta/services.yml @@ -29,6 +29,17 @@ mariadb: bond: 1 enabled: true # nocheck: dynamic-flag shared: "{{ 'svc-db-mariadb' in group_names }}" +# nocheck: playwright-service-flag — session store behind every request, no Playwright surface of its own +redis: + bond: 1 + backup: + disabled: true + enabled: true # nocheck: dynamic-flag + shared: "{{ 'svc-db-redis' in group_names }}" + cpus: "0.25" + mem_reservation: 128m + mem_limit: 256m + pids_limit: 256 # nocheck: playwright-service-flag — self-provider entry; test_env_services_match.py:28-32 grants the forbidden-self-gate exemption suitecrm: healthcheck: @@ -49,12 +60,16 @@ suitecrm: version: 8.2-apache custom: true app_version: 8.9.1 + phpredis_version: 6.3.0 update: - key: app_version - type: git_tags - repository: https://github.com/salesagility/SuiteCRM-Core.git - match: "v" - strip: true + - key: app_version + type: git_tags + repository: https://github.com/salesagility/SuiteCRM-Core.git + match: "v" + strip: true + - key: phpredis_version + type: git_tags + repository: https://github.com/phpredis/phpredis.git name: suitecrm min_storage: 376MB cpus: 1.5 diff --git a/roles/web-app-suitecrm/meta/variants.yml b/roles/web-app-suitecrm/meta/variants.yml index 6353170e71..23ed53e8a9 100644 --- a/roles/web-app-suitecrm/meta/variants.yml +++ b/roles/web-app-suitecrm/meta/variants.yml @@ -24,6 +24,8 @@ shared: true mariadb: shared: true + redis: + shared: true matomo: enabled: true shared: true @@ -56,6 +58,8 @@ shared: false # nocheck: variants-static-override backup shared stays literally true mariadb: shared: false # nocheck: variants-static-override backup shared stays literally true + redis: + shared: false matomo: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true diff --git a/roles/web-app-suitecrm/tasks/01_manager_ops.yml b/roles/web-app-suitecrm/tasks/01_manager_ops.yml index 39f5fdcad8..e1801b6936 100644 --- a/roles/web-app-suitecrm/tasks/01_manager_ops.yml +++ b/roles/web-app-suitecrm/tasks/01_manager_ops.yml @@ -24,3 +24,20 @@ - name: "🐳 Docker Compose Up for '{{ application_id }}'" meta: flush_handlers + +- name: "⏳ Wait until the SuiteCRM container is healthy" + shell: > + container inspect --type container --format '{% raw %}{{.State.Health.Status}}{% endraw %}' {{ SUITECRM_CONTAINER_ADDRESS }} + register: suitecrm_health + changed_when: false + until: suitecrm_health.stdout.strip() == "healthy" + retries: 300 + delay: 5 + +- name: "🔎 List SuiteCRM log paths the web user cannot write" + shell: > + container exec --user {{ SUITECRM_WEB_USER }} {{ SUITECRM_CONTAINER_ADDRESS }} + find {{ SUITECRM_APP_DIR }}/logs ! -writable + register: suitecrm_unwritable_logs + changed_when: false + failed_when: suitecrm_unwritable_logs.rc != 0 or suitecrm_unwritable_logs.stdout | length > 0 diff --git a/roles/web-app-suitecrm/templates/compose.yml.j2 b/roles/web-app-suitecrm/templates/compose.yml.j2 index 62057023e5..a4a9f433e8 100644 --- a/roles/web-app-suitecrm/templates/compose.yml.j2 +++ b/roles/web-app-suitecrm/templates/compose.yml.j2 @@ -6,6 +6,7 @@ SUITECRM_BASE_IMAGE: "{{ SUITECRM_BASE_IMAGE }}" SUITECRM_BASE_VERSION: "{{ SUITECRM_BASE_VERSION }}" SUITECRM_APP_VERSION: "{{ SUITECRM_APP_VERSION }}" + SUITECRM_PHPREDIS_VERSION: "{{ SUITECRM_PHPREDIS_VERSION }}" SUITECRM_ENTRYPOINT_SCRIPT_HOST_REL: "{{ SUITECRM_ENTRYPOINT_SCRIPT_HOST_REL }}" SUITECRM_ENTRYPOINT_SCRIPT_DOCKER: "{{ SUITECRM_ENTRYPOINT_SCRIPT_DOCKER }}" SUITECRM_LDAP_EXTENSION_DIR: "{{ SUITECRM_LDAP_EXTENSION_DIR }}" diff --git a/roles/web-app-suitecrm/templates/env.j2 b/roles/web-app-suitecrm/templates/env.j2 index 826cb31386..acc107ad15 100644 --- a/roles/web-app-suitecrm/templates/env.j2 +++ b/roles/web-app-suitecrm/templates/env.j2 @@ -21,6 +21,8 @@ SUITECRM_ADMIN_EMAIL={{ lookup('users', 'administrator').email }} SUITECRM_URL={{ SUITECRM_URL }} +SUITECRM_SESSION_SAVE_PATH={{ lookup('engine', 'redis', application_id, 'session_path') }} + {% if SUITECRM_SSO_ENABLED | bool %} AUTH_TYPE=saml diff --git a/roles/web-app-suitecrm/templates/php.ini.j2 b/roles/web-app-suitecrm/templates/php.ini.j2 index e818dbc83e..1ff9b031e4 100644 --- a/roles/web-app-suitecrm/templates/php.ini.j2 +++ b/roles/web-app-suitecrm/templates/php.ini.j2 @@ -3,5 +3,7 @@ display_startup_errors = Off log_errors = On error_reporting = E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED -session.save_handler = files -session.save_path = "{{ SUITECRM_APP_DIR }}/tmp" +session.save_handler = redis +session.save_path = ${SUITECRM_SESSION_SAVE_PATH} +redis.session.locking_enabled = 1 +redis.session.lock_retries = -1 diff --git a/roles/web-app-suitecrm/vars/main.yml b/roles/web-app-suitecrm/vars/main.yml index fca35e9cd1..aaf9602ea6 100644 --- a/roles/web-app-suitecrm/vars/main.yml +++ b/roles/web-app-suitecrm/vars/main.yml @@ -11,8 +11,10 @@ SUITECRM_PHP_CONFIG_HOST: "{{ [ lookup('container', application_id, 'directories SUITECRM_BASE_IMAGE: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.image') }}" SUITECRM_BASE_VERSION: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.version') }}" SUITECRM_APP_VERSION: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.app_version') }}" +SUITECRM_PHPREDIS_VERSION: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.phpredis_version') }}" SUITECRM_CONTAINER: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.name') }}" +SUITECRM_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, entity_name) }}" SUITECRM_SERVICE: "{{ entity_name }}" SUITECRM_URL: "{{ lookup('tls', application_id, 'url.base') }}" diff --git a/roles/web-app-wordpress/meta/addons/mcp-adapter.yml b/roles/web-app-wordpress/meta/addons/mcp-adapter.yml index 60fd5c6322..a56aa4270f 100644 --- a/roles/web-app-wordpress/meta/addons/mcp-adapter.yml +++ b/roles/web-app-wordpress/meta/addons/mcp-adapter.yml @@ -3,7 +3,7 @@ enabled: "{{ lookup('config', 'web-app-wordpress', 'mcp.enabled') | bool }}" required: true mechanism: plugin source: upstream -version: v0.5.0 +version: v0.7.0 update: monitored: true catalog: github-releases diff --git a/roles/web-app-wordpress/meta/services.yml b/roles/web-app-wordpress/meta/services.yml index cdc0f4ada9..ed744d0ce3 100644 --- a/roles/web-app-wordpress/meta/services.yml +++ b/roles/web-app-wordpress/meta/services.yml @@ -47,7 +47,7 @@ wordpress: enabled: true swarm: enabled: true - version: 7.1.2 + version: 7.1.3 image: wordpress custom: true name: wordpress diff --git a/roles/web-svc-collabora/meta/services.yml b/roles/web-svc-collabora/meta/services.yml index f36cc05eba..517f7fccfe 100644 --- a/roles/web-svc-collabora/meta/services.yml +++ b/roles/web-svc-collabora/meta/services.yml @@ -25,7 +25,7 @@ collabora: enabled: true shared: true image: collabora/code - version: "26.04.4.2.1" + version: "26.04.5.1.1" name: collabora min_storage: 734MB cpus: 2 diff --git a/roles/web-svc-coturn/meta/services.yml b/roles/web-svc-coturn/meta/services.yml index 46fd83e125..26f1a9818f 100644 --- a/roles/web-svc-coturn/meta/services.yml +++ b/roles/web-svc-coturn/meta/services.yml @@ -36,21 +36,23 @@ gateway: mem_reservation: 256m mem_limit: 512m pids_limit: 256 -# nocheck: dynamic-flag +# nocheck: dynamic-flag coturn runs with user_auth_enabled false, so it keeps no credential store to back; the entry stays literal until auth is switched on and no template references redis today. redis: backup: disabled: true enabled: false shared: "{{ 'svc-db-redis' in group_names }}" +# nocheck: variants-coverage — the tor conjunct is the clearnet-variant-tor invariant below, so no variant may pin the true polarity on an onion node +# nocheck: bond-baseline — same reason: variant 0 must not pin the scrape consumer on prometheus: bond: 1 - enabled: "{{ 'web-app-prometheus' in group_names }}" - shared: "{{ 'web-app-prometheus' in group_names }}" + enabled: "{{ ('web-app-prometheus' in group_names) and ('svc-net-tor' not in group_names) }}" + shared: "{{ ('web-app-prometheus' in group_names) and ('svc-net-tor' not in group_names) }}" +# nocheck: clearnet-variant-tor — STUN/TURN on UDP plus a 20000-port relay range, which no onion descriptor can publish; the only HTTP is a gateway returning a plaintext OK. No dashboard, logout, css or matomo block and no Playwright spec, so an onion round claims no visitable surface for it. Its one consumer declaration, prometheus, carries the tor gate. tor: - enabled: false # nocheck: dynamic-flag - shared: false # nocheck: dynamic-flag -# nocheck: dynamic-flag + enabled: false # nocheck: dynamic-flag no group can turn this on: see the clearnet-variant-tor reason above + shared: false # nocheck: dynamic-flag same # nocheck: playwright-service-flag, dynamic-flag infrastructure backup consumer container_backup: # nocheck: bond-baseline backup host joins outside the variant topology bond: 1 diff --git a/roles/web-svc-coturn/meta/variants.yml b/roles/web-svc-coturn/meta/variants.yml index c3cf254fc1..1297a4474f 100644 --- a/roles/web-svc-coturn/meta/variants.yml +++ b/roles/web-svc-coturn/meta/variants.yml @@ -9,8 +9,8 @@ container_backup: enabled: true prometheus: - enabled: true - shared: true + enabled: "{{ 'svc-net-tor' not in group_names }}" + shared: "{{ 'svc-net-tor' not in group_names }}" redis: shared: true tor: diff --git a/roles/web-svc-mirror/meta/services.yml b/roles/web-svc-mirror/meta/services.yml index 398a51e444..2540a50b14 100644 --- a/roles/web-svc-mirror/meta/services.yml +++ b/roles/web-svc-mirror/meta/services.yml @@ -22,6 +22,8 @@ prometheus: bond: 1 enabled: "{{ 'web-app-prometheus' in group_names }}" shared: "{{ 'web-app-prometheus' in group_names }}" + # nocheck: prometheus-scrape + scrape: false # nocheck: playwright-service-flag # nocheck: variants-coverage — sso-variant-tor requires the onion on in every variant, so the false polarity has no variant left to live in tor: diff --git a/roles/web-svc-xmpp/meta/services.yml b/roles/web-svc-xmpp/meta/services.yml index fa9d91822b..0096bcf9dd 100644 --- a/roles/web-svc-xmpp/meta/services.yml +++ b/roles/web-svc-xmpp/meta/services.yml @@ -7,6 +7,7 @@ prometheus: bond: 1 enabled: "{{ 'web-app-prometheus' in group_names }}" shared: "{{ 'web-app-prometheus' in group_names }}" + ready_path: admin/ sso: bond: 1 enabled: "{{ 'web-app-keycloak' in group_names }}" diff --git a/tests/integration/roles/svc-bkp-remote-2-local/test_ssh_wrapper_rsync_e2e.py b/tests/integration/roles/svc-bkp-remote-2-local/test_ssh_wrapper_rsync_e2e.py index f7269a5a3c..e97744353b 100644 --- a/tests/integration/roles/svc-bkp-remote-2-local/test_ssh_wrapper_rsync_e2e.py +++ b/tests/integration/roles/svc-bkp-remote-2-local/test_ssh_wrapper_rsync_e2e.py @@ -22,7 +22,7 @@ import tempfile import unittest from pathlib import Path -from jinja2 import Template +from jinja2 import Template, select_autoescape from utils.cache.files import read_text @@ -62,7 +62,10 @@ class TestSshWrapperRsyncE2E(unittest.TestCase): (self.version_dir / "data" / "file2.txt").write_text("second") self.wrapper = self.work / "wrapper.sh" - rendered = Template(read_text(str(WRAPPER_TEMPLATE))).render( + rendered = Template( + read_text(str(WRAPPER_TEMPLATE)), + autoescape=select_autoescape(default_for_string=False), + ).render( DIR_BACKUPS=str(self.backups), BACKUP_REPOSITORIES=[BACKUP_TYPE], ) diff --git a/tests/integration/roles/svc-net-tor/test_container_dns_wiring.py b/tests/integration/roles/svc-net-tor/test_container_dns_wiring.py index 4ed72e9dd0..e69326de26 100644 --- a/tests/integration/roles/svc-net-tor/test_container_dns_wiring.py +++ b/tests/integration/roles/svc-net-tor/test_container_dns_wiring.py @@ -1,7 +1,7 @@ import unittest from ansible.module_utils.parsing.convert_bool import boolean as ansible_boolean -from jinja2 import Environment, FileSystemLoader +from jinja2 import Environment, FileSystemLoader, select_autoescape from tests.integration.roles import PROJECT_ROOT from utils.cache.files import read_text @@ -37,7 +37,7 @@ def _render_dnsmasq(**overrides): variables.update(overrides) env = Environment( loader=FileSystemLoader(str(PROJECT_ROOT)), - autoescape=False, # noqa: S701 - dnsmasq config, html escaping would corrupt it + autoescape=select_autoescape(), ) template = env.get_template("roles/svc-net-tor/templates/dnsmasq-tor-onion.conf.j2") return template.render(**variables) @@ -146,7 +146,7 @@ class TestStaticBindSurvivesBoot(unittest.TestCase): self.assertLess(names.index(DROPIN_BLOCK), names.index(START_TASK)) reload_expression = start["ansible.builtin.systemd"]["daemon_reload"] - env = Environment(autoescape=False) # noqa: S701 - renders a boolean, not markup + env = Environment(autoescape=select_autoescape(default_for_string=False)) env.filters["bool"] = ansible_boolean env.tests["changed"] = lambda result: bool(result.get("changed", False)) @@ -192,7 +192,7 @@ class TestHostResolver(unittest.TestCase): task = next(t for t in tasks if t.get("name") == RESOLV_TASK) env = Environment( loader=FileSystemLoader(str(PROJECT_ROOT)), - autoescape=False, # noqa: S701 - resolv.conf, html escaping would corrupt it + autoescape=select_autoescape(), ) template = env.get_template( f"roles/svc-net-tor/templates/{task['ansible.builtin.template']['src']}" diff --git a/tests/lint/ansible/jinja/test_shell_templates_are_valid.py b/tests/lint/ansible/jinja/test_shell_templates_are_valid.py index 921e159c9e..be0ac4d734 100644 --- a/tests/lint/ansible/jinja/test_shell_templates_are_valid.py +++ b/tests/lint/ansible/jinja/test_shell_templates_are_valid.py @@ -100,7 +100,7 @@ class TestShellTemplatesAreValid(unittest.TestCase): environment = jinja2.Environment( undefined=_Placeholder, keep_trailing_newline=True, - autoescape=False, # noqa: S701 shell, not markup + autoescape=jinja2.select_autoescape(default_for_string=False), ) environment.filters = _PassthroughFilters(environment.filters) environment.filters["quote"] = shlex.quote diff --git a/tests/lint/ansible/roles/meta/test_clearnet_role_forbids_variant_tor.py b/tests/lint/ansible/roles/meta/test_clearnet_role_forbids_variant_tor.py new file mode 100644 index 0000000000..31004faeb9 --- /dev/null +++ b/tests/lint/ansible/roles/meta/test_clearnet_role_forbids_variant_tor.py @@ -0,0 +1,145 @@ +"""Lint guard: a variant binding a clearnet-only role must not pin the onion on. + +A role whose ``meta/services.yml`` pins ``tor.enabled`` to a literal false rides +no node onion, so on a tor deployment its surface lives at a clearnet host that +no onion browser reaches, and the dashboard's own +``frame-src 'self' http://*.`` forbids embedding it. A variant that +enables such a role and pins ``services.tor.enabled: true`` therefore declares a +combination the deployment cannot hold: the round advertises a tile, a tracker, +a stylesheet and a scrape target for a surface that is not there. + +``test_sso_variant_requires_tor`` states the complementary half - every variant +of a role that has an onion MUST pin it on - and exempts the clearnet-only role +itself. This rule covers the consumers it does not: the variants that bind one. + +The project already applies the rule by hand. ``web-app-nextcloud``'s variants +head carries "variant 8 pairs PeerTube, which is clearnet-only since 8ffb1f567, +so that round cannot pin the onion on". + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: clearnet-variant-tor`` in the CLEARNET role's + ``meta/services.yml``, which exempts it everywhere: a relay with no browser + surface of its own carries no tile and no injected asset, so an onion round + may deploy it without claiming anything about it. +* the same marker in a consumer's ``meta/variants.yml`` for a case that is + sound only there. + +The marker belongs on the bound role rather than the consumer whenever the +reason is the role's own shape, because a consumer-side marker would also +silence the pairings of every other clearnet role in the same file. +""" + +from __future__ import annotations + +import unittest +from typing import TYPE_CHECKING, Any + +import yaml + +from utils.annotations.suppress import line_has_rule +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_str +from utils.roles.entity.name import get_entity_name +from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_META_VARIANTS + +from . import PROJECT_ROOT + +if TYPE_CHECKING: + from pathlib import Path + +ROLES_DIR = PROJECT_ROOT / "roles" +_RULE = "clearnet-variant-tor" + + +def _load_yaml(path: Path) -> Any: + if not path.is_file(): + return None + try: + text = read_text(str(path)) + except UnicodeDecodeError: + return None + if not text.strip(): + return None + try: + return load_yaml_str(text) + except yaml.YAMLError: + return None + + +def _suppressed(paths: tuple[Path, ...]) -> bool: + for path in paths: + if not path.is_file(): + continue + if any( + line_has_rule(line, _RULE) for line in read_text(str(path)).splitlines() + ): + return True + return False + + +def _flag(variant: Any, service: str) -> Any: + services = variant.get("services") if isinstance(variant, dict) else None + entry = services.get(service) if isinstance(services, dict) else None + return entry.get("enabled") if isinstance(entry, dict) else None + + +def clearnet_only_keys() -> dict[str, str]: + """Service key to role id, for every clearnet-only role the rule covers. + + Returns: + The key a consumer's variant would bind it under, mapped to the role + that declares itself clearnet-only. A role carrying the marker in its + own ``meta/services.yml`` is left out, so it is exempt everywhere. + """ + found: dict[str, str] = {} + for role_dir in sorted(p for p in ROLES_DIR.iterdir() if p.is_dir()): + services_path = role_dir / ROLE_FILE_META_SERVICES + services = _load_yaml(services_path) + tor = services.get("tor") if isinstance(services, dict) else None + if not isinstance(tor, dict) or tor.get("enabled") is not False: + continue + if _suppressed((services_path,)): + continue + key = get_entity_name(role_dir.name) + if key: + found[key] = role_dir.name + return found + + +class TestClearnetRoleForbidsVariantTor(unittest.TestCase): + def test_no_variant_pins_the_onion_while_binding_a_clearnet_role(self) -> None: + clearnet = clearnet_only_keys() + offenders: list[str] = [] + + for role_dir in sorted(p for p in ROLES_DIR.iterdir() if p.is_dir()): + variants_path = role_dir / ROLE_FILE_META_VARIANTS + variants = _load_yaml(variants_path) + if not isinstance(variants, list) or not variants: + continue + if _suppressed((variants_path,)): + continue + + for index, variant in enumerate(variants): + if _flag(variant, "tor") is not True: + continue + for key, bound_role in sorted(clearnet.items()): + if _flag(variant, key) is True: + offenders.append( + f"{role_dir.name} variant {index}: pins " + f"services.tor.enabled true while enabling {key!r} " + f"({bound_role}), which pins tor.enabled false" + ) + + self.assertEqual( + offenders, + [], + "A variant may not pin the onion on while binding a role that rides " + "none; that round advertises a surface no onion browser can reach. " + f"Turn tor off for the variant, or suppress with '# nocheck: {_RULE}' " + "naming why the pairing is sound:\n " + "\n ".join(offenders), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/roles/meta/test_role_subnet_pool.py b/tests/lint/ansible/roles/meta/test_role_subnet_pool.py index b18f584947..d45f12251f 100644 --- a/tests/lint/ansible/roles/meta/test_role_subnet_pool.py +++ b/tests/lint/ansible/roles/meta/test_role_subnet_pool.py @@ -37,7 +37,9 @@ def _declared_space() -> tuple[list[ipaddress.IPv4Network], list[str]]: data = load_yaml_any(str(NETWORKS_FILE), default_if_missing={}) or {} pool = data.get("NETWORK_ROLE_SUBNET_POOL") if isinstance(pool, str) and "{{" in pool: - pool = jinja2.Template(pool).render(**data) + pool = jinja2.Template( + pool, autoescape=jinja2.select_autoescape(default_for_string=False) + ).render(**data) roles = data.get("NETWORK_ROLE_SUBNET_EXCEPTION_ROLES") or [] if not isinstance(pool, str) or not isinstance(roles, list): raise TypeError( diff --git a/tests/lint/ansible/roles/meta/test_sso_access_token_optin.py b/tests/lint/ansible/roles/meta/test_sso_access_token_optin.py index 4ad33f9029..f2778df020 100644 --- a/tests/lint/ansible/roles/meta/test_sso_access_token_optin.py +++ b/tests/lint/ansible/roles/meta/test_sso_access_token_optin.py @@ -45,7 +45,6 @@ GATE = PROJECT_ROOT / ( ) _HEADER_RE = re.compile(r"x[-_]forwarded[-_]access[-_]token", re.IGNORECASE) _EMITS_RE = re.compile(r"proxy_set_header|auth_request_set") -_SKIP_DIRS = {".git", "node_modules", "__pycache__"} _TEXT_SUFFIXES = { ".js", ".mjs", diff --git a/tests/lint/ansible/roles/web-app/integration/test_email.py b/tests/lint/ansible/roles/web-app/integration/test_email.py index c5d3e7e2c1..7197c8451b 100644 --- a/tests/lint/ansible/roles/web-app/integration/test_email.py +++ b/tests/lint/ansible/roles/web-app/integration/test_email.py @@ -168,12 +168,6 @@ class TestWebAppRolesIntegrateEmail(unittest.TestCase): missing.append("enabled: true") if not is_explicit_truth(svc.get("shared")): missing.append("shared: true") - if missing: - rel = ( - config.relative_to(root).as_posix() - if config.is_file() - else role_path.relative_to(root).as_posix() - ) if not _role_pins_the_mail_relay(role_path): errors.append( f"[{role_path.name}]: calls lookup('email', ...) but no " diff --git a/tests/lint/repository/test_compose_build_needs_no_host_network.py b/tests/lint/repository/test_compose_build_needs_no_host_network.py new file mode 100644 index 0000000000..bb951b001a --- /dev/null +++ b/tests/lint/repository/test_compose_build_needs_no_host_network.py @@ -0,0 +1,60 @@ +"""Compose hands a build to ``docker buildx bake`` and grants it only the +``fs.read`` entitlement of the build context. Since Buildx 0.38.0 a block with +``network: host`` stops there with ``additional privileges requested``, and +declaring ``build.entitlements`` or setting ``COMPOSE_BAKE=false`` does not +change that, so such a service cannot be built through ``make compose-up``. +""" + +from __future__ import annotations + +import unittest +from pathlib import Path + +from utils.cache.files import iter_project_files +from utils.cache.yaml import load_yaml_any + +from . import PROJECT_ROOT + +STACK_FILE = str(PROJECT_ROOT / "compose.yml") +OVERRIDES = f"{PROJECT_ROOT / 'compose'}/" +STACK_BUILD = "compose.yml: infinito" + + +def _builds(path): + """Yield ``(label, build)`` for every service of a compose file that builds. + + Args: + path: compose file to read; a YAML file without ``services`` yields nothing. + """ + document = load_yaml_any(path) + if not isinstance(document, dict): + return + for name, service in (document.get("services") or {}).items(): + build = service.get("build") + if isinstance(build, dict): + yield f"{Path(path).relative_to(PROJECT_ROOT)}: {name}", build + + +class TestComposeBuildNeedsNoHostNetwork(unittest.TestCase): + def test_no_build_block_asks_for_host_networking(self) -> None: + compose_files = [ + path + for path in sorted(iter_project_files(extensions=(".yml",))) + if path == STACK_FILE or path.startswith(OVERRIDES) + ] + builds = dict(hit for path in compose_files for hit in _builds(path)) + self.assertIn(STACK_BUILD, builds, "the stack build block was not scanned") + offenders = [ + label for label, build in builds.items() if build.get("network") == "host" + ] + self.assertEqual( + [], + offenders, + "Compose cannot grant bake the network.host entitlement " + "(Buildx >= 0.38.0 refuses the build); drop 'network: host' from: " + f"{offenders}", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/repository/test_workflow_references.py b/tests/lint/repository/test_workflow_references.py index 10340731fb..0c4fc682fa 100644 --- a/tests/lint/repository/test_workflow_references.py +++ b/tests/lint/repository/test_workflow_references.py @@ -14,6 +14,9 @@ Three patterns: ``workflow_dispatch``. Both forms count: ``gh workflow run .yml`` and a REST POST to ``actions/workflows/.yml/dispatches``. +A ``github.com///...`` URL into another repository names that +repository's workflow, which this tree cannot hold, so it is never matched. + Why === Renaming a workflow silently breaks every one of those. A `uses:` line fails @@ -46,6 +49,7 @@ _WORKFLOW_DIR = PROJECT_ROOT / ".github" / "workflows" _SUFFIXES = {".md", ".yml", ".yaml", ".py", ".sh", ".j2", ".rst", ".txt"} _REFERENCE_RE = re.compile(r"(?:\.github|actions)/workflows/([A-Za-z0-9._-]+\.ya?ml)") _BARE_RE = re.compile(r"(?[A-Za-z0-9._-]+\.ya?ml)" r"|actions/workflows/(?P[A-Za-z0-9._-]+\.ya?ml)/dispatches" @@ -90,7 +94,8 @@ def missing_references() -> list[str]: for rel, lines in _candidates(): patterns = _patterns(PROJECT_ROOT / rel) for number, line in enumerate(lines, 1): - names = {name for pattern in patterns for name in pattern.findall(line)} + own = _FOREIGN_URL_RE.sub("", line) + names = {name for pattern in patterns for name in pattern.findall(own)} offenders.extend( f"{rel}:{number}: {name}" for name in sorted(names) if name not in known ) diff --git a/tests/unit/php/roles/web-app-moodle/files/provision/AiGatewayTest.php b/tests/unit/php/roles/web-app-moodle/files/provision/AiGatewayTest.php new file mode 100644 index 0000000000..17fc6b2fa6 --- /dev/null +++ b/tests/unit/php/roles/web-app-moodle/files/provision/AiGatewayTest.php @@ -0,0 +1,346 @@ + $value) { + $copy->$property = $value; + } + return $copy; + } + } + + class manager { + private function rows(): array { + $file = getenv('STUB_STATE'); + return is_file($file) ? json_decode(file_get_contents($file), true) : []; + } + + private function store(provider $provider): provider { + $rows = $this->rows(); + $rows[$provider->id] = [ + 'id' => $provider->id, + 'provider' => get_class($provider), + 'name' => $provider->name, + 'enabled' => $provider->enabled, + 'config' => $provider->config, + 'actionconfig' => $provider->actionconfig, + ]; + file_put_contents(getenv('STUB_STATE'), json_encode($rows)); + return $provider; + } + + public function get_provider_instances(?array $filter = null): array { + $found = []; + foreach ($this->rows() as $row) { + foreach ($filter ?? [] as $column => $value) { + if ($row[$column] != $value) { + continue 2; + } + } + $found[$row['id']] = new $row['provider']( + enabled: $row['enabled'], + name: $row['name'], + config: $row['config'], + actionconfig: $row['actionconfig'], + id: $row['id'], + ); + } + return $found; + } + + public function create_provider_instance( + string $classname, + string $name, + bool $enabled = false, + ?array $config = null, + ?array $actionconfig = null, + ): provider { + return $this->store(new $classname( + enabled: $enabled, + name: $name, + config: $config ?? [], + actionconfig: $actionconfig ?? $classname::initialise_action_settings(), + id: count($this->rows()) + 1, + )); + } + + public function update_provider_instance( + provider $provider, + ?array $config = null, + ?array $actionconfig = null, + ): provider { + return $this->store($provider->with( + config: $config ?? $provider->config, + actionconfig: $actionconfig ?? $provider->actionconfig, + )); + } + + public function enable_provider_instance(provider $provider): provider { + return $provider->enabled ? $provider : $this->store($provider->with(enabled: true)); + } + } + } + + namespace aiprovider_openai { + class provider extends \core_ai\provider { + public static function initialise_action_settings(): array { + $text = [ + 'enabled' => true, + 'settings' => [ + 'endpoint' => 'https://api.openai.com/v1/chat/completions', + 'model' => 'gpt-4o', + 'systeminstruction' => 'upstream default', + ], + ]; + return [ + \core_ai\aiactions\generate_text::class => $text, + \core_ai\aiactions\generate_image::class => [ + 'enabled' => true, + 'settings' => [ + 'endpoint' => 'https://api.openai.com/v1/images/generations', + 'model' => 'dall-e-3', + ], + ], + \core_ai\aiactions\summarise_text::class => $text, + \core_ai\aiactions\explain_text::class => $text, + ]; + } + } + } + + namespace core { + class di { + public static function get(string $class): object { + return new $class(); + } + } + } + PHP; + + private string $config; + + private string $state; + + protected function setUp(): void + { + $this->config = (string) tempnam(sys_get_temp_dir(), 'mdlcfg'); + $this->state = (string) tempnam(sys_get_temp_dir(), 'mdlai'); + file_put_contents($this->config, self::MOODLE); + unlink($this->state); + } + + protected function tearDown(): void + { + unlink($this->config); + if (is_file($this->state)) { + unlink($this->state); + } + } + + /** + * Store provider instances the way an earlier run or an administrator left them. + * + * @param list> $rows instances, each with its id + */ + private function seed(array $rows): void + { + file_put_contents($this->state, json_encode(array_column($rows, null, 'id'))); + } + + /** + * Run the script against the stubbed Moodle. + * + * @return array{0: array, 1: int, 2: array>} + * decoded last output line, exit code and the stored instances by id + */ + private function runScript(): array + { + $script = dirname(__DIR__, 7) . '/roles/web-app-moodle/files/php/provision/ai_gateway.php'; + $process = proc_open( + [PHP_BINARY, $script], + [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], + $pipes, + null, + [ + 'MOODLE_CONFIG' => $this->config, + 'STUB_STATE' => $this->state, + 'AI_PROVIDER_NAME' => self::NAME, + 'AI_API_KEY' => 'sk-gateway', + 'AI_CHAT_ENDPOINT' => self::CHAT, + 'AI_CHAT_MODEL' => self::MODEL, + 'AI_IMAGE_ENDPOINT' => self::IMAGE, + 'PATH' => (string) getenv('PATH'), + ] + ); + $stdout = trim((string) stream_get_contents($pipes[1])); + fclose($pipes[1]); + fclose($pipes[2]); + $code = proc_close($process); + + $lines = explode("\n", $stdout); + $stored = is_file($this->state) + ? json_decode((string) file_get_contents($this->state), true) + : []; + + return [(array) json_decode((string) end($lines), true), $code, $stored]; + } + + public function testAFreshMoodleGetsOneEnabledInstanceWithTheGatewayKey(): void + { + [, $code, $stored] = $this->runScript(); + + $this->assertSame(0, $code); + $this->assertCount(1, $stored); + $instance = reset($stored); + $this->assertSame(self::OPENAI, $instance['provider']); + $this->assertSame(self::NAME, $instance['name']); + $this->assertTrue($instance['enabled']); + $this->assertSame('sk-gateway', $instance['config']['apikey']); + } + + public function testEveryTextActionIsEnabledAndAnswersThroughTheGateway(): void + { + [, , $stored] = $this->runScript(); + + $actions = reset($stored)['actionconfig']; + foreach (self::TEXT_ACTIONS as $action) { + $this->assertTrue($actions[$action]['enabled'], $action); + $this->assertSame(self::CHAT, $actions[$action]['settings']['endpoint'], $action); + $this->assertSame(self::MODEL, $actions[$action]['settings']['model'], $action); + $this->assertSame( + 'upstream default', + $actions[$action]['settings']['systeminstruction'], + $action + ); + } + } + + public function testImageGenerationIsSwitchedOffAndStillPointsAtTheGateway(): void + { + [, , $stored] = $this->runScript(); + + $image = reset($stored)['actionconfig'][self::IMAGE_ACTION]; + $this->assertFalse($image['enabled']); + $this->assertSame(self::IMAGE, $image['settings']['endpoint']); + } + + public function testTheOutputNamesTheInstanceAndTheStoredEndpointOfEveryAction(): void + { + [$output, , $stored] = $this->runScript(); + + $this->assertSame(array_key_first($stored), $output['id']); + $this->assertSame( + [ + self::TEXT_ACTIONS[0] => self::CHAT, + self::IMAGE_ACTION => self::IMAGE, + self::TEXT_ACTIONS[1] => self::CHAT, + self::TEXT_ACTIONS[2] => self::CHAT, + ], + $output['endpoints'] + ); + } + + public function testAnInstanceOfThatNameIsReusedAndKeepsWhatTheScriptDoesNotSet(): void + { + $this->seed([[ + 'id' => 7, + 'provider' => self::OPENAI, + 'name' => self::NAME, + 'enabled' => false, + 'config' => ['apikey' => 'sk-stale', 'orgid' => 'org-1'], + 'actionconfig' => [ + self::TEXT_ACTIONS[0] => [ + 'enabled' => false, + 'settings' => [ + 'endpoint' => 'https://api.openai.com/v1/chat/completions', + 'model' => 'gpt-4o', + 'systeminstruction' => 'answer briefly', + ], + ], + ], + ]]); + + [$output, , $stored] = $this->runScript(); + + $this->assertSame([7], array_keys($stored)); + $this->assertSame(7, $output['id']); + $this->assertTrue($stored[7]['enabled']); + $this->assertSame(['apikey' => 'sk-gateway', 'orgid' => 'org-1'], $stored[7]['config']); + $settings = $stored[7]['actionconfig'][self::TEXT_ACTIONS[0]]['settings']; + $this->assertSame(self::CHAT, $settings['endpoint']); + $this->assertSame('answer briefly', $settings['systeminstruction']); + } + + public function testAnInstanceAnAdministratorAddedIsLeftAlone(): void + { + $own = [ + 'id' => 1, + 'provider' => self::OPENAI, + 'name' => 'Our own OpenAI account', + 'enabled' => true, + 'config' => ['apikey' => 'sk-own'], + 'actionconfig' => [], + ]; + $this->seed([$own]); + + [$output, , $stored] = $this->runScript(); + + $this->assertSame([1, 2], array_keys($stored)); + $this->assertSame($own, $stored[1]); + $this->assertSame(2, $output['id']); + $this->assertSame(self::NAME, $stored[2]['name']); + } + + public function testASecondRunChangesNothing(): void + { + [, , $first] = $this->runScript(); + [, $code, $second] = $this->runScript(); + + $this->assertSame(0, $code); + $this->assertSame($first, $second); + } +} diff --git a/tests/unit/python/plugins/filter/test_dotenv_quote.py b/tests/unit/python/plugins/filter/test_dotenv_quote.py index 9d61bddbdd..f05d3e37da 100644 --- a/tests/unit/python/plugins/filter/test_dotenv_quote.py +++ b/tests/unit/python/plugins/filter/test_dotenv_quote.py @@ -68,7 +68,9 @@ class TestDotenvQuoteModeAware(unittest.TestCase): """ def setUp(self): - env = jinja2.Environment(autoescape=False) # noqa: S701 - test renders a .env value, not HTML + env = jinja2.Environment( + autoescape=jinja2.select_autoescape(default_for_string=False) + ) env.filters["dotenv_quote"] = FilterModule().filters()["dotenv_quote"] self.env = env diff --git a/tests/unit/python/plugins/filter/test_native_metrics_target.py b/tests/unit/python/plugins/filter/test_native_metrics_target.py deleted file mode 100644 index e2d773c2e5..0000000000 --- a/tests/unit/python/plugins/filter/test_native_metrics_target.py +++ /dev/null @@ -1,111 +0,0 @@ -from __future__ import annotations - -import unittest -from unittest.mock import patch - -from ansible.errors import AnsibleFilterError - -from plugins.filter.native_metrics_target import native_metrics_target - - -def _make_applications( - app_id: str, - container: str, - port: int, - entity_name: str, - service_key: str | None = None, -) -> dict: - native_metrics: dict = {"port": port} - if service_key is not None: - native_metrics["service_key"] = service_key - return { - app_id: { - "services": { - entity_name: {"name": container}, - "prometheus": {"native_metrics": native_metrics}, - } - } - } - - -class TestNativeMetricsTargetSuccess(unittest.TestCase): - def test_returns_container_colon_port(self): - apps = _make_applications("web-app-gitea", "gitea", 3000, "gitea") - with patch( - "plugins.filter.native_metrics_target.get_entity_name", return_value="gitea" - ): - result = native_metrics_target("web-app-gitea", apps) - self.assertEqual(result, "gitea:3000") - - def test_different_app(self): - apps = _make_applications( - "web-app-mattermost", "mattermost", 8067, "mattermost" - ) - with patch( - "plugins.filter.native_metrics_target.get_entity_name", - return_value="mattermost", - ): - result = native_metrics_target("web-app-mattermost", apps) - self.assertEqual(result, "mattermost:8067") - - def test_service_key_override(self): - apps = _make_applications( - "web-app-matrix", "matrix-synapse", 9000, "synapse", service_key="synapse" - ) - with patch( - "plugins.filter.native_metrics_target.get_entity_name", - return_value="matrix", - ): - result = native_metrics_target("web-app-matrix", apps) - self.assertEqual(result, "matrix-synapse:9000") - - -class TestNativeMetricsTargetErrors(unittest.TestCase): - def test_raises_when_container_name_missing(self): - apps = { - "web-app-gitea": { - "services": { - "prometheus": {"native_metrics": {"port": 3000}}, - } - } - } - with ( - patch( - "plugins.filter.native_metrics_target.get_entity_name", - return_value="gitea", - ), - self.assertRaises(AnsibleFilterError), - ): - native_metrics_target("web-app-gitea", apps) - - def test_raises_when_port_missing(self): - apps = { - "web-app-gitea": { - "services": { - "gitea": {"name": "gitea"}, - "prometheus": {"native_metrics": {}}, - } - } - } - with ( - patch( - "plugins.filter.native_metrics_target.get_entity_name", - return_value="gitea", - ), - self.assertRaises(AnsibleFilterError), - ): - native_metrics_target("web-app-gitea", apps) - - def test_raises_when_app_not_in_applications(self): - with ( - patch( - "plugins.filter.native_metrics_target.get_entity_name", - return_value="gitea", - ), - self.assertRaises(AnsibleFilterError), - ): - native_metrics_target("web-app-gitea", {}) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_alert_rule_roles.py b/tests/unit/python/plugins/lookup/test_alert_rule_roles.py index 09953d117e..92cf702dbb 100644 --- a/tests/unit/python/plugins/lookup/test_alert_rule_roles.py +++ b/tests/unit/python/plugins/lookup/test_alert_rule_roles.py @@ -17,7 +17,6 @@ import unittest.mock as mock from pathlib import Path import plugins.lookup.alert_rule_roles as module -from plugins.lookup.alert_rule_roles import LookupModule class _Templar: @@ -29,7 +28,7 @@ class _Templar: def _make_lookup(vars_=None): - lm = LookupModule() + lm = module.LookupModule() lm._templar = _Templar(vars_ or {}) lm._loader = mock.MagicMock() return lm diff --git a/tests/unit/python/plugins/lookup/test_compose_volumes_realign.py b/tests/unit/python/plugins/lookup/test_compose_volumes_realign.py index 4cb4765aca..28a633ccec 100644 --- a/tests/unit/python/plugins/lookup/test_compose_volumes_realign.py +++ b/tests/unit/python/plugins/lookup/test_compose_volumes_realign.py @@ -40,7 +40,9 @@ def _render(**answers) -> str: def _lookup(_plugin, _app, key): return values[key] - env = jinja2.Environment(autoescape=False) # noqa: S701 - renders SQL, HTML escaping would corrupt the literals + env = jinja2.Environment( + autoescape=jinja2.select_autoescape(default_for_string=False) + ) return env.from_string(read_text(str(_TEMPLATE))).render( lookup=_lookup, application_id="web-app-x" ) diff --git a/tests/unit/python/plugins/lookup/test_engine_redis_session_path.py b/tests/unit/python/plugins/lookup/test_engine_redis_session_path.py new file mode 100644 index 0000000000..d7576f2d90 --- /dev/null +++ b/tests/unit/python/plugins/lookup/test_engine_redis_session_path.py @@ -0,0 +1,51 @@ +"""phpredis reads ``auth[user]``/``auth[pass]`` and ``prefix`` from the query of +``session.save_path``; a password with a reserved character that is not +percent-encoded splits the query and the handler authenticates with a fragment. +""" + +from __future__ import annotations + +import importlib +import unittest +from urllib.parse import parse_qs, urlsplit + +plugin_module = importlib.import_module("plugins.lookup.engine") +redis_session_path = plugin_module.redis_session_path + + +class TestRedisSessionPath(unittest.TestCase): + def test_an_embedded_sidecar_gets_no_credentials(self) -> None: + self.assertEqual( + "tcp://redis:6379?prefix=suitecrm:session:", + redis_session_path("redis", 6379, "suitecrm", "", ""), + ) + + def test_a_shared_redis_gets_user_and_password(self) -> None: + query = parse_qs( + urlsplit( + redis_session_path("redis-central", 6379, "suitecrm", "default", "pw") + ).query + ) + self.assertEqual(["default"], query["auth[user]"]) + self.assertEqual(["pw"], query["auth[pass]"]) + + def test_a_password_with_reserved_characters_survives_the_query(self) -> None: + password = "a&b=c?d#e/f+g h" + query = parse_qs( + urlsplit( + redis_session_path( + "redis-central", 6379, "suitecrm", "default", password + ) + ).query + ) + self.assertEqual([password], query["auth[pass]"]) + self.assertEqual(["suitecrm:session:"], query["prefix"]) + + def test_a_user_without_a_password_is_not_sent(self) -> None: + self.assertNotIn( + "auth", redis_session_path("redis", 6379, "suitecrm", "default", "") + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_mcp_client_bearer.py b/tests/unit/python/plugins/lookup/test_mcp_client_bearer.py index cfbc4d0e3a..72afc969bf 100644 --- a/tests/unit/python/plugins/lookup/test_mcp_client_bearer.py +++ b/tests/unit/python/plugins/lookup/test_mcp_client_bearer.py @@ -10,8 +10,7 @@ from __future__ import annotations import importlib.util import unittest -from unittest import mock -from unittest.mock import patch +from unittest.mock import MagicMock, patch from ansible.errors import AnsibleError @@ -40,7 +39,7 @@ class TestMcpClientBearerLookup(unittest.TestCase): def _run(self, terms, credential, role_credentials=None, users=None): lookup = self.mod.LookupModule() lookup._templar = _DummyTemplar() - lookup._loader = mock.MagicMock() + lookup._loader = MagicMock() class _StubConfig: def run(self, terms_, variables=None, **kwargs): diff --git a/tests/unit/python/plugins/lookup/test_mcp_credential.py b/tests/unit/python/plugins/lookup/test_mcp_credential.py index fc67f6fb62..4c1b83d4b3 100644 --- a/tests/unit/python/plugins/lookup/test_mcp_credential.py +++ b/tests/unit/python/plugins/lookup/test_mcp_credential.py @@ -9,8 +9,7 @@ from __future__ import annotations import importlib.util import unittest -from unittest import mock -from unittest.mock import patch +from unittest.mock import MagicMock, patch from ansible.errors import AnsibleError @@ -39,7 +38,7 @@ class TestMcpCredentialLookup(unittest.TestCase): def _run(self, terms, owner="mcp-web-app-gitea", users=None): lookup = self.mod.LookupModule() lookup._templar = _DummyTemplar() - lookup._loader = mock.MagicMock() + lookup._loader = MagicMock() class _StubConfig: def run(self, terms_, variables=None, **kwargs): diff --git a/tests/unit/python/plugins/lookup/test_native_metrics_target.py b/tests/unit/python/plugins/lookup/test_native_metrics_target.py new file mode 100644 index 0000000000..e3abbdb9dd --- /dev/null +++ b/tests/unit/python/plugins/lookup/test_native_metrics_target.py @@ -0,0 +1,119 @@ +"""Tests for the native_metrics_target lookup. + +The lookup delegates host resolution to scrape_target, so these run the real +scrape_target rather than a stub: the regression being guarded is that swarm +must not receive a compose container name, and only the delegation proves it. +""" + +from __future__ import annotations + +import unittest +from typing import Any +from unittest.mock import MagicMock, patch + +from ansible.errors import AnsibleError + +from plugins.lookup.native_metrics_target import LookupModule +from plugins.lookup.scrape_target import LookupModule as ScrapeTargetLookup + +ENTITIES = {"web-app-matrix": "matrix", "web-app-gitea": "gitea"} + + +class _Templar: + def __init__(self, vars_=None): + self.available_variables = vars_ or {} + + def template(self, value, **_): + return value + + +def _apps(native_metrics: dict[str, Any]) -> dict[str, Any]: + return { + "web-app-matrix": { + "services": { + "prometheus": {"native_metrics": native_metrics}, + "synapse": { + "name": "matrix-synapse", + "ports": {"internal": {"http": 8008}}, + }, + }, + }, + } + + +def _run(terms, *, mode, apps): + variables = {"DEPLOYMENT_MODE": mode} + lookup = LookupModule() + lookup._templar = _Templar(variables) + lookup._loader = MagicMock() + + def _dispatch(name, **_kwargs): + if name == "applications": + return MagicMock(run=lambda *_a, **_k: [apps]) + scrape = ScrapeTargetLookup() + scrape._templar = _Templar(variables) + scrape._loader = MagicMock() + return scrape + + with ( + patch( + "plugins.lookup.native_metrics_target.lookup_loader" + ) as native_loader_mock, + patch("plugins.lookup.scrape_target.lookup_loader") as scrape_loader_mock, + patch( + "plugins.lookup.native_metrics_target.get_entity_name", + side_effect=lambda app_id: ENTITIES.get(app_id, ""), + ), + patch( + "plugins.lookup.scrape_target.get_entity_name", + side_effect=lambda app_id: ENTITIES.get(app_id, ""), + ), + ): + native_loader_mock.get.side_effect = _dispatch + scrape_loader_mock.get.return_value = MagicMock(run=lambda *_a, **_k: [apps]) + return lookup.run(terms, variables=variables) + + +class TestNativeMetricsTargetLookup(unittest.TestCase): + def test_swarm_uses_per_task_dns_not_the_container_name(self): + apps = _apps({"port": 9000, "service_key": "synapse"}) + result = _run(["web-app-matrix"], mode="swarm", apps=apps) + self.assertEqual(result, ["tasks.matrix_synapse:9000"]) + + def test_compose_uses_the_container_name(self): + apps = _apps({"port": 9000, "service_key": "synapse"}) + result = _run(["web-app-matrix"], mode="compose", apps=apps) + self.assertEqual(result, ["matrix-synapse:9000"]) + + def test_service_key_defaults_to_the_entity_name(self): + apps = { + "web-app-gitea": { + "services": { + "prometheus": {"native_metrics": {"port": 3000}}, + "gitea": { + "name": "gitea", + "ports": {"internal": {"http": 3000}}, + }, + }, + }, + } + result = _run(["web-app-gitea"], mode="swarm", apps=apps) + self.assertEqual(result, ["tasks.gitea_gitea:3000"]) + + def test_native_metrics_port_takes_precedence_over_the_internal_port(self): + apps = _apps({"port": 9000, "service_key": "synapse"}) + result = _run(["web-app-matrix"], mode="compose", apps=apps) + self.assertNotIn("8008", result[0]) + + def test_missing_port_raises(self): + apps = _apps({"service_key": "synapse"}) + with self.assertRaises(AnsibleError): + _run(["web-app-matrix"], mode="compose", apps=apps) + + def test_missing_application_id_raises(self): + with self.assertRaises(AnsibleError): + _run([], mode="compose", apps=_apps({"port": 9000})) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_redirect_uris.py b/tests/unit/python/plugins/lookup/test_redirect_uris.py index 9a4772ea9a..ec7d98dc24 100644 --- a/tests/unit/python/plugins/lookup/test_redirect_uris.py +++ b/tests/unit/python/plugins/lookup/test_redirect_uris.py @@ -1,7 +1,7 @@ from __future__ import annotations import unittest -from unittest import mock +import unittest.mock as mock from ansible.errors import AnsibleError diff --git a/tests/unit/python/roles/agents/test_mcp_tool_filter.py b/tests/unit/python/roles/agents/test_mcp_tool_filter.py index d4d8fa0149..4a09f37952 100644 --- a/tests/unit/python/roles/agents/test_mcp_tool_filter.py +++ b/tests/unit/python/roles/agents/test_mcp_tool_filter.py @@ -20,7 +20,7 @@ import json import unittest import yaml -from jinja2 import Environment, FileSystemLoader +from jinja2 import Environment, FileSystemLoader, select_autoescape from . import PROJECT_ROOT @@ -82,7 +82,9 @@ def _yaml(text: str): def _render(directory, name, **context) -> str: - env = Environment(loader=FileSystemLoader(str(directory)), autoescape=False) # noqa: S701 - renders configuration, not markup + env = Environment( + loader=FileSystemLoader(str(directory)), autoescape=select_autoescape() + ) env.filters.update(_filters()) return env.get_template(name).render(**context) diff --git a/tests/unit/python/roles/agents/test_openclaw_model_provider.py b/tests/unit/python/roles/agents/test_openclaw_model_provider.py index d7939d8710..4ce39d8ee8 100644 --- a/tests/unit/python/roles/agents/test_openclaw_model_provider.py +++ b/tests/unit/python/roles/agents/test_openclaw_model_provider.py @@ -16,7 +16,7 @@ import importlib.util import json import unittest -from jinja2 import Environment, FileSystemLoader +from jinja2 import Environment, FileSystemLoader, select_autoescape from . import PROJECT_ROOT @@ -51,7 +51,9 @@ def _render(**overrides) -> dict: Args: overrides: context values replacing the defaults. """ - env = Environment(loader=FileSystemLoader(str(OPENCLAW)), autoescape=False) # noqa: S701 - renders configuration, not markup + env = Environment( + loader=FileSystemLoader(str(OPENCLAW)), autoescape=select_autoescape() + ) env.filters.update(_filters()) return json.loads( env.get_template("openclaw.json.j2").render(**{**CONTEXT, **overrides}) diff --git a/tests/unit/python/roles/svc-ai-litellm/templates/test_config_model_list.py b/tests/unit/python/roles/svc-ai-litellm/templates/test_config_model_list.py index e1728d0e72..3f21f05fe5 100644 --- a/tests/unit/python/roles/svc-ai-litellm/templates/test_config_model_list.py +++ b/tests/unit/python/roles/svc-ai-litellm/templates/test_config_model_list.py @@ -12,7 +12,7 @@ from __future__ import annotations import unittest import yaml -from jinja2 import Environment, StrictUndefined +from jinja2 import Environment, StrictUndefined, select_autoescape from utils.cache.files import read_text @@ -72,7 +72,10 @@ def render(*, ollama=(), lmstudio=(), keys=None): lmstudio: preload entries svc-ai-lmstudio declares; empty means not deployed. keys: env-name -> provider key for the remote backends. """ - env = Environment(undefined=StrictUndefined, autoescape=False) # noqa: S701 - YAML, not markup + env = Environment( + undefined=StrictUndefined, + autoescape=select_autoescape(default_for_string=False), + ) env.filters["bool"] = _ansible_bool rendered = env.from_string(read_text(str(TEMPLATE))).render( LITELLM_OLLAMA_BACKEND=str(bool(ollama)), diff --git a/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_policy.py b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_policy.py index 376ac03ab3..c04c092e7a 100644 --- a/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_policy.py +++ b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_policy.py @@ -4,6 +4,7 @@ from __future__ import annotations import importlib.util import json +import time import unittest from . import PROJECT_ROOT @@ -234,6 +235,26 @@ class TestDeclaredArguments(unittest.TestCase): self.assertEqual("GET", method) +class TestPathArguments(unittest.TestCase): + def call(self, **arguments): + return policy.authorize_call(contract(), "checkmk_get_host_status", arguments) + + def test_a_value_made_only_of_dots_is_refused(self): + for dots in range(4): + with self.subTest(dots=dots): + with self.assertRaises(PermissionError) as caught: + self.call(host="." * dots) + self.assertIn(policy.DENY_PATH_ARGUMENT, str(caught.exception)) + + def test_dots_inside_a_segment_pass(self): + for value in ("web-01.example", "..web", "web.."): + with self.subTest(value=value): + self.call(host=value) + + def test_a_query_argument_may_be_made_only_of_dots(self): + self.call(host="web-01", columns="." * 2) + + RANGE_TOOLS = { "prometheus_query_range": { "method": "GET", @@ -326,6 +347,22 @@ class TestDurationGrammar(unittest.TestCase): with self.assertRaises(ValueError): policy.parse_duration("1h30") + def test_anything_but_number_unit_pairs_is_refused(self): + for text in ("", "h", "1hh", "1.5h", "-1h", "1 h", "1sm", "abc"): + with self.subTest(text=text), self.assertRaises(ValueError): + policy.parse_duration(text) + + def test_a_long_digit_run_is_refused_in_linear_time(self): + started = time.monotonic() + with self.assertRaises(ValueError): + policy.parse_duration("0" * 20_000 + "!") + self.assertLess( + time.monotonic() - started, + 1.0, + "parsing must not rescan the digit run from every start position; " + "a backtracking pattern needs several seconds for this input", + ) + class TestAudit(unittest.TestCase): def test_the_event_names_both_sides_and_the_outcome(self): diff --git a/tests/unit/python/roles/svc-net-firewall/test_fragments.py b/tests/unit/python/roles/svc-net-firewall/test_fragments.py index 99152196b5..ecadb860ef 100644 --- a/tests/unit/python/roles/svc-net-firewall/test_fragments.py +++ b/tests/unit/python/roles/svc-net-firewall/test_fragments.py @@ -129,7 +129,7 @@ def _render(path: str, mode: str = "swarm") -> str: environment = jinja2.Environment( keep_trailing_newline=True, trim_blocks=True, - autoescape=False, # noqa: S701 nftables, not markup + autoescape=jinja2.select_autoescape(default_for_string=False), ) return environment.from_string(read_text(path)).render( DEPLOYMENT_MODE=mode, **COMMON diff --git a/tests/unit/python/roles/svc-net-tor-smtp/files/test_tor_smtp_gateway.py b/tests/unit/python/roles/svc-net-tor-smtp/files/test_tor_smtp_gateway.py index 67634ed302..a64c68528e 100644 --- a/tests/unit/python/roles/svc-net-tor-smtp/files/test_tor_smtp_gateway.py +++ b/tests/unit/python/roles/svc-net-tor-smtp/files/test_tor_smtp_gateway.py @@ -14,7 +14,7 @@ import os import sys import types import unittest -from unittest import mock +import unittest.mock as mock from . import PROJECT_ROOT diff --git a/tests/unit/python/roles/svc-net-tor/test_egress_clients.py b/tests/unit/python/roles/svc-net-tor/test_egress_clients.py index 52a558a9a9..7b04c193dd 100644 --- a/tests/unit/python/roles/svc-net-tor/test_egress_clients.py +++ b/tests/unit/python/roles/svc-net-tor/test_egress_clients.py @@ -16,7 +16,7 @@ from __future__ import annotations import importlib.util import sys import unittest -from unittest import mock +import unittest.mock as mock import jinja2 @@ -46,7 +46,9 @@ class _Templar: def template(self, value): return ( - jinja2.Environment(autoescape=False) # noqa: S701 - renders CIDRs, not markup + jinja2.Environment( + autoescape=jinja2.select_autoescape(default_for_string=False) + ) .from_string(str(value)) .render(**self.available_variables) ) diff --git a/tests/unit/python/roles/svc-net-tor/test_extra_ports.py b/tests/unit/python/roles/svc-net-tor/test_extra_ports.py index 4deb747de1..98528445a8 100644 --- a/tests/unit/python/roles/svc-net-tor/test_extra_ports.py +++ b/tests/unit/python/roles/svc-net-tor/test_extra_ports.py @@ -16,8 +16,8 @@ from __future__ import annotations import importlib.util import sys import unittest +import unittest.mock as mock from typing import Any -from unittest import mock from ansible.errors import AnsibleError diff --git a/tests/unit/python/roles/sys-svc-mail-msmtp/test_msmtprc_ca_trust.py b/tests/unit/python/roles/sys-svc-mail-msmtp/test_msmtprc_ca_trust.py index 3e7e435f11..43acfc794f 100644 --- a/tests/unit/python/roles/sys-svc-mail-msmtp/test_msmtprc_ca_trust.py +++ b/tests/unit/python/roles/sys-svc-mail-msmtp/test_msmtprc_ca_trust.py @@ -18,7 +18,7 @@ import re import unittest from typing import Any, ClassVar -from jinja2 import Environment, StrictUndefined +from jinja2 import Environment, StrictUndefined, select_autoescape from utils.cache.files import read_text @@ -46,7 +46,7 @@ def _env() -> Environment: trim_blocks=True, lstrip_blocks=True, undefined=StrictUndefined, - autoescape=False, # noqa: S701 - a config file, and Ansible's templar does not escape either + autoescape=select_autoescape(default_for_string=False), ) env.filters["bool"] = bool env.filters["on_off"] = lambda value: "on" if value else "off" diff --git a/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_edge_limits.py b/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_edge_limits.py index 8c6880baec..ee2610af0a 100644 --- a/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_edge_limits.py +++ b/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_edge_limits.py @@ -12,7 +12,7 @@ from __future__ import annotations import unittest -from jinja2 import Environment, FileSystemLoader, StrictUndefined +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape from utils.cache.applications import get_application_defaults from utils.cache.yaml import load_yaml @@ -44,7 +44,7 @@ def render(name: str, **context) -> str: env = Environment( loader=FileSystemLoader(str(TEMPLATE_DIR)), undefined=StrictUndefined, - autoescape=False, # noqa: S701 - nginx config, not markup; Ansible renders it the same way and HTML-escaping `$binary_remote_addr` would break it + autoescape=select_autoescape(), ) return env.get_template(name).render(**context) diff --git a/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_vhost_exposure.py b/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_vhost_exposure.py index cc2eaea1c3..7d2a7611e6 100644 --- a/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_vhost_exposure.py +++ b/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_vhost_exposure.py @@ -22,7 +22,7 @@ from __future__ import annotations import re import unittest -from jinja2 import Environment, FileSystemLoader, StrictUndefined +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape from utils.cache.yaml import load_yaml from utils.roles.mapping import ROLE_FILE_META_MCP @@ -80,7 +80,7 @@ def render(role: str, *, exposure: str, sso_gated: bool = False) -> str: env = Environment( loader=FileSystemLoader(str(TEMPLATE_DIR)), undefined=StrictUndefined, - autoescape=False, # noqa: S701 - nginx config, not markup; HTML-escaping would corrupt the directives + autoescape=select_autoescape(), ) env.filters["regex_replace"] = lambda value, pattern, repl="": re.sub( pattern, repl, value diff --git a/tests/unit/python/roles/test-e2e-cli/files/shared/mcp/test_contract.py b/tests/unit/python/roles/test-e2e-cli/files/shared/mcp/test_contract.py index f4fdf6163f..70086add9d 100644 --- a/tests/unit/python/roles/test-e2e-cli/files/shared/mcp/test_contract.py +++ b/tests/unit/python/roles/test-e2e-cli/files/shared/mcp/test_contract.py @@ -659,5 +659,79 @@ class TestSseSessionProbe(unittest.TestCase): self.assertIn("absent from the probed URL", stderr.getvalue()) +NEGOTIATED = "2025-03-26" + + +class StrictProvider: + def __init__(self): + self.seen = [] + self._server = ThreadingHTTPServer(("127.0.0.1", 0), self._handler()) + threading.Thread(target=self._server.serve_forever, daemon=True).start() + + @property + def url(self): + host, port = self._server.server_address[:2] + return f"http://{host}:{port}/mcp" + + def stop(self): + self._server.shutdown() + self._server.server_close() + + def _handler(self): + provider = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_POST(self): + length = int(self.headers.get("Content-Length", "0")) + payload = json.loads(self.rfile.read(length) or b"{}") + method = payload.get("method") + version = self.headers.get("MCP-Protocol-Version") + status, answer = 200, {"jsonrpc": "2.0", "id": payload.get("id")} + if self.headers.get("Authorization") != "Bearer real": + status, answer["error"] = 401, {"code": -32001, "message": "no"} + elif method == "initialize": + answer["result"] = {"protocolVersion": NEGOTIATED} + elif version != NEGOTIATED: + status = 400 + answer["error"] = { + "code": -32600, + "message": "MCP-Protocol-Version header is required", + } + elif method == "tools/list": + answer["result"] = { + "tools": [{"name": "a_get"}, {"name": "a_list"}] + } + else: + answer["result"] = {"isError": False, "content": []} + if method != "initialize": + provider.seen.append((method, version)) + body = json.dumps(answer).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + return Handler + + +class TestProtocolVersionHeader(unittest.TestCase): + def test_every_request_after_initialize_names_the_negotiated_version(self): + provider = StrictProvider() + self.addCleanup(provider.stop) + load({"MCP_URL": provider.url}).main() + self.assertEqual( + provider.seen, + [ + ("notifications/initialized", NEGOTIATED), + ("tools/list", NEGOTIATED), + ("tools/call", NEGOTIATED), + ], + ) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/roles/test-e2e-playwright/test_readiness_until.py b/tests/unit/python/roles/test-e2e-playwright/test_readiness_until.py index 4fb7076704..d924d3c71b 100644 --- a/tests/unit/python/roles/test-e2e-playwright/test_readiness_until.py +++ b/tests/unit/python/roles/test-e2e-playwright/test_readiness_until.py @@ -2,7 +2,7 @@ from __future__ import annotations import unittest -from jinja2 import Environment +from jinja2 import Environment, select_autoescape from utils.cache.yaml import load_yaml_any @@ -21,9 +21,9 @@ def until_expression() -> str: def settles(result: dict) -> bool: - template = Environment(autoescape=False).from_string( # noqa: S701 - ansible condition, not markup - "{{ " + until_expression() + " }}" - ) + template = Environment( + autoescape=select_autoescape(default_for_string=False) + ).from_string("{{ " + until_expression() + " }}") return template.render(_wait_result=result) == "True" diff --git a/tests/unit/python/roles/web-app-gitlab/test_smtp_settings.py b/tests/unit/python/roles/web-app-gitlab/test_smtp_settings.py index 4198036cc3..ac76ffb055 100644 --- a/tests/unit/python/roles/web-app-gitlab/test_smtp_settings.py +++ b/tests/unit/python/roles/web-app-gitlab/test_smtp_settings.py @@ -17,7 +17,7 @@ from __future__ import annotations import re import unittest -from jinja2 import Environment, StrictUndefined +from jinja2 import Environment, StrictUndefined, select_autoescape from utils.cache.files import read_text @@ -50,7 +50,7 @@ def _render(email: dict, ca_file: str = "") -> str: trim_blocks=True, lstrip_blocks=True, undefined=StrictUndefined, - autoescape=False, # noqa: S701 - a Ruby config file, and Ansible's templar does not escape either + autoescape=select_autoescape(default_for_string=False), ) env.filters["bool"] = bool env.filters["ruby_dq"] = lambda value: '"' + str(value).replace('"', '\\"') + '"' diff --git a/tests/unit/python/roles/web-app-keycloak/templates/test_realm_import_json.py b/tests/unit/python/roles/web-app-keycloak/templates/test_realm_import_json.py index 008a48bd8f..249189de47 100644 --- a/tests/unit/python/roles/web-app-keycloak/templates/test_realm_import_json.py +++ b/tests/unit/python/roles/web-app-keycloak/templates/test_realm_import_json.py @@ -5,7 +5,7 @@ import json import re import unittest -from jinja2 import Environment, FileSystemLoader, StrictUndefined +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape from . import PROJECT_ROOT @@ -102,7 +102,7 @@ def render(saml_apps: list[str], client_apps: list[str] | None = None) -> str: trim_blocks=True, keep_trailing_newline=True, undefined=StrictUndefined, - autoescape=False, # noqa: S701 - renders JSON, where HTML escaping corrupts the value + autoescape=select_autoescape(), ) env.filters["path_join"] = path_join env.filters["to_json"] = json.dumps diff --git a/tests/unit/python/roles/web-app-moodle/__init__.py b/tests/unit/python/roles/web-app-moodle/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-moodle/files/__init__.py b/tests/unit/python/roles/web-app-moodle/files/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-moodle/files/build/__init__.py b/tests/unit/python/roles/web-app-moodle/files/build/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-moodle/files/build/test_moodle_entrypoint.py b/tests/unit/python/roles/web-app-moodle/files/build/test_moodle_entrypoint.py new file mode 100644 index 0000000000..9ed0c5bcb0 --- /dev/null +++ b/tests/unit/python/roles/web-app-moodle/files/build/test_moodle_entrypoint.py @@ -0,0 +1,124 @@ +import os +import pwd +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +from utils import PROJECT_ROOT +from utils.cache.files import read_text + +ENTRYPOINT = PROJECT_ROOT / "roles/web-app-moodle/files/build/moodle-entrypoint.sh" + +FPM_STUB = "#!/usr/bin/env bash\nexit 0\n" + +LAYOUT_4 = {"version.php": "4.5.11", "auth/oidc/version.php": "4.5.8"} +LAYOUT_5 = {"public/version.php": "5.3.0", "public/auth/oidc/version.php": "5.2.1"} + + +class TestMoodleEntrypoint(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.source = self.root / "source" + self.code = self.root / "code" + bin_dir = self.root / "bin" + bin_dir.mkdir() + stub = bin_dir / "php-fpm" + stub.write_text(FPM_STUB) + stub.chmod(0o755) + self.env = dict(os.environ) + self.env.update( + PATH=f"{bin_dir}{os.pathsep}{self.env['PATH']}", + MOODLE_CODE_DIR=str(self.code), + MOODLE_DATA_DIR=str(self.root / "data"), + MOODLE_LOCAL_CACHE_DIR=str(self.root / "localcache"), + MOODLE_SOURCE_DIR=str(self.source), + MOODLE_RUNTIME_USER=pwd.getpwuid(os.getuid()).pw_name, + MOODLE_VERSION_FILE="public/version.php", + ) + + def write(self, tree, files): + for name, content in files.items(): + path = tree / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content) + + def ship(self, files): + shutil.rmtree(self.source, ignore_errors=True) + self.write(self.source, files) + + def run_entrypoint(self, release): + return subprocess.run( + ["bash", str(ENTRYPOINT), "php-fpm"], + env={**self.env, "MOODLE_RELEASE": release}, + capture_output=True, + text=True, + check=False, + ) + + def start(self, release): + done = self.run_entrypoint(release) + self.assertEqual(done.returncode, 0, done.stderr) + + def shipped_files_in_the_volume(self): + return { + name for name in {*LAYOUT_4, *LAYOUT_5} if (self.code / name).is_file() + } + + def test_the_first_start_fills_the_code_volume(self): + self.ship(LAYOUT_5) + self.start("5.3.0") + self.assertEqual(self.shipped_files_in_the_volume(), set(LAYOUT_5)) + + def test_a_restart_on_the_same_release_keeps_what_the_volume_holds(self): + self.ship(LAYOUT_5) + self.start("5.3.0") + added = {"public/local/extra/version.php": "added after the bootstrap"} + self.write(self.code, added) + self.start("5.3.0") + self.assertTrue((self.code / "public/local/extra/version.php").is_file()) + + def test_another_release_replaces_the_tree_and_drops_what_it_no_longer_ships(self): + self.ship(LAYOUT_4) + self.start("4.5.11") + self.ship(LAYOUT_5) + self.start("5.3.0") + self.assertEqual(self.shipped_files_in_the_volume(), set(LAYOUT_5)) + + def test_a_volume_the_previous_entrypoint_marked_done_is_replaced(self): + self.write(self.code, LAYOUT_4) + (self.code / ".bootstrap.done").touch() + self.ship(LAYOUT_5) + self.start("5.3.0") + self.assertEqual(self.shipped_files_in_the_volume(), set(LAYOUT_5)) + + def test_a_missing_source_tree_fails_and_leaves_the_volume_unmarked(self): + done = self.run_entrypoint("5.3.0") + self.assertNotEqual(done.returncode, 0) + self.assertFalse((self.code / ".bootstrap.done").exists()) + + def test_a_failed_copy_keeps_the_tree_the_volume_held(self): + self.ship(LAYOUT_4) + self.start("4.5.11") + shutil.rmtree(self.source) + done = self.run_entrypoint("5.3.0") + self.assertNotEqual(done.returncode, 0) + self.assertEqual(self.shipped_files_in_the_volume(), set(LAYOUT_4)) + self.assertEqual(read_text(str(self.code / ".bootstrap.done")), "4.5.11") + + def test_an_image_older_than_the_recorded_release_refuses_to_replace_it(self): + self.ship(LAYOUT_5) + self.start("5.10.0") + self.ship(LAYOUT_4) + done = self.run_entrypoint("5.9.2") + self.assertNotEqual(done.returncode, 0) + self.assertIn("5.10.0", done.stderr) + self.assertEqual(self.shipped_files_in_the_volume(), set(LAYOUT_5)) + self.assertEqual(read_text(str(self.code / ".bootstrap.done")), "5.10.0") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-openbao/test_credential_rotation.py b/tests/unit/python/roles/web-app-openbao/test_credential_rotation.py index 4beccfb7b3..582607a82d 100644 --- a/tests/unit/python/roles/web-app-openbao/test_credential_rotation.py +++ b/tests/unit/python/roles/web-app-openbao/test_credential_rotation.py @@ -12,7 +12,7 @@ from __future__ import annotations import unittest -from jinja2 import Environment, FileSystemLoader, StrictUndefined +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape from utils.cache.files import read_text from utils.cache.yaml import load_yaml_any @@ -44,7 +44,7 @@ def jinja_env(searchpath) -> Environment: env = Environment( loader=FileSystemLoader(str(searchpath)), undefined=StrictUndefined, - autoescape=False, # noqa: S701 - renders HCL and dotenv, not markup + autoescape=select_autoescape(default_for_string=False), ) env.filters["bool"] = bool env.filters["dotenv_quote"] = lambda value: f'"{value}"' diff --git a/tests/unit/python/roles/web-app-openwebui/files/test_provision_mcp_grants.py b/tests/unit/python/roles/web-app-openwebui/files/test_provision_mcp_grants.py index 65304f0539..97205be309 100644 --- a/tests/unit/python/roles/web-app-openwebui/files/test_provision_mcp_grants.py +++ b/tests/unit/python/roles/web-app-openwebui/files/test_provision_mcp_grants.py @@ -465,7 +465,7 @@ class TestResolveApiKey(unittest.TestCase): modules = {} backend.install(modules) with patch.dict("sys.modules", modules): - return module, asyncio.run(module.resolve_api_key()) + return asyncio.run(module.resolve_api_key()) def test_an_existing_administrator_key_is_reused_and_kept(self) -> None: backend = FakeBackend( @@ -473,7 +473,7 @@ class TestResolveApiKey(unittest.TestCase): keys={"admin1": "sk-operator"}, ) - _module, (user_id, key, minted) = self._resolve(backend) + user_id, key, minted = self._resolve(backend) self.assertEqual("admin1", user_id) self.assertEqual("sk-operator", key) @@ -483,7 +483,7 @@ class TestResolveApiKey(unittest.TestCase): def test_a_missing_key_is_minted_and_marked_for_removal(self) -> None: backend = FakeBackend([FakeUser("admin1", "admin")]) - _module, (user_id, key, minted) = self._resolve(backend) + user_id, key, minted = self._resolve(backend) self.assertEqual("admin1", user_id) self.assertTrue(key.startswith("sk-")) @@ -493,7 +493,7 @@ class TestResolveApiKey(unittest.TestCase): def test_an_instance_without_users_gets_one_administrator(self) -> None: backend = FakeBackend([]) - _module, (user_id, _key, minted) = self._resolve(backend) + user_id, _key, minted = self._resolve(backend) self.assertEqual(["admin"], [user.role for user in backend.created]) self.assertEqual(backend.created[0].id, user_id) @@ -512,9 +512,8 @@ class TestResolveApiKey(unittest.TestCase): admin_id, _key, minted = asyncio.run(module.resolve_api_key()) self.assertTrue(minted) try: - exploding_grant(_key) - except RuntimeError: - pass + with self.assertRaises(RuntimeError): + exploding_grant(_key) finally: asyncio.run(module.drop_api_key(admin_id)) diff --git a/tests/unit/python/roles/web-app-prometheus/__init__.py b/tests/unit/python/roles/web-app-prometheus/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-prometheus/test_blackbox_ready_module.py b/tests/unit/python/roles/web-app-prometheus/test_blackbox_ready_module.py new file mode 100644 index 0000000000..c49856cbc6 --- /dev/null +++ b/tests/unit/python/roles/web-app-prometheus/test_blackbox_ready_module.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +import unittest + +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape + +from utils.cache.files import PROJECT_ROOT +from utils.cache.yaml import load_yaml_str + +TEMPLATE_DIR = PROJECT_ROOT / "roles/web-app-prometheus/templates/configuration" + + +def ready_module(*, tls_mode: str, prometheus_tls: bool, ca_injected: bool) -> dict: + def lookup(name, *terms): + if name == "tls" and terms[1] == "enabled": + return prometheus_tls + if name == "ca_injected": + return ca_injected + raise AssertionError(f"the template calls an unexpected lookup: {name!r}") + + env = Environment( + loader=FileSystemLoader(str(TEMPLATE_DIR)), + undefined=StrictUndefined, + autoescape=select_autoescape(), + ) + env.filters["bool"] = bool + rendered = env.get_template("blackbox.yml.j2").render( + lookup=lookup, + application_id="web-app-prometheus", + TLS_MODE=tls_mode, + ) + return load_yaml_str(rendered)["modules"]["http_ready"]["http"] + + +class TestBlackboxReadyModule(unittest.TestCase): + def test_an_http_target_passes_while_prometheus_itself_uses_tls(self): + module = ready_module( + tls_mode="letsencrypt", prometheus_tls=True, ca_injected=False + ) + self.assertIs(module["fail_if_not_ssl"], False) + + def test_certificates_are_verified_while_prometheus_itself_has_no_tls(self): + module = ready_module( + tls_mode="letsencrypt", prometheus_tls=False, ca_injected=False + ) + self.assertIs(module["tls_config"]["insecure_skip_verify"], False) + + def test_certificates_are_verified_once_the_private_ca_is_mounted(self): + module = ready_module( + tls_mode="self_signed", prometheus_tls=True, ca_injected=True + ) + self.assertIs(module["tls_config"]["insecure_skip_verify"], False) + + def test_verification_is_skipped_only_without_the_private_ca(self): + module = ready_module( + tls_mode="self_signed", prometheus_tls=False, ca_injected=False + ) + self.assertIs(module["tls_config"]["insecure_skip_verify"], True) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-prometheus/test_blackbox_targets.py b/tests/unit/python/roles/web-app-prometheus/test_blackbox_targets.py new file mode 100644 index 0000000000..abc914988d --- /dev/null +++ b/tests/unit/python/roles/web-app-prometheus/test_blackbox_targets.py @@ -0,0 +1,84 @@ +from __future__ import annotations + +import unittest + +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape + +from utils.cache.files import PROJECT_ROOT +from utils.cache.yaml import load_yaml_str + +TEMPLATE_DIR = PROJECT_ROOT / "roles/web-app-prometheus/templates/configuration" +ONION = "a" * 56 + ".onion" + +DOMAINS = { + "web-app-prometheus": [f"prometheus.{ONION}"], + "web-app-nextcloud": {"nextcloud": f"next.cloud.{ONION}"}, + "web-app-gitea": ["git.infinito.test"], + "web-svc-cdn": ["cdn.infinito.test"], + "svc-db-postgres": ["postgres.infinito.test"], +} +ROLES_WITH_THE_PROMETHEUS_SERVICE = ["web-app-nextcloud", "web-app-gitea"] + + +def lookup(name, *terms, **_kwargs): + if name == "domains": + return DOMAINS + if name == "roles_with_service": + return [{"id": role} for role in ROLES_WITH_THE_PROMETHEUS_SERVICE] + if name == "tls": + term, want = terms + scheme = "http" if term.endswith(".onion") else "https" + return { + "url.base": f"{scheme}://{term}/", + "protocols.web": "http", + "enabled": False, + }[want] + if name == "domain": + return DOMAINS[terms[0]][0] + if name == "scrape_target": + return f"{terms[1]}:9000" + if name == "native_metrics_apps": + return [] + raise AssertionError(f"the template calls an unexpected lookup: {name!r}") + + +def probed_targets() -> dict[str, list[str]]: + env = Environment( + loader=FileSystemLoader(str(TEMPLATE_DIR)), + undefined=StrictUndefined, + autoescape=select_autoescape(), + ) + env.filters["bool"] = bool + rendered = env.get_template("prometheus.yml.j2").render( + lookup=lookup, + application_id="web-app-prometheus", + CURRENT_PLAY_APPLICATIONS=list(DOMAINS), + DOMAIN_PRIMARY="infinito.test", + ALERT_RULES_CONFIG_DOCKER="/etc/prometheus/alert_rules.yml", + ) + jobs = {job["job_name"]: job for job in load_yaml_str(rendered)["scrape_configs"]} + return { + group["labels"]["app"]: group["targets"] + for group in jobs["blackbox-healthz"]["static_configs"] + } + + +class TestBlackboxTargets(unittest.TestCase): + def test_an_onion_app_is_probed_under_its_onion_name_over_http(self): + self.assertEqual( + probed_targets()["web-app-nextcloud"], + [f"http://next.cloud.{ONION}/healthz/ready"], + ) + + def test_a_clearnet_app_is_probed_under_its_own_scheme(self): + self.assertEqual( + probed_targets()["web-app-gitea"], + ["https://git.infinito.test/healthz/ready"], + ) + + def test_only_the_roles_the_service_lookup_names_are_probed(self): + self.assertEqual(set(probed_targets()), set(ROLES_WITH_THE_PROMETHEUS_SERVICE)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-stalwart/files/test_production_facts.py b/tests/unit/python/roles/web-app-stalwart/files/test_production_facts.py index 3c57b00f2e..1ef49c2119 100644 --- a/tests/unit/python/roles/web-app-stalwart/files/test_production_facts.py +++ b/tests/unit/python/roles/web-app-stalwart/files/test_production_facts.py @@ -5,8 +5,8 @@ import struct import sys import tempfile import unittest +import unittest.mock as mock from pathlib import Path -from unittest import mock from . import PROJECT_ROOT diff --git a/tests/unit/python/roles/web-app-stalwart/test_onion_route.py b/tests/unit/python/roles/web-app-stalwart/test_onion_route.py index cf6ad49854..296133e61b 100644 --- a/tests/unit/python/roles/web-app-stalwart/test_onion_route.py +++ b/tests/unit/python/roles/web-app-stalwart/test_onion_route.py @@ -12,7 +12,7 @@ from __future__ import annotations import json import unittest -from jinja2 import Environment, StrictUndefined +from jinja2 import Environment, StrictUndefined, select_autoescape from utils.cache.files import read_text from utils.cache.yaml import load_yaml_any @@ -34,7 +34,7 @@ def _render(template_path, **variables) -> str: trim_blocks=True, lstrip_blocks=True, undefined=StrictUndefined, - autoescape=False, # noqa: S701 - JMAP request bodies, never HTML + autoescape=select_autoescape(default_for_string=False), ) env.filters["to_json"] = json.dumps env.filters["int"] = int diff --git a/tests/unit/python/roles/web-app-stalwart/test_roundcube_oauth_scheme.py b/tests/unit/python/roles/web-app-stalwart/test_roundcube_oauth_scheme.py index 164ce94b0c..8261829975 100644 --- a/tests/unit/python/roles/web-app-stalwart/test_roundcube_oauth_scheme.py +++ b/tests/unit/python/roles/web-app-stalwart/test_roundcube_oauth_scheme.py @@ -16,7 +16,7 @@ from __future__ import annotations import unittest -from jinja2 import Environment, StrictUndefined +from jinja2 import Environment, StrictUndefined, select_autoescape from utils.cache.files import read_text @@ -41,7 +41,7 @@ def _render(base_url: str, *, sso_enabled: bool = True, socks_proxy: str = "") - trim_blocks=True, lstrip_blocks=True, undefined=StrictUndefined, - autoescape=False, # noqa: S701 - a PHP config file, and Ansible's templar does not escape either + autoescape=select_autoescape(default_for_string=False), ) env.filters["bool"] = bool return env.from_string(read_text(TEMPLATE)).render( diff --git a/tests/unit/python/utils/roles/test_guide.py b/tests/unit/python/utils/roles/test_guide.py index 49c3bcf1de..387edc71fd 100644 --- a/tests/unit/python/utils/roles/test_guide.py +++ b/tests/unit/python/utils/roles/test_guide.py @@ -1,6 +1,6 @@ import unittest +import unittest.mock as mock from typing import ClassVar -from unittest import mock from utils.cache.applications import get_variants from utils.roles.guide import guide_deployable, guide_variant, smallest_variant diff --git a/tests/unit/python/utils/tests/swarm/test_run_reporting.py b/tests/unit/python/utils/tests/swarm/test_run_reporting.py index ea14038c7a..a63de17fd7 100644 --- a/tests/unit/python/utils/tests/swarm/test_run_reporting.py +++ b/tests/unit/python/utils/tests/swarm/test_run_reporting.py @@ -1,7 +1,7 @@ import contextlib import io import unittest -from unittest import mock +import unittest.mock as mock from utils.tests.swarm import run diff --git a/tests/unit/python/utils/update/test_docker.py b/tests/unit/python/utils/update/test_docker.py index 4fac5a7802..b44f72ef2a 100644 --- a/tests/unit/python/utils/update/test_docker.py +++ b/tests/unit/python/utils/update/test_docker.py @@ -5,7 +5,33 @@ import unittest from pathlib import Path from utils.cache.files import read_text -from utils.update.docker import _registry_cursor, update_config_versions +from utils.roles.mapping import ROLE_FILE_META_SERVICES +from utils.update.docker import ( + _registry_cursor, + collect_entries, + sourced_services, + update_config_versions, +) + +SOURCED = """bundled: + image: example/app + version: v1.0.0 + update: + type: http_regex + url: https://example.invalid/bundle + pattern: "app:(v[0-9.]+)" +tracked: + image: example/side + version: v2.0.0 + other_version: v3.0.0 + update: + - key: other_version + type: git_tags + repository: https://example.invalid/side.git +plain: + image: example/plain + version: v4.0.0 +""" class TestRegistryCursor(unittest.TestCase): @@ -16,6 +42,20 @@ class TestRegistryCursor(unittest.TestCase): self.assertIsNone(_registry_cursor("19.1.1")) +class TestDeclaredSource(unittest.TestCase): + def test_a_version_with_its_own_source_is_left_to_that_source(self) -> None: + root = Path(tempfile.mkdtemp()) + config = root / "roles" / "web-app-example" / ROLE_FILE_META_SERVICES + config.parent.mkdir(parents=True) + config.write_text(SOURCED, encoding="utf-8") + + self.assertEqual(sourced_services(config), {"bundled"}) + self.assertEqual( + sorted(entry.service for entry in collect_entries(root)), + ["plain", "tracked"], + ) + + class TestUpdateDocker(unittest.TestCase): def test_update_config_versions_updates_only_target_services(self) -> None: original = """moodle: diff --git a/tests/unit/python/utils/update/test_fetch.py b/tests/unit/python/utils/update/test_fetch.py new file mode 100644 index 0000000000..066d306bc9 --- /dev/null +++ b/tests/unit/python/utils/update/test_fetch.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +import unittest +import unittest.mock as mock + +from utils.update import fetch as module + +BODIES = { + "https://example.test/tags": b"core v1.0.0", + "https://example.test/compose": b"image: example/app:v1.0.0-1.29", +} + + +class TestDocuments(unittest.TestCase): + def setUp(self) -> None: + module.document.cache_clear() + self.addCleanup(module.document.cache_clear) + + def test_several_documents_are_read_as_one_text(self) -> None: + with mock.patch.object(module, "get", side_effect=BODIES.__getitem__): + self.assertEqual( + module.documents(list(BODIES)), + "core v1.0.0\nimage: example/app:v1.0.0-1.29", + ) + self.assertEqual( + module.documents("https://example.test/tags"), "core v1.0.0" + ) + + def test_a_document_is_fetched_once_per_run(self) -> None: + with mock.patch.object(module, "get", side_effect=BODIES.__getitem__) as get: + module.documents(list(BODIES)) + module.documents("https://example.test/tags") + module.documents("https://example.test/compose") + + self.assertEqual(get.call_count, 2) + + def test_a_failed_fetch_is_tried_again(self) -> None: + with ( + mock.patch.object(module, "get", side_effect=OSError("down")), + self.assertRaises(OSError), + ): + module.documents("https://example.test/tags") + with mock.patch.object(module, "get", side_effect=BODIES.__getitem__): + self.assertEqual( + module.documents("https://example.test/tags"), "core v1.0.0" + ) + + +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 8a02846242..54734dc979 100644 --- a/tests/unit/python/utils/update/test_repository.py +++ b/tests/unit/python/utils/update/test_repository.py @@ -218,6 +218,44 @@ class TestApplyUpdates(unittest.TestCase): self.assertEqual(read_text(str(config_b)), " ref: v2.1.0\n") +SOURCED_FIRST = ( + "sourced:\n" + " repository: https://example.test/a.git\n" + " ref: v1.0.0\n" + " update:\n" + " key: ref\n" + " type: http_regex\n" + " url: https://example.test/tags\n" + " pattern: 'a (v[0-9.]+)'\n" + "plain:\n" + " repository: https://example.test/b.git\n" + " ref: v1.0.0\n" +) + + +class TestSourcedRef(unittest.TestCase): + def test_a_sourced_ref_is_skipped_and_keeps_its_own_line(self) -> None: + with tempfile.TemporaryDirectory() as tmpdir: + root = Path(tmpdir) + config = root / "roles" / "web-app-example" / ROLE_FILE_META_SERVICES + config.parent.mkdir(parents=True) + config.write_text(SOURCED_FIRST, encoding="utf-8") + + entries = collect_entries(root) + + self.assertEqual( + [(entry.entity_path, entry.line) for entry in entries], + [(("plain",), 11)], + ) + + apply_updates([RepositoryRefUpdate(entry=entries[0], latest="v1.1.0")]) + + written = config.read_text() # nocheck: cache-read just rewritten here + lines = written.splitlines() + self.assertEqual(lines[2], " ref: v1.0.0") + self.assertEqual(lines[10], " ref: v1.1.0") + + class TestCollectEntriesCoversAddons(unittest.TestCase): def _role(self, root: Path) -> Path: role = root / "roles" / "web-app-example" diff --git a/tests/unit/python/utils/update/test_source.py b/tests/unit/python/utils/update/test_source.py index a4043f28e5..e10f86c77f 100644 --- a/tests/unit/python/utils/update/test_source.py +++ b/tests/unit/python/utils/update/test_source.py @@ -84,6 +84,30 @@ update: } +COMPOUND = """\ +--- +bundle: + image: example/part + version: "v1.10.12-v3.0.23" + update: + type: http_regex + url: https://example.test/tags + pattern: 'core (?Pv[0-9.]+)\\npart (?Pv[0-9.]+)' + template: "{part}-{core}" +""" + +SUFFIXED = """\ +--- +bundle: + image: example/part + version: "v1.10.12-v3.0.23" + update: + type: http_regex + url: https://example.test/tags + pattern: 'part (v[0-9.]+-v[0-9.]+)' +""" + + def _repo(services: str = SERVICES) -> Path: tmp = Path(tempfile.mkdtemp()) config = tmp / "roles" / "web-app-example" / ROLE_FILE_META_SERVICES @@ -152,6 +176,36 @@ class TestOutdated(unittest.TestCase): self.assertEqual(module.outdated([self._entry(root)], root), []) +class TestTemplate(unittest.TestCase): + def _outdated(self, services: str, upstream: str) -> list[str]: + root = _repo(services) + with mock.patch.object(module, "documents", return_value=upstream): + updates = module.outdated(module.collect_entries(root), root) + return [update.latest for update in updates] + + def test_a_template_assembles_the_tag_from_several_upstream_values(self) -> None: + self.assertEqual( + self._outdated(COMPOUND, "core v3.0.39\npart v1.11.3\n"), + ["v1.11.3-v3.0.39"], + ) + + def test_a_templated_tag_moves_when_only_its_suffix_changed(self) -> None: + self.assertEqual( + self._outdated(COMPOUND, "core v3.0.39\npart v1.10.12\n"), + ["v1.10.12-v3.0.39"], + ) + + def test_an_unchanged_or_older_templated_tag_reports_nothing(self) -> None: + self.assertEqual(self._outdated(COMPOUND, "core v3.0.23\npart v1.10.12\n"), []) + self.assertEqual(self._outdated(COMPOUND, "core v3.0.23\npart v1.9.0\n"), []) + + def test_without_a_template_a_changed_suffix_is_another_flavour(self) -> None: + self.assertEqual(self._outdated(SUFFIXED, "part v1.11.3-v3.0.39\n"), []) + self.assertEqual( + self._outdated(SUFFIXED, "part v1.11.3-v3.0.23\n"), ["v1.11.3-v3.0.23"] + ) + + 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/update/base.py b/utils/update/base.py index 892cbd7be3..8d17c89616 100644 --- a/utils/update/base.py +++ b/utils/update/base.py @@ -92,6 +92,40 @@ def latest_semver(tags: list[str], depth: int, flavor: str = "") -> str | None: return max(candidates, key=version_key, default=None) +def captured_versions(body: str, pattern: str, template: str = "") -> list[str]: + """Return the version every match of a pattern names. + + Args: + body: text to search. + pattern: regular expression; its first group is the version. + template: when set, a ``str.format`` template over the pattern's named + groups that assembles the version instead, for a tag built from + several upstream values. + """ + return [ + template.format(**match.groupdict()) if template else match.group(1) + for match in re.finditer(pattern, body) + ] + + +def newer_version(current: str, found: list[str], assembled: bool) -> str | None: + """Return the version *current* should move to, or ``None``. + + Args: + current: the pinned version. + found: every version the upstream offers. + assembled: *found* was built from several upstream values, so a + changed suffix is a move and not another flavour. + """ + if assembled: + newest = max(filter(is_semver, found), key=version_key, default=None) + moved = newest not in (None, current) + else: + newest = latest_semver(found, version_depth(current), version_flavor(current)) + moved = bool(newest) and version_key(current) != version_key(newest) + return newest if moved and version_key(current) <= version_key(newest) else None + + def resolve_max_fetch_workers() -> int: return int(os.environ["INFINITO_WORKER_FETCH"]) @@ -105,3 +139,19 @@ def is_maintained(roles_root: Path, role: str) -> bool: """ lifecycle = get_role_lifecycle(roles_root / role, role_name=role) return lifecycle not in UNMAINTAINED_LIFECYCLES + + +def declares_source(config: object, key: str) -> bool: + """Report whether a services entity names its own upstream for a pin. + + Args: + config: one entity of ``meta/services.yml``. + key: the pinned key; an ``update:`` block without ``key`` names + ``version``. + """ + declared = config.get("update") if isinstance(config, dict) else None + sources = declared if isinstance(declared, list) else [declared] + return any( + isinstance(source, dict) and source.get("key", "version") == key + for source in sources + ) diff --git a/utils/update/docker.py b/utils/update/docker.py index 65af50cd0d..7c44bed6bf 100644 --- a/utils/update/docker.py +++ b/utils/update/docker.py @@ -8,6 +8,9 @@ walker that rewrites the matching ``version:`` line. Suppress a check by placing ``# nocheck: docker-version`` on the line directly above the ``version:`` key. + +A ``version`` that names its own upstream in an ``update:`` block belongs to +:mod:`utils.update.source` and is not collected here. """ from __future__ import annotations @@ -28,6 +31,7 @@ import yaml from utils.annotations.suppress import is_suppressed_at from utils.cache.files import read_text +from utils.cache.yaml import load_yaml from utils.docker.image.discovery import iter_role_images from utils.docker.image.ref import ( DOCKER_HUB_REGISTRIES, @@ -38,6 +42,7 @@ from utils.docker.image.ref import ( from utils.docker.registry import fetch_registry_tags from utils.roles.mapping import ROLE_FILE_META_SERVICES from utils.update.base import ( + declares_source, is_maintained, is_semver, latest_semver, @@ -265,6 +270,20 @@ def suppressed_services(config_path: Path) -> set[str]: return names +def sourced_services(config_path: Path) -> set[str]: + """Return service names whose ``version`` declares its own upstream. + + Args: + config_path: a role's ``meta/services.yml``. + """ + services = load_yaml(str(config_path)) or {} + return { + str(service) + for service, config in services.items() + if declares_source(config, "version") + } + + def collect_entries(repo_root: Path) -> list[DockerImageVersionEntry]: roles_root = repo_root / "roles" entries: list[DockerImageVersionEntry] = [] @@ -280,6 +299,8 @@ def collect_entries(repo_root: Path) -> list[DockerImageVersionEntry]: config_path = roles_root / ref.role / ROLE_FILE_META_SERVICES if ref.service in suppressed_services(config_path): continue + if ref.service in sourced_services(config_path): + continue if ref.registry == "docker.io": image = ref.name diff --git a/utils/update/fetch.py b/utils/update/fetch.py new file mode 100644 index 0000000000..fa25655fd4 --- /dev/null +++ b/utils/update/fetch.py @@ -0,0 +1,46 @@ +"""Read the documents a declared version source names. + +Every document is fetched once per run, so the pins that read the same release +manifest resolve against one snapshot of it. +""" + +from __future__ import annotations + +import functools +import urllib.request + +TIMEOUT_SECONDS = 30 +USER_AGENT = "infinito-nexus-version-source" + + +def get(url: str, headers: dict[str, str] | None = None) -> bytes: + """Return the body of a declared version source. + + Args: + url: https URL to read. + headers: request headers beside the user agent. + """ + request = urllib.request.Request( # noqa: S310 - https URL of a declared version source + url, headers={"User-Agent": USER_AGENT, **(headers or {})} + ) + with urllib.request.urlopen( # noqa: S310 - https URL of a declared version source + request, timeout=TIMEOUT_SECONDS + ) as response: + return response.read() + + +@functools.cache +def document(url: str) -> str: + """Return the text of *url*, fetched once per run.""" + return get(url).decode("utf-8", "replace") + + +def documents(urls: str | list[str]) -> str: + """Return the text of one URL, or of several as one text. + + Args: + urls: a URL, or several whose bodies are searched together. + """ + return "\n".join( + document(url) for url in ([urls] if isinstance(urls, str) else urls) + ) diff --git a/utils/update/repository.py b/utils/update/repository.py index c0511a362c..0b81bf2612 100644 --- a/utils/update/repository.py +++ b/utils/update/repository.py @@ -17,6 +17,9 @@ reused for every entry pointing at the same repo. Suppress a check by placing ``# nocheck: repository-version`` on the line directly above the `ref:` key. + +A `ref:` that names its own upstream in an ``update:`` block belongs to +:mod:`utils.update.source` and is not collected here. """ from __future__ import annotations @@ -32,6 +35,7 @@ from utils.cache.files import read_text from utils.cache.yaml import load_yaml_any from utils.roles.mapping import ROLE_DIR_META_ADDONS, ROLE_FILE_META_SERVICES from utils.update.base import ( + declares_source, is_maintained, is_semver, latest_semver, @@ -70,23 +74,32 @@ class RepositoryRefUpdate: latest: str +def _walk( + node, path: tuple[str, ...] +) -> Iterator[tuple[tuple[str, ...], str, str, dict]]: + """Yield ``(entity_path, repository, ref, entity)`` for every dict in + the tree that declares both keys with truthy string values.""" + if isinstance(node, dict): + repo = node.get("repository") + ref = node.get("ref") + if isinstance(repo, str) and repo and isinstance(ref, str) and ref: + yield (path, repo.strip(), ref.strip(), node) + for key, value in node.items(): + if key in ("repository", "ref"): + continue + yield from _walk(value, (*path, str(key))) + elif isinstance(node, list): + for index, item in enumerate(node): + yield from _walk(item, (*path, f"[{index}]")) + + def walk_repo_ref_pairs( node, path: tuple[str, ...] ) -> Iterator[tuple[tuple[str, ...], str, str]]: """Yield ``(entity_path, repository, ref)`` for every dict in the tree that declares both keys with truthy string values.""" - if isinstance(node, dict): - repo = node.get("repository") - ref = node.get("ref") - if isinstance(repo, str) and repo and isinstance(ref, str) and ref: - yield (path, repo.strip(), ref.strip()) - for key, value in node.items(): - if key in ("repository", "ref"): - continue - yield from walk_repo_ref_pairs(value, (*path, str(key))) - elif isinstance(node, list): - for index, item in enumerate(node): - yield from walk_repo_ref_pairs(item, (*path, f"[{index}]")) + for entity_path, repo, ref, _entity in _walk(node, path): + yield (entity_path, repo, ref) def git_ls_remote_tags(url: str) -> list[str]: @@ -171,14 +184,14 @@ def _entries_of_file( suppressed = suppressed_ref_lines(config_path) entries: list[RepositoryRefEntry] = [] - for entity_path, repo, ref in walk_repo_ref_pairs(data, entity_prefix): + for entity_path, repo, ref, entity in _walk(data, entity_prefix): if not is_semver(ref): continue candidates = ref_line_index.get(ref) or [] if not candidates: continue line_no = candidates.pop(0) - if line_no in suppressed: + if line_no in suppressed or declares_source(entity, "ref"): continue entries.append( RepositoryRefEntry( diff --git a/utils/update/source.py b/utils/update/source.py index cf6d4bd546..0cf9166337 100644 --- a/utils/update/source.py +++ b/utils/update/source.py @@ -15,8 +15,9 @@ upstream lives:: ``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`` (url, pattern) and ``script`` (path, run with the current -version and printing the latest one). +``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). An addon in ``meta/addons/.yml`` declares the same fields in its ``update:`` block, beside ``monitored``, ``catalog`` and ``upstream_id``. A @@ -31,7 +32,6 @@ import json import re import subprocess import urllib.error -import urllib.request from dataclasses import dataclass from typing import TYPE_CHECKING, Any from urllib.parse import urlencode @@ -42,12 +42,10 @@ from utils.cache.yaml import load_yaml from utils.roles.mapping import ROLE_FILE_META_SERVICES from utils.update.addons import GITHUB_RELEASES_CATALOG, iter_addon_files from utils.update.base import ( + captured_versions, is_maintained, is_semver, - latest_semver, - version_depth, - version_flavor, - version_key, + newer_version, ) from utils.update.docker import ( dockerhub_repo, @@ -58,6 +56,7 @@ from utils.update.docker import ( is_ghcr, is_mcr, ) +from utils.update.fetch import TIMEOUT_SECONDS, documents, get from utils.update.repository import git_ls_remote_tags if TYPE_CHECKING: @@ -68,9 +67,7 @@ NOCHECK_MARKER = "version-source" UNWATCHED_MARKER = "unwatched-version" UPDATE_KEY = "update" DEFAULT_KEY = "version" -TIMEOUT_SECONDS = 30 TYPES = ("git_tags", "registry_tags", "npm", "http_regex", "script") -USER_AGENT = "infinito-nexus-version-source" @dataclass(frozen=True) @@ -104,16 +101,6 @@ class VersionSourceUpdate: latest: str -def _get(url: str, headers: dict[str, str] | None = None) -> bytes: - request = urllib.request.Request( # noqa: S310 - https URL of a declared version source - url, headers={"User-Agent": USER_AGENT, **(headers or {})} - ) - with urllib.request.urlopen( # noqa: S310 - https URL of a declared version source - request, timeout=TIMEOUT_SECONDS - ) as response: - return response.read() - - def dockerhub_named_tags(image: str, match: str) -> list[str]: """Return the Docker Hub tags of *image* whose name contains *match*. @@ -125,7 +112,7 @@ def dockerhub_named_tags(image: str, match: str) -> list[str]: query = urlencode({"name": match, "page_size": 100}) url = f"https://hub.docker.com/v2/repositories/{dockerhub_repo(image)}/tags?{query}" try: - payload = json.loads(_get(url)) + payload = json.loads(get(url)) except (OSError, ValueError): return [] return [str(result["name"]) for result in payload.get("results") or []] @@ -151,7 +138,7 @@ def registry_v2_tags(image: str, match: str = "") -> list[str]: host, _, repository = image.partition("/") url = f"https://{host}/v2/{repository}/tags/list" try: - return list(json.loads(_get(url)).get("tags") or []) + return list(json.loads(get(url)).get("tags") or []) except urllib.error.HTTPError as error: if error.code != 401: return [] @@ -164,8 +151,8 @@ def registry_v2_tags(image: str, match: str = "") -> list[str]: return [] query = "&".join(f"{name}={value}" for name, value in fields.items()) try: - token = json.loads(_get(f"{realm}?{query}")).get("token", "") - payload = _get(url, {"Authorization": f"Bearer {token}"}) + token = json.loads(get(f"{realm}?{query}")).get("token", "") + payload = get(url, {"Authorization": f"Bearer {token}"}) return list(json.loads(payload).get("tags") or []) except (OSError, ValueError): return [] @@ -174,19 +161,21 @@ def registry_v2_tags(image: str, match: str = "") -> list[str]: def npm_versions(package: str) -> list[str]: """Return every published version of an npm *package*.""" try: - payload = json.loads(_get(f"https://registry.npmjs.org/{package}")) + payload = json.loads(get(f"https://registry.npmjs.org/{package}")) except (OSError, ValueError): return [] return list((payload.get("versions") or {}).keys()) -def http_regex_versions(url: str, pattern: str) -> list[str]: - """Return every capture of *pattern* in the body of *url*.""" +def http_regex_versions( + urls: str | list[str], pattern: str, template: str = "" +) -> list[str]: + """Return every version *pattern* names in the documents at *urls*.""" try: - body = _get(url).decode("utf-8", "replace") + body = documents(urls) except OSError: return [] - return [match.group(1) for match in re.finditer(pattern, body)] + return captured_versions(body, pattern, template) def script_versions(repo_root: Path, role: str, path: str, current: str) -> list[str]: @@ -228,7 +217,11 @@ def candidates(entry: VersionSourceEntry, repo_root: Path) -> list[str]: elif kind == "npm": found = npm_versions(str(source["package"])) elif kind == "http_regex": - found = http_regex_versions(str(source["url"]), str(source["pattern"])) + found = http_regex_versions( + source["url"], + str(source["pattern"]), + str(source.get("template", "")), + ) elif kind == "script": found = script_versions( repo_root, entry.role, str(source["path"]), entry.current @@ -460,12 +453,12 @@ def outdated( """Return one update per entry whose source offers a newer version.""" updates: list[VersionSourceUpdate] = [] for entry in entries: - newest = latest_semver( + newest = newer_version( + entry.current, candidates(entry, repo_root), - version_depth(entry.current), - version_flavor(entry.current), + assembled=bool(entry.source.get("template")), ) - if newest and version_key(entry.current) < version_key(newest): + if newest: updates.append(VersionSourceUpdate(entry=entry, latest=newest)) return updates