245 lines
7.6 KiB
Go
245 lines
7.6 KiB
Go
// 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)
|
|
}
|
|
}
|