// Package notify delivers incident events to notification channels. // // Delivery is at least once: the API keeps an outbox and retries, so // receivers should deduplicate by incident ID and event. package notify import ( "bytes" "context" "crypto/hmac" "crypto/sha256" "crypto/tls" "encoding/hex" "encoding/json" "errors" "fmt" "io" "mime" "net" "net/http" "net/smtp" "net/url" "strconv" "strings" "time" "github.com/google/uuid" "git.zb-server.de/ZB-Server/uptimesebi/internal/netguard" ) // Event kinds. const ( Opened = "opened" Resolved = "resolved" // Test is sent when a user tries out a channel. Test = "test" ) // Monitor identifies the affected monitor. type Monitor struct { ID uuid.UUID `json:"id"` Name string `json:"name"` Type string `json:"type"` Target string `json:"target"` } // Event is one incident change, also the webhook payload. type Event struct { Kind string `json:"event"` IncidentID uuid.UUID `json:"incident_id"` StartedAt time.Time `json:"started_at"` ResolvedAt *time.Time `json:"resolved_at,omitempty"` Cause map[string]string `json:"cause,omitempty"` Monitor Monitor `json:"monitor"` } // Webhook signs requests so receivers can verify they came from us: the // signature is HMAC-SHA256 over "." with the channel secret, // sent as "sha256=". Receivers should reject old timestamps. type Webhook struct { URL string Secret []byte AllowPrivate bool } // Headers set on webhook requests. const ( SignatureHeader = "X-Uptimesebi-Signature" TimestampHeader = "X-Uptimesebi-Timestamp" EventHeader = "X-Uptimesebi-Event" ) // Sign returns the signature header value for body at ts. func Sign(secret, body []byte, ts int64) string { mac := hmac.New(sha256.New, secret) _, _ = fmt.Fprintf(mac, "%d.", ts) _, _ = mac.Write(body) return "sha256=" + hex.EncodeToString(mac.Sum(nil)) } // Send posts ev as JSON. func (w Webhook) Send(ctx context.Context, ev Event) error { body, err := json.Marshal(ev) if err != nil { return err } ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodPost, w.URL, bytes.NewReader(body)) if err != nil { return err } ts := time.Now().Unix() req.Header.Set("Content-Type", "application/json") req.Header.Set("User-Agent", "uptimesebi-webhook") req.Header.Set(EventHeader, ev.Kind) req.Header.Set(TimestampHeader, strconv.FormatInt(ts, 10)) req.Header.Set(SignatureHeader, Sign(w.Secret, body, ts)) d := netguard.Dialer(w.AllowPrivate, 5*time.Second) client := &http.Client{ Transport: &http.Transport{DialContext: d.DialContext, DisableKeepAlives: true}, // Redirects would bypass the URL the customer configured. CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, } resp, err := client.Do(req) if err != nil { return err } defer func() { _ = resp.Body.Close() }() _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10)) if resp.StatusCode < 200 || resp.StatusCode > 299 { return fmt.Errorf("webhook answered %d", resp.StatusCode) } return nil } // SMTP is the outgoing mail server, parsed from a URL like // smtp://user:pass@host:587?from=alerts@example.com&tls=starttls. // tls is starttls (default), tls for implicit TLS, or none. type SMTP struct { Host string Port string Username string Password string From string TLS string } // ParseSMTP parses an SMTP URL. An empty string yields nil: mail is off. func ParseSMTP(raw string) (*SMTP, error) { if raw == "" { return nil, nil } u, err := url.Parse(raw) if err != nil || u.Scheme != "smtp" || u.Hostname() == "" { return nil, errors.New("notify: UPTIME_SMTP_URL must look like smtp://user:pass@host:587?from=alerts@example.com") } s := &SMTP{Host: u.Hostname(), Port: u.Port(), From: u.Query().Get("from"), TLS: u.Query().Get("tls")} if s.Port == "" { s.Port = "587" } if s.TLS == "" { s.TLS = "starttls" } if u.User != nil { s.Username = u.User.Username() s.Password, _ = u.User.Password() } if s.From == "" || (s.TLS != "starttls" && s.TLS != "tls" && s.TLS != "none") { return nil, errors.New("notify: UPTIME_SMTP_URL needs ?from= and tls=starttls|tls|none") } return s, nil } // Mail is a plain-text message. type Mail struct { To []string Subject string Body string } // Send delivers m. func (s *SMTP) Send(ctx context.Context, m Mail) error { addr := net.JoinHostPort(s.Host, s.Port) d := &net.Dialer{Timeout: 10 * time.Second} var conn net.Conn var err error if s.TLS == "tls" { conn, err = (&tls.Dialer{NetDialer: d, Config: &tls.Config{ServerName: s.Host}}).DialContext(ctx, "tcp", addr) } else { conn, err = d.DialContext(ctx, "tcp", addr) } if err != nil { return err } if dl, ok := ctx.Deadline(); ok { _ = conn.SetDeadline(dl) } else { _ = conn.SetDeadline(time.Now().Add(30 * time.Second)) } c, err := smtp.NewClient(conn, s.Host) if err != nil { _ = conn.Close() return err } defer func() { _ = c.Close() }() if s.TLS == "starttls" { if err := c.StartTLS(&tls.Config{ServerName: s.Host}); err != nil { return err } } if s.Username != "" { if err := c.Auth(smtp.PlainAuth("", s.Username, s.Password, s.Host)); err != nil { return err } } if err := c.Mail(s.From); err != nil { return err } for _, to := range m.To { if err := c.Rcpt(to); err != nil { return err } } w, err := c.Data() if err != nil { return err } if _, err := w.Write(compose(s.From, m)); err != nil { return err } if err := w.Close(); err != nil { return err } return c.Quit() } func compose(from string, m Mail) []byte { var b bytes.Buffer fmt.Fprintf(&b, "From: %s\r\n", from) fmt.Fprintf(&b, "To: %s\r\n", strings.Join(m.To, ", ")) fmt.Fprintf(&b, "Subject: %s\r\n", encodeHeader(m.Subject)) fmt.Fprintf(&b, "Date: %s\r\n", time.Now().Format(time.RFC1123Z)) fmt.Fprintf(&b, "Message-ID: <%s@uptimesebi>\r\n", uuid.NewString()) b.WriteString("MIME-Version: 1.0\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: 8bit\r\n\r\n") b.WriteString(strings.ReplaceAll(m.Body, "\n", "\r\n")) return b.Bytes() } // encodeHeader applies RFC 2047 encoding when the subject is not ASCII. func encodeHeader(s string) string { for _, r := range s { if r > 127 { return mime.QEncoding.Encode("utf-8", s) } } return s }