org_e2e_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. // org 域越权端到端测试(T6 验收核心:跨校区/跨机构访问被拒)。
  2. //
  3. // 用真 GORM 仓储 + 真 Issuer + miniredis + NewAuth 验签中间件,走 HTTP 全链路,
  4. // 同时覆盖多租户防线的**两道**(架构规格 §3.5):
  5. // 1. Service 层 assertInScope(显式 1004):请求 query 显式携带的 institutionId/campusId
  6. // 与 token 作用域冲突 → code 1004(前端据此校正 scope);
  7. // 2. Repository 层 Scoping(数据层强制过滤):即便请求不带显式 id,查询也强制带
  8. // institution_id/campus_id 过滤——非超管永远查不到别家机构/别校校区的数据。
  9. //
  10. // 场景矩阵:
  11. // - 老师(inst=11, campus=3,校区锁定):
  12. // GET /org/institutions → 只见机构 11(机构 22 被 Scoping 排除,数据层)
  13. // GET /org/campuses → 只见校区 3(校区 4 被机构+校区双重 scoping 排除)
  14. // GET /org/institutions?institutionId=22 → 1004(跨机构,Service 显式)
  15. // GET /org/campuses?campusId=4 → 1004(跨校区,Service 显式)
  16. // GET /org/institutions/22 → 1004(跨机构单查,Service 显式)
  17. // - 平台超管(super_admin):GET /org/institutions → 见全部机构(11 + 22)
  18. // - 无 token:/org/* → 1001(中间件未登录)
  19. //
  20. // 运行前提(同身份域 e2e 纪律:DSN 走环境变量,不入库):
  21. //
  22. // set UNIFIED_TEST_DSN=dev:xxxx@tcp(127.0.0.1:3306)/e2e_test?charset=utf8mb4&parseTime=True&loc=Local
  23. // go test ./internal/org/handler/ -run TestOrgE2E -v
  24. //
  25. // 未设置 UNIFIED_TEST_DSN 时自动跳过(CI / 无库环境 go test ./... 不受影响)。
  26. package handler
  27. import (
  28. "context"
  29. "crypto/rand"
  30. "crypto/rsa"
  31. "crypto/x509"
  32. "encoding/json"
  33. "encoding/pem"
  34. "net/http"
  35. "net/http/httptest"
  36. "os"
  37. "testing"
  38. "time"
  39. miniredis "github.com/alicebob/miniredis/v2"
  40. "github.com/gofiber/fiber/v2"
  41. "gorm.io/gorm"
  42. idhandler "yuansiwei/unified-backend/internal/identity/handler"
  43. "yuansiwei/unified-backend/internal/identity/token"
  44. "yuansiwei/unified-backend/internal/infra/config"
  45. infra "yuansiwei/unified-backend/internal/infra/db"
  46. appredis "yuansiwei/unified-backend/internal/infra/redis"
  47. "yuansiwei/unified-backend/internal/org/model"
  48. orgservice "yuansiwei/unified-backend/internal/org/service"
  49. )
  50. // orgEnv 端到端测试句柄(真库 + 真仓储 + miniredis + 真 Issuer + 验签中间件 + /org 路由)。
  51. type orgEnv struct {
  52. t *testing.T
  53. app *fiber.App
  54. pubKeys []string
  55. revocation *appredis.RevocationStore
  56. gdb *gorm.DB
  57. issuer *token.Issuer
  58. }
  59. // orgE2eSetup 建真库 + AutoMigrate(t_institution/t_campus) + miniredis + 真 Issuer + OrgService + /org 路由。
  60. func orgE2eSetup(t *testing.T) *orgEnv {
  61. t.Helper()
  62. dsn := os.Getenv("UNIFIED_TEST_DSN")
  63. if dsn == "" {
  64. t.Skip("未设置 UNIFIED_TEST_DSN,跳过 org 越权端到端测试")
  65. }
  66. gdb, err := infra.NewDB(config.DBCfg{DSN: dsn, MaxOpenConns: 5, MaxIdleConns: 2, ConnMaxLifetimeSec: 60})
  67. if err != nil {
  68. t.Fatalf("NewDB: %v", err)
  69. }
  70. t.Cleanup(func() { _ = infra.Close(gdb) })
  71. if err := infra.Migrate(gdb, &model.Institution{}, &model.Campus{}); err != nil {
  72. t.Fatalf("Migrate: %v", err)
  73. }
  74. t.Cleanup(func() { _ = gdb.Migrator().DropTable("t_institution", "t_campus") })
  75. mr, err := miniredis.Run()
  76. if err != nil {
  77. t.Fatalf("miniredis.Run: %v", err)
  78. }
  79. t.Cleanup(mr.Close)
  80. rc, err := appredis.NewClient(config.RedisCfg{Addr: mr.Addr()})
  81. if err != nil {
  82. t.Fatalf("NewClient: %v", err)
  83. }
  84. t.Cleanup(func() { _ = rc.Close() })
  85. refreshStore := appredis.NewRefreshStore(rc)
  86. revocation := appredis.NewRevocationStore(rc, "revoked")
  87. privPEM, pubKeys := genOrgRSAKey(t)
  88. issuer, err := token.NewIssuer(privPEM, "https://unified.test", 30*time.Minute, 30*24*time.Hour, refreshStore, revocation)
  89. if err != nil {
  90. t.Fatalf("NewIssuer: %v", err)
  91. }
  92. svc, err := orgservice.NewOrgService(gdb)
  93. if err != nil {
  94. t.Fatalf("NewOrgService: %v", err)
  95. }
  96. h, err := New(Config{Svc: svc})
  97. if err != nil {
  98. t.Fatalf("org handler New: %v", err)
  99. }
  100. mw, err := idhandler.NewAuth(idhandler.AuthConfig{PublicKeys: pubKeys, Revocation: revocation, Issuer: "https://unified.test"})
  101. if err != nil {
  102. t.Fatalf("NewAuth: %v", err)
  103. }
  104. app := fiber.New(fiber.Config{DisableStartupMessage: true})
  105. org := app.Group("/org")
  106. org.Use(mw)
  107. org.Get("/institutions", h.Institutions)
  108. org.Get("/institutions/:institutionId", h.Institution)
  109. org.Get("/campuses", h.Campuses)
  110. org.Get("/campuses/:campusId", h.Campus)
  111. return &orgEnv{t: t, app: app, pubKeys: pubKeys, revocation: revocation, gdb: gdb, issuer: issuer}
  112. }
  113. // genOrgRSAKey 生成 RS2048 私钥 + 公钥 PEM(本包私有,避免与身份域测试 helper 重名冲突)。
  114. func genOrgRSAKey(t *testing.T) (string, []string) {
  115. t.Helper()
  116. key, err := rsa.GenerateKey(rand.Reader, 2048)
  117. if err != nil {
  118. t.Fatalf("生成 RSA 私钥: %v", err)
  119. }
  120. privPEM := string(pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}))
  121. pubDER, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
  122. if err != nil {
  123. t.Fatalf("序列化公钥: %v", err)
  124. }
  125. pubPEM := string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: pubDER}))
  126. return privPEM, []string{pubPEM}
  127. }
  128. // issue 用真 Issuer 签一个 access(指定作用域 claims)。
  129. func (e *orgEnv) issue(claims token.Claims) string {
  130. e.t.Helper()
  131. access, _, err := e.issuer.Issue(context.Background(), claims)
  132. if err != nil {
  133. e.t.Fatalf("Issue: %v", err)
  134. }
  135. return access
  136. }
  137. // seedOrg 落两所机构 + 两校区(inst11/campus3、inst22/campus4,raw SQL 保证 id 确定)。
  138. func (e *orgEnv) seedOrg() {
  139. e.t.Helper()
  140. ctx := context.Background()
  141. now := time.Now()
  142. must := func(err error, what string) {
  143. if err != nil {
  144. e.t.Fatalf("%s: %v", what, err)
  145. }
  146. }
  147. must(e.gdb.WithContext(ctx).Create(&model.Institution{
  148. InstitutionID: 11, InstitutionName: "实验一中", Status: model.StatusActive, CreatedAt: now, UpdatedAt: now,
  149. }).Error, "插入机构 11")
  150. must(e.gdb.WithContext(ctx).Create(&model.Institution{
  151. InstitutionID: 22, InstitutionName: "实验二中", Status: model.StatusActive, CreatedAt: now, UpdatedAt: now,
  152. }).Error, "插入机构 22")
  153. must(e.gdb.WithContext(ctx).Create(&model.Campus{
  154. CampusID: 3, InstitutionID: 11, CampusName: "一中本部", Status: model.StatusActive, CreatedAt: now, UpdatedAt: now,
  155. }).Error, "插入校区 3")
  156. must(e.gdb.WithContext(ctx).Create(&model.Campus{
  157. CampusID: 4, InstitutionID: 22, CampusName: "二中本部", Status: model.StatusActive, CreatedAt: now, UpdatedAt: now,
  158. }).Error, "插入校区 4")
  159. }
  160. // orgEnv envelope(统一信封;Data 留原始 JSON 供按需解析)。
  161. type env struct {
  162. Code int `json:"code"`
  163. Message string `json:"message"`
  164. Data json.RawMessage `json:"data"`
  165. Success bool `json:"success"`
  166. }
  167. // get 带 Bearer 头 GET 并解信封(HTTP 恒 200,断 body.code)。
  168. func (e *orgEnv) get(path, bearer string) *env {
  169. e.t.Helper()
  170. req := httptest.NewRequest(http.MethodGet, path, nil)
  171. if bearer != "" {
  172. req.Header.Set("Authorization", "Bearer "+bearer)
  173. }
  174. resp, err := e.app.Test(req, -1)
  175. if err != nil {
  176. e.t.Fatalf("GET %s 请求失败: %v", path, err)
  177. }
  178. var en env
  179. if err := json.NewDecoder(resp.Body).Decode(&en); err != nil {
  180. e.t.Fatalf("GET %s 解析响应: %v", path, err)
  181. }
  182. return &en
  183. }
  184. // instList 从 PageData 解机构列表(institutionId 集合)。
  185. func instList(t *testing.T, data json.RawMessage) []int64 {
  186. t.Helper()
  187. var pd struct {
  188. List []struct {
  189. InstitutionID int64 `json:"institutionId"`
  190. } `json:"list"`
  191. Total int64 `json:"total"`
  192. }
  193. if err := json.Unmarshal(data, &pd); err != nil {
  194. t.Fatalf("解析机构 PageData: %v", err)
  195. }
  196. out := make([]int64, 0, len(pd.List))
  197. for _, it := range pd.List {
  198. out = append(out, it.InstitutionID)
  199. }
  200. return out
  201. }
  202. // TestOrgE2E_CampusLocked 老师(校区锁定 inst=11/campus=3):
  203. // 数据层 Scoping 只给本机构机构 + 本校区;显式跨机构/跨校区 id → 1004。
  204. func TestOrgE2E_CampusLocked(t *testing.T) {
  205. e := orgE2eSetup(t)
  206. e.seedOrg()
  207. teacher := e.issue(token.Claims{
  208. Sub: "01GAQF0Z6C1V9Y3E5H7K2M8B4T", Roles: []string{"teacher"}, InstitutionID: 11, CampusID: 3,
  209. })
  210. // 数据层:机构列表只见本机构(11),机构 22 被 Scoping 排除
  211. inst := e.get("/org/institutions", teacher)
  212. if inst.Code != 200 {
  213. t.Fatalf("机构列表 code=%d msg=%s(期望 200)", inst.Code, inst.Message)
  214. }
  215. got := instList(t, inst.Data)
  216. if len(got) != 1 || got[0] != 11 {
  217. t.Fatalf("机构列表=%v(期望仅 [11],机构 22 须被 scoping 排除)", got)
  218. }
  219. // 数据层:校区列表只见本校区(3),校区 4(别家机构+别校)被双重 scoping 排除
  220. camp := e.get("/org/campuses", teacher)
  221. if camp.Code != 200 {
  222. t.Fatalf("校区列表 code=%d msg=%s(期望 200)", camp.Code, camp.Message)
  223. }
  224. var cpd struct {
  225. List []struct {
  226. CampusID int64 `json:"campusId"`
  227. InstitutionID int64 `json:"institutionId"`
  228. } `json:"list"`
  229. }
  230. if err := json.Unmarshal(camp.Data, &cpd); err != nil {
  231. t.Fatalf("解析校区 PageData: %v", err)
  232. }
  233. if len(cpd.List) != 1 || cpd.List[0].CampusID != 3 {
  234. t.Fatalf("校区列表=%+v(期望仅 [campus 3])", cpd.List)
  235. }
  236. // Service 显式 1004:跨机构 institutionId=22
  237. if r := e.get("/org/institutions?institutionId=22", teacher); r.Code != 1004 {
  238. t.Fatalf("跨机构机构列表 code=%d(期望 1004 作用域越界)", r.Code)
  239. }
  240. // Service 显式 1004:跨校区 campusId=4(校区锁定 token)
  241. if r := e.get("/org/campuses?campusId=4", teacher); r.Code != 1004 {
  242. t.Fatalf("跨校区校区列表 code=%d(期望 1004 作用域越界)", r.Code)
  243. }
  244. // Service 显式 1004:跨机构单查
  245. if r := e.get("/org/institutions/22", teacher); r.Code != 1004 {
  246. t.Fatalf("跨机构单查 code=%d(期望 1004)", r.Code)
  247. }
  248. }
  249. // TestOrgE2E_SuperAdmin 平台超管:跨机构可见全部机构(Scoping 跳过机构过滤)。
  250. func TestOrgE2E_SuperAdmin(t *testing.T) {
  251. e := orgE2eSetup(t)
  252. e.seedOrg()
  253. super := e.issue(token.Claims{
  254. Sub: "01GAQF0Z6C1V9Y3E5H7K2M8B4T", Roles: []string{"super_admin"}, InstitutionID: 0, CampusID: 0,
  255. })
  256. inst := e.get("/org/institutions", super)
  257. if inst.Code != 200 {
  258. t.Fatalf("超管机构列表 code=%d msg=%s(期望 200)", inst.Code, inst.Message)
  259. }
  260. got := instList(t, inst.Data)
  261. // 超管不加作用域:应见两所机构(11 + 22)
  262. seen := map[int64]bool{}
  263. for _, v := range got {
  264. seen[v] = true
  265. }
  266. if len(got) != 2 || !seen[11] || !seen[22] {
  267. t.Fatalf("超管机构列表=%v(期望 [11 22] 全见)", got)
  268. }
  269. }
  270. // TestOrgE2E_Unauth 无 token:/org/* 一律 1001(中间件未登录拦截)。
  271. func TestOrgE2E_Unauth(t *testing.T) {
  272. e := orgE2eSetup(t)
  273. e.seedOrg()
  274. for _, path := range []string{"/org/institutions", "/org/campuses", "/org/institutions/11"} {
  275. if r := e.get(path, ""); r.Code != 1001 {
  276. t.Fatalf("%s 无 token code=%d(期望 1001 未登录)", path, r.Code)
  277. }
  278. }
  279. }
  280. // TestOrgE2E_ScopeMissingID 老师不带任何显式 id:仍只返回本机构/本校区(Scoping 兜底,非裸查)。
  281. func TestOrgE2E_ScopeMissingID(t *testing.T) {
  282. e := orgE2eSetup(t)
  283. e.seedOrg()
  284. teacher := e.issue(token.Claims{
  285. Sub: "01GAQF0Z6C1V9Y3E5H7K2M8B4T", Roles: []string{"teacher"}, InstitutionID: 11, CampusID: 3,
  286. })
  287. // 不带 institutionId/campusId:数据层 scoping 仍强制 inst=11 + campus=3
  288. inst := e.get("/org/institutions", teacher)
  289. if inst.Code != 200 {
  290. t.Fatalf("code=%d(期望 200)", inst.Code)
  291. }
  292. got := instList(t, inst.Data)
  293. if len(got) != 1 || got[0] != 11 {
  294. t.Fatalf("缺 id 时机构列表=%v(期望仅 [11],scoping 兜底)", got)
  295. }
  296. // 带别家机构 id 但角色是机构级(教务):campus=0 可下钻,但跨机构仍 1004
  297. academic := e.issue(token.Claims{
  298. Sub: "01GAQF0Z6C1V9Y3E5H7K2M8B4T", Roles: []string{"academic"}, InstitutionID: 11, CampusID: 0,
  299. })
  300. if r := e.get("/org/institutions?institutionId=22", academic); r.Code != 1004 {
  301. t.Fatalf("教务跨机构 code=%d(期望 1004)", r.Code)
  302. }
  303. }