1 parent
e27db1e57b
commit
b365c2535f
13 files changed
+533
-77
No files matched your search
@@ -4,7 +4,6 @@ import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/mail"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
@@ -23,66 +22,19 @@ func NormalizeAccount(account string) string {
|
||||
return strings.TrimSpace(account)
|
||||
}
|
||||
|
||||
// AuthenticateIdentifier 支持账号和受信主域名邮箱两种登录标识,最终统一到同一账号密码校验。
|
||||
// AuthenticateIdentifier 支持账号和已验证邮箱两种登录标识,最终统一到同一账号密码校验。
|
||||
func AuthenticateIdentifier(identifier, plain string) (*models.User, error) {
|
||||
account, err := NormalizeIdentifier(identifier)
|
||||
identity, err := ResolveIdentifier(identifier)
|
||||
if err != nil {
|
||||
if plain != "" {
|
||||
password.VerifyDummy(plain)
|
||||
}
|
||||
return nil, errors.New("invalid credentials")
|
||||
}
|
||||
return Authenticate(account, plain)
|
||||
}
|
||||
|
||||
// NormalizeIdentifier 将完整邮箱解析为本地账号,并拒绝未配置的域名。
|
||||
func NormalizeIdentifier(identifier string) (string, error) {
|
||||
identifier = strings.TrimSpace(identifier)
|
||||
if identifier == "" || strings.ContainsAny(identifier, "\r\n") {
|
||||
return "", errors.New("invalid identifier")
|
||||
if identity.Kind == IdentifierEmail {
|
||||
return authenticateUserByID(identity.UserID, plain)
|
||||
}
|
||||
if !strings.Contains(identifier, "@") {
|
||||
return validation.NormalizeAccount(identifier)
|
||||
}
|
||||
identifier = strings.ToLower(identifier)
|
||||
parsed, err := mail.ParseAddress(identifier)
|
||||
if err != nil || parsed.Address != identifier {
|
||||
return "", errors.New("invalid identifier")
|
||||
}
|
||||
parts := strings.Split(identifier, "@")
|
||||
if len(parts) != 2 || parts[0] == "" || !isConfiguredLoginDomain(parts[1]) {
|
||||
return "", errors.New("invalid identifier")
|
||||
}
|
||||
return validation.NormalizeAccount(parts[0])
|
||||
}
|
||||
|
||||
func isConfiguredLoginDomain(domain string) bool {
|
||||
domain = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(domain)), ".")
|
||||
if manager := config.CurrentManager(); manager != nil {
|
||||
runtime := manager.Snapshot()
|
||||
if strings.TrimSuffix(strings.ToLower(strings.TrimSpace(runtime.Root.Domains.Primary)), ".") == domain {
|
||||
return true
|
||||
}
|
||||
for _, item := range runtime.Root.Domains.Accepted {
|
||||
if strings.TrimSuffix(strings.ToLower(strings.TrimSpace(item)), ".") == domain {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
current := config.CurrentConfig()
|
||||
if current == nil {
|
||||
return false
|
||||
}
|
||||
if strings.TrimSuffix(strings.ToLower(strings.TrimSpace(current.Domain)), ".") == domain {
|
||||
return true
|
||||
}
|
||||
for _, item := range current.Domains {
|
||||
if strings.TrimSuffix(strings.ToLower(strings.TrimSpace(item)), ".") == domain {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
return Authenticate(identity.Account, plain)
|
||||
}
|
||||
|
||||
func Authenticate(account, plain string) (*models.User, error) {
|
||||
@@ -93,6 +45,25 @@ func Authenticate(account, plain string) (*models.User, error) {
|
||||
}
|
||||
var user models.User
|
||||
has, err := db.Instance.Where("account = ? and disabled = 0", account).Get(&user)
|
||||
return authenticateLoadedUser(&user, has, err, plain)
|
||||
}
|
||||
|
||||
func authenticateUserByID(userID int, plain string) (*models.User, error) {
|
||||
if userID <= 0 {
|
||||
if plain != "" {
|
||||
password.VerifyDummy(plain)
|
||||
}
|
||||
return nil, errors.New("invalid credentials")
|
||||
}
|
||||
if plain == "" || len([]byte(plain)) > 256 {
|
||||
return nil, errors.New("invalid credentials")
|
||||
}
|
||||
var user models.User
|
||||
has, err := db.Instance.ID(userID).Where("disabled = 0").Get(&user)
|
||||
return authenticateLoadedUser(&user, has, err, plain)
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -107,7 +78,7 @@ func Authenticate(account, plain string) (*models.User, error) {
|
||||
if !password.Verify(user.Password, plain) {
|
||||
return nil, errors.New("invalid credentials")
|
||||
}
|
||||
return &user, nil
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// HashPassword 统一生成新密码哈希。
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
"git.pcux.cn/xuans/Smail/db"
|
||||
@@ -34,7 +35,6 @@ func TestAuthenticateUsesArgon2idOnly(t *testing.T) {
|
||||
if _, err := db.Instance.Insert(&user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var loaded models.User
|
||||
if _, err := db.Instance.Where("account = ?", "test-user").Get(&loaded); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -134,6 +134,15 @@ func TestProtocolAuthenticationAcceptsConfiguredFullEmailIdentifier(t *testing.T
|
||||
if _, err := db.Instance.Insert(&user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
verifiedAt := time.Now().UTC()
|
||||
if _, err := db.Instance.Insert(&models.UserEmail{
|
||||
UserID: user.ID,
|
||||
Address: "alice@example.com",
|
||||
AddressCanonical: "alice@example.com",
|
||||
VerifiedAt: &verifiedAt,
|
||||
}); 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")
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/mail"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
"git.pcux.cn/xuans/Smail/db"
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
"git.pcux.cn/xuans/Smail/utils/validation"
|
||||
)
|
||||
|
||||
const maxLoginIdentifierBytes = 254
|
||||
|
||||
type IdentifierKind string
|
||||
|
||||
const (
|
||||
IdentifierAccount IdentifierKind = "account"
|
||||
IdentifierEmail IdentifierKind = "email"
|
||||
)
|
||||
|
||||
type ResolvedIdentity struct {
|
||||
UserID int
|
||||
Account string
|
||||
LoginAddress string
|
||||
Kind IdentifierKind
|
||||
}
|
||||
|
||||
// NormalizeIdentifier 保留旧调用方的账号规范化行为。
|
||||
// 完整邮箱的认证解析由 ResolveIdentifier 负责,避免在这里截断域名。
|
||||
func NormalizeIdentifier(identifier string) (string, error) {
|
||||
normalized, kind, err := parseLoginIdentifier(identifier)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if kind == IdentifierAccount {
|
||||
return validation.NormalizeAccount(normalized)
|
||||
}
|
||||
parts := strings.SplitN(normalized, "@", 2)
|
||||
if len(parts) != 2 || !isConfiguredLoginDomain(parts[1]) {
|
||||
return "", errors.New("invalid identifier")
|
||||
}
|
||||
return validation.NormalizeAccount(parts[0])
|
||||
}
|
||||
|
||||
// NormalizeIdentifierKey 返回限流和审计使用的稳定标识,不泄露原始输入格式。
|
||||
func NormalizeIdentifierKey(identifier string) (string, error) {
|
||||
normalized, _, err := parseLoginIdentifier(identifier)
|
||||
return normalized, err
|
||||
}
|
||||
|
||||
// ResolveIdentifier 将账号或已验证邮箱绑定解析为唯一用户身份。
|
||||
func ResolveIdentifier(identifier string) (ResolvedIdentity, error) {
|
||||
normalized, kind, err := parseLoginIdentifier(identifier)
|
||||
if err != nil {
|
||||
return ResolvedIdentity{}, err
|
||||
}
|
||||
if kind == IdentifierAccount {
|
||||
return ResolvedIdentity{Account: normalized, Kind: IdentifierAccount}, nil
|
||||
}
|
||||
if db.Instance == nil {
|
||||
return ResolvedIdentity{}, errors.New("database is unavailable")
|
||||
}
|
||||
|
||||
var bindings []models.UserEmail
|
||||
if err := db.Instance.Table(&models.UserEmail{}).
|
||||
Where("address_canonical = ? AND verified_at IS NOT NULL AND status != ?", normalized, 3).
|
||||
Limit(2).
|
||||
Find(&bindings); err != nil {
|
||||
return ResolvedIdentity{}, fmt.Errorf("load login email binding: %w", err)
|
||||
}
|
||||
if len(bindings) != 1 || bindings[0].UserID <= 0 {
|
||||
return ResolvedIdentity{}, errors.New("invalid identifier")
|
||||
}
|
||||
|
||||
var user models.User
|
||||
has, err := db.Instance.ID(bindings[0].UserID).Get(&user)
|
||||
if err != nil {
|
||||
return ResolvedIdentity{}, fmt.Errorf("load login user: %w", err)
|
||||
}
|
||||
if !has || user.ID <= 0 || user.Account == "" {
|
||||
return ResolvedIdentity{}, errors.New("invalid identifier")
|
||||
}
|
||||
return ResolvedIdentity{
|
||||
UserID: user.ID,
|
||||
Account: user.Account,
|
||||
LoginAddress: normalized,
|
||||
Kind: IdentifierEmail,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func parseLoginIdentifier(identifier string) (string, IdentifierKind, error) {
|
||||
identifier = strings.TrimSpace(identifier)
|
||||
if identifier == "" || len([]byte(identifier)) > maxLoginIdentifierBytes || strings.ContainsAny(identifier, "\r\n") {
|
||||
return "", "", errors.New("invalid identifier")
|
||||
}
|
||||
if !strings.Contains(identifier, "@") {
|
||||
account, err := validation.NormalizeAccount(identifier)
|
||||
if err != nil {
|
||||
return "", "", errors.New("invalid identifier")
|
||||
}
|
||||
return account, IdentifierAccount, nil
|
||||
}
|
||||
if strings.Count(identifier, "@") != 1 {
|
||||
return "", "", errors.New("invalid identifier")
|
||||
}
|
||||
|
||||
normalized := strings.ToLower(identifier)
|
||||
parsed, err := mail.ParseAddress(normalized)
|
||||
if err != nil || parsed.Address != normalized {
|
||||
return "", "", errors.New("invalid identifier")
|
||||
}
|
||||
parts := strings.SplitN(normalized, "@", 2)
|
||||
if len(parts) != 2 || parts[0] == "" {
|
||||
return "", "", errors.New("invalid identifier")
|
||||
}
|
||||
if _, err := validation.NormalizeDomain(parts[1]); err != nil {
|
||||
return "", "", errors.New("invalid identifier")
|
||||
}
|
||||
for _, char := range parts[0] {
|
||||
if unicode.IsSpace(char) || unicode.IsControl(char) || strings.ContainsRune(`"(),:;<>[\\]`, char) {
|
||||
return "", "", errors.New("invalid identifier")
|
||||
}
|
||||
}
|
||||
return normalized, IdentifierEmail, nil
|
||||
}
|
||||
|
||||
func isConfiguredLoginDomain(domain string) bool {
|
||||
domain = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(domain)), ".")
|
||||
if manager := config.CurrentManager(); manager != nil {
|
||||
runtime := manager.Snapshot()
|
||||
if strings.TrimSuffix(strings.ToLower(strings.TrimSpace(runtime.Root.Domains.Primary)), ".") == domain {
|
||||
return true
|
||||
}
|
||||
for _, item := range runtime.Root.Domains.Accepted {
|
||||
if strings.TrimSuffix(strings.ToLower(strings.TrimSpace(item)), ".") == domain {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
current := config.CurrentConfig()
|
||||
if current == nil {
|
||||
return false
|
||||
}
|
||||
if strings.TrimSuffix(strings.ToLower(strings.TrimSpace(current.Domain)), ".") == domain {
|
||||
return true
|
||||
}
|
||||
for _, item := range current.Domains {
|
||||
if strings.TrimSuffix(strings.ToLower(strings.TrimSpace(item)), ".") == domain {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
"git.pcux.cn/xuans/Smail/db"
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
)
|
||||
|
||||
func TestResolveIdentifierUsesVerifiedFullEmailBinding(t *testing.T) {
|
||||
oldConfig := config.Instance
|
||||
oldDB := db.Instance
|
||||
config.Instance = &config.Config{
|
||||
DbType: config.DBTypeSQLite,
|
||||
DbDSN: filepath.Join(t.TempDir(), "identifier.db"),
|
||||
}
|
||||
if err := db.Init(""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if db.Instance != nil && db.Instance != oldDB {
|
||||
_ = db.Instance.Close()
|
||||
}
|
||||
db.Instance = oldDB
|
||||
config.Instance = oldConfig
|
||||
})
|
||||
|
||||
user := models.User{Account: "alice", Name: "Alice"}
|
||||
if err := SetPassword(&user, "CorrectP12"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Instance.Insert(&user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
verifiedAt := time.Now().UTC()
|
||||
if _, err := db.Instance.Insert(&models.UserEmail{
|
||||
UserID: user.ID,
|
||||
Address: "Alice@Example.com",
|
||||
AddressCanonical: "alice@example.com",
|
||||
VerifiedAt: &verifiedAt,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Instance.Insert(&models.UserEmail{
|
||||
UserID: user.ID,
|
||||
Address: "pending@example.com",
|
||||
AddressCanonical: "pending@example.com",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
identity, err := ResolveIdentifier(" Alice@EXAMPLE.COM ")
|
||||
if err != nil {
|
||||
t.Fatalf("resolve verified email: %v", err)
|
||||
}
|
||||
if identity.Kind != IdentifierEmail || identity.UserID != user.ID || identity.Account != user.Account || identity.LoginAddress != "alice@example.com" {
|
||||
t.Fatalf("resolved identity = %+v", identity)
|
||||
}
|
||||
if _, err := AuthenticateIdentifier("Alice@Example.com", "CorrectP12"); err != nil {
|
||||
t.Fatalf("authenticate verified email: %v", err)
|
||||
}
|
||||
if _, err := AuthenticateIdentifier("pending@example.com", "CorrectP12"); err == nil {
|
||||
t.Fatal("unverified email binding was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveIdentifierRejectsMalformedOrOversizedEmail(t *testing.T) {
|
||||
for _, identifier := range []string{
|
||||
"alice@@example.com",
|
||||
"Alice <alice@example.com>",
|
||||
"alice@example.com\r\nX-Header: value",
|
||||
strings.Repeat("a", maxLoginIdentifierBytes+1),
|
||||
"alice@-invalid.example",
|
||||
} {
|
||||
if _, err := NormalizeIdentifierKey(identifier); err == nil {
|
||||
t.Fatalf("identifier %q was accepted", identifier)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeIdentifierKeepsLegacyAccountCompatibility(t *testing.T) {
|
||||
if got, err := NormalizeIdentifier("alice"); err != nil || got != "alice" {
|
||||
t.Fatalf("normalized account = %q, err = %v", got, err)
|
||||
}
|
||||
if got, err := NormalizeIdentifierKey(" Alice@Example.com "); err != nil || got != "alice@example.com" {
|
||||
t.Fatalf("normalized email key = %q, err = %v", got, err)
|
||||
}
|
||||
}
|
||||
@@ -43,8 +43,8 @@ var (
|
||||
|
||||
func AuthenticateProtocol(protocol string, remoteAddress string, account string, plain string) (*models.User, error) {
|
||||
normalizedAccount := strings.ToLower(strings.TrimSpace(account))
|
||||
if resolvedAccount, err := NormalizeIdentifier(account); err == nil {
|
||||
normalizedAccount = resolvedAccount
|
||||
if normalizedIdentifier, err := NormalizeIdentifierKey(account); err == nil {
|
||||
normalizedAccount = normalizedIdentifier
|
||||
}
|
||||
normalizedRemote := protocolRemoteHost(remoteAddress)
|
||||
pairKey := hashedProtocolLoginKey("pair", protocol, normalizedRemote, normalizedAccount)
|
||||
|
||||
Reference in new issue
Block a user