Files
uptimesebi/internal/notify/notifytest/smtp.go
Sebastian UnterschützandClaude Opus 5.5 01ef543e62 feat(notify): deliver incidents by signed webhook and smtp
Webhooks carry an HMAC-SHA256 signature over timestamp and body and
refuse private addresses unless allowed.

Refs #16

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

105 lines
2.2 KiB
Go

// Package notifytest provides an in-memory SMTP server for tests.
package notifytest
import (
"bufio"
"net"
"strings"
"sync"
"testing"
)
// Message is one received mail.
type Message struct {
From string
To []string
Data string
}
// SMTP accepts mail without authentication or TLS.
type SMTP struct {
Addr string
mu sync.Mutex
messages []Message
}
// NewSMTP starts a server that stops when t ends.
func NewSMTP(t *testing.T) *SMTP {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
s := &SMTP{Addr: ln.Addr().String()}
t.Cleanup(func() { _ = ln.Close() })
go func() {
for {
conn, err := ln.Accept()
if err != nil {
return
}
go s.serve(conn)
}
}()
return s
}
// Messages returns what was received so far.
func (s *SMTP) Messages() []Message {
s.mu.Lock()
defer s.mu.Unlock()
return append([]Message(nil), s.messages...)
}
// URL returns an UPTIME_SMTP_URL for this server.
func (s *SMTP) URL() string { return "smtp://" + s.Addr + "?from=alerts@uptimesebi.test&tls=none" }
func (s *SMTP) serve(conn net.Conn) {
defer func() { _ = conn.Close() }()
r := bufio.NewReader(conn)
reply := func(line string) { _, _ = conn.Write([]byte(line + "\r\n")) }
reply("220 test")
var msg Message
for {
line, err := r.ReadString('\n')
if err != nil {
return
}
cmd := strings.ToUpper(strings.TrimSpace(line))
switch {
case strings.HasPrefix(cmd, "EHLO"), strings.HasPrefix(cmd, "HELO"):
reply("250 test")
case strings.HasPrefix(cmd, "MAIL FROM:"):
msg = Message{From: strings.Trim(strings.TrimSpace(line)[10:], "<>")}
reply("250 ok")
case strings.HasPrefix(cmd, "RCPT TO:"):
msg.To = append(msg.To, strings.Trim(strings.TrimSpace(line)[8:], "<>"))
reply("250 ok")
case cmd == "DATA":
reply("354 go")
var b strings.Builder
for {
l, err := r.ReadString('\n')
if err != nil {
return
}
if l == ".\r\n" {
break
}
b.WriteString(l)
}
msg.Data = b.String()
s.mu.Lock()
s.messages = append(s.messages, msg)
s.mu.Unlock()
reply("250 queued")
case cmd == "QUIT":
reply("221 bye")
return
default:
reply("250 ok")
}
}
}