保存认证容量保护整改检查点待远程复审
This commit is contained in:
1 parent
e49e392fd1
commit
e30f21849f
27 files changed
+721
-53
No files matched your search
@@ -28,7 +28,9 @@ func AuthenticateIdentifier(identifier, plain string) (*models.User, error) {
|
||||
identity, err := ResolveIdentifier(identifier)
|
||||
if err != nil {
|
||||
if plain != "" {
|
||||
password.VerifyDummy(plain)
|
||||
if err := password.CheckDummy(plain); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nil, errors.New("invalid credentials")
|
||||
}
|
||||
@@ -57,7 +59,9 @@ func AuthenticateUserByID(userID int, plain string) (*models.User, error) {
|
||||
func authenticateUserByID(userID int, plain string) (*models.User, error) {
|
||||
if userID <= 0 {
|
||||
if plain != "" {
|
||||
password.VerifyDummy(plain)
|
||||
if err := password.CheckDummy(plain); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nil, errors.New("invalid credentials")
|
||||
}
|
||||
@@ -72,16 +76,24 @@ func authenticateUserByID(userID int, plain string) (*models.User, error) {
|
||||
func authenticateLoadedUser(user *models.User, has bool, err error, plain string) (*models.User, error) {
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
password.VerifyDummy(plain)
|
||||
if err := password.CheckDummy(plain); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, errors.New("invalid credentials")
|
||||
}
|
||||
return nil, fmt.Errorf("load user: %w", err)
|
||||
}
|
||||
if !has || user.ID == 0 {
|
||||
password.VerifyDummy(plain)
|
||||
if err := password.CheckDummy(plain); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, errors.New("invalid credentials")
|
||||
}
|
||||
if !password.Verify(user.Password, plain) {
|
||||
matched, err := password.Check(user.Password, plain)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !matched {
|
||||
return nil, errors.New("invalid credentials")
|
||||
}
|
||||
return user, nil
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"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/credentials"
|
||||
"git.pcux.cn/xuans/Smail/utils/password"
|
||||
)
|
||||
|
||||
func TestProtocolBusyDoesNotCountAsCredentialFailure(t *testing.T) {
|
||||
oldConfig, oldDB := config.Instance, db.Instance
|
||||
oldPair, oldAccount, oldRemote := protocolPairAttempts, protocolAccountAttempts, protocolRemoteAttempts
|
||||
config.Instance = &config.Config{DbType: config.DBTypeSQLite, DbDSN: filepath.Join(t.TempDir(), "capacity.db"), Domain: "example.com"}
|
||||
if err := db.Init(""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = db.Instance.Close()
|
||||
config.Instance, db.Instance = oldConfig, oldDB
|
||||
protocolPairAttempts, protocolAccountAttempts, protocolRemoteAttempts = oldPair, oldAccount, oldRemote
|
||||
})
|
||||
protocolPairAttempts = newProtocolLoginLimiter(1)
|
||||
protocolAccountAttempts = newProtocolLoginLimiter(1)
|
||||
protocolRemoteAttempts = newProtocolLoginLimiter(1)
|
||||
user := models.User{Account: "capacity-user"}
|
||||
if err := SetPassword(&user, "CorrectP12"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Instance.Insert(&user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
address, now := "capacity-user@example.com", time.Now().UTC()
|
||||
if _, err := db.Instance.Insert(&models.UserEmail{UserID: user.ID, Address: address, AddressCanonical: &address, VerifiedAt: &now}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service, err := credentials.NewService(db.Instance)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
code, _, err := service.CreateClientCredential(user.ID, "容量验收")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
release := passwordtest.Hold(t)
|
||||
for index := 0; index < 12; index++ {
|
||||
for _, protocol := range []string{"smtp", "imap", "pop3"} {
|
||||
if got, err := AuthenticateProtocol(protocol, "192.0.2.70:1234", address, code); got != nil || !errors.Is(err, password.ErrBusy) {
|
||||
t.Fatalf("%s 繁忙被当成凭据失败:%v", protocol, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, account := range []string{user.Account, "missing-user"} {
|
||||
if _, err := Authenticate(account, "CorrectP12"); !errors.Is(err, password.ErrBusy) {
|
||||
t.Fatalf("真实或模拟密码校验未传递繁忙:%v", err)
|
||||
}
|
||||
}
|
||||
if len(protocolPairAttempts.attempts)+len(protocolAccountAttempts.attempts)+len(protocolRemoteAttempts.attempts) != 0 {
|
||||
t.Fatal("资源繁忙增加了协议失败计数")
|
||||
}
|
||||
release()
|
||||
for _, protocol := range []string{"smtp", "imap", "pop3"} {
|
||||
if got, err := AuthenticateProtocol(protocol, "192.0.2.70:1234", address, code); err != nil || got.ID != user.ID {
|
||||
t.Fatalf("%s 繁忙结束后无法正常登录:%v", protocol, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"git.pcux.cn/xuans/Smail/db"
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
"git.pcux.cn/xuans/Smail/services/credentials"
|
||||
"git.pcux.cn/xuans/Smail/utils/password"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -81,7 +82,14 @@ func AuthenticateProtocol(protocol string, remoteAddress string, account string,
|
||||
}
|
||||
|
||||
service, err := credentials.NewService(db.Instance)
|
||||
if err != nil || !service.VerifyClientOrProtocolCode(userID, normalizedProtocol, plain) {
|
||||
if err != nil {
|
||||
return fail()
|
||||
}
|
||||
matched, err := service.CheckClientOrProtocolCode(userID, normalizedProtocol, plain)
|
||||
if errors.Is(err, password.ErrBusy) {
|
||||
return nil, err
|
||||
}
|
||||
if err != nil || !matched {
|
||||
return fail()
|
||||
}
|
||||
var user models.User
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package credentials
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/internal/passwordtest"
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
"git.pcux.cn/xuans/Smail/utils/password"
|
||||
)
|
||||
|
||||
func TestCredentialBusyDoesNotConsumeOrReplaceCodes(t *testing.T) {
|
||||
service := newFixture(t)
|
||||
if err := service.engine.Sync2(&models.ClientCredential{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := service.SetSecurityQuestion(1, "问题", "answer"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := service.SetProtocolEnabled(1, ProtocolIMAP, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
protocolCode, err := service.GenerateProtocolCode(1, ProtocolIMAP)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
codes, err := service.GenerateRecoveryCodes(1, 5)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
release := passwordtest.Hold(t)
|
||||
if _, err := service.VerifySecurityQuestion(1, "answer"); !errors.Is(err, password.ErrBusy) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := service.CheckProtocolCode(1, ProtocolIMAP, protocolCode); !errors.Is(err, password.ErrBusy) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := service.CheckClientOrProtocolCode(1, ProtocolIMAP, protocolCode); !errors.Is(err, password.ErrBusy) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := service.ConsumeRecoveryCode(1, codes[0]); !errors.Is(err, password.ErrBusy) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := service.GenerateRecoveryCodes(1, 5); !errors.Is(err, password.ErrBusy) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
release()
|
||||
if err := service.ConsumeRecoveryCode(1, codes[0]); err != nil {
|
||||
t.Fatalf("繁忙后恢复码已被错误消费或撤销:%v", err)
|
||||
}
|
||||
if _, err := service.CheckProtocolCode(1, ProtocolIMAP, protocolCode); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package credentials
|
||||
package credentials
|
||||
|
||||
import (
|
||||
"errors"
|
||||
@@ -286,14 +286,18 @@ func (s *Service) RevealClientCredentials(userID int) (map[int]string, error) {
|
||||
|
||||
// VerifyClientOrProtocolCode 同时支持客户端专属授权码以及遗留的协议授权码
|
||||
func (s *Service) VerifyClientOrProtocolCode(userID int, protocol string, rawPlain string) bool {
|
||||
matched, _ := s.CheckClientOrProtocolCode(userID, protocol, rawPlain)
|
||||
return matched
|
||||
}
|
||||
|
||||
// CheckClientOrProtocolCode 将计算过载向上返回,避免被当成密码错误累计封禁。
|
||||
func (s *Service) CheckClientOrProtocolCode(userID int, protocol string, rawPlain string) (bool, error) {
|
||||
if s == nil || s.engine == nil || userID <= 0 || rawPlain == "" || len([]byte(rawPlain)) > 256 {
|
||||
password.VerifyDummy(rawPlain)
|
||||
return false
|
||||
return false, password.CheckDummy(rawPlain)
|
||||
}
|
||||
cleanedPlain := CleanAuthCode(rawPlain)
|
||||
if cleanedPlain == "" {
|
||||
password.VerifyDummy(rawPlain)
|
||||
return false
|
||||
return false, password.CheckDummy(rawPlain)
|
||||
}
|
||||
|
||||
// 1. 优先校验客户端专属授权码
|
||||
@@ -302,12 +306,22 @@ func (s *Service) VerifyClientOrProtocolCode(userID int, protocol string, rawPla
|
||||
if err == nil && len(clients) > 0 {
|
||||
for _, client := range clients {
|
||||
// 比对清洗后的统一大写无横线授权码
|
||||
if password.Verify(client.CodeHash, cleanedPlain) {
|
||||
matched, err := password.Check(client.CodeHash, cleanedPlain)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if matched {
|
||||
now := s.now()
|
||||
_, _ = s.engine.ID(client.ID).
|
||||
affected, err := s.engine.ID(client.ID).
|
||||
Where("revoked_at IS NULL AND code_version = ? AND code_hash = ?", client.CodeVersion, client.CodeHash).
|
||||
Cols("last_used_at", "updated_at").Update(&models.ClientCredential{LastUsedAt: &now})
|
||||
return true
|
||||
if err != nil || affected == 1 {
|
||||
return err == nil, err
|
||||
}
|
||||
valid, err := s.engine.ID(client.ID).
|
||||
Where("revoked_at IS NULL AND code_version = ? AND code_hash = ?", client.CodeVersion, client.CodeHash).
|
||||
Exist(&models.ClientCredential{})
|
||||
return valid, err
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -315,20 +329,25 @@ func (s *Service) VerifyClientOrProtocolCode(userID int, protocol string, rawPla
|
||||
// 2. 回退校验旧版按协议划分的授权码(支持 cleanedPlain 或原樣 rawPlain)
|
||||
protocol, err = NormalizeProtocol(protocol)
|
||||
if err != nil {
|
||||
password.VerifyDummy(rawPlain)
|
||||
return false
|
||||
return false, password.CheckDummy(rawPlain)
|
||||
}
|
||||
var item models.ProtocolCredential
|
||||
has, err := s.engine.Where("user_id = ? AND protocol = ? AND enabled = ? AND revoked_at IS NULL", userID, protocol, true).Get(&item)
|
||||
if err != nil || !has || item.CodeHash == "" {
|
||||
password.VerifyDummy(rawPlain)
|
||||
return false
|
||||
return false, password.CheckDummy(rawPlain)
|
||||
}
|
||||
|
||||
// 兼容旧哈希直接比对原始输入,或者比对清洗后的输入
|
||||
matched := password.Verify(item.CodeHash, strings.TrimSpace(rawPlain)) || password.Verify(item.CodeHash, cleanedPlain)
|
||||
if !matched {
|
||||
return false
|
||||
trimmedPlain := strings.TrimSpace(rawPlain)
|
||||
matched, err := password.Check(item.CodeHash, trimmedPlain)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if !matched && trimmedPlain != cleanedPlain {
|
||||
matched, err = password.Check(item.CodeHash, cleanedPlain)
|
||||
}
|
||||
if err != nil || !matched {
|
||||
return false, err
|
||||
}
|
||||
|
||||
now := s.now()
|
||||
@@ -336,11 +355,14 @@ func (s *Service) VerifyClientOrProtocolCode(userID int, protocol string, rawPla
|
||||
Where("enabled = ? AND revoked_at IS NULL AND code_version = ? AND code_hash = ?", true, item.CodeVersion, item.CodeHash).
|
||||
Cols("last_used_at", "updated_at").Update(&models.ProtocolCredential{LastUsedAt: &now})
|
||||
if err == nil && affected == 1 {
|
||||
return true
|
||||
return true, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
valid, err := s.engine.ID(item.ID).
|
||||
Where("enabled = ? AND revoked_at IS NULL AND code_version = ? AND code_hash = ?", true, item.CodeVersion, item.CodeHash).
|
||||
Exist(&models.ProtocolCredential{})
|
||||
return err == nil && valid
|
||||
return valid, err
|
||||
}
|
||||
@@ -9,8 +9,8 @@ import (
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
"git.pcux.cn/xuans/Smail/utils/password"
|
||||
"git.pcux.cn/xuans/Smail/utils/credential"
|
||||
"git.pcux.cn/xuans/Smail/utils/password"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -189,30 +189,34 @@ func (s *Service) RevokeProtocolCode(userID int, protocol string) error {
|
||||
if _, err := s.engine.Where("user_id = ? AND protocol = ? AND revoked_at IS NULL", userID, protocol).
|
||||
Cols("revoked_at", "code_hash", "code_ciphertext", "updated_at").
|
||||
Update(&models.ProtocolCredential{RevokedAt: &now, CodeHash: "", CodeCiphertext: ""}); err != nil {
|
||||
return fmt.Errorf("revoke protocol authorization code: %w", err)
|
||||
return fmt.Errorf("revoke protocol authorization code: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// VerifyProtocolCode 校验协议开关和授权码,不接受网页登录密码。
|
||||
func (s *Service) VerifyProtocolCode(userID int, protocol string, plain string) bool {
|
||||
matched, _ := s.CheckProtocolCode(userID, protocol, plain)
|
||||
return matched
|
||||
}
|
||||
|
||||
// CheckProtocolCode 保留计算过载错误,供需要区分重试与认证失败的调用方使用。
|
||||
func (s *Service) CheckProtocolCode(userID int, protocol string, plain string) (bool, error) {
|
||||
if s == nil || s.engine == nil || userID <= 0 || plain == "" || len([]byte(plain)) > 256 {
|
||||
password.VerifyDummy(plain)
|
||||
return false
|
||||
return false, password.CheckDummy(plain)
|
||||
}
|
||||
protocol, err := NormalizeProtocol(protocol)
|
||||
if err != nil {
|
||||
password.VerifyDummy(plain)
|
||||
return false
|
||||
return false, password.CheckDummy(plain)
|
||||
}
|
||||
var item models.ProtocolCredential
|
||||
has, err := s.engine.Where("user_id = ? AND protocol = ? AND enabled = ? AND revoked_at IS NULL", userID, protocol, true).Get(&item)
|
||||
if err != nil || !has || item.CodeHash == "" {
|
||||
password.VerifyDummy(plain)
|
||||
return false
|
||||
return false, password.CheckDummy(plain)
|
||||
}
|
||||
if !password.Verify(item.CodeHash, strings.TrimSpace(plain)) {
|
||||
return false
|
||||
matched, err := password.Check(item.CodeHash, strings.TrimSpace(plain))
|
||||
if err != nil || !matched {
|
||||
return false, err
|
||||
}
|
||||
now := s.now()
|
||||
// 哈希计算期间可能发生关闭、撤销或换码,返回成功前必须再次原子确认凭据状态。
|
||||
@@ -220,16 +224,16 @@ func (s *Service) VerifyProtocolCode(userID int, protocol string, plain string)
|
||||
Where("enabled = ? AND revoked_at IS NULL AND code_version = ? AND code_hash = ?", true, item.CodeVersion, item.CodeHash).
|
||||
Cols("last_used_at", "updated_at").Update(&models.ProtocolCredential{LastUsedAt: &now})
|
||||
if err != nil {
|
||||
return false
|
||||
return false, err
|
||||
}
|
||||
if affected == 1 {
|
||||
return true
|
||||
return true, nil
|
||||
}
|
||||
// MySQL 在时间字段未变化时可能报告零影响行,必须再次查询有效状态而不是误拒绝或直接放行。
|
||||
valid, err := s.engine.ID(item.ID).
|
||||
Where("enabled = ? AND revoked_at IS NULL AND code_version = ? AND code_hash = ?", true, item.CodeVersion, item.CodeHash).
|
||||
Exist(&models.ProtocolCredential{})
|
||||
return err == nil && valid
|
||||
return valid, err
|
||||
}
|
||||
|
||||
func newProtocolCode() (string, error) {
|
||||
|
||||
@@ -133,10 +133,9 @@ func (s *Service) VerifySecurityQuestion(userID int, answer string) (bool, error
|
||||
return false, fmt.Errorf("load security question: %w", err)
|
||||
}
|
||||
if !has {
|
||||
password.VerifyDummy(answer)
|
||||
return false, nil
|
||||
return false, password.CheckDummy(answer)
|
||||
}
|
||||
return password.Verify(item.AnswerHash, answer), nil
|
||||
return password.Check(item.AnswerHash, answer)
|
||||
}
|
||||
|
||||
// GenerateRecoveryCodes 撤销旧码并生成一组只返回一次的离线恢复码。
|
||||
@@ -241,7 +240,11 @@ func (s *Service) consumeRecoveryCode(session recoveryCodeSession, userID int, c
|
||||
return fmt.Errorf("load recovery codes: %w", err)
|
||||
}
|
||||
for _, item := range items {
|
||||
if !password.Verify(item.CodeHash, code) {
|
||||
matched, err := password.Check(item.CodeHash, code)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !matched {
|
||||
continue
|
||||
}
|
||||
now := s.now()
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package recovery
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/internal/passwordtest"
|
||||
"git.pcux.cn/xuans/Smail/utils/password"
|
||||
)
|
||||
|
||||
func TestRecoveryBusyPreservesTicket(t *testing.T) {
|
||||
service, _, _, user := newRecoveryFixture(t)
|
||||
ticketID, err := service.issueTicket(user.ID, user.SessionVersion)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
release := passwordtest.Hold(t)
|
||||
for index := 0; index < 12; index++ {
|
||||
if err := service.Complete(ticketID, "NewPass123"); !errors.Is(err, password.ErrBusy) {
|
||||
t.Fatalf("繁忙期间票据失效或返回错误:%v", err)
|
||||
}
|
||||
}
|
||||
release()
|
||||
if err := service.Complete(ticketID, "NewPass123"); err != nil {
|
||||
t.Fatalf("繁忙恢复后不能使用原票据:%v", err)
|
||||
}
|
||||
if err := service.Complete(ticketID, "OtherPass12"); !errors.Is(err, ErrRecoveryExpired) {
|
||||
t.Fatalf("成功后票据未保持一次性:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecoveryBusyDoesNotRestoreRevokedTicket(t *testing.T) {
|
||||
service, _, _, user := newRecoveryFixture(t)
|
||||
ticketID, err := service.issueTicket(user.ID, user.SessionVersion)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
release := passwordtest.Hold(t)
|
||||
if err := service.Complete(ticketID, "NewPass123"); !errors.Is(err, password.ErrBusy) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service.InvalidateUser(user.ID)
|
||||
release()
|
||||
if err := service.Complete(ticketID, "NewPass123"); !errors.Is(err, ErrRecoveryExpired) {
|
||||
t.Fatalf("撤销的票据被恢复:%v", err)
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,12 @@ package recovery
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/services/access"
|
||||
"git.pcux.cn/xuans/Smail/services/auth"
|
||||
"git.pcux.cn/xuans/Smail/utils/password"
|
||||
)
|
||||
|
||||
const maxEmailContinuationAttempts = 5
|
||||
@@ -93,10 +95,14 @@ func (s *Service) ContinueEmailWithContext(continuation, identifier, email, reco
|
||||
|
||||
// 数据库和恢复码哈希验证不占用全局锁;同一凭证同时只能有一个请求验证。
|
||||
invalidate := false
|
||||
busy := false
|
||||
defer func() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.emailPending[key] == pending {
|
||||
if busy {
|
||||
pending.Attempts--
|
||||
}
|
||||
if invalidate || pending.Attempts >= maxEmailContinuationAttempts {
|
||||
delete(s.emailPending, key)
|
||||
} else {
|
||||
@@ -115,6 +121,10 @@ func (s *Service) ContinueEmailWithContext(continuation, identifier, email, reco
|
||||
return "", ErrRecoveryDenied
|
||||
}
|
||||
if err := s.credentials.ConsumeRecoveryCode(user.ID, recoveryCode); err != nil {
|
||||
if errors.Is(err, password.ErrBusy) {
|
||||
busy = true
|
||||
return "", err
|
||||
}
|
||||
return "", ErrRecoveryDenied
|
||||
}
|
||||
invalidate = true
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package recovery
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -203,6 +204,9 @@ func (s *Service) CompletePublicLink(token, newPassword, recoveryCode string) er
|
||||
}()
|
||||
if user.EffectiveRole() == access.RoleAdmin {
|
||||
if err := s.credentials.ConsumeRecoveryCodeWithSession(session, user.ID, recoveryCode); err != nil {
|
||||
if errors.Is(err, password.ErrBusy) {
|
||||
return err
|
||||
}
|
||||
if s.recordPublicRecoveryCodeFailure(key, item) {
|
||||
consume = true
|
||||
}
|
||||
|
||||
@@ -63,6 +63,7 @@ type Service struct {
|
||||
}
|
||||
|
||||
type ticket struct {
|
||||
Busy bool
|
||||
UserID int
|
||||
SessionVersion int
|
||||
Method string
|
||||
@@ -249,6 +250,9 @@ func (s *Service) VerifyWithContext(challengeID, account, email, code, recoveryC
|
||||
return "", ErrRecoveryDenied
|
||||
}
|
||||
if err := s.credentials.ConsumeRecoveryCode(user.ID, recoveryCode); err != nil {
|
||||
if errors.Is(err, password.ErrBusy) {
|
||||
return "", err
|
||||
}
|
||||
return "", ErrRecoveryDenied
|
||||
}
|
||||
method = "email_admin"
|
||||
@@ -297,17 +301,26 @@ func (s *Service) VerifyOfflineWithContext(identifier, question, answer, recover
|
||||
}
|
||||
user, err := s.loadRecoverableUser(identifier)
|
||||
if err != nil {
|
||||
password.VerifyDummy(answer)
|
||||
password.VerifyDummy(recoveryCode)
|
||||
if err := password.CheckDummy(answer); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := password.CheckDummy(recoveryCode); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "", ErrRecoveryDenied
|
||||
}
|
||||
storedQuestion, configured, questionErr := s.credentials.GetSecurityQuestion(user.ID)
|
||||
answerVerified, answerErr := s.credentials.VerifySecurityQuestion(user.ID, answer)
|
||||
if errors.Is(answerErr, password.ErrBusy) {
|
||||
return "", answerErr
|
||||
}
|
||||
providedQuestionDigest := sha256.Sum256([]byte(strings.TrimSpace(question)))
|
||||
storedQuestionDigest := sha256.Sum256([]byte(strings.TrimSpace(storedQuestion)))
|
||||
questionVerified := configured && subtle.ConstantTimeCompare(providedQuestionDigest[:], storedQuestionDigest[:]) == 1
|
||||
if questionErr != nil || answerErr != nil || !questionVerified || !answerVerified {
|
||||
password.VerifyDummy(recoveryCode)
|
||||
if err := password.CheckDummy(recoveryCode); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "", ErrRecoveryDenied
|
||||
}
|
||||
ticketID, err := s.issueTicketFor(user.ID, user.SessionVersion, "offline", 0, 0, browserContext)
|
||||
@@ -316,6 +329,9 @@ func (s *Service) VerifyOfflineWithContext(identifier, question, answer, recover
|
||||
}
|
||||
if err := s.credentials.ConsumeRecoveryCode(user.ID, recoveryCode); err != nil {
|
||||
s.invalidateTicket(ticketID)
|
||||
if errors.Is(err, password.ErrBusy) {
|
||||
return "", err
|
||||
}
|
||||
return "", ErrRecoveryDenied
|
||||
}
|
||||
return ticketID, nil
|
||||
@@ -342,6 +358,10 @@ func (s *Service) CompleteWithContext(ticketID, newPassword, browserContext stri
|
||||
s.mu.Unlock()
|
||||
return ErrRecoveryExpired
|
||||
}
|
||||
if item.Busy {
|
||||
s.mu.Unlock()
|
||||
return ErrRecoveryDenied
|
||||
}
|
||||
if item.HasBrowserContextDigest {
|
||||
providedDigest := sha256.Sum256([]byte(strings.TrimSpace(browserContext)))
|
||||
if strings.TrimSpace(browserContext) == "" || subtle.ConstantTimeCompare(providedDigest[:], item.BrowserContextDigest[:]) != 1 {
|
||||
@@ -349,11 +369,28 @@ func (s *Service) CompleteWithContext(ticketID, newPassword, browserContext stri
|
||||
return ErrRecoveryDenied
|
||||
}
|
||||
}
|
||||
delete(s.tickets, ticketDigest)
|
||||
item.Busy = true
|
||||
s.tickets[ticketDigest] = item
|
||||
s.mu.Unlock()
|
||||
|
||||
// 过载时保留同一张有效票据,已失效或已被撤销的票据不得恢复。
|
||||
retry := false
|
||||
defer func() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if current, exists := s.tickets[ticketDigest]; exists && current == item {
|
||||
if retry && s.now().Before(item.ExpiresAt) {
|
||||
item.Busy = false
|
||||
s.tickets[ticketDigest] = item
|
||||
} else {
|
||||
delete(s.tickets, ticketDigest)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
hash, err := auth.HashPassword(newPassword)
|
||||
if err != nil {
|
||||
retry = errors.Is(err, password.ErrBusy)
|
||||
return err
|
||||
}
|
||||
defer clearString(&hash)
|
||||
|
||||
Reference in new issue
Block a user