handler_test.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  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. type fixture struct {
  111. t *testing.T
  112. users *mockUsers
  113. identities *mockIdentities
  114. memberships *mockMemberships
  115. handler *Handler
  116. pubKeys []string
  117. issuer *token.Issuer
  118. }
  119. // newFixture 起 miniredis + 共享 *Client + 真 Issuer(30min/30d) + AuthService + Handler。
  120. func newFixture(t *testing.T) *fixture {
  121. t.Helper()
  122. mr, err := miniredis.Run()
  123. if err != nil {
  124. t.Fatalf("miniredis.Run: %v", err)
  125. }
  126. t.Cleanup(mr.Close)
  127. rc, err := appredis.NewClient(config.RedisCfg{Addr: mr.Addr()})
  128. if err != nil {
  129. t.Fatalf("NewClient: %v", err)
  130. }
  131. t.Cleanup(func() { _ = rc.Close() })
  132. privPEM, pubKeys := genRSAKey(t)
  133. refreshStore := appredis.NewRefreshStore(rc)
  134. revocation := appredis.NewRevocationStore(rc, "revoked")
  135. tickets := appredis.NewLoginTicketStore(rc)
  136. issuer, err := token.NewIssuer(privPEM, "https://unified.test", 30*time.Minute, 30*24*time.Hour, refreshStore, revocation)
  137. if err != nil {
  138. t.Fatalf("NewIssuer: %v", err)
  139. }
  140. users := &mockUsers{byUID: map[string]*model.User{}}
  141. ids := newMockIdentities()
  142. mergs := &mockMemberships{byUser: map[string][]orgmodel.Membership{}}
  143. svc, err := service.NewAuthService(service.Config{
  144. Users: users, Identities: ids, Memberships: mergs,
  145. Issuer: issuer, Tickets: tickets,
  146. AccessTTL: 30 * time.Minute, PublicKeys: pubKeys, IssuerStr: "https://unified.test",
  147. Revocation: revocation, LoginTicketTTL: 5 * time.Minute,
  148. })
  149. if err != nil {
  150. t.Fatalf("NewAuthService: %v", err)
  151. }
  152. h, err := New(Config{Svc: svc})
  153. if err != nil {
  154. t.Fatalf("New Handler: %v", err)
  155. }
  156. return &fixture{t: t, users: users, identities: ids, memberships: mergs, handler: h, pubKeys: pubKeys, issuer: issuer}
  157. }
  158. // genRSAKey 生成 RS2048 私钥 + 公钥 PEM(PKCS1 私有 / PKIX 公共)。
  159. func genRSAKey(t *testing.T) (string, []string) {
  160. t.Helper()
  161. key, err := rsa.GenerateKey(rand.Reader, 2048)
  162. if err != nil {
  163. t.Fatalf("生成 RSA 私钥: %v", err)
  164. }
  165. privPEM := string(pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}))
  166. pubDER, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
  167. if err != nil {
  168. t.Fatalf("序列化公钥: %v", err)
  169. }
  170. pubPEM := string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: pubDER}))
  171. return privPEM, []string{pubPEM}
  172. }
  173. // addUser 造一个 argon2 用户 + username 身份(测试夹具快捷构造)。
  174. func (fx *fixture) addArgon2User(uid, username, password string) {
  175. fx.t.Helper()
  176. hash, err := credential.HashArgon2(password)
  177. if err != nil {
  178. fx.t.Fatalf("HashArgon2: %v", err)
  179. }
  180. fx.users.byUID[uid] = &model.User{
  181. CanonicalUserID: uid, PersonType: model.PersonTypeStaff, Status: model.UserStatusActive,
  182. PasswordHash: &hash, HashVersion: ptr(model.HashVersionArgon2),
  183. }
  184. fx.identities.add(model.IdentityTypeUsername, username,
  185. &model.Identity{CanonicalUserID: uid, Type: model.IdentityTypeUsername, Identifier: username})
  186. }
  187. func ptr[T any](v T) *T { return &v }
  188. // ---- 响应解析 ----
  189. // envelope 统一响应信封(断言用;Data 留原始 JSON 供按需再解析)。
  190. type envelope struct {
  191. Code int `json:"code"`
  192. Message string `json:"message"`
  193. Data json.RawMessage `json:"data"`
  194. Success bool `json:"success"`
  195. }
  196. // do 发一个请求并解出统一信封(HTTP 恒 200,断 body.code)。
  197. func do(t *testing.T, app *fiber.App, method, path, body string, headers map[string]string) *envelope {
  198. t.Helper()
  199. var req *http.Request
  200. if method == http.MethodGet {
  201. req = httptest.NewRequest(method, path, nil)
  202. } else {
  203. req = httptest.NewRequest(method, path, strings.NewReader(body))
  204. }
  205. for k, v := range headers {
  206. req.Header.Set(k, v)
  207. }
  208. resp, err := app.Test(req, -1)
  209. if err != nil {
  210. t.Fatalf("%s %s 请求失败: %v", method, path, err)
  211. }
  212. if resp.StatusCode != http.StatusOK {
  213. t.Fatalf("%s %s HTTP 状态码=%d(铁律 6 要求恒 200)", method, path, resp.StatusCode)
  214. }
  215. var env envelope
  216. if err := json.NewDecoder(resp.Body).Decode(&env); err != nil {
  217. t.Fatalf("%s %s 解析响应失败: %v", method, path, err)
  218. }
  219. return &env
  220. }
  221. // newApp 按端点清单构建 fiber 应用(公开路由 + 受保护路由;受保护路由前挂 claims 中间件)。
  222. // withClaims 为 true 时向 /auth/me、/auth/logout 注入已验签 claims(模拟 T4-5 中间件写入)。
  223. func (fx *fixture) newApp(claims *token.Claims) *fiber.App {
  224. fx.t.Helper()
  225. app := fiber.New(fiber.Config{DisableStartupMessage: true})
  226. // 公开路由
  227. app.Post("/auth/login", fx.handler.Login)
  228. app.Post("/auth/issue", fx.handler.Issue)
  229. app.Post("/auth/refresh", fx.handler.Refresh)
  230. app.Get("/auth/wechat/qrcode", fx.handler.WechatQrcode)
  231. app.Get("/auth/wechat/status", fx.handler.WechatStatus)
  232. // 受保护路由(模拟 T4-5 中间件:把 claims 写入 c.Locals(ClaimsCtxKey))
  233. auth := app.Group("/auth")
  234. auth.Use(func(c *fiber.Ctx) error {
  235. if claims != nil {
  236. _ = c.Locals(ClaimsCtxKey, claims)
  237. }
  238. return c.Next()
  239. })
  240. auth.Get("/me", fx.handler.Me)
  241. auth.Post("/logout", fx.handler.Logout)
  242. return app
  243. }
  244. // login 调 ① 并返回 loginTicket(供 ② 用)。失败即 Fatal。
  245. func (fx *fixture) login(username, password string) string {
  246. fx.t.Helper()
  247. app := fx.newApp(nil)
  248. env := do(fx.t, app, http.MethodPost, "/auth/login",
  249. `{"username":"`+username+`","password":"`+password+`"}`, nil)
  250. if env.Code != 200 {
  251. fx.t.Fatalf("login code=%d msg=%s(期望 200)", env.Code, env.Message)
  252. }
  253. var step1 struct {
  254. LoginTicket string `json:"loginTicket"`
  255. }
  256. if err := json.Unmarshal(env.Data, &step1); err != nil {
  257. fx.t.Fatalf("解析 loginTicket 失败: %v", err)
  258. }
  259. if step1.LoginTicket == "" {
  260. fx.t.Fatal("loginTicket 为空")
  261. }
  262. return step1.LoginTicket
  263. }
  264. // ---- Login(两步第一步)----
  265. // TestLogin_Success argon2 命中:code 200,data 含 loginTicket + user + memberships。
  266. func TestLogin_Success(t *testing.T) {
  267. fx := newFixture(t)
  268. fx.addArgon2User("01GAQF0Z6C1V9Y3E5H7K2M8B4T", "testuser", "correct-password")
  269. fx.memberships.add("01GAQF0Z6C1V9Y3E5H7K2M8B4T", orgmodel.Membership{
  270. MembershipID: 1, CanonicalUserID: "01GAQF0Z6C1V9Y3E5H7K2M8B4T",
  271. InstitutionID: 11, CampusID: 3, Role: "teacher", Status: "active",
  272. })
  273. app := fx.newApp(nil)
  274. env := do(fx.t, app, http.MethodPost, "/auth/login",
  275. `{"username":"testuser","password":"correct-password"}`, nil)
  276. if env.Code != 200 || !env.Success {
  277. t.Fatalf("code=%d msg=%s(期望 200 成功)", env.Code, env.Message)
  278. }
  279. var step1 struct {
  280. LoginTicket string `json:"loginTicket"`
  281. User struct {
  282. ID string `json:"id"`
  283. PersonType string `json:"personType"`
  284. Status string `json:"status"`
  285. } `json:"user"`
  286. Memberships []struct {
  287. InstitutionID int64 `json:"institutionId"`
  288. CampusID int64 `json:"campusId"`
  289. Role string `json:"role"`
  290. } `json:"memberships"`
  291. }
  292. if err := json.Unmarshal(env.Data, &step1); err != nil {
  293. t.Fatalf("解析 data 失败: %v", err)
  294. }
  295. if step1.LoginTicket == "" {
  296. t.Fatal("loginTicket 缺失")
  297. }
  298. if len(step1.LoginTicket) != 32 {
  299. t.Fatalf("loginTicket 长度=%d(期望 32 hex)", len(step1.LoginTicket))
  300. }
  301. if step1.User.ID != "01GAQF0Z6C1V9Y3E5H7K2M8B4T" {
  302. t.Fatalf("user.id=%q(期望 ULID)", step1.User.ID)
  303. }
  304. if len(step1.Memberships) != 1 || step1.Memberships[0].Role != "teacher" {
  305. t.Fatalf("memberships=%+v(期望 1 条 teacher)", step1.Memberships)
  306. }
  307. }
  308. // TestLogin_WrongPassword 密码错:code 1001(统一文案,防枚举)。
  309. func TestLogin_WrongPassword(t *testing.T) {
  310. fx := newFixture(t)
  311. fx.addArgon2User("01GAQF0Z6C1V9Y3E5H7K2M8B4T", "testuser", "correct-password")
  312. app := fx.newApp(nil)
  313. env := do(fx.t, app, http.MethodPost, "/auth/login",
  314. `{"username":"testuser","password":"wrong-password"}`, nil)
  315. if env.Code != apperrors.CodeUnauth {
  316. t.Fatalf("code=%d msg=%s(期望 %d 统一文案)", env.Code, env.Message, apperrors.CodeUnauth)
  317. }
  318. if env.Success {
  319. t.Fatal("success 应为 false")
  320. }
  321. }
  322. // TestLogin_UnknownUsername 未知账号:code 1001(与密码错同码,防枚举)。
  323. func TestLogin_UnknownUsername(t *testing.T) {
  324. fx := newFixture(t)
  325. app := fx.newApp(nil)
  326. env := do(fx.t, app, http.MethodPost, "/auth/login",
  327. `{"username":"ghost","password":"whatever"}`, nil)
  328. if env.Code != apperrors.CodeUnauth {
  329. t.Fatalf("code=%d(期望 %d 统一文案,防枚举)", env.Code, apperrors.CodeUnauth)
  330. }
  331. }
  332. // TestLogin_DisabledUser 禁用账号:code 1001(统一文案,不泄漏"存在但禁用")。
  333. func TestLogin_DisabledUser(t *testing.T) {
  334. fx := newFixture(t)
  335. uid := "01GAQF0Z6C1V9Y3E5H7K2M8B4T"
  336. fx.addArgon2User(uid, "testuser", "correct-password")
  337. fx.users.byUID[uid].Status = model.UserStatusDisabled
  338. app := fx.newApp(nil)
  339. env := do(fx.t, app, http.MethodPost, "/auth/login",
  340. `{"username":"testuser","password":"correct-password"}`, nil)
  341. if env.Code != apperrors.CodeUnauth {
  342. t.Fatalf("code=%d(期望 %d 统一文案)", env.Code, apperrors.CodeUnauth)
  343. }
  344. }
  345. // TestLogin_Md5Salt_LazyUpgrade 命中 md5_salt:升级 argon2 后成功(code 200)。
  346. func TestLogin_Md5Salt_LazyUpgrade(t *testing.T) {
  347. fx := newFixture(t)
  348. uid := "01GAQF0Z6C1V9Y3E5H7K2M8B4T"
  349. salt := "salty"
  350. // md5(password+salt) hex 小写(教务旧算法)
  351. d := md5Hex("correct-password" + salt)
  352. fx.users.byUID[uid] = &model.User{
  353. CanonicalUserID: uid, PersonType: model.PersonTypeStaff, Status: model.UserStatusActive,
  354. PasswordHash: &d, PasswordSalt: ptr(salt), HashVersion: ptr(model.HashVersionMd5Salt),
  355. }
  356. fx.identities.add(model.IdentityTypeUsername, "testuser",
  357. &model.Identity{CanonicalUserID: uid, Type: model.IdentityTypeUsername, Identifier: "testuser"})
  358. fx.memberships.add(uid, orgmodel.Membership{
  359. MembershipID: 1, CanonicalUserID: uid, InstitutionID: 11, CampusID: 3,
  360. Role: "teacher", Status: "active",
  361. })
  362. app := fx.newApp(nil)
  363. env := do(fx.t, app, http.MethodPost, "/auth/login",
  364. `{"username":"testuser","password":"correct-password"}`, nil)
  365. if env.Code != 200 {
  366. t.Fatalf("code=%d msg=%s(期望 200:惰性升级后放行)", env.Code, env.Message)
  367. }
  368. // 升级写回后 hash_version 应为 argon2
  369. if fx.users.byUID[uid].HashVersion == nil || *fx.users.byUID[uid].HashVersion != model.HashVersionArgon2 {
  370. t.Fatalf("hash_version=%v(期望升级后为 argon2)", fx.users.byUID[uid].HashVersion)
  371. }
  372. }
  373. // TestLogin_BadParam 空账号:code 2001(validator 校验失败)。
  374. func TestLogin_BadParam(t *testing.T) {
  375. fx := newFixture(t)
  376. app := fx.newApp(nil)
  377. env := do(fx.t, app, http.MethodPost, "/auth/login", `{"username":"","password":"whatever"}`, nil)
  378. if env.Code != apperrors.CodeBadParam {
  379. t.Fatalf("code=%d(期望 %d 参数缺失)", env.Code, apperrors.CodeBadParam)
  380. }
  381. }
  382. // TestLogin_BadFormat 非法 JSON:code 2002(参数格式错误)。
  383. func TestLogin_BadFormat(t *testing.T) {
  384. fx := newFixture(t)
  385. app := fx.newApp(nil)
  386. env := do(fx.t, app, http.MethodPost, "/auth/login", `{bad json`, nil)
  387. if env.Code != apperrors.CodeBadFormat {
  388. t.Fatalf("code=%d(期望 %d 格式错误)", env.Code, apperrors.CodeBadFormat)
  389. }
  390. }
  391. // ---- Issue(两步第二步)----
  392. // TestIssue_Success 合法票据 + 归属作用域:code 200,data 含 accessToken + institutionId + roles。
  393. func TestIssue_Success(t *testing.T) {
  394. fx := newFixture(t)
  395. uid := "01GAQF0Z6C1V9Y3E5H7K2M8B4T"
  396. fx.addArgon2User(uid, "testuser", "correct-password")
  397. fx.memberships.add(uid, orgmodel.Membership{
  398. MembershipID: 1, CanonicalUserID: uid, InstitutionID: 11, CampusID: 3,
  399. Role: "teacher", Status: "active",
  400. })
  401. ticket := fx.login("testuser", "correct-password")
  402. app := fx.newApp(nil)
  403. env := do(fx.t, app, http.MethodPost, "/auth/issue",
  404. `{"loginTicket":"`+ticket+`","institutionId":11,"campusId":3}`, nil)
  405. if env.Code != 200 || !env.Success {
  406. t.Fatalf("code=%d msg=%s(期望 200 成功)", env.Code, env.Message)
  407. }
  408. var pair struct {
  409. AccessToken string `json:"accessToken"`
  410. RefreshToken string `json:"refreshToken"`
  411. InstitutionID int64 `json:"institutionId"`
  412. CampusID int64 `json:"campusId"`
  413. Roles []string `json:"roles"`
  414. }
  415. if err := json.Unmarshal(env.Data, &pair); err != nil {
  416. t.Fatalf("解析 data 失败: %v", err)
  417. }
  418. if pair.AccessToken == "" || pair.RefreshToken == "" {
  419. t.Fatalf("accessToken/refreshToken 缺失: %+v", pair)
  420. }
  421. if pair.InstitutionID != 11 || pair.CampusID != 3 {
  422. t.Fatalf("作用域=%d/%d(期望 11/3)", pair.InstitutionID, pair.CampusID)
  423. }
  424. if len(pair.Roles) != 1 || pair.Roles[0] != "teacher" {
  425. t.Fatalf("roles=%v(期望 [teacher])", pair.Roles)
  426. }
  427. // access 应可被本公钥验签
  428. claims, err := token.Verify(context.Background(), fx.pubKeys, nil, "https://unified.test", pair.AccessToken)
  429. if err != nil {
  430. t.Fatalf("验签 access 失败: %v", err)
  431. }
  432. if claims.Sub != uid {
  433. t.Fatalf("claims.Sub=%q(期望 %q)", claims.Sub, uid)
  434. }
  435. }
  436. // TestIssue_InvalidTicket 非法/不存在票据:code 1001。
  437. func TestIssue_InvalidTicket(t *testing.T) {
  438. fx := newFixture(t)
  439. fx.addArgon2User("01GAQF0Z6C1V9Y3E5H7K2M8B4T", "testuser", "correct-password")
  440. app := fx.newApp(nil)
  441. env := do(fx.t, app, http.MethodPost, "/auth/issue",
  442. `{"loginTicket":"00000000000000000000000000000000","institutionId":11,"campusId":3}`, nil)
  443. if env.Code != apperrors.CodeUnauth {
  444. t.Fatalf("code=%d(期望 %d 票据失效)", env.Code, apperrors.CodeUnauth)
  445. }
  446. }
  447. // TestIssue_ReplayTicket 同一票据二次消费:code 1001(GETDEL 原子,防重放)。
  448. func TestIssue_ReplayTicket(t *testing.T) {
  449. fx := newFixture(t)
  450. uid := "01GAQF0Z6C1V9Y3E5H7K2M8B4T"
  451. fx.addArgon2User(uid, "testuser", "correct-password")
  452. fx.memberships.add(uid, orgmodel.Membership{
  453. MembershipID: 1, CanonicalUserID: uid, InstitutionID: 11, CampusID: 3,
  454. Role: "teacher", Status: "active",
  455. })
  456. ticket := fx.login("testuser", "correct-password")
  457. app := fx.newApp(nil)
  458. body := `{"loginTicket":"` + ticket + `","institutionId":11,"campusId":3}`
  459. if env := do(fx.t, app, http.MethodPost, "/auth/issue", body, nil); env.Code != 200 {
  460. t.Fatalf("首次消费 code=%d(期望 200)", env.Code)
  461. }
  462. // 重放:票据已被 GETDEL 消费,应失效
  463. env := do(fx.t, app, http.MethodPost, "/auth/issue", body, nil)
  464. if env.Code != apperrors.CodeUnauth {
  465. t.Fatalf("重放 code=%d(期望 %d 票据已消费)", env.Code, apperrors.CodeUnauth)
  466. }
  467. }
  468. // TestIssue_ScopeNotBelong 作用域不属于该账号:code 1003(越权)。
  469. func TestIssue_ScopeNotBelong(t *testing.T) {
  470. fx := newFixture(t)
  471. uid := "01GAQF0Z6C1V9Y3E5H7K2M8B4T"
  472. fx.addArgon2User(uid, "testuser", "correct-password")
  473. fx.memberships.add(uid, orgmodel.Membership{
  474. MembershipID: 1, CanonicalUserID: uid, InstitutionID: 11, CampusID: 3,
  475. Role: "teacher", Status: "active",
  476. })
  477. ticket := fx.login("testuser", "correct-password")
  478. app := fx.newApp(nil)
  479. env := do(fx.t, app, http.MethodPost, "/auth/issue",
  480. `{"loginTicket":"`+ticket+`","institutionId":99,"campusId":99}`, nil)
  481. if env.Code != apperrors.CodeForbidden {
  482. t.Fatalf("code=%d(期望 %d 作用域越权)", env.Code, apperrors.CodeForbidden)
  483. }
  484. }
  485. // TestIssue_ScopeInactive 归属已失效(inactive):code 1003。
  486. func TestIssue_ScopeInactive(t *testing.T) {
  487. fx := newFixture(t)
  488. uid := "01GAQF0Z6C1V9Y3E5H7K2M8B4T"
  489. fx.addArgon2User(uid, "testuser", "correct-password")
  490. fx.memberships.add(uid, orgmodel.Membership{
  491. MembershipID: 1, CanonicalUserID: uid, InstitutionID: 11, CampusID: 3,
  492. Role: "teacher", Status: "inactive",
  493. })
  494. ticket := fx.login("testuser", "correct-password")
  495. app := fx.newApp(nil)
  496. env := do(fx.t, app, http.MethodPost, "/auth/issue",
  497. `{"loginTicket":"`+ticket+`","institutionId":11,"campusId":3}`, nil)
  498. if env.Code != apperrors.CodeForbidden {
  499. t.Fatalf("code=%d(期望 %d 归属失效)", env.Code, apperrors.CodeForbidden)
  500. }
  501. }
  502. // TestIssue_BadParam 票据长度非 32:code 2001。
  503. func TestIssue_BadParam(t *testing.T) {
  504. fx := newFixture(t)
  505. app := fx.newApp(nil)
  506. env := do(fx.t, app, http.MethodPost, "/auth/issue",
  507. `{"loginTicket":"short","institutionId":11,"campusId":3}`, nil)
  508. if env.Code != apperrors.CodeBadParam {
  509. t.Fatalf("code=%d(期望 %d 参数校验)", env.Code, apperrors.CodeBadParam)
  510. }
  511. }
  512. // ---- Me(受保护)----
  513. // TestMe_Success 已验签 claims 注入:code 200,data 含 user + roles + 作用域 + memberships。
  514. func TestMe_Success(t *testing.T) {
  515. fx := newFixture(t)
  516. uid := "01GAQF0Z6C1V9Y3E5H7K2M8B4T"
  517. fx.addArgon2User(uid, "testuser", "correct-password")
  518. fx.memberships.add(uid, orgmodel.Membership{
  519. MembershipID: 1, CanonicalUserID: uid, InstitutionID: 11, CampusID: 3,
  520. Role: "teacher", Status: "active",
  521. })
  522. claims := &token.Claims{Sub: uid, Roles: []string{"teacher"}, InstitutionID: 11, CampusID: 3}
  523. app := fx.newApp(claims)
  524. env := do(fx.t, app, http.MethodGet, "/auth/me", "", nil)
  525. if env.Code != 200 || !env.Success {
  526. t.Fatalf("code=%d msg=%s(期望 200 成功)", env.Code, env.Message)
  527. }
  528. var me struct {
  529. ID string `json:"id"`
  530. Roles []string `json:"roles"`
  531. InstitutionID int64 `json:"institutionId"`
  532. CampusID int64 `json:"campusId"`
  533. Memberships []struct {
  534. Role string `json:"role"`
  535. } `json:"memberships"`
  536. }
  537. if err := json.Unmarshal(env.Data, &me); err != nil {
  538. t.Fatalf("解析 data 失败: %v", err)
  539. }
  540. if me.ID != uid {
  541. t.Fatalf("id=%q(期望 %q)", me.ID, uid)
  542. }
  543. if len(me.Memberships) != 1 || me.Memberships[0].Role != "teacher" {
  544. t.Fatalf("memberships=%+v(期望 1 条 teacher)", me.Memberships)
  545. }
  546. }
  547. // TestMe_Unauth 无 claims(中间件未注入):code 1001(未登录)。
  548. func TestMe_Unauth(t *testing.T) {
  549. fx := newFixture(t)
  550. fx.addArgon2User("01GAQF0Z6C1V9Y3E5H7K2M8B4T", "testuser", "correct-password")
  551. app := fx.newApp(nil) // 无 claims
  552. env := do(fx.t, app, http.MethodGet, "/auth/me", "", nil)
  553. if env.Code != apperrors.CodeUnauth {
  554. t.Fatalf("code=%d(期望 %d 未登录)", env.Code, apperrors.CodeUnauth)
  555. }
  556. }
  557. // ---- Refresh ----
  558. // TestRefresh_Success 合法 refresh:code 200,返回新 token 对。
  559. func TestRefresh_Success(t *testing.T) {
  560. fx := newFixture(t)
  561. uid := "01GAQF0Z6C1V9Y3E5H7K2M8B4T"
  562. fx.addArgon2User(uid, "testuser", "correct-password")
  563. fx.memberships.add(uid, orgmodel.Membership{
  564. MembershipID: 1, CanonicalUserID: uid, InstitutionID: 11, CampusID: 3,
  565. Role: "teacher", Status: "active",
  566. })
  567. ticket := fx.login("testuser", "correct-password")
  568. app := fx.newApp(nil)
  569. issueEnv := do(fx.t, app, http.MethodPost, "/auth/issue",
  570. `{"loginTicket":"`+ticket+`","institutionId":11,"campusId":3}`, nil)
  571. if issueEnv.Code != 200 {
  572. t.Fatalf("issue code=%d(期望 200)", issueEnv.Code)
  573. }
  574. var pair struct {
  575. AccessToken string `json:"accessToken"`
  576. RefreshToken string `json:"refreshToken"`
  577. }
  578. _ = json.Unmarshal(issueEnv.Data, &pair)
  579. // 用旧 refresh 轮换
  580. env := do(fx.t, app, http.MethodPost, "/auth/refresh",
  581. `{"refreshToken":"`+pair.RefreshToken+`"}`, nil)
  582. if env.Code != 200 {
  583. t.Fatalf("refresh code=%d msg=%s(期望 200)", env.Code, env.Message)
  584. }
  585. }
  586. // TestRefresh_Invalid 合法格式(64 hex)但不在白名单:code 1002(登录态失效,前端跳登录)。
  587. func TestRefresh_Invalid(t *testing.T) {
  588. fx := newFixture(t)
  589. app := fx.newApp(nil)
  590. env := do(fx.t, app, http.MethodPost, "/auth/refresh",
  591. `{"refreshToken":"`+strings.Repeat("0", 64)+`"}`, nil)
  592. if env.Code != apperrors.CodeTokenExpired {
  593. t.Fatalf("code=%d(期望 %d 登录态失效)", env.Code, apperrors.CodeTokenExpired)
  594. }
  595. }
  596. // TestRefresh_BadParam refresh 长度非 48:code 2001。
  597. func TestRefresh_BadParam(t *testing.T) {
  598. fx := newFixture(t)
  599. app := fx.newApp(nil)
  600. env := do(fx.t, app, http.MethodPost, "/auth/refresh", `{"refreshToken":"too-short"}`, nil)
  601. if env.Code != apperrors.CodeBadParam {
  602. t.Fatalf("code=%d(期望 %d 参数校验)", env.Code, apperrors.CodeBadParam)
  603. }
  604. }
  605. // ---- Logout(恒 200 幂等)----
  606. // TestLogout_Success 有 claims + refresh:恒 code 200。
  607. func TestLogout_Success(t *testing.T) {
  608. fx := newFixture(t)
  609. uid := "01GAQF0Z6C1V9Y3E5H7K2M8B4T"
  610. fx.addArgon2User(uid, "testuser", "correct-password")
  611. fx.memberships.add(uid, orgmodel.Membership{
  612. MembershipID: 1, CanonicalUserID: uid, InstitutionID: 11, CampusID: 3,
  613. Role: "teacher", Status: "active",
  614. })
  615. ticket := fx.login("testuser", "correct-password")
  616. app := fx.newApp(nil)
  617. issueEnv := do(fx.t, app, http.MethodPost, "/auth/issue",
  618. `{"loginTicket":"`+ticket+`","institutionId":11,"campusId":3}`, nil)
  619. var pair struct {
  620. RefreshToken string `json:"refreshToken"`
  621. }
  622. _ = json.Unmarshal(issueEnv.Data, &pair)
  623. // 带 claims 登出(模拟已验签中间件写入)
  624. claims := &token.Claims{Sub: uid, Roles: []string{"teacher"}, InstitutionID: 11, CampusID: 3, ID: "some-jti"}
  625. appAuth := fx.newApp(claims)
  626. env := do(fx.t, appAuth, http.MethodPost, "/auth/logout",
  627. `{"refreshToken":"`+pair.RefreshToken+`"}`, nil)
  628. if env.Code != 200 || !env.Success {
  629. t.Fatalf("logout code=%d(期望恒 200 幂等)", env.Code)
  630. }
  631. }
  632. // TestLogout_NoClaims 无 claims:仍恒 code 200(本地态必清)。
  633. func TestLogout_NoClaims(t *testing.T) {
  634. fx := newFixture(t)
  635. app := fx.newApp(nil)
  636. env := do(fx.t, app, http.MethodPost, "/auth/logout", `{}`, nil)
  637. if env.Code != 200 {
  638. t.Fatalf("logout code=%d(期望恒 200)", env.Code)
  639. }
  640. }
  641. // ---- 微信占位 ----
  642. // TestWechatQrcode_Placeholder 微信扫码占位:code 5001(暂未开放)。
  643. func TestWechatQrcode_Placeholder(t *testing.T) {
  644. fx := newFixture(t)
  645. app := fx.newApp(nil)
  646. env := do(fx.t, app, http.MethodGet, "/auth/wechat/qrcode", "", nil)
  647. if env.Code != apperrors.CodeInternal {
  648. t.Fatalf("code=%d(期望 %d 暂未开放)", env.Code, apperrors.CodeInternal)
  649. }
  650. }
  651. // TestWechatStatus_Placeholder 微信扫码状态占位:code 5001(暂未开放)。
  652. func TestWechatStatus_Placeholder(t *testing.T) {
  653. fx := newFixture(t)
  654. app := fx.newApp(nil)
  655. env := do(fx.t, app, http.MethodGet, "/auth/wechat/status?state=abc", "", nil)
  656. if env.Code != apperrors.CodeInternal {
  657. t.Fatalf("code=%d(期望 %d 暂未开放)", env.Code, apperrors.CodeInternal)
  658. }
  659. }
  660. // md5Hex 计算 md5 的 hex 小写串(构造 md5_salt 测试夹具用,与 credential.legacyDigest 同语义)。
  661. func md5Hex(s string) string {
  662. d := md5.Sum([]byte(s))
  663. return hex.EncodeToString(d[:])
  664. }