briga-core-api / app /utils /security.py
yabeskn's picture
feat: sync briga-backend β€” 2026 fallback chain (Gemini->OpenRouter :free->Groq), per-agent tier override, supabase JWT auth, agents router, retry columns
3a006a3 verified
Raw History Blame Contribute Delete
6.65 kB
"""Security utilities β€” password hashing, JWT, rate limiting.
Zero-cost: bcrypt, PyJWT, in-memory rate limiter.
No Redis. No external services. Free for 10K users.
"""
import hashlib
import secrets
import time
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, List, Optional
import jwt as pyjwt
import httpx
from loguru import logger
from passlib.context import CryptContext
from app.config.settings import settings
# ─── Password Hashing ───────────────────────────────────────────────────────
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def hash_password(password: str) -> str:
return pwd_context.hash(password)
def verify_password(plain: str, hashed: str) -> bool:
try:
return pwd_context.verify(plain, hashed)
except Exception:
return False # Sentinel values like "GOOGLE_OAUTH" won't crash
def hash_legacy_gas_password(password: str, email: str, salt: str = "BRIGAWAN_AUTH_SALT_2026") -> str:
"""Replicate GAS hashPassword() for backward compatibility."""
pre_hash = hashlib.sha256((password + email.lower()).encode()).hexdigest()
return hashlib.sha256((pre_hash + salt).encode()).hexdigest()
# ─── JWT ────────────────────────────────────────────────────────────────────
def create_access_token(subject: str, email: str, role: str = "talent",
expires_delta: Optional[timedelta] = None) -> str:
now = datetime.now(timezone.utc)
payload = {
"sub": subject, "email": email, "role": role,
"iat": now, "exp": now + (expires_delta or timedelta(hours=settings.jwt_expiry_hours)),
}
return pyjwt.encode(payload, settings.jwt_secret, algorithm=settings.jwt_algorithm)
def decode_access_token(token: str) -> Optional[Dict[str, Any]]:
try:
return pyjwt.decode(token, settings.jwt_secret, algorithms=[settings.jwt_algorithm])
except (pyjwt.ExpiredSignatureError, pyjwt.InvalidTokenError):
return None
async def verify_supabase_token(token: str) -> Optional[Dict[str, Any]]:
"""Verify standard JWT token directly with Supabase Auth server."""
if not settings.supabase_url or not settings.supabase_anon_key:
logger.warning("Supabase URL or Anon Key is missing from settings")
return None
try:
async with httpx.AsyncClient(timeout=10.0) as client:
headers = {
"apikey": settings.supabase_anon_key,
"Authorization": f"Bearer {token}"
}
response = await client.get(f"{settings.supabase_url}/auth/v1/user", headers=headers)
if response.status_code == 200:
data = response.json()
email = data.get("email")
user_id = data.get("id")
app_metadata = data.get("app_metadata", {})
user_metadata = data.get("user_metadata", {})
role = user_metadata.get("role") or app_metadata.get("role") or "talent"
return {
"sub": user_id,
"email": email,
"role": role,
"name": user_metadata.get("full_name") or user_metadata.get("name") or "User"
}
else:
logger.warning(f"Supabase auth check returned status {response.status_code}: {response.text}")
except Exception as e:
logger.error(f"Failed to verify token with Supabase: {str(e)}")
return None
def generate_session_token() -> str:
return secrets.token_urlsafe(32)
# ─── In-Memory Rate Limiter ─────────────────────────────────────────────────
class RateLimiter:
"""Sliding-window in-memory rate limiter.
Max 15K tracked IPs. Oldest entries evicted when limit exceeded.
Free tier: 100 req/hr. Authenticated: up to 2000 req/hr.
"""
def __init__(self, max_requests: int = 100, window_seconds: int = 3600, max_buckets: int = 15000):
self.max_requests = max_requests
self.window_seconds = window_seconds
self.max_buckets = max_buckets
self._buckets: Dict[str, list] = {}
self._prune_counter = 0
self._prune_threshold = 100
def is_allowed(self, key: str, limit: Optional[int] = None) -> bool:
"""Check if request is allowed under the given (or default) limit.
Args:
key: The rate-limit bucket key (e.g. client IP).
limit: Optional per-request limit override. If None, uses self.max_requests.
"""
now = time.time()
cutoff = now - self.window_seconds
effective_limit = limit if limit is not None else self.max_requests
# Evict oldest bucket if over limit
if len(self._buckets) >= self.max_buckets and key not in self._buckets:
oldest = min(self._buckets.keys(), key=lambda k: self._buckets[k][-1] if self._buckets[k] else 0)
del self._buckets[oldest]
if key not in self._buckets:
self._buckets[key] = []
# Prune expired timestamps
bucket = [t for t in self._buckets[key] if t > cutoff]
self._buckets[key] = bucket
if len(bucket) >= effective_limit:
return False
self._buckets[key].append(now)
self._prune_counter += 1
if self._prune_counter >= self._prune_threshold:
self._prune()
self._prune_counter = 0
return True
def _prune(self):
now = time.time()
cutoff = now - self.window_seconds * 2
stale = [k for k, v in self._buckets.items() if not v or max(v) < cutoff]
for k in stale:
del self._buckets[k]
def get_remaining(self, key: str, limit: Optional[int] = None) -> int:
effective_limit = limit if limit is not None else self.max_requests
if key not in self._buckets:
return effective_limit
bucket = [t for t in self._buckets[key] if t > time.time() - self.window_seconds]
return max(0, effective_limit - len(bucket))
rate_limiter = RateLimiter(max_requests=100, window_seconds=3600)