diff --git a/README.md b/README.md index a112f2aa47..627c7fb2fe 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,6 @@ Every invokable role in the tested lifecycle envelope, with its upstream homepag | Name | Status | Description | More | Integrated with | |---|---|---|---|---| -| [Akaunting](roles/web-app-akaunting/) | beta | Self-hosted platform for online accounting, bookkeeping, and business finance management | [๐ŸŒ](https://akaunting.com/) [๐ŸŽฌ](https://www.youtube.com/watch?v=UTVe_Zob_k0) [๐Ÿ› ๏ธ](roles/web-app-akaunting/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Stalwart](roles/web-app-stalwart/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Asset Mirror (Privacy Proxy)](roles/web-svc-mirror/) | alpha | Nginx-based privacy proxy that mirrors whitelisted third-party assets under a first-party domain | [๐Ÿ› ๏ธ](roles/web-svc-mirror/README.md#quick-setup) | [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | | [Assets Server](roles/web-svc-asset/) | beta | Nginx-based server for hosting static assets copied from a source directory to the web data path | [๐Ÿ› ๏ธ](roles/web-svc-asset/README.md#quick-setup) | [File Server](roles/web-svc-file/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/) | beta | Scheduled deduplicating backup system for Docker container volumes to a local directory, with consistent SQL dumps | [๐Ÿ› ๏ธ](roles/svc-bkp-volume-2-local/README.md#quick-setup) | [Backup Host Secrets](roles/svc-bkp-secrets-2-local/) | diff --git a/plugins/filter/seaweedfs.py b/plugins/filter/seaweedfs.py index f1029c6ece..bd5440616a 100644 --- a/plugins/filter/seaweedfs.py +++ b/plugins/filter/seaweedfs.py @@ -1,8 +1,17 @@ from __future__ import annotations +import json +import re + +from ansible.errors import AnsibleFilterError + VOLUME_GROW_BATCH = 7 VOLUME_SIZE_LIMIT_MB = 1024 MIN_FREE_SPACE_VOLUMES = 2 +POLICY_VERSION = "2012-10-17" +ANONYMOUS_DENY_SID = "DenyAnonymousRead" +NO_SUCH_BUCKET_POLICY = "NoSuchBucketPolicy" +_BUCKET_LIST_ENTRY = re.compile(r"(\S+)\tsize:") def min_free_space(): @@ -107,9 +116,106 @@ def seaweedfs_sidecar_script(bucket, s3_port, access_key, secret_key): ) +def seaweedfs_anonymous_deny_policy(bucket): + """Build the bucket policy that denies every unsigned read of *bucket*. + + SeaweedFS honours a public-read object or bucket ACL on an unsigned read + unless a bucket policy explicitly denies it first. A bare + ``Principal: "*"`` deny would also hit the consumer's own signed and + presigned requests; the ``Null`` condition on ``aws:username`` limits it to + unsigned ones, because SeaweedFS derives that key from a signed caller's + IAM user ARN and evaluates an unsigned request as principal ``*`` without + it. + + Args: + bucket: bucket the policy is attached to; scopes both the bucket ARN + (listings) and its object ARNs (GET/HEAD). + """ + return { + "Version": POLICY_VERSION, + "Statement": [ + { + "Sid": ANONYMOUS_DENY_SID, + "Effect": "Deny", + "Principal": "*", + "Action": ["s3:Get*", "s3:List*"], + "Resource": [f"arn:aws:s3:::{bucket}", f"arn:aws:s3:::{bucket}/*"], + "Condition": {"Null": {"aws:username": "true"}}, + } + ], + } + + +def seaweedfs_bucket_names(output): + """Return the bucket names a ``weed shell`` ``s3.bucket.list`` printed. + + Args: + output: stdout of the shell; every bucket line carries the name + followed by a tab and its ``size:`` column, and the first one may + follow the shell prompt on the same line. + """ + return _BUCKET_LIST_ENTRY.findall(str(output)) + + +def seaweedfs_stored_bucket_policy(output): + """Return the policy SeaweedFS reports for a bucket. + + Args: + output: stdout of the admin curl ``GET /?policy`` run with + ``-w '\\n%{http_code}'``: the response body, a newline, and the + HTTP status. + + Returns: + The stored policy document on HTTP 200, an empty dict on HTTP 404 + ``NoSuchBucketPolicy``, and ``None`` on every other answer, a missing + bucket (``NoSuchBucket``) included. + """ + body, _, status = str(output).rpartition("\n") + if status == "200": + return json.loads(body) + if status == "404" and NO_SUCH_BUCKET_POLICY in body: + return {} + return None + + +def seaweedfs_bucket_policy_target(stored, bucket, public): + """Return the policy *bucket* converges to. + + Every statement except ``DenyAnonymousRead`` is kept as stored; that one + is replaced by the current :func:`seaweedfs_anonymous_deny_policy` + statement on a private bucket and dropped on a public one. + + Args: + stored: policy document the bucket carries, an empty dict for none. + bucket: bucket the deny statement scopes. + public: whether the consumer is marked public; must be a bool. + + Returns: + The target policy document, or an empty dict when no statement + remains and the bucket must carry no policy. + """ + if not isinstance(public, bool): + raise AnsibleFilterError( + f"seaweedfs_bucket_policy_target: public must be a bool, got {public!r}" + ) + statements = [ + statement + for statement in stored.get("Statement", []) + if statement.get("Sid") != ANONYMOUS_DENY_SID + ] + if not public: + statements.extend(seaweedfs_anonymous_deny_policy(bucket)["Statement"]) + if not statements: + return {} + return {"Version": POLICY_VERSION, "Statement": statements} + + class FilterModule: def filters(self): return { + "seaweedfs_bucket_names": seaweedfs_bucket_names, + "seaweedfs_bucket_policy_target": seaweedfs_bucket_policy_target, "seaweedfs_command": seaweedfs_command, "seaweedfs_sidecar_script": seaweedfs_sidecar_script, + "seaweedfs_stored_bucket_policy": seaweedfs_stored_bucket_policy, } diff --git a/roles/svc-ai-ollama/meta/services.yml b/roles/svc-ai-ollama/meta/services.yml index c9672eb6d7..1c39365e90 100644 --- a/roles/svc-ai-ollama/meta/services.yml +++ b/roles/svc-ai-ollama/meta/services.yml @@ -13,7 +13,7 @@ ollama: backup: no_stop_required: true image: ollama/ollama - version: 0.40.11 + version: 0.40.12 name: ollama min_storage: 3473MB cpus: "4.0" diff --git a/roles/svc-prx-openresty/meta/services.yml b/roles/svc-prx-openresty/meta/services.yml index 70f57222ff..a679a4ce2c 100644 --- a/roles/svc-prx-openresty/meta/services.yml +++ b/roles/svc-prx-openresty/meta/services.yml @@ -31,7 +31,7 @@ openresty: mem_reservation: 1g mem_limit: 2g image: openresty/openresty - version: 1.31.1.1-alpine + version: 1.31.8.1-alpine custom: true lifecycle: beta pids_limit: 256 diff --git a/roles/web-app-akaunting/meta/services.yml b/roles/web-app-akaunting/meta/services.yml index caa489020f..a4af2de253 100644 --- a/roles/web-app-akaunting/meta/services.yml +++ b/roles/web-app-akaunting/meta/services.yml @@ -66,7 +66,7 @@ akaunting: - web-app-keycloak - web-app-stalwart - web-app-mailu - lifecycle: beta + lifecycle: eol cpus: "0.5" mem_reservation: 256m mem_limit: 1g diff --git a/roles/web-app-akaunting/tasks/setup/swarm.yml b/roles/web-app-akaunting/tasks/setup/swarm.yml index 01a8c17cc0..77073a0689 100644 --- a/roles/web-app-akaunting/tasks/setup/swarm.yml +++ b/roles/web-app-akaunting/tasks/setup/swarm.yml @@ -16,6 +16,15 @@ delay: 5 until: akaunting_swarm_drained.rc == 0 +# Exception: the service runs the image built from the akaunting/docker repository, whose code lands in the shared volume; the upstream tag carries an older PHP that cannot run that code. +- name: "๐Ÿ” Akaunting setup | Read the image the akaunting service runs" + ansible.builtin.command: >- + container service inspect {{ AKAUNTING_SERVICE }} + --format {{ '{{.Spec.TaskTemplate.ContainerSpec.Image}}' }} + register: akaunting_service_image + changed_when: false + failed_when: akaunting_service_image.rc != 0 or (akaunting_service_image.stdout | trim | length == 0) + - name: "โ–ถ๏ธ Akaunting setup | Run one-shot install" ansible.builtin.shell: | set -euo pipefail @@ -28,7 +37,7 @@ --mount type=volume,source={{ AKAUNTING_VOLUME | quote }},target={{ lookup('volume', 'web-app-akaunting', 'data').target }} \ --network {{ application_id | get_entity_name | quote }} \ {% if lookup('database', application_id, 'shared') | bool %}--network {{ lookup('database', application_id, 'network') | quote }} {% endif %}\ - {{ AKAUNTING_IMAGE }}:{{ AKAUNTING_VERSION }} \ + {{ akaunting_service_image.stdout | trim | quote }} \ {{ AKAUNTING_ENTRYPOINT }} changed_when: true diff --git a/roles/web-app-akaunting/vars/main.yml b/roles/web-app-akaunting/vars/main.yml index b08964bc27..f4af43a0a2 100644 --- a/roles/web-app-akaunting/vars/main.yml +++ b/roles/web-app-akaunting/vars/main.yml @@ -4,8 +4,6 @@ application_id: "web-app-akaunting" database_password: "{{ lookup('config', application_id, 'secrets.credentials.database_password') }}" # nocheck: lookup-config-path AKAUNTING_URL: "{{ lookup('tls', application_id, 'url.base') }}" -AKAUNTING_IMAGE: "{{ lookup('config', application_id, 'services.akaunting.image') }}" -AKAUNTING_VERSION: "{{ lookup('config', application_id, 'services.akaunting.version') }}" AKAUNTING_REPOSITORY: "{{ lookup('config', 'web-app-akaunting', 'services.akaunting.repository') }}" AKAUNTING_REF: "{{ lookup('config', 'web-app-akaunting', 'services.akaunting.ref') }}" AKAUNTING_CONTAINER: "{{ lookup('config', application_id, 'services.akaunting.name') }}" diff --git a/roles/web-app-discourse/meta/services.yml b/roles/web-app-discourse/meta/services.yml index c0692ec686..a7a8c4551b 100644 --- a/roles/web-app-discourse/meta/services.yml +++ b/roles/web-app-discourse/meta/services.yml @@ -71,7 +71,7 @@ discourse: repository: https://github.com/discourse/discourse_docker.git application: repository: https://github.com/discourse/discourse.git - ref: v2026.9.1 + ref: v2026.10.0 ports: local: http: 8020 diff --git a/roles/web-app-discourse/templates/ai_gateway/register.rb.j2 b/roles/web-app-discourse/templates/ai_gateway/register.rb.j2 index b059ab8437..e815ee0141 100644 --- a/roles/web-app-discourse/templates/ai_gateway/register.rb.j2 +++ b/roles/web-app-discourse/templates/ai_gateway/register.rb.j2 @@ -15,4 +15,3 @@ SiteSetting.ai_helper_enabled = true SiteSetting.ai_summarization_enabled = true SiteSetting.ai_bot_enabled = true SiteSetting.ai_bot_enabled_llms = llm.id.to_s -llm.reload.toggle_companion_user diff --git a/roles/web-app-hugo/meta/services.yml b/roles/web-app-hugo/meta/services.yml index 98f3b15f8d..7b999515d9 100644 --- a/roles/web-app-hugo/meta/services.yml +++ b/roles/web-app-hugo/meta/services.yml @@ -35,7 +35,7 @@ hugo: version: 1.31-alpine custom: true builder_image: ghcr.io/gohugoio/hugo - builder_version: v0.168.0 + builder_version: v0.169.0 source_repository: https://github.com/gohugoio/hugoDocs.git source_version: v0.165.0 update: diff --git a/roles/web-app-jenkins/meta/services.yml b/roles/web-app-jenkins/meta/services.yml index 82d24d976b..ad0a93c220 100644 --- a/roles/web-app-jenkins/meta/services.yml +++ b/roles/web-app-jenkins/meta/services.yml @@ -46,7 +46,7 @@ jenkins: # nocheck: single-replica replicas: 1 image: jenkins/jenkins - version: 2.580.1-lts + version: 2.580.2-lts custom: true name: jenkins ports: diff --git a/roles/web-app-n8n/meta/services.yml b/roles/web-app-n8n/meta/services.yml index cb068ec35d..0481636024 100644 --- a/roles/web-app-n8n/meta/services.yml +++ b/roles/web-app-n8n/meta/services.yml @@ -67,7 +67,7 @@ n8n: backup: no_stop_required: false image: docker.n8n.io/n8nio/n8n - version: "3.0.0" + version: "3.0.1" update: type: registry_tags image: docker.n8n.io/n8nio/n8n diff --git a/roles/web-app-pretix/meta/services.yml b/roles/web-app-pretix/meta/services.yml index 70bcdb073e..db3aa46d73 100644 --- a/roles/web-app-pretix/meta/services.yml +++ b/roles/web-app-pretix/meta/services.yml @@ -53,7 +53,7 @@ pretix: swarm: enabled: true image: pretix/standalone - version: 2026.8.0 + version: 2026.8.1 custom: true name: pretix min_storage: 1003MB diff --git a/roles/web-app-seaweedfs/README.md b/roles/web-app-seaweedfs/README.md index a29a6b3bf0..1c94a2eb09 100644 --- a/roles/web-app-seaweedfs/README.md +++ b/roles/web-app-seaweedfs/README.md @@ -18,9 +18,13 @@ The role serves three canonical domains: Per-consumer S3 identities are rendered into `s3.json`: each consuming role receives an access key and bucket-scoped `Read`, `Write`, `WriteAcp`, `List`, and `Tagging` actions, and consumers marked `public` additionally receive anonymous read on their bucket. Consumer buckets are created through `weed shell` when a consumer role requests provisioning. +The bucket of every consumer not marked `public` carries a bucket policy statement `DenyAnonymousRead` that denies all unsigned reads, so a `public-read` ACL set by an app never exposes an object; signed and presigned requests are unaffected. +Every deploy of this role converges that statement on all existing consumer buckets, adding it to private buckets and removing it from public ones, and a consumer's provisioning applies it right after creating the bucket. +Other statements an operator adds to a consumer's bucket policy are kept. In embedded mode (`shared: false`) a consumer's compose stack receives a storage-only SeaweedFS container without UI or published ports. -The embedded S3 listener performs no authentication, so it MUST stay confined to the consumer's isolated compose network. +The embedded S3 listener starts without identities and accepts unauthenticated requests until the background `s3.configure` grant at startup registers the consumer identity; from then on it authenticates against that identity. +Embedded buckets carry no `DenyAnonymousRead` statement because the listener publishes no port, so the container MUST stay confined to the consumer's isolated compose network. ## Cosmos diff --git a/roles/web-app-seaweedfs/tasks/00_core.yml b/roles/web-app-seaweedfs/tasks/00_core.yml index d873d9161a..502166c241 100644 --- a/roles/web-app-seaweedfs/tasks/00_core.yml +++ b/roles/web-app-seaweedfs/tasks/00_core.yml @@ -69,3 +69,16 @@ until: _seaweedfs_ready.rc == 0 changed_when: false when: IS_STACK_HOST | bool + +- name: "๐Ÿ” Converge the bucket policy of every existing consumer bucket" + when: IS_STACK_HOST | bool + block: + - name: "๐Ÿ“‹ List SeaweedFS buckets" + include_tasks: utils/bucket/list.yml + + - name: "๐Ÿ” Converge the bucket policy of each consumer whose bucket exists" + include_tasks: utils/bucket/policy.yml + loop: "{{ lookup('objstore_consumers', 'seaweedfs') }}" + loop_control: + loop_var: seaweedfs_bucket_policy_consumer + when: lookup('objstore', seaweedfs_bucket_policy_consumer, 'bucket') in (_seaweedfs_buckets.stdout | seaweedfs_bucket_names) diff --git a/roles/web-app-seaweedfs/tasks/01_init_consumer.yml b/roles/web-app-seaweedfs/tasks/01_init_consumer.yml index f89623a3b6..41030c26d0 100644 --- a/roles/web-app-seaweedfs/tasks/01_init_consumer.yml +++ b/roles/web-app-seaweedfs/tasks/01_init_consumer.yml @@ -7,19 +7,11 @@ - name: "๐Ÿ”ง Provision the SeaweedFS bucket on the stack host" when: IS_STACK_HOST | bool + vars: + _seaweedfs_bucket_listed: "{{ lookup('objstore', objstore_consumer_id, 'bucket') in (_seaweedfs_buckets.stdout | seaweedfs_bucket_names) }}" block: - name: "๐Ÿ“‹ List SeaweedFS buckets" - ansible.builtin.shell: | - set -euo pipefail - echo 's3.bucket.list' | container exec -i {{ SEAWEEDFS_CONTAINER_ADDRESS }} weed shell -master=localhost:{{ SEAWEEDFS_MASTER_PORT_INTERNAL }} - args: - executable: /bin/bash - register: _seaweedfs_buckets - changed_when: false - timeout: "{{ lookup('timeout', 60) | int }}" - retries: 3 - delay: 10 - until: _seaweedfs_buckets is succeeded + include_tasks: utils/bucket/list.yml - name: "๐Ÿ“ Create the SeaweedFS bucket for '{{ objstore_consumer_id }}'" ansible.builtin.shell: | @@ -33,4 +25,10 @@ retries: 3 delay: 10 until: _seaweedfs_create is succeeded - when: lookup('objstore', objstore_consumer_id, 'bucket') not in _seaweedfs_buckets.stdout + when: not _seaweedfs_bucket_listed + + - name: "๐Ÿ” Converge the bucket policy of '{{ objstore_consumer_id }}'" + include_tasks: utils/bucket/policy.yml + vars: + seaweedfs_bucket_policy_consumer: "{{ objstore_consumer_id }}" + when: _seaweedfs_bucket_listed or _seaweedfs_create is changed diff --git a/roles/web-app-seaweedfs/tasks/utils/bucket/list.yml b/roles/web-app-seaweedfs/tasks/utils/bucket/list.yml new file mode 100644 index 0000000000..39897a0bf8 --- /dev/null +++ b/roles/web-app-seaweedfs/tasks/utils/bucket/list.yml @@ -0,0 +1,14 @@ +--- +- name: "๐Ÿ“‹ List SeaweedFS buckets" + ansible.builtin.shell: | + set -euo pipefail + echo 's3.bucket.list' | container exec -i {{ SEAWEEDFS_CONTAINER_ADDRESS }} weed shell -master=localhost:{{ SEAWEEDFS_MASTER_PORT_INTERNAL }} + args: + executable: /bin/bash + register: _seaweedfs_buckets + changed_when: false + check_mode: false + timeout: "{{ lookup('timeout', 60) | int }}" + retries: 3 + delay: 10 + until: _seaweedfs_buckets is succeeded diff --git a/roles/web-app-seaweedfs/tasks/utils/bucket/policy.yml b/roles/web-app-seaweedfs/tasks/utils/bucket/policy.yml new file mode 100644 index 0000000000..38206bdf20 --- /dev/null +++ b/roles/web-app-seaweedfs/tasks/utils/bucket/policy.yml @@ -0,0 +1,65 @@ +--- +# Param: seaweedfs_bucket_policy_consumer - consumer role id; its bucket MUST already exist +- name: "๐Ÿ” Converge the bucket policy of '{{ seaweedfs_bucket_policy_consumer }}'" + vars: + _seaweedfs_bucket: "{{ lookup('objstore', seaweedfs_bucket_policy_consumer, 'bucket') }}" + _seaweedfs_bucket_policy_url: "http://127.0.0.1:{{ SEAWEEDFS_S3_PORT_INTERNAL }}/{{ _seaweedfs_bucket }}?policy" + _seaweedfs_bucket_policy_stored: "{{ _seaweedfs_bucket_policy_read.stdout | seaweedfs_stored_bucket_policy }}" + _seaweedfs_bucket_policy_target: >- + {{ _seaweedfs_bucket_policy_stored | seaweedfs_bucket_policy_target( + _seaweedfs_bucket, + lookup('objstore', seaweedfs_bucket_policy_consumer, 'public') | bool) }} + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + block: + - name: "๐Ÿ” Read the bucket policy of '{{ seaweedfs_bucket_policy_consumer }}'" + ansible.builtin.shell: >- + {{ SEAWEEDFS_S3_ADMIN_CURL }} -w '\n%{http_code}' {{ _seaweedfs_bucket_policy_url | quote }} + args: + executable: /bin/bash + environment: + SEAWEEDFS_ADMIN_CREDENTIALS: "{{ SEAWEEDFS_ADMIN_CREDENTIALS }}" + register: _seaweedfs_bucket_policy_read + changed_when: false + check_mode: false + failed_when: >- + _seaweedfs_bucket_policy_read.rc != 0 + or (_seaweedfs_bucket_policy_read.stdout | seaweedfs_stored_bucket_policy) is none + timeout: "{{ lookup('timeout', 60) | int }}" + retries: 3 + delay: 10 + until: _seaweedfs_bucket_policy_read is succeeded + + - name: "๐Ÿ”’ Put the target bucket policy on '{{ seaweedfs_bucket_policy_consumer }}'" + ansible.builtin.shell: >- + {{ SEAWEEDFS_S3_ADMIN_CURL }} -f -X PUT --data-binary @- {{ _seaweedfs_bucket_policy_url | quote }} + args: + executable: /bin/bash + stdin: "{{ _seaweedfs_bucket_policy_target | to_json }}" + environment: + SEAWEEDFS_ADMIN_CREDENTIALS: "{{ SEAWEEDFS_ADMIN_CREDENTIALS }}" + register: _seaweedfs_bucket_policy_put + changed_when: true + timeout: "{{ lookup('timeout', 60) | int }}" + retries: 3 + delay: 10 + until: _seaweedfs_bucket_policy_put is succeeded + when: >- + _seaweedfs_bucket_policy_target | length > 0 + and _seaweedfs_bucket_policy_target != _seaweedfs_bucket_policy_stored + + - name: "๐Ÿ”“ Delete the bucket policy of '{{ seaweedfs_bucket_policy_consumer }}'" + ansible.builtin.shell: >- + {{ SEAWEEDFS_S3_ADMIN_CURL }} -f -X DELETE {{ _seaweedfs_bucket_policy_url | quote }} + args: + executable: /bin/bash + environment: + SEAWEEDFS_ADMIN_CREDENTIALS: "{{ SEAWEEDFS_ADMIN_CREDENTIALS }}" + register: _seaweedfs_bucket_policy_delete + changed_when: true + timeout: "{{ lookup('timeout', 60) | int }}" + retries: 3 + delay: 10 + until: _seaweedfs_bucket_policy_delete is succeeded + when: >- + _seaweedfs_bucket_policy_target | length == 0 + and _seaweedfs_bucket_policy_stored | length > 0 diff --git a/roles/web-app-seaweedfs/vars/main.yml b/roles/web-app-seaweedfs/vars/main.yml index 9e4e1f4d15..23a1089944 100644 --- a/roles/web-app-seaweedfs/vars/main.yml +++ b/roles/web-app-seaweedfs/vars/main.yml @@ -20,6 +20,13 @@ SEAWEEDFS_MASTER_DOMAIN: "{{ lookup('config', application_id, 'domains.canonical SEAWEEDFS_ADMIN_ACCESS_KEY: "{{ lookup('users', 'administrator').username }}" SEAWEEDFS_ADMIN_SECRET_KEY: "{{ lookup('users', 'administrator').password }}" +SEAWEEDFS_ADMIN_CREDENTIALS: "{{ SEAWEEDFS_ADMIN_ACCESS_KEY }}:{{ SEAWEEDFS_ADMIN_SECRET_KEY }}" + +SEAWEEDFS_S3_REGION: "{{ lookup('config', application_id, 'services.seaweedfs.region') }}" +# Exception: curl expands the credential itself via --variable, because --user "$VAR" puts it on curl's argv, visible in the host's ps. +SEAWEEDFS_S3_ADMIN_CURL: >- + container exec -i -e SEAWEEDFS_ADMIN_CREDENTIALS {{ SEAWEEDFS_CONTAINER_ADDRESS }} + sh -c 'exec {{ lookup('timeout', 30) | curl(retries=0) }} -S --aws-sigv4 "aws:amz:{{ SEAWEEDFS_S3_REGION }}:s3" --variable %SEAWEEDFS_ADMIN_CREDENTIALS --expand-user "{{ '{{' }}SEAWEEDFS_ADMIN_CREDENTIALS{{ '}}' }}" "$@"' curl SEAWEEDFS_S3_CONFIG_PATH: "{{ [ lookup('container', application_id, 'directories.volumes'), 's3.json' ] | path_join }}" diff --git a/roles/web-app-socialhome/meta/services.yml b/roles/web-app-socialhome/meta/services.yml index bf86e05e13..2d1238bd0b 100644 --- a/roles/web-app-socialhome/meta/services.yml +++ b/roles/web-app-socialhome/meta/services.yml @@ -13,7 +13,7 @@ socialhome: # nocheck: default-placement-manager embedded sqlite in a node-local volume; no clustered storage placement: manager image: ghcr.io/social-home-io/socialhome - version: "2026.10.24" + version: "2026.10.27" ports: local: http: 8089 diff --git a/roles/web-app-stalwart/README.md b/roles/web-app-stalwart/README.md index ffc3c1a529..bb3963bc49 100644 --- a/roles/web-app-stalwart/README.md +++ b/roles/web-app-stalwart/README.md @@ -149,6 +149,10 @@ delegates **interactive** authentication to Keycloak: (a claim that already holds an `@` is taken as is), creating it on first login. - **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`. **Design constraint (validated against the live JMAP schema):** Stalwart's authentication directory is *Internal XOR one external directory* โ€” there is no @@ -176,6 +180,22 @@ authenticated sessions in both modes (`STALWART_RELAY_RULE`). With SSO disabled the role uses the Internal directory and the bot's derived account password. +## WebUI sign-in + +The WebUI Application always names `stalwart-webui` (`STALWART_WEBUI_OAUTH_CLIENT_ID`) as its `oauthClientId`, with and without SSO. +Where the WebUI sends a login depends on the account: + +| Account | Authorization server | Client `stalwart-webui` | +|---|---|---| +| Account in a domain bound to the Keycloak OIDC directory | Keycloak | Keycloak client from `templates/keycloak/clients.json.j2` | +| Recovery admin (`STALWART_ADMIN_USER`), and every account while SSO is off | Stalwart | OAuth client the role registers in Stalwart (`tasks/02_webadmin.yml`) | + +The role registers that Stalwart client over JMAP (`templates/jmap/oauth_client/`) as a public first-party client, with one redirect URI `//oauth/callback` and one post-logout URI `//login` per URL prefix of the WebUI Application. +`` is the role's canonical WebUI URL (`STALWART_WEBUI_BASE_URL`), so a Tor deployment registers its `http://` onion origin. +Every deploy compares the registered client with that target and updates it when they differ. +A deployment that serves the WebUI on a further origin MUST add that origin's URIs to [`templates/jmap/oauth_client/webui.json.j2`](templates/jmap/oauth_client/webui.json.j2), because a URI added in Stalwart alone is removed by the next deploy. +Stalwart's login page asks for consent before the password form for every registered client, so a native WebUI login shows an **Allow** step. + ## Calendar & Contacts (CalDAV / CardDAV / WebDAV) Stalwart serves DAV natively on the mail HTTP listener โ€” no extra container @@ -195,7 +215,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` @@ -365,6 +385,62 @@ applications: - The source is not served by Stalwart and gets no DKIM key; it receives mail but sends none. - Removing every alias domain leaves the last rewrite in Stalwart; set the RCPT stage's rewrite back to `false` in WebAdmin. +## Upgrading from 0.16 + +Stalwart 1.x refuses to open a 0.16 store and has no in-place upgrade. Every deploy checks the store in the role's database before it starts Stalwart, whatever state the running server is in, 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, and a database without that column holds no store yet. + +A deploy that has brought Stalwart 1.x up on the store and finished its provisioning writes the marker `store.layout`, holding the store layout version `1`, into the role's instance directory on the stack host (`STALWART_STORE_MARKER_FILE`, written last in [`tasks/manager_ops.yml`](tasks/manager_ops.yml)). +A failed deploy writes no marker. +A deploy that finds the marker passes without reading the store. +A deploy without the marker reads the store: + +| Database | No store yet | Store to read | +|---|---|---| +| Shared PostgreSQL | the `postgres` superuser finds no database `stalwart` in the catalog | read as the role's database user | +| Dedicated PostgreSQL | the volume `stalwart_database` does not exist | read inside the dedicated database container; when that container is not running, the deploy stops and names the database service to start | + +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 finds the migrated 1.x store under the role's database name and lets Stalwart 1.x start on it. +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. + +### Restore and redeploy + +The marker lives outside the stack and its volumes, so it survives `docker stack rm`, `docker compose down`, a crashed database and the stop and start cycle of `backup.project_hard_restart`. +A host that carries the marker therefore redeploys while its dedicated database is down, as in the restore of [`svc-bkp-nfs-2-local`](../svc-bkp-nfs-2-local/README.md) (`docker stack rm`, restore, redeploy). +A dedicated store on a host without the marker, such as a 0.16 host or a host whose instance directory was lost, needs its database running before the deploy: start the database service of the stack the host last deployed, then deploy. +Before a host that carries the marker goes back to a 0.16 store, through `stalwart-migrate rollback` or a backup taken under 0.16, delete the marker, so the next deploy reads the 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/playwright/test-login-native.js b/roles/web-app-stalwart/files/playwright/test-login-native.js index 8ecf9da8d0..3f616fc5f9 100644 --- a/roles/web-app-stalwart/files/playwright/test-login-native.js +++ b/roles/web-app-stalwart/files/playwright/test-login-native.js @@ -1,6 +1,6 @@ const { test, expect } = require("@playwright/test"); -const { safeIsEnabled, gotoOnion } = require("./personas"); +const { gotoOnion } = require("./personas"); const { appBaseUrl, canonicalDomain, @@ -10,16 +10,10 @@ const { } = require("./env"); const { resolveTimeout } = require("./timeouts"); -// WebAdmin native login: the variant where Keycloak is absent and Stalwart's own -// directory owns the credentials. Without this the sso=false variant deploys a -// login surface no spec ever exercises, because every other spec self-skips on sso. -// The account is Stalwart's own WebAdmin administrator (STALWART_ADMIN_USER), not the -// platform's administrator โ€” the latter lives in the OIDC directory and is rejected here. -test("administrator: stalwart native login and logout (no sso)", async ({ page }) => { - test.skip( - safeIsEnabled("sso"), - "Native login is only exercised in the variant without Keycloak โ€” when SSO is on the OIDC path owns the journey.", - ); +// The account is Stalwart's recovery admin (STALWART_ADMIN_USER), not the platform's administrator: +// discovery sends it to Stalwart's own OAuth server even when Keycloak serves the mail domain, so this +// journey runs with and without SSO. +test("administrator: stalwart recovery admin native login and logout", async ({ page }) => { expect(stalwartAdminUsername, "STALWART_ADMIN_USERNAME must be set").toBeTruthy(); expect(stalwartAdminPassword, "STALWART_ADMIN_PASSWORD must be set").toBeTruthy(); @@ -39,6 +33,11 @@ test("administrator: stalwart native login and logout (no sso)", async ({ page } .first() .click(); + // Stalwart asks consent for every registered OAuth client before it shows the password form. + const allow = page.getByRole("button", { name: /^allow$/i }); + await allow.waitFor({ state: "visible", timeout: resolveTimeout(30_000) }); + await allow.click(); + const passwordField = page.locator("input[type='password'], input[name='password']").first(); await passwordField.waitFor({ state: "visible", timeout: resolveTimeout(30_000) }); await passwordField.fill(stalwartAdminPassword); diff --git a/roles/web-app-stalwart/files/sql/store/database.sql b/roles/web-app-stalwart/files/sql/store/database.sql new file mode 100644 index 0000000000..053b8dd618 --- /dev/null +++ b/roles/web-app-stalwart/files/sql/store/database.sql @@ -0,0 +1,3 @@ +SELECT count(*) +FROM pg_catalog.pg_database +WHERE datname = %(name)s; 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..97bde8ab74 --- /dev/null +++ b/roles/web-app-stalwart/files/sql/store/layout.sql @@ -0,0 +1,9 @@ +SELECT + coalesce(( + 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 + ), 'absent'); diff --git a/roles/web-app-stalwart/meta/services.yml b/roles/web-app-stalwart/meta/services.yml index 29ecff9f22..4f30bc1679 100644 --- a/roles/web-app-stalwart/meta/services.yml +++ b/roles/web-app-stalwart/meta/services.yml @@ -43,12 +43,13 @@ stalwart: # nocheck: default-placement-manager mail edge at a known IP: MX A-record, PTR and SPF bind to the stack host IP (a floating task's egress IP breaks deliverability); the mail store is NFS-hostile and IS the app โ€” same rationale as web-app-mailu placement: manager image: stalwartlabs/stalwart - version: "v0.16.27" - webui_version: "v1.0.11" + version: "v1.0.0" + webui_version: "v2.0.2" update: 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 26519610f1..0efbedf778 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 8b0790bf92..9d0dadefff 100644 --- a/roles/web-app-stalwart/tasks/02_webadmin.yml +++ b/roles/web-app-stalwart/tasks/02_webadmin.yml @@ -29,13 +29,46 @@ ansible.builtin.set_fact: stalwart_webui_app_id: "{{ stalwart_webui_apps[0].id }}" -- name: "๐Ÿ”— Point the WebUI Application at the locally-staged bundle" +- name: "๐Ÿ“– List Stalwart OAuth clients" + include_tasks: jmap_call.yml + vars: + stalwart_jmap_body: "{{ lookup('template', 'jmap/oauth_client/get.json.j2') }}" + +- name: "๐Ÿ” Resolve the WebUI OAuth client" + ansible.builtin.set_fact: + stalwart_webui_oauth_client: "{{ lookup('template', 'jmap/oauth_client/webui.json.j2') | from_json }}" + stalwart_webui_oauth_clients: >- + {{ stalwart_jmap.methodResponses[0][1].list + | selectattr('clientId', 'equalto', STALWART_WEBUI_OAUTH_CLIENT_ID) + | list }} + vars: + stalwart_webui_url_prefixes: "{{ stalwart_webui_apps[0].urlPrefix | list }}" + +- name: "๐Ÿ“ Register the WebUI OAuth client" + include_tasks: jmap_call.yml + vars: + stalwart_jmap_body: "{{ lookup('template', 'jmap/oauth_client/create.json.j2') }}" + when: stalwart_webui_oauth_clients | length == 0 + +- name: "๐Ÿ”„ Align the WebUI OAuth client with the origin the WebUI is served from" + include_tasks: jmap_call.yml + vars: + stalwart_jmap_body: "{{ lookup('template', 'jmap/oauth_client/update.json.j2') }}" + when: + - stalwart_webui_oauth_clients | length > 0 + - >- + (stalwart_webui_oauth_clients[0] | dict2items + | selectattr('key', 'in', stalwart_webui_oauth_client) | items2dict) + != stalwart_webui_oauth_client + +- name: "๐Ÿ”— Point the WebUI Application at the locally-staged bundle and its OAuth client" include_tasks: jmap_call.yml vars: stalwart_jmap_body: >- {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], 'methodCalls': [['x:Application/set', - {'update': {stalwart_webui_app_id: {'resourceUrl': STALWART_WEBUI_LOCAL_URL}}}, + {'update': {stalwart_webui_app_id: {'resourceUrl': STALWART_WEBUI_LOCAL_URL, + 'oauthClientId': STALWART_WEBUI_OAUTH_CLIENT_ID}}}, '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/manager_ops.yml b/roles/web-app-stalwart/tasks/manager_ops.yml index 94605703d7..1f43ac1ce7 100644 --- a/roles/web-app-stalwart/tasks/manager_ops.yml +++ b/roles/web-app-stalwart/tasks/manager_ops.yml @@ -51,3 +51,9 @@ - name: "๐Ÿ“จ Provision the declared per-account forwards" include_tasks: 16_forwards.yml when: STALWART_FORWARDS | length > 0 + +- name: "๐Ÿ“ Record that Stalwart 1.x serves the store of this host" + stack_host_copy: + content: "{{ STALWART_STORE_LAYOUT_VERSION }}\n" + dest: "{{ STALWART_STORE_MARKER_FILE }}" + mode: "0644" 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..d8a4a8bc26 --- /dev/null +++ b/roles/web-app-stalwart/tasks/store_guard.yml @@ -0,0 +1,123 @@ +--- +# Stalwart 1.x keeps a bytea column v in table u; every 0.x store keeps its bigint quota counters under the same name. +# mask_values scrubs the role's names out of psql errors, so existence comes from the shared catalog or the dedicated volume, and a stopped dedicated database fails its own assert instead of a masked psql error. +# The host marker outranks the store: a marked host that goes back to a 0.16 store (rollback, old backup) passes unless the marker is removed first. + +- name: "๐Ÿ” Find the 1.x store marker of this host" + ansible.builtin.stat: + path: "{{ STALWART_STORE_MARKER_FILE }}" + register: stalwart_store_marker_file + +- name: "๐Ÿ“– Read the 1.x store marker of this host" + ansible.builtin.slurp: + src: "{{ STALWART_STORE_MARKER_FILE }}" + register: stalwart_store_marker + when: stalwart_store_marker_file.stat.exists + +- name: "๐Ÿ”ง Record whether this host last deployed Stalwart 1.x on its store" + ansible.builtin.set_fact: + stalwart_store_marked: >- + {{ stalwart_store_marker is not skipped + and (stalwart_store_marker.content | b64decode | trim) == (STALWART_STORE_LAYOUT_VERSION | string) }} + +- name: "๐Ÿ” Find the store database on the shared PostgreSQL" + database_query: + config: >- + {{ lookup('database', application_id) | combine({ + 'username': 'postgres', + 'name': 'postgres', + 'password': lookup('config', 'svc-db-postgres', 'secrets.credentials.POSTGRES_PASSWORD'), + }) }} + query_file: "{{ role_path }}/files/sql/store/database.sql" + named_args: + name: "{{ lookup('database', application_id, 'name') }}" + expect_rows: true + mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + register: stalwart_store_database + until: stalwart_store_database is succeeded + retries: 6 + delay: 5 + changed_when: false + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + when: + - not (stalwart_store_marked | bool) + - STALWART_DATABASE_SHARED | bool + +- name: "๐Ÿ” Find the volume of the dedicated store database" + ansible.builtin.command: >- + container volume ls -q --filter name=^{{ lookup('database', application_id, 'volume') }}$ + register: stalwart_store_volume + changed_when: false + when: + - not (stalwart_store_marked | bool) + - not (STALWART_DATABASE_SHARED | bool) + +- name: "๐Ÿ”ง Record whether a store exists that this host never deployed Stalwart 1.x on" + ansible.builtin.set_fact: + stalwart_store_exists: >- + {{ not (stalwart_store_marked | bool) and ( + (stalwart_store_database.rows[0][0] | int > 0) + if STALWART_DATABASE_SHARED | bool + else (stalwart_store_volume.stdout | trim | length > 0)) }} + +- name: "๐Ÿ” Find the running container of the dedicated store database" + ansible.builtin.command: + argv: + - container + - ps + - --quiet + - --filter + - status=running + - --filter + - >- + {{ ('label=com.docker.swarm.service.name=' ~ lookup('database', application_id, 'service_name')) + if DEPLOYMENT_MODE == 'swarm' + else ('name=^' ~ lookup('database', application_id, 'container') ~ '$') }} + register: stalwart_store_engine + changed_when: false + when: + - stalwart_store_exists | bool + - not (STALWART_DATABASE_SHARED | bool) + +- name: "โœ… Ensure the dedicated store database runs, so the deploy can read its layout" + ansible.builtin.assert: + that: + - stalwart_store_engine.stdout | trim | length > 0 + fail_msg: >- + The dedicated store database of Stalwart, service '{{ lookup('database', application_id, 'host') }}' + of stack '{{ application_id | get_entity_name }}', is not running on {{ inventory_hostname }}, + so the deploy cannot read the layout of the store in volume '{{ lookup('database', application_id, 'volume') }}'. + This host has no record of a Stalwart 1.x deploy ({{ STALWART_STORE_MARKER_FILE }}), so that store may predate 1.0, + and the deploy stops before Stalwart {{ lookup('config', application_id, 'services.stalwart.version') }} opens it. + Start that database from the stack this host last deployed, or finish the stalwart-migrate steps of + "Upgrading from 0.16" in roles/web-app-stalwart/README.md, then deploy again. + quiet: true + when: stalwart_store_engine is not skipped + +- name: "๐Ÿ” Read the layout of the store Stalwart opens" + 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 + until: stalwart_store_layout is succeeded + retries: 6 + delay: 5 + changed_when: false + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + when: stalwart_store_exists | bool + +- name: "โœ… Ensure Stalwart opens no store from before 1.0" + ansible.builtin.assert: + that: + - stalwart_store_layout.rows[0][0] in ['bytea', 'absent'] + fail_msg: >- + The store in database '{{ lookup('database', application_id, 'name') }}' predates Stalwart 1.0 + (type of column u.v: {{ stalwart_store_layout.rows[0][0] }}, 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 starts Stalwart. 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_store_layout is not skipped 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/oauth_client/create.json.j2 b/roles/web-app-stalwart/templates/jmap/oauth_client/create.json.j2 new file mode 100644 index 0000000000..21c7a60ae3 --- /dev/null +++ b/roles/web-app-stalwart/templates/jmap/oauth_client/create.json.j2 @@ -0,0 +1,4 @@ +{ + "using": ["urn:ietf:params:jmap:core", "urn:stalwart:jmap"], + "methodCalls": [["x:OAuthClient/set", {"create": {"webui": {{ stalwart_webui_oauth_client | to_json }} }}, "c0"]] +} diff --git a/roles/web-app-stalwart/templates/jmap/oauth_client/get.json.j2 b/roles/web-app-stalwart/templates/jmap/oauth_client/get.json.j2 new file mode 100644 index 0000000000..0fcaac0e8e --- /dev/null +++ b/roles/web-app-stalwart/templates/jmap/oauth_client/get.json.j2 @@ -0,0 +1,4 @@ +{ + "using": ["urn:ietf:params:jmap:core", "urn:stalwart:jmap"], + "methodCalls": [["x:OAuthClient/get", {"ids": null}, "c0"]] +} diff --git a/roles/web-app-stalwart/templates/jmap/oauth_client/update.json.j2 b/roles/web-app-stalwart/templates/jmap/oauth_client/update.json.j2 new file mode 100644 index 0000000000..b6b4cfe671 --- /dev/null +++ b/roles/web-app-stalwart/templates/jmap/oauth_client/update.json.j2 @@ -0,0 +1,4 @@ +{ + "using": ["urn:ietf:params:jmap:core", "urn:stalwart:jmap"], + "methodCalls": [["x:OAuthClient/set", {"update": { {{ stalwart_webui_oauth_clients[0].id | to_json }}: {{ stalwart_webui_oauth_client | to_json }} }}, "c0"]] +} diff --git a/roles/web-app-stalwart/templates/jmap/oauth_client/webui.json.j2 b/roles/web-app-stalwart/templates/jmap/oauth_client/webui.json.j2 new file mode 100644 index 0000000000..a794170c34 --- /dev/null +++ b/roles/web-app-stalwart/templates/jmap/oauth_client/webui.json.j2 @@ -0,0 +1,17 @@ +{# firstParty is load-bearing: a third-party client's tokens are cut down to their granted scopes, which locks the WebUI out of the management API. #} +{ + "clientId": {{ STALWART_WEBUI_OAUTH_CLIENT_ID | to_json }}, + "description": {{ STALWART_WEBUI_APP_DESCRIPTION | to_json }}, + "firstParty": true, + "grantTypes": {"authorizationCode": true, "refreshToken": true}, + "redirectUris": { +{% for prefix in stalwart_webui_url_prefixes %} + {{ (STALWART_WEBUI_BASE_URL ~ '/' ~ (prefix | trim('/')) ~ '/oauth/callback') | to_json }}: true{{ '' if loop.last else ',' }} +{% endfor %} + }, + "postLogoutRedirectUris": { +{% for prefix in stalwart_webui_url_prefixes %} + {{ (STALWART_WEBUI_BASE_URL ~ '/' ~ (prefix | trim('/')) ~ '/login') | to_json }}: true{{ '' if loop.last else ',' }} +{% endfor %} + } +} 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 94b7ce04b0..fa83534360 100644 --- a/roles/web-app-stalwart/vars/main.yml +++ b/roles/web-app-stalwart/vars/main.yml @@ -42,8 +42,15 @@ 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') }}" +STALWART_DATABASE_SHARED: "{{ lookup('database', application_id, 'shared') | bool }}" +STALWART_STORE_LAYOUT_VERSION: "1" +STALWART_STORE_MARKER_FILE: "{{ [ lookup('container', application_id, 'directories.instance'), 'store.layout' ] | path_join }}" STALWART_ANTIVIRUS_ENABLED: "{{ lookup('config', application_id, 'services.clamav.enabled') | bool }}" STALWART_CLAMAV_HOST: "clamav" @@ -66,6 +73,8 @@ STALWART_WEBUI_LOCAL_FILE: "{{ [ STALWART_CONFIG_DIR, 'webui.zip' ] | path_join STALWART_WEBUI_CONTAINER_FILE: "{{ lookup('volume', application_id, 'webui_bundle').target }}" STALWART_WEBUI_LOCAL_URL: "file://{{ STALWART_WEBUI_CONTAINER_FILE }}" STALWART_WEBUI_APP_DESCRIPTION: "Stalwart Web Interface" +STALWART_WEBUI_OAUTH_CLIENT_ID: "{{ lookup('config', application_id, 'services.sso.oidc.clients.webui') }}" +STALWART_WEBUI_BASE_URL: "{{ lookup('canonical_url', application_id) }}" STALWART_IP4_PUBLIC: "{{ DOCKER_PUBLIC_BIND_HOST }}" STALWART_ACTIVE_PROVIDER: "{{ lookup('mail_provider') == application_id }}" diff --git a/roles/web-app-xwiki/meta/services.yml b/roles/web-app-xwiki/meta/services.yml index 464373e48f..49023e8b3f 100644 --- a/roles/web-app-xwiki/meta/services.yml +++ b/roles/web-app-xwiki/meta/services.yml @@ -56,7 +56,7 @@ xwiki: enabled: true # nocheck: dynamic-flag shared: true image: xwiki - version: 18.8.0-postgres-tomcat + version: 18.9.0-postgres-tomcat custom: true name: xwiki min_storage: 965MB diff --git a/tests/unit/python/plugins/filter/test_seaweedfs.py b/tests/unit/python/plugins/filter/test_seaweedfs.py index 0d4511b33a..df539149c3 100644 --- a/tests/unit/python/plugins/filter/test_seaweedfs.py +++ b/tests/unit/python/plugins/filter/test_seaweedfs.py @@ -1,15 +1,73 @@ +import json import unittest +from ansible.errors import AnsibleFilterError + from plugins.filter.seaweedfs import ( + ANONYMOUS_DENY_SID, MIN_FREE_SPACE_VOLUMES, VOLUME_GROW_BATCH, VOLUME_SIZE_LIMIT_MB, min_free_space, + seaweedfs_anonymous_deny_policy, + seaweedfs_bucket_names, + seaweedfs_bucket_policy_target, seaweedfs_command, seaweedfs_sidecar_script, + seaweedfs_stored_bucket_policy, volume_slots, ) +FOREIGN_STATEMENT = { + "Sid": "OperatorReadOnly", + "Effect": "Allow", + "Principal": {"AWS": ["arn:aws:iam::000000000000:user/auditor"]}, + "Action": "s3:GetObject", + "Resource": "arn:aws:s3:::mastodon/*", +} + +NO_SUCH_BUCKET_POLICY_XML = ( + '\n' + "NoSuchBucketPolicy" + "The bucket policy does not exist" + "/mastodon1" + "mastodon" +) + +NO_SUCH_BUCKET_XML = ( + '\n' + "NoSuchBucket" + "The specified bucket does not exist" + "/mastodon1" + "mastodon" +) + + +def _deny(bucket="mastodon"): + (statement,) = seaweedfs_anonymous_deny_policy(bucket)["Statement"] + return statement + + +def _go_marshal(value): + """Mirror how SeaweedFS 4.51 re-serialises a stored policy. + + Args: + value: policy fragment; every one-element string list collapses to + its string, as ``StringOrStringSlice.MarshalJSON`` does. + """ + if isinstance(value, dict): + return {key: _go_marshal(item) for key, item in value.items()} + if isinstance(value, list) and len(value) == 1 and isinstance(value[0], str): + return value[0] + if isinstance(value, list): + return [_go_marshal(item) for item in value] + return value + + +def _curl_output(body, status): + return f"{body}\n{status}" + + BASE = [ "server", "-dir=/data", @@ -92,5 +150,141 @@ class TestSeaweedfsSidecarScriptFilter(unittest.TestCase): self.assertNotIn("$", seaweedfs_sidecar_script("app", 8333, "AK", "SK")) +class TestSeaweedfsAnonymousDenyPolicyFilter(unittest.TestCase): + def test_uses_the_only_policy_version_seaweedfs_accepts(self): + self.assertEqual(seaweedfs_anonymous_deny_policy("b")["Version"], "2012-10-17") + + def test_is_an_explicit_deny_for_every_principal(self): + statement = _deny() + self.assertEqual(statement["Effect"], "Deny") + self.assertEqual(statement["Principal"], "*") + + def test_spares_requests_that_carry_a_signed_username(self): + self.assertEqual(_deny()["Condition"], {"Null": {"aws:username": "true"}}) + + def test_covers_reads_and_listings_but_no_writes(self): + self.assertEqual(_deny()["Action"], ["s3:Get*", "s3:List*"]) + + def test_scopes_the_bucket_and_its_objects(self): + self.assertEqual( + _deny("pixelfed")["Resource"], + ["arn:aws:s3:::pixelfed", "arn:aws:s3:::pixelfed/*"], + ) + + def test_carries_the_sid_the_converge_step_owns(self): + self.assertEqual(_deny()["Sid"], ANONYMOUS_DENY_SID) + + def test_survives_the_seaweedfs_round_trip_unchanged(self): + policy = seaweedfs_anonymous_deny_policy("mastodon") + self.assertEqual(_go_marshal(json.loads(json.dumps(policy))), policy) + + +class TestSeaweedfsBucketNamesFilter(unittest.TestCase): + def test_reads_every_listed_bucket(self): + output = ( + " mastodon\tsize:0\tlogical:0\tchunk:0\n" + ' pixelfed\tsize:42\tlogical:40\tchunk:3\towner:"pixelfed"\n' + ) + self.assertEqual(seaweedfs_bucket_names(output), ["mastodon", "pixelfed"]) + + def test_reads_a_bucket_printed_after_the_shell_prompt(self): + output = "> " + " mastodon\tsize:0\tlogical:0\tchunk:0\n> " + self.assertEqual(seaweedfs_bucket_names(output), ["mastodon"]) + + def test_a_name_inside_a_longer_one_is_not_listed(self): + names = seaweedfs_bucket_names(" mastodon-media\tsize:0\tlogical:0\tchunk:0\n") + self.assertNotIn("mastodon", names) + + def test_an_empty_listing_yields_no_bucket(self): + self.assertEqual(seaweedfs_bucket_names("> "), []) + + +class TestSeaweedfsStoredBucketPolicyFilter(unittest.TestCase): + def test_a_stored_policy_is_returned(self): + policy = seaweedfs_anonymous_deny_policy("mastodon") + output = _curl_output(json.dumps(policy, separators=(",", ":")) + "\n", 200) + self.assertEqual(seaweedfs_stored_bucket_policy(output), policy) + + def test_no_such_bucket_policy_reads_as_no_policy(self): + output = _curl_output(NO_SUCH_BUCKET_POLICY_XML, 404) + self.assertEqual(seaweedfs_stored_bucket_policy(output), {}) + + def test_a_missing_bucket_is_refused(self): + output = _curl_output(NO_SUCH_BUCKET_XML, 404) + self.assertIsNone(seaweedfs_stored_bucket_policy(output)) + + def test_access_denied_is_refused(self): + output = _curl_output("AccessDenied", 403) + self.assertIsNone(seaweedfs_stored_bucket_policy(output)) + + def test_a_server_error_is_refused(self): + output = _curl_output("InternalError", 500) + self.assertIsNone(seaweedfs_stored_bucket_policy(output)) + + def test_a_404_without_the_policy_code_is_refused(self): + self.assertIsNone(seaweedfs_stored_bucket_policy(_curl_output("", 404))) + + +class TestSeaweedfsBucketPolicyTargetFilter(unittest.TestCase): + def _policy(self, *statements): + return {"Version": "2012-10-17", "Statement": list(statements)} + + def test_a_private_bucket_without_policy_gets_the_deny(self): + self.assertEqual( + seaweedfs_bucket_policy_target({}, "mastodon", False), + seaweedfs_anonymous_deny_policy("mastodon"), + ) + + def test_a_private_bucket_with_the_deny_stays_as_stored(self): + stored = _go_marshal(seaweedfs_anonymous_deny_policy("mastodon")) + self.assertEqual( + seaweedfs_bucket_policy_target(stored, "mastodon", False), stored + ) + + def test_a_private_bucket_keeps_a_foreign_statement_next_to_the_deny(self): + stored = self._policy(FOREIGN_STATEMENT, _deny()) + self.assertEqual( + seaweedfs_bucket_policy_target(stored, "mastodon", False), stored + ) + + def test_a_private_bucket_with_only_a_foreign_statement_gains_the_deny(self): + stored = self._policy(FOREIGN_STATEMENT) + self.assertEqual( + seaweedfs_bucket_policy_target(stored, "mastodon", False), + self._policy(FOREIGN_STATEMENT, _deny()), + ) + + def test_a_stale_deny_is_replaced_by_the_current_one(self): + stale = {**_deny(), "Action": "s3:GetObject"} + self.assertEqual( + seaweedfs_bucket_policy_target(self._policy(stale), "mastodon", False), + self._policy(_deny()), + ) + + def test_a_public_bucket_without_policy_stays_without(self): + self.assertEqual(seaweedfs_bucket_policy_target({}, "mastodon", True), {}) + + def test_a_public_bucket_loses_the_deny(self): + stored = seaweedfs_anonymous_deny_policy("mastodon") + self.assertEqual(seaweedfs_bucket_policy_target(stored, "mastodon", True), {}) + + def test_a_public_bucket_loses_a_stale_deny_by_its_sid(self): + stale = {**_deny(), "Action": "s3:GetObject", "Condition": {}} + self.assertEqual( + seaweedfs_bucket_policy_target(self._policy(stale), "mastodon", True), {} + ) + + def test_a_public_bucket_keeps_a_foreign_statement(self): + stored = self._policy(_deny(), FOREIGN_STATEMENT) + self.assertEqual( + seaweedfs_bucket_policy_target(stored, "mastodon", True), + self._policy(FOREIGN_STATEMENT), + ) + + def test_public_must_be_a_bool(self): + with self.assertRaises(AnsibleFilterError): + seaweedfs_bucket_policy_target({}, "mastodon", "False") + + if __name__ == "__main__": unittest.main() 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): diff --git a/tests/unit/python/roles/web-app-stalwart/test_store_guard.py b/tests/unit/python/roles/web-app-stalwart/test_store_guard.py new file mode 100644 index 0000000000..b52a7fe542 --- /dev/null +++ b/tests/unit/python/roles/web-app-stalwart/test_store_guard.py @@ -0,0 +1,182 @@ +"""The guard that stops a deploy before Stalwart 1.x opens a store from before 1.0. + +The marker a finished 1.x deploy leaves on the stack host passes the guard +without touching the store. Without the marker the guard reads every store +that exists, stops when a dedicated database is not running, and lets a fresh +install through. +""" + +from __future__ import annotations + +import base64 +import unittest + +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar + +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_VARS_MAIN +from utils.templating.ansible import _trust_as_template + +from . import PROJECT_ROOT + +ROLE = PROJECT_ROOT / "roles" / "web-app-stalwart" +GUARD = ROLE / "tasks" / "store_guard.yml" +MANAGER_OPS = ROLE / "tasks" / "manager_ops.yml" +VARS = ROLE / ROLE_FILE_VARS_MAIN + +PASS = "pass" +ENGINE_DOWN = "Ensure the dedicated store database runs" +PRE_1_0 = "Ensure Stalwart opens no store from before 1.0" + +SKIPPED = {"skipped": True, "changed": False} +NO_MARKER = {"stalwart_store_marker_file": {"changed": False, "stat": {"exists": False}}} + + +def _render(template: str, **variables): + templar = Templar(loader=DataLoader(), variables=variables) + return templar.template(_trust_as_template(template)) + + +def _holds(condition: str, facts: dict) -> bool: + return _render("{{ (" + condition + ") | bool }}", **facts) + + +def _module(task: dict, name: str) -> dict | None: + return task.get(f"ansible.builtin.{name}") or task.get(name) + + +def _layout_version() -> str: + return load_yaml_any(str(VARS), default_if_missing={})["STALWART_STORE_LAYOUT_VERSION"] + + +def _written_marker() -> str: + tasks = load_yaml_any(str(MANAGER_OPS), default_if_missing=[]) + copy = next( + t["stack_host_copy"] + for t in tasks + if t.get("stack_host_copy", {}).get("dest") == "{{ STALWART_STORE_MARKER_FILE }}" + ) + return _render(copy["content"], STALWART_STORE_LAYOUT_VERSION=_layout_version()) + + +def _guard(results: dict[str, dict], *, shared: bool) -> str: + """Walk store_guard.yml in task order, the way Ansible runs it. + + Args: + results: the result of every task that runs, keyed by its register name; + a task that runs without an entry fails the test with a KeyError. + shared: whether the store lives on the shared PostgreSQL. + + Returns: + the name of the first assert that fails, or PASS. + """ + facts = { + "STALWART_DATABASE_SHARED": shared, + "STALWART_STORE_LAYOUT_VERSION": _layout_version(), + } + for task in load_yaml_any(str(GUARD), default_if_missing=[]): + when = task.get("when", []) + if not all(_holds(c, facts) for c in (when if isinstance(when, list) else [when])): + if "register" in task: + facts[task["register"]] = SKIPPED + continue + set_fact = _module(task, "set_fact") + assertion = _module(task, "assert") + if set_fact is not None: + facts.update({k: _render(v, **facts) for k, v in set_fact.items()}) + elif assertion is not None: + if not all(_holds(c, facts) for c in assertion["that"]): + return task["name"] + else: + facts[task["register"]] = results[task["register"]] + return PASS + + +def _marker(content: str) -> dict: + return { + "stalwart_store_marker_file": {"changed": False, "stat": {"exists": True}}, + "stalwart_store_marker": { + "changed": False, + "content": base64.b64encode(content.encode()).decode(), + }, + } + + +def _rows(value: str) -> dict: + return {"changed": False, "rows": [[value]]} + + +def _stdout(value: str) -> dict: + return {"changed": False, "stdout": value} + + +def _shared(layout: str) -> dict: + return { + **NO_MARKER, + "stalwart_store_database": _rows("1"), + "stalwart_store_layout": _rows(layout), + } + + +def _dedicated(engine: str, layout: str | None = None) -> dict: + results = { + **NO_MARKER, + "stalwart_store_volume": _stdout("stalwart_database\n"), + "stalwart_store_engine": _stdout(engine), + } + if layout is not None: + results["stalwart_store_layout"] = _rows(layout) + return results + + +class TestTheMarkerOfA1xDeployPassesWithoutTheStore(unittest.TestCase): + def test_a_marked_dedicated_store_passes_with_its_database_down(self): + self.assertEqual(_guard(_marker(_written_marker()), shared=False), PASS) + + def test_a_marked_shared_store_passes_without_a_query(self): + self.assertEqual(_guard(_marker(_written_marker()), shared=True), PASS) + + def test_a_marker_of_another_layout_leaves_the_store_to_be_read(self): + results = {**_dedicated(""), **_marker("0\n")} + self.assertIn(ENGINE_DOWN, _guard(results, shared=False)) + + +class TestAHostWithoutAStoreIsAFreshInstall(unittest.TestCase): + def test_no_store_database_on_the_shared_postgres_passes(self): + results = {**NO_MARKER, "stalwart_store_database": _rows("0")} + self.assertEqual(_guard(results, shared=True), PASS) + + def test_no_dedicated_volume_passes(self): + results = {**NO_MARKER, "stalwart_store_volume": _stdout("")} + self.assertEqual(_guard(results, shared=False), PASS) + + +class TestASharedStoreIsRead(unittest.TestCase): + def test_a_store_from_before_1_0_stops_the_deploy(self): + self.assertIn(PRE_1_0, _guard(_shared("bigint"), shared=True)) + + def test_a_1_x_store_passes(self): + self.assertEqual(_guard(_shared("bytea"), shared=True), PASS) + + def test_a_database_without_a_store_passes(self): + self.assertEqual(_guard(_shared("absent"), shared=True), PASS) + + +class TestADedicatedStoreIsReadInItsRunningDatabase(unittest.TestCase): + def test_a_stopped_database_stops_the_deploy_before_any_query(self): + self.assertIn(ENGINE_DOWN, _guard(_dedicated(""), shared=False)) + + def test_a_store_from_before_1_0_stops_the_deploy(self): + self.assertIn( + PRE_1_0, _guard(_dedicated("4f2a9c1e7b3d\n", "bigint"), shared=False) + ) + + def test_a_1_x_store_passes(self): + self.assertEqual( + _guard(_dedicated("4f2a9c1e7b3d\n", "bytea"), shared=False), PASS + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-stalwart/test_webui_oauth_client.py b/tests/unit/python/roles/web-app-stalwart/test_webui_oauth_client.py new file mode 100644 index 0000000000..063623dbaf --- /dev/null +++ b/tests/unit/python/roles/web-app-stalwart/test_webui_oauth_client.py @@ -0,0 +1,211 @@ +"""The OAuth client the WebUI signs in with when Stalwart is the authorization server. + +The WebUI Application always names ``stalwart-webui`` as its client id, so +Stalwart resolves it against a registered ``x:OAuthClient``. That client's +redirect URIs must be the WebUI's own ``//oauth/callback`` for +every URL prefix, also for a plaintext onion origin, and it must be first-party +or its tokens cannot reach the management API. A deploy updates the client only +when it differs from that target. +""" + +from __future__ import annotations + +import json +import unittest + +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar + +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.templating.ansible import _trust_as_template + +from . import PROJECT_ROOT + +ROLE = PROJECT_ROOT / "roles" / "web-app-stalwart" +TASK = ROLE / "tasks" / "02_webadmin.yml" +JMAP = ROLE / "templates" / "jmap" / "oauth_client" + +CLIENT_ID = "stalwart-webui" +ONION = "http://mail.abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion" +CLEARNET = "https://mail.example.test" +PREFIXES = ["/admin", "/account"] + + +def _render(template: str, **variables): + templar = Templar(loader=DataLoader(), variables=variables) + return templar.template(_trust_as_template(template)) + + +def _client(base_url: str, prefixes: list[str]) -> dict: + rendered = _render( + read_text(JMAP / "webui.json.j2"), + STALWART_WEBUI_OAUTH_CLIENT_ID=CLIENT_ID, + STALWART_WEBUI_APP_DESCRIPTION="Stalwart Web Interface", + STALWART_WEBUI_BASE_URL=base_url, + stalwart_webui_url_prefixes=prefixes, + ) + return json.loads(rendered) + + +def _task(name_fragment: str) -> dict: + tasks = load_yaml_any(str(TASK), default_if_missing=[]) + return next(t for t in tasks if name_fragment in t.get("name", "")) + + +def _updates(live: dict, desired: dict) -> bool: + variables = { + "stalwart_webui_oauth_clients": [live], + "stalwart_webui_oauth_client": desired, + } + return all( + _render("{{ (" + condition + ") | bool }}", **variables) + for condition in _task("Align the WebUI OAuth client")["when"] + ) + + +class TestWebuiClientRedirectUris(unittest.TestCase): + def test_an_onion_origin_registers_plaintext_callbacks(self): + client = _client(ONION, PREFIXES) + self.assertEqual( + sorted(client["redirectUris"]), + [f"{ONION}/account/oauth/callback", f"{ONION}/admin/oauth/callback"], + ) + + def test_a_clearnet_origin_registers_tls_callbacks(self): + client = _client(CLEARNET, PREFIXES) + self.assertEqual( + sorted(client["redirectUris"]), + [f"{CLEARNET}/account/oauth/callback", f"{CLEARNET}/admin/oauth/callback"], + ) + + def test_prefix_slashes_do_not_leak_into_the_uri(self): + client = _client(ONION, ["admin/", "//account"]) + self.assertEqual( + sorted(client["redirectUris"]), + [f"{ONION}/account/oauth/callback", f"{ONION}/admin/oauth/callback"], + ) + + def test_logout_returns_to_the_login_page_of_each_prefix(self): + client = _client(ONION, PREFIXES) + self.assertEqual( + sorted(client["postLogoutRedirectUris"]), + [f"{ONION}/account/login", f"{ONION}/admin/login"], + ) + + def test_a_single_prefix_still_renders_valid_json(self): + client = _client(ONION, ["/account"]) + self.assertEqual( + client["redirectUris"], {f"{ONION}/account/oauth/callback": True} + ) + + +class TestWebuiClientIsAFirstPartyPublicClient(unittest.TestCase): + def setUp(self): + self.client = _client(ONION, PREFIXES) + + def test_it_carries_the_application_client_id(self): + self.assertEqual(self.client["clientId"], CLIENT_ID) + + def test_it_is_first_party(self): + self.assertIs(self.client["firstParty"], True) + + def test_it_has_no_secret(self): + self.assertNotIn("secret", self.client) + + def test_it_allows_the_code_and_refresh_grants(self): + self.assertEqual( + self.client["grantTypes"], + {"authorizationCode": True, "refreshToken": True}, + ) + + +class TestWebuiClientJmapBodies(unittest.TestCase): + def setUp(self): + self.client = _client(ONION, PREFIXES) + + def test_create_registers_the_client(self): + body = json.loads( + _render( + read_text(JMAP / "create.json.j2"), + stalwart_webui_oauth_client=self.client, + ) + ) + method, args, _tag = body["methodCalls"][0] + self.assertEqual(method, "x:OAuthClient/set") + self.assertEqual(list(args["create"].values()), [self.client]) + + def test_update_patches_the_registered_record(self): + body = json.loads( + _render( + read_text(JMAP / "update.json.j2"), + stalwart_webui_oauth_client=self.client, + stalwart_webui_oauth_clients=[{"id": "b7", "clientId": CLIENT_ID}], + ) + ) + method, args, _tag = body["methodCalls"][0] + self.assertEqual(method, "x:OAuthClient/set") + self.assertEqual(args["update"], {"b7": self.client}) + + def test_get_lists_every_client(self): + body = json.loads(read_text(JMAP / "get.json.j2")) + method, args, _tag = body["methodCalls"][0] + self.assertEqual(method, "x:OAuthClient/get") + self.assertIsNone(args["ids"]) + + +class TestWebuiClientIsUpdatedOnlyOnDrift(unittest.TestCase): + def setUp(self): + self.desired = _client(ONION, PREFIXES) + self.live = { + **self.desired, + "id": "b7", + "createdAt": "2026-10-27T10:00:00Z", + "expiresAt": None, + "contacts": {}, + "logo": None, + "scopes": {}, + } + + def test_a_matching_client_is_left_alone(self): + self.assertFalse(_updates(self.live, self.desired)) + + def test_a_client_for_another_origin_is_updated(self): + live = { + **self.live, + "redirectUris": _client(CLEARNET, PREFIXES)["redirectUris"], + } + self.assertTrue(_updates(live, self.desired)) + + def test_a_client_missing_a_logout_target_is_updated(self): + live = {**self.live, "postLogoutRedirectUris": {}} + self.assertTrue(_updates(live, self.desired)) + + def test_a_third_party_client_is_updated(self): + live = {**self.live, "firstParty": False} + self.assertTrue(_updates(live, self.desired)) + + +class TestApplicationNamesTheClientUnconditionally(unittest.TestCase): + def _oauth_client_id(self, sso_enabled: bool) -> str: + task = _task("Point the WebUI Application") + body = json.loads( + _render( + task["vars"]["stalwart_jmap_body"], + stalwart_webui_app_id="a1", + STALWART_WEBUI_LOCAL_URL="file:///etc/stalwart/webui.zip", + STALWART_WEBUI_OAUTH_CLIENT_ID=CLIENT_ID, + STALWART_SSO_ENABLED=sso_enabled, + ) + ) + return body["methodCalls"][0][1]["update"]["a1"]["oauthClientId"] + + def test_with_sso(self): + self.assertEqual(self._oauth_client_id(True), CLIENT_ID) + + def test_without_sso(self): + self.assertEqual(self._oauth_client_id(False), CLIENT_ID) + + +if __name__ == "__main__": + unittest.main()