保存内置DNS续期与证书同步接续修复前基线

This commit is contained in:
xuans committed 2026-09-20 04:39:25 +08:00
1 parent 7fec05650f
commit d6ea80a040
23 files changed
+704 -13

No files matched your search

+1 -1
View File
@@ -97,7 +97,7 @@ func flattenAudit(result map[string]any, path string, value any) {
func auditSensitive(path string) bool {
name := strings.ToLower(path[strings.LastIndex(path, ".")+1:])
for _, word := range []string{"password", "secret", "token", "apikey", "api_key", "credential", "ciphertext", "authorization", "cookie"} {
for _, word := range []string{"password", "secret", "token", "apikey", "api_key", "accesskey", "credential", "ciphertext", "authorization", "cookie"} {
if strings.Contains(name, word) {
return true
}
+22 -2
View File
@@ -931,11 +931,20 @@ func applySectionPayload(current RuntimeConfig, section Section, payload json.Ra
}
candidate.Email.Policy.LoginVerificationPolicy = candidate.SMTP.Relay.LoginPolicy
case SectionSSL:
var value SSLSectionConfig
var value struct {
SSLSectionConfig
DNSAccessKeyStatus json.RawMessage `json:"dnsAccessKeyStatus"`
DNSSecretKeyStatus json.RawMessage `json:"dnsSecretKeyStatus"`
}
if err := ParseStrict(payload, &value); err != nil {
return RuntimeConfig{}, err
}
candidate.SSL = value
if storedSecretHasMaterial(value.TLS.DNSAccessKey) || storedSecretHasMaterial(value.TLS.DNSSecretKey) {
return RuntimeConfig{}, ErrInvalidSecretChange
}
value.TLS.DNSAccessKey = current.SSL.TLS.DNSAccessKey
value.TLS.DNSSecretKey = current.SSL.TLS.DNSSecretKey
candidate.SSL = value.SSLSectionConfig
case SectionPlugins:
var value PluginsSectionConfig
if err := ParseStrict(payload, &value); err != nil {
@@ -1018,6 +1027,17 @@ func applySecretChanges(candidate *RuntimeConfig, section Section, changes map[s
return err
}
candidate.SMTP.Relay.Password = stored
case section == SectionSSL && (name == "tls.dnsAccessKey" || name == "tls.dnsSecretKey"):
target := &candidate.SSL.TLS.DNSAccessKey
if name == "tls.dnsSecretKey" {
target = &candidate.SSL.TLS.DNSSecretKey
}
required := candidate.SSL.TLS.DNSProvider != ""
stored, err := ApplySecretChange(vault, *target, change, SecretPolicy{Required: required, AllowClear: !required, MaxLength: 4096}, now)
if err != nil {
return err
}
*target = stored
default:
return ErrInvalidSecretChange
}
+4
View File
@@ -113,6 +113,10 @@ type SSLConfig struct {
PrivateKeyRef string `json:"privateKeyRef,omitempty"`
PreviousCertificateRef string `json:"previousCertificateRef,omitempty"`
PreviousPrivateKeyRef string `json:"previousPrivateKeyRef,omitempty"`
DNSProvider string `json:"dnsProvider,omitempty"`
DNSZone string `json:"dnsZone,omitempty"`
DNSAccessKey StoredSecret `json:"dnsAccessKey,omitempty"`
DNSSecretKey StoredSecret `json:"dnsSecretKey,omitempty"`
}
type PluginConfig struct {
+6
View File
@@ -55,6 +55,12 @@ func ValidateRuntimeConfig(runtime RuntimeConfig, options RuntimeValidationOptio
if err := validateDomains(runtime.Root.Domains); err != nil {
return err
}
if tls := runtime.SSL.TLS; tls.DNSProvider != "" && tls.DNSZone != "" {
primary := runtime.Root.Domains.Primary
if primary != tls.DNSZone && !strings.HasSuffix(primary, "."+tls.DNSZone) {
return ErrInvalidSSL
}
}
if err := validateMailListeners(runtime.SMTP, runtime.Email); err != nil {
return err
}
+1 -1
View File
@@ -145,7 +145,7 @@ func OpenStoredSecret(vault *credential.Vault, stored StoredSecret) (string, err
// ValidateRuntimeSecrets 验证运行时配置中的持久化 Secret 可以由当前密钥解密。
func ValidateRuntimeSecrets(vault *credential.Vault, runtime RuntimeConfig) error {
for _, stored := range []StoredSecret{runtime.Root.Database.Password, runtime.SMTP.Relay.Password} {
for _, stored := range []StoredSecret{runtime.Root.Database.Password, runtime.SMTP.Relay.Password, runtime.SSL.TLS.DNSAccessKey, runtime.SSL.TLS.DNSSecretKey} {
if !stored.Configured() {
continue
}
+4
View File
@@ -31,6 +31,10 @@ var sensitiveFields = []SensitiveField{
{Path: "plugins.*.secret", Policy: PersistenceEncryptedOnly, Description: "插件 Secret"},
{Path: "plugins.*.api_key", Policy: PersistenceEncryptedOnly, Description: "插件 API 密钥"},
{Path: "ssl.private_key", Policy: PersistenceReferenceOnly, Description: "SSL 私钥材料"},
{Path: "ssl.tls.dnsAccessKey", Policy: PersistenceEncryptedOnly, Description: "DNS 服务商访问凭据"},
{Path: "ssl.tls.dnsSecretKey", Policy: PersistenceEncryptedOnly, Description: "DNS 服务商访问密钥"},
{Path: "tls.dnsAccessKey", Policy: PersistenceEncryptedOnly, Description: "DNS 服务商访问凭据"},
{Path: "tls.dnsSecretKey", Policy: PersistenceEncryptedOnly, Description: "DNS 服务商访问密钥"},
{Path: "security.encryption_master_key", Policy: PersistenceReferenceOnly, Description: "配置加密主密钥"},
{Path: "security.question_answer", Policy: PersistenceEncryptedOnly, Description: "密保答案原文"},
{Path: "security.offline_recovery_code", Policy: PersistenceMemoryOnly, Description: "离线恢复码原文"},
+43
View File
@@ -0,0 +1,43 @@
package config
import "git.pcux.cn/xuans/Smail/utils/credential"
const DNSProviderAliDNS = "alidns"
func validateDNSProvider(ssl SSLConfig) error {
if ssl.DNSProvider != "" && ssl.DNSProvider != DNSProviderAliDNS {
return ErrInvalidSSL
}
if ssl.DNSZone != "" {
domain, err := normalizeConfigDomain(ssl.DNSZone)
if err != nil || domain != ssl.DNSZone {
return ErrInvalidSSL
}
}
for _, stored := range []StoredSecret{ssl.DNSAccessKey, ssl.DNSSecretKey} {
if err := ValidateStoredSecret(stored, ssl.DNSProvider != ""); err != nil {
return ErrInvalidSSL
}
}
return nil
}
// DNSProviderCredentials 只在签发进程内解密,调用方不得记录返回值。
func DNSProviderCredentials(ssl SSLConfig) (string, string, error) {
if ssl.DNSProvider != DNSProviderAliDNS || validateDNSProvider(ssl) != nil {
return "", "", ErrSecretUnavailable
}
vault, err := credential.NewVault(ROOT_PATH)
if err != nil {
return "", "", ErrSecretUnavailable
}
accessKey, err := OpenStoredSecret(vault, ssl.DNSAccessKey)
if err != nil {
return "", "", ErrSecretUnavailable
}
secretKey, err := OpenStoredSecret(vault, ssl.DNSSecretKey)
if err != nil {
return "", "", ErrSecretUnavailable
}
return accessKey, secretKey, nil
}
+51
View File
@@ -0,0 +1,51 @@
package config
import (
"encoding/json"
"errors"
"strings"
"testing"
"git.pcux.cn/xuans/Smail/utils/credential"
)
func TestDNSCredentialsEncryptedPreservedAndRedacted(t *testing.T) {
root := t.TempDir()
previousRoot := ROOT_PATH
ROOT_PATH = root
t.Cleanup(func() { ROOT_PATH = previousRoot })
vault, err := credential.NewVault(root)
if err != nil { t.Fatal(err) }
before := validRuntimeConfig()
candidate := cloneRuntimeConfig(before)
candidate.SSL.TLS.DNSProvider = DNSProviderAliDNS
changes := map[string]SecretChange{
"tls.dnsAccessKey": {Operation: SecretReplace, Value: &SecretInput{Plaintext: "dns-access-fixture"}},
"tls.dnsSecretKey": {Operation: SecretReplace, Value: &SecretInput{Plaintext: "dns-secret-fixture"}},
}
if err := applySecretChanges(&candidate, SectionSSL, changes, vault); err != nil { t.Fatal(err) }
if err := validateDNSProvider(candidate.SSL.TLS); err != nil { t.Fatal(err) }
if err := ValidateRuntimeSecrets(vault, candidate); err != nil { t.Fatal(err) }
access, secret, err := DNSProviderCredentials(candidate.SSL.TLS)
if err != nil || access != "dns-access-fixture" || secret != "dns-secret-fixture" { t.Fatal("DNS credentials did not round trip through vault") }
data, _ := json.Marshal(candidate)
for _, value := range []string{access, secret} { if strings.Contains(string(data), value) { t.Fatal("plaintext persisted") } }
audit, _ := json.Marshal(AuditChanges(before, candidate))
public, _ := json.Marshal(RedactPublicValue(candidate.SSL))
for _, data := range [][]byte{audit, public} {
for _, value := range []string{access, secret, candidate.SSL.TLS.DNSAccessKey.Ciphertext, candidate.SSL.TLS.DNSSecretKey.Ciphertext} {
if strings.Contains(string(data), value) { t.Fatal("DNS secret leaked into audit or public view") }
}
}
section := candidate.SSL
section.TLS.DNSAccessKey, section.TLS.DNSSecretKey = StoredSecret{}, StoredSecret{}
payload, _ := json.Marshal(section)
kept, err := applySectionPayload(candidate, SectionSSL, payload, nil, vault)
if err != nil || kept.SSL.TLS.DNSAccessKey != candidate.SSL.TLS.DNSAccessKey || kept.SSL.TLS.DNSSecretKey != candidate.SSL.TLS.DNSSecretKey { t.Fatal("public edit lost stored DNS credentials") }
payload, _ = json.Marshal(candidate.SSL)
if _, err := applySectionPayload(candidate, SectionSSL, payload, nil, vault); !errors.Is(err, ErrInvalidSecretChange) { t.Fatal("direct stored-secret injection accepted") }
clear := map[string]SecretChange{"tls.dnsSecretKey": {Operation: SecretClear, Confirmed: true}}
if err := applySecretChanges(&candidate, SectionSSL, clear, vault); !errors.Is(err, ErrSecretClearDenied) { t.Fatal("enabled DNS provider allowed clearing its secret") }
candidate.SSL.TLS.DNSProvider = ""
if err := applySecretChanges(&candidate, SectionSSL, clear, vault); err != nil { t.Fatal(err) }
}
+68
View File
@@ -0,0 +1,68 @@
package config
import (
"bytes"
"io"
"os"
"path/filepath"
"git.pcux.cn/xuans/Smail/utils/atomicfile"
)
// ExportProjectTLS 为本机 TLS 入口导出一个原子更新的证书私钥合并文件。
// 仅接受项目生成的平铺证书;不允许高权限调用者按配置读取任意服务器路径。
func ExportProjectTLS(root, destination string) error {
runtime, err := NewConfigLoader(root, ConfigLoaderOptions{Validation: RuntimeValidationOptions{HasSuperAdmin: true, Production: true}}).Load()
if err != nil {
return ErrInvalidSSL
}
if EffectiveSSLManagement(runtime.SSL.TLS) != SSLManagementProject || runtime.Root.HTTP.TLSMode == HTTPSTLSModeProxy {
return nil
}
publicPath := filepath.Join(root, filepath.FromSlash(runtime.SSL.TLS.CertificateRef))
privatePath := filepath.Join(root, filepath.FromSlash(runtime.SSL.TLS.PrivateKeyRef))
if !flatSSLPair(root, publicPath, privatePath) {
return ErrInvalidSSLReference
}
sourceDirectory := filepath.Join(root, "ssl")
resolvedSource, err := filepath.EvalSymlinks(sourceDirectory)
if err != nil || resolvedSource != sourceDirectory { return ErrUnsafeSSLFile }
storage, err := os.OpenRoot(sourceDirectory)
if err != nil { return ErrUnsafeSSLFile }
defer storage.Close()
read := func(name string) ([]byte, error) {
info, err := storage.Lstat(name)
if err != nil || !info.Mode().IsRegular() || info.Size() > maxManagedSSLFileSize || info.Mode().Perm() & 0077 != 0 { return nil, ErrUnsafeSSLFile }
file, err := storage.Open(name)
if err != nil { return nil, ErrUnsafeSSLFile }
defer file.Close()
opened, err := file.Stat()
if err != nil || !os.SameFile(info, opened) { return nil, ErrUnsafeSSLFile }
data, err := io.ReadAll(io.LimitReader(file, maxManagedSSLFileSize+1))
if err != nil || len(data) > maxManagedSSLFileSize { return nil, ErrUnsafeSSLFile }
return data, nil
}
certificate, err := read(filepath.Base(publicPath))
if err != nil { return err }
privateKey, err := read(filepath.Base(privatePath))
if err != nil { return err }
if err := validateSSLMaterial(privateKey, certificate, nil, validationCertificateDomains(&runtime)); err != nil { return err }
combined := append(append(append([]byte{}, certificate...), '\n'), privateKey...)
// 输出目录由部署管理员创建,拒绝符号链接和其他用户可写目录。
directory := filepath.Dir(destination)
resolved, err := filepath.EvalSymlinks(directory)
if err != nil || resolved != directory { return ErrUnsafeSSLFile }
info, err := os.Stat(directory)
if err != nil || !info.IsDir() || info.Mode().Perm() & 0022 != 0 { return ErrUnsafeSSLFile }
output, err := os.OpenRoot(directory)
if err != nil { return ErrUnsafeSSLFile }
defer output.Close()
name := filepath.Base(destination)
if info, err := output.Lstat(name); err == nil {
if !info.Mode().IsRegular() || info.Mode().Perm() & 0077 != 0 { return ErrUnsafeSSLFile }
previous, err := output.ReadFile(name)
if err != nil { return ErrUnsafeSSLFile }
if bytes.Equal(previous, combined) { return nil }
} else if !os.IsNotExist(err) { return ErrUnsafeSSLFile }
return atomicfile.WriteRoot(output, name, combined, 0600)
}
+45
View File
@@ -0,0 +1,45 @@
package config
import (
"bytes"
"crypto/tls"
"os"
"path/filepath"
"testing"
"time"
)
func TestExportProjectTLSKeepsOldBundleOnInvalidInput(t *testing.T) {
root := t.TempDir()
outputDirectory := t.TempDir()
if err := os.Chmod(outputDirectory, 0700); err != nil { t.Fatal(err) }
destination := filepath.Join(outputDirectory, "tls.pem")
runtime := validRuntimeConfig()
runtime.Root.Domains = DomainConfig{Primary: "example.com", Web: "web.example.com", Accepted: []string{"example.com"}}
key, certificate := testManagedCertificate(t, "example.com", time.Now().Add(-time.Hour), time.Now().Add(time.Hour), 2048, "*.example.com")
ref, err := stageFlatSSLAtRoot(root, ManagedSSLModeDefault, key, certificate, nil, nil)
if err != nil { t.Fatal(err) }
defer releaseManagedSSL(root, SSLConfig{CertificateRef: ref.CertificateRef})
runtime.SSL.TLS = SSLConfig{Management: SSLManagementProject, Challenge: SSLChallengeDNS, Mode: ManagedSSLModeDefault, DefaultDirectory: "ssl", CertificateRef: ref.CertificateRef, PrivateKeyRef: ref.PrivateKeyRef}
writeRuntimeFixture(t, root, runtime)
if err := ExportProjectTLS(root, destination); err != nil { t.Fatal(err) }
bundle, err := os.ReadFile(destination)
if err != nil { t.Fatal(err) }
if _, err := tls.X509KeyPair(bundle, bundle); err != nil { t.Fatal(err) }
if err := ExportProjectTLS(root, destination); err != nil { t.Fatal(err) }
if err := os.WriteFile(ref.PrivateKeyPath, []byte("invalid"), 0600); err != nil { t.Fatal(err) }
if err := ExportProjectTLS(root, destination); err == nil { t.Fatal("invalid key was exported") }
preserved, _ := os.ReadFile(destination)
if !bytes.Equal(bundle, preserved) { t.Fatal("failed export replaced valid bundle") }
runtime.SSL.TLS.CertificateRef = "ssl/unmanaged.crt"
runtime.SSL.TLS.PrivateKeyRef = "ssl/unmanaged.key"
writeRuntimeFixture(t, root, runtime)
if err := ExportProjectTLS(root, destination); err == nil { t.Fatal("unmanaged input accepted") }
for _, mode := range []string{SSLManagementCustom, SSLManagementWebServer} {
runtime.SSL.TLS.Management = mode
writeRuntimeFixture(t, root, runtime)
if err := ExportProjectTLS(root, destination); err != nil { t.Fatal(err) }
preserved, _ := os.ReadFile(destination)
if !bytes.Equal(bundle, preserved) { t.Fatal("external mode changed exported bundle") }
}
}
+3
View File
@@ -173,6 +173,9 @@ func smtpRelayConfigured(smtp SMTPConfig) bool {
}
func validateSSL(ssl SSLConfig) error {
if err := validateDNSProvider(ssl); err != nil {
return err
}
if (ssl.PreviousCertificateRef == "") != (ssl.PreviousPrivateKeyRef == "") {
return ErrInvalidSSL
}