package notify import ( "bytes" "context" "encoding/base64" "encoding/json" "errors" "fmt" "io" "net" "net/http" "net/url" "slices" "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 // Monitor, MonitorID and Target describe the monitor, for services // with fields of their own for them. Monitor string MonitorID uuid.UUID Target string } // status is "down", "up" or "test". func (m Message) status() string { switch m.Event { case Opened: return "down" case Resolved: return "up" } return "test" } // 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 // Group sorts the service in forms: "chat", "push", "sms", "email" or // "incident". Group 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 d *net.Dialer } // transport is replaced in tests to reach fixed service addresses. var transport = func(d *net.Dialer) http.RoundTripper { return &http.Transport{DialContext: d.DialContext, DisableKeepAlives: true} } func newClient(allowPrivate bool) *client { d := netguard.Dialer(allowPrivate, 5*time.Second) return &client{d: d, hc: &http.Client{ Transport: transport(d), // 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 { _, err := c.call(ctx, method, rawURL, header, body) return err } // call is do returning the reply, for services that report failures in // successful answers. func (c *client) call(ctx context.Context, method, rawURL string, header http.Header, body io.Reader) ([]byte, error) { req, err := http.NewRequestWithContext(ctx, method, rawURL, body) if err != nil { return nil, 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 nil, fmt.Errorf("%s: %w", req.URL.Host, uerr.Err) } if err != nil { return nil, err } defer func() { _ = resp.Body.Close() }() reply, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10)) if resp.StatusCode < 200 || resp.StatusCode > 299 { return nil, fmt.Errorf("%s answered %d: %s", req.URL.Host, resp.StatusCode, truncate(strings.TrimSpace(string(reply)), 300)) } return reply, nil } func (c *client) json(ctx context.Context, method, rawURL string, header http.Header, v any) error { _, err := c.callJSON(ctx, method, rawURL, header, v) return err } func (c *client) callJSON(ctx context.Context, method, rawURL string, header http.Header, v any) ([]byte, error) { body, err := json.Marshal(v) if err != nil { return nil, err } if header == nil { header = http.Header{} } header.Set("Content-Type", "application/json") return c.call(ctx, method, rawURL, header, bytes.NewReader(body)) } // form posts URL-encoded values and returns the reply. func (c *client) form(ctx context.Context, rawURL string, header http.Header, v url.Values) ([]byte, error) { if header == nil { header = http.Header{} } header.Set("Content-Type", "application/x-www-form-urlencoded") return c.call(ctx, http.MethodPost, rawURL, header, strings.NewReader(v.Encode())) } // get sends a GET with query parameters and returns the reply. func (c *client) get(ctx context.Context, rawURL string, header http.Header, q url.Values) ([]byte, error) { if len(q) > 0 { sep := "?" if strings.Contains(rawURL, "?") { sep = "&" } rawURL += sep + q.Encode() } return c.call(ctx, http.MethodGet, rawURL, header, nil) } // basic returns an Authorization header with HTTP basic credentials. func basic(user, password string) http.Header { return http.Header{"Authorization": {"Basic " + base64.StdEncoding.EncodeToString([]byte(user+":"+password))}} } func bearer(token string) http.Header { return http.Header{"Authorization": {"Bearer " + token}} } // replyCheck decodes a JSON reply and fails with what bad reports, for // services that answer 200 to failed requests. func replyCheck(reply []byte, err error, bad func(map[string]any) string) error { if err != nil { return err } var v map[string]any if json.Unmarshal(reply, &v) != nil { return fmt.Errorf("unexpected answer: %s", truncate(string(reply), 200)) } if msg := bad(v); msg != "" { return errors.New(truncate(msg, 300)) } return nil } // str formats a JSON value from a reply for messages and comparisons. func str(v any) string { switch v := v.(type) { case nil: return "" case string: return v case float64: return strconv.FormatFloat(v, 'f', -1, 64) } b, _ := json.Marshal(v) return string(b) } // list splits comma, semicolon or newline separated values. func list(s string) []string { var out []string for _, v := range strings.FieldsFunc(s, func(r rune) bool { return r == ',' || r == ';' || r == '\n' }) { if v = strings.TrimSpace(v); v != "" { out = append(out, v) } } return out } // or returns s, or def when s is blank. func or(s, def string) string { if strings.TrimSpace(s) == "" { return def } return strings.TrimSpace(s) } // 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 = slices.Concat(baseProviders, chatProviders, pushProviders, smsProviders, emailProviders, incidentProviders) var baseProviders = []Provider{ {Type: "slack", Group: "chat", 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", Group: "chat", 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", Group: "chat", 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", Group: "chat", 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", Group: "chat", 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", Group: "chat", 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", Group: "chat", 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", Group: "chat", 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", Group: "push", 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", Group: "push", 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", Group: "push", 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", Group: "push", 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", Group: "chat", 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", Group: "incident", 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", Group: "incident", 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", Group: "other", 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"} )