Mail through mail-prism, as the siblings

fb64a1a · gmorell · 2026-12-02 06:05

33 files +385 -124
Message
{commit_body(@commit)}

Files changed

modified config/runtime.exs
+146 −93
@@ -133,10 +133,19 @@ if config_env() == :prod do
133 133 # Check `Plug.SSL` for all available options in `force_ssl`.
134 134
135 135 # -- Mail (slice 11) ---------------------------------------------------------
136 − # Mailer adapter selection, as the sibling apps (cartosnap):
136 + # Mailer adapter selection by MAIL_PROVIDER, as the sibling apps
137 + # (clayman, waxx):
137 138 #
138 − # * SMTP_RELAY set → Swoosh.Adapters.SMTP (via gen_smtp)
139 − # * otherwise → Swoosh.Adapters.Logger
139 + # * "mail_prism" → MailPrism.SwooshAdapter, needs MAIL_PRISM_URL and
140 + # MAIL_PRISM_API_KEY: send through mail-prism
141 + # (prism.neiam.org), which holds the relay credentials
142 + # and renders priv/mail_prism/ (synced at boot, see
143 + # Vigil.Application). MAIL_FROM_ADDRESS must be the
144 + # address the key was issued for.
145 + # * "smtp" → Swoosh.Adapters.SMTP (via gen_smtp), needs SMTP_RELAY
146 + # * "log" → Swoosh.Adapters.Logger
147 + # * unset → mail_prism if both MAIL_PRISM_* are set (blank counts
148 + # as unset), else smtp if SMTP_RELAY is set, else log
140 149 #
141 150 # The Logger adapter doesn't actually send mail — it logs the rendered
142 151 # email at :info — but it gets us off Swoosh.Adapters.Local (the dev
@@ -155,104 +164,148 @@ if config_env() == :prod do
155 164 end
156 165 end
157 166
158 − mailer_opts =
159 − if relay = System.get_env("SMTP_RELAY") do
160 − # Eager-load the OS CA bundle into OTP's `public_key` cache. Without
161 − # this, `:public_key.cacerts_get/0` returns `:undefined`, and
162 − # `gen_smtp`'s internal default `tls_options` injects
163 − # `cacerts: :undefined` — which `:ssl` then rejects as incompatible
164 − # with `verify: :verify_peer`, clobbering our explicit `cacertfile`.
165 − case :public_key.cacerts_load() do
166 − :ok ->
167 − :ok
168 −
169 − {:error, reason} ->
170 − require Logger
171 −
172 − Logger.warning(
173 − "public_key:cacerts_load failed: #{inspect(reason)} — TLS verify may fail"
174 − )
175 − end
167 + smtp_opts = fn relay ->
168 + # Eager-load the OS CA bundle into OTP's `public_key` cache. Without
169 + # this, `:public_key.cacerts_get/0` returns `:undefined`, and
170 + # `gen_smtp`'s internal default `tls_options` injects
171 + # `cacerts: :undefined` — which `:ssl` then rejects as incompatible
172 + # with `verify: :verify_peer`, clobbering our explicit `cacertfile`.
173 + case :public_key.cacerts_load() do
174 + :ok ->
175 + :ok
176 176
177 − # CA bundle for TLS verification: `cacertfile` (path) as a fallback
178 − # to the cacerts_load above, belt-and-braces. Override
179 − # `SMTP_CACERTFILE` if your image puts the bundle elsewhere; set
180 − # `SMTP_TLS_VERIFY=verify_none` for self-signed / private relays
181 − # where you'd rather skip cert validation.
182 − smtp_cacertfile = System.get_env("SMTP_CACERTFILE", "/etc/ssl/certs/ca-certificates.crt")
177 + {:error, reason} ->
178 + require Logger
183 179
184 − smtp_verify =
185 − case System.get_env("SMTP_TLS_VERIFY", "verify_peer") do
186 − "verify_peer" ->
187 − :verify_peer
180 + Logger.warning("public_key:cacerts_load failed: #{inspect(reason)} — TLS verify may fail")
181 + end
188 182
189 − "verify_none" ->
190 − :verify_none
183 + # CA bundle for TLS verification: `cacertfile` (path) as a fallback
184 + # to the cacerts_load above, belt-and-braces. Override
185 + # `SMTP_CACERTFILE` if your image puts the bundle elsewhere; set
186 + # `SMTP_TLS_VERIFY=verify_none` for self-signed / private relays
187 + # where you'd rather skip cert validation.
188 + smtp_cacertfile = System.get_env("SMTP_CACERTFILE", "/etc/ssl/certs/ca-certificates.crt")
191 189
192 − other ->
193 − raise "SMTP_TLS_VERIFY must be verify_peer or verify_none, got: #{inspect(other)}"
194 − end
190 + smtp_verify =
191 + case System.get_env("SMTP_TLS_VERIFY", "verify_peer") do
192 + "verify_peer" ->
193 + :verify_peer
195 194
196 − # Resolve the CA store NOW (after `cacerts_load`) rather than letting
197 − # the downstream stack call `cacerts_get/0` lazily. gen_smtp / ssl
198 − # has a habit of evaluating it in a context where it still returns
199 − # `:undefined`, which then collides with our `cacertfile`. Passing
200 − # `cacerts: <list>` explicitly is unambiguous — `:ssl` honors it and
201 − # never re-derives.
202 − smtp_cacerts =
203 − case :public_key.cacerts_get() do
204 − certs when is_list(certs) and certs != [] -> certs
205 − _ -> nil
206 − end
195 + "verify_none" ->
196 + :verify_none
197 +
198 + other ->
199 + raise "SMTP_TLS_VERIFY must be verify_peer or verify_none, got: #{inspect(other)}"
200 + end
207 201
208 − tls_options =
209 − [
210 − verify: smtp_verify,
211 − server_name_indication: String.to_charlist(relay),
212 − depth: 99
213 − ] ++
214 − cond do
215 − smtp_verify != :verify_peer -> []
216 − is_list(smtp_cacerts) -> [cacerts: smtp_cacerts]
217 − true -> [cacertfile: smtp_cacertfile]
218 − end
219 −
220 − # Pin modern TLS at both the top level (read by gen_smtp before it
221 − # calls :ssl.connect) and inside tls_options (read by :ssl itself).
222 − tls_versions = [:"tlsv1.2", :"tlsv1.3"]
223 −
224 − # gen_smtp 1.2 has two distinct connection paths with different
225 − # option keys:
226 − #
227 − # * `ssl: true` (port 465 implicit TLS) reads its TLS opts from
228 − # `sockopts`. `tls_options` is ignored on this path.
229 − # * `tls: :always|:if_available` (STARTTLS upgrade) reads from
230 − # `tls_options` — only used during do_STARTTLS.
231 − #
232 − # Without sockopts on the implicit-TLS path, OTP 28's `:ssl` falls
233 − # through to its own defaults (verify_peer + `cacerts_get()` which
234 − # returns `:undefined`) and bails with `{options, incompatible,
235 − # [verify: verify_peer, cacerts: undefined]}`. Putting the same opts
236 − # on both keys covers both relay setups.
237 − ssl_opts = [{:versions, tls_versions} | tls_options]
202 + # Resolve the CA store NOW (after `cacerts_load`) rather than letting
203 + # the downstream stack call `cacerts_get/0` lazily. gen_smtp / ssl
204 + # has a habit of evaluating it in a context where it still returns
205 + # `:undefined`, which then collides with our `cacertfile`. Passing
206 + # `cacerts: <list>` explicitly is unambiguous — `:ssl` honors it and
207 + # never re-derives.
208 + smtp_cacerts =
209 + case :public_key.cacerts_get() do
210 + certs when is_list(certs) and certs != [] -> certs
211 + _ -> nil
212 + end
238 213
214 + tls_options =
239 215 [
240 − adapter: Swoosh.Adapters.SMTP,
241 − relay: relay,
242 − port: String.to_integer(System.get_env("SMTP_PORT", "587")),
243 − username: System.get_env("SMTP_USERNAME"),
244 − password: System.get_env("SMTP_PASSWORD"),
245 − tls: smtp_tri.("SMTP_TLS", "if_available"),
246 − ssl: System.get_env("SMTP_SSL", "false") == "true",
247 − auth: smtp_tri.("SMTP_AUTH", "if_available"),
248 − allowed_tls_versions: tls_versions,
249 − sockopts: ssl_opts,
250 − tls_options: ssl_opts,
251 − retries: 1,
252 − no_mx_lookups: false
253 − ]
254 − else
255 − [adapter: Swoosh.Adapters.Logger, level: :info]
216 + verify: smtp_verify,
217 + server_name_indication: String.to_charlist(relay),
218 + depth: 99
219 + ] ++
220 + cond do
221 + smtp_verify != :verify_peer -> []
222 + is_list(smtp_cacerts) -> [cacerts: smtp_cacerts]
223 + true -> [cacertfile: smtp_cacertfile]
224 + end
225 +
226 + # Pin modern TLS at both the top level (read by gen_smtp before it
227 + # calls :ssl.connect) and inside tls_options (read by :ssl itself).
228 + tls_versions = [:"tlsv1.2", :"tlsv1.3"]
229 +
230 + # gen_smtp 1.2 has two distinct connection paths with different
231 + # option keys:
232 + #
233 + # * `ssl: true` (port 465 implicit TLS) reads its TLS opts from
234 + # `sockopts`. `tls_options` is ignored on this path.
235 + # * `tls: :always|:if_available` (STARTTLS upgrade) reads from
236 + # `tls_options` — only used during do_STARTTLS.
237 + #
238 + # Without sockopts on the implicit-TLS path, OTP 28's `:ssl` falls
239 + # through to its own defaults (verify_peer + `cacerts_get()` which
240 + # returns `:undefined`) and bails with `{options, incompatible,
241 + # [verify: verify_peer, cacerts: undefined]}`. Putting the same opts
242 + # on both keys covers both relay setups.
243 + ssl_opts = [{:versions, tls_versions} | tls_options]
244 +
245 + [
246 + adapter: Swoosh.Adapters.SMTP,
247 + relay: relay,
248 + port: String.to_integer(System.get_env("SMTP_PORT", "587")),
249 + username: System.get_env("SMTP_USERNAME"),
250 + password: System.get_env("SMTP_PASSWORD"),
251 + tls: smtp_tri.("SMTP_TLS", "if_available"),
252 + ssl: System.get_env("SMTP_SSL", "false") == "true",
253 + auth: smtp_tri.("SMTP_AUTH", "if_available"),
254 + allowed_tls_versions: tls_versions,
255 + sockopts: ssl_opts,
256 + tls_options: ssl_opts,
257 + retries: 1,
258 + no_mx_lookups: false
259 + ]
260 + end
261 +
262 + log_opts = [adapter: Swoosh.Adapters.Logger, level: :info]
263 +
264 + present = fn var ->
265 + case System.get_env(var) do
266 + nil -> nil
267 + v -> if String.trim(v) == "", do: nil, else: String.trim(v)
268 + end
269 + end
270 +
271 + mail_prism = {present.("MAIL_PRISM_URL"), present.("MAIL_PRISM_API_KEY")}
272 + mail_prism? = match?({url, key} when is_binary(url) and is_binary(key), mail_prism)
273 +
274 + mail_prism_opts = fn ->
275 + case mail_prism do
276 + {url, key} when is_binary(url) and is_binary(key) ->
277 + [adapter: MailPrism.SwooshAdapter, url: url, api_key: key]
278 +
279 + _ ->
280 + raise "MAIL_PROVIDER=mail_prism needs MAIL_PRISM_URL and MAIL_PRISM_API_KEY"
281 + end
282 + end
283 +
284 + mailer_opts =
285 + case {present.("MAIL_PROVIDER"), present.("SMTP_RELAY")} do
286 + {"mail_prism", _} ->
287 + mail_prism_opts.()
288 +
289 + {nil, _} when mail_prism? ->
290 + mail_prism_opts.()
291 +
292 + {"log", _} ->
293 + log_opts
294 +
295 + {"smtp", nil} ->
296 + raise "MAIL_PROVIDER=smtp needs SMTP_RELAY"
297 +
298 + {"smtp", relay} ->
299 + smtp_opts.(relay)
300 +
301 + {nil, nil} ->
302 + log_opts
303 +
304 + {nil, relay} ->
305 + smtp_opts.(relay)
306 +
307 + {other, _} ->
308 + raise "MAIL_PROVIDER must be one of mail_prism|smtp|log, got: #{inspect(other)}"
256 309 end
257 310
258 311 config :vigil, Vigil.Mailer, mailer_opts
modified docs/deploy.md
+14 −4
@@ -90,13 +90,23 @@ Uploaded files (source maps, artifact bundles) go to local disk unless
90 90
91 91 ### Mail
92 92
93 −Login links, account emails and alert emails. Without `SMTP_RELAY`, mail
94 −is only logged (Swoosh's Logger adapter at `info`), so nothing is sent but
95 −the pod log shows what would have been.
93 +Login links, account emails and alert emails go one of three ways:
94 +
95 +- **mail-prism** (prism.neiam.org), as the sibling apps send. Vigil pushes
96 + its account templates (`priv/mail_prism/`) there at boot. Alerts go as
97 + raw sends.
98 +- **SMTP** through a relay.
99 +- **The log**: nothing is sent; the rendered mail is logged at `info`.
100 +
101 +`MAIL_PROVIDER` chooses. Unset, the choice is mail-prism if both
102 +`MAIL_PRISM_*` are set, else SMTP if `SMTP_RELAY` is set, else the log.
96 103
97 104 | Variable | Default | |
98 105 |---|---|---|
99 −| `SMTP_RELAY` | unset | The relay's hostname. Setting it turns SMTP on |
106 +| `MAIL_PROVIDER` | unset | `mail_prism`, `smtp` or `log`; a named provider missing its settings stops the boot |
107 +| `MAIL_PRISM_URL` | unset | mail-prism's base URL, e.g. `http://mail-prism-svc.mail-prism` in-cluster |
108 +| `MAIL_PRISM_API_KEY` | unset | The application's key. mail-prism only sends as that application's address, so `MAIL_FROM_ADDRESS` must be it |
109 +| `SMTP_RELAY` | unset | The relay's hostname |
100 110 | `SMTP_PORT` | `587` | |
101 111 | `SMTP_USERNAME`, `SMTP_PASSWORD` | unset | |
102 112 | `SMTP_TLS` | `if_available` | STARTTLS: `always`, `if_available` or `never` |
modified lib/vigil/accounts/user_notifier.ex
+50 −25
@@ -5,13 +5,20 @@ defmodule Vigil.Accounts.UserNotifier do
5 5 alias Vigil.Accounts.User
6 6
7 7 # Delivers the email using the application mailer.
8 − defp deliver(recipient, subject, body) do
8 + #
9 + # Each email also names a mail-prism template (priv/mail_prism/<template>.*)
10 + # and its context. MailPrism.SwooshAdapter sends the template and ignores
11 + # the subject and body set here; every other adapter (the dev mailbox,
12 + # tests, SMTP, log) uses them, so they stay and say the same thing.
13 + defp deliver(recipient, subject, body, template, context) do
9 14 email =
10 15 new()
11 16 |> to(recipient)
12 17 |> from(Mailer.sender())
13 18 |> subject(subject)
14 19 |> text_body(body)
20 + |> put_provider_option(:template, template)
21 + |> put_provider_option(:context, context)
15 22
16 23 with {:ok, _metadata} <- Mailer.deliver(email) do
17 24 {:ok, email}
@@ -22,20 +29,26 @@ defmodule Vigil.Accounts.UserNotifier do
22 29 Deliver instructions to update a user email.
23 30 """
24 31 def deliver_update_email_instructions(user, url) do
25 − deliver(user.email, "Update email instructions", """
32 + deliver(
33 + user.email,
34 + "Update email instructions",
35 + """
26 36
27 − ==============================
37 + ==============================
28 38
29 − Hi #{user.email},
39 + Hi #{user.email},
30 40
31 − You can change your email by visiting the URL below:
41 + You can change your email by visiting the URL below:
32 42
33 − #{url}
43 + #{url}
34 44
35 − If you didn't request this change, please ignore this.
45 + If you didn't request this change, please ignore this.
36 46
37 − ==============================
38 − """)
47 + ==============================
48 + """,
49 + "update-email",
50 + %{email: user.email, url: url}
51 + )
39 52 end
40 53
41 54 @doc """
@@ -49,36 +62,48 @@ defmodule Vigil.Accounts.UserNotifier do
49 62 end
50 63
51 64 defp deliver_magic_link_instructions(user, url) do
52 − deliver(user.email, "Log in instructions", """
65 + deliver(
66 + user.email,
67 + "Log in instructions",
68 + """
53 69
54 − ==============================
70 + ==============================
55 71
56 − Hi #{user.email},
72 + Hi #{user.email},
57 73
58 − You can log into your account by visiting the URL below:
74 + You can log into your account by visiting the URL below:
59 75
60 − #{url}
76 + #{url}
61 77
62 − If you didn't request this email, please ignore this.
78 + If you didn't request this email, please ignore this.
63 79
64 − ==============================
65 − """)
80 + ==============================
81 + """,
82 + "magic-link",
83 + %{email: user.email, url: url}
84 + )
66 85 end
67 86
68 87 defp deliver_confirmation_instructions(user, url) do
69 − deliver(user.email, "Confirmation instructions", """
88 + deliver(
89 + user.email,
90 + "Confirmation instructions",
91 + """
70 92
71 − ==============================
93 + ==============================
72 94
73 − Hi #{user.email},
95 + Hi #{user.email},
74 96
75 − You can confirm your account by visiting the URL below:
97 + You can confirm your account by visiting the URL below:
76 98
77 − #{url}
99 + #{url}
78 100
79 − If you didn't create an account with us, please ignore this.
101 + If you didn't create an account with us, please ignore this.
80 102
81 − ==============================
82 − """)
103 + ==============================
104 + """,
105 + "confirm-account",
106 + %{email: user.email, url: url}
107 + )
83 108 end
84 109 end
modified lib/vigil/application.ex
+14 −2
@@ -30,8 +30,7 @@ defmodule Vigil.Application do
30 30 # The ingest edge's key cache and rate-limit counters (subscribes to
31 31 # PubSub for flushes, so after it).
32 32 Vigil.Ingest.Keys,
33 − # Start a worker by calling: Vigil.Worker.start_link(arg)
34 − # {Vigil.Worker, arg},
33 + mail_prism_child(Application.get_env(:vigil, Vigil.Mailer, [])),
35 34 # Start to serve requests, typically the last entry
36 35 VigilWeb.Endpoint
37 36 ]
@@ -53,6 +52,19 @@ defmodule Vigil.Application do
53 52
54 53 # -- end libcluster ----------------------------------------------------------
55 54
55 + # When mail goes through mail-prism, push priv/mail_prism/ to it once at
56 + # boot, in the background (MailPrism.TemplateSync retries for about a
57 + # minute, then logs an error). Sends naming a template that never synced
58 + # fail with unknown_template, so a broken sync is loud, not silent.
59 + defp mail_prism_child(config) do
60 + if config[:adapter] == MailPrism.SwooshAdapter do
61 + {MailPrism.TemplateSync,
62 + dir: Application.app_dir(:vigil, "priv/mail_prism"),
63 + url: config[:url],
64 + api_key: config[:api_key]}
65 + end
66 + end
67 +
56 68 # Tell Phoenix to update the endpoint configuration
57 69 # whenever the application is updated.
58 70 @impl true
modified mix.exs
+3 −0
@@ -92,6 +92,9 @@ defmodule Vigil.MixProject do
92 92 # -- Operations (slice 11): mail and clustering ------------------------
93 93 # Mail in prod goes out through an SMTP relay (config/runtime.exs).
94 94 {:gen_smtp, "~> 1.2"},
95 + # mail-prism (prism.neiam.org): Swoosh adapter + template sync, as the
96 + # sibling apps. Picked by MAIL_PROVIDER / MAIL_PRISM_* (config/runtime.exs).
97 + {:mail_prism, git: "https://gg.neiam.co/neiam/mail_prism_ex.git", tag: "v0.1.0"},
95 98 # Joins the pods into one cluster in prod (Kubernetes strategy behind
96 99 # POD_IP; config/runtime.exs), so PubSub, and with it the ingest key
97 100 # cache flushes, spans the replicas.
modified mix.lock
+1 −0

