补齐反代模式外部证书校验发布与Go续期部署模板
Security Checks / security (push) Waiting to run

This commit is contained in:
xuans committed 2026-10-02 14:45:21 +08:00
1 parent dcfdc3be1a
commit bc50eab30e
6 files changed
+164 -13

No files matched your search

+13 -1
View File
@@ -25,6 +25,8 @@ func run(args []string) error {
runtimeData := flags.Bool("runtime-data", false, "将运行数据迁到 data,保留当前五个配置文件")
historySource := flags.String("deployment-history", "", "停服复制完成后,从原部署导入配置历史并转换证书引用")
exportTLS := flags.String("export-project-tls", "", "将项目托管证书导出为本机 TLS 入口使用的合并 PEM 文件")
publishTLS := flags.String("publish-external-tls", "", "将外部续期证书校验并原子发布为 Nginx 使用的合并 PEM 文件")
externalTLSDirectory := flags.String("external-tls-dir", "", "外部续期目录,包含权限受保护的 smail.crt 和 smail.key")
if err := flags.Parse(args); err != nil {
return err
}
@@ -36,7 +38,7 @@ func run(args []string) error {
return fmt.Errorf("服务根目录无效")
}
if *exportTLS != "" {
if *apply || *runtimeData || *historySource != "" || !filepath.IsAbs(*exportTLS) {
if *apply || *runtimeData || *historySource != "" || *publishTLS != "" || *externalTLSDirectory != "" || !filepath.IsAbs(*exportTLS) {
return fmt.Errorf("证书导出必须单独执行,目标必须是绝对路径")
}
if err := config.ExportProjectTLS(absolute, filepath.Clean(*exportTLS)); err != nil {
@@ -45,6 +47,16 @@ func run(args []string) error {
fmt.Println("项目证书同步检查完成。")
return nil
}
if *publishTLS != "" || *externalTLSDirectory != "" {
if *apply || *runtimeData || *historySource != "" || !filepath.IsAbs(*publishTLS) || !filepath.IsAbs(*externalTLSDirectory) {
return fmt.Errorf("外部证书发布必须单独执行,源目录和目标文件必须同时指定绝对路径")
}
if err := config.PublishExternalTLS(absolute, *externalTLSDirectory, *publishTLS); err != nil {
return fmt.Errorf("外部证书发布失败,原有入口证书保留:%w", err)
}
fmt.Println("外部证书校验及发布完成。")
return nil
}
options := config.RuntimeValidationOptions{HasSuperAdmin: true, Production: true}
if *historySource != "" {
if !*apply || *runtimeData {
+30 -3
View File
@@ -34,6 +34,33 @@ func ExportProjectTLS(root, destination string) error {
return ErrInvalidSSLReference
}
sourceDirectory := filepath.Join(root, "ssl")
return exportTLSBundle(sourceDirectory, filepath.Base(publicPath), filepath.Base(privatePath), destination, validationCertificateDomains(&runtime))
}
// PublishExternalTLS 仅由部署管理员显式提供外部续期目录,不从网页配置读取高权限源路径。
// 外部工具统一使用 smail 文件名;校验失败时不替换入口的有效证书。
func PublishExternalTLS(root, sourceDirectory, destination string) error {
if runtime.GOOS != "linux" {
return errors.New("本机 Nginx 证书同步仅支持 Linux")
}
if !filepath.IsAbs(root) || !filepath.IsAbs(sourceDirectory) || !filepath.IsAbs(destination) {
return ErrUnsafeSSLFile
}
root, sourceDirectory, destination = filepath.Clean(root), filepath.Clean(sourceDirectory), filepath.Clean(destination)
runtime, err := NewConfigLoader(root, ConfigLoaderOptions{Validation: RuntimeValidationOptions{HasSuperAdmin: true, Production: true}}).Load()
if err != nil {
return ErrInvalidSSL
}
if runtime.Root.HTTP.TLSMode != HTTPSTLSModeProxy || EffectiveSSLManagement(runtime.SSL.TLS) == SSLManagementProject {
return ErrInvalidSSL
}
if filepath.Dir(destination) == sourceDirectory {
return ErrUnsafeSSLFile
}
return exportTLSBundle(sourceDirectory, "smail.crt", "smail.key", destination, validationCertificateDomains(&runtime))
}
func exportTLSBundle(sourceDirectory, certificateName, privateKeyName, destination string, domains []string) error {
resolvedSource, err := filepath.EvalSymlinks(sourceDirectory)
if err != nil || resolvedSource != sourceDirectory {
return ErrUnsafeSSLFile
@@ -71,15 +98,15 @@ func ExportProjectTLS(root, destination string) error {
}
return data, nil
}
certificate, err := read(filepath.Base(publicPath))
certificate, err := read(certificateName)
if err != nil {
return err
}
privateKey, err := read(filepath.Base(privatePath))
privateKey, err := read(privateKeyName)
if err != nil {
return err
}
if err := validateSSLMaterial(privateKey, certificate, nil, validationCertificateDomains(&runtime)); err != nil {
if err := validateSSLMaterial(privateKey, certificate, nil, domains); err != nil {
return err
}
combined := append(append(append([]byte{}, certificate...), '\n'), privateKey...)
+82
View File
@@ -10,6 +10,88 @@ import (
"time"
)
func TestPublishExternalTLSValidatesBeforeReplacingBundle(t *testing.T) {
if runtime.GOOS != "linux" {
if err := PublishExternalTLS(t.TempDir(), t.TempDir(), filepath.Join(t.TempDir(), "tls.pem")); err == nil {
t.Fatal("unsupported platform allowed publishing a private key")
}
t.Skip("Linux Nginx publishing requires POSIX permission checks")
}
root, source, output := t.TempDir(), t.TempDir(), t.TempDir()
for _, directory := range []string{source, output} {
if err := os.Chmod(directory, 0700); err != nil {
t.Fatal(err)
}
}
candidate := validRuntimeConfig()
candidate.Root.Domains = DomainConfig{Primary: "example.com", Web: "web.example.com", Accepted: []string{"example.com"}}
candidate.Root.HTTP = HTTPConfig{Port: 15184, TLSMode: HTTPSTLSModeProxy, TrustedProxyCIDRs: []string{"127.0.0.1/32"}}
candidate.SSL.TLS = SSLConfig{Management: SSLManagementWebServer, Mode: ManagedSSLModeUpload, CustomDirectory: "ssl"}
writeRuntimeFixture(t, root, candidate)
key, certificate := testManagedCertificate(t, "example.com", time.Now().Add(-time.Hour), time.Now().Add(time.Hour), 2048, "*.example.com")
write := func(name string, data []byte) {
t.Helper()
if err := os.WriteFile(filepath.Join(source, name), data, 0600); err != nil {
t.Fatal(err)
}
}
write("smail.crt", certificate)
write("smail.key", key)
destination := filepath.Join(output, "tls.pem")
if err := PublishExternalTLS(root, source, 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)
}
before, err := os.Stat(destination)
if err != nil || before.Mode().Perm() != 0600 {
t.Fatal("published bundle must be private")
}
if err := PublishExternalTLS(root, source, destination); err != nil {
t.Fatal(err)
}
after, _ := os.Stat(destination)
if !os.SameFile(before, after) {
t.Fatal("unchanged certificate must not be rewritten")
}
assertRejected := func() {
t.Helper()
if err := PublishExternalTLS(root, source, destination); err == nil {
t.Fatal("invalid publication accepted")
}
preserved, err := os.ReadFile(destination)
if err != nil || !bytes.Equal(bundle, preserved) {
t.Fatal("failed publication replaced the previous bundle")
}
}
write("smail.key", []byte("invalid"))
assertRejected()
wrongKey, wrongCertificate := testManagedCertificate(t, "other.example", time.Now().Add(-time.Hour), time.Now().Add(time.Hour), 2048)
write("smail.key", wrongKey)
write("smail.crt", wrongCertificate)
assertRejected()
write("smail.key", key)
write("smail.crt", certificate)
if err := os.Chmod(filepath.Join(source, "smail.key"), 0644); err != nil {
t.Fatal(err)
}
assertRejected()
if err := os.Chmod(filepath.Join(source, "smail.key"), 0600); err != nil {
t.Fatal(err)
}
if err := PublishExternalTLS(root, source, filepath.Join(source, "smail.crt")); err == nil {
t.Fatal("source overwrite allowed")
}
candidate.Root.HTTP.TLSMode = HTTPSTLSModeDirect
writeRuntimeFixture(t, root, candidate)
assertRejected()
}
func TestExportProjectTLSKeepsOldBundleOnInvalidInput(t *testing.T) {
if runtime.GOOS != "linux" {
if err := ExportProjectTLS(t.TempDir(), filepath.Join(t.TempDir(), "tls.pem")); err == nil {