Implement authentication and chat functionality with JWT support

- Added `auth.py` for mock login and JWT issuance.
- Introduced `chat.py` for handling chat requests with role-based access control.
- Enhanced `main.py` to include new routers and middleware for tracing.
- Implemented input validation in `input_guard.py` to prevent SQL injection.
- Created repositories for managing agent sessions and audit logs.
- Added exception handling for authorization errors.
- Updated settings to include JWT configuration.
- Introduced tests for authentication and input validation.
This commit is contained in:
2026-09-07 17:20:42 +08:00
parent 5f0f86a007
commit 3995cb44d8
26 changed files with 1013 additions and 10 deletions
+37 -1
View File
@@ -1 +1,37 @@
"""业务异常与鉴权错误码(对齐 JWT-RBAC 手册)。"""
"""统一业务异常。"""
from __future__ import annotations
class AppError(Exception):
def __init__(
self,
code: int,
message: str,
*,
http_status: int = 400,
error_code: str | None = None,
audit_event: str | None = None,
) -> None:
super().__init__(message)
self.code = code
self.message = message
self.http_status = http_status
self.error_code = error_code
self.audit_event = audit_event
class UnauthorizedError(AppError):
def __init__(self, message: str = "未授权", *, error_code: str = "AUTH_401") -> None:
super().__init__(401, message, http_status=401, error_code=error_code, audit_event="auth_denied")
class ForbiddenError(AppError):
def __init__(
self,
message: str = "无权访问",
*,
error_code: str = "AUTH_403",
audit_event: str = "auth_denied",
) -> None:
super().__init__(403, message, http_status=403, error_code=error_code, audit_event=audit_event)
+25
View File
@@ -0,0 +1,25 @@
"""输入防护(F-03 最小实现)。"""
from __future__ import annotations
import re
from app.utils.exceptions import AppError
_INJECTION_PATTERNS = (
re.compile(r"(?i)ignore\s+previous\s+instructions"),
re.compile(r"(?i)system\s*:\s*"),
re.compile(r"(?is)(drop|delete|update|insert|alter|truncate)\s+"),
)
def validate_user_message(message: str, *, max_len: int = 8000) -> str:
text = message.strip()
if not text:
raise AppError(400, "消息不能为空", error_code="INPUT_EMPTY")
if len(text) > max_len:
raise AppError(400, "消息过长", error_code="INPUT_OVERSIZE", audit_event="input_guard")
for pattern in _INJECTION_PATTERNS:
if pattern.search(text):
raise AppError(400, "输入包含不允许的内容", error_code="INPUT_BLOCKED", audit_event="input_guard")
return text
+6 -1
View File
@@ -1 +1,6 @@
"""日志模块。"""
"""结构化日志(不打印完整 JWT)。"""
import logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
logger = logging.getLogger("jinrong")
+14
View File
@@ -1 +1,15 @@
"""统一 API 响应格式。"""
from __future__ import annotations
from typing import Any
from app.model.schemas import ApiResponse
def ok(data: Any, trace_id: str, message: str = "ok") -> ApiResponse:
return ApiResponse(code=0, message=message, data=data, trace_id=trace_id)
def fail(code: int, message: str, trace_id: str, *, data: Any = None) -> ApiResponse:
return ApiResponse(code=code, message=message, data=data, trace_id=trace_id)