修复通行密钥默认配置启动并补齐迁移校验
Security Checks / security (push) Waiting to run

This commit is contained in:
xuans committed 2026-09-06 22:39:07 +08:00
1 parent 20a6eea3b3
commit f530ab0078
10 files changed
+269 -12

No files matched your search

+1 -1
View File
@@ -3,7 +3,7 @@
## 目录用途
- `frontend/`:前端自动测试及其构建路径约束测试,直接复用 `frontend/node_modules`。
- `backend/`:集中保存邮件监听、账号协议隔离和凭据竞态回归,通过默认入口的 Go overlay 注入相应业务包;不复制测试文件到源码目录。
- `backend/`:集中保存邮件监听、账号协议隔离、凭据竞态及 WebAuthn 站点配置和启动回归,通过默认入口的 Go overlay 注入相应业务包;不复制测试文件到源码目录。
- `tools/password-check/`:离线密码哈希校验工具,只通过环境变量接收输入,不输出密码和哈希。
- `manual/smtp/`:人工 SMTP 发信脚本,可能向外部发送真实邮件,不包含在自动测试中。运行前需自行检查收发件人和服务器配置。
- `plugins/spam_block/`:垃圾邮件模型测试,需要额外安装 TensorFlow 并准备相应模型;不包含在默认测试中。
+85
View File
@@ -0,0 +1,85 @@
package config
import (
"reflect"
"testing"
)
func TestWebAuthnDefaultsUseConfiguredSiteOnly(t *testing.T) {
t.Setenv("SMAIL_HTTPS_PORT", "")
for _, item := range []struct {
name string
http HTTPConfig
want string
}{
{"legacy", HTTPConfig{}, "https://mail.example.com"},
{"direct", HTTPConfig{HTTPSPort: 9443, HTTPSEnabled: true}, "https://mail.example.com:9443"},
{"proxy", HTTPConfig{Port: 8080, TLSMode: HTTPSTLSModeProxy}, "https://mail.example.com"},
} {
t.Run(item.name, func(t *testing.T) {
root := RootConfig{Domains: DomainConfig{Web: "mail.example.com", AccessHosts: []string{"untrusted.example.net"}}, HTTP: item.http}
got, err := ResolveWebAuthnSecurity(root)
if err != nil {
t.Fatal(err)
}
if got.WebAuthnRPID != "mail.example.com" || got.WebAuthnRPDisplayName != "Smail" || !reflect.DeepEqual(got.WebAuthnRPOrigins, []string{item.want}) {
t.Fatalf("站点默认值错误:%+v", got)
}
if root.Security.WebAuthnRPID != "" || len(root.Security.WebAuthnRPOrigins) != 0 {
t.Fatal("解析默认值改写了原始配置")
}
})
}
}
func TestWebAuthnExplicitConfigurationIsPreserved(t *testing.T) {
root := RootConfig{Domains: DomainConfig{Web: "mail.example.com"}, Security: SecurityConfig{
WebAuthnRPID: "example.com", WebAuthnRPDisplayName: "企业邮箱", WebAuthnRPOrigins: []string{"https://mail.example.com:8443"},
}}
got, err := ResolveWebAuthnSecurity(root)
if err != nil || !reflect.DeepEqual(got, root.Security) {
t.Fatalf("显式配置被覆盖:%v", err)
}
got.WebAuthnRPOrigins[0] = "https://changed.example.com"
if root.Security.WebAuthnRPOrigins[0] != "https://mail.example.com:8443" {
t.Fatal("解析结果与原始配置共用来源切片")
}
}
func TestWebAuthnRejectsUnsafeConfiguredOrigins(t *testing.T) {
for _, origin := range []string{
"http://mail.example.com", "https://attacker.example.net", "https://badexample.com",
"https://mail.example.com/path", "https://mail.example.com?", "https://mail.example.com#",
"https://user@mail.example.com", "https://mail.example.com:65536", "https://*.example.com", "",
"https://mail.example.com:", "https://mail.example.com:0", "https://mail.example.com:invalid",
} {
t.Run(origin, func(t *testing.T) {
root := RootConfig{Domains: DomainConfig{Web: "mail.example.com"}, Security: SecurityConfig{
WebAuthnRPID: "example.com", WebAuthnRPOrigins: []string{origin},
}}
if _, err := ResolveWebAuthnSecurity(root); err == nil {
t.Fatal("不安全的显式来源未被拒绝")
}
})
}
if _, err := ResolveWebAuthnSecurity(RootConfig{}); err == nil {
t.Fatal("缺少站点配置时不应猜测信赖方")
}
}
func TestWebAuthnDefaultsRespectExplicitLocalDevelopmentOrigin(t *testing.T) {
root := RootConfig{Domains: DomainConfig{Web: "localhost"}, Security: SecurityConfig{
WebAuthnRPOrigins: []string{"http://localhost:15173"},
}}
if _, err := ResolveWebAuthnSecurity(root); err != nil {
t.Fatalf("显式 localhost 来源被拒绝:%v", err)
}
}
func TestRuntimeValidationRejectsInvalidWebAuthnBeforeSaving(t *testing.T) {
runtime := validRuntimeConfig()
runtime.Root.Security.WebAuthnRPOrigins = []string{"https://attacker.example.net"}
if err := ValidateRuntimeConfig(runtime, RuntimeValidationOptions{HasSuperAdmin: true, Production: true}); err == nil {
t.Fatal("候选配置接受了不属于站点信赖方的来源")
}
}
+71
View File
@@ -0,0 +1,71 @@
package res_init
import (
"encoding/json"
"os"
"path/filepath"
"testing"
"git.pcux.cn/xuans/Smail/config"
"git.pcux.cn/xuans/Smail/controllers"
"git.pcux.cn/xuans/Smail/db"
"git.pcux.cn/xuans/Smail/models"
_ "modernc.org/sqlite"
"xorm.io/xorm"
)
func TestWebAuthnStartsWithMigratedSiteDefaults(t *testing.T) {
root := t.TempDir()
previousRoot, previousDevelopment, previousDB := config.ROOT_PATH, config.DevelopmentMode, db.Instance
previousManager, previousService := config.CurrentManager(), webAuthnRuntimeService
config.ROOT_PATH, config.DevelopmentMode = root, false
t.Cleanup(func() {
stopConfigManager()
config.SetRuntimeManager(previousManager)
config.ROOT_PATH, config.DevelopmentMode, db.Instance = previousRoot, previousDevelopment, previousDB
webAuthnRuntimeService = previousService
controllers.ConfigureWebAuthnRuntime(previousService)
})
if err := os.MkdirAll(filepath.Join(root, "config"), 0700); err != nil {
t.Fatal(err)
}
data, err := json.Marshal(map[string]any{
"domain": "example.com", "webDomain": "mail.example.com", "dbType": "sqlite",
"dbDSN": "./config/existing.db", "isInit": true, "httpsEnabled": 1, "httpsPort": 443,
})
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "config", "config.json"), data, 0600); err != nil {
t.Fatal(err)
}
if _, err := config.MigrateLegacyConfig(root, config.RuntimeValidationOptions{HasSuperAdmin: true, Production: true}); err != nil {
t.Fatal(err)
}
if err := startConfigManager(); err != nil {
t.Fatal(err)
}
engine, err := xorm.NewEngine("sqlite", filepath.Join(root, "config", "existing.db"))
if err != nil {
t.Fatal(err)
}
defer engine.Close()
db.Instance = engine
if err := engine.Sync2(&models.User{}, &models.WebAuthnCredential{}); err != nil {
t.Fatal(err)
}
user := models.User{Account: "test", Name: "测试用户", Password: "unused", Role: "user"}
if _, err := engine.Insert(&user); err != nil {
t.Fatal(err)
}
if err := startWebAuthnRuntime(); err != nil {
t.Fatal(err)
}
if webAuthnRuntimeService == nil {
t.Fatal("未设置旧全局开关时安全密钥服务仍应可用")
}
options, _, err := webAuthnRuntimeService.BeginRegistration(user.ID)
if err != nil || options.Response.RelyingParty.ID != "mail.example.com" {
t.Fatalf("安全密钥注册未使用受控站点标识:%v", err)
}
}
+19 -3
View File
@@ -10,6 +10,19 @@ const { readFormConfig, getFieldGroups, updateFormConfig, validateFormConfig } =
source.replaceAll('export function ', 'function ') + '\nreturn { readFormConfig, getFieldGroups, updateFormConfig, validateFormConfig }'
)()
test('站点安全配置不再依赖旧全局开关,用户权限仍由账号设置管理', () => {
const config = { security: { webAuthnEnabled: false, externalEmailEnabled: false } }
const groups = getFieldGroups('base', config)
const security = groups.find(group => group.id === 'security')
assert.ok(security)
const keys = security.fields.map(field => field.path.join('.'))
assert.deepEqual(keys, ['security.webAuthnRpId', 'security.webAuthnRpDisplayName', 'security.webAuthnRpOrigins'])
const updated = readFormConfig(updateFormConfig(JSON.stringify(config), 'base', ['security', 'webAuthnRpId'], 'mail.example.com'))
assert.equal(updated.security.webAuthnRpId, 'mail.example.com')
assert.equal(updated.security.webAuthnEnabled, false)
assert.equal(updated.security.externalEmailEnabled, false)
})
test('七个页面使用分组表单,控件和样式能编译且不再提供 JSON 编辑器', () => {
const require = createRequire(new URL('../../frontend/package.json', import.meta.url))
const { parse, compileScript, compileStyle } = require('@vue/compiler-sfc')
@@ -167,7 +180,8 @@ test('基础配置隐藏额外访问主机、代理网段和数据库只读信
assert.equal(updateFormConfig(text, 'base', key.split('.'), 'changed'), text)
}
for (const key of ['security.externalEmailEnabled', 'security.webAuthnEnabled']) {
assert.ok(keys.includes(key))
assert.ok(!keys.includes(key))
assert.equal(updateFormConfig(text, 'base', key.split('.'), true), text)
}
const updated = readFormConfig(updateFormConfig(text, 'base', ['http', 'port'], 9080))
assert.deepEqual(updated, { ...config, http: { ...config.http, port: 9080 } })
@@ -188,8 +202,10 @@ test('开关、数字、空数字和列表保持真实类型,代理 HTTPS 正
text = updateFormConfig(text, 'base', ['http', 'tlsMode'], 'proxy')
assert.deepEqual(readFormConfig(text).http, { tlsMode: 'proxy', httpsEnabled: false, httpsPort: 0, port: 8080 })
assert.equal(updateFormConfig(text, 'base', ['http', 'httpsEnabled'], true), text)
text = updateFormConfig(text, 'base', ['security', 'externalEmailEnabled'], true)
assert.equal(readFormConfig(text).security.externalEmailEnabled, true)
const direct = updateFormConfig(text, 'base', ['http', 'tlsMode'], 'direct')
const disabled = readFormConfig(updateFormConfig(direct, 'base', ['http', 'httpsEnabled'], false))
assert.equal(disabled.http.httpsEnabled, false)
assert.equal(disabled.http.httpsPort, 0)
text = updateFormConfig(text, 'base', ['http', 'port'], 8080)
assert.equal(readFormConfig(text).http.port, 8080)
text = updateFormConfig(text, 'base', ['http', 'port'], undefined)
+2
View File
@@ -42,6 +42,8 @@ if (suite !== 'frontend' && result === 0) {
const args = extra[0] === '--' ? extra.slice(1) : extra
// 独立回归源码集中放在 test/backend,通过 overlay 保留同包测试语义。
const replacements = {
'backend/config/webauthn_defaults_test.go': 'test/backend/webauthn_config_test.go',
'backend/res_init/webauthn_runtime_test.go': 'test/backend/webauthn_runtime_test.go',
'backend/services/credentials/client_regression_test.go': 'test/backend/protocol_credentials_test.go',
'backend/controllers/client_regression_test.go': 'test/backend/protocol_access_test.go',
'backend/res_init/client_listeners_test.go': 'test/backend/mail_listeners_test.go',