From 9dc861d560eefb4d000305b66002b4db7d8049d2 Mon Sep 17 00:00:00 2001 From: smail Date: Wed, 9 Sep 2026 17:42:19 +0800 Subject: [PATCH] =?UTF-8?q?=E8=A7=92=E8=89=B2=E6=9D=83=E9=99=90=E6=94=B6?= =?UTF-8?q?=E7=B4=A7=E5=89=8D=E4=BF=9D=E5=AD=98=E8=AF=81=E4=B9=A6=E7=9B=B4?= =?UTF-8?q?=E6=8E=A5=E5=BC=95=E7=94=A8=E4=B8=8E=E7=BB=AD=E6=9C=9F=E7=83=AD?= =?UTF-8?q?=E5=88=87=E6=8D=A2=E6=94=B9=E9=80=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/config/data_paths.go | 2 + backend/config/manager_v2.go | 5 +- backend/config/model.go | 16 +- backend/config/partitioned_compatibility.go | 3 +- .../config/partitioned_compatibility_test.go | 2 +- backend/config/ssl_commit.go | 19 +- backend/config/ssl_custom.go | 71 ++++- backend/config/ssl_expiry.go | 84 ++++++ backend/config/ssl_flat.go | 221 +++++++++++++++ backend/config/ssl_live.go | 132 +++++++++ backend/config/ssl_migration.go | 143 ++++++++++ backend/config/ssl_retention.go | 46 +++- backend/config/ssl_storage.go | 55 ++-- backend/config/ssl_storage_test.go | 52 ++-- backend/config/validator.go | 23 ++ backend/internal/app/app.go | 3 + backend/listen/cron_server/ssl_update.go | 37 +-- backend/listen/http_server/https_server.go | 5 +- backend/listen/imap_server/imap_server.go | 7 +- .../listen/imap_server/imap_server_test.go | 2 +- backend/listen/pop3_server/pop3server.go | 9 +- backend/listen/smtp_server/smtp.go | 13 +- backend/services/setup/ssl/ssl.go | 27 +- .../setup/ssl/user_certificate_test.go | 2 +- backend/utils/runtimepath/business_keys.go | 4 +- deploy/runtime-config.mjs | 42 ++- docs/部署后自动归档与证书保留.md | 56 +++- frontend/dev-tls.js | 71 +++++ .../ConfigSettings/ConfigForm/ConfigForm.js | 12 +- frontend/vite.config.js | 12 +- test/backend/deployment_state_test.go | 2 +- test/backend/mail_listeners_test.go | 9 +- test/backend/operation_log_test.go | 4 +- test/backend/ssl_custom_test.go | 4 +- test/backend/ssl_lifecycle_test.go | 255 ++++++++++++++++++ test/backend/ssl_retention_test.go | 49 +++- test/deployment/verify_ssl_startup.py | 2 +- test/frontend/config-form.test.mjs | 2 +- test/frontend/dev-tls.test.mjs | 95 +++++++ test/frontend/runtime-deployment.test.mjs | 7 +- test/run.mjs | 1 + 41 files changed, 1408 insertions(+), 198 deletions(-) create mode 100644 backend/config/ssl_expiry.go create mode 100644 backend/config/ssl_flat.go create mode 100644 backend/config/ssl_live.go create mode 100644 backend/config/ssl_migration.go create mode 100644 frontend/dev-tls.js create mode 100644 test/backend/ssl_lifecycle_test.go create mode 100644 test/frontend/dev-tls.test.mjs diff --git a/backend/config/data_paths.go b/backend/config/data_paths.go index db961b26..a71ff76e 100644 --- a/backend/config/data_paths.go +++ b/backend/config/data_paths.go @@ -8,5 +8,7 @@ func normalizeSSLDataReferences(ssl SSLConfig) SSLConfig { ssl.CustomDirectory = runtimepath.LegacyReference(ssl.CustomDirectory) ssl.CertificateRef = runtimepath.LegacyReference(ssl.CertificateRef) ssl.PrivateKeyRef = runtimepath.LegacyReference(ssl.PrivateKeyRef) + ssl.PreviousCertificateRef = runtimepath.LegacyReference(ssl.PreviousCertificateRef) + ssl.PreviousPrivateKeyRef = runtimepath.LegacyReference(ssl.PreviousPrivateKeyRef) return ssl } diff --git a/backend/config/manager_v2.go b/backend/config/manager_v2.go index e21a35d5..e5d719be 100644 --- a/backend/config/manager_v2.go +++ b/backend/config/manager_v2.go @@ -281,6 +281,7 @@ func (m *ConfigManager) Validate(ctx context.Context, req ValidateRequest) (*Val } return &ValidationResult{Valid: false, Generation: current.Generation, Issues: []PublicIssue{issue}}, nil } + retainPreviousSSL(m.loader.root, &candidate.SSL.TLS, current.SSL.TLS) } setCandidateGeneration(&candidate, current.Generation+1) if err := ValidateRuntimeConfig(candidate, m.options); err != nil { @@ -321,6 +322,7 @@ func (m *ConfigManager) Update(ctx context.Context, req UpdateRequest) (*UpdateR if err != nil { return nil, err } + retainPreviousSSL(m.loader.root, &candidate.SSL.TLS, current.SSL.TLS) } if err := contextError(ctx); err != nil { return nil, err @@ -348,7 +350,7 @@ func (m *ConfigManager) Update(ctx context.Context, req UpdateRequest) (*UpdateR setCandidateGeneration(&candidate, current.Generation+1) m.mu.Lock() m.pending = &pendingConfig{ID: id, Candidate: candidate, Section: req.Section, Actor: req.Actor, Confirmation: req.Confirmation, PreviousRestart: append([]ServiceName(nil), m.status.PendingRestart...)} - m.status.PendingRestart = mergeServices(m.status.PendingRestart, servicesForSection(req.Section)) + m.status.PendingRestart = mergeServices(m.status.PendingRestart, servicesForChange(req.Section, current, candidate)) m.mu.Unlock() return &UpdateResult{CandidateID: id, Generation: candidate.Generation, Candidate: cloneRuntimeConfig(candidate), Pending: true}, nil } @@ -677,6 +679,7 @@ func (m *ConfigManager) rollbackWithState(ctx context.Context, generation uint64 if err := validateRollbackSSL(m.loader.root, candidate); err != nil { return nil, false, err } + retainPreviousSSL(m.loader.root, &candidate.SSL.TLS, current.SSL.TLS) setCandidateGeneration(&candidate, current.Generation+1) candidate.Root.UpdatedAt = time.Now().UTC() if err := ValidateRuntimeConfig(candidate, m.options); err != nil { diff --git a/backend/config/model.go b/backend/config/model.go index 476af071..3249e3b6 100644 --- a/backend/config/model.go +++ b/backend/config/model.go @@ -104,13 +104,15 @@ type EmailConfig struct { } type SSLConfig struct { - Management string `json:"management,omitempty"` - Mode string `json:"mode"` - DefaultDirectory string `json:"defaultDirectory"` - CustomDirectory string `json:"customDirectory,omitempty"` - Challenge string `json:"challenge,omitempty"` - CertificateRef string `json:"certificateRef,omitempty"` - PrivateKeyRef string `json:"privateKeyRef,omitempty"` + Management string `json:"management,omitempty"` + Mode string `json:"mode"` + DefaultDirectory string `json:"defaultDirectory"` + CustomDirectory string `json:"customDirectory,omitempty"` + Challenge string `json:"challenge,omitempty"` + CertificateRef string `json:"certificateRef,omitempty"` + PrivateKeyRef string `json:"privateKeyRef,omitempty"` + PreviousCertificateRef string `json:"previousCertificateRef,omitempty"` + PreviousPrivateKeyRef string `json:"previousPrivateKeyRef,omitempty"` } type PluginConfig struct { diff --git a/backend/config/partitioned_compatibility.go b/backend/config/partitioned_compatibility.go index ffb9d439..e5a24040 100644 --- a/backend/config/partitioned_compatibility.go +++ b/backend/config/partitioned_compatibility.go @@ -7,7 +7,6 @@ import ( "net/url" "path/filepath" "strconv" - "strings" "git.pcux.cn/xuans/Smail/utils/credential" "git.pcux.cn/xuans/Smail/utils/runtimepath" @@ -87,7 +86,7 @@ func runtimeCompatibility(runtime RuntimeConfig) (*Config, error) { } } // 迁移器保留的旧证书引用仍走严格的只读文件校验;新托管引用沿用托管解析器。 - if strings.HasPrefix(tls.CertificateRef, managedSSLRelativeRoot+"/") || strings.HasPrefix(tls.CertificateRef, "ssl/managed/") { + if validManagedSSLMode(tls.Mode) { cfg.SSL = tls } else { cfg.SSLPublicKeyPath = resolvePath(tls.CertificateRef) diff --git a/backend/config/partitioned_compatibility_test.go b/backend/config/partitioned_compatibility_test.go index c806ef9e..0524b2b7 100644 --- a/backend/config/partitioned_compatibility_test.go +++ b/backend/config/partitioned_compatibility_test.go @@ -76,7 +76,7 @@ func TestPartitionedCompatibilityStartupAndWriteProtection(t *testing.T) { if !cfg.IsSetupReady() || cfg.DbType != DBTypeSQLite || cfg.DbDSN != filepath.Join(root, "data", "existing.db") { t.Fatal("partitioned startup lost initialization or database identity") } - if cfg.WebDomain != "mail.example.com" || cfg.SSLPublicKeyPath != filepath.Join(root, "data", "ssl", "site.crt") { + if cfg.WebDomain != "mail.example.com" || cfg.SSL.CertificateRef != "data/ssl/site.crt" { t.Fatal("partitioned startup lost domain or certificate path") } } diff --git a/backend/config/ssl_commit.go b/backend/config/ssl_commit.go index e10745f6..4f654975 100644 --- a/backend/config/ssl_commit.go +++ b/backend/config/ssl_commit.go @@ -19,6 +19,7 @@ func WriteSSLConfig(expected, next *Config) error { } sslCommitMu.Lock() defer sslCommitMu.Unlock() + retainPreviousSSL(ROOT_PATH, &next.SSL, expected.SSL) legacyConfigMu.Lock() defer legacyConfigMu.Unlock() data, err := readConfigFile("config.json") @@ -87,6 +88,9 @@ func WriteSSLConfig(expected, next *Config) error { candidate := cloneRuntimeConfig(current) candidate.SSL.TLS = next.SSL candidate.Root.HTTP.HTTPSEnabled = next.HttpsEnabled == 1 + if err := validateCustomSSLReferences(ROOT_PATH, candidate); err != nil { + return err + } setCandidateGeneration(&candidate, current.Generation+1) if err := ValidateRuntimeConfig(candidate, manager.options); err != nil { return err @@ -118,7 +122,7 @@ func WriteSSLConfig(expected, next *Config) error { Actor: AuditActor{UserID: "system", Role: "system"}, PreviousRestart: append([]ServiceName(nil), manager.status.PendingRestart...), } - manager.status.PendingRestart = mergeServices(manager.status.PendingRestart, servicesForSection(SectionSSL)) + manager.status.PendingRestart = mergeServices(manager.status.PendingRestart, servicesForChange(SectionSSL, current, candidate)) manager.mu.Unlock() if err := manager.publishSnapshot(candidate); err != nil { return err @@ -139,7 +143,7 @@ func WriteSSLConfig(expected, next *Config) error { return manager.writeAudit(context.Background(), ConfigAuditEvent{ Operation: ConfigOperationUpdate, Section: SectionSSL, ActorID: "system", ActorRole: "system", FromGeneration: current.Generation, ToGeneration: candidate.Generation, - Changes: AuditChanges(current, candidate), + Changes: AuditChanges(current, candidate), ChangedFields: []string{"tls"}, Result: "success", CreatedAt: now, }) } @@ -152,6 +156,17 @@ func sameSSLPolicy(left, right *Config) bool { left.TLSMode == right.TLSMode } +// 材料和续期策略均可热更新;只有实际监听配置发生变化才提示重启。 +func servicesForChange(section Section, previous, next RuntimeConfig) []ServiceName { + if section == SectionSSL { + if !reflect.DeepEqual(previous.Root.HTTP, next.Root.HTTP) { + return []ServiceName{ServiceHTTP} + } + return nil + } + return servicesForSection(section) +} + func mergeServices(previous, next []ServiceName) []ServiceName { result := append([]ServiceName(nil), previous...) for _, service := range next { diff --git a/backend/config/ssl_custom.go b/backend/config/ssl_custom.go index a25551e9..12c6ef77 100644 --- a/backend/config/ssl_custom.go +++ b/backend/config/ssl_custom.go @@ -12,7 +12,7 @@ import ( var ErrSSLFileUnavailable = errors.New("SSL certificate file is missing or unreadable") -// customSSLMaterial 在只读准备阶段保留已校验的材料,确认后再暂存,避免重新读取外部文件。 +// customSSLMaterial 保留只读准备结果;自定义文件只验证和引用,不复制。 type customSSLMaterial struct { privateKey []byte certificate []byte @@ -22,7 +22,7 @@ type customSSLMaterial struct { func prepareCustomSSLPaths(root string, candidate *RuntimeConfig) (*customSSLMaterial, error) { candidate.SSL.TLS = normalizeSSLDataReferences(candidate.SSL.TLS) ssl := &candidate.SSL.TLS - if EffectiveSSLManagement(*ssl) != SSLManagementCustom { + if EffectiveSSLManagement(*ssl) == SSLManagementProject { return nil, nil } certificatePath := strings.TrimSpace(ssl.CertificateRef) @@ -62,9 +62,8 @@ func prepareCustomSSLPaths(root string, candidate *RuntimeConfig) (*customSSLMat ssl.Mode = ManagedSSLModeUpload ssl.DefaultDirectory = runtimepath.SSLReference(root, "data/ssl") ssl.CustomDirectory = runtimepath.SSLReference(root, "data/ssl") - // 仅在内存中使用合法占位引用完成跨分区校验,最终候选必须换成独立版本。 - ssl.CertificateRef = managedSSLReferenceAtRoot(root, ManagedSSLModeUpload, "public.crt") - ssl.PrivateKeyRef = managedSSLReferenceAtRoot(root, ManagedSSLModeUpload, "private.key") + ssl.CertificateRef = directSSLReference(root, certificatePath) + ssl.PrivateKeyRef = directSSLReference(root, privateKeyPath) return material, nil } @@ -72,16 +71,48 @@ func (material *customSSLMaterial) stage(root string, candidate *RuntimeConfig) if material == nil { return nil } - reference, err := stageManagedSSLAtRoot(root, ManagedSSLModeUpload, material.privateKey, material.certificate, nil, material.domains) - if err != nil { - return err + return validateCustomSSLReferences(root, *candidate) +} + +// 部署目录内使用清晰的相对路径,目录外保留完整绝对路径。 +func directSSLReference(root, path string) string { + absoluteRoot, err := filepath.Abs(root) + if err == nil && pathWithin(absoluteRoot, path) { + if relative, err := filepath.Rel(absoluteRoot, path); err == nil { + return filepath.ToSlash(relative) + } } - candidate.SSL.TLS.CertificateRef = reference.CertificateRef - candidate.SSL.TLS.PrivateKeyRef = reference.PrivateKeyRef - return nil + return filepath.ToSlash(path) +} + +// ValidateDirectSSLPaths 供初始化使用,与配置管理共用相同的文件安全校验。 +func ValidateDirectSSLPaths(certificatePath, privateKeyPath string, domains []string) (ManagedSSLReference, error) { + publicPath, err := resolveCustomSSLInput(ROOT_PATH, certificatePath) + if err != nil { + return ManagedSSLReference{}, err + } + privatePath, err := resolveCustomSSLInput(ROOT_PATH, privateKeyPath) + if err != nil { + return ManagedSSLReference{}, err + } + publicKey, err := readExternalSSLFile(publicPath, false) + if err != nil { + return ManagedSSLReference{}, err + } + privateKey, err := readExternalSSLFile(privatePath, true) + if err != nil { + return ManagedSSLReference{}, err + } + if err := validateSSLMaterial(privateKey, publicKey, nil, domains); err != nil { + return ManagedSSLReference{}, err + } + return ManagedSSLReference{Mode: ManagedSSLModeUpload, CertificateRef: directSSLReference(ROOT_PATH, publicPath), PrivateKeyRef: directSSLReference(ROOT_PATH, privatePath), CertificatePath: publicPath, PrivateKeyPath: privatePath}, nil } func resolveCustomSSLInput(root, value string) (string, error) { + if strings.TrimSpace(value) == "" || strings.ContainsRune(value, 0) { + return "", ErrInvalidSSLReference + } for _, part := range strings.FieldsFunc(value, func(r rune) bool { return r == '/' || r == '\\' }) { if part == ".." { return "", ErrInvalidSSLReference @@ -137,7 +168,7 @@ func readExternalSSLFile(path string, privateKey bool) ([]byte, error) { func validateCustomSSLReferences(root string, candidate RuntimeConfig) error { ssl := candidate.SSL.TLS - if EffectiveSSLManagement(ssl) != SSLManagementCustom || ssl.CertificateRef == "" && ssl.PrivateKeyRef == "" { + if ssl.CertificateRef == "" && ssl.PrivateKeyRef == "" { return nil } reference, err := resolveManagedSSLReferencesAtRoot(root, ssl) @@ -152,7 +183,21 @@ func validateCustomSSLReferences(root string, candidate RuntimeConfig) error { if err != nil { return err } - return validateSSLMaterial(privateKey, certificate, nil, runtimeCertificateDomains(&candidate)) + return validateSSLMaterial(privateKey, certificate, nil, validationCertificateDomains(&candidate)) +} + +func validationCertificateDomains(candidate *RuntimeConfig) []string { + if EffectiveSSLManagement(candidate.SSL.TLS) == SSLManagementProject && candidate.SSL.TLS.Challenge == SSLChallengeDNS { + domains := []string{"*." + strings.TrimPrefix(candidate.Root.Domains.Primary, "*.")} + if candidate.Root.Domains.Web != "" { + domains = append(domains, candidate.Root.Domains.Web) + } + for _, domain := range candidate.Root.Domains.Accepted { + domains = append(domains, "smtp."+domain, "imap."+domain, "pop."+domain) + } + return domains + } + return runtimeCertificateDomains(candidate) } func runtimeCertificateDomains(candidate *RuntimeConfig) []string { diff --git a/backend/config/ssl_expiry.go b/backend/config/ssl_expiry.go new file mode 100644 index 00000000..6fcf22e9 --- /dev/null +++ b/backend/config/ssl_expiry.go @@ -0,0 +1,84 @@ +package config + +import ( + "os" + "time" + + log "github.com/sirupsen/logrus" +) + +// 调用方持有配置写锁;先事务清除过期引用,再由文件维护回收材料。 +func (m *ConfigManager) clearExpiredPreviousSSL() error { + m.mu.RLock() + current := cloneRuntimeConfig(m.current) + pending := m.pending + m.mu.RUnlock() + if pending != nil { + if pending.Committed && pending.Actor.UserID == "ssl-maintenance" { + return m.publishExpiredSSL(pending.Candidate) + } + return nil + } + ssl := current.SSL.TLS + if ssl.PreviousCertificateRef == "" { + return nil + } + path, err := resolveCustomSSLInput(m.loader.root, ssl.PreviousCertificateRef) + if err != nil { + return err + } + if _, err := resolveManagedSSLReferencesAtRoot(m.loader.root, ssl); err != nil { + return err + } + _, statErr := os.Lstat(path) + if !os.IsNotExist(statErr) { + data, err := readExternalSSLFile(path, false) + if err != nil { + return err + } + certificates, err := parseCertificatePEM(data) + if err != nil || len(certificates) == 0 { + return ErrInvalidSSLMaterial + } + if time.Now().Before(certificates[0].NotAfter) { + return nil + } + } + candidate := cloneRuntimeConfig(current) + candidate.SSL.TLS.PreviousCertificateRef = "" + candidate.SSL.TLS.PreviousPrivateKeyRef = "" + setCandidateGeneration(&candidate, current.Generation+1) + if err := m.snapshots.Validate(candidate); err != nil { + return err + } + id, err := newRollbackTicketID() + if err != nil { + return err + } + if err := m.transactions.Commit(current, candidate); err != nil { + return err + } + // 事务已经落盘时保留恢复入口;下轮维护重试发布,不再次提交同一代次。 + m.mu.Lock() + m.pending = &pendingConfig{ID: id, Candidate: candidate, Section: SectionSSL, Committed: true, + Actor: AuditActor{UserID: "ssl-maintenance", Role: "system"}} + m.mu.Unlock() + return m.publishExpiredSSL(candidate) +} + +func (m *ConfigManager) publishExpiredSSL(candidate RuntimeConfig) error { + if err := m.publishSnapshot(candidate); err != nil { + return err + } + now := time.Now().UTC() + m.mu.Lock() + m.current = candidate + m.pending = nil + m.status.SetupState = candidate.SetupState + m.status.DegradedReasons = nil + m.status.ActiveGeneration = candidate.Generation + m.status.LastValidAt = &now + m.mu.Unlock() + log.WithFields(log.Fields{"action": "清理过期证书引用", "result": "success"}).Info("上一套证书已到期,已解除保留") + return nil +} diff --git a/backend/config/ssl_flat.go b/backend/config/ssl_flat.go new file mode 100644 index 00000000..15e74fc7 --- /dev/null +++ b/backend/config/ssl_flat.go @@ -0,0 +1,221 @@ +package config + +import ( + "crypto/tls" + "os" + "path/filepath" + "strings" + + "git.pcux.cn/xuans/Smail/utils/atomicfile" + "git.pcux.cn/xuans/Smail/utils/runtimepath" +) + +const flatSSLPrefix = "smail-tls-" + +func legacyManagedSSLReference(value string) bool { + value = runtimepath.LegacyReference(value) + return strings.HasPrefix(value, "data/ssl/managed/") || strings.HasPrefix(value, "ssl/managed/") +} + +func flatSSLPair(root, certificatePath, privateKeyPath string) bool { + directory, err := filepath.Abs(filepath.Join(root, "ssl")) + if err != nil || filepath.Dir(certificatePath) != directory || filepath.Dir(privateKeyPath) != directory { + return false + } + name := strings.TrimSuffix(filepath.Base(certificatePath), ".crt") + return strings.HasSuffix(certificatePath, ".crt") && strings.HasPrefix(name, flatSSLPrefix) && + validSSLVersion("version-"+strings.TrimPrefix(name, flatSSLPrefix)) && filepath.Base(privateKeyPath) == name+".key" +} + +// 新材料使用不可变的成对文件;配置事务是唯一的生效指针,不覆盖当前文件。 +func stageFlatSSLAtRoot(root, mode string, privateKey, certificate, issuer []byte, domains []string) (ManagedSSLReference, error) { + managedSSLStorage.Lock() + defer managedSSLStorage.Unlock() + if !validManagedSSLMode(mode) { + return ManagedSSLReference{}, ErrInvalidSSLMode + } + if err := validateSSLMaterial(privateKey, certificate, issuer, domains); err != nil { + return ManagedSSLReference{}, err + } + if runtimepath.DeploymentLayout(root) { + unlock, err := NewTransactionStore(root, RuntimeValidationOptions{}).lockState() + if err != nil { + return ManagedSSLReference{}, err + } + defer unlock() + } + directory, err := filepath.Abs(filepath.Join(root, "ssl")) + if err != nil { + return ManagedSSLReference{}, err + } + if err := ensureManagedDirectoryAtRoot(root, directory); err != nil { + return ManagedSSLReference{}, err + } + token, err := randomStorageToken() + if err != nil { + return ManagedSSLReference{}, err + } + base := flatSSLPrefix + token + storage, err := os.OpenRoot(directory) + if err != nil { + return ManagedSSLReference{}, err + } + defer storage.Close() + // 证书链合并到一个证书文件,不额外生成 issuer 文件。 + certificates, _ := parseCertificatePEM(certificate) + issuers, _ := parseCertificatePEM(issuer) + certificate = encodeSSLCertificates(appendUniqueCertificates(certificates, issuers...)) + if len(certificate) > maxManagedSSLFileSize { + return ManagedSSLReference{}, ErrInvalidSSLMaterial + } + var written []string + complete := false + defer func() { + if !complete { + for _, name := range written { + _ = storage.Remove(name) + } + } + }() + for _, file := range []struct { + name string + data []byte + }{{base + ".key", privateKey}, {base + ".crt", certificate}} { + if _, err := storage.Lstat(file.name); !os.IsNotExist(err) { + return ManagedSSLReference{}, ErrUnsafeSSLFile + } + written = append(written, file.name) + if err := atomicfile.WriteRoot(storage, file.name, file.data, 0600); err != nil { + return ManagedSSLReference{}, err + } + } + publicPath, privatePath := filepath.Join(directory, base+".crt"), filepath.Join(directory, base+".key") + if err := validateManagedSSLFiles(publicPath, privatePath); err != nil { + return ManagedSSLReference{}, err + } + lease, err := openSSLLease(privatePath) + if err != nil { + return ManagedSSLReference{}, err + } + unlock, err := lockStateFile(lease) + if err != nil { + lease.Close() + return ManagedSSLReference{}, err + } + managedSSLStorage.staged[publicPath] = func() { unlock(); lease.Close() } + complete = true + return ManagedSSLReference{Mode: mode, CertificateRef: "ssl/" + base + ".crt", PrivateKeyRef: "ssl/" + base + ".key", CertificatePath: publicPath, PrivateKeyPath: privatePath}, nil +} + +// 只有上一套由本程序生成的证书才纳入到期自动删除;手动文件不会被接管。 +func retainPreviousSSL(root string, next *SSLConfig, previous SSLConfig) { + next.PreviousCertificateRef = previous.PreviousCertificateRef + next.PreviousPrivateKeyRef = previous.PreviousPrivateKeyRef + if next.CertificateRef == previous.CertificateRef && next.PrivateKeyRef == previous.PrivateKeyRef { + return + } + ref, err := resolveManagedSSLPathsAtRoot(root, previous) + if err == nil && flatSSLPair(root, ref.CertificatePath, ref.PrivateKeyPath) { + if validateManagedSSLFiles(ref.CertificatePath, ref.PrivateKeyPath) == nil { + next.PreviousCertificateRef = previous.CertificateRef + next.PreviousPrivateKeyRef = previous.PrivateKeyRef + } + } + if next.PreviousCertificateRef == next.CertificateRef { + next.PreviousCertificateRef, next.PreviousPrivateKeyRef = "", "" + } +} + +func pruneFlatSSLLocked(root string, protected []SSLConfig) error { + // 当前材料不可用时暂停回收,避免丢失仍可恢复的历史证书。 + if len(protected) == 0 { + return nil + } + if _, err := resolveManagedSSLReferencesAtRoot(root, protected[0]); err != nil { + return err + } + directory, err := filepath.Abs(filepath.Join(root, "ssl")) + if err != nil { + return err + } + entries, err := os.ReadDir(directory) + if os.IsNotExist(err) { + return nil + } + if err != nil { + return err + } + resolved, err := filepath.EvalSymlinks(directory) + if err != nil || filepath.Clean(resolved) != directory { + return ErrUnsafeSSLFile + } + keep := make(map[string]bool) + for _, ssl := range protected { + if path, err := resolveCustomSSLInput(root, ssl.CertificateRef); ssl.CertificateRef != "" && err == nil { + keep[path] = true + } + // 已经降为上一套的配置不能继续保护更早一代,避免保留链无限延长。 + if ssl.CertificateRef == protected[0].PreviousCertificateRef { + continue + } + publicPath, err := resolveCustomSSLInput(root, ssl.PreviousCertificateRef) + privatePath, keyErr := resolveCustomSSLInput(root, ssl.PreviousPrivateKeyRef) + if err == nil && keyErr == nil && flatSSLPair(root, publicPath, privatePath) { + // 即使已经到期,也必须等配置事务解除引用后才能删除。 + keep[publicPath] = true + } + } + storage, err := os.OpenRoot(directory) + if err != nil { + return err + } + defer storage.Close() + for _, entry := range entries { + publicPath := filepath.Join(directory, entry.Name()) + privatePath := strings.TrimSuffix(publicPath, ".crt") + ".key" + if !flatSSLPair(root, publicPath, privatePath) || keep[publicPath] || managedSSLStorage.staged[publicPath] != nil { + continue + } + // 租约覆盖整个删除过程;未知、链接、不完整材料保留给管理员处理。 + certificate, err := readExternalSSLFile(publicPath, false) + if err != nil { + continue + } + certificates, err := parseCertificatePEM(certificate) + if err != nil || len(certificates) == 0 { + continue + } + privateKey, err := readExternalSSLFile(privatePath, true) + if err != nil { + // 先删私钥、后删证书;中断留下的孤立证书可在下轮安全重试。 + if _, statErr := os.Lstat(privatePath); os.IsNotExist(statErr) { + if err := storage.Remove(filepath.Base(publicPath)); err != nil { + return err + } + } + continue + } + if _, err := tls.X509KeyPair(certificate, privateKey); err != nil { + continue + } + lease, err := openSSLLease(privatePath) + if err != nil { + continue + } + unlock, err := lockStateFile(lease) + if err != nil { + lease.Close() + continue + } + err = storage.Remove(filepath.Base(privatePath)) + if err == nil { + err = storage.Remove(filepath.Base(publicPath)) + } + unlock() + lease.Close() + if err != nil { + return err + } + } + return nil +} diff --git a/backend/config/ssl_live.go b/backend/config/ssl_live.go new file mode 100644 index 00000000..5f8613f8 --- /dev/null +++ b/backend/config/ssl_live.go @@ -0,0 +1,132 @@ +package config + +import ( + "crypto/tls" + "crypto/x509" + "encoding/pem" + "sync" + "time" + + log "github.com/sirupsen/logrus" +) + +func encodeSSLCertificates(certificates []*x509.Certificate) []byte { + var result []byte + for _, certificate := range certificates { + result = append(result, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certificate.Raw})...) + } + return result +} + +// 所有协议共享已完整校验的内存证书;只影响新握手,不关闭既有连接。 +var liveTLS = struct { + sync.Mutex + root string + certificate *tls.Certificate + checked time.Time + warned time.Time +}{} + +func CurrentCertificateConfig() *Config { + cfg := CurrentConfig() + if cfg == nil { + return nil + } + if manager := CurrentManager(); manager != nil { + runtime := manager.Snapshot() + cfg.SSL = runtime.SSL.TLS + cfg.Domain, cfg.WebDomain = runtime.Root.Domains.Primary, runtime.Root.Domains.Web + cfg.Domains = runtime.Root.Domains.Accepted + cfg.TLSMode = runtime.Root.HTTP.TLSMode + cfg.HttpsEnabled = 2 + if runtime.Root.HTTP.HTTPSEnabled { + cfg.HttpsEnabled = 1 + } + cfg.SSLType = SSLTypeUser + if EffectiveSSLManagement(cfg.SSL) == SSLManagementProject { + cfg.SSLType = SSLTypeAutoHTTP + if cfg.SSL.Challenge == SSLChallengeDNS { + cfg.SSLType = SSLTypeAutoDNS + } + } + } + return cfg +} + +func runtimeTLSCertificate(force bool) (*tls.Certificate, error) { + liveTLS.Lock() + defer liveTLS.Unlock() + now := time.Now() + if liveTLS.root != ROOT_PATH { + liveTLS.certificate, liveTLS.checked, liveTLS.warned = nil, time.Time{}, time.Time{} + liveTLS.root = ROOT_PATH + } + if !force && liveTLS.certificate != nil && now.Sub(liveTLS.checked) < time.Second && now.Before(liveTLS.certificate.Leaf.NotAfter) { + return liveTLS.certificate, nil + } + liveTLS.checked = now + cfg := CurrentCertificateConfig() + certificate, err := loadValidatedRuntimeCertificate(cfg) + if err == nil { + liveTLS.certificate = &certificate + return liveTLS.certificate, nil + } + if (liveTLS.certificate == nil || !now.Before(liveTLS.certificate.Leaf.NotAfter)) && cfg != nil && cfg.SSL.PreviousCertificateRef != "" { + previous := *cfg + previous.SSL.CertificateRef = cfg.SSL.PreviousCertificateRef + previous.SSL.PrivateKeyRef = cfg.SSL.PreviousPrivateKeyRef + if fallback, fallbackErr := loadValidatedRuntimeCertificate(&previous); fallbackErr == nil { + liveTLS.certificate = &fallback + } + } + if liveTLS.certificate != nil && now.Before(liveTLS.certificate.Leaf.NotAfter) { + if now.Sub(liveTLS.warned) >= time.Minute { + log.WithFields(log.Fields{"action": "热加载 TLS 证书", "result": "failure"}).Warn("新证书不可用,继续使用尚未过期的已校验证书") + liveTLS.warned = now + } + return liveTLS.certificate, err + } + return nil, err +} + +func loadValidatedRuntimeCertificate(cfg *Config) (tls.Certificate, error) { + certificate, err := LoadRuntimeTLSCertificate(cfg) + if err != nil { + return tls.Certificate{}, err + } + certificate.Leaf, err = x509.ParseCertificate(certificate.Certificate[0]) + if err != nil { + return tls.Certificate{}, err + } + runtime := RuntimeConfig{Root: RootConfig{Domains: DomainConfig{Primary: cfg.Domain, Web: cfg.WebDomain, Accepted: cfg.Domains}}} + runtime.SSL.TLS = cfg.SSL + if cfg.SSLType == SSLTypeAutoDNS { + runtime.SSL.TLS.Management = SSLManagementProject + runtime.SSL.TLS.Challenge = SSLChallengeDNS + } + for _, domain := range validationCertificateDomains(&runtime) { + if err := certificate.Leaf.VerifyHostname(domain); err != nil { + return tls.Certificate{}, ErrSSLCertificateDomain + } + } + return certificate, nil +} + +// NewRuntimeTLSConfig 在启动时验证证书,后续握手自动使用最新有效证书。 +func NewRuntimeTLSConfig() (*tls.Config, error) { + if certificate, err := runtimeTLSCertificate(true); certificate == nil { + return nil, err + } + return &tls.Config{MinVersion: tls.VersionTLS12, GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) { + certificate, err := runtimeTLSCertificate(false) + if certificate != nil { + return certificate, nil + } + return nil, err + }}, nil +} + +func ReloadRuntimeTLSCertificate() error { + _, err := runtimeTLSCertificate(true) + return err +} diff --git a/backend/config/ssl_migration.go b/backend/config/ssl_migration.go new file mode 100644 index 00000000..b90ef469 --- /dev/null +++ b/backend/config/ssl_migration.go @@ -0,0 +1,143 @@ +package config + +import ( + "bytes" + "os" + "path/filepath" + "sort" + "strings" + + "git.pcux.cn/xuans/Smail/utils/runtimepath" +) + +// MigrateLegacySSLStorage 在监听器启动前迁移旧引用;提交失败时不删除旧材料。 +// 自定义模式优先复用 ssl 根目录中完全相同的原件,无法匹配时才迁出旧版本。 +func MigrateLegacySSLStorage(root string) error { + if !runtimepath.DeploymentLayout(root) { + return nil + } + data, err := os.ReadFile(filepath.Join(root, "config", "config.json")) + if os.IsNotExist(err) { + return nil + } + if err != nil { + return err + } + partitioned, err := isPartitionedConfig(data) + if err != nil || !partitioned { + return err + } + options := RuntimeValidationOptions{HasSuperAdmin: true} + store := NewTransactionStore(root, options) + if err := store.Recover(); err != nil { + return err + } + current, err := NewConfigLoader(root, ConfigLoaderOptions{Validation: options}).Load() + if err != nil || !legacyManagedSSLReference(current.SSL.TLS.CertificateRef) { + return err + } + ref, err := resolveManagedSSLReferencesAtRoot(root, current.SSL.TLS) + if err != nil { + return err + } + key, err := readExternalSSLFile(ref.PrivateKeyPath, true) + if err != nil { + return err + } + certificate, err := readExternalSSLFile(ref.CertificatePath, false) + if err != nil { + return err + } + candidate := cloneRuntimeConfig(current) + next := &candidate.SSL.TLS + if EffectiveSSLManagement(*next) != SSLManagementProject { + ref, err = matchingDirectSSL(root, key, certificate) + } else { + ref = ManagedSSLReference{} + } + if err != nil { + return err + } + if ref.CertificateRef == "" { + ref, err = stageFlatSSLAtRoot(root, next.Mode, key, certificate, nil, validationCertificateDomains(&candidate)) + if err != nil { + return err + } + defer releaseManagedSSL(root, SSLConfig{CertificateRef: ref.CertificateRef}) + } + next.CertificateRef, next.PrivateKeyRef = ref.CertificateRef, ref.PrivateKeyRef + next.DefaultDirectory = "ssl" + if next.Mode == ManagedSSLModeUpload { + next.CustomDirectory = "ssl" + } + previous, err := previousLegacySSL(root, current.SSL.TLS, certificate, validationCertificateDomains(&candidate)) + if err != nil { + return err + } + if previous.CertificateRef != "" { + defer releaseManagedSSL(root, SSLConfig{CertificateRef: previous.CertificateRef}) + next.PreviousCertificateRef, next.PreviousPrivateKeyRef = previous.CertificateRef, previous.PrivateKeyRef + } + if err := validateCustomSSLReferences(root, candidate); err != nil { + return err + } + setCandidateGeneration(&candidate, current.Generation+1) + return store.Commit(current, candidate) +} + +func matchingDirectSSL(root string, key, certificate []byte) (ManagedSSLReference, error) { + directory := filepath.Join(root, "ssl") + entries, err := os.ReadDir(directory) + if err != nil { + return ManagedSSLReference{}, err + } + for _, entry := range entries { + if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".crt") || strings.HasPrefix(entry.Name(), flatSSLPrefix) { + continue + } + publicPath := filepath.Join(directory, entry.Name()) + privatePath := strings.TrimSuffix(publicPath, ".crt") + ".key" + publicBytes, publicErr := readExternalSSLFile(publicPath, false) + privateBytes, privateErr := readExternalSSLFile(privatePath, true) + if publicErr == nil && privateErr == nil && bytes.Equal(certificate, publicBytes) && bytes.Equal(key, privateBytes) { + return ManagedSSLReference{Mode: ManagedSSLModeUpload, CertificateRef: directSSLReference(root, publicPath), PrivateKeyRef: directSSLReference(root, privatePath)}, nil + } + } + return ManagedSSLReference{}, nil +} + +// 重复副本不算上一套证书;只迁移最近一套仍有效且覆盖当前服务域名的不同材料。 +func previousLegacySSL(root string, active SSLConfig, certificate []byte, domains []string) (ManagedSSLReference, error) { + var candidates []retainedSSLVersion + for _, mode := range []string{ManagedSSLModeDefault, ManagedSSLModeUpload} { + directory, err := managedSSLRootPathAtRoot(root, mode) + if err != nil { + return ManagedSSLReference{}, err + } + entries, err := os.ReadDir(directory) + if os.IsNotExist(err) { + continue + } + if err != nil { + return ManagedSSLReference{}, err + } + for _, entry := range entries { + if !validSSLVersion(entry.Name()) && entry.Name() != "current" { + continue + } + if info, err := entry.Info(); err == nil && info.IsDir() && info.Mode()&os.ModeSymlink == 0 { + candidates = append(candidates, retainedSSLVersion{directory: filepath.Join(directory, entry.Name()), modified: info.ModTime()}) + } + } + } + sort.Slice(candidates, func(i, j int) bool { return candidates[i].modified.After(candidates[j].modified) }) + for _, candidate := range candidates { + publicBytes, publicErr := readExternalSSLFile(filepath.Join(candidate.directory, "public.crt"), false) + privateBytes, privateErr := readExternalSSLFile(filepath.Join(candidate.directory, "private.key"), true) + if publicErr != nil || privateErr != nil || bytes.Equal(certificate, publicBytes) || validateSSLMaterial(privateBytes, publicBytes, nil, domains) != nil { + continue + } + return stageFlatSSLAtRoot(root, active.Mode, privateBytes, publicBytes, nil, domains) + } + return ManagedSSLReference{}, nil +} diff --git a/backend/config/ssl_retention.go b/backend/config/ssl_retention.go index da2bfe12..86830ef6 100644 --- a/backend/config/ssl_retention.go +++ b/backend/config/ssl_retention.go @@ -36,6 +36,10 @@ func releaseManagedSSLLocked(root string, ssl SSLConfig) { } path, err := filepath.Abs(filepath.Join(root, filepath.FromSlash(runtimepath.SSLReference(root, ssl.CertificateRef)))) if err == nil { + if release := managedSSLStorage.staged[path]; release != nil { + release() + delete(managedSSLStorage.staged, path) + } directory := filepath.Dir(path) if release := managedSSLStorage.staged[directory]; release != nil { release() @@ -86,6 +90,10 @@ func MaintainManagedSSLHistory() { if manager := CurrentManager(); manager != nil { manager.writeMu.Lock() defer manager.writeMu.Unlock() + if err := manager.clearExpiredPreviousSSL(); err != nil { + log.WithFields(log.Fields{"action": "清理过期证书引用", "result": "failure"}).Warn("配置维护未完成,下次自动重试") + return + } manager.mu.RLock() active := manager.current.SSL.TLS var pending []SSLConfig @@ -107,6 +115,11 @@ func pruneManagedSSLLocked(root string, protected []SSLConfig) error { if len(protected) == 0 || protected[0].CertificateRef == "" { return nil } + if !legacyManagedSSLReference(protected[0].CertificateRef) { + if _, err := resolveManagedSSLReferencesAtRoot(root, protected[0]); err != nil { + return err + } + } // 恢复事务可能仍需要旧材料;恢复未完成时不能清理任何版本。 if runtimepath.DeploymentLayout(root) { records, err := NewTransactionStore(root, RuntimeValidationOptions{HasSuperAdmin: true}).stateRecords("transaction") @@ -125,7 +138,9 @@ func pruneManagedSSLLocked(root string, protected []SSLConfig) error { if err != nil { return err } - keep[filepath.Dir(reference.CertificatePath)] = true + if legacyManagedSSLReference(ssl.CertificateRef) { + keep[filepath.Dir(reference.CertificatePath)] = true + } } // 磁盘引用也必须保留,避免其他管理器实例或已提交未发布的候选被删除。 data, err := os.ReadFile(filepath.Join(root, "config", "ssl.json")) @@ -135,11 +150,14 @@ func pruneManagedSSLLocked(root string, protected []SSLConfig) error { return err } if section.TLS.CertificateRef != "" { + protected = append(protected, section.TLS) reference, err := resolveManagedSSLPathsAtRoot(root, section.TLS) if err != nil { return err } - keep[filepath.Dir(reference.CertificatePath)] = true + if legacyManagedSSLReference(section.TLS.CertificateRef) { + keep[filepath.Dir(reference.CertificatePath)] = true + } } } else if !os.IsNotExist(err) { return err @@ -209,12 +227,14 @@ func pruneManagedSSLLocked(root string, protected []SSLConfig) error { } return versions[i].modified.After(versions[j].modified) }) - // 两个模式合计保留两份;正在生效和暂存的版本优先,操作结束后收敛到两份。 - for _, version := range versions { - if len(keep) >= 2 { - break + // 尚未迁移的旧配置暂时沿用旧规则;迁移完成后不再为 managed 额外保留副本。 + if legacyManagedSSLReference(protected[0].CertificateRef) { + for _, version := range versions { + if len(keep) >= 2 { + break + } + keep[version.directory] = true } - keep[version.directory] = true } var result error for _, version := range versions { @@ -222,7 +242,17 @@ func pruneManagedSSLLocked(root string, protected []SSLConfig) error { result = errors.Join(result, removeManagedSSLDirectory(version.directory)) } } - return result + if result == nil { + // 仅删除已空的旧目录;未知文件会使 Remove 失败并原样保留。 + for _, mode := range []string{ManagedSSLModeDefault, ManagedSSLModeUpload} { + directory, err := managedSSLRootPathAtRoot(root, mode) + if err == nil { + _ = os.Remove(directory) + _ = os.Remove(filepath.Dir(directory)) + } + } + } + return errors.Join(result, pruneFlatSSLLocked(root, protected)) } // 回滚前必须检查实际证书,不能提交已经被保留策略淘汰的历史引用。 diff --git a/backend/config/ssl_storage.go b/backend/config/ssl_storage.go index a0269994..a4d8314c 100644 --- a/backend/config/ssl_storage.go +++ b/backend/config/ssl_storage.go @@ -91,16 +91,27 @@ func LoadRuntimeTLSCertificate(cfg *Config) (tls.Certificate, error) { if err != nil { return tls.Certificate{}, err } - certificate, err := tls.LoadX509KeyPair(certificatePath, privateKeyPath) + privateKey, err := readExternalSSLFile(privateKeyPath, true) + if err != nil { + return tls.Certificate{}, err + } + publicKey, err := readExternalSSLFile(certificatePath, false) + if err != nil { + return tls.Certificate{}, err + } + if err := validateSSLMaterial(privateKey, publicKey, nil, nil); err != nil { + return tls.Certificate{}, err + } + certificate, err := tls.X509KeyPair(publicKey, privateKey) if err != nil { return tls.Certificate{}, err } return certificate, nil } -// ImportManagedSSL 校验证书材料后写入候选目录,并原子切换 current 目录。 +// ImportManagedSSL 兼容旧调用名称;新材料只写入 ssl 根目录,不再创建 managed。 func ImportManagedSSL(mode string, privateKeyPEM, certificatePEM, issuerPEM []byte, domains []string) (ManagedSSLReference, error) { - return importManagedSSLAtRoot(ROOT_PATH, mode, privateKeyPEM, certificatePEM, issuerPEM, domains) + return StageManagedSSL(mode, privateKeyPEM, certificatePEM, issuerPEM, domains) } func importManagedSSLAtRoot(root string, mode string, privateKeyPEM, certificatePEM, issuerPEM []byte, domains []string) (ManagedSSLReference, error) { @@ -211,7 +222,7 @@ func importManagedSSLAtRoot(root string, mode string, privateKeyPEM, certificate }, nil } -// ResolveManagedSSLReferences 将内部引用解析为受控文件路径,拒绝任意路径输入。 +// ResolveManagedSSLReferences 兼容旧名称;解析旧受管引用或自定义直接路径并复验证书。 func ResolveManagedSSLReferences(ssl SSLConfig) (ManagedSSLReference, error) { return resolveManagedSSLReferencesAtRoot(ROOT_PATH, ssl) } @@ -236,6 +247,20 @@ func resolveManagedSSLPathsAtRoot(root string, ssl SSLConfig) (ManagedSSLReferen if ssl.CertificateRef == "" || ssl.PrivateKeyRef == "" { return ManagedSSLReference{}, ErrInvalidSSLReference } + if !legacyManagedSSLReference(ssl.CertificateRef) && !legacyManagedSSLReference(ssl.PrivateKeyRef) { + certificatePath, err := resolveCustomSSLInput(root, ssl.CertificateRef) + if err != nil { + return ManagedSSLReference{}, err + } + privateKeyPath, err := resolveCustomSSLInput(root, ssl.PrivateKeyRef) + if err != nil { + return ManagedSSLReference{}, err + } + if ssl.Mode == ManagedSSLModeDefault && !flatSSLPair(root, certificatePath, privateKeyPath) { + return ManagedSSLReference{}, ErrInvalidSSLReference + } + return ManagedSSLReference{Mode: ssl.Mode, CertificateRef: ssl.CertificateRef, PrivateKeyRef: ssl.PrivateKeyRef, CertificatePath: certificatePath, PrivateKeyPath: privateKeyPath}, nil + } rootPath, err := managedSSLRootPathAtRoot(root, ssl.Mode) if err != nil { return ManagedSSLReference{}, err @@ -464,7 +489,7 @@ func validSSLVersion(version string) bool { // StageManagedSSL 只写入独立版本,不替换现用文件;配置事务成功后引用才生效。 func StageManagedSSL(mode string, privateKeyPEM, certificatePEM, issuerPEM []byte, domains []string) (ManagedSSLReference, error) { - return stageManagedSSLAtRoot(ROOT_PATH, mode, privateKeyPEM, certificatePEM, issuerPEM, domains) + return stageFlatSSLAtRoot(ROOT_PATH, mode, privateKeyPEM, certificatePEM, issuerPEM, domains) } func stageManagedSSLAtRoot(root string, mode string, privateKeyPEM, certificatePEM, issuerPEM []byte, domains []string) (ManagedSSLReference, error) { @@ -540,25 +565,13 @@ func stageManagedSSLAtRoot(root string, mode string, privateKeyPEM, certificateP } func validateManagedSSLFiles(certificatePath, privateKeyPath string) error { - for _, item := range []struct { - path string - isPrivate bool - }{{certificatePath, false}, {privateKeyPath, true}} { - info, err := os.Lstat(item.path) - if err != nil || info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() || info.Size() <= 0 || info.Size() > maxManagedSSLFileSize || hasMultipleFileLinks(item.path) { - return ErrUnsafeSSLFile - } - if item.isPrivate && info.Mode().Perm()&0077 != 0 && runtimeSupportsPermissionCheck() { - return ErrSSLPrivateKeyPermission - } - } - privateKeyPEM, err := os.ReadFile(privateKeyPath) + privateKeyPEM, err := readExternalSSLFile(privateKeyPath, true) if err != nil { - return ErrUnsafeSSLFile + return err } - certificatePEM, err := os.ReadFile(certificatePath) + certificatePEM, err := readExternalSSLFile(certificatePath, false) if err != nil { - return ErrUnsafeSSLFile + return err } return validateSSLMaterial(privateKeyPEM, certificatePEM, nil, nil) } diff --git a/backend/config/ssl_storage_test.go b/backend/config/ssl_storage_test.go index 65394428..63bf54d0 100644 --- a/backend/config/ssl_storage_test.go +++ b/backend/config/ssl_storage_test.go @@ -11,12 +11,11 @@ import ( "os" "path/filepath" "runtime" - "strings" "testing" "time" ) -func TestImportManagedSSLUsesInternalReferencesAndAtomicCurrent(t *testing.T) { +func TestImportManagedSSLUsesImmutableRootFiles(t *testing.T) { oldRoot := ROOT_PATH ROOT_PATH = t.TempDir() t.Cleanup(func() { ROOT_PATH = oldRoot }) @@ -26,10 +25,11 @@ func TestImportManagedSSLUsesInternalReferencesAndAtomicCurrent(t *testing.T) { if err != nil { t.Fatal(err) } + defer ReleaseStagedSSL(first) if filepath.IsAbs(first.CertificateRef) || filepath.IsAbs(first.PrivateKeyRef) { t.Fatal("SSL 内部引用不应为绝对路径") } - if first.CertificateRef != "data/ssl/managed/default/current/public.crt" || first.PrivateKeyRef != "data/ssl/managed/default/current/private.key" { + if !flatSSLPair(ROOT_PATH, first.CertificatePath, first.PrivateKeyPath) { t.Fatalf("内部引用不符合预期: %+v", first) } resolved, err := ResolveManagedSSLReferences(SSLConfig{Mode: ManagedSSLModeDefault, DefaultDirectory: "config/ssl", CertificateRef: first.CertificateRef, PrivateKeyRef: first.PrivateKeyRef}) @@ -45,8 +45,9 @@ func TestImportManagedSSLUsesInternalReferencesAndAtomicCurrent(t *testing.T) { if err != nil { t.Fatal(err) } - if second.CertificatePath != first.CertificatePath { - t.Fatal("current 引用路径应保持稳定") + defer ReleaseStagedSSL(second) + if second.CertificatePath == first.CertificatePath { + t.Fatal("新证书必须使用独立文件,不能覆盖正在使用的材料") } currentData, err := os.ReadFile(second.CertificatePath) if err != nil { @@ -55,22 +56,9 @@ func TestImportManagedSSLUsesInternalReferencesAndAtomicCurrent(t *testing.T) { if string(currentData) == string(certificatePEM) { t.Fatal("current 目录没有切换到新证书") } - previousMatches := false - entries, err := os.ReadDir(filepath.Dir(filepath.Dir(second.CertificatePath))) - if err != nil { - t.Fatal(err) - } - for _, entry := range entries { - if !strings.HasPrefix(entry.Name(), ".previous-") { - continue - } - previousData, readErr := os.ReadFile(filepath.Join(filepath.Dir(filepath.Dir(second.CertificatePath)), entry.Name(), "public.crt")) - if readErr == nil && string(previousData) == string(certificatePEM) { - previousMatches = true - } - } - if !previousMatches { - t.Fatal("更新后未保留旧证书目录") + previousData, err := os.ReadFile(first.CertificatePath) + if err != nil || string(previousData) != string(certificatePEM) { + t.Fatal("暂存新证书改变了原证书") } } @@ -146,8 +134,8 @@ func TestResolveManagedSSLReferencesRejectsUnsafeReferences(t *testing.T) { {Mode: ManagedSSLModeUpload, CertificateRef: `\\server\share\public.crt`, PrivateKeyRef: reference.PrivateKeyRef}, } for index, candidate := range unsafe { - if _, err := ResolveManagedSSLReferences(candidate); !errors.Is(err, ErrInvalidSSLReference) { - t.Fatalf("用例 %d error = %v, want %v", index, err, ErrInvalidSSLReference) + if _, err := ResolveManagedSSLReferences(candidate); err == nil { + t.Fatalf("用例 %d 不应接受缺失、不配对或不安全的文件", index) } } } @@ -203,7 +191,7 @@ func TestValidateSSLMaterialRejectsDomainExpiryAndWeakKeys(t *testing.T) { } } -func TestPrepareCustomSSLPathsImportsExternalFilesOnlyWhenSaving(t *testing.T) { +func TestPrepareCustomSSLPathsKeepsDirectFilesWithoutCopying(t *testing.T) { root := t.TempDir() previousRoot := ROOT_PATH ROOT_PATH = root @@ -233,8 +221,8 @@ func TestPrepareCustomSSLPathsImportsExternalFilesOnlyWhenSaving(t *testing.T) { if err != nil { t.Fatalf("校验外部证书失败: %v", err) } - if runtime.SSL.TLS.CertificateRef == certificatePath || runtime.SSL.TLS.PrivateKeyRef == privateKeyPath { - t.Fatal("仅校验阶段不应保留外部证书路径") + if runtime.SSL.TLS.CertificateRef != filepath.ToSlash(certificatePath) || runtime.SSL.TLS.PrivateKeyRef != filepath.ToSlash(privateKeyPath) { + t.Fatal("仅校验阶段应保留规范化的直接路径") } managedRoot := filepath.Join(root, "data", "ssl", "managed", "upload") if _, err := os.Stat(managedRoot); !os.IsNotExist(err) { @@ -244,11 +232,11 @@ func TestPrepareCustomSSLPathsImportsExternalFilesOnlyWhenSaving(t *testing.T) { if err := material.stage(root, &runtime); err != nil { t.Fatalf("保存外部证书失败: %v", err) } - if runtime.SSL.TLS.CertificateRef == certificatePath || runtime.SSL.TLS.PrivateKeyRef == privateKeyPath { - t.Fatal("保存后不应继续使用外部证书路径") + if runtime.SSL.TLS.CertificateRef != filepath.ToSlash(certificatePath) || runtime.SSL.TLS.PrivateKeyRef != filepath.ToSlash(privateKeyPath) { + t.Fatal("保存后应继续引用原始文件") } - if !strings.HasPrefix(runtime.SSL.TLS.CertificateRef, "data/ssl/managed/upload/version-") { - t.Fatalf("证书引用未切换到受管版本: %q", runtime.SSL.TLS.CertificateRef) + if _, err := os.Stat(managedRoot); !os.IsNotExist(err) { + t.Fatal("保存自定义证书不应创建副本") } if _, err := ResolveManagedSSLReferences(runtime.SSL.TLS); err != nil { t.Fatalf("受管证书引用无法解析: %v", err) @@ -263,7 +251,7 @@ func TestValidateSSLMaterialAcceptsBundledIssuerWithoutDuplicateChainEntry(t *te } } -func testManagedCertificate(t *testing.T, domain string, notBefore, notAfter time.Time, bits int) ([]byte, []byte) { +func testManagedCertificate(t *testing.T, domain string, notBefore, notAfter time.Time, bits int, additionalDomains ...string) ([]byte, []byte) { t.Helper() key, err := rsa.GenerateKey(rand.Reader, bits) if err != nil { @@ -272,7 +260,7 @@ func testManagedCertificate(t *testing.T, domain string, notBefore, notAfter tim template := &x509.Certificate{ SerialNumber: big.NewInt(time.Now().UnixNano()), Subject: pkix.Name{CommonName: domain}, - DNSNames: []string{domain}, + DNSNames: append([]string{domain}, additionalDomains...), NotBefore: notBefore, NotAfter: notAfter, BasicConstraintsValid: true, diff --git a/backend/config/validator.go b/backend/config/validator.go index 3bb2d0e4..532e177e 100644 --- a/backend/config/validator.go +++ b/backend/config/validator.go @@ -173,6 +173,16 @@ func smtpRelayConfigured(smtp SMTPConfig) bool { } func validateSSL(ssl SSLConfig) error { + if (ssl.PreviousCertificateRef == "") != (ssl.PreviousPrivateKeyRef == "") { + return ErrInvalidSSL + } + if ssl.PreviousCertificateRef != "" { + publicPath, err := resolveCustomSSLInput(".", ssl.PreviousCertificateRef) + privatePath, keyErr := resolveCustomSSLInput(".", ssl.PreviousPrivateKeyRef) + if err != nil || keyErr != nil || !isControlledRelativePath(ssl.PreviousCertificateRef) || !isControlledRelativePath(ssl.PreviousPrivateKeyRef) || !flatSSLPair(".", publicPath, privatePath) { + return ErrInvalidSSL + } + } if !isControlledRelativePath(ssl.DefaultDirectory) { return ErrInvalidSSL } @@ -196,6 +206,19 @@ func validateSSL(ssl SSLConfig) error { default: return ErrInvalidSSL } + if EffectiveSSLManagement(ssl) == SSLManagementCustom || EffectiveSSLManagement(ssl) == SSLManagementWebServer { + if (ssl.CertificateRef == "") != (ssl.PrivateKeyRef == "") { + return ErrInvalidSSL + } + for _, value := range []string{ssl.CertificateRef, ssl.PrivateKeyRef} { + if value != "" { + if _, err := resolveCustomSSLInput(".", value); err != nil { + return ErrInvalidSSL + } + } + } + return nil + } if (ssl.CertificateRef != "" && !isControlledRelativePath(ssl.CertificateRef)) || (ssl.PrivateKeyRef != "" && !isControlledRelativePath(ssl.PrivateKeyRef)) { return ErrInvalidSSL diff --git a/backend/internal/app/app.go b/backend/internal/app/app.go index b50d3018..b984f334 100644 --- a/backend/internal/app/app.go +++ b/backend/internal/app/app.go @@ -21,6 +21,9 @@ func Run() (err error) { if err := runtimepath.CheckReady(config.ROOT_PATH); err != nil { return err } + if err := config.MigrateLegacySSLStorage(config.ROOT_PATH); err != nil { + return fmt.Errorf("迁移证书存储失败,原文件已保留: %w", err) + } if err := config.Init(); err != nil { return err } diff --git a/backend/listen/cron_server/ssl_update.go b/backend/listen/cron_server/ssl_update.go index f4cabb71..7add64d3 100644 --- a/backend/listen/cron_server/ssl_update.go +++ b/backend/listen/cron_server/ssl_update.go @@ -3,7 +3,6 @@ package cron_server import ( "git.pcux.cn/xuans/Smail/config" "git.pcux.cn/xuans/Smail/services/setup/ssl" - "git.pcux.cn/xuans/Smail/signal" log "github.com/sirupsen/logrus" "time" // 新增:HTTP 就绪探测 @@ -14,8 +13,6 @@ import ( "strconv" ) -var expiredTime time.Time - func Start() { // 第一次启动,等待到初始化完成 @@ -34,26 +31,14 @@ func Start() { // 只检查外部维护的本地邮件证书是否更新,不触发 ACME。 func sslCheck() { - _, newExpTime, _, err := ssl.CheckSSLCrtInfo() - if err != nil { - log.Errorf("SSL Check Error! %+v", err) - return - } - if expiredTime.IsZero() { - expiredTime = newExpTime - return - } - if newExpTime != expiredTime { - expiredTime = newExpTime - log.Infoln("SSL certificate had update! restarting") - signal.RestartChan <- true - } + // 校验失败时保留尚未过期的内存证书;不发送服务重启信号。 + _ = config.ReloadRuntimeTLSCertificate() } // 每轮读取最新策略,切换反代模式后不再等待 HTTP 挑战或执行自动续期。 func maintainSSL() { config.MaintainManagedSSLHistory() - cfg := config.CurrentConfig() + cfg := config.CurrentCertificateConfig() if cfg == nil || !cfg.IsSetupReady() { return } @@ -61,7 +46,6 @@ func maintainSSL() { sslCheck() return } - expiredTime = time.Time{} if cfg.SSLType == config.SSLTypeAutoHTTP && !waitHTTPReady() { return } @@ -70,10 +54,17 @@ func maintainSSL() { // 每天检查证书,外部管理模式仅保留本地证书变更检查。 func sslUpdateLoop() { + lastRenewal := time.Time{} for { - maintainSSL() - // 每24小时检测一次证书有效期 - time.Sleep(24 * time.Hour) + if time.Since(lastRenewal) >= 24*time.Hour { + maintainSSL() + lastRenewal = time.Now() + } else { + config.MaintainManagedSSLHistory() + sslCheck() + } + // 每分钟清理已到期的上一套证书;自动签发仍最多每天检查一次。 + time.Sleep(time.Minute) } } @@ -93,7 +84,7 @@ func waitHTTPReady() bool { client := &http.Client{Timeout: 2 * time.Second} for i := 0; i < 90; i++ { - if !config.CurrentConfig().AutomaticSSLEnabled() { + if !config.CurrentCertificateConfig().AutomaticSSLEnabled() { return false } requestContext, cancel := context.WithTimeout(context.Background(), 2*time.Second) diff --git a/backend/listen/http_server/https_server.go b/backend/listen/http_server/https_server.go index a2e34bf8..a6e21ec2 100644 --- a/backend/listen/http_server/https_server.go +++ b/backend/listen/http_server/https_server.go @@ -67,12 +67,13 @@ func HttpsStart() error { if legacyCfg == nil { return fmt.Errorf("legacy SSL configuration is unavailable") } - certificatePath, privateKeyPath, err := config.ResolveRuntimeSSLPaths(legacyCfg) + tlsConfig, err := config.NewRuntimeTLSConfig() if err != nil { return fmt.Errorf("resolve HTTPS certificate: %w", err) } httpsServer = &http.Server{ + TLSConfig: tlsConfig, Addr: fmt.Sprintf(":%d", httpsPort), Handler: securityHeaders(dbmigration.GuardHTTP(session.Instance.LoadAndSave(mux))), ReadTimeout: time.Second * 90, @@ -83,7 +84,7 @@ func HttpsStart() error { ErrorLog: nullLog, } log.WithFields(log.Fields{"action": "启动 HTTPS 监听", "object": httpsServer.Addr, "result": "started"}).Info("开始绑定监听端口") - if err := httpsServer.ListenAndServeTLS(certificatePath, privateKeyPath); err != nil { + if err := httpsServer.ListenAndServeTLS("", ""); err != nil { if errors.Is(err, http.ErrServerClosed) { log.WithFields(log.Fields{"action": "停止 HTTPS 监听", "object": httpsServer.Addr, "result": "success"}).Info("监听已正常关闭") return nil diff --git a/backend/listen/imap_server/imap_server.go b/backend/listen/imap_server/imap_server.go index 4d8c4a98..97183003 100644 --- a/backend/listen/imap_server/imap_server.go +++ b/backend/listen/imap_server/imap_server.go @@ -1,7 +1,6 @@ package imap_server import ( - "crypto/tls" "fmt" "git.pcux.cn/xuans/Smail/config" "github.com/emersion/go-imap/v2" @@ -62,14 +61,10 @@ func newIMAPServer() (*imapserver.Server, error) { if cfg == nil { return nil, fmt.Errorf("runtime configuration is unavailable") } - crt, err := config.LoadRuntimeTLSCertificate(cfg) + tlsConfig, err := config.NewRuntimeTLSConfig() if err != nil { return nil, fmt.Errorf("load IMAP TLS certificate: %w", err) } - tlsConfig := &tls.Config{ - Certificates: []tls.Certificate{crt}, - MinVersion: tls.VersionTLS12, - } memServer := NewServer() diff --git a/backend/listen/imap_server/imap_server_test.go b/backend/listen/imap_server/imap_server_test.go index 60a01aeb..152e0d31 100644 --- a/backend/listen/imap_server/imap_server_test.go +++ b/backend/listen/imap_server/imap_server_test.go @@ -121,7 +121,7 @@ func writeIMAPTestCertificate(root string) (string, string, error) { template := &x509.Certificate{ SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "localhost"}, - DNSNames: []string{"localhost"}, + DNSNames: []string{"localhost", "test.domain", "*.test.domain"}, NotBefore: time.Now().Add(-time.Minute), NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, diff --git a/backend/listen/pop3_server/pop3server.go b/backend/listen/pop3_server/pop3server.go index 193b6999..b345b289 100644 --- a/backend/listen/pop3_server/pop3server.go +++ b/backend/listen/pop3_server/pop3server.go @@ -2,7 +2,6 @@ package pop3_server import ( "crypto/rand" - "crypto/tls" "fmt" "git.pcux.cn/xuans/Smail/config" "git.pcux.cn/xuans/Smail/internal/gopop" @@ -22,12 +21,10 @@ func StartWithTls() error { if domains.Primary == "" { return fmt.Errorf("mail domain is not configured") } - crt, err := config.LoadRuntimeTLSCertificate(cfg) + tlsConfig, err := config.NewRuntimeTLSConfig() if err != nil { return fmt.Errorf("load POP3 TLS certificate: %w", err) } - tlsConfig := &tls.Config{MinVersion: tls.VersionTLS12} - tlsConfig.Certificates = []tls.Certificate{crt} tlsConfig.Time = time.Now tlsConfig.Rand = rand.Reader port := config.CurrentMailPorts().POP3TLS @@ -52,12 +49,10 @@ func Start() error { if domains.Primary == "" { return fmt.Errorf("mail domain is not configured") } - crt, err := config.LoadRuntimeTLSCertificate(cfg) + tlsConfig, err := config.NewRuntimeTLSConfig() if err != nil { return fmt.Errorf("load POP3 certificate: %w", err) } - tlsConfig := &tls.Config{MinVersion: tls.VersionTLS12} - tlsConfig.Certificates = []tls.Certificate{crt} tlsConfig.Time = time.Now tlsConfig.Rand = rand.Reader port := config.CurrentMailPorts().POP3 diff --git a/backend/listen/smtp_server/smtp.go b/backend/listen/smtp_server/smtp.go index e740cff8..c08294a8 100644 --- a/backend/listen/smtp_server/smtp.go +++ b/backend/listen/smtp_server/smtp.go @@ -1,7 +1,6 @@ package smtp_server import ( - "crypto/tls" "errors" "fmt" "time" @@ -43,12 +42,12 @@ func StartWithTLSNew() error { // force TLS for auth instanceTlsNew.AllowInsecureAuth = false // Load the certificate and key - cer, err := config.LoadRuntimeTLSCertificate(cfg) + tlsConfig, err := config.NewRuntimeTLSConfig() if err != nil { return fmt.Errorf("load SMTP STARTTLS certificate: %w", err) } // Configure the TLS support for STARTTLS - instanceTlsNew.TLSConfig = &tls.Config{Certificates: []tls.Certificate{cer}, MinVersion: tls.VersionTLS12} + instanceTlsNew.TLSConfig = tlsConfig log.WithFields(log.Fields{"action": "启动 SMTP STARTTLS 监听", "object": instanceTlsNew.Addr, "result": "started"}).Info("开始绑定监听端口") // 提交端口使用 STARTTLS(先连接,再升级 TLS),而非隐式 TLS。 @@ -80,12 +79,12 @@ func StartWithTLS() error { // force TLS for auth instanceTls.AllowInsecureAuth = true // Load the certificate and key - cer, err := config.LoadRuntimeTLSCertificate(cfg) + tlsConfig, err := config.NewRuntimeTLSConfig() if err != nil { return fmt.Errorf("load SMTP TLS certificate: %w", err) } // Configure the TLS support - instanceTls.TLSConfig = &tls.Config{Certificates: []tls.Certificate{cer}, MinVersion: tls.VersionTLS12} + instanceTls.TLSConfig = tlsConfig log.WithFields(log.Fields{"action": "启动 SMTP TLS 监听", "object": instanceTls.Addr, "result": "started"}).Info("开始绑定监听端口") if err := instanceTls.ListenAndServeTLS(); err != nil && !errors.Is(err, smtp.ErrServerClosed) { @@ -116,12 +115,12 @@ func Start() error { // force TLS for auth instance.AllowInsecureAuth = false // Load the certificate and key - cer, err := config.LoadRuntimeTLSCertificate(cfg) + tlsConfig, err := config.NewRuntimeTLSConfig() if err != nil { return fmt.Errorf("load SMTP certificate: %w", err) } // Configure the TLS support - instance.TLSConfig = &tls.Config{Certificates: []tls.Certificate{cer}, MinVersion: tls.VersionTLS12} + instance.TLSConfig = tlsConfig log.WithFields(log.Fields{"action": "启动 SMTP 收信监听", "object": instance.Addr, "result": "started"}).Info("开始绑定监听端口") if err := instance.ListenAndServe(); err != nil && !errors.Is(err, smtp.ErrServerClosed) { diff --git a/backend/services/setup/ssl/ssl.go b/backend/services/setup/ssl/ssl.go index 412261fd..99118ca4 100644 --- a/backend/services/setup/ssl/ssl.go +++ b/backend/services/setup/ssl/ssl.go @@ -9,7 +9,6 @@ import ( stderrors "errors" "git.pcux.cn/xuans/Smail/config" "git.pcux.cn/xuans/Smail/services/setup" - "git.pcux.cn/xuans/Smail/signal" "git.pcux.cn/xuans/Smail/utils/async" "git.pcux.cn/xuans/Smail/utils/errors" "git.pcux.cn/xuans/Smail/utils/runtimepath" @@ -138,20 +137,11 @@ func SetSSL(sslType, priKey, crtKey string) error { if err != nil { return err } - privatePEM, err := os.ReadFile(privatePath) - if err != nil { - return newUserCertificateError("SSL 私钥无法读取,请确认文件路径和 smail 用户权限") - } - publicPEM, err := os.ReadFile(publicPath) - if err != nil { - return newUserCertificateError("SSL 证书无法读取,请确认文件路径和 smail 用户权限") - } - reference, err := config.StageManagedSSL(config.ManagedSSLModeUpload, privatePEM, publicPEM, nil, sslDomains(cfg)) + reference, err := config.ValidateDirectSSLPaths(publicPath, privatePath, sslDomains(cfg)) if err != nil { return normalizeUserCertificateImportError(err) } applyManagedSSLReference(cfg, reference) - defer config.ReleaseStagedSSL(reference) // 导入邮件服务证书不能重新启用反代模式下的内置 HTTPS。 if cfg.UsesProxyHTTPS() { cfg.HttpsEnabled = 2 @@ -177,7 +167,7 @@ func clearLegacySSLPaths(cfg *config.Config) { cfg.SSLPublicKeyPath = "" } -// applyManagedSSLReference 将证书切换结果写入内部引用,不持久化服务器路径。 +// applyManagedSSLReference 保存已校验的证书路径,新签发文件直接位于 ssl 下。 func applyManagedSSLReference(cfg *config.Config, reference config.ManagedSSLReference) { if cfg == nil { return @@ -192,12 +182,12 @@ func applyManagedSSLReference(cfg *config.Config, reference config.ManagedSSLRef cfg.SSL = config.SSLConfig{ Management: management, Mode: reference.Mode, - DefaultDirectory: runtimepath.SSLReference(config.ROOT_PATH, "data/ssl"), + DefaultDirectory: "ssl", CertificateRef: reference.CertificateRef, PrivateKeyRef: reference.PrivateKeyRef, } if reference.Mode == config.ManagedSSLModeUpload { - cfg.SSL.CustomDirectory = runtimepath.SSLReference(config.ROOT_PATH, "data/ssl/managed/upload") + cfg.SSL.CustomDirectory = "ssl" } else if cfg.SSLType == config.SSLTypeAutoDNS { cfg.SSL.Challenge = config.SSLChallengeDNS } else { @@ -596,8 +586,8 @@ func CheckSSLCrtInfo() (int, time.Time, bool, error) { return cast.ToInt(hours / 24), cert.NotAfter, nameMatchFail, nil } -func Update(needRestart bool) { - cfg := config.CurrentConfig() +func Update(_ bool) { + cfg := config.CurrentCertificateConfig() if cfg.AutomaticSSLEnabled() && cfg.IsSetupReady() { days, _, nameMatchFail, err := CheckSSLCrtInfo() @@ -613,9 +603,8 @@ func Update(needRestart bool) { return } log.WithFields(log.Fields{"action": "更新 TLS 证书", "result": "success"}).Info("证书已更新并保存") - if needRestart { - // 更新完证书,重启服务 - signal.RestartChan <- true + if err := config.ReloadRuntimeTLSCertificate(); err != nil { + log.WithFields(log.Fields{"action": "热加载 TLS 证书", "result": "failure"}).Warn("续期配置已保存,运行证书切换失败,请检查证书文件") } } else { log.Debugf("SSL Check.") diff --git a/backend/services/setup/ssl/user_certificate_test.go b/backend/services/setup/ssl/user_certificate_test.go index 15e368d5..b9f459cf 100644 --- a/backend/services/setup/ssl/user_certificate_test.go +++ b/backend/services/setup/ssl/user_certificate_test.go @@ -94,7 +94,7 @@ func TestApplyManagedSSLReferenceDoesNotPersistLegacyPaths(t *testing.T) { if cfg.SSL.Mode != config.ManagedSSLModeUpload || cfg.SSL.CertificateRef != reference.CertificateRef || cfg.SSL.PrivateKeyRef != reference.PrivateKeyRef { t.Fatalf("受控 SSL 内部引用写入错误: %+v", cfg.SSL) } - if cfg.SSL.CustomDirectory != "data/ssl/managed/upload" { + if cfg.SSL.CustomDirectory != "ssl" { t.Fatalf("自定义受控目录写入错误: %s", cfg.SSL.CustomDirectory) } } diff --git a/backend/utils/runtimepath/business_keys.go b/backend/utils/runtimepath/business_keys.go index a4307ee7..641c3e11 100644 --- a/backend/utils/runtimepath/business_keys.go +++ b/backend/utils/runtimepath/business_keys.go @@ -104,7 +104,7 @@ func PrepareDeploymentKeys(root string) error { return err } // 先检查所有目标,不能移动第一把密钥后才发现另一业务目录不安全。 - for _, folder := range []string{"credentials", "external-email-encryption", "external-email-fingerprint", "dkim", "managed"} { + for _, folder := range []string{"credentials", "external-email-encryption", "external-email-fingerprint", "dkim"} { if err := safeDirectory(filepath.Join(ssl, folder)); err != nil && !os.IsNotExist(err) { return err } @@ -114,7 +114,7 @@ func PrepareDeploymentKeys(root string) error { return err } } - for _, folder := range []string{"credentials", "external-email-encryption", "external-email-fingerprint", "dkim", "managed"} { + for _, folder := range []string{"credentials", "external-email-encryption", "external-email-fingerprint", "dkim"} { if _, err := SecureDirectory(ssl, folder); err != nil { return err } diff --git a/deploy/runtime-config.mjs b/deploy/runtime-config.mjs index 677902a9..ca673726 100644 --- a/deploy/runtime-config.mjs +++ b/deploy/runtime-config.mjs @@ -38,9 +38,17 @@ export function assertDeploymentLayout(root = runtimeRoot) { if (config.database?.type === 'sqlite') resolveRuntimeFile(root, `data/${config.database.localRef}`) } const ssl = JSON.parse(readFileSync(resolveRuntimeFile(root, 'config/ssl.json'), 'utf8')).tls - for (const reference of [ssl?.certificateRef, ssl?.privateKeyRef]) { - if (!reference?.startsWith('ssl/')) throw new Error('证书引用尚未迁移到 ssl,拒绝使用旧目录启动') - resolveRuntimeFile(root, reference) + try { + resolveDevelopmentCertificate(root, ssl?.certificateRef) + resolveDevelopmentCertificate(root, ssl?.privateKeyRef, true) + } catch (error) { + // 启动预检与热加载使用相同边界;当前材料不可读时允许后端验证上一套。 + try { + resolveDevelopmentCertificate(root, ssl?.previousCertificateRef) + resolveDevelopmentCertificate(root, ssl?.previousPrivateKeyRef, true) + } catch { + throw error + } } return config } @@ -71,16 +79,19 @@ export function resolveRuntimeFile(root, reference) { } // 仅供 Node/Vite 服务端读取,不能把包含凭据的配置对象暴露给浏览器。 -export function readDevelopmentRuntime(root = runtimeRoot) { +export function readDevelopmentRuntime(root = runtimeRoot, { previous = false } = {}) { const read = name => JSON.parse(readFileSync(resolveRuntimeFile(root, `config/${name}.json`), 'utf8')) const config = read('config') const ssl = read('ssl') + if (ssl.meta?.generation !== config.generation) { + throw new Error('配置事务尚未完成,暂不切换开发证书') + } const webDomain = config.domains?.web if (typeof webDomain !== 'string' || !/^[a-z0-9.-]+(?::\d+)?$/i.test(webDomain)) { throw new Error('请先在 yunx-test/config/config.json 配置有效的 Web 域名') } - const certificatePath = resolveRuntimeFile(root, ssl.tls?.certificateRef) - const privateKeyPath = resolveRuntimeFile(root, ssl.tls?.privateKeyRef) + const certificatePath = resolveDevelopmentCertificate(root, previous ? ssl.tls?.previousCertificateRef : ssl.tls?.certificateRef) + const privateKeyPath = resolveDevelopmentCertificate(root, previous ? ssl.tls?.previousPrivateKeyRef : ssl.tls?.privateKeyRef, true) return { origin: `https://${webDomain}`, certificatePath, @@ -88,3 +99,22 @@ export function readDevelopmentRuntime(root = runtimeRoot) { generation: config.generation } } + +// 证书允许显式绝对路径;配置与数据库仍保持部署根目录边界。 +function resolveDevelopmentCertificate(root, reference, privateKey = false) { + if (typeof reference !== 'string' || !reference || reference.includes('\0') || reference.split(/[\\/]/).includes('..')) { + throw new Error('证书路径无效') + } + const target = path.isAbsolute(reference) ? path.resolve(reference) : resolveRuntimeFile(root, reference) + let current = target + while (true) { + if (lstatSync(current).isSymbolicLink()) throw new Error('证书路径不能包含链接') + const parent = path.dirname(current) + if (parent === current) break + current = parent + } + const info = lstatSync(target) + if (!info.isFile() || info.nlink !== 1 || info.size <= 0 || info.size > 1024 * 1024) throw new Error('证书必须是安全的普通文件') + if (privateKey && process.platform !== 'win32' && (info.mode & 0o077)) throw new Error('私钥权限过于宽松') + return target +} diff --git a/docs/部署后自动归档与证书保留.md b/docs/部署后自动归档与证书保留.md index b7b27ab7..ceeab8db 100644 --- a/docs/部署后自动归档与证书保留.md +++ b/docs/部署后自动归档与证书保留.md @@ -4,7 +4,7 @@ - 正式程序在任意部署目录启动后自动创建目录,不依赖手动整理或开发脚本。 - 已采用 `config/ssl/data/log` 布局的旧部署,启动时自动归档三把业务密钥,保留原字节。 -- `ssl/managed` 自动保留两套受管证书材料,后续导入、续期、应用及重启继续执行。 +- 不再创建 `ssl/managed`。自动签发的成对文件直接存放于 `ssl/`,保留当前新证书和上一套未过期证书,上一套到期后清理。 - 域名证书原文件继续保存在 `ssl/` 根目录,不与业务加密密钥混放。 - 模拟部署使用 `yunx-test/`,修改完成后必须完整构建并核验最新二进制。 @@ -21,7 +21,8 @@ │ ├── external-email-fingerprint/ │ │ └── external-email-fingerprint.key │ ├── dkim/ -│ ├── managed/ # default 与 upload 合计保留两套 +│ ├── smail-tls-<版本>.crt # 自动签发的当前或上一套证书 +│ ├── smail-tls-<版本>.key │ ├── 域名.crt │ └── 域名.key ├── data/ @@ -45,19 +46,27 @@ ## 两份保留规则 - 一份是完整的证书和私钥组合,不是两个单独文件。 -- 当前生效证书优先保留;提交新版本时保留上一份材料;其余按版本目录时间排序补足两份。 +- 当前生效证书优先保留;提交新版本时记录上一份完整且未过期的材料,不按文件时间补足两份,也不保留更早的历史链。 - 待应用候选、正在导入或续期的材料、磁盘已提交引用受到保护;操作进行时可能暂时超过两份,应用或取消后再次清理。 - 启动后、定期证书维护、配置应用、回滚、取消候选及重新加载时自动执行。 - 仅删除程序识别的历史版本。未知文件、链接、无法安全检查的目录保留并告警;事务恢复未完成时暂停清理。 - 私钥文件锁保护跨进程暂存,配置状态锁协调提交与清理。停止或替换管理器时释放暂存锁。 -- 上一份证书过期不会阻止正常清理,但运行加载和回滚仍执行完整证书有效期、强度、配对检查。 +- 每分钟检查上一套的到期时间;先通过五分区配置事务清空引用,再删除程序生成的成对文件。当前材料不可用或事务未恢复时暂停回收。 +- 已落盘但运行态发布失败的清理事务保留恢复入口,下轮维护继续发布,不重复提交同一代次。 +- 成对清理先删除私钥再删除证书;中断遗留的已识别孤立证书在下轮重试,无法解析或配对的材料不擅自删除。 - 已清理证书的历史配置不能回滚,预览和执行均返回明确中文错误,必须重新导入有效证书。 ## 域名文件与运行引用的边界 `ssl/域名.crt`、`ssl/域名.key` 是用户放置的证书原文件,自动归档和清理不删除它们。 -**本次没有将服务运行引用改成根目录文件。** 自定义证书仍经校验后导入 `ssl/managed/.../version-...`,配置事务切换成对的受管引用,避免外部文件变化或两文件替换期间配对不一致。若要求运行引用也固定为 `ssl/域名.crt` 与 `ssl/域名.key`,还需实现完整的成对发布、失败恢复和备份引用迁移,不能只复制文件或直接改 JSON 冒充完成。 +自定义证书直接保存原始路径,不复制。部署目录内优先使用 `ssl/域名.crt`、`ssl/域名.key`,部署目录外保留绝对路径;普通文件、链接、大小、私钥权限、强度、有效期、配对及服务域名校验仍执行。 + +启动时自动迁移旧 `managed` 引用:自定义模式优先复用字节完全相同的根目录原件;没有匹配原件时将必要材料迁到根目录程序版本文件。先提交配置事务,再回收已退出引用的旧目录;未知文件不会删除。 + +自动续期先写一套独立新文件,完整校验后事务切换当前引用。SMTP、IMAP、POP3、内置 HTTPS 共享动态证书,新 TLS 握手读取新证书,已有连接不主动关闭。新材料加载失败时仅回退到仍有效的已校验证书;重启无内存缓存时尝试配置中的上一套。 + +手工证书不受自动删除管理,也不自动复制一份历史。外部维护者应先准备好完整的新材料再更新引用;分别覆盖证书与私钥期间验证失败时进程保留有效缓存,但不保证此时重启仍能加载被覆盖的旧材料。 ## 验证与边界 @@ -66,9 +75,38 @@ - 空目录正式启动只验收自动目录创建和初始化页面可达,不等于完成整个首次初始化、管理员恢复权限或插件生产隔离验收。 - Linux 编译通过不等于 Linux 生产运行验收。正式管理员恢复通道的保护不降低。 -## 本轮实测记录(2026-09-08) +## 本轮实测记录(2026-09-09) -以下记录来自本轮最新源码构建,不以手工创建当前目录代替启动验证。 +| 验证项目 | 本轮结果 | 记录位置 | +| --- | --- | --- | +| 完整自动化回归 | 前端 155/155、部署 4/4、Go 全量通过 | `test-log/run-2026-09-09T09-12-56-738Z-9840/` | +| 专项并发检查 | 配置、SSL 设置及 HTTP、SMTP、IMAP、POP3 监听包通过 `-race` | `test-log/run-2026-09-09T09-04-43-786Z-46884/` | +| 证书生命周期 | 当前加上一套保留、到期事务清理、发布失败恢复、暂存租约、未知材料保护、孤立证书重试通过 | `test/backend/ssl_lifecycle_test.go` 及上述回归日志 | +| TLS 热切换 | Go 本机 TLS 测试中,新握手换用新证书,原连接继续收发;无缓存及缓存到期时恢复上一套 | 同上,属于自动化 TLS 测试,不代表真实 CA 续期 | +| 开发 HTTPS | 实际 HTTPS 服务执行 `setSecureContext` 后新连接换证、原连接保留,绝对路径和上一套恢复通过 | `test/frontend/dev-tls.test.mjs` 及上述回归日志 | +| 最新包部署 | 前端、三个插件、主程序及管理员程序完整构建,部署后源码指纹和文件哈希验证通过 | `out/build-state.json`、`test-log/service-launch/` | +| 真实配置迁移 | 启动事务将代次 27 升到 28,改为 `ssl/xuans.com.crt` 和 `ssl/xuans.com.key`,旧 `ssl/managed` 不再存在 | 本机 `yunx-test/config/ssl.json` | +| 原文件保护 | 原证书、原私钥、ACME 账户密钥、三把业务密钥的字节及创建时间不变 | `test-log/ssl-direct-baseline-20260909.json` 为比较基线,不含密钥内容 | +| 浏览器保存与刷新 | MCP 表单输入同一原件的绝对路径,经当前密码确认后显示“配置已保存”;规范化成原件相对路径,五分区代次均为 29;刷新状态及忽略缓存重载后路径一致、登录仍有效 | 当前会话 MCP 操作记录 | + +浏览器操作期间后端 PID 为 31988,前端 PID 为 14648,保存配置未触发服务重启;这些编号仅代表此次现场。前端保留源码热更新,后端使用 `yunx-test` 最新编译程序。部署根目录只有 `config`、`ssl`、`data`、`log` 及两个运行程序。 + +当前仍是自定义证书模式,因此不会为手工原件额外复制上一套,也没有触发真实 ACME 签发。自动续期的两套保留通过独立测试材料验证;Linux 实机运行、正式管理员恢复通道、真实 CA 续期、全流程邮件收发仍不属于本轮验收。数据库没有清空,本轮是存量部署迁移验收,不是首次初始化验收。 + +开发服务器首次进入懒加载页面时发生过依赖预构建刷新,Vite 日志可确认;再次打开页面后完成上述验证。构建仍有富文本编辑器约 809 kB 的分包告警,开发代理有 `util._extend` 弃用提示,不属于本次 SSL 改造范围。MCP 快照落盘被其工作区根目录限制拒绝,未绕过限制写入;页面验收证据保留在本会话工具记录中。 + +### 本轮任务状态 + +- [✓] 自定义证书直接引用,不生成副本。 +- [✓] 自动续期使用根目录版本文件,保留当前与上一套未过期证书。 +- [✓] 到期先清除配置引用再清理文件,暂存及异常材料受到保护。 +- [✓] 新握手热加载,不主动关闭已有连接,失败保留有效证书。 +- [✓] 旧部署迁移、完整构建、部署包核验和浏览器保存刷新完成。 +- [!] 真实 CA 续期及 Linux 生产实机运行未执行,不能视为已验收。 + +## 历史实测记录(2026-09-08,旧存储方案) + +以下为旧 `managed` 存储方案的历史记录,不代表 2026-09-09 直接引用与热切换改造已验收。 | 验证项目 | 实测结果 | 本地记录 | | --- | --- | --- | @@ -85,11 +123,11 @@ 本轮没有进行浏览器页面交互验收,也没有宣称完整生产初始化或 Linux 运行验收通过。前端已有富文本编辑器分包体积提醒不在本次修改范围内。 -## 任务状态 +## 历史任务状态(2026-09-08) - [✓] 正式主程序自动创建业务目录,不依赖部署脚本创建。 - [✓] 已采用 SSL 布局的旧部署自动迁移三把业务密钥,重复启动不更换密钥。 - [✓] 受管证书正常稳定状态保留两套,保护生效、暂存和恢复所需材料。 - [✓] 最新包部署、空目录启动、旧部署升级及邮件 TLS 验证完成。 -- [!] 根目录域名文件直接作为运行引用尚未改造;本轮只保证原文件保留,并继续使用已校验的受管副本。 +- [!] 当时尚未实现根目录直接引用,已由上文 2026-09-09 新规则替代。 - [!] Linux 正式运行、完整首次初始化及正式管理员恢复流程尚未完成本轮实机验收。 diff --git a/frontend/dev-tls.js b/frontend/dev-tls.js new file mode 100644 index 00000000..9fcd3b40 --- /dev/null +++ b/frontend/dev-tls.js @@ -0,0 +1,71 @@ +import { createHash, createPrivateKey, createPublicKey, X509Certificate } from 'node:crypto' +import { readFileSync } from 'node:fs' +import { createSecureContext } from 'node:tls' +import { readDevelopmentRuntime } from '../deploy/runtime-config.mjs' + +// 开发 HTTPS 也读取同一部署配置;整套材料校验后再替换,不关闭现有连接。 +export function readDevelopmentTLS(root) { + try { + return readTLSMaterial(readDevelopmentRuntime(root)) + } catch (error) { + try { + return readTLSMaterial(readDevelopmentRuntime(root, { previous: true })) + } catch { + throw error + } + } +} + +function readTLSMaterial(runtime) { + const cert = readFileSync(runtime.certificatePath) + const key = readFileSync(runtime.privateKeyPath) + const certificate = new X509Certificate(cert) + const now = Date.now() + if (now < Date.parse(certificate.validFrom) || now >= Date.parse(certificate.validTo)) { + throw new Error('开发证书尚未生效或已经过期') + } + const publicKey = createPublicKey(createPrivateKey(key)) + if (!certificate.publicKey.equals(publicKey) || !certificate.checkHost(new URL(runtime.origin).hostname)) { + throw new Error('开发证书与私钥或 Web 域名不匹配') + } + createSecureContext({ cert, key, minVersion: 'TLSv1.2' }) + const fingerprint = createHash('sha256').update(cert).update(key).digest('hex') + return { runtime, options: { cert, key, minVersion: 'TLSv1.2' }, fingerprint, expiresAt: Date.parse(certificate.validTo) } +} + +export function developmentTLSReload(initial, root) { + return { + name: 'smail-development-tls-reload', + apply: 'serve', + configureServer(server) { + let active = initial + let warned = false + let expired = false + const timer = setInterval(() => { + try { + const next = readDevelopmentTLS(root) + if (expired || next.fingerprint !== active.fingerprint) { + server.httpServer.setSecureContext(next.options) + active = next + expired = false + } + warned = false + } catch { + if (!expired && Date.now() >= active.expiresAt) { + // 不再给新握手提供过期证书;已经建立的连接不关闭。 + try { + server.httpServer.setSecureContext({ minVersion: 'TLSv1.2' }) + expired = true + } catch { + server.config.logger.error('无法停用过期开发证书,请重启前端服务') + } + } + if (!warned) server.config.logger.warn('证书热加载失败,暂时保留上一套有效证书,请检查 yunx-test/ssl') + warned = true + } + }, 1000) + timer.unref() + server.httpServer.once('close', () => clearInterval(timer)) + } + } +} diff --git a/frontend/src/views/components/ConfigSettings/ConfigForm/ConfigForm.js b/frontend/src/views/components/ConfigSettings/ConfigForm/ConfigForm.js index 4fb18023..e296ba11 100644 --- a/frontend/src/views/components/ConfigSettings/ConfigForm/ConfigForm.js +++ b/frontend/src/views/components/ConfigSettings/ConfigForm/ConfigForm.js @@ -181,14 +181,14 @@ const sslGroups = [ field('tls.certificateRef', '证书文件', 'text', { wide: true, show: externalManagedCertificate, - placeholder: 'data/ssl/example.com/fullchain.pem', - hint: '填写后端服务器上的 PEM 证书路径。自定义模式支持绝对路径或相对运行根目录的路径,保存后显示导入后的受管路径;Web 服务器管理模式填写已有受管证书的相对路径。' + placeholder: 'ssl/example.com.crt', + hint: '直接使用服务器上的证书文件,支持相对部署目录的路径或绝对路径,不生成副本。' }), field('tls.privateKeyRef', '私钥文件', 'text', { wide: true, show: externalManagedCertificate, - placeholder: 'data/ssl/example.com/privkey.pem', - hint: '填写与证书匹配的 PEM 私钥文件路径,不是私钥内容。文件必须可被后端运行用户读取;自定义模式保存后显示受管副本的路径。' + placeholder: 'ssl/example.com.key', + hint: '填写配套私钥的文件路径,不是私钥内容;须允许运行用户读取。' }) ]) ] @@ -376,8 +376,8 @@ export function validateFormConfig(section, config) { for (const name of ['certificateRef', 'privateKeyRef']) { if (!tls[name]) continue const managedReference = controlled(tls[name]) && tls[name].startsWith(`${directory}/`) - const externalReference = management === 'custom' && absoluteCertificatePath(tls[name]) - if (!managedReference && !externalReference) errors[`tls.${name}`] = '文件引用必须是受管存储引用或自定义服务器绝对路径' + const externalReference = management !== 'project' && (absoluteCertificatePath(tls[name]) || controlled(tls[name])) + if (!managedReference && !externalReference) errors[`tls.${name}`] = '请填写有效的证书文件路径,不允许上级目录跳转' } if (!!tls.certificateRef !== !!tls.privateKeyRef) errors['tls.privateKeyRef'] = '证书与私钥引用必须成对填写' } diff --git a/frontend/vite.config.js b/frontend/vite.config.js index c305cd7e..f9dc39b6 100644 --- a/frontend/vite.config.js +++ b/frontend/vite.config.js @@ -1,5 +1,4 @@ /* eslint-env node */ -import { readFileSync } from 'node:fs' import { createServer as createHTTPServer } from 'node:http' import { fileURLToPath, URL } from 'node:url' import { defineConfig, loadEnv } from 'vite' @@ -7,7 +6,7 @@ import AutoImport from 'unplugin-auto-import/vite' import Components from 'unplugin-vue-components/vite' import { ElementPlusResolver } from 'unplugin-vue-components/resolvers' import vue from '@vitejs/plugin-vue' -import { readDevelopmentRuntime } from '../deploy/runtime-config.mjs' +import { readDevelopmentTLS, developmentTLSReload } from './dev-tls.js' const developmentHTTPRedirect = (frontendOrigin, host = '127.0.0.1', port = 80) => ({ name: 'smail-development-http-redirect', @@ -35,13 +34,15 @@ const developmentHTTPRedirect = (frontendOrigin, host = '127.0.0.1', port = 80) export default defineConfig(({ mode, command }) => { const env = loadEnv(mode, process.cwd(), '') const backendUrl = (env.VITE_DEV_BACKEND_URL || 'http://127.0.0.1:5201').replace(/\/$/, '') - const runtime = command === 'serve' ? readDevelopmentRuntime() : undefined + const developmentTLS = command === 'serve' ? readDevelopmentTLS() : undefined + const runtime = developmentTLS?.runtime const backendOrigin = runtime?.origin const frontendOrigin = runtime?.origin return { plugins: [ developmentHTTPRedirect(frontendOrigin), + command === 'serve' && developmentTLSReload(developmentTLS), vue(), AutoImport({ resolvers: [ElementPlusResolver()], @@ -60,10 +61,7 @@ export default defineConfig(({ mode, command }) => { port: 443, strictPort: true, // 生产构建不依赖本机开发证书,只有开发服务器启动时才读取私钥。 - https: command === 'serve' ? { - cert: readFileSync(runtime.certificatePath), - key: readFileSync(runtime.privateKeyPath) - } : undefined, + https: developmentTLS?.options, cors: true, proxy: { "/api": { diff --git a/test/backend/deployment_state_test.go b/test/backend/deployment_state_test.go index c2c782fe..f4c372ac 100644 --- a/test/backend/deployment_state_test.go +++ b/test/backend/deployment_state_test.go @@ -183,7 +183,7 @@ func TestDeploymentAutomaticallyCreatesBusinessDirectories(t *testing.T) { t.Fatalf("正式启动没有创建部署目录:%s", name) } } - for _, name := range []string{"credentials", "external-email-encryption", "external-email-fingerprint", "dkim", "managed"} { + for _, name := range []string{"credentials", "external-email-encryption", "external-email-fingerprint", "dkim"} { info, err := os.Lstat(filepath.Join(root, "ssl", name)) if err != nil || !info.IsDir() { t.Fatalf("程序启动没有创建业务目录:%s", name) diff --git a/test/backend/mail_listeners_test.go b/test/backend/mail_listeners_test.go index 08de7d0d..b0e9b8d9 100644 --- a/test/backend/mail_listeners_test.go +++ b/test/backend/mail_listeners_test.go @@ -28,6 +28,7 @@ import ( // 使用空白临时配置和临时证书,在非默认端口调用生产监听入口;不连接真实账号库。 func TestConfiguredMailListenerPortsAcceptProtocolConnections(t *testing.T) { root := t.TempDir() + certificate, key := writeCertificate(t, root) ports := reservePorts(t, 6) meta := config.SectionMeta{Schema: config.CurrentSectionSchema, Generation: 1} smtp := config.SMTPSectionConfig{Meta: meta, Listener: config.SMTPListenerConfig{ @@ -42,7 +43,10 @@ func TestConfiguredMailListenerPortsAcceptProtocolConnections(t *testing.T) { FromDomain: "example.com", } email := config.EmailSectionConfig{Meta: meta, IMAP: config.IMAPListenerConfig{TLSPort: ports[3]}, POP3: config.POP3ListenerConfig{Port: ports[4], TLSPort: ports[5]}} - ssl := config.SSLSectionConfig{Meta: meta, TLS: config.SSLConfig{Mode: "default", DefaultDirectory: "config/ssl"}} + ssl := config.SSLSectionConfig{Meta: meta, TLS: config.SSLConfig{ + Management: config.SSLManagementCustom, Mode: config.ManagedSSLModeUpload, + DefaultDirectory: "ssl", CustomDirectory: "ssl", CertificateRef: certificate, PrivateKeyRef: key, + }} rootConfig := config.RootConfig{ ConfigVersion: config.CurrentConfigVersion, SchemaVersion: config.CurrentSchemaVersion, Generation: 1, SetupState: config.SetupStateBootstrap, Database: config.DatabaseConfig{Type: config.DatabaseTypeSQLite, LocalRef: "unused.db"}, @@ -87,7 +91,6 @@ func TestConfiguredMailListenerPortsAcceptProtocolConnections(t *testing.T) { }) config.ROOT_PATH = root config.SetRuntimeManager(manager) - certificate, key := writeCertificate(t, root) config.PublishConfigSnapshot(&config.Config{SSLPublicKeyPath: certificate, SSLPrivateKeyPath: key}) cases := []struct { name string @@ -185,7 +188,7 @@ func writeCertificate(t *testing.T, root string) (string, string) { t.Fatal(err) } template := &x509.Certificate{ - SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "localhost"}, DNSNames: []string{"localhost"}, + SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "localhost"}, DNSNames: []string{"localhost", "mail.example.com", "*.mail.example.com"}, NotBefore: time.Now().Add(-time.Minute), NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, } diff --git a/test/backend/operation_log_test.go b/test/backend/operation_log_test.go index 5d1c1909..d9ad94d0 100644 --- a/test/backend/operation_log_test.go +++ b/test/backend/operation_log_test.go @@ -82,6 +82,8 @@ func TestOperationResponseDistinguishesPendingHTTPFailureAndUnknown(t *testing.T t.Fatal(err) } defer database.Close() + // 与生产 SQLite 连接池一致,避免后台清理和写入争抢无等待的独立连接。 + database.SetMaxOpenConns(1) migrations := migration.DefaultMigrations() for _, statement := range migrations[len(migrations)-1].StatementsFor(migration.DialectSQLite) { if _, err := database.Exec(statement); err != nil { @@ -113,7 +115,7 @@ func TestOperationResponseDistinguishesPendingHTTPFailureAndUnknown(t *testing.T finish() entries, err := store.Query(context.Background(), logstore.Query{Kind: "operation", Limit: 1}) if err != nil || len(entries) != 1 { - t.Fatal(err) + t.Fatalf("操作日志条数为 %d,查询错误:%v", len(entries), err) } entry := entries[0] if entry.Result != item.want || strings.Contains(string(entry.Payload), "private-") || strings.Contains(string(entry.Payload), "not-a-business-response") { diff --git a/test/backend/ssl_custom_test.go b/test/backend/ssl_custom_test.go index cf2c8397..d6b7fd35 100644 --- a/test/backend/ssl_custom_test.go +++ b/test/backend/ssl_custom_test.go @@ -101,8 +101,8 @@ func TestCustomSSLManagerValidateSaveApplyReload(t *testing.T) { if manager.Snapshot().Generation != request.ExpectedGeneration { t.Fatal("暂存提前切换了当前配置") } - if !strings.HasPrefix(updated.Candidate.SSL.TLS.CertificateRef, "data/ssl/managed/upload/version-") { - t.Fatal("候选未使用独立受管引用") + if updated.Candidate.SSL.TLS.CertificateRef != "external/public.crt" || updated.Candidate.SSL.TLS.PrivateKeyRef != "external/private.key" { + t.Fatal("候选未直接引用原始证书") } currentBytes, err := os.ReadFile(oldReference.CertificatePath) if err != nil || string(currentBytes) != string(oldCertificate) { diff --git a/test/backend/ssl_lifecycle_test.go b/test/backend/ssl_lifecycle_test.go new file mode 100644 index 00000000..115b254f --- /dev/null +++ b/test/backend/ssl_lifecycle_test.go @@ -0,0 +1,255 @@ +package config + +import ( + "bytes" + "crypto/tls" + "errors" + "io" + "net" + "os" + "path/filepath" + "testing" + "time" +) + +func stageLifecycleCertificate(t *testing.T, root string) ManagedSSLReference { + t.Helper() + key, cert := testManagedCertificate(t, "example.com", time.Now().Add(-time.Hour), time.Now().Add(time.Hour), 2048) + ref, err := stageFlatSSLAtRoot(root, ManagedSSLModeUpload, key, cert, nil, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { releaseManagedSSL(root, sslConfigForReference(ref)) }) + return ref +} + +func TestFlatSSLRetentionAndExpiryRecovery(t *testing.T) { + root := t.TempDir() + if err := InitializeDeployment(root); err != nil { + t.Fatal(err) + } + first, second, third := stageLifecycleCertificate(t, root), stageLifecycleCertificate(t, root), stageLifecycleCertificate(t, root) + for _, ref := range []ManagedSSLReference{first, second, third} { + releaseManagedSSL(root, sslConfigForReference(ref)) + } + previous := sslConfigForReference(second) + previous.PreviousCertificateRef, previous.PreviousPrivateKeyRef = first.CertificateRef, first.PrivateKeyRef + active := sslConfigForReference(third) + active.Management, active.DefaultDirectory, active.CustomDirectory = SSLManagementCustom, "ssl", "ssl" + retainPreviousSSL(root, &active, previous) + manual := filepath.Join(root, "ssl", "manual-note.txt") + if err := os.WriteFile(manual, []byte("preserve"), 0600); err != nil { + t.Fatal(err) + } + maintainManagedSSL(root, active, previous) + if countFlatVersions(t, root) != 2 { + t.Fatal("稳定状态未立即收敛为当前与上一套") + } + current := validRuntimeConfig() + current.Root.Domains = DomainConfig{Primary: "example.com", Web: "example.com", Accepted: []string{"example.com"}} + current.SSL.TLS = active + writeRuntimeFixture(t, root, current) + manager, err := NewConfigManager(root, ConfigLoaderOptions{Validation: RuntimeValidationOptions{HasSuperAdmin: true}}) + if err != nil { + t.Fatal(err) + } + if err := manager.clearExpiredPreviousSSL(); err != nil || manager.Snapshot().Generation != current.Generation { + t.Fatal("未到期证书不应清除引用", err) + } + key, cert := testManagedCertificate(t, "example.com", time.Now().Add(-2*time.Hour), time.Now().Add(-time.Hour), 2048) + if err := os.WriteFile(second.CertificatePath, cert, 0600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(second.PrivateKeyPath, key, 0600); err != nil { + t.Fatal(err) + } + maintainManagedSSL(root, active) + if countFlatVersions(t, root) != 2 { + t.Fatal("配置尚未解除过期引用就删除了材料") + } + manager.snapshots = &flakyRuntimeSnapshotStore{current: manager.Snapshot(), failures: 1} + if err := manager.clearExpiredPreviousSSL(); !errors.Is(err, ErrRuntimeSnapshotUnavailable) { + t.Fatalf("发布失败未留下恢复状态:%v", err) + } + if manager.pending == nil || !manager.pending.Committed { + t.Fatal("丢失已提交候选") + } + if err := manager.clearExpiredPreviousSSL(); err != nil { + t.Fatal("下轮维护未恢复发布", err) + } + loaded, err := manager.loader.Load() + if err != nil || loaded.Generation != current.Generation+1 || loaded.SSL.TLS.PreviousCertificateRef != "" { + t.Fatal("磁盘引用或代次不一致", err) + } + maintainManagedSSL(root, manager.Snapshot().SSL.TLS) + if countFlatVersions(t, root) != 1 { + t.Fatal("过期上一套未删除") + } + if _, err := os.Stat(manual); err != nil { + t.Fatal("误删未知文件", err) + } +} + +func TestFlatSSLPreservesLeaseAndUnreadableActive(t *testing.T) { + root := t.TempDir() + first, second := stageLifecycleCertificate(t, root), stageLifecycleCertificate(t, root) + maintainManagedSSL(root, sslConfigForReference(second)) + if countFlatVersions(t, root) != 2 { + t.Fatal("误删正在暂存的材料") + } + releaseManagedSSL(root, sslConfigForReference(first)) + if err := os.WriteFile(second.CertificatePath, []byte("invalid"), 0600); err != nil { + t.Fatal(err) + } + maintainManagedSSL(root, sslConfigForReference(second)) + if countFlatVersions(t, root) != 2 { + t.Fatal("当前证书损坏时仍删除了恢复材料") + } +} + +func TestFlatSSLPrunePreservesMalformedAndRetriesOrphan(t *testing.T) { + root := t.TempDir() + active := stageLifecycleCertificate(t, root) + orphan, malformed := stageLifecycleCertificate(t, root), stageLifecycleCertificate(t, root) + releaseManagedSSL(root, sslConfigForReference(orphan)) + releaseManagedSSL(root, sslConfigForReference(malformed)) + if err := os.Remove(orphan.PrivateKeyPath); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(malformed.CertificatePath, []byte("preserve unknown material"), 0600); err != nil { + t.Fatal(err) + } + maintainManagedSSL(root, sslConfigForReference(active)) + if _, err := os.Stat(orphan.CertificatePath); !os.IsNotExist(err) { + t.Fatal("删除中断后留下的证书没有清理", err) + } + if _, err := os.Stat(malformed.PrivateKeyPath); err != nil { + t.Fatal("无法确认的材料被误删", err) + } +} + +func TestLegacySSLMigrationReusesIdenticalDirectFiles(t *testing.T) { + root := t.TempDir() + if err := InitializeDeployment(root); err != nil { + t.Fatal(err) + } + key, cert := testManagedCertificate(t, "example.com", time.Now().Add(-time.Hour), time.Now().Add(time.Hour), 2048, "*.example.com") + legacy, err := stageManagedSSLAtRoot(root, ManagedSSLModeUpload, key, cert, nil, nil) + if err != nil { + t.Fatal(err) + } + releaseManagedSSL(root, sslConfigForReference(legacy)) + for name, data := range map[string][]byte{"example.com.crt": cert, "example.com.key": key} { + if err := os.WriteFile(filepath.Join(root, "ssl", name), data, 0600); err != nil { + t.Fatal(err) + } + } + current := validRuntimeConfig() + current.Root.Domains = DomainConfig{Primary: "example.com", Web: "example.com", Accepted: []string{"example.com"}} + current.SSL.TLS = sslConfigForReference(legacy) + current.SSL.TLS.Management, current.SSL.TLS.DefaultDirectory, current.SSL.TLS.CustomDirectory = SSLManagementCustom, "ssl", "ssl" + writeRuntimeFixture(t, root, current) + if err := MigrateLegacySSLStorage(root); err != nil { + t.Fatal(err) + } + loader := NewConfigLoader(root, ConfigLoaderOptions{Validation: RuntimeValidationOptions{HasSuperAdmin: true}}) + loaded, err := loader.Load() + if err != nil || loaded.SSL.TLS.CertificateRef != "ssl/example.com.crt" || loaded.Generation != current.Generation+1 { + t.Fatal("迁移未使用同一原件或事务代次错误", err) + } + if err := MigrateLegacySSLStorage(root); err != nil { + t.Fatal("重复启动失败", err) + } + maintainManagedSSL(root, loaded.SSL.TLS) + if _, err := os.Stat(filepath.Join(root, "ssl", "managed")); !os.IsNotExist(err) { + t.Fatal("迁移完成仍保留旧副本目录", err) + } + if data, err := os.ReadFile(filepath.Join(root, "ssl", "example.com.key")); err != nil || !bytes.Equal(data, key) { + t.Fatal("迁移改变了原始私钥", err) + } +} + +func TestLiveSSLSwitchKeepsConnectionAndRestoresPrevious(t *testing.T) { + root := t.TempDir() + oldRoot, oldPublished, oldFlag := ROOT_PATH, publishedConfig.Load(), hasPublishedConfig.Load() + oldManager := CurrentManager() + SetRuntimeManager(nil) + ROOT_PATH = root + t.Cleanup(func() { + ROOT_PATH = oldRoot + publishedConfig.Store(oldPublished) + hasPublishedConfig.Store(oldFlag) + SetRuntimeManager(oldManager) + }) + first, second := stageLifecycleCertificate(t, root), stageLifecycleCertificate(t, root) + cfg := &Config{Domain: "example.com", WebDomain: "example.com", SSL: sslConfigForReference(first)} + PublishConfigSnapshot(cfg) + tlsConfig, err := NewRuntimeTLSConfig() + if err != nil { + t.Fatal(err) + } + listener, err := tls.Listen("tcp", "127.0.0.1:0", tlsConfig) + if err != nil { + t.Fatal(err) + } + defer listener.Close() + go func() { + for { + connection, err := listener.Accept() + if err != nil { + return + } + go func(connection net.Conn) { + defer connection.Close() + _ = connection.SetDeadline(time.Now().Add(10 * time.Second)) + _, _ = io.Copy(connection, connection) + }(connection) + } + }() + dial := func() *tls.Conn { + t.Helper() + connection, err := tls.DialWithDialer(&net.Dialer{Timeout: 3 * time.Second}, "tcp", listener.Addr().String(), &tls.Config{InsecureSkipVerify: true}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { connection.Close() }) + return connection + } + firstClient := dial() + oldSerial := firstClient.ConnectionState().PeerCertificates[0].SerialNumber.String() + cfg.SSL = sslConfigForReference(second) + cfg.SSL.PreviousCertificateRef, cfg.SSL.PreviousPrivateKeyRef = first.CertificateRef, first.PrivateKeyRef + PublishConfigSnapshot(cfg) + if err := ReloadRuntimeTLSCertificate(); err != nil { + t.Fatal(err) + } + if dial().ConnectionState().PeerCertificates[0].SerialNumber.String() == oldSerial { + t.Fatal("新握手仍使用旧证书") + } + _ = firstClient.SetDeadline(time.Now().Add(3 * time.Second)) + if _, err := firstClient.Write([]byte("ping")); err != nil { + t.Fatal("换证断开已有连接", err) + } + message := make([]byte, 4) + if _, err := io.ReadFull(firstClient, message); err != nil || string(message) != "ping" { + t.Fatal("已有连接无法继续通信", err) + } + if err := os.WriteFile(second.CertificatePath, []byte("invalid"), 0600); err != nil { + t.Fatal(err) + } + liveTLS.Lock() + liveTLS.certificate = nil + liveTLS.Unlock() + if _, err := NewRuntimeTLSConfig(); err != nil { + t.Fatal("无内存缓存时无法恢复上一套有效证书", err) + } + if dial().ConnectionState().PeerCertificates[0].SerialNumber.String() != oldSerial { + t.Fatal("恢复握手没有使用上一套证书") + } + liveTLS.Lock() + liveTLS.certificate.Leaf.NotAfter = time.Now().Add(-time.Second) + liveTLS.Unlock() + if _, err := NewRuntimeTLSConfig(); err != nil { + t.Fatal("内存证书到期时没有重新尝试有效的上一套", err) + } +} diff --git a/test/backend/ssl_retention_test.go b/test/backend/ssl_retention_test.go index c4a504e6..842656d5 100644 --- a/test/backend/ssl_retention_test.go +++ b/test/backend/ssl_retention_test.go @@ -6,6 +6,7 @@ import ( "errors" "os" "path/filepath" + "strings" "testing" "time" ) @@ -14,6 +15,26 @@ func sslConfigForReference(ref ManagedSSLReference) SSLConfig { return SSLConfig{Mode: ref.Mode, CertificateRef: ref.CertificateRef, PrivateKeyRef: ref.PrivateKeyRef} } +func countFlatVersions(t *testing.T, root string) int { + t.Helper() + entries, err := os.ReadDir(filepath.Join(root, "ssl")) + if err != nil { + t.Fatal(err) + } + count := 0 + for _, entry := range entries { + publicPath := filepath.Join(root, "ssl", entry.Name()) + privatePath := strings.TrimSuffix(publicPath, ".crt") + ".key" + if flatSSLPair(root, publicPath, privatePath) { + if _, err := os.Stat(privatePath); err != nil { + t.Fatal("证书没有对应私钥", err) + } + count++ + } + } + return count +} + func countManagedVersions(t *testing.T, root string) int { t.Helper() count := 0 @@ -185,6 +206,25 @@ func TestSSLRetentionRunsOnApplyCancelAndReload(t *testing.T) { root, manager, request, _ := customSSLFixture(t) var first RuntimeConfig for index := 0; index < 4; index++ { + // 自定义保存不再产生副本;这里显式模拟自动续期的新版本。 + certificate, err := os.ReadFile(filepath.Join(root, "external", "public.crt")) + if err != nil { + t.Fatal(err) + } + key, err := os.ReadFile(filepath.Join(root, "external", "private.key")) + if err != nil { + t.Fatal(err) + } + ref, err := stageFlatSSLAtRoot(root, ManagedSSLModeUpload, key, certificate, nil, nil) + if err != nil { + t.Fatal(err) + } + var section SSLSectionConfig + if err := json.Unmarshal(request.Payload, §ion); err != nil { + t.Fatal(err) + } + section.TLS.CertificateRef, section.TLS.PrivateKeyRef = ref.CertificateRef, ref.PrivateKeyRef + request.Payload, _ = json.Marshal(section) request.ExpectedGeneration = manager.Snapshot().Generation updated, err := manager.Update(context.Background(), request) if err != nil { @@ -199,7 +239,8 @@ func TestSSLRetentionRunsOnApplyCancelAndReload(t *testing.T) { t.Fatal(err) } } - if index > 0 && countManagedVersions(t, root) != 2 { + maintainManagedSSL(root, manager.Snapshot().SSL.TLS) + if index > 0 && countFlatVersions(t, root) != 2 { t.Fatal("配置应用完成后未自动保留两份") } } @@ -217,13 +258,13 @@ func TestSSLRetentionRunsOnApplyCancelAndReload(t *testing.T) { if err := manager.ManagePending(context.Background(), updated.Generation, updated.CandidateID, request.Actor, StepUpConfirmation{}, true); err != nil { t.Fatal(err) } - if countManagedVersions(t, root) != 2 { + if countFlatVersions(t, root) != 2 { t.Fatal("取消候选未收敛到两份") } if err := manager.Load(context.Background()); err != nil { t.Fatal(err) } - if countManagedVersions(t, root) != 2 { + if countFlatVersions(t, root) != 2 { t.Fatal("重新加载后保留数量错误") } // 确认五分区仍可完整读取,证书删除不能导致摘要被直接修改。 @@ -242,7 +283,7 @@ func TestSSLRetentionRunsOnApplyCancelAndReload(t *testing.T) { t.Fatal(err) } managedSSLStorage.Lock() - stillLeased := managedSSLStorage.staged[filepath.Dir(path.CertificatePath)] != nil + stillLeased := managedSSLStorage.staged[path.CertificatePath] != nil managedSSLStorage.Unlock() if stillLeased { t.Fatal("管理器停止后仍持有暂存租约") diff --git a/test/deployment/verify_ssl_startup.py b/test/deployment/verify_ssl_startup.py index b5f8ca5a..88dd9be9 100644 --- a/test/deployment/verify_ssl_startup.py +++ b/test/deployment/verify_ssl_startup.py @@ -93,7 +93,7 @@ def main(): if not (RUNTIME / folder).is_dir(): raise RuntimeError("正式启动没有创建部署目录") directories = [str(p.relative_to(RUNTIME)) for p in sorted((RUNTIME / "ssl").iterdir()) if p.is_dir()] - for folder in (*BUSINESS.values(), "dkim", "managed"): + for folder in (*BUSINESS.values(), "dkim"): if not (RUNTIME / "ssl" / folder).is_dir(): raise RuntimeError("主程序没有自动创建业务目录") if first is not None and directories != first: diff --git a/test/frontend/config-form.test.mjs b/test/frontend/config-form.test.mjs index 13f5352d..aa071431 100644 --- a/test/frontend/config-form.test.mjs +++ b/test/frontend/config-form.test.mjs @@ -318,7 +318,7 @@ test('证书管理方式只展示三种业务模式并同步底层托管配置', assert.ok(validateFormConfig('ssl', { tls: { ...tls, customDirectory } })['tls.customDirectory']) } assert.ok(validateFormConfig('ssl', { tls: { ...tls, privateKeyRef: '' } })['tls.privateKeyRef']) - assert.ok(validateFormConfig('ssl', { tls: { ...tls, certificateRef: 'config/ssl/outside.pem' } })['tls.certificateRef']) + assert.deepEqual(validateFormConfig('ssl', { tls: { ...tls, certificateRef: 'ssl/example.com.crt', privateKeyRef: 'ssl/example.com.key' } }), {}) for (const certificateRef of ['C:\\certs\\site.crt', 'D:/certs/site.crt', '/etc/ssl/site.crt', '\\\\server\\share\\site.crt']) { assert.deepEqual(validateFormConfig('ssl', { tls: { ...tls, certificateRef, privateKeyRef: certificateRef.replace(/(?:crt|pem)$/, 'key') } }), {}) } diff --git a/test/frontend/dev-tls.test.mjs b/test/frontend/dev-tls.test.mjs new file mode 100644 index 00000000..31d373cd --- /dev/null +++ b/test/frontend/dev-tls.test.mjs @@ -0,0 +1,95 @@ +import assert from 'node:assert/strict' +import { spawnSync } from 'node:child_process' +import { once } from 'node:events' +import { chmod, mkdtemp, mkdir, writeFile } from 'node:fs/promises' +import { createServer } from 'node:https' +import os from 'node:os' +import path from 'node:path' +import { connect } from 'node:tls' +import test from 'node:test' +import { setTimeout as delay } from 'node:timers/promises' +import { readDevelopmentTLS, developmentTLSReload } from '../../frontend/dev-tls.js' +import { assertDeploymentLayout } from '../../deploy/runtime-config.mjs' + +function findOpenSSL() { + const candidates = ['openssl'] + if (process.platform === 'win32') { + const located = spawnSync('where.exe', ['git'], { encoding: 'utf8', windowsHide: true }) + for (const executable of (located.stdout || '').trim().split(/\r?\n/).filter(Boolean)) { + candidates.push(path.resolve(path.dirname(executable), '../usr/bin/openssl.exe')) + } + } + const result = candidates.find(command => spawnSync(command, ['version'], { windowsHide: true }).status === 0) + assert.ok(result, '开发 TLS 回归需要 OpenSSL 或 Windows Git 自带的 OpenSSL') + return result +} + +test('开发 HTTPS 完整换证、旧连接保留、直接路径和上一套恢复', async t => { + const root = await mkdtemp(path.join(os.tmpdir(), 'smail-dev-tls-')) + for (const directory of ['config', 'ssl', 'data', 'log']) await mkdir(path.join(root, directory)) + await writeFile(path.join(root, 'config/config.json'), JSON.stringify({ + generation: 1, setupState: 'pending', domains: { web: 'mail.example.test' } + })) + for (const section of ['smtp', 'email', 'plugins']) await writeFile(path.join(root, `config/${section}.json`), '{}') + const openssl = findOpenSSL() + for (const name of ['first', 'second']) { + const generated = spawnSync(openssl, [ + 'req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:P-256', '-nodes', + '-keyout', path.join(root, `ssl/${name}.key`), '-out', path.join(root, `ssl/${name}.crt`), + '-days', '1', '-subj', '/CN=mail.example.test', '-addext', 'subjectAltName=DNS:mail.example.test' + ], { windowsHide: true, encoding: 'utf8' }) + assert.equal(generated.status, 0, generated.stderr) + await chmod(path.join(root, `ssl/${name}.key`), 0o600) + } + const save = async (current, previous, absolute = false) => { + const reference = name => absolute ? path.join(root, `ssl/${name}`) : `ssl/${name}` + await writeFile(path.join(root, 'config/ssl.json'), JSON.stringify({ meta: { generation: 1 }, tls: { + certificateRef: reference(`${current}.crt`), privateKeyRef: reference(`${current}.key`), + ...(previous ? { previousCertificateRef: reference(`${previous}.crt`), previousPrivateKeyRef: reference(`${previous}.key`) } : {}) + } })) + } + await save('first') + const initial = readDevelopmentTLS(root) + const server = createServer(initial.options) + const warnings = [] + const connections = new Set() + server.on('secureConnection', socket => { + connections.add(socket) + socket.on('close', () => connections.delete(socket)) + }) + developmentTLSReload(initial, root).configureServer({ + httpServer: server, config: { logger: { warn: message => warnings.push(message), error: message => warnings.push(message) } } + }) + t.after(async () => { + for (const socket of connections) socket.destroy() + await new Promise(resolve => server.close(resolve)) + }) + server.listen(0, '127.0.0.1') + await once(server, 'listening') + const dial = async () => { + const socket = connect({ host: '127.0.0.1', port: server.address().port, rejectUnauthorized: false }) + t.after(() => socket.destroy()) + await once(socket, 'secureConnect') + return socket + } + const oldConnection = await dial() + const serial = oldConnection.getPeerCertificate().serialNumber + await save('second', 'first', true) + assert.equal(assertDeploymentLayout(root).generation, 1) + await delay(1300) + const newConnection = await dial() + assert.notEqual(newConnection.getPeerCertificate().serialNumber, serial) + assert.equal(oldConnection.destroyed, false) + assert.equal(warnings.length, 0) + + await save('missing', 'first') + assert.equal(assertDeploymentLayout(root).generation, 1) + assert.equal(readDevelopmentTLS(root).fingerprint, initial.fingerprint) + await delay(1300) + assert.equal((await dial()).getPeerCertificate().serialNumber, serial) + assert.equal(oldConnection.destroyed, false) + + await save('missing') + assert.throws(() => readDevelopmentTLS(root)) + assert.throws(() => assertDeploymentLayout(root)) +}) diff --git a/test/frontend/runtime-deployment.test.mjs b/test/frontend/runtime-deployment.test.mjs index 7f90385f..1a45e61a 100644 --- a/test/frontend/runtime-deployment.test.mjs +++ b/test/frontend/runtime-deployment.test.mjs @@ -14,10 +14,11 @@ test('开发配置只从模拟部署目录读取且不返回凭据字段', async generation: 9, domains: { web: 'mail.example.test' }, database: { password: 'not-exported' } })) await writeFile(path.join(root, 'config/ssl.json'), JSON.stringify({ + meta: { generation: 9 }, tls: { certificateRef: 'ssl/public.crt', privateKeyRef: 'ssl/private.key' } })) await writeFile(path.join(root, 'ssl/public.crt'), 'certificate') - await writeFile(path.join(root, 'ssl/private.key'), 'key') + await writeFile(path.join(root, 'ssl/private.key'), 'key', { mode: 0o600 }) const runtime = readDevelopmentRuntime(root) assert.equal(runtime.origin, 'https://mail.example.test') assert.equal(runtime.generation, 9) @@ -26,6 +27,8 @@ test('开发配置只从模拟部署目录读取且不返回凭据字段', async assert.equal(runtimeRoot, path.join(sourceRoot, 'yunx-test')) assert.throws(() => resolveRuntimeFile(root, '../outside.key')) assert.throws(() => resolveRuntimeFile(root, path.join(root, 'ssl/private.key'))) + await writeFile(path.join(root, 'config/ssl.json'), JSON.stringify({ meta: { generation: 10 }, tls: {} })) + assert.throws(() => readDevelopmentRuntime(root), /事务尚未完成/) }) test('源码指纹检测编辑且忽略编译嵌入目录', async () => { @@ -77,7 +80,7 @@ test('部署启动检查兼容自动归档前后的密钥且拒绝双份冲突', for (const name of ['smtp', 'email', 'plugins']) await writeFile(path.join(root, `config/${name}.json`), '{}') await writeFile(path.join(root, 'config/ssl.json'), JSON.stringify({ tls: { certificateRef: 'ssl/public.crt', privateKeyRef: 'ssl/private.key' } })) await writeFile(path.join(root, 'ssl/public.crt'), 'certificate') - await writeFile(path.join(root, 'ssl/private.key'), 'key') + await writeFile(path.join(root, 'ssl/private.key'), 'key', { mode: 0o600 }) for (const [folder, name] of [ ['credentials', 'credential.key'], ['external-email-encryption', 'external-email-encryption.key'], diff --git a/test/run.mjs b/test/run.mjs index 5e084896..1039ddae 100644 --- a/test/run.mjs +++ b/test/run.mjs @@ -68,6 +68,7 @@ if ((suite === 'all' || suite === 'backend') && result === 0) { 'backend/config/config_runtime_log_test.go': 'test/backend/config_runtime_log_test.go', 'backend/config/deployment_state_test.go': 'test/backend/deployment_state_test.go', 'backend/config/ssl_retention_test.go': 'test/backend/ssl_retention_test.go', + 'backend/config/ssl_lifecycle_test.go': 'test/backend/ssl_lifecycle_test.go', 'backend/utils/runtimepath/layout_test.go': 'test/backend/runtime_layout_test.go', 'backend/config/data_paths_test.go': 'test/backend/data_paths_test.go', 'backend/config/ssl_custom_regression_test.go': 'test/backend/ssl_custom_test.go',