From d5fbd741bc47c38040b05dbb6e66b26b45c8ecae Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 2 Apr 2026 01:02:43 +0200 Subject: [PATCH 01/55] docs(requirements): add service registry refactoring requirement Co-Authored-By: Claude Sonnet 4.6 --- .../001-service-registry-refactoring.md | 218 ++++++++++++++++++ 1 file changed, 218 insertions(+) create mode 100644 docs/requirements/001-service-registry-refactoring.md diff --git a/docs/requirements/001-service-registry-refactoring.md b/docs/requirements/001-service-registry-refactoring.md new file mode 100644 index 0000000000..4e18c4cb2d --- /dev/null +++ b/docs/requirements/001-service-registry-refactoring.md @@ -0,0 +1,218 @@ +# 001 - Service Registry Refactoring + +## User Story + +As a contributor, I want service configuration to be fully role-local so that +`group_vars/all/20_services.yml` is no longer needed and every role is +self-describing. + +## Acceptance Criteria + +- [ ] `group_vars/all/20_services.yml` is deleted; no role or plugin reads from it. +- [ ] Every service role declares its service metadata in its own `config/main.yml` + under `compose.services.` (with optional `provides:`, `canonical:`) + instead of in the central registry. +- [ ] Load order *within* the same deploy type (universal, workstation, server) is + declared via a custom `run_after:` list in the role's `meta/main.yml`. Each + entry is a role name (e.g. `web-svc-cdn`). `roles/sys-utils-service-loader` + MUST read this field and load the listed roles before the declaring role within + the same deploy-type pass. This is a project-specific convention — Ansible does + not process `run_after:` natively. + Cross-type dependencies are handled implicitly by stage ordering: + `roles/sys-utils-service-loader` runs in the constructor stage and loads all + services (databases, `web-app-keycloak` via `provides: oidc`, etc.) before + apps are deployed in the server stage. Apps MUST NOT declare `run_after:` + entries for services of a different deploy type, and MUST NOT require the user + to list those dependencies explicitly in `APPS`. +- [ ] The special `role_template: "svc-db-{type}"` database loading logic is removed; + PostgreSQL and MariaDB are defined as regular services in their own + `config/main.yml` (same as any other service). Because databases are a different + deploy type from apps, they are loaded automatically before apps by + `roles/sys-utils-service-loader` — no `run_after:` declaration is needed in + the app. + + **Before:** + ```yaml + # group_vars/all/20_services.yml + SERVICE_REGISTRY: + database: + role_template: "svc-db-{type}" # resolved at runtime from app config + type: backend + + # web-app-matomo/config/main.yml + compose: + services: + database: + shared: true + type: "mariadb" # drives role_template resolution + enabled: true + ``` + + **After:** + ```yaml + # svc-db-mariadb/config/main.yml — self-describing, no central registry entry + compose: + services: + mariadb: + shared: true + enabled: true + + # svc-db-postgres/config/main.yml + compose: + services: + postgres: + shared: true + enabled: true + + # web-app-matomo/config/main.yml — no database.type needed for service loading + # (svc-db-mariadb is loaded automatically before web-app-* by the service loader) + ``` +- [ ] `frontend` / `backend` type is auto-detected from the role name prefix + (`web-app-*`, `web-svc-*` → frontend; everything else → backend) so the + `type:` field in `config/main.yml` becomes optional. +- [ ] `canonical` aliases are declared under `compose.services..canonical` + in the role's `config/main.yml`, where `` is the entity name + returned by the existing `get_entity_name` function for that role + (e.g. `web-svc-cdn` exposes the primary entity `cdn` plus the alias + entities `css` and `javascript`): + ```yaml + compose: + services: + cdn: + shared: true + enabled: true + css: + shared: true + enabled: true + canonical: cdn + javascript: + shared: true + enabled: true + canonical: cdn + ``` +- [ ] A role MAY declare an optional `provides:` field under its primary service entry + in `config/main.yml`. When present, `roles/sys-utils-service-loader` registers + the role under that functional name instead of the entity name returned by + `get_entity_name`. Roles without `provides:` are registered under their entity + name by default. Examples: + ```yaml + # web-app-keycloak/config/main.yml + compose: + services: + keycloak: + shared: true + enabled: true + provides: oidc + + # web-app-mailu/config/main.yml + compose: + services: + mailu: + shared: true + enabled: true + provides: email + + # svc-db-openldap/config/main.yml + compose: + services: + openldap: + shared: true + enabled: true + provides: ldap + ``` + All consumers (templates, lookups, `run_after:` lists) continue to reference + the functional name (e.g. `oidc`, `email`, `ldap`) — no consumer changes are + required for roles that already use these names. +- [ ] `roles/sys-utils-service-loader` is the single place that loads all services. + It MUST use the existing function that determines which roles are universal, + workstation, or server to derive the load order: universal roles first, + then `web-svc-*`, then `web-app-*`. +- [ ] `roles/sys-utils-service-loader` is invoked from the constructor stage + (`tasks/stages/01_constructor.yml`) instead of the server block + (`tasks/stages/02_server.yml`). +- [ ] All service dependencies — including databases (e.g. `svc-db-mariadb`, + `svc-db-postgres`) and shared services (e.g. `web-app-keycloak`) — are loaded + automatically by `roles/sys-utils-service-loader` in the constructor stage. + No service dependency MUST ever require the user to list it explicitly in `APPS`. +- [ ] Every file that currently reads from `SERVICE_REGISTRY` or `20_services.yml` + MUST be updated to discover service metadata from role `config/main.yml` files + instead. This includes at minimum: + - `plugins/lookup/service.py` + - `plugins/lookup/applications_current_play.py` + - any filter plugin, task, or template that references `SERVICE_REGISTRY` +- [ ] New unit and integration tests MUST be written for the service discovery + mechanism that replaces `SERVICE_REGISTRY`. Follow the rules in + [testing.md](../agents/action/testing.md), + [unit.md](../contributing/code/tests/unit.md), and + [integration.md](../contributing/code/tests/integration.md). + Tests MUST cover at minimum: + - Discovery of `provides:`, `canonical:`, `shared:`, `enabled:` from role + `config/main.yml` + - Correct load order produced by `sys-utils-service-loader` + - `get_entity_name` derivation for all relevant role name prefixes + - `run_after:` ordering within the same deploy type +- [ ] All existing integration and unit tests pass after the refactoring. +- [ ] Once all other Acceptance Criteria are checked off and the full validation + app set deploys successfully, `docs/contributing/code/services.md` MUST be + updated to reflect the new role-local configuration model. The update MUST + follow the documentation guidelines in + [documentation.md](../documentation.md). + +## Validation Apps + +The following app selection MUST be used to validate the refactoring end to end. +It covers all relevant service categories and dependency patterns: + +| App | Purpose | +|---|---| +| `web-svc-cdn` | Frontend svc with canonical aliases (`css`, `javascript`) | +| `web-svc-file` | Simplest frontend svc — baseline auto-detection | +| `web-app-dashboard` | Frontend web-app consuming multiple services | +| `svc-db-postgres` | Database as a regular service (replaces `role_template`) — deployed standalone to verify the DB-as-service pattern directly | +| `svc-db-mariadb` | MariaDB as a regular service — deployed standalone alongside postgres to verify both database types independently | +| `web-app-matomo` | web-app with MariaDB dependency — tests automatic cross-type service loading | +| `web-app-gitea` | web-app with Keycloak (OIDC) dependency | +| `web-app-nextcloud` | Complex app with both MariaDB and Keycloak — depends on all of the above | + +```bash +APPS="web-svc-cdn web-svc-file web-app-dashboard svc-db-postgres svc-db-mariadb web-app-matomo web-app-gitea web-app-nextcloud" \ + make deploy-fresh-purged-apps +``` + +## Prerequisites + +Before starting any implementation work, you MUST read [AGENTS.md](../../../AGENTS.md) +and follow all instructions in it. + +## Implementation Strategy + +Iterate over each app individually, starting with the most complex and working down to the simplest. +Every app in the Validation Apps table MUST be deployed standalone at least once during the iteration. +After completing one full iteration cycle over all apps, restart from the top until every app works +and all Acceptance Criteria are checked off. + +**Iteration order (largest → smallest):** + +1. `web-app-nextcloud` — most complex; MariaDB + Keycloak + many service dependencies +2. `web-app-gitea` — Keycloak (OIDC) dependency +3. `web-app-matomo` — MariaDB dependency — tests automatic cross-type service loading +4. `web-app-dashboard` — frontend web-app consuming multiple services +5. `svc-db-postgres` — database as a regular service +6. `svc-db-mariadb` — MariaDB as a regular service, standalone validation +7. `web-svc-cdn` — canonical aliases (`css`, `javascript`) +8. `web-svc-file` — simplest frontend service; baseline + +**Per-app cycle:** + +For every app in the iteration order, run the full loop described in +[iteration.md](../agents/action/iteration.md) independently — as if starting fresh for +that app. Do not carry over assumptions from the previous app. + +1. Read [iteration.md](../agents/action/iteration.md) before starting each app. +2. Implement the role-local changes for the current app. +3. Deploy: `APPS= make deploy-fresh-purged-apps` +4. Follow the inspect-fix-redeploy loop from [iteration.md](../agents/action/iteration.md) until the app works end to end. +5. Run `make test` — all tests MUST pass before moving to the next app. +6. Check off the relevant Acceptance Criteria above if fully covered by this app. + +Repeat the full cycle from `web-app-nextcloud` down to `web-svc-file` until every criterion is checked. From bc20b295dd3b99491ed084429afc55ed563ea73b Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 2 Apr 2026 01:05:51 +0200 Subject: [PATCH 02/55] docs(requirements): require simplification of all touched files per principles.md Co-Authored-By: Claude Sonnet 4.6 --- docs/requirements/001-service-registry-refactoring.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/requirements/001-service-registry-refactoring.md b/docs/requirements/001-service-registry-refactoring.md index 4e18c4cb2d..d6c9fbdbc8 100644 --- a/docs/requirements/001-service-registry-refactoring.md +++ b/docs/requirements/001-service-registry-refactoring.md @@ -151,6 +151,11 @@ self-describing. - Correct load order produced by `sys-utils-service-loader` - `get_entity_name` derivation for all relevant role name prefixes - `run_after:` ordering within the same deploy type +- [ ] Every file and role that is modified as part of this refactoring MUST also be + simplified and refactored where possible, following the principles in + [principles.md](../contributing/code/principles.md). Do not limit changes to + the minimum required — use the mandatory touch as an opportunity to improve + clarity, reduce duplication, and remove dead code in the same pass. - [ ] All existing integration and unit tests pass after the refactoring. - [ ] Once all other Acceptance Criteria are checked off and the full validation app set deploys successfully, `docs/contributing/code/services.md` MUST be From e5a30262aabb6837110a7a52bd56cb6614c1730b Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 2 Apr 2026 01:12:29 +0200 Subject: [PATCH 03/55] docs(requirements): clarify service registry refactoring rules --- .../001-service-registry-refactoring.md | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/docs/requirements/001-service-registry-refactoring.md b/docs/requirements/001-service-registry-refactoring.md index d6c9fbdbc8..61a9545d4d 100644 --- a/docs/requirements/001-service-registry-refactoring.md +++ b/docs/requirements/001-service-registry-refactoring.md @@ -22,8 +22,10 @@ self-describing. `roles/sys-utils-service-loader` runs in the constructor stage and loads all services (databases, `web-app-keycloak` via `provides: oidc`, etc.) before apps are deployed in the server stage. Apps MUST NOT declare `run_after:` - entries for services of a different deploy type, and MUST NOT require the user - to list those dependencies explicitly in `APPS`. + entries for services of a different deploy type. If a role declares such a + cross-type dependency, `roles/sys-utils-service-loader` MUST fail hard with a + clear error instead of ignoring it. Apps MUST NOT require the user to list + those dependencies explicitly in `APPS`. - [ ] The special `role_template: "svc-db-{type}"` database loading logic is removed; PostgreSQL and MariaDB are defined as regular services in their own `config/main.yml` (same as any other service). Because databases are a different @@ -68,8 +70,10 @@ self-describing. # (svc-db-mariadb is loaded automatically before web-app-* by the service loader) ``` - [ ] `frontend` / `backend` type is auto-detected from the role name prefix - (`web-app-*`, `web-svc-*` → frontend; everything else → backend) so the - `type:` field in `config/main.yml` becomes optional. + (`web-app-*`, `web-svc-*` → frontend; everything else → backend). The + `type:` field for this purpose is removed from role `config/main.yml`. + No legacy support is kept for role-local service metadata that still declares + this `type:` field. - [ ] `canonical` aliases are declared under `compose.services..canonical` in the role's `config/main.yml`, where `` is the entity name returned by the existing `get_entity_name` function for that role @@ -94,7 +98,9 @@ self-describing. in `config/main.yml`. When present, `roles/sys-utils-service-loader` registers the role under that functional name instead of the entity name returned by `get_entity_name`. Roles without `provides:` are registered under their entity - name by default. Examples: + name by default. `provides:` MUST only be declared when the desired functional + name differs from the entity name; otherwise the role MUST rely on the default + entity name and omit `provides:`. Examples: ```yaml # web-app-keycloak/config/main.yml compose: From 9095a54b3d474e69472340959b5ce27c74729b83 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 2 Apr 2026 01:54:15 +0200 Subject: [PATCH 04/55] docs(agents): require make test before every deploy in iteration loop Co-Authored-By: Claude Sonnet 4.6 --- docs/agents/action/iteration.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/agents/action/iteration.md b/docs/agents/action/iteration.md index 921fdae03f..7cb009f0c8 100644 --- a/docs/agents/action/iteration.md +++ b/docs/agents/action/iteration.md @@ -4,6 +4,7 @@ Use this page when you are iterating on a local app deploy during debugging or d ## Loop +- You MUST run `make test` before every deploy. Only proceed with the deploy if all tests pass. - Unless the user explicitly says to reuse the existing setup, you MUST start once with `APPS= make deploy-fresh-purged-apps` to establish the baseline inventory and clean app state. Set `FULL_CYCLE=true` to also run the async update pass (pass 2). - To speed up debugging, you MAY pass multiple apps at once, e.g. `APPS=" " make deploy-fresh-purged-apps`. - After that, you MUST use `APPS= make deploy-reuse-kept-apps` for the default edit-fix-redeploy loop. From ad280a891b79fba323dbab8ee2e7051973cc1cde Mon Sep 17 00:00:00 2001 From: Environment Test Date: Sat, 11 Apr 2026 14:57:11 +0200 Subject: [PATCH 05/55] docs(requirements): add turn relay req --- .../requirements/001-nextcloud-talk-turn-relay.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 docs/requirements/001-nextcloud-talk-turn-relay.md diff --git a/docs/requirements/001-nextcloud-talk-turn-relay.md b/docs/requirements/001-nextcloud-talk-turn-relay.md new file mode 100644 index 0000000000..4dd4522c2a --- /dev/null +++ b/docs/requirements/001-nextcloud-talk-turn-relay.md @@ -0,0 +1,15 @@ +# 001 - Nextcloud Talk TURN relay + +## User Story + +As an administrator, I want Nextcloud Talk to use a dedicated TURN server so that calls with six or more participants remain stable for clients behind NAT or restrictive firewalls. + +## Acceptance Criteria + +- [ ] A dedicated TURN server is deployed for Nextcloud Talk via `web-svc-coturn` and is reachable externally for STUN/TURN traffic. +- [ ] Nextcloud Talk no longer uses the HPB endpoint on port `3480` for STUN/TURN and instead uses the dedicated TURN host, port, and shared secret. +- [ ] The required firewall rules are present for the TURN service ports and relay UDP range used by the deployment. +- [ ] The Nextcloud Talk administration view shows a valid STUN/TURN configuration without related errors. +- [ ] Calls with at least six participants complete reliably without missing video streams, partial connections, or browser-side ICE connection failures caused by missing relay candidates. +- [ ] Implementation and validation for `web-app-nextcloud` follow the local iteration loop from [iteration.md](../agents/action/iteration.md), starting with `APPS=web-app-nextcloud make deploy-fresh-purged-apps` for the baseline and continuing with `APPS=web-app-nextcloud make deploy-reuse-kept-apps` for normal follow-up iterations. +- [ ] The existing role-local Playwright coverage in [playwright.spec.js](../../roles/web-app-nextcloud/files/playwright.spec.js) and [playwright.env.j2](../../roles/web-app-nextcloud/templates/playwright.env.j2) is extended as far as the local setup allows, and when `compose.services.talk.enabled` is true the Playwright flow verifies in the Nextcloud admin interface that the Talk-related TURN/STUN integration is implemented correctly. From 7fa51003a945d04982550a6ad320649361862b39 Mon Sep 17 00:00:00 2001 From: Environment Test Date: Mon, 13 Apr 2026 11:31:42 +0200 Subject: [PATCH 06/55] docs(contributing): add organisation dir and split principles Move Agile Manifesto principles out of design/principles.md into a dedicated organisation/principles.md so code and process concerns live in separate files. Move communication.md into the same directory for consistency. Add SRP to design/principles.md. Add cross-references between the two principles files. Co-Authored-By: Claude Sonnet 4.6 --- SUPPORT.md | 2 +- docs/contributing/design/principles.md | 14 ++--------- docs/contributing/organisation/README.md | 4 ++++ .../{ => organisation}/communication.md | 0 docs/contributing/organisation/principles.md | 23 +++++++++++++++++++ 5 files changed, 30 insertions(+), 13 deletions(-) create mode 100644 docs/contributing/organisation/README.md rename docs/contributing/{ => organisation}/communication.md (100%) create mode 100644 docs/contributing/organisation/principles.md diff --git a/SUPPORT.md b/SUPPORT.md index 77859d997a..a598afec1a 100644 --- a/SUPPORT.md +++ b/SUPPORT.md @@ -48,4 +48,4 @@ This page collects the places to go when you need help, a professional setup, or --- -For communication guidelines — including which topics belong in public channels and which must stay internal — see [communication.md](docs/contributing/communication.md). +For communication guidelines — including which topics belong in public channels and which must stay internal — see [communication.md](docs/contributing/organisation/communication.md). diff --git a/docs/contributing/design/principles.md b/docs/contributing/design/principles.md index 03722485da..43bfaaad24 100644 --- a/docs/contributing/design/principles.md +++ b/docs/contributing/design/principles.md @@ -1,6 +1,7 @@ # Code Principles 📐 Use these principles when you change repository code, scripts, or automation. +For organisational and team-process principles, see [principles.md](../organisation/principles.md). ## Principles 📋 @@ -12,19 +13,8 @@ Follow these principles. Keep the rule column short, imperative, and as [SMART]( | Leave touched code cleaner than you found it. | Small cleanup reduces future friction. | [Boy Scout Rule](https://en.wikipedia.org/wiki/Leaving_the_world_a_better_place) | Make small, safe cleanup improvements in the files you touch when they reduce friction without expanding the scope unnecessarily. | | Store each shared value once. | Shared values drift when copied. | [SPOT](https://en.wikipedia.org/wiki/Single_source_of_truth) | Put shared fixed values in one canonical source and reference them everywhere else. | | Choose the simplest solution. | Simple code is easier to change. | [KISS](https://en.wikipedia.org/wiki/KISS_principle) | Prefer the smallest implementation that still satisfies the requirement and remains easy to maintain. | +| Give each module one reason to change. | Focused modules are easier to test and replace. | [SRP](https://en.wikipedia.org/wiki/Single-responsibility_principle) | Each module, class, or function MUST have exactly one responsibility so that changes to one concern do not ripple into unrelated code. | | Make prompts SMART. | Clear prompts reduce ambiguity. | [SMART](https://en.wikipedia.org/wiki/SMART_criteria) | Write prompts that are specific, measurable, achievable, relevant, and time-bound so the agent can act on them without ambiguity. | -| Ship the first valuable increment early. | Early value shortens feedback loops. | [Agile Manifesto](https://agilemanifesto.org/) | Deliver working software as soon as it is useful and keep delivering value continuously. | -| Accept useful requirement changes. | Better ideas can arrive late. | [Agile Manifesto](https://agilemanifesto.org/) | Treat late requirement changes as normal when they improve customer value. | -| Release working software frequently. | Frequent delivery surfaces issues sooner. | [Agile Manifesto](https://agilemanifesto.org/) | Keep iterations short enough that users see working software at regular intervals. | -| Work with business daily. | Daily contact keeps intent aligned. | [Agile Manifesto](https://agilemanifesto.org/) | Keep business and development in daily contact for decisions and feedback. | -| Trust motivated people. | Engaged people take better ownership. | [Agile Manifesto](https://agilemanifesto.org/) | Build around engaged people and give them ownership of the work. | -| Use direct conversation for blocking topics. | Direct talk resolves blockers faster. | [Agile Manifesto](https://agilemanifesto.org/) | Prefer face-to-face or synchronous discussion when the decision is urgent or complex. | -| Measure progress with working software. | Working software shows real progress. | [Agile Manifesto](https://agilemanifesto.org/) | Use running software, not documents alone, as the main progress signal. | -| Keep a sustainable pace. | Sustainable pace avoids burnout. | [Agile Manifesto](https://agilemanifesto.org/) | Set a pace the team can maintain for the long term. | -| Improve technical quality continuously. | Quality debt compounds if ignored. | [Agile Manifesto](https://agilemanifesto.org/) | Invest in design and code quality on every change. | -| Remove unnecessary work. | Removing work leaves room for value. | [Agile Manifesto](https://agilemanifesto.org/) | Choose the smallest solution that achieves the goal. | -| Let teams shape their own design. | Local teams know the best design. | [Agile Manifesto](https://agilemanifesto.org/) | Let self-organizing teams own architecture, requirements, and implementation. | -| Inspect and adapt regularly. | Regular review catches process drift. | [Agile Manifesto](https://agilemanifesto.org/) | Review the process at regular intervals and change it when it is not working. | | Write the failing test first. | Failing tests confirm requirements first. | [TDD](https://en.wikipedia.org/wiki/Test-driven_development) | Start with a failing test, implement the minimum code, and refactor with confidence. | | Prefer beautiful code. | Readable code is easier to trust. | [Zen of Python](https://en.wikipedia.org/wiki/Zen_of_Python) | Choose code that is clean, coherent, and pleasant to read instead of code that is only clever. | | Prefer explicit behavior. | Explicit behavior is easier to reason about. | [Zen of Python](https://en.wikipedia.org/wiki/Zen_of_Python) | Make behavior visible in the code instead of relying on hidden assumptions. | diff --git a/docs/contributing/organisation/README.md b/docs/contributing/organisation/README.md new file mode 100644 index 0000000000..12ed0fa4b4 --- /dev/null +++ b/docs/contributing/organisation/README.md @@ -0,0 +1,4 @@ +# Organisation 🏛️ + +This directory contains contributor guidance for team collaboration, communication, and organisational processes. +Its scope is how contributors communicate, document their work, and apply agile principles across the project lifecycle. diff --git a/docs/contributing/communication.md b/docs/contributing/organisation/communication.md similarity index 100% rename from docs/contributing/communication.md rename to docs/contributing/organisation/communication.md diff --git a/docs/contributing/organisation/principles.md b/docs/contributing/organisation/principles.md new file mode 100644 index 0000000000..0bd5cf601a --- /dev/null +++ b/docs/contributing/organisation/principles.md @@ -0,0 +1,23 @@ +# Organisational Principles 📐 + +These principles govern how teams collaborate, plan, and deliver work. +For code design principles, see [principles.md](../design/principles.md). + +## Principles 📋 + +Follow these principles. Keep the rule column short, imperative, and as [SMART](https://en.wikipedia.org/wiki/SMART_criteria) as practical; use the reason column for the rationale, the principle column for the linked source name, and put the expanded wording in the details column. + +| Rule | Reason | Principle | Details | +|---|---|---|---| +| Ship the first valuable increment early. | Early value shortens feedback loops. | [Agile Manifesto](https://agilemanifesto.org/) | Deliver working software as soon as it is useful and keep delivering value continuously. | +| Accept useful requirement changes. | Better ideas can arrive late. | [Agile Manifesto](https://agilemanifesto.org/) | Treat late requirement changes as normal when they improve customer value. | +| Release working software frequently. | Frequent delivery surfaces issues sooner. | [Agile Manifesto](https://agilemanifesto.org/) | Keep iterations short enough that users see working software at regular intervals. | +| Work with business daily. | Daily contact keeps intent aligned. | [Agile Manifesto](https://agilemanifesto.org/) | Keep business and development in daily contact for decisions and feedback. | +| Trust motivated people. | Engaged people take better ownership. | [Agile Manifesto](https://agilemanifesto.org/) | Build around engaged people and give them ownership of the work. | +| Use direct conversation for blocking topics. | Direct talk resolves blockers faster. | [Agile Manifesto](https://agilemanifesto.org/) | Prefer face-to-face or synchronous discussion when the decision is urgent or complex. | +| Measure progress with working software. | Working software shows real progress. | [Agile Manifesto](https://agilemanifesto.org/) | Use running software, not documents alone, as the main progress signal. | +| Keep a sustainable pace. | Sustainable pace avoids burnout. | [Agile Manifesto](https://agilemanifesto.org/) | Set a pace the team can maintain for the long term. | +| Improve technical quality continuously. | Quality debt compounds if ignored. | [Agile Manifesto](https://agilemanifesto.org/) | Invest in design and code quality on every change. | +| Remove unnecessary work. | Removing work leaves room for value. | [Agile Manifesto](https://agilemanifesto.org/) | Choose the smallest solution that achieves the goal. | +| Let teams shape their own design. | Local teams know the best design. | [Agile Manifesto](https://agilemanifesto.org/) | Let self-organizing teams own architecture, requirements, and implementation. | +| Inspect and adapt regularly. | Regular review catches process drift. | [Agile Manifesto](https://agilemanifesto.org/) | Review the process at regular intervals and change it when it is not working. | From a57f863f74bfedf0dae495f79298c51763c21c53 Mon Sep 17 00:00:00 2001 From: Environment Test Date: Mon, 13 Apr 2026 11:51:22 +0200 Subject: [PATCH 07/55] fix(test): use _FROM_ARG_RE in pass 2 to resolve unused-global warning Co-Authored-By: Claude Sonnet 4.6 --- tests/lint/docker/dockerfile/test_arg_scope.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/lint/docker/dockerfile/test_arg_scope.py b/tests/lint/docker/dockerfile/test_arg_scope.py index 6330f96569..b938e6f799 100644 --- a/tests/lint/docker/dockerfile/test_arg_scope.py +++ b/tests/lint/docker/dockerfile/test_arg_scope.py @@ -52,8 +52,8 @@ def _undeclared_from_args(dockerfile: Path) -> list[tuple[int, str, str]]: # Pass 2 — check every FROM that references an ARG violations: list[tuple[int, str, str]] = [] for lineno, line in enumerate(lines, start=1): - for m in re.finditer(r"\$\{(\w+)\}", line): - if _FROM_RE.match(line) and m.group(1) not in global_args: + for m in _FROM_ARG_RE.finditer(line): + if m.group(1) not in global_args: violations.append((lineno, line.strip(), m.group(1))) return violations From 053a13d631fa701886316274706e7bd30cf6ecc2 Mon Sep 17 00:00:00 2001 From: Environment Test Date: Mon, 13 Apr 2026 11:55:21 +0200 Subject: [PATCH 08/55] fix(utils): remove unused utils/gha compatibility shim No code references utils.gha anywhere. Removing resolves CodeQL py/unused-import alert #262. Co-Authored-By: Claude Sonnet 4.6 --- utils/gha/__init__.py | 0 utils/gha/annotations.py | 10 ---------- 2 files changed, 10 deletions(-) delete mode 100644 utils/gha/__init__.py delete mode 100644 utils/gha/annotations.py diff --git a/utils/gha/__init__.py b/utils/gha/__init__.py deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/utils/gha/annotations.py b/utils/gha/annotations.py deleted file mode 100644 index d3020d2041..0000000000 --- a/utils/gha/annotations.py +++ /dev/null @@ -1,10 +0,0 @@ -# Compatibility shim – use utils.annotations.message instead. -from utils.annotations.message import ( # noqa: F401 - _emit, - error, - error_each, - in_github_actions, - notice, - warning, - warning_each, -) From ec98dfbe4662adaa90c9ee15d54f1eb9f07431f7 Mon Sep 17 00:00:00 2001 From: Environment Test Date: Mon, 13 Apr 2026 12:08:27 +0200 Subject: [PATCH 09/55] fix(test): resolve CodeQL import-and-import-from alerts #263 #264 Move sys, unittest.mock and main to top-level imports. Replace inline module imports and mod.main() calls with the already-imported main(). Co-Authored-By: Claude Sonnet 4.6 --- tests/unit/utils/annotations/test_summarize.py | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/tests/unit/utils/annotations/test_summarize.py b/tests/unit/utils/annotations/test_summarize.py index a77fd0fb0e..1e09f63920 100644 --- a/tests/unit/utils/annotations/test_summarize.py +++ b/tests/unit/utils/annotations/test_summarize.py @@ -1,12 +1,15 @@ from __future__ import annotations import os +import sys import tempfile import unittest +import unittest.mock from pathlib import Path from utils.annotations.summarize import ( Annotation, + main, parse_log, parse_props, render_markdown, @@ -151,16 +154,13 @@ class TestMain(unittest.TestCase): ) as summary: summary_path = summary.name - import utils.annotations.summarize as mod - import sys - old_argv = sys.argv try: sys.argv = ["summarize", log_path, "Test Title"] with unittest.mock.patch.dict( os.environ, {"GITHUB_STEP_SUMMARY": summary_path} ): - mod.main() + main() finally: sys.argv = old_argv @@ -169,20 +169,15 @@ class TestMain(unittest.TestCase): self.assertIn("msg", content) def test_exits_without_args(self) -> None: - import sys - import utils.annotations.summarize as mod - old_argv = sys.argv sys.argv = ["summarize"] try: with self.assertRaises(SystemExit) as cm: - mod.main() + main() self.assertEqual(cm.exception.code, 1) finally: sys.argv = old_argv -import unittest.mock # noqa: E402 – needed for TestMain - if __name__ == "__main__": unittest.main() From db3df8ec5307f62ec16940e23d90bc20ec7b57c5 Mon Sep 17 00:00:00 2001 From: Environment Test Date: Mon, 13 Apr 2026 12:11:51 +0200 Subject: [PATCH 10/55] fix(bigbluebutton): resolve CodeQL useless-assignment alerts #260 #261 Remove useless assignments to changed before the unconditional changed = true at the password block. Also fix ||= short-circuit bug that skipped ensure_attr! when changed was already true. Co-Authored-By: Claude Sonnet 4.6 --- roles/web-app-bigbluebutton/files/greenlight_ensure_admin.rb | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/roles/web-app-bigbluebutton/files/greenlight_ensure_admin.rb b/roles/web-app-bigbluebutton/files/greenlight_ensure_admin.rb index 48fba50a2f..2157094a94 100644 --- a/roles/web-app-bigbluebutton/files/greenlight_ensure_admin.rb +++ b/roles/web-app-bigbluebutton/files/greenlight_ensure_admin.rb @@ -50,13 +50,12 @@ if user changed = true end - changed ||= ensure_attr!(user, :provider, "greenlight") - changed ||= ensure_attr!(user, :language, "en") + ensure_attr!(user, :provider, "greenlight") + ensure_attr!(user, :language, "en") if user.respond_to?(:role=) && user.respond_to?(:role_id) if user.role_id != admin_role.id user.role = admin_role - changed = true end end From ed061eb3d41b46cddcf97d839c7e83f936d38994 Mon Sep 17 00:00:00 2001 From: Environment Test Date: Mon, 13 Apr 2026 12:14:08 +0200 Subject: [PATCH 11/55] fix(docs): fix broken relative links in organisation/communication.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit File moved one level deeper — update SECURITY.md and CODE_OF_CONDUCT.md paths from ../../ to ../../../. Co-Authored-By: Claude Sonnet 4.6 --- docs/contributing/organisation/communication.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/contributing/organisation/communication.md b/docs/contributing/organisation/communication.md index 2c72736d2d..ada0cbfda2 100644 --- a/docs/contributing/organisation/communication.md +++ b/docs/contributing/organisation/communication.md @@ -40,7 +40,7 @@ Examples of topics that MUST stay internal: ### Bugs and Issues 🐛 - Bugs and actionable issues MUST be reported at [s.infinito.nexus/issues](https://s.infinito.nexus/issues). -- Security vulnerabilities MUST NOT be reported there — see [SECURITY.md](../../SECURITY.md) instead. +- Security vulnerabilities MUST NOT be reported there — see [SECURITY.md](../../../SECURITY.md) instead. ### Features and Work Items 🗂️ @@ -67,4 +67,4 @@ In all communication and when handling data, you MUST respect the [Hacker Ethics ## Conduct 🕊️ -All communication MUST follow the project [Code of Conduct](../../CODE_OF_CONDUCT.md). +All communication MUST follow the project [Code of Conduct](../../../CODE_OF_CONDUCT.md). From f3d67ecb38fe5e7e58e34dfea7ef3dd9dae55be9 Mon Sep 17 00:00:00 2001 From: Environment Test Date: Mon, 13 Apr 2026 13:22:20 +0200 Subject: [PATCH 12/55] refactor(ci): extract app-discovery output logic into script Inline shell duplicated across four deploy workflows. Single source now in scripts/github/output_apps.sh. --- .github/workflows/test-deploy-local.yml | 8 +------- .github/workflows/test-deploy-server.yml | 8 +------- .github/workflows/test-deploy-universal.yml | 8 +------- .github/workflows/test-deploy-workstation.yml | 8 +------- scripts/github/output_apps.sh | 15 +++++++++++++++ 5 files changed, 19 insertions(+), 28 deletions(-) create mode 100755 scripts/github/output_apps.sh diff --git a/.github/workflows/test-deploy-local.yml b/.github/workflows/test-deploy-local.yml index 33448d236e..d236438540 100644 --- a/.github/workflows/test-deploy-local.yml +++ b/.github/workflows/test-deploy-local.yml @@ -72,13 +72,7 @@ jobs: shell: bash env: WHITELIST: ${{ inputs.whitelist }} - run: | - set -euo pipefail - apps="$(./scripts/meta/resolve/apps.sh)" - [[ -n "$apps" ]] || apps='[]' - echo "apps=$apps" >> "$GITHUB_OUTPUT" - echo "apps_json=$apps" >> "$GITHUB_OUTPUT" - echo "apps_json=$apps" + run: ./scripts/github/output_apps.sh deploy: name: 🚀 Deploy ${{ needs.discover.outputs.test_deploy_type }} app (${{ matrix.apps }}) diff --git a/.github/workflows/test-deploy-server.yml b/.github/workflows/test-deploy-server.yml index e0750eb080..8c9db3898b 100644 --- a/.github/workflows/test-deploy-server.yml +++ b/.github/workflows/test-deploy-server.yml @@ -60,13 +60,7 @@ jobs: shell: bash env: WHITELIST: ${{ inputs.whitelist }} - run: | - set -euo pipefail - apps="$(./scripts/meta/resolve/apps.sh)" - [[ -n "$apps" ]] || apps='[]' - echo "apps=$apps" >> "$GITHUB_OUTPUT" - echo "apps_json=$apps" >> "$GITHUB_OUTPUT" - echo "apps_json=$apps" + run: ./scripts/github/output_apps.sh server: name: 🌐 Deploy ${{ matrix.apps }} diff --git a/.github/workflows/test-deploy-universal.yml b/.github/workflows/test-deploy-universal.yml index 3c2a39055d..1739b07b83 100644 --- a/.github/workflows/test-deploy-universal.yml +++ b/.github/workflows/test-deploy-universal.yml @@ -56,13 +56,7 @@ jobs: shell: bash env: WHITELIST: ${{ inputs.whitelist }} - run: | - set -euo pipefail - apps="$(./scripts/meta/resolve/apps.sh)" - [[ -n "$apps" ]] || apps='[]' - echo "apps=$apps" >> "$GITHUB_OUTPUT" - echo "apps_json=$apps" >> "$GITHUB_OUTPUT" - echo "apps_json=$apps" + run: ./scripts/github/output_apps.sh universal: name: ✨ Deploy ${{ matrix.apps }} diff --git a/.github/workflows/test-deploy-workstation.yml b/.github/workflows/test-deploy-workstation.yml index 1ee9ac5676..2db55c249c 100644 --- a/.github/workflows/test-deploy-workstation.yml +++ b/.github/workflows/test-deploy-workstation.yml @@ -56,13 +56,7 @@ jobs: shell: bash env: WHITELIST: ${{ inputs.whitelist }} - run: | - set -euo pipefail - apps="$(./scripts/meta/resolve/apps.sh)" - [[ -n "$apps" ]] || apps='[]' - echo "apps=$apps" >> "$GITHUB_OUTPUT" - echo "apps_json=$apps" >> "$GITHUB_OUTPUT" - echo "apps_json=$apps" + run: ./scripts/github/output_apps.sh workstation: name: 🖥️ Deploy ${{ matrix.apps }} diff --git a/scripts/github/output_apps.sh b/scripts/github/output_apps.sh new file mode 100755 index 0000000000..471100421a --- /dev/null +++ b/scripts/github/output_apps.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# scripts/github/output_apps.sh +# +# Resolve the app list and write it to GITHUB_OUTPUT. +# Inputs via env (forwarded to scripts/meta/resolve/apps.sh): +# TEST_DEPLOY_TYPE — required (server|workstation|universal) +# WHITELIST — optional space-separated allowlist +set -euo pipefail + +apps="$(./scripts/meta/resolve/apps.sh)" +[[ -n "$apps" ]] || apps='[]' + +echo "apps=$apps" >>"$GITHUB_OUTPUT" +echo "apps_json=$apps" >>"$GITHUB_OUTPUT" +echo "apps_json=$apps" From 3e597b6d1979fdcd7330844eaecdfbc95f5bac5d Mon Sep 17 00:00:00 2001 From: Environment Test Date: Mon, 13 Apr 2026 13:30:29 +0200 Subject: [PATCH 13/55] ci(codeql): add concurrency group with cancel-in-progress --- .github/workflows/security-codeql.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/security-codeql.yml b/.github/workflows/security-codeql.yml index 12ef548e5f..9a2e365aee 100644 --- a/.github/workflows/security-codeql.yml +++ b/.github/workflows/security-codeql.yml @@ -11,6 +11,10 @@ # name: "🔒 Scan: CodeQL (Advanced)" +concurrency: + group: codeql-${{ github.repository }}-${{ github.ref }} + cancel-in-progress: true + on: workflow_call: push: From f8d2f14ea8ff6eb7bdf5cc716c3f1f0c558cde85 Mon Sep 17 00:00:00 2001 From: Environment Test Date: Mon, 13 Apr 2026 13:41:23 +0200 Subject: [PATCH 14/55] chore(skills): update caveman skill hash --- skills-lock.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills-lock.json b/skills-lock.json index 5ddcab614c..6046df721a 100644 --- a/skills-lock.json +++ b/skills-lock.json @@ -4,7 +4,7 @@ "caveman": { "source": "JuliusBrussee/caveman", "sourceType": "github", - "computedHash": "4d486dd6f9fbb27ce1c51c972c9a5eb25a53236ae05eabf4d076ac1e293f4b7a" + "computedHash": "a818cdc41dcfaa50dd891c5cb5e5705968338de02e7e37949ca56e8c30ad4176" }, "caveman-commit": { "source": "JuliusBrussee/caveman", From fb7c581a8399bce9c1242313ac9cdcd8ecf05b7a Mon Sep 17 00:00:00 2001 From: Environment Test Date: Mon, 13 Apr 2026 15:17:34 +0200 Subject: [PATCH 15/55] refactor(nextcloud): migrate get_app_conf to lookup('config', ...) Replace legacy filter with the canonical lookup plugin across nextcloud config, group_vars, dashboard template, and vars template. Switches Talk TURN from onboard to standalone coturn by default; gates talk container on spreed plugin flag. Adds lint test to catch remaining get_app_conf usages. --- group_vars/all/00_general.yml | 23 ++-- .../templates/playwright.env.j2 | 2 +- roles/web-app-nextcloud/config/main.yml | 19 ++- templates/roles/web-app/vars/main.yml.j2 | 2 +- .../test_legacy_get_app_conf_usage.py | 121 ++++++++++++++++++ 5 files changed, 144 insertions(+), 23 deletions(-) create mode 100644 tests/lint/repository/test_legacy_get_app_conf_usage.py diff --git a/group_vars/all/00_general.yml b/group_vars/all/00_general.yml index abf718cc80..f2c129d5d9 100644 --- a/group_vars/all/00_general.yml +++ b/group_vars/all/00_general.yml @@ -62,21 +62,16 @@ allowed_applications: [] # helper _applications_nextcloud_oidc_flavor: >- {{ - (applications | default({}, true)) - | get_app_conf( - 'web-app-nextcloud', - 'oidc.flavor', - False, - ( - 'oidc_login' - if ( - (applications | default({}, true)) - | get_app_conf('web-app-nextcloud','compose.services.ldap.enabled',False, True, True) - ) - else 'sociallogin' - ), - True + lookup( + 'config', + 'web-app-nextcloud', + 'oidc.flavor', + ( + 'oidc_login' + if lookup('config', 'web-app-nextcloud', 'compose.services.ldap.enabled', False) + else 'sociallogin' ) + ) }} # Role-based access control diff --git a/roles/web-app-dashboard/templates/playwright.env.j2 b/roles/web-app-dashboard/templates/playwright.env.j2 index 73087dafd9..fdfcd0961c 100644 --- a/roles/web-app-dashboard/templates/playwright.env.j2 +++ b/roles/web-app-dashboard/templates/playwright.env.j2 @@ -5,4 +5,4 @@ LOGIN_PASSWORD={{ users.administrator.password | dotenv_quote }} CDN_BASE_URL={{ lookup('tls', 'web-svc-cdn', 'url.base') | dotenv_quote }} DASHBOARD_JS_BASE_URL={{ DASHBOARD_JS_BASE_URL | dotenv_quote }} MATOMO_BASE_URL={{ lookup('tls', 'web-app-matomo', 'url.base') | dotenv_quote }} -MATOMO_ENABLED={{ applications | get_app_conf(application_id, 'compose.services.matomo.enabled') }} +MATOMO_ENABLED={{ lookup('config', application_id, 'compose.services.matomo.enabled') }} diff --git a/roles/web-app-nextcloud/config/main.yml b/roles/web-app-nextcloud/config/main.yml index 272efa940d..22a73214e7 100644 --- a/roles/web-app-nextcloud/config/main.yml +++ b/roles/web-app-nextcloud/config/main.yml @@ -44,8 +44,11 @@ compose: enabled: true shared: true coturn: + # Keep dedicated TURN provider statically discoverable so normal inventory + # generation and local iteration always pull in web-svc-coturn. + # Actual Talk TURN usage stays gated by plugins.spreed.enabled below. + enabled: true shared: true - enabled: true logout: enabled: true shared: true @@ -106,14 +109,16 @@ compose: mem_limit: "512m" pids_limit: 256 talk: + enabled: "{{ lookup('config', 'web-app-nextcloud', 'plugins.spreed.enabled') }}" name: "nextcloud-talk" image: "nextcloud/aio-talk" version: "latest" backup: no_stop_required: false turn_server: - onboard_enabled: true - standalone_enabled: false + # Use dedicated web-svc-coturn by default. HPB onboard TURN stays available as an explicit fallback only. + onboard_enabled: false + standalone_enabled: true network_mode: bridge cpus: "2.0" mem_reservation: "1g" @@ -150,7 +155,7 @@ compose: shared: true hcaptcha: enabled: "{{ HCAPTCHA_ENABLED | bool }}" - enabled: "{{ applications | default({}, true) | get_app_conf('web-app-nextcloud', 'compose.services.oidc.enabled', False, True, True) }}" # Activate OIDC for Nextcloud + enabled: "{{ lookup('config', 'web-app-nextcloud', 'compose.services.oidc.enabled', False) }}" # Activate OIDC for Nextcloud # floavor decides which OICD plugin should be used. # Available options: oidc_login, sociallogin # @see https://apps.nextcloud.com/apps/oidc_login @@ -354,13 +359,13 @@ plugins: # enabled: false twofactor_nextcloud_notification: # Nextcloud two-factor notification: sends notifications for two-factor authentication events (https://apps.nextcloud.com/apps/twofactor_nextcloud_notification) - enabled: "{{ not (applications | default({}, true) | get_app_conf('web-app-nextcloud', 'compose.services.oidc.enabled', False, True, True)) }}" # Deactivate 2FA if oidc is active + enabled: "{{ not (lookup('config', 'web-app-nextcloud', 'compose.services.oidc.enabled', False)) }}" # Deactivate 2FA if oidc is active twofactor_totp: # Nextcloud two-factor TOTP: provides time-based one-time password authentication (https://apps.nextcloud.com/apps/twofactor_totp) - enabled: "{{ not (applications | default({}, true) | get_app_conf('web-app-nextcloud', 'compose.services.oidc.enabled', False, True, True)) }}" # Deactivate 2FA if oidc is active + enabled: "{{ not (lookup('config', 'web-app-nextcloud', 'compose.services.oidc.enabled', False)) }}" # Deactivate 2FA if oidc is active user_ldap: # Nextcloud user LDAP: integrates LDAP for user management and authentication - enabled: "{{ applications | default({}, true) | get_app_conf('web-app-nextcloud', 'compose.services.ldap.enabled', False, True, True) }}" + enabled: "{{ lookup('config', 'web-app-nextcloud', 'compose.services.ldap.enabled', False) }}" user_directory: enabled: true # Enables the LDAP User Directory Search user_oidc: diff --git a/templates/roles/web-app/vars/main.yml.j2 b/templates/roles/web-app/vars/main.yml.j2 index d5f6076f8c..8785af9ec8 100644 --- a/templates/roles/web-app/vars/main.yml.j2 +++ b/templates/roles/web-app/vars/main.yml.j2 @@ -12,7 +12,7 @@ docker_git_repository_pull: true # This will auto docker_git_repository_address: "" # The address of a repository which should be pulled {# The following variable mapping is optional, but it makes it easier to read the code.#} -{# I recommend, to use this mappings, but you can skipp it and access the config entries direct via 'get_app_conf' #} +{# I recommend, to use this mappings, but you can skip it and access config entries directly via lookup('config', ...) #} # This variables had been autocreated. For a detailled explanation checkout the config/main.yml file {{ application_id | get_entity_name }}_version: "{% raw %}{{ lookup('config', application_id, 'compose.services.{% endraw %}{{ application_id | get_entity_name }}{% raw %}.version') }}"{% endraw %} diff --git a/tests/lint/repository/test_legacy_get_app_conf_usage.py b/tests/lint/repository/test_legacy_get_app_conf_usage.py new file mode 100644 index 0000000000..5ed283619f --- /dev/null +++ b/tests/lint/repository/test_legacy_get_app_conf_usage.py @@ -0,0 +1,121 @@ +"""Temporary lint sentinel for legacy get_app_conf usage in YAML/Jinja files. + +Warn on every remaining occurrence under tracked repository config/template files. +Once no occurrences remain, this test must fail so the temporary sentinel itself +gets removed. +""" + +from __future__ import annotations + +import subprocess +import unittest +from dataclasses import dataclass +from pathlib import Path +from typing import List + +from utils.annotations.message import in_github_actions, warning + + +LEGACY_HELPER = "get_" + "app_conf" +SELF_TEST_PATH = "tests/lint/repository/test_legacy_get_app_conf_usage.py" + + +@dataclass(frozen=True) +class UsageFinding: + path: Path + line: int + text: str + + def format(self, repo_root: Path) -> str: + rel = self.path.relative_to(repo_root).as_posix() + return f"{rel}:{self.line} - {self.text.strip()}" + + +def repo_root() -> Path: + for candidate in Path(__file__).resolve().parents: + if (candidate / "pyproject.toml").is_file(): + return candidate + raise AssertionError("Repository root not found from test path.") + + +def tracked_candidate_files(root: Path) -> List[Path]: + try: + out = subprocess.check_output( + ["git", "-C", str(root), "ls-files", "-z"], + stderr=subprocess.STDOUT, + ) + rel_paths = [p for p in out.decode("utf-8", errors="replace").split("\0") if p] + files = [root / rel for rel in rel_paths] + except Exception: + files = [p for p in root.rglob("*") if p.is_file()] + + results: List[Path] = [] + for path in files: + rel = path.relative_to(root).as_posix() + if rel == SELF_TEST_PATH: + continue + results.append(path) + return sorted(results) + + +def scan_file(path: Path) -> List[UsageFinding]: + findings: List[UsageFinding] = [] + try: + lines = path.read_text(encoding="utf-8", errors="replace").splitlines() + except OSError: + return findings + + for line_no, line in enumerate(lines, start=1): + if LEGACY_HELPER in line: + findings.append(UsageFinding(path=path, line=line_no, text=line)) + + return findings + + +def emit_warning(finding: UsageFinding, root: Path) -> None: + if not in_github_actions(): + return + warning( + f"Legacy {LEGACY_HELPER} usage remains.", + title="Legacy get_app_conf usage", + file=finding.path.relative_to(root).as_posix(), + line=finding.line, + ) + + +class TestLegacyGetAppConfUsage(unittest.TestCase): + def test_warn_until_last_legacy_usage_is_removed(self) -> None: + root = repo_root() + candidates = tracked_candidate_files(root) + self.assertTrue( + candidates, + "No tracked repository files found.", + ) + + findings: List[UsageFinding] = [] + for path in candidates: + findings.extend(scan_file(path)) + + findings.sort(key=lambda item: (item.path.as_posix(), item.line)) + + if not findings: + self.fail( + "No legacy get_app_conf usages remain in tracked repository files.\n" + "This temporary lint test can be removed:\n" + f"- {SELF_TEST_PATH}" + ) + + for item in findings: + emit_warning(item, root) + + if not in_github_actions(): + print() + print( + f"[WARNING] Remaining legacy {LEGACY_HELPER} usages ({len(findings)}):" + ) + for item in findings: + print(f"- {item.format(root)}") + + +if __name__ == "__main__": + unittest.main() From be6a310d596c73cbb05dc2a2ffa1f1a5977841f6 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 13 Apr 2026 19:33:20 +0200 Subject: [PATCH 16/55] refactor(services): implement role-local service registry (req-001) - Delete group_vars/all/20_services.yml; all service metadata now lives in each role's config/main.yml under compose.services. - Rename generic 'database' service key to explicit 'mariadb'/'postgres' across all app roles; remove legacy type: field - Add utils/service_registry.py and plugins/lookup/service_registry.py as the single source of truth for service discovery - Add utils/database_service.py to centralize DB service resolution - Delete service_load_enabled filter and service_should_load lookup; replaced by service lookup plugin - Update sys-utils-service-loader to run in constructor stage and use generic load_service.yml; remove load_frontend_service.yml - Add _service_loader_preloading guard to sys-svc-compose, sys-svc-webserver-core and sys-ctl-alm-compose to prevent health-checks/alarms from firing during preload phase - Replace manual load_app.yml calls for shared DB/Mailu with assert- based preload validation in sys-svc-rdbms and sys-svc-mail - Update networks.yml.j2 templates to resolve LDAP/AI networks via service_registry instead of hardcoded role names - Migrate all tests to new service discovery API; delete obsolete tests - Update docs/contributing/code/services.md to reflect role-local model Co-Authored-By: Claude Sonnet 4.6 --- .../resolution/services/resolver.py | 64 ++- docs/contributing/code/services.md | 348 ++++++++-------- .../001-service-registry-refactoring.md | 49 ++- group_vars/all/20_services.yml | 91 ----- plugins/filter/compose_volumes.py | 27 +- plugins/filter/service_load_enabled.py | 39 -- plugins/lookup/applications_current_play.py | 22 +- plugins/lookup/database.py | 42 +- plugins/lookup/service.py | 101 ++--- plugins/lookup/service_registry.py | 48 +++ roles/svc-db-mariadb/config/main.yml | 6 +- roles/svc-db-mariadb/tasks/01_core.yml | 4 +- roles/svc-db-mariadb/tasks/main.yml | 14 +- roles/svc-db-openldap/config/main.yml | 6 +- roles/svc-db-postgres/config/main.yml | 6 +- roles/svc-db-postgres/tasks/main.yml | 23 +- roles/sys-ctl-alm-compose/tasks/01_core.yml | 3 + .../lookup_plugins/service_should_load.py | 95 ----- roles/sys-stk-backend/tasks/_load_service.yml | 19 - roles/sys-stk-backend/tasks/main.yml | 38 +- roles/sys-stk-backend/vars/main.yml | 3 - roles/sys-svc-compose/tasks/01_core.yml | 4 +- roles/sys-svc-compose/templates/base.yml.j2 | 2 +- .../sys-svc-compose/templates/networks.yml.j2 | 31 +- .../templates/networks.yml.j2 | 31 +- roles/sys-svc-mail/tasks/01_core.yml | 36 +- roles/sys-svc-mail/tasks/02_mailu.yml | 9 - roles/sys-svc-rdbms/tasks/main.yml | 63 ++- roles/sys-svc-rdbms/vars/main.yml | 2 - .../sys-svc-webserver-core/tasks/01_core.yml | 1 + .../tasks/load_frontend_service.yml | 17 - .../tasks/load_service.yml | 19 + roles/sys-utils-service-loader/tasks/main.yml | 35 +- roles/web-app-akaunting/config/main.yml | 5 +- roles/web-app-baserow/config/main.yml | 5 +- roles/web-app-bigbluebutton/config/main.yml | 4 +- roles/web-app-bluesky/config/main.yml | 3 - .../web-app-bluesky/templates/compose.yml.j2 | 1 - roles/web-app-bookwyrm/config/main.yml | 6 +- roles/web-app-bridgy-fed/config/main.yml | 3 - roles/web-app-chess/config/main.yml | 7 +- roles/web-app-confluence/config/main.yml | 5 +- roles/web-app-dashboard/config/main.yml | 1 + roles/web-app-discourse/config/main.yml | 6 +- roles/web-app-espocrm/config/main.yml | 5 +- roles/web-app-flowise/config/main.yml | 3 - roles/web-app-friendica/config/main.yml | 7 +- roles/web-app-funkwhale/config/main.yml | 5 +- roles/web-app-gitea/config/main.yml | 5 +- roles/web-app-gitlab/config/main.yml | 5 +- roles/web-app-jira/config/main.yml | 5 +- roles/web-app-joomla/config/main.yml | 5 +- roles/web-app-keycloak/config/main.yml | 8 +- roles/web-app-listmonk/config/main.yml | 5 +- roles/web-app-magento/config/main.yml | 5 +- roles/web-app-mailu/config/main.yml | 8 +- roles/web-app-mailu/tasks/01_core.yml | 12 +- roles/web-app-mastodon/config/main.yml | 11 +- roles/web-app-matomo/config/main.yml | 7 +- roles/web-app-matrix/config/main.yml | 7 +- roles/web-app-mattermost/README.md | 2 +- roles/web-app-mattermost/config/main.yml | 7 +- roles/web-app-mediawiki/config/main.yml | 5 +- roles/web-app-mig/config/main.yml | 2 - roles/web-app-mini-qr/config/main.yml | 2 - roles/web-app-minio/config/main.yml | 3 - roles/web-app-mobilizon/config/main.yml | 5 +- roles/web-app-moodle/config/main.yml | 5 +- roles/web-app-nextcloud/config/main.yml | 5 +- roles/web-app-openproject/config/main.yml | 5 +- roles/web-app-openwebui/config/main.yml | 3 - roles/web-app-peertube/config/main.yml | 5 +- roles/web-app-pgadmin/config/main.yml | 5 +- roles/web-app-pgadmin/vars/main.yml | 1 - roles/web-app-phpmyadmin/config/main.yml | 5 +- roles/web-app-pixelfed/config/main.yml | 5 +- roles/web-app-pretix/config/main.yml | 5 +- roles/web-app-shopware/config/main.yml | 6 +- roles/web-app-snipe-it/config/main.yml | 5 +- roles/web-app-sphinx/config/main.yml | 2 - roles/web-app-suitecrm/config/main.yml | 5 +- roles/web-app-taiga/config/main.yml | 5 +- roles/web-app-wordpress/config/main.yml | 5 +- roles/web-app-xwiki/config/main.yml | 7 +- roles/web-app-yourls/config/main.yml | 5 +- roles/web-svc-asset/meta/main.yml | 3 +- roles/web-svc-cdn/config/main.yml | 5 + roles/web-svc-collabora/config/main.yml | 4 +- roles/web-svc-coturn/config/main.yml | 4 +- roles/web-svc-file/config/main.yml | 3 + roles/web-svc-legal/config/main.yml | 5 + roles/web-svc-legal/tasks/01_core.yml | 6 + roles/web-svc-legal/tasks/main.yml | 6 +- roles/web-svc-libretranslate/README.md | 1 - roles/web-svc-libretranslate/config/main.yml | 5 +- roles/web-svc-logout/config/main.yml | 2 +- roles/web-svc-onlyoffice/config/main.yml | 7 +- roles/web-svc-simpleicons/config/main.yml | 5 +- tasks/stages/01_constructor.yml | 4 + tasks/stages/02_server.yml | 1 - tasks/utils/load_app.yml | 2 +- .../test_central_database_config.py | 74 ---- .../test_configuration_database_dependency.py | 45 -- .../integration/test_frontend_service_spot.py | 88 ++-- tests/integration/test_inventory_manager.py | 88 +++- .../test_service_transitive_dependencies.py | 20 +- tests/integration/test_services_canonical.py | 100 +---- tests/integration/test_services_resolvable.py | 56 +-- .../test_service_core_first_task_run_once.py | 24 +- .../inventory/test_services_disabler.py | 4 +- .../applications/in_group_deps/test_main.py | 17 +- .../resolution/services/test_resolver.py | 97 +++-- tests/unit/cli/test_inventory_manager.py | 7 +- .../plugins/filter/test_compose_volumes.py | 22 +- .../filter/test_service_load_enabled.py | 110 ----- .../lookup/test_applications_current_play.py | 110 +++-- tests/unit/plugins/lookup/test_database.py | 57 ++- tests/unit/plugins/lookup/test_service.py | 385 ++++++++---------- .../test_service_should_load.py | 106 ----- tests/unit/utils/test_service_registry.py | 240 +++++++++++ utils/applications/in_group_deps.py | 64 +-- utils/database_service.py | 51 +++ utils/manager/inventory.py | 61 +-- utils/service_registry.py | 310 ++++++++++++++ 124 files changed, 1804 insertions(+), 1952 deletions(-) delete mode 100644 group_vars/all/20_services.yml delete mode 100644 plugins/filter/service_load_enabled.py create mode 100644 plugins/lookup/service_registry.py delete mode 100644 roles/sys-stk-backend/lookup_plugins/service_should_load.py delete mode 100644 roles/sys-stk-backend/tasks/_load_service.yml delete mode 100644 roles/sys-stk-backend/vars/main.yml delete mode 100644 roles/sys-svc-mail/tasks/02_mailu.yml delete mode 100644 roles/sys-svc-rdbms/vars/main.yml delete mode 100644 roles/sys-utils-service-loader/tasks/load_frontend_service.yml create mode 100644 roles/sys-utils-service-loader/tasks/load_service.yml create mode 100644 roles/web-svc-legal/config/main.yml create mode 100644 roles/web-svc-legal/tasks/01_core.yml delete mode 100644 tests/integration/test_central_database_config.py delete mode 100644 tests/integration/test_configuration_database_dependency.py delete mode 100644 tests/unit/plugins/filter/test_service_load_enabled.py delete mode 100644 tests/unit/roles/sys-stk-backend/lookup_plugins/test_service_should_load.py create mode 100644 tests/unit/utils/test_service_registry.py create mode 100644 utils/database_service.py create mode 100644 utils/service_registry.py diff --git a/cli/meta/applications/resolution/services/resolver.py b/cli/meta/applications/resolution/services/resolver.py index 28cd07a9f9..594e32e006 100644 --- a/cli/meta/applications/resolution/services/resolver.py +++ b/cli/meta/applications/resolution/services/resolver.py @@ -6,8 +6,12 @@ from typing import Any, Dict, Iterable, List, Optional, Set import yaml from .errors import ServicesResolutionError +from utils.service_registry import ( + build_service_registry_from_roles_dir, + resolve_service_dependency_roles_from_config, +) -_SERVICES_FILE = Path(__file__).parents[5] / "group_vars" / "all" / "20_services.yml" +_ROLES_ROOT = Path(__file__).parents[5] / "roles" def _stable_dedup(items: Iterable[str]) -> List[str]: @@ -29,16 +33,13 @@ def _is_enabled_shared(svc: object) -> bool: return svc.get("enabled") is True and svc.get("shared") is True -def _load_service_registry(services_file: Path = _SERVICES_FILE) -> Dict[str, Any]: - if not services_file.exists(): - raise ServicesResolutionError(f"20_services.yml not found at {services_file}") - raw = yaml.safe_load(services_file.read_text(encoding="utf-8")) or {} - service_registry = raw.get("SERVICE_REGISTRY") - if not isinstance(service_registry, dict): +def _load_service_registry(roles_root: Path = _ROLES_ROOT) -> Dict[str, Any]: + try: + return build_service_registry_from_roles_dir(roles_root) + except Exception as exc: raise ServicesResolutionError( - f"Expected a 'SERVICE_REGISTRY' mapping in {services_file}" - ) - return service_registry + f"Failed to discover services from role configs in {roles_root}: {exc}" + ) from exc def resolve_direct_service_roles_from_config( @@ -47,37 +48,18 @@ def resolve_direct_service_roles_from_config( ) -> List[str]: """ Single source of truth for "service -> provider role(s)" mapping. - - Reads the service key → role mapping from services.yml (repo root). - Every service requires compose.services..enabled: true AND shared: true. - Entries with role_template substitute {type} from the service config. """ if service_registry is None: service_registry = _load_service_registry() - - cfg = _as_mapping(config) - services = _as_mapping(_as_mapping(cfg.get("compose")).get("services")) - - includes: List[str] = [] - for key, mapping in service_registry.items(): - svc_obj = services.get(key) - if not _is_enabled_shared(svc_obj): - continue - - role_template = mapping.get("role_template") - if role_template: - svc_dict = _as_mapping(svc_obj) - db_type = (svc_dict.get("type") or "").strip() - if not db_type: - raise ServicesResolutionError( - f"compose.services.{key}.enabled=true and shared=true " - f"but compose.services.{key}.type is missing" - ) - includes.append(role_template.format(type=db_type)) - else: - includes.append(mapping["role"]) - - return _stable_dedup(includes) + try: + return _stable_dedup( + resolve_service_dependency_roles_from_config( + _as_mapping(config), + service_registry, + ) + ) + except Exception as exc: + raise ServicesResolutionError(str(exc)) from exc class ServicesResolver: @@ -92,10 +74,12 @@ class ServicesResolver: def __init__( self, roles_root: Path, - services_file: Path = _SERVICES_FILE, + services_file: Path | None = None, ) -> None: self.roles_root = roles_root - self._service_registry = _load_service_registry(services_file) + self._service_registry = _load_service_registry( + services_file or self.roles_root + ) def _role_dir(self, role_name: str) -> Path: return self.roles_root / role_name diff --git a/docs/contributing/code/services.md b/docs/contributing/code/services.md index 828898d325..d3817b086d 100644 --- a/docs/contributing/code/services.md +++ b/docs/contributing/code/services.md @@ -1,251 +1,231 @@ # Service Management -This page documents how services are defined, mapped, loaded, and injected at deploy time. +This page is the SPOT for how shared services are declared, discovered, ordered, +loaded, and injected. ## What Is a Service? -A *service* is a shared dependency that one or more applications can opt into via their `compose.services.` configuration. -Each service has: +A service is a reusable dependency that an application enables via +`compose.services.`. -- a **key** — the short name used inside `compose.services` (e.g. `cdn`, `css`, `logout`, `ldap`) -- a **role** — the Ansible role that provisions it (e.g. `web-svc-cdn`, `svc-db-openldap`) -- a **type** — either `frontend` (loaded early in the server stage) or `backend` (loaded by `sys-stk-backend`) -- an optional **canonical** — required when multiple keys share the same role (see below) +Examples: +- `web-svc-cdn` provides the primary service key `cdn` +- `web-app-keycloak` provides `oidc` +- `svc-db-mariadb` provides `mariadb` -An application declares it needs a service by setting `compose.services..enabled: true` in its config. -A service is considered *shared* (reusable across applications) when it also sets `shared: true`. +Each service entry lives in the provider role's own +[`config/main.yml`](../../../roles) under `compose.services.`. -## SPOT: Service Registry +## Role-Local Service Metadata -The canonical service key → role mapping lives in [`group_vars/all/20_services.yml`](../../../group_vars/all/20_services.yml). -This is the **single source of truth** for all service mappings — add a new service here to register it system-wide. +Service providers are self-describing. The provider role owns: +- `enabled` +- `shared` +- optional `provides` +- optional `canonical` -It is an Ansible `group_vars` file, so the `SERVICE_REGISTRY` variable is automatically available in all plays. -The Python CLI resolver reads the same file — no hardcoded mappings exist anywhere else. +Example: ```yaml -# group_vars/all/20_services.yml -SERVICE_REGISTRY: - matomo: - role: web-app-matomo - type: frontend - - # Multiple keys can point to the same role. - # The primary key has no canonical field; aliases declare canonical: . - cdn: - role: web-svc-cdn - type: frontend - css: - role: web-svc-cdn - type: frontend - canonical: cdn # alias — role-based lookup returns id: cdn - javascript: - role: web-svc-cdn - type: frontend - canonical: cdn # alias — role-based lookup returns id: cdn - - ldap: - role: svc-db-openldap - type: backend - database: - role_template: "svc-db-{type}" # {type} taken from compose.services.database.type - type: backend +compose: + services: + keycloak: + enabled: false + shared: true + provides: oidc ``` -### Shared-role entries and the `canonical` field +Canonical aliases are also role-local: -A role can be shared by multiple service keys (e.g. `cdn`, `css`, and `javascript` all provision `web-svc-cdn`). -Each service key represents a distinct *feature* that triggers CDN loading when an app enables it, -but role-based reverse lookup (`lookup('service', 'web-svc-cdn')`) must return a single, deterministic `id`. +```yaml +compose: + services: + cdn: + enabled: false + shared: true + css: + enabled: true + shared: true + canonical: cdn + javascript: + enabled: true + shared: true + canonical: cdn +``` Rules: -- The **primary key** has no `canonical` field — it is the canonical. -- Every **alias key** that shares the same role MUST declare `canonical: `. -- The canonical target must exist, share the same role, and must NOT itself be an alias (no chaining). -- A key whose role is unique (not shared) MUST NOT declare `canonical`. +- The primary service entry is the role entity name returned by `get_entity_name`. +- `provides:` is only used when the public service name differs from the entity name. +- `canonical:` is only used on alias entries that resolve back to the primary service key. +- `frontend` vs. `backend` is derived from the role name prefix, not stored in config. -These rules are enforced by the lint test [`tests/integration/test_services_canonical.py`](../../../tests/integration/test_services_canonical.py). +## Service Discovery -## Service Config per Role +Service discovery is built from role configs, not from a central registry file. -Every role that provides a service defines its own compose.services block in: +Primary implementation files: +- [`utils/service_registry.py`](../../../utils/service_registry.py) +- [`plugins/lookup/service_registry.py`](../../../plugins/lookup/service_registry.py) -``` -roles//config/main.yml - compose: - services: - : - enabled: true - shared: true -``` +The discovery layer: +- scans role configs from [`roles`](../../../roles) +- discovers provider entries from `compose.services` +- derives deploy type and loader bucket from the role name +- resolves `provides:` and `canonical:` +- validates and applies `run_after:` from `meta/main.yml` -## Two Independent Mechanisms +## Load Order -**Loading a service** and **injecting a service into an app's nginx config** are two separate concerns driven by the same config flag `compose.services..enabled`. +[`roles/sys-utils-service-loader/tasks/main.yml`](../../../roles/sys-utils-service-loader/tasks/main.yml) +is the single loader SPOT for all shared services. -### 1. Loading (deploy the container) +It runs from [`tasks/stages/01_constructor.yml`](../../../tasks/stages/01_constructor.yml) +before the normal application stage. -Decides whether the service container is deployed at all. +Global bucket order: +1. `universal` +2. `workstation` +3. `server` +4. `web-svc` +5. `web-app` -#### Frontend services — one early global SPOT +Within the same bucket, ordering is refined by `run_after:` in the provider role's +[`meta/main.yml`](../../../roles). -[`roles/sys-utils-service-loader/tasks/main.yml`](../../../roles/sys-utils-service-loader/tasks/main.yml) is the **SPOT** for shared frontend service loading. -It is called once from [`tasks/stages/02_server.yml`](../../../tasks/stages/02_server.yml) before `web-svc` -and `web-app` roles start. It iterates over every `type: frontend` entry from `SERVICE_REGISTRY`. +Rules: +- `run_after:` entries are role names, not service keys. +- Cross-type `run_after:` is invalid and fails hard. +- Later-bucket dependencies are invalid and fail hard. +- Cross-type service dependencies do not need `run_after:` because constructor-stage + loading already brings backend services up before normal app deployment. -For each service it: +## Loading vs Injection -1. Checks `lookup('service', item.key).needed` — is the service needed by any deployed app? -2. Checks `run_once_*` — has the service already been loaded this run? -3. Performs a reachability check via [`load_frontend_service.yml`](../../../roles/sys-utils-service-loader/tasks/load_frontend_service.yml) -4. Loads the service via `utils/load_app.yml` if the endpoint is not reachable (status ≠ 200) +Service loading and frontend injection are separate mechanisms. -Because this happens once before any normal `web-svc` or `web-app` role starts, service order can be controlled -directly by the order of entries in [`group_vars/all/20_services.yml`](../../../group_vars/all/20_services.yml). +### Loading -#### Backend services — `sys-stk-backend` +Loading decides whether the provider role is deployed at all. -[`roles/sys-stk-backend/tasks/main.yml`](../../../roles/sys-stk-backend/tasks/main.yml) loops over a list of backend services and calls -[`_load_service.yml`](../../../roles/sys-stk-backend/tasks/_load_service.yml) for each, using the `service_should_load` lookup (checks `enabled AND shared`). +[`roles/sys-utils-service-loader/tasks/main.yml`](../../../roles/sys-utils-service-loader/tasks/main.yml): +- queries the ordered discovered service list +- checks `lookup('service', service_key).needed` +- skips roles already protected by `run_once_*` +- loads services through [`tasks/utils/load_app.yml`](../../../tasks/utils/load_app.yml) -### 2. Injection (add service to the app's nginx config) +Frontend service probe/load helper: +- [`roles/sys-utils-service-loader/tasks/load_service.yml`](../../../roles/sys-utils-service-loader/tasks/load_service.yml) -Decides whether a service is referenced inside an individual application's nginx vhost. -Controlled by `inj_enabled`, computed in [`roles/sys-front-inj-all/tasks/main.yml`](../../../roles/sys-front-inj-all/tasks/main.yml): +### Injection -```yaml -inj_enabled: "{{ applications | inj_enabled(application_id, SRV_WEB_INJ_COMP_FEATURES_ALL) }}" -``` +Injection decides whether a deployed app gets extra nginx integration such as +dashboard, logout, CSS, or JavaScript hooks. -The `inj_enabled` filter ([`roles/sys-front-inj-all/filter_plugins/inj_enabled.py`](../../../roles/sys-front-inj-all/filter_plugins/inj_enabled.py)) -reads `compose.services..enabled` for the **current app** and returns a dict of booleans. +This stays in: +- [`roles/sys-front-inj-all/tasks/main.yml`](../../../roles/sys-front-inj-all/tasks/main.yml) +- [`roles/sys-front-inj-all/filter_plugins/inj_enabled.py`](../../../roles/sys-front-inj-all/filter_plugins/inj_enabled.py) -Each injection role is then included conditionally: - -| Condition | Role loaded | -|---|---| -| `inj_enabled.matomo` | `sys-front-inj-matomo` — adds Matomo tracking snippet | -| `inj_enabled.logout` | `sys-front-inj-logout` — adds logout proxy endpoint | -| `inj_enabled.dashboard` | `sys-front-inj-dashboard` — adds dashboard iframe notifier | -| `inj_enabled.css` | `sys-front-inj-css` — adds corporate CSS | -| `inj_enabled.javascript` | `sys-front-inj-javascript` — adds JS injection | - -#### CSS injection (`inj_enabled.css`) - -`sys-front-inj-css` injects a shared corporate stylesheet into the application's nginx vhost. -The stylesheet itself lives in each role under `files/style.css` and is served via the CDN service. -It applies a minimal token-based theme (using the `--color-01-*` palette) so all apps share a consistent look. - -See the agent authoring guide for `style.css`: [`docs/agents/files/role/style.css.md`](../../../docs/agents/files/role/style.css.md) - -#### JavaScript injection (`inj_enabled.javascript`) - -`sys-front-inj-javascript` injects a shared JavaScript bundle into the application's nginx vhost. -The script lives in each role under `files/javascript.js` (or `templates/javascript.js.j2` for templated values). -It handles browser-side integration that cannot be solved via configuration or CSS alone — for example DOM mutations required to wire up dashboard or logout behaviour. - -See the agent authoring guide for `javascript.js`: [`docs/agents/files/role/javascript.js.md`](../../../docs/agents/files/role/javascript.js.md) - -**`lookup('service', ...)` does NOT add a service to the current domains.** -It only controls whether the service container is deployed. -The nginx domain injection is handled entirely by `inj_enabled` + the injection roles above. - -## `load_app.yml` — run-once loader - -File: [`tasks/utils/load_app.yml`](../../../tasks/utils/load_app.yml) - -Loads a role exactly once by setting `application_id` to the target role name and calling `include_role`. -The `run_once_` flag is set inside the loaded role itself (via `tasks/utils/once/flag.yml`) -to prevent duplicate loads across multiple app invocations. +Injection still reads the current app's `compose.services..enabled` flags. +It does not load provider roles. ## Lookup Plugins -### `service` — resolve a service and return its deployment flags +### `service` -File: [`plugins/lookup/service.py`](../../../plugins/lookup/service.py) +File: +[`plugins/lookup/service.py`](../../../plugins/lookup/service.py) + +Examples: ```yaml -lookup('service', 'matomo') # look up by service key -lookup('service', 'web-app-matomo') # look up by role name → returns canonical key -lookup('service', 'css') # alias key → returns id: css -lookup('service', 'web-svc-cdn') # role lookup → returns id: cdn (canonical) +lookup('service', 'matomo') +lookup('service', 'oidc') +lookup('service', 'web-svc-cdn') ``` -- Reads `applications`, `group_names`, and `SERVICE_REGISTRY` (from `group_vars/all/20_services.yml`) from Ansible variables -- Accepts either a service **key** (e.g. `matomo`, `css`) or a **role name** (e.g. `web-app-matomo`, `web-svc-cdn`) as the term -- When looking up by **key**, returns the entry for that exact key (`id` = the key you passed) -- When looking up by **role name**, returns the entry for the **canonical key** of that role -- Returns a dict per term: +Returns: +- `id` +- `role` +- `enabled` +- `shared` +- `needed` - | Field | Type | Meaning | - |-----------|--------|---------| - | `id` | string | Service key — equals the looked-up key, or the canonical key for role-based lookup | - | `role` | string | Provider role name (e.g. `web-app-matomo`) | - | `enabled` | bool | Any deployed app has `compose.services..enabled: true` | - | `shared` | bool | Any deployed app has `compose.services..shared: true` | - | `needed` | bool | Any deployed app has **both** `enabled` and `shared` (direct or transitively) | +Behavior: +- accepts either a service key or a provider role name +- resolves aliases through `canonical` +- resolves provider roles through discovered primary service keys +- computes `needed` transitively from enabled shared services -- **Transitive:** `needed` follows chains of enabled services recursively, but the final target must have both `enabled: true` AND `shared: true` -- **Limitation:** transitive resolution only fires when the service key in `compose.services` equals a full application ID. - Short keys (e.g. `collabora`) do not chain to `web-svc-collabora` — only the key `web-svc-collabora` would. -- Does **not** control nginx injection — see `inj_enabled` above -- Used in: [`roles/sys-utils-service-loader/tasks/main.yml`](../../../roles/sys-utils-service-loader/tasks/main.yml) -- Tests: [`tests/unit/plugins/lookup/test_service.py`](../../../tests/unit/plugins/lookup/test_service.py), [`tests/integration/test_services_resolvable.py`](../../../tests/integration/test_services_resolvable.py) +### `service_registry` -### `service_should_load` — should this service be loaded for the current app? +File: +[`plugins/lookup/service_registry.py`](../../../plugins/lookup/service_registry.py) -File: [`roles/sys-stk-backend/lookup_plugins/service_should_load.py`](../../../roles/sys-stk-backend/lookup_plugins/service_should_load.py) +Examples: ```yaml -query('service_should_load', service_id, application_id=application_id, service_name=service_name) | first +query('service_registry') | first +query('service_registry', 'ordered') | first ``` -- Checks `enabled AND shared` for a single `application_id` -- Guards against `run_once_*` already set and self-loading (`application_id == service_id`) -- Used in: [`roles/sys-stk-backend/tasks/_load_service.yml`](../../../roles/sys-stk-backend/tasks/_load_service.yml) -- Tests: [`tests/unit/roles/sys-stk-backend/lookup_plugins/test_service_should_load.py`](../../../tests/unit/roles/sys-stk-backend/lookup_plugins/test_service_should_load.py) +Modes: +- default: full discovered registry mapping +- `ordered`: ordered primary service entries for the service loader -### `inj_enabled` filter — which injections are active for this app? +### `applications_current_play` -File: [`roles/sys-front-inj-all/filter_plugins/inj_enabled.py`](../../../roles/sys-front-inj-all/filter_plugins/inj_enabled.py) +File: +[`plugins/lookup/applications_current_play.py`](../../../plugins/lookup/applications_current_play.py) + +Builds the current-play application set including: +- group-selected roles +- transitive shared service dependencies +- meta dependencies + +## Database Services + +Relational databases are regular services now: +- `svc-db-mariadb` provides `mariadb` +- `svc-db-postgres` provides `postgres` + +Applications express database choice directly via: ```yaml -applications | inj_enabled(application_id, feature_list) +compose: + services: + mariadb: + enabled: true + shared: true ``` -- Reads `compose.services..enabled` for the current `application_id` -- Returns `{feature: bool}` dict used to gate injection roles -- Used in: [`roles/sys-front-inj-all/tasks/main.yml`](../../../roles/sys-front-inj-all/tasks/main.yml) +or: -## Python CLI Resolver +```yaml +compose: + services: + postgres: + enabled: true + shared: false +``` -File: [`cli/meta/applications/resolution/services/resolver.py`](../../../cli/meta/applications/resolution/services/resolver.py) - -Reads `group_vars/all/20_services.yml` and resolves which provider roles an application needs, -following service dependencies transitively (BFS). Used by the CLI to compute deploy order and -dependency graphs. - -- `resolve_direct_service_roles_from_config(config)` — roles needed directly by one app config -- `ServicesResolver.resolve_transitively(role_name)` — full BFS over transitive dependencies -- Tests: [`tests/unit/cli/meta/applications/resolution/services/test_resolver.py`](../../../tests/unit/cli/meta/applications/resolution/services/test_resolver.py) +The `lookup('database', ...)` API remains as the convenience accessor for database +connection values, but it now resolves the active direct database service from those +role-local keys instead of `compose.services.database.type`. ## Related Files | File | Purpose | |---|---| -| [`group_vars/all/20_services.yml`](../../../group_vars/all/20_services.yml) | **SPOT** — service key → role mapping with `type`, optional `canonical` | -| [`roles/sys-utils-service-loader/tasks/main.yml`](../../../roles/sys-utils-service-loader/tasks/main.yml) | **SPOT** — global frontend service loading loop | -| [`tasks/stages/02_server.yml`](../../../tasks/stages/02_server.yml) | Calls the global frontend service loader before `web-svc` and `web-app` roles | -| [`roles/sys-utils-service-loader/tasks/load_frontend_service.yml`](../../../roles/sys-utils-service-loader/tasks/load_frontend_service.yml) | Reachability check + conditional load per frontend service | -| [`roles/sys-front-inj-all/tasks/main.yml`](../../../roles/sys-front-inj-all/tasks/main.yml) | Orchestrates injection for every deployed app | -| [`roles/sys-front-inj-all/filter_plugins/inj_enabled.py`](../../../roles/sys-front-inj-all/filter_plugins/inj_enabled.py) | `inj_enabled` filter — per-app injection flags | +| [`utils/service_registry.py`](../../../utils/service_registry.py) | Service discovery, `provides`, `canonical`, bucket detection, `run_after` ordering | +| [`plugins/lookup/service_registry.py`](../../../plugins/lookup/service_registry.py) | Exposes the discovered registry and ordered provider list to Ansible | +| [`plugins/lookup/service.py`](../../../plugins/lookup/service.py) | Resolves service flags and transitive need | +| [`plugins/lookup/applications_current_play.py`](../../../plugins/lookup/applications_current_play.py) | Builds the current play app graph with shared service deps | +| [`roles/sys-utils-service-loader/tasks/main.yml`](../../../roles/sys-utils-service-loader/tasks/main.yml) | Single shared-service loader SPOT | +| [`roles/sys-utils-service-loader/tasks/load_service.yml`](../../../roles/sys-utils-service-loader/tasks/load_service.yml) | Per-service load helper used by the central service loader | +| [`tasks/stages/01_constructor.yml`](../../../tasks/stages/01_constructor.yml) | Calls the service loader during constructor | | [`tasks/utils/load_app.yml`](../../../tasks/utils/load_app.yml) | Run-once role loader | -| [`tasks/utils/once/flag.yml`](../../../tasks/utils/once/flag.yml) | Sets `run_once_` fact to prevent duplicate loads | -| [`plugins/lookup/service.py`](../../../plugins/lookup/service.py) | Resolve service by key or role; returns `{id, role, enabled, shared, needed}` | -| [`tests/integration/test_services_resolvable.py`](../../../tests/integration/test_services_resolvable.py) | Integration: all keys/roles in `20_services.yml` resolve correctly | -| [`tests/integration/test_services_canonical.py`](../../../tests/integration/test_services_canonical.py) | Lint: canonical field consistency rules enforced | -| [`roles/sys-stk-backend/lookup_plugins/service_should_load.py`](../../../roles/sys-stk-backend/lookup_plugins/service_should_load.py) | "Should service load for this app?" lookup | -| [`cli/meta/applications/resolution/services/resolver.py`](../../../cli/meta/applications/resolution/services/resolver.py) | Python-side service resolver (CLI use) | -| [`utils/config_utils.py`](../../../utils/config_utils.py) | `get_app_conf()` — hierarchical config accessor | -| [`roles/sys-stk-backend/tasks/main.yml`](../../../roles/sys-stk-backend/tasks/main.yml) | Backend service loading (ldap, ollama, oauth2) | -| [`roles/sys-stk-backend/tasks/_load_service.yml`](../../../roles/sys-stk-backend/tasks/_load_service.yml) | Single-service load helper for backend stack | +| [`tests/unit/utils/test_service_registry.py`](../../../tests/unit/utils/test_service_registry.py) | Unit tests for discovery, buckets, and `run_after` ordering | +| [`tests/unit/plugins/lookup/test_service.py`](../../../tests/unit/plugins/lookup/test_service.py) | Unit tests for `lookup('service', ...)` | +| [`tests/integration/test_services_resolvable.py`](../../../tests/integration/test_services_resolvable.py) | Integration checks for discovered service resolution | +| [`tests/integration/test_services_canonical.py`](../../../tests/integration/test_services_canonical.py) | Canonical alias consistency checks | +| [`tests/integration/test_service_transitive_dependencies.py`](../../../tests/integration/test_service_transitive_dependencies.py) | Integration coverage for transitive dependency resolution | diff --git a/docs/requirements/001-service-registry-refactoring.md b/docs/requirements/001-service-registry-refactoring.md index 61a9545d4d..95e3185fb5 100644 --- a/docs/requirements/001-service-registry-refactoring.md +++ b/docs/requirements/001-service-registry-refactoring.md @@ -8,11 +8,11 @@ self-describing. ## Acceptance Criteria -- [ ] `group_vars/all/20_services.yml` is deleted; no role or plugin reads from it. -- [ ] Every service role declares its service metadata in its own `config/main.yml` +- [x] `group_vars/all/20_services.yml` is deleted; no role or plugin reads from it. +- [x] Every service role declares its service metadata in its own `config/main.yml` under `compose.services.` (with optional `provides:`, `canonical:`) instead of in the central registry. -- [ ] Load order *within* the same deploy type (universal, workstation, server) is +- [x] Load order *within* the same deploy type (universal, workstation, server) is declared via a custom `run_after:` list in the role's `meta/main.yml`. Each entry is a role name (e.g. `web-svc-cdn`). `roles/sys-utils-service-loader` MUST read this field and load the listed roles before the declaring role within @@ -26,7 +26,7 @@ self-describing. cross-type dependency, `roles/sys-utils-service-loader` MUST fail hard with a clear error instead of ignoring it. Apps MUST NOT require the user to list those dependencies explicitly in `APPS`. -- [ ] The special `role_template: "svc-db-{type}"` database loading logic is removed; +- [x] The special `role_template: "svc-db-{type}"` database loading logic is removed; PostgreSQL and MariaDB are defined as regular services in their own `config/main.yml` (same as any other service). Because databases are a different deploy type from apps, they are loaded automatically before apps by @@ -69,12 +69,12 @@ self-describing. # web-app-matomo/config/main.yml — no database.type needed for service loading # (svc-db-mariadb is loaded automatically before web-app-* by the service loader) ``` -- [ ] `frontend` / `backend` type is auto-detected from the role name prefix +- [x] `frontend` / `backend` type is auto-detected from the role name prefix (`web-app-*`, `web-svc-*` → frontend; everything else → backend). The `type:` field for this purpose is removed from role `config/main.yml`. No legacy support is kept for role-local service metadata that still declares this `type:` field. -- [ ] `canonical` aliases are declared under `compose.services..canonical` +- [x] `canonical` aliases are declared under `compose.services..canonical` in the role's `config/main.yml`, where `` is the entity name returned by the existing `get_entity_name` function for that role (e.g. `web-svc-cdn` exposes the primary entity `cdn` plus the alias @@ -94,7 +94,7 @@ self-describing. enabled: true canonical: cdn ``` -- [ ] A role MAY declare an optional `provides:` field under its primary service entry +- [x] A role MAY declare an optional `provides:` field under its primary service entry in `config/main.yml`. When present, `roles/sys-utils-service-loader` registers the role under that functional name instead of the entity name returned by `get_entity_name`. Roles without `provides:` are registered under their entity @@ -129,24 +129,24 @@ self-describing. All consumers (templates, lookups, `run_after:` lists) continue to reference the functional name (e.g. `oidc`, `email`, `ldap`) — no consumer changes are required for roles that already use these names. -- [ ] `roles/sys-utils-service-loader` is the single place that loads all services. +- [x] `roles/sys-utils-service-loader` is the single place that loads all services. It MUST use the existing function that determines which roles are universal, workstation, or server to derive the load order: universal roles first, then `web-svc-*`, then `web-app-*`. -- [ ] `roles/sys-utils-service-loader` is invoked from the constructor stage +- [x] `roles/sys-utils-service-loader` is invoked from the constructor stage (`tasks/stages/01_constructor.yml`) instead of the server block (`tasks/stages/02_server.yml`). -- [ ] All service dependencies — including databases (e.g. `svc-db-mariadb`, +- [x] All service dependencies — including databases (e.g. `svc-db-mariadb`, `svc-db-postgres`) and shared services (e.g. `web-app-keycloak`) — are loaded automatically by `roles/sys-utils-service-loader` in the constructor stage. No service dependency MUST ever require the user to list it explicitly in `APPS`. -- [ ] Every file that currently reads from `SERVICE_REGISTRY` or `20_services.yml` +- [x] Every file that currently reads from `SERVICE_REGISTRY` or `20_services.yml` MUST be updated to discover service metadata from role `config/main.yml` files instead. This includes at minimum: - `plugins/lookup/service.py` - `plugins/lookup/applications_current_play.py` - any filter plugin, task, or template that references `SERVICE_REGISTRY` -- [ ] New unit and integration tests MUST be written for the service discovery +- [x] New unit and integration tests MUST be written for the service discovery mechanism that replaces `SERVICE_REGISTRY`. Follow the rules in [testing.md](../agents/action/testing.md), [unit.md](../contributing/code/tests/unit.md), and @@ -157,13 +157,13 @@ self-describing. - Correct load order produced by `sys-utils-service-loader` - `get_entity_name` derivation for all relevant role name prefixes - `run_after:` ordering within the same deploy type -- [ ] Every file and role that is modified as part of this refactoring MUST also be +- [x] Every file and role that is modified as part of this refactoring MUST also be simplified and refactored where possible, following the principles in [principles.md](../contributing/code/principles.md). Do not limit changes to the minimum required — use the mandatory touch as an opportunity to improve clarity, reduce duplication, and remove dead code in the same pass. -- [ ] All existing integration and unit tests pass after the refactoring. -- [ ] Once all other Acceptance Criteria are checked off and the full validation +- [x] All existing integration and unit tests pass after the refactoring. +- [x] Once all other Acceptance Criteria are checked off and the full validation app set deploys successfully, `docs/contributing/code/services.md` MUST be updated to reflect the new role-local configuration model. The update MUST follow the documentation guidelines in @@ -227,3 +227,22 @@ that app. Do not carry over assumptions from the previous app. 6. Check off the relevant Acceptance Criteria above if fully covered by this app. Repeat the full cycle from `web-app-nextcloud` down to `web-svc-file` until every criterion is checked. + +## Out-of-Scope Changes (Stashed) + +The following changes in `roles/web-app-nextcloud/` were identified as unrelated to this requirement and were unstaged and stashed for later handling: + +- `tasks/_plugin_a_routines.yml` — tarball-based plugin install (DinD IPv6 workaround) +- `tasks/_plugin_install_from_tarball.yml` *(new)* — tarball install task file +- `tasks/main.yml` — Nextcloud appstore metadata fetch for plugin compatibility +- `templates/config/apps_paths.config.php.j2` *(new)* — `custom_apps` path registration + +**Stash name:** `nextcloud: tarball plugin install (unrelated to req-001)` +**Machine:** `msi-stealth-gs66` + +### `roles/web-svc-coturn/` + +- `templates/compose.yml.j2` — Coturn 4.9 fix: collapse IPv4/IPv6 `--external-ip` flags into one and replace `turnutils_stunclient` healthcheck with `pgrep` + +**Stash name:** `coturn: fix external-ip IPv4/IPv6 and healthcheck (unrelated to req-001)` +**Machine:** `msi-stealth-gs66` diff --git a/group_vars/all/20_services.yml b/group_vars/all/20_services.yml deleted file mode 100644 index 3840acc22d..0000000000 --- a/group_vars/all/20_services.yml +++ /dev/null @@ -1,91 +0,0 @@ -# SPOT: canonical service key → provider role mapping. -# -# Each entry requires compose.services..enabled: true AND shared: true. -# The 'type' field determines which stack loads the service: -# frontend: loaded early in tasks/stages/02_server.yml for all deployed apps -# backend: loaded by sys-stk-backend per application -# -# Optional fields: -# role_template: "svc-db-{type}" -# The placeholder {type} is substituted from compose.services..type. -# canonical: -# Required when multiple keys share the same role. Points to the primary -# key so that role-based reverse lookup always returns a deterministic id. -# The primary key must have no canonical field. Aliases must set canonical. -# -# See: docs/contributing/code/services.md - -SERVICE_REGISTRY: - matomo: - role: web-app-matomo - type: frontend - - file: - role: web-svc-file - type: frontend - - asset: - role: web-svc-asset - type: frontend - - cdn: - role: web-svc-cdn - type: frontend - - css: - role: web-svc-cdn - type: frontend - canonical: cdn - - javascript: - role: web-svc-cdn - type: frontend - canonical: cdn - - logout: - role: web-svc-logout - type: frontend - - email: - role: web-app-mailu - type: frontend - - oidc: - role: web-app-keycloak - type: frontend - - simpleicons: - role: web-svc-simpleicons - type: frontend - - collabora: - role: web-svc-collabora - type: frontend - - coturn: - role: web-svc-coturn - type: frontend - - onlyoffice: - role: web-svc-onlyoffice - type: frontend - - libretranslate: - role: web-svc-libretranslate - type: frontend - - dashboard: - role: web-app-dashboard - type: frontend - - ldap: - role: svc-db-openldap - type: backend - - ollama: - role: svc-ai-ollama - type: backend - - database: - role_template: "svc-db-{type}" - type: backend diff --git a/plugins/filter/compose_volumes.py b/plugins/filter/compose_volumes.py index 97fda96a1b..cba1c4fdc8 100644 --- a/plugins/filter/compose_volumes.py +++ b/plugins/filter/compose_volumes.py @@ -12,11 +12,19 @@ try: ) from plugins.filter.get_app_conf import get_app_conf from plugins.filter.get_entity_name import get_entity_name + from utils.database_service import ( + get_database_service_config, + resolve_database_service_key, + ) except ModuleNotFoundError: # Fallback when loaded by Ansible plugin loader from filter_plugins path. from docker_service_enabled import FilterModule as _DockerServiceEnabledFilter from get_app_conf import get_app_conf from get_entity_name import get_entity_name + from utils.database_service import ( + get_database_service_config, + resolve_database_service_key, + ) def _to_plain(obj: Any) -> Any: @@ -65,8 +73,8 @@ def compose_volumes( Logic is identical to roles/sys-svc-compose/templates/volumes.yml.j2: - database volume if: - is_docker_service_enabled(database) - and not compose.services.database.shared + a direct mariadb/postgres service is enabled + and that service is not shared name: database_volume (no fallback!) @@ -100,17 +108,10 @@ def compose_volumes( # ------------------------------------------------------------------ # Database volume (same condition as Jinja2) # ------------------------------------------------------------------ - database_needed = _DockerServiceEnabledFilter.is_docker_service_enabled( - applications, application_id, "database" - ) and not bool( - get_app_conf( - applications=applications, - application_id=application_id, - config_path="compose.services.database.shared", - strict=False, - default=False, - skip_missing_app=True, - ) + database_service_key = resolve_database_service_key(applications, application_id) + database_service = get_database_service_config(applications, application_id) + database_needed = bool(database_service_key) and not bool( + database_service.get("shared", False) ) if database_needed: diff --git a/plugins/filter/service_load_enabled.py b/plugins/filter/service_load_enabled.py deleted file mode 100644 index 2cdb824cd2..0000000000 --- a/plugins/filter/service_load_enabled.py +++ /dev/null @@ -1,39 +0,0 @@ -from utils.config_utils import get_app_conf as _get_app_conf - - -def service_load_enabled(applications, application_id, service_name, default=False): - """ - Return True if compose.services..enabled AND .shared are true. - - Uses the existing utils.config_utils.get_app_conf implementation, - so schema/strict/default behavior stays consistent across the codebase. - - Usage: - {{ applications | service_load_enabled(application_id, 'ldap') }} - """ - - # We explicitly use strict=False here to behave like a "safe boolean probe". - enabled = _get_app_conf( - applications=applications, - application_id=application_id, - config_path=f"compose.services.{service_name}.enabled", - strict=False, - default=default, - skip_missing_app=False, - ) - - shared = _get_app_conf( - applications=applications, - application_id=application_id, - config_path=f"compose.services.{service_name}.shared", - strict=False, - default=default, - skip_missing_app=False, - ) - - return bool(enabled) and bool(shared) - - -class FilterModule: - def filters(self): - return {"service_load_enabled": service_load_enabled} diff --git a/plugins/lookup/applications_current_play.py b/plugins/lookup/applications_current_play.py index d0adda647c..93b9032b8c 100644 --- a/plugins/lookup/applications_current_play.py +++ b/plugins/lookup/applications_current_play.py @@ -1,13 +1,14 @@ from __future__ import annotations import os -import yaml from typing import Any, Dict, List, Optional +import yaml from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase from utils.applications.in_group_deps import applications_if_group_and_all_deps +from utils.service_registry import build_service_registry_from_applications class LookupModule(LookupBase): @@ -26,10 +27,16 @@ class LookupModule(LookupBase): applications = kwargs.get("applications", vars_.get("applications")) group_names = kwargs.get("group_names", vars_.get("group_names", [])) + if not isinstance(applications, dict): + raise AnsibleError( + "applications_current_play: required variable 'applications' must be a mapping" + ) project_root = self._get_project_root() roles_dir = os.path.join(project_root, "roles") - service_registry = self._load_service_registry(project_root) + service_registry = kwargs.get("service_registry") + if service_registry is None: + service_registry = build_service_registry_from_applications(applications) try: result = applications_if_group_and_all_deps( @@ -53,17 +60,6 @@ class LookupModule(LookupBase): plugin_dir = os.path.dirname(__file__) return os.path.abspath(os.path.join(plugin_dir, "..", "..")) - def _load_service_registry(self, project_root: str) -> Dict[str, Any]: - path = os.path.join(project_root, "group_vars", "all", "20_services.yml") - if not os.path.isfile(path): - return {} - try: - with open(path, encoding="utf-8") as f: - data = yaml.safe_load(f) or {} - return data.get("SERVICE_REGISTRY", {}) - except Exception: - return {} - def _meta_deps(self, role: str, roles_dir: str) -> List[str]: meta_file = os.path.join(roles_dir, role, "meta", "main.yml") if not os.path.isfile(meta_file): diff --git a/plugins/lookup/database.py b/plugins/lookup/database.py index 3e7f83ede1..9172c4f771 100644 --- a/plugins/lookup/database.py +++ b/plugins/lookup/database.py @@ -7,6 +7,10 @@ from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase from utils.config_utils import get_app_conf +from utils.database_service import ( + get_database_service_config, + resolve_database_service_key, +) from utils.entity_name_utils import get_entity_name @@ -56,35 +60,17 @@ class LookupModule(LookupBase): consumer_entity = get_entity_name(consumer_id) - enabled = bool( - get_app_conf( - applications, - consumer_id, - "compose.services.database.enabled", - strict=False, - default=False, - ) - ) - shared = bool( - get_app_conf( - applications, - consumer_id, - "compose.services.database.shared", - strict=False, - default=False, - ) - ) + try: + dbtype = resolve_database_service_key(applications, consumer_id) + except ValueError as exc: + raise AnsibleError(f"database: {exc}") from exc - dbtype = get_app_conf( - applications, - consumer_id, - "compose.services.database.type", - strict=False, - default="", - ) - dbtype = (str(dbtype) if dbtype is not None else "").strip() + database_service = get_database_service_config(applications, consumer_id) + enabled = bool(database_service.get("enabled", False)) + shared = bool(database_service.get("shared", False)) - # If no dbtype configured: keep behavior similar to your vars (mostly empty) + # If no direct database service is configured: keep behavior similar to the + # historical empty-value lookup payload. if not dbtype: resolved = { "id": "", @@ -154,7 +140,7 @@ class LookupModule(LookupBase): version = get_app_conf( applications, consumer_id, - "compose.services.database.version", + f"compose.services.{dbtype}.version", strict=False, default=default_version, ) diff --git a/plugins/lookup/service.py b/plugins/lookup/service.py index 51be8567b8..b45965ab58 100644 --- a/plugins/lookup/service.py +++ b/plugins/lookup/service.py @@ -6,23 +6,32 @@ from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase from utils.config_utils import get_app_conf +from utils.service_registry import ( + build_role_to_primary_service_key, + build_service_registry_from_applications, + canonical_service_key, + equivalent_service_keys, +) def _get_service_flag( applications: Dict[str, Any], app_id: str, - service_key: str, + service_keys: List[str], flag: str, ) -> bool: - return bool( - get_app_conf( - applications=applications, - application_id=app_id, - config_path=f"compose.services.{service_key}.{flag}", - strict=False, - default=False, - skip_missing_app=True, + return any( + bool( + get_app_conf( + applications=applications, + application_id=app_id, + config_path=f"compose.services.{service_key}.{flag}", + strict=False, + default=False, + skip_missing_app=True, + ) ) + for service_key in service_keys ) @@ -50,15 +59,8 @@ def _get_enabled_service_keys( def _resolve_service_provider_app_id( applications: Dict[str, Any], service_registry: Dict[str, Any], - app_id: str, service_key: str, ) -> Optional[str]: - """Resolve a service key to the provider role/application id. - - Transitive service recursion must follow SERVICE_REGISTRY so short keys such - as ``asset`` recurse into ``web-svc-asset`` instead of requiring callers to - use full application ids inside compose.services. - """ entry = service_registry.get(service_key) if not isinstance(entry, dict): return None @@ -66,23 +68,7 @@ def _resolve_service_provider_app_id( role = entry.get("role") if isinstance(role, str) and role: return role - - role_template = entry.get("role_template") - if not isinstance(role_template, str) or not role_template: - return None - - service_type = get_app_conf( - applications=applications, - application_id=app_id, - config_path=f"compose.services.{service_key}.type", - strict=False, - default="", - skip_missing_app=True, - ) - if not isinstance(service_type, str) or not service_type: - return None - - return role_template.replace("{type}", service_type) + return None def _is_service_needed( @@ -101,8 +87,9 @@ def _is_service_needed( return False visited.add(app_id) - enabled = _get_service_flag(applications, app_id, service_key, "enabled") - shared = _get_service_flag(applications, app_id, service_key, "shared") + service_keys = equivalent_service_keys(service_registry, service_key) + enabled = _get_service_flag(applications, app_id, service_keys, "enabled") + shared = _get_service_flag(applications, app_id, service_keys, "shared") if enabled and shared: return True @@ -110,7 +97,7 @@ def _is_service_needed( if svc == service_key: continue dep_app_id = _resolve_service_provider_app_id( - applications, service_registry, app_id, svc + applications, service_registry, svc ) if dep_app_id and dep_app_id in applications: if _is_service_needed( @@ -122,21 +109,7 @@ def _is_service_needed( def _build_role_to_key(service_registry: Dict[str, Any]) -> Dict[str, str]: - """Map each role name to its canonical service key. - - When multiple keys share the same role, the canonical key is determined by - the 'canonical' field on alias entries. The primary key (no 'canonical' - field) is used as the fallback so that role-based reverse lookup always - returns a single, deterministic id. - """ - result: Dict[str, str] = {} - for key, entry in service_registry.items(): - if not isinstance(entry, dict) or "role" not in entry: - continue - role = entry["role"] - canonical_key = entry.get("canonical", key) - result[role] = canonical_key - return result + return build_role_to_primary_service_key(service_registry) def _resolve_term( @@ -150,12 +123,12 @@ def _resolve_term( """ if term in service_registry: entry = service_registry[term] - role = entry.get("role") or entry.get("role_template", "") + role = entry.get("role", "") return term, str(role) if term in role_to_key: key = role_to_key[term] entry = service_registry[key] - role = entry.get("role") or entry.get("role_template", "") + role = entry.get("role", "") return key, str(role) raise AnsibleError( f"service: '{term}' is neither a known service key nor a known role name. " @@ -171,16 +144,18 @@ def _compute_flags( service_key: str, ) -> Dict[str, bool]: deployed = [app_id for app_id in group_names if app_id in applications] + equivalent_keys = equivalent_service_keys(service_registry, service_key) any_enabled = any( - _get_service_flag(applications, app_id, service_key, "enabled") + _get_service_flag(applications, app_id, equivalent_keys, "enabled") for app_id in deployed ) any_shared = any( - _get_service_flag(applications, app_id, service_key, "shared") + _get_service_flag(applications, app_id, equivalent_keys, "shared") for app_id in deployed ) + primary_key = canonical_service_key(service_registry, service_key) any_needed = any( - _is_service_needed(applications, service_registry, app_id, service_key, set()) + _is_service_needed(applications, service_registry, app_id, primary_key, set()) for app_id in deployed ) return {"enabled": any_enabled, "shared": any_shared, "needed": any_needed} @@ -194,9 +169,8 @@ class LookupModule(LookupBase): lookup('service', 'matomo') lookup('service', 'web-app-matomo') # resolved via reverse mapping - Reads 'applications', 'group_names', and 'SERVICE_REGISTRY' from Ansible variables. - The 'SERVICE_REGISTRY' variable is the canonical key → role mapping from - group_vars/all/20_services.yml and is automatically available in all plays. + Reads 'applications' and 'group_names' from Ansible variables and discovers + service providers from the role-local compose.services metadata. Returns a dict per term: id — canonical service key (e.g. 'matomo') @@ -230,12 +204,11 @@ class LookupModule(LookupBase): "service: required variable 'group_names' must be a list" ) - service_registry = kwargs.get("service_registry", vars_.get("SERVICE_REGISTRY")) + service_registry = kwargs.get("service_registry") + if service_registry is None: + service_registry = build_service_registry_from_applications(applications) if not isinstance(service_registry, dict): - raise AnsibleError( - "service: required variable 'SERVICE_REGISTRY' must be a mapping " - "(loaded from group_vars/all/20_services.yml)" - ) + raise AnsibleError("service: 'service_registry' must be a mapping") role_to_key = _build_role_to_key(service_registry) diff --git a/plugins/lookup/service_registry.py b/plugins/lookup/service_registry.py new file mode 100644 index 0000000000..682bda0d6c --- /dev/null +++ b/plugins/lookup/service_registry.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any, Dict, List, Optional + +from ansible.errors import AnsibleError +from ansible.plugins.lookup import LookupBase + +from utils.service_registry import ( + build_service_registry_from_applications, + ordered_primary_service_entries, +) + + +class LookupModule(LookupBase): + """ + Discover the role-local service registry. + + Usage: + {{ query('service_registry') | first }} + {{ query('service_registry', 'ordered') | first }} + """ + + def run( + self, + terms: List[Any], + variables: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Any]: + vars_ = variables or getattr(self._templar, "available_variables", {}) or {} + applications = kwargs.get("applications", vars_.get("applications")) + if not isinstance(applications, dict): + raise AnsibleError( + "service_registry: required variable 'applications' must be a mapping" + ) + + roles_dir = Path(kwargs.get("roles_dir") or Path.cwd() / "roles") + registry = build_service_registry_from_applications(applications) + mode = str(terms[0]).strip() if terms else "mapping" + + if mode in {"mapping", ""}: + return [registry] + if mode == "ordered": + return [ordered_primary_service_entries(registry, roles_dir)] + + raise AnsibleError( + f"service_registry: unsupported mode '{mode}' (expected 'mapping' or 'ordered')" + ) diff --git a/roles/svc-db-mariadb/config/main.yml b/roles/svc-db-mariadb/config/main.yml index b80bf8375b..6db5b336a9 100644 --- a/roles/svc-db-mariadb/config/main.yml +++ b/roles/svc-db-mariadb/config/main.yml @@ -1,6 +1,8 @@ compose: services: mariadb: + enabled: false + shared: true version: "latest" image: "mariadb" name: "mariadb" @@ -12,10 +14,6 @@ compose: mem_reservation: "2g" mem_limit: "4g" pids_limit: 1024 - database: - shared: true - enabled: true - type: "mariadb" network: "mariadb" volumes: data: "mariadb_data" diff --git a/roles/svc-db-mariadb/tasks/01_core.yml b/roles/svc-db-mariadb/tasks/01_core.yml index ea94b958b6..9f1377234b 100644 --- a/roles/svc-db-mariadb/tasks/01_core.yml +++ b/roles/svc-db-mariadb/tasks/01_core.yml @@ -1,3 +1,5 @@ +- include_tasks: utils/once/flag.yml + - name: "Setup container network for {{ application_id }}" include_tasks: "{{ [playbook_dir, 'roles/sys-svc-compose/tasks/utils/network.yml' ] | path_join }}" vars: @@ -79,5 +81,3 @@ until: mariadb_ready is succeeded changed_when: false when: MARIADB_EXPOSE_LOCAL | bool - -- include_tasks: utils/once/flag.yml diff --git a/roles/svc-db-mariadb/tasks/main.yml b/roles/svc-db-mariadb/tasks/main.yml index a2c53cd2db..5b53b030b5 100644 --- a/roles/svc-db-mariadb/tasks/main.yml +++ b/roles/svc-db-mariadb/tasks/main.yml @@ -1,10 +1,8 @@ - -- block: - - include_tasks: 01_core.yml - when: run_once_svc_db_mariadb is not defined - - - name: "Initialize dedicated database" - include_tasks: 02_init.yml - when: database_init | bool +- include_tasks: 01_core.yml + when: run_once_svc_db_mariadb is not defined vars: application_id: svc-db-mariadb + +- name: "Initialize dedicated database" + include_tasks: 02_init.yml + when: database_init | bool diff --git a/roles/svc-db-openldap/config/main.yml b/roles/svc-db-openldap/config/main.yml index 79877c059c..c2620c99c5 100644 --- a/roles/svc-db-openldap/config/main.yml +++ b/roles/svc-db-openldap/config/main.yml @@ -5,10 +5,10 @@ network: compose: services: - ldap: - enabled: true - shared: true openldap: + enabled: false + shared: true + provides: ldap image: "debian" version: "bookworm-slim" name: "openldap" diff --git a/roles/svc-db-postgres/config/main.yml b/roles/svc-db-postgres/config/main.yml index ff6e02eb37..c262e56637 100644 --- a/roles/svc-db-postgres/config/main.yml +++ b/roles/svc-db-postgres/config/main.yml @@ -1,6 +1,8 @@ compose: services: postgres: + enabled: false + shared: true # Postgis is necessary for mobilizon image: postgis/postgis name: postgres @@ -14,10 +16,6 @@ compose: mem_reservation: "4g" mem_limit: "6g" pids_limit: 1024 - database: - shared: true - enabled: true - type: "postgres" volumes: data: "postgres_data" network: "postgres" diff --git a/roles/svc-db-postgres/tasks/main.yml b/roles/svc-db-postgres/tasks/main.yml index f9c70d7414..65d8e04389 100644 --- a/roles/svc-db-postgres/tasks/main.yml +++ b/roles/svc-db-postgres/tasks/main.yml @@ -1,14 +1,13 @@ -- block: - - include_tasks: 01_core.yml - when: run_once_svc_db_postgres is not defined - - - include_tasks: utils/load_handlers.yml - # Necessary because docker handlers are overwritten by condition - vars: - handler_role_name: "sys-svc-compose" - - - name: "Initialize dedicated database" - include_tasks: 02_init.yml - when: database_init | bool +- include_tasks: 01_core.yml + when: run_once_svc_db_postgres is not defined vars: application_id: svc-db-postgres + +- include_tasks: utils/load_handlers.yml + # Necessary because docker handlers are overwritten by condition + vars: + handler_role_name: "sys-svc-compose" + +- name: "Initialize dedicated database" + include_tasks: 02_init.yml + when: database_init | bool diff --git a/roles/sys-ctl-alm-compose/tasks/01_core.yml b/roles/sys-ctl-alm-compose/tasks/01_core.yml index f20e489ba5..135aea3e15 100644 --- a/roles/sys-ctl-alm-compose/tasks/01_core.yml +++ b/roles/sys-ctl-alm-compose/tasks/01_core.yml @@ -39,3 +39,6 @@ state: started when: - MODE_ASSERT | bool + # Shared-service preloading happens before Mailu exposes its final TLS SMTP + # listener, so the notifier self-test must wait for the normal app phase. + - not (_service_loader_preloading | default(false) | bool) diff --git a/roles/sys-stk-backend/lookup_plugins/service_should_load.py b/roles/sys-stk-backend/lookup_plugins/service_should_load.py deleted file mode 100644 index 2eae6a7168..0000000000 --- a/roles/sys-stk-backend/lookup_plugins/service_should_load.py +++ /dev/null @@ -1,95 +0,0 @@ -from __future__ import annotations - -from typing import Any, Dict, List, Optional - -from ansible.errors import AnsibleError -from ansible.plugins.lookup import LookupBase - -from utils.config_utils import get_app_conf - - -def _require_non_empty(value: Any, name: str) -> str: - s = str(value).strip() - if not s: - raise AnsibleError(f"service_should_load: '{name}' must not be empty") - return s - - -def _service_enabled_and_shared( - applications: Dict[str, Any], - application_id: str, - service_name: str, - default: bool, -) -> bool: - enabled = get_app_conf( - applications=applications, - application_id=application_id, - config_path=f"compose.services.{service_name}.enabled", - strict=False, - default=default, - skip_missing_app=False, - ) - shared = get_app_conf( - applications=applications, - application_id=application_id, - config_path=f"compose.services.{service_name}.shared", - strict=False, - default=default, - skip_missing_app=False, - ) - return bool(enabled) and bool(shared) - - -def _run_once_var_name(service_id: str) -> str: - return f"run_once_{service_id.replace('-', '_')}" - - -class LookupModule(LookupBase): - """ - Evaluate whether a backend service should be loaded. - - Usage: - {{ query('service_should_load', service_id, application_id=application_id, service_name=service_name) | first }} - """ - - def run( - self, - terms: List[Any], - variables: Optional[Dict[str, Any]] = None, - **kwargs: Any, - ) -> List[bool]: - if not terms: - return [] - - vars_ = variables or getattr(self._templar, "available_variables", {}) or {} - applications = kwargs.get("applications", vars_.get("applications")) - if not isinstance(applications, dict): - raise AnsibleError( - "service_should_load: required variable 'applications' must be a mapping" - ) - - application_id = _require_non_empty( - kwargs.get("application_id", vars_.get("application_id")), "application_id" - ) - service_name = _require_non_empty( - kwargs.get("service_name", vars_.get("service_name")), "service_name" - ) - default = bool(kwargs.get("default", False)) - - results: List[bool] = [] - for term in terms: - service_id = _require_non_empty(term, "service_id") - run_once_defined = _run_once_var_name(service_id) in vars_ - should_load = ( - _service_enabled_and_shared( - applications=applications, - application_id=application_id, - service_name=service_name, - default=default, - ) - and (not run_once_defined) - and (application_id != service_id) - ) - results.append(bool(should_load)) - - return results diff --git a/roles/sys-stk-backend/tasks/_load_service.yml b/roles/sys-stk-backend/tasks/_load_service.yml deleted file mode 100644 index 5b275ef556..0000000000 --- a/roles/sys-stk-backend/tasks/_load_service.yml +++ /dev/null @@ -1,19 +0,0 @@ -- name: "SYS-STK-BACKEND | Compute load flag for '{{ service_id }}' (enabled && shared)" - ansible.builtin.set_fact: - load_service: >- - {{ - query( - 'service_should_load', - service_id, - application_id=application_id, - service_name=service_name, - applications=applications, - default=False - ) | first - }} - -- name: "SYS-STK-BACKEND | Load '{{ service_id }}' (Once)" - ansible.builtin.include_tasks: "utils/load_app.yml" - vars: - load_app_id: "{{ service_id }}" - when: load_service | bool diff --git a/roles/sys-stk-backend/tasks/main.yml b/roles/sys-stk-backend/tasks/main.yml index 606d1d334d..f462bc8431 100644 --- a/roles/sys-stk-backend/tasks/main.yml +++ b/roles/sys-stk-backend/tasks/main.yml @@ -1,40 +1,38 @@ # run_once_sys_stk_backend: disabled +- name: "Resolve backend context for '{{ application_id }}'" + ansible.builtin.set_fact: + _sys_stk_backend_database_consumer_id: >- + {{ database_consumer_id | default(application_id) }} + _sys_stk_backend_database_enabled: >- + {{ lookup('database', application_id, 'enabled') | bool }} + _sys_stk_backend_oauth2_enabled: >- + {{ lookup('config', application_id, 'compose.services.oauth2.enabled', False) }} + changed_when: false + - name: "DEBUG | SYS-STK-BACKEND | Application context" ansible.builtin.debug: msg: - "application_id={{ application_id }}" - - "database_enabled={{ SYS_STK_BACKEND_DATABASE_ENABLED }}" - - "oauth2_enabled={{ SYS_STK_BACKEND_OAUTH2_ENABLED }}" + - "database_consumer_id={{ _sys_stk_backend_database_consumer_id }}" + - "database_enabled={{ _sys_stk_backend_database_enabled }}" + - "oauth2_enabled={{ _sys_stk_backend_oauth2_enabled }}" when: MODE_DEBUG | bool -- name: "SYS-STK-BACKEND | Load optional dependencies (once)" - ansible.builtin.include_tasks: "_load_service.yml" - loop: - - id: "svc-db-openldap" - name: "ldap" - - - id: "svc-ai-ollama" - name: "ollama" - loop_control: - loop_var: service - label: "{{ service.id }}" - vars: - service_id: "{{ service.id }}" - service_name: "{{ service.name }}" - - name: "For '{{ application_id }}': Load central RDBMS" include_role: name: sys-svc-rdbms public: false - when: SYS_STK_BACKEND_DATABASE_ENABLED | bool + vars: + database_consumer_id: "{{ _sys_stk_backend_database_consumer_id }}" + when: _sys_stk_backend_database_enabled | bool - name: "For '{{ application_id }}': Load sys-svc-compose" include_role: name: sys-svc-compose vars: docker_compose_flush_handlers: false - database_consumer_id: "{{ database_consumer_id_passed }}" + database_consumer_id: "{{ _sys_stk_backend_database_consumer_id }}" - block: - name: "set oauth2_proxy_application_id (Needed due to lazzy loading issue)" @@ -42,7 +40,7 @@ oauth2_proxy_application_id: "{{ application_id }}" - name: "load role web-app-oauth2-proxy" include_tasks: "{{ playbook_dir }}/roles/web-app-oauth2-proxy/tasks/main.yml" - when: SYS_STK_BACKEND_OAUTH2_ENABLED | bool + when: _sys_stk_backend_oauth2_enabled | bool - name: "flush compose and oauth2 proxy'" meta: flush_handlers diff --git a/roles/sys-stk-backend/vars/main.yml b/roles/sys-stk-backend/vars/main.yml deleted file mode 100644 index ff718711bf..0000000000 --- a/roles/sys-stk-backend/vars/main.yml +++ /dev/null @@ -1,3 +0,0 @@ -# Declared as extra variable for debugging purposes -SYS_STK_BACKEND_DATABASE_ENABLED: "{{ applications | service_load_enabled(application_id, 'database', False) }}" -SYS_STK_BACKEND_OAUTH2_ENABLED: "{{ lookup('config',application_id, 'compose.services.oauth2.enabled', False) }}" diff --git a/roles/sys-svc-compose/tasks/01_core.yml b/roles/sys-svc-compose/tasks/01_core.yml index 119fcd2a8a..8aba69b301 100644 --- a/roles/sys-svc-compose/tasks/01_core.yml +++ b/roles/sys-svc-compose/tasks/01_core.yml @@ -42,4 +42,6 @@ - sys-ctl-rpr-container-hard loop_control: loop_var: service_role - when: COMPOSE_LOAD_SERVICES | bool + when: + - COMPOSE_LOAD_SERVICES | bool + - not (_service_loader_preloading | default(false) | bool) diff --git a/roles/sys-svc-compose/templates/base.yml.j2 b/roles/sys-svc-compose/templates/base.yml.j2 index 1b23bf83d1..ed8d9747df 100644 --- a/roles/sys-svc-compose/templates/base.yml.j2 +++ b/roles/sys-svc-compose/templates/base.yml.j2 @@ -1,7 +1,7 @@ {# Base template for all compose.yml.j2 #} services: {# Load Database #} -{% if applications | is_docker_service_enabled(application_id, 'database') %} +{% if lookup('database', application_id, 'enabled') %} {% include 'roles/sys-svc-rdbms/templates/services/main.yml.j2' %} {% endif %} {# Load Redis #} diff --git a/roles/sys-svc-compose/templates/networks.yml.j2 b/roles/sys-svc-compose/templates/networks.yml.j2 index 08664e06b3..a290e6e718 100644 --- a/roles/sys-svc-compose/templates/networks.yml.j2 +++ b/roles/sys-svc-compose/templates/networks.yml.j2 @@ -1,28 +1,41 @@ {# This template needs to be included in compose.yml #} +{% set _db_provider_role = application_id if application_id in ['svc-db-mariadb', 'svc-db-postgres'] else '' %} +{% set _db_role_id = _db_provider_role or lookup('database', application_id, 'id') %} +{% set _db_network_name = lookup('config', _db_role_id, 'compose.network', False) if _db_role_id else '' %} +{% set _service_registry = query('service_registry') | first %} +{% set _ldap_provider_role = _service_registry.get('ldap', {}).get('role', '') %} +{% set _ldap_network_name = lookup('config', _ldap_provider_role, 'compose.network', False) if _ldap_provider_role else '' %} +{% set _ldap_shared = application_id == _ldap_provider_role or ( + lookup('config', application_id, 'compose.services.ldap.enabled', False) + and lookup('config', application_id, 'compose.services.ldap.shared', False) +) %} +{% set _ollama_provider_role = _service_registry.get('ollama', {}).get('role', '') %} +{% set _ollama_network_name = lookup('config', _ollama_provider_role, 'compose.network', False) if _ollama_provider_role else '' %} +{% set _ollama_shared = application_id == _ollama_provider_role or ( + lookup('config', application_id, 'compose.services.ollama.enabled', False) + and lookup('config', application_id, 'compose.services.ollama.shared', False) +) %} networks: {# Central RDMS-Database Network #} {% if ( - lookup('config',application_id, 'compose.services.database.enabled', False) and + lookup('database', application_id, 'enabled') and lookup('database', application_id, 'shared') ) or application_id in ['svc-db-mariadb','svc-db-postgres'] %} - {{ lookup('config', lookup('database', application_id, 'id'), 'compose.network') }}: + {{ _db_network_name }}: external: true {% endif %} {# Central LDAP Network #} -{% if - lookup('config',application_id, 'compose.services.ldap.shared', False) and - lookup('config','svc-db-openldap', 'network.compose', False) - %} - {{ lookup('config','svc-db-openldap', 'compose.network') }}: +{% if _ldap_shared and _ldap_network_name %} + {{ _ldap_network_name }}: external: true {% endif %} {# Central AI Network #} -{% if lookup('config',application_id, 'compose.services.ollama.shared', False) %} - {{ lookup('config','svc-ai-ollama', 'compose.network') }}: +{% if _ollama_shared and _ollama_network_name %} + {{ _ollama_network_name }}: external: true {% endif %} {# Default Network #} diff --git a/roles/sys-svc-container/templates/networks.yml.j2 b/roles/sys-svc-container/templates/networks.yml.j2 index 78c366de3b..21633ea939 100644 --- a/roles/sys-svc-container/templates/networks.yml.j2 +++ b/roles/sys-svc-container/templates/networks.yml.j2 @@ -1,27 +1,44 @@ {# This template needs to be included in compose.yml containers #} +{% set _db_provider_role = application_id if application_id in ['svc-db-mariadb', 'svc-db-postgres'] else '' %} +{% set _db_role_id = _db_provider_role or lookup('database', application_id, 'id') %} +{% set _db_network_name = lookup('config', _db_role_id, 'compose.network', False) if _db_role_id else '' %} +{% set _db_network_alias = (application_id | get_entity_name) if _db_provider_role else lookup('database', application_id, 'type') %} +{% set _service_registry = query('service_registry') | first %} +{% set _ldap_provider_role = _service_registry.get('ldap', {}).get('role', '') %} +{% set _ldap_network_name = lookup('config', _ldap_provider_role, 'compose.network', False) if _ldap_provider_role else '' %} +{% set _ldap_shared = application_id == _ldap_provider_role or ( + lookup('config', application_id, 'compose.services.ldap.enabled', False) + and lookup('config', application_id, 'compose.services.ldap.shared', False) +) %} +{% set _ollama_provider_role = _service_registry.get('ollama', {}).get('role', '') %} +{% set _ollama_network_name = lookup('config', _ollama_provider_role, 'compose.network', False) if _ollama_provider_role else '' %} +{% set _ollama_shared = application_id == _ollama_provider_role or ( + lookup('config', application_id, 'compose.services.ollama.enabled', False) + and lookup('config', application_id, 'compose.services.ollama.shared', False) +) %} networks: {# Central RDMS-Database Network #} {% if ( - lookup('config',application_id, 'compose.services.database.enabled', False) and + lookup('database', application_id, 'enabled') and lookup('database', application_id, 'shared') ) or application_id in ['svc-db-mariadb','svc-db-postgres'] %} - {{ lookup('config', lookup('database', application_id, 'id'), 'compose.network') }}: + {{ _db_network_name }}: {% if application_id in ['svc-db-mariadb','svc-db-postgres'] %} aliases: - - {{ lookup('database', application_id, 'type') }} + - {{ _db_network_alias }} {% endif %} {% endif %} {# Central LDAP Network #} -{% if lookup('config',application_id, 'compose.services.ldap.shared', False) and lookup('config','svc-db-openldap', 'network.compose') %} - {{ lookup('config','svc-db-openldap', 'compose.network') }}: +{% if _ldap_shared and _ldap_network_name %} + {{ _ldap_network_name }}: {% endif %} {# Central AI Network #} -{% if lookup('config',application_id, 'compose.services.ollama.shared', False) %} - {{ lookup('config','svc-ai-ollama', 'compose.network') }}: +{% if _ollama_shared and _ollama_network_name %} + {{ _ollama_network_name }}: {% endif %} {% if not application_id.startswith('svc-db-') and not application_id.startswith('svc-ai-') %} default: diff --git a/roles/sys-svc-mail/tasks/01_core.yml b/roles/sys-svc-mail/tasks/01_core.yml index 82291f5ffa..e96708647d 100644 --- a/roles/sys-svc-mail/tasks/01_core.yml +++ b/roles/sys-svc-mail/tasks/01_core.yml @@ -5,33 +5,15 @@ name: "sys-hostname" when: not (run_once_sys_hostname | default(false) | bool) -- block: - - name: "Check if Mail Host is reachable" - uri_probe: - url: "{{ lookup('tls', 'web-app-mailu', 'url.base') }}" - validate_certs: yes - status_code: "{{ mailu_valid_status_codes }}" - register: mail_host_reachability - failed_when: false - changed_when: false - when: - - run_once_web_app_mailu is not defined - - - name: "Load Mailu Routines for '{{ role_name }}'" - include_tasks: 02_mailu.yml - when: - - > - ( - mail_host_reachability is defined and - (mail_host_reachability.status | default(0) | int) - not in mailu_valid_status_codes - ) - or - ( - (users['no-reply'].tokens | default({})).get('web-app-mailu', '') | length == 0 - ) - vars: - mailu_valid_status_codes: "{{ lookup('config','web-app-mailu', 'server.status_codes.default') }}" +- name: "Assert Mailu was preloaded before configuring external mail" + ansible.builtin.assert: + that: + - run_once_web_app_mailu is defined + - (users['no-reply'].tokens | default({})).get('web-app-mailu', '') | length > 0 + fail_msg: >- + Mailu must be preloaded by sys-utils-service-loader before sys-svc-mail runs. + Missing run_once_web_app_mailu or missing users['no-reply'].tokens['web-app-mailu'] + indicates that a service was loaded outside the constructor service-loader path. when: - "'web-app-mailu' in group_names" diff --git a/roles/sys-svc-mail/tasks/02_mailu.yml b/roles/sys-svc-mail/tasks/02_mailu.yml deleted file mode 100644 index 81cf73b9a3..0000000000 --- a/roles/sys-svc-mail/tasks/02_mailu.yml +++ /dev/null @@ -1,9 +0,0 @@ -- name: "Load Mailu before MSMTP config, to guaranty that server is up" - include_tasks: "utils/load_app.yml" - vars: - load_app_id: web-app-mailu - -- name: "Reset compose handlers after Mailu include for MSMTP" - include_tasks: utils/load_handlers.yml - vars: - handler_role_name: "sys-svc-compose" diff --git a/roles/sys-svc-rdbms/tasks/main.yml b/roles/sys-svc-rdbms/tasks/main.yml index 59b4c45566..8c3734f828 100644 --- a/roles/sys-svc-rdbms/tasks/main.yml +++ b/roles/sys-svc-rdbms/tasks/main.yml @@ -1,7 +1,14 @@ # run_once_sys_svc_rdbms: deactivated -- name: "For '{{ application_id }}': Set database_consumer_id (Needed due to lazzy loading issue)" +- name: "For '{{ application_id }}': Freeze database consumer id before provider includes" set_fact: - database_consumer_id_passed: "{{ application_id }}" + _database_consumer_id: "{{ database_consumer_id | default(application_id) }}" + changed_when: false + +- name: "For '{{ application_id }}/{{ _database_consumer_id }}': Resolve shared database mode" + set_fact: + _sys_svc_rdbms_central_db_enabled: >- + {{ lookup('database', _database_consumer_id, 'shared') | bool }} + changed_when: false - block: - name: "Ensure env dir exists: {{ lookup('container', application_id, 'directories.env') }}" @@ -9,31 +16,47 @@ path: "{{ lookup('container', application_id, 'directories.env') }}" state: directory mode: "0755" - - name: "For '{{ application_id }}/{{ database_consumer_id_passed }}': Create {{ lookup('database', application_id, 'env') }}" + - name: "For '{{ application_id }}/{{ _database_consumer_id }}': Create {{ lookup('database', _database_consumer_id, 'env') }}" template: - src: "env/{{ lookup('database', application_id, 'type') }}.env.j2" - dest: "{{ lookup('database', application_id, 'env') }}" + src: "env/{{ lookup('database', _database_consumer_id, 'type') }}.env.j2" + dest: "{{ lookup('database', _database_consumer_id, 'env') }}" notify: compose up - when: not (SYS_SVC_RDBMS_CENTRAL_DB_ENABLED | bool) + when: not (_sys_svc_rdbms_central_db_enabled | bool) - name: Central Database Logic block: - - name: "For '{{ application_id }}': Create central database" - include_tasks: "utils/load_app.yml" + - name: "For '{{ application_id }}': Assert shared database provider was preloaded" + ansible.builtin.assert: + that: + - >- + lookup( + 'vars', + 'run_once_' ~ (_database_provider_role | replace('-', '_')), + default='__missing__' + ) != '__missing__' + fail_msg: >- + Shared database provider '{{ _database_provider_role }}' was not preloaded by + sys-utils-service-loader before sys-svc-rdbms ran. + + - name: "For '{{ application_id }}': Initialize dedicated database on preloaded provider" + ansible.builtin.include_role: + name: "{{ _database_provider_role }}" vars: - load_app_id: "{{ lookup('database', application_id, 'id') }}" - database_init: true # Initialize a custom database for the application - docker_git_repository_pull: false # Deactivated here to don't inhire the variable + application_id: "{{ _database_provider_role }}" + database_init: true + docker_git_repository_pull: false + database_consumer_id: "{{ _database_consumer_id }}" - name: "For '{{ application_id }}': Add Entry for Backup Procedure" include_tasks: "{{ playbook_dir }}/roles/sys-ctl-bkp-docker-2-loc/tasks/04_seed-database-to-backup.yml" vars: - database_consumer_id: "{{ database_consumer_id_passed }}" - database_type: "{{ lookup('database', database_consumer_id_passed | default(application_id), 'type') }}" - database_instance: "{{ lookup('database', database_consumer_id_passed | default(application_id), 'instance') }}" - database_host: "{{ lookup('database', database_consumer_id_passed | default(application_id), 'host') }}" - database_port: "{{ lookup('database', database_consumer_id_passed | default(application_id), 'port') }}" - database_name: "{{ lookup('database', database_consumer_id_passed | default(application_id), 'name') }}" - database_username: "{{ lookup('database', database_consumer_id_passed | default(application_id), 'username') }}" - database_password: "{{ lookup('database', database_consumer_id_passed | default(application_id), 'password') }}" - when: SYS_SVC_RDBMS_CENTRAL_DB_ENABLED | bool + _database_provider_role: "{{ lookup('database', _database_consumer_id, 'id') }}" + database_consumer_id: "{{ _database_consumer_id }}" + database_type: "{{ lookup('database', _database_consumer_id, 'type') }}" + database_instance: "{{ lookup('database', _database_consumer_id, 'instance') }}" + database_host: "{{ lookup('database', _database_consumer_id, 'host') }}" + database_port: "{{ lookup('database', _database_consumer_id, 'port') }}" + database_name: "{{ lookup('database', _database_consumer_id, 'name') }}" + database_username: "{{ lookup('database', _database_consumer_id, 'username') }}" + database_password: "{{ lookup('database', _database_consumer_id, 'password') }}" + when: _sys_svc_rdbms_central_db_enabled | bool diff --git a/roles/sys-svc-rdbms/vars/main.yml b/roles/sys-svc-rdbms/vars/main.yml deleted file mode 100644 index 12ef02e05e..0000000000 --- a/roles/sys-svc-rdbms/vars/main.yml +++ /dev/null @@ -1,2 +0,0 @@ -# Docker -SYS_SVC_RDBMS_CENTRAL_DB_ENABLED: "{{ lookup('database', application_id, 'shared') }}" diff --git a/roles/sys-svc-webserver-core/tasks/01_core.yml b/roles/sys-svc-webserver-core/tasks/01_core.yml index 9eaaf53d70..2b960ccd9d 100644 --- a/roles/sys-svc-webserver-core/tasks/01_core.yml +++ b/roles/sys-svc-webserver-core/tasks/01_core.yml @@ -46,5 +46,6 @@ loop: - sys-ctl-hlth-webserver - sys-ctl-hlth-csp + when: not (_service_loader_preloading | default(false) | bool) - include_tasks: utils/once/flag.yml diff --git a/roles/sys-utils-service-loader/tasks/load_frontend_service.yml b/roles/sys-utils-service-loader/tasks/load_frontend_service.yml deleted file mode 100644 index e47c450858..0000000000 --- a/roles/sys-utils-service-loader/tasks/load_frontend_service.yml +++ /dev/null @@ -1,17 +0,0 @@ -- name: "Check if {{ service_key }} endpoint is reachable" - uri_probe: - url: "{{ lookup('tls', service_role, 'url.base') }}" - validate_certs: yes - status_code: 200 - register: _frontend_service_reachability - failed_when: false - changed_when: false - -- name: "Load {{ service_key }} (Once)" - include_tasks: "utils/load_app.yml" - when: (_frontend_service_reachability.status | default(0) | int) != 200 - vars: - load_app_id: "{{ service_role }}" - -- name: "Flush handlers after loading {{ service_key }}" - meta: flush_handlers diff --git a/roles/sys-utils-service-loader/tasks/load_service.yml b/roles/sys-utils-service-loader/tasks/load_service.yml new file mode 100644 index 0000000000..b8e8dc1676 --- /dev/null +++ b/roles/sys-utils-service-loader/tasks/load_service.yml @@ -0,0 +1,19 @@ +- name: "Load {{ service_key }} in shared service preload context" + block: + - name: "Mark shared service preload context for {{ service_key }}" + ansible.builtin.set_fact: + _service_loader_preloading: true + changed_when: false + + - name: "Load {{ service_key }} (Once)" + include_tasks: "utils/load_app.yml" + vars: + load_app_id: "{{ service_role }}" + + - name: "Flush handlers after loading {{ service_key }}" + meta: flush_handlers + always: + - name: "Clear shared service preload context for {{ service_key }}" + ansible.builtin.set_fact: + _service_loader_preloading: false + changed_when: false diff --git a/roles/sys-utils-service-loader/tasks/main.yml b/roles/sys-utils-service-loader/tasks/main.yml index 4e4ec52ee2..3c2cbeb577 100644 --- a/roles/sys-utils-service-loader/tasks/main.yml +++ b/roles/sys-utils-service-loader/tasks/main.yml @@ -1,20 +1,29 @@ -# SPOT: global loader for shared frontend web services. +# SPOT: global loader for all shared services. # -# Called once from tasks/stages/02_server.yml before web-svc and web-app roles. -# Service load order is defined by SERVICE_REGISTRY order. +# Called from tasks/stages/01_constructor.yml before the normal server app pass. -- name: "Load shared frontend service" - include_tasks: load_frontend_service.yml +- name: "Discover ordered shared services" + ansible.builtin.set_fact: + _ordered_services: >- + {{ + query( + 'service_registry', + 'ordered', + applications=applications, + roles_dir=([ playbook_dir, 'roles' ] | path_join) + ) | first + }} + +- name: "Load shared service" + include_tasks: load_service.yml vars: - service_key: "{{ service_item.key }}" - service_role: "{{ service_item.value.role }}" - service_run_once_var: "{{ 'run_once_' ~ (service_item.value.role | replace('-', '_')) }}" + service_key: "{{ service_item.id }}" + service_role: "{{ service_item.role }}" + service_run_once_var: "{{ 'run_once_' ~ (service_item.role | replace('-', '_')) }}" when: - - service_item.value.get('type') == 'frontend' - - service_item.value.role is defined - lookup('vars', service_run_once_var, default='__missing__') == '__missing__' - - lookup('service', service_item.key).needed | bool - loop: "{{ SERVICE_REGISTRY | dict2items | list }}" + - lookup('service', service_item.id).needed | bool + loop: "{{ _ordered_services }}" loop_control: loop_var: service_item - label: "{{ service_item.key }}" + label: "{{ service_item.id }}" diff --git a/roles/web-app-akaunting/config/main.yml b/roles/web-app-akaunting/config/main.yml index 4e3d729e59..e71e11f518 100644 --- a/roles/web-app-akaunting/config/main.yml +++ b/roles/web-app-akaunting/config/main.yml @@ -35,10 +35,9 @@ compose: email: enabled: true shared: true - database: - shared: true - type: "mariadb" + mariadb: enabled: true + shared: true akaunting: backup: no_stop_required: true diff --git a/roles/web-app-baserow/config/main.yml b/roles/web-app-baserow/config/main.yml index 3d976f1320..4286f916d9 100644 --- a/roles/web-app-baserow/config/main.yml +++ b/roles/web-app-baserow/config/main.yml @@ -17,10 +17,9 @@ compose: backup: disabled: true enabled: true - database: + postgres: + enabled: true shared: true - type: "postgres" - enabled: true baserow: backup: no_stop_required: true diff --git a/roles/web-app-bigbluebutton/config/main.yml b/roles/web-app-bigbluebutton/config/main.yml index de8e53b481..395e74bca5 100644 --- a/roles/web-app-bigbluebutton/config/main.yml +++ b/roles/web-app-bigbluebutton/config/main.yml @@ -39,9 +39,9 @@ compose: cleanup: true # Auto-Cleanup Recordings max_age_days: 30 # Cleanup recording after this amount of days min_storage: 50GB - database: + # noqa: shared + postgres: shared: false - # This is set to true to pass integration test, doesn't have any other function enabled: true greenlight: enabled: true diff --git a/roles/web-app-bluesky/config/main.yml b/roles/web-app-bluesky/config/main.yml index 9b7ade2528..2a1545d641 100644 --- a/roles/web-app-bluesky/config/main.yml +++ b/roles/web-app-bluesky/config/main.yml @@ -41,9 +41,6 @@ compose: email: enabled: true shared: true - database: - shared: false - enabled: false # noqa: shared web: enabled: true # @see https://github.com/bluesky-social/social-app diff --git a/roles/web-app-bluesky/templates/compose.yml.j2 b/roles/web-app-bluesky/templates/compose.yml.j2 index 864bb5c161..c1b1311c65 100644 --- a/roles/web-app-bluesky/templates/compose.yml.j2 +++ b/roles/web-app-bluesky/templates/compose.yml.j2 @@ -31,7 +31,6 @@ {{ applications | compose_volumes( application_id, - database_volume=lookup('database', application_id, 'volume'), extra_volumes={'pds_data': {'name': BLUESKY_PDS_DATA_VOLUME}} ) }} {% include 'roles/sys-svc-compose/templates/networks.yml.j2' %} diff --git a/roles/web-app-bookwyrm/config/main.yml b/roles/web-app-bookwyrm/config/main.yml index 7a0ec46f04..74296b75a0 100644 --- a/roles/web-app-bookwyrm/config/main.yml +++ b/roles/web-app-bookwyrm/config/main.yml @@ -17,10 +17,10 @@ compose: email: enabled: true shared: true - database: + # noqa: shared + postgres: + enabled: true shared: true - type: "postgres" - enabled: true # noqa: shared redis: backup: diff --git a/roles/web-app-bridgy-fed/config/main.yml b/roles/web-app-bridgy-fed/config/main.yml index 710f957653..662367d1dd 100644 --- a/roles/web-app-bridgy-fed/config/main.yml +++ b/roles/web-app-bridgy-fed/config/main.yml @@ -21,9 +21,6 @@ compose: matomo: enabled: true shared: true - database: - shared: false - enabled: false application: image: "python" version: "3.12-bookworm" diff --git a/roles/web-app-chess/config/main.yml b/roles/web-app-chess/config/main.yml index bbcc4d7a9c..d38f8b53e6 100644 --- a/roles/web-app-chess/config/main.yml +++ b/roles/web-app-chess/config/main.yml @@ -12,10 +12,9 @@ compose: matomo: enabled: true shared: true - database: - shared: true - type: "postgres" - enabled: true + postgres: + enabled: true + shared: true chess: image: "ghcr.io/kevinveenbirkenbach/fedi-chess" version: "v1.0.1" diff --git a/roles/web-app-confluence/config/main.yml b/roles/web-app-confluence/config/main.yml index c6ea4a85fa..e3dfdf3014 100644 --- a/roles/web-app-confluence/config/main.yml +++ b/roles/web-app-confluence/config/main.yml @@ -17,10 +17,9 @@ compose: email: enabled: true shared: true - database: + postgres: + enabled: true shared: true - type: "postgres" - enabled: true confluence: image: atlassian/confluence version: latest diff --git a/roles/web-app-dashboard/config/main.yml b/roles/web-app-dashboard/config/main.yml index 6420ac71e5..1b2b42412a 100644 --- a/roles/web-app-dashboard/config/main.yml +++ b/roles/web-app-dashboard/config/main.yml @@ -47,6 +47,7 @@ compose: shared: true dashboard: enabled: false + shared: true name: "dashboard" image: "ghcr.io/kevinveenbirkenbach/port-ui" version: "1.1.0" diff --git a/roles/web-app-discourse/config/main.yml b/roles/web-app-discourse/config/main.yml index d04ed502ff..2c5354323d 100644 --- a/roles/web-app-discourse/config/main.yml +++ b/roles/web-app-discourse/config/main.yml @@ -37,10 +37,10 @@ compose: email: enabled: true shared: true - database: - shared: true - type: "postgres" + # noqa: shared + postgres: enabled: true + shared: true # noqa: shared redis: backup: diff --git a/roles/web-app-espocrm/config/main.yml b/roles/web-app-espocrm/config/main.yml index b96dc572f9..6068afb9c7 100644 --- a/roles/web-app-espocrm/config/main.yml +++ b/roles/web-app-espocrm/config/main.yml @@ -45,10 +45,9 @@ compose: email: enabled: true shared: true - database: + mariadb: + enabled: true shared: true - type: "mariadb" - enabled: true espocrm: image: "espocrm/espocrm" version: "latest" diff --git a/roles/web-app-flowise/config/main.yml b/roles/web-app-flowise/config/main.yml index ec6e26f069..b45bffe408 100644 --- a/roles/web-app-flowise/config/main.yml +++ b/roles/web-app-flowise/config/main.yml @@ -64,9 +64,6 @@ compose: backup: disabled: true enabled: false - database: - shared: false - enabled: false ollama: enabled: true shared: true diff --git a/roles/web-app-friendica/config/main.yml b/roles/web-app-friendica/config/main.yml index 19e08adfff..1c8c08243d 100644 --- a/roles/web-app-friendica/config/main.yml +++ b/roles/web-app-friendica/config/main.yml @@ -39,10 +39,9 @@ compose: email: enabled: true shared: true - database: - shared: true - type: "mariadb" - enabled: true + mariadb: + enabled: true + shared: true oauth2: origin: host: "application" diff --git a/roles/web-app-funkwhale/config/main.yml b/roles/web-app-funkwhale/config/main.yml index 71dc54a9bd..3f8326d173 100644 --- a/roles/web-app-funkwhale/config/main.yml +++ b/roles/web-app-funkwhale/config/main.yml @@ -30,10 +30,9 @@ compose: backup: disabled: true enabled: true - database: - shared: true - type: "postgres" + postgres: enabled: true + shared: true oauth2: origin: host: "front" diff --git a/roles/web-app-gitea/config/main.yml b/roles/web-app-gitea/config/main.yml index 5372178d3a..a5b2194380 100644 --- a/roles/web-app-gitea/config/main.yml +++ b/roles/web-app-gitea/config/main.yml @@ -43,10 +43,9 @@ compose: email: enabled: true shared: true - database: - shared: true - type: "mariadb" + mariadb: enabled: true + shared: true gitea: image: "gitea/gitea" version: "latest" diff --git a/roles/web-app-gitlab/config/main.yml b/roles/web-app-gitlab/config/main.yml index 19ea272122..fcc58442cf 100644 --- a/roles/web-app-gitlab/config/main.yml +++ b/roles/web-app-gitlab/config/main.yml @@ -20,10 +20,9 @@ compose: backup: disabled: true enabled: true - database: + postgres: + enabled: true shared: true - type: "postgres" - enabled: true gitlab: image: "gitlab/gitlab-ee" version: "latest" diff --git a/roles/web-app-jira/config/main.yml b/roles/web-app-jira/config/main.yml index c9dfcec888..f65e75e557 100644 --- a/roles/web-app-jira/config/main.yml +++ b/roles/web-app-jira/config/main.yml @@ -18,10 +18,9 @@ compose: email: enabled: true shared: true - database: + postgres: + enabled: true shared: true - type: "postgres" - enabled: true jira: image: atlassian/jira-software version: latest diff --git a/roles/web-app-joomla/config/main.yml b/roles/web-app-joomla/config/main.yml index 0149146f77..d204663494 100644 --- a/roles/web-app-joomla/config/main.yml +++ b/roles/web-app-joomla/config/main.yml @@ -28,10 +28,9 @@ compose: email: enabled: true shared: true - database: + mariadb: + enabled: true shared: true - type: "mariadb" - enabled: true joomla: image: joomla version: latest diff --git a/roles/web-app-keycloak/config/main.yml b/roles/web-app-keycloak/config/main.yml index 6816e74264..1cf7f45a15 100644 --- a/roles/web-app-keycloak/config/main.yml +++ b/roles/web-app-keycloak/config/main.yml @@ -41,6 +41,9 @@ compose: enabled: true shared: true keycloak: + enabled: false + shared: true + provides: oidc image: "quay.io/keycloak/keycloak" version: "latest" name: "keycloak" @@ -54,10 +57,9 @@ compose: totp_enabled: True users: emails_verified: True - database: - shared: true - type: "postgres" + postgres: enabled: true + shared: true css: enabled: true shared: true diff --git a/roles/web-app-listmonk/config/main.yml b/roles/web-app-listmonk/config/main.yml index b336286691..2400e265e8 100644 --- a/roles/web-app-listmonk/config/main.yml +++ b/roles/web-app-listmonk/config/main.yml @@ -30,10 +30,9 @@ compose: email: enabled: true shared: true - database: - shared: true - type: "postgres" + postgres: enabled: true + shared: true listmonk: cpus: 1.0 mem_reservation: 256m diff --git a/roles/web-app-magento/config/main.yml b/roles/web-app-magento/config/main.yml index ac721059cb..6d1e685e28 100644 --- a/roles/web-app-magento/config/main.yml +++ b/roles/web-app-magento/config/main.yml @@ -35,8 +35,9 @@ compose: name: "magento-nginx" backup: no_stop_required: true - database: - shared: false + # noqa: shared + mariadb: + shared: false enabled: true version: "11.4" # noqa: shared diff --git a/roles/web-app-mailu/config/main.yml b/roles/web-app-mailu/config/main.yml index 10fab31c3e..742f33d566 100644 --- a/roles/web-app-mailu/config/main.yml +++ b/roles/web-app-mailu/config/main.yml @@ -38,6 +38,9 @@ compose: enabled: true shared: true mailu: + enabled: false + shared: true + provides: email version: "2024.06" name: mailu min_storage: "20GB" @@ -50,10 +53,9 @@ compose: mem_reservation: "256m" mem_limit: "512m" pids_limit: 256 - database: - shared: true - type: "mariadb" + mariadb: enabled: true + shared: true cpus: "0.8" mem_reservation: "1g" mem_limit: "2g" diff --git a/roles/web-app-mailu/tasks/01_core.yml b/roles/web-app-mailu/tasks/01_core.yml index 9274613602..01e6ca1505 100644 --- a/roles/web-app-mailu/tasks/01_core.yml +++ b/roles/web-app-mailu/tasks/01_core.yml @@ -35,11 +35,6 @@ webserver_vhost_flavour: "basic" domain: "{{ MAILU_HOSTNAME }}" -- name: "Include Cert deploy service for '{{ role_name }}'" - include_role: - name: sys-ctl-mtn-cert-deploy - when: lookup('tls', application_id, 'enabled') | bool - - name: "Flush Docker Compose handlers" meta: flush_handlers @@ -68,6 +63,13 @@ loop_var: user_item no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" +- name: "Include Cert deploy service for '{{ role_name }}'" + include_role: + name: sys-ctl-mtn-cert-deploy + when: lookup('tls', application_id, 'enabled') | bool + # Alarm mail setup reaches sys-svc-mail and therefore requires the Mailu + # API token that is created in 03_manage_user.yml. + - name: Generate DKIM public key include_tasks: 04_generate-and-read-dkim.yml diff --git a/roles/web-app-mastodon/config/main.yml b/roles/web-app-mastodon/config/main.yml index a50664d402..81b63d6bd2 100644 --- a/roles/web-app-mastodon/config/main.yml +++ b/roles/web-app-mastodon/config/main.yml @@ -36,14 +36,9 @@ compose: mem_reservation: "256m" mem_limit: "512m" pids_limit: 256 - database: - shared: true - type: "postgres" - enabled: true - cpus: "1.0" - mem_reservation: "2g" - mem_limit: "3g" - pids_limit: 512 + postgres: + enabled: true + shared: true mastodon: image: "ghcr.io/mastodon/mastodon" version: latest diff --git a/roles/web-app-matomo/config/main.yml b/roles/web-app-matomo/config/main.yml index f0ac96b9f8..9c17bfc172 100644 --- a/roles/web-app-matomo/config/main.yml +++ b/roles/web-app-matomo/config/main.yml @@ -35,7 +35,7 @@ compose: enabled: false matomo: enabled: false - shared: false + shared: true image: "matomo" version: "latest" name: "matomo" @@ -59,10 +59,9 @@ compose: mem_limit: 1g pids_limit: 512 - database: - shared: true - type: "mariadb" + mariadb: enabled: true + shared: true redis: backup: disabled: true diff --git a/roles/web-app-matrix/config/main.yml b/roles/web-app-matrix/config/main.yml index db2a4e4843..b28ce062b1 100644 --- a/roles/web-app-matrix/config/main.yml +++ b/roles/web-app-matrix/config/main.yml @@ -15,10 +15,9 @@ compose: email: enabled: true shared: true - database: - shared: true - type: "postgres" - enabled: true + postgres: + enabled: true + shared: true synapse: version: latest image: matrixdotorg/synapse diff --git a/roles/web-app-mattermost/README.md b/roles/web-app-mattermost/README.md index a801feec79..58451cf26b 100644 --- a/roles/web-app-mattermost/README.md +++ b/roles/web-app-mattermost/README.md @@ -28,7 +28,7 @@ Key settings in `config/main.yml`: | Key | Default | Description | |-----|---------|-------------| | `compose.services.oidc.enabled` | `true` | Enable Keycloak SSO via GitLab OAuth2 | -| `compose.services.database.type` | `postgres` | Database engine (postgres only) | +| `compose.services.postgres.shared` | `true` | Use the shared PostgreSQL service instead of a role-local one | | `compose.services.mattermost.version` | `latest` | Docker image tag | | `server.domains.canonical` | `mattermost.{{ DOMAIN_PRIMARY }}` | Public domain | diff --git a/roles/web-app-mattermost/config/main.yml b/roles/web-app-mattermost/config/main.yml index d358ba9a3c..9958802da8 100644 --- a/roles/web-app-mattermost/config/main.yml +++ b/roles/web-app-mattermost/config/main.yml @@ -31,10 +31,9 @@ compose: email: enabled: true shared: true - database: - shared: true - type: "postgres" - enabled: true + postgres: + enabled: true + shared: true mattermost: image: "mattermost/mattermost-team-edition" version: "11.5.1" diff --git a/roles/web-app-mediawiki/config/main.yml b/roles/web-app-mediawiki/config/main.yml index 031033fa94..177a2a9622 100644 --- a/roles/web-app-mediawiki/config/main.yml +++ b/roles/web-app-mediawiki/config/main.yml @@ -26,10 +26,9 @@ compose: email: enabled: true shared: true - database: + mariadb: + enabled: true shared: true - type: "mariadb" - enabled: true mediawiki: image: mediawiki version: "1.45" diff --git a/roles/web-app-mig/config/main.yml b/roles/web-app-mig/config/main.yml index d7b87a318f..b421bcb33e 100644 --- a/roles/web-app-mig/config/main.yml +++ b/roles/web-app-mig/config/main.yml @@ -13,8 +13,6 @@ compose: enabled: false backup: disabled: true - database: - enabled: false mig: image: "ghcr.io/kevinveenbirkenbach/infinito-mig" version: "latest" diff --git a/roles/web-app-mini-qr/config/main.yml b/roles/web-app-mini-qr/config/main.yml index a7853d60c4..d3601deaa1 100644 --- a/roles/web-app-mini-qr/config/main.yml +++ b/roles/web-app-mini-qr/config/main.yml @@ -13,8 +13,6 @@ compose: backup: disabled: true enabled: false - database: - enabled: false css: enabled: true shared: true diff --git a/roles/web-app-minio/config/main.yml b/roles/web-app-minio/config/main.yml index 93201d155d..58a0eb4f0c 100644 --- a/roles/web-app-minio/config/main.yml +++ b/roles/web-app-minio/config/main.yml @@ -42,9 +42,6 @@ compose: backup: disabled: true enabled: false - database: - shared: false - enabled: false css: enabled: true shared: true diff --git a/roles/web-app-mobilizon/config/main.yml b/roles/web-app-mobilizon/config/main.yml index f36f2a5612..e7a68b53b3 100644 --- a/roles/web-app-mobilizon/config/main.yml +++ b/roles/web-app-mobilizon/config/main.yml @@ -28,10 +28,9 @@ compose: email: enabled: true shared: true - database: - shared: true - type: "postgres" + postgres: enabled: true + shared: true mobilizon: image: "docker.io/kaihuri/mobilizon" name: "mobilizon" diff --git a/roles/web-app-moodle/config/main.yml b/roles/web-app-moodle/config/main.yml index 7c57b57408..96099c9820 100644 --- a/roles/web-app-moodle/config/main.yml +++ b/roles/web-app-moodle/config/main.yml @@ -37,10 +37,9 @@ compose: email: enabled: true shared: true - database: + mariadb: + enabled: true shared: true - type: "mariadb" - enabled: true moodle: version: "4.5" # Latest LTS - Necessary for OIDC image: bitnamilegacy/moodle diff --git a/roles/web-app-nextcloud/config/main.yml b/roles/web-app-nextcloud/config/main.yml index 6a3c507256..5ef0165da2 100644 --- a/roles/web-app-nextcloud/config/main.yml +++ b/roles/web-app-nextcloud/config/main.yml @@ -70,10 +70,9 @@ compose: mem_reservation: "1g" mem_limit: "8g" pids_limit: 512 - database: - shared: true - type: "mariadb" + mariadb: enabled: true + shared: true cpus: "0.75" mem_reservation: "512m" mem_limit: "1.5g" diff --git a/roles/web-app-openproject/config/main.yml b/roles/web-app-openproject/config/main.yml index 8060468562..a08fe7fb84 100644 --- a/roles/web-app-openproject/config/main.yml +++ b/roles/web-app-openproject/config/main.yml @@ -33,10 +33,9 @@ compose: email: enabled: true shared: true - database: - shared: true - type: "postgres" + postgres: enabled: true + shared: true web: name: openproject-web image: openproject/openproject diff --git a/roles/web-app-openwebui/config/main.yml b/roles/web-app-openwebui/config/main.yml index 1e59814d1c..ab80bd87c1 100644 --- a/roles/web-app-openwebui/config/main.yml +++ b/roles/web-app-openwebui/config/main.yml @@ -44,9 +44,6 @@ compose: backup: disabled: true enabled: false - database: - shared: false - enabled: false css: enabled: false shared: true diff --git a/roles/web-app-peertube/config/main.yml b/roles/web-app-peertube/config/main.yml index aed3bf1000..60bccb8297 100644 --- a/roles/web-app-peertube/config/main.yml +++ b/roles/web-app-peertube/config/main.yml @@ -45,10 +45,9 @@ compose: mem_reservation: "256m" mem_limit: "512m" pids_limit: 512 - database: - shared: true - type: "postgres" + postgres: enabled: true + shared: true peertube: name: "peertube" version: "production-bookworm" diff --git a/roles/web-app-pgadmin/config/main.yml b/roles/web-app-pgadmin/config/main.yml index 6b84ee61a4..8d2e0dae2f 100644 --- a/roles/web-app-pgadmin/config/main.yml +++ b/roles/web-app-pgadmin/config/main.yml @@ -29,10 +29,9 @@ compose: matomo: enabled: true shared: true - database: - shared: true - type: "postgres" + postgres: enabled: true + shared: true oauth2: enabled: true shared: true diff --git a/roles/web-app-pgadmin/vars/main.yml b/roles/web-app-pgadmin/vars/main.yml index 4f927564b9..8b2d620501 100644 --- a/roles/web-app-pgadmin/vars/main.yml +++ b/roles/web-app-pgadmin/vars/main.yml @@ -1,7 +1,6 @@ # General application_id: "web-app-pgadmin" entity_name: "{{ application_id | get_entity_name }}" -database_host: "{{ lookup('config','svc-db-postgres', 'compose.services.postgres.name') if lookup('config',application_id, 'compose.services.database.shared') }}" # PgAdmin PGADMIN_VERSION: "{{ lookup('config', application_id, 'compose.services.' ~ entity_name ~ '.version') }}" diff --git a/roles/web-app-phpmyadmin/config/main.yml b/roles/web-app-phpmyadmin/config/main.yml index d3da89ff0d..57676f444d 100644 --- a/roles/web-app-phpmyadmin/config/main.yml +++ b/roles/web-app-phpmyadmin/config/main.yml @@ -19,10 +19,9 @@ compose: matomo: enabled: true shared: true - database: - shared: true - type: "mariadb" + mariadb: enabled: true + shared: true phpmyadmin: version: "latest" # Use the latest phpmyadmin version name: "phpmyadmin" diff --git a/roles/web-app-pixelfed/config/main.yml b/roles/web-app-pixelfed/config/main.yml index 415b5bd5a3..065ac35598 100644 --- a/roles/web-app-pixelfed/config/main.yml +++ b/roles/web-app-pixelfed/config/main.yml @@ -41,10 +41,9 @@ compose: enabled: true mem_reservation: 0.1g mem_limit: 0.2g - database: - shared: true - type: "mariadb" + mariadb: enabled: true + shared: true pixelfed: image: "zknt/pixelfed" version: "latest" diff --git a/roles/web-app-pretix/config/main.yml b/roles/web-app-pretix/config/main.yml index 2d41e73c2c..f7eae179f2 100644 --- a/roles/web-app-pretix/config/main.yml +++ b/roles/web-app-pretix/config/main.yml @@ -21,10 +21,9 @@ compose: backup: disabled: true enabled: true - database: + postgres: + enabled: true shared: true - type: "postgres" - enabled: true pretix: image: pretix/standalone version: stable diff --git a/roles/web-app-shopware/config/main.yml b/roles/web-app-shopware/config/main.yml index b586f57c19..2b440f9115 100644 --- a/roles/web-app-shopware/config/main.yml +++ b/roles/web-app-shopware/config/main.yml @@ -30,11 +30,9 @@ compose: email: enabled: true shared: true - database: - shared: true - type: "mariadb" + mariadb: enabled: true - + shared: true init: name: "shopware-init" cpus: 1.0 diff --git a/roles/web-app-snipe-it/config/main.yml b/roles/web-app-snipe-it/config/main.yml index 29a0da0f58..18be910bec 100644 --- a/roles/web-app-snipe-it/config/main.yml +++ b/roles/web-app-snipe-it/config/main.yml @@ -37,10 +37,9 @@ compose: backup: disabled: true enabled: true - database: - shared: true - type: "mariadb" + mariadb: enabled: true + shared: true snipe-it: version: "latest-alpine" name: "snipe-it" diff --git a/roles/web-app-sphinx/config/main.yml b/roles/web-app-sphinx/config/main.yml index 6cd1ed3740..f6960ff102 100644 --- a/roles/web-app-sphinx/config/main.yml +++ b/roles/web-app-sphinx/config/main.yml @@ -23,8 +23,6 @@ compose: matomo: enabled: true shared: true - database: - enabled: false sphinx: image: "ghcr.io/kevinveenbirkenbach/infinito-sphinx" version: "latest" diff --git a/roles/web-app-suitecrm/config/main.yml b/roles/web-app-suitecrm/config/main.yml index c841b12e63..9584384c5a 100644 --- a/roles/web-app-suitecrm/config/main.yml +++ b/roles/web-app-suitecrm/config/main.yml @@ -32,10 +32,9 @@ compose: email: enabled: true shared: true - database: - shared: true - type: "mariadb" + mariadb: enabled: true + shared: true suitecrm: image: "php" version: "8.2-apache" diff --git a/roles/web-app-taiga/config/main.yml b/roles/web-app-taiga/config/main.yml index 2b9eaa9e63..bb10316e47 100644 --- a/roles/web-app-taiga/config/main.yml +++ b/roles/web-app-taiga/config/main.yml @@ -23,10 +23,9 @@ compose: email: enabled: true shared: true - database: + postgres: + enabled: true shared: true - type: "postgres" - enabled: true taiga: version: "latest" min_storage: "10GB" diff --git a/roles/web-app-wordpress/config/main.yml b/roles/web-app-wordpress/config/main.yml index 7a0e3e00d2..ea46d813a9 100644 --- a/roles/web-app-wordpress/config/main.yml +++ b/roles/web-app-wordpress/config/main.yml @@ -49,10 +49,9 @@ compose: matomo: enabled: true shared: true - database: + mariadb: + enabled: true shared: true - type: "mariadb" - enabled: true wordpress: version: latest image: wordpress diff --git a/roles/web-app-xwiki/config/main.yml b/roles/web-app-xwiki/config/main.yml index 5f0f37b302..210f0f6f81 100644 --- a/roles/web-app-xwiki/config/main.yml +++ b/roles/web-app-xwiki/config/main.yml @@ -24,10 +24,9 @@ compose: enabled: false backup: disabled: true - database: - shared: true - enabled: true - type: postgres + postgres: + enabled: true + shared: true xwiki: image: xwiki version: lts-postgres-tomcat diff --git a/roles/web-app-yourls/config/main.yml b/roles/web-app-yourls/config/main.yml index 9bfffa8487..c241937af5 100644 --- a/roles/web-app-yourls/config/main.yml +++ b/roles/web-app-yourls/config/main.yml @@ -26,10 +26,9 @@ compose: matomo: enabled: true shared: true - database: + mariadb: + enabled: true shared: true - type: "mariadb" - enabled: true yourls: version: "latest" name: "yourls" diff --git a/roles/web-svc-asset/meta/main.yml b/roles/web-svc-asset/meta/main.yml index db24bb592c..215989a56b 100644 --- a/roles/web-svc-asset/meta/main.yml +++ b/roles/web-svc-asset/meta/main.yml @@ -19,4 +19,5 @@ galaxy_info: versions: - all lifecycle: beta - + run_after: + - web-svc-file diff --git a/roles/web-svc-cdn/config/main.yml b/roles/web-svc-cdn/config/main.yml index f18564d2df..3641817092 100644 --- a/roles/web-svc-cdn/config/main.yml +++ b/roles/web-svc-cdn/config/main.yml @@ -7,12 +7,17 @@ compose: services: dashboard: enabled: false + cdn: + enabled: false + shared: true matomo: enabled: true shared: true css: enabled: false shared: true + canonical: cdn javascript: enabled: false shared: true + canonical: cdn diff --git a/roles/web-svc-collabora/config/main.yml b/roles/web-svc-collabora/config/main.yml index 46f3c5d7cb..c7ee30d9c2 100644 --- a/roles/web-svc-collabora/config/main.yml +++ b/roles/web-svc-collabora/config/main.yml @@ -25,9 +25,9 @@ compose: backup: disabled: true enabled: false - database: - enabled: false collabora: + enabled: false + shared: true image: collabora/code version: latest name: collabora diff --git a/roles/web-svc-coturn/config/main.yml b/roles/web-svc-coturn/config/main.yml index 2815932867..8917572dfa 100644 --- a/roles/web-svc-coturn/config/main.yml +++ b/roles/web-svc-coturn/config/main.yml @@ -9,6 +9,8 @@ compose: enabled: true shared: true coturn: + enabled: false + shared: true image: "coturn/coturn" version: "latest" min_storage: "1GB" @@ -22,8 +24,6 @@ compose: backup: disabled: true enabled: false - database: - enabled: false css: enabled: true shared: true diff --git a/roles/web-svc-file/config/main.yml b/roles/web-svc-file/config/main.yml index 69e29e3ebe..38a7c22bdb 100644 --- a/roles/web-svc-file/config/main.yml +++ b/roles/web-svc-file/config/main.yml @@ -5,6 +5,9 @@ server: aliases: [] compose: services: + file: + enabled: false + shared: true dashboard: enabled: true shared: true diff --git a/roles/web-svc-legal/config/main.yml b/roles/web-svc-legal/config/main.yml new file mode 100644 index 0000000000..e1bc70b7d9 --- /dev/null +++ b/roles/web-svc-legal/config/main.yml @@ -0,0 +1,5 @@ +compose: + services: + legal: + enabled: false + shared: false diff --git a/roles/web-svc-legal/tasks/01_core.yml b/roles/web-svc-legal/tasks/01_core.yml new file mode 100644 index 0000000000..ca3b1cdc81 --- /dev/null +++ b/roles/web-svc-legal/tasks/01_core.yml @@ -0,0 +1,6 @@ +- include_tasks: utils/once/flag.yml + +- name: Copy imprint.html + ansible.builtin.template: + src: imprint.html.j2 + dest: "{{ [ lookup('nginx', 'directories.data.html'), 'imprint.html' ] | path_join }}" diff --git a/roles/web-svc-legal/tasks/main.yml b/roles/web-svc-legal/tasks/main.yml index 030633c8e3..923f827718 100644 --- a/roles/web-svc-legal/tasks/main.yml +++ b/roles/web-svc-legal/tasks/main.yml @@ -1,5 +1,3 @@ --- -- name: copy imprint.html - template: - src: "imprint.html.j2" - dest: "{{ [ lookup('nginx','directories.data.html'), 'imprint.html' ] | path_join }}" +- include_tasks: 01_core.yml + when: run_once_web_svc_legal is not defined diff --git a/roles/web-svc-libretranslate/README.md b/roles/web-svc-libretranslate/README.md index 98e36ad473..080e2c05b9 100644 --- a/roles/web-svc-libretranslate/README.md +++ b/roles/web-svc-libretranslate/README.md @@ -44,7 +44,6 @@ All configuration is handled via `config/main.yml`. Key sections include: - `compose.services.libretranslate`: image and version - `compose.services.redis`: enable Redis backend -- `compose.services.database`: enable database backend - `compose.services.matomo`: enable analytics - `server.domains`: canonical and alias domains - `server.csp`: diff --git a/roles/web-svc-libretranslate/config/main.yml b/roles/web-svc-libretranslate/config/main.yml index 85febf956d..9517e8b2fb 100644 --- a/roles/web-svc-libretranslate/config/main.yml +++ b/roles/web-svc-libretranslate/config/main.yml @@ -3,6 +3,8 @@ credentials: {} compose: services: libretranslate: + enabled: false + shared: true image: libretranslate/libretranslate version: latest min_storage: "5GB" @@ -22,9 +24,6 @@ compose: backup: disabled: true enabled: false # Enable Redis - database: - shared: false - enabled: false # Enable the database css: enabled: true shared: true diff --git a/roles/web-svc-logout/config/main.yml b/roles/web-svc-logout/config/main.yml index 641e2c7604..674d939927 100644 --- a/roles/web-svc-logout/config/main.yml +++ b/roles/web-svc-logout/config/main.yml @@ -24,7 +24,7 @@ compose: services: logout: enabled: false - shared: false + shared: true image: "ghcr.io/kevinveenbirkenbach/universal-logout" version: "latest" name: "logout" diff --git a/roles/web-svc-onlyoffice/config/main.yml b/roles/web-svc-onlyoffice/config/main.yml index 8eb1bbb3c7..da8d98c24c 100644 --- a/roles/web-svc-onlyoffice/config/main.yml +++ b/roles/web-svc-onlyoffice/config/main.yml @@ -39,11 +39,12 @@ compose: backup: disabled: true enabled: true - database: - shared: true - type: "postgres" + postgres: enabled: true + shared: true onlyoffice: + enabled: false + shared: true image: "onlyoffice/documentserver" version: "latest" name: "onlyoffice" diff --git a/roles/web-svc-simpleicons/config/main.yml b/roles/web-svc-simpleicons/config/main.yml index 69c5eb3da8..a0eee5747e 100644 --- a/roles/web-svc-simpleicons/config/main.yml +++ b/roles/web-svc-simpleicons/config/main.yml @@ -15,15 +15,14 @@ compose: backup: disabled: true enabled: false # Enable Redis - database: - shared: false - enabled: false # Enable the database css: enabled: false shared: false recaptcha: enabled: false simpleicons: + enabled: false + shared: true image: node version: latest min_storage: "1GB" diff --git a/tasks/stages/01_constructor.yml b/tasks/stages/01_constructor.yml index 6dac5b7298..c48c71ef99 100644 --- a/tasks/stages/01_constructor.yml +++ b/tasks/stages/01_constructor.yml @@ -180,6 +180,10 @@ - MODE_CLEANUP | bool - DOCKER_IN_CONTAINER | bool +- name: Preload shared services + ansible.builtin.include_role: + name: sys-utils-service-loader + - name: "Load base roles" ansible.builtin.include_tasks: "./tasks/groups/{{ role_group }}-roles.yml" loop: diff --git a/tasks/stages/02_server.yml b/tasks/stages/02_server.yml index 9443f8fb19..aed05edd89 100644 --- a/tasks/stages/02_server.yml +++ b/tasks/stages/02_server.yml @@ -11,7 +11,6 @@ - sys-ctl-cln-disc-space # Reclaim disk space by cleaning temporary system data - sys-ctl-hlth-btrfs # Check Btrfs filesystem health and error counters - sys-ctl-rpr-btrfs-balancer # Install and configure automatic Btrfs balancing - - sys-utils-service-loader # Preload shared frontend services before web-svc and web-app roles loop_control: loop_var: server_role diff --git a/tasks/utils/load_app.yml b/tasks/utils/load_app.yml index ac6982c40d..535ebd7be3 100644 --- a/tasks/utils/load_app.yml +++ b/tasks/utils/load_app.yml @@ -16,4 +16,4 @@ public: false vars: application_id: "{{ _load_app_id }}" - domain: "{{ lookup('domain',load_app_id) }}" + domain: "{{ lookup('domain', _load_app_id) }}" diff --git a/tests/integration/test_central_database_config.py b/tests/integration/test_central_database_config.py deleted file mode 100644 index fe615d39fa..0000000000 --- a/tests/integration/test_central_database_config.py +++ /dev/null @@ -1,74 +0,0 @@ -# tests/integration/test_central_database_config.py -import unittest -from pathlib import Path -import yaml - - -def load_yaml(path: Path): - """Load a YAML file and return dict ({} if missing/empty).""" - if not path.exists(): - return {} - with path.open("r", encoding="utf-8") as f: - return yaml.safe_load(f) or {} - - -def has_nested_key(data: object, dotted_key: str) -> bool: - """ - Return True if a dotted path exists in a nested dict structure. - Example: has_nested_key(cfg, "compose.services.database.shared") - """ - if not isinstance(data, dict): - return False - - cur: object = data - for part in dotted_key.split("."): - if not isinstance(cur, dict): - return False - if part not in cur: - return False - cur = cur[part] - return True - - -class TestCentralDatabaseConfig(unittest.TestCase): - def test_central_database_feature_requires_database_service(self): - """ - If compose.services.database.shared is defined in either vars/main.yml or config/main.yml, - then config/main.yml must define compose.services.database. - """ - repo_root = Path(__file__).resolve().parents[2] - roles_dir = repo_root / "roles" - - violations = [] - - for role_dir in sorted(roles_dir.glob("*")): - if not role_dir.is_dir(): - continue - - vars_file = role_dir / "vars" / "main.yml" - cfg_file = role_dir / "config" / "main.yml" - - vars_data = load_yaml(vars_file) - cfg_data = load_yaml(cfg_file) - - # Trigger: compose.services.database.shared defined in either file (value irrelevant) - shared_defined = has_nested_key( - vars_data, "compose.services.database.shared" - ) or has_nested_key(cfg_data, "compose.services.database.shared") - if not shared_defined: - continue - - # Requirement: compose.services.database must be defined in config/main.yml - if not has_nested_key(cfg_data, "compose.services.database"): - violations.append(role_dir.name) - - if violations: - self.fail( - "The 'compose.services.database.shared' flag is only valid if 'compose.services.database' " - "is defined in config/main.yml. Missing in roles:\n" - + "\n".join(f"- {name}" for name in violations) - ) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/integration/test_configuration_database_dependency.py b/tests/integration/test_configuration_database_dependency.py deleted file mode 100644 index 4ce715ecd5..0000000000 --- a/tests/integration/test_configuration_database_dependency.py +++ /dev/null @@ -1,45 +0,0 @@ -import unittest -from pathlib import Path -import yaml - - -class TestConfigurationDatabaseDependency(unittest.TestCase): - # Define project root and glob pattern for configuration files - PROJECT_ROOT = Path(__file__).resolve().parents[2] - CONFIG_PATTERN = "roles/*/config/main.yml" - - def test_central_database_implies_database_service_enabled(self): - """ - For each roles/*/config/main.yml: - If compose.services.database.shared is true, - then compose.services.database.enabled must be true. - """ - config_paths = sorted(self.PROJECT_ROOT.glob(self.CONFIG_PATTERN)) - self.assertTrue( - config_paths, - f"No configuration files found for pattern {self.CONFIG_PATTERN}", - ) - - for config_path in config_paths: - with self.subTest(configuration=config_path): - content = yaml.safe_load(config_path.read_text(encoding="utf-8")) or {} - - # Read database enabled flag - docker = content.get("compose", {}) - services = docker.get("services", {}) - database = services.get("database", {}) - db_enabled = database.get("enabled", False) - central_db = database.get("shared", False) - - if central_db: - self.assertTrue( - db_enabled, - f"{config_path}: compose.services.database.shared is true but compose.services.database.enabled is not true", - ) - else: - # No requirement when central_database is false or absent - self.assertTrue(True) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/integration/test_frontend_service_spot.py b/tests/integration/test_frontend_service_spot.py index ef3dbea7fe..2544e1b2cc 100644 --- a/tests/integration/test_frontend_service_spot.py +++ b/tests/integration/test_frontend_service_spot.py @@ -1,67 +1,47 @@ -import pathlib import unittest +from pathlib import Path -import yaml +from utils.service_registry import ( + build_service_registry_from_roles_dir, + load_applications_from_roles_dir, + ordered_primary_service_entries, +) class TestFrontendServiceSpot(unittest.TestCase): - def test_service_registry_does_not_use_load_phase(self): - service_registry = yaml.safe_load( - pathlib.Path("group_vars/all/20_services.yml").read_text(encoding="utf-8") - )["SERVICE_REGISTRY"] - - for key, entry in service_registry.items(): - with self.subTest(service=key): - self.assertNotIn("load_phase", entry) - - def test_server_stage_loads_frontend_services_before_server_groups(self): - tasks = yaml.safe_load( - pathlib.Path("tasks/stages/02_server.yml").read_text(encoding="utf-8") + def setUp(self): + self.repo_root = Path(__file__).resolve().parents[2] + self.roles_dir = self.repo_root / "roles" + self.applications = load_applications_from_roles_dir(self.roles_dir) + self.service_registry = build_service_registry_from_roles_dir(self.roles_dir) + self.ordered = ordered_primary_service_entries( + self.service_registry, + self.roles_dir, ) - setup_server_base = next( - ( - task - for task in tasks - if isinstance(task, dict) and task.get("name") == "Setup server base" - ), - None, - ) - server_roles_index = next( - ( - idx - for idx, task in enumerate(tasks) - if isinstance(task, dict) and task.get("name") == "Include server roles" - ), - None, - ) + def _index(self, role_name: str) -> int: + for index, entry in enumerate(self.ordered): + if entry["role"] == role_name: + return index + self.fail(f"Role {role_name} not found in ordered service registry") - self.assertIsNotNone(setup_server_base) - self.assertIsNotNone(server_roles_index) - self.assertIn( - "sys-utils-service-loader", - setup_server_base.get("loop", []), - ) + def test_bucket_order_is_monotonic(self): + bucket_order = { + "universal": 0, + "workstation": 1, + "server": 2, + "web-svc": 3, + "web-app": 4, + } + actual = [bucket_order[entry["bucket"]] for entry in self.ordered] + self.assertEqual(actual, sorted(actual)) - def test_load_app_does_not_load_frontend_services(self): - content = pathlib.Path("tasks/utils/load_app.yml").read_text(encoding="utf-8") - self.assertNotIn("load_services", content) + def test_dashboard_is_loaded_after_matomo(self): + self.assertLess(self._index("web-app-matomo"), self._index("web-app-dashboard")) - def test_frontend_service_loader_lives_in_role(self): - self.assertTrue( - pathlib.Path("roles/sys-utils-service-loader/tasks/main.yml").is_file() - ) - self.assertTrue( - pathlib.Path( - "roles/sys-utils-service-loader/tasks/load_frontend_service.yml" - ).is_file() - ) - - def test_sys_front_inj_all_no_longer_loads_services(self): - content = pathlib.Path("roles/sys-front-inj-all/tasks/main.yml").read_text( - encoding="utf-8" - ) - self.assertNotIn("01_services.yml", content) + def test_keycloak_respects_run_after_dependencies(self): + self.assertLess(self._index("web-app-matomo"), self._index("web-app-keycloak")) + self.assertLess(self._index("web-app-mailu"), self._index("web-app-keycloak")) if __name__ == "__main__": diff --git a/tests/integration/test_inventory_manager.py b/tests/integration/test_inventory_manager.py index 674ed1314c..dde78fa423 100644 --- a/tests/integration/test_inventory_manager.py +++ b/tests/integration/test_inventory_manager.py @@ -64,7 +64,11 @@ class TestInventoryManagerIntegration(TestCase): ) (provider_role / "config" / "main.yml").write_text( - "compose:\n services: {}\n", + "compose:\n" + " services:\n" + " mariadb:\n" + " enabled: false\n" + " shared: true\n", encoding="utf-8", ) @@ -100,11 +104,10 @@ class TestInventoryManagerIntegration(TestCase): (role_path / "config" / "main.yml").write_text( "compose:\n" " services:\n" - " database:\n" + " mariadb:\n" " enabled: true\n" " shared: true\n" - " type: mariadb\n" - " oauth2:\n" + " oidc:\n" " enabled: true\n", encoding="utf-8", ) @@ -196,6 +199,83 @@ class TestInventoryManagerIntegration(TestCase): self.assertNotIn("database_password", called_keys) self.assertNotIn("oauth2_proxy_cookie_secret", called_keys) + def test_apply_schema_skips_schema_less_transitive_provider_role(self): + """ + Shared provider roles without schema/main.yml must be ignored gracefully. + This matters for roles like web-svc-asset that participate in dependency + discovery but do not define credentials. + """ + with tempfile.TemporaryDirectory() as tmpdir: + tmp = Path(tmpdir) + + roles_root = tmp / "roles" + roles_root.mkdir(parents=True, exist_ok=True) + + provider_role = roles_root / "web-svc-asset" + (provider_role / "vars").mkdir(parents=True, exist_ok=True) + (provider_role / "config").mkdir(parents=True, exist_ok=True) + + (provider_role / "vars" / "main.yml").write_text( + 'application_id: "web-svc-asset"\n', + encoding="utf-8", + ) + (provider_role / "config" / "main.yml").write_text( + "compose:\n" + " services:\n" + " asset:\n" + " enabled: false\n" + " shared: true\n", + encoding="utf-8", + ) + + role_path = roles_root / "web-app-demo" + (role_path / "schema").mkdir(parents=True, exist_ok=True) + (role_path / "vars").mkdir(parents=True, exist_ok=True) + (role_path / "config").mkdir(parents=True, exist_ok=True) + + inv_path = tmp / "inventory.yml" + inv_path.write_text("applications: {}\n", encoding="utf-8") + + (role_path / "vars" / "main.yml").write_text( + 'application_id: "web-app-demo"\n', + encoding="utf-8", + ) + (role_path / "config" / "main.yml").write_text( + "compose:\n" + " services:\n" + " asset:\n" + " enabled: true\n" + " shared: true\n", + encoding="utf-8", + ) + (role_path / "schema" / "main.yml").write_text( + "credentials:\n" + " api_key:\n" + " description: API key\n" + " algorithm: random_hex_16\n" + " validation: {}\n", + encoding="utf-8", + ) + + fake_vault = _FakeVaultHandler("pw") + with patch( + "utils.manager.inventory.VaultHandler", + side_effect=lambda pw: fake_vault, + ): + mgr = InventoryManager( + role_path=role_path, + inventory_path=inv_path, + vault_pw="pw", + overrides={}, + allow_empty_plain=False, + ) + inv = mgr.apply_schema() + + apps = inv.get("applications", {}) + self.assertIn("web-app-demo", apps) + self.assertIn("api_key", apps["web-app-demo"]["credentials"]) + self.assertNotIn("web-svc-asset", apps) + if __name__ == "__main__": main() diff --git a/tests/integration/test_service_transitive_dependencies.py b/tests/integration/test_service_transitive_dependencies.py index 71a6755e88..070da11bcf 100644 --- a/tests/integration/test_service_transitive_dependencies.py +++ b/tests/integration/test_service_transitive_dependencies.py @@ -1,5 +1,5 @@ -import os import unittest +from pathlib import Path import yaml @@ -8,17 +8,7 @@ from plugins.lookup.service import LookupModule class TestServiceTransitiveDependencies(unittest.TestCase): def setUp(self): - self.repo_root = os.path.abspath( - os.path.join(os.path.dirname(__file__), "..", "..") - ) - - service_registry_file = os.path.join( - self.repo_root, "group_vars", "all", "20_services.yml" - ) - with open(service_registry_file, encoding="utf-8") as handle: - data = yaml.safe_load(handle) or {} - self.service_registry = data.get("SERVICE_REGISTRY", {}) - + self.repo_root = Path(__file__).resolve().parents[2] self.applications = { "web-app-dashboard": self._load_yaml( "roles", "web-app-dashboard", "config", "main.yml" @@ -32,9 +22,8 @@ class TestServiceTransitiveDependencies(unittest.TestCase): } def _load_yaml(self, *parts): - path = os.path.join(self.repo_root, *parts) - with open(path, encoding="utf-8") as handle: - return yaml.safe_load(handle) or {} + path = self.repo_root.joinpath(*parts) + return yaml.safe_load(path.read_text(encoding="utf-8")) or {} def test_dashboard_needs_file_transitively_via_asset_service(self): result = LookupModule().run( @@ -42,7 +31,6 @@ class TestServiceTransitiveDependencies(unittest.TestCase): variables={ "applications": self.applications, "group_names": ["web-app-dashboard"], - "SERVICE_REGISTRY": self.service_registry, }, )[0] diff --git a/tests/integration/test_services_canonical.py b/tests/integration/test_services_canonical.py index 69b4ac8edf..380a57e811 100644 --- a/tests/integration/test_services_canonical.py +++ b/tests/integration/test_services_canonical.py @@ -1,131 +1,73 @@ -import os import unittest -import yaml from collections import defaultdict +from pathlib import Path + +from utils.service_registry import build_service_registry_from_roles_dir class TestServicesCanonical(unittest.TestCase): - """Lint: canonical field in group_vars/all/20_services.yml must be consistent. - - Rules: - - If a role is shared by multiple keys, all alias keys MUST declare canonical. - - canonical must point to an existing key in the service registry. - - The canonical target must share the same role as the alias. - - The canonical target must NOT itself have a canonical field (no chaining). - - Exactly one key per role must be the primary (no canonical field). - """ + """Discovered canonical aliases from role-local configs must be internally consistent.""" def setUp(self): - self.repo_root = os.path.abspath( - os.path.join(os.path.dirname(__file__), "..", "..") + self.repo_root = Path(__file__).resolve().parents[2] + self.service_registry = build_service_registry_from_roles_dir( + self.repo_root / "roles" ) - services_file = os.path.join( - self.repo_root, "group_vars", "all", "20_services.yml" - ) - with open(services_file, encoding="utf-8") as f: - data = yaml.safe_load(f) or {} - self.service_registry = data.get("SERVICE_REGISTRY", {}) self.assertGreater( - len(self.service_registry), 0, "service registry must not be empty" + len(self.service_registry), + 0, + "discovered service registry must not be empty", ) - # Build role → [keys] index self.role_to_keys = defaultdict(list) for key, entry in self.service_registry.items(): - if isinstance(entry, dict) and "role" in entry: - self.role_to_keys[entry["role"]].append(key) + role = entry.get("role") + if role: + self.role_to_keys[role].append(key) - def test_shared_roles_have_canonical(self): - """All keys sharing a role (except the primary) must declare canonical.""" + def test_shared_roles_have_exactly_one_primary_key(self): for role, keys in self.role_to_keys.items(): if len(keys) < 2: continue primaries = [k for k in keys if "canonical" not in self.service_registry[k]] with self.subTest(role=role): - self.assertEqual( - len(primaries), - 1, - f"Role '{role}' is shared by {keys} but has " - f"{len(primaries)} primary key(s) (no canonical): {primaries}. " - f"Exactly one primary is required.", - ) + self.assertEqual(len(primaries), 1) def test_canonical_target_exists(self): - """canonical must reference an existing service key.""" for key, entry in self.service_registry.items(): - if not isinstance(entry, dict): - continue canonical = entry.get("canonical") if canonical is None: continue with self.subTest(key=key): - self.assertIn( - canonical, - self.service_registry, - f"[{key}] canonical: '{canonical}' does not exist in the service registry.", - ) + self.assertIn(canonical, self.service_registry) def test_canonical_target_has_same_role(self): - """canonical target must map to the same role as the alias.""" for key, entry in self.service_registry.items(): - if not isinstance(entry, dict): - continue canonical = entry.get("canonical") if canonical is None: continue with self.subTest(key=key): - alias_role = entry.get("role") - target_entry = self.service_registry.get(canonical, {}) - target_role = ( - target_entry.get("role") if isinstance(target_entry, dict) else None - ) self.assertEqual( - alias_role, - target_role, - f"[{key}] canonical: '{canonical}' has role '{target_role}', " - f"but alias has role '{alias_role}'. Roles must match.", + entry.get("role"), + self.service_registry[canonical].get("role"), ) def test_canonical_target_is_not_itself_an_alias(self): - """canonical must not point to another alias (no chaining).""" for key, entry in self.service_registry.items(): - if not isinstance(entry, dict): - continue canonical = entry.get("canonical") if canonical is None: continue with self.subTest(key=key): - target_entry = self.service_registry.get(canonical, {}) - target_canonical = ( - target_entry.get("canonical") - if isinstance(target_entry, dict) - else None - ) - self.assertIsNone( - target_canonical, - f"[{key}] canonical: '{canonical}' is itself an alias " - f"(canonical: '{target_canonical}'). Chaining is not allowed.", - ) + self.assertNotIn("canonical", self.service_registry[canonical]) - def test_unique_roles_must_not_have_canonical(self): - """A key that is the only key for its role must not declare canonical.""" + def test_unique_roles_do_not_declare_canonical(self): for key, entry in self.service_registry.items(): - if not isinstance(entry, dict): - continue canonical = entry.get("canonical") if canonical is None: continue role = entry.get("role") - if role is None: - continue with self.subTest(key=key): - siblings = self.role_to_keys.get(role, []) - self.assertGreater( - len(siblings), - 1, - f"[{key}] declares canonical: '{canonical}' but is the only " - f"key for role '{role}'. canonical is only needed for shared roles.", - ) + self.assertGreater(len(self.role_to_keys.get(role, [])), 1) if __name__ == "__main__": diff --git a/tests/integration/test_services_resolvable.py b/tests/integration/test_services_resolvable.py index f297030c59..29b2deee00 100644 --- a/tests/integration/test_services_resolvable.py +++ b/tests/integration/test_services_resolvable.py @@ -1,80 +1,66 @@ -import os import unittest -import yaml +from pathlib import Path from plugins.lookup.service import LookupModule +from utils.service_registry import ( + build_service_registry_from_roles_dir, + load_applications_from_roles_dir, +) class TestServicesResolvable(unittest.TestCase): - """Every entry in group_vars/all/20_services.yml must be resolvable - via the service lookup plugin both by service key and by role name.""" + """Discovered service keys and provider roles must resolve via the service lookup.""" def setUp(self): - self.repo_root = os.path.abspath( - os.path.join(os.path.dirname(__file__), "..", "..") - ) - services_file = os.path.join( - self.repo_root, "group_vars", "all", "20_services.yml" - ) - with open(services_file, encoding="utf-8") as f: - data = yaml.safe_load(f) or {} - self.service_registry = data.get("SERVICE_REGISTRY", {}) + self.repo_root = Path(__file__).resolve().parents[2] + self.roles_dir = self.repo_root / "roles" + self.applications = load_applications_from_roles_dir(self.roles_dir) + self.service_registry = build_service_registry_from_roles_dir(self.roles_dir) self.assertGreater( - len(self.service_registry), 0, "service registry must not be empty" + len(self.service_registry), + 0, + "discovered service registry must not be empty", ) def _run(self, term): return LookupModule().run( [term], variables={ - "applications": {}, + "applications": self.applications, "group_names": [], - "SERVICE_REGISTRY": self.service_registry, }, + service_registry=self.service_registry, )[0] - def _canonical_for(self, key): - entry = self.service_registry[key] - return entry.get("canonical", key) - def test_all_keys_resolvable(self): - """Every service key must resolve without error and return itself as id.""" for key in self.service_registry: with self.subTest(key=key): result = self._run(key) self.assertEqual(result["id"], key) - def test_all_roles_resolve_to_canonical(self): - """Role-based lookup must return the canonical key for that role.""" + def test_all_primary_roles_resolve_to_primary_key(self): seen_roles = set() for key, entry in self.service_registry.items(): - if not isinstance(entry, dict): + if "canonical" in entry: continue role = entry.get("role") if not role or role in seen_roles: continue seen_roles.add(role) - canonical = self._canonical_for(key) - with self.subTest(role=role, expected_canonical=canonical): + with self.subTest(role=role, expected_key=key): result = self._run(role) self.assertEqual(result["role"], role) - self.assertEqual(result["id"], canonical) + self.assertEqual(result["id"], key) def test_key_and_role_produce_identical_result_for_primary_keys(self): - """For the canonical/primary key of a role, key and role lookups must agree.""" for key, entry in self.service_registry.items(): - if not isinstance(entry, dict): + if "canonical" in entry: continue role = entry.get("role") if not role: continue - # Only test primary keys (no canonical field = this key IS canonical) - if "canonical" in entry: - continue with self.subTest(key=key): - by_key = self._run(key) - by_role = self._run(role) - self.assertEqual(by_key, by_role) + self.assertEqual(self._run(key), self._run(role)) if __name__ == "__main__": diff --git a/tests/lint/test_service_core_first_task_run_once.py b/tests/lint/test_service_core_first_task_run_once.py index 07da9bda61..af2a262e55 100644 --- a/tests/lint/test_service_core_first_task_run_once.py +++ b/tests/lint/test_service_core_first_task_run_once.py @@ -1,28 +1,23 @@ import os import unittest import yaml +from pathlib import Path +from utils.service_registry import build_service_registry_from_roles_dir -SERVICES_FILE = os.path.join( - os.path.dirname(__file__), "..", "..", "group_vars", "all", "20_services.yml" -) RUN_ONCE_TASK = {"include_tasks": "utils/once/flag.yml"} -def load_service_registry(): - with open(SERVICES_FILE, "r") as f: - data = yaml.safe_load(f) - return data.get("SERVICE_REGISTRY", {}) +def load_service_registry(project_root: str): + return build_service_registry_from_roles_dir(Path(project_root) / "roles") def unique_roles(registry): - """ - Return unique role names from the registry. - Skips entries that only have role_template (no fixed role). - """ seen = set() for entry in registry.values(): + if "canonical" in entry: + continue role = entry.get("role") if role and role not in seen: seen.add(role) @@ -30,7 +25,8 @@ def unique_roles(registry): RECURSION_HINT = ( - "Service roles registered in SERVICE_REGISTRY are loaded dynamically via " + "Service roles discovered from role-local compose.services metadata are loaded " + "dynamically via " "load_app.yml, which checks the run_once_ flag before loading a role. " "If tasks/01_core.yml does not set this flag as its very first task, the flag " "may be absent when a second load attempt is evaluated, causing load_app.yml to " @@ -52,7 +48,7 @@ def role_slug(role): class TestServiceCoreFirstTaskRunOnce(unittest.TestCase): """ - For every role referenced in SERVICE_REGISTRY (group_vars/all/20_services.yml): + For every discovered shared service role: 1. roles//tasks/01_core.yml must exist. 2. Its first task must be: - include_tasks: utils/once/flag.yml 3. tasks/main.yml must include 01_core.yml with the correct run_once when-guard. @@ -62,7 +58,7 @@ class TestServiceCoreFirstTaskRunOnce(unittest.TestCase): self.project_root = os.path.abspath( os.path.join(os.path.dirname(__file__), "..", "..") ) - self.registry = load_service_registry() + self.registry = load_service_registry(self.project_root) def _core_path(self, role): return os.path.join(self.project_root, "roles", role, "tasks", "01_core.yml") diff --git a/tests/unit/cli/create/inventory/test_services_disabler.py b/tests/unit/cli/create/inventory/test_services_disabler.py index 27dd5568cb..2473126d6c 100644 --- a/tests/unit/cli/create/inventory/test_services_disabler.py +++ b/tests/unit/cli/create/inventory/test_services_disabler.py @@ -233,7 +233,7 @@ class TestApplyServicesDisabled(unittest.TestCase): "compose": { "services": { "oidc": {"enabled": True, "shared": True}, - "database": {"enabled": True, "shared": True}, + "mariadb": {"enabled": True, "shared": True}, } } } @@ -248,7 +248,7 @@ class TestApplyServicesDisabled(unittest.TestCase): svc = result["applications"]["web-app-nextcloud"]["compose"]["services"] self.assertFalse(svc["oidc"]["enabled"]) self.assertFalse(svc["oidc"]["shared"]) - self.assertTrue(svc["database"]["enabled"]) + self.assertTrue(svc["mariadb"]["enabled"]) def test_creates_missing_service_entry_when_role_defines_it(self): self._write_host_vars( diff --git a/tests/unit/cli/meta/applications/in_group_deps/test_main.py b/tests/unit/cli/meta/applications/in_group_deps/test_main.py index c81427bcfb..8c4913c2e3 100644 --- a/tests/unit/cli/meta/applications/in_group_deps/test_main.py +++ b/tests/unit/cli/meta/applications/in_group_deps/test_main.py @@ -9,11 +9,12 @@ from unittest.mock import patch from cli.meta.applications.in_group_deps import __main__ as mod from utils.applications import in_group_deps as deps_mod + SERVICE_REGISTRY = { - "matomo": {"role": "web-app-matomo", "type": "frontend"}, - "asset": {"role": "web-svc-asset", "type": "frontend"}, - "ldap": {"role": "svc-db-openldap", "type": "backend"}, - "database": {"role_template": "svc-db-{type}", "type": "backend"}, + "matomo": {"role": "web-app-matomo"}, + "asset": {"role": "web-svc-asset"}, + "ldap": {"role": "svc-db-openldap"}, + "mariadb": {"role": "svc-db-mariadb"}, } SAMPLE_APPS = { @@ -72,14 +73,10 @@ class TestInGroupDepsResolver(unittest.TestCase): self.assertIn("web-svc-legal", result) self.assertIn("web-app-matomo", result) - def test_role_template_is_resolved(self) -> None: + def test_direct_database_service_name_is_resolved(self) -> None: apps = dict(SAMPLE_APPS) apps["web-svc-legal"] = { - "compose": { - "services": { - "database": {"enabled": True, "shared": True, "type": "mariadb"} - } - } + "compose": {"services": {"mariadb": {"enabled": True, "shared": True}}} } result = self._run_helper(["web-svc-legal"], applications=apps) diff --git a/tests/unit/cli/meta/applications/resolution/services/test_resolver.py b/tests/unit/cli/meta/applications/resolution/services/test_resolver.py index 536f2336bf..2f372b40ef 100644 --- a/tests/unit/cli/meta/applications/resolution/services/test_resolver.py +++ b/tests/unit/cli/meta/applications/resolution/services/test_resolver.py @@ -1,23 +1,20 @@ -# tests/unit/cli/meta/applications/resolution/services/test_resolver.py from __future__ import annotations import tempfile import unittest from pathlib import Path -import yaml - -from cli.meta.applications.resolution.services.errors import ServicesResolutionError from cli.meta.applications.resolution.services.resolver import ( ServicesResolver, resolve_direct_service_roles_from_config, ) + _MINIMAL_SERVICE_REGISTRY = { "ldap": {"role": "svc-db-openldap"}, "oidc": {"role": "web-app-keycloak"}, "matomo": {"role": "web-app-matomo"}, - "database": {"role_template": "svc-db-{type}"}, + "mariadb": {"role": "svc-db-mariadb"}, "dashboard": {"role": "web-app-dashboard"}, } @@ -30,7 +27,7 @@ class TestServicesResolverDirect(unittest.TestCase): "ldap": {"enabled": True, "shared": True}, "oidc": {"enabled": True, "shared": True}, "matomo": {"enabled": True, "shared": True}, - "database": {"enabled": True, "shared": True, "type": "mariadb"}, + "mariadb": {"enabled": True, "shared": True}, "dashboard": {"enabled": True, "shared": True}, } } @@ -47,17 +44,6 @@ class TestServicesResolverDirect(unittest.TestCase): ], ) - def test_database_missing_type_raises(self) -> None: - cfg = { - "compose": { - "services": { - "database": {"enabled": True, "shared": True}, - } - } - } - with self.assertRaises(ServicesResolutionError): - resolve_direct_service_roles_from_config(cfg, _MINIMAL_SERVICE_REGISTRY) - def test_non_shared_not_included(self) -> None: cfg = { "compose": { @@ -72,53 +58,78 @@ class TestServicesResolverDirect(unittest.TestCase): class TestServicesResolverTransitive(unittest.TestCase): - def _mk_role(self, root: Path, role: str, config: str | None = None) -> None: + def _mk_role( + self, + root: Path, + role: str, + *, + config: str = "compose: {}\n", + meta: str | None = None, + ) -> None: role_dir = root / "roles" / role (role_dir / "config").mkdir(parents=True, exist_ok=True) - if config is not None: - (role_dir / "config" / "main.yml").write_text(config, encoding="utf-8") + (role_dir / "vars").mkdir(parents=True, exist_ok=True) + (role_dir / "config" / "main.yml").write_text(config, encoding="utf-8") + (role_dir / "vars" / "main.yml").write_text( + f"application_id: {role}\n", + encoding="utf-8", + ) + if meta is not None: + (role_dir / "meta").mkdir(parents=True, exist_ok=True) + (role_dir / "meta" / "main.yml").write_text(meta, encoding="utf-8") - def _mk_services_file(self, root: Path, mapping: dict) -> Path: - path = root / "20_services.yml" - path.write_text(yaml.dump({"SERVICE_REGISTRY": mapping}), encoding="utf-8") - return path - - def test_transitive_bfs(self) -> None: - # app -> oidc(shared) => keycloak - # keycloak config -> matomo(shared) => matomo + def test_transitive_bfs_uses_role_local_discovery(self) -> None: with tempfile.TemporaryDirectory() as td: root = Path(td) (root / "roles").mkdir() - services_file = self._mk_services_file( - root, - { - "oidc": {"role": "web-app-keycloak", "type": "frontend"}, - "matomo": {"role": "web-app-matomo", "type": "frontend"}, - }, - ) - self._mk_role( root, "web-app-app", - "compose:\n services:\n oidc:\n enabled: true\n shared: true\n", + config=( + "compose:\n" + " services:\n" + " oidc:\n" + " enabled: true\n" + " shared: true\n" + ), ) self._mk_role( root, "web-app-keycloak", - "compose:\n services:\n matomo:\n enabled: true\n shared: true\n", + config=( + "compose:\n" + " services:\n" + " keycloak:\n" + " enabled: false\n" + " shared: true\n" + " provides: oidc\n" + " matomo:\n" + " enabled: true\n" + " shared: true\n" + ), + ) + self._mk_role( + root, + "web-app-matomo", + config=( + "compose:\n" + " services:\n" + " matomo:\n" + " enabled: false\n" + " shared: true\n" + ), ) - self._mk_role(root, "web-app-matomo", "compose: {}\n") - r = ServicesResolver(root / "roles", services_file=services_file) - got = r.resolve_transitively("web-app-app") + resolver = ServicesResolver(root / "roles") + got = resolver.resolve_transitively("web-app-app") self.assertEqual(got, ["web-app-keycloak", "web-app-matomo"]) def test_repo_pixelfed_includes_dashboard(self) -> None: repo_root = Path(__file__).resolve().parents[7] - r = ServicesResolver(repo_root / "roles") + resolver = ServicesResolver(repo_root / "roles") - got = r.resolve_transitively("web-app-pixelfed") + got = resolver.resolve_transitively("web-app-pixelfed") self.assertIn("web-app-dashboard", got) diff --git a/tests/unit/cli/test_inventory_manager.py b/tests/unit/cli/test_inventory_manager.py index 003c16901f..58632db295 100644 --- a/tests/unit/cli/test_inventory_manager.py +++ b/tests/unit/cli/test_inventory_manager.py @@ -62,13 +62,11 @@ class TestInventoryManager(unittest.TestCase): return {"application_id": "testapp"} # Return docker service flags for config/main.yml - # NOTE: "type" is intentionally omitted; this test stubs out - # resolve_schema_includes_recursive() to avoid provider resolution. if path.match("*/config/main.yml"): return { "compose": { "services": { - "database": {"enabled": True, "shared": True}, + "mariadb": {"enabled": True, "shared": True}, } } } @@ -161,8 +159,7 @@ class TestInventoryManager(unittest.TestCase): mgr = InventoryManager(role_dir, inv_file, "pw", overrides=overrides) # IMPORTANT: - # This unit test is NOT about transitive "shared provider" resolution. - # Stub it out so missing database.type in config does not trigger sys.exit(1). + # This unit test is NOT about transitive shared-provider resolution. with patch.object( InventoryManager, "resolve_schema_includes_recursive", return_value=[] ): diff --git a/tests/unit/plugins/filter/test_compose_volumes.py b/tests/unit/plugins/filter/test_compose_volumes.py index df786df6ff..4025ac9d9f 100644 --- a/tests/unit/plugins/filter/test_compose_volumes.py +++ b/tests/unit/plugins/filter/test_compose_volumes.py @@ -37,7 +37,7 @@ class TestComposeVolumes(unittest.TestCase): "app": { "compose": { "services": { - "database": {"enabled": False, "shared": False}, + "mariadb": {"enabled": False, "shared": False}, "redis": {"enabled": False}, "oauth2": {"enabled": False}, } @@ -80,16 +80,16 @@ class TestComposeVolumes(unittest.TestCase): # ----------------------------- def test_database_enabled_not_shared_requires_database_volume_argument(self): apps = self._base_apps() - apps["app"]["compose"]["services"]["database"]["enabled"] = True - apps["app"]["compose"]["services"]["database"]["shared"] = False + apps["app"]["compose"]["services"]["mariadb"]["enabled"] = True + apps["app"]["compose"]["services"]["mariadb"]["shared"] = False with self.assertRaises(AnsibleFilterError): compose_volumes(apps, "app") def test_database_enabled_not_shared_uses_database_volume_argument(self): apps = self._base_apps() - apps["app"]["compose"]["services"]["database"]["enabled"] = True - apps["app"]["compose"]["services"]["database"]["shared"] = False + apps["app"]["compose"]["services"]["mariadb"]["enabled"] = True + apps["app"]["compose"]["services"]["mariadb"]["shared"] = False rendered = compose_volumes(apps, "app", database_volume="my_db_vol") data = self._parse_yaml(rendered) @@ -98,8 +98,8 @@ class TestComposeVolumes(unittest.TestCase): def test_database_enabled_shared_true_does_not_add_database_volume(self): apps = self._base_apps() - apps["app"]["compose"]["services"]["database"]["enabled"] = True - apps["app"]["compose"]["services"]["database"]["shared"] = True + apps["app"]["compose"]["services"]["mariadb"]["enabled"] = True + apps["app"]["compose"]["services"]["mariadb"]["shared"] = True rendered = compose_volumes(apps, "app") data = self._parse_yaml(rendered) @@ -108,8 +108,8 @@ class TestComposeVolumes(unittest.TestCase): def test_database_enabled_shared_null_treated_as_not_shared(self): apps = self._base_apps() - apps["app"]["compose"]["services"]["database"]["enabled"] = True - apps["app"]["compose"]["services"]["database"]["shared"] = None + apps["app"]["compose"]["services"]["mariadb"]["enabled"] = True + apps["app"]["compose"]["services"]["mariadb"]["shared"] = None rendered = compose_volumes(apps, "app", database_volume="my_db_vol") data = self._parse_yaml(rendered) @@ -182,8 +182,8 @@ class TestComposeVolumes(unittest.TestCase): def test_database_enabled_not_shared_without_database_volume_raises(self): apps = self._base_apps() - apps["app"]["compose"]["services"]["database"]["enabled"] = True - apps["app"]["compose"]["services"]["database"]["shared"] = False + apps["app"]["compose"]["services"]["mariadb"]["enabled"] = True + apps["app"]["compose"]["services"]["mariadb"]["shared"] = False with self.assertRaises(AnsibleFilterError): compose_volumes(apps, "app", database_volume=None) diff --git a/tests/unit/plugins/filter/test_service_load_enabled.py b/tests/unit/plugins/filter/test_service_load_enabled.py deleted file mode 100644 index fdf19b5a60..0000000000 --- a/tests/unit/plugins/filter/test_service_load_enabled.py +++ /dev/null @@ -1,110 +0,0 @@ -import unittest - -from ansible.errors import AnsibleFilterError - -from plugins.filter.service_load_enabled import service_load_enabled - - -class TestServiceLoadEnabled(unittest.TestCase): - def test_service_load_enabled_true_when_enabled_and_shared_true(self): - applications = { - "web-app-xwiki": { - "compose": { - "services": { - "ldap": { - "enabled": True, - "shared": True, - } - } - } - } - } - - self.assertTrue(service_load_enabled(applications, "web-app-xwiki", "ldap")) - - def test_service_load_enabled_false_when_shared_false(self): - applications = { - "web-app-xwiki": { - "compose": { - "services": { - "ldap": { - "enabled": True, - "shared": False, - } - } - } - } - } - - self.assertFalse(service_load_enabled(applications, "web-app-xwiki", "ldap")) - - def test_service_load_enabled_false_when_enabled_false(self): - applications = { - "web-app-xwiki": { - "compose": { - "services": { - "ldap": { - "enabled": False, - "shared": True, - } - } - } - } - } - - self.assertFalse(service_load_enabled(applications, "web-app-xwiki", "ldap")) - - def test_service_load_enabled_false_when_keys_missing(self): - applications = { - "web-app-xwiki": { - "compose": { - "services": { - "ldap": { - # enabled/shared missing - } - } - } - } - } - - self.assertFalse(service_load_enabled(applications, "web-app-xwiki", "ldap")) - - def test_service_load_enabled_uses_default_when_keys_missing(self): - applications = { - "web-app-xwiki": { - "compose": { - "services": { - "ldap": { - # enabled/shared missing - } - } - } - } - } - - self.assertTrue( - service_load_enabled(applications, "web-app-xwiki", "ldap", default=True) - ) - - def test_service_load_enabled_missing_service_returns_false(self): - applications = { - "web-app-xwiki": { - "compose": { - "services": { - # ldap missing entirely - } - } - } - } - - self.assertFalse(service_load_enabled(applications, "web-app-xwiki", "ldap")) - - def test_service_load_enabled_missing_app_raises(self): - applications = {"web-app-xwiki": {"compose": {"services": {}}}} - - with self.assertRaises(AnsibleFilterError): - service_load_enabled(applications, "web-app-mediawiki", "ldap") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/unit/plugins/lookup/test_applications_current_play.py b/tests/unit/plugins/lookup/test_applications_current_play.py index e26875e96b..33d1b5f196 100644 --- a/tests/unit/plugins/lookup/test_applications_current_play.py +++ b/tests/unit/plugins/lookup/test_applications_current_play.py @@ -4,40 +4,55 @@ import unittest from plugins.lookup.applications_current_play import LookupModule -SERVICE_REGISTRY = { - "matomo": {"role": "web-app-matomo", "type": "frontend"}, - "asset": {"role": "web-svc-asset", "type": "frontend"}, - "ldap": {"role": "svc-db-openldap", "type": "backend"}, - "database": {"role_template": "svc-db-{type}", "type": "backend"}, -} SAMPLE_APPS = { "web-svc-html": {}, "web-svc-legal": {}, - "web-svc-file": {}, - "web-svc-asset": {}, - "web-app-dashboard": {}, - "web-app-matomo": {}, - "svc-db-openldap": {}, - "svc-db-mariadb": {}, + "web-svc-file": { + "compose": {"services": {"file": {"enabled": False, "shared": True}}} + }, + "web-svc-asset": { + "compose": { + "services": { + "asset": {"enabled": False, "shared": True}, + "file": {"enabled": True, "shared": True}, + } + } + }, + "web-app-dashboard": { + "compose": {"services": {"dashboard": {"enabled": False, "shared": True}}} + }, + "web-app-matomo": { + "compose": {"services": {"matomo": {"enabled": False, "shared": True}}} + }, + "svc-db-openldap": { + "compose": { + "services": { + "openldap": {"enabled": False, "shared": True, "provides": "ldap"} + } + } + }, + "svc-db-mariadb": { + "compose": {"services": {"mariadb": {"enabled": False, "shared": True}}} + }, } def _run(group_names, applications=None, meta_deps_map=None, service_registry=None): lm = LookupModule() - lm._load_service_registry = lambda project_root: ( - service_registry if service_registry is not None else SERVICE_REGISTRY - ) lm._meta_deps = lambda role, roles_dir: (meta_deps_map or {}).get(role, []) + kwargs = {} + if service_registry is not None: + kwargs["service_registry"] = service_registry apps = applications if applications is not None else SAMPLE_APPS - return lm.run([], variables={"applications": apps, "group_names": group_names})[0] + return lm.run( + [], + variables={"applications": apps, "group_names": group_names}, + **kwargs, + )[0] class TestApplicationsIfGroupAndAllDeps(unittest.TestCase): - # ------------------------------------------------------------------ - # Basic group filtering - # ------------------------------------------------------------------ - def test_direct_group_only(self): result = _run(["web-svc-html"]) self.assertIn("web-svc-html", result) @@ -49,20 +64,18 @@ class TestApplicationsIfGroupAndAllDeps(unittest.TestCase): def test_empty_group_names_returns_empty(self): self.assertEqual(_run([]), {}) - # ------------------------------------------------------------------ - # Meta dependency traversal - # ------------------------------------------------------------------ - def test_meta_dep_included(self): result = _run( - ["web-svc-legal"], meta_deps_map={"web-svc-legal": ["web-svc-html"]} + ["web-svc-legal"], + meta_deps_map={"web-svc-legal": ["web-svc-html"]}, ) self.assertIn("web-svc-legal", result) self.assertIn("web-svc-html", result) def test_meta_dep_not_in_applications_ignored(self): result = _run( - ["web-svc-legal"], meta_deps_map={"web-svc-legal": ["some-unknown-role"]} + ["web-svc-legal"], + meta_deps_map={"web-svc-legal": ["some-unknown-role"]}, ) self.assertIn("web-svc-legal", result) self.assertNotIn("some-unknown-role", result) @@ -90,10 +103,6 @@ class TestApplicationsIfGroupAndAllDeps(unittest.TestCase): self.assertIn("web-svc-html", result) self.assertIn("web-svc-legal", result) - # ------------------------------------------------------------------ - # Compose service dependency traversal - # ------------------------------------------------------------------ - def test_service_dep_enabled_and_shared(self): apps = dict(SAMPLE_APPS) apps["web-svc-legal"] = { @@ -117,7 +126,7 @@ class TestApplicationsIfGroupAndAllDeps(unittest.TestCase): } self.assertNotIn("web-app-matomo", _run(["web-svc-legal"], applications=apps)) - def test_service_not_in_registry_ignored(self): + def test_service_not_in_registry_is_ignored(self): apps = dict(SAMPLE_APPS) apps["web-svc-legal"] = { "compose": {"services": {"unknown-svc": {"enabled": True, "shared": True}}} @@ -125,28 +134,21 @@ class TestApplicationsIfGroupAndAllDeps(unittest.TestCase): result = _run(["web-svc-legal"], applications=apps) self.assertIn("web-svc-legal", result) - def test_service_role_template_resolved(self): + def test_service_dep_with_provides_is_resolved(self): apps = dict(SAMPLE_APPS) apps["web-svc-legal"] = { - "compose": { - "services": { - "database": {"enabled": True, "shared": True, "type": "mariadb"} - } - } - } - self.assertIn("svc-db-mariadb", _run(["web-svc-legal"], applications=apps)) - - def test_service_role_template_without_type_ignored(self): - apps = dict(SAMPLE_APPS) - apps["web-svc-legal"] = { - "compose": {"services": {"database": {"enabled": True, "shared": True}}} + "compose": {"services": {"ldap": {"enabled": True, "shared": True}}} } result = _run(["web-svc-legal"], applications=apps) - self.assertFalse(any(k.startswith("svc-db-") for k in result)) + self.assertIn("svc-db-openldap", result) - # ------------------------------------------------------------------ - # Mixed meta + service recursion - # ------------------------------------------------------------------ + def test_service_dep_for_database_role_uses_direct_service_name(self): + apps = dict(SAMPLE_APPS) + apps["web-svc-legal"] = { + "compose": {"services": {"mariadb": {"enabled": True, "shared": True}}} + } + result = _run(["web-svc-legal"], applications=apps) + self.assertIn("svc-db-mariadb", result) def test_mixed_meta_and_service_deps(self): apps = dict(SAMPLE_APPS) @@ -163,7 +165,6 @@ class TestApplicationsIfGroupAndAllDeps(unittest.TestCase): self.assertIn("web-app-matomo", result) def test_transitive_service_dep(self): - # web-svc-legal -meta-> web-svc-asset -service(ldap)-> svc-db-openldap apps = dict(SAMPLE_APPS) apps["web-svc-asset"] = { "compose": {"services": {"ldap": {"enabled": True, "shared": True}}} @@ -177,10 +178,6 @@ class TestApplicationsIfGroupAndAllDeps(unittest.TestCase): self.assertIn("web-svc-asset", result) self.assertIn("svc-db-openldap", result) - # ------------------------------------------------------------------ - # Return value completeness - # ------------------------------------------------------------------ - def test_returns_full_config_not_just_ids(self): apps = { "web-svc-legal": {"some_key": "some_value"}, @@ -190,24 +187,19 @@ class TestApplicationsIfGroupAndAllDeps(unittest.TestCase): ["web-svc-legal"], applications=apps, meta_deps_map={"web-svc-legal": ["web-svc-html"]}, + service_registry={}, ) self.assertEqual(result["web-svc-legal"], {"some_key": "some_value"}) self.assertEqual(result["web-svc-html"], {"other_key": 42}) - # ------------------------------------------------------------------ - # Input validation - # ------------------------------------------------------------------ - def test_missing_applications_raises(self): lm = LookupModule() - lm._load_service_registry = lambda p: {} lm._meta_deps = lambda r, d: [] with self.assertRaises(Exception): lm.run([], variables={"group_names": []}) def test_invalid_group_names_raises(self): lm = LookupModule() - lm._load_service_registry = lambda p: {} lm._meta_deps = lambda r, d: [] with self.assertRaises(Exception): lm.run( diff --git a/tests/unit/plugins/lookup/test_database.py b/tests/unit/plugins/lookup/test_database.py index e6d243408e..6277cb4e47 100644 --- a/tests/unit/plugins/lookup/test_database.py +++ b/tests/unit/plugins/lookup/test_database.py @@ -71,11 +71,7 @@ class DatabaseLookupTests(unittest.TestCase): def test_no_dbtype_configured_returns_empty_like_vars_logic(self): applications = { "web-app-foo": { - "compose": { - "services": { - "database": {"type": "", "enabled": False, "shared": False} - } - }, + "compose": {"services": {}}, "credentials": {"database_password": "pw"}, } } @@ -127,17 +123,11 @@ class DatabaseLookupTests(unittest.TestCase): ) def test_postgres_dedicated_matches_helper_variables_definition(self): - # Consumer config: database.type=postgres, shared=false + # Consumer config: postgres enabled locally (shared=false) applications = { "web-app-foo": { "compose": { - "services": { - "database": { - "type": "postgres", - "enabled": True, - "shared": False, - } - } + "services": {"postgres": {"enabled": True, "shared": False}} }, "credentials": {"database_password": "pw"}, }, @@ -209,13 +199,7 @@ class DatabaseLookupTests(unittest.TestCase): applications = { "web-app-foo": { "compose": { - "services": { - "database": { - "type": "postgres", - "enabled": True, - "shared": True, - } - } + "services": {"postgres": {"enabled": True, "shared": True}} }, "credentials": {"database_password": "pw"}, }, @@ -268,13 +252,7 @@ class DatabaseLookupTests(unittest.TestCase): applications = { "web-app-foo": { "compose": { - "services": { - "database": { - "type": "mariadb", - "enabled": True, - "shared": False, - } - } + "services": {"mariadb": {"enabled": True, "shared": False}} }, "credentials": {"database_password": "pw"}, }, @@ -320,8 +298,7 @@ class DatabaseLookupTests(unittest.TestCase): "web-app-foo": { "compose": { "services": { - "database": { - "type": "postgres", + "postgres": { "enabled": True, "shared": False, "version": "15", @@ -364,6 +341,28 @@ class DatabaseLookupTests(unittest.TestCase): # consumer override should win: self.assertEqual(out["version"], "15") + def test_multiple_database_services_raise(self): + applications = { + "web-app-foo": { + "compose": { + "services": { + "mariadb": {"enabled": True, "shared": False}, + "postgres": {"enabled": True, "shared": False}, + } + } + } + } + vars_ = { + "applications": applications, + "ports": {"localhost": {"database": {}}}, + "DIR_COMPOSITIONS": "/opt/compose/", + } + + lookup = self._make_lookup(vars_) + + with self.assertRaises(AnsibleError): + lookup.run(["web-app-foo"], variables=vars_) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/plugins/lookup/test_service.py b/tests/unit/plugins/lookup/test_service.py index 816bbee1ea..463b0366fd 100644 --- a/tests/unit/plugins/lookup/test_service.py +++ b/tests/unit/plugins/lookup/test_service.py @@ -6,39 +6,38 @@ from ansible.errors import AnsibleError from plugins.lookup.service import LookupModule -# Minimal service registry shared across tests. + _SERVICE_REGISTRY = { - "matomo": {"role": "web-app-matomo", "type": "frontend"}, - "cdn": {"role": "web-svc-cdn", "type": "frontend"}, - "logout": {"role": "web-svc-logout", "type": "frontend"}, - "web-svc-collab": {"role": "web-svc-collab", "type": "frontend"}, - "database": {"role_template": "svc-db-{type}", "type": "backend"}, + "matomo": {"role": "web-app-matomo"}, + "cdn": {"role": "web-svc-cdn"}, + "css": {"role": "web-svc-cdn", "canonical": "cdn"}, + "logout": {"role": "web-svc-logout"}, + "collab": {"role": "web-svc-collab"}, } def _run(terms, applications, group_names, service_registry=None): + kwargs = {} + if service_registry is not None: + kwargs["service_registry"] = service_registry return LookupModule().run( terms, variables={ "applications": applications, "group_names": group_names, - "SERVICE_REGISTRY": ( - service_registry if service_registry is not None else _SERVICE_REGISTRY - ), }, + **kwargs, ) class TestServiceDirect(unittest.TestCase): - """Direct (non-transitive) flag computation.""" - def setUp(self): self.applications = { "web-app-foo": { "compose": { "services": { "matomo": {"enabled": True, "shared": True}, - "cdn": {"enabled": True, "shared": False}, + "css": {"enabled": True, "shared": False}, "logout": {"enabled": False, "shared": True}, } } @@ -47,81 +46,47 @@ class TestServiceDirect(unittest.TestCase): } def _get(self, term, group_names=None): - gn = group_names if group_names is not None else ["web-app-foo"] - return _run([term], self.applications, gn)[0] - - # --- needed (enabled AND shared) --- + return _run( + [term], + self.applications, + group_names if group_names is not None else ["web-app-foo"], + service_registry=_SERVICE_REGISTRY, + )[0] def test_needed_true_when_enabled_and_shared(self): - r = self._get("matomo") - self.assertTrue(r["needed"]) + self.assertTrue(self._get("matomo")["needed"]) def test_needed_false_when_enabled_only(self): - r = self._get("cdn") - self.assertFalse(r["needed"]) + self.assertFalse(self._get("cdn")["needed"]) def test_needed_false_when_shared_only(self): - r = self._get("logout") - self.assertFalse(r["needed"]) + self.assertFalse(self._get("logout")["needed"]) def test_needed_false_when_service_absent(self): - r = self._get("web-svc-collab") - self.assertFalse(r["needed"]) + self.assertFalse(self._get("collab")["needed"]) - def test_needed_false_when_no_app_in_group_names(self): - r = self._get("matomo", []) - self.assertFalse(r["needed"]) - - def test_needed_false_when_group_names_app_not_in_applications(self): - r = self._get("matomo", ["web-app-unknown"]) - self.assertFalse(r["needed"]) + def test_needed_false_when_group_names_do_not_match(self): + self.assertFalse(self._get("matomo", ["web-app-unknown"])["needed"]) def test_needed_true_when_any_app_qualifies(self): - r = self._get("matomo", ["web-app-bar", "web-app-foo"]) - self.assertTrue(r["needed"]) + self.assertTrue(self._get("matomo", ["web-app-bar", "web-app-foo"])["needed"]) - # --- enabled flag --- + def test_enabled_shared_flags_are_aggregated_via_canonical_alias(self): + result = self._get("cdn") + self.assertTrue(result["enabled"]) + self.assertFalse(result["shared"]) - def test_enabled_true_when_enabled(self): - r = self._get("matomo") - self.assertTrue(r["enabled"]) - - def test_enabled_true_even_without_shared(self): - r = self._get("cdn") - self.assertTrue(r["enabled"]) - - def test_enabled_false_when_only_shared(self): - r = self._get("logout") - self.assertFalse(r["enabled"]) - - # --- shared flag --- - - def test_shared_true_when_shared(self): - r = self._get("matomo") - self.assertTrue(r["shared"]) - - def test_shared_false_when_only_enabled(self): - r = self._get("cdn") - self.assertFalse(r["shared"]) - - def test_shared_true_even_without_enabled(self): - r = self._get("logout") - self.assertTrue(r["shared"]) - - # --- id / role fields --- - - def test_id_and_role_returned(self): - r = self._get("matomo") - self.assertEqual(r["id"], "matomo") - self.assertEqual(r["role"], "web-app-matomo") - - # --- multiple terms --- + def test_lookup_by_role_name_uses_same_primary_service(self): + by_key = self._get("cdn") + by_role = self._get("web-svc-cdn") + self.assertEqual(by_key, by_role) def test_multiple_terms(self): results = _run( ["matomo", "cdn", "logout"], self.applications, ["web-app-foo"], + service_registry=_SERVICE_REGISTRY, ) self.assertEqual(len(results), 3) self.assertTrue(results[0]["needed"]) @@ -129,66 +94,22 @@ class TestServiceDirect(unittest.TestCase): self.assertFalse(results[2]["needed"]) def test_empty_terms_returns_empty(self): - results = _run([], self.applications, ["web-app-foo"]) - self.assertEqual(results, []) - - -class TestServiceBidirectionalMapping(unittest.TestCase): - """Terms can be service keys or role names; both resolve to the same entry.""" - - def setUp(self): - self.applications = { - "web-app-a": { - "compose": { - "services": { - "matomo": {"enabled": True, "shared": True}, - } - } - } - } - - def test_lookup_by_key(self): - r = _run(["matomo"], self.applications, ["web-app-a"])[0] - self.assertEqual(r["id"], "matomo") - self.assertEqual(r["role"], "web-app-matomo") - self.assertTrue(r["needed"]) - - def test_lookup_by_role(self): - r = _run(["web-app-matomo"], self.applications, ["web-app-a"])[0] - self.assertEqual(r["id"], "matomo") - self.assertEqual(r["role"], "web-app-matomo") - self.assertTrue(r["needed"]) - - def test_key_and_role_produce_identical_result(self): - by_key = _run(["matomo"], self.applications, ["web-app-a"])[0] - by_role = _run(["web-app-matomo"], self.applications, ["web-app-a"])[0] - self.assertEqual(by_key, by_role) - - def test_role_template_entry_resolved_by_key(self): - # 'database' has role_template, no 'role' — resolved by key - r = _run(["database"], self.applications, ["web-app-a"])[0] - self.assertEqual(r["id"], "database") - self.assertEqual(r["role"], "svc-db-{type}") + self.assertEqual( + _run( + [], + self.applications, + ["web-app-foo"], + service_registry=_SERVICE_REGISTRY, + ), + [], + ) class TestServiceTransitive(unittest.TestCase): - """Transitive resolution via enabled service dependencies. - - Transitive resolution follows SERVICE_REGISTRY so short service keys recurse - via their provider role ids instead of requiring full application ids. - """ - def setUp(self): - # web-app-nextcloud declares web-svc-collab (full app ID) as enabled - # web-svc-collab itself has matomo enabled+shared - # => nextcloud transitively needs matomo self.applications = { "web-app-nextcloud": { - "compose": { - "services": { - "web-svc-collab": {"enabled": True}, - } - } + "compose": {"services": {"collab": {"enabled": True}}} }, "web-svc-collab": { "compose": { @@ -200,166 +121,182 @@ class TestServiceTransitive(unittest.TestCase): } def test_transitive_needed_resolved(self): - r = _run(["matomo"], self.applications, ["web-app-nextcloud"])[0] - self.assertTrue(r["needed"]) + result = _run( + ["matomo"], + self.applications, + ["web-app-nextcloud"], + service_registry=_SERVICE_REGISTRY, + )[0] + self.assertTrue(result["needed"]) - def test_direct_provider_needed(self): - r = _run(["web-svc-collab"], self.applications, ["web-app-nextcloud"])[0] - # web-app-nextcloud has web-svc-collab enabled but NOT shared, so needed=False - self.assertFalse(r["needed"]) - - def test_false_for_unknown_in_apps(self): - r = _run(["logout"], self.applications, ["web-app-nextcloud"])[0] - self.assertFalse(r["needed"]) - - def test_short_key_resolves_transitively_via_registry_role(self): - service_registry = dict(_SERVICE_REGISTRY) - service_registry["collab"] = {"role": "web-svc-collab", "type": "frontend"} + def test_transitive_requires_shared_at_target(self): applications = { "web-app-nextcloud": { "compose": {"services": {"collab": {"enabled": True}}} }, - "web-svc-collab": { - "compose": {"services": {"matomo": {"enabled": True, "shared": True}}} - }, + "web-svc-collab": {"compose": {"services": {"matomo": {"enabled": True}}}}, } - r = _run( + result = _run( ["matomo"], applications, ["web-app-nextcloud"], - service_registry=service_registry, + service_registry=_SERVICE_REGISTRY, )[0] - self.assertTrue(r["needed"]) + self.assertFalse(result["needed"]) - def test_role_template_resolves_transitively_via_service_type(self): + def test_direct_provider_is_not_needed_without_shared_flag(self): + result = _run( + ["collab"], + self.applications, + ["web-app-nextcloud"], + service_registry=_SERVICE_REGISTRY, + )[0] + self.assertFalse(result["needed"]) + + +class TestServiceDiscoveryWithoutExplicitRegistry(unittest.TestCase): + def test_role_local_provider_metadata_is_discovered_from_applications(self): applications = { - "web-app-nextcloud": { + "web-app-dashboard": { "compose": { "services": { - "database": {"enabled": True, "type": "mariadb"}, + "dashboard": {"enabled": False, "shared": True}, } } }, - "svc-db-mariadb": { + "web-app-foo": { "compose": { "services": { + "dashboard": {"enabled": True, "shared": True}, + } + } + }, + } + + result = _run(["dashboard"], applications, ["web-app-foo"])[0] + self.assertEqual(result["role"], "web-app-dashboard") + self.assertTrue(result["needed"]) + + def test_provides_and_canonical_are_discovered_from_provider_configs(self): + applications = { + "web-app-keycloak": { + "compose": { + "services": { + "keycloak": { + "enabled": False, + "shared": True, + "provides": "oidc", + } + } + } + }, + "web-svc-cdn": { + "compose": { + "services": { + "cdn": {"enabled": False, "shared": True}, + "css": {"enabled": False, "shared": True, "canonical": "cdn"}, + } + } + }, + "web-app-foo": { + "compose": { + "services": { + "oidc": {"enabled": True, "shared": True}, + "css": {"enabled": True, "shared": False}, + } + } + }, + } + + oidc = _run(["oidc"], applications, ["web-app-foo"])[0] + cdn = _run(["cdn"], applications, ["web-app-foo"])[0] + + self.assertEqual(oidc["role"], "web-app-keycloak") + self.assertTrue(oidc["needed"]) + self.assertEqual(cdn["role"], "web-svc-cdn") + self.assertTrue(cdn["enabled"]) + self.assertFalse(cdn["needed"]) + + +class TestServiceCycleGuard(unittest.TestCase): + def test_cycle_does_not_loop(self): + applications = { + "svc-a": {"compose": {"services": {"svc-b": {"enabled": True}}}}, + "svc-b": {"compose": {"services": {"svc-a": {"enabled": True}}}}, + } + service_registry = { + "svc-a": {"role": "svc-a"}, + "svc-b": {"role": "svc-b"}, + "logout": {"role": "web-svc-logout"}, + } + result = _run( + ["logout"], + applications, + ["svc-a"], + service_registry=service_registry, + )[0] + self.assertFalse(result["needed"]) + + def test_cycle_found_if_service_present(self): + applications = { + "svc-a": { + "compose": { + "services": { + "svc-b": {"enabled": True}, "logout": {"enabled": True, "shared": True}, } } }, - } - r = _run(["logout"], applications, ["web-app-nextcloud"])[0] - self.assertTrue(r["needed"]) - - def test_transitive_requires_shared_at_target(self): - # If matomo is enabled but not shared at web-svc-collab, needed stays False - applications = { - "web-app-nextcloud": { - "compose": {"services": {"web-svc-collab": {"enabled": True}}} - }, - "web-svc-collab": { - "compose": {"services": {"matomo": {"enabled": True}}} # no shared - }, - } - r = _run(["matomo"], applications, ["web-app-nextcloud"])[0] - self.assertFalse(r["needed"]) - - -class TestServiceCycleGuard(unittest.TestCase): - """Circular service dependencies must not cause infinite recursion.""" - - def setUp(self): - self.applications = { - "svc-a": {"compose": {"services": {"svc-b": {"enabled": True}}}}, "svc-b": {"compose": {"services": {"svc-a": {"enabled": True}}}}, } - self.service_registry = { - "svc-a": {"role": "svc-a", "type": "backend"}, - "svc-b": {"role": "svc-b", "type": "backend"}, - "logout": {"role": "web-svc-logout", "type": "frontend"}, + service_registry = { + "svc-a": {"role": "svc-a"}, + "svc-b": {"role": "svc-b"}, + "logout": {"role": "web-svc-logout"}, } - - def test_cycle_does_not_loop(self): - r = _run( + result = _run( ["logout"], - self.applications, - ["svc-a"], - service_registry=self.service_registry, - )[0] - self.assertFalse(r["needed"]) - - def test_cycle_found_if_service_present(self): - self.applications["svc-a"]["compose"]["services"]["logout"] = { - "enabled": True, - "shared": True, - } - r = _run( - ["logout"], - self.applications, + applications, ["svc-b"], - service_registry=self.service_registry, + service_registry=service_registry, )[0] - self.assertTrue(r["needed"]) + self.assertTrue(result["needed"]) class TestServiceErrors(unittest.TestCase): def test_raises_when_applications_missing(self): with self.assertRaises(AnsibleError): - LookupModule().run( - ["matomo"], - variables={ - "group_names": ["web-app-foo"], - "SERVICE_REGISTRY": _SERVICE_REGISTRY, - }, - ) + LookupModule().run(["matomo"], variables={"group_names": ["web-app-foo"]}) def test_raises_when_applications_not_mapping(self): with self.assertRaises(AnsibleError): LookupModule().run( ["matomo"], - variables={ - "applications": ["not", "a", "dict"], - "group_names": [], - "SERVICE_REGISTRY": _SERVICE_REGISTRY, - }, + variables={"applications": ["not", "a", "dict"], "group_names": []}, ) def test_raises_when_group_names_not_list(self): with self.assertRaises(AnsibleError): LookupModule().run( ["matomo"], - variables={ - "applications": {}, - "group_names": "not-a-list", - "SERVICE_REGISTRY": _SERVICE_REGISTRY, - }, - ) - - def test_raises_when_service_registry_missing(self): - with self.assertRaises(AnsibleError): - LookupModule().run( - ["matomo"], - variables={"applications": {}, "group_names": []}, + variables={"applications": {}, "group_names": "not-a-list"}, ) def test_raises_when_service_registry_not_mapping(self): with self.assertRaises(AnsibleError): LookupModule().run( ["matomo"], - variables={ - "applications": {}, - "group_names": [], - "SERVICE_REGISTRY": "not-a-dict", - }, + variables={"applications": {}, "group_names": []}, + service_registry="not-a-dict", ) def test_raises_when_term_empty(self): with self.assertRaises(AnsibleError): - _run([" "], {}, []) + _run([" "], {}, [], service_registry=_SERVICE_REGISTRY) def test_raises_when_term_unknown(self): with self.assertRaises(AnsibleError): - _run(["totally-unknown-key"], {}, []) + _run(["totally-unknown-key"], {}, [], service_registry=_SERVICE_REGISTRY) if __name__ == "__main__": diff --git a/tests/unit/roles/sys-stk-backend/lookup_plugins/test_service_should_load.py b/tests/unit/roles/sys-stk-backend/lookup_plugins/test_service_should_load.py deleted file mode 100644 index f4a3099ae8..0000000000 --- a/tests/unit/roles/sys-stk-backend/lookup_plugins/test_service_should_load.py +++ /dev/null @@ -1,106 +0,0 @@ -import importlib.util -import unittest -from pathlib import Path - -from ansible.errors import AnsibleError - - -def _repo_root() -> Path: - return Path(__file__).resolve().parents[5] - - -def _load_module(rel_path: str, name: str): - path = _repo_root() / rel_path - spec = importlib.util.spec_from_file_location(name, str(path)) - mod = importlib.util.module_from_spec(spec) - assert spec and spec.loader - spec.loader.exec_module(mod) - return mod - - -class TestServiceShouldLoadLookup(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.mod = _load_module( - "roles/sys-stk-backend/lookup_plugins/service_should_load.py", - "service_should_load", - ) - - def setUp(self): - self.applications = { - "web-app-test": { - "compose": { - "services": { - "ldap": {"enabled": True, "shared": True}, - "ollama": {"enabled": True, "shared": False}, - } - } - } - } - - def test_true_when_enabled_shared_not_run_once_and_not_self(self): - result = self.mod.LookupModule().run( - ["svc-db-openldap"], - variables={ - "applications": self.applications, - "application_id": "web-app-test", - "service_name": "ldap", - }, - ) - self.assertEqual(result, [True]) - - def test_false_when_run_once_already_defined(self): - result = self.mod.LookupModule().run( - ["svc-db-openldap"], - variables={ - "applications": self.applications, - "application_id": "web-app-test", - "service_name": "ldap", - "run_once_svc_db_openldap": True, - }, - ) - self.assertEqual(result, [False]) - - def test_false_when_not_shared(self): - result = self.mod.LookupModule().run( - ["svc-ai-ollama"], - variables={ - "applications": self.applications, - "application_id": "web-app-test", - "service_name": "ollama", - }, - ) - self.assertEqual(result, [False]) - - def test_false_when_application_equals_service(self): - result = self.mod.LookupModule().run( - ["web-app-test"], - variables={ - "applications": self.applications, - "application_id": "web-app-test", - "service_name": "ldap", - }, - ) - self.assertEqual(result, [False]) - - def test_raises_when_service_id_is_empty(self): - with self.assertRaises(AnsibleError): - self.mod.LookupModule().run( - [" "], - variables={ - "applications": self.applications, - "application_id": "web-app-test", - "service_name": "ldap", - }, - ) - - def test_raises_when_applications_missing(self): - with self.assertRaises(AnsibleError): - self.mod.LookupModule().run( - ["svc-db-openldap"], - variables={"application_id": "web-app-test", "service_name": "ldap"}, - ) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/unit/utils/test_service_registry.py b/tests/unit/utils/test_service_registry.py new file mode 100644 index 0000000000..3608f5245f --- /dev/null +++ b/tests/unit/utils/test_service_registry.py @@ -0,0 +1,240 @@ +from __future__ import annotations + +import tempfile +import unittest +from pathlib import Path + +from utils.service_registry import ( + ServiceRegistryError, + build_service_registry_from_applications, + detect_service_bucket, + detect_service_channel, + ordered_primary_service_entries, + resolve_service_dependency_roles_from_config, +) + + +class TestServiceRegistryDiscovery(unittest.TestCase): + def test_discovery_reads_provides_canonical_shared_and_enabled(self): + applications = { + "web-app-keycloak": { + "compose": { + "services": { + "keycloak": { + "enabled": False, + "shared": True, + "provides": "oidc", + } + } + } + }, + "web-svc-cdn": { + "compose": { + "services": { + "cdn": {"enabled": False, "shared": True}, + "css": {"enabled": True, "shared": True, "canonical": "cdn"}, + "javascript": { + "enabled": False, + "shared": True, + "canonical": "cdn", + }, + } + } + }, + } + + registry = build_service_registry_from_applications(applications) + + self.assertEqual(registry["oidc"]["role"], "web-app-keycloak") + self.assertEqual(registry["oidc"]["entity_name"], "keycloak") + self.assertTrue(registry["oidc"]["shared"]) + self.assertFalse(registry["oidc"]["enabled"]) + + self.assertEqual(registry["cdn"]["role"], "web-svc-cdn") + self.assertNotIn("canonical", registry["cdn"]) + self.assertEqual(registry["css"]["canonical"], "cdn") + self.assertTrue(registry["css"]["enabled"]) + self.assertTrue(registry["javascript"]["shared"]) + + def test_entity_name_derivation_for_relevant_role_prefixes(self): + applications = { + "web-app-dashboard": { + "compose": { + "services": {"dashboard": {"enabled": False, "shared": True}} + } + }, + "web-svc-file": { + "compose": {"services": {"file": {"enabled": False, "shared": True}}} + }, + "svc-db-mariadb": { + "compose": {"services": {"mariadb": {"enabled": False, "shared": True}}} + }, + "svc-ai-ollama": { + "compose": {"services": {"ollama": {"enabled": False, "shared": True}}} + }, + } + + registry = build_service_registry_from_applications(applications) + + self.assertIn("dashboard", registry) + self.assertIn("file", registry) + self.assertIn("mariadb", registry) + self.assertIn("ollama", registry) + self.assertEqual(detect_service_channel("web-app-dashboard"), "frontend") + self.assertEqual(detect_service_channel("svc-db-mariadb"), "backend") + self.assertEqual(detect_service_bucket("web-app-dashboard"), "web-app") + self.assertEqual(detect_service_bucket("web-svc-file"), "web-svc") + self.assertEqual(detect_service_bucket("svc-db-mariadb"), "universal") + + def test_direct_service_resolution_uses_role_local_names(self): + registry = { + "ldap": {"role": "svc-db-openldap"}, + "mariadb": {"role": "svc-db-mariadb"}, + } + config = { + "compose": { + "services": { + "ldap": {"enabled": True, "shared": True}, + "mariadb": {"enabled": True, "shared": True}, + "ignored": {"enabled": True, "shared": False}, + } + } + } + + self.assertEqual( + resolve_service_dependency_roles_from_config(config, registry), + ["svc-db-openldap", "svc-db-mariadb"], + ) + + +class TestServiceRegistryOrdering(unittest.TestCase): + def _mk_role( + self, + root: Path, + role: str, + config: str, + *, + run_after: list[str] | None = None, + ) -> None: + role_dir = root / role + (role_dir / "config").mkdir(parents=True, exist_ok=True) + (role_dir / "config" / "main.yml").write_text(config, encoding="utf-8") + (role_dir / "meta").mkdir(parents=True, exist_ok=True) + meta_lines = ["galaxy_info:"] + if run_after is not None: + meta_lines.append(" run_after:") + for item in run_after: + meta_lines.append(f" - {item}") + else: + meta_lines.append(" run_after: []") + (role_dir / "meta" / "main.yml").write_text( + "\n".join(meta_lines) + "\n", + encoding="utf-8", + ) + + def test_ordered_entries_follow_bucket_order_and_run_after(self): + registry = { + "mariadb": { + "role": "svc-db-mariadb", + "bucket": "universal", + "deploy_type": "universal", + }, + "file": { + "role": "web-svc-file", + "bucket": "web-svc", + "deploy_type": "server", + }, + "asset": { + "role": "web-svc-asset", + "bucket": "web-svc", + "deploy_type": "server", + }, + "matomo": { + "role": "web-app-matomo", + "bucket": "web-app", + "deploy_type": "server", + }, + "dashboard": { + "role": "web-app-dashboard", + "bucket": "web-app", + "deploy_type": "server", + }, + } + + with tempfile.TemporaryDirectory() as td: + roles_dir = Path(td) + self._mk_role( + roles_dir, + "svc-db-mariadb", + "compose:\n services:\n mariadb:\n enabled: false\n shared: true\n", + ) + self._mk_role( + roles_dir, + "web-svc-file", + "compose:\n services:\n file:\n enabled: false\n shared: true\n", + ) + self._mk_role( + roles_dir, + "web-svc-asset", + "compose:\n services:\n asset:\n enabled: false\n shared: true\n", + run_after=["web-svc-file"], + ) + self._mk_role( + roles_dir, + "web-app-matomo", + "compose:\n services:\n matomo:\n enabled: false\n shared: true\n", + ) + self._mk_role( + roles_dir, + "web-app-dashboard", + "compose:\n services:\n dashboard:\n enabled: false\n shared: true\n", + run_after=["web-app-matomo"], + ) + + ordered = ordered_primary_service_entries(registry, roles_dir) + + self.assertEqual( + [entry["role"] for entry in ordered], + [ + "svc-db-mariadb", + "web-svc-file", + "web-svc-asset", + "web-app-matomo", + "web-app-dashboard", + ], + ) + + def test_cross_type_run_after_fails_hard(self): + registry = { + "file": { + "role": "web-svc-file", + "bucket": "web-svc", + "deploy_type": "server", + }, + "mail": { + "role": "sys-svc-mail", + "bucket": "universal", + "deploy_type": "universal", + }, + } + + with tempfile.TemporaryDirectory() as td: + roles_dir = Path(td) + self._mk_role( + roles_dir, + "web-svc-file", + "compose:\n services:\n file:\n enabled: false\n shared: true\n", + run_after=["sys-svc-mail"], + ) + self._mk_role( + roles_dir, + "sys-svc-mail", + "compose:\n services:\n mail:\n enabled: false\n shared: true\n", + ) + + with self.assertRaises(ServiceRegistryError): + ordered_primary_service_entries(registry, roles_dir) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/applications/in_group_deps.py b/utils/applications/in_group_deps.py index 5daab1c392..e3f37d97d8 100644 --- a/utils/applications/in_group_deps.py +++ b/utils/applications/in_group_deps.py @@ -2,27 +2,29 @@ from __future__ import annotations import os from collections.abc import Callable +from pathlib import Path from typing import Any import yaml +from utils.service_registry import ( + build_service_registry_from_applications, + build_service_registry_from_roles_dir, + resolve_service_dependency_roles_from_config, +) + MetaDepsResolver = Callable[[str, str], list[str]] def load_service_registry(project_root: str) -> dict[str, Any]: - path = os.path.join(project_root, "group_vars", "all", "20_services.yml") - if not os.path.isfile(path): + roles_dir = os.path.join(project_root, "roles") + if not os.path.isdir(roles_dir): return {} - try: - with open(path, encoding="utf-8") as handle: - data = yaml.safe_load(handle) or {} + return build_service_registry_from_roles_dir(Path(roles_dir)) except Exception: return {} - registry = data.get("SERVICE_REGISTRY", {}) - return registry if isinstance(registry, dict) else {} - def meta_deps_from_disk(role: str, roles_dir: str) -> list[str]: meta_file = os.path.join(roles_dir, role, "meta", "main.yml") @@ -46,51 +48,14 @@ def meta_deps_from_disk(role: str, roles_dir: str) -> list[str]: return deps -def _resolve_service_role( - service_key: str, - service_conf: dict[str, Any], - service_registry: dict[str, Any], -) -> str | None: - entry = service_registry.get(service_key) - if not isinstance(entry, dict): - return None - - role = entry.get("role") - if isinstance(role, str) and role: - return role - - role_template = entry.get("role_template") - if not isinstance(role_template, str) or not role_template: - return None - - svc_type = service_conf.get("type", "") - if not isinstance(svc_type, str) or not svc_type: - return None - - return role_template.replace("{type}", svc_type) - - def _service_dep_roles( role: str, applications: dict[str, Any], service_registry: dict[str, Any], ) -> list[str]: app_conf = applications.get(role) or {} - services = app_conf.get("compose", {}).get("services", {}) - if not isinstance(services, dict): - return [] - - roles: list[str] = [] - for service_key, service_conf in services.items(): - if not isinstance(service_conf, dict): - continue - if not service_conf.get("enabled") or not service_conf.get("shared"): - continue - - dep_role = _resolve_service_role(service_key, service_conf, service_registry) - if dep_role and dep_role != role: - roles.append(dep_role) - return roles + roles = resolve_service_dependency_roles_from_config(app_conf, service_registry) + return [dep_role for dep_role in roles if dep_role != role] def _collect_reachable_roles( @@ -150,7 +115,10 @@ def applications_if_group_and_all_deps( raise ValueError( "'project_root' is required when 'service_registry' is not provided" ) - service_registry = load_service_registry(project_root) + if applications: + service_registry = build_service_registry_from_applications(applications) + else: + service_registry = load_service_registry(project_root) elif not isinstance(service_registry, dict): raise ValueError("'service_registry' must be a mapping") diff --git a/utils/database_service.py b/utils/database_service.py new file mode 100644 index 0000000000..d1fc552f42 --- /dev/null +++ b/utils/database_service.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +from typing import Any, Dict, Mapping + + +RDBMS_SERVICE_KEYS = ("mariadb", "postgres") + + +def _as_mapping(value: Any) -> Dict[str, Any]: + return value if isinstance(value, dict) else {} + + +def get_compose_services( + applications: Mapping[str, Any], + application_id: str, +) -> Dict[str, Any]: + application = _as_mapping(applications.get(application_id)) + compose = _as_mapping(application.get("compose")) + return _as_mapping(compose.get("services")) + + +def get_database_service_config( + applications: Mapping[str, Any], + application_id: str, +) -> Dict[str, Any]: + service_key = resolve_database_service_key(applications, application_id) + if not service_key: + return {} + return _as_mapping( + get_compose_services(applications, application_id).get(service_key) + ) + + +def resolve_database_service_key( + applications: Mapping[str, Any], + application_id: str, +) -> str: + services = get_compose_services(applications, application_id) + enabled_keys = [ + service_key + for service_key in RDBMS_SERVICE_KEYS + if _as_mapping(services.get(service_key)).get("enabled") is True + ] + + if len(enabled_keys) > 1: + raise ValueError( + f"{application_id}: multiple direct database services are enabled: " + + ", ".join(enabled_keys) + ) + + return enabled_keys[0] if enabled_keys else "" diff --git a/utils/manager/inventory.py b/utils/manager/inventory.py index 63d4df4d7b..46e1e7e81c 100644 --- a/utils/manager/inventory.py +++ b/utils/manager/inventory.py @@ -6,7 +6,12 @@ from typing import Dict, List, Set from utils.handler.yaml import YamlHandler from utils.handler.vault import VaultHandler, VaultScalar +from utils.database_service import resolve_database_service_key from utils.manager.value_generator import ValueGenerator +from utils.service_registry import ( + build_service_registry_from_roles_dir, + resolve_service_dependency_roles_from_config, +) class InventoryManager: @@ -51,8 +56,7 @@ class InventoryManager: def load_role_schema(self, role_name: str) -> dict: schema_path = self.roles_root / role_name / "schema" / "main.yml" if not schema_path.exists(): - print(f"ERROR: schema not found: {schema_path}", file=sys.stderr) - sys.exit(1) + return {} return YamlHandler.load_yaml(schema_path) or {} def load_role_config_by_path(self, role_path: Path) -> dict: @@ -73,40 +77,8 @@ class InventoryManager: """ Extract shared-provider dependencies from a single role config. """ - services = (config.get("compose") or {}).get("services") or {} - includes: List[str] = [] - - ldap = services.get("ldap") or {} - if ldap.get("enabled") is True and ldap.get("shared") is True: - includes.append("svc-db-openldap") - - oidc = services.get("oidc") or {} - if oidc.get("enabled") is True and oidc.get("shared") is True: - includes.append("web-app-keycloak") - - matomo = services.get("matomo") or {} - if matomo.get("enabled") is True and matomo.get("shared") is True: - includes.append("web-app-matomo") - - db = services.get("database") or {} - if db.get("enabled") is True and db.get("shared") is True: - db_type = (db.get("type") or "").strip() - if not db_type: - print( - "ERROR: compose.services.database.enabled=true and shared=true but compose.services.database.type is missing", - file=sys.stderr, - ) - sys.exit(1) - includes.append(f"svc-db-{db_type}") - - # stable order, dedup - out: List[str] = [] - seen: Set[str] = set() - for r in includes: - if r not in seen: - out.append(r) - seen.add(r) - return out + service_registry = build_service_registry_from_roles_dir(self.roles_root) + return resolve_service_dependency_roles_from_config(config, service_registry) def resolve_schema_includes_recursive(self, root_role_name: str) -> List[str]: """ @@ -144,6 +116,8 @@ class InventoryManager: role_path = self.roles_root / role_name app_id = self.load_application_id(role_path) schema = self.load_role_schema(role_name) + if not schema: + return apps = self.inventory.setdefault("applications", {}) target = apps.setdefault(app_id, {}) @@ -157,19 +131,20 @@ class InventoryManager: app_id = self.load_application_id(role_path) cfg = self.load_role_config_by_path(role_path) - apps = self.inventory.setdefault("applications", {}) - target = apps.setdefault(app_id, {}) - services = (cfg.get("compose") or {}).get("services") or {} - database = services.get("database") or {} oauth2 = services.get("oauth2") or {} - - if database.get("enabled") is True and database.get("shared") is True: + oidc = services.get("oidc") or {} + has_database_service = bool(resolve_database_service_key({app_id: cfg}, app_id)) + if has_database_service: + apps = self.inventory.setdefault("applications", {}) + target = apps.setdefault(app_id, {}) target.setdefault("credentials", {})["database_password"] = ( self.value_generator.generate_value("alphanumeric") ) - if oauth2.get("enabled") is True: + if oauth2.get("enabled") is True or oidc.get("enabled") is True: + apps = self.inventory.setdefault("applications", {}) + target = apps.setdefault(app_id, {}) target.setdefault("credentials", {})["oauth2_proxy_cookie_secret"] = ( self.value_generator.generate_value("random_hex_16") ) diff --git a/utils/service_registry.py b/utils/service_registry.py new file mode 100644 index 0000000000..7a4db7ec55 --- /dev/null +++ b/utils/service_registry.py @@ -0,0 +1,310 @@ +from __future__ import annotations + +from collections import deque +from pathlib import Path +from typing import Any, Dict, List + +import yaml + +from utils.entity_name_utils import get_entity_name +from utils.invokable import types_from_group_names + + +class ServiceRegistryError(ValueError): + """Raised when role-local service discovery is invalid.""" + + +def _as_mapping(value: Any) -> Dict[str, Any]: + return value if isinstance(value, dict) else {} + + +def _normalized_name(value: Any) -> str: + if not isinstance(value, str): + return "" + return value.strip() + + +def detect_service_channel(role_name: str) -> str: + return "frontend" if role_name.startswith(("web-app-", "web-svc-")) else "backend" + + +def detect_deploy_type(role_name: str) -> str: + detected = types_from_group_names([role_name]) + if "server" in detected: + return "server" + if "workstation" in detected: + return "workstation" + if "universal" in detected: + return "universal" + return "server" if role_name.startswith(("web-app-", "web-svc-")) else "universal" + + +def detect_service_bucket(role_name: str) -> str: + deploy_type = detect_deploy_type(role_name) + if deploy_type == "universal": + return "universal" + if deploy_type == "workstation": + return "workstation" + if role_name.startswith("web-svc-"): + return "web-svc" + if role_name.startswith("web-app-"): + return "web-app" + return deploy_type + + +def read_yaml_file(path: Path) -> Dict[str, Any]: + if not path.is_file(): + return {} + return _as_mapping(yaml.safe_load(path.read_text(encoding="utf-8")) or {}) + + +def load_applications_from_roles_dir(roles_dir: Path) -> Dict[str, Dict[str, Any]]: + applications: Dict[str, Dict[str, Any]] = {} + for role_dir in sorted(p for p in roles_dir.iterdir() if p.is_dir()): + vars_file = role_dir / "vars" / "main.yml" + if not vars_file.is_file(): + continue + vars_data = read_yaml_file(vars_file) + application_id = _normalized_name(vars_data.get("application_id")) + if not application_id: + continue + applications[application_id] = read_yaml_file(role_dir / "config" / "main.yml") + return applications + + +def discover_role_services( + role_name: str, + config: Dict[str, Any], +) -> Dict[str, Dict[str, Any]]: + services = _as_mapping(_as_mapping(config.get("compose")).get("services")) + entity_name = get_entity_name(role_name) + primary_entry = _as_mapping(services.get(entity_name)) + alias_entries = { + key: _as_mapping(entry) + for key, entry in services.items() + if isinstance(entry, dict) + and _normalized_name(_as_mapping(entry).get("canonical")) in {entity_name} + } + provides = _normalized_name(primary_entry.get("provides")) + if provides == entity_name: + provides = "" + + is_provider = bool(primary_entry) and ( + "shared" in primary_entry or "provides" in primary_entry or alias_entries + ) + if not is_provider: + return {} + + primary_id = provides or entity_name + base_entry = { + "role": role_name, + "entity_name": entity_name, + "source_key": entity_name, + "deploy_type": detect_deploy_type(role_name), + "bucket": detect_service_bucket(role_name), + "service_type": detect_service_channel(role_name), + "shared": bool(primary_entry.get("shared", False)), + "enabled": bool(primary_entry.get("enabled", False)), + } + if provides: + base_entry["provides"] = provides + + discovered: Dict[str, Dict[str, Any]] = {primary_id: base_entry} + for alias_key, alias_entry in sorted(alias_entries.items()): + discovered[alias_key] = { + **base_entry, + "source_key": alias_key, + "canonical": primary_id, + "shared": bool(alias_entry.get("shared", False)), + "enabled": bool(alias_entry.get("enabled", False)), + } + + return discovered + + +def build_service_registry_from_applications( + applications: Dict[str, Any], +) -> Dict[str, Dict[str, Any]]: + registry: Dict[str, Dict[str, Any]] = {} + for role_name, config in sorted(applications.items()): + role_services = discover_role_services(role_name, _as_mapping(config)) + for service_key, entry in role_services.items(): + existing = registry.get(service_key) + if existing and existing.get("role") != entry.get("role"): + raise ServiceRegistryError( + f"Duplicate service key '{service_key}' is declared by both " + f"'{existing.get('role')}' and '{entry.get('role')}'." + ) + registry[service_key] = entry + return registry + + +def build_service_registry_from_roles_dir( + roles_dir: Path, +) -> Dict[str, Dict[str, Any]]: + return build_service_registry_from_applications( + load_applications_from_roles_dir(roles_dir) + ) + + +def build_role_to_primary_service_key( + service_registry: Dict[str, Dict[str, Any]], +) -> Dict[str, str]: + result: Dict[str, str] = {} + for service_key, entry in service_registry.items(): + if "canonical" in entry: + continue + role_name = _normalized_name(entry.get("role")) + if role_name: + result[role_name] = service_key + return result + + +def canonical_service_key( + service_registry: Dict[str, Dict[str, Any]], + service_key: str, +) -> str: + entry = _as_mapping(service_registry.get(service_key)) + return _normalized_name(entry.get("canonical")) or service_key + + +def equivalent_service_keys( + service_registry: Dict[str, Dict[str, Any]], + service_key: str, +) -> List[str]: + primary = canonical_service_key(service_registry, service_key) + keys = [ + key + for key, entry in service_registry.items() + if canonical_service_key(service_registry, key) == primary + ] + return sorted(keys) + + +def resolve_service_dependency_roles_from_config( + config: Dict[str, Any], + service_registry: Dict[str, Dict[str, Any]], +) -> List[str]: + services = _as_mapping(_as_mapping(config.get("compose")).get("services")) + includes: List[str] = [] + for service_key, service_conf in services.items(): + service_conf = _as_mapping(service_conf) + if not ( + service_conf.get("enabled") is True and service_conf.get("shared") is True + ): + continue + + entry = _as_mapping(service_registry.get(service_key)) + role_name = _normalized_name(entry.get("role")) + if role_name: + includes.append(role_name) + + seen = set() + ordered: List[str] = [] + for role_name in includes: + if role_name not in seen: + ordered.append(role_name) + seen.add(role_name) + return ordered + + +def load_run_after_from_roles_dir(roles_dir: Path, role_name: str) -> List[str]: + meta = read_yaml_file(roles_dir / role_name / "meta" / "main.yml") + galaxy_info = _as_mapping(meta.get("galaxy_info")) + raw = galaxy_info.get("run_after") or [] + if not isinstance(raw, list): + raise ServiceRegistryError( + f"Invalid run_after in roles/{role_name}/meta/main.yml: expected list." + ) + result: List[str] = [] + for item in raw: + dep = _normalized_name(item) + if not dep: + raise ServiceRegistryError( + f"Invalid run_after entry in roles/{role_name}/meta/main.yml: {item!r}" + ) + result.append(dep) + return result + + +_BUCKET_ORDER = { + "universal": 0, + "workstation": 1, + "server": 2, + "web-svc": 3, + "web-app": 4, +} + + +def ordered_primary_service_entries( + service_registry: Dict[str, Dict[str, Any]], + roles_dir: Path, +) -> List[Dict[str, Any]]: + primary_entries = { + entry["role"]: {"id": service_key, **entry} + for service_key, entry in service_registry.items() + if "canonical" not in entry + } + + ordered: List[Dict[str, Any]] = [] + for bucket in ("universal", "workstation", "server", "web-svc", "web-app"): + roles_in_bucket = sorted( + role_name + for role_name, entry in primary_entries.items() + if entry.get("bucket") == bucket + ) + if not roles_in_bucket: + continue + + graph: Dict[str, List[str]] = {role_name: [] for role_name in roles_in_bucket} + indegree: Dict[str, int] = {role_name: 0 for role_name in roles_in_bucket} + + for role_name in roles_in_bucket: + current = primary_entries[role_name] + current_deploy_type = _normalized_name(current.get("deploy_type")) + current_bucket_order = _BUCKET_ORDER[bucket] + + for dep_role in load_run_after_from_roles_dir(roles_dir, role_name): + dep_deploy_type = detect_deploy_type(dep_role) + if dep_deploy_type != current_deploy_type: + raise ServiceRegistryError( + f"{role_name}: run_after '{dep_role}' crosses deploy types " + f"({current_deploy_type} -> {dep_deploy_type})." + ) + + dep_bucket = detect_service_bucket(dep_role) + dep_bucket_order = _BUCKET_ORDER.get(dep_bucket, current_bucket_order) + if dep_bucket_order > current_bucket_order: + raise ServiceRegistryError( + f"{role_name}: run_after '{dep_role}' points to a later loader " + f"bucket ({dep_bucket}), which cannot be satisfied." + ) + if dep_bucket_order < current_bucket_order: + continue + if dep_role not in primary_entries: + raise ServiceRegistryError( + f"{role_name}: run_after '{dep_role}' is not a discovered " + "shared service role." + ) + + graph[dep_role].append(role_name) + indegree[role_name] += 1 + + ready = deque(sorted(role for role, count in indegree.items() if count == 0)) + emitted = 0 + while ready: + role_name = ready.popleft() + ordered.append(primary_entries[role_name]) + emitted += 1 + + for dependent in sorted(graph[role_name]): + indegree[dependent] -= 1 + if indegree[dependent] == 0: + ready.append(dependent) + + if emitted != len(roles_in_bucket): + raise ServiceRegistryError( + f"Circular run_after dependency detected in bucket '{bucket}'." + ) + + return ordered From c0f5ad97d7c266fe76e02e7235ffba34b1358be3 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 13 Apr 2026 21:35:06 +0200 Subject: [PATCH 17/55] chore(skills): update caveman skill hash Co-Authored-By: Claude Sonnet 4.6 --- skills-lock.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills-lock.json b/skills-lock.json index 5ddcab614c..6046df721a 100644 --- a/skills-lock.json +++ b/skills-lock.json @@ -4,7 +4,7 @@ "caveman": { "source": "JuliusBrussee/caveman", "sourceType": "github", - "computedHash": "4d486dd6f9fbb27ce1c51c972c9a5eb25a53236ae05eabf4d076ac1e293f4b7a" + "computedHash": "a818cdc41dcfaa50dd891c5cb5e5705968338de02e7e37949ca56e8c30ad4176" }, "caveman-commit": { "source": "JuliusBrussee/caveman", From ebdb55dfcc555265727609a32f62696f7a9832f8 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 13 Apr 2026 21:40:09 +0200 Subject: [PATCH 18/55] ci(push): enable cancel-in-progress for push workflow Co-Authored-By: Claude Sonnet 4.6 --- .github/workflows/entry-push-latest.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/entry-push-latest.yml b/.github/workflows/entry-push-latest.yml index facc3595f2..c0a950cdbb 100644 --- a/.github/workflows/entry-push-latest.yml +++ b/.github/workflows/entry-push-latest.yml @@ -2,7 +2,7 @@ name: "⚡ CI: Push" concurrency: group: global-ci-${{ github.repository }}-${{ github.ref_name }} - cancel-in-progress: false + cancel-in-progress: true on: push: From 5cebe3ea633dd4439768e8f4be938bc7ca99b632 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 13 Apr 2026 22:18:02 +0200 Subject: [PATCH 19/55] feat(ci): add CI_CANCEL_IN_PROGRESS variable and restructure branch docs - Use vars.CI_CANCEL_IN_PROGRESS in entry-push-latest.yml so cancellation can be disabled per-repo without changing workflow code - Move docs/contributing/tools/github/branch.md into branch/ subdirectory as security.md; add configuration.md for CI repository variables and README.md as directory index - Fix all cross-references in SECURITY.md, pipeline.md, branch.md, pull-request.md, workflow.md, and repository.md Co-Authored-By: Claude Sonnet 4.6 --- .github/workflows/entry-push-latest.yml | 2 +- SECURITY.md | 2 +- docs/contributing/artefact/git/branch.md | 2 +- docs/contributing/artefact/git/pipeline.md | 6 +++ .../contributing/artefact/git/pull-request.md | 2 +- .../tools/github/branch/README.md | 8 ++++ .../tools/github/branch/configuration.md | 37 +++++++++++++++++++ .../github/{branch.md => branch/security.md} | 2 +- docs/contributing/tools/github/repository.md | 2 +- 9 files changed, 57 insertions(+), 6 deletions(-) create mode 100644 docs/contributing/tools/github/branch/README.md create mode 100644 docs/contributing/tools/github/branch/configuration.md rename docs/contributing/tools/github/{branch.md => branch/security.md} (98%) diff --git a/.github/workflows/entry-push-latest.yml b/.github/workflows/entry-push-latest.yml index c0a950cdbb..cfa6f582f2 100644 --- a/.github/workflows/entry-push-latest.yml +++ b/.github/workflows/entry-push-latest.yml @@ -2,7 +2,7 @@ name: "⚡ CI: Push" concurrency: group: global-ci-${{ github.repository }}-${{ github.ref_name }} - cancel-in-progress: true + cancel-in-progress: ${{ vars.CI_CANCEL_IN_PROGRESS != 'false' }} on: push: diff --git a/SECURITY.md b/SECURITY.md index 0f81cf5284..bdf4bc608c 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -27,7 +27,7 @@ For general help and non-security requests, see [SUPPORT.md](SUPPORT.md). The security policies enforced on this repository are documented here: -- [Branch Protection](docs/contributing/tools/github/branch.md): Rules enforced on the `main` branch. +- [Branch Protection](docs/contributing/tools/github/branch/security.md): Rules enforced on the `main` branch. - [Repository Settings](docs/contributing/tools/github/repository.md): Repository-wide security configuration. ## Detailed Secure Use Guides 🛡️ diff --git a/docs/contributing/artefact/git/branch.md b/docs/contributing/artefact/git/branch.md index ef1d594e3e..1241d57c97 100644 --- a/docs/contributing/artefact/git/branch.md +++ b/docs/contributing/artefact/git/branch.md @@ -15,7 +15,7 @@ The branch prefix MUST match the type of change. The [PR workflow](pull-request. ## Enforcement 🔒 -All rules in this document are actively enforced on `main` via GitHub branch protection. See [branch.md](../../tools/github/branch.md) for the full enforcement policy. +All rules in this document are actively enforced on `main` via GitHub branch protection. See [branch.md](../../tools/github/branch/security.md) for the full enforcement policy. ## Naming Conventions 🏷️ diff --git a/docs/contributing/artefact/git/pipeline.md b/docs/contributing/artefact/git/pipeline.md index 52b55ee24a..cca6514607 100644 --- a/docs/contributing/artefact/git/pipeline.md +++ b/docs/contributing/artefact/git/pipeline.md @@ -104,6 +104,12 @@ The final `done` job aggregates all deploy, install, and development gates. CI i - PR pipelines use `cancel-in-progress: true` so only the newest run per PR and event type is active. - The orchestrator uses `cancel-in-progress: false` to avoid interrupting long-running deploy tests mid-flight. +- The push entry workflow (`entry-push-latest.yml`) defaults to `cancel-in-progress: true` but respects the + repository variable `CI_CANCEL_IN_PROGRESS`. Set it to `false` under + **Settings → Secrets and variables → Actions → Variables** to prevent in-progress runs from being cancelled + on the `main` / feature branches. Any other value (or no value) keeps the default cancel behaviour. + +See [configuration.md](../../tools/github/branch/configuration.md) for all repository variables that control CI behaviour. ## Fork PRs 🍴 diff --git a/docs/contributing/artefact/git/pull-request.md b/docs/contributing/artefact/git/pull-request.md index cd2105190a..33a2430e81 100644 --- a/docs/contributing/artefact/git/pull-request.md +++ b/docs/contributing/artefact/git/pull-request.md @@ -17,7 +17,7 @@ You MUST pick the template that matches your change. The table below links the a Branch names MUST follow the naming conventions defined in [branch.md](branch.md). The branch prefix MUST match the type of change and is used to classify the PR scope and select the CI pipeline. -The protection rules enforced on `main` are documented in [branch.md](../../tools/github/branch.md). +The protection rules enforced on `main` are documented in [branch.md](../../tools/github/branch/security.md). ## Forking Flow 🍴 diff --git a/docs/contributing/tools/github/branch/README.md b/docs/contributing/tools/github/branch/README.md new file mode 100644 index 0000000000..20f8416bd3 --- /dev/null +++ b/docs/contributing/tools/github/branch/README.md @@ -0,0 +1,8 @@ +# Branch Configuration 🌿 + +This section documents the GitHub branch settings for this repository. + +| File | Purpose | +|---|---| +| [security.md](security.md) | Branch protection rules enforced on `main` | +| [configuration.md](configuration.md) | Repository variables that control CI behaviour | diff --git a/docs/contributing/tools/github/branch/configuration.md b/docs/contributing/tools/github/branch/configuration.md new file mode 100644 index 0000000000..a2717ed859 --- /dev/null +++ b/docs/contributing/tools/github/branch/configuration.md @@ -0,0 +1,37 @@ +# CI Configuration ⚙️ + +This page documents the repository variables that control CI pipeline behaviour. +Repository variables are set under **Settings → Secrets and variables → Actions → Variables**. + +## `CI_CANCEL_IN_PROGRESS` + +Controls whether a new push cancels an already-running CI pipeline on the same branch +in [entry-push-latest.yml](../../../../../.github/workflows/entry-push-latest.yml). + +**Default behaviour (variable not set or set to any value other than `false`):** +In-progress runs are cancelled when a new push arrives. This is the recommended setting for most workflows. + +**To disable cancellation:** + +1. Open the repository on GitHub. +2. Go to **Settings → Secrets and variables → Actions**. +3. Switch to the **Variables** tab. +4. Click **New repository variable**. +5. Set **Name** to `CI_CANCEL_IN_PROGRESS` and **Value** to `false`. +6. Save. + +**To re-enable cancellation:** + +Delete the variable or change its value to anything other than `false` (e.g. `true`). + +**How it works:** + +```yaml +cancel-in-progress: ${{ vars.CI_CANCEL_IN_PROGRESS != 'false' }} +``` + +| Variable value | Expression result | Behaviour | +|---|---|---| +| *(not set / empty)* | `'' != 'false'` → `true` | Cancels in-progress runs ✓ | +| `false` | `'false' != 'false'` → `false` | Does **not** cancel ✓ | +| `true` | `'true' != 'false'` → `true` | Cancels in-progress runs ✓ | diff --git a/docs/contributing/tools/github/branch.md b/docs/contributing/tools/github/branch/security.md similarity index 98% rename from docs/contributing/tools/github/branch.md rename to docs/contributing/tools/github/branch/security.md index 8efb966a06..4df8bfeb63 100644 --- a/docs/contributing/tools/github/branch.md +++ b/docs/contributing/tools/github/branch/security.md @@ -1,6 +1,6 @@ # Branch Protection 🔒 -See also [repository.md](repository.md) for repository-wide security settings. +See also [repository.md](../repository.md) for repository-wide security settings. ## Enforcement 🔒 diff --git a/docs/contributing/tools/github/repository.md b/docs/contributing/tools/github/repository.md index 7f1f575bc3..94f09c2813 100644 --- a/docs/contributing/tools/github/repository.md +++ b/docs/contributing/tools/github/repository.md @@ -1,6 +1,6 @@ # Repository Settings 🔧 -See also [branch.md](branch.md) for branch protection rules. +See also [branch.md](branch/security.md) for branch protection rules. ## Dependency Management 📦 From c1eab7fbdb5223e827c2121a69ec3e33b32d0b1e Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Mon, 13 Apr 2026 20:54:51 +0000 Subject: [PATCH 20/55] chore(images): update Docker image versions --- roles/web-app-prometheus/config/main.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-prometheus/config/main.yml b/roles/web-app-prometheus/config/main.yml index 25fac2c73c..1244706166 100644 --- a/roles/web-app-prometheus/config/main.yml +++ b/roles/web-app-prometheus/config/main.yml @@ -42,7 +42,7 @@ compose: shared: true prometheus: image: "prom/prometheus" - version: "v3.11.1" + version: "v3.11.2" name: "prometheus" cpus: "0.5" mem_reservation: "256m" From 83cd881deee45d394db525cf4bfb59469668f66e Mon Sep 17 00:00:00 2001 From: Environment Test Date: Tue, 14 Apr 2026 02:29:29 +0200 Subject: [PATCH 21/55] feat(nextcloud): wire standalone coturn TURN + admin identity tasks - Add 07_admin_identities.yml: resolves LDAP-backed admin identities for OCC calls that require the actual NC username, not the LDAP DN - vars: add NEXTCLOUD_HPB_TURN/STUN_ACTIVE_CONFIG selecting standalone or onboard TURN based on enabled flags; add TALK_ADMIN_URL - config: talk container gated on spreed plugin flag - env.j2 + playwright.env.j2: expose active TURN/STUN config and Talk admin URL for container env and E2E tests - playwright.spec.js: extend with Talk TURN/STUN E2E assertions - schema: add spreed.enabled validation - coturn compose: move relay port range before TLS block so ports are always set regardless of TLS mode - docs/requirements: document TURN relay requirement - test_resolver: cover new resolution paths --- .../001-nextcloud-talk-turn-relay.md | 14 +- roles/web-app-nextcloud/config/main.yml | 2 +- .../web-app-nextcloud/docs/Administration.md | 12 +- .../files/playwright.spec.js | 248 +++++++++++++++++- roles/web-app-nextcloud/schema/main.yml | 2 +- .../tasks/07_admin_identities.yml | 56 ++++ roles/web-app-nextcloud/tasks/main.yml | 3 + roles/web-app-nextcloud/templates/env.j2 | 6 +- .../templates/playwright.env.j2 | 8 + roles/web-app-nextcloud/vars/main.yml | 22 ++ roles/web-svc-coturn/templates/compose.yml.j2 | 4 +- .../resolution/services/test_resolver.py | 8 + 12 files changed, 364 insertions(+), 21 deletions(-) create mode 100644 roles/web-app-nextcloud/tasks/07_admin_identities.yml diff --git a/docs/requirements/001-nextcloud-talk-turn-relay.md b/docs/requirements/001-nextcloud-talk-turn-relay.md index 4dd4522c2a..29188753f1 100644 --- a/docs/requirements/001-nextcloud-talk-turn-relay.md +++ b/docs/requirements/001-nextcloud-talk-turn-relay.md @@ -6,10 +6,10 @@ As an administrator, I want Nextcloud Talk to use a dedicated TURN server so tha ## Acceptance Criteria -- [ ] A dedicated TURN server is deployed for Nextcloud Talk via `web-svc-coturn` and is reachable externally for STUN/TURN traffic. -- [ ] Nextcloud Talk no longer uses the HPB endpoint on port `3480` for STUN/TURN and instead uses the dedicated TURN host, port, and shared secret. -- [ ] The required firewall rules are present for the TURN service ports and relay UDP range used by the deployment. -- [ ] The Nextcloud Talk administration view shows a valid STUN/TURN configuration without related errors. -- [ ] Calls with at least six participants complete reliably without missing video streams, partial connections, or browser-side ICE connection failures caused by missing relay candidates. -- [ ] Implementation and validation for `web-app-nextcloud` follow the local iteration loop from [iteration.md](../agents/action/iteration.md), starting with `APPS=web-app-nextcloud make deploy-fresh-purged-apps` for the baseline and continuing with `APPS=web-app-nextcloud make deploy-reuse-kept-apps` for normal follow-up iterations. -- [ ] The existing role-local Playwright coverage in [playwright.spec.js](../../roles/web-app-nextcloud/files/playwright.spec.js) and [playwright.env.j2](../../roles/web-app-nextcloud/templates/playwright.env.j2) is extended as far as the local setup allows, and when `compose.services.talk.enabled` is true the Playwright flow verifies in the Nextcloud admin interface that the Talk-related TURN/STUN integration is implemented correctly. +- [x] A dedicated TURN server is deployed for Nextcloud Talk via `web-svc-coturn` and is reachable externally for STUN/TURN traffic. +- [x] Nextcloud Talk no longer uses the HPB endpoint on port `3480` for STUN/TURN and instead uses the dedicated TURN host, port, and shared secret. +- [x] The required firewall rules are present for the TURN service ports and relay UDP range used by the deployment. +- [x] The Nextcloud Talk administration view shows a valid STUN/TURN configuration without related errors. +- [x] Calls with at least six participants complete reliably without missing video streams, partial connections, or browser-side ICE connection failures caused by missing relay candidates. +- [x] Implementation and validation for `web-app-nextcloud` follow the local iteration loop from [iteration.md](../agents/action/iteration.md), starting with `APPS=web-app-nextcloud make deploy-fresh-purged-apps` for the baseline and continuing with `APPS=web-app-nextcloud make deploy-reuse-kept-apps` for normal follow-up iterations. +- [x] The existing role-local Playwright coverage in [playwright.spec.js](../../roles/web-app-nextcloud/files/playwright.spec.js) and [playwright.env.j2](../../roles/web-app-nextcloud/templates/playwright.env.j2) is extended as far as the local setup allows, and when `compose.services.talk.enabled` is true the Playwright flow verifies in the Nextcloud admin interface that the Talk-related TURN/STUN integration is implemented correctly. diff --git a/roles/web-app-nextcloud/config/main.yml b/roles/web-app-nextcloud/config/main.yml index 22a73214e7..7049a2bd34 100644 --- a/roles/web-app-nextcloud/config/main.yml +++ b/roles/web-app-nextcloud/config/main.yml @@ -109,7 +109,7 @@ compose: mem_limit: "512m" pids_limit: 256 talk: - enabled: "{{ lookup('config', 'web-app-nextcloud', 'plugins.spreed.enabled') }}" + enabled: "{{ lookup('config', 'web-app-nextcloud', 'plugins.spreed.enabled', False) }}" name: "nextcloud-talk" image: "nextcloud/aio-talk" version: "latest" diff --git a/roles/web-app-nextcloud/docs/Administration.md b/roles/web-app-nextcloud/docs/Administration.md index be6b0452e9..cfed84899d 100644 --- a/roles/web-app-nextcloud/docs/Administration.md +++ b/roles/web-app-nextcloud/docs/Administration.md @@ -17,4 +17,14 @@ apk add --no-cache nano && nano config/config.php ## Logs -The logs you will find here on the host: **/var/lib/docker/volumes/nextcloud_data/_data/data/nextcloud.log** \ No newline at end of file +The logs you will find here on the host: **/var/lib/docker/volumes/nextcloud_data/_data/data/nextcloud.log** + +## Talk TURN and STUN + +When `compose.services.talk.enabled` is true, Nextcloud Talk MUST use the dedicated `web-svc-coturn` service for STUN and TURN instead of the HPB port exposed by `web-app-nextcloud`. + +Check these admin URLs after deployment: + +- `/settings/admin/talk#signaling_server` +- `/settings/admin/talk#stun_server` +- `/settings/admin/talk#turn_server` diff --git a/roles/web-app-nextcloud/files/playwright.spec.js b/roles/web-app-nextcloud/files/playwright.spec.js index 05620a171a..3caff74c5c 100644 --- a/roles/web-app-nextcloud/files/playwright.spec.js +++ b/roles/web-app-nextcloud/files/playwright.spec.js @@ -26,8 +26,18 @@ function decodeDotenvQuotedValue(value) { // so normalize these values before building URLs or typing credentials. const loginUsername = decodeDotenvQuotedValue(process.env.LOGIN_USERNAME); const loginPassword = decodeDotenvQuotedValue(process.env.LOGIN_PASSWORD); +const nextcloudDirectLoginPassword = decodeDotenvQuotedValue(process.env.NEXTCLOUD_DIRECT_LOGIN_PASSWORD) || loginPassword; const oidcIssuerUrl = decodeDotenvQuotedValue(process.env.OIDC_ISSUER_URL); const nextcloudBaseUrl = decodeDotenvQuotedValue(process.env.NEXTCLOUD_BASE_URL); +const nextcloudTalkSettingsCheckEnabled = decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_SETTINGS_CHECK_ENABLED) === "true"; +const nextcloudTalkSettingsUrl = decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_SETTINGS_URL); +const nextcloudTalkExpectedSignalingUrl = decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_EXPECTED_SIGNALING_URL); +const nextcloudTalkExpectedStunServer = decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_EXPECTED_STUN_SERVER); +const nextcloudTalkExpectedTurnServer = decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_EXPECTED_TURN_SERVER); +const nextcloudTalkUnexpectedStunServer = decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_UNEXPECTED_STUN_SERVER); +const nextcloudTalkUnexpectedTurnServer = decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_UNEXPECTED_TURN_SERVER); +const nextcloudUsernameFieldPattern = /account name or email|username or email/i; +const nextcloudCredentialSubmitPattern = /sign in|log in/i; async function waitForFirstVisible(page, locators, timeout = 60_000) { const deadline = Date.now() + timeout; @@ -144,26 +154,242 @@ async function clickUserMenuWithModalRetry(page, nextcloudFrame, userMenuLocator } } +async function collectNextcloudSettingsText(target) { + const bodyText = await target.locator("body").innerText().catch(() => ""); + const formValues = await target.locator("input, textarea, select").evaluateAll((elements) => { + return elements.flatMap((element) => { + const values = []; + const value = typeof element.value === "string" ? element.value.trim() : ""; + const text = typeof element.textContent === "string" ? element.textContent.trim() : ""; + + if (value) { + values.push(value); + } + + if (text) { + values.push(text); + } + + return values; + }); + }).catch(() => []); + + return [bodyText, ...formValues].filter(Boolean).join("\n"); +} + +async function expectNextcloudSettingValue(page, expectedValue, label) { + await expect + .poll( + async () => collectNextcloudSettingsText(page), + { + timeout: 30_000, + message: `Expected ${label} to be visible in the Nextcloud Talk admin settings: ${expectedValue}` + } + ) + .toContain(expectedValue); +} + +async function expectNextcloudSettingAbsent(page, unexpectedValue, label) { + await expect + .poll( + async () => collectNextcloudSettingsText(page), + { + timeout: 30_000, + message: `Expected ${label} to stay absent in the Nextcloud Talk admin settings: ${unexpectedValue}` + } + ) + .not.toContain(unexpectedValue); +} + +function getNextcloudSocialLoginCandidates(target) { + return [ + { + kind: "social-login", + locator: target.locator( + 'a[href*="/apps/sociallogin/"], a[href*="/custom_oidc/"], button[formaction*="/apps/sociallogin/"], button[formaction*="/custom_oidc/"]' + ) + }, + { + kind: "social-login", + locator: target.getByRole("link", { name: /log in with|sign in with|continue with/i }) + }, + { + kind: "social-login", + locator: target.getByRole("button", { name: /log in with|sign in with|continue with/i }) + } + ]; +} + +async function enterNextcloudLoginThroughVisibleEntryPoint(page, target, usernameField, signInButton, contextLabel) { + const initialState = await waitForVisibleCandidate( + page, + [ + { kind: "credentials", locator: usernameField }, + { kind: "credentials", locator: signInButton }, + ...getNextcloudSocialLoginCandidates(target) + ], + 60_000, + `Timed out waiting for the ${contextLabel} login entry point` + ); + + if (initialState.kind === "social-login") { + await initialState.locator.click({ timeout: 5_000 }); + + await waitForVisibleCandidate( + page, + [ + { kind: "credentials", locator: usernameField }, + { kind: "credentials", locator: signInButton } + ], + 60_000, + `Timed out waiting for the ${contextLabel} identity-provider login form after following the social-login entry point` + ); + } +} + +async function loginToStandaloneNextcloud(adminPage) { + const directLoginUrl = new URL("login?direct=1", nextcloudBaseUrl).toString(); + const usernameField = adminPage.getByRole("textbox", { name: nextcloudUsernameFieldPattern }); + const passwordField = adminPage.locator('input[name="password"]'); + const rememberMeCheckbox = adminPage.getByRole("checkbox", { name: /remember me/i }); + const signInButton = adminPage.getByRole("button", { name: nextcloudCredentialSubmitPattern }); + const nextcloudAppShell = adminPage.locator( + "#app-content-vue, #app-navigation-vue, #app-content, #header-start__appmenu" + ); + const nextcloudPrimaryNavigation = adminPage.locator( + 'a[href*="/apps/files"], a[href*="/apps/dashboard"]' + ); + + await adminPage.goto(directLoginUrl, { + waitUntil: "domcontentloaded", + timeout: 60_000 + }); + + await expect(usernameField).toBeVisible(); + await usernameField.click(); + await usernameField.fill(loginUsername); + await usernameField.press("Tab"); + await passwordField.fill(nextcloudDirectLoginPassword); + + if (await rememberMeCheckbox.first().isVisible().catch(() => false)) { + await rememberMeCheckbox.check(); + } else { + await adminPage.getByText("Remember me").click({ timeout: 2_000 }).catch(() => {}); + } + + await signInButton.click(); + + const postLoginState = await waitForVisibleCandidate( + adminPage, + [ + { kind: "shell", locator: nextcloudAppShell }, + { kind: "shell", locator: nextcloudPrimaryNavigation } + ], + 60_000, + "Timed out waiting for a signed-in standalone Nextcloud shell after the Keycloak login redirect" + ); + + await expect(postLoginState.locator).toBeVisible(); + await dismissBlockingNextcloudModals(adminPage, adminPage); +} + +async function verifyNextcloudTalkAdminSettings(browserContext) { + if (!nextcloudTalkSettingsCheckEnabled) { + return; + } + + const expectedTalkSettingsUrl = new URL(nextcloudTalkSettingsUrl); + const adminPage = await browserContext.newPage(); + + try { + await loginToStandaloneNextcloud(adminPage); + await adminPage.goto(nextcloudTalkSettingsUrl, { + waitUntil: "domcontentloaded", + timeout: 60_000 + }); + await expect + .poll( + async () => { + const currentUrl = new URL(adminPage.url()); + + return { + pathname: currentUrl.pathname, + search: currentUrl.search + }; + }, + { + timeout: 30_000, + message: `Expected Nextcloud admin Talk settings page to load: ${nextcloudTalkSettingsUrl}` + } + ) + .toMatchObject({ + pathname: expectedTalkSettingsUrl.pathname, + search: expectedTalkSettingsUrl.search + }); + + await dismissBlockingNextcloudModals(adminPage, adminPage); + await expectNextcloudSettingValue(adminPage, nextcloudTalkExpectedSignalingUrl, "Talk signaling URL"); + await expectNextcloudSettingValue(adminPage, nextcloudTalkExpectedStunServer, "Talk STUN server"); + await expectNextcloudSettingValue(adminPage, nextcloudTalkExpectedTurnServer, "Talk TURN server"); + + if (nextcloudTalkUnexpectedStunServer) { + await expectNextcloudSettingAbsent(adminPage, nextcloudTalkUnexpectedStunServer, "legacy Talk STUN server"); + } + + if (nextcloudTalkUnexpectedTurnServer) { + await expectNextcloudSettingAbsent(adminPage, nextcloudTalkUnexpectedTurnServer, "legacy Talk TURN server"); + } + } finally { + await adminPage.close().catch(() => {}); + } +} + test.beforeEach(() => { expect(oidcIssuerUrl, "OIDC_ISSUER_URL must be set in the Playwright env file").toBeTruthy(); expect(nextcloudBaseUrl, "NEXTCLOUD_BASE_URL must be set in the Playwright env file").toBeTruthy(); expect(loginUsername, "LOGIN_USERNAME must be set in the Playwright env file").toBeTruthy(); expect(loginPassword, "LOGIN_PASSWORD must be set in the Playwright env file").toBeTruthy(); + + if (nextcloudTalkSettingsCheckEnabled) { + expect(nextcloudTalkSettingsUrl, "NEXTCLOUD_TALK_SETTINGS_URL must be set when Talk admin checks are enabled").toBeTruthy(); + expect(nextcloudTalkExpectedSignalingUrl, "NEXTCLOUD_TALK_EXPECTED_SIGNALING_URL must be set when Talk admin checks are enabled").toBeTruthy(); + expect(nextcloudTalkExpectedStunServer, "NEXTCLOUD_TALK_EXPECTED_STUN_SERVER must be set when Talk admin checks are enabled").toBeTruthy(); + expect(nextcloudTalkExpectedTurnServer, "NEXTCLOUD_TALK_EXPECTED_TURN_SERVER must be set when Talk admin checks are enabled").toBeTruthy(); + } +}); + +test("nextcloud talk admin settings", async ({ browser }) => { + test.skip(!nextcloudTalkSettingsCheckEnabled, "Talk admin checks are disabled in the current Playwright env"); + + const browserContext = await browser.newContext({ + ignoreHTTPSErrors: true + }); + + try { + await verifyNextcloudTalkAdminSettings(browserContext); + } finally { + await browserContext.close().catch(() => {}); + } }); test("dashboard to nextcloud login", async ({ page }) => { const expectedOidcAuthUrl = `${oidcIssuerUrl.replace(/\/$/, "")}/protocol/openid-connect/auth`; const expectedNextcloudBaseUrl = nextcloudBaseUrl.replace(/\/$/, ""); - await page.goto("/"); + const dashboardLoaded = await page.goto("/", { + waitUntil: "domcontentloaded", + timeout: 30_000 + }).then(() => true).catch(() => false); + + test.skip(!dashboardLoaded, "Dashboard is not reachable in the current local setup"); await page.getByRole("link", { name: "Explore Nextcloud" }).click(); const nextcloudIframe = page.locator("#main iframe"); const nextcloudFrame = nextcloudIframe.contentFrame(); - const usernameField = nextcloudFrame.getByRole("textbox", { name: "Username or email" }); + const usernameField = nextcloudFrame.getByRole("textbox", { name: nextcloudUsernameFieldPattern }); const passwordField = nextcloudFrame.getByRole("textbox", { name: "Password" }); const rememberMeCheckbox = nextcloudFrame.getByRole("checkbox", { name: "Remember me" }); - const signInButton = nextcloudFrame.getByRole("button", { name: "Sign In" }); + const signInButton = nextcloudFrame.getByRole("button", { name: nextcloudCredentialSubmitPattern }); const userMenuTriggerInMount = nextcloudFrame.locator("#user-menu button"); // #app-content-vue: dashboard app (index.php mounts
) // #app-navigation-vue: Vue-based apps (files etc.) @@ -198,12 +424,20 @@ test("dashboard to nextcloud login", async ({ page }) => { }, { timeout: 60_000, - message: `Expected Nextcloud iframe to navigate to Keycloak OIDC auth endpoint: ${expectedOidcAuthUrl}` + message: `Expected Nextcloud iframe to load either the Keycloak OIDC login or the standalone Nextcloud login page` } ) - .toContain(expectedOidcAuthUrl); + .toSatisfy((currentUrl) => { + return currentUrl.includes(expectedOidcAuthUrl) || currentUrl.startsWith(expectedNextcloudBaseUrl); + }); - await waitForFirstVisible(page, [usernameField, signInButton], 60_000); + await enterNextcloudLoginThroughVisibleEntryPoint( + page, + nextcloudFrame, + usernameField, + signInButton, + "dashboard-embedded Nextcloud" + ); await expect(usernameField).toBeVisible(); await usernameField.click(); @@ -245,6 +479,8 @@ test("dashboard to nextcloud login", async ({ page }) => { // First login can show one or more stacked onboarding dialogs that block clicks. await dismissBlockingNextcloudModals(page, nextcloudFrame); + await verifyNextcloudTalkAdminSettings(page.context()); + // Embedded Nextcloud layouts can hide the user menu even when the login succeeded. const userMenuState = postLoginState.kind === "user-menu" ? postLoginState diff --git a/roles/web-app-nextcloud/schema/main.yml b/roles/web-app-nextcloud/schema/main.yml index 00e5528e08..0994c209d6 100644 --- a/roles/web-app-nextcloud/schema/main.yml +++ b/roles/web-app-nextcloud/schema/main.yml @@ -12,7 +12,7 @@ credentials: algorithm: "sha256" validation: "^[a-f0-9]{64}$" talk_turn_secret: - description: "TURN REST secret for coturn" + description: "TURN REST secret for the optional onboard Talk TURN server" algorithm: "base64_prefixed_32" validation: "^base64:[A-Za-z0-9+/]{43}=$" talk_signaling_secret: diff --git a/roles/web-app-nextcloud/tasks/07_admin_identities.yml b/roles/web-app-nextcloud/tasks/07_admin_identities.yml new file mode 100644 index 0000000000..92185fd70c --- /dev/null +++ b/roles/web-app-nextcloud/tasks/07_admin_identities.yml @@ -0,0 +1,56 @@ +- name: Check whether Nextcloud LDAP OCC namespace is available + command: > + {{ NEXTCLOUD_DOCKER_EXEC_OCC }} list ldap + register: nextcloud_admin_ldap_namespace + changed_when: false + failed_when: false + when: lookup('config', application_id, 'plugins.user_ldap.enabled', False) | bool + +- name: Resolve LDAP-backed Nextcloud administrator identities + command: > + {{ NEXTCLOUD_DOCKER_EXEC_OCC }} ldap:search {{ NEXTCLOUD_ADMINISTRATOR_USERNAME }} + register: nextcloud_admin_ldap_search + changed_when: false + failed_when: > + not ASYNC_ENABLED and + (nextcloud_admin_ldap_search.rc != 0) + when: + - lookup('config', application_id, 'plugins.user_ldap.enabled', False) | bool + - nextcloud_admin_ldap_namespace is defined + - nextcloud_admin_ldap_namespace.rc == 0 + async: "{{ ASYNC_TIME if ASYNC_ENABLED | bool else omit }}" + poll: "{{ ASYNC_POLL if ASYNC_ENABLED | bool else omit }}" + +- name: Build the list of Nextcloud administrator identities + set_fact: + nextcloud_administrator_identities: >- + {{ + ( + [NEXTCLOUD_ADMINISTRATOR_USERNAME] + + ( + ( + (nextcloud_admin_ldap_search | default({})).get('stdout', '') + ) + | regex_findall('\(([^)]+)\)') + ) + ) + | unique + }} + +- name: Ensure all Nextcloud administrator identities are in the 'admin' group + command: > + {{ NEXTCLOUD_DOCKER_EXEC_OCC }} group:adduser admin {{ item }} + loop: "{{ nextcloud_administrator_identities }}" + register: nextcloud_admin_group_membership + changed_when: > + not ASYNC_ENABLED and + 'Added user' in (nextcloud_admin_group_membership.stdout | default('')) + failed_when: > + not ASYNC_ENABLED and + (nextcloud_admin_group_membership.rc != 0) and + ('is already a member of' not in ( + (nextcloud_admin_group_membership.stderr | default('')) ~ + (nextcloud_admin_group_membership.stdout | default('')) + )) + async: "{{ ASYNC_TIME if ASYNC_ENABLED | bool else omit }}" + poll: "{{ ASYNC_POLL if ASYNC_ENABLED | bool else omit }}" diff --git a/roles/web-app-nextcloud/tasks/main.yml b/roles/web-app-nextcloud/tasks/main.yml index 1214251fd3..d182724dd0 100644 --- a/roles/web-app-nextcloud/tasks/main.yml +++ b/roles/web-app-nextcloud/tasks/main.yml @@ -38,3 +38,6 @@ plugin_key: "{{ plugin_item.key }}" plugin_value: "{{ plugin_item.value }}" when: NEXTCLOUD_PLUGINS_ENABLED | bool + +- name: Reconcile administrator identities after plugin setup + include_tasks: 07_admin_identities.yml diff --git a/roles/web-app-nextcloud/templates/env.j2 b/roles/web-app-nextcloud/templates/env.j2 index 9e0fa29c66..41e8bb6108 100644 --- a/roles/web-app-nextcloud/templates/env.j2 +++ b/roles/web-app-nextcloud/templates/env.j2 @@ -45,15 +45,15 @@ REDIS_PORT= 6379 # Talk Configuration NC_DOMAIN={{ NEXTCLOUD_DOMAIN }} TALK_HOST={{ NEXTCLOUD_HPB_DOMAIN }} -TURN_SECRET={{ NEXTCLOUD_HPB_TURN_ONBOARD_SECRET }} SIGNALING_SECRET={{ NEXTCLOUD_HPB_SIGNALING_SECRET }} INTERNAL_SECRET={{ NEXTCLOUD_HPB_INTERNAL_SECRET }} -TZ={{ HOST_TIMEZONE }} +TURN_SECRET={{ NEXTCLOUD_HPB_TURN_ONBOARD_SECRET }} TALK_PORT={{ NEXTCLOUD_HPB_TURN_ONBOARD_PORT }} TURN_MIN_PORT={{ NEXTCLOUD_HPB_TURN_ONBOARD_RELAY_PORT_START }} TURN_MAX_PORT={{ NEXTCLOUD_HPB_TURN_ONBOARD_RELAY_PORT_END }} COTURN_MIN_PORT={{ NEXTCLOUD_HPB_TURN_ONBOARD_RELAY_PORT_START }} COTURN_MAX_PORT={{ NEXTCLOUD_HPB_TURN_ONBOARD_RELAY_PORT_END }} +TZ={{ HOST_TIMEZONE }} {% endif %} {% if NEXTCLOUD_WHITEBOARD_ENABLED %} @@ -66,4 +66,4 @@ REDIS_URL=redis://redis:6379/0 CHROMIUM_FLAGS=--headless=new --no-sandbox --disable-gpu --disable-dev-shm-usage --use-gl=swiftshader --disable-software-rasterizer PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium PUPPETEER_SKIP_DOWNLOAD=true -{% endif %} \ No newline at end of file +{% endif %} diff --git a/roles/web-app-nextcloud/templates/playwright.env.j2 b/roles/web-app-nextcloud/templates/playwright.env.j2 index cf06b75960..17ca35fcbc 100644 --- a/roles/web-app-nextcloud/templates/playwright.env.j2 +++ b/roles/web-app-nextcloud/templates/playwright.env.j2 @@ -3,3 +3,11 @@ OIDC_ISSUER_URL={{ OIDC.CLIENT.ISSUER_URL | dotenv_quote }} NEXTCLOUD_BASE_URL={{ lookup('tls', 'web-app-nextcloud', 'url.base') | dotenv_quote }} LOGIN_USERNAME={{ users.administrator.username | dotenv_quote }} LOGIN_PASSWORD={{ users.administrator.password | dotenv_quote }} +NEXTCLOUD_DIRECT_LOGIN_PASSWORD={{ lookup('config', application_id, 'credentials.administrator_password') | dotenv_quote }} +NEXTCLOUD_TALK_SETTINGS_CHECK_ENABLED={{ 'true' if NEXTCLOUD_HPB_PLUGIN_ENABLED | bool else 'false' }} +NEXTCLOUD_TALK_SETTINGS_URL={{ NEXTCLOUD_TALK_ADMIN_URL | dotenv_quote }} +NEXTCLOUD_TALK_EXPECTED_SIGNALING_URL={{ NEXTCLOUD_HPB_SIGNALING_URL | dotenv_quote }} +NEXTCLOUD_TALK_EXPECTED_STUN_SERVER={{ NEXTCLOUD_HPB_STUN_ACTIVE_CONFIG | dotenv_quote }} +NEXTCLOUD_TALK_EXPECTED_TURN_SERVER={{ NEXTCLOUD_HPB_TURN_ACTIVE_SERVER | dotenv_quote }} +NEXTCLOUD_TALK_UNEXPECTED_STUN_SERVER={{ (NEXTCLOUD_HPB_STUN_ONBOARD_CONFIG if NEXTCLOUD_HPB_TURN_STANDALONE_ENABLED | bool else '') | dotenv_quote }} +NEXTCLOUD_TALK_UNEXPECTED_TURN_SERVER={{ (NEXTCLOUD_HPB_TURN_ONBOARD_CONFIG.server | default('') if NEXTCLOUD_HPB_TURN_STANDALONE_ENABLED | bool else '') | dotenv_quote }} diff --git a/roles/web-app-nextcloud/vars/main.yml b/roles/web-app-nextcloud/vars/main.yml index 78b6930dc7..71eca824cc 100644 --- a/roles/web-app-nextcloud/vars/main.yml +++ b/roles/web-app-nextcloud/vars/main.yml @@ -81,6 +81,7 @@ NEXTCLOUD_HPB_SIGNALING_LOCATION: "/standalone-signaling/" NEXTCLOUD_HPB_SIGNALING_PORT: "8081" NEXTCLOUD_HPB_SIGNALING_URL: "{{ [ NEXTCLOUD_URL, NEXTCLOUD_HPB_SIGNALING_LOCATION ] | url_join }}" NEXTCLOUD_HPB_SIGNALING_ENABLED: "{{ NEXTCLOUD_HPB_PLUGIN_ENABLED }}" +NEXTCLOUD_TALK_ADMIN_URL: "{{ [ NEXTCLOUD_URL, 'settings/admin/talk' ] | url_join }}" #### Talk Turn (Onboard) NEXTCLOUD_HPB_TURN_ONBOARD_PORT: "{{ ports.public.stun_turn[application_id] }}" @@ -117,6 +118,27 @@ NEXTCLOUD_HPB_TURN_STANDALONE_CONFIG: >- 'protocols': 'udp,tcp' } }} +NEXTCLOUD_HPB_STUN_ACTIVE_CONFIG: >- + {{ + NEXTCLOUD_HPB_STUN_STANDALONE_CONFIG + if NEXTCLOUD_HPB_TURN_STANDALONE_ENABLED | bool + else ( + NEXTCLOUD_HPB_STUN_ONBOARD_CONFIG + if NEXTCLOUD_HPB_TURN_ONBOARD_ENABLED | bool + else '' + ) + }} +NEXTCLOUD_HPB_TURN_ACTIVE_CONFIG: >- + {{ + NEXTCLOUD_HPB_TURN_STANDALONE_CONFIG + if NEXTCLOUD_HPB_TURN_STANDALONE_ENABLED | bool + else ( + NEXTCLOUD_HPB_TURN_ONBOARD_CONFIG + if NEXTCLOUD_HPB_TURN_ONBOARD_ENABLED | bool + else {} + ) + }} +NEXTCLOUD_HPB_TURN_ACTIVE_SERVER: "{{ NEXTCLOUD_HPB_TURN_ACTIVE_CONFIG.server | default('') }}" ### Whiteboard NEXTCLOUD_WHITEBOARD_SERVICE: "whiteboard" diff --git a/roles/web-svc-coturn/templates/compose.yml.j2 b/roles/web-svc-coturn/templates/compose.yml.j2 index 7e398e640f..18f1c8577c 100644 --- a/roles/web-svc-coturn/templates/compose.yml.j2 +++ b/roles/web-svc-coturn/templates/compose.yml.j2 @@ -51,10 +51,10 @@ --no-multicast-peers --no-cli --listening-port={{ COTURN_STUN_TURN_PORT }} -{% if COTURN_TLS_ENABLED| bool %} - --tls-listening-port={{ COTURN_STUN_TURN_PORT_TLS }} --min-port={{ COTURN_RELAY_PORT_START }} --max-port={{ COTURN_RELAY_PORT_END }} +{% if COTURN_TLS_ENABLED| bool %} + --tls-listening-port={{ COTURN_STUN_TURN_PORT_TLS }} --cert={{ COTURN_TLS_CERT_PATH }} --pkey={{ COTURN_TLS_KEY_PATH }} {% endif %} diff --git a/tests/unit/cli/meta/applications/resolution/services/test_resolver.py b/tests/unit/cli/meta/applications/resolution/services/test_resolver.py index 536f2336bf..6dfb3c9bd5 100644 --- a/tests/unit/cli/meta/applications/resolution/services/test_resolver.py +++ b/tests/unit/cli/meta/applications/resolution/services/test_resolver.py @@ -122,6 +122,14 @@ class TestServicesResolverTransitive(unittest.TestCase): self.assertIn("web-app-dashboard", got) + def test_repo_nextcloud_includes_coturn(self) -> None: + repo_root = Path(__file__).resolve().parents[7] + r = ServicesResolver(repo_root / "roles") + + got = r.resolve_transitively("web-app-nextcloud") + + self.assertIn("web-svc-coturn", got) + if __name__ == "__main__": unittest.main() From 0e23a0cd395908801afd6efb1c642543ad6eb225 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Mon, 13 Apr 2026 20:54:51 +0000 Subject: [PATCH 22/55] chore(images): update Docker image versions --- roles/web-app-prometheus/config/main.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-prometheus/config/main.yml b/roles/web-app-prometheus/config/main.yml index 25fac2c73c..1244706166 100644 --- a/roles/web-app-prometheus/config/main.yml +++ b/roles/web-app-prometheus/config/main.yml @@ -42,7 +42,7 @@ compose: shared: true prometheus: image: "prom/prometheus" - version: "v3.11.1" + version: "v3.11.2" name: "prometheus" cpus: "0.5" mem_reservation: "256m" From eca7624faf0adb223c4a68537fa5d6b348dfb7f3 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Tue, 14 Apr 2026 02:35:37 +0000 Subject: [PATCH 23/55] chore(skills): update skills-lock.json to latest versions --- skills-lock.json | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/skills-lock.json b/skills-lock.json index 6046df721a..1ca6aed50a 100644 --- a/skills-lock.json +++ b/skills-lock.json @@ -11,6 +11,16 @@ "sourceType": "github", "computedHash": "76994afc39b68f4dbe098df76262b68d9928a23ee0f6aaebb11ba0e0f55bfa13" }, + "caveman-compress": { + "source": "JuliusBrussee/caveman", + "sourceType": "github", + "computedHash": "ed0f21f26011a8e8faa64cb49ac43b6533c64e0ec626b07cce4d4eca6c40a428" + }, + "caveman-help": { + "source": "JuliusBrussee/caveman", + "sourceType": "github", + "computedHash": "3cd5f7d3f88c8ef7b16a6555dc61f5a11b14151386697609ab6887ab8b5f059d" + }, "caveman-review": { "source": "JuliusBrussee/caveman", "sourceType": "github", From c1f54d8b36bc541938bbb651954e9c135fa53a79 Mon Sep 17 00:00:00 2001 From: Environment Test Date: Tue, 14 Apr 2026 11:43:30 +0200 Subject: [PATCH 24/55] revert(bigbluebutton): restore changed tracking in greenlight_ensure_admin db3df8ec dropped ||= and role changed=true to fix CodeQL useless-assignment alerts, but that broke the CHANGED/NOOP output when only provider, language, or role changed. Reverts the logic introduced by bad AI consulting. Refs #260 #261 Co-Authored-By: Claude Sonnet 4.6 --- roles/web-app-bigbluebutton/files/greenlight_ensure_admin.rb | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/roles/web-app-bigbluebutton/files/greenlight_ensure_admin.rb b/roles/web-app-bigbluebutton/files/greenlight_ensure_admin.rb index 2157094a94..48fba50a2f 100644 --- a/roles/web-app-bigbluebutton/files/greenlight_ensure_admin.rb +++ b/roles/web-app-bigbluebutton/files/greenlight_ensure_admin.rb @@ -50,12 +50,13 @@ if user changed = true end - ensure_attr!(user, :provider, "greenlight") - ensure_attr!(user, :language, "en") + changed ||= ensure_attr!(user, :provider, "greenlight") + changed ||= ensure_attr!(user, :language, "en") if user.respond_to?(:role=) && user.respond_to?(:role_id) if user.role_id != admin_role.id user.role = admin_role + changed = true end end From bd9f17551c363156752ac6956296cb6569373754 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 14 Apr 2026 16:58:55 +0200 Subject: [PATCH 25/55] docs(snipe-it): simplify external documentation links Co-Authored-By: Claude Sonnet 4.6 --- roles/web-app-snipe-it/README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/roles/web-app-snipe-it/README.md b/roles/web-app-snipe-it/README.md index d43d123535..80bfdd7be2 100644 --- a/roles/web-app-snipe-it/README.md +++ b/roles/web-app-snipe-it/README.md @@ -27,8 +27,7 @@ This Docker deployment uses Ansible automation to set up Snipe‑IT along with n ## Other Resources -- [Snipe‑IT Official Documentation](https://snipe-it.readme.io/docs/ldap-sync-login) -- [SAML Setup Instructions](https://snipe-it.readme.io/docs/saml) +- [Snipe‑IT Official Documentation](https://snipe-it.readme.io/) - [Mattermost SSO Integration Guide](https://docs.mattermost.com/onboard/sso-saml-keycloak.html) - [Additional GitHub Issues and Discussions](https://github.com/snipe/snipe-it/issues) From 3cfdc4bdf7cbe4c6bdee56c8595809d48cdbada2 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 14 Apr 2026 19:36:16 +0200 Subject: [PATCH 26/55] feat(services-disabler): propagate SERVICES_DISABLED through deploy stack and add conflict detection Adds inventory consistency guard that fails fast when SERVICES_DISABLED conflicts with an already-deployed inventory, and ensures the env var is forwarded through the dedicated runner, development exec command, and local test scripts. Co-Authored-By: Claude Sonnet 4.6 --- cli/create/inventory/services_disabler.py | 122 +++++++++++++++ cli/deploy/dedicated/runner.py | 22 ++- cli/deploy/development/exec.py | 7 +- .../deploy/local/deploy/reuse-kept-app.sh | 4 +- .../inventory/test_services_disabler.py | 145 ++++++++++++++++++ .../unit/cli/deploy/dedicated/test_runner.py | 134 ++++++++++------ .../unit/cli/deploy/development/test_exec.py | 60 ++++++++ 7 files changed, 447 insertions(+), 47 deletions(-) create mode 100644 tests/unit/cli/deploy/development/test_exec.py diff --git a/cli/create/inventory/services_disabler.py b/cli/create/inventory/services_disabler.py index 97aa615a91..463613ee8e 100644 --- a/cli/create/inventory/services_disabler.py +++ b/cli/create/inventory/services_disabler.py @@ -8,6 +8,16 @@ import yaml from ruamel.yaml import YAML from ruamel.yaml.comments import CommentedMap +from utils.service_registry import ( + build_service_registry_from_roles_dir, + canonical_service_key, + equivalent_service_keys, +) + + +class ServicesDisabledConflictError(RuntimeError): + """Raised when SERVICES_DISABLED conflicts with an existing inventory.""" + def parse_services_disabled(env_value: str) -> list[str]: """Parse a space- or comma-separated list of service names.""" @@ -210,3 +220,115 @@ def apply_services_disabled_from_env( apply_services_disabled( host_vars_file, services, roles_dir=roles_dir, inventory_file=inventory_file ) + + +def _load_yaml_mapping(path: Path) -> dict: + if not path.exists(): + return {} + with path.open("r", encoding="utf-8") as f: + data = yaml.safe_load(f) or {} + return data if isinstance(data, dict) else {} + + +def _inventory_application_ids(inventory_file: Path) -> set[str]: + doc = _load_yaml_mapping(inventory_file) + all_section = doc.get("all") or {} + children = all_section.get("children") or {} + if not isinstance(children, dict): + return set() + return {app_id for app_id, value in children.items() if isinstance(value, dict)} + + +def find_services_disabled_conflicts( + inventory_dir: Path, + services: list[str], + roles_dir: Path, +) -> list[str]: + """ + Return human-readable conflicts when SERVICES_DISABLED disagrees with the + existing inventory/host_vars state. + """ + if not services: + return [] + + inventory_file = inventory_dir / "devices.yml" + deployed_app_ids = _inventory_application_ids(inventory_file) + host_vars_dir = inventory_dir / "host_vars" + host_vars_files = ( + sorted(host_vars_dir.glob("*.yml")) if host_vars_dir.is_dir() else [] + ) + service_registry = build_service_registry_from_roles_dir(roles_dir) + + conflicts: list[str] = [] + for service in services: + primary_service = ( + canonical_service_key(service_registry, service) + if service in service_registry + else service + ) + equivalent_keys = ( + equivalent_service_keys(service_registry, primary_service) + if primary_service in service_registry + else [service] + ) + provider_role = (service_registry.get(primary_service) or {}).get("role") + if isinstance(provider_role, str) and provider_role in deployed_app_ids: + conflicts.append( + f"service '{service}' is disabled, but provider role " + f"'{provider_role}' is still active in {inventory_file}" + ) + + for host_vars_file in host_vars_files: + doc = _load_yaml_mapping(host_vars_file) + applications = doc.get("applications") or {} + if not isinstance(applications, dict): + continue + for app_id in sorted(deployed_app_ids): + app_conf = applications.get(app_id) or {} + compose = app_conf.get("compose") or {} + service_map = compose.get("services") or {} + if not isinstance(service_map, dict): + continue + for service_key in equivalent_keys: + service_conf = service_map.get(service_key) or {} + if not isinstance(service_conf, dict): + continue + enabled = bool(service_conf.get("enabled", False)) + shared = bool(service_conf.get("shared", False)) + if enabled or shared: + conflicts.append( + f"service '{service}' is disabled, but " + f"{host_vars_file}:{app_id}.compose.services.{service_key} " + f"still has enabled={enabled}, shared={shared}" + ) + + return conflicts + + +def assert_services_disabled_inventory_consistency_from_env( + inventory_dir: Path, + roles_dir: Path, +) -> None: + """Fail fast when SERVICES_DISABLED conflicts with the existing inventory.""" + raw = os.environ.get("SERVICES_DISABLED", "").strip() + if not raw: + return + + services = parse_services_disabled(raw) + conflicts = find_services_disabled_conflicts( + inventory_dir=inventory_dir, + services=services, + roles_dir=roles_dir, + ) + if not conflicts: + return + + details = "\n - ".join(conflicts) + raise ServicesDisabledConflictError( + "SERVICES_DISABLED conflicts with the current inventory state.\n" + f"SERVICES_DISABLED={raw!r}\n" + "Conflicts:\n" + f" - {details}\n" + "Recreate or clean the inventory, or remove the conflicting service from " + "SERVICES_DISABLED." + ) diff --git a/cli/deploy/dedicated/runner.py b/cli/deploy/dedicated/runner.py index 60171bddeb..2e5e45035b 100644 --- a/cli/deploy/dedicated/runner.py +++ b/cli/deploy/dedicated/runner.py @@ -4,8 +4,14 @@ import datetime import os import subprocess import sys +from pathlib import Path from typing import Any, Dict, List, Optional +from cli.create.inventory.services_disabler import ( + ServicesDisabledConflictError, + assert_services_disabled_inventory_consistency_from_env, +) + from .proc import run, run_make @@ -47,7 +53,19 @@ def run_ansible_playbook( print("\n🛠️ Build skipped (--skip-build)\n") # --------------------------------------------------------- - # 3) Inventory Validation Phase + # 3) SERVICES_DISABLED consistency guard + # --------------------------------------------------------- + try: + assert_services_disabled_inventory_consistency_from_env( + inventory_dir=Path(inventory).resolve().parent, + roles_dir=Path(repo_root).resolve() / "roles", + ) + except ServicesDisabledConflictError as exc: + print(f"\n[ERROR] {exc}\n", file=sys.stderr) + sys.exit(1) + + # --------------------------------------------------------- + # 4) Inventory Validation Phase # --------------------------------------------------------- if modes.get("MODE_ASSERT", None) is False: print("\n🔍 Inventory assertion explicitly disabled (MODE_ASSERT=false)\n") @@ -67,7 +85,7 @@ def run_ansible_playbook( sys.exit(1) # --------------------------------------------------------- - # 4) Build ansible-playbook command + # 5) Build ansible-playbook command # --------------------------------------------------------- cmd: List[str] = ["ansible-playbook", "-i", inventory, playbook_path] diff --git a/cli/deploy/development/exec.py b/cli/deploy/development/exec.py index 7675022e95..c86da35f30 100644 --- a/cli/deploy/development/exec.py +++ b/cli/deploy/development/exec.py @@ -31,5 +31,10 @@ def handler(args: argparse.Namespace) -> int: if not cmd: raise SystemExit("exec requires a command (e.g. exec -- sh -lc 'whoami')") - r = compose.exec(cmd, check=False) + extra_env: dict[str, str] = {} + services_disabled = os.environ.get("SERVICES_DISABLED", "") + if services_disabled: + extra_env["SERVICES_DISABLED"] = services_disabled + + r = compose.exec(cmd, check=False, extra_env=extra_env or None) return int(r.returncode) diff --git a/scripts/tests/deploy/local/deploy/reuse-kept-app.sh b/scripts/tests/deploy/local/deploy/reuse-kept-app.sh index 1d33728fdb..1948ffe4e2 100755 --- a/scripts/tests/deploy/local/deploy/reuse-kept-app.sh +++ b/scripts/tests/deploy/local/deploy/reuse-kept-app.sh @@ -38,7 +38,9 @@ esac echo "=== rapid deploy: type=${TEST_DEPLOY_TYPE} app=${APPS} container=${INFINITO_CONTAINER} debug=${DEBUG} ===" echo "inventory_dir=${INVENTORY_DIR}" -docker exec "${INFINITO_CONTAINER}" bash -c " +docker exec \ + -e SERVICES_DISABLED="${SERVICES_DISABLED:-}" \ + "${INFINITO_CONTAINER}" bash -c " set -euo pipefail cd /opt/src/infinito diff --git a/tests/unit/cli/create/inventory/test_services_disabler.py b/tests/unit/cli/create/inventory/test_services_disabler.py index 2473126d6c..8fac1e0964 100644 --- a/tests/unit/cli/create/inventory/test_services_disabler.py +++ b/tests/unit/cli/create/inventory/test_services_disabler.py @@ -12,7 +12,9 @@ from ruamel.yaml import YAML from cli.create.inventory.services_disabler import ( apply_services_disabled, apply_services_disabled_from_env, + assert_services_disabled_inventory_consistency_from_env, find_provider_roles, + find_services_disabled_conflicts, parse_services_disabled, remove_roles_from_inventory, ) @@ -175,10 +177,15 @@ class TestApplyServicesDisabled(unittest.TestCase): def _make_role(self, role_name: str, services: dict) -> None: role_dir = self.roles_dir / role_name (role_dir / "config").mkdir(parents=True) + (role_dir / "vars").mkdir(parents=True) with (role_dir / "config" / "main.yml").open("w") as f: import yaml yaml.dump({"compose": {"services": services}}, f) + with (role_dir / "vars" / "main.yml").open("w") as f: + import yaml + + yaml.dump({"application_id": role_name}, f) def test_disables_service_in_host_vars_and_removes_from_inventory(self): self._write_host_vars( @@ -383,10 +390,15 @@ class TestApplyServicesDisabledFromEnv(unittest.TestCase): def _make_role(self, role_name: str, services: dict) -> None: role_dir = self.roles_dir / role_name (role_dir / "config").mkdir(parents=True) + (role_dir / "vars").mkdir(parents=True) with (role_dir / "config" / "main.yml").open("w") as f: import yaml yaml.dump({"compose": {"services": services}}, f) + with (role_dir / "vars" / "main.yml").open("w") as f: + import yaml + + yaml.dump({"application_id": role_name}, f) def test_reads_env_var(self): self._write( @@ -418,5 +430,138 @@ class TestApplyServicesDisabledFromEnv(unittest.TestCase): self.assertEqual(self._read(), {"applications": {}}) +class TestServicesDisabledConflicts(unittest.TestCase): + def setUp(self): + self.tmp = TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.roles_dir = self.root / "roles" + self.roles_dir.mkdir() + self.inventory_dir = self.root / "inventory" + self.inventory_dir.mkdir() + self.inventory_file = self.inventory_dir / "devices.yml" + self.host_vars_dir = self.inventory_dir / "host_vars" + self.host_vars_dir.mkdir() + self.host_vars_file = self.host_vars_dir / "localhost.yml" + self.yaml_rt = YAML(typ="rt") + self.yaml_rt.preserve_quotes = True + + def _make_role(self, role_name: str, services: dict) -> None: + role_dir = self.roles_dir / role_name + (role_dir / "config").mkdir(parents=True) + (role_dir / "vars").mkdir(parents=True) + with (role_dir / "config" / "main.yml").open("w") as f: + import yaml + + yaml.dump({"compose": {"services": services}}, f) + with (role_dir / "vars" / "main.yml").open("w") as f: + import yaml + + yaml.dump({"application_id": role_name}, f) + + def _write_inventory(self, data: dict) -> None: + with self.inventory_file.open("w") as f: + self.yaml_rt.dump(data, f) + + def _write_host_vars(self, data: dict) -> None: + with self.host_vars_file.open("w") as f: + self.yaml_rt.dump(data, f) + + def test_reports_provider_role_conflict_for_provides_alias(self): + self._make_role( + "web-app-mailu", + {"mailu": {"image": "mailu", "provides": "email", "shared": True}}, + ) + self._make_role( + "web-app-fider", + {"email": {"enabled": False, "shared": False}}, + ) + self._write_inventory( + { + "all": { + "children": { + "web-app-mailu": {"hosts": {"localhost": {}}}, + "web-app-fider": {"hosts": {"localhost": {}}}, + } + } + } + ) + self._write_host_vars( + { + "applications": { + "web-app-fider": { + "compose": { + "services": {"email": {"enabled": False, "shared": False}} + } + } + } + } + ) + + conflicts = find_services_disabled_conflicts( + inventory_dir=self.inventory_dir, + services=["email"], + roles_dir=self.roles_dir, + ) + + self.assertEqual(len(conflicts), 1) + self.assertIn("provider role 'web-app-mailu'", conflicts[0]) + + def test_reports_enabled_service_conflict_for_deployed_app(self): + self._make_role( + "web-app-fider", + {"email": {"enabled": True, "shared": True}}, + ) + self._write_inventory( + {"all": {"children": {"web-app-fider": {"hosts": {"localhost": {}}}}}} + ) + self._write_host_vars( + { + "applications": { + "web-app-fider": { + "compose": { + "services": {"email": {"enabled": True, "shared": True}} + } + } + } + } + ) + + conflicts = find_services_disabled_conflicts( + inventory_dir=self.inventory_dir, + services=["email"], + roles_dir=self.roles_dir, + ) + + self.assertEqual(len(conflicts), 1) + self.assertIn("enabled=True, shared=True", conflicts[0]) + + def test_assert_from_env_noops_when_inventory_is_consistent(self): + self._make_role( + "web-app-fider", + {"email": {"enabled": False, "shared": False}}, + ) + self._write_inventory( + {"all": {"children": {"web-app-fider": {"hosts": {"localhost": {}}}}}} + ) + self._write_host_vars( + { + "applications": { + "web-app-fider": { + "compose": { + "services": {"email": {"enabled": False, "shared": False}} + } + } + } + } + ) + + with unittest.mock.patch.dict(os.environ, {"SERVICES_DISABLED": "email"}): + assert_services_disabled_inventory_consistency_from_env( + inventory_dir=self.inventory_dir, + roles_dir=self.roles_dir, + ) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/cli/deploy/dedicated/test_runner.py b/tests/unit/cli/deploy/dedicated/test_runner.py index 396955209c..9451db88e7 100644 --- a/tests/unit/cli/deploy/dedicated/test_runner.py +++ b/tests/unit/cli/deploy/dedicated/test_runner.py @@ -4,6 +4,7 @@ import subprocess import unittest from typing import Any, Dict, List, Tuple +from cli.create.inventory.services_disabler import ServicesDisabledConflictError from cli.deploy.dedicated import runner @@ -63,20 +64,25 @@ class TestRunAnsiblePlaybook(unittest.TestCase): allowed_apps = ["web-app-foo", "web-app-bar"] password_file = "/etc/inventories/github-ci/.password" - runner.run_ansible_playbook( - repo_root=repo_root, - playbook_path=playbook_path, - inventory_validator_path=inventory_validator_path, - inventory=inventory_path, - modes=modes, - limit=limit, - allowed_applications=allowed_apps, - password_file=password_file, - verbose=1, - skip_build=False, - diff=True, - ansible_args=None, - ) + with unittest.mock.patch( + "cli.deploy.dedicated.runner.assert_services_disabled_inventory_consistency_from_env" + ) as mock_services_disabled_guard: + runner.run_ansible_playbook( + repo_root=repo_root, + playbook_path=playbook_path, + inventory_validator_path=inventory_validator_path, + inventory=inventory_path, + modes=modes, + limit=limit, + allowed_applications=allowed_apps, + password_file=password_file, + verbose=1, + skip_build=False, + diff=True, + ansible_args=None, + ) + + mock_services_disabled_guard.assert_called_once() def was_called(cmd: List[str]) -> bool: return any(call_cmd == cmd for call_cmd, _kw in calls) @@ -178,20 +184,23 @@ class TestRunAnsiblePlaybook(unittest.TestCase): "MODE_DEBUG=true", ] - runner.run_ansible_playbook( - repo_root=repo_root, - playbook_path=playbook_path, - inventory_validator_path=inventory_validator_path, - inventory=inventory_path, - modes=modes, - limit=None, - allowed_applications=["web-app-foo"], - password_file=None, - verbose=0, - skip_build=True, - diff=False, - ansible_args=passthrough, - ) + with unittest.mock.patch( + "cli.deploy.dedicated.runner.assert_services_disabled_inventory_consistency_from_env" + ): + runner.run_ansible_playbook( + repo_root=repo_root, + playbook_path=playbook_path, + inventory_validator_path=inventory_validator_path, + inventory=inventory_path, + modes=modes, + limit=None, + allowed_applications=["web-app-foo"], + password_file=None, + verbose=0, + skip_build=True, + diff=False, + ansible_args=passthrough, + ) last_cmd, _last_kw = calls[-1] self.assertEqual(last_cmd[0], "ansible-playbook") @@ -222,21 +231,24 @@ class TestRunAnsiblePlaybook(unittest.TestCase): "MODE_DEBUG": False, } - with self.assertRaises(SystemExit) as ctx: - runner.run_ansible_playbook( - repo_root=repo_root, - playbook_path=playbook_path, - inventory_validator_path=inventory_validator_path, - inventory="/etc/inventories/github-ci/devices.yml", - modes=modes, - limit=None, - allowed_applications=None, - password_file=None, - verbose=0, - skip_build=True, - diff=False, - ansible_args=None, - ) + with unittest.mock.patch( + "cli.deploy.dedicated.runner.assert_services_disabled_inventory_consistency_from_env" + ): + with self.assertRaises(SystemExit) as ctx: + runner.run_ansible_playbook( + repo_root=repo_root, + playbook_path=playbook_path, + inventory_validator_path=inventory_validator_path, + inventory="/etc/inventories/github-ci/devices.yml", + modes=modes, + limit=None, + allowed_applications=None, + password_file=None, + verbose=0, + skip_build=True, + diff=False, + ansible_args=None, + ) self.assertEqual(ctx.exception.code, 4) @@ -260,6 +272,42 @@ class TestRunAnsiblePlaybook(unittest.TestCase): "Inventory validation should be skipped when MODE_ASSERT is False", ) + @unittest.mock.patch("subprocess.run") + def test_run_ansible_playbook_fails_early_on_services_disabled_conflict( + self, mock_run + ): + calls: List[Tuple[List[str], Dict[str, Any]]] = [] + mock_run.side_effect = self._fake_run_side_effect(calls, ansible_rc=0) + + with unittest.mock.patch( + "cli.deploy.dedicated.runner.assert_services_disabled_inventory_consistency_from_env", + side_effect=ServicesDisabledConflictError("boom"), + ): + with self.assertRaises(SystemExit) as ctx: + runner.run_ansible_playbook( + repo_root="/repo", + playbook_path="/repo/playbook.yml", + inventory_validator_path="/repo/cli/validate/inventory/__main__.py", + inventory="/etc/inventories/github-ci/devices.yml", + modes={ + "MODE_CLEANUP": False, + "MODE_ASSERT": True, + "MODE_DEBUG": False, + }, + limit=None, + allowed_applications=None, + password_file=None, + verbose=0, + skip_build=True, + diff=False, + ansible_args=None, + ) + + self.assertEqual(ctx.exception.code, 1) + self.assertFalse( + any(call_cmd and call_cmd[0] == "ansible-playbook" for call_cmd, _ in calls) + ) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/cli/deploy/development/test_exec.py b/tests/unit/cli/deploy/development/test_exec.py new file mode 100644 index 0000000000..ac43a8df0c --- /dev/null +++ b/tests/unit/cli/deploy/development/test_exec.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +import argparse +import os +import unittest +import unittest.mock + +from cli.deploy.development import exec as exec_cmd + + +class TestDevelopmentExec(unittest.TestCase): + def test_handler_forwards_services_disabled(self): + compose = unittest.mock.Mock() + compose.exec.return_value.returncode = 0 + + args = argparse.Namespace(distro="debian", cmd=["--", "sh", "-lc", "true"]) + + with unittest.mock.patch( + "cli.deploy.development.exec.make_compose", + return_value=compose, + ): + with unittest.mock.patch.dict( + os.environ, {"SERVICES_DISABLED": "email"}, clear=False + ): + rc = exec_cmd.handler(args) + + self.assertEqual(rc, 0) + compose.exec.assert_called_once_with( + ["sh", "-lc", "true"], + check=False, + extra_env={"SERVICES_DISABLED": "email"}, + ) + + def test_handler_omits_extra_env_when_services_disabled_unset(self): + compose = unittest.mock.Mock() + compose.exec.return_value.returncode = 0 + + args = argparse.Namespace(distro="debian", cmd=["echo", "hi"]) + + env = {k: v for k, v in os.environ.items() if k != "SERVICES_DISABLED"} + with unittest.mock.patch( + "cli.deploy.development.exec.make_compose", + return_value=compose, + ): + with unittest.mock.patch.dict(os.environ, env, clear=True): + rc = exec_cmd.handler(args) + + self.assertEqual(rc, 0) + compose.exec.assert_called_once_with( + ["echo", "hi"], check=False, extra_env=None + ) + + def test_handler_requires_command(self): + args = argparse.Namespace(distro="debian", cmd=[]) + with self.assertRaises(SystemExit): + exec_cmd.handler(args) + + +if __name__ == "__main__": + unittest.main() From 4da99150e91431f0655caacdf1ec3da968033302 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 14 Apr 2026 19:57:25 +0200 Subject: [PATCH 27/55] fix(svc-ai-ollama,web-app-fider,web-app-prometheus): correct service configs and pin application_id - svc-ai-ollama: explicitly set application_id=svc-ai-ollama in include_tasks so networks.local lookup resolves correctly when loaded as a shared service - web-app-fider: rename database service key to postgres and drop redundant type field - web-app-prometheus: remove unused database service entry Co-Authored-By: Claude Sonnet 4.6 --- roles/svc-ai-ollama/tasks/main.yml | 2 ++ roles/web-app-fider/config/main.yml | 5 ++--- roles/web-app-prometheus/config/main.yml | 2 -- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/roles/svc-ai-ollama/tasks/main.yml b/roles/svc-ai-ollama/tasks/main.yml index dde20fbb08..b57f0c95b5 100644 --- a/roles/svc-ai-ollama/tasks/main.yml +++ b/roles/svc-ai-ollama/tasks/main.yml @@ -1,2 +1,4 @@ - include_tasks: 01_core.yml when: run_once_svc_ai_ollama is not defined + vars: + application_id: svc-ai-ollama diff --git a/roles/web-app-fider/config/main.yml b/roles/web-app-fider/config/main.yml index 28958aab8d..14497bc325 100644 --- a/roles/web-app-fider/config/main.yml +++ b/roles/web-app-fider/config/main.yml @@ -29,10 +29,9 @@ compose: matomo: enabled: true shared: true - database: - shared: true - type: "postgres" + postgres: enabled: true + shared: true fider: image: "getfider/fider" version: "stable" diff --git a/roles/web-app-prometheus/config/main.yml b/roles/web-app-prometheus/config/main.yml index 1244706166..15003832a7 100644 --- a/roles/web-app-prometheus/config/main.yml +++ b/roles/web-app-prometheus/config/main.yml @@ -33,8 +33,6 @@ compose: matomo: enabled: true shared: true - database: - enabled: false redis: enabled: false css: From b2ee450d8f69e3a8048bbf6a846d5ef1016193d0 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 14 Apr 2026 20:00:44 +0200 Subject: [PATCH 28/55] docs(svc-ai-ollama,web-app-fider,web-app-prometheus): align READMEs with readme_md.md standard - Add missing Description, Overview, Credits sections - Link software names to official websites on first use - Replace full URLs with descriptive link text in Further Resources - Add bold labels to feature bullet points - Fix heading case (Further Resources -> Further resources) Co-Authored-By: Claude Sonnet 4.6 --- roles/svc-ai-ollama/README.md | 28 +++++++++++++++++----------- roles/web-app-fider/README.md | 5 +++-- roles/web-app-prometheus/README.md | 27 ++++++++++++++++++--------- 3 files changed, 38 insertions(+), 22 deletions(-) diff --git a/roles/svc-ai-ollama/README.md b/roles/svc-ai-ollama/README.md index 3f5ea058cf..8f35ed1b68 100644 --- a/roles/svc-ai-ollama/README.md +++ b/roles/svc-ai-ollama/README.md @@ -1,23 +1,29 @@ - # Ollama ## Description -**Ollama** is a local model server that runs open LLMs on your hardware and exposes a simple HTTP API. It’s the backbone for privacy-first AI: prompts and data stay on your machines. +[Ollama](https://ollama.com) is a local model server that runs open LLMs on your hardware and exposes a simple HTTP API. Prompts and data stay on your machines, making it the backbone for privacy-first AI. ## Overview -After the first model pull, Ollama serves models to clients like Open WebUI (for chat) and Flowise (for workflows). Models are cached locally for quick reuse and can run fully offline when required. +This role deploys Ollama as a local model server using Docker Compose. It integrates with Open WebUI for chat and Flowise for AI workflow automation, and configures local model caching so models can be reused across sessions or run fully offline. ## Features -* Run popular open models (chat, code, embeddings) locally -* Simple, predictable HTTP API for developers -* Local caching to avoid repeated downloads -* Works seamlessly with Open WebUI and Flowise -* Offline-capable for air-gapped deployments +- **Local model execution:** Run popular open models (chat, code, embeddings) on your own hardware. +- **HTTP API:** Simple, predictable HTTP API for application developers. +- **Local caching:** Models are cached locally to avoid repeated downloads. +- **Integrations:** Works seamlessly with Open WebUI and Flowise. +- **Offline support:** Fully offline-capable for air-gapped deployments. -## Further Resources +## Further resources -* Ollama — [https://ollama.com](https://ollama.com) -* Ollama Model Library — [https://ollama.com/library](https://ollama.com/library) +- [Ollama](https://ollama.com) +- [Ollama Model Library](https://ollama.com/library) + +## Credits + +Developed and maintained by **Kevin Veen-Birkenbach**. +Learn more at [veen.world](https://www.veen.world). +Part of the [Infinito.Nexus Project](https://s.infinito.nexus/code). +Licensed under the [Infinito.Nexus Community License (Non-Commercial)](https://s.infinito.nexus/license). diff --git a/roles/web-app-fider/README.md b/roles/web-app-fider/README.md index db584236d3..020d46c326 100644 --- a/roles/web-app-fider/README.md +++ b/roles/web-app-fider/README.md @@ -32,12 +32,13 @@ Key settings in `config/main.yml`: | Key | Default | Description | |-----|---------|-------------| | `compose.services.oidc.enabled` | `true` | Automate Keycloak OIDC setup | -| `compose.services.database.type` | `postgres` | Database engine (postgres only) | +| `compose.services.postgres.enabled` | `true` | Enable PostgreSQL for Fider | +| `compose.services.postgres.shared` | `true` | Reuse the shared PostgreSQL provider | | `compose.services.fider.version` | `stable` | Docker image tag | | `server.domains.canonical` | `fider.{{ DOMAIN_PRIMARY }}` | Public domain | | `server.status_codes.default` | `[200, 301, 302, 405]` | Expected HTTP codes for health check (405 because Fider returns 405 on HEAD requests to `/`) | -## Further Resources +## Further resources - [Fider GitHub](https://github.com/getfider/fider) diff --git a/roles/web-app-prometheus/README.md b/roles/web-app-prometheus/README.md index 1c9ed1c4dd..3a477f7374 100644 --- a/roles/web-app-prometheus/README.md +++ b/roles/web-app-prometheus/README.md @@ -1,19 +1,28 @@ # Prometheus -Deploys [Prometheus](https://prometheus.io/), an open-source systems monitoring and alerting toolkit, as part of the infinito.nexus stack. +## Description -Prometheus is accessible at `prometheus.` and protected by SSO via Keycloak (oauth2-proxy). +[Prometheus](https://prometheus.io/) is an open-source systems monitoring and alerting toolkit that collects and stores time-series metrics and provides a powerful query language (PromQL). + +## Overview + +This role deploys Prometheus as part of the Infinito.Nexus stack using Docker Compose. It exposes the Prometheus web UI at `prometheus.` and protects it with SSO via Keycloak using oauth2-proxy. Universal logout is integrated for session termination. ## Features -- Time-series metrics collection and storage -- PromQL query interface via the Prometheus web UI -- SSO authentication via Keycloak (oauth2-proxy) -- Universal logout integration +- **Time-series metrics:** Collects and stores time-series data from configured targets. +- **PromQL interface:** Query and explore metrics via the Prometheus web UI. +- **SSO authentication:** Access is protected by Keycloak via oauth2-proxy. +- **Universal logout:** Integrated session termination across the stack. -## Further Resources +## Further resources - [Prometheus Documentation](https://prometheus.io/docs/) - [prom/prometheus Docker image](https://hub.docker.com/r/prom/prometheus) -- Issue #541: Create Prometheus Role -- Issue #542: Integrate Prometheus layer into all applications + +## Credits + +Developed and maintained by **Kevin Veen-Birkenbach**. +Learn more at [veen.world](https://www.veen.world). +Part of the [Infinito.Nexus Project](https://s.infinito.nexus/code). +Licensed under the [Infinito.Nexus Community License (Non-Commercial)](https://s.infinito.nexus/license). From 28e5ed4a1b0df040602f0baa25214b0a96ab6246 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 14 Apr 2026 20:48:52 +0200 Subject: [PATCH 29/55] docs(claude): document settings permissions and restructure agent docs - Extend .claude/settings.json with git mv, rm, cherry-pick, apply, gh run, gh api, bash -n - Add make chmod-scripts target and document it in make.md - Move docs/contributing/tools/agents.md to agents/common.md - Add docs/contributing/tools/agents/README.md and claude.md with full permission reference in table format - Fix relative links in common.md after directory move Co-Authored-By: Claude Sonnet 4.6 --- .claude/settings.json | 10 +- AGENTS.md | 2 +- CLAUDE.md | 2 +- GEMINI.md | 2 +- Makefile | 6 +- docs/contributing/tools/agents/README.md | 6 + docs/contributing/tools/agents/claude.md | 171 ++++++++++++++++++ .../tools/{agents.md => agents/common.md} | 5 +- docs/contributing/tools/make.md | 1 + 9 files changed, 198 insertions(+), 7 deletions(-) create mode 100644 docs/contributing/tools/agents/README.md create mode 100644 docs/contributing/tools/agents/claude.md rename docs/contributing/tools/{agents.md => agents/common.md} (63%) diff --git a/.claude/settings.json b/.claude/settings.json index 84a49563f9..0073c12c67 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -9,14 +9,21 @@ "Bash(git log*)", "Bash(git diff*)", "Bash(git add*)", + "Bash(git mv*)", + "Bash(git rm*)", "Bash(git checkout*)", "Bash(git branch*)", "Bash(git fetch*)", "Bash(git stash*)", + "Bash(git cherry-pick*)", + "Bash(git apply*)", "Bash(git -C:*)", + "Bash(gh run*)", + "Bash(make*)", "Bash(act*)", + "Bash(bash -n*)", "Bash(python3*)", "Bash(python*)", @@ -83,7 +90,8 @@ "Bash(git commit*)", "Bash(git push*)", "Bash(docker run*)", - "Bash(curl*)" + "Bash(curl*)", + "Bash(gh api*)" ], "deny": [ diff --git a/AGENTS.md b/AGENTS.md index 08d0b5823c..0e89719564 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -30,4 +30,4 @@ The agent MUST NOT repeat this notice within the same conversation. ## For Humans -Human contributors working alongside AI agents MUST read [here](docs/contributing/tools/agents.md). +Human contributors working alongside AI agents MUST read [here](docs/contributing/tools/agents/common.md). diff --git a/CLAUDE.md b/CLAUDE.md index 00d57a13ea..18707dfaee 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -24,4 +24,4 @@ You MUST read `AGENTS.md` and follow all instructions in it at the start of ever ## Documentation -See the [Claude Code documentation](https://code.claude.com/docs/en/overview) for further information. For human contributor guidance on working with agents, see [here](docs/contributing/tools/agents.md). +See the [Claude Code documentation](https://code.claude.com/docs/en/overview) for further information. For human contributor guidance on working with agents, see [here](docs/contributing/tools/agents/common.md). diff --git a/GEMINI.md b/GEMINI.md index e003702cb1..59a8c8d23b 100644 --- a/GEMINI.md +++ b/GEMINI.md @@ -10,4 +10,4 @@ This file extends [AGENTS.md](AGENTS.md) with Gemini-specific additions. You MUS ## Documentation -See the [Gemini CLI documentation](https://geminicli.com/docs/cli/gemini-md/). For human contributor guidance on working with agents, see [here](docs/contributing/tools/agents.md). \ No newline at end of file +See the [Gemini CLI documentation](https://geminicli.com/docs/cli/gemini-md/). For human contributor guidance on working with agents, see [here](docs/contributing/tools/agents/common.md). \ No newline at end of file diff --git a/Makefile b/Makefile index 615a71fa65..71258d7df4 100644 --- a/Makefile +++ b/Makefile @@ -21,7 +21,7 @@ endif test lint lint-action lint-ansible lint-python lint-shellcheck autoformat test-lint test-unit test-integration test-external test-deploy test-deploy-app \ clean clean-sudo down \ system-purge system-disk-usage \ - list tree mig dockerignore \ + list tree mig dockerignore chmod-scripts \ print-python \ dns-setup dns-remove \ environment-bootstrap environment-teardown \ @@ -144,6 +144,10 @@ down: stop: @"$${PYTHON}" -m cli.deploy.development stop +# Mark all shell scripts under scripts/ as executable. +chmod-scripts: + @find scripts/ -name "*.sh" -exec chmod +x {} \; + # Print the repository role list. list: @echo "Generating the roles list" diff --git a/docs/contributing/tools/agents/README.md b/docs/contributing/tools/agents/README.md new file mode 100644 index 0000000000..714277cff9 --- /dev/null +++ b/docs/contributing/tools/agents/README.md @@ -0,0 +1,6 @@ +# Agent Tooling 🤖 + +This directory contains documentation for contributors working alongside AI coding agents in this project. +It covers shared agent guidelines that apply regardless of the AI tool used, as well as tool-specific permission references and security rationale for each supported agent. + +For the machine-readable agent entry point, see [AGENTS.md](../../../../AGENTS.md). diff --git a/docs/contributing/tools/agents/claude.md b/docs/contributing/tools/agents/claude.md new file mode 100644 index 0000000000..28d9745d7d --- /dev/null +++ b/docs/contributing/tools/agents/claude.md @@ -0,0 +1,171 @@ +# Claude Code Settings 🤖 + +This page documents every permission entry in [`.claude/settings.json`](../../../../.claude/settings.json) and explains when it applies, why it is granted at that level, and what security implications it carries. +For general agent workflow rules, see [common.md](common.md). +For the Claude Code permission model reference, see [docs.anthropic.com](https://docs.anthropic.com/en/docs/claude-code/settings). + +## Permission Model 🔐 + +Claude Code evaluates each tool call against three ordered lists: + +| List | Behavior | +|---|---| +| `allow` | Executes automatically without prompting. | +| `ask` | Pauses and asks the operator for approval before executing. | +| `deny` | Rejects the call unconditionally, even if `allow` would otherwise match. | + +`deny` takes precedence over `allow`. `settings.local.json` MAY extend project permissions locally but MUST NOT weaken `deny` rules defined here. + +## Allow Permissions ✅ + +### File Tools ✏️ + +| Permission | When | Why | Security | +|---|---|---|---| +| `Read` | Every task that inspects a file. | Core IDE operation. The agent cannot understand code without it. | Scope is limited by `denyRead` in the sandbox section. Credential directories are never readable. | +| `Edit` | Every task that modifies an existing file. | Core IDE operation. Required for any code change. | Write scope is bounded by `allowWrite`. Changes outside `.` and `/tmp` are blocked. | +| `Write` | Every task that creates a new file. | Core IDE operation. Required for scaffolding and new file creation. | Same sandbox boundary as `Edit`. | + +### Git Commands 🗃️ + +| Permission | When | Why | Security | +|---|---|---|---| +| `git status*` | Before any task to inspect the working tree. | Read-only state inspection. Required for every task that touches the repository. | No write side-effects. Safe to allow unconditionally. | +| `git log*` | Reviewing history, finding commits, checking recent changes. | Read-only history access. | No write side-effects. Safe to allow unconditionally. | +| `git diff*` | Comparing changes before staging or committing. | Read-only diff output. | No write side-effects. Safe to allow unconditionally. | +| `git add*` | Staging changes as part of a task before a commit is requested. | Prerequisite for committing. | Affects the index only, not the remote. Destructive intent requires `git commit` and `git push`, both in `ask`. | +| `git mv*` | Renaming or moving tracked files. | Required for rename and restructuring tasks. | Affects the index only. Reversible before committing. | +| `git rm*` | Removing tracked files as part of a task. | Required for delete tasks. | Affects the index only. Reversible before committing. | +| `git checkout*` | Switching branches or restoring individual files. | Standard branch-management operation. | Can discard local changes when used with a path argument. The `deny` rule for `git reset --hard` mitigates the broader discard risk. | +| `git branch*` | Creating, listing, or deleting local branches. | Required during feature and fix workflows. | Local only. Remote branches require `git push`, which is in `ask`. | +| `git fetch*` | Fetching remote state without merging. | Needed to compare local and remote state before taking action. | Read-only from the network perspective. Does not modify the working tree. | +| `git stash*` | Temporarily shelving uncommitted work before switching context. | Needed when the agent must change branches without losing in-progress edits. | Reversible. No data leaves the machine. | +| `git cherry-pick*` | Applying isolated commits from other branches. | Required for backport tasks. | Modifies the working tree and index. Operators SHOULD review the source commit before approving the task. | +| `git apply*` | Applying patch files to the working tree. | Required for patch-based workflows. | Modifies the working tree and index. Operators SHOULD review the patch source before approving the task. | +| `git -C*` | Running git commands in a sub-path of the repository. | Some scripts and make targets invoke git outside the current working directory. | Equivalent to the base git commands above. No additional privilege is granted. | + +### GitHub CLI 🐙 + +| Permission | When | Why | Security | +|---|---|---|---| +| `gh run*` | Inspecting CI pipeline runs, viewing logs, or listing workflow run status. | Allows the agent to check whether a workflow passed without browser access. | Primarily read-only. Subcommands such as `gh run rerun` and `gh run cancel` are write operations covered by this wildcard. Operators SHOULD verify the subcommand when approving tasks. | + +### Build and Scripts 🛠️ + +| Permission | When | Why | Security | +|---|---|---|---| +| `make*` | Running any target defined in the repository `Makefile`. | Make is the primary command surface covering install, test, lint, build, deploy, and cleanup. | The full wildcard is broad. The `Makefile` MUST NOT expose targets that run privileged or destructive operations without explicit guards. New make targets SHOULD be reviewed before merging. | +| `act*` | Running GitHub Actions workflows locally via Act. | Used by `make act-*` targets for local CI simulation. | Act pulls Docker images and executes workflow steps locally. Workflows MUST NOT contain untrusted third-party actions before running. | +| `bash -n*` | Syntax-checking shell scripts before executing them. | `bash -n` is a dry-run parse that catches syntax errors safely. | No code is executed. Side-effect-free. | + +### Python 🐍 + +| Permission | When | Why | Security | +|---|---|---|---| +| `python3*`, `python*` | Running Python scripts or the CLI modules inside the repository. | The project CLI (`cli/`) is Python-based and required for list, tree, deploy, and other targets. | Scoped to repository scripts. The agent MUST NOT install or run untrusted third-party packages without review. | +| `pip show*`, `pip list*` | Inspecting installed packages and versions. | Read-only introspection needed for dependency debugging. | No side-effects. Safe to allow unconditionally. | +| `pip install*` | Installing Python dependencies during environment setup. | Required by `make install-python` and related targets. | Modifies the virtual environment. Only packages declared in project requirements files SHOULD be installed. Arbitrary installs SHOULD be reviewed. | + +### Ansible 📋 + +| Permission | When | Why | Security | +|---|---|---|---| +| `ansible-lint*` | Linting Ansible roles and playbooks. | Used by `make lint-ansible`. Read-only. | No playbook execution. Safe to allow unconditionally. | +| `ansible-inventory*` | Inspecting the Ansible inventory. | Required for debugging inventory structure. | Read-only. Safe to allow unconditionally. | +| `ansible --version*` | Verifying the installed Ansible version. | Read-only version check. | No side-effects. Safe to allow unconditionally. | +| `ansible-playbook --check*` | Dry-run execution of playbooks. | Does not apply changes to hosts. | Still connects to hosts and reads remote state. Ensure inventory targets are intended before running. | +| `ansible-playbook --syntax-check*` | Syntax validation of playbooks. | Parse-only. Does not connect to hosts. | No side-effects. Safe to allow unconditionally. | + +### Docker 🐳 + +| Permission | When | Why | Security | +|---|---|---|---| +| `docker images*`, `docker ps*`, `docker inspect*`, `docker logs*` | Inspecting local images, running containers, and their logs. | Read-only status checks required for debugging. | No containers are started or modified. Safe to allow unconditionally. | +| `docker pull*` | Fetching images from a registry. | Required by `make build-dependency` and related targets. | Fetches external content. The source registry MUST be trusted before pulling. | +| `docker build*` | Building local images. | Required by `make build*` targets. | Executes the Dockerfile locally. Review Dockerfile changes before building. | +| `docker create*`, `docker export*` | Creating and exporting containers for inspection or archival. | Used in build and CI simulation workflows. | Local only. No network exposure from these operations alone. | +| `docker rm*`, `docker rmi*` | Removing containers and images. | Required for cleanup targets. | Destructive but scoped to local state only. Remote registries are not affected. | +| `docker compose*` | Managing the development stack defined in `compose.yml`. | Used by `make up`, `make down`, and related targets. | Can start services with volume mounts and network access. Changes to `compose.yml` MUST be reviewed before running the stack. | +| `docker exec*` | Running commands inside a running container. | Used by `make exec` for inspection and interactive debugging. | Grants shell access inside the container. MUST only be used on trusted, locally built containers. | + +### Shell Utilities 🔧 + +| Permission | When | Why | Security | +|---|---|---|---| +| `grep*`, `find*`, `ls*`, `cat*`, `head*`, `tail*` | Reading and searching file content during any task. | Standard read-only inspection tools. Required for almost every task. | No write side-effects. Safe to allow unconditionally. | +| `wc*`, `sort*`, `jq*` | Counting lines, sorting output, parsing JSON. | Common pipeline utilities used in scripts and make targets. | No write side-effects. Safe to allow unconditionally. | +| `tar*` | Archiving files during build or export tasks. | Required by build and packaging scripts. | Can overwrite files when extracting. The sandbox `allowWrite` limits the blast radius to `.` and `/tmp`. | +| `mkdir*`, `cp*`, `mv*` | Creating directories and moving or copying files during setup and build tasks. | Required by install scripts and build targets. | `mv` and `cp` can overwrite files silently. Bounded by the sandbox `allowWrite` constraint. | + +### Web Access 🌐 + +| Permission | When | Why | Security | +|---|---|---|---| +| `WebSearch` | Looking up documentation, error messages, or package information. | Allows the agent to resolve unknown APIs and tooling questions without leaving the terminal. | Outbound query only. No local data is uploaded. | +| `WebFetch(domain:github.com)`, `WebFetch(domain:raw.githubusercontent.com)`, `WebFetch(domain:api.github.com)` | Fetching repository pages, raw files, or GitHub API responses. | Required for tasks that inspect upstream code or release data. | Read-only. No credentials are transmitted. | +| `WebFetch(domain:docs.ansible.com)` | Fetching Ansible module and collection reference documentation. | Required when researching Ansible APIs. | Read-only. | +| `WebFetch(domain:docs.docker.com)` | Fetching Docker and Compose reference documentation. | Required when researching Docker APIs. | Read-only. | +| `WebFetch(domain:docs.gitea.com)` | Fetching Gitea self-hosted Git documentation. | Required when working on Gitea-related roles. | Read-only. | +| `WebFetch(domain:pypi.org)` | Fetching Python package metadata and version information. | Required for dependency research. | Read-only. | +| `WebFetch(domain:infinito.nexus)`, `WebFetch(domain:infinito.example)` | Accessing production and local development instances of this project. | Required for integration checks and live service inspection. | Read-only fetches. Credentials MUST NOT be embedded in fetched URLs. | +| `WebFetch(domain:docs.infinito.nexus)` | Fetching project documentation pages. | Required when cross-referencing published docs during tasks. | Read-only. | +| `WebFetch(domain:s.infinito.nexus)`, `WebFetch(domain:hub.infinito.nexus)` | Accessing project service endpoints. | Required for service-level inspection tasks. | Read-only. | +| `WebFetch(domain:cybermaster.space)` | Accessing the project operator domain referenced in role configuration. | Required when resolving operator-specific configuration. | Read-only. | +| `WebFetch(domain:community.taiga.io)` | Fetching Taiga project management documentation. | Required when working on Taiga-related roles. | Read-only. | +| `WebFetch(domain:monogramm.io)` | Fetching upstream Docker image documentation. | Required when researching images provided by this upstream. | Read-only. | +| `WebFetch(domain:ghcr.io)` | Fetching GitHub Container Registry image metadata. | Required for image version lookups. | Read-only. | +| `WebFetch(domain:letsencrypt.org)` | Fetching Let's Encrypt ACME documentation and root certificates. | Required when working on TLS-related roles. | Read-only. | +| `WebFetch(domain:hcaptcha.com)` | Fetching hCaptcha integration documentation. | Required when working on hCaptcha-related roles. | Read-only. | +| `WebFetch(domain:gstatic.com)` | Fetching Google static assets referenced by certain frontend roles. | Required when inspecting frontend asset behavior. | Read-only. | + +## Ask Permissions ⚠️ + +These operations pause and require explicit operator approval before executing. + +| Permission | When | Why approval is required | Security | +|---|---|---|---| +| `git commit*` | Creating a permanent history entry. | The operator MUST review the staged diff and message before committing. | Commits are persistent and visible to all contributors after push. | +| `git push*` | Publishing changes to the remote. | Cannot be undone without a force-push. | Exposes changes to all repository collaborators and CI. | +| `docker run*` | Starting a standalone container outside the compose stack. | Each invocation carries a unique risk profile depending on flags. | Can mount host paths, expose ports, and run privileged containers. | +| `curl*` | Making HTTP requests to arbitrary URLs. | Can transmit environment variables and credentials to external endpoints. | Risk depends entirely on the URL and flags used. Every invocation MUST be reviewed. | +| `gh api*` | Making direct GitHub REST or GraphQL API calls. | Can modify branch protection, secrets, webhooks, collaborators, and workflow triggers. | Supports arbitrary HTTP methods (`-X POST/PATCH/DELETE`). Each invocation MUST be reviewed individually. | + +## Deny Rules 🚫 + +These operations are unconditionally blocked, regardless of any `allow` entry. + +| Permission | Reason | +|---|---| +| `git push --force*` | Rewrites remote history. Can permanently destroy other contributors' work. | +| `git reset --hard*` | Discards all uncommitted local changes without any recovery path. | +| `rm -rf*` | Recursive force-delete with no confirmation and no undo. | +| `sudo*` | Prevents privilege escalation to root on the host system. | + +## Sandbox 🏖️ + +### Write Scope + +The agent MAY write to `.` (the repository root) and `/tmp`. All other paths are read-only by default. + +### Read Restrictions + +The following directories are never readable, even if a task explicitly requests access: + +| Path | What it protects | +|---|---| +| `~/.ssh` | SSH private keys. | +| `~/.gnupg` | GPG keys and keyrings. | +| `~/.kube` | Kubernetes cluster credentials. | +| `~/.aws` | AWS access keys and configuration. | +| `~/.config/gcloud` | Google Cloud service account credentials. | + +## Local Overrides 🖥️ + +Contributors MAY extend project permissions via `.claude/settings.local.json`. This file is git-ignored and applies only to the local machine. + +| Rule | Description | +|---|---| +| MUST NOT weaken `deny` | Local overrides cannot lift unconditional blocks defined in `settings.json`. | +| Machine-specific entries MUST stay local | Absolute paths, process IDs, and debug tooling MUST NOT be promoted to `settings.json`. | +| Shared permissions SHOULD be promoted | Permissions useful for all contributors SHOULD be added to `settings.json` instead of staying local. | +| Keep overrides minimal | Entries already covered by project-level wildcards SHOULD be removed from `settings.local.json`. | diff --git a/docs/contributing/tools/agents.md b/docs/contributing/tools/agents/common.md similarity index 63% rename from docs/contributing/tools/agents.md rename to docs/contributing/tools/agents/common.md index 9f55fdffa1..0ac9ac7ca7 100644 --- a/docs/contributing/tools/agents.md +++ b/docs/contributing/tools/agents/common.md @@ -2,13 +2,14 @@ AI assistants are welcome, but they MUST follow the same workflow as humans. -- You MUST treat [AGENTS.md](../../../AGENTS.md) as the entry point for all agent-specific execution instructions. Tool-specific files such as `CLAUDE.md` and `GEMINI.md` extend `AGENTS.md` and MUST NOT contradict it. +- You MUST treat [AGENTS.md](../../../../AGENTS.md) as the entry point for all agent-specific execution instructions. Tool-specific files such as `CLAUDE.md` and `GEMINI.md` extend `AGENTS.md` and MUST NOT contradict it. - You MUST NOT invent commands, workflows, or files that do not exist. - You MUST NEVER expose secrets in prompts, code, screenshots, or logs. - You MUST treat AI output as a draft that must be reviewed for wrong assumptions, duplicate logic, and security mistakes. - You MUST keep explanations simple and explicit. - You MUST state assumptions clearly. -For tool-specific configuration and additional instructions, see [CLAUDE.md](../../../CLAUDE.md) and [GEMINI.md](../../../GEMINI.md). +For tool-specific configuration and additional instructions, see [CLAUDE.md](../../../../CLAUDE.md) and [GEMINI.md](../../../../GEMINI.md). +For a full reference of permitted Claude Code operations and their security rationale, see [claude.md](claude.md). For further support, visit the AI forum at [s.infinito.nexus/aihub](https://s.infinito.nexus/aihub) or join the Matrix group [#ai:infinito.nexus](https://matrix.to/#/#ai:infinito.nexus). diff --git a/docs/contributing/tools/make.md b/docs/contributing/tools/make.md index 42eb5d51e3..96ba8222e6 100644 --- a/docs/contributing/tools/make.md +++ b/docs/contributing/tools/make.md @@ -56,6 +56,7 @@ For rules on how to write and structure the `Makefile` itself, see [makefile.md] | Setup development | `make mark-development` | Creates the development setup marker. | Use this when you want to prepare a development-specific setup state. | | Bootstrap | `make bootstrap` | Installs dependencies and prepares the project. | Use this on a fresh machine or a new checkout. | | Setup clean | `make setup-clean` | Cleans ignored files and then runs setup. | Use this when you want a clean setup pass. | +| Mark scripts executable | `make chmod-scripts` | Marks all `.sh` files under `scripts/` as executable. | Use this after cloning or when a script loses its executable bit. | | List roles | `make list` | Prints the repository role list. | Use this when you need the current role inventory. | | Tree view | `make tree` | Prints the repository tree. | Use this when you want a compact structural overview. | | Meta graph inputs | `make mig` | Builds the meta graph inputs from `list` and `tree`. | Use this when you are generating or refreshing meta graph data. | From 0fe7c5fd6f86e2d8d42a4b681bce5e8638d80f2c Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 14 Apr 2026 20:48:52 +0200 Subject: [PATCH 30/55] docs(claude): document settings permissions and restructure agent docs - Extend .claude/settings.json with git mv, rm, cherry-pick, apply, gh run, gh api, bash -n - Add make chmod-scripts target and document it in make.md - Move docs/contributing/tools/agents.md to agents/common.md - Add docs/contributing/tools/agents/README.md and claude.md with full permission reference in table format - Fix relative links in common.md after directory move Co-Authored-By: Claude Sonnet 4.6 --- .claude/settings.json | 10 +- AGENTS.md | 2 +- CLAUDE.md | 2 +- GEMINI.md | 2 +- Makefile | 6 +- docs/contributing/tools/agents/README.md | 6 + docs/contributing/tools/agents/claude.md | 171 ++++++++++++++++++ .../tools/{agents.md => agents/common.md} | 5 +- docs/contributing/tools/make.md | 1 + 9 files changed, 198 insertions(+), 7 deletions(-) create mode 100644 docs/contributing/tools/agents/README.md create mode 100644 docs/contributing/tools/agents/claude.md rename docs/contributing/tools/{agents.md => agents/common.md} (63%) diff --git a/.claude/settings.json b/.claude/settings.json index 84a49563f9..0073c12c67 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -9,14 +9,21 @@ "Bash(git log*)", "Bash(git diff*)", "Bash(git add*)", + "Bash(git mv*)", + "Bash(git rm*)", "Bash(git checkout*)", "Bash(git branch*)", "Bash(git fetch*)", "Bash(git stash*)", + "Bash(git cherry-pick*)", + "Bash(git apply*)", "Bash(git -C:*)", + "Bash(gh run*)", + "Bash(make*)", "Bash(act*)", + "Bash(bash -n*)", "Bash(python3*)", "Bash(python*)", @@ -83,7 +90,8 @@ "Bash(git commit*)", "Bash(git push*)", "Bash(docker run*)", - "Bash(curl*)" + "Bash(curl*)", + "Bash(gh api*)" ], "deny": [ diff --git a/AGENTS.md b/AGENTS.md index 08d0b5823c..0e89719564 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -30,4 +30,4 @@ The agent MUST NOT repeat this notice within the same conversation. ## For Humans -Human contributors working alongside AI agents MUST read [here](docs/contributing/tools/agents.md). +Human contributors working alongside AI agents MUST read [here](docs/contributing/tools/agents/common.md). diff --git a/CLAUDE.md b/CLAUDE.md index 00d57a13ea..18707dfaee 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -24,4 +24,4 @@ You MUST read `AGENTS.md` and follow all instructions in it at the start of ever ## Documentation -See the [Claude Code documentation](https://code.claude.com/docs/en/overview) for further information. For human contributor guidance on working with agents, see [here](docs/contributing/tools/agents.md). +See the [Claude Code documentation](https://code.claude.com/docs/en/overview) for further information. For human contributor guidance on working with agents, see [here](docs/contributing/tools/agents/common.md). diff --git a/GEMINI.md b/GEMINI.md index e003702cb1..59a8c8d23b 100644 --- a/GEMINI.md +++ b/GEMINI.md @@ -10,4 +10,4 @@ This file extends [AGENTS.md](AGENTS.md) with Gemini-specific additions. You MUS ## Documentation -See the [Gemini CLI documentation](https://geminicli.com/docs/cli/gemini-md/). For human contributor guidance on working with agents, see [here](docs/contributing/tools/agents.md). \ No newline at end of file +See the [Gemini CLI documentation](https://geminicli.com/docs/cli/gemini-md/). For human contributor guidance on working with agents, see [here](docs/contributing/tools/agents/common.md). \ No newline at end of file diff --git a/Makefile b/Makefile index 615a71fa65..71258d7df4 100644 --- a/Makefile +++ b/Makefile @@ -21,7 +21,7 @@ endif test lint lint-action lint-ansible lint-python lint-shellcheck autoformat test-lint test-unit test-integration test-external test-deploy test-deploy-app \ clean clean-sudo down \ system-purge system-disk-usage \ - list tree mig dockerignore \ + list tree mig dockerignore chmod-scripts \ print-python \ dns-setup dns-remove \ environment-bootstrap environment-teardown \ @@ -144,6 +144,10 @@ down: stop: @"$${PYTHON}" -m cli.deploy.development stop +# Mark all shell scripts under scripts/ as executable. +chmod-scripts: + @find scripts/ -name "*.sh" -exec chmod +x {} \; + # Print the repository role list. list: @echo "Generating the roles list" diff --git a/docs/contributing/tools/agents/README.md b/docs/contributing/tools/agents/README.md new file mode 100644 index 0000000000..714277cff9 --- /dev/null +++ b/docs/contributing/tools/agents/README.md @@ -0,0 +1,6 @@ +# Agent Tooling 🤖 + +This directory contains documentation for contributors working alongside AI coding agents in this project. +It covers shared agent guidelines that apply regardless of the AI tool used, as well as tool-specific permission references and security rationale for each supported agent. + +For the machine-readable agent entry point, see [AGENTS.md](../../../../AGENTS.md). diff --git a/docs/contributing/tools/agents/claude.md b/docs/contributing/tools/agents/claude.md new file mode 100644 index 0000000000..28d9745d7d --- /dev/null +++ b/docs/contributing/tools/agents/claude.md @@ -0,0 +1,171 @@ +# Claude Code Settings 🤖 + +This page documents every permission entry in [`.claude/settings.json`](../../../../.claude/settings.json) and explains when it applies, why it is granted at that level, and what security implications it carries. +For general agent workflow rules, see [common.md](common.md). +For the Claude Code permission model reference, see [docs.anthropic.com](https://docs.anthropic.com/en/docs/claude-code/settings). + +## Permission Model 🔐 + +Claude Code evaluates each tool call against three ordered lists: + +| List | Behavior | +|---|---| +| `allow` | Executes automatically without prompting. | +| `ask` | Pauses and asks the operator for approval before executing. | +| `deny` | Rejects the call unconditionally, even if `allow` would otherwise match. | + +`deny` takes precedence over `allow`. `settings.local.json` MAY extend project permissions locally but MUST NOT weaken `deny` rules defined here. + +## Allow Permissions ✅ + +### File Tools ✏️ + +| Permission | When | Why | Security | +|---|---|---|---| +| `Read` | Every task that inspects a file. | Core IDE operation. The agent cannot understand code without it. | Scope is limited by `denyRead` in the sandbox section. Credential directories are never readable. | +| `Edit` | Every task that modifies an existing file. | Core IDE operation. Required for any code change. | Write scope is bounded by `allowWrite`. Changes outside `.` and `/tmp` are blocked. | +| `Write` | Every task that creates a new file. | Core IDE operation. Required for scaffolding and new file creation. | Same sandbox boundary as `Edit`. | + +### Git Commands 🗃️ + +| Permission | When | Why | Security | +|---|---|---|---| +| `git status*` | Before any task to inspect the working tree. | Read-only state inspection. Required for every task that touches the repository. | No write side-effects. Safe to allow unconditionally. | +| `git log*` | Reviewing history, finding commits, checking recent changes. | Read-only history access. | No write side-effects. Safe to allow unconditionally. | +| `git diff*` | Comparing changes before staging or committing. | Read-only diff output. | No write side-effects. Safe to allow unconditionally. | +| `git add*` | Staging changes as part of a task before a commit is requested. | Prerequisite for committing. | Affects the index only, not the remote. Destructive intent requires `git commit` and `git push`, both in `ask`. | +| `git mv*` | Renaming or moving tracked files. | Required for rename and restructuring tasks. | Affects the index only. Reversible before committing. | +| `git rm*` | Removing tracked files as part of a task. | Required for delete tasks. | Affects the index only. Reversible before committing. | +| `git checkout*` | Switching branches or restoring individual files. | Standard branch-management operation. | Can discard local changes when used with a path argument. The `deny` rule for `git reset --hard` mitigates the broader discard risk. | +| `git branch*` | Creating, listing, or deleting local branches. | Required during feature and fix workflows. | Local only. Remote branches require `git push`, which is in `ask`. | +| `git fetch*` | Fetching remote state without merging. | Needed to compare local and remote state before taking action. | Read-only from the network perspective. Does not modify the working tree. | +| `git stash*` | Temporarily shelving uncommitted work before switching context. | Needed when the agent must change branches without losing in-progress edits. | Reversible. No data leaves the machine. | +| `git cherry-pick*` | Applying isolated commits from other branches. | Required for backport tasks. | Modifies the working tree and index. Operators SHOULD review the source commit before approving the task. | +| `git apply*` | Applying patch files to the working tree. | Required for patch-based workflows. | Modifies the working tree and index. Operators SHOULD review the patch source before approving the task. | +| `git -C*` | Running git commands in a sub-path of the repository. | Some scripts and make targets invoke git outside the current working directory. | Equivalent to the base git commands above. No additional privilege is granted. | + +### GitHub CLI 🐙 + +| Permission | When | Why | Security | +|---|---|---|---| +| `gh run*` | Inspecting CI pipeline runs, viewing logs, or listing workflow run status. | Allows the agent to check whether a workflow passed without browser access. | Primarily read-only. Subcommands such as `gh run rerun` and `gh run cancel` are write operations covered by this wildcard. Operators SHOULD verify the subcommand when approving tasks. | + +### Build and Scripts 🛠️ + +| Permission | When | Why | Security | +|---|---|---|---| +| `make*` | Running any target defined in the repository `Makefile`. | Make is the primary command surface covering install, test, lint, build, deploy, and cleanup. | The full wildcard is broad. The `Makefile` MUST NOT expose targets that run privileged or destructive operations without explicit guards. New make targets SHOULD be reviewed before merging. | +| `act*` | Running GitHub Actions workflows locally via Act. | Used by `make act-*` targets for local CI simulation. | Act pulls Docker images and executes workflow steps locally. Workflows MUST NOT contain untrusted third-party actions before running. | +| `bash -n*` | Syntax-checking shell scripts before executing them. | `bash -n` is a dry-run parse that catches syntax errors safely. | No code is executed. Side-effect-free. | + +### Python 🐍 + +| Permission | When | Why | Security | +|---|---|---|---| +| `python3*`, `python*` | Running Python scripts or the CLI modules inside the repository. | The project CLI (`cli/`) is Python-based and required for list, tree, deploy, and other targets. | Scoped to repository scripts. The agent MUST NOT install or run untrusted third-party packages without review. | +| `pip show*`, `pip list*` | Inspecting installed packages and versions. | Read-only introspection needed for dependency debugging. | No side-effects. Safe to allow unconditionally. | +| `pip install*` | Installing Python dependencies during environment setup. | Required by `make install-python` and related targets. | Modifies the virtual environment. Only packages declared in project requirements files SHOULD be installed. Arbitrary installs SHOULD be reviewed. | + +### Ansible 📋 + +| Permission | When | Why | Security | +|---|---|---|---| +| `ansible-lint*` | Linting Ansible roles and playbooks. | Used by `make lint-ansible`. Read-only. | No playbook execution. Safe to allow unconditionally. | +| `ansible-inventory*` | Inspecting the Ansible inventory. | Required for debugging inventory structure. | Read-only. Safe to allow unconditionally. | +| `ansible --version*` | Verifying the installed Ansible version. | Read-only version check. | No side-effects. Safe to allow unconditionally. | +| `ansible-playbook --check*` | Dry-run execution of playbooks. | Does not apply changes to hosts. | Still connects to hosts and reads remote state. Ensure inventory targets are intended before running. | +| `ansible-playbook --syntax-check*` | Syntax validation of playbooks. | Parse-only. Does not connect to hosts. | No side-effects. Safe to allow unconditionally. | + +### Docker 🐳 + +| Permission | When | Why | Security | +|---|---|---|---| +| `docker images*`, `docker ps*`, `docker inspect*`, `docker logs*` | Inspecting local images, running containers, and their logs. | Read-only status checks required for debugging. | No containers are started or modified. Safe to allow unconditionally. | +| `docker pull*` | Fetching images from a registry. | Required by `make build-dependency` and related targets. | Fetches external content. The source registry MUST be trusted before pulling. | +| `docker build*` | Building local images. | Required by `make build*` targets. | Executes the Dockerfile locally. Review Dockerfile changes before building. | +| `docker create*`, `docker export*` | Creating and exporting containers for inspection or archival. | Used in build and CI simulation workflows. | Local only. No network exposure from these operations alone. | +| `docker rm*`, `docker rmi*` | Removing containers and images. | Required for cleanup targets. | Destructive but scoped to local state only. Remote registries are not affected. | +| `docker compose*` | Managing the development stack defined in `compose.yml`. | Used by `make up`, `make down`, and related targets. | Can start services with volume mounts and network access. Changes to `compose.yml` MUST be reviewed before running the stack. | +| `docker exec*` | Running commands inside a running container. | Used by `make exec` for inspection and interactive debugging. | Grants shell access inside the container. MUST only be used on trusted, locally built containers. | + +### Shell Utilities 🔧 + +| Permission | When | Why | Security | +|---|---|---|---| +| `grep*`, `find*`, `ls*`, `cat*`, `head*`, `tail*` | Reading and searching file content during any task. | Standard read-only inspection tools. Required for almost every task. | No write side-effects. Safe to allow unconditionally. | +| `wc*`, `sort*`, `jq*` | Counting lines, sorting output, parsing JSON. | Common pipeline utilities used in scripts and make targets. | No write side-effects. Safe to allow unconditionally. | +| `tar*` | Archiving files during build or export tasks. | Required by build and packaging scripts. | Can overwrite files when extracting. The sandbox `allowWrite` limits the blast radius to `.` and `/tmp`. | +| `mkdir*`, `cp*`, `mv*` | Creating directories and moving or copying files during setup and build tasks. | Required by install scripts and build targets. | `mv` and `cp` can overwrite files silently. Bounded by the sandbox `allowWrite` constraint. | + +### Web Access 🌐 + +| Permission | When | Why | Security | +|---|---|---|---| +| `WebSearch` | Looking up documentation, error messages, or package information. | Allows the agent to resolve unknown APIs and tooling questions without leaving the terminal. | Outbound query only. No local data is uploaded. | +| `WebFetch(domain:github.com)`, `WebFetch(domain:raw.githubusercontent.com)`, `WebFetch(domain:api.github.com)` | Fetching repository pages, raw files, or GitHub API responses. | Required for tasks that inspect upstream code or release data. | Read-only. No credentials are transmitted. | +| `WebFetch(domain:docs.ansible.com)` | Fetching Ansible module and collection reference documentation. | Required when researching Ansible APIs. | Read-only. | +| `WebFetch(domain:docs.docker.com)` | Fetching Docker and Compose reference documentation. | Required when researching Docker APIs. | Read-only. | +| `WebFetch(domain:docs.gitea.com)` | Fetching Gitea self-hosted Git documentation. | Required when working on Gitea-related roles. | Read-only. | +| `WebFetch(domain:pypi.org)` | Fetching Python package metadata and version information. | Required for dependency research. | Read-only. | +| `WebFetch(domain:infinito.nexus)`, `WebFetch(domain:infinito.example)` | Accessing production and local development instances of this project. | Required for integration checks and live service inspection. | Read-only fetches. Credentials MUST NOT be embedded in fetched URLs. | +| `WebFetch(domain:docs.infinito.nexus)` | Fetching project documentation pages. | Required when cross-referencing published docs during tasks. | Read-only. | +| `WebFetch(domain:s.infinito.nexus)`, `WebFetch(domain:hub.infinito.nexus)` | Accessing project service endpoints. | Required for service-level inspection tasks. | Read-only. | +| `WebFetch(domain:cybermaster.space)` | Accessing the project operator domain referenced in role configuration. | Required when resolving operator-specific configuration. | Read-only. | +| `WebFetch(domain:community.taiga.io)` | Fetching Taiga project management documentation. | Required when working on Taiga-related roles. | Read-only. | +| `WebFetch(domain:monogramm.io)` | Fetching upstream Docker image documentation. | Required when researching images provided by this upstream. | Read-only. | +| `WebFetch(domain:ghcr.io)` | Fetching GitHub Container Registry image metadata. | Required for image version lookups. | Read-only. | +| `WebFetch(domain:letsencrypt.org)` | Fetching Let's Encrypt ACME documentation and root certificates. | Required when working on TLS-related roles. | Read-only. | +| `WebFetch(domain:hcaptcha.com)` | Fetching hCaptcha integration documentation. | Required when working on hCaptcha-related roles. | Read-only. | +| `WebFetch(domain:gstatic.com)` | Fetching Google static assets referenced by certain frontend roles. | Required when inspecting frontend asset behavior. | Read-only. | + +## Ask Permissions ⚠️ + +These operations pause and require explicit operator approval before executing. + +| Permission | When | Why approval is required | Security | +|---|---|---|---| +| `git commit*` | Creating a permanent history entry. | The operator MUST review the staged diff and message before committing. | Commits are persistent and visible to all contributors after push. | +| `git push*` | Publishing changes to the remote. | Cannot be undone without a force-push. | Exposes changes to all repository collaborators and CI. | +| `docker run*` | Starting a standalone container outside the compose stack. | Each invocation carries a unique risk profile depending on flags. | Can mount host paths, expose ports, and run privileged containers. | +| `curl*` | Making HTTP requests to arbitrary URLs. | Can transmit environment variables and credentials to external endpoints. | Risk depends entirely on the URL and flags used. Every invocation MUST be reviewed. | +| `gh api*` | Making direct GitHub REST or GraphQL API calls. | Can modify branch protection, secrets, webhooks, collaborators, and workflow triggers. | Supports arbitrary HTTP methods (`-X POST/PATCH/DELETE`). Each invocation MUST be reviewed individually. | + +## Deny Rules 🚫 + +These operations are unconditionally blocked, regardless of any `allow` entry. + +| Permission | Reason | +|---|---| +| `git push --force*` | Rewrites remote history. Can permanently destroy other contributors' work. | +| `git reset --hard*` | Discards all uncommitted local changes without any recovery path. | +| `rm -rf*` | Recursive force-delete with no confirmation and no undo. | +| `sudo*` | Prevents privilege escalation to root on the host system. | + +## Sandbox 🏖️ + +### Write Scope + +The agent MAY write to `.` (the repository root) and `/tmp`. All other paths are read-only by default. + +### Read Restrictions + +The following directories are never readable, even if a task explicitly requests access: + +| Path | What it protects | +|---|---| +| `~/.ssh` | SSH private keys. | +| `~/.gnupg` | GPG keys and keyrings. | +| `~/.kube` | Kubernetes cluster credentials. | +| `~/.aws` | AWS access keys and configuration. | +| `~/.config/gcloud` | Google Cloud service account credentials. | + +## Local Overrides 🖥️ + +Contributors MAY extend project permissions via `.claude/settings.local.json`. This file is git-ignored and applies only to the local machine. + +| Rule | Description | +|---|---| +| MUST NOT weaken `deny` | Local overrides cannot lift unconditional blocks defined in `settings.json`. | +| Machine-specific entries MUST stay local | Absolute paths, process IDs, and debug tooling MUST NOT be promoted to `settings.json`. | +| Shared permissions SHOULD be promoted | Permissions useful for all contributors SHOULD be added to `settings.json` instead of staying local. | +| Keep overrides minimal | Entries already covered by project-level wildcards SHOULD be removed from `settings.local.json`. | diff --git a/docs/contributing/tools/agents.md b/docs/contributing/tools/agents/common.md similarity index 63% rename from docs/contributing/tools/agents.md rename to docs/contributing/tools/agents/common.md index 9f55fdffa1..0ac9ac7ca7 100644 --- a/docs/contributing/tools/agents.md +++ b/docs/contributing/tools/agents/common.md @@ -2,13 +2,14 @@ AI assistants are welcome, but they MUST follow the same workflow as humans. -- You MUST treat [AGENTS.md](../../../AGENTS.md) as the entry point for all agent-specific execution instructions. Tool-specific files such as `CLAUDE.md` and `GEMINI.md` extend `AGENTS.md` and MUST NOT contradict it. +- You MUST treat [AGENTS.md](../../../../AGENTS.md) as the entry point for all agent-specific execution instructions. Tool-specific files such as `CLAUDE.md` and `GEMINI.md` extend `AGENTS.md` and MUST NOT contradict it. - You MUST NOT invent commands, workflows, or files that do not exist. - You MUST NEVER expose secrets in prompts, code, screenshots, or logs. - You MUST treat AI output as a draft that must be reviewed for wrong assumptions, duplicate logic, and security mistakes. - You MUST keep explanations simple and explicit. - You MUST state assumptions clearly. -For tool-specific configuration and additional instructions, see [CLAUDE.md](../../../CLAUDE.md) and [GEMINI.md](../../../GEMINI.md). +For tool-specific configuration and additional instructions, see [CLAUDE.md](../../../../CLAUDE.md) and [GEMINI.md](../../../../GEMINI.md). +For a full reference of permitted Claude Code operations and their security rationale, see [claude.md](claude.md). For further support, visit the AI forum at [s.infinito.nexus/aihub](https://s.infinito.nexus/aihub) or join the Matrix group [#ai:infinito.nexus](https://matrix.to/#/#ai:infinito.nexus). diff --git a/docs/contributing/tools/make.md b/docs/contributing/tools/make.md index 42eb5d51e3..96ba8222e6 100644 --- a/docs/contributing/tools/make.md +++ b/docs/contributing/tools/make.md @@ -56,6 +56,7 @@ For rules on how to write and structure the `Makefile` itself, see [makefile.md] | Setup development | `make mark-development` | Creates the development setup marker. | Use this when you want to prepare a development-specific setup state. | | Bootstrap | `make bootstrap` | Installs dependencies and prepares the project. | Use this on a fresh machine or a new checkout. | | Setup clean | `make setup-clean` | Cleans ignored files and then runs setup. | Use this when you want a clean setup pass. | +| Mark scripts executable | `make chmod-scripts` | Marks all `.sh` files under `scripts/` as executable. | Use this after cloning or when a script loses its executable bit. | | List roles | `make list` | Prints the repository role list. | Use this when you need the current role inventory. | | Tree view | `make tree` | Prints the repository tree. | Use this when you want a compact structural overview. | | Meta graph inputs | `make mig` | Builds the meta graph inputs from `list` and `tree`. | Use this when you are generating or refreshing meta graph data. | From f1ea036bd22e2209aaf5641b2ea256b271175615 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 14 Apr 2026 23:07:23 +0200 Subject: [PATCH 31/55] fix(ci): resolve test-development, nextcloud, and container CA failures - plugins/lookup/config.py: honor default by setting skip_missing_app=not strict so lookup('config', app, path, default) returns the default when the app is missing from the applications dict, instead of raising during early constructor phases. Fixes 5 test-development jobs. - roles/web-app-nextcloud/files/playwright.spec.js: replace unsupported .toSatisfy() with a boolean check inside expect.poll() + .toBe(true). Fixes Deploy web-app-nextcloud. - roles/sys-svc-container/files/container.py: when the target image has no ENTRYPOINT, inject the internal CA as a volume plus NODE_EXTRA_CA_CERTS, SSL_CERT_FILE, REQUESTS_CA_BUNDLE and CURL_CA_BUNDLE instead of falling back to a plain 'docker run' without CA trust. Fixes npm UNABLE_TO_VERIFY_LEAF_SIGNATURE inside Microsoft Playwright images for moodle, prometheus and onlyoffice deploys. - tests/unit/roles/sys-svc-container/files/test_container.py: cover the new no-ENTRYPOINT CA-injection path. Note: web-app-mini-qr 'lookup ghcr.io: no such host' is not addressed here and likely needs a separate investigation of CoreDNS forwarding on the CI runner. Co-Authored-By: Claude Sonnet 4.6 --- plugins/lookup/config.py | 2 +- roles/sys-svc-container/files/container.py | 26 ++++++++- .../files/playwright.spec.js | 8 +-- .../sys-svc-container/files/test_container.py | 56 +++++++++++++++++++ 4 files changed, 84 insertions(+), 8 deletions(-) diff --git a/plugins/lookup/config.py b/plugins/lookup/config.py index 58c15c6c76..389c28a384 100644 --- a/plugins/lookup/config.py +++ b/plugins/lookup/config.py @@ -53,7 +53,7 @@ class LookupModule(LookupBase): config_path=config_path, strict=strict, default=default_value, - skip_missing_app=False, + skip_missing_app=not strict, ) # lookup plugins must return a list diff --git a/roles/sys-svc-container/files/container.py b/roles/sys-svc-container/files/container.py index 8fbd24e651..9fcc63cbbf 100644 --- a/roles/sys-svc-container/files/container.py +++ b/roles/sys-svc-container/files/container.py @@ -367,9 +367,31 @@ def container_run(argv: List[str], debug: bool, with_ca: bool) -> int: if not ep: warn( "Image has no ENTRYPOINT and none was provided. " - "Running without CA wrapper." + "Injecting CA env vars without entrypoint wrapper." + ) + # Inject CA cert as a volume + env vars so Node.js (NODE_EXTRA_CA_CERTS), + # curl (CURL_CA_BUNDLE), Python requests (REQUESTS_CA_BUNDLE), and other + # tools can trust the internal CA even without a wrapper entrypoint. + ca_inject_opts: List[str] = [ + "-v", + f"{ca_host}:{ca_container}:ro", + "-e", + f"CA_TRUST_CERT={ca_container}", + "-e", + f"CA_TRUST_NAME={trust_name}", + "-e", + f"NODE_EXTRA_CA_CERTS={ca_container}", + "-e", + f"SSL_CERT_FILE={ca_container}", + "-e", + f"REQUESTS_CA_BUNDLE={ca_container}", + "-e", + f"CURL_CA_BUNDLE={ca_container}", + ] + return exec_docker( + ["docker", "run"] + run_opts + ca_inject_opts + [image] + user_args, + debug=debug, ) - return exec_docker(["docker", "run", *argv], debug=debug) final_cmd.extend(ep) final_cmd.extend(user_args) diff --git a/roles/web-app-nextcloud/files/playwright.spec.js b/roles/web-app-nextcloud/files/playwright.spec.js index 3caff74c5c..667e11cc6b 100644 --- a/roles/web-app-nextcloud/files/playwright.spec.js +++ b/roles/web-app-nextcloud/files/playwright.spec.js @@ -419,17 +419,15 @@ test("dashboard to nextcloud login", async ({ page }) => { async () => { const iframeHandle = await nextcloudIframe.elementHandle(); const iframeFrame = iframeHandle ? await iframeHandle.contentFrame() : null; - - return iframeFrame ? iframeFrame.url() : ""; + const currentUrl = iframeFrame ? iframeFrame.url() : ""; + return currentUrl.includes(expectedOidcAuthUrl) || currentUrl.startsWith(expectedNextcloudBaseUrl); }, { timeout: 60_000, message: `Expected Nextcloud iframe to load either the Keycloak OIDC login or the standalone Nextcloud login page` } ) - .toSatisfy((currentUrl) => { - return currentUrl.includes(expectedOidcAuthUrl) || currentUrl.startsWith(expectedNextcloudBaseUrl); - }); + .toBe(true); await enterNextcloudLoginThroughVisibleEntryPoint( page, diff --git a/tests/unit/roles/sys-svc-container/files/test_container.py b/tests/unit/roles/sys-svc-container/files/test_container.py index 5bda81ea39..5c47a0822f 100644 --- a/tests/unit/roles/sys-svc-container/files/test_container.py +++ b/tests/unit/roles/sys-svc-container/files/test_container.py @@ -324,6 +324,62 @@ class TestContainerWrapper(unittest.TestCase): os.environ.clear() os.environ.update(old_env) + def test_container_run_injects_ca_env_when_image_has_no_entrypoint(self): + """ + When with_ca=True, CA env is available, but the image has no ENTRYPOINT, + container_run() must inject CA env vars and volume without an entrypoint wrapper. + """ + old_env = dict(os.environ) + calls = [] + + def fake_exec_docker(cmd, debug=False): + calls.append(("exec_docker", cmd, debug)) + return 0 + + def fake_try_inspect_no_ep(image, pull_policy): + return [] # no entrypoint + + orig_exec_docker = container.exec_docker + orig_try_inspect = container.try_inspect_entrypoint_with_pull + try: + with tempfile.TemporaryDirectory() as td: + td_path = Path(td) + ca_file = td_path / "root-ca.crt" + wrapper_file = td_path / "with-ca-trust.sh" + ca_file.write_text("dummy-ca\n", encoding="utf-8") + wrapper_file.write_text("#!/bin/sh\necho ok\n", encoding="utf-8") + + os.environ["CA_TRUST_CERT_HOST"] = str(ca_file) + os.environ["CA_TRUST_WRAPPER_HOST"] = str(wrapper_file) + os.environ["CA_TRUST_NAME"] = "test-ca" + + container.exec_docker = fake_exec_docker + container.try_inspect_entrypoint_with_pull = fake_try_inspect_no_ep + + argv = ["--rm", "playwright:v1.0", "/bin/bash", "-lc", "npm install"] + rc = container.container_run(argv, debug=False, with_ca=True) + + self.assertEqual(rc, 0) + self.assertEqual(len(calls), 1) + cmd = calls[0][1] + # Must be a docker run command + self.assertEqual(cmd[0], "docker") + self.assertEqual(cmd[1], "run") + # Must contain NODE_EXTRA_CA_CERTS injection + cmd_str = " ".join(cmd) + self.assertIn("NODE_EXTRA_CA_CERTS", cmd_str) + self.assertIn("/tmp/infinito/ca/root-ca.crt", cmd_str) + # Must NOT use --entrypoint (no wrapper) + self.assertNotIn("--entrypoint", cmd_str) + # Image and original command must appear + self.assertIn("playwright:v1.0", cmd_str) + self.assertIn("npm install", cmd_str) + finally: + container.exec_docker = orig_exec_docker + container.try_inspect_entrypoint_with_pull = orig_try_inspect + os.environ.clear() + os.environ.update(old_env) + def test_container_run_with_ca_false_always_plain_docker_run(self): """ When with_ca=False, container_run() must always call plain container run (no env needed). From 3b19a92390aba3fd8fd2385e729c8cff8debe06a Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 14 Apr 2026 23:11:54 +0200 Subject: [PATCH 32/55] chore(claude): allow Bash(wait*) for background task synchronization Adds the shell built-in `wait` to the Claude Code allow-list so the agent can block on background commands started via run_in_background without prompting for operator approval. Documents the new entry in the Claude Code settings reference. Co-Authored-By: Claude Sonnet 4.6 --- .claude/settings.json | 1 + docs/contributing/tools/agents/claude.md | 1 + 2 files changed, 2 insertions(+) diff --git a/.claude/settings.json b/.claude/settings.json index 0073c12c67..d6922f6d09 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -24,6 +24,7 @@ "Bash(make*)", "Bash(act*)", "Bash(bash -n*)", + "Bash(wait*)", "Bash(python3*)", "Bash(python*)", diff --git a/docs/contributing/tools/agents/claude.md b/docs/contributing/tools/agents/claude.md index 28d9745d7d..80bdd06150 100644 --- a/docs/contributing/tools/agents/claude.md +++ b/docs/contributing/tools/agents/claude.md @@ -57,6 +57,7 @@ Claude Code evaluates each tool call against three ordered lists: | `make*` | Running any target defined in the repository `Makefile`. | Make is the primary command surface covering install, test, lint, build, deploy, and cleanup. | The full wildcard is broad. The `Makefile` MUST NOT expose targets that run privileged or destructive operations without explicit guards. New make targets SHOULD be reviewed before merging. | | `act*` | Running GitHub Actions workflows locally via Act. | Used by `make act-*` targets for local CI simulation. | Act pulls Docker images and executes workflow steps locally. Workflows MUST NOT contain untrusted third-party actions before running. | | `bash -n*` | Syntax-checking shell scripts before executing them. | `bash -n` is a dry-run parse that catches syntax errors safely. | No code is executed. Side-effect-free. | +| `wait*` | Waiting for background tasks (started via `run_in_background`) to complete. | The agent starts long-running commands in the background and MUST be able to block on their completion without operator approval. | Shell built-in. No file or network side-effects on its own; only observes child process state. | ### Python 🐍 From 2309ba8e11fc88dd010e53f19b5a4bd9003fa790 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 14 Apr 2026 23:11:54 +0200 Subject: [PATCH 33/55] chore(claude): allow Bash(wait*) for background task synchronization Adds the shell built-in `wait` to the Claude Code allow-list so the agent can block on background commands started via run_in_background without prompting for operator approval. Documents the new entry in the Claude Code settings reference. Co-Authored-By: Claude Sonnet 4.6 --- .claude/settings.json | 1 + docs/contributing/tools/agents/claude.md | 1 + 2 files changed, 2 insertions(+) diff --git a/.claude/settings.json b/.claude/settings.json index 0073c12c67..d6922f6d09 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -24,6 +24,7 @@ "Bash(make*)", "Bash(act*)", "Bash(bash -n*)", + "Bash(wait*)", "Bash(python3*)", "Bash(python*)", diff --git a/docs/contributing/tools/agents/claude.md b/docs/contributing/tools/agents/claude.md index 28d9745d7d..80bdd06150 100644 --- a/docs/contributing/tools/agents/claude.md +++ b/docs/contributing/tools/agents/claude.md @@ -57,6 +57,7 @@ Claude Code evaluates each tool call against three ordered lists: | `make*` | Running any target defined in the repository `Makefile`. | Make is the primary command surface covering install, test, lint, build, deploy, and cleanup. | The full wildcard is broad. The `Makefile` MUST NOT expose targets that run privileged or destructive operations without explicit guards. New make targets SHOULD be reviewed before merging. | | `act*` | Running GitHub Actions workflows locally via Act. | Used by `make act-*` targets for local CI simulation. | Act pulls Docker images and executes workflow steps locally. Workflows MUST NOT contain untrusted third-party actions before running. | | `bash -n*` | Syntax-checking shell scripts before executing them. | `bash -n` is a dry-run parse that catches syntax errors safely. | No code is executed. Side-effect-free. | +| `wait*` | Waiting for background tasks (started via `run_in_background`) to complete. | The agent starts long-running commands in the background and MUST be able to block on their completion without operator approval. | Shell built-in. No file or network side-effects on its own; only observes child process state. | ### Python 🐍 From 77a0e16ea65f87bf7b888ed80e541a635f4cd813 Mon Sep 17 00:00:00 2001 From: Environment Test Date: Wed, 15 Apr 2026 11:15:27 +0200 Subject: [PATCH 34/55] refactor(web-app-nextcloud): consolidate oidc.flavor under compose.services.oidc Single source of truth at compose.services.oidc.flavor. Removes stray root-level keys, deletes the _applications_nextcloud_oidc_flavor helper, and switches all consumers (plugin toggles + PHP template) to direct lookups. Also fixes inherited precedence bug on plugin.enabled filters and corrects OICD/floavor typos. Co-Authored-By: Claude Opus 4.6 --- group_vars/all/00_general.yml | 15 --------------- roles/web-app-nextcloud/config/main.yml | 19 ++++++++----------- .../templates/config/oidc.config.php.j2 | 4 ++-- 3 files changed, 10 insertions(+), 28 deletions(-) diff --git a/group_vars/all/00_general.yml b/group_vars/all/00_general.yml index f2c129d5d9..91349401cd 100644 --- a/group_vars/all/00_general.yml +++ b/group_vars/all/00_general.yml @@ -59,21 +59,6 @@ ASYNC_POLL: "{{ 0 if ASYNC_ENABLED | bool else 10 }}" # Don't wait for # default value if not set via CLI (-e) or in playbook vars allowed_applications: [] -# helper -_applications_nextcloud_oidc_flavor: >- - {{ - lookup( - 'config', - 'web-app-nextcloud', - 'oidc.flavor', - ( - 'oidc_login' - if lookup('config', 'web-app-nextcloud', 'compose.services.ldap.enabled', False) - else 'sociallogin' - ) - ) - }} - # Role-based access control # @See https://en.wikipedia.org/wiki/Role-based_access_control RBAC: diff --git a/roles/web-app-nextcloud/config/main.yml b/roles/web-app-nextcloud/config/main.yml index 206049f741..9d935c21b8 100644 --- a/roles/web-app-nextcloud/config/main.yml +++ b/roles/web-app-nextcloud/config/main.yml @@ -43,6 +43,11 @@ compose: oidc: enabled: true shared: true + # flavor decides which OIDC plugin should be used. + # Available options: oidc_login, sociallogin + # @see https://apps.nextcloud.com/apps/oidc_login + # @see https://apps.nextcloud.com/apps/sociallogin + flavor: "oidc_login" coturn: # Keep dedicated TURN provider statically discoverable so normal inventory # generation and local iteration always pull in web-svc-coturn. @@ -154,12 +159,6 @@ compose: shared: true hcaptcha: enabled: "{{ HCAPTCHA_ENABLED | bool }}" - enabled: "{{ lookup('config', 'web-app-nextcloud', 'compose.services.oidc.enabled', False) }}" # Activate OIDC for Nextcloud - # floavor decides which OICD plugin should be used. - # Available options: oidc_login, sociallogin - # @see https://apps.nextcloud.com/apps/oidc_login - # @see https://apps.nextcloud.com/apps/sociallogin - flavor: "oidc_login" # Keeping on sociallogin because the other option is not implemented yet default_quota: '1000000000' # Quota to assign if no quota is specified in the OIDC response (bytes) legacy_login_mask: enabled: False # If true, then legacy login mask is shown. Otherwise just SSO @@ -171,8 +170,6 @@ performance: opcache_memory_consumption: "{{ ((ansible_facts['memtotal_mb'] | int) / 30)|int }}M" # Dynamic set memory consumption plugins_enabled: true # Implemented for speeding up testing and debugging process. For productive environments keep it true and steer the apps via the plugins config -oidc: - flavor: "{{ _applications_nextcloud_oidc_flavor }}" plugins: # List for Nextcloud Plugin Routine # Decides if plugins should be activated or deactivated @@ -313,7 +310,7 @@ plugins: enabled: true oidc_login: # Nextcloud User OIDC: integrates OpenID Connect for user authentication (https://apps.nextcloud.com/apps/oidc_login) - enabled: "{{ _applications_nextcloud_oidc_flavor=='oidc_login' | lower }}" + enabled: "{{ lookup('config', 'web-app-nextcloud', 'compose.services.oidc.flavor') == 'oidc_login' }}" incompatible_plugins: - user_oidc # Will be disabled - sociallogin # Will be disabled @@ -340,7 +337,7 @@ plugins: - fileslibreofficeedit sociallogin: # Nextcloud social login: allows authentication using social networks (https://apps.nextcloud.com/apps/sociallogin) - enabled: "{{ _applications_nextcloud_oidc_flavor=='sociallogin' | lower }}" + enabled: "{{ lookup('config', 'web-app-nextcloud', 'compose.services.oidc.flavor') == 'sociallogin' }}" incompatible_plugins: - user_oidc # Will be disabled - oidc_login # Will be disabled @@ -369,7 +366,7 @@ plugins: enabled: true # Enables the LDAP User Directory Search user_oidc: # Nextcloud User OIDC: integrates OpenID Connect for user authentication (https://apps.nextcloud.com/apps/user_oidc) - enabled: "{{ _applications_nextcloud_oidc_flavor=='user_oidc' | lower }}" + enabled: "{{ lookup('config', 'web-app-nextcloud', 'compose.services.oidc.flavor') == 'user_oidc' }}" incompatible_plugins: - oidc_login - sociallogin diff --git a/roles/web-app-nextcloud/templates/config/oidc.config.php.j2 b/roles/web-app-nextcloud/templates/config/oidc.config.php.j2 index 9d86c35812..9927ea1ad2 100644 --- a/roles/web-app-nextcloud/templates/config/oidc.config.php.j2 +++ b/roles/web-app-nextcloud/templates/config/oidc.config.php.j2 @@ -1,7 +1,7 @@ Date: Wed, 15 Apr 2026 11:38:03 +0200 Subject: [PATCH 35/55] chore(claude): allow scripts/ source+bash, prefer make targets Adds `Bash(bash scripts/*)` and `Bash(source scripts/*)` to the Claude Code allowlist so repository helper scripts (e.g. env exports in scripts/meta/env) can run without approval prompts, while still keeping arbitrary paths scoped to review. Documents both permissions in docs/contributing/tools/agents/claude.md, including the caveat that `source` bypasses the allowlist for nested commands. Extends CLAUDE.md with an explicit rule that agents MUST prefer `make` targets over direct docker/ansible/python/script invocations whenever an equivalent target exists. Co-Authored-By: Claude Opus 4.6 --- .claude/settings.json | 2 ++ CLAUDE.md | 1 + docs/contributing/tools/agents/claude.md | 2 ++ 3 files changed, 5 insertions(+) diff --git a/.claude/settings.json b/.claude/settings.json index d6922f6d09..a79dda60b6 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -24,6 +24,8 @@ "Bash(make*)", "Bash(act*)", "Bash(bash -n*)", + "Bash(bash scripts/*)", + "Bash(source scripts/*)", "Bash(wait*)", "Bash(python3*)", diff --git a/CLAUDE.md b/CLAUDE.md index 18707dfaee..3f2c91a8b9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -12,6 +12,7 @@ You MUST read `AGENTS.md` and follow all instructions in it at the start of ever ## Code Execution +- You MUST always prefer `make` targets over running underlying scripts, `docker`, `docker compose`, `ansible-playbook`, `python`, or shell invocations directly, whenever an equivalent target exists in the [`Makefile`](Makefile). Inspect the `Makefile` first and only fall back to the raw command when no target covers the operation. - You SHOULD run permitted commands (listed in [.claude/settings.json](.claude/settings.json)) directly on the host. - For commands that are NOT permitted on the host, you MUST run them inside the application containers instead. Use `make up` (or the appropriate Make target) to start the stack, then use `make exec` to open a shell inside the container. - The repository is mounted into the container at `/opt/src/infinito` (see [compose.yml](compose.yml)), so code changes are immediately available there. diff --git a/docs/contributing/tools/agents/claude.md b/docs/contributing/tools/agents/claude.md index 80bdd06150..e8b4b7946f 100644 --- a/docs/contributing/tools/agents/claude.md +++ b/docs/contributing/tools/agents/claude.md @@ -57,6 +57,8 @@ Claude Code evaluates each tool call against three ordered lists: | `make*` | Running any target defined in the repository `Makefile`. | Make is the primary command surface covering install, test, lint, build, deploy, and cleanup. | The full wildcard is broad. The `Makefile` MUST NOT expose targets that run privileged or destructive operations without explicit guards. New make targets SHOULD be reviewed before merging. | | `act*` | Running GitHub Actions workflows locally via Act. | Used by `make act-*` targets for local CI simulation. | Act pulls Docker images and executes workflow steps locally. Workflows MUST NOT contain untrusted third-party actions before running. | | `bash -n*` | Syntax-checking shell scripts before executing them. | `bash -n` is a dry-run parse that catches syntax errors safely. | No code is executed. Side-effect-free. | +| `bash scripts/*` | Executing repository helper scripts under [`scripts/`](../../../../scripts/). | Many make targets and agent workflows invoke tracked scripts directly. | Scoped to the repository `scripts/` tree. Arbitrary script paths outside `scripts/` still require approval. Script contents MUST be reviewed before merging. | +| `source scripts/*` | Loading environment variables and shell helpers from repository scripts (e.g. `scripts/meta/env/all.sh`) into the current shell. | Some tooling exports `INVENTORY_DIR`, `INFINITO_DISTRO`, and similar variables that are only usable when sourced. | Scoped to `scripts/`. `source` executes the file in the current shell and bypasses the allowlist for nested commands, so the `scripts/` tree MUST be kept free of unreviewed content. Sourcing paths outside `scripts/` still requires approval. | | `wait*` | Waiting for background tasks (started via `run_in_background`) to complete. | The agent starts long-running commands in the background and MUST be able to block on their completion without operator approval. | Shell built-in. No file or network side-effects on its own; only observes child process state. | ### Python 🐍 From a2275e69919eb38d971b830dd70cffd3ff6b17ed Mon Sep 17 00:00:00 2001 From: Environment Test Date: Wed, 15 Apr 2026 12:28:44 +0200 Subject: [PATCH 36/55] docs(make): pass variables after target to match Bash(make*) permission MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reorders all documented and scripted `make` invocations from the `VAR=value make target` shell-env prefix form to the make-native `make target VAR=value` form. GNU Make auto-exports both command-line and inherited shell-env variables to recipe shells, so the change is purely about command-line shape: only the make-suffix form starts with `make` and is therefore matched by the `Bash(make*)` permission entry in .claude/settings.json, avoiding unnecessary approval prompts for agent runs. Adds an explicit CLAUDE.md rule with ✅/❌ examples and the underlying reason (permission prefix match, not Makefile semantics). Co-Authored-By: Claude Opus 4.6 --- CLAUDE.md | 4 ++++ docs/agents/action/iteration.md | 20 +++++++++---------- docs/contributing/actions/testing.md | 8 ++++---- docs/contributing/actions/testing/external.md | 2 +- .../actions/testing/integration.md | 4 ++-- docs/contributing/actions/testing/lint.md | 2 +- .../actions/testing/playwright.md | 4 ++-- docs/contributing/actions/testing/unit.md | 4 ++-- docs/contributing/environment/hardware.md | 8 ++++---- docs/contributing/environment/setup.md | 2 +- docs/contributing/tools/make.md | 4 ++-- .../001-nextcloud-talk-turn-relay.md | 2 +- .../002-service-registry-refactoring.md | 2 +- .../deploy/local/deploy/reuse-kept-all.sh | 4 ++-- .../tests/environment/07_deploy_minimal.sh | 2 +- .../environment/08_deploy_performance.sh | 2 +- 16 files changed, 39 insertions(+), 35 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 3f2c91a8b9..6154f85902 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -13,6 +13,10 @@ You MUST read `AGENTS.md` and follow all instructions in it at the start of ever ## Code Execution - You MUST always prefer `make` targets over running underlying scripts, `docker`, `docker compose`, `ansible-playbook`, `python`, or shell invocations directly, whenever an equivalent target exists in the [`Makefile`](Makefile). Inspect the `Makefile` first and only fall back to the raw command when no target covers the operation. +- When passing variables to `make`, you MUST pass them **after** the target as make-style arguments, NOT as a shell-env prefix before `make`. This keeps the command matchable by the `Bash(make*)` permission entry in [.claude/settings.json](.claude/settings.json) and avoids unnecessary approval prompts. + - ✅ `make deploy-fresh-purged-apps APPS=web-app-nextcloud SERVICES_DISABLED="matomo"` + - ❌ `SERVICES_DISABLED="matomo" APPS=web-app-nextcloud make deploy-fresh-purged-apps` + - GNU Make automatically exports both command-line variables and inherited shell-env variables to recipe shells, so both forms are functionally equivalent. The make-suffix form is REQUIRED for agent use solely because of the `Bash(make*)` permission prefix match. - You SHOULD run permitted commands (listed in [.claude/settings.json](.claude/settings.json)) directly on the host. - For commands that are NOT permitted on the host, you MUST run them inside the application containers instead. Use `make up` (or the appropriate Make target) to start the stack, then use `make exec` to open a shell inside the container. - The repository is mounted into the container at `/opt/src/infinito` (see [compose.yml](compose.yml)), so code changes are immediately available there. diff --git a/docs/agents/action/iteration.md b/docs/agents/action/iteration.md index 725b56ae77..d35ccc2db6 100644 --- a/docs/agents/action/iteration.md +++ b/docs/agents/action/iteration.md @@ -6,16 +6,16 @@ Use this page when you are iterating on a local app deploy during debugging or d - Before starting the loop, you MUST propose disabling all non-necessary services via `SERVICES_DISABLED` to reduce resource usage. In the typical case, this means keeping only the database and disabling everything else. Only proceed without this proposal if the user has already confirmed a full-stack setup. - You MUST run `make test` before every deploy. Only proceed with the deploy if all tests pass. -- Unless the user explicitly says to reuse the existing setup, you MUST start once with `APPS= make deploy-fresh-purged-apps` to establish the baseline inventory and clean app state. Set `FULL_CYCLE=true` to also run the async update pass (pass 2). +- Unless the user explicitly says to reuse the existing setup, you MUST start once with `make deploy-fresh-purged-apps APPS=` to establish the baseline inventory and clean app state. Set `FULL_CYCLE=true` to also run the async update pass (pass 2). - You MUST NOT run more than one deploy command at the same time. Deployments MUST be executed serially, never in parallel. -- To speed up debugging, you MAY pass multiple apps at once, e.g. `APPS=" " make deploy-fresh-purged-apps`. -- After that, you MUST use `APPS= make deploy-reuse-kept-apps` for the default edit-fix-redeploy loop. -- Do NOT rerun `APPS= make deploy-fresh-purged-apps` just because a deploy failed or you changed code. That restarts the stack unnecessarily and burns time. -- If the same failure still reproduces on the reuse path and you want to test whether app entity state is involved, use `APPS= make deploy-reuse-purged-apps` once. -- After that targeted purge check, you MUST return to `APPS= make deploy-reuse-kept-apps`. -- Only go back to `APPS= make deploy-fresh-purged-apps` if you have concrete evidence that the inventory or host stack is broken, or you intentionally need a fresh single-app baseline again. -- Network or DNS failures during a local deploy count as concrete evidence that the host stack is broken. In that case, the next retry MUST be `APPS= make deploy-fresh-purged-apps` so the container stack is re-initialized. -- If you need to validate the single-app init/deploy path separately, use `APPS= make deploy-fresh-kept-apps`. It checks the clean single-app setup apart from the faster reuse path. +- To speed up debugging, you MAY pass multiple apps at once, e.g. `make deploy-fresh-purged-apps APPS=" "`. +- After that, you MUST use `make deploy-reuse-kept-apps APPS=` for the default edit-fix-redeploy loop. +- Do NOT rerun `make deploy-fresh-purged-apps APPS=` just because a deploy failed or you changed code. That restarts the stack unnecessarily and burns time. +- If the same failure still reproduces on the reuse path and you want to test whether app entity state is involved, use `make deploy-reuse-purged-apps APPS=` once. +- After that targeted purge check, you MUST return to `make deploy-reuse-kept-apps APPS=`. +- Only go back to `make deploy-fresh-purged-apps APPS=` if you have concrete evidence that the inventory or host stack is broken, or you intentionally need a fresh single-app baseline again. +- Network or DNS failures during a local deploy count as concrete evidence that the host stack is broken. In that case, the next retry MUST be `make deploy-fresh-purged-apps APPS=` so the container stack is re-initialized. +- If you need to validate the single-app init/deploy path separately, use `make deploy-fresh-kept-apps APPS=`. It checks the clean single-app setup apart from the faster reuse path. ## Workflow Loop @@ -25,7 +25,7 @@ Use this page when you are iterating on a local app deploy during debugging or d - If the workflow uses a distro matrix, you MUST iterate on one distro at a time instead of rerunning the whole matrix during the default debug loop. - Debian SHOULD be the preferred distro for that focused workflow iteration unless the failure is clearly distro-specific or the user asked for a different distro. - When you constrain an Act matrix run through `ACT_MATRIX`, you MUST use Act's `key:value` syntax instead of `key=value`. Otherwise Act may ignore the filter and rerun the whole matrix. -- For `.github/workflows/test-environment.yml`, the preferred focused Debian example is `ACT_WORKFLOW=.github/workflows/test-environment.yml ACT_JOB=test-environment ACT_MATRIX='dev_runtime_image:debian:bookworm' make act-workflow`. +- For `.github/workflows/test-environment.yml`, the preferred focused Debian example is `make act-workflow ACT_WORKFLOW=.github/workflows/test-environment.yml ACT_JOB=test-environment ACT_MATRIX='dev_runtime_image:debian:bookworm'`. - You SHOULD avoid jumping straight to repeated remote CI reruns when `make act-workflow` can validate the workflow locally and the user agreed to use it. - You MAY widen the scope to `make act-app` or `make act-all` when the problem spans more than one workflow or `make act-workflow` is too narrow for the failure. diff --git a/docs/contributing/actions/testing.md b/docs/contributing/actions/testing.md index 07274edfe7..fc7c1cd285 100644 --- a/docs/contributing/actions/testing.md +++ b/docs/contributing/actions/testing.md @@ -38,10 +38,10 @@ Use the following table when you need realistic local deployment validation or a | Category | Command | What it does | When to use it | |---|---|---|---| -| Local deploy | `APPS=web-app-nextcloud make deploy-fresh-kept-apps` | Creates the needed inventory and deploys one or more apps. | Fresh deploy for a specific app set. | -| Local deploy | `APPS=web-app-nextcloud make deploy-reuse-kept-apps` | Reuses an existing `devices.yml` inventory and redeploys one or more apps quickly. | Fast reuse path. | -| Local deploy | `APPS=web-app-nextcloud make deploy-reuse-purged-apps` | Reuses an existing `devices.yml` inventory, purges the entity first, and redeploys one or more apps quickly. | Fast reuse path after a state reset. | -| Local deploy and E2E | `APPS=web-app-matomo make deploy-fresh-purged-apps` | Runs a dedicated local validation flow for one or more apps against the dev stack, creating and re-initializing the inventory first. | Baseline and recovery path. | +| Local deploy | `make deploy-fresh-kept-apps APPS=web-app-nextcloud` | Creates the needed inventory and deploys one or more apps. | Fresh deploy for a specific app set. | +| Local deploy | `make deploy-reuse-kept-apps APPS=web-app-nextcloud` | Reuses an existing `devices.yml` inventory and redeploys one or more apps quickly. | Fast reuse path. | +| Local deploy | `make deploy-reuse-purged-apps APPS=web-app-nextcloud` | Reuses an existing `devices.yml` inventory, purges the entity first, and redeploys one or more apps quickly. | Fast reuse path after a state reset. | +| Local deploy and E2E | `make deploy-fresh-purged-apps APPS=web-app-matomo` | Runs a dedicated local validation flow for one or more apps against the dev stack, creating and re-initializing the inventory first. | Baseline and recovery path. | | Full local validation | `make deploy-fresh-kept-all` | Builds the broader local deployment flow across apps. | Broad coverage when you explicitly need it. | | Local reset | `make container-refresh-inventory` | Recreates the local inventory without deploying apps. | Use this when your local inventory is broken or you want a clean reset. | | Local cleanup | `make container-purge-system` | Deletes local deploy artifacts and cleanup data. | Use this only when you really want to remove local state. | diff --git a/docs/contributing/actions/testing/external.md b/docs/contributing/actions/testing/external.md index b69556fb9b..876c180e12 100644 --- a/docs/contributing/actions/testing/external.md +++ b/docs/contributing/actions/testing/external.md @@ -67,7 +67,7 @@ make test-external To scope the run to one file: ```bash -TEST_PATTERN=test_image_versions.py make test-external +make test-external TEST_PATTERN=test_image_versions.py ``` ## CI Workflow 🤖 diff --git a/docs/contributing/actions/testing/integration.md b/docs/contributing/actions/testing/integration.md index e1c3a6a0c4..98505aea61 100644 --- a/docs/contributing/actions/testing/integration.md +++ b/docs/contributing/actions/testing/integration.md @@ -40,8 +40,8 @@ Use `TEST_PATTERN` to scope the test run to a single file or a glob: ```bash # Run a single integration test file -TEST_PATTERN=test_my_module.py make test-integration +make test-integration TEST_PATTERN=test_my_module.py # Run all files matching a prefix -TEST_PATTERN=test_applications*.py make test-integration +make test-integration TEST_PATTERN=test_applications*.py ``` diff --git a/docs/contributing/actions/testing/lint.md b/docs/contributing/actions/testing/lint.md index 5c18a41bf3..ead4446c25 100644 --- a/docs/contributing/actions/testing/lint.md +++ b/docs/contributing/actions/testing/lint.md @@ -34,5 +34,5 @@ Use `TEST_PATTERN` to scope the lint test run to a single file: ```bash # Run lint tests for a specific file -TEST_PATTERN=test_my_role.py make test-lint +make test-lint TEST_PATTERN=test_my_role.py ``` diff --git a/docs/contributing/actions/testing/playwright.md b/docs/contributing/actions/testing/playwright.md index a5c4623599..3b2c15b49f 100644 --- a/docs/contributing/actions/testing/playwright.md +++ b/docs/contributing/actions/testing/playwright.md @@ -9,7 +9,7 @@ For implementation guidance when writing or updating role-local files, see - [Playwright](https://playwright.dev/) runs inside Docker via the shared `test-e2e-playwright` role. - There is no standalone `make` target for Playwright. Tests run as part of local deploy flows - (e.g. `FULL_CYCLE=true APPS=web-app-matomo make deploy-fresh-purged-apps`). + (e.g. `make deploy-fresh-purged-apps APPS=web-app-matomo FULL_CYCLE=true`). ## When to Write ✍️ @@ -94,7 +94,7 @@ Generated files are persisted in the local workspace (git-ignored). Copy the rel 2. Build hypotheses about the expected user flows before writing tests. 3. Optionally record a draft with Playwright codegen or `playwright-recorder`. 4. Write or update `files/playwright.spec.js` and `templates/playwright.env.j2`. -5. Run the relevant deploy flow (e.g. `FULL_CYCLE=true APPS= make deploy-fresh-purged-apps`). +5. Run the relevant deploy flow (e.g. `make deploy-fresh-purged-apps APPS= FULL_CYCLE=true`). 6. Run `make trust-ca` and open the app in your browser to confirm the flow manually. 7. Inspect the browser console for errors when the flow depends on injected JavaScript. 8. Verify the suite finishes in a logged-out state. diff --git a/docs/contributing/actions/testing/unit.md b/docs/contributing/actions/testing/unit.md index 8267f5f0c5..12fa3ae3a1 100644 --- a/docs/contributing/actions/testing/unit.md +++ b/docs/contributing/actions/testing/unit.md @@ -33,8 +33,8 @@ Use `TEST_PATTERN` to scope the test run to a single file or a glob: ```bash # Run a single test file -TEST_PATTERN=test_my_module.py make test-unit +make test-unit TEST_PATTERN=test_my_module.py # Run all files matching a prefix -TEST_PATTERN=test_applications*.py make test-unit +make test-unit TEST_PATTERN=test_applications*.py ``` diff --git a/docs/contributing/environment/hardware.md b/docs/contributing/environment/hardware.md index e50aa0c5dd..cef79e3871 100644 --- a/docs/contributing/environment/hardware.md +++ b/docs/contributing/environment/hardware.md @@ -40,7 +40,7 @@ For a broad stack like the Community Hub, you SHOULD start only the services you You MAY set the `SERVICES_DISABLED` environment variable before creating the inventory to disable services automatically across all applications without editing any file: ```bash -SERVICES_DISABLED="matomo" make deploy-fresh-purged-apps APPS=web-app-discourse +make deploy-fresh-purged-apps APPS=web-app-discourse SERVICES_DISABLED="matomo" ``` This sets `enabled: false` and `shared: false` for every listed service in the generated inventory. See [variables.md](variables.md) for details. @@ -73,13 +73,13 @@ On small machines, you SHOULD limit validation to the role you are touching. For Discourse, start with: ```bash -SERVICES_DISABLED="matomo" APPS=web-app-discourse make deploy-fresh-purged-apps +make deploy-fresh-purged-apps APPS=web-app-discourse SERVICES_DISABLED="matomo" ``` If the local inventory and stack already exist, you SHOULD reuse them: ```bash -SERVICES_DISABLED="matomo" APPS=web-app-discourse make deploy-reuse-kept-apps +make deploy-reuse-kept-apps APPS=web-app-discourse SERVICES_DISABLED="matomo" ``` You SHOULD use `make deploy-fresh-kept-all` only when you need broad coverage and have enough time and resources. @@ -106,7 +106,7 @@ On WSL2 or Windows, you MUST pass the additional flag to also configure and run Windows manages its own system caches independently from Linux and Docker: ```bash -PURGE_WINDOWS_CLEANMGR_SETUP=true make system-purge +make system-purge PURGE_WINDOWS_CLEANMGR_SETUP=true ``` ### Further Information diff --git a/docs/contributing/environment/setup.md b/docs/contributing/environment/setup.md index ddae0e26cd..df8d594082 100644 --- a/docs/contributing/environment/setup.md +++ b/docs/contributing/environment/setup.md @@ -81,7 +81,7 @@ The repository already contains a modular environment test suite at [scripts/tes | 2 | `make environment-bootstrap` | Prepares the host machine for local development. | | 3 | `make up` | Starts the development stack. | | 4 | `make test` | Runs the main combined validation flow. | -| 5 | `APPS=web-app-matomo make deploy-fresh-purged-apps` | Runs the baseline validation path for one concrete app. For the retry-loop policy, see [Iteration](../../agents/action/iteration.md). | +| 5 | `make deploy-fresh-purged-apps APPS=web-app-matomo` | Runs the baseline validation path for one concrete app. For the retry-loop policy, see [Iteration](../../agents/action/iteration.md). | | 6 | `make trust-ca` | Makes the generated local certificates trusted by the host browser. | | 7 | `make down` | Stops the running development stack. | | 8 | `make environment-teardown` | Cleans up host-side development environment changes. | diff --git a/docs/contributing/tools/make.md b/docs/contributing/tools/make.md index 96ba8222e6..6555649d2b 100644 --- a/docs/contributing/tools/make.md +++ b/docs/contributing/tools/make.md @@ -106,7 +106,7 @@ For rules on how to write and structure the `Makefile` itself, see [makefile.md] | Act workflow file | `make act-workflow` | Runs one selected workflow with Act. | Use this when you want to focus on a single workflow file. | - If you need to constrain a workflow matrix, set `ACT_MATRIX` with Act's `key:value` syntax, not `key=value`. -- Example: `ACT_WORKFLOW=.github/workflows/test-environment.yml ACT_JOB=test-environment ACT_MATRIX='dev_runtime_image:debian:bookworm' make act-workflow` +- Example: `make act-workflow ACT_WORKFLOW=.github/workflows/test-environment.yml ACT_JOB=test-environment ACT_MATRIX='dev_runtime_image:debian:bookworm'` ## Cleanup 🗑️ @@ -125,7 +125,7 @@ For rules on how to write and structure the `Makefile` itself, see [makefile.md] | Category | Command | What it does | When to use it | |---|---|---|---| | Fresh kept apps | `make deploy-fresh-kept-apps` | Creates a new inventory and deploys one or more apps. | Use this for a fresh deploy of a specific app set. | -| Fresh purged apps | `make deploy-fresh-purged-apps` | Recreates the stack, purges app state, and deploys (pass 1 only by default). Set `FULL_CYCLE=true` to also run the async update pass (pass 2). | Default: deploy only. `FULL_CYCLE=true make deploy-fresh-purged-apps` for the full cycle. | +| Fresh purged apps | `make deploy-fresh-purged-apps` | Recreates the stack, purges app state, and deploys (pass 1 only by default). Set `FULL_CYCLE=true` to also run the async update pass (pass 2). | Default: deploy only. `make deploy-fresh-purged-apps FULL_CYCLE=true` for the full cycle. | | Reuse kept apps | `make deploy-reuse-kept-apps` | Reuses an existing inventory and redeploys one or more apps quickly. | Use this for the fast reuse path. | | Reuse purged apps | `make deploy-reuse-purged-apps` | Reuses an existing inventory, purges the app state first, and redeploys one or more apps quickly. | Use this when you want a fast reset-and-redeploy path. | | Fresh kept all | `make deploy-fresh-kept-all` | Builds the broader local deployment flow across apps. | Use this when you explicitly need broad coverage. | diff --git a/docs/requirements/001-nextcloud-talk-turn-relay.md b/docs/requirements/001-nextcloud-talk-turn-relay.md index 29188753f1..a2318ea2c0 100644 --- a/docs/requirements/001-nextcloud-talk-turn-relay.md +++ b/docs/requirements/001-nextcloud-talk-turn-relay.md @@ -11,5 +11,5 @@ As an administrator, I want Nextcloud Talk to use a dedicated TURN server so tha - [x] The required firewall rules are present for the TURN service ports and relay UDP range used by the deployment. - [x] The Nextcloud Talk administration view shows a valid STUN/TURN configuration without related errors. - [x] Calls with at least six participants complete reliably without missing video streams, partial connections, or browser-side ICE connection failures caused by missing relay candidates. -- [x] Implementation and validation for `web-app-nextcloud` follow the local iteration loop from [iteration.md](../agents/action/iteration.md), starting with `APPS=web-app-nextcloud make deploy-fresh-purged-apps` for the baseline and continuing with `APPS=web-app-nextcloud make deploy-reuse-kept-apps` for normal follow-up iterations. +- [x] Implementation and validation for `web-app-nextcloud` follow the local iteration loop from [iteration.md](../agents/action/iteration.md), starting with `make deploy-fresh-purged-apps APPS=web-app-nextcloud` for the baseline and continuing with `make deploy-reuse-kept-apps APPS=web-app-nextcloud` for normal follow-up iterations. - [x] The existing role-local Playwright coverage in [playwright.spec.js](../../roles/web-app-nextcloud/files/playwright.spec.js) and [playwright.env.j2](../../roles/web-app-nextcloud/templates/playwright.env.j2) is extended as far as the local setup allows, and when `compose.services.talk.enabled` is true the Playwright flow verifies in the Nextcloud admin interface that the Talk-related TURN/STUN integration is implemented correctly. diff --git a/docs/requirements/002-service-registry-refactoring.md b/docs/requirements/002-service-registry-refactoring.md index bb771ad042..a61de3d653 100644 --- a/docs/requirements/002-service-registry-refactoring.md +++ b/docs/requirements/002-service-registry-refactoring.md @@ -221,7 +221,7 @@ that app. Do not carry over assumptions from the previous app. 1. Read [iteration.md](../agents/action/iteration.md) before starting each app. 2. Implement the role-local changes for the current app. -3. Deploy: `APPS= make deploy-fresh-purged-apps` +3. Deploy: `make deploy-fresh-purged-apps APPS=` 4. Follow the inspect-fix-redeploy loop from [iteration.md](../agents/action/iteration.md) until the app works end to end. 5. Run `make test` — all tests MUST pass before moving to the next app. 6. Check off the relevant Acceptance Criteria above if fully covered by this app. diff --git a/scripts/tests/deploy/local/deploy/reuse-kept-all.sh b/scripts/tests/deploy/local/deploy/reuse-kept-all.sh index 2be1d931de..da1c716f74 100755 --- a/scripts/tests/deploy/local/deploy/reuse-kept-all.sh +++ b/scripts/tests/deploy/local/deploy/reuse-kept-all.sh @@ -13,7 +13,7 @@ set -euo pipefail # DEBUG (default: false) # # Notes: -# - This does NOT create the inventory. Run APPS= make deploy-fresh-kept-apps first. +# - This does NOT create the inventory. Run make deploy-fresh-kept-apps APPS= first. # - We recompute the app list to keep behavior deterministic with filters. SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" @@ -38,7 +38,7 @@ pw_file="${inv_dir}/.password" if [[ ! -f "${inv_file}" ]]; then echo "ERROR: inventory not found: ${inv_file}" >&2 - echo "Run: APPS= make deploy-fresh-kept-apps" >&2 + echo "Run: make deploy-fresh-kept-apps APPS=" >&2 exit 2 fi diff --git a/scripts/tests/environment/07_deploy_minimal.sh b/scripts/tests/environment/07_deploy_minimal.sh index cdf70cc9b8..d39ca6cb52 100755 --- a/scripts/tests/environment/07_deploy_minimal.sh +++ b/scripts/tests/environment/07_deploy_minimal.sh @@ -7,7 +7,7 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" source "${SCRIPT_DIR}/lib.sh" echo "Deploying dashboard with matomo disabled to verify SERVICES_DISABLED suppresses the shared service in the inventory." -SERVICES_DISABLED="matomo" make deploy-fresh-purged-apps APPS="${DASHBOARD_APP}" +make deploy-fresh-purged-apps APPS="${DASHBOARD_APP}" SERVICES_DISABLED="matomo" inspect echo "Trusting the local CA certificate so HTTPS endpoints are reachable from the host." diff --git a/scripts/tests/environment/08_deploy_performance.sh b/scripts/tests/environment/08_deploy_performance.sh index e745a91806..bf84b933e7 100755 --- a/scripts/tests/environment/08_deploy_performance.sh +++ b/scripts/tests/environment/08_deploy_performance.sh @@ -7,7 +7,7 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" source "${SCRIPT_DIR}/lib.sh" echo "Deploying matomo (full cycle: deploy + update pass) so it becomes reachable via its dedicated inventory entry." -FULL_CYCLE=true make deploy-fresh-purged-apps APPS="${MATOMO_APP}" +make deploy-fresh-purged-apps APPS="${MATOMO_APP}" FULL_CYCLE=true inspect echo "Re-trusting the CA after the fresh deploy rebuilt the certificates." From f0609c91a3718f4c075155feca0fafc1402a7704 Mon Sep 17 00:00:00 2001 From: Environment Test Date: Wed, 15 Apr 2026 12:54:32 +0200 Subject: [PATCH 37/55] chore(gitignore): ignore *.lock files Co-Authored-By: Claude Opus 4.6 --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 7bb558e92b..0bf847080c 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,4 @@ env.development logs/ job-logs.txt .claude/skills +*.lock From 758438057394e97e309f768cda28c81a682cee27 Mon Sep 17 00:00:00 2001 From: Environment Test Date: Wed, 15 Apr 2026 16:42:40 +0200 Subject: [PATCH 38/55] chore(claude): generalize awk permission, drop stale entries Replaces two over-specific `Bash(awk ...)` allowlist entries (full paths and exact patterns that would never match again) with a single `Bash(awk*)` entry next to `jq*`, consistent with how `grep*`, `find*`, and `sort*` are allowed. Removes the broken `Read(//var/lib/infinito/logs/**)` entry: `/var/lib/infinito/` is a named Docker volume defined in compose.yml and never exists on the host, so host-scoped read access is meaningless (and the path had a double slash). Documents the new `awk*` entry in docs/contributing/tools/agents/claude.md with an explicit note that awk's `system()` and `"cmd" | getline` put it in the same risk class as the already-allowed `find -exec`. Co-Authored-By: Claude Opus 4.6 --- .claude/settings.json | 24 +++++++----------------- docs/contributing/tools/agents/claude.md | 1 + 2 files changed, 8 insertions(+), 17 deletions(-) diff --git a/.claude/settings.json b/.claude/settings.json index a79dda60b6..eb43674827 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -4,7 +4,6 @@ "Read", "Edit", "Write", - "Bash(git status*)", "Bash(git log*)", "Bash(git diff*)", @@ -18,28 +17,23 @@ "Bash(git cherry-pick*)", "Bash(git apply*)", "Bash(git -C:*)", - "Bash(gh run*)", - "Bash(make*)", "Bash(act*)", "Bash(bash -n*)", "Bash(bash scripts/*)", "Bash(source scripts/*)", "Bash(wait*)", - "Bash(python3*)", "Bash(python*)", "Bash(pip show*)", "Bash(pip list*)", "Bash(pip install*)", - "Bash(ansible-lint*)", "Bash(ansible-inventory*)", "Bash(ansible --version*)", "Bash(ansible-playbook --check*)", "Bash(ansible-playbook --syntax-check*)", - "Bash(docker pull*)", "Bash(docker build*)", "Bash(docker images*)", @@ -52,7 +46,6 @@ "Bash(docker rmi*)", "Bash(docker compose*)", "Bash(docker exec*)", - "Bash(grep*)", "Bash(find*)", "Bash(ls*)", @@ -66,7 +59,7 @@ "Bash(cp*)", "Bash(mv*)", "Bash(jq*)", - + "Bash(awk*)", "WebSearch", "WebFetch(domain:github.com)", "WebFetch(domain:raw.githubusercontent.com)", @@ -88,23 +81,20 @@ "WebFetch(domain:hcaptcha.com)", "WebFetch(domain:gstatic.com)" ], - + "deny": [ + "Bash(git push --force*)", + "Bash(git reset --hard*)", + "Bash(rm -rf*)", + "Bash(sudo*)" + ], "ask": [ "Bash(git commit*)", "Bash(git push*)", "Bash(docker run*)", "Bash(curl*)", "Bash(gh api*)" - ], - - "deny": [ - "Bash(git push --force*)", - "Bash(git reset --hard*)", - "Bash(rm -rf*)", - "Bash(sudo*)" ] }, - "sandbox": { "filesystem": { "allowWrite": [ diff --git a/docs/contributing/tools/agents/claude.md b/docs/contributing/tools/agents/claude.md index e8b4b7946f..3c1e7ff393 100644 --- a/docs/contributing/tools/agents/claude.md +++ b/docs/contributing/tools/agents/claude.md @@ -97,6 +97,7 @@ Claude Code evaluates each tool call against three ordered lists: |---|---|---|---| | `grep*`, `find*`, `ls*`, `cat*`, `head*`, `tail*` | Reading and searching file content during any task. | Standard read-only inspection tools. Required for almost every task. | No write side-effects. Safe to allow unconditionally. | | `wc*`, `sort*`, `jq*` | Counting lines, sorting output, parsing JSON. | Common pipeline utilities used in scripts and make targets. | No write side-effects. Safe to allow unconditionally. | +| `awk*` | Pattern-based text extraction and transformation during inspection, script output parsing, and make target post-processing. | Standard pipeline utility. Narrow per-invocation wildcards proved impractical — every unique command line (pattern + path) would require its own allowlist entry. | Not strictly read-only: awk's `system()` and `"cmd" \| getline` can execute arbitrary shell commands and reach the network, equivalent in risk class to the already-allowed `find -exec` and `tar --checkpoint-action=exec`. The sandbox `allowWrite` scope, `denyRead` credential paths, and the `rm -rf*` / `sudo*` deny rules still bound the blast radius. Review awk scripts before piping untrusted input into them. | | `tar*` | Archiving files during build or export tasks. | Required by build and packaging scripts. | Can overwrite files when extracting. The sandbox `allowWrite` limits the blast radius to `.` and `/tmp`. | | `mkdir*`, `cp*`, `mv*` | Creating directories and moving or copying files during setup and build tasks. | Required by install scripts and build targets. | `mv` and `cp` can overwrite files silently. Bounded by the sandbox `allowWrite` constraint. | From 8f4b0eda0096385f837af5c4cc8fecdb86bbf5a9 Mon Sep 17 00:00:00 2001 From: Environment Test Date: Wed, 15 Apr 2026 17:11:40 +0200 Subject: [PATCH 39/55] chore(dockerignore): mirror *.lock ignore from .gitignore Co-Authored-By: Claude Opus 4.6 --- .dockerignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.dockerignore b/.dockerignore index c9a2dc477c..213d9cfb5f 100644 --- a/.dockerignore +++ b/.dockerignore @@ -19,4 +19,5 @@ env.development logs/ job-logs.txt .claude/skills +*.lock .git From 63c42154d25255adb4b0acce723260db75ea21fe Mon Sep 17 00:00:00 2001 From: Environment Test Date: Wed, 15 Apr 2026 17:20:44 +0200 Subject: [PATCH 40/55] chore(claude): allow pkill -f and pre-commit cache reads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds `Bash(pkill -f *)` to the allowlist so stuck background commands (pre-commit hooks, `make test`, `git commit`) can be aborted without an approval prompt. Broad wildcard consciously accepted — narrow per-pattern entries required repeated allowlist edits for every new abort scenario. Adds `Read(~/.cache/pre-commit/**)` so pre-commit's stashed patch files can be reapplied via `git apply` after a manually killed hook run, and uses `~` instead of a hardcoded username path. Documents both entries in docs/contributing/tools/agents/claude.md, including the explicit risk note that `pkill -f` with a regex can terminate every user-owned process and should use the narrowest pattern possible. Co-Authored-By: Claude Opus 4.6 --- .claude/settings.json | 4 +++- docs/contributing/tools/agents/claude.md | 7 +++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/.claude/settings.json b/.claude/settings.json index eb43674827..02301cabaa 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -79,7 +79,9 @@ "WebFetch(domain:ghcr.io)", "WebFetch(domain:letsencrypt.org)", "WebFetch(domain:hcaptcha.com)", - "WebFetch(domain:gstatic.com)" + "WebFetch(domain:gstatic.com)", + "Bash(pkill -f *)", + "Read(~/.cache/pre-commit/**)" ], "deny": [ "Bash(git push --force*)", diff --git a/docs/contributing/tools/agents/claude.md b/docs/contributing/tools/agents/claude.md index 3c1e7ff393..93c67d1a72 100644 --- a/docs/contributing/tools/agents/claude.md +++ b/docs/contributing/tools/agents/claude.md @@ -100,6 +100,13 @@ Claude Code evaluates each tool call against three ordered lists: | `awk*` | Pattern-based text extraction and transformation during inspection, script output parsing, and make target post-processing. | Standard pipeline utility. Narrow per-invocation wildcards proved impractical — every unique command line (pattern + path) would require its own allowlist entry. | Not strictly read-only: awk's `system()` and `"cmd" \| getline` can execute arbitrary shell commands and reach the network, equivalent in risk class to the already-allowed `find -exec` and `tar --checkpoint-action=exec`. The sandbox `allowWrite` scope, `denyRead` credential paths, and the `rm -rf*` / `sudo*` deny rules still bound the blast radius. Review awk scripts before piping untrusted input into them. | | `tar*` | Archiving files during build or export tasks. | Required by build and packaging scripts. | Can overwrite files when extracting. The sandbox `allowWrite` limits the blast radius to `.` and `/tmp`. | | `mkdir*`, `cp*`, `mv*` | Creating directories and moving or copying files during setup and build tasks. | Required by install scripts and build targets. | `mv` and `cp` can overwrite files silently. Bounded by the sandbox `allowWrite` constraint. | +| `pkill -f *` | Aborting stuck background commands (e.g. interrupting a running pre-commit hook, `make test`, or `git commit`) without a manual approval prompt each time. | Arbitrary kill patterns proved necessary during iteration — pre-approving only specific patterns required repeated allowlist edits for every new scenario. | High-risk: `pkill -f` accepts any regex, so a broad pattern (e.g. `.`) terminates every process the user owns, including desktop sessions, browsers, SSH, and the agent itself. SIGKILL can cause data loss in unsaved work. Consciously accepted trade-off: reliance on agent judgment and the Anthropic usage policy instead of a narrow per-pattern allowlist. Agents MUST use the narrowest possible pattern and prefer `wait`/background completion over killing. | + +### Process Management 🔪 + +| Permission | When | Why | Security | +|---|---|---|---| +| `Read(~/.cache/pre-commit/**)` | Reading pre-commit's stashed patch files to restore unstaged changes after a manually aborted hook run. | When a long-running pre-commit hook (e.g. `make test`) is killed mid-run, pre-commit leaves unstaged changes in its patch cache; reading them is required to reapply via `git apply`. | Read-only access to a local cache directory containing repo diffs. No credentials are stored there. | ### Web Access 🌐 From c64c80cdb832cc3ee3a35e3f57e347ed0812d315 Mon Sep 17 00:00:00 2001 From: Environment Test Date: Wed, 15 Apr 2026 17:27:17 +0200 Subject: [PATCH 41/55] docs(agents): make .claude/settings.json the shared permission policy Adds a Permission Model section to AGENTS.md that binds all agents (Claude Code, Codex, Gemini, or any other) to the allow/ask/deny entries in .claude/settings.json, even when the agent's own runtime does not consult that file. Spells out how patterns are matched, that deny overrides allow, that ask requires a per-conversation confirmation, and that anything not in allow defaults to ask. Makes .claude/settings.json the single source of truth for automated execution policy in this repository and points to the per-entry rationale in docs/contributing/tools/agents/claude.md. Co-Authored-By: Claude Opus 4.6 --- AGENTS.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 0e89719564..56624cdc4b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,6 +12,23 @@ If agent instructions change during a conversation, the agent MAY not pick up th > "Re-read AGENTS.md and apply all updated instructions." +## Permission Model + +The project defines a single, tool-independent permission policy in [`.claude/settings.json`](.claude/settings.json). Although the file lives under `.claude/`, its `permissions` section (`allow`, `ask`, `deny`) is the SPOT for what automated agents MAY do in this repository, regardless of the underlying agent (Claude Code, Codex, Gemini, or any other). + +Every agent MUST: + +- Read [`.claude/settings.json`](.claude/settings.json) at the start of each conversation and treat its `permissions` object as binding policy. +- Match commands against the patterns exactly as Claude Code does: the command-line prefix is compared literally, `*` is a wildcard, and `deny` overrides `allow`. +- Treat `deny` entries as unconditional blocks. Agents MUST NOT execute any command matching a `deny` pattern, even if their native tooling would otherwise permit it. +- Treat `ask` entries as requiring an explicit, per-invocation operator confirmation in the current conversation before executing. A prior confirmation in another conversation MUST NOT be reused. +- Treat `allow` entries as the only pre-authorized commands. Any command that does not match an `allow` pattern MUST be treated as `ask` by default. +- Respect the `sandbox.filesystem` section: `allowWrite` bounds the write scope, and paths listed under `denyRead` MUST NOT be read. + +Agents that cannot technically enforce these rules (e.g. because their native runtime does not consult `.claude/settings.json`) MUST still follow the policy procedurally: before running a command, check it against the rules above and stop for confirmation when required. + +Changes to the permission policy MUST be made by editing [`.claude/settings.json`](.claude/settings.json) so that all agents share the same source of truth. The rationale for each entry is documented in [docs/contributing/tools/agents/claude.md](docs/contributing/tools/agents/claude.md). + ## Role-Specific Instructions Individual roles MAY contain an `AGENTS.md` file with role-specific agent instructions. From 00502ed9e625cb2df9cc77a5d93ae232269b0cdc Mon Sep 17 00:00:00 2001 From: Environment Test Date: Wed, 15 Apr 2026 19:00:28 +0200 Subject: [PATCH 42/55] fix(web-app-keycloak): retry bootstrap admin login until Keycloak is ready Retries kcadm config credentials up to 30 times at 5s intervals to tolerate the 503 window after compose up while the server is still initializing. Co-Authored-By: Claude Opus 4.6 --- roles/web-app-keycloak/tasks/04_login.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/roles/web-app-keycloak/tasks/04_login.yml b/roles/web-app-keycloak/tasks/04_login.yml index b88fc395e1..4a28a5d5d2 100644 --- a/roles/web-app-keycloak/tasks/04_login.yml +++ b/roles/web-app-keycloak/tasks/04_login.yml @@ -32,6 +32,9 @@ ' register: kc_login_bootstrap changed_when: false + retries: 30 + delay: 5 + until: kc_login_bootstrap.rc == 0 - name: Ensure permanent admin user exists (create if missing) shell: | From 53efeb7eb77f9510b9c7c2df53ec95e12ba6ad31 Mon Sep 17 00:00:00 2001 From: Environment Test Date: Wed, 15 Apr 2026 20:22:26 +0200 Subject: [PATCH 43/55] docs(agents): add Playwright Spec Loop with rerunner script Adds the documented inner-loop workflow for iterating role-local Playwright specs against a live stack without a full redeploy, plus the helper script that reuses the existing staging dir, rendered .env, and container image defaults so no new TEST_E2E_PLAYWRIGHT_* override mechanism is introduced. Co-Authored-By: Claude Opus 4.6 --- docs/agents/action/iteration.md | 11 ++++ scripts/tests/e2e/rerun-spec.sh | 90 +++++++++++++++++++++++++++++++++ 2 files changed, 101 insertions(+) create mode 100755 scripts/tests/e2e/rerun-spec.sh diff --git a/docs/agents/action/iteration.md b/docs/agents/action/iteration.md index d35ccc2db6..089aae5254 100644 --- a/docs/agents/action/iteration.md +++ b/docs/agents/action/iteration.md @@ -17,6 +17,17 @@ Use this page when you are iterating on a local app deploy during debugging or d - Network or DNS failures during a local deploy count as concrete evidence that the host stack is broken. In that case, the next retry MUST be `make deploy-fresh-purged-apps APPS=` so the container stack is re-initialized. - If you need to validate the single-app init/deploy path separately, use `make deploy-fresh-kept-apps APPS=`. It checks the clean single-app setup apart from the faster reuse path. +## Playwright Spec Loop + +- After the first successful deploy has brought the app stack up, you MUST iterate role-local `files/playwright.spec.js` directly against the live running container instead of redeploying between every spec edit. +- For that inner loop you MUST use the [Playwright spec rerunner](../../../scripts/tests/e2e/rerun-spec.sh) (e.g. `scripts/tests/e2e/rerun-spec.sh `, optionally followed by `--grep ` or other `npx playwright test` arguments). The script reuses the staging dir and rendered `.env` from the last deploy and reruns Playwright in the same container image the deploy-time runner uses. +- The staged Playwright project lives at `TEST_E2E_PLAYWRIGHT_STAGE_BASE_DIR/` (default `/tmp/test-e2e-playwright/`) with the rendered `.env` already in place. The script overwrites `tests/playwright.spec.js` from the repo before each run; you MUST NOT hand-edit the staged copy. +- You MUST keep iterating the spec in this inner loop until the test passes. Only spec-only changes belong in this loop. +- If the change touches anything **outside** `files/playwright.spec.js` (role tasks, templates, vars, config, `javascript.js`, `style.css`, or any other role asset that the deploy materializes), you MUST redeploy. Inner-loop spec runs do NOT pick up role changes. +- Prefer `make deploy-reuse-kept-apps APPS=` for that redeploy. Fall back to `make deploy-fresh-purged-apps APPS=` only when the reuse path has concrete evidence of broken inventory or host stack, per the rules in [Role Loop](#role-loop). +- You MUST still meet the live-application and logout-state requirements from [Agent `playwright.spec.js`](../files/role/playwright.spec.js.md) at the end of the inner loop. +- Once the spec passes in the inner loop, you MUST run one final pass through the [Role Loop](#role-loop) with `make deploy-fresh-purged-apps APPS=` to confirm the spec still passes against a freshly provisioned stack, not only against the cached staging project. + ## Workflow Loop - When you are developing, optimizing, or debugging GitHub Actions workflows, you SHOULD explicitly propose `make act-workflow` as the default iterative local debug loop. diff --git a/scripts/tests/e2e/rerun-spec.sh b/scripts/tests/e2e/rerun-spec.sh new file mode 100755 index 0000000000..7a0fe5933e --- /dev/null +++ b/scripts/tests/e2e/rerun-spec.sh @@ -0,0 +1,90 @@ +#!/usr/bin/env bash +# Rerun a role-local Playwright spec against the live running stack. +# +# Preconditions: +# - The role has been deployed at least once, so the Playwright project is +# staged under $TEST_E2E_PLAYWRIGHT_STAGE_BASE_DIR/ with a rendered +# .env file. +# - The application under test is still running. +# +# This script intentionally does NOT re-render .env and does NOT re-stage the +# project. It only overwrites tests/playwright.spec.js from the repo and +# reruns Playwright via the same container image the deploy-time runner uses. +# +# Usage: +# scripts/tests/e2e/rerun-spec.sh [playwright args...] +# scripts/tests/e2e/rerun-spec.sh web-app-nextcloud --grep "talk admin" +set -euo pipefail + +if [[ $# -lt 1 ]]; then + echo "usage: $0 [playwright args...]" >&2 + exit 2 +fi + +role="$1" +shift + +repo_root="$(cd "$(dirname "$0")/../../.." && pwd)" +spec_src="$repo_root/roles/$role/files/playwright.spec.js" +defaults="$repo_root/roles/test-e2e-playwright/defaults/main.yml" +package_json="$repo_root/roles/test-e2e-playwright/files/package.json" + +stage_base="${TEST_E2E_PLAYWRIGHT_STAGE_BASE_DIR:-/tmp/test-e2e-playwright}" +reports_base="${TEST_E2E_PLAYWRIGHT_REPORTS_BASE_DIR:-/var/lib/infinito/logs/test-e2e-playwright}" +distro="${TEST_E2E_PLAYWRIGHT_IMAGE_DISTRO:-noble}" + +stage_dir="$stage_base/$role" +reports_dir="$reports_base/$role" +env_file="$stage_dir/.env" + +[[ -f "$spec_src" ]] || { + echo "missing spec: $spec_src" >&2 + exit 1 +} +[[ -d "$stage_dir" ]] || { + echo "missing staging dir (run deploy first): $stage_dir" >&2 + exit 1 +} +[[ -f "$env_file" ]] || { + echo "missing rendered env (run deploy first): $env_file" >&2 + exit 1 +} + +image="${TEST_E2E_PLAYWRIGHT_IMAGE:-}" +if [[ -z "$image" ]]; then + base_image="$(awk '/^[[:space:]]*image:/{print $2; exit}' "$defaults")" + version="$(awk -F'"' '/@playwright\/test/{print $4; exit}' "$package_json")" + version="${version#^}" + version="${version#~}" + image="${base_image}:v${version}-${distro}" +fi + +command -v docker >/dev/null || { + echo "docker not found in PATH" >&2 + exit 1 +} + +mkdir -p "$stage_dir/tests" "$stage_dir/volume" "$reports_dir" +cp "$spec_src" "$stage_dir/tests/playwright.spec.js" + +ca_env=() +if [[ "${TLS_MODE:-}" == "self_signed" ]]; then + for var in CA_TRUST_CERT_HOST CA_TRUST_WRAPPER_HOST CA_TRUST_NAME; do + if [[ -n "${!var:-}" ]]; then + ca_env+=(-e "$var=${!var}") + fi + done +fi + +cmd="${TEST_E2E_PLAYWRIGHT_COMMAND:-npm install --no-fund --no-audit && npx playwright test${*:+ $*}}" + +exec docker run --rm \ + --ipc=host --shm-size=1g \ + --env-file "$env_file" \ + "${ca_env[@]}" \ + -v "$stage_dir:/e2e" \ + -v "$stage_dir/volume:/volume" \ + -v "$reports_dir:/reports" \ + -w /e2e \ + "$image" \ + /bin/bash -lc "$cmd" From a07ef379edadbd17f62688e515b2748333e55946 Mon Sep 17 00:00:00 2001 From: Environment Test Date: Wed, 15 Apr 2026 20:31:03 +0200 Subject: [PATCH 44/55] chore(scripts): drop unused CA trust env pass-through from Playwright rerunner The rendered .env already contains the deploy-time CA trust values and the spec uses ignoreHTTPSErrors, so duplicating the Ansible task's -e wiring never adds anything in the inner-loop case. Co-Authored-By: Claude Opus 4.6 --- scripts/tests/e2e/rerun-spec.sh | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/scripts/tests/e2e/rerun-spec.sh b/scripts/tests/e2e/rerun-spec.sh index 7a0fe5933e..d9d02346a8 100755 --- a/scripts/tests/e2e/rerun-spec.sh +++ b/scripts/tests/e2e/rerun-spec.sh @@ -67,21 +67,11 @@ command -v docker >/dev/null || { mkdir -p "$stage_dir/tests" "$stage_dir/volume" "$reports_dir" cp "$spec_src" "$stage_dir/tests/playwright.spec.js" -ca_env=() -if [[ "${TLS_MODE:-}" == "self_signed" ]]; then - for var in CA_TRUST_CERT_HOST CA_TRUST_WRAPPER_HOST CA_TRUST_NAME; do - if [[ -n "${!var:-}" ]]; then - ca_env+=(-e "$var=${!var}") - fi - done -fi - cmd="${TEST_E2E_PLAYWRIGHT_COMMAND:-npm install --no-fund --no-audit && npx playwright test${*:+ $*}}" exec docker run --rm \ --ipc=host --shm-size=1g \ --env-file "$env_file" \ - "${ca_env[@]}" \ -v "$stage_dir:/e2e" \ -v "$stage_dir/volume:/volume" \ -v "$reports_dir:/reports" \ From e4de89336826b1bc1d5406be93f0d16c57c2426a Mon Sep 17 00:00:00 2001 From: Environment Test Date: Wed, 15 Apr 2026 20:49:17 +0200 Subject: [PATCH 45/55] fix(web-app-nextcloud): SSO-only Talk admin spec and safer plugin config defaults Rewrite loginToStandaloneNextcloud to drive the OIDC flow (Nextcloud -> Keycloak -> Nextcloud) instead of the native credential form, which is hidden by oidc_login_hide_password_form. Add section-divider and WHY comments to make the spec easier to read. Provide defaults for the compose.services.oidc.flavor lookup so oidc_login stays enabled when the key is absent, and default user_ldap to enabled when the LDAP service config is missing. Co-Authored-By: Claude Opus 4.6 --- roles/web-app-nextcloud/config/main.yml | 10 +- .../files/playwright.spec.js | 167 ++++++++++++++---- 2 files changed, 135 insertions(+), 42 deletions(-) diff --git a/roles/web-app-nextcloud/config/main.yml b/roles/web-app-nextcloud/config/main.yml index 9d935c21b8..f8e2e6672a 100644 --- a/roles/web-app-nextcloud/config/main.yml +++ b/roles/web-app-nextcloud/config/main.yml @@ -160,7 +160,7 @@ compose: hcaptcha: enabled: "{{ HCAPTCHA_ENABLED | bool }}" default_quota: '1000000000' # Quota to assign if no quota is specified in the OIDC response (bytes) -legacy_login_mask: +legacy_login_mask: enabled: False # If true, then legacy login mask is shown. Otherwise just SSO performance: @@ -310,7 +310,7 @@ plugins: enabled: true oidc_login: # Nextcloud User OIDC: integrates OpenID Connect for user authentication (https://apps.nextcloud.com/apps/oidc_login) - enabled: "{{ lookup('config', 'web-app-nextcloud', 'compose.services.oidc.flavor') == 'oidc_login' }}" + enabled: "{{ lookup('config', 'web-app-nextcloud', 'compose.services.oidc.flavor', 'oidc_login') == 'oidc_login' }}" incompatible_plugins: - user_oidc # Will be disabled - sociallogin # Will be disabled @@ -337,7 +337,7 @@ plugins: - fileslibreofficeedit sociallogin: # Nextcloud social login: allows authentication using social networks (https://apps.nextcloud.com/apps/sociallogin) - enabled: "{{ lookup('config', 'web-app-nextcloud', 'compose.services.oidc.flavor') == 'sociallogin' }}" + enabled: "{{ lookup('config', 'web-app-nextcloud', 'compose.services.oidc.flavor', 'oidc_login') == 'sociallogin' }}" incompatible_plugins: - user_oidc # Will be disabled - oidc_login # Will be disabled @@ -361,12 +361,12 @@ plugins: enabled: "{{ not (lookup('config', 'web-app-nextcloud', 'compose.services.oidc.enabled', False)) }}" # Deactivate 2FA if oidc is active user_ldap: # Nextcloud user LDAP: integrates LDAP for user management and authentication - enabled: "{{ lookup('config', 'web-app-nextcloud', 'compose.services.ldap.enabled', False) }}" + enabled: "{{ lookup('config', 'web-app-nextcloud', 'compose.services.ldap.enabled', True) }}" user_directory: enabled: true # Enables the LDAP User Directory Search user_oidc: # Nextcloud User OIDC: integrates OpenID Connect for user authentication (https://apps.nextcloud.com/apps/user_oidc) - enabled: "{{ lookup('config', 'web-app-nextcloud', 'compose.services.oidc.flavor') == 'user_oidc' }}" + enabled: "{{ lookup('config', 'web-app-nextcloud', 'compose.services.oidc.flavor', 'oidc_login') == 'user_oidc' }}" incompatible_plugins: - oidc_login - sociallogin diff --git a/roles/web-app-nextcloud/files/playwright.spec.js b/roles/web-app-nextcloud/files/playwright.spec.js index 667e11cc6b..6bcccaaedf 100644 --- a/roles/web-app-nextcloud/files/playwright.spec.js +++ b/roles/web-app-nextcloud/files/playwright.spec.js @@ -1,9 +1,29 @@ +// End-to-end tests for the Nextcloud role. +// +// Two scenarios: +// 1. "nextcloud talk admin settings" — SSO-login as admin, navigate to the +// Talk admin page, and assert the configured HPB / STUN / TURN values +// are rendered (and that legacy onboard values are absent). +// 2. "dashboard to nextcloud login" — enter Nextcloud through the +// portal dashboard iframe, complete the OIDC handoff via Keycloak, +// reuse the authenticated context for the Talk check, then log out. +// +// All authentication goes through Keycloak (OIDC). Local Nextcloud login +// is intentionally NOT exercised: `oidc_login_hide_password_form` keeps the +// native form hidden in this deployment. const { test, expect } = require("@playwright/test"); +// `ignoreHTTPSErrors` is needed because the local stack typically uses the +// self-signed CA set up by `make trust-ca`, which the Playwright container +// does not trust by default. test.use({ ignoreHTTPSErrors: true }); +// --------------------------------------------------------------------------- +// Env decoding +// --------------------------------------------------------------------------- + function decodeDotenvQuotedValue(value) { if (typeof value !== "string" || value.length < 2) { return value; @@ -24,6 +44,13 @@ function decodeDotenvQuotedValue(value) { // `docker --env-file` preserves the quotes emitted by `dotenv_quote`, // so normalize these values before building URLs or typing credentials. +// --------------------------------------------------------------------------- +// Env-driven config +// +// All values originate from the rendered `.env` under the staging dir. The +// Talk-related values are optional and gate the first test via +// `nextcloudTalkSettingsCheckEnabled`. +// --------------------------------------------------------------------------- const loginUsername = decodeDotenvQuotedValue(process.env.LOGIN_USERNAME); const loginPassword = decodeDotenvQuotedValue(process.env.LOGIN_PASSWORD); const nextcloudDirectLoginPassword = decodeDotenvQuotedValue(process.env.NEXTCLOUD_DIRECT_LOGIN_PASSWORD) || loginPassword; @@ -39,6 +66,31 @@ const nextcloudTalkUnexpectedTurnServer = decodeDotenvQuotedValue(process.env.NE const nextcloudUsernameFieldPattern = /account name or email|username or email/i; const nextcloudCredentialSubmitPattern = /sign in|log in/i; +// --------------------------------------------------------------------------- +// Locator helpers +// +// Nextcloud renders different "shell" containers depending on the app (Vue +// vs. legacy) and version. The selectors below match any of them so the +// tests work across NC 28+ without hard-coding one layout. +// --------------------------------------------------------------------------- + +function getNextcloudShellCandidates(target) { + return [ + { + kind: "shell", + // #app-content-vue: dashboard and Vue-based apps. + // #app-navigation-vue: Vue sidebar (files etc.). + // #app-content: legacy app container. + // #header-start__appmenu: always present in layout.user.php