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..3991767cf4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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/roles/svc-ai-ollama/meta/services.yml b/roles/svc-ai-ollama/meta/services.yml index b60dc775cc..10de306f04 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.1 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/web-app-bigbluebutton/meta/services.yml b/roles/web-app-bigbluebutton/meta/services.yml index ffe9f17949..787197db53 100644 --- a/roles/web-app-bigbluebutton/meta/services.yml +++ b/roles/web-app-bigbluebutton/meta/services.yml @@ -100,55 +100,55 @@ prometheus: # nocheck: dynamic-flag: fixed upstream-compose sub-service, not group-gated bbb-web: image: alangecker/bbb-docker-web - version: "v3.0.23" + version: "v3.0.23" # nocheck: docker-version: one release set with bigbluebutton.ref 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" + version: "v1.10.12-v3.0.23" # nocheck: docker-version: one release set with bigbluebutton.ref 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" + version: "v3.0.23-v5.4.4-1.29" # nocheck: docker-version: one release set with bigbluebutton.ref 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" + version: "2.4.2-s8328b77-p88f3f6b" # nocheck: docker-version: one release set with bigbluebutton.ref 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" + version: "v1.5.8" # nocheck: docker-version: one release set with bigbluebutton.ref 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" + version: "v3.0.23" # nocheck: docker-version: one release set with bigbluebutton.ref 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" + version: "v2.22.0" # nocheck: docker-version: one release set with bigbluebutton.ref 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" + version: "v3.0.23" # nocheck: docker-version: one release set with bigbluebutton.ref 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" + version: "v3.0.23" # nocheck: docker-version: one release set with bigbluebutton.ref 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 @@ -159,37 +159,37 @@ bbb-graphql-server: timeout: 10s retries: 5 image: alangecker/bbb-docker-graphql-server - version: "v3.0.23" + version: "v3.0.23" # nocheck: docker-version: one release set with bigbluebutton.ref 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" + version: "v3.0.23" # nocheck: docker-version: one release set with bigbluebutton.ref 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" + version: "v3.0.23" # nocheck: docker-version: one release set with bigbluebutton.ref 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" + version: "v3.0.0" # nocheck: docker-version: one release set with bigbluebutton.ref 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" + version: "v3.0.23" # nocheck: docker-version: one release set with bigbluebutton.ref 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" + version: "v0.14.0" # nocheck: docker-version: one release set with bigbluebutton.ref 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-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/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/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 7baefdccaa..214c63294f 100644 --- a/roles/web-app-moodle/vars/main.yml +++ b/roles/web-app-moodle/vars/main.yml @@ -63,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-opentalk/meta/services.yml b/roles/web-app-opentalk/meta/services.yml index 38ceb548c3..949d42f490 100644 --- a/roles/web-app-opentalk/meta/services.yml +++ b/roles/web-app-opentalk/meta/services.yml @@ -96,7 +96,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 diff --git a/roles/web-app-pixelfed/meta/services.yml b/roles/web-app-pixelfed/meta/services.yml index 5a60ba5576..9932025adb 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: "20261006" + version: "20261007" name: pixelfed min_storage: 588MB backup: diff --git a/roles/web-app-socialhome/meta/services.yml b/roles/web-app-socialhome/meta/services.yml index b1f16bcb44..44f07fe13d 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.7" ports: local: http: 8089 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/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/vars/main.yml b/roles/web-app-suitecrm/vars/main.yml index fca35e9cd1..2b1708dfdd 100644 --- a/roles/web-app-suitecrm/vars/main.yml +++ b/roles/web-app-suitecrm/vars/main.yml @@ -13,6 +13,7 @@ SUITECRM_BASE_VERSION: "{{ lookup('config', application_id, 'services.' ~ entity SUITECRM_APP_VERSION: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.app_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/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); + } +}