backend refactor#8688
Conversation
There was a problem hiding this comment.
CodeQL found more than 20 potential problems in the proposed changes. Check the Files changed tab for more details.
There was a problem hiding this comment.
Code Review
This pull request migrates the AstrBot dashboard and webhook servers from Quart to FastAPI, introducing a new ASGI runtime adapter, a unified FastAPI webhook server, and restructuring all dashboard API endpoints into FastAPI routers. The review feedback highlights several critical issues: FastAPIAppAdapter needs to register itself on the FastAPI application state to prevent authentication failures over HTTP in local development; the require_scope dependency must be updated to check cookies to support dashboard users; the close callback in open_api.py should be an asynchronous function to ensure the WebSocket close coroutine is properly awaited; and inspect.signature in the webhook server should be called once during route registration rather than on every request to avoid performance bottlenecks.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
|
|
||
| def add_url_rule( | ||
| self, | ||
| path: str, | ||
| view_func: Callable, | ||
| methods: list[str] | None = None, | ||
| endpoint: str | None = None, | ||
| ) -> None: | ||
| route_path = _convert_rule(path) |
There was a problem hiding this comment.
The dashboard_app_adapter attribute is expected to be present on request.app.state (e.g., in _use_secure_dashboard_jwt_cookie to check debug and testing flags). However, FastAPIAppAdapter never registers itself on the FastAPI application's state. This causes request.app.state.dashboard_app_adapter to always be None, forcing secure cookies to be enabled even in local development or testing environments, which breaks authentication over HTTP. Register the adapter instance on app.state during initialization.
| def add_url_rule( | |
| self, | |
| path: str, | |
| view_func: Callable, | |
| methods: list[str] | None = None, | |
| endpoint: str | None = None, | |
| ) -> None: | |
| route_path = _convert_rule(path) | |
| class FastAPIAppAdapter: | |
| def __init__(self, app: FastAPI, static_folder: str | None = None) -> None: | |
| self._app = app | |
| self.static_folder = static_folder | |
| self._dashboard_server: Any | None = None | |
| self.config: dict[str, Any] = {} | |
| self.debug = False | |
| self.testing = False | |
| self.name = "dashboard" | |
| app.state.dashboard_app_adapter = self |
| auth_header = request.headers.get("Authorization", "").strip() | ||
| if not auth_header.startswith("Bearer "): | ||
| raise ApiError("Missing API key", status_code=401) | ||
| token = auth_header.removeprefix("Bearer ").strip() |
There was a problem hiding this comment.
The require_scope dependency only extracts tokens from the Authorization header and does not check cookies. However, several dashboard-specific endpoints (e.g., in config_profiles.py, bots.py, and providers.py) use dependencies that rely on require_scope. This means logged-in dashboard users using cookie-based sessions will be denied access to these pages with a 401 Unauthorized error. Update require_scope to use _extract_dashboard_jwt(request) so it seamlessly supports both Authorization headers and cookies.
| auth_header = request.headers.get("Authorization", "").strip() | |
| if not auth_header.startswith("Bearer "): | |
| raise ApiError("Missing API key", status_code=401) | |
| token = auth_header.removeprefix("Bearer ").strip() | |
| token = _extract_dashboard_jwt(request) | |
| if not token: | |
| raise ApiError("Missing API key", status_code=401) |
| async def endpoint(request: Request): | ||
| if inspect.signature(view_func).parameters: | ||
| result = view_func(WebhookRequest(request)) | ||
| else: | ||
| result = view_func() | ||
| if inspect.isawaitable(result): | ||
| result = await result | ||
| return _response_from_result(result) |
There was a problem hiding this comment.
Calling inspect.signature on every request inside the endpoint coroutine is highly inefficient and can cause significant performance bottlenecks under load. Instead, inspect the signature once when registering the route in add_url_rule and store the result in a local variable.
has_params = bool(inspect.signature(view_func).parameters)
async def endpoint(request: Request):
if has_params:
result = view_func(WebhookRequest(request))
else:
result = view_func()
if inspect.isawaitable(result):
result = await result
return _response_from_result(result)| await service.run_chat_websocket( | ||
| raw_api_key=_extract_ws_api_key(websocket), | ||
| receive_json=websocket.receive_json, | ||
| send_json=websocket.send_json, | ||
| close=lambda code, reason: websocket.close(code=code, reason=reason), | ||
| conf_list=_get_chat_config_list(service), | ||
| chat_bridge=_build_chat_ws_bridge(service, chat_service), | ||
| ) |
There was a problem hiding this comment.
The close callback is defined as a synchronous lambda returning a coroutine (websocket.close(...)). If the caller (run_chat_websocket) executes this callback synchronously, the coroutine will never be awaited, leading to a RuntimeWarning and failing to close the WebSocket connection. Define an asynchronous helper function instead to ensure proper awaiting.
| await service.run_chat_websocket( | |
| raw_api_key=_extract_ws_api_key(websocket), | |
| receive_json=websocket.receive_json, | |
| send_json=websocket.send_json, | |
| close=lambda code, reason: websocket.close(code=code, reason=reason), | |
| conf_list=_get_chat_config_list(service), | |
| chat_bridge=_build_chat_ws_bridge(service, chat_service), | |
| ) | |
| async def close_ws(code: int, reason: str): | |
| await websocket.close(code=code, reason=reason) | |
| await service.run_chat_websocket( | |
| raw_api_key=_extract_ws_api_key(websocket), | |
| receive_json=websocket.receive_json, | |
| send_json=websocket.send_json, | |
| close=close_ws, | |
| conf_list=_get_chat_config_list(service), | |
| chat_bridge=_build_chat_ws_bridge(service, chat_service), | |
| ) |
|
|
||
| def _service_error(exc: UpdateServiceError) -> JSONResponse: | ||
| return JSONResponse( | ||
| {"status": "error", "message": str(exc), "data": None}, |
- Updated API client configuration to use a dedicated HTTP client. - Introduced utility functions for generating options, queries, and form data for API requests. - Refactored multiple API methods to utilize the new utility functions for improved consistency and readability. - Renamed types for clarity and updated import statements accordingly. feat(docs): add script to update OpenAPI JSON from YAML spec - Created a Python script to convert OpenAPI YAML specification to JSON format. - The script supports customizable input and output paths. - Ensured the script handles directory creation for output paths and validates the YAML structure.
… request handling
…atibility - Changed all instances of dashboard_router to legacy_router across multiple API modules including platform, plugins, providers, sessions, skills, stats, subagents, t2i, tools, updates, and asgi_runtime. - Updated route definitions to ensure existing endpoints remain functional under the new router structure. - Introduced support for Quart request context in asgi_runtime to enhance compatibility with existing Quart-based plugins. - Added a test case to validate the functionality of the new Quart request context handling in plugin extensions.
Modifications / 改动点
Screenshots or Test Results / 运行截图或测试结果
Checklist / 检查清单
😊 If there are new features added in the PR, I have discussed it with the authors through issues/emails, etc.
/ 如果 PR 中有新加入的功能,已经通过 Issue / 邮件等方式和作者讨论过。
👀 My changes have been well-tested, and "Verification Steps" and "Screenshots" have been provided above.
/ 我的更改经过了良好的测试,并已在上方提供了“验证步骤”和“运行截图”。
🤓 I have ensured that no new dependencies are introduced, OR if new dependencies are introduced, they have been added to the appropriate locations in
requirements.txtandpyproject.toml./ 我确保没有引入新依赖库,或者引入了新依赖库的同时将其添加到
requirements.txt和pyproject.toml文件相应位置。😮 My changes do not introduce malicious code.
/ 我的更改没有引入恶意代码。