Estructura inicial funcional con documentación en el README.md de la FastAPI
This commit is contained in:
67
app/security.py
Normal file
67
app/security.py
Normal file
@@ -0,0 +1,67 @@
|
||||
"""Seguridad: quién puede buscar (JWT) y enlaces de descarga firmados que vencen."""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from urllib.parse import quote
|
||||
|
||||
import jwt
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
|
||||
from app.config import get_settings
|
||||
|
||||
_bearer = HTTPBearer(auto_error=False)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Usuario:
|
||||
id: str
|
||||
rol: str
|
||||
|
||||
|
||||
def usuario_actual(cred: HTTPAuthorizationCredentials | None = Depends(_bearer)) -> Usuario:
|
||||
"""El sistema Admin genera un JWT con {sub, rol, exp} firmado con JWT_SECRET
|
||||
y lo manda en el header: Authorization: Bearer <token>."""
|
||||
if cred is None:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Falta el token", {"WWW-Authenticate": "Bearer"})
|
||||
s = get_settings()
|
||||
try:
|
||||
datos = jwt.decode(
|
||||
cred.credentials, s.jwt_secret, algorithms=[s.jwt_algorithm], options={"require": ["exp", "sub"]}
|
||||
)
|
||||
except jwt.ExpiredSignatureError:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Token vencido")
|
||||
except jwt.InvalidTokenError:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Token inválido")
|
||||
|
||||
usuario = Usuario(id=str(datos["sub"]), rol=str(datos.get("rol", "")).lower())
|
||||
if usuario.rol not in s.roles_permitidos:
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, "Sin permiso para consultar archivos")
|
||||
return usuario
|
||||
|
||||
|
||||
# ---------- Enlaces de descarga firmados ----------
|
||||
# El enlace lleva: id del archivo, usuario que lo pidió, vencimiento y una firma HMAC.
|
||||
# Nadie puede cambiar el id ni extender el vencimiento sin invalidar la firma.
|
||||
|
||||
def _firma(archivo_id: str, usuario_id: str, exp: int) -> str:
|
||||
msg = f"{archivo_id}:{usuario_id}:{exp}".encode()
|
||||
digest = hmac.new(get_settings().download_secret.encode(), msg, hashlib.sha256).digest()
|
||||
return base64.urlsafe_b64encode(digest).decode().rstrip("=")
|
||||
|
||||
|
||||
def generar_url_descarga(archivo_id: str, usuario_id: str) -> str:
|
||||
s = get_settings()
|
||||
exp = int(time.time()) + s.download_link_ttl_minutes * 60
|
||||
firma = _firma(archivo_id, usuario_id, exp)
|
||||
base = s.public_base_url.rstrip("/")
|
||||
return f"{base}/descargas/{quote(archivo_id, safe='')}?u={quote(usuario_id, safe='')}&exp={exp}&sig={firma}"
|
||||
|
||||
|
||||
def validar_firma(archivo_id: str, usuario_id: str, exp: int, sig: str) -> None:
|
||||
if exp < int(time.time()):
|
||||
raise HTTPException(status.HTTP_410_GONE, "El enlace de descarga venció")
|
||||
if not hmac.compare_digest(_firma(archivo_id, usuario_id, exp), sig):
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, "Enlace de descarga inválido")
|
||||
Reference in New Issue
Block a user