保存认证容量保护整改检查点待远程复审

This commit is contained in:
xuans committed 2026-09-17 12:00:45 +08:00
1 parent e49e392fd1
commit e30f21849f
27 files changed
+721 -53

No files matched your search

+3
View File
@@ -202,6 +202,9 @@ func Login(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
user, err := auth.AuthenticateIdentifier(identifier, reqData.Password)
if err != nil {
if writePasswordBusy(w, err) {
return
}
loginPairAttempts.recordFailure(pairKey)
loginAccountAttempts.recordFailure(accountKey)
loginIPAttempts.recordFailure(ipKey)
+22
View File
@@ -0,0 +1,22 @@
package controllers
import (
"errors"
"net/http"
"git.pcux.cn/xuans/Smail/dto/response"
"git.pcux.cn/xuans/Smail/utils/password"
)
// 计算繁忙不是凭据错误,不计入失败次数,也不触发会话失效。
func writePasswordBusy(w http.ResponseWriter, err error) bool {
if !errors.Is(err, password.ErrBusy) {
return false
}
w.Header().Set("Retry-After", "1")
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusServiceUnavailable)
response.NewErrorResponse(http.StatusServiceUnavailable, "认证服务繁忙,请稍后重试", response.ConfigErrorData{Code: "AUTH_BUSY"}).FPrint(w)
return true
}
@@ -0,0 +1,86 @@
package controllers
import (
"fmt"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"git.pcux.cn/xuans/Smail/config"
"git.pcux.cn/xuans/Smail/db"
"git.pcux.cn/xuans/Smail/internal/passwordtest"
"git.pcux.cn/xuans/Smail/models"
"git.pcux.cn/xuans/Smail/services/auth"
"git.pcux.cn/xuans/Smail/session"
appcontext "git.pcux.cn/xuans/Smail/utils/context"
"git.pcux.cn/xuans/Smail/utils/password"
"github.com/alexedwards/scs/v2"
)
func TestPasswordBusyHTTPDoesNotLockAccounts(t *testing.T) {
oldConfig, oldDB, oldSession := config.Instance, db.Instance, session.Instance
oldPair, oldAccount, oldIP := loginPairAttempts, loginAccountAttempts, loginIPAttempts
oldReauthUser, oldReauthIP := reauthUserAttempts, reauthIPAttempts
config.Instance = &config.Config{DbType: config.DBTypeSQLite, DbDSN: filepath.Join(t.TempDir(), "capacity.db")}
if err := db.Init(""); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = db.Instance.Close()
config.Instance, db.Instance, session.Instance = oldConfig, oldDB, oldSession
loginPairAttempts, loginAccountAttempts, loginIPAttempts = oldPair, oldAccount, oldIP
reauthUserAttempts, reauthIPAttempts = oldReauthUser, oldReauthIP
})
loginPairAttempts, loginAccountAttempts, loginIPAttempts = newLoginLimiter(1), newLoginLimiter(1), newLoginLimiter(1)
reauthUserAttempts, reauthIPAttempts = newLoginLimiter(1), newLoginLimiter(1)
session.Instance = scs.New()
user := models.User{Account: "capacity-user", SessionVersion: 1}
if err := auth.SetPassword(&user, "CorrectP12"); err != nil {
t.Fatal(err)
}
if _, err := db.Instance.Insert(&user); err != nil {
t.Fatal(err)
}
release := passwordtest.Hold(t)
cases := []struct {
handler func(*appcontext.Context, http.ResponseWriter, *http.Request)
body string
}{
{Login, `{"account":"capacity-user","password":"CorrectP12"}`},
{Login, `{"account":"missing-user","password":"CorrectP12"}`},
{ReauthenticateCurrentUser, `{"password":"CorrectP12"}`},
{ModifyPassword, `{"current_password":"CorrectP12","password":"NewPass123"}`},
}
for index := 0; index < 12; index++ {
for _, item := range cases {
request := httptest.NewRequest(http.MethodPost, "https://mail.example.com/api/test", strings.NewReader(item.body))
request.RemoteAddr = "192.0.2.71:1234"
recorder := httptest.NewRecorder()
ctx := &appcontext.Context{Context: request.Context(), UserID: user.ID, UserAccount: user.Account}
item.handler(ctx, recorder, request)
if recorder.Code != http.StatusServiceUnavailable || recorder.Header().Get("Retry-After") != "1" || !strings.Contains(recorder.Body.String(), "AUTH_BUSY") {
t.Fatalf("认证繁忙响应不正确:%d %s", recorder.Code, recorder.Body.String())
}
}
}
for _, limiter := range []*loginLimiter{loginPairAttempts, loginAccountAttempts, loginIPAttempts, reauthUserAttempts, reauthIPAttempts} {
if len(limiter.attempts) != 0 {
t.Fatal("认证繁忙增加了登录失败计数")
}
}
release()
if _, err := auth.Authenticate(user.Account, "CorrectP12"); err != nil {
t.Fatal(err)
}
}
func TestPasswordBusyResponsePreservesOtherErrors(t *testing.T) {
if writePasswordBusy(httptest.NewRecorder(), fmt.Errorf("wrapped: %w", password.ErrInvalidLength)) {
t.Fatal("普通错误被错误标记为资源繁忙")
}
if !writePasswordBusy(httptest.NewRecorder(), fmt.Errorf("wrapped: %w", password.ErrBusy)) {
t.Fatal("包装后的繁忙错误未被识别")
}
}
+3
View File
@@ -49,6 +49,9 @@ func ReauthenticateCurrentUser(ctx *appcontext.Context, w http.ResponseWriter, r
user, err := auth.AuthenticateUserByID(ctx.UserID, input.Password)
if err != nil {
if writePasswordBusy(w, err) {
return
}
reauthUserAttempts.recordFailure(userKey)
reauthIPAttempts.recordFailure(ipKey)
log.WithContext(ctx).Info("reauthentication failed")
+29 -1
View File
@@ -24,6 +24,7 @@ import (
"git.pcux.cn/xuans/Smail/services/verification"
webauthnservice "git.pcux.cn/xuans/Smail/services/webauthn"
"git.pcux.cn/xuans/Smail/utils/context"
"git.pcux.cn/xuans/Smail/utils/password"
log "github.com/sirupsen/logrus"
)
@@ -279,6 +280,9 @@ func SetSecurityQuestion(ctx *context.Context, w http.ResponseWriter, req *http.
return
}
if err := service.SetSecurityQuestion(ctx.UserID, input.Question, input.Answer); err != nil {
if writePasswordBusy(w, err) {
return
}
writeSecurityError(w, response.ParamsError, "密保问题设置失败")
return
}
@@ -308,6 +312,9 @@ func GenerateRecoveryCodes(ctx *context.Context, w http.ResponseWriter, req *htt
}
codes, err := service.GenerateRecoveryCodes(ctx.UserID, input.Count)
if err != nil {
if writePasswordBusy(w, err) {
return
}
writeSecurityError(w, response.ParamsError, "离线恢复码生成失败")
return
}
@@ -424,6 +431,9 @@ func GenerateProtocolCredential(ctx *context.Context, w http.ResponseWriter, req
}
code, err := service.GenerateProtocolCode(ctx.UserID, input.Protocol)
if err != nil {
if writePasswordBusy(w, err) {
return
}
writeSecurityError(w, response.ParamsError, "请先开启协议后再生成授权码")
return
}
@@ -464,6 +474,9 @@ func RevealProtocolCredentials(ctx *context.Context, w http.ResponseWriter, req
return
}
if _, err := auth.AuthenticateUserByID(ctx.UserID, input.Password); err != nil {
if writePasswordBusy(w, err) {
return
}
writeSecurityError(w, response.ParamsError, "密码验证失败")
return
}
@@ -617,6 +630,9 @@ func VerifyPasswordRecovery(ctx *context.Context, w http.ResponseWriter, req *ht
}
}
if err != nil {
if writePasswordBusy(w, err) {
return
}
emailRecoveryFailureIPAttempts.recordFailure(failureKey)
writeSecurityError(w, response.ParamsError, "验证失败")
return
@@ -647,6 +663,9 @@ func CompletePasswordRecovery(ctx *context.Context, w http.ResponseWriter, req *
return
}
if err := runtime.recovery.CompleteWithContext(input.Ticket, input.NewPassword, browserContext); err != nil {
if writePasswordBusy(w, err) {
return
}
emailRecoveryFailureIPAttempts.recordFailure(failureKey)
writeSecurityError(w, response.ParamsError, "重置失败")
return
@@ -696,7 +715,16 @@ func CompletePublicLinkPasswordRecovery(w http.ResponseWriter, req *http.Request
return
}
runtime := currentSecurityRuntime()
if runtime.recovery == nil || runtime.recovery.CompletePublicLink(input.Token, input.NewPassword, input.RecoveryCode) != nil {
if runtime.recovery == nil {
writePublicRecoveryJSON(w, http.StatusBadRequest, map[string]bool{"reset": false})
return
}
if err := runtime.recovery.CompletePublicLink(input.Token, input.NewPassword, input.RecoveryCode); err != nil {
if errors.Is(err, password.ErrBusy) {
w.Header().Set("Retry-After", "1")
writePublicRecoveryJSON(w, http.StatusServiceUnavailable, map[string]bool{"reset": false})
return
}
writePublicRecoveryJSON(w, http.StatusBadRequest, map[string]bool{"reset": false})
return
}
@@ -1,4 +1,4 @@
package controllers
package controllers
import (
"net/http"
@@ -38,6 +38,9 @@ func CreateClientCredential(ctx *context.Context, w http.ResponseWriter, req *ht
}
code, item, err := service.CreateClientCredential(ctx.UserID, input.ClientName)
if err != nil {
if writePasswordBusy(w, err) {
return
}
writeSecurityError(w, response.ParamsError, err.Error())
return
}
@@ -59,6 +62,9 @@ func RegenerateClientCredential(ctx *context.Context, w http.ResponseWriter, req
}
code, err := service.RegenerateClientCredential(ctx.UserID, input.ClientID)
if err != nil {
if writePasswordBusy(w, err) {
return
}
writeSecurityError(w, response.ParamsError, err.Error())
return
}
@@ -99,6 +105,9 @@ func RevealClientCredentials(ctx *context.Context, w http.ResponseWriter, req *h
return
}
if _, err := auth.AuthenticateUserByID(ctx.UserID, input.Password); err != nil {
if writePasswordBusy(w, err) {
return
}
writeSecurityError(w, response.ParamsError, "密码验证失败")
return
}
+6
View File
@@ -62,6 +62,9 @@ func ModifyPassword(ctx *context.Context, w http.ResponseWriter, req *http.Reque
currentUser, err = auth.Authenticate(ctx.UserAccount, retData.CurrentPassword)
}
if err != nil || currentUser == nil || currentUser.ID != ctx.UserID {
if writePasswordBusy(w, err) {
return
}
loginPairAttempts.recordFailure(pairKey)
loginAccountAttempts.recordFailure(accountKey)
loginIPAttempts.recordFailure(ipKey)
@@ -89,6 +92,9 @@ func ModifyPassword(ctx *context.Context, w http.ResponseWriter, req *http.Reque
PasswordChangedAt: &now,
}
if err := auth.SetPassword(&user, retData.Password); err != nil {
if writePasswordBusy(w, err) {
return
}
if errors.Is(err, password.ErrInvalidLength) {
response.NewErrorResponse(response.ParamsError, "密码长度必须为 8-12 字节", "").FPrint(w)
return
+6
View File
@@ -86,6 +86,9 @@ func CreateUser(ctx *context.Context, w http.ResponseWriter, req *http.Request)
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 writePasswordBusy(w, err) {
return
}
if errors.Is(err, password.ErrInvalidLength) {
response.NewErrorResponse(response.ParamsError, "密码长度必须为 8-12 字节", "").FPrint(w)
return
@@ -337,6 +340,9 @@ func EditUser(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
user.Disabled = reqData.Disabled
if reqData.Password != "" {
if err := auth.SetPassword(&user, reqData.Password); err != nil {
if writePasswordBusy(w, err) {
return
}
if errors.Is(err, password.ErrInvalidLength) {
response.NewErrorResponse(response.ParamsError, "密码长度必须为 8-12 字节", "").FPrint(w)
return