Files
cotizador/api/app/auth.py
T

347 lines
10 KiB
Python

from __future__ import annotations
import hashlib
import json
import math
import time
import uuid
from datetime import datetime, timedelta, timezone
from typing import Any
from fastapi import Depends, Header, HTTPException, Request, status
from jose import JWTError, jwt
from passlib.context import CryptContext
from app.config import settings
from app.database import get_pool
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_DAYS = 7
# Rate limiter en memoria con ventana deslizante de 60 segundos por key_id.
_WINDOW_SECS = 60.0
_rate_buckets: dict[str, list[float]] = {}
def hash_secret(raw: str) -> str:
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
def verify_password(plain: str, hashed: str) -> bool:
return pwd_context.verify(plain, hashed)
def get_password_hash(password: str) -> str:
return pwd_context.hash(password)
def create_access_token(data: dict) -> str:
to_encode = data.copy()
expire = datetime.now(timezone.utc) + timedelta(days=ACCESS_TOKEN_EXPIRE_DAYS)
to_encode.update({"exp": expire, "iat": datetime.now(timezone.utc)})
return jwt.encode(to_encode, settings.JWT_SECRET, algorithm=ALGORITHM)
def decode_token(token: str) -> dict | None:
try:
return jwt.decode(token, settings.JWT_SECRET, algorithms=[ALGORITHM])
except JWTError:
return None
def _client_ip(request: Request | None) -> str | None:
if request is None:
return None
xff = request.headers.get("x-forwarded-for")
if xff:
first = xff.split(",")[0].strip()
if first:
return first
xri = request.headers.get("x-real-ip")
if xri:
return xri.strip()
return request.client.host if request.client else None
def check_rate_limit(key_id: str, limit_per_min: int, now: float | None = None) -> dict[str, Any]:
now_ts = now if now is not None else time.time()
limit = max(1, limit_per_min or 60)
cutoff = now_ts - _WINDOW_SECS
stamps = [ts for ts in _rate_buckets.get(key_id, []) if ts > cutoff]
if len(stamps) >= limit:
oldest = stamps[0] if stamps else now_ts
reset_ts = oldest + _WINDOW_SECS
retry_after = max(1, math.ceil(reset_ts - now_ts))
_rate_buckets[key_id] = stamps
return {
"ok": False,
"limit": limit,
"remaining": 0,
"reset_at": math.ceil(reset_ts),
"retry_after": retry_after,
}
stamps.append(now_ts)
_rate_buckets[key_id] = stamps
oldest = stamps[0] if stamps else now_ts
reset_ts = oldest + _WINDOW_SECS
return {
"ok": True,
"limit": limit,
"remaining": max(0, limit - len(stamps)),
"reset_at": math.ceil(reset_ts),
"retry_after": 0,
}
async def registrar_auditoria(
conn,
auth: dict | None,
accion: str,
recurso_tipo: str,
recurso_id: str | None = None,
exito: bool = True,
detalle: dict[str, Any] | None = None,
ip: str | None = None,
) -> None:
"""Registra una entrada en AuditLog (best-effort; nunca tumba el request)."""
try:
actor_tipo = "system"
actor_id: str | None = None
actor_nombre = "system"
if auth:
atype = auth.get("auth_type")
if atype == "jwt":
actor_tipo = "user"
actor_id = auth.get("userId")
actor_nombre = auth.get("email") or auth.get("name") or str(actor_id or "user")
elif atype == "agent":
actor_tipo = "agent"
actor_id = auth.get("key_id")
actor_nombre = auth.get("nombre") or "agent"
elif atype == "legacy_api_key":
actor_tipo = "system"
actor_nombre = "legacy_api_key"
ip_final = ip or (auth.get("ip") if auth else None)
await conn.execute(
"""
INSERT INTO "AuditLog"
(id, "actorTipo", "actorId", "actorNombre", accion, "recursoTipo",
"recursoId", ip, exito, detalle, "createdAt")
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10::jsonb, NOW())
""",
uuid.uuid4().hex[:25],
actor_tipo,
actor_id,
actor_nombre,
accion,
recurso_tipo,
recurso_id,
ip_final,
exito,
json.dumps(detalle) if detalle is not None else None,
)
except Exception:
pass
async def _validate_agent_key(raw_key: str, ip: str | None) -> dict | None:
pool = await get_pool()
key_hash = hash_secret(raw_key)
row = await pool.fetchrow(
"""
SELECT id, nombre, prefijo, scopes, "rateLimitPerMin", "lastUsedAt"
FROM "AgentApiKey"
WHERE "keyHash" = $1 AND activo = true AND "revokedAt" IS NULL
""",
key_hash,
)
if not row:
return None
rl = check_rate_limit(row["id"], row["rateLimitPerMin"])
actor = {
"auth_type": "agent",
"key_id": row["id"],
"nombre": row["nombre"],
"prefijo": row["prefijo"],
"scopes": list(row["scopes"] or []),
"rate_limit": row["rateLimitPerMin"],
"ip": ip,
}
if not rl["ok"]:
await registrar_auditoria(
pool,
actor,
"auth.rate_limit",
"api",
exito=False,
detalle={"limit": rl["limit"]},
ip=ip,
)
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail="Limite de peticiones por minuto excedido",
headers={
"X-RateLimit-Limit": str(rl["limit"]),
"X-RateLimit-Remaining": "0",
"X-RateLimit-Reset": str(rl["reset_at"]),
"Retry-After": str(rl["retry_after"]),
},
)
last_used = row["lastUsedAt"]
now_dt = datetime.now(timezone.utc)
if last_used is None or (
now_dt - (last_used.replace(tzinfo=timezone.utc) if last_used.tzinfo is None else last_used)
).total_seconds() > 60:
try:
await pool.execute(
'UPDATE "AgentApiKey" SET "lastUsedAt" = NOW() WHERE id = $1',
row["id"],
)
except Exception:
pass
return actor
async def require_auth(
request: Request,
authorization: str | None = Header(None),
x_api_key: str | None = Header(None),
) -> dict:
ip = _client_ip(request)
bearer_token: str | None = None
if authorization:
scheme, _, token = authorization.partition(" ")
if scheme.lower() == "bearer" and token.strip():
bearer_token = token.strip()
# 1. Intentar JWT humano primero
payload = decode_token(bearer_token)
if payload:
if payload.get("role") == "cliente":
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Acceso restringido al panel de cliente",
)
return {"auth_type": "jwt", "ip": ip, **payload}
raw_key = (x_api_key or "").strip() or bearer_token
if raw_key:
# 2. Validar contra AgentApiKey en PostgreSQL (SHA-256)
agent_actor = await _validate_agent_key(raw_key, ip)
if agent_actor:
return agent_actor
# 3. Compatibilidad legacy SOLO si ALLOW_LEGACY_API_KEY=true explicitamente
if settings.ALLOW_LEGACY_API_KEY and raw_key == settings.API_KEY:
return {"auth_type": "legacy_api_key", "scopes": [], "ip": ip}
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Credenciales de autenticacion invalidas o ausentes",
headers={"WWW-Authenticate": "Bearer"},
)
def require_scope(*required_scopes: str, mode: str = "any"):
async def _checker(
request: Request,
auth: dict = Depends(require_auth),
) -> dict:
atype = auth.get("auth_type")
if atype in ("jwt", "legacy_api_key"):
return auth
scopes = set(auth.get("scopes") or [])
ok = (
all(s in scopes for s in required_scopes)
if mode == "all"
else any(s in scopes for s in required_scopes)
)
if not ok:
pool = await get_pool()
await registrar_auditoria(
pool,
auth,
"auth.scope_insuficiente",
"api",
exito=False,
detalle={
"path": request.url.path,
"requiredScopes": list(required_scopes),
"actorScopes": list(scopes),
},
ip=auth.get("ip"),
)
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Alcance insuficiente. Requerido: {', '.join(required_scopes)}",
)
return auth
return _checker
async def require_staff_human(
request: Request,
auth: dict = Depends(require_auth),
) -> dict:
atype = auth.get("auth_type")
if atype == "jwt" and auth.get("role") != "cliente":
return auth
if atype == "legacy_api_key":
return auth
pool = await get_pool()
await registrar_auditoria(
pool,
auth,
"auth.staff_requerido",
"api",
exito=False,
detalle={"path": request.url.path, "auth_type": atype},
ip=auth.get("ip"),
)
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Accion restringida a personal humano",
)
async def require_admin_human(
request: Request,
auth: dict = Depends(require_auth),
) -> dict:
if auth.get("auth_type") == "jwt" and auth.get("role") == "admin":
return auth
pool = await get_pool()
await registrar_auditoria(
pool,
auth,
"auth.admin_requerido",
"api",
exito=False,
detalle={"path": request.url.path, "auth_type": auth.get("auth_type")},
ip=auth.get("ip"),
)
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Accion restringida exclusivamente a un administrador humano",
)
def es_agente_solo_aceptadas(auth: dict) -> bool:
if auth.get("auth_type") != "agent":
return False
scopes = set(auth.get("scopes") or [])
return "cotizaciones:leer_aceptadas" in scopes and "cotizaciones:leer" not in scopes