完善第三方协议授权码登录
Security Checks / security (push) Waiting to run

This commit is contained in:
xuans committed 2026-08-31 02:11:45 +08:00
1 parent e76e802cc3
commit 18f9fd34e5
18 files changed
+633 -17

No files matched your search

+19 -1
View File
@@ -9,6 +9,7 @@ import (
"git.pcux.cn/xuans/Smail/config"
"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/context"
"git.pcux.cn/xuans/Smail/utils/password"
)
@@ -145,16 +146,33 @@ func TestProtocolAuthenticationAcceptsConfiguredFullEmailIdentifier(t *testing.T
t.Fatal(err)
}
service, err := credentials.NewService(db.Instance)
if err != nil {
t.Fatal(err)
}
for _, protocol := range []string{"smtp", "imap", "pop3"} {
got, err := AuthenticateProtocol(protocol, "192.0.2.10:12345", " Alice@Example.com ", "CorrectP12")
if err := service.SetProtocolEnabled(user.ID, protocol, true); err != nil {
t.Fatalf("enable %s: %v", protocol, err)
}
code, err := service.GenerateProtocolCode(user.ID, protocol)
if err != nil {
t.Fatalf("generate %s code: %v", protocol, err)
}
got, err := AuthenticateProtocol(protocol, "192.0.2.10:12345", " Alice@Example.com ", code)
if err != nil {
t.Fatalf("%s full email authentication failed: %v", protocol, err)
}
if got == nil || got.Account != "alice" {
t.Fatalf("%s authenticated user = %+v", protocol, got)
}
if _, err := AuthenticateProtocol(protocol, "192.0.2.10:12345", "alice@example.com", "CorrectP12"); err == nil {
t.Fatalf("%s must reject the web password", protocol)
}
}
if _, err := AuthenticateProtocol("imap", "192.0.2.10:12345", "alice", "CorrectP12"); err == nil {
t.Fatal("account-only protocol login should be rejected")
}
if _, err := AuthenticateProtocol("imap", "192.0.2.10:12345", "alice@other.example", "CorrectP12"); err == nil {
t.Fatal("unconfigured email domain should be rejected")
}
+23 -5
View File
@@ -9,7 +9,9 @@ import (
"sync"
"time"
"git.pcux.cn/xuans/Smail/db"
"git.pcux.cn/xuans/Smail/models"
"git.pcux.cn/xuans/Smail/services/credentials"
)
const (
@@ -42,28 +44,44 @@ var (
)
func AuthenticateProtocol(protocol string, remoteAddress string, account string, plain string) (*models.User, error) {
normalizedProtocol, protocolErr := credentials.NormalizeProtocol(protocol)
normalizedAccount := strings.ToLower(strings.TrimSpace(account))
if normalizedIdentifier, err := NormalizeIdentifierKey(account); err == nil {
normalizedAccount = normalizedIdentifier
}
normalizedRemote := protocolRemoteHost(remoteAddress)
pairKey := hashedProtocolLoginKey("pair", protocol, normalizedRemote, normalizedAccount)
pairKey := hashedProtocolLoginKey("pair", normalizedProtocol, normalizedRemote, normalizedAccount)
accountKey := hashedProtocolLoginKey("account", normalizedAccount)
remoteKey := hashedProtocolLoginKey("remote", normalizedRemote)
if protocolPairAttempts.blocked(pairKey) || protocolAccountAttempts.blocked(accountKey) || protocolRemoteAttempts.blocked(remoteKey) {
return nil, errors.New("invalid credentials")
}
user, err := AuthenticateIdentifier(account, plain)
if err != nil {
fail := func() (*models.User, error) {
protocolPairAttempts.recordFailure(pairKey)
protocolAccountAttempts.recordFailure(accountKey)
protocolRemoteAttempts.recordFailure(remoteKey)
return nil, err
return nil, errors.New("invalid credentials")
}
if protocolErr != nil || db.Instance == nil {
return fail()
}
identity, err := ResolveIdentifier(account)
if err != nil || identity.Kind != IdentifierEmail || identity.UserID <= 0 {
return fail()
}
service, err := credentials.NewService(db.Instance)
if err != nil || !service.VerifyProtocolCode(identity.UserID, normalizedProtocol, plain) {
return fail()
}
var user models.User
has, err := db.Instance.ID(identity.UserID).Where("disabled = 0").Get(&user)
if err != nil || !has || user.ID <= 0 {
return fail()
}
protocolPairAttempts.clear(pairKey)
protocolAccountAttempts.clear(accountKey)
return user, nil
return &user, nil
}
func newProtocolLoginLimiter(failureLimit int) *protocolLoginLimiter {
+226
View File
@@ -0,0 +1,226 @@
package credentials
import (
"crypto/rand"
"encoding/base32"
"errors"
"fmt"
"strings"
"time"
"git.pcux.cn/xuans/Smail/models"
"git.pcux.cn/xuans/Smail/utils/password"
)
const (
ProtocolIMAP = "imap"
ProtocolPOP3 = "pop3"
ProtocolSMTP = "smtp"
)
var (
ErrInvalidProtocol = errors.New("invalid mail protocol")
ErrProtocolDisabled = errors.New("mail protocol is disabled")
ErrProtocolCodeMissing = errors.New("protocol authorization code is missing")
)
var supportedProtocols = []string{ProtocolIMAP, ProtocolPOP3, ProtocolSMTP}
// ProtocolCredentialStatus 返回协议开关和授权码状态,不包含授权码哈希。
type ProtocolCredentialStatus struct {
Protocol string `json:"protocol"`
Enabled bool `json:"enabled"`
Configured bool `json:"configured"`
CreatedAt *time.Time `json:"created_at,omitempty"`
UpdatedAt *time.Time `json:"updated_at,omitempty"`
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
}
func NormalizeProtocol(value string) (string, error) {
protocol := strings.ToLower(strings.TrimSpace(value))
switch protocol {
case ProtocolIMAP, ProtocolPOP3, ProtocolSMTP:
return protocol, nil
default:
return "", ErrInvalidProtocol
}
}
func SupportedProtocols() []string {
return append([]string(nil), supportedProtocols...)
}
// ListProtocolCredentials 返回当前用户三个邮件协议的完整状态。
func (s *Service) ListProtocolCredentials(userID int) ([]ProtocolCredentialStatus, error) {
if s == nil || s.engine == nil {
return nil, ErrUnavailable
}
if userID <= 0 {
return nil, ErrInvalidUser
}
var items []models.ProtocolCredential
if err := s.engine.Where("user_id = ?", userID).Find(&items); err != nil {
return nil, fmt.Errorf("load protocol credentials: %w", err)
}
byProtocol := make(map[string]models.ProtocolCredential, len(items))
for _, item := range items {
byProtocol[item.Protocol] = item
}
result := make([]ProtocolCredentialStatus, 0, len(supportedProtocols))
for _, protocol := range supportedProtocols {
status := ProtocolCredentialStatus{Protocol: protocol}
if item, ok := byProtocol[protocol]; ok {
createdAt := item.CreatedAt
updatedAt := item.UpdatedAt
status.Enabled = item.Enabled
status.Configured = item.CodeHash != "" && item.RevokedAt == nil
status.CreatedAt = &createdAt
status.UpdatedAt = &updatedAt
status.LastUsedAt = item.LastUsedAt
}
result = append(result, status)
}
return result, nil
}
// SetProtocolEnabled 设置用户级协议开关。关闭后授权码会保留,但认证立即失效。
func (s *Service) SetProtocolEnabled(userID int, protocol string, enabled bool) error {
if s == nil || s.engine == nil {
return ErrUnavailable
}
if userID <= 0 {
return ErrInvalidUser
}
protocol, err := NormalizeProtocol(protocol)
if err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
var item models.ProtocolCredential
has, err := s.engine.Where("user_id = ? AND protocol = ?", userID, protocol).Get(&item)
if err != nil {
return fmt.Errorf("load protocol credential: %w", err)
}
if !has {
item = models.ProtocolCredential{UserID: userID, Protocol: protocol, Enabled: enabled, CodeVersion: 1}
if _, err := s.engine.Insert(&item); err != nil {
return fmt.Errorf("create protocol credential: %w", err)
}
return nil
}
item.Enabled = enabled
if _, err := s.engine.ID(item.ID).Cols("enabled", "updated_at").Update(&item); err != nil {
return fmt.Errorf("update protocol credential: %w", err)
}
return nil
}
// GenerateProtocolCode 生成只展示一次的协议授权码,并撤销同协议旧授权码。
func (s *Service) GenerateProtocolCode(userID int, protocol string) (string, error) {
if s == nil || s.engine == nil {
return "", ErrUnavailable
}
if userID <= 0 {
return "", ErrInvalidUser
}
protocol, err := NormalizeProtocol(protocol)
if err != nil {
return "", err
}
plain, err := newProtocolCode()
if err != nil {
return "", err
}
hash, err := password.Hash(plain)
if err != nil {
return "", fmt.Errorf("hash protocol authorization code: %w", err)
}
s.mu.Lock()
defer s.mu.Unlock()
var item models.ProtocolCredential
has, err := s.engine.Where("user_id = ? AND protocol = ?", userID, protocol).Get(&item)
if err != nil {
return "", fmt.Errorf("load protocol credential: %w", err)
}
if !has || !item.Enabled {
return "", ErrProtocolDisabled
}
version := item.CodeVersion + 1
if version <= 1 {
version = 1
}
item.CodeHash = hash
item.CodeVersion = version
item.RevokedAt = nil
item.LastUsedAt = nil
if _, err := s.engine.ID(item.ID).Cols("code_hash", "code_version", "revoked_at", "last_used_at", "updated_at").Update(&item); err != nil {
return "", fmt.Errorf("update protocol authorization code: %w", err)
}
return plain, nil
}
// RevokeProtocolCode 撤销指定协议的授权码,协议开关状态保持不变。
func (s *Service) RevokeProtocolCode(userID int, protocol string) error {
if s == nil || s.engine == nil {
return ErrUnavailable
}
if userID <= 0 {
return ErrInvalidUser
}
protocol, err := NormalizeProtocol(protocol)
if err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
now := s.now()
if _, err := s.engine.Where("user_id = ? AND protocol = ? AND revoked_at IS NULL", userID, protocol).
Cols("revoked_at", "updated_at").
Update(&models.ProtocolCredential{RevokedAt: &now}); err != nil {
return fmt.Errorf("revoke protocol authorization code: %w", err)
}
return nil
}
// VerifyProtocolCode 校验协议开关和授权码,不接受网页登录密码。
func (s *Service) VerifyProtocolCode(userID int, protocol string, plain string) bool {
if s == nil || s.engine == nil || userID <= 0 || plain == "" || len([]byte(plain)) > 256 {
password.VerifyDummy(plain)
return false
}
protocol, err := NormalizeProtocol(protocol)
if err != nil {
password.VerifyDummy(plain)
return false
}
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
}
if !password.Verify(item.CodeHash, strings.TrimSpace(plain)) {
return false
}
now := s.now()
_, _ = s.engine.ID(item.ID).Cols("last_used_at", "updated_at").Update(&models.ProtocolCredential{LastUsedAt: &now})
return true
}
func newProtocolCode() (string, error) {
buf := make([]byte, 15)
if _, err := rand.Read(buf); err != nil {
return "", fmt.Errorf("generate protocol authorization code: %w", err)
}
encoded := base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(buf)
groups := make([]string, 0, 6)
for len(encoded) > 4 {
groups = append(groups, encoded[:4])
encoded = encoded[4:]
}
if encoded != "" {
groups = append(groups, encoded)
}
return strings.Join(groups, "-"), nil
}
+7
View File
@@ -281,6 +281,9 @@ func (s *Service) RevokeAllWithSession(session *xorm.Session, userID int) error
if _, err := session.Where("user_id = ? AND revoked_at IS NULL", userID).Cols("revoked_at").Update(&models.WebAuthnCredential{RevokedAt: &now}); err != nil {
return fmt.Errorf("revoke webauthn credentials: %w", err)
}
if _, err := session.Where("user_id = ? AND revoked_at IS NULL", userID).Cols("revoked_at", "updated_at").Update(&models.ProtocolCredential{RevokedAt: &now}); err != nil {
return fmt.Errorf("revoke protocol credentials: %w", err)
}
return nil
}
@@ -306,6 +309,10 @@ func revokeAllOnSession(session *xorm.Session, now func() time.Time, userID int)
_ = session.Rollback()
return fmt.Errorf("revoke webauthn credentials: %w", err)
}
if _, err := session.Where("user_id = ? AND revoked_at IS NULL", userID).Cols("revoked_at", "updated_at").Update(&models.ProtocolCredential{RevokedAt: &when}); err != nil {
_ = session.Rollback()
return fmt.Errorf("revoke protocol credentials: %w", err)
}
if err := session.Commit(); err != nil {
return fmt.Errorf("commit credential revocation: %w", err)
}
+38 -1
View File
@@ -3,6 +3,7 @@ package credentials
import (
"errors"
"path/filepath"
"strings"
"sync"
"testing"
@@ -18,7 +19,7 @@ func newFixture(t *testing.T) *Service {
t.Fatal(err)
}
t.Cleanup(func() { _ = engine.Close() })
if err := engine.Sync2(&models.User{}, &models.SecurityQuestion{}, &models.RecoveryCode{}, &models.WebAuthnCredential{}); err != nil {
if err := engine.Sync2(&models.User{}, &models.SecurityQuestion{}, &models.RecoveryCode{}, &models.WebAuthnCredential{}, &models.ProtocolCredential{}); err != nil {
t.Fatal(err)
}
if _, err := engine.Insert(&models.User{Account: "alice", Name: "Alice", Password: "unused", Role: "user"}); err != nil {
@@ -107,3 +108,39 @@ func TestRecoveryCodeConcurrentConsumptionHasOneWinner(t *testing.T) {
t.Fatalf("winners = %d", winners)
}
}
func TestProtocolCredentialLifecycle(t *testing.T) {
service := newFixture(t)
if err := service.SetProtocolEnabled(1, ProtocolSMTP, true); err != nil {
t.Fatal(err)
}
statuses, err := service.ListProtocolCredentials(1)
if err != nil {
t.Fatal(err)
}
if len(statuses) != 3 || !statuses[2].Enabled || statuses[2].Configured {
t.Fatalf("unexpected initial protocol status: %+v", statuses)
}
if _, err := service.GenerateProtocolCode(1, ProtocolIMAP); !errors.Is(err, ErrProtocolDisabled) {
t.Fatalf("generating a disabled protocol code error = %v", err)
}
code, err := service.GenerateProtocolCode(1, ProtocolSMTP)
if err != nil {
t.Fatal(err)
}
if code == "" || strings.Contains(code, " ") {
t.Fatalf("invalid generated protocol code %q", code)
}
if !service.VerifyProtocolCode(1, ProtocolSMTP, code) {
t.Fatal("generated protocol code was rejected")
}
if service.VerifyProtocolCode(1, ProtocolSMTP, "wrong-code") {
t.Fatal("wrong protocol code was accepted")
}
if err := service.RevokeProtocolCode(1, ProtocolSMTP); err != nil {
t.Fatal(err)
}
if service.VerifyProtocolCode(1, ProtocolSMTP, code) {
t.Fatal("revoked protocol code was accepted")
}
}
+1 -1
View File
@@ -23,7 +23,7 @@ func newRecoveryFixture(t *testing.T) (*Service, *verification.Service, *xorm.En
t.Fatal(err)
}
t.Cleanup(func() { _ = engine.Close() })
for _, table := range []any{&models.User{}, &models.ExternalEmail{}, &models.Sessions{}, &models.SecurityQuestion{}, &models.RecoveryCode{}, &models.WebAuthnCredential{}} {
for _, table := range []any{&models.User{}, &models.ExternalEmail{}, &models.Sessions{}, &models.SecurityQuestion{}, &models.RecoveryCode{}, &models.WebAuthnCredential{}, &models.ProtocolCredential{}} {
if err := engine.Sync2(table); err != nil {
t.Fatal(err)
}