Archived
initial
This commit is contained in:
59 files changed
+11046
No files matched your search
@@ -0,0 +1,41 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
type TokenCipher struct{ aead cipher.AEAD }
|
||||
|
||||
func NewTokenCipher(key []byte) (TokenCipher, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return TokenCipher{}, err
|
||||
}
|
||||
aead, err := cipher.NewGCM(block)
|
||||
return TokenCipher{aead: aead}, err
|
||||
}
|
||||
func (c TokenCipher) Encrypt(value string) ([]byte, error) {
|
||||
nonce := make([]byte, c.aead.NonceSize())
|
||||
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c.aead.Seal(nonce, nonce, []byte(value), nil), nil
|
||||
}
|
||||
func (c TokenCipher) Decrypt(value []byte) (string, error) {
|
||||
if len(value) < c.aead.NonceSize() {
|
||||
return "", fmt.Errorf("invalid encrypted token")
|
||||
}
|
||||
nonce, ciphertext := value[:c.aead.NonceSize()], value[c.aead.NonceSize():]
|
||||
raw, err := c.aead.Open(nil, nonce, ciphertext, nil)
|
||||
return string(raw), err
|
||||
}
|
||||
func RandomID(prefix string) string {
|
||||
raw := make([]byte, 18)
|
||||
_, _ = rand.Read(raw)
|
||||
return prefix + base64.RawURLEncoding.EncodeToString(raw)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTokenCipherRoundTripAndRandomNonce(t *testing.T) {
|
||||
cipher, err := NewTokenCipher(bytes.Repeat([]byte{7}, 32))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
one, err := cipher.Encrypt("access-token")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
two, _ := cipher.Encrypt("access-token")
|
||||
if bytes.Equal(one, two) {
|
||||
t.Fatal("ciphertext reused a nonce")
|
||||
}
|
||||
plain, err := cipher.Decrypt(one)
|
||||
if err != nil || plain != "access-token" {
|
||||
t.Fatalf("round trip = %q, %v", plain, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Addr string
|
||||
DataDir string
|
||||
PublicURL string
|
||||
StalwartURL string
|
||||
StalwartBootstrapURL string
|
||||
StalwartTLSInsecure bool
|
||||
StalwartRecoveryAdmin string
|
||||
SMTPAddress string
|
||||
SMTPTLSServerName string
|
||||
SMTPUsername string
|
||||
SMTPPassword string
|
||||
SessionKey []byte
|
||||
InternalWebhookSecret string
|
||||
BootstrapToken string
|
||||
MessageRetention time.Duration
|
||||
WebhookRetention time.Duration
|
||||
AuditRetention time.Duration
|
||||
MaxMessageBytes int64
|
||||
MaxRecipients int
|
||||
RateLimitPerMinute int
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
dataDir := value("MEOVV_DATA_DIR", "/var/lib/meovv-mail")
|
||||
cfg := Config{
|
||||
Addr: value("MEOVV_ADDR", ":8080"),
|
||||
DataDir: dataDir,
|
||||
PublicURL: strings.TrimRight(value("MEOVV_PUBLIC_URL", "http://localhost:8080"), "/"),
|
||||
StalwartURL: strings.TrimRight(value("STALWART_URL", "http://stalwart:8080"), "/"),
|
||||
StalwartBootstrapURL: strings.TrimRight(value("STALWART_BOOTSTRAP_URL", "http://stalwart:8080"), "/"),
|
||||
StalwartTLSInsecure: strings.EqualFold(value("STALWART_TLS_INSECURE", "false"), "true"),
|
||||
StalwartRecoveryAdmin: secret("STALWART_RECOVERY_ADMIN", "STALWART_RECOVERY_ADMIN_FILE"),
|
||||
SMTPAddress: value("STALWART_SMTP_ADDRESS", "stalwart:587"),
|
||||
SMTPTLSServerName: value("STALWART_TLS_SERVER_NAME", ""),
|
||||
SMTPUsername: os.Getenv("STALWART_SMTP_USERNAME"),
|
||||
SMTPPassword: secret("STALWART_SMTP_PASSWORD", "STALWART_SMTP_PASSWORD_FILE"),
|
||||
InternalWebhookSecret: secret("MEOVV_INTERNAL_WEBHOOK_SECRET", "MEOVV_INTERNAL_WEBHOOK_SECRET_FILE"),
|
||||
BootstrapToken: secret("MEOVV_BOOTSTRAP_TOKEN", "MEOVV_BOOTSTRAP_TOKEN_FILE"),
|
||||
MessageRetention: duration("MEOVV_MESSAGE_RETENTION", 30*24*time.Hour),
|
||||
WebhookRetention: duration("MEOVV_WEBHOOK_RETENTION", 7*24*time.Hour),
|
||||
AuditRetention: duration("MEOVV_AUDIT_RETENTION", 180*24*time.Hour),
|
||||
MaxMessageBytes: int64Value("MEOVV_MAX_MESSAGE_BYTES", 25*1024*1024),
|
||||
MaxRecipients: intValue("MEOVV_MAX_RECIPIENTS", 100),
|
||||
RateLimitPerMinute: intValue("MEOVV_RATE_LIMIT_PER_MINUTE", 60),
|
||||
}
|
||||
|
||||
sessionSecret := secret("MEOVV_SESSION_KEY", "MEOVV_SESSION_KEY_FILE")
|
||||
if sessionSecret == "" {
|
||||
if err := os.MkdirAll(dataDir, 0o700); err != nil {
|
||||
return Config{}, fmt.Errorf("create data directory: %w", err)
|
||||
}
|
||||
path := filepath.Join(dataDir, "session.key")
|
||||
contents, err := os.ReadFile(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
key := make([]byte, 32)
|
||||
if _, err = rand.Read(key); err != nil {
|
||||
return Config{}, fmt.Errorf("generate session key: %w", err)
|
||||
}
|
||||
sessionSecret = base64.RawURLEncoding.EncodeToString(key)
|
||||
if err = os.WriteFile(path, []byte(sessionSecret+"\n"), 0o600); err != nil {
|
||||
return Config{}, fmt.Errorf("write session key: %w", err)
|
||||
}
|
||||
} else if err != nil {
|
||||
return Config{}, fmt.Errorf("read session key: %w", err)
|
||||
} else {
|
||||
sessionSecret = strings.TrimSpace(string(contents))
|
||||
}
|
||||
}
|
||||
key, err := base64.RawURLEncoding.DecodeString(sessionSecret)
|
||||
if err != nil || len(key) != 32 {
|
||||
return Config{}, errors.New("MEOVV_SESSION_KEY must be a base64url encoded 32-byte key")
|
||||
}
|
||||
cfg.SessionKey = key
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func value(name, fallback string) string {
|
||||
if v := strings.TrimSpace(os.Getenv(name)); v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func secret(valueName, fileName string) string {
|
||||
if v := strings.TrimSpace(os.Getenv(valueName)); v != "" {
|
||||
return v
|
||||
}
|
||||
if path := strings.TrimSpace(os.Getenv(fileName)); path != "" {
|
||||
if contents, err := os.ReadFile(path); err == nil {
|
||||
return strings.TrimSpace(string(contents))
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func duration(name string, fallback time.Duration) time.Duration {
|
||||
if v := strings.TrimSpace(os.Getenv(name)); v != "" {
|
||||
if parsed, err := time.ParseDuration(v); err == nil {
|
||||
return parsed
|
||||
}
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func intValue(name string, fallback int) int {
|
||||
if v, err := strconv.Atoi(strings.TrimSpace(os.Getenv(name))); err == nil && v > 0 {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func int64Value(name string, fallback int64) int64 {
|
||||
if v, err := strconv.ParseInt(strings.TrimSpace(os.Getenv(name)), 10, 64); err == nil && v > 0 {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
@@ -0,0 +1,886 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/mail"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/meovv-mail/meovv-mail/internal/app"
|
||||
"github.com/meovv-mail/meovv-mail/internal/config"
|
||||
"github.com/meovv-mail/meovv-mail/internal/mailer"
|
||||
"github.com/meovv-mail/meovv-mail/internal/stalwart"
|
||||
"github.com/meovv-mail/meovv-mail/internal/store"
|
||||
"github.com/meovv-mail/meovv-mail/internal/webhook"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
Config config.Config
|
||||
Store *store.Store
|
||||
Mailer mailer.Sender
|
||||
Stalwart *stalwart.Client
|
||||
Cipher app.TokenCipher
|
||||
Logger *slog.Logger
|
||||
StaticDir string
|
||||
started time.Time
|
||||
accepted atomic.Uint64
|
||||
failed atomic.Uint64
|
||||
limiter *rateLimiter
|
||||
}
|
||||
|
||||
func New(cfg config.Config, st *store.Store, sender mailer.Sender, client *stalwart.Client, cipher app.TokenCipher, logger *slog.Logger, staticDir string) *Server {
|
||||
return &Server{Config: cfg, Store: st, Mailer: sender, Stalwart: client, Cipher: cipher, Logger: logger, StaticDir: staticDir, started: time.Now(), limiter: newRateLimiter()}
|
||||
}
|
||||
|
||||
func (s *Server) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /health/live", s.live)
|
||||
mux.HandleFunc("GET /health/ready", s.ready)
|
||||
mux.HandleFunc("GET /metrics", s.metrics)
|
||||
mux.HandleFunc("GET /api/setup/status", s.setupStatus)
|
||||
mux.HandleFunc("POST /api/setup/complete", s.setupComplete)
|
||||
mux.HandleFunc("POST /api/session/exchange", s.sessionExchange)
|
||||
mux.HandleFunc("GET /api/session", s.sessionStatus)
|
||||
mux.HandleFunc("POST /api/session/logout", s.logout)
|
||||
mux.HandleFunc("POST /api/mail/jmap", s.jmap)
|
||||
mux.HandleFunc("GET /api/mail/session", s.jmapSession)
|
||||
mux.HandleFunc("GET /api/mail/events", s.jmapEvents)
|
||||
mux.HandleFunc("GET /api/admin/overview", s.adminOverview)
|
||||
mux.HandleFunc("POST /api/admin/stalwart", s.adminStalwart)
|
||||
mux.HandleFunc("GET /api/admin/api-keys", s.listAPIKeys)
|
||||
mux.HandleFunc("POST /api/admin/api-keys", s.createAPIKey)
|
||||
mux.HandleFunc("DELETE /api/admin/api-keys/{id}", s.revokeAPIKey)
|
||||
mux.HandleFunc("GET /api/admin/webhooks", s.listWebhooks)
|
||||
mux.HandleFunc("POST /api/admin/webhooks", s.createWebhook)
|
||||
mux.HandleFunc("DELETE /api/admin/webhooks/{id}", s.deleteWebhook)
|
||||
mux.HandleFunc("POST /api/internal/stalwart/events", s.internalEvents)
|
||||
mux.HandleFunc("POST /api/v1/messages", s.authAPI("messages.send", s.sendMessage))
|
||||
mux.HandleFunc("GET /api/v1/messages", s.authAPI("messages.status", s.listMessages))
|
||||
mux.HandleFunc("GET /api/v1/messages/{id}", s.authAPI("messages.status", s.getMessage))
|
||||
mux.Handle("/", s.frontend())
|
||||
return s.security(s.csrf(mux))
|
||||
}
|
||||
|
||||
func (s *Server) csrf(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodGet || r.Method == http.MethodHead || r.Method == http.MethodOptions || strings.HasPrefix(r.URL.Path, "/api/v1/") || r.URL.Path == "/api/internal/stalwart/events" {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
origin := strings.TrimRight(r.Header.Get("Origin"), "/")
|
||||
if origin != "" && origin != s.Config.PublicURL {
|
||||
problem(w, http.StatusForbidden, "cross_site_request", "Cross-site state changes are not allowed.")
|
||||
return
|
||||
}
|
||||
if strings.EqualFold(r.Header.Get("Sec-Fetch-Site"), "cross-site") {
|
||||
problem(w, http.StatusForbidden, "cross_site_request", "Cross-site state changes are not allowed.")
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) security(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("X-Frame-Options", "DENY")
|
||||
w.Header().Set("Referrer-Policy", "same-origin")
|
||||
w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
|
||||
w.Header().Set("Content-Security-Policy", "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self' wss:; frame-src 'none'; object-src 'none'; base-uri 'self'; form-action 'self'")
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) live(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, map[string]any{"status": "ok", "uptime_seconds": int(time.Since(s.started).Seconds())})
|
||||
}
|
||||
func (s *Server) ready(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
checks := map[string]string{"database": "ok", "stalwart": "ok"}
|
||||
status := 200
|
||||
if err := s.Store.Ping(ctx); err != nil {
|
||||
checks["database"] = err.Error()
|
||||
status = 503
|
||||
}
|
||||
if err := s.Stalwart.Ready(ctx); err != nil {
|
||||
checks["stalwart"] = err.Error()
|
||||
status = 503
|
||||
}
|
||||
writeJSON(w, status, map[string]any{"status": map[bool]string{true: "ok", false: "degraded"}[status == 200], "checks": checks})
|
||||
}
|
||||
func (s *Server) metrics(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain; version=0.0.4")
|
||||
fmt.Fprintf(w, "# HELP meovv_messages_accepted_total Messages accepted by the REST API.\n# TYPE meovv_messages_accepted_total counter\nmeovv_messages_accepted_total %d\n# HELP meovv_messages_failed_total Message submissions that failed.\n# TYPE meovv_messages_failed_total counter\nmeovv_messages_failed_total %d\n", s.accepted.Load(), s.failed.Load())
|
||||
}
|
||||
|
||||
type setupRequest struct {
|
||||
Hostname string `json:"hostname"`
|
||||
PrimaryDomain string `json:"primary_domain"`
|
||||
AdminEmail string `json:"admin_email"`
|
||||
Organization string `json:"organization"`
|
||||
Accent string `json:"accent"`
|
||||
DeliveryMode string `json:"delivery_mode"`
|
||||
RelayHost string `json:"relay_host,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) setupStatus(w http.ResponseWriter, r *http.Request) {
|
||||
var setup setupRequest
|
||||
err := s.Store.GetSetting(r.Context(), "installation", &setup)
|
||||
writeJSON(w, 200, map[string]any{"configured": err == nil, "installation": func() any {
|
||||
if err == nil {
|
||||
return setup
|
||||
}
|
||||
return nil
|
||||
}()})
|
||||
}
|
||||
func (s *Server) setupComplete(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Config.BootstrapToken == "" || !hmac.Equal([]byte(r.Header.Get("X-Bootstrap-Token")), []byte(s.Config.BootstrapToken)) {
|
||||
problem(w, 401, "invalid_bootstrap_token", "The one-time bootstrap token is missing or invalid.")
|
||||
return
|
||||
}
|
||||
var in setupRequest
|
||||
if !decodeJSON(w, r, &in, 64<<10) {
|
||||
return
|
||||
}
|
||||
if !validHostname(in.Hostname) || !validDomain(in.PrimaryDomain) {
|
||||
problem(w, 422, "invalid_installation", "Hostname and primary domain must be valid DNS names.")
|
||||
return
|
||||
}
|
||||
if address, err := mail.ParseAddress(in.AdminEmail); err != nil || !strings.HasSuffix(strings.ToLower(address.Address), "@"+strings.ToLower(in.PrimaryDomain)) {
|
||||
problem(w, 422, "invalid_admin", "Administrator email must belong to the primary domain.")
|
||||
return
|
||||
}
|
||||
if in.DeliveryMode != "direct" && in.DeliveryMode != "relay" {
|
||||
problem(w, 422, "invalid_delivery_mode", "Delivery mode must be direct or relay.")
|
||||
return
|
||||
}
|
||||
bootstrapResult, err := s.Stalwart.Bootstrap(r.Context(), s.Config.StalwartBootstrapURL, s.Config.StalwartRecoveryAdmin, in.Hostname, in.PrimaryDomain)
|
||||
if err != nil {
|
||||
problem(w, 502, "mail_core_setup_failed", err.Error())
|
||||
return
|
||||
}
|
||||
if err := s.Store.SetSetting(r.Context(), "installation", in); err != nil {
|
||||
problem(w, 500, "storage_error", "Could not save the installation.")
|
||||
return
|
||||
}
|
||||
_ = s.Store.Audit(r.Context(), app.RandomID("aud_"), in.AdminEmail, "installation.completed", in.Hostname, in)
|
||||
writeJSON(w, 201, map[string]any{"configured": true, "next": "Save the one-time administrator result, restart Stalwart, verify permanent administrator sign-in, then run mailctl harden.", "mail_core_result": json.RawMessage(bootstrapResult), "dns_checks": []string{"A/AAAA", "MX", "PTR", "SPF", "DKIM", "DMARC", "TLS"}})
|
||||
}
|
||||
|
||||
func (s *Server) sessionExchange(w http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
ClientCode string `json:"client_code"`
|
||||
CodeVerifier string `json:"code_verifier"`
|
||||
Account string `json:"account"`
|
||||
ClientID string `json:"client_id"`
|
||||
RedirectURI string `json:"redirect_uri"`
|
||||
}
|
||||
if !decodeJSON(w, r, &in, 16<<10) {
|
||||
return
|
||||
}
|
||||
if in.ClientID == "" {
|
||||
in.ClientID = "meovv-web"
|
||||
}
|
||||
if in.RedirectURI == "" {
|
||||
in.RedirectURI = s.Config.PublicURL + "/auth/callback"
|
||||
}
|
||||
tokens, err := s.Stalwart.Exchange(r.Context(), in.ClientID, in.ClientCode, in.CodeVerifier, in.RedirectURI)
|
||||
if err != nil {
|
||||
problem(w, 401, "exchange_failed", err.Error())
|
||||
return
|
||||
}
|
||||
access, _ := s.Cipher.Encrypt(tokens.AccessToken)
|
||||
refresh, _ := s.Cipher.Encrypt(tokens.RefreshToken)
|
||||
now := time.Now()
|
||||
id := app.RandomID("ses_")
|
||||
expiry := now.Add(time.Duration(tokens.ExpiresIn) * time.Second)
|
||||
if expiry.Equal(now) {
|
||||
expiry = now.Add(time.Hour)
|
||||
}
|
||||
sessionExpiry := now.Add(30 * 24 * time.Hour)
|
||||
if err = s.Store.CreateSession(r.Context(), store.Session{ID: id, Account: in.Account, AccessToken: access, RefreshToken: refresh, ExpiresAt: expiry, SessionExpiresAt: sessionExpiry, CreatedAt: now, LastSeenAt: now}); err != nil {
|
||||
problem(w, 500, "session_failed", "Could not establish the session.")
|
||||
return
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: "meovv_session", Value: id, Path: "/", HttpOnly: true, Secure: strings.HasPrefix(s.Config.PublicURL, "https://"), SameSite: http.SameSiteLaxMode, MaxAge: int(time.Until(sessionExpiry).Seconds())})
|
||||
writeJSON(w, 200, map[string]any{"authenticated": true, "account": in.Account})
|
||||
}
|
||||
func (s *Server) sessionStatus(w http.ResponseWriter, r *http.Request) {
|
||||
session, _, err := s.session(r)
|
||||
if err != nil {
|
||||
problem(w, 401, "authentication_required", "Sign in to continue.")
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"authenticated": true, "account": session.Account})
|
||||
}
|
||||
func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
|
||||
if cookie, err := r.Cookie("meovv_session"); err == nil {
|
||||
_ = s.Store.DeleteSession(r.Context(), cookie.Value)
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: "meovv_session", Value: "", Path: "/", HttpOnly: true, Secure: strings.HasPrefix(s.Config.PublicURL, "https://"), SameSite: http.SameSiteLaxMode, MaxAge: -1})
|
||||
w.WriteHeader(204)
|
||||
}
|
||||
func (s *Server) session(r *http.Request) (store.Session, string, error) {
|
||||
cookie, err := r.Cookie("meovv_session")
|
||||
if err != nil {
|
||||
return store.Session{}, "", store.ErrNotFound
|
||||
}
|
||||
session, err := s.Store.GetSession(r.Context(), cookie.Value)
|
||||
if err != nil {
|
||||
return session, "", err
|
||||
}
|
||||
if time.Until(session.ExpiresAt) < time.Minute {
|
||||
refreshToken, decryptErr := s.Cipher.Decrypt(session.RefreshToken)
|
||||
if decryptErr != nil {
|
||||
return session, "", decryptErr
|
||||
}
|
||||
tokens, refreshErr := s.Stalwart.Refresh(r.Context(), "meovv-web", refreshToken)
|
||||
if refreshErr != nil {
|
||||
_ = s.Store.DeleteSession(r.Context(), session.ID)
|
||||
return session, "", refreshErr
|
||||
}
|
||||
access, encryptErr := s.Cipher.Encrypt(tokens.AccessToken)
|
||||
if encryptErr != nil {
|
||||
return session, "", encryptErr
|
||||
}
|
||||
if tokens.RefreshToken == "" {
|
||||
tokens.RefreshToken = refreshToken
|
||||
}
|
||||
refresh, encryptErr := s.Cipher.Encrypt(tokens.RefreshToken)
|
||||
if encryptErr != nil {
|
||||
return session, "", encryptErr
|
||||
}
|
||||
expires := time.Now().Add(time.Duration(tokens.ExpiresIn) * time.Second)
|
||||
if tokens.ExpiresIn <= 0 {
|
||||
expires = time.Now().Add(time.Hour)
|
||||
}
|
||||
if err = s.Store.UpdateSessionTokens(r.Context(), session.ID, access, refresh, expires); err != nil {
|
||||
return session, "", err
|
||||
}
|
||||
session.AccessToken = access
|
||||
session.RefreshToken = refresh
|
||||
session.ExpiresAt = expires
|
||||
}
|
||||
token, err := s.Cipher.Decrypt(session.AccessToken)
|
||||
return session, token, err
|
||||
}
|
||||
func (s *Server) jmap(w http.ResponseWriter, r *http.Request) {
|
||||
_, token, err := s.session(r)
|
||||
if err != nil {
|
||||
problem(w, 401, "authentication_required", "Sign in to access this mailbox.")
|
||||
return
|
||||
}
|
||||
raw, err := io.ReadAll(io.LimitReader(r.Body, 32<<20))
|
||||
if err != nil {
|
||||
problem(w, 400, "invalid_body", err.Error())
|
||||
return
|
||||
}
|
||||
status, headers, response, err := s.Stalwart.ProxyJMAP(r.Context(), token, raw)
|
||||
if err != nil {
|
||||
problem(w, 502, "mail_service_error", err.Error())
|
||||
return
|
||||
}
|
||||
if content := headers.Get("Content-Type"); content != "" {
|
||||
w.Header().Set("Content-Type", content)
|
||||
}
|
||||
w.WriteHeader(status)
|
||||
_, _ = w.Write(response)
|
||||
}
|
||||
func (s *Server) jmapSession(w http.ResponseWriter, r *http.Request) {
|
||||
_, token, err := s.session(r)
|
||||
if err != nil {
|
||||
problem(w, 401, "authentication_required", "Sign in to access this mailbox.")
|
||||
return
|
||||
}
|
||||
status, headers, response, err := s.Stalwart.JMAPSession(r.Context(), token)
|
||||
if err != nil {
|
||||
problem(w, 502, "mail_service_error", err.Error())
|
||||
return
|
||||
}
|
||||
if content := headers.Get("Content-Type"); content != "" {
|
||||
w.Header().Set("Content-Type", content)
|
||||
}
|
||||
w.WriteHeader(status)
|
||||
_, _ = w.Write(response)
|
||||
}
|
||||
func (s *Server) jmapEvents(w http.ResponseWriter, r *http.Request) {
|
||||
_, token, err := s.session(r)
|
||||
if err != nil {
|
||||
problem(w, 401, "authentication_required", "Sign in to access this mailbox.")
|
||||
return
|
||||
}
|
||||
response, err := s.Stalwart.EventStream(r.Context(), token)
|
||||
if err != nil {
|
||||
problem(w, 502, "mail_service_error", err.Error())
|
||||
return
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode/100 != 2 {
|
||||
body, _ := io.ReadAll(io.LimitReader(response.Body, 4096))
|
||||
problem(w, 502, "mail_service_error", strings.TrimSpace(string(body)))
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.Header().Set("Cache-Control", "no-cache, no-transform")
|
||||
w.Header().Set("X-Accel-Buffering", "no")
|
||||
w.WriteHeader(200)
|
||||
flusher, _ := w.(http.Flusher)
|
||||
buffer := make([]byte, 16<<10)
|
||||
for {
|
||||
n, readErr := response.Body.Read(buffer)
|
||||
if n > 0 {
|
||||
if _, err = w.Write(buffer[:n]); err != nil {
|
||||
return
|
||||
}
|
||||
if flusher != nil {
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
if readErr != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
func (s *Server) adminOverview(w http.ResponseWriter, r *http.Request) {
|
||||
session, _, ok := s.requireAdmin(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
stats, err := s.Store.Stats(r.Context())
|
||||
if err != nil {
|
||||
problem(w, 500, "storage_error", err.Error())
|
||||
return
|
||||
}
|
||||
stats["account"] = session.Account
|
||||
stats["version"] = "0.1.0"
|
||||
stats["stalwart_version"] = "0.16.17"
|
||||
writeJSON(w, 200, stats)
|
||||
}
|
||||
|
||||
func (s *Server) requireAdmin(w http.ResponseWriter, r *http.Request) (store.Session, string, bool) {
|
||||
session, token, err := s.session(r)
|
||||
if err != nil {
|
||||
if os.Getenv("MEOVV_DEMO_MODE") == "1" {
|
||||
return store.Session{Account: "demo-admin"}, "", true
|
||||
}
|
||||
problem(w, 401, "authentication_required", "Administrator sign-in is required.")
|
||||
return store.Session{}, "", false
|
||||
}
|
||||
var installation setupRequest
|
||||
if err = s.Store.GetSetting(r.Context(), "installation", &installation); err == nil && !strings.EqualFold(session.Account, installation.AdminEmail) && !strings.EqualFold(session.Account, "admin") {
|
||||
problem(w, 403, "administrator_required", "This account is not the installation administrator.")
|
||||
return store.Session{}, "", false
|
||||
}
|
||||
return session, token, true
|
||||
}
|
||||
|
||||
func (s *Server) adminStalwart(w http.ResponseWriter, r *http.Request) {
|
||||
_, token, ok := s.requireAdmin(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
raw, err := io.ReadAll(io.LimitReader(r.Body, 4<<20))
|
||||
if err != nil {
|
||||
problem(w, 400, "invalid_body", err.Error())
|
||||
return
|
||||
}
|
||||
status, headers, response, err := s.Stalwart.ProxyManagement(r.Context(), token, raw)
|
||||
if err != nil {
|
||||
problem(w, 502, "mail_service_error", err.Error())
|
||||
return
|
||||
}
|
||||
if value := headers.Get("Content-Type"); value != "" {
|
||||
w.Header().Set("Content-Type", value)
|
||||
}
|
||||
w.WriteHeader(status)
|
||||
_, _ = w.Write(response)
|
||||
}
|
||||
|
||||
func (s *Server) listAPIKeys(w http.ResponseWriter, r *http.Request) {
|
||||
if _, _, ok := s.requireAdmin(w, r); !ok {
|
||||
return
|
||||
}
|
||||
keys, err := s.Store.ListAPIKeys(r.Context())
|
||||
if err != nil {
|
||||
problem(w, 500, "storage_error", err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": keys})
|
||||
}
|
||||
|
||||
func (s *Server) createAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||
session, _, ok := s.requireAdmin(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
Name string `json:"name"`
|
||||
Scopes []string `json:"scopes"`
|
||||
AllowedSenders []string `json:"allowed_senders"`
|
||||
RateLimit int `json:"rate_limit"`
|
||||
}
|
||||
if !decodeJSON(w, r, &in, 64<<10) {
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(in.Name) == "" || !validScopes(in.Scopes) || len(in.AllowedSenders) == 0 {
|
||||
problem(w, 422, "invalid_api_key", "Name, valid scopes, and at least one approved sender are required.")
|
||||
return
|
||||
}
|
||||
for _, sender := range in.AllowedSenders {
|
||||
if !validSenderPattern(sender) {
|
||||
problem(w, 422, "invalid_sender", "Approved senders must be complete addresses or domain wildcards such as *@example.com.")
|
||||
return
|
||||
}
|
||||
}
|
||||
if in.RateLimit <= 0 {
|
||||
in.RateLimit = s.Config.RateLimitPerMinute
|
||||
}
|
||||
secret := app.RandomID("meovv_")
|
||||
key := store.APIKey{ID: app.RandomID("key_"), Name: strings.TrimSpace(in.Name), Prefix: secret[:min(14, len(secret))], Scopes: in.Scopes, AllowedSenders: in.AllowedSenders, RateLimit: in.RateLimit, CreatedAt: time.Now().UTC()}
|
||||
if err := s.Store.CreateAPIKey(r.Context(), key, secret); err != nil {
|
||||
problem(w, 500, "storage_error", err.Error())
|
||||
return
|
||||
}
|
||||
_ = s.Store.Audit(r.Context(), app.RandomID("aud_"), session.Account, "api_key.created", key.ID, map[string]any{"name": key.Name, "scopes": key.Scopes})
|
||||
writeJSON(w, 201, map[string]any{"api_key": key, "secret": secret, "warning": "This secret is shown once and cannot be recovered."})
|
||||
}
|
||||
|
||||
func (s *Server) revokeAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||
session, _, ok := s.requireAdmin(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := s.Store.RevokeAPIKey(r.Context(), r.PathValue("id")); err != nil {
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
problem(w, 404, "not_found", "API key not found.")
|
||||
} else {
|
||||
problem(w, 500, "storage_error", err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
_ = s.Store.Audit(r.Context(), app.RandomID("aud_"), session.Account, "api_key.revoked", r.PathValue("id"), nil)
|
||||
w.WriteHeader(204)
|
||||
}
|
||||
|
||||
var allowedWebhookEvents = map[string]bool{"message.queued": true, "message.delivered": true, "message.deferred": true, "message.bounced": true, "message.failed": true}
|
||||
|
||||
func (s *Server) listWebhooks(w http.ResponseWriter, r *http.Request) {
|
||||
if _, _, ok := s.requireAdmin(w, r); !ok {
|
||||
return
|
||||
}
|
||||
items, err := s.Store.ListWebhookEndpoints(r.Context())
|
||||
if err != nil {
|
||||
problem(w, 500, "storage_error", err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": items})
|
||||
}
|
||||
|
||||
func (s *Server) createWebhook(w http.ResponseWriter, r *http.Request) {
|
||||
session, _, ok := s.requireAdmin(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
Name string `json:"name"`
|
||||
URL string `json:"url"`
|
||||
Events []string `json:"events"`
|
||||
}
|
||||
if !decodeJSON(w, r, &in, 64<<10) {
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(in.Name) == "" || len(in.Events) == 0 {
|
||||
problem(w, 422, "invalid_webhook", "Name and at least one event are required.")
|
||||
return
|
||||
}
|
||||
for _, event := range in.Events {
|
||||
if !allowedWebhookEvents[event] {
|
||||
problem(w, 422, "invalid_event", "The webhook contains an unsupported event type.")
|
||||
return
|
||||
}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
|
||||
defer cancel()
|
||||
if err := webhook.ValidatePublicURL(ctx, in.URL); err != nil {
|
||||
problem(w, 422, "unsafe_webhook_url", err.Error())
|
||||
return
|
||||
}
|
||||
rawSecret := app.RandomID("whsec_")
|
||||
encryptedSecret, err := s.Cipher.Encrypt(rawSecret)
|
||||
if err != nil {
|
||||
problem(w, 500, "secret_encryption_failed", "Could not protect the webhook signing secret.")
|
||||
return
|
||||
}
|
||||
endpoint := store.WebhookEndpoint{ID: app.RandomID("wh_"), Name: strings.TrimSpace(in.Name), URL: in.URL, Secret: base64.RawStdEncoding.EncodeToString(encryptedSecret), Events: in.Events, Enabled: true, CreatedAt: time.Now().UTC()}
|
||||
if err := s.Store.CreateWebhookEndpoint(r.Context(), endpoint); err != nil {
|
||||
problem(w, 500, "storage_error", err.Error())
|
||||
return
|
||||
}
|
||||
_ = s.Store.Audit(r.Context(), app.RandomID("aud_"), session.Account, "webhook.created", endpoint.ID, map[string]any{"url": endpoint.URL, "events": endpoint.Events})
|
||||
writeJSON(w, 201, map[string]any{"webhook": endpoint, "secret": rawSecret, "warning": "This signing secret is shown once."})
|
||||
}
|
||||
|
||||
func (s *Server) deleteWebhook(w http.ResponseWriter, r *http.Request) {
|
||||
session, _, ok := s.requireAdmin(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := s.Store.DeleteWebhookEndpoint(r.Context(), r.PathValue("id")); err != nil {
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
problem(w, 404, "not_found", "Webhook endpoint not found.")
|
||||
} else {
|
||||
problem(w, 500, "storage_error", err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
_ = s.Store.Audit(r.Context(), app.RandomID("aud_"), session.Account, "webhook.deleted", r.PathValue("id"), nil)
|
||||
w.WriteHeader(204)
|
||||
}
|
||||
|
||||
func (s *Server) sendMessage(w http.ResponseWriter, r *http.Request, key store.APIKey) {
|
||||
var in struct {
|
||||
From string `json:"from"`
|
||||
To []string `json:"to"`
|
||||
CC []string `json:"cc"`
|
||||
BCC []string `json:"bcc"`
|
||||
ReplyTo string `json:"reply_to"`
|
||||
Subject string `json:"subject"`
|
||||
Text string `json:"text"`
|
||||
HTML string `json:"html"`
|
||||
Headers map[string]string `json:"headers"`
|
||||
Attachments []struct {
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
Content string `json:"content_base64"`
|
||||
} `json:"attachments"`
|
||||
}
|
||||
if !decodeJSON(w, r, &in, s.Config.MaxMessageBytes*2) {
|
||||
return
|
||||
}
|
||||
if in.Text == "" && in.HTML == "" {
|
||||
problem(w, 422, "body_required", "A text or HTML body is required.")
|
||||
return
|
||||
}
|
||||
if !allowedSender(key, in.From) {
|
||||
problem(w, 403, "sender_not_allowed", "The API key is not allowed to use this sender.")
|
||||
return
|
||||
}
|
||||
if len(in.To)+len(in.CC)+len(in.BCC) > s.Config.MaxRecipients {
|
||||
problem(w, 422, "too_many_recipients", fmt.Sprintf("At most %d recipients are allowed.", s.Config.MaxRecipients))
|
||||
return
|
||||
}
|
||||
id := app.RandomID("msg_")
|
||||
headers := in.Headers
|
||||
if headers == nil {
|
||||
headers = map[string]string{}
|
||||
}
|
||||
headers["X-MEOVV-Message-ID"] = id
|
||||
attachments := make([]mailer.Attachment, len(in.Attachments))
|
||||
for i, a := range in.Attachments {
|
||||
attachments[i] = mailer.Attachment{Filename: a.Filename, ContentType: a.ContentType, ContentBase64: a.Content}
|
||||
}
|
||||
raw, recipients, err := mailer.Build(mailer.Message{From: in.From, To: in.To, CC: in.CC, BCC: in.BCC, ReplyTo: in.ReplyTo, Subject: in.Subject, Text: in.Text, HTML: in.HTML, Headers: headers, Attachments: attachments}, s.Config.MaxMessageBytes)
|
||||
if err != nil {
|
||||
problem(w, 422, "invalid_message", err.Error())
|
||||
return
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
message := store.Message{ID: id, APIKeyID: key.ID, Sender: strings.ToLower(in.From), Subject: in.Subject, Status: "queued", SizeBytes: int64(len(raw)), SubmittedAt: now, UpdatedAt: now}
|
||||
for _, recipient := range recipients {
|
||||
message.Recipients = append(message.Recipients, store.Recipient{Address: recipient, Status: "queued"})
|
||||
}
|
||||
digest := sha256.Sum256(raw)
|
||||
existing, err := s.Store.InsertMessage(r.Context(), message, r.Header.Get("Idempotency-Key"), hex.EncodeToString(digest[:]))
|
||||
if err != nil {
|
||||
problem(w, 409, "idempotency_conflict", err.Error())
|
||||
return
|
||||
}
|
||||
if existing != "" {
|
||||
prior, err := s.Store.GetMessage(r.Context(), existing)
|
||||
if err != nil {
|
||||
problem(w, 500, "storage_error", err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 202, receipt(prior))
|
||||
return
|
||||
}
|
||||
smtpID, err := s.Mailer.Send(r.Context(), in.From, recipients, raw)
|
||||
if err != nil {
|
||||
s.failed.Add(1)
|
||||
_ = s.Store.UpdateMessageStatus(r.Context(), id, "failed", err.Error(), "")
|
||||
problem(w, 502, "submission_failed", "The mail service did not accept this message.")
|
||||
return
|
||||
}
|
||||
s.accepted.Add(1)
|
||||
_ = s.Store.UpdateMessageStatus(r.Context(), id, "processing", "", smtpID)
|
||||
eventPayload, _ := json.Marshal(map[string]any{"id": app.RandomID("evt_"), "type": "message.queued", "created_at": now, "data": map[string]any{"message_id": id, "status": "queued"}})
|
||||
_ = s.Store.EnqueueEvent(r.Context(), app.RandomID("evt_"), "message.queued", eventPayload, now)
|
||||
w.Header().Set("Location", "/api/v1/messages/"+id)
|
||||
writeJSON(w, 202, map[string]any{"id": id, "status": "queued", "submitted_at": now})
|
||||
}
|
||||
func receipt(m store.Message) map[string]any {
|
||||
return map[string]any{"id": m.ID, "status": m.Status, "submitted_at": m.SubmittedAt}
|
||||
}
|
||||
func (s *Server) getMessage(w http.ResponseWriter, r *http.Request, key store.APIKey) {
|
||||
m, err := s.Store.GetMessage(r.Context(), r.PathValue("id"))
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
problem(w, 404, "not_found", "Message not found.")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
problem(w, 500, "storage_error", err.Error())
|
||||
return
|
||||
}
|
||||
if m.APIKeyID != key.ID {
|
||||
problem(w, 404, "not_found", "Message not found.")
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, m)
|
||||
}
|
||||
func (s *Server) listMessages(w http.ResponseWriter, r *http.Request, key store.APIKey) {
|
||||
q := r.URL.Query()
|
||||
filter := store.MessageFilter{Status: q.Get("status"), Sender: q.Get("sender"), Recipient: q.Get("recipient"), Cursor: q.Get("cursor"), APIKeyID: key.ID}
|
||||
filter.Limit, _ = strconv.Atoi(q.Get("limit"))
|
||||
if v := q.Get("from"); v != "" {
|
||||
if t, err := time.Parse(time.RFC3339, v); err == nil {
|
||||
filter.From = &t
|
||||
}
|
||||
}
|
||||
if v := q.Get("to"); v != "" {
|
||||
if t, err := time.Parse(time.RFC3339, v); err == nil {
|
||||
filter.To = &t
|
||||
}
|
||||
}
|
||||
items, next, err := s.Store.ListMessages(r.Context(), filter)
|
||||
if err != nil {
|
||||
problem(w, 500, "storage_error", err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": items, "next_cursor": next})
|
||||
}
|
||||
|
||||
func (s *Server) internalEvents(w http.ResponseWriter, r *http.Request) {
|
||||
raw, err := io.ReadAll(io.LimitReader(r.Body, 2<<20))
|
||||
if err != nil {
|
||||
problem(w, 400, "invalid_body", err.Error())
|
||||
return
|
||||
}
|
||||
if s.Config.InternalWebhookSecret == "" || !verifyInternal(s.Config.InternalWebhookSecret, r.Header.Get("X-Signature"), raw) {
|
||||
problem(w, 401, "invalid_signature", "Invalid Stalwart webhook signature.")
|
||||
return
|
||||
}
|
||||
var envelope struct {
|
||||
Events []struct {
|
||||
ID, Type, CreatedAt string
|
||||
Data map[string]any
|
||||
} `json:"events"`
|
||||
}
|
||||
if err = json.Unmarshal(raw, &envelope); err != nil {
|
||||
problem(w, 400, "invalid_event", err.Error())
|
||||
return
|
||||
}
|
||||
for _, event := range envelope.Events {
|
||||
messageID := findString(event.Data, "message_id", "messageId", "queue_id", "queueId")
|
||||
recipient := findString(event.Data, "recipient", "to")
|
||||
status, external := normalizeEvent(event.Type)
|
||||
if messageID != "" && status != "" {
|
||||
if recipient != "" {
|
||||
_ = s.Store.UpdateRecipient(r.Context(), messageID, recipient, status, findString(event.Data, "response", "reason"), time.Now())
|
||||
} else {
|
||||
_ = s.Store.UpdateMessageStatus(r.Context(), messageID, status, findString(event.Data, "reason"), "")
|
||||
}
|
||||
}
|
||||
if external != "" {
|
||||
payload, _ := json.Marshal(map[string]any{"id": event.ID, "type": external, "created_at": event.CreatedAt, "data": map[string]any{"message_id": messageID, "recipient": recipient, "status": status}})
|
||||
_ = s.Store.EnqueueEvent(r.Context(), event.ID, external, payload, time.Now())
|
||||
}
|
||||
}
|
||||
w.WriteHeader(204)
|
||||
}
|
||||
|
||||
type apiHandler func(http.ResponseWriter, *http.Request, store.APIKey)
|
||||
|
||||
func (s *Server) authAPI(scope string, next apiHandler) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
value := strings.TrimSpace(strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "))
|
||||
if value == "" {
|
||||
problem(w, 401, "authentication_required", "Provide a bearer API key.")
|
||||
return
|
||||
}
|
||||
key, err := s.Store.AuthenticateAPIKey(r.Context(), value)
|
||||
if err != nil {
|
||||
problem(w, 401, "invalid_api_key", "The API key is invalid or revoked.")
|
||||
return
|
||||
}
|
||||
if !hasScope(key, scope) {
|
||||
problem(w, 403, "insufficient_scope", "The API key does not have the required scope.")
|
||||
return
|
||||
}
|
||||
limit := key.RateLimit
|
||||
if limit <= 0 {
|
||||
limit = s.Config.RateLimitPerMinute
|
||||
}
|
||||
if !s.limiter.Allow(key.ID, limit) {
|
||||
w.Header().Set("Retry-After", "60")
|
||||
problem(w, 429, "rate_limited", "API key rate limit exceeded.")
|
||||
return
|
||||
}
|
||||
next(w, r, key)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) frontend() http.Handler {
|
||||
files := http.FileServer(http.Dir(s.StaticDir))
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
path := filepath.Join(s.StaticDir, filepath.Clean(r.URL.Path))
|
||||
if info, err := os.Stat(path); err == nil && !info.IsDir() {
|
||||
files.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
http.ServeFile(w, r, filepath.Join(s.StaticDir, "index.html"))
|
||||
})
|
||||
}
|
||||
|
||||
func decodeJSON(w http.ResponseWriter, r *http.Request, dst any, limit int64) bool {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, limit)
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(dst); err != nil {
|
||||
problem(w, 400, "invalid_json", err.Error())
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
func problem(w http.ResponseWriter, status int, code, detail string) {
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
writeJSON(w, status, map[string]any{"type": "https://docs.meovv.mail/problems/" + code, "title": strings.ReplaceAll(code, "_", " "), "status": status, "detail": detail, "code": code})
|
||||
}
|
||||
func validHostname(v string) bool { return validDomain(v) && strings.Contains(v, ".") }
|
||||
func validDomain(v string) bool {
|
||||
if len(v) < 3 || len(v) > 253 || strings.ContainsAny(v, " /:@") {
|
||||
return false
|
||||
}
|
||||
for _, part := range strings.Split(v, ".") {
|
||||
if part == "" || strings.HasPrefix(part, "-") || strings.HasSuffix(part, "-") {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
func hasScope(k store.APIKey, scope string) bool {
|
||||
for _, s := range k.Scopes {
|
||||
if s == scope {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func allowedSender(k store.APIKey, value string) bool {
|
||||
address, err := mail.ParseAddress(value)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
for _, allowed := range k.AllowedSenders {
|
||||
if strings.EqualFold(allowed, address.Address) {
|
||||
return true
|
||||
}
|
||||
if strings.HasPrefix(allowed, "*@") && strings.HasSuffix(strings.ToLower(address.Address), strings.ToLower(allowed[1:])) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func validSenderPattern(value string) bool {
|
||||
if strings.HasPrefix(value, "*@") {
|
||||
return validDomain(strings.TrimPrefix(value, "*@"))
|
||||
}
|
||||
_, err := mail.ParseAddress(value)
|
||||
return err == nil
|
||||
}
|
||||
func validScopes(scopes []string) bool {
|
||||
if len(scopes) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, scope := range scopes {
|
||||
if scope != "messages.send" && scope != "messages.status" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
func verifyInternal(secret, signature string, body []byte) bool {
|
||||
mac := hmac.New(sha256.New, []byte(secret))
|
||||
mac.Write(body)
|
||||
expected := base64.StdEncoding.EncodeToString(mac.Sum(nil))
|
||||
return hmac.Equal([]byte(expected), []byte(signature))
|
||||
}
|
||||
func normalizeEvent(event string) (string, string) {
|
||||
switch event {
|
||||
case "queue.queue-message", "queue.queue-message-authenticated":
|
||||
return "queued", "message.queued"
|
||||
case "delivery.delivered":
|
||||
return "delivered", "message.delivered"
|
||||
case "delivery.dsn-temp-fail", "queue.rescheduled":
|
||||
return "deferred", "message.deferred"
|
||||
case "delivery.dsn-perm-fail":
|
||||
return "bounced", "message.bounced"
|
||||
case "delivery.double-bounce":
|
||||
return "failed", "message.failed"
|
||||
}
|
||||
return "", ""
|
||||
}
|
||||
func findString(data map[string]any, keys ...string) string {
|
||||
for _, key := range keys {
|
||||
if v, ok := data[key].(string); ok {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type rateLimiter struct {
|
||||
mu sync.Mutex
|
||||
entries map[string]rateEntry
|
||||
}
|
||||
type rateEntry struct {
|
||||
minute int64
|
||||
count int
|
||||
}
|
||||
|
||||
func newRateLimiter() *rateLimiter { return &rateLimiter{entries: map[string]rateEntry{}} }
|
||||
func (l *rateLimiter) Allow(id string, limit int) bool {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
minute := time.Now().Unix() / 60
|
||||
entry := l.entries[id]
|
||||
if entry.minute != minute {
|
||||
entry = rateEntry{minute: minute}
|
||||
}
|
||||
if entry.count >= limit {
|
||||
return false
|
||||
}
|
||||
entry.count++
|
||||
l.entries[id] = entry
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/meovv-mail/meovv-mail/internal/store"
|
||||
)
|
||||
|
||||
func TestEventNormalization(t *testing.T) {
|
||||
tests := map[string][2]string{
|
||||
"queue.queue-message": {"queued", "message.queued"},
|
||||
"delivery.delivered": {"delivered", "message.delivered"},
|
||||
"delivery.dsn-temp-fail": {"deferred", "message.deferred"},
|
||||
"delivery.dsn-perm-fail": {"bounced", "message.bounced"},
|
||||
"delivery.double-bounce": {"failed", "message.failed"},
|
||||
}
|
||||
for event, expected := range tests {
|
||||
state, external := normalizeEvent(event)
|
||||
if state != expected[0] || external != expected[1] {
|
||||
t.Errorf("%s = %s/%s", event, state, external)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestScopesAndApprovedSender(t *testing.T) {
|
||||
key := store.APIKey{Scopes: []string{"messages.send"}, AllowedSenders: []string{"alerts@example.com", "*@internal.example.com"}}
|
||||
if !hasScope(key, "messages.send") || hasScope(key, "messages.status") {
|
||||
t.Fatal("scope evaluation failed")
|
||||
}
|
||||
if !allowedSender(key, "Alerts <alerts@example.com>") || !allowedSender(key, "robot@internal.example.com") || allowedSender(key, "attacker@example.net") {
|
||||
t.Fatal("sender identity evaluation failed")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package mailer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"mime"
|
||||
"net/mail"
|
||||
"net/textproto"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Attachment struct{ Filename, ContentType, ContentBase64 string }
|
||||
type Message struct {
|
||||
From string
|
||||
To, CC, BCC []string
|
||||
ReplyTo, Subject, Text, HTML string
|
||||
Headers map[string]string
|
||||
Attachments []Attachment
|
||||
}
|
||||
|
||||
var allowedHeader = regexp.MustCompile(`(?i)^(X-[A-Za-z0-9-]{1,64}|List-Unsubscribe|List-Unsubscribe-Post)$`)
|
||||
|
||||
func Build(m Message, maxBytes int64) ([]byte, []string, error) {
|
||||
from, err := mail.ParseAddress(m.From)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("invalid from address: %w", err)
|
||||
}
|
||||
recipients := append(append(append([]string{}, m.To...), m.CC...), m.BCC...)
|
||||
if len(recipients) == 0 {
|
||||
return nil, nil, fmt.Errorf("at least one recipient is required")
|
||||
}
|
||||
for i, value := range recipients {
|
||||
address, err := mail.ParseAddress(value)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("invalid recipient %q", value)
|
||||
}
|
||||
recipients[i] = strings.ToLower(address.Address)
|
||||
}
|
||||
var out bytes.Buffer
|
||||
boundary := randomBoundary()
|
||||
bodyBoundary := randomBoundary()
|
||||
headers := textproto.MIMEHeader{}
|
||||
headers.Set("From", from.String())
|
||||
headers.Set("To", strings.Join(m.To, ", "))
|
||||
if len(m.CC) > 0 {
|
||||
headers.Set("Cc", strings.Join(m.CC, ", "))
|
||||
}
|
||||
if m.ReplyTo != "" {
|
||||
if _, err = mail.ParseAddress(m.ReplyTo); err != nil {
|
||||
return nil, nil, fmt.Errorf("invalid reply-to")
|
||||
}
|
||||
headers.Set("Reply-To", m.ReplyTo)
|
||||
}
|
||||
headers.Set("Subject", mime.QEncoding.Encode("utf-8", m.Subject))
|
||||
headers.Set("Date", time.Now().Format(time.RFC1123Z))
|
||||
headers.Set("MIME-Version", "1.0")
|
||||
headers.Set("Message-ID", fmt.Sprintf("<%s@meovv.local>", strings.ToLower(randomBoundary())))
|
||||
for k, v := range m.Headers {
|
||||
if !allowedHeader.MatchString(k) || strings.ContainsAny(k+v, "\r\n") {
|
||||
return nil, nil, fmt.Errorf("header %q is not allowed", k)
|
||||
}
|
||||
headers.Set(k, v)
|
||||
}
|
||||
withAttachments := len(m.Attachments) > 0
|
||||
decodedBytes := int64(len([]byte(m.Text)) + len([]byte(m.HTML)))
|
||||
if withAttachments {
|
||||
headers.Set("Content-Type", fmt.Sprintf(`multipart/mixed; boundary="%s"`, boundary))
|
||||
} else {
|
||||
headers.Set("Content-Type", fmt.Sprintf(`multipart/alternative; boundary="%s"`, bodyBoundary))
|
||||
}
|
||||
keys := make([]string, 0, len(headers))
|
||||
for k := range headers {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, k := range keys {
|
||||
fmt.Fprintf(&out, "%s: %s\r\n", k, headers.Get(k))
|
||||
}
|
||||
out.WriteString("\r\n")
|
||||
if withAttachments {
|
||||
fmt.Fprintf(&out, "--%s\r\nContent-Type: multipart/alternative; boundary=\"%s\"\r\n\r\n", boundary, bodyBoundary)
|
||||
}
|
||||
writeAlternative(&out, bodyBoundary, m.Text, m.HTML)
|
||||
if withAttachments {
|
||||
for _, a := range m.Attachments {
|
||||
filename := filepath.Base(strings.ReplaceAll(a.Filename, "\\", "/"))
|
||||
if filename == "." || filename == "" {
|
||||
return nil, nil, fmt.Errorf("attachment filename is required")
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(a.ContentBase64)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("attachment %q is not valid base64", filename)
|
||||
}
|
||||
decodedBytes += int64(len(raw))
|
||||
if decodedBytes > maxBytes {
|
||||
return nil, nil, fmt.Errorf("decoded message exceeds %d bytes", maxBytes)
|
||||
}
|
||||
contentType := a.ContentType
|
||||
if contentType == "" {
|
||||
contentType = "application/octet-stream"
|
||||
}
|
||||
fmt.Fprintf(&out, "--%s\r\nContent-Type: %s; name=%q\r\nContent-Disposition: attachment; filename=%q\r\nContent-Transfer-Encoding: base64\r\n\r\n", boundary, contentType, filename, filename)
|
||||
writeBase64(&out, raw)
|
||||
out.WriteString("\r\n")
|
||||
}
|
||||
fmt.Fprintf(&out, "--%s--\r\n", boundary)
|
||||
}
|
||||
if decodedBytes > maxBytes {
|
||||
return nil, nil, fmt.Errorf("decoded message exceeds %d bytes", maxBytes)
|
||||
}
|
||||
return out.Bytes(), recipients, nil
|
||||
}
|
||||
|
||||
func writeAlternative(out *bytes.Buffer, boundary, text, html string) {
|
||||
if text == "" {
|
||||
text = stripHTML(html)
|
||||
}
|
||||
fmt.Fprintf(out, "--%s\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n", boundary)
|
||||
writeBase64(out, []byte(text))
|
||||
out.WriteString("\r\n")
|
||||
if html != "" {
|
||||
fmt.Fprintf(out, "--%s\r\nContent-Type: text/html; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n", boundary)
|
||||
writeBase64(out, []byte(html))
|
||||
out.WriteString("\r\n")
|
||||
}
|
||||
fmt.Fprintf(out, "--%s--\r\n", boundary)
|
||||
}
|
||||
func writeBase64(out *bytes.Buffer, data []byte) {
|
||||
encoded := base64.StdEncoding.EncodeToString(data)
|
||||
for len(encoded) > 76 {
|
||||
out.WriteString(encoded[:76])
|
||||
out.WriteString("\r\n")
|
||||
encoded = encoded[76:]
|
||||
}
|
||||
out.WriteString(encoded)
|
||||
}
|
||||
func randomBoundary() string {
|
||||
b := make([]byte, 18)
|
||||
_, _ = rand.Read(b)
|
||||
return base64.RawURLEncoding.EncodeToString(b)
|
||||
}
|
||||
func stripHTML(value string) string {
|
||||
return strings.TrimSpace(regexp.MustCompile(`<[^>]+>`).ReplaceAllString(value, " "))
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package mailer
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBuildMIMEAndProtectAttachmentFilename(t *testing.T) {
|
||||
raw, recipients, err := Build(Message{
|
||||
From: "MEOVV <sender@example.com>",
|
||||
To: []string{"Person <PERSON@example.net>"},
|
||||
Subject: "سلام — status",
|
||||
Text: "Hello",
|
||||
HTML: "<p>Hello</p>",
|
||||
Headers: map[string]string{"X-Campaign-ID": "welcome"},
|
||||
Attachments: []Attachment{{Filename: "../../private/statement.pdf", ContentType: "application/pdf", ContentBase64: base64.StdEncoding.EncodeToString([]byte("content"))}},
|
||||
}, 25<<20)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(recipients) != 1 || recipients[0] != "person@example.net" {
|
||||
t.Fatalf("unexpected recipients: %#v", recipients)
|
||||
}
|
||||
message := string(raw)
|
||||
if strings.Contains(message, "../") || !strings.Contains(message, `filename="statement.pdf"`) {
|
||||
t.Fatalf("unsafe or missing filename in MIME:\n%s", message)
|
||||
}
|
||||
if strings.Contains(message, "Bcc:") {
|
||||
t.Fatal("Bcc header leaked into MIME")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildRejectsHeaderInjectionAndDecodedLimit(t *testing.T) {
|
||||
_, _, err := Build(Message{From: "sender@example.com", To: []string{"to@example.net"}, Text: "hello", Headers: map[string]string{"X-Test": "ok\r\nBcc: stolen@example.net"}}, 1024)
|
||||
if err == nil {
|
||||
t.Fatal("expected injected header to be rejected")
|
||||
}
|
||||
_, _, err = Build(Message{From: "sender@example.com", To: []string{"to@example.net"}, Text: strings.Repeat("x", 1025)}, 1024)
|
||||
if err == nil || !strings.Contains(err.Error(), "decoded message") {
|
||||
t.Fatalf("expected decoded size limit, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildRequiresRecipient(t *testing.T) {
|
||||
_, _, err := Build(Message{From: "sender@example.com", Text: "hello"}, 1024)
|
||||
if err == nil {
|
||||
t.Fatal("expected recipient validation error")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package mailer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/smtp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Sender interface {
|
||||
Send(context.Context, string, []string, []byte) (string, error)
|
||||
}
|
||||
|
||||
type SMTP struct {
|
||||
Address, Username, Password string
|
||||
TLSConfig *tls.Config
|
||||
}
|
||||
|
||||
func (s SMTP) Send(ctx context.Context, from string, to []string, raw []byte) (string, error) {
|
||||
host, _, err := net.SplitHostPort(s.Address)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
dialer := net.Dialer{}
|
||||
conn, err := dialer.DialContext(ctx, "tcp", s.Address)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("connect to submission service: %w", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
c, err := smtp.NewClient(conn, host)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer c.Close()
|
||||
tlsConfig := s.TLSConfig
|
||||
if tlsConfig == nil {
|
||||
tlsConfig = &tls.Config{ServerName: host, MinVersion: tls.VersionTLS12}
|
||||
}
|
||||
if ok, _ := c.Extension("STARTTLS"); ok {
|
||||
if err = c.StartTLS(tlsConfig); err != nil {
|
||||
return "", fmt.Errorf("start TLS: %w", err)
|
||||
}
|
||||
} else {
|
||||
return "", fmt.Errorf("submission service did not offer STARTTLS")
|
||||
}
|
||||
if s.Username != "" {
|
||||
auth := smtp.PlainAuth("", s.Username, s.Password, host)
|
||||
if err = c.Auth(auth); err != nil {
|
||||
return "", fmt.Errorf("authenticate: %w", err)
|
||||
}
|
||||
}
|
||||
address, err := mailbox(from)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = c.Mail(address); err != nil {
|
||||
return "", err
|
||||
}
|
||||
for _, recipient := range to {
|
||||
if err = c.Rcpt(recipient); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
w, err := c.Data()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err = w.Write(raw); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = w.Close(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = c.Quit(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "smtp-accepted", nil
|
||||
}
|
||||
|
||||
func mailbox(value string) (string, error) {
|
||||
start := strings.LastIndex(value, "<")
|
||||
end := strings.LastIndex(value, ">")
|
||||
if start >= 0 && end > start {
|
||||
return strings.TrimSpace(value[start+1 : end]), nil
|
||||
}
|
||||
if strings.Contains(value, "@") {
|
||||
return strings.TrimSpace(value), nil
|
||||
}
|
||||
return "", fmt.Errorf("invalid mailbox")
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package stalwart
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
BaseURL string
|
||||
HTTP *http.Client
|
||||
}
|
||||
|
||||
func New(base string, insecure bool) *Client {
|
||||
transport := http.DefaultTransport.(*http.Transport).Clone()
|
||||
transport.TLSClientConfig = &tls.Config{MinVersion: tls.VersionTLS12, InsecureSkipVerify: insecure} // Internal Docker TLS; public TLS terminates at Caddy.
|
||||
return &Client{BaseURL: strings.TrimRight(base, "/"), HTTP: &http.Client{Timeout: 15 * time.Second, Transport: transport}}
|
||||
}
|
||||
|
||||
func (c *Client) Bootstrap(ctx context.Context, bootstrapURL, recoveryAdmin, hostname, domain string) ([]byte, error) {
|
||||
parts := strings.SplitN(recoveryAdmin, ":", 2)
|
||||
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
|
||||
return nil, fmt.Errorf("Stalwart recovery administrator is not configured")
|
||||
}
|
||||
payload := map[string]any{
|
||||
"using": []string{"urn:ietf:params:jmap:core", "urn:stalwart:jmap"},
|
||||
"methodCalls": []any{[]any{"x:Bootstrap/set", map[string]any{"update": map[string]any{"singleton": map[string]any{
|
||||
"serverHostname": hostname, "defaultDomain": domain, "requestTlsCertificate": true, "generateDkimKeys": true,
|
||||
"dataStore": map[string]any{"@type": "RocksDb", "path": "/var/lib/stalwart/"},
|
||||
"blobStore": map[string]any{"@type": "Default"}, "searchStore": map[string]any{"@type": "Default"}, "inMemoryStore": map[string]any{"@type": "Default"},
|
||||
"directory": map[string]any{"@type": "Internal"}, "tracer": map[string]any{"@type": "Console"}, "dnsServer": map[string]any{"@type": "Manual"},
|
||||
}}}, "bootstrap"}},
|
||||
}
|
||||
raw, _ := json.Marshal(payload)
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(bootstrapURL, "/")+"/api", bytes.NewReader(raw))
|
||||
req.SetBasicAuth(parts[0], parts[1])
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("configure Stalwart: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if resp.StatusCode/100 != 2 {
|
||||
return nil, fmt.Errorf("configure Stalwart: %s: %s", resp.Status, strings.TrimSpace(string(body)))
|
||||
}
|
||||
if bytes.Contains(body, []byte(`"type":"error"`)) || bytes.Contains(body, []byte(`"notUpdated"`)) {
|
||||
return nil, fmt.Errorf("Stalwart rejected bootstrap configuration: %s", strings.TrimSpace(string(body)))
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
func (c *Client) Ready(ctx context.Context) error {
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, c.BaseURL+"/.well-known/jmap", nil)
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode >= 500 {
|
||||
return fmt.Errorf("stalwart returned %s", resp.Status)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type Tokens struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
TokenType string `json:"token_type"`
|
||||
}
|
||||
|
||||
func (c *Client) Exchange(ctx context.Context, clientID, code, verifier, redirectURI string) (Tokens, error) {
|
||||
form := url.Values{"grant_type": {"authorization_code"}, "client_id": {clientID}, "code": {code}, "code_verifier": {verifier}, "redirect_uri": {redirectURI}}
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL+"/auth/token", strings.NewReader(form.Encode()))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return Tokens{}, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode/100 != 2 {
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
||||
return Tokens{}, fmt.Errorf("token exchange: %s: %s", resp.Status, strings.TrimSpace(string(body)))
|
||||
}
|
||||
var out Tokens
|
||||
err = json.NewDecoder(resp.Body).Decode(&out)
|
||||
return out, err
|
||||
}
|
||||
func (c *Client) Refresh(ctx context.Context, clientID, refreshToken string) (Tokens, error) {
|
||||
form := url.Values{"grant_type": {"refresh_token"}, "client_id": {clientID}, "refresh_token": {refreshToken}}
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL+"/auth/token", strings.NewReader(form.Encode()))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return Tokens{}, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode/100 != 2 {
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
||||
return Tokens{}, fmt.Errorf("token refresh: %s: %s", resp.Status, strings.TrimSpace(string(body)))
|
||||
}
|
||||
var out Tokens
|
||||
err = json.NewDecoder(resp.Body).Decode(&out)
|
||||
return out, err
|
||||
}
|
||||
func (c *Client) ProxyJMAP(ctx context.Context, token string, body []byte) (int, http.Header, []byte, error) {
|
||||
return c.proxy(ctx, token, "/jmap", body)
|
||||
}
|
||||
|
||||
// ProxyManagement keeps Stalwart's pre-1.0 management schema behind the MEOVV
|
||||
// adapter. The browser never receives an administrator token or direct access
|
||||
// to Stalwart's management endpoint.
|
||||
func (c *Client) ProxyManagement(ctx context.Context, token string, body []byte) (int, http.Header, []byte, error) {
|
||||
return c.proxy(ctx, token, "/api", body)
|
||||
}
|
||||
|
||||
func (c *Client) JMAPSession(ctx context.Context, token string) (int, http.Header, []byte, error) {
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, c.BaseURL+"/.well-known/jmap", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return 0, nil, nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
|
||||
return resp.StatusCode, resp.Header, raw, err
|
||||
}
|
||||
|
||||
func (c *Client) EventStream(ctx context.Context, token string) (*http.Response, error) {
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, c.BaseURL+"/jmap/eventsource/?types=Email,Mailbox&closeafter=45&ping=15", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
client := &http.Client{Transport: c.HTTP.Transport}
|
||||
return client.Do(req)
|
||||
}
|
||||
|
||||
func (c *Client) proxy(ctx context.Context, token, path string, body []byte) (int, http.Header, []byte, error) {
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL+path, bytes.NewReader(body))
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return 0, nil, nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, 32<<20))
|
||||
return resp.StatusCode, resp.Header, raw, err
|
||||
}
|
||||
@@ -0,0 +1,623 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
var ErrNotFound = errors.New("not found")
|
||||
|
||||
type Store struct{ db *sql.DB }
|
||||
|
||||
type APIKey struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Prefix string `json:"prefix"`
|
||||
Scopes []string `json:"scopes"`
|
||||
AllowedSenders []string `json:"allowed_senders"`
|
||||
RateLimit int `json:"rate_limit"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
|
||||
}
|
||||
|
||||
type Recipient struct {
|
||||
Address string `json:"address"`
|
||||
Status string `json:"status"`
|
||||
LastResponse string `json:"last_response,omitempty"`
|
||||
LastAttemptAt *time.Time `json:"last_attempt_at,omitempty"`
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
ID string `json:"id"`
|
||||
APIKeyID string `json:"api_key_id,omitempty"`
|
||||
Sender string `json:"sender"`
|
||||
Subject string `json:"subject"`
|
||||
Status string `json:"status"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
SubmittedAt time.Time `json:"submitted_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
StalwartID string `json:"stalwart_id,omitempty"`
|
||||
FailureReason string `json:"failure_reason,omitempty"`
|
||||
Recipients []Recipient `json:"recipients"`
|
||||
}
|
||||
|
||||
type MessageFilter struct {
|
||||
Status, Sender, Recipient, Cursor, APIKeyID string
|
||||
From, To *time.Time
|
||||
Limit int
|
||||
}
|
||||
|
||||
type WebhookEndpoint struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
URL string `json:"url"`
|
||||
Secret string `json:"-"`
|
||||
Events []string `json:"events"`
|
||||
Enabled bool `json:"enabled"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type WebhookDelivery struct {
|
||||
ID, EndpointID, EventID, EventType string
|
||||
Payload []byte
|
||||
Attempt int
|
||||
NextAttemptAt, CreatedAt time.Time
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
ID, Account string
|
||||
AccessToken, RefreshToken []byte
|
||||
ExpiresAt, SessionExpiresAt, CreatedAt, LastSeenAt time.Time
|
||||
}
|
||||
|
||||
func Open(path string) (*Store, error) {
|
||||
db, err := sql.Open("sqlite", path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
db.SetMaxOpenConns(1)
|
||||
if _, err = db.Exec(`PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;`); err != nil {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
s := &Store{db: db}
|
||||
if err = s.migrate(context.Background()); err != nil {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (s *Store) Close() error { return s.db.Close() }
|
||||
func (s *Store) Ping(ctx context.Context) error { return s.db.PingContext(ctx) }
|
||||
|
||||
func (s *Store) migrate(ctx context.Context) error {
|
||||
statements := []string{
|
||||
`CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at TEXT NOT NULL)`,
|
||||
`CREATE TABLE IF NOT EXISTS api_keys (id TEXT PRIMARY KEY, name TEXT NOT NULL, prefix TEXT NOT NULL, digest TEXT NOT NULL UNIQUE, scopes TEXT NOT NULL, allowed_senders TEXT NOT NULL, rate_limit INTEGER NOT NULL, created_at TEXT NOT NULL, last_used_at TEXT, revoked_at TEXT)`,
|
||||
`CREATE TABLE IF NOT EXISTS messages (id TEXT PRIMARY KEY, api_key_id TEXT, sender TEXT NOT NULL, subject TEXT NOT NULL, status TEXT NOT NULL, size_bytes INTEGER NOT NULL, submitted_at TEXT NOT NULL, updated_at TEXT NOT NULL, stalwart_id TEXT NOT NULL DEFAULT '', failure_reason TEXT NOT NULL DEFAULT '', FOREIGN KEY(api_key_id) REFERENCES api_keys(id))`,
|
||||
`CREATE TABLE IF NOT EXISTS message_recipients (message_id TEXT NOT NULL, address TEXT NOT NULL, status TEXT NOT NULL, last_response TEXT NOT NULL DEFAULT '', last_attempt_at TEXT, PRIMARY KEY(message_id,address), FOREIGN KEY(message_id) REFERENCES messages(id) ON DELETE CASCADE)`,
|
||||
`CREATE TABLE IF NOT EXISTS idempotency_keys (api_key_id TEXT NOT NULL, token TEXT NOT NULL, message_id TEXT NOT NULL, request_digest TEXT NOT NULL, expires_at TEXT NOT NULL, PRIMARY KEY(api_key_id,token), FOREIGN KEY(message_id) REFERENCES messages(id) ON DELETE CASCADE)`,
|
||||
`CREATE TABLE IF NOT EXISTS webhook_endpoints (id TEXT PRIMARY KEY, name TEXT NOT NULL, url TEXT NOT NULL, secret TEXT NOT NULL, events TEXT NOT NULL, enabled INTEGER NOT NULL DEFAULT 1, created_at TEXT NOT NULL)`,
|
||||
`CREATE TABLE IF NOT EXISTS webhook_deliveries (id TEXT PRIMARY KEY, endpoint_id TEXT NOT NULL, event_id TEXT NOT NULL, event_type TEXT NOT NULL, payload BLOB NOT NULL, attempt INTEGER NOT NULL DEFAULT 0, next_attempt_at TEXT NOT NULL, delivered_at TEXT, last_error TEXT NOT NULL DEFAULT '', created_at TEXT NOT NULL, FOREIGN KEY(endpoint_id) REFERENCES webhook_endpoints(id) ON DELETE CASCADE)`,
|
||||
`CREATE TABLE IF NOT EXISTS audit_events (id TEXT PRIMARY KEY, actor TEXT NOT NULL, action TEXT NOT NULL, target TEXT NOT NULL, detail TEXT NOT NULL, created_at TEXT NOT NULL)`,
|
||||
`CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, account TEXT NOT NULL, access_token BLOB NOT NULL, refresh_token BLOB NOT NULL, expires_at TEXT NOT NULL, session_expires_at TEXT NOT NULL, created_at TEXT NOT NULL, last_seen_at TEXT NOT NULL)`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_messages_submitted ON messages(submitted_at DESC)`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_messages_status_submitted ON messages(status, submitted_at DESC)`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_recipients_address ON message_recipients(address, message_id)`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_webhook_due ON webhook_deliveries(next_attempt_at) WHERE delivered_at IS NULL`,
|
||||
}
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
for _, stmt := range statements {
|
||||
if _, err = tx.ExecContext(ctx, stmt); err != nil {
|
||||
return fmt.Errorf("migration: %w", err)
|
||||
}
|
||||
}
|
||||
if err = ensureSessionExpiryColumn(ctx, tx); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, `PRAGMA optimize`); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func ensureSessionExpiryColumn(ctx context.Context, tx *sql.Tx) error {
|
||||
rows, err := tx.QueryContext(ctx, `PRAGMA table_info(sessions)`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
found := false
|
||||
for rows.Next() {
|
||||
var cid, notNull, primaryKey int
|
||||
var name, columnType string
|
||||
var defaultValue any
|
||||
if err = rows.Scan(&cid, &name, &columnType, ¬Null, &defaultValue, &primaryKey); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
if name == "session_expires_at" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if err = rows.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if found {
|
||||
return nil
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, `ALTER TABLE sessions ADD COLUMN session_expires_at TEXT`); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, `UPDATE sessions SET session_expires_at=expires_at WHERE session_expires_at IS NULL`)
|
||||
return err
|
||||
}
|
||||
|
||||
func DigestSecret(secret string) string {
|
||||
sum := sha256.Sum256([]byte(secret))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func (s *Store) CreateAPIKey(ctx context.Context, key APIKey, secret string) error {
|
||||
scopes, _ := json.Marshal(key.Scopes)
|
||||
senders, _ := json.Marshal(key.AllowedSenders)
|
||||
_, err := s.db.ExecContext(ctx, `INSERT INTO api_keys(id,name,prefix,digest,scopes,allowed_senders,rate_limit,created_at) VALUES(?,?,?,?,?,?,?,?)`, key.ID, key.Name, key.Prefix, DigestSecret(secret), string(scopes), string(senders), key.RateLimit, key.CreatedAt.UTC().Format(time.RFC3339Nano))
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) AuthenticateAPIKey(ctx context.Context, secret string) (APIKey, error) {
|
||||
var k APIKey
|
||||
var scopes, senders, created string
|
||||
var last sql.NullString
|
||||
err := s.db.QueryRowContext(ctx, `SELECT id,name,prefix,scopes,allowed_senders,rate_limit,created_at,last_used_at FROM api_keys WHERE digest=? AND revoked_at IS NULL`, DigestSecret(secret)).Scan(&k.ID, &k.Name, &k.Prefix, &scopes, &senders, &k.RateLimit, &created, &last)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return k, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return k, err
|
||||
}
|
||||
_ = json.Unmarshal([]byte(scopes), &k.Scopes)
|
||||
_ = json.Unmarshal([]byte(senders), &k.AllowedSenders)
|
||||
k.CreatedAt, _ = time.Parse(time.RFC3339Nano, created)
|
||||
if last.Valid {
|
||||
t, _ := time.Parse(time.RFC3339Nano, last.String)
|
||||
k.LastUsedAt = &t
|
||||
}
|
||||
_, _ = s.db.ExecContext(ctx, `UPDATE api_keys SET last_used_at=? WHERE id=?`, time.Now().UTC().Format(time.RFC3339Nano), k.ID)
|
||||
return k, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListAPIKeys(ctx context.Context) ([]APIKey, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT id,name,prefix,scopes,allowed_senders,rate_limit,created_at,last_used_at FROM api_keys WHERE revoked_at IS NULL ORDER BY created_at DESC`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []APIKey
|
||||
for rows.Next() {
|
||||
var key APIKey
|
||||
var scopes, senders, created string
|
||||
var last sql.NullString
|
||||
if err = rows.Scan(&key.ID, &key.Name, &key.Prefix, &scopes, &senders, &key.RateLimit, &created, &last); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = json.Unmarshal([]byte(scopes), &key.Scopes)
|
||||
_ = json.Unmarshal([]byte(senders), &key.AllowedSenders)
|
||||
key.CreatedAt, _ = time.Parse(time.RFC3339Nano, created)
|
||||
if last.Valid {
|
||||
t, _ := time.Parse(time.RFC3339Nano, last.String)
|
||||
key.LastUsedAt = &t
|
||||
}
|
||||
out = append(out, key)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) RevokeAPIKey(ctx context.Context, id string) error {
|
||||
result, err := s.db.ExecContext(ctx, `UPDATE api_keys SET revoked_at=? WHERE id=? AND revoked_at IS NULL`, time.Now().UTC().Format(time.RFC3339Nano), id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected, _ := result.RowsAffected(); affected == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) InsertMessage(ctx context.Context, m Message, idemToken, requestDigest string) (existing string, err error) {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if idemToken != "" {
|
||||
var priorID, priorDigest string
|
||||
err = tx.QueryRowContext(ctx, `SELECT message_id,request_digest FROM idempotency_keys WHERE api_key_id=? AND token=? AND expires_at>?`, m.APIKeyID, idemToken, time.Now().UTC().Format(time.RFC3339Nano)).Scan(&priorID, &priorDigest)
|
||||
if err == nil {
|
||||
if priorDigest != requestDigest {
|
||||
return "", fmt.Errorf("idempotency key reused with a different request")
|
||||
}
|
||||
return priorID, nil
|
||||
}
|
||||
if !errors.Is(err, sql.ErrNoRows) {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, `INSERT INTO messages(id,api_key_id,sender,subject,status,size_bytes,submitted_at,updated_at) VALUES(?,?,?,?,?,?,?,?)`, m.ID, m.APIKeyID, m.Sender, m.Subject, m.Status, m.SizeBytes, m.SubmittedAt.UTC().Format(time.RFC3339Nano), m.UpdatedAt.UTC().Format(time.RFC3339Nano))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
for _, r := range m.Recipients {
|
||||
if _, err = tx.ExecContext(ctx, `INSERT INTO message_recipients(message_id,address,status) VALUES(?,?,?)`, m.ID, strings.ToLower(r.Address), r.Status); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
if idemToken != "" {
|
||||
_, err = tx.ExecContext(ctx, `INSERT INTO idempotency_keys(api_key_id,token,message_id,request_digest,expires_at) VALUES(?,?,?,?,?)`, m.APIKeyID, idemToken, m.ID, requestDigest, time.Now().Add(24*time.Hour).UTC().Format(time.RFC3339Nano))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
return "", tx.Commit()
|
||||
}
|
||||
|
||||
func (s *Store) UpdateMessageStatus(ctx context.Context, id, status, reason, stalwartID string) error {
|
||||
_, err := s.db.ExecContext(ctx, `UPDATE messages SET status=?,failure_reason=?,stalwart_id=CASE WHEN ?='' THEN stalwart_id ELSE ? END,updated_at=? WHERE id=?`, status, reason, stalwartID, stalwartID, time.Now().UTC().Format(time.RFC3339Nano), id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) UpdateRecipient(ctx context.Context, id, address, status, response string, at time.Time) error {
|
||||
_, err := s.db.ExecContext(ctx, `UPDATE message_recipients SET status=?,last_response=?,last_attempt_at=? WHERE message_id=? AND address=?`, status, response, at.UTC().Format(time.RFC3339Nano), id, strings.ToLower(address))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.recalculate(ctx, id)
|
||||
}
|
||||
|
||||
func (s *Store) recalculate(ctx context.Context, id string) error {
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT status,COUNT(*) FROM message_recipients WHERE message_id=? GROUP BY status`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
counts := map[string]int{}
|
||||
total := 0
|
||||
for rows.Next() {
|
||||
var status string
|
||||
var n int
|
||||
if err = rows.Scan(&status, &n); err != nil {
|
||||
return err
|
||||
}
|
||||
counts[status] = n
|
||||
total += n
|
||||
}
|
||||
status := "processing"
|
||||
switch {
|
||||
case total > 0 && counts["delivered"] == total:
|
||||
status = "delivered"
|
||||
case counts["delivered"] > 0 && (counts["bounced"]+counts["failed"] > 0):
|
||||
status = "partial"
|
||||
case total > 0 && counts["bounced"] == total:
|
||||
status = "bounced"
|
||||
case total > 0 && counts["failed"] == total:
|
||||
status = "failed"
|
||||
case counts["deferred"] > 0:
|
||||
status = "deferred"
|
||||
case counts["queued"] == total:
|
||||
status = "queued"
|
||||
}
|
||||
return s.UpdateMessageStatus(ctx, id, status, "", "")
|
||||
}
|
||||
|
||||
func (s *Store) GetMessage(ctx context.Context, id string) (Message, error) {
|
||||
var m Message
|
||||
var submitted, updated string
|
||||
err := s.db.QueryRowContext(ctx, `SELECT id,COALESCE(api_key_id,''),sender,subject,status,size_bytes,submitted_at,updated_at,stalwart_id,failure_reason FROM messages WHERE id=?`, id).Scan(&m.ID, &m.APIKeyID, &m.Sender, &m.Subject, &m.Status, &m.SizeBytes, &submitted, &updated, &m.StalwartID, &m.FailureReason)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return m, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return m, err
|
||||
}
|
||||
m.SubmittedAt, _ = time.Parse(time.RFC3339Nano, submitted)
|
||||
m.UpdatedAt, _ = time.Parse(time.RFC3339Nano, updated)
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT address,status,last_response,last_attempt_at FROM message_recipients WHERE message_id=? ORDER BY address`, id)
|
||||
if err != nil {
|
||||
return m, err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var r Recipient
|
||||
var at sql.NullString
|
||||
if err = rows.Scan(&r.Address, &r.Status, &r.LastResponse, &at); err != nil {
|
||||
return m, err
|
||||
}
|
||||
if at.Valid {
|
||||
t, _ := time.Parse(time.RFC3339Nano, at.String)
|
||||
r.LastAttemptAt = &t
|
||||
}
|
||||
m.Recipients = append(m.Recipients, r)
|
||||
}
|
||||
return m, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) ListMessages(ctx context.Context, f MessageFilter) ([]Message, string, error) {
|
||||
if f.Limit <= 0 || f.Limit > 100 {
|
||||
f.Limit = 25
|
||||
}
|
||||
args := []any{}
|
||||
where := []string{"1=1"}
|
||||
if f.APIKeyID != "" {
|
||||
where = append(where, "m.api_key_id=?")
|
||||
args = append(args, f.APIKeyID)
|
||||
}
|
||||
if f.Status != "" {
|
||||
where = append(where, "m.status=?")
|
||||
args = append(args, f.Status)
|
||||
}
|
||||
if f.Sender != "" {
|
||||
where = append(where, "m.sender=?")
|
||||
args = append(args, strings.ToLower(f.Sender))
|
||||
}
|
||||
if f.Recipient != "" {
|
||||
where = append(where, "EXISTS(SELECT 1 FROM message_recipients mr WHERE mr.message_id=m.id AND mr.address=?)")
|
||||
args = append(args, strings.ToLower(f.Recipient))
|
||||
}
|
||||
if f.From != nil {
|
||||
where = append(where, "m.submitted_at>=?")
|
||||
args = append(args, f.From.UTC().Format(time.RFC3339Nano))
|
||||
}
|
||||
if f.To != nil {
|
||||
where = append(where, "m.submitted_at<=?")
|
||||
args = append(args, f.To.UTC().Format(time.RFC3339Nano))
|
||||
}
|
||||
if f.Cursor != "" {
|
||||
where = append(where, "m.submitted_at<?")
|
||||
args = append(args, f.Cursor)
|
||||
}
|
||||
args = append(args, f.Limit+1)
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT m.id FROM messages m WHERE `+strings.Join(where, " AND ")+` ORDER BY m.submitted_at DESC LIMIT ?`, args...)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
defer rows.Close()
|
||||
ids := []string{}
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if err = rows.Scan(&id); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
next := ""
|
||||
if len(ids) > f.Limit {
|
||||
last, err := s.GetMessage(ctx, ids[f.Limit-1])
|
||||
if err == nil {
|
||||
next = last.SubmittedAt.UTC().Format(time.RFC3339Nano)
|
||||
}
|
||||
ids = ids[:f.Limit]
|
||||
}
|
||||
out := make([]Message, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
m, err := s.GetMessage(ctx, id)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
out = append(out, m)
|
||||
}
|
||||
return out, next, nil
|
||||
}
|
||||
|
||||
func (s *Store) SetSetting(ctx context.Context, key string, value any) error {
|
||||
raw, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.db.ExecContext(ctx, `INSERT INTO settings(key,value,updated_at) VALUES(?,?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value,updated_at=excluded.updated_at`, key, string(raw), time.Now().UTC().Format(time.RFC3339Nano))
|
||||
return err
|
||||
}
|
||||
func (s *Store) GetSetting(ctx context.Context, key string, dst any) error {
|
||||
var raw string
|
||||
err := s.db.QueryRowContext(ctx, `SELECT value FROM settings WHERE key=?`, key).Scan(&raw)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return json.Unmarshal([]byte(raw), dst)
|
||||
}
|
||||
|
||||
func (s *Store) EnqueueEvent(ctx context.Context, eventID, eventType string, payload []byte, now time.Time) error {
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT id FROM webhook_endpoints WHERE enabled=1 AND EXISTS(SELECT 1 FROM json_each(events) WHERE value=?)`, eventType)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var endpointIDs []string
|
||||
for rows.Next() {
|
||||
var endpointID string
|
||||
if err = rows.Scan(&endpointID); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
endpointIDs = append(endpointIDs, endpointID)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
if err = rows.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, endpointID := range endpointIDs {
|
||||
id := eventID + "_" + endpointID
|
||||
if _, err = s.db.ExecContext(ctx, `INSERT OR IGNORE INTO webhook_deliveries(id,endpoint_id,event_id,event_type,payload,next_attempt_at,created_at) VALUES(?,?,?,?,?,?,?)`, id, endpointID, eventID, eventType, payload, now.UTC().Format(time.RFC3339Nano), now.UTC().Format(time.RFC3339Nano)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s *Store) DueWebhooks(ctx context.Context, now time.Time, limit int) ([]WebhookDelivery, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT id,endpoint_id,event_id,event_type,payload,attempt,next_attempt_at,created_at FROM webhook_deliveries WHERE delivered_at IS NULL AND next_attempt_at<=? ORDER BY next_attempt_at LIMIT ?`, now.UTC().Format(time.RFC3339Nano), limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []WebhookDelivery
|
||||
for rows.Next() {
|
||||
var d WebhookDelivery
|
||||
var next, created string
|
||||
if err = rows.Scan(&d.ID, &d.EndpointID, &d.EventID, &d.EventType, &d.Payload, &d.Attempt, &next, &created); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d.NextAttemptAt, _ = time.Parse(time.RFC3339Nano, next)
|
||||
d.CreatedAt, _ = time.Parse(time.RFC3339Nano, created)
|
||||
out = append(out, d)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
func (s *Store) GetWebhookEndpoint(ctx context.Context, id string) (WebhookEndpoint, error) {
|
||||
var e WebhookEndpoint
|
||||
var events, created string
|
||||
var enabled int
|
||||
err := s.db.QueryRowContext(ctx, `SELECT id,name,url,secret,events,enabled,created_at FROM webhook_endpoints WHERE id=?`, id).Scan(&e.ID, &e.Name, &e.URL, &e.Secret, &events, &enabled, &created)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return e, ErrNotFound
|
||||
}
|
||||
_ = json.Unmarshal([]byte(events), &e.Events)
|
||||
e.Enabled = enabled == 1
|
||||
e.CreatedAt, _ = time.Parse(time.RFC3339Nano, created)
|
||||
return e, err
|
||||
}
|
||||
|
||||
func (s *Store) CreateWebhookEndpoint(ctx context.Context, endpoint WebhookEndpoint) error {
|
||||
events, _ := json.Marshal(endpoint.Events)
|
||||
_, err := s.db.ExecContext(ctx, `INSERT INTO webhook_endpoints(id,name,url,secret,events,enabled,created_at) VALUES(?,?,?,?,?,?,?)`, endpoint.ID, endpoint.Name, endpoint.URL, endpoint.Secret, string(events), boolInt(endpoint.Enabled), endpoint.CreatedAt.UTC().Format(time.RFC3339Nano))
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) ListWebhookEndpoints(ctx context.Context) ([]WebhookEndpoint, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT id,name,url,events,enabled,created_at FROM webhook_endpoints ORDER BY created_at DESC`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []WebhookEndpoint
|
||||
for rows.Next() {
|
||||
var endpoint WebhookEndpoint
|
||||
var events, created string
|
||||
var enabled int
|
||||
if err = rows.Scan(&endpoint.ID, &endpoint.Name, &endpoint.URL, &events, &enabled, &created); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = json.Unmarshal([]byte(events), &endpoint.Events)
|
||||
endpoint.Enabled = enabled == 1
|
||||
endpoint.CreatedAt, _ = time.Parse(time.RFC3339Nano, created)
|
||||
out = append(out, endpoint)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) DeleteWebhookEndpoint(ctx context.Context, id string) error {
|
||||
result, err := s.db.ExecContext(ctx, `DELETE FROM webhook_endpoints WHERE id=?`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected, _ := result.RowsAffected(); affected == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s *Store) CompleteWebhook(ctx context.Context, id string, delivered bool, next time.Time, lastErr string) error {
|
||||
if delivered {
|
||||
_, err := s.db.ExecContext(ctx, `UPDATE webhook_deliveries SET attempt=attempt+1,delivered_at=?,last_error='' WHERE id=?`, time.Now().UTC().Format(time.RFC3339Nano), id)
|
||||
return err
|
||||
}
|
||||
_, err := s.db.ExecContext(ctx, `UPDATE webhook_deliveries SET attempt=attempt+1,next_attempt_at=?,last_error=? WHERE id=?`, next.UTC().Format(time.RFC3339Nano), lastErr, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) Stats(ctx context.Context) (map[string]any, error) {
|
||||
out := map[string]any{}
|
||||
for key, query := range map[string]string{"messages_24h": `SELECT COUNT(*) FROM messages WHERE submitted_at>=datetime('now','-1 day')`, "queued": `SELECT COUNT(*) FROM messages WHERE status IN ('queued','processing','deferred')`, "failed_webhooks": `SELECT COUNT(*) FROM webhook_deliveries WHERE delivered_at IS NULL AND attempt>0`, "api_keys": `SELECT COUNT(*) FROM api_keys WHERE revoked_at IS NULL`} {
|
||||
var n int
|
||||
if err := s.db.QueryRowContext(ctx, query).Scan(&n); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[key] = n
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *Store) Cleanup(ctx context.Context, messageBefore, webhookBefore, auditBefore time.Time) error {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
for _, q := range []struct {
|
||||
sql string
|
||||
arg time.Time
|
||||
}{{`DELETE FROM messages WHERE submitted_at<?`, messageBefore}, {`DELETE FROM webhook_deliveries WHERE created_at<?`, webhookBefore}, {`DELETE FROM audit_events WHERE created_at<?`, auditBefore}, {`DELETE FROM idempotency_keys WHERE expires_at<?`, time.Now()}, {`DELETE FROM sessions WHERE session_expires_at<?`, time.Now()}} {
|
||||
if _, err = tx.ExecContext(ctx, q.sql, q.arg.UTC().Format(time.RFC3339Nano)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (s *Store) CreateSession(ctx context.Context, v Session) error {
|
||||
_, err := s.db.ExecContext(ctx, `INSERT INTO sessions(id,account,access_token,refresh_token,expires_at,session_expires_at,created_at,last_seen_at) VALUES(?,?,?,?,?,?,?,?)`, v.ID, v.Account, v.AccessToken, v.RefreshToken, v.ExpiresAt.UTC().Format(time.RFC3339Nano), v.SessionExpiresAt.UTC().Format(time.RFC3339Nano), v.CreatedAt.UTC().Format(time.RFC3339Nano), v.LastSeenAt.UTC().Format(time.RFC3339Nano))
|
||||
return err
|
||||
}
|
||||
func (s *Store) GetSession(ctx context.Context, id string) (Session, error) {
|
||||
var v Session
|
||||
var expires, sessionExpires, created, seen string
|
||||
err := s.db.QueryRowContext(ctx, `SELECT id,account,access_token,refresh_token,expires_at,session_expires_at,created_at,last_seen_at FROM sessions WHERE id=? AND session_expires_at>?`, id, time.Now().UTC().Format(time.RFC3339Nano)).Scan(&v.ID, &v.Account, &v.AccessToken, &v.RefreshToken, &expires, &sessionExpires, &created, &seen)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return v, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
v.ExpiresAt, _ = time.Parse(time.RFC3339Nano, expires)
|
||||
v.SessionExpiresAt, _ = time.Parse(time.RFC3339Nano, sessionExpires)
|
||||
v.CreatedAt, _ = time.Parse(time.RFC3339Nano, created)
|
||||
v.LastSeenAt, _ = time.Parse(time.RFC3339Nano, seen)
|
||||
_, _ = s.db.ExecContext(ctx, `UPDATE sessions SET last_seen_at=? WHERE id=?`, time.Now().UTC().Format(time.RFC3339Nano), id)
|
||||
return v, nil
|
||||
}
|
||||
func (s *Store) UpdateSessionTokens(ctx context.Context, id string, access, refresh []byte, expiresAt time.Time) error {
|
||||
_, err := s.db.ExecContext(ctx, `UPDATE sessions SET access_token=?,refresh_token=?,expires_at=?,last_seen_at=? WHERE id=?`, access, refresh, expiresAt.UTC().Format(time.RFC3339Nano), time.Now().UTC().Format(time.RFC3339Nano), id)
|
||||
return err
|
||||
}
|
||||
func (s *Store) DeleteSession(ctx context.Context, id string) error {
|
||||
_, err := s.db.ExecContext(ctx, `DELETE FROM sessions WHERE id=?`, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) Audit(ctx context.Context, id, actor, action, target string, detail any) error {
|
||||
raw, _ := json.Marshal(detail)
|
||||
_, err := s.db.ExecContext(ctx, `INSERT INTO audit_events(id,actor,action,target,detail,created_at) VALUES(?,?,?,?,?,?)`, id, actor, action, target, string(raw), time.Now().UTC().Format(time.RFC3339Nano))
|
||||
return err
|
||||
}
|
||||
|
||||
func boolInt(value bool) int {
|
||||
if value {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func testStore(t *testing.T) *Store {
|
||||
t.Helper()
|
||||
db, err := Open(filepath.Join(t.TempDir(), "test.sqlite"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
return db
|
||||
}
|
||||
|
||||
func TestAPIKeyHashingListingAndRevocation(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db := testStore(t)
|
||||
key := APIKey{ID: "key_1", Name: "Production", Prefix: "meovv_abc", Scopes: []string{"messages.send"}, AllowedSenders: []string{"*@example.com"}, RateLimit: 60, CreatedAt: time.Now()}
|
||||
if err := db.CreateAPIKey(ctx, key, "meovv_secret"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := db.AuthenticateAPIKey(ctx, "meovv_secret")
|
||||
if err != nil || got.ID != key.ID || len(got.Scopes) != 1 {
|
||||
t.Fatalf("authenticate = %#v, %v", got, err)
|
||||
}
|
||||
keys, err := db.ListAPIKeys(ctx)
|
||||
if err != nil || len(keys) != 1 {
|
||||
t.Fatalf("list = %#v, %v", keys, err)
|
||||
}
|
||||
if err = db.RevokeAPIKey(ctx, key.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.AuthenticateAPIKey(ctx, "meovv_secret"); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("revoked key authenticated: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdempotencyAndRecipientStateRollup(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db := testStore(t)
|
||||
now := time.Now().UTC()
|
||||
key := APIKey{ID: "key_1", Name: "test", Prefix: "meovv_test", Scopes: []string{"messages.send"}, AllowedSenders: []string{"sender@example.com"}, RateLimit: 60, CreatedAt: now}
|
||||
if err := db.CreateAPIKey(ctx, key, "secret"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
message := Message{ID: "msg_1", APIKeyID: key.ID, Sender: "sender@example.com", Subject: "test", Status: "queued", SubmittedAt: now, UpdatedAt: now, Recipients: []Recipient{{Address: "a@example.net", Status: "queued"}, {Address: "b@example.net", Status: "queued"}}}
|
||||
if prior, err := db.InsertMessage(ctx, message, "retry-token", "digest-a"); err != nil || prior != "" {
|
||||
t.Fatalf("insert = %q, %v", prior, err)
|
||||
}
|
||||
duplicate := message
|
||||
duplicate.ID = "msg_2"
|
||||
if prior, err := db.InsertMessage(ctx, duplicate, "retry-token", "digest-a"); err != nil || prior != "msg_1" {
|
||||
t.Fatalf("replay = %q, %v", prior, err)
|
||||
}
|
||||
if _, err := db.InsertMessage(ctx, duplicate, "retry-token", "digest-b"); err == nil {
|
||||
t.Fatal("expected conflicting idempotency digest")
|
||||
}
|
||||
if err := db.UpdateRecipient(ctx, "msg_1", "a@example.net", "delivered", "250 ok", now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.UpdateRecipient(ctx, "msg_1", "b@example.net", "bounced", "550 no", now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := db.GetMessage(ctx, "msg_1")
|
||||
if err != nil || got.Status != "partial" {
|
||||
t.Fatalf("status = %q, %v", got.Status, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebhookEndpointLifecycle(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db := testStore(t)
|
||||
endpoint := WebhookEndpoint{ID: "wh_1", Name: "Billing", URL: "https://example.com/hook", Secret: "secret", Events: []string{"message.delivered"}, Enabled: true, CreatedAt: time.Now()}
|
||||
if err := db.CreateWebhookEndpoint(ctx, endpoint); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, err := db.ListWebhookEndpoints(ctx)
|
||||
if err != nil || len(items) != 1 || items[0].Secret != "" {
|
||||
t.Fatalf("list = %#v, %v", items, err)
|
||||
}
|
||||
if err = db.DeleteWebhookEndpoint(ctx, endpoint.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/meovv-mail/meovv-mail/internal/app"
|
||||
"github.com/meovv-mail/meovv-mail/internal/store"
|
||||
)
|
||||
|
||||
type Dispatcher struct {
|
||||
Store *store.Store
|
||||
Cipher app.TokenCipher
|
||||
HTTP *http.Client
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
func New(s *store.Store, cipher app.TokenCipher) *Dispatcher {
|
||||
return &Dispatcher{Store: s, Cipher: cipher, HTTP: &http.Client{Timeout: 10 * time.Second}, Now: time.Now}
|
||||
}
|
||||
|
||||
func Signature(secret string, timestamp int64, body []byte) string {
|
||||
mac := hmac.New(sha256.New, []byte(secret))
|
||||
fmt.Fprintf(mac, "%d.", timestamp)
|
||||
mac.Write(body)
|
||||
return hex.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
func Verify(secret, signature, timestamp string, body []byte, maxSkew time.Duration) bool {
|
||||
unix, err := strconv.ParseInt(timestamp, 10, 64)
|
||||
if err != nil || time.Since(time.Unix(unix, 0)) > maxSkew || time.Until(time.Unix(unix, 0)) > maxSkew {
|
||||
return false
|
||||
}
|
||||
expected := Signature(secret, unix, body)
|
||||
return hmac.Equal([]byte(expected), []byte(strings.ToLower(signature)))
|
||||
}
|
||||
|
||||
func (d *Dispatcher) Run(ctx context.Context) {
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
d.DispatchOnce(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
func (d *Dispatcher) DispatchOnce(ctx context.Context) {
|
||||
items, err := d.Store.DueWebhooks(ctx, d.Now(), 25)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, item := range items {
|
||||
d.dispatch(ctx, item)
|
||||
}
|
||||
}
|
||||
func (d *Dispatcher) dispatch(ctx context.Context, item store.WebhookDelivery) {
|
||||
endpoint, err := d.Store.GetWebhookEndpoint(ctx, item.EndpointID)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if err = ValidatePublicURL(ctx, endpoint.URL); err != nil {
|
||||
d.fail(ctx, item, err)
|
||||
return
|
||||
}
|
||||
secretBytes, err := base64.RawStdEncoding.DecodeString(endpoint.Secret)
|
||||
if err != nil {
|
||||
d.fail(ctx, item, fmt.Errorf("decode webhook secret: %w", err))
|
||||
return
|
||||
}
|
||||
secret, err := d.Cipher.Decrypt(secretBytes)
|
||||
if err != nil {
|
||||
d.fail(ctx, item, fmt.Errorf("decrypt webhook secret: %w", err))
|
||||
return
|
||||
}
|
||||
timestamp := d.Now().Unix()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint.URL, bytes.NewReader(item.Payload))
|
||||
if err != nil {
|
||||
d.fail(ctx, item, err)
|
||||
return
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("User-Agent", "MEOVV-Mail-Webhooks/1.0")
|
||||
req.Header.Set("X-MEOVV-Event-ID", item.EventID)
|
||||
req.Header.Set("X-MEOVV-Event", item.EventType)
|
||||
req.Header.Set("X-MEOVV-Timestamp", strconv.FormatInt(timestamp, 10))
|
||||
req.Header.Set("X-MEOVV-Signature", "v1="+Signature(secret, timestamp, item.Payload))
|
||||
resp, err := d.HTTP.Do(req)
|
||||
if err == nil {
|
||||
io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
|
||||
_ = d.Store.CompleteWebhook(ctx, item.ID, true, time.Time{}, "")
|
||||
return
|
||||
}
|
||||
err = fmt.Errorf("endpoint returned %s", resp.Status)
|
||||
}
|
||||
d.fail(ctx, item, err)
|
||||
}
|
||||
func (d *Dispatcher) fail(ctx context.Context, item store.WebhookDelivery, err error) {
|
||||
age := d.Now().Sub(item.CreatedAt)
|
||||
if age >= 24*time.Hour {
|
||||
_ = d.Store.CompleteWebhook(ctx, item.ID, false, d.Now().Add(365*24*time.Hour), "retry window expired: "+err.Error())
|
||||
return
|
||||
}
|
||||
delay := time.Duration(math.Min(3600, math.Pow(2, float64(item.Attempt))*15)) * time.Second
|
||||
_ = d.Store.CompleteWebhook(ctx, item.ID, false, d.Now().Add(delay), err.Error())
|
||||
}
|
||||
|
||||
func ValidatePublicURL(ctx context.Context, raw string) error {
|
||||
parsed, err := url.Parse(raw)
|
||||
if err != nil || parsed.Scheme != "https" || parsed.Hostname() == "" {
|
||||
return fmt.Errorf("webhook URL must be public HTTPS")
|
||||
}
|
||||
ips, err := net.DefaultResolver.LookupIP(ctx, "ip", parsed.Hostname())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, ip := range ips {
|
||||
if ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsUnspecified() || ip.IsMulticast() {
|
||||
return fmt.Errorf("webhook URL resolves to a non-public address")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/meovv-mail/meovv-mail/internal/store"
|
||||
)
|
||||
|
||||
func TestSignatureAndVerification(t *testing.T) {
|
||||
body := []byte(`{"id":"evt_1"}`)
|
||||
timestamp := time.Now().Unix()
|
||||
signature := Signature("secret", timestamp, body)
|
||||
if !Verify("secret", signature, fmtInt(timestamp), body, 5*time.Minute) {
|
||||
t.Fatal("valid signature was rejected")
|
||||
}
|
||||
if Verify("wrong", signature, fmtInt(timestamp), body, 5*time.Minute) {
|
||||
t.Fatal("wrong secret was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetryScheduleStartsAtFifteenSeconds(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, err := store.Open(filepath.Join(t.TempDir(), "test.sqlite"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
now := time.Date(2026, 8, 12, 10, 0, 0, 0, time.UTC)
|
||||
endpoint := store.WebhookEndpoint{ID: "wh_1", Name: "test", URL: "https://example.com", Secret: "secret", Events: []string{"message.failed"}, Enabled: true, CreatedAt: now}
|
||||
if err = db.CreateWebhookEndpoint(ctx, endpoint); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = db.EnqueueEvent(ctx, "evt_1", "message.failed", []byte(`{}`), now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, err := db.DueWebhooks(ctx, now, 10)
|
||||
if err != nil || len(items) != 1 {
|
||||
t.Fatalf("due = %#v, %v", items, err)
|
||||
}
|
||||
dispatcher := &Dispatcher{Store: db, Now: func() time.Time { return now }}
|
||||
dispatcher.fail(ctx, items[0], context.DeadlineExceeded)
|
||||
if due, _ := db.DueWebhooks(ctx, now.Add(14*time.Second), 10); len(due) != 0 {
|
||||
t.Fatal("delivery retried too early")
|
||||
}
|
||||
if due, _ := db.DueWebhooks(ctx, now.Add(15*time.Second), 10); len(due) != 1 {
|
||||
t.Fatal("delivery was not scheduled after 15 seconds")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRejectsPrivateWebhookTargets(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
if err := ValidatePublicURL(ctx, "http://example.com/hook"); err == nil {
|
||||
t.Fatal("plain HTTP was accepted")
|
||||
}
|
||||
if err := ValidatePublicURL(ctx, "https://127.0.0.1/hook"); err == nil {
|
||||
t.Fatal("loopback target was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func fmtInt(value int64) string {
|
||||
return strconv.FormatInt(value, 10)
|
||||
}
|
||||
Reference in new issue
Block a user