Skip to content

armgit / posta

Public Imported from GitHub
0

Self-hosted email delivery platform that enables applications to send emails via HTTP APIs while handling SMTP delivery, templates, storage, security, and analytics. Fully self-hostable alternative to services like SendGrid or Mailgun.

feat(smtp): add optional STARTTLS to authenticated relay (#267)

Anas Dadidea06717b088
diff --git a/.env.example b/.env.example
index b22c5f7..2a922f8 100644
--- a/.env.example
+++ b/.env.example
@@ -187,12 +187,17 @@ POSTA_MESSAGES_INBOUND_DOMAIN=
# SMTP Relay — lets a workspace issue SMTP credentials for migrating existing senders
# Master toggle — enables the SMTP relay listener and the /workspaces/current/smtp-credentials routes
POSTA_SMTP_RELAY_ENABLED=false
-# Bind address for the built-in SMTP relay listener (plaintext, no TLS — not for public internet)
+# Bind address for the built-in SMTP relay listener (keep private even with STARTTLS)
POSTA_SMTP_RELAY_HOST=0.0.0.0
# SMTP relay listener port (separate from POSTA_INBOUND_SMTP_PORT)
POSTA_SMTP_RELAY_PORT=2526
# Hostname announced in EHLO
POSTA_SMTP_RELAY_HOSTNAME=posta.example.com
+# Use starttls to require TLS before AUTH; none preserves the private-network legacy mode.
+POSTA_SMTP_RELAY_TLS_MODE=none
+# Required when POSTA_SMTP_RELAY_TLS_MODE=starttls; certificate must match the client-facing hostname.
+POSTA_SMTP_RELAY_TLS_CERT_FILE=
+POSTA_SMTP_RELAY_TLS_KEY_FILE=
# Max raw message size in bytes (default 25 MiB)
POSTA_SMTP_RELAY_MAX_MESSAGE_SIZE=26214400
# Per-IP SMTP rate limit: max sessions per window (0 disables)
@@ -222,4 +227,4 @@ POSTA_EMAIL_VERIFY_RATE_HOURLY=1000
# recorded in the database (normally refused to prevent schema mismatches)
POSTA_ALLOW_DOWNGRADE=false
# Enforce hosted plan limits / quotas. Off by default.
-POSTA_PLAN_ENFORCEMENT=false
\ No newline at end of file
+POSTA_PLAN_ENFORCEMENT=false
diff --git a/cmd/posta/server.go b/cmd/posta/server.go
index 7704bc6..e15999b 100644
--- a/cmd/posta/server.go
+++ b/cmd/posta/server.go
@@ -190,7 +190,7 @@ func runServer(cli *okapicli.CLI) {
if cfg.SMTPRelayEnabled && !cfg.DevMode {
if srv, err := startSMTPRelayServer(res.db, cfg, emailSvc); err != nil {
- logger.Error("failed to start SMTP relay server", "error", err)
+ logger.Fatal("failed to start SMTP relay server", "error", err)
} else {
res.smtpRelay = srv
}
@@ -380,6 +380,9 @@ func startSMTPRelayServer(db *gorm.DB, cfg *config.Config, emailSvc *email.Servi
Port: cfg.SMTPRelayPort,
Hostname: cfg.SMTPRelayHostname,
MaxMessageSize: cfg.SMTPRelayMaxMessageSize,
+ TLSMode: cfg.SMTPRelayTLSMode,
+ TLSCertFile: cfg.SMTPRelayTLSCertFile,
+ TLSKeyFile: cfg.SMTPRelayTLSKeyFile,
})
if err != nil {
return nil, err
diff --git a/docs/docs/security/smtp-relay.md b/docs/docs/security/smtp-relay.md
index d03d70c..a6ec651 100644
--- a/docs/docs/security/smtp-relay.md
+++ b/docs/docs/security/smtp-relay.md
@@ -20,20 +20,24 @@ The SMTP Relay is off by default. Enable it with configuration:
| `POSTA_SMTP_RELAY_HOST` | `0.0.0.0` | Bind address for the built-in SMTP relay listener. |
| `POSTA_SMTP_RELAY_PORT` | `2526` | Listener port. Separate from `POSTA_INBOUND_SMTP_PORT` — the two listeners never share a port or process state. |
| `POSTA_SMTP_RELAY_HOSTNAME` | `posta.local` | Hostname announced in the SMTP `EHLO` greeting. |
+| `POSTA_SMTP_RELAY_TLS_MODE` | `none` | Set to `starttls` to advertise STARTTLS and require TLS before AUTH. |
+| `POSTA_SMTP_RELAY_TLS_CERT_FILE` | — | PEM certificate chain; required with `starttls`. |
+| `POSTA_SMTP_RELAY_TLS_KEY_FILE` | — | PEM private key; required with `starttls`. |
| `POSTA_SMTP_RELAY_MAX_MESSAGE_SIZE` | `26214400` (25 MiB) | Maximum raw message size in bytes. Larger messages are rejected with `552`. |
| `POSTA_SMTP_RELAY_RATE_LIMIT` | `60` | Per-IP maximum SMTP sessions per window; `0` disables the limit. |
| `POSTA_SMTP_RELAY_RATE_WINDOW` | `60` | Rate-limit window, in seconds. |
-:::danger No TLS
-The Relay listener does **not** support TLS or STARTTLS, by design — it is a minimal, plaintext-AUTH migration aid, not a hardened public MTA. Credentials and message content travel unencrypted. Only expose `POSTA_SMTP_RELAY_PORT` on a private network, over a VPN, or to `localhost` — never bind it directly to the public internet. If you need Relay access from outside your private network, put a TLS-terminating TCP proxy (e.g. stunnel, an SMTP-aware load balancer) in front of it; Posta itself will never decrypt or negotiate TLS on this listener.
+:::warning Transport security
+The default `none` mode preserves the legacy plaintext-AUTH relay. Set `POSTA_SMTP_RELAY_TLS_MODE=starttls` and provide a certificate/key to advertise STARTTLS and withhold AUTH until TLS is established (minimum TLS 1.2). Clients must require STARTTLS and verify the certificate against the relay hostname; opportunistic TLS can silently fall back to plaintext. Keep either mode on a private network or VPN; STARTTLS does not make this listener a public MTA.
:::
## How It Works
```
-your SMTP client POSTA_SMTP_RELAY_PORT (no TLS)
+your SMTP client POSTA_SMTP_RELAY_PORT
│ │
- ├── EHLO / AUTH PLAIN ────────────►│ verify SMTPCredential (workspace-scoped)
+ ├── EHLO / STARTTLS (if enabled) ─►│ require TLS before AUTH
+ ├── AUTH PLAIN ───────────────────►│ verify SMTPCredential (workspace-scoped)
│ │
└── MAIL FROM / RCPT TO / DATA ───►│ parse message
│
@@ -80,6 +84,7 @@ Response (`201`):
"password": "8b1c...e02f",
"host": "posta.local",
"port": 2526,
+ "encryption": "starttls",
"created_at": "2026-07-20T00:00:00Z",
"message": "Save this password securely. It will not be shown again."
}
@@ -120,25 +125,26 @@ Permanently removes the credential record.
## Connecting Your SMTP Client
-Point your existing SMTP client at the Relay host and port, with the generated username/password and no encryption:
+Point your existing SMTP client at the Relay host and port with the generated username/password. Match the client encryption setting to the listener configuration:
| Setting | Value |
|---|---|
| Host | `POSTA_SMTP_RELAY_HOST` (or wherever it's reachable from your app) |
| Port | `POSTA_SMTP_RELAY_PORT` (default `2526`) |
-| Encryption | None — do not configure TLS or STARTTLS on the client |
+| Encryption | `starttls` when enabled (required and certificate-verified); otherwise `none` only on a trusted private path |
| Auth mechanism | `PLAIN` |
| Username / Password | From the credential creation response |
```bash
swaks --server localhost --port 2526 \
+ --tls --tls-verify \
--auth PLAIN --auth-user smtp_9f3c2a1b7e4d5601 --auth-password 8b1c...e02f \
--header "Subject: Hello from the SMTP Relay" \
--body "This message was relayed through Posta's outbound pipeline."
```
-`AUTH PLAIN` is the only mechanism the Relay advertises; clients that default to `LOGIN` or `CRAM-MD5` should be configured to use `PLAIN` explicitly. The listener accepts up to 50 recipients per message.
+The example assumes STARTTLS mode and a trusted relay certificate. In `none` mode, omit the `--tls` flags and restrict access to a trusted private path. `AUTH PLAIN` is the only mechanism the Relay advertises; clients that default to `LOGIN` or `CRAM-MD5` should be configured to use `PLAIN` explicitly. The listener accepts up to 50 recipients per message.
## Send Outcomes
diff --git a/internal/config/config.go b/internal/config/config.go
index 9a2acb4..b32a523 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -164,11 +164,14 @@ type Config struct {
MessagesPerWorkspaceDaily int
MessagesInboundDomain string
- // SMTP Relay settings. No TLS by design.
+ // SMTP Relay settings.
SMTPRelayEnabled bool
SMTPRelayHost string
SMTPRelayPort int
SMTPRelayHostname string
+ SMTPRelayTLSMode string
+ SMTPRelayTLSCertFile string
+ SMTPRelayTLSKeyFile string
SMTPRelayMaxMessageSize int64
SMTPRelayRateLimit int
SMTPRelayRateWindow int
@@ -375,6 +378,9 @@ func New() *Config {
SMTPRelayHost: goutils.Env("POSTA_SMTP_RELAY_HOST", "0.0.0.0"),
SMTPRelayPort: goutils.EnvInt("POSTA_SMTP_RELAY_PORT", 2526),
SMTPRelayHostname: goutils.Env("POSTA_SMTP_RELAY_HOSTNAME", "posta.local"),
+ SMTPRelayTLSMode: goutils.Env("POSTA_SMTP_RELAY_TLS_MODE", "none"),
+ SMTPRelayTLSCertFile: goutils.Env("POSTA_SMTP_RELAY_TLS_CERT_FILE", ""),
+ SMTPRelayTLSKeyFile: goutils.Env("POSTA_SMTP_RELAY_TLS_KEY_FILE", ""),
SMTPRelayMaxMessageSize: int64(goutils.EnvInt("POSTA_SMTP_RELAY_MAX_MESSAGE_SIZE", 26214400)),
SMTPRelayRateLimit: goutils.EnvInt("POSTA_SMTP_RELAY_RATE_LIMIT", 60),
SMTPRelayRateWindow: goutils.EnvInt("POSTA_SMTP_RELAY_RATE_WINDOW", 60),
@@ -408,6 +414,17 @@ func (c *Config) validate() error {
return fmt.Errorf("POSTA_INBOUND_TLS_MODE=%s requires POSTA_INBOUND_TLS_CERT_FILE and POSTA_INBOUND_TLS_KEY_FILE", c.InboundTLSMode)
}
}
+ if c.SMTPRelayEnabled {
+ switch c.SMTPRelayTLSMode {
+ case "", "none":
+ case "starttls":
+ if c.SMTPRelayTLSCertFile == "" || c.SMTPRelayTLSKeyFile == "" {
+ return fmt.Errorf("POSTA_SMTP_RELAY_TLS_MODE=starttls requires POSTA_SMTP_RELAY_TLS_CERT_FILE and POSTA_SMTP_RELAY_TLS_KEY_FILE")
+ }
+ default:
+ return fmt.Errorf("unsupported POSTA_SMTP_RELAY_TLS_MODE %q (use none or starttls)", c.SMTPRelayTLSMode)
+ }
+ }
// okapi drops an invalid list and trusts no proxy, which would quietly
// collapse every client onto the proxy's address. Refuse to start instead.
for _, entry := range c.TrustedProxies {
diff --git a/internal/config/security_test.go b/internal/config/security_test.go
index 8710fd2..cb03e00 100644
--- a/internal/config/security_test.go
+++ b/internal/config/security_test.go
@@ -20,6 +20,7 @@
package config
import (
+ "os"
"strings"
"testing"
)
@@ -383,6 +384,32 @@ func TestValidateRejectsInvalidTrustedProxy(t *testing.T) {
}
}
+func TestValidateSMTPRelayTLS(t *testing.T) {
+ t.Setenv("POSTA_SMTP_RELAY_TLS_MODE", "")
+ _ = os.Unsetenv("POSTA_SMTP_RELAY_TLS_MODE")
+ if got := New().SMTPRelayTLSMode; got != "none" {
+ t.Fatalf("unset relay TLS mode = %q, want none", got)
+ }
+ for _, tc := range []struct {
+ name, mode, cert, key string
+ wantErr bool
+ }{
+ {"plain default", "none", "", "", false},
+ {"starttls", "starttls", "cert.pem", "key.pem", false},
+ {"missing certificate", "starttls", "", "key.pem", true},
+ {"missing key", "starttls", "cert.pem", "", true},
+ {"unknown mode", "ssl", "cert.pem", "key.pem", true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ c := &Config{Env: "dev", SMTPRelayEnabled: true, SMTPRelayTLSMode: tc.mode,
+ SMTPRelayTLSCertFile: tc.cert, SMTPRelayTLSKeyFile: tc.key}
+ if err := c.validate(); (err != nil) != tc.wantErr {
+ t.Fatalf("validate() error = %v, wantErr %t", err, tc.wantErr)
+ }
+ })
+ }
+}
+
func TestSplitList(t *testing.T) {
got := splitList(" 10.0.0.0/8 , ,192.0.2.7,")
if len(got) != 2 || got[0] != "10.0.0.0/8" || got[1] != "192.0.2.7" {
diff --git a/internal/handlers/smtp_credential_handler.go b/internal/handlers/smtp_credential_handler.go
index bfc797d..3133a08 100644
--- a/internal/handlers/smtp_credential_handler.go
+++ b/internal/handlers/smtp_credential_handler.go
@@ -85,6 +85,7 @@ func (h *SMTPCredentialHandler) Create(c *okapi.Context, req *CreateSMTPCredenti
"password": password,
"host": h.cfg.SMTPRelayHostname,
"port": h.cfg.SMTPRelayPort,
+ "encryption": h.cfg.SMTPRelayTLSMode,
"created_at": cred.CreatedAt,
"message": "Save this password securely. It will not be shown again.",
})
diff --git a/internal/services/smtprelay/smtp_server.go b/internal/services/smtprelay/smtp_server.go
index 2d741c9..29dd56b 100644
--- a/internal/services/smtprelay/smtp_server.go
+++ b/internal/services/smtprelay/smtp_server.go
@@ -20,7 +20,9 @@
package smtprelay
import (
+ "crypto/tls"
"fmt"
+ "strings"
"time"
"github.com/emersion/go-smtp"
@@ -32,9 +34,11 @@ type SMTPConfig struct {
Port int
Hostname string
MaxMessageSize int64
+ TLSMode string // "none" or "starttls"
+ TLSCertFile string
+ TLSKeyFile string
}
-// AllowInsecureAuth is required here: it's what permits AUTH PLAIN without TLS.
func NewSMTPServer(backend *Backend, cfg SMTPConfig) (*smtp.Server, error) {
srv := smtp.NewServer(backend)
srv.Addr = fmt.Sprintf("%s:%d", cfg.Host, cfg.Port)
@@ -43,7 +47,22 @@ func NewSMTPServer(backend *Backend, cfg SMTPConfig) (*smtp.Server, error) {
srv.WriteTimeout = 30 * time.Second
srv.MaxMessageBytes = cfg.MaxMessageSize
srv.MaxRecipients = 50
- srv.AllowInsecureAuth = true
srv.EnableSMTPUTF8 = true
+ switch strings.ToLower(strings.TrimSpace(cfg.TLSMode)) {
+ case "", "none":
+ // Preserve the existing private-network plaintext relay by default.
+ srv.AllowInsecureAuth = true
+ case "starttls":
+ cert, err := tls.LoadX509KeyPair(cfg.TLSCertFile, cfg.TLSKeyFile)
+ if err != nil {
+ return nil, fmt.Errorf("load SMTP relay TLS cert: %w", err)
+ }
+ srv.TLSConfig = &tls.Config{
+ Certificates: []tls.Certificate{cert},
+ MinVersion: tls.VersionTLS12,
+ }
+ default:
+ return nil, fmt.Errorf("unsupported SMTP relay TLS mode %q (use none or starttls)", cfg.TLSMode)
+ }
return srv, nil
}
diff --git a/internal/services/smtprelay/smtp_server_test.go b/internal/services/smtprelay/smtp_server_test.go
new file mode 100644
index 0000000..e798db1
--- /dev/null
+++ b/internal/services/smtprelay/smtp_server_test.go
@@ -0,0 +1,112 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package smtprelay
+
+import (
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/tls"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "encoding/pem"
+ "math/big"
+ "net"
+ "net/smtp"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+)
+
+func TestSMTPRelaySTARTTLS(t *testing.T) {
+ certFile, keyFile, roots := testRelayCertificate(t)
+ srv, err := NewSMTPServer(NewBackend(nil, nil, nil, 1024), SMTPConfig{
+ Host: "127.0.0.1", Hostname: "localhost", TLSMode: "starttls",
+ TLSCertFile: certFile, TLSKeyFile: keyFile,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if srv.AllowInsecureAuth || srv.TLSConfig.MinVersion != tls.VersionTLS12 {
+ t.Fatal("STARTTLS relay must require TLS before AUTH and TLS 1.2 or newer")
+ }
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = srv.Close() })
+ go func() { _ = srv.Serve(listener) }()
+ conn, err := net.Dial("tcp", listener.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ client, err := smtp.NewClient(conn, "localhost")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = client.Close() })
+ if ok, _ := client.Extension("STARTTLS"); !ok {
+ t.Fatal("STARTTLS not advertised")
+ }
+ if ok, _ := client.Extension("AUTH"); ok {
+ t.Fatal("AUTH advertised before TLS")
+ }
+ if err := client.StartTLS(&tls.Config{ServerName: "localhost", RootCAs: roots, MinVersion: tls.VersionTLS12}); err != nil {
+ t.Fatal(err)
+ }
+ if ok, mech := client.Extension("AUTH"); !ok || mech != "PLAIN" {
+ t.Fatalf("AUTH after TLS = %t %q, want PLAIN", ok, mech)
+ }
+}
+
+func TestSMTPRelayTLSConfiguration(t *testing.T) {
+ for _, cfg := range []SMTPConfig{{}, {TLSMode: "none"}} {
+ plain, err := NewSMTPServer(nil, cfg)
+ if err != nil || plain.TLSConfig != nil || !plain.AllowInsecureAuth {
+ t.Fatalf("plaintext relay changed for %+v: server=%+v error=%v", cfg, plain, err)
+ }
+ }
+ for _, cfg := range []SMTPConfig{{TLSMode: "starttls"}, {TLSMode: "unexpected"}} {
+ if _, err := NewSMTPServer(nil, cfg); err == nil {
+ t.Fatalf("invalid TLS config %+v accepted", cfg)
+ }
+ }
+}
+
+func testRelayCertificate(t *testing.T) (string, string, *x509.CertPool) {
+ t.Helper()
+ key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ der, err := x509.CreateCertificate(rand.Reader, &x509.Certificate{
+ SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "localhost"},
+ DNSNames: []string{"localhost"}, NotBefore: time.Now().Add(-time.Minute),
+ NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature,
+ }, &x509.Certificate{
+ SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "localhost"},
+ DNSNames: []string{"localhost"}, NotBefore: time.Now().Add(-time.Minute),
+ NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature,
+ }, &key.PublicKey, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ keyDER, err := x509.MarshalECPrivateKey(key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ dir := t.TempDir()
+ certFile, keyFile := filepath.Join(dir, "relay.crt"), filepath.Join(dir, "relay.key")
+ certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
+ if err := os.WriteFile(certFile, certPEM, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(keyFile, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER}), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ roots := x509.NewCertPool()
+ roots.AppendCertsFromPEM(certPEM)
+ return certFile, keyFile, roots
+}
diff --git a/web/src/api/types.ts b/web/src/api/types.ts
index 9106606..26c386d 100644
--- a/web/src/api/types.ts
+++ b/web/src/api/types.ts
@@ -164,6 +164,7 @@ export interface SMTPCredentialCreateResponse {
password: string
host: string
port: number
+ encryption: 'none' | 'starttls'
created_at: string
message: string
}
diff --git a/web/src/views/smtp-relay/SmtpCredentials.vue b/web/src/views/smtp-relay/SmtpCredentials.vue
index fa7467f..8f3e79d 100644
--- a/web/src/views/smtp-relay/SmtpCredentials.vue
+++ b/web/src/views/smtp-relay/SmtpCredentials.vue
@@ -109,7 +109,7 @@ async function deleteCredential(cred: SMTPCredential) {
function copyCredential() {
if (!createdCredential.value) return
const c = createdCredential.value
- const text = `Host: ${c.host}\nPort: ${c.port}\nUsername: ${c.username}\nPassword: ${c.password}`
+ const text = `Host: ${c.host}\nPort: ${c.port}\nEncryption: ${c.encryption}\nUsername: ${c.username}\nPassword: ${c.password}`
navigator.clipboard.writeText(text)
copied.value = true
setTimeout(() => (copied.value = false), 2000)
@@ -288,6 +288,10 @@ onMounted(() => {
<label class="form-label">Port</label>
<div class="code-block">{{ createdCredential?.port }}</div>
</div>
+ <div class="form-group">
+ <label class="form-label">Encryption</label>
+ <div class="code-block">{{ createdCredential?.encryption === 'starttls' ? 'STARTTLS (required)' : 'None — private network only' }}</div>
+ </div>
<div class="form-group">
<label class="form-label">Username</label>
<div class="code-block">{{ createdCredential?.username }}</div>