feat: audit log всех действий + GLM-5.1 + домен infosmeta.ru
- Таблица audit_log + middleware для логирования всех API-запросов - Раздел "Журнал" в админке с фильтрами по пользователю/действию - Переход на GLM-5.1 с отключённым reasoning (thinking: disabled) - max_tokens 2000→4096, timeout 60→120с - Домен smeta.kazin.ru → infosmeta.ru во всех файлах Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -11,7 +11,7 @@ from fastapi.responses import FileResponse, HTMLResponse, StreamingResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from auth import authenticate, verify_token
|
||||
from db import get_history, get_history_any_user, init_db, list_sessions, save_message
|
||||
from db import get_audit_log, get_history, get_history_any_user, init_db, list_sessions, log_action, save_message
|
||||
|
||||
# Backend: "claude" (Docker sandbox), "glm" (GLM-5 + CAG), "auto" (route by task)
|
||||
AI_BACKEND = os.environ.get("AI_BACKEND", "claude")
|
||||
@@ -101,12 +101,97 @@ app.mount("/static", StaticFiles(directory="static"), name="static")
|
||||
MAX_UPLOAD_SIZE = 50 * 1024 * 1024 # 50 MB
|
||||
MAX_MESSAGE_LEN = 10_000
|
||||
|
||||
# Audit: path → action name mapping
|
||||
_AUDIT_MAP = [
|
||||
("POST", "/api/login", "login"),
|
||||
("POST", "/api/register", "register"),
|
||||
("POST", "/api/verify-email", "verify_email"),
|
||||
("POST", "/api/refresh", "refresh"),
|
||||
("POST", "/api/chat", "chat"),
|
||||
("POST", "/api/upload", "upload"),
|
||||
("GET", "/api/files/", "download"),
|
||||
("GET", "/api/files", "list_files"),
|
||||
("POST", "/api/clear-files", "clear_files"),
|
||||
("POST", "/api/reset", "reset_session"),
|
||||
("POST", "/api/batch-v2/", "batch_v2"),
|
||||
("GET", "/api/batch-v2/", "batch_v2"),
|
||||
("POST", "/api/batch-v3/", "batch_v3"),
|
||||
("GET", "/api/batch-v3/", "batch_v3"),
|
||||
("POST", "/api/ssr/", "ssr"),
|
||||
("GET", "/api/ssr/", "ssr"),
|
||||
("POST", "/api/check/", "check"),
|
||||
("POST", "/api/gen/", "generate"),
|
||||
("GET", "/api/gen/", "generate"),
|
||||
("POST", "/api/wizard/", "wizard"),
|
||||
("GET", "/api/wizard/", "wizard"),
|
||||
("GET", "/api/ref/", "reference"),
|
||||
("GET", "/api/history", "history"),
|
||||
("GET", "/api/sessions", "sessions"),
|
||||
("GET", "/api/admin/", "admin"),
|
||||
("POST", "/api/admin/", "admin"),
|
||||
]
|
||||
|
||||
_SKIP_PREFIXES = ("/static/", "/favicon")
|
||||
|
||||
|
||||
def _resolve_action(method: str, path: str) -> str | None:
|
||||
if any(path.startswith(p) for p in _SKIP_PREFIXES):
|
||||
return None
|
||||
for m, prefix, action in _AUDIT_MAP:
|
||||
if method == m and path.startswith(prefix):
|
||||
# For admin sub-actions: admin.invite, admin.block, etc.
|
||||
if action == "admin":
|
||||
sub = path.removeprefix("/api/admin/").split("/")[0].split("?")[0]
|
||||
return f"admin.{sub}" if sub else "admin"
|
||||
return action
|
||||
# Pages (GET /, /batch2, /admin, etc.) — skip
|
||||
if not path.startswith("/api/"):
|
||||
return None
|
||||
return method.lower() + ":" + path
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
async def startup():
|
||||
init_db()
|
||||
|
||||
|
||||
# Actions logged manually in handlers (with richer detail)
|
||||
_MANUAL_ACTIONS = {"login", "login_fail", "chat", "upload", "register", "register_fail"}
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def audit_middleware(request: Request, call_next):
|
||||
method = request.method
|
||||
path = request.url.path
|
||||
action = _resolve_action(method, path)
|
||||
response = await call_next(request)
|
||||
if action is None or action in _MANUAL_ACTIONS:
|
||||
return response
|
||||
# Extract username from JWT (best-effort, don't fail)
|
||||
username = None
|
||||
try:
|
||||
auth_header = request.headers.get("authorization", "")
|
||||
tok = auth_header.removeprefix("Bearer ").strip()
|
||||
if tok:
|
||||
username = verify_token(tok)
|
||||
except Exception:
|
||||
pass
|
||||
# Extract detail based on action
|
||||
detail = None
|
||||
if action == "download":
|
||||
parts = path.split("/api/files/")
|
||||
detail = parts[1] if len(parts) > 1 else None
|
||||
elif action in ("batch_v2", "batch_v3", "ssr", "generate"):
|
||||
sub = path.split("/")[-1] if "/" in path else None
|
||||
detail = sub
|
||||
ip = request.client.host if request.client else None
|
||||
try:
|
||||
log_action(username, action, method, path, detail, ip, response.status_code)
|
||||
except Exception:
|
||||
pass
|
||||
return response
|
||||
|
||||
|
||||
# Rate limiting for chat API (10 requests/minute per user)
|
||||
_chat_rate: dict[str, list[float]] = {}
|
||||
CHAT_RATE_LIMIT = 10
|
||||
@@ -153,10 +238,12 @@ async def login(request: Request):
|
||||
client_ip = request.client.host if request.client else ""
|
||||
token = authenticate(username, password, client_ip)
|
||||
if not token:
|
||||
log_action(username, "login_fail", "POST", "/api/login", None, client_ip, 401)
|
||||
raise HTTPException(401, "Wrong credentials")
|
||||
from auth import _make_refresh_token, get_token_role
|
||||
role = get_token_role(token)
|
||||
refresh = _make_refresh_token(username, role)
|
||||
log_action(username, "login", "POST", "/api/login", f"role={role}", client_ip, 200)
|
||||
return {"token": token, "refresh_token": refresh, "username": username}
|
||||
|
||||
|
||||
@@ -183,9 +270,13 @@ async def register(request: Request):
|
||||
|
||||
from auth import register_user
|
||||
result = register_user(email, password, invite)
|
||||
client_ip = request.client.host if request.client else ""
|
||||
if not result["ok"]:
|
||||
log_action(email, "register_fail", "POST", "/api/register", result["error"], client_ip, 400)
|
||||
raise HTTPException(400, result["error"])
|
||||
|
||||
log_action(email, "register", "POST", "/api/register", None, client_ip, 200)
|
||||
|
||||
# Send verification code via email
|
||||
code = result.get("code", "")
|
||||
if code:
|
||||
@@ -256,6 +347,8 @@ async def chat(request: Request):
|
||||
raise HTTPException(400, "Empty message")
|
||||
if len(message) > MAX_MESSAGE_LEN:
|
||||
raise HTTPException(400, f"Message too long (max {MAX_MESSAGE_LEN} chars)")
|
||||
ip = request.client.host if request.client else None
|
||||
log_action(user, "chat", "POST", "/api/chat", f"tab={tab_id} | {message[:120]}", ip, 200)
|
||||
|
||||
return StreamingResponse(
|
||||
_stream_and_save(message, user, tab_id),
|
||||
@@ -317,6 +410,8 @@ async def upload(request: Request, file: UploadFile):
|
||||
dest = work_dir / safe_name
|
||||
dest.write_bytes(b"".join(chunks))
|
||||
save_message(user, tab_id, "system", f"Загружен файл: {safe_name} ({total} байт)")
|
||||
ip = request.client.host if request.client else None
|
||||
log_action(user, "upload", "POST", "/api/upload", f"{safe_name} ({total}B) tab={tab_id}", ip, 200)
|
||||
return {"filename": safe_name, "size": total}
|
||||
|
||||
|
||||
@@ -572,6 +667,17 @@ async def admin_sessions(request: Request):
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
@app.get("/api/admin/audit")
|
||||
async def admin_audit(request: Request):
|
||||
"""Full audit log — admin only."""
|
||||
_require_admin(request)
|
||||
limit = int(request.query_params.get("limit", "200"))
|
||||
offset = int(request.query_params.get("offset", "0"))
|
||||
username = request.query_params.get("username") or None
|
||||
action = request.query_params.get("action") or None
|
||||
return get_audit_log(limit, offset, username, action)
|
||||
|
||||
|
||||
@app.get("/api/admin/stats")
|
||||
async def admin_stats(request: Request):
|
||||
"""Dashboard stats: messages per day, total sessions, etc."""
|
||||
@@ -608,7 +714,7 @@ async def create_invite_endpoint(request: Request):
|
||||
from db import create_invite
|
||||
invite_token = secrets.token_urlsafe(24)
|
||||
create_invite(invite_token, user)
|
||||
return {"invite_token": invite_token, "url": f"https://smeta.kazin.ru/register?invite={invite_token}"}
|
||||
return {"invite_token": invite_token, "url": f"https://infosmeta.ru/register?invite={invite_token}"}
|
||||
|
||||
|
||||
@app.get("/api/admin/invites")
|
||||
|
||||
Reference in New Issue
Block a user