完成邮件服务策略整合与安全配置调整
Security Checks / security (push) Waiting to run

This commit is contained in:
xuans committed 2026-09-07 15:24:41 +08:00
1 parent d2f14ede7a
commit cfe4401b70
32 files changed
+893 -318

No files matched your search

+1 -1
View File
@@ -30,7 +30,7 @@ func ValidateConfigAuditQuery(query ConfigAuditQuery) error {
if query.Operation != "" && query.Operation != ConfigOperationUpdate && query.Operation != ConfigOperationRollback && query.Operation != ConfigOperationMigration {
return ErrInvalidAuditQuery
}
if query.Section != "" && query.Section != SectionRoot && query.Section != SectionSMTP && query.Section != SectionEmail && query.Section != SectionSSL && query.Section != SectionPlugins {
if query.Section != "" && query.Section != SectionRoot && query.Section != SectionMail && query.Section != SectionSMTP && query.Section != SectionEmail && query.Section != SectionSSL && query.Section != SectionPlugins {
return ErrInvalidAuditQuery
}
return nil
+21 -1
View File
@@ -1,6 +1,7 @@
package config
import (
"context"
"errors"
"strings"
"testing"
@@ -13,7 +14,7 @@ func TestValidateConfigAuditQueryAcceptsSupportedFilters(t *testing.T) {
To: time.Date(2026, 8, 30, 0, 0, 0, 0, time.UTC),
ActorID: "42",
Operation: ConfigOperationUpdate,
Section: SectionSMTP,
Section: SectionMail,
Limit: 1000,
}
if err := ValidateConfigAuditQuery(query); err != nil {
@@ -21,6 +22,25 @@ func TestValidateConfigAuditQueryAcceptsSupportedFilters(t *testing.T) {
}
}
func TestConfigAuditQueryFiltersCombinedMailSection(t *testing.T) {
writer := &MemoryAuditWriter{}
for _, event := range []ConfigAuditEvent{
{Operation: ConfigOperationUpdate, Section: SectionMail, ActorID: "42", ActorRole: "super_admin", FromGeneration: 1, ToGeneration: 2, Result: "success", CreatedAt: time.Now().UTC()},
{Operation: ConfigOperationUpdate, Section: SectionSMTP, ActorID: "42", ActorRole: "super_admin", FromGeneration: 2, ToGeneration: 3, Result: "success", CreatedAt: time.Now().UTC()},
} {
if err := writer.WriteConfigAudit(context.Background(), event); err != nil {
t.Fatal(err)
}
}
items, err := writer.Query(context.Background(), ConfigAuditQuery{Section: SectionMail, Limit: 10})
if err != nil {
t.Fatal(err)
}
if len(items) != 1 || items[0].Section != SectionMail {
t.Fatalf("mail audit filter returned %+v", items)
}
}
func TestValidateConfigAuditQueryRejectsAmbiguousFilters(t *testing.T) {
tests := []ConfigAuditQuery{
{Limit: -1},
+31 -10
View File
@@ -199,7 +199,7 @@ func Init() error {
if err = json.Unmarshal(cfgData, loaded); err != nil {
return errors.Wrap(err)
}
applyLegacyLoginPolicy(cfgData, loaded)
applyLegacySecurityDefaults(cfgData, loaded)
migrated, err := unprotectCredentials(loaded)
if err != nil {
return errors.Wrap(err)
@@ -331,9 +331,12 @@ func ReadConfig() (*Config, error) {
func readConfig() (*Config, error) {
configData := Config{
DkimPrivateKeyPath: ROOT_PATH + "config/dkim/dkim.priv",
SSLPrivateKeyPath: ROOT_PATH + "config/ssl/private.key",
SSLPublicKeyPath: ROOT_PATH + "config/ssl/public.crt",
DkimPrivateKeyPath: ROOT_PATH + "config/dkim/dkim.priv",
SSLPrivateKeyPath: ROOT_PATH + "config/ssl/private.key",
SSLPublicKeyPath: ROOT_PATH + "config/ssl/public.crt",
VerificationEnabled: true,
ExternalRecoveryEnabled: true,
LoginPolicy: "new_device",
}
cfgData, err := readConfigFile("config.json")
if os.IsNotExist(err) {
@@ -362,7 +365,7 @@ func readConfig() (*Config, error) {
log.Error("Read Config Unmarshal Error")
return nil, errors.Wrap(err)
}
applyLegacyLoginPolicy(cfgData, &configData)
applyLegacySecurityDefaults(cfgData, &configData)
migrated, err := unprotectCredentials(&configData)
if err != nil {
log.Error("Read Config Credential Error")
@@ -378,16 +381,34 @@ func readConfig() (*Config, error) {
return &configData, nil
}
func applyLegacyLoginPolicy(data []byte, cfg *Config) {
if cfg == nil || strings.TrimSpace(cfg.LoginPolicy) != "" {
func applyLegacySecurityDefaults(data []byte, cfg *Config) {
if cfg == nil {
return
}
var legacy struct {
VerificationLoginPolicy string `json:"verificationLoginPolicy"`
VerificationEnabled *bool `json:"verificationEnabled"`
ExternalRecoveryEnabled *bool `json:"externalRecoveryEnabled"`
LoginPolicy *string `json:"loginPolicy"`
VerificationLoginPolicy string `json:"verificationLoginPolicy"`
}
if json.Unmarshal(data, &legacy) == nil {
cfg.LoginPolicy = strings.TrimSpace(legacy.VerificationLoginPolicy)
if json.Unmarshal(data, &legacy) != nil {
return
}
if legacy.VerificationEnabled == nil {
cfg.VerificationEnabled = true
}
if legacy.ExternalRecoveryEnabled == nil {
cfg.ExternalRecoveryEnabled = true
}
if legacy.LoginPolicy != nil && strings.TrimSpace(*legacy.LoginPolicy) != "" {
cfg.LoginPolicy = strings.TrimSpace(*legacy.LoginPolicy)
return
}
if policy := strings.TrimSpace(legacy.VerificationLoginPolicy); policy != "" {
cfg.LoginPolicy = policy
return
}
cfg.LoginPolicy = "new_device"
}
func (c *Config) fixPath() {
+29 -1
View File
@@ -744,6 +744,8 @@ func servicesForSection(section Section) []ServiceName {
return []ServiceName{ServiceSMTP}
case SectionEmail:
return []ServiceName{ServiceEmail}
case SectionMail:
return []ServiceName{ServiceSMTP, ServiceEmail}
case SectionSSL:
return []ServiceName{ServiceHTTP, ServiceSMTP, ServiceSSL}
case SectionPlugins:
@@ -813,12 +815,38 @@ func applySectionPayload(current RuntimeConfig, section Section, payload json.Ra
}
value.SMTPSectionConfig.Relay.Password = current.SMTP.Relay.Password
candidate.SMTP = value.SMTPSectionConfig
candidate.Email.Policy.LoginVerificationPolicy = candidate.SMTP.Relay.LoginPolicy
case SectionEmail:
var value EmailSectionConfig
if err := ParseStrict(payload, &value); err != nil {
return RuntimeConfig{}, err
}
candidate.Email = value
candidate.SMTP.Relay.LoginPolicy = candidate.Email.Policy.LoginVerificationPolicy
case SectionMail:
var value struct {
MailSectionConfig
RelayPasswordStatus json.RawMessage `json:"relayPasswordStatus"`
}
if err := ParseStrict(payload, &value); err != nil {
return RuntimeConfig{}, err
}
if value.MailSectionConfig.Relay.Password.Configured() {
return RuntimeConfig{}, ErrInvalidSecretChange
}
value.MailSectionConfig.Relay.Password = current.SMTP.Relay.Password
candidate.SMTP = SMTPSectionConfig{
Meta: value.Meta,
Listener: value.Listener,
Relay: value.Relay,
}
candidate.Email = EmailSectionConfig{
Meta: value.Meta,
IMAP: value.IMAP,
POP3: value.POP3,
Policy: value.Policy,
}
candidate.Email.Policy.LoginVerificationPolicy = candidate.SMTP.Relay.LoginPolicy
case SectionSSL:
var value SSLSectionConfig
if err := ParseStrict(payload, &value); err != nil {
@@ -901,7 +929,7 @@ func applySecretChanges(candidate *RuntimeConfig, section Section, changes map[s
return err
}
candidate.Root.Database.Password = stored
case section == SectionSMTP && name == "relay.password":
case (section == SectionSMTP || section == SectionMail) && name == "relay.password":
stored, err := ApplySecretChange(vault, candidate.SMTP.Relay.Password, change, SecretPolicy{Required: candidate.SMTP.Relay.Username != "", AllowClear: candidate.SMTP.Relay.Username == "", MaxLength: 4096}, now)
if err != nil {
return err
+264 -2
View File
@@ -96,6 +96,17 @@ func authorizedConfigActor() AuditActor {
return AuditActor{UserID: "1", Role: "super_admin", SessionID: "test-session", RecentAuth: true, RecoveryCodeConfigured: true}
}
func mailSectionFromRuntime(runtime RuntimeConfig) MailSectionConfig {
return MailSectionConfig{
Meta: runtime.SMTP.Meta,
Listener: runtime.SMTP.Listener,
Relay: runtime.SMTP.Relay,
IMAP: runtime.Email.IMAP,
POP3: runtime.Email.POP3,
Policy: runtime.Email.Policy,
}
}
type rejectingRuntimeSnapshotStore struct {
current RuntimeConfig
err error
@@ -372,6 +383,249 @@ func TestConfigManagerUpdateApplyUsesPendingGeneration(t *testing.T) {
}
}
func TestConfigManagerMailSectionRejectsNonStrictPayloadsAndDirectSecrets(t *testing.T) {
root := t.TempDir()
writeRuntimeFixture(t, root, validRuntimeConfig())
manager, err := NewConfigManager(root, ConfigLoaderOptions{Validation: RuntimeValidationOptions{HasSuperAdmin: true, Production: true}})
if err != nil {
t.Fatal(err)
}
mail := mailSectionFromRuntime(manager.Snapshot())
payload, err := json.Marshal(mail)
if err != nil {
t.Fatal(err)
}
unknown := append([]byte(nil), payload[:len(payload)-1]...)
unknown = append(unknown, []byte(`,"unknown":true}`)...)
if _, err := manager.Validate(context.Background(), ValidateRequest{Section: SectionMail, Payload: unknown}); err == nil {
t.Fatal("mail section accepted an unknown JSON field")
}
meta, err := json.Marshal(mail.Meta)
if err != nil {
t.Fatal(err)
}
duplicate := append([]byte(`{"meta":`), meta...)
duplicate = append(duplicate, ',')
duplicate = append(duplicate, payload[1:]...)
if _, err := manager.Validate(context.Background(), ValidateRequest{Section: SectionMail, Payload: duplicate}); err == nil {
t.Fatal("mail section accepted a duplicate JSON field")
}
mail.Relay.Password = StoredSecret{Ciphertext: "enc:v1:direct-secret", Version: credential.CurrentVersion, UpdatedAt: time.Now().UTC()}
directSecret, err := json.Marshal(mail)
if err != nil {
t.Fatal(err)
}
if _, err := manager.Validate(context.Background(), ValidateRequest{Section: SectionMail, Payload: directSecret}); !errors.Is(err, ErrInvalidSecretChange) {
t.Fatalf("direct relay secret error = %v, want invalid secret change", err)
}
}
func TestConfigManagerMailSectionAppliesBothPartitionsWithoutMailFile(t *testing.T) {
root := t.TempDir()
runtime := validRuntimeConfig()
vault, err := credential.NewVault(root)
if err != nil {
t.Fatal(err)
}
stored, err := ApplySecretChange(vault, StoredSecret{}, SecretChange{
Operation: SecretReplace,
Value: &SecretInput{Plaintext: "existing-relay-secret"},
}, SecretPolicy{Required: true, MaxLength: 4096}, time.Now().UTC())
if err != nil {
t.Fatal(err)
}
runtime.SMTP.Relay = SMTPConfig{
RelayHost: "smtp.example.com",
RelayPort: 587,
Username: "relay-user",
Password: stored,
Security: "starttls",
From: "no-reply@example.com",
FromDomain: "example.com",
VerificationEnabled: true,
LoginPolicy: "new_device",
}
runtime.Email.Policy.LoginVerificationPolicy = "new_device"
runtime.Email.Policy.ExternalRecoveryEnabled = true
writeRuntimeFixture(t, root, runtime)
options := ConfigLoaderOptions{Validation: RuntimeValidationOptions{HasSuperAdmin: true, Production: true}}
manager, err := NewConfigManager(root, options)
if err != nil {
t.Fatal(err)
}
mail := mailSectionFromRuntime(manager.Snapshot())
mail.Relay.Password = StoredSecret{}
mail.Listener = SMTPListenerConfig{Port: 2525, STARTTLSPort: 2587, TLSPort: 2465}
mail.IMAP.TLSPort = 2993
mail.POP3 = POP3ListenerConfig{Port: 2110, TLSPort: 2995}
mail.Policy.MaxMessageBytes = 8 << 20
mail.Policy.SpamFilterLevel = 2
payload, err := json.Marshal(mail)
if err != nil {
t.Fatal(err)
}
updated, err := manager.Update(context.Background(), UpdateRequest{
Section: SectionMail, ExpectedGeneration: 1, Payload: payload, Actor: authorizedConfigActor(),
})
if err != nil {
t.Fatal(err)
}
if updated.Candidate.SMTP.Relay.Password != stored {
t.Fatal("mail candidate did not preserve the existing relay secret")
}
status := manager.Status()
if len(status.PendingRestart) != 2 || status.PendingRestart[0] != ServiceSMTP || status.PendingRestart[1] != ServiceEmail {
t.Fatalf("mail pending restart services = %+v, want smtp and email", status.PendingRestart)
}
if _, err := manager.ApplyPendingAuthorized(context.Background(), updated.Generation, "wrong-candidate", SectionMail, authorizedConfigActor()); !errors.Is(err, ErrGenerationConflict) {
t.Fatalf("wrong candidate ID error = %v, want generation conflict", err)
}
if _, err := manager.ApplyPendingAuthorized(context.Background(), updated.Generation, updated.CandidateID, SectionSMTP, authorizedConfigActor()); !errors.Is(err, ErrGenerationConflict) {
t.Fatalf("wrong section error = %v, want generation conflict", err)
}
if _, err := manager.ApplyPendingAuthorized(context.Background(), updated.Generation+1, updated.CandidateID, SectionMail, authorizedConfigActor()); !errors.Is(err, ErrGenerationConflict) {
t.Fatalf("wrong generation error = %v, want generation conflict", err)
}
if _, err := manager.ApplyPendingAuthorized(context.Background(), updated.Generation, updated.CandidateID, SectionMail, authorizedConfigActor()); err != nil {
t.Fatal(err)
}
configDirectory := filepath.Join(root, "config")
if _, err := os.Stat(filepath.Join(configDirectory, "mail.json")); !os.IsNotExist(err) {
t.Fatalf("combined mail view was persisted as mail.json: %v", err)
}
for _, name := range []string{"smtp.json", "email.json"} {
data, err := os.ReadFile(filepath.Join(configDirectory, name))
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(data), `"generation":2`) {
t.Fatalf("%s was not updated to generation 2: %s", name, data)
}
}
reloaded, err := NewConfigLoader(root, options).Load()
if err != nil {
t.Fatal(err)
}
wantPorts := MailPorts{SMTP: 2525, SMTPSTARTTLS: 2587, SMTPTLS: 2465, IMAP: 2993, POP3: 2110, POP3TLS: 2995}
if got := ResolveMailPorts(reloaded.SMTP, reloaded.Email); got != wantPorts {
t.Fatalf("reloaded mail ports = %+v, want %+v", got, wantPorts)
}
if reloaded.Email.Policy.MaxMessageBytes != 8<<20 || reloaded.Email.Policy.SpamFilterLevel != 2 {
t.Fatalf("reloaded mail policy is incomplete: %+v", reloaded.Email.Policy)
}
if reloaded.SMTP.Relay.Password != stored {
t.Fatal("reloaded relay secret changed without an explicit secret operation")
}
}
func TestConfigManagerMailSectionSecretReplacementUsesVault(t *testing.T) {
root := t.TempDir()
writeRuntimeFixture(t, root, validRuntimeConfig())
manager, err := NewConfigManager(root, ConfigLoaderOptions{Validation: RuntimeValidationOptions{HasSuperAdmin: true, Production: true}})
if err != nil {
t.Fatal(err)
}
mail := mailSectionFromRuntime(manager.Snapshot())
mail.Relay = SMTPConfig{
RelayHost: "smtp.example.com",
RelayPort: 587,
Username: "relay-user",
Security: "starttls",
From: "no-reply@example.com",
FromDomain: "example.com",
}
payload, err := json.Marshal(mail)
if err != nil {
t.Fatal(err)
}
request := UpdateRequest{
Section: SectionMail, ExpectedGeneration: 1, Payload: payload, Actor: authorizedConfigActor(),
SecretChanges: map[string]SecretChange{
"relay.password": {Operation: SecretReplace, Value: &SecretInput{Plaintext: "new-relay-secret"}},
},
}
if _, err := manager.Update(context.Background(), request); !errors.Is(err, ErrStepUpRequired) {
t.Fatalf("mail secret replacement without step-up error = %v, want step-up required", err)
}
request.Confirmation = StepUpConfirmation{Confirmed: true, Method: "recent_auth"}
updated, err := manager.Update(context.Background(), request)
if err != nil {
t.Fatal(err)
}
stored := updated.Candidate.SMTP.Relay.Password
if !stored.Configured() || stored.Ciphertext == "new-relay-secret" || !credential.IsEncrypted(stored.Ciphertext) {
t.Fatalf("relay secret was not stored as managed ciphertext: %+v", stored)
}
plaintext, err := manager.vault.Decrypt(stored.Version, stored.Ciphertext)
if err != nil || plaintext != "new-relay-secret" {
t.Fatalf("relay secret cannot be recovered from the managed vault: value=%q error=%v", plaintext, err)
}
}
func TestConfigManagerMailSectionPreservesFieldsAcrossPageSpecificEdits(t *testing.T) {
root := t.TempDir()
runtime := validRuntimeConfig()
runtime.SMTP.Listener = SMTPListenerConfig{Port: 2525, STARTTLSPort: 2587, TLSPort: 2465}
runtime.Email.IMAP.TLSPort = 2993
runtime.Email.POP3 = POP3ListenerConfig{Port: 2110, TLSPort: 2995}
runtime.Email.Policy.MaxMessageBytes = 4 << 20
writeRuntimeFixture(t, root, runtime)
options := ConfigLoaderOptions{Validation: RuntimeValidationOptions{HasSuperAdmin: true, Production: true}}
manager, err := NewConfigManager(root, options)
if err != nil {
t.Fatal(err)
}
securityEdit := mailSectionFromRuntime(manager.Snapshot())
securityEdit.Relay.VerificationEnabled = true
securityEdit.Relay.LoginPolicy = "new_device"
securityEdit.Policy.ExternalRecoveryEnabled = true
securityPayload, err := json.Marshal(securityEdit)
if err != nil {
t.Fatal(err)
}
updated, err := manager.Update(context.Background(), UpdateRequest{
Section: SectionMail, ExpectedGeneration: 1, Payload: securityPayload, Actor: authorizedConfigActor(),
})
if err != nil {
t.Fatal(err)
}
if _, err := manager.ApplyPendingAuthorized(context.Background(), updated.Generation, updated.CandidateID, SectionMail, authorizedConfigActor()); err != nil {
t.Fatal(err)
}
afterSecurity := manager.Snapshot()
wantPorts := MailPorts{SMTP: 2525, SMTPSTARTTLS: 2587, SMTPTLS: 2465, IMAP: 2993, POP3: 2110, POP3TLS: 2995}
if got := ResolveMailPorts(afterSecurity.SMTP, afterSecurity.Email); got != wantPorts || afterSecurity.Email.Policy.MaxMessageBytes != 4<<20 {
t.Fatal("security policy edit overwrote mail listener or policy fields")
}
mailEdit := mailSectionFromRuntime(afterSecurity)
mailEdit.Policy.MaxMessageBytes = 12 << 20
mailPayload, err := json.Marshal(mailEdit)
if err != nil {
t.Fatal(err)
}
updated, err = manager.Update(context.Background(), UpdateRequest{
Section: SectionMail, ExpectedGeneration: 2, Payload: mailPayload, Actor: authorizedConfigActor(),
})
if err != nil {
t.Fatal(err)
}
if _, err := manager.ApplyPendingAuthorized(context.Background(), updated.Generation, updated.CandidateID, SectionMail, authorizedConfigActor()); err != nil {
t.Fatal(err)
}
afterMail := manager.Snapshot()
if !afterMail.SMTP.Relay.VerificationEnabled || afterMail.SMTP.Relay.LoginPolicy != "new_device" ||
afterMail.Email.Policy.LoginVerificationPolicy != "new_device" || !afterMail.Email.Policy.ExternalRecoveryEnabled {
t.Fatal("mail page edit overwrote security policy fields")
}
}
func TestTransactionRecoveryRestoresOldGenerationAfterSectionFailure(t *testing.T) {
root := t.TempDir()
current := validRuntimeConfig()
@@ -688,7 +942,13 @@ func TestConfigManagerSecretChangesRequireStepUpAndPreserveStoredSecret(t *testi
func TestConfigManagerSecretClearRequiresExplicitConfirmation(t *testing.T) {
root := t.TempDir()
runtime := validRuntimeConfig()
runtime.SMTP.Relay = SMTPConfig{}
runtime.SMTP.Relay = SMTPConfig{
RelayHost: "smtp.example.com",
RelayPort: 587,
Security: "starttls",
From: "no-reply@example.com",
FromDomain: "example.com",
}
writeRuntimeFixture(t, root, runtime)
options := ConfigLoaderOptions{Validation: RuntimeValidationOptions{HasSuperAdmin: true, Production: true}}
manager, err := NewConfigManager(root, options)
@@ -696,6 +956,7 @@ func TestConfigManagerSecretClearRequiresExplicitConfirmation(t *testing.T) {
t.Fatal(err)
}
smtp := manager.Snapshot().SMTP
smtp.Relay.Username = "relay-user"
payload, err := json.Marshal(smtp)
if err != nil {
t.Fatal(err)
@@ -713,6 +974,7 @@ func TestConfigManagerSecretClearRequiresExplicitConfirmation(t *testing.T) {
t.Fatal(err)
}
smtp = manager.Snapshot().SMTP
smtp.Relay.Username = ""
smtp.Relay.Password = StoredSecret{}
payload, err = json.Marshal(smtp)
if err != nil {
@@ -1255,7 +1517,7 @@ func TestConfigManagerStatusReportsPendingRestartServices(t *testing.T) {
}
current := manager.Snapshot()
smtp := current.SMTP
smtp.Relay.RelayPort++
smtp.Listener.Port++
payload, err := json.Marshal(smtp)
if err != nil {
t.Fatal(err)
+16 -6
View File
@@ -78,8 +78,8 @@ type legacyMigrationConfig struct {
SMTPSecurity string `json:"smtpSecurity"`
SMTPFrom string `json:"smtpFrom"`
SMTPFromDomain string `json:"smtpFromDomain"`
VerificationEnabled bool `json:"verificationEnabled"`
ExternalRecoveryEnabled bool `json:"externalRecoveryEnabled"`
VerificationEnabled *bool `json:"verificationEnabled"`
ExternalRecoveryEnabled *bool `json:"externalRecoveryEnabled"`
LoginPolicy string `json:"loginPolicy"`
VerificationLoginPolicy string `json:"verificationLoginPolicy"`
PluginAllowList []string `json:"pluginAllowList"`
@@ -514,7 +514,7 @@ func legacyRuntimeConfig(root string, legacy legacyMigrationConfig) (RuntimeConf
POP3Port: 110,
SpamFilterLevel: legacy.SpamFilterLevel,
LoginVerificationPolicy: legacyLoginPolicy(legacy),
ExternalRecoveryEnabled: legacy.ExternalRecoveryEnabled,
ExternalRecoveryEnabled: legacyBoolDefault(legacy.ExternalRecoveryEnabled, true),
}},
SSL: SSLSectionConfig{Meta: meta, TLS: ssl},
Plugins: PluginsSectionConfig{Meta: meta, Plugins: plugins},
@@ -705,13 +705,13 @@ func legacySMTPConfig(root string, vault *credential.Vault, legacy legacyMigrati
Security: legacy.SMTPSecurity,
From: legacy.SMTPFrom,
FromDomain: legacy.SMTPFromDomain,
VerificationEnabled: legacy.VerificationEnabled,
VerificationEnabled: legacyBoolDefault(legacy.VerificationEnabled, true),
LoginPolicy: legacyLoginPolicy(legacy),
}
if relay.FromDomain == "" {
relay.FromDomain = legacy.Domain
}
if !relay.VerificationEnabled && relay.RelayHost == "" && relay.RelayPort == 0 && relay.Username == "" && legacy.SMTPPassword == "" {
if relay.RelayHost == "" && relay.RelayPort == 0 && relay.Username == "" && legacy.SMTPPassword == "" {
return relay, nil, nil
}
if relay.RelayPort == 0 {
@@ -871,7 +871,17 @@ func legacyLoginPolicy(legacy legacyMigrationConfig) string {
if legacy.LoginPolicy != "" {
return legacy.LoginPolicy
}
return legacy.VerificationLoginPolicy
if legacy.VerificationLoginPolicy != "" {
return legacy.VerificationLoginPolicy
}
return "new_device"
}
func legacyBoolDefault(value *bool, fallback bool) bool {
if value == nil {
return fallback
}
return *value
}
func legacyControlledReference(value string) (string, bool) {
+59
View File
@@ -100,6 +100,65 @@ func TestMigrateLegacyConfigPreservesBackupAndLoadsPartitions(t *testing.T) {
}
}
func TestLegacySecurityDefaultsPreserveExplicitValues(t *testing.T) {
falseValue := false
tests := []struct {
name string
legacy legacyMigrationConfig
verification bool
recovery bool
policy string
}{
{
name: "missing values use secure defaults",
verification: true,
recovery: true,
policy: "new_device",
},
{
name: "explicit false values are preserved",
legacy: legacyMigrationConfig{
VerificationEnabled: &falseValue,
ExternalRecoveryEnabled: &falseValue,
LoginPolicy: "off",
},
policy: "off",
},
{
name: "legacy policy is preserved",
legacy: legacyMigrationConfig{
VerificationLoginPolicy: "always",
},
verification: true,
recovery: true,
policy: "always",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
runtime, manualFields, err := legacyRuntimeConfig(t.TempDir(), test.legacy)
if err != nil {
t.Fatal(err)
}
if len(manualFields) != 0 {
t.Fatalf("unexpected manual fields: %+v", manualFields)
}
if runtime.SMTP.Relay.VerificationEnabled != test.verification ||
runtime.Email.Policy.ExternalRecoveryEnabled != test.recovery ||
runtime.SMTP.Relay.LoginPolicy != test.policy ||
runtime.Email.Policy.LoginVerificationPolicy != test.policy {
t.Fatalf("security migration = verification %t, recovery %t, smtp policy %q, email policy %q",
runtime.SMTP.Relay.VerificationEnabled,
runtime.Email.Policy.ExternalRecoveryEnabled,
runtime.SMTP.Relay.LoginPolicy,
runtime.Email.Policy.LoginVerificationPolicy,
)
}
})
}
}
func TestMigrateLegacyConfigResumesAfterNonSecretPartitionWrite(t *testing.T) {
root := t.TempDir()
original := writeLegacyMigrationFixture(t, root, map[string]any{
+1 -1
View File
@@ -61,7 +61,7 @@ func runtimeCompatibility(runtime RuntimeConfig) (*Config, error) {
DkimPrivateKeyPath: filepath.Join(ROOT_PATH, "config", "dkim", "dkim.priv"),
SSLType: SSLTypeUser,
SpamFilterLevel: runtime.Email.Policy.SpamFilterLevel,
LoginPolicy: runtime.Email.Policy.LoginVerificationPolicy,
LoginPolicy: runtime.SMTP.Relay.LoginPolicy,
ExternalRecoveryEnabled: runtime.Email.Policy.ExternalRecoveryEnabled,
SMTPHost: runtime.SMTP.Relay.RelayHost, SMTPPort: runtime.SMTP.Relay.RelayPort,
SMTPUsername: runtime.SMTP.Relay.Username, SMTPSecurity: runtime.SMTP.Relay.Security,
+11
View File
@@ -13,6 +13,7 @@ type Section string
const (
SectionRoot Section = "root"
SectionMail Section = "mail"
SectionSMTP Section = "smtp"
SectionEmail Section = "email"
SectionSSL Section = "ssl"
@@ -66,6 +67,16 @@ type EmailSectionConfig struct {
POP3 POP3ListenerConfig `json:"pop3,omitempty"`
}
// MailSectionConfig 是 API 与候选配置使用的组合视图,磁盘仍分别保存 smtp.json 和 email.json。
type MailSectionConfig struct {
Meta SectionMeta `json:"meta"`
Listener SMTPListenerConfig `json:"listener"`
Relay SMTPConfig `json:"relay"`
IMAP IMAPListenerConfig `json:"imap"`
POP3 POP3ListenerConfig `json:"pop3"`
Policy EmailConfig `json:"policy"`
}
type SSLSectionConfig struct {
Meta SectionMeta `json:"meta"`
TLS SSLConfig `json:"tls"`
+28 -43
View File
@@ -117,68 +117,53 @@ func validateSMTP(smtp SMTPConfig) error {
if !validLoginVerificationPolicy(smtp.LoginPolicy) {
return ErrInvalidSMTP
}
if smtp.RelayHost != "" && !validSMTPHost(smtp.RelayHost) {
return ErrInvalidSMTP
}
if smtp.RelayPort != 0 && !validPort(smtp.RelayPort) {
return ErrInvalidSMTP
}
if smtp.FromDomain != "" && !validCanonicalDomain(smtp.FromDomain) {
return ErrInvalidSMTP
}
if strings.TrimSpace(smtp.Username) != smtp.Username {
return ErrInvalidSMTP
}
if err := ValidateStoredSecret(smtp.Password, false); err != nil {
return ErrInvalidSMTP
}
if smtp.From != "" {
parsedFrom, err := mail.ParseAddress(smtp.From)
if err != nil || parsedFrom.Address != smtp.From || strings.ContainsAny(smtp.From, "\r\n") {
return ErrInvalidSMTP
}
}
if !smtp.VerificationEnabled {
if smtp.RelayHost != "" && !validSMTPHost(smtp.RelayHost) {
return ErrInvalidSMTP
}
if smtp.RelayPort != 0 && !validPort(smtp.RelayPort) {
return ErrInvalidSMTP
}
if smtp.FromDomain != "" && !validCanonicalDomain(smtp.FromDomain) {
return ErrInvalidSMTP
}
if strings.TrimSpace(smtp.Username) != smtp.Username {
return ErrInvalidSMTP
}
if err := ValidateStoredSecret(smtp.Password, false); err != nil {
return ErrInvalidSMTP
}
if smtp.Username != "" {
if err := ValidateStoredSecret(smtp.Password, true); err != nil {
return ErrInvalidSMTP
}
}
if smtp.Security != "" {
switch smtp.Security {
case "starttls", "implicit_tls", "tls":
case "plain":
if !isLocalSMTPHost(smtp.RelayHost) {
return ErrInvalidSMTP
}
default:
if smtp.Security != "" {
switch smtp.Security {
case "starttls", "implicit_tls", "tls":
case "plain":
if !isLocalSMTPHost(smtp.RelayHost) {
return ErrInvalidSMTP
}
default:
return ErrInvalidSMTP
}
}
relayConfigured := smtp.RelayHost != "" || smtp.RelayPort != 0 || smtp.Username != "" ||
smtp.Password.Configured() || smtp.Security != "" || smtp.From != ""
if !relayConfigured {
return nil
}
if !validSMTPHost(smtp.RelayHost) || !validPort(smtp.RelayPort) || !validCanonicalDomain(smtp.FromDomain) || smtp.From == "" {
return ErrInvalidSMTP
}
if strings.TrimSpace(smtp.Username) != smtp.Username {
if smtp.RelayHost == "" || smtp.RelayPort == 0 || smtp.Security == "" || smtp.From == "" || smtp.FromDomain == "" {
return ErrInvalidSMTP
}
if smtp.Username == "" {
if err := ValidateStoredSecret(smtp.Password, false); err != nil || smtp.Password.Configured() {
if smtp.Password.Configured() {
return ErrInvalidSMTP
}
} else if err := ValidateStoredSecret(smtp.Password, true); err != nil {
return ErrInvalidSMTP
}
switch smtp.Security {
case "starttls", "implicit_tls", "tls":
case "plain":
if !isLocalSMTPHost(smtp.RelayHost) {
return ErrInvalidSMTP
}
default:
return ErrInvalidSMTP
}
return nil
}
+51
View File
@@ -168,6 +168,57 @@ func TestValidateRuntimeConfigRejectsUnsafeCrossSectionValues(t *testing.T) {
}
}
func TestValidateSMTPKeepsLoginVerificationIndependentFromRelay(t *testing.T) {
tests := []struct {
name string
smtp SMTPConfig
valid bool
}{
{
name: "verification enabled without relay",
smtp: SMTPConfig{
VerificationEnabled: true,
LoginPolicy: "new_device",
FromDomain: "example.com",
},
valid: true,
},
{
name: "partially configured relay",
smtp: SMTPConfig{
RelayHost: "smtp.example.com",
RelayPort: 587,
Security: "starttls",
LoginPolicy: "new_device",
},
},
{
name: "complete relay",
smtp: SMTPConfig{
RelayHost: "smtp.example.com",
RelayPort: 587,
Security: "starttls",
From: "no-reply@example.com",
FromDomain: "example.com",
LoginPolicy: "new_device",
},
valid: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
err := validateSMTP(test.smtp)
if test.valid && err != nil {
t.Fatalf("validateSMTP() error = %v", err)
}
if !test.valid && !errors.Is(err, ErrInvalidSMTP) {
t.Fatalf("validateSMTP() error = %v, want %v", err, ErrInvalidSMTP)
}
})
}
}
func TestSnapshotStoreRejectsInvalidCandidateWithoutChangingSnapshot(t *testing.T) {
initial := validRuntimeConfig()
store, err := NewSnapshotStore(initial, RuntimeValidationOptions{HasSuperAdmin: true, Production: true})