Channels of the new types store their settings with secrets sealed and bound to type and field, never return them, and keep them when an update leaves them empty. Messages are rendered in the channel's language with a link to the monitor. The channels page offers every service with its fields. Closes #92 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
313 lines
8.6 KiB
Go
313 lines
8.6 KiB
Go
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,max=32"`
|
|
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"`
|
|
// Settings configure the other channel types, as listed by
|
|
// notify.Providers; secret settings left empty keep their value.
|
|
Settings map[string]string `json:"settings" binding:"max=20"`
|
|
}
|
|
|
|
type channelView struct {
|
|
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"`
|
|
// Settings and SecretsSet describe other channel types; secret values
|
|
// are never returned.
|
|
Settings map[string]string `json:"settings,omitempty"`
|
|
SecretsSet []string `json:"secrets_set,omitempty"`
|
|
}
|
|
|
|
func viewChannel(ch store.NotificationChannel) channelView {
|
|
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
|
|
default:
|
|
v.Settings, v.SecretsSet, v.Locale = providerView(ch.Config)
|
|
}
|
|
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, "", ""
|
|
}
|
|
if p, ok := notify.Lookup(req.Type); ok {
|
|
config, code = s.providerSettings(p, req, previous)
|
|
return config, "", code
|
|
}
|
|
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})
|
|
}
|