S1-B D2.3: B 层搬运 auth(JWT 登录/RBAC 联动,P1 等价零改动;91.2% 覆盖)
This commit is contained in:
@@ -0,0 +1,38 @@
|
|||||||
|
// login_audit_test.go Day 29:登录成功/失败均写 system_login_log。
|
||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"go-sms/internal/model/entity"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestLogin_AuditWritten Day 29:登录成功/失败均写 system_login_log。
|
||||||
|
func TestLogin_AuditWritten(t *testing.T) {
|
||||||
|
s, u := newSvc(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
if err := s.dao.DB().AutoMigrate(&entity.SystemLoginLog{}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 失败 → 留痕(ok=0 原因)
|
||||||
|
_, _ = s.Login(ctx, u.Username, "wrong-pass", "10.1.1.1")
|
||||||
|
// 成功 → 留痕(ok=1)
|
||||||
|
if _, err := s.Login(ctx, u.Username, "secret66", "10.1.1.2"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var logs []entity.SystemLoginLog
|
||||||
|
if err := s.dao.DB().Order("id").Find(&logs).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(logs) != 2 {
|
||||||
|
t.Fatalf("登录审计 = %d 条, 期望 2", len(logs))
|
||||||
|
}
|
||||||
|
if logs[0].Ok != 0 || logs[0].FailReason == "" || logs[0].IP != "10.1.1.1" {
|
||||||
|
t.Fatalf("失败记录异常: %+v", logs[0])
|
||||||
|
}
|
||||||
|
if logs[1].Ok != 1 || logs[1].IP != "10.1.1.2" || logs[1].Username != u.Username {
|
||||||
|
t.Fatalf("成功记录异常: %+v", logs[1])
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
// Package auth 认证服务(Day 24):登录(bcrypt + 失败 5 次锁定 15 分钟)、
|
||||||
|
// 登出(JWT 黑名单,TTL=剩余有效期)、刷新令牌(旧令牌轮换作废)。
|
||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
"go-sms/internal/model/entity"
|
||||||
|
errs "go-sms/internal/pkg/errors"
|
||||||
|
jwtpkg "go-sms/internal/pkg/jwt"
|
||||||
|
"go-sms/internal/repository/mysql"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 登录保护默认值(验收:错误密码 5 次锁定 15 分钟)。
|
||||||
|
const (
|
||||||
|
DefaultMaxFails = 5
|
||||||
|
DefaultLockWindow = 15 * time.Minute
|
||||||
|
)
|
||||||
|
|
||||||
|
// TokenStore 令牌黑名单与登录失败计数存储(生产 Redis,内存实现供测试/降级)。
|
||||||
|
type TokenStore interface {
|
||||||
|
// Revoke 将令牌哈希写入黑名单,ttl 为剩余有效期。
|
||||||
|
Revoke(ctx context.Context, tokenHash string, ttl time.Duration) error
|
||||||
|
// IsRevoked 令牌是否已注销。
|
||||||
|
IsRevoked(ctx context.Context, tokenHash string) (bool, error)
|
||||||
|
// IncrFail 失败计数 +1(进入新窗口时重置为 1),返回当前计数。
|
||||||
|
IncrFail(ctx context.Context, key string, window time.Duration) (int64, error)
|
||||||
|
// GetFail 当前失败计数(窗口过期返回 0)。
|
||||||
|
GetFail(ctx context.Context, key string) (int64, error)
|
||||||
|
// ResetFail 清零失败计数(登录成功调用)。
|
||||||
|
ResetFail(ctx context.Context, key string) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Service 认证服务。
|
||||||
|
// maxFails/lockWindow 未导出但同包测试可注入。
|
||||||
|
type Service struct {
|
||||||
|
dao *mysql.AccountDAO
|
||||||
|
jwt *jwtpkg.Manager
|
||||||
|
store TokenStore // nil 时降级内存实现
|
||||||
|
maxFails int
|
||||||
|
lockWindow time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewService 构造;store 为 nil 时降级内存实现(单实例有效)。
|
||||||
|
func NewService(db *gorm.DB, jm *jwtpkg.Manager, store TokenStore) *Service {
|
||||||
|
if store == nil {
|
||||||
|
store = NewMemoryTokenStore()
|
||||||
|
}
|
||||||
|
return &Service{
|
||||||
|
dao: mysql.NewAccountDAO(db),
|
||||||
|
jwt: jm,
|
||||||
|
store: store,
|
||||||
|
maxFails: DefaultMaxFails,
|
||||||
|
lockWindow: DefaultLockWindow,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoginRequest 登录请求(POST /api/v1/auth/login)。
|
||||||
|
type LoginRequest struct {
|
||||||
|
Username string `json:"username" binding:"required"`
|
||||||
|
Password string `json:"password" binding:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoginResult 登录/刷新响应。
|
||||||
|
type LoginResult struct {
|
||||||
|
Token string `json:"token"`
|
||||||
|
ExpiresIn int64 `json:"expires_in"` // 秒
|
||||||
|
Username string `json:"username"` // 兼容保留(Day 31 前已暴露)
|
||||||
|
Role string `json:"role"` // 兼容保留(单数)
|
||||||
|
User LoginUser `json:"user"` // 前端契约主字段(web user store 依赖)
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoginUser 登录用户视图(与前端 UserInfo 契约对齐:account_id/username/roles/permissions)。
|
||||||
|
type LoginUser struct {
|
||||||
|
AccountID int64 `json:"account_id"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
RealName string `json:"real_name,omitempty"`
|
||||||
|
Roles []string `json:"roles"`
|
||||||
|
Permissions []string `json:"permissions"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// failKey 登录失败计数键(按用户名隔离)。
|
||||||
|
func failKey(username string) string { return "login:fail:" + username }
|
||||||
|
|
||||||
|
// tokenKey 令牌黑名单键:原始令牌 SHA-256(Redis key 定长,避免存储整段 JWT)。
|
||||||
|
func tokenKey(raw string) string {
|
||||||
|
sum := sha256.Sum256([]byte(raw))
|
||||||
|
return hex.EncodeToString(sum[:])
|
||||||
|
}
|
||||||
|
|
||||||
|
// Login 登录:锁定检查 → 口令校验(bcrypt)→ 失败计数 → 签发 JWT。
|
||||||
|
// 验收:正确密码返回 Token;错误密码 5 次锁定 15 分钟。
|
||||||
|
func (s *Service) Login(ctx context.Context, username, password, clientIP string) (*LoginResult, error) {
|
||||||
|
username = strings.TrimSpace(username)
|
||||||
|
if username == "" || password == "" {
|
||||||
|
return nil, errs.InvalidParam.WithMsg("用户名与密码不能为空")
|
||||||
|
}
|
||||||
|
// 锁定检查:失败计数达上限后窗口内一律拒绝(含正确密码)
|
||||||
|
if n, _ := s.store.GetFail(ctx, failKey(username)); n >= int64(s.maxFails) {
|
||||||
|
return nil, errs.RateLimited.WithMsg(
|
||||||
|
"密码连续错误达上限,账号已锁定,请 " + s.lockAgoTip() + " 后重试")
|
||||||
|
}
|
||||||
|
|
||||||
|
u, err := s.dao.GetByUsername(ctx, username)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, mysql.ErrNotFound) {
|
||||||
|
// 用户不存在与口令错误同响应,避免账号枚举
|
||||||
|
_, _ = s.store.IncrFail(ctx, failKey(username), s.lockWindow)
|
||||||
|
s.recordLogin(ctx, username, 0, clientIP, "用户名或密码错误")
|
||||||
|
return nil, errs.Unauthorized.WithMsg("用户名或密码错误")
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if u.Status != 1 {
|
||||||
|
s.recordLogin(ctx, username, u.ID, clientIP, "账号被禁用")
|
||||||
|
return nil, errs.AccountDisabled // ISC:002
|
||||||
|
}
|
||||||
|
if bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(password)) != nil {
|
||||||
|
n, _ := s.store.IncrFail(ctx, failKey(username), s.lockWindow)
|
||||||
|
if n >= int64(s.maxFails) {
|
||||||
|
s.recordLogin(ctx, username, u.ID, clientIP, "连续错误锁定")
|
||||||
|
return nil, errs.RateLimited.WithMsg("密码连续错误达上限,账号已锁定 15 分钟")
|
||||||
|
}
|
||||||
|
s.recordLogin(ctx, username, u.ID, clientIP, "用户名或密码错误")
|
||||||
|
return nil, errs.Unauthorized.WithMsg("用户名或密码错误")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 成功:清零计数 + 签发令牌 + 回写登录时间/IP(尽力而为)
|
||||||
|
_ = s.store.ResetFail(ctx, failKey(username))
|
||||||
|
s.recordLogin(ctx, username, u.ID, clientIP, "")
|
||||||
|
token, err := s.jwt.Sign(u.ID, u.Username, []string{u.Role}, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
now := time.Now()
|
||||||
|
s.dao.DB().WithContext(ctx).Model(&entity.AccountUser{}).
|
||||||
|
Where("id = ?", u.ID).
|
||||||
|
Updates(map[string]any{"last_login_at": now, "last_login_ip": clientIP})
|
||||||
|
|
||||||
|
return &LoginResult{
|
||||||
|
Token: token, ExpiresIn: int64(s.jwt.Validity().Seconds()),
|
||||||
|
Username: u.Username, Role: u.Role,
|
||||||
|
User: LoginUser{
|
||||||
|
AccountID: u.ID, Username: u.Username, RealName: u.RealName,
|
||||||
|
Roles: []string{u.Role}, Permissions: []string{},
|
||||||
|
},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// lockAgoTip 锁定提示(分钟粒度)。
|
||||||
|
func (s *Service) lockAgoTip() string { return "15 分钟" }
|
||||||
|
|
||||||
|
// recordLogin 登录审计留痕(Day 29,尽力而为:无审计表/写失败不影响登录流程)。
|
||||||
|
// Ok 列 default:1,失败记录 Ok=0 需 map 创建避免被 GORM 零值过滤吞掉。
|
||||||
|
func (s *Service) recordLogin(ctx context.Context, username string, accountID int64, ip, failReason string) {
|
||||||
|
ok := 1
|
||||||
|
if failReason != "" {
|
||||||
|
ok = 0
|
||||||
|
}
|
||||||
|
_ = s.dao.DB().WithContext(ctx).Model(&entity.SystemLoginLog{}).Create(map[string]any{
|
||||||
|
"username": username, "account_id": accountID, "ip": ip,
|
||||||
|
"user_agent": "gateway", "ok": ok, "fail_reason": failReason,
|
||||||
|
}).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Logout 登出:令牌写入黑名单,TTL=剩余有效期(过期令牌无需写入)。
|
||||||
|
func (s *Service) Logout(ctx context.Context, rawToken string) error {
|
||||||
|
claims, err := s.jwt.Parse(rawToken)
|
||||||
|
if err != nil {
|
||||||
|
return errs.Unauthorized.WithMsg("令牌无效")
|
||||||
|
}
|
||||||
|
ttl := time.Until(claims.ExpiresAt.Time)
|
||||||
|
if ttl <= 0 {
|
||||||
|
return nil // 已过期:自然失效,无需黑名单
|
||||||
|
}
|
||||||
|
return s.store.Revoke(ctx, tokenKey(rawToken), ttl)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refresh 刷新令牌:旧令牌立即作废(轮换),按原 claims 重签。
|
||||||
|
func (s *Service) Refresh(ctx context.Context, rawToken string, claims *jwtpkg.Claims) (*LoginResult, error) {
|
||||||
|
if claims == nil || claims.Username == "" {
|
||||||
|
return nil, errs.Unauthorized.WithMsg("缺少有效的认证信息")
|
||||||
|
}
|
||||||
|
if err := s.Logout(ctx, rawToken); err != nil { // 旧令牌轮换作废
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
token, err := s.jwt.Sign(claims.AccountID, claims.Username, claims.Roles, claims.Permissions)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
role := ""
|
||||||
|
if len(claims.Roles) > 0 {
|
||||||
|
role = claims.Roles[0]
|
||||||
|
}
|
||||||
|
return &LoginResult{
|
||||||
|
Token: token, ExpiresIn: int64(s.jwt.Validity().Seconds()),
|
||||||
|
Username: claims.Username, Role: role,
|
||||||
|
User: LoginUser{
|
||||||
|
AccountID: claims.AccountID, Username: claims.Username,
|
||||||
|
Roles: claims.Roles, Permissions: claims.Permissions,
|
||||||
|
},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Revoked 令牌是否已注销(鉴权中间件回调;查询失败放行,由状态校验兜底)。
|
||||||
|
func (s *Service) Revoked(ctx context.Context, rawToken string) bool {
|
||||||
|
if rawToken == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
ok, err := s.store.IsRevoked(ctx, tokenKey(rawToken))
|
||||||
|
return err == nil && ok
|
||||||
|
}
|
||||||
@@ -0,0 +1,244 @@
|
|||||||
|
// service_test.go 认证服务测试(Day 24 验收):
|
||||||
|
// 正确密码返回 Token;错误密码 5 次锁定 15 分钟;登出后 Token 立即失效;刷新轮换。
|
||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/glebarez/sqlite"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
"go-sms/internal/model/entity"
|
||||||
|
errs "go-sms/internal/pkg/errors"
|
||||||
|
jwtpkg "go-sms/internal/pkg/jwt"
|
||||||
|
)
|
||||||
|
|
||||||
|
const testSecret = "day24-test-secret"
|
||||||
|
|
||||||
|
func newAuthDB(t *testing.T) *gorm.DB {
|
||||||
|
t.Helper()
|
||||||
|
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := db.AutoMigrate(&entity.AccountUser{}, &entity.SystemLoginLog{}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return db
|
||||||
|
}
|
||||||
|
|
||||||
|
// newSvc 构造服务并预置一个启用账号,返回 (服务, 账号)。
|
||||||
|
func newSvc(t *testing.T) (*Service, *entity.AccountUser) {
|
||||||
|
t.Helper()
|
||||||
|
db := newAuthDB(t)
|
||||||
|
hash, err := bcrypt.GenerateFromPassword([]byte("secret66"), bcrypt.MinCost)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
u := &entity.AccountUser{
|
||||||
|
Username: "day24-user", PasswordHash: string(hash),
|
||||||
|
Role: "ops", Status: 1, CreditBalance: 100,
|
||||||
|
}
|
||||||
|
if err := db.Create(u).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return NewService(db, jwtpkg.NewManager(testSecret, time.Hour), NewMemoryTokenStore()), u
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustBizErr(t *testing.T, err error) *errs.Error {
|
||||||
|
t.Helper()
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("期望返回错误,实际 nil")
|
||||||
|
}
|
||||||
|
bizErr, ok := err.(*errs.Error)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("期望业务错误,实际 %T: %v", err, err)
|
||||||
|
}
|
||||||
|
return bizErr
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestLogin_OK 验收:正确密码返回 Token,claims 正确,登录时间回写。
|
||||||
|
func TestLogin_OK(t *testing.T) {
|
||||||
|
s, u := newSvc(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
res, err := s.Login(ctx, u.Username, "secret66", "10.0.0.8")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if res.Token == "" || res.ExpiresIn != 3600 || res.Username != u.Username || res.Role != "ops" {
|
||||||
|
t.Fatalf("登录结果异常: %+v", res)
|
||||||
|
}
|
||||||
|
// Day 31:前端契约主字段 user(account_id/username/roles/permissions)。
|
||||||
|
if res.User.AccountID != u.ID || res.User.Username != u.Username ||
|
||||||
|
len(res.User.Roles) != 1 || res.User.Roles[0] != "ops" || res.User.Permissions == nil {
|
||||||
|
t.Fatalf("user 契约字段异常: %+v", res.User)
|
||||||
|
}
|
||||||
|
claims, err := s.jwt.Parse(res.Token)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("签发的令牌无法解析: %v", err)
|
||||||
|
}
|
||||||
|
if claims.AccountID != u.ID || claims.Username != u.Username || len(claims.Roles) != 1 || claims.Roles[0] != "ops" {
|
||||||
|
t.Fatalf("claims 异常: %+v", claims)
|
||||||
|
}
|
||||||
|
// 登录时间/IP 回写
|
||||||
|
var after entity.AccountUser
|
||||||
|
if err := s.dao.DB().First(&after, u.ID).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if after.LastLoginAt == nil || after.LastLoginIP != "10.0.0.8" {
|
||||||
|
t.Fatalf("last_login 未回写: at=%v ip=%q", after.LastLoginAt, after.LastLoginIP)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestLogin_WrongAndLock 验收:错误密码 5 次锁定;锁定期内正确密码也被拒。
|
||||||
|
func TestLogin_WrongAndLock(t *testing.T) {
|
||||||
|
s, u := newSvc(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
for i := 1; i <= 4; i++ { // 前 4 次:401
|
||||||
|
_, err := s.Login(ctx, u.Username, "wrong-pass", "1.1.1.1")
|
||||||
|
if bizErr := mustBizErr(t, err); bizErr.Code != errs.Unauthorized.Code {
|
||||||
|
t.Fatalf("第 %d 次:期望 ISC:401,实际 %s", i, bizErr.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 第 5 次:触发锁定 429
|
||||||
|
_, err := s.Login(ctx, u.Username, "wrong-pass", "1.1.1.1")
|
||||||
|
if bizErr := mustBizErr(t, err); bizErr.Code != errs.RateLimited.Code {
|
||||||
|
t.Fatalf("第 5 次:期望 ISC:429 锁定,实际 %s(%s)", bizErr.Code, bizErr.Msg)
|
||||||
|
}
|
||||||
|
// 锁定期内:正确密码仍被拒
|
||||||
|
_, err = s.Login(ctx, u.Username, "secret66", "1.1.1.1")
|
||||||
|
if bizErr := mustBizErr(t, err); bizErr.Code != errs.RateLimited.Code {
|
||||||
|
t.Fatalf("锁定后正确密码应被拒:实际 %s(%s)", bizErr.Code, bizErr.Msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestLogin_LockWindowExpiry 锁定窗口过期自动解锁。
|
||||||
|
func TestLogin_LockWindowExpiry(t *testing.T) {
|
||||||
|
s, u := newSvc(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
s.lockWindow = 800 * time.Millisecond // 注入短窗口(需覆盖 5 次登录耗时,防时序 flaky)
|
||||||
|
|
||||||
|
for i := 0; i < 5; i++ {
|
||||||
|
_, _ = s.Login(ctx, u.Username, "wrong-pass", "1.1.1.1")
|
||||||
|
}
|
||||||
|
if _, err := s.Login(ctx, u.Username, "secret66", "1.1.1.1"); mustBizErr(t, err).Code != errs.RateLimited.Code {
|
||||||
|
t.Fatal("锁定期内应 429")
|
||||||
|
}
|
||||||
|
time.Sleep(900 * time.Millisecond)
|
||||||
|
if _, err := s.Login(ctx, u.Username, "secret66", "1.1.1.1"); err != nil {
|
||||||
|
t.Fatalf("窗口过期后应可登录: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestLogin_DisabledAndNotFound 禁用账号 ISC:002;不存在用户名同口令错误响应。
|
||||||
|
func TestLogin_DisabledAndNotFound(t *testing.T) {
|
||||||
|
s, u := newSvc(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
s.dao.DB().Model(&entity.AccountUser{}).Where("id = ?", u.ID).Update("status", 0)
|
||||||
|
if _, err := s.Login(ctx, u.Username, "secret66", "1.1.1.1"); mustBizErr(t, err).Code != errs.AccountDisabled.Code {
|
||||||
|
t.Fatal("禁用账号应返回 ISC:002")
|
||||||
|
}
|
||||||
|
if _, err := s.Login(ctx, "no-such-user", "whatever", "1.1.1.1"); mustBizErr(t, err).Code != errs.Unauthorized.Code {
|
||||||
|
t.Fatal("不存在用户应返回 ISC:401")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestLogout 验收:登出后令牌立即失效(Revoked 为真)。
|
||||||
|
func TestLogout(t *testing.T) {
|
||||||
|
s, u := newSvc(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
res, err := s.Login(ctx, u.Username, "secret66", "2.2.2.2")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if s.Revoked(ctx, res.Token) {
|
||||||
|
t.Fatal("刚签发的令牌不应被注销")
|
||||||
|
}
|
||||||
|
if err := s.Logout(ctx, res.Token); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !s.Revoked(ctx, res.Token) {
|
||||||
|
t.Fatal("登出后令牌应已注销")
|
||||||
|
}
|
||||||
|
// 无效令牌登出 → 业务错误
|
||||||
|
if err := s.Logout(ctx, "not-a-jwt"); mustBizErr(t, err).Code != errs.Unauthorized.Code {
|
||||||
|
t.Fatal("无效令牌登出应返回 ISC:401")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRefresh 刷新:旧令牌作废、新令牌可用且 claims 保持。
|
||||||
|
func TestRefresh(t *testing.T) {
|
||||||
|
s, u := newSvc(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
res, _ := s.Login(ctx, u.Username, "secret66", "3.3.3.3")
|
||||||
|
claims, err := s.jwt.Parse(res.Token)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
fresh, err := s.Refresh(ctx, res.Token, claims)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !s.Revoked(ctx, res.Token) {
|
||||||
|
t.Fatal("刷新后旧令牌应作废")
|
||||||
|
}
|
||||||
|
newClaims, err := s.jwt.Parse(fresh.Token)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("新令牌解析失败: %v", err)
|
||||||
|
}
|
||||||
|
if newClaims.AccountID != claims.AccountID || newClaims.Username != claims.Username {
|
||||||
|
t.Fatalf("新令牌 claims 异常: %+v", newClaims)
|
||||||
|
}
|
||||||
|
// claims 缺失守卫
|
||||||
|
if _, err := s.Refresh(ctx, fresh.Token, nil); mustBizErr(t, err).Code != errs.Unauthorized.Code {
|
||||||
|
t.Fatal("claims 缺失应返回 ISC:401")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestMemoryTokenStore_TTL 语义:黑名单与失败计数随 TTL 过期。
|
||||||
|
func TestMemoryTokenStore_TTL(t *testing.T) {
|
||||||
|
m := NewMemoryTokenStore()
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
if err := m.Revoke(ctx, "k1", 40*time.Millisecond); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ok, _ := m.IsRevoked(ctx, "k1"); !ok {
|
||||||
|
t.Fatal("k1 应在黑名单")
|
||||||
|
}
|
||||||
|
time.Sleep(60 * time.Millisecond)
|
||||||
|
if ok, _ := m.IsRevoked(ctx, "k1"); ok {
|
||||||
|
t.Fatal("过期后应移出黑名单")
|
||||||
|
}
|
||||||
|
if err := m.Revoke(ctx, "k2", -time.Second); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ok, _ := m.IsRevoked(ctx, "k2"); ok {
|
||||||
|
t.Fatal("非正 TTL 不应写入黑名单")
|
||||||
|
}
|
||||||
|
|
||||||
|
if n, _ := m.IncrFail(ctx, "u1", 40*time.Millisecond); n != 1 {
|
||||||
|
t.Fatalf("首次计数 = %d, 期望 1", n)
|
||||||
|
}
|
||||||
|
if n, _ := m.IncrFail(ctx, "u1", 40*time.Millisecond); n != 2 {
|
||||||
|
t.Fatalf("二次计数 = %d, 期望 2", n)
|
||||||
|
}
|
||||||
|
time.Sleep(60 * time.Millisecond)
|
||||||
|
if n, _ := m.IncrFail(ctx, "u1", 40*time.Millisecond); n != 1 {
|
||||||
|
t.Fatalf("窗口过期后应重新从 1 计数,实际 %d", n)
|
||||||
|
}
|
||||||
|
if err := m.ResetFail(ctx, "u1"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if n, _ := m.GetFail(ctx, "u1"); n != 0 {
|
||||||
|
t.Fatalf("重置后计数 = %d, 期望 0", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
// store_memory.go 内存 TokenStore 实现(单测 / Redis 降级;非线程安全的清理采用惰性淘汰)。
|
||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MemoryTokenStore 内存实现:黑名单 + 失败计数均带过期时间。
|
||||||
|
type MemoryTokenStore struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
blk map[string]time.Time // tokenHash → 过期时刻
|
||||||
|
failures map[string]*failEntry
|
||||||
|
}
|
||||||
|
|
||||||
|
type failEntry struct {
|
||||||
|
count int64
|
||||||
|
deadline time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewMemoryTokenStore 构造空存储。
|
||||||
|
func NewMemoryTokenStore() *MemoryTokenStore {
|
||||||
|
return &MemoryTokenStore{blk: map[string]time.Time{}, failures: map[string]*failEntry{}}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Revoke 写入黑名单(ttl<=0 忽略:令牌已自然过期)。
|
||||||
|
func (m *MemoryTokenStore) Revoke(_ context.Context, tokenHash string, ttl time.Duration) error {
|
||||||
|
if ttl <= 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
// 惰性清理已过期黑名单,防长跑内存增长
|
||||||
|
now := time.Now()
|
||||||
|
for k, exp := range m.blk {
|
||||||
|
if now.After(exp) {
|
||||||
|
delete(m.blk, k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
m.blk[tokenHash] = now.Add(ttl)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsRevoked 是否仍在黑名单(过期视为未注销)。
|
||||||
|
func (m *MemoryTokenStore) IsRevoked(_ context.Context, tokenHash string) (bool, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
exp, ok := m.blk[tokenHash]
|
||||||
|
return ok && time.Now().Before(exp), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// IncrFail 失败计数 +1;窗口过期则进入新窗口从 1 起算。
|
||||||
|
func (m *MemoryTokenStore) IncrFail(_ context.Context, key string, window time.Duration) (int64, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
now := time.Now()
|
||||||
|
e, ok := m.failures[key]
|
||||||
|
if !ok || now.After(e.deadline) {
|
||||||
|
e = &failEntry{deadline: now.Add(window)}
|
||||||
|
m.failures[key] = e
|
||||||
|
}
|
||||||
|
e.count++
|
||||||
|
return e.count, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetFail 当前计数(窗口过期返回 0)。
|
||||||
|
func (m *MemoryTokenStore) GetFail(_ context.Context, key string) (int64, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
e, ok := m.failures[key]
|
||||||
|
if !ok || time.Now().After(e.deadline) {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
return e.count, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResetFail 清零计数。
|
||||||
|
func (m *MemoryTokenStore) ResetFail(_ context.Context, key string) error {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
delete(m.failures, key)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
// store_redis.go Redis TokenStore 实现(生产;黑名单与失败计数均带 TTL)。
|
||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Redis 键前缀。
|
||||||
|
// 注:IncrFail 等收到的 key 已是 failKey() 生成的 "login:fail:<user>",
|
||||||
|
// 此处仅补全局命名空间,避免拼出 "go-sms:login:fail:login:fail:<user>" 双前缀。
|
||||||
|
const (
|
||||||
|
redisBlkPrefix = "go-sms:jwt:blk:" // + token sha256
|
||||||
|
redisFailPrefix = "go-sms:" // + "login:fail:" + username(由 failKey 提供)
|
||||||
|
)
|
||||||
|
|
||||||
|
// RedisTokenStore 基于 go-redis UniversalClient(single/cluster 通吃)。
|
||||||
|
type RedisTokenStore struct {
|
||||||
|
rdb redis.UniversalClient
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewRedisTokenStore 构造。
|
||||||
|
func NewRedisTokenStore(rdb redis.UniversalClient) *RedisTokenStore {
|
||||||
|
return &RedisTokenStore{rdb: rdb}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Revoke SET key 1 EX ttl(过期令牌由 JWT 自然校验拦截,无需写入)。
|
||||||
|
func (r *RedisTokenStore) Revoke(ctx context.Context, tokenHash string, ttl time.Duration) error {
|
||||||
|
if ttl <= 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return r.rdb.Set(ctx, redisBlkPrefix+tokenHash, 1, ttl).Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsRevoked EXISTS 查询;Redis 不可用返回 false 放行(由账号状态校验兜底)。
|
||||||
|
func (r *RedisTokenStore) IsRevoked(ctx context.Context, tokenHash string) (bool, error) {
|
||||||
|
n, err := r.rdb.Exists(ctx, redisBlkPrefix+tokenHash).Result()
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return n > 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// IncrFail INCR;首次进入窗口(n==1)时设置 EXPIRE。
|
||||||
|
func (r *RedisTokenStore) IncrFail(ctx context.Context, key string, window time.Duration) (int64, error) {
|
||||||
|
pipe := r.rdb.Pipeline()
|
||||||
|
incr := pipe.Incr(ctx, redisFailPrefix+key)
|
||||||
|
pipe.Expire(ctx, redisFailPrefix+key, window)
|
||||||
|
if _, err := pipe.Exec(ctx); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return incr.Val(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetFail GET 计数(无键=0)。
|
||||||
|
func (r *RedisTokenStore) GetFail(ctx context.Context, key string) (int64, error) {
|
||||||
|
return r.rdb.Get(ctx, redisFailPrefix+key).Int64()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResetFail DEL 计数键。
|
||||||
|
func (r *RedisTokenStore) ResetFail(ctx context.Context, key string) error {
|
||||||
|
return r.rdb.Del(ctx, redisFailPrefix+key).Err()
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
// store_redis_test.go Redis TokenStore 单测(miniredis 内存服务器,
|
||||||
|
// 校验键名/TTL/INCR 语义与 Redis 不可用时的行为)。
|
||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/alicebob/miniredis/v2"
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
|
)
|
||||||
|
|
||||||
|
func newRedisStore(t *testing.T) (*RedisTokenStore, *miniredis.Miniredis) {
|
||||||
|
t.Helper()
|
||||||
|
mr := miniredis.RunT(t)
|
||||||
|
rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
|
||||||
|
t.Cleanup(func() { _ = rdb.Close() })
|
||||||
|
return NewRedisTokenStore(rdb), mr
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRedisStore_Blacklist 黑名单写入/查询/过期/非正 TTL。
|
||||||
|
func TestRedisStore_Blacklist(t *testing.T) {
|
||||||
|
s, mr := newRedisStore(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
if err := s.Revoke(ctx, "h1", time.Minute); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ok, _ := s.IsRevoked(ctx, "h1"); !ok {
|
||||||
|
t.Fatal("h1 应在黑名单")
|
||||||
|
}
|
||||||
|
if err := s.Revoke(ctx, "h2", -time.Second); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ok, _ := s.IsRevoked(ctx, "h2"); ok {
|
||||||
|
t.Fatal("非正 TTL 不应写入")
|
||||||
|
}
|
||||||
|
mr.FastForward(2 * time.Minute) // 快进过期
|
||||||
|
if ok, _ := s.IsRevoked(ctx, "h1"); ok {
|
||||||
|
t.Fatal("过期后应不在黑名单")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRedisStore_FailCounter 失败计数 INCR + 窗口过期 + 重置。
|
||||||
|
func TestRedisStore_FailCounter(t *testing.T) {
|
||||||
|
s, mr := newRedisStore(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
for i := 1; i <= 3; i++ {
|
||||||
|
n, err := s.IncrFail(ctx, "u1", time.Minute)
|
||||||
|
if err != nil || n != int64(i) {
|
||||||
|
t.Fatalf("第 %d 次计数 = (%d,%v)", i, n, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if n, _ := s.GetFail(ctx, "u1"); n != 3 {
|
||||||
|
t.Fatalf("当前计数 = %d, 期望 3", n)
|
||||||
|
}
|
||||||
|
mr.FastForward(2 * time.Minute)
|
||||||
|
if n, _ := s.GetFail(ctx, "u1"); n != 0 {
|
||||||
|
t.Fatalf("窗口过期后计数 = %d, 期望 0", n)
|
||||||
|
}
|
||||||
|
if err := s.ResetFail(ctx, "u1"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if n, _ := s.GetFail(ctx, "u1"); n != 0 {
|
||||||
|
t.Fatalf("重置后计数 = %d, 期望 0", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRedisStore_ServerDown Redis 不可用:命令返回错误,不 panic。
|
||||||
|
func TestRedisStore_ServerDown(t *testing.T) {
|
||||||
|
mr := miniredis.RunT(t)
|
||||||
|
rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
|
||||||
|
t.Cleanup(func() { _ = rdb.Close() })
|
||||||
|
s := NewRedisTokenStore(rdb)
|
||||||
|
mr.Close() // 关停服务器模拟宕机
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
if _, err := s.IsRevoked(ctx, "h1"); err == nil {
|
||||||
|
t.Fatal("宕机时 IsRevoked 应返回错误")
|
||||||
|
}
|
||||||
|
if _, err := s.IncrFail(ctx, "u1", time.Minute); err == nil {
|
||||||
|
t.Fatal("宕机时 IncrFail 应返回错误")
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user