Buckets:

download
raw
11.1 kB
"""
WebSocket Router for Zen-AI-Pentest
Handles real-time communication for scan updates and notifications
"""
import json
from typing import Dict, List
import jwt
from fastapi import APIRouter, WebSocket, WebSocketDisconnect, status
from app.core.config import settings
from app.core.database import async_session_maker
from app.models.user import User
router = APIRouter()
# Store active connections
class ConnectionManager:
"""Manage WebSocket connections"""
def __init__(self):
# Map user_id to their websocket connections
self.active_connections: Dict[str, List[WebSocket]] = {}
# Map scan_id to connected websockets (for scan-specific updates)
self.scan_connections: Dict[str, List[WebSocket]] = {}
# Map websocket to user_id for cleanup
self.websocket_to_user: Dict[WebSocket, str] = {}
async def connect(self, websocket: WebSocket, user_id: str):
"""Accept and store a new connection"""
await websocket.accept()
if user_id not in self.active_connections:
self.active_connections[user_id] = []
self.active_connections[user_id].append(websocket)
self.websocket_to_user[websocket] = user_id
def disconnect(self, websocket: WebSocket):
"""Remove a disconnected websocket"""
user_id = self.websocket_to_user.get(websocket)
if user_id and user_id in self.active_connections:
if websocket in self.active_connections[user_id]:
self.active_connections[user_id].remove(websocket)
# Clean up empty user entries
if not self.active_connections[user_id]:
del self.active_connections[user_id]
# Remove from scan connections
for scan_id, connections in self.scan_connections.items():
if websocket in connections:
connections.remove(websocket)
# Remove mapping
if websocket in self.websocket_to_user:
del self.websocket_to_user[websocket]
def subscribe_to_scan(self, websocket: WebSocket, scan_id: str):
"""Subscribe a websocket to scan-specific updates"""
if scan_id not in self.scan_connections:
self.scan_connections[scan_id] = []
if websocket not in self.scan_connections[scan_id]:
self.scan_connections[scan_id].append(websocket)
def unsubscribe_from_scan(self, websocket: WebSocket, scan_id: str):
"""Unsubscribe a websocket from scan-specific updates"""
if scan_id in self.scan_connections:
if websocket in self.scan_connections[scan_id]:
self.scan_connections[scan_id].remove(websocket)
async def send_to_user(self, user_id: str, message: dict):
"""Send a message to all connections of a specific user"""
if user_id in self.active_connections:
disconnected = []
for connection in self.active_connections[user_id]:
try:
await connection.send_json(message)
except Exception:
disconnected.append(connection)
# Clean up disconnected websockets
for conn in disconnected:
self.disconnect(conn)
async def send_to_scan_subscribers(self, scan_id: str, message: dict):
"""Send a message to all subscribers of a specific scan"""
if scan_id in self.scan_connections:
disconnected = []
for connection in self.scan_connections[scan_id]:
try:
await connection.send_json(message)
except Exception:
disconnected.append(connection)
# Clean up disconnected websockets
for conn in disconnected:
self.disconnect(conn)
async def broadcast(self, message: dict):
"""Broadcast a message to all connected clients"""
disconnected = []
for user_id, connections in self.active_connections.items():
for connection in connections:
try:
await connection.send_json(message)
except Exception:
disconnected.append(connection)
# Clean up disconnected websockets
for conn in disconnected:
self.disconnect(conn)
async def send_personal_message(self, websocket: WebSocket, message: dict):
"""Send a message to a specific websocket"""
await websocket.send_json(message)
# Global connection manager
manager = ConnectionManager()
async def get_user_from_token(token: str) -> User:
"""Validate JWT token and return user"""
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.JWT_ALGORITHM])
user_id: str = payload.get("sub")
token_type: str = payload.get("type")
if user_id is None or token_type != "access":
raise ValueError("Invalid token")
# Get user from database
async with async_session_maker() as db:
from sqlalchemy.future import select
result = await db.execute(select(User).where(User.id == user_id))
user = result.scalar_one_or_none()
if not user or not user.is_active:
raise ValueError("User not found or inactive")
return user
except (jwt.ExpiredSignatureError, jwt.InvalidTokenError):
raise ValueError("Invalid token")
@router.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
"""Main WebSocket endpoint for real-time updates"""
user = None
try:
# Wait for authentication message
auth_message = await websocket.receive_text()
auth_data = json.loads(auth_message)
if auth_data.get("type") != "auth":
await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
return
token = auth_data.get("token")
if not token:
await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
return
# Validate token
try:
user = await get_user_from_token(token)
except ValueError:
await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
return
# Accept connection
await manager.connect(websocket, str(user.id))
# Send connection success message
await manager.send_personal_message(
websocket,
{
"type": "connection_established",
"payload": {
"userId": str(user.id),
"message": "Connected to Zen-AI-Pentest real-time updates",
},
},
)
# Handle incoming messages
while True:
try:
message = await websocket.receive_text()
data = json.loads(message)
message_type = data.get("type")
payload = data.get("payload", {})
if message_type == "subscribe_scan":
# Subscribe to scan updates
scan_id = payload.get("scanId")
if scan_id:
manager.subscribe_to_scan(websocket, scan_id)
await manager.send_personal_message(
websocket,
{
"type": "subscription_confirmed",
"payload": {"scanId": scan_id},
},
)
elif message_type == "unsubscribe_scan":
# Unsubscribe from scan updates
scan_id = payload.get("scanId")
if scan_id:
manager.unsubscribe_from_scan(websocket, scan_id)
elif message_type == "ping":
# Respond to ping
await manager.send_personal_message(
websocket,
{
"type": "pong",
"timestamp": payload.get("timestamp"),
},
)
else:
# Unknown message type
await manager.send_personal_message(
websocket,
{
"type": "error",
"payload": {"message": f"Unknown message type: {message_type}"},
},
)
except json.JSONDecodeError:
await manager.send_personal_message(
websocket,
{
"type": "error",
"payload": {"message": "Invalid JSON format"},
},
)
except WebSocketDisconnect:
if websocket in manager.websocket_to_user:
manager.disconnect(websocket)
except Exception:
if websocket in manager.websocket_to_user:
manager.disconnect(websocket)
# Helper functions for sending updates
async def send_scan_update(scan_id: str, update: dict):
"""Send scan progress update to all subscribers"""
message = {"type": "scan_update", "payload": {"scanId": scan_id, **update}}
await manager.send_to_scan_subscribers(scan_id, message)
async def send_scan_progress(scan_id: str, progress: int, status: str, message: str = None):
"""Send scan progress update"""
update = {"progress": progress, "status": status, "message": message}
await send_scan_update(scan_id, update)
async def send_vulnerability_found(scan_id: str, vulnerability: dict):
"""Send notification when new vulnerability is found"""
message = {
"type": "vulnerability_found",
"payload": {"scanId": scan_id, "vulnerability": vulnerability},
}
await manager.send_to_scan_subscribers(scan_id, message)
async def send_scan_completed(scan_id: str, findings_count: int):
"""Send notification when scan is completed"""
message = {
"type": "scan_completed",
"payload": {"scanId": scan_id, "findingsCount": findings_count},
}
await manager.send_to_scan_subscribers(scan_id, message)
async def send_notification(user_id: str, notification: dict):
"""Send notification to specific user"""
message = {"type": "notification", "payload": notification}
await manager.send_to_user(user_id, message)
async def broadcast_notification(notification: dict):
"""Broadcast notification to all connected users"""
message = {"type": "notification", "payload": notification}
await manager.broadcast(message)
async def send_agent_status_update(agent_id: str, status: str, metrics: dict = None):
"""Send agent status update"""
message = {
"type": "agent_status",
"payload": {
"agentId": agent_id,
"status": status,
"metrics": metrics or {},
},
}
await manager.broadcast(message)

Xet Storage Details

Size:
11.1 kB
·
Xet hash:
43960cb636976e8da652fc37071513901ba726f514bed6908af4815761641b57

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.