security: скачивание админом через короткоживущий тикет, а не JWT в URL
Ревью указало: долгоживущий admin-JWT в query попадает в логи nginx/journal. Замена: POST /api/admin/download_ticket выдаёт HMAC-подпись (SESSION_SECRET), живёт 60с, привязана к (username,tab_id,filename). В URL уходит только exp+sig. file_download проверяет тикет (constant-time), отдаёт FileResponse с Referrer-Policy: no-referrer. JWT остаётся в заголовке. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -10,7 +10,7 @@ from fastapi import FastAPI, HTTPException, Request, UploadFile
|
||||
from fastapi.responses import FileResponse, HTMLResponse, StreamingResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from auth import authenticate, verify_token
|
||||
from auth import authenticate, verify_token, make_download_ticket, verify_download_ticket
|
||||
from db import get_audit_log, get_history, get_history_any_user, init_db, list_sessions, log_action, save_message
|
||||
from tus_upload import register_tus
|
||||
|
||||
@@ -1001,6 +1001,21 @@ async def admin_list_files_endpoint(request: Request):
|
||||
return {"username": safe_user, "count": len(files), "files": files}
|
||||
|
||||
|
||||
@app.post("/api/admin/download_ticket")
|
||||
async def admin_download_ticket_endpoint(request: Request):
|
||||
"""Issue a short-lived signed ticket so the admin UI can trigger a native
|
||||
browser download (streams to disk, any size) without putting the JWT in a URL."""
|
||||
_require_admin(request)
|
||||
body = await request.json()
|
||||
username = (body.get("username") or "").strip()
|
||||
tab_id = (body.get("tab_id") or "").strip()
|
||||
filename = (body.get("filename") or "").strip()
|
||||
if not (username and tab_id and filename):
|
||||
raise HTTPException(400, "username, tab_id, filename required")
|
||||
exp, sig = make_download_ticket(username, tab_id, filename)
|
||||
return {"exp": exp, "sig": sig}
|
||||
|
||||
|
||||
@app.get("/api/admin/file_download")
|
||||
async def admin_download_file_endpoint(request: Request):
|
||||
"""Download any user's uploaded file (admin only).
|
||||
@@ -1008,18 +1023,17 @@ async def admin_download_file_endpoint(request: Request):
|
||||
Path components passed as query params to avoid URL-escaping pain
|
||||
with names like `!Реестр СМ..xlsm` and tab_ids containing slashes.
|
||||
"""
|
||||
# Native browser download of large files can't send an Authorization header,
|
||||
# so accept the admin token via query param as a fallback to the header.
|
||||
from auth import get_token_role
|
||||
_tok = (request.headers.get("authorization", "").removeprefix("Bearer ").strip()
|
||||
or request.query_params.get("token", "").strip())
|
||||
if not verify_token(_tok) or get_token_role(_tok) != "admin":
|
||||
raise HTTPException(403, "Admin only")
|
||||
target_user = request.query_params.get("username", "").strip()
|
||||
tab_id = request.query_params.get("tab_id", "").strip()
|
||||
filename = request.query_params.get("filename", "").strip()
|
||||
if not (target_user and tab_id and filename):
|
||||
raise HTTPException(400, "username, tab_id, filename required")
|
||||
# Auth via short-lived signed ticket (issued by /api/admin/download_ticket to
|
||||
# an authenticated admin) so the admin JWT never lands in a URL or access log.
|
||||
if not verify_download_ticket(target_user, tab_id, filename,
|
||||
request.query_params.get("exp", ""),
|
||||
request.query_params.get("sig", "")):
|
||||
raise HTTPException(403, "Invalid or expired download ticket")
|
||||
safe_user = Path(target_user).name
|
||||
safe_tab = Path(tab_id).name
|
||||
safe_name = Path(filename).name
|
||||
@@ -1033,10 +1047,10 @@ async def admin_download_file_endpoint(request: Request):
|
||||
raise HTTPException(400, "Path traversal denied")
|
||||
if not fpath.exists() or not fpath.is_file():
|
||||
raise HTTPException(404, "File not found")
|
||||
return FileResponse(fpath, filename=safe_name)
|
||||
return FileResponse(fpath, filename=safe_name, headers={"Referrer-Policy": "no-referrer"})
|
||||
|
||||
|
||||
ADMIN_HTML_VERSION = "20260602a"
|
||||
ADMIN_HTML_VERSION = "20260602b"
|
||||
|
||||
|
||||
@app.get("/admin", response_class=HTMLResponse)
|
||||
|
||||
Reference in New Issue
Block a user