Files
superbrain/internal/mailer/mailer.go
T
Andrew S Erwin f372936894
release gate / check (push) Failing after 7m28s
Add deployment tiers, self-service password reset, and Authelia SSO fixes
Product tiers (decided 2026-10-26): TIER=core|multi is the deployment knob.
core (federated install, paying customers) derives AUTH_MODE=oidc with
signup/bootstrap off - Authelia is the only way in and accounts are
provisioned upstream (Superpanel -> LDAP -> Authelia). multi (hosted
self-service) derives AUTH_MODE=password: signup, password login and
SMTP-backed self-reset, with the OIDC bridge refused even when variables
are set. Explicit AUTH_MODE/SIGNUP_ENABLED/ALLOW_BOOTSTRAP_SIGNUP always
override the tier; invalid values fail startup instead of falling back.
Go enforces every gate at the API; the web UI mirrors it (conditional
credentials provider, SSO-only login page, signup/reset redirects).

Authelia-only bootstrap: ProvisionExternal grants ADMIN to ADMIN_EMAILS
addresses at first SSO login, and --seed accepts SEED_SUBJECT to link a
pre-existing password account offline - the only path when 409 'account
link required' meets a deployment where nobody can password-login to call
oidc-link.

Self-service password reset (multi tier): POST /api/password/forgot and
/api/password/reset with hashed single-use 30-minute tokens
(PasswordResetToken, migration 011 + schema.sql), enumeration-safe
identical 200s, per-IP rate limits, tokenVersion bump on success (all
prior sessions revoked), OIDC-only accounts excluded by design. New
internal/mailer sends via netguard+outbound budget; NETGUARD_TRUSTED_HOSTS
pins operator-chosen relays that resolve privately (split-horizon DNS)
without the blanket INTEGRATIONS_ALLOW_PRIVATE switch. Web gains
/forgot-password and /reset-password pages and a login-page link.

Federated install fixes: the Authelia client now registers a
claims_policy putting email in the ID token (production AccessDenied -
Auth.js builds OIDC profiles exclusively from ID-token claims), config is
validated before restarting the shared Authelia, uninstall removes the
claims block marker-safely, and generated .env switches to TIER=core with
a password-less admin seed.

Tests: tier derivation/override unit tests, mode and tier integration
tests (403 gates, bridge refusal, ADMIN_EMAILS promotion, offline link),
reset-flow integration tests against a loopback SMTP fake, netguard
trusted-host tests. Docs: RUNNING.md, web/docs/AUTHELIA.md section 7,
.env.example, STRATEGY.md.
2026-10-26 12:28:43 -05:00

179 lines
5.6 KiB
Go

