handler_test.go 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  1. // Handler 单测(T4-4 验收):/auth/* 端点端到端(mock 仓储 + 真 Issuer + miniredis,不连真实 DB/Redis)。
  2. //
  3. // 覆盖:
  4. // - 入参校验(validator)→ code 2001 / 2002
  5. // - 两步登录①② → code 200(含 loginTicket / accessToken)
  6. // - 防枚举统一文案 → code 1001(未知账号 / 密码错 / 禁用)
  7. // - 票据失效 / 重放 / 作用域越权 → code 1001 / 1003
  8. // - Me(受保护,读中间件写入的 claims)/ Logout(恒 200 幂等)/ Refresh
  9. // - 微信占位 → code 5001(暂未开放)
  10. //
  11. // 断言纪律(响应契约 = code-based,HTTP 恒 200):只断 body.code(铁律 6),
  12. // 不依赖 HTTP 状态码(恒 200)。
  13. package handler
  14. import (
  15. "context"
  16. "crypto/md5"
  17. "crypto/rand"
  18. "crypto/rsa"
  19. "crypto/x509"
  20. "encoding/hex"
  21. "encoding/json"
  22. "encoding/pem"
  23. "net/http"
  24. "net/http/httptest"
  25. "strings"
  26. "testing"
  27. "time"
  28. miniredis "github.com/alicebob/miniredis/v2"
  29. "github.com/gofiber/fiber/v2"
  30. "yuansiwei/unified-backend/internal/identity/credential"
  31. "yuansiwei/unified-backend/internal/identity/model"
  32. "yuansiwei/unified-backend/internal/identity/repository"
  33. "yuansiwei/unified-backend/internal/identity/service"
  34. "yuansiwei/unified-backend/internal/identity/token"
  35. "yuansiwei/unified-backend/internal/infra/config"
  36. apperrors "yuansiwei/unified-backend/internal/infra/errors"
  37. appredis "yuansiwei/unified-backend/internal/infra/redis"
  38. orgmodel "yuansiwei/unified-backend/internal/org/model"
  39. )
  40. // ---- 仓储 mock(实现 repository 接口,纯内存;与 service 单测同源逻辑)----
  41. type mockUsers struct{ byUID map[string]*model.User }
  42. func (m *mockUsers) GetByCanonicalUserID(_ context.Context, uid string) (*model.User, error) {
  43. u, ok := m.byUID[uid]
  44. if !ok {
  45. return nil, apperrors.ErrNotFound
  46. }
  47. return u, nil
  48. }
  49. func (m *mockUsers) UpdatePasswordLazyUpgrade(_ context.Context, uid, newHash string) error {
  50. u, ok := m.byUID[uid]
  51. if !ok {
  52. return apperrors.ErrNotFound
  53. }
  54. u.PasswordHash = &newHash
  55. u.PasswordSalt = nil
  56. hv := model.HashVersionArgon2
  57. u.HashVersion = &hv
  58. return nil
  59. }
  60. type mockIdentities struct{ byTypeIdent map[string]map[string]*model.Identity }
  61. func newMockIdentities() *mockIdentities {
  62. return &mockIdentities{byTypeIdent: map[string]map[string]*model.Identity{}}
  63. }
  64. func (m *mockIdentities) add(typ, identifier string, it *model.Identity) {
  65. if m.byTypeIdent[typ] == nil {
  66. m.byTypeIdent[typ] = map[string]*model.Identity{}
  67. }
  68. m.byTypeIdent[typ][identifier] = it
  69. }
  70. func (m *mockIdentities) GetByTypeIdentifier(_ context.Context, typ, identifier string) (*model.Identity, error) {
  71. it, ok := m.byTypeIdent[typ][identifier]
  72. if !ok {
  73. return nil, apperrors.ErrNotFound
  74. }
  75. return it, nil
  76. }
  77. type mockMemberships struct{ byUser map[string][]orgmodel.Membership }
  78. func (m *mockMemberships) add(uid string, ms ...orgmodel.Membership) {
  79. m.byUser[uid] = append(m.byUser[uid], ms...)
  80. }
  81. func (m *mockMemberships) ListByCanonicalUserID(_ context.Context, uid string) ([]orgmodel.Membership, error) {
  82. list := m.byUser[uid]
  83. if list == nil {
  84. return []orgmodel.Membership{}, nil
  85. }
  86. return list, nil
  87. }
  88. func (m *mockMemberships) GetByUserInstitutionCampus(_ context.Context, uid string, inst, campus int64) (*orgmodel.Membership, error) {
  89. var best *orgmodel.Membership
  90. for i := range m.byUser[uid] {
  91. mm := &m.byUser[uid][i]
  92. if mm.InstitutionID == inst && mm.CampusID == campus {
  93. if best == nil || mm.CreatedAt.After(best.CreatedAt) {
  94. best = mm
  95. }
  96. }
  97. }
  98. if best == nil {
  99. return nil, apperrors.ErrNotFound
  100. }
  101. return best, nil
  102. }
  103. // 编译期断言:mock 满足 repository 接口(签名漂移即编译失败)。
  104. var (
  105. _ repository.UserRepository = (*mockUsers)(nil)
  106. _ repository.IdentityRepository = (*mockIdentities)(nil)
  107. _ repository.MembershipRepository = (*mockMemberships)(nil)
  108. )
  109. // ---- fixture ----
  110. // fakeWechat 微信客户端打桩:code→openid 映射(默认返回 "openid-fixed";可注入失败)。
  111. type fakeWechat struct {
  112. byCode map[string]string
  113. fail bool
  114. called int
  115. }
  116. func (f *fakeWechat) ExchangeCode(_ context.Context, _, _, code, _ string) (string, error) {
  117. f.called++
  118. if f.fail {
  119. return "", &wechatErr{}
  120. }
  121. if oid, ok := f.byCode[code]; ok {
  122. return oid, nil
  123. }
  124. return "", &wechatErr{}
  125. }
  126. // wechatErr 实现 wechat 包的"换 openid 失败"错误形态(IsTokenError 兼容:此处仅需非 nil error)。
  127. type wechatErr struct{}
  128. func (*wechatErr) Error() string { return "wechat: 换 openid 失败(测试打桩)" }
  129. type fixture struct {
  130. t *testing.T
  131. users *mockUsers
  132. identities *mockIdentities
  133. memberships *mockMemberships
  134. wechat *fakeWechat
  135. wxSvc *service.WechatService
  136. handler *Handler
  137. pubKeys []string
  138. privPEM string
  139. issuer *token.Issuer
  140. revoke *appredis.RevocationStore
  141. refresh *appredis.RefreshStore
  142. }
  143. // newFixture 起 miniredis + 共享 *Client + 真 Issuer(30min/30d) + AuthService + Handler。
  144. func newFixture(t *testing.T) *fixture {
  145. t.Helper()
  146. mr, err := miniredis.Run()
  147. if err != nil {
  148. t.Fatalf("miniredis.Run: %v", err)
  149. }
  150. t.Cleanup(mr.Close)
  151. rc, err := appredis.NewClient(config.RedisCfg{Addr: mr.Addr()})
  152. if err != nil {
  153. t.Fatalf("NewClient: %v", err)
  154. }
  155. t.Cleanup(func() { _ = rc.Close() })
  156. privPEM, pubKeys := genRSAKey(t)
  157. refreshStore := appredis.NewRefreshStore(rc)
  158. revocation := appredis.NewRevocationStore(rc, "revoked")
  159. tickets := appredis.NewLoginTicketStore(rc)
  160. wxStates := appredis.NewWechatQrcodeStore(rc)
  161. issuer, err := token.NewIssuer(privPEM, "https://unified.test", 30*time.Minute, 30*24*time.Hour, refreshStore, revocation)
  162. if err != nil {
  163. t.Fatalf("NewIssuer: %v", err)
  164. }
  165. users := &mockUsers{byUID: map[string]*model.User{}}
  166. ids := newMockIdentities()
  167. mergs := &mockMemberships{byUser: map[string][]orgmodel.Membership{}}
  168. svc, err := service.NewAuthService(service.Config{
  169. Users: users, Identities: ids, Memberships: mergs,
  170. Issuer: issuer, Tickets: tickets,
  171. AccessTTL: 30 * time.Minute, PublicKeys: pubKeys, IssuerStr: "https://unified.test",
  172. Revocation: revocation, LoginTicketTTL: 5 * time.Minute,
  173. })
  174. if err != nil {
  175. t.Fatalf("NewAuthService: %v", err)
  176. }
  177. fw := &fakeWechat{byCode: map[string]string{}}
  178. wxSvc, err := service.NewWechatService(service.WechatConfig{
  179. Client: fw, States: wxStates, Tickets: tickets, Identities: ids,
  180. Campuses: []service.WechatCampus{{CampusID: 3, AppID: "appid-test", Secret: "secret-test"}},
  181. CallbackURL: "https://unified.test/auth/wechat/callback",
  182. })
  183. if err != nil {
  184. t.Fatalf("NewWechatService: %v", err)
  185. }
  186. h, err := New(Config{Svc: svc, Wechat: wxSvc})
  187. if err != nil {
  188. t.Fatalf("New Handler: %v", err)
  189. }
  190. return &fixture{
  191. t: t, users: users, identities: ids, memberships: mergs, wechat: fw, wxSvc: wxSvc, handler: h,
  192. pubKeys: pubKeys, privPEM: privPEM, issuer: issuer, revoke: revocation, refresh: refreshStore,
  193. }
  194. }
  195. // genRSAKey 生成 RS2048 私钥 + 公钥 PEM(PKCS1 私有 / PKIX 公共)。
  196. func genRSAKey(t *testing.T) (string, []string) {
  197. t.Helper()
  198. key, err := rsa.GenerateKey(rand.Reader, 2048)
  199. if err != nil {
  200. t.Fatalf("生成 RSA 私钥: %v", err)
  201. }
  202. privPEM := string(pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}))
  203. pubDER, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
  204. if err != nil {
  205. t.Fatalf("序列化公钥: %v", err)
  206. }
  207. pubPEM := string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: pubDER}))
  208. return privPEM, []string{pubPEM}
  209. }
  210. // addWechatUser 造一个用户 + wechat 身份(type=wechat, identifier=openid;扫码登录绑定用)。
  211. func (fx *fixture) addWechatUser(uid, openid string) {
  212. fx.t.Helper()
  213. if fx.users.byUID[uid] == nil {
  214. fx.users.byUID[uid] = &model.User{CanonicalUserID: uid, PersonType: model.PersonTypeStaff, Status: model.UserStatusActive}
  215. }
  216. fx.identities.add(model.IdentityTypeWechat, openid,
  217. &model.Identity{CanonicalUserID: uid, Type: model.IdentityTypeWechat, Identifier: openid, Verified: true})
  218. }
  219. // addUser 造一个 argon2 用户 + username 身份(测试夹具快捷构造)。
  220. func (fx *fixture) addArgon2User(uid, username, password string) {
  221. fx.t.Helper()
  222. hash, err := credential.HashArgon2(password)
  223. if err != nil {
  224. fx.t.Fatalf("HashArgon2: %v", err)
  225. }
  226. fx.users.byUID[uid] = &model.User{
  227. CanonicalUserID: uid, PersonType: model.PersonTypeStaff, Status: model.UserStatusActive,
  228. PasswordHash: &hash, HashVersion: ptr(model.HashVersionArgon2),
  229. }
  230. fx.identities.add(model.IdentityTypeUsername, username,
  231. &model.Identity{CanonicalUserID: uid, Type: model.IdentityTypeUsername, Identifier: username})
  232. }
  233. func ptr[T any](v T) *T { return &v }
  234. // ---- 响应解析 ----
  235. // envelope 统一响应信封(断言用;Data 留原始 JSON 供按需再解析)。
  236. type envelope struct {
  237. Code int `json:"code"`
  238. Message string `json:"message"`
  239. Data json.RawMessage `json:"data"`
  240. Success bool `json:"success"`
  241. }
  242. // do 发一个请求并解出统一信封(HTTP 恒 200,断 body.code)。
  243. func do(t *testing.T, app *fiber.App, method, path, body string, headers map[string]string) *envelope {
  244. t.Helper()
  245. var req *http.Request
  246. if method == http.MethodGet {
  247. req = httptest.NewRequest(method, path, nil)
  248. } else {
  249. req = httptest.NewRequest(method, path, strings.NewReader(body))
  250. }
  251. for k, v := range headers {
  252. req.Header.Set(k, v)
  253. }
  254. resp, err := app.Test(req, -1)
  255. if err != nil {
  256. t.Fatalf("%s %s 请求失败: %v", method, path, err)
  257. }
  258. if resp.StatusCode != http.StatusOK {
  259. t.Fatalf("%s %s HTTP 状态码=%d(铁律 6 要求恒 200)", method, path, resp.StatusCode)
  260. }
  261. var env envelope
  262. if err := json.NewDecoder(resp.Body).Decode(&env); err != nil {
  263. t.Fatalf("%s %s 解析响应失败: %v", method, path, err)
  264. }
  265. return &env
  266. }
  267. // newApp 按端点清单构建 fiber 应用(公开路由 + 受保护路由;受保护路由前挂 claims 中间件)。
  268. // withClaims 为 true 时向 /auth/me、/auth/logout 注入已验签 claims(模拟 T4-5 中间件写入)。
  269. func (fx *fixture) newApp(claims *token.Claims) *fiber.App {
  270. fx.t.Helper()
  271. app := fiber.New(fiber.Config{DisableStartupMessage: true})
  272. // 公开路由
  273. app.Post("/auth/login", fx.handler.Login)
  274. app.Post("/auth/issue", fx.handler.Issue)
  275. app.Post("/auth/refresh", fx.handler.Refresh)
  276. app.Get("/auth/wechat/qrcode", fx.handler.WechatQrcode)
  277. app.Get("/auth/wechat/status", fx.handler.WechatStatus)
  278. app.Get("/auth/wechat/callback", fx.handler.WechatCallback)
  279. // 受保护路由(模拟 T4-5 中间件:把 claims 写入 c.Locals(ClaimsCtxKey))
  280. auth := app.Group("/auth")
  281. auth.Use(func(c *fiber.Ctx) error {
  282. if claims != nil {
  283. _ = c.Locals(ClaimsCtxKey, claims)
  284. }
  285. return c.Next()
  286. })
  287. auth.Get("/me", fx.handler.Me)
  288. auth.Post("/logout", fx.handler.Logout)
  289. return app
  290. }
  291. // login 调 ① 并返回 loginTicket(供 ② 用)。失败即 Fatal。
  292. func (fx *fixture) login(username, password string) string {
  293. fx.t.Helper()
  294. app := fx.newApp(nil)
  295. env := do(fx.t, app, http.MethodPost, "/auth/login",
  296. `{"username":"`+username+`","password":"`+password+`"}`, nil)
  297. if env.Code != 200 {
  298. fx.t.Fatalf("login code=%d msg=%s(期望 200)", env.Code, env.Message)
  299. }
  300. var step1 struct {
  301. LoginTicket string `json:"loginTicket"`
  302. }
  303. if err := json.Unmarshal(env.Data, &step1); err != nil {
  304. fx.t.Fatalf("解析 loginTicket 失败: %v", err)
  305. }
  306. if step1.LoginTicket == "" {
  307. fx.t.Fatal("loginTicket 为空")
  308. }
  309. return step1.LoginTicket
  310. }
  311. // ---- Login(两步第一步)----
  312. // TestLogin_Success argon2 命中:code 200,data 含 loginTicket + user + memberships。
  313. func TestLogin_Success(t *testing.T) {
  314. fx := newFixture(t)
  315. fx.addArgon2User("01GAQF0Z6C1V9Y3E5H7K2M8B4T", "testuser", "correct-password")
  316. fx.memberships.add("01GAQF0Z6C1V9Y3E5H7K2M8B4T", orgmodel.Membership{
  317. MembershipID: 1, CanonicalUserID: "01GAQF0Z6C1V9Y3E5H7K2M8B4T",
  318. InstitutionID: 11, CampusID: 3, Role: "teacher", Status: "active",
  319. })
  320. app := fx.newApp(nil)
  321. env := do(fx.t, app, http.MethodPost, "/auth/login",
  322. `{"username":"testuser","password":"correct-password"}`, nil)
  323. if env.Code != 200 || !env.Success {
  324. t.Fatalf("code=%d msg=%s(期望 200 成功)", env.Code, env.Message)
  325. }
  326. var step1 struct {
  327. LoginTicket string `json:"loginTicket"`
  328. User struct {
  329. ID string `json:"id"`
  330. PersonType string `json:"personType"`
  331. Status string `json:"status"`
  332. } `json:"user"`
  333. Memberships []struct {
  334. InstitutionID int64 `json:"institutionId"`
  335. CampusID int64 `json:"campusId"`
  336. Role string `json:"role"`
  337. } `json:"memberships"`
  338. }
  339. if err := json.Unmarshal(env.Data, &step1); err != nil {
  340. t.Fatalf("解析 data 失败: %v", err)
  341. }
  342. if step1.LoginTicket == "" {
  343. t.Fatal("loginTicket 缺失")
  344. }
  345. if len(step1.LoginTicket) != 32 {
  346. t.Fatalf("loginTicket 长度=%d(期望 32 hex)", len(step1.LoginTicket))
  347. }
  348. if step1.User.ID != "01GAQF0Z6C1V9Y3E5H7K2M8B4T" {
  349. t.Fatalf("user.id=%q(期望 ULID)", step1.User.ID)
  350. }
  351. if len(step1.Memberships) != 1 || step1.Memberships[0].Role != "teacher" {
  352. t.Fatalf("memberships=%+v(期望 1 条 teacher)", step1.Memberships)
  353. }
  354. }
  355. // TestLogin_WrongPassword 密码错:code 1001(统一文案,防枚举)。
  356. func TestLogin_WrongPassword(t *testing.T) {
  357. fx := newFixture(t)
  358. fx.addArgon2User("01GAQF0Z6C1V9Y3E5H7K2M8B4T", "testuser", "correct-password")
  359. app := fx.newApp(nil)
  360. env := do(fx.t, app, http.MethodPost, "/auth/login",
  361. `{"username":"testuser","password":"wrong-password"}`, nil)
  362. if env.Code != apperrors.CodeUnauth {
  363. t.Fatalf("code=%d msg=%s(期望 %d 统一文案)", env.Code, env.Message, apperrors.CodeUnauth)
  364. }
  365. if env.Success {
  366. t.Fatal("success 应为 false")
  367. }
  368. }
  369. // TestLogin_UnknownUsername 未知账号:code 1001(与密码错同码,防枚举)。
  370. func TestLogin_UnknownUsername(t *testing.T) {
  371. fx := newFixture(t)
  372. app := fx.newApp(nil)
  373. env := do(fx.t, app, http.MethodPost, "/auth/login",
  374. `{"username":"ghost","password":"whatever"}`, nil)
  375. if env.Code != apperrors.CodeUnauth {
  376. t.Fatalf("code=%d(期望 %d 统一文案,防枚举)", env.Code, apperrors.CodeUnauth)
  377. }
  378. }
  379. // TestLogin_DisabledUser 禁用账号:code 1001(统一文案,不泄漏"存在但禁用")。
  380. func TestLogin_DisabledUser(t *testing.T) {
  381. fx := newFixture(t)
  382. uid := "01GAQF0Z6C1V9Y3E5H7K2M8B4T"
  383. fx.addArgon2User(uid, "testuser", "correct-password")
  384. fx.users.byUID[uid].Status = model.UserStatusDisabled
  385. app := fx.newApp(nil)
  386. env := do(fx.t, app, http.MethodPost, "/auth/login",
  387. `{"username":"testuser","password":"correct-password"}`, nil)
  388. if env.Code != apperrors.CodeUnauth {
  389. t.Fatalf("code=%d(期望 %d 统一文案)", env.Code, apperrors.CodeUnauth)
  390. }
  391. }
  392. // TestLogin_Md5Salt_LazyUpgrade 命中 md5_salt:升级 argon2 后成功(code 200)。
  393. func TestLogin_Md5Salt_LazyUpgrade(t *testing.T) {
  394. fx := newFixture(t)
  395. uid := "01GAQF0Z6C1V9Y3E5H7K2M8B4T"
  396. salt := "salty"
  397. // md5(password+salt) hex 小写(教务旧算法)
  398. d := md5Hex("correct-password" + salt)
  399. fx.users.byUID[uid] = &model.User{
  400. CanonicalUserID: uid, PersonType: model.PersonTypeStaff, Status: model.UserStatusActive,
  401. PasswordHash: &d, PasswordSalt: ptr(salt), HashVersion: ptr(model.HashVersionMd5Salt),
  402. }
  403. fx.identities.add(model.IdentityTypeUsername, "testuser",
  404. &model.Identity{CanonicalUserID: uid, Type: model.IdentityTypeUsername, Identifier: "testuser"})
  405. fx.memberships.add(uid, orgmodel.Membership{
  406. MembershipID: 1, CanonicalUserID: uid, InstitutionID: 11, CampusID: 3,
  407. Role: "teacher", Status: "active",
  408. })
  409. app := fx.newApp(nil)
  410. env := do(fx.t, app, http.MethodPost, "/auth/login",
  411. `{"username":"testuser","password":"correct-password"}`, nil)
  412. if env.Code != 200 {
  413. t.Fatalf("code=%d msg=%s(期望 200:惰性升级后放行)", env.Code, env.Message)
  414. }
  415. // 升级写回后 hash_version 应为 argon2
  416. if fx.users.byUID[uid].HashVersion == nil || *fx.users.byUID[uid].HashVersion != model.HashVersionArgon2 {
  417. t.Fatalf("hash_version=%v(期望升级后为 argon2)", fx.users.byUID[uid].HashVersion)
  418. }
  419. }
  420. // TestLogin_BadParam 空账号:code 2001(validator 校验失败)。
  421. func TestLogin_BadParam(t *testing.T) {
  422. fx := newFixture(t)
  423. app := fx.newApp(nil)
  424. env := do(fx.t, app, http.MethodPost, "/auth/login", `{"username":"","password":"whatever"}`, nil)
  425. if env.Code != apperrors.CodeBadParam {
  426. t.Fatalf("code=%d(期望 %d 参数缺失)", env.Code, apperrors.CodeBadParam)
  427. }
  428. }
  429. // TestLogin_BadFormat 非法 JSON:code 2002(参数格式错误)。
  430. func TestLogin_BadFormat(t *testing.T) {
  431. fx := newFixture(t)
  432. app := fx.newApp(nil)
  433. env := do(fx.t, app, http.MethodPost, "/auth/login", `{bad json`, nil)
  434. if env.Code != apperrors.CodeBadFormat {
  435. t.Fatalf("code=%d(期望 %d 格式错误)", env.Code, apperrors.CodeBadFormat)
  436. }
  437. }
  438. // ---- Issue(两步第二步)----
  439. // TestIssue_Success 合法票据 + 归属作用域:code 200,data 含 accessToken + institutionId + roles。
  440. func TestIssue_Success(t *testing.T) {
  441. fx := newFixture(t)
  442. uid := "01GAQF0Z6C1V9Y3E5H7K2M8B4T"
  443. fx.addArgon2User(uid, "testuser", "correct-password")
  444. fx.memberships.add(uid, orgmodel.Membership{
  445. MembershipID: 1, CanonicalUserID: uid, InstitutionID: 11, CampusID: 3,
  446. Role: "teacher", Status: "active",
  447. })
  448. ticket := fx.login("testuser", "correct-password")
  449. app := fx.newApp(nil)
  450. env := do(fx.t, app, http.MethodPost, "/auth/issue",
  451. `{"loginTicket":"`+ticket+`","institutionId":11,"campusId":3}`, nil)
  452. if env.Code != 200 || !env.Success {
  453. t.Fatalf("code=%d msg=%s(期望 200 成功)", env.Code, env.Message)
  454. }
  455. var pair struct {
  456. AccessToken string `json:"accessToken"`
  457. RefreshToken string `json:"refreshToken"`
  458. InstitutionID int64 `json:"institutionId"`
  459. CampusID int64 `json:"campusId"`
  460. Roles []string `json:"roles"`
  461. }
  462. if err := json.Unmarshal(env.Data, &pair); err != nil {
  463. t.Fatalf("解析 data 失败: %v", err)
  464. }
  465. if pair.AccessToken == "" || pair.RefreshToken == "" {
  466. t.Fatalf("accessToken/refreshToken 缺失: %+v", pair)
  467. }
  468. if pair.InstitutionID != 11 || pair.CampusID != 3 {
  469. t.Fatalf("作用域=%d/%d(期望 11/3)", pair.InstitutionID, pair.CampusID)
  470. }
  471. if len(pair.Roles) != 1 || pair.Roles[0] != "teacher" {
  472. t.Fatalf("roles=%v(期望 [teacher])", pair.Roles)
  473. }
  474. // access 应可被本公钥验签
  475. claims, err := token.Verify(context.Background(), fx.pubKeys, nil, "https://unified.test", pair.AccessToken)
  476. if err != nil {
  477. t.Fatalf("验签 access 失败: %v", err)
  478. }
  479. if claims.Sub != uid {
  480. t.Fatalf("claims.Sub=%q(期望 %q)", claims.Sub, uid)
  481. }
  482. }
  483. // TestIssue_InvalidTicket 非法/不存在票据:code 1001。
  484. func TestIssue_InvalidTicket(t *testing.T) {
  485. fx := newFixture(t)
  486. fx.addArgon2User("01GAQF0Z6C1V9Y3E5H7K2M8B4T", "testuser", "correct-password")
  487. app := fx.newApp(nil)
  488. env := do(fx.t, app, http.MethodPost, "/auth/issue",
  489. `{"loginTicket":"00000000000000000000000000000000","institutionId":11,"campusId":3}`, nil)
  490. if env.Code != apperrors.CodeUnauth {
  491. t.Fatalf("code=%d(期望 %d 票据失效)", env.Code, apperrors.CodeUnauth)
  492. }
  493. }
  494. // TestIssue_ReplayTicket 同一票据二次消费:code 1001(GETDEL 原子,防重放)。
  495. func TestIssue_ReplayTicket(t *testing.T) {
  496. fx := newFixture(t)
  497. uid := "01GAQF0Z6C1V9Y3E5H7K2M8B4T"
  498. fx.addArgon2User(uid, "testuser", "correct-password")
  499. fx.memberships.add(uid, orgmodel.Membership{
  500. MembershipID: 1, CanonicalUserID: uid, InstitutionID: 11, CampusID: 3,
  501. Role: "teacher", Status: "active",
  502. })
  503. ticket := fx.login("testuser", "correct-password")
  504. app := fx.newApp(nil)
  505. body := `{"loginTicket":"` + ticket + `","institutionId":11,"campusId":3}`
  506. if env := do(fx.t, app, http.MethodPost, "/auth/issue", body, nil); env.Code != 200 {
  507. t.Fatalf("首次消费 code=%d(期望 200)", env.Code)
  508. }
  509. // 重放:票据已被 GETDEL 消费,应失效
  510. env := do(fx.t, app, http.MethodPost, "/auth/issue", body, nil)
  511. if env.Code != apperrors.CodeUnauth {
  512. t.Fatalf("重放 code=%d(期望 %d 票据已消费)", env.Code, apperrors.CodeUnauth)
  513. }
  514. }
  515. // TestIssue_ScopeNotBelong 作用域不属于该账号:code 1003(越权)。
  516. func TestIssue_ScopeNotBelong(t *testing.T) {
  517. fx := newFixture(t)
  518. uid := "01GAQF0Z6C1V9Y3E5H7K2M8B4T"
  519. fx.addArgon2User(uid, "testuser", "correct-password")
  520. fx.memberships.add(uid, orgmodel.Membership{
  521. MembershipID: 1, CanonicalUserID: uid, InstitutionID: 11, CampusID: 3,
  522. Role: "teacher", Status: "active",
  523. })
  524. ticket := fx.login("testuser", "correct-password")
  525. app := fx.newApp(nil)
  526. env := do(fx.t, app, http.MethodPost, "/auth/issue",
  527. `{"loginTicket":"`+ticket+`","institutionId":99,"campusId":99}`, nil)
  528. if env.Code != apperrors.CodeForbidden {
  529. t.Fatalf("code=%d(期望 %d 作用域越权)", env.Code, apperrors.CodeForbidden)
  530. }
  531. }
  532. // TestIssue_ScopeInactive 归属已失效(inactive):code 1003。
  533. func TestIssue_ScopeInactive(t *testing.T) {
  534. fx := newFixture(t)
  535. uid := "01GAQF0Z6C1V9Y3E5H7K2M8B4T"
  536. fx.addArgon2User(uid, "testuser", "correct-password")
  537. fx.memberships.add(uid, orgmodel.Membership{
  538. MembershipID: 1, CanonicalUserID: uid, InstitutionID: 11, CampusID: 3,
  539. Role: "teacher", Status: "inactive",
  540. })
  541. ticket := fx.login("testuser", "correct-password")
  542. app := fx.newApp(nil)
  543. env := do(fx.t, app, http.MethodPost, "/auth/issue",
  544. `{"loginTicket":"`+ticket+`","institutionId":11,"campusId":3}`, nil)
  545. if env.Code != apperrors.CodeForbidden {
  546. t.Fatalf("code=%d(期望 %d 归属失效)", env.Code, apperrors.CodeForbidden)
  547. }
  548. }
  549. // TestIssue_BadParam 票据长度非 32:code 2001。
  550. func TestIssue_BadParam(t *testing.T) {
  551. fx := newFixture(t)
  552. app := fx.newApp(nil)
  553. env := do(fx.t, app, http.MethodPost, "/auth/issue",
  554. `{"loginTicket":"short","institutionId":11,"campusId":3}`, nil)
  555. if env.Code != apperrors.CodeBadParam {
  556. t.Fatalf("code=%d(期望 %d 参数校验)", env.Code, apperrors.CodeBadParam)
  557. }
  558. }
  559. // ---- Me(受保护)----
  560. // TestMe_Success 已验签 claims 注入:code 200,data 含 user + roles + 作用域 + memberships。
  561. func TestMe_Success(t *testing.T) {
  562. fx := newFixture(t)
  563. uid := "01GAQF0Z6C1V9Y3E5H7K2M8B4T"
  564. fx.addArgon2User(uid, "testuser", "correct-password")
  565. fx.memberships.add(uid, orgmodel.Membership{
  566. MembershipID: 1, CanonicalUserID: uid, InstitutionID: 11, CampusID: 3,
  567. Role: "teacher", Status: "active",
  568. })
  569. claims := &token.Claims{Sub: uid, Roles: []string{"teacher"}, InstitutionID: 11, CampusID: 3}
  570. app := fx.newApp(claims)
  571. env := do(fx.t, app, http.MethodGet, "/auth/me", "", nil)
  572. if env.Code != 200 || !env.Success {
  573. t.Fatalf("code=%d msg=%s(期望 200 成功)", env.Code, env.Message)
  574. }
  575. var me struct {
  576. ID string `json:"id"`
  577. Roles []string `json:"roles"`
  578. InstitutionID int64 `json:"institutionId"`
  579. CampusID int64 `json:"campusId"`
  580. Memberships []struct {
  581. Role string `json:"role"`
  582. } `json:"memberships"`
  583. }
  584. if err := json.Unmarshal(env.Data, &me); err != nil {
  585. t.Fatalf("解析 data 失败: %v", err)
  586. }
  587. if me.ID != uid {
  588. t.Fatalf("id=%q(期望 %q)", me.ID, uid)
  589. }
  590. if len(me.Memberships) != 1 || me.Memberships[0].Role != "teacher" {
  591. t.Fatalf("memberships=%+v(期望 1 条 teacher)", me.Memberships)
  592. }
  593. }
  594. // TestMe_Unauth 无 claims(中间件未注入):code 1001(未登录)。
  595. func TestMe_Unauth(t *testing.T) {
  596. fx := newFixture(t)
  597. fx.addArgon2User("01GAQF0Z6C1V9Y3E5H7K2M8B4T", "testuser", "correct-password")
  598. app := fx.newApp(nil) // 无 claims
  599. env := do(fx.t, app, http.MethodGet, "/auth/me", "", nil)
  600. if env.Code != apperrors.CodeUnauth {
  601. t.Fatalf("code=%d(期望 %d 未登录)", env.Code, apperrors.CodeUnauth)
  602. }
  603. }
  604. // ---- Refresh ----
  605. // TestRefresh_Success 合法 refresh:code 200,返回新 token 对。
  606. func TestRefresh_Success(t *testing.T) {
  607. fx := newFixture(t)
  608. uid := "01GAQF0Z6C1V9Y3E5H7K2M8B4T"
  609. fx.addArgon2User(uid, "testuser", "correct-password")
  610. fx.memberships.add(uid, orgmodel.Membership{
  611. MembershipID: 1, CanonicalUserID: uid, InstitutionID: 11, CampusID: 3,
  612. Role: "teacher", Status: "active",
  613. })
  614. ticket := fx.login("testuser", "correct-password")
  615. app := fx.newApp(nil)
  616. issueEnv := do(fx.t, app, http.MethodPost, "/auth/issue",
  617. `{"loginTicket":"`+ticket+`","institutionId":11,"campusId":3}`, nil)
  618. if issueEnv.Code != 200 {
  619. t.Fatalf("issue code=%d(期望 200)", issueEnv.Code)
  620. }
  621. var pair struct {
  622. AccessToken string `json:"accessToken"`
  623. RefreshToken string `json:"refreshToken"`
  624. }
  625. _ = json.Unmarshal(issueEnv.Data, &pair)
  626. // 用旧 refresh 轮换
  627. env := do(fx.t, app, http.MethodPost, "/auth/refresh",
  628. `{"refreshToken":"`+pair.RefreshToken+`"}`, nil)
  629. if env.Code != 200 {
  630. t.Fatalf("refresh code=%d msg=%s(期望 200)", env.Code, env.Message)
  631. }
  632. }
  633. // TestRefresh_Invalid 合法格式(64 hex)但不在白名单:code 1002(登录态失效,前端跳登录)。
  634. func TestRefresh_Invalid(t *testing.T) {
  635. fx := newFixture(t)
  636. app := fx.newApp(nil)
  637. env := do(fx.t, app, http.MethodPost, "/auth/refresh",
  638. `{"refreshToken":"`+strings.Repeat("0", 64)+`"}`, nil)
  639. if env.Code != apperrors.CodeTokenExpired {
  640. t.Fatalf("code=%d(期望 %d 登录态失效)", env.Code, apperrors.CodeTokenExpired)
  641. }
  642. }
  643. // TestRefresh_BadParam refresh 长度非 48:code 2001。
  644. func TestRefresh_BadParam(t *testing.T) {
  645. fx := newFixture(t)
  646. app := fx.newApp(nil)
  647. env := do(fx.t, app, http.MethodPost, "/auth/refresh", `{"refreshToken":"too-short"}`, nil)
  648. if env.Code != apperrors.CodeBadParam {
  649. t.Fatalf("code=%d(期望 %d 参数校验)", env.Code, apperrors.CodeBadParam)
  650. }
  651. }
  652. // ---- Logout(恒 200 幂等)----
  653. // TestLogout_Success 有 claims + refresh:恒 code 200。
  654. func TestLogout_Success(t *testing.T) {
  655. fx := newFixture(t)
  656. uid := "01GAQF0Z6C1V9Y3E5H7K2M8B4T"
  657. fx.addArgon2User(uid, "testuser", "correct-password")
  658. fx.memberships.add(uid, orgmodel.Membership{
  659. MembershipID: 1, CanonicalUserID: uid, InstitutionID: 11, CampusID: 3,
  660. Role: "teacher", Status: "active",
  661. })
  662. ticket := fx.login("testuser", "correct-password")
  663. app := fx.newApp(nil)
  664. issueEnv := do(fx.t, app, http.MethodPost, "/auth/issue",
  665. `{"loginTicket":"`+ticket+`","institutionId":11,"campusId":3}`, nil)
  666. var pair struct {
  667. RefreshToken string `json:"refreshToken"`
  668. }
  669. _ = json.Unmarshal(issueEnv.Data, &pair)
  670. // 带 claims 登出(模拟已验签中间件写入)
  671. claims := &token.Claims{Sub: uid, Roles: []string{"teacher"}, InstitutionID: 11, CampusID: 3, ID: "some-jti"}
  672. appAuth := fx.newApp(claims)
  673. env := do(fx.t, appAuth, http.MethodPost, "/auth/logout",
  674. `{"refreshToken":"`+pair.RefreshToken+`"}`, nil)
  675. if env.Code != 200 || !env.Success {
  676. t.Fatalf("logout code=%d(期望恒 200 幂等)", env.Code)
  677. }
  678. }
  679. // TestLogout_NoClaims 无 claims:仍恒 code 200(本地态必清)。
  680. func TestLogout_NoClaims(t *testing.T) {
  681. fx := newFixture(t)
  682. app := fx.newApp(nil)
  683. env := do(fx.t, app, http.MethodPost, "/auth/logout", `{}`, nil)
  684. if env.Code != 200 {
  685. t.Fatalf("logout code=%d(期望恒 200)", env.Code)
  686. }
  687. }
  688. // ---- 微信扫码登录(状态机 + 复用两步票据)----
  689. // TestWechatQrcode_Success 生成二维码:code 200,data 含 state(32hex) + qrUrl(含 state) + campusId + expiresIn。
  690. func TestWechatQrcode_Success(t *testing.T) {
  691. fx := newFixture(t)
  692. app := fx.newApp(nil)
  693. env := do(fx.t, app, http.MethodGet, "/auth/wechat/qrcode", "", nil)
  694. if env.Code != 200 || !env.Success {
  695. t.Fatalf("code=%d msg=%s(期望 200 成功)", env.Code, env.Message)
  696. }
  697. var qr struct {
  698. State string `json:"state"`
  699. QRURL string `json:"qrUrl"`
  700. CampusID int64 `json:"campusId"`
  701. ExpiresIn int64 `json:"expiresIn"`
  702. }
  703. if err := json.Unmarshal(env.Data, &qr); err != nil {
  704. t.Fatalf("解析 data 失败: %v", err)
  705. }
  706. if len(qr.State) != 32 {
  707. t.Fatalf("state 长度=%d(期望 32 hex)", len(qr.State))
  708. }
  709. if !strings.Contains(qr.QRURL, "open.weixin.qq.com/connect/qrconnect") {
  710. t.Fatalf("qrUrl=%q(期望微信网页授权 URL)", qr.QRURL)
  711. }
  712. if !strings.Contains(qr.QRURL, "state="+qr.State) {
  713. t.Fatalf("qrUrl=%q(期望携带 state=%q)", qr.QRURL, qr.State)
  714. }
  715. if qr.CampusID != 3 {
  716. t.Fatalf("campusId=%d(期望 3,配置首个 campus)", qr.CampusID)
  717. }
  718. if qr.ExpiresIn <= 0 {
  719. t.Fatalf("expiresIn=%d(期望 >0 秒)", qr.ExpiresIn)
  720. }
  721. }
  722. // TestWechatStatus_Pending 新 state 轮询:status=pending(继续轮询)。
  723. func TestWechatStatus_Pending(t *testing.T) {
  724. fx := newFixture(t)
  725. app := fx.newApp(nil)
  726. qr := do(fx.t, app, http.MethodGet, "/auth/wechat/qrcode", "", nil)
  727. var q struct {
  728. State string `json:"state"`
  729. }
  730. _ = json.Unmarshal(qr.Data, &q)
  731. env := do(fx.t, app, http.MethodGet, "/auth/wechat/status?state="+q.State, "", nil)
  732. if env.Code != 200 {
  733. t.Fatalf("code=%d msg=%s(期望 200)", env.Code, env.Message)
  734. }
  735. var st struct {
  736. Status string `json:"status"`
  737. }
  738. if err := json.Unmarshal(env.Data, &st); err != nil {
  739. t.Fatalf("解析 data 失败: %v", err)
  740. }
  741. if st.Status != "pending" {
  742. t.Fatalf("status=%q(期望 pending)", st.Status)
  743. }
  744. }
  745. // TestWechatStatus_Expired 未知 state 轮询:expired=true(前端停轮询,提示刷新)。
  746. func TestWechatStatus_Expired(t *testing.T) {
  747. fx := newFixture(t)
  748. app := fx.newApp(nil)
  749. env := do(fx.t, app, http.MethodGet, "/auth/wechat/status?state=doesnotexist00000000000000000000", "", nil)
  750. if env.Code != 200 {
  751. t.Fatalf("code=%d msg=%s(期望 200,expired 语义非故障)", env.Code, env.Message)
  752. }
  753. var st struct {
  754. Expired bool `json:"expired"`
  755. }
  756. if err := json.Unmarshal(env.Data, &st); err != nil {
  757. t.Fatalf("解析 data 失败: %v", err)
  758. }
  759. if !st.Expired {
  760. t.Fatal("未知 state 应 expired=true")
  761. }
  762. }
  763. // TestWechatCallback_Success 扫码成功(已绑定):code 换 openid → 发 loginTicket → status=success。
  764. // 校验:callback 返回 success + loginTicket + userId;state 内票据可被 ② issue 消费(复用两步②)。
  765. func TestWechatCallback_Success(t *testing.T) {
  766. fx := newFixture(t)
  767. uid := "01GAQF0Z6C1V9Y3E5H7K2M8B4T"
  768. fx.addWechatUser(uid, "openid-bound")
  769. fx.memberships.add(uid, orgmodel.Membership{
  770. MembershipID: 1, CanonicalUserID: uid, InstitutionID: 11, CampusID: 3,
  771. Role: "teacher", Status: "active",
  772. })
  773. fx.wechat.byCode["code-ok"] = "openid-bound"
  774. app := fx.newApp(nil)
  775. // ① 生成二维码
  776. qrEnv := do(fx.t, app, http.MethodGet, "/auth/wechat/qrcode", "", nil)
  777. var qr struct {
  778. State string `json:"state"`
  779. }
  780. _ = json.Unmarshal(qrEnv.Data, &qr)
  781. // ② 微信回调:code=code-ok, state=<state>
  782. cbEnv := do(fx.t, app, http.MethodGet, "/auth/wechat/callback?code=code-ok&state="+qr.State, "", nil)
  783. if cbEnv.Code != 200 {
  784. t.Fatalf("callback code=%d msg=%s(期望 200 成功)", cbEnv.Code, cbEnv.Message)
  785. }
  786. var cb struct {
  787. Status string `json:"status"`
  788. LoginTicket string `json:"loginTicket"`
  789. UserID string `json:"userId"`
  790. }
  791. if err := json.Unmarshal(cbEnv.Data, &cb); err != nil {
  792. t.Fatalf("解析 callback data 失败: %v", err)
  793. }
  794. if cb.Status != "success" {
  795. t.Fatalf("status=%q(期望 success)", cb.Status)
  796. }
  797. if cb.UserID != uid {
  798. t.Fatalf("userId=%q(期望 %q)", cb.UserID, uid)
  799. }
  800. if cb.LoginTicket == "" || len(cb.LoginTicket) != 32 {
  801. t.Fatalf("loginTicket=%q(期望 32 hex)", cb.LoginTicket)
  802. }
  803. // ③ 轮询确认 state=success 且携带同一 loginTicket
  804. stEnv := do(fx.t, app, http.MethodGet, "/auth/wechat/status?state="+qr.State, "", nil)
  805. var st struct {
  806. Status string `json:"status"`
  807. LoginTicket string `json:"loginTicket"`
  808. }
  809. _ = json.Unmarshal(stEnv.Data, &st)
  810. if st.Status != "success" || st.LoginTicket != cb.LoginTicket {
  811. t.Fatalf("轮询 status=%q ticket=%q(期望 success + 同票据)", st.Status, st.LoginTicket)
  812. }
  813. // ④ 复用两步②:携 loginTicket 签 token(证明微信登录与账密登录走同一套 ②)
  814. issueEnv := do(fx.t, app, http.MethodPost, "/auth/issue",
  815. `{"loginTicket":"`+cb.LoginTicket+`","institutionId":11,"campusId":3}`, nil)
  816. if issueEnv.Code != 200 {
  817. t.Fatalf("issue code=%d msg=%s(期望 200:微信票据应可走同一套 ②)", issueEnv.Code, issueEnv.Message)
  818. }
  819. }
  820. // TestWechatCallback_Unbound 扫码成功但 openid 未绑定:status=unbound(前端提示"未绑定账号")。
  821. func TestWechatCallback_Unbound(t *testing.T) {
  822. fx := newFixture(t)
  823. fx.wechat.byCode["code-x"] = "openid-not-bound" // 不造该 openid 的身份记录
  824. app := fx.newApp(nil)
  825. qrEnv := do(fx.t, app, http.MethodGet, "/auth/wechat/qrcode", "", nil)
  826. var qr struct {
  827. State string `json:"state"`
  828. }
  829. _ = json.Unmarshal(qrEnv.Data, &qr)
  830. cbEnv := do(fx.t, app, http.MethodGet, "/auth/wechat/callback?code=code-x&state="+qr.State, "", nil)
  831. if cbEnv.Code != 200 {
  832. t.Fatalf("callback code=%d msg=%s(期望 200,unbound 语义)", cbEnv.Code, cbEnv.Message)
  833. }
  834. var cb struct {
  835. Status string `json:"status"`
  836. }
  837. _ = json.Unmarshal(cbEnv.Data, &cb)
  838. if cb.Status != "unbound" {
  839. t.Fatalf("status=%q(期望 unbound)", cb.Status)
  840. }
  841. }
  842. // TestWechatCallback_ThirdPartyFail 微信换 openid 失败:status=fail + code 4003(第三方超时/失败)。
  843. func TestWechatCallback_ThirdPartyFail(t *testing.T) {
  844. fx := newFixture(t)
  845. fx.wechat.fail = true // 打桩:换 openid 失败
  846. app := fx.newApp(nil)
  847. qrEnv := do(fx.t, app, http.MethodGet, "/auth/wechat/qrcode", "", nil)
  848. var qr struct {
  849. State string `json:"state"`
  850. }
  851. _ = json.Unmarshal(qrEnv.Data, &qr)
  852. cbEnv := do(fx.t, app, http.MethodGet, "/auth/wechat/callback?code=bad&state="+qr.State, "", nil)
  853. if cbEnv.Code != apperrors.CodeThirdTimeout {
  854. t.Fatalf("callback code=%d(期望 %d 第三方失败)", cbEnv.Code, apperrors.CodeThirdTimeout)
  855. }
  856. // state 应被置 fail(前端后续轮询读到 fail)
  857. stEnv := do(fx.t, app, http.MethodGet, "/auth/wechat/status?state="+qr.State, "", nil)
  858. var st struct {
  859. Status string `json:"status"`
  860. }
  861. _ = json.Unmarshal(stEnv.Data, &st)
  862. if st.Status != "fail" {
  863. t.Fatalf("state 应置 fail,实际 %q", st.Status)
  864. }
  865. }
  866. // TestWechatCallback_Replay 已终态 state 二次回调:code 1001(防重放)。
  867. func TestWechatCallback_Replay(t *testing.T) {
  868. fx := newFixture(t)
  869. uid := "01GAQF0Z6C1V9Y3E5H7K2M8B4T"
  870. fx.addWechatUser(uid, "openid-bound")
  871. fx.wechat.byCode["code-ok"] = "openid-bound"
  872. app := fx.newApp(nil)
  873. qrEnv := do(fx.t, app, http.MethodGet, "/auth/wechat/qrcode", "", nil)
  874. var qr struct {
  875. State string `json:"state"`
  876. }
  877. _ = json.Unmarshal(qrEnv.Data, &qr)
  878. // 首次回调 → success(终态)
  879. if env := do(fx.t, app, http.MethodGet, "/auth/wechat/callback?code=code-ok&state="+qr.State, "", nil); env.Code != 200 {
  880. t.Fatalf("首次回调 code=%d(期望 200)", env.Code)
  881. }
  882. // 二次回同样 state → 1001(已终态,防重放)
  883. env := do(fx.t, app, http.MethodGet, "/auth/wechat/callback?code=code-ok&state="+qr.State, "", nil)
  884. if env.Code != apperrors.CodeUnauth {
  885. t.Fatalf("重放 callback code=%d(期望 %d 已终态)", env.Code, apperrors.CodeUnauth)
  886. }
  887. }
  888. // TestWechatCallback_MissingParam 缺 code 或 state:code 2001(参数校验)。
  889. func TestWechatCallback_MissingParam(t *testing.T) {
  890. fx := newFixture(t)
  891. app := fx.newApp(nil)
  892. env := do(fx.t, app, http.MethodGet, "/auth/wechat/callback?code=only-code", "", nil)
  893. if env.Code != apperrors.CodeBadParam {
  894. t.Fatalf("code=%d(期望 %d 缺 state 参数)", env.Code, apperrors.CodeBadParam)
  895. }
  896. }
  897. // TestWechat_NotConfigured wechat 服务未注入:qrcode/status/callback 均 code 4004(未配置)。
  898. func TestWechat_NotConfigured(t *testing.T) {
  899. fx := newFixture(t)
  900. // 构造一个 wechat 为 nil 的 handler(复用 fx.svc 之外的 AuthService,此处直接重造 Handler)
  901. svc := fx.handler.svc // 复用现有 svc
  902. h, err := New(Config{Svc: svc}) // Wechat 缺省 nil
  903. if err != nil {
  904. t.Fatalf("New Handler: %v", err)
  905. }
  906. app := fiber.New(fiber.Config{DisableStartupMessage: true})
  907. app.Get("/auth/wechat/qrcode", h.WechatQrcode)
  908. app.Get("/auth/wechat/status", h.WechatStatus)
  909. app.Get("/auth/wechat/callback", h.WechatCallback)
  910. for _, path := range []string{"/auth/wechat/qrcode", "/auth/wechat/status?state=x", "/auth/wechat/callback?code=x&state=x"} {
  911. env := do(fx.t, app, http.MethodGet, path, "", nil)
  912. if env.Code != apperrors.CodeThirdNotConfigured {
  913. t.Fatalf("%s code=%d(期望 %d 未配置)", path, env.Code, apperrors.CodeThirdNotConfigured)
  914. }
  915. }
  916. }
  917. // md5Hex 计算 md5 的 hex 小写串(构造 md5_salt 测试夹具用,与 credential.legacyDigest 同语义)。
  918. func md5Hex(s string) string {
  919. d := md5.Sum([]byte(s))
  920. return hex.EncodeToString(d[:])
  921. }