Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /api /routes /legacy_misc.py
| """ | |
| Legacy misc routes extracted from api/main.py. | |
| Contains stats, Slack notifications, health rate-limited, | |
| and rate-limiting demo endpoints. | |
| """ | |
| import logging | |
| from datetime import datetime, timezone | |
| from typing import Any, List, Optional | |
| from fastapi import APIRouter, Depends, HTTPException, Request, Response | |
| from api.auth_deps import optional_auth, verify_token | |
| from api.rate_limiter import AuthRateLimitDependency, RateLimitDependency, RateLimitInfo, rate_limit | |
| from api.schemas import UserLogin | |
| from database.models import get_db | |
| logger = logging.getLogger(__name__) | |
| router = APIRouter(tags=["Legacy Misc"]) | |
| # ============================================================================ | |
| # STATS | |
| # ============================================================================ | |
| async def get_stats_overview(user: Optional[dict] = Depends(optional_auth), db=Depends(get_db)): | |
| """Get dashboard statistics overview""" | |
| from sqlalchemy import func | |
| from database.models import Finding, Scan | |
| # Basic counts | |
| total_scans = db.query(Scan).count() | |
| completed_scans = db.query(Scan).filter(Scan.status == "completed").count() | |
| running_scans = db.query(Scan).filter(Scan.status == "running").count() | |
| # Findings counts | |
| total_findings = db.query(Finding).count() | |
| # Severity distribution | |
| severity_counts = db.query(Finding.severity, func.count(Finding.id)).group_by(Finding.severity).all() | |
| severity_distribution = [ | |
| { | |
| "name": sev.capitalize(), | |
| "value": count, | |
| "color": get_severity_color(sev), | |
| } | |
| for sev, count in severity_counts | |
| ] | |
| # Fill missing severities | |
| all_severities = ["critical", "high", "medium", "low", "info"] | |
| existing = {s["name"].lower(): s for s in severity_distribution} | |
| for sev in all_severities: | |
| if sev not in existing: | |
| severity_distribution.append( | |
| { | |
| "name": sev.capitalize(), | |
| "value": 0, | |
| "color": get_severity_color(sev), | |
| } | |
| ) | |
| return { | |
| "total_scans": total_scans, | |
| "completed_scans": completed_scans, | |
| "running_scans": running_scans, | |
| "total_findings": total_findings, | |
| "critical_findings": sum(1 for s in severity_counts if s[0] == "critical"), | |
| "severity_distribution": severity_distribution, | |
| "trends": calculate_trends(days=30, db=db), | |
| "tool_usage": get_tool_usage_stats(days=30, db=db), | |
| } | |
| def calculate_trends(days: int = 30, db=None) -> List[dict]: | |
| """Calculate scan trends over time | |
| Returns list of {date, count, severity_breakdown} for the last N days. | |
| If no database session provided or no data, returns empty list. | |
| """ | |
| if db is None: | |
| return [] | |
| try: | |
| from datetime import timedelta, timezone | |
| from sqlalchemy import func | |
| from database.models import Finding, Scan | |
| # Calculate date range | |
| end_date = datetime.now(timezone.utc) | |
| start_date = end_date - timedelta(days=days) | |
| # Query scans grouped by date (using created_at) | |
| from database.models import DATABASE_URL | |
| if DATABASE_URL.startswith("sqlite"): | |
| date_func = func.date(Scan.created_at) | |
| else: | |
| date_func = func.date(Scan.created_at) | |
| scan_counts = ( | |
| db.query( | |
| date_func.label("scan_date"), | |
| func.count(Scan.id).label("count"), | |
| ) | |
| .filter(Scan.created_at >= start_date) | |
| .group_by(date_func) | |
| .order_by(date_func) | |
| .all() | |
| ) | |
| # Get findings severity breakdown per date | |
| findings_by_date = ( | |
| db.query( | |
| date_func.label("scan_date"), | |
| Finding.severity, | |
| func.count(Finding.id).label("count"), | |
| ) | |
| .join(Scan, Finding.scan_id == Scan.id) | |
| .filter(Scan.created_at >= start_date) | |
| .group_by(date_func, Finding.severity) | |
| .all() | |
| ) | |
| # Build severity breakdown dict per date | |
| severity_by_date = {} | |
| for date_val, severity, count in findings_by_date: | |
| date_key = str(date_val) if date_val else None | |
| if date_key: | |
| if date_key not in severity_by_date: | |
| severity_by_date[date_key] = { | |
| "critical": 0, | |
| "high": 0, | |
| "medium": 0, | |
| "low": 0, | |
| "info": 0, | |
| } | |
| severity_by_date[date_key][severity] = count | |
| # Build trends result | |
| trends = [] | |
| for date_val, count in scan_counts: | |
| date_str = str(date_val) if date_val else None | |
| if date_str: | |
| severity_breakdown = severity_by_date.get( | |
| date_str, | |
| { | |
| "critical": 0, | |
| "high": 0, | |
| "medium": 0, | |
| "low": 0, | |
| "info": 0, | |
| }, | |
| ) | |
| trends.append( | |
| { | |
| "date": date_str, | |
| "count": count, | |
| "severity_breakdown": severity_breakdown, | |
| } | |
| ) | |
| return trends | |
| except Exception as e: | |
| logger.warning(f"Error calculating trends: {e}") | |
| return [] | |
| def get_tool_usage_stats(days: int = 30, db=None) -> List[dict]: | |
| """Get tool usage statistics | |
| Returns list of {tool_name, execution_count, avg_duration} for the last N days. | |
| Uses Finding.tool field to track tool usage. | |
| If no database session provided or no data, returns empty list. | |
| """ | |
| if db is None: | |
| return [] | |
| try: | |
| from datetime import timedelta, timezone | |
| from sqlalchemy import func | |
| from database.models import Finding, Scan | |
| # Calculate date range | |
| end_date = datetime.now(timezone.utc) | |
| start_date = end_date - timedelta(days=days) | |
| # Query tool usage from findings (tool field) | |
| tool_stats = ( | |
| db.query( | |
| Finding.tool.label("tool_name"), | |
| func.count(Finding.id).label("execution_count"), | |
| ) | |
| .join(Scan, Finding.scan_id == Scan.id) | |
| .filter(Scan.created_at >= start_date) | |
| .filter(Finding.tool.isnot(None)) | |
| .group_by(Finding.tool) | |
| .order_by(func.count(Finding.id).desc()) | |
| .all() | |
| ) | |
| # Calculate average scan duration per tool | |
| tool_duration_stats = ( | |
| db.query( | |
| Finding.tool.label("tool_name"), | |
| func.avg(func.julianday(Scan.completed_at) - func.julianday(Scan.started_at)).label("avg_duration"), | |
| ) | |
| .join(Scan, Finding.scan_id == Scan.id) | |
| .filter(Scan.created_at >= start_date) | |
| .filter(Finding.tool.isnot(None)) | |
| .filter(Scan.completed_at.isnot(None)) | |
| .filter(Scan.started_at.isnot(None)) | |
| .group_by(Finding.tool) | |
| .all() | |
| ) | |
| # Build duration lookup dict | |
| duration_by_tool = { | |
| tool: (avg_dur * 86400 if avg_dur else 0) | |
| for tool, avg_dur in tool_duration_stats # Convert days to seconds | |
| } | |
| # Build result | |
| usage_stats = [] | |
| for tool_name, exec_count in tool_stats: | |
| if tool_name: # Skip None values | |
| avg_duration = duration_by_tool.get(tool_name, 0) | |
| usage_stats.append( | |
| { | |
| "tool_name": tool_name, | |
| "execution_count": exec_count, | |
| "avg_duration": round(avg_duration, 2), | |
| } | |
| ) | |
| return usage_stats | |
| except Exception as e: | |
| logger.warning(f"Error calculating tool usage stats: {e}") | |
| return [] | |
| def get_severity_color(severity: str) -> str: | |
| """Get color for severity level""" | |
| colors = { | |
| "critical": "#ef4444", | |
| "high": "#f97316", | |
| "medium": "#eab308", | |
| "low": "#22c55e", | |
| "info": "#3b82f6", | |
| } | |
| return colors.get(severity.lower(), "#6b7280") | |
| async def get_stats_trends( | |
| days: int = 30, | |
| user: Optional[dict] = Depends(optional_auth), | |
| db=Depends(get_db), | |
| ): | |
| """Get scan trends for the last N days""" | |
| trends = calculate_trends(days=days, db=db) | |
| return trends | |
| async def get_severity_stats(user: Optional[dict] = Depends(optional_auth), db=Depends(get_db)): | |
| """Get findings by severity""" | |
| from sqlalchemy import func | |
| from database.models import Finding | |
| severity_counts = db.query(Finding.severity, func.count(Finding.id)).group_by(Finding.severity).all() | |
| return [{"severity": sev, "count": count} for sev, count in severity_counts] | |
| async def get_tool_usage(user: Optional[dict] = Depends(optional_auth), db=Depends(get_db)): | |
| """Get tool usage statistics""" | |
| tool_stats = get_tool_usage_stats(days=30, db=db) | |
| return tool_stats | |
| # ============================================================================ | |
| # NOTIFICATIONS (SLACK) | |
| # ============================================================================ | |
| async def test_slack_notification(webhook_url: str, user: Any = Depends(verify_token)): | |
| """Test Slack webhook configuration""" | |
| try: | |
| from api.routes.legacy_settings import _validate_slack_webhook_url | |
| from notifications.slack import SlackNotifier | |
| safe_webhook_url = _validate_slack_webhook_url(webhook_url) | |
| notifier = SlackNotifier(safe_webhook_url) | |
| success = notifier.send_message( | |
| f"Test notification from Zen AI Pentest\nUser: {user.get('sub', 'unknown')}\nTime: {datetime.now().isoformat()}" | |
| ) | |
| if success: | |
| return {"status": "success", "message": "Test notification sent"} | |
| else: | |
| raise HTTPException(status_code=400, detail="Failed to send Slack notification") | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def notify_slack_scan_complete( | |
| scan_id: int, | |
| webhook_url: str, | |
| user: Any = Depends(verify_token), | |
| db=Depends(get_db), | |
| ): | |
| """Send Slack notification for scan completion""" | |
| try: | |
| from api.routes.legacy_settings import _validate_slack_webhook_url | |
| from database.models import Finding, Scan | |
| from notifications.slack import SlackNotifier | |
| # Get scan details | |
| scan = db.query(Scan).filter(Scan.id == scan_id).first() | |
| if not scan: | |
| raise HTTPException(status_code=404, detail="Scan not found") | |
| # Validate webhook URL to prevent SSRF | |
| safe_webhook_url = _validate_slack_webhook_url(webhook_url) | |
| # Count findings | |
| findings = db.query(Finding).filter(Finding.scan_id == scan_id).all() | |
| findings_count = len(findings) | |
| critical_count = sum(1 for f in findings if f.severity == "critical") | |
| # Send notification | |
| notifier = SlackNotifier(safe_webhook_url) | |
| success = notifier.send_scan_completed( | |
| scan_id=scan_id, | |
| target=scan.target, | |
| findings_count=findings_count, | |
| critical_count=critical_count, | |
| ) | |
| if success: | |
| return {"status": "success", "message": "Notification sent"} | |
| else: | |
| raise HTTPException(status_code=400, detail="Failed to send notification") | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| # ============================================================================ | |
| # Rate Limiting Demo Endpoints | |
| # ============================================================================ | |
| async def health_check(request: Request, response: Response, rate_info: RateLimitInfo = Depends(RateLimitDependency())): | |
| """ | |
| Health check endpoint with standard rate limiting. | |
| - Anonymous: 20 req/min | |
| - Authenticated: 100 req/min | |
| Returns X-RateLimit-* headers. | |
| """ | |
| return { | |
| "status": "healthy", | |
| "timestamp": datetime.now().isoformat(), | |
| "rate_limit": { | |
| "limit": int(response.headers.get("X-RateLimit-Limit", 0)), | |
| "remaining": int(response.headers.get("X-RateLimit-Remaining", 0)), | |
| "reset": int(response.headers.get("X-RateLimit-Reset", 0)), | |
| }, | |
| } | |
| async def list_scans_v2( | |
| request: Request, | |
| response: Response, | |
| user: dict = Depends(verify_token), | |
| rate_info: RateLimitInfo = Depends(RateLimitDependency()), | |
| ): | |
| """ | |
| List scans - requires authentication. | |
| Rate limit: 100 req/min for authenticated users. | |
| """ | |
| return {"scans": [], "user": user.get("sub")} | |
| async def login_with_rate_limit( | |
| request: Request, response: Response, credentials: UserLogin, rate_info: RateLimitInfo = Depends(AuthRateLimitDependency()) | |
| ): | |
| """ | |
| Login endpoint with strict rate limiting (5 req/min). | |
| Protects against brute force attacks. | |
| """ | |
| raise HTTPException(status_code=501, detail="Use /auth/token endpoint instead") | |
| async def public_status(request: Request, response: Response, rate_info: RateLimitInfo = Depends(RateLimitDependency())): | |
| """ | |
| Public status endpoint with anonymous rate limiting (20 req/min). | |
| """ | |
| return { | |
| "status": "operational", | |
| "version": "2.2.0", | |
| "rate_limit": { | |
| "limit": int(response.headers.get("X-RateLimit-Limit", 0)), | |
| "remaining": int(response.headers.get("X-RateLimit-Remaining", 0)), | |
| }, | |
| } | |
| async def custom_limit_endpoint( | |
| request: Request, | |
| response: Response, | |
| rate_info: RateLimitInfo = Depends(RateLimitDependency(requests_per_minute=50, burst_size=10)), | |
| ): | |
| """ | |
| Endpoint with custom rate limit (50 req/min). | |
| """ | |
| return { | |
| "message": "Custom rate limit endpoint", | |
| "limit": 50, | |
| "remaining": int(response.headers.get("X-RateLimit-Remaining", 0)), | |
| } | |
| async def legacy_style_endpoint(request: Request, response: Response): | |
| """ | |
| Endpoint using decorator-style rate limiting. | |
| Note: Headers are added automatically. | |
| """ | |
| return {"message": "Legacy style endpoint with rate limiting"} | |
Xet Storage Details
- Size:
- 15 kB
- Xet hash:
- f1c3140df7545aa68142a0e00c43e9ee72687c33ceef7dd392db8305a73a0cad
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.