完成安全整改、配置重构与邮件认证优化
Security Checks / security (push) Waiting to run

This commit is contained in:
xuans committed 2026-08-28 14:33:13 +08:00
1 parent 18b6dfbdf7
commit dd04bdb49e
83 files changed
+4547 -583

No files matched your search

+41 -3
View File
@@ -365,9 +365,41 @@ 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, "localRef": runtime.Root.Database.LocalRef, "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": nil,
},
"databasePasswordStatus": 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
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": nil,
},
"relayPasswordStatus": publicSecret(runtime.SMTP.Relay.Password),
}, nil
case config.SectionEmail:
return runtime.Email, nil
case config.SectionSSL:
@@ -375,7 +407,13 @@ func publicConfigSection(runtime config.RuntimeConfig, section config.Section) (
case config.SectionPlugins:
plugins := make(map[string]any, len(runtime.Plugins.Plugins))
for id, item := range runtime.Plugins.Plugins {
plugins[id] = map[string]any{"enabled": item.Enabled, "executable": item.Executable, "permissions": item.Permissions, "settingsConfigured": len(item.Settings) > 0}
plugins[id] = map[string]any{
"enabled": item.Enabled,
"executable": item.Executable,
"permissions": item.Permissions,
"settings": nil,
"secretStatus": publicSecret(item.Secret),
}
}
return map[string]any{"meta": runtime.Plugins.Meta, "plugins": plugins}, nil
default:
@@ -0,0 +1,136 @@
package controllers
import (
"encoding/json"
"strings"
"testing"
"time"
"git.pcux.cn/xuans/Smail/config"
"git.pcux.cn/xuans/Smail/utils/credential"
)
func TestPublicConfigSectionsDoNotExposeSecretsAndRemainStrictlyDecodable(t *testing.T) {
runtime := config.RuntimeConfig{
Generation: 7,
SetupState: config.SetupStateReady,
Root: config.RootConfig{
ConfigVersion: config.CurrentConfigVersion,
SchemaVersion: config.CurrentSchemaVersion,
Generation: 7,
SetupState: config.SetupStateReady,
Database: config.DatabaseConfig{
Type: config.DatabaseTypeMySQL,
Host: "127.0.0.1",
Port: config.DefaultMySQLPort,
Username: "smail",
Name: "smail",
Password: config.StoredSecret{Ciphertext: "enc:v1:database-secret", Version: credential.CurrentVersion, UpdatedAt: time.Now().UTC()},
},
},
SMTP: config.SMTPSectionConfig{
Meta: config.SectionMeta{Schema: config.CurrentSectionSchema, Generation: 7},
Relay: config.SMTPConfig{
RelayHost: "smtp.example.com",
RelayPort: 587,
Username: "relay-user",
Password: config.StoredSecret{Ciphertext: "enc:v1:relay-secret", Version: credential.CurrentVersion, UpdatedAt: time.Now().UTC()},
Security: "starttls",
},
},
Email: config.EmailSectionConfig{Meta: config.SectionMeta{Schema: config.CurrentSectionSchema, Generation: 7}},
SSL: config.SSLSectionConfig{Meta: config.SectionMeta{Schema: config.CurrentSectionSchema, Generation: 7}},
Plugins: config.PluginsSectionConfig{
Meta: config.SectionMeta{Schema: config.CurrentSectionSchema, Generation: 7},
Plugins: map[string]config.PluginInstance{
"sample": {
Enabled: true, Executable: "sample.exe", Permissions: config.PluginPermissions{},
Secret: config.StoredSecret{Ciphertext: "enc:v1:plugin-secret", Version: credential.CurrentVersion, UpdatedAt: time.Now().UTC()},
},
},
},
}
tests := []struct {
section config.Section
decode func([]byte) error
}{
{config.SectionRoot, func(data []byte) error {
var value config.RootConfig
return config.ParseStrict(data, &value)
}},
{config.SectionSMTP, func(data []byte) error {
var value config.SMTPSectionConfig
return config.ParseStrict(data, &value)
}},
{config.SectionEmail, func(data []byte) error {
var value config.EmailSectionConfig
return config.ParseStrict(data, &value)
}},
{config.SectionSSL, func(data []byte) error {
var value config.SSLSectionConfig
return config.ParseStrict(data, &value)
}},
{config.SectionPlugins, func(data []byte) error {
var value config.PluginsSectionConfig
return config.ParseStrict(data, &value)
}},
}
for _, test := range tests {
t.Run(string(test.section), func(t *testing.T) {
public, err := publicConfigSection(runtime, test.section)
if err != nil {
t.Fatal(err)
}
data, err := json.Marshal(public)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(data), "database-secret") || strings.Contains(string(data), "relay-secret") {
t.Fatalf("public configuration contains secret data: %s", data)
}
writableData := make(map[string]json.RawMessage)
if err := json.Unmarshal(data, &writableData); err != nil {
t.Fatalf("public configuration is not a JSON object: %v", err)
}
delete(writableData, "databasePasswordStatus")
delete(writableData, "relayPasswordStatus")
if test.section == config.SectionPlugins {
var plugins map[string]json.RawMessage
if err := json.Unmarshal(writableData["plugins"], &plugins); err != nil {
t.Fatalf("plugin public configuration is not an object: %v", err)
}
for id, raw := range plugins {
var plugin map[string]json.RawMessage
if err := json.Unmarshal(raw, &plugin); err != nil {
t.Fatalf("plugin %q public configuration is not an object: %v", id, err)
}
status, ok := plugin["secretStatus"]
if !ok || !strings.Contains(string(status), `"configured":true`) || !strings.Contains(string(status), `"hint":"******"`) {
t.Fatalf("plugin %q secret status is incomplete: %s", id, status)
}
if strings.Contains(string(status), "plugin-secret") || strings.Contains(string(status), "enc:v1:") {
t.Fatalf("plugin %q secret status exposed secret material: %s", id, status)
}
delete(plugin, "secretStatus")
plugins[id], err = json.Marshal(plugin)
if err != nil {
t.Fatal(err)
}
}
writableData["plugins"], err = json.Marshal(plugins)
if err != nil {
t.Fatal(err)
}
}
data, err = json.Marshal(writableData)
if err != nil {
t.Fatal(err)
}
if err := test.decode(data); err != nil {
t.Fatalf("public configuration is not strictly decodable: %v; data=%s", err, data)
}
})
}
}
+37 -13
View File
@@ -11,9 +11,10 @@ import (
"git.pcux.cn/xuans/Smail/config"
"git.pcux.cn/xuans/Smail/dto/response"
"git.pcux.cn/xuans/Smail/i18n"
"git.pcux.cn/xuans/Smail/models"
"git.pcux.cn/xuans/Smail/services/access"
"git.pcux.cn/xuans/Smail/services/auth"
"git.pcux.cn/xuans/Smail/session"
"git.pcux.cn/xuans/Smail/utils/array"
"git.pcux.cn/xuans/Smail/utils/context"
"git.pcux.cn/xuans/Smail/utils/csrf"
log "github.com/sirupsen/logrus"
@@ -98,6 +99,25 @@ func hashedLoginKey(parts ...string) string {
return hex.EncodeToString(hash.Sum(nil))
}
// loginSecurityFields returns the non-sensitive state used by the post-login security guide.
func loginSecurityFields(user *models.User) map[string]any {
fields := map[string]any{
"recoveryCodesConfigured": false,
"showRecoverySetupPrompt": false,
}
if user == nil || user.EffectiveRole() == access.RoleSuperAdmin {
return fields
}
configured := false
if service := credentialRuntime(); service != nil {
configured, _ = service.HasValidRecoveryCode(user.ID)
}
fields["recoveryCodesConfigured"] = configured
fields["showRecoverySetupPrompt"] = !configured
return fields
}
func (limiter *loginLimiter) blocked(key string) bool {
now := limiter.now()
limiter.mu.Lock()
@@ -229,22 +249,26 @@ func Login(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
return
}
currentConfig := config.CurrentConfig()
if currentConfig == nil {
domain, domains, ok := loginDomainSettings()
if !ok {
response.NewErrorResponse(response.ServerError, "登录失败", "").FPrint(w)
return
}
domains := currentConfig.Domains
domains = array.Difference(domains, []string{currentConfig.Domain})
domains = append([]string{currentConfig.Domain}, domains...)
domains = append([]string{domain}, domains...)
response.NewSuccessResponse(map[string]any{
"account": user.Account,
"name": user.Name,
"role": user.EffectiveRole(),
"is_admin": user.IsAdmin,
"domains": domains,
}).FPrint(w)
result := map[string]any{
"account": user.Account,
"name": user.Name,
"role": user.EffectiveRole(),
"capabilities": access.Capabilities(user.EffectiveRole()),
"is_admin": user.IsAdmin,
"domains": domains,
"must_change_password": user.MustChangePassword != 0,
}
for key, value := range loginSecurityFields(user) {
result[key] = value
}
response.NewSuccessResponse(result).FPrint(w)
}
func Logout(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
+15
View File
@@ -6,8 +6,23 @@ import (
"strings"
"testing"
"time"
"git.pcux.cn/xuans/Smail/models"
"git.pcux.cn/xuans/Smail/services/access"
)
func TestLoginSecurityFieldsByRole(t *testing.T) {
ordinary := loginSecurityFields(&models.User{ID: 1, Role: string(access.RoleUser)})
if ordinary["recoveryCodesConfigured"] != false || ordinary["showRecoverySetupPrompt"] != true {
t.Fatalf("ordinary user security fields = %#v", ordinary)
}
superAdmin := loginSecurityFields(&models.User{ID: 2, Role: string(access.RoleSuperAdmin)})
if superAdmin["recoveryCodesConfigured"] != false || superAdmin["showRecoverySetupPrompt"] != false {
t.Fatalf("super administrator security fields = %#v", superAdmin)
}
}
func TestLoginLimiterBlocksAndExpires(t *testing.T) {
limiter := newLoginLimiter()
now := time.Date(2026, 8, 24, 12, 0, 0, 0, time.UTC)
+128 -11
View File
@@ -11,6 +11,7 @@ import (
"git.pcux.cn/xuans/Smail/db"
"git.pcux.cn/xuans/Smail/dto/response"
"git.pcux.cn/xuans/Smail/models"
"git.pcux.cn/xuans/Smail/services/access"
"git.pcux.cn/xuans/Smail/services/verification"
"git.pcux.cn/xuans/Smail/session"
"git.pcux.cn/xuans/Smail/utils/array"
@@ -40,6 +41,10 @@ type loginVerificationItem struct {
ExpiresAt time.Time
}
type resendLoginVerificationRequest struct {
ID string `json:"id"`
Account string `json:"account"`
}
type loginVerificationRequest struct {
ID string `json:"id"`
Account string `json:"account"`
@@ -49,11 +54,24 @@ type loginVerificationRequest struct {
}
func loginVerificationEnabled() bool {
if manager := config.CurrentManager(); manager != nil {
runtime := manager.Snapshot()
if runtime.SetupState == config.SetupStateReady {
return loginVerificationPolicyEnabled(runtime.SMTP.Relay.VerificationEnabled, runtime.SMTP.Relay.LoginPolicy)
}
}
current := config.CurrentConfig()
if current == nil || !current.VerificationEnabled {
if current == nil {
return false
}
switch strings.ToLower(strings.TrimSpace(current.LoginPolicy)) {
return loginVerificationPolicyEnabled(current.VerificationEnabled, current.LoginPolicy)
}
func loginVerificationPolicyEnabled(enabled bool, policy string) bool {
if !enabled {
return false
}
switch strings.ToLower(strings.TrimSpace(policy)) {
case "", "off":
return false
case "always", "new_device":
@@ -108,6 +126,58 @@ func beginLoginVerification(user *models.User, remoteIP string) (map[string]any,
}, nil
}
// ResendLoginVerification 使旧登录验证码失效后重新发送新验证码。
func ResendLoginVerification(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
var input resendLoginVerificationRequest
if err := decodeJSONRequest(w, req, &input); err != nil || strings.TrimSpace(input.ID) == "" {
writeSecurityError(w, response.ParamsError, "验证码请求无效")
return
}
loginVerificationState.Lock()
cleanupLoginVerificationLocked(time.Now())
item, ok := loginVerificationState.items[input.ID]
if ok {
delete(loginVerificationState.items, input.ID)
}
loginVerificationState.Unlock()
if !ok || !strings.EqualFold(strings.TrimSpace(input.Account), item.Account) {
writeSecurityError(w, response.ParamsError, "登录验证已失效,请重新登录")
return
}
if securityRuntime.verification == nil || securityRuntime.verification.Store == nil {
writeSecurityError(w, response.ParamsError, "验证码服务暂不可用")
return
}
securityRuntime.verification.Store.InvalidateChallenge(input.ID)
challenge, err := securityRuntime.verification.Issue(verification.IssueRequest{
Purpose: verification.PurposeLogin,
UserID: item.UserID,
Account: item.Account,
Email: item.Email,
TTL: loginVerificationTTL,
}, remoteIP(req))
if err != nil {
writeSecurityError(w, response.ParamsError, "验证码发送失败,请稍后重试")
return
}
loginVerificationState.Lock()
cleanupLoginVerificationLocked(time.Now())
loginVerificationState.items[challenge.ID] = loginVerificationItem{
UserID: item.UserID, Account: item.Account, Email: item.Email,
SessionVersion: item.SessionVersion, ExpiresAt: challenge.ExpiresAt,
}
loginVerificationState.Unlock()
response.NewSuccessResponse(map[string]any{
"pending": true,
"challenge_id": challenge.ID,
"expires_at": challenge.ExpiresAt.UTC(),
"email": maskEmail(item.Email),
"account": item.Account,
}).FPrint(w)
}
// CompleteLoginVerification 只有验证码成功后才创建完整 Session。
func CompleteLoginVerification(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
var input loginVerificationRequest
@@ -174,16 +244,63 @@ func completeLoginSession(ctx *context.Context, w http.ResponseWriter, req *http
response.NewErrorResponse(response.ServerError, "登录失败", "").FPrint(w)
return
}
cfg := config.CurrentConfig()
if cfg == nil || cfg.Domain == "" {
domain, domains, ok := loginDomainSettings()
if !ok {
response.NewErrorResponse(response.ServerError, "登录失败", "").FPrint(w)
return
}
domains := cfg.Domains
domains = array.Difference(domains, []string{cfg.Domain})
domains = append([]string{cfg.Domain}, domains...)
response.NewSuccessResponse(map[string]any{
"account": user.Account, "name": user.Name, "role": user.EffectiveRole(),
"is_admin": user.IsAdmin, "domains": domains,
}).FPrint(w)
domains = append([]string{domain}, domains...)
result := map[string]any{
"account": user.Account,
"name": user.Name,
"role": user.EffectiveRole(),
"capabilities": access.Capabilities(user.EffectiveRole()),
"is_admin": user.IsAdmin,
"domains": domains,
"must_change_password": user.MustChangePassword != 0,
}
for key, value := range loginSecurityFields(user) {
result[key] = value
}
response.NewSuccessResponse(result).FPrint(w)
}
func loginDomainSettings() (string, []string, bool) {
if manager := config.CurrentManager(); manager != nil {
runtime := manager.Snapshot()
primary := strings.TrimSpace(runtime.Root.Domains.Primary)
if primary == "" {
return "", nil, false
}
domains := append([]string(nil), runtime.Root.Domains.Accepted...)
domains = array.Difference(domains, []string{primary})
return primary, domains, true
}
current := config.CurrentConfig()
if current == nil || strings.TrimSpace(current.Domain) == "" {
return "", nil, false
}
domains := array.Difference(append([]string(nil), current.Domains...), []string{current.Domain})
return current.Domain, domains, true
}
func pendingLoginVerification(challengeID, account string) (loginVerificationItem, bool) {
loginVerificationState.Lock()
defer loginVerificationState.Unlock()
cleanupLoginVerificationLocked(time.Now())
item, ok := loginVerificationState.items[strings.TrimSpace(challengeID)]
if !ok || !strings.EqualFold(strings.TrimSpace(account), item.Account) {
return loginVerificationItem{}, false
}
return item, true
}
func consumePendingLoginVerification(challengeID string, expected loginVerificationItem) bool {
loginVerificationState.Lock()
defer loginVerificationState.Unlock()
item, ok := loginVerificationState.items[strings.TrimSpace(challengeID)]
if !ok || item.UserID != expected.UserID || item.SessionVersion != expected.SessionVersion || !strings.EqualFold(item.Account, expected.Account) {
return false
}
delete(loginVerificationState.items, strings.TrimSpace(challengeID))
return true
}
@@ -0,0 +1,26 @@
package controllers
import "testing"
func TestLoginVerificationPolicyEnabled(t *testing.T) {
tests := []struct {
name string
enabled bool
policy string
want bool
}{
{name: "disabled", enabled: false, policy: "always", want: false},
{name: "empty policy is disabled", enabled: true, policy: "", want: false},
{name: "off policy is disabled", enabled: true, policy: "off", want: false},
{name: "always policy is enabled", enabled: true, policy: "always", want: true},
{name: "new device policy is enabled", enabled: true, policy: "new_device", want: true},
{name: "policy is case insensitive", enabled: true, policy: "ALWAYS", want: true},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := loginVerificationPolicyEnabled(test.enabled, test.policy); got != test.want {
t.Fatalf("login verification policy result = %v, want %v", got, test.want)
}
})
}
}
@@ -10,6 +10,7 @@ import (
"git.pcux.cn/xuans/Smail/config"
"git.pcux.cn/xuans/Smail/db"
"git.pcux.cn/xuans/Smail/dto/response"
"git.pcux.cn/xuans/Smail/models"
"git.pcux.cn/xuans/Smail/services/access"
"git.pcux.cn/xuans/Smail/services/auth"
@@ -177,3 +178,38 @@ func assertUserPassword(t *testing.T, userID int, plainPassword string) {
func authPasswordMatches(hash, plain string) bool {
return password.Verify(hash, plain)
}
func TestSuperAdminCannotChangePasswordThroughWeb(t *testing.T) {
testRoot := t.TempDir()
oldConfig := config.Instance
oldDB := db.Instance
t.Cleanup(func() {
if db.Instance != nil && db.Instance != oldDB {
_ = db.Instance.Close()
}
config.Instance = oldConfig
db.Instance = oldDB
})
config.Instance = &config.Config{DbType: config.DBTypeSQLite, DbDSN: filepath.Join(testRoot, "web-password.db")}
if err := db.Init(""); err != nil {
t.Fatal(err)
}
user := newControllerTestUser(t, "web-super-admin", "super admin", access.RoleSuperAdmin, "OldPass123")
if _, err := db.Instance.Insert(&user); err != nil {
t.Fatal(err)
}
ctx := &appcontext.Context{UserID: user.ID, UserAccount: user.Account, Role: access.RoleSuperAdmin, Lang: "zhCn"}
request := httptest.NewRequest(http.MethodPost, "/api/settings/modify_password", strings.NewReader(`{"current_password":"OldPass123","password":"NewPass123"}`))
recorder := httptest.NewRecorder()
ModifyPassword(ctx, recorder, request)
var result struct {
ErrorNo int `json:"errorNo"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil {
t.Fatal(err)
}
if result.ErrorNo != response.NoAccessPrivileges {
t.Fatalf("expected web reset to be denied, got %d", result.ErrorNo)
}
assertUserPassword(t, user.ID, "OldPass123")
}
+25
View File
@@ -12,6 +12,7 @@ import (
"git.pcux.cn/xuans/Smail/config"
"git.pcux.cn/xuans/Smail/db"
"git.pcux.cn/xuans/Smail/dto/response"
"git.pcux.cn/xuans/Smail/services/access"
"git.pcux.cn/xuans/Smail/services/credentials"
"git.pcux.cn/xuans/Smail/services/externalemail"
"git.pcux.cn/xuans/Smail/services/recovery"
@@ -79,6 +80,9 @@ func ConfigureSecurityRuntime(verify *verification.Service, external *externalem
securityRuntime.external = external
securityRuntime.recovery = recover
securityRuntime.credentials = credential
if recover != nil {
recover.SetSecurityStateInvalidator(InvalidateSecurityRuntimeUser)
}
}
func ConfigureWebAuthnRuntime(service *webauthnservice.Service) {
@@ -112,6 +116,10 @@ func LoadSecurityContext(ctx *context.Context) {
if ctx == nil || ctx.UserID <= 0 {
return
}
if ctx.EffectiveRole() == access.RoleSuperAdmin {
ctx.RecoveryCodeConfigured = false
return
}
service := securityRuntime.credentials
if service == nil && db.Instance != nil {
service, _ = credentials.NewService(db.Instance)
@@ -180,6 +188,14 @@ type recoveryCodeRequest struct {
Count int `json:"count"`
}
func rejectSuperAdminRecoveryCodes(ctx *context.Context, w http.ResponseWriter) bool {
if ctx != nil && ctx.EffectiveRole() == access.RoleSuperAdmin {
writeSecurityError(w, response.NoAccessPrivileges, "超级管理员恢复码只能通过部署端专用通道管理")
return true
}
return false
}
// GetSecurityQuestion 返回当前用户的密保问题,不返回答案哈希。
func GetSecurityQuestion(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
if ctx == nil || ctx.UserID <= 0 {
@@ -229,6 +245,9 @@ func GenerateRecoveryCodes(ctx *context.Context, w http.ResponseWriter, req *htt
writeSecurityError(w, response.NeedLogin, "请先登录")
return
}
if rejectSuperAdminRecoveryCodes(ctx, w) {
return
}
var input recoveryCodeRequest
if req != nil && req.Body != nil {
if err := decodeJSONRequest(w, req, &input); err != nil {
@@ -256,6 +275,9 @@ func GetRecoveryCodeStatus(ctx *context.Context, w http.ResponseWriter, req *htt
writeSecurityError(w, response.NeedLogin, "请先登录")
return
}
if rejectSuperAdminRecoveryCodes(ctx, w) {
return
}
service := credentialRuntime()
if service == nil {
writeSecurityError(w, response.ServerError, "安全凭据服务不可用")
@@ -275,6 +297,9 @@ func RevokeRecoveryCodes(ctx *context.Context, w http.ResponseWriter, req *http.
writeSecurityError(w, response.NeedLogin, "请先登录")
return
}
if rejectSuperAdminRecoveryCodes(ctx, w) {
return
}
service := credentialRuntime()
if service == nil {
writeSecurityError(w, response.ServerError, "安全凭据服务不可用")
@@ -8,6 +8,7 @@ import (
"testing"
"git.pcux.cn/xuans/Smail/dto/response"
"git.pcux.cn/xuans/Smail/services/access"
appcontext "git.pcux.cn/xuans/Smail/utils/context"
)
@@ -45,3 +46,18 @@ func TestSecurityHandlersRejectUnauthenticatedRequests(t *testing.T) {
})
}
}
func TestSuperAdminCannotManageRecoveryCodesThroughWeb(t *testing.T) {
ctx := &appcontext.Context{UserID: 1, Role: access.RoleSuperAdmin}
request := httptest.NewRequest(http.MethodPost, "/api/security/credentials/recovery-codes", strings.NewReader(`{"count":5}`))
recorder := httptest.NewRecorder()
GenerateRecoveryCodes(ctx, recorder, request)
var result response.Response
if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil {
t.Fatalf("invalid JSON response: %v", err)
}
if result.ErrorNo != response.NoAccessPrivileges {
t.Fatalf("error number = %d, want %d; body=%s", result.ErrorNo, response.NoAccessPrivileges, recorder.Body.String())
}
}
@@ -196,15 +196,15 @@ func TestPasswordRecoveryBeginResponsesDoNotRevealAccountState(t *testing.T) {
}
}
func TestWebAuthnLoginBeginResponsesIgnoreIdentifier(t *testing.T) {
func TestWebAuthnLoginBeginRequiresPendingLoginTransaction(t *testing.T) {
_, webAuthnService, _, _, _ := newPublicSecurityFixture(t)
previous := securityRuntime
securityRuntime.webauthn = webAuthnService
t.Cleanup(func() { securityRuntime = previous })
bodies := []string{`{}`, `{"identifier":"alice"}`, `{"identifier":"missing"}`}
bodies := []string{`{}`, `{"challenge_id":"unknown","account":"alice"}`, `{"challenge_id":"unknown","account":"missing"}`}
baselineStatus, baseline, baselineShape := invokePublicSecurityHandler(t, BeginWebAuthnLogin, bodies[0])
if baseline.ErrorNo != 0 || baseline.ErrorMsg != "" {
if baseline.ErrorNo == 0 || baseline.ErrorMsg == "" {
t.Fatalf("unexpected baseline response: %+v", baseline)
}
for _, body := range bodies[1:] {
+26 -11
View File
@@ -7,6 +7,7 @@ import (
"git.pcux.cn/xuans/Smail/dto/response"
"git.pcux.cn/xuans/Smail/i18n"
"git.pcux.cn/xuans/Smail/models"
"git.pcux.cn/xuans/Smail/services/access"
"git.pcux.cn/xuans/Smail/services/auth"
"git.pcux.cn/xuans/Smail/session"
"git.pcux.cn/xuans/Smail/utils/context"
@@ -15,6 +16,7 @@ import (
log "github.com/sirupsen/logrus"
"net/http"
"strings"
"time"
)
type modifyPasswordRequest struct {
@@ -27,6 +29,10 @@ func ModifyPassword(ctx *context.Context, w http.ResponseWriter, req *http.Reque
response.NewErrorResponse(response.NoAccessPrivileges, "未登录用户不能修改密码", "").FPrint(w)
return
}
if ctx.EffectiveRole() == access.RoleSuperAdmin {
response.NewErrorResponse(response.NoAccessPrivileges, "\u8d85\u7ea7\u7ba1\u7406\u5458\u5fc5\u987b\u901a\u8fc7\u90e8\u7f72\u7aef\u4e13\u7528\u901a\u9053\u91cd\u7f6e\u5bc6\u7801", "").FPrint(w)
return
}
var retData modifyPasswordRequest
if err := decodeJSONRequest(w, req, &retData); err != nil {
log.WithContext(ctx).Debug("invalid password change request")
@@ -56,7 +62,18 @@ func ModifyPassword(ctx *context.Context, w http.ResponseWriter, req *http.Reque
loginPairAttempts.clear(pairKey)
loginAccountAttempts.clear(accountKey)
user := models.User{ID: ctx.UserID, SessionVersion: currentUser.SessionVersion + 1}
securityVersion := currentUser.SecurityVersion + 1
if securityVersion <= 0 {
securityVersion = 1
}
now := time.Now().UTC()
user := models.User{
ID: ctx.UserID,
SessionVersion: currentUser.SessionVersion + 1,
SecurityVersion: securityVersion,
MustChangePassword: 0,
PasswordChangedAt: &now,
}
if err := auth.SetPassword(&user, retData.Password); err != nil {
if errors.Is(err, password.ErrInvalidLength) {
response.NewErrorResponse(response.ParamsError, "\u5bc6\u7801\u957f\u5ea6\u5fc5\u987b\u4e3a 8-256 \u5b57\u8282", "").FPrint(w)
@@ -90,7 +107,7 @@ func ModifyPassword(ctx *context.Context, w http.ResponseWriter, req *http.Reque
}
}()
affected, err := tx.Where("id = ? and password = ? and session_version = ?", ctx.UserID, currentUser.Password, currentUser.SessionVersion).Cols("password", "session_version").Update(&user)
affected, err := tx.Where("id = ? and password = ? and session_version = ?", ctx.UserID, currentUser.Password, currentUser.SessionVersion).Cols("password", "session_version", "security_version", "must_change_password", "password_changed_at").Update(&user)
if err != nil {
log.WithContext(ctx).WithError(err).Error("update password failed")
response.NewErrorResponse(response.ServerError, i18n.GetText(ctx.Lang, "unknowError"), "").FPrint(w)
@@ -112,17 +129,15 @@ func ModifyPassword(ctx *context.Context, w http.ResponseWriter, req *http.Reque
return
}
committed = true
currentUser.Password = user.Password
currentUser.SessionVersion = user.SessionVersion
if err := session.PutUser(req.Context(), currentUser); err != nil {
if destroyErr := session.Instance.Destroy(req.Context()); destroyErr != nil {
log.WithContext(ctx).WithError(destroyErr).Error("session destruction after password refresh failure failed")
}
csrf.Clear(w, req, !config.DevelopmentMode)
log.WithContext(ctx).WithError(err).Error("refresh password change session failed")
if err := session.Instance.Destroy(req.Context()); err != nil {
log.WithContext(ctx).WithError(err).Error("session destruction after password change failed")
response.NewErrorResponse(response.ServerError, i18n.GetText(ctx.Lang, "unknowError"), "").FPrint(w)
return
}
csrf.Clear(w, req, !config.DevelopmentMode)
response.NewSuccessResponse(i18n.GetText(ctx.Lang, "succ")).FPrint(w)
response.NewSuccessResponse(map[string]any{
"message": i18n.GetText(ctx.Lang, "succ"),
"reauth_required": true,
}).FPrint(w)
}
+5 -2
View File
@@ -109,7 +109,10 @@ func TestModifyPasswordRequiresCurrentPassword(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if identity.ID != user.ID || identity.SessionVersion != unchanged.SessionVersion {
t.Fatalf("current session was not refreshed after password change: %+v", identity)
if identity.ID != 0 {
t.Fatalf("current session was not destroyed after password change: %+v", identity)
}
if unchanged.MustChangePassword != 0 || unchanged.SecurityVersion <= 0 || unchanged.PasswordChangedAt == nil {
t.Fatalf("password lifecycle fields were not updated: %+v", unchanged)
}
}
+35 -9
View File
@@ -18,6 +18,7 @@ import (
"io"
"math"
"net/http"
"time"
)
const maxUserRequestBytes int64 = 64 << 10
@@ -81,7 +82,7 @@ func CreateUser(ctx *context.Context, w http.ResponseWriter, req *http.Request)
response.NewErrorResponse(response.ParamsError, "\u53c2\u6570\u9519\u8bef", "").FPrint(w)
return
}
user := models.User{Name: username, Account: account, Disabled: reqData.Disabled, SessionVersion: 1}
user := models.User{Name: username, Account: account, Disabled: reqData.Disabled, SessionVersion: 1, SecurityVersion: 1}
user.ApplyRole(targetRole)
if err := auth.SetPassword(&user, reqData.Password); err != nil {
if errors.Is(err, password.ErrInvalidLength) {
@@ -146,13 +147,23 @@ func Info(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
domains := cfg.Domains
domains = array.Difference(domains, []string{cfg.Domain})
domains = append([]string{cfg.Domain}, domains...)
response.NewSuccessResponse(map[string]any{
"account": ctx.UserAccount,
"name": ctx.UserName,
"role": ctx.EffectiveRole(),
"is_admin": ctx.IsAdmin,
"domains": domains,
}).FPrint(w)
result := map[string]any{
"account": ctx.UserAccount,
"name": ctx.UserName,
"role": ctx.EffectiveRole(),
"capabilities": access.Capabilities(ctx.EffectiveRole()),
"is_admin": ctx.IsAdmin,
"must_change_password": ctx.MustChangePassword,
"domains": domains,
}
if ctx.EffectiveRole() != access.RoleSuperAdmin {
result["recoveryCodesConfigured"] = ctx.RecoveryCodeConfigured
result["showRecoverySetupPrompt"] = !ctx.RecoveryCodeConfigured
} else {
result["recoveryCodesConfigured"] = false
result["showRecoverySetupPrompt"] = false
}
response.NewSuccessResponse(result).FPrint(w)
}
func EditUser(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
@@ -238,6 +249,7 @@ func EditUser(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
originalDisabled := user.Disabled
originalRole := user.EffectiveRole()
originalSessionVersion := user.SessionVersion
originalSecurityVersion := user.SecurityVersion
if reqData.Username != "" {
username, validationErr := validation.NormalizeDisplayName(reqData.Username)
if validationErr != nil {
@@ -257,9 +269,13 @@ func EditUser(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
response.NewErrorResponse(response.ServerError, "密码设置失败", "").FPrint(w)
return
}
user.MustChangePassword = 1
now := time.Now().UTC()
user.PasswordChangedAt = &now
}
if reqData.Password != "" || user.Disabled != originalDisabled || user.EffectiveRole() != originalRole {
user.SessionVersion = originalSessionVersion + 1
user.SecurityVersion = originalSecurityVersion + 1
}
credentialService := credentialRuntime()
if reqData.Password != "" && credentialService == nil {
@@ -284,7 +300,14 @@ func EditUser(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
_ = tx.Rollback()
}
}()
if num, err := tx.ID(user.ID).Where("session_version = ?", originalSessionVersion).Cols("name", "password", "disabled", "role", "is_admin", "session_version").Update(&user); err != nil {
updateColumns := []string{"name", "disabled", "role", "is_admin"}
if reqData.Password != "" {
updateColumns = append(updateColumns, "password", "must_change_password", "password_changed_at")
}
if reqData.Password != "" || user.Disabled != originalDisabled || user.EffectiveRole() != originalRole {
updateColumns = append(updateColumns, "session_version", "security_version")
}
if num, err := tx.ID(user.ID).Where("session_version = ?", originalSessionVersion).Cols(updateColumns...).Update(&user); err != nil {
log.WithContext(ctx).WithError(err).Error("update user failed")
response.NewErrorResponse(response.ServerError, "更新用户失败", "").FPrint(w)
return
@@ -305,6 +328,9 @@ func EditUser(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
return
}
committed = true
if reqData.Password != "" {
InvalidateSecurityRuntimeUser(user.ID, user.Account)
}
_ = roleChanged
response.NewSuccessResponse(user).FPrint(w)
}
+45 -9
View File
@@ -7,6 +7,7 @@ import (
"net/http"
"strings"
"git.pcux.cn/xuans/Smail/db"
"git.pcux.cn/xuans/Smail/dto/response"
"git.pcux.cn/xuans/Smail/models"
webauthnservice "git.pcux.cn/xuans/Smail/services/webauthn"
@@ -15,13 +16,16 @@ import (
type webAuthnFinishRequest struct {
SessionID string `json:"session_id"`
ChallengeID string `json:"challenge_id"`
Identifier string `json:"identifier"`
Account string `json:"account"`
DisplayName string `json:"display_name"`
Credential json.RawMessage `json:"credential"`
}
type webAuthnLoginBeginRequest struct {
Identifier string `json:"identifier"`
ChallengeID string `json:"challenge_id"`
Account string `json:"account"`
}
type webAuthnCredentialRequest struct {
@@ -186,18 +190,30 @@ func BeginWebAuthnLogin(ctx *context.Context, w http.ResponseWriter, req *http.R
return
}
var input webAuthnLoginBeginRequest
if err := decodeJSONRequest(w, req, &input); err != nil {
if err := decodeJSONRequest(w, req, &input); err != nil || strings.TrimSpace(input.ChallengeID) == "" || strings.TrimSpace(input.Account) == "" {
webAuthnLoginFailureIPAttempts.recordFailure(failureKey)
writeSecurityError(w, response.ParamsError, "\u5b89\u5168\u5bc6\u94a5\u767b\u5f55\u8bf7\u6c42\u65e0\u6548")
return
}
options, sessionID, err := service.BeginDiscoverableLogin()
item, ok := pendingLoginVerification(input.ChallengeID, input.Account)
if !ok {
webAuthnLoginFailureIPAttempts.recordFailure(failureKey)
writeSecurityError(w, response.ParamsError, "安全密钥登录请求无效")
return
}
options, sessionID, err := service.BeginLogin(item.UserID)
if err != nil {
webAuthnLoginFailureIPAttempts.recordFailure(failureKey)
writeSecurityError(w, response.ParamsError, "\u5b89\u5168\u5bc6\u94a5\u767b\u5f55\u5931\u8d25")
return
}
webAuthnLoginBeginIPAttempts.recordFailure(beginKey)
response.NewSuccessResponse(map[string]any{"session_id": sessionID, "options": options}).FPrint(w)
response.NewSuccessResponse(map[string]any{
"challenge_id": input.ChallengeID,
"account": item.Account,
"expires_at": item.ExpiresAt.UTC(),
"session_id": sessionID,
"options": options,
}).FPrint(w)
}
// FinishWebAuthnLogin 完成安全密钥登录并创建普通业务会话。
@@ -213,21 +229,41 @@ func FinishWebAuthnLogin(ctx *context.Context, w http.ResponseWriter, req *http.
return
}
var input webAuthnFinishRequest
if err := decodeJSONRequest(w, req, &input); err != nil || strings.TrimSpace(input.SessionID) == "" || len(input.Credential) == 0 || !json.Valid(input.Credential) {
if err := decodeJSONRequest(w, req, &input); err != nil || strings.TrimSpace(input.ChallengeID) == "" || strings.TrimSpace(input.SessionID) == "" || len(input.Credential) == 0 || !json.Valid(input.Credential) {
webAuthnLoginFailureIPAttempts.recordFailure(failureKey)
loginIPAttempts.recordFailure(loginIPAttempts.ipKey(req))
writeSecurityError(w, response.ParamsError, "\u5b89\u5168\u5bc6\u94a5\u767b\u5f55\u8bf7\u6c42\u65e0\u6548")
return
}
account := strings.TrimSpace(input.Account)
if account == "" {
account = strings.TrimSpace(input.Identifier)
}
item, ok := pendingLoginVerification(input.ChallengeID, account)
if !ok {
webAuthnLoginFailureIPAttempts.recordFailure(failureKey)
loginIPAttempts.recordFailure(loginIPAttempts.ipKey(req))
writeSecurityError(w, response.ParamsError, "登录验证已失效,请重新登录")
return
}
credentialRequest := cloneWebAuthnRequest(req, input.Credential)
user, _, err := service.FinishDiscoverableLogin(input.SessionID, credentialRequest)
if err != nil || user == nil {
if _, err := service.FinishLogin(item.UserID, input.SessionID, credentialRequest); err != nil {
webAuthnLoginFailureIPAttempts.recordFailure(failureKey)
loginIPAttempts.recordFailure(loginIPAttempts.ipKey(req))
writeSecurityError(w, response.ParamsError, "\u5b89\u5168\u5bc6\u94a5\u767b\u5f55\u5931\u8d25")
return
}
completeLoginSession(ctx, w, req, user)
var user models.User
has, err := db.Instance.ID(item.UserID).Get(&user)
if err != nil || !has || user.Disabled != 0 || user.Account != item.Account || user.SessionVersion != item.SessionVersion {
writeSecurityError(w, response.ParamsError, "登录验证已失效,请重新登录")
return
}
if securityRuntime.verification != nil && securityRuntime.verification.Store != nil {
securityRuntime.verification.Store.InvalidateChallenge(input.ChallengeID)
}
consumePendingLoginVerification(input.ChallengeID, item)
completeLoginSession(ctx, w, req, &user)
}
func BeginWebAuthnRecovery(ctx *context.Context, w http.ResponseWriter, req *http.Request) {