分离五项配置与运行数据并实现无损目录迁移
Security Checks / security (push) Waiting to run

This commit is contained in:
xuans committed 2026-09-08 17:16:09 +08:00
1 parent dc188b1ed8
commit d6cc81ed87
53 files changed
+909 -127

No files matched your search

+1 -1
View File
@@ -117,7 +117,7 @@ func HasAuth(ctx *context.Context, email *models.Email) bool {
}
func DkimGen() (string, error) {
basePath := filepath.Join(config.ROOT_PATH, "config", "dkim")
basePath := filepath.Join(config.ROOT_PATH, "data", "dkim")
cfg := config.CurrentConfig()
if cfg == nil {
return "", fmt.Errorf("runtime configuration is unavailable")
@@ -19,10 +19,10 @@ import (
func portableFixture(t *testing.T) (string, config.DatabaseConfig) {
t.Helper()
root := t.TempDir()
if err := os.Mkdir(filepath.Join(root, "config"), 0700); err != nil {
if err := os.Mkdir(filepath.Join(root, "data"), 0700); err != nil {
t.Fatal(err)
}
database, err := sql.Open("sqlite", filepath.Join(root, "config", "source.db"))
database, err := sql.Open("sqlite", filepath.Join(root, "data", "source.db"))
if err != nil {
t.Fatal(err)
}
@@ -57,7 +57,7 @@ func TestPortableSQLiteCopyPreservesDataAndLocksUntilRestart(t *testing.T) {
if err := executor.Preview(context.Background(), plan); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Join(root, "config", "target.db")); !os.IsNotExist(err) {
if _, err := os.Stat(filepath.Join(root, "data", "target.db")); !os.IsNotExist(err) {
t.Fatal("preview created target")
}
if err := executor.Run(context.Background(), plan, func(Status) error { return nil }); err != nil {
@@ -87,7 +87,7 @@ func TestPortableSQLiteCopyPreservesDataAndLocksUntilRestart(t *testing.T) {
if err := target.QueryRow(`SELECT id FROM "user" WHERE account='next'`).Scan(&next); err != nil || next <= 40 {
t.Fatal("identity sequence not advanced")
}
old, err := sql.Open("sqlite", filepath.Join(root, "config", "source.db")+"?_pragma=busy_timeout(1)")
old, err := sql.Open("sqlite", filepath.Join(root, "data", "source.db")+"?_pragma=busy_timeout(1)")
if err != nil {
t.Fatal(err)
}
@@ -113,7 +113,7 @@ func TestPortableSwitchFailurePreservesSourceAndTarget(t *testing.T) {
t.Fatal("rejected switch kept write lock")
}
for _, name := range []string{"source.db", "target.db"} {
if _, err := os.Stat(filepath.Join(root, "config", name)); err != nil {
if _, err := os.Stat(filepath.Join(root, "data", name)); err != nil {
t.Fatal("database removed")
}
}
@@ -205,7 +205,7 @@ func TestPortableRejectsCustomObjectsBeforeCreatingTarget(t *testing.T) {
if err := executor.Run(context.Background(), plan, func(Status) error { return nil }); !errors.Is(err, ErrSQLUnsupportedObject) {
t.Fatalf("custom view accepted: %v", err)
}
if _, err := os.Stat(filepath.Join(root, "config", "target.db")); !os.IsNotExist(err) {
if _, err := os.Stat(filepath.Join(root, "data", "target.db")); !os.IsNotExist(err) {
t.Fatal("unsupported source created target")
}
}
+1 -1
View File
@@ -241,7 +241,7 @@ func TestExecuteAuthorizedPassesActorToSQLiteSwitch(t *testing.T) {
root = t.TempDir()
executor = NewAuthorizedSQLiteExecutor(root, switchConfig)
service = NewService(executor)
configDirectory := filepath.Join(root, "config")
configDirectory := filepath.Join(root, "data")
if err := os.Mkdir(configDirectory, 0700); err != nil {
t.Fatal(err)
}
@@ -152,7 +152,7 @@ func (e *SQLiteExecutor) resolveReference(reference string) (string, error) {
if err != nil {
return "", ErrInvalidTargetName
}
configDirectory := filepath.Join(root, "config")
configDirectory := filepath.Join(root, "data")
info, err := os.Lstat(configDirectory)
if err != nil || info.Mode()&os.ModeSymlink != 0 || !info.IsDir() {
return "", ErrInvalidTargetName
@@ -17,7 +17,7 @@ import (
func newSQLiteMigrationFixture(t *testing.T, switchConfig SQLiteSwitch) (*Service, string) {
t.Helper()
root := t.TempDir()
configDirectory := filepath.Join(root, "config")
configDirectory := filepath.Join(root, "data")
if err := os.Mkdir(configDirectory, 0700); err != nil {
t.Fatal(err)
}
@@ -57,7 +57,7 @@ func TestSQLiteExecutorCopiesDatabaseAndSwitchesConfiguration(t *testing.T) {
if switched.LocalRef != "smail-next.db" || switched.Type != config.DatabaseTypeSQLite {
t.Fatalf("unexpected switched configuration: %+v", switched)
}
database, err := sql.Open("sqlite", filepath.Join(root, "config", "smail-next.db"))
database, err := sql.Open("sqlite", filepath.Join(root, "data", "smail-next.db"))
if err != nil {
t.Fatal(err)
}
@@ -69,7 +69,7 @@ func TestSQLiteExecutorCopiesDatabaseAndSwitchesConfiguration(t *testing.T) {
if body != "测试邮件" {
t.Fatalf("copied row = %q, want copied content", body)
}
info, err := os.Stat(filepath.Join(root, "config", "smail-next.db"))
info, err := os.Stat(filepath.Join(root, "data", "smail-next.db"))
if err != nil {
t.Fatal(err)
}
@@ -84,10 +84,10 @@ func TestSQLiteExecutorSupportsNestedReferences(t *testing.T) {
switched = candidate
return nil
})
if err := os.MkdirAll(filepath.Join(root, "config", "archive"), 0700); err != nil {
if err := os.MkdirAll(filepath.Join(root, "data", "archive"), 0700); err != nil {
t.Fatal(err)
}
if err := os.Rename(filepath.Join(root, "config", "smail.db"), filepath.Join(root, "config", "archive", "review.db")); err != nil {
if err := os.Rename(filepath.Join(root, "data", "smail.db"), filepath.Join(root, "data", "archive", "review.db")); err != nil {
t.Fatal(err)
}
record, token, err := service.Preview(context.Background(), config.DatabaseConfig{Type: config.DatabaseTypeSQLite, LocalRef: "archive/review.db"}, 1, "archive/next.db")
@@ -101,14 +101,14 @@ func TestSQLiteExecutorSupportsNestedReferences(t *testing.T) {
if switched.LocalRef != "archive/next.db" {
t.Fatalf("switched localRef = %q, want archive/next.db", switched.LocalRef)
}
if _, err := os.Stat(filepath.Join(root, "config", "archive", "next.db")); err != nil {
if _, err := os.Stat(filepath.Join(root, "data", "archive", "next.db")); err != nil {
t.Fatal(err)
}
}
func TestSQLiteExecutorRejectsExistingTarget(t *testing.T) {
service, root := newSQLiteMigrationFixture(t, func(context.Context, config.DatabaseConfig) error { return nil })
if err := os.WriteFile(filepath.Join(root, "config", "smail-next.db"), []byte("existing"), 0600); err != nil {
if err := os.WriteFile(filepath.Join(root, "data", "smail-next.db"), []byte("existing"), 0600); err != nil {
t.Fatal(err)
}
record, token, err := service.Preview(context.Background(), config.DatabaseConfig{Type: config.DatabaseTypeSQLite, LocalRef: "smail.db"}, 1, "smail-next.db")
@@ -126,10 +126,10 @@ func TestSQLiteExecutorRejectsExistingTarget(t *testing.T) {
func TestSQLiteExecutorRejectsCorruptSource(t *testing.T) {
root := t.TempDir()
if err := os.Mkdir(filepath.Join(root, "config"), 0700); err != nil {
if err := os.Mkdir(filepath.Join(root, "data"), 0700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "config", "smail.db"), []byte("not sqlite"), 0600); err != nil {
if err := os.WriteFile(filepath.Join(root, "data", "smail.db"), []byte("not sqlite"), 0600); err != nil {
t.Fatal(err)
}
executor := NewSQLiteExecutor(root, func(context.Context, config.DatabaseConfig) error { return nil })
@@ -162,7 +162,7 @@ func TestSQLiteExecutorRequiresConfigurationSwitch(t *testing.T) {
if failed.ErrorCode != "SWITCH_UNAVAILABLE" {
t.Fatalf("error code = %q, want SWITCH_UNAVAILABLE", failed.ErrorCode)
}
if _, err := os.Stat(filepath.Join(root, "config", "next.db")); !errors.Is(err, os.ErrNotExist) {
if _, err := os.Stat(filepath.Join(root, "data", "next.db")); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("target database remained after switch failure, stat error = %v", err)
}
}
@@ -179,7 +179,7 @@ func TestSQLiteExecutorCleansTargetForKnownConfigurationSwitchRejection(t *testi
if !errors.Is(err, config.ErrGenerationConflict) || errors.Is(err, ErrSwitchOutcomeUnknown) {
t.Fatalf("known switch rejection = %v, record = %+v", err, failed)
}
if _, statErr := os.Stat(filepath.Join(root, "config", "known-rejection.db")); !errors.Is(statErr, os.ErrNotExist) {
if _, statErr := os.Stat(filepath.Join(root, "data", "known-rejection.db")); !errors.Is(statErr, os.ErrNotExist) {
t.Fatalf("target database remained after known switch rejection, stat error = %v", statErr)
}
}
@@ -199,7 +199,7 @@ func TestSQLiteExecutorPreservesTargetWhenConfigurationSwitchOutcomeIsUnknown(t
if !errors.Is(err, ErrSwitchOutcomeUnknown) {
t.Fatalf("switch failure error = %v, want unknown switch outcome", err)
}
if _, statErr := os.Stat(filepath.Join(root, "config", "next.db")); statErr != nil {
if _, statErr := os.Stat(filepath.Join(root, "data", "next.db")); statErr != nil {
t.Fatalf("target database was removed after unknown switch outcome: %v", statErr)
}
}
@@ -209,8 +209,8 @@ func TestSQLiteExecutorRejectsTargetSymlink(t *testing.T) {
t.Skip("Windows 创建符号链接需要额外权限")
}
service, root := newSQLiteMigrationFixture(t, func(context.Context, config.DatabaseConfig) error { return nil })
target := filepath.Join(root, "config", "next.db")
if err := os.Symlink(filepath.Join(root, "config", "smail.db"), target); err != nil {
target := filepath.Join(root, "data", "next.db")
if err := os.Symlink(filepath.Join(root, "data", "smail.db"), target); err != nil {
t.Fatal(err)
}
record, token, err := service.Preview(context.Background(), config.DatabaseConfig{Type: config.DatabaseTypeSQLite, LocalRef: "smail.db"}, 1, "next.db")
@@ -267,7 +267,7 @@ func TestSQLiteExecutorReportsOrderedStatuses(t *testing.T) {
if len(statuses) != 2 || statuses[0] != StatusVerifying || statuses[1] != StatusSwitching {
t.Fatalf("statuses = %v, want verifying then switching", statuses)
}
if _, err := os.Stat(filepath.Join(root, "config", "next.db")); err != nil {
if _, err := os.Stat(filepath.Join(root, "data", "next.db")); err != nil {
t.Fatal(err)
}
}
+9 -2
View File
@@ -16,6 +16,8 @@ import (
"runtime"
"strings"
"sync"
"git.pcux.cn/xuans/Smail/utils/runtimepath"
)
const (
@@ -41,8 +43,13 @@ func NewVault(root string) (*Vault, error) {
if strings.TrimSpace(root) == "" {
return nil, ErrVaultUnavailable
}
configDir := filepath.Join(root, "config")
if err := os.MkdirAll(configDir, 0700); err != nil {
for _, name := range []string{"external-email-encryption.key", "external-email-fingerprint.key"} {
if _, err := os.Lstat(filepath.Join(root, "config", name)); err == nil || !os.IsNotExist(err) {
return nil, ErrVaultUnavailable
}
}
configDir, err := runtimepath.Directory(root)
if err != nil {
return nil, ErrVaultUnavailable
}
encryptionKey, err := loadKey(filepath.Join(configDir, "external-email-encryption.key"))
+3 -3
View File
@@ -80,7 +80,7 @@ func GetDatabaseSettings(ctx *context.Context) (string, string, error) {
return "", "", errors.Wrap(err)
}
if configData.DbType == "" && configData.DbDSN == "" {
return config.DBTypeSQLite, config.ROOT_PATH + "./config/smail.db", nil
return config.DBTypeSQLite, config.ROOT_PATH + "./data/smail.db", nil
}
return configData.DbType, configData.DbDSN, nil
}
@@ -98,7 +98,7 @@ func GetDatabaseSettingsDetail(ctx *context.Context) (map[string]string, error)
}
if dbType == config.DBTypeSQLite {
if strings.TrimSpace(result["db_dsn"]) == "" {
result["db_dsn"] = config.ROOT_PATH + "./config/smail.db"
result["db_dsn"] = config.ROOT_PATH + "./data/smail.db"
}
return result, nil
}
@@ -238,7 +238,7 @@ func SetDatabaseSettingsWithOptions(ctx *context.Context, settings DatabaseSetti
}
if dbType == config.DBTypeSQLite {
if dbDSN == "" {
dbDSN = config.ROOT_PATH + "./config/smail.db"
dbDSN = config.ROOT_PATH + "./data/smail.db"
}
if err = prepareSQLiteDatabase(dbDSN); err != nil {
return databaseError("准备 SQLite 数据文件失败", err)
+3 -3
View File
@@ -116,7 +116,7 @@ func SetSSL(sslType, priKey, crtKey string) error {
cfg.SSL = config.SSLConfig{
Management: config.SSLManagementProject,
Mode: config.ManagedSSLModeDefault,
DefaultDirectory: "config/ssl",
DefaultDirectory: "data/ssl",
}
if cfg.SSLType == config.SSLTypeAutoDNS {
cfg.SSL.Challenge = config.SSLChallengeDNS
@@ -190,12 +190,12 @@ func applyManagedSSLReference(cfg *config.Config, reference config.ManagedSSLRef
cfg.SSL = config.SSLConfig{
Management: management,
Mode: reference.Mode,
DefaultDirectory: "config/ssl",
DefaultDirectory: "data/ssl",
CertificateRef: reference.CertificateRef,
PrivateKeyRef: reference.PrivateKeyRef,
}
if reference.Mode == config.ManagedSSLModeUpload {
cfg.SSL.CustomDirectory = "config/ssl/managed/upload"
cfg.SSL.CustomDirectory = "data/ssl/managed/upload"
} else if cfg.SSLType == config.SSLTypeAutoDNS {
cfg.SSL.Challenge = config.SSLChallengeDNS
} else {
+2 -2
View File
@@ -31,7 +31,7 @@ func writeCertificateBundle(cfg *config.Config, privateKey, certificate, issuer
return err
}
defer workspaceRoot.Close()
baseRelative := filepath.Join("config", "ssl")
baseRelative := filepath.Join("data", "ssl")
if err := ensureSecureRootDirectory(workspaceRoot, baseRelative); err != nil {
return err
}
@@ -57,7 +57,7 @@ func writeCertificateBundle(cfg *config.Config, privateKey, certificate, issuer
}
relativePath, err := securefile.ControlledRelativePath(basePath, item.path)
if err != nil {
return errors.New("SSL file path must stay inside config/ssl")
return errors.New("SSL file path must stay inside data/ssl")
}
if _, exists := seen[relativePath]; exists {
return errors.New("SSL file paths must be unique")
+5 -5
View File
@@ -17,7 +17,7 @@ func TestWriteCertificateBundleUsesRestrictedAtomicStorage(t *testing.T) {
root := t.TempDir()
config.ROOT_PATH = root + string(os.PathSeparator)
t.Cleanup(func() { config.ROOT_PATH = oldRoot })
basePath := filepath.Join(root, "config", "ssl")
basePath := filepath.Join(root, "data", "ssl")
cfg := &config.Config{
SSLPrivateKeyPath: filepath.Join(basePath, "private.key"),
SSLPublicKeyPath: filepath.Join(basePath, "public.crt"),
@@ -52,7 +52,7 @@ func TestWriteCertificateBundleUsesRestrictedAtomicStorage(t *testing.T) {
}
}
if runtime.GOOS != "windows" {
for _, directory := range []string{filepath.Join(root, "config"), basePath} {
for _, directory := range []string{filepath.Join(root, "data"), basePath} {
info, err := os.Stat(directory)
if err != nil {
t.Fatal(err)
@@ -79,7 +79,7 @@ func TestWriteCertificateBundleRejectsSymlinkDirectory(t *testing.T) {
root := t.TempDir()
config.ROOT_PATH = root + string(os.PathSeparator)
t.Cleanup(func() { config.ROOT_PATH = oldRoot })
configDirectory := filepath.Join(root, "config")
configDirectory := filepath.Join(root, "data")
if err := os.Mkdir(configDirectory, 0700); err != nil {
t.Fatal(err)
}
@@ -103,7 +103,7 @@ func TestWriteCertificateBundleRejectsSymlinkFile(t *testing.T) {
root := t.TempDir()
config.ROOT_PATH = root + string(os.PathSeparator)
t.Cleanup(func() { config.ROOT_PATH = oldRoot })
basePath := filepath.Join(root, "config", "ssl")
basePath := filepath.Join(root, "data", "ssl")
if err := os.MkdirAll(basePath, 0700); err != nil {
t.Fatal(err)
}
@@ -139,7 +139,7 @@ func TestWriteCertificateBundleRejectsMismatchedPair(t *testing.T) {
root := t.TempDir()
config.ROOT_PATH = root + string(os.PathSeparator)
t.Cleanup(func() { config.ROOT_PATH = oldRoot })
basePath := filepath.Join(root, "config", "ssl")
basePath := filepath.Join(root, "data", "ssl")
cfg := &config.Config{
SSLPrivateKeyPath: filepath.Join(basePath, "private.key"),
SSLPublicKeyPath: filepath.Join(basePath, "public.crt"),
@@ -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 != "config/ssl/managed/upload" {
if cfg.SSL.CustomDirectory != "data/ssl/managed/upload" {
t.Fatalf("自定义受控目录写入错误: %s", cfg.SSL.CustomDirectory)
}
}