整改基线:封存公网端口分离与远程后端回归候选
Security Checks / security (push) Waiting to run

This commit is contained in:
xuans committed 2026-09-18 01:05:50 +08:00
1 parent a4280e7abc
commit d193324e6d
23 files changed
+338 -43

No files matched your search

+1
View File
@@ -44,6 +44,7 @@ type Config struct {
HttpPort int `json:"httpPort"` //http服务端口设置,默认80
HttpsPort int `json:"httpsPort"` //https服务端口,默认443
TLSMode string `json:"tlsMode,omitempty"`
PublicHTTPSPort int `json:"publicHttpsPort,omitempty"`
TrustedProxyCIDRs []string `json:"trustedProxyCidrs,omitempty"`
WeChatPushAppId string `json:"weChatPushAppId"`
WeChatPushSecret string `json:"weChatPushSecret"`
+3
View File
@@ -61,6 +61,7 @@ type legacyMigrationConfig struct {
SpamFilterLevel int `json:"spamFilterLevel"`
HttpPort int `json:"httpPort"`
HttpsPort int `json:"httpsPort"`
PublicHTTPSPort int `json:"publicHttpsPort"`
TLSMode string `json:"tlsMode"`
TrustedProxyCIDRs []string `json:"trustedProxyCidrs"`
WeChatPushAppID string `json:"weChatPushAppId"`
@@ -92,6 +93,7 @@ var legacyMigrationKnownFields = map[string]struct{}{
"logLevel": {}, "domain": {}, "domains": {}, "webDomain": {}, "adminRecoveryDomain": {}, "accessHosts": {},
"dkimPrivateKeyPath": {}, "sslType": {}, "SSLPrivateKeyPath": {}, "SSLPublicKeyPath": {},
"dbDSN": {}, "dbType": {}, "httpsEnabled": {}, "spamFilterLevel": {}, "httpPort": {}, "httpsPort": {}, "tlsMode": {}, "trustedProxyCidrs": {},
"publicHttpsPort": {},
"weChatPushAppId": {}, "weChatPushSecret": {}, "weChatPushTemplateId": {}, "weChatPushUserId": {},
"tgBotToken": {}, "tgChatId": {}, "isInit": {}, "setupState": {}, "webPushUrl": {}, "webPushToken": {},
"smtpHost": {}, "smtpPort": {}, "smtpUsername": {}, "smtpPassword": {}, "smtpSecurity": {}, "smtpFrom": {},
@@ -517,6 +519,7 @@ func legacyRuntimeConfig(root string, legacy legacyMigrationConfig) (RuntimeConf
HTTP: HTTPConfig{
Port: legacy.HttpPort,
HTTPSPort: httpsPort,
PublicHTTPSPort: legacy.PublicHTTPSPort,
HTTPSEnabled: httpsEnabled,
TLSMode: tlsMode,
TrustedProxyCIDRs: append([]string(nil), legacy.TrustedProxyCIDRs...),
+4
View File
@@ -43,6 +43,7 @@ func TestMigrateLegacyConfigPreservesBackupAndLoadsPartitions(t *testing.T) {
"httpsEnabled": 1,
"httpPort": 80,
"httpsPort": 443,
"publicHttpsPort": 9443,
"weChatPushAppId": "app-id",
"weChatPushSecret": "wechat-secret",
"weChatPushTemplateId": "template-id",
@@ -79,6 +80,9 @@ func TestMigrateLegacyConfigPreservesBackupAndLoadsPartitions(t *testing.T) {
if runtime.Root.Database.LocalRef != "smail.db" || runtime.Plugins.Plugins["wechat_push"].Secret.Ciphertext == "" {
t.Fatalf("unexpected migrated runtime: %+v", runtime)
}
if runtime.Root.HTTP.PublicHTTPSPort != 9443 || runtime.Root.HTTP.HTTPSPort != 443 {
t.Fatal("旧配置迁移丢失公网端口或修改了内部监听端口")
}
manager, err := NewConfigManager(root, ConfigLoaderOptions{Validation: RuntimeValidationOptions{HasSuperAdmin: true, Production: true}})
if err != nil {
t.Fatal(err)
@@ -58,6 +58,7 @@ func runtimeCompatibility(runtime RuntimeConfig) (*Config, error) {
IsInit: runtime.SetupState == SetupStateReady,
HttpPort: root.HTTP.Port, HttpsPort: root.HTTP.HTTPSPort,
HttpsEnabled: 2, TLSMode: root.HTTP.TLSMode,
PublicHTTPSPort: root.HTTP.PublicHTTPSPort,
TrustedProxyCIDRs: append([]string(nil), root.HTTP.TrustedProxyCIDRs...),
DkimPrivateKeyPath: filepath.Join(runtimepath.DKIMDirectory(ROOT_PATH), "dkim.priv"),
SSLType: SSLTypeUser,
@@ -59,6 +59,7 @@ func TestPartitionedCompatibilityStartupAndWriteProtection(t *testing.T) {
"dbType": "sqlite", "dbDSN": "./config/existing.db", "isInit": true,
"sslType": "1", "SSLPublicKeyPath": "./config/ssl/site.crt", "SSLPrivateKeyPath": "./config/ssl/site.key",
"httpPort": 80, "httpsPort": 443, "httpsEnabled": 1,
"publicHttpsPort": 9443,
})
if _, err := MigrateLegacyConfig(root, RuntimeValidationOptions{HasSuperAdmin: true, Production: true}); err != nil {
t.Fatal(err)
@@ -73,6 +74,9 @@ func TestPartitionedCompatibilityStartupAndWriteProtection(t *testing.T) {
t.Fatal(err)
}
cfg := CurrentConfig()
if cfg.PublicHTTPSPort != 9443 || cfg.HttpsPort != 443 {
t.Fatal("分区启动兼容快照丢失公网或内部端口")
}
if !cfg.IsSetupReady() || cfg.DbType != DBTypeSQLite || cfg.DbDSN != filepath.Join(root, "data", "existing.db") {
t.Fatal("partitioned startup lost initialization or database identity")
}
+14
View File
@@ -0,0 +1,14 @@
package config
// ResolvePublicHTTPSPort 只从受控配置确定公网端口,不改变内部监听端口。
// 未设置时保留直连端口及 HTTP 反代模式的 443 默认值;非法显式值交由调用方拒绝。
func ResolvePublicHTTPSPort(value HTTPConfig) int {
if value.PublicHTTPSPort != 0 {
return value.PublicHTTPSPort
}
resolved := ResolveHTTPPortDefaults(value, 0)
if resolved.TLSMode == HTTPSTLSModeProxy {
return 443
}
return resolved.HTTPSPort
}
+101
View File
@@ -0,0 +1,101 @@
package config
import (
"encoding/json"
"testing"
)
func TestResolvePublicHTTPSPort(t *testing.T) {
t.Setenv("SMAIL_HTTP_TLS_MODE_OVERRIDE", "")
t.Setenv("SMAIL_HTTPS_PORT", "")
cases := []struct {
name string
config HTTPConfig
want int
}{
{"default direct", HTTPConfig{}, 443},
{"custom direct", HTTPConfig{HTTPSPort: 8443}, 8443},
{"https upstream", HTTPConfig{HTTPSPort: 8002, PublicHTTPSPort: 443}, 443},
{"custom public", HTTPConfig{HTTPSPort: 8002, PublicHTTPSPort: 9443}, 9443},
{"http upstream", HTTPConfig{TLSMode: HTTPSTLSModeProxy}, 443},
{"custom http upstream", HTTPConfig{TLSMode: HTTPSTLSModeProxy, PublicHTTPSPort: 9443}, 9443},
{"invalid negative", HTTPConfig{PublicHTTPSPort: -1}, -1},
{"invalid upper bound", HTTPConfig{PublicHTTPSPort: 65536}, 65536},
}
for _, test := range cases {
t.Run(test.name, func(t *testing.T) {
if got := ResolvePublicHTTPSPort(test.config); got != test.want {
t.Fatalf("公网端口为 %d,预期 %d", got, test.want)
}
})
}
}
func TestPublicHTTPSPortValidationAndSerialization(t *testing.T) {
for _, port := range []int{0, 1, 443, 8002, 65535} {
value := HTTPConfig{Port: 8001, HTTPSPort: 8002, HTTPSEnabled: true, PublicHTTPSPort: port}
if err := validateHTTP(value); err != nil {
t.Fatal(err)
}
// 公网端口不是当前进程监听端口,不能参与本机端口冲突检查。
if err := validateRuntimePorts(value, MailPorts{}); err != nil {
t.Fatal(err)
}
data, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
var restored HTTPConfig
if err := ParseStrict(data, &restored); err != nil {
t.Fatal(err)
}
if restored.PublicHTTPSPort != port || restored.HTTPSPort != 8002 {
t.Fatalf("序列化丢失公网或内部端口:%s", data)
}
}
for _, port := range []int{-1, 65536} {
if validateHTTP(HTTPConfig{PublicHTTPSPort: port}) == nil {
t.Fatalf("接受了非法公网端口 %d", port)
}
}
}
func TestPublicHTTPSPortRuntimeAccess(t *testing.T) {
oldInstance, oldSnapshot, oldManager := Instance, CurrentConfig(), CurrentManager()
t.Cleanup(func() {
Instance = oldInstance
PublishConfigSnapshot(oldSnapshot)
SetRuntimeManager(oldManager)
})
SetRuntimeManager(nil)
PublishConfigSnapshot(&Config{HttpPort: 8001, HttpsPort: 8002, PublicHTTPSPort: 443})
if got := CurrentHTTPConfig(); got.PublicHTTPSPort != 443 || got.HTTPSPort != 8002 {
t.Fatalf("旧配置运行时映射丢失端口:%+v", got)
}
runtime := validRuntimeConfig()
runtime.Root.HTTP = HTTPConfig{Port: 8001, HTTPSPort: 8002, HTTPSEnabled: true, PublicHTTPSPort: 9443}
SetRuntimeManager(&ConfigManager{snapshots: runtimeAccessSnapshotStore{runtime: runtime}})
if got := CurrentHTTPConfig(); got.PublicHTTPSPort != 9443 || got.HTTPSPort != 8002 {
t.Fatalf("分区配置运行时映射丢失端口:%+v", got)
}
}
func TestWebAuthnUsesPublicHTTPSPort(t *testing.T) {
root := RootConfig{Domains: DomainConfig{Web: "mail.example.com"}, HTTP: HTTPConfig{HTTPSPort: 8002, PublicHTTPSPort: 443}}
for _, test := range []struct {
port int
want string
}{{443, "https://mail.example.com"}, {9443, "https://mail.example.com:9443"}, {0, "https://mail.example.com:8002"}} {
root.HTTP.PublicHTTPSPort = test.port
security, err := ResolveWebAuthnSecurity(root)
if err != nil || len(security.WebAuthnRPOrigins) != 1 || security.WebAuthnRPOrigins[0] != test.want {
t.Fatalf("安全密钥默认来源不匹配:%+v,%v", security, err)
}
}
root.HTTP.PublicHTTPSPort = 443
root.Security.WebAuthnRPOrigins = []string{"https://mail.example.com:9443"}
security, err := ResolveWebAuthnSecurity(root)
if err != nil || security.WebAuthnRPOrigins[0] != root.Security.WebAuthnRPOrigins[0] {
t.Fatal("公网端口覆盖了显式配置的安全密钥来源")
}
}
+1
View File
@@ -68,6 +68,7 @@ func CurrentHTTPConfig() HTTPConfig {
return ResolveHTTPPortDefaults(HTTPConfig{
Port: cfg.HttpPort,
HTTPSPort: cfg.HttpsPort,
PublicHTTPSPort: cfg.PublicHTTPSPort,
HTTPSEnabled: cfg.HttpsEnabled != 2,
TLSMode: mode,
TrustedProxyCIDRs: append([]string(nil), cfg.TrustedProxyCIDRs...),
+1
View File
@@ -45,6 +45,7 @@ type DomainConfig struct {
type HTTPConfig struct {
Port int `json:"port,omitempty"`
HTTPSPort int `json:"httpsPort,omitempty"`
PublicHTTPSPort int `json:"publicHttpsPort,omitempty"`
HTTPSEnabled bool `json:"httpsEnabled"`
TLSMode string `json:"tlsMode,omitempty"`
TrustedProxyCIDRs []string `json:"trustedProxyCidrs,omitempty"`
+3
View File
@@ -239,6 +239,9 @@ func validateHTTP(http HTTPConfig) error {
if http.HTTPSPort != 0 && !validPort(http.HTTPSPort) {
return ErrInvalidHTTP
}
if http.PublicHTTPSPort != 0 && !validPort(http.PublicHTTPSPort) {
return ErrInvalidHTTP
}
if http.TLSMode != "" && http.TLSMode != HTTPSTLSModeDirect && http.TLSMode != HTTPSTLSModeProxy {
return ErrInvalidHTTP
}
+6 -10
View File
@@ -31,16 +31,12 @@ func ResolveWebAuthnSecurity(root RootConfig) (SecurityConfig, error) {
}
if len(security.WebAuthnRPOrigins) == 0 {
origin := "https://" + web
httpConfig := ResolveHTTPPortDefaults(root.HTTP, 0)
// 反代的外部端口不等于内部 HTTP 端口,非标准外部端口需显式配置。
if httpConfig.TLSMode != HTTPSTLSModeProxy {
port := httpConfig.HTTPSPort
if !validServicePort(port) {
return SecurityConfig{}, fmt.Errorf("安全密钥站点 HTTPS 端口无效")
}
if port != 443 {
origin += ":" + strconv.Itoa(port)
}
port := ResolvePublicHTTPSPort(root.HTTP)
if !validServicePort(port) {
return SecurityConfig{}, fmt.Errorf("安全密钥站点 HTTPS 端口无效")
}
if port != 443 {
origin += ":" + strconv.Itoa(port)
}
security.WebAuthnRPOrigins = []string{origin}
}