diff --git a/AGENTS.md b/AGENTS.md index 19a4a16f2..d61ea236a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -254,7 +254,7 @@ Services provision their own AppRoles via `tasks/manage-approle.yml` — no need | `secret/services/github-runner` | GitHub App private key (`app_private_key`) for the org runner-automation App. The App's OAuth client secret is NOT used and is not stored; the client id is the JWT issuer and is not secret. Read only by the orchestrator — a runner host is denied OpenBao by its own firewall declaration and never holds this | | `secret/services/weft/door`, `secret/services/weft-staging/door` | Front door `signing_key` (hex, generated once by the front door's deploy, reused forever) and its `public_key` (derived on the controller by every front door deploy, read by each workspace's deploy); staging shares nothing with the rack | | `secret/services/weft/workspaces/` (and `weft-staging/…`) | `seal`, 64 hex digits (32 bytes), generated once by the workspace's deploy and rendered as its `seal.key`; its only origin, never in a backup set. A workspace's model keys and forge token are NOT in OpenBao: its admin enters them in weft and they stay sealed in its catalog (weft D539) | -| `secret/services/smtp` | Outbound mail: `authentik_smtp_token`, `plane_smtp_token` and `grafana_smtp_token`. One shared mail token today, with a field per service so it can be split later (plan 29). The Authentik, Plane and Grafana deploys are to read them through `_shared_reads` (plan 29, units S4, S6 and S7); no deploy reads them yet. Local-dev seeds each field with a `LOCAL_FAKE__placeholder` value; the production value is placed by the operator, never generated | +| `secret/services/smtp` | Outbound mail: `authentik_smtp_token`, `plane_smtp_token` and `grafana_smtp_token`. One shared mail token today, with a field per service so it can be split later (plan 29). Deploy Plane reads `plane_smtp_token` through `_shared_reads` while mail is on. The Authentik and Grafana deploys are to read theirs the same way (plan 29, units S4 and S7); they do not yet. Local-dev seeds each field with a `LOCAL_FAKE__placeholder` value; the production value is placed by the operator, never generated | ## Composable Task Library @@ -338,7 +338,7 @@ Each deployment concern is its own playbook — independently runnable and retry | Deploy Postiz | `deploy-postiz.yml` | Social publishing (rootless podman, 5 containers + the inventory-gated search node `compose.search.yml`, required as of v2.23.0 — the backend registers >3 Text search attributes and SQL visibility caps at 3): secrets (+OIDC shared-read) → render BOTH env files → deploy.sh → verify app AND workflow engine | | Store Postiz API Key | `store-postiz-api-key.yml` | Capture the app-minted `/api/public/v1` key (the DB column IS the bearer value; minted on first sign-in) into `secret/services/postiz:postiz_api_key` — read from the service's own Postgres, never printed, all key-bearing steps `no_log`. | | Clean Deploy Postiz | `clean-deploy-postiz.yml` | Destructive: wipe containers + all four volumes + fresh deploy (social accounts need re-authorizing by hand afterwards) | -| Deploy Plane | `deploy-plane.yml` | Work tracker (rootless podman, Commercial edition): fetch Plane's Compose and variables files for the pinned release and verify each sha256 (never committed) → secrets + `.env` (refuses Plane's shipped default credentials) → deploy.sh with `compose.agentcloud.yml`, the proxy held until the instance is set up → first-run configuration (setup, invitation-only sign-up, workspace) → verify through the proxy. With `plane_github_app_id` declared it also renders the GitHub App settings (all six or none), sets the App's webhook URL and secret from the controller, and verifies an unsigned delivery is refused 401 | +| Deploy Plane | `deploy-plane.yml` | Work tracker (rootless podman, Commercial edition): fetch Plane's Compose and variables files for the pinned release and verify each sha256 (never committed) → secrets + `.env` (refuses Plane's shipped default credentials) → deploy.sh with `compose.agentcloud.yml`, the proxy held until the instance is set up → first-run configuration (setup, invitation-only sign-up, workspace) → verify through the proxy. With `plane_github_app_id` declared it also renders the GitHub App settings (all six or none), sets the App's webhook URL and secret from the controller, and verifies an unsigned delivery is refused 401. With `smtp_host` set it also writes Plane's outbound mail settings from the inventory and the mail token from `secret/services/smtp`; on local-dev it sends a test mail from the Plane worker and checks the local mail catcher | | Clean Deploy Plane | `clean-deploy-plane.yml` | Destructive: remove every container and named volume and deploy fresh; secrets return from OpenBao, all workspaces and work items are gone | | Back Up Plane DB | `backup-plane-db.yml` | Timestamped pg_dump of `plane-db` into an owner-only (0700) dir on the VM; read-only against the database, each run a NEW file. The database only; uploads are covered by a VM snapshot | | Restore Plane DB | `restore-plane-db.yml` | DESTRUCTIVE: restore a named dump (`-e plane_dump_file=` REQUIRED) into a staging database, swap it in only after it fully loads (prior kept as `plane_prev`), and bring the stack back through deploy.sh in an `always:` block, which reruns the migrator | diff --git a/docs/LESSONS.md b/docs/LESSONS.md index 8bb859ef2..6a30dd289 100644 --- a/docs/LESSONS.md +++ b/docs/LESSONS.md @@ -227,3 +227,9 @@ Superseded by L-033 - **ACCEPTED:** the pull request titled with AC-1149 (batch v0.18.0, unit U16c). - **DERIVED:** Proxmox runs a connection test inside every create and update of a metric server, and the write is refused when that test fails: `POST` and `PUT` `/cluster/metrics/server/{id}` both call `test_connection` before saving (pve-manager `PVE/API2/Cluster/MetricServer.pm`, `master`, :178 and :252), and the OpenTelemetry plugin's test posts an empty metrics payload to the declared URL with the certificate checked by host name (`PVE/Status/OpenTelemetry.pm`, :665-670). So a declared metric server can be written only after its receiver answers from the cluster: the receiver's listener is deployed, the node trusts the receiver's CA and resolves its name, and the receiver's firewall admits the node. A plan that converges a metric server orders its real run after those steps, and a dry run cannot show that the write will succeed. - **APPLIES TO:** `platform/playbooks/converge-proxmox-metric-server.yml` and any later converge of a Proxmox metric server, and the order of production runs that bring up the o11y Proxmox listener. + +### L-038 · 2026-12-02 · playbooks + +- **ACCEPTED:** the pull request titled with AC-1127 (unit 06 of batch proton-smtp, #1249). +- **DERIVED:** Plane's `manage.py test_email` exits 0 when delivery fails: it catches the send exception and prints an `Error: Email could not be delivered` line instead (`apps/api/plane/db/management/commands/test_email.py`, makeplane/plane default branch, :64-67). A task that sends a test mail through it judges the exact line `Email successfully sent` in its output and then the delivery itself (the local catcher, or the relay), never the exit code alone. +- **APPLIES TO:** any playbook or test under `platform/playbooks/` and `platform/tests/` that proves Plane's outbound mail by running its test-mail command (the local verify of `deploy-plane.yml` and the production test send, plan 29 unit S9). diff --git a/docs/MISTAKES.md b/docs/MISTAKES.md index 46715e098..7ab381875 100644 --- a/docs/MISTAKES.md +++ b/docs/MISTAKES.md @@ -158,7 +158,7 @@ and why. | 4.11 | A workstation home path reached a committed ledger entry; the audit grep for it ran by hand only | Data handling | 1 | Pre-commit hook (`no-machine-paths`) | | 4.12 | A brief carried an instance detail (a person) into the public template (widens 4.9) | Data handling | 1 | Convention | | 5.1 | Security check duplicated per caller; a fix reached three copies and missed two | Duplication | 1 | Test | -| 5.2 | Committed while a test was failing, because the check did not gate the commit (repeat 2026-09-25: a merge after a mergeability read, joined by `;`; 2026-10-30: a push under `SKIP_TESTS=1`; 2026-11-02: another, past two repo-wide guards; 2026-11-03: past the TLS guard again; 2026-11-04: a ledger edit past the citation guard; 2026-11-05: a playbook change past the check-mode contract test; 2026-11-08: a template comment past the check-mode injection guard; 2026-11-09: a template-order test the fast subset skips; 2026-11-11: a new test file past the spawn guard; 2026-11-11: a test-only push under `SKIP_TESTS=1`, past the line-window ratchet; 2026-11-17: a merge go sent in the same step as a CONFLICTING read; 2026-11-20: a registry row reported to a peer in the same step as a write that failed; 2026-11-27: a new tempfile user past the tempfile allowlist; 2026-11-28: a fixture certificate under `SKIP_TESTS=1` past the strict-chain guard; 2026-11-29: a new tempfile user under `SKIP_TESTS=1` past the tempfile allowlist again; 2026-11-29: a lesson-only push under `SKIP_TESTS=1` before its own hook run, over a red lint; 2026-11-30: a `dev` merge head pushed under `SKIP_TESTS=1` with no batch decision and no hook run of its own; 2026-12-01: a playbook refactor past the check-mode contract test the fast lane did not run) | Process | 22 | Pre-push hook (bypassed whole by `SKIP_TESTS=1`; narrower skip proposed); ledger citation test at pre-commit when `docs/MISTAKES.md` is staged | +| 5.2 | Committed while a test was failing, because the check did not gate the commit (repeat 2026-09-25: a merge after a mergeability read, joined by `;`; 2026-10-30: a push under `SKIP_TESTS=1`; 2026-11-02: another, past two repo-wide guards; 2026-11-03: past the TLS guard again; 2026-11-04: a ledger edit past the citation guard; 2026-11-05: a playbook change past the check-mode contract test; 2026-11-08: a template comment past the check-mode injection guard; 2026-11-09: a template-order test the fast subset skips; 2026-11-11: a new test file past the spawn guard; 2026-11-11: a test-only push under `SKIP_TESTS=1`, past the line-window ratchet; 2026-11-17: a merge go sent in the same step as a CONFLICTING read; 2026-11-20: a registry row reported to a peer in the same step as a write that failed; 2026-11-27: a new tempfile user past the tempfile allowlist; 2026-11-28: a fixture certificate under `SKIP_TESTS=1` past the strict-chain guard; 2026-11-28: a play var removed past the play-vars scope guard; 2026-11-29: a new tempfile user under `SKIP_TESTS=1` past the tempfile allowlist again; 2026-11-29: a lesson-only push under `SKIP_TESTS=1` before its own hook run, over a red lint; 2026-11-30: a `dev` merge head pushed under `SKIP_TESTS=1` with no batch decision and no hook run of its own; 2026-12-01: a playbook refactor past the check-mode contract test the fast lane did not run) | Process | 23 | Pre-push hook (bypassed whole by `SKIP_TESTS=1`; narrower skip proposed); ledger citation test at pre-commit when `docs/MISTAKES.md` is staged | | 5.3 | Merged a PR while its review was rate-limited | Process | 1 | Convention (user-stated) | | 5.4 | A command's own planning boundary honoured over an explicit instruction to implement (widened by 5.47) | Process | 1 | Convention + stop hook | | 5.5 | Repeated 5.2 — committed with a failing test; hooks do not gate the suite | Process | 1 | Pre-push hook | @@ -5185,6 +5185,8 @@ fast subset of scans that launch nothing includes it and would have stopped the **Occurrence 2026-11-28 (a fixture certificate past the strict-chain guard).** PR #1245 (AC-1147) head `fc91e167c` added a bats test that signs two fixture certificates with `openssl x509 -req -extfile`. It was pushed with `SKIP_TESTS=1` under batch v0.18.0 decision 35's extension, after the three changed test files ran alone and passed. CI's Python (8/8) failed on `test_fixture_certs_strict_chain.py::test_every_extfile_signing_site_is_followed_by_a_strict_chain_check`, which counts the `-extfile` signing sites in every test file and requires an `assert_strict_chain(` call for each (1 failed, 1211 passed). Fixed in `5832b2c6d` by adding key identifiers and a strict check after each signing. Why the rule did not fire: the extension asks for the test files the head changes or that cover the code it changes, and I read that as the changed files only; this guard scans every test file without naming any. This is the shape of the 2026-11-11 test-only push above, which already says a pushed change to a `*.bats` file is the subject of repo-wide guards that only the full suite runs. +**Occurrence 2026-11-28 (a play var removed past the play-vars scope guard).** PR #1249 (AC-1127) head `c8c6cdb5` carried a `/simplify` fix (`210720ad`) that dropped `_deploy_dir` from the Phase 4 vars of `deploy-plane.yml`, on the reading that `tasks/list-service-containers.yml` sets it as a fact earlier in that play. It was pushed through the pre-push hook, which passed. CI's Python (2/8) failed on `test_play_vars_scope.py::test_no_play_reads_another_plays_vars` (1 failed, 1185 passed): that guard does not scan included task files, so the read looked like another play's var. Fixed before merge by defining it in Phase 4 again (`c7e0a310`). Why the rule did not fire: the fast lane keeps an unchanged file only when every one of its tests ran under 0.25 s in CI, and `test_durations.json` records this file at a 1.09 s maximum, so the push ran without it. This is the shape of the 2026-11-09 occurrence above. + **Occurrence 2026-11-29 (a new tempfile user past the tempfile allowlist again).** PR #1256 (AC-1002) head `a23a9a804` added an `ansible.builtin.tempfile` task to `cleanup-proxmox-backup-archives.yml` for the reviewed helpers' scratch directory. It was pushed with `SKIP_TESTS=1` under the batch's rule for weft-only pre-push failures, after the cleanup Rust tests and five playbook scanners passed locally; the hook's own run had failed only on weft tests. CI's Python (5/8) failed on `test_materialise_ssh_key.py::test_exactly_one_file_materialises_an_ssh_probe_key` (1 failed). Fixed in the PR's correction by adding the playbook to `TEMPFILE_USERS`. Why the rule did not fire: the 2026-11-27 occurrence above names this exact test and why the fast lane skips it, and I chose the local test set from the files the change touched without searching the tests for `tempfile`. A change that adds a `tempfile` task runs every test file that names `tempfile` before it is pushed. **Occurrence 2026-11-29 (a lesson-only head pushed under `SKIP_TESTS=1` before its own hook run, over a red lint).** PR #1259 (AC-1136): the simplify fix `cde00b8f5` left `platform/tests/ssh_harness.py:95` at 158 characters. Neither the pre-commit hook nor the pre-push hook runs ruff, so it reached the remote with the `dev` merge `31ac1dde3`, whose Static Analysis failed on ruff E501. Before reading that result I pushed `8e5e13186`, which only adds a `docs/LESSONS.md` entry, with `SKIP_TESTS=1`. Batch v0.18.0 allows that only after the full hook on that head fails solely on the known weft failures, and the hook had run on `31ac1dde3`, not on that head. Run after the push, it failed only on those (16 tests in `test_weft_deploy_runs.py`, BATS 845; the Rust lane passed 1042). Static Analysis failed again on `8e5e13186`; fixed in `cb746b1ef`. Why the rule did not fire: the head changed one Markdown file, so the parent's run felt like its own, and the parent's CI was not read before the next push. A push under `SKIP_TESTS=1` waits for the hook's run on that exact head, and for the previous head's CI to be read; `ruff check` runs on every changed Python file before a push. diff --git a/platform/playbooks/deploy-plane.yml b/platform/playbooks/deploy-plane.yml index 86ac479d1..fc8426e66 100644 --- a/platform/playbooks/deploy-plane.yml +++ b/platform/playbooks/deploy-plane.yml @@ -11,6 +11,8 @@ # Phase 3: First-run configuration (configure_instance.py, inside plane-api): instance setup, # invitation-only sign-up and the workspace. In the SAME run as the first start, # because until the first admin signs up anyone who reaches /god-mode/ claims it. +# With mail on (smtp_host set), the same run also writes Plane's outbound mail settings +# from the inventory's SMTP values and the mail token in secret/services/smtp. # Phase 3b: Get or create the workspace service token (service_token.py) and store it in # OpenBao, so sync-plane-projects.yml only ever reads it. # Phase 3c: Activate the Pro licence from OpenBao (activate_license.py), as the workspace owner; @@ -19,7 +21,9 @@ # (github_app_token.py set-hook-secret, on the controller) to the one Plane holds. # Phase 3e: Create Plane's marketplace applications (GitHub, Slack, ...) that are missing, the # entries Workspace settings > Integrations lists (ensure_marketplace_apps.py). -# Phase 4: Verify through the proxy, then record the service-deploy step result. +# Phase 4: Verify through the proxy. With mail on locally, it also sends a test mail from the Plane +# worker and checks that the local mail catcher received it. Then it records the +# service-deploy step result. # # Plan: plan/development/16-plane-work-management.md # Change: plan/development/openspec/changes/deploy-plane-work-management/ @@ -126,14 +130,23 @@ # the worker's env). Read it read-only, and only when sign-in through Authentik is configured # (plane_authentik_base), so a host without OIDC never depends on Deploy Authentik having # declared it. Never stored back under secret/services/plane. + # The mail token is read only when mail is on (smtp_host set), and then as a listed read: a + # missing path fails the run, so Phase 3 never reaches the mail settings without it. _shared_reads: >- - {{ [{'from_service': 'authentik', 'read_keys': ['plane_oidc_client_secret']}] - if plane_authentik_base is defined else [] }} + {{ ([{'from_service': 'authentik', 'read_keys': ['plane_oidc_client_secret']}] + if plane_authentik_base is defined else []) + + ([{'from_service': 'smtp', 'read_keys': ['plane_smtp_token']}] + if (smtp_host | default('', true) | string) | length > 0 else []) }} _env_templates: - { src: env.j2, dest: .env, mode: "0600" } _service_url: "{{ plane_public_url | default('') }}" tasks: + # The SMTP guard runs first: it refuses a mail setting that would send the token somewhere it + # must not go, before any secret is read. + - name: "Refuse SMTP settings that would send the mail token somewhere it must not go" + ansible.builtin.include_tasks: tasks/assert-smtp-settings.yml + # manage-secrets sends the controller AppRole and receives every secret over this # connection — refuse a public cleartext endpoint before any of it is sent. - name: "Refuse a cleartext OpenBao endpoint" @@ -213,8 +226,25 @@ 'OIDC_AUTHORIZE_URL': plane_authentik_base ~ '/application/o/authorize/', 'OIDC_TOKEN_URL': plane_authentik_base ~ '/application/o/token/', 'OIDC_USERINFO_URL': plane_authentik_base ~ '/application/o/userinfo/'} }} + # Outbound mail, on when the inventory sets smtp_host (the guard reads the same expression). Off, + # no mail key is sent and nothing is cleared: the disable endpoint is not called. Every value is + # a string, so a second run with the same settings patches nothing. + _plane_mail_settings: >- + {{ {} if not ((smtp_host | default('', true) | string) | length > 0) else { + 'ENABLE_SMTP': '1', + 'EMAIL_HOST': smtp_host | string, + 'EMAIL_PORT': smtp_port | string, + 'EMAIL_HOST_USER': smtp_username | string, + 'EMAIL_HOST_PASSWORD': _shared.plane_smtp_token, + 'EMAIL_USE_TLS': '1' if (smtp_starttls | default(true) | bool) else '0', + 'EMAIL_USE_SSL': '0', + 'EMAIL_FROM': smtp_from_address | string} }} tasks: + # The SMTP guard runs first, as in every play that renders a mail setting. + - name: "Refuse SMTP settings that would send the mail token somewhere it must not go" + ansible.builtin.include_tasks: tasks/assert-smtp-settings.yml + # Credential task: the admin password goes to the script on stdin, so no_log here and # only the non-secret summary is shown below. - name: "Converge instance setup, invitation-only sign-up and the workspace" @@ -237,7 +267,7 @@ 'company': plane_company_name, 'workspace_slug': plane_workspace_slug, 'workspace_name': plane_workspace_name, - 'settings': _plane_oidc_settings} | to_json }} + 'settings': _plane_oidc_settings | combine(_plane_mail_settings)} | to_json }} register: _plane_configure # The script prints one JSON line, {"changed", "actions"} or {"error"}, never a credential. # Judged below from that line, so a refusal is visible while this task stays no_log. @@ -592,8 +622,28 @@ become: false vars: _engine: "{{ container_engine | default('podman') }}" + # The fact tasks/list-service-containers.yml sets in the containers-stable check replaces this, with + # the same formula. It is declared here too because test_play_vars_scope.py does not follow includes. + _deploy_dir: >- + {{ compose_working_dir if (compose_working_dir | default('') | length > 0) + else (local_monorepo_dir | default('/home/' ~ (ansible_user | default('deploy')) ~ '/agent-cloud')) + ~ '/' ~ monorepo_deploy_path }} + # The names of the running containers whose compose service label is exactly `worker` + # (not beat-worker, not a worker2). Read from the `podman ps` the local mail check registers. + _plane_worker_names: >- + {%- set ns = namespace(names=[]) -%} + {%- for c in (_plane_ps.stdout | default('[]', true) | from_json) -%} + {%- if ((c.Labels | default({}, true))['com.docker.compose.service'] | default('', true)) == 'worker' -%} + {%- set ns.names = ns.names + [c.Names[0]] -%} + {%- endif -%} + {%- endfor -%} + {{ ns.names }} tasks: + # The SMTP guard runs first, as in every play that renders a mail setting. + - name: "Refuse SMTP settings that would send the mail token somewhere it must not go" + ansible.builtin.include_tasks: tasks/assert-smtp-settings.yml + # A dry run skipped the deploy, so on a fresh host the stack does not exist and the probe # below would fail on it: check, and stop the dry run there (deploy-agentgateway.yml). - name: "Dry run: is the plane proxy running?" @@ -682,6 +732,62 @@ - name: "Every container is running and stable (no crash loop)" ansible.builtin.include_tasks: tasks/assert-containers-stable.yml + # Local-dev only, with mail on (AC-1127): a test mail from the Plane worker must reach the local + # catcher. test_email exits 0 even when delivery fails, so the send task judges its exact success + # line rather than the exit code. + - name: "Local mail check: a test mail from the Plane worker reaches the local catcher" + when: + - (smtp_host | default('', true) | string) | length > 0 + - groups['all'] | local_dev_inventory + - not ansible_check_mode + block: + - name: "Find the Plane worker container (local mail check)" + ansible.builtin.command: + argv: + - "{{ _engine }}" + - ps + - --filter + - "{{ 'label=com.docker.compose.project.working_dir=' ~ _deploy_dir }}" + - --format + - json + register: _plane_ps + changed_when: false + + - name: "Require exactly one Plane worker container" + ansible.builtin.assert: + that: + - _plane_worker_names | length == 1 + # default() keeps this renderable when the list is empty (MISTAKES 10.36). + fail_msg: "expected exactly one Plane worker container, found {{ _plane_worker_names | default([]) | length }}" + quiet: true + + # The send is judged from the time just before it, so the catcher check counts only this run's mail. + - name: "Mark the time just before the test mail" + ansible.builtin.set_fact: + _plane_mail_since: "{{ now(utc=true, fmt='%Y-%m-%dT%H:%M:%SZ') }}" + + - name: "Send a test mail from the Plane worker" + ansible.builtin.command: + argv: + - "{{ _engine }}" + - exec + - "{{ _plane_worker_names[0] }}" + - python + - manage.py + - test_email + - "{{ smtp_from_address | string }}" + register: _plane_test_mail + changed_when: false + failed_when: _plane_test_mail.rc != 0 or 'Email successfully sent' not in _plane_test_mail.stdout_lines + + - name: "The test mail reached the local mail catcher" + ansible.builtin.include_tasks: tasks/assert-mail-captured.yml + vars: + mail_captured_api_url: "http://mailpit:8025" + mail_captured_recipient: "{{ smtp_from_address }}" + mail_captured_subject: "Test email" + mail_captured_since: "{{ _plane_mail_since }}" + - name: "Report" ansible.builtin.debug: msg: >- diff --git a/platform/services/plane/deployment/CLAUDE.md b/platform/services/plane/deployment/CLAUDE.md index 94eeda8e0..a77700d0f 100644 --- a/platform/services/plane/deployment/CLAUDE.md +++ b/platform/services/plane/deployment/CLAUDE.md @@ -140,6 +140,33 @@ identical on every install. `env.j2` refuses to render if any of them comes out equal to the shipped value. Note the RabbitMQ trap: Plane's Compose reads `RABBITMQ_PASSWORD`, not the `RABBITMQ_DEFAULT_PASS` its `variables.env` sets, so both are written. +## Outbound mail + +With `smtp_host` set in the inventory, the deploy also sends Plane's mail through the platform SMTP +service (AC-1127). It writes these instance settings, and only these: `ENABLE_SMTP` as `1`, +`EMAIL_HOST` from `smtp_host`, `EMAIL_PORT` from `smtp_port`, `EMAIL_HOST_USER` from `smtp_username`, +`EMAIL_HOST_PASSWORD` from the mail token, `EMAIL_USE_TLS` as `1` unless `smtp_starttls` is false, +`EMAIL_USE_SSL` as `0`, and `EMAIL_FROM` from `smtp_from_address`. Every value is a string, so a rerun +with the same inventory patches nothing. + +The token is read from `secret/services/smtp:plane_smtp_token` through `_shared_reads`, and only while +mail is on. A listed read of a missing key fails the run before Phase 3 reaches the mail settings. The +token goes on the stdin of the configuration task, which is `no_log`, as the OIDC secret does. + +With `smtp_host` unset, `false`, `0`, blank or null, mail is off. No mail key is sent, nothing is +cleared, and Plane's disable endpoint is not called, so Plane keeps the settings it already has. The SMTP +guard (`tasks/assert-smtp-settings.yml`) is the first task of Phases 1, 3 and 4. + +Local verification runs in Phase 4 on local-dev only, with mail on. It finds the one running Plane worker +by its compose service label, sends a test mail from it to `smtp_from_address` with +`python manage.py test_email`, and requires the exact line `Email successfully sent`, because +`test_email` exits 0 even when delivery fails. It then checks the Mailpit catcher for a message to that +address with subject `Test email` created since just before the send. The worker joins `local-dev` in +`compose.local.yml` so it can reach `mailpit:1025`. + +Only outbound mail is covered here. The inbound `email` service stays disabled by its profile. Production +mail stays off until an inventory names `smtp_host`, which this change does not do. + ## First run closes the instance Until the first admin signs up, **anyone who reaches `/god-mode/` claims the instance**. The diff --git a/platform/services/plane/deployment/compose.local.yml b/platform/services/plane/deployment/compose.local.yml index baf3a56f5..5c43652ea 100644 --- a/platform/services/plane/deployment/compose.local.yml +++ b/platform/services/plane/deployment/compose.local.yml @@ -22,3 +22,8 @@ services: networks: - default - local-dev + # worker sends Plane's mail (its celery tasks) to the local catcher, mailpit:1025 on local-dev. + worker: + networks: + - default + - local-dev diff --git a/platform/tests/test_plane_outbound_mail.py b/platform/tests/test_plane_outbound_mail.py new file mode 100644 index 000000000..a491fac6a --- /dev/null +++ b/platform/tests/test_plane_outbound_mail.py @@ -0,0 +1,432 @@ +"""Plane's outbound mail (AC-1127), tested from deploy-plane.yml itself. + +The expressions and tasks below are read from the playbook's YAML, never copied, so a red test +names the playbook's own text. They run under ansible-playbook on localhost through harness_sandbox, +and each group of cases is one run: every case is a host with its own inventory vars, each host +writes what its tasks render to a file in the run's out directory, and a test reads only its own +host's file, so a red case still names itself. + +Three things are stubbed: the worker listing (a `_plane_ps` host var stands in for `podman ps`), the +test-mail command (a `send_argv` host var replaces its argv with printf or sh), and the mail catcher +(not called here). Every value is a placeholder: example.test addresses and a fake token. Nothing +here reaches a container, a mail server or the network. +""" + +import copy +import json +import re +from pathlib import Path + +import harness_sandbox +import playbook_yaml +import pytest +import yaml + +REPO = playbook_yaml.REPO +DEPLOY = REPO / "platform/playbooks/deploy-plane.yml" +COMPOSE_LOCAL = REPO / "platform/services/plane/deployment/compose.local.yml" + +PHASE1 = "Phase 1: Place repo + manage plane secrets" +PHASE3 = "Phase 3: Configure plane" +PHASE4 = "Phase 4: Verify plane" +GUARD = "Refuse SMTP settings that would send the mail token somewhere it must not go" +GUARD_FILE = "tasks/assert-smtp-settings.yml" +CONVERGE = "Converge instance setup, invitation-only sign-up and the workspace" +CONTAINERS_STABLE = "Every container is running and stable (no crash loop)" +MAIL_BLOCK = "Local mail check: a test mail from the Plane worker reaches the local catcher" +FIND = "Find the Plane worker container (local mail check)" +WORKER_ASSERT = "Require exactly one Plane worker container" +MARK = "Mark the time just before the test mail" +SEND = "Send a test mail from the Plane worker" +CATCHER = "The test mail reached the local mail catcher" +RECORD = "Record the service-deploy step result" +MAIL_ON_WHEN = [ + "(smtp_host | default('', true) | string) | length > 0", + "groups['all'] | local_dev_inventory", + "not ansible_check_mode", +] +FAKE_TOKEN = "tok-example-not-real" +UNSET = object() +# What the mail-settings host renders: the Phase 3 expression, as the playbook writes it. +MAIL_EXPR = "{{ _plane_mail_settings | to_json }}" + +# The five inventory names as local-dev sets them, with a mail host that is on. +MAIL = { + "smtp_host": "mail.example.test", + "smtp_port": 587, + "smtp_starttls": True, + "smtp_username": "plane-mail@example.test", + "smtp_from_address": "noreply@example.test", +} +MAIL_OTHER = {k: v for k, v in MAIL.items() if k != "smtp_host"} +NO_STARTTLS = {k: v for k, v in MAIL.items() if k != "smtp_starttls"} +# The eight settings mail on writes. Every value is a string, so the port is "587", never 587. +MAIL_SETTINGS = { + "ENABLE_SMTP": "1", + "EMAIL_HOST": "mail.example.test", + "EMAIL_PORT": "587", + "EMAIL_HOST_USER": "plane-mail@example.test", + "EMAIL_HOST_PASSWORD": FAKE_TOKEN, + "EMAIL_USE_TLS": "1", + "EMAIL_USE_SSL": "0", + "EMAIL_FROM": "noreply@example.test", +} +AUTH = {"plane_authentik_base": "https://auth.example.test:8443"} +# The inventory vars the converge stdin reads, besides the mail names. +CONVERGE_BASE = { + "plane_public_url": "https://plane.example.test", + "plane_automation_email": "automation@example.test", + "plane_company_name": "Example Co", + "plane_workspace_slug": "example", + "plane_workspace_name": "Example", +} + + +# Group (a), Phase 3: mail is off for every spelling of "not set", and on for the rest. +MAIL_OFF_HOSTS = { + "off-unset": {}, + "off-false": {"smtp_host": False}, + "off-zero": {"smtp_host": 0}, + "off-blank": {"smtp_host": ""}, + "off-null": {"smtp_host": None}, +} +# smtp_starttls as the inventory gives it (UNSET: not given), and the EMAIL_USE_TLS it must map to. +STARTTLS_HOSTS = { + "starttls-bool-true": (True, "1"), + "starttls-str-true": ("true", "1"), + "starttls-str-capitalised-true": ("True", "1"), + "starttls-unset": (UNSET, "1"), + "starttls-bool-false": (False, "0"), + "starttls-str-false": ("false", "0"), + "starttls-str-capitalised-false": ("False", "0"), +} + + +def _starttls_host(tls) -> dict: + return dict(NO_STARTTLS) if tls is UNSET else {**NO_STARTTLS, "smtp_starttls": tls} + + +MAIL_HOSTS = { + **{host: {**MAIL_OTHER, **extra} for host, extra in MAIL_OFF_HOSTS.items()}, + "on": MAIL, + "port-int": {**MAIL, "smtp_port": 1025}, + "port-str": {**MAIL, "smtp_port": "1025"}, + **{host: _starttls_host(tls) for host, (tls, _) in STARTTLS_HOSTS.items()}, +} +# Group (a), converge: the stdin the converge task sends, rendered for a host with the base Plane vars. +CONVERGE_HOSTS = { + "converge-mail-on": {**CONVERGE_BASE, **MAIL}, + "converge-mail-off": {**CONVERGE_BASE}, +} +# Group (b): the listed reads for each combination of authentik and mail, as (authentik, mail). +SHARED_READ_CASES = { + "authentik-off-mail-off": (False, False), + "authentik-off-mail-on": (False, True), + "authentik-on-mail-off": (True, False), + "authentik-on-mail-on": (True, True), +} + + +def _play(name: str) -> dict: + return next(p for p in playbook_yaml.load(DEPLOY) if p.get("name") == name) + + +def _task(play: dict, name: str) -> dict: + """A task by its exact name, at any depth, as a copy the test may edit.""" + return copy.deepcopy(next(t for t in playbook_yaml.tasks(play.get("tasks")) if t.get("name") == name)) + + +def _phase3_vars() -> dict: + # The real Phase 3 vars; `_shared` stands in for the fact manage-secrets sets in Phase 1. + return {**_play(PHASE3)["vars"], "_shared": {"plane_smtp_token": FAKE_TOKEN}} + + +def _host(case: str) -> str: + """A plain host name for a case: its label in lower case, each run of other characters a hyphen.""" + return re.sub(r"[^a-z0-9]+", "-", case.lower()).strip("-") + + +def _emit(content: str) -> dict: + """A task that writes `content`, rendered for this host, to the run's out directory as .json.""" + return {"ansible.builtin.copy": {"content": content, "dest": "{{ out_dir }}/{{ inventory_hostname }}.json"}} + + +class _Batch: + """A finished run: the output of ansible-playbook, and the JSON each host wrote to the out directory.""" + + def __init__(self, out: Path, run) -> None: + self.out = out + self.run = run + + def result(self, host: str): + path = self.out / f"{host}.json" + assert path.exists(), f"host {host} wrote no result\n{self.run.stdout}{self.run.stderr}" + return json.loads(path.read_text()) + + +def _batch(tmp: Path, hosts: dict, play_vars: dict, tasks: list) -> _Batch: + """One ansible-playbook run of one play over every host. A host's own vars are its case; the play + vars and the tasks are shared. The exit status is not asserted here: a host that failed writes no + result, and its own case reports that with the run's output.""" + out = tmp / "out" + out.mkdir() + inventory = {"all": {"hosts": {name: {"ansible_connection": "local", **hv} for name, hv in hosts.items()}}} + (tmp / "inv.yml").write_text(yaml.safe_dump(inventory)) + play = {"hosts": "all", "gather_facts": False, "vars": {**play_vars, "out_dir": str(out)}, "tasks": tasks} + (tmp / "play.yml").write_text(yaml.safe_dump([play])) + run = harness_sandbox.run_playbook(tmp / "play.yml", tmp, inventory=tmp / "inv.yml") + return _Batch(out, run) + + +# ── What Plane is told (Phase 3) ───────────────────────────────────────────── + + +@pytest.fixture(scope="module") +def mail_batch(tmp_path_factory): + """Group (a): every Phase 3 mail case and both converge stdins, one run.""" + stdin = _task(_play(PHASE3), CONVERGE)["ansible.builtin.command"]["stdin"] + hosts = {host: {**hv, "_probe": MAIL_EXPR} for host, hv in MAIL_HOSTS.items()} + hosts |= {host: {**hv, "_probe": stdin} for host, hv in CONVERGE_HOSTS.items()} + play_vars = {**_phase3_vars(), "_resolved": {"plane_automation_password": "pw-example-not-real"}} + return _batch(tmp_path_factory.mktemp("mail-settings"), hosts, play_vars, [_emit("{{ _probe }}")]) + + +@pytest.mark.parametrize("host", list(MAIL_OFF_HOSTS)) +def test_mail_is_off_when_smtp_host_is_unset_false_zero_blank_or_null(mail_batch, host): + assert mail_batch.result(host) == {} + + +def test_mail_on_writes_exactly_the_eight_settings_and_every_value_is_a_string(mail_batch): + assert mail_batch.result("on") == MAIL_SETTINGS + + +@pytest.mark.parametrize("host", ["port-int", "port-str"]) +def test_the_port_is_a_string_whether_the_inventory_gives_an_int_or_a_string(mail_batch, host): + assert mail_batch.result(host)["EMAIL_PORT"] == "1025" + + +@pytest.mark.parametrize(("host", "tls"), [pytest.param(h, tls, id=h) for h, (_, tls) in STARTTLS_HOSTS.items()]) +def test_starttls_maps_to_tls_as_a_string_for_every_spelling(mail_batch, host, tls): + got = mail_batch.result(host) + assert got["EMAIL_USE_TLS"] == tls + # SSL is never on: Plane's TLS and SSL are exclusive, and the catcher and the relay both use STARTTLS. + assert got["EMAIL_USE_SSL"] == "0" + + +@pytest.mark.parametrize( + ("host", "expected"), + [ + ("converge-mail-on", {"IS_OIDC_ENABLED": "0", **MAIL_SETTINGS}), + ("converge-mail-off", {"IS_OIDC_ENABLED": "0"}), + ], +) +def test_the_converge_stdin_carries_the_oidc_settings_and_the_mail_settings_only_while_mail_is_on( + mail_batch, host, expected +): + task = _task(_play(PHASE3), CONVERGE) + assert "_plane_oidc_settings | combine(_plane_mail_settings)" in task["ansible.builtin.command"]["stdin"] + assert mail_batch.result(host)["settings"] == expected + + +# ── What the deploy reads (Phase 1) ────────────────────────────────────────── + + +@pytest.fixture(scope="module") +def shared_batch(tmp_path_factory): + """Group (b): the Phase 1 listed reads for every combination of authentik and mail, one run.""" + hosts = { + host: {**(AUTH if auth else {}), **(MAIL if mail else {})} for host, (auth, mail) in SHARED_READ_CASES.items() + } + play_vars = {"_shared_reads": _play(PHASE1)["vars"]["_shared_reads"]} + return _batch(tmp_path_factory.mktemp("shared-reads"), hosts, play_vars, [_emit("{{ _shared_reads | to_json }}")]) + + +@pytest.mark.parametrize("host", list(SHARED_READ_CASES)) +def test_the_token_is_a_listed_read_only_while_mail_is_on(shared_batch, host): + auth, mail = SHARED_READ_CASES[host] + got = shared_batch.result(host) + authentik = [e for e in got if e["from_service"] == "authentik"] + smtp = [e for e in got if e["from_service"] == "smtp"] + assert authentik == ([{"from_service": "authentik", "read_keys": ["plane_oidc_client_secret"]}] if auth else []) + assert smtp == ([{"from_service": "smtp", "read_keys": ["plane_smtp_token"]}] if mail else []) + assert len(got) == int(auth) + int(mail) + + +# ── The worker and the test mail (Phase 4 local mail check) ────────────────── + + +def _container(name: str, service: str) -> dict: + return {"Names": [name], "Labels": {"com.docker.compose.service": service}} + + +WORKER_CASES = [ + ( + "one worker beside beat-worker", + [_container("plane_worker_1", "worker"), _container("plane_beat-worker_1", "beat-worker")], + True, + ["plane_worker_1"], + ), + ("the name is not the selector", [_container("plane_worker_10", "worker")], True, ["plane_worker_10"]), + ( + "a worker2 service beside the worker", + [_container("plane_worker2_1", "worker2"), _container("plane_worker_1", "worker")], + True, + ["plane_worker_1"], + ), + ("no worker", [_container("plane_beat-worker_1", "beat-worker")], False, []), + ("no containers", [], False, []), + ( + "two workers", + [_container("plane_worker_1", "worker"), _container("plane_worker_2", "worker")], + False, + ["plane_worker_1", "plane_worker_2"], + ), + ("a worker without a compose label", [{"Names": ["plane_worker_1"]}], False, []), +] + + +@pytest.fixture(scope="module") +def worker_batch(tmp_path_factory): + """Group (c): the real worker selection and the real assert, one host per container listing, one run.""" + hosts = { + _host(label): {"_plane_ps": {"stdout": json.dumps(containers)}} for label, containers, _, _ in WORKER_CASES + } + assertion = _task(_play(PHASE4), WORKER_ASSERT) + assertion |= {"register": "_plane_assert", "ignore_errors": True} + probe = ( + "{{ {'names': _plane_worker_names," + " 'failed': _plane_assert is failed," + " 'msg': _plane_assert.msg | default('')} | to_json }}" + ) + return _batch(tmp_path_factory.mktemp("worker"), hosts, _play(PHASE4)["vars"], [assertion, _emit(probe)]) + + +@pytest.mark.parametrize( + ("host", "passes", "names"), + [pytest.param(_host(label), passes, names, id=label) for label, _, passes, names in WORKER_CASES], +) +def test_exactly_one_worker_is_selected_by_its_compose_service_label(worker_batch, host, passes, names): + got = worker_batch.result(host) + assert got["names"] == names + assert (not got["failed"]) is passes, got + if not passes: + assert f"found {len(names)}" in got["msg"], got + + +SEND_CASES = [ + # label, stub argv, its rc, its stdout lines, whether the send passes + ( + "the exact success line", + ["printf", "%s\n", "Trying to send test email...", "Email successfully sent"], + 0, + ["Trying to send test email...", "Email successfully sent"], + True, + ), + ( + "an error line with exit 0", + ["printf", "%s\n", "Error: Email could not be delivered due to x"], + 0, + ["Error: Email could not be delivered due to x"], + False, + ), + ( + "a line that only contains the success text", + ["printf", "%s\n", "Not: Email successfully sent yet"], + 0, + ["Not: Email successfully sent yet"], + False, + ), + ( + "the success line with exit 1", + ["sh", "-c", "echo 'Email successfully sent'; exit 1"], + 1, + ["Email successfully sent"], + False, + ), +] + + +@pytest.fixture(scope="module") +def send_batch(tmp_path_factory): + """Group (d): the real send task judged on each stub, and the time the mail check marks, one run.""" + hosts = {_host(label): {"send_argv": argv} for label, argv, *_ in SEND_CASES} + send = _task(_play(PHASE4), SEND) + send["ansible.builtin.command"] = {"argv": "{{ send_argv }}"} + send |= {"ignore_errors": True} + probe = ( + "{{ {'failed': _plane_test_mail is failed, 'rc': _plane_test_mail.rc | default(none)," + " 'stdout_lines': _plane_test_mail.stdout_lines | default(none), 'since': _plane_mail_since} | to_json }}" + ) + tasks = [_task(_play(PHASE4), MARK), send, _emit(probe)] + return _batch(tmp_path_factory.mktemp("send"), hosts, {}, tasks) + + +@pytest.mark.parametrize( + ("host", "rc", "lines", "passes"), + [pytest.param(_host(label), rc, lines, passes, id=label) for label, _, rc, lines, passes in SEND_CASES], +) +def test_the_test_mail_is_judged_by_its_exact_success_line_and_its_exit_status(send_batch, host, rc, lines, passes): + got = send_batch.result(host) + # The stub ran and printed what the case says, so a failure is the judgement's, not a skipped command. + assert (got["rc"], got["stdout_lines"]) == (rc, lines) + assert (not got["failed"]) is passes + + +def test_the_since_time_is_the_fixed_utc_form_the_catcher_check_accepts(send_batch): + for label, *_ in SEND_CASES: + since = send_batch.result(_host(label))["since"] + assert re.fullmatch(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ", since), since + + +# ── Static: the shape of the plays and the block ───────────────────────────── + + +def test_every_play_that_renders_a_mail_setting_starts_with_the_guard(): + plays = {p["name"]: p for p in playbook_yaml.load(DEPLOY) if "tasks" in p} + mail_plays = sorted(name for name, p in plays.items() if "smtp_" in json.dumps(p)) + assert mail_plays == sorted([PHASE1, PHASE3, PHASE4]) + for name in mail_plays: + first = plays[name]["tasks"][0] + assert first.get("name") == GUARD, name + assert first.get("ansible.builtin.include_tasks") == GUARD_FILE, name + + +def test_the_local_mail_check_follows_the_containers_check_and_precedes_the_report(): + tasks = _play(PHASE4)["tasks"] + names = [t.get("name") for t in tasks] + assert names.index(CONTAINERS_STABLE) < names.index(MAIL_BLOCK) < names.index("Report") + assert names[-1] == RECORD + + +def test_the_mail_block_is_gated_and_runs_its_tasks_in_order_without_no_log(): + block = _task(_play(PHASE4), MAIL_BLOCK) + assert sorted(block["when"]) == sorted(MAIL_ON_WHEN) + inner = [t.get("name") for t in block["block"]] + assert inner == [FIND, WORKER_ASSERT, MARK, SEND, CATCHER] + assert not any(t.get("no_log") for t in block["block"]) + + +def test_the_catcher_check_reads_the_mailpit_api_and_this_runs_since_the_mark(): + catcher = _task(_play(PHASE4), CATCHER) + assert catcher["ansible.builtin.include_tasks"] == "tasks/assert-mail-captured.yml" + assert catcher["vars"]["mail_captured_api_url"] == "http://mailpit:8025" + assert catcher["vars"]["mail_captured_since"] == "{{ _plane_mail_since }}" + assert catcher["vars"]["mail_captured_subject"] == "Test email" + + +def test_the_catcher_inputs_are_set_only_as_the_include_vars_of_the_catcher_check(): + # assert-mail-captured.yml takes its inputs as include vars or play vars. Here they are include + # vars of the one catcher task and nothing else defines them: a play var, a block var, a set_fact + # or a register would be a second source the shared task's own extra-var refusal does not cover. + found = set() + for node in playbook_yaml.tasks(playbook_yaml.load(DEPLOY)): + names = [*(node.get("vars") or {}), node.get("register")] + names += [name for module in playbook_yaml.SET_FACT for name in node.get(module) or {}] + found |= {(node.get("name"), name) for name in names if str(name).startswith("mail_captured_")} + expected = {"mail_captured_api_url", "mail_captured_recipient", "mail_captured_subject", "mail_captured_since"} + assert found == {(CATCHER, name) for name in expected} + + +def test_the_local_worker_joins_the_local_dev_network_for_the_catcher(): + compose = yaml.safe_load(COMPOSE_LOCAL.read_text()) + assert "local-dev" in compose["services"]["worker"]["networks"] diff --git a/platform/tests/test_service_plane.bats b/platform/tests/test_service_plane.bats index 338410918..92ede9e0a 100644 --- a/platform/tests/test_service_plane.bats +++ b/platform/tests/test_service_plane.bats @@ -222,7 +222,7 @@ PY grep -qF 'PLANE_OIDC_CLIENT_SECRET={{ secrets.plane_oidc_client_secret }}' "$ak/templates/env.j2" # Plane shared-reads it (never stores a copy) and converges its instance settings with it. # Read only when OIDC is configured, so a host without it never depends on Deploy Authentik. - grep -qF "if plane_authentik_base is defined else [] }}" "$PLAYBOOK" + grep -qF "if plane_authentik_base is defined else [])" "$PLAYBOOK" # Unset is the kill switch: OIDC is switched off, not left as it was. grep -qF "{'IS_OIDC_ENABLED': '0'} if plane_authentik_base is not defined" "$PLAYBOOK" grep -qF "'OIDC_CLIENT_SECRET': _shared.plane_oidc_client_secret" "$PLAYBOOK"