diff --git a/.github/workflows/call-validation.yml b/.github/workflows/call-validation.yml index 94b821f6e9..289d1dd4e4 100644 --- a/.github/workflows/call-validation.yml +++ b/.github/workflows/call-validation.yml @@ -135,12 +135,13 @@ jobs: PR_SCOPE: ${{ inputs.pr_scope }} run: ./scripts/meta/resolve/pr/branch_prefix.sh - - name: πŸ”€ Assert the base branch is fully merged into the PR head + - name: πŸ”€ Assert the event's base commit is merged into the PR head if: ${{ github.event_name == 'pull_request' && inputs.pr_scope != '' }} working-directory: pr-head env: INFINITO_MAIN_REMOTE: origin INFINITO_MAIN_BRANCH: ${{ github.event.pull_request.base.ref }} + INFINITO_MAIN_COMMIT: ${{ github.event.pull_request.base.sha }} run: bash "${GITHUB_WORKSPACE}/.base-tooling/scripts/git/assert/main_merged.sh" - name: πŸ”§ Set up Python diff --git a/TODO.md b/TODO.md index 3e3eebef5f..34c79e43f2 100644 --- a/TODO.md +++ b/TODO.md @@ -4,7 +4,7 @@ - Implement rbac administration interface - Enable IP6 for docker. - backup docker to local fΓΌr ca optimieren -- Drop `memory_limit = -1` from [hardening.ini](roles/sys-svc-compose-php/files/hardening.ini) once every PHP image ships PHP 8.2.35, 8.3.36, 8.4.27, 8.5.12 or later. It is the interim mitigation for CVE-2026-109618 and overrides the per-role `service_memory_mb` share, so a single request can exhaust the container instead of hitting a PHP limit. `web-app-joomla` keeps its own `memory_limit` because its media API compares uploads against it, and `web-app-magento` keeps the 756M its `nginx.conf.sample` (`PHP_VALUE`) and `pub/.user.ini` set; both keep `post_max_size` below a quarter of that limit. While the override is in place, `web-app-nextcloud` (`upload_limit` 5G at 3g) accepts POST bodies above a quarter of its container memory, `web-app-friendica` caps account imports at 64 MiB instead of half the memory limit, EspoCRM's System Requirements page flags `memory_limit` as failed, and Pixelfed (`InstanceService`), phpMyAdmin (import and export) and Snipe-IT (imports and LDAP sync) set a finite limit again via `ini_set` after the request has started. +- Drop the `php_memory_unlimited` mount ([memory-unlimited.ini](roles/sys-svc-compose-php/files/memory-unlimited.ini), `memory_limit = -1`) from each role whose image ships PHP 8.2.35, 8.3.36, 8.4.27, 8.5.12 or later, and the file, its install task and `FILE_PHP_MEMORY_UNLIMITED_INI` once no role mounts it. It is the interim mitigation for CVE-2026-109618 and overrides the per-role `service_memory_mb` share, so a single request can exhaust the container instead of hitting a PHP limit. Still mounted by `web-app-magento` (`markoshust/magento-php:8.4-fpm`, PHP 8.4.21), `web-app-mailu` (`ghcr.io/heviat/webmail:2024.06`, the OIDC flavor, built 2025-04-04), `web-app-phpldapadmin` (`phpldapadmin/phpldapadmin:2.3.11`, built 2026-05-15) and `web-app-shopware` (`ghcr.io/shopware/docker-base:8.3`, PHP 8.3.25). `web-app-magento` keeps the 756M its `nginx.conf.sample` (`PHP_VALUE`) and `pub/.user.ini` set and keeps `post_max_size` below a quarter of that limit. - Fork [rpardini/docker-registry-proxy](https://github.com/rpardini/docker-registry-proxy) and teach the bundled nginx to handle GCP Artifact Registry redirect URLs (`/artifacts-downloads/namespaces//repositories//downloads/`). Currently `gcr.io` blob pulls are bypassed via `NO_PROXY=…,gcr.io,storage.googleapis.com,googleusercontent.com` in [compose/registry-cache/proxy.conf](compose/registry-cache/proxy.conf), which is a workaround that disables caching for those registries. Long-term: rebase upstream's `proxy.conf` / `sub_filter` rules to recognise the new redirect shape, ship the fix in our fork, point `compose/registry-cache/Dockerfile` (or its image tag) at the fork, and drop the `NO_PROXY` bypass. ## Testing diff --git a/docs/contributing/artefact/files/plugins/lookup/applications.md b/docs/contributing/artefact/files/plugins/lookup/applications.md index a2963acfe5..5b69fd185e 100644 --- a/docs/contributing/artefact/files/plugins/lookup/applications.md +++ b/docs/contributing/artefact/files/plugins/lookup/applications.md @@ -33,14 +33,15 @@ No other source is consulted. Ansible forks a fresh worker process for every task. The in-process cache inside `get_merged_applications` therefore never survives from one task to the next, and every task that touches the lookup would render the full tree again (about 16 to 23 seconds per task on a CI runner, measured on the workspace jobs). -The constructor stage renders once through the [applications_carrier](../../../../../../plugins/action/applications_carrier.py) action and parks the result together with its cache key in the host fact `_INFINITO_APPLICATIONS_RENDERED` (the action calls `lookup('applications', carrier=True)`). Every later worker inherits that fact at fork time; `get_merged_applications` serves it whenever the key still matches and renders only when it does not (a changed `applications`, `users`, `DOMAIN_PRIMARY`, `SYSTEM_EMAIL_DOMAIN` or `group_names`, or changed tokens in the store the users are hydrated from). +The constructor stage renders once through the [applications_carrier](../../../../../../plugins/action/applications_carrier.py) action and parks the result together with its cache key in the host fact `_INFINITO_APPLICATIONS_RENDERED` (the action calls `lookup('applications', carrier=True)`). Every later worker inherits that fact at fork time; `get_merged_applications` serves it whenever the key still matches and renders only when it does not (a changed `applications`, `users`, `DOMAIN_PRIMARY`, `SYSTEM_EMAIL_DOMAIN` or `group_names`). - The stage-wide task sits in `tasks/stages/01_constructor.yml` after the `networks` and `service_provider` merges, after the `add_host` placements and after the token store, so the payload renders with the same `group_names`, `groups` and user records a role would see. Moving it earlier bakes stale values into the play. - The carrier is parked again after every role in `tasks/utils/setup/role.yml`, after every nested application load in `tasks/utils/load/app.yml`, and after every store write in `roles/sys-token-store/tasks/write_many.yml`, which `write.yml` runs for a single token. The first two run on every host of the include, also on hosts the loaded role skips. A re-park whose key still matches serves the carried payload without rendering. - The action renders with `application_id` removed from its variables, so the carried tree holds the play-scope result of every consumer-aligned `lookup('tls', ...)`, whichever role parks it. -- The token store enters the key as the SHA-256 of exactly the tokens the users are hydrated from: the controller's tokens file until `sys-token-store` loads, the `sys_token_store_users` fact after. Both sources key alike when they hold the same tokens, so loading an unchanged store keeps the carrier, and a touch keeps the key. The carrier action opens the file before it computes the key, so an NFS client keys on revalidated attributes. +- The token store is not part of the key: a store write keeps the applications carrier and re-renders only the users carrier (see [users.md](users.md)). - The action masks its own result: the fact is the whole rendered tree with every application's credentials, so it never reaches a log regardless of `MASK_CREDENTIALS_IN_LOGS`. -- User records inside the payload are the token store's state at render time. Readers of tokens captured later in the play MUST go through `lookup('users', ...)` or `lookup('config', , 'users....')`, both of which read the users cache fresh. +- User records inside the payload are the token store's state at render time, which can predate every store write of the play. Readers of tokens MUST go through `lookup('users', ...)` or `lookup('config', , 'users....')`, both of which key the users on the current token store. Application config MUST NOT derive a value from a token. +- The action parks the users carrier `_INFINITO_USERS_RENDERED` at the same points, after the applications render; `clear: true` drops both. See [users.md](users.md). - The carrier is private to the lookup. Consumers MUST NOT read `_INFINITO_APPLICATIONS_RENDERED`; they keep going through `lookup('applications')`, which is what makes the carrier transparent. - The carrier is the only materialised merged view a play MAY hold. The rule against a top-level `applications` fact above is unchanged. diff --git a/docs/contributing/artefact/files/plugins/lookup/users.md b/docs/contributing/artefact/files/plugins/lookup/users.md index d7d6ac46c1..d60c79c006 100644 --- a/docs/contributing/artefact/files/plugins/lookup/users.md +++ b/docs/contributing/artefact/files/plugins/lookup/users.md @@ -18,6 +18,16 @@ The `users` lookup is the ONLY supported runtime entry point for merged user con | `lookup('users')` | Full merged mapping keyed by the canonical user key. | | `lookup('users', '')` | Merged entry for that user. Raises when missing. | | `lookup('users', '', default_value)` | Merged entry, or `default_value` when the entry is missing. | +| `lookup('users', carrier=True)` | `{"key": [...], "users": {...}}`: the full mapping plus the cache key it is valid under. Reserved for the `applications_carrier` action (see below). | + +## Play-Scoped Carrier 🧊 + +The [applications_carrier](../../../../../../plugins/action/applications_carrier.py) action parks the rendered users next to the applications in the host fact `_INFINITO_USERS_RENDERED`, at every point listed in [applications.md](applications.md), and `clear: true` drops both facts. `get_merged_users` serves the fact to a templated read when its key matches and renders otherwise. + +- The key is the applications carrier key plus the token store and `inventory_hostname`: a changed `applications`, `users`, `DOMAIN_PRIMARY`, `SYSTEM_EMAIL_DOMAIN`, `group_names`, token store or host rejects the carrier. +- The token store enters the key as the SHA-256 of exactly the tokens the users are hydrated from: the controller's tokens file until `sys-token-store` loads, the `sys_token_store_users` fact after. Both sources key alike when they hold the same tokens, so loading an unchanged store keeps the carrier, and a touch keeps the key. The carrier action opens the file before it computes the key, so an NFS client keys on revalidated attributes. +- A read without a templar (the raw users inside an applications render) never takes the carrier. +- The carrier is private to the lookup. Consumers MUST NOT read `_INFINITO_USERS_RENDERED`; they keep going through `lookup('users')` or `lookup('config', , 'users....')`. ## Data Sources πŸ“š @@ -26,7 +36,7 @@ The lookup merges exactly two sources: 1. **Defaults** discovered from every `roles/*/meta/users.yml` in the repository (file root IS the users map; no `users:` wrapper). 2. **Overrides** supplied through the normal Ansible variable `users` in inventory, group vars, host vars, or role vars. -No intermediate merged `users` fact exists. No other source is consulted. +No intermediate merged `users` fact exists besides the carrier above. No other source is consulted. ## Canonical User Key πŸ”‘ @@ -82,6 +92,7 @@ users: |---|---| | [users.py](../../../../../../plugins/lookup/users.py) | Runtime entry point for the `users` lookup. | | `utils/cache/users/` | Shared aggregation helper package that builds and caches defaults, handles reserved users, UID/GID allocation, and uniqueness validation. Placeholder substitution (DOMAIN_PRIMARY / ORGANIZATION / SOFTWARE_NAME) lives in [users/placeholders.py](../../../../../../utils/cache/users/placeholders.py). | +| [carrier.py](../../../../../../utils/cache/carrier.py) | The play-scoped carrier: fact name, `merged_users_cache_key`, and the reader that serves the carried payload. | | [test_users.py](../../../../../../tests/unit/python/plugins/lookup/test_users.py) | Unit tests covering the full-dict, single-entry, override, strict missing, and non-strict missing cases. | For the related applications pattern see [applications.md](applications.md). diff --git a/docs/contributing/design/role/services/base.md b/docs/contributing/design/role/services/base.md index 635fa83f3d..c4f6f91d52 100644 --- a/docs/contributing/design/role/services/base.md +++ b/docs/contributing/design/role/services/base.md @@ -74,6 +74,24 @@ Rules: - `card:` MUST be a key of the role's `canonical` mapping in `meta/domains.yml`; the card URL is `lookup('canonical_url', , )`. - Without `card:` the card targets the primary domain via `lookup('tls', , 'url.base')`. +## Dashboard Card Display πŸ‘€ + +`enabled: false` on a consumer's `dashboard` binding takes the role out of the dashboard: no card, no Apps menu entry, no tile-reachability target and no dashboard origin in its CSP `frame-ancestors`. +The flag is read from the merged applications, so an inventory MAY set it per host without touching the role: + +```yaml +applications: + web-app-gitea: + services: + dashboard: + enabled: false +``` + +Rules: + +- `enabled:` MUST render to a boolean; any other value fails the card lookup. +- A `web-app-*` role without a `dashboard` binding still gets a card. + ## Service Discovery πŸ” Service discovery is built from role configs, not from a central registry file. diff --git a/docs/contributing/design/role/services/layout.md b/docs/contributing/design/role/services/layout.md index 2bc5cfe918..8674265aac 100644 --- a/docs/contributing/design/role/services/layout.md +++ b/docs/contributing/design/role/services/layout.md @@ -7,7 +7,7 @@ All role-owned metadata lives under `roles//meta/.yml`. | File | Contents | |--------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------| -| `meta/main.yml` | Ansible Galaxy metadata + Ansible `dependencies:`. No project-internal `run_after:` / `lifecycle:` keys, no `logo:` / `homepage:` / `video:` / `display:`. | +| `meta/main.yml` | Ansible Galaxy metadata + Ansible `dependencies:`. No project-internal `run_after:` / `lifecycle:` keys, no `logo:` / `homepage:` / `video:`. | | `meta/services.yml` | Per-entity service config. **File root IS the services map** keyed by ``. No `compose:` and no `services:` wrapper. | | `meta/server.yml` | CSP, `domains`, `status_codes`, plus per-role `networks.local.{subnet,dns_resolver}`. File root IS `applications..server`. | | `meta/rbac.yml` | RBAC declarations. File root IS `applications..rbac`. | @@ -15,7 +15,7 @@ All role-owned metadata lives under `roles//meta/.yml`. | `meta/addons/.yml` | Optional. One file per addon (file root IS the addon spec; filename stem = addon id). See [Unified Addons](#unified-addons-metaaddons-) below. | | `meta/users.yml` | Role-local user definitions. File root IS the users map (no `users:` wrapper). | | `meta/secrets.yml` | Credential schema definitions and runtime credential values. | -| `meta/info.yml` | Optional. Descriptive role-level metadata (`logo`, `homepage`, `video`, `display`). File root IS `applications..info` (no `info:` wrapper). | +| `meta/info.yml` | Optional. Descriptive role-level metadata (`logo`, `homepage`, `video`). File root IS `applications..info` (no `info:` wrapper). | | `meta/variants.yml` | Optional. Variant overrides deep-merged over the assembled application payload (used by `svc-ai-ollama`, `web-app-phpmyadmin`). | Ansible only auto-loads `meta/main.yml`. @@ -359,7 +359,7 @@ The helper returns `[]` / `None` gracefully when `meta/services.yml` is absent o ## Descriptive Role-Level Metadata: `meta/info.yml` πŸ“ -Project-internal descriptive metadata (icon, upstream homepage, demo video, dashboard display flag) lives in an OPTIONAL `meta/info.yml`, not nested inside `galaxy_info:`. +Project-internal descriptive metadata (icon, upstream homepage, demo video) lives in an OPTIONAL `meta/info.yml`, not nested inside `galaxy_info:`. The file-root convention applies: there is no wrapping `info:` key, and the file content IS `applications..info`. ```yaml @@ -377,23 +377,23 @@ video: https://youtu.be/3jcYJGQgenI?si=FDmoMSrAb9_WvviC | `logo` | map | UI icon descriptor. Today only `class:` (FontAwesome). Future fields (`source:`, `svg:`) require an explicit allowlist update in the lint. | | `homepage` | string | Upstream project URL: the canonical landing page of the software the role deploys. | | `video` | string | Upstream demo / overview video URL. | -| `display` | bool | Default `true`. `false` opts the role out of dashboards / cards / apps grids. | The lint (`tests/lint/ansible/roles/meta/test_info.py`) rejects any other top-level key so the file does not become a dumping ground. +Whether the dashboard shows the role's card is not set here but in `services.dashboard.enabled`, see [Dashboard Card Display](base.md#dashboard-card-display-). ### Optionality `meta/info.yml` is OPTIONAL. -A role with none of the four fields does not grow the file. -Consumers MUST treat a missing file or missing field as absent / default, and `display` defaults to `true`. +A role with none of the three fields does not grow the file. +Consumers MUST treat a missing file or missing field as absent / default. ### Materialised Path ``` -applications..info.{logo,homepage,video,display} +applications..info.{logo,homepage,video} ``` -The dashboard's `web-app-dashboard/lookup_plugins/docker_cards.py` reads `logo.class` and `display` from this location, while `description` and `galaxy_tags` continue to come from `galaxy_info` (Galaxy-spec fields). +The dashboard's `web-app-dashboard/lookup_plugins/docker_cards.py` reads `logo.class` from this location, while `description` and `galaxy_tags` continue to come from `galaxy_info` (Galaxy-spec fields). ## Unified Addons: `meta/addons/` 🧩 diff --git a/docs/requirements/061-nextcloud-talk-hpb-decoupled.md b/docs/requirements/061-nextcloud-talk-hpb-decoupled.md new file mode 100644 index 0000000000..15f3a66cdc --- /dev/null +++ b/docs/requirements/061-nextcloud-talk-hpb-decoupled.md @@ -0,0 +1,24 @@ +# 061 - Nextcloud Talk high-performance backend from pinned upstream components + +## User Story + +As an operator, I want the Nextcloud Talk high-performance backend and recording server to run as separate services built from semver-pinned upstream sources, with every configuration file rendered by `web-app-nextcloud`, so that the updater can raise their versions automatically and no upstream start script can overwrite the role's configuration. + +## Acceptance Criteria + +- [x] `roles/web-app-nextcloud/meta/services.yml` no longer references `nextcloud/aio-talk` or `nextcloud/aio-talk-recording`. +- [x] The signaling server runs as its own service from the upstream `nextcloud-spreed-signaling` project, pinned to a semver version without a `# nocheck: docker-version` marker. +- [x] Janus runs as its own service from an image the role builds from a semver git tag of `meetecho/janus-gateway`. +- [x] NATS runs as its own service from the official `nats` image pinned to a semver version. +- [x] The recording server runs as its own service from an image the role builds from a semver release tag of `nextcloud/nextcloud-talk-recording`. +- [x] The role renders the signaling `server.conf`, `janus.jcfg` and the recording `server.conf`; no file inside an image regenerates or overwrites them at container start. +- [x] The Janus config drift guard in `tasks/01_fullstack.yml` and the `janus_config_drift` filter are removed together with their tests. +- [ ] `utils/update` reports a newer upstream version for each of the four pins, and `tests/lint/ansible/services/test_version_pins_are_watched` passes for them. +- [ ] The public signaling endpoint stays `/standalone-signaling/`, and the Talk admin settings show the pinned signaling version as "Running version" with `chat-relay` not listed as missing. +- [ ] Direct media keeps working: with `services.talk.network_mode: host`, `nat_1_1_mapping` carries the public IP and `test-talk-call-capacity.js` passes. +- [ ] A recording started from a Talk call through the recording server produces a file, verified by a Playwright or CLI test. +- [ ] Each new service has its own healthcheck and resource limits, and in swarm the services Janus shares a network namespace with are placed on the same node. +- [ ] Deploying over an existing `aio-talk` installation removes the old container or swarm service and starts the new services with the existing signaling, TURN and recording secrets in one deploy. +- [x] No secret of the new services appears in a container's argv; secrets reach them through config files or environment. +- [ ] `web-app-nextcloud` with Talk enabled is green in a compose and a swarm roundtrip, including the Talk Playwright specs. +- [x] `roles/web-app-nextcloud/README.md` and `docs/Administration.md` describe the four services, their sources and how a version update reaches them. diff --git a/group_vars/all/04_webserver.yml b/group_vars/all/04_webserver.yml index 4dd42d205a..05a1e44a87 100644 --- a/group_vars/all/04_webserver.yml +++ b/group_vars/all/04_webserver.yml @@ -10,3 +10,13 @@ WEBSERVER_WORKER_PROCESSES: >- }} WEBSERVER_WORKER_CONNECTIONS: "{{ lookup('webserver_resource', 'pids_limit') }}" + +# Response security headers of every vhost; an app overrides any key under `security_headers` in its meta/server.yml. +WEBSERVER_SECURITY_HEADERS: + nosniff: false # X-Content-Type-Options: nosniff + referrer_policy: "" # Referrer-Policy, sent only when the upstream sends none; "" sends none + permissions_policy: "" # Permissions-Policy on HTML documents; "" sends none + hsts: + max_age: 31536000 # Strict-Transport-Security max-age in seconds + include_subdomains: false # adds includeSubDomains, which covers every subdomain of the vhost + preload: false # adds preload; requires include_subdomains and a max_age of one year diff --git a/group_vars/all/05_paths.yml b/group_vars/all/05_paths.yml index 56bff92e2f..5436be4f36 100644 --- a/group_vars/all/05_paths.yml +++ b/group_vars/all/05_paths.yml @@ -33,8 +33,10 @@ DIR_METRICS_TEXTFILE: "{{ [DIR_VAR_LIB, 'metrics'] | path_join }}" DIR_PHP_HARDENING: "/etc/{{ SOFTWARE_DOMAIN }}/php" PHP_HARDENING_INI_DIGEST: "{{ (lookup('file', lookup('path_absolute', 'roles/sys-svc-compose-php/files/hardening.ini')) | hash('sha1'))[:8] }}" +PHP_MEMORY_UNLIMITED_INI_DIGEST: "{{ (lookup('file', lookup('path_absolute', 'roles/sys-svc-compose-php/files/memory-unlimited.ini')) | hash('sha1'))[:8] }}" PHP_FPM_HARDENING_CONF_DIGEST: "{{ (lookup('template', lookup('path_absolute', 'roles/sys-svc-compose-php/templates/fpm-hardening.conf.j2')) | hash('sha1'))[:8] }}" FILE_PHP_HARDENING_INI: "{{ [DIR_PHP_HARDENING, 'hardening-' ~ PHP_HARDENING_INI_DIGEST ~ '.ini'] | path_join }}" +FILE_PHP_MEMORY_UNLIMITED_INI: "{{ [DIR_PHP_HARDENING, 'memory-unlimited-' ~ PHP_MEMORY_UNLIMITED_INI_DIGEST ~ '.ini'] | path_join }}" FILE_PHP_FPM_HARDENING_CONF: "{{ [DIR_PHP_HARDENING, 'fpm-hardening-' ~ PHP_FPM_HARDENING_CONF_DIGEST ~ '.conf'] | path_join }}" DIR_RESCUE_DIAGNOSTICS: "/tmp/infinito-rescue-diagnostics" diff --git a/plugins/action/applications_carrier.py b/plugins/action/applications_carrier.py index d7da126d30..39cae6ed84 100644 --- a/plugins/action/applications_carrier.py +++ b/plugins/action/applications_carrier.py @@ -1,11 +1,13 @@ -"""Render the applications SPOT once and park it as the play-scoped carrier fact. +"""Render the applications and users SPOTs once and park them as play-scoped carrier facts. -Ansible forks a fresh worker per task, so the in-process render cache of -``lookup('applications')`` is cold in every task until something renders in -a place all later workers inherit. This action renders in the worker of one -constructor task and returns the payload as a host fact; every later worker -inherits that fact at fork time and ``get_merged_applications`` serves it -instead of rendering:: +Ansible forks a fresh worker per task, so the in-process render caches of +``lookup('applications')`` and ``lookup('users')`` are cold in every task +until something renders in a place all later workers inherit. This action +renders in the worker of one constructor task and returns both payloads as +host facts; every later worker inherits them at fork time and +``get_merged_applications`` / ``get_merged_users`` serve them instead of +rendering. The users carrier is keyed like the applications carrier plus +the token store digest and ``inventory_hostname``:: - name: 🧊 Render the applications SPOT once and carry it into every task's worker applications_carrier: {} @@ -13,11 +15,12 @@ instead of rendering:: ``tasks/stages/01_constructor.yml`` parks three of them: a block-scoped one for the merge block, which it drops again at the block's end, one after the ``add_host`` tasks for the swarm bootstrap roles, parked only when -``DEPLOYMENT_MODE`` is ``swarm``, and the stage-wide one after the token store. ``merged_applications_cache_key`` reads ``group_names`` and a -digest of the tokens the users are hydrated from (the tokens file, or the -``sys_token_store_users`` fact once the token store loaded; both key alike for -the same tokens), so a carrier whose groups or tokens no longer match is -rejected and the reader renders afresh:: +``DEPLOYMENT_MODE`` is ``swarm``, and the stage-wide one after the token store. ``merged_applications_cache_key`` reads ``group_names``, so a +carrier whose groups no longer match is rejected and the reader renders +afresh. ``merged_users_cache_key`` adds a digest of the tokens the users are +hydrated from (the tokens file, or the ``sys_token_store_users`` fact once the +token store loaded; both key alike for the same tokens), so changed tokens +reject the users carrier only:: - name: 🧊 Drop the merge-block carrier so later stages re-render applications_carrier: @@ -26,14 +29,16 @@ rejected and the reader renders afresh:: ``tasks/utils/setup/role.yml`` parks one after every role, ``tasks/utils/load/app.yml`` one after every nested application load and ``roles/sys-token-store/tasks/write_many.yml`` one after every store write; -where the key still matches they serve the carried payload without rendering. +where the key still matches they serve the carried payload without rendering, +and a users carrier that still matches is left in place instead of being +returned again. A store write therefore re-renders the users alone. -The result is masked by the action itself: the fact is the whole rendered -tree, about 0.4 MB with every application's credentials, and printing it at -``-v`` is neither credential debugging nor readable. +The result is masked by the action itself: the facts are the whole rendered +trees, about 0.4 MB with every application's and user's credentials, and +printing them at ``-v`` is neither credential debugging nor readable. Args: - clear: drop the carrier fact instead of rendering. Defaults to false. + clear: drop both carrier facts instead of rendering. Defaults to false. Any other argument is an error. """ @@ -46,7 +51,12 @@ from ansible.module_utils.parsing.convert_bool import boolean from ansible.plugins.action import ActionBase from ansible.plugins.loader import lookup_loader -from utils.cache.carrier import APPLICATIONS_RENDERED_FACT, revalidate_tokens_file +from utils.cache.carrier import ( + APPLICATIONS_RENDERED_FACT, + USERS_RENDERED_FACT, + _carried_users, + revalidate_tokens_file, +) class ActionModule(ActionBase): @@ -67,7 +77,11 @@ class ActionModule(ActionBase): if boolean(args.get("clear", False)): result.update( - changed=False, ansible_facts={APPLICATIONS_RENDERED_FACT: None} + changed=False, + ansible_facts={ + APPLICATIONS_RENDERED_FACT: None, + USERS_RENDERED_FACT: None, + }, ) return result @@ -77,16 +91,25 @@ class ActionModule(ActionBase): previous = self._templar.available_variables self._templar.available_variables = render_vars try: - lookup = lookup_loader.get( - "applications", loader=self._loader, templar=self._templar - ) - carrier = lookup.run([], variables=render_vars, carrier=True)[0] + carriers = { + fact: lookup_loader.get( + name, loader=self._loader, templar=self._templar + ).run([], variables=render_vars, carrier=True)[0] + for fact, name in ( + (APPLICATIONS_RENDERED_FACT, "applications"), + (USERS_RENDERED_FACT, "users"), + ) + } finally: self._templar.available_variables = previous + users_key = carriers[USERS_RENDERED_FACT]["key"] + if _carried_users(task_vars, (users_key[0], tuple(users_key[1]))) is not None: + del carriers[USERS_RENDERED_FACT] + result.update( changed=False, - ansible_facts={APPLICATIONS_RENDERED_FACT: carrier}, + ansible_facts=carriers, _ansible_no_log=True, ) return result diff --git a/plugins/filter/README.md b/plugins/filter/README.md index 44bfac94af..aa56377245 100644 --- a/plugins/filter/README.md +++ b/plugins/filter/README.md @@ -33,13 +33,14 @@ flowchart TD grant["csp_filters.py:354
logout grant"] wl["csp_filters.py:123
get_csp_whitelist"] inj["sys-front-inj-dashboard,
-javascript, -matomo, -logout
add_csp_hash"] - gate["csp_filters.py:365
hash gate"] + gate["csp_filters.py:366
hash gate"] build["csp_filters.py:203
build_csp_header"] header["set $csp
nginx vhost"] decl -->|"1. flags read by"| flags flags -->|"2. tokens"| build svc -->|"3. read by"| grant + decl -->|"3a. unsafe-inline: false
on -elem or -attr vetoes"| grant grant -->|"4. adds 'unsafe-inline'
to script-src-elem and -attr"| build decl -->|"5. whitelist read by"| wl wl -->|"6. tokens"| build @@ -52,7 +53,7 @@ flowchart TD grant -.->|"TRIP-WIRE: absent from the
smart-defaults docstring, which
names logout only for frame-ancestors"| build ``` -Styles carry `'unsafe-inline'` by default; scripts do not. The logout grant is the only path that puts it into a script directive. +Styles carry `'unsafe-inline'` by default; scripts do not. The logout grant is the only implicit path that puts it into a script directive. An application keeps it out of `script-src-elem` or `script-src-attr` by setting `unsafe-inline: false` on that directive in its `meta/csp.yml`. ## Further Reading diff --git a/plugins/filter/csp_filters.py b/plugins/filter/csp_filters.py index be667a0d21..c390d0e9d8 100644 --- a/plugins/filter/csp_filters.py +++ b/plugins/filter/csp_filters.py @@ -369,10 +369,11 @@ class FilterModule: tokens.append(provider("web-svc-logout")) tokens.append(provider("web-app-keycloak")) - if directive in ( - "script-src-attr", - "script-src-elem", - ) and self.is_feature_enabled(applications, "logout", application_id): + if ( + directive in ("script-src-attr", "script-src-elem") + and self.is_feature_enabled(applications, "logout", application_id) + and explicit_flags.get("unsafe-inline") is not False + ): tokens.append("'unsafe-inline'") tokens += self.get_csp_whitelist( diff --git a/plugins/filter/security_headers.py b/plugins/filter/security_headers.py new file mode 100644 index 0000000000..78af696964 --- /dev/null +++ b/plugins/filter/security_headers.py @@ -0,0 +1,10 @@ +"""Expose the response security headers of one application to templates.""" + +from __future__ import annotations + +from utils.roles.applications.security_headers import security_headers + + +class FilterModule: + def filters(self): + return {"security_headers": security_headers} diff --git a/plugins/lookup/proxy_hops.py b/plugins/lookup/proxy_hops.py new file mode 100644 index 0000000000..b1de021516 --- /dev/null +++ b/plugins/lookup/proxy_hops.py @@ -0,0 +1,61 @@ +"""Lookup ``proxy_hops``: the addresses the reverse proxy's requests reach an +application from, for that application's trusted-proxy list. + +Usage: + + {{ lookup('proxy_hops', application_id) }} # compose: ['192.168.41.1', '192.168.201.1'] + # swarm: ['192.168.107.0/24'] + +Returns what :func:`utils.networks.proxy.proxy_hops` derives from the networks +the service_registry attaches. +""" + +from __future__ import annotations + +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +from utils.networks.lookup_context import build_context, resolve_var +from utils.networks.proxy import proxy_hops +from utils.networks.render import compute_external_network_roles + + +class LookupModule(LookupBase): + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[Any]: + if not terms or len(terms) != 1: + raise AnsibleError( + "proxy_hops lookup requires exactly one term: application_id" + ) + + ctx = build_context(self, variables) + application_id = str(resolve_var(ctx.templar, terms[0])) + role_subnets = lookup_loader.get( + "role_subnets", loader=self._loader, templar=ctx.templar + ) + + def network_roles(role: str) -> list[str]: + return compute_external_network_roles( + application_id=role, + deployment_mode=ctx.deployment_mode, + registry=ctx.registry, + lookup_config=ctx.lookup_config, + lookup_database=ctx.lookup_database, + ) + + def subnets(roles: list[str]) -> list[str]: + return role_subnets.run([roles], variables=ctx.vars)[0] + + try: + return [ + proxy_hops(application_id, ctx.deployment_mode, network_roles, subnets) + ] + except ValueError as exc: + raise AnsibleError(f"proxy_hops: {exc}") from exc diff --git a/plugins/lookup/users.py b/plugins/lookup/users.py index 099110bcba..cedcf6516a 100644 --- a/plugins/lookup/users.py +++ b/plugins/lookup/users.py @@ -6,6 +6,7 @@ from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase from utils.cache import _reset_cache_for_tests as _reset_runtime_lookup_cache +from utils.cache.carrier import merged_users_cache_key # nocheck: lookup-cache-import (this lookup IS the users SPOT provider) from utils.cache.users import get_merged_users @@ -22,21 +23,39 @@ class LookupModule(LookupBase): variables: dict[str, Any] | None = None, **kwargs: Any, ) -> list[Any]: + """ + Terms: + 0) full merged mapping + 1) canonical_user_key + 2) canonical_user_key, default value + + Keyword arguments: + roles_dir: roles tree to build from (defaults to the repository's) + carrier: with no terms, return ``{"key": [...], "users": {...}}`` + for the constructor to park in `_INFINITO_USERS_RENDERED` + """ terms = terms or [] if len(terms) > 2: raise AnsibleError( "users: expected 0, 1, or 2 terms: " "lookup('users'[, canonical_user_key[, default]])" ) + carrier = bool(kwargs.get("carrier", False)) + if carrier and terms: + raise AnsibleError("users: carrier=True takes no terms") + variables = variables or getattr(self._templar, "available_variables", {}) or {} + roles_dir = kwargs.get("roles_dir") users = get_merged_users( - variables=variables - or getattr(self._templar, "available_variables", {}) - or {}, - roles_dir=kwargs.get("roles_dir"), + variables=variables, + roles_dir=roles_dir, templar=getattr(self, "_templar", None), ) + if carrier: + key = merged_users_cache_key(variables, roles_dir=roles_dir) + return [{"key": [key[0], list(key[1])], "users": users}] + if len(terms) == 0: return [users] diff --git a/roles/pkgmgr/meta/services.yml b/roles/pkgmgr/meta/services.yml index 079f44d0e8..ea3a8c7739 100644 --- a/roles/pkgmgr/meta/services.yml +++ b/roles/pkgmgr/meta/services.yml @@ -3,4 +3,4 @@ pkgmgr: lifecycle: beta repository: https://github.com/kevinveenbirkenbach/package-manager.git - ref: v2.0.4 + ref: v2.0.5 diff --git a/roles/svc-prx-openresty/tasks/00_core.yml b/roles/svc-prx-openresty/tasks/00_core.yml index c15faf0fd8..3949a903ad 100644 --- a/roles/svc-prx-openresty/tasks/00_core.yml +++ b/roles/svc-prx-openresty/tasks/00_core.yml @@ -1,19 +1,6 @@ --- - include_tasks: utils/once/flag.yml -- when: IS_SWARM_MODE - block: - - name: "πŸ”Ž Stat the docker socket so the swarm openresty worker can be group-added to it" - ansible.builtin.stat: - # nocheck: volumes-path-single-spot this stats the socket on the HOST; it only happens to spell the same string as the container mount target - path: /var/run/docker.sock - register: _openresty_docker_sock - - - name: "πŸ”§ Set OPENRESTY_DOCKER_SOCK_GID from the live socket gid" - ansible.builtin.set_fact: - OPENRESTY_DOCKER_SOCK_GID: "{{ _openresty_docker_sock.stat.gid }}" - when: _openresty_docker_sock.stat.exists | default(false) - - name: "βœ… Ensure the full openresty config tree exists before any http-include writer" directory_batch: entries: >- @@ -49,17 +36,6 @@ vars: compose_handlers_flush: true -- name: "πŸ”§ Add openresty to docker.sock group for swarm (stack deploy rejects group_add)" - ansible.builtin.command: >- - container service update --detach=false - --group-add {{ OPENRESTY_DOCKER_SOCK_GID | quote }} - {{ lookup('container_service', application_id, 'openresty') | quote }} - changed_when: true - delegate_to: "{{ STACK_HOST }}" - when: - - IS_SWARM_MODE - - OPENRESTY_DOCKER_SOCK_GID is defined - - name: "βœ… Verify that '{{ role_name }}' works" include_tasks: 01_assert.yml when: MODE_ASSERT_LOCAL | bool diff --git a/roles/sys-front-tls/templates/nginx_ssl_header.j2 b/roles/sys-front-tls/templates/nginx_ssl_header.j2 index ae24cd11f7..4ba5dce035 100644 --- a/roles/sys-front-tls/templates/nginx_ssl_header.j2 +++ b/roles/sys-front-tls/templates/nginx_ssl_header.j2 @@ -11,7 +11,7 @@ ssl_session_timeout 1d; ssl_session_cache shared:SSL:50m; ssl_session_tickets on; -add_header Strict-Transport-Security max-age=31536000 always; +add_header Strict-Transport-Security "{{ (lookup('applications') | security_headers(application_id, WEBSERVER_SECURITY_HEADERS)).hsts }}" always; {% include 'roles/sys-front-tls/templates/ssl_credentials.j2' %} diff --git a/roles/sys-svc-compose-php/README.md b/roles/sys-svc-compose-php/README.md index 3f78916474..44348f719e 100644 --- a/roles/sys-svc-compose-php/README.md +++ b/roles/sys-svc-compose-php/README.md @@ -8,11 +8,14 @@ configs from their own `meta/volumes.yml`. ## Overview -This role installs one PHP ini (`FILE_PHP_HARDENING_INI`) and one PHP-FPM pool -drop-in (`FILE_PHP_FPM_HARDENING_CONF`). A PHP role opts in by declaring a +This role installs one PHP ini (`FILE_PHP_HARDENING_INI`), one interim PHP ini +(`FILE_PHP_MEMORY_UNLIMITED_INI`) and one PHP-FPM pool drop-in +(`FILE_PHP_FPM_HARDENING_CONF`). A PHP role opts in by declaring a `type: config` entry with that file as `source` and a file inside the scan dir of its image as `target`, e.g. `conf.d/zz-infinito-hardening.ini` or, for the -pool, `php-fpm.d/zz-infinito-hardening.conf`. +pool, `php-fpm.d/zz-infinito-hardening.conf`. Only roles whose image still +ships a PHP release without the CVE-2026-109618 fix also mount +`FILE_PHP_MEMORY_UNLIMITED_INI`, as `conf.d/zz-infinito-memory-unlimited.ini`. ## Cosmos @@ -29,5 +32,6 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( ## Features -- **PHP ini hardening:** `expose_php` off; `session.upload_progress.enabled = 0` and, on PHP 8.5 only, `fatal_error_backtraces = 0` against CVE-2026-109619; the interim `memory_limit = -1` against CVE-2026-109618. +- **PHP ini hardening:** `expose_php` off; `session.upload_progress.enabled = 0` and, on PHP 8.5 only, `fatal_error_backtraces = 0` against CVE-2026-109619. +- **Interim CVE-2026-109618 mitigation:** `memory_limit = -1` for images that predate PHP 8.2.35, 8.3.36, 8.4.27 and 8.5.12. - **PHP-FPM worker recycling:** `pm.max_requests` from `PHP_FPM_MAX_REQUESTS` for images whose `[www]` pool reads `php-fpm.d/*.conf`. diff --git a/roles/sys-svc-compose-php/files/hardening.ini b/roles/sys-svc-compose-php/files/hardening.ini index 2e5a25ec09..20ac81b037 100644 --- a/roles/sys-svc-compose-php/files/hardening.ini +++ b/roles/sys-svc-compose-php/files/hardening.ini @@ -1,4 +1,3 @@ expose_php = Off session.upload_progress.enabled = 0 fatal_error_backtraces = 0 -memory_limit = -1 diff --git a/roles/sys-svc-compose-php/files/memory-unlimited.ini b/roles/sys-svc-compose-php/files/memory-unlimited.ini new file mode 100644 index 0000000000..7999e96156 --- /dev/null +++ b/roles/sys-svc-compose-php/files/memory-unlimited.ini @@ -0,0 +1 @@ +memory_limit = -1 diff --git a/roles/sys-svc-compose-php/tasks/00_core.yml b/roles/sys-svc-compose-php/tasks/00_core.yml index c974b5eee9..fb69a45693 100644 --- a/roles/sys-svc-compose-php/tasks/00_core.yml +++ b/roles/sys-svc-compose-php/tasks/00_core.yml @@ -17,6 +17,15 @@ owner: root group: root +- name: "πŸ›‘οΈ PHP hardening | install interim memory ini" + become: true + stack_host_copy: + src: "memory-unlimited.ini" + dest: "{{ FILE_PHP_MEMORY_UNLIMITED_INI }}" + mode: "0444" + owner: root + group: root + - name: "πŸ›‘οΈ PHP hardening | render FPM pool" become: true stack_host_template: diff --git a/roles/sys-svc-compose/handlers/compose.yml b/roles/sys-svc-compose/handlers/compose.yml index c332676728..e203128c71 100644 --- a/roles/sys-svc-compose/handlers/compose.yml +++ b/roles/sys-svc-compose/handlers/compose.yml @@ -33,7 +33,7 @@ - name: πŸ”¨ Build compose ansible.builtin.shell: | set -euo pipefail - compose build + compose build --pull || compose build args: chdir: "{{ lookup('container', application_id, 'directories.instance') }}" executable: /bin/bash @@ -129,7 +129,7 @@ - name: πŸ”¨ Build the services queued for a lone recreate ansible.builtin.shell: | set -euo pipefail - compose build {{ compose_service_up_targets | map('quote') | join(' ') }} + compose build --pull {{ compose_service_up_targets | map('quote') | join(' ') }} || compose build {{ compose_service_up_targets | map('quote') | join(' ') }} args: chdir: "{{ lookup('container', application_id, 'directories.instance') }}" executable: /bin/bash diff --git a/roles/sys-svc-container/templates/daemon.json.j2 b/roles/sys-svc-container/templates/daemon.json.j2 index 31b781fd7e..c3cd09553b 100644 --- a/roles/sys-svc-container/templates/daemon.json.j2 +++ b/roles/sys-svc-container/templates/daemon.json.j2 @@ -19,6 +19,7 @@ "dns-search": ["{{ DOMAIN_PRIMARY }}"], "dns-opts": ["ndots:0"], "default-address-pools": {{ NETWORK_DOCKER_ADDRESS_POOLS | tojson }}, + "userland-proxy": false, "log-driver": "json-file", "log-opts": {"max-size": "10m", "max-file": "2"} {% if DOCKER_IN_CONTAINER | bool %}, diff --git a/roles/sys-svc-proxy/README.md b/roles/sys-svc-proxy/README.md index 4a16fd6c16..c7531b3103 100644 --- a/roles/sys-svc-proxy/README.md +++ b/roles/sys-svc-proxy/README.md @@ -18,7 +18,31 @@ The goal of this role is to deliver a **hassle-free, production-ready reverse pr - **Automatic TLS & HSTS**: integrates with the *sys-svc-webserver-https* role for certificate management. - **Flexible vHost templates**: *basic* and *ws_generic* flavours cover standard HTTP and WebSocket applications. -- **Security headers**: sensible defaults plus optional X-Frame-Options / CSP based on application settings. +- **Security headers**: CSP from each role's `meta/csp.yml`, plus the per-role headers described in [Security Headers](#security-headers). - **WebSocket & HTTP/2 aware**: upgrades, keep-alive tuning, and gzip already configured. - **OAuth2 gating**: drop-in support when *web-app-keycloak's SSO-proxy sidecar* is present. - **Modular includes**: headers, locations, and global snippets are factored for easy extension. + +## Security Headers + +`WEBSERVER_SECURITY_HEADERS` in [04_webserver.yml](../../group_vars/all/04_webserver.yml) holds the platform values. A role overrides any key under `security_headers` in its `meta/server.yml`; an inventory overrides it at `applications..server.security_headers`. + +```yaml +# roles//meta/server.yml +security_headers: + nosniff: true + referrer_policy: strict-origin-when-cross-origin + permissions_policy: 'camera=(self "https://meet.example.org"), microphone=(self)' + hsts: + include_subdomains: true + preload: true +``` + +| Key | Header | Where it is rendered | +|---|---|---| +| `nosniff` | `X-Content-Type-Options: nosniff` | every response of a location that includes [content_security_policy.conf.j2](templates/headers/content_security_policy.conf.j2) | +| `referrer_policy` | `Referrer-Policy` | the same locations, only when the upstream sends none | +| `permissions_policy` | `Permissions-Policy` | HTML documents of the same locations | +| `hsts.*` | `Strict-Transport-Security` | the server block of every TLS vhost, via [nginx_ssl_header.j2](../sys-front-tls/templates/nginx_ssl_header.j2); an onion vhost has no TLS and gets none | + +The `security_headers` filter rejects unknown keys, wrong types, unknown `Referrer-Policy` tokens, and `preload` without `include_subdomains` or below a one-year `max_age`. diff --git a/roles/sys-svc-proxy/templates/headers/content_security_policy.conf.j2 b/roles/sys-svc-proxy/templates/headers/content_security_policy.conf.j2 index 9b06bac3c7..8ac429ddd7 100644 --- a/roles/sys-svc-proxy/templates/headers/content_security_policy.conf.j2 +++ b/roles/sys-svc-proxy/templates/headers/content_security_policy.conf.j2 @@ -18,6 +18,8 @@ header_filter_by_lua_block { ngx.header["Content-Security-Policy-Report-Only"] = nil end +{% include 'roles/sys-svc-proxy/templates/headers/security_headers.lua.j2' %} + if is_html then ngx.ctx.is_html = true ngx.header.content_length = nil diff --git a/roles/sys-svc-proxy/templates/headers/security_headers.lua.j2 b/roles/sys-svc-proxy/templates/headers/security_headers.lua.j2 new file mode 100644 index 0000000000..58dd96ed17 --- /dev/null +++ b/roles/sys-svc-proxy/templates/headers/security_headers.lua.j2 @@ -0,0 +1,14 @@ +{% set _security_headers = lookup('applications') | security_headers(application_id, WEBSERVER_SECURITY_HEADERS) %} +{% if _security_headers.nosniff %} + ngx.header["X-Content-Type-Options"] = "nosniff" +{% endif %} +{% if _security_headers.referrer_policy %} + if not ngx.header["Referrer-Policy"] then + ngx.header["Referrer-Policy"] = {{ _security_headers.referrer_policy | to_json }} + end +{% endif %} +{% if _security_headers.permissions_policy %} + if is_html then + ngx.header["Permissions-Policy"] = {{ _security_headers.permissions_policy | to_json }} + end +{% endif %} diff --git a/roles/sys-token-store/README.md b/roles/sys-token-store/README.md index 75eaa0dca1..5a47c0f771 100644 --- a/roles/sys-token-store/README.md +++ b/roles/sys-token-store/README.md @@ -90,7 +90,7 @@ Empty tokens are rejected explicitly. `write.yml` hands its token to `write_many ### `write_many.yml` -Persists several tokens with one store write and at most one re-render of the applications SPOT. +Persists several tokens with one store write and at most one re-render of the users SPOT. **Input** @@ -99,7 +99,7 @@ Persists several tokens with one store write and at most one re-render of the ap **Effects** - Merges every entry into the store in list order, so a later entry for the same user and app wins -- Writes the store file and re-renders the applications SPOT once, and only when the merged store differs from the loaded one +- Writes the store file and re-renders the users SPOT once, and only when the merged store differs from the loaded one --- diff --git a/roles/sys-token-store/tasks/write_many.yml b/roles/sys-token-store/tasks/write_many.yml index 2f2862ab65..70482d47f8 100644 --- a/roles/sys-token-store/tasks/write_many.yml +++ b/roles/sys-token-store/tasks/write_many.yml @@ -60,6 +60,6 @@ sys_token_store_users: "{{ sys_token_store_users_merged }}" no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" -- name: "🧊 Re-render the applications SPOT the new tokens invalidated" +- name: "🧊 Re-render the users SPOT the new tokens invalidated" applications_carrier: {} when: sys_token_store_persisted is changed or sys_token_store_mirrored is changed diff --git a/roles/web-app-bookwyrm/meta/services.yml b/roles/web-app-bookwyrm/meta/services.yml index 596ebae0cc..843ed9945d 100644 --- a/roles/web-app-bookwyrm/meta/services.yml +++ b/roles/web-app-bookwyrm/meta/services.yml @@ -64,7 +64,7 @@ bookwyrm: version: 3.11-slim custom: true repository: https://github.com/bookwyrm-social/bookwyrm.git - ref: v0.9.3 + ref: v0.9.4 min_storage: 579MB registration_open: false allow_invite_request: false diff --git a/roles/web-app-dashboard/files/playwright/test-csp-canonical-domain.js b/roles/web-app-dashboard/files/playwright/test-csp-canonical-domain.js index 3edfdebcaf..63f1448081 100644 --- a/roles/web-app-dashboard/files/playwright/test-csp-canonical-domain.js +++ b/roles/web-app-dashboard/files/playwright/test-csp-canonical-domain.js @@ -23,6 +23,12 @@ exports.register = function (shared) { const directives = assertCspResponseHeader(response, "dashboard landing"); await assertCspMetaParity(page, directives, "dashboard landing"); + for (const directive of ["script-src", "script-src-elem"]) { + expect( + directives[directive], + `dashboard landing: ${directive} MUST NOT carry 'unsafe-inline', inline scripts run by hash` + ).not.toContain("'unsafe-inline'"); + } const documentHtml = await response.text(); const documentUrl = response.url(); diff --git a/roles/web-app-dashboard/lookup_plugins/docker_cards.py b/roles/web-app-dashboard/lookup_plugins/docker_cards.py index 5d08d82b0c..a0d9a83d36 100644 --- a/roles/web-app-dashboard/lookup_plugins/docker_cards.py +++ b/roles/web-app-dashboard/lookup_plugins/docker_cards.py @@ -9,7 +9,11 @@ from ansible.plugins.lookup import LookupBase from utils.cache.files import read_text from utils.cache.yaml import load_yaml_any from utils.roles.applications.config import get -from utils.roles.applications.dashboard import DASHBOARD_SERVICE, card_target_key +from utils.roles.applications.dashboard import ( + DASHBOARD_SERVICE, + card_is_displayed, + card_target_key, +) from utils.roles.mapping import ( ROLE_FILE_META_INFO, ROLE_FILE_META_MAIN, @@ -27,7 +31,8 @@ class LookupModule(LookupBase): - Reads the title from the role's README.md (the first H1 line) - Retrieves the description from galaxy_info.description in meta/main.yml - Retrieves the icon class from meta/info.yml.logo.class - - Retrieves the display flag from meta/info.yml.display + - Skips the role when services.dashboard.enabled in applications + is false - Retrieves the tags from galaxy_info.galaxy_tags - Builds the URL from the primary domain, or from the domains.canonical key named by services.dashboard.card @@ -114,7 +119,14 @@ class LookupModule(LookupBase): except Exception as e: raise AnsibleError(f"Error reading '{info_path}': {e}") from e - if not info_data.get("display", True): + dashboard_cfg = get( + applications, + application_id, + f"services.{DASHBOARD_SERVICE}", + strict=False, + default={}, + ) + if not card_is_displayed(application_id, dashboard_cfg): continue logo = info_data.get("logo") or {} @@ -134,14 +146,6 @@ class LookupModule(LookupBase): self._templar.template(domain_url).strip() if domain_url else "" ) - dashboard_cfg = get( - applications, - application_id, - f"services.{DASHBOARD_SERVICE}", - strict=False, - default={}, - ) - url = "" if domain_url: card_key = card_target_key(application_id, dashboard_cfg) diff --git a/roles/web-app-dashboard/meta/csp.yml b/roles/web-app-dashboard/meta/csp.yml index af37f51006..ebb36ca255 100644 --- a/roles/web-app-dashboard/meta/csp.yml +++ b/roles/web-app-dashboard/meta/csp.yml @@ -18,5 +18,9 @@ whitelist: - "*.{{ DOMAIN_PRIMARY }}" - "{{ lookup('domain', 'web-app-keycloak') }}" flags: + script-src: + unsafe-inline: false + script-src-elem: + unsafe-inline: false script-src-attr: - unsafe-inline: true # nocheck: csp-unsafe Reason: historical, TODO: re-verify it is really required and does not open attack surface + unsafe-inline: true # nocheck: csp-unsafe Reason: port-ui 2.2.2 renders inline event handlers (menu onclick entries, openDynamicPopup, closeAllModals, card image onerror) diff --git a/roles/web-app-fider/README.md b/roles/web-app-fider/README.md index 5195f69497..25aedddece 100644 --- a/roles/web-app-fider/README.md +++ b/roles/web-app-fider/README.md @@ -8,7 +8,7 @@ This role deploys Fider as part of the Infinito.Nexus stack using a single Docker Compose container backed by PostgreSQL. It configures SSO via Keycloak automatically on first deploy, optional email notifications via Mailu, and HTTPS via NGINX reverse proxy. -The setup tasks handle the full first-deploy bootstrap automatically: +The setup tasks handle the full first-deploy bootstrap automatically. Steps 1 to 3 run on every deploy, with or without SSO; step 4 runs only when `services.sso.enabled` is `true`: 1. **Tenant bootstrap:** calls Fider's `POST /_api/tenants` API to create the initial tenant. 2. **Admin user creation:** inserts the admin user directly into the `users` table, bypassing email verification. Idempotent via `WHERE NOT EXISTS`. diff --git a/roles/web-app-fider/TODO.md b/roles/web-app-fider/TODO.md deleted file mode 100644 index c5eb7813a8..0000000000 --- a/roles/web-app-fider/TODO.md +++ /dev/null @@ -1,3 +0,0 @@ -# TODO - -- With `services.sso.enabled` false the role creates no tenant: `tasks/00_core.yml` includes `tasks/01_setup_oidc.yml` (tenant bootstrap, administrator, activation, provider row) only under `FIDER_OIDC_ENABLED`. Upstream then redirects every route to its installation form `/signup`, which any visitor can submit (read from the task conditions and from `app/middlewares/tenant.go` and `app/handlers/signup.go` of the deployed commit `67c52826`; the compose stack of the design pass ran with `sso` on). Fider has no password sign-in, so such a deployment also has no account. Options: bootstrap tenant and administrator in every variant and keep only the provider row under the flag; or refuse `/signup` at the proxy while no tenant exists. diff --git a/roles/web-app-fider/tasks/00_core.yml b/roles/web-app-fider/tasks/00_core.yml index 92acea82ae..f942171570 100644 --- a/roles/web-app-fider/tasks/00_core.yml +++ b/roles/web-app-fider/tasks/00_core.yml @@ -20,12 +20,16 @@ - name: "🚿 Flush compose handlers for {{ application_id }}" ansible.builtin.meta: flush_handlers -- name: "🧭 Converge sign-in provider and design of {{ application_id }}" +- name: "πŸ₯Ύ Fider | Tenant bootstrap" + include_tasks: 01_tenant.yml when: IS_STACK_HOST | bool - block: - - name: "πŸ”§ Fider | OIDC setup" - include_tasks: 01_setup_oidc.yml - when: FIDER_OIDC_ENABLED | bool - - name: "🎨 Fider | Corporate design" - include_tasks: 02_design.yml +- name: "πŸ”§ Fider | OIDC setup" + include_tasks: 02_setup_oidc.yml + when: + - FIDER_OIDC_ENABLED | bool + - IS_STACK_HOST | bool + +- name: "🎨 Fider | Corporate design" + include_tasks: 03_design.yml + when: IS_STACK_HOST | bool diff --git a/roles/web-app-fider/tasks/01_setup_oidc.yml b/roles/web-app-fider/tasks/01_tenant.yml similarity index 73% rename from roles/web-app-fider/tasks/01_setup_oidc.yml rename to roles/web-app-fider/tasks/01_tenant.yml index eb7ec11f34..c9eb6487f3 100644 --- a/roles/web-app-fider/tasks/01_setup_oidc.yml +++ b/roles/web-app-fider/tasks/01_tenant.yml @@ -41,19 +41,29 @@ body_format: json body: "{{ FIDER_TENANT_BOOTSTRAP_BODY }}" status_code: [200, 201] + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" when: - IS_COMPOSE_MODE - (fider_tenant_count.rows[0][0] | int) == 0 -- name: "πŸ₯Ύ Fider | Bootstrap initial tenant via API (swarm, routing-mesh port)" - uri_retry: - url: "http://127.0.0.1:{{ lookup('config', application_id, 'services.fider.ports.local.http') }}/_api/tenants" - method: POST - body_format: json - body: "{{ FIDER_TENANT_BOOTSTRAP_BODY }}" - status_code: [200, 201] +- name: "πŸ₯Ύ Fider | Bootstrap initial tenant via API (swarm in-container)" + ansible.builtin.shell: + cmd: >- # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container exec -i {{ FIDER_LOCAL_CID | quote }} + timeout {{ lookup('timeout', 30) | int }} bash -c + 'set -e; body=$(cat); length=$(printf %s "$body" | wc -c); + exec 3<>"/dev/tcp/127.0.0.1/$1" || exit 75; + printf "POST /_api/tenants HTTP/1.0\r\nContent-Type: application/json\r\nContent-Length: %d\r\n\r\n%s" "$length" "$body" >&3; + read -r _ status _ <&3; printf %s "$status"; + case $status in 5*) exit 75;; esac' _ {{ FIDER_INTERNAL_PORT | quote }} + stdin: "{{ FIDER_TENANT_BOOTSTRAP_BODY | to_json }}" register: fider_tenant_bootstrap changed_when: true + failed_when: fider_tenant_bootstrap.rc != 0 or (fider_tenant_bootstrap.stdout | trim) not in ['200', '201'] + retries: 30 + delay: 2 + until: fider_tenant_bootstrap.rc != 75 + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" delegate_to: "{{ FIDER_HOST_NODE }}" when: - IS_SWARM_MODE @@ -75,17 +85,3 @@ query_file: "{{ role_path }}/files/sql/activate-tenants.sql" mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" changed_when: true - -- name: "πŸ”§ Fider | Configure Keycloak as OIDC provider in database" - database_query: - config: "{{ lookup('database', application_id) }}" - query_file: "{{ role_path }}/files/sql/configure-oidc-provider.sql" - named_args: - display_name: "{{ SOFTWARE_NAME }} SSO" - client_id: "{{ OIDC.CLIENT.ID }}" - client_secret: "{{ OIDC.CLIENT.SECRET }}" - authorize_url: "{{ OIDC.CLIENT.AUTHORIZE_URL }}" - token_url: "{{ OIDC.CLIENT.TOKEN_URL }}" - profile_url: "{{ OIDC.CLIENT.USER_INFO_URL }}" - mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - changed_when: true diff --git a/roles/web-app-fider/tasks/02_setup_oidc.yml b/roles/web-app-fider/tasks/02_setup_oidc.yml new file mode 100644 index 0000000000..d8327ba53f --- /dev/null +++ b/roles/web-app-fider/tasks/02_setup_oidc.yml @@ -0,0 +1,14 @@ +--- +- name: "πŸ”§ Fider | Configure Keycloak as OIDC provider in database" + database_query: + config: "{{ lookup('database', application_id) }}" + query_file: "{{ role_path }}/files/sql/configure-oidc-provider.sql" + named_args: + display_name: "{{ SOFTWARE_NAME }} SSO" + client_id: "{{ OIDC.CLIENT.ID }}" + client_secret: "{{ OIDC.CLIENT.SECRET }}" + authorize_url: "{{ OIDC.CLIENT.AUTHORIZE_URL }}" + token_url: "{{ OIDC.CLIENT.TOKEN_URL }}" + profile_url: "{{ OIDC.CLIENT.USER_INFO_URL }}" + mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + changed_when: true diff --git a/roles/web-app-fider/tasks/02_design.yml b/roles/web-app-fider/tasks/03_design.yml similarity index 100% rename from roles/web-app-fider/tasks/02_design.yml rename to roles/web-app-fider/tasks/03_design.yml diff --git a/roles/web-app-fider/vars/main.yml b/roles/web-app-fider/vars/main.yml index 76e9bc7f23..bfdbd687cf 100644 --- a/roles/web-app-fider/vars/main.yml +++ b/roles/web-app-fider/vars/main.yml @@ -3,6 +3,7 @@ application_id: "web-app-fider" FIDER_CONTAINER: "{{ lookup('config', application_id, 'services.fider.name') }}" +FIDER_INTERNAL_PORT: "{{ lookup('config', application_id, 'services.fider.ports.internal.http') }}" FIDER_OIDC_ENABLED: "{{ lookup('config', application_id, 'services.sso.enabled') }}" @@ -27,7 +28,7 @@ FIDER_MCP_PORT: "{{ lookup('config', application_id, 'services.fidermcp.ports.in FIDER_MCP_BEARER: "{{ lookup('config', application_id, 'secrets.credentials.mcp_bearer') }}" FIDER_MCP_INSTANCE_DIR: "{{ [lookup('container', application_id, 'directories.instance'), 'mcp'] | path_join }}" FIDER_MCP_UPSTREAM_HOST: "{{ lookup('config', application_id, 'services.fider.name') }}" -FIDER_MCP_UPSTREAM_PORT: "{{ lookup('config', application_id, 'services.fider.ports.internal.http') }}" +FIDER_MCP_UPSTREAM_PORT: "{{ FIDER_INTERNAL_PORT }}" FIDER_MCP_UPSTREAM_URL: "http://{{ FIDER_MCP_UPSTREAM_HOST }}:{{ FIDER_MCP_UPSTREAM_PORT }}" FIDER_MCP_CONTRACT: provider: "{{ application_id }}" diff --git a/roles/web-app-gitea/tasks/01_manager_ops.yml b/roles/web-app-gitea/tasks/01_manager_ops.yml index d3f7718671..e518b679b2 100644 --- a/roles/web-app-gitea/tasks/01_manager_ops.yml +++ b/roles/web-app-gitea/tasks/01_manager_ops.yml @@ -1,15 +1,4 @@ --- -- name: "⏳ Wait until Gitea has migrated its database and serves the API" - uri_retry: - url: "http://{{ DOCKER_REACH_HOST }}:{{ lookup('config', application_id, 'services.gitea.ports.local.http') }}/api/v1/version" - method: GET - status_code: 200 - return_content: false - register: gitea_ready - until: gitea_ready.status == 200 - retries: 120 - delay: 5 - - name: "πŸ” Resolve {{ application_id }} hosting node + container id" ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" vars: @@ -17,6 +6,17 @@ resolve_output_prefix: GITEA resolve_compose_cid: "{{ GITEA_CONTAINER_ADDRESS }}" +- name: "⏳ Wait until Gitea has migrated its database and serves the API" + ansible.builtin.shell: >- # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container exec {{ GITEA_LOCAL_CID | quote }} + {{ 10 | curl(retries=0) }} -fS -o /dev/null {{ GITEA_LOOPBACK_VERSION_URL | quote }} + delegate_to: "{{ GITEA_HOST_NODE }}" + register: gitea_ready + changed_when: false + retries: "{{ ((lookup('timeout', 600) | int) / 5) | round(0, 'ceil') | int }}" + delay: 5 + until: gitea_ready.rc == 0 + - name: "πŸ“ Create initial admin user" no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" shell: | # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node diff --git a/roles/web-app-gitea/vars/main.yml b/roles/web-app-gitea/vars/main.yml index 74ad17b371..27b6f1b09f 100644 --- a/roles/web-app-gitea/vars/main.yml +++ b/roles/web-app-gitea/vars/main.yml @@ -22,6 +22,7 @@ GITEA_CONTAINER: "{{ lookup('config', application_id, 'services.gitea.name') }}" GITEA_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, entity_name) }}" GITEA_USER: "git" GITEA_CONFIG: "/data/gitea/conf/app.ini" +GITEA_LOOPBACK_VERSION_URL: "http://127.0.0.1:{{ lookup('config', application_id, 'services.gitea.ports.internal.http') }}/api/v1/version" GITEA_DESIGN_ENABLED: "{{ lookup('config', application_id, 'services.design.enabled') | bool }}" GITEA_DESIGN_DIR: "{{ [lookup('container', application_id, 'directories.config'), 'design'] | path_join }}" diff --git a/roles/web-app-gitlab/meta/services.yml b/roles/web-app-gitlab/meta/services.yml index 6c1746d4f7..8ebb1131ab 100644 --- a/roles/web-app-gitlab/meta/services.yml +++ b/roles/web-app-gitlab/meta/services.yml @@ -78,7 +78,7 @@ webservice: backup: stop_required: false image: registry.gitlab.com/gitlab-org/build/cng/gitlab-webservice-ce - version: v19.5.1 + version: v19.5.3 name: gitlab-webservice healthcheck: test: ["CMD", "/scripts/healthcheck"] @@ -99,7 +99,7 @@ sidekiq: flavor: tcp path: liveness image: registry.gitlab.com/gitlab-org/build/cng/gitlab-sidekiq-ce - version: v19.5.1 + version: v19.5.3 name: gitlab-sidekiq cpus: "1.0" mem_reservation: 2g @@ -112,7 +112,7 @@ workhorse: backup: stop_required: false image: registry.gitlab.com/gitlab-org/build/cng/gitlab-workhorse-ce - version: v19.5.1 + version: v19.5.3 name: gitlab-workhorse healthcheck: test: ["CMD", "/scripts/healthcheck"] @@ -128,7 +128,7 @@ gitaly: # nocheck: default-placement-manager the repositories live on a node-local volume (meta/volumes.yml nfs: false, gitaly does not support NFS), which a reschedule leaves behind on the old node placement: manager image: registry.gitlab.com/gitlab-org/build/cng/gitaly - version: v19.5.1 + version: v19.5.3 healthcheck: test: ["CMD", "/scripts/healthcheck"] name: gitlab-gitaly @@ -143,7 +143,7 @@ shell: backup: stop_required: false image: registry.gitlab.com/gitlab-org/build/cng/gitlab-shell - version: v19.5.1 + version: v19.5.3 name: gitlab-shell ports: internal: @@ -158,7 +158,7 @@ migrations: # nocheck: single-replica replicas: 1 image: registry.gitlab.com/gitlab-org/build/cng/gitlab-rails-ce - version: v19.5.1 + version: v19.5.3 name: gitlab-migrations cpus: "1.0" mem_reservation: 1g diff --git a/roles/web-app-jellyfin/meta/info.yml b/roles/web-app-jellyfin/meta/info.yml index 6bf73058fe..093292613b 100644 --- a/roles/web-app-jellyfin/meta/info.yml +++ b/roles/web-app-jellyfin/meta/info.yml @@ -3,4 +3,3 @@ logo: class: fa-solid fa-film homepage: https://jellyfin.org/ video: https://www.youtube.com/watch?v=0t3lSJL3B_Q -display: true diff --git a/roles/web-app-joomla/meta/volumes.yml b/roles/web-app-joomla/meta/volumes.yml index f9bbb1d80c..d9c14bc427 100644 --- a/roles/web-app-joomla/meta/volumes.yml +++ b/roles/web-app-joomla/meta/volumes.yml @@ -12,7 +12,7 @@ php_upload: mode: "0444" mounts: - service: joomla - target: /usr/local/etc/php/conf.d/zzz-joomla-uploads.ini + target: /usr/local/etc/php/conf.d/uploads.ini php_hardening: type: config diff --git a/roles/web-app-magento/meta/volumes.yml b/roles/web-app-magento/meta/volumes.yml index 8fceecaa8a..541ceefd0d 100644 --- a/roles/web-app-magento/meta/volumes.yml +++ b/roles/web-app-magento/meta/volumes.yml @@ -31,3 +31,11 @@ php_hardening: mounts: - service: php target: /usr/local/etc/php/conf.d/zz-infinito-hardening.ini + +php_memory_unlimited: + type: config + source: "{{ FILE_PHP_MEMORY_UNLIMITED_INI }}" + mode: "0444" + mounts: + - service: php + target: /usr/local/etc/php/conf.d/zz-infinito-memory-unlimited.ini diff --git a/roles/web-app-mailu/meta/volumes.yml b/roles/web-app-mailu/meta/volumes.yml index 01bbc488c9..5ca24f6c35 100644 --- a/roles/web-app-mailu/meta/volumes.yml +++ b/roles/web-app-mailu/meta/volumes.yml @@ -91,3 +91,10 @@ php_hardening: mounts: - service: webmail target: /etc/php83/conf.d/zz-infinito-hardening.ini +php_memory_unlimited: + type: config + source: "{{ FILE_PHP_MEMORY_UNLIMITED_INI }}" + mode: "0444" + mounts: + - service: webmail + target: /etc/php83/conf.d/zz-infinito-memory-unlimited.ini diff --git a/roles/web-app-nextcloud/README.md b/roles/web-app-nextcloud/README.md index dfe124a210..cbf017144b 100644 --- a/roles/web-app-nextcloud/README.md +++ b/roles/web-app-nextcloud/README.md @@ -33,6 +33,8 @@ The enable-only appstore apps stay under `nextcloud.plugins` in [`meta/services. | `spreed` | `plugin` | enabled with the `talk` service | `talk`, `coturn` | | `whiteboard` | `plugin` | `required` (always installed) | none (self-hosted backend) | | `xwiki` | `plugin` | enabled with the `xwiki` partner | `xwiki` β†’ `web-app-xwiki` | +| `app_api` | `plugin` | enabled while `services.context_agent.enabled` is true (it follows `mcp.enabled` unless the inventory sets it), disabled otherwise | none | +| `logreader` | `plugin` | disabled, `log_type` is `errorlog` | none | The SSO (`sociallogin`) and LDAP (`user_ldap`) login surfaces are covered by the OIDC/LDAP Playwright specs (requirements 017/018). @@ -77,6 +79,19 @@ A redeploy of an unchanged version includes [`03_upgrade/02_cached_updates.yml`] An app the background job has not checked yet is not updated until its next run. +## Talk + +While `services.talk.enabled` is true, the role runs the Talk high-performance backend and the recording server as four services: + +| Service | Component | Source | +|---------|-----------|--------| +| `talk_signaling` | signaling server | upstream image `strukturag/nextcloud-spreed-signaling`, semver pin | +| `talk` | Janus media server | image the role builds from a semver tag of `meetecho/janus-gateway` | +| `talk_nats` | NATS message bus | official image `nats`, semver pin | +| `talk_recording` | recording server | image the role builds from a semver release tag of `nextcloud/nextcloud-talk-recording` | + +The role renders the signaling `server.conf`, `janus.jcfg` and the recording `server.conf` from [`templates/`](./templates/), and the version updaters raise every pin. [docs/Administration.md](docs/Administration.md#talk-high-performance-backend) describes how the services connect, how a version update reaches them and how the first deploy replaces `nextcloud/aio-talk`. + ## MCP Server Nextcloud serves a Model Context Protocol endpoint through the AppAPI proxy of the `context_agent` ExApp. @@ -142,7 +157,7 @@ Off. `mcp.enabled` is true only while `web-app-hermes`, `web-app-openclaw` or `w ### How to disable -Remove the MCP client roles, or pin `mcp.enabled: false` for this role. The `context_agent` service is then not rendered, the ExApp is not registered with AppAPI, and no app password is minted. +Remove the MCP client roles, or pin `mcp.enabled: false` for this role. The `context_agent` service is then not rendered, the ExApp is not registered with AppAPI, no app password is minted, and the `app_api` app is disabled. ## Documentation diff --git a/roles/web-app-nextcloud/docs/Administration.md b/roles/web-app-nextcloud/docs/Administration.md index 61e65dd23e..cef6371e7a 100644 --- a/roles/web-app-nextcloud/docs/Administration.md +++ b/roles/web-app-nextcloud/docs/Administration.md @@ -24,7 +24,7 @@ The logs you will find here on the host: **/var/lib/docker/volumes/nextcloud_dat ## Talk TURN and STUN -When `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`. +When `services.talk.enabled` is true, Nextcloud Talk uses the dedicated `web-svc-coturn` service for STUN and TURN. `web-app-nextcloud` runs no TURN server of its own. Check these admin URLs after deployment: @@ -32,10 +32,53 @@ Check these admin URLs after deployment: - `/settings/admin/talk#stun_server` - `/settings/admin/talk#turn_server` +## Talk high-performance backend + +The high-performance backend and the recording server run as four services of the `web-app-nextcloud` stack. Each one is pinned in `meta/services.yml`, and the role renders every configuration file they read. + +| Service | Component | Source | Configuration | +|---|---|---|---| +| `talk_signaling` | [nextcloud-spreed-signaling](https://github.com/strukturag/nextcloud-spreed-signaling) | upstream image `strukturag/nextcloud-spreed-signaling` at `services.talk_signaling.version` | `templates/signaling.conf.j2`, mounted as a secret at `/config/server.conf` | +| `talk` | [Janus](https://github.com/meetecho/janus-gateway) | built by the role from `services.talk.repository` at the tag `services.talk.ref` on `services.talk.image:services.talk.version`, see `files/Dockerfiles/Janus/Dockerfile` | `templates/janus.jcfg.j2`, mounted as a config at `/usr/local/etc/janus/janus.jcfg` | +| `talk_nats` | [NATS](https://nats.io) | official image `nats` at `services.talk_nats.version` | command line only | +| `talk_recording` | [nextcloud-talk-recording](https://github.com/nextcloud/nextcloud-talk-recording) | built by the role from `services.talk_recording.repository` at the tag `services.talk_recording.ref` on `services.talk_recording.image:services.talk_recording.version`, see `files/Dockerfiles/Recording/Dockerfile` | `templates/recording.conf.j2`, mounted as a secret at `/conf/recording.conf` | + +How the services connect: + +- The `proxy` service forwards `/standalone-signaling/` to `talk_signaling` on `services.talk_signaling.ports.internal.signaling`. +- `talk_signaling` reaches `talk_nats` at `nats://talk_nats:4222` and Janus at `ws://talk:8188`, or at `ws://host.docker.internal:8188` while Janus uses the host network. +- `talk_signaling` and `talk_recording` reach Nextcloud at its public URL, and `talk_recording` joins calls through the public `/standalone-signaling/` endpoint. +- Nextcloud reaches the recording server at `http://talk_recording:1234/`. + +`credentials.talk_signaling_secret`, `credentials.talk_internal_secret` and `credentials.talk_recording_secret` reach the services only through the rendered files. The signaling session keys are derived from `credentials.talk_signaling_secret`, so they stay stable across deploys. `talk_signaling` runs as UID 850, `talk` as UID 1000, `talk_nats` as UID 65534 and `talk_recording` as UID 122, each with one swarm replica. In swarm mode all four join the stack network and share no network namespace, so swarm may schedule them on different nodes. + +### Version updates + +1. The `cron-update` workflow runs `python3 -m cli.contributing.update.docker`, which raises `services.talk_signaling.version` and `services.talk_nats.version` from their registries together with the base images `services.talk.version` and `services.talk_recording.version`, and opens an update pull request. +2. The same workflow runs `python3 -m cli.contributing.update.repository`, which raises `services.talk.ref` and `services.talk_recording.ref` to the newest semver tag of their git repositories. +3. A new `ref` or base `version` changes the build arguments in `templates/compose.yml.j2` and the image tag `-`, so the next deploy rebuilds the image and replaces the container in compose mode or the task in swarm mode. +4. A new upstream release that changes its configuration format needs a change to the matching template, because no start script inside an image writes or rewrites these files. + +### Switching from nextcloud/aio-talk + +The first deploy of this layout replaces the `nextcloud/aio-talk` and `nextcloud/aio-talk-recording` containers: + +- In compose mode `compose up --force-recreate --remove-orphans` recreates the `talk` and `talk_recording` services with the new images and starts `talk_signaling` and `talk_nats`. +- In swarm mode `docker stack deploy --prune` updates `nextcloud_talk` and `nextcloud_talk_recording` in place and creates the two new services. +- The signaling, internal and recording secrets keep their inventory values, so Nextcloud needs no reconfiguration. Calls drop while the containers are replaced. +- The TURN server bundled in `nextcloud/aio-talk` is gone together with `credentials.talk_turn_secret`, `services.talk.turn_server.onboard_enabled` and the `stun_turn`, `stun_turn_tls` and `relay` ports of `services.nextcloud`. Remove those keys from inventories that set them. + ## Talk media -With `services.talk.direct_media` true, the Janus media server inside the `talk` container announces `networks.internet.ip4` and publishes `services.talk.ports.public.relay` (UDP, default 61000-61999) on that address, so clients send their media to Janus directly and only fall back to `web-svc-coturn` when UDP to that range is blocked. The flag is on in compose mode with a bridged `talk` service that uses `web-svc-coturn` for TURN, and only while `networks.internet.ip4` is an address of the host itself. Set it to `false` in the inventory to send every stream through TURN again. +By default every Talk stream goes through `web-svc-coturn`, and Janus publishes no port. Set `services.talk.direct_media` to `true` in the inventory to let clients send their media to Janus directly: Janus then announces `networks.internet.ip4` as `nat_1_1_mapping`, takes its media ports from `services.talk.ports.public.relay` (UDP, default 61000-61999) and publishes them on that address, and clients fall back to `web-svc-coturn` only when UDP to that range is blocked. The setting takes effect in compose mode when `web-svc-coturn` provides TURN and `networks.internet.ip4` is an address of the host itself. -Open the range for UDP in any firewall in front of the host. Each participant of a call holds one peer connection per participant, so all calls together get at most as many peer connections as the range has ports, and a call of N participants needs NΒ² of them. Janus refuses a new peer connection once the range is used up. Docker starts one `docker-proxy` process per published port. +`services.talk.network_mode` decides how Janus reaches that range: -`templates/janus.jcfg.j2` replaces the `janus.jcfg` of the `nextcloud/aio-talk` image. Before every deploy the role reads `/supervisord.conf` and that file from the image and stops unless Janus is started with that file and its settings equal the template without `rtp_port_range`, `nat_1_1_mapping` and `keep_private_host`. Re-derive the template from the new image when that happens. +| Value | Janus | +|---|---| +| `bridge` | runs on the stack network and publishes the range on `networks.internet.ip4` | +| `host` | runs in the host network namespace and binds the range itself; compose mode only, the deploy stops in swarm mode | + +With `host`, Janus also answers its websocket API on port 8188 of every host interface. Block that port in any firewall in front of the host. + +Open the media range for UDP in any firewall in front of the host. Each participant of a call holds one peer connection per participant, so all calls together get at most as many peer connections as the range has ports, and a call of N participants needs NΒ² of them. Janus refuses a new peer connection once the range is used up. With `bridge`, Docker starts one `docker-proxy` process per published port. diff --git a/roles/web-app-nextcloud/files/Dockerfile b/roles/web-app-nextcloud/files/Dockerfile new file mode 100644 index 0000000000..b5a360fbff --- /dev/null +++ b/roles/web-app-nextcloud/files/Dockerfile @@ -0,0 +1,16 @@ +ARG NEXTCLOUD_IMAGE +ARG NEXTCLOUD_VERSION +FROM ${NEXTCLOUD_IMAGE}:${NEXTCLOUD_VERSION} +ARG NEXTCLOUD_ONLYOFFICE_ENABLED +ARG NEXTCLOUD_INIT_GATE_FILE + +RUN case "${NEXTCLOUD_ONLYOFFICE_ENABLED}" in \ + true) apk add --no-cache ca-certificates && update-ca-certificates ;; \ + false) ;; \ + *) echo "NEXTCLOUD_ONLYOFFICE_ENABLED must be true or false, got '${NEXTCLOUD_ONLYOFFICE_ENABLED}'" >&2; exit 1 ;; \ + esac + +COPY ${NEXTCLOUD_INIT_GATE_FILE} /usr/local/bin/init-gate.sh +RUN chmod 0755 /usr/local/bin/init-gate.sh +ENTRYPOINT ["/usr/local/bin/init-gate.sh"] +CMD ["php-fpm"] diff --git a/roles/web-app-nextcloud/files/Dockerfiles/Janus/Dockerfile b/roles/web-app-nextcloud/files/Dockerfiles/Janus/Dockerfile new file mode 100644 index 0000000000..e2479cbab6 --- /dev/null +++ b/roles/web-app-nextcloud/files/Dockerfiles/Janus/Dockerfile @@ -0,0 +1,61 @@ +ARG JANUS_BASE_IMAGE +ARG JANUS_BASE_VERSION +FROM ${JANUS_BASE_IMAGE}:${JANUS_BASE_VERSION} AS build +ARG JANUS_REPOSITORY +ARG JANUS_REF + +WORKDIR /src +RUN set -ex; \ + apk upgrade --no-cache -a; \ + apk add --no-cache \ + ca-certificates \ + git \ + autoconf \ + automake \ + build-base \ + pkgconfig \ + libtool \ + util-linux \ + glib-dev \ + zlib-dev \ + openssl-dev \ + jansson-dev \ + libnice-dev \ + libconfig-dev \ + libsrtp-dev \ + libusrsctp-dev \ + gengetopt-dev \ + libwebsockets-dev; \ + git clone --recursive "${JANUS_REPOSITORY}" --depth=1 --single-branch --branch "${JANUS_REF}" /src; \ + /src/autogen.sh; \ + /src/configure --disable-rabbitmq --disable-mqtt --disable-boringssl; \ + make; \ + make install; \ + make configs; \ + rename -v ".jcfg.sample" ".jcfg" /usr/local/etc/janus/*.jcfg.sample + +FROM ${JANUS_BASE_IMAGE}:${JANUS_BASE_VERSION} + +COPY --from=build /usr/local /usr/local + +RUN set -ex; \ + apk upgrade --no-cache -a; \ + apk add --no-cache \ + ca-certificates \ + tzdata \ + netcat-openbsd \ + glib \ + zlib \ + libssl3 \ + libcrypto3 \ + jansson \ + libnice \ + libconfig \ + libsrtp \ + libusrsctp \ + libwebsockets; \ + mkdir -p /usr/local/lib/janus/loggers; \ + adduser -D -H -u 1000 janus + +USER janus +ENTRYPOINT ["janus", "--disable-colors", "--log-stdout", "--full-trickle", "--debug-level", "3"] diff --git a/roles/web-app-nextcloud/files/Dockerfiles/Recording/Dockerfile b/roles/web-app-nextcloud/files/Dockerfiles/Recording/Dockerfile new file mode 100644 index 0000000000..c64cd5e1f5 --- /dev/null +++ b/roles/web-app-nextcloud/files/Dockerfiles/Recording/Dockerfile @@ -0,0 +1,50 @@ +ARG RECORDING_BASE_IMAGE +ARG RECORDING_BASE_VERSION +FROM ${RECORDING_BASE_IMAGE}:${RECORDING_BASE_VERSION} +ARG RECORDING_REPOSITORY +ARG RECORDING_REF +ARG RECORDING_USER_ID +ARG RECORDING_DIRECTORY +ARG RECORDING_CONFIG_DIRECTORY + +RUN set -ex; \ + apk upgrade --no-cache -a; \ + apk add --no-cache \ + ca-certificates \ + tzdata \ + bash \ + xvfb \ + ffmpeg \ + firefox \ + font-noto-all \ + font-noto-cjk \ + font-noto-cjk-extra \ + bind-tools \ + netcat-openbsd \ + git \ + shadow \ + pulseaudio \ + build-base \ + linux-headers \ + geckodriver; \ + useradd -d "${RECORDING_DIRECTORY}" --system recording -u "${RECORDING_USER_ID}"; \ + git clone --recursive "${RECORDING_REPOSITORY}" --depth=1 --single-branch --branch "${RECORDING_REF}" /src; \ + python3 -m pip install --no-cache-dir /src; \ + rm -rf /src; \ + mkdir -p "${RECORDING_CONFIG_DIRECTORY}"; \ + chown recording:recording -R "${RECORDING_DIRECTORY}"; \ + apk del --no-cache \ + git \ + shadow \ + build-base \ + linux-headers + +ARG RECORDING_CA_CERT +RUN if [ -n "${RECORDING_CA_CERT}" ]; then \ + mkdir -p /etc/firefox/policies \ + && printf '{"policies":{"Certificates":{"Install":["%s"]}}}\n' "${RECORDING_CA_CERT}" > /etc/firefox/policies/policies.json; \ + fi + +WORKDIR ${RECORDING_DIRECTORY} +USER ${RECORDING_USER_ID} +ENTRYPOINT ["python", "-m", "nextcloud.talk.recording"] diff --git a/roles/web-app-nextcloud/templates/Dockerfiles/Whiteboard.j2 b/roles/web-app-nextcloud/files/Dockerfiles/Whiteboard/Dockerfile similarity index 82% rename from roles/web-app-nextcloud/templates/Dockerfiles/Whiteboard.j2 rename to roles/web-app-nextcloud/files/Dockerfiles/Whiteboard/Dockerfile index ec05bc4b40..cc95fa0c51 100644 --- a/roles/web-app-nextcloud/templates/Dockerfiles/Whiteboard.j2 +++ b/roles/web-app-nextcloud/files/Dockerfiles/Whiteboard/Dockerfile @@ -1,4 +1,6 @@ -FROM {{ NEXTCLOUD_WHITEBOARD_IMAGE }}:{{ NEXTCLOUD_WHITEBOARD_VERSION }} +ARG WHITEBOARD_IMAGE +ARG WHITEBOARD_VERSION +FROM ${WHITEBOARD_IMAGE}:${WHITEBOARD_VERSION} USER 0 diff --git a/roles/web-app-nextcloud/files/playwright/addons/app_api.spec.js b/roles/web-app-nextcloud/files/playwright/addons/app_api.spec.js new file mode 100644 index 0000000000..cc812f76cc --- /dev/null +++ b/roles/web-app-nextcloud/files/playwright/addons/app_api.spec.js @@ -0,0 +1,41 @@ +const { test, expect } = require("@playwright/test"); +const { resolveTimeout } = require("../timeouts"); +const { skipUnlessAddonEnabled } = require("../addon-gating"); +const shared = require("../_shared"); +const { gotoOnion } = require("../personas"); + +test.use({ ignoreHTTPSErrors: true }); + +test("app_api addon: the AppAPI app is enabled for the logged-in user", async ({ browser }) => { + skipUnlessAddonEnabled("app_api"); + test.setTimeout(resolveTimeout(120_000)); + + const context = await browser.newContext({ ignoreHTTPSErrors: true }); + const page = await context.newPage(); + + try { + await shared.loginToStandaloneNextcloud(page); + + const filesUrl = new URL("apps/files/", shared.env.nextcloudBaseUrl).toString(); + await gotoOnion(page, filesUrl, { waitUntil: "domcontentloaded", timeout: resolveTimeout(60_000) }); + await shared.dismissBlockingNextcloudModals(page, page); + + await expect( + page.locator("#app-content, #app-content-vue, #app-navigation-vue").first(), + "the Nextcloud Files app shell must render before reading the enabled apps", + ).toBeVisible({ timeout: resolveTimeout(60_000) }); + + const appApiEnabled = await page.evaluate(() => { + const oc = window.OC || {}; + const webroots = oc.appswebroots || (oc.appConfig && oc.appConfig.appswebroots) || {}; + return Object.prototype.hasOwnProperty.call(webroots, "app_api"); + }); + expect( + appApiEnabled, + "app_api must be listed in OC.appswebroots, which Nextcloud fills with the enabled apps only: the MCP surface proxies through AppAPI, so the role keeps it enabled while the context_agent service runs", + ).toBe(true); + } finally { + await page.close().catch(() => {}); + await context.close().catch(() => {}); + } +}); diff --git a/roles/web-app-nextcloud/files/playwright/addons/logreader.spec.js b/roles/web-app-nextcloud/files/playwright/addons/logreader.spec.js new file mode 100644 index 0000000000..28ffbfb66b --- /dev/null +++ b/roles/web-app-nextcloud/files/playwright/addons/logreader.spec.js @@ -0,0 +1,41 @@ +const { test, expect } = require("@playwright/test"); +const { resolveTimeout } = require("../timeouts"); +const { skipUnlessAddonEnabled } = require("../addon-gating"); +const shared = require("../_shared"); +const { gotoOnion } = require("../personas"); + +test.use({ ignoreHTTPSErrors: true }); + +test("logreader addon: the log reader app is enabled for the logged-in user", async ({ browser }) => { + skipUnlessAddonEnabled("logreader"); + test.setTimeout(resolveTimeout(120_000)); + + const context = await browser.newContext({ ignoreHTTPSErrors: true }); + const page = await context.newPage(); + + try { + await shared.loginToStandaloneNextcloud(page); + + const filesUrl = new URL("apps/files/", shared.env.nextcloudBaseUrl).toString(); + await gotoOnion(page, filesUrl, { waitUntil: "domcontentloaded", timeout: resolveTimeout(60_000) }); + await shared.dismissBlockingNextcloudModals(page, page); + + await expect( + page.locator("#app-content, #app-content-vue, #app-navigation-vue").first(), + "the Nextcloud Files app shell must render before reading the enabled apps", + ).toBeVisible({ timeout: resolveTimeout(60_000) }); + + const logreaderEnabled = await page.evaluate(() => { + const oc = window.OC || {}; + const webroots = oc.appswebroots || (oc.appConfig && oc.appConfig.appswebroots) || {}; + return Object.prototype.hasOwnProperty.call(webroots, "logreader"); + }); + expect( + logreaderEnabled, + "logreader must be listed in OC.appswebroots, which Nextcloud fills with the enabled apps only", + ).toBe(true); + } finally { + await page.close().catch(() => {}); + await context.close().catch(() => {}); + } +}); diff --git a/roles/web-app-nextcloud/files/playwright/playwright.spec.js b/roles/web-app-nextcloud/files/playwright/playwright.spec.js index c82c4fb37c..d32c9764c1 100644 --- a/roles/web-app-nextcloud/files/playwright/playwright.spec.js +++ b/roles/web-app-nextcloud/files/playwright/playwright.spec.js @@ -21,6 +21,7 @@ test.beforeEach(shared.beforeEach); require("./test-design").register(shared); require("./test-talk-admin-settings").register(shared); require("./test-talk-call-capacity").register(shared); +require("./test-talk-recording").register(shared); require("./test-login-admin-oidc").register(shared); require("./test-login-admin-native").register(shared); require("./test-login-biber-oidc").register(shared); diff --git a/roles/web-app-nextcloud/files/playwright/test-talk-admin-settings.js b/roles/web-app-nextcloud/files/playwright/test-talk-admin-settings.js index c69b579bd0..ebafbfcdae 100644 --- a/roles/web-app-nextcloud/files/playwright/test-talk-admin-settings.js +++ b/roles/web-app-nextcloud/files/playwright/test-talk-admin-settings.js @@ -13,8 +13,7 @@ const nextcloudTalkSettingsUrl = decodeDotenvQuotedValue(process.env.NEXTCLOUD_T 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 nextcloudTalkExpectedSignalingVersion = decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_EXPECTED_SIGNALING_VERSION); // Error strings emitted by the spreed admin UI when a signaling / STUN / TURN // test button reports a failure. Kept in one place so the list stays easy to @@ -43,8 +42,8 @@ const talkTestServerRequiredOkPattern = /OK:\s*Running version:\s*\S+/i; // Talk admin settings are partly rendered as plain text and partly as // `` fields. `innerText()` alone would miss the input -// values, so collect both text and form values before asserting presence or -// absence of configured / legacy endpoints. +// values, so collect both text and form values before asserting the +// configured endpoints. async function collectNextcloudSettingsText(target) { const bodyText = await target.locator("body").innerText().catch(() => ""); const formValues = await target.locator("input, textarea, select").evaluateAll((elements) => { @@ -80,18 +79,6 @@ async function expectNextcloudSettingValue(page, expectedValue, label) { .toContain(expectedValue); } -async function expectNextcloudSettingAbsent(page, unexpectedValue, label) { - await expect - .poll( - async () => collectNextcloudSettingsText(page), - { - timeout: resolveTimeout(30_000), - message: `Expected ${label} to stay absent in the Nextcloud Talk admin settings: ${unexpectedValue}` - } - ) - .not.toContain(unexpectedValue); -} - async function clickAllTalkTestServerButtonsAndVerify(page) { // Spreed renders the test result inside `` // and the explicit re-test button (icon-only NcButton with @@ -154,6 +141,25 @@ async function clickAllTalkTestServerButtonsAndVerify(page) { } } +function runningVersionPattern(version) { + const escaped = version.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + return new RegExp(`Running version:\\s*${escaped}(?:~[^;\\s]*)?(?=;|\\s|$)`, "i"); +} + +async function expectPinnedSignalingVersion(page) { + const connectionSpans = page.locator("span.test-connection"); + await expect + .poll(async () => connectionSpans.allInnerTexts().catch(() => []), { + timeout: resolveTimeout(60_000), + message: `Expected the HPB signaling row to report the pinned version ${nextcloudTalkExpectedSignalingVersion} as its running version`, + }) + .toEqual(expect.arrayContaining([expect.stringMatching(runningVersionPattern(nextcloudTalkExpectedSignalingVersion))])); + + for (const text of await connectionSpans.allInnerTexts()) { + expect(text, `The HPB signaling server reports chat-relay as missing: ${text}`).not.toMatch(/missing features:[^\n]*\bchat-relay\b/i); + } +} + exports.register = function (shared) { test("nextcloud talk admin settings", async ({ browser }) => { test.skip(!nextcloudTalkSettingsCheckEnabled, "Talk admin checks are disabled in the current Playwright env"); @@ -163,6 +169,7 @@ exports.register = function (shared) { 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(); + expect(nextcloudTalkExpectedSignalingVersion, "NEXTCLOUD_TALK_EXPECTED_SIGNALING_VERSION must be set when Talk admin checks are enabled").toBeTruthy(); const browserContext = await browser.newContext({ ignoreHTTPSErrors: true @@ -203,15 +210,8 @@ exports.register = function (shared) { 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"); - } - await clickAllTalkTestServerButtonsAndVerify(adminPage); + await expectPinnedSignalingVersion(adminPage); } finally { await adminPage.close().catch(() => {}); } diff --git a/roles/web-app-nextcloud/files/playwright/test-talk-call-capacity.js b/roles/web-app-nextcloud/files/playwright/test-talk-call-capacity.js index e1d3a7eb73..082d276789 100644 --- a/roles/web-app-nextcloud/files/playwright/test-talk-call-capacity.js +++ b/roles/web-app-nextcloud/files/playwright/test-talk-call-capacity.js @@ -119,6 +119,10 @@ async function joinCallAsGuest(browser, roomUrl, name) { return { name, page, context }; } +exports.ocsHeaders = ocsHeaders; +exports.createPublicRoom = createPublicRoom; +exports.joinCallAsGuest = joinCallAsGuest; + exports.register = function (shared) { test("nextcloud talk call holds more than five participants", async ({ browser }) => { test.skip(!talkEnabled, "Talk is disabled in the current Playwright env"); diff --git a/roles/web-app-nextcloud/files/playwright/test-talk-recording.js b/roles/web-app-nextcloud/files/playwright/test-talk-recording.js new file mode 100644 index 0000000000..a3e33f86e0 --- /dev/null +++ b/roles/web-app-nextcloud/files/playwright/test-talk-recording.js @@ -0,0 +1,115 @@ +const { test, expect, chromium } = require("@playwright/test"); +const { resolveTimeout, isOnionTarget } = require("./timeouts"); +const { decodeDotenvQuotedValue } = require("./personas"); +const { ocsHeaders, createPublicRoom, joinCallAsGuest } = require("./test-talk-call-capacity"); + +const talkEnabled = decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_SETTINGS_CHECK_ENABLED) === "true"; +const recordingAudio = 2; +const recordingFailed = 5; +const recordingDurationMs = 15_000; + +async function ocs(page, method, url) { + const response = await page.request.fetch(url, { method, headers: ocsHeaders }); + const body = await response.json().catch(() => ({})); + return { status: response.status(), data: body?.ocs?.data }; +} + +async function readCallRecording(page, baseUrl, token) { + const { data } = await ocs(page, "GET", new URL(`ocs/v2.php/apps/spreed/api/v4/room/${token}`, baseUrl).toString()); + return data?.callRecording; +} + +async function findStoredRecording(page, baseUrl, token) { + const { data } = await ocs(page, "GET", new URL("ocs/v2.php/apps/notifications/api/v2/notifications", baseUrl).toString()); + const stored = (Array.isArray(data) ? data : []).find( + (notification) => + notification.app === "spreed" && + notification.object_type === "recording" && + notification.object_id === token && + notification.messageRichParameters?.file?.path, + ); + return stored ? stored.messageRichParameters.file : null; +} + +function readFileSize(page, path) { + return page.evaluate(async (relativePath) => { + const user = window.OC.getCurrentUser().uid; + const encoded = relativePath.split("/").filter(Boolean).map(encodeURIComponent).join("/"); + const response = await fetch(`${window.OC.getRootPath()}/remote.php/dav/files/${encodeURIComponent(user)}/${encoded}`, { + method: "PROPFIND", + headers: { Depth: "0", requesttoken: window.OC.requestToken, "Content-Type": "application/xml" }, + body: '', + }); + if (response.status !== 207) { + return -response.status; + } + const length = new DOMParser() + .parseFromString(await response.text(), "application/xml") + .getElementsByTagNameNS("DAV:", "getcontentlength")[0]; + return length ? Number(length.textContent) : 0; + }, path); +} + +exports.register = function (shared) { + test("nextcloud talk recording server stores a recording of a call", async ({ browser }) => { + test.skip(!talkEnabled, "Talk is disabled in the current Playwright env"); + test.skip(isOnionTarget(), "Nextcloud Talk realtime (HPB signaling + recording) is WebRTC; not reachable over Tor"); + test.setTimeout(resolveTimeout(10 * 60_000)); + + const baseUrl = shared.env.nextcloudBaseUrl; + const adminContext = await browser.newContext({ ignoreHTTPSErrors: true }); + const adminPage = await adminContext.newPage(); + const mediaBrowser = await chromium.launch({ + args: ["--use-fake-ui-for-media-stream", "--use-fake-device-for-media-stream"], + }); + let token = ""; + + try { + await shared.loginToStandaloneNextcloud(adminPage); + token = await createPublicRoom(adminPage, baseUrl); + await joinCallAsGuest(mediaBrowser, new URL(`call/${token}`, baseUrl).toString(), "Playwright recording guest"); + + const recordingUrl = new URL(`ocs/v2.php/apps/spreed/api/v1/recording/${token}`, baseUrl).toString(); + const start = await adminPage.request.post(recordingUrl, { headers: ocsHeaders, data: { status: recordingAudio } }); + expect(start.ok(), `starting the call recording answered HTTP ${start.status()}: ${await start.text()}`).toBeTruthy(); + + await expect + .poll(async () => readCallRecording(adminPage, baseUrl, token), { + timeout: resolveTimeout(180_000), + message: "the recording server must join the call and report the audio recording as running", + }) + .toBe(recordingAudio); + + await adminPage.waitForTimeout(recordingDurationMs); + + const stop = await ocs(adminPage, "DELETE", recordingUrl); + expect(stop.status, "stopping the call recording must succeed").toBe(200); + expect(await readCallRecording(adminPage, baseUrl, token), "the recording must not end as failed").not.toBe(recordingFailed); + + let stored = null; + await expect + .poll( + async () => { + stored = await findStoredRecording(adminPage, baseUrl, token); + return Boolean(stored); + }, + { + timeout: resolveTimeout(300_000), + message: "the recording server must upload the recording and Talk must notify the moderator that it is stored", + }, + ) + .toBe(true); + + await adminPage.goto(new URL("apps/files/", baseUrl).toString(), { waitUntil: "domcontentloaded", timeout: resolveTimeout(60_000) }); + expect(await readFileSize(adminPage, stored.path), `the stored recording ${stored.path} must not be empty`).toBeGreaterThan(0); + } finally { + await mediaBrowser.close().catch(() => {}); + if (token) { + await adminPage.request + .delete(new URL(`ocs/v2.php/apps/spreed/api/v4/room/${token}`, baseUrl).toString(), { headers: ocsHeaders }) + .catch(() => {}); + } + await adminContext.close().catch(() => {}); + } + }); +}; diff --git a/roles/web-app-nextcloud/files/shell/talk-network-backends.sh b/roles/web-app-nextcloud/files/shell/talk-network-backends.sh deleted file mode 100644 index f321987314..0000000000 --- a/roles/web-app-nextcloud/files/shell/talk-network-backends.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/sh -# Param: TALK_NETWORK_BACKEND_URLS comma-separated backend base URLs of the network siblings beyond NC_DOMAIN -# The aio-talk start script rewrites signaling.conf with one backend (https://$NC_DOMAIN) on every start, -# while Talk reports the backend URL of each request's network, so the other siblings are appended here. -set -eu -conf=/conf/signaling.conf -names=backend-1 -index=1 -IFS=, -for url in ${TALK_NETWORK_BACKEND_URLS:-}; do - index=$((index + 1)) - printf '\n[backend-%s]\nurl = %s\nsecret = %s\n' "$index" "$url" "$SIGNALING_SECRET" >>"$conf" - names="$names, backend-$index" -done -sed -i "s/^backends = backend-1\$/backends = ${names}/" "$conf" -exec "$@" diff --git a/roles/web-app-nextcloud/files/shell/utils/replace_pinned_app.sh b/roles/web-app-nextcloud/files/shell/utils/replace_pinned_app.sh new file mode 100644 index 0000000000..df1d4af6bf --- /dev/null +++ b/roles/web-app-nextcloud/files/shell/utils/replace_pinned_app.sh @@ -0,0 +1,33 @@ +#!/bin/sh +set -eu + +# Usage: +# replace_pinned_app.sh < +# stdin: the release archive, holding the app under /. +# +# Exit: 0, with [CHANGED] on stdout when / was replaced +# by the release; non-zero when the archive does not unpack or lacks +# /appinfo/info.xml, with / left untouched. + +apps_dir="$1" +app_id="$2" +live="$apps_dir/$app_id" +stage="$apps_dir/.$app_id.stage" +old="$apps_dir/.$app_id.old" + +rm -rf "$stage" "$old" +mkdir "$stage" +tar -xzf - -C "$stage" +test -f "$stage/$app_id/appinfo/info.xml" + +if [ -d "$live" ] && diff -rq "$live" "$stage/$app_id" >/dev/null; then + rm -rf "$stage" + exit 0 +fi + +if [ -d "$live" ]; then + mv "$live" "$old" +fi +mv "$stage/$app_id" "$live" +rm -rf "$stage" "$old" +echo "[CHANGED] $live now holds exactly the files of the pinned $app_id release." diff --git a/roles/web-app-nextcloud/filter_plugins/nextcloud_janus.py b/roles/web-app-nextcloud/filter_plugins/nextcloud_janus.py deleted file mode 100644 index ea7398fa7b..0000000000 --- a/roles/web-app-nextcloud/filter_plugins/nextcloud_janus.py +++ /dev/null @@ -1,121 +0,0 @@ -from __future__ import annotations - -import re - - -def _strip_comments(content): - out = [] - in_string = in_block = False - index = 0 - while index < len(content): - char = content[index] - if in_block: - if content.startswith("*/", index): - in_block = False - index += 1 - elif char == "\n": - out.append(char) - elif in_string: - out.append(char) - if char == "\\" and index + 1 < len(content): - out.append(content[index + 1]) - index += 1 - elif char == '"': - in_string = False - elif char == '"': - in_string = True - out.append(char) - elif content.startswith("/*", index): - in_block = True - index += 1 - elif char == "#" or content.startswith("//", index): - while index + 1 < len(content) and content[index + 1] != "\n": - index += 1 - else: - out.append(char) - index += 1 - return "".join(out) - - -def _without_blanks(line): - out = [] - in_string = False - for index, char in enumerate(line): - if char == '"' and (index == 0 or line[index - 1] != "\\"): - in_string = not in_string - if in_string or not char.isspace(): - out.append(char) - return "".join(out).rstrip(";") - - -def _key(setting): - for index, char in enumerate(setting): - if char in "=:": - return setting[:index] - if char == '"': - return "" - return "" - - -def janus_settings(content, overrides): - """Return the settings a Janus ``.jcfg`` file declares, one per line. - - Args: - content: text of a Janus libconfig file. - overrides: setting names to leave out, the ones a deployment sets on - top of the stock file; empty to keep every setting. - - Returns: - Every line that holds more than comments and blanks, with the comments, - a trailing ``;`` and the whitespace outside quoted strings removed, in - file order. - """ - dropped = {str(name) for name in overrides} - settings = [] - for raw in _strip_comments(str(content)).splitlines(): - setting = _without_blanks(raw) - if setting and _key(setting) not in dropped: - settings.append(setting) - return settings - - -def janus_config_drift(template, stock, overrides, launcher, target): - """Return why a rendered Janus config may not replace an image's own. - - Args: - template: the rendered config that is mounted over ``target``. - stock: the image's own file at ``target``. - overrides: setting names the template adds to the stock settings. - launcher: the image's process manager config that starts Janus. - target: the path the template is mounted at. - - Returns: - One message per problem; empty when Janus reads ``target`` and the - template without ``overrides`` declares exactly the stock settings. - """ - problems = [] - started_with = re.compile(rf"--config={re.escape(str(target))}( |$)", re.MULTILINE) - if not started_with.search(str(launcher)): - problems.append(f"Janus is not started with --config={target}") - expected = janus_settings(stock, []) - rendered = janus_settings(template, overrides) - if expected != rendered: - first = next( - ( - f"{index}: image {theirs!r}, template {ours!r}" - for index, (theirs, ours) in enumerate( - zip(expected, rendered, strict=False) - ) - if theirs != ours - ), - f"{len(expected)} settings in the image, {len(rendered)} in the template", - ) - problems.append(f"the stock settings differ at setting {first}") - return problems - - -class FilterModule: - def filters(self): - return { - "janus_config_drift": janus_config_drift, - } diff --git a/roles/web-app-nextcloud/meta/addons/app_api.yml b/roles/web-app-nextcloud/meta/addons/app_api.yml new file mode 100644 index 0000000000..a3bfb12408 --- /dev/null +++ b/roles/web-app-nextcloud/meta/addons/app_api.yml @@ -0,0 +1,5 @@ +--- +enabled: "{{ lookup('config', 'web-app-nextcloud', 'services.context_agent.enabled') | bool }}" +required: false +mechanism: plugin +source: upstream diff --git a/roles/web-app-nextcloud/meta/addons/logreader.yml b/roles/web-app-nextcloud/meta/addons/logreader.yml new file mode 100644 index 0000000000..29609554ac --- /dev/null +++ b/roles/web-app-nextcloud/meta/addons/logreader.yml @@ -0,0 +1,5 @@ +--- +enabled: false +required: false +mechanism: plugin +source: upstream diff --git a/roles/web-app-nextcloud/meta/addons/spreed.yml b/roles/web-app-nextcloud/meta/addons/spreed.yml index 31f088c09f..7b8965e665 100644 --- a/roles/web-app-nextcloud/meta/addons/spreed.yml +++ b/roles/web-app-nextcloud/meta/addons/spreed.yml @@ -22,7 +22,6 @@ config: configvalue: >- {{ [ - NEXTCLOUD_HPB_STUN_ONBOARD_CONFIG if NEXTCLOUD_HPB_TURN_ONBOARD_ENABLED else none, NEXTCLOUD_HPB_STUN_STANDALONE_CONFIG if NEXTCLOUD_HPB_TURN_STANDALONE_ENABLED else none ] | select @@ -35,7 +34,6 @@ config: configvalue: >- {{ [ - NEXTCLOUD_HPB_TURN_ONBOARD_CONFIG if NEXTCLOUD_HPB_TURN_ONBOARD_ENABLED else none, NEXTCLOUD_HPB_TURN_STANDALONE_CONFIG if NEXTCLOUD_HPB_TURN_STANDALONE_ENABLED else none ] | select diff --git a/roles/web-app-nextcloud/meta/secrets.yml b/roles/web-app-nextcloud/meta/secrets.yml index 9f4413eeba..dad8dc3deb 100644 --- a/roles/web-app-nextcloud/meta/secrets.yml +++ b/roles/web-app-nextcloud/meta/secrets.yml @@ -19,16 +19,12 @@ credentials: description: Secret used for JWT signing algorithm: base64_prefixed_32 validation: ^base64:[A-Za-z0-9+/]{43}=$ - talk_turn_secret: - 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: description: Secret for Talk signaling algorithm: base64_prefixed_32 validation: ^base64:[A-Za-z0-9+/]{43}=$ talk_internal_secret: - description: Internal secret for AIO Talk + description: Secret internal clients such as the Talk recording server present to the signaling server algorithm: base64_prefixed_32 validation: ^base64:[A-Za-z0-9+/]{43}=$ context_agent_app_secret: diff --git a/roles/web-app-nextcloud/meta/services.yml b/roles/web-app-nextcloud/meta/services.yml index f7c9ee507f..9da1f01255 100644 --- a/roles/web-app-nextcloud/meta/services.yml +++ b/roles/web-app-nextcloud/meta/services.yml @@ -101,12 +101,6 @@ nextcloud: internal: http: 80 fpm: 9000 - public: - stun_turn: 3480 - stun_turn_tls: 5350 - relay: - start: 50000 - end: 59999 run_after: - web-app-keycloak - web-app-matomo @@ -188,45 +182,91 @@ cron: mem_limit: 512m pids_limit: 256 min_storage: 1GB +taskprocessing: + name: nextcloud-taskprocessing + cpus: "0.5" + mem_reservation: 128m + mem_limit: 1g + pids_limit: 256 # nocheck: dynamic-flag # nocheck: playwright-service-flag: infrastructural sub-component (real-time communication) talk: bond: 1 enabled: "{{ 'web-svc-coturn' in group_names }}" shared: "{{ 'web-svc-coturn' in group_names }}" - name: nextcloud-talk - image: nextcloud/aio-talk - # nocheck: docker-version -- all 174 tags upstream publishes are AIO build stamps, none is a version - version: latest - backup: - stop_required: true + name: nextcloud-talk-janus + image: alpine + version: 3.23.3 + custom: nextcloud-talk-janus + repository: https://github.com/meetecho/janus-gateway.git + ref: v1.4.0 + # nocheck: single-replica the signaling server addresses exactly one Janus by URL and keeps every media session on it + replicas: 1 turn_server: - onboard_enabled: "{{ not ( 'web-svc-coturn' in group_names ) }}" standalone_enabled: "{{ 'web-svc-coturn' in group_names }}" network_mode: bridge - direct_media: >- - {{ (lookup('config', 'web-app-nextcloud', 'services.talk.enabled') | bool) - and (lookup('config', 'web-app-nextcloud', 'services.talk.turn_server.standalone_enabled') | bool) - and (lookup('config', 'web-app-nextcloud', 'services.talk.network_mode') == 'bridge') - and (IS_COMPOSE_MODE | bool) - and (networks.internet.ip4 in ansible_facts['all_ipv4_addresses']) }} + direct_media: false cpus: "2.0" - mem_reservation: 1g - mem_limit: 2g + mem_reservation: 512m + mem_limit: 1g pids_limit: 1024 - min_storage: 274MB + min_storage: 600MB ports: internal: - signaling: 8081 + websocket: 8188 public: relay: start: 61000 end: 61999 healthcheck: - flavor: tcp + flavor: nc + port_key: websocket +# nocheck: playwright-service-flag the signaling server is part of the Talk deployment, covered by the Talk admin settings spec +# nocheck: dynamic-flag the signaling server is part of the Talk deployment, so it follows the talk entry rather than a role's presence +talk_signaling: + enabled: "{{ lookup('config', 'web-app-nextcloud', 'services.talk.enabled') | bool }}" + shared: false + name: nextcloud-talk-signaling + image: strukturag/nextcloud-spreed-signaling + version: 2.1.1 + # nocheck: single-replica sessions live in this process; a second replica behind the VIP would split one call across servers + replicas: 1 + max_stream_bitrate: 1048576 + max_screen_bitrate: 2097152 + cpus: "1.0" + mem_reservation: 128m + mem_limit: 512m + pids_limit: 256 + min_storage: 223MB + ports: + internal: + signaling: 8081 + healthcheck: + flavor: http_status port_key: signaling - # nocheck: healthcheck-timing-override a sidecar of a stack whose main service alone takes minutes; the value predates this default and has not been measured against it - start_period: 20m + path: api/v1/welcome +# nocheck: playwright-service-flag internal message bus, reachable only from the Talk signaling server +# nocheck: dynamic-flag the message bus is part of the Talk deployment, so it follows the talk entry rather than a role's presence +talk_nats: + enabled: "{{ lookup('config', 'web-app-nextcloud', 'services.talk.enabled') | bool }}" + shared: false + name: nextcloud-talk-nats + image: nats + version: 2.12.6-alpine + # nocheck: single-replica an unclustered NATS server; the signaling server connects to exactly one + replicas: 1 + cpus: "0.5" + mem_reservation: 32m + mem_limit: 256m + pids_limit: 128 + min_storage: 211MB + ports: + internal: + nats: 4222 + http: 8222 + healthcheck: + flavor: http + path: healthz whiteboard: name: nextcloud-whiteboard image: ghcr.io/nextcloud-releases/whiteboard @@ -280,19 +320,24 @@ talk_recording: enabled: "{{ lookup('config', 'web-app-nextcloud', 'services.talk.enabled') | bool }}" shared: false name: nextcloud-talk-recording - image: nextcloud/aio-talk-recording - # nocheck: docker-version -- all 104 tags upstream publishes are AIO build stamps, none is a version - version: latest - backup: - stop_required: false + image: python + version: 3.14.3-alpine3.23 + custom: nextcloud-talk-recording + repository: https://github.com/nextcloud/nextcloud-talk-recording.git + ref: v0.2.1 + # nocheck: single-replica Talk starts and stops a recording on the server it reached; a second replica behind the VIP would receive half of the stop requests + replicas: 1 cpus: "2.0" mem_reservation: 1g mem_limit: 3g pids_limit: 1024 - min_storage: 507MB + min_storage: 993MB ports: internal: recording: 1234 + healthcheck: + flavor: nc + port_key: recording # nocheck: playwright-service-flag: verified by web-svc-design provider spec design: bond: 1 diff --git a/roles/web-app-nextcloud/meta/volumes.yml b/roles/web-app-nextcloud/meta/volumes.yml index 384d050809..fd4dd9d89f 100644 --- a/roles/web-app-nextcloud/meta/volumes.yml +++ b/roles/web-app-nextcloud/meta/volumes.yml @@ -7,6 +7,8 @@ data: target: &var_www_html_target /var/www/html/ - service: cron target: *var_www_html_target + - service: taskprocessing + target: *var_www_html_target - service: proxy target: *var_www_html_target read_only: true @@ -31,6 +33,8 @@ talk_recording_tmp: name: nextcloud_talk_recording_tmp type: volume backup: false + # nocheck: nfs-false-data-loss Reason: scratch for Xvfb sockets, the Firefox profile and the ffmpeg output before its upload; single replica, nothing persists. + nfs: false mounts: - service: talk_recording target: *tmp_target @@ -43,15 +47,6 @@ nginx_conf: - service: proxy target: /etc/nginx/nginx.conf -talk_network_backends: - type: config - source: "{{ [ lookup('container', 'web-app-nextcloud', 'directories.volumes'), 'talk-network-backends.sh' ] | path_join }}" - mode: "0444" - mounts: - - service: talk - target: /usr/local/share/infinito/talk-network-backends.sh - when: "{{ lookup('config', 'web-app-nextcloud', 'addons.spreed.enabled') | bool }}" - fpm_pool_conf: type: config source: "{{ [ lookup('container', 'web-app-nextcloud', 'directories.volumes'), 'fpm-pool.conf' ] | path_join }}" @@ -69,14 +64,35 @@ infinito_conf: target: &var_www_infinito_target /var/www/infinito/ - service: cron target: *var_www_infinito_target + - service: taskprocessing + target: *var_www_infinito_target janus_conf: type: config source: "{{ [ lookup('container', 'web-app-nextcloud', 'directories.volumes'), 'janus.jcfg' ] | path_join }}" + mode: "0444" mounts: - service: talk target: /usr/local/etc/janus/janus.jcfg - when: "{{ lookup('config', 'web-app-nextcloud', 'services.talk.direct_media') | bool }}" + when: "{{ lookup('config', 'web-app-nextcloud', 'services.talk.enabled') | bool }}" + +talk_signaling_conf: + type: secret + source: "{{ [ lookup('container', 'web-app-nextcloud', 'directories.volumes'), 'signaling.conf' ] | path_join }}" + mode: "0444" + mounts: + - service: talk_signaling + target: /config/server.conf + when: "{{ lookup('config', 'web-app-nextcloud', 'services.talk.enabled') | bool }}" + +talk_recording_conf: + type: secret + source: "{{ [ lookup('container', 'web-app-nextcloud', 'directories.volumes'), 'recording.conf' ] | path_join }}" + mode: "0444" + mounts: + - service: talk_recording + target: /conf/recording.conf + when: "{{ lookup('config', 'web-app-nextcloud', 'services.talk.enabled') | bool }}" php_hardening: type: config diff --git a/roles/web-app-nextcloud/tasks/01_fullstack.yml b/roles/web-app-nextcloud/tasks/01_fullstack.yml index 4913023619..67e84706eb 100644 --- a/roles/web-app-nextcloud/tasks/01_fullstack.yml +++ b/roles/web-app-nextcloud/tasks/01_fullstack.yml @@ -1,4 +1,24 @@ --- +- when: NEXTCLOUD_HPB_SIGNALING_ENABLED | bool + block: + - name: "πŸ›‘ Assert Janus joins the host network only in compose mode" + ansible.builtin.assert: + that: IS_COMPOSE_MODE + fail_msg: >- + services.talk.network_mode host gives Janus the host network namespace, + which docker stack deploy cannot provide. Use bridge in swarm mode. + quiet: true + when: NEXTCLOUD_HPB_JANUS_HOST_NETWORK | bool + + - name: "πŸ›‘ Assert Talk has the TURN server its calls relay through" + ansible.builtin.assert: + that: NEXTCLOUD_HPB_TURN_ACTIVE_SERVER | length > 0 + fail_msg: >- + services.talk.enabled is true, but {{ NEXTCLOUD_HPB_TURN_STANDALONE_ROLE }} is not deployed + on this host, so Talk would hand out no STUN or TURN server and calls behind NAT would carry + no media. Deploy {{ NEXTCLOUD_HPB_TURN_STANDALONE_ROLE }} or set services.talk.enabled to false. + quiet: true + - name: "🧩 load docker, db and proxy for {{ application_id }}" include_role: name: sys-stk-full @@ -7,49 +27,6 @@ application_id: web-app-nextcloud webserver_client_max_body_size: 10G -- when: - - NEXTCLOUD_HPB_MEDIA_DIRECT | bool - - IS_STACK_HOST | bool - block: - - name: "πŸ” Read the Janus launcher and config from {{ NEXTCLOUD_HPB_IMAGE }}" - ansible.builtin.command: - argv: - - container - - run - - --rm - - --pull - - always - - --entrypoint - - cat - - "{{ NEXTCLOUD_HPB_IMAGE }}" - - "{{ item }}" - environment: - CA_CONTAINER_ENABLED: "0" - loop: - - "{{ NEXTCLOUD_HPB_JANUS_LAUNCHER }}" - - "{{ NEXTCLOUD_HPB_JANUS_CONFIG_TARGET }}" - register: nextcloud_janus_image_files - changed_when: false - retries: 3 - delay: 30 - until: nextcloud_janus_image_files is succeeded - - - name: "πŸ›‘ Assert Janus reads the mounted config and the image's copy still matches" - ansible.builtin.assert: - that: nextcloud_janus_drift | length == 0 - fail_msg: >- - templates/janus.jcfg.j2 cannot replace {{ NEXTCLOUD_HPB_JANUS_CONFIG_TARGET }} - of {{ NEXTCLOUD_HPB_IMAGE }}: {{ nextcloud_janus_drift | join('; ') }}. - Re-derive the template from the new image before deploying. - quiet: true - vars: - nextcloud_janus_drift: >- - {{ lookup('template', 'janus.jcfg.j2') - | janus_config_drift(nextcloud_janus_image_files.results[1].stdout, - NEXTCLOUD_HPB_JANUS_OVERRIDES, - nextcloud_janus_image_files.results[0].stdout, - NEXTCLOUD_HPB_JANUS_CONFIG_TARGET) }} - - name: "πŸ“„ Deploy '{{ NEXTCLOUD_INIT_GATE_HOST }}'" copy: src: "{{ NEXTCLOUD_INIT_GATE_SRC }}" @@ -71,8 +48,8 @@ mode: "0755" - name: "πŸ“„ Deploy Whiteboard Dockerfile to {{ NEXTCLOUD_WHITEBOARD_SERVICE_DOCKERFILE }}" - stack_host_template: - src: "Dockerfiles/Whiteboard.j2" + stack_host_copy: + src: "Dockerfiles/Whiteboard/Dockerfile" dest: "{{ NEXTCLOUD_WHITEBOARD_SERVICE_DOCKERFILE }}" notify: - compose-build @@ -122,22 +99,43 @@ - src: "fpm-pool.conf.j2" dest: "{{ NEXTCLOUD_HOST_FPM_POOL_PATH }}" -- name: "πŸ“„ Render the Talk signaling backend list for every network (local + swarm peers)" - ansible.builtin.include_tasks: - file: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/render_replicated_templates.yml') }}" - vars: - role_templates: - - src: "{{ lookup('path_absolute', 'roles/web-app-nextcloud/files/shell/talk-network-backends.sh') }}" - dest: "{{ NEXTCLOUD_HOST_TALK_BACKENDS_PATH }}" - mode: "0444" - when: NEXTCLOUD_HPB_SIGNALING_ENABLED | bool +- when: NEXTCLOUD_HPB_SIGNALING_ENABLED | bool + block: + - name: "πŸ“ Create the Talk build directories" + ansible.builtin.file: + path: "{{ item }}" + state: directory + mode: "0755" + loop: + - "{{ NEXTCLOUD_HPB_JANUS_BUILD_DIRECTORY }}" + - "{{ NEXTCLOUD_RECORDING_BUILD_DIRECTORY }}" -- name: "πŸ“„ Render the Janus config that publishes Talk media directly" - ansible.builtin.include_tasks: - file: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/render_replicated_templates.yml') }}" - vars: - role_templates: - - src: "janus.jcfg.j2" - dest: "{{ NEXTCLOUD_HPB_JANUS_CONFIG_HOST }}" - mode: "0644" - when: NEXTCLOUD_HPB_MEDIA_DIRECT | bool + - name: "πŸ“„ Deploy the Talk Dockerfiles that build Janus and the recording server" + stack_host_copy: + src: "{{ item.src }}" + dest: "{{ item.dest }}" + loop: + - { src: "Dockerfiles/Janus/Dockerfile", dest: "{{ NEXTCLOUD_HPB_JANUS_DOCKERFILE }}" } + - { src: "Dockerfiles/Recording/Dockerfile", dest: "{{ NEXTCLOUD_RECORDING_DOCKERFILE }}" } + notify: + - compose-build + - compose-up + + - name: "πŸ“„ Render the Janus, signaling and recording configs (local + swarm peers)" + ansible.builtin.include_tasks: + file: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/render_replicated_templates.yml') }}" + vars: + role_templates: + - src: "janus.jcfg.j2" + dest: "{{ NEXTCLOUD_HPB_JANUS_CONFIG_HOST }}" + mode: "0644" + - src: "signaling.conf.j2" + dest: "{{ NEXTCLOUD_HPB_SIGNALING_CONFIG_HOST }}" + owner: "{{ NEXTCLOUD_HPB_SIGNALING_USER_ID }}" + group: "{{ NEXTCLOUD_HPB_SIGNALING_USER_ID }}" + mode: "0400" + - src: "recording.conf.j2" + dest: "{{ NEXTCLOUD_RECORDING_CONFIG_HOST }}" + owner: "{{ NEXTCLOUD_RECORDING_USER_ID }}" + group: "{{ NEXTCLOUD_RECORDING_USER_ID }}" + mode: "0400" diff --git a/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/02_install.yml b/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/02_install.yml index 9f7f8222d0..8515687f96 100644 --- a/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/02_install.yml +++ b/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/02_install.yml @@ -16,14 +16,16 @@ dest: "/tmp/nextcloud-plugin-{{ plugin_key }}.tar.gz" mode: "0644" - - name: "πŸ“¦ Unpack the pinned {{ plugin_key }} release so occ finds it installed" + - name: "πŸ“¦ Replace {{ plugin_key }} with the pinned release when any of its files differ" ansible.builtin.shell: >- cat /tmp/nextcloud-plugin-{{ plugin_key }}.tar.gz | {{ NEXTCLOUD_DOCKER_EXEC_INTERACTIVE }} - tar -xzf - -C {{ NEXTCLOUD_APPS_DIRECTORY | quote }} + sh -c {{ lookup('file', 'shell/utils/replace_pinned_app.sh') | quote }} + replace_pinned_app.sh {{ NEXTCLOUD_APPS_DIRECTORY | quote }} {{ plugin_key | quote }} args: executable: /bin/bash - changed_when: false + register: nextcloud_plugin_archive_replace + changed_when: "'[CHANGED]' in nextcloud_plugin_archive_replace.stdout" - name: "πŸ”΄ Disable incompatible plugins for {{ plugin_key }} (batched shell, no async)" ansible.builtin.shell: | diff --git a/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/README.md b/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/README.md index 5844edeffb..e8fb82f362 100644 --- a/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/README.md +++ b/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/README.md @@ -52,6 +52,16 @@ Each `tasks/02_manager_ops/06_plugin/.yml` file owns exactly one OCC stage | [03_enable.yml](./03_enable.yml) | enable | `occ app:enable` | enable result is not flagged `incompatible`; the plugin is then queued for the configure stage | | [04_configure.yml](./04_configure.yml) | configure | one `occ config:list`, then `occ config:app:set` for the values that differ, plus optional hook | (terminal stage) | +## Pinned archives + +An addon MAY pin a release through `config.archive`. Before `occ app:install`, [02_install.yml](./02_install.yml) stages the archive on the node and pipes it into [files/shell/utils/replace_pinned_app.sh](../../../files/shell/utils/replace_pinned_app.sh) inside the container: + +1. The script unpacks the archive into `custom_apps/..stage`, a directory Nextcloud skips because of its leading dot, and fails without touching the installed app when the archive lacks `/appinfo/info.xml`. +2. When `diff -rq` finds the installed app identical to the release, it removes the stage and the task reports no change. +3. Otherwise it renames the installed app to `custom_apps/..old`, moves the release into its place and removes both, so the app directory holds exactly the files of the release and the task reports a change. + +`occ app:install` then answers `already installed`. + ## Configure stage [04_configure.yml](./04_configure.yml) runs once for every queued plugin: first the plugins the install loop enabled, then the background installs, then those the enable loop enabled, then those of the `configure` plan list. diff --git a/roles/web-app-nextcloud/tasks/addons/app_api.yml b/roles/web-app-nextcloud/tasks/addons/app_api.yml new file mode 100644 index 0000000000..ed97d539c0 --- /dev/null +++ b/roles/web-app-nextcloud/tasks/addons/app_api.yml @@ -0,0 +1 @@ +--- diff --git a/roles/web-app-nextcloud/templates/Dockerfile.j2 b/roles/web-app-nextcloud/templates/Dockerfile.j2 deleted file mode 100644 index 62bf81e348..0000000000 --- a/roles/web-app-nextcloud/templates/Dockerfile.j2 +++ /dev/null @@ -1,9 +0,0 @@ -FROM {{ NEXTCLOUD_IMAGE }}:{{ NEXTCLOUD_VERSION }} -{% if NEXTCLOUD_ONLYOFFICE_ENABLED | bool %} -RUN apk add --no-cache ca-certificates && update-ca-certificates -{% endif %} - -COPY {{ NEXTCLOUD_INIT_GATE_FILE }} /usr/local/bin/{{ NEXTCLOUD_INIT_GATE_FILE }} -RUN chmod 0755 /usr/local/bin/{{ NEXTCLOUD_INIT_GATE_FILE }} -ENTRYPOINT ["/usr/local/bin/{{ NEXTCLOUD_INIT_GATE_FILE }}"] -CMD ["php-fpm"] diff --git a/roles/web-app-nextcloud/templates/compose.yml.j2 b/roles/web-app-nextcloud/templates/compose.yml.j2 index f44ab994bb..db7f067fe4 100644 --- a/roles/web-app-nextcloud/templates/compose.yml.j2 +++ b/roles/web-app-nextcloud/templates/compose.yml.j2 @@ -11,9 +11,7 @@ {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_healthcheck', service_name, samples=(groups[application_id] | default([]) | length) if IS_SWARM_MODE else 1) | indent(4) }} {{ lookup('container_networks') | indent(4) }} - {{ lookup('container_extra_hosts', extra_hosts=( - ['host.docker.internal:host-gateway'] if NEXTCLOUD_HPB_NETWORK_MODE == 'host' else [] - )) | indent(4) }} + {{ lookup('container_extra_hosts') | indent(4) }} {% set service_name = NEXTCLOUD_SERVICE %} {% set container_healthcheck_start_period = '20m' %} @@ -21,12 +19,21 @@ {{ lookup('container_image', application_id, 'nextcloud') }} {{ lookup('compose_only', 'container_name', NEXTCLOUD_CONTAINER) }} {{ lookup('template', 'roles/sys-svc-container/templates/build.yml.j2') | indent(4) }} + args: + NEXTCLOUD_IMAGE: "{{ NEXTCLOUD_IMAGE }}" + NEXTCLOUD_VERSION: "{{ NEXTCLOUD_VERSION }}" + NEXTCLOUD_ONLYOFFICE_ENABLED: "{{ NEXTCLOUD_ONLYOFFICE_ENABLED | bool | lower }}" + NEXTCLOUD_INIT_GATE_FILE: "{{ NEXTCLOUD_INIT_GATE_FILE }}" {{ lookup('container_volumes', service_name) | indent(4) }} - {% if IS_SWARM_MODE %} - environment: # nocheck: compose-environment-from-env-file the value is a swarm task-template placeholder, and this role's single env.j2 is also the env_file of context_agent, hpb, whiteboard and talk_recording + # nocheck: compose-environment-from-env-file NC_serverid belongs to this service alone and in swarm is a task-template placeholder, while this role's single env.j2 is also the env_file of cron, taskprocessing, context_agent, whiteboard and the Talk services + environment: + {% if IS_SWARM_MODE %} TASK_SLOT: "{% raw %}{{.Task.Slot}}{% endraw %}" - {% endif %} + NC_serverid: "{% raw %}{{.Task.Slot}}{% endraw %}" + {% else %} + NC_serverid: "1" + {% endif %} sysctls: net.ipv6.conf.all.disable_ipv6: "{{ (not NETWORK_IPV6_ENABLED | bool) | int }}" healthcheck: @@ -66,42 +73,62 @@ {% if NEXTCLOUD_HPB_SIGNALING_ENABLED | bool %} {% set service_name = NEXTCLOUD_HPB_SERVICE %} - {% set container_port = NEXTCLOUD_HPB_SIGNALING_PORT %} {{ service_name }}: {% include 'roles/sys-svc-container/templates/base.yml.j2' %} - {{ lookup('container_healthcheck', service_name) | indent(4) }} - {{ lookup('container_image', application_id, 'talk') }} + build: + context: {{ NEXTCLOUD_HPB_JANUS_BUILD_DIRECTORY }} + dockerfile: Dockerfile + args: + JANUS_BASE_IMAGE: "{{ NEXTCLOUD_HPB_JANUS_BASE_IMAGE }}" + JANUS_BASE_VERSION: "{{ NEXTCLOUD_HPB_JANUS_BASE_VERSION }}" + JANUS_REPOSITORY: "{{ NEXTCLOUD_HPB_JANUS_REPOSITORY }}" + JANUS_REF: "{{ NEXTCLOUD_HPB_JANUS_REF }}" + {{ lookup('compose_only', 'pull_policy', 'never') }} + {{ lookup('container_image', application_id, service_name, version=NEXTCLOUD_HPB_JANUS_TAG) }} {{ lookup('compose_only', 'container_name', NEXTCLOUD_HPB_CONTAINER) }} - command: ["/start.sh", "sh", "{{ NEXTCLOUD_TALK_BACKENDS_SCRIPT }}", "supervisord", "-c", "/supervisord.conf"] - {{ lookup('container_volumes', service_name) | indent(4) }} + command: ["--config={{ NEXTCLOUD_HPB_JANUS_CONFIG_TARGET }}"] init: true - {% if NEXTCLOUD_HPB_NETWORK_MODE == 'bridge' %} - {% set _talk_ports = [] %} - {% if NEXTCLOUD_HPB_TURN_ONBOARD_ENABLED | bool and NEXTCLOUD_HPB_TURN_ONBOARD_PUBLISH_PORTS | bool %} - {% set _ = _talk_ports.extend([ - {'service': 'nextcloud', 'protocol': 'stun_turn', - 'ip': NEXTCLOUD_HPB_TURN_ONBOARD_BIND_HOST, - 'transport': ['tcp', 'udp'], 'container': 'same'}, - {'service': 'nextcloud', 'protocol': 'relay', - 'ip': NEXTCLOUD_HPB_TURN_ONBOARD_BIND_HOST, - 'transport': ['udp', 'tcp'], 'container': 'same'}, - ]) %} - {% endif %} + {{ lookup('container_healthcheck', service_name) | indent(4) }} + {{ lookup('container_volumes', service_name) | indent(4) }} + {% if IS_COMPOSE_MODE and NEXTCLOUD_HPB_JANUS_HOST_NETWORK | bool %} + network_mode: host + {% else %} {% if NEXTCLOUD_HPB_MEDIA_DIRECT | bool %} - {% set _ = _talk_ports.append( - {'service': 'talk', 'protocol': 'relay', - 'ip': NEXTCLOUD_HPB_MEDIA_PUBLIC_IP, - 'transport': 'udp', 'container': 'same'}) %} - {% endif %} - {% if _talk_ports %} - {{ lookup('container_ports', *_talk_ports) | indent(4) }} + {{ lookup('container_ports', + {'service': service_name, 'protocol': 'relay', + 'ip': NEXTCLOUD_HPB_MEDIA_PUBLIC_IP, + 'transport': 'udp', 'container': 'same'}) | indent(4) }} {% endif %} expose: - - "{{ container_port }}" - {{ lookup('container_networks', provider_self_alias=False) | indent(4) }} - {% else %} - network_mode: {{ NEXTCLOUD_HPB_NETWORK_MODE }} + - "{{ NEXTCLOUD_HPB_JANUS_PORT }}" + {{ lookup('container_networks', own_network_only=True, provider_self_alias=False) | indent(4) }} {% endif %} + + {% set service_name = NEXTCLOUD_HPB_SIGNALING_SERVICE %} + {{ service_name }}: + {% include 'roles/sys-svc-container/templates/base.yml.j2' %} + {{ lookup('container_image', application_id, service_name) }} + {{ lookup('compose_only', 'container_name', NEXTCLOUD_HPB_SIGNALING_CONTAINER) }} + user: "{{ NEXTCLOUD_HPB_SIGNALING_USER_ID }}:{{ NEXTCLOUD_HPB_SIGNALING_USER_ID }}" + command: ["{{ NEXTCLOUD_HPB_SIGNALING_BINARY }}", "-config", "{{ NEXTCLOUD_HPB_SIGNALING_CONFIG_TARGET }}"] + {{ lookup('container_healthcheck', service_name) | indent(4) }} + {{ lookup('container_volumes', service_name) | indent(4) }} + expose: + - "{{ NEXTCLOUD_HPB_SIGNALING_PORT }}" + {{ lookup('container_extra_hosts', host_alias=NEXTCLOUD_HPB_JANUS_HOST_NETWORK) | indent(4) }} + {{ lookup('container_networks', provider_self_alias=False) | indent(4) }} + + {% set service_name = NEXTCLOUD_HPB_NATS_SERVICE %} + {{ service_name }}: + {% include 'roles/sys-svc-container/templates/base.yml.j2' %} + {{ lookup('container_image', application_id, service_name) }} + {{ lookup('compose_only', 'container_name', NEXTCLOUD_HPB_NATS_CONTAINER) }} + user: "{{ NEXTCLOUD_HPB_NATS_USER_ID }}:{{ NEXTCLOUD_HPB_NATS_USER_ID }}" + command: ["nats-server", "--addr", "0.0.0.0", "--port", "{{ NEXTCLOUD_HPB_NATS_PORT }}", "--http_port", "{{ NEXTCLOUD_HPB_NATS_MONITOR_PORT }}"] + {{ lookup('container_healthcheck', service_name) | indent(4) }} + expose: + - "{{ NEXTCLOUD_HPB_NATS_PORT }}" + {{ lookup('container_networks', own_network_only=True, provider_self_alias=False) | indent(4) }} {% endif %} {% if NEXTCLOUD_WHITEBOARD_ENABLED %} @@ -110,8 +137,11 @@ {{ service_name }}: {% include 'roles/sys-svc-container/templates/base.yml.j2' %} build: - context: . - dockerfile: {{ NEXTCLOUD_WHITEBOARD_SERVICE_DOCKERFILE }} + context: {{ NEXTCLOUD_WHITEBOARD_SERVICE_DIRECTORY }} + dockerfile: Dockerfile + args: + WHITEBOARD_IMAGE: "{{ NEXTCLOUD_WHITEBOARD_IMAGE }}" + WHITEBOARD_VERSION: "{{ NEXTCLOUD_WHITEBOARD_VERSION }}" {{ lookup('compose_only', 'pull_policy', 'never') }} {{ lookup('container_image', application_id, 'whiteboard') }} {{ lookup('container_healthcheck', service_name) | indent(4) }} @@ -150,12 +180,52 @@ {{ lookup('container_depends_on', application_id) | indent(4) }} {{ lookup('container_networks', provider_self_alias=False) | indent(4) }} + {% set service_name = NEXTCLOUD_TASKPROCESSING_SERVICE %} + {{ service_name }}: + {% include 'roles/sys-svc-container/templates/deploy.yml.j2' %} + {{ lookup('compose_only', 'container_name', NEXTCLOUD_TASKPROCESSING_CONTAINER) }} + {{ lookup('container_image', application_id, 'nextcloud') }} + {{ lookup('compose_restart') }} + logging: + driver: journald + {{ lookup('container_volumes', service_name) | indent(4) }} + entrypoint: ["su", "{{ NEXTCLOUD_DOCKER_USER }}", "-s", "/bin/sh", "-c", "while true; do php {{ NEXTCLOUD_INTERNAL_OCC_COMMAND }} taskprocessing:worker -t 60 || sleep 10; done"] + sysctls: + net.ipv6.conf.all.disable_ipv6: "{{ (not NETWORK_IPV6_ENABLED | bool) | int }}" + healthcheck: + test: ["CMD", "su", "{{ NEXTCLOUD_DOCKER_USER }}", "-s", "/bin/sh", "-c", "php {{ NEXTCLOUD_INTERNAL_OCC_COMMAND }} status"] + # nocheck: healthcheck-timing-override occ boots the whole Nextcloud stack per probe, so it stays off a 30s loop + interval: 1m + # nocheck: healthcheck-timing-override occ regularly needs more than the 5s default to answer + timeout: 30s + retries: 10 + # nocheck: healthcheck-timing-override a role variable the linter cannot compare, tuned per deployment size + start_period: {{ container_healthcheck_start_period }} + start_interval: 5s + {{ lookup('container_depends_on', application_id) | indent(4) }} + {{ lookup('container_networks', provider_self_alias=False) | indent(4) }} + {% if NEXTCLOUD_RECORDING_ENABLED | bool %} - {% set service_name = 'talk_recording' %} + {% set service_name = NEXTCLOUD_RECORDING_SERVICE %} {{ service_name }}: {% include 'roles/sys-svc-container/templates/base.yml.j2' %} - {{ lookup('container_image', application_id, 'talk_recording') }} + build: + context: {{ NEXTCLOUD_RECORDING_BUILD_DIRECTORY }} + dockerfile: Dockerfile + args: + RECORDING_BASE_IMAGE: "{{ NEXTCLOUD_RECORDING_BASE_IMAGE }}" + RECORDING_BASE_VERSION: "{{ NEXTCLOUD_RECORDING_BASE_VERSION }}" + RECORDING_REPOSITORY: "{{ NEXTCLOUD_RECORDING_REPOSITORY }}" + RECORDING_REF: "{{ NEXTCLOUD_RECORDING_REF }}" + RECORDING_USER_ID: "{{ NEXTCLOUD_RECORDING_USER_ID }}" + RECORDING_DIRECTORY: "{{ NEXTCLOUD_RECORDING_DIRECTORY }}" + RECORDING_CONFIG_DIRECTORY: "{{ NEXTCLOUD_RECORDING_CONFIG_TARGET | dirname }}" + RECORDING_CA_CERT: "{{ NEXTCLOUD_RECORDING_CA_CERT }}" + {{ lookup('compose_only', 'pull_policy', 'never') }} + {{ lookup('container_image', application_id, service_name, version=NEXTCLOUD_RECORDING_TAG) }} {{ lookup('compose_only', 'container_name', NEXTCLOUD_RECORDING_CONTAINER) }} + command: ["--config", "{{ NEXTCLOUD_RECORDING_CONFIG_TARGET }}"] + {{ lookup('container_healthcheck', service_name) | indent(4) }} expose: - "{{ NEXTCLOUD_RECORDING_PORT }}" {{ lookup('container_networks', provider_self_alias=False) | indent(4) }} diff --git a/roles/web-app-nextcloud/templates/docker.conf.j2 b/roles/web-app-nextcloud/templates/docker.conf.j2 index e34378de6e..214f187c37 100644 --- a/roles/web-app-nextcloud/templates/docker.conf.j2 +++ b/roles/web-app-nextcloud/templates/docker.conf.j2 @@ -119,13 +119,9 @@ http { } {% if NEXTCLOUD_HPB_SIGNALING_ENABLED | bool %} location {{ NEXTCLOUD_HPB_SIGNALING_LOCATION }} { -{% if NEXTCLOUD_HPB_NETWORK_MODE == 'host' %} - proxy_pass http://host.docker.internal:{{ NEXTCLOUD_HPB_SIGNALING_PORT }}/; -{% else %} - set $upstream_nextcloud_talk http://talk:{{ NEXTCLOUD_HPB_SIGNALING_PORT }}; + set $upstream_nextcloud_talk http://{{ NEXTCLOUD_HPB_SIGNALING_SERVICE }}:{{ NEXTCLOUD_HPB_SIGNALING_PORT }}; rewrite ^{{ NEXTCLOUD_HPB_SIGNALING_LOCATION }}(.*)$ /$1 break; proxy_pass $upstream_nextcloud_talk; -{% endif %} proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header Upgrade $http_upgrade; diff --git a/roles/web-app-nextcloud/templates/env.j2 b/roles/web-app-nextcloud/templates/env.j2 index 6177bc5260..d459b3e9ad 100644 --- a/roles/web-app-nextcloud/templates/env.j2 +++ b/roles/web-app-nextcloud/templates/env.j2 @@ -27,7 +27,7 @@ NEXTCLOUD_ADMIN_PASSWORD={{ NEXTCLOUD_ADMINISTRATOR_PASSWORD | dotenv_quote }} NEXTCLOUD_INIT_GATE_USER={{ NEXTCLOUD_DOCKER_USER }} NEXTCLOUD_TRUSTED_DOMAINS={{ NEXTCLOUD_DOMAIN }} -TRUSTED_PROXIES={{ NEXTCLOUD_TRUSTED_PROXIES | join(',') }} +TRUSTED_PROXIES={{ NEXTCLOUD_TRUSTED_PROXIES | join(' ') }} OVERWRITECLIURL={{ NEXTCLOUD_URL }} REDIS_HOST={{ lookup('engine', 'redis', application_id, 'host') }} @@ -53,20 +53,6 @@ OBJECTSTORE_S3_SECRET={{ lookup('objstore', application_id, 'secret_key') | dote OBJECTSTORE_S3_AUTOCREATE=false {% endif %} -{% if NEXTCLOUD_HPB_PLUGIN_ENABLED %} -NC_DOMAIN={{ NEXTCLOUD_DOMAIN }} -TALK_NETWORK_BACKEND_URLS={{ lookup('network_urls', lookup('tls', application_id, 'url.origin'))[1:] | join(',') }} -TALK_HOST={{ NEXTCLOUD_HPB_DOMAIN }} -SIGNALING_SECRET={{ NEXTCLOUD_HPB_SIGNALING_SECRET }} -INTERNAL_SECRET={{ NEXTCLOUD_HPB_INTERNAL_SECRET }} -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 }} -{% endif %} - {% if NEXTCLOUD_WHITEBOARD_ENABLED %} NEXTCLOUD_URL={{ NEXTCLOUD_URL }} JWT_SECRET_KEY={{ NEXTCLOUD_WHITEBOARD_JWT }} diff --git a/roles/web-app-nextcloud/templates/janus.jcfg.j2 b/roles/web-app-nextcloud/templates/janus.jcfg.j2 index 983506ab06..956b422048 100644 --- a/roles/web-app-nextcloud/templates/janus.jcfg.j2 +++ b/roles/web-app-nextcloud/templates/janus.jcfg.j2 @@ -34,13 +34,16 @@ certificates: { } media: { +{% if NEXTCLOUD_HPB_MEDIA_DIRECT | bool %} rtp_port_range = "{{ NEXTCLOUD_HPB_MEDIA_PORT_START }}-{{ NEXTCLOUD_HPB_MEDIA_PORT_END }}" +{% endif %} } nat: { - nice_debug = false +{% if NEXTCLOUD_HPB_MEDIA_DIRECT | bool %} nat_1_1_mapping = "{{ NEXTCLOUD_HPB_MEDIA_PUBLIC_IP }}" keep_private_host = true +{% endif %} ice_ignore_list = "vmnet" } diff --git a/roles/web-app-nextcloud/templates/playwright.env.j2 b/roles/web-app-nextcloud/templates/playwright.env.j2 index e9a91558f5..19d680c4f5 100644 --- a/roles/web-app-nextcloud/templates/playwright.env.j2 +++ b/roles/web-app-nextcloud/templates/playwright.env.j2 @@ -57,6 +57,8 @@ NEXTCLOUD_TALK_DIRECT_MEDIA_PORT_START={{ NEXTCLOUD_HPB_MEDIA_PORT_START }} NEXTCLOUD_TALK_EXPECTED_SIGNALING_URL={{ NEXTCLOUD_HPB_SIGNALING_URL | dotenv_quote }} +NEXTCLOUD_TALK_EXPECTED_SIGNALING_VERSION={{ NEXTCLOUD_HPB_SIGNALING_VERSION | 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 }} @@ -65,10 +67,6 @@ NEXTCLOUD_TALK_SETTINGS_CHECK_ENABLED={{ NEXTCLOUD_HPB_PLUGIN_ENABLED | string | NEXTCLOUD_TALK_SETTINGS_URL={{ NEXTCLOUD_TALK_ADMIN_URL | 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 }} - OIDC_ISSUER_URL={{ OIDC.CLIENT.ISSUER_URL | dotenv_quote }} OPENPROJECT_BASE_URL={{ (lookup('landing_url', 'web-app-openproject') if (lookup('config', application_id, 'services.openproject.enabled') | bool) else '') | dotenv_quote }} diff --git a/roles/web-app-nextcloud/templates/recording.conf.j2 b/roles/web-app-nextcloud/templates/recording.conf.j2 new file mode 100644 index 0000000000..5549758113 --- /dev/null +++ b/roles/web-app-nextcloud/templates/recording.conf.j2 @@ -0,0 +1,36 @@ +[logs] +level = 30 + +[http] +listen = 0.0.0.0:{{ NEXTCLOUD_RECORDING_PORT }} + +[backend] +allowall = false +secret = {{ NEXTCLOUD_RECORDING_SECRET }} +backends = backend-1 +skipverify = false +maxmessagesize = 1024 +videowidth = 1920 +videoheight = 1080 +directory = {{ NEXTCLOUD_RECORDING_DIRECTORY }} + +[backend-1] +url = {{ NEXTCLOUD_HPB_BACKEND_URL }} +secret = {{ NEXTCLOUD_RECORDING_SECRET }} +skipverify = false + +[signaling] +signalings = signaling-1 + +[signaling-1] +url = {{ NEXTCLOUD_HPB_BACKEND_URL }}{{ NEXTCLOUD_HPB_SIGNALING_LOCATION }} +internalsecret = {{ NEXTCLOUD_HPB_INTERNAL_SECRET }} + +[ffmpeg] +extensionaudio = .ogg +extensionvideo = .webm + +[recording] +browser = firefox +driverPath = /usr/bin/geckodriver +browserPath = /usr/bin/firefox diff --git a/roles/web-app-nextcloud/templates/signaling.conf.j2 b/roles/web-app-nextcloud/templates/signaling.conf.j2 new file mode 100644 index 0000000000..efce602701 --- /dev/null +++ b/roles/web-app-nextcloud/templates/signaling.conf.j2 @@ -0,0 +1,34 @@ +[http] +listen = 0.0.0.0:{{ NEXTCLOUD_HPB_SIGNALING_PORT }} + +[app] +debug = false + +[sessions] +hashkey = {{ ((NEXTCLOUD_HPB_SIGNALING_SECRET ~ '/sessions/hashkey') | hash('sha256'))[:32] }} +blockkey = {{ ((NEXTCLOUD_HPB_SIGNALING_SECRET ~ '/sessions/blockkey') | hash('sha256'))[:32] }} + +[clients] +internalsecret = {{ NEXTCLOUD_HPB_INTERNAL_SECRET }} + +[backend] +backends = backend-1 +allowall = false +timeout = 10 +connectionsperhost = 8 +skipverify = false + +[backend-1] +urls = {{ NEXTCLOUD_HPB_SIGNALING_BACKEND_URLS }} +secret = {{ NEXTCLOUD_HPB_SIGNALING_SECRET }} +maxstreambitrate = {{ NEXTCLOUD_HPB_SIGNALING_MAX_STREAM_BITRATE }} +maxscreenbitrate = {{ NEXTCLOUD_HPB_SIGNALING_MAX_SCREEN_BITRATE }} + +[nats] +url = {{ NEXTCLOUD_HPB_NATS_URL }} + +[mcu] +type = janus +url = {{ NEXTCLOUD_HPB_JANUS_URL }} +maxstreambitrate = {{ NEXTCLOUD_HPB_SIGNALING_MAX_STREAM_BITRATE }} +maxscreenbitrate = {{ NEXTCLOUD_HPB_SIGNALING_MAX_SCREEN_BITRATE }} diff --git a/roles/web-app-nextcloud/vars/main.yml b/roles/web-app-nextcloud/vars/main.yml index aa2ad5da7e..5e226c171a 100644 --- a/roles/web-app-nextcloud/vars/main.yml +++ b/roles/web-app-nextcloud/vars/main.yml @@ -10,7 +10,8 @@ database_password: "{{ lookup('config', application_id, 'secrets.credentials.dat NEXTCLOUD_DOMAIN: "{{ lookup('domain',application_id) }}" NEXTCLOUD_PORT: "{{ lookup('config', application_id, 'services.nextcloud.ports.local.http') }}" NEXTCLOUD_URL: "{{ lookup('tls', application_id, 'url.base') }}" -NEXTCLOUD_TRUSTED_PROXIES: "{{ networks.internet.values() | select }}" +NEXTCLOUD_PROTOCOL: "{{ lookup('tls', application_id, 'protocols.web') }}" +NEXTCLOUD_TRUSTED_PROXIES: "{{ lookup('proxy_hops', application_id) }}" NEXTCLOUD_SSO_ENABLED: "{{ lookup('config', application_id, 'services.sso.enabled') | bool }}" NEXTCLOUD_OIDC_HOST: "{{ lookup('tls', 'web-app-keycloak', 'domain') }}" @@ -40,8 +41,6 @@ NEXTCLOUD_LDAP_CONFIG_PREFIX: "s01" NEXTCLOUD_HOST_CONF_ADD_PATH: "{{ [ lookup('container', application_id, 'directories.volumes'), 'infinito' ] | path_join }}" NEXTCLOUD_HOST_NGINX_PATH: "{{ [ lookup('container', application_id, 'directories.volumes'), 'nginx.conf' ] | path_join }}" NEXTCLOUD_HOST_FPM_POOL_PATH: "{{ [ lookup('container', application_id, 'directories.volumes'), 'fpm-pool.conf' ] | path_join }}" -NEXTCLOUD_HOST_TALK_BACKENDS_PATH: "{{ [ lookup('container', application_id, 'directories.volumes'), 'talk-network-backends.sh' ] | path_join }}" -NEXTCLOUD_TALK_BACKENDS_SCRIPT: "{{ lookup('volume', application_id, 'talk_network_backends').target }}" NEXTCLOUD_CNODE_PLUGIN_TASKS_PATH: "{{ [role_path, 'tasks/addons/'] | path_join }}" @@ -156,51 +155,64 @@ NEXTCLOUD_CONTEXT_AGENT_JSON_INFO: >- NEXTCLOUD_CRON_SERVICE: "cron" NEXTCLOUD_CRON_CONTAINER: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_CRON_SERVICE ~ '.name') }}" +NEXTCLOUD_TASKPROCESSING_SERVICE: "taskprocessing" +NEXTCLOUD_TASKPROCESSING_CONTAINER: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_TASKPROCESSING_SERVICE ~ '.name') }}" + NEXTCLOUD_HPB_SERVICE: "talk" NEXTCLOUD_HPB_CONTAINER: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.name') }}" NEXTCLOUD_HPB_NETWORK_MODE: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.network_mode') }}" NEXTCLOUD_HPB_PLUGIN_ENABLED: "{{ lookup('config', application_id, 'addons.spreed.enabled') }}" NEXTCLOUD_HPB_INTERNAL_SECRET: "{{ lookup('config', application_id, 'secrets.credentials.talk_internal_secret') }}" NEXTCLOUD_HPB_DOMAIN: "{{ NEXTCLOUD_DOMAIN }}" +NEXTCLOUD_HPB_BACKEND_URL: "{{ NEXTCLOUD_PROTOCOL }}://{{ NEXTCLOUD_HPB_DOMAIN }}" +NEXTCLOUD_HPB_SIGNALING_BACKEND_URLS: "{{ lookup('network_urls', NEXTCLOUD_HPB_BACKEND_URL) | join(',') }}" -NEXTCLOUD_HPB_MEDIA_DIRECT: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.direct_media') | bool }}" +# nocheck: host-local-fact read only in compose mode, where the host rendering this file is the host Janus publishes its media ports on; Ansible omits the key on a host without the ip binary, which leaves the media on TURN +NEXTCLOUD_HPB_HOST_ADDRESSES: "{{ ansible_facts['all_ipv4_addresses'] | default([]) }}" +NEXTCLOUD_HPB_MEDIA_DIRECT: >- + {{ (lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.direct_media') | bool) + and (NEXTCLOUD_HPB_SIGNALING_ENABLED | bool) + and (NEXTCLOUD_HPB_TURN_STANDALONE_ENABLED | bool) + and IS_COMPOSE_MODE + and (networks.internet.ip4 in NEXTCLOUD_HPB_HOST_ADDRESSES) }} NEXTCLOUD_HPB_MEDIA_PUBLIC_IP: "{{ networks.internet.ip4 }}" NEXTCLOUD_HPB_MEDIA_PORT_START: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.ports.public.relay.start') }}" NEXTCLOUD_HPB_MEDIA_PORT_END: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.ports.public.relay.end') }}" NEXTCLOUD_HPB_JANUS_CONFIG_HOST: "{{ [ lookup('container', application_id, 'directories.volumes'), 'janus.jcfg' ] | path_join }}" NEXTCLOUD_HPB_JANUS_CONFIG_TARGET: "{{ lookup('volume', application_id, 'janus_conf').target }}" -NEXTCLOUD_HPB_JANUS_LAUNCHER: "/supervisord.conf" -NEXTCLOUD_HPB_JANUS_OVERRIDES: - - rtp_port_range - - nat_1_1_mapping - - keep_private_host -NEXTCLOUD_HPB_IMAGE: "{{ lookup('image', application_id, NEXTCLOUD_HPB_SERVICE) }}" +NEXTCLOUD_HPB_JANUS_PORT: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.ports.internal.websocket') }}" +NEXTCLOUD_HPB_JANUS_HOST_NETWORK: "{{ NEXTCLOUD_HPB_NETWORK_MODE == 'host' }}" +NEXTCLOUD_HPB_JANUS_URL: "ws://{{ 'host.docker.internal' if NEXTCLOUD_HPB_JANUS_HOST_NETWORK | bool else NEXTCLOUD_HPB_SERVICE }}:{{ NEXTCLOUD_HPB_JANUS_PORT }}" +NEXTCLOUD_HPB_JANUS_REPOSITORY: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.repository') }}" +NEXTCLOUD_HPB_JANUS_REF: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.ref') }}" +NEXTCLOUD_HPB_JANUS_BASE_IMAGE: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.image') }}" +NEXTCLOUD_HPB_JANUS_BASE_VERSION: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.version') }}" +NEXTCLOUD_HPB_JANUS_TAG: "{{ NEXTCLOUD_HPB_JANUS_REF }}-{{ NEXTCLOUD_HPB_JANUS_BASE_VERSION }}" +NEXTCLOUD_HPB_JANUS_BUILD_DIRECTORY: "{{ [ lookup('container', application_id, 'directories.services'), 'talk-janus' ] | path_join }}" +NEXTCLOUD_HPB_JANUS_DOCKERFILE: "{{ [ NEXTCLOUD_HPB_JANUS_BUILD_DIRECTORY, 'Dockerfile' ] | path_join }}" +NEXTCLOUD_HPB_SIGNALING_SERVICE: "talk_signaling" +NEXTCLOUD_HPB_SIGNALING_CONTAINER: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SIGNALING_SERVICE ~ '.name') }}" +NEXTCLOUD_HPB_SIGNALING_VERSION: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SIGNALING_SERVICE ~ '.version') }}" NEXTCLOUD_HPB_SIGNALING_SECRET: "{{ lookup('config', application_id, 'secrets.credentials.talk_signaling_secret') }}" NEXTCLOUD_HPB_SIGNALING_LOCATION: "/standalone-signaling/" -NEXTCLOUD_HPB_SIGNALING_PORT: "{{ lookup('config', application_id, 'services.talk.ports.internal.signaling') }}" +NEXTCLOUD_HPB_SIGNALING_PORT: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SIGNALING_SERVICE ~ '.ports.internal.signaling') }}" NEXTCLOUD_HPB_SIGNALING_URL: "{{ [ lookup('tls', NEXTCLOUD_DOMAIN, 'url.base'), NEXTCLOUD_HPB_SIGNALING_LOCATION ] | url_join }}" NEXTCLOUD_HPB_SIGNALING_ENABLED: "{{ NEXTCLOUD_HPB_PLUGIN_ENABLED }}" +NEXTCLOUD_HPB_SIGNALING_MAX_STREAM_BITRATE: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SIGNALING_SERVICE ~ '.max_stream_bitrate') }}" +NEXTCLOUD_HPB_SIGNALING_MAX_SCREEN_BITRATE: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SIGNALING_SERVICE ~ '.max_screen_bitrate') }}" +NEXTCLOUD_HPB_SIGNALING_USER_ID: 850 +NEXTCLOUD_HPB_SIGNALING_BINARY: "/usr/bin/nextcloud-spreed-signaling" +NEXTCLOUD_HPB_SIGNALING_CONFIG_HOST: "{{ [ lookup('container', application_id, 'directories.volumes'), 'signaling.conf' ] | path_join }}" +NEXTCLOUD_HPB_SIGNALING_CONFIG_TARGET: "{{ lookup('volume', application_id, 'talk_signaling_conf').target }}" NEXTCLOUD_TALK_ADMIN_URL: "{{ [ NEXTCLOUD_URL, 'settings/admin/talk' ] | url_join }}" -NEXTCLOUD_HPB_TURN_ONBOARD_PORT: "{{ lookup('config', application_id, 'services.nextcloud.ports.public.stun_turn') }}" -NEXTCLOUD_HPB_TURN_ONBOARD_BIND_HOST: "{{ DOCKER_PUBLIC_BIND_HOST }}" -NEXTCLOUD_HPB_TURN_ONBOARD_ENABLED: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.turn_server.onboard_enabled') if NEXTCLOUD_HPB_PLUGIN_ENABLED - else false }}" -NEXTCLOUD_HPB_TURN_ONBOARD_SECRET: "{{ lookup('config', application_id, 'secrets.credentials.talk_turn_secret') }}" -NEXTCLOUD_HPB_TURN_ONBOARD_PUBLISH_PORTS: "{{ not DOCKER_IN_CONTAINER | bool }}" -NEXTCLOUD_HPB_TURN_ONBOARD_RELAY_PORT_START: "{{ lookup('config', application_id, 'services.nextcloud.ports.public.relay.start') }}" -NEXTCLOUD_HPB_TURN_ONBOARD_RELAY_PORT_END: "{{ lookup('config', application_id, 'services.nextcloud.ports.public.relay.end') }}" -NEXTCLOUD_HPB_STUN_ONBOARD_CONFIG: "{{ NEXTCLOUD_HPB_DOMAIN }}:{{ NEXTCLOUD_HPB_TURN_ONBOARD_PORT }}" -NEXTCLOUD_HPB_TURN_ONBOARD_CONFIG: >- - {{ - { - 'server': NEXTCLOUD_HPB_DOMAIN ~ ':' ~ NEXTCLOUD_HPB_TURN_ONBOARD_PORT, - 'secret': NEXTCLOUD_HPB_TURN_ONBOARD_SECRET, - 'ttl': 86400, - 'protocols': 'udp,tcp' - } - }} +NEXTCLOUD_HPB_NATS_SERVICE: "talk_nats" +NEXTCLOUD_HPB_NATS_CONTAINER: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_NATS_SERVICE ~ '.name') }}" +NEXTCLOUD_HPB_NATS_PORT: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_NATS_SERVICE ~ '.ports.internal.nats') }}" +NEXTCLOUD_HPB_NATS_MONITOR_PORT: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_NATS_SERVICE ~ '.ports.internal.http') }}" +NEXTCLOUD_HPB_NATS_URL: "nats://{{ NEXTCLOUD_HPB_NATS_SERVICE }}:{{ NEXTCLOUD_HPB_NATS_PORT }}" +NEXTCLOUD_HPB_NATS_USER_ID: 65534 NEXTCLOUD_HPB_TURN_STANDALONE_ROLE: "web-svc-coturn" NEXTCLOUD_HPB_TURN_STANDALONE_PORT: "{{ lookup('config', NEXTCLOUD_HPB_TURN_STANDALONE_ROLE, 'services.coturn.ports.public.stun_turn') }}" @@ -218,26 +230,8 @@ 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_STUN_ACTIVE_CONFIG: "{{ NEXTCLOUD_HPB_STUN_STANDALONE_CONFIG if NEXTCLOUD_HPB_TURN_STANDALONE_ENABLED | bool else '' }}" +NEXTCLOUD_HPB_TURN_ACTIVE_CONFIG: "{{ NEXTCLOUD_HPB_TURN_STANDALONE_CONFIG if NEXTCLOUD_HPB_TURN_STANDALONE_ENABLED | bool else {} }}" NEXTCLOUD_HPB_TURN_ACTIVE_SERVER: "{{ NEXTCLOUD_HPB_TURN_ACTIVE_CONFIG.server | default('') }}" NEXTCLOUD_WHITEBOARD_SERVICE: "whiteboard" @@ -258,6 +252,18 @@ NEXTCLOUD_RECORDING_CONTAINER: "{{ lookup('config', application_id, 'services.' NEXTCLOUD_RECORDING_ENABLED: "{{ NEXTCLOUD_HPB_PLUGIN_ENABLED }}" NEXTCLOUD_RECORDING_PORT: "{{ lookup('config', application_id, 'services.talk_recording.ports.internal.recording') }}" NEXTCLOUD_RECORDING_SECRET: "{{ lookup('config', application_id, 'secrets.credentials.talk_recording_secret') }}" +NEXTCLOUD_RECORDING_REPOSITORY: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_RECORDING_SERVICE ~ '.repository') }}" +NEXTCLOUD_RECORDING_REF: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_RECORDING_SERVICE ~ '.ref') }}" +NEXTCLOUD_RECORDING_BASE_IMAGE: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_RECORDING_SERVICE ~ '.image') }}" +NEXTCLOUD_RECORDING_BASE_VERSION: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_RECORDING_SERVICE ~ '.version') }}" +NEXTCLOUD_RECORDING_TAG: "{{ NEXTCLOUD_RECORDING_REF }}-{{ NEXTCLOUD_RECORDING_BASE_VERSION }}" +NEXTCLOUD_RECORDING_BUILD_DIRECTORY: "{{ [ lookup('container', application_id, 'directories.services'), 'talk-recording' ] | path_join }}" +NEXTCLOUD_RECORDING_DOCKERFILE: "{{ [ NEXTCLOUD_RECORDING_BUILD_DIRECTORY, 'Dockerfile' ] | path_join }}" +NEXTCLOUD_RECORDING_USER_ID: 122 +NEXTCLOUD_RECORDING_CONFIG_HOST: "{{ [ lookup('container', application_id, 'directories.volumes'), 'recording.conf' ] | path_join }}" +NEXTCLOUD_RECORDING_CONFIG_TARGET: "{{ lookup('volume', application_id, 'talk_recording_conf').target }}" +NEXTCLOUD_RECORDING_DIRECTORY: "{{ lookup('volume', application_id, 'talk_recording_tmp').target }}" +NEXTCLOUD_RECORDING_CA_CERT: "{{ CA_TRUST.inject_cert_container if lookup('ca_injected', application_id) else '' }}" NEXTCLOUD_COLLABORA_URL: "{{ lookup('tls', 'web-svc-collabora', 'url.base') }}" diff --git a/roles/web-app-nextcloud/vars/system.yml b/roles/web-app-nextcloud/vars/system.yml index 30c44d4fdb..115d56b624 100644 --- a/roles/web-app-nextcloud/vars/system.yml +++ b/roles/web-app-nextcloud/vars/system.yml @@ -28,7 +28,7 @@ nextcloud_system_config: - parameter: "trusted_proxies" type: "json" - value: "{{ NEXTCLOUD_TRUSTED_PROXIES }}" + value: "{{ NEXTCLOUD_TRUSTED_PROXIES | to_json }}" - parameter: "log_type" value: "errorlog" diff --git a/roles/web-app-pgadmin/meta/services.yml b/roles/web-app-pgadmin/meta/services.yml index a5a35bfaf0..4911da5f13 100644 --- a/roles/web-app-pgadmin/meta/services.yml +++ b/roles/web-app-pgadmin/meta/services.yml @@ -13,7 +13,7 @@ pgadmin: # nocheck: default-placement-manager embedded sqlite config db; node-local in swarm placement: manager image: dpage/pgadmin4 - version: "9.18" + version: "9.19" min_storage: 378MB name: pgadmin server_mode: false diff --git a/roles/web-app-phpldapadmin/meta/volumes.yml b/roles/web-app-phpldapadmin/meta/volumes.yml index df9e69ec7e..d5c7b46468 100644 --- a/roles/web-app-phpldapadmin/meta/volumes.yml +++ b/roles/web-app-phpldapadmin/meta/volumes.yml @@ -6,3 +6,11 @@ php_hardening: mounts: - service: phpldapadmin target: /usr/local/etc/php/conf.d/zz-infinito-hardening.ini + +php_memory_unlimited: + type: config + source: "{{ FILE_PHP_MEMORY_UNLIMITED_INI }}" + mode: "0444" + mounts: + - service: phpldapadmin + target: /usr/local/etc/php/conf.d/zz-infinito-memory-unlimited.ini diff --git a/roles/web-app-prometheus/meta/services.yml b/roles/web-app-prometheus/meta/services.yml index 507ea2a085..122dba2a27 100644 --- a/roles/web-app-prometheus/meta/services.yml +++ b/roles/web-app-prometheus/meta/services.yml @@ -91,7 +91,7 @@ alertmanager: flavor: wget path: -/healthy image: prom/alertmanager # nocheck: volumes-path-single-spot: the repository path of an image name, not a mount target - version: v0.34.1 + version: v0.34.2 name: prometheus-alertmanager cpus: "0.25" mem_reservation: 64m diff --git a/roles/web-app-shopware/meta/volumes.yml b/roles/web-app-shopware/meta/volumes.yml index 021a1a0809..44cfe23ed8 100644 --- a/roles/web-app-shopware/meta/volumes.yml +++ b/roles/web-app-shopware/meta/volumes.yml @@ -131,6 +131,14 @@ php_hardening: - service: web target: /usr/local/etc/php/conf.d/zz-infinito-hardening.ini +php_memory_unlimited: + type: config + source: "{{ FILE_PHP_MEMORY_UNLIMITED_INI }}" + mode: "0444" + mounts: + - service: web + target: /usr/local/etc/php/conf.d/zz-infinito-memory-unlimited.ini + php_fpm_hardening: type: config source: "{{ FILE_PHP_FPM_HARDENING_CONF }}" diff --git a/roles/web-app-shopware/tasks/02_manager_ops.yml b/roles/web-app-shopware/tasks/02_manager_ops.yml index 106ed8596c..3e94169ba1 100644 --- a/roles/web-app-shopware/tasks/02_manager_ops.yml +++ b/roles/web-app-shopware/tasks/02_manager_ops.yml @@ -37,13 +37,6 @@ - name: "🚿 Flush compose handlers" meta: flush_handlers -- name: ⏳ Wait for Shopware HTTP endpoint - wait_for: - host: "{{ DOCKER_REACH_HOST }}" - port: "{{ lookup('config', application_id, 'services.shopware.ports.local.http') }}" - delay: 5 - timeout: "{{ lookup('timeout', 300) | int }}" - - name: "πŸ” Resolve Shopware web hosting node + container id" ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" vars: @@ -53,6 +46,18 @@ resolve_converge_retries: 120 resolve_converge_delay: 5 +- name: ⏳ Wait for Shopware HTTP endpoint + ansible.builtin.shell: >- # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container exec {{ SHOPWARE_WEB_LOCAL_CID | quote }} + sh -c 'timeout "$2" wget -q --spider "$1/robots.txt" || timeout "$2" wget -q --spider "$1/"' + _ {{ SHOPWARE_API_BASE | quote }} {{ lookup('timeout', 10) | int }} + delegate_to: "{{ SHOPWARE_WEB_HOST_NODE }}" + register: shopware_http_ready + changed_when: false + retries: "{{ ((lookup('timeout', 300) | int) / 5) | round(0, 'ceil') | int }}" + delay: 5 + until: shopware_http_ready.rc == 0 + - name: "βœ… Ensure admin user exists with correct password" ansible.builtin.include_tasks: file: 01_admin.yml diff --git a/roles/web-app-socialhome/meta/services.yml b/roles/web-app-socialhome/meta/services.yml index 72364dcaa1..0f036073df 100644 --- a/roles/web-app-socialhome/meta/services.yml +++ b/roles/web-app-socialhome/meta/services.yml @@ -16,7 +16,7 @@ socialhome: placement: manager name: socialhome image: ghcr.io/social-home-io/socialhome - version: "2026.10.27" + version: "2026.10.29" ports: local: http: 8089 diff --git a/roles/web-app-wazuh/meta/services.yml b/roles/web-app-wazuh/meta/services.yml index 77adf3f5f4..94f2c6d85b 100644 --- a/roles/web-app-wazuh/meta/services.yml +++ b/roles/web-app-wazuh/meta/services.yml @@ -67,7 +67,7 @@ wazuh: lifecycle: beta certs_generator: image: wazuh/wazuh-certs-generator - version: "0.0.4" + version: "0.0.5" name: wazuh-certs-generator cpus: "0.2" mem_reservation: 64m diff --git a/scripts/git/assert/main_merged.sh b/scripts/git/assert/main_merged.sh index bb63e43b46..ac7471884d 100755 --- a/scripts/git/assert/main_merged.sh +++ b/scripts/git/assert/main_merged.sh @@ -4,23 +4,37 @@ # from the current tip, so a branch can never be pushed while it lags main. # # Env overrides: INFINITO_MAIN_REMOTE (default origin), INFINITO_MAIN_BRANCH -# (default main). +# (default main), INFINITO_MAIN_COMMIT (unset: check the live branch tip; set: +# fetch and check this full commit SHA of that branch instead, e.g. the base +# SHA a CI event carries). set -euo pipefail remote="${INFINITO_MAIN_REMOTE:-origin}" # nocheck: git maintainer tooling knob, not a deployment env key branch="${INFINITO_MAIN_BRANCH:-main}" # nocheck: git maintainer tooling knob, not a deployment env key +if [[ -v INFINITO_MAIN_COMMIT ]]; then + target="${INFINITO_MAIN_COMMIT}" # nocheck: git maintainer tooling knob, not a deployment env key + if [[ ! "$target" =~ ^[0-9a-f]{40}([0-9a-f]{24})?$ ]]; then + echo "❌ assert-main-merged: INFINITO_MAIN_COMMIT must be a full commit SHA, got '${target}'." >&2 + exit 2 + fi + label="${remote}/${branch}@${target}" +else + target="$branch" + label="${remote}/${branch}" +fi + cd "$(git rev-parse --show-toplevel)" -echo "assert-main-merged: fetching ${remote}/${branch} ..." >&2 -git fetch --quiet "$remote" "$branch" +echo "assert-main-merged: fetching ${label} ..." >&2 +git fetch --quiet "$remote" "$target" if git merge-base --is-ancestor FETCH_HEAD HEAD; then - echo "βœ… assert-main-merged: ${remote}/${branch} is fully merged into HEAD." >&2 + echo "βœ… assert-main-merged: ${label} is fully merged into HEAD." >&2 exit 0 fi behind="$(git rev-list --count HEAD..FETCH_HEAD)" -echo "❌ assert-main-merged: ${remote}/${branch} has ${behind} commit(s) not merged into HEAD." >&2 +echo "❌ assert-main-merged: ${label} has ${behind} commit(s) not merged into HEAD." >&2 echo " Merge upstream main first, e.g.: git pull ${remote} ${branch}" >&2 exit 1 diff --git a/tests/integration/ansible/lookups/test_proxy_hops.py b/tests/integration/ansible/lookups/test_proxy_hops.py new file mode 100644 index 0000000000..71a4b14a75 --- /dev/null +++ b/tests/integration/ansible/lookups/test_proxy_hops.py @@ -0,0 +1,109 @@ +"""Integration test: proxy_hops for web-app-nextcloud against the real role tree.""" + +from __future__ import annotations + +import unittest + +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar + +from plugins.lookup.applications import ( + LookupModule as ApplicationsLookup, +) +from plugins.lookup.applications import ( + _reset_cache_for_tests, +) +from plugins.lookup.proxy_hops import LookupModule as ProxyHopsLookup +from utils.cache.yaml import load_yaml +from utils.networks.address import subnet_gateway +from utils.networks.proxy import REVERSE_PROXY_APPLICATION_ID +from utils.roles.mapping import ROLE_FILE_META_NETWORKS + +from . import PROJECT_ROOT + +ROLES_DIR = PROJECT_ROOT / "roles" +APP = "web-app-nextcloud" +CENTRAL_DATABASE = "svc-db-mariadb" +DIRECTORY = "svc-db-openldap" +GROUP_NAMES = [APP, CENTRAL_DATABASE, DIRECTORY, REVERSE_PROXY_APPLICATION_ID] +PUBLIC_ADDRESSES = ["198.51.100.7", "2001:db8:1::2"] + + +def _subnet(role: str) -> str: + return load_yaml(str(ROLES_DIR / role / ROLE_FILE_META_NETWORKS))["local"]["subnet"] + + +def _variables(applications: dict, mode: str) -> dict: + return { + "applications": applications, + "users": {}, + "DOMAIN_PRIMARY": "infinito.test", + "SYSTEM_EMAIL_DOMAIN": "infinito.test", + "DIR_COMPOSITIONS": "/opt/compose/", + "group_names": list(GROUP_NAMES), + "DEPLOYMENT_MODE": mode, + "application_id": APP, + "networks": { + "internet": { + "ip4": PUBLIC_ADDRESSES[0], + "ip6": PUBLIC_ADDRESSES[1], + "dns": "", + } + }, + } + + +def _hops(applications: dict, mode: str) -> list[str]: + lookup = ProxyHopsLookup() + lookup._loader = DataLoader() + lookup._templar = Templar(loader=lookup._loader) + return lookup.run([APP], variables=_variables(applications, mode))[0] + + +class TestProxyHopsIntegration(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + _reset_cache_for_tests() + applications = ApplicationsLookup() + applications._templar = Templar(loader=DataLoader()) + merged = applications.run( + [], variables=_variables({}, "compose"), roles_dir=str(ROLES_DIR) + )[0] + cls.compose = _hops(merged, "compose") + cls.swarm = _hops(merged, "swarm") + + @classmethod + def tearDownClass(cls) -> None: + _reset_cache_for_tests() + + def test_compose_trusts_the_gateway_of_every_network_the_proxy_service_joins( + self, + ) -> None: + self.assertEqual( + sorted(self.compose), + sorted( + subnet_gateway(_subnet(role)) + for role in (APP, CENTRAL_DATABASE, DIRECTORY) + ), + "Openresty reaches the published port from the host, and Docker " + "forwards it from the gateway of whichever of these networks it " + "routes the container through; production saw the central " + "database's gateway.", + ) + + def test_swarm_trusts_the_openresty_overlay(self) -> None: + self.assertEqual(self.swarm, [_subnet(REVERSE_PROXY_APPLICATION_ID)]) + + def test_swarm_does_not_trust_overlays_openresty_is_not_on(self) -> None: + for role in (APP, CENTRAL_DATABASE, DIRECTORY): + with self.subTest(role=role): + self.assertNotIn(_subnet(role), self.swarm) + + def test_public_host_addresses_are_not_proxy_hops(self) -> None: + for mode, hops in (("compose", self.compose), ("swarm", self.swarm)): + with self.subTest(mode=mode): + self.assertFalse(set(PUBLIC_ADDRESSES) & set(hops)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/roles/meta/test_info.py b/tests/lint/ansible/roles/meta/test_info.py index 40db4ccffa..030b394673 100644 --- a/tests/lint/ansible/roles/meta/test_info.py +++ b/tests/lint/ansible/roles/meta/test_info.py @@ -6,13 +6,12 @@ with no upstream homepage or demo video to name; * file-root convention: the file's content IS the value of ``applications..info`` β€” there is NO wrapping ``info:`` key; - * allowed top-level keys: ``logo``, ``homepage``, ``video``, ``display``; + * allowed top-level keys: ``logo``, ``homepage``, ``video``; the licence of the deployed software lives in ``meta/license.yml``, which ``test_license_declared.py`` guards; * ``logo`` is a mapping with at least a string ``class:`` field; * ``homepage`` and ``video`` are non-empty strings; - * ``display`` is a bool; - * none of these four fields may reappear under + * none of these three fields may reappear under ``meta/main.yml.galaxy_info``. Caching: parsed YAML comes through the shared process-wide @@ -37,13 +36,11 @@ if TYPE_CHECKING: ROLES_DIR = PROJECT_ROOT / "roles" -_ALLOWED_INFO_KEYS: frozenset[str] = frozenset({"logo", "homepage", "video", "display"}) +_ALLOWED_INFO_KEYS: frozenset[str] = frozenset({"logo", "homepage", "video"}) _INFO_MEDIA_RULE = "info-media" -_FORBIDDEN_GALAXY_INFO_KEYS: frozenset[str] = frozenset( - {"logo", "homepage", "video", "display"} -) +_FORBIDDEN_GALAXY_INFO_KEYS: frozenset[str] = frozenset({"logo", "homepage", "video"}) def _meta_main_paths() -> list[Path]: @@ -107,9 +104,6 @@ def _validate_meta_info(path: Path) -> list[str]: if not isinstance(value, str) or not value.strip(): problems.append(f"`{str_field}` must be a non-empty string") - if "display" in parsed and not isinstance(parsed["display"], bool): - problems.append("`display` must be a bool (true/false)") - return problems @@ -155,7 +149,7 @@ class TestMetaInfoShape(unittest.TestCase): class TestMetaMainHasNoMigratedFields(unittest.TestCase): - """galaxy_info MUST NOT carry the four fields after.""" + """galaxy_info MUST NOT carry the three meta/info.yml fields.""" def test_no_forbidden_keys_in_galaxy_info(self) -> None: offenders: dict[Path, list[str]] = {} diff --git a/tests/unit/python/plugins/action/test_applications_carrier.py b/tests/unit/python/plugins/action/test_applications_carrier.py index 4e0c8d213e..95f8cc355b 100644 --- a/tests/unit/python/plugins/action/test_applications_carrier.py +++ b/tests/unit/python/plugins/action/test_applications_carrier.py @@ -4,7 +4,7 @@ from unittest.mock import patch from ansible.errors import AnsibleActionFail from plugins.action.applications_carrier import ActionModule -from utils.cache.carrier import APPLICATIONS_RENDERED_FACT +from utils.cache.carrier import APPLICATIONS_RENDERED_FACT, USERS_RENDERED_FACT class _FakeTask: @@ -31,6 +31,16 @@ class _FakeLookup: return [self.carrier] +class _FakeLoader: + def __init__(self, applications, users): + self.lookups = {"applications": applications, "users": users} + self.order = [] + + def get(self, name, loader=None, templar=None): + self.order.append(name) + return self.lookups[name] + + def _make_action(task: _FakeTask, templar=None) -> ActionModule: action = object.__new__(ActionModule) action._task = task @@ -39,10 +49,19 @@ def _make_action(task: _FakeTask, templar=None) -> ActionModule: return action +def _lookups(templar=None): + applications = _FakeLookup( + {"key": ["roles", ["a", "b", "c", "d"]], "applications": {"x": {}}}, templar + ) + users = _FakeLookup( + {"key": ["roles", ["a", "b", "c", "d", "h"]], "users": {"u": {}}}, templar + ) + return applications, users, _FakeLoader(applications, users) + + class TestApplicationsCarrierActionPlugin(unittest.TestCase): - def test_parks_the_carrier_as_a_masked_fact(self): - carrier = {"key": ["roles", ["a", "b", "c", "d"]], "applications": {"x": {}}} - lookup = _FakeLookup(carrier) + def test_parks_both_carriers_as_masked_facts(self): + applications, users, loader = _lookups() action = _make_action(_FakeTask()) with ( patch( @@ -52,23 +71,78 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase): ), patch( "plugins.action.applications_carrier.lookup_loader.get", - return_value=lookup, + side_effect=loader.get, ), ): result = action.run(task_vars={"applications": {}}) - self.assertIs(result["ansible_facts"][APPLICATIONS_RENDERED_FACT], carrier) + self.assertIs( + result["ansible_facts"][APPLICATIONS_RENDERED_FACT], applications.carrier + ) + self.assertIs(result["ansible_facts"][USERS_RENDERED_FACT], users.carrier) self.assertTrue(result["_ansible_no_log"]) self.assertFalse(result["changed"]) - terms, variables, kwargs = lookup.calls[0] - self.assertEqual(terms, []) - self.assertEqual(variables, {"applications": {}}) - self.assertTrue(kwargs["carrier"]) + for lookup in (applications, users): + terms, variables, kwargs = lookup.calls[0] + self.assertEqual(terms, []) + self.assertEqual(variables, {"applications": {}}) + self.assertTrue(kwargs["carrier"]) + + def _park(self, task_vars): + applications, users, loader = _lookups() + action = _make_action(_FakeTask()) + with ( + patch( + "plugins.action.applications_carrier.ActionBase.run", + autospec=True, + return_value={}, + ), + patch( + "plugins.action.applications_carrier.lookup_loader.get", + side_effect=loader.get, + ), + patch("plugins.action.applications_carrier.revalidate_tokens_file"), + ): + return action.run(task_vars=task_vars), applications, users + + def test_a_users_carrier_that_still_matches_stays_in_place(self): + parked = {"key": ["roles", ["a", "b", "c", "d", "h"]], "users": {"u": {}}} + result, applications, _ = self._park({USERS_RENDERED_FACT: parked}) + + self.assertNotIn(USERS_RENDERED_FACT, result["ansible_facts"]) + self.assertIs( + result["ansible_facts"][APPLICATIONS_RENDERED_FACT], applications.carrier + ) + + def test_a_stale_users_carrier_is_replaced(self): + parked = {"key": ["roles", ["a", "b", "c", "d", "h2"]], "users": {"u": {}}} + result, _, users = self._park({USERS_RENDERED_FACT: parked}) + + self.assertIs(result["ansible_facts"][USERS_RENDERED_FACT], users.carrier) + + def test_renders_the_applications_before_the_users(self): + _, _, loader = _lookups() + action = _make_action(_FakeTask()) + with ( + patch( + "plugins.action.applications_carrier.ActionBase.run", + autospec=True, + return_value={}, + ), + patch( + "plugins.action.applications_carrier.lookup_loader.get", + side_effect=loader.get, + ), + patch("plugins.action.applications_carrier.revalidate_tokens_file"), + ): + action.run(task_vars={}) + + self.assertEqual(loader.order, ["applications", "users"]) def test_renders_without_the_callers_application_id(self): task_vars = {"applications": {}, "application_id": "web-app-bluesky"} templar = _FakeTemplar(task_vars) - lookup = _FakeLookup({"key": ["roles", []], "applications": {}}, templar) + applications, users, loader = _lookups(templar) action = _make_action(_FakeTask(), templar) with ( patch( @@ -78,22 +152,26 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase): ), patch( "plugins.action.applications_carrier.lookup_loader.get", - return_value=lookup, + side_effect=loader.get, ), patch("plugins.action.applications_carrier.revalidate_tokens_file"), ): action.run(task_vars=task_vars) - _, variables, _ = lookup.calls[0] - self.assertEqual(variables, {"applications": {}}) - self.assertEqual(lookup.templar_variables, [{"applications": {}}]) + for lookup in (applications, users): + _, variables, _ = lookup.calls[0] + self.assertEqual(variables, {"applications": {}}) + self.assertEqual(lookup.templar_variables, [{"applications": {}}]) self.assertIs(templar.available_variables, task_vars) self.assertEqual(task_vars["application_id"], "web-app-bluesky") def test_revalidates_the_tokens_file_before_rendering(self): order = [] - lookup = _FakeLookup({"key": ["roles", []], "applications": {}}) - lookup.run = lambda *args, **kwargs: order.append("render") or [{}] + applications, users, loader = _lookups() + applications.run = lambda *args, **kwargs: ( + order.append("applications") or [applications.carrier] + ) + users.run = lambda *args, **kwargs: order.append("users") or [users.carrier] action = _make_action(_FakeTask()) with ( patch( @@ -103,7 +181,7 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase): ), patch( "plugins.action.applications_carrier.lookup_loader.get", - return_value=lookup, + side_effect=loader.get, ), patch( "plugins.action.applications_carrier.revalidate_tokens_file", @@ -113,7 +191,8 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase): action.run(task_vars={"FILE_TOKENS": "/x/tokens.yml"}) self.assertEqual( - order, [("revalidate", {"FILE_TOKENS": "/x/tokens.yml"}), "render"] + order, + [("revalidate", {"FILE_TOKENS": "/x/tokens.yml"}), "applications", "users"], ) def test_clear_does_not_revalidate(self): @@ -144,8 +223,8 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase): ): action.run(task_vars={}) - def test_clear_drops_the_fact_without_rendering(self): - lookup = _FakeLookup({"key": ["roles", []], "applications": {}}) + def test_clear_drops_both_facts_without_rendering(self): + applications, users, loader = _lookups() action = _make_action(_FakeTask(args={"clear": True})) with ( patch( @@ -155,18 +234,21 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase): ), patch( "plugins.action.applications_carrier.lookup_loader.get", - return_value=lookup, + side_effect=loader.get, ), ): result = action.run(task_vars={"applications": {}}) - self.assertIsNone(result["ansible_facts"][APPLICATIONS_RENDERED_FACT]) + self.assertEqual( + result["ansible_facts"], + {APPLICATIONS_RENDERED_FACT: None, USERS_RENDERED_FACT: None}, + ) self.assertFalse(result["changed"]) - self.assertEqual(lookup.calls, []) + self.assertEqual(applications.calls, []) + self.assertEqual(users.calls, []) def test_clear_false_still_renders(self): - carrier = {"key": ["roles", ["a", "b", "c", "d"]], "applications": {"x": {}}} - lookup = _FakeLookup(carrier) + applications, users, loader = _lookups() action = _make_action(_FakeTask(args={"clear": "no"})) with ( patch( @@ -176,13 +258,17 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase): ), patch( "plugins.action.applications_carrier.lookup_loader.get", - return_value=lookup, + side_effect=loader.get, ), ): result = action.run(task_vars={"applications": {}}) - self.assertIs(result["ansible_facts"][APPLICATIONS_RENDERED_FACT], carrier) - self.assertEqual(len(lookup.calls), 1) + self.assertIs( + result["ansible_facts"][APPLICATIONS_RENDERED_FACT], applications.carrier + ) + self.assertIs(result["ansible_facts"][USERS_RENDERED_FACT], users.carrier) + self.assertEqual(len(applications.calls), 1) + self.assertEqual(len(users.calls), 1) if __name__ == "__main__": diff --git a/tests/unit/python/plugins/filter/test_csp_filters/test_toggles_desktop_logout.py b/tests/unit/python/plugins/filter/test_csp_filters/test_toggles_desktop_logout.py index 87563c8582..7d3ed0923d 100644 --- a/tests/unit/python/plugins/filter/test_csp_filters/test_toggles_desktop_logout.py +++ b/tests/unit/python/plugins/filter/test_csp_filters/test_toggles_desktop_logout.py @@ -89,6 +89,47 @@ class TestCspTogglesDashboardLogout(unittest.TestCase): self.assertIn("'unsafe-inline'", attr) self.assertIn("'unsafe-inline'", elem) + def test_logout_respects_explicit_disable_on_elem_directive(self): + apps = copy.deepcopy(self.apps) + apps["app1"]["csp"]["flags"]["script-src-elem"] = {"unsafe-inline": False} + self._set_service_enabled(apps, "logout", True) + + header = self.filter.build_csp_header( + apps, + "app1", + self.domains, + "https", + extra_hashes={"script-src-elem": ["console.log('logout');"]}, + ) + elem = self._get_directive_tokens(header, "script-src-elem") + attr = self._get_directive_tokens(header, "script-src-attr") + expected_hash = self.filter.get_csp_hash("console.log('logout');") + + self.assertNotIn("'unsafe-inline'", elem) + self.assertIn(expected_hash, elem) + self.assertIn("'unsafe-inline'", attr) + + def test_logout_respects_explicit_disable_on_whole_script_family(self): + apps = copy.deepcopy(self.apps) + for directive in ("script-src", "script-src-elem", "script-src-attr"): + apps["app1"]["csp"]["flags"][directive] = {"unsafe-inline": False} + self._set_service_enabled(apps, "logout", True) + + header = self.filter.build_csp_header( + apps, + "app1", + self.domains, + "https", + extra_hashes={"script-src-elem": ["console.log('logout');"]}, + ) + expected_hash = self.filter.get_csp_hash("console.log('logout');") + + for directive in ("script-src", "script-src-elem", "script-src-attr"): + self.assertNotIn( + "'unsafe-inline'", self._get_directive_tokens(header, directive) + ) + self.assertIn(expected_hash, self._get_directive_tokens(header, "script-src")) + def test_logout_propagates_to_base_when_not_explicitly_disabled(self): apps = copy.deepcopy(self.apps) apps["app1"].setdefault("csp", {}).setdefault("flags", {}) diff --git a/tests/unit/python/plugins/filter/test_security_headers.py b/tests/unit/python/plugins/filter/test_security_headers.py new file mode 100644 index 0000000000..797f9e5f88 --- /dev/null +++ b/tests/unit/python/plugins/filter/test_security_headers.py @@ -0,0 +1,153 @@ +import copy +import unittest + +from plugins.filter.security_headers import FilterModule +from utils.cache.yaml import load_yaml +from utils.roles.applications.security_headers import security_headers + +from . import PROJECT_ROOT + +PLATFORM = { + "nosniff": False, + "referrer_policy": "", + "permissions_policy": "", + "hsts": {"max_age": 31536000, "include_subdomains": False, "preload": False}, +} + + +def apps_with(override): + """Return an applications map whose one app declares *override*. + + Args: + override: the app's ``server.security_headers`` block. + """ + return {"web-app-x": {"server": {"security_headers": override}}} + + +class TestPlatformValues(unittest.TestCase): + def test_an_app_without_a_block_gets_the_platform_values(self): + apps = {"web-app-plain": {"server": {"status_codes": {"default": [200]}}}} + self.assertEqual( + security_headers(apps, "web-app-plain", PLATFORM), + { + "nosniff": False, + "referrer_policy": "", + "permissions_policy": "", + "hsts": "max-age=31536000", + }, + ) + + def test_a_redirect_vhost_passes_its_domain_and_gets_the_platform_values(self): + result = security_headers(apps_with({"nosniff": True}), "old.example", PLATFORM) + self.assertFalse(result["nosniff"]) + self.assertEqual(result["hsts"], "max-age=31536000") + + def test_the_repository_platform_values_are_valid(self): + platform = load_yaml(PROJECT_ROOT / "group_vars/all/04_webserver.yml")[ + "WEBSERVER_SECURITY_HEADERS" + ] + self.assertEqual( + security_headers({}, "web-app-plain", platform)["hsts"], + "max-age=31536000", + ) + + def test_an_incomplete_platform_block_fails(self): + platform = copy.deepcopy(PLATFORM) + del platform["hsts"]["preload"] + with self.assertRaisesRegex(ValueError, "preload"): + security_headers({}, "web-app-plain", platform) + + def test_the_platform_block_is_not_mutated(self): + platform = copy.deepcopy(PLATFORM) + security_headers( + apps_with({"hsts": {"include_subdomains": True}}), "web-app-x", platform + ) + self.assertEqual(platform, PLATFORM) + + +class TestOverrides(unittest.TestCase): + def test_an_override_replaces_only_its_own_keys(self): + result = security_headers( + apps_with({"nosniff": True, "hsts": {"include_subdomains": True}}), + "web-app-x", + PLATFORM, + ) + self.assertTrue(result["nosniff"]) + self.assertEqual(result["referrer_policy"], "") + self.assertEqual(result["hsts"], "max-age=31536000; includeSubDomains") + + def test_preload_follows_include_subdomains(self): + result = security_headers( + apps_with({"hsts": {"include_subdomains": True, "preload": True}}), + "web-app-x", + PLATFORM, + ) + self.assertEqual(result["hsts"], "max-age=31536000; includeSubDomains; preload") + + def test_a_referrer_policy_list_is_accepted(self): + value = "no-referrer, strict-origin-when-cross-origin" + result = security_headers( + apps_with({"referrer_policy": value}), "web-app-x", PLATFORM + ) + self.assertEqual(result["referrer_policy"], value) + + def test_a_permissions_policy_keeps_its_quoted_origins(self): + value = 'camera=(self "https://meet.example.org"), microphone=(self)' + result = security_headers( + apps_with({"permissions_policy": value}), "web-app-x", PLATFORM + ) + self.assertEqual(result["permissions_policy"], value) + + +class TestRejections(unittest.TestCase): + def assert_rejected(self, override, pattern, error=ValueError): + with self.assertRaisesRegex(error, pattern): + security_headers(apps_with(override), "web-app-x", PLATFORM) + + def test_an_unknown_key_fails(self): + self.assert_rejected({"nosnif": True}, "unknown keys") + + def test_an_unknown_hsts_key_fails(self): + self.assert_rejected({"hsts": {"subdomains": True}}, "unknown keys") + + def test_a_non_mapping_block_fails(self): + self.assert_rejected(None, "must be a mapping", TypeError) + + def test_a_string_flag_fails(self): + self.assert_rejected({"nosniff": "yes"}, "must be bool", TypeError) + + def test_a_boolean_max_age_fails(self): + self.assert_rejected({"hsts": {"max_age": True}}, "must be int", TypeError) + + def test_a_negative_max_age_fails(self): + self.assert_rejected({"hsts": {"max_age": -1}}, "negative") + + def test_preload_without_include_subdomains_fails(self): + self.assert_rejected({"hsts": {"preload": True}}, "requires include_subdomains") + + def test_preload_with_a_short_max_age_fails(self): + self.assert_rejected( + {"hsts": {"max_age": 86400, "include_subdomains": True, "preload": True}}, + "at least 31536000", + ) + + def test_an_unknown_referrer_policy_token_fails(self): + self.assert_rejected( + {"referrer_policy": "strict-origin-when-cross-orgin"}, + "unknown policy tokens", + ) + + def test_a_line_break_in_a_header_value_fails(self): + self.assert_rejected( + {"permissions_policy": "camera=()\r\nSet-Cookie: x=1"}, + "printable ASCII", + ) + + +class TestFilterModule(unittest.TestCase): + def test_filter_is_registered(self): + self.assertIs(FilterModule().filters()["security_headers"], security_headers) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_docker_cards.py b/tests/unit/python/plugins/lookup/test_docker_cards.py index 5a981df409..f6620d8695 100644 --- a/tests/unit/python/plugins/lookup/test_docker_cards.py +++ b/tests/unit/python/plugins/lookup/test_docker_cards.py @@ -359,6 +359,94 @@ logo: with self.assertRaisesRegex(AnsibleError, "nope"): self._run_lookup(LookupModule(), fake_variables) + def _add_role(self, role_name, application_id, info_yaml): + role_dir = Path(self.test_roles_dir) / role_name + (role_dir / "meta").mkdir(parents=True) + (role_dir / "vars").mkdir(parents=True) + (role_dir / ROLE_FILE_VARS_MAIN).write_text( + f"application_id: {application_id}\n", encoding="utf-8" + ) + (role_dir / "README.md").write_text(f"# {role_name}\n", encoding="utf-8") + (role_dir / ROLE_FILE_META_MAIN).write_text( + 'galaxy_info:\n description: "Second role."\n', encoding="utf-8" + ) + (role_dir / ROLE_FILE_META_INFO).write_text(info_yaml, encoding="utf-8") + + def _two_role_variables(self): + self._add_role("web-app-other", "other", "logo:\n class: fa-solid fa-cube\n") + fake_variables = self._base_fake_variables() + fake_variables["domains"]["other"] = "other.example.com" + fake_variables["applications"]["other"] = { + "services": {"dashboard": {"enabled": True}} + } + fake_variables["group_names"] = ["portfolio", "other"] + return fake_variables + + def test_enabled_false_skips_the_card(self): + fake_variables = self._base_fake_variables() + fake_variables["applications"]["portfolio"]["services"]["dashboard"][ + "enabled" + ] = False + + result = self._run_lookup(LookupModule(), fake_variables) + + self.assertEqual(result, [[]]) + + def test_a_role_without_a_dashboard_binding_shows_the_card(self): + fake_variables = self._base_fake_variables() + fake_variables["applications"]["portfolio"]["services"] = {} + + result = self._run_lookup(LookupModule(), fake_variables) + + self.assertEqual([c["title"] for c in result[0]], ["Portfolio Application"]) + + def test_enabled_true_shows_the_card(self): + fake_variables = self._base_fake_variables() + + result = self._run_lookup(LookupModule(), fake_variables) + + self.assertEqual([c["title"] for c in result[0]], ["Portfolio Application"]) + + def test_enabled_false_hides_only_its_own_card(self): + fake_variables = self._two_role_variables() + fake_variables["applications"]["other"]["services"]["dashboard"]["enabled"] = ( + False + ) + + result = self._run_lookup(LookupModule(), fake_variables) + + self.assertEqual([c["title"] for c in result[0]], ["Portfolio Application"]) + + def test_both_cards_render_when_both_are_enabled(self): + fake_variables = self._two_role_variables() + + result = self._run_lookup(LookupModule(), fake_variables) + + self.assertEqual( + [c["title"] for c in result[0]], + ["Portfolio Application", "web-app-other"], + ) + + def test_info_display_false_no_longer_hides_the_card(self): + meta_info_path = Path(self.role_dir) / ROLE_FILE_META_INFO + meta_info_path.write_text( + "logo:\n class: fa-solid fa-briefcase\ndisplay: false\n", + encoding="utf-8", + ) + + result = self._run_lookup(LookupModule(), self._base_fake_variables()) + + self.assertEqual([c["title"] for c in result[0]], ["Portfolio Application"]) + + def test_non_boolean_enabled_fails_loudly(self): + fake_variables = self._base_fake_variables() + fake_variables["applications"]["portfolio"]["services"]["dashboard"][ + "enabled" + ] = "maybe" + + with self.assertRaisesRegex(AnsibleError, "portfolio"): + self._run_lookup(LookupModule(), fake_variables) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_proxy_hops.py b/tests/unit/python/plugins/lookup/test_proxy_hops.py new file mode 100644 index 0000000000..1027e0cba1 --- /dev/null +++ b/tests/unit/python/plugins/lookup/test_proxy_hops.py @@ -0,0 +1,101 @@ +"""Unit tests for plugins/lookup/proxy_hops.py.""" + +from __future__ import annotations + +import unittest +import unittest.mock as mock + +from ansible.errors import AnsibleError + +from plugins.lookup.proxy_hops import LookupModule + +_SUBNETS = { + "web-app-nextcloud": "192.168.41.0/24", + "svc-db-mariadb": "192.168.201.0/24", + "svc-prx-openresty": "192.168.107.0/24", +} + + +class _Templar: + def __init__(self, vars_=None): + self.available_variables = vars_ or {} + + def template(self, value, **_): + return value + + +def _make_lookup(vars_): + lm = LookupModule() + lm._templar = _Templar(vars_) + lm._loader = mock.MagicMock() + return lm + + +def _role_subnets(): + return mock.MagicMock( + run=lambda terms, **_: [[_SUBNETS[role] for role in terms[0]]] + ) + + +def _joined(application_id, deployment_mode, **_): + if application_id == "svc-prx-openresty": + return ["svc-prx-openresty"] if deployment_mode == "swarm" else [] + if deployment_mode == "swarm": + return ["svc-db-mariadb", "svc-prx-openresty", application_id] + return ["svc-db-mariadb", application_id] + + +def _run(mode, terms=("web-app-nextcloud",), joined=_joined): + vars_ = {"application_id": "web-app-nextcloud", "DEPLOYMENT_MODE": mode} + lm = _make_lookup(vars_) + with ( + mock.patch( + "utils.networks.lookup_context.build_service_registry_from_applications", + return_value={}, + ), + mock.patch("utils.networks.lookup_context.lookup_loader") as context_loader, + mock.patch("plugins.lookup.proxy_hops.lookup_loader") as plugin_loader, + mock.patch( + "plugins.lookup.proxy_hops.compute_external_network_roles", + side_effect=lambda **kwargs: joined( + kwargs["application_id"], kwargs["deployment_mode"] + ), + ) as roles_mock, + ): + context_loader.get.return_value = mock.MagicMock(run=lambda *_a, **_k: [""]) + plugin_loader.get.return_value = _role_subnets() + result = lm.run(list(terms), variables=vars_) + return result, roles_mock + + +class TestProxyHopsLookup(unittest.TestCase): + def test_raises_without_application_id_term(self): + lm = _make_lookup({"DEPLOYMENT_MODE": "compose"}) + with self.assertRaises(AnsibleError): + lm.run([], variables={}) + + def test_raises_on_extra_terms(self): + lm = _make_lookup({"DEPLOYMENT_MODE": "compose"}) + with self.assertRaises(AnsibleError): + lm.run(["web-app-nextcloud", "extra"], variables={}) + + def test_compose_returns_gateways_of_the_joined_networks(self): + result, _ = _run("compose") + self.assertEqual(result, [["192.168.41.1", "192.168.201.1"]]) + + def test_swarm_returns_the_overlay_shared_with_openresty(self): + result, roles_mock = _run("swarm") + self.assertEqual(result, [["192.168.107.0/24"]]) + asked = {call.kwargs["application_id"] for call in roles_mock.call_args_list} + self.assertEqual(asked, {"web-app-nextcloud", "svc-prx-openresty"}) + + def test_missing_shared_overlay_surfaces_as_ansible_error(self): + def isolated(application_id, deployment_mode): + return [application_id] + + with self.assertRaises(AnsibleError): + _run("swarm", joined=isolated) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_users.py b/tests/unit/python/plugins/lookup/test_users.py index 8e051fa630..56528c37a4 100644 --- a/tests/unit/python/plugins/lookup/test_users.py +++ b/tests/unit/python/plugins/lookup/test_users.py @@ -10,6 +10,7 @@ from ansible.errors import AnsibleError from plugins.lookup.users import LookupModule, _reset_cache_for_tests from utils.cache import base as runtime_data_base +from utils.cache.carrier import USERS_RENDERED_FACT, merged_users_cache_key from utils.cache.yaml import dump_yaml_str from utils.domains.default_primary import default_domain_primary from utils.paths import FILE_TOKENS @@ -305,6 +306,46 @@ class TestUsersLookup(unittest.TestCase): self.assertEqual(result["tokens"]["web-app-mailu"], "token-from-default-path") + def test_carrier_returns_the_users_with_the_key_they_are_valid_under( + self, + ) -> None: + roles = str(self._tmp / "roles") + variables = {"inventory_hostname": "h1"} + result = self.lookup.run( + [], variables=variables, roles_dir=roles, carrier=True + )[0] + key = merged_users_cache_key(variables, roles_dir=roles) + self.assertEqual(result["key"], [key[0], list(key[1])]) + self.assertEqual( + result["users"], + self.lookup.run([], variables=variables, roles_dir=roles)[0], + ) + + def test_carrier_takes_no_terms(self) -> None: + with self.assertRaises(AnsibleError): + self.lookup.run( + ["alice"], + variables={}, + roles_dir=str(self._tmp / "roles"), + carrier=True, + ) + + def test_a_parked_carrier_answers_a_fresh_worker_without_rendering(self) -> None: + roles = str(self._tmp / "roles") + self.lookup._templar = _DummyTemplar({"SYSTEM_EMAIL_DOMAIN": "example.org"}) + variables = {"inventory_hostname": "h1", "SYSTEM_EMAIL_DOMAIN": "example.org"} + parked = self.lookup.run( + [], variables=variables, roles_dir=roles, carrier=True + )[0] + _reset_cache_for_tests() + variables[USERS_RENDERED_FACT] = parked + with patch( + "utils.cache.users._render_with_templar", + side_effect=AssertionError("rendered"), + ): + result = self.lookup.run(["alice"], variables=variables, roles_dir=roles)[0] + self.assertIs(result, parked["users"]["alice"]) + class _DummyTemplar: def __init__(self, variables: dict[str, str]) -> None: diff --git a/tests/unit/python/roles/sys-front-tls/__init__.py b/tests/unit/python/roles/sys-front-tls/__init__.py new file mode 100644 index 0000000000..8ee16d7567 --- /dev/null +++ b/tests/unit/python/roles/sys-front-tls/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] diff --git a/tests/unit/python/roles/sys-front-tls/templates/__init__.py b/tests/unit/python/roles/sys-front-tls/templates/__init__.py new file mode 100644 index 0000000000..087c384b57 --- /dev/null +++ b/tests/unit/python/roles/sys-front-tls/templates/__init__.py @@ -0,0 +1,5 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/sys-front-tls/templates/test_nginx_ssl_header.py b/tests/unit/python/roles/sys-front-tls/templates/test_nginx_ssl_header.py new file mode 100644 index 0000000000..cb4fdba067 --- /dev/null +++ b/tests/unit/python/roles/sys-front-tls/templates/test_nginx_ssl_header.py @@ -0,0 +1,106 @@ +from __future__ import annotations + +import re +import unittest + +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape + +from plugins.filter.security_headers import FilterModule +from utils.tls_common import resolve_enabled + +from . import PROJECT_ROOT + +TEMPLATE = "roles/sys-front-tls/templates/nginx_ssl_header.j2" + +PLATFORM = { + "nosniff": False, + "referrer_policy": "", + "permissions_policy": "", + "hsts": {"max_age": 31536000, "include_subdomains": False, "preload": False}, +} + +PRIMARY_DOMAINS = { + "web-app-x": "x.example.org", + "web-app-onion": "x.abcdefghijklmnop.onion", + "old.example.org": "old.example.org", +} + + +def render(application_id: str, override: dict) -> str: + """Return the TLS server header of one vhost. + + Args: + application_id: the app the vhost belongs to, or a redirect domain. + override: the app's ``server.security_headers`` block. + """ + applications = { + app: {"server": {"security_headers": override}} + for app in ("web-app-x", "web-app-onion") + } + apps_by_domain = {domain: app for app, domain in PRIMARY_DOMAINS.items()} + + def lookup(kind, *args, **_kw): + if kind == "applications": + return applications + if kind == "tls": + term, want = args + app = apps_by_domain.get(term, term) + enabled = resolve_enabled( + applications.get(app, {}), True, primary_domain=PRIMARY_DOMAINS[app] + ) + return {"enabled": enabled, "ports.web": 443 if enabled else 80}[want] + if kind == "cert": + return f"/etc/certs/{args[0]}/{args[1]}" + raise AssertionError(f"unexpected lookup {kind!r}") + + env = Environment( + loader=FileSystemLoader(str(PROJECT_ROOT)), + undefined=StrictUndefined, + autoescape=select_autoescape(), + ) + env.filters.update(FilterModule().filters()) + env.filters["bool"] = bool + return env.get_template(TEMPLATE).render( + application_id=application_id, + domain=PRIMARY_DOMAINS[application_id], + lookup=lookup, + WEBSERVER_SECURITY_HEADERS=PLATFORM, + ) + + +def hsts(rendered: str) -> list[str]: + """Return every Strict-Transport-Security value the header adds. + + Args: + rendered: the rendered TLS server header. + """ + return re.findall( + r'^add_header Strict-Transport-Security "([^"]*)" always;$', + rendered, + re.MULTILINE, + ) + + +class TestHsts(unittest.TestCase): + def test_the_platform_value_is_one_year_without_subdomains(self): + self.assertEqual(hsts(render("web-app-x", {})), ["max-age=31536000"]) + + def test_include_subdomains_and_preload_are_opt_in_per_app(self): + rendered = render( + "web-app-x", {"hsts": {"include_subdomains": True, "preload": True}} + ) + self.assertEqual( + hsts(rendered), ["max-age=31536000; includeSubDomains; preload"] + ) + + def test_a_redirect_vhost_sends_the_platform_value(self): + self.assertEqual(hsts(render("old.example.org", {})), ["max-age=31536000"]) + + def test_an_onion_vhost_sends_no_hsts_even_when_opted_in(self): + rendered = render("web-app-onion", {"hsts": {"include_subdomains": True}}) + self.assertNotIn("Strict-Transport-Security", rendered) + self.assertNotIn("ssl", rendered) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/sys-svc-compose/files/test_pull.py b/tests/unit/python/roles/sys-svc-compose/files/test_pull.py index 15f500cc6c..c8f01b7aa4 100644 --- a/tests/unit/python/roles/sys-svc-compose/files/test_pull.py +++ b/tests/unit/python/roles/sys-svc-compose/files/test_pull.py @@ -7,6 +7,8 @@ from pathlib import Path from types import ModuleType from unittest.mock import patch +from utils.cache.yaml import load_yaml_any + from . import PROJECT_ROOT @@ -445,5 +447,23 @@ services: self.assertIn("missing locally", str(ctx.exception)) +class TestBuildHandlersSharePullCache(unittest.TestCase): + def test_build_handlers_build_with_pull_and_fall_back_like_pull_py(self) -> None: + handlers = { + handler["name"]: handler.get("ansible.builtin.shell", "") + for handler in load_yaml_any( + str(PROJECT_ROOT / "roles/sys-svc-compose/handlers/compose.yml") + ) + } + for name in ( + "πŸ”¨ Build compose", + "πŸ”¨ Build the services queued for a lone recreate", + ): + with self.subTest(handler=name): + self.assertRegex( + handlers[name], r"compose build --pull\b.*\|\| compose build\b" + ) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/roles/sys-svc-container/test_userland_proxy.py b/tests/unit/python/roles/sys-svc-container/test_userland_proxy.py new file mode 100644 index 0000000000..463c7bdbe9 --- /dev/null +++ b/tests/unit/python/roles/sys-svc-container/test_userland_proxy.py @@ -0,0 +1,61 @@ +import json +import unittest +from pathlib import Path +from types import SimpleNamespace + +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape + +from utils import PROJECT_ROOT + +TEMPLATES = Path(PROJECT_ROOT) / "roles" / "sys-svc-container" / "templates" + + +def _shim(exists): + return SimpleNamespace(stat=SimpleNamespace(exists=exists)) + + +def _daemon_json(**overrides): + env = Environment( + loader=FileSystemLoader(str(TEMPLATES)), + trim_blocks=True, + undefined=StrictUndefined, + autoescape=select_autoescape(), + ) + env.filters["bool"] = lambda value: value is True or str(value).lower() == "true" + env.filters["to_json"] = json.dumps + env.globals["lookup"] = lambda name, *_a, **_k: [] + variables = { + "DEPLOYMENT_MODE": "compose", + "IS_STACK_HOST": True, + "DOCKER_IN_CONTAINER": False, + "DOMAIN_PRIMARY": "infinito.test", + "KATA_SHIM_BINARY": "/usr/bin/containerd-shim-kata-v2", + "RUNSC_SHIM_BINARY": "/usr/local/bin/runsc", + "SANDBOX_RUNTIME": "runsc", + "SYS_SVC_CONTAINER_DATA_ROOT": "", + "swarm": {"registry": {"host": "", "port": 5000}}, + "groups": {"svc-registry-cache": []}, + "ansible_facts": {"os_family": "Debian"}, + "SYS_SVC_CONTAINER_DOCKER_FIREWALL_BACKEND_BY_OS_FAMILY": {"Debian": "iptables"}, + "NETWORK_DOCKER_ADDRESS_POOLS": [{"base": "10.208.0.0/12", "size": 24}], + "sys_svc_container_kvm": _shim(False), + "sys_svc_container_kata_shim": _shim(False), + "sys_svc_container_runsc_shim": _shim(False), + **overrides, + } + return json.loads(env.get_template("daemon.json.j2").render(variables)) + + +class TestUserlandProxy(unittest.TestCase): + def test_the_daemon_publishes_ports_without_the_userland_proxy(self): + self.assertIs(_daemon_json()["userland-proxy"], False) + + def test_swarm_and_docker_in_docker_keep_it_off(self): + parsed = _daemon_json( + DEPLOYMENT_MODE="swarm", IS_STACK_HOST=False, DOCKER_IN_CONTAINER=True + ) + self.assertIs(parsed["userland-proxy"], False) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/sys-svc-proxy/templates/test_security_headers_lua.py b/tests/unit/python/roles/sys-svc-proxy/templates/test_security_headers_lua.py new file mode 100644 index 0000000000..3baee51efc --- /dev/null +++ b/tests/unit/python/roles/sys-svc-proxy/templates/test_security_headers_lua.py @@ -0,0 +1,117 @@ +"""Exception: a location with its own ``add_header`` drops every server-level one, +so these headers live in the Lua header filter of ``content_security_policy.conf.j2``. +""" + +from __future__ import annotations + +import json +import re +import unittest + +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape + +from plugins.filter.security_headers import FilterModule +from utils.cache.files import read_text + +from . import PROJECT_ROOT + +SNIPPET = "roles/sys-svc-proxy/templates/headers/security_headers.lua.j2" +CSP_TEMPLATE = "roles/sys-svc-proxy/templates/headers/content_security_policy.conf.j2" + +PLATFORM = { + "nosniff": False, + "referrer_policy": "", + "permissions_policy": "", + "hsts": {"max_age": 31536000, "include_subdomains": False, "preload": False}, +} + + +def render(override: dict) -> str: + """Return the Lua snippet for an app declaring *override*. + + Args: + override: the app's ``server.security_headers`` block. + """ + applications = {"web-app-x": {"server": {"security_headers": override}}} + + def lookup(kind, *_args, **_kw): + if kind == "applications": + return applications + raise AssertionError(f"unexpected lookup {kind!r}") + + env = Environment( + loader=FileSystemLoader(str(PROJECT_ROOT)), + undefined=StrictUndefined, + autoescape=select_autoescape(), + ) + env.filters.update(FilterModule().filters()) + env.filters["to_json"] = json.dumps + return env.get_template(SNIPPET).render( + application_id="web-app-x", + lookup=lookup, + WEBSERVER_SECURITY_HEADERS=PLATFORM, + ) + + +def assignment(rendered: str, header: str) -> str: + """Return the Lua literal assigned to *header*, or an empty string. + + Args: + rendered: the rendered snippet. + header: the response header name. + """ + match = re.search( + rf'ngx\.header\["{re.escape(header)}"\] = (".*")$', rendered, re.MULTILINE + ) + return match.group(1) if match else "" + + +class TestSecurityHeadersSnippet(unittest.TestCase): + def test_the_platform_values_send_nothing(self): + self.assertNotIn("ngx.header", render({})) + + def test_nosniff_is_sent_when_opted_in(self): + rendered = render({"nosniff": True}) + self.assertEqual( + json.loads(assignment(rendered, "X-Content-Type-Options")), "nosniff" + ) + + def test_the_referrer_policy_never_replaces_the_upstream_one(self): + rendered = render({"referrer_policy": "strict-origin-when-cross-origin"}) + self.assertRegex( + rendered, + r'if not ngx\.header\["Referrer-Policy"\] then\s+' + r'ngx\.header\["Referrer-Policy"\] = "strict-origin-when-cross-origin"\s+end', + ) + + def test_the_permissions_policy_is_sent_on_documents_only(self): + rendered = render({"permissions_policy": "camera=(self)"}) + self.assertRegex( + rendered, + r'if is_html then\s+ngx\.header\["Permissions-Policy"\] = "camera=\(self\)"\s+end', + ) + + def test_quoted_origins_stay_one_lua_string(self): + value = 'camera=(self "https://meet.example.org"), microphone=(self)' + rendered = render({"permissions_policy": value}) + self.assertEqual(json.loads(assignment(rendered, "Permissions-Policy")), value) + + def test_hsts_is_left_to_the_server_level_header(self): + rendered = render({"hsts": {"include_subdomains": True}}) + self.assertNotIn("Strict-Transport-Security", rendered) + + +class TestSnippetPlacement(unittest.TestCase): + def test_the_snippet_runs_inside_the_csp_header_filter_after_is_html(self): + text = read_text(str(PROJECT_ROOT / CSP_TEMPLATE)) + block = text.index("header_filter_by_lua_block {") + is_html = text.index("local is_html") + include = text.index(f"{{% include '{SNIPPET}' %}}") + block_end = text.index("\n}\n", block) + self.assertLess(block, is_html) + self.assertLess(is_html, include) + self.assertLess(include, block_end) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/sys-token-store/test_write_many.py b/tests/unit/python/roles/sys-token-store/test_write_many.py index 2cfc570883..442d482b27 100644 --- a/tests/unit/python/roles/sys-token-store/test_write_many.py +++ b/tests/unit/python/roles/sys-token-store/test_write_many.py @@ -15,7 +15,7 @@ EMPTY = "πŸ›‘ Abort if a token is empty (do not persist empties)" PERSIST = "πŸ’Ύ Persist store (idempotent, single-writer via STACK_HOST)" MIRROR = "πŸͺž Mirror the store onto the controller, where every users lookup reads" HAND_OVER = "πŸ”„ Hand the written store to the lookups of the rest of the play" -RERENDER = "🧊 Re-render the applications SPOT the new tokens invalidated" +RERENDER = "🧊 Re-render the users SPOT the new tokens invalidated" USERS = { "alice": {"tokens": {"web-app-a": "old-a"}, "note": "kept"}, diff --git a/tests/unit/python/roles/web-app-fider/__init__.py b/tests/unit/python/roles/web-app-fider/__init__.py new file mode 100644 index 0000000000..8ee16d7567 --- /dev/null +++ b/tests/unit/python/roles/web-app-fider/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] diff --git a/tests/unit/python/roles/web-app-fider/test_tenant_bootstrap_gate.py b/tests/unit/python/roles/web-app-fider/test_tenant_bootstrap_gate.py new file mode 100644 index 0000000000..6f2688eddc --- /dev/null +++ b/tests/unit/python/roles/web-app-fider/test_tenant_bootstrap_gate.py @@ -0,0 +1,103 @@ +import unittest + +from jinja2 import Environment + +from utils.cache.yaml import load_yaml_any + +from . import PROJECT_ROOT + +TASKS = PROJECT_ROOT / "roles" / "web-app-fider" / "tasks" +MODES = ("compose", "swarm") + +_TRUTHY = frozenset({"1", "true", "yes", "y", "on"}) + + +def _to_bool(value): + if isinstance(value, bool): + return value + return str(value).strip().lower() in _TRUTHY + + +def _guard_holds(task, context) -> bool: + when = task.get("when", []) + guards = when if isinstance(when, list) else [when] + env = Environment(autoescape=True) + env.filters["bool"] = _to_bool + return all(bool(env.compile_expression(expr)(**context)) for expr in guards) + + +def _run_tasks(*, sso: bool, stack_host: bool, mode: str, tenants: int) -> list: + context = { + "FIDER_OIDC_ENABLED": sso, + "FIDER_MCP_ENABLED": False, + "IS_STACK_HOST": stack_host, + "DEPLOYMENT_MODE": mode, + "IS_COMPOSE_MODE": mode == "compose", + "IS_SWARM_MODE": mode == "swarm", + "fider_tenant_count": {"rows": [[tenants]]}, + } + executed: list = [] + for include in load_yaml_any(str(TASKS / "00_core.yml")): + target = include.get("include_tasks") + if not isinstance(target, str) or not (TASKS / target).is_file(): + continue + if not _guard_holds(include, context): + continue + executed.extend( + task + for task in load_yaml_any(str(TASKS / target)) + if _guard_holds(task, context) + ) + return executed + + +def _tenant_posts(tasks: list) -> list: + return [ + task + for task in tasks + if str(task.get("uri_retry", {}).get("url", "")).endswith("/_api/tenants") + or "POST /_api/tenants" in str(task.get("ansible.builtin.shell", "")) + ] + + +def _configures_keycloak(tasks: list) -> bool: + return any( + str(task.get("database_query", {}).get("query_file", "")).endswith( + "configure-oidc-provider.sql" + ) + for task in tasks + ) + + +class TestTenantBootstrapGate(unittest.TestCase): + def test_fresh_stack_host_posts_one_tenant_with_and_without_sso(self): + for sso in (True, False): + for mode in MODES: + with self.subTest(sso=sso, mode=mode): + tasks = _run_tasks(sso=sso, stack_host=True, mode=mode, tenants=0) + self.assertEqual(len(_tenant_posts(tasks)), 1) + + def test_existing_tenant_is_not_posted_again(self): + for sso in (True, False): + for mode in MODES: + with self.subTest(sso=sso, mode=mode): + tasks = _run_tasks(sso=sso, stack_host=True, mode=mode, tenants=1) + self.assertEqual(_tenant_posts(tasks), []) + + def test_keycloak_provider_is_configured_only_with_sso(self): + for sso in (True, False): + for mode in MODES: + with self.subTest(sso=sso, mode=mode): + tasks = _run_tasks(sso=sso, stack_host=True, mode=mode, tenants=1) + self.assertEqual(_configures_keycloak(tasks), sso) + + def test_non_stack_host_runs_no_bootstrap(self): + for sso in (True, False): + for mode in MODES: + with self.subTest(sso=sso, mode=mode): + tasks = _run_tasks(sso=sso, stack_host=False, mode=mode, tenants=0) + self.assertEqual(tasks, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-nextcloud/filter_plugins/test_nextcloud_janus.py b/tests/unit/python/roles/web-app-nextcloud/filter_plugins/test_nextcloud_janus.py deleted file mode 100644 index 1b0d72af21..0000000000 --- a/tests/unit/python/roles/web-app-nextcloud/filter_plugins/test_nextcloud_janus.py +++ /dev/null @@ -1,138 +0,0 @@ -from __future__ import annotations - -import importlib.util -import sys -import unittest - -from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape - -from . import PROJECT_ROOT - -OVERRIDES = ("rtp_port_range", "nat_1_1_mapping", "keep_private_host") -TARGET = "/usr/local/etc/janus/janus.jcfg" -LAUNCHER = ( - "[program:janus]\n" - "command=janus --config=/usr/local/etc/janus/janus.jcfg --disable-colors" - " --log-stdout --full-trickle --debug-level 3\n" -) - - -def _load_module(rel_path: str, name: str): - path = PROJECT_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 - sys.modules[name] = mod - spec.loader.exec_module(mod) - return mod - - -MODULE = _load_module( - "roles/web-app-nextcloud/filter_plugins/nextcloud_janus.py", "nextcloud_janus" -) - - -def _rendered_template() -> str: - env = Environment( - loader=FileSystemLoader( - str(PROJECT_ROOT / "roles/web-app-nextcloud/templates") - ), - undefined=StrictUndefined, - keep_trailing_newline=True, - autoescape=select_autoescape(default_for_string=False), - ) - return env.get_template("janus.jcfg.j2").render( - NEXTCLOUD_HPB_MEDIA_PORT_START=61000, - NEXTCLOUD_HPB_MEDIA_PORT_END=61999, - NEXTCLOUD_HPB_MEDIA_PUBLIC_IP="203.0.113.7", - ) - - -def _stock_like() -> str: - lines = ["/* a block comment the image ships", " over two lines */"] - for line in _rendered_template().splitlines(): - if line.strip().split(" ", 1)[0] in OVERRIDES: - lines.append("\t#" + line.strip() + "\t\t# commented out upstream") - continue - lines.append("\t\t# a comment line the image ships") - lines.append(line.replace(" = ", " = ") + "\t// trailing remark") - return "\n".join(lines) + "\n" - - -def _drift(stock: str, launcher: str = LAUNCHER) -> list[str]: - return MODULE.janus_config_drift( - _rendered_template(), stock, OVERRIDES, launcher, TARGET - ) - - -class TestJanusSettings(unittest.TestCase): - def test_comments_and_blank_lines_are_dropped(self): - content = "# head\n\ngeneral: {\n\tdebug_level = 4\t\t# level\n}\n" - self.assertEqual( - MODULE.janus_settings(content, []), ["general:{", "debug_level=4", "}"] - ) - - def test_block_comments_and_a_trailing_semicolon_are_dropped(self): - content = "/* head\n tail */\ndebug_level = 4; /* level */\n" - self.assertEqual(MODULE.janus_settings(content, []), ["debug_level=4"]) - - def test_a_hash_inside_a_quoted_value_is_kept(self): - content = 'log_prefix = "[janus] #1" # prefix\n' - self.assertEqual( - MODULE.janus_settings(content, []), ['log_prefix="[janus] #1"'] - ) - - def test_named_overrides_are_left_out(self): - content = 'nat: {\n\tnat_1_1_mapping = "1.2.3.4"\n\tnice_debug = false\n}\n' - self.assertEqual( - MODULE.janus_settings(content, ["nat_1_1_mapping"]), - ["nat:{", "nice_debug=false", "}"], - ) - - def test_the_template_sets_every_override_once(self): - keys = [ - setting.split("=", 1)[0] - for setting in MODULE.janus_settings(_rendered_template(), []) - ] - for override in OVERRIDES: - self.assertEqual(keys.count(override), 1, override) - - -class TestJanusConfigDrift(unittest.TestCase): - def test_a_stock_file_that_differs_only_in_comments_and_layout_passes(self): - self.assertEqual(_drift(_stock_like()), []) - - def test_a_moved_plugin_folder_stops_the_deploy(self): - stock = _stock_like().replace( - '"/usr/local/lib/janus/plugins"', '"/usr/lib/janus/plugins"' - ) - self.assertEqual(len(_drift(stock)), 1) - - def test_an_upstream_value_for_a_masked_key_stops_the_deploy(self): - stock = _stock_like().replace("\t#rtp_port_range", "\trtp_port_range", 1) - self.assertEqual(len(_drift(stock)), 1) - - def test_a_setting_upstream_added_stops_the_deploy(self): - stock = _stock_like().replace("nat: {", "nat: {\n\tice_tcp = true", 1) - self.assertEqual(len(_drift(stock)), 1) - - def test_an_empty_read_stops_the_deploy(self): - self.assertEqual(len(_drift("")), 1) - - def test_janus_reading_a_generated_config_stops_the_deploy(self): - launcher = LAUNCHER.replace(TARGET, "/conf/janus.jcfg") - self.assertEqual( - _drift(_stock_like(), launcher), - [f"Janus is not started with --config={TARGET}"], - ) - - def test_a_config_path_that_only_shares_the_prefix_stops_the_deploy(self): - launcher = LAUNCHER.replace(f"{TARGET} ", f"{TARGET}.generated ") - self.assertEqual(len(_drift(_stock_like(), launcher)), 1) - - def test_a_launcher_without_janus_stops_the_deploy(self): - self.assertEqual(len(_drift(_stock_like(), "")), 1) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/unit/python/roles/web-app-nextcloud/test_replace_pinned_app.py b/tests/unit/python/roles/web-app-nextcloud/test_replace_pinned_app.py new file mode 100644 index 0000000000..d01272bb56 --- /dev/null +++ b/tests/unit/python/roles/web-app-nextcloud/test_replace_pinned_app.py @@ -0,0 +1,150 @@ +from __future__ import annotations + +import io +import subprocess +import tarfile +import tempfile +import unittest +from pathlib import Path + +from utils.cache.files import PROJECT_ROOT + +SCRIPT = ( + PROJECT_ROOT / "roles/web-app-nextcloud/files/shell/utils/replace_pinned_app.sh" +) +APP = "onlyoffice" +INFO = "appinfo/info.xml" + + +def _archive(files: dict[str, str]) -> bytes: + """Return a gzipped tar that holds each file under ``/``. + + Args: + files: archive member path mapped to its text content. + """ + buffer = io.BytesIO() + with tarfile.open(fileobj=buffer, mode="w:gz") as tar: + for name, content in files.items(): + data = content.encode() + member = tarfile.TarInfo(name) + member.size = len(data) + tar.addfile(member, io.BytesIO(data)) + return buffer.getvalue() + + +def _release(version: str, *extra: str) -> dict[str, str]: + files = { + f"{APP}/{INFO}": f"{version}", + f"{APP}/lib/Migration/Version{version}.php": version, + } + files.update({f"{APP}/{name}": version for name in extra}) + return files + + +def _tree(root: Path) -> dict[str, str]: + return { + path.relative_to(root).as_posix(): path.read_text() # nocheck: cache-read + for path in sorted(root.rglob("*")) # nocheck: project-walk + if path.is_file() + } + + +class TestReplacePinnedApp(unittest.TestCase): + def setUp(self): + self._tmp = tempfile.TemporaryDirectory() + self.apps = Path(self._tmp.name) / "custom_apps" + self.apps.mkdir() + self.live = self.apps / APP + + def tearDown(self): + self._tmp.cleanup() + + def _run(self, files: dict[str, str]) -> subprocess.CompletedProcess: + return subprocess.run( + ["sh", str(SCRIPT), str(self.apps), APP], + input=_archive(files), + capture_output=True, + check=False, + ) + + def _install(self, files: dict[str, str]) -> None: + self.assertEqual(self._run(files).returncode, 0) + + def _expected(self, files: dict[str, str]) -> dict[str, str]: + return {name.removeprefix(f"{APP}/"): text for name, text in files.items()} + + def test_a_fresh_install_places_the_release(self): + release = _release("100201") + result = self._run(release) + self.assertEqual(result.returncode, 0) + self.assertEqual(_tree(self.live), self._expected(release)) + + def test_a_fresh_install_reports_a_change(self): + self.assertIn(b"[CHANGED]", self._run(_release("100201")).stdout) + + def test_an_identical_tree_reports_no_change(self): + release = _release("100201") + self._install(release) + result = self._run(release) + self.assertEqual(result.returncode, 0) + self.assertNotIn(b"[CHANGED]", result.stdout) + + def test_files_of_an_earlier_release_are_removed(self): + self._install(_release("091501", "js/old.chunk.mjs")) + release = _release("100201", "js/new.chunk.mjs") + result = self._run(release) + self.assertIn(b"[CHANGED]", result.stdout) + self.assertEqual(_tree(self.live), self._expected(release)) + + def test_an_overlaid_tree_with_leftovers_is_healed(self): + release = _release("100201") + self._install(release) + (self.live / "js").mkdir() + (self.live / "js/leftover.chunk.mjs").write_text("091501") + result = self._run(release) + self.assertIn(b"[CHANGED]", result.stdout) + self.assertEqual(_tree(self.live), self._expected(release)) + + def test_a_changed_file_is_replaced(self): + release = _release("100201") + self._install(release) + (self.live / INFO).write_text("patched") + self.assertIn(b"[CHANGED]", self._run(release).stdout) + self.assertEqual(_tree(self.live), self._expected(release)) + + def test_an_archive_without_the_app_fails(self): + result = self._run({"other/appinfo/info.xml": "x"}) + self.assertNotEqual(result.returncode, 0) + + def test_an_archive_without_the_app_keeps_the_installed_app(self): + release = _release("100201") + self._install(release) + self._run({"other/appinfo/info.xml": "x"}) + self.assertEqual(_tree(self.live), self._expected(release)) + + def test_a_corrupt_archive_keeps_the_installed_app(self): + release = _release("100201") + self._install(release) + result = subprocess.run( + ["sh", str(SCRIPT), str(self.apps), APP], + input=b"not a tarball", + capture_output=True, + check=False, + ) + self.assertNotEqual(result.returncode, 0) + self.assertEqual(_tree(self.live), self._expected(release)) + + def test_leftovers_of_an_interrupted_run_are_cleared(self): + (self.apps / f".{APP}.stage/{APP}").mkdir(parents=True) + (self.apps / f".{APP}.old/js").mkdir(parents=True) + self._install(_release("100201")) + self.assertEqual(sorted(p.name for p in self.apps.iterdir()), [APP]) + + def test_the_apps_directory_holds_only_the_app_after_a_replace(self): + self._install(_release("091501")) + self._install(_release("100201")) + self.assertEqual(sorted(p.name for p in self.apps.iterdir()), [APP]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-nextcloud/test_server_id.py b/tests/unit/python/roles/web-app-nextcloud/test_server_id.py new file mode 100644 index 0000000000..9b1303b8ab --- /dev/null +++ b/tests/unit/python/roles/web-app-nextcloud/test_server_id.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +import unittest + +from jinja2 import Environment, select_autoescape + +from utils.cache.files import PROJECT_ROOT, read_text +from utils.cache.yaml import load_yaml_str +from utils.roles.mapping import ROLE_FILE_TEMPL_COMPOSE + +TEMPLATE = read_text( + str(PROJECT_ROOT / "roles/web-app-nextcloud" / ROLE_FILE_TEMPL_COMPOSE) +) + + +def _environment(deployment_mode: str) -> dict: + start = TEMPLATE.index(" environment:\n") + end = TEMPLATE.index(" sysctls:", start) + rendered = ( + Environment(autoescape=select_autoescape(default_for_string=False)) + .from_string(TEMPLATE[start:end]) + .render(IS_SWARM_MODE=deployment_mode == "swarm") + ) + return load_yaml_str(rendered)["environment"] + + +class TestServerId(unittest.TestCase): + def test_compose_pins_a_server_id_nextcloud_accepts(self): + server_id = int(_environment("compose")["NC_serverid"]) + self.assertGreaterEqual(server_id, 1) + self.assertLessEqual(server_id, 511) + + def test_swarm_gives_every_replica_its_task_slot(self): + environment = _environment("swarm") + self.assertEqual(environment["NC_serverid"], "{{.Task.Slot}}") + self.assertEqual(environment["TASK_SLOT"], "{{.Task.Slot}}") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-nextcloud/test_talk_configs.py b/tests/unit/python/roles/web-app-nextcloud/test_talk_configs.py new file mode 100644 index 0000000000..5e7475ffd7 --- /dev/null +++ b/tests/unit/python/roles/web-app-nextcloud/test_talk_configs.py @@ -0,0 +1,460 @@ +from __future__ import annotations + +import configparser +import hashlib +import posixpath +import re +import unittest +from typing import ClassVar + +from jinja2 import Environment, StrictUndefined, select_autoescape + +from utils.cache.files import PROJECT_ROOT, read_text +from utils.cache.yaml import load_yaml +from utils.roles.mapping import ROLE_FILE_VARS_MAIN + +ROLE = PROJECT_ROOT / "roles" / "web-app-nextcloud" +TEMPLATES = ROLE / "templates" +FILES = ROLE / "files" + +SIGNALING_SECRET = "base64:signaling-fixture-secret" +INTERNAL_SECRET = "base64:internal-fixture-secret" +RECORDING_SECRET = "recording-fixture-secret" + +VARIABLES = { + "NEXTCLOUD_HPB_SIGNALING_PORT": 8081, + "NEXTCLOUD_HPB_SIGNALING_SECRET": SIGNALING_SECRET, + "NEXTCLOUD_HPB_INTERNAL_SECRET": INTERNAL_SECRET, + "NEXTCLOUD_HPB_BACKEND_URL": "https://next.example.org", + "NEXTCLOUD_HPB_SIGNALING_BACKEND_URLS": "https://next.example.org", + "NEXTCLOUD_HPB_SIGNALING_LOCATION": "/standalone-signaling/", + "NEXTCLOUD_HPB_SIGNALING_MAX_STREAM_BITRATE": 1048576, + "NEXTCLOUD_HPB_SIGNALING_MAX_SCREEN_BITRATE": 2097152, + "NEXTCLOUD_HPB_NATS_URL": "nats://talk_nats:4222", + "NEXTCLOUD_HPB_JANUS_URL": "ws://talk:8188", + "NEXTCLOUD_RECORDING_PORT": 1234, + "NEXTCLOUD_RECORDING_SECRET": RECORDING_SECRET, + "NEXTCLOUD_RECORDING_DIRECTORY": "/tmp", + "NEXTCLOUD_HPB_MEDIA_PORT_START": 61000, + "NEXTCLOUD_HPB_MEDIA_PORT_END": 61999, + "NEXTCLOUD_HPB_MEDIA_PUBLIC_IP": "203.0.113.7", + "NEXTCLOUD_HPB_JANUS_BASE_IMAGE": "alpine", + "NEXTCLOUD_HPB_JANUS_BASE_VERSION": "3.23.3", + "NEXTCLOUD_HPB_JANUS_REPOSITORY": "https://github.com/meetecho/janus-gateway.git", + "NEXTCLOUD_HPB_JANUS_REF": "v1.4.0", + "NEXTCLOUD_HPB_JANUS_CONFIG_TARGET": "/usr/local/etc/janus/janus.jcfg", + "NEXTCLOUD_RECORDING_BASE_IMAGE": "python", + "NEXTCLOUD_RECORDING_BASE_VERSION": "3.14.3-alpine3.23", + "NEXTCLOUD_RECORDING_REPOSITORY": "https://github.com/nextcloud/nextcloud-talk-recording.git", + "NEXTCLOUD_RECORDING_REF": "v0.2.1", + "NEXTCLOUD_RECORDING_USER_ID": 122, + "NEXTCLOUD_RECORDING_CONFIG_TARGET": "/conf/recording.conf", + "NEXTCLOUD_RECORDING_CA_CERT": "/tmp/infinito/ca/root-ca.crt", +} + +AIO_SIGNALING = { + "http": {"listen": "0.0.0.0:8081"}, + "app": {"debug": "false"}, + "clients": {"internalsecret": INTERNAL_SECRET}, + "backend": { + "backends": "backend-1", + "allowall": "false", + "timeout": "10", + "connectionsperhost": "8", + "skipverify": "false", + }, + "backend-1": { + "urls": "https://next.example.org", + "secret": SIGNALING_SECRET, + "maxstreambitrate": "1048576", + "maxscreenbitrate": "2097152", + }, + "nats": {"url": "nats://127.0.0.1:4222"}, + "mcu": { + "type": "janus", + "url": "ws://127.0.0.1:8188", + "maxstreambitrate": "1048576", + "maxscreenbitrate": "2097152", + }, +} + +AIO_RECORDING = { + "logs": {"level": "30"}, + "http": {"listen": "0.0.0.0:1234"}, + "backend": { + "allowall": "false", + "secret": RECORDING_SECRET, + "backends": "backend-1", + "skipverify": "false", + "maxmessagesize": "1024", + "videowidth": "1920", + "videoheight": "1080", + "directory": "/tmp", + }, + "backend-1": { + "url": "https://next.example.org", + "secret": RECORDING_SECRET, + "skipverify": "false", + }, + "signaling": {"signalings": "signaling-1"}, + "signaling-1": { + "url": "https://next.example.org/standalone-signaling/", + "internalsecret": INTERNAL_SECRET, + }, + "ffmpeg": {"extensionaudio": ".ogg", "extensionvideo": ".webm"}, + "recording": { + "browser": "firefox", + "driverPath": "/usr/bin/geckodriver", + "browserPath": "/usr/bin/firefox", + }, +} + +STOCK_JANUS = [ + "general:{", + 'configs_folder="/usr/local/etc/janus"', + 'plugins_folder="/usr/local/lib/janus/plugins"', + 'transports_folder="/usr/local/lib/janus/transports"', + 'events_folder="/usr/local/lib/janus/events"', + 'loggers_folder="/usr/local/lib/janus/loggers"', + "debug_level=4", + 'admin_secret="janusoverlord"', + "protected_folders=[", + *[ + f'"{folder}",' + for folder in ( + "/bin", + "/boot", + "/dev", + "/etc", + "/initrd", + "/lib", + "/lib32", + "/lib64", + "/proc", + "/sbin", + "/sys", + "/usr", + "/var", + "/opt/janus/bin", + "/opt/janus/etc", + "/opt/janus/include", + "/opt/janus/lib", + "/opt/janus/lib32", + "/opt/janus/lib64", + ) + ], + '"/opt/janus/sbin"', + "]", + "}", + "certificates:{", + "}", + "media:{", + "}", + "nat:{", + 'ice_ignore_list="vmnet"', + "}", + "plugins:{", + "}", + "transports:{", + "}", + "loggers:{", + "}", + "events:{", + "}", +] + + +def _render(source: str, **overrides) -> str: + env = Environment( + trim_blocks=True, + keep_trailing_newline=True, + undefined=StrictUndefined, + autoescape=select_autoescape(default_for_string=False), + ) + env.filters["hash"] = lambda value, algorithm: hashlib.new( + algorithm, str(value).encode() + ).hexdigest() + env.filters["bool"] = bool + env.filters["dirname"] = posixpath.dirname + return env.from_string(source).render({**VARIABLES, **overrides}) + + +def _template(name: str) -> str: + return read_text(str(TEMPLATES / name)) + + +def _build_args(dockerfile: str) -> str: + compose = _template("compose.yml.j2") + args: dict[str, str] = {} + for arg in re.findall(r"^ARG (\w+)$", dockerfile, re.MULTILINE): + passed = re.search(rf'^\s+{arg}: "(.*)"$', compose, re.MULTILINE) + if passed is None: + raise AssertionError(f"compose.yml.j2 passes no build arg {arg}") + args[arg] = _render(passed.group(1)) + return re.sub(r"\$\{(\w+)\}", lambda match: args[match.group(1)], dockerfile) + + +def _build(name: str) -> str: + return _build_args(read_text(str(FILES / "Dockerfiles" / name / "Dockerfile"))) + + +def _ini(text: str) -> dict[str, dict[str, str]]: + parser = configparser.ConfigParser(interpolation=None, strict=True) + parser.optionxform = str + parser.read_string(text) + return {section: dict(parser[section]) for section in parser.sections()} + + +def _settings(text: str) -> list[str]: + return [joined for line in text.splitlines() if (joined := "".join(line.split()))] + + +class TestSignalingConfig(unittest.TestCase): + def test_matches_what_the_aio_start_script_wrote_apart_from_the_split(self): + rendered = _ini(_render(_template("signaling.conf.j2"))) + sessions = rendered.pop("sessions") + expected = { + **AIO_SIGNALING, + "nats": {"url": "nats://talk_nats:4222"}, + "mcu": {**AIO_SIGNALING["mcu"], "url": "ws://talk:8188"}, + } + self.assertEqual(rendered, expected) + self.assertEqual(sorted(sessions), ["blockkey", "hashkey"]) + + def test_session_keys_have_the_shape_aio_generated_and_stay_stable(self): + first = _ini(_render(_template("signaling.conf.j2")))["sessions"] + second = _ini(_render(_template("signaling.conf.j2")))["sessions"] + self.assertEqual(first, second) + for key in ("hashkey", "blockkey"): + self.assertRegex(first[key], r"^[0-9a-f]{32}$") + self.assertNotEqual(first["hashkey"], first["blockkey"]) + self.assertNotIn(first["hashkey"], SIGNALING_SECRET) + + def test_negative_control_another_signaling_secret_changes_the_keys(self): + first = _ini(_render(_template("signaling.conf.j2")))["sessions"] + other = _ini( + _render( + _template("signaling.conf.j2"), + NEXTCLOUD_HPB_SIGNALING_SECRET="base64:another-secret", + ) + )["sessions"] + self.assertNotEqual(first["hashkey"], other["hashkey"]) + self.assertNotEqual(first["blockkey"], other["blockkey"]) + + def test_negative_control_a_changed_setting_breaks_parity(self): + drifted = _template("signaling.conf.j2").replace( + "allowall = false", "allowall = true" + ) + self.assertNotEqual(drifted, _template("signaling.conf.j2")) + rendered = _ini(_render(drifted)) + rendered.pop("sessions") + self.assertNotEqual(rendered["backend"], AIO_SIGNALING["backend"]) + + +CANONICAL_BACKEND_URL = VARIABLES["NEXTCLOUD_HPB_BACKEND_URL"] +ONION_BACKEND_URL = ( + "http://next.7csk6epqensl5eaw3rogyw2hhzusuahoj4n6iidgnrolgzq3muymrlyd.onion" +) + + +def _signaling_backend_urls(network_urls: list[str]) -> str: + """Render NEXTCLOUD_HPB_SIGNALING_BACKEND_URLS from vars/main.yml. + + Args: + network_urls: the answer of lookup('network_urls', NEXTCLOUD_HPB_BACKEND_URL) on the host. + + Returns: + The value signaling.conf.j2 receives. + """ + + def lookup(*terms: str) -> list[str]: + if terms != ("network_urls", CANONICAL_BACKEND_URL): + raise AssertionError(f"the backend urls render an unexpected lookup{terms}") + return network_urls + + expression = load_yaml(ROLE / ROLE_FILE_VARS_MAIN)[ + "NEXTCLOUD_HPB_SIGNALING_BACKEND_URLS" + ] + env = Environment( + undefined=StrictUndefined, + autoescape=select_autoescape(default_for_string=False), + ) + return env.compile_expression( + expression.strip().removeprefix("{{").removesuffix("}}") + )(lookup=lookup, NEXTCLOUD_HPB_BACKEND_URL=CANONICAL_BACKEND_URL) + + +def _signaling_backends(network_urls: list[str]) -> dict[str, dict[str, str]]: + rendered = _ini( + _render( + _template("signaling.conf.j2"), + NEXTCLOUD_HPB_SIGNALING_BACKEND_URLS=_signaling_backend_urls(network_urls), + ) + ) + return {"backend": rendered["backend"], "backend-1": rendered["backend-1"]} + + +class TestSignalingNetworkBackends(unittest.TestCase): + def test_every_network_sibling_reaches_the_one_backend_with_its_secret(self): + backends = _signaling_backends([CANONICAL_BACKEND_URL, ONION_BACKEND_URL]) + self.assertEqual(backends["backend"]["backends"], "backend-1") + self.assertEqual( + backends["backend-1"]["urls"], + f"{CANONICAL_BACKEND_URL},{ONION_BACKEND_URL}", + ) + self.assertEqual(backends["backend-1"]["secret"], SIGNALING_SECRET) + + def test_a_host_served_on_one_network_lists_only_the_canonical_backend(self): + self.assertEqual( + _signaling_backends([CANONICAL_BACKEND_URL])["backend-1"]["urls"], + CANONICAL_BACKEND_URL, + ) + + def test_negative_control_the_single_backend_url_drops_the_onion_sibling(self): + drifted = _template("signaling.conf.j2").replace( + "NEXTCLOUD_HPB_SIGNALING_BACKEND_URLS", "NEXTCLOUD_HPB_BACKEND_URL" + ) + self.assertNotEqual(drifted, _template("signaling.conf.j2")) + rendered = _ini( + _render( + drifted, + NEXTCLOUD_HPB_SIGNALING_BACKEND_URLS=_signaling_backend_urls( + [CANONICAL_BACKEND_URL, ONION_BACKEND_URL] + ), + ) + ) + self.assertNotIn(ONION_BACKEND_URL, rendered["backend-1"]["urls"]) + + +class TestRecordingConfig(unittest.TestCase): + def test_matches_what_the_aio_start_script_wrote(self): + self.assertEqual(_ini(_render(_template("recording.conf.j2"))), AIO_RECORDING) + + def test_negative_control_a_dropped_setting_breaks_parity(self): + drifted = _template("recording.conf.j2").replace("maxmessagesize = 1024\n", "") + self.assertNotEqual(drifted, _template("recording.conf.j2")) + self.assertNotEqual(_ini(_render(drifted)), AIO_RECORDING) + + +class TestJanusConfig(unittest.TestCase): + def test_without_direct_media_it_equals_the_stock_janus_config(self): + rendered = _render(_template("janus.jcfg.j2"), NEXTCLOUD_HPB_MEDIA_DIRECT=False) + self.assertEqual(_settings(rendered), STOCK_JANUS) + + def test_direct_media_adds_exactly_the_three_overrides(self): + rendered = _settings( + _render(_template("janus.jcfg.j2"), NEXTCLOUD_HPB_MEDIA_DIRECT=True) + ) + expected = list(STOCK_JANUS) + expected.insert(expected.index("media:{") + 1, 'rtp_port_range="61000-61999"') + expected.insert(expected.index("nat:{") + 1, 'nat_1_1_mapping="203.0.113.7"') + expected.insert(expected.index("nat:{") + 2, "keep_private_host=true") + self.assertEqual(rendered, expected) + + def test_negative_control_an_unguarded_override_breaks_the_stock_config(self): + drifted = _template("janus.jcfg.j2").replace( + "{% if NEXTCLOUD_HPB_MEDIA_DIRECT | bool %}\n\trtp_port_range", + "{% if true %}\n\trtp_port_range", + ) + self.assertNotEqual(drifted, _template("janus.jcfg.j2")) + rendered = _render(drifted, NEXTCLOUD_HPB_MEDIA_DIRECT=False) + self.assertNotEqual(_settings(rendered), STOCK_JANUS) + + +class TestTalkDockerfiles(unittest.TestCase): + AIO_JANUS_BUILD_PACKAGES: ClassVar[list[str]] = [ + "ca-certificates", + "git", + "autoconf", + "automake", + "build-base", + "pkgconfig", + "libtool", + "util-linux", + "glib-dev", + "zlib-dev", + "openssl-dev", + "jansson-dev", + "libnice-dev", + "libconfig-dev", + "libsrtp-dev", + "libusrsctp-dev", + "gengetopt-dev", + "libwebsockets-dev", + ] + + def test_janus_builds_the_pinned_tag_on_the_pinned_base(self): + rendered = _build("Janus") + self.assertEqual( + re.findall(r"^FROM (\S+)", rendered, re.MULTILINE), + ["alpine:3.23.3", "alpine:3.23.3"], + ) + self.assertIn( + 'git clone --recursive "https://github.com/meetecho/janus-gateway.git" ' + '--depth=1 --single-branch --branch "v1.4.0" /src', + rendered, + ) + self.assertIn( + "/src/configure --disable-rabbitmq --disable-mqtt --disable-boringssl", + rendered, + ) + build_stage = rendered.split("\nFROM ")[1] + for package in self.AIO_JANUS_BUILD_PACKAGES: + with self.subTest(package=package): + self.assertRegex(build_stage, rf"\n\s+{re.escape(package)}( \\|;)") + self.assertIn( + 'ENTRYPOINT ["janus", "--disable-colors", "--log-stdout", ' + '"--full-trickle", "--debug-level", "3"]', + rendered, + ) + + def test_recording_installs_the_pinned_release_on_the_pinned_base(self): + rendered = _build("Recording") + self.assertEqual( + re.findall(r"^FROM (\S+)", rendered, re.MULTILINE), + ["python:3.14.3-alpine3.23"], + ) + self.assertIn( + 'git clone --recursive "https://github.com/nextcloud/nextcloud-talk-recording.git" ' + '--depth=1 --single-branch --branch "v0.2.1" /src', + rendered, + ) + self.assertIn('useradd -d "/tmp" --system recording -u "122"', rendered) + self.assertIn('mkdir -p "/conf"', rendered) + self.assertIn( + """printf '{"policies":{"Certificates":{"Install":["%s"]}}}\\n' """ + '"/tmp/infinito/ca/root-ca.crt" > /etc/firefox/policies/policies.json', + rendered, + ) + self.assertIn("USER 122", rendered) + self.assertIn( + 'ENTRYPOINT ["python", "-m", "nextcloud.talk.recording"]', rendered + ) + + def test_the_compose_command_points_each_binary_at_its_rendered_config(self): + compose = _template("compose.yml.j2") + self.assertIn( + 'command: ["--config={{ NEXTCLOUD_HPB_JANUS_CONFIG_TARGET }}"]', compose + ) + self.assertIn( + 'command: ["--config", "{{ NEXTCLOUD_RECORDING_CONFIG_TARGET }}"]', compose + ) + + def test_no_image_ships_a_start_script_that_writes_its_config(self): + for name in ("Janus", "Recording"): + with self.subTest(dockerfile=name): + rendered = _build(name) + self.assertNotRegex(rendered, r"ENTRYPOINT \[\"[^\"]*\.sh\"") + self.assertNotIn( + "COPY", + rendered.split("\nFROM ")[-1].replace("COPY --from=build", ""), + ) + self.assertNotIn("SECRET", rendered) + + def test_negative_control_an_arg_compose_does_not_pass_fails_the_build(self): + with self.assertRaisesRegex(AssertionError, "JANUS_UNPASSED"): + _build_args("ARG JANUS_UNPASSED\nFROM ${JANUS_UNPASSED}\n") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py b/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py index d93e3495c2..6ce7806382 100644 --- a/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py +++ b/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py @@ -18,53 +18,108 @@ from plugins.lookup.container_volumes import container_volumes from utils.cache import _reset_cache_for_tests from utils.cache.files import PROJECT_ROOT, read_text from utils.cache.yaml import load_yaml_any -from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_TEMPL_COMPOSE +from utils.roles.mapping import ( + ROLE_FILE_META_SERVICES, + ROLE_FILE_TEMPL_COMPOSE, + ROLE_FILE_VARS_MAIN, +) ROLE = "roles/web-app-nextcloud" TEMPLATE = f"{ROLE}/{ROLE_FILE_TEMPL_COMPOSE}" PUBLIC_IP = "203.0.113.7" SERVICES = load_yaml_any(str(PROJECT_ROOT / ROLE / ROLE_FILE_META_SERVICES)) +TALK_SERVICES = ("talk", "talk_signaling", "talk_nats", "talk_recording") -TALK_HEAD = ( - " talk:\n" - " \n" - " \n" - " \n" - " )>\n" - ' command: ["/start.sh", "sh", "", "supervisord", "-c", "/supervisord.conf"]\n' - " \n" - " init: true\n" -) +JANUS_HEAD = """ talk: + + build: + context: + dockerfile: Dockerfile + args: + JANUS_BASE_IMAGE: "" + JANUS_BASE_VERSION: "" + JANUS_REPOSITORY: "" + JANUS_REF: "" + + }> + )> + command: ["--config="] + init: true + + \n configs: + - source: janus_conf + target: /usr/local/etc/janus/janus.jcfg + mode: 292""" -LEGACY_BRIDGE_ONBOARD = ( - TALK_HEAD - + """ ports: - - "203.0.113.7:3480:3480/tcp" - - "203.0.113.7:3480:3480/udp" - - "203.0.113.7:50000-59999:50000-59999/udp" - - "203.0.113.7:50000-59999:50000-59999/tcp" +JANUS_HOST = JANUS_HEAD + "\n network_mode: host" + +JANUS_BRIDGE = ( + JANUS_HEAD + + """ expose: - - "8081" - """ + - "" + """ ) -LEGACY_BRIDGE = ( - TALK_HEAD - + """ expose: - - "8081" - """ +DIRECT_PORT = ( + ' ports:\n - "203.0.113.7:61000-61999:61000-61999/udp"\n expose:' ) -LEGACY_HOST = TALK_HEAD + " network_mode: host" +SIGNALING = """ talk_signaling: + + + )> + user: ":" + command: ["", "-config", ""] + + \n secrets: + - source: talk_signaling_conf + target: /config/server.conf + mode: 292 + expose: + - "" + + """ -DIRECT_MOUNT = ( - " \n" - " configs:\n" - " - source: janus_conf\n" - " target: /usr/local/etc/janus/janus.jcfg" -) +NATS = """ talk_nats: + + + )> + user: ":" + command: ["nats-server", "--addr", "0.0.0.0", "--port", "", "--http_port", ""] + + expose: + - "" + """ -DIRECT_PORT = ' - "203.0.113.7:61000-61999:61000-61999/udp"' +RECORDING = """ talk_recording: + + build: + context: + dockerfile: Dockerfile + args: + RECORDING_BASE_IMAGE: "" + RECORDING_BASE_VERSION: "" + RECORDING_REPOSITORY: "" + RECORDING_REF: "" + RECORDING_USER_ID: "" + RECORDING_DIRECTORY: "" + RECORDING_CONFIG_DIRECTORY: ">" + RECORDING_CA_CERT: "" + + }> + )> + command: ["--config", ""] + + expose: + - "" + + \n volumes: + - talk_recording_tmp:/tmp + secrets: + - source: talk_recording_conf + target: /conf/recording.conf + mode: 292""" class _Marker(ChainableUndefined): @@ -82,9 +137,7 @@ def _bool(value): return str(value).strip().lower() in {"y", "yes", "true", "on", "1"} -def _render( - template_text: str, *, onboard: bool, direct: bool, mode: str, network: str -) -> str: +def _render(template_text: str, *, direct: bool, mode: str, network: str) -> str: applications = {"web-app-nextcloud": {"services": SERVICES}} env = Environment( loader=ChoiceLoader( @@ -108,19 +161,24 @@ def _render( ) env.filters["bool"] = _bool env.filters["path_join"] = lambda parts: "/".join(str(part) for part in parts) + env.filters["dirname"] = lambda value: f"" variables = { "application_id": "web-app-nextcloud", "NEXTCLOUD_PROXY_SERVICE": "proxy", "NEXTCLOUD_SERVICE": "nextcloud", "NEXTCLOUD_CRON_SERVICE": "cron", + "NEXTCLOUD_TASKPROCESSING_SERVICE": "taskprocessing", "DEPLOYMENT_MODE": mode, + "IS_COMPOSE_MODE": mode == "compose", + "IS_SWARM_MODE": mode == "swarm", "NEXTCLOUD_HPB_SIGNALING_ENABLED": True, "NEXTCLOUD_HPB_SERVICE": "talk", - "NEXTCLOUD_HPB_SIGNALING_PORT": 8081, + "NEXTCLOUD_HPB_SIGNALING_SERVICE": "talk_signaling", + "NEXTCLOUD_HPB_NATS_SERVICE": "talk_nats", + "NEXTCLOUD_RECORDING_SERVICE": "talk_recording", + "NEXTCLOUD_RECORDING_ENABLED": True, "NEXTCLOUD_HPB_NETWORK_MODE": network, - "NEXTCLOUD_HPB_TURN_ONBOARD_ENABLED": onboard, - "NEXTCLOUD_HPB_TURN_ONBOARD_PUBLISH_PORTS": True, - "NEXTCLOUD_HPB_TURN_ONBOARD_BIND_HOST": PUBLIC_IP, + "NEXTCLOUD_HPB_JANUS_HOST_NETWORK": network == "host", "NEXTCLOUD_HPB_MEDIA_DIRECT": direct, "NEXTCLOUD_HPB_MEDIA_PUBLIC_IP": PUBLIC_IP, } @@ -138,7 +196,10 @@ def _render( def lookup(name, *args, **kwargs): if name == "config": - return {"services.talk.direct_media": direct}[args[1]] + return { + "services.talk.direct_media": direct, + "services.talk.enabled": True, + }[args[1]] if name == "container_ports": with mock.patch.object(container_ports_lookup, "lookup_loader", _Loader()): return container_ports_lookup.LookupModule().run( @@ -149,15 +210,16 @@ def _render( applications, "web-app-nextcloud", args[0], render_jinja=render_jinja ) return "\n" + block if block else block - return f"" + suffix = f" {dict(sorted(kwargs.items()))!r}" if kwargs else "" + return f"" env.globals["lookup"] = lookup return env.get_template("compose.yml.j2").render(variables) -def _talk_block(rendered: str) -> str: +def _block(rendered: str, service: str) -> str: lines = rendered.splitlines() - start = lines.index(" talk:") + start = lines.index(f" {service}:") end = next( index for index in range(start + 1, len(lines)) @@ -166,107 +228,171 @@ def _talk_block(rendered: str) -> str: return "\n".join(lines[start:end]).rstrip() -def _cells(direct: bool): - for onboard, mode, network in itertools.product( +def _cells(): + for direct, mode, network in itertools.product( (True, False), ("compose", "swarm"), ("bridge", "host") ): - yield {"onboard": onboard, "direct": direct, "mode": mode, "network": network} + yield {"direct": direct, "mode": mode, "network": network} -def _legacy(cell) -> str: - if cell["network"] == "host": - return LEGACY_HOST - return LEGACY_BRIDGE_ONBOARD if cell["onboard"] else LEGACY_BRIDGE +def _expected_janus(cell) -> str: + if cell["mode"] == "compose" and cell["network"] == "host": + return JANUS_HOST + if cell["direct"]: + return JANUS_BRIDGE.replace(" expose:", DIRECT_PORT) + return JANUS_BRIDGE -class TestTalkComposeBlock(unittest.TestCase): - def test_every_cell_without_direct_media_renders_the_legacy_block(self): - template = read_text(str(PROJECT_ROOT / TEMPLATE)) - for cell in _cells(direct=False): +def _template() -> str: + return read_text(str(PROJECT_ROOT / TEMPLATE)) + + +class TestTalkComposeBlocks(unittest.TestCase): + def test_janus_block_follows_network_mode_and_direct_media(self): + for cell in _cells(): with self.subTest(**cell): - self.assertEqual(_talk_block(_render(template, **cell)), _legacy(cell)) - - def test_direct_media_adds_only_the_janus_mount_and_the_udp_range(self): - template = read_text(str(PROJECT_ROOT / TEMPLATE)) - for cell in _cells(direct=True): - if cell["network"] != "bridge": - continue - with self.subTest(**cell): - block = _talk_block(_render(template, **cell)) - legacy = _legacy(cell) - expected = legacy.replace( - "\n \n init: true", "\n" + DIRECT_MOUNT + "\n init: true" + self.assertEqual( + _block(_render(_template(), **cell), "talk"), _expected_janus(cell) ) - if cell["onboard"]: - expected = expected.replace( - " expose:", DIRECT_PORT + "\n expose:" - ) - else: - expected = expected.replace( - " expose:", " ports:\n" + DIRECT_PORT + "\n expose:" - ) - self.assertEqual(block, expected) - def test_negative_control_direct_media_does_not_render_the_legacy_block(self): - template = read_text(str(PROJECT_ROOT / TEMPLATE)) - cell = { - "onboard": False, - "direct": True, - "mode": "compose", - "network": "bridge", - } - rendered = _render(template, **cell) - self.assertIn("janus_conf", rendered) - self.assertNotEqual(_talk_block(rendered), _legacy(cell)) + def test_signaling_block_is_the_same_in_every_cell(self): + for cell in _cells(): + with self.subTest(**cell): + expected = SIGNALING.replace( + "{host_alias}", str(cell["network"] == "host") + ) + self.assertEqual( + _block(_render(_template(), **cell), "talk_signaling"), expected + ) + + def test_nats_and_recording_blocks_are_the_same_in_every_cell(self): + for cell in _cells(): + with self.subTest(**cell): + rendered = _render(_template(), **cell) + self.assertEqual(_block(rendered, "talk_nats"), NATS) + self.assertEqual(_block(rendered, "talk_recording"), RECORDING) + + def test_no_talk_service_passes_a_secret_through_compose(self): + for cell in _cells(): + rendered = _render(_template(), **cell) + for service in TALK_SERVICES: + with self.subTest(service=service, **cell): + self.assertNotIn("SECRET", _block(rendered, service)) + + def test_negative_control_an_ungated_host_network_reaches_swarm(self): + template = _template().replace( + "{% if IS_COMPOSE_MODE and NEXTCLOUD_HPB_JANUS_HOST_NETWORK | bool %}", + "{% if NEXTCLOUD_HPB_JANUS_HOST_NETWORK | bool %}", + ) + cell = {"direct": False, "mode": "swarm", "network": "host"} + self.assertNotEqual(template, _template()) + block = _block(_render(template, **cell), "talk") + self.assertIn("network_mode: host", block) + self.assertNotEqual(block, _expected_janus(cell)) + + def test_negative_control_a_secret_in_the_environment_is_caught(self): + template = _template().replace( + ' command: ["--config", "{{ NEXTCLOUD_RECORDING_CONFIG_TARGET }}"]', + ' command: ["--config", "{{ NEXTCLOUD_RECORDING_CONFIG_TARGET }}"]\n' + " environment:\n" + ' RECORDING_SECRET: "{{ NEXTCLOUD_RECORDING_SECRET }}"', + ) + self.assertNotEqual(template, _template()) + block = _block( + _render(template, direct=False, mode="compose", network="bridge"), + "talk_recording", + ) + self.assertIn("SECRET", block) -def _direct_media(group_names, *, mode="compose", ip4=PUBLIC_IP, applications=None): +ROLE_VARS = load_yaml_any(str(PROJECT_ROOT / ROLE / ROLE_FILE_VARS_MAIN)) +DIRECT_MEDIA_CHAIN = ( + "NEXTCLOUD_HPB_PLUGIN_ENABLED", + "NEXTCLOUD_HPB_SIGNALING_ENABLED", + "NEXTCLOUD_HPB_TURN_STANDALONE_ENABLED", + "NEXTCLOUD_HPB_HOST_ADDRESSES", +) + + +def _direct_media( + group_names, *, mode="compose", ip4=PUBLIC_IP, applications=None, facts=True +): from ansible.parsing.dataloader import DataLoader - from ansible.template import Templar - - from utils.cache.applications import get_merged_applications + from ansible.template import Templar, trust_as_template variables = { "group_names": group_names, "applications": applications or {}, + "application_id": "web-app-nextcloud", + "NEXTCLOUD_HPB_SERVICE": "talk", "DEPLOYMENT_MODE": mode, "IS_COMPOSE_MODE": mode == "compose", "networks": {"internet": {"ip4": ip4, "ip6": "::1"}}, - "ansible_facts": {"all_ipv4_addresses": [PUBLIC_IP, "10.208.0.1"]}, + **{name: trust_as_template(ROLE_VARS[name]) for name in DIRECT_MEDIA_CHAIN}, } + if facts: + variables["ansible_facts"] = {"all_ipv4_addresses": [PUBLIC_IP, "10.208.0.1"]} templar = Templar(loader=DataLoader(), variables=dict(variables)) templar.available_variables = dict(variables) _reset_cache_for_tests() try: - merged = get_merged_applications(variables=variables, templar=templar) + return templar.template( + trust_as_template(ROLE_VARS["NEXTCLOUD_HPB_MEDIA_DIRECT"]) + ) finally: _reset_cache_for_tests() - return merged["web-app-nextcloud"]["services"]["talk"]["direct_media"] STANDALONE_TURN = ("web-app-nextcloud", "web-svc-coturn") +def _talk(**talk): + return {"web-app-nextcloud": {"services": {"talk": talk}}} + + +OPTED_IN = _talk(direct_media=True) + + class TestDirectMediaFlag(unittest.TestCase): - def test_compose_with_standalone_turn_and_an_owned_address_turns_it_on(self): - self.assertIs(_direct_media(list(STANDALONE_TURN)), True) + def test_by_default_every_stream_goes_through_turn(self): + self.assertIs(_direct_media(list(STANDALONE_TURN)), False) + + def test_opting_in_with_standalone_turn_and_an_owned_address_turns_it_on(self): + self.assertIs(_direct_media(list(STANDALONE_TURN), applications=OPTED_IN), True) + + def test_host_networking_keeps_it_on(self): + host = _talk(direct_media=True, network_mode="host") + self.assertIs(_direct_media(list(STANDALONE_TURN), applications=host), True) def test_an_address_the_host_does_not_own_keeps_it_off(self): - self.assertIs(_direct_media(list(STANDALONE_TURN), ip4="198.51.100.9"), False) + self.assertIs( + _direct_media( + list(STANDALONE_TURN), ip4="198.51.100.9", applications=OPTED_IN + ), + False, + ) def test_the_loopback_placeholder_keeps_it_off(self): - self.assertIs(_direct_media(list(STANDALONE_TURN), ip4="127.0.0.1"), False) + self.assertIs( + _direct_media(list(STANDALONE_TURN), ip4="127.0.0.1", applications=OPTED_IN), + False, + ) def test_swarm_keeps_it_off(self): - self.assertIs(_direct_media(list(STANDALONE_TURN), mode="swarm"), False) + self.assertIs( + _direct_media(list(STANDALONE_TURN), mode="swarm", applications=OPTED_IN), + False, + ) - def test_onboard_turn_keeps_it_off(self): - forced = {"web-app-nextcloud": {"services": {"talk": {"enabled": True}}}} + def test_talk_without_coturn_keeps_it_off(self): + forced = _talk(enabled=True, direct_media=True) self.assertIs(_direct_media(["web-app-nextcloud"], applications=forced), False) - def test_host_networking_keeps_it_off(self): - host = {"web-app-nextcloud": {"services": {"talk": {"network_mode": "host"}}}} - self.assertIs(_direct_media(list(STANDALONE_TURN), applications=host), False) + def test_missing_host_facts_render_false_instead_of_a_raw_expression(self): + self.assertIs( + _direct_media(list(STANDALONE_TURN), facts=False, applications=OPTED_IN), + False, + ) if __name__ == "__main__": diff --git a/tests/unit/python/roles/web-app-nextcloud/test_talk_version_pins.py b/tests/unit/python/roles/web-app-nextcloud/test_talk_version_pins.py new file mode 100644 index 0000000000..fddc1a2e78 --- /dev/null +++ b/tests/unit/python/roles/web-app-nextcloud/test_talk_version_pins.py @@ -0,0 +1,137 @@ +from __future__ import annotations + +import os +import re +import unittest +import unittest.mock as mock +from typing import ClassVar + +from utils.cache.files import PROJECT_ROOT, read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_SERVICES +from utils.update import docker, repository + +ROLE = "web-app-nextcloud" +SERVICES_FILE = PROJECT_ROOT / "roles" / ROLE / ROLE_FILE_META_SERVICES +JANUS = "https://github.com/meetecho/janus-gateway.git" +RECORDING = "https://github.com/nextcloud/nextcloud-talk-recording.git" + + +def _pinned(service: str, key: str) -> str: + return str(load_yaml_any(str(SERVICES_FILE))[service][key]) + + +class TestTalkPinsAreWatched(unittest.TestCase): + IMAGES: ClassVar[dict[str, str]] = { + "talk_signaling": "strukturag/nextcloud-spreed-signaling", + "talk_nats": "nats", + "talk": "alpine", + "talk_recording": "python", + } + REFS: ClassVar[dict[str, str]] = {"talk": JANUS, "talk_recording": RECORDING} + + def test_the_docker_updater_watches_every_talk_image(self): + entries = { + (entry.service, entry.image): entry.version + for entry in docker.collect_entries(PROJECT_ROOT) + if entry.role == ROLE + } + for service, image in self.IMAGES.items(): + with self.subTest(service=service): + self.assertEqual( + entries.get((service, image)), _pinned(service, "version") + ) + + def test_the_repository_updater_watches_both_built_sources(self): + entries = { + entry.entity_path: (entry.repository, entry.ref) + for entry in repository.collect_entries(PROJECT_ROOT) + if entry.role == ROLE + } + for service, url in self.REFS.items(): + with self.subTest(service=service): + self.assertEqual( + entries.get((service,)), (url, _pinned(service, "ref")) + ) + + def test_no_talk_pin_opts_out_of_the_updaters(self): + lines = read_text(str(SERVICES_FILE)).splitlines() + owner = None + for number, line in enumerate(lines): + if match := re.match(r"^([a-z_]+):", line): + owner = match.group(1) + if owner in self.IMAGES and re.match(r"^\s+(version|ref):", line): + with self.subTest(service=owner, line=number + 1): + self.assertNotIn("nocheck", lines[number - 1]) + self.assertNotIn("nocheck", line) + + def test_a_newer_upstream_release_is_reported_for_every_pin(self): + newer = { + "strukturag/nextcloud-spreed-signaling": ["2.1.1", "9.0.0", "9.0.0-proxy"], + "nats": ["2.12.6-alpine", "9.0.0-alpine", "9.1.0"], + "alpine": ["3.23.3", "9.0.0"], + "python": ["3.14.3-alpine3.23", "3.14.9-alpine3.23", "3.15.0-slim"], + } + tags = {JANUS: ["v1.4.0", "v9.0.0"], RECORDING: ["v0.2.1", "v9.0.0"]} + with ( + mock.patch.dict(os.environ, {"INFINITO_WORKER_FETCH": "2"}), + mock.patch.object( + docker, "fetch_dockerhub_tags", lambda image: newer.get(image, []) + ), + mock.patch.object(docker, "fetch_ghcr_tags", lambda image: []), + mock.patch.object(docker, "fetch_mcr_tags", lambda image: []), + mock.patch.object( + docker, "fetch_registry_tags", lambda image, last=None: [] + ), + mock.patch.object( + repository, "git_ls_remote_tags", lambda url: tags.get(url, []) + ), + ): + images = { + (update.entry.service, update.latest) + for update in docker.find_outdated_updates(PROJECT_ROOT) + if update.entry.role == ROLE + } + refs = { + (update.entry.entity_path, update.latest) + for update in repository.find_outdated_updates(PROJECT_ROOT) + if update.entry.role == ROLE + } + self.assertTrue( + { + ("talk_signaling", "9.0.0"), + ("talk_nats", "9.0.0-alpine"), + ("talk", "9.0.0"), + ("talk_recording", "3.14.9-alpine3.23"), + } + <= images, + images, + ) + self.assertEqual(refs, {(("talk",), "v9.0.0"), (("talk_recording",), "v9.0.0")}) + + def test_negative_control_current_tags_report_nothing(self): + current = { + image: [_pinned(service, "version")] + for service, image in self.IMAGES.items() + } + with ( + mock.patch.dict(os.environ, {"INFINITO_WORKER_FETCH": "2"}), + mock.patch.object( + docker, "fetch_dockerhub_tags", lambda image: current.get(image, []) + ), + mock.patch.object(docker, "fetch_ghcr_tags", lambda image: []), + mock.patch.object(docker, "fetch_mcr_tags", lambda image: []), + mock.patch.object( + docker, "fetch_registry_tags", lambda image, last=None: [] + ), + ): + reported = { + update.entry.service + for update in docker.find_outdated_updates(PROJECT_ROOT) + if update.entry.role == ROLE + } + self.assertFalse(reported & set(self.IMAGES), reported) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-nextcloud/test_taskprocessing_worker.py b/tests/unit/python/roles/web-app-nextcloud/test_taskprocessing_worker.py new file mode 100644 index 0000000000..a17656b30e --- /dev/null +++ b/tests/unit/python/roles/web-app-nextcloud/test_taskprocessing_worker.py @@ -0,0 +1,77 @@ +from __future__ import annotations + +import re +import unittest + +from jinja2 import ChainableUndefined, Environment, select_autoescape + +from plugins.lookup.container_volumes import container_volumes +from utils.cache.files import PROJECT_ROOT, read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ( + ROLE_FILE_META_SERVICES, + ROLE_FILE_TEMPL_COMPOSE, + ROLE_FILE_VARS_MAIN, +) + +ROLE = "roles/web-app-nextcloud" +APPLICATION_ID = "web-app-nextcloud" +SERVICES = load_yaml_any(str(PROJECT_ROOT / ROLE / ROLE_FILE_META_SERVICES)) +VARS = load_yaml_any(str(PROJECT_ROOT / ROLE / ROLE_FILE_VARS_MAIN)) +TEMPLATE = read_text(str(PROJECT_ROOT / ROLE / ROLE_FILE_TEMPL_COMPOSE)) + + +def _render_jinja(expression: str) -> str: + env = Environment( + undefined=ChainableUndefined, + autoescape=select_autoescape(default_for_string=False), + ) + env.globals["lookup"] = lambda name, *args, **kwargs: f"<{name} {args!r}>" + env.filters["path_join"] = lambda parts: "/".join(str(part) for part in parts) + return env.from_string(expression).render() + + +def _mounts(service: str) -> str: + return container_volumes( + {APPLICATION_ID: {"services": SERVICES}}, + APPLICATION_ID, + service, + render_jinja=_render_jinja, + ) + + +def _service_block(service_var: str) -> str: + start = TEMPLATE.index(f"{{% set service_name = {service_var} %}}") + following = re.search(r"\{% (set service_name|if|endif)\b", TEMPLATE[start + 1 :]) + end = start + 1 + following.start() if following else len(TEMPLATE) + return TEMPLATE[start:end] + + +class TestTaskProcessingWorker(unittest.TestCase): + def test_service_key_matches_the_vars_spot(self): + self.assertIn(VARS["NEXTCLOUD_TASKPROCESSING_SERVICE"], SERVICES) + + def test_worker_mounts_exactly_what_cron_mounts(self): + cron = _mounts(VARS["NEXTCLOUD_CRON_SERVICE"]) + self.assertIn("/var/www/html/", cron) + self.assertEqual(_mounts(VARS["NEXTCLOUD_TASKPROCESSING_SERVICE"]), cron) + + def test_worker_scales_with_the_swarm_topology(self): + self.assertNotIn("replicas", SERVICES[VARS["NEXTCLOUD_TASKPROCESSING_SERVICE"]]) + + def test_worker_runs_the_command_that_records_its_heartbeat(self): + block = _service_block("NEXTCLOUD_TASKPROCESSING_SERVICE") + self.assertIn("taskprocessing:worker -t 60", block) + self.assertNotIn("background-job:worker", block) + + def test_worker_runs_the_cron_image_as_the_occ_owner(self): + worker = _service_block("NEXTCLOUD_TASKPROCESSING_SERVICE") + cron = _service_block("NEXTCLOUD_CRON_SERVICE") + image = "{{ lookup('container_image', application_id, 'nextcloud') }}" + self.assertIn(image, cron) + self.assertIn(image, worker) + self.assertIn('"su", "{{ NEXTCLOUD_DOCKER_USER }}"', worker) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/scripts/git/__init__.py b/tests/unit/python/scripts/git/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/scripts/git/assert/__init__.py b/tests/unit/python/scripts/git/assert/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/scripts/git/assert/test_main_merged.py b/tests/unit/python/scripts/git/assert/test_main_merged.py new file mode 100644 index 0000000000..5a41470cb1 --- /dev/null +++ b/tests/unit/python/scripts/git/assert/test_main_merged.py @@ -0,0 +1,134 @@ +from __future__ import annotations + +import os +import subprocess +import tempfile +import unittest +from pathlib import Path + +from utils.cache.files import PROJECT_ROOT + +SCRIPT = PROJECT_ROOT / "scripts" / "git" / "assert" / "main_merged.sh" +MAIN_COMMIT_ENV = "INFINITO_MAIN_COMMIT" # nocheck: git maintainer tooling knob, not a deployment env key + + +class MainMergedFixture: + """A bare ``origin`` whose ``main`` moved on after ``head`` branched off it. + + Args: + tmp: directory that holds the bare remote and its two clones. + """ + + def __init__(self, tmp: str) -> None: + root = Path(tmp) + inherited = { + k: v + for k, v in os.environ.items() + if not k.startswith(("GIT_", "INFINITO_")) + } + self.env = { + **inherited, + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_AUTHOR_NAME": "test", + "GIT_AUTHOR_EMAIL": "test@example.invalid", + "GIT_COMMITTER_NAME": "test", + "GIT_COMMITTER_EMAIL": "test@example.invalid", + } + origin = root / "origin.git" + maintainer = root / "maintainer" + self.head = root / "head" + self.git(root, "init", "--bare", "-b", "main", str(origin)) + self.git(root, "init", "-b", "main", str(maintainer)) + self.git(maintainer, "remote", "add", "origin", str(origin)) + self.base = self.commit(maintainer, "base") + self.git(maintainer, "push", "origin", "main") + self.git(root, "clone", str(origin), str(self.head)) + self.git(self.head, "switch", "-c", "feature") + self.commit(self.head, "feature") + self.main_tip = self.commit(maintainer, "main moved on") + self.git(maintainer, "push", "origin", "main") + + def git(self, cwd: Path, *args: str) -> str: + return subprocess.run( + ["git", *args], + cwd=cwd, + env=self.env, + capture_output=True, + text=True, + check=True, + ).stdout.strip() + + def commit(self, repo: Path, message: str) -> str: + self.git(repo, "commit", "--allow-empty", "-m", message) + return self.git(repo, "rev-parse", "HEAD") + + def merge_main(self) -> None: + self.git(self.head, "pull", "--no-rebase", "--no-edit", "origin", "main") + + def run_script(self, main_commit: str | None) -> subprocess.CompletedProcess: + """Run the script in ``head``. + + Args: + main_commit: value of the main-commit override; ``None`` leaves it unset. + """ + env = dict(self.env) + if main_commit is not None: + env[MAIN_COMMIT_ENV] = main_commit + return subprocess.run( + ["bash", str(SCRIPT)], + cwd=self.head, + env=env, + capture_output=True, + text=True, + check=False, + ) + + +class TestMainMergedPinnedCommit(unittest.TestCase): + def test_contained_commit_passes_after_main_moved_on(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + fixture = MainMergedFixture(tmp) + result = fixture.run_script(fixture.base) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn(f"origin/main@{fixture.base} is fully merged", result.stderr) + + def test_commit_missing_from_head_fails(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + fixture = MainMergedFixture(tmp) + result = fixture.run_script(fixture.main_tip) + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn( + f"origin/main@{fixture.main_tip} has 1 commit(s) not merged into HEAD", + result.stderr, + ) + + def test_empty_commit_fails_loudly(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + fixture = MainMergedFixture(tmp) + result = fixture.run_script("") + self.assertEqual(result.returncode, 2, result.stderr) + self.assertIn("must be a full commit SHA", result.stderr) + + +class TestMainMergedLiveTip(unittest.TestCase): + def test_live_tip_missing_from_head_fails(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + fixture = MainMergedFixture(tmp) + result = fixture.run_script(None) + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn( + "origin/main has 1 commit(s) not merged into HEAD", result.stderr + ) + + def test_merged_live_tip_passes(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + fixture = MainMergedFixture(tmp) + fixture.merge_main() + result = fixture.run_script(None) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("origin/main is fully merged into HEAD", result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/tests/test_untracked_files_in_scope.py b/tests/unit/python/tests/test_untracked_files_in_scope.py index ef85777c49..661e576ebb 100644 --- a/tests/unit/python/tests/test_untracked_files_in_scope.py +++ b/tests/unit/python/tests/test_untracked_files_in_scope.py @@ -43,6 +43,8 @@ class _ListingFixture: def git(self, tracked: bytes | Exception, untracked: bytes | Exception): def run(args, **_kwargs): + if "--deleted" in args: + return SimpleNamespace(stdout=b"") listing = untracked if "--others" in args else tracked if isinstance(listing, Exception): raise listing diff --git a/tests/unit/python/utils/cache/test_applications.py b/tests/unit/python/utils/cache/test_applications.py index 717714097b..c9c757eb8a 100644 --- a/tests/unit/python/utils/cache/test_applications.py +++ b/tests/unit/python/utils/cache/test_applications.py @@ -390,7 +390,7 @@ class TestGetMergedApplicationsCarrierFact(unittest.TestCase): merged["web-app-foo"]["services"]["foo"]["image"], "override" ) - def test_a_changed_tokens_file_rejects_the_carrier(self): + def test_a_changed_tokens_file_keeps_the_carrier(self): with tempfile.TemporaryDirectory() as tmp: roles = _seed_minimal_roles(Path(tmp)) tokens = Path(tmp) / "tokens.yml" @@ -398,9 +398,10 @@ class TestGetMergedApplicationsCarrierFact(unittest.TestCase): variables = self._variables() variables["FILE_TOKENS"] = str(tokens) key = merged_applications_cache_key(variables, roles_dir=roles) + carried = {"web-app-foo": {"carried": True}} variables[APPLICATIONS_RENDERED_FACT] = { "key": [key[0], list(key[1])], - "applications": {"web-app-foo": {"carried": True}}, + "applications": carried, } tokens.write_text( "users: {no-reply: {tokens: {web-app-stalwart: minted}}}\n", @@ -409,7 +410,7 @@ class TestGetMergedApplicationsCarrierFact(unittest.TestCase): merged = cache_apps.get_merged_applications( variables=variables, roles_dir=roles, templar=None ) - self.assertNotIn("carried", merged["web-app-foo"]) + self.assertIs(merged, carried) def _park_from_the_tokens_file(self, tmp: Path, token: str) -> tuple: roles = _seed_minimal_roles(tmp) @@ -441,28 +442,31 @@ class TestGetMergedApplicationsCarrierFact(unittest.TestCase): ) self.assertIs(merged, carried) - def test_the_store_fact_with_other_tokens_than_the_file_rejects_the_carrier( + def test_the_store_fact_with_other_tokens_than_the_file_keeps_the_carrier( self, ): with tempfile.TemporaryDirectory() as tmp: - roles, variables, _ = self._park_from_the_tokens_file(Path(tmp), "minted") + roles, variables, carried = self._park_from_the_tokens_file( + Path(tmp), "minted" + ) variables["sys_token_store_users"] = { "no-reply": {"tokens": {"web-app-stalwart": "rotated"}} } merged = cache_apps.get_merged_applications( variables=variables, roles_dir=roles, templar=None ) - self.assertNotIn("carried", merged["web-app-foo"]) + self.assertIs(merged, carried) - def test_a_changed_store_fact_rejects_the_carrier(self): + def test_a_changed_store_fact_keeps_the_carrier(self): with tempfile.TemporaryDirectory() as tmp: roles = _seed_minimal_roles(Path(tmp)) variables = self._variables() variables["sys_token_store_users"] = {} key = merged_applications_cache_key(variables, roles_dir=roles) + carried = {"web-app-foo": {"carried": True}} variables[APPLICATIONS_RENDERED_FACT] = { "key": [key[0], list(key[1])], - "applications": {"web-app-foo": {"carried": True}}, + "applications": carried, } variables["sys_token_store_users"] = { "no-reply": {"tokens": {"web-app-stalwart": "minted"}} @@ -470,7 +474,7 @@ class TestGetMergedApplicationsCarrierFact(unittest.TestCase): merged = cache_apps.get_merged_applications( variables=variables, roles_dir=roles, templar=None ) - self.assertNotIn("carried", merged["web-app-foo"]) + self.assertIs(merged, carried) def test_malformed_carrier_is_ignored(self): with tempfile.TemporaryDirectory() as tmp: diff --git a/tests/unit/python/utils/cache/test_files.py b/tests/unit/python/utils/cache/test_files.py index 42de4006da..468a6bd991 100644 --- a/tests/unit/python/utils/cache/test_files.py +++ b/tests/unit/python/utils/cache/test_files.py @@ -208,7 +208,7 @@ class TestRepositoryFiles(_ProjectRootFixture, unittest.TestCase): _touch(self.root / self.TRACKED, "- y") _touch(self.root / self.CUSTOM, "- x") _touch(self.root / "roles/web-app-cst-demo/__pycache__/x.pyc", "") - with self._git(f"{self.TRACKED}\0".encode()): + with self._git(f"{self.TRACKED}\0".encode(), b""): self.assertEqual( (self.CUSTOM, self.TRACKED), files_module.repository_files(), @@ -217,18 +217,24 @@ class TestRepositoryFiles(_ProjectRootFixture, unittest.TestCase): def test_lists_only_the_tracked_files_without_placed_custom_roles(self) -> None: _touch(self.root / self.TRACKED, "- y") _touch(self.root / "build/install.stamp", "") - with self._git(f"{self.TRACKED}\0".encode()): + with self._git(f"{self.TRACKED}\0".encode(), b""): self.assertEqual((self.TRACKED,), files_module.repository_files()) + def test_leaves_out_a_tracked_file_deleted_in_the_worktree(self) -> None: + gone = "roles/web-app-nextcloud/filter_plugins/gone.py" + with self._git(f"{self.TRACKED}\0{gone}\0".encode(), f"{gone}\0".encode()) as run: + self.assertEqual((self.TRACKED,), files_module.repository_files()) + self.assertEqual(["--deleted"], run.call_args_list[1].args[0][-1:]) + def test_untracked_adds_the_files_gitignore_does_not_exclude(self) -> None: - with self._git(f"{self.TRACKED}\0".encode(), b"new.py\0") as run: + with self._git(f"{self.TRACKED}\0".encode(), b"", b"new.py\0") as run: self.assertEqual( ("new.py", self.TRACKED), files_module.repository_files(untracked=True), ) self.assertEqual( ["--others", "--exclude-standard"], - run.call_args_list[1].args[0][-2:], + run.call_args_list[2].args[0][-2:], ) def test_a_git_failure_propagates(self) -> None: diff --git a/tests/unit/python/utils/cache/users/test_module.py b/tests/unit/python/utils/cache/users/test_module.py index ff71a3b171..c2f283ab95 100644 --- a/tests/unit/python/utils/cache/users/test_module.py +++ b/tests/unit/python/utils/cache/users/test_module.py @@ -14,12 +14,14 @@ from __future__ import annotations import tempfile import textwrap import unittest +import unittest.mock as mock from collections import OrderedDict from pathlib import Path from utils.cache import _reset_cache_for_tests from utils.cache import base as cache_base from utils.cache import users as cache_users +from utils.cache.carrier import USERS_RENDERED_FACT, merged_users_cache_key from utils.cache.users import store as cache_users_store from utils.cache.yaml import dump_yaml_str from utils.domains.default_primary import default_domain_primary @@ -426,6 +428,191 @@ class TestGetMergedUsersTokenSource(unittest.TestCase): self.assertEqual(after["foo"]["tokens"]["web-app-foo"], "minted") +class _Templar: + def __init__(self) -> None: + self.available_variables: dict = {} + + def template(self, value, fail_on_undefined=False): + return value + + +class TestGetMergedUsersCarrierFact(unittest.TestCase): + def setUp(self) -> None: + _reset_cache_for_tests() + + @staticmethod + def _variables(host: str = "h1") -> dict: + return { + "inventory_hostname": host, + "users": {"foo": {"email": "foo@example.org"}}, + cache_users_store.STORE_FACT: { + "foo": {"tokens": {"web-app-foo": "minted"}} + }, + } + + @staticmethod + def _park(roles: Path, variables: dict, payload: dict) -> dict: + key = merged_users_cache_key(variables, roles_dir=roles) + variables[USERS_RENDERED_FACT] = { + "key": [key[0], list(key[1])], + "users": payload, + } + return payload + + @staticmethod + def _merged(roles: Path, variables: dict, templar=None) -> tuple: + with mock.patch.object( + cache_users, + "_render_with_templar", + side_effect=lambda value, **_: {"rendered": value}, + ) as render: + merged = cache_users.get_merged_users( + variables=variables, + roles_dir=roles, + templar=_Templar() if templar is None else templar, + ) + return merged, render.call_count + + def test_matching_key_serves_the_carried_payload_without_rendering(self): + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_user_role(Path(tmp)) + variables = self._variables() + carried = self._park(roles, variables, {"foo": {"carried": True}}) + merged, renders = self._merged(roles, variables) + self.assertIs(merged, carried) + self.assertEqual(renders, 0) + + def test_the_carried_payload_answers_the_rest_of_the_process(self): + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_user_role(Path(tmp)) + variables = self._variables() + carried = self._park(roles, variables, {"foo": {"carried": True}}) + self._merged(roles, variables) + del variables[USERS_RENDERED_FACT] + merged, renders = self._merged(roles, variables) + self.assertIs(merged, carried) + self.assertEqual(renders, 0) + + def test_stale_key_falls_back_to_a_fresh_render(self): + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_user_role(Path(tmp)) + variables = self._variables() + key = merged_users_cache_key(variables, roles_dir=roles) + variables[USERS_RENDERED_FACT] = { + "key": [key[0], ["stale"] * len(key[1])], + "users": {"foo": {"carried": True}}, + } + merged, renders = self._merged(roles, variables) + self.assertEqual(renders, 1) + self.assertEqual(merged["rendered"]["foo"]["email"], "foo@example.org") + + def test_another_hosts_carrier_is_rejected(self): + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_user_role(Path(tmp)) + variables = self._variables("h1") + self._park(roles, variables, {"foo": {"carried": True}}) + variables["inventory_hostname"] = "h2" + merged, renders = self._merged(roles, variables) + self.assertEqual(renders, 1) + self.assertNotIn("carried", merged["rendered"]["foo"]) + + def test_a_rotated_store_token_rejects_the_carrier(self): + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_user_role(Path(tmp)) + variables = self._variables() + self._park(roles, variables, {"foo": {"carried": True}}) + variables[cache_users_store.STORE_FACT] = { + "foo": {"tokens": {"web-app-foo": "rotated"}} + } + merged, renders = self._merged(roles, variables) + self.assertEqual(renders, 1) + self.assertEqual( + merged["rendered"]["foo"]["tokens"]["web-app-foo"], "rotated" + ) + + def _park_from_the_tokens_file(self, tmp: Path, token: str) -> tuple: + roles = _seed_minimal_user_role(tmp) + tokens = tmp / "tokens.yml" + tokens.write_text( + f"users: {{foo: {{tokens: {{web-app-foo: {token}}}}}}}\n", + encoding="utf-8", + ) + variables = self._variables() + del variables[cache_users_store.STORE_FACT] + variables["FILE_TOKENS"] = str(tokens) + carried = self._park(roles, variables, {"foo": {"carried": True}}) + return roles, variables, tokens, carried + + def test_a_changed_tokens_file_rejects_the_carrier(self): + with tempfile.TemporaryDirectory() as tmp: + roles, variables, tokens, _ = self._park_from_the_tokens_file( + Path(tmp), "minted" + ) + tokens.write_text( + "users: {foo: {tokens: {web-app-foo: rotated-token}}}\n", + encoding="utf-8", + ) + merged, renders = self._merged(roles, variables) + self.assertEqual(renders, 1) + self.assertEqual( + merged["rendered"]["foo"]["tokens"]["web-app-foo"], "rotated-token" + ) + + def test_the_store_fact_with_the_file_tokens_keeps_the_carrier(self): + with tempfile.TemporaryDirectory() as tmp: + roles, variables, _, carried = self._park_from_the_tokens_file( + Path(tmp), "minted" + ) + variables[cache_users_store.STORE_FACT] = { + "foo": {"tokens": {"web-app-foo": "minted"}} + } + merged, renders = self._merged(roles, variables) + self.assertIs(merged, carried) + self.assertEqual(renders, 0) + + def test_a_rotated_inventory_password_rejects_the_carrier(self): + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_user_role(Path(tmp)) + variables = self._variables() + variables["users"]["foo"]["password"] = "before" + self._park(roles, variables, {"foo": {"carried": True}}) + variables["users"] = {"foo": {"password": "after"}} + merged, renders = self._merged(roles, variables) + self.assertEqual(renders, 1) + self.assertEqual(merged["rendered"]["foo"]["password"], "after") + + def test_without_a_templar_the_carrier_is_ignored(self): + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_user_role(Path(tmp)) + variables = self._variables() + self._park(roles, variables, {"foo": {"carried": True}}) + merged = cache_users.get_merged_users( + variables=variables, roles_dir=roles, templar=None + ) + self.assertNotIn("carried", merged["foo"]) + self.assertEqual(merged["foo"]["email"], "foo@example.org") + + def test_malformed_carrier_is_ignored(self): + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_user_role(Path(tmp)) + key = merged_users_cache_key(self._variables(), roles_dir=roles) + for carrier in ( + "not-a-mapping", + {"key": "x", "users": {}}, + {"key": [key[0], list(key[1])], "users": "not-a-mapping"}, + {}, + ): + with self.subTest(carrier=carrier): + _reset_cache_for_tests() + variables = self._variables() + variables[USERS_RENDERED_FACT] = carrier + merged, renders = self._merged(roles, variables) + self.assertEqual(renders, 1) + self.assertEqual( + merged["rendered"]["foo"]["email"], "foo@example.org" + ) + + class TestStoreSignature(unittest.TestCase): def setUp(self) -> None: _reset_cache_for_tests() diff --git a/tests/unit/python/utils/networks/test_proxy.py b/tests/unit/python/utils/networks/test_proxy.py index 7afce429f8..a8eb7ae899 100644 --- a/tests/unit/python/utils/networks/test_proxy.py +++ b/tests/unit/python/utils/networks/test_proxy.py @@ -1,10 +1,54 @@ -"""Tests for utils.networks.proxy: resolve_upstream + render_proxy_pass.""" +"""Tests for utils.networks.proxy: resolve_upstream, render_proxy_pass, proxy_hops.""" from __future__ import annotations import unittest -from utils.networks.proxy import render_proxy_pass, resolve_upstream +from utils.networks.proxy import ( + REVERSE_PROXY_APPLICATION_ID, + proxy_hops, + render_proxy_pass, + resolve_upstream, +) + +_APP = "web-app-nextcloud" +_SUBNETS = { + _APP: "192.168.41.0/24", + "svc-db-mariadb": "192.168.201.0/24", + "svc-db-openldap": "192.168.202.0/24", + REVERSE_PROXY_APPLICATION_ID: "192.168.107.0/24", +} +_JOINED = { + "compose": { + _APP: ["svc-db-mariadb", "svc-db-openldap", _APP], + REVERSE_PROXY_APPLICATION_ID: [], + }, + "swarm": { + _APP: [ + "svc-db-mariadb", + "svc-db-openldap", + REVERSE_PROXY_APPLICATION_ID, + _APP, + ], + REVERSE_PROXY_APPLICATION_ID: [REVERSE_PROXY_APPLICATION_ID], + }, +} + + +def _hops(mode: str, joined: dict[str, list[str]] | None = None) -> list[str]: + """``proxy_hops`` over the fixture topology. + + Args: + mode: ``compose`` or ``swarm``. + joined: role id to the networks it joins; ``None`` means ``_JOINED[mode]``. + """ + networks = _JOINED[mode] if joined is None else joined + return proxy_hops( + _APP, + mode, + lambda role: list(networks[role]), + lambda roles: [_SUBNETS[role] for role in roles], + ) def _apps(): @@ -194,5 +238,45 @@ class TestRenderProxyPassGuards(unittest.TestCase): render_proxy_pass("", "swarm") +class TestProxyHopsCompose(unittest.TestCase): + def test_gateway_of_every_network_the_app_joins(self): + self.assertEqual( + _hops("compose"), + ["192.168.41.1", "192.168.201.1", "192.168.202.1"], + ) + + def test_own_network_counts_when_the_app_provides_no_shared_net(self): + joined = {_APP: ["svc-db-mariadb"], REVERSE_PROXY_APPLICATION_ID: []} + self.assertEqual(_hops("compose", joined), ["192.168.41.1", "192.168.201.1"]) + + def test_network_the_app_does_not_join_is_not_trusted(self): + joined = {_APP: [_APP], REVERSE_PROXY_APPLICATION_ID: []} + self.assertEqual(_hops("compose", joined), ["192.168.41.1"]) + + def test_whole_subnets_are_not_trusted(self): + for hop in _hops("compose"): + with self.subTest(hop=hop): + self.assertNotIn("/", hop) + + +class TestProxyHopsSwarm(unittest.TestCase): + def test_subnet_of_the_overlay_shared_with_the_proxy(self): + self.assertEqual(_hops("swarm"), ["192.168.107.0/24"]) + + def test_overlay_only_the_app_joins_is_not_trusted(self): + hops = _hops("swarm") + for role in ("svc-db-mariadb", "svc-db-openldap", _APP): + with self.subTest(role=role): + self.assertNotIn(_SUBNETS[role], hops) + + def test_no_shared_overlay_raises(self): + joined = { + _APP: ["svc-db-mariadb", _APP], + REVERSE_PROXY_APPLICATION_ID: [REVERSE_PROXY_APPLICATION_ID], + } + with self.assertRaises(ValueError): + _hops("swarm", joined) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/utils/roles/applications/test_dashboard.py b/tests/unit/python/utils/roles/applications/test_dashboard.py index 77a6b601a0..4b5d942040 100644 --- a/tests/unit/python/utils/roles/applications/test_dashboard.py +++ b/tests/unit/python/utils/roles/applications/test_dashboard.py @@ -6,7 +6,7 @@ import unittest from ansible.errors import AnsibleError -from utils.roles.applications.dashboard import card_target_key +from utils.roles.applications.dashboard import card_is_displayed, card_target_key class TestCardTargetKey(unittest.TestCase): @@ -42,5 +42,26 @@ class TestCardTargetKey(unittest.TestCase): card_target_key("web-app-foo", {"card": ["element"]}) +class TestCardIsDisplayed(unittest.TestCase): + def test_a_binding_without_the_key_is_displayed(self): + self.assertTrue(card_is_displayed("web-app-foo", {"shared": True})) + + def test_a_missing_binding_is_displayed(self): + self.assertTrue(card_is_displayed("web-app-foo", None)) + + def test_enabled_false_hides_the_card(self): + self.assertFalse(card_is_displayed("web-app-foo", {"enabled": False})) + + def test_enabled_true_shows_the_card(self): + self.assertTrue(card_is_displayed("web-app-foo", {"enabled": True})) + + def test_a_rendered_string_flag_is_read_as_a_boolean(self): + self.assertFalse(card_is_displayed("web-app-foo", {"enabled": "False"})) + + def test_a_non_boolean_flag_fails_loudly(self): + with self.assertRaisesRegex(AnsibleError, "web-app-foo"): + card_is_displayed("web-app-foo", {"enabled": "maybe"}) + + if __name__ == "__main__": unittest.main() diff --git a/utils/cache/README.md b/utils/cache/README.md index aeba13cee2..b4e1bb6ae4 100644 --- a/utils/cache/README.md +++ b/utils/cache/README.md @@ -10,8 +10,8 @@ This package contains the in-process cache layers Infinito.Nexus uses to keep CL | [files.py](files.py) | The project tree's full path list (one walk per process) and per-file UTF-8 contents (`read_text`). Used by lint/integration tests and CLI tools that scan the repo. | | [base.py](base.py) | Cross-cutting helpers: filesystem constants (`PROJECT_ROOT`, `ROLES_DIR`, `DEFAULT_TOKENS_FILE`), `_deep_merge`, cache-key + content-fingerprint signatures, the cross-domain re-entry guard, and the templar-render machinery. The only ansible-coupled symbol is `_render_with_templar`, which lazy-imports its dependency. | | [applications.py](applications.py) | Per-app variants + defaults + `get_merged_applications`. **Strictly ansible-free at import time** so the GitHub Actions runner-host CLI path (`cli.administration.deploy.development.init` β†’ `plan_dev_inventory_matrix` β†’ `get_variants`) keeps working without ansible installed. | -| [carrier.py](carrier.py) | The play-scoped carrier of the rendered applications payload: the fact name `_INFINITO_APPLICATIONS_RENDERED`, `merged_applications_cache_key`, and the reader `get_merged_applications` consults before it renders. | -| `users/` | User definitions, token store hydration, alias materialization, `get_user_defaults`, `get_merged_users` (package; `users/placeholders.py` substitutes `DOMAIN_PRIMARY` / `ORGANIZATION` / `SOFTWARE_NAME` ahead of the templar render pass; `users/store.py` reads the `sys_token_store_users` fact and digests the tokens the users are hydrated from, the digest the users and carrier keys share). | +| [carrier.py](carrier.py) | The play-scoped carriers of the rendered applications and users payloads: the fact names `_INFINITO_APPLICATIONS_RENDERED` and `_INFINITO_USERS_RENDERED`, `merged_applications_cache_key`, `merged_users_cache_key`, and the readers `get_merged_applications` and `get_merged_users` consult before they render. | +| `users/` | User definitions, token store hydration, alias materialization, `get_user_defaults`, `get_merged_users` (package; `users/placeholders.py` substitutes `DOMAIN_PRIMARY` / `ORGANIZATION` / `SOFTWARE_NAME` ahead of the templar render pass; `users/store.py` reads the `sys_token_store_users` fact and digests the tokens the users are hydrated from, the digest the users cache and users carrier keys share). | | [domains.py](domains.py) | Canonical-domains map derived from the merged applications view: `get_merged_domains`. A read issued while the applications render is in progress (the re-entry guard is set) sees the unrendered view, so it is cached under its own key and never answers a later read. | | [`__init__.py`](__init__.py) | Owns the package-level `_reset_cache_for_tests()` orchestrator that clears every cache plus the shared fingerprint memo in one call. | @@ -26,7 +26,7 @@ The layers are orthogonal: `yaml.py` caches "this file's parsed root", the `appl Both layers are process-wide in-process caches. They intentionally do NOT track on-disk file mtimes; CLI tools are short-lived and the assumption "the on-disk file does not change while my process runs" holds. The single exception is `utils.cache.yaml.dump_yaml`, which writes through and evicts the cached entry for the path it just wrote so a tool that edits a file mid-run sees the new content on the next read. -Inside a play the process boundary is the task: Ansible forks a fresh worker per task, so `_MERGED_APPLICATIONS_CACHE` starts empty in every worker. `get_merged_applications` therefore also accepts the play-scoped carrier fact `_INFINITO_APPLICATIONS_RENDERED` (payload plus cache key, parked by the constructor stage and again after every role, every nested application load and every persisted token) and serves it when the key matches. See [applications.md](../../docs/contributing/artefact/files/plugins/lookup/applications.md) for the contract. +Inside a play the process boundary is the task: Ansible forks a fresh worker per task, so `_MERGED_APPLICATIONS_CACHE` and `_MERGED_USERS_CACHE` start empty in every worker. `get_merged_applications` therefore also accepts the play-scoped carrier fact `_INFINITO_APPLICATIONS_RENDERED` (payload plus cache key, parked by the constructor stage and again after every role, every nested application load and every persisted token) and serves it when the key matches. The same action parks `_INFINITO_USERS_RENDERED`, which `get_merged_users` serves to templated reads under the applications key plus the token store digest and `inventory_hostname`. See [applications.md](../../docs/contributing/artefact/files/plugins/lookup/applications.md) and [users.md](../../docs/contributing/artefact/files/plugins/lookup/users.md) for the contract. While one render runs, the re-entry guard also holds that render's unrendered view and its cache key. A nested `get_merged_applications` call from a lookup inside a role template (`config`, `tls`, `domain`, ...) with the same key returns that view instead of copying and merging the role defaults again. The view is shared by every nested call of the render, so callers MUST NOT mutate it. The guard drops it when the render ends. @@ -84,7 +84,7 @@ flowchart TD proc -.->|"TRIP-WIRE: read BEFORE the
host's own fact, so an inherited
entry outranks it"| fact render -.->|"TRIP-WIRE: main process renders
task names for one host; forked
workers inherit that entry"| proc - key -.->|"TRIP-WIRE: carrier.py:68 stringifies
only one side, so a non-scalar key
part silently never matches again"| fact + key -.->|"TRIP-WIRE: carrier.py:121 stringifies
only one side, so a non-scalar key
part silently never matches again"| fact ``` The key covers `group_names`. `domains.py` derives from the applications view and shares that dependency; `users` reads `group_names` nowhere. diff --git a/utils/cache/carrier.py b/utils/cache/carrier.py index 989a0c2fc2..b8fdf5e1d8 100644 --- a/utils/cache/carrier.py +++ b/utils/cache/carrier.py @@ -1,11 +1,12 @@ -"""Play-scoped carrier of the rendered applications payload. +"""Play-scoped carriers of the rendered applications and users payloads. Ansible forks a fresh worker process per task, so the in-process -`_MERGED_APPLICATIONS_CACHE` starts empty in every worker. The constructor -stage renders once and parks the payload plus its cache key in the host fact -named by `APPLICATIONS_RENDERED_FACT`; every later worker inherits that fact -at fork time and `get_merged_applications` serves it instead of rendering. -Ansible-free at import time like the rest of the package. +`_MERGED_APPLICATIONS_CACHE` and `_MERGED_USERS_CACHE` start empty in every +worker. The constructor stage renders once and parks each payload plus its +cache key in the host facts named by `APPLICATIONS_RENDERED_FACT` and +`USERS_RENDERED_FACT`; every later worker inherits those facts at fork time +and `get_merged_applications` / `get_merged_users` serve them instead of +rendering. Ansible-free at import time like the rest of the package. """ from __future__ import annotations @@ -24,6 +25,7 @@ if TYPE_CHECKING: import os APPLICATIONS_RENDERED_FACT = "_INFINITO_APPLICATIONS_RENDERED" +USERS_RENDERED_FACT = "_INFINITO_USERS_RENDERED" def merged_applications_cache_key( @@ -35,21 +37,46 @@ def merged_applications_cache_key( Args: variables: The play's variable scope. Only the subset that - `_stable_variables_signature` reads, and the token store the users - are hydrated from, influence the key. + `_stable_variables_signature` reads influences the key; the token + store keys the users carrier instead (`merged_users_cache_key`). roles_dir: Roles tree the payload is built from; defaults to the repository's `roles/`. Returns: - ``(resolved roles dir, stable variables signature extended by the - token store signature)``. + ``(resolved roles dir, stable variables signature)``. + """ + return ( + _cache_key(_resolve_roles_dir(roles_dir=roles_dir)), + _stable_variables_signature(variables), + ) + + +def merged_users_cache_key( + variables: Mapping[str, Any] | None, + *, + roles_dir: str | os.PathLike[str] | None = None, +) -> tuple[str, tuple]: + """Key under which one rendered users payload stays valid. + + Args: + variables: The play's variable scope. The applications key's inputs, + the token store the users are hydrated from and + ``inventory_hostname`` influence the key. + roles_dir: Roles tree the payload is built from; defaults to the + repository's `roles/`. + + Returns: + ``(resolved roles dir, applications key signature extended by the + token store signature and the host the payload was rendered for)``. """ from .users import _resolve_tokens_file, _store_signature + roles_key, signature = merged_applications_cache_key(variables, roles_dir=roles_dir) tokens = _store_signature(variables, _resolve_tokens_file(variables)) + host = (variables or {}).get("inventory_hostname") return ( - _cache_key(_resolve_roles_dir(roles_dir=roles_dir)), - (*_stable_variables_signature(variables), *(str(part) for part in tokens)), + roles_key, + (*signature, *(str(part) for part in tokens), str(host or "")), ) @@ -64,21 +91,26 @@ def revalidate_tokens_file(variables: Mapping[str, Any] | None) -> None: _revalidate_tokens_file(_resolve_tokens_file(variables)) -def _carried_applications( - variables: Mapping[str, Any], cache_key: tuple[str, tuple] +def _carried( + variables: Mapping[str, Any], + fact: str, + field: str, + cache_key: tuple[str, tuple], ) -> dict[str, Any] | None: - """Return the payload carried in `APPLICATIONS_RENDERED_FACT` when its - key equals *cache_key*, else ``None``. + """Return the payload carried in *fact* when its key equals *cache_key*, + else ``None``. Args: variables: The play's variable scope, read for the carrier fact. + fact: The carrier fact's name. + field: The carrier's payload field. cache_key: The key the caller would render under. """ - carrier = variables.get(APPLICATIONS_RENDERED_FACT) + carrier = variables.get(fact) if not isinstance(carrier, Mapping): return None key = carrier.get("key") - payload = carrier.get("applications") + payload = carrier.get(field) if ( not isinstance(payload, Mapping) or not isinstance(key, (list, tuple)) @@ -92,3 +124,29 @@ def _carried_applications( ]: return None return payload + + +def _carried_applications( + variables: Mapping[str, Any], cache_key: tuple[str, tuple] +) -> dict[str, Any] | None: + """Return the payload carried in `APPLICATIONS_RENDERED_FACT` when its + key equals *cache_key*, else ``None``. + + Args: + variables: The play's variable scope, read for the carrier fact. + cache_key: The key the caller would render under. + """ + return _carried(variables, APPLICATIONS_RENDERED_FACT, "applications", cache_key) + + +def _carried_users( + variables: Mapping[str, Any], cache_key: tuple[str, tuple] +) -> dict[str, Any] | None: + """Return the payload carried in `USERS_RENDERED_FACT` when its key + equals *cache_key*, else ``None``. + + Args: + variables: The play's variable scope, read for the carrier fact. + cache_key: The key the caller would render under. + """ + return _carried(variables, USERS_RENDERED_FACT, "users", cache_key) diff --git a/utils/cache/files.py b/utils/cache/files.py index 15bb488e88..3a7c27e3dd 100644 --- a/utils/cache/files.py +++ b/utils/cache/files.py @@ -208,9 +208,9 @@ def iter_non_ignored_files( def repository_files(*, untracked: bool = False) -> tuple[str, ...]: """Repository-relative POSIX paths of every file ``git ls-files`` lists. - Git ignores the custom roles an inventory pulls into ``roles/``, yet - every scan checks them like in-tree roles, so their files are listed - as well. + A tracked file deleted in the worktree is left out. Git ignores the custom + roles an inventory pulls into ``roles/``, yet every scan checks them like + in-tree roles, so their files are listed as well. Args: untracked: also list the untracked files ``.gitignore`` does not exclude. @@ -220,7 +220,7 @@ def repository_files(*, untracked: bool = False) -> tuple[str, ...]: subprocess.CalledProcessError: git cannot list the files. """ root = str(PROJECT_ROOT) - rels = _git_files() + rels = _git_files() - _git_files("--deleted") if untracked: rels.update(untracked_files()) rels.update( diff --git a/utils/cache/users/__init__.py b/utils/cache/users/__init__.py index 2d51d8332e..5fbb5aa923 100644 --- a/utils/cache/users/__init__.py +++ b/utils/cache/users/__init__.py @@ -27,6 +27,7 @@ from utils.cache.base import ( _resolve_roles_dir, _stable_variables_signature, ) +from utils.cache.carrier import _carried_users, merged_users_cache_key from utils.cache.users import store as _store from utils.cache.users.placeholders import ( substitute_primary_domain_placeholder as _substitute_primary_domain_placeholder, @@ -431,6 +432,15 @@ def get_merged_users( if cached is not None: return cached + if templar is not None and source_variables: + carried = _carried_users( + source_variables, + merged_users_cache_key(source_variables, roles_dir=resolved_roles_dir), + ) + if carried is not None: + _MERGED_USERS_CACHE[cache_key] = carried + return carried + defaults = get_user_defaults(roles_dir=roles_dir) overrides = _resolve_override_mapping(variables, "users", templar=templar) diff --git a/utils/networks/proxy.py b/utils/networks/proxy.py index 30c0ccd4a3..4d795349a2 100644 --- a/utils/networks/proxy.py +++ b/utils/networks/proxy.py @@ -1,4 +1,5 @@ -"""Mode-aware nginx ``proxy_pass`` directive renderer (compose/swarm), SPOT. +"""Mode-aware nginx ``proxy_pass`` directive renderer and the addresses its +requests reach an application from (compose/swarm), SPOT. Trip-wire: the swarm oauth2 endpoint must forward ``$uri$is_args$args``, not ``$request_uri`` β€” during the ``error_page 401 = @oauth2_start`` jump the original @@ -8,14 +9,19 @@ Trip-wire: the swarm oauth2 endpoint must forward ``$uri$is_args$args``, not from __future__ import annotations import re -from typing import Any +from typing import TYPE_CHECKING, Any +from utils.networks.address import subnet_gateway from utils.roles.applications.config import get from utils.roles.entity.name import entity_name +if TYPE_CHECKING: + from collections.abc import Callable + _REGEX_OR_NAMED_LOCATION = re.compile(r"^[@~]") _LOCATION_MODIFIER = re.compile(r"^(?:=|\^~)\s*") _UPSTREAM_VAR = "proxy_pass_upstream" +REVERSE_PROXY_APPLICATION_ID = "svc-prx-openresty" def _as_str(value: Any) -> str: @@ -132,3 +138,42 @@ def render_proxy_pass( f" proxy_pass http://${_UPSTREAM_VAR}{_swarm_tail(tail)};" ) return f"proxy_pass http://{authority}{_compose_suffix(tail, location)};" + + +def proxy_hops( + application_id: str, + deployment_mode: str, + network_roles: Callable[[str], list[str]], + subnets: Callable[[list[str]], list[str]], +) -> list[str]: + """Addresses the reverse proxy's requests reach ``application_id`` from. + + Args: + application_id: the proxied application. + deployment_mode: ``compose`` or ``swarm``, after any per-role override. + network_roles: role id to the provider roles whose networks it joins. + subnets: role ids to their ``networks.local.subnet``, in order. + + Returns: + Under compose the gateway of the application's own network and of + every network it joins: the proxy runs on the host network and reaches + a published port, which Docker forwards from the gateway of whichever + of those networks it routes the container through. Under swarm the + subnets of the overlays the application shares with the proxy, which + reaches it from its task address there. + + Raises: + ValueError: under swarm the application shares no overlay with the + proxy. + """ + if deployment_mode != "swarm": + roles = list(dict.fromkeys([application_id, *network_roles(application_id)])) + return list(dict.fromkeys(subnet_gateway(subnet) for subnet in subnets(roles))) + proxy_networks = network_roles(REVERSE_PROXY_APPLICATION_ID) + shared = [role for role in network_roles(application_id) if role in proxy_networks] + if not shared: + raise ValueError( + f"{application_id} shares no overlay with " + f"{REVERSE_PROXY_APPLICATION_ID}, so no address carries its proxied requests" + ) + return list(dict.fromkeys(subnets(shared))) diff --git a/utils/roles/applications/dashboard.py b/utils/roles/applications/dashboard.py index 403df776e5..a2e31b01d8 100644 --- a/utils/roles/applications/dashboard.py +++ b/utils/roles/applications/dashboard.py @@ -1,9 +1,13 @@ -"""Target of an application's dashboard card. +"""Target and visibility of an application's dashboard card. A role's ``services.dashboard`` binding MAY name ``card: ``, a key of its ``domains.canonical`` mapping. The card, the Apps menu entry and the dashboard tile-reachability target then point at that domain instead of the role's primary domain. + +``enabled: false`` on the same binding takes the application out of the +dashboard: no card and no Apps menu entry, and the tile-reachability targets +and the CSP frame-ancestors already follow the same flag. """ from __future__ import annotations @@ -11,9 +15,39 @@ from __future__ import annotations from typing import Any from ansible.errors import AnsibleError +from ansible.module_utils.parsing.convert_bool import boolean DASHBOARD_SERVICE = "dashboard" CARD_TARGET_KEY = "card" +ENABLED_KEY = "enabled" +ENABLED_PATH = f"services.{DASHBOARD_SERVICE}.{ENABLED_KEY}" + + +def card_is_displayed(application_id: str, dashboard: Any) -> bool: + """Return whether the application's dashboard card is shown. + + Args: + application_id: the role whose binding is read, named in the error. + dashboard: the role's ``services.dashboard`` binding from the merged + applications. + + Returns: + The ``enabled`` flag, or ``True`` when the role declares no binding or + the binding sets none. + + Raises: + AnsibleError: the binding sets ``enabled`` to something that is not a + boolean. + """ + if not isinstance(dashboard, dict) or ENABLED_KEY not in dashboard: + return True + enabled = dashboard[ENABLED_KEY] + try: + return boolean(enabled, strict=True) + except TypeError as exc: + raise AnsibleError( + f"{application_id}: {ENABLED_PATH} must be a boolean, got {enabled!r}" + ) from exc def card_target_key(application_id: str, dashboard: Any) -> str: diff --git a/utils/roles/applications/security_headers.py b/utils/roles/applications/security_headers.py new file mode 100644 index 0000000000..f350bcc626 --- /dev/null +++ b/utils/roles/applications/security_headers.py @@ -0,0 +1,168 @@ +"""Response security headers the front proxy adds for one application. + +``WEBSERVER_SECURITY_HEADERS`` holds the platform values. An application +overrides any of them under ``security_headers`` in its ``meta/server.yml``. +""" + +from __future__ import annotations + +import re +from collections.abc import Mapping +from typing import Any + +from utils.roles.applications.config import get + +HSTS_PRELOAD_MIN_MAX_AGE = 31536000 + +REFERRER_POLICY_TOKENS = frozenset( + { + "no-referrer", + "no-referrer-when-downgrade", + "origin", + "origin-when-cross-origin", + "same-origin", + "strict-origin", + "strict-origin-when-cross-origin", + "unsafe-url", + } +) + +SCHEMA: dict[str, Any] = { + "nosniff": bool, + "referrer_policy": str, + "permissions_policy": str, + "hsts": { + "max_age": int, + "include_subdomains": bool, + "preload": bool, + }, +} + +_FIELD_VALUE = re.compile(r"[\x20-\x7e]*") + + +def _check_type(value: Any, expected: type, where: str) -> None: + if expected is int: + valid = isinstance(value, int) and not isinstance(value, bool) + else: + valid = isinstance(value, expected) + if not valid: + raise TypeError( + f"{where} must be {expected.__name__}, got {type(value).__name__} {value!r}" + ) + + +def _resolve( + schema: Mapping[str, Any], base: Any, override: Any, where: str +) -> dict[str, Any]: + """Validate *override* against *schema* and lay it over *base*. + + Args: + schema: the expected keys and their types. + base: the complete mapping the override applies to, ``None`` when + *override* is the complete mapping itself. + override: the mapping to validate; partial when *base* is given. + where: dotted origin of *override*, for error messages. + + Returns: + A complete mapping with every key of *schema*. + """ + if not isinstance(override, Mapping): + raise TypeError(f"{where} must be a mapping, got {override!r}") + unknown = sorted(set(override) - set(schema)) + if unknown: + raise ValueError(f"{where} has unknown keys {unknown}, known: {sorted(schema)}") + if base is None: + missing = sorted(set(schema) - set(override)) + if missing: + raise ValueError(f"{where} lacks the keys {missing}") + + resolved: dict[str, Any] = {} + for key, expected in schema.items(): + path = f"{where}.{key}" + if key not in override: + resolved[key] = base[key] + elif isinstance(expected, Mapping): + resolved[key] = _resolve( + expected, None if base is None else base[key], override[key], path + ) + else: + _check_type(override[key], expected, path) + resolved[key] = override[key] + return resolved + + +def _field_value(value: str, where: str) -> str: + if not _FIELD_VALUE.fullmatch(value): + raise ValueError(f"{where} must be printable ASCII, got {value!r}") + return value + + +def _referrer_policy(value: str, where: str) -> str: + _field_value(value, where) + if not value: + return value + unknown = [ + token + for token in (part.strip() for part in value.split(",")) + if token not in REFERRER_POLICY_TOKENS + ] + if unknown: + raise ValueError(f"{where} has unknown policy tokens {unknown}") + return value + + +def _hsts(hsts: Mapping[str, Any], where: str) -> str: + if hsts["max_age"] < 0: + raise ValueError(f"{where}.max_age must not be negative") + if hsts["preload"] and not hsts["include_subdomains"]: + raise ValueError(f"{where}.preload requires include_subdomains") + if hsts["preload"] and hsts["max_age"] < HSTS_PRELOAD_MIN_MAX_AGE: + raise ValueError( + f"{where}.preload requires a max_age of at least {HSTS_PRELOAD_MIN_MAX_AGE}" + ) + directives = [f"max-age={hsts['max_age']}"] + if hsts["include_subdomains"]: + directives.append("includeSubDomains") + if hsts["preload"]: + directives.append("preload") + return "; ".join(directives) + + +def security_headers( + applications: Mapping[str, Any], application_id: str, platform: Mapping[str, Any] +) -> dict[str, Any]: + """Return the security header values the proxy sends for *application_id*. + + Args: + applications: the applications SPOT. + application_id: the role whose vhost is rendered; a redirect vhost + passes its domain, which owns no override. + platform: ``WEBSERVER_SECURITY_HEADERS``. + + Returns: + ``nosniff`` as a bool, ``referrer_policy`` and ``permissions_policy`` + as header values (empty when not sent) and ``hsts`` as the complete + ``Strict-Transport-Security`` value. + """ + base = _resolve(SCHEMA, None, platform, "WEBSERVER_SECURITY_HEADERS") + where = f"applications[{application_id!r}].server.security_headers" + override = get( + applications, + application_id, + "server.security_headers", + strict=False, + default={}, + skip_missing_app=True, + ) + resolved = _resolve(SCHEMA, base, override, where) + return { + "nosniff": resolved["nosniff"], + "referrer_policy": _referrer_policy( + resolved["referrer_policy"], f"{where}.referrer_policy" + ), + "permissions_policy": _field_value( + resolved["permissions_policy"], f"{where}.permissions_policy" + ), + "hsts": _hsts(resolved["hsts"], f"{where}.hsts"), + }