登录支持用户选择邮箱或手机动态码并消除同步发信等待
This commit is contained in:
1 parent
9706e52a29
commit
7553b27cb2
25 files changed
+1223
-207
No files matched your search
@@ -219,7 +219,7 @@ func Login(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
|
||||
log.WithContext(ctx).WithError(err).Info("登录二次验证未就绪")
|
||||
|
||||
response.NewErrorResponse(response.ParamsError, "请先配置可用的外部安全邮箱", "").FPrint(w)
|
||||
response.NewErrorResponse(response.ParamsError, "登录验证服务暂不可用,请稍后重试", "").FPrint(w)
|
||||
|
||||
return
|
||||
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base32"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
"git.pcux.cn/xuans/Smail/db"
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
"git.pcux.cn/xuans/Smail/services/access"
|
||||
"git.pcux.cn/xuans/Smail/services/externalemail"
|
||||
"git.pcux.cn/xuans/Smail/services/totp"
|
||||
"git.pcux.cn/xuans/Smail/services/verification"
|
||||
"git.pcux.cn/xuans/Smail/session"
|
||||
appcontext "git.pcux.cn/xuans/Smail/utils/context"
|
||||
"github.com/alexedwards/scs/v2"
|
||||
)
|
||||
|
||||
func setupLoginMethods(t *testing.T, delivery verification.Delivery) (*models.User, *totp.Service) {
|
||||
t.Helper()
|
||||
oldConfig, oldDB, oldSession, oldManager := config.Instance, db.Instance, session.Instance, config.CurrentManager()
|
||||
oldRuntime, oldAttempts := currentSecurityRuntime(), loginSecondFactorAttempts
|
||||
root := t.TempDir()
|
||||
config.SetRuntimeManager(nil)
|
||||
config.Instance = &config.Config{DbType: config.DBTypeSQLite, DbDSN: filepath.Join(root, "login.db"), Domain: "example.com", VerificationEnabled: true, LoginPolicy: "always"}
|
||||
if err := db.Init(""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
session.Instance = scs.New()
|
||||
loginSecondFactorAttempts = newLoginLimiter(20)
|
||||
t.Cleanup(func() {
|
||||
ClearSecurityRuntime()
|
||||
_ = db.Instance.Close()
|
||||
config.Instance, db.Instance, session.Instance = oldConfig, oldDB, oldSession
|
||||
config.SetRuntimeManager(oldManager)
|
||||
securityRuntimeMu.Lock()
|
||||
securityRuntime = oldRuntime
|
||||
securityRuntimeMu.Unlock()
|
||||
loginSecondFactorAttempts = oldAttempts
|
||||
})
|
||||
user := &models.User{Account: "login-method-user", Role: string(access.RoleUser), SessionVersion: 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.net", Type: models.ExternalEmailTypePrimary})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := repo.Verify(user.ID, binding.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store, err := verification.NewStore(100)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service, err := verification.NewService(store, delivery, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
authenticator, err := totp.NewService(db.Instance, root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ConfigureSecurityRuntime(service, repo, nil, nil)
|
||||
ConfigureTOTPRuntime(authenticator)
|
||||
return user, authenticator
|
||||
}
|
||||
|
||||
func callLoginHandler(t *testing.T, handler func(*appcontext.Context, http.ResponseWriter, *http.Request), input any) (int, map[string]any) {
|
||||
t.Helper()
|
||||
body, err := json.Marshal(input)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "https://example.com/api/v1/security/login/verify", strings.NewReader(string(body)))
|
||||
loaded, err := session.Instance.Load(req.Context(), "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req = req.WithContext(loaded)
|
||||
recorder := httptest.NewRecorder()
|
||||
handler(&appcontext.Context{Context: loaded}, recorder, req)
|
||||
var result struct {
|
||||
ErrorNo int `json:"errorNo"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
var data map[string]any
|
||||
if result.ErrorNo == 0 {
|
||||
if err := json.Unmarshal(result.Data, &data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return result.ErrorNo, data
|
||||
}
|
||||
|
||||
func TestLoginEmailDeliveryDoesNotBlockHTTP(t *testing.T) {
|
||||
started, release := make(chan struct{}), make(chan struct{})
|
||||
var once sync.Once
|
||||
var calls atomic.Int32
|
||||
user, _ := setupLoginMethods(t, func(verification.Challenge, string) error {
|
||||
calls.Add(1)
|
||||
once.Do(func() { close(started) })
|
||||
<-release
|
||||
return nil
|
||||
})
|
||||
t.Cleanup(func() {
|
||||
close(release)
|
||||
deadline := time.After(2 * time.Second)
|
||||
for len(loginDeliverySlots) != 0 {
|
||||
select {
|
||||
case <-deadline:
|
||||
t.Error("mail worker did not stop")
|
||||
return
|
||||
case <-time.After(time.Millisecond):
|
||||
}
|
||||
}
|
||||
})
|
||||
begin := time.Now()
|
||||
pending, err := beginLoginVerification(user, "127.0.0.1")
|
||||
if err != nil || calls.Load() != 0 {
|
||||
t.Fatalf("begin invoked mail delivery: %v", err)
|
||||
}
|
||||
input := resendLoginVerificationRequest{ID: pending["challenge_id"].(string), Account: user.Account}
|
||||
code, data := callLoginHandler(t, ResendLoginVerification, input)
|
||||
if code != 0 || data["delivery_status"] != "sending" {
|
||||
t.Fatalf("send response: %d %+v", code, data)
|
||||
}
|
||||
select {
|
||||
case <-started:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("mail worker did not start")
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
code, _ = callLoginHandler(t, ResendLoginVerification, input)
|
||||
if code != 0 {
|
||||
t.Fatal("duplicate request failed")
|
||||
}
|
||||
code, data = callLoginHandler(t, LoginVerificationStatus, input)
|
||||
if code != 0 || data["delivery_status"] != "sending" {
|
||||
t.Fatal("status failed while mail blocked")
|
||||
}
|
||||
}
|
||||
if elapsed := time.Since(begin); elapsed > time.Second {
|
||||
t.Fatalf("HTTP operations blocked for %s", elapsed)
|
||||
} else {
|
||||
t.Logf("begin/send/status with blocked sender: %s", elapsed)
|
||||
}
|
||||
if calls.Load() != 1 {
|
||||
t.Fatalf("duplicate mail jobs: %d", calls.Load())
|
||||
}
|
||||
if code, _ := callLoginHandler(t, LoginVerificationStatus, resendLoginVerificationRequest{ID: input.ID, Account: "another-user"}); code == 0 {
|
||||
t.Fatal("status disclosed across accounts")
|
||||
}
|
||||
InvalidateSecurityRuntimeUser(user.ID, user.Account)
|
||||
}
|
||||
|
||||
func testTOTPCode(secret string, step int64) string {
|
||||
decoded, _ := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(secret)
|
||||
var counter [8]byte
|
||||
binary.BigEndian.PutUint64(counter[:], uint64(step))
|
||||
mac := hmac.New(sha256.New, decoded)
|
||||
_, _ = mac.Write(counter[:])
|
||||
digest := mac.Sum(nil)
|
||||
offset := digest[len(digest)-1] & 15
|
||||
return fmt.Sprintf("%06d", (binary.BigEndian.Uint32(digest[offset:offset+4])&0x7fffffff)%1000000)
|
||||
}
|
||||
|
||||
func TestLoginMethodsRolesAndSingleConsumption(t *testing.T) {
|
||||
for _, role := range []access.Role{access.RoleSuperAdmin, access.RoleAdmin, access.RoleUser} {
|
||||
t.Run(string(role), func(t *testing.T) {
|
||||
user, service := setupLoginMethods(t, func(verification.Challenge, string) error { return nil })
|
||||
user.Role = string(role)
|
||||
if _, err := db.Instance.ID(user.ID).Cols("role").Update(user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := &appcontext.Context{UserID: user.ID, UserAccount: user.Account, Role: role, RecentAuth: true}
|
||||
recorder := httptest.NewRecorder()
|
||||
TOTPSettings(ctx, recorder, httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"action":"begin"}`)))
|
||||
var result struct {
|
||||
ErrorNo int `json:"errorNo"`
|
||||
Data totp.Enrollment `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil || result.ErrorNo != 0 || result.Data.Secret == "" {
|
||||
t.Fatalf("role cannot enroll: %v", err)
|
||||
}
|
||||
step := time.Now().Unix() / 30
|
||||
if err := service.ConfirmEnrollment(user.ID, result.Data.ID, testTOTPCode(result.Data.Secret, step-1)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pending, err := beginLoginVerification(user, "127.0.0.1")
|
||||
if err != nil || len(pending["methods"].([]string)) != 2 {
|
||||
t.Fatalf("expected both methods: %v", err)
|
||||
}
|
||||
id := pending["challenge_id"].(string)
|
||||
var emailCode string
|
||||
challenge, err := currentSecurityRuntime().verification.Store.Issue(verification.IssueRequest{Purpose: verification.PurposeLogin, Account: user.Account, Email: "owner@example.net"}, func(_ verification.Challenge, code string) error { emailCode = code; return nil })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
loginVerificationState.Lock()
|
||||
item := loginVerificationState.items[id]
|
||||
item.EmailChallenge, item.DeliveryStatus = challenge.ID, "sent"
|
||||
loginVerificationState.items[id] = item
|
||||
loginVerificationState.Unlock()
|
||||
var successes atomic.Int32
|
||||
var wg sync.WaitGroup
|
||||
for _, method := range []string{"email", "totp"} {
|
||||
wg.Add(1)
|
||||
go func(method string) {
|
||||
defer wg.Done()
|
||||
code := emailCode
|
||||
if method == "totp" {
|
||||
code = testTOTPCode(result.Data.Secret, step)
|
||||
}
|
||||
errorNo, _ := callLoginHandler(t, CompleteLoginVerification, loginVerificationRequest{ID: id, Account: user.Account, Method: method, Code: code})
|
||||
if errorNo == 0 {
|
||||
successes.Add(1)
|
||||
}
|
||||
}(method)
|
||||
}
|
||||
wg.Wait()
|
||||
if successes.Load() != 1 {
|
||||
t.Fatalf("expected one login, got %d", successes.Load())
|
||||
}
|
||||
if _, ok := pendingLoginVerification(id, user.Account); ok {
|
||||
t.Fatal("successful challenge retained")
|
||||
}
|
||||
// 新的登录流程必须能独立使用 TOTP,且旧动态码不能重放。
|
||||
pending, err = beginLoginVerification(user, "127.0.0.1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
input := loginVerificationRequest{ID: pending["challenge_id"].(string), Account: user.Account, Method: "totp", Code: testTOTPCode(result.Data.Secret, step+1)}
|
||||
if code, _ := callLoginHandler(t, CompleteLoginVerification, input); code != 0 {
|
||||
t.Fatal("TOTP login failed")
|
||||
}
|
||||
pending, _ = beginLoginVerification(user, "127.0.0.1")
|
||||
input.ID = pending["challenge_id"].(string)
|
||||
if code, _ := callLoginHandler(t, CompleteLoginVerification, input); code == 0 {
|
||||
t.Fatal("TOTP replay accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginMethodsRejectInvalidState(t *testing.T) {
|
||||
user, _ := setupLoginMethods(t, func(verification.Challenge, string) error { return nil })
|
||||
pending, _ := beginLoginVerification(user, "127.0.0.1")
|
||||
id := pending["challenge_id"].(string)
|
||||
for i := 0; i < 5; i++ {
|
||||
if code, _ := callLoginHandler(t, CompleteLoginVerification, loginVerificationRequest{ID: id, Account: user.Account, Method: "totp", Code: "123456"}); code == 0 {
|
||||
t.Fatal("disabled TOTP accepted")
|
||||
}
|
||||
}
|
||||
if _, ok := pendingLoginVerification(id, user.Account); ok {
|
||||
t.Fatal("five failed attempts did not expire login")
|
||||
}
|
||||
pending, _ = beginLoginVerification(user, "127.0.0.1")
|
||||
id = pending["challenge_id"].(string)
|
||||
user.SessionVersion++
|
||||
if _, err := db.Instance.ID(user.ID).Cols("session_version").Update(user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if code, _ := callLoginHandler(t, ResendLoginVerification, resendLoginVerificationRequest{ID: id, Account: user.Account}); code == 0 {
|
||||
t.Fatal("stale session version sent mail")
|
||||
}
|
||||
loginVerificationState.Lock()
|
||||
item := loginVerificationState.items[id]
|
||||
item.ExpiresAt = time.Now().Add(-time.Second)
|
||||
loginVerificationState.items[id] = item
|
||||
loginVerificationState.Unlock()
|
||||
if consumePendingLoginVerification(id, item) {
|
||||
t.Fatal("expired login consumed")
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
@@ -40,8 +42,18 @@ type loginVerificationItem struct {
|
||||
Email string
|
||||
SessionVersion int
|
||||
ExpiresAt time.Time
|
||||
TOTPEnabled bool
|
||||
EmailChallenge string
|
||||
DeliveryStatus string
|
||||
DeliveryError string
|
||||
RetryAt time.Time
|
||||
Attempts int
|
||||
Verifying bool
|
||||
}
|
||||
|
||||
var loginDeliverySlots = make(chan struct{}, 16)
|
||||
var loginSecondFactorAttempts = newLoginLimiter(20)
|
||||
|
||||
type resendLoginVerificationRequest struct {
|
||||
ID string `json:"id"`
|
||||
Account string `json:"account"`
|
||||
@@ -52,6 +64,7 @@ type loginVerificationRequest struct {
|
||||
Identifier string `json:"identifier"`
|
||||
Email string `json:"email"`
|
||||
Code string `json:"code"`
|
||||
Method string `json:"method"`
|
||||
}
|
||||
|
||||
func loginVerificationEnabled() bool {
|
||||
@@ -84,54 +97,70 @@ func loginVerificationPolicyEnabled(enabled bool, policy string) bool {
|
||||
|
||||
func beginLoginVerification(user *models.User, remoteIP string) (map[string]any, error) {
|
||||
runtime := currentSecurityRuntime()
|
||||
if !loginVerificationEnabled() {
|
||||
if user == nil || user.ID <= 0 {
|
||||
return nil, errLoginVerificationUnavailable
|
||||
}
|
||||
item := loginVerificationItem{
|
||||
UserID: user.ID, Account: user.Account, SessionVersion: user.SessionVersion,
|
||||
ExpiresAt: time.Now().Add(loginVerificationTTL), DeliveryStatus: "idle",
|
||||
}
|
||||
if runtime.totp != nil {
|
||||
var err error
|
||||
item.TOTPEnabled, err = runtime.totp.IsEnabled(user.ID)
|
||||
if err != nil {
|
||||
return nil, errLoginVerificationUnavailable
|
||||
}
|
||||
}
|
||||
if loginVerificationEnabled() || item.TOTPEnabled {
|
||||
if runtime.external == nil || runtime.verification == nil {
|
||||
return nil, errLoginVerificationUnavailable
|
||||
}
|
||||
binding, err := runtime.external.FindVerifiedPrimaryByUser(user.ID)
|
||||
if err != nil && !errors.Is(err, externalemail.ErrBindingNotFound) {
|
||||
return nil, errLoginVerificationUnavailable
|
||||
}
|
||||
if err == nil {
|
||||
item.Email, err = runtime.external.Decrypt(*binding)
|
||||
if err != nil {
|
||||
return nil, errLoginVerificationUnavailable
|
||||
}
|
||||
}
|
||||
}
|
||||
if item.Email == "" && !item.TOTPEnabled {
|
||||
return nil, nil
|
||||
}
|
||||
if user == nil || user.ID <= 0 || runtime.verification == nil || runtime.external == nil {
|
||||
var token [32]byte
|
||||
if _, err := rand.Read(token[:]); err != nil {
|
||||
return nil, errLoginVerificationUnavailable
|
||||
}
|
||||
binding, err := runtime.external.FindVerifiedPrimaryByUser(user.ID)
|
||||
if err != nil {
|
||||
if errors.Is(err, externalemail.ErrBindingNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, errLoginVerificationUnavailable
|
||||
}
|
||||
email, err := runtime.external.Decrypt(*binding)
|
||||
if err != nil {
|
||||
return nil, errLoginVerificationUnavailable
|
||||
}
|
||||
challenge, err := runtime.verification.Issue(verification.IssueRequest{
|
||||
Purpose: verification.PurposeLogin,
|
||||
Account: user.Account,
|
||||
Email: email,
|
||||
TTL: loginVerificationTTL,
|
||||
}, remoteIP)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id := hex.EncodeToString(token[:])
|
||||
loginVerificationState.Lock()
|
||||
defer loginVerificationState.Unlock()
|
||||
cleanupLoginVerificationLocked(time.Now())
|
||||
if len(loginVerificationState.items) >= loginVerificationMaxEntries {
|
||||
loginVerificationState.Unlock()
|
||||
runtime.verification.Store.InvalidateChallenge(challenge.ID)
|
||||
return nil, errLoginVerificationUnavailable
|
||||
}
|
||||
loginVerificationState.items[challenge.ID] = loginVerificationItem{
|
||||
UserID: user.ID, Account: user.Account, Email: email,
|
||||
SessionVersion: user.SessionVersion, ExpiresAt: challenge.ExpiresAt,
|
||||
}
|
||||
loginVerificationState.Unlock()
|
||||
return map[string]any{
|
||||
"pending": true,
|
||||
"challenge_id": challenge.ID,
|
||||
"expires_at": challenge.ExpiresAt.UTC(),
|
||||
"email": maskEmail(email),
|
||||
"account": user.Account,
|
||||
}, nil
|
||||
loginVerificationState.items[id] = item
|
||||
return loginVerificationResponse(id, item), nil
|
||||
}
|
||||
|
||||
// ResendLoginVerification 使旧登录验证码失效后重新发送新验证码。
|
||||
func loginVerificationResponse(id string, item loginVerificationItem) map[string]any {
|
||||
methods := []string{}
|
||||
if item.Email != "" {
|
||||
methods = append(methods, "email")
|
||||
}
|
||||
if item.TOTPEnabled {
|
||||
methods = append(methods, "totp")
|
||||
}
|
||||
return map[string]any{
|
||||
"pending": true, "challenge_id": id, "account": item.Account,
|
||||
"expires_at": item.ExpiresAt.UTC(), "email": maskEmail(item.Email),
|
||||
"methods": methods, "delivery_status": item.DeliveryStatus,
|
||||
"delivery_error": item.DeliveryError, "retry_at": item.RetryAt.UTC(),
|
||||
}
|
||||
}
|
||||
|
||||
// ResendLoginVerification 只启动有并发上限的后台投递,HTTP 请求不等待邮件服务器。
|
||||
func ResendLoginVerification(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
runtime := currentSecurityRuntime()
|
||||
var input resendLoginVerificationRequest
|
||||
@@ -140,70 +169,153 @@ func ResendLoginVerification(ctx *context.Context, w http.ResponseWriter, req *h
|
||||
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) {
|
||||
item, ok := pendingLoginVerification(input.ID, input.Account)
|
||||
if !ok || !loginVerificationUserValid(item) {
|
||||
writeSecurityError(w, response.ParamsError, "登录验证已失效,请重新登录")
|
||||
return
|
||||
}
|
||||
if runtime.verification == nil || runtime.verification.Store == nil {
|
||||
if runtime.verification == nil || runtime.verification.Store == nil || item.Email == "" {
|
||||
writeSecurityError(w, response.ParamsError, "验证码服务暂不可用")
|
||||
return
|
||||
}
|
||||
runtime.verification.Store.InvalidateChallenge(input.ID)
|
||||
challenge, err := runtime.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, "验证码发送失败,请稍后重试")
|
||||
loginVerificationState.Lock()
|
||||
item, ok = loginVerificationState.items[input.ID]
|
||||
if !ok || !time.Now().Before(item.ExpiresAt) {
|
||||
loginVerificationState.Unlock()
|
||||
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,
|
||||
if item.DeliveryStatus == "sending" || time.Now().Before(item.RetryAt) {
|
||||
loginVerificationState.Unlock()
|
||||
response.NewSuccessResponse(loginVerificationResponse(input.ID, item)).FPrint(w)
|
||||
return
|
||||
}
|
||||
select {
|
||||
case loginDeliverySlots <- struct{}{}:
|
||||
default:
|
||||
loginVerificationState.Unlock()
|
||||
writeSecurityError(w, response.ParamsError, "邮件发送繁忙,请稍后重试或使用动态码")
|
||||
return
|
||||
}
|
||||
previousChallenge := item.EmailChallenge
|
||||
item.EmailChallenge = ""
|
||||
item.DeliveryStatus, item.DeliveryError = "sending", ""
|
||||
item.RetryAt = time.Now().Add(time.Minute)
|
||||
loginVerificationState.items[input.ID] = item
|
||||
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)
|
||||
ip := remoteIP(req)
|
||||
go func() {
|
||||
defer func() { <-loginDeliverySlots }()
|
||||
if previousChallenge != "" {
|
||||
runtime.verification.Store.InvalidateChallenge(previousChallenge)
|
||||
}
|
||||
challenge, err := runtime.verification.Issue(verification.IssueRequest{
|
||||
Purpose: verification.PurposeLogin, UserID: item.UserID, Account: item.Account,
|
||||
Email: item.Email, TTL: time.Until(item.ExpiresAt),
|
||||
}, ip)
|
||||
loginVerificationState.Lock()
|
||||
current, exists := loginVerificationState.items[input.ID]
|
||||
if exists && time.Now().Before(current.ExpiresAt) {
|
||||
if err != nil {
|
||||
current.DeliveryStatus = "failed"
|
||||
current.DeliveryError = externalEmailVerificationIssueMessage(err)
|
||||
} else {
|
||||
current.DeliveryStatus, current.EmailChallenge = "sent", challenge.ID
|
||||
}
|
||||
loginVerificationState.items[input.ID] = current
|
||||
}
|
||||
loginVerificationState.Unlock()
|
||||
if !exists || !time.Now().Before(current.ExpiresAt) {
|
||||
runtime.verification.Store.InvalidateChallenge(challenge.ID)
|
||||
}
|
||||
}()
|
||||
response.NewSuccessResponse(loginVerificationResponse(input.ID, item)).FPrint(w)
|
||||
}
|
||||
|
||||
func LoginVerificationStatus(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
var input resendLoginVerificationRequest
|
||||
if err := decodeJSONRequest(w, req, &input); err != nil {
|
||||
writeSecurityError(w, response.ParamsError, "登录验证请求无效")
|
||||
return
|
||||
}
|
||||
item, ok := pendingLoginVerification(input.ID, input.Account)
|
||||
if !ok || !loginVerificationUserValid(item) {
|
||||
writeSecurityError(w, response.ParamsError, "登录验证已失效,请重新登录")
|
||||
return
|
||||
}
|
||||
response.NewSuccessResponse(loginVerificationResponse(input.ID, item)).FPrint(w)
|
||||
}
|
||||
|
||||
func loginVerificationUserValid(item loginVerificationItem) bool {
|
||||
if db.Instance == nil {
|
||||
return false
|
||||
}
|
||||
var user models.User
|
||||
has, err := db.Instance.ID(item.UserID).Get(&user)
|
||||
return err == nil && has && user.Disabled == 0 && user.Account == item.Account && user.SessionVersion == item.SessionVersion
|
||||
}
|
||||
|
||||
// CompleteLoginVerification 只有验证码成功后才创建完整 Session。
|
||||
func CompleteLoginVerification(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
runtime := currentSecurityRuntime()
|
||||
var input loginVerificationRequest
|
||||
if err := decodeJSONRequest(w, req, &input); err != nil || runtime.verification == nil {
|
||||
if err := decodeJSONRequest(w, req, &input); err != nil {
|
||||
writeSecurityError(w, response.ParamsError, "验证失败")
|
||||
return
|
||||
}
|
||||
if input.Account == "" {
|
||||
input.Account = input.Identifier
|
||||
}
|
||||
loginVerificationState.Lock()
|
||||
cleanupLoginVerificationLocked(time.Now())
|
||||
item, ok := loginVerificationState.items[input.ID]
|
||||
loginVerificationState.Unlock()
|
||||
if !ok || !strings.EqualFold(strings.TrimSpace(input.Account), item.Account) {
|
||||
item, ok := pendingLoginVerification(input.ID, input.Account)
|
||||
if !ok || !loginVerificationUserValid(item) {
|
||||
writeSecurityError(w, response.ParamsError, "验证失败")
|
||||
return
|
||||
}
|
||||
if err := runtime.verification.Verify(input.ID, item.Account, item.Email, input.Code, verification.PurposeLogin, remoteIP(req)); err != nil {
|
||||
limitKey := loginSecondFactorAttempts.accountKey(item.Account)
|
||||
if loginSecondFactorAttempts.blocked(limitKey) {
|
||||
writeSecurityError(w, response.ParamsError, "验证失败次数过多,请十五分钟后重试")
|
||||
return
|
||||
}
|
||||
loginVerificationState.Lock()
|
||||
item, ok = loginVerificationState.items[input.ID]
|
||||
if !ok || item.Verifying || item.Attempts >= 5 || !time.Now().Before(item.ExpiresAt) {
|
||||
loginVerificationState.Unlock()
|
||||
writeSecurityError(w, response.ParamsError, "登录验证已失效或正在验证,请重新登录")
|
||||
return
|
||||
}
|
||||
item.Attempts++
|
||||
item.Verifying = true
|
||||
loginVerificationState.items[input.ID] = item
|
||||
loginVerificationState.Unlock()
|
||||
var verifyErr error
|
||||
switch input.Method {
|
||||
case "totp":
|
||||
if !item.TOTPEnabled || runtime.totp == nil {
|
||||
verifyErr = errLoginVerificationUnavailable
|
||||
} else {
|
||||
verifyErr = runtime.totp.Verify(item.UserID, input.Code)
|
||||
}
|
||||
case "", "email":
|
||||
if item.EmailChallenge == "" || runtime.verification == nil {
|
||||
verifyErr = errLoginVerificationUnavailable
|
||||
} else {
|
||||
verifyErr = runtime.verification.Verify(item.EmailChallenge, item.Account, item.Email, input.Code, verification.PurposeLogin, remoteIP(req))
|
||||
}
|
||||
default:
|
||||
verifyErr = errLoginVerificationUnavailable
|
||||
}
|
||||
if verifyErr != nil {
|
||||
loginSecondFactorAttempts.recordFailure(limitKey)
|
||||
loginVerificationState.Lock()
|
||||
if current, exists := loginVerificationState.items[input.ID]; exists {
|
||||
current.Verifying = false
|
||||
if current.Attempts >= 5 {
|
||||
delete(loginVerificationState.items, input.ID)
|
||||
} else {
|
||||
loginVerificationState.items[input.ID] = current
|
||||
}
|
||||
}
|
||||
loginVerificationState.Unlock()
|
||||
writeSecurityError(w, response.ParamsError, "验证失败")
|
||||
return
|
||||
}
|
||||
@@ -216,9 +328,14 @@ func CompleteLoginVerification(ctx *context.Context, w http.ResponseWriter, req
|
||||
writeSecurityError(w, response.ParamsError, "登录验证已失效,请重新登录")
|
||||
return
|
||||
}
|
||||
loginVerificationState.Lock()
|
||||
delete(loginVerificationState.items, input.ID)
|
||||
loginVerificationState.Unlock()
|
||||
if !consumePendingLoginVerification(input.ID, item) {
|
||||
writeSecurityError(w, response.ParamsError, "登录验证已失效,请重新登录")
|
||||
return
|
||||
}
|
||||
loginSecondFactorAttempts.clear(limitKey)
|
||||
if runtime.verification != nil && item.EmailChallenge != "" {
|
||||
runtime.verification.Store.InvalidateChallenge(item.EmailChallenge)
|
||||
}
|
||||
completeLoginSession(ctx, w, req, &user)
|
||||
}
|
||||
|
||||
@@ -306,7 +423,7 @@ func consumePendingLoginVerification(challengeID string, expected loginVerificat
|
||||
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) {
|
||||
if !ok || !time.Now().Before(item.ExpiresAt) || item.UserID != expected.UserID || item.SessionVersion != expected.SessionVersion || !strings.EqualFold(item.Account, expected.Account) {
|
||||
return false
|
||||
}
|
||||
delete(loginVerificationState.items, strings.TrimSpace(challengeID))
|
||||
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
"git.pcux.cn/xuans/Smail/services/credentials"
|
||||
"git.pcux.cn/xuans/Smail/services/externalemail"
|
||||
"git.pcux.cn/xuans/Smail/services/recovery"
|
||||
"git.pcux.cn/xuans/Smail/services/totp"
|
||||
"git.pcux.cn/xuans/Smail/services/verification"
|
||||
webauthnservice "git.pcux.cn/xuans/Smail/services/webauthn"
|
||||
"git.pcux.cn/xuans/Smail/utils/clientip"
|
||||
@@ -87,6 +88,7 @@ type securityRuntimeState struct {
|
||||
recovery *recovery.Service
|
||||
credentials *credentials.Service
|
||||
webauthn *webauthnservice.Service
|
||||
totp *totp.Service
|
||||
}
|
||||
|
||||
var securityRuntime securityRuntimeState
|
||||
@@ -118,6 +120,12 @@ func ConfigureWebAuthnRuntime(service *webauthnservice.Service) {
|
||||
securityRuntime.webauthn = service
|
||||
}
|
||||
|
||||
func ConfigureTOTPRuntime(service *totp.Service) {
|
||||
securityRuntimeMu.Lock()
|
||||
defer securityRuntimeMu.Unlock()
|
||||
securityRuntime.totp = service
|
||||
}
|
||||
|
||||
// ClearSecurityRuntime 在停止入口后一次撤下全部安全服务,避免保留已停止的旧库依赖。
|
||||
func ClearSecurityRuntime() {
|
||||
securityRuntimeMu.Lock()
|
||||
@@ -134,6 +142,9 @@ func InvalidateSecurityRuntimeUser(userID int, account string) {
|
||||
return
|
||||
}
|
||||
runtime := currentSecurityRuntime()
|
||||
if runtime.totp != nil {
|
||||
runtime.totp.InvalidateUser(userID)
|
||||
}
|
||||
if runtime.recovery != nil {
|
||||
runtime.recovery.InvalidateUser(userID)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/dto/response"
|
||||
"git.pcux.cn/xuans/Smail/services/access"
|
||||
"git.pcux.cn/xuans/Smail/utils/context"
|
||||
)
|
||||
|
||||
// TOTPSettings 所有登录角色均可管理自己的验证器,不接受客户端指定用户。
|
||||
func TOTPSettings(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
service := currentSecurityRuntime().totp
|
||||
if ctx == nil || ctx.UserID <= 0 || service == nil {
|
||||
writeSecurityError(w, response.ParamsError, "动态码服务暂不可用")
|
||||
return
|
||||
}
|
||||
if req.Method == http.MethodGet {
|
||||
enabled, err := service.IsEnabled(ctx.UserID)
|
||||
if err != nil {
|
||||
writeSecurityError(w, response.ParamsError, "无法读取动态码状态")
|
||||
return
|
||||
}
|
||||
response.NewSuccessResponse(map[string]any{"enabled": enabled}).FPrint(w)
|
||||
return
|
||||
}
|
||||
if !ctx.RecentAuth {
|
||||
writeSecurityErrorWithCode(w, response.NoAccessPrivileges, "请确认当前密码后继续操作", string(access.CodeRecentAuthRequired))
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
Action string `json:"action"`
|
||||
ID string `json:"id"`
|
||||
Code string `json:"code"`
|
||||
}
|
||||
if err := decodeJSONRequest(w, req, &input); err != nil {
|
||||
writeSecurityError(w, response.ParamsError, "动态码请求无效")
|
||||
return
|
||||
}
|
||||
var err error
|
||||
limitKey := loginSecondFactorAttempts.accountKey(ctx.UserAccount)
|
||||
if loginSecondFactorAttempts.blocked(limitKey) {
|
||||
writeSecurityError(w, response.ParamsError, "验证失败次数过多,请十五分钟后重试")
|
||||
return
|
||||
}
|
||||
switch input.Action {
|
||||
case "begin":
|
||||
enrollment, beginErr := service.BeginEnrollment(ctx.UserID, ctx.UserAccount)
|
||||
if beginErr != nil {
|
||||
writeSecurityError(w, response.ParamsError, "无法开始绑定,请刷新状态后重试")
|
||||
return
|
||||
}
|
||||
response.NewSuccessResponse(enrollment).FPrint(w)
|
||||
return
|
||||
case "confirm":
|
||||
err = service.ConfirmEnrollment(ctx.UserID, input.ID, strings.TrimSpace(input.Code))
|
||||
case "disable":
|
||||
err = service.Disable(ctx.UserID, strings.TrimSpace(input.Code))
|
||||
case "cancel":
|
||||
service.InvalidateUser(ctx.UserID)
|
||||
default:
|
||||
writeSecurityError(w, response.ParamsError, "动态码操作无效")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
loginSecondFactorAttempts.recordFailure(limitKey)
|
||||
writeSecurityError(w, response.ParamsError, "动态码无效、已使用或绑定已过期,请使用新的动态码重试")
|
||||
return
|
||||
}
|
||||
if input.Action == "confirm" || input.Action == "disable" {
|
||||
loginSecondFactorAttempts.clear(limitKey)
|
||||
InvalidateSecurityRuntimeUser(ctx.UserID, ctx.UserAccount)
|
||||
}
|
||||
response.NewSuccessResponse(map[string]any{"success": true}).FPrint(w)
|
||||
}
|
||||
Reference in new issue
Block a user