完成安全整改与配置系统重构阶段开发
Security Checks / security (push) Waiting to run

This commit is contained in:
xuans committed 2026-08-28 00:42:28 +08:00
1 parent 6ec462895f
commit 18b6dfbdf7
26 files changed
+1913 -169

No files matched your search

+1 -1
View File
@@ -10,7 +10,7 @@ import (
func testRootConfig() RootConfig {
return RootConfig{SchemaVersion: CurrentSchemaVersion, Generation: 1, SetupState: SetupStateBootstrap,
Database: DatabaseConfig{Type: DBTypeSQLite, SQLiteLocalRef: "smail.db"},
Database: DatabaseConfig{Type: DatabaseTypeSQLite, LocalRef: "smail.db"},
SMTP: SMTPConfig{VerificationEnabled: false},
SSL: SSLConfig{Mode: "default", DefaultDirectory: "config/ssl"},
Security: SecurityConfig{PasswordVersion: "argon2id"}}
+1 -1
View File
@@ -716,7 +716,7 @@ func applySecretChanges(candidate *RuntimeConfig, section Section, changes map[s
for name, change := range changes {
switch {
case section == SectionRoot && name == "database.password":
stored, err := ApplySecretChange(vault, candidate.Root.Database.Password, change, SecretPolicy{Required: candidate.Root.Database.Type != DBTypeSQLite, AllowClear: false, MaxLength: 4096}, now)
stored, err := ApplySecretChange(vault, candidate.Root.Database.Password, change, SecretPolicy{Required: candidate.Root.Database.Type != DatabaseTypeSQLite, AllowClear: false, MaxLength: 4096}, now)
if err != nil {
return err
}
+32 -10
View File
@@ -10,6 +10,7 @@ import (
"time"
"git.pcux.cn/xuans/Smail/utils/atomicfile"
"git.pcux.cn/xuans/Smail/utils/credential"
)
func writeRuntimeFixture(t *testing.T, root string, runtime RuntimeConfig) {
@@ -29,6 +30,27 @@ func writeRuntimeFixture(t *testing.T, root string, runtime RuntimeConfig) {
}
}
func validMySQLRuntimeConfig(t *testing.T, root string) RuntimeConfig {
t.Helper()
runtime := validRuntimeConfig()
vault, err := credential.NewVault(root)
if err != nil {
t.Fatal(err)
}
ciphertext, err := vault.Encrypt("initial-database-secret")
if err != nil {
t.Fatal(err)
}
runtime.Root.Database = DatabaseConfig{
Type: DatabaseTypeMySQL,
Host: "127.0.0.1",
Port: DefaultMySQLPort,
Username: "smail",
Password: StoredSecret{Ciphertext: ciphertext, Version: vault.Version(), UpdatedAt: time.Now().UTC()},
Name: "smail",
}
return runtime
}
func authorizedConfigActor() AuditActor {
return AuditActor{UserID: "1", Role: "super_admin", SessionID: "test-session", RecentAuth: true, RecoveryCodeConfigured: true}
}
@@ -309,14 +331,16 @@ func TestTransactionRecoveryKeepsOrRestoresByPhase(t *testing.T) {
func TestConfigManagerSecretChangesRequireStepUpAndPreserveStoredSecret(t *testing.T) {
root := t.TempDir()
runtime := validRuntimeConfig()
runtime := validMySQLRuntimeConfig(t, root)
writeRuntimeFixture(t, root, runtime)
options := ConfigLoaderOptions{Validation: RuntimeValidationOptions{HasSuperAdmin: true, Production: true}}
manager, err := NewConfigManager(root, options)
if err != nil {
t.Fatal(err)
}
rootPayload, err := json.Marshal(manager.Snapshot().Root)
rootValue := manager.Snapshot().Root
rootValue.Database.Password = StoredSecret{}
rootPayload, err := json.Marshal(rootValue)
if err != nil {
t.Fatal(err)
}
@@ -344,14 +368,10 @@ func TestConfigManagerSecretChangesRequireStepUpAndPreserveStoredSecret(t *testi
t.Fatal(err)
}
stored := manager.Snapshot().Root.Database.Password
payload, err := json.Marshal(manager.Snapshot().Root)
if err != nil {
t.Fatal(err)
}
rootValue := manager.Snapshot().Root
rootValue = manager.Snapshot().Root
rootValue.Database.Password = StoredSecret{}
rootValue.Database.Name = "next"
payload, err = json.Marshal(rootValue)
payload, err := json.Marshal(rootValue)
if err != nil {
t.Fatal(err)
}
@@ -417,14 +437,16 @@ func TestConfigManagerSecretClearRequiresExplicitConfirmation(t *testing.T) {
func TestConfigManagerSecretChangesUseVaultAndRejectUnknownFields(t *testing.T) {
root := t.TempDir()
runtime := validRuntimeConfig()
runtime := validMySQLRuntimeConfig(t, root)
writeRuntimeFixture(t, root, runtime)
options := ConfigLoaderOptions{Validation: RuntimeValidationOptions{HasSuperAdmin: true, Production: true}}
manager, err := NewConfigManager(root, options)
if err != nil {
t.Fatal(err)
}
rootPayload, err := json.Marshal(manager.Snapshot().Root)
rootValue := manager.Snapshot().Root
rootValue.Database.Password = StoredSecret{}
rootPayload, err := json.Marshal(rootValue)
if err != nil {
t.Fatal(err)
}
+55 -9
View File
@@ -11,6 +11,19 @@ const (
SetupStateDegraded SetupState = "degraded"
)
type DatabaseType string
const (
DatabaseTypeMySQL DatabaseType = "mysql"
DatabaseTypePostgreSQL DatabaseType = "postgresql"
DatabaseTypeSQLite DatabaseType = "sqlite"
)
const (
DefaultMySQLPort uint16 = 3306
DefaultPostgreSQLPort uint16 = 5432
)
type RootConfig struct {
ConfigVersion uint32 `json:"configVersion,omitempty"`
SchemaVersion int `json:"schemaVersion,omitempty"`
@@ -50,18 +63,22 @@ func normalizeRootConfig(source RootConfig) RootConfig {
result.Generation = 1
}
}
result.Database = NormalizeDatabaseConfig(result.Database)
if result.LogLevel == "" {
result.LogLevel = "info"
}
result.Version = 0
return result
}
type DatabaseConfig struct {
Type string `json:"type"`
Host string `json:"host,omitempty"`
Port int `json:"port,omitempty"`
Username string `json:"username,omitempty"`
Password StoredSecret `json:"password,omitempty"`
Name string `json:"name,omitempty"`
SQLiteLocalRef string `json:"sqliteLocalRef,omitempty"`
Type DatabaseType `json:"type"`
Host string `json:"host,omitempty"`
Port uint16 `json:"port,omitempty"`
Username string `json:"username,omitempty"`
Password StoredSecret `json:"password,omitempty"`
Name string `json:"name,omitempty"`
LocalRef string `json:"localRef,omitempty"`
}
type SMTPConfig struct {
@@ -120,6 +137,35 @@ func (s SetupState) Valid() bool {
}
}
func (d DatabaseConfig) IsStructured() bool {
return d.Type == DBTypeSQLite || (d.Host != "" && d.Username != "" && d.Name != "" && d.Password.Configured())
func (t DatabaseType) Valid() bool {
switch t {
case DatabaseTypeMySQL, DatabaseTypePostgreSQL, DatabaseTypeSQLite:
return true
default:
return false
}
}
func DefaultDatabasePort(databaseType DatabaseType) (uint16, bool) {
switch databaseType {
case DatabaseTypeMySQL:
return DefaultMySQLPort, true
case DatabaseTypePostgreSQL:
return DefaultPostgreSQLPort, true
default:
return 0, false
}
}
func NormalizeDatabaseConfig(database DatabaseConfig) DatabaseConfig {
if database.Port == 0 {
if port, ok := DefaultDatabasePort(database.Type); ok {
database.Port = port
}
}
return database
}
func (d DatabaseConfig) IsStructured() bool {
return d.Type == DatabaseTypeSQLite || (d.Host != "" && d.Username != "" && d.Name != "" && d.Password.Configured())
}
+105
View File
@@ -0,0 +1,105 @@
package config
import (
"encoding/json"
"strings"
"testing"
"time"
)
func TestDatabaseTypeDefaultsAndValidation(t *testing.T) {
secret := StoredSecret{Ciphertext: "enc:v1:stored", Version: 1, UpdatedAt: time.Now().UTC()}
tests := []struct {
name string
typeValue DatabaseType
port uint16
wantPort uint16
}{
{name: "mysql default", typeValue: DatabaseTypeMySQL, wantPort: DefaultMySQLPort},
{name: "postgresql default", typeValue: DatabaseTypePostgreSQL, wantPort: DefaultPostgreSQLPort},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got := NormalizeDatabaseConfig(DatabaseConfig{Type: test.typeValue})
if got.Port != test.wantPort {
t.Fatalf("default port = %d, want %d", got.Port, test.wantPort)
}
valid := got
valid.Host = "127.0.0.1"
valid.Username = "smail"
valid.Password = secret
valid.Name = "smail"
if err := ValidateDatabaseConfig(valid); err != nil {
t.Fatalf("valid database rejected: %v", err)
}
})
}
if _, ok := DefaultDatabasePort(DatabaseTypeSQLite); ok {
t.Fatal("SQLite unexpectedly received a network default port")
}
if DatabaseType("postgres").Valid() {
t.Fatal("legacy PostgreSQL enum was accepted")
}
}
func TestSQLiteLocalRefIsBackendReferenceOnly(t *testing.T) {
valid := DatabaseConfig{Type: DatabaseTypeSQLite, LocalRef: "smail.db"}
if err := ValidateDatabaseConfig(valid); err != nil {
t.Fatalf("valid SQLite database rejected: %v", err)
}
for _, localRef := range []string{
"../smail.db",
"config/smail.db",
"C:\\data\\smail.db",
"/var/lib/smail/smail.db",
"\\\\server\\share\\smail.db",
"",
} {
t.Run(localRef, func(t *testing.T) {
candidate := valid
candidate.LocalRef = localRef
if err := ValidateDatabaseConfig(candidate); err == nil {
t.Fatalf("arbitrary localRef %q was accepted", localRef)
}
})
}
for name, mutate := range map[string]func(*DatabaseConfig){
"host": func(candidate *DatabaseConfig) { candidate.Host = "127.0.0.1" },
"port": func(candidate *DatabaseConfig) { candidate.Port = 3306 },
"username": func(candidate *DatabaseConfig) { candidate.Username = "smail" },
"name": func(candidate *DatabaseConfig) { candidate.Name = "smail" },
"password": func(candidate *DatabaseConfig) {
candidate.Password = StoredSecret{Ciphertext: "enc:v1:secret", Version: 1, UpdatedAt: time.Now().UTC()}
},
} {
t.Run(name, func(t *testing.T) {
candidate := valid
mutate(&candidate)
if err := ValidateDatabaseConfig(candidate); err == nil {
t.Fatalf("SQLite %s field was accepted", name)
}
})
}
}
func TestDatabaseModelSerializationUsesLocalRef(t *testing.T) {
root := testRootConfig()
data, err := json.Marshal(root)
if err != nil {
t.Fatal(err)
}
encoded := string(data)
if !strings.Contains(encoded, `"localRef":"smail.db"`) {
t.Fatalf("serialized database omitted localRef: %s", encoded)
}
if strings.Contains(encoded, "sqliteLocalRef") {
t.Fatalf("serialized database contains legacy SQLite field: %s", encoded)
}
var decoded RootConfig
if err := ParseStrict(data, &decoded); err != nil {
t.Fatal(err)
}
if decoded.Database.LocalRef != "smail.db" {
t.Fatalf("decoded localRef = %q", decoded.Database.LocalRef)
}
}
+1 -1
View File
@@ -5,7 +5,7 @@ import "testing"
func TestRootConfigValidatesStructuredDatabaseAndPluginID(t *testing.T) {
root := RootConfig{
SchemaVersion: CurrentSchemaVersion, Generation: 1, SetupState: SetupStateBootstrap,
Database: DatabaseConfig{Type: DBTypeSQLite, SQLiteLocalRef: "smail.db"},
Database: DatabaseConfig{Type: DatabaseTypeSQLite, LocalRef: "smail.db"},
SMTP: SMTPConfig{VerificationEnabled: false},
SSL: SSLConfig{Mode: "default", DefaultDirectory: "config/ssl"},
Plugins: []PluginConfig{{LogicalID: "telegram_push", FileName: "telegram_push", NetworkAllowlist: []string{"api.telegram.org"}}},
+147 -17
View File
@@ -1,6 +1,11 @@
package config
import "strings"
import (
"fmt"
"reflect"
"strings"
"time"
)
type PersistencePolicy string
@@ -8,28 +13,48 @@ const (
PersistenceEncryptedOnly PersistencePolicy = "encrypted_only"
PersistenceReferenceOnly PersistencePolicy = "reference_only"
PersistenceMemoryOnly PersistencePolicy = "memory_only"
PersistenceHashedOnly PersistencePolicy = "hashed_only"
)
const RedactedValue = "[REDACTED]"
type SensitiveField struct {
Path string
Policy PersistencePolicy
Path string
Policy PersistencePolicy
Description string
}
var sensitiveFields = []SensitiveField{
{Path: "database.password", Policy: PersistenceEncryptedOnly},
{Path: "smtp.relay.password", Policy: PersistenceEncryptedOnly},
{Path: "plugins.*.token", Policy: PersistenceEncryptedOnly},
{Path: "plugins.*.secret", Policy: PersistenceEncryptedOnly},
{Path: "plugins.*.api_key", Policy: PersistenceEncryptedOnly},
{Path: "ssl.private_key", Policy: PersistenceReferenceOnly},
{Path: "security.encryption_master_key", Policy: PersistenceReferenceOnly},
{Path: "security.question_answer", Policy: PersistenceEncryptedOnly},
{Path: "security.offline_recovery_code", Policy: PersistenceEncryptedOnly},
{Path: "security.maintenance_credential", Policy: PersistenceMemoryOnly},
{Path: "verification.code", Policy: PersistenceMemoryOnly},
{Path: "verification.code_hmac", Policy: PersistenceMemoryOnly},
{Path: "verification.process_key", Policy: PersistenceMemoryOnly},
{Path: "recovery.authorization", Policy: PersistenceMemoryOnly},
{Path: "database.password", Policy: PersistenceEncryptedOnly, Description: "数据库认证密码"},
{Path: "smtp.relay.password", Policy: PersistenceEncryptedOnly, Description: "SMTP Relay 认证密码"},
{Path: "plugins.*.token", Policy: PersistenceEncryptedOnly, Description: "插件访问令牌"},
{Path: "plugins.*.secret", Policy: PersistenceEncryptedOnly, Description: "插件 Secret"},
{Path: "plugins.*.api_key", Policy: PersistenceEncryptedOnly, Description: "插件 API 密钥"},
{Path: "ssl.private_key", Policy: PersistenceReferenceOnly, Description: "SSL 私钥材料"},
{Path: "security.encryption_master_key", Policy: PersistenceReferenceOnly, Description: "配置加密主密钥"},
{Path: "security.question_answer", Policy: PersistenceEncryptedOnly, Description: "密保答案原文"},
{Path: "security.offline_recovery_code", Policy: PersistenceMemoryOnly, Description: "离线恢复码原文"},
{Path: "security.maintenance_credential", Policy: PersistenceMemoryOnly, Description: "维护凭据"},
{Path: "verification.code", Policy: PersistenceMemoryOnly, Description: "邮箱验证码原文"},
{Path: "verification.code_hmac", Policy: PersistenceMemoryOnly, Description: "验证码 HMAC 校验值"},
{Path: "verification.process_key", Policy: PersistenceMemoryOnly, Description: "验证码进程临时密钥"},
{Path: "verification.challenge", Policy: PersistenceMemoryOnly, Description: "验证码挑战上下文"},
{Path: "verification.account_fingerprint", Policy: PersistenceHashedOnly, Description: "验证码账号运营指纹"},
{Path: "verification.email_fingerprint", Policy: PersistenceHashedOnly, Description: "验证码邮箱运营指纹"},
{Path: "verification.ip_fingerprint", Policy: PersistenceHashedOnly, Description: "验证码 IP 运营指纹"},
{Path: "verification.rate_limit_fingerprint", Policy: PersistenceHashedOnly, Description: "验证码限流指纹"},
{Path: "recovery.authorization", Policy: PersistenceMemoryOnly, Description: "恢复授权上下文"},
{Path: "recovery.ticket", Policy: PersistenceMemoryOnly, Description: "密码恢复票据"},
{Path: "recovery.code", Policy: PersistenceMemoryOnly, Description: "恢复码原文"},
{Path: "external_email.email", Policy: PersistenceEncryptedOnly, Description: "完整外部安全邮箱"},
{Path: "external_email.address", Policy: PersistenceEncryptedOnly, Description: "完整外部邮箱地址"},
{Path: "external_email.credential", Policy: PersistenceEncryptedOnly, Description: "外部邮箱凭据材料"},
{Path: "webauthn.credential_data", Policy: PersistenceEncryptedOnly, Description: "WebAuthn 凭据私密材料"},
{Path: "webauthn.private_key", Policy: PersistenceMemoryOnly, Description: "WebAuthn 私钥材料"},
{Path: "ipc.nonce", Policy: PersistenceMemoryOnly, Description: "本机 IPC 一次性 nonce"},
{Path: "ipc.maintenance_credential", Policy: PersistenceMemoryOnly, Description: "本机维护通道凭据"},
{Path: "session.token", Policy: PersistenceReferenceOnly, Description: "会话令牌"},
{Path: "session.data", Policy: PersistenceEncryptedOnly, Description: "会话数据"},
}
func SensitiveFields() []SensitiveField {
@@ -63,11 +88,116 @@ func CanPersist(path string, encrypted bool) bool {
return encrypted
case PersistenceReferenceOnly, PersistenceMemoryOnly:
return false
case PersistenceHashedOnly:
return false
default:
return false
}
}
// CanPersistRepresentation 判断敏感数据只能以哪一种表示形式进入持久化介质。
// verification.code 等内存字段即使经过哈希或加密也不得落盘。
func CanPersistRepresentation(path string, representation string) bool {
field, sensitive := ClassifySensitive(path)
if !sensitive {
return true
}
switch field.Policy {
case PersistenceEncryptedOnly:
return representation == "encrypted"
case PersistenceReferenceOnly:
return representation == "reference"
case PersistenceHashedOnly:
return representation == "hash"
case PersistenceMemoryOnly:
return representation == "memory"
default:
return false
}
}
// RedactSensitiveValue 为公共输出提供统一的敏感值占位符。
func RedactSensitiveValue(path string, value any) any {
if _, ok := ClassifySensitive(path); ok {
return RedactedValue
}
return value
}
// RedactPublicValue 递归生成只读公共视图,避免把 Secret 结构直接交给 JSON 反射器。
// 持久化配置必须继续使用原始结构和专用存储路径,不能把该函数用于写盘。
func RedactPublicValue(value any) any {
return redactPublicValue(reflect.ValueOf(value), "")
}
func redactPublicValue(value reflect.Value, path string) any {
if !value.IsValid() {
return nil
}
if value.Kind() == reflect.Interface || value.Kind() == reflect.Pointer {
if value.IsNil() {
return nil
}
return redactPublicValue(value.Elem(), path)
}
if path != "" {
if _, ok := ClassifySensitive(path); ok {
return RedactedValue
}
}
if value.Type() == reflect.TypeOf(time.Time{}) {
return value.Interface()
}
switch value.Kind() {
case reflect.Struct:
result := make(map[string]any)
typ := value.Type()
for index := 0; index < value.NumField(); index++ {
field := typ.Field(index)
if field.PkgPath != "" {
continue
}
name := jsonFieldName(field.Tag.Get("json"), field.Name)
if name == "" || name == "-" {
continue
}
fieldPath := joinSensitivePath(path, name)
result[name] = redactPublicValue(value.Field(index), fieldPath)
}
return result
case reflect.Map:
result := make(map[string]any)
iter := value.MapRange()
for iter.Next() {
key := fmt.Sprint(iter.Key().Interface())
result[key] = redactPublicValue(iter.Value(), joinSensitivePath(path, key))
}
return result
case reflect.Slice, reflect.Array:
result := make([]any, value.Len())
for index := 0; index < value.Len(); index++ {
result[index] = redactPublicValue(value.Index(index), path)
}
return result
default:
return value.Interface()
}
}
func jsonFieldName(tag, fallback string) string {
if tag == "" {
return fallback
}
return strings.Split(tag, ",")[0]
}
func joinSensitivePath(parent, child string) string {
if parent == "" {
return child
}
return parent + "." + child
}
func matchSensitivePath(pattern string, value string) bool {
patternParts := strings.Split(pattern, ".")
valueParts := strings.Split(value, ".")
+52 -3
View File
@@ -4,8 +4,8 @@ import "testing"
func TestSensitiveFieldCatalog(t *testing.T) {
fields := SensitiveFields()
if len(fields) != 14 {
t.Fatalf("unexpected sensitive field count: %d", len(fields))
if len(fields) < 30 {
t.Fatalf("sensitive field catalog is incomplete: %d", len(fields))
}
seen := map[string]struct{}{}
for _, field := range fields {
@@ -14,10 +14,13 @@ func TestSensitiveFieldCatalog(t *testing.T) {
}
seen[field.Path] = struct{}{}
switch field.Policy {
case PersistenceEncryptedOnly, PersistenceReferenceOnly, PersistenceMemoryOnly:
case PersistenceEncryptedOnly, PersistenceReferenceOnly, PersistenceMemoryOnly, PersistenceHashedOnly:
default:
t.Fatalf("invalid policy for %s", field.Path)
}
if field.Description == "" {
t.Fatalf("missing description for %s", field.Path)
}
if CanGenericSerialize(field.Path) {
t.Fatalf("sensitive field can be generically serialized: %s", field.Path)
}
@@ -47,6 +50,7 @@ func TestSensitivePersistenceRules(t *testing.T) {
{path: "verification.code_hmac", encrypted: true, want: false},
{path: "verification.process_key", encrypted: true, want: false},
{path: "public.display_name", encrypted: false, want: true},
{path: "verification.account_fingerprint", encrypted: true, want: false},
}
for _, test := range tests {
if got := CanPersist(test.path, test.encrypted); got != test.want {
@@ -54,3 +58,48 @@ func TestSensitivePersistenceRules(t *testing.T) {
}
}
}
func TestSensitiveRepresentations(t *testing.T) {
tests := []struct {
path string
representation string
want bool
}{
{path: "database.password", representation: "encrypted", want: true},
{path: "database.password", representation: "hash", want: false},
{path: "verification.code", representation: "hash", want: false},
{path: "verification.code", representation: "memory", want: true},
{path: "verification.email_fingerprint", representation: "hash", want: true},
{path: "ssl.private_key", representation: "reference", want: true},
}
for _, test := range tests {
if got := CanPersistRepresentation(test.path, test.representation); got != test.want {
t.Fatalf("CanPersistRepresentation(%q, %q) = %t, want %t", test.path, test.representation, got, test.want)
}
}
}
func TestRedactPublicValue(t *testing.T) {
value := map[string]any{
"database": map[string]any{
"password": map[string]any{"ciphertext": "enc-secret"},
"name": "smail",
},
"verification": map[string]any{
"code": "12345678",
"email_fingerprint": "fingerprint",
},
}
redacted, ok := RedactPublicValue(value).(map[string]any)
if !ok {
t.Fatalf("unexpected redacted value type: %T", RedactPublicValue(value))
}
database := redacted["database"].(map[string]any)
if database["password"] != RedactedValue || database["name"] != "smail" {
t.Fatalf("database public view was not redacted: %#v", database)
}
verification := redacted["verification"].(map[string]any)
if verification["code"] != RedactedValue || verification["email_fingerprint"] != RedactedValue {
t.Fatalf("verification public view was not redacted: %#v", verification)
}
}
+16 -5
View File
@@ -17,6 +17,7 @@ var (
)
var logicalIDPattern = regexp.MustCompile(`^[a-z][a-z0-9_-]{1,63}$`)
var databaseLocalRefPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`)
func ValidateRootConfig(root RootConfig) error {
if root.ConfigVersion > CurrentConfigVersion || root.SchemaVersion <= 0 || root.SchemaVersion > CurrentSchemaVersion || root.Generation == 0 || !root.SetupState.Valid() {
@@ -27,7 +28,7 @@ func ValidateRootConfig(root RootConfig) error {
return err
}
}
if err := validateDatabase(root.Database); err != nil {
if err := ValidateDatabaseConfig(root.Database); err != nil {
return err
}
if err := validateSMTP(root.SMTP); err != nil {
@@ -52,14 +53,24 @@ func ValidateRootConfig(root RootConfig) error {
return nil
}
func ValidateDatabaseConfig(database DatabaseConfig) error {
return validateDatabase(database)
}
func validateDatabase(database DatabaseConfig) error {
database = NormalizeDatabaseConfig(database)
switch database.Type {
case DBTypeSQLite:
if database.SQLiteLocalRef == "" || filepath.IsAbs(database.SQLiteLocalRef) || strings.Contains(database.SQLiteLocalRef, "..") {
case DatabaseTypeSQLite:
if !databaseLocalRefPattern.MatchString(database.LocalRef) ||
filepath.IsAbs(database.LocalRef) ||
isWindowsAbsolute(database.LocalRef) ||
strings.ContainsAny(database.LocalRef, `/\\:`) ||
database.Host != "" || database.Port != 0 || database.Username != "" ||
database.Password.Configured() || database.Password.Ciphertext != "" || database.Password.Version != 0 || !database.Password.UpdatedAt.IsZero() || database.Name != "" {
return ErrInvalidDatabase
}
case DBTypeMySQL, DBTypePostgres:
if database.Host == "" || database.Username == "" || database.Name == "" || !database.Password.Configured() || !validPort(database.Port) {
case DatabaseTypeMySQL, DatabaseTypePostgreSQL:
if database.Host == "" || database.Username == "" || database.Name == "" || !database.Password.Configured() || database.LocalRef != "" || !validPort(int(database.Port)) {
return ErrInvalidDatabase
}
if err := ValidateStoredSecret(database.Password, true); err != nil {
+9 -4
View File
@@ -261,8 +261,8 @@ func ExportConfigAudit(ctx *appcontext.Context, w http.ResponseWriter, req *http
if !ok {
return
}
if ctx.EffectiveRole() != access.RoleSuperAdmin || !ctx.RecentAuth {
writeConfigAccessError(w, errors.New("audit export requires recent super administrator authentication"))
if err := authorizeCapability(ctx, access.CapabilityAuditExport, "", false); err != nil {
writeConfigAccessError(w, err)
return
}
var input struct {
@@ -365,7 +365,7 @@ func publicConfigSection(runtime config.RuntimeConfig, section config.Section) (
publicSecret := func(value config.StoredSecret) config.SecretStatus { return value.Status() }
switch section {
case config.SectionRoot:
return map[string]any{"configVersion": runtime.Root.ConfigVersion, "schemaVersion": runtime.Root.SchemaVersion, "generation": runtime.Root.Generation, "setupState": runtime.Root.SetupState, "logLevel": runtime.Root.LogLevel, "domains": runtime.Root.Domains, "http": runtime.Root.HTTP, "database": map[string]any{"type": runtime.Root.Database.Type, "host": runtime.Root.Database.Host, "port": runtime.Root.Database.Port, "username": runtime.Root.Database.Username, "name": runtime.Root.Database.Name, "sqliteLocalRef": runtime.Root.Database.SQLiteLocalRef, "password": publicSecret(runtime.Root.Database.Password)}, "security": runtime.Root.Security}, nil
return map[string]any{"configVersion": runtime.Root.ConfigVersion, "schemaVersion": runtime.Root.SchemaVersion, "generation": runtime.Root.Generation, "setupState": runtime.Root.SetupState, "logLevel": runtime.Root.LogLevel, "domains": runtime.Root.Domains, "http": runtime.Root.HTTP, "database": map[string]any{"type": runtime.Root.Database.Type, "host": runtime.Root.Database.Host, "port": runtime.Root.Database.Port, "username": runtime.Root.Database.Username, "name": runtime.Root.Database.Name, "localRef": runtime.Root.Database.LocalRef, "password": publicSecret(runtime.Root.Database.Password)}, "security": runtime.Root.Security}, nil
case config.SectionSMTP:
return map[string]any{"meta": runtime.SMTP.Meta, "relay": map[string]any{"relayHost": runtime.SMTP.Relay.RelayHost, "relayPort": runtime.SMTP.Relay.RelayPort, "username": runtime.SMTP.Relay.Username, "security": runtime.SMTP.Relay.Security, "fromDomain": runtime.SMTP.Relay.FromDomain, "verificationEnabled": runtime.SMTP.Relay.VerificationEnabled, "loginPolicy": runtime.SMTP.Relay.LoginPolicy, "password": publicSecret(runtime.SMTP.Relay.Password)}}, nil
case config.SectionEmail:
@@ -387,6 +387,11 @@ func writeConfigAccessError(w http.ResponseWriter, err error) { writeConfigError
func writeConfigError(w http.ResponseWriter, err error) {
status := response.NoAccessPrivileges
message := "无权访问或请求不满足安全条件"
var data any = ""
var denial *access.Denial
if errors.As(err, &denial) {
data = map[string]string{"code": string(denial.Code)}
}
if errors.Is(err, config.ErrManagerStorage) {
status = response.ServerError
message = "配置服务不可用"
@@ -395,5 +400,5 @@ func writeConfigError(w http.ResponseWriter, err error) {
status = response.ParamsError
message = "配置已发生变化,请刷新后重试"
}
response.NewErrorResponse(status, message, "").FPrint(w)
response.NewErrorResponse(status, message, data).FPrint(w)
}
+42
View File
@@ -0,0 +1,42 @@
package controllers
import (
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"git.pcux.cn/xuans/Smail/dto/response"
"git.pcux.cn/xuans/Smail/services/access"
)
func TestWriteConfigErrorKeepsStableAuthorizationCode(t *testing.T) {
recorder := httptest.NewRecorder()
writeConfigError(recorder, &access.Denial{Code: access.CodeRecoveryCodeRequired})
var payload struct {
ErrorNo int `json:"errorNo"`
Data map[string]any `json:"data"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
t.Fatalf("failed to decode authorization error response: %v", err)
}
if payload.ErrorNo != response.NoAccessPrivileges {
t.Fatalf("unexpected authorization error number: %d", payload.ErrorNo)
}
if payload.Data["code"] != string(access.CodeRecoveryCodeRequired) {
t.Fatalf("stable authorization code was not exposed: %#v", payload.Data)
}
}
func TestWriteConfigErrorDoesNotExposeInternalErrorText(t *testing.T) {
recorder := httptest.NewRecorder()
writeConfigError(recorder, &access.Denial{Code: access.CodeRecentAuthRequired})
body := strings.ToLower(recorder.Body.String())
for _, forbidden := range []string{"password", "secret", "token", "nonce", "ticket", "challenge"} {
if strings.Contains(body, forbidden) {
t.Fatalf("authorization response contains sensitive response text: %s", body)
}
}
}
+24
View File
@@ -80,3 +80,27 @@ func TestCustomMigrationChecksumIncludesSeed(t *testing.T) {
t.Fatal("custom migration checksum ignored its seed")
}
}
func TestDefaultMigrationsAreContiguousAndDialectComplete(t *testing.T) {
migrations := DefaultMigrations()
if len(migrations) == 0 {
t.Fatal("default migrations are empty")
}
for index, item := range migrations {
wantVersion := int64(index + 1)
if item.Version != wantVersion {
t.Fatalf("migration %d has version %d, want %d", index, item.Version, wantVersion)
}
if item.Name == "" {
t.Fatalf("migration %d has an empty name", item.Version)
}
for _, dialect := range []Dialect{DialectSQLite, DialectMySQL, DialectPostgres} {
if item.Apply == nil && len(item.StatementsFor(dialect)) == 0 {
t.Fatalf("migration %d (%s) has no statements for %s", item.Version, item.Name, dialect)
}
}
}
if _, err := normalize(migrations); err != nil {
t.Fatalf("default migrations failed normalization: %v", err)
}
}
@@ -0,0 +1,31 @@
package http_server
import (
"net/http"
"net/http/httptest"
"testing"
appcontext "git.pcux.cn/xuans/Smail/utils/context"
)
func TestConfigRouteAcceptsConfigurationUpdateMethod(t *testing.T) {
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPut, "/api/v1/config/email", nil)
configRoute(&appcontext.Context{}, recorder, request)
if recorder.Code == http.StatusMethodNotAllowed {
t.Fatal("configuration update route rejected the documented PUT method")
}
}
func TestConfigRouteRejectsUnsupportedMethod(t *testing.T) {
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPatch, "/api/v1/config/email", nil)
configRoute(&appcontext.Context{}, recorder, request)
if recorder.Code != http.StatusMethodNotAllowed {
t.Fatalf("unsupported configuration method returned status %d", recorder.Code)
}
}
+7 -3
View File
@@ -169,10 +169,14 @@ func configRoute(ctx *context.Context, w http.ResponseWriter, r *http.Request) {
}
controllers.ApplyConfig(ctx, w, r)
case configSectionRoute(path, ""):
if !allowRouteMethod(w, r, http.MethodGet) {
return
switch r.Method {
case http.MethodGet:
controllers.GetConfigSection(ctx, w, r)
case http.MethodPut:
controllers.UpdateConfig(ctx, w, r)
default:
allowRouteMethod(w, r, http.MethodGet, http.MethodPut)
}
controllers.GetConfigSection(ctx, w, r)
default:
http.NotFound(w, r)
}
+22 -6
View File
@@ -57,12 +57,12 @@ func TestRecoveryAndRecentAuthentication(t *testing.T) {
t.Fatalf("expected recent authentication requirement, got %v", err)
}
superAdmin := Request{ActorRole: RoleSuperAdmin, Capability: CapabilityConfigRollback, RecentAuth: true}
if err := Authorize(superAdmin); !IsDenied(err, CodeRecoveryCodeRequired) {
t.Fatalf("super admin without recovery code must be denied: %v", err)
}
superAdmin.RecoveryCodeConfigured = true
if err := Authorize(superAdmin); err != nil {
t.Fatalf("super admin with recovery code should be allowed: %v", err)
t.Fatalf("super admin should be exempt from recovery code precondition: %v", err)
}
adminRollback := Request{ActorRole: RoleAdmin, Capability: CapabilityConfigRollback, RecentAuth: true}
if err := Authorize(adminRollback); !IsDenied(err, CodeAccessDenied) {
t.Fatalf("admin must not receive a recovery-code bypass for a super-admin capability: %v", err)
}
}
@@ -90,7 +90,7 @@ func TestAdminPluginRestartScope(t *testing.T) {
func TestManagementEndpointCatalog(t *testing.T) {
endpoints := ManagementEndpoints()
if len(endpoints) != 7 {
if len(endpoints) != 18 {
t.Fatalf("unexpected endpoint count: %d", len(endpoints))
}
seen := map[string]struct{}{}
@@ -108,6 +108,22 @@ func TestManagementEndpointCatalog(t *testing.T) {
if !ok || endpoint.Capability != CapabilityPluginWriteOwn {
t.Fatal("plugin settings endpoint was not matched")
}
endpoint, ok = LookupEndpoint("POST", "/api/v1/config/smtp/validate")
if !ok || endpoint.Capability != CapabilityConfigWriteGlobal {
t.Fatal("configuration validation endpoint was not matched")
}
endpoint, ok = LookupEndpoint("GET", "/api/v1/config/email")
if !ok || endpoint.Capability != CapabilityConfigRead {
t.Fatal("configuration section endpoint was not matched")
}
endpoint, ok = LookupEndpoint("PUT", "/api/v1/config/email")
if !ok || endpoint.Capability != CapabilityConfigWriteGlobal {
t.Fatal("configuration update endpoint was not matched")
}
endpoint, ok = LookupEndpoint("GET", "/api/v1/config/backups")
if !ok || endpoint.Capability != CapabilityConfigRollback {
t.Fatal("configuration backup endpoint did not require rollback capability")
}
}
func TestEveryManagementEndpointHasAllowAndDeny(t *testing.T) {
+1 -1
View File
@@ -55,7 +55,7 @@ func Authorize(request Request) error {
if policy.RequiresRecentAuth && !request.RecentAuth {
return deny(CodeRecentAuthRequired)
}
if policy.RequiresRecoveryCode && !request.RecoveryCodeConfigured && !request.DeploymentChannel {
if policy.RequiresRecoveryCode && request.ActorRole != RoleSuperAdmin && !request.RecoveryCodeConfigured && !request.DeploymentChannel {
return deny(CodeRecoveryCodeRequired)
}
return authorizeResource(request)
+3 -1
View File
@@ -20,6 +20,7 @@ const (
CapabilityPasswordChangeOwn Capability = "password.change_own"
CapabilityPasswordReset Capability = "password.reset"
CapabilityAuditRead Capability = "audit.read"
CapabilityAuditExport Capability = "audit.export"
)
type Policy struct {
@@ -48,6 +49,7 @@ var policies = map[Capability]Policy{
CapabilityPasswordChangeOwn: {Capability: CapabilityPasswordChangeOwn},
CapabilityPasswordReset: {Capability: CapabilityPasswordReset, HighRisk: true, RequiresRecentAuth: true, RequiresRecoveryCode: true, RequiresTarget: true},
CapabilityAuditRead: {Capability: CapabilityAuditRead},
CapabilityAuditExport: {Capability: CapabilityAuditExport, HighRisk: true, RequiresRecentAuth: true},
}
var grants = map[Role]map[Capability]struct{}{
@@ -57,7 +59,7 @@ var grants = map[Role]map[Capability]struct{}{
CapabilityPluginRestart, CapabilityServiceRestart, CapabilityPluginWriteGlobal, CapabilityPluginWriteAnyUser,
CapabilityPluginWriteOwn, CapabilityUserRead, CapabilityUserManage,
CapabilityRoleManage, CapabilityPasswordChangeOwn, CapabilityPasswordReset,
CapabilityAuditRead,
CapabilityAuditRead, CapabilityAuditExport,
),
RoleAdmin: grant(
CapabilityConfigRead, CapabilityPluginRead, CapabilityPluginRestart,
+38 -4
View File
@@ -16,6 +16,17 @@ var managementEndpoints = []Endpoint{
{Method: "POST", Path: "/api/user/list", Capability: CapabilityUserRead},
{Method: "GET", Path: "/api/plugin/list", Capability: CapabilityPluginRead},
{Method: "*", Path: "/api/plugin/settings/", Capability: CapabilityPluginWriteOwn},
{Method: "GET", Path: "/api/v1/config/status", Capability: CapabilityConfigRead},
{Method: "GET", Path: "/api/v1/config/backups", Capability: CapabilityConfigRollback},
{Method: "POST", Path: "/api/v1/config/rollback/preview", Capability: CapabilityConfigRollback},
{Method: "POST", Path: "/api/v1/config/rollback/ticket", Capability: CapabilityConfigRollback},
{Method: "POST", Path: "/api/v1/config/rollback", Capability: CapabilityConfigRollback},
{Method: "POST", Path: "/api/v1/config/:section/validate", Capability: CapabilityConfigWriteGlobal},
{Method: "POST", Path: "/api/v1/config/:section/apply", Capability: CapabilityConfigWriteGlobal},
{Method: "GET", Path: "/api/v1/config/:section", Capability: CapabilityConfigRead},
{Method: "PUT", Path: "/api/v1/config/:section", Capability: CapabilityConfigWriteGlobal},
{Method: "GET", Path: "/api/v1/audits/config", Capability: CapabilityAuditRead},
{Method: "POST", Path: "/api/v1/audits/config", Capability: CapabilityAuditExport},
}
func ManagementEndpoints() []Endpoint {
@@ -28,13 +39,36 @@ func LookupEndpoint(method string, path string) (Endpoint, bool) {
method = strings.ToUpper(strings.TrimSpace(method))
for _, endpoint := range managementEndpoints {
methodMatches := endpoint.Method == "*" || endpoint.Method == method
pathMatches := endpoint.Path == path
if strings.HasSuffix(endpoint.Path, "/") {
pathMatches = strings.HasPrefix(path, endpoint.Path)
}
pathMatches := matchEndpointPath(endpoint.Path, path)
if methodMatches && pathMatches {
return endpoint, true
}
}
return Endpoint{}, false
}
func matchEndpointPath(pattern, path string) bool {
if pattern == path {
return true
}
if strings.HasSuffix(pattern, "/") {
return strings.HasPrefix(path, pattern)
}
patternParts := strings.Split(strings.Trim(pattern, "/"), "/")
pathParts := strings.Split(strings.Trim(path, "/"), "/")
if len(patternParts) != len(pathParts) {
return false
}
for index := range patternParts {
if strings.HasPrefix(patternParts[index], ":") && patternParts[index] != ":" {
if pathParts[index] == "" {
return false
}
continue
}
if patternParts[index] != pathParts[index] {
return false
}
}
return true
}
+1
View File
@@ -12,6 +12,7 @@ func TestCapabilityMatrix(t *testing.T) {
{name: "admin reads config", req: Request{ActorRole: RoleAdmin, Capability: CapabilityConfigRead}, allowed: true},
{name: "user cannot read config", req: Request{ActorRole: RoleUser, Capability: CapabilityConfigRead}},
{name: "super admin controls plugin", req: Request{ActorRole: RoleSuperAdmin, Capability: CapabilityPluginControl, RecentAuth: true, RecoveryCodeConfigured: true}, allowed: true},
{name: "super admin controls plugin without recovery code", req: Request{ActorRole: RoleSuperAdmin, Capability: CapabilityPluginControl, RecentAuth: true}, allowed: true},
{name: "admin cannot control plugin", req: Request{ActorRole: RoleAdmin, Capability: CapabilityPluginControl, RecentAuth: true, RecoveryCodeConfigured: true}},
{name: "super admin writes global plugin settings", req: Request{ActorRole: RoleSuperAdmin, Capability: CapabilityPluginWriteGlobal, RecentAuth: true, RecoveryCodeConfigured: true}, allowed: true},
{name: "admin cannot write global plugin settings", req: Request{ActorRole: RoleAdmin, Capability: CapabilityPluginWriteGlobal, RecentAuth: true, RecoveryCodeConfigured: true}},