From 26be67f4cdafb3fef8bdbd9e4cd00be2e5697242 Mon Sep 17 00:00:00 2001 From: Justin Klein Date: Fri, 2 Oct 2026 19:13:49 +0000 Subject: [PATCH 1/2] feat(stalwart): new chart for the Stalwart mail server Cluster-capable from the start, with roles rather than symmetry: one StatefulSet per entry of the "nodes" map, the key passed in STALWART_ROLE. Since v0.16 Stalwart keeps its whole configuration inside the data store and manages it over JMAP, so the chart's scope is deliberately narrow: it renders config.json (exactly the DataStore object), the workloads, the Services, the NetworkPolicies, the Ingress and a cert-manager Certificate. Listeners, blob store, in-memory store, TLS object and cluster roles are operator work in the WebUI, which is why NOTES.txt carries an eight-step first install. config.json stays secret-free: authSecret uses the EnvironmentVariable variant (verified against the serde definition of PostgreSqlStore at v0.16.24), so the password arrives through secretKeyRef and checksum/config stays meaningful. The username cannot follow it - authUsername is a plain String with no secret form - so it is a public value and says so. Services are per PORT, not per group: a NodePort is cluster-unique, so "full" and "mx" can only accept SMTP behind one Service, selected through a per-port pod label. The http port gets a per-group ClusterIP Service instead, so the Ingress reaches exactly ingress.nodeGroup. Four traps, documented rather than explained away: - The role lookup FAILS OPEN. A node whose ClusterRole is missing from the database enables every listener and every task while staying Running with a green probe, and the log line arrives after the listeners are bound. Hence mx at replicas 0, per-port Services, and a NetworkPolicy that is a ceiling independent of what was bound. - NET_BIND_SERVICE is a documented deviation needed to EXEC, not to bind. The image sets setcap cap_net_bind_service=+ep, which makes the kernel fail execve when the bounding set is empty. The values comment says both why it is there and that it is never used, because the second half is what stops the next hardening pass from removing it. - externalTrafficPolicy must be Cluster - no pod runs on a control-plane node while the HA proxy delivers to them, so Local would drop every packet - and the source address that costs is restored only by the HA proxy's PROXY v2 header. - /healthz is rate-limited to 100 requests/60s per source IP, which is a node IP for kubelet probes, so all pods on a node share one bucket. The probe intervals are calculated (6 req/min/pod, ~16 pods per node) and the sum is a comment in values.yaml. A first install needs bootstrap.enabled: true: the setup wizard appears only when config.json is ABSENT, and this chart always renders one, so recovery mode is upstream's documented path for a templated config.json. Second chart in the repo with a dependency - the Valkey project's own chart, off by default behind condition:, because Stalwart's cluster coordinator rides on the in-memory store connection. The render aborts when more than one pod runs with no in-memory store address anywhere. Also wired up: publish-stalwart.yml through the shared block in workflow-util/pipelines, the change-app-version.yml choice list, a Renovate customManagers block anchored on the v prefix (which excludes the moving latest / v0.16 / -alpine tags), CI fixtures, and the README and CLAUDE.md lines that claimed ytdlp-web-player was the only chart with a dependency. Verified locally: ci/helm-dependencies.sh, helm lint --strict (0 failed), helm package, helm template against chart defaults and against ci/stalwart/test-values.yaml, the rendered config.json parsed as JSON with the field types the serde definition requires, ci/run-quantity-render-test.sh (0 failed, both nodes.*.resources paths exercised), NOTES.txt rendered through a scratch ConfigMap, and the null-safety and fail paths (securityContext=null keeps NET_BIND_SERVICE; a cluster without an in-memory store, an unknown port name, a group without http and an unknown ingress.nodeGroup all abort with a named message; the schema rejects timeout, a string timeoutMs and a list-shaped nodes). NO runtime verification was possible - there is no k3d or Docker daemon in this workspace. Part of #65 --- .github/workflows/change-app-version.yml | 1 + .github/workflows/publish-stalwart.yml | 16 + CLAUDE.md | 2 +- README.md | 9 +- ci/stalwart/fixtures.yaml | 104 +++ ci/stalwart/test-values.yaml | 123 ++++ renovate.json5 | 30 + stalwart/Chart.yaml | 76 ++ stalwart/templates/NOTES.txt | 270 +++++++ stalwart/templates/_helpers.tpl | 428 +++++++++++ stalwart/templates/stalwart.certificate.yaml | 56 ++ stalwart/templates/stalwart.configmap.yaml | 52 ++ stalwart/templates/stalwart.ingress.yaml | 65 ++ .../templates/stalwart.networkpolicy.yaml | 136 ++++ stalwart/templates/stalwart.secret.yaml | 75 ++ stalwart/templates/stalwart.service.yaml | 123 ++++ stalwart/templates/stalwart.sfs.yaml | 266 +++++++ stalwart/values.schema.json | 502 +++++++++++++ stalwart/values.yaml | 676 ++++++++++++++++++ 19 files changed, 3007 insertions(+), 3 deletions(-) create mode 100644 .github/workflows/publish-stalwart.yml create mode 100644 ci/stalwart/fixtures.yaml create mode 100644 ci/stalwart/test-values.yaml create mode 100644 stalwart/Chart.yaml create mode 100644 stalwart/templates/NOTES.txt create mode 100644 stalwart/templates/_helpers.tpl create mode 100644 stalwart/templates/stalwart.certificate.yaml create mode 100644 stalwart/templates/stalwart.configmap.yaml create mode 100644 stalwart/templates/stalwart.ingress.yaml create mode 100644 stalwart/templates/stalwart.networkpolicy.yaml create mode 100644 stalwart/templates/stalwart.secret.yaml create mode 100644 stalwart/templates/stalwart.service.yaml create mode 100644 stalwart/templates/stalwart.sfs.yaml create mode 100644 stalwart/values.schema.json create mode 100644 stalwart/values.yaml diff --git a/.github/workflows/change-app-version.yml b/.github/workflows/change-app-version.yml index 09c0dd2..bc427d2 100644 --- a/.github/workflows/change-app-version.yml +++ b/.github/workflows/change-app-version.yml @@ -40,6 +40,7 @@ on: - ytdlp-web-player - sure - valkey + - stalwart # freesailarr is deliberately absent: none of its ten images takes # its tag from appVersion (they are all pinned in its values.yaml), # so this workflow would rewrite appVersion and republish the chart diff --git a/.github/workflows/publish-stalwart.yml b/.github/workflows/publish-stalwart.yml new file mode 100644 index 0000000..91923d1 --- /dev/null +++ b/.github/workflows/publish-stalwart.yml @@ -0,0 +1,16 @@ +name: Publish Stalwart Helm Chart +on: + workflow_dispatch: + push: + branches: + - main + paths: + - stalwart/** +jobs: + publish-stalwart: + name: Publish Stalwart Helm Chart + uses: workflow-util/pipelines/.gitea/workflows/publish-helm-chart.yml@v3 + with: + chart-name: 'stalwart' + registry-owner: ${{ github.repository_owner }} + secrets: inherit diff --git a/CLAUDE.md b/CLAUDE.md index e588c4b..8e25770 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -117,4 +117,4 @@ The binding style guide for all current and future charts lives in **README.md ( - Resources: requests as values defaults; limits auto-computed by the `_helpers.tpl` helper (`limitFactor` default 3; no CPU limits unless set explicitly). - Replicas per workload (explicit `0` allowed) plus a chart-global `scaleDown` flag that overrides them. - `icon:` mandatory in every `Chart.yaml`; `helm lint --strict` without findings; CI fixtures under `ci//` or a justified exclusion. -- **Chart dependencies are admissible but expensive** (the former "no dependencies" rule fell with #214; `ytdlp-web-player` is the only chart using one). A dependency has to be optional and off by default via `condition:`, and upstream's chart is consumed as it comes — where its defaults fall short of these conventions, that is **documented in our `values.yaml`, never patched**. The price to know before adding the next one: a subchart is invisible to everything downstream that watches Helm release versions, so a new upstream version — a security fix included — reaches a cluster only when the outer chart is republished (Renovate's built-in `helmv3` manager plus `ci/renovate-bump-chart.sh` is the whole safety net, and it belongs in a comment at the pinned version); and every helm command exits 1 while `charts/` is unfilled, which is why `ci/helm-dependencies.sh` runs before lint, package, render and install — including the render test that covers **all** charts on **every** PR. Full rules and the rest of the cost: README, "Chart dependencies". +- **Chart dependencies are admissible but expensive** (the former "no dependencies" rule fell with #214; `ytdlp-web-player` was the first to use one, `stalwart` the second). A dependency has to be optional and off by default via `condition:`, and upstream's chart is consumed as it comes — where its defaults fall short of these conventions, that is **documented in our `values.yaml`, never patched**. The price to know before adding the next one: a subchart is invisible to everything downstream that watches Helm release versions, so a new upstream version — a security fix included — reaches a cluster only when the outer chart is republished (Renovate's built-in `helmv3` manager plus `ci/renovate-bump-chart.sh` is the whole safety net, and it belongs in a comment at the pinned version); and every helm command exits 1 while `charts/` is unfilled, which is why `ci/helm-dependencies.sh` runs before lint, package, render and install — including the render test that covers **all** charts on **every** PR. Full rules and the rest of the cost: README, "Chart dependencies". diff --git a/README.md b/README.md index efa863e..56e39fa 100644 --- a/README.md +++ b/README.md @@ -32,13 +32,14 @@ Every chart has a wiki page of its own — `https://git.jk-dev.de/jlab-cluster/h | `samba` | Samba | StatefulSet, users secret + config ConfigMap | | `satisfactory` | Satisfactory game server | StatefulSet, no ingress | | `searxng` | SearXNG | Stateless Deployment + settings ConfigMap (`use_default_settings: true` plus a free-form `settings.extra` passthrough); the signing key is a required `OnePasswordItem`, an external Valkey an optional second one. `ingress.domain` is read twice — Ingress host and `SEARXNG_BASE_URL` — so it stays required with the Ingress switched off | +| `stalwart` | Stalwart mail server (SMTP, IMAP, POP3, JMAP, ManageSieve) | **The chart configures almost nothing, and that is the chart's defining property.** Since v0.16 Stalwart keeps its whole configuration — every listener, the blob store, the in-memory store, TLS objects, domains and the cluster roles — inside the data store and manages it over JMAP; the only file on disk is a `config.json` that names the data store and nothing else. So the chart renders that ConfigMap (secret-free: `authSecret` uses the `EnvironmentVariable` variant, so the password arrives by `secretKeyRef` and `checksum/config` stays meaningful), one StatefulSet per entry of the `nodes` **map** with `STALWART_ROLE` and `STALWART_HOSTNAME`, one NodePort Service **per port** (not per group — a NodePort is cluster-unique, so `full` and `mx` can only take SMTP behind the same Service, selected by a per-port pod label), a per-group ClusterIP `http` Service for the Ingress, per-group headless Services and NetworkPolicies, and a cert-manager `Certificate` for the mail ports. Everything else is operator work in the WebUI, which is why `NOTES.txt` carries an eight-step first install. Four traps worth knowing before reading the chart: **the role lookup fails open** — a node whose `ClusterRole` is missing from the database enables every listener *and* every task while staying Running with a green probe, so `mx` ships at `replicas: 0` and the NetworkPolicy is a ceiling independent of what was bound; **`NET_BIND_SERVICE` is a documented deviation needed to `exec`, not to bind** (the image sets `setcap cap_net_bind_service=+ep`, so `drop: [ALL]` alone makes the kernel fail `execve` — removing it as "unused" stops the chart starting); **`externalTrafficPolicy` must be `Cluster`** (no pod runs on a control-plane node while the HA proxy delivers to them, so `Local` would drop every packet) and the source address it costs is restored only by the HA proxy's PROXY v2 header; and **`/healthz` is rate-limited to 100 req/60s per source IP**, which is a node IP for kubelet probes, so the probe intervals are calculated rather than chosen. A first install needs `bootstrap.enabled: true` because the setup wizard appears only when `config.json` is *absent*. Optional `valkey` subchart (the Valkey project's own chart), off by default | | `sure` | Sure (we-promise, the maintained Maybe-finance fork) | One StatefulSet with **two containers**: the Puma web process and a Sidekiq worker, sharing one ReadWriteOnce PVC at `/rails/storage` — that shared volume is the reason they live in one pod. Only the web container migrates (the image entrypoint runs `db:prepare` solely for the `./bin/rails server` command, so the worker is started through `args:` and skips it). Three 1Password items (app/database/redis); Postgres and Redis stay external. Readiness deliberately probes `/` rather than Rails' `/up`, which is a boot check and touches no database; the worker's three probes ask `sidekiqmon` for this pod's own heartbeat. `ingress.domain` is read for `APP_DOMAIN` and the WebAuthn relying party, so it stays required with the Ingress switched off | | `teamspeak-server` | TeamSpeak server | StatefulSet, no ingress | | `template-chart` | — | Scaffold for new charts (placeholder `xxx`), never published | | `urlaubsverwaltung` | Urlaubsverwaltung | Deployment, DB + OIDC secrets | | `valkey` | Valkey | One instance per application (cache or queue backend), replacing the shared `cluster-redis` whose single ACL file coupled six applications together. StatefulSet with one replica + ClusterIP Service, no cluster mode, no Ingress and no value to add one. The password arrives as a **finished configuration line** (`requirepass `) in the 1Password field `auth-conf`, is mounted as a file and `include`d by the config — never in argv, never in the environment; an init container refuses to start the pod unless that line is really there, because the alternative failure is an open server that looks healthy. `maxmemory` is **derived from the computed memory limit** and a configured value above it aborts the render. Persistence and eviction are a pair, not two switches (queue = PVC + `noeviction`, the default; cache = emptyDir + `allkeys-lru`). First chart carrying a **NetworkPolicy** (on by default, Gitea #5), and the first whose probes had to be proven capable of failing: `valkey-cli` exits 0 on an error reply unless `-e` is given | | `voucher-vault` | VoucherVault | StatefulSet, DB + OIDC secrets | -| `ytdlp-web-player` | ytdlp_web_player | Stateless Deployment, video cache and tool cache as emptyDirs (no PVC). **The only chart with a dependency**: an optional `oauth2-proxy` subchart, off by default, wired in front of the app because the application ships no authentication at all — see "Chart dependencies" below | +| `ytdlp-web-player` | ytdlp_web_player | Stateless Deployment, video cache and tool cache as emptyDirs (no PVC). **The first chart with a dependency** (`stalwart` is the second): an optional `oauth2-proxy` subchart, off by default, wired in front of the app because the application ships no authentication at all — see "Chart dependencies" below | | `zipline` | Zipline | StatefulSet, DB secret | ## Versioning @@ -408,7 +409,9 @@ Reference implementation: `template-chart/values.schema.json` and `template-char The other half of the same rule: readiness **must** hang on the dependency, and a separate path is not proof that it does. `urlaubsverwaltung` probed `/actuator/health/liveness` and `/actuator/health/readiness` for two years and still stayed 1/1 Ready through a total database outage (#218), because Spring Boot's `readiness` group contains `readinessState` **alone** — the split paths were right, the group content was empty of anything external. Whatever aggregates behind a probe path (Spring health groups, a `/healthz` a framework assembles for you) has to be read off the **running** endpoint, not off the path name; the chart names the members explicitly (`MANAGEMENT_ENDPOINT_HEALTH_GROUP_READINESS_INCLUDE=readinessState,db`) so the composition is in the template rather than in an upstream default. -**4. A fallback reproduces *this chart's* defaults, not the repo standard.** Five charts deviate from the hardening baseline on purpose. A "cleaned up" standard default is not tidying, it is an outage: `calibre-web-automated` must keep `readOnlyRootFilesystem: false`, because in read-only mode the image disables its PUID/PGID remapping and the runtime uid silently moves from 1000 to 911 — **making existing volume data inaccessible**. The same applies to non-standard values that look like mistakes: `satisfactory` keeps `limitFactor: 2` (that is what holds the memory limit at the published 8Gi) and `fsGroupChangePolicy: OnRootMismatch` (which avoids a recursive chown of multi-GB game files on every start). +**4. A fallback reproduces *this chart's* defaults, not the repo standard.** Several charts deviate from the hardening baseline on purpose (no count here — the previous wording named one and went stale the next time a chart landed). A "cleaned up" standard default is not tidying, it is an outage: `calibre-web-automated` must keep `readOnlyRootFilesystem: false`, because in read-only mode the image disables its PUID/PGID remapping and the runtime uid silently moves from 1000 to 911 — **making existing volume data inaccessible**. The same applies to non-standard values that look like mistakes: `satisfactory` keeps `limitFactor: 2` (that is what holds the memory limit at the published 8Gi) and `fsGroupChangePolicy: OnRootMismatch` (which avoids a recursive chown of multi-GB game files on every start). + + **The sharpest case is a capability that is granted and never used.** `stalwart`'s fallback has to carry `capabilities.add: [NET_BIND_SERVICE]`, because the image sets `setcap cap_net_bind_service=+ep` on its binary — which makes it a capability-dumb binary, and `capabilities(7)` then has the kernel fail the **`execve` itself** when the bounding set does not carry the capability: *"If the process did not obtain the full set of file permitted capabilities, then `execve(2)` fails with the error `EPERM`."* So `drop: [ALL]` with the standard empty `add` does not produce an unhardened container, it produces `exec /usr/local/bin/stalwart: operation not permitted` and a chart that cannot start. The capability is then spent entirely on the exec check and is never used to bind anything, which is exactly what makes it a magnet for a hardening pass looking for dead grants. This is why a deviation is documented with its **mechanism** and not only its name: "needed for binding" would have been wrong and would have invited the removal. **5. A probe default carries the probe's context, not just its timings.** Two different symptoms, both from real charts: `teamspeak-server` addresses its TCP port by the name `file-transfer` because the voice service is UDP and cannot be probed — a default without that name leaves the workload **with no working probe at all**. `patchmon` sends a `Host` header because the server answers **403** to any request whose Host is neither loopback nor a CORS_ORIGIN host — a default without it means the pod never becomes Ready. Port names, `Host` headers and `exec` commands belong in the fallback; where the context is dynamic, pass the root context in and rebuild it (patchmon derives the header from `ingress.domain`). @@ -435,6 +438,8 @@ Reference implementation: `template-chart/values.schema.json` and `template-char Until `ytdlp-web-player` (#214) this section read "charts have no dependencies (`charts/` directories are empty)". That rule is gone, replaced by a bar rather than a ban — a dependency is **admissible, not free**, and the reason it stopped being a ban is worth keeping: the chart needed an oauth2-proxy in the data path in front of an application that ships no authentication at all, and proxy and app are only useful wired to each other. +Two charts carry one, and comparing them is the quickest way to see where the bar sits. `ytdlp-web-player` takes `oauth2-proxy` because the app has no authentication and the two are useless apart. `stalwart` (Gitea #65) takes the Valkey project's own chart because Stalwart's **cluster coordinator rides on the in-memory store connection**, so a multi-node install does not work without one — and because this repo also publishes a `valkey` chart of its own, the subchart is the convenience path rather than the expected one: `externalServices.valkey.host` points at an existing instance and then the dependency renders nothing. Both are `condition:`-gated and off by default, and in both cases upstream's shortfalls against the guidelines above (`stalwart`: `auth.enabled: false`, and a NetworkPolicy with upstream's own semantics that our `networkPolicy` block does not reach) are **documented in our `values.yaml` rather than patched**. + **When a dependency earns its place.** All three, not two of three: 1. The dependent piece would otherwise be a second Helm release that only exists to serve this one, with the wiring between them living in neither chart. diff --git a/ci/stalwart/fixtures.yaml b/ci/stalwart/fixtures.yaml new file mode 100644 index 0000000..bd48f0f --- /dev/null +++ b/ci/stalwart/fixtures.yaml @@ -0,0 +1,104 @@ +# Fixtures for the stalwart install-test: a throwaway Postgres, the one Secret +# the 1Password operator would otherwise materialize, and a stub CRD for +# cert-manager's Certificate (release name: ci; the OnePasswordItem stub CRD +# comes from ci/common/). +# +# NO VALKEY HERE, DELIBERATELY. The in-memory store is an object in Stalwart's +# DATABASE, not a chart value, so a Valkey in this namespace would be reachable +# and unused - it would make the test look like it covered the clustering path +# while covering nothing of it. The test runs a single node (nodes.full +# replicas 1, nodes.mx replicas 0), which is the configuration that needs no +# in-memory store at all. The subchart path is covered by a local render only, +# named as a known gap in the PR that introduced this chart. +# +# A stub CRD for Certificate rather than certificate.enabled: false, because +# switching the Certificate off would also drop the volume and volumeMount that +# carry it - and the mount is on the risky side of readOnlyRootFilesystem. With +# the stub the object applies, the Secret it names never appears, and the +# optional: true on the volume is exercised for real: the pods must start +# without it. That is the behaviour an operator meets on every first install, +# before cert-manager has answered the challenge. +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: certificates.cert-manager.io +spec: + group: cert-manager.io + names: + kind: Certificate + listKind: CertificateList + plural: certificates + singular: certificate + scope: Namespaced + versions: + - name: v1 + served: true + storage: true + schema: + openAPIV3Schema: + type: object + x-kubernetes-preserve-unknown-fields: true +--- +apiVersion: v1 +kind: Secret +metadata: + name: ci-stalwart-datastore-secret +stringData: + # The ONLY field this chart reads from the data store item. config.json + # references it by variable name through + # "authSecret": {"@type":"EnvironmentVariable","variableName":"STALWART_DB_PASSWORD"} + # so this value has to match the throwaway Postgres below. A real password + # rather than an empty string on purpose: upstream's resolver treats an empty + # environment variable as "not found" and fails the store open, so an empty + # value here would fail the run for the right reason in the wrong place. + password: ci-stalwart-throwaway-password +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: postgres + labels: + app: postgres +spec: + replicas: 1 + selector: + matchLabels: + app: postgres + template: + metadata: + labels: + app: postgres + spec: + containers: + - name: postgres + image: public.ecr.aws/docker/library/postgres:16-alpine + env: + - name: POSTGRES_USER + value: stalwart + - name: POSTGRES_PASSWORD + value: ci-stalwart-throwaway-password + - name: POSTGRES_DB + value: stalwart + ports: + - containerPort: 5432 + readinessProbe: + exec: + command: ["pg_isready", "-U", "stalwart"] + periodSeconds: 5 + volumeMounts: + - name: data + mountPath: /var/lib/postgresql/data + volumes: + - name: data + emptyDir: {} +--- +apiVersion: v1 +kind: Service +metadata: + name: postgres +spec: + selector: + app: postgres + ports: + - port: 5432 + targetPort: 5432 diff --git a/ci/stalwart/test-values.yaml b/ci/stalwart/test-values.yaml new file mode 100644 index 0000000..fc2e166 --- /dev/null +++ b/ci/stalwart/test-values.yaml @@ -0,0 +1,123 @@ +# CI values for the stalwart install-test. +# +# WHAT THIS TEST CAN AND CANNOT PROVE — read this before trusting a green run. +# +# It CANNOT prove a working mail server, and no install-test here could. Since +# v0.16 every listener, the blob store, the in-memory store, the TLS object and +# the cluster roles live in Stalwart's DATABASE and are created by a human in +# the WebUI. Against an empty database there is no SMTP service to test, so a +# green run says nothing about mail. +# +# What it DOES prove is the part that is the chart's own responsibility, and the +# first item is the reason this chart is tested rather than excluded: +# +# 1. THE CONTAINER EXECS AT ALL. The image carries +# "setcap cap_net_bind_service=+ep" on its binary, which makes the kernel +# fail execve itself when the capability is not in the bounding set. The +# first draft of this chart had capabilities.drop: [ALL] with nothing +# added and would have failed with "operation not permitted" in every +# install - caught by reading the Dockerfile, but exactly the class of +# failure an install-test exists to catch rather than reason about. +# 2. readOnlyRootFilesystem: true holds with the two image volumes plus /tmp +# as emptyDirs, and the init container really can write config.json into +# the /etc/stalwart emptyDir. +# 3. The rendered config.json parses AS STALWART READS IT, not just as JSON: +# the server opens the data store, which means "@type": "PostgreSql", the +# integer-millisecond timeout and the authSecret EnvironmentVariable +# indirection are all accepted. This is the one check that the password +# really arrives without ever being in the ConfigMap. +# 4. The Secret key names match what the templates reference, the ConfigMap +# mount works, the NodePorts can be allocated, the resource quantities are +# valid, the schema accepts a realistic (non-default) values file, and the +# NetworkPolicy objects are accepted without cutting off the probes. +# +# RECOVERY MODE IS ON, and that is not a shortcut - it is the only mode that can +# work here. The bootstrap wizard appears only when config.json is ABSENT, and +# this chart always renders one; upstream's documented path for a templated +# config.json is to start once with STALWART_RECOVERY_MODE=1. Recovery mode +# brings up the management HTTP endpoint and keeps the mail ports closed, which +# is precisely the reachable surface the probes use. +# +# THE ONE THING THIS FILE COULD NOT BE VERIFIED AGAINST: whether /healthz/live +# and /healthz/ready are served on the RECOVERY listener. The source shows them +# handled in the general HTTP request path with no auth and no network +# restriction, but recovery mode binds a single listener and skips most config +# parsing, and there is no cluster in the authoring environment to try it on. +# If the install-test goes red with the pods never becoming Ready, that is the +# reason, and the fix is either an exec probe or an entry in +# ci/excluded-charts.txt - see the PR for #65. +bootstrap: + enabled: true + logLevel: debug + +dataStore: + postgres: + host: postgres + database: stalwart + username: stalwart + tls: + # OFF, against the chart's own default of true. The throwaway Postgres in + # fixtures.yaml serves no TLS, and the alternative - allowInvalidCerts - + # would be worse: it would pass whether or not TLS worked, so a chart + # change that broke the TLS path would still go green. A deviation that + # fails loudly beats one that hides. + enable: false + allowInvalidCerts: false + +secrets: + # Materialized by ci/stalwart/fixtures.yaml as ci-stalwart-datastore-secret. + dataStoreSecretRef: op://ci/stalwart-datastore + # Both deliberately unset: neither is needed to bring a pod up, and leaving + # them out exercises the conditional env and OnePasswordItem blocks in the + # "absent" direction, which is the shape a minimal install really has. + recoveryAdminSecretRef: null + s3SecretRef: null + +ingress: + # Left ON although no ingress controller answers in CI: the point is that the + # object is accepted and that the per-group http Service it names actually + # exists - a selector typo there is otherwise invisible until someone opens + # the URL. + enabled: true + domain: stalwart.ci.example.com + clusterIssuer: ci-selfsigned + nodeGroup: full + +certificate: + # On, against a STUB CRD (fixtures.yaml). Nothing issues the Secret it names, + # which is the interesting case: the volume is mounted optional, so the pods + # must start without it. That is what every real first install looks like + # before cert-manager has answered the challenge. + enabled: true + clusterIssuer: ci-selfsigned + +networkPolicy: + # Left ON. probeSources stays empty, so the http rule renders without a + # "from" selector - the configuration this chart ships. Whether the policy + # actually FILTERS is a property of the cluster's CNI and is not claimed by + # this test; what is claimed is that the objects are accepted and that they + # do not keep the kubelet's probes from working. + enabled: true + +nodes: + full: + replicas: 1 + exposedPorts: [smtp, submissions, imaps, http] + resources: + # Small, to stay inside the runner's budget, while still exercising the + # limit derivation: 256Mi x limitFactor 3 = 768Mi. + requests: + cpu: 100m + memory: 256Mi + ephemeral-storage: 64Mi + mx: + # Stays at 0, which is also the chart default. Two reasons rather than one: + # a second node would need an in-memory store (the render aborts without + # one), and the "mx" ClusterRole does not exist in an empty database, so a + # running mx pod would fail-open into a second full node and the two would + # fight over the same NodePort-backed SMTP Service. The StatefulSet is + # still created and the harness still waits on it - a 0-replica rollout + # completes immediately, so this covers the explicit-zero path of the + # replicas helper. + replicas: 0 + exposedPorts: [smtp, http] diff --git a/renovate.json5 b/renovate.json5 index b831595..655ddbd 100644 --- a/renovate.json5 +++ b/renovate.json5 @@ -485,6 +485,36 @@ datasourceTemplate: "docker", depTypeTemplate: "app-version", }, + { + description: [ + "stalwart: the registry carries three kinds of tag - versioned ones (v0.16.24), the", + "same versions with an -alpine suffix (v0.16.24-alpine), and three MOVING names:", + "'latest', 'latest-alpine' and the truncated line tags 'v0.16' / 'v0.16-alpine'.", + "Measured on 2026-10-02: 'latest', 'v0.16' and 'v0.16.24' all resolve to the same", + "digest (sha256:ec011be2285...), pushed within seconds of each other - so 'latest'", + "and 'v0.16' pin nothing and would move the running image with no commit here.", + "", + "The anchored regex below is what keeps all five out, and it does so for two", + "independent reasons rather than one: the v prefix plus THREE numeric parts rejects", + "'latest' and 'latest-alpine' (no numbers) and 'v0.16' / 'v0.16-alpine' (two parts),", + "and the terminating anchor rejects the -alpine suffix. Choosing the glibc image over", + "the alpine one is a deployment decision and belongs in the chart, not in a", + "compatibility suffix Renovate would then have to maintain - contrast the valkey", + "block below, where '-alpine' IS the chosen flavour and docker versioning carries it.", + "", + "The 'v' stays outside every capture group, as in the ytdlp-web-player block: it is", + "part of the tag and carries no ordering, and a group is a claim about how the value", + "is compared. It is part of the tag, so it is part of appVersion (+upv0.16.24) -", + "precedent: calibre-web-automated, matrix-synapse, ytdlp-web-player.", + ], + customType: "regex", + managerFilePatterns: ["stalwart/Chart.yaml"], + matchStrings: ["(?m)^appVersion:\\s*\"?(?[^\"\\s]+)\"?"], + depNameTemplate: "docker.io/stalwartlabs/stalwart", + datasourceTemplate: "docker", + depTypeTemplate: "app-version", + versioningTemplate: "regex:^v(?\\d+)\\.(?\\d+)\\.(?\\d+)$", + }, { description: [ "sure: the registry carries four kinds of tag side by side - releases (0.7.4), the", diff --git a/stalwart/Chart.yaml b/stalwart/Chart.yaml new file mode 100644 index 0000000..bd9b987 --- /dev/null +++ b/stalwart/Chart.yaml @@ -0,0 +1,76 @@ +apiVersion: v2 +name: stalwart +description: A Helm chart to deploy a cluster-capable Stalwart mail server (SMTP, IMAP, JMAP, ManageSieve) on Kubernetes +icon: https://avatars.githubusercontent.com/u/76623657 + +type: application + +# appVersion is the exact image tag, and the "v" is part of it - so it is part +# of appVersion and of the "+up" suffix. Precedent: calibre-web-automated +# (+upv4.0.6), matrix-synapse (+upv1.159.0), ytdlp-web-player (+upv1.2.0). +# +# The glibc image, not "-alpine". Both flavours are published for every release +# from the same source and carry the same uid/gid 2000 and the same two volumes; +# the choice is a deployment decision, and keeping it out of the tag is what +# lets renovate.json5 anchor the version with a plain three-part regex instead +# of maintaining a compatibility suffix. The moving tags "latest", "v0.16" and +# their -alpine twins are excluded by that same anchor: measured on 2026-10-02 +# all three of latest / v0.16 / v0.16.24 resolved to one digest pushed seconds +# apart, so either floating name would change the running image with no commit +# in this repository and nothing to report it. +version: 1.0.0+upv0.16.24 +appVersion: "v0.16.24" + +maintainers: + - name: jklein + +# The second chart in this repo with a dependency (after ytdlp-web-player). +# README, "Chart dependencies", holds the bar it has to clear and the price; +# both are restated here because the price is paid by whoever reads this file +# next, not by whoever added the line. +# +# WHY ONE HERE. Stalwart's in-memory store is not a cache that can be dropped: +# from v0.16 it also carries the cluster coordinator ("the Default variant +# reuses the Redis connection already configured on the in-memory store"), so a +# multi-node install does not work without it. Redis/Valkey is admissible as +# the in-memory store ONLY - never as the data or blob store. Offering it inside +# the chart means the wiring (host, port, egress rule) is in one place instead +# of split across two releases that have to agree. +# +# WHY IT IS OFF BY DEFAULT, and why that is more than convention here: most +# installations already run a Valkey, and this repo publishes a valkey chart of +# its own that is the better choice when one application owns the instance. +# Point externalServices.valkey at it and this dependency renders nothing. +# +# UPSTREAM'S CHART IS CONSUMED AS IT COMES (guideline 14.2). Two of its defaults +# fall short of this repo's conventions and are deliberately NOT patched here; +# they are documented in our values.yaml under "valkey:" instead, where the +# values-level fix stays available to whoever installs the chart. +dependencies: + - name: valkey + # KEEP THIS VERSION MOVING - it is the only path a Valkey update has. + # + # A subchart is invisible to everything downstream that watches Helm release + # versions: what this file declares is baked into our packaged .tgz, and + # Fleet only ever sees the version of "stalwart". So a new valkey chart - a + # security fix included - reaches a cluster ONLY when this line is raised + # and a new stalwart version is published. Nothing reports the gap. + # + # Renovate's BUILT-IN helmv3 manager reads this block and opens the PR (no + # customManagers entry exists or would help - repository and version sit + # together in one file, which is the case that manager is for), and + # ci/renovate-bump-chart.sh bumps this chart's patch version, which is what + # actually ships it. That chain is the whole safety net; switched off, this + # line needs a human on a calendar instead. + # + # Independent of appVersion: raising it is a patch or minor bump of this + # chart and is never tied to the Stalwart image. + version: "0.12.0" + # The Valkey project's own chart, so upstream owns the schema - not a + # re-packaging. Note the repository is the plain HTTP index, not OCI. + repository: "https://valkey.io/valkey-helm" + # Off by default, so a plain install renders none of its objects. Helm + # splits a condition on dots only; this name carries no dash, so unlike + # ytdlp-web-player's oauth2-proxy it is also reachable as .Values.valkey.* + # inside templates without index. + condition: valkey.enabled diff --git a/stalwart/templates/NOTES.txt b/stalwart/templates/NOTES.txt new file mode 100644 index 0000000..4b2b63b --- /dev/null +++ b/stalwart/templates/NOTES.txt @@ -0,0 +1,270 @@ +{{- $release := include "stalwart.fullname" . -}} +{{- $nodes := fromYaml (include "stalwart.nodes" .) -}} +{{- $ports := fromYaml (include "stalwart.ports" .) -}} +{{- $valkeyHost := include "stalwart.valkeyHost" . -}} +{{- $ingressGroup := "" -}} +{{- if .Values.ingress.enabled }}{{- $ingressGroup = include "stalwart.ingressNodeGroup" . }}{{- end -}} +Stalwart {{ .Chart.AppVersion }} — release {{ .Release.Name }} in namespace {{ .Release.Namespace }}. + +THIS CHART CONFIGURES ALMOST NOTHING, AND THAT IS NOT A GAP + Since v0.16 Stalwart keeps its whole configuration inside the data store and + manages it over JMAP. The only file on disk is config.json, which names the + data store and nothing else. So this release has given you the workloads, the + Services, the NetworkPolicies, the Ingress and a certificate — but no + domains, no listeners, no blob store, no in-memory store and no cluster + roles. Those are the steps below, and without them this is not yet a mail + server. + +NODE GROUPS IN THIS RELEASE +{{- range $group, $spec := $nodes }} +{{- $replicas := include "stalwart.replicas" (dict "scaleDown" $.Values.scaleDown "replicas" $spec.replicas) }} + {{ printf "%-10s" $group }} replicas {{ $replicas }}, reachable on: {{ $spec.exposedPorts | join ", " }} +{{- end }} +{{- if .Values.scaleDown }} + + scaleDown: true — every group is at replicas 0 and nothing is running. The + Services, Ingress, Secrets and the Certificate stay in place, so setting it + back to false brings the release up without re-issuing the certificate. +{{- end }} +{{- if .Values.bootstrap.enabled }} + +!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +RECOVERY MODE IS ON — THIS RELEASE SERVES NO MAIL +!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + bootstrap.enabled is true, so every pod runs with STALWART_RECOVERY_MODE=1: + the management HTTP endpoint on {{ (index $ports "http").containerPort }} is the ONLY thing listening and + every mail port is closed. The Services and the Ingress look exactly as + healthy as they do in normal operation, which is why this banner exists. + + This is correct for a first install (step 1 below). When the database is + provisioned, set bootstrap.enabled: false and upgrade again. +{{- end }} + +THE 1PASSWORD ITEMS MUST CARRY THE FIELDS THIS CHART READS + One Secret key is created per FIELD of the item, and these templates + reference the keys by name — an item missing a field leaves the container in + CreateContainerConfigError. An EMPTY field fails the same way as a missing + one: Stalwart's secret resolver treats an empty environment variable as "not + found". +{{- if .Values.secrets.dataStoreSecretRef }} + + secrets.dataStoreSecretRef → {{ .Values.secrets.dataStoreSecretRef }} + field: password (the data store password) + The USERNAME is not in this item and cannot be: authUsername is a plain + String on the DataStore object with no secret form. It is + dataStore.postgres.username = "{{ .Values.dataStore.postgres.username }}" and is rendered into the + ConfigMap. +{{- else }} + + secrets.dataStoreSecretRef is NOT SET, so no data store password reaches the + pods and config.json references an environment variable that will not exist. + Stalwart fails to open the store with + Environment variable '{{ include "stalwart.env.dbPassword" . }}' not found + Set it unless the database genuinely takes no password. +{{- end }} +{{- if .Values.secrets.recoveryAdminSecretRef }} + + secrets.recoveryAdminSecretRef → {{ .Values.secrets.recoveryAdminSecretRef }} + field: recovery-admin (the COMPLETE value "admin:") + One field, not two. The upstream parser splits on the first ":" and drops + the entry when either half is empty, so a half-filled item would silently + mean "no recovery admin" instead of failing — and this credential logs in + regardless of directory state. + + REMOVE IT WHEN YOU ARE DONE. It is a back door. Once a permanent + administrator exists in the database, set secrets.recoveryAdminSecretRef + to null and upgrade; the variable then disappears from the pods. +{{- else }} + + secrets.recoveryAdminSecretRef is NOT SET. That is the right end state once a + permanent administrator exists — but during a first install or a recovery + start it means Stalwart generates a temporary administrator password and + prints it to STDOUT, i.e. into the pod log, freshly on every restart and + visible to anyone who can read logs. Catch it with + kubectl -n {{ .Release.Namespace }} logs sts/{{ $release }}-{{ $ingressGroup | default "" }}-sfs | grep -A3 bootstrap +{{- end }} +{{- if .Values.secrets.s3SecretRef }} + + secrets.s3SecretRef → {{ .Values.secrets.s3SecretRef }} + fields: access-key, secret-key + Exposed to the containers as {{ include "stalwart.env.s3AccessKey" . }} and + {{ include "stalwart.env.s3SecretKey" . }}. The chart does NOT configure the blob + store; point the BlobStore object in the WebUI at these names: + accessKey: {"@type":"EnvironmentVariable","variableName":"{{ include "stalwart.env.s3AccessKey" . }}"} + secretKey: {"@type":"EnvironmentVariable","variableName":"{{ include "stalwart.env.s3SecretKey" . }}"} +{{- end }} + + CHANGING WHAT IS INSIDE AN ITEM RESTARTS NOTHING. Helm never sees a secret's + content, so there is nothing to hash. Repointing one of the values above at a + different vault item DOES roll the pods (checksum/secret-ref covers the + op:// path). After rotating a password inside an item: +{{- range $group, $spec := $nodes }} + kubectl -n {{ $.Release.Namespace }} rollout restart statefulset/{{ $release }}-{{ $group }}-sfs +{{- end }} + +FIRST INSTALL — EIGHT STEPS, AND NONE OF THEM IS OPTIONAL + 1. bootstrap.enabled: true, nodes.mx.replicas: 0. + The setup wizard everyone reaches for appears only when config.json is + ABSENT, and this chart always renders one — so the wizard never runs here. + Recovery mode is the documented path for a templated config.json: it + opens the management endpoint and keeps the mail ports shut. With a second + group running, the wizard would be unusable anyway: each request would + land on a random pod. + + 2. Open the management UI and create the permanent administrator. + kubectl -n {{ .Release.Namespace }} port-forward svc/{{ $release }}-{{ $ingressGroup | default "" }}-http-service {{ (index $ports "http").containerPort }}:{{ (index $ports "http").containerPort }} + then http://localhost:{{ (index $ports "http").containerPort }}/admin + + 3. In the WebUI, create: the blob store (S3), the in-memory store + ({{ if $valkeyHost }}{{ $valkeyHost }}:{{ .Values.externalServices.valkey.port }}{{ else }}no address configured — see externalServices.valkey{{ end }}), + the coordinator (Default — it reuses the in-memory store connection), the + search store (Default — it uses the data store, so no extra service is + needed), the TLS object pointing at the certificate from step 5, the + NetworkListener objects, and one ClusterRole per node group below. + + THE LISTENER PORTS MUST MATCH THIS RELEASE EXACTLY. The chart cannot + create listener objects, so these numbers are a second copy of a decision + made in the WebUI, and a mismatch is silent — the Service points at a port + nothing listens on, every pod stays Ready, nothing reports it: +{{- range $portName, $port := $ports }} + {{ printf "%-12s" $portName }} bind {{ printf "%-5s" (printf "%v" $port.containerPort) }}{{ if $port.public }} (published on node port {{ $port.nodePort }}){{ else }} (not published){{ end }} +{{- end }} + + AND ONE ClusterRole PER GROUP, NAMED EXACTLY: +{{- range $group, $spec := $nodes }} + {{ $group }} +{{- end }} + A node whose role name is not in the database does not fail. It becomes a + FULL node — every listener and every task — while staying Running with a + green readiness probe. The only trace is one log line, + 'Cluster role "" not found in registry', and it is printed AFTER the + listeners are already bound. + + 4. Configure HTTP forwarding before the auto-ban notices the Ingress. + Stalwart sees the ingress controller's pod IP for every WebUI and JMAP + request, not the client's. Sooner or later the auto-ban bans that one + address and the WebUI and JMAP go dark for everyone at once. The PROXY + protocol is not the fix for HTTP: enable "forwarded" handling with + X-Forwarded-For evaluation, and discard forwarding headers the client + brought itself. The outage arrives weeks later and looks like a server + fault, which is why this is a step and not a tip. + + 5. Point the TLS object at the mounted certificate. +{{- if .Values.certificate.enabled }} + certificate: {{ .Values.certificate.mountPath }}/tls.crt + privateKey: {{ .Values.certificate.mountPath }}/tls.key + cert-manager writes these into tls-{{ $release }}-mail. Watch it with + kubectl -n {{ .Release.Namespace }} get certificate {{ $release }}-mail-certificate + Until it is issued the mail ports serve a self-signed certificate: the + volume is mounted optional so that a pending challenge does not hold every + pod in ContainerCreating. +{{- else }} + certificate.enabled is false, so this chart issues no mail certificate. + The Ingress certificate does NOT cover the mail ports — the HA proxy + terminates no TLS, so Stalwart has to present one itself for STARTTLS on + 25 and implicit TLS on 465/993. Provide it another way or clients will see + a name mismatch. +{{- end }} + + 6. Set send-proxy-v2 on the HA proxy. ALL OR NOTHING WITH STEP 3. + externalTrafficPolicy is {{ .Values.service.externalTrafficPolicy }}, which it has to be — no Stalwart + pod runs on a control-plane node, and the HA proxy delivers to the + control-plane nodes, so Local would drop every packet. The cost is that + kube-proxy masquerades the source address, and on a mail server a lost + source address switches off SPF, takes DMARC with it, makes every + blocklist report "clean", collapses per-IP rate limits onto one address, + removes greylisting's key, and makes the auto-ban lock out every sender at + once. The Received: chain becomes worthless — the one item there that + destroys evidence retroactively rather than just failing. + + The PROXY v2 header restores it, for port 25 as well, because the HA proxy + opens its own connection to the node. But a trusted network makes the + header MANDATORY: without it a connection from there hangs until timeout, + and with it from an untrusted network Stalwart reads "PROXY TCP4 ..." as + an SMTP command. Test on a spare port with its own frontend, and move 25 + only once a Received: line shows the real sender address. + + 7. Restart the pods — "a newly added listener binds only on the next start" — + and set bootstrap.enabled: false in the same round. + + 8. Raise nodes.mx.replicas only after the "mx" ClusterRole exists (step 3), + and publish DNS (below). + +DNS A MAIL SERVER CANNOT RUN WITHOUT + None of this is rendered by the chart; all of it is required. + MX {{ .Values.ingress.domain | default "" }}. → this deployment's public name + SPF TXT "v=spf1 ..." naming the HA proxy's address as a sender + DKIM TXT at ._domainkey — the key is generated IN Stalwart + (Domains → DKIM), so this record is published after step 3 + DMARC TXT at _dmarc — start at p=none with rua= and tighten only once + the reports are clean + REVERSE DNS PTR for the HA PROXY's public address, matching its forward + name. Not the node's and not the pod's: the HA proxy is what + other mail servers see connecting. Many receivers reject mail + outright when it is missing, and nothing in Kubernetes can set + it — it belongs to whoever owns the IP range. + +WHAT A GREEN POD PROVES HERE, AND WHAT IT DOES NOT + Liveness asks /healthz/live, readiness and startup ask /healthz/ready. + Read off the source at v0.16.24: /healthz/ready returns 200 as soon as a data + store HANDLE exists — it does not query the database. So Ready does not mean + the database is reachable, and it does not catch a pod that fell back to an + ephemeral in-memory store because config.json was missing. A green pod here + means the process is answering HTTP. + + The probe intervals are calculated, not chosen: Stalwart rate-limits + anonymous /healthz requests to 100 per 60s PER SOURCE IP, probes arrive from + the node IP, and so every pod on a node shares one bucket. The defaults cost + 6 requests/min/pod and leave room for about 16 pods per node. Tightening them + produces 429s, and a 429 on liveness is a restart loop. +{{- if .Values.ingress.enabled }} + +WEB UI AND JMAP + https://{{ .Values.ingress.domain }} → node group "{{ $ingressGroup }}" + Certificate requested by cert-manager through the "{{ .Values.ingress.clusterIssuer }}" cluster issuer: + kubectl -n {{ .Release.Namespace }} get certificate tls-{{ $release }}-ingress + + AFTER BOOTSTRAP, PORT {{ (index $ports "http").containerPort }} IS NOT THE ADMIN PORT ANY MORE. Upstream moves + administration to https:///admin once setup is complete, so this + Ingress only works while an HTTP NetworkListener on {{ (index $ports "http").containerPort }} exists in the + database (step 3). Between finishing setup and creating that listener the + Ingress resolves to a port that answers nothing. +{{- else }} + +NO INGRESS + ingress.enabled is false, so there is no Ingress and no WebUI certificate. + ingress.domain STAYS REQUIRED even so — the mail Certificate reads it for its + dnsNames, and without it the certificate would carry no name at all. +{{- end }} +{{- if .Values.valkey.enabled }} + +THE VALKEY SUBCHART IS ENABLED + Reachable at {{ $valkeyHost }}:{{ .Values.externalServices.valkey.port }}, and it is upstream's chart consumed as it + comes. Two of its defaults fall short of this repo's conventions and are NOT + patched by us: auth.enabled is false (unauthenticated access from anything + the CNI permits), and its NetworkPolicy is its own object with its own + semantics, which this chart's networkPolicy block does not reach. See the + valkey section of values.yaml. + + scaleDown and checksum/config stop at the subchart boundary, and a new Valkey + release reaches you only when this chart is republished. +{{- end }} +{{- if not .Values.networkPolicy.enabled }} + +NETWORKPOLICY IS OFF + networkPolicy.enabled is false, so nothing limits reachability except the + Services. That removes the second line of defence against the fail-open in + step 3: a group that accidentally became a full node is then reachable on + every port it bound. +{{- else if not .Values.networkPolicy.probeSources }} + +NETWORKPOLICY: THE HTTP PORT IS OPEN INSIDE THE CLUSTER + networkPolicy.probeSources is empty, so the rule for port {{ (index $ports "http").containerPort }} renders with + no "from" selector. Deliberate: the kubelet probes from the worker node's IP, + which this chart cannot know, and a wrong guess blocks every probe — a pod + that never becomes Ready reads as a broken application rather than as a + policy. The port carries no nodePort, so this is open inside the cluster, not + from outside. Narrow it with networkPolicy.probeSources, and then add the + ingress controller's namespace to networkPolicy.allowedNamespaces or the + Ingress goes dark. +{{- end }} diff --git a/stalwart/templates/_helpers.tpl b/stalwart/templates/_helpers.tpl new file mode 100644 index 0000000..ee5ef55 --- /dev/null +++ b/stalwart/templates/_helpers.tpl @@ -0,0 +1,428 @@ +{{/* +Resource / replica / null-safety helpers. + +These are copied from template-chart with "stalwart." as the define prefix, +as in every other chart here: sharing them would mean a library chart, and a +dependency is admissible but expensive (README, guideline 14) - this chart +already carries one and does not need a second. template-chart holds the +reference implementation; the resource-quantity render test in CI exists +because a copy can carry an old bug into a diff nobody reads. +*/}} +{{- define "stalwart.resources" -}} +{{- $resources := . | default dict -}} +{{- $factor := 3.0 -}} +{{- if not (kindIs "invalid" $resources.limitFactor) -}} +{{- $factor = float64 $resources.limitFactor -}} +{{- end -}} +{{- $requests := dict -}} +{{- range $key, $value := ($resources.requests | default dict) -}} +{{- if not (kindIs "invalid" $value) -}} +{{- $_ := set $requests (include "stalwart.resourceKey" $key) $value -}} +{{- end -}} +{{- end -}} +{{- $limits := dict -}} +{{- range $key, $value := ($resources.limits | default dict) -}} +{{- if not (kindIs "invalid" $value) -}} +{{- $_ := set $limits (include "stalwart.resourceKey" $key) $value -}} +{{- end -}} +{{- end -}} +{{- range $key, $request := $requests -}} +{{- if and (ne $key "cpu") (not (hasKey $limits $key)) -}} +{{- $_ := set $limits $key (include "stalwart.multiplyQuantity" (dict "quantity" $request "factor" $factor)) -}} +{{- end -}} +{{- end -}} +{{- $out := dict -}} +{{- with $requests }}{{- $_ := set $out "requests" . }}{{- end -}} +{{- with $limits }}{{- $_ := set $out "limits" . }}{{- end -}} +{{- toYaml $out -}} +{{- end -}} + +{{/* +Normalize a resource name from values to its Kubernetes key. +*/}} +{{- define "stalwart.resourceKey" -}} +{{- if eq . "ephemeralStorage" -}}ephemeral-storage{{- else -}}{{ . }}{{- end -}} +{{- end -}} + +{{/* +Multiply a Kubernetes quantity by a factor, keeping its suffix. +Input: dict "quantity" "factor" . +*/}} +{{- define "stalwart.multiplyQuantity" -}} +{{- $quantity := include "stalwart.formatNumber" .quantity -}} +{{- $number := regexFind "^[0-9]+(\\.[0-9]+)?" $quantity -}} +{{- if not $number -}} +{{- fail (printf "cannot parse resource quantity %q" $quantity) -}} +{{- end -}} +{{- $suffix := trimPrefix $number $quantity -}} +{{- if not (regexMatch "^(m|k|M|G|T|P|E|Ki|Mi|Gi|Ti|Pi|Ei)?$" $suffix) -}} +{{- fail (printf "unsupported resource quantity suffix %q in %q" $suffix $quantity) -}} +{{- end -}} +{{- $product := mulf (float64 $number) .factor -}} +{{- if eq $product (floor $product) -}} +{{- printf "%d%s" (int64 $product) $suffix -}} +{{- else -}} +{{- printf "%s%s" (include "stalwart.formatNumber" $product) $suffix -}} +{{- end -}} +{{- end -}} + +{{/* +Render a number as a plain decimal string, never in exponential notation +(issue #157): the null-safe helpers pass values through fromYaml, which parses +every number as float64, and Go's "%v" switches to exponential notation from +about 1e6 upwards - not a valid Kubernetes quantity. +*/}} +{{- define "stalwart.formatNumber" -}} +{{- if kindIs "float64" . -}} +{{- regexReplaceAll "\\.?0+$" (printf "%.10f" .) "" -}} +{{- else -}} +{{- printf "%v" . -}} +{{- end -}} +{{- end -}} + +{{/* +The replica count of one node group. +Input: dict "scaleDown" "replicas" . +The explicit kindIs "invalid" check is what keeps an explicit 0 - which this +chart relies on, since the "mx" group ships with replicas: 0. +*/}} +{{- define "stalwart.replicas" -}} +{{- if .scaleDown -}} +0 +{{- else if not (kindIs "invalid" .replicas) -}} +{{- .replicas -}} +{{- else -}} +1 +{{- end -}} +{{- end -}} + +{{/* +Merge a user-supplied values sub-tree onto a dict of chart defaults so that a +null / empty override falls back to the defaults instead of erasing them +(issues #61 and #99). Input: dict "defaults" "given" "path" +. Output: YAML, consume it with fromYaml. +*/}} +{{- define "stalwart.defaultedDict" -}} +{{- $defaults := .defaults | default dict -}} +{{- $given := .given -}} +{{- $path := .path | default "value" -}} +{{- if kindIs "invalid" $given -}} +{{- $given = dict -}} +{{- end -}} +{{- if not (kindIs "map" $given) -}} +{{- fail (printf "%s must be a mapping or null, got %s (%v)" $path (kindOf $given) $given) -}} +{{- end -}} +{{- $out := deepCopy $defaults -}} +{{- range $key, $value := $given -}} +{{- if not (kindIs "invalid" $value) -}} +{{- $default := index $defaults $key -}} +{{- if and (kindIs "map" $value) (kindIs "map" $default) -}} +{{- $_ := set $out $key (fromYaml (include "stalwart.defaultedDict" (dict "defaults" $default "given" $value "path" (printf "%s.%s" $path $key)))) -}} +{{- else if kindIs "map" $default -}} +{{- fail (printf "%s.%s must be a mapping or null, got %s (%v)" $path $key (kindOf $value) $value) -}} +{{- else -}} +{{- $_ := set $out $key $value -}} +{{- end -}} +{{- end -}} +{{- end -}} +{{- toYaml $out -}} +{{- end -}} + +{{/* +Pick one sub-block out of a values block that may itself be null. +Input: dict "block" "key" "path" . +*/}} +{{- define "stalwart.subBlock" -}} +{{- $block := .block -}} +{{- if kindIs "invalid" $block -}} +{{- $block = dict -}} +{{- end -}} +{{- if not (kindIs "map" $block) -}} +{{- fail (printf "%s must be a mapping or null, got %s (%v)" .path (kindOf $block) $block) -}} +{{- end -}} +{{- toYaml (dict "value" (index $block .key)) -}} +{{- end -}} + +{{/* +The effective security contexts, probes and resources (issue #99). + +The defaults below MUST stay in sync with values.yaml, which stays the +documented, user-facing place for them; this copy is only the fallback for the +case where an override has erased the block. + +Two rules these fallbacks exist to honour (README, guideline 12): + - reproduce THIS chart's defaults, not the repo standard. uid/gid 2000 is the + image's own user, and there is deliberately NO fsGroup here because this + chart mounts no PVC. + - carry the probe's CONTEXT, not just its timings. The paths and the port + name are part of these defaults; without them the probes would hit "/" on + a port that may not exist, and liveness would stop being independent of + the data store. +*/}} +{{- define "stalwart.podSecurityContext" -}} +{{- $given := (fromYaml (include "stalwart.subBlock" (dict "block" . "key" "pod" "path" "securityContext"))).value -}} +{{- $defaults := dict + "runAsNonRoot" true + "runAsUser" 2000 + "runAsGroup" 2000 + "seccompProfile" (dict "type" "RuntimeDefault") -}} +{{- include "stalwart.defaultedDict" (dict "defaults" $defaults "given" $given "path" "securityContext.pod") -}} +{{- end -}} + +{{- define "stalwart.containerSecurityContext" -}} +{{- $given := (fromYaml (include "stalwart.subBlock" (dict "block" . "key" "container" "path" "securityContext"))).value -}} +{{/* +NET_BIND_SERVICE is part of the FALLBACK, not only of values.yaml, and that is +the whole point of rule "reproduce THIS chart's defaults, not the repo +standard". The image carries setcap cap_net_bind_service=+ep on its binary, so +with an empty bounding set the kernel fails the execve itself - an erased +securityContext block that fell back to the repo-standard "add: []" would stop +the chart from starting at all, with "operation not permitted" and nothing +pointing at this file. +*/}} +{{- $defaults := dict + "allowPrivilegeEscalation" false + "readOnlyRootFilesystem" true + "runAsNonRoot" true + "capabilities" (dict "drop" (list "ALL") "add" (list "NET_BIND_SERVICE")) -}} +{{- include "stalwart.defaultedDict" (dict "defaults" $defaults "given" $given "path" "securityContext.container") -}} +{{- end -}} + +{{/* +The probe fallbacks carry the calculated intervals, not just the paths. The +arithmetic is in values.yaml: Stalwart rate-limits anonymous /healthz requests +to 100 per 60s PER SOURCE IP, probes come from the node IP, so every pod on a +node shares one bucket. 20/20/10 costs 6 requests/min/pod in both phases +(the startup probe gates the other two, so they never run together) and leaves +room for ~16 pods per node. The obvious 10/10/5 would halve that to ~8. +Tightening these here without redoing that sum produces 429s, and a 429 on +liveness is a restart loop. +*/}} +{{- define "stalwart.livenessProbe" -}} +{{- $defaults := dict + "httpGet" (dict "path" "/healthz/live" "port" "http") + "periodSeconds" 20 + "timeoutSeconds" 5 + "failureThreshold" 3 -}} +{{- include "stalwart.defaultedDict" (dict "defaults" $defaults "given" . "path" "livenessProbe") -}} +{{- end -}} + +{{- define "stalwart.readinessProbe" -}} +{{- $defaults := dict + "httpGet" (dict "path" "/healthz/ready" "port" "http") + "periodSeconds" 20 + "timeoutSeconds" 5 + "failureThreshold" 3 -}} +{{- include "stalwart.defaultedDict" (dict "defaults" $defaults "given" . "path" "readinessProbe") -}} +{{- end -}} + +{{- define "stalwart.startupProbe" -}} +{{- $defaults := dict + "httpGet" (dict "path" "/healthz/ready" "port" "http") + "periodSeconds" 10 + "timeoutSeconds" 5 + "failureThreshold" 30 -}} +{{- include "stalwart.defaultedDict" (dict "defaults" $defaults "given" . "path" "startupProbe") -}} +{{- end -}} + +{{/* +============================================================================= +Chart-specific helpers +============================================================================= +*/}} + +{{/* +The common name prefix. One place, because it appears in every object name and +in the Service selectors. +*/}} +{{- define "stalwart.fullname" -}} +{{- printf "%s-%s" .Release.Name .Chart.Name -}} +{{- end -}} + +{{/* +The validated "ports" map. Rejects a non-mapping and an empty map, and checks +every entry for the one field the chart cannot do without. + +Why the number is checked here rather than where it is used: an erased +ports.smtp.number used to render "port:" and "targetPort:" empty into the +Service and an empty "containerPort" into the StatefulSet - rejected by nothing +until the API server saw it (the satisfactory lesson, Gitea #16). +*/}} +{{- define "stalwart.ports" -}} +{{- $ports := .Values.ports -}} +{{- if kindIs "invalid" $ports -}} +{{- fail "ports must be a mapping of port name to { containerPort, nodePort, protocol, public }, and it cannot be erased: every Service, containerPort and NetworkPolicy rule in this chart is rendered from it" -}} +{{- end -}} +{{- if not (kindIs "map" $ports) -}} +{{- fail (printf "ports must be a mapping, got %s" (kindOf $ports)) -}} +{{- end -}} +{{- if eq (len $ports) 0 -}} +{{- fail "ports is empty - the chart would render workloads with no containerPort and no Service at all" -}} +{{- end -}} +{{- range $name, $spec := $ports -}} +{{- if not (kindIs "map" $spec) -}} +{{- fail (printf "ports.%s must be a mapping, got %s (%v)" $name (kindOf $spec) $spec) -}} +{{- end -}} +{{- if kindIs "invalid" $spec.containerPort -}} +{{- fail (printf "ports.%s.containerPort is required - a port without one renders an empty containerPort and an empty Service targetPort. Note containerPort and nodePort are two different numbers here and are not interchangeable: containerPort is what the application binds (and what the NetworkListener object in the database must say), nodePort is what the cluster publishes" $name) -}} +{{- end -}} +{{- if and $spec.public (kindIs "invalid" $spec.nodePort) -}} +{{- fail (printf "ports.%s is marked public but has no nodePort - a NodePort Service without a nodePort would be assigned a random one, which the HA proxy in front of the cluster does not know about" $name) -}} +{{- end -}} +{{- end -}} +{{- toYaml $ports -}} +{{- end -}} + +{{/* +The validated "nodes" map, with each group's exposedPorts checked against the +ports map. Input: the root context. + +The exposedPorts check is the one that earns its keep: a typo there would +silently drop a port from a group's containerPorts and from its NetworkPolicy, +leaving a Service selecting pods that never bound the port. +*/}} +{{- define "stalwart.nodes" -}} +{{- $ports := fromYaml (include "stalwart.ports" .) -}} +{{- $nodes := .Values.nodes -}} +{{- if kindIs "invalid" $nodes -}} +{{- fail "nodes must be a mapping of cluster-role name to node group, and it cannot be erased: it is what every StatefulSet in this chart is rendered from" -}} +{{- end -}} +{{- if not (kindIs "map" $nodes) -}} +{{- fail (printf "nodes must be a mapping of cluster-role name to node group, got %s - note it is a MAP and not a list, so that an override never depends on a position" (kindOf $nodes)) -}} +{{- end -}} +{{- if eq (len $nodes) 0 -}} +{{- fail "nodes is empty - the release would contain Services and an Ingress but no workload" -}} +{{- end -}} +{{- range $group, $spec := $nodes -}} +{{- if not (kindIs "map" $spec) -}} +{{- fail (printf "nodes.%s must be a mapping, got %s (%v)" $group (kindOf $spec) $spec) -}} +{{- end -}} +{{- if not (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" $group) -}} +{{- fail (printf "nodes.%s is not usable as a Kubernetes name segment: a group key becomes part of every object name and of a label value, so it must be lowercase alphanumeric with dashes. It is ALSO the cluster-role name passed in STALWART_ROLE, so renaming it here without renaming the ClusterRole object in the database turns the group into a full node" $group) -}} +{{- end -}} +{{- $exposed := $spec.exposedPorts -}} +{{- if kindIs "invalid" $exposed -}} +{{- fail (printf "nodes.%s.exposedPorts is required - a group with no ports is unreachable, and because this list is also the NetworkPolicy's ingress rule, an erased one is indistinguishable from a deliberate lockout" $group) -}} +{{- end -}} +{{- if not (kindIs "slice" $exposed) -}} +{{- fail (printf "nodes.%s.exposedPorts must be a list of port names, got %s (%v)" $group (kindOf $exposed) $exposed) -}} +{{- end -}} +{{- range $exposed -}} +{{- if not (hasKey $ports .) -}} +{{- fail (printf "nodes.%s.exposedPorts names %q, which is not a key of ports: - known ports are %s. Left unchecked this would drop the port from the group's containerPorts and from its NetworkPolicy while the Service still selected its pods" $group . (keys $ports | sortAlpha | join ", ")) -}} +{{- end -}} +{{- end -}} +{{- if not (has "http" $exposed) -}} +{{- fail (printf "nodes.%s.exposedPorts does not include \"http\", but all three probes target that port - the group would never become Ready. Every group needs it, including an SMTP-only one; it is simply not published there" $group) -}} +{{- end -}} +{{- end -}} +{{- toYaml $nodes -}} +{{- end -}} + +{{/* +The effective resources of one node group. +Input: dict "group" "given" + "limitFactor" . + +The per-group defaults are reproduced here, not a single generic set: "mx" is +deliberately lighter than "full", and a fallback that handed an erased +mx.resources the heavier figures would quietly change what the chart had been +rendering. A group the chart does not ship gets the "full" figures, which is +the safe direction - too much accounting rather than too little. +*/}} +{{- define "stalwart.effectiveResources" -}} +{{- $factor := 3 -}} +{{- if not (kindIs "invalid" .limitFactor) -}} +{{- $factor = .limitFactor -}} +{{- end -}} +{{- $requests := dict "cpu" "200m" "memory" "512Mi" "ephemeral-storage" "64Mi" -}} +{{- if eq .group "mx" -}} +{{- $requests = dict "cpu" "100m" "memory" "256Mi" "ephemeral-storage" "64Mi" -}} +{{- end -}} +{{- $defaults := dict "limitFactor" $factor "requests" $requests -}} +{{- $merged := fromYaml (include "stalwart.defaultedDict" (dict "defaults" $defaults "given" .given "path" (printf "nodes.%s.resources" .group))) -}} +{{- include "stalwart.resources" $merged -}} +{{- end -}} + +{{/* +The label a pod carries for one port it is reachable on. The per-port Services +select on these, which is what lets one NodePort Service serve several node +groups - NodePorts are cluster-globally unique, so "full" and "mx" can only +accept SMTP behind the SAME Service object. +*/}} +{{- define "stalwart.portLabel" -}} +{{- printf "stalwart.jk-dev.de/port-%s" . -}} +{{- end -}} + +{{/* +The address of the in-memory store, and the render abort that goes with it. +Input: the root context. Returns the host, or "" when none is needed. + +The abort is the point. From v0.16 the cluster coordinator's Default variant +"reuses the Redis connection already configured on the in-memory store", so +more than one node without an in-memory store is a cluster with no +coordination path - and the symptom is not a failed install but a cluster that +comes up and disagrees with itself. Note what this value does NOT do: it does +not configure Stalwart. The in-memory store is an object in the database; this +is the address to type into the WebUI, and the port for the egress rule. +*/}} +{{- define "stalwart.valkeyHost" -}} +{{- $given := "" -}} +{{- if not (kindIs "invalid" .Values.externalServices) -}} +{{- $valkey := .Values.externalServices.valkey -}} +{{- if and (not (kindIs "invalid" $valkey)) (not (kindIs "invalid" $valkey.host)) -}} +{{- $given = $valkey.host -}} +{{- end -}} +{{- end -}} +{{- $subchartOn := false -}} +{{- if and (not (kindIs "invalid" .Values.valkey)) .Values.valkey.enabled -}} +{{- $subchartOn = true -}} +{{- end -}} +{{- if $given -}} +{{- $given -}} +{{- else if $subchartOn -}} +{{/* The subchart's own fullname helper: release name plus chart name, unless + the release name already contains it. Reproduced rather than called, + because a parent cannot include a subchart's define with the subchart's + context. */}} +{{- if contains "valkey" .Release.Name -}} +{{- .Release.Name | trunc 63 | trimSuffix "-" -}} +{{- else -}} +{{- printf "%s-valkey" .Release.Name | trunc 63 | trimSuffix "-" -}} +{{- end -}} +{{- else -}} +{{- $total := 0 -}} +{{- range $group, $spec := fromYaml (include "stalwart.nodes" .) -}} +{{- $total = add $total (int (include "stalwart.replicas" (dict "scaleDown" $.Values.scaleDown "replicas" $spec.replicas))) -}} +{{- end -}} +{{- if gt $total 1 -}} +{{- fail (printf "this release runs %d Stalwart pods, which is a cluster, but no in-memory store has an address: externalServices.valkey.host is empty and valkey.enabled is false. Stalwart's cluster coordinator rides on the in-memory store connection, so a multi-node install has no coordination path at all - and that failure does not show up as a failed install, it shows up as nodes that do not agree with each other. Set externalServices.valkey.host to an existing instance, or set valkey.enabled: true to deploy the subchart" $total) -}} +{{- end -}} +{{- end -}} +{{- end -}} + +{{/* +The environment-variable names that config.json references and the StatefulSet +sets. They are helpers rather than literals in two files because a mismatch +between the two is not a render error: the server starts, resolves authSecret, +finds no such variable, and fails to open the data store with +"Environment variable '' not found". One definition, used by both. + +Note the upstream resolver treats an EMPTY value as not found, so a 1Password +item whose field exists but is blank fails exactly like a missing field. +*/}} +{{- define "stalwart.env.dbPassword" -}}STALWART_DB_PASSWORD{{- end -}} +{{- define "stalwart.env.s3AccessKey" -}}STALWART_S3_ACCESS_KEY{{- end -}} +{{- define "stalwart.env.s3SecretKey" -}}STALWART_S3_SECRET_KEY{{- end -}} + +{{/* +The node group the Ingress routes to, validated. Input: the root context. +*/}} +{{- define "stalwart.ingressNodeGroup" -}} +{{- $nodes := fromYaml (include "stalwart.nodes" .) -}} +{{- $group := required "ingress.nodeGroup must name the node group the Ingress routes to" .Values.ingress.nodeGroup -}} +{{- if not (hasKey $nodes $group) -}} +{{- fail (printf "ingress.nodeGroup is %q, which is not a key of nodes: - known groups are %s" $group (keys $nodes | sortAlpha | join ", ")) -}} +{{- end -}} +{{- $group -}} +{{- end -}} diff --git a/stalwart/templates/stalwart.certificate.yaml b/stalwart/templates/stalwart.certificate.yaml new file mode 100644 index 0000000..d5f4847 --- /dev/null +++ b/stalwart/templates/stalwart.certificate.yaml @@ -0,0 +1,56 @@ +{{- /* +The certificate for the MAIL ports, issued by cert-manager and mounted into +every node group read-only. + +WHY THE INGRESS CERTIFICATE IS NOT ENOUGH: the Ingress covers the WebUI and +JMAP only. The HA proxy in front of the cluster terminates no TLS, so Stalwart +itself has to present a certificate for STARTTLS on 25 and implicit TLS on 465 +and 993. Those connections never pass through the ingress controller. + +WHY NOT STALWART'S OWN ACME: the HA proxy forwards 25, 465 and 993 and not 80, +so an HTTP-01 challenge answered by Stalwart is unreachable from outside. +DNS-01 inside Stalwart would work and would duplicate what cert-manager +already does here. + +THIS OBJECT ONLY OBTAINS THE FILES. Pointing Stalwart at them is a separate, +manual step: the TLS object in the DATABASE has to name the two paths below. +Until it does, the mail ports serve whatever default certificate Stalwart +generates for itself, and clients see a name mismatch while every Kubernetes +object here is green. +*/ -}} +{{- if .Values.certificate.enabled }} +{{- $domain := required "A Domain/Host must be provided (ingress.domain) - it is read here for the mail certificate as well as by the Ingress, so it stays required even with ingress.enabled false" .Values.ingress.domain -}} +{{- /* An explicit if, NOT + .Values.certificate.clusterIssuer | default (required "..." .Values.ingress.clusterIssuer) + which is the obvious one-liner and is wrong: Go evaluates a pipeline's + arguments eagerly, so required() fires whenever ingress.clusterIssuer is + null even though certificate.clusterIssuer is set and the fallback is + never needed. Measured: ingress.enabled=false plus + certificate.clusterIssuer= aborted the render. */ -}} +{{- $issuer := .Values.certificate.clusterIssuer -}} +{{- if not $issuer -}} +{{- $issuer = required "A Cluster-Issuer must be provided: set certificate.clusterIssuer for the mail certificate (usually a DNS-01 issuer), or ingress.clusterIssuer, which it falls back to" .Values.ingress.clusterIssuer -}} +{{- end -}} +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + name: {{ include "stalwart.fullname" . }}-mail-certificate + labels: + app: {{ include "stalwart.fullname" . }} +spec: + # Deliberately NOT the Ingress TLS secret name (tls--stalwart-ingress). + # Two separate certificates on purpose: this one usually comes from a + # different issuer (DNS-01, see below) and covers different names, and + # sharing one secret would make the ingress controller and the mail + # listeners fight over which names the certificate has to carry. + secretName: tls-{{ include "stalwart.fullname" . }}-mail + issuerRef: + name: {{ $issuer }} + kind: ClusterIssuer + group: cert-manager.io + dnsNames: + - {{ $domain | quote }} + {{- range .Values.certificate.extraDnsNames }} + - {{ . | quote }} + {{- end }} +{{- end }} diff --git a/stalwart/templates/stalwart.configmap.yaml b/stalwart/templates/stalwart.configmap.yaml new file mode 100644 index 0000000..6e9af3c --- /dev/null +++ b/stalwart/templates/stalwart.configmap.yaml @@ -0,0 +1,52 @@ +{{- /* +config.json - the ONLY file Stalwart reads from disk, and the only part of its +configuration this chart owns. + +It is exactly the DataStore object, with no wrapper: upstream's declarative +deployment page states "It only needs to contain the DataStore object", and the +reader confirms it - crates/store/src/registry/local.rs deserializes the whole +file straight into the DataStore enum, which is internally tagged on "@type". +Everything else (listeners, blob store, in-memory store, TLS objects, domains, +cluster roles) is a JMAP object in the database and is created in the WebUI. + +WHY A CONFIGMAP AND NOT A SECRET: there is no credential in here. authSecret +is a tagged sub-object with an EnvironmentVariable variant, so the password is +referenced by NAME and arrives through the env (see the StatefulSet). That is +what keeps checksum/config meaningful - Helm can hash this file because Helm +can see all of it. + +The username is NOT a secret and cannot be made one: authUsername is a plain +String on the object with no secret form, unlike authSecret. It is public here +by necessity, not by oversight. +*/ -}} +{{- $pg := .Values.dataStore.postgres -}} +{{- $store := dict + "@type" "PostgreSql" + "host" (required "dataStore.postgres.host is required - without it Stalwart has no database, and a config.json that cannot be parsed or reached is the one case that does abort the start loudly" $pg.host) + "port" (int $pg.port) + "database" $pg.database + "authUsername" $pg.username + "authSecret" (dict "@type" "EnvironmentVariable" "variableName" (include "stalwart.env.dbPassword" .)) + "useTls" $pg.tls.enable + "allowInvalidCerts" $pg.tls.allowInvalidCerts + "poolMaxConnections" (int $pg.poolMaxConnections) + "timeout" (int $pg.timeoutMs) -}} +{{- if not (kindIs "invalid" $pg.options) -}} +{{- $_ := set $store "options" $pg.options -}} +{{- end -}} +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ include "stalwart.fullname" . }}-configmap + labels: + app: {{ include "stalwart.fullname" . }} +data: + # Rendered through toPrettyJson from a dict rather than written as a JSON + # literal: "timeout" is a Duration, which upstream's object encoding defines + # as an INTEGER COUNT OF MILLISECONDS and which explicitly "does not accept a + # string" - the serde impl deserializes it through u64::deserialize into + # Duration::from_millis. A hand-written literal is where a "15s" creeps in, + # and the server then refuses to parse the file at startup. Going through the + # dict also means "port" and "poolMaxConnections" cannot come out quoted. + config.json: | + {{- toPrettyJson $store | nindent 4 }} diff --git a/stalwart/templates/stalwart.ingress.yaml b/stalwart/templates/stalwart.ingress.yaml new file mode 100644 index 0000000..bb5a70c --- /dev/null +++ b/stalwart/templates/stalwart.ingress.yaml @@ -0,0 +1,65 @@ +{{- /* +The Ingress for the WebUI and JMAP only. SMTP, IMAP and ManageSieve are not +HTTP and cannot pass through it - those reach the pods through the per-port +NodePort Services. + +It targets exactly ONE node group (ingress.nodeGroup) through that group's own +http Service, never a port-label selector: the management surface is not safe +to spread across a group that may not run the management tasks. + +TWO TRAPS THAT BELONG TO THIS OBJECT AND ARE NOT SOLVED BY IT: + +1. The auto-ban sees the INGRESS CONTROLLER's pod IP for every JMAP and WebUI + request, not the client's. Sooner or later it bans that address and the + WebUI and JMAP go dark for everyone at once. The PROXY protocol is not the + remedy for HTTP: the remedy is Stalwart's "forwarded" handling with + X-Forwarded-For evaluation, plus discarding whatever forwarding headers the + client brought along. That is a configuration step in the database, and it + is mandatory rather than optional - the failure arrives weeks later and + looks like a server problem. + +2. AFTER BOOTSTRAP, PORT 8080 IS NOT THE ADMIN PORT ANY MORE. Upstream: + "After the restart, the WebUI is reached at https:///admin on the + configured server hostname, and HTTP access on port 8080 is no longer + available for administration." So this Ingress only works once an HTTP + NetworkListener on 8080 exists in the database. Between finishing the setup + and creating that listener, the Ingress resolves to a port that answers + nothing. +*/ -}} +{{- if .Values.ingress.enabled }} +{{- $group := include "stalwart.ingressNodeGroup" . -}} +{{- $nodes := fromYaml (include "stalwart.nodes" .) -}} +{{- $spec := index $nodes $group -}} +{{- if not (has "http" $spec.exposedPorts) -}} +{{- fail (printf "ingress.nodeGroup is %q, but nodes.%s.exposedPorts does not include \"http\" - there would be no Service for the Ingress to point at" $group $group) -}} +{{- end -}} +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: {{ include "stalwart.fullname" . }}-ingress + labels: + app: {{ include "stalwart.fullname" . }} + annotations: + cert-manager.io/cluster-issuer: {{ required "A Cluster-Issuer must be provided (ingress.clusterIssuer)" .Values.ingress.clusterIssuer }} + {{- with .Values.ingress.annotations }} + {{- toYaml . | nindent 4 }} + {{- end }} +spec: + ingressClassName: {{ .Values.ingress.className }} + rules: + - host: {{ required "A Domain/Host must be provided (ingress.domain)" .Values.ingress.domain }} + http: + paths: + - backend: + service: + # The http Service of the "{{ $group }}" group only. + name: {{ include "stalwart.fullname" . }}-{{ $group }}-http-service + port: + name: http + path: / + pathType: Prefix + tls: + - hosts: + - {{ required "A Domain/Host must be provided (ingress.domain)" .Values.ingress.domain }} + secretName: tls-{{ include "stalwart.fullname" . }}-ingress +{{- end }} diff --git a/stalwart/templates/stalwart.networkpolicy.yaml b/stalwart/templates/stalwart.networkpolicy.yaml new file mode 100644 index 0000000..ea9e681 --- /dev/null +++ b/stalwart/templates/stalwart.networkpolicy.yaml @@ -0,0 +1,136 @@ +{{- /* +One NetworkPolicy per node group. + +This object is the CEILING ON REACHABILITY, and that is its real job here: it +holds no matter which ports the process actually bound. A node whose +ClusterRole is missing from the database fail-opens into a full node and binds +every listener - including IMAP and the admin interface on a group meant to +take SMTP only - while staying Running with a green probe. The per-port +Services publish only what was asked for, and this policy is the second, +independent limit. See values.yaml for the source-level detail. + +!!! THE PORT NUMBERS HERE ARE POD PORTS (25/465/993/8080), NOT NODEPORTS !!! + +This is the easiest mistake to make in this chart, so it is spelled out. A +NetworkPolicy is evaluated at the POD's network interface, after kube-proxy has +already translated the NodePort to the targetPort. Writing 30025 here would +match nothing: the packet arrives at the pod on 25. The policy would then look +strict, be accepted by the API server, and silently block every inbound +connection - or, if it is the only rule, block the lot. + +Egress is restricted BY PORT and not by destination, because a NetworkPolicy +matches CIDRs and selectors and never hostnames - so dataStore.postgres.host +and externalServices.*.host cannot appear in it. What it still buys: a +compromised pod cannot open arbitrary outbound ports. + +And a NetworkPolicy is only a boundary where the cluster's CNI enforces one. An +unenforced policy is accepted and filters nothing. +*/ -}} +{{- if .Values.networkPolicy.enabled }} +{{- $root := . -}} +{{- $ports := fromYaml (include "stalwart.ports" .) -}} +{{- $egress := .Values.networkPolicy.egress -}} +{{- $probeSources := .Values.networkPolicy.probeSources | default list -}} +{{- $allowedNs := .Values.networkPolicy.allowedNamespaces | default list -}} +{{- range $group, $spec := fromYaml (include "stalwart.nodes" .) }} +{{- $name := printf "%s-%s" (include "stalwart.fullname" $root) $group }} +--- +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: {{ $name }}-networkpolicy + labels: + app: {{ $name }} +spec: + podSelector: + matchLabels: + app: {{ $name }}-sfs + policyTypes: + - Ingress + - Egress + ingress: + {{- /* The public mail ports: open to any source. They have to be - the + senders are the whole internet, and after NodePort masquerading the + source address is a control-plane node anyway. */}} + {{- $publicPorts := list }} + {{- range $portName := $spec.exposedPorts }} + {{- $port := index $ports $portName }} + {{- if $port.public }}{{- $publicPorts = append $publicPorts $portName }}{{- end }} + {{- end }} + {{- if $publicPorts }} + - ports: + {{- range $portName := $publicPorts }} + {{- $port := index $ports $portName }} + # {{ $portName }}: published on nodePort {{ int $port.nodePort }}, reaching the pod on {{ int $port.containerPort }} + - protocol: {{ $port.protocol | default "TCP" }} + port: {{ int $port.containerPort }} + {{- end }} + {{- end }} + {{- /* The http port: probes plus the ingress controller. */}} + {{- $http := index $ports "http" }} + - ports: + - protocol: {{ $http.protocol | default "TCP" }} + port: {{ int $http.containerPort }} + {{- if or $probeSources $allowedNs }} + # Restricted because networkPolicy.probeSources or .allowedNamespaces is + # set. MIND THE KUBELET: probes come from the IP of the worker node + # running the pod, so that address has to be in probeSources or the pod + # never becomes Ready - and a pod that is never Ready reads as a broken + # application rather than as a policy. + from: + - namespaceSelector: + matchLabels: + # Set by Kubernetes itself on every namespace (>= 1.21), so this + # needs no labelling work. + kubernetes.io/metadata.name: {{ $root.Release.Namespace }} + {{- range $allowedNs }} + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: {{ . | quote }} + {{- end }} + {{- range $probeSources }} + - ipBlock: + cidr: {{ . | quote }} + {{- end }} + {{- else }} + # NO "from" SELECTOR, WHICH MEANS OPEN - deliberately, and only inside + # the cluster: http carries no nodePort, so nothing outside reaches it + # through this chart. The alternative was to guess the worker node CIDRs, + # and a wrong guess blocks every kubelet probe. Narrow it by setting + # networkPolicy.probeSources (and then .allowedNamespaces for the + # ingress controller, or the Ingress goes dark). + {{- end }} + egress: + {{- if $egress.dns }} + - ports: + - protocol: UDP + port: 53 + - protocol: TCP + port: 53 + {{- end }} + {{- if $egress.smtp }} + # Outbound delivery: port 25 on any host on the internet. Uniform for every + # group on purpose - the chart does not know which groups run the + # outboundMta task, the value would drift away from the database, and the + # failure mode of getting it wrong is mail silently not leaving. + - ports: + - protocol: TCP + port: 25 + {{- end }} + {{- $outPorts := list (int $root.Values.dataStore.postgres.port) }} + {{- with $root.Values.externalServices }} + {{- if .s3 }}{{- $outPorts = append $outPorts (int .s3.port) }}{{- end }} + {{- if .valkey }}{{- $outPorts = append $outPorts (int .valkey.port) }}{{- end }} + {{- end }} + {{- range $root.Values.networkPolicy.egress.extraPorts }} + {{- $outPorts = append $outPorts (int .) }} + {{- end }} + # The data store, the blob store, the in-memory store and anything added + # through networkPolicy.egress.extraPorts. Ports only - see the header. + - ports: + {{- range $outPorts | uniq }} + - protocol: TCP + port: {{ . }} + {{- end }} +{{- end }} +{{- end }} diff --git a/stalwart/templates/stalwart.secret.yaml b/stalwart/templates/stalwart.secret.yaml new file mode 100644 index 0000000..f44e22d --- /dev/null +++ b/stalwart/templates/stalwart.secret.yaml @@ -0,0 +1,75 @@ +{{- /* +The 1Password items this chart materializes. Each is rendered only when its +op:// path is set, because two of the three are genuinely optional. + +WHAT THE FIELD NAMES ARE AND WHY THEY ARE NOT FREE-FORM: the operator +materializes one Secret key per FIELD of the item, and these templates mount or +reference those keys by name. An item without the expected field leaves the +container in CreateContainerConfigError. NOTES.txt lists them for the installer. + +AND THE LIMIT THAT CANNOT BE CLOSED: a change to the CONTENT of any of these +items does not restart anything. Helm never sees a secret's value - the +operator fills the Secret in-cluster after rendering - so there is nothing to +hash. What this chart does cover is the op:// PATH, through checksum/secret-ref +on the pod template (see the StatefulSet): repointing one of the values below +at a different vault item does roll the pods. For a content change, and after +rotating a password inside the item, the manual step is + kubectl -n rollout restart statefulset/-stalwart--sfs +for every group. The 1Password operator's auto-restart annotation is NOT set +here and must not be: verified against operator 1.12.0 it enumerates +Deployments only, so on a StatefulSet it is a silent no-op that advertises a +guarantee it does not provide (README, guideline 9). +*/ -}} +{{- if .Values.secrets.dataStoreSecretRef }} +apiVersion: onepassword.com/v1 +kind: OnePasswordItem +metadata: + name: {{ include "stalwart.fullname" . }}-datastore-secret + labels: + app: {{ include "stalwart.fullname" . }} +spec: + # Must carry the field: password + # + # Only the password. The data store's username is dataStore.postgres.username + # and is rendered into the ConfigMap, because authUsername is a plain String + # on the DataStore object while authSecret is a SecretKeyOptional - upstream + # offers a secret form for one and not the other. + itemPath: {{ .Values.secrets.dataStoreSecretRef }} +{{- end }} +{{- if .Values.secrets.recoveryAdminSecretRef }} +--- +apiVersion: onepassword.com/v1 +kind: OnePasswordItem +metadata: + name: {{ include "stalwart.fullname" . }}-recovery-admin-secret + labels: + app: {{ include "stalwart.fullname" . }} +spec: + # Must carry the field: recovery-admin + # + # Holding the COMPLETE value of STALWART_RECOVERY_ADMIN as one string, + # "admin:". The chart deliberately does not assemble it from a + # username and a password field: the upstream parser splits on the first ":" + # and drops the entry when either half is empty, so a half-filled item would + # silently mean "no recovery admin" rather than failing - and this credential + # is a back door that logs in regardless of directory state, which is not + # something to be uncertain about in either direction. + itemPath: {{ .Values.secrets.recoveryAdminSecretRef }} +{{- end }} +{{- if .Values.secrets.s3SecretRef }} +--- +apiVersion: onepassword.com/v1 +kind: OnePasswordItem +metadata: + name: {{ include "stalwart.fullname" . }}-s3-secret + labels: + app: {{ include "stalwart.fullname" . }} +spec: + # Must carry the fields: access-key, secret-key + # + # This chart does not configure the blob store - that object lives in the + # database. It exposes both fields to the container as {{ include "stalwart.env.s3AccessKey" . }} + # and {{ include "stalwart.env.s3SecretKey" . }}, so the BlobStore object created in the WebUI can + # reference them by name instead of storing the credentials in the database. + itemPath: {{ .Values.secrets.s3SecretRef }} +{{- end }} diff --git a/stalwart/templates/stalwart.service.yaml b/stalwart/templates/stalwart.service.yaml new file mode 100644 index 0000000..3b64d6e --- /dev/null +++ b/stalwart/templates/stalwart.service.yaml @@ -0,0 +1,123 @@ +{{- /* +Three kinds of Service, and the split is forced rather than stylistic. + +1. ONE NodePort Service PER PUBLIC PORT, not per node group. A NodePort is + unique across the whole cluster, so "full" and "mx" can only accept SMTP + behind the SAME Service object - two Services asking for 30025 is a + conflict. Hence the selector matches a per-port LABEL on the pods instead + of a node group, which lets one Service cover every group that lists the + port and still exclude the ones that do not. + + Putting all the ports into one Service does not work either: a Service has + exactly one selector, so 30993 would then be routed to "mx" pods as well, + where nothing is listening. + +2. ONE ClusterIP http Service PER NODE GROUP. The Ingress must reach exactly + one group (ingress.nodeGroup): the management surface is not safe to spread + across a group that may not run the management tasks, and a port-label + selector would send each request to a random group. So http gets a + per-group Service and the Ingress names one of them. + +3. ONE headless Service PER NODE GROUP, for the StatefulSet's stable pod DNS. +*/ -}} +{{- $root := . -}} +{{- $ports := fromYaml (include "stalwart.ports" .) -}} +{{- $nodes := fromYaml (include "stalwart.nodes" .) -}} +{{- $release := include "stalwart.fullname" . -}} + +{{- /* 1. Per-port NodePort Services. */ -}} +{{- range $portName, $port := $ports }} +{{- if $port.public }} +{{- $groups := list }} +{{- range $group, $spec := $nodes }} +{{- if has $portName $spec.exposedPorts }}{{- $groups = append $groups $group }}{{- end }} +{{- end }} +{{- if $groups }} +--- +apiVersion: v1 +kind: Service +metadata: + name: {{ $release }}-{{ $portName }}-service + labels: + app: {{ $release }} + {{- with $root.Values.service.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +spec: + type: NodePort + # Cluster, never Local. No Stalwart pod is ever scheduled on a control-plane + # node, and the HA proxy delivers to the control-plane nodes - under Local + # every packet would be dropped, not some. The cost is that kube-proxy + # masquerades the source address; the PROXY v2 header the HA proxy prepends + # is what makes that harmless. values.yaml has the full reasoning and the + # list of what a lost source address breaks on a mail server. + externalTrafficPolicy: {{ $root.Values.service.externalTrafficPolicy }} + selector: + # Scoped to this release, then to the port. Node groups serving this port: + # {{ $groups | sortAlpha | join ", " }} + stalwart.jk-dev.de/release: {{ $release }} + {{ include "stalwart.portLabel" $portName }}: "true" + ports: + - name: {{ $portName }} + protocol: {{ $port.protocol | default "TCP" }} + # port and nodePort are the published number; targetPort is the number + # the application binds inside the pod. They differ here on purpose. + port: {{ int $port.nodePort }} + nodePort: {{ int $port.nodePort }} + targetPort: {{ $portName }} +{{- end }} +{{- end }} +{{- end }} + +{{- /* 2. + 3. Per-group http ClusterIP and headless Services. */ -}} +{{- range $group, $spec := $nodes }} +{{- $name := printf "%s-%s" $release $group }} +{{- if has "http" $spec.exposedPorts }} +{{- $http := index $ports "http" }} +--- +apiVersion: v1 +kind: Service +metadata: + name: {{ $name }}-http-service + labels: + app: {{ $name }} + {{- with $root.Values.service.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +spec: + type: ClusterIP + selector: + app: {{ $name }}-sfs + ports: + - name: http + protocol: {{ $http.protocol | default "TCP" }} + port: {{ int $http.containerPort }} + targetPort: http +{{- end }} +--- +apiVersion: v1 +kind: Service +metadata: + name: {{ $name }}-headless + labels: + app: {{ $name }} +spec: + # Headless: this exists for the StatefulSet's stable per-pod DNS names + # (.-stalwart--headless), not for load balancing. + clusterIP: None + # So the DNS names resolve before a pod is Ready - a cluster member has to be + # findable by its peers while it is still starting up. + publishNotReadyAddresses: true + selector: + app: {{ $name }}-sfs + ports: + {{- range $portName := $spec.exposedPorts }} + {{- $port := index $ports $portName }} + - name: {{ $portName }} + protocol: {{ $port.protocol | default "TCP" }} + port: {{ int $port.containerPort }} + targetPort: {{ $portName }} + {{- end }} +{{- end }} diff --git a/stalwart/templates/stalwart.sfs.yaml b/stalwart/templates/stalwart.sfs.yaml new file mode 100644 index 0000000..f0b0e6a --- /dev/null +++ b/stalwart/templates/stalwart.sfs.yaml @@ -0,0 +1,266 @@ +{{- /* +One StatefulSet per node group. The group key is the cluster-role name and is +passed in STALWART_ROLE. + +A StatefulSet and not a Deployment, although this chart mounts no PVC: the +node-id lease Stalwart acquires for clustering is keyed on the hostname, and +only a StatefulSet gives a pod a stable one. STALWART_HOSTNAME is fed from the +pod name for exactly that reason. + +NO volumeClaimTemplates. All state is external - messages and metadata in +Postgres, blobs in S3, the in-memory store in Valkey - so both image volumes +are emptyDirs. That is also why there is no fsGroup in the pod context. +*/ -}} +{{- $root := . -}} +{{- $ports := fromYaml (include "stalwart.ports" .) -}} +{{- /* Evaluated here, in a template that is ALWAYS rendered, because this is + where the "cluster without an in-memory store" render abort lives. A + guard that only ran from NOTES.txt would never fire under helm template + or helm lint - NOTES.txt is not rendered by either - and would therefore + pass every check in CI while being broken (guideline 12.2). The value is + emitted as a comment below, which is also the address an operator has to + enter in the WebUI. */ -}} +{{- $valkeyHost := include "stalwart.valkeyHost" . -}} +{{- range $group, $spec := fromYaml (include "stalwart.nodes" .) }} +{{- $name := printf "%s-%s" (include "stalwart.fullname" $root) $group }} +--- +{{ if $valkeyHost -}} +# In-memory store this release expects: {{ $valkeyHost }}:{{ $root.Values.externalServices.valkey.port }} +# NOT configured by this chart - it is an InMemoryStore object in the database, +# and this is the address to enter in the WebUI. The cluster coordinator's +# Default variant reuses the same connection. +{{ end -}} +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: {{ $name }}-sfs + labels: + app: {{ $name }}-sfs + stalwart.jk-dev.de/release: {{ include "stalwart.fullname" $root }} + stalwart.jk-dev.de/node-group: {{ $group }} +spec: + replicas: {{ include "stalwart.replicas" (dict "scaleDown" $root.Values.scaleDown "replicas" $spec.replicas) }} + serviceName: {{ $name }}-headless + selector: + matchLabels: + app: {{ $name }}-sfs + template: + metadata: + name: {{ $name }}-sfs + labels: + app: {{ $name }}-sfs + # Scopes every per-port Service to THIS release, so a second stalwart + # release in the same namespace does not get its pods selected. + stalwart.jk-dev.de/release: {{ include "stalwart.fullname" $root }} + stalwart.jk-dev.de/node-group: {{ $group }} + {{- /* One label per port this group may be reached on. The per-port + Services select on these: NodePorts are cluster-globally + unique, so "full" and "mx" can only accept SMTP behind the SAME + Service object, and a label is what lets one selector cover + both groups while still excluding a group that does not list + the port. */}} + {{- range $spec.exposedPorts }} + {{ include "stalwart.portLabel" . }}: "true" + {{- end }} + annotations: + # Hash of the rendered ConfigMap: a changed config.json changes the pod + # template and therefore restarts the pods. Without it the change would + # be invisible to the running container - the file is mounted by + # subPath, which the kubelet never refreshes, and Stalwart reads it only + # at start. + checksum/config: {{ include (print $root.Template.BasePath "/stalwart.configmap.yaml") $root | sha256sum }} + # Hash of the rendered OnePasswordItems - the op:// PATHS, not their + # contents. Repointing secrets.* at a different vault item therefore + # takes effect instead of leaving the old credentials in the running + # pod. Named separately from checksum/config on purpose: that one + # promises "the config changed", this one only "the config SOURCE + # changed". A change inside an item is not covered and cannot be - + # Helm never sees a secret's content. + checksum/secret-ref: {{ include (print $root.Template.BasePath "/stalwart.secret.yaml") $root | sha256sum }} + spec: + automountServiceAccountToken: false + securityContext: + {{- include "stalwart.podSecurityContext" $root.Values.securityContext | nindent 8 }} + initContainers: + # config.json is copied out of the ConfigMap into the emptyDir rather + # than mounted from it, because STALWART WRITES THIS FILE ITSELF: on + # completing its setup wizard it "writes config.json ... and restarts + # into normal operation", and a ConfigMap mount is read-only. Copying + # keeps /etc/stalwart writable AND keeps checksum/config honest, which + # a bare emptyDir would not. + # + # The copy direction matters: the chart's version wins on every pod + # start. If an operator has let the server rewrite the file, that + # rewrite is discarded on the next restart - which is the intended + # behaviour here (the chart owns the data store setting) but is worth + # knowing before editing it through the WebUI. + - name: copy-config + image: "{{ $root.Values.initImage.repository }}:{{ $root.Values.initImage.tag }}" + imagePullPolicy: IfNotPresent + command: + - /bin/sh + - -c + - cp /chart-config/config.json /etc/stalwart/config.json + volumeMounts: + - name: config + mountPath: /chart-config + readOnly: true + - name: etc-stalwart + mountPath: /etc/stalwart + resources: + {{- include "stalwart.resources" (dict "limitFactor" 3 "requests" (dict "cpu" "10m" "memory" "16Mi" "ephemeral-storage" "8Mi")) | nindent 12 }} + securityContext: + {{- include "stalwart.containerSecurityContext" $root.Values.securityContext | nindent 12 }} + containers: + - name: {{ $name }}-sfs + image: "docker.io/stalwartlabs/stalwart:{{ $root.Chart.AppVersion }}" + imagePullPolicy: IfNotPresent + env: + # The cluster role. A ClusterRole object of exactly this name has + # to exist in the database - if it does not, the node silently + # becomes a FULL node (every listener AND every task) while staying + # Running with a green readiness probe. See values.yaml. + - name: STALWART_ROLE + value: {{ $group | quote }} + # The node identity for the cluster node-id lease. The pod name is + # stable because this is a StatefulSet; the OS hostname inside the + # pod would be too, but reading it from the API is what makes the + # value survive a hostname the image cannot change. + - name: STALWART_HOSTNAME + valueFrom: + fieldRef: + fieldPath: metadata.name + {{- if $root.Values.bootstrap.enabled }} + # RECOVERY MODE IS ON: management HTTP on 8080 only, every mail + # port closed. Required for a first install because this chart + # always renders config.json and the bootstrap wizard only appears + # when that file is ABSENT. Turn it off and upgrade again once the + # database is provisioned. + - name: STALWART_RECOVERY_MODE + value: "1" + - name: STALWART_RECOVERY_MODE_LOG_LEVEL + value: {{ $root.Values.bootstrap.logLevel | quote }} + {{- end }} + {{- if $root.Values.secrets.dataStoreSecretRef }} + # Referenced BY NAME from config.json as + # "authSecret": {"@type":"EnvironmentVariable","variableName":"..."} + # which is what keeps the password out of the ConfigMap. An empty + # value counts as "not found" upstream and fails the store open. + - name: {{ include "stalwart.env.dbPassword" $root }} + valueFrom: + secretKeyRef: + name: {{ include "stalwart.fullname" $root }}-datastore-secret + key: password + {{- end }} + {{- if $root.Values.secrets.recoveryAdminSecretRef }} + - name: STALWART_RECOVERY_ADMIN + valueFrom: + secretKeyRef: + name: {{ include "stalwart.fullname" $root }}-recovery-admin-secret + key: recovery-admin + {{- end }} + {{- if $root.Values.secrets.s3SecretRef }} + # Not read by the chart and not by config.json: these exist so the + # BlobStore object in the DATABASE can reference them instead of + # storing the credentials there. + - name: {{ include "stalwart.env.s3AccessKey" $root }} + valueFrom: + secretKeyRef: + name: {{ include "stalwart.fullname" $root }}-s3-secret + key: access-key + - name: {{ include "stalwart.env.s3SecretKey" $root }} + valueFrom: + secretKeyRef: + name: {{ include "stalwart.fullname" $root }}-s3-secret + key: secret-key + {{- end }} + {{- range $value := $spec.env }} + {{- if $value.value }} + - name: {{ $value.name | quote }} + # quote is required, not cosmetic: a value like "8080" or "true" + # renders unquoted as a YAML number/bool and the API server + # rejects the whole manifest. + value: {{ tpl $value.value $root | quote }} + {{- else if $value.valueFrom }} + {{- if $value.valueFrom.secretKeyRef }} + - name: {{ $value.name }} + valueFrom: + secretKeyRef: + name: {{ tpl $value.valueFrom.secretKeyRef.name $root | quote }} + key: {{ tpl $value.valueFrom.secretKeyRef.key $root | quote }} + {{- else if $value.valueFrom.configMapKeyRef }} + - name: {{ $value.name }} + valueFrom: + configMapKeyRef: + name: {{ tpl $value.valueFrom.configMapKeyRef.name $root | quote }} + key: {{ tpl $value.valueFrom.configMapKeyRef.key $root | quote }} + {{- end }} + {{- end }} + {{- end }} + ports: + {{- range $portName := $spec.exposedPorts }} + {{- $port := index $ports $portName }} + - name: {{ $portName }} + # containerPort, NOT nodePort. This is the number the application + # binds and the number the NetworkListener object in the database + # has to carry; the nodePort only appears in the Service. + containerPort: {{ int $port.containerPort }} + protocol: {{ $port.protocol | default "TCP" }} + {{- end }} + # Probes, resources and both security contexts go through the + # null-safe helpers (#99): an erased block means "chart defaults + # apply" instead of a vanished probe or an unhardened container. + # Never wrap these in an "if". + livenessProbe: + {{- include "stalwart.livenessProbe" $root.Values.livenessProbe | nindent 12 }} + readinessProbe: + {{- include "stalwart.readinessProbe" $root.Values.readinessProbe | nindent 12 }} + startupProbe: + {{- include "stalwart.startupProbe" $root.Values.startupProbe | nindent 12 }} + resources: + {{- include "stalwart.effectiveResources" (dict "group" $group "given" $spec.resources "limitFactor" $root.Values.limitFactor) | nindent 12 }} + securityContext: + {{- include "stalwart.containerSecurityContext" $root.Values.securityContext | nindent 12 }} + volumeMounts: + - name: etc-stalwart + mountPath: /etc/stalwart + - name: var-lib-stalwart + mountPath: /var/lib/stalwart + - name: tmp + mountPath: /tmp + {{- if $root.Values.certificate.enabled }} + - name: mail-tls + mountPath: {{ $root.Values.certificate.mountPath }} + readOnly: true + {{- end }} + volumes: + - name: config + configMap: + name: {{ include "stalwart.fullname" $root }}-configmap + # Writable because Stalwart rewrites config.json itself after its setup + # wizard; the init container seeds it from the ConfigMap. + - name: etc-stalwart + emptyDir: {} + # The image's data volume. An emptyDir because the data store, the blob + # store and the in-memory store are all external. + # + # OPEN MEASUREMENT: whether anything under this path has to survive a + # restart once all three stores are external. If it does, this needs a + # PVC per group. Not verified at runtime. + - name: var-lib-stalwart + emptyDir: {} + - name: tmp + emptyDir: {} + {{- if $root.Values.certificate.enabled }} + - name: mail-tls + secret: + secretName: tls-{{ include "stalwart.fullname" $root }}-mail + # The pods do not block on the certificate: a Secret that + # cert-manager has not written yet would otherwise hold every pod + # in ContainerCreating until the challenge completes. Stalwart + # falls back to a self-signed certificate on the mail ports in the + # meantime, which is the better of the two failures. + optional: true + {{- end }} + restartPolicy: Always +{{- end }} diff --git a/stalwart/values.schema.json b/stalwart/values.schema.json new file mode 100644 index 0000000..be2068b --- /dev/null +++ b/stalwart/values.schema.json @@ -0,0 +1,502 @@ +{ + "$schema": "https://json-schema.org/draft-07/schema#", + "title": "stalwart values", + "description": "Values schema for the stalwart chart (#68, guideline 12). additionalProperties is false on every chart-owned object level, so a misspelled key fails the render instead of being silently ignored. Three kinds of object stay open: the ones passed verbatim into the pod spec (probes, security contexts, free-form annotation maps), because Kubernetes owns their schema; the whole valkey block, because that schema belongs to the subchart; and 'global'. Two objects are user-extensible MAPS (ports, nodes) - there additionalProperties carries the value schema rather than false, which keeps a new entry legal and its contents strict. Values with no valid default (ingress.domain, ingress.clusterIssuer, dataStore.postgres.host, the secrets.*SecretRef paths) are enforced by required() in the templates, not here: they ship as null, so a JSON Schema 'required' array could never fire against them (#18).", + "type": "object", + "additionalProperties": false, + "properties": { + "global": { + "description": "Helm's conventional cross-chart values. Unused by this chart, kept open so an umbrella install cannot break on it - and with a subchart present that is not hypothetical: whatever is set here reaches valkey too.", + "type": "object" + }, + "scaleDown": { + "description": "true renders every node group's StatefulSet with replicas: 0 and overrides every nodes..replicas. Services, Ingress, Secrets and the Certificate stay in place, so no certificate is re-issued.", + "type": "boolean" + }, + "limitFactor": { + "description": "Chart-wide default limit factor for every node group; a group's resources.limitFactor wins over it.", + "type": ["number", "null"], + "exclusiveMinimum": 0 + }, + "secrets": { + "type": "object", + "additionalProperties": false, + "properties": { + "dataStoreSecretRef": { + "description": "op:// path of the item carrying the field 'password'. Only the password: authUsername is a plain String on the DataStore object with no secret form, so the username is the public value dataStore.postgres.username.", + "type": ["string", "null"] + }, + "recoveryAdminSecretRef": { + "description": "op:// path of the item carrying the field 'recovery-admin' with the complete 'admin:' value of STALWART_RECOVERY_ADMIN. null switches the variable off, which is the correct end state once a permanent administrator exists.", + "type": ["string", "null"] + }, + "s3SecretRef": { + "description": "op:// path of the item carrying 'access-key' and 'secret-key'. Exposed to the container as environment variables for the BlobStore object in the database to reference; the chart itself does not configure the blob store.", + "type": ["string", "null"] + } + } + }, + "dataStore": { + "description": "The only part of Stalwart this chart configures: the contents of config.json, which is exactly the DataStore object.", + "type": "object", + "additionalProperties": false, + "properties": { + "postgres": { + "type": "object", + "additionalProperties": false, + "properties": { + "host": { + "description": "REQUIRED (enforced by required() in the template).", + "type": ["string", "null"] + }, + "port": { + "type": "integer", + "minimum": 1, + "maximum": 65535 + }, + "database": { + "type": "string", + "minLength": 1 + }, + "username": { + "description": "Rendered into the ConfigMap as authUsername. Public by necessity - see secrets.dataStoreSecretRef.", + "type": "string", + "minLength": 1 + }, + "tls": { + "type": "object", + "additionalProperties": false, + "properties": { + "enable": { + "description": "Rendered as the object's useTls field. Defaults to true here, the opposite of upstream's default.", + "type": "boolean" + }, + "allowInvalidCerts": { + "description": "Accepting an invalid certificate makes TLS obfuscation rather than protection. Only ever a temporary diagnostic.", + "type": "boolean" + } + } + }, + "poolMaxConnections": { + "type": "integer", + "minimum": 1, + "maximum": 8192 + }, + "timeoutMs": { + "description": "MILLISECONDS as an integer, rendered into config.json as the 'timeout' field. Upstream's object encoding: 'A duration is an integer count of milliseconds... Neither accepts a string.' The key is named for its unit so that a '15s' is rejected here rather than by the server at startup. Integer-typed on purpose: a string form cannot be accepted at all.", + "type": "integer", + "minimum": 1 + }, + "options": { + "description": "Extra libpq connection options, passed through verbatim. null omits the field.", + "type": ["string", "null"] + } + } + } + } + }, + "bootstrap": { + "description": "Recovery mode, which a first install needs because this chart always renders config.json and the bootstrap wizard only appears when that file is absent.", + "type": "object", + "additionalProperties": false, + "properties": { + "enabled": { + "description": "Sets STALWART_RECOVERY_MODE=1: management HTTP on 8080 only, every mail port closed. true for the first install, then false. Leaving it on keeps the mail ports shut while every Kubernetes object looks healthy.", + "type": "boolean" + }, + "logLevel": { + "description": "STALWART_RECOVERY_MODE_LOG_LEVEL. No effect once bootstrap.enabled is false. Not enumerated: the accepted set is upstream's tracing level parser, which this chart has not pinned down.", + "type": "string", + "minLength": 1 + } + } + }, + "initImage": { + "description": "The init container that seeds config.json into the writable config volume. An auxiliary image, so it is pinned here rather than taken from appVersion (guideline 3).", + "type": "object", + "additionalProperties": false, + "properties": { + "repository": { + "type": "string", + "minLength": 1 + }, + "tag": { + "type": "string", + "minLength": 1 + } + } + }, + "ports": { + "description": "Port name -> port spec. A user-extensible map, so additionalProperties carries the value schema instead of false: adding 587 or 4190 is a legal, additive change. containerPort is what the application binds (and what the NetworkListener object in the database must say); nodePort is what the cluster publishes. They are different numbers here and are not interchangeable.", + "type": "object", + "minProperties": 1, + "additionalProperties": { + "type": "object", + "additionalProperties": false, + "required": ["containerPort"], + "properties": { + "containerPort": { + "type": "integer", + "minimum": 1, + "maximum": 65535 + }, + "nodePort": { + "description": "Required while public is true (checked in the template). Must be inside the API server's --service-node-port-range, default 30000-32767.", + "type": ["integer", "null"], + "minimum": 1, + "maximum": 65535 + }, + "protocol": { + "type": "string", + "enum": ["TCP", "UDP", "SCTP"] + }, + "public": { + "description": "true renders a NodePort Service for this port, shared by every node group that exposes it.", + "type": "boolean" + } + } + } + }, + "service": { + "type": "object", + "additionalProperties": false, + "properties": { + "externalTrafficPolicy": { + "description": "Enumerated, and Local is admissible only in a topology where a pod runs on every node that receives mail. In this deployment no Stalwart pod is scheduled on a control-plane node while the HA proxy delivers to the control-plane nodes, so Local would drop every packet - not some. See values.yaml.", + "type": "string", + "enum": ["Cluster", "Local"] + }, + "annotations": { + "description": "Extra annotations for every Service this chart renders. Free-form keys by nature, so this object stays open.", + "type": "object" + } + } + }, + "nodes": { + "description": "Cluster-role name -> node group. A MAP and not a list, so that an override never depends on a position: with a list, inserting a group would silently repoint every existing --set nodes[n]... at the wrong one. The key is passed in STALWART_ROLE and a ClusterRole object of exactly that name must exist in the database - if it does not, the node fail-opens into a full node with every listener AND every task, while staying Running with a green probe. There is deliberately no 'tasks' key: that is a property of the database object and a values key that did nothing would be worse than its absence.", + "type": "object", + "minProperties": 1, + "$comment": "The two groups the chart ships are spelled out under properties rather than left to additionalProperties alone, and that is not redundancy: ci/run-quantity-render-test.sh discovers a chart's resources blocks by walking 'properties' only, so a resources block reachable solely through additionalProperties is invisible to it - and the test then fails the chart for declaring none while its templates call the helper. Writing them out gives that test two real --set paths (nodes.full.resources, nodes.mx.resources). additionalProperties keeps a user-added group legal and equally strict. Keep the three in sync; resources and env are $refs precisely to limit how far they can drift.", + "properties": { + "full": { + "type": "object", + "additionalProperties": false, + "required": ["exposedPorts"], + "properties": { + "replicas": { + "description": "0 is allowed and scales the group down; the chart-global scaleDown wins over it.", + "type": "integer", + "minimum": 0 + }, + "exposedPorts": { + "$ref": "#/definitions/exposedPorts" + }, + "resources": { + "$ref": "#/definitions/resources" + }, + "env": { + "$ref": "#/definitions/env" + } + } + }, + "mx": { + "type": "object", + "additionalProperties": false, + "required": ["exposedPorts"], + "properties": { + "replicas": { + "description": "Ships as 0. Raising it before the 'mx' ClusterRole exists in the database produces a SECOND FULL NODE rather than an SMTP-only one, because a node whose role is not found enables every listener and every task.", + "type": "integer", + "minimum": 0 + }, + "exposedPorts": { + "$ref": "#/definitions/exposedPorts" + }, + "resources": { + "$ref": "#/definitions/resources" + }, + "env": { + "$ref": "#/definitions/env" + } + } + } + }, + "additionalProperties": { + "type": "object", + "additionalProperties": false, + "required": ["exposedPorts"], + "properties": { + "replicas": { + "type": "integer", + "minimum": 0 + }, + "exposedPorts": { + "$ref": "#/definitions/exposedPorts" + }, + "resources": { + "$ref": "#/definitions/resources" + }, + "env": { + "$ref": "#/definitions/env" + } + } + } + }, + "networkPolicy": { + "type": "object", + "additionalProperties": false, + "properties": { + "enabled": { + "description": "On by default. Only a real boundary where the cluster's CNI enforces NetworkPolicies; an unenforced policy is accepted by the API server and filters nothing.", + "type": "boolean" + }, + "probeSources": { + "description": "Source CIDRs allowed to reach the http port, where the kubelet's probe traffic has to be permitted - probes come from the IP of the worker node running the pod. EMPTY MEANS OPEN (the rule renders without a 'from' selector), which is the deliberate choice: a guessed CIDR that misses the real node addresses blocks every probe, and a pod that never becomes Ready reads as a broken application rather than as a policy.", + "type": ["array", "null"], + "items": { + "type": "string", + "minLength": 1 + } + }, + "allowedNamespaces": { + "description": "Namespaces allowed to reach the http port in addition to the release's own, matched on the kubernetes.io/metadata.name label Kubernetes sets itself. The ingress controller's namespace belongs here as soon as probeSources is non-empty, or the Ingress goes dark. A name that does not exist matches nothing and is silently ineffective.", + "type": ["array", "null"], + "items": { + "type": "string", + "minLength": 1 + } + }, + "egress": { + "description": "Egress is restricted by PORT, not by destination: a NetworkPolicy matches CIDRs and selectors and never hostnames, so no host value from this file can appear in it.", + "type": "object", + "additionalProperties": false, + "properties": { + "dns": { + "type": "boolean" + }, + "smtp": { + "description": "Outbound port 25 to any destination, required for delivery. Uniform for every group on purpose - the chart does not know which groups run the outboundMta task, and the failure mode of guessing is mail silently not leaving.", + "type": "boolean" + }, + "extraPorts": { + "description": "Additional outbound TCP ports beyond the data store, S3 and Valkey ports the chart derives. Add 443 for outbound HTTPS (DNS-01 provider APIs, AI model endpoints, remote lookup lists).", + "type": ["array", "null"], + "items": { + "type": "integer", + "minimum": 1, + "maximum": 65535 + } + } + } + } + } + }, + "externalServices": { + "description": "KUBERNETES ONLY - these do not configure Stalwart. The blob store and the in-memory store are objects in the database. The chart uses the ports for the egress rules, the valkey host to decide whether the in-memory store has an address at all, and both hosts to print the WebUI checklist in NOTES.txt.", + "type": "object", + "additionalProperties": false, + "properties": { + "s3": { + "$ref": "#/definitions/externalService" + }, + "valkey": { + "$ref": "#/definitions/externalService" + } + } + }, + "certificate": { + "description": "The cert-manager Certificate for the MAIL ports. The Ingress certificate covers only the WebUI and JMAP; the HA proxy terminates no TLS, so Stalwart presents this one itself for STARTTLS on 25 and implicit TLS on 465/993. This object only obtains the files - pointing Stalwart at them is a TLS object in the database.", + "type": "object", + "additionalProperties": false, + "properties": { + "enabled": { + "type": "boolean" + }, + "clusterIssuer": { + "description": "null falls back to ingress.clusterIssuer. Usually a DIFFERENT issuer: the same reasoning that rules out Stalwart's own ACME rules out HTTP-01 here, because port 80 does not reach this cluster for the mail hostname, so a DNS-01 issuer is normally required.", + "type": ["string", "null"] + }, + "extraDnsNames": { + "description": "Additional names for the mail certificate; ingress.domain is always included. For the hostnames other MTAs and clients actually connect to when they differ from the WebUI host.", + "type": ["array", "null"], + "items": { + "type": "string", + "minLength": 1 + } + }, + "mountPath": { + "description": "Where the issued certificate is mounted read-only. A top-level path so no mount is nested inside the config emptyDir. The TLS object in the database points at /tls.crt and /tls.key.", + "type": "string", + "minLength": 1 + } + } + }, + "ingress": { + "type": "object", + "additionalProperties": false, + "properties": { + "enabled": { + "description": "Gates the Ingress template only. ingress.domain stays REQUIRED either way, because the mail Certificate's dnsNames reads it too - switching the Ingress off would otherwise render a certificate with no name in it (guideline 12.1). clusterIssuer becomes unnecessary only if certificate.clusterIssuer is set, since that falls back to it.", + "type": "boolean" + }, + "clusterIssuer": { + "description": "REQUIRED (enforced by required() in the template).", + "type": ["string", "null"] + }, + "domain": { + "description": "REQUIRED (enforced by required() in the template), and read in two places - the Ingress host and the mail Certificate.", + "type": ["string", "null"] + }, + "className": { + "type": ["string", "null"] + }, + "nodeGroup": { + "description": "Which node group the Ingress routes to, through that group's own http Service. Must be a key of nodes: and must expose http; both are checked in the template. A single group on purpose - the management surface is not safe to spread across a group that may not run the management tasks, and a port-label selector would send each request to a random group.", + "type": "string", + "minLength": 1 + }, + "annotations": { + "description": "Extra Ingress annotations, merged with the cert-manager annotation the chart always sets. Free-form keys by nature, so this object stays open.", + "type": "object" + } + } + }, + "securityContext": { + "description": "May be null / empty at any level: the chart then falls back to its hardening defaults (#99). THIS CHART'S FALLBACK REPRODUCES ITS DEVIATION, not the repo standard - capabilities.add carries NET_BIND_SERVICE, because the image sets 'setcap cap_net_bind_service=+ep' on its binary and the kernel then fails the execve itself when the bounding set does not carry the capability. An erased block that fell back to the standard 'add: []' would stop the chart from starting. uid/gid 2000 is the image's own user, and there is deliberately no fsGroup because this chart mounts no PVC.", + "type": ["object", "null"], + "additionalProperties": false, + "properties": { + "pod": { + "description": "Merged onto the chart's pod hardening defaults; open because the chart does not interpret the individual fields. seccompProfile lives here so it also covers the init container.", + "type": ["object", "null"] + }, + "container": { + "description": "Merged onto the chart's container hardening defaults and applied to BOTH the server and the config-seeding init container; open because the chart does not interpret the individual fields.", + "type": ["object", "null"] + } + } + }, + "livenessProbe": { + "$ref": "#/definitions/probe" + }, + "readinessProbe": { + "$ref": "#/definitions/probe" + }, + "startupProbe": { + "$ref": "#/definitions/probe" + }, + "valkey": { + "description": "Values of the valkey subchart (the Valkey project's own chart), passed straight through. Open on purpose and at every level: this chart owns neither the keys nor their meaning, and a closed copy would reject whatever the subchart adds in its next release - the exact failure a schema exists to prevent, pointed at the wrong chart. This chart reads exactly one of them, 'enabled', which is the dependency condition. Two of upstream's defaults fall short of this repo's conventions and are documented in values.yaml rather than patched here.", + "type": "object" + } + }, + "definitions": { + "exposedPorts": { + "description": "Keys of ports: this group may be reached on. Checked against ports: in the template, which also requires 'http' - all three probes target it, so a group without it would never become Ready. Not a copy of the database's listener configuration but a statement of its own, which is why a disagreement in either direction is harmless and why it blunts the fail-open described on nodes:.", + "type": "array", + "minItems": 1, + "items": { + "type": "string", + "minLength": 1 + } + }, + "externalService": { + "type": ["object", "null"], + "additionalProperties": false, + "properties": { + "host": { + "description": "For valkey, empty plus valkey.enabled resolves to the subchart's Service; empty with the subchart off and more than one Stalwart pod aborts the render, because Stalwart's cluster coordinator rides on the in-memory store connection. Does not point Stalwart at anything by itself.", + "type": ["string", "null"] + }, + "port": { + "description": "Used for the egress rule of every NetworkPolicy.", + "type": "integer", + "minimum": 1, + "maximum": 65535 + } + } + }, + "resources": { + "description": "May be null / empty: the chart then falls back to that GROUP's default requests and computed limits (#99) instead of rendering a container without resource accounting. The per-group fallback matters here - 'mx' is deliberately lighter than 'full'.", + "type": ["object", "null"], + "additionalProperties": false, + "properties": { + "limitFactor": { + "type": "number", + "exclusiveMinimum": 0 + }, + "requests": { + "$ref": "#/definitions/resourceList" + }, + "limits": { + "$ref": "#/definitions/resourceList" + } + } + }, + "resourceList": { + "description": "Both spellings of the ephemeral-storage key are accepted because the resources helper normalizes camelCase to the Kubernetes key.", + "type": ["object", "null"], + "additionalProperties": false, + "properties": { + "cpu": { + "type": ["string", "number", "null"] + }, + "memory": { + "type": ["string", "number", "null"] + }, + "ephemeral-storage": { + "type": ["string", "number", "null"] + }, + "ephemeralStorage": { + "type": ["string", "number", "null"] + } + } + }, + "env": { + "description": "Additive environment entries for a node group's container. Additive means additive: an entry repeating a name the chart already sets does not replace it - at install both reach the pod and the later one wins, but on an existing release Kubernetes merges env by name, the pair collapses to the chart's own value, and helm upgrade still reports success.", + "type": ["array", "null"], + "items": { + "type": "object", + "additionalProperties": false, + "required": ["name"], + "properties": { + "name": { + "type": "string" + }, + "value": { + "type": "string" + }, + "valueFrom": { + "type": "object", + "additionalProperties": false, + "properties": { + "secretKeyRef": { + "$ref": "#/definitions/keyRef" + }, + "configMapKeyRef": { + "$ref": "#/definitions/keyRef" + } + } + } + } + } + }, + "keyRef": { + "type": "object", + "additionalProperties": false, + "required": ["name", "key"], + "properties": { + "name": { + "type": "string" + }, + "key": { + "type": "string" + } + } + }, + "probe": { + "description": "Merged onto the chart's probe defaults and rendered as a container probe; open because the chart does not interpret the individual fields. May be null / empty, which means the defaults apply (#99) rather than the probe disappearing. The defaults carry the probe's CONTEXT - the /healthz paths, the port name AND the calculated intervals: Stalwart rate-limits anonymous /healthz requests to 100 per 60s per SOURCE IP, probes arrive from the node IP, so every pod on a node shares one bucket. 20/20/10 costs 6 requests/min/pod and leaves room for roughly 16 pods per node; 10/10/5 would allow about 8. Tightening these produces 429s, and a 429 on liveness is a restart loop.", + "type": ["object", "null"] + } + } +} diff --git a/stalwart/values.yaml b/stalwart/values.yaml new file mode 100644 index 0000000..ae06b03 --- /dev/null +++ b/stalwart/values.yaml @@ -0,0 +1,676 @@ +# Stalwart — a cluster-capable mail server (SMTP, IMAP, POP3, JMAP, ManageSieve). +# +# READ THIS FIRST: THIS CHART CONFIGURES ALMOST NOTHING. +# +# Since v0.16 Stalwart keeps its entire configuration — over 2400 settings in +# 117 object types, including every listener, the blob store, the in-memory +# store, TLS objects, domains and the cluster roles — INSIDE the data store, +# managed over the JMAP API (WebUI or stalwart-cli). The only thing left on +# disk is a small config.json that names the data store and nothing else: +# "It only needs to contain the DataStore object" +# (https://stalw.art/docs/configuration/declarative-deployments). +# +# So this chart renders config.json, the workloads with their STALWART_ROLE, +# the Services, the NetworkPolicies, the Ingress and a cert-manager +# Certificate. Everything else is operator work in the WebUI, and the values +# below say for each block whether it configures Stalwart or only Kubernetes. +# A value that only describes something to Kubernetes is marked as such rather +# than left to look like application configuration. + +# Scale the whole chart down without uninstalling it: scaleDown: true renders +# every StatefulSet with replicas: 0 and takes precedence over every +# nodes..replicas. Services, Ingress, Secrets and the Certificate stay +# in place, so no certificate is re-issued when you scale back up. +scaleDown: false + +# Chart-wide default for the limit factor of every node group. A group may +# override it as nodes..resources.limitFactor, which always wins. Memory +# and ephemeral-storage limits are computed as limitFactor x the request; a CPU +# limit is only set when configured explicitly. +limitFactor: 3 + +secrets: + # op:// path of the 1Password item carrying the data-store password in the + # field "password". + # + # ONLY the password. The username cannot live here, and that is an upstream + # constraint rather than a choice: on the DataStore object authSecret has the + # type SecretKeyOptional (which has an EnvironmentVariable variant, and that + # is what this chart uses) while authUsername is a plain String with no + # secret form at all. So the username is the public value + # dataStore.postgres.username below and ends up in the ConfigMap, while the + # password never does. + dataStoreSecretRef: null + + # op:// path of the 1Password item carrying the field "recovery-admin" with + # the COMPLETE value of STALWART_RECOVERY_ADMIN, i.e. "admin:" in + # one string — the same shape as valkey's auth-conf field. The chart does not + # assemble it from two fields, because a half-built credential ("admin:" with + # an empty password) is accepted by the server as a working back door. + # + # Why it is worth pinning at all: without it Stalwart generates a temporary + # administrator password on every bootstrap or recovery start and prints it to + # stdout — in Kubernetes that means a fresh password in the pod log on every + # restart, visible to anyone who can read logs, and lost as soon as it + # scrolls. Set to null to switch the variable off entirely once a permanent + # administrator exists in the database; that is the documented end state, see + # NOTES.txt. + recoveryAdminSecretRef: null + + # op:// path of the 1Password item for the S3 blob store, carrying the fields + # "access-key" and "secret-key". + # + # This chart does NOT configure the blob store — that object lives in the + # database. What it does is expose both fields to the container as the + # environment variables STALWART_S3_ACCESS_KEY and STALWART_S3_SECRET_KEY, so + # that the BlobStore object you create in the WebUI can reference them + # instead of storing the credentials in the database: + # accessKey: {"@type":"EnvironmentVariable","variableName":"STALWART_S3_ACCESS_KEY"} + # secretKey: {"@type":"EnvironmentVariable","variableName":"STALWART_S3_SECRET_KEY"} + # Both fields accept that variant (accessKey is PublicStringOptional, + # secretKey is SecretKeyOptional; both offer Value, EnvironmentVariable and + # File). Leave null when the blob store is not S3 or when you prefer to keep + # the credentials in the database — the variables are then not set and + # nothing references them. + s3SecretRef: null + +# --------------------------------------------------------------------------- +# config.json — the ONLY part of Stalwart this chart actually configures +# --------------------------------------------------------------------------- +dataStore: + postgres: + # REQUIRED, no default (enforced by required() in the template). + host: null + port: 5432 + database: stalwart + # Public on purpose — see secrets.dataStoreSecretRef above for why this is + # not a secret reference. It is rendered into the ConfigMap. + username: stalwart + tls: + # Rendered as the object's "useTls" field. The names differ because this + # chart groups the two TLS switches that upstream keeps flat; the mapping + # is tls.enable -> useTls and tls.allowInvalidCerts -> allowInvalidCerts. + # + # Note the default is the OPPOSITE of upstream's (false). A mail server's + # data store carries every message's metadata, and this chart would + # rather fail to connect to a plaintext-only Postgres than reach it + # silently unencrypted. + enable: true + # Accepting an invalid certificate turns TLS into obfuscation: the + # connection is encrypted against a passive listener and wide open to an + # active one. Only ever a temporary diagnostic. + allowInvalidCerts: false + poolMaxConnections: 10 + # MILLISECONDS, as an integer — not "15s". + # + # This is not a styling preference. Stalwart's object encoding states it + # outright: "A duration is an integer count of milliseconds, and a size is + # an integer count of bytes. Neither accepts a string." + # (https://stalw.art/docs/configuration/object-encoding). The DataStore + # reference gives this field as "Duration? default: 15000". A config.json + # carrying "15s" is rejected by the server at startup, so the key is named + # for its unit instead of accepting a suffix the file cannot hold. + timeoutMs: 15000 + # Extra libpq connection options, passed through verbatim as the object's + # "options" field. null omits the field. + options: null + +# --------------------------------------------------------------------------- +# First start: Stalwart needs recovery mode when config.json is provided +# --------------------------------------------------------------------------- +bootstrap: + # Sets STALWART_RECOVERY_MODE=1 on every node group. + # + # WHY THIS EXISTS, AND WHY IT IS NOT OPTIONAL ON A FIRST INSTALL. The setup + # wizard everyone reaches for runs in BOOTSTRAP mode, and bootstrap mode is + # entered only when there is no config.json: "The first time Stalwart is + # started without a config.json, it enters bootstrap mode" + # (https://stalw.art/docs/configuration/bootstrap-mode). This chart always + # renders one, so the wizard never appears. Against an empty database that + # leaves a server with no listeners, no domain and no administrator, and + # nothing to fix it with. + # + # The documented path for exactly this case is recovery mode: "template + # config.json onto the host, start Stalwart once with STALWART_RECOVERY_MODE=1 + # and a STALWART_RECOVERY_ADMIN supplied from a secrets manager, run + # stalwart-cli apply against the recovery listener to load the initial + # configuration, and then restart Stalwart without the recovery variables" + # (https://stalw.art/docs/configuration/declarative-deployments). Recovery + # mode brings up the management HTTP endpoint on port 8080 — the WebUI + # included — and keeps every mail port closed. + # + # So: true for the first install, then false and upgrade again. Leaving it on + # is not a small untidiness — the mail ports stay shut while the Services and + # the Ingress look perfectly healthy, which is the loudest-looking silent + # failure this chart has. NOTES.txt prints a warning for as long as it is on. + enabled: false + # Log verbosity while recovery mode is on (STALWART_RECOVERY_MODE_LOG_LEVEL). + # Has no effect once bootstrap.enabled is false. + logLevel: info + +# --------------------------------------------------------------------------- +# Ports. KUBERNETES ONLY — these numbers do not reach Stalwart. +# --------------------------------------------------------------------------- +# THE DUPLICATION BELOW CANNOT BE AVOIDED, SO IT IS WRITTEN DOWN INSTEAD. +# +# Every listener Stalwart binds is a NetworkListener object in the database. +# This chart cannot create those objects, so containerPort here is a second +# copy of a decision that is really made in the WebUI. If the two disagree, the +# Service points at a port nothing listens on: connections are refused or time +# out, every pod stays Ready, and no object reports a problem. Check both sides +# whenever you touch one. +# +# TWO NUMBERS PER ENTRY, AND THEY ARE NOT INTERCHANGEABLE: +# containerPort — what the application binds inside the pod, and what the +# NetworkListener object in the database must say. +# nodePort — what the cluster publishes on every node, and what the HA +# proxy in front of the cluster connects to. +# The Service maps one onto the other: nodePort 30025 -> targetPort 25. +# +# WHY THE APPLICATION BINDS THE ORDINARY 25/465/993. An earlier draft had it +# bind 30025/30465/30993 so that nothing privileged was ever bound and the +# NET_BIND_SERVICE capability could be dropped. That reasoning collapsed: the +# image ships "setcap cap_net_bind_service=+ep" on the binary, which makes it a +# capability-dumb binary, and the kernel then fails the execve ITSELF when the +# bounding set does not carry the capability — before the program binds +# anything. The capability has to be granted either way (see securityContext +# below), so high ports bought no hardening at all. What the ordinary numbers +# buy instead is predictability: the listener objects an operator creates in +# the WebUI carry the numbers from every page of Stalwart's documentation and +# from the image's own EXPOSE list, which takes most of the surprise out of the +# duplication above. +# +# The nodePorts must be inside the API server's --service-node-port-range +# (default 30000-32767). 30025/30465/30993 are, with the default — UNVERIFIED +# against this cluster's actual setting. +# +# Only these three plus HTTP are published. 587, 143, 110, 995 and 4190 are +# deliberately absent and can be added later without a breaking change: add an +# entry here and list it in the groups that should answer on it. +ports: + smtp: + containerPort: 25 + nodePort: 30025 + protocol: TCP + public: true + submissions: + containerPort: 465 + nodePort: 30465 + protocol: TCP + public: true + imaps: + containerPort: 993 + nodePort: 30993 + protocol: TCP + public: true + http: + # The management/JMAP/WebUI port, and the port the probes use. Never + # published as a NodePort: it is reached through the Ingress (ClusterIP + # Service) and by the kubelet. + containerPort: 8080 + protocol: TCP + public: false + +# The init container that seeds /etc/stalwart/config.json out of the ConfigMap. +# Pinned here rather than hardcoded in the template, and reviewed on every +# app-update round, because it is an auxiliary image and its tag does not come +# from appVersion (README, guideline 3). +initImage: + repository: docker.io/library/busybox + tag: "1.37.0-uclibc" + +service: + # Cluster, and Local is not an option here — this is a property of the + # deployment's topology, not a preference. + # + # externalTrafficPolicy: Local only forwards to pods on the node that + # received the packet. Mail enters through an HA proxy that distributes + # 25/465/993 across the three control-plane nodes, and no Stalwart pod is + # ever scheduled on a control-plane node — so under Local EVERY packet would + # be dropped, not some. + # + # The price of Cluster is that kube-proxy masquerades the source address to + # the receiving node's IP (it has to: the reply would otherwise leave through + # a different node than the one the sender holds its connection with). For a + # mail server a lost source address is not cosmetic; it switches off SPF, + # takes DMARC with it, makes every blocklist report "clean", collapses + # per-IP rate limits onto one address, removes greylisting's key, and makes + # the auto-ban lock out every sender at once by banning the node IP. The + # Received: chain becomes worthless, which is the one item on that list that + # destroys evidence retroactively instead of just failing. + # + # What pays that price back is the PROXY protocol, and only because of this + # topology: the HA proxy terminates the inbound connection and opens its OWN + # to the node, so it can prepend a PROXY v2 header on that connection — for + # port 25 as well, where no remote mail server would ever send one. The real + # client address then travels in the header and the masquerading stops + # mattering. This is a MANDATORY companion step, not an optimisation; the + # wiki page has the all-or-nothing warning that goes with it. + externalTrafficPolicy: Cluster + # Extra annotations for every Service this chart renders (ClusterIP and + # NodePort alike). Free-form by nature. + annotations: {} + +# --------------------------------------------------------------------------- +# Node groups. One StatefulSet, one headless Service and one NetworkPolicy each. +# --------------------------------------------------------------------------- +# A MAP, NOT A LIST, and on purpose: with a list every override would be +# index-based (--set nodes[1].replicas=2), so inserting a group later would +# silently repoint every existing override at the wrong group. +# +# The key is the cluster role name and goes into STALWART_ROLE. A ClusterRole +# object of exactly that name has to exist in the database — see the fail-open +# warning below, which is the most important paragraph in this file. +# +# THERE IS NO nodes..tasks KEY. Which tasks and listeners a role runs is +# a property of the ClusterRole object in the database, and this chart cannot +# write it. A values key that looked like it set them and did not would be +# worse than its absence. +# +# FAIL-OPEN: A NODE WHOSE ROLE IS MISSING FROM THE DATABASE BECOMES A FULL NODE. +# +# From the source, not the documentation. The bootstrap registry looks a role +# up by name; when it finds none it records a non-fatal error and leaves the +# role unset, and the listener check then reads +# bp.role.as_ref().is_none_or(|r| ...) +# which yields true for EVERY listener when the role is None. The same holds +# for the task set. So a typo in a group name here, or a rename here without +# the matching rename in the database, turns that group into a node that binds +# everything — the mx group would serve IMAP and the admin interface. The pod +# is Running, the log holds one line ('Cluster role "mx" not found in +# registry'), and the readiness probe is GREEN. Kubernetes cannot detect it. +# +# Three things in this chart contain that failure, and they are the reason the +# layout looks the way it does: mx ships with replicas: 0, the per-port +# Services publish only what was asked for, and the NetworkPolicy is a ceiling +# on reachability that holds no matter which ports the process actually bound. +# Documented as a trap rather than explained away. +nodes: + # Everything: all tasks, all listeners. The group the Ingress points at. + full: + # 0 is allowed and scales this group down; the chart-global scaleDown wins. + replicas: 1 + # Which ports this group may be reached on. NOT a copy of the listener + # configuration in the database but a statement of its own: "this group is + # reachable here and nowhere else". That is why a disagreement in either + # direction is harmless — a role that binds more is unreachable on the + # extra ports, and a policy that permits more has nothing listening — and + # it is exactly what takes the edge off the fail-open above. + # + # Every group needs http, including mx: it is the port all three probes + # use. It is not published for mx. + exposedPorts: [smtp, submissions, imaps, http] + resources: + requests: + cpu: 200m + memory: 512Mi + ephemeral-storage: 64Mi + # Additive environment entries for this group's container, appended to the + # ones the chart sets (STALWART_ROLE, STALWART_HOSTNAME and the secret-fed + # ones). Supports the value, secretKeyRef and configMapKeyRef forms and is + # rendered through tpl. + # + # ADDITIVE MEANS ADDITIVE: an entry repeating a name the chart already sets + # does not replace it. At install both reach the pod and the later one wins; + # on an EXISTING release Kubernetes merges env by name, the pair collapses + # to the chart's own value, and helm upgrade still reports success. Do not + # use this to override STALWART_ROLE. + env: [] + # SMTP intake only. Add the matching ClusterRole in the database first: + # {"name":"mx","tasks":{"@type":"DisableAll"},"listeners":{"@type":"EnableSome", ...}} + mx: + # Zero until the role "mx" exists in the database. Raising this before the + # role is there does not fail — it produces a second full node (see + # fail-open above), which is the opposite of what this group is for. + replicas: 0 + exposedPorts: [smtp, http] + resources: + requests: + cpu: 100m + memory: 256Mi + ephemeral-storage: 64Mi + env: [] + +# --------------------------------------------------------------------------- +# NetworkPolicy — the ceiling on reachability, independent of what bound what +# --------------------------------------------------------------------------- +networkPolicy: + # On by default. Only a real boundary where the cluster's CNI enforces + # NetworkPolicies; an unenforced policy is accepted by the API server and + # filters nothing. + enabled: true + # Source CIDRs allowed to reach the http port, in addition to + # allowedNamespaces. This is where the kubelet's probe traffic has to be + # permitted: probes come from the IP of the WORKER node running the pod, an + # address this chart cannot know. + # + # EMPTY MEANS OPEN, not blocked. With no entry the http rule is rendered + # without a "from" selector, so the port is reachable from anywhere the CNI + # routes to. That is the deliberate choice between two bad defaults: a + # guessed CIDR that excludes the real node addresses blocks every probe, and + # a pod that never becomes Ready reads as a broken application rather than as + # a policy. http is not a NodePort, so "open" here means open inside the + # cluster, not from the internet. Narrow it by listing the worker node IPs + # (e.g. ["10.0.1.11/32", "10.0.1.12/32"]). + # + # And mind the companion trap: once this list is non-empty the http rule is + # restricted, which cuts off the ingress controller too unless its namespace + # is in allowedNamespaces below. + probeSources: [] + # Namespaces allowed to reach the http port, matched on the + # kubernetes.io/metadata.name label Kubernetes sets on every namespace + # itself. The release's own namespace is always allowed. Put the ingress + # controller's namespace here (e.g. ["ingress-nginx"]) as soon as + # probeSources is set. A name that does not exist matches nothing and is + # silently ineffective. + allowedNamespaces: [] + # Egress is restricted BY PORT, not by destination, and the reason is a limit + # of the object rather than laziness: a NetworkPolicy matches ipBlock CIDRs + # and pod/namespace selectors, never hostnames — so dataStore.postgres.host + # and externalServices.*.host cannot appear in it. Each rule below therefore + # permits its port to any destination. What it still buys is real: a + # compromised pod cannot open arbitrary ports outbound. + # + # Outbound SMTP is the one that must stay wide: delivering mail means + # connecting to port 25 on any host on the internet. + egress: + # DNS (UDP and TCP 53) to any destination. Switching this off breaks + # everything, including MX lookups and SPF. + dns: true + # Outbound SMTP on port 25 to any destination — required for delivery. + # Deliberately NOT derived per group from the outboundMta task: this chart + # does not know which tasks a role runs, the value would drift away from + # the database, and the failure mode would be mail silently not leaving. + # So it is uniform for every group. + smtp: true + # Additional outbound TCP ports, beyond the data store, S3 and Valkey ports + # the chart already derives from the values above. Add 443 here if the + # deployment needs outbound HTTPS (ACME over DNS-01 through a provider API, + # an AI model endpoint, a remote lookup list). + extraPorts: [] + +# --------------------------------------------------------------------------- +# External services — KUBERNETES ONLY. These do not configure Stalwart. +# --------------------------------------------------------------------------- +# The blob store and the in-memory store are objects in the database and are +# created in the WebUI. What the chart uses these values for is exactly three +# things, and nothing else: +# - the port goes into the egress rule of every NetworkPolicy, +# - the valkey host decides whether the in-memory store has an address at all +# (see the fail below), and +# - both hosts are printed in NOTES.txt as the addresses to enter in the +# WebUI, so the installation checklist is not a separate document. +# Setting a host here does not point Stalwart at it. +externalServices: + s3: + host: "" + port: 443 + valkey: + # Empty plus valkey.enabled: true resolves to the subchart's Service, + # "-valkey". Empty with the subchart off and more than one + # Stalwart pod ABORTS THE RENDER with a message naming both values, because + # that combination is a cluster without an in-memory store: from v0.16 the + # coordinator's Default variant "reuses the Redis connection already + # configured on the in-memory store", so a multi-node install has no + # coordination path at all. Failing the render is the loud version of a + # cluster that comes up and then does not agree with itself. + host: "" + port: 6379 + +# --------------------------------------------------------------------------- +# TLS for the mail ports — cert-manager, not Stalwart's own ACME +# --------------------------------------------------------------------------- +# Why not Stalwart's built-in ACME: the HA proxy forwards 25, 465 and 993, and +# NOT 80, so an HTTP-01 challenge answered by Stalwart is unreachable from +# outside. DNS-01 inside Stalwart would work but would duplicate what +# cert-manager already does in this cluster. +# +# Why a certificate is needed at all when there is an Ingress: the Ingress +# covers only the WebUI and JMAP. The HA proxy terminates no TLS, so Stalwart +# itself has to present the certificate for STARTTLS on 25 and implicit TLS on +# 465 and 993. +certificate: + enabled: true + # Cluster issuer for the MAIL certificate. null falls back to + # ingress.clusterIssuer. + # + # MIND THE CHALLENGE TYPE. The same reasoning that rules out Stalwart's ACME + # rules out an HTTP-01 issuer here: port 80 does not reach this cluster for + # the mail hostname. A DNS-01 issuer is usually the right answer, and it is + # usually a DIFFERENT issuer from the one the Ingress uses — which is why + # this is its own value instead of reusing ingress.clusterIssuer silently. + clusterIssuer: null + # Additional DNS names for the mail certificate. ingress.domain is always + # included, so this is for the hostnames clients and other MTAs actually + # connect to when they differ from the WebUI host — typically the MX name and + # the autoconfig names (mail., smtp., imap.). + extraDnsNames: [] + # Mount path of the issued certificate inside the container. A separate + # top-level path rather than something under /etc/stalwart, so there is no + # mount nested inside the config emptyDir. + # + # These two files are what the TLS object in the DATABASE has to point at: + # certificate: /etc/stalwart-tls/tls.crt + # privateKey: /etc/stalwart-tls/tls.key + mountPath: /etc/stalwart-tls + +ingress: + # Gates the whole Ingress template. ingress.domain stays REQUIRED either way: + # it is read by the Certificate's dnsNames as well, so switching the Ingress + # off would otherwise render a certificate with no name in it. Only + # ingress.clusterIssuer becomes unnecessary — and only if + # certificate.clusterIssuer is set, since that falls back to it. + enabled: true + # REQUIRED, no default. + clusterIssuer: null + # REQUIRED, no default. + domain: null + className: nginx + # Which node group the Ingress routes to. Must be a key of nodes: above, and + # that group must list http in its exposedPorts — both are checked, and the + # render aborts naming the value. It matters that this is a single group: the + # WebUI's setup and management screens are not safe to spread over a group + # that may not run the management tasks, and a Service selecting several + # groups would send every request to a random one of them. + nodeGroup: full + # Extra annotations for the Ingress; merged with the cert-manager + # cluster-issuer annotation the chart always sets. + annotations: {} + +# --------------------------------------------------------------------------- +# Hardening — chart-wide, applied to every node group +# --------------------------------------------------------------------------- +securityContext: + pod: + # uid/gid 2000 is the image's own "stalwart" user: the image already runs + # as non-root, so nothing has to be bent here. + runAsNonRoot: true + runAsUser: 2000 + runAsGroup: 2000 + # In the pod context so it also covers the init container that places + # config.json; a container-level profile would have to be repeated for + # every container and would be missed on the next one added. + seccompProfile: + type: RuntimeDefault + # No fsGroup and no fsGroupChangePolicy: this chart mounts no PVC. Both + # volumes are emptyDirs (state lives in Postgres, S3 and Valkey) and the + # kubelet creates those owned by the pod's user already. + container: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + runAsNonRoot: true + # DOCUMENTED DEVIATION from the repo's hardening baseline (README, + # guideline 5), forced by the stalwartlabs/stalwart image. Precedent for a + # justified capability: samba. + # + # NET_BIND_SERVICE IS REQUIRED TO *START* THE CONTAINER, NOT TO BIND A PORT. + # Both published image variants run + # setcap cap_net_bind_service=+ep /usr/local/bin/stalwart + # (Dockerfile.build at v0.16.24, line 164 for the glibc target and line 186 + # for the musl/-alpine one). The "e" in "+ep" sets the file's effective + # bit, which makes the binary a "capability-dumb binary" in the kernel's + # terms, and capabilities(7) then applies this check at execve time: + # + # "When executing a capability-dumb binary, the kernel checks if the + # process obtained all permitted capabilities that were specified in the + # file permitted set... If the process did not obtain the full set of + # file permitted capabilities, then execve(2) fails with the error + # EPERM." + # + # drop: [ALL] empties the bounding set, so the capability cannot be + # obtained, so the exec fails outright: + # exec /usr/local/bin/stalwart: operation not permitted + # The check runs BEFORE the program binds anything, and it does not ask + # whether the capability is needed. This is why the three escape routes + # that look obvious all fail for the same reason: high ports do not help, + # the -alpine image carries the identical setcap, and the + # net.ipv4.ip_unprivileged_port_start sysctl addresses binding rather than + # exec. + # + # AND THE SECOND HALF, WHICH IS WHY THIS LINE MUST NOT BE "CLEANED UP": + # THE CAPABILITY IS NEVER ACTUALLY USED. It is spent entirely on satisfying + # the execve check. Stalwart does bind 25/465/993 here, which are + # privileged — but inside a pod that needs no capability either way: the + # kubelet sets net.ipv4.ip_unprivileged_port_start=0 in the pod network + # namespace, so a non-root container binds low ports regardless (measured + # in k3d for template-chart, see its ports comment). So a hardening pass + # that greps for "a capability nobody uses" will find exactly this one and + # removing it stops the chart from starting at all. Do not remove it + # without first checking whether upstream still sets the file capability; + # the day that setcap disappears from Dockerfile.build is the day this + # deviation can go with it. + capabilities: + drop: + - ALL + add: + - NET_BIND_SERVICE + +# Probes for every node group, on the two separate endpoints the image +# provides. Values-configurable; an erased block falls back to these defaults +# rather than removing the probe. +# +# THE INTERVALS ARE CALCULATED, NOT TASTE. DO NOT TIGHTEN THEM WITHOUT REDOING +# THE ARITHMETIC BELOW. +# +# Stalwart applies an anonymous HTTP rate limit to /healthz as to everything +# else, and its default is 100 requests per 60 seconds KEYED ON THE SOURCE IP +# (registry default rate_limit_anonymous: count 100, period 60000ms). Kubelet +# probes arrive from the IP of the NODE running the pod, not from the pod, so +# every Stalwart pod on one node draws from the SAME bucket. Exceeding it +# returns 429, a 429 fails the probe, and failing liveness restarts the pod — +# a self-inflicted restart loop that gets worse the more pods a node holds. +# +# The budget per pod, with the values below: +# steady state liveness 60/20 = 3/min + readiness 60/20 = 3/min = 6/min +# while starting startup 60/10 = 6/min = 6/min +# The startup probe GATES liveness and readiness, so the three never run at +# once and 6 requests/min/pod is the worst case in both phases. Against a +# 100/60s bucket that leaves room for about 16 Stalwart pods per node before +# the limit is in sight. +# +# For comparison, the obvious 10/10/5 defaults would cost 12/min/pod in steady +# state and allow only about 8 pods per node — which is not far from a +# plausible deployment. That is the whole reason these numbers are 20/20/10. +# +# What the wider intervals cost, stated so the trade is visible: up to 20s +# before unreadiness removes a pod from its Services, and up to 60s +# (3 x 20s) before a hung pod is restarted. For a mail server both are +# acceptable — SMTP senders retry for days. +# +# WHY HTTP AND NOT A tcpSocket READINESS PROBE. A tcpSocket probe on the mail +# port would bypass the bucket entirely, and it was considered for exactly that +# reason. It is rejected on three grounds, none of them about convenience: +# 1. It would be GREEN in precisely the failure this chart is built to +# contain. A node that fail-opens (its ClusterRole missing from the +# database) binds every listener, so a TCP connect to 25 succeeds on a +# broken "mx" node just as it does on a healthy "full" one. +# 2. It proves strictly less. A TCP accept says a socket is bound; +# /healthz/ready additionally says the server reached the point where a +# data store handle exists at all. +# 3. It would have to differ per node group (the "mx" group has no 465 or +# 993), so the fallback default in _helpers.tpl could no longer carry the +# probe's context — the failure mode guideline 12.5 exists for. +# If a node ever does need to carry more than ~16 pods, the right move is to +# raise the limit on the server (the allow-list bypasses the limiter outright +# for listed addresses) rather than to blind the probes. +# +# WHAT THESE PROVE, AND WHAT THEY DO NOT — three honest limits: +# - Liveness is deliberately on /healthz/live so a Postgres outage cannot +# restart every pod in the cluster at once; the restart would fix nothing +# and would drop every connection in flight (guideline 12.3). +# - /healthz/ready DOES NOT QUERY THE DATABASE. Read from the source at +# v0.16.24: it returns 200 iff the data store handle is not Store::None. +# So readiness here does not hang on the dependency the way guideline 12.3 +# asks, and it cannot — the endpoint upstream offers is shallow. Named +# rather than papered over, because a green pod proves less than it looks. +# - It also does not catch the missing-config.json trap (a server that fell +# back to an ephemeral in-memory store still has a data store handle). +# +# NOT VERIFIED AGAINST A RUNNING SERVER: whether /healthz answers a plain +# kubelet probe at all. The source shows no auth, no loopback check and no +# trusted-network restriction, but the request still passes the configurable +# Http.allowedEndpoints expression (default "200", i.e. everything allowed) — +# and its loopback escape hatch does NOT cover a node IP, so an operator who +# later writes a restrictive expression breaks every probe. The image's own +# healthcheck sends "X-Forwarded-For: 127.0.0.1", which is how it puts itself +# in the loopback rate-limit bucket; that only has an effect when +# Http.useXForwarded is on, and it is off by default. +livenessProbe: + httpGet: + path: /healthz/live + port: http + periodSeconds: 20 + timeoutSeconds: 5 + failureThreshold: 3 +readinessProbe: + httpGet: + path: /healthz/ready + port: http + periodSeconds: 20 + timeoutSeconds: 5 + failureThreshold: 3 +# The startup probe gates liveness and readiness, so neither needs an +# initialDelaySeconds. Budget = periodSeconds x failureThreshold = 300s, which +# is generous on purpose: the first start of a node has to reach Postgres, +# acquire its cluster node-id lease and read the whole configuration registry +# out of the database. +startupProbe: + httpGet: + path: /healthz/ready + port: http + periodSeconds: 10 + timeoutSeconds: 5 + failureThreshold: 30 + +# --------------------------------------------------------------------------- +# Valkey subchart (the Valkey project's own chart) — OFF by default +# --------------------------------------------------------------------------- +# Stalwart needs an in-memory store for a cluster, and the coordinator rides on +# the same connection. This dependency is the convenience path for a +# deployment that has no Valkey yet; point externalServices.valkey.host at an +# existing instance (this repo's own valkey chart, for example) and leave this +# off. +# +# UPSTREAM'S CHART IS CONSUMED AS IT COMES — two of its defaults fall short of +# this repo's conventions and are deliberately NOT patched here (README, +# "Chart dependencies", point 2). Named rather than silently inherited: +# +# 1. auth.enabled defaults to FALSE, so the instance accepts unauthenticated +# connections from anything the CNI lets through to it. Upstream's own +# values file warns about the related footgun (enabling auth without a +# "default" user leaves it open anyway). If this Valkey is reachable +# beyond the pod, set auth.enabled plus auth.aclUsers / auth.aclConfig — +# and prefer usersExistingSecret over an inline password, since inline +# values land in the Helm release. +# 2. networkPolicy is upstream's own object with upstream's own semantics; +# this chart's networkPolicy block does not reach it. Our Stalwart pods +# get an egress rule for externalServices.valkey.port, but nothing here +# restricts who else may reach the Valkey. +# +# Other costs, stated so they are not rediscovered: the subchart is invisible +# to anything watching Helm release versions (a Valkey fix arrives only when +# this chart is republished — Chart.yaml has the detail), scaleDown and +# checksum/config stop at the subchart boundary, and every helm command needs +# ci/helm-dependencies.sh to have run first. +valkey: + enabled: false -- 2.54.0 From 2768d0ae05b60a1e9fc002fee55511d6f0f78777 Mon Sep 17 00:00:00 2001 From: Justin Klein Date: Fri, 2 Oct 2026 20:40:24 +0000 Subject: [PATCH 2/2] feat(stalwart): take our own published valkey chart as the subchart Replaces the dependency on upstream's valkey chart with this repo's own, resolved from the published index: version: "1.0.0+up9.1.2.alpine" repository: "https://git.jk-dev.de/api/packages/jlab-cluster/helm" The condition is "valkeySubchart.enabled", NOT "valkey.enabled", and that is forced rather than stylistic. Everything under "valkey:" is handed to the subchart as its values and validated against ITS schema, and our valkey chart ships additionalProperties: false with no "enabled" property - so "valkey.enabled" is rejected by the subchart: valkey: - at '': additional properties 'enabled' not allowed Measured. And because Helm skips a DISABLED subchart's schema validation, that error would have surfaced only for whoever first set it to true: every render, lint and install-test in CI would have stayed green. Adding "enabled" to valkey/values.schema.json was rejected as the repair - that chart does not read the key, and it would have needed its own PR and a publish first. The host helper was also wrong for our chart and is fixed: our Service is "-valkey-service", not upstream's bare "-valkey". The values block is rewritten for our chart's schema, with the pair chosen rather than inherited: CACHE (persistence off + allkeys-lru), because everything Stalwart keeps in the in-memory store - rate limiters, auth tokens, sessions, auto-ban entries, coordination pub/sub - is reconstructible, and the node-id lease lives in the data store. The cost is named where it is set: with allkeys-lru the rate limiters and the auto-ban FAIL OPEN under memory pressure, so the answer is to size memory, not to switch to noeviction (which would make writes error and take out authentication instead). secrets.authSecretRef wants an item whose single field "auth-conf" holds the complete "requirepass " line, not a bare password. Chart.yaml's comments are corrected where they became false: nothing is "consumed as it comes" any more and there is no shortfall of someone else's to document. The Renovate reasoning stays and is now backed by measurement. New trap, in Chart.yaml and in three places in the wiki: NEVER change valkey/ and a chart depending on it in the same PR. The dependency resolves from the published index, so a combined PR lints, packages, renders AND install-tests against the OLD subchart - green on an artifact that is not the one in the diff. Two consecutive PRs. Two things measured, not assumed, because either could have broken the update path with no symptom but "no updates ever": - helm dependency update AND build resolve the exact build-metadata version from the URL alone with an EMPTY HELM_REPOSITORY_CONFIG - a fresh runner's state - so the anonymous index needs no credential and ci/helm-dependencies.sh is untouched; - Renovate 44.132.2 dry run with the dependency pinned low: manager helmv3 matched the file, took registryUrls from Chart.yaml and offered newVersion "1.0.0+up9.1.2.alpine", versioning "helm". The self-hosted index and the "+up..." suffix are both handled. README: the claim "no registry address appears in this repository" is narrowed to what still holds - the publish target and its credentials come from 1Password and are not in the repo. The read path is now in Chart.yaml by necessity, carries no credential, and the host was always in CLAUDE.md. Done here rather than later so the paperless PR finds it already corrected. Re-verified after the change: helm lint --strict (0 failed), helm package (the subchart is embedded in the .tgz), helm template with the subchart OFF and ON (ON was previously impossible), against CI test-values, the rendered config.json, ci/run-quantity-render-test.sh (0 failed), NOTES.txt through the scratch-ConfigMap trick, and the fail paths including the reworded abort. The rendered subchart Service name matches what the helper emits, the cache pairing really renders (maxmemory-policy allkeys-lru, appendonly no, save "", emptyDir) and no PVC appears. Part of #65 --- README.md | 18 +++++- stalwart/Chart.yaml | 87 ++++++++++++++++++++----- stalwart/templates/NOTES.txt | 40 +++++++++--- stalwart/templates/_helpers.tpl | 27 ++++---- stalwart/values.schema.json | 12 +++- stalwart/values.yaml | 110 ++++++++++++++++++++++++-------- 6 files changed, 226 insertions(+), 68 deletions(-) diff --git a/README.md b/README.md index 56e39fa..43734b5 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ Every chart has a wiki page of its own — `https://git.jk-dev.de/jlab-cluster/h | `samba` | Samba | StatefulSet, users secret + config ConfigMap | | `satisfactory` | Satisfactory game server | StatefulSet, no ingress | | `searxng` | SearXNG | Stateless Deployment + settings ConfigMap (`use_default_settings: true` plus a free-form `settings.extra` passthrough); the signing key is a required `OnePasswordItem`, an external Valkey an optional second one. `ingress.domain` is read twice — Ingress host and `SEARXNG_BASE_URL` — so it stays required with the Ingress switched off | -| `stalwart` | Stalwart mail server (SMTP, IMAP, POP3, JMAP, ManageSieve) | **The chart configures almost nothing, and that is the chart's defining property.** Since v0.16 Stalwart keeps its whole configuration — every listener, the blob store, the in-memory store, TLS objects, domains and the cluster roles — inside the data store and manages it over JMAP; the only file on disk is a `config.json` that names the data store and nothing else. So the chart renders that ConfigMap (secret-free: `authSecret` uses the `EnvironmentVariable` variant, so the password arrives by `secretKeyRef` and `checksum/config` stays meaningful), one StatefulSet per entry of the `nodes` **map** with `STALWART_ROLE` and `STALWART_HOSTNAME`, one NodePort Service **per port** (not per group — a NodePort is cluster-unique, so `full` and `mx` can only take SMTP behind the same Service, selected by a per-port pod label), a per-group ClusterIP `http` Service for the Ingress, per-group headless Services and NetworkPolicies, and a cert-manager `Certificate` for the mail ports. Everything else is operator work in the WebUI, which is why `NOTES.txt` carries an eight-step first install. Four traps worth knowing before reading the chart: **the role lookup fails open** — a node whose `ClusterRole` is missing from the database enables every listener *and* every task while staying Running with a green probe, so `mx` ships at `replicas: 0` and the NetworkPolicy is a ceiling independent of what was bound; **`NET_BIND_SERVICE` is a documented deviation needed to `exec`, not to bind** (the image sets `setcap cap_net_bind_service=+ep`, so `drop: [ALL]` alone makes the kernel fail `execve` — removing it as "unused" stops the chart starting); **`externalTrafficPolicy` must be `Cluster`** (no pod runs on a control-plane node while the HA proxy delivers to them, so `Local` would drop every packet) and the source address it costs is restored only by the HA proxy's PROXY v2 header; and **`/healthz` is rate-limited to 100 req/60s per source IP**, which is a node IP for kubelet probes, so the probe intervals are calculated rather than chosen. A first install needs `bootstrap.enabled: true` because the setup wizard appears only when `config.json` is *absent*. Optional `valkey` subchart (the Valkey project's own chart), off by default | +| `stalwart` | Stalwart mail server (SMTP, IMAP, POP3, JMAP, ManageSieve) | **The chart configures almost nothing, and that is the chart's defining property.** Since v0.16 Stalwart keeps its whole configuration — every listener, the blob store, the in-memory store, TLS objects, domains and the cluster roles — inside the data store and manages it over JMAP; the only file on disk is a `config.json` that names the data store and nothing else. So the chart renders that ConfigMap (secret-free: `authSecret` uses the `EnvironmentVariable` variant, so the password arrives by `secretKeyRef` and `checksum/config` stays meaningful), one StatefulSet per entry of the `nodes` **map** with `STALWART_ROLE` and `STALWART_HOSTNAME`, one NodePort Service **per port** (not per group — a NodePort is cluster-unique, so `full` and `mx` can only take SMTP behind the same Service, selected by a per-port pod label), a per-group ClusterIP `http` Service for the Ingress, per-group headless Services and NetworkPolicies, and a cert-manager `Certificate` for the mail ports. Everything else is operator work in the WebUI, which is why `NOTES.txt` carries an eight-step first install. Four traps worth knowing before reading the chart: **the role lookup fails open** — a node whose `ClusterRole` is missing from the database enables every listener *and* every task while staying Running with a green probe, so `mx` ships at `replicas: 0` and the NetworkPolicy is a ceiling independent of what was bound; **`NET_BIND_SERVICE` is a documented deviation needed to `exec`, not to bind** (the image sets `setcap cap_net_bind_service=+ep`, so `drop: [ALL]` alone makes the kernel fail `execve` — removing it as "unused" stops the chart starting); **`externalTrafficPolicy` must be `Cluster`** (no pod runs on a control-plane node while the HA proxy delivers to them, so `Local` would drop every packet) and the source address it costs is restored only by the HA proxy's PROXY v2 header; and **`/healthz` is rate-limited to 100 req/60s per source IP**, which is a node IP for kubelet probes, so the probe intervals are calculated rather than chosen. A first install needs `bootstrap.enabled: true` because the setup wizard appears only when `config.json` is *absent*. Optional `valkey` subchart — **this repo's own chart, from the published index**, off by default and gated on `valkeySubchart.enabled` (not `valkey.enabled`, which the subchart's strict schema rejects); never change `valkey/` and this chart in the same PR, see "Chart dependencies" | | `sure` | Sure (we-promise, the maintained Maybe-finance fork) | One StatefulSet with **two containers**: the Puma web process and a Sidekiq worker, sharing one ReadWriteOnce PVC at `/rails/storage` — that shared volume is the reason they live in one pod. Only the web container migrates (the image entrypoint runs `db:prepare` solely for the `./bin/rails server` command, so the worker is started through `args:` and skips it). Three 1Password items (app/database/redis); Postgres and Redis stay external. Readiness deliberately probes `/` rather than Rails' `/up`, which is a boot check and touches no database; the worker's three probes ask `sidekiqmon` for this pod's own heartbeat. `ingress.domain` is read for `APP_DOMAIN` and the WebAuthn relying party, so it stays required with the Ingress switched off | | `teamspeak-server` | TeamSpeak server | StatefulSet, no ingress | | `template-chart` | — | Scaffold for new charts (placeholder `xxx`), never published | @@ -57,7 +57,9 @@ Every chart has a wiki page of its own — `https://git.jk-dev.de/jlab-cluster/h - **`secrets: inherit`**, unchanged, for `OP_CONNECT_TOKEN`. - the repository **variable `OP_CONNECT_HOST`**, which replaced the Connect host that used to be hardcoded in our copy. A shared block must not carry one tenant's infrastructure address; the block's first step fails and names the variable when it is unset. - The registry credentials and the target URL still come from 1Password Connect (item `op://GitHub-Actions/jlab-registry-access/` with `username`, `password`, `charts-url`). `charts-url` holds only the **base up to `/api/packages`** and the block composes `//helm/api/charts`, so **no registry address appears in this repository** — not even the owner path segment. `ci/helm-dependencies.sh` is still run before `helm package`, and it is still **our** script: the block's checkout clones the calling repository, so it runs from this tree. + The registry credentials and the target URL still come from 1Password Connect (item `op://GitHub-Actions/jlab-registry-access/` with `username`, `password`, `charts-url`). `charts-url` holds only the **base up to `/api/packages`** and the block composes `//helm/api/charts`, so **the publish target and its credentials appear nowhere in this repository.** `ci/helm-dependencies.sh` is still run before `helm package`, and it is still **our** script: the block's checkout clones the calling repository, so it runs from this tree. + + **What this does *not* claim any more**: that no registry address is in the repo at all. That wording was true until a chart took one of our own published charts as a subchart — `stalwart`'s `Chart.yaml` names `https://git.jk-dev.de/api/packages/jlab-cluster/helm` as a dependency `repository:`, because a Helm dependency is resolved from a URL in the chart and there is nowhere else to put it. The narrower claim above is the one that matters and it is unchanged: that is the **read** path, the index is anonymously readable (measured), so it carries **no credential** and grants nothing a `git clone` of this repo does not already imply. The host itself has always been in `CLAUDE.md`; what is new is only the read-only path segment. The reasons behind the upload step are **not repeated here**, because they are no longer ours to keep current: why both halves of the composed URL are guarded, why the credentials go in through `curl --config -` instead of `--user`, why `--fail-with-body` is what makes a failed upload fail the job, and why the file name is built rather than globbed, are all on the [`publish-helm-chart` wiki page](https://git.jk-dev.de/workflow-util/pipelines/wiki/publish-helm-chart) of that repository. Nothing was dropped in the move — the upload step's shell body went across unchanged except for two error messages that name the owner as an input. @@ -438,7 +440,17 @@ Reference implementation: `template-chart/values.schema.json` and `template-char Until `ytdlp-web-player` (#214) this section read "charts have no dependencies (`charts/` directories are empty)". That rule is gone, replaced by a bar rather than a ban — a dependency is **admissible, not free**, and the reason it stopped being a ban is worth keeping: the chart needed an oauth2-proxy in the data path in front of an application that ships no authentication at all, and proxy and app are only useful wired to each other. -Two charts carry one, and comparing them is the quickest way to see where the bar sits. `ytdlp-web-player` takes `oauth2-proxy` because the app has no authentication and the two are useless apart. `stalwart` (Gitea #65) takes the Valkey project's own chart because Stalwart's **cluster coordinator rides on the in-memory store connection**, so a multi-node install does not work without one — and because this repo also publishes a `valkey` chart of its own, the subchart is the convenience path rather than the expected one: `externalServices.valkey.host` points at an existing instance and then the dependency renders nothing. Both are `condition:`-gated and off by default, and in both cases upstream's shortfalls against the guidelines above (`stalwart`: `auth.enabled: false`, and a NetworkPolicy with upstream's own semantics that our `networkPolicy` block does not reach) are **documented in our `values.yaml` rather than patched**. +Two charts carry one, and comparing them is the quickest way to see where the bar sits. `ytdlp-web-player` takes **upstream's** `oauth2-proxy` because the app has no authentication and the two are useless apart; there, point 2 above applies in full. `stalwart` (Gitea #65) takes **one of our own published charts**, `valkey`, because Stalwart's **cluster coordinator rides on the in-memory store connection**, so a multi-node install does not work without one. Both are `condition:`-gated and off by default — for `stalwart` the subchart is the path for an installation that has no Valkey yet, and one that already has points `externalServices.valkey.host` at it so the dependency renders nothing. + +**A dependency on one of our own charts is cheaper in one way and more dangerous in another.** Point 2 stops applying: there are no third-party defaults to leave unpatched, because the subchart follows these guidelines by being one of ours. In exchange it adds a hazard an external dependency does not have, and it is sharp enough to be a rule: + +> **Never change a chart and a chart that depends on it in the same pull request.** + +The dependency resolves from the **published index**, not from the working tree, and a chart is published only by a push to `main` that touches it. So a combined PR runs every `helm` command — lint, package, render **and the install-test** — against the **old** subchart, goes green on an artifact that is not the one in the diff, and leaves the subchart's own change exercised by nothing. Two consecutive PRs: change the subchart, merge, let it publish, then raise the `version:` in the dependent chart. + +Two mechanical details of a self-referencing dependency, both measured for #65: the index is **anonymously readable**, so `ci/helm-dependencies.sh` needs no credential and resolves the exact build-metadata version (`1.0.0+up9.1.2.alpine`) from the URL alone with an empty `HELM_REPOSITORY_CONFIG` — the state a fresh runner is in. And Renovate's built-in `helmv3` manager does follow a self-hosted Gitea index: a dry run (Renovate 44.132.2) with the dependency pinned low reported `newVersion: "1.0.0+up9.1.2.alpine"`, `versioning: "helm"`, timestamp read from our index. Without that second result the published-version form would have had no update path at all, which is why it was measured rather than assumed. + +One more trap, and it is the reason `stalwart` gates its subchart on `valkeySubchart.enabled` rather than the conventional `valkey.enabled`: **everything under the subchart's key is handed to the subchart as its values**, so a `condition:` key placed there is validated against *its* schema. Our charts ship `additionalProperties: false`, so `valkey.enabled` is rejected by the subchart — and because Helm skips a **disabled** subchart's schema validation, the error surfaces only for whoever first switches it on. Put the condition on a key of the parent's own. **When a dependency earns its place.** All three, not two of three: diff --git a/stalwart/Chart.yaml b/stalwart/Chart.yaml index bd9b987..131812f 100644 --- a/stalwart/Chart.yaml +++ b/stalwart/Chart.yaml @@ -37,15 +37,17 @@ maintainers: # the chart means the wiring (host, port, egress rule) is in one place instead # of split across two releases that have to agree. # -# WHY IT IS OFF BY DEFAULT, and why that is more than convention here: most -# installations already run a Valkey, and this repo publishes a valkey chart of -# its own that is the better choice when one application owns the instance. -# Point externalServices.valkey at it and this dependency renders nothing. +# WHY IT IS OFF BY DEFAULT: an installation that already runs a Valkey points +# externalServices.valkey.host at it and this dependency renders nothing. The +# subchart is the path for an installation that has none. # -# UPSTREAM'S CHART IS CONSUMED AS IT COMES (guideline 14.2). Two of its defaults -# fall short of this repo's conventions and are deliberately NOT patched here; -# they are documented in our values.yaml under "valkey:" instead, where the -# values-level fix stays available to whoever installs the chart. +# THE SUBCHART IS OUR OWN valkey CHART, resolved from the published index - +# NOT upstream's. So guideline 14.2 ("we consume their chart as it comes") does +# not apply here and there is nothing of someone else's to leave unpatched: the +# subchart follows this repo's conventions because it IS this repo's chart. What +# does apply is everything about the subchart being invisible downstream, plus +# one hazard that a self-referencing dependency adds and an external one does +# not - see the PR-ordering warning below. dependencies: - name: valkey # KEEP THIS VERSION MOVING - it is the only path a Valkey update has. @@ -63,14 +65,65 @@ dependencies: # actually ships it. That chain is the whole safety net; switched off, this # line needs a human on a calendar instead. # + # MEASURED, not assumed, because the registry is self-hosted and the version + # carries build metadata - two things that could each have broken the chain + # silently. Renovate 44.132.2, dry run on 2026-10-02 with this dependency + # pinned at a lower version: manager helmv3 matched the file, took + # registryUrls from the line below, and offered + # newVersion: "1.0.0+up9.1.2.alpine", versioning: "helm" + # with the release timestamp read from our index. So both the self-hosted + # index and the "+up..." suffix are handled. + # # Independent of appVersion: raising it is a patch or minor bump of this # chart and is never tied to the Stalwart image. - version: "0.12.0" - # The Valkey project's own chart, so upstream owns the schema - not a - # re-packaging. Note the repository is the plain HTTP index, not OCI. - repository: "https://valkey.io/valkey-helm" - # Off by default, so a plain install renders none of its objects. Helm - # splits a condition on dots only; this name carries no dash, so unlike - # ytdlp-web-player's oauth2-proxy it is also reachable as .Values.valkey.* - # inside templates without index. - condition: valkey.enabled + version: "1.0.0+up9.1.2.alpine" + # Our own published index, and the READ path only. It is anonymously + # readable - measured 2026-10-02: GET .../index.yaml returns 200 without + # credentials - so ci/helm-dependencies.sh needs no secret and was not + # touched. Verified with an empty HELM_REPOSITORY_CONFIG, i.e. the state a + # fresh runner is in: helm reports "Getting updates for unmanaged Helm + # repositories" and resolves the exact build-metadata version from the URL + # alone, with no "helm repo add" anywhere. Both "helm dependency update" and + # "helm dependency build" were tried. + # + # The PUBLISH target and its credentials still live in 1Password and appear + # nowhere in this repository - see README, "CI/CD". + repository: "https://git.jk-dev.de/api/packages/jlab-cluster/helm" + # Off by default, so a plain install renders none of its objects. + # + # NOT "valkey.enabled", AND THAT IS NOT A STYLE CHOICE. Everything under the + # "valkey:" key is passed to the subchart as its values, and our valkey + # chart ships a values.schema.json with additionalProperties: false and no + # "enabled" property - so "valkey.enabled" is rejected by the SUBCHART: + # Error: values don't meet the specifications of the schema(s) in the + # following chart(s): valkey: - at '': additional properties 'enabled' + # not allowed + # Measured. Worse, Helm skips a disabled subchart's schema validation, so + # the error appears only for whoever first sets it to true - the default + # path renders clean. + # + # The condition is therefore a key of OUR OWN, outside the subchart's value + # subtree, which is also the honest shape: "enabled" is not a valkey value. + # It only ever looked like one because upstream's schema was permissive. + # The alternative - adding "enabled" to valkey/values.schema.json - would + # have to be its own PR and be published first (see the warning below), for + # a key that chart does not read. + condition: valkeySubchart.enabled +# +# !!! NEVER CHANGE valkey/ AND THIS CHART IN THE SAME PULL REQUEST !!! +# +# The hazard a self-referencing dependency adds. This dependency resolves out of +# the PUBLISHED index, not out of the working tree, and valkey/ is only +# published by a push to main that touches it. So in one PR carrying both: +# +# - every helm command here - lint, package, render, AND the install-test - +# pulls the OLD valkey .tgz, because the new one does not exist yet; +# - the PR therefore goes green against a version of the subchart that is not +# the one in the diff, and the diff to valkey/ is reviewed while nothing +# actually exercised it; +# - after the merge both charts publish, and the first install of the new +# stalwart is the first time the new valkey is used anywhere. +# +# Two consecutive pull requests instead: change valkey/, merge, let it publish, +# then raise the version here. The ordering is not a nicety - the green check on +# the combined PR is a statement about the wrong artifact. diff --git a/stalwart/templates/NOTES.txt b/stalwart/templates/NOTES.txt index 4b2b63b..fe2bf0d 100644 --- a/stalwart/templates/NOTES.txt +++ b/stalwart/templates/NOTES.txt @@ -236,18 +236,40 @@ NO INGRESS ingress.domain STAYS REQUIRED even so — the mail Certificate reads it for its dnsNames, and without it the certificate would carry no name at all. {{- end }} -{{- if .Values.valkey.enabled }} +{{- if .Values.valkeySubchart.enabled }} THE VALKEY SUBCHART IS ENABLED - Reachable at {{ $valkeyHost }}:{{ .Values.externalServices.valkey.port }}, and it is upstream's chart consumed as it - comes. Two of its defaults fall short of this repo's conventions and are NOT - patched by us: auth.enabled is false (unauthenticated access from anything - the CNI permits), and its NetworkPolicy is its own object with its own - semantics, which this chart's networkPolicy block does not reach. See the - valkey section of values.yaml. + Reachable at {{ $valkeyHost }}:{{ .Values.externalServices.valkey.port }} — this repo's own valkey chart, + pulled from the published index. Enter that address as the in-memory store in + step 3; the coordinator's Default variant reuses the same connection. - scaleDown and checksum/config stop at the subchart boundary, and a new Valkey - release reaches you only when this chart is republished. + ITS 1PASSWORD ITEM IS A SEPARATE ONE, AND ITS FIELD IS NOT A PASSWORD: + valkey.secrets.authSecretRef points at + {{ .Values.valkey.secrets.authSecretRef | default "" }} + and that item carries ONE field, "auth-conf", whose value is the complete + configuration line + + requirepass + + not a bare password. The valkey chart mounts the file and includes it, and + an init container refuses to start the pod unless the line is really there — + because the alternative failure is an open server that looks healthy. + + IT IS CONFIGURED AS A CACHE, NOT A QUEUE + persistence.enabled false + maxmemoryPolicy allkeys-lru. Everything Stalwart + keeps here — rate-limiter counters, auth tokens, sessions, auto-ban entries, + the coordination pub/sub — is reconstructible after a restart; nothing in it + is the system of record. + + The cost of allkeys-lru, so it is not a surprise: under memory pressure keys + are discarded, so the rate limiters and the auto-ban FAIL OPEN. Size memory + for the working set rather than switching to noeviction — with noeviction + Stalwart's writes to the store start erroring, which takes out + authentication instead of just the limits. + + scaleDown and checksum/config stop at the subchart boundary, so scaling this + release to zero does NOT stop the Valkey, and a new valkey chart release + reaches you only when stalwart itself is republished. {{- end }} {{- if not .Values.networkPolicy.enabled }} diff --git a/stalwart/templates/_helpers.tpl b/stalwart/templates/_helpers.tpl index ee5ef55..3790233 100644 --- a/stalwart/templates/_helpers.tpl +++ b/stalwart/templates/_helpers.tpl @@ -375,28 +375,33 @@ is the address to type into the WebUI, and the port for the egress rule. {{- end -}} {{- end -}} {{- $subchartOn := false -}} -{{- if and (not (kindIs "invalid" .Values.valkey)) .Values.valkey.enabled -}} +{{- if and (not (kindIs "invalid" .Values.valkeySubchart)) .Values.valkeySubchart.enabled -}} {{- $subchartOn = true -}} {{- end -}} {{- if $given -}} {{- $given -}} {{- else if $subchartOn -}} -{{/* The subchart's own fullname helper: release name plus chart name, unless - the release name already contains it. Reproduced rather than called, - because a parent cannot include a subchart's define with the subchart's - context. */}} -{{- if contains "valkey" .Release.Name -}} -{{- .Release.Name | trunc 63 | trimSuffix "-" -}} -{{- else -}} -{{- printf "%s-valkey" .Release.Name | trunc 63 | trimSuffix "-" -}} -{{- end -}} +{{/* The Service our own valkey chart renders: + {{ .Release.Name }}-{{ .Chart.Name }}-service + and inside a subchart .Chart.Name is the SUBCHART's name, so this is + "-valkey-service" with no special case. Reproduced rather than + included, because a parent cannot call a subchart's define with the + subchart's context. + + Note the "-service" suffix: this repo's naming scheme ends every Service + that way, which is NOT what upstream's valkey chart does (it would be a + bare "-valkey"). An earlier draft of this chart depended on + upstream's and carried their name; getting this wrong points the operator + at an address that does not resolve, and nothing in the chart would say + so. */}} +{{- printf "%s-valkey-service" .Release.Name | trunc 63 | trimSuffix "-" -}} {{- else -}} {{- $total := 0 -}} {{- range $group, $spec := fromYaml (include "stalwart.nodes" .) -}} {{- $total = add $total (int (include "stalwart.replicas" (dict "scaleDown" $.Values.scaleDown "replicas" $spec.replicas))) -}} {{- end -}} {{- if gt $total 1 -}} -{{- fail (printf "this release runs %d Stalwart pods, which is a cluster, but no in-memory store has an address: externalServices.valkey.host is empty and valkey.enabled is false. Stalwart's cluster coordinator rides on the in-memory store connection, so a multi-node install has no coordination path at all - and that failure does not show up as a failed install, it shows up as nodes that do not agree with each other. Set externalServices.valkey.host to an existing instance, or set valkey.enabled: true to deploy the subchart" $total) -}} +{{- fail (printf "this release runs %d Stalwart pods, which is a cluster, but no in-memory store has an address: externalServices.valkey.host is empty and valkeySubchart.enabled is false. Stalwart's cluster coordinator rides on the in-memory store connection, so a multi-node install has no coordination path at all - and that failure does not show up as a failed install, it shows up as nodes that do not agree with each other. Set externalServices.valkey.host to an existing instance, or set valkeySubchart.enabled: true to deploy the subchart" $total) -}} {{- end -}} {{- end -}} {{- end -}} diff --git a/stalwart/values.schema.json b/stalwart/values.schema.json index be2068b..7398770 100644 --- a/stalwart/values.schema.json +++ b/stalwart/values.schema.json @@ -385,8 +385,18 @@ "startupProbe": { "$ref": "#/definitions/probe" }, + "valkeySubchart": { + "description": "The dependency condition for the valkey subchart. A key of THIS chart, deliberately outside the 'valkey' subtree: everything under 'valkey:' is handed to the subchart as its values, and this repo's valkey chart has additionalProperties: false with no 'enabled' property, so 'valkey.enabled' is rejected by the subchart itself. Helm skips a disabled subchart's schema validation, so that error would only have surfaced for whoever first set it to true.", + "type": "object", + "additionalProperties": false, + "properties": { + "enabled": { + "type": "boolean" + } + } + }, "valkey": { - "description": "Values of the valkey subchart (the Valkey project's own chart), passed straight through. Open on purpose and at every level: this chart owns neither the keys nor their meaning, and a closed copy would reject whatever the subchart adds in its next release - the exact failure a schema exists to prevent, pointed at the wrong chart. This chart reads exactly one of them, 'enabled', which is the dependency condition. Two of upstream's defaults fall short of this repo's conventions and are documented in values.yaml rather than patched here.", + "description": "Values passed through to the valkey subchart - this repo's OWN valkey chart, resolved from the published index. Open on purpose and at every level: the subchart owns this schema (it ships its own, and a stricter one than this), and a closed copy here would reject whatever that chart adds in its next release while also duplicating a validation that already happens. This chart reads NONE of these keys; the dependency condition is valkeySubchart.enabled instead. Note the field shape that is easy to get wrong: secrets.authSecretRef points at an item whose single field 'auth-conf' holds the complete line 'requirepass ', not a bare password. values.yaml argues the cache-vs-queue choice.", "type": "object" } }, diff --git a/stalwart/values.yaml b/stalwart/values.yaml index ae06b03..5798257 100644 --- a/stalwart/values.yaml +++ b/stalwart/values.yaml @@ -643,34 +643,90 @@ startupProbe: failureThreshold: 30 # --------------------------------------------------------------------------- -# Valkey subchart (the Valkey project's own chart) — OFF by default +# The Valkey subchart — THIS REPO'S OWN valkey CHART, off by default # --------------------------------------------------------------------------- # Stalwart needs an in-memory store for a cluster, and the coordinator rides on -# the same connection. This dependency is the convenience path for a -# deployment that has no Valkey yet; point externalServices.valkey.host at an -# existing instance (this repo's own valkey chart, for example) and leave this -# off. +# the same connection. The subchart is the path for a deployment that has no +# Valkey yet; an installation that already runs one points +# externalServices.valkey.host at it and leaves this off. # -# UPSTREAM'S CHART IS CONSUMED AS IT COMES — two of its defaults fall short of -# this repo's conventions and are deliberately NOT patched here (README, -# "Chart dependencies", point 2). Named rather than silently inherited: -# -# 1. auth.enabled defaults to FALSE, so the instance accepts unauthenticated -# connections from anything the CNI lets through to it. Upstream's own -# values file warns about the related footgun (enabling auth without a -# "default" user leaves it open anyway). If this Valkey is reachable -# beyond the pod, set auth.enabled plus auth.aclUsers / auth.aclConfig — -# and prefer usersExistingSecret over an inline password, since inline -# values land in the Helm release. -# 2. networkPolicy is upstream's own object with upstream's own semantics; -# this chart's networkPolicy block does not reach it. Our Stalwart pods -# get an egress rule for externalServices.valkey.port, but nothing here -# restricts who else may reach the Valkey. -# -# Other costs, stated so they are not rediscovered: the subchart is invisible -# to anything watching Helm release versions (a Valkey fix arrives only when -# this chart is republished — Chart.yaml has the detail), scaleDown and -# checksum/config stop at the subchart boundary, and every helm command needs -# ci/helm-dependencies.sh to have run first. -valkey: +# THE SWITCH IS HERE AND NOT UNDER "valkey:", and it has to be. Everything under +# "valkey:" is handed to the subchart as its values, and our valkey chart ships +# a strict schema (additionalProperties: false) with no "enabled" property — so +# "valkey.enabled" is rejected BY THE SUBCHART. Measured; and because Helm skips +# a disabled subchart's schema validation, the error would only ever appear for +# whoever first switched it on. Chart.yaml has the error text. +valkeySubchart: enabled: false + +# --------------------------------------------------------------------------- +# Values passed THROUGH to the valkey subchart +# --------------------------------------------------------------------------- +# Read as the subchart's own values, so the key names are ITS schema, not +# upstream's and not this chart's. `valkey/values.yaml` in the repo is the +# reference; its header comment explains the pairs. Nothing here has any effect +# while valkeySubchart.enabled is false. +# +# WHY THIS IS NOT "upstream's chart as it comes": it is our chart, so there is +# no third party's defaults to leave unpatched and no shortfall against this +# repo's conventions to document — it follows them because it IS one of them. +# What still applies in full is the subchart being invisible downstream (a +# Valkey fix reaches a cluster only when THIS chart is republished — Chart.yaml +# has the detail and the PR-ordering warning), that scaleDown and +# checksum/config stop at the subchart boundary, and that every helm command +# needs ci/helm-dependencies.sh to have run first. +valkey: + secrets: + # REQUIRED once the subchart is on — the subchart's own required() aborts + # the render without it, which is the correct loud failure. + # + # MIND THE FIELD, it is not a password. The 1Password item carries ONE + # field, `auth-conf`, whose value is the COMPLETE configuration line + # requirepass + # The valkey chart mounts that file and `include`s it, and an init container + # refuses to start the pod unless the line is really there — because the + # alternative failure is an open server that looks perfectly healthy. A bare + # password in that field does not work. + authSecretRef: null + + # CACHE, not queue — a decision, with its cost named. + # + # The valkey chart treats persistence and eviction as a PAIR and warns against + # mixing them: QUEUE is `persistence.enabled: true` + `noeviction`, CACHE is + # `persistence.enabled: false` + `allkeys-lru`. + # + # Stalwart's in-memory store holds rate-limiter counters, auth tokens and + # sessions, auto-ban entries, and the cluster coordination pub/sub. Every one + # of those is reconstructible: counters and bans restart from zero, tokens and + # sessions force a re-authentication, and pub/sub messages are not stored keys + # at all. Nothing in it is the system of record — messages and metadata are in + # Postgres, blobs in S3, and the cluster node-id lease is in the data store + # too, not here. Paying for a PVC and for AOF replay to protect data that is + # worthless after a restart is the wrong trade, so: cache. + # + # THE COST, because `allkeys-lru` means keys really are discarded under memory + # pressure: the rate limiters and the auto-ban FAIL OPEN. An attacker who can + # drive memory usage can age out their own ban entry. The answer is to size + # memory for the working set rather than to switch to `noeviction` — with + # `noeviction` Stalwart's writes to the store start erroring instead, which + # takes out authentication rather than just the limits. Size it, and treat the + # limiters as a nuisance filter, not as a security boundary. + persistence: + enabled: false + + valkey: + maxmemoryPolicy: allkeys-lru + # The subchart derives maxmemory from the computed memory limit and aborts + # its render if an explicit maxmemory exceeds it. Defaults left alone. + resources: + requests: + cpu: 50m + memory: 128Mi + ephemeral-storage: 32Mi + + # The subchart's own NetworkPolicy, with its own semantics — this chart's + # networkPolicy block does not reach it. On by default there, allowing the + # release's own namespace. It needs an entry here only when Stalwart runs in a + # DIFFERENT namespace from the Valkey, which with the subchart it does not. + networkPolicy: + allowedNamespaces: [] -- 2.54.0