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.

feat(web): AI estate console page, and close two blind spots in the 6.1 gate

Beenu Arora9c1836f2d7b5
diff --git a/apps/web/src/app/(app)/ai-estate/page.tsx b/apps/web/src/app/(app)/ai-estate/page.tsx
new file mode 100644
index 000000000..fd5688f53
--- /dev/null
+++ b/apps/web/src/app/(app)/ai-estate/page.tsx
@@ -0,0 +1,10 @@
+import AiEstateView from "@/components/ai-estate/AiEstateView";
+
+export const metadata = {
+ title: "AI estate",
+ description: "Observed AI apps, coding agents, MCP servers, provider keys and OAuth grants",
+};
+
+export default function AiEstatePage() {
+ return <AiEstateView />;
+}
diff --git a/apps/web/src/components/ai-estate/AiEstateView.tsx b/apps/web/src/components/ai-estate/AiEstateView.tsx
new file mode 100644
index 000000000..8c6fe15a2
--- /dev/null
+++ b/apps/web/src/components/ai-estate/AiEstateView.tsx
@@ -0,0 +1,280 @@
+"use client";
+
+/**
+ * The observed AI estate (depth plan 6.1).
+ *
+ * Every AI app, coding agent, MCP server, IDE extension, provider key and
+ * OAuth grant AiSOC has seen, with the person and device behind it.
+ *
+ * Three rendering decisions that are the whole point of the page:
+ *
+ * 1. An unlinked person or device renders as "not learned", in the colour of
+ * a finding, never as a blank cell. The API sends `null` when a source did
+ * not say, and the difference between "no person" and "we did not learn
+ * one" is the thing an operator acts on.
+ * 2. A failed read says so. It never renders as an empty estate, because "you
+ * have no shadow AI" is the single most dangerous false statement this
+ * page could make.
+ * 3. Nothing is fabricated. No sample rows, no `?? MOCK`, no SWR
+ * `fallbackData` — an invented AI inventory is a security surface a
+ * reader would act on.
+ */
+
+import { useState } from "react";
+import useSWR, { mutate } from "swr";
+import { apiHeaders } from "@/lib/api";
+
+const KINDS = [
+ { value: "", label: "All kinds" },
+ { value: "coding_agent", label: "Coding agents" },
+ { value: "ai_app", label: "AI apps" },
+ { value: "mcp_server", label: "MCP servers" },
+ { value: "ide_extension", label: "IDE extensions" },
+ { value: "provider_key", label: "Provider keys" },
+ { value: "oauth_grant", label: "OAuth grants" },
+] as const;
+
+const SOURCE_LIMITS: Record<string, string> = {
+ ai_runtime: "SDK and gateway telemetry: knows the agent, the model and the tools. Never the device.",
+ endpoint: "EDR and osquery process telemetry: knows the device and the binary. Never the model.",
+ provider_audit: "Provider audit log: knows the account and the key. Never a device.",
+ oauth_audit: "Directory consent events: knows the application and its scopes. Never a device.",
+ declared: "Registered by an operator rather than observed.",
+};
+
+interface AiAsset {
+ id: string;
+ kind: string;
+ externalId: string;
+ displayName: string | null;
+ vendor: string | null;
+ discoverySource: string;
+ principal: string | null;
+ device: string | null;
+ effectivePermissions: Record<string, unknown> | null;
+ attributes: Record<string, unknown>;
+ risk: number;
+ riskReasons: string[];
+ sanctioned: boolean | null;
+ firstSeen: string;
+ lastSeen: string;
+ observationCount: number;
+}
+
+interface AiAssetList {
+ items: AiAsset[];
+ total: number;
+ observedSources: string[];
+}
+
+const fetcher = (url: string) =>
+ fetch(url, { headers: apiHeaders() }).then((r) => {
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ return r.json();
+ });
+
+function riskTone(risk: number): string {
+ if (risk >= 70) return "text-red-400";
+ if (risk >= 40) return "text-yellow-400";
+ return "text-gray-300";
+}
+
+/** A link we have, or an explicit statement that we do not. Never a blank. */
+function Link({ value, missing }: { value: string | null; missing: string }) {
+ if (value) return <span className="text-gray-300">{value}</span>;
+ return (
+ <span className="text-amber-400" title={missing}>
+ not learned
+ </span>
+ );
+}
+
+function SanctionBadge({ sanctioned }: { sanctioned: boolean | null }) {
+ if (sanctioned === true) {
+ return <span className="inline-flex px-2 py-0.5 rounded text-xs bg-green-900/40 text-green-300">approved</span>;
+ }
+ if (sanctioned === false) {
+ return <span className="inline-flex px-2 py-0.5 rounded text-xs bg-red-900/40 text-red-300">refused</span>;
+ }
+ return <span className="inline-flex px-2 py-0.5 rounded text-xs bg-gray-800 text-gray-400">undecided</span>;
+}
+
+export default function AiEstateView() {
+ const [kind, setKind] = useState<string>("");
+ const [unlinkedOnly, setUnlinkedOnly] = useState(false);
+ const [expanded, setExpanded] = useState<string | null>(null);
+
+ const query = new URLSearchParams();
+ if (kind) query.set("kind", kind);
+ if (unlinkedOnly) query.set("unlinked", "true");
+ const key = `/api/v1/ai-assets${query.toString() ? `?${query}` : ""}`;
+
+ const { data, error, isLoading } = useSWR<AiAssetList>(key, fetcher, { refreshInterval: 30_000 });
+
+ const sanction = async (id: string, value: boolean | null) => {
+ await fetch(`/api/v1/ai-assets/${id}/sanction`, {
+ method: "POST",
+ headers: apiHeaders(),
+ body: JSON.stringify({ sanctioned: value }),
+ });
+ void mutate(key);
+ };
+
+ return (
+ <div className="p-6 max-w-7xl mx-auto">
+ <div className="mb-6">
+ <h1 className="text-2xl font-bold text-gray-100">AI estate</h1>
+ <p className="text-sm text-gray-500 mt-1">
+ What AiSOC has observed running, not what was registered. The interesting row is the one nobody
+ declared.
+ </p>
+ </div>
+
+ <div className="flex flex-wrap gap-3 mb-4 items-center">
+ <select
+ className="border border-gray-600 bg-gray-800 text-gray-200 rounded-md px-3 py-1.5 text-sm outline-none focus:ring-2 focus:ring-blue-500"
+ value={kind}
+ onChange={(e) => setKind(e.target.value)}
+ >
+ {KINDS.map((k) => (
+ <option key={k.value} value={k.value}>
+ {k.label}
+ </option>
+ ))}
+ </select>
+ <label className="flex items-center gap-2 text-sm text-gray-400">
+ <input type="checkbox" checked={unlinkedOnly} onChange={(e) => setUnlinkedOnly(e.target.checked)} />
+ Only assets with nobody accountable
+ </label>
+ {data?.total != null && <span className="text-xs text-gray-500">{data.total} observed</span>}
+ </div>
+
+ {data?.observedSources?.length ? (
+ <div className="mb-4 text-xs text-gray-500 space-y-1">
+ <p className="uppercase tracking-wide">What the sources behind this list can and cannot see</p>
+ {data.observedSources.map((s) => (
+ <p key={s}>
+ <span className="text-gray-400">{s}</span>
+ {": "}
+ {SOURCE_LIMITS[s] ?? "Unrecognised discovery source."}
+ </p>
+ ))}
+ </div>
+ ) : null}
+
+ <div className="bg-gray-900/60 border border-gray-700 rounded-lg overflow-hidden">
+ {isLoading ? (
+ <div className="p-8 text-center text-sm text-gray-500">Loading the AI estate…</div>
+ ) : error ? (
+ <div className="p-8 text-center text-sm text-red-400">
+ Could not load the AI estate. This is not a report that none exists.
+ </div>
+ ) : !data?.items?.length ? (
+ <div className="p-8 text-center text-sm text-gray-500">
+ No AI assets observed yet. AiSOC builds this list from AI runtime telemetry, endpoint process
+ activity and provider audit logs — if none of those is connected, this stays empty whatever is
+ running.
+ </div>
+ ) : (
+ <table className="w-full text-sm">
+ <thead className="bg-gray-800 border-b border-gray-700">
+ <tr>
+ <th className="px-4 py-3 text-left font-medium text-gray-400">Asset</th>
+ <th className="px-4 py-3 text-left font-medium text-gray-400">Kind</th>
+ <th className="px-4 py-3 text-left font-medium text-gray-400">Person</th>
+ <th className="px-4 py-3 text-left font-medium text-gray-400">Device</th>
+ <th className="px-4 py-3 text-left font-medium text-gray-400">First seen</th>
+ <th className="px-4 py-3 text-left font-medium text-gray-400">Last seen</th>
+ <th className="px-4 py-3 text-left font-medium text-gray-400">Risk</th>
+ <th className="px-4 py-3 text-left font-medium text-gray-400">Status</th>
+ </tr>
+ </thead>
+ <tbody className="divide-y divide-gray-800">
+ {data.items.map((asset) => (
+ <>
+ <tr
+ key={asset.id}
+ className="hover:bg-gray-800/50 cursor-pointer"
+ onClick={() => setExpanded(expanded === asset.id ? null : asset.id)}
+ >
+ <td className="px-4 py-3 text-gray-100 max-w-xs truncate">
+ {asset.displayName ?? asset.externalId}
+ {asset.vendor ? <span className="text-gray-500"> · {asset.vendor}</span> : null}
+ </td>
+ <td className="px-4 py-3 text-gray-400">{asset.kind.replace(/_/g, " ")}</td>
+ <td className="px-4 py-3">
+ <Link
+ value={asset.principal}
+ missing={`No source linked a person. ${SOURCE_LIMITS[asset.discoverySource] ?? ""}`}
+ />
+ </td>
+ <td className="px-4 py-3">
+ <Link
+ value={asset.device}
+ missing={`No source linked a device. ${SOURCE_LIMITS[asset.discoverySource] ?? ""}`}
+ />
+ </td>
+ <td className="px-4 py-3 text-gray-500" suppressHydrationWarning>
+ {new Date(asset.firstSeen).toLocaleString()}
+ </td>
+ <td className="px-4 py-3 text-gray-500" suppressHydrationWarning>
+ {new Date(asset.lastSeen).toLocaleString()}
+ </td>
+ <td className={`px-4 py-3 font-semibold ${riskTone(asset.risk)}`}>{asset.risk}</td>
+ <td className="px-4 py-3">
+ <SanctionBadge sanctioned={asset.sanctioned} />
+ </td>
+ </tr>
+ {expanded === asset.id && (
+ <tr key={`${asset.id}-detail`} className="bg-gray-900">
+ <td colSpan={8} className="px-6 py-4">
+ <p className="text-xs uppercase tracking-wide text-gray-500 mb-2">
+ Why it scores {asset.risk}
+ </p>
+ {asset.riskReasons.length ? (
+ <ul className="list-disc pl-5 space-y-1 text-sm text-gray-300">
+ {asset.riskReasons.map((reason) => (
+ <li key={reason}>{reason}</li>
+ ))}
+ </ul>
+ ) : (
+ <p className="text-sm text-gray-500">Nothing about this asset raised its score.</p>
+ )}
+ <p className="text-xs text-gray-500 mt-3">
+ Seen {asset.observationCount} times via {asset.discoverySource}.
+ {asset.effectivePermissions
+ ? " Effective permissions were resolved at the last sighting."
+ : " No permission snapshot was available, so permissions did not contribute to the score."}
+ </p>
+ <div className="flex gap-3 mt-4">
+ <button
+ onClick={() => void sanction(asset.id, true)}
+ className="px-3 py-1.5 text-xs bg-green-700 text-white rounded hover:bg-green-600"
+ >
+ Approve
+ </button>
+ <button
+ onClick={() => void sanction(asset.id, false)}
+ className="px-3 py-1.5 text-xs bg-red-700 text-white rounded hover:bg-red-600"
+ >
+ Refuse
+ </button>
+ <button
+ onClick={() => void sanction(asset.id, null)}
+ className="px-3 py-1.5 text-xs bg-gray-700 text-gray-200 rounded hover:bg-gray-600"
+ >
+ Back to undecided
+ </button>
+ </div>
+ </td>
+ </tr>
+ )}
+ </>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/layout/Sidebar.tsx b/apps/web/src/components/layout/Sidebar.tsx
index 6994c1458..2ce213aff 100644
--- a/apps/web/src/components/layout/Sidebar.tsx
+++ b/apps/web/src/components/layout/Sidebar.tsx
@@ -293,6 +293,11 @@ const navSections: NavSection[] = [
href: '/honeytokens',
icon: <EyeIcon />,
},
+ {
+ label: 'AI Estate',
+ href: '/ai-estate',
+ icon: <EyeIcon />,
+ },
{
label: 'Purple Team',
href: '/purple-team',
diff --git a/apps/web/src/components/layout/TopBar.tsx b/apps/web/src/components/layout/TopBar.tsx
index f13150729..0f49748ed 100644
--- a/apps/web/src/components/layout/TopBar.tsx
+++ b/apps/web/src/components/layout/TopBar.tsx
@@ -28,6 +28,7 @@ const routeLabels: Record<string, { title: string; description: string }> = {
'/playbooks': { title: 'Playbooks', description: 'Automated response and SOAR workflows' },
'/marketplace': { title: 'Marketplace', description: 'Plugins, integrations, and content packs' },
'/honeytokens': { title: 'Honeytokens', description: 'Deception assets and trip-wire alerts' },
+ '/ai-estate': { title: 'AI Estate', description: 'Observed AI apps, agents, MCP servers, keys and grants' },
'/purple-team': { title: 'Purple Team', description: 'Adversary emulation and detection coverage' },
'/connectors': { title: 'Connectors', description: 'Security tool integrations' },
'/compliance': { title: 'Compliance', description: 'Frameworks, controls, and evidence' },
diff --git a/scripts/check_ai_asset_inventory.py b/scripts/check_ai_asset_inventory.py
index 4661a075e..fa7e4ea8f 100644
--- a/scripts/check_ai_asset_inventory.py
+++ b/scripts/check_ai_asset_inventory.py
@@ -278,7 +278,7 @@ def _check_writer(root: Path) -> list[str]:
failures.append(f"WRITER: {RECORDER_PATH} never names {TABLE}, so whatever it writes, it is not the inventory.")
consumer = _read(root, CONSUMER_PATH)
- if not _calls_within(consumer, "_process_message", ("_ai_assets",)):
+ if not _calls_within(consumer, "_process_message", ("_ai_assets.observe",)):
failures.append(
f"WRITER: {CONSUMER_PATH}::_process_message does not reach the recorder. Module reachability cannot "
f"see this: the module imports, the tests pass, and no event ever reaches it."
@@ -305,6 +305,20 @@ def _check_kinds(root: Path) -> list[str]:
return []
+def _all_node_labels(go_text: str) -> set[str]:
+ """Members of the ``AllNodeLabels`` literal, comments excluded."""
+ match = re.search(r"AllNodeLabels\s*=\s*\[\]NodeLabel\{(.*?)\n\}", go_text, re.DOTALL)
+ if not match:
+ return set()
+ members: set[str] = set()
+ for line in match.group(1).splitlines():
+ stripped = line.strip()
+ if not stripped or stripped.startswith("//"):
+ continue
+ members.add(stripped.rstrip(","))
+ return members
+
+
def _check_graph(root: Path) -> list[str]:
"""The label is declared on both sides and something emits it."""
failures: list[str] = []
@@ -315,10 +329,12 @@ def _check_graph(root: Path) -> list[str]:
failures.append(f"GRAPH: {GRAPH_YAML} does not declare node label {GRAPH_LABEL}.")
if f'NodeAIAsset NodeLabel = "{GRAPH_LABEL}"' not in go_text.replace("\t", " ").replace(" ", " "):
failures.append(f"GRAPH: {GRAPH_GO} does not declare NodeAIAsset = {GRAPH_LABEL!r}.")
- # Declared and never enumerated is the drift the schema gate was blind to
- # for 11 labels: the YAML listed them, the Go constant existed, and
- # AllNodeLabels — the list every consumer reads — did not.
- if "NodeAIAsset," not in go_text:
+ # Declared and never enumerated is the drift a schema gate is blind to:
+ # the YAML lists the label, the Go constant exists, and AllNodeLabels —
+ # the list every consumer reads — does not. Parsed out of the literal
+ # rather than substring-matched, because `// NodeAIAsset,` contains the
+ # substring and means the opposite.
+ if "NodeAIAsset" not in _all_node_labels(go_text):
failures.append(f"GRAPH: NodeAIAsset is not in AllNodeLabels in {GRAPH_GO}, so no consumer enumerates it.")
if "NodeAIAsset" not in extractor:
failures.append(
@@ -328,6 +344,18 @@ def _check_graph(root: Path) -> list[str]:
return failures
+def _strip_ts_comments(source: str) -> str:
+ """Drop `//` and `/* */` so the gate does not read its own prose.
+
+ `check_gate_coverage.py` counted a gate named only in a docstring as
+ invoked, and reported "all reachable" while the gate ran in no workflow.
+ The same mistake here would be a component documenting that it does not
+ fabricate, failing for saying so.
+ """
+ without_block = re.sub(r"/\*.*?\*/", "", source, flags=re.DOTALL)
+ return re.sub(r"^\s*//.*$", "", without_block, flags=re.MULTILINE)
+
+
def _check_console(root: Path) -> list[str]:
source = _read(root, CONSOLE_PAGE)
if not source:
@@ -336,7 +364,8 @@ def _check_console(root: Path) -> list[str]:
for needle, label in (("firstSeen", "first seen"), ("lastSeen", "last seen"), ("risk", "risk")):
if needle not in source:
failures.append(f"CONSOLE: {CONSOLE_PAGE} does not render {label}, which the plan names as a required column.")
- if re.search(r"\?\?\s*(MOCK|SAMPLE|DEMO_[A-Z_]*ASSET)", source) or "fallbackData" in source:
+ code = _strip_ts_comments(source)
+ if re.search(r"\?\?\s*(MOCK|SAMPLE|DEMO_[A-Z_]*ASSET)", code) or "fallbackData" in code:
failures.append(
f"CONSOLE: {CONSOLE_PAGE} falls back to fabricated rows. An invented AI inventory is worse than an "
f"empty one: it is a security surface a reader would act on."
@@ -375,10 +404,14 @@ INJECTIONS: tuple[tuple[str, Path, str, str], ...] = (
("MODEL", MODEL_PATH, f'__tablename__ = "{TABLE}"', '__tablename__ = "aisoc_ai_assets_v2"'),
("ROUTES", ROUTES_PATH, "Depends(require_permission", "Annotated_discarded(require_permission"),
("PERMISSIONS", SECURITY_PATH, '"ai_estate:read"', '"ai_estate:read_TYPO"'),
- ("WRITER", CONSUMER_PATH, "self._ai_assets", "self._unwired_ai_assets"),
+ ("WRITER", CONSUMER_PATH, "await self._ai_assets.observe(payload)", "await _noop(payload)"),
("KINDS", RECORDER_PATH, '"coding_agent"', '"coding_agent_TYPO"'),
- ("GRAPH", GRAPH_GO, "NodeAIAsset,", "// NodeAIAsset,"),
- ("CONSOLE", CONSOLE_PAGE, "firstSeen", "firstSeenXX"),
+ # Commenting the member out, not deleting it — the shape a reviewer waves
+ # through, and the one a substring match cannot see.
+ ("GRAPH", GRAPH_GO, "\tNodeAIAsset,", "\t// NodeAIAsset,"),
+ # Renamed rather than suffixed: `firstSeenXX` still contains `firstSeen`,
+ # so a suffix injection would be caught by a gate that does nothing.
+ ("CONSOLE", CONSOLE_PAGE, "firstSeen", "createdOn"),
)
@@ -396,12 +429,18 @@ def _materialise(dest: Path) -> None:
shutil.copy2(sql, dest / MIGRATIONS_DIR / sql.name)
-def _apply(root: Path, target: Path, old: str, new: str) -> bool:
+#: Injections where renaming one occurrence proves nothing: four roles hold
+#: the permission, and `firstSeen` appears in both the wire type and the cell
+#: that renders it, so renaming the declaration alone leaves the column there.
+_REPLACE_ALL = {"PERMISSIONS", "CONSOLE"}
+
+
+def _apply(root: Path, target: Path, old: str, new: str, *, replace_all: bool = False) -> bool:
if target == MIGRATIONS_DIR:
for sql in (root / MIGRATIONS_DIR).glob("*.sql"):
text = sql.read_text(encoding="utf-8")
if old in text:
- sql.write_text(text.replace(old, new, 1), encoding="utf-8")
+ sql.write_text(text.replace(old, new, -1 if replace_all else 1), encoding="utf-8")
return True
return False
path = root / target
@@ -410,7 +449,7 @@ def _apply(root: Path, target: Path, old: str, new: str) -> bool:
text = path.read_text(encoding="utf-8")
if old not in text:
return False
- path.write_text(text.replace(old, new, 1), encoding="utf-8")
+ path.write_text(text.replace(old, new, -1 if replace_all else 1), encoding="utf-8")
return True
@@ -433,7 +472,7 @@ def _self_test() -> int:
tmp = Path(tempfile.mkdtemp(prefix="ai-inv-"))
try:
_materialise(tmp)
- applied = _apply(tmp, target, old, new)
+ applied = _apply(tmp, target, old, new, replace_all=rule_name in _REPLACE_ALL)
if not applied:
results.append((f"{rule_name}: injection applies", False))
continue