data-permission.integration.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
  2. import { testClient } from 'hono/testing';
  3. import { IntegrationTestDatabase, setupIntegrationDatabaseHooksWithEntities } from '@d8d/shared-test-util';
  4. import { JWTUtil } from '@d8d/shared-utils';
  5. import { z } from '@hono/zod-openapi';
  6. import { createCrudRoutes } from '../../src/routes/generic-crud.routes';
  7. import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
  8. // 测试用户实体
  9. @Entity()
  10. class TestUser {
  11. @PrimaryGeneratedColumn()
  12. id!: number;
  13. @Column('varchar')
  14. username!: string;
  15. @Column('varchar')
  16. password!: string;
  17. @Column('varchar')
  18. nickname!: string;
  19. @Column('varchar')
  20. registrationSource!: string;
  21. }
  22. // 测试实体类
  23. @Entity()
  24. class TestEntity {
  25. @PrimaryGeneratedColumn()
  26. id!: number;
  27. @Column('varchar')
  28. name!: string;
  29. @Column('int')
  30. userId!: number;
  31. @Column('int', { nullable: true })
  32. createdBy?: number;
  33. @Column('int', { nullable: true })
  34. updatedBy?: number;
  35. }
  36. // 定义测试实体的Schema
  37. const createTestSchema = z.object({
  38. name: z.string().min(1, '名称不能为空'),
  39. userId: z.number().optional()
  40. });
  41. const updateTestSchema = z.object({
  42. name: z.string().min(1, '名称不能为空').optional()
  43. });
  44. const getTestSchema = z.object({
  45. id: z.number(),
  46. name: z.string(),
  47. userId: z.number(),
  48. createdBy: z.number().nullable().optional(),
  49. updatedBy: z.number().nullable().optional()
  50. });
  51. const listTestSchema = z.object({
  52. id: z.number(),
  53. name: z.string(),
  54. userId: z.number(),
  55. createdBy: z.number().nullable().optional(),
  56. updatedBy: z.number().nullable().optional()
  57. });
  58. // 设置集成测试钩子
  59. setupIntegrationDatabaseHooksWithEntities([TestUser, TestEntity])
  60. describe('共享CRUD数据权限控制集成测试', () => {
  61. let client: any;
  62. let testToken1: string;
  63. let testToken2: string;
  64. let testUser1: TestUser;
  65. let testUser2: TestUser;
  66. let mockAuthMiddleware: any;
  67. beforeEach(async () => {
  68. // 获取数据源
  69. const dataSource = await IntegrationTestDatabase.getDataSource();
  70. // 创建测试用户1
  71. const userRepository = dataSource.getRepository(TestUser);
  72. testUser1 = userRepository.create({
  73. username: `test_user_1_${Date.now()}`,
  74. password: 'test_password',
  75. nickname: '测试用户1',
  76. registrationSource: 'web'
  77. });
  78. await userRepository.save(testUser1);
  79. // 创建测试用户2
  80. testUser2 = userRepository.create({
  81. username: `test_user_2_${Date.now()}`,
  82. password: 'test_password',
  83. nickname: '测试用户2',
  84. registrationSource: 'web'
  85. });
  86. await userRepository.save(testUser2);
  87. // 生成测试用户的token
  88. testToken1 = JWTUtil.generateToken({
  89. id: testUser1.id,
  90. username: testUser1.username,
  91. roles: [{name:'user'}]
  92. });
  93. testToken2 = JWTUtil.generateToken({
  94. id: testUser2.id,
  95. username: testUser2.username,
  96. roles: [{name:'user'}]
  97. });
  98. // 创建模拟认证中间件
  99. mockAuthMiddleware = async (c: any, next: any) => {
  100. const authHeader = c.req.header('Authorization');
  101. if (authHeader && authHeader.startsWith('Bearer ')) {
  102. const token = authHeader.substring(7);
  103. try {
  104. // 简单模拟用户解析
  105. if (token === testToken1) {
  106. c.set('user', { id: testUser1.id, username: testUser1.username });
  107. } else if (token === testToken2) {
  108. c.set('user', { id: testUser2.id, username: testUser2.username });
  109. }
  110. } catch (error) {
  111. // token解析失败
  112. }
  113. } else {
  114. // 没有认证信息,返回401
  115. return c.json({ code: 401, message: '认证失败' }, 401);
  116. }
  117. await next();
  118. };
  119. // 创建测试路由 - 启用数据权限控制
  120. const testRoutes = createCrudRoutes({
  121. entity: TestEntity,
  122. createSchema: createTestSchema,
  123. updateSchema: updateTestSchema,
  124. getSchema: getTestSchema,
  125. listSchema: listTestSchema,
  126. middleware: [mockAuthMiddleware],
  127. dataPermission: {
  128. enabled: true,
  129. userIdField: 'userId'
  130. }
  131. });
  132. client = testClient(testRoutes);
  133. });
  134. describe('GET / - 列表查询权限过滤', () => {
  135. it('应该只返回当前用户的数据', async () => {
  136. // 创建测试数据
  137. const dataSource = await IntegrationTestDatabase.getDataSource();
  138. const testRepository = dataSource.getRepository(TestEntity);
  139. // 为用户1创建数据
  140. const user1Data1 = testRepository.create({
  141. name: '用户1的数据1',
  142. userId: testUser1.id
  143. });
  144. await testRepository.save(user1Data1);
  145. const user1Data2 = testRepository.create({
  146. name: '用户1的数据2',
  147. userId: testUser1.id
  148. });
  149. await testRepository.save(user1Data2);
  150. // 为用户2创建数据
  151. const user2Data = testRepository.create({
  152. name: '用户2的数据',
  153. userId: testUser2.id
  154. });
  155. await testRepository.save(user2Data);
  156. // 用户1查询列表
  157. const response = await client.index.$get({
  158. query: {
  159. page: 1,
  160. pageSize: 10
  161. }
  162. }, {
  163. headers: {
  164. 'Authorization': `Bearer ${testToken1}`
  165. }
  166. });
  167. console.debug('列表查询响应状态:', response.status);
  168. if (response.status !== 200) {
  169. const errorData = await response.json();
  170. console.debug('列表查询错误信息:', errorData);
  171. }
  172. expect(response.status).toBe(200);
  173. if (response.status === 200) {
  174. const data = await response.json();
  175. expect(data).toHaveProperty('data');
  176. expect(Array.isArray(data.data)).toBe(true);
  177. expect(data.data).toHaveLength(2); // 应该只返回用户1的2条数据
  178. // 验证所有返回的数据都属于用户1
  179. data.data.forEach((item: any) => {
  180. expect(item.userId).toBe(testUser1.id);
  181. });
  182. }
  183. });
  184. it('应该拒绝未认证用户的访问', async () => {
  185. const response = await client.index.$get({
  186. query: {
  187. page: 1,
  188. pageSize: 10
  189. }
  190. });
  191. expect(response.status).toBe(401);
  192. });
  193. });
  194. describe('POST / - 创建操作权限验证', () => {
  195. it('应该成功创建属于当前用户的数据', async () => {
  196. const createData = {
  197. name: '测试创建数据',
  198. userId: testUser1.id // 用户ID与当前用户匹配
  199. };
  200. const response = await client.index.$post({
  201. json: createData
  202. }, {
  203. headers: {
  204. 'Authorization': `Bearer ${testToken1}`
  205. }
  206. });
  207. console.debug('创建数据响应状态:', response.status);
  208. expect(response.status).toBe(201);
  209. if (response.status === 201) {
  210. const data = await response.json();
  211. expect(data).toHaveProperty('id');
  212. expect(data.name).toBe(createData.name);
  213. expect(data.userId).toBe(testUser1.id);
  214. }
  215. });
  216. it('应该拒绝创建不属于当前用户的数据', async () => {
  217. const createData = {
  218. name: '测试创建数据',
  219. userId: testUser2.id // 用户ID与当前用户不匹配
  220. };
  221. const response = await client.index.$post({
  222. json: createData
  223. }, {
  224. headers: {
  225. 'Authorization': `Bearer ${testToken1}`
  226. }
  227. });
  228. console.debug('创建无权数据响应状态:', response.status);
  229. expect(response.status).toBe(403); // 权限验证失败返回403 Forbidden
  230. if (response.status === 403) {
  231. const data = await response.json();
  232. expect(data.message).toContain('无权');
  233. }
  234. });
  235. });
  236. describe('GET /:id - 获取详情权限验证', () => {
  237. it('应该成功获取属于当前用户的数据详情', async () => {
  238. // 先创建测试数据
  239. const dataSource = await IntegrationTestDatabase.getDataSource();
  240. const testRepository = dataSource.getRepository(TestEntity);
  241. const testData = testRepository.create({
  242. name: '测试数据详情',
  243. userId: testUser1.id
  244. });
  245. await testRepository.save(testData);
  246. const response = await client[':id'].$get({
  247. param: { id: testData.id }
  248. }, {
  249. headers: {
  250. 'Authorization': `Bearer ${testToken1}`
  251. }
  252. });
  253. console.debug('获取详情响应状态:', response.status);
  254. if (response.status !== 200) {
  255. const errorData = await response.json();
  256. console.debug('获取详情错误信息:', errorData);
  257. }
  258. expect(response.status).toBe(200);
  259. if (response.status === 200) {
  260. const data = await response.json();
  261. expect(data.id).toBe(testData.id);
  262. expect(data.name).toBe(testData.name);
  263. expect(data.userId).toBe(testUser1.id);
  264. }
  265. });
  266. it('应该拒绝获取不属于当前用户的数据详情', async () => {
  267. // 先创建属于用户2的数据
  268. const dataSource = await IntegrationTestDatabase.getDataSource();
  269. const testRepository = dataSource.getRepository(TestEntity);
  270. const testData = testRepository.create({
  271. name: '用户2的数据',
  272. userId: testUser2.id
  273. });
  274. await testRepository.save(testData);
  275. // 用户1尝试获取用户2的数据
  276. const response = await client[':id'].$get({
  277. param: { id: testData.id }
  278. }, {
  279. headers: {
  280. 'Authorization': `Bearer ${testToken1}`
  281. }
  282. });
  283. console.debug('获取无权详情响应状态:', response.status);
  284. expect(response.status).toBe(403); // 权限验证失败返回403
  285. });
  286. it('应该处理不存在的资源', async () => {
  287. const response = await client[':id'].$get({
  288. param: { id: 999999 }
  289. }, {
  290. headers: {
  291. 'Authorization': `Bearer ${testToken1}`
  292. }
  293. });
  294. expect(response.status).toBe(404);
  295. });
  296. });
  297. describe('PUT /:id - 更新操作权限验证', () => {
  298. it('应该成功更新属于当前用户的数据', async () => {
  299. // 先创建测试数据
  300. const dataSource = await IntegrationTestDatabase.getDataSource();
  301. const testRepository = dataSource.getRepository(TestEntity);
  302. const testData = testRepository.create({
  303. name: '原始数据',
  304. userId: testUser1.id
  305. });
  306. await testRepository.save(testData);
  307. const updateData = {
  308. name: '更新后的数据'
  309. };
  310. const response = await client[':id'].$put({
  311. param: { id: testData.id },
  312. json: updateData
  313. }, {
  314. headers: {
  315. 'Authorization': `Bearer ${testToken1}`
  316. }
  317. });
  318. console.debug('更新数据响应状态:', response.status);
  319. expect(response.status).toBe(200);
  320. if (response.status === 200) {
  321. const data = await response.json();
  322. expect(data.name).toBe(updateData.name);
  323. expect(data.userId).toBe(testUser1.id);
  324. }
  325. });
  326. it('应该拒绝更新不属于当前用户的数据', async () => {
  327. // 先创建属于用户2的数据
  328. const dataSource = await IntegrationTestDatabase.getDataSource();
  329. const testRepository = dataSource.getRepository(TestEntity);
  330. const testData = testRepository.create({
  331. name: '用户2的数据',
  332. userId: testUser2.id
  333. });
  334. await testRepository.save(testData);
  335. const updateData = {
  336. name: '尝试更新的数据'
  337. };
  338. // 用户1尝试更新用户2的数据
  339. const response = await client[':id'].$put({
  340. param: { id: testData.id },
  341. json: updateData
  342. }, {
  343. headers: {
  344. 'Authorization': `Bearer ${testToken1}`
  345. }
  346. });
  347. console.debug('更新无权数据响应状态:', response.status);
  348. expect(response.status).toBe(403); // 权限验证失败返回403 Forbidden
  349. if (response.status === 403) {
  350. const data = await response.json();
  351. expect(data.message).toContain('无权');
  352. }
  353. });
  354. });
  355. describe('DELETE /:id - 删除操作权限验证', () => {
  356. it('应该成功删除属于当前用户的数据', async () => {
  357. // 先创建测试数据
  358. const dataSource = await IntegrationTestDatabase.getDataSource();
  359. const testRepository = dataSource.getRepository(TestEntity);
  360. const testData = testRepository.create({
  361. name: '待删除数据',
  362. userId: testUser1.id
  363. });
  364. await testRepository.save(testData);
  365. const response = await client[':id'].$delete({
  366. param: { id: testData.id }
  367. }, {
  368. headers: {
  369. 'Authorization': `Bearer ${testToken1}`
  370. }
  371. });
  372. console.debug('删除数据响应状态:', response.status);
  373. expect(response.status).toBe(204);
  374. // 验证数据确实被删除
  375. const deletedData = await testRepository.findOne({
  376. where: { id: testData.id }
  377. });
  378. expect(deletedData).toBeNull();
  379. });
  380. it('应该拒绝删除不属于当前用户的数据', async () => {
  381. // 先创建属于用户2的数据
  382. const dataSource = await IntegrationTestDatabase.getDataSource();
  383. const testRepository = dataSource.getRepository(TestEntity);
  384. const testData = testRepository.create({
  385. name: '用户2的数据',
  386. userId: testUser2.id
  387. });
  388. await testRepository.save(testData);
  389. // 用户1尝试删除用户2的数据
  390. const response = await client[':id'].$delete({
  391. param: { id: testData.id }
  392. }, {
  393. headers: {
  394. 'Authorization': `Bearer ${testToken1}`
  395. }
  396. });
  397. console.debug('删除无权数据响应状态:', response.status);
  398. expect(response.status).toBe(403); // 权限验证失败返回403 Forbidden
  399. if (response.status === 403) {
  400. const data = await response.json();
  401. expect(data.message).toContain('无权');
  402. }
  403. // 验证数据没有被删除
  404. const existingData = await testRepository.findOne({
  405. where: { id: testData.id }
  406. });
  407. expect(existingData).not.toBeNull();
  408. });
  409. });
  410. describe('禁用数据权限控制的情况', () => {
  411. it('当数据权限控制禁用时应该允许跨用户访问', async () => {
  412. // 创建禁用数据权限控制的路由
  413. const noPermissionRoutes = createCrudRoutes({
  414. entity: TestEntity,
  415. createSchema: createTestSchema,
  416. updateSchema: updateTestSchema,
  417. getSchema: getTestSchema,
  418. listSchema: listTestSchema,
  419. middleware: [mockAuthMiddleware],
  420. dataPermission: {
  421. enabled: false, // 禁用权限控制
  422. userIdField: 'userId'
  423. }
  424. });
  425. const noPermissionClient = testClient(noPermissionRoutes);
  426. // 创建属于用户2的数据
  427. const dataSource = await IntegrationTestDatabase.getDataSource();
  428. const testRepository = dataSource.getRepository(TestEntity);
  429. const testData = testRepository.create({
  430. name: '用户2的数据',
  431. userId: testUser2.id
  432. });
  433. await testRepository.save(testData);
  434. // 用户1应该能够访问用户2的数据(权限控制已禁用)
  435. const response = await noPermissionClient[':id'].$get({
  436. param: { id: testData.id }
  437. }, {
  438. headers: {
  439. 'Authorization': `Bearer ${testToken1}`
  440. }
  441. });
  442. console.debug('禁用权限控制时的响应状态:', response.status);
  443. if (response.status !== 200) {
  444. try {
  445. const errorData = await response.json();
  446. console.debug('禁用权限控制时的错误信息:', errorData);
  447. } catch (e) {
  448. const text = await response.text();
  449. console.debug('禁用权限控制时的响应文本:', text);
  450. }
  451. }
  452. expect(response.status).toBe(200);
  453. if (response.status === 200) {
  454. const data = await response.json();
  455. expect(data.id).toBe(testData.id);
  456. expect(data.userId).toBe(testUser2.id);
  457. }
  458. });
  459. it('当不传递dataPermission配置时应该允许跨用户访问', async () => {
  460. // 创建不传递数据权限控制的路由
  461. const noPermissionRoutes = createCrudRoutes({
  462. entity: TestEntity,
  463. createSchema: createTestSchema,
  464. updateSchema: updateTestSchema,
  465. getSchema: getTestSchema,
  466. listSchema: listTestSchema,
  467. middleware: [mockAuthMiddleware]
  468. // 不传递 dataPermission 配置
  469. });
  470. const noPermissionClient = testClient(noPermissionRoutes);
  471. // 创建属于用户2的数据
  472. const dataSource = await IntegrationTestDatabase.getDataSource();
  473. const testRepository = dataSource.getRepository(TestEntity);
  474. const testData = testRepository.create({
  475. name: '用户2的数据(无权限配置)',
  476. userId: testUser2.id
  477. });
  478. await testRepository.save(testData);
  479. // 用户1应该能够访问用户2的数据(没有权限控制配置)
  480. console.debug('测试数据ID(无权限配置):', testData.id);
  481. const response = await noPermissionClient[':id'].$get({
  482. param: { id: testData.id }
  483. }, {
  484. headers: {
  485. 'Authorization': `Bearer ${testToken1}`
  486. }
  487. });
  488. console.debug('无权限配置时的响应状态:', response.status);
  489. expect(response.status).toBe(200);
  490. if (response.status === 200) {
  491. const data = await response.json();
  492. expect(data.id).toBe(testData.id);
  493. expect(data.userId).toBe(testUser2.id);
  494. }
  495. });
  496. });
  497. });