Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /poc /backend /app /routers /vulnerabilities.py
| """ | |
| Vulnerability Management Router | |
| Handles vulnerability CRUD, analysis, and remediation tracking | |
| """ | |
| from typing import Optional | |
| from fastapi import APIRouter, Depends, HTTPException, Query, status | |
| from sqlalchemy import desc, func | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from sqlalchemy.future import select | |
| from app.core.database import get_db | |
| from app.models.user import User | |
| from app.models.vulnerability import ( | |
| Severity, | |
| Vulnerability, | |
| VulnerabilityStatus, | |
| ) | |
| from app.routers.auth import get_current_active_user, require_admin | |
| from app.schemas.vulnerabilities import ( | |
| VulnerabilityBulkUpdate, | |
| VulnerabilityDetailResponse, | |
| VulnerabilityListResponse, | |
| VulnerabilityResponse, | |
| VulnerabilitySeverityStats, | |
| VulnerabilityStatusUpdate, | |
| VulnerabilityUpdate, | |
| ) | |
| router = APIRouter() | |
| async def list_vulnerabilities( | |
| scan_id: Optional[str] = None, | |
| severity: Optional[Severity] = None, | |
| status: Optional[VulnerabilityStatus] = None, | |
| search: Optional[str] = None, | |
| cve_id: Optional[str] = None, | |
| assigned_to: Optional[str] = None, | |
| page: int = Query(1, ge=1), | |
| limit: int = Query(10, ge=1, le=100), | |
| sort_by: str = Query("created_at"), | |
| sort_order: str = Query("desc"), | |
| db: AsyncSession = Depends(get_db), | |
| current_user: User = Depends(get_current_active_user), | |
| ): | |
| """List all vulnerabilities with advanced filtering.""" | |
| query = select(Vulnerability) | |
| # Apply filters | |
| if scan_id: | |
| query = query.where(Vulnerability.scan_id == scan_id) | |
| if severity: | |
| query = query.where(Vulnerability.severity == severity) | |
| if status: | |
| query = query.where(Vulnerability.status == status) | |
| if cve_id: | |
| query = query.where(Vulnerability.cve_id.ilike(f"%{cve_id}%")) | |
| if assigned_to: | |
| query = query.where(Vulnerability.assigned_to == assigned_to) | |
| if search: | |
| query = query.where(Vulnerability.name.ilike(f"%{search}%") | Vulnerability.description.ilike(f"%{search}%")) | |
| # Apply sorting | |
| if sort_order == "desc": | |
| query = query.order_by(desc(getattr(Vulnerability, sort_by))) | |
| else: | |
| query = query.order_by(getattr(Vulnerability, sort_by)) | |
| # Get total count | |
| count_result = await db.execute(select(func.count()).select_from(query.subquery())) | |
| total = count_result.scalar() | |
| # Apply pagination | |
| query = query.offset((page - 1) * limit).limit(limit) | |
| result = await db.execute(query) | |
| vulnerabilities = result.scalars().all() | |
| return VulnerabilityListResponse( | |
| success=True, | |
| data=[vuln.to_dict() for vuln in vulnerabilities], | |
| meta={ | |
| "page": page, | |
| "limit": limit, | |
| "total": total, | |
| "totalPages": (total + limit - 1) // limit, | |
| "hasNext": page * limit < total, | |
| "hasPrev": page > 1, | |
| }, | |
| ) | |
| async def get_vulnerability_stats( | |
| scan_id: Optional[str] = None, | |
| db: AsyncSession = Depends(get_db), | |
| current_user: User = Depends(get_current_active_user), | |
| ): | |
| """Get vulnerability statistics by severity.""" | |
| query = select(Vulnerability.severity, func.count().label("count")) | |
| if scan_id: | |
| query = query.where(Vulnerability.scan_id == scan_id) | |
| query = query.group_by(Vulnerability.severity) | |
| result = await db.execute(query) | |
| stats = result.all() | |
| # Initialize all severities with 0 | |
| severity_counts = { | |
| "critical": 0, | |
| "high": 0, | |
| "medium": 0, | |
| "low": 0, | |
| "info": 0, | |
| } | |
| for severity, count in stats: | |
| severity_counts[severity.value] = count | |
| # Calculate total | |
| total = sum(severity_counts.values()) | |
| return VulnerabilitySeverityStats( | |
| success=True, | |
| data={ | |
| "total": total, | |
| "critical": severity_counts["critical"], | |
| "high": severity_counts["high"], | |
| "medium": severity_counts["medium"], | |
| "low": severity_counts["low"], | |
| "info": severity_counts["info"], | |
| }, | |
| ) | |
| async def get_vulnerability( | |
| vulnerability_id: str, | |
| db: AsyncSession = Depends(get_db), | |
| current_user: User = Depends(get_current_active_user), | |
| ): | |
| """Get detailed information about a specific vulnerability.""" | |
| result = await db.execute(select(Vulnerability).where(Vulnerability.id == vulnerability_id)) | |
| vulnerability = result.scalar_one_or_none() | |
| if not vulnerability: | |
| raise HTTPException( | |
| status_code=status.HTTP_404_NOT_FOUND, | |
| detail="Vulnerability not found", | |
| ) | |
| # Get scan information | |
| scan_info = None | |
| if vulnerability.scan: | |
| scan_info = { | |
| "id": str(vulnerability.scan.id), | |
| "name": vulnerability.scan.name, | |
| "target": vulnerability.scan.target, | |
| } | |
| vuln_data = vulnerability.to_dict() | |
| vuln_data["scan"] = scan_info | |
| return VulnerabilityDetailResponse(success=True, data=vuln_data) | |
| async def update_vulnerability( | |
| vulnerability_id: str, | |
| vuln_data: VulnerabilityUpdate, | |
| db: AsyncSession = Depends(get_db), | |
| current_user: User = Depends(get_current_active_user), | |
| ): | |
| """Update a vulnerability.""" | |
| result = await db.execute(select(Vulnerability).where(Vulnerability.id == vulnerability_id)) | |
| vulnerability = result.scalar_one_or_none() | |
| if not vulnerability: | |
| raise HTTPException( | |
| status_code=status.HTTP_404_NOT_FOUND, | |
| detail="Vulnerability not found", | |
| ) | |
| # Update fields | |
| if vuln_data.name is not None: | |
| vulnerability.name = vuln_data.name | |
| if vuln_data.description is not None: | |
| vulnerability.description = vuln_data.description | |
| if vuln_data.severity is not None: | |
| vulnerability.severity = vuln_data.severity | |
| if vuln_data.cvss_score is not None: | |
| vulnerability.cvss_score = vuln_data.cvss_score | |
| if vuln_data.remediation is not None: | |
| vulnerability.remediation = vuln_data.remediation | |
| if vuln_data.status is not None: | |
| vulnerability.status = vuln_data.status | |
| if vuln_data.assigned_to is not None: | |
| vulnerability.assigned_to = vuln_data.assigned_to | |
| if vuln_data.tags is not None: | |
| vulnerability.tags = vuln_data.tags | |
| await db.commit() | |
| await db.refresh(vulnerability) | |
| return VulnerabilityResponse(success=True, data=vulnerability.to_dict()) | |
| async def update_vulnerability_status( | |
| vulnerability_id: str, | |
| status_update: VulnerabilityStatusUpdate, | |
| db: AsyncSession = Depends(get_db), | |
| current_user: User = Depends(get_current_active_user), | |
| ): | |
| """Update vulnerability status (open, in_progress, resolved, etc.).""" | |
| result = await db.execute(select(Vulnerability).where(Vulnerability.id == vulnerability_id)) | |
| vulnerability = result.scalar_one_or_none() | |
| if not vulnerability: | |
| raise HTTPException( | |
| status_code=status.HTTP_404_NOT_FOUND, | |
| detail="Vulnerability not found", | |
| ) | |
| # Update status | |
| vulnerability.status = status_update.status | |
| # Handle verification | |
| if status_update.status == VulnerabilityStatus.RESOLVED: | |
| vulnerability.verified_by = current_user.id | |
| from datetime import datetime, timezone | |
| vulnerability.verified_at = datetime.now(timezone.utc) | |
| # Handle false positive | |
| if status_update.status == VulnerabilityStatus.FALSE_POSITIVE: | |
| vulnerability.false_positive_reason = status_update.reason | |
| await db.commit() | |
| await db.refresh(vulnerability) | |
| return VulnerabilityResponse(success=True, data=vulnerability.to_dict()) | |
| async def bulk_update_vulnerabilities( | |
| bulk_update: VulnerabilityBulkUpdate, | |
| db: AsyncSession = Depends(get_db), | |
| current_user: User = Depends(require_admin), | |
| ): | |
| """Bulk update vulnerabilities (admin only).""" | |
| if not bulk_update.vulnerability_ids: | |
| raise HTTPException( | |
| status_code=status.HTTP_400_BAD_REQUEST, | |
| detail="No vulnerability IDs provided", | |
| ) | |
| # Get vulnerabilities | |
| result = await db.execute(select(Vulnerability).where(Vulnerability.id.in_(bulk_update.vulnerability_ids))) | |
| vulnerabilities = result.scalars().all() | |
| if not vulnerabilities: | |
| raise HTTPException( | |
| status_code=status.HTTP_404_NOT_FOUND, | |
| detail="No vulnerabilities found", | |
| ) | |
| # Apply updates | |
| for vuln in vulnerabilities: | |
| if bulk_update.status is not None: | |
| vuln.status = bulk_update.status | |
| if bulk_update.severity is not None: | |
| vuln.severity = bulk_update.severity | |
| if bulk_update.assigned_to is not None: | |
| vuln.assigned_to = bulk_update.assigned_to | |
| if bulk_update.tags is not None: | |
| vuln.tags = list(set(vuln.tags + bulk_update.tags)) | |
| await db.commit() | |
| return { | |
| "success": True, | |
| "message": f"Updated {len(vulnerabilities)} vulnerabilities", | |
| "updated_count": len(vulnerabilities), | |
| } | |
| async def delete_vulnerability( | |
| vulnerability_id: str, | |
| db: AsyncSession = Depends(get_db), | |
| current_user: User = Depends(require_admin), | |
| ): | |
| """Delete a vulnerability (admin only).""" | |
| result = await db.execute(select(Vulnerability).where(Vulnerability.id == vulnerability_id)) | |
| vulnerability = result.scalar_one_or_none() | |
| if not vulnerability: | |
| raise HTTPException( | |
| status_code=status.HTTP_404_NOT_FOUND, | |
| detail="Vulnerability not found", | |
| ) | |
| await db.delete(vulnerability) | |
| await db.commit() | |
| return None | |
| async def get_similar_vulnerabilities( | |
| vulnerability_id: str, | |
| limit: int = Query(5, ge=1, le=20), | |
| db: AsyncSession = Depends(get_db), | |
| current_user: User = Depends(get_current_active_user), | |
| ): | |
| """Find similar vulnerabilities based on name and tags.""" | |
| result = await db.execute(select(Vulnerability).where(Vulnerability.id == vulnerability_id)) | |
| vulnerability = result.scalar_one_or_none() | |
| if not vulnerability: | |
| raise HTTPException( | |
| status_code=status.HTTP_404_NOT_FOUND, | |
| detail="Vulnerability not found", | |
| ) | |
| # Find similar vulnerabilities | |
| query = ( | |
| select(Vulnerability) | |
| .where( | |
| Vulnerability.id != vulnerability_id, | |
| Vulnerability.name.ilike(f"%{vulnerability.name.split()[0]}%"), | |
| ) | |
| .limit(limit) | |
| ) | |
| result = await db.execute(query) | |
| similar = result.scalars().all() | |
| return {"success": True, "data": [vuln.to_dict() for vuln in similar]} | |
Xet Storage Details
- Size:
- 11.1 kB
- Xet hash:
- 8be69cf6b6b6f7f996df533585a7f63243c3c90cfb7bc7071ba22e7f157a24ee
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.