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(workspaces): provision the system SMTP server into the system workspace

Jonas Kaninda83ad6c804684
diff --git a/.env.example b/.env.example
index 0f77a6e..3eb3022 100644
--- a/.env.example
+++ b/.env.example
@@ -107,7 +107,15 @@ POSTA_OAUTH_CALLBACK_URL=https://posta.example.com
# If empty, passwords are stored with base64 encoding only
# POSTA_ENCRYPTION_KEY=
-# System SMTP server used for platform notifications (daily reports, invitations, etc.)
+# System SMTP server used for platform notifications (daily reports, invitations,
+# password resets, security alerts).
+#
+# On boot these are provisioned as a real SMTP server inside the "Posta System"
+# workspace, so the settings are visible and testable from the dashboard. The
+# connection fields below are re-synced on every restart — rotating a password
+# here and restarting is enough — while the server's label and status stay as
+# the operator left them.
+#
# Required: Host and From must be set for SMTP to be active
POSTA_SYSTEM_SMTP_HOST=smtp.example.com
POSTA_SYSTEM_SMTP_PORT=587
diff --git a/cmd/posta/server.go b/cmd/posta/server.go
index e010aad..eb637cf 100644
--- a/cmd/posta/server.go
+++ b/cmd/posta/server.go
@@ -94,7 +94,7 @@ func runServer(cli *okapicli.CLI) {
// The system workspace needs an administrator to own it, so it is
// ensured after seeding rather than in the migration step, which may
// run before any admin exists.
- if _, err := workspacesvc.EnsureSystem(res.db); err != nil {
+ if _, err := workspacesvc.EnsureSystem(res.db, cfg.SystemSMTP); err != nil {
logger.Error("failed to ensure the system workspace", "error", err)
} else if err := workspacesvc.SyncMembers(res.db); err != nil {
logger.Error("failed to sync system workspace members", "error", err)
@@ -131,6 +131,7 @@ func runServer(cli *okapicli.CLI) {
userRepo,
userSettingRepo,
repositories.NewWorkspaceRepository(res.db))
+ notifier.SetSMTPRepo(repositories.NewSMTPRepository(res.db))
if notifier.IsConfigured() {
logger.Info("system notification service enabled")
}
diff --git a/cmd/posta/worker.go b/cmd/posta/worker.go
index 4ca1594..95130ff 100644
--- a/cmd/posta/worker.go
+++ b/cmd/posta/worker.go
@@ -141,6 +141,7 @@ func runWorker() error {
repositories.NewUserSettingRepository(db),
repositories.NewWorkspaceRepository(db),
)
+ notifier.SetSMTPRepo(repositories.NewSMTPRepository(db))
dailyReportHandler := worker.NewDailyReportHandler(
notifier,
repositories.NewAnalyticsRepository(db),
diff --git a/docs/docs/getting-started/configuration.md b/docs/docs/getting-started/configuration.md
index 7b831a8..13b6fb4 100644
--- a/docs/docs/getting-started/configuration.md
+++ b/docs/docs/getting-started/configuration.md
@@ -114,7 +114,11 @@ Controls the `POST /api/v1/emails/verify` endpoint (syntax, MX, disposable & rol
## System SMTP
-Outbound SMTP server used for platform notifications (daily reports, invitations, alerts). `HOST` and `FROM` must both be set for it to activate.
+Outbound SMTP server used for platform notifications (daily reports, invitations, password resets, security alerts). `HOST` and `FROM` must both be set for it to activate.
+
+On boot, Posta provisions these settings as a real SMTP server inside the built-in **Posta System** workspace, so they are visible and testable from the dashboard rather than only readable from the deployment's environment. See [Workspaces](../workspaces/overview.md#the-system-workspace).
+
+The connection fields — host, port, username, password, encryption — are re-synced from the environment on every restart, so rotating a credential means changing it here and restarting. The server's label and status belong to the operator and survive a restart.
| Variable | Default | Description |
|----------|---------|-------------|
diff --git a/docs/docs/workspaces/overview.md b/docs/docs/workspaces/overview.md
index bfcdab3..64e2859 100644
--- a/docs/docs/workspaces/overview.md
+++ b/docs/docs/workspaces/overview.md
@@ -16,6 +16,28 @@ A workspace is provisioned for you when you sign up, named after you and owned b
One workspace is special. The **system workspace** is created on first boot, owned by the first administrator, and holds platform-managed resources. It is flagged `system: true`, admits only platform administrators, and cannot be renamed or deleted.
+### The system workspace
+
+Its job is to give the platform's own mail somewhere to belong. Posta sends password resets, email verification, sign-in alerts, workspace invitations, and daily reports on its own behalf; that mail needs an SMTP server that belongs to the operator rather than to a tenant.
+
+On boot, the `POSTA_SYSTEM_SMTP_*` settings are provisioned as an ordinary `SMTPServer` inside this workspace, labelled **System SMTP**. Because it is an ordinary workspace-scoped server, it appears under SMTP Servers in the dashboard, can be tested from there, and the normal delivery pipeline can send through it with no special cases.
+
+Ownership of that row is split:
+
+| Field | Owner | On restart |
+|-------|-------|------------|
+| Host, port, username, password, encryption | Configuration | Re-synced from the environment |
+| Name, status, retry and recipient limits | Operator | Left as you set them |
+
+That is what makes credential rotation a matter of changing the environment and restarting, while leaving you free to relabel the server without a restart undoing it.
+
+Two consequences worth knowing:
+
+- **The provisioned server cannot be deleted** (`409`). It is recreated from configuration on the next restart regardless, and platform mail depends on it.
+- **Disabling it does not stop platform mail.** Password resets and security alerts must reach you even when something is misconfigured, so the notification path uses the row's connection settings without consulting its status. Whether the platform sends at all is governed by whether `POSTA_SYSTEM_SMTP_*` is configured.
+
+A server you add to the system workspace yourself is left alone: the provisioned one is found by an internal marker, never by name or position.
+
### Workspaces
A workspace is an isolated environment where team members collaborate. Resources created within a workspace are only visible to members of that workspace. Each workspace has:
diff --git a/internal/handlers/smtp_handler.go b/internal/handlers/smtp_handler.go
index 1938be7..a7f4094 100644
--- a/internal/handlers/smtp_handler.go
+++ b/internal/handlers/smtp_handler.go
@@ -266,6 +266,11 @@ func (h *SMTPHandler) Delete(c *okapi.Context, req *DeleteSMTPRequest) error {
if err != nil || !ownsResource(c, server.UserID, server.WorkspaceID) {
return c.AbortNotFound("SMTP server not found")
}
+ // Provisioned from configuration, and the platform's own mail depends on it.
+ // Deleting it would be undone on the next restart anyway.
+ if server.IsSystem {
+ return c.AbortConflict("the system SMTP server is provisioned from POSTA_SYSTEM_SMTP_* and cannot be deleted")
+ }
if err := h.repo.Delete(server.ID); err != nil {
return c.AbortInternalServerError("failed to delete SMTP server")
diff --git a/internal/models/smtp_server.go b/internal/models/smtp_server.go
index 3767db8..501575b 100644
--- a/internal/models/smtp_server.go
+++ b/internal/models/smtp_server.go
@@ -26,9 +26,17 @@ const (
)
type SMTPServer struct {
- ID uint `json:"id" gorm:"primaryKey"`
- UserID uint `json:"user_id" gorm:"index;not null"`
- WorkspaceID *uint `json:"workspace_id,omitempty" gorm:"index"`
+ ID uint `json:"id" gorm:"primaryKey"`
+ UserID uint `json:"user_id" gorm:"index;not null"`
+ WorkspaceID *uint `json:"workspace_id,omitempty" gorm:"index"`
+ // Name is an optional label so a workspace holding several servers can tell
+ // them apart. Existing rows keep an empty name.
+ Name string `json:"name"`
+ // IsSystem marks the server provisioned from POSTA_SYSTEM_SMTP_*. It is how
+ // that row is found again on the next boot, so a server the operator adds to
+ // the same workspace is never mistaken for it and overwritten from the
+ // environment.
+ IsSystem bool `json:"is_system" gorm:"not null;default:false;index"`
Host string `json:"host" gorm:"not null"`
Port int `json:"port" gorm:"not null"`
Username string `json:"username"`
diff --git a/internal/services/notification/service.go b/internal/services/notification/service.go
index 9a6e6ba..91603b1 100644
--- a/internal/services/notification/service.go
+++ b/internal/services/notification/service.go
@@ -63,6 +63,7 @@ type Service struct {
userRepo *repositories.UserRepository
userSettingRepo *repositories.UserSettingRepository
workspaceRepo *repositories.WorkspaceRepository
+ smtpRepo *repositories.SMTPRepository
templates map[string]*template.Template
}
@@ -255,7 +256,19 @@ func (s *Service) render(templateName string, data map[string]any) (string, erro
return buf.String(), nil
}
+// systemServer resolves the connection the platform sends its own mail through.
+//
+// The row provisioned into the system workspace from POSTA_SYSTEM_SMTP_* is
+// preferred, so what an operator sees in the dashboard is what the platform
+// actually uses. Configuration remains the fallback: the worker binary builds
+// this service without a repository, and on a first boot the row does not exist
+// until provisioning has run.
func (s *Service) systemServer() *models.SMTPServer {
+ if s.smtpRepo != nil {
+ if server, err := s.smtpRepo.FindSystem(); err == nil && server.Host != "" {
+ return server
+ }
+ }
return &models.SMTPServer{
Host: s.smtpCfg.Host,
Port: s.smtpCfg.Port,
@@ -264,3 +277,7 @@ func (s *Service) systemServer() *models.SMTPServer {
Encryption: s.smtpCfg.Encryption,
}
}
+
+// SetSMTPRepo lets the service read the provisioned system SMTP server. Without
+// it the service still works, sending straight from configuration.
+func (s *Service) SetSMTPRepo(repo *repositories.SMTPRepository) { s.smtpRepo = repo }
diff --git a/internal/services/workspace/smtp.go b/internal/services/workspace/smtp.go
new file mode 100644
index 0000000..0aa71d8
--- /dev/null
+++ b/internal/services/workspace/smtp.go
@@ -0,0 +1,175 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package workspace
+
+import (
+ "errors"
+ "fmt"
+ "net/mail"
+ "strings"
+
+ "github.com/goposta/posta/internal/config"
+ "github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/services/crypto"
+ "github.com/jkaninda/logger"
+ "gorm.io/gorm"
+)
+
+// SystemSMTPServerName labels the server provisioned from POSTA_SYSTEM_SMTP_*.
+// Only the label: the row is located by its IsSystem marker, so an operator may
+// rename it freely.
+const SystemSMTPServerName = "System SMTP"
+
+// connectionColumns are owned by configuration and re-synced on every boot, so
+// rotating a credential in the environment takes effect on restart. Everything
+// else on the row — the label, the status, retry and recipient limits — belongs
+// to the operator and is written once at creation.
+var connectionColumns = []string{"host", "port", "username", "encryption", "password"}
+
+// provisionSystemSMTP creates the system workspace's SMTP server from
+// configuration, or re-syncs the connection settings of the one already there.
+//
+// An unconfigured or unusable POSTA_SYSTEM_SMTP_* is not an error: the platform
+// boots without a server and the notification service falls back to sending
+// straight from configuration.
+func provisionSystemSMTP(tx *gorm.DB, ws *models.Workspace, ownerID uint, cfg config.SystemSMTPConfig) error {
+ existing, err := findSystemSMTP(tx, ws.ID)
+ if err != nil {
+ return err
+ }
+
+ if !cfg.IsConfigured() {
+ if existing != nil {
+ logger.Warn("system workspace: POSTA_SYSTEM_SMTP_* is no longer configured; "+
+ "the provisioned server keeps its stored settings until it is removed",
+ "workspace_id", ws.ID, "smtp_server_id", existing.ID)
+ }
+ return nil
+ }
+
+ if existing == nil {
+ server := &models.SMTPServer{
+ UserID: ownerID,
+ WorkspaceID: &ws.ID,
+ Name: SystemSMTPServerName,
+ IsSystem: true,
+ Host: cfg.Host,
+ Port: cfg.Port,
+ Username: cfg.Username,
+ Password: cfg.Password,
+ Encryption: NormalizeEncryption(cfg.Encryption),
+ Status: models.SMTPStatusEnabled,
+ }
+ if err := tx.Create(server).Error; err != nil {
+ return fmt.Errorf("create system SMTP server: %w", err)
+ }
+ logger.Info("system workspace: provisioned SMTP server",
+ "workspace_id", ws.ID, "smtp_server_id", server.ID,
+ "host", server.Host, "port", server.Port, "encryption", server.Encryption)
+ return nil
+ }
+
+ updates := connectionDrift(cfg, existing)
+ if len(updates) == 0 {
+ return nil
+ }
+ if err := tx.Model(&models.SMTPServer{}).Where("id = ?", existing.ID).Updates(updates).Error; err != nil {
+ return fmt.Errorf("sync system SMTP server: %w", err)
+ }
+ logger.Info("system workspace: synced SMTP connection settings from configuration",
+ "smtp_server_id", existing.ID, "fields", strings.Join(changedColumns(updates), ","))
+ return nil
+}
+
+// findSystemSMTP locates the provisioned server by its marker rather than by
+// name or position, so a server the operator adds to the same workspace is
+// never adopted and overwritten from the environment.
+func findSystemSMTP(tx *gorm.DB, workspaceID uint) (*models.SMTPServer, error) {
+ var server models.SMTPServer
+ err := tx.Where("workspace_id = ? AND is_system = ?", workspaceID, true).
+ Order("id").First(&server).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, fmt.Errorf("look up system SMTP server: %w", err)
+ }
+ return &server, nil
+}
+
+// connectionDrift returns the config-owned columns whose stored value differs
+// from configuration. An empty map means the row is already in sync and no
+// write happens.
+//
+// The password compares in plaintext because models.SMTPServer decrypts it on
+// read, and is re-encrypted explicitly here: a map-based Updates call bypasses
+// BeforeSave, so without this the secret would be stored in the clear.
+func connectionDrift(cfg config.SystemSMTPConfig, existing *models.SMTPServer) map[string]any {
+ updates := map[string]any{}
+ if existing.Host != cfg.Host {
+ updates["host"] = cfg.Host
+ }
+ if existing.Port != cfg.Port {
+ updates["port"] = cfg.Port
+ }
+ if existing.Username != cfg.Username {
+ updates["username"] = cfg.Username
+ }
+ if enc := NormalizeEncryption(cfg.Encryption); existing.Encryption != enc {
+ updates["encryption"] = enc
+ }
+ if cfg.Password != "" && existing.Password != cfg.Password {
+ encrypted, err := crypto.Encrypt(cfg.Password)
+ if err != nil {
+ logger.Error("system workspace: could not encrypt the SMTP password; "+
+ "leaving the stored one in place", "error", err)
+ } else {
+ updates["password"] = encrypted
+ }
+ }
+ return updates
+}
+
+// changedColumns lists updated column names in a stable order for logging. The
+// password's presence is reported; its value never is.
+func changedColumns(updates map[string]any) []string {
+ out := make([]string, 0, len(updates))
+ for _, col := range connectionColumns {
+ if _, ok := updates[col]; ok {
+ out = append(out, col)
+ }
+ }
+ return out
+}
+
+// NormalizeEncryption maps a configured value onto a mode the sender
+// understands, treating "tls" as a synonym for implicit TLS and defaulting to
+// STARTTLS as the configuration default does. Without it a typo produces a row
+// the sender rejects at delivery time rather than at boot.
+func NormalizeEncryption(enc string) string {
+ switch strings.ToLower(strings.TrimSpace(enc)) {
+ case models.EncryptionNone:
+ return models.EncryptionNone
+ case models.EncryptionSSL, "tls":
+ return models.EncryptionSSL
+ default:
+ return models.EncryptionSTARTTLS
+ }
+}
+
+// ParseSender splits POSTA_SYSTEM_SMTP_FROM into a display name and an address,
+// accepting both a bare address and RFC 5322 display-name form.
+func ParseSender(from string) (name, addr string, err error) {
+ from = strings.TrimSpace(from)
+ if from == "" {
+ return "", "", errors.New("sender address is empty")
+ }
+ if parsed, perr := mail.ParseAddress(from); perr == nil {
+ return parsed.Name, parsed.Address, nil
+ }
+ if !strings.Contains(from, "@") {
+ return "", "", fmt.Errorf("sender address %q has no domain", from)
+ }
+ return "", from, nil
+}
diff --git a/internal/services/workspace/smtp_test.go b/internal/services/workspace/smtp_test.go
new file mode 100644
index 0000000..c4da58e
--- /dev/null
+++ b/internal/services/workspace/smtp_test.go
@@ -0,0 +1,175 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package workspace
+
+import (
+ "testing"
+
+ "github.com/goposta/posta/internal/config"
+ "github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/services/crypto"
+)
+
+func TestNormalizeEncryption(t *testing.T) {
+ cases := map[string]string{
+ "none": models.EncryptionNone,
+ "NONE": models.EncryptionNone,
+ "ssl": models.EncryptionSSL,
+ "SSL": models.EncryptionSSL,
+ "tls": models.EncryptionSSL,
+ "starttls": models.EncryptionSTARTTLS,
+ "": models.EncryptionSTARTTLS,
+ " ": models.EncryptionSTARTTLS,
+ "garbage": models.EncryptionSTARTTLS,
+ }
+ for in, want := range cases {
+ if got := NormalizeEncryption(in); got != want {
+ t.Fatalf("NormalizeEncryption(%q) = %q, want %q", in, got, want)
+ }
+ }
+}
+
+func TestParseSender(t *testing.T) {
+ cases := []struct {
+ in string
+ wantName string
+ wantAddr string
+ wantErr bool
+ }{
+ {"Posta <[email protected]>", "Posta", "[email protected]", false},
+ {" [email protected] ", "", "[email protected]", false},
+ {"", "", "", true},
+ {"not-an-address", "", "", true},
+ }
+ for _, tc := range cases {
+ name, addr, err := ParseSender(tc.in)
+ if (err != nil) != tc.wantErr {
+ t.Fatalf("ParseSender(%q) err = %v, wantErr %v", tc.in, err, tc.wantErr)
+ }
+ if err != nil {
+ continue
+ }
+ if name != tc.wantName || addr != tc.wantAddr {
+ t.Fatalf("ParseSender(%q) = (%q, %q), want (%q, %q)", tc.in, name, addr, tc.wantName, tc.wantAddr)
+ }
+ }
+}
+
+func testConfig() config.SystemSMTPConfig {
+ return config.SystemSMTPConfig{
+ Host: "smtp.example.com",
+ Port: 587,
+ Username: "posta",
+ Password: "s3cret",
+ From: "Posta <[email protected]>",
+ Encryption: "starttls",
+ }
+}
+
+func syncedServer(cfg config.SystemSMTPConfig) *models.SMTPServer {
+ return &models.SMTPServer{
+ Host: cfg.Host,
+ Port: cfg.Port,
+ Username: cfg.Username,
+ Password: cfg.Password,
+ Encryption: NormalizeEncryption(cfg.Encryption),
+ }
+}
+
+func TestConnectionDriftNoChange(t *testing.T) {
+ cfg := testConfig()
+ if got := connectionDrift(cfg, syncedServer(cfg)); len(got) != 0 {
+ t.Fatalf("an in-sync row must produce no update, got %v", got)
+ }
+}
+
+func TestConnectionDriftPerField(t *testing.T) {
+ cases := []struct {
+ name string
+ mutate func(*models.SMTPServer)
+ column string
+ }{
+ {"host", func(s *models.SMTPServer) { s.Host = "old.example.com" }, "host"},
+ {"port", func(s *models.SMTPServer) { s.Port = 25 }, "port"},
+ {"username", func(s *models.SMTPServer) { s.Username = "old" }, "username"},
+ {"encryption", func(s *models.SMTPServer) { s.Encryption = models.EncryptionNone }, "encryption"},
+ {"password", func(s *models.SMTPServer) { s.Password = "old" }, "password"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ cfg := testConfig()
+ server := syncedServer(cfg)
+ tc.mutate(server)
+
+ got := connectionDrift(cfg, server)
+ if len(got) != 1 {
+ t.Fatalf("expected exactly one changed column, got %v", got)
+ }
+ if _, ok := got[tc.column]; !ok {
+ t.Fatalf("expected column %q to change, got %v", tc.column, got)
+ }
+ })
+ }
+}
+
+// A map-based Updates call bypasses GORM's BeforeSave hook, so the rotated
+// password has to be encrypted here. Without it the secret lands in the
+// database in the clear, and nothing else in the system would notice.
+func TestConnectionDriftEncryptsRotatedPassword(t *testing.T) {
+ crypto.Init("0123456789abcdef0123456789abcdef")
+
+ cfg := testConfig()
+ server := syncedServer(cfg)
+ server.Password = "the-previous-one"
+
+ got := connectionDrift(cfg, server)
+ stored, ok := got["password"].(string)
+ if !ok {
+ t.Fatalf("password not updated: %v", got)
+ }
+ if stored == cfg.Password {
+ t.Fatal("the rotated password was stored in plaintext")
+ }
+ if !crypto.IsEncrypted(stored) {
+ t.Fatalf("stored password is not encrypted: %q", stored)
+ }
+ if plain, err := crypto.Decrypt(stored); err != nil || plain != cfg.Password {
+ t.Fatalf("stored password does not decrypt to the configured one: %q, %v", plain, err)
+ }
+}
+
+// An unset password must not clear the stored one: an operator may have set it
+// through the dashboard and dropped it from the environment.
+func TestConnectionDriftIgnoresEmptyPassword(t *testing.T) {
+ cfg := testConfig()
+ cfg.Password = ""
+ server := syncedServer(testConfig())
+
+ if _, ok := connectionDrift(cfg, server)["password"]; ok {
+ t.Fatal("an empty configured password must not overwrite the stored one")
+ }
+}
+
+func TestChangedColumnsIsStableAndOmitsValues(t *testing.T) {
+ got := changedColumns(map[string]any{
+ "password": "encrypted-blob",
+ "host": "smtp.example.com",
+ "port": 587,
+ })
+ want := []string{"host", "port", "password"}
+ if len(got) != len(want) {
+ t.Fatalf("changedColumns = %v, want %v", got, want)
+ }
+ for i := range want {
+ if got[i] != want[i] {
+ t.Fatalf("changedColumns = %v, want %v", got, want)
+ }
+ }
+ for _, c := range got {
+ if c == "encrypted-blob" {
+ t.Fatal("changedColumns must report column names, never values")
+ }
+ }
+}
diff --git a/internal/services/workspace/system.go b/internal/services/workspace/system.go
index 5c4e398..3776167 100644
--- a/internal/services/workspace/system.go
+++ b/internal/services/workspace/system.go
@@ -7,6 +7,7 @@ import (
"errors"
"fmt"
+ "github.com/goposta/posta/internal/config"
"github.com/goposta/posta/internal/models"
"github.com/jkaninda/logger"
"gorm.io/gorm"
@@ -30,9 +31,16 @@ func FindSystem(db *gorm.DB) (*models.Workspace, error) {
}
// EnsureSystem creates the built-in platform workspace when it does not exist,
-// owned by the lowest-id active administrator. Idempotent.
-func EnsureSystem(db *gorm.DB) (*models.Workspace, error) {
+// owned by the lowest-id active administrator, and provisions the SMTP server
+// described by POSTA_SYSTEM_SMTP_*. Idempotent and safe to call on every boot:
+// an existing workspace has only its SMTP connection settings re-synced.
+func EnsureSystem(db *gorm.DB, smtp config.SystemSMTPConfig) (*models.Workspace, error) {
if ws, err := FindSystem(db); err == nil {
+ if serr := db.Transaction(func(tx *gorm.DB) error {
+ return provisionSystemSMTP(tx, ws, ws.OwnerID, smtp)
+ }); serr != nil {
+ return nil, serr
+ }
return ws, nil
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, err
@@ -72,7 +80,25 @@ func EnsureSystem(db *gorm.DB) (*models.Workspace, error) {
if err := tx.Create(member).Error; err != nil {
return fmt.Errorf("create system workspace owner: %w", err)
}
- return nil
+
+ settings := &models.WorkspaceSetting{
+ WorkspaceID: ws.ID,
+ Timezone: "UTC",
+ WebhookRetryCount: 3,
+ APIKeyExpiryDays: 90,
+ BounceAutoSuppress: true,
+ }
+ // The platform's own From address is the workspace's sending default, so
+ // a test send from the dashboard uses the same identity as its mail.
+ if name, addr, perr := ParseSender(smtp.From); perr == nil {
+ settings.DefaultSenderName = name
+ settings.DefaultSenderEmail = addr
+ }
+ if err := tx.Create(settings).Error; err != nil {
+ return fmt.Errorf("create system workspace settings: %w", err)
+ }
+
+ return provisionSystemSMTP(tx, ws, owner.ID, smtp)
})
if err != nil {
return nil, err
diff --git a/internal/storage/migration/upgrade/steps_2026_08_28_workspace_types.go b/internal/storage/migration/upgrade/steps_2026_08_28_workspace_types.go
index 735b5fd..68b1ded 100644
--- a/internal/storage/migration/upgrade/steps_2026_08_28_workspace_types.go
+++ b/internal/storage/migration/upgrade/steps_2026_08_28_workspace_types.go
@@ -7,6 +7,7 @@ import (
"errors"
"fmt"
+ "github.com/goposta/posta/internal/config"
"github.com/goposta/posta/internal/services/workspace"
"github.com/jkaninda/logger"
"gorm.io/gorm"
@@ -23,7 +24,10 @@ func applySystemWorkspace(tx *gorm.DB) error {
return fmt.Errorf("create one_system_workspace: %w", err)
}
- if _, err := workspace.EnsureSystem(tx); err != nil {
+ // No SMTP configuration here on purpose: this step runs before crypto.Init,
+ // so a password encrypted now would use an uninitialised key. The workspace
+ // is all this step needs; the server is provisioned at boot, after seeding.
+ if _, err := workspace.EnsureSystem(tx, config.SystemSMTPConfig{}); err != nil {
if errors.Is(err, workspace.ErrNoAdmin) {
logger.Info("system workspace deferred: no administrator yet")
return nil
diff --git a/internal/storage/repositories/smtp_repo.go b/internal/storage/repositories/smtp_repo.go
index 7291b34..1cf6ea6 100644
--- a/internal/storage/repositories/smtp_repo.go
+++ b/internal/storage/repositories/smtp_repo.go
@@ -108,6 +108,20 @@ func (r *SMTPRepository) FindFirstByWorkspaceID(workspaceID uint) (*models.SMTPS
return &server, nil
}
+// FindSystem returns the server provisioned from POSTA_SYSTEM_SMTP_*.
+//
+// Status is deliberately not filtered: the platform's own mail is password
+// resets and security alerts, and a dashboard toggle must not be able to lock
+// an operator out of their installation. Whether the platform sends at all is
+// governed by whether POSTA_SYSTEM_SMTP_* is configured.
+func (r *SMTPRepository) FindSystem() (*models.SMTPServer, error) {
+ var server models.SMTPServer
+ if err := r.db.Where("is_system = ?", true).Order("id").First(&server).Error; err != nil {
+ return nil, err
+ }
+ return &server, nil
+}
+
// SetStatus updates the status, validation error, and validated_at timestamp for a server.
func (r *SMTPRepository) SetStatus(id uint, status, validationError string) error {
return r.db.Model(&models.SMTPServer{}).Where("id = ?", id).Updates(map[string]interface{}{