mirror of
https://github.com/yogeshojha/rengine.git
synced 2026-10-20 23:31:31 +02:00
The in-app feed was a second copy of the activity log with a red badge on it. A scan published up to six notifications (started, completed, new subdomains, new services, new vulnerabilities, coverage), every one of them already an activity_logs row and every one of them toasted for five seconds. A nightly twenty-target schedule left forty to a hundred and twenty unread rows. If it does not want a human to do something, it is not a notification. Deleted scan_started, scan_completed and scan_cancelled (both the API-side echo of the user's own Cancel click and the finalize one). whois/ripestat enrichment_complete became enrichment_incomplete and return None unless something actually failed. One digest replaces the five scan templates. scan_digest(...) -> dict | None takes a ScanDeltas and derives its severity, title, type and deep-link tab from the worst thing inside it, and returns None when nothing changed, so a quiet scheduled run is silent. Severity now encodes risk rather than process: scan_failed is warning, not error, because the bell takes its colour from the highest unread severity and one flaky run should not read like a KEV. Toasts are interrupts only: warning and error toast, success and info land silently in the bell. A toast with a url finally gets a View action; it used to require an action_label no template ever set. notifications.project_id scopes the bell to the active project (nullable and indexed, no FK so a transient row can never block a project delete). The list, stats, read-all and clear-all endpoints take ?project_id=, and the store drops SSE events from other projects. app.tasks.notifications.cleanup runs on beat every six hours. expires_at had been decorative since nothing ever called cleanup_expired, and the inbox modal fetched stats.total rows in a single request. Three bugs this uncovered: _count_new_subdomains had no baseline gate while services and vulnerabilities did, so a target's first scan announced its whole inventory as new: the first gov.np run would have reported 24022 new subdomains. Baselines are now per dimension, and a run with none reports the census instead. The delta counts ignored census_only, so a focused rescan both counted as a baseline and had its own rows announced. Every comparison now joins scans bs ... scope = 'full' AND bs.started_at < :started. Measuring the deltas took 16.8s on a 13,528-host scan: the scan-level baseline was a correlated EXISTS re-evaluated once per row and could not use ix_subdomains_target_name_discovered, having no name predicate. Hoisting it to one scan-level check and rewriting the per-row test as a hash anti-join over a WITH seen AS (SELECT DISTINCT ...) CTE gives the identical answer in 52ms, verified against a plain EXCEPT query. Not done, deliberately: is_read is still one global flag, so on a shared instance one analyst's Mark all as read still applies to everyone; that needs a notification_reads table. And notifier.wants() still governs external channels only, the bell having no preference layer, because volume reduction was the fix. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01BCPTXCr5qPESCt3LxR3329
109 lines
4.3 KiB
Python
109 lines
4.3 KiB
Python
"""Scan orchestrator celery tasks: run_scan (dispatch canvas), run_scan_stage, finalize_scan."""
|
|
|
|
import uuid
|
|
|
|
from celery import shared_task
|
|
|
|
from app.config import settings
|
|
from app.database import get_sync_session
|
|
from app.orchestrator import build_canvas, finalize_scan_run, run_stage
|
|
from shared.enums.activity import ActivityEvent, ActivityLevel
|
|
from shared.enums.scan import SCAN_TERMINAL_STATUSES, ScanStatus
|
|
from shared.logging import get_logger
|
|
from shared.models.scan import Scan
|
|
from shared.services.activity_log import ActivityLogService
|
|
from shared.services.orchestrator.events import ScanEventPublisher
|
|
from shared.utils.datetime import utc_now
|
|
from stages.registry import get_stage
|
|
|
|
logger = get_logger(__name__)
|
|
|
|
# run_scan id + canvas root id — a RUNNING scan with fewer was claimed but not dispatched.
|
|
_DISPATCHED_TASK_IDS = 2
|
|
|
|
|
|
@shared_task(bind=True, name="app.tasks.scan.run_scan", max_retries=0)
|
|
def run_scan(self, scan_id: str) -> dict:
|
|
"""Orchestrator entrypoint: claim RUNNING, dispatch the stage canvas, then notify."""
|
|
redis_url = settings.celery_broker_url
|
|
with get_sync_session() as session:
|
|
scan = session.get(Scan, uuid.UUID(scan_id))
|
|
if scan is None:
|
|
logger.warning("scan %s not found", scan_id)
|
|
return {"error": "scan not found"}
|
|
if scan.status in SCAN_TERMINAL_STATUSES:
|
|
logger.info("scan %s already %s, skipping", scan_id, scan.status)
|
|
return {"skipped": scan.status}
|
|
if (
|
|
scan.status == ScanStatus.RUNNING.value
|
|
and len(scan.celery_task_ids or []) >= _DISPATCHED_TASK_IDS
|
|
):
|
|
logger.info("scan %s canvas already dispatched, skipping", scan_id)
|
|
return {"skipped": "already dispatched"}
|
|
|
|
was_pending = scan.status == ScanStatus.PENDING.value
|
|
if was_pending:
|
|
scan.status = ScanStatus.RUNNING.value
|
|
scan.started_at = utc_now()
|
|
scan.error = None
|
|
scan.celery_task_ids = [self.request.id]
|
|
session.commit()
|
|
|
|
workflow = build_canvas(scan_id)
|
|
result = workflow.apply_async()
|
|
scan.celery_task_ids = [self.request.id, result.id]
|
|
session.commit()
|
|
logger.info("scan %s canvas dispatched (root=%s)", scan_id, result.id)
|
|
|
|
if was_pending:
|
|
events = ScanEventPublisher(
|
|
redis_url, scan_id=scan_id, project_id=str(scan.project_id)
|
|
)
|
|
target_value = (scan.execution_config or {}).get("target_value", "")
|
|
ActivityLogService(session).log(
|
|
event=ActivityEvent.SCAN_STARTED,
|
|
title=f"Scan started · {target_value}",
|
|
description=scan.engine_name,
|
|
level=ActivityLevel.INFO,
|
|
project_id=scan.project_id,
|
|
target_id=scan.target_id,
|
|
scan_id=scan.id,
|
|
target_value=target_value,
|
|
)
|
|
session.commit()
|
|
events.scan_started(status=scan.status, engine=scan.engine_name)
|
|
return {"dispatched": True, "task_id": result.id}
|
|
|
|
|
|
@shared_task(bind=True, name="app.tasks.scan.run_scan_stage", max_retries=0)
|
|
def run_scan_stage(self, scan_id: str, stage_name: str) -> dict:
|
|
"""Run one engine stage with activity tracking + command registration."""
|
|
spec = get_stage(stage_name)
|
|
if spec is None:
|
|
logger.warning("unknown scan stage %s", stage_name)
|
|
return {"error": "unknown stage", "stage": stage_name}
|
|
|
|
with get_sync_session() as session:
|
|
scan = session.get(Scan, uuid.UUID(scan_id))
|
|
if scan is None:
|
|
return {"error": "scan not found"}
|
|
run_stage(
|
|
session,
|
|
scan,
|
|
spec,
|
|
celery_task_id=self.request.id,
|
|
redis_url=settings.celery_broker_url,
|
|
)
|
|
return {"stage": stage_name}
|
|
|
|
|
|
@shared_task(bind=True, name="app.tasks.scan.finalize_scan", max_retries=0)
|
|
def finalize_scan(self, scan_id: str) -> dict: # noqa: ARG001
|
|
"""Aggregate stage outcomes into the final scan status + terminal notif."""
|
|
with get_sync_session() as session:
|
|
scan = session.get(Scan, uuid.UUID(scan_id))
|
|
if scan is None:
|
|
return {"error": "scan not found"}
|
|
finalize_scan_run(session, scan, redis_url=settings.celery_broker_url)
|
|
return {"finalized": True, "scan_id": scan_id}
|