test_web_sensitive_permissions.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  1. import asyncio
  2. from pathlib import Path
  3. import pytest
  4. from fastapi import FastAPI, HTTPException
  5. from fastapi.testclient import TestClient
  6. from sqlalchemy import create_engine
  7. from sqlalchemy.orm import sessionmaker
  8. from sqlalchemy.pool import StaticPool
  9. from app.core import menu_guard
  10. from app.core.auth import get_current_user
  11. from app.core.database import get_db
  12. from app.models.base import Base
  13. from app.models.models import (
  14. SysMenu,
  15. SysPost,
  16. SysPostRole,
  17. SysRole,
  18. SysRoleMenu,
  19. SysUser,
  20. SysUserPost,
  21. SysUserRole,
  22. )
  23. PROTOCOL_LIST = "biz:cellStorageProtocol:list"
  24. PROTOCOL_AUDIT = "biz:cellStorageProtocolAudit:list"
  25. PAYMENT_CONFIRM = "biz:cellStoragePaymentConfirm:list"
  26. REFUND_CONFIRM = "biz:cellStorageRefundConfirm:list"
  27. STORAGE_CERT = "cell-storage:storage-cert:list"
  28. QC_MENUS = {"biz:qcWorkOrder:list", "biz:myQcTask:list"}
  29. def _session():
  30. engine = create_engine("sqlite:///:memory:")
  31. Base.metadata.create_all(
  32. engine,
  33. tables=[
  34. SysMenu.__table__,
  35. SysPost.__table__,
  36. SysPostRole.__table__,
  37. SysRole.__table__,
  38. SysRoleMenu.__table__,
  39. SysUser.__table__,
  40. SysUserPost.__table__,
  41. SysUserRole.__table__,
  42. ],
  43. )
  44. return sessionmaker(bind=engine)()
  45. def _thread_session():
  46. engine = create_engine(
  47. "sqlite://",
  48. connect_args={"check_same_thread": False},
  49. poolclass=StaticPool,
  50. )
  51. Base.metadata.create_all(
  52. engine,
  53. tables=[
  54. SysMenu.__table__,
  55. SysPost.__table__,
  56. SysPostRole.__table__,
  57. SysRole.__table__,
  58. SysRoleMenu.__table__,
  59. SysUser.__table__,
  60. SysUserPost.__table__,
  61. SysUserRole.__table__,
  62. ],
  63. )
  64. return sessionmaker(bind=engine)()
  65. def _add_user(db, *, user_id="u1", tenant_no="tenant-a"):
  66. db.add(
  67. SysUser(
  68. id=user_id,
  69. user_no=user_id,
  70. nick_name=user_id,
  71. password="unused",
  72. status="1",
  73. tenant_no=tenant_no,
  74. create_dept_id="",
  75. del_flag=0,
  76. )
  77. )
  78. def _add_role(db, *, role_id, tenant_no, role_name="普通角色"):
  79. db.add(
  80. SysRole(
  81. id=role_id,
  82. role_name=role_name,
  83. status="1",
  84. tenant_no=tenant_no,
  85. create_dept_id="",
  86. del_flag=0,
  87. )
  88. )
  89. def _add_menu_grant(db, *, role_id, tenant_no, code, suffix):
  90. menu_id = f"menu-{suffix}"
  91. db.add_all(
  92. [
  93. SysMenu(
  94. id=menu_id,
  95. menu_name=code,
  96. parent_id="root",
  97. menu_type="C",
  98. path=f"/{suffix}",
  99. perms=code,
  100. status="1",
  101. tenant_no=tenant_no,
  102. create_dept_id="",
  103. del_flag=0,
  104. ),
  105. SysRoleMenu(
  106. id=f"rm-{role_id}-{suffix}",
  107. role_id=role_id,
  108. menu_id=menu_id,
  109. tenant_no=tenant_no,
  110. create_dept_id="",
  111. del_flag=0,
  112. ),
  113. ]
  114. )
  115. def _bind_direct(db, *, user_id, role_id, tenant_no, suffix):
  116. db.add(
  117. SysUserRole(
  118. id=f"ur-{suffix}",
  119. user_id=user_id,
  120. role_id=role_id,
  121. tenant_no=tenant_no,
  122. create_dept_id="",
  123. del_flag=0,
  124. )
  125. )
  126. def _bind_post(db, *, user_id, role_id, tenant_no, suffix):
  127. post_id = f"post-{suffix}"
  128. db.add_all(
  129. [
  130. SysPost(
  131. id=post_id,
  132. post_name="授权职位",
  133. post_code=post_id,
  134. status="1",
  135. tenant_no=tenant_no,
  136. create_dept_id="",
  137. del_flag=0,
  138. ),
  139. SysUserPost(
  140. id=f"up-{suffix}",
  141. user_id=user_id,
  142. post_id=post_id,
  143. tenant_no=tenant_no,
  144. create_dept_id="",
  145. del_flag=0,
  146. ),
  147. SysPostRole(
  148. id=f"pr-{suffix}",
  149. post_id=post_id,
  150. role_id=role_id,
  151. tenant_no=tenant_no,
  152. create_dept_id="",
  153. del_flag=0,
  154. ),
  155. ]
  156. )
  157. def _strict_checker():
  158. checker = getattr(menu_guard, "strict_user_has_menu_perm", None)
  159. assert callable(checker), "menu_guard must expose strict_user_has_menu_perm"
  160. return checker
  161. def _strict_dependency(code):
  162. factory = getattr(menu_guard, "require_strict_menu_code", None)
  163. assert callable(factory), "menu_guard must expose require_strict_menu_code"
  164. return factory(code)
  165. def test_strict_permission_uses_direct_and_post_role_union():
  166. db = _session()
  167. _add_user(db)
  168. _add_role(db, role_id="market", tenant_no="tenant-a", role_name="市场专员")
  169. _add_role(db, role_id="finance", tenant_no="tenant-a", role_name="财务人员")
  170. _add_menu_grant(
  171. db,
  172. role_id="market",
  173. tenant_no="tenant-a",
  174. code="mini:market:specialist:payment",
  175. suffix="mini",
  176. )
  177. _add_menu_grant(
  178. db,
  179. role_id="finance",
  180. tenant_no="tenant-a",
  181. code=PAYMENT_CONFIRM,
  182. suffix="finance",
  183. )
  184. _bind_direct(
  185. db, user_id="u1", role_id="market", tenant_no="tenant-a", suffix="market"
  186. )
  187. _bind_post(
  188. db, user_id="u1", role_id="finance", tenant_no="tenant-a", suffix="finance"
  189. )
  190. db.commit()
  191. checker = _strict_checker()
  192. user = {"user_id": "u1", "tenant_no": "forged", "role": "admin"}
  193. assert checker(db, user, PAYMENT_CONFIRM)
  194. assert not checker(db, user, REFUND_CONFIRM)
  195. assert asyncio.run(_strict_dependency(PAYMENT_CONFIRM)(user=user, db=db)) is user
  196. def test_strict_permission_ignores_cross_tenant_grants():
  197. db = _session()
  198. _add_user(db, tenant_no="tenant-a")
  199. _add_role(db, role_id="market", tenant_no="tenant-a", role_name="市场专员")
  200. _bind_direct(
  201. db, user_id="u1", role_id="market", tenant_no="tenant-a", suffix="market"
  202. )
  203. _add_role(db, role_id="finance-b", tenant_no="tenant-b", role_name="财务人员")
  204. _add_menu_grant(
  205. db,
  206. role_id="finance-b",
  207. tenant_no="tenant-b",
  208. code=PAYMENT_CONFIRM,
  209. suffix="finance-b",
  210. )
  211. _bind_direct(
  212. db,
  213. user_id="u1",
  214. role_id="finance-b",
  215. tenant_no="tenant-b",
  216. suffix="finance-b",
  217. )
  218. db.commit()
  219. assert not _strict_checker()(
  220. db,
  221. {"user_id": "u1", "tenant_no": "tenant-b", "role": "super_admin"},
  222. PAYMENT_CONFIRM,
  223. )
  224. @pytest.mark.parametrize("role_name", ["超级市场专员", "超级管理员"])
  225. def test_strict_permission_rejects_privileged_role_name_without_menu(role_name):
  226. db = _session()
  227. _add_user(db)
  228. _add_role(
  229. db,
  230. role_id="super",
  231. tenant_no="tenant-a",
  232. role_name=role_name,
  233. )
  234. _bind_direct(
  235. db, user_id="u1", role_id="super", tenant_no="tenant-a", suffix="super"
  236. )
  237. db.commit()
  238. user = {"user_id": "u1", "tenant_no": "forged", "role": "admin"}
  239. assert not _strict_checker()(db, user, REFUND_CONFIRM)
  240. with pytest.raises(HTTPException) as exc_info:
  241. asyncio.run(_strict_dependency(REFUND_CONFIRM)(user=user, db=db))
  242. assert exc_info.value.status_code == 403
  243. def test_strict_permission_allows_super_admin_only_with_explicit_menu_grant():
  244. db = _session()
  245. _add_user(db)
  246. _add_role(db, role_id="super", tenant_no="tenant-a", role_name="超级管理员")
  247. _add_menu_grant(
  248. db,
  249. role_id="super",
  250. tenant_no="tenant-a",
  251. code=REFUND_CONFIRM,
  252. suffix="refund",
  253. )
  254. _bind_direct(
  255. db, user_id="u1", role_id="super", tenant_no="tenant-a", suffix="super"
  256. )
  257. db.commit()
  258. user = {"user_id": "u1", "tenant_no": "forged", "role": "super_admin"}
  259. assert _strict_checker()(db, user, REFUND_CONFIRM)
  260. assert asyncio.run(_strict_dependency(REFUND_CONFIRM)(user=user, db=db)) is user
  261. def test_strict_dependency_rejects_market_only_role():
  262. db = _session()
  263. _add_user(db)
  264. _add_role(db, role_id="market", tenant_no="tenant-a", role_name="地区经理")
  265. _add_menu_grant(
  266. db,
  267. role_id="market",
  268. tenant_no="tenant-a",
  269. code="mini:market:manager:protocol",
  270. suffix="mini",
  271. )
  272. _bind_direct(
  273. db, user_id="u1", role_id="market", tenant_no="tenant-a", suffix="market"
  274. )
  275. db.commit()
  276. with pytest.raises(HTTPException) as exc_info:
  277. asyncio.run(
  278. _strict_dependency(PROTOCOL_AUDIT)(
  279. user={"user_id": "u1", "tenant_no": "tenant-a", "role": "admin"},
  280. db=db,
  281. )
  282. )
  283. assert exc_info.value.status_code == 403
  284. def _route_strict_codes(router, endpoint_name):
  285. route = next(r for r in router.routes if r.endpoint.__name__ == endpoint_name)
  286. codes = set()
  287. for dependency in route.dependant.dependencies:
  288. codes.update(getattr(dependency.call, "strict_menu_codes", ()))
  289. return codes
  290. @pytest.mark.parametrize(
  291. ("module_name", "endpoint_names", "expected_codes"),
  292. [
  293. (
  294. "collection_protocol",
  295. [
  296. "create_collection_protocol",
  297. "update_collection_protocol",
  298. "delete_collection_protocol",
  299. ],
  300. {PROTOCOL_LIST},
  301. ),
  302. (
  303. "research_donation",
  304. [
  305. "create_research_donation",
  306. "update_research_donation",
  307. "delete_research_donation",
  308. "batch_delete_research_donations",
  309. ],
  310. {PROTOCOL_LIST},
  311. ),
  312. (
  313. "collection_protocol",
  314. ["submit_collection_protocol_audit"],
  315. {PROTOCOL_AUDIT},
  316. ),
  317. (
  318. "research_donation",
  319. [
  320. "submit_donation_audit",
  321. "change_donation_status",
  322. "convert_from_storage",
  323. "convert_to_storage",
  324. ],
  325. {PROTOCOL_AUDIT},
  326. ),
  327. (
  328. "collection_protocol",
  329. ["post_receipt_confirm", "post_receipt_reject"],
  330. {PAYMENT_CONFIRM},
  331. ),
  332. (
  333. "protocol_sample_payment",
  334. ["confirm_payment_transfer", "reject_payment_transfer"],
  335. {PAYMENT_CONFIRM},
  336. ),
  337. (
  338. "presign_order",
  339. ["confirm_presign_transfer", "reject_presign_transfer"],
  340. {PAYMENT_CONFIRM},
  341. ),
  342. (
  343. "collection_protocol",
  344. ["post_protocol_invoice_request", "complete_protocol_invoice_request"],
  345. {PAYMENT_CONFIRM},
  346. ),
  347. (
  348. "collection_protocol",
  349. [
  350. "post_submit_refund_finance",
  351. "post_submit_refund_finance_batch",
  352. "post_refund_confirm",
  353. "post_refund_reject",
  354. ],
  355. {REFUND_CONFIRM},
  356. ),
  357. (
  358. "protocol_refund_record",
  359. [
  360. "create_protocol_refund_record",
  361. "update_protocol_refund_record",
  362. "delete_protocol_refund_record",
  363. ],
  364. {REFUND_CONFIRM},
  365. ),
  366. (
  367. "collection_protocol",
  368. [
  369. "update_fullmoon_todo_insurance",
  370. "update_storage_cert_handle",
  371. "update_fullmoon_todo_handle",
  372. ],
  373. {STORAGE_CERT},
  374. ),
  375. (
  376. "sample_cert_insurance",
  377. ["put_sample_storage_cert", "put_sample_insurance"],
  378. {STORAGE_CERT},
  379. ),
  380. (
  381. "sample_storage_cert_qc",
  382. ["put_sample_storage_cert_qc"],
  383. QC_MENUS,
  384. ),
  385. ],
  386. )
  387. def test_sensitive_write_routes_declare_strict_menu_dependencies(
  388. module_name, endpoint_names, expected_codes
  389. ):
  390. module = __import__(f"app.api.{module_name}", fromlist=["router"])
  391. for endpoint_name in endpoint_names:
  392. assert _route_strict_codes(module.router, endpoint_name) == expected_codes
  393. def test_collection_protocol_write_paths_assert_sensitive_field_permissions():
  394. source = Path("app/api/collection_protocol.py").read_text()
  395. assert "assert_protocol_sensitive_fields" in source
  396. assert PROTOCOL_AUDIT in source
  397. assert STORAGE_CERT in source
  398. def test_research_donation_write_paths_assert_sensitive_field_permissions():
  399. source = Path("app/api/research_donation.py").read_text()
  400. assert "assert_donation_sensitive_fields" in source
  401. assert PROTOCOL_AUDIT in source
  402. def _permission_user(db, *codes):
  403. _add_user(db)
  404. _add_role(db, role_id="protocol", tenant_no="tenant-a", role_name="协议录入")
  405. _add_menu_grant(
  406. db,
  407. role_id="protocol",
  408. tenant_no="tenant-a",
  409. code=PROTOCOL_LIST,
  410. suffix="protocol",
  411. )
  412. _bind_direct(
  413. db,
  414. user_id="u1",
  415. role_id="protocol",
  416. tenant_no="tenant-a",
  417. suffix="protocol",
  418. )
  419. for index, code in enumerate(codes):
  420. role_id = f"extra-{index}"
  421. _add_role(db, role_id=role_id, tenant_no="tenant-a")
  422. _add_menu_grant(
  423. db,
  424. role_id=role_id,
  425. tenant_no="tenant-a",
  426. code=code,
  427. suffix=role_id,
  428. )
  429. _bind_direct(
  430. db,
  431. user_id="u1",
  432. role_id=role_id,
  433. tenant_no="tenant-a",
  434. suffix=role_id,
  435. )
  436. db.commit()
  437. return {"user_id": "u1", "tenant_no": "tenant-a", "role": "admin"}
  438. def test_protocol_sensitive_fields_require_dedicated_permissions():
  439. from app.api.collection_protocol import (
  440. ProtocolCreateBody,
  441. ProtocolUpdateBody,
  442. assert_protocol_sensitive_fields,
  443. )
  444. db = _session()
  445. user = _permission_user(db)
  446. assert_protocol_sensitive_fields(db, user, ProtocolCreateBody(), creating=True)
  447. with pytest.raises(HTTPException) as status_error:
  448. assert_protocol_sensitive_fields(
  449. db,
  450. user,
  451. ProtocolCreateBody(protocolStatus="sxz"),
  452. creating=True,
  453. )
  454. assert status_error.value.status_code == 403
  455. with pytest.raises(HTTPException) as storage_error:
  456. assert_protocol_sensitive_fields(
  457. db,
  458. user,
  459. ProtocolUpdateBody(storageCert={}),
  460. creating=False,
  461. )
  462. assert storage_error.value.status_code == 403
  463. def test_protocol_sensitive_fields_allow_union_of_dedicated_permissions():
  464. from app.api.collection_protocol import (
  465. ProtocolUpdateBody,
  466. assert_protocol_sensitive_fields,
  467. )
  468. db = _session()
  469. user = _permission_user(db, PROTOCOL_AUDIT, STORAGE_CERT)
  470. assert_protocol_sensitive_fields(
  471. db,
  472. user,
  473. ProtocolUpdateBody(protocolStatus="sxz", storageCert={}),
  474. creating=False,
  475. )
  476. def test_donation_sensitive_fields_require_audit_permission():
  477. from app.api.research_donation import (
  478. DonationCreateBody,
  479. DonationUpdateBody,
  480. assert_donation_sensitive_fields,
  481. )
  482. db = _session()
  483. user = _permission_user(db)
  484. assert_donation_sensitive_fields(db, user, DonationCreateBody(), creating=True)
  485. for body, creating in (
  486. (DonationCreateBody(donationStatus="sxz"), True),
  487. (DonationCreateBody(sourceType="cell_storage"), True),
  488. (DonationUpdateBody(sourceProtocolId="p1"), False),
  489. ):
  490. with pytest.raises(HTTPException) as exc_info:
  491. assert_donation_sensitive_fields(db, user, body, creating=creating)
  492. assert exc_info.value.status_code == 403
  493. def test_market_only_user_is_stopped_before_sensitive_crud(monkeypatch):
  494. from app.api import (
  495. collection_protocol,
  496. protocol_refund_record,
  497. protocol_sample_payment,
  498. sample_cert_insurance,
  499. sample_storage_cert_qc,
  500. )
  501. db = _thread_session()
  502. _add_user(db)
  503. _add_role(db, role_id="market", tenant_no="tenant-a", role_name="市场专员")
  504. _add_menu_grant(
  505. db,
  506. role_id="market",
  507. tenant_no="tenant-a",
  508. code="mini:market:specialist:protocol",
  509. suffix="mini-protocol",
  510. )
  511. _bind_direct(
  512. db, user_id="u1", role_id="market", tenant_no="tenant-a", suffix="market"
  513. )
  514. db.commit()
  515. called = []
  516. def forbidden_call(*args, **kwargs):
  517. called.append((args, kwargs))
  518. raise AssertionError("sensitive CRUD must not be called")
  519. monkeypatch.setattr(
  520. collection_protocol.cp_svc, "create_collection_protocol", forbidden_call
  521. )
  522. monkeypatch.setattr(collection_protocol.cp_svc, "create_audit", forbidden_call)
  523. monkeypatch.setattr(
  524. protocol_sample_payment.psp_svc, "confirm_receipt", forbidden_call
  525. )
  526. monkeypatch.setattr(
  527. protocol_refund_record.rr_svc, "create_refund_record", forbidden_call
  528. )
  529. monkeypatch.setattr(
  530. sample_cert_insurance.cert_crud, "upsert_handle", forbidden_call
  531. )
  532. monkeypatch.setattr(sample_storage_cert_qc.svc, "upsert", forbidden_call)
  533. app = FastAPI()
  534. for router in (
  535. collection_protocol.router,
  536. protocol_sample_payment.router,
  537. protocol_refund_record.router,
  538. sample_cert_insurance.router,
  539. sample_storage_cert_qc.router,
  540. ):
  541. app.include_router(router)
  542. user = {"user_id": "u1", "tenant_no": "tenant-a", "role": "admin"}
  543. def override_db():
  544. yield db
  545. app.dependency_overrides[get_current_user] = lambda: user
  546. app.dependency_overrides[get_db] = override_db
  547. requests = [
  548. ("post", "/web/admin/collection-protocols", {}),
  549. (
  550. "post",
  551. "/web/admin/collection-protocols/p1/audit",
  552. {"auditStatus": "tg"},
  553. ),
  554. ("post", "/web/admin/payment-transfers/t1/receipt-confirm", {}),
  555. (
  556. "post",
  557. "/web/admin/collection-protocols/p1/refund-records",
  558. {"refundAmount": 1},
  559. ),
  560. ("put", "/web/admin/sample-storage-certs/S1", {}),
  561. ("put", "/web/admin/sample-storage-cert-qc/S1", {"payload": {}}),
  562. ]
  563. client = TestClient(app)
  564. for method, url, body in requests:
  565. response = client.request(method, url, json=body)
  566. assert response.status_code == 403, (method, url, response.text)
  567. assert called == []
  568. @pytest.mark.parametrize("kind", ["storage_cert", "insurance", "all"])
  569. def test_market_only_user_cannot_use_sensitive_quick_register_branches(
  570. monkeypatch, kind
  571. ):
  572. from app.api import protocol_sample_collection
  573. db = _session()
  574. user = _permission_user(db)
  575. called = []
  576. def forbidden_call(*args, **kwargs):
  577. called.append((args, kwargs))
  578. return {"success": 1, "fail": 0}
  579. monkeypatch.setattr(
  580. protocol_sample_collection.quick_svc,
  581. "batch_handle_storage_certs",
  582. forbidden_call,
  583. )
  584. monkeypatch.setattr(
  585. protocol_sample_collection.quick_svc,
  586. "batch_handle_insurance",
  587. forbidden_call,
  588. )
  589. body = protocol_sample_collection.QuickRegisterBody(
  590. kind=kind,
  591. receptionSource="cell_storage",
  592. items=[{"sampleCode": "S1", "protocolId": "P1"}],
  593. handleTime="2026-10-14 10:00:00",
  594. )
  595. with pytest.raises(HTTPException) as exc_info:
  596. asyncio.run(
  597. protocol_sample_collection.quick_register_sample_info(
  598. body=body,
  599. db=db,
  600. user=user,
  601. )
  602. )
  603. assert exc_info.value.status_code == 403
  604. assert called == []
  605. @pytest.mark.parametrize(
  606. "payment_detail",
  607. [
  608. {"installmentNo": 1, "payStatus": "yjf"},
  609. {"installmentNo": 1, "PayStatus": "yjf"},
  610. {"installmentNo": 1, "financeConfirmAttachments": "secret.pdf"},
  611. {
  612. "installmentNo": 1,
  613. "financeConfirmAttachmentFiles": [{"url": "secret.pdf"}],
  614. },
  615. {"installmentNo": 1, "financeRemark": "confirmed"},
  616. {"installmentNo": 1, "refundAmount": 100},
  617. {"installmentNo": 1, "refundRemark": "refund"},
  618. {"installmentNo": 1, "refundAttachments": "refund.pdf"},
  619. {
  620. "installmentNo": 1,
  621. "refundAttachmentFiles": [{"url": "refund.pdf"}],
  622. },
  623. {
  624. "installmentNo": 1,
  625. "refundFinanceConfirmAttachments": "finance.pdf",
  626. },
  627. {
  628. "installmentNo": 1,
  629. "refundFinanceConfirmAttachmentFiles": [{"url": "finance.pdf"}],
  630. },
  631. {"installmentNo": 1, "refundFinanceRemark": "confirmed"},
  632. ],
  633. )
  634. def test_protocol_create_rejects_nested_finance_and_refund_fields_before_crud(
  635. monkeypatch, payment_detail
  636. ):
  637. from app.api import collection_protocol
  638. called = []
  639. def forbidden_call(*args, **kwargs):
  640. called.append((args, kwargs))
  641. raise AssertionError("protocol CRUD must not be called")
  642. monkeypatch.setattr(
  643. collection_protocol.cp_svc,
  644. "create_collection_protocol",
  645. forbidden_call,
  646. )
  647. body = collection_protocol.ProtocolCreateBody(
  648. paymentModelVersion=1,
  649. paymentDetails=[payment_detail],
  650. )
  651. with pytest.raises(HTTPException) as exc_info:
  652. asyncio.run(
  653. collection_protocol.create_collection_protocol(
  654. body=body,
  655. user={"user_id": "u1", "role": "admin"},
  656. db=None,
  657. )
  658. )
  659. assert exc_info.value.status_code == 400
  660. assert called == []
  661. def test_protocol_update_rejects_snake_case_nested_sensitive_fields_before_crud(
  662. monkeypatch,
  663. ):
  664. from app.api import collection_protocol
  665. called = []
  666. def forbidden_call(*args, **kwargs):
  667. called.append((args, kwargs))
  668. raise AssertionError("protocol CRUD must not be called")
  669. monkeypatch.setattr(
  670. collection_protocol.cp_svc,
  671. "update_collection_protocol",
  672. forbidden_call,
  673. )
  674. body = collection_protocol.ProtocolUpdateBody(
  675. payment_details=[
  676. {
  677. "installment_no": 1,
  678. "finance_confirm_attachment_files": [{"url": "secret.pdf"}],
  679. }
  680. ]
  681. )
  682. with pytest.raises(HTTPException) as exc_info:
  683. asyncio.run(
  684. collection_protocol.update_collection_protocol(
  685. protocol_id="p1",
  686. body=body,
  687. user={"user_id": "u1", "role": "admin"},
  688. db=None,
  689. )
  690. )
  691. assert exc_info.value.status_code == 400
  692. assert called == []
  693. def test_payment_detail_sensitive_field_inventory_matches_crud_write_fields():
  694. from app.api.collection_protocol import _PAYMENT_DETAIL_SENSITIVE_FIELDS
  695. assert _PAYMENT_DETAIL_SENSITIVE_FIELDS == {
  696. "pay_status",
  697. "payStatus",
  698. "finance_confirm_attachments",
  699. "financeConfirmAttachments",
  700. "finance_confirm_attachment_files",
  701. "financeConfirmAttachmentFiles",
  702. "finance_remark",
  703. "financeRemark",
  704. "refund_amount",
  705. "refundAmount",
  706. "refund_remark",
  707. "refundRemark",
  708. "refund_attachments",
  709. "refundAttachments",
  710. "refund_attachment_files",
  711. "refundAttachmentFiles",
  712. "refund_finance_confirm_attachments",
  713. "refundFinanceConfirmAttachments",
  714. "refund_finance_confirm_attachment_files",
  715. "refundFinanceConfirmAttachmentFiles",
  716. "refund_finance_remark",
  717. "refundFinanceRemark",
  718. }