Buckets:

download
raw
24.6 kB
"""
Scan Scheduler API Routes
REST API für den Celery-basierten Scan Scheduler.
Unterstützt:
- Einmalige und wiederkehrende Scans
- Cron-Ausdrücke
- Prioritäts-Warteschlangen
- Benachrichtigungen (Email/Slack)
- Ausführungshistorie
"""
import logging
from datetime import datetime
from typing import Any, Dict, List, Optional
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query
from pydantic import BaseModel, Field, validator
from api.auth import get_current_user
from database.models import User
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/scheduler", tags=["Scan Scheduler"])
# ==================== Pydantic Models ====================
class ScheduleConfig(BaseModel):
"""Zeitplanungs-Konfiguration"""
type: str = Field(..., description="once, recurring, oder interval")
cron: Optional[str] = Field(None, description="Cron-Ausdruck für wiederkehrende Scans")
interval_minutes: Optional[int] = Field(None, description="Intervall in Minuten")
run_at: Optional[datetime] = Field(None, description="Zeitpunkt für einmalige Scans")
timezone: str = Field(default="UTC", description="Zeitzone")
@validator("type")
def validate_type(cls, v):
if v not in ["once", "recurring", "interval"]:
raise ValueError("Type must be once, recurring, or interval")
return v
@validator("cron")
def validate_cron(cls, v, values):
if values.get("type") == "recurring" and not v:
raise ValueError("Cron expression required for recurring scans")
if v:
# Validiere Cron-Syntax
from scheduler.cron import CronParser
if not CronParser.is_valid(v):
raise ValueError("Invalid cron expression")
return v
class NotificationConfig(BaseModel):
"""Benachrichtigungs-Konfiguration"""
on_completion: bool = Field(default=True, description="Bei Abschluss benachrichtigen")
on_failure: bool = Field(default=True, description="Bei Fehler benachrichtigen")
on_success: bool = Field(default=False, description="Bei erfolgreichem Scan ohne Findings benachrichtigen")
on_critical: bool = Field(default=True, description="Bei kritischen Findings sofort benachrichtigen")
email: Optional[str] = Field(None, description="Email-Adresse")
slack_webhook: Optional[str] = Field(None, description="Slack Webhook URL")
class ScanConfig(BaseModel):
"""Scan-Konfiguration"""
tools: Optional[List[str]] = Field(None, description="Zu verwendende Tools")
ports: Optional[str] = Field(None, description="Ports (z.B. '80,443' oder '1-65535')")
depth: Optional[str] = Field(default="normal", description="Scan-Tiefe: quick, normal, deep")
timeout: Optional[int] = Field(default=3600, description="Timeout in Sekunden")
risk_level: Optional[int] = Field(default=1, ge=0, le=3, description="Risiko-Level (0-3)")
extra_params: Optional[Dict[str, Any]] = Field(default={}, description="Zusätzliche Parameter")
class CreateScheduledScanRequest(BaseModel):
"""Request-Modell für neuen geplanten Scan"""
name: str = Field(..., min_length=1, max_length=255, description="Name des Scans")
description: Optional[str] = Field(default="", max_length=1000)
target: str = Field(..., min_length=1, max_length=500, description="Ziel-URL/IP")
scan_type: str = Field(..., description="scan_type: vulnerability, network, web, etc.")
schedule: ScheduleConfig
priority: int = Field(default=5, ge=1, le=10, description="Priorität (1=Höchste, 10=Niedrigste)")
scan_config: Optional[ScanConfig] = Field(default=ScanConfig())
notifications: Optional[NotificationConfig] = Field(default=NotificationConfig())
max_retries: int = Field(default=3, ge=0, le=10)
retry_delay_minutes: int = Field(default=5, ge=1, le=1440)
class UpdateScheduledScanRequest(BaseModel):
"""Request-Modell für Scan-Update"""
name: Optional[str] = Field(None, min_length=1, max_length=255)
description: Optional[str] = Field(None, max_length=1000)
target: Optional[str] = Field(None, min_length=1, max_length=500)
scan_type: Optional[str] = None
schedule: Optional[ScheduleConfig] = None
priority: Optional[int] = Field(None, ge=1, le=10)
scan_config: Optional[ScanConfig] = None
notifications: Optional[NotificationConfig] = None
is_active: Optional[bool] = None
max_retries: Optional[int] = Field(None, ge=0, le=10)
retry_delay_minutes: Optional[int] = Field(None, ge=1, le=1440)
class ScheduledScanResponse(BaseModel):
"""Response-Modell für ScheduledScan"""
id: int
name: str
description: str
target: str
scan_type: str
schedule_type: str
cron_expression: Optional[str]
interval_minutes: Optional[int]
next_run: Optional[datetime]
last_run: Optional[datetime]
timezone: str
priority: int
status: str
is_active: bool
max_retries: int
retry_count: int
notifications: Dict[str, Any]
created_by: Optional[int]
created_at: datetime
updated_at: datetime
class ExecutionHistoryResponse(BaseModel):
"""Response-Modell für Ausführungshistorie"""
id: int
scheduled_scan_id: int
scan_id: Optional[int]
started_at: datetime
completed_at: Optional[datetime]
status: str
result_summary: Optional[str]
error_message: Optional[str]
findings_count: int
critical_count: int
high_count: int
medium_count: int
low_count: int
celery_task_id: Optional[str]
class SchedulerStatisticsResponse(BaseModel):
"""Response-Modell für Scheduler-Statistiken"""
total_scheduled: int
active: int
pending: int
running: int
failed: int
due_now: int
total_executions: int
successful_executions: int
failed_executions: int
success_rate: float
class CronPresetsResponse(BaseModel):
"""Response-Modell für Cron-Presets"""
presets: Dict[str, str]
descriptions: Dict[str, str]
# ==================== Hilfsfunktionen ====================
def get_scheduler():
"""Dependency für ScanScheduler"""
from core.scan_scheduler import ScanScheduler
return ScanScheduler()
def schedule_to_dict(scan) -> Dict[str, Any]:
"""Konvertiert ScheduledScan zu Dict"""
return {
"id": scan.id,
"name": scan.name,
"description": scan.description or "",
"target": scan.target,
"scan_type": scan.scan_type,
"schedule_type": scan.schedule_type,
"cron_expression": scan.cron_expression,
"interval_minutes": scan.interval_minutes,
"next_run": scan.next_run,
"last_run": scan.last_run,
"timezone": scan.timezone,
"priority": scan.priority,
"status": scan.status,
"is_active": scan.is_active,
"max_retries": scan.max_retries,
"retry_count": scan.retry_count,
"notifications": scan.notifications or {},
"created_by": scan.created_by,
"created_at": scan.created_at,
"updated_at": scan.updated_at,
}
def execution_to_dict(exec) -> Dict[str, Any]:
"""Konvertiert ScanExecutionHistory zu Dict"""
return {
"id": exec.id,
"scheduled_scan_id": exec.scheduled_scan_id,
"scan_id": exec.scan_id,
"started_at": exec.started_at,
"completed_at": exec.completed_at,
"status": exec.status,
"result_summary": exec.result_summary,
"error_message": exec.error_message,
"findings_count": exec.findings_count,
"critical_count": exec.critical_count,
"high_count": exec.high_count,
"medium_count": exec.medium_count,
"low_count": exec.low_count,
"celery_task_id": exec.celery_task_id,
}
# ==================== API Endpoints ====================
@router.post("/scans", response_model=ScheduledScanResponse, status_code=201)
async def create_scheduled_scan(
request: CreateScheduledScanRequest,
scheduler: Any = Depends(get_scheduler),
current_user: User = Depends(get_current_user),
):
"""
Erstellt einen neuen geplanten Scan
Beispiel:
```json
{
"name": "Daily Security Scan",
"target": "https://example.com",
"scan_type": "comprehensive",
"schedule": {
"type": "recurring",
"cron": "0 2 * * *",
"timezone": "Europe/Berlin"
},
"priority": 3,
"notifications": {
"on_completion": true,
"on_failure": true,
"email": "admin@example.com"
}
}
```
"""
from core.scan_scheduler import ScheduleType
try:
# Konvertiere Request zu Scheduler-Parametern
schedule_type = ScheduleType(request.schedule.type)
# Scan-Config
scan_config = {}
if request.scan_config:
scan_config = {
"tools": request.scan_config.tools,
"ports": request.scan_config.ports,
"depth": request.scan_config.depth,
"timeout": request.scan_config.timeout,
"risk_level": request.scan_config.risk_level,
**(request.scan_config.extra_params or {}),
}
# Notifications
notifications = {}
if request.notifications:
notifications = {
"on_completion": request.notifications.on_completion,
"on_failure": request.notifications.on_failure,
"on_success": request.notifications.on_success,
"on_critical": request.notifications.on_critical,
"email": request.notifications.email,
"slack_webhook": request.notifications.slack_webhook,
}
# Erstelle Scheduled Scan
scan = scheduler.create_scheduled_scan(
name=request.name,
target=request.target,
scan_type=request.scan_type,
schedule_type=schedule_type,
description=request.description,
scan_config=scan_config,
cron_expression=request.schedule.cron,
interval_minutes=request.schedule.interval_minutes,
next_run=request.schedule.run_at,
timezone=request.schedule.timezone,
priority=request.priority,
max_retries=request.max_retries,
retry_delay_minutes=request.retry_delay_minutes,
notifications=notifications,
created_by=current_user.id if current_user else None,
)
return schedule_to_dict(scan)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
logger.error(f"Failed to create scheduled scan: {e}")
raise HTTPException(status_code=500, detail=f"Failed to create scan: {str(e)}")
@router.get("/scans", response_model=List[ScheduledScanResponse])
async def list_scheduled_scans(
status: Optional[str] = Query(None, description="Filter by status"),
is_active: Optional[bool] = Query(None, description="Filter by active status"),
target: Optional[str] = Query(None, description="Filter by target"),
limit: int = Query(100, ge=1, le=1000),
offset: int = Query(0, ge=0),
scheduler: Any = Depends(get_scheduler),
current_user: User = Depends(get_current_user),
):
"""
Listet alle geplanten Scans
"""
try:
scans = scheduler.list_scheduled_scans(
user_id=current_user.id if current_user else None,
status=status,
is_active=is_active,
target=target,
limit=limit,
offset=offset,
)
return [schedule_to_dict(scan) for scan in scans]
except Exception as e:
logger.error(f"Failed to list scans: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.get("/scans/{scan_id}", response_model=ScheduledScanResponse)
async def get_scheduled_scan(
scan_id: int, scheduler: Any = Depends(get_scheduler), current_user: User = Depends(get_current_user)
):
"""
Holt Details eines geplanten Scans
"""
try:
scan = scheduler.get_scheduled_scan(scan_id)
if not scan:
raise HTTPException(status_code=404, detail="Scheduled scan not found")
# Berechtigungsprüfung
if scan.created_by and current_user and scan.created_by != current_user.id:
if current_user.role != "admin":
raise HTTPException(status_code=403, detail="Access denied")
return schedule_to_dict(scan)
except HTTPException:
raise
except Exception as e:
logger.error(f"Failed to get scan {scan_id}: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.put("/scans/{scan_id}", response_model=ScheduledScanResponse)
async def update_scheduled_scan(
scan_id: int,
request: UpdateScheduledScanRequest,
scheduler: Any = Depends(get_scheduler),
current_user: User = Depends(get_current_user),
):
"""
Aktualisiert einen geplanten Scan
"""
try:
# Prüfe Existenz und Berechtigung
existing = scheduler.get_scheduled_scan(scan_id)
if not existing:
raise HTTPException(status_code=404, detail="Scheduled scan not found")
if existing.created_by and current_user and existing.created_by != current_user.id:
if current_user.role != "admin":
raise HTTPException(status_code=403, detail="Access denied")
# Baue Update-Dict
updates = {}
if request.name is not None:
updates["name"] = request.name
if request.description is not None:
updates["description"] = request.description
if request.target is not None:
updates["target"] = request.target
if request.scan_type is not None:
updates["scan_type"] = request.scan_type
if request.priority is not None:
updates["priority"] = request.priority
if request.is_active is not None:
updates["is_active"] = request.is_active
if request.max_retries is not None:
updates["max_retries"] = request.max_retries
if request.retry_delay_minutes is not None:
updates["retry_delay_minutes"] = request.retry_delay_minutes
# Schedule-Update
if request.schedule:
if request.schedule.cron:
updates["cron_expression"] = request.schedule.cron
if request.schedule.interval_minutes:
updates["interval_minutes"] = request.schedule.interval_minutes
if request.schedule.timezone:
updates["timezone"] = request.schedule.timezone
if request.schedule.run_at:
updates["next_run"] = request.schedule.run_at
# Scan-Config
if request.scan_config:
updates["scan_config"] = {
"tools": request.scan_config.tools,
"ports": request.scan_config.ports,
"depth": request.scan_config.depth,
"timeout": request.scan_config.timeout,
"risk_level": request.scan_config.risk_level,
**(request.scan_config.extra_params or {}),
}
# Notifications
if request.notifications:
updates["notifications"] = {
"on_completion": request.notifications.on_completion,
"on_failure": request.notifications.on_failure,
"on_success": request.notifications.on_success,
"on_critical": request.notifications.on_critical,
"email": request.notifications.email,
"slack_webhook": request.notifications.slack_webhook,
}
updated = scheduler.update_scheduled_scan(scan_id, **updates)
if not updated:
raise HTTPException(status_code=404, detail="Scheduled scan not found")
return schedule_to_dict(updated)
except HTTPException:
raise
except Exception as e:
logger.error(f"Failed to update scan {scan_id}: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.delete("/scans/{scan_id}")
async def delete_scheduled_scan(
scan_id: int, scheduler: Any = Depends(get_scheduler), current_user: User = Depends(get_current_user)
):
"""
Löscht einen geplanten Scan
"""
try:
# Prüfe Existenz und Berechtigung
existing = scheduler.get_scheduled_scan(scan_id)
if not existing:
raise HTTPException(status_code=404, detail="Scheduled scan not found")
if existing.created_by and current_user and existing.created_by != current_user.id:
if current_user.role != "admin":
raise HTTPException(status_code=403, detail="Access denied")
success = scheduler.delete_scheduled_scan(scan_id)
if not success:
raise HTTPException(status_code=404, detail="Scheduled scan not found")
return {"message": "Scheduled scan deleted successfully"}
except HTTPException:
raise
except Exception as e:
logger.error(f"Failed to delete scan {scan_id}: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.post("/scans/{scan_id}/pause")
async def pause_scheduled_scan(
scan_id: int, scheduler: Any = Depends(get_scheduler), current_user: User = Depends(get_current_user)
):
"""
Pausiert einen geplanten Scan
"""
try:
scan = scheduler.pause_scheduled_scan(scan_id)
if not scan:
raise HTTPException(status_code=404, detail="Scheduled scan not found")
return {"message": "Scan paused successfully", "scan": schedule_to_dict(scan)}
except Exception as e:
logger.error(f"Failed to pause scan {scan_id}: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.post("/scans/{scan_id}/resume")
async def resume_scheduled_scan(
scan_id: int, scheduler: Any = Depends(get_scheduler), current_user: User = Depends(get_current_user)
):
"""
Setzt einen pausierten Scan fort
"""
try:
scan = scheduler.resume_scheduled_scan(scan_id)
if not scan:
raise HTTPException(status_code=404, detail="Scheduled scan not found")
return {"message": "Scan resumed successfully", "scan": schedule_to_dict(scan)}
except Exception as e:
logger.error(f"Failed to resume scan {scan_id}: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.post("/scans/{scan_id}/run-now")
async def run_scan_now(
scan_id: int,
background_tasks: BackgroundTasks,
scheduler: Any = Depends(get_scheduler),
current_user: User = Depends(get_current_user),
):
"""
Führt einen geplanten Scan sofort aus (manueller Trigger)
"""
from tasks.scan_tasks import execute_scheduled_scan
try:
scan = scheduler.get_scheduled_scan(scan_id)
if not scan:
raise HTTPException(status_code=404, detail="Scheduled scan not found")
# Queue Scan sofort
task = execute_scheduled_scan.delay(scan_id)
return {"message": "Scan queued for immediate execution", "task_id": task.id, "scan_id": scan_id}
except HTTPException:
raise
except Exception as e:
logger.error(f"Failed to trigger scan {scan_id}: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.get("/scans/{scan_id}/history", response_model=List[ExecutionHistoryResponse])
async def get_scan_history(
scan_id: int,
limit: int = Query(100, ge=1, le=1000),
offset: int = Query(0, ge=0),
scheduler: Any = Depends(get_scheduler),
current_user: User = Depends(get_current_user),
):
"""
Holt Ausführungshistorie für einen Scan
"""
try:
# Prüfe Existenz
scan = scheduler.get_scheduled_scan(scan_id)
if not scan:
raise HTTPException(status_code=404, detail="Scheduled scan not found")
history = scheduler.get_execution_history(scheduled_scan_id=scan_id, limit=limit, offset=offset)
return [execution_to_dict(h) for h in history]
except HTTPException:
raise
except Exception as e:
logger.error(f"Failed to get history for scan {scan_id}: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.get("/history", response_model=List[ExecutionHistoryResponse])
async def get_all_history(
status: Optional[str] = Query(None, description="Filter by status"),
limit: int = Query(100, ge=1, le=1000),
offset: int = Query(0, ge=0),
scheduler: Any = Depends(get_scheduler),
current_user: User = Depends(get_current_user),
):
"""
Holt Ausführungshistorie für alle Scans
"""
try:
history = scheduler.get_all_execution_history(limit=limit, offset=offset, status=status)
return [execution_to_dict(h) for h in history]
except Exception as e:
logger.error(f"Failed to get history: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.get("/statistics", response_model=SchedulerStatisticsResponse)
async def get_scheduler_statistics(scheduler: Any = Depends(get_scheduler), current_user: User = Depends(get_current_user)):
"""
Holt Scheduler-Statistiken
"""
try:
stats = scheduler.get_statistics()
return stats
except Exception as e:
logger.error(f"Failed to get statistics: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.get("/cron-presets", response_model=CronPresetsResponse)
async def get_cron_presets():
"""
Holt häufig verwendete Cron-Presets
"""
presets = {
"every_minute": "* * * * *",
"every_5_minutes": "*/5 * * * *",
"every_15_minutes": "*/15 * * * *",
"every_30_minutes": "*/30 * * * *",
"hourly": "0 * * * *",
"every_2_hours": "0 */2 * * *",
"daily": "0 0 * * *",
"daily_morning": "0 9 * * *",
"daily_evening": "0 18 * * *",
"weekly": "0 0 * * 0",
"weekly_monday": "0 0 * * 1",
"monthly": "0 0 1 * *",
"yearly": "0 0 1 1 *",
}
descriptions = {
"every_minute": "Jede Minute",
"every_5_minutes": "Alle 5 Minuten",
"every_15_minutes": "Alle 15 Minuten",
"every_30_minutes": "Alle 30 Minuten",
"hourly": "Jede Stunde",
"every_2_hours": "Alle 2 Stunden",
"daily": "Täglich um Mitternacht",
"daily_morning": "Täglich um 9:00",
"daily_evening": "Täglich um 18:00",
"weekly": "Wöchentlich am Sonntag",
"weekly_monday": "Wöchentlich am Montag",
"monthly": "Monatlich am 1.",
"yearly": "Jährlich am 1. Januar",
}
return {"presets": presets, "descriptions": descriptions}
@router.post("/validate-cron")
async def validate_cron(cron: str):
"""
Validiert einen Cron-Ausdruck und gibt Beschreibung zurück
"""
from scheduler.cron import CronParser
try:
if not CronParser.is_valid(cron):
raise HTTPException(status_code=400, detail="Invalid cron expression")
description = CronParser.describe(cron)
next_run = CronParser.get_next_run(cron)
return {"valid": True, "cron": cron, "description": description, "next_run": next_run}
except HTTPException:
raise
except Exception as e:
logger.error(f"Failed to validate cron: {type(e).__name__}")
raise HTTPException(status_code=500, detail="Invalid cron expression")
raise HTTPException(status_code=400, detail="Invalid cron expression")
@router.get("/celery-status")
async def get_celery_status():
"""
Prüft Celery-Worker Status
"""
from celery_app import celery_app
try:
# Prüfe Worker
inspector = celery_app.control.inspect()
active = inspector.active()
scheduled = inspector.scheduled()
reserved = inspector.reserved()
# Queue-Statistiken
stats = inspector.stats()
return {
"status": "ok" if active else "no_workers",
"active_workers": len(active) if active else 0,
"active_tasks": active,
"scheduled_tasks": scheduled,
"reserved_tasks": reserved,
"worker_stats": stats,
}
except Exception as e:
logger.error(f"Failed to get Celery status: {type(e).__name__}")
return {"status": "error", "error": "Celery status unavailable"}

Xet Storage Details

Size:
24.6 kB
·
Xet hash:
c9f228865c171850cbd37cd9b01c9a97eaf07e79fe30da4fde5c735c5d00f523

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