反代模式停用自动证书签发续期并完善初始化提示与测试
Security Checks / security (push) Waiting to run

This commit is contained in:
xuans committed 2026-09-06 13:27:06 +08:00
1 parent 7ffb1e751d
commit 369f502c10
20 files changed
+599 -56

No files matched your search

+85
View File
@@ -13,6 +13,91 @@ import (
_ "modernc.org/sqlite"
)
func TestAuditAutomaticSSLPolicy(t *testing.T) {
var empty *Config
if empty.UsesProxyHTTPS() || empty.AutomaticSSLEnabled() {
t.Fatal("空配置不能启用自动证书")
}
for _, mode := range []string{"", HTTPSTLSModeDirect, HTTPSTLSModeProxy, " PROXY "} {
for _, sslType := range []string{"", SSLTypeUser, SSLTypeAutoHTTP, SSLTypeAutoDNS} {
cfg := &Config{TLSMode: mode, SSLType: sslType}
want := (mode == "" || mode == HTTPSTLSModeDirect) && (sslType == SSLTypeAutoHTTP || sslType == SSLTypeAutoDNS)
if cfg.AutomaticSSLEnabled() != want {
t.Fatalf("自动证书策略错误: mode=%q type=%q", mode, sslType)
}
}
}
}
func TestAuditProxySwitchRejectsStaleSSLCommit(t *testing.T) {
previousRoot, previousSnapshot := ROOT_PATH, CurrentConfig()
ROOT_PATH = t.TempDir()
t.Cleanup(func() {
ROOT_PATH = previousRoot
PublishConfigSnapshot(previousSnapshot)
})
expected := &Config{TLSMode: HTTPSTLSModeDirect, SSLType: SSLTypeAutoDNS, HttpsEnabled: 2}
if err := WriteConfig(expected); err != nil {
t.Fatal(err)
}
live := *expected
// 只修改 TLSMode,确保拒绝不是由 HTTPS 开关或域名变化引起。
live.TLSMode = HTTPSTLSModeProxy
if err := WriteConfig(&live); err != nil {
t.Fatal(err)
}
if err := WriteSSLConfig(expected, expected); !errors.Is(err, ErrGenerationConflict) {
t.Fatalf("切换反代后未拒绝旧签发结果: %v", err)
}
stored, err := ReadConfig()
if err != nil || !stored.UsesProxyHTTPS() {
t.Fatal("过期签发改变了反代策略")
}
}
func TestAuditTLSStatusTracksAppliedPolicy(t *testing.T) {
root := t.TempDir()
runtime := validRuntimeConfig()
runtime.Root.HTTP.TLSMode = HTTPSTLSModeDirect
writeRuntimeFixture(t, root, runtime)
manager, err := NewConfigManager(root, ConfigLoaderOptions{Validation: RuntimeValidationOptions{HasSuperAdmin: true, Production: true}})
if err != nil {
t.Fatal(err)
}
actor := authorizedConfigActor()
for _, mode := range []string{HTTPSTLSModeProxy, HTTPSTLSModeDirect} {
current := manager.Snapshot()
next := current.Root
next.HTTP.TLSMode = mode
next.HTTP.HTTPSEnabled = mode == HTTPSTLSModeDirect
next.HTTP.HTTPSPort = 0
if next.HTTP.HTTPSEnabled {
next.HTTP.HTTPSPort = 443
}
next.HTTP.TrustedProxyCIDRs = []string{"127.0.0.1/32"}
payload, err := json.Marshal(next)
if err != nil {
t.Fatal(err)
}
updated, err := manager.Update(context.Background(), UpdateRequest{
Section: SectionRoot, ExpectedGeneration: current.Generation, Payload: payload, Actor: actor,
Confirmation: StepUpConfirmation{Confirmed: true, Method: "recent_auth"},
})
if err != nil {
t.Fatal(err)
}
if manager.Status().TLSMode != current.Root.HTTP.TLSMode {
t.Fatal("未应用的候选不能改变生效模式提示")
}
if _, err := manager.ApplyAuthorized(context.Background(), updated.Generation, actor); err != nil {
t.Fatal(err)
}
if manager.Status().TLSMode != mode {
t.Fatal("状态没有跟随已应用的 HTTPS 模式")
}
}
}
func TestAuditPendingIdentityAndRecovery(t *testing.T) {
root := t.TempDir()
writeRuntimeFixture(t, root, validRuntimeConfig())
+52
View File
@@ -0,0 +1,52 @@
package cron_server
import (
"io"
"net/http"
"strings"
"testing"
"time"
"git.pcux.cn/xuans/Smail/config"
"git.pcux.cn/xuans/Smail/signal"
)
type auditHTTPTransport struct {
calls int
}
func (transport *auditHTTPTransport) RoundTrip(request *http.Request) (*http.Response, error) {
transport.calls++
return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader("ok")), Header: make(http.Header), Request: request}, nil
}
// 代理检查和就绪探测只使用隔离配置,传输层替身阻止访问真实服务。
func TestAuditProxyMaintenanceSkipsNetwork(t *testing.T) {
previousRoot, previousSnapshot := config.ROOT_PATH, config.CurrentConfig()
previousTransport, previousExpiry, previousRestart := http.DefaultTransport, expiredTime, signal.RestartChan
config.ROOT_PATH = t.TempDir()
transport := &auditHTTPTransport{}
http.DefaultTransport = transport
signal.RestartChan = make(chan bool, 1)
expiredTime = time.Time{}
t.Cleanup(func() {
config.ROOT_PATH = previousRoot
config.PublishConfigSnapshot(previousSnapshot)
http.DefaultTransport, expiredTime, signal.RestartChan = previousTransport, previousExpiry, previousRestart
})
for _, sslType := range []string{config.SSLTypeAutoHTTP, config.SSLTypeAutoDNS, config.SSLTypeUser} {
config.PublishConfigSnapshot(&config.Config{TLSMode: config.HTTPSTLSModeProxy, SSLType: sslType, SetupState: config.SetupStateReady})
if waitHTTPReady() {
t.Fatal("反代模式不应探测 HTTP 挑战服务")
}
maintainSSL()
}
if transport.calls != 0 || len(signal.RestartChan) != 0 {
t.Fatal("反代模式触发了网络请求或无证书重启")
}
// 切回直接 HTTPS 后,每轮读取最新策略,而非沿用启动时的分支。
config.PublishConfigSnapshot(&config.Config{TLSMode: config.HTTPSTLSModeDirect, SSLType: config.SSLTypeAutoHTTP, SetupState: config.SetupStateReady})
if !waitHTTPReady() || transport.calls != 1 {
t.Fatal("直接 HTTPS 的 HTTP 就绪探测未恢复")
}
}
+58
View File
@@ -0,0 +1,58 @@
package controllers
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"git.pcux.cn/xuans/Smail/config"
"git.pcux.cn/xuans/Smail/services/access"
appcontext "git.pcux.cn/xuans/Smail/utils/context"
)
func TestAuditConfigStatusIncludesTLSMode(t *testing.T) {
root := t.TempDir()
if err := os.MkdirAll(filepath.Join(root, "config"), 0700); err != nil {
t.Fatal(err)
}
legacy := []byte(`{"domain":"mail.example.test","webDomain":"mail.example.test","dbType":"sqlite","dbDSN":"./config/test.db","isInit":true,"httpPort":8080,"httpsEnabled":2,"tlsMode":"proxy","trustedProxyCidrs":["127.0.0.1/32"]}`)
if err := os.WriteFile(filepath.Join(root, "config", "config.json"), legacy, 0600); err != nil {
t.Fatal(err)
}
validation := config.RuntimeValidationOptions{HasSuperAdmin: true, Production: true}
if _, err := config.MigrateLegacyConfig(root, validation); err != nil {
t.Fatal(err)
}
manager, err := config.NewConfigManager(root, config.ConfigLoaderOptions{Validation: validation})
if err != nil {
t.Fatal(err)
}
previous := config.CurrentManager()
config.SetRuntimeManager(manager)
t.Cleanup(func() { config.SetRuntimeManager(previous) })
for _, role := range []access.Role{access.RoleSuperAdmin, access.RoleUser} {
recorder := httptest.NewRecorder()
ConfigStatus(&appcontext.Context{UserID: 1, Role: role}, recorder, httptest.NewRequest(http.MethodGet, "/api/v1/config/status", nil))
if role == access.RoleUser {
if recorder.Code != http.StatusForbidden {
t.Fatal("增加证书状态字段不能放宽配置读取权限")
}
continue
}
var payload struct {
ErrorNo int `json:"errorNo"`
Data struct {
TLSMode string `json:"tlsMode"`
} `json:"data"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if recorder.Code != http.StatusOK || payload.ErrorNo != 0 || payload.Data.TLSMode != config.HTTPSTLSModeProxy {
t.Fatalf("状态响应缺少生效反代模式: status=%d error=%d mode=%q", recorder.Code, payload.ErrorNo, payload.Data.TLSMode)
}
}
}
+5 -1
View File
@@ -15,6 +15,8 @@ const replacements = {
'backend/utils/address/audit_findings_test.go': 'test/review/address_findings_test.go',
'backend/services/totp/audit_findings_test.go': 'test/review/totp_findings_test.go',
'backend/services/setup/ssl/audit_findings_test.go': 'test/review/ssl_findings_test.go',
'backend/services/setup/ssl/audit_proxy_test.go': 'test/review/ssl_proxy_test.go',
'backend/listen/cron_server/audit_ssl_test.go': 'test/review/cron_ssl_test.go',
'backend/services/setup/audit_findings_test.go': 'test/review/setup_findings_test.go',
'backend/config/audit_findings_test.go': 'test/review/config_findings_test.go',
'backend/services/dbmigration/audit_findings_test.go': 'test/review/dbmigration_findings_test.go',
@@ -27,6 +29,7 @@ const replacements = {
'backend/listen/imap_server/audit_wire_findings_test.go': 'test/review/imap_wire_findings_test.go',
'backend/controllers/audit_findings_test.go': 'test/review/runtime_findings_test.go',
'backend/controllers/audit_controller_findings_test.go': 'test/review/controller_findings_test.go',
'backend/controllers/audit_proxy_test.go': 'test/review/proxy_controller_test.go',
'backend/internal/gopop/audit_findings_test.go': 'test/review/pop3_parser_findings_test.go',
'backend/listen/pop3_server/audit_findings_test.go': 'test/review/pop3_action_findings_test.go',
'backend/dto/parsemail/audit_findings_test.go': 'test/review/message_findings_test.go',
@@ -51,10 +54,11 @@ const totpOnly = process.argv.includes('--totp-only')
const frameworkOnly = process.argv.includes('--framework-only')
const asyncOnly = process.argv.includes('--async-only')
const addressOnly = process.argv.includes('--address-only')
const packages = frameworkOnly ? ['./hooks/framework'] : asyncOnly ? ['./utils/async'] : addressOnly ? ['./utils/address'] : totpOnly ? ['./services/totp'] : sslOnly ? ['./services/setup/ssl'] : setupOnly ? ['./services/setup'] : httpOnly ? ['./listen/http_server'] : controllersOnly ? ['./controllers'] : configOnly ? ['./config'] : migrationOnly ? ['./services/dbmigration'] : pop3Only ? ['./internal/gopop', './listen/pop3_server'] : messageOnly ? [
const packages = frameworkOnly ? ['./hooks/framework'] : asyncOnly ? ['./utils/async'] : addressOnly ? ['./utils/address'] : totpOnly ? ['./services/totp'] : sslOnly ? ['./services/setup/ssl', './listen/cron_server'] : setupOnly ? ['./services/setup'] : httpOnly ? ['./listen/http_server'] : controllersOnly ? ['./controllers'] : configOnly ? ['./config'] : migrationOnly ? ['./services/dbmigration'] : pop3Only ? ['./internal/gopop', './listen/pop3_server'] : messageOnly ? [
'./dto/parsemail', './listen/smtp_server'
] : [
'./res_init',
'./listen/cron_server',
'./hooks/wechat_push',
'./services/dbmigration', './listen/http_server', './services/list', './services/recovery',
'./listen/imap_server', './controllers', './internal/gopop', './listen/pop3_server',
+163
View File
@@ -0,0 +1,163 @@
package ssl
import (
"bytes"
"encoding/json"
"errors"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"git.pcux.cn/xuans/Smail/config"
"git.pcux.cn/xuans/Smail/signal"
)
type proxyBlockedTransport struct {
calls int
}
func (transport *proxyBlockedTransport) RoundTrip(*http.Request) (*http.Response, error) {
transport.calls++
return nil, errors.New("测试禁止外部网络请求")
}
// 旧版及分区配置均只在临时目录中测试,禁止连接真实 ACME 服务。
func TestAuditProxyDisablesAutomaticSSL(t *testing.T) {
for _, sslType := range []string{config.SSLTypeAutoHTTP, config.SSLTypeAutoDNS} {
t.Run(sslType, func(t *testing.T) {
auditSSLRoot(t)
cfg := &config.Config{
TLSMode: config.HTTPSTLSModeProxy, HttpsEnabled: 2,
SSLType: sslType, SetupState: config.SetupStateReady,
Domain: "example.test", WebDomain: "mail.example.test",
}
if err := config.WriteConfig(cfg); err != nil {
t.Fatal(err)
}
path := filepath.Join(config.ROOT_PATH, "config", "config.json")
before, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
transport := &proxyBlockedTransport{}
previousTransport, previousRestart := http.DefaultTransport, signal.RestartChan
http.DefaultTransport = transport
signal.RestartChan = make(chan bool, 1)
t.Cleanup(func() {
http.DefaultTransport, signal.RestartChan = previousTransport, previousRestart
})
selected, err := GetSSL()
if err != nil || selected != config.SSLTypeUser {
t.Fatalf("反代初始化必须选择外部证书: type=%s err=%v", selected, err)
}
if err := SetSSL(sslType, "", ""); !strings.Contains(UserCertificateErrorMessage(err), "反代") {
t.Fatalf("反代模式未拒绝自动证书设置: %v", err)
}
for _, update := range []bool{false, true} {
if err := GenSSL(update); !strings.Contains(UserCertificateErrorMessage(err), "反代") {
t.Fatalf("反代模式未拒绝自动签发: update=%t err=%v", update, err)
}
}
Update(true)
after, err := os.ReadFile(path)
if err != nil || !bytes.Equal(before, after) {
t.Fatal("反代模式改变了已有配置")
}
if transport.calls != 0 || len(signal.RestartChan) != 0 {
t.Fatalf("反代模式触发网络请求或重启: requests=%d", transport.calls)
}
if _, err := os.Stat(filepath.Join(config.ROOT_PATH, "config", "ssl", "account_private.pem")); !os.IsNotExist(err) {
t.Fatalf("反代模式不应生成 ACME 账户密钥: %v", err)
}
})
}
}
func TestAuditProxyCertificateImportPreservesInternalHTTPSDisabled(t *testing.T) {
auditSSLRoot(t)
cfg := &config.Config{
TLSMode: config.HTTPSTLSModeProxy, HttpsEnabled: 2,
Domain: "mail.example.com", WebDomain: "mail.example.com",
}
if err := config.WriteConfig(cfg); err != nil {
t.Fatal(err)
}
key, cert := writeTestCertificate(t, t.TempDir(), 2048)
if err := SetSSL(config.SSLTypeUser, key, cert); err != nil {
t.Fatal(err)
}
stored, err := config.ReadConfig()
if err != nil {
t.Fatal(err)
}
if stored.HttpsEnabled != 2 || !stored.UsesProxyHTTPS() || stored.SSLType != config.SSLTypeUser {
t.Fatal("导入邮件证书改变了反代 HTTPS 策略")
}
if _, err := config.LoadRuntimeTLSCertificate(stored); err != nil {
t.Fatalf("反代模式邮件 TLS 证书必须仍可加载: %v", err)
}
}
func TestAuditPartitionedProxyBlocksIssuance(t *testing.T) {
expected, _ := auditMigratedSSL(t, config.SSLTypeAutoHTTP)
// 保持证书分区不变,只在测试根文件上模拟管理员切换反代。
path := filepath.Join(config.ROOT_PATH, "config", "config.json")
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
// 使用结构化配置读写,避免依赖序列化格式。
var root config.RootConfig
if err := json.Unmarshal(data, &root); err != nil {
t.Fatal(err)
}
root.HTTP.TLSMode = config.HTTPSTLSModeProxy
root.HTTP.HTTPSEnabled = false
root.HTTP.HTTPSPort = 0
root.HTTP.TrustedProxyCIDRs = []string{"127.0.0.1/32"}
data, err = json.Marshal(root)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, data, 0600); err != nil {
t.Fatal(err)
}
loaded, err := config.ReadConfig()
if err != nil {
t.Fatal(err)
}
if loaded.AutomaticSSLEnabled() {
t.Fatal("分区兼容快照仍允许反代自动续期")
}
if err := GenSSL(true); !strings.Contains(UserCertificateErrorMessage(err), "反代") {
t.Fatalf("分区反代未拒绝自动签发: %v", err)
}
resource := auditCertificateChain(t, "imap.example.test", "smtp.imap.example.test", "pop.imap.example.test", "imap.imap.example.test")
if err := writeCertificateFiles(expected, resource.PrivateKey, resource.Certificate, nil); !errors.Is(err, config.ErrGenerationConflict) {
t.Fatalf("分区反代必须拒绝旧签发结果提交: %v", err)
}
// 使用同一临时分区配置,验证转交外部管理后仍可安全导入邮件证书。
directory := t.TempDir()
key, cert := filepath.Join(directory, "private.pem"), filepath.Join(directory, "certificate.pem")
if err := os.WriteFile(key, resource.PrivateKey, 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(cert, resource.Certificate, 0600); err != nil {
t.Fatal(err)
}
if err := SetSSL(config.SSLTypeUser, key, cert); err != nil {
t.Fatal(err)
}
stored, err := config.ReadConfig()
if err != nil {
t.Fatal(err)
}
if !stored.UsesProxyHTTPS() || stored.HttpsEnabled != 2 || stored.AutomaticSSLEnabled() {
t.Fatal("分区证书导入改变了反代策略")
}
if _, err := config.LoadRuntimeTLSCertificate(stored); err != nil {
t.Fatalf("分区配置导入后邮件 TLS 证书无法加载: %v", err)
}
}