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(honesty): stop presenting generated content as real findings (#662)

Beenu Arora65a49e1d9124
diff --git a/apps/web/src/components/alerts/AlertDetailView.tsx b/apps/web/src/components/alerts/AlertDetailView.tsx
index 0c20df720..dacb598c1 100644
--- a/apps/web/src/components/alerts/AlertDetailView.tsx
+++ b/apps/web/src/components/alerts/AlertDetailView.tsx
@@ -1,16 +1,16 @@
'use client';
import { useState } from 'react';
+import { useRouter } from 'next/navigation';
import useSWR from 'swr';
import Link from 'next/link';
import toast from 'react-hot-toast';
import {
alertsApi,
- agentsApi,
+ casesApi,
ledgerApi,
feedbackApi,
type Alert,
- type AgentInvestigation,
type ConfidenceFactor,
type ConfidenceLabel,
type AnalystVerdict,
@@ -342,144 +342,74 @@ function LedgerEvidenceChain({ runId }: { runId: string }) {
// ─── AI Investigation Panel ───────────────────────────────────────────────────
-function AIInvestigation({ alertId }: { alertId: string }) {
- const [investigation, setInvestigation] = useState<AgentInvestigation | null>(null);
+function AIInvestigation({ alertId, alertTitle }: { alertId: string; alertTitle?: string }) {
+ const router = useRouter();
const [isRunning, setIsRunning] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ // Investigations are owned by a case, not by a bare alert: the agent writes
+ // its prompts, tool calls and rationale into that case's ledger, and the case
+ // workspace is where they are rendered and replayed. So promote the alert to
+ // a case, launch the real run, and hand the analyst to the surface that can
+ // actually show it.
+ //
+ // This previously called `POST /api/v1/agents/investigate`, a route that
+ // exists on no backend. The 404 was caught and the catch block rendered a
+ // hardcoded "Advanced Persistent Threat - High Confidence" verdict naming a
+ // specific IP, a specific C2 domain and three pending response actions, with
+ // status 'completed' and no disclaimer. A security product must never invent
+ // a finding about a customer's environment.
const startInvestigation = async () => {
setIsRunning(true);
+ setError(null);
try {
- const result = await agentsApi.investigate(alertId);
- setInvestigation(result);
- } catch (err) {
- // Show mock investigation for demo
- setInvestigation({
- id: 'inv-1',
- alertId,
- status: 'completed',
- findings: `## AI Investigation Summary
-
-**Threat Classification:** Advanced Persistent Threat (APT) - High Confidence
-
-### Executive Summary
-The PowerShell execution event represents a multi-stage attack with C2 communication. The attacker leveraged legitimate administrative credentials obtained via credential stuffing to execute an obfuscated downloader script.
-
-### Key Findings
-1. **Initial Access**: Credential abuse from IP 185.220.101.45 (known Tor exit node)
-2. **Execution**: Obfuscated PowerShell base64 encoded payload downloading secondary stage
-3. **C2 Communication**: Established encrypted channel to payload-c2.xyz (newly registered domain, 3 days old)
-4. **Lateral Movement Risk**: Current user has admin rights on 12 additional systems
-
-### MITRE ATT&CK Coverage
-- T1059.001 (PowerShell) → Active
-- T1027 (Obfuscation) → Active
-- T1071 (Application Layer Protocol) → Active
-
-### Recommended Actions
-1. Isolate affected endpoint immediately
-2. Block IP 185.220.101.45 at perimeter firewall
-3. Block domain payload-c2.xyz at DNS level
-4. Reset credentials for affected user account
-5. Hunt for similar PowerShell patterns across fleet`,
- recommendations: [
- 'Isolate endpoint DESKTOP-ABC123 from network immediately',
- 'Block IP 185.220.101.45 at firewall',
- 'Block domain payload-c2.xyz at DNS',
- 'Reset password for user [email protected]',
- 'Review admin rights across all systems',
- ],
- actions: [
- { type: 'isolate_endpoint', target: 'DESKTOP-ABC123', status: 'pending' },
- { type: 'block_ip', target: '185.220.101.45', status: 'pending' },
- { type: 'block_domain', target: 'payload-c2.xyz', status: 'pending' },
- ],
- startedAt: new Date().toISOString(),
- completedAt: new Date().toISOString(),
+ const summary = alertTitle ? `Investigate alert: ${alertTitle}` : 'Investigate alert';
+ const createdCase = await casesApi.create({
+ title: alertTitle ? `Investigation — ${alertTitle}` : `Investigation — alert ${alertId}`,
+ description: summary,
+ alertIds: [alertId],
});
+ await casesApi.investigate(createdCase.id, summary);
+ router.push(`/cases/${createdCase.id}?tab=ledger`);
+ } catch (err) {
+ setError(
+ err instanceof Error
+ ? err.message
+ : 'Could not start the investigation. Check that the agents service is reachable.',
+ );
+ setIsRunning(false);
}
- setIsRunning(false);
};
- if (!investigation) {
- return (
- <div className="text-center py-8">
- <p className="text-sm text-gray-400 mb-1">Agent investigation</p>
- <p className="text-xs text-gray-600 mb-4">Run the agent on this alert to produce a markdown report, MITRE mapping, and a list of recommended actions. Every step is recorded in the case ledger.</p>
- <button
- onClick={startInvestigation}
- disabled={isRunning}
- className="bg-blue-600 hover:bg-blue-500 text-white text-sm font-medium px-6 py-2 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
- >
- {isRunning ? (
- <span className="flex items-center gap-2">
- <span className="w-3 h-3 border-2 border-white/30 border-t-white rounded-full animate-spin" />
- Investigating...
- </span>
- ) : (
- 'Start AI Investigation'
- )}
- </button>
- </div>
- );
- }
-
return (
- <div className="space-y-4">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <span className={clsx(
- 'w-2 h-2 rounded-full',
- investigation.status === 'completed' ? 'bg-green-500' :
- investigation.status === 'running' ? 'bg-blue-500 animate-pulse' :
- 'bg-red-500'
- )} />
- <span className="text-xs text-gray-400 capitalize">{investigation.status}</span>
- </div>
- <button
- onClick={startInvestigation}
- className="text-xs text-blue-400 hover:text-blue-300"
- >
- Re-investigate
- </button>
- </div>
-
- {/* Findings */}
- {investigation.findings && (
- <div className="bg-gray-950/60 rounded-lg p-4 text-xs text-gray-300 font-mono leading-relaxed whitespace-pre-wrap max-h-64 overflow-y-auto">
- {investigation.findings}
+ <div className="py-6">
+ <p className="text-sm text-gray-400 mb-1">Agent investigation</p>
+ <p className="text-xs text-gray-600 mb-4">
+ Promotes this alert to a case and runs the agent against it. Every prompt, tool call and
+ piece of cited evidence is written to that case&apos;s ledger, where the run can be replayed
+ step by step. You&apos;ll be taken to the case when it starts.
+ </p>
+
+ {error && (
+ <div className="mb-4 rounded-lg border border-red-900/60 bg-red-950/40 px-3 py-2 text-xs text-red-300">
+ {error}
</div>
)}
- {/* Recommendations */}
- {investigation.recommendations && investigation.recommendations.length > 0 && (
- <div className="space-y-2">
- <p className="text-xs font-medium text-gray-400">Recommended Actions</p>
- {investigation.recommendations.map((rec, i) => (
- <div key={i} className="flex items-start gap-2 text-xs text-gray-300">
- <span className="text-blue-400 shrink-0 mt-0.5">→</span>
- {rec}
- </div>
- ))}
- </div>
- )}
-
- {/* Actions */}
- {investigation.actions && investigation.actions.length > 0 && (
- <div className="space-y-2">
- <p className="text-xs font-medium text-gray-400">Automated Actions Available</p>
- {investigation.actions.map((action, i) => (
- <div key={i} className="flex items-center justify-between bg-gray-800/60 rounded-lg px-3 py-2">
- <div className="flex items-center gap-2">
- <span className="text-xs text-blue-400 font-mono">{action.type}</span>
- <span className="text-xs text-gray-500">→</span>
- <span className="text-xs text-gray-300 font-mono">{action.target}</span>
- </div>
- <button className="text-xs bg-blue-600/20 text-blue-400 hover:bg-blue-600/40 px-2 py-1 rounded transition-colors">
- Execute
- </button>
- </div>
- ))}
- </div>
- )}
+ <button
+ onClick={startInvestigation}
+ disabled={isRunning}
+ className="bg-blue-600 hover:bg-blue-500 text-white text-sm font-medium px-6 py-2 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {isRunning ? (
+ <span className="flex items-center gap-2">
+ <span className="w-3 h-3 border-2 border-white/30 border-t-white rounded-full animate-spin" />
+ Starting investigation...
+ </span>
+ ) : (
+ 'Start AI investigation'
+ )}
+ </button>
</div>
);
}
@@ -1055,7 +985,7 @@ export function AlertDetailView({ alertId }: { alertId: string }) {
{/* Right column - 1/3 */}
<div className="space-y-4">
<Section title="AI Investigation">
- <AIInvestigation alertId={alertId} />
+ <AIInvestigation alertId={alertId} alertTitle={alert?.title} />
</Section>
<Section title="Verdict & feedback">
diff --git a/apps/web/src/components/copilot/CopilotView.tsx b/apps/web/src/components/copilot/CopilotView.tsx
index 101781e58..7ebf63827 100644
--- a/apps/web/src/components/copilot/CopilotView.tsx
+++ b/apps/web/src/components/copilot/CopilotView.tsx
@@ -382,7 +382,29 @@ export function CopilotView() {
context: { page: 'copilot' },
});
setConversationId(res.conversationId);
- setMessages((prev) => [...prev, res.reply]);
+ // A 200 does not mean a model answered. When no LLM key is configured,
+ // or the call fails, the backend falls back to a canned paragraph and
+ // now says so with `source: "template"`. Without this the analyst reads
+ // generic claims — "this IP was seen in 3 other alerts" — as real
+ // analysis of their own environment, and the honest fallback below never
+ // fires because the request technically succeeded.
+ const source = (res as { source?: string }).source;
+ const notice = (res as { notice?: string }).notice;
+ const reply =
+ source === 'template'
+ ? {
+ ...res.reply,
+ content: [
+ notice ??
+ 'This reply came from a built-in template, not a language model, and is not analysis of your environment.',
+ '',
+ '---',
+ '',
+ res.reply.content,
+ ].join('\n'),
+ }
+ : res.reply;
+ setMessages((prev) => [...prev, reply]);
} catch (err) {
// Backend not reachable / not implemented yet — fall back to a demo
// reply so the dock still feels alive in local dev.
diff --git a/apps/web/src/components/hunt/HuntView.tsx b/apps/web/src/components/hunt/HuntView.tsx
index 761cb39b8..dee1508f0 100644
--- a/apps/web/src/components/hunt/HuntView.tsx
+++ b/apps/web/src/components/hunt/HuntView.tsx
@@ -636,6 +636,9 @@ export function HuntView() {
const [activeSavedHuntId, setActiveSavedHuntId] = useState<string | null>(null);
const editorRef = useRef<unknown>(null);
const [demoMode, setDemoMode] = useState(false);
+ // Reason the results are not live, surfaced verbatim from the backend so
+ // the console never has to guess why it is showing sample data.
+ const [sampleNotice, setSampleNotice] = useState<string | null>(null);
// Natural-language hero state.
const [nlInput, setNlInput] = useState('');
@@ -659,6 +662,7 @@ export function HuntView() {
} catch (err) {
// First-load fallback to demo so the UI is never empty.
setDemoMode(true);
+ setSampleNotice('Saved searches could not be loaded from the backend.');
throw err;
}
},
@@ -769,7 +773,15 @@ export function HuntView() {
limit: 200,
});
setResults(res);
- setDemoMode(false);
+ // A 200 is not the same as real data. The search endpoint currently
+ // generates illustrative events rather than querying the lake, and says
+ // so with `source: "sample"` — trusting the status code alone is how a
+ // green "Live backend" pill ended up sitting over fabricated telemetry.
+ setDemoMode(
+ (res as { source?: string }).source === 'sample' ||
+ Boolean((res as { notice?: string }).notice),
+ );
+ setSampleNotice((res as { notice?: string }).notice ?? null);
} catch (err) {
// Demo fallback so the page still feels alive without a seeded backend.
setResults({
@@ -778,8 +790,11 @@ export function HuntView() {
hits: DEMO_RESULTS,
});
setDemoMode(true);
+ setSampleNotice(
+ 'The hunt backend is unreachable, so these are illustrative sample events rather than results from your telemetry.',
+ );
setRunError(err);
- toast('Backend unreachable — showing demo results');
+ toast('Backend unreachable — showing sample results');
} finally {
setRunning(false);
}
@@ -950,8 +965,11 @@ export function HuntView() {
demoMode ? 'bg-amber-400' : 'bg-emerald-400 animate-ping-slow',
)}
/>
- {demoMode ? 'Demo data' : 'Live backend'}
+ {demoMode ? 'Sample data' : 'Live backend'}
</span>
+ {demoMode && sampleNotice && (
+ <p className="mt-1 text-[11px] leading-snug text-amber-300/80">{sampleNotice}</p>
+ )}
</div>
</div>
)}
diff --git a/services/agents/app/api/copilot.py b/services/agents/app/api/copilot.py
index 0a13a46d2..53207c32d 100644
--- a/services/agents/app/api/copilot.py
+++ b/services/agents/app/api/copilot.py
@@ -20,7 +20,7 @@ import os
import uuid
from collections.abc import AsyncIterator
from datetime import UTC, datetime
-from typing import Any
+from typing import Any, Literal
import structlog
from fastapi import APIRouter
@@ -53,6 +53,12 @@ class CopilotChatRequest(BaseModel):
class CopilotChatResponse(BaseModel):
conversationId: str
reply: CopilotMessage
+ #: ``llm`` when a model produced the reply, ``template`` when this service
+ #: fell back to a canned paragraph (no API key, or the call failed).
+ #: The console must label a ``template`` reply rather than presenting it as
+ #: analysis of the user's environment.
+ source: Literal["llm", "template"] = "llm"
+ notice: str | None = None
class CopilotConversation(BaseModel):
@@ -115,10 +121,18 @@ def _title_from_message(msg: str) -> str:
async def _get_openai_reply(
conversation: dict[str, Any],
user_message: str,
-) -> str:
+) -> tuple[str, str]:
+ """Return ``(reply_text, source)`` where source is ``llm`` or ``template``.
+
+ The caller must surface ``template`` to the user. This function silently
+ returned a canned paragraph as a normal 200 whenever the key was missing or
+ any exception fired, so an analyst read "this IP was seen in 3 other
+ alerts" as real analysis of their environment. The frontend had an honest
+ fallback of its own that never fired, because the backend reported success.
+ """
api_key = os.getenv("OPENAI_API_KEY", "")
if not api_key:
- return _synthetic_reply(user_message)
+ return _synthetic_reply(user_message), "template"
try:
from app.llm.contract import safe_chat_completions_request
@@ -146,10 +160,10 @@ async def _get_openai_reply(
url=chat_completions_url(),
max_tokens=512,
)
- return body["choices"][0]["message"]["content"]
+ return body["choices"][0]["message"]["content"], "llm"
except Exception as exc:
logger.warning("copilot.openai_error", error=str(exc))
- return _synthetic_reply(user_message)
+ return _synthetic_reply(user_message), "template"
# ---------------------------------------------------------------------------
@@ -212,7 +226,7 @@ async def chat(req: CopilotChatRequest) -> CopilotChatResponse:
}
conv["messages"].append(user_msg)
- reply_text = await _get_openai_reply(conv, req.message)
+ reply_text, reply_source = await _get_openai_reply(conv, req.message)
assistant_msg: dict[str, Any] = {
"id": str(uuid.uuid4()),
@@ -226,6 +240,14 @@ async def chat(req: CopilotChatRequest) -> CopilotChatResponse:
return CopilotChatResponse(
conversationId=conv_id,
reply=CopilotMessage(**assistant_msg),
+ source=reply_source,
+ notice=(
+ "This reply came from a built-in template, not a language model. "
+ "It is generic guidance and is not analysis of your environment. "
+ "Configure an LLM key to get a real investigation."
+ if reply_source == "template"
+ else None
+ ),
)
@@ -253,10 +275,13 @@ async def chat_stream(req: CopilotChatRequest) -> StreamingResponse:
}
conv["messages"].append(user_msg)
- reply_text = await _get_openai_reply(conv, req.message)
+ reply_text, reply_source = await _get_openai_reply(conv, req.message)
msg_id = str(uuid.uuid4())
async def _stream() -> AsyncIterator[bytes]:
+ # Provenance first: a consumer must be able to label the answer before
+ # it starts rendering tokens, not after.
+ yield (json.dumps({"source": reply_source, "delta": "", "done": False}) + "\n").encode()
words = reply_text.split(" ")
for i, word in enumerate(words):
chunk = word + (" " if i < len(words) - 1 else "")
diff --git a/services/agents/app/api/hunt_search.py b/services/agents/app/api/hunt_search.py
index 350120e2b..2380bbf75 100644
--- a/services/agents/app/api/hunt_search.py
+++ b/services/agents/app/api/hunt_search.py
@@ -17,7 +17,7 @@ from __future__ import annotations
import uuid
from datetime import UTC, datetime
-from typing import Any
+from typing import Any, Literal
import structlog
from fastapi import APIRouter, HTTPException
@@ -55,6 +55,18 @@ class HuntResponse(BaseModel):
total: int
took_ms: int
hits: list[HuntHit]
+ #: Where the hits came from. ``sample`` means this handler generated
+ #: illustrative telemetry rather than querying anything.
+ #:
+ #: This field exists because the endpoint returns synthetic hits
+ #: unconditionally and used to say nothing about it. A 200 with no marker
+ #: read to the console as a successful live query, so the hunt workbench
+ #: rendered a green "Live backend" pill over fabricated CrowdStrike process
+ #: events. A caller must be able to tell the difference without reading
+ #: this file.
+ source: Literal["sample", "live"] = "sample"
+ #: Human-readable reason, surfaced in the UI banner.
+ notice: str | None = None
class SavedSearchCreate(BaseModel):
@@ -152,6 +164,12 @@ async def hunt_search(query: HuntQuery) -> HuntResponse:
total=len(hits_raw),
took_ms=took_ms,
hits=[HuntHit(**h) for h in hits_raw],
+ source="sample",
+ notice=(
+ "These are illustrative sample events, not results from your telemetry. "
+ "This endpoint does not yet execute the query against the event lake; "
+ "run the hunt from /hunt against a configured data source for real hits."
+ ),
)
diff --git a/services/agents/tests/test_response_provenance.py b/services/agents/tests/test_response_provenance.py
new file mode 100644
index 000000000..25303a365
--- /dev/null
+++ b/services/agents/tests/test_response_provenance.py
@@ -0,0 +1,71 @@
+"""Synthetic output must never be indistinguishable from real output.
+
+Two endpoints returned generated content as an ordinary 200 with nothing on the
+wire to mark it:
+
+ * ``POST /api/v1/hunt/search`` always returns ``_synthetic_hits`` — it does
+ not query the lake at all — and the console read the 200 as success and
+ rendered a green "Live backend" pill over fabricated CrowdStrike events.
+ * ``POST /api/v1/copilot/chat`` falls back to a canned paragraph whenever
+ ``OPENAI_API_KEY`` is unset or the call raises, so an analyst read generic
+ claims as analysis of their own environment.
+
+These tests pin the provenance fields that let a caller tell the difference.
+They are deliberately about the contract, not the prose: the fixtures may
+change, but a consumer must always be able to ask "did a model produce this?"
+and "is this my data?" and get a truthful answer.
+"""
+
+from __future__ import annotations
+
+import pytest
+from app.api import copilot as copilot_mod
+from app.api import hunt_search as hunt_mod
+
+
+class TestHuntSearchProvenance:
+ @pytest.mark.asyncio
+ async def test_search_declares_itself_as_sample(self):
+ res = await hunt_mod.hunt_search(hunt_mod.HuntQuery(query="process_name:powershell"))
+ assert res.source == "sample", (
+ "the search handler generates events rather than querying telemetry; " "it must not present them as live"
+ )
+ assert res.notice, "a sample response must carry a human-readable reason"
+ assert "not results from your telemetry" in res.notice
+
+ @pytest.mark.asyncio
+ async def test_hits_are_still_returned(self):
+ """Labelling the data must not empty the workbench."""
+ res = await hunt_mod.hunt_search(hunt_mod.HuntQuery(query="anything", limit=5))
+ assert res.hits, "sample mode should still populate the UI"
+ assert res.total == len(res.hits)
+
+
+class TestCopilotProvenance:
+ @pytest.mark.asyncio
+ async def test_no_api_key_is_reported_as_template(self, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)
+ text, source = await copilot_mod._get_openai_reply({"messages": []}, "what happened?")
+ assert source == "template"
+ assert text, "the fallback should still say something useful"
+
+ @pytest.mark.asyncio
+ async def test_llm_failure_is_reported_as_template(self, monkeypatch: pytest.MonkeyPatch):
+ """A provider error must degrade visibly, not silently."""
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-test-not-a-real-key")
+
+ async def _boom(*args, **kwargs):
+ raise RuntimeError("provider unreachable")
+
+ monkeypatch.setattr("app.llm.contract.safe_chat_completions_request", _boom, raising=False)
+ _text, source = await copilot_mod._get_openai_reply({"messages": []}, "hello")
+ assert source == "template"
+
+ def test_response_model_defaults_to_llm_but_can_carry_template(self):
+ """The field must exist on the wire, not just in the handler."""
+ fields = copilot_mod.CopilotChatResponse.model_fields
+ assert "source" in fields
+ assert "notice" in fields
+ msg = copilot_mod.CopilotMessage(id="m1", role="assistant", content="hi", timestamp="2026-01-01T00:00:00Z")
+ templated = copilot_mod.CopilotChatResponse(conversationId="c1", reply=msg, source="template", notice="canned")
+ assert templated.source == "template"