Spaces:
Running on Zero
Running on Zero
sreevidhuyarra
Demo overview: replay recorded alerts in the live feed, show recorded throughput
8c6b005 Download src/sentinel/services/api.py from sreevidhuyarra/Sentinel: direct link, hf CLI and curl.
- Browser
- Download file 35.5 kB
-
https://huggingface.co/spaces/sreevidhuyarra/Sentinel/resolve/main/src/sentinel/services/api.py
- Command line
-
hf download hf://spaces/sreevidhuyarra/Sentinel/src/sentinel/services/api.py
-
curl -L -o api.py https://huggingface.co/spaces/sreevidhuyarra/Sentinel/resolve/main/src/sentinel/services/api.py
35.5 kB
| """FastAPI gateway: health, models, flow / email / URL scoring, alerts and the SOC copilot.""" | |
| from __future__ import annotations | |
| import asyncio | |
| import threading | |
| import time | |
| from collections.abc import AsyncIterator, Callable | |
| from concurrent.futures import Future | |
| from contextlib import asynccontextmanager | |
| from datetime import UTC, datetime, timedelta | |
| from pathlib import Path | |
| from typing import Any, Literal, NamedTuple | |
| import polars as pl | |
| from fastapi import FastAPI, HTTPException, Query, Request, WebSocket, WebSocketDisconnect | |
| from fastapi.encoders import jsonable_encoder | |
| from fastapi.responses import FileResponse, RedirectResponse | |
| from pydantic import BaseModel, Field, model_validator | |
| from sqlalchemy import Engine, func, insert, select | |
| from sqlalchemy.exc import SQLAlchemyError | |
| from sentinel.anomaly.bundle import AnomalyBundle | |
| from sentinel.common.config import PROJECT_ROOT, get_settings | |
| from sentinel.common.logging import get_logger | |
| from sentinel.copilot.graph import Copilot | |
| from sentinel.copilot.models import IncidentReport | |
| from sentinel.copilot.tools import AlertTools | |
| from sentinel.db.schema import alerts as alerts_table | |
| from sentinel.db.schema import reports as reports_table | |
| from sentinel.detection.fusion import Detector, load_review_delta | |
| from sentinel.ids.bundle import IDSBundle | |
| from sentinel.phishing.explain import explain | |
| from sentinel.phishing.export import PhishingOnnxModel | |
| from sentinel.phishing.intel import Intel, sent_at | |
| from sentinel.phishing.payment import check_payment, escalate | |
| from sentinel.phishing.sender import ( | |
| Role, | |
| Sender, | |
| check_sender, | |
| load_policy, | |
| parse_eml, | |
| parse_sender, | |
| role_of, | |
| ) | |
| from sentinel.phishing.text import extract_urls, model_input | |
| from sentinel.phishing.urls import UrlModel | |
| from sentinel.services.auth import authorized, protect | |
| from sentinel.services.dashboard import router as dashboard_router | |
| from sentinel.services.feedback import router as feedback_router | |
| from sentinel.services.metrics import instrument, record_report | |
| log = get_logger(__name__) | |
| MAX_BATCH = 10_000 | |
| class FlowBatch(BaseModel): | |
| flows: list[dict[str, float | int | None]] = Field(min_length=1, max_length=MAX_BATCH) | |
| explain: bool = True | |
| class Reason(BaseModel): | |
| feature: str | |
| value: float | |
| contribution: float | |
| text: str | |
| expected: float | None = None # anomaly reasons: value of a normal-looking flow | |
| class FlowScore(BaseModel): | |
| family: str | |
| is_attack: bool | |
| detector: str | None # "supervised", "anomaly" or None (benign) | |
| confidence: float | None # calibrated P(family); None for "Unknown anomaly" | |
| attack_score: float | |
| anomaly_score: float | None | |
| is_anomalous: bool | None | |
| severity: str | None | |
| probabilities: dict[str, float] | |
| reasons: list[Reason] | |
| needs_review: bool = False # passed as benign, but the ensemble's members disagree | |
| member_gap: float | None = None | |
| class ScoreResponse(BaseModel): | |
| model_version: str | |
| anomaly_model_version: str | None | |
| results: list[FlowScore] | |
| def _load[T]( | |
| uri: str, | |
| path: Path, | |
| from_registry: Callable[[str], T], | |
| from_dir: Callable[[Path], T], | |
| required: bool, | |
| ) -> tuple[T | None, str | None]: | |
| """Registry alias first; fall back to the last local training output.""" | |
| if not get_settings().sentinel_demo: # the demo has no MLflow: bundled models only | |
| try: | |
| import mlflow | |
| mlflow.set_tracking_uri(get_settings().mlflow_tracking_uri) | |
| return from_registry(uri), _with_version(uri) | |
| except Exception as exc: # registry unreachable or alias missing | |
| log.warning("registry load of %s failed (%s); trying %s", uri, exc, path) | |
| if path.exists() or required: | |
| return from_dir(path), str(path) | |
| log.warning("no model at %s; the endpoints that need it are disabled", path) | |
| return None, None | |
| def _with_version(uri: str) -> str: | |
| """`models:/name@alias` -> `models:/name@alias (v3)`, so the UI shows what is served.""" | |
| name, _, alias = uri.removeprefix("models:/").partition("@") | |
| if not alias: | |
| return uri | |
| try: | |
| from mlflow.tracking import MlflowClient | |
| return f"{uri} (v{MlflowClient().get_model_version_by_alias(name, alias).version})" | |
| except Exception: # the model loaded, so this is cosmetic | |
| return uri | |
| class Models(NamedTuple): | |
| detector: Detector | |
| ids_source: str | |
| anomaly_source: str | None | |
| phishing: PhishingOnnxModel | None | |
| phishing_source: str | None | |
| url: UrlModel | None | |
| url_source: str | None | |
| def load_production_models() -> Models: | |
| from sentinel.anomaly.registry import load_bundle as load_anomaly | |
| from sentinel.ids.registry import load_bundle as load_ids | |
| from sentinel.phishing.registry import load_model as load_phishing | |
| from sentinel.phishing.registry import load_url_model | |
| s = get_settings() | |
| ids, ids_src = _load(s.ids_model_uri, s.ids_model_path, load_ids, IDSBundle.load, True) | |
| anomaly, an_src = _load( | |
| s.anomaly_model_uri, s.anomaly_model_path, load_anomaly, AnomalyBundle.load, False | |
| ) | |
| phishing, ph_src = _load( | |
| s.phishing_model_uri, s.phishing_model_path, load_phishing, PhishingOnnxModel.load, False | |
| ) | |
| url, url_src = _load(s.url_model_uri, s.url_model_path, load_url_model, UrlModel.load, False) | |
| assert ids is not None and ids_src is not None | |
| review = load_review_delta(PROJECT_ROOT / "reports" / "adversarial" / "results.json") | |
| detector = Detector(ids, anomaly, review_delta=review) | |
| return Models(detector, ids_src, an_src, phishing, ph_src, url, url_src) | |
| MAX_EMAIL_URLS = 20 | |
| SENDER_POLICY = PROJECT_ROOT / "models" / "phishing" / "sender_policy.json" | |
| INTEL_POLICY = PROJECT_ROOT / "models" / "phishing" / "intel_policy.json" | |
| PAYMENT_POLICY = PROJECT_ROOT / "models" / "phishing" / "payment_policy.json" | |
| INTEL_CACHE = PROJECT_ROOT / "data" / "cache" / "intel" | |
| FRONTEND_DIST = PROJECT_ROOT / "frontend" / "dist" | |
| WS_POLL_SECONDS = 1.0 | |
| WS_MAX_BATCH = 200 | |
| DEMO_REPLAY_BATCH = 3 # alerts a second in the demo's replayed feed | |
| WS_COLUMNS = [ | |
| "id", | |
| "ts", | |
| "source", | |
| "src_ip", | |
| "dst_ip", | |
| "dst_port", | |
| "sender_domain", | |
| "predicted_family", | |
| "detector", | |
| "confidence", | |
| "severity", | |
| ] | |
| def _db_engine(app: Any) -> Engine: | |
| """The API's read/write engine (created on first use unless injected). | |
| Creating it also brings the schema up to date (idempotent), so columns added in a later | |
| release exist before the dashboard selects them, whichever service started first. | |
| """ | |
| if app.state.db is None: | |
| from sentinel.db.schema import init_db, make_engine | |
| engine_ = make_engine(get_settings().postgres_url) | |
| init_db(engine_) | |
| app.state.db = engine_ | |
| engine: Engine = app.state.db | |
| return engine | |
| def _get_copilot(app: Any) -> Copilot: | |
| """The app's copilot, built on first use. Loading its models takes minutes on a laptop | |
| (DeBERTa guard, embedder, re-ranker), so the lock makes a request that arrives during the | |
| startup warm-up wait for it instead of loading a second copy.""" | |
| with app.state.copilot_lock: | |
| if app.state.copilot is None: | |
| from sentinel.common.config import load_params | |
| from sentinel.copilot.service import build_copilot | |
| app.state.copilot = build_copilot(load_params(), interactive=True) | |
| c: Copilot = app.state.copilot | |
| return c | |
| def _warm_copilot(app: Any) -> None: | |
| """Load the copilot and run each model once, so the first investigation is not slow.""" | |
| t0 = time.perf_counter() | |
| try: | |
| c = _get_copilot(app) | |
| c.guard.scan("Warm-up text for the prompt-injection guard.") | |
| c.retriever.search("port scan from one host", k=1) | |
| except Exception as exc: # the first investigation will retry and report the error | |
| log.warning("copilot warm-up failed: %s", exc) | |
| return | |
| log.info("copilot ready in %.0f s", time.perf_counter() - t0) | |
| class UrlReason(BaseModel): | |
| feature: str | |
| contribution: float # TreeSHAP log-odds pushed toward malicious | |
| text: str | |
| class UrlScore(BaseModel): | |
| url: str | |
| is_malicious: bool | |
| probability: float | |
| reasons: list[UrlReason] | |
| class UrlBatch(BaseModel): | |
| urls: list[str] = Field(min_length=1, max_length=1000) | |
| explain: bool = True | |
| class UrlResponse(BaseModel): | |
| threshold: float | |
| results: list[UrlScore] | |
| model_version: str | None | |
| def score_urls(model: UrlModel, urls: list[str], explain_hits: bool) -> list[UrlScore]: | |
| if not urls: | |
| return [] | |
| prob = model.predict_proba(urls) | |
| return [ | |
| UrlScore( | |
| url=u, | |
| is_malicious=bool(p >= model.threshold), | |
| probability=float(p), | |
| reasons=[UrlReason(**r) for r in model.explain(u)] | |
| if explain_hits and p >= model.threshold | |
| else [], | |
| ) | |
| for u, p in zip(urls, prob, strict=True) | |
| ] | |
| class EmailIn(BaseModel): | |
| subject: str = "" | |
| body: str = Field("", max_length=200_000) | |
| sender: str = Field("", max_length=1000) # From line: 'PayPal <service@paypal.com>' | |
| reply_to: str = Field("", max_length=1000) | |
| # The whole message (.eml). When given, subject, body, sender, Reply-To and the receiving | |
| # server's SPF/DKIM/DMARC results are read from it; attachments are never opened. | |
| eml: str | None = Field(None, max_length=5_000_000) | |
| urls: list[str] = Field(default_factory=list, max_length=500) | |
| explain: bool = True | |
| def _has_content(self) -> EmailIn: | |
| if not self.body.strip() and not self.eml: | |
| raise ValueError("give the email body or the raw .eml") | |
| return self | |
| class SenderFinding(BaseModel): | |
| check: str | |
| severity: str # high / medium / low: how strongly it points at phishing | |
| role: str # alert / review / ignore: what it does to the verdict (measured) | |
| text: str | |
| class SenderReport(BaseModel): | |
| from_line: str | |
| address: str | |
| domain: str | |
| reply_to: str | |
| auth: dict[str, str] # spf/dkim/dmarc results, from the .eml only | |
| findings: list[SenderFinding] | |
| class IntelDomain(BaseModel): | |
| domain: str | |
| seen_as: list[str] # sender / reply-to / link | |
| registered: str | None # RDAP registration date | |
| age_days: int | None # at the email's Date, or today | |
| listed_on: list[str] # blocklists naming it | |
| lookup: str # found / no_record / well_known / skipped / off | |
| class IntelReportOut(BaseModel): | |
| domains: list[IntelDomain] | |
| findings: list[SenderFinding] | |
| feeds_loaded: bool | |
| class EmailReason(BaseModel): | |
| text: str | |
| contribution: float # drop in the malicious logit when this sentence is removed | |
| class EmailScore(BaseModel): | |
| is_malicious: bool # text model, a link or an alert-level sender check flagged it | |
| flagged_by: list[str] # subset of ["text", "url", "sender", "intel", "payment"] | |
| # malicious = an alert; suspicious = below the alert threshold but worth a look (text score | |
| # in the review band, or a link the URL model judges malicious); clean = neither. | |
| verdict: Literal["malicious", "suspicious", "clean"] | |
| suspicious_because: list[str] # why a non-malicious email is suspicious | |
| probability: float # text model's P(phishing, fraud or spam) | |
| threshold: float | |
| suspicious_threshold: float | |
| severity: str | None | |
| reasons: list[EmailReason] # sentences that raised the text score | |
| urls: list[str] # URLs found in the email plus those supplied | |
| url_results: list[UrlScore] # first 20 URLs, when the URL model is loaded | |
| sender: SenderReport | None # when a From line or .eml was given | |
| intel: IntelReportOut | None # blocklists and domain age, when enabled | |
| payment: list[SenderFinding] # payment / invoice-fraud requests in the text | |
| subject: str # as scored (read from the .eml when one was given) | |
| model_version: str | None | |
| url_model_version: str | None | |
| def create_app( | |
| bundle: IDSBundle | None = None, | |
| source: str = "injected", | |
| anomaly: AnomalyBundle | None = None, | |
| anomaly_source: str | None = None, | |
| phishing: PhishingOnnxModel | None = None, | |
| phishing_source: str | None = None, | |
| url: UrlModel | None = None, | |
| url_source: str | None = None, | |
| copilot: Copilot | None = None, | |
| db: Engine | None = None, | |
| api_key: str | None = None, | |
| suspicious_threshold: float | None = None, | |
| warm_copilot: bool | None = None, | |
| sender_policy: dict[str, Role] | None = None, | |
| intel: Intel | None = None, | |
| ) -> FastAPI: | |
| """`api_key` turns on HTTP Basic auth (see services.auth); serve passes SENTINEL_API_KEY. | |
| `warm_copilot` (default: on when the models come from the registry) builds the copilot | |
| in a background thread at startup; otherwise it is built on the first investigation. | |
| `intel` (blocklists and domain age) is built from params.yaml when the models come from | |
| the registry; tests inject one or run without it. | |
| """ | |
| demo = get_settings().sentinel_demo | |
| if warm_copilot is None: | |
| warm_copilot = bundle is None and not demo | |
| async def lifespan(app: FastAPI) -> AsyncIterator[None]: | |
| if bundle is None: | |
| m = load_production_models() | |
| app.state.detector, app.state.source, app.state.anomaly_source = ( | |
| m.detector, | |
| m.ids_source, | |
| m.anomaly_source, | |
| ) | |
| app.state.phishing, app.state.phishing_source = m.phishing, m.phishing_source | |
| app.state.url, app.state.url_source = m.url, m.url_source | |
| else: | |
| app.state.detector = Detector(bundle, anomaly) | |
| app.state.source = source | |
| app.state.anomaly_source = anomaly_source if anomaly else None | |
| app.state.phishing = phishing | |
| app.state.phishing_source = phishing_source if phishing else None | |
| app.state.url = url | |
| app.state.url_source = url_source if url else None | |
| app.state.copilot = copilot | |
| app.state.copilot_lock = threading.Lock() | |
| app.state.investigations = {} # alert id -> Future of the running investigation | |
| app.state.investigations_lock = threading.Lock() | |
| if copilot is None and warm_copilot: | |
| # Built in the background: the API serves scoring and alerts meanwhile. | |
| threading.Thread(target=_warm_copilot, args=(app,), daemon=True).start() | |
| if suspicious_threshold is None: | |
| from sentinel.common.config import load_params | |
| app.state.suspicious = load_params().phishing.suspicious_threshold | |
| else: | |
| app.state.suspicious = suspicious_threshold | |
| app.state.sender_policy = ( | |
| load_policy(SENDER_POLICY) | load_policy(INTEL_POLICY) | load_policy(PAYMENT_POLICY) | |
| if sender_policy is None | |
| else sender_policy | |
| ) | |
| if not app.state.sender_policy: | |
| log.warning("no %s: sender checks can only mark email suspicious", SENDER_POLICY) | |
| app.state.intel = intel | |
| if intel is None and bundle is None: | |
| from sentinel.common.config import load_params | |
| cfg = load_params().phishing.intel | |
| if cfg.enabled: | |
| app.state.intel = Intel( | |
| INTEL_CACHE, | |
| new_domain_days=cfg.new_domain_days, | |
| rdap=cfg.rdap, | |
| rdap_timeout=cfg.rdap_timeout_s, | |
| max_lookups=cfg.max_lookups, | |
| refresh_hours=cfg.refresh_hours, | |
| ) | |
| if app.state.intel is not None and not app.state.intel.feeds_loaded: | |
| # Downloads take seconds; emails are checked without blocklists meanwhile. | |
| threading.Thread(target=app.state.intel.refresh_feeds, daemon=True).start() | |
| app.state.db = db | |
| yield | |
| app = FastAPI(title="Sentinel API", version="0.5.0", lifespan=lifespan) | |
| instrument(app) | |
| if api_key: | |
| protect(app, api_key) | |
| if demo: | |
| from sentinel.demo import guard | |
| guard(app) | |
| app.include_router(dashboard_router) | |
| app.include_router(feedback_router) | |
| async def _replay_feed(ws: WebSocket) -> None: | |
| """Demo: nothing streams, so replay the recorded alerts in time order, a few a second, | |
| from where the overview's hour window begins, looping at the end. Marked `replay`.""" | |
| def start() -> int: | |
| with _db_engine(ws.app).connect() as conn: | |
| latest = conn.execute(select(func.max(alerts_table.c.ts))).scalar() | |
| if latest is None: | |
| return 0 | |
| return int( | |
| conn.execute( | |
| select(func.count()).where(alerts_table.c.ts < latest - timedelta(hours=1)) | |
| ).scalar() | |
| or 0 | |
| ) | |
| def chunk(offset: int) -> list[Any]: | |
| with _db_engine(ws.app).connect() as conn: | |
| return list( | |
| conn.execute( | |
| select(*[alerts_table.c[c] for c in WS_COLUMNS]) | |
| .order_by(alerts_table.c.ts, alerts_table.c.id) | |
| .offset(offset) | |
| .limit(DEMO_REPLAY_BATCH) | |
| ).all() | |
| ) | |
| try: | |
| offset = await asyncio.to_thread(start) | |
| while True: | |
| rows = await asyncio.to_thread(chunk, offset) | |
| if not rows: | |
| if offset == 0: # empty database | |
| return | |
| offset = 0 | |
| continue | |
| offset += len(rows) | |
| await ws.send_json( | |
| { | |
| "alerts": [ | |
| jsonable_encoder(dict(zip(WS_COLUMNS, r, strict=True))) for r in rows | |
| ], | |
| "replay": True, | |
| } | |
| ) | |
| await asyncio.sleep(WS_POLL_SECONDS) | |
| except WebSocketDisconnect: | |
| return | |
| async def ws_alerts(ws: WebSocket) -> None: | |
| """Live alert feed: new rows of the alerts table, pushed as they are written. | |
| Polls the database once a second for ids above the last one sent, so any writer | |
| (stream detector, batch loader) shows up and the API needs no Kafka connection. | |
| Query `since_id` to resume; by default the feed starts at the newest alert. | |
| """ | |
| if api_key and not authorized(ws.headers.get("authorization"), api_key): | |
| await ws.close(code=1008) # policy violation: the HTTP middleware skips WebSockets | |
| return | |
| await ws.accept() | |
| if demo: | |
| await _replay_feed(ws) | |
| return | |
| since = ws.query_params.get("since_id") | |
| # Database calls run in worker threads: a slow or stopped database must not block | |
| # the event loop, which serves every other request too. | |
| def newest() -> int: | |
| with _db_engine(ws.app).connect() as conn: | |
| return int(conn.execute(select(func.max(alerts_table.c.id))).scalar() or 0) | |
| def after(last: int) -> list[Any]: | |
| with _db_engine(ws.app).connect() as conn: | |
| return list( | |
| conn.execute( | |
| select(*[alerts_table.c[c] for c in WS_COLUMNS]) | |
| .where(alerts_table.c.id > last) | |
| .order_by(alerts_table.c.id) | |
| .limit(WS_MAX_BATCH) | |
| ).all() | |
| ) | |
| try: | |
| last = int(since) if since else await asyncio.to_thread(newest) | |
| while True: | |
| rows = await asyncio.to_thread(after, last) | |
| if rows: | |
| last = int(rows[-1][0]) | |
| await ws.send_json( | |
| { | |
| "alerts": [ | |
| jsonable_encoder(dict(zip(WS_COLUMNS, r, strict=True))) | |
| for r in rows | |
| ] | |
| } | |
| ) | |
| await asyncio.sleep(WS_POLL_SECONDS) | |
| except WebSocketDisconnect: | |
| return | |
| except SQLAlchemyError as exc: # the client reconnects and resumes | |
| log.warning("alert feed closed: database error: %s", exc) | |
| await ws.close(code=1011) | |
| def root() -> RedirectResponse: | |
| return RedirectResponse("/app/" if FRONTEND_DIST.exists() else "/docs") | |
| def frontend(path: str = "") -> FileResponse: | |
| """The built dashboard (frontend/dist); client routes fall back to index.html.""" | |
| if not FRONTEND_DIST.exists(): | |
| raise HTTPException(404, detail="dashboard not built: cd frontend && npm run build") | |
| target = (FRONTEND_DIST / path).resolve() | |
| if path and target.is_file() and FRONTEND_DIST.resolve() in target.parents: | |
| return FileResponse(target) | |
| return FileResponse(FRONTEND_DIST / "index.html") | |
| def health(request: Request) -> dict[str, Any]: | |
| d: Detector | None = getattr(request.app.state, "detector", None) | |
| return { | |
| "status": "ok", | |
| "model_loaded": d is not None, | |
| "anomaly_model_loaded": d is not None and d.anomaly is not None, | |
| "phishing_model_loaded": getattr(request.app.state, "phishing", None) is not None, | |
| "url_model_loaded": getattr(request.app.state, "url", None) is not None, | |
| "demo": demo, | |
| "intel": ti.status() if (ti := getattr(request.app.state, "intel", None)) else None, | |
| } | |
| def models(request: Request) -> dict[str, Any]: | |
| d: Detector = request.app.state.detector | |
| out: dict[str, Any] = { | |
| "ids": { | |
| "source": request.app.state.source, | |
| "threshold": d.ids.threshold, | |
| "lgbm_weight": d.ids.lgbm_weight, | |
| "severity_bands": d.ids.severity_bands, | |
| "n_features": len(d.ids.spec.columns), | |
| "metadata": d.ids.metadata, | |
| }, | |
| "anomaly": None, | |
| } | |
| if d.anomaly is not None: | |
| out["anomaly"] = { | |
| "source": request.app.state.anomaly_source, | |
| "threshold": d.anomaly.threshold, | |
| "fpr_target": d.anomaly.fpr_target, | |
| "metadata": d.anomaly.metadata, | |
| } | |
| ph: PhishingOnnxModel | None = request.app.state.phishing | |
| out["phishing"] = ( | |
| { | |
| "source": request.app.state.phishing_source, | |
| "threshold": ph.threshold, | |
| "max_len": ph.max_len, | |
| "metadata": ph.metadata, | |
| } | |
| if ph is not None | |
| else None | |
| ) | |
| um: UrlModel | None = request.app.state.url | |
| out["url"] = ( | |
| { | |
| "source": request.app.state.url_source, | |
| "threshold": um.threshold, | |
| "metadata": um.metadata, | |
| } | |
| if um is not None | |
| else None | |
| ) | |
| return out | |
| def score_url(batch: UrlBatch, request: Request) -> UrlResponse: | |
| um: UrlModel | None = request.app.state.url | |
| if um is None: | |
| raise HTTPException(503, detail="URL model not loaded") | |
| return UrlResponse( | |
| threshold=um.threshold, | |
| results=score_urls(um, batch.urls, batch.explain), | |
| model_version=request.app.state.url_source, | |
| ) | |
| def score_phishing(email: EmailIn, request: Request) -> EmailScore: | |
| ph: PhishingOnnxModel | None = request.app.state.phishing | |
| if ph is None: | |
| raise HTTPException(503, detail="phishing model not loaded") | |
| subject, body = email.subject, email.body | |
| who: Sender | None = None | |
| sent = None | |
| if email.eml: | |
| try: | |
| parsed = parse_eml(email.eml.encode("utf-8", "surrogateescape")) | |
| except Exception as exc: # malformed message | |
| raise HTTPException(422, detail=f"could not read the .eml: {exc}") from None | |
| subject, body, who = parsed.subject, parsed.body, parsed.sender | |
| sent = sent_at(parsed.date) | |
| if not body.strip() and not subject.strip(): | |
| raise HTTPException(422, detail="the .eml has no readable text part") | |
| else: | |
| who = parse_sender(email.sender, email.reply_to) if email.sender else None | |
| text = model_input(subject, body) | |
| prob = float(ph.predict_proba([text])[0]) | |
| text_flag = prob >= ph.threshold | |
| urls = list(dict.fromkeys([*extract_urls(f"{subject}\n{body}"), *email.urls])) | |
| um: UrlModel | None = request.app.state.url | |
| url_results = score_urls(um, urls[:MAX_EMAIL_URLS], email.explain) if um else [] | |
| # A link flags the email only above the validation-tuned email threshold; the | |
| # per-URL verdict (is_malicious) uses the stricter-on-false-alarms URL threshold. | |
| url_flag = ( | |
| um is not None | |
| and um.email_threshold is not None | |
| and any(r.probability >= um.email_threshold for r in url_results) | |
| ) | |
| policy = request.app.state.sender_policy | |
| findings = ( | |
| [ | |
| SenderFinding( | |
| check=f.check, severity=f.severity, role=role_of(f.check, policy), text=f.text | |
| ) | |
| for f in check_sender(who) | |
| ] | |
| if who is not None | |
| else [] | |
| ) | |
| sender_flag = any(f.role == "alert" for f in findings) | |
| intel_out: IntelReportOut | None = None | |
| ti: Intel | None = request.app.state.intel | |
| if ti is not None: | |
| found = ti.check(who, urls[:MAX_EMAIL_URLS], sent) | |
| intel_out = IntelReportOut( | |
| domains=[IntelDomain(**vars(d)) for d in found.domains], | |
| findings=[ | |
| SenderFinding( | |
| check=f.check, | |
| severity=f.severity, | |
| role=role_of(f.check, policy), | |
| text=f.text, | |
| ) | |
| for f in found.findings | |
| ], | |
| feeds_loaded=found.feeds_loaded, | |
| ) | |
| intel_findings = intel_out.findings if intel_out else [] | |
| intel_flag = any(f.role == "alert" for f in intel_findings) | |
| pay = check_payment(text) | |
| risky = escalate(pay, [f.check for f in (*findings, *intel_findings)]) | |
| payment = [ | |
| SenderFinding( | |
| check=f.check, severity=f.severity, role=role_of(f.check, policy), text=f.text | |
| ) | |
| for f in (*pay, *([risky] if risky else [])) | |
| ] | |
| payment_flag = any(f.role == "alert" for f in payment) | |
| flagged_by = [ | |
| name | |
| for name, hit in ( | |
| ("text", text_flag), | |
| ("url", url_flag), | |
| ("sender", sender_flag), | |
| ("intel", intel_flag), | |
| ("payment", payment_flag), | |
| ) | |
| if hit | |
| ] | |
| strong = prob >= 0.999 or any(r.probability >= 0.99 for r in url_results) | |
| review = float(request.app.state.suspicious) | |
| because: list[str] = [] | |
| if not flagged_by: | |
| # The alert thresholds are strict (0.31% false alarms on legitimate mail), so | |
| # near-misses and bad links go to review instead of passing as clean. | |
| if prob >= review: | |
| because.append( | |
| f"text score {prob:.3f} is in the review band " | |
| f"({review:.2f} to {ph.threshold:.3f})" | |
| ) | |
| because += [ | |
| f"link judged malicious ({r.probability:.3f}): {r.url}" | |
| for r in url_results | |
| if r.is_malicious | |
| ] | |
| because += [f"sender: {f.text}" for f in findings if f.role == "review"] | |
| because += [f"intel: {f.text}" for f in intel_findings if f.role == "review"] | |
| because += [f"payment: {f.text}" for f in payment if f.role == "review"] | |
| verdict = "malicious" if flagged_by else "suspicious" if because else "clean" | |
| reasons = explain(ph, text) if email.explain and (text_flag or prob >= review) else [] | |
| return EmailScore( | |
| is_malicious=bool(flagged_by), | |
| flagged_by=flagged_by, | |
| verdict=verdict, | |
| suspicious_because=because, | |
| probability=prob, | |
| threshold=ph.threshold, | |
| suspicious_threshold=review, | |
| severity=("High" if strong or len(flagged_by) >= 2 else "Medium") | |
| if flagged_by | |
| else "Low" | |
| if because | |
| else None, | |
| reasons=[EmailReason(**r) for r in reasons], | |
| urls=urls, | |
| url_results=url_results, | |
| sender=SenderReport( | |
| from_line=who.from_, | |
| address=who.address, | |
| domain=who.registered, | |
| reply_to=who.reply_to, | |
| auth=who.auth, | |
| findings=findings, | |
| ) | |
| if who is not None | |
| else None, | |
| intel=intel_out, | |
| payment=payment, | |
| subject=subject, | |
| model_version=request.app.state.phishing_source, | |
| url_model_version=request.app.state.url_source, | |
| ) | |
| def _db(request: Request) -> Engine: | |
| return _db_engine(request.app) | |
| def list_alerts( | |
| request: Request, | |
| family: str | None = None, | |
| severity: str | None = None, | |
| source: str | None = None, | |
| src_ip: str | None = None, | |
| since: datetime | None = None, | |
| limit: int = Query(50, ge=1, le=100), | |
| ) -> dict[str, Any]: | |
| tools = AlertTools(_db(request)) | |
| rows = tools.query_alerts( | |
| since=since, | |
| limit=limit, | |
| predicted_family=family, | |
| severity=severity, | |
| source=source, | |
| src_ip=src_ip, | |
| ) | |
| return {"alerts": rows, "count": len(rows)} | |
| def get_alert(alert_id: int, request: Request) -> dict[str, Any]: | |
| alert = AlertTools(_db(request)).get_alert(alert_id) | |
| if alert is None: | |
| raise HTTPException(404, detail="alert not found") | |
| return alert | |
| def investigate(alert_id: int, request: Request) -> IncidentReport: | |
| """Run the investigation graph (seconds with Gemini, minutes on the local model). | |
| A second request for an alert already being investigated (a double click, another | |
| tab) waits for that run and gets the same report instead of starting another one. | |
| """ | |
| if demo: | |
| return _stored_report(alert_id, request) | |
| state = request.app.state | |
| with state.investigations_lock: | |
| running: Future[IncidentReport] | None = state.investigations.get(alert_id) | |
| if running is None: | |
| mine: Future[IncidentReport] = Future() | |
| state.investigations[alert_id] = mine | |
| if running is not None: | |
| return running.result() | |
| try: | |
| report = _investigate(alert_id, request) | |
| except BaseException as exc: | |
| mine.set_exception(exc) | |
| raise | |
| else: | |
| mine.set_result(report) | |
| return report | |
| finally: | |
| with state.investigations_lock: | |
| state.investigations.pop(alert_id, None) | |
| def _stored_report(alert_id: int, request: Request) -> IncidentReport: | |
| """Demo: the latest stored report for the alert; live investigations are off.""" | |
| with _db(request).connect() as conn: | |
| row = conn.execute( | |
| select(reports_table.c.report) | |
| .where(reports_table.c.alert_id == alert_id, reports_table.c.status == "done") | |
| .order_by(reports_table.c.created.desc()) | |
| .limit(1) | |
| ).first() | |
| if row is None: | |
| with_reports = conn.execute( | |
| select(reports_table.c.alert_id).distinct().order_by(reports_table.c.alert_id) | |
| ).scalars() | |
| ids = ", ".join(f"#{a}" for a in with_reports) | |
| raise HTTPException( | |
| 403, | |
| detail="Live investigations are turned off in the public demo (they call " | |
| f"an LLM). Stored reports exist for alerts {ids}.", | |
| ) | |
| return IncidentReport.model_validate(row[0]) | |
| def _investigate(alert_id: int, request: Request) -> IncidentReport: | |
| from sentinel.copilot.graph import AlertNotFoundError | |
| t0 = time.perf_counter() | |
| try: | |
| report, trace = _get_copilot(request.app).investigate(alert_id) | |
| except AlertNotFoundError: | |
| raise HTTPException(404, detail="alert not found") from None | |
| record_report(report, time.perf_counter() - t0) | |
| with _db(request).begin() as conn: | |
| conn.execute( | |
| insert(reports_table).values( | |
| id=report.report_id, | |
| alert_id=alert_id, | |
| created=datetime.now(UTC).replace(tzinfo=None), | |
| status="done", | |
| provider=report.provider, | |
| report=report.model_dump(mode="json"), | |
| trace=trace, | |
| ) | |
| ) | |
| return report | |
| def get_report(report_id: str, request: Request) -> IncidentReport: | |
| with _db(request).connect() as conn: | |
| row = conn.execute( | |
| select(reports_table.c.report).where(reports_table.c.id == report_id) | |
| ).first() | |
| if row is None: | |
| raise HTTPException(404, detail="report not found") | |
| return IncidentReport.model_validate(row[0]) | |
| def score_flows(batch: FlowBatch, request: Request) -> ScoreResponse: | |
| d: Detector = request.app.state.detector | |
| required = sorted( | |
| set(d.ids.spec.input_columns) | set(d.anomaly.spec.input_columns if d.anomaly else []) | |
| ) | |
| missing = sorted({c for row in batch.flows for c in required if c not in row}) | |
| if missing: | |
| raise HTTPException(422, detail={"missing_features": missing}) | |
| df = pl.DataFrame( | |
| [{c: row[c] for c in required} for row in batch.flows], | |
| schema={c: pl.Float64 for c in required}, | |
| ) | |
| results = d.predict(df, explain=batch.explain) | |
| return ScoreResponse( | |
| model_version=str(request.app.state.source), | |
| anomaly_model_version=request.app.state.anomaly_source, | |
| results=[FlowScore.model_validate(r) for r in results], | |
| ) | |
| return app | |