parsimony/internal/app/app.go
tgiachi dca9117a2e feat(app): sign outgoing mail with the configured DKIM keys
- Load the keys at startup and refuse to start on a broken one
- Sign every outgoing message, confirmation mail included, with the key of its From domain
- Send unsigned when the domain has no key
2026-11-09 19:59:57 +01:00

189 lines
4.9 KiB
Go

// Package app wires the store, router, LMTP server and REST API together.
package app
import (
"context"
"errors"
"fmt"
"log"
"net"
"net/http"
"os"
"sync"
"time"
"github.com/emersion/go-smtp"
"codeberg.org/squidd/parsimony/internal/adminui"
"codeberg.org/squidd/parsimony/internal/api"
"codeberg.org/squidd/parsimony/internal/config"
"codeberg.org/squidd/parsimony/internal/dkimsign"
"codeberg.org/squidd/parsimony/internal/ingest"
"codeberg.org/squidd/parsimony/internal/outbound"
"codeberg.org/squidd/parsimony/internal/queue"
"codeberg.org/squidd/parsimony/internal/router"
"codeberg.org/squidd/parsimony/internal/store"
"codeberg.org/squidd/parsimony/internal/web"
)
// nowFunc is the clock of the store (queue schedules, token expiry). Tests move it.
var nowFunc = time.Now
// App is a running daemon.
type App struct {
// LMTPAddr and APIAddr are the addresses actually bound.
// APIAddr is empty when the API is disabled.
LMTPAddr string
APIAddr string
WebAddr string // empty when the public web is disabled
store *store.Store
lmtp *smtp.Server
lns []net.Listener // closed by Close so Serve returns even if Close wins the race with it
web *http.Server
pub *http.Server
wg sync.WaitGroup
stop context.CancelFunc // stops the queue worker
once sync.Once
}
// releaser lets the API approve held messages through the router.
type releaser struct{ rt *router.Router }
func (r releaser) Release(_ context.Context, id int64) error { return r.rt.Release(id) }
// Start opens the database and begins serving. The REST API runs only when
// apiToken is not empty.
func Start(cfg config.Config, apiToken string) (*App, error) {
// Load the signing keys first: a broken key stops the daemon now, not at the first send.
var sign func([]byte) ([]byte, error)
if len(cfg.DKIM) > 0 {
keys := make([]dkimsign.Key, 0, len(cfg.DKIM))
for _, k := range cfg.DKIM {
key, err := dkimsign.LoadKey(k.Domain, k.Selector, k.KeyFile)
if err != nil {
return nil, fmt.Errorf("dkim key for %s: %w", k.Domain, err)
}
keys = append(keys, key)
}
signer, err := dkimsign.New(keys)
if err != nil {
return nil, err
}
sign = signer.Sign
}
st, err := store.Open(cfg.DB)
if err != nil {
return nil, fmt.Errorf("store: %w", err)
}
st.Now = nowFunc
a := &App{store: st}
rt := router.New(st)
rt.BaseURL = cfg.BaseURL
worker := &queue.Worker{
Store: st,
Sender: &outbound.SMTPRelay{Addr: cfg.Relay.Addr},
Concurrency: cfg.Relay.Concurrency,
Sign: sign,
}
rt.OnEnqueue = worker.Wake
a.lmtp = ingest.NewServer(rt)
if cfg.LMTP.Network == "unix" {
os.Remove(cfg.LMTP.Addr)
}
lmtpLn, err := net.Listen(cfg.LMTP.Network, cfg.LMTP.Addr)
if err != nil {
st.Close()
return nil, fmt.Errorf("listen lmtp: %w", err)
}
a.LMTPAddr = lmtpLn.Addr().String()
a.lns = append(a.lns, lmtpLn)
var apiLn net.Listener
if apiToken != "" {
apiLn, err = net.Listen("tcp", cfg.API.Listen)
if err != nil {
lmtpLn.Close()
st.Close()
return nil, fmt.Errorf("listen api: %w", err)
}
a.APIAddr = apiLn.Addr().String()
a.lns = append(a.lns, apiLn)
// The admin UI and the API share a listener, so the UI needs no CORS.
mux := http.NewServeMux()
mux.Handle("/api/", api.New(st, apiToken, releaser{rt}))
mux.Handle("/", adminui.Embedded())
a.web = &http.Server{Handler: mux, ReadHeaderTimeout: 10 * time.Second}
}
var pubLn net.Listener
if cfg.Web.Listen != "" {
pubLn, err = net.Listen("tcp", cfg.Web.Listen)
if err != nil {
for _, ln := range a.lns {
ln.Close()
}
st.Close()
return nil, fmt.Errorf("listen web: %w", err)
}
a.WebAddr = pubLn.Addr().String()
a.lns = append(a.lns, pubLn)
a.pub = &http.Server{Handler: web.New(st, rt), ReadHeaderTimeout: 10 * time.Second}
}
var workerCtx context.Context
workerCtx, a.stop = context.WithCancel(context.Background())
a.wg.Add(1)
go func() {
defer a.wg.Done()
worker.Run(workerCtx)
}()
a.wg.Add(1)
go func() {
defer a.wg.Done()
if err := a.lmtp.Serve(lmtpLn); err != nil && !errors.Is(err, smtp.ErrServerClosed) && !errors.Is(err, net.ErrClosed) {
log.Printf("lmtp: %v", err)
}
}()
if a.web != nil {
a.wg.Add(1)
go func() {
defer a.wg.Done()
if err := a.web.Serve(apiLn); err != nil && !errors.Is(err, http.ErrServerClosed) && !errors.Is(err, net.ErrClosed) {
log.Printf("api: %v", err)
}
}()
}
if a.pub != nil {
a.wg.Add(1)
go func() {
defer a.wg.Done()
if err := a.pub.Serve(pubLn); err != nil && !errors.Is(err, http.ErrServerClosed) && !errors.Is(err, net.ErrClosed) {
log.Printf("web: %v", err)
}
}()
}
return a, nil
}
// Close stops the servers and closes the database. It is safe to call twice.
func (a *App) Close() {
a.once.Do(func() {
for _, ln := range a.lns {
ln.Close()
}
a.lmtp.Close()
if a.web != nil {
a.web.Close()
}
if a.pub != nil {
a.pub.Close()
}
a.stop() // in-flight sends are interrupted and stay queued
a.wg.Wait()
a.store.Close()
})
}