Files
uptimesebi/internal/notify/services_test.go
T
Sebastian UnterschützandClaude Opus 5.5 52819e64bb
ci / image (pull_request) Successful in 4m24s
ci / build (pull_request) Successful in 5m6s
ci / lint (pull_request) Successful in 12m3s
ci / test (pull_request) Successful in 15m27s
feat(notify): the remaining notification services of Uptime Kuma
Adds 93 services, bringing the total to 109 plus webhook and email:
chat and messengers (DingTalk, Feishu, LINE, Nextcloud Talk, Threema,
WhatsApp gateways, Nostr, Home Assistant, …), push (Bark, Gorush,
ServerChan, …), SMS and calls (Twilio, Plivo, 46elks, Alibaba Cloud,
Teltonika routers, …), email APIs (SendGrid, Brevo, Resend, Microsoft
Graph, …) and incident management (Grafana OnCall, Jira Service
Management, Splunk On-Call, Squadcast, SIGNL4, …). Customers bring
their own credentials; secrets are sealed like the others.

Services pair incidents by their ID where they can resolve alerts.
Signed requests (DingTalk, Nextcloud Talk, Alibaba Cloud) and replies
that report failures with status 200 are handled. Nostr messages are
sealed and gift-wrapped (NIP-17/59) with go-nostr, but sent over our own
WebSocket connections so relays go through the network guard. Messages
now carry the monitor's name, ID and target.

The channel form groups services, the i18n test derives provider keys
from the registry, and channel types may contain digits.

Refs #92

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 17:40:19 +01:00

393 lines
28 KiB
Go

