permissions.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. from __future__ import annotations
  2. from collections.abc import Iterable
  3. from functools import wraps
  4. from flask import current_app, g, jsonify, request
  5. from app.models.result import failed
  6. READ_GOVERNANCE = "governance:read"
  7. EDIT_GOVERNANCE = "governance:edit"
  8. APPROVE_REVIEW = "review:approve"
  9. MANAGE_USERS = "users:manage"
  10. ACTIVATE_WORKFLOW = "workflow:activate"
  11. OPERATE_ORDERS = "orders:operate"
  12. DATASOURCE_POOL_MANAGE = "datasources:pools:manage"
  13. KNOWLEDGE_MANAGE = "knowledge:manage"
  14. RULES_READ = "rules:read"
  15. RULES_EDIT = "rules:edit"
  16. RULES_PUBLISH = "rules:publish"
  17. DATAFLOW_RELEASE = "dataflows:release"
  18. DATAFLOW_DEPLOY = "dataflows:deploy"
  19. DATAFLOW_CANARY = "dataflows:canary"
  20. DATAFLOW_ACTIVATE = "dataflows:activate"
  21. DATAFLOW_ROLLBACK = "dataflows:rollback"
  22. RULES_EXECUTE = "rules:execute"
  23. ROLE_PERMISSIONS = {
  24. "viewer": frozenset({READ_GOVERNANCE, RULES_READ}),
  25. "editor": frozenset(
  26. {
  27. READ_GOVERNANCE,
  28. EDIT_GOVERNANCE,
  29. APPROVE_REVIEW,
  30. OPERATE_ORDERS,
  31. RULES_READ,
  32. RULES_EDIT,
  33. RULES_EXECUTE,
  34. }
  35. ),
  36. "admin": frozenset(
  37. {
  38. READ_GOVERNANCE,
  39. EDIT_GOVERNANCE,
  40. APPROVE_REVIEW,
  41. MANAGE_USERS,
  42. ACTIVATE_WORKFLOW,
  43. OPERATE_ORDERS,
  44. DATASOURCE_POOL_MANAGE,
  45. KNOWLEDGE_MANAGE,
  46. RULES_READ,
  47. RULES_EDIT,
  48. RULES_PUBLISH,
  49. DATAFLOW_RELEASE,
  50. DATAFLOW_DEPLOY,
  51. DATAFLOW_CANARY,
  52. DATAFLOW_ACTIVATE,
  53. DATAFLOW_ROLLBACK,
  54. RULES_EXECUTE,
  55. }
  56. ),
  57. }
  58. PUBLIC = "public"
  59. def permission_for_request(path: str, method: str) -> tuple[str, ...]:
  60. """Classify every API request in one auditable, deny-by-default policy."""
  61. method = method.upper()
  62. if path in {"/api/system/health", "/api/system/auth/login"}:
  63. return (PUBLIC,)
  64. if path in {"/api/knowledge/search", "/api/knowledge/ask"}:
  65. return (READ_GOVERNANCE,)
  66. if path.startswith("/api/rules"):
  67. if path.startswith("/api/rules/deployments"):
  68. if method == "GET":
  69. return (RULES_READ,)
  70. if path.endswith("/deploy-disabled"):
  71. return (DATAFLOW_DEPLOY,)
  72. if path.endswith("/canary"):
  73. return (DATAFLOW_CANARY, RULES_EXECUTE)
  74. if path.endswith("/activate"):
  75. return (DATAFLOW_ACTIVATE,)
  76. if path.endswith("/rollback"):
  77. return (DATAFLOW_ROLLBACK,)
  78. if path.endswith("/reconcile-deploy"):
  79. return (DATAFLOW_DEPLOY,)
  80. if path.endswith("/reconcile-activate"):
  81. return (DATAFLOW_ACTIVATE,)
  82. if path.endswith("/reconcile-rollback"):
  83. return (DATAFLOW_ROLLBACK,)
  84. if method == "POST":
  85. return (DATAFLOW_DEPLOY,)
  86. return (DATAFLOW_DEPLOY,)
  87. if method == "GET":
  88. return (RULES_READ,)
  89. if path.endswith("/publish"):
  90. return (RULES_PUBLISH,)
  91. if (
  92. path.startswith("/api/rules/production-lines/")
  93. and path.endswith("/release")
  94. ):
  95. return (DATAFLOW_RELEASE,)
  96. if path.endswith("/test") or path.endswith("/execute"):
  97. return (RULES_EXECUTE,)
  98. if method in {"POST", "PUT", "PATCH", "DELETE"}:
  99. return (RULES_EDIT,)
  100. return (RULES_PUBLISH,)
  101. if path.startswith("/api/knowledge/admin"):
  102. return (KNOWLEDGE_MANAGE,)
  103. if path.startswith("/api/system/users"):
  104. return (MANAGE_USERS,)
  105. if path.startswith("/api/system/workbench"):
  106. return (READ_GOVERNANCE,)
  107. if (
  108. path == "/api/datasource/pools"
  109. or (
  110. path.startswith("/api/datasource/")
  111. and (
  112. path.endswith("/pool")
  113. or path.endswith("/pool/invalidate")
  114. )
  115. )
  116. ):
  117. return (DATASOURCE_POOL_MANAGE,)
  118. if path == "/api/datasource/list":
  119. return (READ_GOVERNANCE,)
  120. if path.startswith("/api/system/") and not path.startswith("/api/system/auth/me"):
  121. return (MANAGE_USERS,)
  122. if path.startswith("/api/dataflow/") and any(
  123. marker in path.lower() for marker in ("activate", "publish", "execute")
  124. ):
  125. return (ACTIVATE_WORKFLOW,)
  126. if "order" in path.lower() and method != "GET":
  127. return (OPERATE_ORDERS,)
  128. if method == "GET":
  129. return (READ_GOVERNANCE,)
  130. if method in {"POST", "PUT", "PATCH", "DELETE"}:
  131. return (EDIT_GOVERNANCE,)
  132. return (MANAGE_USERS,)
  133. def permissions_for_roles(roles: Iterable[str]) -> frozenset[str]:
  134. result: set[str] = set()
  135. for role in roles:
  136. result.update(ROLE_PERMISSIONS.get(role, ()))
  137. return frozenset(result)
  138. def authenticate_request() -> dict | None:
  139. from app.core.system.auth import load_identity_from_token
  140. existing = getattr(g, "current_user", None)
  141. if existing:
  142. return existing
  143. header = request.headers.get("Authorization", "")
  144. if not header.startswith("Bearer "):
  145. return None
  146. token = header[7:].strip()
  147. if not token:
  148. return None
  149. return load_identity_from_token(token, secret=current_app.config["SECRET_KEY"])
  150. def configure_api_authorization(app) -> None:
  151. @app.before_request
  152. def enforce_api_policy():
  153. if not request.path.startswith("/api/") or request.method == "OPTIONS":
  154. return None
  155. required = permission_for_request(request.path, request.method)
  156. if required == (PUBLIC,):
  157. return None
  158. identity = authenticate_request()
  159. if identity is None:
  160. return jsonify(failed("未登录或登录已过期", code=401)), 401
  161. permissions = permissions_for_roles(identity["roles"])
  162. if not set(required).issubset(permissions):
  163. return jsonify(failed("权限不足", code=403)), 403
  164. identity["permissions"] = sorted(permissions)
  165. g.current_user = identity
  166. return None
  167. def require_permissions(*required: str):
  168. def decorator(view):
  169. @wraps(view)
  170. def wrapped(*args, **kwargs):
  171. identity = authenticate_request()
  172. if identity is None:
  173. return jsonify(failed("未登录或登录已过期", code=401)), 401
  174. permissions = permissions_for_roles(identity["roles"])
  175. if not set(required).issubset(permissions):
  176. return jsonify(failed("权限不足", code=403)), 403
  177. identity["permissions"] = sorted(permissions)
  178. g.current_user = identity
  179. return view(*args, **kwargs)
  180. wrapped.required_permissions = tuple(required)
  181. return wrapped
  182. return decorator