From 8a4f4142ff33dcb6a2fdf0df7752b45d59a5847e Mon Sep 17 00:00:00 2001 From: Alejandro Roman Date: Wed, 19 Aug 2026 14:32:56 +0400 Subject: [PATCH] feat(swarm): Fix issues with mailu swarm --- .github/workflows/call-orchestrator.yml | 3 +- pyproject.toml | 4 - .../sys-ctl-mtn-cert-deploy/tasks/00_core.yml | 7 - roles/sys-svc-compose/files/compose.py | 27 +-- .../templates/msmtprc.conf.j2 | 4 +- roles/sys-svc-rdbms/tasks/dedicated.yml | 7 +- roles/web-app-bookwyrm/files/Dockerfile | 5 +- roles/web-app-bridgy-fed/files/Dockerfile | 19 +- .../tasks/03_manager_ops/update_routines.yml | 13 +- .../tasks/update/09_stalwart_webui_client.yml | 1 - .../update/10_stalwart_webmail_client.yml | 1 - .../templates/import/realm.json.j2 | 4 +- roles/web-app-keycloak/vars/main.yml | 8 +- roles/web-app-mailu/meta/services.yml | 12 +- roles/web-app-mailu/tasks/00_core.yml | 3 +- .../02_manager_ops/post_bootstrap_ops.yml | 5 - roles/web-app-mailu/tasks/10_oidc_refresh.yml | 35 +-- roles/web-app-mailu/tasks/main.yml | 3 - roles/web-app-mailu/templates/env.j2 | 1 - roles/web-app-mailu/vars/main.yml | 7 - roles/web-app-postmarks/files/Dockerfile | 9 +- roles/web-app-stalwart/README.md | 24 ++ .../web-app-stalwart/files/playwright/env.js | 26 +++ .../files/playwright/playwright.spec.js | 218 +----------------- .../files/playwright/test-mailflow.js | 62 +++++ .../files/playwright/test-personas.js | 30 +++ .../files/playwright/test-sso.js | 47 ++++ .../files/playwright/test-tls.js | 21 ++ .../files/playwright/webmail.js | 57 +++++ .../files/tests/verify_migration.py | 29 ++- roles/web-app-stalwart/meta/services.yml | 20 +- roles/web-app-stalwart/meta/volumes.yml | 17 +- roles/web-app-stalwart/tasks/00_core.yml | 23 +- .../tasks/01_wait_for_api.yml | 3 - roles/web-app-stalwart/tasks/02_webadmin.yml | 3 +- roles/web-app-stalwart/tasks/06_oidc.yml | 72 ++---- roles/web-app-stalwart/tasks/07_antivirus.yml | 26 +-- .../web-app-stalwart/tasks/09_dns-records.yml | 31 +-- roles/web-app-stalwart/tasks/manager_ops.yml | 15 +- .../jmap/authentication/create.json.j2 | 4 + .../templates/jmap/authentication/get.json.j2 | 4 + .../jmap/authentication/update.json.j2 | 4 + .../jmap/directory/clear_audience.json.j2 | 4 + .../jmap/directory/create_oidc.json.j2 | 11 + .../templates/jmap/directory/get.json.j2 | 4 + .../templates/jmap/milter/create.json.j2 | 12 + .../templates/jmap/milter/get.json.j2 | 4 + .../templates/jmap/milter/update.json.j2 | 9 + .../templates/jmap/rcpt/create.json.j2 | 4 + .../templates/jmap/rcpt/get.json.j2 | 4 + .../templates/jmap/rcpt/update.json.j2 | 4 + .../templates/jmap/role_get.json.j2 | 4 + roles/web-app-stalwart/vars/main.yml | 34 +-- .../templates/Dockerfile.backend.j2 | 4 +- roles/web-app-zammad/vars/main.yml | 2 +- scripts/system/network/dns/common.sh | 21 +- .../services/test_mail_provider_dependency.py | 11 - .../roles/meta/services/test_dynamic_flags.py | 3 - .../dockerfile/apt/test_update_purge_lists.py | 7 +- .../sys-svc-compose/files/test_compose.py | 4 - .../test_files_migrate_from_mailu.py | 6 +- tests/unit/utils/cache/test_files.py | 15 +- tests/unit/utils/templating/test_ansible.py | 2 - utils/github/variant/limits.py | 9 +- 64 files changed, 481 insertions(+), 611 deletions(-) create mode 100644 roles/web-app-stalwart/files/playwright/env.js create mode 100644 roles/web-app-stalwart/files/playwright/test-mailflow.js create mode 100644 roles/web-app-stalwart/files/playwright/test-personas.js create mode 100644 roles/web-app-stalwart/files/playwright/test-sso.js create mode 100644 roles/web-app-stalwart/files/playwright/test-tls.js create mode 100644 roles/web-app-stalwart/files/playwright/webmail.js create mode 100644 roles/web-app-stalwart/templates/jmap/authentication/create.json.j2 create mode 100644 roles/web-app-stalwart/templates/jmap/authentication/get.json.j2 create mode 100644 roles/web-app-stalwart/templates/jmap/authentication/update.json.j2 create mode 100644 roles/web-app-stalwart/templates/jmap/directory/clear_audience.json.j2 create mode 100644 roles/web-app-stalwart/templates/jmap/directory/create_oidc.json.j2 create mode 100644 roles/web-app-stalwart/templates/jmap/directory/get.json.j2 create mode 100644 roles/web-app-stalwart/templates/jmap/milter/create.json.j2 create mode 100644 roles/web-app-stalwart/templates/jmap/milter/get.json.j2 create mode 100644 roles/web-app-stalwart/templates/jmap/milter/update.json.j2 create mode 100644 roles/web-app-stalwart/templates/jmap/rcpt/create.json.j2 create mode 100644 roles/web-app-stalwart/templates/jmap/rcpt/get.json.j2 create mode 100644 roles/web-app-stalwart/templates/jmap/rcpt/update.json.j2 create mode 100644 roles/web-app-stalwart/templates/jmap/role_get.json.j2 diff --git a/.github/workflows/call-orchestrator.yml b/.github/workflows/call-orchestrator.yml index 01e45de93a..0859194abd 100644 --- a/.github/workflows/call-orchestrator.yml +++ b/.github/workflows/call-orchestrator.yml @@ -465,9 +465,8 @@ jobs: blacklist: ${{ inputs.priority }} exclude_compose_covered: ${{ contains(inputs.modes, 'compose') && 'true' || 'false' }} - # Exception: opt-in job — the called workflow gates itself on the forwarded - # test_migration input or the INFINITO_TEST_MIGRATION repository variable. test-deploy-migration: + if: ${{ inputs.test_migration == 'true' || vars.INFINITO_TEST_MIGRATION == 'true' }} needs: - test-dns - images-mirror-missing diff --git a/pyproject.toml b/pyproject.toml index 0db510cfcb..8e883bbfcc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -191,10 +191,6 @@ ignore = [ "roles/sys-ctl-rpr-container-hard/files/script.py" = ["PTH"] "roles/sys-ctl-rpr-container-soft/files/script.py" = ["PTH"] -# Role-local migration test fixtures: assert IS their verification mechanism — -# same test-script latitude as ``tests/**`` above. -"roles/web-app-stalwart/files/tests/*.py" = ["S101"] - # BLE001 (flake8-blind-except) ratchet. # Broad `except Exception:` is now selected project-wide so NEW code is # gated. Standalone role scripts under ``roles/*/files/`` legitimately diff --git a/roles/sys-ctl-mtn-cert-deploy/tasks/00_core.yml b/roles/sys-ctl-mtn-cert-deploy/tasks/00_core.yml index 706e18bdf5..9f0914fb54 100644 --- a/roles/sys-ctl-mtn-cert-deploy/tasks/00_core.yml +++ b/roles/sys-ctl-mtn-cert-deploy/tasks/00_core.yml @@ -20,13 +20,6 @@ --chdir {{ lookup('container', application_id, 'directories.instance') }} --project {{ (lookup('container', application_id, 'directories.instance') | regex_replace('/+$', '')) | basename }} -# Exception: local mode checks the material the unit just deployed (parses, -# key matches, not expiring); remote mode checks live endpoints from -# CERT_TEST_REMOTE_ENDPOINTS ("host[:port] ...", fed via CI/GitHub variables) -# so a misconfigured production server fails here. -# Exception: script (not command) — the play may target a remote swarm -# manager where the controller-local role_path does not exist; script -# transfers the file before running it. - name: "✅ Verify deployed certificate material" ansible.builtin.script: cmd: "{{ [ role_path, 'files/test.sh' ] | path_join }} {{ lookup('container', application_id, 'directories.instance') }}" diff --git a/roles/sys-svc-compose/files/compose.py b/roles/sys-svc-compose/files/compose.py index 0e9fe6c890..91de1ca82c 100755 --- a/roles/sys-svc-compose/files/compose.py +++ b/roles/sys-svc-compose/files/compose.py @@ -7,8 +7,7 @@ import shlex import sys from pathlib import Path -# Exception: `utils.cache.yaml` is unavailable here — this file is -# copy-deployed. +# `utils.cache.yaml` is unavailable here: this file is copy-deployed. import yaml @@ -78,9 +77,9 @@ def detect_compose_files(project_dir: Path) -> list[Path]: return files -# Exception: mirrors that speak HTTP by default in their distro's -# package-manager config. Alpine 3.18+ defaults to HTTPS and would fail TLS -# verification inside builds that lack the frontend CA, so it is excluded. +# Mirrors that speak HTTP by default in their distro's package-manager +# config. Alpine 3.18+ defaults to HTTPS and would fail TLS verification +# inside builds that lack the frontend CA, so it is excluded. _CACHE_HTTP_HOSTNAMES = ( "deb.debian.org", "archive.ubuntu.com", @@ -142,18 +141,16 @@ def resolve_files(project_dir: Path, files: list[str]) -> list[Path]: return out -# Exception: subcommands that parse service `env_file:` values. Compose's env -# parser rejects $-bearing secrets, but the swarm dotenv keeps $ literal -# because `docker stack deploy` does NOT parse env_file. build/config need no -# runtime env, so they get env_file-stripped copies (and no --env-file) -# instead. +# Subcommands that parse service `env_file:` values. Compose's env parser +# rejects $-bearing secrets, but the swarm dotenv keeps $ literal because +# `docker stack deploy` does NOT parse env_file. build/config need no runtime +# env, so they get env_file-stripped copies (and no --env-file) instead. _ENV_PARSING_SUBCOMMANDS = {"build", "config"} def _subcommand(passthrough: list[str]) -> str: - # Exception: the docker compose subcommand is the first passthrough token - # (main() strips a leading `--`; the wrapper's own flags are parsed off - # earlier). + # The docker compose subcommand is the first passthrough token (main() + # strips a leading `--`; the wrapper's own flags are parsed off earlier). return passthrough[0] if passthrough else "" @@ -291,8 +288,8 @@ def main() -> int: if args.debug: print(">>> " + " ".join(shlex.quote(x) for x in cmd), file=sys.stderr) - # Exception: execvp preserves signal handling under systemd. The argv list - # is built from this script's own argv plus `--env-file` / `--profile` + # execvp preserves signal handling under systemd. The argv list is + # built from this script's own argv plus `--env-file` / `--profile` # additions; no shell parses it. os.execvp(cmd[0], cmd) # noqa: S606 return 0 diff --git a/roles/sys-svc-mail-msmtp/templates/msmtprc.conf.j2 b/roles/sys-svc-mail-msmtp/templates/msmtprc.conf.j2 index 0bcb035b0e..8fa4951eb6 100644 --- a/roles/sys-svc-mail-msmtp/templates/msmtprc.conf.j2 +++ b/roles/sys-svc-mail-msmtp/templates/msmtprc.conf.j2 @@ -1,8 +1,6 @@ {% set email = lookup('email') %} defaults -# Exception: EHLO/HELO identity must be a valid FQDN — strict servers (e.g. -# Stalwart) reject a bare container hostname on port 25 (rejectNonFqdn), so -# pin it to the domain. +# Exception: strict servers (Stalwart rejectNonFqdn) refuse a bare container hostname as EHLO. domain {{ DOMAIN_PRIMARY }} logfile ~/.msmtp.log timeout {{ email.timeout }} diff --git a/roles/sys-svc-rdbms/tasks/dedicated.yml b/roles/sys-svc-rdbms/tasks/dedicated.yml index 454d3891d1..350d91694e 100644 --- a/roles/sys-svc-rdbms/tasks/dedicated.yml +++ b/roles/sys-svc-rdbms/tasks/dedicated.yml @@ -15,12 +15,7 @@ include_tasks: dedicated_postgres.yml when: _database_type == 'postgres' -# Exception: without this row baudolo has no credentials for the embedded -# sidecar, silently falls back to a FILE snapshot of the live database volume, -# and the restore drill replays a torn data dir (postgres PANICs on a missing -# checkpoint record). Mirrors the central-path seed in main.yml; the instance -# resolves to the consumer entity, matching baudolo's `-database` -# container-name derivation. +# Exception: without this row baudolo silently falls back to a live-file snapshot and the restore replays a torn data dir. - name: "➕ For '{{ _database_consumer_id }}': Add Entry for Backup Procedure" include_tasks: "{{ lookup('path_absolute', 'roles/svc-bkp-volume-2-local/tasks/03_seed-database-to-backup.yml') }}" vars: diff --git a/roles/web-app-bookwyrm/files/Dockerfile b/roles/web-app-bookwyrm/files/Dockerfile index c86f54f0f7..6ca5960bc2 100644 --- a/roles/web-app-bookwyrm/files/Dockerfile +++ b/roles/web-app-bookwyrm/files/Dockerfile @@ -3,7 +3,7 @@ ARG BOOKWYRM_IMAGE ARG BOOKWYRM_VERSION FROM ${BOOKWYRM_IMAGE}:${BOOKWYRM_VERSION} AS builder -# Exception: libsass-dev + SYSTEM_SASS=True avoids the in-tree libsass build (~25 min on arm64). +# libsass-dev + SYSTEM_SASS=True avoids the in-tree libsass build (~25 min on arm64). RUN rm -rf /var/lib/apt/lists/* \ && apt-get -o Acquire::Retries=3 update && apt-get -o Acquire::Retries=3 install -y --no-install-recommends \ git build-essential libpq-dev \ @@ -18,6 +18,7 @@ ARG BOOKWYRM_REPOSITORY ARG BOOKWYRM_REF RUN git clone --depth=1 --branch "${BOOKWYRM_REF}" "${BOOKWYRM_REPOSITORY}" . +# Resolve PEP 735 `[dependency-groups].main` into an isolated venv. RUN python -m venv /venv \ && /venv/bin/pip install --upgrade "pip>=25.1.0" \ && /venv/bin/pip install --group main @@ -29,7 +30,7 @@ ENV PATH=/venv/bin:$PATH ENV SYSTEM_SASS=True WORKDIR /app -# Exception: libsass1 must stay in the runtime stage — SYSTEM_SASS links against it. +# libsass1 is the runtime sibling of the build-time libsass-dev. RUN rm -rf /var/lib/apt/lists/* \ && apt-get -o Acquire::Retries=3 update && apt-get -o Acquire::Retries=3 install -y --no-install-recommends \ libpq5 curl \ diff --git a/roles/web-app-bridgy-fed/files/Dockerfile b/roles/web-app-bridgy-fed/files/Dockerfile index 45c7dcc44c..15e6b00ec4 100644 --- a/roles/web-app-bridgy-fed/files/Dockerfile +++ b/roles/web-app-bridgy-fed/files/Dockerfile @@ -5,6 +5,7 @@ FROM ${PY_BASE} AS build ARG BRIDGY_REPO_URL ARG BRIDGY_REF +# System deps: git, build tools, curl for healthchecks, and gunicorn RUN rm -rf /var/lib/apt/lists/* && \ apt-get -o Acquire::Retries=3 update && apt-get -o Acquire::Retries=3 install -y --no-install-recommends \ git build-essential curl ca-certificates && \ @@ -13,11 +14,11 @@ RUN rm -rf /var/lib/apt/lists/* && \ WORKDIR /app RUN git clone --depth=1 --branch "${BRIDGY_REF}" "${BRIDGY_REPO_URL}" ./ +# Python deps RUN pip install --upgrade pip && \ pip install --no-cache-dir -r requirements.txt -# Exception: upstream expects the /app/oauth_dropins_static symlink; without it -# the oauth_dropins static assets 404 at runtime. +# Create oauth_dropins static symlink (upstream expects this) RUN python - <<'PY' import oauth_dropins, pathlib, os target = pathlib.Path(oauth_dropins.__file__).parent / 'static' @@ -31,10 +32,10 @@ except FileExistsError: print('Symlinked oauth_dropins_static ->', target) PY -# Exception: the final stage must carry over the application directory AND the -# python site-packages from the build stage so gunicorn / bridgy-fed deps are -# present at runtime; otherwise the entrypoint exits with `gunicorn: not found` -# and the container restarts forever. +# Final stage. Carry over the application directory AND the python +# site-packages from the build stage so gunicorn / bridgy-fed deps +# are present at runtime; otherwise the entrypoint exits with +# `gunicorn: not found` and the container restarts forever. FROM ${PY_BASE} ARG CONTAINER_PORT @@ -42,13 +43,15 @@ ENV PORT=${CONTAINER_PORT} WORKDIR /app COPY --from=build /app /app -# Exception: carry the entire /usr/local layer over (Python's site-packages and -# bin scripts), so the python-version-specific path (python3.14, python3.12, …) +# Carry the entire /usr/local layer over (Python's site-packages and bin +# scripts), so the python-version-specific path (python3.14, python3.12, …) # does not have to be hardcoded. COPY --from=build /usr/local /usr/local +# Non-root good practice RUN useradd -r -m -d /nonroot appuser && chown -R appuser:appuser /app USER appuser EXPOSE ${PORT} +# Upstream flask app entry: 'flask_app:app' CMD ["sh", "-lc", "exec gunicorn -w 2 -k gthread -b 0.0.0.0:${PORT} flask_app:app"] diff --git a/roles/web-app-keycloak/tasks/03_manager_ops/update_routines.yml b/roles/web-app-keycloak/tasks/03_manager_ops/update_routines.yml index da87cad8e9..9af2f61dde 100644 --- a/roles/web-app-keycloak/tasks/03_manager_ops/update_routines.yml +++ b/roles/web-app-keycloak/tasks/03_manager_ops/update_routines.yml @@ -47,13 +47,14 @@ include_tasks: "{{ role_path }}/tasks/update/08_users/email_verified.yml" when: KEYCLOAK_USER_EMAILS_VERIFIED | bool -- name: "📂 Ensure the stalwart-webui public client (existing realms)" - include_tasks: "{{ role_path }}/tasks/update/09_stalwart_webui_client.yml" - when: KEYCLOAK_STALWART_WEBUI_ENABLED | bool +- name: "📂 Ensure the stalwart clients (existing realms)" + when: KEYCLOAK_STALWART_ENABLED | bool + block: + - name: "📂 Ensure the stalwart-webui public client" + include_tasks: "{{ role_path }}/tasks/update/09_stalwart_webui_client.yml" -- name: "📂 Ensure the stalwart-webmail confidential client (existing realms)" - include_tasks: "{{ role_path }}/tasks/update/10_stalwart_webmail_client.yml" - when: KEYCLOAK_STALWART_WEBMAIL_ENABLED | bool + - name: "📂 Ensure the stalwart-webmail confidential client" + include_tasks: "{{ role_path }}/tasks/update/10_stalwart_webmail_client.yml" - name: "⏳ Reap the remaining Keycloak update jobs" ansible.builtin.include_tasks: utils/async/reap.yml diff --git a/roles/web-app-keycloak/tasks/update/09_stalwart_webui_client.yml b/roles/web-app-keycloak/tasks/update/09_stalwart_webui_client.yml index 886229238c..aeaccd2aed 100644 --- a/roles/web-app-keycloak/tasks/update/09_stalwart_webui_client.yml +++ b/roles/web-app-keycloak/tasks/update/09_stalwart_webui_client.yml @@ -23,4 +23,3 @@ # rationale: async; nothing reads the client back in this chain, reaped at the end of update_routines.yml async: "{{ ASYNC_TIME if ASYNC_ENABLED | bool else omit }}" poll: "{{ ASYNC_POLL if ASYNC_ENABLED | bool else omit }}" - when: KEYCLOAK_STALWART_WEBUI_ENABLED | bool diff --git a/roles/web-app-keycloak/tasks/update/10_stalwart_webmail_client.yml b/roles/web-app-keycloak/tasks/update/10_stalwart_webmail_client.yml index 55d9d21b4e..6559fcdb79 100644 --- a/roles/web-app-keycloak/tasks/update/10_stalwart_webmail_client.yml +++ b/roles/web-app-keycloak/tasks/update/10_stalwart_webmail_client.yml @@ -24,4 +24,3 @@ # rationale: async; nothing reads the client back in this chain, reaped at the end of update_routines.yml async: "{{ ASYNC_TIME if ASYNC_ENABLED | bool else omit }}" poll: "{{ ASYNC_POLL if ASYNC_ENABLED | bool else omit }}" - when: KEYCLOAK_STALWART_WEBMAIL_ENABLED | bool diff --git a/roles/web-app-keycloak/templates/import/realm.json.j2 b/roles/web-app-keycloak/templates/import/realm.json.j2 index 47a14e11b5..3769c11345 100644 --- a/roles/web-app-keycloak/templates/import/realm.json.j2 +++ b/roles/web-app-keycloak/templates/import/realm.json.j2 @@ -791,10 +791,8 @@ ] }, {% include "clients/default.json.j2" %} -{% if KEYCLOAK_STALWART_WEBUI_ENABLED | bool %} +{% if KEYCLOAK_STALWART_ENABLED | bool %} ,{% include "clients/stalwart/webui.json.j2" %} -{% endif %} -{% if KEYCLOAK_STALWART_WEBMAIL_ENABLED | bool %} ,{% include "clients/stalwart/webmail.json.j2" %} {% endif %} ], diff --git a/roles/web-app-keycloak/vars/main.yml b/roles/web-app-keycloak/vars/main.yml index 0856f08141..fb1ea97ad9 100644 --- a/roles/web-app-keycloak/vars/main.yml +++ b/roles/web-app-keycloak/vars/main.yml @@ -116,16 +116,10 @@ KEYCLOAK_USER_EMAILS_VERIFIED: "{{ lookup('config', application_id, 'services.ke KEYCLOAK_MOODLE_ENABLED: "{{ 'web-app-moodle' in group_names }}" -# Exception: the WebAdmin SPA hardcodes its client_id, so provision a matching -# public (PKCE) client. Client ids are self-declared by web-app-stalwart -# (services.sso.oidc.*_client_id) — one SPOT for both roles. # Todo: replace these gates with self-declaration. -KEYCLOAK_STALWART_WEBUI_ENABLED: "{{ 'web-app-stalwart' in group_names }}" +KEYCLOAK_STALWART_ENABLED: "{{ 'web-app-stalwart' in group_names }}" KEYCLOAK_STALWART_WEBUI_CLIENT_ID: "{{ lookup('config', 'web-app-stalwart', 'services.sso.oidc.webui_client_id') }}" -# Exception: Roundcube confidential client — needs a small access token (no -# roles/groups) so its XOAUTH2 SASL line fits Stalwart's 4096-byte SMTP limit. -KEYCLOAK_STALWART_WEBMAIL_ENABLED: "{{ 'web-app-stalwart' in group_names }}" KEYCLOAK_STALWART_WEBMAIL_CLIENT_ID: "{{ lookup('config', 'web-app-stalwart', 'services.sso.oidc.webmail_client_id') }}" KEYCLOAK_STALWART_WEBMAIL_BASE: "{{ lookup('tls', 'web-app-stalwart', 'protocols.web') ~ '://' ~ lookup('config', 'web-app-stalwart', 'domains.canonical.webmail') }}" KEYCLOAK_STALWART_WEBMAIL_REDIRECT_URIS: diff --git a/roles/web-app-mailu/meta/services.yml b/roles/web-app-mailu/meta/services.yml index 4b7e582ea4..f5233f0d8a 100644 --- a/roles/web-app-mailu/meta/services.yml +++ b/roles/web-app-mailu/meta/services.yml @@ -20,10 +20,7 @@ matomo: bond: 1 enabled: "{{ 'web-app-matomo' in group_names }}" shared: "{{ 'web-app-matomo' in group_names }}" -# Exception: gate on web-app-stalwart, never MAIL_PROVIDER — a Mailu-active -# deploy must not pull stalwart into the closure. `email` is a covered key of -# this role, but the entry must never gate on self, so only a legacy-Mailu -# deploy pulls the active provider in. +# Exception: gates on the OTHER provider — gating on MAIL_PROVIDER or self would pull Stalwart into a Mailu-active closure. # nocheck: dynamic-flag email: bond: 1 @@ -41,12 +38,6 @@ mailu: placement: manager enabled: true # nocheck: dynamic-flag shared: true - # Rationale: the static `email` provider slot belongs to the default - # (web-app-stalwart); the registry allows only one. Mailu is selected at - # runtime via MAIL_PROVIDER, which routes lookup('email') + consumer mail - # flags here instead. `covers` makes the consumers' `services.email` - # declaration satisfy their `run_after: web-app-mailu` entry (consumers run - # after BOTH providers). covers: - email version: "2024.06" @@ -81,7 +72,6 @@ mailu: service_key: front run_after: - web-app-matomo - # Rationale: the mail provider must preload first (sys-svc-mail asserts its token). - web-app-stalwart lifecycle: beta cpus: "1.0" diff --git a/roles/web-app-mailu/tasks/00_core.yml b/roles/web-app-mailu/tasks/00_core.yml index 18dfcce05e..9686e99d33 100644 --- a/roles/web-app-mailu/tasks/00_core.yml +++ b/roles/web-app-mailu/tasks/00_core.yml @@ -48,8 +48,7 @@ compose_handlers_flush: true webserver_vhost_flavour: "basic" webserver_extra_configuration: "client_max_body_size 31M;" - # Exception: own canonical, NOT MAILU_HOSTNAME — in legacy mode the latter - # is the active provider's vhost and writing it would clobber that provider. + # Exception: MAILU_HOSTNAME here would clobber the active provider's vhost in legacy mode. domain: "{{ MAILU_CANONICAL_HOST }}" - name: "👔 Mailu manager-side operations (file deploys + container exec)" diff --git a/roles/web-app-mailu/tasks/02_manager_ops/post_bootstrap_ops.yml b/roles/web-app-mailu/tasks/02_manager_ops/post_bootstrap_ops.yml index fda4a9551c..3bb958bfe6 100644 --- a/roles/web-app-mailu/tasks/02_manager_ops/post_bootstrap_ops.yml +++ b/roles/web-app-mailu/tasks/02_manager_ops/post_bootstrap_ops.yml @@ -37,9 +37,6 @@ - name: "📂 Include Cert deploy service for '{{ role_name }}'" include_role: name: sys-ctl-mtn-cert-deploy - # Exception: active provider only — the cert-deploy unit is shared - # (run-once) and a legacy instance runs TLS_FLAVOR=notls behind the proxy - # anyway. when: - lookup('tls', application_id, 'enabled') | bool - MAILU_ACTIVE_PROVIDER | bool @@ -53,8 +50,6 @@ - name: 🔧 Set Mailu DNS records include_tasks: ../08_dns-records.yml -# Exception: refresh-or-defer — a /sso hit before Keycloak is up poisons the -# cached discovery. - name: "🔐 Apply Mailu OIDC provider config" include_tasks: ../09_oidc_apply.yml when: MAILU_OIDC_ENABLED | bool diff --git a/roles/web-app-mailu/tasks/10_oidc_refresh.yml b/roles/web-app-mailu/tasks/10_oidc_refresh.yml index 427f89f6db..d48ace3feb 100644 --- a/roles/web-app-mailu/tasks/10_oidc_refresh.yml +++ b/roles/web-app-mailu/tasks/10_oidc_refresh.yml @@ -3,36 +3,25 @@ # provider config on the first /sso request and caches a failure until restart. - name: "⏳ Wait for the OIDC issuer discovery endpoint" - ansible.builtin.command: - argv: - - "{{ BIN_COMPOSE }}" - - exec - - -T - - admin - - curl - - -ksS - - -o - - /dev/null - - -w - - "%{http_code}" - - "{{ OIDC.CLIENT.DISCOVERY_DOCUMENT }}" - args: - chdir: "{{ MAILU_INSTANCE_DIR }}" + ansible.builtin.shell: >- + container exec -i {{ MAILU_ADMIN_CONTAINER_ADDRESS }} + {{ 30 | curl }} -ksS -o /dev/null -w "%{http_code}" {{ OIDC.CLIENT.DISCOVERY_DOCUMENT }} register: mailu_oidc_issuer_probe changed_when: false retries: 30 delay: 5 until: mailu_oidc_issuer_probe.stdout == '200' -- name: "🔄 Restart Mailu admin so the OIDC provider config is re-fetched" - ansible.builtin.command: - argv: - - "{{ BIN_COMPOSE }}" - - restart - - admin - args: - chdir: "{{ MAILU_INSTANCE_DIR }}" +- name: "🔄 Restart Mailu admin so the OIDC provider config is re-fetched (compose)" + ansible.builtin.command: "container restart {{ MAILU_ADMIN_CONTAINER_ADDRESS }}" changed_when: true + when: DEPLOYMENT_MODE == 'compose' + +- name: "🔄 Restart Mailu admin so the OIDC provider config is re-fetched (swarm)" + ansible.builtin.command: "container service update --force {{ lookup('container_service', application_id, 'admin') }}" + changed_when: true + timeout: "{{ lookup('timeout', 600) | int }}" + when: DEPLOYMENT_MODE == 'swarm' - name: "🧹 Clear the deferred OIDC refresh flag" ansible.builtin.set_fact: diff --git a/roles/web-app-mailu/tasks/main.yml b/roles/web-app-mailu/tasks/main.yml index 998f66df60..94b30f055c 100644 --- a/roles/web-app-mailu/tasks/main.yml +++ b/roles/web-app-mailu/tasks/main.yml @@ -4,9 +4,6 @@ vars: application_id: "web-app-mailu" -# Exception: re-entry from the service-loader post-load flush (queued in -# 09_oidc_apply when the OIDC issuer was not yet deployed — Keycloak loads -# after mail roles). - include_tasks: 10_oidc_refresh.yml when: - run_once_web_app_mailu is defined diff --git a/roles/web-app-mailu/templates/env.j2 b/roles/web-app-mailu/templates/env.j2 index 57c459c32d..e86ca8bc92 100644 --- a/roles/web-app-mailu/templates/env.j2 +++ b/roles/web-app-mailu/templates/env.j2 @@ -4,7 +4,6 @@ LD_PRELOAD= SECRET_KEY={{ MAILU_SECRET_KEY }} SUBNET={{ MAILU_SUBNET }} DOMAIN={{ MAILU_DOMAIN }} -# Exception: the served vhost — heviat's OIDC redirect refuses request Hosts outside this list. HOSTNAMES={{ MAILU_CANONICAL_HOST }} POSTMASTER=admin TLS_FLAVOR={{ MAILU_TLS_FLAVOR }} diff --git a/roles/web-app-mailu/vars/main.yml b/roles/web-app-mailu/vars/main.yml index 1e4eb6f334..a2e36303a4 100644 --- a/roles/web-app-mailu/vars/main.yml +++ b/roles/web-app-mailu/vars/main.yml @@ -12,15 +12,8 @@ MAILU_DOMAIN: "{{ lookup('config', application_id, 'services.mailu.domain') }}" MAILU_DOMAIN_DNS_ZONE: "{{ MAILU_DOMAIN | to_zone }}" MAILU_EMAIL: "{{ lookup('email', application_id) }}" MAILU_HOSTNAME: "{{ MAILU_EMAIL.host }}" -# Exception: the vhost this instance is actually served under — mail. when -# active MAIL_PROVIDER, legacy-mail. otherwise (see meta/server.yml). -# MAILU_HOSTNAME stays the mail identity (MX/SPF/PTR) and may belong to the -# active provider. MAILU_CANONICAL_HOST: "{{ lookup('domain', application_id) }}" MAILU_ACTIVE_PROVIDER: "{{ MAIL_PROVIDER == application_id }}" -# Exception: legacy instances terminate TLS at the proxy only — no public mail -# ports, no own cert stack (the shared cert-deploy unit belongs to the active -# provider). MAILU_TLS_FLAVOR: "{{ (MAILU_EMAIL.tls and MAILU_ACTIVE_PROVIDER | bool) | ternary('mail', 'notls') }}" MAILU_HOSTNAME_DNS_ZONE: "{{ MAILU_HOSTNAME | to_zone }}" MAILU_VERSION: "{{ lookup('config', application_id, 'services.mailu.version') }}" diff --git a/roles/web-app-postmarks/files/Dockerfile b/roles/web-app-postmarks/files/Dockerfile index 60ba2c48ad..a06623bd33 100644 --- a/roles/web-app-postmarks/files/Dockerfile +++ b/roles/web-app-postmarks/files/Dockerfile @@ -15,14 +15,14 @@ WORKDIR /app RUN git clone --depth=1 --branch "${POSTMARKS_REF}" "${POSTMARKS_REPO_URL}" ./ RUN npm install --no-fund --no-audit --omit=dev -# Exception: trusted-header SSO bridge patched into upstream's server.js at -# build time; it self-gates at runtime on PROXY_HEADER_SSO. +# Trusted-header SSO bridge (gated at runtime on PROXY_HEADER_SSO). COPY header_auth.js /app/src/sso-header-auth.js COPY patch_server.js /app/sso-patch-server.js RUN node /app/sso-patch-server.js /app/server.js && rm -f /app/sso-patch-server.js -# Exception: the final stage must carry over the application directory and the -# npm install artefacts; without them node_modules is missing at runtime. +# Final stage. Carry over the application directory and the npm +# install artefacts so Postmarks does not have to refetch packages +# at runtime. FROM ${NODE_BASE} ARG CONTAINER_PORT @@ -32,6 +32,7 @@ ENV NODE_ENV=production WORKDIR /app COPY --from=build /app /app +# Non-root good practice RUN useradd -r -m -d /nonroot appuser && chown -R appuser:appuser /app USER appuser diff --git a/roles/web-app-stalwart/README.md b/roles/web-app-stalwart/README.md index 851e1ced9f..858d602914 100644 --- a/roles/web-app-stalwart/README.md +++ b/roles/web-app-stalwart/README.md @@ -165,6 +165,30 @@ Stalwart serves DAV natively on the mail HTTP listener — no extra container `https://mail./dav/cal` and `/dav/card`. Authenticate with the mailbox account (or the Keycloak SSO token when SSO is enabled). +## Design Decisions + +- **Client ports are implicit-TLS only (465/993/995).** Stalwart's default + configuration binds no STARTTLS listeners, so the role neither publishes + 587/143/110 nor advertises them via SRV records. +- **The WebUI (WebAdmin) bundle is staged by the controller.** Stalwart fetches + it from GitHub on first boot, which fails behind restricted egress; the + controller downloads it into a host-level cache (matrix rounds purge the + instance dir, and per-round downloads hit GitHub rate limits) and bind-mounts + it read-only. `webui_version` in `meta/services.yml` MUST be bumped together + with the Stalwart `version`. +- **The embedded PostgreSQL pins the plain `postgres` image** — the platform's + postgis default defeats baudolo's substring database detection and would + degrade backups to torn live-file snapshots. `backup.project_hard_restart` + brings the whole project back through one coherent restart after baudolo's + per-volume stop/start cycles. +- **ClamAV runs fail-open with short milter timeouts** so mail keeps flowing + while clamd warms its signature database instead of blocking the DATA stage. +- **`config.json` is bootstrap-only** (data store selection); all other + configuration lives in the database and is provisioned over JMAP + (`templates/jmap/*.json.j2`). +- **Under SSO, trusted internal networks relay without SMTP AUTH** — the + no-reply bot has no password once the auth directory is OIDC. + ## Features - All-in-one mail server (SMTP/IMAP/JMAP/POP3/ManageSieve) diff --git a/roles/web-app-stalwart/files/playwright/env.js b/roles/web-app-stalwart/files/playwright/env.js new file mode 100644 index 0000000000..35699c07ee --- /dev/null +++ b/roles/web-app-stalwart/files/playwright/env.js @@ -0,0 +1,26 @@ +const { decodeDotenvQuotedValue } = require("./personas"); + +const appBaseUrl = decodeDotenvQuotedValue(process.env.APP_BASE_URL || "").replace(/\/+$/, ""); +const webmailBaseUrl = decodeDotenvQuotedValue(process.env.WEBMAIL_BASE_URL || "").replace(/\/+$/, ""); +const canonicalDomain = decodeDotenvQuotedValue(process.env.CANONICAL_DOMAIN || ""); +const oidcIssuerUrl = decodeDotenvQuotedValue(process.env.OIDC_ISSUER_URL || ""); +const adminEmail = decodeDotenvQuotedValue(process.env.ADMIN_EMAIL || ""); +const adminUsername = decodeDotenvQuotedValue(process.env.ADMIN_USERNAME || ""); +const adminPassword = decodeDotenvQuotedValue(process.env.ADMIN_PASSWORD || ""); +const biberUsername = decodeDotenvQuotedValue(process.env.BIBER_USERNAME || ""); +const biberPassword = decodeDotenvQuotedValue(process.env.BIBER_PASSWORD || ""); + +const expectedOidcAuthUrl = `${oidcIssuerUrl.replace(/\/$/, "")}/protocol/openid-connect/auth`; + +module.exports = { + appBaseUrl, + webmailBaseUrl, + canonicalDomain, + oidcIssuerUrl, + expectedOidcAuthUrl, + adminEmail, + adminUsername, + adminPassword, + biberUsername, + biberPassword, +}; diff --git a/roles/web-app-stalwart/files/playwright/playwright.spec.js b/roles/web-app-stalwart/files/playwright/playwright.spec.js index d7e45b0ccb..00facd17cb 100644 --- a/roles/web-app-stalwart/files/playwright/playwright.spec.js +++ b/roles/web-app-stalwart/files/playwright/playwright.spec.js @@ -1,220 +1,18 @@ const { test, expect } = require("@playwright/test"); -const { - decodeDotenvQuotedValue, - performKeycloakLoginForm, - runAdminFlow, - runBiberFlow, - runGuestFlow, - safeSkipUnlessEnabled, -} = require("./personas"); +const { appBaseUrl, canonicalDomain } = require("./env"); -// Stalwart e2e — mirrors web-app-mailu: WebAdmin TLS smoke, SSO login, biber -> -// admin send/receive via Roundcube, and the shared persona flows. SSO scenarios -// run when SSO_SERVICE_ENABLED; personas gated by PERSONA_*_BLOCKED. +// Aggregator: the runner collects only *.spec.js; the scenarios live in the +// test-*.js modules required below (TLS/DAV baseline, WebAdmin SSO, the +// Roundcube mail flow, and the shared persona flows). test.use({ ignoreHTTPSErrors: true }); -const appBaseUrl = decodeDotenvQuotedValue(process.env.APP_BASE_URL || "").replace(/\/+$/, ""); -const webmailBaseUrl = decodeDotenvQuotedValue(process.env.WEBMAIL_BASE_URL || "").replace(/\/+$/, ""); -const canonicalDomain = decodeDotenvQuotedValue(process.env.CANONICAL_DOMAIN || ""); -const oidcIssuerUrl = decodeDotenvQuotedValue(process.env.OIDC_ISSUER_URL || ""); -const adminEmail = decodeDotenvQuotedValue(process.env.ADMIN_EMAIL || ""); -const adminUsername = decodeDotenvQuotedValue(process.env.ADMIN_USERNAME || ""); -const adminPassword = decodeDotenvQuotedValue(process.env.ADMIN_PASSWORD || ""); -const biberUsername = decodeDotenvQuotedValue(process.env.BIBER_USERNAME || ""); -const biberPassword = decodeDotenvQuotedValue(process.env.BIBER_PASSWORD || ""); - -// Roundcube auto-redirects to Keycloak (oauth_login_redirect); drive the login -// form, then wait for the mail UI. -async function roundcubeSsoLogin(page, username, password) { - const expectedOidcAuthUrl = `${oidcIssuerUrl.replace(/\/$/, "")}/protocol/openid-connect/auth`; - await page.goto(`${webmailBaseUrl}/`); - const ssoButton = page - .getByRole("button", { name: /sso|single sign.?on|login with|openid/i }) - .or(page.getByRole("link", { name: /sso|single sign.?on|login with|openid/i })); - if (await ssoButton.first().isVisible({ timeout: 5_000 }).catch(() => false)) { - await ssoButton.first().click(); - } - await expect - .poll(() => page.url(), { - timeout: 30_000, - message: `Expected redirect to Keycloak OIDC: ${expectedOidcAuthUrl}`, - }) - .toContain(expectedOidcAuthUrl); - await performKeycloakLoginForm(page, username, password); - await page.locator("#messagelist, .compose, a[href*='_action=compose'], .toolbar").first() - .waitFor({ state: "visible", timeout: 60_000 }); -} - -// Logout MUST exist and work — a missing control is a failure, not a skip. -async function roundcubeLogout(page) { - const logout = page.locator("a[href*='_task=logout'], a[href*='logout'], a.logout") - .or(page.getByRole("link", { name: /logout|sign out/i })); - await expect(logout.first(), "Roundcube logout control must be present").toBeVisible({ - timeout: 10_000, - }); - await logout.first().click(); -} - -// Wait for a delivered mail in the recipient's mailbox — accept Inbox OR Junk (the -// .test env has no mail-auth DNS, so Stalwart files authenticated mail under Junk). -// Folders are switched by _mbox URL to avoid clicking a non-actionable folder link. -async function waitForEmailInMailbox(page, webmailBaseUrl, subjectText, timeout = 90_000) { - const deadline = Date.now() + timeout; - const mailboxes = ["INBOX", "Junk Mail"]; - const rowFor = () => - page.locator("#messagelist tbody tr, table.messagelist tbody tr").filter({ hasText: subjectText }).first(); - while (Date.now() < deadline) { - for (const mbox of mailboxes) { - await page - .goto(`${webmailBaseUrl}/?_task=mail&_mbox=${encodeURIComponent(mbox)}`, { waitUntil: "domcontentloaded" }) - .catch(() => {}); - await page.waitForTimeout(2_000); - if (await rowFor().isVisible().catch(() => false)) return rowFor(); - } - } - throw new Error(`Timed out waiting for email "${subjectText}" in ${mailboxes.join(" / ")}`); -} - test.beforeEach(() => { expect(appBaseUrl, "APP_BASE_URL must be set").toBeTruthy(); expect(canonicalDomain, "CANONICAL_DOMAIN must be set").toBeTruthy(); }); -// Baseline: WebAdmin is served on the canonical domain with TLS. -test("stalwart: WebAdmin is served under canonical domain with TLS", async ({ page }) => { - const response = await page.goto(`${appBaseUrl}/`); - expect(response, "Expected Stalwart response").toBeTruthy(); - expect(response.status(), "Expected status < 400").toBeLessThan(400); - expect(response.url().includes(canonicalDomain), `Expected canonical domain "${canonicalDomain}"`).toBe(true); - expect(response.headers()["strict-transport-security"], "Stalwart must emit HSTS").toBeTruthy(); -}); - -// CalDAV/CardDAV auto-discovery is reachable through the proxy (.well-known -> /dav/*). -test("stalwart: CalDAV/CardDAV discovery is reachable", async ({ request }) => { - for (const [wk, path] of [["caldav", "/dav/cal"], ["carddav", "/dav/card"]]) { - const res = await request.get(`${appBaseUrl}/.well-known/${wk}`, { maxRedirects: 0 }); - expect([301, 302, 307, 308].includes(res.status()), - `${wk} well-known must redirect (got ${res.status()})`).toBe(true); - expect(res.headers()["location"] || "", `${wk} should point at ${path}`).toContain("/dav/"); - } -}); - -// Scenario I: SSO login -> WebAdmin -> logout. -// WebAdmin is a username-first OAuth flow: enter the email, and (the mail domain -// being bound to our OIDC directory) the webui redirects to Keycloak. There is no -// static SSO link, so we type the email first, then drive the Keycloak form. -test("stalwart: sso login, open WebAdmin, logout", async ({ page }) => { - safeSkipUnlessEnabled("sso"); - const expectedOidcAuthUrl = `${oidcIssuerUrl.replace(/\/$/, "")}/protocol/openid-connect/auth`; - - await page.goto(`${appBaseUrl}/`); - // WebAdmin SPA routes the unauthenticated admin to its own /account/login. - await expect.poll(() => page.url(), { timeout: 30_000 }).toContain(`${canonicalDomain}/account/login`); - - // Enter the admin email; the webui discovers the OIDC provider and redirects. - const loginField = page - .getByRole("textbox", { name: /email|user|login/i }) - .or(page.locator("input[type='email'], input[type='text'], input[name='username'], input[name='email']")) - .first(); - await loginField.waitFor({ state: "visible", timeout: 30_000 }); - await loginField.fill(adminEmail); - await page - .getByRole("button", { name: /continue|next|log ?in|sign ?in/i }) - .or(page.locator("button[type='submit']")) - .first() - .click(); - - await expect.poll(() => page.url(), { timeout: 60_000 }).toContain(expectedOidcAuthUrl); - await performKeycloakLoginForm(page, adminUsername, adminPassword); - await expect.poll(() => page.url(), { timeout: 60_000 }).toContain(canonicalDomain); - - // WebAdmin chrome confirms the authenticated admin session. - await expect( - page.locator("nav, .sidebar, [class*='menu'], h1, h2").filter({ hasText: /dashboard|domains|account|settings|directory/i }).first() - ).toBeVisible({ timeout: 30_000 }); - - // The WebAdmin SPA keeps logout behind its account menu — no stable direct - // control exists on the page (verified in CI), so click it only when exposed. - // Hard logout coverage lives in the Roundcube scenarios (roundcubeLogout). - const logout = page.locator("a[href*='logout'], button:has-text('Logout')").or(page.getByRole("link", { name: /logout/i })); - if (await logout.first().isVisible({ timeout: 5_000 }).catch(() => false)) { - await logout.first().click(); - } -}); - -// Scenario II: biber -> administrator send/receive through the Roundcube webmail UI. -// Login is via Keycloak SSO (Roundcube XOAUTH2 -> Stalwart), mirroring web-app-mailu. -// biber and the administrator are separate people: isolated browser contexts. -test("stalwart: biber sends to administrator, administrator receives it", async ({ browser }) => { - safeSkipUnlessEnabled("sso"); - // The env template always renders these — a missing value is a rendering - // regression and MUST fail, not silently skip the flagship scenario. - expect(webmailBaseUrl, "WEBMAIL_BASE_URL must be set").toBeTruthy(); - expect(biberPassword, "BIBER_PASSWORD must be set").toBeTruthy(); - expect(adminPassword, "ADMIN_PASSWORD must be set").toBeTruthy(); - - const testSubject = `Playwright stalwart ${Date.now()}`; - const biberContext = await browser.newContext({ ignoreHTTPSErrors: true }); - const adminContext = await browser.newContext({ ignoreHTTPSErrors: true }); - - try { - const biberPage = await biberContext.newPage(); - await roundcubeSsoLogin(biberPage, biberUsername, biberPassword); - await biberPage.goto(`${webmailBaseUrl}/?_task=mail&_action=compose`); - await biberPage.waitForLoadState("networkidle", { timeout: 15_000 }).catch(() => {}); - await biberPage.locator("#_to, input[name='_to']").first().fill(adminEmail); - await biberPage.locator("#compose-subject, input[name='_subject']").first().fill(testSubject); - await biberPage.locator("#composebody, textarea[name='_message'], [contenteditable='true']").first() - .fill("Hello Administrator, this is an automated Playwright test email."); - await biberPage.locator(".formbuttons .send, button.send, a.send").first().click(); - // Roundcube (Elastic, framed) sends via AJAX: it may stay on the compose URL and - // just show a toast. Surface an SMTP error immediately if one appears; otherwise - // the real proof of a successful send is receipt in the admin inbox below. - const sendError = biberPage.locator("#messagestack .error, .toast .error, .toast-error").first(); - if (await sendError.isVisible({ timeout: 15_000 }).catch(() => false)) { - throw new Error(`Roundcube reported a send error: ${await sendError.textContent()}`); - } - await roundcubeLogout(biberPage); - - const adminPage = await adminContext.newPage(); - await roundcubeSsoLogin(adminPage, adminUsername, adminPassword); - const emailRow = await waitForEmailInMailbox(adminPage, webmailBaseUrl, testSubject, 90_000); - await expect(emailRow).toBeVisible(); - await emailRow.click(); - await expect( - adminPage.locator("#messagecontframe, #mailview-right, .message-part").first() - ).toBeVisible({ timeout: 15_000 }); - await roundcubeLogout(adminPage); - } finally { - await biberContext.close().catch(() => {}); - await adminContext.close().catch(() => {}); - } -}); - -// Shared persona flows (gated by PERSONA_*_BLOCKED in templates/playwright.env.j2). -test("guest: public-landing → auth chain → never authenticated", async ({ page }) => { - await runGuestFlow(page); -}); - -test("biber: app → universal logout", async ({ page }) => { - await runBiberFlow(page); -}); - -test("administrator: app → universal logout", async ({ page }) => { - await runAdminFlow(page, { - adminInteraction: async (interactivePage) => { - const link = interactivePage - .getByRole("link", { name: /^(domains|accounts|directory|settings|dashboard)$/i }) - .first(); - if (await link.isVisible({ timeout: 10_000 }).catch(() => false)) { - await link.click().catch(() => {}); - await interactivePage.waitForLoadState("domcontentloaded", { timeout: 30_000 }).catch(() => {}); - await expect(interactivePage.locator("body")).toContainText( - /domains|accounts|directory|settings|dashboard/i, - { timeout: 30_000 }, - ); - } - }, - }); -}); +require("./test-tls"); +require("./test-sso"); +require("./test-mailflow"); +require("./test-personas"); diff --git a/roles/web-app-stalwart/files/playwright/test-mailflow.js b/roles/web-app-stalwart/files/playwright/test-mailflow.js new file mode 100644 index 0000000000..ad9829c15c --- /dev/null +++ b/roles/web-app-stalwart/files/playwright/test-mailflow.js @@ -0,0 +1,62 @@ +const { test, expect } = require("@playwright/test"); + +const { safeSkipUnlessEnabled } = require("./personas"); +const { roundcubeSsoLogin, roundcubeLogout, waitForEmailInMailbox } = require("./webmail"); +const { + webmailBaseUrl, + adminEmail, + adminUsername, + adminPassword, + biberUsername, + biberPassword, +} = require("./env"); + +// biber -> administrator send/receive through the Roundcube webmail UI. +// Login is via Keycloak SSO (Roundcube XOAUTH2 -> Stalwart), mirroring +// web-app-mailu. biber and the administrator are separate people: isolated +// browser contexts. +test("stalwart: biber sends to administrator, administrator receives it", async ({ browser }) => { + safeSkipUnlessEnabled("sso"); + // Exception: the env template always renders these — a missing value is a + // rendering regression and MUST fail, not silently skip the flagship scenario. + expect(webmailBaseUrl, "WEBMAIL_BASE_URL must be set").toBeTruthy(); + expect(biberPassword, "BIBER_PASSWORD must be set").toBeTruthy(); + expect(adminPassword, "ADMIN_PASSWORD must be set").toBeTruthy(); + + const testSubject = `Playwright stalwart ${Date.now()}`; + const biberContext = await browser.newContext({ ignoreHTTPSErrors: true }); + const adminContext = await browser.newContext({ ignoreHTTPSErrors: true }); + + try { + const biberPage = await biberContext.newPage(); + await roundcubeSsoLogin(biberPage, biberUsername, biberPassword); + await biberPage.goto(`${webmailBaseUrl}/?_task=mail&_action=compose`); + await biberPage.waitForLoadState("networkidle", { timeout: 15_000 }).catch(() => {}); + await biberPage.locator("#_to, input[name='_to']").first().fill(adminEmail); + await biberPage.locator("#compose-subject, input[name='_subject']").first().fill(testSubject); + await biberPage.locator("#composebody, textarea[name='_message'], [contenteditable='true']").first() + .fill("Hello Administrator, this is an automated Playwright test email."); + await biberPage.locator(".formbuttons .send, button.send, a.send").first().click(); + // Exception: Roundcube (Elastic, framed) sends via AJAX and may stay on the + // compose URL with only a toast; surface an SMTP error immediately, the + // real proof of a successful send is receipt in the admin inbox below. + const sendError = biberPage.locator("#messagestack .error, .toast .error, .toast-error").first(); + if (await sendError.isVisible({ timeout: 15_000 }).catch(() => false)) { + throw new Error(`Roundcube reported a send error: ${await sendError.textContent()}`); + } + await roundcubeLogout(biberPage); + + const adminPage = await adminContext.newPage(); + await roundcubeSsoLogin(adminPage, adminUsername, adminPassword); + const emailRow = await waitForEmailInMailbox(adminPage, webmailBaseUrl, testSubject, 90_000); + await expect(emailRow).toBeVisible(); + await emailRow.click(); + await expect( + adminPage.locator("#messagecontframe, #mailview-right, .message-part").first() + ).toBeVisible({ timeout: 15_000 }); + await roundcubeLogout(adminPage); + } finally { + await biberContext.close().catch(() => {}); + await adminContext.close().catch(() => {}); + } +}); diff --git a/roles/web-app-stalwart/files/playwright/test-personas.js b/roles/web-app-stalwart/files/playwright/test-personas.js new file mode 100644 index 0000000000..f5033cae0f --- /dev/null +++ b/roles/web-app-stalwart/files/playwright/test-personas.js @@ -0,0 +1,30 @@ +const { test, expect } = require("@playwright/test"); + +const { runAdminFlow, runBiberFlow, runGuestFlow } = require("./personas"); + +// Shared persona flows (gated by PERSONA_*_BLOCKED in templates/playwright.env.j2). +test("guest: public-landing → auth chain → never authenticated", async ({ page }) => { + await runGuestFlow(page); +}); + +test("biber: app → universal logout", async ({ page }) => { + await runBiberFlow(page); +}); + +test("administrator: app → universal logout", async ({ page }) => { + await runAdminFlow(page, { + adminInteraction: async (interactivePage) => { + const link = interactivePage + .getByRole("link", { name: /^(domains|accounts|directory|settings|dashboard)$/i }) + .first(); + if (await link.isVisible({ timeout: 10_000 }).catch(() => false)) { + await link.click().catch(() => {}); + await interactivePage.waitForLoadState("domcontentloaded", { timeout: 30_000 }).catch(() => {}); + await expect(interactivePage.locator("body")).toContainText( + /domains|accounts|directory|settings|dashboard/i, + { timeout: 30_000 }, + ); + } + }, + }); +}); diff --git a/roles/web-app-stalwart/files/playwright/test-sso.js b/roles/web-app-stalwart/files/playwright/test-sso.js new file mode 100644 index 0000000000..c07169715f --- /dev/null +++ b/roles/web-app-stalwart/files/playwright/test-sso.js @@ -0,0 +1,47 @@ +const { test, expect } = require("@playwright/test"); + +const { performKeycloakLoginForm, safeSkipUnlessEnabled } = require("./personas"); +const { + appBaseUrl, + canonicalDomain, + expectedOidcAuthUrl, + adminEmail, + adminUsername, + adminPassword, +} = require("./env"); + +// WebAdmin SSO: a username-first OAuth flow — enter the email, and (the mail +// domain being bound to our OIDC directory) the webui redirects to Keycloak. +test("stalwart: sso login, open WebAdmin, logout", async ({ page }) => { + safeSkipUnlessEnabled("sso"); + + await page.goto(`${appBaseUrl}/`); + await expect.poll(() => page.url(), { timeout: 30_000 }).toContain(`${canonicalDomain}/account/login`); + + const loginField = page + .getByRole("textbox", { name: /email|user|login/i }) + .or(page.locator("input[type='email'], input[type='text'], input[name='username'], input[name='email']")) + .first(); + await loginField.waitFor({ state: "visible", timeout: 30_000 }); + await loginField.fill(adminEmail); + await page + .getByRole("button", { name: /continue|next|log ?in|sign ?in/i }) + .or(page.locator("button[type='submit']")) + .first() + .click(); + + await expect.poll(() => page.url(), { timeout: 60_000 }).toContain(expectedOidcAuthUrl); + await performKeycloakLoginForm(page, adminUsername, adminPassword); + await expect.poll(() => page.url(), { timeout: 60_000 }).toContain(canonicalDomain); + + await expect( + page.locator("nav, .sidebar, [class*='menu'], h1, h2").filter({ hasText: /dashboard|domains|account|settings|directory/i }).first() + ).toBeVisible({ timeout: 30_000 }); + + // Exception: the WebAdmin SPA keeps logout behind its account menu with no + // stable direct control; hard logout coverage lives in the Roundcube scenarios. + const logout = page.locator("a[href*='logout'], button:has-text('Logout')").or(page.getByRole("link", { name: /logout/i })); + if (await logout.first().isVisible({ timeout: 5_000 }).catch(() => false)) { + await logout.first().click(); + } +}); diff --git a/roles/web-app-stalwart/files/playwright/test-tls.js b/roles/web-app-stalwart/files/playwright/test-tls.js new file mode 100644 index 0000000000..4b0b7e6401 --- /dev/null +++ b/roles/web-app-stalwart/files/playwright/test-tls.js @@ -0,0 +1,21 @@ +const { test, expect } = require("@playwright/test"); + +const { appBaseUrl, canonicalDomain } = require("./env"); + +// Baseline reachability: WebAdmin TLS + DAV auto-discovery through the proxy. +test("stalwart: WebAdmin is served under canonical domain with TLS", async ({ page }) => { + const response = await page.goto(`${appBaseUrl}/`); + expect(response, "Expected Stalwart response").toBeTruthy(); + expect(response.status(), "Expected status < 400").toBeLessThan(400); + expect(response.url().includes(canonicalDomain), `Expected canonical domain "${canonicalDomain}"`).toBe(true); + expect(response.headers()["strict-transport-security"], "Stalwart must emit HSTS").toBeTruthy(); +}); + +test("stalwart: CalDAV/CardDAV discovery is reachable", async ({ request }) => { + for (const [wk, path] of [["caldav", "/dav/cal"], ["carddav", "/dav/card"]]) { + const res = await request.get(`${appBaseUrl}/.well-known/${wk}`, { maxRedirects: 0 }); + expect([301, 302, 307, 308].includes(res.status()), + `${wk} well-known must redirect (got ${res.status()})`).toBe(true); + expect(res.headers()["location"] || "", `${wk} should point at ${path}`).toContain("/dav/"); + } +}); diff --git a/roles/web-app-stalwart/files/playwright/webmail.js b/roles/web-app-stalwart/files/playwright/webmail.js new file mode 100644 index 0000000000..7e6ff01f76 --- /dev/null +++ b/roles/web-app-stalwart/files/playwright/webmail.js @@ -0,0 +1,57 @@ +const { expect } = require("@playwright/test"); + +const { performKeycloakLoginForm } = require("./personas"); +const { webmailBaseUrl, expectedOidcAuthUrl } = require("./env"); + +// Roundcube auto-redirects to Keycloak (oauth_login_redirect); drive the login +// form, then wait for the mail UI. +async function roundcubeSsoLogin(page, username, password) { + await page.goto(`${webmailBaseUrl}/`); + const ssoButton = page + .getByRole("button", { name: /sso|single sign.?on|login with|openid/i }) + .or(page.getByRole("link", { name: /sso|single sign.?on|login with|openid/i })); + if (await ssoButton.first().isVisible({ timeout: 5_000 }).catch(() => false)) { + await ssoButton.first().click(); + } + await expect + .poll(() => page.url(), { + timeout: 30_000, + message: `Expected redirect to Keycloak OIDC: ${expectedOidcAuthUrl}`, + }) + .toContain(expectedOidcAuthUrl); + await performKeycloakLoginForm(page, username, password); + await page.locator("#messagelist, .compose, a[href*='_action=compose'], .toolbar").first() + .waitFor({ state: "visible", timeout: 60_000 }); +} + +// Logout MUST exist and work — a missing control is a failure, not a skip. +async function roundcubeLogout(page) { + const logout = page.locator("a[href*='_task=logout'], a[href*='logout'], a.logout") + .or(page.getByRole("link", { name: /logout|sign out/i })); + await expect(logout.first(), "Roundcube logout control must be present").toBeVisible({ + timeout: 10_000, + }); + await logout.first().click(); +} + +// Wait for a delivered mail in the recipient's mailbox — accept Inbox OR Junk (the +// .test env has no mail-auth DNS, so Stalwart files authenticated mail under Junk). +// Folders are switched by _mbox URL to avoid clicking a non-actionable folder link. +async function waitForEmailInMailbox(page, baseUrl, subjectText, timeout = 90_000) { + const deadline = Date.now() + timeout; + const mailboxes = ["INBOX", "Junk Mail"]; + const rowFor = () => + page.locator("#messagelist tbody tr, table.messagelist tbody tr").filter({ hasText: subjectText }).first(); + while (Date.now() < deadline) { + for (const mbox of mailboxes) { + await page + .goto(`${baseUrl}/?_task=mail&_mbox=${encodeURIComponent(mbox)}`, { waitUntil: "domcontentloaded" }) + .catch(() => {}); + await page.waitForTimeout(2_000); + if (await rowFor().isVisible().catch(() => false)) return rowFor(); + } + } + throw new Error(`Timed out waiting for email "${subjectText}" in ${mailboxes.join(" / ")}`); +} + +module.exports = { roundcubeSsoLogin, roundcubeLogout, waitForEmailInMailbox }; diff --git a/roles/web-app-stalwart/files/tests/verify_migration.py b/roles/web-app-stalwart/files/tests/verify_migration.py index 301db27138..ddeea5ec84 100755 --- a/roles/web-app-stalwart/files/tests/verify_migration.py +++ b/roles/web-app-stalwart/files/tests/verify_migration.py @@ -1,11 +1,13 @@ #!/usr/bin/env python3 """Verify the Mailu->Stalwart migration fixture over IMAP. -Asserts exactly what seed_mailu_maildir.py planted (also serving as the +Checks exactly what seed_mailu_maildir.py planted (also serving as the idempotency check: counts MUST stay exact after a second migration run): - INBOX: exactly 2 messages, subjects "Migrated one" + "Migrated two", and "Migrated one" kept its \\Seen flag, - Archive: exactly 1 message, subject "Archived three". + +Failures raise SystemExit instead of assert so the checks survive `python -O`. """ from __future__ import annotations @@ -15,9 +17,14 @@ import ssl import sys +def _require(condition: bool, message: str) -> None: + if not condition: + raise SystemExit(f"FAIL: {message}") + + def fetch_subject_and_flags(imap: imaplib.IMAP4, num: bytes) -> tuple[str, str]: typ, data = imap.fetch(num, "(FLAGS BODY.PEEK[HEADER.FIELDS (SUBJECT)])") - assert typ == "OK", f"FETCH failed: {data}" + _require(typ == "OK", f"FETCH failed: {data}") flags = "" subject = "" for part in data: @@ -31,29 +38,31 @@ def fetch_subject_and_flags(imap: imaplib.IMAP4, num: bytes) -> tuple[str, str]: def check_folder(imap: imaplib.IMAP4, mailbox: str, expected: dict[str, bool]) -> None: typ, data = imap.select(mailbox, readonly=True) - assert typ == "OK", f"cannot SELECT {mailbox}" + _require(typ == "OK", f"cannot SELECT {mailbox}") count = int(data[0]) - assert count == len(expected), ( - f"{mailbox}: expected {len(expected)} messages, found {count}" + _require( + count == len(expected), + f"{mailbox}: expected {len(expected)} messages, found {count}", ) typ, nums = imap.search(None, "ALL") - assert typ == "OK" + _require(typ == "OK", f"{mailbox}: SEARCH failed") seen_subjects: dict[str, bool] = {} for num in nums[0].split(): subject, flags = fetch_subject_and_flags(imap, num) seen_subjects[subject] = "\\Seen" in flags for subject, want_seen in expected.items(): - assert subject in seen_subjects, f"{mailbox}: missing subject {subject!r}" - assert seen_subjects[subject] == want_seen, ( + _require(subject in seen_subjects, f"{mailbox}: missing subject {subject!r}") + _require( + seen_subjects[subject] == want_seen, f"{mailbox}: {subject!r} Seen-flag expected={want_seen} " - f"got={seen_subjects[subject]}" + f"got={seen_subjects[subject]}", ) print(f"OK {mailbox}: {count} messages, subjects + flags match") def main(host: str, port: int, user: str, password: str) -> None: context = ssl.create_default_context() - # Fixture container serves Stalwart's built-in bootstrap certificate. + # Exception: the fixture container serves Stalwart's built-in bootstrap certificate. context.check_hostname = False context.verify_mode = ssl.CERT_NONE imap = imaplib.IMAP4_SSL(host, port, ssl_context=context, timeout=30) diff --git a/roles/web-app-stalwart/meta/services.yml b/roles/web-app-stalwart/meta/services.yml index 3e62403e84..8c97dc7bee 100644 --- a/roles/web-app-stalwart/meta/services.yml +++ b/roles/web-app-stalwart/meta/services.yml @@ -50,21 +50,14 @@ stalwart: placement: manager image: stalwartlabs/stalwart version: "v0.16.12" - # Warn: WebUI (WebAdmin) bundle pin, staged by the controller - # (tasks/02_webadmin.yml); bump together with `version` above. webui_version: "v1.0.5" name: stalwart - # Exception: with an embedded postgres the whole project must come back up - # through one coherent restart after baudolo's per-volume stop/start cycles. backup: project_hard_restart: true # nocheck: min-storage-headroom Reason: the mail store (maildir blobs, FTS index, queue) lives in this service's volumes and dwarfs the image transfer size min_storage: 20GB domain: "{{ lookup('email').domain }}" - # Exception: no 587/143/110 — Stalwart's default config serves only - # implicit-TLS client ports (465/993/995); publishing the STARTTLS - # triplet would expose dead ports (the swarm drill's reachability - # check fails on them). + # Exception: no 587/143/110 — Stalwart's default config binds only the implicit-TLS client ports. ports: local: http: 8081 @@ -92,16 +85,9 @@ stalwart: postgres: bond: 1 enabled: true # nocheck: dynamic-flag - # Exception: central postgres only in compose — under swarm the overlay VIP - # to svc-db-postgres adds pressure on the manager-pinned stack (mailu pins - # its embedded redis for the same reason), and the embedded sidecar keeps - # the mail database node-local next to the NFS-hostile mail store. + # Exception: embedded in swarm — mailu pins its embedded redis for the same manager-VIP reason. shared: "{{ ('svc-db-postgres' in group_names) and (DEPLOYMENT_MODE == 'compose') }}" - # Exception: the dedicated sidecar pins plain postgres — the platform default - # (postgis/postgis) defeats baudolo's substring database detection - # ('postgres' not in 'postgis/…'), so the volume was live-file-snapshotted - # instead of sql-dumped and restored with a torn WAL (postgres PANIC). - # Central mode ignores the pin (svc-db-postgres provides the container). + # Exception: plain postgres, not the postgis default — baudolo's substring detection needs it for sql-dump backups. image: postgres version: "17" cpus: "0.8" diff --git a/roles/web-app-stalwart/meta/volumes.yml b/roles/web-app-stalwart/meta/volumes.yml index 41f323fed7..4fcb41ef57 100644 --- a/roles/web-app-stalwart/meta/volumes.yml +++ b/roles/web-app-stalwart/meta/volumes.yml @@ -5,9 +5,6 @@ data: mounts: - service: stalwart target: /var/lib/stalwart -# Exception: named volume for the image's declared VOLUME /etc/stalwart -# (config bind mounts overlay it) — prevents a per-deploy anonymous volume -# that sys-ctl-hlth-volumes flags. config: type: volume name: stalwart_config @@ -26,21 +23,14 @@ clamav_data: mounts: - service: clamav target: /var/lib/clamav -# Exception: 0.16 JSON bootstrap (data store); the rest of the config lives in -# the DB. config_file: type: config source: "{{ [ lookup('container', 'web-app-stalwart', 'directories.volumes'), 'etc/config.json' ] | path_join }}" - # Exception: world-readable — the container runs as UID 2000. mode: "0444" mounts: - service: stalwart target: /etc/stalwart/config.json -# Exception: WebUI (WebAdmin) bundle staged by the controller (see -# tasks/02_webadmin.yml). -# nocheck: meta-volume-file-bind-should-be-config -# Exception: multi-MB zip exceeds the docker config size limit; the role is -# manager-pinned so the bind source is always node-local. +# nocheck: meta-volume-file-bind-should-be-config — multi-MB zip exceeds the docker config size limit; the role is manager-pinned so the bind source is always node-local webui_bundle: type: bind source: "{{ [ lookup('container', 'web-app-stalwart', 'directories.volumes'), 'etc/webui.zip' ] | path_join }}" @@ -48,8 +38,6 @@ webui_bundle: mounts: - service: stalwart target: /etc/stalwart/webui.zip -# Exception: platform TLS cert for the mail listeners (referenced via -# x:Certificate). certs: type: bind source: "{{ [ lookup('container', 'web-app-stalwart', 'directories.volumes'), 'certs' ] | path_join }}" @@ -64,12 +52,9 @@ clamav_milter_conf: mounts: - service: clamav target: /etc/clamav/clamav-milter.conf -# Exception: rendered unconditionally (content self-gates on SSO) so the -# source always exists. webmail_oauth: type: config source: "{{ [ lookup('container', 'web-app-stalwart', 'directories.volumes'), 'webmail/oauth.inc.php' ] | path_join }}" - # Exception: readable by www-data in the roundcube container. mode: "0444" mounts: - service: webmail diff --git a/roles/web-app-stalwart/tasks/00_core.yml b/roles/web-app-stalwart/tasks/00_core.yml index 6ebdab4d60..8417ed1633 100644 --- a/roles/web-app-stalwart/tasks/00_core.yml +++ b/roles/web-app-stalwart/tasks/00_core.yml @@ -1,8 +1,7 @@ --- - include_tasks: utils/once/flag.yml -# Exception: Stalwart's compiled-in validation rejects .example/.invalid -# (RFC 6761) — fail before any state change. +# Exception: Stalwart's compiled-in validation rejects RFC 6761 reserved TLDs — fail before any state change. - name: "✅ Assert the mail domain is provisionable by Stalwart" ansible.builtin.assert: that: @@ -22,9 +21,7 @@ state: directory mode: "0755" -# Exception: swarm does not auto-create a missing bind source — the certs -# directory must exist before stack-up; sys-ctl-mtn-cert-deploy fills it -# later (05_tls). +# Exception: swarm does not auto-create a missing bind source; sys-ctl-mtn-cert-deploy fills the directory later (05_tls). - name: ✅ Ensure certs bind-source directory exists (host) file: path: "{{ [ STALWART_VOLUMES_DIR, 'certs' ] | path_join }}" @@ -35,22 +32,14 @@ stack_host_template: src: config.json.j2 dest: "{{ STALWART_CONFIG_FILE }}" - # Exception: must be world-readable — the container runs as UID 2000. mode: "0644" -# Exception: stage the WebUI bundle before container start so the read-only -# mount targets a real file. The controller can fetch what Stalwart (pinned CA -# roots) cannot. A failed download fails the deploy: shipping a 404 WebAdmin -# silently is worse. Air-gapped hosts override STALWART_WEBUI_RESOURCE_URL to -# an internal mirror. - name: "✅ Ensure the WebUI cache directory exists" ansible.builtin.file: path: "{{ STALWART_WEBUI_CACHE_FILE | dirname }}" state: directory mode: "0755" -# Exception: only the stack host needs the bundle (the service is -# manager-pinned) — N workers hammering GitHub would hit rate limits. - name: "⬇️ Download the Stalwart WebUI bundle (skipped when cached)" get_url_retry: url: "{{ STALWART_WEBUI_RESOURCE_URL }}" @@ -71,14 +60,10 @@ state: directory mode: "0755" -# Exception: rendered even without SSO — the file is a bind source -# (meta/volumes.yml) and must exist before container start; its content -# self-gates on SSO. - name: 📄 Render Roundcube OAuth (Keycloak SSO) configuration stack_host_template: src: roundcube-oauth.inc.php.j2 dest: "{{ STALWART_WEBMAIL_OAUTH_CONFIG }}" - # Exception: included by the roundcube container, which runs as www-data. mode: "0644" register: stalwart_webmail_conf @@ -102,9 +87,7 @@ - name: "🚿 Flush Docker Compose handlers" meta: flush_handlers -# Exception: name the webmail service explicitly — the swarm upstream resolver -# defaults to the primary entity (stalwart:8080), which serves the mail server -# instead of Roundcube on the webmail vhost. +# Exception: without the explicit service key the swarm upstream resolver picks the primary entity and the webmail vhost serves the mail server. - name: "🌐 Proxy the Roundcube webmail at {{ STALWART_WEBMAIL_DOMAIN }}" include_role: name: sys-stk-front-proxy diff --git a/roles/web-app-stalwart/tasks/01_wait_for_api.yml b/roles/web-app-stalwart/tasks/01_wait_for_api.yml index 10cbd363b3..6b9ec06a58 100644 --- a/roles/web-app-stalwart/tasks/01_wait_for_api.yml +++ b/roles/web-app-stalwart/tasks/01_wait_for_api.yml @@ -1,7 +1,4 @@ --- -# Wait for readiness (not just liveness): /healthz/ready covers the stores, so -# directory-backed SMTP checks (e.g. hlth-msmtp right after a restart) cannot -# race a booting instance whose RCPT lookups still fail closed. - name: "⏳ Wait for the stalwart task to converge (swarm; no-op in compose)" ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/wait_converged.yml') }}" vars: diff --git a/roles/web-app-stalwart/tasks/02_webadmin.yml b/roles/web-app-stalwart/tasks/02_webadmin.yml index 9bfaa1fdcf..82387145c6 100644 --- a/roles/web-app-stalwart/tasks/02_webadmin.yml +++ b/roles/web-app-stalwart/tasks/02_webadmin.yml @@ -35,8 +35,7 @@ {'update': {stalwart_webui_app_id: {'resourceUrl': STALWART_WEBUI_LOCAL_URL}}}, 'c0']]} | to_json }} -# Exception: UpdateApps force-unpacks from resourceUrl (the -# /api/update/webadmin endpoint is gone). +# Exception: the /api/update/webadmin endpoint is gone; UpdateApps re-unpacks from resourceUrl. - name: "📦 Unpack the WebUI bundle from the local file" include_tasks: jmap_call.yml vars: diff --git a/roles/web-app-stalwart/tasks/06_oidc.yml b/roles/web-app-stalwart/tasks/06_oidc.yml index 6fed0b812b..5408975aad 100644 --- a/roles/web-app-stalwart/tasks/06_oidc.yml +++ b/roles/web-app-stalwart/tasks/06_oidc.yml @@ -2,14 +2,12 @@ # Point Stalwart's auth directory at Keycloak. The directory is Internal XOR one # external directory (no fallback), so SSO switches all interactive auth to OIDC # and disables password login — see the role README for the full rationale. +# JMAP request bodies live in templates/jmap/*.json.j2. -# OIDC directory (Keycloak) - name: "📖 List existing Stalwart directories" include_tasks: jmap_call.yml vars: - stalwart_jmap_body: >- - {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], - 'methodCalls': [['x:Directory/get', {'ids': none}, 'c0']]} | to_json }} + stalwart_jmap_body: "{{ lookup('template', 'jmap/directory/get.json.j2') }}" - name: "🔍 Resolve existing Keycloak OIDC directory id (if any)" ansible.builtin.set_fact: @@ -22,16 +20,7 @@ - name: "📁 Create the Keycloak OIDC authentication directory" include_tasks: jmap_call.yml vars: - stalwart_jmap_body: >- - {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], - 'methodCalls': [['x:Directory/set', {'create': {'kc': { - '@type': 'Oidc', - 'description': 'Keycloak SSO (' ~ OIDC.CLIENT.REALM ~ ')', - 'issuerUrl': OIDC.CLIENT.ISSUER_URL, - 'claimUsername': OIDC.ATTRIBUTES.USERNAME, - 'usernameDomain': STALWART_DOMAIN, - 'claimName': 'name' - }}}, 'c0']]} | to_json }} + stalwart_jmap_body: "{{ lookup('template', 'jmap/directory/create_oidc.json.j2') }}" when: stalwart_oidc_dir_id | length == 0 - name: "📖 Capture the newly created OIDC directory id" @@ -39,29 +28,17 @@ stalwart_oidc_dir_id: "{{ stalwart_jmap.methodResponses[0][1].created.kc.id }}" when: stalwart_oidc_dir_id | length == 0 -# Exception: clear requireAudience — Keycloak tokens carry aud=account, so -# pinning it would reject them as InvalidAudience. The username claim still -# identifies the user. +# Exception: Keycloak tokens carry aud=account — pinning requireAudience would reject them as InvalidAudience. - name: "🧹 Clear the OIDC directory's required audience" include_tasks: jmap_call.yml vars: - stalwart_jmap_body: >- - {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], - 'methodCalls': [['x:Directory/set', - {'update': {stalwart_oidc_dir_id: {'requireAudience': none}}}, - 'c0']]} | to_json }} + stalwart_jmap_body: "{{ lookup('template', 'jmap/directory/clear_audience.json.j2') }}" when: stalwart_oidc_dir_id | length > 0 -# Exception: we create the Authentication singleton ourselves, so it lands -# with EMPTY defaultUserRoleIds — leaving User accounts without -# ImapAuthenticate (mailbox login then fails silently with an IMAP EOF). Seed -# the built-in roles like Stalwart's own bootstrap does. - name: "📖 List Stalwart built-in roles" include_tasks: jmap_call.yml vars: - stalwart_jmap_body: >- - {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], - 'methodCalls': [['x:Role/get', {'ids': none}, 'c0']]} | to_json }} + stalwart_jmap_body: "{{ lookup('template', 'jmap/role_get.json.j2') }}" - name: "🔍 Resolve built-in Stalwart role ids by description" ansible.builtin.set_fact: @@ -75,9 +52,8 @@ that: stalwart_role_user | length > 0 fail_msg: "Stalwart built-in 'User' role not found; cannot grant IMAP/SMTP mailbox permissions." -# Exception: Map is JSON-encoded as {"": true}; a whole-object set -# clears+replaces it. Defaults mirror crates/common/src/manager/defaults.rs -# (admin/tenant also get User). +# Exception: a self-created Authentication singleton lands with EMPTY defaultUserRoleIds — User accounts +# then fail IMAP login with a silent EOF; seed the built-in roles like Stalwart's own bootstrap does. - name: "🔧 Assemble default role-id maps for the authentication singleton" ansible.builtin.set_fact: stalwart_auth_defaults: @@ -90,9 +66,7 @@ - name: "📖 Read the Stalwart authentication singleton" include_tasks: jmap_call.yml vars: - stalwart_jmap_body: >- - {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], - 'methodCalls': [['x:Authentication/get', {'ids': none}, 'c0']]} | to_json }} + stalwart_jmap_body: "{{ lookup('template', 'jmap/authentication/get.json.j2') }}" - name: "🔧 Record whether the authentication singleton exists" ansible.builtin.set_fact: @@ -101,24 +75,16 @@ - name: "📁 Create the authentication singleton (OIDC directory + default roles)" include_tasks: jmap_call.yml vars: - stalwart_jmap_body: >- - {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], - 'methodCalls': [['x:Authentication/set', {'create': {'a': - stalwart_auth_defaults}}, 'c0']]} | to_json }} + stalwart_jmap_body: "{{ lookup('template', 'jmap/authentication/create.json.j2') }}" when: not (stalwart_auth_exists | bool) - name: "🔗 Point the authentication singleton at Keycloak + seed default roles" include_tasks: jmap_call.yml vars: - stalwart_jmap_body: >- - {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], - 'methodCalls': [['x:Authentication/set', {'update': {'singleton': - stalwart_auth_defaults}}, 'c0']]} | to_json }} + stalwart_jmap_body: "{{ lookup('template', 'jmap/authentication/update.json.j2') }}" when: stalwart_auth_exists | bool -# Exception: trusted-network relay — let the internal nets relay without SMTP -# AUTH (the no-reply account has no password under OIDC). `remote_ip == -# ''` is a subnet match. +# Exception: the no-reply account has no password under OIDC, so trusted internal nets must relay without SMTP AUTH. - name: "⚙️ Build the trusted-network relay expression" ansible.builtin.set_fact: stalwart_relay_expr: >- @@ -127,9 +93,7 @@ - name: "📖 Read the RCPT stage singleton" include_tasks: jmap_call.yml vars: - stalwart_jmap_body: >- - {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], - 'methodCalls': [['x:MtaStageRcpt/get', {'ids': none}, 'c0']]} | to_json }} + stalwart_jmap_body: "{{ lookup('template', 'jmap/rcpt/get.json.j2') }}" - name: "🔧 Record whether the RCPT stage singleton exists" ansible.builtin.set_fact: @@ -138,17 +102,11 @@ - name: "📁 Create the RCPT stage with trusted-network relay" include_tasks: jmap_call.yml vars: - stalwart_jmap_body: >- - {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], - 'methodCalls': [['x:MtaStageRcpt/set', {'create': {'r': - {'allowRelaying': {'else': stalwart_relay_expr | trim}}}}, 'c0']]} | to_json }} + stalwart_jmap_body: "{{ lookup('template', 'jmap/rcpt/create.json.j2') }}" when: not (stalwart_rcpt_exists | bool) - name: "🔄 Update the RCPT stage with trusted-network relay" include_tasks: jmap_call.yml vars: - stalwart_jmap_body: >- - {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], - 'methodCalls': [['x:MtaStageRcpt/set', {'update': {'singleton': - {'allowRelaying': {'else': stalwart_relay_expr | trim}}}}, 'c0']]} | to_json }} + stalwart_jmap_body: "{{ lookup('template', 'jmap/rcpt/update.json.j2') }}" when: stalwart_rcpt_exists | bool diff --git a/roles/web-app-stalwart/tasks/07_antivirus.yml b/roles/web-app-stalwart/tasks/07_antivirus.yml index 5c1e21058c..8391e25fbd 100644 --- a/roles/web-app-stalwart/tasks/07_antivirus.yml +++ b/roles/web-app-stalwart/tasks/07_antivirus.yml @@ -1,12 +1,11 @@ --- # Register the ClamAV container as a DATA-stage milter (idempotent by hostname). # Short timeouts + fail-open keep mail flowing while clamd warms up. +# JMAP request bodies live in templates/jmap/*.json.j2. - name: "📖 List existing Stalwart milters" include_tasks: jmap_call.yml vars: - stalwart_jmap_body: >- - {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], - 'methodCalls': [['x:MtaMilter/get', {'ids': none}, 'c0']]} | to_json }} + stalwart_jmap_body: "{{ lookup('template', 'jmap/milter/get.json.j2') }}" - name: "🔍 Resolve existing ClamAV milter id (if any)" ansible.builtin.set_fact: @@ -18,28 +17,11 @@ - name: "📁 Create the ClamAV milter" include_tasks: jmap_call.yml vars: - stalwart_jmap_body: >- - {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], - 'methodCalls': [['x:MtaMilter/set', {'create': {'av': { - 'hostname': STALWART_CLAMAV_HOST, - 'port': STALWART_CLAMAV_MILTER_PORT, - 'stages': {'data': true}, - 'tempFailOnError': false, - 'timeoutConnect': STALWART_CLAMAV_MILTER_TIMEOUT_CONNECT_MS, - 'timeoutCommand': STALWART_CLAMAV_MILTER_TIMEOUT_COMMAND_MS, - 'timeoutData': STALWART_CLAMAV_MILTER_TIMEOUT_DATA_MS - }}}, 'c0']]} | to_json }} + stalwart_jmap_body: "{{ lookup('template', 'jmap/milter/create.json.j2') }}" when: stalwart_av_milter_id | length == 0 - name: "🔄 Update the ClamAV milter timeouts (fail-open on slow/cold clamd)" include_tasks: jmap_call.yml vars: - stalwart_jmap_body: >- - {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], - 'methodCalls': [['x:MtaMilter/set', {'update': {stalwart_av_milter_id: { - 'tempFailOnError': false, - 'timeoutConnect': STALWART_CLAMAV_MILTER_TIMEOUT_CONNECT_MS, - 'timeoutCommand': STALWART_CLAMAV_MILTER_TIMEOUT_COMMAND_MS, - 'timeoutData': STALWART_CLAMAV_MILTER_TIMEOUT_DATA_MS - }}}, 'c0']]} | to_json }} + stalwart_jmap_body: "{{ lookup('template', 'jmap/milter/update.json.j2') }}" when: stalwart_av_milter_id | length > 0 diff --git a/roles/web-app-stalwart/tasks/09_dns-records.yml b/roles/web-app-stalwart/tasks/09_dns-records.yml index 1906fa27b3..05270d9bfd 100644 --- a/roles/web-app-stalwart/tasks/09_dns-records.yml +++ b/roles/web-app-stalwart/tasks/09_dns-records.yml @@ -35,16 +35,7 @@ name: "{{ stalwart_dkim_selector }}._domainkey.{{ STALWART_DOMAIN_DNS_ZONE }}" solo: true value: '"{{ stalwart_dkim_public_key }}"' - - type: SRV - zone: "{{ STALWART_DOMAIN_DNS_ZONE }}" - name: "{{ STALWART_DOMAIN }}" - solo: true - service: "_submission" - proto: "_tcp" - priority: 20 - weight: 1 - port: 587 - value: "{{ STALWART_HOSTNAME }}" + # Exception: SRV only for the implicit-TLS ports the service binds (no 587/143/110). - type: SRV zone: "{{ STALWART_DOMAIN_DNS_ZONE }}" name: "{{ STALWART_DOMAIN }}" @@ -65,16 +56,6 @@ weight: 1 port: 993 value: "{{ STALWART_HOSTNAME }}" - - type: SRV - zone: "{{ STALWART_DOMAIN_DNS_ZONE }}" - name: "{{ STALWART_DOMAIN }}" - solo: true - service: "_imap" - proto: "_tcp" - priority: 20 - weight: 1 - port: 143 - value: "{{ STALWART_HOSTNAME }}" - type: SRV zone: "{{ STALWART_DOMAIN_DNS_ZONE }}" name: "{{ STALWART_DOMAIN }}" @@ -85,16 +66,6 @@ weight: 1 port: 995 value: "{{ STALWART_HOSTNAME }}" - - type: SRV - zone: "{{ STALWART_DOMAIN_DNS_ZONE }}" - name: "{{ STALWART_DOMAIN }}" - solo: true - service: "_pop3" - proto: "_tcp" - priority: 20 - weight: 1 - port: 110 - value: "{{ STALWART_HOSTNAME }}" - type: SRV zone: "{{ STALWART_DOMAIN_DNS_ZONE }}" name: "{{ STALWART_DOMAIN }}" diff --git a/roles/web-app-stalwart/tasks/manager_ops.yml b/roles/web-app-stalwart/tasks/manager_ops.yml index 16c978ffb2..10754e9304 100644 --- a/roles/web-app-stalwart/tasks/manager_ops.yml +++ b/roles/web-app-stalwart/tasks/manager_ops.yml @@ -3,10 +3,7 @@ # Manager-side operations: every task here execs into or restarts containers # of the manager-pinned stack, so only the stack host may run them. -# Exception: compose only — `compose up` won't recreate a container when -# only a bind-mounted config changed, so restart clamav explicitly to load -# the new clamav-milter.conf. Under swarm the file is a `type: config` -# object whose content-hash rotation already recreates the task. +# Exception: compose only — under swarm the config-object rotation already recreates the task. - name: "🔄 Restart clamav to apply milter config change (compose)" ansible.builtin.command: "container restart {{ STALWART_CONTAINER }}_clamav" changed_when: true @@ -16,10 +13,7 @@ - stalwart_clamav_conf is defined - stalwart_clamav_conf is changed -# Exception: compose only — the roundcube image reads its config at -# container start, so restart webmail to pick up a changed oauth.inc.php -# (compose up alone won't recreate it). Under swarm the config-object -# rotation recreates the task. +# Exception: compose only — under swarm the config-object rotation already recreates the task. - name: "🔄 Restart webmail to apply Roundcube config change (compose)" ansible.builtin.command: "container restart {{ STALWART_CONTAINER }}_webmail" changed_when: true @@ -32,17 +26,12 @@ - name: ⏳ Wait for Stalwart database and management API include_tasks: 01_wait_for_api.yml -# Exception: a failed unpack or 404 WebAdmin fails the deploy (the bundle -# download already failed hard in 00_core) — Playwright would fail later -# anyway. - name: "⚙️ Provision the Stalwart WebUI (WebAdmin) bundle" include_tasks: 02_webadmin.yml - name: "⚙️ Provision Stalwart mail domain, accounts, DKIM and DNS" include_tasks: 03_provision_domain.yml -# Exception: restart-or-defer — a restart while the OIDC issuer is down -# sticks on internal auth. - name: "🔧 Apply Stalwart OIDC directory changes" include_tasks: 10_oidc_apply.yml when: STALWART_SSO_ENABLED | bool diff --git a/roles/web-app-stalwart/templates/jmap/authentication/create.json.j2 b/roles/web-app-stalwart/templates/jmap/authentication/create.json.j2 new file mode 100644 index 0000000000..d087e485e8 --- /dev/null +++ b/roles/web-app-stalwart/templates/jmap/authentication/create.json.j2 @@ -0,0 +1,4 @@ +{ + "using": ["urn:ietf:params:jmap:core", "urn:stalwart:jmap"], + "methodCalls": [["x:Authentication/set", {"create": {"a": {{ stalwart_auth_defaults | to_json }} }}, "c0"]] +} diff --git a/roles/web-app-stalwart/templates/jmap/authentication/get.json.j2 b/roles/web-app-stalwart/templates/jmap/authentication/get.json.j2 new file mode 100644 index 0000000000..3a993dee17 --- /dev/null +++ b/roles/web-app-stalwart/templates/jmap/authentication/get.json.j2 @@ -0,0 +1,4 @@ +{ + "using": ["urn:ietf:params:jmap:core", "urn:stalwart:jmap"], + "methodCalls": [["x:Authentication/get", {"ids": null}, "c0"]] +} diff --git a/roles/web-app-stalwart/templates/jmap/authentication/update.json.j2 b/roles/web-app-stalwart/templates/jmap/authentication/update.json.j2 new file mode 100644 index 0000000000..7160a3e48d --- /dev/null +++ b/roles/web-app-stalwart/templates/jmap/authentication/update.json.j2 @@ -0,0 +1,4 @@ +{ + "using": ["urn:ietf:params:jmap:core", "urn:stalwart:jmap"], + "methodCalls": [["x:Authentication/set", {"update": {"singleton": {{ stalwart_auth_defaults | to_json }} }}, "c0"]] +} diff --git a/roles/web-app-stalwart/templates/jmap/directory/clear_audience.json.j2 b/roles/web-app-stalwart/templates/jmap/directory/clear_audience.json.j2 new file mode 100644 index 0000000000..f7f1eb04a1 --- /dev/null +++ b/roles/web-app-stalwart/templates/jmap/directory/clear_audience.json.j2 @@ -0,0 +1,4 @@ +{ + "using": ["urn:ietf:params:jmap:core", "urn:stalwart:jmap"], + "methodCalls": [["x:Directory/set", {"update": { {{ stalwart_oidc_dir_id | to_json }}: {"requireAudience": null} }}, "c0"]] +} diff --git a/roles/web-app-stalwart/templates/jmap/directory/create_oidc.json.j2 b/roles/web-app-stalwart/templates/jmap/directory/create_oidc.json.j2 new file mode 100644 index 0000000000..785ad55cee --- /dev/null +++ b/roles/web-app-stalwart/templates/jmap/directory/create_oidc.json.j2 @@ -0,0 +1,11 @@ +{ + "using": ["urn:ietf:params:jmap:core", "urn:stalwart:jmap"], + "methodCalls": [["x:Directory/set", {"create": {"kc": { + "@type": "Oidc", + "description": {{ ('Keycloak SSO (' ~ OIDC.CLIENT.REALM ~ ')') | to_json }}, + "issuerUrl": {{ OIDC.CLIENT.ISSUER_URL | to_json }}, + "claimUsername": {{ OIDC.ATTRIBUTES.USERNAME | to_json }}, + "usernameDomain": {{ STALWART_DOMAIN | to_json }}, + "claimName": "name" + }}}, "c0"]] +} diff --git a/roles/web-app-stalwart/templates/jmap/directory/get.json.j2 b/roles/web-app-stalwart/templates/jmap/directory/get.json.j2 new file mode 100644 index 0000000000..a1cd852a7b --- /dev/null +++ b/roles/web-app-stalwart/templates/jmap/directory/get.json.j2 @@ -0,0 +1,4 @@ +{ + "using": ["urn:ietf:params:jmap:core", "urn:stalwart:jmap"], + "methodCalls": [["x:Directory/get", {"ids": null}, "c0"]] +} diff --git a/roles/web-app-stalwart/templates/jmap/milter/create.json.j2 b/roles/web-app-stalwart/templates/jmap/milter/create.json.j2 new file mode 100644 index 0000000000..0dfe7281b8 --- /dev/null +++ b/roles/web-app-stalwart/templates/jmap/milter/create.json.j2 @@ -0,0 +1,12 @@ +{ + "using": ["urn:ietf:params:jmap:core", "urn:stalwart:jmap"], + "methodCalls": [["x:MtaMilter/set", {"create": {"av": { + "hostname": {{ STALWART_CLAMAV_HOST | to_json }}, + "port": {{ STALWART_CLAMAV_MILTER_PORT | int }}, + "stages": {"data": true}, + "tempFailOnError": false, + "timeoutConnect": {{ STALWART_CLAMAV_MILTER_TIMEOUT_CONNECT_MS | int }}, + "timeoutCommand": {{ STALWART_CLAMAV_MILTER_TIMEOUT_COMMAND_MS | int }}, + "timeoutData": {{ STALWART_CLAMAV_MILTER_TIMEOUT_DATA_MS | int }} + }}}, "c0"]] +} diff --git a/roles/web-app-stalwart/templates/jmap/milter/get.json.j2 b/roles/web-app-stalwart/templates/jmap/milter/get.json.j2 new file mode 100644 index 0000000000..6d236e2e89 --- /dev/null +++ b/roles/web-app-stalwart/templates/jmap/milter/get.json.j2 @@ -0,0 +1,4 @@ +{ + "using": ["urn:ietf:params:jmap:core", "urn:stalwart:jmap"], + "methodCalls": [["x:MtaMilter/get", {"ids": null}, "c0"]] +} diff --git a/roles/web-app-stalwart/templates/jmap/milter/update.json.j2 b/roles/web-app-stalwart/templates/jmap/milter/update.json.j2 new file mode 100644 index 0000000000..13cc9fea77 --- /dev/null +++ b/roles/web-app-stalwart/templates/jmap/milter/update.json.j2 @@ -0,0 +1,9 @@ +{ + "using": ["urn:ietf:params:jmap:core", "urn:stalwart:jmap"], + "methodCalls": [["x:MtaMilter/set", {"update": { {{ stalwart_av_milter_id | to_json }}: { + "tempFailOnError": false, + "timeoutConnect": {{ STALWART_CLAMAV_MILTER_TIMEOUT_CONNECT_MS | int }}, + "timeoutCommand": {{ STALWART_CLAMAV_MILTER_TIMEOUT_COMMAND_MS | int }}, + "timeoutData": {{ STALWART_CLAMAV_MILTER_TIMEOUT_DATA_MS | int }} + }}}, "c0"]] +} diff --git a/roles/web-app-stalwart/templates/jmap/rcpt/create.json.j2 b/roles/web-app-stalwart/templates/jmap/rcpt/create.json.j2 new file mode 100644 index 0000000000..a5df60533b --- /dev/null +++ b/roles/web-app-stalwart/templates/jmap/rcpt/create.json.j2 @@ -0,0 +1,4 @@ +{ + "using": ["urn:ietf:params:jmap:core", "urn:stalwart:jmap"], + "methodCalls": [["x:MtaStageRcpt/set", {"create": {"r": {"allowRelaying": {"else": {{ stalwart_relay_expr | trim | to_json }} }}}}, "c0"]] +} diff --git a/roles/web-app-stalwart/templates/jmap/rcpt/get.json.j2 b/roles/web-app-stalwart/templates/jmap/rcpt/get.json.j2 new file mode 100644 index 0000000000..ac0c8cb2b1 --- /dev/null +++ b/roles/web-app-stalwart/templates/jmap/rcpt/get.json.j2 @@ -0,0 +1,4 @@ +{ + "using": ["urn:ietf:params:jmap:core", "urn:stalwart:jmap"], + "methodCalls": [["x:MtaStageRcpt/get", {"ids": null}, "c0"]] +} diff --git a/roles/web-app-stalwart/templates/jmap/rcpt/update.json.j2 b/roles/web-app-stalwart/templates/jmap/rcpt/update.json.j2 new file mode 100644 index 0000000000..027616add2 --- /dev/null +++ b/roles/web-app-stalwart/templates/jmap/rcpt/update.json.j2 @@ -0,0 +1,4 @@ +{ + "using": ["urn:ietf:params:jmap:core", "urn:stalwart:jmap"], + "methodCalls": [["x:MtaStageRcpt/set", {"update": {"singleton": {"allowRelaying": {"else": {{ stalwart_relay_expr | trim | to_json }} }}}}, "c0"]] +} diff --git a/roles/web-app-stalwart/templates/jmap/role_get.json.j2 b/roles/web-app-stalwart/templates/jmap/role_get.json.j2 new file mode 100644 index 0000000000..0b4e8d302f --- /dev/null +++ b/roles/web-app-stalwart/templates/jmap/role_get.json.j2 @@ -0,0 +1,4 @@ +{ + "using": ["urn:ietf:params:jmap:core", "urn:stalwart:jmap"], + "methodCalls": [["x:Role/get", {"ids": null}, "c0"]] +} diff --git a/roles/web-app-stalwart/vars/main.yml b/roles/web-app-stalwart/vars/main.yml index f28e7c2670..3765ed1268 100644 --- a/roles/web-app-stalwart/vars/main.yml +++ b/roles/web-app-stalwart/vars/main.yml @@ -6,18 +6,12 @@ database_password: "{{ lookup('config', application_id, 'credentials.database_pa STALWART_VOLUMES_DIR: "{{ lookup('container', application_id, 'directories.volumes') }}" STALWART_CONFIG_DIR: "{{ [ STALWART_VOLUMES_DIR, 'etc' ] | path_join }}" -# Exception: JSON bootstrap (data store) only; everything else lives in the -# database. STALWART_CONFIG_FILE: "{{ [ STALWART_CONFIG_DIR, 'config.json' ] | path_join }}" container_port: "{{ lookup('config', application_id, 'services.stalwart.ports.internal.http') }}" -# Exception: management endpoints sit on the internal HTTP listener (bypass -# the public proxy); reached via `container exec … curl`, hence localhost. STALWART_LOCAL_BASE_URL: "http://localhost:{{ container_port }}" STALWART_JMAP_URL: "{{ STALWART_LOCAL_BASE_URL }}/jmap/" -# Exception: mode-aware exec target — bare container name in compose, resolved -# task container id ($(resolve-container-id …)) in swarm; must stay unquoted in -# shell tasks. +# Exception: must stay unquoted in shell tasks — resolves to $(resolve-container-id …) in swarm. STALWART_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, 'stalwart') }}" STALWART_DOMAIN: "{{ lookup('config', application_id, 'services.stalwart.domain') }}" @@ -31,58 +25,32 @@ STALWART_CONTAINER: "{{ lookup('config', application_id, 'services.stalwart.name STALWART_ANTIVIRUS_ENABLED: "{{ lookup('config', application_id, 'services.clamav.enabled') | bool }}" STALWART_CLAMAV_HOST: "clamav" STALWART_CLAMAV_MILTER_PORT: "{{ lookup('config', application_id, 'services.clamav.ports.internal.milter') }}" -# Exception: milter timeouts (ms) — with fail-open (tempFailOnError:false), -# short timeouts let Stalwart accept mail while clamd warms up instead of -# blocking the DATA stage. STALWART_CLAMAV_MILTER_TIMEOUT_CONNECT_MS: 5000 STALWART_CLAMAV_MILTER_TIMEOUT_COMMAND_MS: 5000 STALWART_CLAMAV_MILTER_TIMEOUT_DATA_MS: 15000 STALWART_CLAMAV_MILTER_CONF: "{{ [ STALWART_CONFIG_DIR, 'clamav-milter.conf' ] | path_join }}" -# Exception: webmail is the secondary canonical (lookup('domain') only exposes -# the primary). STALWART_WEBMAIL_DOMAIN: "{{ lookup('config', application_id, 'domains.canonical.webmail') }}" STALWART_WEBMAIL_HTTP_PORT: "{{ lookup('config', application_id, 'services.webmail.ports.local.http') }}" -# Exception: Roundcube OAuth config include — the template self-gates so the -# bind source always renders, even with SSO disabled. STALWART_WEBMAIL_CONFIG_DIR: "{{ [ STALWART_VOLUMES_DIR, 'webmail' ] | path_join }}" STALWART_WEBMAIL_OAUTH_CONFIG: "{{ [ STALWART_WEBMAIL_CONFIG_DIR, 'oauth.inc.php' ] | path_join }}" -# Exception: self-declared in meta/services.yml (one SPOT, also read by -# web-app-keycloak). STALWART_WEBMAIL_OIDC_CLIENT_ID: "{{ lookup('config', application_id, 'services.sso.oidc.webmail_client_id') }}" -# Exception: Stalwart fetches the WebUI (WebAdmin) bundle from GitHub on first -# boot, which fails behind restricted egress, so the controller stages it -# locally (see 02_webadmin.yml). Pinned in meta/services.yml next to the -# stalwart image version. STALWART_WEBUI_VERSION: "{{ lookup('config', application_id, 'services.stalwart.webui_version') }}" STALWART_WEBUI_RESOURCE_URL: "https://github.com/stalwartlabs/webui/releases/download/{{ STALWART_WEBUI_VERSION }}/webui.zip" -# Exception: host-level cache under the managed cache tree — matrix rounds -# purge the instance dir, and re-downloading per round runs into GitHub rate -# limits. STALWART_WEBUI_CACHE_FILE: "/var/cache/infinito/core/cache/package/stalwart-webui/webui-{{ STALWART_WEBUI_VERSION }}.zip" STALWART_WEBUI_LOCAL_FILE: "{{ [ STALWART_CONFIG_DIR, 'webui.zip' ] | path_join }}" STALWART_WEBUI_CONTAINER_FILE: "/etc/stalwart/webui.zip" STALWART_WEBUI_LOCAL_URL: "file://{{ STALWART_WEBUI_CONTAINER_FILE }}" -# Exception: identity of the upstream WebAdmin Application record (validated -# against the live JMAP x:Application/get response for the pinned Stalwart -# version). STALWART_WEBUI_APP_DESCRIPTION: "Stalwart Web Interface" - STALWART_IP4_PUBLIC: "{{ DOCKER_PUBLIC_BIND_HOST }}" STALWART_ACTIVE_PROVIDER: "{{ MAIL_PROVIDER == application_id }}" STALWART_ADMIN_USER: "admin" STALWART_ADMIN_PASSWORD: "{{ lookup('config', application_id, 'credentials.admin_password') }}" -# Exception: DMARC report address (DKIM selector + key are read at runtime in -# 08_read_dkim.yml). STALWART_DMARC_RUF: "{{ lookup('config', application_id, 'users.administrator.email') }}" -# Exception: internal nets trusted to relay without SMTP AUTH under SSO (see -# tasks/06_oidc.yml). One SPOT with the platform's trusted-internal CIDR set -# (loopback + the RFC1918 ranges docker allocates from) instead of re-spelling -# it here. STALWART_TRUSTED_NETWORKS: "{{ NETWORK_TRUSTED_PROXY_CIDRS }}" STALWART_SSO_ENABLED: "{{ lookup('sso', application_id, 'is_enabled') | bool }}" diff --git a/roles/web-app-taiga/templates/Dockerfile.backend.j2 b/roles/web-app-taiga/templates/Dockerfile.backend.j2 index 05977480fe..ade55d019c 100644 --- a/roles/web-app-taiga/templates/Dockerfile.backend.j2 +++ b/roles/web-app-taiga/templates/Dockerfile.backend.j2 @@ -1,8 +1,8 @@ FROM taigaio/taiga-back:{{ TAIGA_VERSION }} {% if TAIGA_OIDC_ENABLED | bool %} -# Exception: the OIDC plugin installs from the repository's back/ subdirectory, -# so git is required only for this build step and purged again afterwards. +# The OIDC backend lives in the repository's back/ subdirectory, so git is +# required only for this build step. RUN rm -rf /var/lib/apt/lists/* && \ apt-get -o Acquire::Retries=3 update && \ apt-get -o Acquire::Retries=3 install -y --no-install-recommends git && \ diff --git a/roles/web-app-zammad/vars/main.yml b/roles/web-app-zammad/vars/main.yml index 964783da6e..c0b10c67cb 100644 --- a/roles/web-app-zammad/vars/main.yml +++ b/roles/web-app-zammad/vars/main.yml @@ -55,5 +55,5 @@ ZAMMAD_LDAP_ENABLED: "{{ lookup('config', application_id, 'services.ldap.enabled ZAMMAD_MAIL: "{{ lookup('email', application_id) if ZAMMAD_EMAIL_ENABLED else {} }}" ZAMMAD_HELPDESK_USER: "{{ lookup('users', 'helpdesk') if ZAMMAD_EMAIL_ENABLED else {} }}" ZAMMAD_HELPDESK_EMAIL: "{{ ZAMMAD_HELPDESK_USER.email | default('') }}" -# The provider enforces change_pw_next_login → user password rejects SMTP AUTH (535); per-app token is required. +# Exception: the user password rejects SMTP AUTH (535, change_pw_next_login) — only the per-app token works. ZAMMAD_HELPDESK_PASS: "{{ (ZAMMAD_HELPDESK_USER.tokens | default({})).get(MAIL_PROVIDER, '') }}" diff --git a/scripts/system/network/dns/common.sh b/scripts/system/network/dns/common.sh index 29efd7b7be..4cb6f205a9 100755 --- a/scripts/system/network/dns/common.sh +++ b/scripts/system/network/dns/common.sh @@ -9,7 +9,6 @@ DNS_HOSTS_BLOCK_END="# END infinito-dns-fallback" DNS_HOSTS_GENERATOR="${DNS_PROJECT_ROOT}/cli/meta/domains/__main__.py" DNS_HOSTS_FALLBACK_DEFAULT_RAW="${DNS_DOMAIN} dashboard.${DNS_DOMAIN} matomo.${DNS_DOMAIN}" -# Used by setup.sh/remove.sh after sourcing this shared helper. # shellcheck disable=SC2034 DNS_NM_CONF="/etc/NetworkManager/conf.d/00-infinito-dnsmasq.conf" DNS_NM_DNSMASQ_DIR="/etc/NetworkManager/dnsmasq.d" @@ -101,7 +100,7 @@ dns_read_hosts_fallback_entries() { dns_rewrite_hosts_file() { local tmp="$1" - # Keep the existing inode when the hosts file is bind-mounted (for example /etc/hosts in CI containers). + # Exception: replacing the inode breaks a bind-mounted hosts file (/etc/hosts in CI containers) — write in place. if [[ -e "${DNS_HOSTS_FILE}" ]]; then dns_write_file_in_place "${tmp}" "${DNS_HOSTS_FILE}" else @@ -158,16 +157,24 @@ dns_remove_hosts_fallback() { } dns_test_resolution() { - local checked=0 failed=0 host + local checked=0 failed=0 host attempt echo echo ">>> Testing resolution" if [[ "${DNS_HOSTS_FILE}" == "/etc/hosts" ]]; then while IFS= read -r host; do - if ! getent hosts "${host}"; then - echo " FAIL: ${host}" - failed=$((failed + 1)) - fi + # Exception: retried — a freshly restarted resolver may need a moment before it answers. + for attempt in 1 2 3; do + if getent hosts "${host}"; then + break + fi + if [[ "${attempt}" -eq 3 ]]; then + echo " FAIL: ${host}" + failed=$((failed + 1)) + else + sleep 1 + fi + done checked=$((checked + 1)) if [[ "${checked}" -ge 3 ]]; then break diff --git a/tests/integration/infrastructure/services/test_mail_provider_dependency.py b/tests/integration/infrastructure/services/test_mail_provider_dependency.py index b57b7842af..f58a828178 100644 --- a/tests/integration/infrastructure/services/test_mail_provider_dependency.py +++ b/tests/integration/infrastructure/services/test_mail_provider_dependency.py @@ -8,19 +8,12 @@ from utils.roles.mapping import ROLE_FILE_META_SERVICES from . import PROJECT_ROOT -# The default email provider is web-app-stalwart; web-app-mailu is a fully -# supported alternative selected via the MAIL_PROVIDER variable. Both are -# providers (they call lookup('email') as the source of truth, not as dependent -# consumers). _PROVIDER_ROLES = {"web-app-stalwart", "web-app-mailu"} _EMAIL_SERVICE_KEY = "email" -# Patterns that indicate an email dependency on the mail provider — either a -# direct role ref or the MAIL_PROVIDER selector consumers gate their email on. _PROVIDER_REF_RE = re.compile(r"web-app-(?:stalwart|mailu)|MAIL_PROVIDER") _EMAIL_LOOKUP_RE = re.compile(r"""lookup\(\s*['"]email['"]""") -# File extensions to scan within a role _SCAN_EXTENSIONS = {".yml", ".yaml", ".j2", ".py", ".sh", ".conf", ".env"} @@ -105,10 +98,6 @@ class TestMailProviderServiceDependency(unittest.TestCase): role_name = role_path.name if role_name in _PROVIDER_ROLES: continue - # Email transport providers (msmtp, smtp/postfix) and the - # email-alerting / mail-health roles implement or directly - # service the email subsystem; they call lookup('email') as the - # source of truth, not as dependent consumers. Exempt them. if role_name.startswith("sys-svc-mail") or role_name in { "sys-ctl-alm-email", "sys-ctl-hlth-msmtp", diff --git a/tests/integration/roles/meta/services/test_dynamic_flags.py b/tests/integration/roles/meta/services/test_dynamic_flags.py index 0bd6b36613..60d2363e73 100644 --- a/tests/integration/roles/meta/services/test_dynamic_flags.py +++ b/tests/integration/roles/meta/services/test_dynamic_flags.py @@ -137,8 +137,6 @@ def _suppressed_inline_flags(file_path: Path) -> set[tuple[str, str]]: return result -# Consumer ``email`` blocks reference the MAIL_PROVIDER indirection variable -# instead of a concrete provider role (Stalwart <-> Mailu is a one-var switch). _MAIL_PROVIDER_INDIRECTION = "MAIL_PROVIDER in group_names" @@ -206,7 +204,6 @@ class TestServicesDynamicFlags(unittest.TestCase): f"databases)." ) continue - # email slot references MAIL_PROVIDER, not a provider role. if ( service_key == "email" and isinstance(value, str) diff --git a/tests/lint/docker/dockerfile/apt/test_update_purge_lists.py b/tests/lint/docker/dockerfile/apt/test_update_purge_lists.py index 74e2da2219..d87218843c 100644 --- a/tests/lint/docker/dockerfile/apt/test_update_purge_lists.py +++ b/tests/lint/docker/dockerfile/apt/test_update_purge_lists.py @@ -52,15 +52,10 @@ if TYPE_CHECKING: _REPO_ROOT = PROJECT_ROOT _ROLES_ROOT = _REPO_ROOT / "roles" -# Exception: strips Jinja2 control tags so they don't fragment RUN-block -# parsing in templated Dockerfiles. Any branch that ships an unsafe RUN must -# fail the lint, so collapsing the branches into one text body is correct. +# Exception: collapsing Jinja branches into one text body is correct — any branch shipping an unsafe RUN must fail. _J2_CTRL_RE = re.compile(r"\{%-?.*?-?%\}", re.DOTALL) _RUN_START_RE = re.compile(r"^\s*RUN\b", re.IGNORECASE) -# Exception: matches `apt-get update` with optional `-flag` / `--flag` / -# `-o KEY=VAL` tokens in between, but not arbitrary words (so -# `apt-get install update` does NOT match). _APT_UPDATE_RE = re.compile( r"\bapt-get\b(?:\s+-\S+(?:\s+[^-\s]\S*)?)*\s+update\b", re.IGNORECASE, diff --git a/tests/unit/roles/sys-svc-compose/files/test_compose.py b/tests/unit/roles/sys-svc-compose/files/test_compose.py index 051d82903f..9cb70b6766 100644 --- a/tests/unit/roles/sys-svc-compose/files/test_compose.py +++ b/tests/unit/roles/sys-svc-compose/files/test_compose.py @@ -30,8 +30,6 @@ class TestInfinitoComposeWrapper(unittest.TestCase): cls.script = load_script_module() def setUp(self): - # Exception: disable the wrapper's cache-override branch; tests use - # mocked is_file. self._env_patch = patch.dict( os.environ, {"INFINITO_CACHE_PACKAGE_FRONTEND_IP": ""}, clear=False ) @@ -697,8 +695,6 @@ class TestCaOverrideStaleDetection(unittest.TestCase): self.assertFalse(s.ca_override_is_stale(base, override)) def test_fresh_when_override_is_strict_subset(self): - # Exception: an override may legitimately wrap only a subset; a subset - # MUST NOT be flagged. import tempfile s = self.script diff --git a/tests/unit/roles/web_app_stalwart/test_files_migrate_from_mailu.py b/tests/unit/roles/web_app_stalwart/test_files_migrate_from_mailu.py index 6f28f7a369..2e4aef032c 100644 --- a/tests/unit/roles/web_app_stalwart/test_files_migrate_from_mailu.py +++ b/tests/unit/roles/web_app_stalwart/test_files_migrate_from_mailu.py @@ -12,7 +12,7 @@ def _load_module(): spec = importlib.util.spec_from_file_location("migrate_from_mailu", str(path)) mod = importlib.util.module_from_spec(spec) assert spec and spec.loader - # dataclasses resolve their module via sys.modules — register before exec. + # Exception: dataclasses resolve their module via sys.modules — register before exec. sys.modules["migrate_from_mailu"] = mod spec.loader.exec_module(mod) return mod @@ -65,7 +65,6 @@ class TestFlagAndFolderMapping(unittest.TestCase): ) self.assertEqual(self.m.maildir_flags_to_imap("123.M1.host:2,"), "") self.assertEqual(self.m.maildir_flags_to_imap("123.M1.host"), "") - # Unknown info letters are ignored, known ones kept. self.assertEqual(self.m.maildir_flags_to_imap("a:2,XR"), "(\\Answered)") def test_maildir_folder_to_imap(self): @@ -99,7 +98,6 @@ class TestMaildirWalk(unittest.TestCase): (self.account / ".Archive" / "cur" / "3.host:2,").write_bytes( b"Message-ID: <3@x>\r\n\r\nc" ) - # Non-maildir noise must be ignored. (self.account / ".dovecot.sieve.d").mkdir() def test_iter_maildir_folders_and_messages(self): @@ -129,7 +127,7 @@ class TestMaildirWalk(unittest.TestCase): ) stats = self.m.AccountStats() self.m.migrate_account(imap, self.account, "/", stats) - self.assertEqual(stats.folder("INBOX").appended, 1) # only <2@x> + self.assertEqual(stats.folder("INBOX").appended, 1) self.assertEqual(stats.folder("INBOX").skipped, 1) self.assertEqual(stats.folder("Archive").skipped, 1) self.assertEqual(stats.folder("Archive").appended, 0) diff --git a/tests/unit/utils/cache/test_files.py b/tests/unit/utils/cache/test_files.py index 77e6e47f0f..601046de84 100644 --- a/tests/unit/utils/cache/test_files.py +++ b/tests/unit/utils/cache/test_files.py @@ -57,7 +57,6 @@ class TestReadText(_ProjectRootFixture, unittest.TestCase): path = _touch(self.root / "a.txt", "first") self.assertEqual(read_text(str(path)), "first") path.write_text("changed", encoding="utf-8") - # Same string path → cache hit; the on-disk change is not seen. self.assertEqual(read_text(str(path)), "first") def test_reset_invalidates_cache(self) -> None: @@ -75,7 +74,6 @@ class TestReadText(_ProjectRootFixture, unittest.TestCase): class TestIterProjectFiles(_ProjectRootFixture, unittest.TestCase): def setUp(self) -> None: super().setUp() - # Build a small synthetic tree. _touch(self.root / f"roles/web-app-foo/{ROLE_FILE_META_SERVICES}", "foo: 1") _touch(self.root / "roles/web-app-foo/templates/x.j2", "{{ x }}") _touch(self.root / "docs/readme.md", "# Hi") @@ -86,7 +84,6 @@ class TestIterProjectFiles(_ProjectRootFixture, unittest.TestCase): def test_skip_dirs_pruned(self) -> None: all_paths = set(iter_project_files()) - # The pruned dirs MUST never appear in the walk. self.assertFalse( any("/.git/" in p for p in all_paths), f".git not pruned in {all_paths}", @@ -105,7 +102,6 @@ class TestIterProjectFiles(_ProjectRootFixture, unittest.TestCase): _reset() all_paths = set(iter_project_files()) self.assertFalse(any("/local-tool-out/" in p for p in all_paths)) - # sanity: normal project files still present self.assertTrue(any(p.endswith("readme.md") for p in all_paths)) def test_extensions_filter(self) -> None: @@ -127,19 +123,15 @@ class TestIterProjectFiles(_ProjectRootFixture, unittest.TestCase): self.assertEqual(without_tests, []) def test_exclude_dirs_path_segment_match(self) -> None: - # Excluding "docs" must drop the markdown file under docs/. kept = list(iter_project_files(exclude_dirs=("docs",))) self.assertFalse(any(p.endswith("readme.md") for p in kept)) def test_walk_is_cached_across_calls(self) -> None: - # First call populates the cache, then we add a new file: a fresh - # walk would discover it; the cache MUST not. first = set(iter_project_files()) _touch(self.root / "after.txt", "late") second = set(iter_project_files()) self.assertEqual(first, second) - # _reset() clears the cache → the new file is now visible. _reset() third = set(iter_project_files()) self.assertIn(str(self.root / "after.txt"), third) @@ -172,15 +164,12 @@ class TestIterProjectFilesWithContent(_ProjectRootFixture, unittest.TestCase): class TestReset(_ProjectRootFixture, unittest.TestCase): def test_reset_clears_both_caches(self) -> None: _touch(self.root / "x.txt", "v1") - list(iter_project_files()) # populate walk cache - read_text(str(self.root / "x.txt")) # populate text cache - # Mutate underlying state. + list(iter_project_files()) + read_text(str(self.root / "x.txt")) _touch(self.root / "y.txt", "v2") (self.root / "x.txt").write_text("v1-changed", encoding="utf-8") - # Cached views still see the OLD state. self.assertNotIn(str(self.root / "y.txt"), set(iter_project_files())) self.assertEqual(read_text(str(self.root / "x.txt")), "v1") - # Reset → fresh views. _reset() self.assertIn(str(self.root / "y.txt"), set(iter_project_files())) self.assertEqual(read_text(str(self.root / "x.txt")), "v1-changed") diff --git a/tests/unit/utils/templating/test_ansible.py b/tests/unit/utils/templating/test_ansible.py index e40baec9fc..db9eb85667 100644 --- a/tests/unit/utils/templating/test_ansible.py +++ b/tests/unit/utils/templating/test_ansible.py @@ -205,7 +205,6 @@ class TestTemplatingRenderStrict(unittest.TestCase): self.assertEqual(out, ca_cert_host("infinito.nexus")) def test_inline_conditional_with_concat(self): - # Mirrors web-app-mailu/meta/server.yml (inline conditional + ~ concat). raw = ( "{{ ('mail.' ~ DOMAIN_PRIMARY) if MAIL_PROVIDER == 'web-app-mailu' " "else ('legacy-mail.' ~ DOMAIN_PRIMARY) }}" @@ -231,7 +230,6 @@ class TestTemplatingRenderStrict(unittest.TestCase): ), "legacy-mail.example.com", ) - # Unset MAIL_PROVIDER takes the else branch. self.assertEqual( render_ansible_strict( templar=None, diff --git a/utils/github/variant/limits.py b/utils/github/variant/limits.py index 478021d56a..47697de1f4 100644 --- a/utils/github/variant/limits.py +++ b/utils/github/variant/limits.py @@ -4,13 +4,14 @@ Kept apart from :mod:`utils.github.variant.bundles`, which reaches yaml and humanfriendly at import time: the env handlers that seed these defaults are imported by the .env generator on the bare bootstrap python, where no third-party module exists. This module must stay stdlib-only. + +``DEFAULT_MAX_STORAGE`` is also a runtime proxy: hosted runners kill jobs at +6 h, and heavy multi-round roles (nextcloud) only fit that wall with <= 2 +variants per bundle — the cap must stay below their lightest 3-variant sum or +the greedy packer overshoots. """ from __future__ import annotations DEFAULT_BUNDLE_SIZE = 3 -# Rationale: also a runtime proxy — hosted runners kill jobs at 6h, and heavy -# multi-round roles (nextcloud) only fit that wall with <= 2 variants per -# bundle. Keep the cap below their lightest 3-variant sum or the greedy packer -# overshoots. DEFAULT_MAX_STORAGE = "330GB"