Spaces:
Paused

dushyantsingh0 commited on
Commit
2dfe0ae
·
1 Parent(s): 3aef1db

security: enforce strict portal isolation and role-based guards

Browse files
core/deps.py CHANGED
@@ -43,6 +43,7 @@ async def get_arq_pool(request: Request):
43
 
44
 
45
  async def get_current_user(
 
46
  db: AsyncSession = Depends(get_db),
47
  token: str = Depends(oauth2_scheme)
48
  ) -> User:
@@ -50,32 +51,8 @@ async def get_current_user(
50
  Decodes the JWT access token and fetches the current user from the database.
51
  Raises HTTPException if token is invalid or user doesn't exist.
52
  """
53
- credentials_exception = HTTPException(
54
- status_code=status.HTTP_401_UNAUTHORIZED,
55
- detail="Could not validate credentials",
56
- headers={"WWW-Authenticate": "Bearer"},
57
- )
58
- try:
59
- payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
60
- user_id: str = payload.get("sub")
61
- token_type: str = payload.get("type")
62
- jti: str = payload.get("jti")
63
- # Multi-workspace context from JWT
64
- active_ws_id: str = payload.get("workspace_id")
65
- active_role: str = payload.get("role")
66
-
67
- if user_id is None or token_type != "access":
68
- raise credentials_exception
69
-
70
- # Check if token has been revoked (logout blocklist)
71
- if jti:
72
- from core.token_blocklist import is_token_blocked
73
- if await is_token_blocked(jti):
74
- raise credentials_exception
75
- except JWTError:
76
- raise credentials_exception
77
-
78
- return await get_current_user_from_token(token, db)
79
 
80
 
81
  async def get_current_user_flexible(
@@ -105,12 +82,12 @@ async def get_current_user_flexible(
105
  headers={"WWW-Authenticate": "Bearer"},
106
  )
107
 
108
- # Reuse the same validation logic but without the oauth2_scheme dependency
109
- return await get_current_user_from_token(token, db)
110
 
111
 
112
- async def get_current_user_from_token(token: str, db: AsyncSession) -> User:
113
- """Refactored logic from get_current_user for reuse."""
114
  credentials_exception = HTTPException(
115
  status_code=status.HTTP_401_UNAUTHORIZED,
116
  detail="Could not validate credentials",
@@ -141,6 +118,23 @@ async def get_current_user_from_token(token: str, db: AsyncSession) -> User:
141
  if user is None or not user.is_active:
142
  raise credentials_exception
143
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  from uuid import UUID
145
  setattr(user, "workspace_id", UUID(active_ws_id) if active_ws_id else None)
146
  setattr(user, "role", active_role)
 
43
 
44
 
45
  async def get_current_user(
46
+ request: Request,
47
  db: AsyncSession = Depends(get_db),
48
  token: str = Depends(oauth2_scheme)
49
  ) -> User:
 
51
  Decodes the JWT access token and fetches the current user from the database.
52
  Raises HTTPException if token is invalid or user doesn't exist.
53
  """
54
+ portal = request.headers.get("X-Nexus-Portal")
55
+ return await get_current_user_from_token(token, db, portal)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
 
58
  async def get_current_user_flexible(
 
82
  headers={"WWW-Authenticate": "Bearer"},
83
  )
84
 
85
+ portal = request.headers.get("X-Nexus-Portal")
86
+ return await get_current_user_from_token(token, db, portal)
87
 
88
 
89
+ async def get_current_user_from_token(token: str, db: AsyncSession, portal: Optional[str] = None) -> User:
90
+ """Refactored logic from get_current_user for reuse with portal validation."""
91
  credentials_exception = HTTPException(
92
  status_code=status.HTTP_401_UNAUTHORIZED,
93
  detail="Could not validate credentials",
 
118
  if user is None or not user.is_active:
119
  raise credentials_exception
120
 
121
+ # --- STRICT PORTAL ISOLATION (Backend Guard) ---
122
+ from models.user import UserRole
123
+ if portal == "internal" and active_role not in [UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN]:
124
+ # Log this attempt for security audit
125
+ import logging
126
+ logging.getLogger("security").warning(f"BLOCKED: Customer {user.email} attempted internal portal API access")
127
+ raise HTTPException(
128
+ status_code=status.HTTP_403_FORBIDDEN,
129
+ detail="Access Denied: Customers cannot access internal operations endpoints."
130
+ )
131
+ elif portal == "customer" and active_role not in [UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER, UserRole.SC_ADMIN]:
132
+ # Staff can only access the customer portal if they are SC_ADMIN (Super Admin)
133
+ raise HTTPException(
134
+ status_code=status.HTTP_403_FORBIDDEN,
135
+ detail="Access Denied: Staff must use the Operations Console."
136
+ )
137
+
138
  from uuid import UUID
139
  setattr(user, "workspace_id", UUID(active_ws_id) if active_ws_id else None)
140
  setattr(user, "role", active_role)
frontend/apps/customer/src/App.tsx CHANGED
@@ -34,6 +34,24 @@ export default function App() {
34
  return <LoginCard onLogin={login} loading={authLoading} portal="customer" error={authError} />;
35
  }
36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  // Pre-load logic: Only show splash if we haven't entered the portal yet.
38
  // We gate only on Auth and the first tick of identity.
39
  const isHydrating = !booted && (authLoading && !user);
 
34
  return <LoginCard onLogin={login} loading={authLoading} portal="customer" error={authError} />;
35
  }
36
 
37
+ // --- STRICT PORTAL GUARD: Customers Only + Super Admins ---
38
+ const isCustomer = user && (user.role === 'customer_admin' || user.role === 'customer_user' || user.role === '3sc_admin');
39
+ if (user && !isCustomer) {
40
+ return (
41
+ <div className="nexus-unauthorized-overlay">
42
+ <div className="nexus-unauthorized-box">
43
+ <NexusLogo subtitle="RESTRICTED ENTRY" />
44
+ <h1>Staff Redirection</h1>
45
+ <p>You are logged in as 3SC Operations Staff. Please use the Internal Operations Console for security and audit compliance.</p>
46
+ <div className="nexus-unauthorized-actions">
47
+ <button onClick={() => window.location.href = '/admin/'} className="nexus-btn-primary">Go to Operations Console</button>
48
+ <button onClick={logout} className="nexus-btn-secondary">Logout</button>
49
+ </div>
50
+ </div>
51
+ </div>
52
+ );
53
+ }
54
+
55
  // Pre-load logic: Only show splash if we haven't entered the portal yet.
56
  // We gate only on Auth and the first tick of identity.
57
  const isHydrating = !booted && (authLoading && !user);
frontend/apps/internal/src/App.tsx CHANGED
@@ -51,6 +51,24 @@ function App() {
51
  );
52
  }
