Merge branch 'worktree-agent-a8a119efd611ffe4b'

0f3693e · gmorell · 2026-12-01 23:05

11 files +1553 -0

Files changed

modified NOTICE.md
+1 −0
@@ -9,6 +9,7 @@ licenses require.
9 9 Organization roles and their scopes (`Vigil.Organizations.Roles`), the data
10 10 model of organizations, teams, projects and keys, and the ingest and
11 11 processing design described in ROADMAP.md.
12 +Alert webhook payloads for Slack-compatible, Discord, Google Chat, ntfy, Teams and Zulip recipients (`Vigil.Alerts.Webhooks`, from `apps/alerts/webhooks.py` and `apps/uptime/webhooks.py`) and the outbound URL guard (`Vigil.Outbound`, from `check_url_safe` in `apps/uptime/utils.py`).
12 13
13 14 > MIT License
14 15 >
added lib/vigil/alerts/webhooks.ex
+581 −0
@@ -0,0 +1,581 @@
1 +defmodule Vigil.Alerts.Webhooks do
2 + @moduledoc """
3 + Alerts sent over HTTP: to a Slack-compatible webhook, Discord, Google
4 + Chat, ntfy, Microsoft Teams or Zulip. Ported from GlitchTip's
5 + `apps/alerts/webhooks.py` and `apps/uptime/webhooks.py` (MIT), whose
6 + payloads these match field for field, so a receiver set up for GlitchTip
7 + works unchanged.
8 +
9 + There are two kinds of thing to send:
10 +
11 + * an **alert** (`deliver/3`) about one or more issues. Only the first
12 + 3 issues are shown (GlitchTip's `MAX_ISSUES_PER_ALERT`); when there
13 + are more, a line says how many were left out ("and 2 more issues").
14 + The total is `alert.issue_count` when given, else the length of
15 + `alert.issues`;
16 + * a **message** (`deliver_message/3`): a title and a line of text, as
17 + used for test notifications (`test_message/1`) and, later, uptime and
18 + cron alerts. Its shape per type follows GlitchTip's test and uptime
19 + notifications.
20 +
21 + `build/2` and `build_message/2` are pure: they return
22 + `{url, headers, body}`, where `body` is a map (sent as JSON) or a binary
23 + (sent as is, with its content type among the headers). The `deliver`
24 + functions check the URL with `Vigil.Outbound.check_url/2`, then post it.
25 +
26 + ## Recipients
27 +
28 + `%{type: type, url: url, config: config}`, `config` with string keys:
29 +
30 + * `"webhook"` — a Slack-compatible incoming webhook (Slack, Rocket.Chat,
31 + Mattermost…): `{text, attachments: [...]}`. No config.
32 + * `"discord"` — a Discord webhook URL: `{content, embeds: [...]}`. No
33 + config.
34 + * `"googlechat"` — a Google Chat space webhook: `{cardsV2: [...]}`. No
35 + config.
36 + * `"ntfy"` — the topic URL (`https://ntfy.sh/my-topic`). The text is the
37 + body, the title and link go in headers. Config: `"token"` (optional),
38 + an access token sent as `Authorization: Bearer …` for protected
39 + topics. GlitchTip has no such option.
40 + * `"teams"` — a Teams Workflows ("When a Teams webhook request is
41 + received") URL: an Adaptive Card 1.4. No config.
42 + * `"zulip"` — `url` is the Zulip server (`https://chat.example.com`);
43 + the message goes to `/api/v1/messages` as a form, with HTTP Basic
44 + auth. Config: `"bot_email"`, `"api_key"` (the bot's), `"channel"`
45 + (the stream name) and `"topic"` (default `"Vigil Alerts"`). Missing
46 + values are sent empty, as GlitchTip does, and Zulip refuses them.
47 +
48 + ## Colors
49 +
50 + Issues are colored by level as GlitchTip's `Issue.get_hex_color`:
51 + fatal and error `#e52b50`, warning `#e9b949`, info `#4b60b4`, debug
52 + none. Messages by level: error and warning as above, info `#4b60b4`,
53 + ok `#36a64f`. Discord takes the same colors as integers.
54 +
55 + ## HTTP
56 +
57 + `Req.post/1` with a 10 s receive timeout, no retries (the caller's Oban
58 + job retries) and the user agent `Vigil-Alerts/1`. A 2xx answer is `:ok`;
59 + any other is `{:error, {:http, status, body}}` with the body cut to 500
60 + characters; a failed connection is `{:error, {:transport, reason}}`.
61 + Options: `:req_options` (merged into the Req call; tests pass `plug:`)
62 + and `:resolver` (passed to `Vigil.Outbound.check_url/2`).
63 + """
64 +
65 + @max_issues 3
66 + @body_limit 500
67 + @user_agent "Vigil-Alerts/1"
68 + @default_zulip_topic "Vigil Alerts"
69 +
70 + @level_colors %{
71 + "fatal" => "#e52b50",
72 + "error" => "#e52b50",
73 + "warning" => "#e9b949",
74 + "info" => "#4b60b4"
75 + }
76 +
77 + @message_colors %{
78 + "error" => "#e52b50",
79 + "warning" => "#e9b949",
80 + "info" => "#4b60b4",
81 + "ok" => "#36a64f"
82 + }
83 +
84 + @standard_tags [
85 + {"environment", "Environment"},
86 + {"server_name", "Server Name"},
87 + {"release", "Release"}
88 + ]
89 +
90 + @types ~w(webhook discord googlechat ntfy teams zulip)
91 +
92 + @type recipient :: %{type: String.t(), url: String.t(), config: map()}
93 + @type issue :: %{
94 + title: String.t(),
95 + culprit: String.t() | nil,
96 + short_id: String.t(),
97 + url: String.t(),
98 + level: String.t(),
99 + count: non_neg_integer(),
100 + first_seen: DateTime.t(),
101 + last_seen: DateTime.t(),
102 + status: atom(),
103 + tags: %{optional(String.t()) => String.t()}
104 + }
105 + @type alert :: %{
106 + required(:title) => String.t(),
107 + required(:project) => %{name: String.t(), slug: String.t()},
108 + required(:organization) => %{name: String.t(), slug: String.t()},
109 + required(:url) => String.t() | nil,
110 + required(:issues) => [issue()],
111 + optional(:issue_count) => non_neg_integer()
112 + }
113 + @type message :: %{
114 + title: String.t(),
115 + text: String.t(),
116 + url: String.t() | nil,
117 + level: String.t()
118 + }
119 + @type request :: {String.t(), [{String.t(), String.t()}], map() | binary()}
120 + @type error ::
121 + {:http, pos_integer(), String.t()}
122 + | {:transport, term()}
123 + | {:unsafe_url, Vigil.Outbound.reason()}
124 + | {:unsupported_type, term()}
125 +
126 + @doc "The recipient types this module can send to."
127 + @spec types() :: [String.t()]
128 + def types, do: @types
129 +
130 + @doc "How many issues an alert shows at most."
131 + @spec max_issues() :: pos_integer()
132 + def max_issues, do: @max_issues
133 +
134 + @doc "Sends an issue alert to `recipient`."
135 + @spec deliver(recipient(), alert(), keyword()) :: :ok | {:error, error()}
136 + def deliver(recipient, alert, opts \\ []) do
137 + send_request(recipient, opts, fn -> build(recipient, alert) end)
138 + end
139 +
140 + @doc "Sends a plain message (a test notification, an uptime alert) to `recipient`."
141 + @spec deliver_message(recipient(), message(), keyword()) :: :ok | {:error, error()}
142 + def deliver_message(recipient, message, opts \\ []) do
143 + send_request(recipient, opts, fn -> build_message(recipient, message) end)
144 + end
145 +
146 + @doc """
147 + The message sent by the "send test notification" button, worded as
148 + GlitchTip's fallback test notification.
149 + """
150 + @spec test_message(%{name: String.t()}) :: message()
151 + def test_message(project) do
152 + %{
153 + title: "Vigil Test Notification",
154 + text:
155 + "Test notification for project #{project.name}. " <>
156 + "Your alert recipient is configured correctly.",
157 + url: nil,
158 + level: "info"
159 + }
160 + end
161 +
162 + ## Builders
163 +
164 + @doc "The `{url, headers, body}` for an issue alert. Raises on an unknown type."
165 + @spec build(recipient(), alert()) :: request()
166 + def build(%{type: "webhook", url: url}, alert) do
167 + attachments = Enum.map(shown_issues(alert), &slack_attachment(&1, alert))
168 +
169 + more =
170 + case more_text(alert) do
171 + nil -> []
172 + text -> [slack_more_attachment(text, alert)]
173 + end
174 +
175 + json(url, %{text: alert.title, attachments: attachments ++ more})
176 + end
177 +
178 + def build(%{type: "discord", url: url}, alert) do
179 + embeds = Enum.map(shown_issues(alert), &discord_embed(&1, alert))
180 + json(url, %{content: with_more(alert.title, alert, "\n"), embeds: embeds})
181 + end
182 +
183 + def build(%{type: "googlechat", url: url}, alert) do
184 + cards = Enum.map(shown_issues(alert), &googlechat_issue_card(&1, alert))
185 +
186 + more =
187 + case more_text(alert) do
188 + nil -> []
189 + text -> [googlechat_card(alert.title, alert.project.name, text, alert.url)]
190 + end
191 +
192 + json(url, googlechat_payload(cards ++ more))
193 + end
194 +
195 + def build(%{type: "ntfy"} = recipient, alert) do
196 + issues = shown_issues(alert)
197 + body = issues |> Enum.map(&ntfy_issue(&1, alert)) |> Enum.join("\n\n")
198 + click = Enum.find_value(issues, & &1.url)
199 + ntfy(recipient, alert.title, with_more(body, alert, "\n\n"), click, "warning")
200 + end
201 +
202 + def build(%{type: "teams", url: url}, alert) do
203 + issues = shown_issues(alert)
204 + title_block = teams_title(alert.title)
205 + issue_blocks = Enum.flat_map(issues, &teams_issue_blocks(&1, alert))
206 +
207 + more =
208 + case more_text(alert) do
209 + nil -> []
210 + text -> [%{type: "TextBlock", text: text, wrap: true}]
211 + end
212 +
213 + actions = Enum.map(issues, &teams_action("View Issue #{&1.short_id}", &1.url))
214 + json(url, teams_payload([title_block | issue_blocks] ++ more, actions))
215 + end
216 +
217 + def build(%{type: "zulip"} = recipient, alert) do
218 + issues = alert |> shown_issues() |> Enum.map(&zulip_issue(&1, alert))
219 + content = Enum.join(["## #{alert.title}" | issues], "\n\n")
220 + zulip(recipient, with_more(content, alert, "\n\n"))
221 + end
222 +
223 + def build(%{type: type}, _alert), do: raise(ArgumentError, "unsupported type #{inspect(type)}")
224 +
225 + @doc "The `{url, headers, body}` for a plain message. Raises on an unknown type."
226 + @spec build_message(recipient(), message()) :: request()
227 + def build_message(%{type: "webhook", url: url}, message) do
228 + attachment = %{
229 + title: message.title,
230 + title_link: message.url || "",
231 + text: message.text,
232 + image_url: nil,
233 + color: message_color(message),
234 + fields: nil,
235 + mrkdown_in: nil
236 + }
237 +
238 + json(url, %{text: message.title, attachments: [attachment]})
239 + end
240 +
241 + def build_message(%{type: "discord", url: url}, message) do
242 + embed = %{
243 + title: message.title,
244 + description: message.text,
245 + color: discord_color(message_color(message)),
246 + url: message.url || "",
247 + fields: []
248 + }
249 +
250 + json(url, %{content: message.title, embeds: [embed]})
251 + end
252 +
253 + def build_message(%{type: "googlechat", url: url}, message) do
254 + card = googlechat_card(message.title, nil, message.text, message.url)
255 + json(url, googlechat_payload([card]))
256 + end
257 +
258 + def build_message(%{type: "ntfy"} = recipient, message) do
259 + tag = if message.level in ["ok", "info"], do: "white_check_mark", else: "warning"
260 + ntfy(recipient, message.title, message.text, message.url, tag)
261 + end
262 +
263 + def build_message(%{type: "teams", url: url}, message) do
264 + body = [teams_title(message.title), %{type: "TextBlock", text: message.text, wrap: true}]
265 + actions = if message.url, do: [teams_action("View", message.url)], else: []
266 + json(url, teams_payload(body, actions))
267 + end
268 +
269 + def build_message(%{type: "zulip"} = recipient, message) do
270 + link = if message.url, do: ["[View](#{message.url})"], else: []
271 + zulip(recipient, Enum.join(["## #{message.title}", message.text | link], "\n\n"))
272 + end
273 +
274 + def build_message(%{type: type}, _message),
275 + do: raise(ArgumentError, "unsupported type #{inspect(type)}")
276 +
277 + ## Slack-compatible
278 +
279 + defp slack_attachment(issue, alert) do
280 + project = %{title: "Project", value: alert.project.name, short: true}
281 +
282 + tags =
283 + for {key, label, value} <- issue_tags(issue) do
284 + %{title: label, value: value, short: key in ["environment", "server_name"]}
285 + end
286 +
287 + %{
288 + title: issue.title,
289 + title_link: issue.url,
290 + text: issue.culprit,
291 + image_url: nil,
292 + color: issue_color(issue),
293 + fields: [project | tags],
294 + mrkdown_in: ["text"]
295 + }
296 + end
297 +
298 + defp slack_more_attachment(text, alert) do
299 + %{
300 + title: text,
301 + title_link: alert.url || "",
302 + text: "",
303 + image_url: nil,
304 + color: nil,
305 + fields: nil,
306 + mrkdown_in: nil
307 + }
308 + end
309 +
310 + ## Discord
311 +
312 + defp discord_embed(issue, alert) do
313 + project = %{name: "Project", value: alert.project.name, inline: true}
314 +
315 + tags =
316 + for {key, label, value} <- issue_tags(issue) do
317 + %{name: label, value: value, inline: key == "environment"}
318 + end
319 +
320 + %{
321 + title: issue.title,
322 + description: issue.culprit,
323 + color: discord_color(issue_color(issue)),
324 + url: issue.url,
325 + fields: [project | tags]
326 + }
327 + end
328 +
329 + defp discord_color(nil), do: nil
330 + defp discord_color("#" <> hex), do: String.to_integer(hex, 16)
331 +
332 + ## Google Chat
333 +
334 + defp googlechat_payload(cards) do
335 + %{cardsV2: Enum.map(cards, &%{cardId: "createCardMessage", card: &1})}
336 + end
337 +
338 + defp googlechat_issue_card(issue, alert) do
339 + tags =
340 + for {_key, label, value} <- issue_tags(issue) do
341 + %{decoratedText: %{topLabel: label, text: value}}
342 + end
343 +
344 + button = %{
345 + buttonList: %{
346 + buttons: [
347 + %{text: "View Issue #{issue.short_id}", onClick: %{openLink: %{url: issue.url}}}
348 + ]
349 + }
350 + }
351 +
352 + culprit = %{decoratedText: %{topLabel: "Culprit", text: issue.culprit}}
353 +
354 + %{
355 + header: %{title: alert.title, subtitle: alert.project.name},
356 + sections: [
357 + %{header: googlechat_section_header(issue), widgets: [culprit | tags] ++ [button]}
358 + ]
359 + }
360 + end
361 +
362 + # GlitchTip writes `<font color='None'>` for colorless levels; we leave
363 + # the font tag out instead.
364 + defp googlechat_section_header(issue) do
365 + case issue_color(issue) do
366 + nil -> issue.title
367 + color -> "<font color='#{color}'>#{issue.title}</font>"
368 + end
369 + end
370 +
371 + # With a link: GlitchTip's uptime card (text and a "View" button);
372 + # without: its test-notification card (text only).
373 + defp googlechat_card(title, subtitle, text, url) do
374 + decorated =
375 + if url,
376 + do: %{text: text, button: %{text: "View", onClick: %{openLink: %{url: url}}}},
377 + else: %{text: text}
378 +
379 + header = if subtitle, do: %{title: title, subtitle: subtitle}, else: %{title: title}
380 + %{header: header, sections: [%{widgets: [%{decoratedText: decorated}]}]}
381 + end
382 +
383 + ## ntfy
384 +
385 + defp ntfy_issue(issue, alert) do
386 + culprit = if present?(issue.culprit), do: ["Culprit: #{issue.culprit}"], else: []
387 +
388 + Enum.join(
389 + ["**#{issue.title}**", "Project: #{alert.project.name}"] ++
390 + culprit ++
391 + tag_lines(issue) ++ ["[View Issue #{issue.short_id}](#{issue.url})"],
392 + "\n"
393 + )
394 + end
395 +
396 + defp ntfy(%{url: url} = recipient, title, body, click, tag) do
397 + headers =
398 + [{"title", title}, {"markdown", "yes"}] ++
399 + if(click, do: [{"click", click}], else: []) ++
400 + [{"tags", tag}, {"content-type", "text/plain; charset=utf-8"}] ++
401 + ntfy_auth(config(recipient))
402 +
403 + {url, headers, body}
404 + end
405 +
406 + defp ntfy_auth(%{"token" => token}) when is_binary(token) and token != "",
407 + do: [{"authorization", "Bearer " <> token}]
408 +
409 + defp ntfy_auth(_config), do: []
410 +
411 + ## Teams
412 +
413 + defp teams_title(text), do: %{type: "TextBlock", size: "Large", weight: "Bolder", text: text}
414 +
415 + defp teams_issue_blocks(issue, alert) do
416 + facts = [
417 + %{title: "Project", value: alert.project.name}
418 + | for({_key, label, value} <- issue_tags(issue), do: %{title: label, value: value})
419 + ]
420 +
421 + culprit =
422 + if present?(issue.culprit),
423 + do: [%{type: "TextBlock", text: issue.culprit, wrap: true}],
424 + else: []
425 +
426 + [%{type: "TextBlock", weight: "Bolder", color: "Attention", text: issue.title, wrap: true}] ++
427 + culprit ++ [%{type: "FactSet", facts: facts}]
428 + end
429 +
430 + defp teams_action(title, url), do: %{type: "Action.OpenUrl", title: title, url: url}
431 +
432 + defp teams_payload(body, actions) do
433 + content =
434 + %{
435 + "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
436 + type: "AdaptiveCard",
437 + version: "1.4",
438 + body: body
439 + }
440 + |> then(&if actions == [], do: &1, else: Map.put(&1, :actions, actions))
441 +
442 + %{
443 + type: "message",
444 + attachments: [
445 + %{
446 + contentType: "application/vnd.microsoft.card.adaptive",
447 + contentUrl: nil,
448 + content: content
449 + }
450 + ]
451 + }
452 + end
453 +
454 + ## Zulip
455 +
456 + defp zulip_issue(issue, alert) do
457 + culprit = if present?(issue.culprit), do: ["Culprit: #{issue.culprit}"], else: []
458 +
459 + Enum.join(
460 + ["**[#{issue.title}](#{issue.url})**", "Project: #{alert.project.name}"] ++
461 + culprit ++ tag_lines(issue),
462 + "\n"
463 + )
464 + end
465 +
466 + defp zulip(%{url: server} = recipient, content) do
467 + config = config(recipient)
468 +
469 + form = [
470 + type: "channel",
471 + to: config["channel"] || "",
472 + topic: config["topic"] || @default_zulip_topic,
473 + content: content
474 + ]
475 +
476 + credentials = Base.encode64("#{config["bot_email"]}:#{config["api_key"]}")
477 +
478 + headers = [
479 + {"authorization", "Basic " <> credentials},
480 + {"content-type", "application/x-www-form-urlencoded"}
481 + ]
482 +
483 + {String.trim_trailing(server, "/") <> "/api/v1/messages", headers, URI.encode_query(form)}
484 + end
485 +
486 + ## Shared
487 +
488 + defp json(url, payload), do: {url, [], payload}
489 +
490 + defp config(recipient), do: Map.get(recipient, :config) || %{}
491 +
492 + defp shown_issues(alert), do: Enum.take(alert.issues, @max_issues)
493 +
494 + defp issue_count(alert), do: Map.get(alert, :issue_count) || length(alert.issues)
495 +
496 + defp more_text(alert) do
497 + case issue_count(alert) - length(shown_issues(alert)) do
498 + n when n <= 0 -> nil
499 + 1 -> "and 1 more issue"
500 + n -> "and #{n} more issues"
501 + end
502 + end
503 +
504 + defp with_more(text, alert, separator) do
505 + case more_text(alert) do
506 + nil -> text
507 + more -> text <> separator <> more
508 + end
509 + end
510 +
511 + # GlitchTip's gather_issue_tags: environment, server name and release
512 + # first, then the extra tags (here sorted by key), labelled like Python's
513 + # str.capitalize ("custom_tag" → "Custom_tag"). Empty values are skipped.
514 + defp issue_tags(issue) do
515 + tags = Map.get(issue, :tags) || %{}
516 + standard = for {key, label} <- @standard_tags, do: {key, label, tags[key]}
517 + standard_keys = Enum.map(@standard_tags, &elem(&1, 0))
518 +
519 + extra =
520 + for {key, value} <- Enum.sort(tags), key not in standard_keys do
521 + {key, String.capitalize(key), value}
522 + end
523 +
524 + Enum.filter(standard ++ extra, fn {_, _, value} -> present?(value) end)
525 + end
526 +
527 + defp tag_lines(issue), do: for({_, label, value} <- issue_tags(issue), do: "#{label}: #{value}")
528 +
529 + defp issue_color(issue), do: @level_colors[issue.level]
530 +
531 + defp message_color(message), do: @message_colors[message.level]
532 +
533 + defp present?(value), do: is_binary(value) and value != ""
534 +
535 + ## HTTP
536 +
537 + defp send_request(%{type: type, url: url}, opts, build) when type in @types do
538 + case Vigil.Outbound.check_url(url, Keyword.take(opts, [:resolver])) do
539 + :ok -> post(build.(), Keyword.get(opts, :req_options, []))
540 + {:error, reason} -> {:error, {:unsafe_url, reason}}
541 + end
542 + end
543 +
544 + defp send_request(recipient, _opts, _build),
545 + do: {:error, {:unsupported_type, Map.get(recipient, :type)}}
546 +
547 + defp post({url, headers, body}, req_options) do
548 + payload = if is_map(body), do: [json: body], else: [body: body]
549 +
550 + [
551 + url: url,
552 + headers: headers,
553 + receive_timeout: 10_000,
554 + retry: false,
555 + decode_body: false,
556 + user_agent: @user_agent
557 + ]
558 + |> Keyword.merge(payload)
559 + |> Keyword.merge(req_options)
560 + |> Req.post()
561 + |> handle_response()
562 + end
563 +
564 + defp handle_response({:ok, %Req.Response{status: status}}) when status in 200..299, do: :ok
565 +
566 + defp handle_response({:ok, %Req.Response{status: status, body: body}}),
567 + do: {:error, {:http, status, truncate(body)}}
568 +
569 + defp handle_response({:error, %Req.TransportError{reason: reason}}),
570 + do: {:error, {:transport, reason}}
571 +
572 + defp handle_response({:error, exception}), do: {:error, {:transport, exception}}
573 +
574 + defp truncate(body) when is_binary(body) do
575 + if String.valid?(body),
576 + do: String.slice(body, 0, @body_limit),
577 + else: binary_part(body, 0, min(byte_size(body), @body_limit))
578 + end
579 +
580 + defp truncate(body), do: body |> inspect() |> truncate()
581 +end
added lib/vigil/outbound.ex
+196 −0
@@ -0,0 +1,196 @@
1 +defmodule Vigil.Outbound do
2 + @moduledoc """
3 + A guard for requests Vigil makes to URLs its users typed in: alert
4 + webhooks today, uptime checks later. Without it, anyone who can edit an
5 + alert recipient could point Vigil at `http://169.254.169.254/` (a cloud
6 + provider's metadata service, which hands out credentials) or at a
7 + database admin page on the private network, and read the answer back
8 + through error messages.
9 +
10 + `check_url/2` says `:ok` only when:
11 +
12 + 1. the scheme is `http` or `https` and there is a host;
13 + 2. every address the host resolves to (A *and* AAAA records, or the
14 + literal address when the host is an IP) is a public unicast one.
15 +
16 + Refused addresses, IPv4: `0.0.0.0/8`, `10/8`, `100.64/10` (carrier-grade
17 + NAT), `127/8`, `169.254/16` (link-local, including the metadata service),
18 + `172.16/12`, `192.0.0/24`, the documentation nets `192.0.2/24`,
19 + `198.51.100/24` and `203.0.113/24`, `198.18/15` (benchmarking),
20 + `192.168/16`, `224/4` (multicast) and `240/4` (reserved, with the
21 + broadcast address). IPv6: `::` and `::1` (and the rest of the deprecated
22 + IPv4-compatible `::/96`), `fc00::/7` (unique local), `fe80::/10`
23 + (link-local), `fec0::/10` (old site-local), `ff00::/8` (multicast),
24 + `100::/64` (discard), `2001:db8::/32` (documentation) and `2001::/32`
25 + (Teredo). Addresses with an IPv4 address inside — IPv4-mapped
26 + `::ffff:a.b.c.d`, NAT64 `64:ff9b::a.b.c.d` and 6to4 `2002:a.b.c.d::` — are
27 + judged by that IPv4 address.
28 +
29 + One refused address is enough: a host with a public and a private record
30 + could be connected to over either.
31 +
32 + Unlike GlitchTip's `check_url_safe` (`apps/uptime/utils.py`, MIT), on
33 + which this is modelled, a host that does not resolve is refused rather
34 + than waved through; the request would fail anyway, and the error is
35 + clearer this way.
36 +
37 + ## Configuration
38 +
39 + `config :vigil, :allow_private_outbound, true` skips the address checks
40 + (the scheme and host are still checked), so a developer can point a
41 + webhook at a server on `localhost`. It is meant for development only:
42 + never set it where untrusted users can create alert recipients.
43 +
44 + ## Known limitation: DNS rebinding
45 +
46 + The check resolves the name, and then the HTTP client resolves it again
47 + to connect. A hostile DNS server can answer the first lookup with a
48 + public address and the second with a private one. Closing that hole
49 + means connecting to the checked address itself (and sending the name in
50 + `Host`/SNI), which Vigil does not do yet.
51 + """
52 +
53 + import Bitwise
54 +
55 + @type reason ::
56 + :invalid_url
57 + | {:scheme_not_allowed, String.t() | nil}
58 + | :missing_host
59 + | {:blocked_address, :inet.ip_address()}
60 + | {:resolve, term()}
61 +
62 + @ipv4_blocked [
63 + {{0, 0, 0, 0}, 8},
64 + {{10, 0, 0, 0}, 8},
65 + {{100, 64, 0, 0}, 10},
66 + {{127, 0, 0, 0}, 8},
67 + {{169, 254, 0, 0}, 16},
68 + {{172, 16, 0, 0}, 12},
69 + {{192, 0, 0, 0}, 24},
70 + {{192, 0, 2, 0}, 24},
71 + {{192, 168, 0, 0}, 16},
72 + {{198, 18, 0, 0}, 15},
73 + {{198, 51, 100, 0}, 24},
74 + {{203, 0, 113, 0}, 24},
75 + {{224, 0, 0, 0}, 4},
76 + {{240, 0, 0, 0}, 4}
77 + ]
78 +
79 + @ipv6_blocked [
80 + {{0, 0, 0, 0, 0, 0, 0, 0}, 96},
81 + {{0x100, 0, 0, 0, 0, 0, 0, 0}, 64},
82 + {{0x2001, 0, 0, 0, 0, 0, 0, 0}, 32},
83 + {{0x2001, 0xDB8, 0, 0, 0, 0, 0, 0}, 32},
84 + {{0xFC00, 0, 0, 0, 0, 0, 0, 0}, 7},
85 + {{0xFE80, 0, 0, 0, 0, 0, 0, 0}, 10},
86 + {{0xFEC0, 0, 0, 0, 0, 0, 0, 0}, 10},
87 + {{0xFF00, 0, 0, 0, 0, 0, 0, 0}, 8}
88 + ]
89 +
90 + @doc """
91 + `:ok` when `url` may be requested, `{:error, reason}` otherwise.
92 +
93 + Options:
94 +
95 + * `:resolver` — a 1-arity function from the host (a string) to
96 + `{:ok, [ip_tuple]} | {:error, reason}`; defaults to asking
97 + `:inet.getaddrs/2` for both IPv4 and IPv6 addresses. Tests use it to
98 + avoid real DNS.
99 + """
100 + @spec check_url(String.t(), keyword()) :: :ok | {:error, reason()}
101 + def check_url(url, opts \\ [])
102 +
103 + def check_url(url, opts) when is_binary(url) do
104 + with {:ok, host} <- parse(url) do
105 + if Application.get_env(:vigil, :allow_private_outbound, false),
106 + do: :ok,
107 + else: check_host(host, Keyword.get(opts, :resolver, &resolve/1))
108 + end
109 + end
110 +
111 + def check_url(_url, _opts), do: {:error, :invalid_url}
112 +
113 + @doc "True when `ip` (an `:inet` address tuple) must not be connected to."
114 + @spec blocked_address?(:inet.ip_address()) :: boolean()
115 + def blocked_address?({_, _, _, _} = ip), do: Enum.any?(@ipv4_blocked, &in_cidr?(ip, &1))
116 +
117 + def blocked_address?({_, _, _, _, _, _, _, _} = ip) do
118 + case embedded_ipv4(ip) do
119 + nil -> Enum.any?(@ipv6_blocked, &in_cidr?(ip, &1))
120 + v4 -> blocked_address?(v4)
121 + end
122 + end
123 +
124 + defp parse(url) do
125 + case URI.new(url) do
126 + {:ok, %URI{scheme: scheme}} when scheme not in ["http", "https"] ->
127 + {:error, {:scheme_not_allowed, scheme}}
128 +
129 + {:ok, %URI{host: host}} when host in [nil, ""] ->
130 + {:error, :missing_host}
131 +
132 + {:ok, %URI{host: host}} ->
133 + {:ok, host}
134 +
135 + {:error, _} ->
136 + {:error, :invalid_url}
137 + end
138 + end
139 +
140 + defp check_host(host, resolver) do
141 + with {:ok, addresses} <- addresses(host, resolver) do
142 + case Enum.find(addresses, &blocked_address?/1) do
143 + nil -> :ok
144 + ip -> {:error, {:blocked_address, ip}}
145 + end
146 + end
147 + end
148 +
149 + # A literal address (URI strips the brackets of `[::1]`) is used as is.
150 + defp addresses(host, resolver) do
151 + case :inet.parse_strict_address(String.to_charlist(host)) do
152 + {:ok, ip} ->
153 + {:ok, [ip]}
154 +
155 + {:error, _} ->
156 + case resolver.(host) do
157 + {:ok, [_ | _] = ips} -> {:ok, ips}
158 + {:ok, []} -> {:error, {:resolve, :nxdomain}}
159 + {:error, reason} -> {:error, {:resolve, reason}}
160 + end
161 + end
162 + end
163 +
164 + defp resolve(host) do
165 + name = String.to_charlist(host)
166 + results = for family <- [:inet, :inet6], do: :inet.getaddrs(name, family)
167 +
168 + case for({:ok, ips} <- results, do: ips) do
169 + # Both lookups failed; report the IPv4 one.
170 + [] -> hd(results)
171 + lists -> {:ok, Enum.concat(lists)}
172 + end
173 + end
174 +
175 + # ::ffff:a.b.c.d, 64:ff9b::a.b.c.d and 2002:AABB:CCDD::/48 carry IPv4.
176 + defp embedded_ipv4({0, 0, 0, 0, 0, 0xFFFF, hi, lo}), do: v4(hi, lo)
177 + defp embedded_ipv4({0x64, 0xFF9B, 0, 0, 0, 0, hi, lo}), do: v4(hi, lo)
178 + defp embedded_ipv4({0x2002, hi, lo, _, _, _, _, _}), do: v4(hi, lo)
179 + defp embedded_ipv4(_), do: nil
180 +
181 + defp v4(hi, lo), do: {hi >>> 8, hi &&& 0xFF, lo >>> 8, lo &&& 0xFF}
182 +
183 + defp in_cidr?(ip, {net, bits}) when tuple_size(ip) == tuple_size(net) do
184 + width = if tuple_size(ip) == 4, do: 32, else: 128
185 + shift = width - bits
186 + to_integer(ip) >>> shift == to_integer(net) >>> shift
187 + end
188 +
189 + defp in_cidr?(_ip, _cidr), do: false
190 +
191 + defp to_integer({a, b, c, d}), do: a <<< 24 ||| b <<< 16 ||| c <<< 8 ||| d
192 +
193 + defp to_integer(ip6) do
194 + ip6 |> Tuple.to_list() |> Enum.reduce(0, fn part, acc -> acc <<< 16 ||| part end)
195 + end
196 +end
added test/vigil/alerts/webhooks_test.exs
+646 −0
@@ -0,0 +1,646 @@
1 +defmodule Vigil.Alerts.WebhooksTest do
2 + # Mirrors GlitchTip's apps/alerts/tests/test_webhooks.py, plus delivery.
3 + use ExUnit.Case, async: true
4 +
5 + alias Vigil.Alerts.Webhooks
6 +
7 + @webhook_url "https://chat.example.com/hooks/abc"
8 + @discord_url "https://discord.com/api/webhooks/not_real_id/not_real_token"
9 + @googlechat_url "https://chat.googleapis.com/v1/spaces/space_id/messages?key=k&token=t"
10 + @ntfy_url "https://ntfy.sh/vigil-test-topic"
11 + @teams_url "https://example.webhook.office.com/webhookb2/test"
12 + @zulip_url "https://zulip.example.com/"
13 + @zulip_config %{
14 + "bot_email" => "bot@zulip.example.com",
15 + "api_key" => "test-api-key",
16 + "channel" => "alerts",
17 + "topic" => "Vigil Alerts"
18 + }
19 +
20 + @public_resolver [resolver: &__MODULE__.public_resolver/1]
21 +
22 + def public_resolver(_host), do: {:ok, [{93, 184, 216, 34}]}
23 +
24 + defp recipient(type, url, config \\ %{}), do: %{type: type, url: url, config: config}
25 +
26 + defp issue(attrs \\ %{}) do
27 + Map.merge(
28 + %{
29 + title: "ZeroDivisionError: division by zero",
30 + culprit: "app.views in divide",
31 + short_id: "WEB-12",
32 + url: "https://vigil.example.com/acme/issues/12",
33 + level: "error",
34 + count: 7,
35 + first_seen: ~U[2026-11-30 10:00:00Z],
36 + last_seen: ~U[2026-12-01 09:00:00Z],
37 + status: :unresolved,
38 + tags: %{
39 + "environment" => "test-environment",
40 + "release" => "test-release",
41 + "custom_tag" => "custom_value"
42 + }
43 + },
44 + attrs
45 + )
46 + end
47 +
48 + defp alert(issues, attrs \\ %{}) do
49 + count = Map.get(attrs, :issue_count, length(issues))
50 + title = if count > 1, do: "Vigil Alert (#{count} issues)", else: "Vigil Alert"
51 +
52 + Map.merge(
53 + %{
54 + title: title,
55 + project: %{name: "Web", slug: "web"},
56 + organization: %{name: "Acme", slug: "acme"},
57 + url: "https://vigil.example.com/acme/projects/web",
58 + issues: issues
59 + },
60 + attrs
61 + )
62 + end
63 +
64 + defp many_issues(n) do
65 + for i <- 1..n,
66 + do: issue(%{short_id: "WEB-#{i}", title: "Issue #{i}", url: "https://v.example/#{i}"})
67 + end
68 +
69 + defp json_body({_url, _headers, body}), do: body |> Jason.encode!() |> Jason.decode!()
70 +
71 + describe "build/2 webhook (Slack-compatible)" do
72 + test "an issue becomes an attachment with project and tag fields" do
73 + {url, headers, body} = Webhooks.build(recipient("webhook", @webhook_url), alert([issue()]))
74 +
75 + assert url == @webhook_url
76 + assert headers == []
77 + assert body.text == "Vigil Alert"
78 +
79 + assert [attachment] = body.attachments
80 +
81 + assert attachment == %{
82 + title: "ZeroDivisionError: division by zero",
83 + title_link: "https://vigil.example.com/acme/issues/12",
84 + text: "app.views in divide",
85 + image_url: nil,
86 + color: "#e52b50",
87 + mrkdown_in: ["text"],
88 + fields: [
89 + %{title: "Project", value: "Web", short: true},
90 + %{title: "Environment", value: "test-environment", short: true},
91 + %{title: "Release", value: "test-release", short: false},
92 + %{title: "Custom_tag", value: "custom_value", short: false}
93 + ]
94 + }
95 + end
96 +
97 + test "server_name is a short field and empty tags are skipped" do
98 + tags = %{"server_name" => "web-1", "release" => "", "environment" => "prod"}
99 +
100 + {_, _, body} =
101 + Webhooks.build(recipient("webhook", @webhook_url), alert([issue(%{tags: tags})]))
102 +
103 + assert [_project, env, server] = hd(body.attachments).fields
104 + assert env == %{title: "Environment", value: "prod", short: true}
105 + assert server == %{title: "Server Name", value: "web-1", short: true}
106 + end
107 +
108 + test "colors follow the level" do
109 + colors =
110 + for level <- ~w(fatal error warning info debug) do
111 + {_, _, body} =
112 + Webhooks.build(recipient("webhook", @webhook_url), alert([issue(%{level: level})]))
113 +
114 + hd(body.attachments).color
115 + end
116 +
117 + assert colors == ["#e52b50", "#e52b50", "#e9b949", "#4b60b4", nil]
118 + end
119 +
120 + test "at most three issues, then an 'N more' attachment linking to the project" do
121 + a = alert(many_issues(5))
122 + {_, _, body} = Webhooks.build(recipient("webhook", @webhook_url), a)
123 +
124 + assert body.text == "Vigil Alert (5 issues)"
125 + assert length(body.attachments) == 4
126 +
127 + assert Enum.map(Enum.take(body.attachments, 3), & &1.title) == [
128 + "Issue 1",
129 + "Issue 2",
130 + "Issue 3"
131 + ]
132 +
133 + more = List.last(body.attachments)
134 + assert more.title == "and 2 more issues"
135 + assert more.title_link == a.url
136 + end
137 +
138 + test "issue_count beyond the issues given counts toward 'more'" do
139 + a = alert([issue()], %{issue_count: 2})
140 + {_, _, body} = Webhooks.build(recipient("webhook", @webhook_url), a)
141 +
142 + assert body.text == "Vigil Alert (2 issues)"
143 + assert List.last(body.attachments).title == "and 1 more issue"
144 + end
145 + end
146 +
147 + describe "build/2 discord" do
148 + test "issues become embeds with integer colors" do
149 + {url, [], body} = Webhooks.build(recipient("discord", @discord_url), alert([issue()]))
150 +
151 + assert url == @discord_url
152 + assert body.content == "Vigil Alert"
153 +
154 + assert [embed] = body.embeds
155 +
156 + assert embed == %{
157 + title: "ZeroDivisionError: division by zero",
158 + description: "app.views in divide",
159 + color: 0xE52B50,
160 + url: "https://vigil.example.com/acme/issues/12",
161 + fields: [
162 + %{name: "Project", value: "Web", inline: true},
163 + %{name: "Environment", value: "test-environment", inline: true},
164 + %{name: "Release", value: "test-release", inline: false},
165 + %{name: "Custom_tag", value: "custom_value", inline: false}
166 + ]
167 + }
168 +
169 + assert json_body({url, [], body}) |> get_in(["embeds", Access.at(0), "color"]) ==
170 + 15_018_832
171 + end
172 +
173 + test "debug issues have no color; extra issues are counted in the content" do
174 + {_, _, body} =
175 + Webhooks.build(
176 + recipient("discord", @discord_url),
177 + alert([issue(%{level: "debug"}) | many_issues(3)])
178 + )
179 +
180 + assert hd(body.embeds).color == nil
181 + assert length(body.embeds) == 3
182 + assert body.content == "Vigil Alert (4 issues)\nand 1 more issue"
183 + end
184 + end
185 +
186 + describe "build/2 googlechat" do
187 + test "one cardsV2 card per issue" do
188 + {url, [], body} = Webhooks.build(recipient("googlechat", @googlechat_url), alert([issue()]))
189 + assert url == @googlechat_url
190 +
191 + assert [%{cardId: "createCardMessage", card: card}] = body.cardsV2
192 + assert card.header == %{title: "Vigil Alert", subtitle: "Web"}
193 +
194 + assert [section] = card.sections
195 + assert section.header == "<font color='#e52b50'>ZeroDivisionError: division by zero</font>"
196 +
197 + assert section.widgets == [
198 + %{decoratedText: %{topLabel: "Culprit", text: "app.views in divide"}},
199 + %{decoratedText: %{topLabel: "Environment", text: "test-environment"}},
200 + %{decoratedText: %{topLabel: "Release", text: "test-release"}},
201 + %{decoratedText: %{topLabel: "Custom_tag", text: "custom_value"}},
202 + %{
203 + buttonList: %{
204 + buttons: [
205 + %{
206 + text: "View Issue WEB-12",
207 + onClick: %{openLink: %{url: "https://vigil.example.com/acme/issues/12"}}
208 + }
209 + ]
210 + }
211 + }
212 + ]
213 + end
214 +
215 + test "extra issues get a closing card" do
216 + {_, _, body} =
217 + Webhooks.build(recipient("googlechat", @googlechat_url), alert(many_issues(4)))
218 +
219 + assert length(body.cardsV2) == 4
220 + %{card: more} = List.last(body.cardsV2)
221 + assert [%{widgets: [%{decoratedText: %{text: "and 1 more issue"}}]}] = more.sections
222 + end
223 + end
224 +
225 + describe "build/2 ntfy" do
226 + test "markdown body with title, click and tags headers" do
227 + {url, headers, body} = Webhooks.build(recipient("ntfy", @ntfy_url), alert([issue()]))
228 +
229 + assert url == @ntfy_url
230 + headers = Map.new(headers)
231 + assert headers["title"] == "Vigil Alert"
232 + assert headers["markdown"] == "yes"
233 + assert headers["click"] == "https://vigil.example.com/acme/issues/12"
234 + assert headers["tags"] == "warning"
235 + refute Map.has_key?(headers, "authorization")
236 +
237 + assert body ==
238 + """
239 + **ZeroDivisionError: division by zero**
240 + Project: Web
241 + Culprit: app.views in divide
242 + Environment: test-environment
243 + Release: test-release
244 + Custom_tag: custom_value
245 + [View Issue WEB-12](https://vigil.example.com/acme/issues/12)\
246 + """
247 + end
248 +
249 + test "multiple issues, 'more' and the access token" do
250 + r = recipient("ntfy", @ntfy_url, %{"token" => "tk_secret"})
251 + {_, headers, body} = Webhooks.build(r, alert(many_issues(4)))
252 +
253 + headers = Map.new(headers)
254 + assert headers["title"] == "Vigil Alert (4 issues)"
255 + assert headers["click"] == "https://v.example/1"
256 + assert headers["authorization"] == "Bearer tk_secret"
257 + assert body =~ "**Issue 3**"
258 + refute body =~ "**Issue 4**"
259 + assert String.ends_with?(body, "\n\nand 1 more issue")
260 + end
261 +
262 + test "issues without a culprit leave the line out" do
263 + {_, _, body} = Webhooks.build(recipient("ntfy", @ntfy_url), alert([issue(%{culprit: nil})]))
264 + refute body =~ "Culprit"
265 + end
266 + end
267 +
268 + describe "build/2 teams" do
269 + test "an Adaptive Card 1.4 with a fact set and an action per issue" do
270 + {url, [], body} = Webhooks.build(recipient("teams", @teams_url), alert([issue()]))
271 + assert url == @teams_url
272 + assert body.type == "message"
273 +
274 + assert [attachment] = body.attachments
275 + assert attachment.contentType == "application/vnd.microsoft.card.adaptive"
276 + assert attachment.contentUrl == nil
277 +
278 + card = attachment.content
279 + assert card.type == "AdaptiveCard"
280 + assert card.version == "1.4"
281 + assert card."$schema" == "http://adaptivecards.io/schemas/adaptive-card.json"
282 +
283 + assert card.body == [
284 + %{type: "TextBlock", size: "Large", weight: "Bolder", text: "Vigil Alert"},
285 + %{
286 + type: "TextBlock",
287 + weight: "Bolder",
288 + color: "Attention",
289 + text: "ZeroDivisionError: division by zero",
290 + wrap: true
291 + },
292 + %{type: "TextBlock", text: "app.views in divide", wrap: true},
293 + %{
294 + type: "FactSet",
295 + facts: [
296 + %{title: "Project", value: "Web"},
297 + %{title: "Environment", value: "test-environment"},
298 + %{title: "Release", value: "test-release"},
299 + %{title: "Custom_tag", value: "custom_value"}
300 + ]
301 + }
302 + ]
303 +
304 + assert card.actions == [
305 + %{
306 + type: "Action.OpenUrl",
307 + title: "View Issue WEB-12",
308 + url: "https://vigil.example.com/acme/issues/12"
309 + }
310 + ]
311 +
312 + assert json_body({url, [], body})
313 + |> get_in(["attachments", Access.at(0), "content", "$schema"])
314 + end
315 +
316 + test "multiple issues and 'more'" do
317 + {_, _, body} = Webhooks.build(recipient("teams", @teams_url), alert(many_issues(5)))
318 + card = hd(body.attachments).content
319 +
320 + assert hd(card.body).text == "Vigil Alert (5 issues)"
321 + assert List.last(card.body) == %{type: "TextBlock", text: "and 2 more issues", wrap: true}
322 + assert length(card.actions) == 3
323 + end
324 + end
325 +
326 + describe "build/2 zulip" do
327 + test "a form post to the messages API with basic auth" do
328 + r = recipient("zulip", @zulip_url, @zulip_config)
329 + {url, headers, body} = Webhooks.build(r, alert([issue()]))
330 +
331 + assert url == "https://zulip.example.com/api/v1/messages"
332 + headers = Map.new(headers)
333 + assert headers["content-type"] == "application/x-www-form-urlencoded"
334 +
335 + assert headers["authorization"] ==
336 + "Basic " <> Base.encode64("bot@zulip.example.com:test-api-key")
337 +
338 + form = URI.decode_query(body)
339 + assert form["type"] == "channel"
340 + assert form["to"] == "alerts"
341 + assert form["topic"] == "Vigil Alerts"
342 +
343 + assert form["content"] ==
344 + """
345 + ## Vigil Alert
346 +
347 + **[ZeroDivisionError: division by zero](https://vigil.example.com/acme/issues/12)**
348 + Project: Web
349 + Culprit: app.views in divide
350 + Environment: test-environment
351 + Release: test-release
352 + Custom_tag: custom_value\
353 + """
354 + end
355 +
356 + test "default topic, multiple issues and 'more'" do
357 + config = Map.delete(@zulip_config, "topic")
358 + r = recipient("zulip", "https://zulip.example.com", config)
359 + {_, _, body} = Webhooks.build(r, alert(many_issues(4)))
360 +
361 + form = URI.decode_query(body)
362 + assert form["topic"] == "Vigil Alerts"
363 + assert form["content"] =~ "## Vigil Alert (4 issues)"
364 + assert String.ends_with?(form["content"], "\n\nand 1 more issue")
365 + end
366 + end
367 +
368 + test "build/2 raises on an unknown type" do
369 + assert_raise ArgumentError, fn ->
370 + Webhooks.build(recipient("email", "x"), alert([issue()]))
371 + end
372 + end
373 +
374 + describe "build_message/2 (test notification)" do
375 + setup do
376 + %{message: Webhooks.test_message(%{name: "Web"})}
377 + end
378 +
379 + test "the GlitchTip wording", %{message: message} do
380 + assert message.title == "Vigil Test Notification"
381 +
382 + assert message.text ==
383 + "Test notification for project Web. Your alert recipient is configured correctly."
384 + end
385 +
386 + test "webhook", %{message: m} do
387 + {_, [], body} = Webhooks.build_message(recipient("webhook", @webhook_url), m)
388 +
389 + assert body == %{
390 + text: "Vigil Test Notification",
391 + attachments: [
392 + %{
393 + title: "Vigil Test Notification",
394 + title_link: "",
395 + text: m.text,
396 + image_url: nil,
397 + color: "#4b60b4",
398 + fields: nil,
399 + mrkdown_in: nil
400 + }
401 + ]
402 + }
403 + end
404 +
405 + test "discord", %{message: m} do
406 + {_, [], body} = Webhooks.build_message(recipient("discord", @discord_url), m)
407 +
408 + assert body == %{
409 + content: "Vigil Test Notification",
410 + embeds: [
411 + %{
412 + title: "Vigil Test Notification",
413 + description: m.text,
414 + color: 0x4B60B4,
415 + url: "",
416 + fields: []
417 + }
418 + ]
419 + }
420 + end
421 +
422 + test "googlechat", %{message: m} do
423 + {_, [], body} = Webhooks.build_message(recipient("googlechat", @googlechat_url), m)
424 +
425 + assert body == %{
426 + cardsV2: [
427 + %{
428 + cardId: "createCardMessage",
429 + card: %{
430 + header: %{title: "Vigil Test Notification"},
431 + sections: [%{widgets: [%{decoratedText: %{text: m.text}}]}]
432 + }
433 + }
434 + ]
435 + }
436 + end
437 +
438 + test "ntfy", %{message: m} do
439 + {_, headers, body} = Webhooks.build_message(recipient("ntfy", @ntfy_url), m)
440 + headers = Map.new(headers)
441 +
442 + assert headers["title"] == "Vigil Test Notification"
443 + assert headers["tags"] == "white_check_mark"
444 + refute Map.has_key?(headers, "click")
445 + assert body == m.text
446 + end
447 +
448 + test "teams", %{message: m} do
449 + {_, [], body} = Webhooks.build_message(recipient("teams", @teams_url), m)
450 + card = hd(body.attachments).content
451 +
452 + assert card.body == [
453 + %{
454 + type: "TextBlock",
455 + size: "Large",
456 + weight: "Bolder",
457 + text: "Vigil Test Notification"
458 + },
459 + %{type: "TextBlock", text: m.text, wrap: true}
460 + ]
461 +
462 + refute Map.has_key?(card, :actions)
463 + end
464 +
465 + test "zulip", %{message: m} do
466 + r = recipient("zulip", @zulip_url, @zulip_config)
467 + {_, _, body} = Webhooks.build_message(r, m)
468 +
469 + assert URI.decode_query(body)["content"] == "## Vigil Test Notification\n\n" <> m.text
470 + end
471 + end
472 +
473 + describe "build_message/2 with a link (uptime-style)" do
474 + setup do
475 + %{
476 + message: %{
477 + title: "Vigil Uptime Alert",
478 + text: "The monitored site has gone down.",
479 + url: "https://vigil.example.com/acme/uptime/1",
480 + level: "error"
481 + }
482 + }
483 + end
484 +
485 + test "each type carries the link", %{message: m} do
486 + {_, _, slack} = Webhooks.build_message(recipient("webhook", @webhook_url), m)
487 + assert hd(slack.attachments).title_link == m.url
488 + assert hd(slack.attachments).color == "#e52b50"
489 +
490 + {_, _, discord} = Webhooks.build_message(recipient("discord", @discord_url), m)
491 + assert hd(discord.embeds).url == m.url
492 +
493 + {_, _, chat} = Webhooks.build_message(recipient("googlechat", @googlechat_url), m)
494 + [%{card: %{sections: [%{widgets: [%{decoratedText: text}]}]}}] = chat.cardsV2
495 +
496 + assert text == %{
497 + text: m.text,
498 + button: %{text: "View", onClick: %{openLink: %{url: m.url}}}
499 + }
500 +
501 + {_, headers, _} = Webhooks.build_message(recipient("ntfy", @ntfy_url), m)
502 + assert {"click", m.url} in headers
503 + assert {"tags", "warning"} in headers
504 +
505 + {_, _, teams} = Webhooks.build_message(recipient("teams", @teams_url), m)
506 +
507 + assert hd(teams.attachments).content.actions == [
508 + %{type: "Action.OpenUrl", title: "View", url: m.url}
509 + ]
510 +
511 + {_, _, zulip} = Webhooks.build_message(recipient("zulip", @zulip_url, @zulip_config), m)
512 + assert URI.decode_query(zulip)["content"] =~ "\n\n[View](#{m.url})"
513 + end
514 +
515 + test "ok messages are green", %{message: m} do
516 + {_, _, body} =
517 + Webhooks.build_message(recipient("webhook", @webhook_url), %{m | level: "ok"})
518 +
519 + assert hd(body.attachments).color == "#36a64f"
520 + end
521 + end
522 +
523 + ## Delivery
524 +
525 + defp capture(status \\ 200, resp_body \\ "ok") do
526 + parent = self()
527 +
528 + plug = fn conn ->
529 + {:ok, body, conn} = Plug.Conn.read_body(conn)
530 + send(parent, {:request, conn, body})
531 + Plug.Conn.send_resp(conn, status, resp_body)
532 + end
533 +
534 + [req_options: [plug: plug]] ++ @public_resolver
535 + end
536 +
537 + describe "deliver/3" do
538 + test "posts JSON with the Vigil user agent" do
539 + r = recipient("discord", @discord_url)
540 + assert :ok = Webhooks.deliver(r, alert([issue()]), capture())
541 +
542 + assert_received {:request, conn, body}
543 + assert conn.method == "POST"
544 + assert conn.host == "discord.com"
545 + assert conn.request_path == "/api/webhooks/not_real_id/not_real_token"
546 + assert Plug.Conn.get_req_header(conn, "user-agent") == ["Vigil-Alerts/1"]
547 + assert [ct] = Plug.Conn.get_req_header(conn, "content-type")
548 + assert ct =~ "application/json"
549 + assert Jason.decode!(body)["content"] == "Vigil Alert"
550 + end
551 +
552 + test "posts ntfy as plain text with headers" do
553 + r = recipient("ntfy", @ntfy_url, %{"token" => "tk"})
554 + assert :ok = Webhooks.deliver(r, alert([issue()]), capture())
555 +
556 + assert_received {:request, conn, body}
557 + assert Plug.Conn.get_req_header(conn, "title") == ["Vigil Alert"]
558 + assert Plug.Conn.get_req_header(conn, "authorization") == ["Bearer tk"]
559 + assert body =~ "**ZeroDivisionError: division by zero**"
560 + end
561 +
562 + test "posts zulip as a form" do
563 + r = recipient("zulip", @zulip_url, @zulip_config)
564 + assert :ok = Webhooks.deliver(r, alert([issue()]), capture())
565 +
566 + assert_received {:request, conn, body}
567 + assert conn.request_path == "/api/v1/messages"
568 + assert URI.decode_query(body)["to"] == "alerts"
569 + end
570 +
571 + test "any 2xx is success" do
572 + r = recipient("webhook", @webhook_url)
573 + assert :ok = Webhooks.deliver(r, alert([issue()]), capture(204, ""))
574 + end
575 +
576 + test "other statuses are errors with the body, truncated" do
577 + r = recipient("webhook", @webhook_url)
578 +
579 + assert {:error, {:http, 404, "no_team"}} =
580 + Webhooks.deliver(r, alert([issue()]), capture(404, "no_team"))
581 +
582 + long = String.duplicate("é", 2000)
583 +
584 + assert {:error, {:http, 500, body}} =
585 + Webhooks.deliver(r, alert([issue()]), capture(500, long))
586 +
587 + assert String.length(body) == 500
588 + end
589 +
590 + test "transport errors" do
591 + plug = &Req.Test.transport_error(&1, :timeout)
592 + r = recipient("teams", @teams_url)
593 +
594 + assert {:error, {:transport, :timeout}} =
595 + Webhooks.deliver(
596 + r,
597 + alert([issue()]),
598 + [req_options: [plug: plug]] ++ @public_resolver
599 + )
600 + end
601 +
602 + test "unsafe URLs are refused before any request" do
603 + for url <- ["http://127.0.0.1/hook", "http://169.254.169.254/", "ftp://example.com/x"] do
604 + assert {:error, {:unsafe_url, _}} =
605 + Webhooks.deliver(recipient("webhook", url), alert([issue()]), capture())
606 + end
607 +
608 + private = [resolver: fn _ -> {:ok, [{192, 168, 1, 10}]} end]
609 + opts = Keyword.merge(capture(), private)
610 +
611 + assert {:error, {:unsafe_url, {:blocked_address, {192, 168, 1, 10}}}} =
612 + Webhooks.deliver(recipient("zulip", @zulip_url, @zulip_config), alert([]), opts)
613 +
614 + refute_received {:request, _, _}
615 + end
616 +
617 + test "unknown types are refused" do
618 + assert {:error, {:unsupported_type, "email"}} =
619 + Webhooks.deliver(recipient("email", "a@example.com"), alert([issue()]), capture())
620 +
621 + refute_received {:request, _, _}
622 + end
623 + end
624 +
625 + describe "deliver_message/3" do
626 + test "posts the message" do
627 + r = recipient("googlechat", @googlechat_url)
628 + assert :ok = Webhooks.deliver_message(r, Webhooks.test_message(%{name: "Web"}), capture())
629 +
630 + assert_received {:request, conn, body}
631 + assert conn.query_string == "key=k&token=t"
632 +
633 + assert Jason.decode!(body)["cardsV2"] |> hd() |> get_in(["card", "header", "title"]) ==
634 + "Vigil Test Notification"
635 + end
636 +
637 + test "refuses unsafe URLs" do
638 + r = recipient("ntfy", "http://[::1]:8080/topic")
639 +
640 + assert {:error, {:unsafe_url, {:blocked_address, _}}} =
641 + Webhooks.deliver_message(r, Webhooks.test_message(%{name: "Web"}), capture())
642 +
643 + refute_received {:request, _, _}
644 + end
645 + end
646 +end
added test/vigil/outbound_test.exs
+129 −0
@@ -0,0 +1,129 @@
1 +defmodule Vigil.OutboundTest do
2 + use ExUnit.Case, async: true
3 +
4 + alias Vigil.Outbound
5 +
6 + defp resolves_to(ips), do: fn _host -> {:ok, ips} end
7 +
8 + defp ip(string) do
9 + {:ok, ip} = :inet.parse_strict_address(String.to_charlist(string))
10 + ip
11 + end
12 +
13 + describe "blocked_address?/1" do
14 + @refused ~w(
15 + 0.0.0.0 0.1.2.3 10.0.0.1 10.255.255.255 100.64.0.1 100.127.255.254
16 + 127.0.0.1 127.8.8.8 169.254.169.254 169.254.0.1 172.16.0.1
17 + 172.31.255.255 192.0.0.8 192.0.2.1 192.168.1.1 198.18.0.1 198.19.255.1
18 + 198.51.100.7 203.0.113.9 224.0.0.1 239.255.255.250 240.0.0.1
19 + 255.255.255.255
20 + :: ::1 ::127.0.0.1 fc00::1 fd12:3456::1 fe80::1 febf::1 fec0::1 ff02::1
21 + 100::1 2001:db8::1 2001::1
22 + ::ffff:127.0.0.1 ::ffff:10.0.0.1 ::ffff:169.254.169.254 ::ffff:192.168.0.1
23 + 64:ff9b::10.0.0.1 2002:a00:1::1 2002:7f00:1::
24 + )
25 +
26 + @allowed ~w(
27 + 1.1.1.1 8.8.8.8 93.184.216.34 100.63.255.255 100.128.0.1 172.15.255.255
28 + 172.32.0.1 169.253.0.1 192.169.0.1 198.20.0.1 223.255.255.255
29 + 2606:4700:4700::1111 2001:4860:4860::8888 2a00:1450:4001::1
30 + ::ffff:1.1.1.1 64:ff9b::808:808 2002:808:808::1
31 + )
32 +
33 + for address <- @refused do
34 + test "refuses #{address}" do
35 + assert Outbound.blocked_address?(ip(unquote(address)))
36 + end
37 + end
38 +
39 + for address <- @allowed do
40 + test "allows #{address}" do
41 + refute Outbound.blocked_address?(ip(unquote(address)))
42 + end
43 + end
44 + end
45 +
46 + describe "check_url/2" do
47 + test "allows a public host" do
48 + assert :ok =
49 + Outbound.check_url("https://hooks.example.com/x",
50 + resolver: resolves_to([{93, 184, 216, 34}])
51 + )
52 + end
53 +
54 + test "allows http and public literal addresses, v4 and v6" do
55 + assert :ok = Outbound.check_url("http://1.1.1.1/hook", resolver: &flunk_resolve/1)
56 +
57 + assert :ok =
58 + Outbound.check_url("http://[2606:4700:4700::1111]:8080/",
59 + resolver: &flunk_resolve/1
60 + )
61 + end
62 +
63 + test "checks literal addresses without resolving" do
64 + assert {:error, {:blocked_address, {127, 0, 0, 1}}} =
65 + Outbound.check_url("http://127.0.0.1:4000/", resolver: &flunk_resolve/1)
66 +
67 + assert {:error, {:blocked_address, {0, 0, 0, 0, 0, 0, 0, 1}}} =
68 + Outbound.check_url("http://[::1]/", resolver: &flunk_resolve/1)
69 +
70 + assert {:error, {:blocked_address, {169, 254, 169, 254}}} =
71 + Outbound.check_url("http://169.254.169.254/latest/meta-data/")
72 +
73 + assert {:error, {:blocked_address, _}} =
74 + Outbound.check_url("http://[::ffff:10.0.0.1]/", resolver: &flunk_resolve/1)
75 + end
76 +
77 + test "refuses when any resolved address is private" do
78 + resolver = resolves_to([{93, 184, 216, 34}, {10, 0, 0, 5}])
79 +
80 + assert {:error, {:blocked_address, {10, 0, 0, 5}}} =
81 + Outbound.check_url("https://mixed.example.com", resolver: resolver)
82 +
83 + resolver = resolves_to([{93, 184, 216, 34}, ip("fd00::1")])
84 +
85 + assert {:error, {:blocked_address, _}} =
86 + Outbound.check_url("https://mixed.example.com", resolver: resolver)
87 + end
88 +
89 + test "refuses names that do not resolve" do
90 + assert {:error, {:resolve, :nxdomain}} =
91 + Outbound.check_url("https://nope.example",
92 + resolver: fn _ -> {:error, :nxdomain} end
93 + )
94 +
95 + assert {:error, {:resolve, :nxdomain}} =
96 + Outbound.check_url("https://empty.example", resolver: resolves_to([]))
97 + end
98 +
99 + test "passes the bare host to the resolver" do
100 + parent = self()
101 +
102 + Outbound.check_url("https://user:pw@Hooks.Example.com:8443/p?q=1",
103 + resolver: fn host ->
104 + send(parent, {:host, host})
105 + {:ok, [{1, 1, 1, 1}]}
106 + end
107 + )
108 +
109 + assert_received {:host, "Hooks.Example.com"}
110 + end
111 +
112 + test "refuses other schemes and missing hosts" do
113 + for url <- ["ftp://example.com/", "file:///etc/passwd", "gopher://x", "javascript:alert(1)"] do
114 + assert {:error, {:scheme_not_allowed, _}} = Outbound.check_url(url)
115 + end
116 +
117 + assert {:error, {:scheme_not_allowed, nil}} = Outbound.check_url("example.com/hook")
118 + assert {:error, :missing_host} = Outbound.check_url("http:///path")
119 + assert {:error, :invalid_url} = Outbound.check_url("http://exa mple.com/")
120 + assert {:error, :invalid_url} = Outbound.check_url(nil)
121 + end
122 +
123 + test "resolves localhost for real and refuses it" do
124 + assert {:error, {:blocked_address, _}} = Outbound.check_url("http://localhost:4000/")
125 + end
126 + end
127 +
128 + defp flunk_resolve(host), do: flunk("unexpected lookup of #{host}")
129 +end

Parents: 2f56e4f 06933b0