1 parent
77abc51a9d
commit
659d98b589
10 files changed
+426
-13
No files matched your search
@@ -0,0 +1,73 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/dto/response"
|
||||
"git.pcux.cn/xuans/Smail/services/auth"
|
||||
"git.pcux.cn/xuans/Smail/session"
|
||||
appcontext "git.pcux.cn/xuans/Smail/utils/context"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const (
|
||||
reauthUserFailureLimit = 10
|
||||
reauthIPFailureLimit = 50
|
||||
)
|
||||
|
||||
var (
|
||||
reauthUserAttempts = newLoginLimiter(reauthUserFailureLimit)
|
||||
reauthIPAttempts = newLoginLimiter(reauthIPFailureLimit)
|
||||
)
|
||||
|
||||
type reauthRequest struct {
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
// ReauthenticateCurrentUser 在不离开当前页面的情况下重新确认当前会话用户密码。
|
||||
func ReauthenticateCurrentUser(ctx *appcontext.Context, w http.ResponseWriter, req *http.Request) {
|
||||
if ctx == nil || ctx.UserID <= 0 || session.Instance == nil {
|
||||
writeReauthError(w, http.StatusUnauthorized, "REAUTH_SESSION_REQUIRED", "登录状态已失效,请重新登录")
|
||||
return
|
||||
}
|
||||
|
||||
var input reauthRequest
|
||||
if err := decodeJSONRequest(w, req, &input); err != nil || input.Password == "" {
|
||||
writeReauthError(w, http.StatusBadRequest, "REAUTH_REQUEST_INVALID", "请输入当前密码")
|
||||
return
|
||||
}
|
||||
defer func() { input.Password = "" }()
|
||||
|
||||
userKey := reauthUserAttempts.accountKey(strconv.Itoa(ctx.UserID))
|
||||
ipKey := reauthIPAttempts.ipKey(req)
|
||||
if reauthUserAttempts.blocked(userKey) || reauthIPAttempts.blocked(ipKey) {
|
||||
log.WithContext(ctx).Info("reauthentication rejected by rate limit")
|
||||
writeReauthError(w, http.StatusTooManyRequests, "REAUTH_RATE_LIMITED", "尝试次数过多,请稍后再试")
|
||||
return
|
||||
}
|
||||
|
||||
user, err := auth.AuthenticateUserByID(ctx.UserID, input.Password)
|
||||
if err != nil {
|
||||
reauthUserAttempts.recordFailure(userKey)
|
||||
reauthIPAttempts.recordFailure(ipKey)
|
||||
log.WithContext(ctx).Info("reauthentication failed")
|
||||
writeReauthError(w, http.StatusUnauthorized, "REAUTH_FAILED", "当前密码不正确")
|
||||
return
|
||||
}
|
||||
if err := session.RefreshRecentAuthentication(req.Context(), user); err != nil {
|
||||
log.WithContext(ctx).WithError(err).Warn("refresh recent authentication failed")
|
||||
writeReauthError(w, http.StatusUnauthorized, "REAUTH_SESSION_CHANGED", "登录状态已变化,请重新登录")
|
||||
return
|
||||
}
|
||||
|
||||
reauthUserAttempts.clear(userKey)
|
||||
response.NewSuccessResponse(map[string]any{"reauthenticated": true}).FPrint(w)
|
||||
}
|
||||
|
||||
func writeReauthError(w http.ResponseWriter, status int, code string, message string) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
response.NewErrorResponse(response.ConfigErrorNumber(status), message, response.ConfigErrorData{Code: code}).FPrint(w)
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"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/auth"
|
||||
"git.pcux.cn/xuans/Smail/session"
|
||||
appcontext "git.pcux.cn/xuans/Smail/utils/context"
|
||||
"github.com/alexedwards/scs/v2"
|
||||
)
|
||||
|
||||
func TestReauthenticateCurrentUser(t *testing.T) {
|
||||
oldConfig := config.Instance
|
||||
oldDB := db.Instance
|
||||
oldSession := session.Instance
|
||||
oldUserAttempts := reauthUserAttempts
|
||||
oldIPAttempts := reauthIPAttempts
|
||||
t.Cleanup(func() {
|
||||
if db.Instance != nil && db.Instance != oldDB {
|
||||
_ = db.Instance.Close()
|
||||
}
|
||||
config.Instance = oldConfig
|
||||
db.Instance = oldDB
|
||||
session.Instance = oldSession
|
||||
reauthUserAttempts = oldUserAttempts
|
||||
reauthIPAttempts = oldIPAttempts
|
||||
})
|
||||
|
||||
config.Instance = &config.Config{DbType: config.DBTypeSQLite, DbDSN: filepath.Join(t.TempDir(), "reauth.db")}
|
||||
if err := db.Init(""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
user := models.User{Account: "reauth-user", Name: "续验用户", SessionVersion: 1, SecurityVersion: 1}
|
||||
if err := auth.SetPassword(&user, "CorrectP12"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Instance.Insert(&user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
reauthUserAttempts = newLoginLimiter(reauthUserFailureLimit)
|
||||
reauthIPAttempts = newLoginLimiter(reauthIPFailureLimit)
|
||||
manager := scs.New()
|
||||
loaded, err := manager.Load(httptest.NewRequest(http.MethodGet, "/", nil).Context(), "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
session.Instance = manager
|
||||
if err := session.PutUser(loaded, &user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
identity, err := session.GetUser(loaded)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
identity.AuthenticatedAt = time.Now().Add(-time.Hour).Unix()
|
||||
encoded, err := json.Marshal(identity)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manager.Put(loaded, "user", string(encoded))
|
||||
ctx := &appcontext.Context{Context: loaded, UserID: user.ID, UserAccount: user.Account}
|
||||
|
||||
status, failed := invokeReauth(t, ctx, `{"password":"WrongPass12"}`)
|
||||
if status != http.StatusUnauthorized || failed.ErrorNo == 0 {
|
||||
t.Fatalf("incorrect password response: status=%d body=%+v", status, failed)
|
||||
}
|
||||
unchanged, err := session.GetUser(loaded)
|
||||
if err != nil || unchanged.AuthenticatedAt != identity.AuthenticatedAt {
|
||||
t.Fatalf("failed reauthentication changed session: identity=%+v err=%v", unchanged, err)
|
||||
}
|
||||
|
||||
status, succeeded := invokeReauth(t, ctx, `{"password":"CorrectP12"}`)
|
||||
if status != http.StatusOK || succeeded.ErrorNo != 0 {
|
||||
t.Fatalf("correct password response: status=%d body=%+v", status, succeeded)
|
||||
}
|
||||
refreshed, err := session.GetUser(loaded)
|
||||
if err != nil || !refreshed.HasRecentAuthentication(time.Now().UTC()) {
|
||||
t.Fatalf("recent authentication was not refreshed: identity=%+v err=%v", refreshed, err)
|
||||
}
|
||||
|
||||
if _, err := db.Instance.ID(user.ID).Cols("disabled").Update(&models.User{Disabled: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
status, disabled := invokeReauth(t, ctx, `{"password":"CorrectP12"}`)
|
||||
if status != http.StatusUnauthorized || disabled.ErrorNo == 0 {
|
||||
t.Fatalf("disabled user was reauthenticated: status=%d body=%+v", status, disabled)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReauthenticateCurrentUserRequiresSessionAndRateLimitsFailures(t *testing.T) {
|
||||
oldUserAttempts := reauthUserAttempts
|
||||
oldIPAttempts := reauthIPAttempts
|
||||
oldSession := session.Instance
|
||||
t.Cleanup(func() {
|
||||
reauthUserAttempts = oldUserAttempts
|
||||
reauthIPAttempts = oldIPAttempts
|
||||
session.Instance = oldSession
|
||||
})
|
||||
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/security/reauth", strings.NewReader(`{"password":"AnyPass12"}`))
|
||||
recorder := httptest.NewRecorder()
|
||||
ReauthenticateCurrentUser(&appcontext.Context{}, recorder, request)
|
||||
if recorder.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("missing session status = %d", recorder.Code)
|
||||
}
|
||||
|
||||
reauthUserAttempts = newLoginLimiter(1)
|
||||
reauthIPAttempts = newLoginLimiter(10)
|
||||
reauthUserAttempts.recordFailure(reauthUserAttempts.accountKey("7"))
|
||||
ctx := &appcontext.Context{UserID: 7, UserAccount: "limited"}
|
||||
request = httptest.NewRequest(http.MethodPost, "/api/v1/security/reauth", strings.NewReader(`{"password":"AnyPass12"}`))
|
||||
request.RemoteAddr = "192.0.2.50:1234"
|
||||
recorder = httptest.NewRecorder()
|
||||
session.Instance = scs.New()
|
||||
ReauthenticateCurrentUser(ctx, recorder, request)
|
||||
if recorder.Code != http.StatusTooManyRequests || !strings.Contains(recorder.Body.String(), "REAUTH_RATE_LIMITED") {
|
||||
t.Fatalf("rate limit response: status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func invokeReauth(t *testing.T, ctx *appcontext.Context, body string) (int, response.Response) {
|
||||
t.Helper()
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/security/reauth", strings.NewReader(body))
|
||||
request.RemoteAddr = "192.0.2.10:1234"
|
||||
request = request.WithContext(ctx.Context)
|
||||
recorder := httptest.NewRecorder()
|
||||
ReauthenticateCurrentUser(ctx, recorder, request)
|
||||
var result response.Response
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil {
|
||||
t.Fatalf("invalid response: %v body=%s", err, recorder.Body.String())
|
||||
}
|
||||
return recorder.Code, result
|
||||
}
|
||||
Reference in new issue
Block a user