This commit is contained in:
1 parent
dd9d659cb7
commit
9dc861d560
41 files changed
+1408
-198
No files matched your search
@@ -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)
|
||||
|
||||
@@ -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},
|
||||
}
|
||||
|
||||
@@ -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") {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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("管理器停止后仍持有暂存租约")
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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') } }), {})
|
||||
}
|
||||
|
||||
@@ -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))
|
||||
})
|
||||
@@ -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'],
|
||||
|
||||
@@ -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',
|
||||
|
||||
Reference in new issue
Block a user