feat(api): open incidents and notify channels when monitors go down
Results are evaluated as they arrive. Transitions open or resolve the monitor's incident and queue a notification per enabled channel in the same transaction; every API replica delivers the outbox with leases and exponential retries. Organizations manage webhook and email channels, can send test notifications and list incidents. Email requires UPTIME_SMTP_URL. Closes #14 Closes #15 Closes #16 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
01ef543e62
commit
5f42e3e650
12 files changed
+822
-13
No files matched your search
+13
-9
@@ -187,18 +187,20 @@ func (s *Server) agentResults(c *gin.Context) {
|
||||
ids[i] = r.MonitorID
|
||||
}
|
||||
now := time.Now()
|
||||
monitors := map[uuid.UUID]store.MonitorsForResultsRow{}
|
||||
var accepted []agentapi.Result
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
monitors, err := q.MonitorsForJobs(ctx, store.MonitorsForJobsParams{Region: region, Ids: ids})
|
||||
rows, err := q.MonitorsForResults(ctx, store.MonitorsForResultsParams{Region: region, Ids: ids})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
orgOf := make(map[uuid.UUID]uuid.UUID, len(monitors))
|
||||
for _, m := range monitors {
|
||||
orgOf[m.ID] = m.OrgID
|
||||
for _, m := range rows {
|
||||
monitors[m.ID] = m
|
||||
}
|
||||
rows := make([]store.InsertCheckResultsParams, 0, len(req.Results))
|
||||
params := make([]store.InsertCheckResultsParams, 0, len(req.Results))
|
||||
for _, r := range req.Results {
|
||||
org, ok := orgOf[r.MonitorID]
|
||||
m, ok := monitors[r.MonitorID]
|
||||
org := m.OrgID
|
||||
// A checker may only report monitors of its own region, and
|
||||
// timestamps far from now are rejected rather than skewing
|
||||
// history.
|
||||
@@ -215,18 +217,20 @@ func (s *Server) agentResults(c *gin.Context) {
|
||||
if r.Error != "" {
|
||||
row.Error = ptr(truncateValid(r.Error, 500))
|
||||
}
|
||||
rows = append(rows, row)
|
||||
params = append(params, row)
|
||||
accepted = append(accepted, r)
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
if len(params) == 0 {
|
||||
return nil
|
||||
}
|
||||
_, err = q.InsertCheckResults(ctx, rows)
|
||||
_, err = q.InsertCheckResults(ctx, params)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
s.evaluateResults(ctx, region, accepted, monitors)
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/evaluate"
|
||||
"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/tenant"
|
||||
)
|
||||
|
||||
const (
|
||||
maxNotifyAttempts = 10
|
||||
notifyBatch = 20
|
||||
)
|
||||
|
||||
// evaluateResults feeds stored results to the evaluator in time order and
|
||||
// acts on the resulting transitions.
|
||||
func (s *Server) evaluateResults(ctx context.Context, region string, results []agentapi.Result, monitors map[uuid.UUID]store.MonitorsForResultsRow) {
|
||||
slices.SortFunc(results, func(a, b agentapi.Result) int { return a.StartedAt.Compare(b.StartedAt) })
|
||||
for _, r := range results {
|
||||
m, ok := monitors[r.MonitorID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
t, err := s.eval.Observe(ctx, evaluate.Observation{
|
||||
MonitorID: m.ID, Region: region, OK: r.OK, At: r.StartedAt,
|
||||
Interval: time.Duration(m.IntervalSeconds) * time.Second, Confirmations: int(m.Confirmations), Regions: m.Regions,
|
||||
})
|
||||
if err == nil && t != evaluate.None {
|
||||
err = s.transition(ctx, m, t, r.StartedAt)
|
||||
}
|
||||
if err != nil {
|
||||
// The next result re-evaluates; a missed transition only delays
|
||||
// the alert by one interval.
|
||||
s.log.ErrorContext(ctx, "evaluating result failed", "monitor", m.ID, "error", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// transition opens or resolves the monitor's incident and queues a
|
||||
// notification for every enabled channel of the org, in one transaction.
|
||||
func (s *Server) transition(ctx context.Context, m store.MonitorsForResultsRow, t evaluate.Transition, at time.Time) error {
|
||||
return s.db.Tx(ctx, tenant.Org(m.OrgID, uuid.Nil), func(q *store.Queries) error {
|
||||
var (
|
||||
inc store.Incident
|
||||
event string
|
||||
err error
|
||||
)
|
||||
switch t {
|
||||
case evaluate.Down:
|
||||
cause := map[string]string{}
|
||||
latest, lerr := q.LatestResultsForMonitor(ctx, store.LatestResultsForMonitorParams{OrgID: m.OrgID, MonitorID: m.ID})
|
||||
if lerr != nil {
|
||||
return lerr
|
||||
}
|
||||
for _, l := range latest {
|
||||
if !l.Ok {
|
||||
cause[l.Region] = deref(l.Error)
|
||||
}
|
||||
}
|
||||
raw, _ := json.Marshal(cause)
|
||||
inc, err = q.OpenIncident(ctx, store.OpenIncidentParams{OrgID: m.OrgID, MonitorID: m.ID, StartedAt: at, Cause: raw})
|
||||
event = notify.Opened
|
||||
case evaluate.Up:
|
||||
inc, err = q.ResolveIncident(ctx, store.ResolveIncidentParams{MonitorID: m.ID, ResolvedAt: &at})
|
||||
event = notify.Resolved
|
||||
}
|
||||
// No row means the incident already exists or is already resolved,
|
||||
// e.g. after the evaluation state was lost; nothing to announce.
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
channels, err := q.ListEnabledChannelIDs(ctx, m.OrgID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, ch := range channels {
|
||||
if err := q.EnqueueNotification(ctx, store.EnqueueNotificationParams{OrgID: m.OrgID, ChannelID: ch, IncidentID: inc.ID, Event: event}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
s.log.InfoContext(ctx, "incident "+event, "monitor", m.ID, "incident", inc.ID, "channels", len(channels))
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// RunNotifier delivers queued notifications until ctx ends. Every API replica
|
||||
// runs it; rows are leased so each is sent by one replica at a time.
|
||||
func (s *Server) RunNotifier(ctx context.Context) {
|
||||
tick := time.NewTicker(2 * time.Second)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
for s.deliverBatch(ctx) == notifyBatch && ctx.Err() == nil {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) deliverBatch(ctx context.Context) int {
|
||||
var rows []store.NotificationDetailsRow
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
ids, err := q.ClaimNotifications(ctx, notifyBatch)
|
||||
if err != nil || len(ids) == 0 {
|
||||
return err
|
||||
}
|
||||
rows, err = q.NotificationDetails(ctx, ids)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
if ctx.Err() == nil {
|
||||
s.log.WarnContext(ctx, "claiming notifications failed", "error", err)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
for _, n := range rows {
|
||||
sendErr := s.send(ctx, n.ChannelType, n.ChannelConfig, eventOf(n))
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
if sendErr == nil {
|
||||
return q.MarkNotificationSent(ctx, n.ID)
|
||||
}
|
||||
return q.MarkNotificationFailed(ctx, store.MarkNotificationFailedParams{
|
||||
ID: n.ID, LastError: ptr(truncateValid(sendErr.Error(), 500)), MaxAttempts: maxNotifyAttempts,
|
||||
RetryInSeconds: int32(retryDelay(int(n.Attempts)).Seconds()),
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "recording notification result failed", "notification", n.ID, "error", err)
|
||||
}
|
||||
if sendErr != nil {
|
||||
s.log.WarnContext(ctx, "notification failed", "notification", n.ID, "channel", n.ChannelID, "attempt", n.Attempts+1, "error", sendErr)
|
||||
}
|
||||
}
|
||||
return len(rows)
|
||||
}
|
||||
|
||||
// retryDelay grows from 30 s to about four hours over ten attempts.
|
||||
func retryDelay(attempts int) time.Duration {
|
||||
return min(30*time.Second<<attempts, 4*time.Hour)
|
||||
}
|
||||
|
||||
func eventOf(n store.NotificationDetailsRow) notify.Event {
|
||||
ev := notify.Event{
|
||||
Kind: n.Event, IncidentID: n.IncidentID, StartedAt: n.StartedAt, ResolvedAt: n.ResolvedAt,
|
||||
Monitor: notify.Monitor{ID: n.MonitorID, Name: n.MonitorName, Type: n.MonitorType, Target: n.MonitorTarget},
|
||||
}
|
||||
_ = json.Unmarshal(n.Cause, &ev.Cause)
|
||||
return ev
|
||||
}
|
||||
|
||||
// webhookConfig is stored for webhook channels; Secret is sealed.
|
||||
type webhookConfig struct {
|
||||
URL string `json:"url"`
|
||||
Secret string `json:"secret"`
|
||||
}
|
||||
|
||||
// emailConfig is stored for email channels.
|
||||
type emailConfig struct {
|
||||
To []string `json:"to"`
|
||||
Locale string `json:"locale"`
|
||||
}
|
||||
|
||||
var errMailDisabled = errors.New("email is not configured on this server (UPTIME_SMTP_URL)")
|
||||
|
||||
func (s *Server) send(ctx context.Context, typ string, config []byte, ev notify.Event) error {
|
||||
switch typ {
|
||||
case "webhook":
|
||||
var c webhookConfig
|
||||
if err := json.Unmarshal(config, &c); err != nil {
|
||||
return err
|
||||
}
|
||||
sealedSecret, err := base64.StdEncoding.DecodeString(c.Secret)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
secret, err := s.keys.Open(sealedSecret, []byte(c.URL))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return notify.Webhook{URL: c.URL, Secret: secret, AllowPrivate: !s.cloud()}.Send(ctx, ev)
|
||||
case "email":
|
||||
if s.smtp == nil {
|
||||
return errMailDisabled
|
||||
}
|
||||
var c emailConfig
|
||||
if err := json.Unmarshal(config, &c); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.smtp.Send(ctx, s.mailFor(ev, c.To, c.Locale))
|
||||
}
|
||||
return fmt.Errorf("unknown channel type %q", typ)
|
||||
}
|
||||
|
||||
func (s *Server) mailFor(ev notify.Event, to []string, locale string) notify.Mail {
|
||||
l := s.catalog.Match(locale)
|
||||
data := map[string]any{
|
||||
"Monitor": ev.Monitor.Name,
|
||||
"Target": ev.Monitor.Target,
|
||||
"Since": ev.StartedAt.UTC().Format("2006-01-02 15:04 MST"),
|
||||
}
|
||||
var cause []string
|
||||
for region, msg := range ev.Cause {
|
||||
cause = append(cause, region+": "+msg)
|
||||
}
|
||||
slices.Sort(cause)
|
||||
data["Cause"] = strings.Join(cause, "\n")
|
||||
if ev.ResolvedAt != nil {
|
||||
data["Duration"] = ev.ResolvedAt.Sub(ev.StartedAt).Round(time.Second).String()
|
||||
}
|
||||
return notify.Mail{
|
||||
To: to,
|
||||
Subject: l.T("email."+ev.Kind+".subject", data),
|
||||
Body: l.T("email."+ev.Kind+".body", data),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify/notifytest"
|
||||
)
|
||||
|
||||
// receiver records verified webhook deliveries.
|
||||
type receiver struct {
|
||||
srv *httptest.Server
|
||||
secret atomic.Value
|
||||
mu sync.Mutex
|
||||
events []notify.Event
|
||||
forged int
|
||||
}
|
||||
|
||||
func newReceiver(t *testing.T) *receiver {
|
||||
r := &receiver{}
|
||||
r.secret.Store("")
|
||||
r.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||
body, _ := io.ReadAll(req.Body)
|
||||
ts, _ := strconv.ParseInt(req.Header.Get(notify.TimestampHeader), 10, 64)
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if req.Header.Get(notify.SignatureHeader) != notify.Sign([]byte(r.secret.Load().(string)), body, ts) {
|
||||
r.forged++
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
var ev notify.Event
|
||||
_ = json.Unmarshal(body, &ev)
|
||||
r.events = append(r.events, ev)
|
||||
}))
|
||||
t.Cleanup(r.srv.Close)
|
||||
return r
|
||||
}
|
||||
|
||||
func (r *receiver) kinds() []string {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
var out []string
|
||||
for _, e := range r.events {
|
||||
out = append(out, e.Kind)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestAlerting(t *testing.T) {
|
||||
mail := notifytest.NewSMTP(t)
|
||||
e := newEnvWith(t, func(c *config.API) { c.SMTPURL = mail.URL() })
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
go e.api.RunScheduler(ctx)
|
||||
go e.api.RunNotifier(ctx)
|
||||
|
||||
var healthy atomic.Bool
|
||||
healthy.Store(true)
|
||||
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
if !healthy.Load() {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
}
|
||||
}))
|
||||
defer target.Close()
|
||||
|
||||
eu, us := uniq("eu-"), uniq("us-")
|
||||
e.startChecker(t, e.agentToken(t, eu))
|
||||
e.startChecker(t, e.agentToken(t, us))
|
||||
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("a")+".test", uniq("alert-"))
|
||||
|
||||
hook := newReceiver(t)
|
||||
st, body := owner.do("POST", "/api/v1/org/channels", map[string]any{"name": "Ops hook", "type": "webhook", "url": hook.srv.URL})
|
||||
if st != http.StatusCreated || body["signing_secret"] == "" {
|
||||
t.Fatalf("create webhook channel = %d %v", st, body)
|
||||
}
|
||||
hook.secret.Store(body["signing_secret"].(string))
|
||||
hookID := body["channel"].(map[string]any)["id"].(string)
|
||||
|
||||
st, body = owner.do("POST", "/api/v1/org/channels", map[string]any{"name": "Ops mail", "type": "email", "to": []string{"ops@example.test"}, "locale": "de"})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create email channel = %d %v", st, body)
|
||||
}
|
||||
|
||||
st, body = owner.do("POST", "/api/v1/org/channels/"+hookID+"/test", nil)
|
||||
if st != http.StatusNoContent || len(hook.kinds()) != 1 || hook.kinds()[0] != notify.Test {
|
||||
t.Fatalf("test webhook = %d %v, received %v", st, body, hook.kinds())
|
||||
}
|
||||
|
||||
st, body = owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "Shop", "type": "http", "target": target.URL, "interval_seconds": 10, "confirmations": 1, "regions": []string{eu, us},
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create monitor = %d %v", st, body)
|
||||
}
|
||||
monitorID := body["id"].(string)
|
||||
waitFor(t, 10*time.Second, "first healthy results", func() bool {
|
||||
_, body := owner.do("GET", "/api/v1/org/monitors", nil)
|
||||
return len(body["monitors"].([]any)[0].(map[string]any)["latest"].([]any)) == 2
|
||||
})
|
||||
|
||||
healthy.Store(false)
|
||||
waitFor(t, 20*time.Second, "incident opened and announced", func() bool {
|
||||
return len(hook.kinds()) == 2 && len(mail.Messages()) == 1
|
||||
})
|
||||
_, body = owner.do("GET", "/api/v1/org/incidents", nil)
|
||||
incidents := body["incidents"].([]any)
|
||||
if len(incidents) != 1 {
|
||||
t.Fatalf("incidents = %v, want one", incidents)
|
||||
}
|
||||
inc := incidents[0].(map[string]any)
|
||||
if inc["monitor_id"] != monitorID || inc["resolved_at"] != nil || len(inc["cause"].(map[string]any)) != 2 {
|
||||
t.Errorf("open incident = %v, want unresolved with a cause per region", inc)
|
||||
}
|
||||
if msg := mail.Messages()[0].Data; !strings.Contains(msg, "Subject: [DOWN] Shop") || !strings.Contains(msg, "ist in allen Regionen nicht erreichbar") {
|
||||
t.Errorf("down mail = %q, want German down notice", msg)
|
||||
}
|
||||
|
||||
healthy.Store(true)
|
||||
waitFor(t, 20*time.Second, "incident resolved and announced", func() bool {
|
||||
return len(hook.kinds()) == 3 && len(mail.Messages()) == 2
|
||||
})
|
||||
if got := strings.Join(hook.kinds(), ","); got != "test,opened,resolved" {
|
||||
t.Errorf("webhook events = %s, want test,opened,resolved", got)
|
||||
}
|
||||
_, body = owner.do("GET", "/api/v1/org/incidents", nil)
|
||||
if inc := body["incidents"].([]any)[0].(map[string]any); inc["resolved_at"] == nil {
|
||||
t.Errorf("incident after recovery = %v, want resolved", inc)
|
||||
}
|
||||
if hook.forged != 0 {
|
||||
t.Errorf("receiver saw %d requests with bad signatures", hook.forged)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmailChannelNeedsSMTP(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("m")+".test", uniq("mail-"))
|
||||
st, body := owner.do("POST", "/api/v1/org/channels", map[string]any{"name": "x", "type": "email", "to": []string{"a@b.test"}})
|
||||
expect(t, "email channel without smtp", st, body, http.StatusUnprocessableEntity, "email_not_configured")
|
||||
st, body = owner.do("POST", "/api/v1/org/channels", map[string]any{"name": "x", "type": "webhook", "url": "ftp://x"})
|
||||
expect(t, "webhook with bad url", st, body, http.StatusUnprocessableEntity, "invalid_webhook_url")
|
||||
}
|
||||
|
||||
// TestLostEvaluationStateDoesNotDuplicateIncidents simulates Redis losing
|
||||
// the evaluation state while an incident is open: the next failure tries to
|
||||
// open the incident again, which must neither fail nor notify twice.
|
||||
func TestLostEvaluationStateDoesNotDuplicateIncidents(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
go e.api.RunScheduler(ctx)
|
||||
go e.api.RunNotifier(ctx)
|
||||
|
||||
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}))
|
||||
defer target.Close()
|
||||
region := uniq("eu-")
|
||||
e.startChecker(t, e.agentToken(t, region))
|
||||
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("l")+".test", uniq("lost-"))
|
||||
hook := newReceiver(t)
|
||||
_, body := owner.do("POST", "/api/v1/org/channels", map[string]any{"name": "hook", "type": "webhook", "url": hook.srv.URL})
|
||||
hook.secret.Store(body["signing_secret"].(string))
|
||||
_, body = owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "Down", "type": "http", "target": target.URL, "interval_seconds": 10, "confirmations": 1, "regions": []string{region},
|
||||
})
|
||||
monitorID := body["id"].(string)
|
||||
|
||||
waitFor(t, 10*time.Second, "incident announced", func() bool { return len(hook.kinds()) == 1 })
|
||||
if err := e.rdb.Del(context.Background(), "eval:"+monitorID).Err(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Wait for the next run, which sees a fresh state and transitions again.
|
||||
time.Sleep(12 * time.Second)
|
||||
_, body = owner.do("GET", "/api/v1/org/incidents", nil)
|
||||
if n := len(body["incidents"].([]any)); n != 1 {
|
||||
t.Errorf("incidents = %d, want 1", n)
|
||||
}
|
||||
if got := hook.kinds(); len(got) != 1 {
|
||||
t.Errorf("webhook events = %v, want a single opened", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/mail"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
)
|
||||
|
||||
type channelRequest struct {
|
||||
Name string `json:"name" binding:"required,max=100"`
|
||||
Type string `json:"type" binding:"required,oneof=webhook email"`
|
||||
URL string `json:"url" binding:"max=2000"`
|
||||
To []string `json:"to" binding:"max=20,dive,max=320"`
|
||||
Locale string `json:"locale" binding:"max=10"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
|
||||
type channelView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Enabled bool `json:"enabled"`
|
||||
URL string `json:"url,omitempty"`
|
||||
To []string `json:"to,omitempty"`
|
||||
Locale string `json:"locale,omitempty"`
|
||||
}
|
||||
|
||||
func viewChannel(ch store.NotificationChannel) channelView {
|
||||
v := channelView{ID: ch.ID, Name: ch.Name, Type: ch.Type, Enabled: ch.Enabled}
|
||||
switch ch.Type {
|
||||
case "webhook":
|
||||
var c webhookConfig
|
||||
_ = json.Unmarshal(ch.Config, &c)
|
||||
v.URL = c.URL
|
||||
case "email":
|
||||
var c emailConfig
|
||||
_ = json.Unmarshal(ch.Config, &c)
|
||||
v.To, v.Locale = c.To, c.Locale
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// channelConfig validates req and builds the stored config. For webhooks a
|
||||
// new signing secret is created unless previous holds one for the same URL;
|
||||
// the plain secret is returned only when it is new.
|
||||
func (s *Server) channelConfig(req *channelRequest, previous []byte) (config []byte, newSecret, code string) {
|
||||
req.Name = strings.TrimSpace(req.Name)
|
||||
if req.Name == "" {
|
||||
return nil, "", "invalid_input"
|
||||
}
|
||||
switch req.Type {
|
||||
case "webhook":
|
||||
u, err := url.Parse(strings.TrimSpace(req.URL))
|
||||
if err != nil || u.Host == "" || u.User != nil || (u.Scheme != "https" && (s.cloud() || u.Scheme != "http")) {
|
||||
return nil, "", "invalid_webhook_url"
|
||||
}
|
||||
req.URL = u.String()
|
||||
var secret []byte
|
||||
if previous != nil {
|
||||
var old webhookConfig
|
||||
if json.Unmarshal(previous, &old) == nil {
|
||||
if sealedOld, err := base64.StdEncoding.DecodeString(old.Secret); err == nil {
|
||||
secret, _ = s.keys.Open(sealedOld, []byte(old.URL))
|
||||
}
|
||||
}
|
||||
}
|
||||
if secret == nil {
|
||||
b := make([]byte, 32)
|
||||
_, _ = rand.Read(b)
|
||||
secret = []byte(hex.EncodeToString(b))
|
||||
newSecret = string(secret)
|
||||
}
|
||||
// The secret is bound to the URL so a copied config row cannot be
|
||||
// pointed at another receiver with the same secret.
|
||||
sealedSecret := s.keys.Seal(secret, []byte(req.URL))
|
||||
config, _ = json.Marshal(webhookConfig{URL: req.URL, Secret: base64.StdEncoding.EncodeToString(sealedSecret)})
|
||||
return config, newSecret, ""
|
||||
case "email":
|
||||
if s.smtp == nil {
|
||||
return nil, "", "email_not_configured"
|
||||
}
|
||||
if len(req.To) == 0 {
|
||||
return nil, "", "invalid_email"
|
||||
}
|
||||
for i, to := range req.To {
|
||||
to = normalizeEmail(to)
|
||||
if a, err := mail.ParseAddress(to); err != nil || a.Address != to {
|
||||
return nil, "", "invalid_email"
|
||||
}
|
||||
req.To[i] = to
|
||||
}
|
||||
if req.Locale == "" || !s.catalog.IsSupported(req.Locale) {
|
||||
req.Locale = "en"
|
||||
}
|
||||
config, _ = json.Marshal(emailConfig{To: req.To, Locale: req.Locale})
|
||||
return config, "", ""
|
||||
}
|
||||
return nil, "", "invalid_input"
|
||||
}
|
||||
|
||||
func (s *Server) listChannels(c *gin.Context) {
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var rows []store.NotificationChannel
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListChannels(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
out := make([]channelView, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = viewChannel(r)
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"channels": out, "email_available": s.smtp != nil})
|
||||
}
|
||||
|
||||
func (s *Server) createChannel(c *gin.Context) {
|
||||
var req channelRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
config, secret, code := s.channelConfig(&req, nil)
|
||||
if code != "" {
|
||||
fail(c, http.StatusUnprocessableEntity, code)
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var row store.NotificationChannel
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
row, err = q.CreateChannel(ctx, store.CreateChannelParams{
|
||||
OrgID: p.Org.ID, Name: req.Name, Type: req.Type, Config: config, Enabled: req.Enabled == nil || *req.Enabled,
|
||||
})
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, gin.H{"channel": viewChannel(row), "signing_secret": secret})
|
||||
}
|
||||
|
||||
func (s *Server) updateChannel(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
var req channelRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var (
|
||||
row store.NotificationChannel
|
||||
secret string
|
||||
code string
|
||||
)
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
old, err := q.GetChannel(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if old.Type != req.Type {
|
||||
code = "channel_type_immutable"
|
||||
return nil
|
||||
}
|
||||
var config []byte
|
||||
config, secret, code = s.channelConfig(&req, old.Config)
|
||||
if code != "" {
|
||||
return nil
|
||||
}
|
||||
row, err = q.UpdateChannel(ctx, store.UpdateChannelParams{ID: id, Name: req.Name, Config: config, Enabled: req.Enabled == nil || *req.Enabled})
|
||||
return err
|
||||
})
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
case err != nil:
|
||||
internalError(c, err)
|
||||
case code != "":
|
||||
fail(c, http.StatusUnprocessableEntity, code)
|
||||
default:
|
||||
c.JSON(http.StatusOK, gin.H{"channel": viewChannel(row), "signing_secret": secret})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) deleteChannel(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var n int64
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
n, err = q.DeleteChannel(ctx, id)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if n == 0 {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// testChannel sends a sample event right away so users can verify their
|
||||
// receiver; the error is returned to the user.
|
||||
func (s *Server) testChannel(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
if !s.limit(c, "channel_test:"+id.String(), 10, time.Minute) {
|
||||
return
|
||||
}
|
||||
var ch store.NotificationChannel
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
ch, err = q.GetChannel(ctx, id)
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
ev := notify.Event{
|
||||
Kind: notify.Test, IncidentID: uuid.Nil, StartedAt: time.Now(),
|
||||
Monitor: notify.Monitor{Name: "Example monitor", Type: "http", Target: "https://example.com"},
|
||||
}
|
||||
if err := s.send(ctx, ch.Type, ch.Config, ev); err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusBadGateway, gin.H{
|
||||
"error": "channel_test_failed", "message": truncateValid(err.Error(), 300),
|
||||
})
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
type incidentView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
MonitorID uuid.UUID `json:"monitor_id"`
|
||||
MonitorName string `json:"monitor_name"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
ResolvedAt *time.Time `json:"resolved_at"`
|
||||
Cause map[string]string `json:"cause"`
|
||||
}
|
||||
|
||||
func (s *Server) listIncidents(c *gin.Context) {
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var rows []store.ListIncidentsRow
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListIncidents(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
out := make([]incidentView, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = incidentView{ID: r.ID, MonitorID: r.MonitorID, MonitorName: r.MonitorName, StartedAt: r.StartedAt, ResolvedAt: r.ResolvedAt}
|
||||
_ = json.Unmarshal(r.Cause, &out[i].Cause)
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"incidents": out})
|
||||
}
|
||||
@@ -28,6 +28,9 @@ type monitorRequest struct {
|
||||
Config json.RawMessage `json:"config"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
Regions []string `json:"regions" binding:"required,min=1,max=50"`
|
||||
// Confirmations is how many failures in a row make a region count as
|
||||
// down; 0 keeps the default of 2.
|
||||
Confirmations int `json:"confirmations" binding:"min=0,max=10"`
|
||||
}
|
||||
|
||||
type latestView struct {
|
||||
@@ -48,6 +51,7 @@ type monitorView struct {
|
||||
TimeoutMS int32 `json:"timeout_ms"`
|
||||
Config json.RawMessage `json:"config"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Confirmations int32 `json:"confirmations"`
|
||||
Regions []string `json:"regions"`
|
||||
Latest []latestView `json:"latest"`
|
||||
}
|
||||
@@ -55,7 +59,7 @@ type monitorView struct {
|
||||
func viewMonitor(m store.Monitor, regions []string) monitorView {
|
||||
return monitorView{
|
||||
ID: m.ID, Name: m.Name, Type: m.Type, Target: m.Target, IntervalSeconds: m.IntervalSeconds,
|
||||
TimeoutMS: m.TimeoutMs, Config: m.Config, Enabled: m.Enabled, Regions: regions, Latest: []latestView{},
|
||||
TimeoutMS: m.TimeoutMs, Config: m.Config, Enabled: m.Enabled, Confirmations: m.Confirmations, Regions: regions, Latest: []latestView{},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,6 +84,9 @@ func (s *Server) validateMonitor(c *gin.Context, req *monitorRequest) bool {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_interval", "Min", s.minInterval())
|
||||
return false
|
||||
}
|
||||
if req.Confirmations == 0 {
|
||||
req.Confirmations = 2
|
||||
}
|
||||
if req.TimeoutMS == 0 {
|
||||
req.TimeoutMS = min(10000, req.IntervalSeconds*1000/2)
|
||||
}
|
||||
@@ -176,7 +183,7 @@ func (s *Server) createMonitor(c *gin.Context) {
|
||||
m, err = q.CreateMonitor(ctx, store.CreateMonitorParams{
|
||||
OrgID: p.Org.ID, Name: req.Name, Type: req.Type, Target: req.Target,
|
||||
IntervalSeconds: int32(req.IntervalSeconds), TimeoutMs: int32(req.TimeoutMS),
|
||||
Config: req.Config, Enabled: req.Enabled == nil || *req.Enabled,
|
||||
Config: req.Config, Enabled: req.Enabled == nil || *req.Enabled, Confirmations: int32(req.Confirmations),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -241,7 +248,7 @@ func (s *Server) updateMonitor(c *gin.Context) {
|
||||
m, err = q.UpdateMonitor(ctx, store.UpdateMonitorParams{
|
||||
ID: id, Name: req.Name, Type: req.Type, Target: req.Target,
|
||||
IntervalSeconds: int32(req.IntervalSeconds), TimeoutMs: int32(req.TimeoutMS),
|
||||
Config: req.Config, Enabled: req.Enabled == nil || *req.Enabled,
|
||||
Config: req.Config, Enabled: req.Enabled == nil || *req.Enabled, Confirmations: int32(req.Confirmations),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -295,6 +302,7 @@ func (s *Server) deleteMonitor(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
_ = s.eval.Forget(ctx, id)
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,9 @@ import (
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/evaluate"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/requestid"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/schedule"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/sealed"
|
||||
@@ -38,6 +40,8 @@ type Server struct {
|
||||
totp *auth.TOTPVerifier
|
||||
sso *sso.Client
|
||||
sched *schedule.Scheduler
|
||||
eval *evaluate.Evaluator
|
||||
smtp *notify.SMTP
|
||||
}
|
||||
|
||||
// Deps are the external resources a Server needs.
|
||||
@@ -50,9 +54,13 @@ type Deps struct {
|
||||
}
|
||||
|
||||
// New returns a Server. It does not register any routes; see Mount.
|
||||
// cfg must have passed Validate.
|
||||
func New(cfg config.API, d Deps) *Server {
|
||||
allowPrivate := cfg.SSOAllowPrivate()
|
||||
mail, _ := notify.ParseSMTP(cfg.SMTPURL)
|
||||
return &Server{
|
||||
eval: evaluate.New(d.Redis),
|
||||
smtp: mail,
|
||||
cfg: cfg,
|
||||
log: d.Log,
|
||||
db: d.DB,
|
||||
@@ -105,6 +113,14 @@ func (s *Server) Mount(r gin.IRouter) {
|
||||
org.PUT("/monitors/:id", can(authz.MonitorsWrite), s.updateMonitor)
|
||||
org.DELETE("/monitors/:id", can(authz.MonitorsWrite), s.deleteMonitor)
|
||||
|
||||
org.GET("/incidents", can(authz.IncidentsRead), s.listIncidents)
|
||||
|
||||
org.GET("/channels", can(authz.NotificationsRead), s.listChannels)
|
||||
org.POST("/channels", can(authz.NotificationsWrite), s.createChannel)
|
||||
org.PUT("/channels/:id", can(authz.NotificationsWrite), s.updateChannel)
|
||||
org.DELETE("/channels/:id", can(authz.NotificationsWrite), s.deleteChannel)
|
||||
org.POST("/channels/:id/test", can(authz.NotificationsWrite), s.testChannel)
|
||||
|
||||
org.GET("/sso", can(authz.OrgManage), s.listSSOProviders)
|
||||
org.POST("/sso", sessionOnly(), can(authz.OrgManage), s.createSSOProvider)
|
||||
org.PUT("/sso/:id", sessionOnly(), can(authz.OrgManage), s.updateSSOProvider)
|
||||
|
||||
@@ -34,10 +34,17 @@ import (
|
||||
type env struct {
|
||||
srv *httptest.Server
|
||||
dbPool *pgxpool.Pool
|
||||
rdb *redis.Client
|
||||
api *api.Server
|
||||
}
|
||||
|
||||
func newEnv(t *testing.T) *env {
|
||||
t.Helper()
|
||||
return newEnvWith(t, nil)
|
||||
}
|
||||
|
||||
// newEnvWith lets a test adjust the API configuration before start.
|
||||
func newEnvWith(t *testing.T, adjust func(*config.API)) *env {
|
||||
t.Helper()
|
||||
dsn, redisURL := os.Getenv("UPTIME_TEST_DATABASE_URL"), os.Getenv("UPTIME_TEST_REDIS_URL")
|
||||
if dsn == "" || redisURL == "" {
|
||||
@@ -76,7 +83,7 @@ func newEnv(t *testing.T) *env {
|
||||
}
|
||||
log := slog.New(slog.DiscardHandler)
|
||||
|
||||
e := &env{dbPool: pool}
|
||||
e := &env{dbPool: pool, rdb: rdb}
|
||||
r := platform.NewRouter(log)
|
||||
e.srv = httptest.NewUnstartedServer(r)
|
||||
e.srv.StartTLS()
|
||||
@@ -90,6 +97,9 @@ func newEnv(t *testing.T) *env {
|
||||
PublicURL: e.srv.URL,
|
||||
SSOPrivateNetworks: "true",
|
||||
}
|
||||
if adjust != nil {
|
||||
adjust(&cfg)
|
||||
}
|
||||
e.api = api.New(cfg, api.Deps{Log: log, DB: tenant.New(pool), Redis: rdb, Keys: keys, Catalog: catalog})
|
||||
e.api.Mount(r)
|
||||
return e
|
||||
|
||||
Reference in new issue
Block a user