// auth_test.go 认证端点全链路测试(Day 24 验收): // 登录 → 受保护接口 → 登出即失效 → 刷新轮换 → 锁定。 package v1 import ( "bytes" "encoding/json" "net/http" "net/http/httptest" "strconv" "testing" "time" "github.com/gin-gonic/gin" "github.com/glebarez/sqlite" "golang.org/x/crypto/bcrypt" "gorm.io/gorm" "go-sms/internal/middleware" "go-sms/internal/model/entity" jwtpkg "go-sms/internal/pkg/jwt" "go-sms/internal/service/account" "go-sms/internal/service/auth" ) const d24Secret = "d24-api-secret" // newAuthRouter 装配带认证中间件的完整 v1 路由。 func newD24Router(t *testing.T) (*gin.Engine, *gorm.DB) { t.Helper() gin.SetMode(gin.TestMode) db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) if err != nil { t.Fatal(err) } if err := db.AutoMigrate(&entity.AccountUser{}, &entity.AccountConfig{}, &entity.AccountBalanceLog{}); err != nil { t.Fatal(err) } acctSvc := account.NewService(db, account.BcryptMinCost) authSvc := auth.NewService(db, jwtpkg.NewManager(d24Secret, time.Hour), auth.NewMemoryTokenStore()) r := gin.New() Register(r.Group("/api/v1"), Deps{ Account: acctSvc, AuthSvc: authSvc, Auth: middleware.AuthJWTWithRevocation(d24Secret, authSvc.Revoked, acctSvc.CheckEnabled), }) // 种子账号 hash, _ := bcrypt.GenerateFromPassword([]byte("secret66"), bcrypt.MinCost) if err := db.Create(&entity.AccountUser{ Username: "d24-api", PasswordHash: string(hash), Role: "ops", Status: 1, }).Error; err != nil { t.Fatal(err) } return r, db } // doReq 通用请求:可选 Bearer 令牌与 JSON 体。 func doJSON(r *gin.Engine, method, path, token string, body any) *httptest.ResponseRecorder { raw, _ := json.Marshal(body) w := httptest.NewRecorder() req := httptest.NewRequest(method, path, bytes.NewReader(raw)) req.Header.Set("Content-Type", "application/json") if token != "" { req.Header.Set("Authorization", "Bearer "+token) } r.ServeHTTP(w, req) return w } // loginOK 登录成功并返回令牌。 func loginOK(t *testing.T, r *gin.Engine) string { t.Helper() w := doJSON(r, http.MethodPost, "/api/v1/auth/login", "", map[string]string{ "username": "d24-api", "password": "secret66", }) if w.Code != http.StatusOK { t.Fatalf("登录 = %d, body=%s", w.Code, w.Body.String()) } var resp struct { Data struct { Token string `json:"token"` } `json:"data"` } if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { t.Fatal(err) } if resp.Data.Token == "" { t.Fatalf("未返回 token: %s", w.Body.String()) } return resp.Data.Token } // TestAPI_AuthFlow 验收主线:登录可用 → 受保护接口放行 → 登出后同一令牌 401。 func TestAPI_AuthFlow(t *testing.T) { r, db := newD24Router(t) var u entity.AccountUser if err := db.Where("username = ?", "d24-api").First(&u).Error; err != nil { t.Fatal(err) } // 登录前:受保护接口 401 if w := doJSON(r, http.MethodGet, "/api/v1/accounts/1", "", nil); w.Code != http.StatusUnauthorized { t.Fatalf("未登录访问 = %d, 期望 401", w.Code) } token := loginOK(t, r) // 登录后:放行 if w := doJSON(r, http.MethodGet, "/api/v1/accounts/"+strconv.FormatInt(u.ID, 10), token, nil); w.Code != http.StatusOK { t.Fatalf("登录后访问 = %d, body=%s", w.Code, w.Body.String()) } // 登出 if w := doJSON(r, http.MethodPost, "/api/v1/auth/logout", token, nil); w.Code != http.StatusOK { t.Fatalf("登出 = %d, body=%s", w.Code, w.Body.String()) } // 登出后:同一令牌立即失效 if w := doJSON(r, http.MethodGet, "/api/v1/accounts/"+strconv.FormatInt(u.ID, 10), token, nil); w.Code != http.StatusUnauthorized { t.Fatalf("登出后访问 = %d, 期望 401(令牌已注销)", w.Code) } } // TestAPI_AuthRefresh 刷新:旧令牌作废,新令牌可用。 func TestAPI_AuthRefresh(t *testing.T) { r, _ := newD24Router(t) old := loginOK(t, r) w := doJSON(r, http.MethodPost, "/api/v1/auth/refresh", old, nil) if w.Code != http.StatusOK { t.Fatalf("刷新 = %d, body=%s", w.Code, w.Body.String()) } var resp struct { Data struct { Token string `json:"token"` } `json:"data"` } if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { t.Fatal(err) } if resp.Data.Token == "" || resp.Data.Token == old { t.Fatalf("新令牌异常: %s", w.Body.String()) } // 旧令牌 401,新令牌 200 if w := doJSON(r, http.MethodGet, "/api/v1/accounts", old, nil); w.Code != http.StatusUnauthorized { t.Fatalf("旧令牌 = %d, 期望 401", w.Code) } if w := doJSON(r, http.MethodGet, "/api/v1/accounts", resp.Data.Token, nil); w.Code != http.StatusOK { t.Fatalf("新令牌 = %d, 期望 200", w.Code) } } // TestAPI_AuthLogin_Locked 验收:错误密码 5 次后第 5 次即 429,正确密码也被拒。 func TestAPI_AuthLogin_Locked(t *testing.T) { r, _ := newD24Router(t) body := map[string]string{"username": "d24-api", "password": "wrong-pass"} for i := 1; i <= 4; i++ { if w := doJSON(r, http.MethodPost, "/api/v1/auth/login", "", body); w.Code != http.StatusUnauthorized { t.Fatalf("第 %d 次错误密码 = %d, 期望 401", i, w.Code) } } if w := doJSON(r, http.MethodPost, "/api/v1/auth/login", "", body); w.Code != http.StatusTooManyRequests { t.Fatalf("第 5 次 = %d, 期望 429 锁定, body=%s", w.Code, w.Body.String()) } w := doJSON(r, http.MethodPost, "/api/v1/auth/login", "", map[string]string{ "username": "d24-api", "password": "secret66", }) if w.Code != http.StatusTooManyRequests { t.Fatalf("锁定期内正确密码 = %d, 期望 429", w.Code) } } // TestAPI_AuthLogin_BadRequest 缺参 400。 func TestAPI_AuthLogin_BadRequest(t *testing.T) { r, _ := newD24Router(t) w := doJSON(r, http.MethodPost, "/api/v1/auth/login", "", map[string]string{"username": "x"}) if w.Code != http.StatusBadRequest { t.Fatalf("缺参 = %d, 期望 400", w.Code) } }