1 parent
48f4b24781
commit
a045a0cd17
27 files changed
+1209
-24
No files matched your search
@@ -55,6 +55,8 @@ func TestDataMigrationKeepsSecretsCertificatesAndBackupRestorable(t *testing.T)
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 构造旧版磁盘布局;文件内容及密文均来自真实实现,而不是手写假密钥。
|
||||
// 模拟停服时释放暂存租约,真实进程退出后操作系统也会释放文件锁。
|
||||
releaseManagedSSL(root, SSLConfig{CertificateRef: reference.CertificateRef})
|
||||
entries, _ := os.ReadDir(filepath.Join(root, "data"))
|
||||
for _, entry := range entries {
|
||||
if err := os.Rename(filepath.Join(root, "data", entry.Name()), filepath.Join(root, "config", entry.Name())); err != nil {
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/services/externalemail"
|
||||
"git.pcux.cn/xuans/Smail/utils/credential"
|
||||
"git.pcux.cn/xuans/Smail/utils/runtimepath"
|
||||
)
|
||||
@@ -171,3 +172,84 @@ func TestDeploymentManagedReferenceUsesArgumentRoot(t *testing.T) {
|
||||
t.Fatalf("引用错误:%s", ref.CertificateRef)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeploymentAutomaticallyCreatesBusinessDirectories(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
if err := InitializeDeployment(root); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, name := range []string{"config", "ssl", "data", "log"} {
|
||||
if info, err := os.Lstat(filepath.Join(root, name)); err != nil || !info.IsDir() {
|
||||
t.Fatalf("正式启动没有创建部署目录:%s", name)
|
||||
}
|
||||
}
|
||||
for _, name := range []string{"credentials", "external-email-encryption", "external-email-fingerprint", "dkim", "managed"} {
|
||||
info, err := os.Lstat(filepath.Join(root, "ssl", name))
|
||||
if err != nil || !info.IsDir() {
|
||||
t.Fatalf("程序启动没有创建业务目录:%s", name)
|
||||
}
|
||||
}
|
||||
if _, err := credential.Encrypt(root, "fixture"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := externalemail.NewVault(root); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, name := range runtimepath.BusinessKeyNames() {
|
||||
if filepath.Dir(runtimepath.KeyPath(root, name)) == filepath.Join(root, "ssl") {
|
||||
t.Fatal("新密钥仍在 ssl 根目录生成")
|
||||
}
|
||||
if info, err := os.Stat(runtimepath.KeyPath(root, name)); err != nil || info.Size() != 32 {
|
||||
t.Fatal("业务密钥未正确生成")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeploymentAutomaticallyMigratesOriginalKeyBytes(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
if err := os.Mkdir(filepath.Join(root, "ssl"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for index, name := range runtimepath.BusinessKeyNames() {
|
||||
if err := os.WriteFile(filepath.Join(root, "ssl", name), bytes.Repeat([]byte{byte(index + 1)}, 32), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
secret, err := credential.Encrypt(root, "preserved-secret")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
oldVault, err := externalemail.NewVault(root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
email, _ := oldVault.Encrypt("user@example.com")
|
||||
fingerprint, _ := oldVault.Fingerprint("user@example.com")
|
||||
for attempt := 0; attempt < 3; attempt++ {
|
||||
if err := InitializeDeployment(root); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for index, name := range runtimepath.BusinessKeyNames() {
|
||||
actual, err := os.ReadFile(runtimepath.KeyPath(root, name))
|
||||
if err != nil || !bytes.Equal(actual, bytes.Repeat([]byte{byte(index + 1)}, 32)) {
|
||||
t.Fatal("迁移或重复启动改变了原密钥")
|
||||
}
|
||||
if _, err := os.Lstat(filepath.Join(root, "ssl", name)); !os.IsNotExist(err) {
|
||||
t.Fatal("旧位置未迁移")
|
||||
}
|
||||
}
|
||||
}
|
||||
if value, err := credential.Decrypt(root, secret); err != nil || value != "preserved-secret" {
|
||||
t.Fatal("旧凭据密文无法解密")
|
||||
}
|
||||
vault, err := externalemail.NewVault(root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if value, err := vault.Decrypt(email); err != nil || value != "user@example.com" {
|
||||
t.Fatal("外部邮箱旧密文无法解密")
|
||||
}
|
||||
if value, err := vault.Fingerprint("user@example.com"); err != nil || value != fingerprint {
|
||||
t.Fatal("邮箱索引指纹发生变化")
|
||||
}
|
||||
}
|
||||
@@ -154,3 +154,49 @@ func TestLegacyReferenceOnlyChangesKnownRelativeDirectories(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupedKeysRejectConflictMissingAndUnsafeTarget(t *testing.T) {
|
||||
for _, failure := range []string{"conflict", "missing", "unsafe", "invalid"} {
|
||||
t.Run(failure, func(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
put(t, root, "data/smail-state.db", []byte("marker"))
|
||||
put(t, root, "config/config.json", []byte(`{"setupState":"ready","database":{"type":"mysql"}}`))
|
||||
for _, name := range BusinessKeyNames() {
|
||||
if failure != "missing" || name != "external-email-fingerprint.key" {
|
||||
put(t, root, "ssl/"+name, bytes.Repeat([]byte{1}, 32))
|
||||
}
|
||||
}
|
||||
switch failure {
|
||||
case "conflict":
|
||||
put(t, root, "ssl/credentials/credential.key", bytes.Repeat([]byte{2}, 32))
|
||||
case "unsafe":
|
||||
put(t, root, "ssl/external-email-fingerprint", []byte("not-directory"))
|
||||
case "invalid":
|
||||
put(t, root, "ssl/external-email-encryption.key", []byte("invalid"))
|
||||
}
|
||||
if err := PrepareDeploymentKeys(root); err == nil {
|
||||
t.Fatal("异常部署不应继续自动迁移")
|
||||
}
|
||||
if data, err := os.ReadFile(filepath.Join(root, "ssl", "credential.key")); err != nil || !bytes.Equal(data, bytes.Repeat([]byte{1}, 32)) {
|
||||
t.Fatal("预检失败修改了原密钥")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupedKeysResumePartiallyMovedDeployment(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
put(t, root, "data/smail-state.db", []byte("marker"))
|
||||
put(t, root, "config/config.json", []byte(`{"setupState":"ready","database":{"type":"mysql"}}`))
|
||||
put(t, root, "ssl/credentials/credential.key", bytes.Repeat([]byte{1}, 32))
|
||||
put(t, root, "ssl/external-email-encryption.key", bytes.Repeat([]byte{2}, 32))
|
||||
put(t, root, "ssl/external-email-fingerprint.key", bytes.Repeat([]byte{3}, 32))
|
||||
if err := PrepareDeploymentKeys(root); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for index, name := range BusinessKeyNames() {
|
||||
if data, err := os.ReadFile(groupedKeyPath(root, name)); err != nil || !bytes.Equal(data, bytes.Repeat([]byte{byte(index + 1)}, 32)) {
|
||||
t.Fatal("中断恢复改变了原始密钥")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func sslConfigForReference(ref ManagedSSLReference) SSLConfig {
|
||||
return SSLConfig{Mode: ref.Mode, CertificateRef: ref.CertificateRef, PrivateKeyRef: ref.PrivateKeyRef}
|
||||
}
|
||||
|
||||
func countManagedVersions(t *testing.T, root string) int {
|
||||
t.Helper()
|
||||
count := 0
|
||||
for _, mode := range []string{ManagedSSLModeDefault, ManagedSSLModeUpload} {
|
||||
path, err := managedSSLRootPathAtRoot(root, mode)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entries, err := os.ReadDir(path)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if validSSLVersion(entry.Name()) {
|
||||
count++
|
||||
}
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
func TestSSLRetentionHandlesExpiredPreviousAndLegacyCurrent(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)
|
||||
legacy, err := importManagedSSLAtRoot(root, ManagedSSLModeDefault, key, cert, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var refs []ManagedSSLReference
|
||||
for index := 0; index < 4; index++ {
|
||||
ref, err := stageManagedSSLAtRoot(root, ManagedSSLModeUpload, key, cert, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
releaseManagedSSL(root, sslConfigForReference(ref))
|
||||
refs = append(refs, ref)
|
||||
}
|
||||
expiredKey, expiredCert := testManagedCertificate(t, "example.com", time.Now().Add(-2*time.Hour), time.Now().Add(-time.Hour), 2048)
|
||||
if err := os.WriteFile(refs[2].PrivateKeyPath, expiredKey, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(refs[2].CertificatePath, expiredCert, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
maintainManagedSSL(root, sslConfigForReference(refs[3]), sslConfigForReference(refs[2]))
|
||||
if countManagedVersions(t, root) != 2 {
|
||||
t.Fatal("上一份证书过期阻止了清理")
|
||||
}
|
||||
if _, err := os.Stat(legacy.CertificatePath); !os.IsNotExist(err) {
|
||||
t.Fatal("未被引用的旧 current 未清理")
|
||||
}
|
||||
if _, err := os.Stat(refs[2].CertificatePath); err != nil {
|
||||
t.Fatal("清理删除了受保护的上一份证书")
|
||||
}
|
||||
old := validRuntimeConfig()
|
||||
old.SSL.TLS = sslConfigForReference(legacy)
|
||||
if err := validateRollbackSSL(root, old); !errors.Is(err, ErrSSLHistoryUnavailable) {
|
||||
t.Fatal("历史 current 丢失后仍允许回滚")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSLRetentionProtectsIndependentLease(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)
|
||||
var refs []ManagedSSLReference
|
||||
for index := 0; index < 4; index++ {
|
||||
ref, err := stageManagedSSLAtRoot(root, ManagedSSLModeUpload, key, cert, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
releaseManagedSSL(root, sslConfigForReference(ref))
|
||||
refs = append(refs, ref)
|
||||
}
|
||||
lease, err := openSSLLease(refs[0].PrivateKeyPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer lease.Close()
|
||||
unlock, err := lockStateFile(lease)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer unlock()
|
||||
maintainManagedSSL(root, sslConfigForReference(refs[3]))
|
||||
if _, err := os.Stat(refs[0].CertificatePath); err != nil {
|
||||
t.Fatal("清理忽略了其他句柄持有的暂存租约")
|
||||
}
|
||||
if countManagedVersions(t, root) != 2 {
|
||||
t.Fatal("暂存和生效证书以外的历史未清理")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSLRetentionKeepsTwoAcrossModesAndProtectsStaged(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)
|
||||
var refs []ManagedSSLReference
|
||||
for index := 0; index < 4; index++ {
|
||||
mode := ManagedSSLModeDefault
|
||||
if index%2 == 1 {
|
||||
mode = ManagedSSLModeUpload
|
||||
}
|
||||
ref, err := stageManagedSSLAtRoot(root, mode, key, cert, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
refs = append(refs, ref)
|
||||
if index > 0 {
|
||||
maintainManagedSSL(root, sslConfigForReference(refs[index-1]))
|
||||
if _, err := os.Stat(ref.PrivateKeyPath); err != nil {
|
||||
t.Fatal("清理误删尚未提交的续期版本")
|
||||
}
|
||||
maintainManagedSSL(root, sslConfigForReference(ref), sslConfigForReference(refs[index-1]))
|
||||
} else {
|
||||
maintainManagedSSL(root, sslConfigForReference(ref))
|
||||
}
|
||||
want := index + 1
|
||||
if want > 2 {
|
||||
want = 2
|
||||
}
|
||||
if actual := countManagedVersions(t, root); actual != want {
|
||||
t.Fatalf("跨模式保留总量错误:%d,期望 %d", actual, want)
|
||||
}
|
||||
}
|
||||
old := validRuntimeConfig()
|
||||
old.SSL.TLS = sslConfigForReference(refs[0])
|
||||
if err := validateRollbackSSL(root, old); !errors.Is(err, ErrSSLHistoryUnavailable) {
|
||||
t.Fatalf("旧证书已清理却允许回滚:%v", err)
|
||||
}
|
||||
// 即使当前证书的目录时间最旧,也必须保留当前证书。
|
||||
if err := os.Chtimes(filepath.Dir(refs[2].CertificatePath), time.Unix(1, 0), time.Unix(1, 0)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
maintainManagedSSL(root, sslConfigForReference(refs[2]))
|
||||
if _, err := resolveManagedSSLReferencesAtRoot(root, sslConfigForReference(refs[2])); err != nil {
|
||||
t.Fatal("清理删除了旧时间的生效证书")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSLRetentionDoesNotPartiallyDeleteUnknownFiles(t *testing.T) {
|
||||
directory := filepath.Join(t.TempDir(), "version-00000000000000000000000000000000")
|
||||
if err := os.Mkdir(directory, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, name := range []string{"private.key", "public.crt", "zzz-user-note.txt"} {
|
||||
if err := os.WriteFile(filepath.Join(directory, name), []byte("preserved"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := removeManagedSSLDirectory(directory); !errors.Is(err, ErrUnsafeSSLFile) {
|
||||
t.Fatal("未知文件没有阻止删除")
|
||||
}
|
||||
for _, name := range []string{"private.key", "public.crt", "zzz-user-note.txt"} {
|
||||
if _, err := os.Stat(filepath.Join(directory, name)); err != nil {
|
||||
t.Fatal("预检期间已经删除了部分文件")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSLRetentionRunsOnApplyCancelAndReload(t *testing.T) {
|
||||
root, manager, request, _ := customSSLFixture(t)
|
||||
var first RuntimeConfig
|
||||
for index := 0; index < 4; index++ {
|
||||
request.ExpectedGeneration = manager.Snapshot().Generation
|
||||
updated, err := manager.Update(context.Background(), request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := manager.ApplyPendingAuthorized(context.Background(), updated.Generation, updated.CandidateID, SectionSSL, request.Actor); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if index == 0 {
|
||||
first = manager.Snapshot()
|
||||
if _, err := manager.transactions.CreateBackup(first); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if index > 0 && countManagedVersions(t, root) != 2 {
|
||||
t.Fatal("配置应用完成后未自动保留两份")
|
||||
}
|
||||
}
|
||||
if _, err := manager.PreviewRollback(context.Background(), first.Generation, request.Actor); !errors.Is(err, ErrSSLHistoryUnavailable) {
|
||||
t.Fatalf("预览允许回滚已经清理的证书:%v", err)
|
||||
}
|
||||
if _, _, err := manager.rollbackWithState(context.Background(), first.Generation, request.Actor, StepUpConfirmation{Confirmed: true, Method: "ticket"}); !errors.Is(err, ErrSSLHistoryUnavailable) {
|
||||
t.Fatalf("实际回滚没有拒绝已清理证书:%v", err)
|
||||
}
|
||||
request.ExpectedGeneration = manager.Snapshot().Generation
|
||||
updated, err := manager.Update(context.Background(), request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := manager.ManagePending(context.Background(), updated.Generation, updated.CandidateID, request.Actor, StepUpConfirmation{}, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if countManagedVersions(t, root) != 2 {
|
||||
t.Fatal("取消候选未收敛到两份")
|
||||
}
|
||||
if err := manager.Load(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if countManagedVersions(t, root) != 2 {
|
||||
t.Fatal("重新加载后保留数量错误")
|
||||
}
|
||||
// 确认五分区仍可完整读取,证书删除不能导致摘要被直接修改。
|
||||
data, _ := json.Marshal(manager.Snapshot().SSL)
|
||||
if len(data) == 0 {
|
||||
t.Fatal("配置快照不可读")
|
||||
}
|
||||
request.ExpectedGeneration = manager.Snapshot().Generation
|
||||
updated, err = manager.Update(context.Background(), request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manager.releasePendingSSL()
|
||||
path, err := resolveManagedSSLPathsAtRoot(root, updated.Candidate.SSL.TLS)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
managedSSLStorage.Lock()
|
||||
stillLeased := managedSSLStorage.staged[filepath.Dir(path.CertificatePath)] != nil
|
||||
managedSSLStorage.Unlock()
|
||||
if stillLeased {
|
||||
t.Fatal("管理器停止后仍持有暂存租约")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
"""使用最新二进制验证空目录正式启动,保留并恢复现有模拟部署。"""
|
||||
|
||||
import hashlib
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
RUNTIME = ROOT / "yunx-test"
|
||||
BUSINESS = {
|
||||
"credential.key": "credentials",
|
||||
"external-email-encryption.key": "external-email-encryption",
|
||||
"external-email-fingerprint.key": "external-email-fingerprint",
|
||||
}
|
||||
|
||||
|
||||
def checked(path):
|
||||
absolute = path.resolve()
|
||||
if not absolute.is_relative_to(ROOT) or absolute == ROOT or path.is_symlink():
|
||||
raise RuntimeError("测试路径越过项目边界或为链接")
|
||||
return absolute
|
||||
|
||||
|
||||
def digest(path):
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def main():
|
||||
for service_port in (80, 443, 5201):
|
||||
with socket.socket() as probe:
|
||||
probe.settimeout(0.5)
|
||||
if probe.connect_ex(("127.0.0.1", service_port)) == 0:
|
||||
raise RuntimeError("请先停止模拟部署的前后端,不能移动运行中的部署")
|
||||
receipt = json.loads((ROOT / "out" / "build-state.json").read_text(encoding="utf-8"))
|
||||
for item in receipt["files"]:
|
||||
if item["target"] and digest(RUNTIME / item["target"]) != item["sha256"]:
|
||||
raise RuntimeError("部署二进制与最新构建清单不一致")
|
||||
port = 15201
|
||||
with socket.socket() as probe:
|
||||
probe.bind(("127.0.0.1", port))
|
||||
record = checked(ROOT / "test-log" / time.strftime("ssl-startup-%Y%m%d-%H%M%S"))
|
||||
record.mkdir()
|
||||
saved = checked(record / "existing-runtime")
|
||||
fixture = checked(record / "fresh-runtime")
|
||||
checked(RUNTIME)
|
||||
# 必须由调用方先停止本项目两个服务;部署入口自身也会拒绝覆盖运行程序。
|
||||
RUNTIME.rename(saved)
|
||||
result = {"productionArguments": ["-p", str(port)], "starts": []}
|
||||
process = None
|
||||
try:
|
||||
RUNTIME.mkdir()
|
||||
for name in ("smail.exe", "smail-admin.exe"):
|
||||
shutil.copy2(saved / name, RUNTIME / name)
|
||||
env = dict(os.environ)
|
||||
env["SMAIL_ROOT"] = str(RUNTIME)
|
||||
env["SMAIL_SETUP_HOST"] = "127.0.0.1"
|
||||
for name in ("SMAIL_HTTP_PORT_OVERRIDE", "SMAIL_HTTP_TLS_MODE_OVERRIDE", "SMAIL_SETUP_TOKEN", "SMAIL_SETUP_ALLOWED_CIDRS"):
|
||||
env.pop(name, None)
|
||||
first = None
|
||||
for attempt in range(2):
|
||||
with (record / f"startup-{attempt + 1}.log").open("wb") as log:
|
||||
process = subprocess.Popen(
|
||||
[str(RUNTIME / "smail.exe"), "-p", str(port)], cwd=RUNTIME,
|
||||
env=env, stdout=log, stderr=subprocess.STDOUT,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0,
|
||||
)
|
||||
ready = False
|
||||
for _ in range(100):
|
||||
if process.poll() is not None:
|
||||
raise RuntimeError("正式启动提前退出,请检查测试日志")
|
||||
connection = http.client.HTTPConnection("127.0.0.1", port, timeout=1)
|
||||
try:
|
||||
connection.request("GET", "/")
|
||||
response = connection.getresponse()
|
||||
ready = response.status == 200
|
||||
response.read()
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
connection.close()
|
||||
if ready:
|
||||
break
|
||||
time.sleep(0.1)
|
||||
if not ready:
|
||||
raise RuntimeError("正式启动未进入初始化页面")
|
||||
for folder in ("config", "ssl", "data", "log"):
|
||||
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"):
|
||||
if not (RUNTIME / "ssl" / folder).is_dir():
|
||||
raise RuntimeError("主程序没有自动创建业务目录")
|
||||
if first is not None and directories != first:
|
||||
raise RuntimeError("重复启动的业务目录结构发生变化")
|
||||
first = directories
|
||||
result["starts"].append({"httpStatus": 200, "sslDirectories": directories})
|
||||
process.terminate()
|
||||
process.wait(timeout=15)
|
||||
process = None
|
||||
result["binaryMatchesLatest"] = digest(RUNTIME / "smail.exe") == digest(saved / "smail.exe")
|
||||
finally:
|
||||
if process is not None and process.poll() is None:
|
||||
process.kill()
|
||||
process.wait(timeout=15)
|
||||
if RUNTIME.exists():
|
||||
checked(RUNTIME).rename(fixture)
|
||||
checked(saved).rename(RUNTIME)
|
||||
result["existingRuntimeRestored"] = True
|
||||
(record / "result.json").write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print("空目录正式启动和重复启动通过,现有部署已恢复:", record.relative_to(ROOT))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,9 +1,9 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { mkdtemp, mkdir, readFile, writeFile } from 'node:fs/promises'
|
||||
import { mkdtemp, mkdir, readFile, symlink, writeFile } from 'node:fs/promises'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import test from 'node:test'
|
||||
import { readDevelopmentRuntime, resolveRuntimeFile, runtimeRoot, sourceRoot } from '../../deploy/runtime-config.mjs'
|
||||
import { assertDeploymentLayout, readDevelopmentRuntime, resolveRuntimeFile, runtimeRoot, sourceRoot } from '../../deploy/runtime-config.mjs'
|
||||
import { fileDigest, sourceFingerprint } from '../../deploy/build-state.mjs'
|
||||
|
||||
test('开发配置只从模拟部署目录读取且不返回凭据字段', async () => {
|
||||
@@ -45,6 +45,15 @@ test('源码指纹检测编辑且忽略编译嵌入目录', async () => {
|
||||
await assert.rejects(fileDigest(path.join(root, 'empty.exe')))
|
||||
})
|
||||
|
||||
test('运行文件拒绝通过父目录链接访问另一个业务目录', async () => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), 'smail-runtime-link-'))
|
||||
await mkdir(path.join(root, 'ssl'))
|
||||
await mkdir(path.join(root, 'data'))
|
||||
await writeFile(path.join(root, 'data/private.key'), 'fixture')
|
||||
await symlink(path.join(root, 'data'), path.join(root, 'ssl/linked'), process.platform === 'win32' ? 'junction' : 'dir')
|
||||
assert.throws(() => resolveRuntimeFile(root, 'ssl/linked/private.key'), /链接/)
|
||||
})
|
||||
|
||||
test('部署和启动必须完整构建、验证产物且不覆盖运行配置', async () => {
|
||||
const read = name => readFile(path.join(sourceRoot, name), 'utf8')
|
||||
const deploy = await read('deploy/deploy-runtime.ps1')
|
||||
@@ -59,3 +68,28 @@ test('部署和启动必须完整构建、验证产物且不覆盖运行配置',
|
||||
assert.match(start, /build-state\.mjs'\) verify --deployed/)
|
||||
assert.match(await read('.gitignore'), /^\/yunx-test\/$/m)
|
||||
})
|
||||
|
||||
test('部署启动检查兼容自动归档前后的密钥且拒绝双份冲突', async () => {
|
||||
for (const grouped of [false, true]) {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), 'smail-key-layout-'))
|
||||
for (const name of ['config', 'ssl', 'data', 'log']) await mkdir(path.join(root, name))
|
||||
await writeFile(path.join(root, 'config/config.json'), JSON.stringify({ setupState: 'ready', database: { type: 'mysql' } }))
|
||||
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')
|
||||
for (const [folder, name] of [
|
||||
['credentials', 'credential.key'],
|
||||
['external-email-encryption', 'external-email-encryption.key'],
|
||||
['external-email-fingerprint', 'external-email-fingerprint.key']
|
||||
]) {
|
||||
if (grouped) await mkdir(path.join(root, 'ssl', folder))
|
||||
await writeFile(path.join(root, 'ssl', ...(grouped ? [folder] : []), name), Buffer.alloc(32, 1))
|
||||
}
|
||||
assert.equal(assertDeploymentLayout(root).setupState, 'ready')
|
||||
if (grouped) {
|
||||
await writeFile(path.join(root, 'ssl/credential.key'), Buffer.alloc(32, 2))
|
||||
assert.throws(() => assertDeploymentLayout(root), /冲突/)
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -50,6 +50,7 @@ if ((suite === 'all' || suite === 'backend') && result === 0) {
|
||||
// 独立回归源码集中放在 test/backend,通过 overlay 保留同包测试语义。
|
||||
const replacements = {
|
||||
'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/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