10xgraph-api 0.7.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (203) hide show
  1. 10xgraph_api-0.7.0.dist-info/METADATA +618 -0
  2. 10xgraph_api-0.7.0.dist-info/RECORD +203 -0
  3. 10xgraph_api-0.7.0.dist-info/WHEEL +5 -0
  4. 10xgraph_api-0.7.0.dist-info/entry_points.txt +3 -0
  5. 10xgraph_api-0.7.0.dist-info/licenses/LICENSE +21 -0
  6. 10xgraph_api-0.7.0.dist-info/top_level.txt +2 -0
  7. agentflow_cli/__init__.py +69 -0
  8. tenxgraph_api/__init__.py +23 -0
  9. tenxgraph_api/cli/__init__.py +6 -0
  10. tenxgraph_api/cli/capabilities.py +127 -0
  11. tenxgraph_api/cli/commands/__init__.py +49 -0
  12. tenxgraph_api/cli/commands/api.py +262 -0
  13. tenxgraph_api/cli/commands/audit.py +213 -0
  14. tenxgraph_api/cli/commands/build.py +305 -0
  15. tenxgraph_api/cli/commands/config.py +71 -0
  16. tenxgraph_api/cli/commands/demo.py +93 -0
  17. tenxgraph_api/cli/commands/eval.py +909 -0
  18. tenxgraph_api/cli/commands/init.py +531 -0
  19. tenxgraph_api/cli/commands/skills.py +532 -0
  20. tenxgraph_api/cli/commands/test.py +113 -0
  21. tenxgraph_api/cli/commands/version.py +47 -0
  22. tenxgraph_api/cli/config_editor/__init__.py +15 -0
  23. tenxgraph_api/cli/config_editor/schema.py +566 -0
  24. tenxgraph_api/cli/config_editor/server.py +240 -0
  25. tenxgraph_api/cli/config_editor/static/app.css +2 -0
  26. tenxgraph_api/cli/config_editor/static/app.js +3 -0
  27. tenxgraph_api/cli/config_editor/static/favicon.svg +11 -0
  28. tenxgraph_api/cli/config_editor/static/index.html +20 -0
  29. tenxgraph_api/cli/config_editor/store.py +120 -0
  30. tenxgraph_api/cli/config_editor/validation.py +377 -0
  31. tenxgraph_api/cli/constants.py +112 -0
  32. tenxgraph_api/cli/context.py +46 -0
  33. tenxgraph_api/cli/core/__init__.py +0 -0
  34. tenxgraph_api/cli/core/animations.py +550 -0
  35. tenxgraph_api/cli/core/config.py +279 -0
  36. tenxgraph_api/cli/core/output.py +625 -0
  37. tenxgraph_api/cli/core/prompts.py +220 -0
  38. tenxgraph_api/cli/core/screen.py +287 -0
  39. tenxgraph_api/cli/core/steps.py +621 -0
  40. tenxgraph_api/cli/core/theme.py +242 -0
  41. tenxgraph_api/cli/core/validation.py +251 -0
  42. tenxgraph_api/cli/exceptions.py +129 -0
  43. tenxgraph_api/cli/logger.py +84 -0
  44. tenxgraph_api/cli/main.py +936 -0
  45. tenxgraph_api/cli/templates/__init__.py +0 -0
  46. tenxgraph_api/cli/templates/defaults.py +844 -0
  47. tenxgraph_api/cli/templates/dev/.env.example +1 -0
  48. tenxgraph_api/cli/templates/dev/10xgraph.json +16 -0
  49. tenxgraph_api/cli/templates/dev/graph/__init__.py +0 -0
  50. tenxgraph_api/cli/templates/dev/graph/agent.py +63 -0
  51. tenxgraph_api/cli/templates/prod/.env.example +75 -0
  52. tenxgraph_api/cli/templates/prod/.pre-commit-config.yaml +50 -0
  53. tenxgraph_api/cli/templates/prod/.python-version +1 -0
  54. tenxgraph_api/cli/templates/prod/10xgraph.json +42 -0
  55. tenxgraph_api/cli/templates/prod/auth/__init__.py +0 -0
  56. tenxgraph_api/cli/templates/prod/auth/agent_auth.py +46 -0
  57. tenxgraph_api/cli/templates/prod/evals/__init__.py +0 -0
  58. tenxgraph_api/cli/templates/prod/evals/user_simulator_eval.py +76 -0
  59. tenxgraph_api/cli/templates/prod/evals/weather_agents_eval.py +53 -0
  60. tenxgraph_api/cli/templates/prod/graph/__init__.py +0 -0
  61. tenxgraph_api/cli/templates/prod/graph/agent.py +50 -0
  62. tenxgraph_api/cli/templates/prod/graph/state.py +5 -0
  63. tenxgraph_api/cli/templates/prod/graph/thread_name_generator.py +7 -0
  64. tenxgraph_api/cli/templates/prod/graph/tools/__init__.py +0 -0
  65. tenxgraph_api/cli/templates/prod/graph/tools/weather_tool.py +43 -0
  66. tenxgraph_api/cli/templates/prod/graph/validators/__init__.py +0 -0
  67. tenxgraph_api/cli/templates/prod/graph/validators/lifecyle.py +107 -0
  68. tenxgraph_api/cli/templates/prod/graph/validators/manager.py +9 -0
  69. tenxgraph_api/cli/templates/prod/graph/validators/validators.py +21 -0
  70. tenxgraph_api/cli/templates/prod/pyproject.toml +79 -0
  71. tenxgraph_api/cli/templates/prod/tests/__init__.py +0 -0
  72. tenxgraph_api/cli/templates/prod/tests/conftest.py +6 -0
  73. tenxgraph_api/cli/templates/prod/tests/test_agent_eval.py +78 -0
  74. tenxgraph_api/cli/templates/prod/tests/test_catalog_tools.py +47 -0
  75. tenxgraph_api/cli/templates/prod/tests/test_graph_nodes.py +57 -0
  76. tenxgraph_api/cli/templates/skills/10xgraph/SKILL.md +92 -0
  77. tenxgraph_api/cli/templates/skills/10xgraph/references/agents-and-tools.md +389 -0
  78. tenxgraph_api/cli/templates/skills/10xgraph/references/api-client.md +61 -0
  79. tenxgraph_api/cli/templates/skills/10xgraph/references/api-configuration.md +75 -0
  80. tenxgraph_api/cli/templates/skills/10xgraph/references/api-settings-and-middleware.md +89 -0
  81. tenxgraph_api/cli/templates/skills/10xgraph/references/architecture.md +91 -0
  82. tenxgraph_api/cli/templates/skills/10xgraph/references/auth-and-authorization.md +149 -0
  83. tenxgraph_api/cli/templates/skills/10xgraph/references/callbacks-and-command.md +283 -0
  84. tenxgraph_api/cli/templates/skills/10xgraph/references/checkpointing-and-threads.md +63 -0
  85. tenxgraph_api/cli/templates/skills/10xgraph/references/cli-commands.md +73 -0
  86. tenxgraph_api/cli/templates/skills/10xgraph/references/client-auth-and-errors.md +94 -0
  87. tenxgraph_api/cli/templates/skills/10xgraph/references/client-messages-invoke-stream.md +115 -0
  88. tenxgraph_api/cli/templates/skills/10xgraph/references/client-threads-memory-files.md +80 -0
  89. tenxgraph_api/cli/templates/skills/10xgraph/references/context-id-background.md +80 -0
  90. tenxgraph_api/cli/templates/skills/10xgraph/references/dependency-injection.md +58 -0
  91. tenxgraph_api/cli/templates/skills/10xgraph/references/evaluation.md +500 -0
  92. tenxgraph_api/cli/templates/skills/10xgraph/references/id-and-thread-name-generators.md +69 -0
  93. tenxgraph_api/cli/templates/skills/10xgraph/references/media-and-files.md +66 -0
  94. tenxgraph_api/cli/templates/skills/10xgraph/references/memory-and-store.md +70 -0
  95. tenxgraph_api/cli/templates/skills/10xgraph/references/prebuilt-agents-and-tools.md +394 -0
  96. tenxgraph_api/cli/templates/skills/10xgraph/references/production-runtime.md +56 -0
  97. tenxgraph_api/cli/templates/skills/10xgraph/references/providers-and-adapters.md +89 -0
  98. tenxgraph_api/cli/templates/skills/10xgraph/references/publishers-and-runtime-protocols.md +84 -0
  99. tenxgraph_api/cli/templates/skills/10xgraph/references/rate-limiting.md +194 -0
  100. tenxgraph_api/cli/templates/skills/10xgraph/references/realtime.md +172 -0
  101. tenxgraph_api/cli/templates/skills/10xgraph/references/remote-tools.md +55 -0
  102. tenxgraph_api/cli/templates/skills/10xgraph/references/rest-api-and-errors.md +97 -0
  103. tenxgraph_api/cli/templates/skills/10xgraph/references/security-and-validators.md +86 -0
  104. tenxgraph_api/cli/templates/skills/10xgraph/references/state-and-messages.md +68 -0
  105. tenxgraph_api/cli/templates/skills/10xgraph/references/state-graph.md +232 -0
  106. tenxgraph_api/cli/templates/skills/10xgraph/references/stream-emitter.md +144 -0
  107. tenxgraph_api/cli/templates/skills/10xgraph/references/streaming.md +53 -0
  108. tenxgraph_api/cli/templates/skills/10xgraph/references/testing-and-evaluation.md +64 -0
  109. tenxgraph_api/cli/templates/skills/10xgraph/references/unit-testing.md +202 -0
  110. tenxgraph_api/cli/templates/skills/copilot/10xgraph.instructions.md +108 -0
  111. tenxgraph_api/py.typed +0 -0
  112. tenxgraph_api/src/__init__.py +0 -0
  113. tenxgraph_api/src/app/__init__.py +13 -0
  114. tenxgraph_api/src/app/core/__init__.py +15 -0
  115. tenxgraph_api/src/app/core/auth/__init__.py +0 -0
  116. tenxgraph_api/src/app/core/auth/auth_backend.py +38 -0
  117. tenxgraph_api/src/app/core/auth/authorization.py +379 -0
  118. tenxgraph_api/src/app/core/auth/base_auth.py +27 -0
  119. tenxgraph_api/src/app/core/auth/jwt_auth.py +122 -0
  120. tenxgraph_api/src/app/core/auth/ownership_resolver.py +170 -0
  121. tenxgraph_api/src/app/core/auth/permissions.py +354 -0
  122. tenxgraph_api/src/app/core/auth/request_config.py +130 -0
  123. tenxgraph_api/src/app/core/auth/route_guard.py +105 -0
  124. tenxgraph_api/src/app/core/config/__init__.py +0 -0
  125. tenxgraph_api/src/app/core/config/graph_config.py +532 -0
  126. tenxgraph_api/src/app/core/config/media_settings.py +72 -0
  127. tenxgraph_api/src/app/core/config/sentry_config.py +60 -0
  128. tenxgraph_api/src/app/core/config/settings.py +202 -0
  129. tenxgraph_api/src/app/core/config/setup_logs.py +65 -0
  130. tenxgraph_api/src/app/core/config/setup_middleware.py +483 -0
  131. tenxgraph_api/src/app/core/config/worker_middleware.py +99 -0
  132. tenxgraph_api/src/app/core/exceptions/__init__.py +17 -0
  133. tenxgraph_api/src/app/core/exceptions/general_exception.py +58 -0
  134. tenxgraph_api/src/app/core/exceptions/handle_errors.py +363 -0
  135. tenxgraph_api/src/app/core/exceptions/resources_exceptions.py +72 -0
  136. tenxgraph_api/src/app/core/exceptions/user_exception.py +58 -0
  137. tenxgraph_api/src/app/core/middleware/__init__.py +25 -0
  138. tenxgraph_api/src/app/core/middleware/rate_limit/__init__.py +15 -0
  139. tenxgraph_api/src/app/core/middleware/rate_limit/base.py +27 -0
  140. tenxgraph_api/src/app/core/middleware/rate_limit/factory.py +98 -0
  141. tenxgraph_api/src/app/core/middleware/rate_limit/keying.py +133 -0
  142. tenxgraph_api/src/app/core/middleware/rate_limit/memory.py +98 -0
  143. tenxgraph_api/src/app/core/middleware/rate_limit/middleware.py +90 -0
  144. tenxgraph_api/src/app/core/middleware/rate_limit/redis.py +115 -0
  145. tenxgraph_api/src/app/core/middleware/request_limits.py +154 -0
  146. tenxgraph_api/src/app/core/middleware/security_headers.py +239 -0
  147. tenxgraph_api/src/app/core/utils/__init__.py +14 -0
  148. tenxgraph_api/src/app/core/utils/log_sanitizer.py +216 -0
  149. tenxgraph_api/src/app/loader.py +516 -0
  150. tenxgraph_api/src/app/main.py +180 -0
  151. tenxgraph_api/src/app/routers/__init__.py +4 -0
  152. tenxgraph_api/src/app/routers/ag_ui/__init__.py +10 -0
  153. tenxgraph_api/src/app/routers/ag_ui/converter.py +195 -0
  154. tenxgraph_api/src/app/routers/ag_ui/event_mapper.py +353 -0
  155. tenxgraph_api/src/app/routers/ag_ui/router.py +90 -0
  156. tenxgraph_api/src/app/routers/ag_ui/service.py +193 -0
  157. tenxgraph_api/src/app/routers/checkpointer/__init__.py +1 -0
  158. tenxgraph_api/src/app/routers/checkpointer/router.py +482 -0
  159. tenxgraph_api/src/app/routers/checkpointer/schemas/__init__.py +1 -0
  160. tenxgraph_api/src/app/routers/checkpointer/schemas/checkpointer_schemas.py +121 -0
  161. tenxgraph_api/src/app/routers/checkpointer/services/__init__.py +1 -0
  162. tenxgraph_api/src/app/routers/checkpointer/services/checkpointer_service.py +300 -0
  163. tenxgraph_api/src/app/routers/evals/__init__.py +6 -0
  164. tenxgraph_api/src/app/routers/evals/router.py +38 -0
  165. tenxgraph_api/src/app/routers/evals/services/__init__.py +1 -0
  166. tenxgraph_api/src/app/routers/evals/services/eval_report_service.py +354 -0
  167. tenxgraph_api/src/app/routers/graph/__init__.py +6 -0
  168. tenxgraph_api/src/app/routers/graph/realtime_guard.py +161 -0
  169. tenxgraph_api/src/app/routers/graph/router.py +821 -0
  170. tenxgraph_api/src/app/routers/graph/schemas/__init__.py +1 -0
  171. tenxgraph_api/src/app/routers/graph/schemas/graph_schemas.py +386 -0
  172. tenxgraph_api/src/app/routers/graph/services/__init__.py +1 -0
  173. tenxgraph_api/src/app/routers/graph/services/graph_service.py +1219 -0
  174. tenxgraph_api/src/app/routers/graph/services/multimodal_preprocessor.py +164 -0
  175. tenxgraph_api/src/app/routers/media/__init__.py +506 -0
  176. tenxgraph_api/src/app/routers/media/router.py +242 -0
  177. tenxgraph_api/src/app/routers/media/schemas.py +39 -0
  178. tenxgraph_api/src/app/routers/ping/__init__.py +4 -0
  179. tenxgraph_api/src/app/routers/ping/router.py +28 -0
  180. tenxgraph_api/src/app/routers/setup_router.py +60 -0
  181. tenxgraph_api/src/app/routers/store/__init__.py +4 -0
  182. tenxgraph_api/src/app/routers/store/router.py +200 -0
  183. tenxgraph_api/src/app/routers/store/schemas/__init__.py +28 -0
  184. tenxgraph_api/src/app/routers/store/schemas/store_schemas.py +200 -0
  185. tenxgraph_api/src/app/routers/store/services/__init__.py +4 -0
  186. tenxgraph_api/src/app/routers/store/services/store_service.py +203 -0
  187. tenxgraph_api/src/app/tasks/__init__.py +0 -0
  188. tenxgraph_api/src/app/tasks/user_tasks.py +38 -0
  189. tenxgraph_api/src/app/utils/__init__.py +12 -0
  190. tenxgraph_api/src/app/utils/callable_helper.py +26 -0
  191. tenxgraph_api/src/app/utils/media/__init__.py +15 -0
  192. tenxgraph_api/src/app/utils/media/extractor.py +172 -0
  193. tenxgraph_api/src/app/utils/media/pipeline.py +83 -0
  194. tenxgraph_api/src/app/utils/parse_output.py +17 -0
  195. tenxgraph_api/src/app/utils/response_helper.py +129 -0
  196. tenxgraph_api/src/app/utils/schemas/__init__.py +11 -0
  197. tenxgraph_api/src/app/utils/schemas/output_schemas.py +28 -0
  198. tenxgraph_api/src/app/utils/schemas/user_schemas.py +13 -0
  199. tenxgraph_api/src/app/utils/snowflake_id_generator.py +90 -0
  200. tenxgraph_api/src/app/utils/swagger_helper.py +160 -0
  201. tenxgraph_api/src/app/utils/telemetry_store.py +123 -0
  202. tenxgraph_api/src/app/utils/thread_name_generator.py +304 -0
  203. tenxgraph_api/src/app/worker.py +91 -0
