diff --git a/roles/web-app-stalwart/README.md b/roles/web-app-stalwart/README.md index e1c2cc16a0..2afc4d12ca 100644 --- a/roles/web-app-stalwart/README.md +++ b/roles/web-app-stalwart/README.md @@ -148,6 +148,13 @@ delegates **interactive** authentication to Keycloak: `preferred_username` claim to the provisioned account. - **Roundcube** logs users in over OAuth2 and talks to Stalwart with **XOAUTH2** (`templates/roundcube-oauth.inc.php.j2`). +- The OIDC directory skips the audience check and gives Keycloak tokens without + Stalwart scopes access to mail, contacts, calendars and files + (`STALWART_OIDC_TOKEN_VALIDATION`). Tokens of the `stalwart-webui` client get + full access, because the WebUI Application names it as its `oauthClientId`. +- With SSO disabled the WebUI Application carries no `oauthClientId`, so the + WebUI signs in against Stalwart's own OAuth server with its client metadata + document. **Design constraint (validated against the live JMAP schema):** Stalwart's authentication directory is *Internal XOR one external directory* — there is no @@ -193,7 +200,7 @@ account (or the Keycloak SSO token when SSO is enabled). instance dir, and per-round downloads hit GitHub rate limits) and bind-mounts it read-only. The `update:` block next to `webui_version` in `meta/services.yml` names the upstream tags, so the version-source updater - bumps the bundle on its own. + bumps the bundle on its own, within the `v2.` line that server 1.x serves. - **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` @@ -279,6 +286,43 @@ The provider cutover is an inventory change; mailbox data moves with it when the The cutover is covered end to end by [`files/test/test.sh`](files/test/test.sh), which runs as this role's CLI test whenever `web-app-mailu` is co-deployed — matrix **variant 1**, the round where SSO is off, because the import authenticates with per-account passwords. The whole scenario runs inside the deployed host and needs nothing from the environment around it: it stores mail in both directions in the legacy Mailu, confirms it landed in the maildir volume, runs [`files/python/migrate_from_mailu.py`](files/python/migrate_from_mailu.py) — the same script and argv a real cutover uses — and then asserts over IMAP that the stored mail survived and that live mail still flows. No redeploy is involved; the cutover is a docker-level data move. +## Upgrading from 0.16 + +Stalwart 1.x refuses to open a 0.16 store and has no in-place upgrade. Before it replaces a running server, the deploy reads the layout of the store that server serves and stops when the store predates 1.0 ([`tasks/store_guard.yml`](tasks/store_guard.yml)). A store from before 1.0 keeps a `bigint` column `v` in table `u`, a 1.x store a `bytea` one. Migrate the store with [`stalwart-migrate`](https://github.com/stalwartlabs/stalwart-migrate) into a new database and swap it in under the role's database name. That name is fixed to `stalwart` ([`plugins/lookup/database.py`](../../plugins/lookup/database.py) derives it from the entity name), so the migration targets a second database that later takes over the name. + +1. Make sure the server runs Stalwart `v0.16.27`; `stalwart-migrate` reads no other release. Upgrade an older 0.16 server with the previous revision of this role first. +2. Back up the database `stalwart` (for example `pg_dump -Fc -d stalwart -f stalwart-v016.dump`) and the role's volumes. +3. As a PostgreSQL superuser, create the empty target database, owned by the role's database user: + + ```sql + CREATE DATABASE stalwart_v1 OWNER stalwart; + ``` + +4. Copy the rendered `config.json` (`STALWART_CONFIG_FILE`, `etc/config.json` in the role's volumes directory) into a new directory and set its `"database"` to `"stalwart_v1"`. This file is the `--target`. +5. Answer the conversion questions and copy the data while 0.16 keeps serving. Run the tool on the network the `stalwart` container reaches its database on (`docker inspect stalwart`), so the hosts in both files resolve: + + ```sh + docker run --rm -it --network \ + -v /etc:/etc/stalwart:ro \ + -v :/etc/stalwart-v1 \ + -v :/var/lib/stalwart-migrate \ + stalwartlabs/stalwart-migrate:1.0.0 prepare \ + --source /etc/stalwart/config.json \ + --state /var/lib/stalwart-migrate + ``` + + Then run the same container with `run --source /etc/stalwart/config.json --target /etc/stalwart-v1/config.json --state /var/lib/stalwart-migrate`. `run` copies only what changed since the previous run and may be repeated. +6. Stop the Stalwart server (`docker stop stalwart` in compose, `docker service scale _stalwart=0` in swarm) and run the same container with `run --final` and the same options. It verifies the copy and writes `final-report.txt` into the state directory. +7. Swap the databases, as a PostgreSQL superuser connected to the `postgres` database: + + ```sql + ALTER DATABASE stalwart RENAME TO stalwart_v016; + ALTER DATABASE stalwart_v1 RENAME TO stalwart; + ``` + +8. Deploy this role. The store guard reads only the store of a running server, so it lets the deploy replace the stopped server, and Stalwart 1.x starts on the migrated store. +9. Keep `stalwart_v016`, the dump and the state directory until 1.x is verified. `stalwart-migrate rollback` reads the state directory to copy the 1.x store back into a new 0.16 store. + ## Verifying a production server Deploying against a publicly reachable mail server additionally asserts that server's live **hard facts** — the records and listeners either match the deployed configuration or they do not. There is no mail-flow scenario here; that is what the suites above are for. diff --git a/roles/web-app-stalwart/files/sql/store_layout.sql b/roles/web-app-stalwart/files/sql/store_layout.sql new file mode 100644 index 0000000000..8482b72899 --- /dev/null +++ b/roles/web-app-stalwart/files/sql/store_layout.sql @@ -0,0 +1,5 @@ +SELECT format_type(attribute.atttypid, attribute.atttypmod) +FROM pg_catalog.pg_attribute AS attribute +WHERE attribute.attrelid = to_regclass('u') + AND attribute.attname = 'v' + AND NOT attribute.attisdropped; diff --git a/roles/web-app-stalwart/meta/services.yml b/roles/web-app-stalwart/meta/services.yml index ecd22eddc7..6cd7533ebb 100644 --- a/roles/web-app-stalwart/meta/services.yml +++ b/roles/web-app-stalwart/meta/services.yml @@ -48,6 +48,7 @@ stalwart: key: webui_version type: git_tags repository: https://github.com/stalwartlabs/webui.git + match: "v2." name: stalwart backup: project_hard_restart: true diff --git a/roles/web-app-stalwart/tasks/00_core.yml b/roles/web-app-stalwart/tasks/00_core.yml index a6dd7b16d8..9dbc8f7761 100644 --- a/roles/web-app-stalwart/tasks/00_core.yml +++ b/roles/web-app-stalwart/tasks/00_core.yml @@ -11,6 +11,10 @@ `.test` domain for local/CI stacks. quiet: true +- name: "🛡️ Refuse to replace a Stalwart that serves a store from before 1.0" + include_tasks: store_guard.yml + when: IS_STACK_HOST | bool + - name: "🔴 Disable SMTP to avoid port conflicts" include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-mail-smtp/tasks/disable.yml') }}" diff --git a/roles/web-app-stalwart/tasks/02_webadmin.yml b/roles/web-app-stalwart/tasks/02_webadmin.yml index 37f1de0f3c..f79b5b7ec1 100644 --- a/roles/web-app-stalwart/tasks/02_webadmin.yml +++ b/roles/web-app-stalwart/tasks/02_webadmin.yml @@ -36,7 +36,7 @@ {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], 'methodCalls': [['x:Application/set', {'update': {stalwart_webui_app_id: {'resourceUrl': STALWART_WEBUI_LOCAL_URL, - 'oauthClientId': STALWART_WEBUI_OAUTH_CLIENT_ID}}}, + 'oauthClientId': STALWART_WEBUI_OAUTH_CLIENT_ID if STALWART_SSO_ENABLED | bool else none}}}, 'c0']]} | to_json }} - name: "📦 Unpack the WebUI bundle from the local file" diff --git a/roles/web-app-stalwart/tasks/06_oidc.yml b/roles/web-app-stalwart/tasks/06_oidc.yml index a042e1f990..b6908ca085 100644 --- a/roles/web-app-stalwart/tasks/06_oidc.yml +++ b/roles/web-app-stalwart/tasks/06_oidc.yml @@ -28,10 +28,10 @@ stalwart_oidc_dir_id: "{{ stalwart_jmap.methodResponses[0][1].created.kc.id }}" when: stalwart_oidc_dir_id | length == 0 -- name: "🧹 Clear the OIDC directory's required audience" +- name: "🔧 Accept Keycloak tokens without a Stalwart audience or mail scope" include_tasks: jmap_call.yml vars: - stalwart_jmap_body: "{{ lookup('template', 'jmap/directory/clear_audience.json.j2') }}" + stalwart_jmap_body: "{{ lookup('template', 'jmap/directory/token_validation.json.j2') }}" when: stalwart_oidc_dir_id | length > 0 - name: "📖 List Stalwart built-in roles" diff --git a/roles/web-app-stalwart/tasks/07_antivirus.yml b/roles/web-app-stalwart/tasks/07_antivirus.yml index 8391e25fbd..91e947ede3 100644 --- a/roles/web-app-stalwart/tasks/07_antivirus.yml +++ b/roles/web-app-stalwart/tasks/07_antivirus.yml @@ -1,5 +1,5 @@ --- -# Register the ClamAV container as a DATA-stage milter (idempotent by hostname). +# Register the ClamAV container as a DATA-stage milter (idempotent by host). # 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" @@ -11,7 +11,7 @@ ansible.builtin.set_fact: stalwart_av_milter_id: >- {{ (stalwart_jmap.methodResponses[0][1].list - | selectattr('hostname', 'equalto', STALWART_CLAMAV_HOST) + | selectattr('host', 'equalto', STALWART_CLAMAV_HOST) | map(attribute='id') | first) | default('') }} - name: "📁 Create the ClamAV milter" diff --git a/roles/web-app-stalwart/tasks/store_guard.yml b/roles/web-app-stalwart/tasks/store_guard.yml new file mode 100644 index 0000000000..14cbff4975 --- /dev/null +++ b/roles/web-app-stalwart/tasks/store_guard.yml @@ -0,0 +1,34 @@ +--- +# Stalwart 1.x keeps its schema marker in table `u` (v bytea); every 0.x store keeps its bigint quota counters under the same name. + +- name: "🔍 Find a running Stalwart server of this deployment" + ansible.builtin.command: >- + container ps -q --filter status=running + --filter {{ ('label=com.docker.swarm.service.name=' ~ lookup('container_service', application_id, 'stalwart')) + if DEPLOYMENT_MODE == 'swarm' else ('name=^' ~ STALWART_CONTAINER ~ '$') }} + register: stalwart_running_server + changed_when: false + +- name: "🔍 Read the store layout the running Stalwart serves" + database_query: + config: "{{ lookup('database', application_id) }}" + query_file: "{{ role_path }}/files/sql/store_layout.sql" + expect_rows: true + mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + register: stalwart_store_layout + changed_when: false + when: stalwart_running_server.stdout | trim | length > 0 + +- name: "✅ Ensure the running Stalwart serves a 1.x store" + ansible.builtin.assert: + that: + - (stalwart_store_layout.rows | map('first') | list) == ['bytea'] + fail_msg: >- + The running Stalwart serves a store from before 1.0 (type of column u.v: + {{ stalwart_store_layout.rows | map('first') | list }}, a 1.x store holds ['bytea']). + Stalwart {{ lookup('config', application_id, 'services.stalwart.version') }} refuses to open it and has no in-place upgrade, + so the deploy stops before it replaces the running server. Migrate the store into a new + database with stalwart-migrate and swap it in as '{{ lookup('database', application_id, 'name') }}', + following "Upgrading from 0.16" in roles/web-app-stalwart/README.md, then deploy again. + quiet: true + when: stalwart_running_server.stdout | trim | length > 0 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 index 785ad55cee..370271efda 100644 --- a/roles/web-app-stalwart/templates/jmap/directory/create_oidc.json.j2 +++ b/roles/web-app-stalwart/templates/jmap/directory/create_oidc.json.j2 @@ -6,6 +6,8 @@ "issuerUrl": {{ OIDC.CLIENT.ISSUER_URL | to_json }}, "claimUsername": {{ OIDC.ATTRIBUTES.USERNAME | to_json }}, "usernameDomain": {{ STALWART_DOMAIN | to_json }}, - "claimName": "name" + "claimName": "name", + "skipAudienceValidation": {{ STALWART_OIDC_TOKEN_VALIDATION.skipAudienceValidation | to_json }}, + "unscopedTokens": {{ STALWART_OIDC_TOKEN_VALIDATION.unscopedTokens | 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/token_validation.json.j2 similarity index 61% rename from roles/web-app-stalwart/templates/jmap/directory/clear_audience.json.j2 rename to roles/web-app-stalwart/templates/jmap/directory/token_validation.json.j2 index f7f1eb04a1..ae09aa5f28 100644 --- a/roles/web-app-stalwart/templates/jmap/directory/clear_audience.json.j2 +++ b/roles/web-app-stalwart/templates/jmap/directory/token_validation.json.j2 @@ -1,4 +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"]] + "methodCalls": [["x:Directory/set", {"update": { {{ stalwart_oidc_dir_id | to_json }}: {{ STALWART_OIDC_TOKEN_VALIDATION | to_json }} }}, "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 index 0dfe7281b8..627e7d8d8b 100644 --- a/roles/web-app-stalwart/templates/jmap/milter/create.json.j2 +++ b/roles/web-app-stalwart/templates/jmap/milter/create.json.j2 @@ -1,12 +1,12 @@ { "using": ["urn:ietf:params:jmap:core", "urn:stalwart:jmap"], "methodCalls": [["x:MtaMilter/set", {"create": {"av": { - "hostname": {{ STALWART_CLAMAV_HOST | to_json }}, + "host": {{ 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 }} + "connectTimeout": {{ STALWART_CLAMAV_MILTER_TIMEOUT_CONNECT_MS | int }}, + "commandTimeout": {{ STALWART_CLAMAV_MILTER_TIMEOUT_COMMAND_MS | int }}, + "dataTimeout": {{ STALWART_CLAMAV_MILTER_TIMEOUT_DATA_MS | int }} }}}, "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 index 13cc9fea77..19efe3d4ee 100644 --- a/roles/web-app-stalwart/templates/jmap/milter/update.json.j2 +++ b/roles/web-app-stalwart/templates/jmap/milter/update.json.j2 @@ -2,8 +2,8 @@ "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 }} + "connectTimeout": {{ STALWART_CLAMAV_MILTER_TIMEOUT_CONNECT_MS | int }}, + "commandTimeout": {{ STALWART_CLAMAV_MILTER_TIMEOUT_COMMAND_MS | int }}, + "dataTimeout": {{ STALWART_CLAMAV_MILTER_TIMEOUT_DATA_MS | int }} }}}, "c0"]] } diff --git a/roles/web-app-stalwart/templates/jmap/route/create.json.j2 b/roles/web-app-stalwart/templates/jmap/route/create.json.j2 index 5d3ed5029e..2658fb7e7f 100644 --- a/roles/web-app-stalwart/templates/jmap/route/create.json.j2 +++ b/roles/web-app-stalwart/templates/jmap/route/create.json.j2 @@ -3,7 +3,7 @@ "methodCalls": [["x:MtaRoute/set", {"create": { {{ STALWART_ONION_ROUTE_NAME | to_json }}: { "@type": "Relay", "name": {{ STALWART_ONION_ROUTE_NAME | to_json }}, - "address": {{ STALWART_ONION_RELAY_HOST | to_json }}, + "host": {{ STALWART_ONION_RELAY_HOST | to_json }}, "port": {{ STALWART_ONION_RELAY_PORT | int }}, "protocol": "smtp", "implicitTls": false, diff --git a/roles/web-app-stalwart/vars/main.yml b/roles/web-app-stalwart/vars/main.yml index 4ee5fb87fd..7176392fcb 100644 --- a/roles/web-app-stalwart/vars/main.yml +++ b/roles/web-app-stalwart/vars/main.yml @@ -41,6 +41,10 @@ container_hostname: "{{ lookup('container_hostname', application_id) }}" STALWART_OIDC_ONION_ISSUER: "{{ lookup('tls', 'web-app-keycloak', 'domain').endswith('.onion') }}" STALWART_OIDC_SOCKS_PROXY: "{{ lookup('tor_socks_proxy') if STALWART_OIDC_ONION_ISSUER | bool else '' }}" +# Keycloak access tokens carry neither a Stalwart audience nor a urn:ietf:params:oauth:scope:mail scope, so the v1 defaults reject every one of them. +STALWART_OIDC_TOKEN_VALIDATION: + skipAudienceValidation: true + unscopedTokens: "interoperable" STALWART_CONTAINER: "{{ lookup('config', application_id, 'services.stalwart.name') }}" diff --git a/tests/unit/python/roles/web-app-stalwart/test_onion_route.py b/tests/unit/python/roles/web-app-stalwart/test_onion_route.py index 296133e61b..5ed52da1f0 100644 --- a/tests/unit/python/roles/web-app-stalwart/test_onion_route.py +++ b/tests/unit/python/roles/web-app-stalwart/test_onion_route.py @@ -121,7 +121,7 @@ class TestRelayRouteRendersValidJson(unittest.TestCase): route = args["create"][ROUTE_NAME] self.assertEqual(route["@type"], "Relay") self.assertEqual(route["name"], ROUTE_NAME) - self.assertEqual(route["address"], "tor-smtp") + self.assertEqual(route["host"], "tor-smtp") self.assertEqual(route["port"], 1525) def test_the_relay_hop_is_plaintext_smtp(self):