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:
anor
2026-06-02 16:33:18 +10:00
co-authored by Claude Opus 4.8
parent f17ddc12df
commit cbc1b3410b
3 changed files with 59 additions and 16 deletions
+22
View File
@@ -183,3 +183,25 @@ def get_token_role(token: str) -> str:
return payload.get("role", "user")
except Exception:
return "user"
def _download_sig(username: str, tab_id: str, filename: str, exp: int) -> str:
msg = f"{username}|{tab_id}|{filename}|{exp}".encode()
return hmac.new(SECRET.encode(), msg, hashlib.sha256).hexdigest()
def make_download_ticket(username: str, tab_id: str, filename: str, ttl: int = 60):
"""Short-lived signed ticket for native browser downloads — keeps the
long-lived JWT out of URLs/logs. Bound to the exact (user, tab, file)."""
exp = int(time.time()) + ttl
return exp, _download_sig(username, tab_id, filename, exp)
def verify_download_ticket(username: str, tab_id: str, filename: str, exp, sig: str) -> bool:
try:
exp = int(exp)
except (TypeError, ValueError):
return False
if exp < int(time.time()):
return False
return hmac.compare_digest(sig or "", _download_sig(username, tab_id, filename, exp))
+24 -10
View File
@@ -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)
+13 -6
View File
@@ -282,13 +282,20 @@ async function loadFiles() {
tbl.appendChild(tr);
}
}
function adminDownload(url, filename) {
// Native download: the browser streams straight to disk, so it works for
// multi-GB files. The old fetch→blob approach buffered the whole file in
// browser memory and silently failed on large ones. <a> can't set an auth
// header, so the endpoint also accepts the token via query param.
async function adminDownload(url, filename) {
// Native download streams straight to disk (works for multi-GB files; the old
// fetch→blob buffered the whole file in memory and failed on large ones).
// <a> can't send an auth header, so first fetch a short-lived signed ticket
// (with the header) and put only that in the URL — never the JWT.
const p = new URLSearchParams(url.split('?')[1]);
const r = await fetch('/api/admin/download_ticket', {
method: 'POST', headers: {...H, 'Content-Type': 'application/json'},
body: JSON.stringify({username: p.get('username'), tab_id: p.get('tab_id'), filename: p.get('filename')}),
});
if (!r.ok) { alert('Ошибка скачивания: ' + r.status); return; }
const t = await r.json();
const a = document.createElement('a');
a.href = url + '&token=' + encodeURIComponent(token);
a.href = url + '&exp=' + t.exp + '&sig=' + encodeURIComponent(t.sig);
a.download = filename;
document.body.appendChild(a); a.click(); a.remove();
}