53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  // Pre-load logic: We wait for auth AND for the first set of stats to arrive.
55
  // AI/Narrative loading is now "soft" to avoid navigation flickers.
56
  const isInitialLoading = (authLoading && !user) || (user && (
 
51
  );
52
  }
53
 
54
+ // --- STRICT PORTAL GUARD: Internal Staff Only ---
55
+ const isStaff = hasRole(['3sc_admin', '3sc_lead', '3sc_agent']);
56
+ if (user && !isStaff) {
57
+ return (
58
+ <div className="nexus-unauthorized-overlay">
59
+ <div className="nexus-unauthorized-box">
60
+ <NexusLogo subtitle="SECURITY CLEARANCE DENIED" />
61
+ <h1>Access Forbidden</h1>
62
+ <p>This portal is reserved for 3SC Operations Staff. Your account identity is restricted to the Customer Portal.</p>
63
+ <div className="nexus-unauthorized-actions">
64
+ <button onClick={() => window.location.href = '/'} className="nexus-btn-primary">Return to Customer Portal</button>
65
+ <button onClick={logout} className="nexus-btn-secondary">Logout and Switch Account</button>
66
+ </div>
67
+ </div>
68
+ </div>
69
+ );
70
+ }
71
+
72
  // Pre-load logic: We wait for auth AND for the first set of stats to arrive.
73
  // AI/Narrative loading is now "soft" to avoid navigation flickers.
74
  const isInitialLoading = (authLoading && !user) || (user && (
main.py CHANGED
@@ -102,6 +102,11 @@ app.add_middleware(RateLimiterMiddleware)
102
  # --- SLEDGEHAMMER CORS: FORCE HEADERS ON ALL RESPONSES ---
103
  @app.middleware("http")
104
  async def force_cors_middleware(request: Request, call_next):
 
 
 
 
 
105
  origin = request.headers.get("origin")
106
  if request.method == "OPTIONS":
107
  response = JSONResponse(content="OK")
@@ -152,6 +157,7 @@ app.include_router(escalations.router, prefix=f"{settings.API_V1_STR}/escalation
152
  app.include_router(reports.router, prefix=f"{settings.API_V1_STR}/reports", tags=["reports"])
153
  app.include_router(nexus.router, prefix=f"{settings.API_V1_STR}/nexus", tags=["Nexus Master Agent"])
154
  app.include_router(nexus_stream.router, prefix=f"{settings.API_V1_STR}/nexus", tags=["Nexus Master Agent"])
 
155
  import os
156
  from fastapi.staticfiles import StaticFiles
157
 
 
102
  # --- SLEDGEHAMMER CORS: FORCE HEADERS ON ALL RESPONSES ---
103
  @app.middleware("http")
104
  async def force_cors_middleware(request: Request, call_next):
105
+ # Skip CORS logic for WebSockets (they have their own handshake mechanisms)
106
+ if "upgrade" in request.headers.get("connection", "").lower() and \
107
+ request.headers.get("upgrade", "").lower() == "websocket":
108
+ return await call_next(request)
109
+
110
  origin = request.headers.get("origin")
111
  if request.method == "OPTIONS":
112
  response = JSONResponse(content="OK")
 
157
  app.include_router(reports.router, prefix=f"{settings.API_V1_STR}/reports", tags=["reports"])
158
  app.include_router(nexus.router, prefix=f"{settings.API_V1_STR}/nexus", tags=["Nexus Master Agent"])
159
  app.include_router(nexus_stream.router, prefix=f"{settings.API_V1_STR}/nexus", tags=["Nexus Master Agent"])
160
+ app.include_router(websockets.router, tags=["websockets"]) # Included at root to match frontend /ws/ logic
161
  import os
162
  from fastapi.staticfiles import StaticFiles
163