diff --git a/internal/notify/providers.go b/internal/notify/providers.go new file mode 100644 index 0000000..4fcb3dd --- /dev/null +++ b/internal/notify/providers.go @@ -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"} +) diff --git a/internal/notify/providers_test.go b/internal/notify/providers_test.go new file mode 100644 index 0000000..d9b5772 --- /dev/null +++ b/internal/notify/providers_test.go @@ -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) + } +}