// Package mailer sends transactional email (password-reset links) through a
// configured SMTP relay.
//
// Like every server-initiated dial, sending is bounded by internal/outbound
// and guarded by internal/netguard: private/link-local relay hosts (the
// normal in-cluster case, e.g. a docker-mailserver on the compose network)
// require INTEGRATIONS_ALLOW_PRIVATE=1, exactly like IMAP and CardDAV.
//
// Configuration (env):
//
// SMTP_HOST relay host (required; empty disables sending entirely)
// SMTP_PORT default 587; 465 selects implicit TLS, otherwise STARTTLS
// is used when the server advertises it
// SMTP_USERNAME optional; enables AUTH PLAIN when non-empty
// SMTP_PASSWORD optional
// SMTP_FROM envelope+header sender (required, e.g. superbrain@host)
package mailer
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net"
"net/smtp"
"os"
"strconv"
"strings"
"time"
"github.com/andrew/superbrain/internal/netguard"
"github.com/andrew/superbrain/internal/outbound"
)
// ErrNotConfigured means SMTP_HOST/SMTP_FROM are unset; callers surface a
// 503 rather than pretending the message was queued.
var ErrNotConfigured = errors.New("mailer: SMTP is not configured")
// sendTimeout bounds one full SMTP conversation (dial + TLS + transfer).
const sendTimeout = 30 * time.Second
// Config is the SMTP_* environment snapshot.
type Config struct {
Host string
Port int
Username string
Password string
From string
}
// LoadConfig reads the SMTP_* variables. An unset or unparsable SMTP_PORT
// falls back to 587 (submission).
func LoadConfig() Config {
port := 587
if v := strings.TrimSpace(os.Getenv("SMTP_PORT")); v != "" {
if p, err := strconv.Atoi(v); err == nil && p > 0 && p < 65536 {
port = p
}
}
return Config{
Host: strings.TrimSpace(os.Getenv("SMTP_HOST")),
Port: port,
Username: strings.TrimSpace(os.Getenv("SMTP_USERNAME")),
Password: os.Getenv("SMTP_PASSWORD"),
From: strings.TrimSpace(os.Getenv("SMTP_FROM")),
}
}
// Configured reports whether Send can possibly work. This is a global
// deployment property, so surfacing it to unauthenticated callers leaks
// nothing per-account.
func (c Config) Configured() bool { return c.Host != "" && c.From != "" }
// Send delivers one plain-text message. It is synchronous: the caller owns
// the request context and any retry policy.
func Send(ctx context.Context, to, subject, body string) error {
cfg := LoadConfig()
if !cfg.Configured() {
return ErrNotConfigured
}
if to == "" {
return errors.New("mailer: missing recipient")
}
// Global send budget: password resets are rare and an unreachable or
// blackholed relay must not pile up goroutines (same shape as the IMAP
// and CardDAV callers).
release, _, ok := outbound.Reserve("smtp", 5, time.Minute)
if !ok {
return errors.New("mailer: send budget exhausted")
}
defer release()
ctx, cancel := context.WithTimeout(ctx, sendTimeout)
defer cancel()
conn, err := dial(ctx, cfg.Host, cfg.Port)
if err != nil {
return fmt.Errorf("mailer: dial: %w", err)
}
if cfg.Port == 465 {
// Implicit TLS: handshake before the SMTP greeting is read.
tlsConn := tls.Client(conn, &tls.Config{ServerName: cfg.Host})
if err := tlsConn.HandshakeContext(ctx); err != nil {
conn.Close()
return fmt.Errorf("mailer: tls: %w", err)
}
conn = tlsConn
}
client, err := smtp.NewClient(conn, cfg.Host)
if err != nil {
conn.Close()
return fmt.Errorf("mailer: smtp handshake: %w", err)
}
defer client.Close()
if cfg.Port != 465 {
if ok, _ := client.Extension("STARTTLS"); ok {
if err := client.StartTLS(&tls.Config{ServerName: cfg.Host}); err != nil {
return fmt.Errorf("mailer: starttls: %w", err)
}
}
}
if cfg.Username != "" {
if ok, _ := client.Extension("AUTH"); !ok {
return errors.New("mailer: relay requires credentials but does not advertise AUTH")
}
if err := client.Auth(smtp.PlainAuth("", cfg.Username, cfg.Password, cfg.Host)); err != nil {
return fmt.Errorf("mailer: auth: %w", err)
}
}
if err := client.Mail(cfg.From); err != nil {
return fmt.Errorf("mailer: MAIL FROM: %w", err)
}
if err := client.Rcpt(to); err != nil {
return fmt.Errorf("mailer: RCPT TO: %w", err)
}
data, err := client.Data()
if err != nil {
return fmt.Errorf("mailer: DATA: %w", err)
}
msg := strings.Join([]string{
"From: " + cfg.From,
"To: " + to,
"Subject: " + sanitizeHeader(subject),
"Date: " + time.Now().UTC().Format(time.RFC1123Z),
"MIME-Version: 1.0",
"Content-Type: text/plain; charset=UTF-8",
"Content-Transfer-Encoding: 8BIT",
"",
body,
"",
}, "\r\n")
if _, err := data.Write([]byte(msg)); err != nil {
return fmt.Errorf("mailer: write: %w", err)
}
if err := data.Close(); err != nil {
return fmt.Errorf("mailer: data close: %w", err)
}
// Best effort; Close() above already released the connection on error.
_ = client.Quit()
return nil
}
// sanitizeHeader strips CR/LF so a caller-controlled subject can never
// inject additional headers (or a second message).
func sanitizeHeader(s string) string {
return strings.NewReplacer("\r", " ", "\n", " ").Replace(strings.TrimSpace(s))
}
// dial resolves and connects through netguard: range checks apply unless
// INTEGRATIONS_ALLOW_PRIVATE=1 (house relays live on private networks), and
// only the standard SMTP ports are reachable from public ranges.
func dial(ctx context.Context, host string, port int) (net.Conn, error) {
address := net.JoinHostPort(host, strconv.Itoa(port))
if netguard.AllowPrivate() {
return netguard.DialContext(ctx, "tcp", address)
}
return netguard.DialContextPorts(ctx, "tcp", address, 25, 465, 587)
}