实现安全中心邮箱验证码修改密码并补充测试

This commit is contained in:
xuans committed 2026-09-15 19:00:52 +08:00
1 parent 63f8b1777b
commit 45268ce2b7
10 files changed
+478 -32

No files matched your search

+80
View File
@@ -0,0 +1,80 @@
package controllers
import (
"errors"
"net/http"
"strconv"
"strings"
"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/utils/context"
)
var errPasswordChangeVerification = errors.New("password change verification unavailable")
// 从数据库读取当前身份和主要安全邮箱,不允许客户端指定验证码接收人。
func passwordChangeIdentity(ctx *context.Context, runtime securityRuntimeState) (*models.User, *models.ExternalEmail, string, error) {
if ctx == nil || db.Instance == nil || runtime.external == nil || runtime.verification == nil {
return nil, nil, "", errPasswordChangeVerification
}
user := &models.User{}
found, err := db.Instance.ID(ctx.UserID).Get(user)
if err != nil || !found || user.Disabled != 0 || user.EffectiveRole() != access.RoleSuperAdmin || user.Account != ctx.UserAccount {
return nil, nil, "", errPasswordChangeVerification
}
binding, err := runtime.external.FindVerifiedPrimaryByUser(user.ID)
if err != nil {
return nil, nil, "", errPasswordChangeVerification
}
email, err := runtime.external.Decrypt(*binding)
if err != nil || strings.TrimSpace(email) == "" {
return nil, nil, "", errPasswordChangeVerification
}
return user, binding, email, nil
}
func requestPasswordChangeVerification(ctx *context.Context, w http.ResponseWriter, req *http.Request, input verificationRequest, runtime securityRuntimeState) {
user, binding, email, err := passwordChangeIdentity(ctx, runtime)
if err != nil {
writeSecurityError(w, response.ParamsError, "请确认超级管理员已绑定并验证主要外部安全邮箱")
return
}
if input.Email != "" && !strings.EqualFold(strings.TrimSpace(input.Email), email) {
writeSecurityError(w, response.ParamsError, "邮箱地址与绑定的主安全邮箱不匹配")
return
}
challenge, err := runtime.verification.Issue(verification.IssueRequest{
Purpose: verification.PurposePasswordChange, UserID: user.ID,
Account: user.Account, Email: email, ResourceID: binding.ID,
BrowserTransaction: strconv.Itoa(user.SecurityVersion),
}, remoteIP(req))
if err != nil {
writeSecurityError(w, response.ParamsError, "验证码发送失败或请求过于频繁,请稍后重试")
return
}
response.NewSuccessResponse(map[string]any{
"id": challenge.ID, "expires_at": challenge.ExpiresAt.UTC(), "email": maskEmail(email),
}).FPrint(w)
}
func verifyPasswordChange(ctx *context.Context, req *http.Request, input modifyPasswordRequest) (*models.User, error) {
runtime := currentSecurityRuntime()
user, binding, email, err := passwordChangeIdentity(ctx, runtime)
if err != nil || strings.TrimSpace(input.Code) == "" || strings.TrimSpace(input.ChallengeID) == "" {
return nil, errPasswordChangeVerification
}
if input.Email != "" && !strings.EqualFold(strings.TrimSpace(input.Email), email) {
return nil, errPasswordChangeVerification
}
// 验证码同时绑定用途、账号、邮箱绑定记录及安全版本,不能跨流程复用。
if err := runtime.verification.VerifyBoundWithContext(input.ChallengeID, user.Account, email,
strings.TrimSpace(input.Code), verification.PurposePasswordChange, binding.ID,
remoteIP(req), strconv.Itoa(user.SecurityVersion)); err != nil {
return nil, err
}
return user, nil
}
@@ -5,8 +5,10 @@ import (
"net/http"
"net/http/httptest"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"git.pcux.cn/xuans/Smail/config"
"git.pcux.cn/xuans/Smail/db"
@@ -15,6 +17,8 @@ import (
"git.pcux.cn/xuans/Smail/services/access"
"git.pcux.cn/xuans/Smail/services/auth"
"git.pcux.cn/xuans/Smail/services/credentials"
"git.pcux.cn/xuans/Smail/services/externalemail"
"git.pcux.cn/xuans/Smail/services/verification"
"git.pcux.cn/xuans/Smail/session"
appcontext "git.pcux.cn/xuans/Smail/utils/context"
"git.pcux.cn/xuans/Smail/utils/password"
@@ -179,7 +183,7 @@ func authPasswordMatches(hash, plain string) bool {
return password.Verify(hash, plain)
}
func TestSuperAdminCannotChangePasswordThroughWeb(t *testing.T) {
func TestSuperAdminCannotChangePasswordWithoutEmailVerification(t *testing.T) {
testRoot := t.TempDir()
oldConfig := config.Instance
oldDB := db.Instance
@@ -208,8 +212,159 @@ func TestSuperAdminCannotChangePasswordThroughWeb(t *testing.T) {
if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil {
t.Fatal(err)
}
if result.ErrorNo != response.NoAccessPrivileges {
if result.ErrorNo != response.ParamsError {
t.Fatalf("expected web reset to be denied, got %d", result.ErrorNo)
}
assertUserPassword(t, user.ID, "OldPass123")
}
func TestSuperAdminPasswordChangeVerification(t *testing.T) {
for _, scenario := range []string{"success", "missing", "wrong-code", "wrong-purpose", "wrong-email", "unverified", "expired", "security-version", "disabled", "invalid-password", "replay"} {
t.Run(scenario, func(t *testing.T) {
testRoot := t.TempDir()
oldConfig, oldDB, oldSession := config.Instance, db.Instance, session.Instance
oldRuntime := currentSecurityRuntime()
oldPair, oldAccount, oldIP := loginPairAttempts, loginAccountAttempts, loginIPAttempts
loginPairAttempts = newLoginLimiter(loginFailureLimit)
loginAccountAttempts = newLoginLimiter(loginAccountFailureLimit)
loginIPAttempts = newLoginLimiter(loginIPFailureLimit)
session.Instance = scs.New()
t.Cleanup(func() {
_ = db.Instance.Close()
config.Instance, db.Instance, session.Instance = oldConfig, oldDB, oldSession
loginPairAttempts, loginAccountAttempts, loginIPAttempts = oldPair, oldAccount, oldIP
ConfigureSecurityRuntime(oldRuntime.verification, oldRuntime.external, oldRuntime.recovery, oldRuntime.credentials)
})
config.Instance = &config.Config{DbType: config.DBTypeSQLite, DbDSN: filepath.Join(testRoot, "password.db")}
if err := db.Init(""); err != nil {
t.Fatal(err)
}
user := newControllerTestUser(t, "verified-super", "超级管理员", access.RoleSuperAdmin, "OldPass123")
user.SecurityVersion = 1
if _, err := db.Instance.Insert(&user); err != nil {
t.Fatal(err)
}
vault := externalemail.NewVaultWithKeys([]byte("01234567890123456789012345678901"), []byte("abcdefabcdefabcdefabcdefabcdefab"))
repo, err := externalemail.NewRepository(db.Instance, vault)
if err != nil {
t.Fatal(err)
}
binding, err := repo.Bind(externalemail.BindRequest{UserID: user.ID, Email: "owner@example.com", Type: models.ExternalEmailTypePrimary})
if err != nil {
t.Fatal(err)
}
if scenario != "unverified" {
if err := repo.Verify(user.ID, binding.ID); err != nil {
t.Fatal(err)
}
}
store, err := verification.NewStore(32)
if err != nil {
t.Fatal(err)
}
var code string
var delivered verification.Challenge
send := func(challenge verification.Challenge, value string) error {
delivered, code = challenge, value
return nil
}
service, err := verification.NewService(store, send, nil)
if err != nil {
t.Fatal(err)
}
ConfigureSecurityRuntime(service, repo, nil, nil)
ctx := &appcontext.Context{UserID: user.ID, UserAccount: user.Account, Role: access.RoleSuperAdmin, Lang: "zhCn"}
issueRecorder := httptest.NewRecorder()
RequestVerification(ctx, issueRecorder, httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"purpose":"password_change","account":"verified-super"}`)))
if scenario == "unverified" {
if delivered.ID != "" {
t.Fatal("sent to unverified email")
}
return
}
if delivered.ID == "" || delivered.Email != "owner@example.com" {
t.Fatalf("issue failed: %s", issueRecorder.Body.String())
}
input := modifyPasswordRequest{Password: "NewPass123", Code: code, ChallengeID: delivered.ID}
switch scenario {
case "missing":
input.Code = ""
case "wrong-code":
input.Code = "not-a-code"
case "wrong-email":
input.Email = "other@example.com"
case "invalid-password":
input.Password = "short"
case "security-version":
_, err = db.Instance.ID(user.ID).Cols("security_version").Update(&models.User{SecurityVersion: 2})
case "disabled":
_, err = db.Instance.ID(user.ID).Cols("disabled").Update(&models.User{Disabled: 1})
case "wrong-purpose", "expired":
purpose, ttl := verification.PurposeLogin, time.Minute
if scenario == "expired" {
purpose, ttl = verification.PurposePasswordChange, time.Nanosecond
}
challenge, issueErr := store.Issue(verification.IssueRequest{Purpose: purpose, Account: user.Account, Email: delivered.Email, ResourceID: binding.ID, BrowserTransaction: strconv.Itoa(user.SecurityVersion), TTL: ttl}, send)
if issueErr != nil {
t.Fatal(issueErr)
}
input.ChallengeID, input.Code = challenge.ID, code
if scenario == "expired" {
time.Sleep(time.Millisecond)
}
}
if err != nil {
t.Fatal(err)
}
change := func() int {
body, err := json.Marshal(input)
if err != nil {
t.Fatal(err)
}
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(string(body)))
loaded, err := session.Instance.Load(req.Context(), "")
if err != nil {
t.Fatal(err)
}
session.Instance.Put(loaded, "user_id", user.ID)
recorder := httptest.NewRecorder()
ModifyPassword(ctx, recorder, req.WithContext(loaded))
var result struct {
ErrorNo int `json:"errorNo"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil {
t.Fatal(err)
}
if result.ErrorNo == 0 && session.Instance.Exists(loaded, "user_id") {
t.Fatal("session survived password change")
}
return result.ErrorNo
}
succeeded := scenario == "success" || scenario == "replay"
if result := change(); (result == 0) != succeeded {
t.Fatalf("unexpected result: %d", result)
}
if !succeeded {
assertUserPassword(t, user.ID, "OldPass123")
if scenario == "invalid-password" {
input.Password = "NewPass123"
if change() != 0 {
t.Fatal("invalid password consumed verification")
}
}
return
}
assertUserPassword(t, user.ID, "NewPass123")
var updated models.User
if _, err := db.Instance.ID(user.ID).Get(&updated); err != nil {
t.Fatal(err)
}
if updated.SessionVersion != 2 || updated.SecurityVersion != 2 {
t.Fatal("security versions not rotated")
}
if scenario == "replay" && change() == 0 {
t.Fatal("verification replay accepted")
}
})
}
}
+4
View File
@@ -482,6 +482,10 @@ func RequestVerification(ctx *context.Context, w http.ResponseWriter, req *http.
writeSecurityError(w, response.ParamsError, "请求无效")
return
}
if input.Purpose == verification.PurposePasswordChange {
requestPasswordChangeVerification(ctx, w, req, input, runtime)
return
}
if input.Email == "" || strings.TrimSpace(input.Account) == "" || !verification.IsSupportedPurpose(input.Purpose) || runtime.verification == nil {
writeSecurityError(w, response.ParamsError, "请求已受理")
return
+24 -9
View File
@@ -22,6 +22,9 @@ import (
type modifyPasswordRequest struct {
CurrentPassword string `json:"current_password"`
Password string `json:"password"`
Code string `json:"code"`
ChallengeID string `json:"challenge_id"`
Email string `json:"email"`
}
func ModifyPassword(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
@@ -29,17 +32,13 @@ 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, "超级管理员必须通过部署端专用通道重置密码", "").FPrint(w)
return
}
var retData modifyPasswordRequest
if err := decodeJSONRequest(w, req, &retData); err != nil {
log.WithContext(ctx).Debug("invalid password change request")
response.NewErrorResponse(response.ParamsError, i18n.GetText(ctx.Lang, "unknowError"), "").FPrint(w)
return
}
if retData.CurrentPassword == "" || retData.Password == "" {
if retData.Password == "" || (ctx.EffectiveRole() != access.RoleSuperAdmin && retData.CurrentPassword == "") {
response.NewErrorResponse(response.ParamsError, i18n.GetText(ctx.Lang, "unknowError"), "").FPrint(w)
return
}
@@ -50,13 +49,28 @@ func ModifyPassword(ctx *context.Context, w http.ResponseWriter, req *http.Reque
response.NewErrorResponse(response.ParamsError, i18n.GetText(ctx.Lang, "aperror"), "").FPrint(w)
return
}
currentUser, err := auth.Authenticate(ctx.UserAccount, retData.CurrentPassword)
if err != nil || currentUser.ID != ctx.UserID {
var currentUser *models.User
var err error
if ctx.EffectiveRole() == access.RoleSuperAdmin {
// 先校验新密码格式,避免无效输入消耗一次性验证码。
if password.ValidateUserPassword(retData.Password) != nil {
writeSecurityError(w, response.ParamsError, "密码长度必须为 8-12 字节")
return
}
currentUser, err = verifyPasswordChange(ctx, req, retData)
} else {
currentUser, err = auth.Authenticate(ctx.UserAccount, retData.CurrentPassword)
}
if err != nil || currentUser == nil || currentUser.ID != ctx.UserID {
loginPairAttempts.recordFailure(pairKey)
loginAccountAttempts.recordFailure(accountKey)
loginIPAttempts.recordFailure(ipKey)
log.WithContext(ctx).Info("password change authentication failed")
response.NewErrorResponse(response.ParamsError, i18n.GetText(ctx.Lang, "aperror"), "").FPrint(w)
if ctx.EffectiveRole() == access.RoleSuperAdmin {
writeSecurityError(w, response.ParamsError, "请使用已绑定主安全邮箱的有效验证码,失败后可重新获取")
} else {
response.NewErrorResponse(response.ParamsError, i18n.GetText(ctx.Lang, "aperror"), "").FPrint(w)
}
return
}
loginPairAttempts.clear(pairKey)
@@ -107,7 +121,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", "security_version", "must_change_password", "password_changed_at").Update(&user)
affected, err := tx.Where("id = ? and password = ? and session_version = ? and security_version = ? and disabled = 0", ctx.UserID, currentUser.Password, currentUser.SessionVersion, currentUser.SecurityVersion).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)
@@ -129,6 +143,7 @@ func ModifyPassword(ctx *context.Context, w http.ResponseWriter, req *http.Reque
return
}
committed = true
InvalidateSecurityRuntimeUser(ctx.UserID, ctx.UserAccount)
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)