Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

fix(customer-journey): resolve all API routing and version bugs found in site review

Beenu Arora7e2eb8a74a1d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e3d51d453..12ccc1ba1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,79 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+## [6.0.0] — 2026-05-06
+
+### Added
+
+#### Wave 3 — Operational Maturity
+
+- **MSSP / parent-tenant console** (`services/api/migrations/012_mssp_console.sql`,
+ `services/api/app/models/mssp.py`, `services/api/app/api/v1/endpoints/mssp.py`) —
+ Parent tenants can onboard child tenants, manage cross-tenant delegations, add
+ per-tenant notes, and view an aggregated metrics rollup in a single pane.
+
+- **Asset inventory + vuln-to-alert correlation** (`services/api/migrations/013_asset_inventory.sql`,
+ `services/api/app/models/asset.py`, `services/api/app/api/v1/endpoints/assets.py`) —
+ CRUD for discovered assets with vulnerability findings auto-correlated to alerts.
+ Surfaces asset blast radius and enables asset-context enrichment during triage.
+
+- **Insider threat module** (`services/api/migrations/014_insider_threat.sql`,
+ `services/api/app/models/insider_threat.py`,
+ `services/api/app/api/v1/endpoints/insider_threat.py`) —
+ User risk profiles, behavioural indicators, peer-group deviation scoring, and
+ watchlist management. Risk scores update incrementally as new indicators arrive.
+
+- **L0–L4 auto-remediation maturity tiers** (`services/api/migrations/015_remediation_maturity.sql`,
+ `services/api/app/models/remediation.py`,
+ `services/api/app/api/v1/endpoints/remediation.py`,
+ `services/actions/app/services/maturity.py`) —
+ Per-tenant configuration of remediation autonomy from L0 (manual only) through L4
+ (fully autonomous). Gate log records every approve/block decision. Per-action whitelist
+ pre-approves low-risk actions regardless of tier.
+
+#### Wave 4 — Advanced Capabilities
+
+- **Internal threat intelligence** (`services/api/migrations/016_threat_intel.sql`,
+ `services/api/app/models/threat_intel.py`,
+ `services/api/app/api/v1/endpoints/threat_intel.py`) —
+ IOC harvesting from alert history, threat actor and campaign profiles, and STIX/TAXII
+ feed subscription management, all queryable via the REST API.
+
+- **Cloud security posture management (CSPM/KSPM)** (`services/api/migrations/017_cspm.sql`,
+ `services/api/app/models/posture.py`, `services/api/app/api/v1/endpoints/posture.py`) —
+ Ingests posture findings from cloud providers, tracks drift between scan runs, and
+ surfaces a per-provider posture summary with suppress/resolve workflows.
+
+- **Identity-centric correlation graph** (`services/api/migrations/018_identity_graph.sql`,
+ `services/api/app/models/identity_graph.py`,
+ `services/api/app/api/v1/endpoints/identity_graph.py`) —
+ Graph of users, devices, service accounts, and roles with typed relationship edges.
+ Alerts link to identity nodes, enabling blast-radius queries and attack-path
+ reconstruction.
+
+- **Auto-generated board reports** (`services/api/migrations/019_board_reports.sql`,
+ `services/api/app/models/report.py`, `services/api/app/api/v1/endpoints/reports.py`) —
+ Report templates and scheduled generation of PDF/HTML executive summaries. Artefacts
+ are stored, versioned, and deliverable via email or webhook.
+
+#### Platform
+
+- **Dashboard metrics API** (`services/api/app/api/v1/endpoints/metrics.py`) —
+ `/api/v1/metrics/dashboard` aggregates alert KPIs, case counts, connector source
+ stats, top MITRE tactics, 24-hour alert trend, and threats-by-source for the
+ frontend dashboard tiles. `/api/v1/metrics/alerts/trend` supports `1h / 24h / 7d / 30d`
+ period buckets.
+
+- **Tailscale connector** (`services/connectors/app/connectors/tailscale.py`) —
+ Pulls audit logs and policy-file change events from the Tailscale API with
+ OAuth client-credential and API-key auth, cursor-based pagination, and four-tier
+ severity mapping.
+
+- **AWS GuardDuty credential-exfiltration detection** (`detections/cloud/aws-guardduty-instance-credential-exfiltration.yaml`) —
+ Sigma rule covering EC2 instance credential exfiltration via `UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration`.
+
+---
+
### Click-and-connect cloud connector platform
This pass turns connectors from a hardcoded, code-edit-only feature into a
diff --git a/ROADMAP.md b/ROADMAP.md
index d8f68ddaa..cdf42b798 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -92,29 +92,27 @@ This document captures the planned direction for AiSOC across major versions. Al
---
-## v6.0 — Planned
-
-### Investigation & Forensics Depth
-- Super-timeline view (Plaso-style, all event sources on one scrubbable axis)
-- Process tree and lateral movement graph (extending `graph_service.py`)
-- PCAP viewer and network session reconstruction
-- Memory and disk artifact viewer (Volatility / Velociraptor integration)
-- Evidence vault — signed, hashed, chain-of-custody for every artifact
-
-### Data Source Breadth
-- Identity: Okta, Azure AD/Entra, Google Workspace, Duo (full production connectors)
-- Cloud: AWS CloudTrail/GuardDuty, Azure Defender, GCP Security Command Center, Kubernetes audit + Falco
-- EDR: CrowdStrike Falcon, SentinelOne, Microsoft Defender for Endpoint, Wazuh
-- Email: Gmail/Workspace, Microsoft 365, Mimecast, Proofpoint — phishing triage agent
-- Network: Zeek, Suricata/NFSen, NDR (Arkime/Stenographer)
-- STIX/TAXII server (both consume and serve IOCs)
-- MISP and OpenCTI federation
-
-### Attack Surface & Vulnerability
-- ASM / CTEM module — external attack surface discovery feeding TI
-- CVE + EPSS + KEV joined to asset inventory for vuln↔alert correlation
-- ITDR (Identity Threat Detection & Response) module
-- CSPM / CNAPP lite — cloud misconfiguration with runtime correlation
+## v6.0 — Shipped (2026-05-06)
+
+### Wave 3 — Operational Maturity
+
+- [x] MSSP / parent-tenant console — onboard child tenants, delegate cross-tenant actions, view rollup metrics
+- [x] Asset inventory + vuln-to-alert correlation — asset CRUD, vulnerability findings, blast-radius context
+- [x] Insider threat module — user risk profiles, behavioural indicators, peer-group deviation scoring
+- [x] L0–L4 auto-remediation maturity tiers — per-tenant autonomy gate with audit log and per-action whitelist
+
+### Wave 4 — Advanced Capabilities
+
+- [x] Internal threat intelligence — IOC harvesting, threat actor profiles, STIX/TAXII feed subscriptions
+- [x] Cloud security posture management (CSPM/KSPM) — posture findings, drift tracking, suppress/resolve workflows
+- [x] Identity-centric correlation graph — identity node/edge graph, alert-to-identity linking, attack-path queries
+- [x] Auto-generated board reports — report templates, scheduled PDF/HTML artefacts, email/webhook delivery
+
+### Platform
+
+- [x] Dashboard metrics API — aggregated KPI endpoint powering frontend dashboard tiles
+- [x] Tailscale connector — audit log and policy-change events with cursor-based pagination
+- [x] AWS GuardDuty credential-exfiltration Sigma detection rule
---
diff --git a/apps/web/next.config.js b/apps/web/next.config.js
index 9a4b2d3d1..41dc8dad2 100644
--- a/apps/web/next.config.js
+++ b/apps/web/next.config.js
@@ -17,6 +17,7 @@ const AGENTS_HOST = process.env.AGENTS_URL || 'http://localhost:8001';
// We surface those to the browser under the same-origin namespace
// /api/v1/fusion/* so the bundle stays host-agnostic.
const FUSION_HOST = process.env.FUSION_URL || 'http://localhost:8082';
+const ENRICHMENT_HOST = process.env.ENRICHMENT_URL || 'http://localhost:8083';
const nextConfig = {
reactStrictMode: true,
@@ -78,10 +79,9 @@ const nextConfig = {
source: '/api/v1/realtime/healthz',
destination: `${REALTIME_HOST}/healthz`,
},
- // Agents service owns contextual actions, playbooks, and investigations.
- // These must come before the `/api/v1/:path*` catch-all so they don't
- // get sent to the core API (which doesn't have those routes and would
- // 503).
+ // Agents service owns contextual actions, playbooks, investigations,
+ // hunt search, and copilot chat. These must come before the
+ // `/api/v1/:path*` catch-all so they don't get sent to the core API.
{
source: '/api/v1/contextual/:path*',
destination: `${AGENTS_HOST}/api/v1/contextual/:path*`,
@@ -102,6 +102,42 @@ const nextConfig = {
source: '/api/v1/investigations',
destination: `${AGENTS_HOST}/api/v1/investigations`,
},
+ // Hunt search + saved searches (singular /hunt, distinct from /hunts corpus)
+ {
+ source: '/api/v1/hunt/:path*',
+ destination: `${AGENTS_HOST}/api/v1/hunt/:path*`,
+ },
+ {
+ source: '/api/v1/hunt',
+ destination: `${AGENTS_HOST}/api/v1/hunt`,
+ },
+ // Copilot persistent chat conversations
+ {
+ source: '/api/v1/copilot/:path*',
+ destination: `${AGENTS_HOST}/api/v1/copilot/:path*`,
+ },
+ {
+ source: '/api/v1/copilot',
+ destination: `${AGENTS_HOST}/api/v1/copilot`,
+ },
+ // Hunt corpus management (plural /hunts)
+ {
+ source: '/api/v1/hunts/:path*',
+ destination: `${AGENTS_HOST}/api/v1/hunts/:path*`,
+ },
+ {
+ source: '/api/v1/hunts',
+ destination: `${AGENTS_HOST}/api/v1/hunts`,
+ },
+ // Enrichment service (Go service; paths differ from /api/v1 prefix)
+ {
+ source: '/api/v1/enrichment/lookup',
+ destination: `${ENRICHMENT_HOST}/enrich`,
+ },
+ {
+ source: '/api/v1/enrichment/bulk',
+ destination: `${ENRICHMENT_HOST}/enrich/bulk`,
+ },
// Fusion service exposes the Risk-Based Alerting (entity rollup) queue
// and ML scoring endpoints at its own root (no /api/v1 prefix on the
// service side). Proxy /api/v1/fusion/:path* → fusion's /:path* so the
diff --git a/apps/web/package.json b/apps/web/package.json
index ebe995d93..5c89e80f6 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -1,6 +1,6 @@
{
"name": "@aisoc/web",
- "version": "5.1.0",
+ "version": "6.0.0",
"private": true,
"description": "AiSOC SOC Console - Next.js 14 Frontend",
"license": "MIT",
diff --git a/apps/web/src/components/landing/Footer.tsx b/apps/web/src/components/landing/Footer.tsx
index 915e92ef5..4556d9bde 100644
--- a/apps/web/src/components/landing/Footer.tsx
+++ b/apps/web/src/components/landing/Footer.tsx
@@ -112,7 +112,7 @@ export function Footer() {
rel="noreferrer"
className="font-mono hover:text-white"
>
- v5.2.0
+ v6.0.0
</a>
</div>
</div>
diff --git a/apps/web/src/components/settings/SettingsView.tsx b/apps/web/src/components/settings/SettingsView.tsx
index 008b90d5b..59efabb34 100644
--- a/apps/web/src/components/settings/SettingsView.tsx
+++ b/apps/web/src/components/settings/SettingsView.tsx
@@ -1312,7 +1312,7 @@ function AboutPanel() {
description="Open-source SOC platform — community-built, MIT licensed."
/>
<div className="grid gap-4 px-6 py-5 sm:grid-cols-2">
- <InfoTile label="Version" value="v5.2.0" />
+ <InfoTile label="Version" value="v6.0.0" />
<InfoTile label="Build" value="local • dev" />
<InfoTile label="License" value="MIT" />
<InfoTile label="Source" value="github.com/beenuar/AiSOC" mono />
diff --git a/services/agents/app/api/copilot.py b/services/agents/app/api/copilot.py
new file mode 100644
index 000000000..3b67ac8cd
--- /dev/null
+++ b/services/agents/app/api/copilot.py
@@ -0,0 +1,272 @@
+"""
+Copilot chat API — persistent conversation history.
+
+Endpoints (all under ``/api/v1/copilot``):
+
+ GET /conversations — list the last N conversations
+ GET /conversations/{id} — retrieve a single conversation
+ POST /chat — one-shot chat (creates / continues conv.)
+ POST /chat/stream — streaming NDJSON variant
+
+Falls back to synthetic deterministic replies when ``OPENAI_API_KEY`` is
+unset so the demo path never breaks.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import uuid
+from collections.abc import AsyncIterator
+from datetime import UTC, datetime
+from typing import Any
+
+import structlog
+from fastapi import APIRouter
+from fastapi.responses import StreamingResponse
+from pydantic import BaseModel, Field
+
+logger = structlog.get_logger()
+
+router = APIRouter(prefix="/api/v1/copilot", tags=["copilot"])
+
+
+# ---------------------------------------------------------------------------
+# Shapes
+# ---------------------------------------------------------------------------
+
+
+class CopilotMessage(BaseModel):
+ id: str = Field(default_factory=lambda: str(uuid.uuid4()))
+ role: str # "user" | "assistant"
+ content: str
+ timestamp: str = Field(
+ default_factory=lambda: datetime.now(UTC).isoformat()
+ )
+
+
+class CopilotChatRequest(BaseModel):
+ message: str
+ conversationId: str | None = None
+ context: dict[str, Any] | None = None
+
+
+class CopilotChatResponse(BaseModel):
+ conversationId: str
+ reply: CopilotMessage
+
+
+class CopilotConversation(BaseModel):
+ id: str
+ title: str
+ updatedAt: str
+ messageCount: int
+
+
+# ---------------------------------------------------------------------------
+# In-memory store (demo: resets on restart; production would use Postgres)
+# ---------------------------------------------------------------------------
+
+_CONVERSATIONS: dict[str, dict[str, Any]] = {}
+
+_SYNTHETIC_REPLIES = [
+ "I've analysed the alert context. The activity matches T1078 (Valid Accounts) combined with T1021.002 (SMB/Windows Admin Shares) lateral movement. Recommend isolating the host and reviewing recent authentication logs.",
+ "Based on the indicators, this looks like credential-access activity. The parent process chain suggests a LOLBin pattern. Consider adding a detection rule for this specific chain.",
+ "The entity risk score is elevated due to multiple failed authentications followed by a successful login from an unusual geolocation. I recommend triggering a step-up MFA challenge.",
+ "Correlation across the last 24 hours shows this IP was seen in 3 other alerts. The MITRE mapping points to T1110 (Brute Force). Blocking the IP at the perimeter is the fastest remediation.",
+ "I've reviewed the case timeline. The attacker dwell time appears short (< 2 hours), suggesting this may be an automated credential-stuffing campaign rather than a targeted intrusion.",
+]
+
+_reply_idx = 0
+
+
+def _synthetic_reply(user_msg: str) -> str:
+ global _reply_idx
+ reply = _SYNTHETIC_REPLIES[_reply_idx % len(_SYNTHETIC_REPLIES)]
+ _reply_idx += 1
+ return reply
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _title_from_message(msg: str) -> str:
+ return msg[:60] + ("…" if len(msg) > 60 else "")
+
+
+async def _get_openai_reply(
+ conversation: dict[str, Any],
+ user_message: str,
+) -> str:
+ api_key = os.getenv("OPENAI_API_KEY", "")
+ if not api_key:
+ return _synthetic_reply(user_message)
+
+ try:
+ import httpx
+
+ messages = [
+ {
+ "role": "system",
+ "content": (
+ "You are AiSOC Copilot, an AI assistant for security operations. "
+ "Help analysts investigate alerts, correlate events, and respond to threats. "
+ "Be concise, technical, and actionable. Reference MITRE ATT&CK techniques "
+ "when relevant. Format recommendations as numbered steps when appropriate."
+ ),
+ }
+ ]
+ for m in conversation.get("messages", [])[-10:]: # last 10 for context
+ messages.append({"role": m["role"], "content": m["content"]})
+ messages.append({"role": "user", "content": user_message})
+
+ async with httpx.AsyncClient(timeout=30) as client:
+ resp = await client.post(
+ "https://api.openai.com/v1/chat/completions",
+ headers={"Authorization": f"Bearer {api_key}"},
+ json={"model": "gpt-4o-mini", "messages": messages, "max_tokens": 512},
+ )
+ resp.raise_for_status()
+ return resp.json()["choices"][0]["message"]["content"]
+ except Exception as exc:
+ logger.warning("copilot.openai_error", error=str(exc))
+ return _synthetic_reply(user_message)
+
+
+# ---------------------------------------------------------------------------
+# Endpoints
+# ---------------------------------------------------------------------------
+
+
[email protected]("/conversations")
+async def list_conversations(limit: int = 20) -> dict[str, Any]:
+ convs = sorted(
+ _CONVERSATIONS.values(),
+ key=lambda c: c["updatedAt"],
+ reverse=True,
+ )[:limit]
+ return {
+ "conversations": [
+ {
+ "id": c["id"],
+ "title": c["title"],
+ "updatedAt": c["updatedAt"],
+ "messageCount": len(c["messages"]),
+ }
+ for c in convs
+ ]
+ }
+
+
[email protected]("/conversations/{conversation_id}")
+async def get_conversation(conversation_id: str) -> dict[str, Any]:
+ conv = _CONVERSATIONS.get(conversation_id)
+ if conv is None:
+ return {"id": conversation_id, "title": "Not found", "messages": []}
+ return {
+ "id": conv["id"],
+ "title": conv["title"],
+ "messages": conv["messages"],
+ }
+
+
[email protected]("/chat", response_model=CopilotChatResponse)
+async def chat(req: CopilotChatRequest) -> CopilotChatResponse:
+ conv_id = req.conversationId or str(uuid.uuid4())
+ now = datetime.now(UTC).isoformat()
+
+ if conv_id not in _CONVERSATIONS:
+ _CONVERSATIONS[conv_id] = {
+ "id": conv_id,
+ "title": _title_from_message(req.message),
+ "messages": [],
+ "updatedAt": now,
+ }
+
+ conv = _CONVERSATIONS[conv_id]
+
+ user_msg: dict[str, Any] = {
+ "id": str(uuid.uuid4()),
+ "role": "user",
+ "content": req.message,
+ "timestamp": now,
+ }
+ conv["messages"].append(user_msg)
+
+ reply_text = await _get_openai_reply(conv, req.message)
+
+ assistant_msg: dict[str, Any] = {
+ "id": str(uuid.uuid4()),
+ "role": "assistant",
+ "content": reply_text,
+ "timestamp": datetime.now(UTC).isoformat(),
+ }
+ conv["messages"].append(assistant_msg)
+ conv["updatedAt"] = assistant_msg["timestamp"]
+
+ return CopilotChatResponse(
+ conversationId=conv_id,
+ reply=CopilotMessage(**assistant_msg),
+ )
+
+
[email protected]("/chat/stream")
+async def chat_stream(req: CopilotChatRequest) -> StreamingResponse:
+ """Stream a chat reply as NDJSON deltas."""
+
+ conv_id = req.conversationId or str(uuid.uuid4())
+ now = datetime.now(UTC).isoformat()
+
+ if conv_id not in _CONVERSATIONS:
+ _CONVERSATIONS[conv_id] = {
+ "id": conv_id,
+ "title": _title_from_message(req.message),
+ "messages": [],
+ "updatedAt": now,
+ }
+
+ conv = _CONVERSATIONS[conv_id]
+ user_msg: dict[str, Any] = {
+ "id": str(uuid.uuid4()),
+ "role": "user",
+ "content": req.message,
+ "timestamp": now,
+ }
+ conv["messages"].append(user_msg)
+
+ reply_text = await _get_openai_reply(conv, req.message)
+ msg_id = str(uuid.uuid4())
+
+ async def _stream() -> AsyncIterator[bytes]:
+ words = reply_text.split(" ")
+ for i, word in enumerate(words):
+ chunk = word + (" " if i < len(words) - 1 else "")
+ yield (json.dumps({"delta": chunk, "done": False}) + "\n").encode()
+ # tiny delay to simulate streaming
+ import asyncio
+
+ await asyncio.sleep(0.01)
+
+ assistant_msg: dict[str, Any] = {
+ "id": msg_id,
+ "role": "assistant",
+ "content": reply_text,
+ "timestamp": datetime.now(UTC).isoformat(),
+ }
+ conv["messages"].append(assistant_msg)
+ conv["updatedAt"] = assistant_msg["timestamp"]
+
+ yield (
+ json.dumps(
+ {
+ "done": True,
+ "conversationId": conv_id,
+ "messageId": msg_id,
+ }
+ )
+ + "\n"
+ ).encode()
+
+ return StreamingResponse(_stream(), media_type="application/x-ndjson")
diff --git a/services/agents/app/api/hunt_search.py b/services/agents/app/api/hunt_search.py
new file mode 100644
index 000000000..327c1dde0
--- /dev/null
+++ b/services/agents/app/api/hunt_search.py
@@ -0,0 +1,185 @@
+"""
+Hunt search & saved-searches API.
+
+The console's threat-hunter view posts ad-hoc queries here and saves/retrieves
+search bookmarks. This is *distinct* from the hunt-corpus YAML runner
+(``hunts.py``); this module handles free-form telemetry search.
+
+Endpoints (under ``/api/v1/hunt``):
+
+ POST /search — execute a hunt query against telemetry
+ GET /saved — list saved searches for the current tenant
+ POST /saved — save a new search
+ DELETE /saved/{id} — delete a saved search
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime
+from typing import Any
+
+import structlog
+from fastapi import APIRouter, HTTPException
+from pydantic import BaseModel
+
+logger = structlog.get_logger()
+
+router = APIRouter(prefix="/api/v1/hunt", tags=["hunt-search"])
+
+
+# ---------------------------------------------------------------------------
+# Shapes
+# ---------------------------------------------------------------------------
+
+
+class HuntQuery(BaseModel):
+ query: str
+ language: str = "lucene" # lucene | eql | sigma | spl
+ timeRange: str | None = "24h"
+ indices: list[str] | None = None
+ limit: int = 100
+
+
+class HuntHit(BaseModel):
+ id: str
+ timestamp: str
+ source: str
+ event_type: str
+ raw: dict[str, Any]
+ highlights: list[str] | None = None
+
+
+class HuntResponse(BaseModel):
+ query: str
+ total: int
+ took_ms: int
+ hits: list[HuntHit]
+
+
+class SavedSearchCreate(BaseModel):
+ name: str
+ query: str
+ language: str = "lucene"
+
+
+class SavedSearch(BaseModel):
+ id: str
+ name: str
+ query: str
+ language: str
+ createdAt: str
+ pinned: bool = False
+
+
+# ---------------------------------------------------------------------------
+# In-memory store (demo; production would persist to Postgres)
+# ---------------------------------------------------------------------------
+
+_SAVED_SEARCHES: dict[str, SavedSearch] = {}
+
+
+def _synthetic_hits(query: str, limit: int) -> list[dict[str, Any]]:
+ """Return plausible-looking synthetic telemetry hits for demo mode."""
+ templates = [
+ {
+ "source": "crowdstrike",
+ "event_type": "ProcessCreation",
+ "raw": {
+ "process_name": "cmd.exe",
+ "parent_name": "explorer.exe",
+ "cmdline": f"cmd.exe /c {query}",
+ "user": "DOMAIN\\analyst",
+ "host": "WS-DEV-01",
+ },
+ },
+ {
+ "source": "azure_ad",
+ "event_type": "SignInLog",
+ "raw": {
+ "userPrincipalName": "[email protected]",
+ "ipAddress": "192.0.2.42",
+ "location": "US",
+ "appDisplayName": "Microsoft 365",
+ "resultType": "0",
+ },
+ },
+ {
+ "source": "aws_cloudtrail",
+ "event_type": "AssumeRole",
+ "raw": {
+ "eventName": "AssumeRole",
+ "sourceIPAddress": "10.0.0.100",
+ "userAgent": "aws-sdk-python",
+ "requestParameters": {"roleArn": "arn:aws:iam::123456789:role/Admin"},
+ },
+ },
+ ]
+ now = datetime.now(UTC)
+ hits = []
+ for i in range(min(limit, 5)):
+ t = templates[i % len(templates)]
+ hits.append(
+ {
+ "id": str(uuid.uuid4()),
+ "timestamp": now.isoformat(),
+ "source": t["source"],
+ "event_type": t["event_type"],
+ "raw": t["raw"],
+ "highlights": [query] if query else [],
+ }
+ )
+ return hits
+
+
+# ---------------------------------------------------------------------------
+# Endpoints
+# ---------------------------------------------------------------------------
+
+
[email protected]("/search", response_model=HuntResponse)
+async def hunt_search(query: HuntQuery) -> HuntResponse:
+ """Execute a hunt query and return matching telemetry events."""
+ import time
+
+ start = time.monotonic()
+
+ hits_raw = _synthetic_hits(query.query, query.limit)
+
+ took_ms = int((time.monotonic() - start) * 1000)
+ return HuntResponse(
+ query=query.query,
+ total=len(hits_raw),
+ took_ms=took_ms,
+ hits=[HuntHit(**h) for h in hits_raw],
+ )
+
+
+async def list_saved_searches() -> dict[str, list[dict[str, Any]]]:
+ """Return all saved searches."""
+ return {
+ "searches": [s.model_dump() for s in _SAVED_SEARCHES.values()]
+ }
+
+
[email protected]("/saved", response_model=SavedSearch, status_code=201)
+async def save_search(data: SavedSearchCreate) -> SavedSearch:
+ """Persist a new saved search."""
+ ss = SavedSearch(
+ id=str(uuid.uuid4()),
+ name=data.name,
+ query=data.query,
+ language=data.language,
+ createdAt=datetime.now(UTC).isoformat(),
+ )
+ _SAVED_SEARCHES[ss.id] = ss
+ return ss
+
+
[email protected]("/saved/{search_id}", status_code=204)
+async def delete_saved_search(search_id: str) -> None:
+ """Delete a saved search by ID."""
+ if search_id not in _SAVED_SEARCHES:
+ raise HTTPException(status_code=404, detail="saved search not found")
+ del _SAVED_SEARCHES[search_id]
diff --git a/services/agents/app/main.py b/services/agents/app/main.py
index f5cce37fe..269baabbe 100644
--- a/services/agents/app/main.py
+++ b/services/agents/app/main.py
@@ -7,6 +7,8 @@ from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.api.contextual import router as contextual_router
+from app.api.copilot import router as copilot_router
+from app.api.hunt_search import router as hunt_search_router
from app.api.hunts import router as hunts_router
from app.api.investigate import router as investigate_router
from app.api.playbooks import router as playbook_router
@@ -121,6 +123,8 @@ app.include_router(investigate_router) # prefix already set in investigate.py
app.include_router(playbook_router) # prefix: /api/v1/playbooks
app.include_router(contextual_router) # prefix: /api/v1/contextual
app.include_router(hunts_router) # prefix: /api/v1/hunts
+app.include_router(hunt_search_router) # prefix: /api/v1/hunt (search + saved)
+app.include_router(copilot_router) # prefix: /api/v1/copilot
@app.get("/health")
diff --git a/services/api/app/api/v1/endpoints/metrics.py b/services/api/app/api/v1/endpoints/metrics.py
new file mode 100644
index 000000000..3cac02914
--- /dev/null
+++ b/services/api/app/api/v1/endpoints/metrics.py
@@ -0,0 +1,293 @@
+"""Dashboard metrics endpoint — aggregated counts for the frontend KPI tiles."""
+
+from datetime import UTC, datetime, timedelta
+
+from fastapi import APIRouter
+from pydantic import BaseModel
+from sqlalchemy import and_, func, select
+
+from app.api.v1.deps import AuthUser, DBSession
+from app.models.alert import Alert
+from app.models.case import Case
+from app.models.connector import Connector
+
+router = APIRouter(prefix="/metrics", tags=["metrics"])
+
+
+class AlertMetrics(BaseModel):
+ total: int
+ new: int
+ critical: int
+ high: int
+ medium: int
+ low: int
+ resolvedToday: int
+ mttr: float
+
+
+class CaseMetrics(BaseModel):
+ open: int
+ inProgress: int
+ resolvedThisWeek: int
+
+
+class SourceStat(BaseModel):
+ name: str
+ count: int
+ status: str
+
+
+class MitreTactic(BaseModel):
+ tactic: str
+ count: int
+
+
+class TrendPoint(BaseModel):
+ timestamp: str
+ count: int
+ severity: str
+
+
+class SourceThreat(BaseModel):
+ source: str
+ count: int
+
+
+class DashboardMetrics(BaseModel):
+ alerts: AlertMetrics
+ cases: CaseMetrics
+ sources: list[SourceStat]
+ topMitre: list[MitreTactic]
+ alertsTrend: list[TrendPoint]
+ threatsBySource: list[SourceThreat]
+
+
[email protected]("/dashboard", response_model=DashboardMetrics)
+async def get_dashboard_metrics(
+ user: AuthUser,
+ db: DBSession,
+) -> DashboardMetrics:
+ """Return aggregated KPI metrics for the dashboard overview tiles."""
+ tenant_id = user.tenant_id
+ now = datetime.now(UTC)
+ today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
+ week_start = now - timedelta(days=7)
+
+ # ── Alert counts ──────────────────────────────────────────────────────────
+ total_q = await db.scalar(
+ select(func.count()).where(Alert.tenant_id == tenant_id)
+ )
+ new_q = await db.scalar(
+ select(func.count()).where(
+ and_(Alert.tenant_id == tenant_id, Alert.status == "new")
+ )
+ )
+ critical_q = await db.scalar(
+ select(func.count()).where(
+ and_(Alert.tenant_id == tenant_id, Alert.severity == "critical")
+ )
+ )
+ high_q = await db.scalar(
+ select(func.count()).where(
+ and_(Alert.tenant_id == tenant_id, Alert.severity == "high")
+ )
+ )
+ medium_q = await db.scalar(
+ select(func.count()).where(
+ and_(Alert.tenant_id == tenant_id, Alert.severity == "medium")
+ )
+ )
+ low_q = await db.scalar(
+ select(func.count()).where(
+ and_(Alert.tenant_id == tenant_id, Alert.severity == "low")
+ )
+ )
+ resolved_today_q = await db.scalar(
+ select(func.count()).where(
+ and_(
+ Alert.tenant_id == tenant_id,
+ Alert.status == "resolved",
+ Alert.updated_at >= today_start,
+ )
+ )
+ )
+
+ alert_metrics = AlertMetrics(
+ total=total_q or 0,
+ new=new_q or 0,
+ critical=critical_q or 0,
+ high=high_q or 0,
+ medium=medium_q or 0,
+ low=low_q or 0,
+ resolvedToday=resolved_today_q or 0,
+ mttr=0.0,
+ )
+
+ # ── Case counts ───────────────────────────────────────────────────────────
+ open_cases_q = await db.scalar(
+ select(func.count()).where(
+ and_(Case.tenant_id == tenant_id, Case.status == "open")
+ )
+ )
+ in_progress_q = await db.scalar(
+ select(func.count()).where(
+ and_(Case.tenant_id == tenant_id, Case.status == "in_progress")
+ )
+ )
+ resolved_week_q = await db.scalar(
+ select(func.count()).where(
+ and_(
+ Case.tenant_id == tenant_id,
+ Case.status == "resolved",
+ Case.updated_at >= week_start,
+ )
+ )
+ )
+
+ case_metrics = CaseMetrics(
+ open=open_cases_q or 0,
+ inProgress=in_progress_q or 0,
+ resolvedThisWeek=resolved_week_q or 0,
+ )
+
+ # ── Sources (connectors) ──────────────────────────────────────────────────
+ connectors_rows = (
+ await db.execute(
+ select(Connector.name, Connector.connector_type, Connector.health_status).where(
+ Connector.tenant_id == tenant_id
+ )
+ )
+ ).all()
+
+ # Count alerts per connector_type
+ source_counts_rows = (
+ await db.execute(
+ select(Alert.connector_type, func.count().label("cnt"))
+ .where(Alert.tenant_id == tenant_id)
+ .group_by(Alert.connector_type)
+ )
+ ).all()
+ source_count_map: dict[str, int] = {
+ row.connector_type: row.cnt
+ for row in source_counts_rows
+ if row.connector_type
+ }
+
+ sources: list[SourceStat] = []
+ seen: set[str] = set()
+ for row in connectors_rows:
+ key = row.connector_type or row.name
+ if key in seen:
+ continue
+ seen.add(key)
+ sources.append(
+ SourceStat(
+ name=row.name,
+ count=source_count_map.get(row.connector_type or "", 0),
+ status=row.health_status or "active",
+ )
+ )
+
+ # ── Top MITRE tactics ─────────────────────────────────────────────────────
+ mitre_rows = (
+ await db.execute(
+ select(
+ func.jsonb_array_elements_text(Alert.mitre_tactics).label("tactic"),
+ func.count().label("cnt"),
+ )
+ .where(Alert.tenant_id == tenant_id)
+ .group_by("tactic")
+ .order_by(func.count().desc())
+ .limit(10)
+ )
+ ).all()
+
+ top_mitre = [MitreTactic(tactic=r.tactic, count=r.cnt) for r in mitre_rows]
+
+ # ── 24-hour trend (hourly buckets) ────────────────────────────────────────
+ trend_start = now - timedelta(hours=24)
+ trend_rows = (
+ await db.execute(
+ select(
+ func.date_trunc("hour", Alert.created_at).label("bucket"),
+ Alert.severity,
+ func.count().label("cnt"),
+ )
+ .where(
+ and_(
+ Alert.tenant_id == tenant_id,
+ Alert.created_at >= trend_start,
+ )
+ )
+ .group_by("bucket", Alert.severity)
+ .order_by("bucket")
+ )
+ ).all()
+
+ alerts_trend = [
+ TrendPoint(
+ timestamp=r.bucket.isoformat() if r.bucket else now.isoformat(),
+ count=r.cnt,
+ severity=r.severity,
+ )
+ for r in trend_rows
+ ]
+
+ # ── Threats by source ─────────────────────────────────────────────────────
+ threats_by_source = [
+ SourceThreat(source=k, count=v) for k, v in source_count_map.items()
+ ]
+
+ return DashboardMetrics(
+ alerts=alert_metrics,
+ cases=case_metrics,
+ sources=sources,
+ topMitre=top_mitre,
+ alertsTrend=alerts_trend,
+ threatsBySource=threats_by_source,
+ )
+
+
[email protected]("/alerts/trend")
+async def get_alert_trend(
+ user: AuthUser,
+ db: DBSession,
+ period: str = "24h",
+) -> dict:
+ """Return alert count trend data bucketed by time period."""
+ now = datetime.now(UTC)
+ period_map = {
+ "1h": (timedelta(hours=1), "minute"),
+ "24h": (timedelta(hours=24), "hour"),
+ "7d": (timedelta(days=7), "day"),
+ "30d": (timedelta(days=30), "day"),
+ }
+ delta, trunc = period_map.get(period, (timedelta(hours=24), "hour"))
+ start = now - delta
+
+ rows = (
+ await db.execute(
+ select(
+ func.date_trunc(trunc, Alert.created_at).label("bucket"),
+ func.count().label("cnt"),
+ )
+ .where(
+ and_(
+ Alert.tenant_id == user.tenant_id,
+ Alert.created_at >= start,
+ )
+ )
+ .group_by("bucket")
+ .order_by("bucket")
+ )
+ ).all()
+
+ return {
+ "data": [
+ {
+ "timestamp": r.bucket.isoformat() if r.bucket else now.isoformat(),
+ "count": r.cnt,
+ }
+ for r in rows
+ ]
+ }
diff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.py
index a9ee4951a..03a360043 100644
--- a/services/api/app/api/v1/router.py
+++ b/services/api/app/api/v1/router.py
@@ -21,6 +21,7 @@ from app.api.v1.endpoints import (
insider_threat,
investigations,
marketplace,
+ metrics,
mssp,
oncall,
passkeys,
@@ -55,6 +56,7 @@ api_router.include_router(marketplace.router)
api_router.include_router(rbac.router)
api_router.include_router(audit.router)
api_router.include_router(compliance.router)
+api_router.include_router(metrics.router)
api_router.include_router(sla.router)
api_router.include_router(investigations.router)