package notify
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"io"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"testing"
"github.com/coder/websocket"
"github.com/google/uuid"
"github.com/nbd-wtf/go-nostr"
"github.com/nbd-wtf/go-nostr/nip19"
"github.com/nbd-wtf/go-nostr/nip44"
"github.com/nbd-wtf/go-nostr/nip59"
)
// call is a request a fake service received, with the host it was meant
// for.
type call struct {
Method, Host, Path string
Query url.Values
Header http.Header
Body string
}
func (c call) form() url.Values { v, _ := url.ParseQuery(c.Body); return v }
func (c call) json() map[string]any {
var v map[string]any
_ = json.Unmarshal([]byte(c.Body), &v)
return v
}
// services routes every request to one fake server, whatever host it was
// addressed to, and answers with reply.
func services(t *testing.T, reply func(call) (int, string)) func() []call {
t.Helper()
var mu sync.Mutex
var calls []call
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
c := call{r.Method, r.Header.Get("X-Test-Host"), r.URL.Path, r.URL.Query(), r.Header.Clone(), string(b)}
mu.Lock()
calls = append(calls, c)
mu.Unlock()
status, body := reply(c)
w.WriteHeader(status)
_, _ = io.WriteString(w, body)
}))
t.Cleanup(srv.Close)
target, _ := url.Parse(srv.URL)
old := transport
transport = func(*net.Dialer) http.RoundTripper {
return roundTrip(func(r *http.Request) (*http.Response, error) {
r = r.Clone(r.Context())
r.Header.Set("X-Test-Host", r.URL.Host)
r.URL.Scheme, r.URL.Host, r.Host = "http", target.Host, target.Host
return http.DefaultTransport.RoundTrip(r)
})
}
t.Cleanup(func() { transport = old })
return func() []call { mu.Lock(); defer mu.Unlock(); return append([]call(nil), calls...) }
}
type roundTrip func(*http.Request) (*http.Response, error)
func (f roundTrip) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
var (
testKey = uuid.MustParse("00000000-0000-0000-0000-0000000000aa")
testOpened = Message{Event: Opened, Title: "Shop is down", Body: "eu: unexpected status 502", URL: "https://uptime.example/monitors/1", Key: testKey, Monitor: "Shop", Target: "https://shop.example"}
testResolve = func() Message { m := testOpened; m.Event, m.Title = Resolved, "Shop is up again"; return m }()
)
// serviceCase sends msg through typ with cfg; check inspects the requests.
type serviceCase struct {
typ string
cfg map[string]string
msg Message
reply string
check func(t *testing.T, calls []call)
}
// one asserts a single request to host and path containing all of want in
// its URL, headers or body.
func one(host, path string, want ...string) func(*testing.T, []call) {
return func(t *testing.T, calls []call) {
t.Helper()
if len(calls) != 1 {
t.Fatalf("%d requests, want 1", len(calls))
}
c := calls[0]
if c.Host != host || !strings.HasPrefix(c.Path, path) {
t.Errorf("request to %s%s, want %s%s", c.Host, c.Path, host, path)
}
all := c.Path + "?" + c.Query.Encode() + "\n" + c.Body
for k, v := range c.Header {
all += "\n" + k + ": " + strings.Join(v, ",")
}
decoded, _ := url.QueryUnescape(all)
for _, w := range want {
if !strings.Contains(all, w) && !strings.Contains(decoded, w) {
t.Errorf("request lacks %q:\n%s", w, all)
}
}
}
}
func TestServices(t *testing.T) {
var current *serviceCase
calls := services(t, func(call) (int, string) {
if current.reply != "" {
return http.StatusOK, current.reply
}
return http.StatusOK, "{}"
})
basicAuth := func(u, p string) string { return "Basic " + base64.StdEncoding.EncodeToString([]byte(u+":"+p)) }
cases := []serviceCase{
// Chat and messengers.
{typ: "bale", cfg: map[string]string{"bot_token": "b0t", "chat_id": "42"}, check: one("tapi.bale.ai", "/botb0t/sendMessage", `"chat_id":"42"`, "Shop is down")},
{typ: "bitrix", cfg: map[string]string{"webhook_url": "https://corp.bitrix24.de/rest/1/k3y", "user_id": "7"}, check: one("corp.bitrix24.de", "/rest/1/k3y/im.notify.system.add.json", "user_id=7", "Shop is down")},
{typ: "clickup", cfg: map[string]string{"api_token": "pk_1", "workspace_id": "w1", "channel_id": "c1"}, check: one("api.clickup.com", "/api/v3/workspaces/w1/chat/channels/c1/messages", "Authorization: pk_1", "Shop is down")},
{typ: "dingtalk", cfg: map[string]string{"webhook_url": "https://oapi.dingtalk.com/robot/send?access_token=at", "sign_secret": "SECabc"}, reply: `{"errcode":0,"errmsg":"ok"}`,
check: func(t *testing.T, calls []call) {
one("oapi.dingtalk.com", "/robot/send", "access_token=at", "Shop is down")(t, calls)
ts, sign := calls[0].Query.Get("timestamp"), calls[0].Query.Get("sign")
mac := hmac.New(sha256.New, []byte("SECabc"))
mac.Write([]byte(ts + "\nSECabc"))
if sign != base64.StdEncoding.EncodeToString(mac.Sum(nil)) {
t.Error("DingTalk signature does not verify")
}
}},
{typ: "feishu", cfg: map[string]string{"webhook_url": "https://open.feishu.cn/open-apis/bot/v2/hook/x"}, reply: `{"code":0}`, check: one("open.feishu.cn", "/open-apis/bot/v2/hook/x", `"msg_type":"text"`, "Shop is down")},
{typ: "fluxer", cfg: map[string]string{"webhook_url": "https://api.fluxer.app/webhooks/1/t"}, check: one("api.fluxer.app", "/webhooks/1/t", `"content":"Shop is down`)},
{typ: "kook", cfg: map[string]string{"bot_token": "kt", "channel_id": "ch"}, reply: `{"code":0}`, check: one("www.kookapp.cn", "/api/v3/message/create", "Authorization: Bot kt", `"target_id":"ch"`)},
{typ: "line", cfg: map[string]string{"access_token": "lt", "user_id": "U1"}, check: one("api.line.me", "/v2/bot/message/push", "Bearer lt", `"to":"U1"`, "Shop is down")},
{typ: "max", cfg: map[string]string{"bot_token": "mt", "chat_id": "-5"}, check: one("platform-api.max.ru", "/messages", "chat_id=-5", "Authorization: mt", "Shop is down")},
{typ: "milky", cfg: map[string]string{"api_url": "http://qq.lan:3000", "access_token": "mk", "message_type": "group", "receiver_id": "123"}, check: one("qq.lan:3000", "/api/send_group_message", `"group_id":123`, "Bearer mk")},
{typ: "onebot", cfg: map[string]string{"api_url": "http://qq.lan:5700", "message_type": "private", "receiver_id": "9"}, check: one("qq.lan:5700", "/send_msg", `"message_type":"private"`, `"user_id":"9"`)},
{typ: "onechat", cfg: map[string]string{"access_token": "oc", "receiver_id": "r", "bot_id": "b"}, check: one("chat-api.one.th", "/message/api/v1/push_message", "Bearer oc", `"bot_id":"b"`)},
{typ: "nextcloudtalk", cfg: map[string]string{"server_url": "https://cloud.example", "conversation_token": "ct", "bot_secret": "bs"},
check: func(t *testing.T, calls []call) {
one("cloud.example", "/ocs/v2.php/apps/spreed/api/v1/bot/ct/message", "Shop is down")(t, calls)
c := calls[0]
mac := hmac.New(sha256.New, []byte("bs"))
mac.Write([]byte(c.Header.Get("X-Nextcloud-Talk-Bot-Random") + c.json()["message"].(string)))
if c.Header.Get("X-Nextcloud-Talk-Bot-Signature") != hex.EncodeToString(mac.Sum(nil)) {
t.Error("Nextcloud Talk signature does not verify")
}
}},
{typ: "pumble", cfg: map[string]string{"webhook_url": "https://api.pumble.com/workspaces/w/x"}, check: one("api.pumble.com", "/workspaces/w/x", `"color":"#DC3645"`)},
{typ: "stackfield", cfg: map[string]string{"webhook_url": "https://www.stackfield.com/apiwebhook/x"}, check: one("www.stackfield.com", "/apiwebhook/x", `"Title":"Shop is down`)},
{typ: "vk", cfg: map[string]string{"access_token": "vt", "peer_id": "2000000001"}, reply: `{"response":1}`, check: one("api.vk.ru", "/method/messages.send", "access_token=vt", "v=5.199", "peer_id=2000000001")},
{typ: "vkteams", cfg: map[string]string{"bot_token": "vkt", "chat_id": "c@chat"}, reply: `{"ok":true}`, check: one("myteam.mail.ru", "/bot/v1/messages/sendText", "token=vkt", "chatId=c@chat")},
{typ: "wecom", cfg: map[string]string{"bot_key": "wk", "mentioned_mobiles": "138, 139"}, reply: `{"errcode":0}`, check: one("qyapi.weixin.qq.com", "/cgi-bin/webhook/send", "key=wk", `"mentioned_mobile_list":["138","139"]`)},
{typ: "yunzhijia", cfg: map[string]string{"webhook_url": "https://www.yunzhijia.com/gateway/robot/webhook/send", "token": "yt"}, reply: `{"success":true}`, check: one("www.yunzhijia.com", "/gateway/robot/webhook/send", "yzjtoken=yt", "Shop is down")},
{typ: "zohocliq", cfg: map[string]string{"webhook_url": "https://cliq.zoho.eu/api/v2/channelsbyname/ops/message?zapikey=z"}, check: one("cliq.zoho.eu", "/api/v2/channelsbyname/ops/message", `"text":"Shop is down`)},
{typ: "threema", cfg: map[string]string{"gateway_id": "*UPTIME1", "gateway_secret": "ts", "recipient_type": "phone", "recipient": "41791234567"}, check: one("msgapi.threema.ch", "/send_simple", "from=*UPTIME1", "phone=41791234567", "secret=ts")},
{typ: "evolution", cfg: map[string]string{"api_url": "https://evo.example", "api_key": "ek", "instance": "main", "recipient": "4917"}, check: one("evo.example", "/message/sendText/main", "Apikey: ek", `"number":"4917"`)},
{typ: "waha", cfg: map[string]string{"api_url": "http://waha.lan:3000", "api_key": "wk", "session": "default", "chat_id": "49@c.us"}, check: one("waha.lan:3000", "/api/sendText", "X-Api-Key: wk", `"chatId":"49@c.us"`)},
{typ: "whapi", cfg: map[string]string{"api_token": "wt", "recipient": "4917"}, check: one("gate.whapi.cloud", "/messages/text", "Bearer wt", `"to":"4917"`)},
{typ: "openwa", cfg: map[string]string{"api_url": "http://wa.lan", "api_key": "ok", "session": "s1", "chat_ids": "1@c.us"}, check: one("wa.lan", "/api/sessions/s1/messages/send-text", "X-Api-Key: ok", `"chatId":"1@c.us"`)},
{typ: "onesender", cfg: map[string]string{"api_url": "https://os.example/api/v1/messages", "api_token": "ot", "message_type": "group", "recipient": "123"}, check: one("os.example", "/api/v1/messages", "Bearer ot", `"to":"123@g.us"`)},
{typ: "messenger360", cfg: map[string]string{"api_token": "m3", "recipients": "4917"}, check: one("api.360messenger.com", "/v2/sendMessage", "Bearer m3", `"phonenumber":"4917"`)},
{typ: "homeassistant", cfg: map[string]string{"server_url": "http://ha.lan:8123", "access_token": "ha", "service": "mobile_app_phone"}, check: one("ha.lan:8123", "/api/services/notify/mobile_app_phone", "Bearer ha", "Shop is down")},
{typ: "indigo", cfg: map[string]string{"server_url": "https://indigo.lan", "api_key": "ik", "variable_id": "12"}, check: one("indigo.lan", "/v2/api/command", "indigo.variable.updateValue", `"objectId":12`)},
{typ: "googlesheets", cfg: map[string]string{"webhook_url": "https://script.google.com/macros/s/x/exec"}, check: one("script.google.com", "/macros/s/x/exec", `"status":"DOWN"`, `"monitorName":"Shop"`)},
{typ: "callmebot", cfg: map[string]string{"endpoint_url": "https://api.callmebot.com/whatsapp.php?phone=49&apikey=cb"}, check: one("api.callmebot.com", "/whatsapp.php", "apikey=cb", "text=Shop is down")},
// Push.
{typ: "bark", cfg: map[string]string{"endpoint_url": "https://api.day.app/devkey"}, check: one("api.day.app", "/devkey", `"title":"Shop is down"`, `"group":"UptimeSebi"`)},
{typ: "gorush", cfg: map[string]string{"server_url": "https://push.example", "device_token": "dt", "platform": "android"}, check: one("push.example", "/api/push", `"platform":2`, `"tokens":["dt"]`)},
{typ: "lunasea", cfg: map[string]string{"target": "user", "target_id": "u1"}, check: one("notify.lunasea.app", "/v1/custom/user/u1", "Shop is down")},
{typ: "notifery", cfg: map[string]string{"api_key": "nk"}, check: one("api.notifery.com", "/event", "X-Api-Key: nk", `"code":1`)},
{typ: "notifyapp", cfg: map[string]string{"device_id": "d1", "token": "nt"}, check: one("push.getnotifyapp.com", "/notify-json/d1", "token=nt", `"timeSensitive":true`)},
{typ: "pushdeer", cfg: map[string]string{"push_key": "PDU1"}, reply: `{"code":0}`, check: one("api2.pushdeer.com", "/message/push", `"pushkey":"PDU1"`)},
{typ: "pushplus", cfg: map[string]string{"send_key": "pp"}, reply: `{"code":200}`, check: one("www.pushplus.plus", "/send", `"token":"pp"`)},
{typ: "pushy", cfg: map[string]string{"api_key": "pk", "device_token": "dt"}, check: one("api.pushy.me", "/push", "api_key=pk", `"to":"dt"`)},
{typ: "serverchan", cfg: map[string]string{"send_key": "sctp123tABC"}, check: one("123.push.ft07.com", "/send/sctp123tABC.send", `"title":"Shop is down"`)},
{typ: "signalgrid", cfg: map[string]string{"client_key": "sg", "channel": "ops"}, reply: `{"code":200}`, check: one("api.signalgrid.co", "/v1/push", "client_key=sg", "type=CRIT")},
{typ: "spugpush", cfg: map[string]string{"template_key": "tk"}, check: one("push.spug.cc", "/send/tk", "Shop is down")},
{typ: "techulus", cfg: map[string]string{"api_key": "tk", "channel": "ops"}, check: one("push.techulus.com", "/api/v1/notify/tk", `"channel":"ops"`)},
{typ: "wpush", cfg: map[string]string{"api_key": "wk", "channel": "wechat"}, reply: `{"code":0}`, check: one("api.wpush.cn", "/api/v1/send", `"apikey":"wk"`)},
{typ: "wxpusher", cfg: map[string]string{"spt": "SPT_1, SPT_2"}, reply: `{"code":1000}`, check: one("wxpusher.zjiecode.com", "/api/send/message/simple-push", `"sptList":["SPT_1","SPT_2"]`)},
// SMS and calls.
{typ: "elks46", cfg: map[string]string{"username": "u", "auth_token": "p", "sender": "Uptime", "phone_number": "+4670"}, check: one("api.46elks.com", "/a1/sms", basicAuth("u", "p"), "to=+4670")},
{typ: "aliyunsms", cfg: map[string]string{"access_key_id": "id", "access_key_secret": "sk", "sign_name": "S", "template_code": "T1", "phone_number": "138"}, reply: `{"Code":"OK"}`,
check: func(t *testing.T, calls []call) {
one("dysmsapi.aliyuncs.com", "/", "PhoneNumbers=138", "TemplateCode=T1")(t, calls)
v := calls[0].form()
sig := v.Get("Signature")
v.Del("Signature")
if aliyunSign(v, "sk") != sig || sig == "" {
t.Error("Alibaba Cloud signature does not verify")
}
}},
{typ: "amootsms", cfg: map[string]string{"api_token": "at", "line_number": "9821", "phone_numbers": "0912"}, reply: `{"Status":"Success"}`, check: one("portal.amootsms.com", "/rest/SendSimple", "Authorization: at", "Mobiles=0912")},
{typ: "bearsms", cfg: map[string]string{"username": "u", "hash_key": "h", "phone_number": "88017"}, reply: `{"status":"OK","data":[{"status":"OK"}]}`, check: one("app.bearsms.com", "/index.php", "u=u", "h=h", "to=88017")},
{typ: "cellsynt", cfg: map[string]string{"username": "u", "password": "p", "phone_number": "0046", "sender": "Uptime"}, reply: "OK: abc", check: one("se-1.cellsynt.net", "/sms.php", "destination=0046", "originator=Uptime")},
{typ: "clicksend", cfg: map[string]string{"username": "u", "api_key": "k", "phone_number": "+61"}, reply: `{"data":{"messages":[{"status":"SUCCESS"}]}}`, check: one("rest.clicksend.com", "/v3/sms/send", basicAuth("u", "k"), `"to":"+61"`)},
{typ: "egosms", cfg: map[string]string{"username": "u", "password": "p", "phone_number": "256"}, check: one("www.egosms.co", "/api/v1/plain/", "number=256", "sender=EGOSMS")},
{typ: "freemobile", cfg: map[string]string{"username": "123", "password": "fp"}, check: one("smsapi.free-mobile.fr", "/sendmsg", `"user":"123"`, "msg=Shop is down")},
{typ: "gtxmessaging", cfg: map[string]string{"api_key": "gk", "sender": "Uptime", "phone_number": "49"}, check: one("rest.gtx-messaging.net", "/smsc/sendsms/gk/json", "to=49")},
{typ: "octopush", cfg: map[string]string{"username": "me@x", "api_key": "ok", "phone_number": "+33"}, check: one("api.octopush.com", "/v1/public/sms-campaign/send", "Api-Key: ok", "Api-Login: me@x", `"phone_number":"+33"`)},
{typ: "ooredoo", cfg: map[string]string{"username": "u", "access_key": "ak", "api_token": "bt", "phone_numbers": "7771234, 9607771235"}, reply: `{"response_code":0}`, check: one("o-papi1-lb01.ooredoo.mv", "/bulk_sms/v2", "Bearer bt", "batch=7771234 9607771235")},
{typ: "plivo", cfg: map[string]string{"auth_id": "MA1", "auth_token": "pt", "sender": "+1", "phone_number": "+2"}, check: one("api.plivo.com", "/v1/Account/MA1/Message/", basicAuth("MA1", "pt"), `"dst":"+2"`)},
{typ: "promosms", cfg: map[string]string{"username": "u", "password": "p", "phone_number": "48", "sms_type": "3"}, reply: `{"response":{"status":0}}`, check: one("promosms.com", "/api/rest/v3_2/sms", basicAuth("u", "p"), `"type":3`)},
{typ: "serwersms", cfg: map[string]string{"username": "u", "password": "p", "phone_number": "48"}, reply: `{"success":true}`, check: one("api2.serwersms.pl", "/messages/send_sms", `"phone":"48"`)},
{typ: "sevenio", cfg: map[string]string{"api_key": "sk", "phone_number": "49"}, check: one("gateway.seven.io", "/api/sms", "X-Api-Key: sk", `"to":"49"`)},
{typ: "smsgateway", cfg: map[string]string{"api_url": "http://phone.lan:8080", "api_key": "gk", "phone_numbers": "49"}, reply: `{"status":"sent"}`, check: one("phone.lan:8080", "/api/v1/sms/send", "X-Api-Key: gk")},
{typ: "smsplanet", cfg: map[string]string{"api_token": "st", "sender": "Uptime", "phone_numbers": "48"}, reply: `{"messageId":1}`, check: one("api2.smsplanet.pl", "/sms", "Bearer st", "to=48")},
{typ: "smsc", cfg: map[string]string{"username": "u", "password": "p", "phone_number": "7"}, reply: `{"id":1}`, check: one("smsc.kz", "/sys/send.php", "login=u", "phones=7")},
{typ: "smseagle", cfg: map[string]string{"api_url": "https://eagle.lan", "access_token": "et", "phone_numbers": "48, 49"}, check: one("eagle.lan", "/api/v2/messages/sms", "Access-Token: et", `"to":["48","49"]`)},
{typ: "smsir", cfg: map[string]string{"api_key": "ik", "template_id": "100", "phone_numbers": "09121234567"}, check: one("api.sms.ir", "/v1/send/verify", "X-Api-Key: ik", `"mobile":"9121234567"`, `"templateId":100`)},
{typ: "smsmanager", cfg: map[string]string{"api_key": "mk", "phone_numbers": "420"}, check: one("http-api.smsmanager.cz", "/Send", "apikey=mk", "gateway=high")},
{typ: "smspartner", cfg: map[string]string{"api_key": "pk", "phone_numbers": "33", "sender": "Uptime"}, reply: `{"success":true}`, check: one("api.smspartner.fr", "/v1/send", `"apiKey":"pk"`)},
{typ: "telnyx", cfg: map[string]string{"api_key": "tk", "sender": "+1", "phone_number": "+2"}, check: one("api.telnyx.com", "/v2/messages", "Bearer tk", `"to":"+2"`)},
{typ: "teltonika", cfg: map[string]string{"server_url": "https://192.168.1.1/x", "username": "admin", "password": "rp", "modem": "1-1", "phone_number": "+49"}, reply: `{"success":true,"data":{"token":"tt"}}`,
check: func(t *testing.T, calls []call) {
if len(calls) != 2 || calls[0].Path != "/api/login" || calls[1].Path != "/api/messages/actions/send" || calls[1].Header.Get("Authorization") != "Bearer tt" {
t.Errorf("calls = %+v", calls)
}
}},
{typ: "twilio", cfg: map[string]string{"account_sid": "AC1", "auth_token": "tt", "sender": "+1", "phone_number": "+2"}, check: one("api.twilio.com", "/2010-04-01/Accounts/AC1/Messages.json", basicAuth("AC1", "tt"), "To=+2", "From=+1")},
// Email.
{typ: "brevo", cfg: map[string]string{"api_key": "bk", "from_email": "a@x", "to_email": "b@x, c@x", "cc_email": "d@x"}, check: one("api.brevo.com", "/v3/smtp/email", "Api-Key: bk", `"to":[{"email":"b@x"},{"email":"c@x"}]`, `"cc":[{"email":"d@x"}]`)},
{typ: "resend", cfg: map[string]string{"api_key": "rk", "from_email": "a@x", "to_email": "b@x"}, check: one("api.resend.com", "/emails", "Bearer rk", `"from":"UptimeSebi \u003ca@x\u003e"`, `"subject":"Shop is down"`)},
{typ: "sendgrid", cfg: map[string]string{"api_key": "sg", "from_email": "a@x", "to_email": "b@x", "subject": "Alert"}, check: one("api.sendgrid.com", "/v3/mail/send", "Bearer sg", `"subject":"Alert"`)},
{typ: "turbosmtp", cfg: map[string]string{"consumer_key": "ck", "consumer_secret": "cs", "region": "eu", "from_email": "a@x", "to_email": "b@x, c@x"}, check: one("api.eu.turbo-smtp.com", "/api/v2/mail/send", "Consumerkey: ck", `"to":"b@x,c@x"`)},
{typ: "microsoftgraph", cfg: map[string]string{"tenant_id": "t1", "client_id": "c1", "client_secret": "cs", "mailbox": "alerts@x", "to_email": "b@x"}, reply: `{"access_token":"gt"}`,
check: func(t *testing.T, calls []call) {
if len(calls) != 2 || calls[0].Host != "login.microsoftonline.com" || calls[0].form().Get("client_secret") != "cs" ||
calls[1].Path != "/v1.0/users/alerts@x/sendMail" || calls[1].Header.Get("Authorization") != "Bearer gt" {
t.Errorf("calls = %+v", calls)
}
}},
// Incident management.
{typ: "alerta", cfg: map[string]string{"api_url": "https://alerta.example/api/alert", "api_key": "ak", "environment": "Production"}, check: one("alerta.example", "/api/alert", "Authorization: Key ak", `"resource":"Shop"`, `"severity":"critical"`)},
{typ: "alerta", msg: testResolve, cfg: map[string]string{"api_url": "https://alerta.example/api/alert", "api_key": "ak", "environment": "Production"}, check: one("alerta.example", "/api/alert", `"severity":"normal"`)},
{typ: "alertnow", cfg: map[string]string{"webhook_url": "https://alertnowitgr.opsnow.com/x"}, check: one("alertnowitgr.opsnow.com", "/x", `"status":"open"`, testKey.String())},
{typ: "flashduty", cfg: map[string]string{"integration_key": "fk"}, check: one("api.flashcat.cloud", "/event/push/alert/standard", "integration_key=fk", `"event_status":"Critical"`)},
{typ: "goalert", msg: testResolve, cfg: map[string]string{"server_url": "https://goalert.example", "token": "gt"}, check: one("goalert.example", "/api/v2/generic/incoming", "token=gt", "action=close", "dedup="+testKey.String())},
{typ: "grafanaoncall", cfg: map[string]string{"webhook_url": "https://oncall.example/integrations/v1/formatted_webhook/x/"}, check: one("oncall.example", "/integrations/v1/formatted_webhook/x/", `"state":"alerting"`, `"alert_uid":"`+testKey.String())},
{typ: "heiioncall", msg: testResolve, cfg: map[string]string{"api_key": "hk", "trigger_id": "tr"}, check: one("heiioncall.com", "/triggers/tr/resolve", "Bearer hk")},
{typ: "jsm", cfg: map[string]string{"cloud_id": "cid", "email": "a@x", "api_token": "jt", "priority": "P2"}, check: one("api.atlassian.com", "/jsm/ops/api/cid/v1/alerts", basicAuth("a@x", "jt"), `"alias":"`+testKey.String(), `"priority":"P2"`)},
{typ: "jsm", msg: testResolve, cfg: map[string]string{"cloud_id": "cid", "email": "a@x", "api_token": "jt"}, reply: `{"id":"al1"}`,
check: func(t *testing.T, calls []call) {
if len(calls) != 2 || calls[0].Query.Get("alias") != testKey.String() || calls[1].Path != "/jsm/ops/api/cid/v1/alerts/al1/close" {
t.Errorf("calls = %+v", calls)
}
}},
{typ: "pagertree", msg: testResolve, cfg: map[string]string{"integration_url": "https://api.pagertree.com/integration/int_x"}, check: one("api.pagertree.com", "/integration/int_x", `"event_type":"resolve"`, `"id":"`+testKey.String())},
{typ: "signl4", cfg: map[string]string{"webhook_url": "https://connect.signl4.com/webhook/team"}, check: one("connect.signl4.com", "/webhook/team", `"X-S4-Status":"new"`, `"X-S4-ExternalID":"UptimeSebi-`+testKey.String())},
{typ: "splunk", msg: testResolve, cfg: map[string]string{"rest_url": "https://alert.victorops.com/integrations/generic/20131114/alert/k/route"}, check: one("alert.victorops.com", "/integrations/generic/20131114/alert/k/route", `"message_type":"RECOVERY"`)},
{typ: "squadcast", cfg: map[string]string{"webhook_url": "https://api.squadcast.com/v2/incidents/api/x"}, check: one("api.squadcast.com", "/v2/incidents/api/x", `"status":"trigger"`, `"event_id":"`+testKey.String())},
{typ: "trigv", cfg: map[string]string{"api_key": "tv"}, check: one("api.trigv.com", "/v1/events", "Bearer tv", `"level":"error"`, `"channel":"general"`)},
{typ: "halopsa", cfg: map[string]string{"webhook_url": "https://halo.example/api/webhook", "username": "u", "password": "p"}, check: one("halo.example", "/api/webhook", basicAuth("u", "p"), `"status":"DOWN"`)},
{typ: "flowtriq", cfg: map[string]string{"webhook_url": "https://flowtriq.example/hook", "api_key": "fk"}, check: one("flowtriq.example", "/hook", "X-Api-Key: fk", `"status":"down"`)},
{typ: "keep", cfg: map[string]string{"server_url": "https://keep.example", "api_key": "kk"}, check: one("keep.example", "/alerts/event/uptimekuma", "X-Api-Key: kk", `"status":0`, `"name":"Shop"`)},
{typ: "opsimate", cfg: map[string]string{"server_url": "https://opsimate.example", "api_token": "ot"}, check: one("opsimate.example", "/api/v1/alerts/custom/uptimekuma", "X-Api-Token: ot")},
{typ: "pinglet", cfg: map[string]string{"publish_url": "https://pinglet.example/p/x", "api_key": "pk"}, check: one("pinglet.example", "/p/x", "rewrite=uptimekuma", "Bearer pk")},
}
for i := range cases {
tc := &cases[i]
t.Run(tc.typ, func(t *testing.T) {
current = tc
p, ok := Lookup(tc.typ)
if !ok {
t.Fatalf("unknown provider %s", tc.typ)
}
before := len(calls())
msg := tc.msg
if msg.Event == "" {
msg = testOpened
}
if err := p.Send(context.Background(), tc.cfg, msg, true); err != nil {
t.Fatalf("Send: %v", err)
}
tc.check(t, calls()[before:])
})
}
// Every provider is exercised here or in TestProviders.
tested := map[string]bool{"slack": true, "discord": true, "teams": true, "googlechat": true, "mattermost": true, "rocketchat": true,
"telegram": true, "matrix": true, "ntfy": true, "gotify": true, "pushover": true, "pushbullet": true, "signal": true,
"pagerduty": true, "opsgenie": true, "apprise": true, "nostr": true}
for _, tc := range cases {
tested[tc.typ] = true
}
for _, p := range Providers {
if !tested[p.Type] {
t.Errorf("%s has no test", p.Type)
}
}
}
// Services that answer 200 to failed requests are reported as failed.
func TestServicesReportRefusals(t *testing.T) {
var reply string
services(t, func(call) (int, string) { return http.StatusOK, reply })
for typ, tc := range map[string]struct {
cfg map[string]string
reply string
want string
}{
"dingtalk": {map[string]string{"webhook_url": "https://oapi.dingtalk.com/robot/send?access_token=x"}, `{"errcode":310000,"errmsg":"keywords not in content"}`, "keywords not in content"},
"vk": {map[string]string{"access_token": "x", "peer_id": "1"}, `{"error":{"error_code":5,"error_msg":"User authorization failed"}}`, "User authorization failed"},
"clicksend": {map[string]string{"username": "u", "api_key": "k", "phone_number": "1"}, `{"data":{"messages":[{"status":"INVALID_RECIPIENT"}]}}`, "INVALID_RECIPIENT"},
"cellsynt": {map[string]string{"username": "u", "password": "p", "phone_number": "1", "sender": "x"}, "Error: Invalid username", "Invalid username"},
"wxpusher": {map[string]string{"spt": "x"}, `{"code":1001,"msg":"spt invalid"}`, "spt invalid"},
} {
reply = tc.reply
p, _ := Lookup(typ)
if err := p.Send(context.Background(), tc.cfg, testOpened, true); err == nil || !strings.Contains(err.Error(), tc.want) {
t.Errorf("%s: err = %v, want %q", typ, err, tc.want)
}
}
}
func TestNostr(t *testing.T) {
senderSK, recipientSK := nostr.GeneratePrivateKey(), nostr.GeneratePrivateKey()
nsec, _ := nip19.EncodePrivateKey(senderSK)
recipientPub, _ := nostr.GetPublicKey(recipientSK)
npub, _ := nip19.EncodePublicKey(recipientPub)
got := make(chan nostr.Event, 1)
relay := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
conn, err := websocket.Accept(w, r, nil)
if err != nil {
return
}
defer func() { _ = conn.CloseNow() }()
_, data, err := conn.Read(r.Context())
if err != nil {
return
}
var msg []json.RawMessage
var e nostr.Event
if json.Unmarshal(data, &msg) != nil || len(msg) != 2 || json.Unmarshal(msg[1], &e) != nil {
return
}
ok, _ := e.CheckSignature()
reply, _ := json.Marshal([]any{"OK", e.ID, ok, ""})
_ = conn.Write(r.Context(), websocket.MessageText, reply)
got <- e
_, _, _ = conn.Read(r.Context())
}))
t.Cleanup(relay.Close)
services(t, func(call) (int, string) { return http.StatusNotFound, "" })
old := transport
transport = func(*net.Dialer) http.RoundTripper { return http.DefaultTransport }
t.Cleanup(func() { transport = old })
p, _ := Lookup("nostr")
cfg := map[string]string{"sender_nsec": nsec, "recipients": npub, "relays": "ws://" + strings.TrimPrefix(relay.URL, "http://")}
if err := p.Send(context.Background(), cfg, testOpened, true); err != nil {
t.Fatalf("Send: %v", err)
}
wrap := <-got
if wrap.Kind != nostr.KindGiftWrap {
t.Fatalf("kind = %d, want gift wrap", wrap.Kind)
}
rumor, err := nip59.GiftUnwrap(wrap, func(otherPub, ciphertext string) (string, error) {
key, err := nip44.GenerateConversationKey(otherPub, recipientSK)
if err != nil {
return "", err
}
return nip44.Decrypt(ciphertext, key)
})
if err != nil || !strings.Contains(rumor.Content, "Shop is down") || rumor.Kind != nostr.KindDirectMessage {
t.Errorf("unwrapped = %+v, %v", rumor, err)
}
cfg["sender_nsec"] = npub
if err := p.Send(context.Background(), cfg, testOpened, true); err == nil {
t.Error("a public key accepted as sender")
}
}