feat: 16 notification services (chat, push, paging, Apprise) #99

Merged
Sebi merged 2 commits from feat/notification-providers into main 2026-11-22 17:42:21 +00:00
14 changed files with 1594 additions and 133 deletions

No files matched your search

+7
View File
@@ -217,6 +217,13 @@ func (s *Server) send(ctx context.Context, typ string, config []byte, ev notify.
} }
return s.smtp.Send(ctx, s.mailFor(ev, c.To, c.Locale)) return s.smtp.Send(ctx, s.mailFor(ev, c.To, c.Locale))
} }
if p, ok := notify.Lookup(typ); ok {
settings, locale, err := s.openProviderSettings(typ, config)
if err != nil {
return err
}
return p.Send(ctx, settings, s.messageFor(ev, locale), !s.cloud())
}
return fmt.Errorf("unknown channel type %q", typ) return fmt.Errorf("unknown channel type %q", typ)
} }
+2 -1
View File
@@ -121,7 +121,8 @@ var endpoints = []endpoint{
{method: "GET", path: "/api/v1/org/channels", tag: "Alerting", summary: "List notification channels", perm: "notifications.read", {method: "GET", path: "/api/v1/org/channels", tag: "Alerting", summary: "List notification channels", perm: "notifications.read",
resp: obj{"channels": []channelView{}, "email_available": false}}, resp: obj{"channels": []channelView{}, "email_available": false}},
{method: "POST", path: "/api/v1/org/channels", tag: "Alerting", summary: "Create a channel", {method: "POST", path: "/api/v1/org/channels", tag: "Alerting", summary: "Create a channel",
description: "Webhook channels return their signing secret once.", perm: "notifications.write", description: "`type` is webhook (`url`), email (`to`, `locale`) or one of slack, discord, teams, googlechat, mattermost, rocketchat, telegram, matrix, ntfy, gotify, pushover, pushbullet, signal, pagerduty, opsgenie, apprise with their `settings`. Secret settings are stored encrypted and never returned; on update, leaving one empty keeps it. Webhook channels return their signing secret once.",
perm: "notifications.write",
req: channelRequest{}, status: http.StatusCreated, resp: obj{"channel": channelView{}, "signing_secret": ""}}, req: channelRequest{}, status: http.StatusCreated, resp: obj{"channel": channelView{}, "signing_secret": ""}},
{method: "PUT", path: "/api/v1/org/channels/:id", tag: "Alerting", summary: "Change a channel", perm: "notifications.write", {method: "PUT", path: "/api/v1/org/channels/:id", tag: "Alerting", summary: "Change a channel", perm: "notifications.write",
req: channelRequest{}, resp: obj{"channel": channelView{}, "signing_secret": ""}}, req: channelRequest{}, resp: obj{"channel": channelView{}, "signing_secret": ""}},
+14 -1
View File
@@ -22,11 +22,14 @@ import (
type channelRequest struct { type channelRequest struct {
Name string `json:"name" binding:"required,max=100"` Name string `json:"name" binding:"required,max=100"`
Type string `json:"type" binding:"required,oneof=webhook email"` Type string `json:"type" binding:"required,max=32"`
URL string `json:"url" binding:"max=2000"` URL string `json:"url" binding:"max=2000"`
To []string `json:"to" binding:"max=20,dive,max=320"` To []string `json:"to" binding:"max=20,dive,max=320"`
Locale string `json:"locale" binding:"max=10"` Locale string `json:"locale" binding:"max=10"`
Enabled *bool `json:"enabled"` Enabled *bool `json:"enabled"`
// Settings configure the other channel types, as listed by
// notify.Providers; secret settings left empty keep their value.
Settings map[string]string `json:"settings" binding:"max=20"`
} }
type channelView struct { type channelView struct {
@@ -37,6 +40,10 @@ type channelView struct {
URL string `json:"url,omitempty"` URL string `json:"url,omitempty"`
To []string `json:"to,omitempty"` To []string `json:"to,omitempty"`
Locale string `json:"locale,omitempty"` Locale string `json:"locale,omitempty"`
// Settings and SecretsSet describe other channel types; secret values
// are never returned.
Settings map[string]string `json:"settings,omitempty"`
SecretsSet []string `json:"secrets_set,omitempty"`
} }
func viewChannel(ch store.NotificationChannel) channelView { func viewChannel(ch store.NotificationChannel) channelView {
@@ -50,6 +57,8 @@ func viewChannel(ch store.NotificationChannel) channelView {
var c emailConfig var c emailConfig
_ = json.Unmarshal(ch.Config, &c) _ = json.Unmarshal(ch.Config, &c)
v.To, v.Locale = c.To, c.Locale v.To, v.Locale = c.To, c.Locale
default:
v.Settings, v.SecretsSet, v.Locale = providerView(ch.Config)
} }
return v return v
} }
@@ -109,6 +118,10 @@ func (s *Server) channelConfig(req *channelRequest, previous []byte) (config []b
config, _ = json.Marshal(emailConfig{To: req.To, Locale: req.Locale}) config, _ = json.Marshal(emailConfig{To: req.To, Locale: req.Locale})
return config, "", "" return config, "", ""
} }
if p, ok := notify.Lookup(req.Type); ok {
config, code = s.providerSettings(p, req, previous)
return config, "", code
}
return nil, "", "invalid_input" return nil, "", "invalid_input"
} }
+25
View File
@@ -21,6 +21,7 @@ import (
"git.zb-server.de/ZB-Server/uptimesebi/internal/check" "git.zb-server.de/ZB-Server/uptimesebi/internal/check"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
"git.zb-server.de/ZB-Server/uptimesebi/internal/maintenance" "git.zb-server.de/ZB-Server/uptimesebi/internal/maintenance"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store" "git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web" "git.zb-server.de/ZB-Server/uptimesebi/internal/web"
) )
@@ -663,12 +664,36 @@ func (s *Server) channelsView(c *gin.Context, p *principal, page web.Page, me we
return nil, err return nil, err
} }
v := web.ChannelsView{EmailAvailable: s.smtp != nil, CanWrite: p.Grants.Can(authz.NotificationsWrite), Languages: s.catalog.Supported()} v := web.ChannelsView{EmailAvailable: s.smtp != nil, CanWrite: p.Grants.Can(authz.NotificationsWrite), Languages: s.catalog.Supported()}
ctx2 := c.Request.Context()
for _, pr := range notify.Providers {
opt := web.ProviderOption{Type: pr.Type}
if help := i18n.T(ctx2, "channels.help_"+pr.Type); help != "channels.help_"+pr.Type {
opt.Help = help
}
for _, f := range pr.Fields {
opt.Fields = append(opt.Fields, web.ProviderField{
Name: f.Name, Label: i18n.T(ctx2, "channels.field_"+f.Name), Required: f.Required, Secret: f.Secret,
Kind: f.Kind, Options: f.Options, Default: f.Default,
})
}
v.Providers = append(v.Providers, opt)
}
for _, r := range rows { for _, r := range rows {
cv := viewChannel(r) cv := viewChannel(r)
target := cv.URL target := cv.URL
if cv.Type == "email" { if cv.Type == "email" {
target = strings.Join(cv.To, ", ") target = strings.Join(cv.To, ", ")
} }
// Other services show their first setting that is no secret, such
// as the chat, topic or server.
if p, ok := notify.Lookup(cv.Type); ok {
for _, f := range p.Fields {
if v, ok := cv.Settings[f.Name]; ok && !f.Secret {
target = v
break
}
}
}
v.Channels = append(v.Channels, web.ChannelRow{ID: r.ID.String(), Name: r.Name, Type: r.Type, Target: target, Enabled: r.Enabled}) v.Channels = append(v.Channels, web.ChannelRow{ID: r.ID.String(), Name: r.Name, Type: r.Type, Target: target, Enabled: r.Enabled})
} }
return web.ChannelsPage(page, me, v), nil return web.ChannelsPage(page, me, v), nil
+158
View File
@@ -0,0 +1,158 @@
package api
import (
"encoding/base64"
"encoding/json"
"net/url"
"slices"
"strconv"
"strings"
"time"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
)
// providerConfig is stored for channels of notify.Providers. Secret
// settings are sealed, bound to the channel type and field, and never
// shown again.
type providerConfig struct {
Settings map[string]string `json:"settings"`
Sealed map[string]string `json:"sealed"`
Locale string `json:"locale"`
}
func secretAAD(typ, field string) []byte { return []byte("channel:" + typ + ":" + field) }
// providerSettings validates the settings of a provider channel. Secret
// fields left empty keep their previous value, so a form can be saved
// without asking for tokens again.
func (s *Server) providerSettings(p notify.Provider, req *channelRequest, previous []byte) ([]byte, string) {
var old providerConfig
if previous != nil {
_ = json.Unmarshal(previous, &old)
}
cfg := providerConfig{Settings: map[string]string{}, Sealed: map[string]string{}, Locale: req.Locale}
for _, f := range p.Fields {
v := strings.TrimSpace(req.Settings[f.Name])
if f.Secret {
if v == "" {
if sealed, ok := old.Sealed[f.Name]; ok {
cfg.Sealed[f.Name] = sealed
continue
}
if f.Required {
return nil, "invalid_channel_settings"
}
continue
}
} else if v == "" {
v = f.Default
}
if v == "" {
if f.Required {
return nil, "invalid_channel_settings"
}
continue
}
if len(v) > 2000 || !s.validSetting(f, v) {
return nil, "invalid_channel_settings"
}
if f.Secret {
cfg.Sealed[f.Name] = base64.StdEncoding.EncodeToString(s.keys.Seal([]byte(v), secretAAD(p.Type, f.Name)))
} else {
cfg.Settings[f.Name] = v
}
}
if cfg.Locale == "" || !s.catalog.IsSupported(cfg.Locale) {
cfg.Locale = "en"
}
raw, _ := json.Marshal(cfg)
return raw, ""
}
func (s *Server) validSetting(f notify.Field, v string) bool {
switch f.Kind {
case "url":
u, err := url.Parse(v)
// Plain http only where services may live on private networks.
return err == nil && u.Host != "" && u.User == nil && (u.Scheme == "https" || (u.Scheme == "http" && !s.cloud()))
case "number":
_, err := strconv.Atoi(v)
return err == nil
case "select":
return slices.Contains(f.Options, v)
}
return !strings.ContainsAny(v, "\r\n")
}
// providerView shows the settings of a provider channel; secrets appear
// only as the names of fields that are set.
func providerView(raw []byte) (map[string]string, []string, string) {
var cfg providerConfig
_ = json.Unmarshal(raw, &cfg)
set := make([]string, 0, len(cfg.Sealed))
for k := range cfg.Sealed {
set = append(set, k)
}
slices.Sort(set)
if cfg.Settings == nil {
cfg.Settings = map[string]string{}
}
return cfg.Settings, set, cfg.Locale
}
// openProviderSettings returns all settings with secrets unsealed.
func (s *Server) openProviderSettings(typ string, raw []byte) (map[string]string, string, error) {
var cfg providerConfig
if err := json.Unmarshal(raw, &cfg); err != nil {
return nil, "", err
}
out := map[string]string{}
for k, v := range cfg.Settings {
out[k] = v
}
for k, v := range cfg.Sealed {
sealed, err := base64.StdEncoding.DecodeString(v)
if err != nil {
return nil, "", err
}
plain, err := s.keys.Open(sealed, secretAAD(typ, k))
if err != nil {
return nil, "", err
}
out[k] = string(plain)
}
return out, cfg.Locale, nil
}
// messageFor renders an event for chat and push services in locale.
func (s *Server) messageFor(ev notify.Event, locale string) notify.Message {
l := s.catalog.Match(locale)
data := map[string]any{"Monitor": ev.Monitor.Name}
m := notify.Message{Event: ev.Kind, Key: ev.IncidentID}
var lines []string
switch ev.Kind {
case notify.Opened:
m.Title = l.T("notify.title_opened", data)
for region, msg := range ev.Cause {
lines = append(lines, region+": "+msg)
}
slices.Sort(lines)
case notify.Resolved:
m.Title = l.T("notify.title_resolved", data)
if ev.ResolvedAt != nil {
lines = append(lines, l.T("notify.duration", map[string]any{"Duration": ev.ResolvedAt.Sub(ev.StartedAt).Round(time.Second).String()}))
}
default:
m.Title = l.T("notify.title_test", data)
lines = append(lines, l.T("notify.test_body", nil))
}
if ev.Monitor.Target != "" && ev.Monitor.Type != "heartbeat" {
lines = append([]string{ev.Monitor.Type + " · " + ev.Monitor.Target}, lines...)
}
m.Body = strings.Join(lines, "\n")
if ev.Monitor.ID != [16]byte{} {
m.URL = strings.TrimSuffix(s.cfg.PublicURL, "/") + "/monitors/" + ev.Monitor.ID.String()
}
return m
}
+105
View File
@@ -0,0 +1,105 @@
package api_test
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
)
func TestProvidersAreTranslated(t *testing.T) {
catalog, err := i18n.Load()
if err != nil {
t.Fatal(err)
}
for _, lang := range catalog.Supported() {
ctx := i18n.NewContext(context.Background(), catalog.Match(lang))
for _, p := range notify.Providers {
ids := []string{"channels.type_" + p.Type}
for _, f := range p.Fields {
ids = append(ids, "channels.field_"+f.Name)
}
for _, id := range ids {
if i18n.T(ctx, id) == id {
t.Errorf("%s: %s is not translated", lang, id)
}
}
}
}
}
func TestProviderChannel(t *testing.T) {
e := newEnv(t)
var mu sync.Mutex
var paths, bodies []string
telegram := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
mu.Lock()
paths, bodies = append(paths, r.URL.Path), append(bodies, string(b))
mu.Unlock()
}))
defer telegram.Close()
owner := e.browser(t)
owner.signup("o@"+uniq("pr")+".test", uniq("pr-"))
st, body := owner.do("POST", "/api/v1/org/channels", map[string]any{"name": "Ops chat", "type": "telegram", "settings": map[string]string{"chat_id": "-100"}})
expect(t, "missing bot token", st, body, http.StatusUnprocessableEntity, "invalid_channel_settings")
st, body = owner.do("POST", "/api/v1/org/channels", map[string]any{"name": "x", "type": "carrierpigeon"})
expect(t, "unknown type", st, body, http.StatusUnprocessableEntity, "invalid_input")
st, body = owner.do("POST", "/api/v1/org/channels", map[string]any{
"name": "Ops chat", "type": "telegram", "locale": "de",
"settings": map[string]string{"bot_token": "4711:very-secret", "chat_id": "-100123", "api_url": telegram.URL},
})
if st != http.StatusCreated {
t.Fatalf("create telegram channel = %d %v", st, body)
}
ch := body["channel"].(map[string]any)
id := ch["id"].(string)
if raw := mustJSON(body); strings.Contains(raw, "very-secret") || ch["settings"].(map[string]any)["chat_id"] != "-100123" ||
mustJSON(ch["secrets_set"]) != `["bot_token"]` {
t.Errorf("create answer = %s", raw)
}
var stored string
_ = e.asSystem(t, func(tx pgx.Tx) error {
return tx.QueryRow(context.Background(), `SELECT config::text FROM notification_channels WHERE id = $1`, id).Scan(&stored)
})
if strings.Contains(stored, "very-secret") {
t.Error("the bot token is stored in plain text")
}
if _, list := owner.do("GET", "/api/v1/org/channels", nil); strings.Contains(mustJSON(list), "very-secret") {
t.Error("the channel list shows the bot token")
}
if st, body := owner.do("POST", "/api/v1/org/channels/"+id+"/test", nil); st != http.StatusNoContent {
t.Fatalf("test send = %d %v", st, body)
}
// Saving without the token keeps it.
st, body = owner.do("PUT", "/api/v1/org/channels/"+id, map[string]any{
"name": "Ops chat", "type": "telegram", "locale": "de",
"settings": map[string]string{"chat_id": "-100999", "api_url": telegram.URL},
})
if st != http.StatusOK {
t.Fatalf("update = %d %v", st, body)
}
owner.do("POST", "/api/v1/org/channels/"+id+"/test", nil)
mu.Lock()
defer mu.Unlock()
if len(paths) != 2 || paths[0] != "/bot4711:very-secret/sendMessage" || paths[1] != paths[0] {
t.Errorf("telegram requests = %v", paths)
}
if !strings.Contains(bodies[0], "Test von UptimeSebi") || !strings.Contains(bodies[1], `"chat_id":"-100999"`) {
t.Errorf("telegram bodies = %v", bodies)
}
if _, _, page := owner.page("/settings/channels"); !strings.Contains(page, `name="settings.bot_token"`) || !strings.Contains(page, "-100999") {
t.Error("the channels page lacks the service form or the channel")
}
}
+2 -1
View File
@@ -153,7 +153,7 @@ func TestDynamicFamilies(t *testing.T) {
families := map[string][]string{ families := map[string][]string{
"status.": {"up", "degraded", "down", "unknown", "paused", "maintenance"}, "status.": {"up", "degraded", "down", "unknown", "paused", "maintenance"},
"monitors.type_": {"http", "tcp", "tls", "dns", "icmp", "json", "prometheus", "heartbeat", "alertmanager"}, "monitors.type_": {"http", "tcp", "tls", "dns", "icmp", "json", "prometheus", "heartbeat", "alertmanager"},
"channels.type_": {"webhook", "email"}, "channels.type_": {"webhook", "email", "slack", "discord", "teams", "googlechat", "mattermost", "rocketchat", "telegram", "matrix", "ntfy", "gotify", "pushover", "pushbullet", "signal", "pagerduty", "opsgenie", "apprise"},
"agents.kind_": {"checker", "statuspage"}, "agents.kind_": {"checker", "statuspage"},
"page.status.": {"operational", "degraded", "outage", "unknown", "maintenance"}, "page.status.": {"operational", "degraded", "outage", "unknown", "maintenance"},
"page.component.": {"operational", "degraded", "outage", "unknown", "maintenance"}, "page.component.": {"operational", "degraded", "outage", "unknown", "maintenance"},
@@ -162,6 +162,7 @@ func TestDynamicFamilies(t *testing.T) {
"monitors.op_": {"eq", "ne", "gt", "ge", "lt", "le", "contains", "exists", "absent"}, "monitors.op_": {"eq", "ne", "gt", "ge", "lt", "le", "contains", "exists", "absent"},
"evidence.stage_": {"dns", "connect", "tls", "response", "body"}, "evidence.stage_": {"dns", "connect", "tls", "response", "body"},
"evidence.phase_": {"dns", "connect", "tls", "wait", "download"}, "evidence.phase_": {"dns", "connect", "tls", "wait", "download"},
"channels.field_": {"webhook_url", "channel", "bot_token", "chat_id", "thread_id", "api_url", "homeserver_url", "access_token", "room_id", "server_url", "topic", "priority", "app_token", "user_key", "device", "number", "recipients", "routing_key", "severity", "api_key", "region", "urls", "config_key"},
"weekday.": {"0", "1", "2", "3", "4", "5", "6"}, "weekday.": {"0", "1", "2", "3", "4", "5", "6"},
"md.": {"heading", "bold", "italic", "strike", "link", "ul", "ol", "quote", "code", "codeblock", "table", "hr"}, "md.": {"heading", "bold", "italic", "strike", "link", "ul", "ol", "quote", "code", "codeblock", "table", "hr"},
"maintenance.recurrence_": {"none", "daily", "weekly", "monthly"}, "maintenance.recurrence_": {"none", "daily", "weekly", "monthly"},
+55
View File
@@ -112,16 +112,65 @@
"auth.sso.submit": "Weiter", "auth.sso.submit": "Weiter",
"channels.create": "Kanal anlegen", "channels.create": "Kanal anlegen",
"channels.delete_confirm": "Diesen Kanal löschen?", "channels.delete_confirm": "Diesen Kanal löschen?",
"channels.field_access_token": "Zugriffstoken",
"channels.field_api_key": "API-Schlüssel",
"channels.field_api_url": "API-URL",
"channels.field_app_token": "Anwendungs-Token",
"channels.field_bot_token": "Bot-Token",
"channels.field_channel": "Kanal",
"channels.field_chat_id": "Chat-ID",
"channels.field_config_key": "Konfigurationsschlüssel",
"channels.field_device": "Gerät",
"channels.field_homeserver_url": "Homeserver-URL",
"channels.field_number": "Absendernummer",
"channels.field_priority": "Priorität",
"channels.field_recipients": "Empfänger (durch Komma getrennt)",
"channels.field_region": "Region",
"channels.field_room_id": "Raum-ID",
"channels.field_routing_key": "Integrationsschlüssel",
"channels.field_server_url": "Server-URL",
"channels.field_severity": "Schweregrad",
"channels.field_thread_id": "Themen-ID (Forum-Gruppen)",
"channels.field_topic": "Topic",
"channels.field_urls": "Apprise-URLs",
"channels.field_user_key": "Benutzer-Schlüssel",
"channels.field_webhook_url": "Webhook-URL",
"channels.help_apprise": "Erreicht über 100 Dienste über einen Apprise-API-Server: gib Apprise-URLs oder den Schlüssel einer dort gespeicherten Konfiguration an.",
"channels.help_opsgenie": "Der Alert wird geschlossen, wenn der Vorfall behoben ist.",
"channels.help_pagerduty": "Nutze den Integrationsschlüssel einer Events-API-v2-Integration; die Behebung schließt den PagerDuty-Vorfall.",
"channels.help_signal": "Braucht einen signal-cli-REST-API-Server (bbernhard/signal-cli-rest-api) mit registrierter Nummer.",
"channels.help_teams": "Nutze die URL eines Teams-Workflows „Bei Empfang einer Webhookanforderung in einem Kanal posten“.",
"channels.help_telegram": "Lege mit @BotFather einen Bot an; die Chat-ID einer Gruppe beginnt mit -100.",
"channels.intro": "Jeder aktive Kanal wird benachrichtigt, wenn ein Monitor in allen seinen Regionen ausfällt und wenn er sich erholt.", "channels.intro": "Jeder aktive Kanal wird benachrichtigt, wenn ein Monitor in allen seinen Regionen ausfällt und wenn er sich erholt.",
"channels.language": "Sprache", "channels.language": "Sprache",
"channels.new_email": "Neuer E-Mail-Kanal", "channels.new_email": "Neuer E-Mail-Kanal",
"channels.new_service": "Weitere Dienste",
"channels.new_webhook": "Neuer Webhook", "channels.new_webhook": "Neuer Webhook",
"channels.optional": "optional",
"channels.secret_now": "Signatur-Secret: Prüfe damit den Header X-Uptimesebi-Signature. Es wird nicht erneut angezeigt.", "channels.secret_now": "Signatur-Secret: Prüfe damit den Header X-Uptimesebi-Signature. Es wird nicht erneut angezeigt.",
"channels.service": "Dienst",
"channels.service_intro": "Chat-, Push- und Alarmierungsdienste. Tokens und Schlüssel werden verschlüsselt gespeichert und nie wieder angezeigt.",
"channels.test": "Test senden", "channels.test": "Test senden",
"channels.test_ok": "Testbenachrichtigung zugestellt.", "channels.test_ok": "Testbenachrichtigung zugestellt.",
"channels.title": "Benachrichtigungen", "channels.title": "Benachrichtigungen",
"channels.to": "Empfänger", "channels.to": "Empfänger",
"channels.type_apprise": "Apprise",
"channels.type_discord": "Discord",
"channels.type_email": "E-Mail", "channels.type_email": "E-Mail",
"channels.type_googlechat": "Google Chat",
"channels.type_gotify": "Gotify",
"channels.type_matrix": "Matrix",
"channels.type_mattermost": "Mattermost",
"channels.type_ntfy": "ntfy",
"channels.type_opsgenie": "Opsgenie",
"channels.type_pagerduty": "PagerDuty",
"channels.type_pushbullet": "Pushbullet",
"channels.type_pushover": "Pushover",
"channels.type_rocketchat": "Rocket.Chat",
"channels.type_signal": "Signal",
"channels.type_slack": "Slack",
"channels.type_teams": "Microsoft Teams",
"channels.type_telegram": "Telegram",
"channels.type_webhook": "Webhook", "channels.type_webhook": "Webhook",
"channels.url": "Webhook-URL", "channels.url": "Webhook-URL",
"checkers.avg_latency": "Mittlere Latenz", "checkers.avg_latency": "Mittlere Latenz",
@@ -189,6 +238,7 @@
"error.invalid_assertion_path": "Ein Pfad ist ungültig. Nutze durch Punkte getrennte Schlüssel und [n] für Array-Elemente.", "error.invalid_assertion_path": "Ein Pfad ist ungültig. Nutze durch Punkte getrennte Schlüssel und [n] für Array-Elemente.",
"error.invalid_assertion_value": "Vergleiche mit <, >, ≤ und ≥ brauchen eine Zahl.", "error.invalid_assertion_value": "Vergleiche mit <, >, ≤ und ≥ brauchen eine Zahl.",
"error.invalid_assertions": "Lege 1 bis 10 Bedingungen an.", "error.invalid_assertions": "Lege 1 bis 10 Bedingungen an.",
"error.invalid_channel_settings": "Fülle die Pflichtfelder aus; Adressen müssen https-URLs sein.",
"error.invalid_code": "Code ungültig.", "error.invalid_code": "Code ungültig.",
"error.invalid_config": "Die Check-Einstellungen sind ungültig.", "error.invalid_config": "Die Check-Einstellungen sind ungültig.",
"error.invalid_credentials": "E-Mail oder Passwort falsch.", "error.invalid_credentials": "E-Mail oder Passwort falsch.",
@@ -595,6 +645,11 @@
"monitors.type_tls": "TLS-Zertifikat", "monitors.type_tls": "TLS-Zertifikat",
"monitors.uptime_chart": "Uptime pro Zeitraum", "monitors.uptime_chart": "Uptime pro Zeitraum",
"monitors.verify_tls": "TLS-Zertifikat prüfen", "monitors.verify_tls": "TLS-Zertifikat prüfen",
"notify.duration": "Ausgefallen für {{.Duration}}",
"notify.test_body": "Wenn du das lesen kannst, funktioniert der Kanal.",
"notify.title_opened": "{{.Monitor}} ist ausgefallen",
"notify.title_resolved": "{{.Monitor}} ist wieder erreichbar",
"notify.title_test": "Test von UptimeSebi",
"org.policy": "Anmelderichtlinie", "org.policy": "Anmelderichtlinie",
"org.require_sso": "SSO verlangen", "org.require_sso": "SSO verlangen",
"org.require_sso_hint": "Mitglieder müssen sich über den Identity Provider dieser Organisation anmelden. Der Owner kann weiterhin ein Passwort nutzen, damit ein defekter IdP euch nicht aussperrt.", "org.require_sso_hint": "Mitglieder müssen sich über den Identity Provider dieser Organisation anmelden. Der Owner kann weiterhin ein Passwort nutzen, damit ein defekter IdP euch nicht aussperrt.",
+55
View File
@@ -112,16 +112,65 @@
"auth.sso.submit": "Continue", "auth.sso.submit": "Continue",
"channels.create": "Create channel", "channels.create": "Create channel",
"channels.delete_confirm": "Delete this channel?", "channels.delete_confirm": "Delete this channel?",
"channels.field_access_token": "Access token",
"channels.field_api_key": "API key",
"channels.field_api_url": "API URL",
"channels.field_app_token": "Application token",
"channels.field_bot_token": "Bot token",
"channels.field_channel": "Channel",
"channels.field_chat_id": "Chat ID",
"channels.field_config_key": "Configuration key",
"channels.field_device": "Device",
"channels.field_homeserver_url": "Homeserver URL",
"channels.field_number": "Sender number",
"channels.field_priority": "Priority",
"channels.field_recipients": "Recipients (comma-separated)",
"channels.field_region": "Region",
"channels.field_room_id": "Room ID",
"channels.field_routing_key": "Integration key",
"channels.field_server_url": "Server URL",
"channels.field_severity": "Severity",
"channels.field_thread_id": "Topic ID (forum groups)",
"channels.field_topic": "Topic",
"channels.field_urls": "Apprise URLs",
"channels.field_user_key": "User key",
"channels.field_webhook_url": "Webhook URL",
"channels.help_apprise": "Reaches over 100 services through an Apprise API server: give Apprise URLs or the key of a configuration stored there.",
"channels.help_opsgenie": "The alert closes when the incident is resolved.",
"channels.help_pagerduty": "Use the integration key of an Events API v2 integration; resolving closes the PagerDuty incident.",
"channels.help_signal": "Needs a signal-cli REST API server (bbernhard/signal-cli-rest-api) with a registered number.",
"channels.help_teams": "Use the URL of a Teams workflow \"Post to a channel when a webhook request is received\".",
"channels.help_telegram": "Create a bot with @BotFather; the chat ID of a group starts with -100.",
"channels.intro": "Every enabled channel is notified when a monitor goes down in all of its regions and when it recovers.", "channels.intro": "Every enabled channel is notified when a monitor goes down in all of its regions and when it recovers.",
"channels.language": "Language", "channels.language": "Language",
"channels.new_email": "New email channel", "channels.new_email": "New email channel",
"channels.new_service": "Other services",
"channels.new_webhook": "New webhook", "channels.new_webhook": "New webhook",
"channels.optional": "optional",
"channels.secret_now": "Signing secret: verify the X-Uptimesebi-Signature header with it. It will not be shown again.", "channels.secret_now": "Signing secret: verify the X-Uptimesebi-Signature header with it. It will not be shown again.",
"channels.service": "Service",
"channels.service_intro": "Chat, push and paging services. Tokens and keys are stored encrypted and never shown again.",
"channels.test": "Send test", "channels.test": "Send test",
"channels.test_ok": "Test notification delivered.", "channels.test_ok": "Test notification delivered.",
"channels.title": "Notifications", "channels.title": "Notifications",
"channels.to": "Recipients", "channels.to": "Recipients",
"channels.type_apprise": "Apprise",
"channels.type_discord": "Discord",
"channels.type_email": "Email", "channels.type_email": "Email",
"channels.type_googlechat": "Google Chat",
"channels.type_gotify": "Gotify",
"channels.type_matrix": "Matrix",
"channels.type_mattermost": "Mattermost",
"channels.type_ntfy": "ntfy",
"channels.type_opsgenie": "Opsgenie",
"channels.type_pagerduty": "PagerDuty",
"channels.type_pushbullet": "Pushbullet",
"channels.type_pushover": "Pushover",
"channels.type_rocketchat": "Rocket.Chat",
"channels.type_signal": "Signal",
"channels.type_slack": "Slack",
"channels.type_teams": "Microsoft Teams",
"channels.type_telegram": "Telegram",
"channels.type_webhook": "Webhook", "channels.type_webhook": "Webhook",
"channels.url": "Webhook URL", "channels.url": "Webhook URL",
"checkers.avg_latency": "Average latency", "checkers.avg_latency": "Average latency",
@@ -189,6 +238,7 @@
"error.invalid_assertion_path": "A condition path is invalid. Use keys separated by dots and [n] for array elements.", "error.invalid_assertion_path": "A condition path is invalid. Use keys separated by dots and [n] for array elements.",
"error.invalid_assertion_value": "Comparisons with <, >, ≤ and ≥ need a number.", "error.invalid_assertion_value": "Comparisons with <, >, ≤ and ≥ need a number.",
"error.invalid_assertions": "Add between 1 and 10 conditions.", "error.invalid_assertions": "Add between 1 and 10 conditions.",
"error.invalid_channel_settings": "Fill in the required fields; addresses must be https URLs.",
"error.invalid_code": "Invalid code.", "error.invalid_code": "Invalid code.",
"error.invalid_config": "The check settings are not valid.", "error.invalid_config": "The check settings are not valid.",
"error.invalid_credentials": "Wrong email or password.", "error.invalid_credentials": "Wrong email or password.",
@@ -595,6 +645,11 @@
"monitors.type_tls": "TLS certificate", "monitors.type_tls": "TLS certificate",
"monitors.uptime_chart": "Uptime per period", "monitors.uptime_chart": "Uptime per period",
"monitors.verify_tls": "Verify TLS certificate", "monitors.verify_tls": "Verify TLS certificate",
"notify.duration": "Down for {{.Duration}}",
"notify.test_body": "If you can read this, the channel works.",
"notify.title_opened": "{{.Monitor}} is down",
"notify.title_resolved": "{{.Monitor}} is up again",
"notify.title_test": "Test from UptimeSebi",
"org.policy": "Sign-in policy", "org.policy": "Sign-in policy",
"org.require_sso": "Require SSO", "org.require_sso": "Require SSO",
"org.require_sso_hint": "Members must sign in through this organization's identity provider. The owner can still use a password so a broken IdP cannot lock you out.", "org.require_sso_hint": "Members must sign in through this organization's identity provider. The owner can still use a password so a broken IdP cannot lock you out.",
@@ -0,0 +1,10 @@
-- +goose Up
-- Channel types follow notify.Providers; the application validates them
-- and their settings, secrets of which are sealed in config.
ALTER TABLE notification_channels DROP CONSTRAINT notification_channels_type_check;
ALTER TABLE notification_channels ADD CONSTRAINT notification_channels_type_check CHECK (type ~ '^[a-z]{2,32}$');
-- +goose Down
DELETE FROM notification_channels WHERE type NOT IN ('webhook', 'email');
ALTER TABLE notification_channels DROP CONSTRAINT notification_channels_type_check;
ALTER TABLE notification_channels ADD CONSTRAINT notification_channels_type_check CHECK (type IN ('webhook', 'email'));
+347
View File
@@ -0,0 +1,347 @@
package notify
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/netguard"
)
// Message is an incident event rendered for chat and push services.
type Message struct {
// Event is Opened, Resolved or Test.
Event string
Title string
Body string
// URL links to the monitor in the console.
URL string
// Key identifies the incident across its events, for services that
// pair "opened" with "resolved" such as PagerDuty.
Key uuid.UUID
}
// Field is a setting of a provider. Secret fields are stored sealed and
// never shown again.
type Field struct {
Name string
Required bool
Secret bool
// Kind is "url", "text", "number" or "select".
Kind string
Options []string
Default string
}
// Provider delivers messages to one kind of service.
type Provider struct {
Type string
Fields []Field
send func(ctx context.Context, c *client, cfg map[string]string, m Message) error
}
// Send delivers m with the settings in cfg. allowPrivate permits services
// on private networks, which self-hosted installations may use.
func (p Provider) Send(ctx context.Context, cfg map[string]string, m Message, allowPrivate bool) error {
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
return p.send(ctx, newClient(allowPrivate), cfg, m)
}
// Lookup returns the provider of type t.
func Lookup(t string) (Provider, bool) {
for _, p := range Providers {
if p.Type == t {
return p, true
}
}
return Provider{}, false
}
type client struct{ hc *http.Client }
func newClient(allowPrivate bool) *client {
d := netguard.Dialer(allowPrivate, 5*time.Second)
return &client{hc: &http.Client{
Transport: &http.Transport{DialContext: d.DialContext, DisableKeepAlives: true},
// Redirects would bypass the address the customer configured.
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
}}
}
// do sends a request and turns non-2xx answers into errors that quote the
// start of the service's reply, which usually says what is wrong.
func (c *client) do(ctx context.Context, method, rawURL string, header http.Header, body io.Reader) error {
req, err := http.NewRequestWithContext(ctx, method, rawURL, body)
if err != nil {
return err
}
for k, vs := range header {
req.Header[k] = vs
}
req.Header.Set("User-Agent", "uptimesebi-notify")
resp, err := c.hc.Do(req)
var uerr *url.Error
if errors.As(err, &uerr) {
// The URL may carry a secret, as Telegram's bot token in the path:
// name only the host.
return fmt.Errorf("%s: %w", req.URL.Host, uerr.Err)
}
if err != nil {
return err
}
defer func() { _ = resp.Body.Close() }()
reply, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return fmt.Errorf("%s answered %d: %s", req.URL.Host, resp.StatusCode, strings.TrimSpace(string(reply)))
}
return nil
}
func (c *client) json(ctx context.Context, method, rawURL string, header http.Header, v any) error {
body, err := json.Marshal(v)
if err != nil {
return err
}
if header == nil {
header = http.Header{}
}
header.Set("Content-Type", "application/json")
return c.do(ctx, method, rawURL, header, bytes.NewReader(body))
}
// text joins title, body and link for services that take plain text.
func (m Message) text() string {
s := m.Title
if m.Body != "" {
s += "\n" + m.Body
}
if m.URL != "" {
s += "\n" + m.URL
}
return s
}
func trimURL(s string) string { return strings.TrimSuffix(strings.TrimSpace(s), "/") }
var webhookField = Field{Name: "webhook_url", Required: true, Secret: true, Kind: "url"}
// Providers lists the supported services. Webhook and email are handled by
// their own types; Apprise reaches the services not listed here.
var Providers = []Provider{
{Type: "slack", Fields: []Field{webhookField}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
return c.json(ctx, http.MethodPost, cfg["webhook_url"], nil, map[string]any{"text": m.text()})
}},
{Type: "discord", Fields: []Field{webhookField}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
return c.json(ctx, http.MethodPost, cfg["webhook_url"], nil, map[string]any{"content": m.text(), "username": "UptimeSebi"})
}},
{Type: "teams", Fields: []Field{webhookField}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
// Teams workflows take Adaptive Cards.
blocks := []map[string]any{{"type": "TextBlock", "text": m.Title, "weight": "Bolder", "size": "Medium", "wrap": true}}
if m.Body != "" {
blocks = append(blocks, map[string]any{"type": "TextBlock", "text": m.Body, "wrap": true})
}
card := map[string]any{"type": "AdaptiveCard", "version": "1.4", "body": blocks,
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json"}
if m.URL != "" {
card["actions"] = []map[string]any{{"type": "Action.OpenUrl", "title": "UptimeSebi", "url": m.URL}}
}
return c.json(ctx, http.MethodPost, cfg["webhook_url"], nil, map[string]any{
"type": "message", "attachments": []map[string]any{{"contentType": "application/vnd.microsoft.card.adaptive", "content": card}},
})
}},
{Type: "googlechat", Fields: []Field{webhookField}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
return c.json(ctx, http.MethodPost, cfg["webhook_url"], nil, map[string]any{"text": m.text()})
}},
{Type: "mattermost", Fields: []Field{webhookField, {Name: "channel", Kind: "text"}}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
body := map[string]any{"text": m.text(), "username": "UptimeSebi"}
if cfg["channel"] != "" {
body["channel"] = cfg["channel"]
}
return c.json(ctx, http.MethodPost, cfg["webhook_url"], nil, body)
}},
{Type: "rocketchat", Fields: []Field{webhookField}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
return c.json(ctx, http.MethodPost, cfg["webhook_url"], nil, map[string]any{"text": m.text()})
}},
{Type: "telegram", Fields: []Field{
{Name: "bot_token", Required: true, Secret: true, Kind: "text"},
{Name: "chat_id", Required: true, Kind: "text"},
{Name: "thread_id", Kind: "number"},
{Name: "api_url", Kind: "url", Default: "https://api.telegram.org"},
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
body := map[string]any{"chat_id": cfg["chat_id"], "text": m.text(), "link_preview_options": map[string]any{"is_disabled": true}}
if id, err := strconv.Atoi(cfg["thread_id"]); err == nil && id > 0 {
body["message_thread_id"] = id
}
api := trimURL(cfg["api_url"])
if api == "" {
api = "https://api.telegram.org"
}
return c.json(ctx, http.MethodPost, api+"/bot"+cfg["bot_token"]+"/sendMessage", nil, body)
}},
{Type: "matrix", Fields: []Field{
{Name: "homeserver_url", Required: true, Kind: "url"},
{Name: "access_token", Required: true, Secret: true, Kind: "text"},
{Name: "room_id", Required: true, Kind: "text"},
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
u := trimURL(cfg["homeserver_url"]) + "/_matrix/client/v3/rooms/" + url.PathEscape(cfg["room_id"]) +
"/send/m.room.message/" + uuid.NewString()
h := http.Header{"Authorization": {"Bearer " + cfg["access_token"]}}
return c.json(ctx, http.MethodPut, u, h, map[string]any{"msgtype": "m.text", "body": m.text()})
}},
{Type: "ntfy", Fields: []Field{
{Name: "server_url", Kind: "url", Default: "https://ntfy.sh"},
{Name: "topic", Required: true, Kind: "text"},
{Name: "priority", Kind: "select", Options: []string{"3", "1", "2", "4", "5"}, Default: "4"},
{Name: "access_token", Secret: true, Kind: "text"},
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
server := trimURL(cfg["server_url"])
if server == "" {
server = "https://ntfy.sh"
}
h := http.Header{"Title": {m.Title}, "Priority": {cfg["priority"]}}
if m.Event == Resolved {
h.Set("Priority", "3")
}
if m.URL != "" {
h.Set("Click", m.URL)
}
if cfg["access_token"] != "" {
h.Set("Authorization", "Bearer "+cfg["access_token"])
}
return c.do(ctx, http.MethodPost, server+"/"+url.PathEscape(cfg["topic"]), h, strings.NewReader(m.Body))
}},
{Type: "gotify", Fields: []Field{
{Name: "server_url", Required: true, Kind: "url"},
{Name: "app_token", Required: true, Secret: true, Kind: "text"},
{Name: "priority", Kind: "number", Default: "8"},
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
prio, _ := strconv.Atoi(cfg["priority"])
h := http.Header{"X-Gotify-Key": {cfg["app_token"]}}
return c.json(ctx, http.MethodPost, trimURL(cfg["server_url"])+"/message", h,
map[string]any{"title": m.Title, "message": m.Body + "\n" + m.URL, "priority": prio})
}},
{Type: "pushover", Fields: []Field{
{Name: "user_key", Required: true, Secret: true, Kind: "text"},
{Name: "app_token", Required: true, Secret: true, Kind: "text"},
{Name: "priority", Kind: "select", Options: []string{"0", "-1", "1"}, Default: "1"},
{Name: "device", Kind: "text"},
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
form := url.Values{"token": {cfg["app_token"]}, "user": {cfg["user_key"]}, "title": {m.Title}, "message": {m.Body}, "priority": {cfg["priority"]}}
if m.URL != "" {
form.Set("url", m.URL)
}
if cfg["device"] != "" {
form.Set("device", cfg["device"])
}
h := http.Header{"Content-Type": {"application/x-www-form-urlencoded"}}
return c.do(ctx, http.MethodPost, pushoverURL, h, strings.NewReader(form.Encode()))
}},
{Type: "pushbullet", Fields: []Field{{Name: "access_token", Required: true, Secret: true, Kind: "text"}},
send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
h := http.Header{"Access-Token": {cfg["access_token"]}}
return c.json(ctx, http.MethodPost, pushbulletURL, h,
map[string]any{"type": "note", "title": m.Title, "body": m.Body + "\n" + m.URL})
}},
{Type: "signal", Fields: []Field{
{Name: "api_url", Required: true, Kind: "url"},
{Name: "number", Required: true, Kind: "text"},
{Name: "recipients", Required: true, Kind: "text"},
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
// signal-cli-rest-api: recipients are comma-separated numbers or
// group IDs.
var recipients []string
for _, r := range strings.Split(cfg["recipients"], ",") {
if r = strings.TrimSpace(r); r != "" {
recipients = append(recipients, r)
}
}
return c.json(ctx, http.MethodPost, trimURL(cfg["api_url"])+"/v2/send", nil,
map[string]any{"message": m.text(), "number": cfg["number"], "recipients": recipients})
}},
{Type: "pagerduty", Fields: []Field{
{Name: "routing_key", Required: true, Secret: true, Kind: "text"},
{Name: "severity", Kind: "select", Options: []string{"critical", "error", "warning", "info"}, Default: "critical"},
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
// Events API v2: the incident ID pairs trigger and resolve.
action := "trigger"
if m.Event == Resolved {
action = "resolve"
}
body := map[string]any{"routing_key": cfg["routing_key"], "event_action": action, "dedup_key": m.Key.String()}
if action == "trigger" {
body["payload"] = map[string]any{"summary": m.Title, "source": "UptimeSebi", "severity": cfg["severity"],
"custom_details": map[string]any{"details": m.Body}}
if m.URL != "" {
body["links"] = []map[string]any{{"href": m.URL, "text": "UptimeSebi"}}
}
}
return c.json(ctx, http.MethodPost, pagerdutyURL, nil, body)
}},
{Type: "opsgenie", Fields: []Field{
{Name: "api_key", Required: true, Secret: true, Kind: "text"},
{Name: "region", Kind: "select", Options: []string{"us", "eu"}, Default: "us"},
{Name: "priority", Kind: "select", Options: []string{"P1", "P2", "P3", "P4", "P5"}, Default: "P2"},
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
base := opsgenieURL["us"]
if cfg["region"] == "eu" {
base = opsgenieURL["eu"]
}
h := http.Header{"Authorization": {"GenieKey " + cfg["api_key"]}}
alias := m.Key.String()
if m.Event == Resolved {
return c.json(ctx, http.MethodPost, base+"/"+alias+"/close?identifierType=alias", h, map[string]any{"source": "UptimeSebi"})
}
return c.json(ctx, http.MethodPost, base, h, map[string]any{
"message": truncate(m.Title, 130), "alias": alias, "description": m.Body + "\n" + m.URL,
"priority": cfg["priority"], "source": "UptimeSebi",
})
}},
{Type: "apprise", Fields: []Field{
{Name: "api_url", Required: true, Kind: "url"},
{Name: "urls", Secret: true, Kind: "text"},
{Name: "config_key", Kind: "text"},
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
// An Apprise API server reaches over a hundred services: either
// stateless with Apprise URLs, or through a configuration stored
// on the server under a key.
typ := map[string]string{Opened: "failure", Resolved: "success"}[m.Event]
if typ == "" {
typ = "info"
}
body := map[string]any{"title": m.Title, "body": m.Body + "\n" + m.URL, "type": typ}
api := trimURL(cfg["api_url"])
if key := strings.TrimSpace(cfg["config_key"]); key != "" {
return c.json(ctx, http.MethodPost, api+"/notify/"+url.PathEscape(key), nil, body)
}
body["urls"] = cfg["urls"]
return c.json(ctx, http.MethodPost, api+"/notify", nil, body)
}},
}
// truncate shortens s to n characters.
func truncate(s string, n int) string {
r := []rune(s)
if len(r) <= n {
return s
}
return string(r[:n-1]) + "…"
}
// Fixed service addresses, replaced in tests.
var (
pushoverURL = "https://api.pushover.net/1/messages.json"
pushbulletURL = "https://api.pushbullet.com/v2/pushes"
pagerdutyURL = "https://events.pagerduty.com/v2/enqueue"
opsgenieURL = map[string]string{"us": "https://api.opsgenie.com/v2/alerts", "eu": "https://api.eu.opsgenie.com/v2/alerts"}
)
+134
View File
@@ -0,0 +1,134 @@
package notify
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/google/uuid"
)
// recorded is a request a fake service received.
type recorded struct {
Method, Path, Query string
Header http.Header
Body string
}
func fakeService(t *testing.T) (*httptest.Server, func() recorded) {
t.Helper()
var mu sync.Mutex
var last recorded
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
mu.Lock()
last = recorded{r.Method, r.URL.Path, r.URL.RawQuery, r.Header.Clone(), string(b)}
mu.Unlock()
w.WriteHeader(http.StatusOK)
}))
t.Cleanup(srv.Close)
return srv, func() recorded { mu.Lock(); defer mu.Unlock(); return last }
}
func TestProviders(t *testing.T) {
srv, last := fakeService(t)
pushoverURL, pushbulletURL, pagerdutyURL = srv.URL+"/pushover", srv.URL+"/pushbullet", srv.URL+"/pagerduty"
opsgenieURL = map[string]string{"us": srv.URL + "/opsgenie", "eu": srv.URL + "/opsgenie-eu"}
key := uuid.MustParse("00000000-0000-0000-0000-0000000000aa")
opened := Message{Event: Opened, Title: "Shop is down", Body: "unexpected status 502", URL: "https://uptime.example/monitors/1", Key: key}
resolved := opened
resolved.Event, resolved.Title = Resolved, "Shop is up again"
for _, tc := range []struct {
typ string
cfg map[string]string
msg Message
check func(r recorded) bool
}{
{"slack", map[string]string{"webhook_url": srv.URL + "/slack"}, opened, func(r recorded) bool { return strings.Contains(r.Body, `"text":"Shop is down`) }},
{"discord", map[string]string{"webhook_url": srv.URL + "/discord"}, opened, func(r recorded) bool { return strings.Contains(r.Body, `"content":"Shop is down`) }},
{"teams", map[string]string{"webhook_url": srv.URL + "/teams"}, opened, func(r recorded) bool {
return strings.Contains(r.Body, "application/vnd.microsoft.card.adaptive") && strings.Contains(r.Body, "Action.OpenUrl")
}},
{"telegram", map[string]string{"bot_token": "123:abc", "chat_id": "-100", "thread_id": "7", "api_url": srv.URL}, opened, func(r recorded) bool {
return r.Path == "/bot123:abc/sendMessage" && strings.Contains(r.Body, `"chat_id":"-100"`) && strings.Contains(r.Body, `"message_thread_id":7`)
}},
{"matrix", map[string]string{"homeserver_url": srv.URL, "access_token": "tok", "room_id": "!room:example.org"}, opened, func(r recorded) bool {
return r.Method == http.MethodPut && strings.HasPrefix(r.Path, "/_matrix/client/v3/rooms/!room:example.org/send/m.room.message/") && r.Header.Get("Authorization") == "Bearer tok"
}},
{"ntfy", map[string]string{"server_url": srv.URL, "topic": "ops", "priority": "5", "access_token": "tk"}, opened, func(r recorded) bool {
return r.Path == "/ops" && r.Header.Get("Title") == "Shop is down" && r.Header.Get("Priority") == "5" && r.Header.Get("Click") != ""
}},
{"ntfy", map[string]string{"server_url": srv.URL, "topic": "ops", "priority": "5"}, resolved, func(r recorded) bool { return r.Header.Get("Priority") == "3" }},
{"gotify", map[string]string{"server_url": srv.URL, "app_token": "gk", "priority": "8"}, opened, func(r recorded) bool {
return r.Path == "/message" && r.Header.Get("X-Gotify-Key") == "gk" && strings.Contains(r.Body, `"priority":8`)
}},
{"pushover", map[string]string{"user_key": "u", "app_token": "a", "priority": "1"}, opened, func(r recorded) bool {
return r.Path == "/pushover" && strings.Contains(r.Body, "user=u") && strings.Contains(r.Body, "token=a")
}},
{"pushbullet", map[string]string{"access_token": "pb"}, opened, func(r recorded) bool { return r.Header.Get("Access-Token") == "pb" }},
{"signal", map[string]string{"api_url": srv.URL, "number": "+49", "recipients": "+491, group.abc"}, opened, func(r recorded) bool {
return r.Path == "/v2/send" && strings.Contains(r.Body, `"recipients":["+491","group.abc"]`)
}},
{"pagerduty", map[string]string{"routing_key": "rk", "severity": "critical"}, opened, func(r recorded) bool {
return strings.Contains(r.Body, `"event_action":"trigger"`) && strings.Contains(r.Body, `"dedup_key":"`+key.String()+`"`)
}},
{"pagerduty", map[string]string{"routing_key": "rk"}, resolved, func(r recorded) bool {
return strings.Contains(r.Body, `"event_action":"resolve"`) && !strings.Contains(r.Body, "payload")
}},
{"opsgenie", map[string]string{"api_key": "ok", "region": "eu", "priority": "P1"}, opened, func(r recorded) bool {
return r.Path == "/opsgenie-eu" && r.Header.Get("Authorization") == "GenieKey ok" && strings.Contains(r.Body, `"alias":"`+key.String()+`"`)
}},
{"opsgenie", map[string]string{"api_key": "ok"}, resolved, func(r recorded) bool {
return r.Path == "/opsgenie/"+key.String()+"/close" && r.Query == "identifierType=alias"
}},
{"apprise", map[string]string{"api_url": srv.URL, "urls": "tgram://bot/chat"}, opened, func(r recorded) bool {
return r.Path == "/notify" && strings.Contains(r.Body, `"type":"failure"`) && strings.Contains(r.Body, "tgram://")
}},
{"apprise", map[string]string{"api_url": srv.URL, "config_key": "ops team"}, resolved, func(r recorded) bool {
return r.Path == "/notify/ops team" && strings.Contains(r.Body, `"type":"success"`)
}},
} {
p, ok := Lookup(tc.typ)
if !ok {
t.Fatalf("no provider %s", tc.typ)
}
if err := p.Send(context.Background(), tc.cfg, tc.msg, true); err != nil {
t.Errorf("%s: Send() = %v", tc.typ, err)
continue
}
if r := last(); !tc.check(r) {
t.Errorf("%s: unexpected request %s %s?%s %v %s", tc.typ, r.Method, r.Path, r.Query, r.Header, r.Body)
}
}
}
func TestProviderErrorsQuoteTheService(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
_ = json.NewEncoder(w).Encode(map[string]string{"description": "Unauthorized: invalid token"})
}))
defer srv.Close()
p, _ := Lookup("slack")
err := p.Send(context.Background(), map[string]string{"webhook_url": srv.URL}, Message{Title: "t"}, true)
if err == nil || !strings.Contains(err.Error(), "401") || !strings.Contains(err.Error(), "invalid token") {
t.Errorf("Send() = %v, want the status and the service's reason", err)
}
// Services on private networks are refused unless allowed.
if err := p.Send(context.Background(), map[string]string{"webhook_url": srv.URL}, Message{Title: "t"}, false); err == nil {
t.Error("a private address was reached without permission")
}
}
func TestProviderErrorsHideSecretURLs(t *testing.T) {
p, _ := Lookup("telegram")
err := p.Send(context.Background(), map[string]string{"bot_token": "123:secret", "chat_id": "1", "api_url": "http://127.0.0.1:1"}, Message{Title: "t"}, true)
if err == nil || strings.Contains(err.Error(), "secret") {
t.Errorf("Send() = %v, want an error without the token", err)
}
}
+88
View File
@@ -766,6 +766,7 @@ type ChannelsView struct {
EmailAvailable bool EmailAvailable bool
CanWrite bool CanWrite bool
Languages []string Languages []string
Providers []ProviderOption
} }
templ ChannelsPage(p Page, me Me, v ChannelsView) { templ ChannelsPage(p Page, me Me, v ChannelsView) {
@@ -834,11 +835,98 @@ templ ChannelsPage(p Page, me Me, v ChannelsView) {
<p class="text-sm text-muted">{ i18n.T(ctx, "error.email_not_configured") }</p> <p class="text-sm text-muted">{ i18n.T(ctx, "error.email_not_configured") }</p>
} }
</section> </section>
<section class="md:col-span-2">
@sectionHeading("channels.new_service")
<p class="mb-4 max-w-2xl text-sm text-muted">{ i18n.T(ctx, "channels.service_intro") }</p>
<form data-api="/org/channels" data-next="/settings/channels" class="grid gap-x-8 md:grid-cols-2">
<div>
@formError()
<label class="mb-4 block">
<span class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "channels.service") }</span>
<select name="type" data-type-select class="w-full border border-rule bg-transparent px-2 py-1.5 text-sm">
for _, pr := range v.Providers {
<option value={ pr.Type }>{ i18n.T(ctx, "channels.type_"+pr.Type) }</option>
}
</select>
</label>
@valueField(i18n.T(ctx, "sso.field.name"), "name", "", "Ops", true)
<label class="mb-4 block">
<span class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "channels.language") }</span>
<select name="locale" class="w-40 border border-rule bg-transparent px-2 py-1.5 text-sm">
for _, l := range v.Languages {
<option value={ l } selected?={ l == i18n.Lang(ctx) }>{ i18n.T(ctx, "lang."+l) }</option>
}
</select>
</label>
</div>
<div>
for i, pr := range v.Providers {
<fieldset data-type={ pr.Type } disabled?={ i != 0 } hidden?={ i != 0 }>
if pr.Help != "" {
<p class="mb-3 text-xs text-muted">{ pr.Help }</p>
}
for _, f := range pr.Fields {
@providerField(f)
}
</fieldset>
}
@submit(i18n.T(ctx, "channels.create"))
</div>
</form>
</section>
</div> </div>
} }
} }
} }
// ProviderOption is a notification service the form offers.
type ProviderOption struct {
Type string
Help string
Fields []ProviderField
}
// ProviderField is a setting of a service.
type ProviderField struct {
Name string
Label string
Required bool
Secret bool
Kind string
Options []string
Default string
}
templ providerField(f ProviderField) {
<label class="mb-4 block">
<span class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">
{ f.Label }
if !f.Required {
<span class="normal-case tracking-normal">{ " · " + i18n.T(ctx, "channels.optional") }</span>
}
</span>
switch {
case f.Kind == "select":
<select name={ "settings." + f.Name } class="w-full border border-rule bg-transparent px-2 py-1.5 font-mono text-sm">
for _, o := range f.Options {
<option value={ o } selected?={ o == f.Default }>{ o }</option>
}
</select>
case f.Secret:
<input type="password" name={ "settings." + f.Name } required?={ f.Required } autocomplete="off" class="w-full border border-rule bg-transparent px-2.5 py-1.5 font-mono text-sm outline-none focus:border-ink"/>
default:
<input
type={ map[bool]string{true: "number", false: "text"}[f.Kind == "number"] }
name={ "settings." + f.Name }
value={ f.Default }
required?={ f.Required }
placeholder={ map[bool]string{true: "https://", false: ""}[f.Kind == "url"] }
class="w-full border border-rule bg-transparent px-2.5 py-1.5 font-mono text-sm outline-none focus:border-ink"
/>
}
</label>
}
templ groupSelect(name string, groups []GroupOption, selected string, allowNone bool) { templ groupSelect(name string, groups []GroupOption, selected string, allowNone bool) {
<select name={ name } data-nullable class="w-full border border-rule bg-transparent px-2 py-1.5 text-sm"> <select name={ name } data-nullable class="w-full border border-rule bg-transparent px-2 py-1.5 text-sm">
if allowNone { if allowNone {
File diff suppressed because it is too large. Load diff