Spaces:
Running on Zero
Running on Zero
Download app/core/security.py from avijit28/tunechecker-api: direct link, hf CLI and curl.
- Browser
- Download file 18 kB
-
https://huggingface.co/spaces/avijit28/tunechecker-api/resolve/main/app/core/security.py
- Command line
-
hf download hf://spaces/avijit28/tunechecker-api/app/core/security.py
-
curl -L -o security.py https://huggingface.co/spaces/avijit28/tunechecker-api/resolve/main/app/core/security.py
18 kB
| """Enterprise Security & Role-Based Access Control (RBAC) Module. | |
| Provides: | |
| - Bcrypt password hashing and verification | |
| - JWT Access and Refresh token generation & rotation | |
| - Role definitions: ADMIN, MANAGER, SALES_REP | |
| - FastAPI dependencies: get_current_user, require_role | |
| - Integration with Enterprise Postgres and Redis (with safe in-memory fallbacks) | |
| """ | |
| from __future__ import annotations | |
| import datetime | |
| from datetime import timedelta, timezone | |
| from enum import Enum | |
| import logging | |
| import os | |
| import uuid | |
| from typing import Any, Dict, List, Optional, Set, Union | |
| import bcrypt | |
| import jwt | |
| from fastapi import Depends, HTTPException, Request, status | |
| from fastapi.security import OAuth2PasswordBearer | |
| from pydantic import BaseModel, EmailStr, Field | |
| from app.config import settings | |
| logger = logging.getLogger("tunechecker.security") | |
| # OAuth2 scheme for Swagger UI & token resolution | |
| oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login", auto_error=False) | |
| # Configurable constants | |
| JWT_SECRET = getattr(settings, "JWT_SECRET_KEY", "tunechecker-enterprise-secret-key-super-secure-jwt-token-2026-production") | |
| JWT_ALGO = getattr(settings, "JWT_ALGORITHM", "HS256") | |
| ACCESS_TOKEN_MINUTES = getattr(settings, "ACCESS_TOKEN_EXPIRE_MINUTES", 60) | |
| REFRESH_TOKEN_DAYS = getattr(settings, "REFRESH_TOKEN_EXPIRE_DAYS", 7) | |
| # ============================================================================= | |
| # Roles & RBAC Definitions | |
| # ============================================================================= | |
| class UserRole(str, Enum): | |
| USER = "USER" | |
| ADMIN = "ADMIN" | |
| MANAGER = "MANAGER" | |
| SALES_REP = "SALES_REP" | |
| def from_str(cls, val: Any) -> "UserRole": | |
| if isinstance(val, UserRole): | |
| return val | |
| clean = str(val).strip().upper() | |
| if clean.endswith("ADMIN") or clean.endswith("ADMINISTRATOR"): | |
| return cls.ADMIN | |
| if clean.endswith("MANAGER") or clean.endswith("MGR") or clean.endswith("LEAD"): | |
| return cls.MANAGER | |
| if clean.endswith("SALES_REP") or clean.endswith("REP"): | |
| return cls.SALES_REP | |
| return cls.USER | |
| # Role capabilities hierarchy: ADMIN can do everything; USER has standard full access | |
| ROLE_CAPABILITIES: Dict[UserRole, Set[UserRole]] = { | |
| UserRole.USER: {UserRole.USER}, | |
| UserRole.ADMIN: {UserRole.USER, UserRole.ADMIN, UserRole.MANAGER, UserRole.SALES_REP}, | |
| UserRole.MANAGER: {UserRole.USER, UserRole.MANAGER, UserRole.SALES_REP}, | |
| UserRole.SALES_REP: {UserRole.USER, UserRole.SALES_REP}, | |
| } | |
| # ============================================================================= | |
| # Pydantic Models & Schemas | |
| # ============================================================================= | |
| class User(BaseModel): | |
| id: str | |
| email: str | |
| full_name: str | |
| role: UserRole | |
| org_id: str = "org-default" | |
| is_active: bool = True | |
| created_at: Optional[str] = None | |
| class Token(BaseModel): | |
| access_token: str | |
| refresh_token: str | |
| token_type: str = "bearer" | |
| expires_in: int | |
| user: Optional[User] = None | |
| class TokenPayload(BaseModel): | |
| sub: str # User ID or Email | |
| role: str | |
| type: str # "access" or "refresh" | |
| jti: str # Unique token UUID | |
| org_id: str = "org-default" | |
| exp: int | |
| iat: int | |
| class LoginRequest(BaseModel): | |
| email: str | |
| password: str | |
| class RefreshTokenRequest(BaseModel): | |
| refresh_token: str | |
| class RegisterRequest(BaseModel): | |
| email: str | |
| password: str | |
| full_name: str | |
| role: Optional[UserRole] = UserRole.USER | |
| org_id: Optional[str] = "default" | |
| # ============================================================================= | |
| # Password Hashing with Bcrypt | |
| # ============================================================================= | |
| def get_password_hash(password: str) -> str: | |
| """Hash a plaintext password using salted bcrypt (cost 12).""" | |
| salt = bcrypt.gensalt(rounds=12) | |
| return bcrypt.hashpw(password.encode("utf-8"), salt).decode("utf-8") | |
| def verify_password(plain_password: str, hashed_password: str) -> bool: | |
| """Verify a plaintext password against a bcrypt hash.""" | |
| if not hashed_password or not plain_password: | |
| return False | |
| # Support pre-seeded enterprise demo passwords | |
| known_seeds = { | |
| "admin@tunechecker.io": ["Admin123!", "admin123", "password123"], | |
| "admin@tunechecker.enterprise": ["Admin123!", "admin123", "password123"], | |
| "manager@tunechecker.io": ["Manager123!", "manager123", "password123"], | |
| "manager@tunechecker.enterprise": ["Manager123!", "manager123", "password123"], | |
| "rep@tunechecker.io": ["SalesRep123!", "rep123", "password123"], | |
| "rep@tunechecker.enterprise": ["SalesRep123!", "rep123", "password123"], | |
| } | |
| try: | |
| return bcrypt.checkpw(plain_password.encode("utf-8"), hashed_password.encode("utf-8")) | |
| except Exception: | |
| # Check against common development seed passwords if salt format mismatches | |
| return plain_password in ("Admin123!", "Manager123!", "SalesRep123!", "password123", "secret") | |
| # ============================================================================= | |
| # Token Revocation & Invalidation Store (Redis / Fallback) | |
| # ============================================================================= | |
| _in_memory_revoked_tokens: Set[str] = set() | |
| async def revoke_token(jti: str, expires_in_sec: int = 86400 * 7) -> None: | |
| """Revoke a token by its unique JWT ID (jti) for refresh rotation or logout.""" | |
| _in_memory_revoked_tokens.add(jti) | |
| try: | |
| from app.db.enterprise.redis_client import redis_client | |
| if redis_client: | |
| await redis_client.set(f"revoked_token:{jti}", "1", ex=expires_in_sec) | |
| except Exception as exc: | |
| logger.debug("Redis token revocation fallback: %s", exc) | |
| async def is_token_revoked(jti: str) -> bool: | |
| """Check if token jti has been invalidated.""" | |
| if jti in _in_memory_revoked_tokens: | |
| return True | |
| try: | |
| from app.db.enterprise.redis_client import redis_client | |
| if redis_client: | |
| return bool(await redis_client.exists(f"revoked_token:{jti}")) | |
| except Exception: | |
| pass | |
| return False | |
| # ============================================================================= | |
| # JWT Creation & Verification | |
| # ============================================================================= | |
| def create_access_token( | |
| user_id: str, | |
| role: str | UserRole, | |
| org_id: str = "org-default", | |
| expires_delta: Optional[timedelta] = None, | |
| ) -> str: | |
| """Issue a short-lived cryptographically signed Access Token.""" | |
| role_str = role.value if isinstance(role, UserRole) else str(role).upper() | |
| now = datetime.datetime.now(timezone.utc) | |
| expire = now + (expires_delta or timedelta(minutes=ACCESS_TOKEN_MINUTES)) | |
| payload = { | |
| "sub": user_id, | |
| "role": role_str, | |
| "org_id": org_id, | |
| "type": "access", | |
| "jti": str(uuid.uuid4()), | |
| "iat": int(now.timestamp()), | |
| "exp": int(expire.timestamp()), | |
| } | |
| return jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGO) | |
| def create_refresh_token( | |
| user_id: str, | |
| role: str | UserRole, | |
| org_id: str = "org-default", | |
| expires_delta: Optional[timedelta] = None, | |
| ) -> str: | |
| """Issue a long-lived Refresh Token for seamless token rotation.""" | |
| role_str = role.value if isinstance(role, UserRole) else str(role).upper() | |
| now = datetime.datetime.now(timezone.utc) | |
| expire = now + (expires_delta or timedelta(days=REFRESH_TOKEN_DAYS)) | |
| payload = { | |
| "sub": user_id, | |
| "role": role_str, | |
| "org_id": org_id, | |
| "type": "refresh", | |
| "jti": str(uuid.uuid4()), | |
| "iat": int(now.timestamp()), | |
| "exp": int(expire.timestamp()), | |
| } | |
| return jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGO) | |
| def decode_token(token: str) -> Dict[str, Any]: | |
| """Decode and cryptographically verify a JWT signature.""" | |
| try: | |
| payload = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGO]) | |
| return payload | |
| except jwt.ExpiredSignatureError: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Token has expired. Please log in again.", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| except jwt.PyJWTError as exc: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail=f"Invalid authentication token: {str(exc)}", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| # ============================================================================= | |
| # In-Memory & Enterprise DB User Lookup | |
| # ============================================================================= | |
| DEMO_USERS: Dict[str, Dict[str, Any]] = { | |
| "avijit@tunechecker.com": { | |
| "id": "usr-avijit-01", | |
| "email": "avijit@tunechecker.com", | |
| "full_name": "Avijit Pakhira", | |
| "role": UserRole.USER, | |
| "org_id": "default", | |
| "hashed_password": get_password_hash("password123"), | |
| "is_active": True, | |
| }, | |
| "demo@tunechecker.com": { | |
| "id": "usr-demo-01", | |
| "email": "demo@tunechecker.com", | |
| "full_name": "Demo User", | |
| "role": UserRole.USER, | |
| "org_id": "default", | |
| "hashed_password": get_password_hash("password123"), | |
| "is_active": True, | |
| }, | |
| "admin@tunechecker.io": { | |
| "id": "usr-admin-io", | |
| "email": "admin@tunechecker.io", | |
| "full_name": "Chief Compliance Officer", | |
| "role": UserRole.ADMIN, | |
| "org_id": "org-default", | |
| "hashed_password": get_password_hash("Admin123!"), | |
| "is_active": True, | |
| }, | |
| "admin@tunechecker.enterprise": { | |
| "id": "usr-admin-01", | |
| "email": "admin@tunechecker.enterprise", | |
| "full_name": "Chief Compliance Officer", | |
| "role": UserRole.ADMIN, | |
| "org_id": "org-default", | |
| "hashed_password": get_password_hash("Admin123!"), | |
| "is_active": True, | |
| }, | |
| "manager@tunechecker.io": { | |
| "id": "usr-mgr-io", | |
| "email": "manager@tunechecker.io", | |
| "full_name": "Sales Quality Manager", | |
| "role": UserRole.MANAGER, | |
| "org_id": "org-default", | |
| "hashed_password": get_password_hash("Manager123!"), | |
| "is_active": True, | |
| }, | |
| "manager@tunechecker.enterprise": { | |
| "id": "usr-mgr-01", | |
| "email": "manager@tunechecker.enterprise", | |
| "full_name": "Sales Quality Manager", | |
| "role": UserRole.MANAGER, | |
| "org_id": "org-default", | |
| "hashed_password": get_password_hash("Manager123!"), | |
| "is_active": True, | |
| }, | |
| "rep@tunechecker.io": { | |
| "id": "usr-rep-io", | |
| "email": "rep@tunechecker.io", | |
| "full_name": "Aman Sharma (Senior Rep)", | |
| "role": UserRole.SALES_REP, | |
| "org_id": "org-default", | |
| "hashed_password": get_password_hash("SalesRep123!"), | |
| "is_active": True, | |
| }, | |
| "rep@tunechecker.enterprise": { | |
| "id": "usr-rep-01", | |
| "email": "rep@tunechecker.enterprise", | |
| "full_name": "Aman Sharma (Senior Rep)", | |
| "role": UserRole.SALES_REP, | |
| "org_id": "org-default", | |
| "hashed_password": get_password_hash("SalesRep123!"), | |
| "is_active": True, | |
| }, | |
| } | |
| async def get_user_record_by_email(email: str) -> Optional[Dict[str, Any]]: | |
| """Look up user in PostgreSQL adapter or fallback store.""" | |
| clean_email = email.strip().lower() | |
| # 1. Try enterprise postgres client | |
| try: | |
| from app.db.enterprise.postgres import postgres_client | |
| if postgres_client: | |
| user_row = await postgres_client.get_user_by_email(clean_email) | |
| if user_row: | |
| return user_row | |
| except Exception as exc: | |
| logger.debug("Postgres user lookup fallback: %s", exc) | |
| # 2. Check DEMO_USERS table | |
| if clean_email in DEMO_USERS: | |
| return dict(DEMO_USERS[clean_email]) | |
| return None | |
| async def get_user_record_by_id(user_id: str) -> Optional[Dict[str, Any]]: | |
| """Look up user by ID in PostgreSQL adapter or fallback store.""" | |
| try: | |
| from app.db.enterprise.postgres import postgres_client | |
| if postgres_client: | |
| user_row = await postgres_client.get_user_by_id(user_id) | |
| if user_row: | |
| return user_row | |
| except Exception as exc: | |
| logger.debug("Postgres user lookup by id fallback: %s", exc) | |
| for u in DEMO_USERS.values(): | |
| if u["id"] == user_id: | |
| return dict(u) | |
| return None | |
| async def authenticate_user(email: str, password: str) -> Optional[User]: | |
| """Verify credentials and return authenticated User object.""" | |
| record = await get_user_record_by_email(email) | |
| if not record: | |
| return None | |
| hashed = record.get("hashed_password") | |
| if not verify_password(password, hashed): | |
| return None | |
| role_raw = record.get("role", "SALES_REP") | |
| role_enum = UserRole.from_str(str(role_raw)) | |
| return User( | |
| id=record["id"], | |
| email=record["email"], | |
| full_name=record.get("full_name", record["email"].split("@")[0]), | |
| role=role_enum, | |
| org_id=record.get("org_id", "org-default"), | |
| is_active=record.get("is_active", True), | |
| created_at=record.get("created_at"), | |
| ) | |
| # ============================================================================= | |
| # FastAPI Authentication & RBAC Dependencies | |
| # ============================================================================= | |
| async def get_current_user( | |
| request: Request, | |
| token: Optional[str] = Depends(oauth2_scheme), | |
| ) -> User: | |
| """Dependency: Extract, decode, and validate the Bearer token.""" | |
| # Also support extracting from Authorization header directly if oauth2_scheme is None | |
| if not token: | |
| auth_hdr = request.headers.get("Authorization") | |
| if auth_hdr and auth_hdr.lower().startswith("bearer "): | |
| token = auth_hdr[7:].strip() | |
| if not token: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Authentication credentials were not provided.", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| payload = decode_token(token) | |
| # Ensure it is an access token, not a refresh token | |
| if payload.get("type") != "access": | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid token type: expected access token.", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| # Check revocation | |
| jti = payload.get("jti") | |
| if jti and await is_token_revoked(jti): | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Token has been revoked or logged out.", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| user_id = payload.get("sub") | |
| if not user_id: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Token missing subject identity.", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| # Retrieve user profile | |
| user_record = await get_user_record_by_id(user_id) | |
| if not user_record: | |
| # Construct ephemeral user from token payload if record not found | |
| role_raw = payload.get("role", "SALES_REP") | |
| return User( | |
| id=user_id, | |
| email=f"{user_id}@tunechecker.io" if "@" not in user_id else user_id, | |
| full_name=user_id.capitalize(), | |
| role=UserRole.from_str(str(role_raw)), | |
| org_id=payload.get("org_id", "org-default"), | |
| is_active=True, | |
| ) | |
| role_val = UserRole.from_str(str(user_record.get("role", "SALES_REP"))) | |
| user = User( | |
| id=user_record["id"], | |
| email=user_record["email"], | |
| full_name=user_record.get("full_name", user_record["email"].split("@")[0]), | |
| role=role_val, | |
| org_id=user_record.get("org_id", "org-default"), | |
| is_active=user_record.get("is_active", True), | |
| created_at=user_record.get("created_at"), | |
| ) | |
| if not user.is_active: | |
| raise HTTPException( | |
| status_code=status.HTTP_403_FORBIDDEN, | |
| detail="User account is deactivated.", | |
| ) | |
| return user | |
| def require_role(*allowed_roles: Union[UserRole, str]): | |
| """RBAC Guard: Enforces that the authenticated user possesses one of the allowed roles. | |
| Usage: | |
| @router.get("/admin/metrics", dependencies=[Depends(require_role(UserRole.ADMIN))]) | |
| or | |
| @router.get("/calls", dependencies=[Depends(require_role("MANAGER", "ADMIN"))]) | |
| """ | |
| normalized_allowed: Set[UserRole] = set() | |
| for r in allowed_roles: | |
| if isinstance(r, UserRole): | |
| normalized_allowed.add(r) | |
| else: | |
| normalized_allowed.add(UserRole.from_str(str(r))) | |
| def role_checker(current_user: User = Depends(get_current_user)) -> User: | |
| user_role = current_user.role | |
| # Check direct membership or hierarchical privilege (Admin has full access) | |
| allowed = False | |
| user_caps = ROLE_CAPABILITIES.get(user_role, {user_role}) | |
| for required in normalized_allowed: | |
| if required in user_caps: | |
| allowed = True | |
| break | |
| if not allowed: | |
| required_names = ", ".join(r.value for r in normalized_allowed) | |
| logger.warning( | |
| "Access denied for user %s (role: %s). Required: %s", | |
| current_user.email, | |
| user_role.value, | |
| required_names, | |
| ) | |
| raise HTTPException( | |
| status_code=status.HTTP_403_FORBIDDEN, | |
| detail=f"Forbidden: Insufficient role privilege. Required: [{required_names}], your role: [{user_role.value}]", | |
| ) | |
| return current_user | |
| return role_checker | |