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.
Go email-relayemail-routinghttp-to-smtpmail-deliverymailchimp-alternativemailgun-alternativemailsendermailservermailtemplatemailtestpostmark-alternativesend-emailsendgrid-alternativesendmailtransactional-emailtransactional-outbox
feat(security): encrypt SMTP server passwords at rest with AES-256-GCM
Jonas Kaninda318ad0aa9c04
diff --git a/.env.example b/.env.exampleindex 906c14b..7bab4a5 100644--- a/.env.example+++ b/.env.example@@ -82,3 +82,7 @@ POSTA_OAUTH_CALLBACK_URL=https://posta.example.com# POSTA_BLOB_S3_PATH_STYLE=false# Filesystem storage path# POSTA_BLOB_FS_PATH=/data/attachments++# Encryption key for SMTP server passwords (AES-256-GCM)+# If empty, passwords are stored with base64 encoding only+# POSTA_ENCRYPTION_KEY=\ No newline at end of filediff --git a/cmd/posta/server.go b/cmd/posta/server.goindex 7df6f23..385418a 100644--- a/cmd/posta/server.go+++ b/cmd/posta/server.go@@ -26,6 +26,7 @@ import ("github.com/goposta/posta/internal/cron/jobs""github.com/goposta/posta/internal/metrics""github.com/goposta/posta/internal/routes"+ "github.com/goposta/posta/internal/services/crypto""github.com/goposta/posta/internal/services/retry""github.com/goposta/posta/internal/services/seeder""github.com/goposta/posta/internal/services/settings"@@ -69,6 +70,9 @@ func runServer(cli *okapicli.CLI) {logger.Fatal("failed to run migrations", "error", err)}+ // Initialize SMTP password encryption+ crypto.Init(cfg.EncryptionKey)+if err := storage.SeedAdmin(res.db, cfg.AdminEmail, cfg.AdminPassword); err != nil {logger.Fatal("failed to seed admin user", "error", err)}diff --git a/cmd/posta/worker.go b/cmd/posta/worker.goindex b0e0770..3e7ab55 100644--- a/cmd/posta/worker.go+++ b/cmd/posta/worker.go@@ -20,6 +20,7 @@ package mainimport ("github.com/goposta/posta/internal/config""github.com/goposta/posta/internal/metrics"+ "github.com/goposta/posta/internal/services/crypto""github.com/goposta/posta/internal/services/tracking""github.com/goposta/posta/internal/storage/blob""github.com/goposta/posta/internal/storage/repositories"@@ -40,6 +41,9 @@ func runWorker() error {}}()+ // Initialize SMTP password encryption+ crypto.Init(cfg.EncryptionKey)+// Initialize blob storage for attachment retrievalvar blobStore blob.Storeif cfg.BlobProvider != "" {diff --git a/internal/config/config.go b/internal/config/config.goindex 42c91d6..45f4008 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -65,6 +65,9 @@ type Config struct {GoogleOAuthClientSecret stringOAuthCallbackBaseURL string+ // Encryption key for SMTP password encryption (if empty, base64 encoding is used)+ EncryptionKey string+// Blob storage settings (S3-compatible or filesystem)BlobProvider stringBlobS3Endpoint string@@ -148,6 +151,8 @@ func New() *Config {GoogleOAuthClientSecret: goutils.Env("POSTA_GOOGLE_OAUTH_CLIENT_SECRET", ""),OAuthCallbackBaseURL: goutils.Env("POSTA_OAUTH_CALLBACK_URL", ""),+ EncryptionKey: goutils.Env("POSTA_ENCRYPTION_KEY", ""),+BlobProvider: goutils.Env("POSTA_BLOB_PROVIDER", ""),BlobS3Endpoint: goutils.Env("POSTA_BLOB_S3_ENDPOINT", ""),BlobS3Region: goutils.Env("POSTA_BLOB_S3_REGION", "us-east-1"),diff --git a/internal/models/server.go b/internal/models/server.goindex d75ed5c..b6bbdbd 100644--- a/internal/models/server.go+++ b/internal/models/server.go@@ -18,9 +18,9 @@package modelsimport (- "encoding/base64""time"+ "github.com/goposta/posta/internal/services/crypto""github.com/lib/pq""gorm.io/gorm")@@ -63,23 +63,30 @@ func (s *Server) IsEnabled() bool {return s.Status == SMTPStatusEnabled}-// BeforeSave encodes the password to base64 before writing to the database.+// BeforeSave encrypts the password before writing to the database.+// Uses AES-256-GCM if POSTA_ENCRYPTION_KEY is set, otherwise base64.func (s *Server) BeforeSave(tx *gorm.DB) error {- if s.Password != "" {- s.Password = base64.StdEncoding.EncodeToString([]byte(s.Password))+ if s.Password == "" || crypto.IsEncrypted(s.Password) {+ return nil}+ encrypted, err := crypto.Encrypt(s.Password)+ if err != nil {+ return err+ }+ s.Password = encryptedreturn nil}-// AfterFind decodes the base64-encoded password after reading from the database.+// AfterFind decrypts the password after reading from the database.func (s *Server) AfterFind(tx *gorm.DB) error {- if s.Password != "" {- decoded, err := base64.StdEncoding.DecodeString(s.Password)- if err != nil {- return nil- }- s.Password = string(decoded)+ if s.Password == "" {+ return nil+ }+ plaintext, err := crypto.Decrypt(s.Password)+ if err != nil {+ return nil // degrade gracefully}+ s.Password = plaintextreturn nil}diff --git a/internal/models/smtp_server.go b/internal/models/smtp_server.goindex 8ec9942..a39e3e7 100644--- a/internal/models/smtp_server.go+++ b/internal/models/smtp_server.go@@ -18,9 +18,9 @@package modelsimport (- "encoding/base64""time"+ "github.com/goposta/posta/internal/services/crypto""github.com/lib/pq""gorm.io/gorm")@@ -63,22 +63,29 @@ func (s *SMTPServer) IsEnabled() bool {return s.Status == SMTPStatusEnabled}-// BeforeSave encodes the password to base64 before writing to the database.+// BeforeSave encrypts the password before writing to the database.+// Uses AES-256-GCM if POSTA_ENCRYPTION_KEY is set, otherwise base64.func (s *SMTPServer) BeforeSave(tx *gorm.DB) error {- if s.Password != "" {- s.Password = base64.StdEncoding.EncodeToString([]byte(s.Password))+ if s.Password == "" || crypto.IsEncrypted(s.Password) {+ return nil}+ encrypted, err := crypto.Encrypt(s.Password)+ if err != nil {+ return err+ }+ s.Password = encryptedreturn nil}-// AfterFind decodes the base64-encoded password after reading from the database.+// AfterFind decrypts the password after reading from the database.func (s *SMTPServer) AfterFind(tx *gorm.DB) error {- if s.Password != "" {- decoded, err := base64.StdEncoding.DecodeString(s.Password)- if err != nil {- return nil- }- s.Password = string(decoded)+ if s.Password == "" {+ return nil+ }+ plaintext, err := crypto.Decrypt(s.Password)+ if err != nil {+ return nil // degrade gracefully}+ s.Password = plaintextreturn nil}diff --git a/internal/services/crypto/crypto.go b/internal/services/crypto/crypto.gonew file mode 100644index 0000000..15f8e75--- /dev/null+++ b/internal/services/crypto/crypto.go@@ -0,0 +1,148 @@+/*+ * Copyright 2026 Jonas Kaninda+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ */++package crypto++import (+ "crypto/aes"+ "crypto/cipher"+ "crypto/rand"+ "crypto/sha256"+ "encoding/base64"+ "fmt"+ "strings"+ "sync"+)++const encryptedPrefix = "enc:"++// key holds the derived 32-byte AES key. nil means encryption is disabled (base64 fallback).+var (+ key []byte+ keyMu sync.RWMutex+)++// Init derives a 32-byte AES-256 key from the provided secret via SHA-256.+// Call this once at startup. If secret is empty, encryption is disabled and+// passwords will be stored with base64 encoding only.+func Init(secret string) {+ keyMu.Lock()+ defer keyMu.Unlock()+ if secret == "" {+ key = nil+ return+ }+ h := sha256.Sum256([]byte(secret))+ key = h[:]+}++// Enabled returns true if encryption is configured.+func Enabled() bool {+ keyMu.RLock()+ defer keyMu.RUnlock()+ return key != nil+}++// Encrypt encrypts plaintext with AES-256-GCM.+// Returns "enc:" + base64(nonce||ciphertext).+// If encryption is not configured, returns base64-encoded plaintext.+func Encrypt(plaintext string) (string, error) {+ keyMu.RLock()+ k := key+ keyMu.RUnlock()++ if k == nil {+ return base64.StdEncoding.EncodeToString([]byte(plaintext)), nil+ }++ ct, err := aesGCMEncrypt(k, []byte(plaintext))+ if err != nil {+ return "", fmt.Errorf("crypto: failed to encrypt: %w", err)+ }+ return encryptedPrefix + base64.StdEncoding.EncodeToString(ct), nil+}++// Decrypt decrypts a stored value. If it has the "enc:" prefix, AES-256-GCM+// decryption is used. Otherwise it is treated as base64.+func Decrypt(stored string) (string, error) {+ if IsEncrypted(stored) {+ keyMu.RLock()+ k := key+ keyMu.RUnlock()++ if k == nil {+ return "", fmt.Errorf("crypto: encrypted value found but no encryption key configured")+ }++ encoded := strings.TrimPrefix(stored, encryptedPrefix)+ ct, err := base64.StdEncoding.DecodeString(encoded)+ if err != nil {+ return "", fmt.Errorf("crypto: failed to decode ciphertext: %w", err)+ }+ pt, err := aesGCMDecrypt(k, ct)+ if err != nil {+ return "", fmt.Errorf("crypto: failed to decrypt: %w", err)+ }+ return string(pt), nil+ }++ // base64 fallback+ decoded, err := base64.StdEncoding.DecodeString(stored)+ if err != nil {+ return stored, nil+ }+ return string(decoded), nil+}++// IsEncrypted returns true if the stored value uses the encrypted format.+func IsEncrypted(s string) bool {+ return strings.HasPrefix(s, encryptedPrefix)+}++// aesGCMEncrypt performs AES-256-GCM encryption, returning nonce||ciphertext.+func aesGCMEncrypt(key, plaintext []byte) ([]byte, error) {+ block, err := aes.NewCipher(key)+ if err != nil {+ return nil, err+ }+ gcm, err := cipher.NewGCM(block)+ if err != nil {+ return nil, err+ }+ nonce := make([]byte, gcm.NonceSize())+ if _, err := rand.Read(nonce); err != nil {+ return nil, err+ }+ return gcm.Seal(nonce, nonce, plaintext, nil), nil+}++// aesGCMDecrypt performs AES-256-GCM decryption on nonce||ciphertext.+func aesGCMDecrypt(key, data []byte) ([]byte, error) {+ block, err := aes.NewCipher(key)+ if err != nil {+ return nil, err+ }+ gcm, err := cipher.NewGCM(block)+ if err != nil {+ return nil, err+ }+ nonceSize := gcm.NonceSize()+ if len(data) < nonceSize {+ return nil, fmt.Errorf("ciphertext too short")+ }+ return gcm.Open(nil, data[:nonceSize], data[nonceSize:], nil)+}diff --git a/internal/services/crypto/crypto_test.go b/internal/services/crypto/crypto_test.gonew file mode 100644index 0000000..d7a3cef--- /dev/null+++ b/internal/services/crypto/crypto_test.go@@ -0,0 +1,122 @@+/*+ * Copyright 2026 Jonas Kaninda+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ */++package crypto++import (+ "strings"+ "testing"+)++func TestEncryptDecryptWithKey(t *testing.T) {+ Init("test-secret-key")+ defer Init("")++ plaintext := "my-smtp-password-123"++ encrypted, err := Encrypt(plaintext)+ if err != nil {+ t.Fatalf("Encrypt failed: %v", err)+ }+ if !strings.HasPrefix(encrypted, "enc:") {+ t.Fatalf("encrypted value should start with 'enc:', got: %s", encrypted[:10])+ }++ decrypted, err := Decrypt(encrypted)+ if err != nil {+ t.Fatalf("Decrypt failed: %v", err)+ }+ if decrypted != plaintext {+ t.Fatalf("got %q, want %q", decrypted, plaintext)+ }+}++func TestEncryptWithoutKey(t *testing.T) {+ Init("")++ encoded, err := Encrypt("my-password")+ if err != nil {+ t.Fatalf("Encrypt failed: %v", err)+ }+ if strings.HasPrefix(encoded, "enc:") {+ t.Fatal("without key, should use base64 not enc: prefix")+ }++ decoded, err := Decrypt(encoded)+ if err != nil {+ t.Fatalf("Decrypt failed: %v", err)+ }+ if decoded != "my-password" {+ t.Fatalf("got %q, want %q", decoded, "my-password")+ }+}++func TestDecryptLegacyBase64(t *testing.T) {+ Init("some-key")+ defer Init("")++ // "my-password" in base64+ legacy := "bXktcGFzc3dvcmQ="+ decrypted, err := Decrypt(legacy)+ if err != nil {+ t.Fatalf("Decrypt legacy failed: %v", err)+ }+ if decrypted != "my-password" {+ t.Fatalf("got %q, want %q", decrypted, "my-password")+ }+}++func TestIsEncrypted(t *testing.T) {+ if IsEncrypted("bXktcGFzc3dvcmQ=") {+ t.Fatal("base64 should not be detected as encrypted")+ }+ if !IsEncrypted("enc:abcdef") {+ t.Fatal("enc: prefixed should be detected as encrypted")+ }+ if IsEncrypted("") {+ t.Fatal("empty string should not be encrypted")+ }+}++func TestEncryptProducesDifferentCiphertexts(t *testing.T) {+ Init("test-key")+ defer Init("")++ enc1, _ := Encrypt("same")+ enc2, _ := Encrypt("same")+ if enc1 == enc2 {+ t.Fatal("same plaintext should produce different ciphertexts (random nonce)")+ }++ dec1, _ := Decrypt(enc1)+ dec2, _ := Decrypt(enc2)+ if dec1 != "same" || dec2 != "same" {+ t.Fatal("both should decrypt to 'same'")+ }+}++func TestEnabled(t *testing.T) {+ Init("")+ if Enabled() {+ t.Fatal("should not be enabled without key")+ }+ Init("key")+ if !Enabled() {+ t.Fatal("should be enabled with key")+ }+ Init("")+}