@@ -0,0 +1,130 @@
1
+ """Keep server-owned keys out of client-supplied request ``config``.
2
+
3
+ Request ``config`` is an open dict on purpose: frontends pass their own values through it and
4
+ graph nodes and tools read them. Its keys cannot be allow-listed, because the API does not know
5
+ what an application sends.
6
+
7
+ A small set of keys is owned by the server instead, and a client must never set them:
8
+
9
+ - ``authz`` -- the isolation policy and scopes; the trusted copy lives in ``user["authz"]``
10
+ - ``user`` -- the verified identity
11
+ - ``user_id`` -- derived from the verified identity
12
+ - ``remote_tools`` -- per-run client tool schemas the model may call; only protocol adapters
13
+ whose clients legitimately bring tools (AG-UI) set it, from the protocol's own tool list
14
+ - ``_*`` -- framework internals (``_skip_interrupt_at``, ``_node_name``, ...)
15
+
16
+ Every route and service that forwards client config to the graph, checkpointer or store must
17
+ pass it through :func:`client_config` first, then set the server-owned keys itself.
18
+
19
+ The thread a request runs on is also server-controlled: routes use the thread the permission
20
+ check approved, and both sides normalise it with :func:`normalize_thread_id`.
21
+
22
+ Tool calls are server-controlled too: only the model may request a tool. Client messages
23
+ are checked with :func:`client_tool_call_error`. A client may send a tool *result* only as the
24
+ answer to a remote tool call that is still waiting for one (:func:`unanswered_tool_calls`).
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ from typing import Any
30
+
31
+
32
+ RESERVED_CONFIG_KEYS: frozenset[str] = frozenset({"authz", "user", "user_id", "remote_tools"})
33
+ INTERNAL_KEY_PREFIX = "_"
34
+
35
+
36
+ def _is_client_key(key: Any) -> bool:
37
+ return (
38
+ isinstance(key, str)
39
+ and key not in RESERVED_CONFIG_KEYS
40
+ and not key.startswith(INTERNAL_KEY_PREFIX)
41
+ )
42
+
43
+
44
+ def client_config(config: Any) -> dict[str, Any]:
45
+ """Return a copy of client-supplied config without server-owned keys.
46
+
47
+ Application keys pass through unchanged, including ``thread_id``, which each route then
48
+ replaces with, or checks against, the thread the permission check approved.
49
+ """
50
+ if not isinstance(config, dict):
51
+ return {}
52
+ return {key: value for key, value in config.items() if _is_client_key(key)}
53
+
54
+
55
+ # Content blocks that ask the server to run a tool. Only the model produces these; tool
56
+ # *results* (``tool_result``) are fine, since remote tools send them back from the client.
57
+ TOOL_CALL_BLOCK_TYPES: frozenset[str] = frozenset({"tool_call", "remote_tool_call"})
58
+
59
+
60
+ def _field(message: Any, name: str) -> Any:
61
+ if isinstance(message, dict):
62
+ return message.get(name)
63
+ return getattr(message, name, None)
64
+
65
+
66
+ def client_tool_call_error(messages: Any) -> str | None:
67
+ """Describe the first client-supplied message that carries a tool call, or ``None``.
68
+
69
+ A ``ToolNode`` executes the ``tools_calls`` of the last message in context, so a client
70
+ that can write a tool call can run any server tool with its own arguments, skipping the
71
+ model, the system prompt and any guard node. Accepts ``Message`` objects or plain dicts.
72
+ """
73
+ if not isinstance(messages, list | tuple):
74
+ return None
75
+ for index, message in enumerate(messages):
76
+ carries_call = bool(_field(message, "tools_calls")) or any(
77
+ _field(block, "type") in TOOL_CALL_BLOCK_TYPES
78
+ for block in _field(message, "content") or []
79
+ )
80
+ if carries_call:
81
+ return f"messages[{index}] carries a tool call; only the model may request tools"
82
+ return None
83
+
84
+
85
+ def tool_result_ids(messages: Any) -> list[str]:
86
+ """The ``call_id`` of every tool result block in ``messages``, in order."""
87
+ if not isinstance(messages, list | tuple):
88
+ return []
89
+ return [
90
+ str(_field(block, "call_id"))
91
+ for message in messages
92
+ for block in _field(message, "content") or []
93
+ if _field(block, "type") == "tool_result"
94
+ ]
95
+
96
+
97
+ def _tool_calls(message: Any) -> list[tuple[str, str]]:
98
+ """``(call_id, tool_name)`` for every tool call a message makes."""
99
+ calls: list[tuple[str, str]] = []
100
+ for call in _field(message, "tools_calls") or []:
101
+ if isinstance(call, dict) and call.get("id"):
102
+ name = (call.get("function") or {}).get("name") or call.get("name") or ""
103
+ calls.append((str(call["id"]), str(name)))
104
+ for block in _field(message, "content") or []:
105
+ if _field(block, "type") in TOOL_CALL_BLOCK_TYPES and _field(block, "id"):
106
+ calls.append((str(_field(block, "id")), str(_field(block, "name") or "")))
107
+ return calls
108
+
109
+
110
+ def unanswered_tool_calls(context: Any) -> dict[str, str]:
111
+ """Map ``call_id -> tool_name`` for the tool calls in ``context`` that have no result yet."""
112
+ calls: dict[str, str] = {}
113
+ for message in context or []:
114
+ if _field(message, "role") == "assistant":
115
+ for call_id, name in _tool_calls(message):
116
+ calls.setdefault(call_id, name)
117
+ for call_id in tool_result_ids(list(context or [])):
118
+ calls.pop(call_id, None)
119
+ return calls
120
+
121
+
122
+ def normalize_thread_id(value: Any) -> str | None:
123
+ """The one canonical form of a thread id, shared by the permission check and the services.
124
+
125
+ Returns ``None`` for a missing or blank id, which means "start a new thread".
126
+ """
127
+ if value is None or isinstance(value, bool):
128
+ return None
129
+ text = str(value).strip()
130
+ return text or None
@@ -0,0 +1,105 @@
1
+ """Boot-time invariant: every route must go through the authorization layer.
2
+
3
+ Authorization is applied per-handler via ``Depends(RequirePermission(...))``, which is
4
+ precise (each endpoint declares its own resource/action) but easy to forget on a new
5
+ endpoint -- and a forgotten guard ships an open endpoint. This module makes that failure
6
+ happen at startup instead: :func:`assert_all_routes_protected` refuses to boot if any
7
+ non-public route lacks a ``RequirePermission`` dependency.
8
+
9
+ It adds zero per-request cost and turns "someone forgot the guard" into a loud deploy-time
10
+ error rather than a silent production hole.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import logging
16
+
17
+ from fastapi import FastAPI
18
+ from fastapi.routing import APIRoute, APIWebSocketRoute
19
+
20
+ from tenxgraph_api.src.app.core.auth.permissions import RequirePermission
21
+
22
+
23
+ logger = logging.getLogger("tenxgraph_api.route_guard")
24
+
25
+ # Paths that are intentionally public (no authorization). Keep this list tiny and explicit.
26
+ # Evals is a dev-only report viewer over local files (no user data, not a production surface).
27
+ DEFAULT_PUBLIC_PATHS = frozenset(
28
+ {
29
+ "/ping",
30
+ "/v1/evals/runs",
31
+ "/v1/evals/runs/{run_id}",
32
+ }
33
+ )
34
+
35
+
36
+ def _has_permission_guard(dependant) -> bool:
37
+ """True if ``RequirePermission`` appears anywhere in the dependant subtree."""
38
+ for dep in getattr(dependant, "dependencies", ()):
39
+ if isinstance(getattr(dep, "call", None), RequirePermission):
40
+ return True
41
+ if _has_permission_guard(dep):
42
+ return True
43
+ return False
44
+
45
+
46
+ def _is_guard(dependency: object) -> bool:
47
+ """True for a ``Depends(RequirePermission(...))`` given at ``include_router`` time."""
48
+ return isinstance(getattr(dependency, "dependency", None), RequirePermission)
49
+
50
+
51
+ def _iter_routes(routes, prefix: str = "", guarded: bool = False):
52
+ """Yield ``(full_path, route, guarded_by_include)`` for every route, however nested.
53
+
54
+ FastAPI 0.139 keeps ``include_router`` lazy: ``app.routes`` holds one wrapper per
55
+ included router instead of copies of its routes, so a plain walk of ``app.routes`` sees
56
+ no ``APIRoute`` at all. The wrapper carries the router and its include prefix and
57
+ dependencies; older releases copy the routes, which the plain branch handles.
58
+ """
59
+ for route in routes:
60
+ included = getattr(route, "original_router", None)
61
+ context = getattr(route, "include_context", None)
62
+ if included is not None and context is not None:
63
+ yield from _iter_routes(
64
+ included.routes,
65
+ prefix + (getattr(context, "prefix", "") or ""),
66
+ guarded or any(_is_guard(dep) for dep in getattr(context, "dependencies", [])),
67
+ )
68
+ elif isinstance(route, APIRoute | APIWebSocketRoute):
69
+ yield prefix + route.path, route, guarded
70
+
71
+
72
+ def find_unprotected_routes(
73
+ app: FastAPI, public_paths: frozenset[str] = DEFAULT_PUBLIC_PATHS
74
+ ) -> list[str]:
75
+ """Return ``"METHODS path"`` for every route missing a RequirePermission guard.
76
+
77
+ Starlette infra routes (docs, openapi.json, redoc) are not APIRoutes and are skipped.
78
+ """
79
+ unprotected: list[str] = []
80
+ for path, route, guarded in _iter_routes(app.routes):
81
+ if path in public_paths or guarded:
82
+ continue
83
+ dependant = getattr(route, "dependant", None)
84
+ if dependant is None or not _has_permission_guard(dependant):
85
+ methods = ",".join(sorted(getattr(route, "methods", None) or ["WS"]))
86
+ unprotected.append(f"{methods} {path}")
87
+ return unprotected
88
+
89
+
90
+ def assert_all_routes_protected(
91
+ app: FastAPI, public_paths: frozenset[str] = DEFAULT_PUBLIC_PATHS
92
+ ) -> None:
93
+ """Refuse to start if any non-public route lacks a RequirePermission guard.
94
+
95
+ Raises:
96
+ RuntimeError: listing every unprotected route.
97
+ """
98
+ unprotected = find_unprotected_routes(app, public_paths)
99
+ if unprotected:
100
+ raise RuntimeError(
101
+ "Refusing to start: the following routes are not protected by "
102
+ "RequirePermission. Add the dependency, or add the path to the public "
103
+ "allowlist if it is intentionally open:\n - " + "\n - ".join(unprotected)
104
+ )
105
+ logger.debug("Route protection invariant OK (%d routes checked).", len(app.routes))
File without changes