Spaces:
Paused
Paused
dushyantsingh0 commited on
Commit ·
2dfe0ae
1
Parent(s): 3aef1db
security: enforce strict portal isolation and role-based guards
Browse filesFiles changed (4)
42 unmodified lines4344454647481 unmodified line505152535455565758596061626364656667686970717273747576777879808123 unmodified lines10510610710810911011111211311411511624 unmodified lines14114214314414514642 unmodified linesasync def get_current_user(db: AsyncSession = Depends(get_db),token: str = Depends(oauth2_scheme)) -> User:1 unmodified lineDecodes the JWT access token and fetches the current user from the database.Raises HTTPException if token is invalid or user doesn't exist."""credentials_exception = HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,detail="Could not validate credentials",headers={"WWW-Authenticate": "Bearer"},)try:payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])user_id: str = payload.get("sub")token_type: str = payload.get("type")jti: str = payload.get("jti")# Multi-workspace context from JWTactive_ws_id: str = payload.get("workspace_id")active_role: str = payload.get("role")if user_id is None or token_type != "access":raise credentials_exception# Check if token has been revoked (logout blocklist)if jti:from core.token_blocklist import is_token_blockedif await is_token_blocked(jti):raise credentials_exceptionexcept JWTError:raise credentials_exceptionreturn await get_current_user_from_token(token, db)async def get_current_user_flexible(23 unmodified linesheaders={"WWW-Authenticate": "Bearer"},)# Reuse the same validation logic but without the oauth2_scheme dependencyreturn await get_current_user_from_token(token, db)async def get_current_user_from_token(token: str, db: AsyncSession) -> User:"""Refactored logic from get_current_user for reuse."""credentials_exception = HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,detail="Could not validate credentials",24 unmodified linesif user is None or not user.is_active:raise credentials_exceptionfrom uuid import UUIDsetattr(user, "workspace_id", UUID(active_ws_id) if active_ws_id else None)setattr(user, "role", active_role)42 unmodified lines434445464748491 unmodified line515253545556575823 unmodified lines82838485868788899091929324 unmodified lines11811912012112212312412512612712812913013113213313413513613713813914042 unmodified linesasync def get_current_user(request: Request,db: AsyncSession = Depends(get_db),token: str = Depends(oauth2_scheme)) -> User:1 unmodified lineDecodes the JWT access token and fetches the current user from the database.Raises HTTPException if token is invalid or user doesn't exist."""portal = request.headers.get("X-Nexus-Portal")return await get_current_user_from_token(token, db, portal)async def get_current_user_flexible(23 unmodified linesheaders={"WWW-Authenticate": "Bearer"},)portal = request.headers.get("X-Nexus-Portal")return await get_current_user_from_token(token, db, portal)async def get_current_user_from_token(token: str, db: AsyncSession, portal: Optional[str] = None) -> User:"""Refactored logic from get_current_user for reuse with portal validation."""credentials_exception = HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,detail="Could not validate credentials",24 unmodified linesif user is None or not user.is_active:raise credentials_exception# --- STRICT PORTAL ISOLATION (Backend Guard) ---from models.user import UserRoleif portal == "internal" and active_role not in [UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN]:# Log this attempt for security auditimport logginglogging.getLogger("security").warning(f"BLOCKED: Customer {user.email} attempted internal portal API access")raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,detail="Access Denied: Customers cannot access internal operations endpoints.")elif portal == "customer" and active_role not in [UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER, UserRole.SC_ADMIN]:# Staff can only access the customer portal if they are SC_ADMIN (Super Admin)raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,detail="Access Denied: Staff must use the Operations Console.")from uuid import UUIDsetattr(user, "workspace_id", UUID(active_ws_id) if active_ws_id else None)setattr(user, "role", active_role)
33 unmodified lines34353637383933 unmodified linesreturn <LoginCard onLogin={login} loading={authLoading} portal="customer" error={authError} />;}// Pre-load logic: Only show splash if we haven't entered the portal yet.// We gate only on Auth and the first tick of identity.const isHydrating = !booted && (authLoading && !user);33 unmodified lines34353637383940414243444546474849505152535455565733 unmodified linesreturn <LoginCard onLogin={login} loading={authLoading} portal="customer" error={authError} />;}// --- STRICT PORTAL GUARD: Customers Only + Super Admins ---const isCustomer = user && (user.role === 'customer_admin' || user.role === 'customer_user' || user.role === '3sc_admin');if (user && !isCustomer) {return (<div className="nexus-unauthorized-overlay"><div className="nexus-unauthorized-box"><NexusLogo subtitle="RESTRICTED ENTRY" /><h1>Staff Redirection</h1><p>You are logged in as 3SC Operations Staff. Please use the Internal Operations Console for security and audit compliance.</p><div className="nexus-unauthorized-actions"><button onClick={() => window.location.href = '/admin/'} className="nexus-btn-primary">Go to Operations Console</button><button onClick={logout} className="nexus-btn-secondary">Logout</button></div></div></div>);}// Pre-load logic: Only show splash if we haven't entered the portal yet.// We gate only on Auth and the first tick of identity.const isHydrating = !booted && (authLoading && !user);
50 unmodified lines51525354555650 unmodified lines);}// Pre-load logic: We wait for auth AND for the first set of stats to arrive.// AI/Narrative loading is now "soft" to avoid navigation flickers.const isInitialLoading = (authLoading && !user) || (user && (50 unmodified lines51525354555657585960616263646566676869707172737450 unmodified lines);}// --- STRICT PORTAL GUARD: Internal Staff Only ---const isStaff = hasRole(['3sc_admin', '3sc_lead', '3sc_agent']);if (user && !isStaff) {return (<div className="nexus-unauthorized-overlay"><div className="nexus-unauthorized-box"><NexusLogo subtitle="SECURITY CLEARANCE DENIED" /><h1>Access Forbidden</h1><p>This portal is reserved for 3SC Operations Staff. Your account identity is restricted to the Customer Portal.</p><div className="nexus-unauthorized-actions"><button onClick={() => window.location.href = '/'} className="nexus-btn-primary">Return to Customer Portal</button><button onClick={logout} className="nexus-btn-secondary">Logout and Switch Account</button></div></div></div>);}// Pre-load logic: We wait for auth AND for the first set of stats to arrive.// AI/Narrative loading is now "soft" to avoid navigation flickers.const isInitialLoading = (authLoading && !user) || (user && (
101 unmodified lines10210310410510610744 unmodified lines152153154155156157101 unmodified lines# --- SLEDGEHAMMER CORS: FORCE HEADERS ON ALL RESPONSES ---@app.middleware("http")async def force_cors_middleware(request: Request, call_next):origin = request.headers.get("origin")if request.method == "OPTIONS":response = JSONResponse(content="OK")44 unmodified linesapp.include_router(reports.router, prefix=f"{settings.API_V1_STR}/reports", tags=["reports"])app.include_router(nexus.router, prefix=f"{settings.API_V1_STR}/nexus", tags=["Nexus Master Agent"])app.include_router(nexus_stream.router, prefix=f"{settings.API_V1_STR}/nexus", tags=["Nexus Master Agent"])import osfrom fastapi.staticfiles import StaticFiles101 unmodified lines10210310410510610710810911011111244 unmodified lines157158159160161162163101 unmodified lines# --- SLEDGEHAMMER CORS: FORCE HEADERS ON ALL RESPONSES ---@app.middleware("http")async def force_cors_middleware(request: Request, call_next):# Skip CORS logic for WebSockets (they have their own handshake mechanisms)if "upgrade" in request.headers.get("connection", "").lower() and \request.headers.get("upgrade", "").lower() == "websocket":return await call_next(request)origin = request.headers.get("origin")if request.method == "OPTIONS":response = JSONResponse(content="OK")44 unmodified linesapp.include_router(reports.router, prefix=f"{settings.API_V1_STR}/reports", tags=["reports"])app.include_router(nexus.router, prefix=f"{settings.API_V1_STR}/nexus", tags=["Nexus Master Agent"])app.include_router(nexus_stream.router, prefix=f"{settings.API_V1_STR}/nexus", tags=["Nexus Master Agent"])app.include_router(websockets.router, tags=["websockets"]) # Included at root to match frontend /ws/ logicimport osfrom fastapi.staticfiles import StaticFiles
core/deps.py+24-30
frontend/apps/customer/src/App.tsx+18
frontend/apps/internal/src/App.tsx+18
main.py+6