Click to load diff…

added priv/mail_prism/README.md
+25 −0

Click to load diff…

added priv/mail_prism/confirm-account.html
+8 −0

Click to load diff…

added priv/mail_prism/confirm-account.json
+1 −0

Click to load diff…

added priv/mail_prism/confirm-account.subject
+1 −0

Click to load diff…

added priv/mail_prism/confirm-account.txt
+10 −0

Click to load diff…

added priv/mail_prism/layout.html
+18 −0

Click to load diff…

added priv/mail_prism/layout.json
+1 −0

Click to load diff…

added priv/mail_prism/layout.subject
+1 −0

Click to load diff…

added priv/mail_prism/layout.txt
+4 −0

Click to load diff…

added priv/mail_prism/magic-link.html
+8 −0

Click to load diff…

added priv/mail_prism/magic-link.json
+1 −0

Click to load diff…

added priv/mail_prism/magic-link.subject
+1 −0

Click to load diff…

added priv/mail_prism/magic-link.txt
+10 −0

Click to load diff…

added priv/mail_prism/update-email.html
+8 −0

Click to load diff…

added priv/mail_prism/update-email.json
+1 −0

Click to load diff…

added priv/mail_prism/update-email.subject
+1 −0

Click to load diff…

added priv/mail_prism/update-email.txt
+10 −0

Click to load diff…

added test/vigil/mail_prism_test.exs
+48 −0

Click to load diff…

Parents: 12479e3